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

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

相关推荐
放下华子我只抽RuiKe5几秒前
机器学习核心算法全景指南
人工智能·python·深度学习·算法·机器学习·机器人·交互
加密狗复制模拟2 分钟前
软件加密狗中时间限制机制的破解
开发语言·网络·安全·php·软件工程·个人开发
setmoon2144 分钟前
C++中的装饰器模式高级应用
开发语言·c++·算法
m0_528174455 分钟前
C++中的装饰器模式实战
开发语言·c++·算法
阿贵---7 分钟前
实时信号处理库
开发语言·c++·算法
爱炸薯条的小朋友9 分钟前
C#使用反射,特性,表达式树仿写AutoMapper
开发语言·c#
白小筠10 分钟前
# 决策树
算法·决策树·机器学习
快乐柠檬不快乐11 分钟前
C++中的享元模式高级应用
开发语言·c++·算法
时寒的笔记12 分钟前
逆向入门1整理2025.3.18
javascript·python
oem11013 分钟前
C++与Docker集成开发
开发语言·c++·算法