SARIMA-LSTM模型python代码
时间: 2024-06-18 20:03:08 浏览: 223
时间序列预测(LSTM模型)python代码实现(95分以上).zip
5星 · 资源好评率100%
SARIMA-LSTM模型是一种结合了季节性自回归移动平均模型(Seasonal Autoregressive Integrated Moving Average,SARIMA)和长短期记忆神经网络(Long Short-Term Memory,LSTM)的时间序列预测模型,其主要思想是利用SARIMA模型对季节性和趋势性进行建模,再将残差序列输入LSTM网络进行预测。下面是一个简单的SARIMA-LSTM模型的Python代码示例:
```python
# 导入相关库
import numpy as np
import pandas as pd
from statsmodels.tsa.statespace.sarimax import SARIMAX
from keras.models import Sequential
from keras.layers import LSTM, Dense
# 加载数据
data = pd.read_csv('data.csv', index_col=0, parse_dates=True)
# 划分训练集和测试集
train_data = data[:'2019']
test_data = data['2020':]
# SARIMA模型拟合
model = SARIMAX(train_data, order=(1, 1, 1), seasonal_order=(0, 1, 1, 12))
results = model.fit()
# 预测训练集和测试集
train_pred = results.predict(start=train_data.index, end=train_data.index[-1])
test_pred = results.predict(start=test_data.index, end=test_data.index[-1])
# LSTM模型训练和预测
def create_dataset(dataset, look_back=12):
X, Y = [], []
for i in range(len(dataset)-look_back-1):
a = dataset[i:(i+look_back), 0]
X.append(a)
Y.append(dataset[i+look_back, 0])
return np.array(X), np.array(Y)
look_back = 12
train_X, train_Y = create_dataset(train_pred.values.reshape(-1,1), look_back)
test_X, test_Y = create_dataset(test_pred.values.reshape(-1,1), look_back)
train_X = np.reshape(train_X, (train_X.shape, train_X.shape, 1))
test_X = np.reshape(test_X, (test_X.shape, test_X.shape, 1))
model = Sequential()
model.add(LSTM(50, input_shape=(look_back, 1)))
model.add(Dense(1))
model.compile(loss='mean_squared_error', optimizer='adam')
model.fit(train_X, train_Y, epochs=100, batch_size=32)
train_lstm_pred = model.predict(train_X)
test_lstm_pred = model.predict(test_X)
# 组合预测结果
train_pred_final = train_lstm_pred + train_pred[look_back+1:].values.reshape(-1,1)
test_pred_final = test_lstm_pred + test_pred[look_back+1:].values.reshape(-1,1)
# 输出预测结果
print('训练集RMSE:', np.sqrt(np.mean((train_data[look_back+1:]-train_pred_final)**2)))
print('测试集RMSE:', np.sqrt(np.mean((test_data[look_back+1:]-test_pred_final)**2)))
```
该代码首先使用SARIMA模型对训练集和测试集进行拟合和预测,然后将SARIMA模型的预测结果作为LSTM模型的输入,对其进行训练和预测。最后将SARIMA和LSTM的预测结果组合起来,计算并输出训练集和测试集的均方根误差(Root Mean Squared Error,RMSE)。
阅读全文