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

时间:2019-08-14 18:02:18

标签: python scikit-learn deep-learning pytorch roc

我正在尝试绘制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

我不明白如何解决此问题。 非常感谢您提供有关此问题的任何帮助。

1 个答案:

答案 0 :(得分:0)

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