You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

能否在XGBoost随机森林回归模型中获取单棵树的预测结果?

获取XGBRFRegressor单棵树的预测结果

要获取集成前每棵树对测试集的预测结果,你可以借助XGBoost底层的Booster对象来实现,具体步骤如下:

  1. 获取模型的底层Booster实例
    XGBoost的Scikit-learn接口模型(包括XGBRFRegressor)都提供了get_booster()方法,用于获取底层的Booster对象,它支持更精细的预测控制。

  2. 遍历每棵树获取预测结果
    通过Booster的predict方法,利用iteration_range参数指定单棵树的范围(索引从0开始),依次获取每棵树的预测值,最后拼接成目标维度的数组。

完整代码示例

import numpy as np
import xgboost

# 你的原有模型训练代码
rfr_model = xgboost.XGBRFRegressor(n_estimators = 300,
                                max_depth = 5,
                                objective='reg:squarederror')
rfr_model.fit(X_train, y_train)

# 获取底层Booster对象
booster = rfr_model.get_booster()
n_trees = rfr_model.n_estimators

# 存储每棵树的预测结果
tree_preds = []
for tree_idx in range(n_trees):
    # 指定仅使用第tree_idx棵树进行预测
    single_tree_pred = booster.predict(X_test, iteration_range=(tree_idx, tree_idx + 1))
    tree_preds.append(single_tree_pred)

# 转换为(测试样本行数,树的数量)的维度
tree_preds = np.array(tree_preds).T

说明

  • iteration_range=(tree_idx, tree_idx + 1)表示只使用索引为tree_idx的树(左闭右开区间)进行预测
  • 最终的tree_preds数组,每行对应一个测试样本,每列对应一棵决策树的预测值

内容的提问来源于stack exchange,提问作者quasimodo

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.01 19:22:38