首页 > 解决方案 > 如何手动创建 scikit-learn 树?

问题描述

为了测试一些代码,我希望能够手动创建一个 sklearn.tree._tree.Tree,而不是通过拟合一些数据。

具体而言,假设我想要一棵树,它将实线中的点分类为区间(-infinity,5],(5,6] 或(6,infinity)。我想要树形

----0----
|        |
|     ---2---
|     |      |
1     3      4

其中节点 0 在 5 处分割实线,节点 2 在 6 处分割实线。

这该怎么做?我看到树有一个__setstate__方法,看着它的输出__getstate__看起来我需要类似的东西

state = {
        'n_features_': 1,
        'max_depth': 2,
        'node_count': 5,
        'nodes': np.array([(1 ,   2,  0,  5., 0.375, 3, 3.),
                           (-1,  -1,  0, -2., 0.   , 1, 1.),
                           (3 ,   4,  0,  6., 0.,  , 2, 2.),
                           (-1,  -1,  0, -2., 0.,  , 1, 1.),
                           (-1,  -1,  0, -2., 0.,  , 1, 1.),
                           ],
                          dtype=[('left_child', '<i8'), ('right_child', '<i8'), ('feature', '<i8'),('threshold', '<f8'), ('impurity', '<f8'), ('n_node_samples', '<i8'), ('weighted_n_node_samples', '<f8')]),
}

但是我并不真正理解这些参数的含义,而且无论如何我一开始都看不到如何用这种状态初始化树。

标签: pythonscikit-learndecision-tree

解决方案


经过数小时尝试手动更改节点。我找到了解决方案。的确,你是对的。通过使用setstate,您可以进行树自定义。“节点”键必须如下:

  • numpy 元组数组
  • 每个元组必须如下所示: (left_child[i], right_child[i], feature[i], threshold[i], impurity[i], n_node_samples[i], weighted_n_node_samples[i])

-1(左/右孩子)和 -2(特征)代表叶子。

在训练分类器时,您将拥有另一个键:'value'。


推荐阅读