LSTM and GRU Networks

Deep Learning with Keras and TensorFlow 11 min min read Updated: Nov 16, 2026 Intermediate
LSTM and GRU Networks
Intermediate Topic 5 of 9

The Memory Problem

A simple RNN forgets old information. LSTM (Long Short-Term Memory) and GRU (Gated Recurrent Unit) add gates, small controllers that decide what to remember, what to forget and what to output.

Simple example: Think of a notebook. At each step you decide: should I erase something (forget gate), write something new (input gate) and what should I read out loud (output gate)? An LSTM has such a notebook, called the cell state, that runs through the whole sequence.
LayerGatesSpeedUse
LSTMForget, input, outputSlowerLong sequences, strong default
GRUReset, updateFaster, fewer parametersSmaller data, quick experiments

LSTM Text Classifier

python import keras from keras import layers model = keras.Sequential([ keras.Input(shape=(250,), dtype="int32"), layers.Embedding(20000, 64, mask_zero=True), # ignore padding layers.LSTM(64), layers.Dropout(0.3), layers.Dense(1, activation="sigmoid"), ]) model.compile(optimizer="adam", loss="binary_crossentropy", metrics=["accuracy"])

GRU Version

python model = keras.Sequential([ keras.Input(shape=(250,), dtype="int32"), layers.Embedding(20000, 64, mask_zero=True), layers.GRU(64), layers.Dense(1, activation="sigmoid"), ])

Bidirectional Layers

Sometimes the meaning of a word depends on words that come later. A bidirectional layer reads the sequence forward and backward and joins both results.

python layers.Bidirectional(layers.LSTM(64)) model = keras.Sequential([ keras.Input(shape=(250,), dtype="int32"), layers.Embedding(20000, 64, mask_zero=True), layers.Bidirectional(layers.LSTM(64, return_sequences=True)), layers.Bidirectional(layers.LSTM(32)), layers.Dense(1, activation="sigmoid"), ])

Useful Tips

  • Use return_sequences=True for every recurrent layer except the last one when stacking
  • Use dropout=0.2, recurrent_dropout=0.2 options inside the layer to reduce overfitting (recurrent dropout is slower)
  • Use clipnorm=1.0 in the optimizer if the loss becomes NaN
  • Keep sequences as short as the task allows, since long sequences train slowly
python layers.LSTM(64, dropout=0.2, return_sequences=True)

When to Use What

TaskGood choice
Short text classificationEmbedding + pooling or one Bidirectional GRU
Time series forecastingLSTM or GRU
Long documents, translation, chatbotsTransformers (later lesson)

Conclusion

LSTM and GRU are the workhorses of sequence modeling. They remember much longer than simple RNNs and are easy to use in Keras.

Quick Summary: LSTM and GRU use gates for memory. Add Bidirectional for context in both directions and mask_zero for padding.

Get Newsletter

Subscibe to our newsletter and we will notify you about the newest updates on Edugators