【问题标题】:Cross-validation on XGBClassifier for multiclass classification in pythonpython中多类分类的XGBClassifier交叉验证
【发布时间】:2016-10-17 04:30:00
【问题描述】:

我正在尝试使用改编自http://www.analyticsvidhya.com/blog/2016/03/complete-guide-parameter-tuning-xgboost-with-codes-python/ 的以下代码对 XGBClassifier 执行多类分类问题的交叉验证

import numpy as np
import pandas as pd
import xgboost as xgb
from xgboost.sklearn import  XGBClassifier
from sklearn.preprocessing import LabelEncoder
from sklearn import cross_validation, metrics
from sklearn.grid_search import GridSearchCV


def modelFit(alg, X, y, useTrainCV=True, cvFolds=5, early_stopping_rounds=50):
    if useTrainCV:
        xgbParams = alg.get_xgb_params()
        xgTrain = xgb.DMatrix(X, label=y)
        cvresult = xgb.cv(xgbParams,
                      xgTrain,
                      num_boost_round=alg.get_params()['n_estimators'],
                      nfold=cvFolds,
                      stratified=True,
                      metrics={'mlogloss'},
                      early_stopping_rounds=early_stopping_rounds,
                      seed=0,
                      callbacks=[xgb.callback.print_evaluation(show_stdv=False),                                                               xgb.callback.early_stop(3)])

        print cvresult
        alg.set_params(n_estimators=cvresult.shape[0])

    # Fit the algorithm
    alg.fit(X, y, eval_metric='mlogloss')

    # Predict
    dtrainPredictions = alg.predict(X)
    dtrainPredProb = alg.predict_proba(X)

    # Print model report:
    print "\nModel Report"
    print "Classification report: \n"
    print(classification_report(y_val, y_val_pred))
    print "Accuracy : %.4g" % metrics.accuracy_score(y, dtrainPredictions)
    print "Log Loss Score (Train): %f" % metrics.log_loss(y, dtrainPredProb)
    feat_imp = pd.Series(alg.booster().get_fscore()).sort_values(ascending=False)
    feat_imp.plot(kind='bar', title='Feature Importances')
    plt.ylabel('Feature Importance Score')


# 1) Read training set
print('>> Read training set')
train = pd.read_csv(trainFile)

# 2) Extract target attribute and convert to numeric
print('>> Preprocessing')
y_train = train['OutcomeType'].values
le_y = LabelEncoder()
y_train = le_y.fit_transform(y_train)
train.drop('OutcomeType', axis=1, inplace=True)

# 4) Extract features and target from training set
X_train = train.values

# 5) First classifier
xgb = XGBClassifier(learning_rate =0.1,
                    n_estimators=1000,
                    max_depth=5,
                    min_child_weight=1,
                    gamma=0,
                    subsample=0.8,
                    colsample_bytree=0.8,
                    scale_pos_weight=1,
                    objective='multi:softprob',
                    seed=27)

modelFit(xgb, X_train, y_train)

其中y_train 包含从0 到4 的标签。但是,当我运行此代码时,我从xgb.cv 函数xgboost.core.XGBoostError: value 0for Parameter num_class should be greater equal to 1 收到以下错误。在 XGBoost 文档上,我读到在多类情况下,xgb 从目标向量中的标签推断出类的数量,所以我不明白发生了什么。

【问题讨论】:

    标签: python classification cross-validation xgboost


    【解决方案1】:

    您必须将参数“num_class”添加到 xgb_param 字典。参数说明和您在上面提供的链接的评论中也提到了这一点。

    【讨论】:

    • 这解决了我的问题。我之前尝试在 XGBClassifier 初始化中设置num_class,但它无法识别参数。非常感谢!
    • 我不关注,当我将它添加到参数网格时,我得到ValueError: Invalid parameter num_class for estimator XGBClassifier. Check the list of available parameters with estimator.get_params().keys()。`
    • 我认为这个答案并没有充分解决问题,没有解释应该如何设置参数。与 sklearn 包装器相关的错误,但很多人都有这个问题,解决方案不明显。
    • @LetsPlayYahtzee how is someone supposed to set the parameter is not explained 这样:xgb_param[‘num_class’] = k #k = number of classes 这就是原始问题的答案。 The error related to the sklearn不是OP问题中的错误,而是另一个人的评论中的错误。
    • 这是完全错误的答案! API (xgboost.readthedocs.io/en/latest//python/…) 说 {num_class} 不是参数的一部分!他是怎么设置的?
    猜你喜欢
    • 2016-03-10
    • 2017-04-14
    • 2017-05-07
    • 2015-07-07
    • 2020-08-21
    • 2016-10-27
    • 2012-09-30
    • 2014-11-24
    • 2014-06-04
    相关资源
    最近更新 更多