機(jī)器學(xué)習(xí)模型的性能評(píng)估中,ROC曲線和AUC(曲線下面積)是常用的工具,它們能清晰展示模型的分類能力,但是一般ROC曲線展示的AUC值不會(huì)去展示置信區(qū)間,但是帶有95%置信區(qū)間的ROC曲線在醫(yī)學(xué)研究中非常常見(jiàn),因?yàn)樗軌蚋茖W(xué)地體現(xiàn)模型的診斷性能以及不確定性范圍

代碼實(shí)現(xiàn)

數(shù)據(jù)讀取

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
# 讀取數(shù)據(jù)
df = pd.read_excel('2024-11-21公眾號(hào)Python機(jī)器學(xué)習(xí)AI.xlsx')
# 劃分特征和目標(biāo)變量
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文件中讀取二分類數(shù)據(jù),將數(shù)據(jù)劃分為特征(X)和目標(biāo)變量(y),然后按80%訓(xùn)練集和20%測(cè)試集的比例進(jìn)行分層抽樣拆分,為后續(xù)機(jī)器學(xué)習(xí)建模做好準(zhǔn)備

logistic模型ROC曲線繪制

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ù)測(cè)概率
y_score = model.predict_proba(X_test)[:, 1]
# 計(jì)算 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='--')
# 調(diào)整顯示范圍,增加邊距
plt.xlim([-0.02, 1.02]) # 左右兩側(cè)各增加一點(diǎn)邊距
plt.ylim([-0.02, 1.02]) # 上下各增加一點(diǎn)邊距
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回歸模型進(jìn)行訓(xùn)練和預(yù)測(cè),通過(guò)計(jì)算假陽(yáng)性率和真陽(yáng)性率繪制最常見(jiàn)的ROC曲線,并標(biāo)注AUC值(不含95%置信區(qū)間),主要用于演示基本的ROC曲線繪制方法

AUC95% 置信區(qū)間函數(shù)定義

from math import sqrt

# 定義函數(shù):計(jì)算 AUC 及其 95% 置信區(qū)間
def roc_auc_ci(y_true, y_score, positive=1):
AUC = roc_auc_score(y_true, y_score)
# 統(tǒng)計(jì)正類和負(fù)類的樣本數(shù)
N1 = sum(y_true == positive)
N2 = sum(y_true != positive)
Q1 = AUC / (2 - AUC) # Q1 是 AUC 在正類樣本上的一個(gè)調(diào)整量
Q2 = 2 * AUC**2 / (1 + AUC) # Q2 是 AUC 在負(fù)類樣本上的一個(gè)調(diào)整量
# 計(jì)算 AUC 的標(biāo)準(zhǔn)誤差
SE_AUC = sqrt((AUC * (1 - AUC) + (N1 - 1) * (Q1 - AUC**2) + (N2 - 1) * (Q2 - AUC**2)) / (N1 * N2))
# 計(jì)算 95% 置信區(qū)間的下限和上限
lower = AUC - 1.96 * SE_AUC # 下限:AUC - 1.96 * 標(biāo)準(zhǔn)誤差
upper = AUC + 1.96 * SE_AUC # 上限:AUC + 1.96 * 標(biāo)準(zhǔn)誤差
# 修正置信區(qū)間邊界,確保在 [0, 1] 范圍內(nèi)
if lower < 0:
lower = 0
if upper > 1:
upper = 1
return (AUC, lower, upper)

通過(guò)計(jì)算AUC值及其標(biāo)準(zhǔn)誤差,可以推導(dǎo)出95%置信區(qū)間,用于評(píng)估模型區(qū)分正負(fù)樣本能力的穩(wěn)定性和可靠性。當(dāng)然,除了標(biāo)準(zhǔn)誤差法外,還可以采用Bootstrap方法計(jì)算置信區(qū)間,當(dāng)樣本量較大且數(shù)據(jù)分布平衡時(shí),標(biāo)準(zhǔn)誤差法因其快速高效是更優(yōu)選擇;而當(dāng)樣本量較小、不平衡或需要更靈活的分布假設(shè)時(shí),Bootstrap方法因其穩(wěn)健性更適用,但計(jì)算量更大, 不同計(jì)算方法可能會(huì)導(dǎo)致置信區(qū)間結(jié)果略有差異,應(yīng)根據(jù)具體需求選擇適用方法

logistic模型帶有置信區(qū)間的ROC曲線繪制

# 預(yù)測(cè)概率y_score = model.predict_proba(X_test)[:, 1]# 計(jì)算 ROC 曲線fpr, tpr, _ = roc_curve(y_test, y_score)
# 計(jì)算 AUC 和置信區(qū)間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()

通過(guò)Logistic回歸模型預(yù)測(cè)結(jié)果計(jì)算ROC曲線,并繪制包含AUC值及其95%置信區(qū)間的ROC圖,以直觀展示模型分類性能及其穩(wěn)定性

一個(gè)畫布下繪制多個(gè)機(jī)器學(xué)習(xí)帶有置信區(qū)間的的ROC曲線

from sklearn.ensemble import RandomForestClassifier
from sklearn.svm import SVC
import xgboost as xgb

# 訓(xùn)練和計(jì)算 Logistic Regression 的結(jié)果
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)

# 訓(xùn)練 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)

# 訓(xùn)練 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)

# 訓(xùn)練隨機(jī)森林
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))

# 繪制各個(gè)模型的 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()

同時(shí)對(duì)Logistic回歸、XGBoost、SVM和隨機(jī)森林模型分別計(jì)算并繪制包含AUC值及其95%置信區(qū)間的ROC曲線,以對(duì)比不同模型的分類性能和穩(wěn)定性,和前文參考文獻(xiàn)ROC曲線圖所表達(dá)的思想一致。

文章轉(zhuǎn)自微信公眾號(hào)@Python機(jī)器學(xué)習(xí)AI

上一篇:

整合數(shù)據(jù)分布+擬合線+置信區(qū)間+相關(guān)系數(shù)的皮爾遜相關(guān)可視化

下一篇:

基于Optuna的機(jī)器學(xué)習(xí)超參數(shù)調(diào)優(yōu)與自定義可視化分析
#你可能也喜歡這些API文章!

我們有何不同?

API服務(wù)商零注冊(cè)

多API并行試用

數(shù)據(jù)驅(qū)動(dòng)選型,提升決策效率

查看全部API→
??

熱門場(chǎng)景實(shí)測(cè),選對(duì)API

#AI文本生成大模型API

對(duì)比大模型API的內(nèi)容創(chuàng)意新穎性、情感共鳴力、商業(yè)轉(zhuǎn)化潛力

25個(gè)渠道
一鍵對(duì)比試用API 限時(shí)免費(fèi)

#AI深度推理大模型API

對(duì)比大模型API的邏輯推理準(zhǔn)確性、分析深度、可視化建議合理性

10個(gè)渠道
一鍵對(duì)比試用API 限時(shí)免費(fèi)