xgb.cv
sklearn.model_selection.cross_validate
即使我设置了相同的种子/随机状态并且我确保两种方法都使用相同的折叠,也不会产生相同的平均训练/测试错误。底部的代码允许重现我的问题。(提前停止默认关闭)。
我发现这个问题是由subsample
参数引起的(如果此参数设置为 1,两种方法都会产生相同的结果),但我找不到一种方法可以使两种方法以相同的方式进行子采样。除了如底部代码所示设置种子/随机状态外,我还尝试显式添加:
import random
random.seed(1)
np.random.seed(1)
在我文件的开头,但这也不能解决我的问题。有任何想法吗?
import numpy as np
import xgboost as xgb
from xgboost import XGBClassifier
from sklearn.model_selection import cross_validate, StratifiedKFold
X = np.random.randn(100,20)
y = np.random.randint(0,2,100)
dtrain = xgb.DMatrix(X, label=y)
params = {'eta':0.3,
'max_depth': 4,
'gamma':0.1,
'silent': 1,
'objective': 'binary:logistic',
'seed': 1,
'subsample': 0.8
}
cv_results = xgb.cv(params, dtrain, num_boost_round=99, seed=1,
folds=StratifiedKFold(5, shuffle=False, random_state=1),
early_stopping_rounds=10)
print(cv_results, '\n')
xgbc = XGBClassifier(learning_rate=0.3,
max_depth=4,
gamma=0.1,
silent = 1,
objective = 'binary:logistic',
subsample = 0.8,
random_state = 1,
n_estimators=len(cv_results))
scores = cross_validate(xgbc, X, y,
cv=StratifiedKFold(5, shuffle=False, random_state=1),
return_train_score=True)
print('train-error-mean = {} test-error-mean = {}'.format(
1-scores['train_score'].mean(), 1-scores['test_score'].mean()))
输出:
train-error-mean train-error-std test-error-mean test-error-std
0 0.214981 0.030880 0.519173 0.129533
1 0.140039 0.018552 0.549549 0.034696
2 0.105100 0.017420 0.510501 0.040517
3 0.092474 0.012587 0.450977 0.075866
train-error-mean = 0.06994061572120636 test-error-mean = 0.4706015037593986
子样本设置为 1 时的输出:
train-error-mean train-error-std test-error-mean test-error-std
0 0.180043 0.013266 0.491504 0.093246
1 0.117381 0.021328 0.488070 0.097733
2 0.074972 0.030605 0.530075 0.091446
3 0.044907 0.032232 0.519073 0.130802
4 0.032438 0.021816 0.481027 0.080622
train-error-mean = 0.032438271604938285 test-error-mean = 0.4810275689223057