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

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

相关推荐
C嘎嘎嵌入式开发9 分钟前
(10)100天python从入门到拿捏《Python中的数据结构与自定义数据结构》
数据结构·python·算法
熬了夜的程序员10 分钟前
【LeetCode】69. x 的平方根
开发语言·算法·leetcode·职场和发展·动态规划
程序员杰哥11 分钟前
Pytest与Unittest测试框架对比
自动化测试·软件测试·python·测试工具·测试用例·excel·pytest
草莓熊Lotso27 分钟前
C++ 手写 List 容器实战:从双向链表原理到完整功能落地,附源码与测试验证
开发语言·c++·链表·list
无限进步_28 分钟前
【C语言】杨辉三角:数学之美与编程实现的完美结合
c语言·开发语言
Cg1362691597430 分钟前
封装的实现和定义
java·开发语言
wxin_VXbishe30 分钟前
基于SpringBoot的天天商城管理系统的设计与现-计算机毕业设计源码79506
java·c++·spring boot·python·spring·django·php
睿思达DBA_WGX31 分钟前
使用 python-docx 库操作 word 文档(3):读取word文档的内容
python·word
武子康35 分钟前
Java-146 深入浅出 MongoDB 数据插入、批量写入、BSON 格式与逻辑查询and or not操作指南
java·开发语言·数据库·sql·mongodb·性能优化·nosql
初圣魔门首席弟子38 分钟前
const string getWord() ;和 string getWord() const ;是一样的效果吗
开发语言·c++