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

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

相关推荐
無限進步D4 小时前
Java 运行原理
java·开发语言·入门
是苏浙4 小时前
JDK17新增特性
java·开发语言
花酒锄作田5 小时前
企业微信机器人与 DeepAgents 集成实践
python·mcp·deepagents
阿里加多7 小时前
第 4 章:Go 线程模型——GMP 深度解析
java·开发语言·后端·golang
likerhood7 小时前
java中`==`和`.equals()`区别
java·开发语言·python
qq_283720058 小时前
Python Celery + FastAPI + Vue 全栈异步任务实战
vue.js·python·fastapi
2401_885885048 小时前
营销推广短信接口集成:结合营销策略实现的API接口动态变量填充方案
前端·python
zs宝来了8 小时前
AQS详解
java·开发语言·jvm
telllong9 小时前
Python异步编程从入门到不懵:asyncio实战踩坑7连发
开发语言·python
wjs202410 小时前
JavaScript 条件语句
开发语言