解决方案:用决策树算法如何生成决策树图及生成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)

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

相关推荐
漂流瓶jz3 小时前
【AI】大模型LoRA微调原理与实验:基于CMRC2018与Qwen3-0.6B训练实测
人工智能·算法·llm
对你无可奈何4 小时前
用 AI 开发一套 AIOps 平台:接入工具、编排 Agent,追踪任务和资源
人工智能
羲云网络4 小时前
GPT Image 2.6 海报改横竖版:文字安全区、排版分离与交付验收
图像处理·人工智能·python·aigc
weixin_418772724 小时前
公司年会年年办,AI 日历一年翻不了几页
人工智能·数字化转型·企业信息化
明川6 小时前
RAG 到底是什么
人工智能·llm
罗西的思考7 小时前
【轻量化复刻大模型 / KIMI K3】K3 PostTrain 后训练交互式演示
人工智能·算法·机器学习
ZhengEnCi8 小时前
黄仁勋回归英伟达:没有欢迎仪式,员工自发拥抱说明了什么
人工智能·nvidia
陆枫Larry8 小时前
从一头雾水到自己开发一个 MCP Server 来加深理解
人工智能
Csvn8 小时前
模型被「忽略指令」劫持怎么办?双层防线:输入过滤 + 输出校验(S02)
人工智能
Flynn Liang9 小时前
AI Agent Redis 生产踩坑实录:13 类故障的根因、复现与调优
数据库·人工智能·redis·缓存·ai agent·故障分析