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

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

相关推荐
谅望者21 分钟前
数据分析笔记07:Python编程语言介绍
大数据·数据库·笔记·python·数据挖掘·数据分析
5***790024 分钟前
Swift进阶
开发语言·ios·swift
独自破碎E34 分钟前
从括号匹配到字符串解码:递归思想的巧妙应用
android·java·开发语言
Charles_go41 分钟前
C#13、什么是部分类
开发语言·c#
Geo_V1 小时前
LangChain Memory 使用示例
人工智能·python·chatgpt·langchain·openai·大模型应用·llm 开发
忧郁的橙子.1 小时前
二、Rabbit MQ 高级
java·开发语言
谢尔登1 小时前
原型理解从入门到精通
开发语言·javascript·原型模式
小呀小萝卜儿1 小时前
2025-11-15 学习记录--Python-LSTM模型定义(PyTorch)
python·学习·lstm
百锦再2 小时前
第15章 并发编程
android·java·开发语言·python·rust·django·go
laufing2 小时前
pyinstaller 介绍
python·构建打包