# ROC 曲线
## 准备数据
import numpy as np
from sklearn import metrics
pred = np.concatenate((np.random.normal(5, 2, 30), np.random.normal(7, 2, 30)))
y = np.concatenate((np.full(30, 0), np.full(30, 1)))
## 绘制ROC曲线
from sklearn.metrics import roc_curve
from sklearn.metrics import RocCurveDisplay
fpr, tpr, thresholds = metrics.roc_curve(y, pred, pos_label=1)
roc_display = RocCurveDisplay(fpr=fpr, tpr=tpr, roc_auc=roc_auc, estimator_name='example estimator').plot(color="darkorange")
roc_display.roc_auc
# 0.8366666666666667
- 自定义图元素
import matplotlib.pyplot as plt
RocCurveDisplay.from_predictions(
y_true = y,
y_pred = pred,
name=f"Title",
color="darkorange",
)
plt.plot([0, 1], [0, 1], "k--", label="chance level (AUC = 0.5)")
plt.axis("square")
plt.xlabel("False Positive Rate")
plt.ylabel("True Positive Rate")
plt.title("Title")
plt.legend()
plt.show()
## 计算AUC
metrics.auc(fpr, tpr)
# 0.8366666666666667
使用yardstick包进行ROC分析
使用 pROC包进行ROC分析
参考:
sklearn.metrics.auc
Multiclass Receiver Operating Characteristic ROC