【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年后的价格预测结果非常好,但忽略了训练数据和测试数据中一些更细微的变化。树模型则完美预测了训练数据,但一旦输入超过了模型训练数据的范围,模型就只能持续预测最后一个已知数据点。树不能在训练数据的范围之外生成新的响应,所有基于树的模型都有这个缺点。

相关推荐
喵叔哟3 分钟前
02-YOLO-v8-v9-v10工程差异对比
人工智能·yolo·机器学习
ZH15455891314 分钟前
Flutter for OpenHarmony Python学习助手实战:面向对象编程实战的实现
python·学习·flutter
玄同7655 分钟前
SQLite + LLM:大模型应用落地的轻量级数据存储方案
jvm·数据库·人工智能·python·语言模型·sqlite·知识图谱
L、2185 分钟前
CANN 内存管理深度解析:高效利用显存,突破 AI 推理瓶颈
人工智能
聊聊科技7 分钟前
原创音乐人使用AI编曲软件制作伴奏,编曲用什么音源好听
人工智能
爱吃烤鸡翅的酸菜鱼7 分钟前
CANN ops-nn卷积算子深度解析与性能优化
人工智能·性能优化·aigc
向哆哆7 分钟前
CANN生态安全保障:cann-security-module技术解读
人工智能·安全·cann
The Straggling Crow8 分钟前
模型全套服务 cube-studio
人工智能
User_芊芊君子10 分钟前
CANN010:PyASC Python编程接口—简化AI算子开发的Python框架
开发语言·人工智能·python
AI科技16 分钟前
原创音乐人搭配AI编曲软件,编曲音源下载哪个软件
人工智能