【问题标题】:GridSearch / make_scorer strange results with xgboost modelGridSearch / make_scorer xgboost 模型的奇怪结果
【发布时间】:2016-03-15 22:16:25
【问题描述】:

我正在尝试将 sklearn 的 gridsearch 与 xgboost 创建的模型一起使用。为此,我正在创建一个基于 ndcg 评估的自定义记分器。我可以成功地使用 Snippet 1,但它太杂乱/太老套了,我宁愿使用好的旧 sklearn 来简化代码。我尝试实现 GridSearch,但结果完全关闭:对于相同的 X 和 y 集,我得到 NDCG@k = 0.8 与 Snippet 1 与 0.5 与 Snippet 2。显然我在这里没有做一些事情......

以下代码段返回的结果截然不同:

片段1:

kf = StratifiedKFold(y, n_folds=5, shuffle=True, random_state=42)

max_depth = [6]
learning_rate = [0.22]
n_estimators = [43]
reg_alpha = [0.1]
reg_lambda = [10]
for md in max_depth:
    for lr in learning_rate:
        for ne in n_estimators:
            for ra in reg_alpha:
                for rl in reg_lambda:

                    xgb = XGBClassifier(objective='multi:softprob', 
                                        max_depth=md, 
                                        learning_rate=lr, 
                                        n_estimators=ne,
                                        reg_alpha=ra, 
                                        reg_lambda=rl,
                                        subsample=0.6, colsample_bytree=0.6, seed=0)
                    print([md, lr, ne])

                    score = []
                    for train_index, test_index in kf:
                        X_train, X_test = X[train_index], X[test_index]
                        y_train, y_test = y[train_index], y[test_index]

                        xgb.fit(X_train, y_train)
                        y_pred = xgb.predict_proba(X_test)

                        score.append(ndcg_scorer(y_test, y_pred))

                    print('all scores: %s' % score)
                    print('average score: %s' % np.mean(score))

片段2:

from sklearn.grid_search import GridSearchCV

params = {
    'max_depth':[6], 
    'learning_rate':[0.22], 
    'n_estimators':[43],
    'reg_alpha':[0.1], 
    'reg_lambda':[10],
    'subsample':[0.6], 
    'colsample_bytree':[0.6]
}
xgb = XGBClassifier(objective='multi:softprob',seed=0)
scorer = make_scorer(ndcg_scorer, needs_proba=True)    
gs = GridSearchCV(xgb, params, cv=5, scoring=scorer, verbose=10, refit=False)
gs.fit(X,y)
gs.best_score_

虽然 sn-p1 给了我预期的结果,但 Snippet2 返回的分数与 ndcg_scorer 不一致。

【问题讨论】:

  • 我看到的第一个不一致 - 您在第二个 sn-p 中隐式使用带有 n_folds=2 的 KFold,而不是像第一个那样使用带有 n_folds=5 的 StratifiedKFold。第二次创建相同的 StratifiedKFold 并将其作为 cv 参数传递给 GridSearchCV。

标签: scikit-learn xgboost grid-search


【解决方案1】:

问题在于 cv inGridSearchCV(xgb, params, cv=5, scoring=scorer, verbose=10, refit=False)。它可以接收 KFold / StratifiedKFold 而不是 int。与doc 中所说的不同,默认情况下,“int”类型的 agrument 似乎不会调用 StratifiedKFold 另一个函数,可能是 KFold。

【讨论】:

    猜你喜欢
    • 2019-03-20
    • 2013-05-18
    • 2015-09-16
    • 2021-07-29
    • 2013-03-29
    • 2011-10-07
    • 2021-10-10
    • 1970-01-01
    • 2019-12-25
    相关资源
    最近更新 更多