使用scikit的随机森林sample_weights功能

8
我一直在尝试理解scikit的随机森林的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
1个回答

7
使用随机森林算法时,正如其名称所示,它具有一定的“随机性”。由于随机森林算法(RFA)使用数据子集生成决策树,然后对所有树进行平均,因此您会得到不同的F1分数。因此,我并不惊讶您每次运行时得到类似但非完全相同的F1分数。 我之前尝试过权重平衡。您可以尝试通过人口中每个类的大小来平衡权重。例如,如果您有两个这样的类:
Class A: 5 members
Class B: 2 members

您可能希望通过为 A类的成员分配2/7,为 B类的成员分配5/7来平衡权重。这只是一个起点的想法,您如何给不同的类别分配权重将取决于您面对的问题。


3
一旦我为随机森林设置了种子,事情开始变得有意义起来。 - ADJ
2
如果您想设置类别权重,只需在RandomForestClassifier初始化中使用 class_weight 可选参数即可。请参考以下链接:http://scikit-learn.org/stable/modules/generated/sklearn.ensemble.RandomForestClassifier.html - makansij

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接