Recurrent Neural Networks: Sequential Data Analysis

How recurrent neural networks carry a hidden state through sequences, why they forget, and how to train one on time series without fooling yourself.

AI & ML

A feedforward network takes a fixed-size input and treats it as an unordered bag of numbers. Shuffle the columns consistently and it learns just as well. That is fine for a row of customer attributes, but much of the data you care about is a sequence: sensor readings every second, daily sales, words in a sentence, clicks in a session. In a sequence, order carries meaning, and the length often varies from one example to the next.

Recurrent neural networks (RNNs) handle this by reading a sequence one step at a time and carrying a summary of everything seen so far, the hidden state, from each step to the next. This article works through that mechanism by hand, shows the tensor shapes you will meet in PyTorch, demonstrates the main weakness of plain RNNs with a small experiment, and then trains one on a forecasting problem, including the mistake that makes it lose to a one-line baseline.

Why order needs its own architecture

You can feed a sequence to a dense network by flattening a fixed window, say the last 28 days of sales, into 28 input columns. It works up to a point, but it has three problems:

  • Fixed length. The window size is baked into the first layer. A 29-day history or a 12-word sentence needs a different network or padding.
  • No sharing across positions. A pattern such as “a spike followed by a dip” has to be learned separately for every position it can occur in, much like the dense layer on images in the CNN article.
  • No built-in notion of time. Nothing tells the network that column 27 comes right after column 26.

An RNN solves all three with weight sharing over time instead of over space. The same small set of weights processes every step, so the sequence can be any length, a pattern is recognized wherever it occurs, and the order is part of the computation itself.

How recurrence works

The update rule

At each step t, an RNN combines the current input x_t with the previous hidden state h_(t-1) to produce a new hidden state:

h_t = tanh(W_x * x_t + W_h * h_(t-1) + b)

W_x maps the input into the hidden space, W_h maps the old state into the new one, and tanh keeps every value between -1 and 1. The hidden state starts at zero. The same W_x, W_h and b are used at every step, which is the whole trick: the network is one cell applied repeatedly, with its own output fed back in.

Drawn as a loop it looks compact. Unrolled across time, it is a deep feedforward network whose layers all share the same weights:

flowchart LR
    H0["h0 = 0"] --> C1["RNN cell"]
    X1["x1"] --> C1
    C1 -->|"h1"| C2["RNN cell"]
    X2["x2"] --> C2
    C2 -->|"h2"| C3["RNN cell"]
    X3["x3"] --> C3
    C3 -->|"h3"| O["Output layer"]
    O --> Y["Prediction"]

A worked example by hand

Take the smallest possible RNN: one input, one hidden unit, with W_x = 1, W_h = 0.5 and b = 0. Feed it the sequence 1, 0, 0, -1:

import numpy as np

w_x, w_h, b = 1.0, 0.5, 0.0
h = 0.0
for t, x in enumerate([1.0, 0.0, 0.0, -1.0], start=1):
    h = np.tanh(w_h * h + w_x * x + b)
    print(f"t={t}  x={x:+.0f}  h={h:.3f}")
t=1  x=+1  h=0.762
t=2  x=+0  h=0.363
t=3  x=+0  h=0.180
t=4  x=-1  h=-0.721

Check the first two. At t=1, tanh(0.5 x 0 + 1) = tanh(1) = 0.762. At t=2 the input is zero, so the new state is tanh(0.5 x 0.762) = tanh(0.381) = 0.363. The network still “remembers” the 1 it saw a step earlier, but the memory halves at every step because W_h is 0.5. By t=4 the new input dominates and the early 1 has almost no influence.

That small example already shows the central tension. The recurrent weight decides how long information survives. Too small and the past fades within a few steps; too large and values saturate or blow up. A real RNN has a hidden vector of dozens or hundreds of units and a full matrix W_h, but the same arithmetic applies along each direction in that space.

Shapes in PyTorch

In PyTorch, nn.RNN runs the whole loop for you:

