XGboost Python-分类器类权重选项?

Fic*_*ion 6 scikit-learn xgboost

有没有办法为xgboost分类器设置不同的类权重?例如,在sklearn RandomForestClassifier中,这是通过“ class_weight”参数完成的。

epa*_*aro 7

使用sklearn包装纸时,有一个重量参数。

例:

import xgboost as xgb
exgb_classifier = xgboost.XGBClassifier()
exgb_classifier.fit(X, y, sample_weight=sample_weights_data)
Run Code Online (Sandbox Code Playgroud)

其中参数shld为数组,长度N,等于目标长度


Pra*_*mit 7

我最近遇到了这个问题,所以想到会留下我尝试过的解决方案

from xgboost import XGBClassifier

# manually handling imbalance. Below is same as computing float(18501)/392318 
on the trainig dataset.
# We are going to inversely assign the weights
weight_ratio = float(len(y_train[y_train == 0]))/float(len(y_train[y_train == 
1]))
w_array = np.array([1]*y_train.shape[0])
w_array[y_train==1] = weight_ratio
w_array[y_train==0] = 1- weight_ratio

xgc = XGBClassifier()
xgc.fit(x_df_i_p_filtered, y_train, sample_weight=w_array)
Run Code Online (Sandbox Code Playgroud)

不知道为什么,但结果非常令人失望。希望这可以帮助某人。

[参考链接] https://www.programcreek.com/python/example/99824/xgboost.XGBClassifier

  • 应该是 w1 = np.array([1.0] * y_train.shape[0]) ,将 numpy 数组的 dtype 初始化为浮点数。否则,以下语句将生成一个包含全零的 numpy 数组。 (2认同)

Fir*_*ane 5

对于 sklearn 版本 < 0.19

只需为您的火车数据的每个条目分配其类别权重。首先使用class_weight.compute_class_weightsklearn获取类权重,然后为训练数据的每一行分配适当的权重。

我在这里假设火车数据有class包含班级编号的列。我还假设nb_classes有从 1 到nb_classes.

from sklearn.utils import class_weight
classes_weights = list(class_weight.compute_class_weight('balanced',
                                             np.unique(train_df['class']),
                                             train_df['class']))

weights = np.ones(y_train.shape[0], dtype = 'float')
for i, val in enumerate(y_train):
    weights[i] = classes_weights[val-1]

xgb_classifier.fit(X, y, sample_weight=weights)
Run Code Online (Sandbox Code Playgroud)

更新 sklearn 版本 >= 0.19

有更简单的解决方案

from sklearn.utils import class_weight
classes_weights = class_weight.compute_sample_weight(
    class_weight='balanced',
    y=train_df['class']
)

xgb_classifier.fit(X, y, sample_weight=classes_weights)
Run Code Online (Sandbox Code Playgroud)