python绘制多分类的ROC曲线
时间: 2023-09-09 12:10:02 浏览: 175
ROC曲线绘制
绘制多分类的ROC曲线需要先将多分类问题转化为多个二分类问题。下面给出一个例子,代码使用Python和scikit-learn库。
假设有3个类别(0,1,2),以下是绘制多分类的ROC曲线的代码:
```python
import numpy as np
import matplotlib.pyplot as plt
from itertools import cycle
from sklearn.metrics import roc_curve, auc
from scipy import interp
# 随机生成三个类别的数据
n_classes = 3
n_samples = 1000
X = np.random.randn(n_samples, 10)
y = np.random.randint(0, n_classes, n_samples)
# 将多分类问题转化为三个二分类问题
from sklearn.preprocessing import label_binarize
y_bin = label_binarize(y, classes=[0, 1, 2])
n_classes = y_bin.shape[1]
# 计算每个类别的ROC曲线和AUC值
fpr = dict()
tpr = dict()
roc_auc = dict()
for i in range(n_classes):
fpr[i], tpr[i], _ = roc_curve(y_bin[:, i], X[:, i])
roc_auc[i] = auc(fpr[i], tpr[i])
# 计算微平均ROC曲线和AUC值
fpr["micro"], tpr["micro"], _ = roc_curve(y_bin.ravel(), X.ravel())
roc_auc["micro"] = auc(fpr["micro"], tpr["micro"])
# 计算宏平均ROC曲线和AUC值
fpr["macro"] = np.linspace(0, 1, 100)
tpr["macro"] = np.zeros_like(fpr["macro"])
for i in range(n_classes):
tpr["macro"] += interp(fpr["macro"], fpr[i], tpr[i])
tpr["macro"] /= n_classes
roc_auc["macro"] = auc(fpr["macro"], tpr["macro"])
# 绘制ROC曲线
plt.figure()
lw = 2
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=lw,
label='ROC curve of class {0} (area = {1:0.2f})'
''.format(i, roc_auc[i]))
plt.plot([0, 1], [0, 1], 'k--', lw=lw)
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 for multi-class')
plt.legend(loc="lower right")
plt.show()
```
该代码将三个类别的数据随机生成,使用label_binarize函数将多分类问题转化为三个二分类问题,然后计算每个类别的ROC曲线和AUC值。接着,计算微平均和宏平均ROC曲线和AUC值,并将它们绘制在同一张图中。最后,使用plt.show()显示图像。
阅读全文