python - python中神经网络循环的多次迭代

标签 python loops for-loop neural-network

我有一个有效的神经网络循环,因此我可以使用隐藏层(“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 曲线下的面积放入一个列表中,计算该列表的平均值,并将平均值放入一个新列表中。最终,我想要一个包含三个数字的列表(每个模型 1 个),它们是该模型 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, 

关于python - python中神经网络循环的多次迭代,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51845056/

相关文章:

C++ : Trouble with a nested if loop not ending properly

python - 带有列标题的 pandas isnull 总和

python - 从给定的字符串 S 中删除多少个字符才能使它成为一个排序的字符串

python - 了解 Python 的虚拟环境

c - C 中 do-while 循环内的 fgets() 问题

javascript - 如果 for 循环返回 null javascript

java - 比较二维 boolean 数组值?

python - 解码 RFC 2231 header

python - 嵌套循环显然不在 PyOpenGL 中循环

python - 处理选定行时避免 pandas 数据框中的 for 循环