机器学习入门项目:使用支持向量回归(SVR)进行时间序列预测
前言
时间序列预测是机器学习中一个重要且实用的应用领域。在之前的课程中,我们学习了使用ARIMA模型进行时间序列预测。本文将介绍另一种强大的预测方法——支持向量回归(SVR),它特别适合处理非线性时间序列数据。
什么是支持向量回归(SVR)
支持向量回归(Support Vector Regressor, SVR)是基于支持向量机(Support Vector Machine, SVM)的一种回归方法。与传统的回归方法不同,SVR通过寻找一个最优超平面来进行回归预测,这个超平面能够使尽可能多的数据点落在其周围的ε-带内。
SVR在时间序列预测中的优势
- 处理非线性关系:SVR通过核技巧可以有效地处理非线性关系,这是许多时间序列数据的重要特征
- 全局最优解:SVR通过优化凸函数保证找到全局最优解,避免了局部最优问题
- 泛化能力强:SVR具有良好的泛化能力,能够很好地处理未见过的数据
- 对异常值鲁棒:SVR通过ε-不敏感损失函数,对异常值具有较好的鲁棒性
实战:构建SVR时间序列预测模型
1. 数据准备
首先,我们需要加载并准备数据。我们使用能源负载数据集,该数据集记录了从2012年1月到2014年12月的能源消耗情况。
import pandas as pd
import matplotlib.pyplot as plt
# 加载数据
energy = pd.read_csv('energy.csv', index_col=0, parse_dates=True)[['load']]
# 可视化数据
energy.plot(y='load', figsize=(15, 6))
plt.xlabel('时间戳')
plt.ylabel('负载')
plt.title('能源负载时间序列')
plt.show()
2. 划分训练集和测试集
为了评估模型性能,我们需要将数据划分为训练集和测试集。这里我们选择2014年11月1日到2014年12月30日作为训练集,2014年12月30日之后的数据作为测试集。
train_start_dt = '2014-11-01 00:00:00'
test_start_dt = '2014-12-30 00:00:00'
train = energy[(energy.index >= train_start_dt) & (energy.index < test_start_dt)]
test = energy[energy.index >= test_start_dt]
3. 数据预处理
时间序列数据通常需要进行标准化处理,以消除量纲影响并提高模型性能。
from sklearn.preprocessing import MinMaxScaler
scaler = MinMaxScaler()
train['load'] = scaler.fit_transform(train)
test['load'] = scaler.transform(test)
4. 创建时间步长数据
SVR需要将时间序列数据转换为监督学习问题。我们通过创建时间步长来实现这一点。
import numpy as np
timesteps = 5 # 使用前4个时间点预测第5个时间点
# 转换训练数据
train_data = train.values
train_data_timesteps = np.array([[j for j in train_data[i:i+timesteps]]
for i in range(0, len(train_data)-timesteps+1)])[:,:,0]
# 分割输入输出
x_train, y_train = train_data_timesteps[:,:timesteps-1], train_data_timesteps[:,[timesteps-1]]
5. 构建和训练SVR模型
我们使用RBF核函数构建SVR模型,并设置适当的超参数。
from sklearn.svm import SVR
model = SVR(kernel='rbf', gamma=0.5, C=10, epsilon=0.05)
model.fit(x_train, y_train[:,0])
6. 模型评估
我们需要对模型在训练集和测试集上的表现进行评估。
from sklearn.metrics import mean_absolute_percentage_error as mape
# 训练集预测
y_train_pred = model.predict(x_train).reshape(-1,1)
y_train_pred = scaler.inverse_transform(y_train_pred)
y_train = scaler.inverse_transform(y_train)
# 计算MAPE
print('训练集MAPE:', mape(y_train, y_train_pred)*100, '%')
# 可视化预测结果
plt.figure(figsize=(15,6))
plt.plot(train.index[timesteps-1:], y_train, label='实际值')
plt.plot(train.index[timesteps-1:], y_train_pred, label='预测值')
plt.legend()
plt.title('训练集预测结果')
plt.show()
模型优化建议
- 超参数调优:尝试不同的gamma、C和epsilon值,寻找最优组合
- 核函数选择:除了RBF核,还可以尝试线性核、多项式核等
- 时间步长调整:实验不同的时间步长,找到最适合数据特征的长度
- 特征工程:考虑添加其他相关特征,如季节性指标、趋势分量等
总结
支持向量回归(SVR)是时间序列预测中一个强大的工具,特别适合处理非线性关系。通过本教程,我们学习了如何:
- 准备时间序列数据
- 构建SVR模型
- 评估模型性能
- 可视化预测结果
SVR虽然计算复杂度较高,但在许多实际应用中表现出色。掌握SVR的使用方法,将为你的时间序列预测工具箱增添一件利器。
创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考