python - 在 LightGBM 中使用“predict_contrib”获取 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
这似乎不起作用
解决方案
塑造价值观的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])
在我看来是一样的。
推荐阅读
- mysql - 案例在 Phalcon 模型管理器中的使用没有给出正确的值
- java - 使用 vert.x 处理异步操作
- php - 一次提交插入多个表
- sql - 在 APEX 5 ORACLE SQL 中使用动态魔法枢轴出现错误“此处只允许简单的列名”
- razor - 在 .net 核心上发布后对象丢失
- excel - VBA将excel文件作为附件附加并在电子邮件正文中包含工作表
- php - 从 vue axios 调用 laravel 命名路由
- javascript - 如果先前的日期输入具有特定值,则添加选择选项
- android - 检测 Android TV 上的 HDMI 服务是否已启动
- android - 在自定义位置安装 Android Studio