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

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

相关推荐
Python私教13 小时前
Codex 写出的代码能跑却算错钱:我用 3 个测试拆穿一次 AI 编程幻觉
python·单元测试·ai编程
Python私教14 小时前
我只写了一个 add 工具,终于把 MCP 的 Host、Client、Server 跑明白了
python·ai编程·mcp
霸道流氓气质14 小时前
分布式系统中接口时序不确定性处理
java·开发语言·分布式
库克克14 小时前
【C++】C++11 包装器function 与 绑定器 bind
开发语言·c++
多加点辣也没关系14 小时前
JavaScript|第30章:事件机制
开发语言·javascript
小大宇14 小时前
python milvus 案例
开发语言·python·milvus
Gauss松鼠会14 小时前
【GaussDB】GaussDB锁阻塞源头查询
java·开发语言·前端·数据库·算法·gaussdb·经验总结
mingo_敏15 小时前
DeepAgents : 后端(Backends)
java·开发语言
mabing99315 小时前
Qt QMessageBox、QDialogButtonBox中英文翻译动态切换
开发语言·qt
BerryS3N15 小时前
Java 后端转型大模型:Demo 能跑不等于能上线
java·人工智能·python·java后端·spring ai·langchain4j·大模型转型