import torch
import torch.nn as nn

rnn = nn.RNN(input_size=3, hidden_size=16, batch_first=True)
x = torch.randn(8, 50, 3)          # 8 sequences, 50 steps, 3 features per step
out, h_n = rnn(x)
print(out.shape)                   # hidden state at every step
print(h_n.shape)                   # final hidden state only
print(sum(p.numel() for p in rnn.parameters()))
for name, p in rnn.named_parameters():
    print(name, tuple(p.shape))
torch.Size([8, 50, 16])
torch.Size([1, 8, 16])
336
weight_ih_l0 (16, 3)
weight_hh_l0 (16, 16)
bias_ih_l0 (16,)
bias_hh_l0 (16,)

A few things trip people up here:

  • Without batch_first=True, PyTorch expects inputs shaped (steps, batch, features). Forgetting the flag does not raise an error when the dimensions happen to fit; it silently treats your batch as time.
  • out holds the hidden state at every step, which you need when you predict something per step. h_n holds only the last one, with a leading dimension for the number of layers (times two if bidirectional).
  • The parameter count is hidden x (input + hidden) + 2 x hidden. PyTorch keeps two bias vectors per layer, one for the input path and one for the recurrent path, so it reports 32 bias parameters where the textbook formula has 16. The count does not depend on sequence length at all.

In Keras the equivalent layer is SimpleRNN, which returns only the final state unless you pass return_sequences=True.

An nn.RNN layer has input_size=10 and hidden_size=20. How many parameters does PyTorch report?

  • 600
  • 640
  • It depends on the sequence length

Correct! 20 x 10 input weights plus 20 x 20 recurrent weights is 600, and two bias vectors of 20 add 40, whatever the sequence length.

Sequence task shapes

The same recurrent core supports several kinds of problem, depending on which hidden states you read and what you feed in.

flowchart TD
    R["Recurrent core"] --> A["Many to one: read last state"]
    R --> B["Many to many: read every state"]
    R --> C["Encoder-decoder: state seeds a second RNN"]
    A --> A1["Sentiment, anomaly flag, next-day forecast"]
    B --> B1["Tagging each word, per-frame labels"]
    C --> C1["Translation, multi-step forecasts"]
  • Many to one. Read the whole sequence, then make one prediction from the final hidden state. Classifying a review as positive or negative, or forecasting tomorrow from the last four weeks.
  • Many to many, aligned. Produce an output at every step from out. Labeling each word with its part of speech, or flagging each second of a sensor stream as normal or abnormal.
  • Encoder-decoder. One RNN reads the input and compresses it into its final state; a second RNN starts from that state and generates an output sequence of a different length. This was the original neural machine translation design, covered in text generation models from RNNs to transformers.

Two common variations stack on top of these. A stacked RNN (num_layers=2 or more) feeds each layer’s hidden states into the next, letting higher layers work with more abstract features. A bidirectional RNN (bidirectional=True) runs a second pass from the end of the sequence to the start and concatenates both states, so each position sees its future as well as its past. That helps tagging and classification, where you have the whole sequence up front, and is not an option for forecasting or real-time streams, where the future is not available yet.

Training through time, and why RNNs forget

Backpropagation through time

Training an RNN uses ordinary backpropagation on the unrolled network, a procedure called backpropagation through time (BPTT). The loss at the end sends gradients back through every step, and because all steps share W_h, the gradients from each step are added together to update it.

The problem is what happens on the way back. The gradient reaching step 1 from step 50 has been multiplied by W_h and by the derivative of tanh (at most 1) forty-nine times. Treat it as a single number for intuition: 0.9 raised to the 50th power is about 0.005, and 1.1 raised to the 50th power is about 117. Factors slightly below 1 make the signal from early steps vanish; factors slightly above 1 make it explode.

  • Exploding gradients show up as a loss that suddenly jumps to NaN. The standard fix is gradient clipping: rescale the gradient whenever its norm exceeds a threshold. In PyTorch that is one line, nn.utils.clip_grad_norm_(model.parameters(), 1.0), between backward() and step().
  • Vanishing gradients are quieter. Nothing crashes; the network simply never learns dependencies longer than a handful of steps.

