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

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

相关推荐
小白不白111几秒前
C# WinForm 与 VP 二次开发
开发语言·c#
秦jh_6 分钟前
【LangChain核心组件】少样本提示(示例选择器)
人工智能·python·langchain
程序猿乐锅7 分钟前
【JAVASE | 第十七篇】Java 网络通信
java·开发语言
资深流水灯工程师13 分钟前
PyCharm 增强插件完整安装与配置指南(PySide6 开发专用)
ide·python·pycharm
飞舞哲18 分钟前
三维点云最小二乘拟合MATLAB程序
开发语言·算法·matlab
有点。19 分钟前
C++(贪心算法二)
开发语言·c++·贪心算法
meilindehuzi_a19 分钟前
透视 V8 底部:从物理内存到函数式哲学,重新解构 JavaScript 数组
开发语言·javascript·ecmascript
jllllyuz20 分钟前
HVDC 高压直流输电系统 MATLAB/Simulink 仿真全集
开发语言·matlab
我命由我1234520 分钟前
Windows 操作系统 - Windows 查看防火墙是否开启、Windows 查看防火墙放行端口
java·运维·开发语言·windows·java-ee·操作系统·运维开发
Kobebryant-Manba20 分钟前
学习模型构造
python·深度学习·学习