1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191
|
import shap import xgboost import numpy as np import matplotlib.pyplot as plt from sklearn.model_selection import train_test_split import lightgbm as lgb import pandas as pd
X, y = shap.datasets.adult() X_display, y_display = shap.datasets.adult(display=True) X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=7)
model = xgboost.XGBClassifier(eval_metric='mlogloss').fit(X, y)
explainer = shap.Explainer(model) shap_values = explainer.shap_values(X) shap_values2 = explainer(X)
''' # 全局条形图:summary plot是针对全部样本预测的解释,是取每个特征的shap values的平均绝对值来获得标准条形图,这个其实就是全局重要度 # Summary_plot 为每一个样本绘制其每个特征的Shapley value,它说明哪些特征最重要,以及它们对数据集的影响范围。 # 另一种是通过散点简单绘制每个样本的每个特征的shap values,通过颜色可以看到特征值大小与预测影响之间的关系,同时展示其特征值分布 # 两个图都可以看到Relationship全局重要度是最高的,其次是Age。第一个图可以看到各个特征重要度的相对关系,虽然Capital Gain是第三,但是重要度只有Relationship的60%, # shap.summary_plot使用的是shap_values的数据类型为 <class 'numpy.ndarray'> # shap.plots.bar使用的是shap_values2的数据类型为<class 'shap._explanation.Explanation'> #shap.plots.bar(shap_values2, max_display = 12) shap.summary_plot(shap_values, X, plot_type="bar") #按照计算公式,可得其数值表格化如下 feature_importance = pd.DataFrame() feature_importance['feature'] = X.columns feature_importance['importance'] = np.abs(shap_values).mean(0) feature_importance.sort_values('importance', ascending=False) print(feature_importance) '''
shap.dependence_plot('Age', shap_values, X, display_features=X_display, interaction_index='Capital Gain')
shap_interaction_values = explainer.shap_interaction_values(X) shap.dependence_plot(('Age', 'Age'), shap_interaction_values, X, interaction_index=None)
plt.figure(figsize=(7.5, 5)) plt.scatter(X['Age'], shap_interaction_values[:, 0, 0], s=10, alpha=1)
''' # SHAP force plot 提供了单一模型预测的可解释性,可用于误差分析,找到对特定实例预测的解释 # 如果不想用JS,需要在shap.force_plot传入matplotlib=True的参数。否则就需要使用shap.initjs() # 模型输出值是-6.75,模型基值是-1.297,绘图箭头下方数字是此实例的特征值,将预测推高的特征用红色表示,将预测推低的特征用蓝色表示 # 箭头越长,特征对输出的影响越大。explainer.expected_value是解释模型的常数 #shap.initjs() # 初始化JavaScript库 #shap.force_plot(explainer.expected_value, shap_values[0,:], X_display.iloc[0,:]) # 或者 shap.force_plot(explainer.expected_value, shap_values[0,:], X_display.iloc[0,:], matplotlib=True) #其数值表格化如下: sample_0_shap = pd.DataFrame(X.iloc[0,:]) sample_0_shap.rename(columns={0: 'feature_value'}, inplace=True) sample_0_shap['shap_value'] = shap_values[0] sample_0_shap.sort_values('shap_value', ascending=False) print(sample_0_shap) '''
''' shap_values = explainer.shap_values(features) y_pred = (shap_values.sum(1) + expected_value) > 0 misclassified = y_pred != y[:20] shap.decision_plot(expected_value, shap_values, features_display, link='logit', highlight=misclassified)
# 通过单独绘制来检查错误分类的观察结果 shap.decision_plot(expected_value, shap_values[misclassified], features_display[misclassified], link='logit', highlight=0)
# 错误分类观察的力图 shap.force_plot(expected_value, shap_values[misclassified], features_display[misclassified], link='logit') '''
|