【问题标题】:How to set `class_weight` in version 0.14 of sklearn?如何在 sklearn 0.14 版中设置“class_weight”?
【发布时间】:2016-03-27 02:17:44
【问题描述】:

我知道sklearn.ensemble.RandomForestClassifier的0.17版本中有一个class_weight参数。

我无法安装 0.17。如何在 0.14 版本中访问此参数?

或者,是否有另一种方法来处理 RandomForestClassifier 中的不平衡标签 (y values)?我有一个负数多于正数的二元分类器,这自然会扭曲结果,所以我想设置类权重来抵消这一点。

【问题讨论】:

    标签: scikit-learn version random-forest sklearn-pandas


    【解决方案1】:

    看源码,貌似0.14中没有实现。或者,您可以对负类进行下采样以获得平衡:

    import numpy as np
    
    # Fake class labels skewed toward negative class:
    real_p = 0.01 # true probability of class 1 (unknown in real cases)
    Y = (np.random.rand(10000) < real_p).astype(np.int)
    
    # Use average number of pos examples as an estimate of P(Y=1)
    p = (Y==1).mean()
    
    print "Label balance: %.3f pos / %.3f neg" % (p,1-p)
    
    # Resample the training set:
    inds = np.zeros(Y.shape[0], dtype=np.bool)
    inds[np.where(Y==1)] = True
    inds[np.where(Y==0)] = np.random.rand((Y==0).sum()) < p
    
    resample_p = (Y[inds]==1).mean()
    
    print "After resampling:"
    print "Label balance: %.3f pos / %.3f neg" % (resample_p,1-resample_p)
    

    输出:

    Label balance: 0.013 pos / 0.987 neg
    After resampling:
    Label balance: 0.531 pos / 0.469 neg
    

    请注意,这是对负类进行下采样的一种非常简单的方法。更好的方法可能是将下采样或加权集成到学习方案中 - 也许是提升或级联方法?

    【讨论】:

    • 我在想也许更简单的方法是使用sample_weight 参数。通过检查我的训练样本,我可以找出每个样本属于哪个类,并创建一个维度为n_samples x 1 的向量来适当地加权每个样本。这行得通吗?
    • 我在这里提出这个问题:stackoverflow.com/questions/34389624/…
    • 像我上面展示的那样下采样是您可以采取的最直接的方法。我建议先试一试。我不相信缩放特征向量会像你建议的那样工作。您真正需要做的是增加算法用于进行节点拆分的杂质函数。如果您真的想深入了解这一点,您需要对 CART 和杂质测量有一个很好的了解,您可以在 Brieman 的 CART 教科书上(或在网上找到)。
    • 顺便说一下,this is the paper cited in sklearn 的类权重方案基于DecisionTreeClassifier
    • @Hunle 对不起 - 我误读了您的评论,因为它仍然指的是 class_weight。您使用sample_weight 是正确的。
    猜你喜欢
    • 2018-09-06
    • 1970-01-01
    • 2021-12-28
    • 2014-09-08
    • 2019-10-06
    • 1970-01-01
    • 2021-02-01
    • 2019-03-08
    • 1970-01-01
    相关资源
    最近更新 更多