[机器学习]决策树

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

相关推荐
之歆4 小时前
Spring AI入门到实战到原理源码-MCP
java·人工智能·spring
知乎的哥廷根数学学派4 小时前
面向可信机械故障诊断的自适应置信度惩罚深度校准算法(Pytorch)
人工智能·pytorch·python·深度学习·算法·机器学习·矩阵
且去填词5 小时前
DeepSeek :基于 Schema 推理与自愈机制的智能 ETL
数据仓库·人工智能·python·语言模型·etl·schema·deepseek
待续3015 小时前
订阅了 Qoder 之后,我想通过这篇文章分享一些个人使用心得和感受。
人工智能
weixin_397578025 小时前
人工智能发展历史
人工智能
数字化转型20255 小时前
企业数字化架构集成能力建设
大数据·程序人生·机器学习
强盛小灵通专卖员5 小时前
基于深度学习的山体滑坡检测科研辅导:从论文实验到系统落地的完整思路
人工智能·深度学习·sci·小论文·山体滑坡
OidEncoder5 小时前
从 “粗放清扫” 到 “毫米级作业”,编码器重塑环卫机器人新能力
人工智能·自动化·智慧城市
Hcoco_me5 小时前
大模型面试题61:Flash Attention中online softmax(在线softmax)的实现方式
人工智能·深度学习·自然语言处理·transformer·vllm
阿部多瑞 ABU6 小时前
`chenmo` —— 可编程元叙事引擎 V2.3+
linux·人工智能·python·ai写作