LSTM simplest example in python

description: simplest example for LSTM ANN in python

import packages

1
2
3
4
5
import numpy
from keras.models import Sequential
from keras.layers import Dense
from keras.layers import LSTM
import matplotlib.pyplot as plt

initial dataset

1
2
3
4
test_set = [0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8]
dataset = []
for i in range(1, 100):
dataset.append(i%10/10)

transform data into [current_data, next_data]

1
2
3
4
5
6
dataX, dataY = [], []
for i in range(len(dataset) - 2):
dataX.append(dataset[i])
dataY.append(dataset[i + 1])
dataX = numpy.array(dataX)
dataY = numpy.array(dataY)

reshape data

1
dataX = numpy.reshape(dataX, (dataX.shape[0], 1, 1))

create and fit the LSTM network

1
2
3
4
5
model = Sequential()
model.add(LSTM(4, input_shape=(1, 1)))
model.add(Dense(1))
model.compile(loss='mean_squared_error', optimizer='adam')
model.fit(dataX, dataY, epochs=10, batch_size=1, verbose=2)

make predictions

1
2
3
test = numpy.array(test_set)
test = numpy.reshape(test, (test.shape[0], 1, 1))
trainPredict = model.predict(test)

plot baseline and predictions

1
2
3
plt.plot(test_set)
plt.plot(trainPredict)
plt.show()