[机器学习]决策树

1 决策树简介

2 信息熵

3 ID3决策树

3.1 决策树构建流程

3.2 决策树案例

4 C4.5决策树

5 CART决策树(分类&回归)

6 泰坦尼克号生存预测案例

python 复制代码
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.tree import DecisionTreeClassifier,plot_tree
import matplotlib.pyplot as plt
from sklearn.metrics import accuracy_score,precision_score,recall_score,f1_score,classification_report
# 获取数据
data=pd.read_csv('titanic/train.csv')
# data.info()
# 数据处理
x=data[['Sex','Age','Pclass']]
y=data['Survived']
# x.head()
# 热编码
x=pd.get_dummies(x)
# 缺失值填充
x['Age']=x['Age'].fillna(x['Age'].mean())
# x.head()
x_train,x_test,y_train,y_test=train_test_split(x,y,test_size=0.2,random_state=22)
# 模型训练
tree=DecisionTreeClassifier(criterion='gini',max_depth=6)
tree.fit(x_train,y_train)
# 模型预测
y_predict=tree.predict(x_test)
# print(y_predict)
# 模型评估
print('accuracy_score',accuracy_score(y_test,y_predict))
print('precision_score',precision_score(y_test,y_predict))
print('recall_score',recall_score(y_test,y_predict))
print('f1_score',f1_score(y_test,y_predict))
print(classification_report(y_test,y_predict))
# 绘制树
plt.figure(figsize=(30,20))
plot_tree(tree,filled=True,feature_names=['Age','Pclass','Sex_female','Sex_male'],class_names=['died','survived'])
plt.show()

7 CART回归树

python 复制代码
import numpy as np
from sklearn.linear_model import LinearRegression
from sklearn.tree import DecisionTreeRegressor,plot_tree
import matplotlib.pyplot as plt

# 构建数据
x=np.array(list(range(1,11))).reshape(-1,1)
print(x.shape)
y=np.array([5.56,5.7,5.91,6.4,6.8,7.05,8.9,8.7,9,9.05])
# print(x)

# 模型训练
model1=LinearRegression()
model2=DecisionTreeRegressor(max_depth=1)
model3=DecisionTreeRegressor(max_depth=3)

model1.fit(x,y)
model2.fit(x,y)
model3.fit(x,y)
# 模型预测
x_test=np.arange(0.0,10.0,0.01).reshape(-1,1)
print(x_test.shape)
y1=model1.predict(x_test)
y2=model2.predict(x_test)
y3=model3.predict(x_test)

plt.scatter(x,y)
plt.plot(x_test,y1)
plt.plot(x_test,y2)
plt.plot(x_test,y3)
plt.grid()
plt.show()

plt.figure(figsize=(30,20))
plot_tree(model3,filled=True)
plt.show()

8 决策树剪枝

相关推荐
ting94520005 小时前
Humalike X Hermes 深度技术剖析:单指令注入群聊社交智能的底层架构、算法与跨 IM 平台实现
人工智能·算法·架构
涤生大数据5 小时前
一次“没有运行日志”的DolphinScheduler任务失败排查
大数据·数据库·人工智能·状态模式
东风破_5 小时前
Vibe Coding 上头之后,我开始用 SDD 给 AI 编程加一张“施工图”
人工智能·程序员
weixin_403810135 小时前
AI智能体写安卓自动化脚本教程:Cursor/Trae+CLI 实战,自然语言生成代码
android·人工智能·自动化·跨境电商·安卓自动化脚本·多账户运营
深圳雨林凯AI6 小时前
雨林凯AI四方连图介质适配原理:像素密度、纱线纹理与颜色管理怎么协调
人工智能
ZGIAI6 小时前
ZGI 混合检索:汇集候选并统一重排
人工智能·架构
ZGIAI6 小时前
ZGI 运行日志:还原任务与节点状态
人工智能·架构
Scott9999HH6 小时前
2026 中小企业如何破局 AI 搜索?轻量化 GEO 优化系统架构设计与 Python 实战落地
人工智能
甲维斯6 小时前
opencode的“恶果”来了,吃掉100G空间!
人工智能
IT大白鼠7 小时前
PentestGPT作为AI运维编排工作流自动化底座的技术架构与应用价值评估
运维·人工智能·自动化·pentestgpt