我目前正在尝试在 SHAP 汇总图上绘制一组特定功能。但是,我正在努力寻找这样做所需的代码。
查看 Github 上的源代码时,summary_plot 函数似乎确实具有“特征”属性。但是,这似乎不能解决我的问题。
任何人都可以帮我绘制一组特定的功能,或者这在当前的 SHAP 代码中不是一个可行的选项。
一个可能的解决方案虽然很老套,但可能如下所示,例如在第 5 列中为单个特征绘制摘要图
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),
)
要仅绘制 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