python - SHAP:如何解释 force_plot 的预期值?

标签 python machine-learning random-forest shap xai

我正在尝试为我的随机森林模型创建一个 force_plot,它有两个类(1 和 2),但我对 force_plot 的参数有点困惑。

我有两个不同的 force_plot 参数,我可以提供以下参数:

shap.force_plot(explainer.expected_value[0], shap_values[0], choosen_instance, show=True, matplotlib=True)

expected and shap values: 0

shap.force_plot(explainer.expected_value[1], shap_values[1], choosen_instance, show=True, matplotlib=True)

expected and shap values: 1

所以我的问题是:

  1. 创建 force_plot 时,我必须提供 expected_value。对于我的模型,我有两个预期值:[0.20826239 0.79173761],我怎么知道要使用哪个?我对期望值的理解是它是我的模型对火车数据的平均预测。是否有两个值,因为我同时拥有 class_1 和 class_2?那么对于 class_1,平均预测是 0.20826239 而 class_2 是 0.79173761?

  2. 下一个参数是 shap_values,对于我选择的实例:

        index   B    G    R    Prediction
       113833  107  119  237      2
    

我得到以下 SHAP_values:

[array([[ 0.01705462, -0.01812987,  0.23416978]]), 
 array([[-0.01705462,  0.01812987, -0.23416978]])]

不太明白为什么会得到两组SHAP值?一个用于 class_1,一个用于 class_2?给定两组 SHAP 值和预期值,我一直在尝试比较我附加的图像,但我无法真正解释预测方面发生了什么。

最佳答案

让我们尝试可重现:

from sklearn.ensemble import RandomForestClassifier
from sklearn.datasets import load_breast_cancer
from sklearn.model_selection import train_test_split
from shap import TreeExplainer
from shap.maskers import Independent
from scipy.special import expit, logit

X, y = load_breast_cancer(return_X_y=True)
X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=42)

model = RandomForestClassifier(max_depth=5, n_estimators=100).fit(X_train, y_train)

那么,您的 SHAP 预期值为:

masker = Independent(data = X_train)
explainer = TreeExplainer(model, data=masker)
ev = explainer.expected_value
ev

array([0.35468973, 0.64531027])

这是您的模型在给定背景数据集(提供给上面的解释器)的情况下平均预测的结果:

model.predict_proba(masker.data).mean(0)

array([0.35468973, 0.64531027])

然后,如果您有感兴趣的数据点:

data_to_explain = X_train[[0]]
model.predict_proba(data_to_explain)  

array([[0.00470234, 0.99529766]])

您可以使用 SHAP 值实现完全相同的效果:

sv = explainer.shap_values(data_to_explain)
np.array(sv).sum(2).ravel() 

array([-0.34998739,  0.34998739])

请注意,它们是对称的,因为增加1 类机会的因素会减少相同数量的0 类机会。

对于基值和 SHAP 值,概率(或数据点最终出现在叶 01 中的机会)为:

ev + np.array(sv).sum(2).ravel()

array([0.00470234, 0.99529766])

请注意,这与模型预测相同。

关于python - SHAP:如何解释 force_plot 的预期值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71559181/

相关文章:

python - 如何使用 opencv - python 去除图像噪声?

machine-learning - Keras 中 LSTM 的多维输入

machine-learning - TensorFlow 二元分类任务精度较差,但 SciKit-Learn GBM 效果良好

带插入符包的随机森林 : Error: cannot allocate vector of size 153. 1 Gb

machine-learning - 给定特征数量找到随机森林的最大深度

python - 检查大型数据帧在 python 中合并/组合期间是否出现错误

python - 在文件中连续写入和读取

python - 每小时重新采样数据框

python - 值错误: Input has n_features=10 while the model has been trained with n_features=4261

statistics - 随机森林中每棵树的平均绝对误差