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

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

相关推荐
保持低旋律节奏9 分钟前
C++——C++11特性
开发语言·c++·windows
ID_1800790547326 分钟前
基于 Python 的淘宝商品详情数据结构化解析:SKU、价格与库存字段提取
开发语言·数据结构·python
星释29 分钟前
Rust 练习册 82:Hamming与字符串处理
开发语言·算法·rust
时间不说谎30 分钟前
c/c++的语法糖
开发语言
Laughtin42 分钟前
终端Python环境的选择与切换
开发语言·python
头发还在的女程序员1 小时前
基于JAVA语言的短剧小程序-抖音短剧小程序
java·开发语言·小程序
JHC0000001 小时前
Python PDF 相关操作
开发语言·python·pdf
databook1 小时前
Manim进阶:用背景图片让你的数学视频脱颖而出
python·动效
温轻舟2 小时前
Python自动办公工具01-Excel文件编辑器
开发语言·python·编辑器·excel·温轻舟
星星上的吴彦祖2 小时前
多模态感知驱动的人机交互决策研究综述
python·深度学习·计算机视觉·人机交互