【Python机器学习】用于回归的决策树

用于回归的决策树与用于分类的决策树类似,在DecisionTreeRegressor中实现。DecisionTreeRegressor不能外推,也不能在训练数据范围之外的数据进行预测。

利用计算机内存历史及格的数据进行实验,数据展示:

python 复制代码
import pandas as pd
import matplotlib.pyplot as plt

plt.rcParams['font.sans-serif'] = ['SimHei']

ram_price=pd.read_csv('ram_price.csv')
plt.semilogy(ram_price.date,ram_price.price)
plt.xlabel('年份')
plt.ylabel('价格')
plt.show()

利用2000年前的历史数据来预测2000年之后的价格,只用日期作为特征,对比决策树、线性模型的预测结果:

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

plt.rcParams['font.sans-serif'] = ['SimHei']
ram_price=pd.read_csv('ram_price.csv')
#plt.semilogy(ram_price.data,ram_price.price)
data_train=ram_price[ram_price.date<2000]
data_test=ram_price[ram_price.date>=2000]

X_train=np.array(data_train)
#X_train=data_train.date[:, np.newaxis]
y_train=np.log(data_train.price)

tree=DecisionTreeRegressor().fit(X_train,y_train)
line_reg=LinearRegression().fit(X_train,y_train)

X_all = np.array(ram_price)
#X_all=ram_price.date[:,np.newaxis]
pred_tree=tree.predict(X_all)
pred_lr=line_reg.predict(X_all)

price_tree=np.exp(pred_tree)
price_lr=np.exp(pred_lr)

plt.semilogy(data_train.date,data_train.price,label='训练数据')
plt.semilogy(data_test.date,data_test.price,label='测试数据')
plt.semilogy(ram_price.date,price_tree,label='决策树预测')
plt.semilogy(ram_price.date,price_lr,label='线性预测')
plt.legend()
plt.show()

可以看到两个模型的差异非常明显。线性模型用一条直线对数据做近似,对2000年后的价格预测结果非常好,但忽略了训练数据和测试数据中一些更细微的变化。树模型则完美预测了训练数据,但一旦输入超过了模型训练数据的范围,模型就只能持续预测最后一个已知数据点。树不能在训练数据的范围之外生成新的响应,所有基于树的模型都有这个缺点。

相关推荐
技术探索家5 小时前
别再让Claude乱写代码了!一个配置文件让AI准确率提升10%
人工智能
算家计算5 小时前
AI学习范式变革:Ilya Sutskever最新访谈揭示后规模时代的AI发展路径—从算力竞争到研究竞争的转向
人工智能·资讯
Jing_Rainbow6 小时前
【AI-7 全栈-2 /Lesson16(2025-11-01)】构建一个基于 AIGC 的 Logo 生成 Bot:从前端到后端的完整技术指南 🎨
前端·人工智能·后端
syounger6 小时前
奔驰全球 IT 加速转型:SAP × AWS × Agentic AI 如何重塑企业核心系统
人工智能·云计算·aws
上班日常摸鱼6 小时前
Shell脚本基础教程:变量、条件判断、循环、函数实战(附案例)
python
16_one6 小时前
autoDL安装Open-WebUi+Rag本地知识库问答+Function Calling
人工智能·后端·算法
智能交通技术6 小时前
iTSTech:自动驾驶技术综述报告 2025
人工智能·机器学习·自动驾驶
无心水6 小时前
【Python实战进阶】5、Python字符串终极指南:从基础到高性能处理的完整秘籍
开发语言·网络·python·字符串·unicode·python实战进阶·python工业化实战进阶
2301_807583236 小时前
了解python,并编写第一个程序,常见的bug
linux·python
小白学大数据6 小时前
构建混合爬虫:何时使用Requests,何时切换至Selenium处理请求头?
爬虫·python·selenium·测试工具