Dar*_*ero 4 python machine-learning scikit-learn cross-validation xgboost
我正在尝试对数据集进行分类。我首先使用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
Run Code Online (Sandbox Code Playgroud)
结果是:
test-logloss-mean test-logloss-std train-logloss-mean
0 0.683539 0.000141 0.683407
179 0.622302 0.001504 0.606452
Run Code Online (Sandbox Code Playgroud)
我们可以看到它在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")
Run Code Online (Sandbox Code Playgroud)
其结果是:[-4.11429976 -2.08675843 -3.27346662]反转后仍然远离0.622。
我将断点抛到cross_val_score,然后看到分类器通过尝试以约0.99的概率预测测试集中的每个元组为负来做出疯狂的预测。
我想知道我哪里出错了。有人可以帮我吗?
小智 5
这个问题是有点老了,但我今天遇到了这个问题,并想出了为什么给出的结果xgboost.cv,并sklearn.model_selection.cross_val_score有很大的不同。
默认情况下,使用cross_val_score KFold或StratifiedKFoldshuffle参数为False的折叠,因此不会从数据中随机抽取折叠。
因此,如果执行此操作,则应该获得相同的结果,
cross_val_score(estimator, X=train_features, y=train_labels, scoring="neg_log_loss", cv = StratifiedKFold(shuffle=True, random_state=23333))
Run Code Online (Sandbox Code Playgroud)
保持random state中StratifiedKfold和seed在xgboost.cv同一得到准确可重复的结果。