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语言1 小时前
Qt—信号和槽
开发语言·qt
geovindu1 小时前
go:Decorator Pattern
开发语言·设计模式·golang·装饰器模式
故事和你912 小时前
洛谷-算法2-1-前缀和、差分与离散化1
开发语言·数据结构·c++·算法·深度优先·动态规划·图论
励志的小陈8 小时前
贪吃蛇(C语言实现,API)
c语言·开发语言
kishu_iOS&AI8 小时前
深度学习 —— 损失函数
人工智能·pytorch·python·深度学习·线性回归
Makoto_Kimur8 小时前
java开发面试-AI Coding速成
java·开发语言
好运的阿财8 小时前
OpenClaw工具拆解之canvas+message
人工智能·python·ai编程·openclaw·openclaw工具
laowangpython8 小时前
Gurobi求解器Matlab安装配置教程
开发语言·其他·matlab
wengqidaifeng8 小时前
python启航:1.基础语法知识
开发语言·python
观北海8 小时前
Windows 平台 Python 极简 ORB-SLAM3 Demo,从零实现实时视觉定位
开发语言·python·动态规划