【基础+实践】随机森林预测心脏病患者

技术

给大家分享一个新的kaggle案例: 基于随机森林模型(RandomForest)的心脏病人预测分类 。本文涉及到的知识点主要包含:

  • 数据预处理和类型转化
  • 随机森林模型建立与解释
  • 决策树如何可视化
  • 基于混淆矩阵的分类评价指标
  • 部分依赖图PDP的绘制和解释
  • AutoML机器学习SHAP库的使用和解释(待提升)

picture.image

导读

Of all the applications of machine-learning, diagnosing any serious disease using a black box is always going to be a hard sell. If the output from a model is the particular course of treatment (potentially with side-effects), or surgery, or the absence of treatment, people are going to want to know why .

在机器学习的所有应用中,使用黑匣子诊断任何严重疾病总是很难的。如果模型的输出是特定的治疗过程(可能有副作用)、手术或是否有疗效,人们会想知道为什么。

This dataset gives a number of variables along with a target condition of having or not having heart disease. Below, the data is first used in a simple random forest model, and then the model is investigated using ML explainability tools and techniques.

该数据集提供了许多变量以及患有或不患有心脏病的目标条件。下面,数据首先用于一个简单的随机森林模型,然后使用 ML 可解释性工具和技术对该模型进行研究。

感兴趣的可以参考原文学习,notebook地址为:https://www.kaggle.com/tentotheminus9/what-causes-heart-disease-explaining-the-model

导入库

本案例中涉及到多个不同方向的库:

  • 数据预处理
  • 多种可视化绘图;尤其是shap的可视化 ,模型可解释性的使用(后面会专门写这个库)
  • 随机森林模型
  • 模型评价等

        
            

          import numpy as np  
import pandas as pd  
import matplotlib.pyplot as plt  
import seaborn as sns   
from sklearn.ensemble import RandomForestClassifier   
from sklearn.tree import DecisionTreeClassifier  
from sklearn.tree import export\_graphviz   
from sklearn.metrics import roc\_curve, auc   
from sklearn.metrics import classification\_report   
from sklearn.metrics import confusion\_matrix   
from sklearn.model\_selection import train\_test\_split   
import eli5   
from eli5.sklearn import PermutationImportance  
import shap   
from pdpbox import pdp, info\_plots   
np.random.seed(123)   
  
pd.options.mode.chained\_assignment = None    

        
      

数据探索EDA

1、导入数据

picture.image

2、缺失值情况

数据比较完美,没有任何缺失值!

picture.image

字段含义

在这里重点介绍下各个字段的含义。Peter近期导出的数据集中的额字段和原notebook中的字段名字写法稍有差异(时间原因导致),还好Peter已经为大家做了一一对应的关系,下面是具体的中文含义:

  1. age:年龄
  2. sex 性别 1=male 0=female
  3. cp 胸痛类型;4种取值情况
  • 1:典型心绞痛
  • 2:非典型心绞痛
  • 3:非心绞痛
  • 4:无症状
  • trestbps 静息血压

  • chol 血清胆固醇

  • fbs 空腹血糖 >120mg/dl :1=true;0=false

  • restecg 静息心电图(值0,1,2)

  • thalach 达到的最大心率

  • exang 运动诱发的心绞痛(1=yes;0=no)

  • oldpeak 相对于休息的运动引起的ST值(ST值与心电图上的位置有关)

  • slope 运动高峰ST段的坡度

  • 1:upsloping向上倾斜
  • 2:flat持平
  • 3:downsloping向下倾斜
  • ca The number of major vessels(血管) (0-3)

  • thal A blood disorder called thalassemia ,一种叫做地中海贫血的血液疾病(3 = normal;6 = fixed defect;;7 = reversable defect)

  • target 生病没有(0=no;1=yes)

原notebook中的英文含义;

picture.image


下面是Peter整理的对应关系。本文中以当前的版本为标准:

picture.image

字段转化

转化编码

对部分字段进行一一的转化。以sex字段为例:将数据中的0变成female,1变成male


        
            

          # 1、sex  
  
df["sex"][df["sex"] == 0] = "female"  
df["sex"][df["sex"] == 1] = "male"  

        
      

picture.image

picture.image

字段类型转化


        
            

          # 指定数据类型  
df["sex"] = df["sex"].astype("object")  
df["cp"] = df["cp"].astype("object")  
df["fbs"] = df["fbs"].astype("object")  
df["restecg"] = df["restecg"].astype("object")  
df["exang"] = df["exang"].astype("object")  
df["slope"] = df["slope"].astype("object")  
df["thal"] = df["thal"].astype("object")  

        
      

生成哑变量


        
            

          # 生成哑变量  
df = pd.get\_dummies(df,drop\_first=True)  
df  

        
      

