在LightGBM中使用“predict_contrib”获取值

2024-09-28 03:24:32 发布

您现在位置:Python中文网/ 问答频道 /正文

在LightGBMdocumentation中,说明可以设置predict_contrib=True来预测形状值

我们如何提取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

这似乎不起作用


Tags: truemodelistraincontribpredictfit形状
2条回答

Shap以LGBM的方式对pred_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])

输出:

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

在我看来是一样的

这种混淆是因为在两个不同的lightgbmAPI中重复了控制参数(命名不一致)

两个主要API都使用自己的拼写:

而且documentation支持C版本(python API的拼写甚至不被视为别名…)

相关问题 更多 >

    热门问题