[机器学习]决策树

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

相关推荐
gptplusplus8 分钟前
AI智能体(Agent):从“辅助决策”到“自主行动”,重新定义下一个商业时代
人工智能
别忘了微笑啊9 分钟前
hCaptcha 图像识别 API 对接说明
人工智能
大千AI助手31 分钟前
灾难性遗忘:神经网络持续学习的核心挑战与解决方案
人工智能·深度学习·神经网络·大模型·llm·持续学习·灾难性遗忘
gotouniverse32 分钟前
之前自学RAG时做的调研
人工智能
新智元39 分钟前
刚刚,英伟达祭出下一代 GPU!狂飙百万 token 巨兽,投 1 亿爆赚 50 亿
人工智能·openai
霍格沃兹_测试1 小时前
从零开始搭建Qwen智能体:新手也能轻松上手指南
人工智能
SmartJavaAI1 小时前
Java调用Whisper和Vosk语音识别(ASR)模型,实现高效实时语音识别(附源码)
java·人工智能·whisper·语音识别
山东小木1 小时前
JBoltAI需求分析大师:基于SpringBoot的大模型智能需求文档生成解决方案
人工智能·spring boot·后端·需求分析·jboltai·javaai·aigs
君名余曰正则1 小时前
【竞赛系列】机器学习实操项目08——全球城市计算AI挑战赛(数据可视化分析)
人工智能·机器学习·信息可视化
算家计算1 小时前
一张图+一段音频=电影级视频!阿里Wan2.2-S2V-14B本地部署教程:实现丝滑口型同步
人工智能·开源·aigc