gpt4 book ai didi

class - 尝试通过 scikit-learn 中的 sample_weight 平衡我的数据集

转载 作者:行者123 更新时间:2023-12-01 02:07:03 27 4
gpt4 key购买 nike

我使用 RandomForest 进行分类,我得到了一个不平衡的数据集,如:5830-no, 1006-yes。我尝试用 class_weight 和 sample_weight 平衡我的数据集,但我不能。

我的代码是:

X_train,X_test,y_train,y_test = train_test_split(arrX,y,test_size=0.25)
cw='auto'
clf=RandomForestClassifier(class_weight=cw)
param_grid = { 'n_estimators': [10,50,100,200,300],'max_features': ['auto', 'sqrt', 'log2']}
sw = np.array([1 if i == 0 else 8 for i in y_train])
CV_clf = GridSearchCV(estimator=clf, param_grid=param_grid, cv= 10,fit_params={'sample_weight': sw})

但是在使用 class_weight 和 sample_weight 时,我的 TPR、FPR、ROC 比率没有得到任何改善。

为什么?我做错了什么吗?

尽管如此,如果我使用名为 balance_subsample 的函数,我的比率会得到很大的改善:
def balanced_subsample(x,y,subsample_size):

class_xs = []
min_elems = None

for yi in np.unique(y):
elems = x[(y == yi)]
class_xs.append((yi, elems))
if min_elems == None or elems.shape[0] < min_elems:
min_elems = elems.shape[0]

use_elems = min_elems
if subsample_size < 1:
use_elems = int(min_elems*subsample_size)

xs = []
ys = []

for ci,this_xs in class_xs:
if len(this_xs) > use_elems:
np.random.shuffle(this_xs)

x_ = this_xs[:use_elems]
y_ = np.empty(use_elems)
y_.fill(ci)

xs.append(x_)
ys.append(y_)

xs = np.concatenate(xs)
ys = np.concatenate(ys)

return xs,ys

我的新代码是:
X_train_subsampled,y_train_subsampled=balanced_subsample(arrX,y,0.5)
X_train,X_test,y_train,y_test = train_test_split(X_train_subsampled,y_train_subsampled,test_size=0.25)
cw='auto'
clf=RandomForestClassifier(class_weight=cw)
param_grid = { 'n_estimators': [10,50,100,200,300],'max_features': ['auto', 'sqrt', 'log2']}
sw = np.array([1 if i == 0 else 8 for i in y_train])
CV_clf = GridSearchCV(estimator=clf, param_grid=param_grid, cv= 10,fit_params={'sample_weight': sw})

谢谢

最佳答案

这还不是一个完整的答案,但希望它会帮助到达那里。

首先是一些一般性评论:

  • 要调试此类问题,确定性行为通常很有用。您可以通过 random_state归因于 RandomForestClassifier以及各种 scikit-learn 对象,它们具有固有的随机性,可以在每次运行时获得相同的结果。您还需要:
    import numpy as np
    np.random.seed()
    import random
    random.seed()

  • 为您 balanced_subsample函数在每次运行时都以相同的方式运行。
  • 不要在 n_estimators 上进行网格搜索:在随机森林中,更多的树总是更好。
  • 请注意 sample_weightclass_weight有一个类似的目标:实际样本权重为 sample_weight * 从 class_weight 推断出的权重 .

  • 你能不能试试:
  • 在您的 balanced_subsample 中使用 subsample=1功能。除非有特殊原因不这样做,否则我们最好比较相似数量的样本的结果。
  • 将您的子抽样策略与 class_weight 一起使用和 sample_weight都设置为无。

  • 编辑 : 再次阅读您的评论,我意识到您的结果并不那么令人惊讶!
    您获得更好(更高)的 TPR,但获得更差(更高)的 FPR .
    这只是意味着您的分类器努力使第 1 类的样本正确,从而产生更多的误报(当然,同时也获得更多正确的样本!)。
    如果您继续在同一方向增加类/样本权重,您将看到这种趋势继续下去。

    关于class - 尝试通过 scikit-learn 中的 sample_weight 平衡我的数据集,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31696987/

    27 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com