An LSTM (long short-term memory) layer is a recurrent neural network layer for ordered data. It processes a sequence one timestep at a time while maintaining state, making it useful when earlier inputs matter to later predictions. In temperature forecasting, flattening the timeseries discarded its temporal structure; an LSTM preserved it and beat the commonsense baseline. section 13.3 section 20.1.6
Forecast temperature with an LSTM
In R/Keras, a compact model is `inputs <- keras_input(shape = c(sequence_length, ncol_input_data)); outputs <- inputs |> layer_lstm(16) |> layer_dense(1); model <- keras_model(inputs, outputs)`. Compile it with Adam, mean squared error loss, and mean absolute error (MAE) as a metric. Train against a validation dataset, save the best checkpoint, then evaluate it on the test dataset. The saved model produced a test MAE of 2.52 degrees. section 13.3
Two choices shape how a recurrent layer fits into a model:
- Inputs have shape `(batch_size, timesteps, input_features)`. Use an unspecified timestep dimension for variable-length sequences; specify the length when it is fixed to make output shapes clearer and potentially improve performance. section 13.3.2
- Return the last output for a single sequence-level prediction. Set `return_sequences = TRUE` on every LSTM that feeds another recurrent layer, so the next layer receives an output at each timestep. section 13.3.2 section 20.1.6
The simpler `SimpleRNN` struggles to learn long-term dependencies because of vanishing gradients. An LSTM adds a carry track whose next value combines new information with retained information: `c_t+1 = i_t * k_t + c_t * f_t`. Its learned components control those contributions rather than relying only on a repeatedly updated simple state. section 13.3.2
Listing 13.22 Pseudocode details of the LSTM architecture (2/2)
c_t+1 = i_t * k_t + c_t * f_t
The carry-track update shows how an LSTM combines a new contribution with information retained from the preceding timestep. section 13.3.2
LSTMs also accept sequences of word embeddings. For movie-review classification, a bidirectional LSTM with a pretrained CBOW embedding reached about 0.891 test accuracy. That result was slightly below a bigram model: learning from word order can demand more training data. For a cheaper recurrent alternative, consider GRU; for difficult long-text dependencies, Transformers offer another approach. Compare each against a simple baseline before paying for a larger model. section 14.5.5 section 20.1.6 section 14.1 section 13.5







