python - 在 sklearn 中使用 RandomForestClassifier 进行不平衡分类

标签 python machine-learning classification scikit-learn random-forest

我有一个类不平衡的数据集。类是“1”或“0”,其中“1”:“0”类的比率为 5:1。你如何计算每个类的预测误差和相应的重新平衡权重在带有随机森林的 sklearn 中,有点像下面的链接:http://www.stat.berkeley.edu/~breiman/RandomForests/cc_home.htm#balance

最佳答案

您可以将样本权重参数传递给随机森林 fit method

sample_weight : array-like, shape = [n_samples] or None

Sample weights. If None, then samples are equally weighted. Splits that would create child nodes with net zero or negative weight are ignored while searching for a split in each node. In the case of classification, splits are also ignored if they would result in any single class carrying a negative weight in either child node.

在旧版本中,有一个 preprocessing.balance_weights 方法可以为给定的样本生成平衡权重,从而使类变得均匀分布。它仍然存在,在内部但仍然可用preprocessing._weights模块,但已弃用,将在未来版本中删除。不知 Prop 体原因。

更新

一些澄清,因为你似乎很困惑。 sample_weight 的用法很简单,只要您记住它的目的是平衡训练数据集中的目标类。也就是说,如果您将 X 作为观察值并将 y 作为类(标签),那么 len(X) == len(y) == len(sample_wight ),并且 sample witght 一维数组的每个元素表示相应 (observation, label) 对的权重。对于您的情况,如果 1 类被表示为 0 类的 5 次,并且您平衡了类分布,您可以使用简单的

sample_weight = np.array([5 if i == 0 else 1 for i in y])

5 的权重分配给所有 0 实例,将 1 的权重分配给所有 1 实例。有关更巧妙的 balance_weights 权重评估函数,请参见上面的链接。

关于python - 在 sklearn 中使用 RandomForestClassifier 进行不平衡分类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20082674/

相关文章:

java - Weka 分类器的参数

python - 重新加载功能无法删除已删除的变量

python - 从数据框中删除空白列不起作用,Python 3.6

python - 如何使用纬度和经度坐标进行分组?

python - 从 Python 中的 ONNX 模型获取预测

python - 如何对张量的每一行/列使用 tf.unique_with_counts

maven - 根据配置文件更改部署的 Artifact 名称

python - 基本列表检查器

python - 我的重力模拟有什么问题?

machine-learning - 为什么不能从宏精度和召回率计算宏 F1 度量?