Recurrent Neural Networks: Giving a Model a Memory
Try finishing this sentence: "I grew up in Spain, so I speak fluent ..."
You said Spanish, almost certainly. And the reason you got there is the word "Spain" appearing several words earlier. You carried it along while you read the rest. That ability to hold onto what came before is exactly what a recurrent neural network, or RNN, tries to give a machine.
When order matters
Some data comes as a sequence where the order carries meaning: words in a sentence, notes in a melody, daily temperatures, heartbeats on a monitor, stock prices. "Dog bites man" and "man bites dog" contain the same words and mean very different things.
A model that takes a fixed-size set of numbers all at once has trouble here. Sequences vary in length, and the meaning of each item depends on what surrounded it. We need something that reads step by step and remembers.
The core idea
An RNN reads a sequence one element at a time. At each step it does two things:
- Looks at the current input.
- Looks at its own hidden state, a summary of everything it has seen so far. It blends the two and produces a new hidden state, which gets handed to the next step:
text
h_t = tanh(W * x_t + U * h_(t-1) + b)
Here x_t is the input at time t, h_(t-1) is the memory from the previous step, and h_t is the updated memory. The output at each step (a predicted next word, say) is computed from h_t.
One detail is easy to miss: the same weights W, U and b are used at every step. The network isn't a different machine for each position. It's one small unit applied over and over, which is why it handles sequences of any length.
Unrolling it
A helpful way to picture an RNN is to "unroll" it. Write one copy of the unit for each time step, with the hidden state flowing from left to right like a baton in a relay. Drawn this way it looks like a very deep network, with one layer per time step and shared weights across all of them.
Different shapes of problem
RNNs are flexible about what goes in and what comes out:
- Many to one: read a whole sequence, give one answer. Example: classify a movie review as positive or negative.
- One to many: take one input, generate a sequence. Example: write a caption for an image.
- Many to many (aligned): an output for every input. Example: label each word in a sentence as a noun, verb and so on.
- Many to many (encoder-decoder): read a full sequence, then produce a different one. Example: translate a sentence. ## Training and where it hurts
Training uses backpropagation through time: the loss is computed, and then gradients are passed backwards along the unrolled network, one step after another.
Here's the snag. Going backwards through many steps means multiplying many numbers together. If those numbers are smaller than 1, the product shrinks toward zero, and the gradient vanishes. If they're larger than 1, it explodes. The result is that a basic RNN struggles to connect something from the start of a long passage to something much later. It has a memory, but a short one.
Exploding gradients have a simple remedy called gradient clipping: if the gradient is too big, scale it down. Vanishing gradients needed a smarter design.
LSTM and GRU
The Long Short-Term Memory unit, or LSTM, was invented to fix the memory problem. Alongside the hidden state it keeps a separate cell state, a kind of conveyor belt that information can ride along with only small, controlled changes. Three gates, each a little learned switch between 0 and 1, control the traffic:
- The forget gate decides what to erase from the cell state.
- The input gate decides what new information to write.
- The output gate decides what to reveal as the hidden state. Because the cell state can pass through many steps almost unchanged, gradients survive the trip back, and the network can learn dependencies that span hundreds of steps.
The GRU (Gated Recurrent Unit) is a streamlined cousin with two gates and no separate cell state. It has fewer parameters, trains faster, and often performs about as well. A sensible habit is to try both.
A short code example
python
import torch
import torch.nn as nn
class SentimentLSTM(nn.Module):
def init(self, vocab_size, embed_dim=64, hidden_dim=128):
super().init()
self.embed = nn.Embedding(vocab_size, embed_dim)
self.lstm = nn.LSTM(embed_dim, hidden_dim, batch_first=True)
self.fc = nn.Linear(hidden_dim, 1)
def forward(self, tokens):
x = self.embed(tokens)
_, (h_n, _) = self.lstm(x)
return torch.sigmoid(self.fc(h_n[-1]))
Words become vectors through an embedding, the LSTM reads them in order, and the final hidden state feeds a single output that says positive or negative.
Useful variations
- Bidirectional RNNs read the sequence both forwards and backwards, so each position gets context from before and after. Great for tagging and classification, but not for live prediction, since you can't see the future.
- Stacked RNNs put several recurrent layers on top of one another to learn more abstract patterns.
- Teacher forcing is a training trick for generators: feed the true previous word instead of the model's own guess, which speeds up learning.
Where RNNs still earn their keep
Speech recognition, handwriting recognition, music generation, anomaly detection in sensor streams, and forecasting of all sorts. They're particularly comfortable on small devices and in streaming settings, where data arrives piece by piece and you want to update a compact state rather than reprocess everything.
Honest downsides
They're inherently sequential: step 50 can't be computed until step 49 is done, so training doesn't parallelize well. Very long-range dependencies are still hard, even for LSTMs. And they need careful tuning of sequence length, batch construction and padding.
Takeaways
- An RNN processes a sequence step by step, carrying a hidden state as memory.
- The same weights are reused at every step.
- Plain RNNs suffer from vanishing and exploding gradients.
- LSTM and GRU gates let the memory last much longer.
- Choose the input-output shape (many-to-one, many-to-many and so on) to match your task.
Top comments (0)