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

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

相关推荐
深度学习lover几秒前
<数据集>yolo航拍军事目标识别<目标检测>
人工智能·python·yolo·目标检测·计算机视觉·航拍军事目标识别
架构师老Y几秒前
002、Prompt基础:大模型交互的第一性原理
人工智能·python·prompt
fish_xk几秒前
c++中的继承
开发语言·c++
2401_832365521 分钟前
如何用 FormData 配合 Fetch 实现无刷新的多文件上传
jvm·数据库·python
froginwe113 分钟前
CSS 图像透明/不透明
开发语言
2401_871492854 分钟前
如何在网页中实现国际象棋棋子的拖拽与格点吸附功能
jvm·数据库·python
m0_674294644 分钟前
JavaScript窗口大小调整resize事件的适配方案
jvm·数据库·python
初心未改HD7 分钟前
Go语言Map底层原理与并发安全深度解析
开发语言·golang
Brilliantwxx7 分钟前
【算法题】日期类算法题
开发语言·c++·笔记·程序人生·算法
qq_392690669 分钟前
JavaScript中Symbol类型的唯一性特征与创建规范
jvm·数据库·python