xgboost CV与自定义折叠python

时间:2017-03-24 17:39:06

标签: python cross-validation xgboost

我正在处理数据,每个患者都可以拥有不同数量的训练样例。运行Xgboost CV时,我想确保来自同一患者的数据仅限于同一折叠,因此我需要使用折叠,其中可能包含不同数量的索引。

当我在xgb.cv函数中使用'fold'参数传递包含索引的numpy数组列表时,我得到:

dtrain = dall.slice(np.concatenate([idset [i] for i in range(nfold)if k!= i])) ValueError:无法连接零维数组

我在R中实现了相同的过程,没有任何问题,我将自定义折叠作为列表传递,其中每个元素都是测试折叠索引的向量。

请问您可以建议将自定义索引传递给Python XGBoost CV函数的正确方法。谢谢!

1 个答案:

答案 0 :(得分:2)

这很旧,但是当我遇到类似问题时,我在Google搜索上给出了答案。

我想将TimeSeriesSplit与xgboost cv一起使用,但是由于folds参数期望使用KFold或StratifiedKFold而不能直接使用它,但是,您可以将自己的索引列表作为元组列表提供,如下所示

train1 =  [0, 1, 2, 3, 4] 
test1  =  [4, 5, 6, 7, 8]

train2 =  [9 ,10 ,11 ,12 ,13]
test2 =   [14, 15, 16, 17, 18]

train3=  [19, 20, 21, 22, 23, 24]
test3 =  [25, 26, 27, 28, 29, 30]

tsFolds = [(train1, test1), (train2, test2), (train3, test3)]

xgbCV = xgb.cv(
    params = parameters, 
    dtrain = trainDMat, 
    num_boost_round = num_boost_round,
    nfold = len(tsFolds),
    folds = tsFolds,
    metrics = {'rmse'},
    early_stopping_rounds = early_stopping_rounds,
    verbose_eval = True,
    seed = seed     
)