
使用這些基本 REST API 最佳實踐構建出色的 API
在機器學習模型的性能評估中,ROC曲線和AUC(曲線下面積)是常用的工具,它們能清晰展示模型的分類能力,但是一般ROC曲線展示的AUC值不會去展示置信區間,但是帶有95%置信區間的ROC曲線在醫學研究中非常常見,因為它能夠更科學地體現模型的診斷性能以及不確定性范圍
import pandas as pd
import numpy as np
from sklearn.model_selection import train_test_split
import matplotlib.pyplot as plt
import matplotlib.ticker as ticker
plt.rcParams['font.family'] = 'Times New Roman'
plt.rcParams['axes.unicode_minus'] = False
# 讀取數據
df = pd.read_excel('2024-11-21公眾號Python機器學習AI.xlsx')
# 劃分特征和目標變量
X = df.drop(['y'], axis=1)
y = df['y']
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2,
random_state=42, stratify=df['y'])
從Excel文件中讀取二分類數據,將數據劃分為特征(X)和目標變量(y),然后按80%訓練集和20%測試集的比例進行分層抽樣拆分,為后續機器學習建模做好準備
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import roc_curve, auc, roc_auc_score
model = LogisticRegression(max_iter=1200)
model.fit(X_train, y_train)
# 預測概率
y_score = model.predict_proba(X_test)[:, 1]
# 計算 ROC 曲線
fpr_logistic, tpr_logistic, _ = roc_curve(y_test, y_score)
roc_auc_logistic = auc(fpr_logistic, tpr_logistic)
# 繪制 ROC 曲線
plt.figure(dpi=1200)
plt.plot(fpr_logistic, tpr_logistic, color='darkorange', lw=2, label='ROC curve (area = %0.2f)' % roc_auc_logistic)
plt.plot([0, 1], [0, 1], color='navy', lw=2, linestyle='--')
# 調整顯示范圍,增加邊距
plt.xlim([-0.02, 1.02]) # 左右兩側各增加一點邊距
plt.ylim([-0.02, 1.02]) # 上下各增加一點邊距
plt.xlabel('1 - Specificity')
plt.ylabel('Sensitivity')
plt.title('Receiver Operating Characteristic')
plt.legend(loc="lower right")
plt.savefig('Logistic_roc_curve.pdf', format='pdf', bbox_inches='tight')
plt.show()
使用Logistic回歸模型進行訓練和預測,通過計算假陽性率和真陽性率繪制最常見的ROC曲線,并標注AUC值(不含95%置信區間),主要用于演示基本的ROC曲線繪制方法
from math import sqrt
# 定義函數:計算 AUC 及其 95% 置信區間
def roc_auc_ci(y_true, y_score, positive=1):
AUC = roc_auc_score(y_true, y_score)
# 統計正類和負類的樣本數
N1 = sum(y_true == positive)
N2 = sum(y_true != positive)
Q1 = AUC / (2 - AUC) # Q1 是 AUC 在正類樣本上的一個調整量
Q2 = 2 * AUC**2 / (1 + AUC) # Q2 是 AUC 在負類樣本上的一個調整量
# 計算 AUC 的標準誤差
SE_AUC = sqrt((AUC * (1 - AUC) + (N1 - 1) * (Q1 - AUC**2) + (N2 - 1) * (Q2 - AUC**2)) / (N1 * N2))
# 計算 95% 置信區間的下限和上限
lower = AUC - 1.96 * SE_AUC # 下限:AUC - 1.96 * 標準誤差
upper = AUC + 1.96 * SE_AUC # 上限:AUC + 1.96 * 標準誤差
# 修正置信區間邊界,確保在 [0, 1] 范圍內
if lower < 0:
lower = 0
if upper > 1:
upper = 1
return (AUC, lower, upper)
通過計算AUC值及其標準誤差,可以推導出95%置信區間,用于評估模型區分正負樣本能力的穩定性和可靠性。當然,除了標準誤差法外,還可以采用Bootstrap方法計算置信區間,當樣本量較大且數據分布平衡時,標準誤差法因其快速高效是更優選擇;而當樣本量較小、不平衡或需要更靈活的分布假設時,Bootstrap方法因其穩健性更適用,但計算量更大, 不同計算方法可能會導致置信區間結果略有差異,應根據具體需求選擇適用方法
# 預測概率y_score = model.predict_proba(X_test)[:, 1]# 計算 ROC 曲線fpr, tpr, _ = roc_curve(y_test, y_score)
# 計算 AUC 和置信區間roc_auc, lower_ci, upper_ci = roc_auc_ci(y_test, y_score)
plt.figure(dpi=1200)plt.plot(fpr, tpr, color='darkorange', lw=2, label='ROC curve (AUC = %0.2f 95%% CI[%0.2f, %0.2f])' % (roc_auc, lower_ci, upper_ci))plt.plot([0, 1], [0, 1], color='navy', lw=2, linestyle='--')plt.xlim([-0.02, 1.02]) plt.ylim([-0.02, 1.02]) plt.xlabel('1 - Specificity')plt.ylabel('Sensitivity')plt.title('Receiver Operating Characteristic with 95% CI')plt.legend(loc="lower right")plt.savefig('Logistic_roc_with_ci.pdf', format='pdf', bbox_inches='tight')plt.show()
通過Logistic回歸模型預測結果計算ROC曲線,并繪制包含AUC值及其95%置信區間的ROC圖,以直觀展示模型分類性能及其穩定性
from sklearn.ensemble import RandomForestClassifier
from sklearn.svm import SVC
import xgboost as xgb
# 訓練和計算 Logistic Regression 的結果
model.fit(X_train, y_train)
y_score_logistic = model.predict_proba(X_test)[:, 1]
fpr_logistic, tpr_logistic, _ = roc_curve(y_test, y_score_logistic)
roc_auc_logistic, lower_logistic, upper_logistic = roc_auc_ci(y_test, y_score_logistic)
# 訓練 XGBoost
xgb_model = xgb.XGBClassifier(use_label_encoder=False, eval_metric='logloss')
xgb_model.fit(X_train, y_train)
y_score_xgb = xgb_model.predict_proba(X_test)[:, 1]
fpr_xgb, tpr_xgb, _ = roc_curve(y_test, y_score_xgb)
roc_auc_xgb, lower_xgb, upper_xgb = roc_auc_ci(y_test, y_score_xgb)
# 訓練 SVM
svm_model = SVC(probability=True)
svm_model.fit(X_train, y_train)
y_score_svm = svm_model.predict_proba(X_test)[:, 1]
fpr_svm, tpr_svm, _ = roc_curve(y_test, y_score_svm)
roc_auc_svm, lower_svm, upper_svm = roc_auc_ci(y_test, y_score_svm)
# 訓練隨機森林
rf_model = RandomForestClassifier()
rf_model.fit(X_train, y_train)
y_score_rf = rf_model.predict_proba(X_test)[:, 1]
fpr_rf, tpr_rf, _ = roc_curve(y_test, y_score_rf)
roc_auc_rf, lower_rf, upper_rf = roc_auc_ci(y_test, y_score_rf)
plt.figure(figsize=(10, 8))
# 繪制各個模型的 ROC 曲線
plt.plot(fpr_logistic, tpr_logistic, color='darkorange', lw=2,
label='Logistic (AUC = %0.2f 95%% CI[%0.2f, %0.2f])' % (roc_auc_logistic, lower_logistic, upper_logistic))
plt.plot(fpr_xgb, tpr_xgb, color='green', lw=2,
label='XGBoost (AUC = %0.2f 95%% CI[%0.2f, %0.2f])' % (roc_auc_xgb, lower_xgb, upper_xgb))
plt.plot(fpr_svm, tpr_svm, color='purple', lw=2,
label='SVM (AUC = %0.2f 95%% CI[%0.2f, %0.2f])' % (roc_auc_svm, lower_svm, upper_svm))
plt.plot(fpr_rf, tpr_rf, color='red', lw=2,
label='Random Forest (AUC = %0.2f 95%% CI[%0.2f, %0.2f])' % (roc_auc_rf, lower_rf, upper_rf))
plt.plot([0, 1], [0, 1], color='navy', lw=2, linestyle='--')
plt.xlim([-0.02, 1.02])
plt.ylim([-0.02, 1.02])
plt.xlabel('1 - Specificity', fontsize=14)
plt.ylabel('Sensitivity', fontsize=14)
plt.title('Test ROC Curve', fontsize=16)
plt.legend(loc="lower right", fontsize=12)
plt.grid(alpha=0.3)
plt.tight_layout()
plt.savefig('ROC_Curves_with_CI.pdf', format='pdf', bbox_inches='tight')
plt.show()
同時對Logistic回歸、XGBoost、SVM和隨機森林模型分別計算并繪制包含AUC值及其95%置信區間的ROC曲線,以對比不同模型的分類性能和穩定性,和前文參考文獻ROC曲線圖所表達的思想一致。