picture.image

随机森林RandomForest

切分数据


        
            

          # 生成特征变量数据集和因变量数据集  
X = df.drop("target",1)  
y = df["target"]  
  
# 切分比例为8:2  
X\_train, X\_test, y\_train, y\_test = train\_test\_split(X,y,test\_size=0.2,random\_state=10)  
  
X\_train  

        
      

建模


        
            

          rf = RandomForestClassifier(max\_depth=5)  
rf.fit(X\_train, y\_train)  

        
      

3个重要属性

随机森林中3个重要的属性:

  • 查看森林中树的状况 :estimators_
  • 袋外估计准确率得分:oob_score_,必须是 oob\_score 参数选择True的时候才可用
  • 变量的重要性 :feature_importances_

决策树可视化

在这里我们选择的第二棵树的可视化过程:


        
            

          # 查看第二棵树的状况  
estimator = rf.estimators\_[1]  
  
# 全部属性  
feature\_names = [i for i in X\_train.columns]  
#print(feature\_names)  

        
      

        
            

          # 指定数据类型  
y\_train\_str = y\_train.astype('str')  
# 0-no 1-disease  
y\_train\_str[y\_train\_str == '0'] = 'no disease'  
y\_train\_str[y\_train\_str == '1'] = 'disease'  
# 训练数据的取值  
y\_train\_str = y\_train\_str.values  
y\_train\_str[:5]  

        
      

picture.image

绘图的具体代码为:


        
            

          # 绘图显示  
  
export\_graphviz(  
    estimator,   # 传入第二颗树  
    out\_file='tree.dot',   # 导出文件名  
    feature\_names = feature\_names,  # 属性名  
    class\_names = y\_train\_str,  # 最终的分类数据  
    rounded = True,   
    proportion = True,   
    label='root',  
    precision = 2,   
    filled = True  
)  
  
from subprocess import call  
call(['dot', '-Tpng', 'tree.dot', '-o', 'tree.png', '-Gdpi=600'])  
  
from IPython.display import Image  
Image(filename = 'tree.png')  

        
      

picture.image

决策树的可视化过程能够让我们看到具体的分类过程,但是并不能解决哪些特征或者属性比较重要。后面会对部分属性的特征重要性进行探索

模型得分验证

关于混淆矩阵和使用特异性(specificity)以及灵敏度(sensitivity)这两个指标来描述分类器的性能:


        
            

          # 模型预测  
y\_predict = rf.predict(X\_test)  
y\_pred\_quant = rf.predict\_proba(X\_test)[:,1]  
y\_pred\_bin = rf.predict(X\_test)  
  
# 混淆矩阵  
confusion\_matrix = confusion\_matrix(y\_test,y\_pred\_bin)  
confusion\_matrix  
  
# 计算sensitivity and specificity   
total=sum(sum(confusion\_matrix))  
sensitivity = confusion\_matrix[0,0]/(confusion\_matrix[0,0]+confusion\_matrix[1,0])  
specificity = confusion\_matrix[1,1]/(confusion\_matrix[1,1]+confusion\_matrix[0,1])  

        
      

picture.image

绘制ROC曲线


        
            

          fpr, tpr, thresholds = roc\_curve(y\_test, y\_pred\_quant)  
  
fig, ax = plt.subplots()  
ax.plot(fpr, tpr)  
  
ax.plot([0,1],[0,1],  
        transform = ax.transAxes,  
        ls = "--",  
        c = ".3"  
       )  
  
plt.xlim([0.0, 1.0])  
plt.ylim([0.0, 1.0])  
  
plt.rcParams['font.size'] = 12  
  
# 标题  
plt.title('ROC Curve')  
# 两个轴的名称  
plt.xlabel('False Positive Rate (1 - Specificity)')  
plt.ylabel('True Positive Rate (Sensitivity)')  
# 网格线  
plt.grid(True)  

        
      

picture.image

本案例中的ROC曲线值:


        
            

          auc(fpr, tpr)  
# 结果  
0.9076923076923078  

        
      

根据一般ROC曲线的评价标准,案例的表现结果还是不错的:

  • 0.90 - 1.00 = excellent
  • 0.80 - 0.90 = good
  • 0.70 - 0.80 = fair
  • 0.60 - 0.70 = poor
  • 0.50 - 0.60 = fail

补充知识点:分类器的评价指标

考虑一个二分类的情况,类别为1和0,我们将1和0分别作为正类(positive)和负类(negative),根据实际的结果和预测的结果,则最终的结果有4种,表格如下:

picture.image

常见的评价指标:

1、ACC :classification accuracy,描述分类器的分类准确率

计算公式为:ACC=(TP+TN)/(TP+FP+FN+TN)

