[机器学习]决策树

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 决策树剪枝

相关推荐
大树881 分钟前
液冷从“电老虎“变“热银行“:算力废热如何变成真金白银?
人工智能
E等于MC平方3 分钟前
用 Next.js + Prisma + Gemini 打造 AI 替代风险追踪平台
人工智能·ai·职业·岗位·失业·替代
段一凡-华北理工大学3 分钟前
【高炉炼铁领域炉温监测、预警、调控智能体设计与应用】~系列文章10:实时预警机制:跑在问题前面!
网络·人工智能·python·知识图谱·高炉炼铁·工业智能体
β添砖java8 分钟前
深度学习(20)深度卷积神经网络AlexNet
人工智能·深度学习·cnn
weixin_4080996730 分钟前
身份证OCR识别如何做到99.9%准确率?揭秘石榴智能六大核心技术(矫正/完整度/翻拍检测/头像提取)
图像处理·人工智能·ocr·api接口·身份证识别·石榴智能
林小卫很行31 分钟前
Obsidian 入门39:怎么创建自己的 Skill?我把五步拆给你看
人工智能
Baihai_IDP42 分钟前
为什么 AI Agent 重新爱上了文件系统(Filesystems)
人工智能·llm·agent
灵机一物1 小时前
灵机一物AI原生电商小程序、PC端(已上线)-Token成产研新KPI:2026年,AI提效、数字员工与研发效能变革
人工智能
薛定猫AI1 小时前
【深度解析】Pi 极简终端 Coding Agent:为什么 4 个工具反而更适合 AI 编程?
人工智能