解决方案:用决策树算法如何生成决策树图及生成SQL规则

文章目录


一、现象

一开始没有做过生成决策树图及生成SQL规则,一时犯了难,百度很多找到了解决方法,于是乎,写一篇博客,这样下次就能直接拿来使用咯

二、解决方案

见最后三块代码,为了区分做个标记(#********************,以下)

python 复制代码
import numpy as np
import pandas as pd
df = pd.read_csv("data.csv")


# 构建特征和标签集
y = df.Exited.values
X = df.drop(['flag'], axis = 1)


from sklearn.model_selection import train_test_split  # 拆分训练集和测试集
X_train, X_test, y_train, y_test = train_test_split(X,y,test_size = 0.2,random_state=0)


# 进行特征缩放
from sklearn import preprocessing
scaler = preprocessing.MinMaxScaler()
X_train = scaler.fit_transform(X_train)
X_test = scaler.transform(X_test)


from sklearn.metrics import (f1_score, confusion_matrix) # 导入评估指标
from sklearn.tree import DecisionTreeClassifier # 导入模型
dt = DecisionTreeClassifier() # 分类决策树
dt.fit(X_train, y_train) # 拟合模型
y_pred = dt.predict(X_test) # 预测结果
dt_acc = dt.score(X_test,y_test)*100 # 准确率
dt_f1 = f1_score(y_test, y_pred)*100 # F1分数
print("决策树测试集准确率:: {:.2f}%".format(dt_acc))
print("决策树测试集F1分数: {:.2f}%".format(dt_f1))
print('决策树混淆矩阵:\n', confusion_matrix(y_test,y_pred))


#********************
df_copy = df.drop(columns = ['user_id', 'flag'])
col_tree = df_copy.columns[:]
class_flag = ['no', 'yes']


from sklearn.tree import plot_tree
plt.figure(figsize=(32, 20), dpi=300)
dot_data = plot_tree(dt, feature_names = col_tree, class_names = class_flag, filled = True, rounded = True)
plt.savefig('dt_pic.pdf', format = 'pdf', bbox_inches = 'tight')


from sklearn.tree import export_text
text_sql = export_text(dt, feature_names = list(col_tree))
print(text_sql)

代码部分参考(为了做个完整案例):
机器学习_常见算法比较模型效果(LR、KNN、SVM、NB、DT、RF、XGB、LGB、CAT)

解决方案:网上各种资料尝试一番

相关推荐
宿州派大星3 小时前
Python实战:PyQt5 + OpenCV + Dlib 打造AI桌面应用
人工智能·python·qt
风娜4 小时前
IT 疑难杂症诊疗室:从现象到根因的系统排查方法论
人工智能·github
碧海银沙音频科技研究院4 小时前
炬芯ATS3089X手表的HFP通话不自动路由到设备BT的问题解决
网络·人工智能·嵌入式硬件·算法
承渊政道4 小时前
【从零开始大模型开发与微调:基于PyTorch与ChatGLM】(开源大模型ChatGLM高级定制化应用实战)
人工智能·pytorch·python·llm·模型微调·glm
howdoyoudo2026064 小时前
AI审计手记 #28:从“暂停训练”到“切断联网”——AI安全控制手段的极限升级
大数据·人工智能·安全·ai·语言模型
colman wang4 小时前
人工智能课程(配套AIMA(Artificial Intelligence: A Modern Approach))
人工智能
LinXunFeng8 小时前
Draw Things 换装 LoRA 实战:用 Silo 秒装,同一提示词对比出图
人工智能·开源·aigc
xiaohaiAIgeo8 小时前
【2026年】通风柜自动门安全吗?联锁逻辑与防夹设计
人工智能·安全·科普知识
像风一样自由20208 小时前
52.Docker部署大模型应用从本地开发到服务化运行
运维·人工智能·docker·容器·大模型·智能体