2、BER :balanced error rate 计算公式为:BER=1/2*(FPR+FN/(FN+TP))

3、TPR :true positive rate,描述识别出的所有正例占所有正例的比例 计算公式为:TPR=TP/ (TP+ FN)

4、FPR :false positive rate,描述将负例识别为正例的情况占所有负例的比例 计算公式为:FPR= FP / (FP + TN)

5、TNR :true negative rate,描述识别出的负例占所有负例的比例 计算公式为:TNR= TN / (FP + TN)

6、PPV :Positive predictive value计算公式为:PPV=TP / (TP + FP)

7、NPV :Negative predictive value计算公式:NPV=TN / (FN + TN)

其中 TPR 即为敏感度(sensitivity), TNR 即为特异度(specificity)。

picture.image

来自维基百科的经典图形:

picture.image

可解释性

排列重要性-Permutation Importance

下面的内容是关于机器学习模型的结果可解释性。首先考察的是每个变量对模型的重要性。重点考量的排列重要性Permutation Importance:

picture.image

部分依赖图( Partial dependence plots ,PDP)

一维PDP

Partial Dependence就是用来解释某个特征和目标值y的关系的,一般是通过画出Partial Dependence Plot(PDP)来体现。也就是说PDP在X1的值,就是把训练集中第一个变量换成X1之后,原模型预测出来的平均值。

重点:查看单个特征和目标值的关系

字段ca


        
            

          base\_features = df.columns.values.tolist()  
base\_features.remove("target")  
  
feat\_name = 'ca'  # ca-num\_major\_vessels 原文  
pdp\_dist = pdp.pdp\_isolate(  
    model=rf,  # 模型  
    dataset=X\_test,  # 测试集  
    model\_features=base\_features,  # 特征变量;除去目标值   
    feature=feat\_name  # 指定单个字段  
)  
  
pdp.pdp\_plot(pdp\_dist, feat\_name)  # 传入两个参数  
plt.show()  

        
      

通过下面的图形我们观察到:当ca字段增加的时候,患病的几率在下降。ca字段的含义是血管数量(num_major_vessels),也就是说当血管数量增加的时候,患病率随之降低

picture.image

字段age


        
            

          feat\_name = 'age'  
  
pdp\_dist = pdp.pdp\_isolate(  
    model=rf,   
    dataset=X\_test,   
    model\_features=base\_features,   
    feature=feat\_name)  
  
pdp.pdp\_plot(pdp\_dist, feat\_name)  
plt.show()  

        
      

关于年龄字段age,原文的描述:

That's a bit odd. The higher the age, the lower the chance of heart disease? Althought the blue confidence regions show that this might not be true (the red baseline is within the blue zone).

翻译:这有点奇怪。年龄越大,患心脏病的几率越低?尽管蓝色置信区间表明这可能不是真的(红色基线在蓝色区域内)

picture.image

字段oldpeak


        
            

          feat\_name = 'oldpeak'  
  
pdp\_dist = pdp.pdp\_isolate(  
    model=rf,   
    dataset=X\_test,   
    model\_features=base\_features,   
    feature=feat\_name)  
  
pdp.pdp\_plot(pdp\_dist, feat\_name)  
plt.show()  

        
      

oldpeak字段同样表明:取值越大,患病几率越低。

picture.image

这个变量称之为“相对休息运动引起的ST压低值”。正常的状态下, 该值越高,患病几率越高 。但是上面的图像却显示了相反的结果。

作者推断:造成这个结果的原因除了the depression amount,可能还和slope type有关系。原文摘录如下,于是作者绘制了2D-PDP图形

Perhaps it's not just the depression amount that's important, but the interaction with the slope type? Let's check with a 2D PDP

2D-PDP图

查看的是 slope_upsloping 、slope_flat和 oldpeak的关系:


        
            

          inter1  =  pdp.pdp\_interact(  
    model=rf,  # 模型  
    dataset=X\_test,  # 特征数据集  
    model\_features=base\_features,  # 特征  
    features=['slope\_upsloping', 'oldpeak'])  
  
pdp.pdp\_interact\_plot(  
    pdp\_interact\_out=inter1,   
    feature\_names=['slope\_upsloping', 'oldpeak'],   
    plot\_type='contour')  
plt.show()  
  
## ------------  
  
inter1  =  pdp.pdp\_interact(  
    model=rf,   
    dataset=X\_test,  
    model\_features=base\_features,   
    features=['slope\_flat', 'oldpeak']  
)  
  
pdp.pdp\_interact\_plot(  
    pdp\_interact\_out=inter1,   
    feature\_names=['slope\_flat', 'oldpeak'],   
    plot\_type='contour')  
plt.show()  

        
      

picture.image

picture.image