Seeing the limit

A small experiment makes this concrete. Each training example is a sequence of random numbers, and the label is 1 if the first number is positive. Everything after the first step is noise. The network reads the whole sequence and must answer from its final hidden state, so it has to carry one bit of information across the full length.

import torch
import torch.nn as nn

def make_data(n, length):
    x = torch.randn(n, length, 1)
    y = (x[:, 0, 0] > 0).float()     # label depends only on the FIRST step
    return x, y

class Classifier(nn.Module):
    def __init__(self, cell):
        super().__init__()
        self.rnn = cell(input_size=1, hidden_size=32, batch_first=True)
        self.head = nn.Linear(32, 1)
    def forward(self, x):
        out, _ = self.rnn(x)
        return self.head(out[:, -1]).squeeze(1)   # read the last step only

def run(cell, length):
    torch.manual_seed(0)
    x_train, y_train = make_data(4000, length)
    x_test, y_test = make_data(1000, length)
    model = Classifier(cell)
    opt = torch.optim.Adam(model.parameters(), lr=1e-3)
    loss_fn = nn.BCEWithLogitsLoss()
    for epoch in range(20):
        for i in range(0, len(x_train), 64):
            opt.zero_grad()
            loss = loss_fn(model(x_train[i:i+64]), y_train[i:i+64])
            loss.backward()
            nn.utils.clip_grad_norm_(model.parameters(), 1.0)
            opt.step()
    with torch.no_grad():
        acc = ((model(x_test) > 0).float() == y_test).float().mean().item()
    return acc

for length in [5, 20, 50, 100]:
    print(f"sequence length {length:>3}: test accuracy {run(nn.RNN, length):.3f}")

With PyTorch 2.15 on a CPU, the whole run takes under a minute:

sequence length   5: test accuracy 0.994
sequence length  20: test accuracy 0.979
sequence length  50: test accuracy 0.504
sequence length 100: test accuracy 0.507

At 5 and 20 steps the task is easy. At 50 steps the same network, with the same training budget and gradient clipping, scores 50 percent, which is a coin flip. It is not that the network lacks the capacity to hold one bit; it is that the training signal connecting the label to step 1 has faded to almost nothing by the time it gets there. More epochs or a lucky seed can push the limit out somewhat, but the trend holds.

That is why plain RNNs are rarely used for long sequences. Gated variants, the LSTM and the simpler GRU, add a separate memory path that the network can deliberately keep open, so gradients survive across hundreds of steps. LSTMs are the subject of the next article in this series. A related practical technique is truncated BPTT: split a very long sequence into chunks, carry the hidden state forward between chunks but stop gradients at each boundary. It keeps training cost bounded, at the price of not learning dependencies longer than a chunk.

A plain RNN trains well on 10-step sequences but scores at chance when the key information is 80 steps back. What is the most likely cause?

  • Exploding gradients, which clipping would have prevented
  • Too many parameters for the sequence length
  • Vanishing gradients through the many recurrent steps

Correct! The gradient from the loss shrinks at every step back through time, so the network never learns to keep information from 80 steps earlier.

A forecasting example, and a baseline that wins

Time series forecasting is the most common reason people reach for an RNN today, and also where it is easiest to fool yourself. Here is a synthetic version of a familiar problem: three years of daily demand with an upward trend, a weekly cycle (busy Fridays and Saturdays, quiet Mondays) and noise. The model reads 28 days and predicts the next one. It trains on the first two years and is tested on the third.

import numpy as np
import torch
import torch.nn as nn

# Three years of synthetic daily demand: trend, weekly cycle, noise
rng = np.random.default_rng(0)
days = np.arange(3 * 365)
weekly = np.array([0.8, 1.0, 1.0, 1.05, 1.2, 1.4, 0.9])[days % 7]
series = (100 + 0.05 * days) * weekly + rng.normal(0, 5, len(days))

