今天介绍一种画多条ROC曲线的方法
将每条的曲线概率和标签添加到里面就可以了
import matplotlib.pyplot as plt
from sklearn.metrics import roc_curve, auc
import numpy as np
# 生成七组概率和标签数据
probabilities = [
[0.2, 0.4, 0.6, 0.7, 0.75, 0.8, 0.85, 0.9, 0.95, 0.99],
[0.1, 0.3, 0.5, 0.65, 0.7, 0.78, 0.82, 0.88, 0.92, 0.98],
[0.3, 0.45, 0.55, 0.63, 0.68, 0.74, 0.79, 0.83, 0.91, 0.97],
[0.25, 0.42, 0.58, 0.67, 0.72, 0.77, 0.81, 0.86, 0.93, 0.96],
[0.15, 0.35, 0.52, 0.69, 0.73, 0.79, 0.84, 0.89, 0.94, 0.98],
[0.22, 0.38, 0.53, 0.68, 0.76, 0.81, 0.85, 0.9, 0.96, 0.99],
[0.18, 0.32, 0.48, 0.66, 0.71, 0.78, 0.82, 0.87, 0.92, 0.97]
]
labels = [
[0, 0, 1, 1, 1, 0, 1, 0, 1, 0],
[1, 0, 1, 0, 1, 0, 1, 0, 1, 0],
[0, 1, 1, 0, 1, 0, 1, 0, 1, 0],
[1, 1, 0, 1, 0, 0, 1, 1, 1, 0],
[0, 1, 1, 1, 0, 0, 1, 0, 1, 0],
[1, 0, 1, 0, 1, 0, 1, 0, 1, 0],
[0, 1, 0, 1, 1, 0, 1, 0, 1, 0]
]
# 绘制AUC曲线
plt.figure(figsize=(8, 8))
for i in range(len(labels)):
fpr, tpr, _ = roc_curve(labels[i], probabilities[i])
roc_auc = auc(fpr, tpr)
plt.plot(fpr, tpr, lw=2, label='ROC curve %d (AUC = %0.2f)' % (i+1, 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 (ROC)')
plt.legend(loc='lower right')
plt.show()
当然也可以修改一下自己的图例,把每条曲线的名字添加到labels_name中就可以了,其他的大同小异了。
import matplotlib.pyplot as plt
from sklearn.metrics import roc_curve, auc
import numpy as np
# 生成七组概率和标签数据
P1 = [0.2, 0.4, 0.6, 0.7, 0.75, 0.8, 0.85, 0.9, 0.95, 0.99]
P2 =[0.1, 0.3, 0.5, 0.65, 0.7, 0.78, 0.82, 0.88, 0.92, 0.98]
P3 =[0.3, 0.45, 0.55, 0.63, 0.68, 0.74, 0.79, 0.83, 0.91, 0.97]
P4 =[0.25, 0.42, 0.58, 0.67, 0.72, 0.77, 0.81, 0.86, 0.93, 0.96]
P5 =[0.15, 0.35, 0.52, 0.69, 0.73, 0.79, 0.84, 0.89, 0.94, 0.98]
P6 =[0.22, 0.38, 0.53, 0.68, 0.76, 0.81, 0.85, 0.9, 0.96, 0.99]
P7 =[0.18, 0.32, 0.48, 0.66, 0.71, 0.78, 0.82, 0.87, 0.92, 0.97]
probabilities = [P1,P2,P3,P4,P5,P6,P7]
L1 = [0, 0, 1, 1, 1, 0, 1, 0, 1, 0]
L2 =[1, 0, 1, 0, 1, 0, 1, 0, 1, 0]
L3 =[0, 1, 1, 0, 1, 0, 1, 0, 1, 0]
L4 =[1, 1, 0, 1, 0, 0, 1, 1, 1, 0]
L5 =[0, 1, 1, 1, 0, 0, 1, 0, 1, 0]
L6 =[1, 0, 1, 0, 1, 0, 1, 0, 1, 0]
L7 =[0, 1, 0, 1, 1, 0, 1, 0, 1, 0]
labels = [L1,L2,L3,L4,L5,L6,L7]
labels_name =['L1','L2','L3','L4','L5','L6','L7']
# 绘制AUC曲线
plt.figure(figsize=(8, 8))
for i in range(len(labels)):
fpr, tpr, _ = roc_curve(labels[i], probabilities[i])
roc_auc = auc(fpr, tpr)
plt.plot(fpr, tpr, lw=2, label=f'{labels_name[i]} (AUC = {roc_auc:.2f})')
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 (ROC)')
plt.legend(loc='lower right')
plt.show()
这样多条ROC曲线的绘制就OK了。