LSTM和SARIMA组合预测代码
时间: 2023-10-24 16:38:01 浏览: 111
Python基于遗传算法优化LSTM模型之股市预测代码+文档说明(高分)
5星 · 资源好评率100%
以下是一个使用 LSTM 和 SARIMA 进行组合预测的 Python 代码示例:
```python
import pandas as pd
from statsmodels.tsa.statespace.sarimax import SARIMAX
from sklearn.preprocessing import MinMaxScaler
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import LSTM, Dense
# 读入数据并进行预处理
data = pd.read_csv('data.csv', index_col=0)
scaler = MinMaxScaler()
data_scaled = scaler.fit_transform(data)
# 划分训练集和测试集
train_size = int(len(data_scaled) * 0.7)
train_data = data_scaled[:train_size]
test_data = data_scaled[train_size:]
# 训练 SARIMA 模型并进行预测
sarima_model = SARIMAX(train_data, order=(1, 1, 1), seasonal_order=(1, 1, 1, 12))
sarima_result = sarima_model.fit()
sarima_pred = sarima_result.predict(start=train_size, end=len(data_scaled)-1)
# 训练 LSTM 模型并进行预测
def create_dataset(data, look_back=1):
X, Y = [], []
for i in range(len(data)-look_back-1):
X.append(data[i:(i+look_back), 0])
Y.append(data[i+look_back, 0])
return np.array(X), np.array(Y)
look_back = 12
train_x, train_y = create_dataset(train_data, look_back)
test_x, test_y = create_dataset(test_data, look_back)
train_x = np.reshape(train_x, (train_x.shape[0], train_x.shape[1], 1))
test_x = np.reshape(test_x, (test_x.shape[0], test_x.shape[1], 1))
lstm_model = Sequential()
lstm_model.add(LSTM(units=50, return_sequences=True, input_shape=(look_back, 1)))
lstm_model.add(LSTM(units=50))
lstm_model.add(Dense(1))
lstm_model.compile(loss='mean_squared_error', optimizer='adam')
lstm_model.fit(train_x, train_y, epochs=50, batch_size=72, verbose=2)
lstm_pred = lstm_model.predict(test_x)
lstm_pred = scaler.inverse_transform(lstm_pred)
# 组合预测结果
pred = []
for i in range(len(test_y)):
pred.append((sarima_pred[i] + lstm_pred[i])/2)
# 可视化预测结果
import matplotlib.pyplot as plt
plt.plot(data.index[train_size+look_back+1:], data[train_size+look_back+1:], label='true')
plt.plot(data.index[train_size+look_back+1:], pred, label='pred')
plt.legend()
plt.show()
```
需要注意的是,这里使用了 SARIMA(1,1,1)(1,1,1,12) 和 LSTM(50,50) 作为示例模型,并且未进行参数调优。实际使用时需要根据数据特点进行参数调整。
阅读全文