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

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

相关推荐
吴佳浩1 小时前
大模型量化部署终极指南:让700亿参数的AI跑进你的显卡
人工智能·python·gpu
diegoXie2 小时前
Python / R 向量顺序分割与跨步分割
开发语言·python·r语言
程序员小白条2 小时前
0经验如何找实习?
java·开发语言·数据结构·数据库·链表
七牛云行业应用2 小时前
解决OSError: No space left... 给DeepSeek Agent装上无限云硬盘
python·架构设计·七牛云·deepseek·agent开发
liulilittle2 小时前
C++ 浮点数封装。
linux·服务器·开发语言·前端·网络·数据库·c++
BoBoZz193 小时前
CutWithScalars根据标量利用vtkContourFilter得到等值线
python·vtk·图形渲染·图形处理
失散133 小时前
Python——1 概述
开发语言·python
萧鼎3 小时前
Python 图像哈希库 imagehash——从原理到实践
开发语言·python·哈希算法
qq_251533593 小时前
使用 Python 提取 MAC 地址
网络·python·macos
小小8程序员3 小时前
STL 库(C++ Standard Template Library)全面介绍
java·开发语言·c++