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

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

相关推荐
南瓜胖胖3 分钟前
【R语言编程——数据调用】
开发语言·r语言
老歌老听老掉牙4 分钟前
旋量理论:刚体运动的几何描述与机器人应用
python·算法·机器学习·机器人·旋量
henreash7 分钟前
C# dll版本冲突解决方案
开发语言·c#
黎䪽圓28 分钟前
【Java多线程从青铜到王者】单例设计模式(八)
java·开发语言·设计模式
我是初九37 分钟前
【李沐-动手学深度学习v2】1.Colab学习环境配置
人工智能·python·学习·colab
失败又激情的man42 分钟前
python爬虫之数据存储
前端·数据库·python
一刀到底2111 小时前
Python 高级应用10:在python 大型项目中 FastAPI 和 Django 的相互配合
python·django·fastapi
摸鱼仙人~1 小时前
Redux Toolkit 快速入门指南:createSlice、configureStore、useSelector、useDispatch 全面解析
开发语言·javascript·ecmascript