split = 2 * 365                          # train on years 1-2, test on year 3
mean, std = series[:split].mean(), series[:split].std()
scaled = (series - mean) / std

window = 28
X = np.stack([scaled[i - window:i] for i in range(window, len(scaled))])
y = scaled[window:]
target_day = np.arange(window, len(scaled))
train, test = target_day < split, target_day >= split

X_train = torch.tensor(X[train], dtype=torch.float32).unsqueeze(-1)
y_train = torch.tensor(y[train], dtype=torch.float32)
X_test = torch.tensor(X[test], dtype=torch.float32).unsqueeze(-1)

class Forecaster(nn.Module):
    def __init__(self):
        super().__init__()
        self.rnn = nn.RNN(input_size=1, hidden_size=32, batch_first=True)
        self.head = nn.Linear(32, 1)
    def forward(self, x):
        out, _ = self.rnn(x)
        return self.head(out[:, -1]).squeeze(1)

torch.manual_seed(0)
model = Forecaster()
opt = torch.optim.Adam(model.parameters(), lr=1e-3)
loss_fn = nn.MSELoss()
for epoch in range(100):
    perm = torch.randperm(len(X_train))
    for i in range(0, len(perm), 32):
        idx = perm[i:i + 32]
        opt.zero_grad()
        loss_fn(model(X_train[idx]), y_train[idx]).backward()
        opt.step()

with torch.no_grad():
    rnn_pred = model(X_test).numpy() * std + mean
actual = series[split:]
naive = series[split - 1:-1]             # tomorrow equals today
seasonal = series[split - 7:-7]          # tomorrow equals the same day last week

def mae(pred):
    return np.abs(pred - actual).mean()

print(f"naive (yesterday)      MAE {mae(naive):6.2f}")
print(f"seasonal naive (t-7)   MAE {mae(seasonal):6.2f}")
print(f"RNN                    MAE {mae(rnn_pred):6.2f}")
naive (yesterday)      MAE  25.94
seasonal naive (t-7)   MAE   5.23
RNN                    MAE   8.02

The RNN beats “same as yesterday” comfortably, but loses badly to “same as the same weekday last week”, a baseline with no parameters at all. Shuffling the training windows is fine here, by the way: each window is a self-contained example, and the split itself is by time, which is what matters.

The cause is scaling. The series is standardized with the training mean and standard deviation, which is the textbook move. But demand keeps growing, and the third year runs from about 105 to 225 while the training years topped out around 196. The test inputs sit partly outside anything the network saw, and a network built from tanh units does not extrapolate well. Neural networks interpolate; trends push forecasts into extrapolation.

One fix is to scale each window by its own average level, so the model learns the shape of the week relative to the recent level, and then multiply back. Replace the scaling block with:

window = 28
target_day = np.arange(window, len(series))
windows = np.stack([series[t - window:t] for t in target_day])
levels = windows.mean(axis=1)            # each window's own average level
X = windows / levels[:, None] - 1        # shape relative to that level
y = series[window:] / levels - 1

and the prediction line with rnn_pred = (model(X_test).numpy() + 1) * levels[test]. Nothing else changes:

naive (yesterday)      MAE  25.94
seasonal naive (t-7)   MAE   5.23
RNN                    MAE   4.31

Now the RNN beats the seasonal baseline by about 18 percent. The noise added to this series has a standard deviation of 5, which puts the best possible MAE near 4, so there is little left to gain. The lessons carry over to real data:

  • Always compute naive baselines first. If your model cannot beat “same as last week”, it is not ready, whatever its training loss says.
  • Split by time, never at random. A random split lets the model see the future of the period it is tested on.
  • Make the inputs stationary-ish. Per-window scaling, differencing, or modeling the ratio to a seasonal baseline all keep test inputs in the range the network learned on.

