Skip to main content
 首页 » 编程设计

python之sklearn.tree.DecisionTreeRegressor : depth of tree is bigger than specified when max_leaf_nodes ! = 无

2024年11月24日11bluestorm

我目前正在研究一个预测问题,当我遇到以下问题时,我试图用 scikit-learns DecisionTreeRegressor 解决这个问题:

When fitting a tree specifying both parameters max_depth and max_leaf_nodes, the depth of the resulting tree is max_depth+1. When fitting a tree specifying only max_depth, the resulting tree has the correct depth.

这可能是 DecisionTreeRegressor 类 中的一个错误,还是我遗漏了一些关于回归树的常识?

我正在 windows 机器上工作,在 python 3.7 jupyter notebook 中。 Sklearn 版本为 0.20.3。 实际上,我在使用 RandomForestRegressor 时遇到了这个问题,但在 DecisionTreeRegressor 中发现了同样的问题。

我写了下面的简化示例,所以你可以自己试试。只需取消注释 max_leaf_nodes=10。

我还使用 graphviz 可视化了树,它实际上显示了不同深度的树。

import numpy as np 
from sklearn.tree import DecisionTreeRegressor 
 
X = np.random.rand(10,4) 
y = np.random.rand(10,1) 
 
 
tree = DecisionTreeRegressor(max_depth = 2, 
                             #max_leaf_nodes = 10  
                             ) 
tree.fit(X,y) 
 
print(tree.tree_.max_depth) 

感谢任何评论。

请您参考如下方法:

虽然没有记录,但如果未设置max_leaf_nodes,将使用DepthFirstTreeBuilder 来适应底层树对象;如果是,则使用 BestFirstTreeBuilder;这种差异导致生成不同深度的树。

这是一个特定于实现的细节,而不是因为决策树的特定特征。

顺便说一句,我会注意到叶节点的最大数量也限制了最大深度。