python已有y_test为测试集,y_train为训练集,如何绘制ROC图
时间: 2024-05-14 19:15:37 浏览: 10
绘制 ROC 曲线需要先计算出真正率(True Positive Rate,TPR)和假正率(False Positive Rate,FPR),其中:
- TPR = TP / (TP + FN),表示实际为正例中被正确预测为正例的比率。
- FPR = FP / (FP + TN),表示实际为负例中被错误预测为正例的比率。
其中,TP表示真正例(True Positive),即实际为正例且被预测为正例的样本数;FN表示假负例(False Negative),即实际为正例但被预测为负例的样本数;FP表示假正例(False Positive),即实际为负例但被预测为正例的样本数;TN表示真负例(True Negative),即实际为负例且被预测为负例的样本数。
下面是一个使用 scikit-learn 库绘制 ROC 曲线的示例代码,假设 y_test 和 y_pred 为测试集标签和模型预测标签:
```
from sklearn.metrics import roc_curve, auc
# 计算 FPR 和 TPR
fpr, tpr, thresholds = roc_curve(y_test, y_pred)
roc_auc = auc(fpr, tpr)
# 绘制 ROC 曲线
plt.plot(fpr, tpr, color='darkorange', lw=2, label='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')
plt.legend(loc="lower right")
plt.show()
```
其中,roc_curve() 函数用于计算 FPR 和 TPR,auc() 函数用于计算 ROC 曲线下的面积(AUC)。最后使用 matplotlib 库绘制 ROC 曲线。
相关推荐
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)