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

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

相关推荐
leiming62 分钟前
c++ qt开发第一天 hello world
开发语言·c++·qt
奋斗者1号8 分钟前
MQTT连接失败定位步骤
开发语言·机器学习·网络安全
0思必得09 分钟前
[Web自动化] BeautifulSoup导航文档树
前端·python·自动化·html·beautifulsoup
vyuvyucd14 分钟前
Python条件与循环语句全解析
python
33三 三like16 分钟前
毕设任务分析
开发语言
gf132111120 分钟前
制作卡点视频
数据库·python·音视频
vyuvyucd21 分钟前
Linux线程编程:POSIX与C++实战指南
java·开发语言
owlion23 分钟前
如何将视频文案整理成学习笔记
人工智能·python·机器学习·语言模型·自然语言处理
Kratzdisteln24 分钟前
【MVCD 3】
开发语言·php
癫狂的兔子24 分钟前
【Python】【NumPy】random.rand和random.uniform的异同点
开发语言·python·numpy