绘制ROC曲线时出现KeyError

时间:2019-07-18 09:11:07

标签: python roc

我正在尝试绘制ROC曲线以解决多标签分类问题。 在给它加上标签之前,我的目标列看起来像:

TargetGrouped
I5
I2
R0
I3

这是用于绘制ROC的代码的一部分:

    def computeROC(self, n_classes, y_test, y_score):
        # Compute ROC curve and ROC area for each class
        fpr = dict()
        tpr = dict()
        roc_auc = dict()

        # 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"])

        # Plot ROC curve
        plt.figure()
        plt.plot(fpr["micro"], tpr["micro"],
                 label='micro-average ROC curve (area = {0:0.2f})'
                       ''.format(roc_auc["micro"]))
        for i in range(n_classes):
            plt.plot(fpr[i], tpr[i], label='ROC curve of class {0} (area = {1:0.2f})'
                                           ''.format(i, roc_auc[i]))

        plt.plot([0, 1], [0, 1], 'k--')
        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()

    lb = preprocessing.LabelBinarizer()
    infoDF = infoDF.join(pd.DataFrame(lb.fit_transform(infoDF["TargetGrouped"]), columns = lb.classes_, index = infoDF.index))

#Extracted features and split infoDF dataframe => got X_train, X_test, y_train, y_test

    rfc = RandomForestClassifier()
    rfc.fit(X_train, y_train)
    y_pred = rfc.predict(X_test)

    classes = y_train.shape[1]
    computeROC(classes, y_test, y_pred)

运行它时,出现以下错误:

Traceback (most recent call last):

  File "<ipython-input-50-15a83ece5e44>", line 3, in <module>
    evaluation.computeROC(classes, y_test, y_pred)

  File "<ipython-input-49-526a19a07850>", line 18, in computeROC
    plt.plot(fpr[i], tpr[i], label='ROC curve of class {0} (area = {1:0.2f})'

KeyError: 0

我知道plt.plot()中类的格式可能有问题,但我不知道如何解决。

更新

这是computeROC()中缺少的代码:

        for i in range(n_classes):
            fpr[i], tpr[i], _ = roc_curve(y_test[:, i], y_score[:, i])
            roc_auc[i] = auc(fpr[i], tpr[i])

1 个答案:

答案 0 :(得分:1)

问题实际上出在以下几行:

for i in range(n_classes):
            plt.plot(fpr[i], tpr[i], label='ROC curve of class {0} (area = {1:0.2f})'
                                           ''.format(i, roc_auc[i]))

fprtpr是词典,并且初始化的唯一键是'micro'。此for循环将0n_classes-1之间的整数值分配给i,但是您从未定义fpr[0]tpr[0]是什么(我怀疑您在想其中的一个作为列表,但这只是猜测)。