Long Short-Term Memory (LSTM)

Machine Learning
Introduced by
Hochreiter, S. & Schmidhuber, J.
Year
1997
Type
Recurrent neural network with gated memory cells
Family
Deep learning / NLP / CV

What does it do?

Long Short-Term Memory (LSTM) is a gated recurrent neural network architecture introduced by Hochreiter and Schmidhuber in 1997.

It was designed to address the difficulty that plain recurrent networks have in learning dependencies across long sequences. It does this by routing information through a dedicated memory cell, whose contents are controlled by multiplicative gates. The widely used modern form has forget, input, and output gates; the forget gate was added to the original design in later work.

The intuition behind the method

A plain recurrent network carries information through time by repeatedly reusing a single hidden state. The 1997 paper attributes the failure on long time lags to insufficient, decaying error backflow during training, so dependencies that span many steps are hard to learn. An LSTM keeps a separate cell state that can carry information forward largely unchanged. In the common modern formulation, the forget gate decides which stored content to erase, the input gate decides which new content to write, and the output gate decides how much of the cell is exposed as the hidden state. Because the cell update is additive, the gradient path through the cell state is more stable across steps than in a vanilla recurrent network, which is what allows the network to learn patterns that span long stretches of a sequence.

History

Hochreiter and Schmidhuber introduced the LSTM in 1997 as a gradient-based method to overcome the insufficient, decaying error backflow that prevents recurrent networks from learning long time lags. The forget gate found in most modern implementations was added in later work. Graves, Mohamed and Hinton (2013) applied deep LSTM recurrent networks to speech recognition and reported a 17.7% phoneme error on the TIMIT benchmark. Transformer-based models later displaced LSTMs on many sequence tasks, although LSTMs remain in use in time-series and resource-constrained settings.

When to use it

Choose an LSTM when the order of observations matters, relevant context may extend over many steps, and the training data is large enough to fit the recurrent parameters. Typical examples include text classification, sequence labelling, machine translation, time-series forecasting, and speech processing. Sequences from tens of steps up to a few hundred are a common practical range, although the 1997 paper reports learning time lags longer than 1000 steps on artificial tasks, so sequence length alone is not a hard limit. When highly parallel training matters and sequences are of moderate length, a Transformer is usually preferable; long-context Transformers have their own computational cost trade-offs. For smaller models with fewer parameters, a GRU may be preferable, and for many text tasks a pretrained model fine-tuned on the target data may outperform an LSTM trained from scratch.

Limitations and considerations

  • Recurrence forces computation to proceed step by step through the sequence, so training parallelises much less well than Transformer models.
  • Each gate has its own weight matrix over the concatenated hidden state and input, so parameter count grows with hidden size, and hidden units, layers, dropout, and learning rate all need tuning.
  • The cell state is a fixed-size vector, so memory capacity is limited by the hidden size and dependencies that must compete for that capacity can still be lost in practice, even though the 1997 paper reports bridging lags over 1000 steps on artificial tasks.
  • On small datasets the model tends to overfit despite dropout.
  • For many NLP tasks, pretrained Transformer models have displaced LSTMs trained from scratch.

Source conditions do not replace independent scientific review or validation by an analysis engine.

Strengths

  • The additive cell-state update lets gradients propagate across many time steps more readily than in a vanilla recurrent network, which is the core motivation of the 1997 design.
  • The learned gates let the layer decide what to retain, write, and expose. Gate activations can be recorded and examined, but their interpretation is not guaranteed and should be checked empirically.
  • Output configuration is flexible: the same layer can return the final state for sequence classification or all states for per-step labelling and generation.
  • A bidirectional variant processes the sequence in both directions when the full input is available before prediction.
  • The 1997 paper reports constant computational complexity per time step and weight, and Graves, Mohamed and Hinton (2013) reported a 17.7% test-set error on TIMIT phoneme recognition with deep LSTM recurrent networks.

Applications

  • Text classification and sentiment analysis on documents or reviews.
  • Sequence labeling: named-entity recognition, part-of-speech tagging.
  • Time-series forecasting: stock prices, sensor readings, energy demand.
  • Speech recognition as an acoustic model component.
  • Machine translation via encoder-decoder LSTM architectures.
  • Anomaly detection in sequential log or sensor data.

How it works

How it works

1

In the standard modern formulation, the forget gate takes the previous hidden state and the current input, applies a sigmoid, and produces a value between 0 and 1 for each cell-state element. Values near 0 erase that element from memory, and values near 1 keep it. Because the gate is learned, the network decides which past context to discard. This gate was not part of the original 1997 design, which used multiplicative input and output gates around a constant error carousel; it was introduced in later work.

