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

如何确定XGBoost每棵树训练时所用的样本子集?

获取XGBoost每棵树训练时subsample选中的具体样本行

XGBoost官方API没有直接提供获取每棵树subsample采样样本索引的功能,但可以通过以下两种方法实现:

方法一:手动控制单棵树训练流程(Python API)

通过手动循环训练每一棵树,在训练前自行完成subsample采样并记录样本索引,逻辑和XGBoost原生采样一致,完全可控。

代码示例

import xgboost as xgb
import numpy as np

# 准备训练数据(示例:100行样本,10个特征)
X = np.random.rand(100, 10)
y = np.random.randint(0, 2, size=100)
dtrain = xgb.DMatrix(X, label=y)

# 模型参数:关闭原生subsample,手动处理
params = {
    'objective': 'binary:logistic',
    'max_depth': 3,
    'learning_rate': 0.1,
    'seed': 42  # 设置随机种子保证结果可复现
}

# 初始化模型与存储容器
model = xgb.Booster(params, [dtrain])
num_trees = 10  # 计划训练的树数量
subsample_ratio = 0.7
tree_sample_indices = []

for round_idx in range(num_trees):
    # 手动生成无放回采样的样本索引
    sample_size = int(len(X) * subsample_ratio)
    selected_idx = np.random.choice(len(X), size=sample_size, replace=False)
    tree_sample_indices.append(selected_idx)
    
    # 基于采样后的样本创建DMatrix
    sampled_dtrain = dtrain.slice(selected_idx)
    
    # 训练单棵树并更新模型
    model.update(sampled_dtrain, round_idx)

# 查看结果:tree_sample_indices中存储了每棵树对应的样本索引
print("第1棵树选中的样本索引:", tree_sample_indices[0])

说明

  • 该方法完全复现XGBoost原生的subsample逻辑(默认无放回采样),若需要有放回采样,将replace=False改为replace=True即可。
  • 设置seed可以保证采样结果可复现,便于调试和验证。

方法二:修改XGBoost源码(深度定制)

如果需要保留XGBoost原生的自动训练流程,可以修改其C++源码,在采样逻辑中添加样本索引的记录逻辑:

  1. 找到XGBoost中负责subsample采样的代码(例如src/tree/updater_colmaker.cc中的采样逻辑);
  2. 在采样完成后,添加代码将选中的样本索引输出到日志或写入文件;
  3. 重新编译XGBoost即可使用。

该方法适合有C++开发基础的用户,能在不改变训练流程的前提下获取采样信息。

内容的提问来源于stack exchange,提问作者Mathew Darren Kusuma

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.30 05:50:16