y_score[[[0.10579571 0.89420429] [0.55098666 0.44901334] [0.36715617 0.63284383] ... [0.80762724 0.19237276] [0.6495282 0.3504718 ] [0.64156421 0.35843579]] [[0.9323137 0.0676863 ] [0.5349633 0.4650367 ] [0.75478328 0.24521672] ... [0.27653182 0.72346818] [0.4277243 0.5722757 ] [0.44331892 0.55668108]] [[0.96189059 0.03810941] [0.91405004 0.08594996] [0.87806054 0.12193946] ... [0.91584095 0.08415905] [0.9227475 0.0772525 ] [0.91511687 0.08488313]]]怎么和三分类的y_test对应起来画三个类别的aoc曲线
时间: 2023-06-28 10:08:46 浏览: 34
假设你的y_test是一个形状为 (n_samples, ) 的一维数组,其中每个元素是一个 0、1 或 2,对应三个类别中的一个。
你可以使用 `sklearn.metrics.roc_curve` 函数计算每个类别的 FPR 和 TPR,然后将其绘制在同一个图中。
代码示例:
```python
import numpy as np
from sklearn.metrics import roc_curve, auc
import matplotlib.pyplot as plt
# 将 y_test 转换为 one-hot 编码
n_classes = 3
y_test_one_hot = np.eye(n_classes)[y_test]
# 计算每个类别的 FPR 和 TPR
fpr = dict()
tpr = dict()
roc_auc = dict()
for i in range(n_classes):
fpr[i], tpr[i], _ = roc_curve(y_test_one_hot[:, i], y_score[:, i, 1])
roc_auc[i] = auc(fpr[i], tpr[i])
# 绘制 ROC 曲线
plt.figure()
lw = 2
colors = ['red', 'blue', 'green']
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], color='gray', lw=lw, 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()
```
在上面的代码中,`y_score` 是模型的预测结果,它是一个形状为 (n_samples, n_classes, 2) 的三维数组。其中,最后一维的第一个元素是负类的预测概率,第二个元素是正类的预测概率。
`y_test` 是真实标签,它是一个形状为 (n_samples, ) 的一维数组,其中每个元素是一个 0、1 或 2,对应三个类别中的一个。我们将其转换为 one-hot 编码,以便计算 FPR 和 TPR。
对于每个类别,我们使用 `sklearn.metrics.roc_curve` 函数计算其 FPR 和 TPR,并使用 `sklearn.metrics.auc` 函数计算其 AUC 值。
最后,我们将三个类别的 ROC 曲线绘制在同一个图中,并展示出每个类别的 AUC 值。