使用 xgboost 分类器进行多类分类?

2024-01-29

我正在尝试使用 xgboost 进行多类分类,并使用此代码构建了它,

clf = xgb.XGBClassifier(max_depth=7, n_estimators=1000)

clf.fit(byte_train, y_train)
train1 = clf.predict_proba(train_data)
test1 = clf.predict_proba(test_data)

这给了我一些好的结果。我的案例的对数损失低于 0.7。但浏览了几页后,我发现我们必须使用 XGBClassifier 中的另一个目标来解决多类问题。以下是这些页面的推荐内容。

clf = xgb.XGBClassifier(max_depth=5, objective='multi:softprob', n_estimators=1000, 
                        num_classes=9)

clf.fit(byte_train, y_train)  
train1 = clf.predict_proba(train_data)
test1 = clf.predict_proba(test_data)

该代码也可以工作,但与我的第一个代码相比,它需要花费很多时间才能完成。

为什么我的第一个代码也适用于多类案例?我已经检查过它的默认目标是二元:用于二元分类的逻辑,但它对于多类确实效果很好?如果两者都正确,我应该使用哪一个?


事实上,即使默认的 obj 参数XGBClassifier is binary:logistic,它会内部判断标签y的类别数。当类号大于2时,会修改obj参数为multi:softmax.

https://github.com/dmlc/xgboost/blob/master/python-package/xgboost/sklearn.py https://github.com/dmlc/xgboost/blob/master/python-package/xgboost/sklearn.py

class XGBClassifier(XGBModel, XGBClassifierBase):
    # pylint: disable=missing-docstring,invalid-name,too-many-instance-attributes
    def __init__(self, objective="binary:logistic", **kwargs):
        super().__init__(objective=objective, **kwargs)

    def fit(self, X, y, sample_weight=None, base_margin=None,
            eval_set=None, eval_metric=None,
            early_stopping_rounds=None, verbose=True, xgb_model=None,
            sample_weight_eval_set=None, callbacks=None):
        # pylint: disable = attribute-defined-outside-init,arguments-differ

        evals_result = {}
        self.classes_ = np.unique(y)
        self.n_classes_ = len(self.classes_)

        xgb_options = self.get_xgb_params()

        if callable(self.objective):
            obj = _objective_decorator(self.objective)
            # Use default value. Is it really not used ?
            xgb_options["objective"] = "binary:logistic"
        else:
            obj = None

        if self.n_classes_ > 2:
            # Switch to using a multiclass objective in the underlying
            # XGB instance
            xgb_options['objective'] = 'multi:softprob'
            xgb_options['num_class'] = self.n_classes_
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

使用 xgboost 分类器进行多类分类? 的相关文章

随机推荐