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

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

相关推荐
2401_86495928几秒前
C++与Python混合编程实战
开发语言·c++·算法
左左右右左右摇晃2 分钟前
Java并发——锁的状态演变
java·开发语言·笔记
2501_945424802 分钟前
C++与硬件交互编程
开发语言·c++·算法
2301_818419012 分钟前
C++中的表达式模板
开发语言·c++·算法
Roselind_Yi4 分钟前
排查Visual C++堆损坏(HEAP CORRUPTION)错误:从报错到解决的完整复盘
java·开发语言·c++·spring·bug·学习方法·远程工作
全栈凯哥8 分钟前
27.Python datetime 与 time 完全指南
python
ZoeJoy88 分钟前
C# Windows Forms 学生成绩管理器(StudentGradeManager)—— 方法重载、out、ref、params 参数示例
开发语言·c#
千百元11 分钟前
网络图标显示不正常
开发语言·网络·php
Amumu1213814 分钟前
Js: ES新特性(一)
开发语言·前端·javascript
qiumingxun16 分钟前
Redis——使用 python 操作 redis 之从 hmse 迁移到 hset
数据库·redis·python