温馨提示:文末有 CSDN 平台官方提供的学长 QQ 名片 :)
重症患者或重大手术后的患者在重症监护室(ICU)内通过多种生命支持系统以维持生理功能。患者在ICU 内会被频繁持续的记录生命体征和实验室测量等多种数据。由于高频次的数据采集,数十年来ICU 内已经形成了一个巨大的临床医疗数据信息库,这俨然是一种重要的、可被利用的医疗资源。
本系统通过构建决策树机器学习算法,可根据ICU中脑血管疾病患者的实时17项生理参数的输入来实时预测患者的死亡风险,预测结果为0代表无风险,结果为1代表有风险。利用Pandas、Numpy、Matplotlib 和 Seaborn 等工具包对脑血管数据进行多维度的可视化分析。最后,利用 Flask + Bootstrap + Echarts 框架搭建 Web 系统,通过上传最新 ICU脑血管监测数据,实时预测患者的死亡风险。
- def contains_null(dataframe):
- """数据缺失值分析"""
- missing_df = dataframe.isnull().sum(axis=0).reset_index()
- missing_df.columns = ['column_name', 'missing_count']
- missing_df['missing_rate'] = 1.0 * missing_df['missing_count'] / dataframe.shape[0]
- missing_df = missing_df[missing_df.missing_count > 0]
- missing_df = missing_df.sort_values(by='missing_count', ascending=False)
- return missing_df

可以看出,原始数据集存在大量的缺失,将缺失率超过 80% 的特征进行剔除。剩下的数值类型的缺失值,利用相应特征的平均值进行填充。
通过对原始数据集进行标签化处理,构造机器学习模型训练所需要的训练集:
- from tqdm import tqdm
-
- def create_dataset(df, is_test=False):
- train_x = []
- train_y = []
- for i, row in tqdm(df.iterrows(), total=df.shape[0]):
- f = row['stay']
-
- if is_test:
- data = pd.read_csv('./data/test/' + f)
- else:
- data = pd.read_csv('./data/train/' + f)
- # 数据预处理
- data = data.drop(['Capillary refill rate', 'Height', 'Fraction inspired oxygen', 'Weight', 'pH',
- 'Glucose', 'Temperature', 'Glascow coma scale total', 'Glascow coma scale verbal response',
- 'Glascow coma scale eye opening'], axis=1)
- # 删除类别类型的特征
- del data['Glascow coma scale motor response']
- # 缺失值填充
- col_mean = dict(data.mean())
- for key in data.columns:
- data[key].fillna(col_mean[key], inplace=True)
-
- # 特征工程核心函数
- features = feature_engineering(data)
-
- train_x.append(features)
- train_y.append(row['y_true'])
-
- # 创建 dataframe 表格
- train_x = ......
-
- return train_x, train_y
- plt.figure(figsize=(20, 5))
- plt.subplot(131)
- sns.countplot(train_x['label'])
- plt.title('训练集ICU脑血管疾病死亡风险分布', fontsize=16, weight='bold')
-
- plt.subplot(132)
- sns.countplot(valid_x['label'])
- plt.title('验证集ICU脑血管疾病死亡风险分布', fontsize=16, weight='bold')
-
- plt.subplot(133)
- sns.countplot(test_x['label'])
- plt.title('测试集ICU脑血管疾病死亡风险分布', fontsize=16, weight='bold')
- plt.show()

ICU 脑血管疾病死亡风险预测为典型的二分类问题,以此目标函数选择 `binary:logistic`,验证指标选择 AUC 指标:
- import xgboost as xgb
- from sklearn.model_selection import train_test_split
- from sklearn.metrics import auc, roc_curve
- from sklearn.metrics import accuracy_score, precision_score, recall_score
-
- def evaluate_score(predict, y_true):
- false_positive_rate, true_positive_rate, thresholds = roc_curve(y_true, predict, pos_label=1)
- auc_score = auc(false_positive_rate, true_positive_rate)
- return auc_score
-
- dtrain = xgb.DMatrix(train_x, train_y, feature_names=feature_names)
- dvalid = xgb.DMatrix(valid_x, valid_y, feature_names=feature_names)
- dtest = xgb.DMatrix(test_x, test_y, feature_names=feature_names)
-
- watchlist = [(dtrain, 'train'), (dvalid, 'valid')]
-
- xgb_params = {
- 'eta': 0.05,
- 'colsample_bytree': 0.1,
- 'max_depth': 6,
- 'subsample': 0.1,
- 'lambda': 1,
- 'scale_pos_weight': 1,
- 'eval_metric': 'auc',
- 'objective': 'binary:logistic',
- 'nthread': -1,
- 'silent': 1,
- 'booster': 'gbtree'
- }
- model = xgb.train(dict(xgb_params),
- dtrain,
- evals=watchlist,
- verbose_eval=1,
- early_stopping_rounds=10,
- num_boost_round=5)
模型训练日志如下:
- [0] train-auc:0.785276 valid-auc:0.785276
- Multiple eval metrics have been passed: 'valid-auc' will be used for early stopping.
-
- Will train until valid-auc hasn't improved in 10 rounds.
- [1] train-auc:0.848569 valid-auc:0.848569
- [2] train-auc:0.897501 valid-auc:0.897501
- [3] train-auc:0.898473 valid-auc:0.898473
- [4] train-auc:0.903983 valid-auc:0.903983
模型训练完成后,可以看出,训练集和验证集的 AUC 指标可以达到 90% 以上,可以有效预测脑血管疾病的死亡风险。其特征的重要程度分布如下:

- from sklearn.metrics import auc, roc_curve
-
- fpr, tpr, _ = roc_curve(valid_y, predict_valid)
- roc_auc = auc(fpr, tpr)
-
- plt.figure(figsize=(10,10))
- plt.plot(fpr, tpr, color='darkorange',
- lw=2, label='ROC curve (area = %0.2f)' % roc_auc)
- plt.plot([0, 1], [0, 1], color='navy', lw=2, linestyle='--')
- plt.xlim([-0.02, 1.0])
- plt.ylim([0.0, 1.05])
- plt.xlabel('False Positive Rate')
- plt.ylabel('True Positive Rate')
- plt.title('ROC curve')
- plt.legend(loc="lower right")
- plt.show()

可以看出,构建的机器学习模型具备很好的预测性能,可以根据用户的历史 Diastolic blood pressure Heart Rate Mean blood pressure Oxygen saturation Respiratory rate Systolic blood pressure 特征,实现脑血管死亡风险预警!
本课题利用 Flask + Bootstrap + Echarts 框架搭建 Web 系统,通过上传最新 ICU脑血管监测数据,绘制主要特征的时序变化情况、模型的性能表现,并实时预测患者的死亡风险的概率值。

欢迎大家点赞、收藏、关注、评论啦 ,由于篇幅有限,只展示了部分核心代码。
精彩专栏推荐订阅:
