python – 为什么xgboost.cv和sklearn.cross_val_score给出不同的结果?

我正在尝试在数据集上创建分类器.我第一次使用XGBoost:

import xgboost as xgb
import pandas as pd
import numpy as np

train = pd.read_csv("train_users_processed_onehot.csv")
labels = train["Buy"].map({"Y":1, "N":0})

features = train.drop("Buy", axis=1)
data_dmat = xgb.DMatrix(data=features, label=labels)

params={"max_depth":5, "min_child_weight":2, "eta": 0.1, "subsamples":0.9, "colsample_bytree":0.8, "objective" : "binary:logistic", "eval_metric": "logloss"}
rounds = 180

result = xgb.cv(params=params, dtrain=data_dmat, num_boost_round=rounds, early_stopping_rounds=50, as_pandas=True, seed=23333)
print result

结果是:

        test-logloss-mean  test-logloss-std  train-logloss-mean  
0             0.683539          0.000141            0.683407
179           0.622302          0.001504            0.606452  

我们可以看到它大约是0.622;

但是当我使用完全相同的参数(我认为)切换到sklearn时,结果是完全不同的.以下是我的代码:

from sklearn.model_selection import cross_val_score
from xgboost.sklearn import XGBClassifier
import pandas as pd

train_dataframe = pd.read_csv("train_users_processed_onehot.csv")
train_labels = train_dataframe["Buy"].map({"Y":1, "N":0})
train_features = train_dataframe.drop("Buy", axis=1)

estimator = XGBClassifier(learning_rate=0.1, n_estimators=190, max_depth=5, min_child_weight=2, objective="binary:logistic", subsample=0.9, colsample_bytree=0.8, seed=23333)
print cross_val_score(estimator, X=train_features, y=train_labels, scoring="neg_log_loss")

结果是:[ – 4.11429976 -2.08675843 -3.27346662],在逆转之后仍然远离0.622.

我把一个断点扔进了cross_val_score,并且看到分类器正在通过尝试预测测试集中的每个元组为负的概率为0.99左右进行疯狂的预测.

我想知道我哪里出错了.有人能帮助我吗?

解决方法:

这个问题有点陈旧,但我今天遇到了问题并弄清楚为什么xgboost.cv和sklearn.model_selection.cross_val_score给出的结果完全不同.

默认情况下,cross_val_score使用KFold或StratifiedKFold,其shuffle参数为False,因此折叠不会从数据中随机拉取.

所以,如果你这样做,那么你应该得到相同的结果,

cross_val_score(estimator, X=train_features, y=train_labels, scoring="neg_log_loss", cv = StratifiedKFold(shuffle=True, random_state=23333))

保持StratifiedKfold中的随机状态并在xgboost.cv中播种相同以获得完全可重现的结果.

上一篇:机器学习之集成学习(三)


下一篇:推荐系统系列3-基于决策树做推荐系统的方法