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

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

相关推荐
紫金修道3 小时前
【DeepAgent】概述
开发语言·数据库·python
Via_Neo3 小时前
JAVA中以2为底的对数表示方式
java·开发语言
书到用时方恨少!3 小时前
Python multiprocessing 使用指南:突破 GIL 束缚的并行计算利器
开发语言·python·并行·多进程
cch89183 小时前
PHP五大后台框架横向对比
开发语言·php
Warson_L3 小时前
Python 常用内置标准库
python
天真萌泪3 小时前
JS逆向自用
开发语言·javascript·ecmascript
Warson_L4 小时前
Python 函数的艺术 (Functions)
python
Warson_L4 小时前
Python 流程控制与逻辑
后端·python
野生技术架构师4 小时前
一线大厂Java面试八股文全栈通关手册(含源码级详解)
java·开发语言·面试
long_songs4 小时前
手柄键盘映射器【github链接见文末 】
python·游戏·计算机外设·pygame·软件推荐·手柄映射键盘