从两张图形中我们可以观察到:在oldpeak取值较低的时候,患病几率都比较高(黄色),这是一个奇怪的现象。于是作者进行了如下的SHAP可视化探索:针对单个变量进行分析。

SHAP可视化

关于SHAP的介绍可以参考文章:https://zhuanlan.zhihu.com/p/83412330https://blog.csdn.net/sinat\_26917383/article/details/115400327

SHAP 是Python开发的一个"模型解释"包,可以解释任何机器学习模型的输出。下面SHAP使用的部分功能:

Explainer

在SHAP中进行模型解释之前需要先创建一个 explainer ,SHAP支持很多类型的explainer,例如deep, gradient, kernel, linear, tree, sampling)。在这个案例我们以tree为例:


        
            

          # 传入随机森林模型rf  
explainer = shap.TreeExplainer(rf)    
# 在explainer中传入特征值的数据,计算shap值  
shap\_values = explainer.shap\_values(X\_test)    
shap\_values  

        
      

picture.image

image-20220131173928357

Feature Importance

取每个特征 SHAP值的绝对值的平均值 作为该特征的重要性,得到一个标准的条形图(multi-class则生成堆叠的条形图:

picture.image

结论:能够直观地观察到ca字段的SHAP值最高

summary_plot

summary plot 为每个样本绘制其每个特征的SHAP值,这可以更好地理解整体模式,并允许发现预测异常值。

  • 每一行代表一个特征,横坐标为SHAP值
  • 一个点代表一个样本,颜色表示特征值的高低(红色高,蓝色低)

picture.image

个体差异

查看单个病人的不同特征属性对其结果的影响,原文描述为:

Next, let's pick out individual patients and see how the different variables are affecting their outcomes


        
            

          def heart\_disease\_risk\_factors(model, patient):  
  
    explainer = shap.TreeExplainer(model)  # 建立explainer  
    shap\_values = explainer.shap\_values(patient)  # 计算shape值  
    shap.initjs()  
    return shap.force\_plot(  
      explainer.expected\_value[1],  
      shap\_values[1],   
      patient)  

        
      

picture.image

从两个病人的结果中显示:

  • P1:预测准确率高达29%(baseline是57%),更多的因素集中在ca、thal_fixed_defect、oldpeak等蓝色部分。
  • P3:预测准确率高达82%,更多的影响因素在sel_male=0,thalach=143等

通过对比不同的患者,我们是可以观察到不同病人之间的预测率和主要影响因素。

dependence_plot

为了理解单个feature如何影响模型的输出,我们可以将该feature的SHAP值与数据集中所有样本的feature值进行比较:

picture.image

多样本可视化探索

下面的图形是针对多患者的预测和影响因素的探索。在jupyter notebook的交互式作用下,能够观察不同的特征属性对前50个患者的影响:


        
            

          shap\_values = explainer.shap\_values(X\_train.iloc[:50])  
shap.force\_plot(explainer.expected\_value[1],   
                shap\_values[1],   
                X\_test.iloc[:50])  

        
      

picture.image

picture.image

picture.image

交流群:点击“联系作者”--备注“研究方向-公司或学校”

欢迎干货投稿|论文宣传|合作交流

往期推荐

[picture.image

WWW'22 | GDNS:基于增益的动态负采样方法用于推荐系统](https://mp.weixin.qq.com/s?__biz=MzkxNjI4MDkzOQ==&mid=2247490673&idx=1&sn=0b991f8f718ea470370c5f58db079281&chksm=c1531f75f6249663ffe789e25bd9b63a9e3643ef03196883d9b775453d0a2eddb912fc0e13ff&scene=21#wechat_redirect)

[picture.image

WWW'22「华为」CPR Loss:交叉成对排序损失对推荐系统纠偏](https://mp.weixin.qq.com/s?__biz=MzkxNjI4MDkzOQ==&mid=2247490641&idx=1&sn=df4fd8acf12b8bf28ecc0703f5f11789&chksm=c1531f55f6249643757ab4ef6d22a9347882dc81408a56ebeabdccea6ee09911c321c98a077f&scene=21#wechat_redirect)

[picture.image

AAAI'22「腾讯」多任务推荐系统中的跨任务知识蒸馏](https://mp.weixin.qq.com/s?__biz=MzkxNjI4MDkzOQ==&mid=2247490616&idx=1&sn=af0d34e0673bfde89d528da60b59a26e&chksm=c1531f3cf624962add8eafbcc2f47070252d7354a299b02aedfcd87233305c163f66b26eef04&scene=21#wechat_redirect)

picture.image

长按关注,更多精彩

picture.image

picture.image

点个在看你最好看

0
0
0
0
评论
未登录
看完啦,登录分享一下感受吧~
暂无评论