LSTM and GRU Networks
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.
| Layer | Gates | Speed | Use |
|---|---|---|---|
| LSTM | Forget, input, output | Slower | Long sequences, strong default |
| GRU | Reset, update | Faster, fewer parameters | Smaller 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=Truefor every recurrent layer except the last one when stacking - Use
dropout=0.2, recurrent_dropout=0.2options inside the layer to reduce overfitting (recurrent dropout is slower) - Use
clipnorm=1.0in 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
| Task | Good choice |
|---|---|
| Short text classification | Embedding + pooling or one Bidirectional GRU |
| Time series forecasting | LSTM or GRU |
| Long documents, translation, chatbots | Transformers (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.

