我目前正在尝试在 SHAP 摘要图上绘制一组特定特征。但是,我正在努力寻找执行此操作所需的代码。
查看 Github 上的源代码时,summary_plot 函数似乎确实具有“features”属性。然而,这似乎并不能解决我的问题。
任何人都可以帮我绘制一组特定的特征,或者这在当前的 SHAP 代码中不是一个可行的选项。
一个可能的解决方案,尽管有点hacky,可能如下所示,例如在第五列中绘制单个特征的摘要图
shap.summary_plot(shap_values[:,5:6], X.iloc[:, 5:6])
我使用下面的代码重建 shap_value 以将您想要的特征包含到图中。
shap_values = explainer.shap_values(samples)[1]
vals = np.abs(shap_values).mean(0)
feature_importance = pd.DataFrame(
list(zip(samples.columns, vals)),
columns=["col_name", "feature_importance_vals"],
)
feature_importance.sort_values(
by=["feature_importance_vals"], ascending=False, inplace=True
)
feature_importance['rank'] = feature_importance['feature_importance_vals'].rank(method='max',ascending=False)
missing_features = [
i
for i in columns_to_show
if i not in feature_importance["col_name"][:20].tolist()
]
missing_index = []
for i in missing_features:
missing_index.append(samples.columns.tolist().index(i))
missing_features_new = []
rename_col = {}
for i in missing_features:
rank = int(feature_importance[feature_importance['col_name']==i]['rank'].values)
missing_features_new.append('rank:'+str(rank)+' - '+i)
rename_col[i] = 'rank:'+str(rank)+' - '+i
column_names = feature_importance["col_name"][:20].values.tolist() + missing_features_new
feature_index = feature_importance.index[:20].tolist() + missing_index
shap.summary_plot(
shap_values[:, feature_index].reshape(
samples.shape[0], len(feature_index)
),
samples.rename(columns=rename_col)[column_names],
max_display=len(feature_index),
)
看起来 shap._explanation.Explanation 对象将采用索引列表。 下面的代码将根据与特征名称的子字符串匹配来选择特征,并仅在蜂群图中显示这些特征名称的 SHAP 值。
selected_indices = [i for i,name in enumerate(shap_values.feature_names) if 'substring' in name]
shap.plots.beeswarm(shap_values_xgb[:,selected_indices])
要仅绘制 1 个特征,请在特征列表中获取要检查的特征的索引
i = X.iloc[:,:].index.tolist().index('your_feature_name_here')
shap.summary_plot(shap_values[1][:,i:i+1], X.iloc[:, i:i+1])
要绘制您选择的特征,
your_feature_list = ['your_feature_1','your_feature_2','your_feature_3']
your_feature_indices = [X.iloc[:,:].index.tolist().index(x) for x in your_feature_list]
shap.summary_plot(shap_values[1][:,your_feature_indices], X.iloc[:, your_feature_indices])
随意将“your_feature_indices”更改为更短的变量名称
如果您不进行二元分类,请将 shap_values[1] 更改为 shap_values