簡體   English   中英

python中神經網絡循環的多次迭代

[英]Multiple iterations of neural network loop in python

我有一個正常工作的神經網絡循環,因此可以在我的隱藏層(“ nodes_list”)中使用預定數量的節點來運行神經網絡。 然后,我為每個節點數計算ROC曲線下的面積,並將其放入列表(“ roc_outcomes”)中以進行繪圖。 但是,我想在此循環中循環5次,以得到三個模型中每個模型的ROC曲線下的平均面積(模型1:隱藏層中的20個節點,模型2:隱藏層中的28個節點,模型3:38隱藏層中的節點)。 當我只在一個模型上嘗試時,這很好用,但是當我迭代多個模型而不是對模型1進行5次迭代,然后對模型2進行5次迭代,然后對模型3進行5次迭代時.... 1,然后是模型2,然后是模型3,然后執行5次。 這個嵌套循環的目的是讓我遍歷每個神經網絡模型5次,將每次迭代的ROC曲線下的面積放入列表中,計算該列表的平均值,然后將平均值放入新列表中。 最終,我希望列出三個數字(每個模型一個),這是該模型的5次迭代的ROC曲線下的平均面積。 希望我能很好地解釋這一點。 請要求任何澄清。

這是我的代碼:

nodes_list = [20, 28, 38]  # list with number of nodes in hidden layer per model
roc_outcomes = [] # list of ROC AUC

for i in np.arange(1,6):

    for nodes in nodes_list:
        # Add first layer
        model.add(Dense(units=n_cols, activation='relu', input_shape=(n_cols,)))
        # Add hidden layer
        model.add(Dense(units=nodes, activation='relu'))
        # Add output layer
        model.add(Dense(units=2, activation='softmax'))

        # Compile model
        model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy'])
        # Fit model
        model.fit(X, y, validation_split=0.33, epochs=epochs, callbacks=early_stopping_monitor, verbose=True)

        # Get predicted probabilities
        pred_prob = model.predict_proba(X)[:,1]

        # Calculate area under the curve (logit_roc_auc)
        logit_roc_auc = roc_auc_score(y[:,1], pred_prob) 
        # Append roc scores to the roc_outcomes list
        roc_outcomes.append(logit_roc_auc)

    # Get the mean of that list
    mean_roc = np.mean(roc_outcomes)
    # Append to another list
    mean_roc_outcomes = []
    mean_roc_outcomes.append(mean_roc)

像這樣構造循環:

for nodes in node_list:
    for i in range(0,5):
        #do your stuff

例:

myList = ['a', 'b', 'c']
for item in myList:
    for i in range(0,5):
        print(item, end=", ")

輸出:

a, a, a, a, a, b, b, b, b, b, c, c, c, c, c, 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM