【问题标题】:How to deal with unbalanced xgboost multiclass classification within Scikit.learn pipeline?如何处理 Scikit.learn 管道中不平衡的 xgboost 多类分类?
【发布时间】:2019-11-22 10:32:28
【问题描述】:

我正在使用 XGBClassifier 对不平衡的多类目标进行建模。我有几个问题:

First I would like to now where should I use the parameter weight on the instantion of the classifier or on the fit step of the pipeline?

Second question is how I calculate a weights. I assume that the sum of the array should be 1.

Third: Is there any order of the weight array that maps the diferent label classes?

提前谢谢大家

【问题讨论】:

    标签: python scikit-learn xgboost


    【解决方案1】:

    第一个问题:

    我应该在哪里使用参数权重

    在XGBClassifier.fit() 中使用sample_weight

    xgb_clf = xgb.XGBClassifier()
    xgb_clf.fit(X, y, sample_weight=sample_weight)
    

    使用pipeline时:

    pipe = Pipeline([
        ('my_xgb_clf', xgb.XGBClassifier()),
    ])
    pipe.fit(X, y, my_xgb_clf__sample_weight=sample_weight)
    

    顺便说一句,sklearn 中的某些 API 不支持 sample_weight kwarg,例如 learning_curve。

    所以我只是这样做:

    import functools
    xgb_clf.fit = functools.partial(xgb_clf.fit, sample_weight=sample_weight)
    

    注意:您需要在网格搜索后再次修补 fit(),因为 GridSearchCV.best_estimator_ 不会是原始估算器。


    第二个问题:

    我如何计算权重。我假设数组的总和应该是 1。

    from sklearn.utils import compute_sample_weight
    sample_weight = compute_sample_weight('balanced', y_train)
    

    这模拟了 sklearn 中的class_weight='balanced'。

    注意:

    • 数组的总和不是 1。你可以对其进行归一化,但我认为 分数结果会有所不同。
    • 这不等于class_weight='balanced_subsample' 我找不到模拟这个的方法。

    关于第三个问题:

    有什么顺序吗……

    对不起,我不明白你的意思......

    也许您想要xgb_clf.classes_ 的订单? 您可以在致电xgb_clf.fit 后访问它。 或者直接使用np.unique(y_train)。

    【讨论】:

    • 关于第一个问题的答案:当我使用pipe.fit(X, y, my_xgb_clf__sample_weight=sample_weight) 时,我的内核死了……当我使用xgb_clf.fit = functools.partial(xgb_clf.fit, sample_weight=sample_weight) 时,出现以下错误:NotFittedError: This ColumnTransformer instance is not fitted yet. Call 'fit' with appropriate arguments before using this method.
    • @Hugo 这个错误是针对ColumnTransformer的。 ColumnTransformer.transform() 在 ColumnTransformer.fit() 之前的某个地方被调用。你是怎么用的?
    • preprocessor = ColumnTransformer( transformers=[ ('num', numeric_transformer, numeric_features), ('cat', categorical_transformer, categorical_features), ]) clf = Pipeline(steps=[ ('preprocessor', preprocessor), ('classifier', XGBClassifier()) ])
    • @Hugo This 示例在我的机器(Python 3.7 和 sklearn 0.21.2)上运行良好,将最后一行更改为 clf.fit(X_train, y_train, classifier__sample_weight=sample_weight)。我无法重现错误。
    • 谢谢。可能是另一种错误。我正在尝试查找它是否与 Scikit-Learn 相关
    猜你喜欢
    • 2017-04-19
    • 2013-12-26
    • 2016-06-19
    • 2021-08-24
    • 2021-06-28
    • 2020-09-04
    • 2023-03-17
    • 2018-01-30
    • 1970-01-01
    相关资源
    最近更新 更多