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

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

相关推荐
迷迭香yy11 分钟前
Python实战:涨停板“假封板”识别系统的工程实现
开发语言·人工智能·python
charlie11451419111 分钟前
Cinux是如何管理进程的 —— 上下文与调度
开发语言·c++·操作系统·开源项目
aqi0029 分钟前
15天学会AI应用开发(二十)使用LangChain实现RAG检索功能
人工智能·python·ai编程
-银雾鸢尾-38 分钟前
C#中的协变和逆变
开发语言·c#
阿米亚波39 分钟前
【C++ 异常处理】try-catch
开发语言·c++·笔记·try-catch
本地化文档41 分钟前
skbuild-docs-l10n
python·github·gitcode·sphinx
旖旎夜光1 小时前
C++(内存管理)
开发语言·c++·学习
≮傷£≯√1 小时前
QT配置FFmpeg
开发语言·qt·ffmpeg
事缓则圆1 小时前
从零推导 Python 装饰器:不用背语法,看完这篇就懂了
python