统计数据

Ban*_*njo 5 python shap

我曾经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')
Run Code Online (Sandbox Code Playgroud)

在此处输入图片说明

shap提供一个图表以获取shap值。是否还有可用的统计信息?我对确切的shap值感兴趣。我阅读了Github存储库和文档,但是没有找到关于此主题的任何内容。

gre*_*uar 3

当我们查看时,shap_values我们发现它包含一些正数和负数,并且其维度等于数据集的维度boston。线性回归是一种 ML 算法,它计算最优y = wx + b,其中y是 MEDV,x是特征向量,w是权重向量。在我看来,shap_values存储wx- 每个特征的值乘以通过线性回归计算的权重向量的矩阵。

因此,为了计算想要的统计数据,我首先提取绝对值,然后对它们求平均值。顺序很重要!接下来,我使用初始列名称,并从最大影响到最小影响进行排序。至此,我希望我已经回答了你的问题!:)

from matplotlib import pyplot as plt


#rataining only the size of effect
shap_values_abs = np.absolute(shap_values)

#dividing to get good numbers
means_norm = shap_values_abs.mean(axis = 0)/1e-15

#sorting values and names
idx = np.argsort(means_norm)
means = np.array(means_norm)[idx]
names = np.array(boston.feature_names)[idx]

#plotting
plt.figure(figsize=(10,10))
plt.barh(names, means)
Run Code Online (Sandbox Code Playgroud)

平均值(Abs(shap_values))图