如何获取每个特征的SHAP值?

How to get the SHAP values of each feature?

我目前正在使用 SHAP 库,我已经用每个特征的平均贡献生成了我的图表,但是我想知道绘制在图表上的确切值

import numpy as np
import pandas as pd  
from sklearn.linear_model import LinearRegression
from sklearn.datasets import load_boston
import shap


boston = load_boston()
regr = pd.DataFrame(boston.data)
regr.columns = boston.feature_names
regr['MEDV'] = boston.target

X = regr.drop('MEDV', axis = 1)
Y = regr['MEDV']

fit = LinearRegression().fit(X, Y)

explainer = shap.LinearExplainer(fit, X, feature_dependence = 'independent')
# I used 'independent' because the result is consistent with the ordinary 
# shapely values where `correlated' is not

shap_values = explainer.shap_values(X)

shap.summary_plot(shap_values, X, plot_type = 'bar')

如何获得图表中描绘的准确值?

pd.DataFrame((zip(X.columns[np.argsort(np.abs(shap_values).mean(0))],
np.abs(shap_values).mean(0))), columns=["feature", "importance" ]).sort_values(by="importance", ascending=False)

参考GitHub

尝试:

features = X.columns
mask = np.abs(shap_values).mean(0).argsort()[::-1]
features[mask]

Index(['LSTAT', 'DIS', 'RAD', 'RM', 'TAX', 'PTRATIO', 'NOX', 'ZN', 'CRIM', 'B',
       'CHAS', 'INDUS', 'AGE'],
      dtype='object')