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

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

相关推荐
百***92023 分钟前
java进阶1——JVM
java·开发语言·jvm
蓝桉~MLGT10 分钟前
Python学习历程——Python面向对象编程详解
开发语言·python·学习
Evand J11 分钟前
【MATLAB例程】2雷达二维目标跟踪滤波系统-UKF(无迹卡尔曼滤波)实现,目标匀速运动模型(带扰动)。附代码下载链接
开发语言·matlab·目标跟踪·滤波·卡尔曼滤波
larance14 分钟前
Python 中的 *args 和 **kwargs
开发语言·python
Easonmax17 分钟前
用 Rust 打造可复现的 ASCII 艺术渲染器:从像素到字符的完整工程实践
开发语言·后端·rust
lsx20240622 分钟前
Rust 宏:深入理解与高效使用
开发语言
百锦再22 分钟前
选择Rust的理由:从内存管理到抛弃抽象
android·java·开发语言·后端·python·rust·go
yaoxin52112323 分钟前
238. Java 集合 - 使用 ListIterator 遍历 List 元素
java·python·list
小羊失眠啦.25 分钟前
深入解析Rust的所有权系统:告别空指针和数据竞争
开发语言·后端·rust
Dxxyyyy26 分钟前
零基础学JAVA--Day32(ArrayList底层+Vector+LinkedList)
java·开发语言