RNNs Explained: How Neural Networks Understand Sequential Data
From the publisher’s feed, collected in the ZeroLabs newsroom.
CNNs learned to look at images. RNNs learn to read, listen and follow along.IntroductionIn the last article, CNNs showed us how a network can understand where things are in an image. But some data isn’t about space at all. It’s about order. Read this sentence backwards and it stops making sense. Shuffle a week of stock prices and the trend disappears.CNNs learn spatial patterns in images. RNNs are designed for information where the order matters.That kind of data is called sequential data, and it’s everywhere:• Sentences and text• Time series and stock prices• Speech and audio• Sensor data• Weather measurementsThe network built for it is the Recurrent Neural Network (RNN). Let’s see how it works.What is sequential data?Sequential data is information that comes in a specific order, where each item depends on what came before it. Take a simple sentence:Same words, different order, different meaning.The individual words are identical in both rows. What changed is the order, and with it, everything. An RNN is built around this idea: it processes information one step at a time, while carrying along what it has learned from earlier steps.Why regular neural networks struggle with sequencesA traditional neural network, like the ones from our earlier articles, has some awkward limits when it comes to sequences:• It treats each input independently. Once one input is processed, it’s forgotten.• It has no built-in memory of previous inputs.• It expects a fixed input size, but sentences and recordings come in all lengths.Earlier information often matters for understanding what’s happening now.To fill the blank, the model has to remember something said much earlier.“I speak fluent ___” is almost impossible to complete without knowing the speaker grew up in France. We need a network that can remember.What is an RNN?An RNN is a neural network designed to process sequential data by carrying information from previous time steps to the current step.The trick is a loop. At every step the network takes in the new input and also its own hidden state from the previous step, a compact summary of everything it has seen so far. Then it updates that hidden state and passes it on.On the left, the RNN with its loop. On the right, the same thing “unrolled” across time.The idea of memoryThis is the concept to hold on to. At each step:Current input plus previous memory produces new memory.The hidden state acts as a running summary of the information from previous steps.Think of reading a book and keeping a short note in your head: “so far, the detective suspects the butler.” With each new page you update that note rather than re-reading the whole book. The hidden state is that note.RNN architectureAn RNN has three main pieces: the input xₜ at time step t, the hidden state hₜ, and (optionally) an output yₜ. Here’s how one step works:One RNN step: mix the new input with the old memory, squash it, and pass it on.hₜ = f( Wx · xₜ + Wh · hₜ₋₁ + b )• xₜ: the current input• hₜ₋₁: the previous memory• hₜ: the new, updated memory• Wx, Wh: learnable weights (one set for the input, one for the memory)• b: the bias• f: an activation function, usually tanhLet’s run it with tiny numbers. Let Wx = 0.5, Wh = 0.8, b = 0 and start with h₀ = 0. Feed in the sequence 1, 2, 3:h₁ = tanh(0.5×1 + 0.8×0 ) = tanh(0.50) = 0.462h₂ = tanh(0.5×2 + 0.8×0.462 ) = tanh(1.37) = 0.879h₃ = tanh(0.5×3 + 0.8×0.879 ) = tanh(2.20) = 0.976Notice that h₂ is not just a function of the input 2. It also carries a trace of the earlier input 1. That’s memory in action, in three lines of arithmetic.Unrolling an RNN through timeAn RNN isn’t really a long chain of different networks. It’s one network applied again and again. Unrolling just lets us draw each time step separately:Four time steps, one set of weights.The weights are shared across time steps.That sharing is important for two reasons. It keeps the parameter count small, and it lets the same RNN handle sequences of any length, because we just repeat the step as many times as we need.How does an RNN learn?What is BPTT?Backpropagation Through Time (BPTT) is the method used to train an RNN by propagating errors backward through its sequence of time steps.the end is traced back through every step that contributed to it.Because h₄ depends on h₃, which depends on h₂, which depends on h₁, an error at the end of the sequence traces back through all of them. It’s exactly the chain rule from Article #3, stretched along the time axis. And since the weights are shared, the gradients from all the time steps are added together to update the same weights.Different types of RNN applicationsDepending on the task, the inputs and outputs can be arranged in a few different ways:Blue circles are inputs, squares are RNN steps, green circles are outputs.• One-to-one: a single input, a single output. This is a plain neural network.• One-to-many: one input produces a sequence. Example: image → caption.• Many-to-one: a sequence produces one output. Example: text → sentiment.• Many-to-many: a sequence in, a sequence out. Example: machine translation.Example: sentiment analysisTake the sentence “The movie was absolutely amazing.” The RNN reads it one word at a time, updating its memory after each word. Only at the end does it produce a verdict:A many-to-one RNN reads the whole sentence before deciding.Each word nudges the hidden state. “absolutely” intensifies whatever comes next, and “amazing” tips the balance. By the final step the hidden state holds a summary of the whole sentence, and that summary is what produces “Positive.”Example: next-word predictionNow a many-to-many setup. After every word, the RNN predicts what comes next.Given “I am learning”, the most likely next word might be “deep”. Then given “I am learning deep”, the natural next word is “learning”. The previous words provide the context that makes the prediction sensible. This is also the basic idea behind language models.The problem with long-term dependenciesBasic RNNs have one famous weakness. Consider:“I grew up in India. … [many words later] … I speak fluent ___.”The clue is far back in the sequence. A short-term dependency is when the relevant information is only a few steps away (easy for an RNN). A long-term dependency is when it’s many steps away, and that’s where basic RNNs struggle. The memory gets overwritten a little at every step, and the faint trace of an early word can be gone by the time we need it.Vanishing gradientsThe reason is mathematical, and it shows up during BPTT. To send the error back through ten time steps, the gradient is multiplied by a factor at every step. If that factor is smaller than 1, the signal shrinks again and again:Gradient → × small → × small → × small → … → almost zeroWith a factor of 0.5 per step, after 10 steps the gradient is only 0.⁵¹⁰ ≈ 0.001, about a thousandth of its original size. The earliest time steps get almost no learning signal, so the network can’t learn to connect them to the outcome.Exploding gradientsThe opposite can happen too. If the repeated factor is larger than 1, the gradient grows instead:Gradient → × large → × large → × large → … → hugeWith a factor of 2 per step, ten steps back gives ²¹⁰ = 1,024 times the original gradient. That leads to unstable training, enormous weight updates, and sometimes a loss that turns into NaN. A common fix is gradient clipping: if the gradient gets bigger than a chosen threshold, scale it down before applying the update. Vanishing gradients are harder to fix, which is what motivated the LSTM in the next article.Advantages of RNNs• Designed for sequential data.• Maintain information from previous steps.• Can handle variable-length sequences.• Useful for time-dependent problems.Limitations of RNNs• Difficulty with long-term memory.• Vanishing gradients.• Exploding gradients.• Sequential computation can be slow, since step 5 must wait for step 4.Hard to parallelize across time steps.A simple Python exampleLet’s teach a tiny RNN to continue a pattern: given [10, 20, 30, 40], predict 50. We’ll train on many sequences that climb by a constant step, but deliberately leave out the exact [10, 20, 30, 40] one so we can test on it.import numpy as npimport tensorflow as tffrom tensorflow.keras import layers, models, optimizers# 1) Build training data: 4 numbers in, the next number outX, y = [], []for start in range(1, 21):for step in range(1, 11):if (start, step) == (10, 10): # held out for testingcontinueseq = [start + step * i for i in range(4)]X.append(seq)y.append(start + step * 4)# Shape must be (samples, time steps, features); scale to small valuesX = np.array(X, dtype=”float32")[…, None] / 100.0y = np.array(y, dtype=”float32") / 100.0# 2) Create the RNNmodel = models.Sequential([layers.Input(shape=(4, 1)),layers.SimpleRNN(16), # the recurrent layer with 16 hidden unitslayers.Dense(1), # turns the final hidden state into a number])model.compile(optimizer=optimizers.Adam(0.01), loss=”mse”)# 3) Trainmodel.fit(X, y, epochs=300, batch_size=32, verbose=0)# 4) Predict on the unseen sequencetest = np.array([[10, 20, 30, 40]], dtype=”float32")[…, None] / 100.0print(model.predict(test)[0, 0] * 100) # should be close to 50A few details worth understanding. The data shape (samples, time steps, features) is how Keras expects sequences. The SimpleRNN(16) layer has 16 × 1 input weights, 16 × 16 recurrent weights and 16 biases, which is 288 parameters in total. And scaling the numbers down matters, because large raw values push tanh into its flat regions where learning stalls. The prediction should land close to 50 but won’t be exactly 50. If it’s well off, train for more epochs.Want to see clipping? Change the optimizer to optimizers.Adam(0.01, clipnorm=1.0).Where are RNNs used?• Speech recognition• Sentiment analysis• Text generation• Time-series forecasting• Language modeling• Sequence classification• Machine translationA note on the present day: because of the limits above, many modern systems use LSTMs, GRUs and Transformers instead of basic RNNs, especially where long-range memory matters. Basic RNNs are still the best place to learn the core idea.Common beginner questionsWhat is the hidden state? A vector of numbers that summarizes everything the network has seen so far in the sequence.Is hidden state the same as memory? Roughly, yes, as an analogy. But it’s a compressed, constantly overwritten summary, not a filing cabinet of exact past inputs.Why are RNN weights shared? So the same learned rule applies at every time step. It keeps the model small and lets it handle sequences of any length.What is BPTT? Backpropagation applied to the unrolled network, sending the error back through each time step.Why do RNNs have vanishing gradients? Because the gradient is multiplied by similar factors at every step going back, and repeated multiplication by numbers below 1 shrinks it toward zero.Can RNNs remember everything? No. Basic RNNs mostly remember recent information well and distant information poorly.RNN vs CNN? CNNs find local patterns in grids like images. RNNs process ordered sequences with a running memory.RNN vs LSTM? An LSTM is an RNN with extra machinery (gates) that decides what to keep, forget and output, which helps it remember over long distances.ConclusionRNNs introduced the idea of giving neural networks a form of memory, allowing them to process information where sequence and order matter.But basic RNNs struggle to hold on to information over long sequences. So how could we build a network that can decide what to remember, what to forget, and what to use?RNNs Explained: How Neural Networks Understand Sequential Data was originally published in Towards AI on Medium, where people are continuing the conversation by highlighting and responding to this story.