如何在SHAP总结图上绘制特定特征?

4

我目前正在尝试在SHAP总结图上绘制一组特定的特征。然而,我无法找到必要的代码来实现这一点。

查看Github上的源代码时,summary_plot函数似乎有一个“features”属性。但是,这似乎不是解决我的问题的方法。

是否有人能帮助我绘制一组特定的功能,或者在SHAP当前代码中这不是可行的选项?


1
在我看来,这是一个不寻常但合理的问题,尽管缺少了一些信息可能会有所帮助(具体来说:您指的是哪个代码库?您的版本是否最新?)。此外,我之所以说“不寻常”,部分原因在于它并不是非常适合在SO上进行讨论,但很可能更适合于数据科学或交叉验证(统计)Stack Exchange,并参考您正在使用的代码库。 - ti7
1
显然,这是相关的,但是SO更适合形式为“我尝试了X,但它没有达到我的预期,反而导致了错误!”并附有最小完整可验证示例的问题,因此重新表述您的问题将有助于它生存(不会被标记为离题/需要更多信息)并获得更多审查。 - ti7
3个回答

6
一种可行的解决方案可能是如下所示,例如在第五列中为单个特征绘制汇总图表。
shap.summary_plot(shap_values[:,5:6], X.iloc[:, 5:6])

0

我使用以下代码重构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),
        )

-2

如果只想绘制一个特征,需要在特征列表中获取要检查的特征的索引。

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


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接