python - 如何手动创建 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')]),
}
但是我并不真正理解这些参数的含义,而且无论如何我一开始都看不到如何用这种状态初始化树。
解决方案
经过数小时尝试手动更改节点。我找到了解决方案。的确,你是对的。通过使用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'。
推荐阅读
- pandas - Pandas - 从键中提取值
- win32com - AttributeError:模块“pythoncom”没有属性“Coinitialize”
- php - 将邮政编码运输字段更改为 Woocommerce 中的下拉列表
- azure-cosmosdb - 无法创建 documentdb 数据库
- security - IE 中的证书吊销列表检查失败 - 服务器端是否有修复?
- recommendation-engine - 组合多臂老虎机(CMAB)和“尝试和统计”有什么区别?
- android - 如何使用 Appium 检测按钮是否在屏幕底部而不是在屏幕顶部?
- sql - 找到三个连续可用的座位号
- python - 具有多列的文本文件中的最大值
- spring-cloud-stream - SpringBoot CloudStream (Kafka) 和 JPA