gpt4 book ai didi

python - 如何在 Scikit-Learn 的随机森林分类器中设置子样本大小?特别是对于不平衡数据

转载 作者:太空狗 更新时间:2023-10-29 22:24:47 28 4
gpt4 key购买 nike

目前,我正在 Sklearn 中为我的不平衡数据实现 RandomForestClassifier。我不太清楚 RF 在 Sklearn 中究竟是如何工作的。以下是我的担忧:

  1. 根据文档,似乎没有办法为每个树学习器设置子样本大小(即小于原始数据大小)。但实际上,在随机森林算法中,我们需要得到每棵树的样本子集和特征子集。我不确定我们能否通过 Sklearn 实现这一目标?如果是,如何?

下面是Sklearn中对RandomForestClassifier的描述。

“随机森林是一种元估计器,它在数据集的各种子样本上拟合多个决策树分类器,并使用平均来提高预测准确性和控制过度拟合。子样本大小为始终与原始输入样本大小相同,但如果 bootstrap=True(默认),则抽取样本并进行替换。”

这里我之前发现了一个类似的问题。但这个问题的答案并不多。

How can SciKit-Learn Random Forest sub sample size may be equal to original training data size?

  1. 对于不平衡数据,如果我们可以通过 Sklearn 提取子样本(即解决上面的问题 #1),我们可以做平衡随机森林吗?即对于每个树学习器,它将从人口较少的类别中选取一个子集,并从人口较多的类别中选取相同数量的样本,以构成两个类别均等分布的整个训练集。然后重复该过程一批处理(即树的数量)。

谢谢!程

最佳答案

没有明显的方法,但您可以破解 sklearn.ensemble.forest 中的采样方法。

(更新于 2021-04-23,因为我发现 sklearn 重构了代码)

通过使用 set_rf_samples(n),您可以强制树对 n 行进行子采样,并调用 reset_rf_samples() 对整个数据集进行采样。

版本 < 0.22.0

from sklearn.ensemble import forest

def set_rf_samples(n):
""" Changes Scikit learn's random forests to give each tree a random sample of
n random rows.
"""
forest._generate_sample_indices = (lambda rs, n_samples:
forest.check_random_state(rs).randint(0, n_samples, n))

def reset_rf_samples():
""" Undoes the changes produced by set_rf_samples.
"""
forest._generate_sample_indices = (lambda rs, n_samples:
forest.check_random_state(rs).randint(0, n_samples, n_samples))

版本 >=0.22.0

现在有一个参数可用https://scikit-learn.org/stable/modules/generated/sklearn.ensemble.RandomForestRegressor.html

max_samples: int or float, default=None

If bootstrap is True, the number of samples to draw from X to train each base estimator.

If None (default), then draw X.shape[0] samples.

If int, then draw max_samples samples.

If float, then draw max_samples * X.shape[0] samples. Thus, max_samples should be in the interval (0, 1).

引用:fast.ai机器学习教程

关于python - 如何在 Scikit-Learn 的随机森林分类器中设置子样本大小?特别是对于不平衡数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44955555/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com