我正在使用 LightGBM 和 Python 来解决多类分类问题。我想知道每棵树的单独预测。然而,我还没有成功。您能告诉我如何访问给定测试样本的每棵树的预测吗?我的最终目标是了解 LGBMClassifier.predict_proba 如何估计类别概率。
对于 LightGBM 模型,每棵树的叶子都包含以目标函数为单位的原始值,并对叶子值进行求和以产生预测。
LightGBM 的
predict()
API 允许您自定义使用哪些迭代树。
这是一个 Python 示例,展示了如何从 LightGBM 模型中获取预测:
import lightgbm as lgb
import numpy as np
from sklearn.datasets import make_blobs
X, y = make_blobs(n_samples=10_000, centers=3)
dtrain = lgb.Dataset(X, label=y)
bst = lgb.train(
train_set=dtrain,
params={
"objective": "multiclass",
"num_class": 3,
"num_leaves": 7
},
num_boost_round=10
)
# get predictions using all trees up to the 5th tree
preds_first5 = bst.predict(
X, num_iteration=5, raw_score=True
)
# get predictions using all trees up to the 6th tree
preds_first6 = bst.predict(
X, num_iteration=6, raw_score=True
)
# get predictions from exactly the 6th tree
preds_tree6 = bst.predict(
X, start_iteration=5, num_iteration=1, raw_score=True
)
# confirm that those things are consistent
np.testing.assert_allclose(
actual=preds_tree6,
desired=preds_first6 - preds_first5,
rtol=1e-10
)
请注意,对于多类分类,对于每次 boosting 迭代,LightGBM 为每个类训练 1 棵树。使用上面示例中训练的模型尝试以下操作。
# 30 trees (3 classes * 10 iterations)
assert bst.num_trees() == 30
LightGBM 的 predict()
API 可根据迭代(而不是树)进行配置。对于多类分类,它返回形状为
[num_data, num_classes]
的数组,其中元素
[i, j]
是数据中第
i
个样本属于第
j
类的预测概率。
bst.predict(X, start_iteration=5, num_iteration=1)
array([[0.37597866, 0.31173329, 0.31228805],
[0.37597866, 0.31173329, 0.31228805],
[0.37597866, 0.31173329, 0.31228805],
...])
如果您确实想查看多类分类模型的一棵 tree 的预测,请使用 lightgbm
Python 包,安装
pandas
并将模型转储到 DataFrame。
model_df = bst.trees_to_dataframe()
# dump the structure of exactly the 6th tree
model_df[model_df["tree_index"] == 5].head(50)
<= | |||||||||||||||
<= | |||||||||||||||
<= | |||||||||||||||
<= | |||||||||||||||
<= | |||||||||||||||
<= | |||||||||||||||
node_index
具有
L
的行)。您必须研究树的规则才能找出样本落入哪一片叶子。