Day 66 of 100DaysofML

Charan Soneji
100DaysofMLcode
Published in
2 min readSep 2, 2020

LSTM model implementation. So for the given IOT model from yesterday’s blog, I thought of talking about the implementation of the LSTM model. I shall discuss more about LSTM in the upcoming blogs but today I shall explain the implementation.

We need to prepare dataset as a 3D matrix for LSTM from [samples, timesteps] to [samples, timesteps, features] . Here, we have only 1 feature i.e., use, and timesteps are the sequence of steps, here, we choose 28 timesteps and the output timesteps to predict as 16, because we need to validate on the Test set.

# define input sequence
raw_seq = train[:307].values.tolist()
# choose a number of time steps
n_steps_in, n_steps_out = 28, 16
# split into samples
X, y = split_sequence(raw_seq, n_steps_in, n_steps_out)
# reshape from [samples, timesteps] into [samples, timesteps, features]
n_features = 1
X = X.reshape((X.shape[0], X.shape[1], n_features))

The link to the dataset shall be mentioned below but it is the same as the one mentioned yesterday.

The next step would be to implement and create the model.

#LSTM model
model = Sequential()
model.add(LSTM(100, activation='relu', return_sequences=True, input_shape=(n_steps_in, n_features)))
model.add(LSTM(100, activation='relu'))
model.add(Dense(n_steps_out))
model.compile(optimizer='adam', loss='mse')
# fit model
model.fit(X, y, epochs=50, verbose=0)

We have added the respective activation functions needed and the layers needed by the neural net. The next step would be to check the predictions.

# demonstrate prediction
x_input = train[307:].values
x_input = x_input.reshape((1, n_steps_in, n_features))
yhat = model.predict(x_input, verbose=0)
print(yhat)
Predicted values using LSTM

Plot the predictions in order to visualize the consumption.

yhat=yhat.reshape(16,1)
forecast = pd.DataFrame(yhat,index = test.index,columns=['Prediction'])
#plot the predictions for validation set
plt.figure(figsize=(16,8))
plt.plot(test, label='Valid')
plt.plot(forecast, label='Prediction')
plt.show()
Predicted model graph

You can experiment with the model by changing the parameters or modifying the neural net that has been defined. The link to the dataset is given below:

The link to the notebook is given below:

That’s it for today. Thanks for reading. Keep Learning.

Cheers.

--

--