gpt4 book ai didi

python - sklearn RandomForestRegressor 显示的树值中的差异

转载 作者:行者123 更新时间:2023-12-03 16:32:39 25 4
gpt4 key购买 nike

在使用 RandomForestRegressor 时,我注意到一些奇怪的事情。为了说明问题,这里有一个小例子。我在测试数据集上应用了 RandomForestRegressor 并绘制了森林中第一棵树的图。这给了我以下输出:

Root_node: 
mse=8.64
samples=2
value=20.4

Left_leaf:
mse=0
samples=1
value=24

Right_leaf:
mse=0
samples=1
value=18
首先,我希望根节点的值为 (24+18)/2=21 .但不知何故,它是 20.4。
但是,即使这个值是正确的,我如何获得 8.64 的 mse?
从我的角度来看,它应该是: 1/2[(24-20.4)^2+(18-20.4)^2]=9.36 (假设根值20.4是正确的)
我的解决方案是: 1/2[(24-21)^2+(18-21)^2]=9 .如果我只使用 DecisionTreeRegressor,这也是我得到的结果。
RandomForestRegressor 的实现有什么问题还是我完全错了?
这是我的可重现代码:
import pandas as pd
from sklearn import tree
from sklearn.ensemble import RandomForestRegressor
import graphviz

# create example dataset
data = {'AGE': [91, 42, 29, 94, 85], 'TAX': [384, 223, 280, 666, 384], 'Y': [19, 21, 24, 13, 18]}
df = pd.DataFrame(data=data)
x = df[['AGE','TAX']]
y = df[['Y']]

rf_reg = RandomForestRegressor(max_depth=2, random_state=1)
rf_reg.fit(x,y)

# plot a single tree of forest
dot_data = tree.export_graphviz(rf_reg.estimators_[0], out_file=None, feature_names=x.columns)
graph = graphviz.Source(dot_data)
graph
和输出图:
enter image description here

最佳答案

tl;博士
这是由于 引导抽样 .
详细 :
使用默认设置 bootstrap=True , RF 将在构建单个树时使用 bootstrap 采样;引自交叉验证线程 Number of Samples per-Tree in a Random Forest :

If bootstrap=True, then for each tree, N samples are drawn randomly with replacement from the training set and the tree is built on this new version of the training data. This introduces randomness in the training procedure since trees will each be trained on slightly different training sets. In expectation, drawing N samples with replacement from a dataset of size N will select ~2/3 unique samples from the original set.


“有替换”意味着某些样本可能会被多次选择,而其他样本将被排除在外,选择的样本总数仍然等于原始数据集的样本数(此处为 5)。
您显示的树中实际发生的情况是,尽管 Graphviz 显示 samples=2 ,这应该理解为唯一样本的数量;共有 5 个( bootstrap )样本 在根节点中:样本的 2 个副本,带有 y=24和 3 份带有 y=18 的副本(回想一下,根据引导抽样过程的定义,这里的根节点必须包含 5 个样本,不多也不少)。
现在显示的值相加:
# value:
(2*24 + 3*18)/5
# 20.4

# mse:
(2*(24-20.4)**2 + 3*(18-20.4)**2)/5
# 8.64
显然似乎有一些设计选择,无论是在 Graphviz 可视化中还是在底层 DecisionTreeRegressor 中。 ,所以只有 的数量唯一样本被存储/显示,这可能(也可能不是)是打开 Github 问题的一个原因,但这就是目前的情况(说实话,我不确定我自己是否想要实际总数此处显示的样本,包括由于引导抽样而产生的重复项)。

关于python - sklearn RandomForestRegressor 显示的树值中的差异,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63920980/

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