liveBook · Manning

LSTM

As explained in Deep Learning with R, Third Edition

Long short-term memory is a gated recurrent-neural-network architecture designed to preserve and control information across sequence timesteps.

Long short-term memory (LSTM) is a recurrent neural network architecture for sequences where order matters. It processes one timestep at a time, maintaining state that can carry information forward. This makes it useful for tasks such as forecasting temperature from past measurements or classifying ordered text. section 13.3 section 14.5.5 section 20.1.6

Listing 13.13 A simple LSTM-based model
inputs <- keras_input(shape = c(sequence_length, ncol_input_data))
outputs <- inputs |>
  layer_lstm(16) |>
  layer_dense(1)
model <- keras_model(inputs, outputs)

callbacks <- list(
  callback_model_checkpoint("jena_lstm.keras", save_best_only = TRUE)
)

compile(model, optimizer = "adam", loss = "mse", metrics = "mae")history <- model |> fit(
  train_dataset,
  epochs = 10,
  validation_data = val_dataset,
  callbacks = callbacks
)model <- load_model("jena_lstm.keras")
sprintf("Test MAE: %.2f", evaluate(model, test_dataset)[["mae"]])

[1] "Test MAE: 2.52"

A temperature-forecasting model uses a 16-unit LSTM followed by a dense layer. It trains with mean squared error, tracks mean absolute error (MAE), and reloads the best checkpoint for evaluation; the listing reports a test MAE of 2.52 degrees. section 13.3

Unlike a model that first flattens a timeseries, an LSTM works with the sequence as a sequence. In the temperature example, it beat the commonsense baseline, although only slightly. Establishing such a baseline helps determine whether the extra model complexity is worthwhile. section 13.3 section 13.5

A simple recurrent layer can struggle to learn dependencies across many timesteps because of vanishing gradients. An LSTM adds a carry track: at each step, computations control how much existing information to retain and how much new information to add. The resulting state helps carry information across the sequence. section 13.3.2

Figure 13.9 Anatomy of an LSTM
figure

The architecture diagram shows the LSTM’s carry track and its relationship to the recurrent output. section 13.3.2

When using an LSTM layer in Keras:

  • Provide input with shape (batch_size, timesteps, input_features). Set the timestep entry to NA for variable-length sequences; a complete shape can enable output-length reporting and performance optimizations. section 13.3.2
  • Use return_sequences = TRUE to return an output for every timestep; otherwise the layer returns only the last output. Every recurrent layer before another recurrent layer in a stack must return the full sequence. section 13.3.2 section 20.1.6
  • Compare a single layer with a stack only when the added representational power justifies the expense. GRU is a simpler, cheaper alternative to LSTM. section 13.5 section 20.1.6
inputs <- keras_input(shape = c(num_timesteps, num_features))
outputs <- inputs |>
  layer_lstm(32, return_sequences = TRUE) |>
  layer_lstm(32, return_sequences = TRUE) |>
  layer_lstm(32) |>
  layer_dense(1, activation = "sigmoid")
model <- keras_model(inputs, outputs)
model |> compile(optimizer = "rmsprop", loss = "binary_crossentropy")

This stacked classifier returns full sequences from its first two LSTM layers and only the final output from the last. section 20.1.6

Classifying movie reviews

A text classifier can pass token sequences through an embedding layer, a bidirectional LSTM, dropout, and a sigmoid output. Initializing the embedding with pretrained CBOW weights brought its performance roughly in line with set-based models. Ordered sequence models can still be data-hungry, so a simpler baseline may be preferable when data or compute is limited. section 14.5.5

Listing 14.28 Building an LSTM sequence model with an Embedding layer
inputs <- keras_input(shape = c(max_length), dtype = "int32")
lstm_embedding <- layer_embedding(
  input_dim = max_tokens,
  output_dim = hidden_dim,
  mask_zero = TRUE
)
outputs <- inputs |>
  lstm_embedding() |>
  layer_bidirectional(layer_lstm(units = hidden_dim)) |>
  layer_dropout(0.5) |>
  layer_dense(1, activation = "sigmoid")

model <- keras_model(inputs, outputs, name = "lstm_with_cbow")

The classifier’s R Keras model combines an embedding layer with a bidirectional LSTM. section 14.5.5

How Deep Learning with R, Third Edition covers it

How deep it goes
Explains recurrent input and output shapes, stacking, and the LSTM carry track, with architecture pseudocode.
Examples
Demonstrates Jena temperature forecasting and movie-review classification with a pretrained CBOW embedding.
What you can do after
Apply it via R Keras to build, train, and evaluate sequence models, including stacked and bidirectional variants.
How it connects
Connects LSTMs to vanishing gradients, GRUs, recurrent networks, and pretrained word embeddings.

Also explained in

Compare how 8 books explain LSTM →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Deep Learning with R, Third Edition. The section links point to the parts of the book it draws on.