roc curve for binary classification in python

Here's a simple code to plot ROC curve for binary classification using scikit-learn library in Python:

main.py
from sklearn.metrics import roc_curve, auc
import matplotlib.pyplot as plt

# y_score contains predicted probabilities of class 1
# y_true contains true labels (binary 0 or 1)
fpr, tpr, _ = roc_curve(y_true, y_score)
roc_auc = auc(fpr, tpr)

# Plot the ROC curve
plt.figure()
plt.plot(fpr, tpr, color='darkorange', lw=2, label='ROC curve (area = %0.2f)' % roc_auc)
plt.plot([0, 1], [0, 1], color='navy', lw=2, linestyle='--')
plt.xlim([0.0, 1.0])
plt.ylim([0.0, 1.05])
plt.xlabel('False Positive Rate')
plt.ylabel('True Positive Rate')
plt.title('Receiver operating characteristic')
plt.legend(loc="lower right")
plt.show()
624 chars
20 lines

In the above code, we first import roc_curve and auc from sklearn.metrics library. Then we predict the probabilities y_score of class 1 and true labels y_true. Then, we calculate fpr (false positive rate) and tpr (true positive rate) using roc_curve function. Finally, we plot the ROC curve using matplotlib.pyplot library.

gistlibby LogSnag