Reputation: 129
I am trying to plot the ROC curve for a multi label classification problem. My target column before giving it labels looked like:
TargetGrouped
I5
I2
R0
I3
This is part of the code used to plot the 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)
When I run it, I get the following error:
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
I know it might be an issue with the format of the class in the plt.plot()
but I don't know how to fix it.
Update
This is the code missing from the 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])
Upvotes: 0
Views: 1079
Reputation: 1653
The issue is actually with the following line:
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]))
fpr
and tpr
are dictionaries and the only key you initialized is 'micro'
. This for loop assigns integer values between 0
and n_classes-1
to i
, but you have never defined what fpr[0]
and tpr[0]
are (and I suspect you are thinking of them as lists, but this is just speculation).
Upvotes: 1