python - 在 LightGBM 中使用 'predict_contrib' 获取 SHAP 值

标签 python machine-learning lightgbm shap

在光GBM documentation据说可以设置 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

这似乎不起作用

最佳答案

Shap 使用 pred_contrib=True 来评估 LGBM 方式:

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])

输出:

(150, 15)
[-0.0176954   0.50644615  5.56584344  3.43032313]

来自 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])

输出:

3
array([-0.0176954 ,  0.50644615,  5.56584344,  3.43032313])

在我看来是一样的。

关于python - 在 LightGBM 中使用 'predict_contrib' 获取 SHAP 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64783497/

相关文章:

python - 如何避免需要递归地使用正则表达式来删除字符串末尾的单词?

python - 有没有办法在 python 中为类的所有实例运行一个方法?

python - Py4JJavaError : An error occurred while calling z:org. apache.spark.api.python.PythonRDD.runJob。 ModuleNotFoundError:没有名为 'numpy' 的模块

python - lightGBM 中的分类特征是如何编码的?

python - 用于二进制分类的 spark 逻辑回归 : apply new threshold for predicting 2 classes

python - Google App Engine模板unicode解码问题

python - SciKit Learn 中的多类逻辑回归

python - scikit-learn - 根据新输入预测训练模型

machine-learning - 情感分析的最佳预处理技术是什么?

python - Python LightGBM 中的 leaf_values 是什么?