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

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

相关推荐
Muyuan19982 分钟前
22.让 RAG Agent 更像真实产品:聊天页面优化、PDF 上传、知识库重建与检索片段展示
python·django·pdf·fastapi
冷雨夜中漫步9 分钟前
Claude Code源码分析——Claude Code Agent Loop 详细设计文档
java·开发语言·人工智能·ai
超龄编码人12 分钟前
Qt Widgets Designer QTabWidget无法添加布局
开发语言·qt
程序员-小李13 分钟前
uv 学习总结:从零到一掌握现代化 Python 工具链
python·学习·uv
直奔標竿15 分钟前
Java开发者AI转型第二十六课!Spring AI 个人知识库实战(五)——联网搜索增强实战
java·开发语言·人工智能·spring boot·后端·spring
Python大数据分析@20 分钟前
CLI一键采集,使用Python搭建TikTok电商爬虫Agent
开发语言·爬虫·python
研究点啥好呢26 分钟前
高德多模态算法工程师面试题精选:10道高频考题+答案解析
python·面试·llm·求职招聘·笔试·高德
测试员周周40 分钟前
【AI测试系统】第3篇:AI生成的测试用例太“水”?14年老兵:规则引擎+AI才是王炸组合
人工智能·python·测试
@小码农1 小时前
2026年3月Scratch图形化编程等级考试一级真题试卷
开发语言·数据结构·c++·算法
这儿有一堆花1 小时前
住宅代理(Residential Proxy)技术指南
开发语言·数据库·php