A forecasting RNN trained on two years of growing sales does worse on year three than a seasonal naive baseline. What should you check first?

  • Whether year-three inputs fall outside the range the model was trained on
  • Whether the model needs a bidirectional layer
  • Whether the training windows should not be shuffled

Correct! With a trend, global scaling puts later inputs outside the training range, and neural networks extrapolate poorly; scaling per window or differencing usually fixes it.

RNNs and the alternatives

RNNs are no longer the default for most sequence problems, but they have not disappeared either. Here is how they compare with the other options you will consider.

ApproachStrengthsWeaknessesGood fit
Classical models (ARIMA, exponential smoothing)Few parameters, interpretable, strong on single short seriesOne model per series, limited use of extra featuresA handful of business time series
Gradient boosting on lag featuresFast, handles many features, strong in practiceYou design the lags and windows by handTabular forecasting with lots of covariates
Plain RNNSmall, simple, processes streams step by step with constant memoryForgets beyond tens of stepsShort sequences, teaching, tiny devices
LSTM and GRURemember across hundreds of stepsSequential, so slower to train than convolutions or attentionStreaming sensors, on-device speech, forecasting many related series
1D CNNParallel training, good at local patternsFixed receptive field unless stacked deep or dilatedAudio, sensor classification
TransformerRelates every step to every other, scales with data and hardwareCost grows with the square of sequence length, needs more dataLanguage, long documents, large datasets

The key structural difference is in how computation flows. An RNN must finish step t before starting step t+1, so training cannot be parallelized across time, while attention processes all positions at once. That parallelism is the main reason transformers replaced RNNs for language. In exchange, an RNN’s inference cost per step is constant: to process the next reading in a stream it needs only its current hidden state, not the whole history. That property is why recurrent ideas keep returning in newer architectures aimed at long sequences, such as state space models.

Running sequence models in the cloud

For your own architectures, the managed ML platforms (Amazon SageMaker AI, Gemini Enterprise Agent Platform on Google Cloud, and Azure Machine Learning) run PyTorch or TensorFlow training jobs in prebuilt containers; setting up a simple ML project compares them. Models the size of the ones above train in seconds on a CPU. Recurrent layers gain less from GPUs than convolutions do, because the steps run one after another, so measure before paying for GPU hours.

If your goal is forecasting rather than building models, check for a built-in option first. SageMaker AI includes DeepAR, a built-in algorithm that uses recurrent networks to forecast one-dimensional time series. Instead of fitting one model per series, it trains a single model across many related series, such as demand for every product in a catalog, and produces probabilistic forecasts as well as point estimates. AWS documents that it tends to beat ARIMA and exponential smoothing when you have hundreds of related series, which matches the general rule: deep sequence models earn their keep with many series and plenty of history, and lose to simple methods on one short series.

Further reading:

Key takeaways

  • An RNN applies one small cell at every step of a sequence and passes a hidden state forward, so it handles any length, shares weights across time and builds order into the computation.
  • The update is h_t = tanh(W_x * x_t + W_h * h_(t-1) + b). The recurrent weights decide how quickly past information fades.
  • In PyTorch, mind batch_first, and know that out gives every step’s state while h_n gives only the last. Parameter count does not depend on sequence length.
  • Backpropagation through time multiplies gradients once per step. Clipping fixes exploding gradients; vanishing gradients limit plain RNNs to short dependencies, which is what LSTMs and GRUs address.
  • For forecasting, beat a seasonal naive baseline before trusting a model, split by time, and scale inputs so test data stays inside the training range.
  • Transformers replaced RNNs for most language work because they train in parallel, but recurrence still fits streaming, on-device and many-series forecasting problems.

Part 3 of 3 · Deep Learning and Neural Networks

  1. 01Understanding Feedforward Neural Networks
  2. 02Convolutional Neural Networks: Computer Vision Applications
  3. 03Recurrent Neural Networks: Sequential Data Analysis
Ready to check your understanding?Take the Artificial Unintelligence quiz
esc

Type to search all articles · ↑↓ to move · ↵ to open