Formula
f_t = \sigma(W_f [h_{t-1}, x_t] + b_f)
2

The input gate, also sigmoid-activated, scales the candidate cell state, which is computed from the same inputs through a tanh. Their product determines what new information is written into the cell. Together with the forget gate, this lets the cell keep some earlier content while admitting new content.

Formula
i_t = \sigma(W_i [h_{t-1}, x_t] + b_i),\quad \tilde{c}_t = \tanh(W_c [h_{t-1}, x_t] + b_c)
3

The new cell state is the old cell state multiplied elementwise by the forget gate, plus the input-gated candidate. Because this memory path is additive rather than a repeated multiplication by a weight matrix, gradients can propagate across many time steps more readily than in a vanilla recurrent network. The 1997 paper describes the underlying mechanism as constant error flow through constant error carousels, and in the modern formulation this constant-flow behaviour holds most closely when the forget gate is near 1.

Formula
c_t = f_t \odot c_{t-1} + i_t \odot \tilde{c}_t
4

The output gate controls how much of the tanh-squashed cell state is passed out as the hidden state for the next time step and for the layer above. Separating the internal memory from the exposed hidden state gives the layer more flexibility in how it uses its memory.

Formula
o_t = \sigma(W_o [h_{t-1}, x_t] + b_o),\quad h_t = o_t \odot \tanh(c_t)
5

Depending on the task, the layer can return the final hidden state, the hidden state at every time step, or both. A task-specific output layer then maps the hidden state to predictions, for example y_t = W_y h_t followed by the output nonlinearity suited to the task. Sequence classification typically uses the final state, while labelling and translation typically use the per-step states. Stacking LSTM layers and applying dropout between them are common ways to add capacity and regularisation, although the benefit depends on the data.

Formula
y_t = f_y(W_y h_t + b_y)

Common pitfalls

  • Feeding variable-length sequences to an LSTM without padding and masking, so that padded zeros enter the hidden state and the loss.
  • Leaving dropout active at inference time, which makes predictions stochastic and inconsistent with validation results.
  • Training without gradient clipping; the gating reduces vanishing gradients but does not remove the risk of exploding gradients.
  • Using only the final hidden state for per-token labelling tasks, which yields a single output per sequence rather than one per time step.
  • Treating a unidirectional LSTM as sufficient for tasks where future context is available at prediction time, such as sequence labelling of a complete input.
  • Splitting time-series or sensor data randomly, or fitting normalisation statistics on all the data, which leaks future information into training and inflates validation results.

Frequently asked questions

What is the difference between LSTM and GRU?

A GRU merges the forget and input gates into a single update gate and has no separate cell state, giving it fewer parameters and often faster training. Reported comparisons between LSTM and GRU are mixed and depend on the dataset, so compare both on validation data.

Should I use a bidirectional LSTM?

If your task allows access to the full sequence before making predictions, such as classification, sequence labelling, or offline forecasting, a BiLSTM can improve accuracy by incorporating both past and future context. If predictions must be made in real time, as in online forecasting or streaming, use a unidirectional LSTM.

When should I choose a Transformer over an LSTM?

For many modern NLP tasks with sufficient compute, pretrained Transformers such as BERT and RoBERTa tend to outperform LSTMs trained from scratch. An LSTM is a reasonable choice when compute or latency is constrained, when the sequences are numerical time series rather than text, or when the labelled data is too limited to fine-tune a large pretrained model.

How do I handle variable-length sequences?

Pad shorter sequences to a common length, create a mask so that padding tokens are ignored in the loss, and use packed sequences (PyTorch) or masking layers (Keras/TensorFlow) so that padded positions do not affect the hidden state.

How should I choose the number of layers and hidden units?

Start with a small network and increase capacity only if validation performance shows underfitting. More layers and units add capacity but also training time and the risk of overfitting, so use dropout between layers and check performance on a held-out validation set or with cross-validation.

Related methods

Sources

  1. Hochreiter, S. & Schmidhuber, J. (1997). Long short-term memory. Neural Computation, 9(8), 1735–1780.

    Open DOI reference
  2. Graves, A., Mohamed, A.-R. & Hinton, G. (2013). Speech recognition with deep recurrent neural networks. Proceedings of ICASSP 2013, pp. 6645–6649. IEEE.

    Open DOI reference