共计 2032 个字符,预计需要花费 6 分钟才能阅读完成。
背景与痛点
慢性肾病(CKD)是一种逐渐丧失肾脏功能的疾病,早期诊断对治疗至关重要。CKD 数据集包含了患者的临床指标(如血红蛋白、血糖、白蛋白等)以及最终的诊断结果。这类数据集对机器学习模型构建极具价值,但也面临以下挑战:

- 数据不均衡 :健康样本远多于患病样本
- 特征相关性 :医学指标间存在复杂关联
- 缺失值普遍 :临床检查项目不完整
- 类别特征多 :如尿蛋白检测结果的分级
数据探索
首先加载数据并查看基本信息:
import pandas as pd
import matplotlib.pyplot as plt
df = pd.read_csv('ckd.csv')
print(df.info()) # 查看字段类型和缺失值
print(df.describe()) # 数值型特征统计
绘制关键特征的分布图:
# 血红蛋白分布对比
plt.figure(figsize=(10,6))
df[df['classification']=='ckd']['hemo'].hist(alpha=0.5, bins=20, label='CKD')
df[df['classification']=='notckd']['hemo'].hist(alpha=0.5, bins=20, label='Healthy')
plt.legend()
plt.xlabel('Hemoglobin Level')
plt.title('Feature Distribution Comparison')
预处理方案
缺失值处理
# 数值型特征用中位数填充
num_cols = ['age','bp','sg','al','su','bgr','bu','sc','sod','pot','hemo','pcv','wc','rc']
df[num_cols] = df[num_cols].fillna(df[num_cols].median())
# 类别型特征用众数填充
cat_cols = ['rbc','pc','pcc','ba','htn','dm','cad','appet','pe','ane']
df[cat_cols] = df[cat_cols].fillna(df[cat_cols].mode().iloc[0])
类别特征编码
from sklearn.preprocessing import LabelEncoder
# 二元类别直接编码
binary_cols = ['htn','dm','cad','pe','ane']
le = LabelEncoder()
for col in binary_cols:
df[col] = le.fit_transform(df[col])
# 多类别使用独热编码
df = pd.get_dummies(df, columns=['rbc','pc','pcc','ba','appet'])
处理数据不平衡
from imblearn.over_sampling import SMOTE
X = df.drop('classification', axis=1)
y = df['classification']
smote = SMOTE(random_state=42)
X_res, y_res = smote.fit_resample(X, y)
建模示例
构建完整的机器学习流水线:
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.ensemble import RandomForestClassifier
from sklearn.model_selection import train_test_split
# 划分数据集
X_train, X_test, y_train, y_test = train_test_split(X_res, y_res, test_size=0.2)
# 构建 pipeline
pipeline = Pipeline([('scaler', StandardScaler()),
('clf', RandomForestClassifier(n_estimators=100))
])
# 训练与评估
pipeline.fit(X_train, y_train)
print(f"Test Accuracy: {pipeline.score(X_test, y_test):.2f}")
避坑指南
处理医学数据时需要特别注意:
- 特征泄露 :确保预处理步骤(如填充缺失值)只在训练集上学习
- 评估指标 :不要仅看准确率,要关注召回率和 AUC 等指标
- 特征解释 :医学模型需要可解释性,避免黑箱模型
- 数据合规 :确保患者隐私保护,必要时进行数据匿名化
延伸阅读
- 《医学数据挖掘》第 5 章:特征工程方法
- Scikit-learn 文档中的 Pipeline 使用指南
- SMOTE 算法原始论文
实操练习
- 尝试用 XGBoost 替换随机森林,比较性能差异
- 实现一个自定义的特征选择器,筛选 Top-10 重要特征
- 用 SHAP 方法解释模型的预测逻辑
正文完
发表至: 未分类
近两天内
