python绘制决策树

python 复制代码
from sklearn.datasets import load_iris
from sklearn.tree import DecisionTreeClassifier 
from sklearn.model_selection import train_test_split
from sklearn.tree import export_graphviz
from IPython.display import Image  
import matplotlib.pyplot as plt
import pydotplus

# 1.定义X和y
X = df_churn.iloc[:, :-1]
y = df_churn.Status


# 2. 建立决策树模型
dt_model = DecisionTreeClassifier(max_depth=30, min_samples_split=50, min_samples_leaf=25, 
                                  max_leaf_nodes=100, class_weight='balanced', ccp_alpha=0.0001)
# Fit model to training data
dt_model.fit(X_train, y_train)

# 3. 决策树的可视化
tmp_dot_file = 'decision_tree_tmp.dot'
export_graphviz(dt_model, out_file=tmp_dot_file,filled=True,feature_names=X.columns, class_names=list(set(y)),impurity=False)
with open(tmp_dot_file) as f:
    dot_graph = f.read()
graph = pydotplus.graph_from_dot_data(dot_graph)
graph.write_pdf('example.pdf')    #保存图像为pdf格式
Image(graph.create_png())   #绘制图像为png格式

就可以得到这样的结果啦:

相关推荐
小糯米6012 分钟前
C++顺序表和vector
开发语言·c++·算法
froginwe118 分钟前
JavaScript 函数调用
开发语言
阔皮大师12 分钟前
INote轻量文本编辑器
java·javascript·python·c#
独望漫天星辰12 分钟前
C++ 多态深度解析:从语法规则到底层实现(附实战验证代码)
开发语言·c++
小法师爱分享16 分钟前
StickyNotes,简单便签超实用
java·python
深蓝电商API16 分钟前
处理字体反爬:woff字体文件解析实战
爬虫·python
开源技术18 分钟前
Claude Opus 4.6 发布,100万上下文窗口,越贵越好用
人工智能·python
张3蜂30 分钟前
深入理解 Python 的 frozenset:为什么要有“不可变集合”?
前端·python·spring
无小道30 分钟前
Qt——事件简单介绍
开发语言·前端·qt
devmoon35 分钟前
在 Paseo 测试网上获取 Coretime:On-demand 与 Bulk 的完整实操指南
开发语言·web3·区块链·测试用例·智能合约·solidity