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

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

相关推荐
R-sz5 分钟前
java流式计算 获取全量树形数据,非懒加载树,递归找儿
java·开发语言·windows
随意02324 分钟前
Qt 事件
开发语言·qt
Gyoku Mint30 分钟前
深度学习×第4卷:Pytorch实战——她第一次用张量去拟合你的轨迹
人工智能·pytorch·python·深度学习·神经网络·算法·聚类
鸥梨菌Honevid31 分钟前
Qt自定义控件(1)——QPaintEvent
开发语言·qt
Code季风34 分钟前
深入比较 Gin 与 Beego:Go Web 框架的两大选择
开发语言·golang·go·gin·beego
专注VB编程开发20年2 小时前
javascript的类,ES6模块写法在VSCODE中智能提示
开发语言·javascript·vscode
郭庆汝6 小时前
pytorch、torchvision与python版本对应关系
人工智能·pytorch·python
黄雪超9 小时前
JVM——函数式语法糖:如何使用Function、Stream来编写函数式程序?
java·开发语言·jvm
ThetaarSofVenice9 小时前
对象的finalization机制Test
java·开发语言·jvm
思则变9 小时前
[Pytest] [Part 2]增加 log功能
开发语言·python·pytest