使用micro-average方法绘制ROC曲线 demo
时间: 2023-08-14 09:05:02 浏览: 58
这里给出一个使用micro-average方法绘制ROC曲线的demo,使用Python的sklearn库来实现:
```python
from sklearn.metrics import roc_curve, auc
import matplotlib.pyplot as plt
import numpy as np
# 假设有3个类别,每个类别有4个样本,预测结果为类别1的概率、类别2的概率、类别3的概率
y_score = np.array([[0.9, 0.1, 0.0], [0.3, 0.6, 0.1], [0.8, 0.2, 0.0], [0.2, 0.5, 0.3],
[0.1, 0.8, 0.1], [0.2, 0.3, 0.5], [0.4, 0.5, 0.1], [0.1, 0.6, 0.3],
[0.6, 0.2, 0.2], [0.3, 0.4, 0.3], [0.1, 0.7, 0.2], [0.2, 0.3, 0.5]])
# 标签为0/1/2,对应三个类别
y_true = np.array([0, 1, 0, 1, 2, 2, 1, 0, 2, 1, 0, 2])
# 将标签转化为one-hot编码
y_true_onehot = np.zeros((y_true.shape[0], 3))
for i in range(y_true.shape[0]):
y_true_onehot[i][y_true[i]] = 1
# 计算总体的TPR和FPR
fpr, tpr, _ = roc_curve(y_true_onehot.ravel(), y_score.ravel())
roc_auc = auc(fpr, tpr)
# 绘制ROC曲线
plt.figure()
plt.plot(fpr, tpr, color='darkorange', lw=2, label='micro-average 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 example')
plt.legend(loc="lower right")
plt.show()
```
运行以上代码,即可绘制出使用micro-average方法绘制的ROC曲线。