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

相关推荐
不辉放弃7 分钟前
零基础讲解pandas
开发语言·python
Chaos_Wang_14 分钟前
NLP高频面试题(三十)——LLama系列模型介绍,包括LLama LLama2和LLama3
人工智能·自然语言处理·llama
databook17 分钟前
线性判别分析(LDA):降维与分类的完美结合
python·机器学习·scikit-learn
慕丹19 分钟前
虫洞数观系列三 | 数据分析全链路实践:Pandas清洗统计 + Navicat可视化呈现
python·mysql·数据挖掘·数据分析·pandas
新智元19 分钟前
美国 CS 专业卷上天,满分学霸惨遭藤校全拒!父亲大受震撼引爆热议
人工智能·openai
新智元22 分钟前
美国奥数题撕碎 AI 数学神话,顶级模型现场翻车!最高得分 5%,DeepSeek 唯一逆袭
人工智能·openai
ZHW_AI课题组31 分钟前
调用阿里云API实现运营商实名认证
python·阿里云·云计算·api
Baihai_IDP32 分钟前
「DeepSeek-V3 技术解析」:无辅助损失函数的负载均衡
人工智能·llm·deepseek
闲人编程33 分钟前
图像插值算法(最近邻/双线性/立方卷积)
python·opencv·图像识别
硅谷秋水39 分钟前
大语言模型智体的综述:方法论、应用和挑战(下)
人工智能·深度学习·机器学习·语言模型·自然语言处理