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

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

相关推荐
哈哈不让取名字5 分钟前
用Pygame开发你的第一个小游戏
jvm·数据库·python
程序员敲代码吗6 分钟前
Python异步编程入门:Asyncio库的使用
jvm·数据库·python
MediaTea6 分钟前
Python:MRO 解密 —— C3 线性化算法
java·开发语言
sunfove8 分钟前
Python小游戏:在 2048 游戏中实现基于线性插值(Lerp)的平滑动画
开发语言·python·游戏
2501_9445264212 分钟前
Flutter for OpenHarmony 万能游戏库App实战 - 抽牌游戏实现
android·开发语言·python·flutter·游戏
a程序小傲14 分钟前
听说前端又死了?
开发语言·前端·mysql·算法·postgresql·深度优先
副露のmagic15 分钟前
python基础复健
python·算法
学Linux的语莫24 分钟前
python项目打包为镜像
java·python·spring
Ashley_Amanda36 分钟前
Python 进阶:从熟练到精通的核心技能体系
开发语言·python
你怎么知道我是队长41 分钟前
C语言---命令行参数
c语言·开发语言