您好,登录后才能下订单哦!
密码登录
登录注册
点击 登录注册 即表示同意《亿速云用户服务条款》
# Python中ROC曲线怎么绘制
## 什么是ROC曲线
ROC曲线(Receiver Operating Characteristic Curve)是评估二分类模型性能的重要工具,通过绘制真正例率(TPR)与假正例率(FPR)的关系曲线,直观展示模型在不同阈值下的表现。
### 核心概念
- **真正例率(TPR/Recall)**:`TP / (TP + FN)`
- **假正例率(FPR)**:`FP / (FP + TN)`
- **AUC值**:曲线下面积,范围0.5-1,值越大模型越好
## 绘制ROC曲线的完整步骤
### 1. 准备数据与模型
```python
from sklearn.datasets import make_classification
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LogisticRegression
# 生成模拟数据
X, y = make_classification(n_samples=1000, n_classes=2, random_state=42)
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3)
# 训练模型
model = LogisticRegression()
model.fit(X_train, y_train)
# 获取正类的预测概率
y_scores = model.predict_proba(X_test)[:, 1]
from sklearn.metrics import roc_curve
fpr, tpr, thresholds = roc_curve(y_test, y_scores)
import matplotlib.pyplot as plt
plt.figure(figsize=(8, 6))
plt.plot(fpr, tpr, label='ROC curve')
plt.plot([0, 1], [0, 1], 'k--', label='Random guess')
plt.xlabel('False Positive Rate')
plt.ylabel('True Positive Rate')
plt.title('ROC Curve')
plt.legend()
plt.show()
from sklearn.metrics import auc
roc_auc = auc(fpr, tpr)
plt.plot(fpr, tpr, label=f'AUC = {roc_auc:.3f}')
from sklearn.ensemble import RandomForestClassifier
# 训练第二个模型
rf_model = RandomForestClassifier()
rf_model.fit(X_train, y_train)
y_scores_rf = rf_model.predict_proba(X_test)[:, 1]
# 计算两个模型的ROC曲线
fpr_lr, tpr_lr, _ = roc_curve(y_test, y_scores)
fpr_rf, tpr_rf, _ = roc_curve(y_test, y_scores_rf)
# 绘制对比图
plt.plot(fpr_lr, tpr_lr, label='Logistic Regression')
plt.plot(fpr_rf, tpr_rf, label='Random Forest')
# 标记特定阈值点
optimal_idx = np.argmax(tpr - fpr)
optimal_threshold = thresholds[optimal_idx]
plt.scatter(fpr[optimal_idx], tpr[optimal_idx], marker='o', color='red',
label=f'Optimal Threshold (={optimal_threshold:.2f})')
原因:样本量不足或阈值点过少
解决:
# 增加thresholds参数
fpr, tpr, thresholds = roc_curve(y_test, y_scores, drop_intermediate=False)
解决方案:
from sklearn.preprocessing import label_binarize
from sklearn.metrics import roc_auc_score
# 二值化标签
y_test_bin = label_binarize(y_test, classes=[0,1,2])
n_classes = y_test_bin.shape[1]
# 计算每个类别的ROC曲线
for i in range(n_classes):
fpr, tpr, _ = roc_curve(y_test_bin[:, i], y_scores[:, i])
plt.plot(fpr, tpr, label=f'Class {i}')
# 完整ROC曲线绘制示例
import numpy as np
import matplotlib.pyplot as plt
from sklearn.datasets import make_classification
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import roc_curve, auc
# 数据准备
X, y = make_classification(n_samples=1000, n_classes=2, random_state=42)
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3)
# 模型训练
model = LogisticRegression()
model.fit(X_train, y_train)
y_scores = model.predict_proba(X_test)[:, 1]
# 计算ROC
fpr, tpr, thresholds = roc_curve(y_test, y_scores)
roc_auc = auc(fpr, tpr)
# 绘图
plt.figure(figsize=(10, 8))
plt.plot(fpr, tpr, color='darkorange', lw=2,
label=f'ROC curve (AUC = {roc_auc:.2f})')
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")
# 标记最佳阈值
optimal_idx = np.argmax(tpr - fpr)
plt.scatter(fpr[optimal_idx], tpr[optimal_idx], marker='o', color='red')
plt.annotate(f'Threshold: {thresholds[optimal_idx]:.2f}',
xy=(fpr[optimal_idx], tpr[optimal_idx]),
xytext=(20, -20),
textcoords='offset points',
ha='right', va='bottom',
bbox=dict(boxstyle='round,pad=0.5', fc='yellow', alpha=0.5),
arrowprops=dict(arrowstyle='->'))
plt.show()
sklearn.metrics.roc_curve
计算关键坐标点通过掌握这些技巧,您可以有效评估和比较不同分类模型的性能表现。 “`
该文章包含约1500字,采用Markdown格式编写,包含: - 核心概念解释 - 分步骤实现指南 - 代码示例(含完整可运行示例) - 常见问题解决方案 - 可视化效果优化技巧 - 多模型对比方法 - 阈值选择策略 - 完整代码块和注释
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。