求多分类问题ROC曲线的代码
时间: 2023-06-17 21:03:22 浏览: 86
以下是一个简单的多分类问题ROC曲线绘制的Python代码示例:
```python
import numpy as np
import matplotlib.pyplot as plt
from sklearn.metrics import roc_curve, auc
from itertools import cycle
# 生成样本数据
n_classes = 4
n_samples = 1000
y = np.random.randint(0, n_classes, size=n_samples)
scores = np.random.rand(n_samples, n_classes)
# 计算ROC曲线和AUC值
fpr = dict()
tpr = dict()
roc_auc = dict()
for i in range(n_classes):
fpr[i], tpr[i], _ = roc_curve((y == i).astype(int), scores[:, i])
roc_auc[i] = auc(fpr[i], tpr[i])
# 绘制ROC曲线
plt.figure()
colors = cycle(['blue', 'green', 'red', 'cyan'])
for i, color in zip(range(n_classes), colors):
plt.plot(fpr[i], tpr[i], color=color, lw=2,
label='ROC curve of class {0} (area = {1:0.2f})'
''.format(i, roc_auc[i]))
plt.plot([0, 1], [0, 1], 'k--', lw=2)
plt.xlim([0.0, 1.0])
plt.ylim([0.0, 1.05])
plt.xlabel('False Positive Rate')
plt.ylabel('True Positive Rate')
plt.title('ROC Curve for Multi-class Classification')
plt.legend(loc="lower right")
plt.show()
```
这段代码使用了sklearn库中的`roc_curve`和`auc`函数计算每个类别的ROC曲线和AUC值,并使用matplotlib库绘制了多分类问题的ROC曲线。