Making Predictions using LSTM with Keras

Asked

Viewed 235 times

0

Good morning, group.

I’m doing some tests with predictive models using lstm with the keras.

In the test that I did, I trained the model with some random data that I found on the internet.

Only I’m having second thoughts on the predictions part.

To make the predictions on the Keras he uses the model.predict variably X to make the predictions.

Like, I trained my model with 200 samples for example. Then I notice that he makes the forecast for 200 samples, since the entries and exits (X and y) have the same Shape.

But if I want to train my model with 200 samples (in the case of my model I did the training with 5 samples) and make the forecast for 20 samples (samples that are not part of the training and testing data).

In short, I have time data from 2012 to 2018. I used (not in this example) I divided my training dataset from 2012 to 2017. I used the year 2018 to test the model (evaluate). But now I want to make predictions (with my trained model) of these data for the year 2019. How does it do? I would have to create an empty vector of size "Z" (Shape of the predictions I want) and use it in model.predict?

Below follows my code.

Grateful for the attention.

from keras.models import Sequential
from keras.layers import Dense
from keras.layers import LSTM
from numpy import array
from keras.models import load_model
import numpy as np
from sklearn.metrics import mean_absolute_error
import matplotlib.pyplot as plt

# return training data
def get_train():
    seq = [[0.0, 0.1], [0.1, 0.2], [0.2, 0.3], [0.3, 0.4], [0.4, 0.5]]
    seq = array(seq)
    X, y = seq[:,0], seq[:, 1]
    X = X.reshape((len(X), 1, 1))
    return X, y

# define model
model = Sequential()
model.add(LSTM(10, input_shape=(1,1)))
model.add(Dense(1, activation='linear'))
# compile model
model.compile(loss='mse', optimizer='adam')
# fit model
X,y = get_train()
model.fit(X, y, epochs=300)
# save model to single file
model.save('lstm_model.h5')

# load model from single file
model = load_model('lstm_model.h5')
# make predictions
previsao = model.predict(X, verbose=0)
print(previsao)

#Plotagem Previsões
plt.plot(y, color = 'red', label = 'Gravidade Real')
plt.plot(previsao, color = 'blue', label = 'Previsoes')
plt.title('Previsões')
plt.xlabel('Prev_Gravidade')
plt.ylabel('Gravidade Real')
plt.legend()
plt.show()

1 answer

1


If your 2019 samples are in the same input format as the ones used for training and testing, you can either create a list of arrays with all or make one for and go playing one by one on the forecast and go saving the results.

To documentation of the Keras says the following about the prediction function: x: The input data, as a Numpy array (or list of Numpy arrays if the model has multiple inputs)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.