如何得到决策树每个叶节点的类别计数python代码
时间: 2023-06-08 21:04:24 浏览: 63
以下是获取决策树每个叶节点类别计数的Python代码示例:
```python
from sklearn.datasets import load_iris
from sklearn.tree import DecisionTreeClassifier, export_graphviz
# 加载鸢尾花数据集
iris = load_iris()
# 构建决策树模型
clf = DecisionTreeClassifier()
clf.fit(iris.data, iris.target)
# 导出决策树结构到dot文件中
export_graphviz(clf, out_file='tree.dot', feature_names=iris.feature_names)
# 打开tree.dot文件,找到每个叶节点的编号
# 计算每个叶节点每个类别的样本数量
n_nodes = clf.tree_.node_count
node_indicator = clf.predict(iris.data).astype(int)
counts = {i: [0, 0, 0] for i in range(n_nodes)}
for i in range(len(node_indicator)):
node = node_indicator[i]
count = counts[node]
count[iris.target[i]] += 1
for node in range(n_nodes):
if clf.tree_.children_left[node] == -1:
count = counts[node]
print(f"Node {node}: {count}")
```
注意:此代码仅供学习参考,实际使用时需要根据具体数据集和决策树模型进行修改。
相关推荐
![py](https://img-home.csdnimg.cn/images/20210720083646.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![py](https://img-home.csdnimg.cn/images/20210720083646.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)