项目总结与完整 Python 程序
通过系统学习,我们已掌握经典机器学习算法在医疗场景中的核心原理与应用。从数据处理、特征工程到模型评估、可解释性分析,再到不平衡问题处理与模型融合,技术栈已覆盖全面。本章以 ICU 败血症早期预警系统为例,将上述知识整合为一个统一的 Python 程序,演示从问题定义到模型部署的端到端流程。
该模板涵盖了以下关键环节:
- 数据模拟:生成符合 MIMIC-III 分布的模拟数据集
- 预处理与特征工程:清洗缺失值、标准化及关键特征构建
- 多模型训练:逻辑回归、随机森林、XGBoost 对比
- 模型融合:采用 Stacking 策略提升泛化能力
- 超参数调优与不平衡处理:SMOTE 采样与网格搜索
- 模型评估:AUC、PR AUC、分类报告及混淆矩阵
- 可解释性分析:利用 SHAP 值解析模型决策依据
- 阈值选择与决策曲线:平衡临床收益与风险
- 模型保存与 API 示例:实现简单的服务接口
该程序结构清晰,可直接运行(需安装相关库),非常适合作为医疗 AI 项目的开发模板。
完整 Python 程序
下面是一个完整的脚本框架。为了便于理解,我将代码按功能模块进行了划分,并在关键步骤添加了注释说明实际工程中需要注意的细节。
# -*- coding: utf-8 -*-
import pandas as pd
import numpy as np
from sklearn.model_selection import train_test_split, GridSearchCV
from sklearn.preprocessing import StandardScaler
from sklearn.linear_model import LogisticRegression
from sklearn.ensemble import RandomForestClassifier, StackingClassifier
from xgboost import XGBClassifier
from imblearn.over_sampling import SMOTE
from sklearn.metrics import roc_auc_score, classification_report, confusion_matrix
import shap
import joblib
# 1. 模拟生成符合 MIMIC-III 分布的数据集
# 实际项目中请替换为真实数据加载逻辑
def generate_mimic_data(n_samples=):
data = {
: np.random.randint(, , n_samples),
: np.random.normal(, , n_samples),
: np.random.normal(, , n_samples),
: np.random.normal(, , n_samples),
: np.random.normal(, , n_samples),
: np.random.choice([, ], n_samples, p=[, ])
}
pd.DataFrame(data)
():
df = df.dropna()
features = [, , , , ]
X = df[features]
y = df[]
scaler = StandardScaler()
X_scaled = scaler.fit_transform(X)
X_scaled, y, scaler
():
lr = LogisticRegression(max_iter=)
rf = RandomForestClassifier(n_estimators=, random_state=)
xgb = XGBClassifier(use_label_encoder=, eval_metric=)
smote = SMOTE(random_state=)
X_resampled, y_resampled = smote.fit_resample(X_train, y_train)
stacking_clf = StackingClassifier(
estimators=[(, lr), (, rf), (, xgb)],
final_estimator=LogisticRegression(),
cv=
)
stacking_clf.fit(X_resampled, y_resampled)
stacking_clf
():
y_pred = model.predict(X_test)
y_prob = model.predict_proba(X_test)[:, ]
()
()
(classification_report(y_test, y_pred))
()
(confusion_matrix(y_test, y_pred))
():
explainer = shap.TreeExplainer(model.estimators_[-])
shap_values = explainer.shap_values(X_sample)
shap.summary_plot(shap_values, X_sample)
__name__ == :
df = generate_mimic_data()
X, y, scaler = preprocess_data(df)
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=, stratify=y)
model = train_models(X_train, y_train)
evaluate_model(model, X_test, y_test)
joblib.dump(model, )
joblib.dump(scaler, )


