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格式

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

相关推荐
itwangyang5208 分钟前
AIDD药物筛选与设计详细方法
人工智能·python
悟能不能悟15 分钟前
JAVA 对象转为二级制流,再转化为base64
java·开发语言
NiceAsiv20 分钟前
VSCode之打开python终端 取消conda activate的powershell弹窗
vscode·python·conda
蔚说31 分钟前
is 与 == 的区别 python
python
cnxy18834 分钟前
围棋对弈Python程序开发完整指南:步骤3 - 气(Liberties)的计算算法设计
python·算法·深度优先
进击的前栈1 小时前
Flutter跨平台网络图片缓存库cached_network_image鸿蒙化适配指导手册
开发语言·网络·rust
叶子2024221 小时前
骨架点排序计算
python
老华带你飞1 小时前
房屋租赁管理系统|基于java+ vue房屋租赁管理系统(源码+数据库+文档)
java·开发语言·前端·数据库·vue.js·spring boot·后端
AC赳赳老秦1 小时前
行业数据 benchmark 对比:DeepSeek上传数据生成竞品差距分析报告
开发语言·网络·人工智能·python·matplotlib·涛思数据·deepseek
小鸡吃米…1 小时前
带Python的人工智能——深度学习
人工智能·python·深度学习