python构建lightgbm模型,制作force plot代码
时间: 2023-06-18 14:05:22 浏览: 181
构建LightGBM模型可以使用以下代码:
```python
import lightgbm as lgb
from sklearn.datasets import load_boston
from sklearn.model_selection import train_test_split
# 载入数据
data = load_boston()
X_train, X_test, y_train, y_test = train_test_split(data.data, data.target, test_size=0.2, random_state=42)
# 构建LightGBM模型
params = {
'boosting_type': 'gbdt',
'objective': 'regression',
'metric': {'l2', 'l1'},
'num_leaves': 31,
'learning_rate': 0.05,
'feature_fraction': 0.9,
'bagging_fraction': 0.8,
'bagging_freq': 5,
'verbose': 0
}
lgb_train = lgb.Dataset(X_train, y_train)
lgb_eval = lgb.Dataset(X_test, y_test, reference=lgb_train)
gbm = lgb.train(params,
lgb_train,
num_boost_round=100,
valid_sets=lgb_eval,
early_stopping_rounds=5)
# 预测结果
y_pred = gbm.predict(X_test, num_iteration=gbm.best_iteration)
```
制作Force Plot需要使用shap包,可以使用以下代码实现:
```python
import shap
# 计算SHAP值
explainer = shap.TreeExplainer(gbm)
shap_values = explainer.shap_values(X_test)
# 制作Force Plot
shap.initjs()
shap.force_plot(explainer.expected_value, shap_values[0,:], X_test[0,:])
```
其中,`shap.TreeExplainer()`用于计算SHAP值,`shap_values()`用于计算所有测试数据的SHAP值,`shap.force_plot()`用于制作Force Plot。
阅读全文