python - scikit随机森林sample_weights的使用

标签 python scikit-learn random-forest

我一直在尝试弄清楚 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

最佳答案

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

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

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

Class A: 5 members
Class B: 2 members

您可能希望通过为每个 Class A 的成员分配 2/7 和为每个 Class B 的成员分配 5/7 来平衡权重。不过,这只是一个起点。您如何为类(class)分配权重取决于您遇到的问题。

关于python - scikit随机森林sample_weights的使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21418606/

相关文章:

python - 如何实现请求的多线程或多处理

python - Sklearn GMM 给出偏移的高斯峰

python - 使用 R-Squared 评估随机森林性能

python - 在 PyCharm 中查找调用 Python 函数的位置

python - 从 .yaml 文件运行 python 命令

python - 类型错误 : fit() takes exactly 3 arguments (2 given) with sklearn and sklearn_pandas

python - 属性错误 : 'GMM' object has no attribute 'covariances_' || AttributeError: 'module' object has no attribute 'GaussianMixture'

r - 使用 step_naomit 进行预测并使用 tidymodels 保留 ID

用于分类的 R randomForest

python - 如何更改数据框中保存的数据的格式?