本项目是Kaggle上面的一个经典竞赛题,心脏病分类问题,题目链接在这里. 主要基于随机森林的bagging集成学习框架,通过13个生理特征数据,实现对心脏病分类的预测。
由于自己想要在这个项目更多的学习到模型解释方面的内容,所以对于模型精度没有过多的在意和调参。模型解释主要用了eli5,shap和部分依赖图。
下面是完整的代码和运行结果。在python3.7环境下可以运行。
文章目录
1 导入各种模块
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns # 画图
from sklearn.ensemble import RandomForestClassifier # bagging的随机森林
from sklearn.tree import DecisionTreeClassifier # 决策树模型
from sklearn.tree import export_graphviz # 绘制决策树
from sklearn.metrics import roc_curve,auc # 模型评价之ROC,AUC曲线
from sklearn.metrics import classification_report # 决策树分类报告
from sklearn.metrics import confusion_matrix # 混淆矩阵
from sklearn.model_selection import train_test_split # 训练集划分
import eli5 #for purmutation importance
from eli5.sklearn import PermutationImportance
import shap #for SHAP values
from sklearn.inspection import plot_partial_dependence
2 导入数据
数据集点这里下载:数据集免费下载
dt = pd.read_csv('./heart.csv')
2.1 修改特征名称
dt.columns = ['age', 'sex', 'chest_pain_type', 'resting_blood_pressure', 'cholesterol', 'fasting_blood_sugar', 'rest_ecg', 'max_heart_rate_achieved',
'exercise_induced_angina', 'st_depression', 'st_slope', 'num_major_vessels', 'thalassemia', 'target']
2.2 特征说明
| 特征名称 | 意义 | 数据说明 |
|---|---|---|
| age | 年龄 | 岁数 |
| sex | 性别 | 1:男;0:女 |
| chest_pain_type | 胸痛类别 | 1:典型胸痛;2:非典型胸痛;3:无胸痛;4:无症状 |
| resting_blood_pressure | 血压 | 单位mm |
| cholesterol | 胆固醇含量 | 单位:mg/dl |
| fasting_blood_sugar | 人的空腹血糖 | 1:大于120mg/dl;0:不大于120mg/dl |
| rest_ecg | 静息心电图测量 | 0 =正常;1 = ST-T波异常;2 = Estes标准可能或明确显示左室肥厚 |
| max_heart_rate_achieved | 最大心率 | |
| exercise_induced_angina | 运动引发的心绞痛 | 1=是;0=不是 |
| st_depressionoldpeak | 运动相对于休息引起的ST抑制 | |
| st_slope | 运动峰值ST段的斜率 | 1=上斜;2=平;3=下斜 |
| num_major_vessels | 主要血管的数量 | (0-3) |
| thalassemia | 地中海贫血的血液疾病 | 3=正常; 6=固定缺陷; 7 =可逆转缺陷 |
| target | 心脏病类别 | 1=有;0=没有 |
2.3 特征属性说明
# 展示前十个数据
dt.head(10)
| age | sex | chest_pain_type | resting_blood_pressure | cholesterol | fasting_blood_sugar | rest_ecg | max_heart_rate_achieved | exercise_induced_angina | st_depression | st_slope | num_major_vessels | thalassemia | target | |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
| 0 | 63 | 1 | 3 | 145 | 233 | 1 | 0 | 150 | 0 | 2.3 | 0 | 0 | 1 | 1 |
| 1 | 37 | 1 | 2 | 130 | 250 | 0 | 1 | 187 | 0 | 3.5 | 0 | 0 | 2 | 1 |
| 2 | 41 | 0 | 1 | 130 | 204 | 0 | 0 | 172 | 0 | 1.4 | 2 | 0 | 2 | 1 |
| 3 | 56 | 1 | 1 | 120 | 236 | 0< |
使用随机森林与模型解释技术分析心脏病预测

最低0.47元/天 解锁文章
3743

被折叠的 条评论
为什么被折叠?



