尝试为多类分类绘制 ROC 时出错

Getting error while trying to plot ROC for multiclass classification

我正在尝试为多类 classification.I 绘制 ROC 曲线,然后是 https://scikit-learn.org/stable/auto_examples/model_selection/plot_roc.html。 我使用下面的代码来计算 y_test 和 y_score

def test_epoch(net,test_loader):
 y_test =[]
 y_score =[]
 with torch.no_grad():
  for batch in test_loader:
    images, labels = batch['image'], batch['grade']
    images =Variable(images)
    labels= Variable(labels)
    target =F.one_hot(labels,5)
    outputs = net(images)
    _, predicted = torch.max(outputs.data, 1)
    c = (predicted == labels).squeeze().numpy()
    y_score.append(outputs.numpy())
    y_test.append(labels.numpy())
    return y_test,y_score 

我看到我的 y_test 是如下数组

y_test data>> [array([[0, 0, 1, 0, 0],
       [1, 0, 0, 0, 0],
       [0, 1, 0, 0, 0],
       [1, 0, 0, 0, 0],
       [1, 0, 0, 0, 0],
       [0, 0, 0, 1, 0],
       [0, 0, 1, 0, 0],
       [1, 0, 0, 0, 0],
       [0, 0, 1, 0, 0],
       [0, 0, 1, 0, 0],
       [0, 1, 0, 0, 0]

而 y_score 就像

[array([[ 0.30480504, -0.12213976,  0.09632117, -0.16465648, -0.44081157],[ 0.21797988, -0.09650452,  0.07616544, -0.12001953, -0.34972644],[ 0.3230184 , -0.13098559,  0.10277118, -0.17656785, -0.45888817],[ 0.38143447, -0.15880316,  0.12123139, -0.21719441, -0.5281661 ],[ 0.3427343 , -0.13945231,  0.11076729, -0.19657779, -0.4913683 ]

每当我调用绘制 ROC 曲线的函数时

def plot_roc(y_test, y_score, N_classes):
    """
    compute ROC curve and ROC area for each class in each fold

    """

    fpr = dict()
    tpr = dict()
    roc_auc = dict()
    for i in range(N_classes):
        fpr[i], tpr[i], _ = roc_curve(np.array(y_test[:, i]),np.array(y_score[:, i]))
        roc_auc[i] = auc(fpr[i], tpr[i])
    # Compute micro-average ROC curve and ROC area
    fpr["micro"], tpr["micro"], _ = roc_curve(y_test.ravel(), y_score.ravel())
    roc_auc["micro"] = auc(fpr["micro"], tpr["micro"])

    # Compute macro-average ROC curve and ROC area

    # First aggregate all false positive rates
    all_fpr = np.unique(np.concatenate([fpr[i] for i in range(N_classes)]))

    # Then interpolate all ROC curves at this points
    mean_tpr = np.zeros_like(all_fpr)
    for i in range(N_classes):
        mean_tpr += interp(all_fpr, fpr[i], tpr[i])

    # Finally average it and compute AUC
    mean_tpr /= N_classes

    fpr["macro"] = all_fpr
    tpr["macro"] = mean_tpr
    roc_auc["macro"] = auc(fpr["macro"], tpr["macro"])

    # Plot all ROC curves
    plt.figure()
    plt.plot(fpr["micro"], tpr["micro"],
             label='micro-average ROC curve (area = {0:0.2f})'
                   ''.format(roc_auc["micro"]),
             color='deeppink', linestyle=':', linewidth=4)

    plt.plot(fpr["macro"], tpr["macro"],
             label='macro-average ROC curve (area = {0:0.2f})'
                   ''.format(roc_auc["macro"]),
             color='navy', linestyle=':', linewidth=4)

    colors = cycle(['aqua', 'darkorange', 'cornflowerblue'])
    for i, color in zip(range(N_classes), colors):
        plt.plot(fpr[i], tpr[i], color=color, lw=2,
                 label='ROC curve of class {0} (area = {1:0.2f})'
                       ''.format(i, roc_auc[i]))

    plt.plot([0, 1], [0, 1], 'k--', lw=2)
    plt.xlim([0.0, 1.0])
    plt.ylim([0.0, 1.05])
    plt.xlabel('False Positive Rate')
    plt.ylabel('True Positive Rate')
    plt.title('Some extension of Receiver operating characteristic to multi-class')
    plt.legend(loc="lower right")
    plt.show()

我收到此错误信息,

 Traceback (most recent call last):
  File "/home/Downloads/demo 3.py", line 405, in <module>
    plot_roc(y_test, y_score, 5)
  File "/home/Downloads/demo 3.py", line 225, in plot_roc
    fpr[i], tpr[i], _ = roc_curve(np.array(y_test[:, i]),np.array(y_score[:, i]))
TypeError: list indices must be integers or slices, not tuple

我不明白我将如何解决这个问题。 我非常感谢有关此问题的任何帮助。

在您的代码中,您有一个名为 roc_curve 的先前定义的变量(列表),这会影响代码中的 scikit-learn 函数 sklearn.metrics.roc_curve,您不应该将变量命名为与众所周知的功能相同,以防止出现此类问题。