【问题标题】:Use of scikit Random Forest sample_weightsscikit 随机森林 sample_weights 的使用
【发布时间】:2014-02-20 12:28:18
【问题描述】:

我一直在试图弄清楚 scikit 的 Random Forest sample_weight 使用情况,但我无法解释我看到的一些结果。从根本上说,我需要它来平衡分类问题和不平衡的类。

特别是,我期望如果我使用全为 1 的 sample_weights 数组,我会得到与 w sample_weights=None 相同的结果。此外,我希望任何具有相同权重的数组(即全 1、全 10 或全 0.8 ...)都将提供相同的结果。在这种情况下,也许我对权重的直觉是错误的。

代码如下:

import numpy as np
from sklearn import ensemble,metrics, cross_validation, datasets

#create a synthetic dataset with unbalanced classes
X,y = datasets.make_classification(
n_samples=10000, 
n_features=20, 
n_informative=4, 
n_redundant=2, 
n_repeated=0, 
n_classes=2, 
n_clusters_per_class=2, 
weights=[0.9],
flip_y=0.01,
class_sep=1.0, 
hypercube=True, 
shift=0.0, 
scale=1.0, 
shuffle=True, 
random_state=0)

model = ensemble.RandomForestClassifier()

w0=1 #weight associated to 0's
w1=1 #weight associated to 1's

#I should split train and validation but for the sake of understanding sample_weights I'll skip this step
model.fit(X, y,sample_weight=np.array([w0 if r==0 else w1 for r in y]))    
preds = model.predict(X)
probas = model.predict_proba(X)
ACC = metrics.accuracy_score(y,preds)
precision, recall, thresholds = metrics.precision_recall_curve(y, probas[:, 1])
fpr, tpr, thresholds = metrics.roc_curve(y, probas[:, 1])
ROC = metrics.auc(fpr, tpr)
cm = metrics.confusion_matrix(y,preds)
print "ACCURACY:", ACC
print "ROC:", ROC
print "F1 Score:", metrics.f1_score(y,preds)
print "TP:", cm[1,1], cm[1,1]/(cm.sum()+0.0)
print "FP:", cm[0,1], cm[0,1]/(cm.sum()+0.0)
print "Precision:", cm[1,1]/(cm[1,1]+cm[0,1]*1.1)
print "Recall:", cm[1,1]/(cm[1,1]+cm[1,0]*1.1)
  • 使用w0=w1=1,例如,我得到F1=0.9456
  • 使用w0=w1=10,例如,我得到F1=0.9569
  • sample_weights=None 我得到F1=0.9474

【问题讨论】:

    标签: python scikit-learn random-forest


    【解决方案1】:

    对于随机森林算法,顾名思义,它具有某种“随机性”。

    您获得不同的 F1 分数,因为随机森林算法 (RFA) 使用您的数据子集来生成决策树,然后对所有树进行平均。因此,对于您每次跑步的 F1 分数都相似(但不相同),我并不感到惊讶。

    我之前尝试过平衡重物。您可能想尝试根据总体中每个类别的大小来平衡权重。例如,如果你有两个这样的类:

    Class A: 5 members
    Class B: 2 members
    

    您可能希望通过为 Class A 的每个成员分配 2/7 和为 Class B 的每个成员分配 5/7 来平衡权重。不过,这只是一个作为起点的想法。您对课程的权重将取决于您遇到的问题。

    【讨论】:

    • 一旦我为随机森林设置了种子,事情就开始变得有意义了。
    • 如果你想设置类权重,你应该在RandomForestClassifier初始化时使用class_weight可选参数。 scikit-learn.org/stable/modules/generated/…
    猜你喜欢
    • 2017-12-10
    • 2015-03-28
    • 2015-09-28
    • 2013-04-26
    • 2014-11-12
    • 2015-04-16
    • 2015-12-01
    • 2015-09-16
    • 2017-01-05
    相关资源
    最近更新 更多