溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

Python中ROC曲線怎么繪制

發布時間:2021-12-09 15:09:15 來源:億速云 閱讀:711 作者:iii 欄目:開發技術
# 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)

2. 計算預測概率

# 獲取正類的預測概率
y_scores = model.predict_proba(X_test)[:, 1]

3. 計算ROC曲線坐標

from sklearn.metrics import roc_curve

fpr, tpr, thresholds = roc_curve(y_test, y_scores)

4. 繪制基礎ROC曲線

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()

5. 添加AUC值

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})')

常見問題解決方案

問題1:曲線鋸齒狀不平滑

原因:樣本量不足或閾值點過少
解決

# 增加thresholds參數
fpr, tpr, thresholds = roc_curve(y_test, y_scores, drop_intermediate=False)

問題2:多類別分類

解決方案

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()

總結

  1. ROC曲線通過TPR-FPR關系直觀展示模型性能
  2. 使用sklearn.metrics.roc_curve計算關鍵坐標點
  3. AUC值越大表示模型區分能力越強
  4. 多模型對比時,曲線越靠近左上角性能越好
  5. 實際應用中需結合業務需求選擇合適閾值

通過掌握這些技巧,您可以有效評估和比較不同分類模型的性能表現。 “`

該文章包含約1500字,采用Markdown格式編寫,包含: - 核心概念解釋 - 分步驟實現指南 - 代碼示例(含完整可運行示例) - 常見問題解決方案 - 可視化效果優化技巧 - 多模型對比方法 - 閾值選擇策略 - 完整代碼塊和注釋

向AI問一下細節

免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。

AI

亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女