在 LightGBM 中使用“predict_contrib”来获取 SHAP 值

Cut*_*son 5 python machine-learning lightgbm shap

LightGBM文档中指出,可以设置predict_contrib=True来预测 SHAP 值。

我们如何提取 SHAP 值(除了使用shap包之外)?

我努力了

model = LGBM(objective="binary",is_unbalance=True,predict_contrib=True)
model.fit(X_train,y_train)
pred_shap = opt_model.predict(X_train) #Does not get SHAP-values
Run Code Online (Sandbox Code Playgroud)

这似乎不起作用

Ser*_*nov 6

Shap 的价值观LGBMpred_contrib=True

from lightgbm.sklearn import LGBMClassifier
from sklearn.datasets import load_iris

X,y = load_iris(return_X_y=True)
lgbm = LGBMClassifier()
lgbm.fit(X,y)
lgbm_shap = lgbm.predict(X, pred_contrib=True)
# Shape of returned LGBM shap values: 4 features x 3 classes + 3 expected values over the training dataset
print(lgbm_shap.shape)
# 0th row of LGBM shap values for 0th feature
print(lgbm_shap[0,:4])
Run Code Online (Sandbox Code Playgroud)

输出:

(150, 15)
[-0.0176954   0.50644615  5.56584344  3.43032313]
Run Code Online (Sandbox Code Playgroud)

形状值来自shap

import shap
explainer = shap.TreeExplainer(lgbm)
shap_values = explainer.shap_values(X)
# num of predicted classes
print(len(shap_values))
# shap values for 0th class for 0th row
print(shap_values[0][0])
Run Code Online (Sandbox Code Playgroud)

输出:

3
array([-0.0176954 ,  0.50644615,  5.56584344,  3.43032313])
Run Code Online (Sandbox Code Playgroud)

对我来说看起来一样。