Fluxy
Fluxy

Reputation: 2978

How to change the forecast horizon in LSTM model?

I have the following model to forecast the price time series. It generates a forecast for 1 day ahead. So, the planning horizon is 1.

model = Sequential()
model.add(LSTM(4, input_shape=(1, look_back)))
model.add(Dense(1))
model.compile(loss="mean_squared_error", optimizer="adam")
model.fit(trainX, trainY, epochs=10, batch_size=1, verbose=2) 

What is the right approach to change this model to forecast 5 days ahead (i.e. planning horizon -> 5).

Should I just change input_shape=(1, look_back) to input_shape=(5, look_back), and change the trainY in such a way that it contains 5 points for each row in trainX? Or is it more trick?

Upvotes: 0

Views: 978

Answers (1)

Nicolas Gervais
Nicolas Gervais

Reputation: 36684

Try using this function:

def univariate_data(dataset, start_index, end_index, history_size,
                    target_size, single_step=False):
    data, labels = [], []
    start_index = start_index + history_size
    if end_index is None:
        end_index = len(dataset) - target_size
    for i in range(start_index, end_index):
        indices = np.arange(i-history_size, i)
        data.append(np.reshape(dataset[indices], (history_size, 1)))
        if single_step:
            labels.append(dataset[i + target_size])
        else:
            labels.append(dataset[i:i + target_size])
    return np.array(data), np.array(labels)
trainX, trainY = univariate_data(X, 0, len(X) - look_ahead, look_back, look_ahead)

Full example:

import tensorflow as tf
import numpy as np

look_back = 5
look_ahead = 5
X = np.random.rand(100)
y = np.random.rand(100)

def univariate_data(dataset, start_index, end_index, history_size,
                    target_size, single_step=False):
    data, labels = [], []
    start_index = start_index + history_size
    if end_index is None:
        end_index = len(dataset) - target_size
    for i in range(start_index, end_index):
        indices = np.arange(i-history_size, i)
        data.append(np.reshape(dataset[indices], (history_size, 1)))
        if single_step:
            labels.append(dataset[i + target_size])
        else:
            labels.append(dataset[i:i + target_size])
    return np.array(data), np.array(labels)

trainX, trainY = univariate_data(X, 0, len(X) - look_ahead, look_back, look_ahead)

model = tf.keras.Sequential()
model.add(tf.keras.layers.LSTM(4, input_shape=trainX.shape[1:], 
          return_sequences=True))
model.add(tf.keras.layers.Dense(1))
model.compile(loss="mean_squared_error", optimizer="adam")
model.fit(trainX, trainY, epochs=10, batch_size=1, verbose=2)

Upvotes: 1

Related Questions