Sign in

Recurrent neural network (RNN)

Recurrent Neural Network

A recurrent network that reads a sequence one step at a time, keeping a hidden state that summarises what it has seen so far.

Overview

An ordinary network sees its whole input at once and has no sense of order. A recurrent network instead reads one item of a sequence at a time and carries a small vector of memory, the hidden state, from step to step. At each step it mixes the new input with the old state to produce a new state, using the same weights every time. Whatever the network knows about the past must be packed into that state. The vanilla form in this template is the simplest version. Information from many steps back fades quickly, which is the problem that LSTM and GRU cells were designed to ease.

A short history

Recurrent networks for sequences took shape in the 1980s. Michael Jordan described one form in 1986, and Jeffrey Elman's 1990 paper Finding Structure in Time gave the simple architecture usually taught today. Training them by backpropagation through time was described by Paul Werbos among others. Sepp Hochreiter in 1991 and Yoshua Bengio and colleagues in 1994 showed that their gradients vanish over long spans, which led to the LSTM and GRU.

How it works

  1. Start with a hidden state of zeros, h0=0\mathbf{h}_0 = \mathbf{0}.
  2. At each step, combine the current input and the previous state: ht=tanh⁡(xtWxh+ht−1Whh+bh)\mathbf{h}_t = \tanh(\mathbf{x}_t W_{xh} + \mathbf{h}_{t-1} W_{hh} + \mathbf{b}_h).
  3. Read out one output per step from the state: ot=htWhy+by\mathbf{o}_t = \mathbf{h}_t W_{hy} + \mathbf{b}_y.
  4. Average the loss over every step of every sequence: half squared error for regression, softmax cross-entropy for classification.
  5. Run backpropagation through time: walk from the last step to the first, adding at each step the gradient from that step's output to the gradient carried back from later steps.
  6. Rescale the gradients if their overall norm exceeds clip_norm, then update with Adam.

Watch out for

  • Gradients shrink as they travel back through many steps, because each step multiplies them by a factor that is usually below 1. The network then fails to learn long-range dependencies.
  • When the recurrent weights are large the same product grows instead, and one step can throw the weights far away. Keep clip_norm on to limit this.
  • Steps must be computed in order, so the model cannot process a sequence in parallel and is slow on long inputs.
  • This template produces one output per step and expects all sequences to have the same length TT. Variable-length data needs padding and masking that it does not provide.

Use cases

When to use it

Short sequences where order matters and a small model is enough: sensor readings, simple time series, character-level toy tasks. It is also the clearest starting point for understanding LSTM, GRU and attention.

In industry

Consumer devices
Small on-device sequence models, such as keyboard next-character prediction, where memory and compute are tight.
Signal processing
Modelling short sensor or audio sequences where only the last few steps matter.
Education and research
The reference model for learning how hidden state and backpropagation through time work before moving to gated networks.

Choosing it: what must hold

  • Ordered data in which the useful context is short, roughly ten to twenty steps.
  • Gradient clipping, because gradients can explode as well as vanish.
  • Sequences that can be processed one step at a time.

When to choose something else

IfUse instead
Context from far back mattersAn LSTM or a GRU
You have large data and parallel hardwareA Transformer
A fixed window of recent values is all that mattersAn MLP or gradient boosted trees on lag features

Math foundations

  1. The recurrence

    ht=tanh⁡ ⁣(xtWxh+ht−1Whh+bh),h0=0\mathbf{h}_t = \tanh\!\left(\mathbf{x}_t W_{xh} + \mathbf{h}_{t-1} W_{hh} + \mathbf{b}_h\right), \qquad \mathbf{h}_0 = \mathbf{0}

    The new state depends on the current input and the previous state. The same three parameters are reused at every step, which is what lets the model handle any position in a sequence.

  2. The read-out

    ot=htWhy+by\mathbf{o}_t = \mathbf{h}_t W_{hy} + \mathbf{b}_y

    A linear layer turns the state into the output for step tt: a predicted value, or class scores that go through a softmax.

  3. The loss

    L=1nT∑i=1n∑t=1Tℓ ⁣(oi,t,yi,t)L = \frac{1}{nT}\sum_{i=1}^{n}\sum_{t=1}^{T} \ell\!\left(\mathbf{o}_{i,t}, \mathbf{y}_{i,t}\right)

    The per-step loss ℓ\ell averaged over all sequences and steps. ℓ\ell is half the squared error or the cross-entropy.

  4. Backpropagation through time

    δt=(∂L∂otWhy⊤+δt+1Whh⊤)⊙(1−ht2),δT+1=0\boldsymbol{\delta}_t = \left(\frac{\partial L}{\partial \mathbf{o}_t} W_{hy}^\top + \boldsymbol{\delta}_{t+1} W_{hh}^\top\right) \odot \left(1 - \mathbf{h}_t^2\right), \qquad \boldsymbol{\delta}_{T+1} = \mathbf{0}

    The error at step tt has two sources: this step's own output, and everything later that this state influenced. The factor 1−ht21 - \mathbf{h}_t^2 is the slope of tanh.

  5. Gradients of the shared weights

    ∂L∂Whh=∑t=1Tht−1⊤δt,∂L∂Wxh=∑t=1Txt⊤δt\frac{\partial L}{\partial W_{hh}} = \sum_{t=1}^{T} \mathbf{h}_{t-1}^\top \boldsymbol{\delta}_t, \qquad \frac{\partial L}{\partial W_{xh}} = \sum_{t=1}^{T} \mathbf{x}_t^\top \boldsymbol{\delta}_t

    Because the weights are reused at every step, their gradient is the sum of the contributions from all steps.

  6. Why gradients vanish or explode

    ∂hT∂ht=∏τ=t+1T∂hτ∂hτ−1\frac{\partial \mathbf{h}_T}{\partial \mathbf{h}_t} = \prod_{\tau = t+1}^{T} \frac{\partial \mathbf{h}_\tau}{\partial \mathbf{h}_{\tau - 1}}

    The effect of an early state on a late one is a product of one factor per step, each built from WhhW_{hh} and a tanh slope. If the factors are mostly below 1 the product dies away, and if above 1 it blows up.

  7. Gradient clipping

    g←g⋅min⁡ ⁣(1,c∥g∥)\mathbf{g} \leftarrow \mathbf{g} \cdot \min\!\left(1, \frac{c}{\lVert \mathbf{g} \rVert}\right)

    If the norm of all gradients together exceeds cc, shrink them to length cc without changing direction. This guards against exploding gradients. It does nothing for vanishing ones.

Symbols

xt\mathbf{x}_t
input at step t
ht\mathbf{h}_t
hidden state after step t
ot\mathbf{o}_t
output at step t
Wxh,Whh,bhW_{xh}, W_{hh}, \mathbf{b}_h
input weights, recurrent weights and bias of the state update
Why,byW_{hy}, \mathbf{b}_y
weights and bias of the read-out
T,nT, n
sequence length and number of sequences
ℓ\ell
loss for a single step
δt\boldsymbol{\delta}_t
gradient of the loss with respect to the pre-tanh sum at step t
g\mathbf{g}
all gradients stacked into one vector
cc
the clip_norm limit

Worked by hand

A one-unit RNN with Wxh=1W_{xh} = 1, Whh=0.5W_{hh} = 0.5 and no bias reads the sequence x1=1x_1 = 1, x2=0x_2 = 0.

h1=tanh⁡(1×1+0.5×0)=tanh⁡(1)=0.7616h_1 = \tanh(1 \times 1 + 0.5 \times 0) = \tanh(1) = 0.7616
h2=tanh⁡(1×0+0.5×0.7616)=tanh⁡(0.3808)=0.3634h_2 = \tanh(1 \times 0 + 0.5 \times 0.7616) = \tanh(0.3808) = 0.3634
∂h2∂h1=(1−h22)Whh=(1−0.1321)×0.5=0.4340\frac{\partial h_2}{\partial h_1} = \left(1 - h_2^2\right) W_{hh} = (1 - 0.1321) \times 0.5 = 0.4340

The input at step 1 is still visible in h2h_2, but weakened. Each further step with no input multiplies its influence by at most 0.5, so after ten steps under 0.1 percent would remain.

Visual example

Loading the example.

Try this

  • Press Step and follow the numbers through the diagram. Step 2 gives the 0.363 of the worked example.
  • Raise W_hh toward 1.2 and watch the share of step 1 that survives.
  • Switch on a second input later in the sequence and see the state jump.

Code sample

import numpy as np
from impl import RNN
from config import RNNConfig

# Task: output the input seen one step earlier. It cannot be solved without memory.
rng = np.random.default_rng(0)
X = rng.choice([-1.0, 1.0], size=(128, 12, 1))            # (sequences, time steps, features)
Y = np.concatenate([np.zeros((128, 1, 1)), X[:, :-1]], axis=1)

model = RNN(RNNConfig(hidden_dim=16, epochs=60)).fit(X, Y)
print(np.mean((model.predict(X) - Y) ** 2))               # mean squared error, close to 0 (guessing gives about 0.92)
print(model.hidden_states(X[:1]).shape)                   # (1, 12, 16)
Read the implementation (173 lines)
"""Vanilla (Elman) recurrent network with backpropagation through time and Adam.

NumPy only. For a batch of n sequences of length T with d features per step:

    h_t = tanh(x_t Wxh + h_{t-1} Whh + bh)     h_0 = 0, h_t of shape (n, hidden_dim)
    o_t = h_t Why + by                         one output per step, shape (n, n_out)

The loss is averaged over all n * T steps.
"""
from __future__ import annotations

import numpy as np

try:
    from .config import RNNConfig
except ImportError:  # run from the template's own folder
    from config import RNNConfig


class _Adam:
    """Adam optimizer over a dict of NumPy arrays; `step` updates the arrays in place."""

    def __init__(self, params: dict, lr: float, beta1: float = 0.9, beta2: float = 0.999, eps: float = 1e-8) -> None:
        self.params, self.lr, self.beta1, self.beta2, self.eps = params, lr, beta1, beta2, eps
        self.m = {k: np.zeros_like(v) for k, v in params.items()}
        self.v = {k: np.zeros_like(v) for k, v in params.items()}
        self.t = 0

    def step(self, grads: dict) -> None:
        """Apply one update. grads: same keys and shapes as the parameters."""
        self.t += 1
        for k, g in grads.items():
            self.m[k] = self.beta1 * self.m[k] + (1 - self.beta1) * g
            self.v[k] = self.beta2 * self.v[k] + (1 - self.beta2) * g * g
            m_hat = self.m[k] / (1 - self.beta1**self.t)
            v_hat = self.v[k] / (1 - self.beta2**self.t)
            self.params[k] -= self.lr * m_hat / (np.sqrt(v_hat) + self.eps)

def _softmax(z: np.ndarray) -> np.ndarray:
    e = np.exp(z - z.max(axis=-1, keepdims=True))
    return e / e.sum(axis=-1, keepdims=True)


class RNN:
    """Single-layer tanh RNN with a per-step read-out. After `fit`: `params`, `loss_history_`."""

    def __init__(self, config: RNNConfig | None = None) -> None:
        self.config = config or RNNConfig()
        self.params: dict[str, np.ndarray] = {}
        self.loss_history_: list[float] = []

    def initialize(self, input_dim: int, output_dim: int) -> None:
        """Create the weights for `input_dim` features per step and `output_dim` outputs (targets or classes)."""
        rng = np.random.default_rng(self.config.seed)
        h = self.config.hidden_dim
        # An orthogonal recurrent matrix keeps the hidden state's size stable at the start of training.
        q, _ = np.linalg.qr(rng.normal(size=(h, h)))
        self.params = {
            "Wxh": np.sqrt(1.0 / input_dim) * rng.normal(size=(input_dim, h)),
            "Whh": q,
            "bh": np.zeros(h),
            "Why": np.sqrt(1.0 / h) * rng.normal(size=(h, output_dim)),
            "by": np.zeros(output_dim),
        }

    def _forward(self, X: np.ndarray) -> tuple[np.ndarray, np.ndarray]:
        """X: (n, T, d). Returns hidden states (n, T + 1, h), index 0 being h_0 = 0, and outputs (n, T, n_out)."""
        p = self.params
        n, T, _ = X.shape
        H = np.zeros((n, T + 1, self.config.hidden_dim))
        for t in range(T):
            H[:, t + 1] = np.tanh(X[:, t] @ p["Wxh"] + H[:, t] @ p["Whh"] + p["bh"])
        return H, H[:, 1:] @ p["Why"] + p["by"]

    def loss_and_grads(self, X: np.ndarray, Y: np.ndarray) -> tuple[float, dict]:
        """Loss on a batch and its gradient for every parameter, by backpropagation through time.

        X: (n, T, d). Y: real targets (n, T, n_out) for regression, or class indices (n, T) for classification.
        """
        p = self.params
        n, T, _ = X.shape
        H, out = self._forward(X)
        if self.config.task == "classification":
            prob = _softmax(out)
            rows, steps = np.indices((n, T))
            loss = -np.mean(np.log(prob[rows, steps, Y] + 1e-300))
            d_out = prob
            d_out[rows, steps, Y] -= 1.0
            d_out /= n * T
        else:
            diff = out - Y
            loss = 0.5 * np.sum(diff**2) / (n * T)
            d_out = diff / (n * T)
        grads = {key: np.zeros_like(value) for key, value in p.items()}
        grads["Why"] = np.einsum("nth,nto->ho", H[:, 1:], d_out)
        grads["by"] = d_out.sum(axis=(0, 1))
        carry = np.zeros((n, self.config.hidden_dim))  # gradient arriving at h_t from step t + 1
        for t in reversed(range(T)):
            dh = d_out[:, t] @ p["Why"].T + carry
            dz = dh * (1.0 - H[:, t + 1] ** 2)  # through tanh
            grads["Wxh"] += X[:, t].T @ dz
            grads["Whh"] += H[:, t].T @ dz
            grads["bh"] += dz.sum(axis=0)
            carry = dz @ p["Whh"].T
        return float(loss), grads

    def clip_gradients(self, grads: dict) -> dict:
        """Rescale all gradients together so their global L2 norm is at most `clip_norm`."""
        limit = self.config.clip_norm
        if limit <= 0:
            return grads
        norm = np.sqrt(sum(float(np.sum(g**2)) for g in grads.values()))
        if norm <= limit:
            return grads
        return {key: g * (limit / norm) for key, g in grads.items()}

    def fit(self, X: np.ndarray, Y: np.ndarray) -> "RNN":
        """Train with mini-batch Adam.

        X: sequences, shape (n, T, d). Y: per-step targets. Regression: (n, T) or (n, T, n_out) real values.
        Classification: (n, T) integer class indices in 0..C-1.
        """
        cfg = self.config
        X = np.asarray(X, dtype=float)
        if X.ndim != 3:
            raise ValueError("X must have shape (n, T, d)")
        if cfg.task == "classification":
            Y = np.asarray(Y, dtype=int)
            n_out = int(Y.max()) + 1
        else:
            Y = np.asarray(Y, dtype=float)
            Y = Y[:, :, None] if Y.ndim == 2 else Y
            n_out = Y.shape[2]
        if Y.shape[:2] != X.shape[:2]:
            raise ValueError("Y must have one target per sequence and time step")
        self.initialize(X.shape[2], n_out)
        optimizer = _Adam(self.params, cfg.lr)
        rng = np.random.default_rng(cfg.seed + 1)
        self.loss_history_ = []
        n = len(X)
        for _ in range(cfg.epochs):
            order = rng.permutation(n)
            total = 0.0
            for start in range(0, n, cfg.batch_size):
                rows = order[start : start + cfg.batch_size]
                loss, grads = self.loss_and_grads(X[rows], Y[rows])
                optimizer.step(self.clip_gradients(grads))
                total += loss * len(rows)
            self.loss_history_.append(total / n)
        return self

    def forward(self, X: np.ndarray) -> np.ndarray:
        """Raw per-step outputs. X: (n, T, d). Returns (n, T, n_out)."""
        if not self.params:
            raise RuntimeError("call fit (or initialize) before predicting")
        return self._forward(np.asarray(X, dtype=float))[1]

    def hidden_states(self, X: np.ndarray) -> np.ndarray:
        """Hidden state after every step. X: (n, T, d). Returns (n, T, hidden_dim)."""
        if not self.params:
            raise RuntimeError("call fit (or initialize) before predicting")
        return self._forward(np.asarray(X, dtype=float))[0][:, 1:]

    def predict(self, X: np.ndarray) -> np.ndarray:
        """Per-step predictions. X: (n, T, d). Returns values (n, T, n_out) or class indices (n, T)."""
        out = self.forward(X)
        return out.argmax(axis=2) if self.config.task == "classification" else out

    def predict_proba(self, X: np.ndarray) -> np.ndarray:
        """Per-step class probabilities (classification only). X: (n, T, d). Returns (n, T, C)."""
        if self.config.task != "classification":
            raise RuntimeError("predict_proba is for classification")
        return _softmax(self.forward(X))
Repository
Not published yet
Needs
Python 3.10 and NumPy
Tests
7, run with python3 -m unittest -v

Practice

Build sequences of 20 random numbers and set the target at each step to the input from 2 steps earlier. Fit RNN with RNNConfig task set to regression and hidden_dim 32, and check the final value of loss_history_. Then change the delay to 15 steps and train again. Call hidden_states on one sequence and compare how well each version solved its task.

Check on learning

  1. The same weights are used at every time step. What does the model gain from that, and what would be lost with separate weights per step?
    A way to think about it

    Think about a pattern that can occur at any position, and about sequences longer than any seen in training.

  2. The template starts WhhW_{hh} as an orthogonal matrix. Why is that a sensible choice given the product formula for the gradient?
    A way to think about it

    An orthogonal matrix keeps the length of any vector it multiplies. Consider what the product of many such matrices does compared with random ones.

  3. Gradient clipping helps with exploding gradients but not vanishing ones. Why can you not simply scale small gradients up?
    A way to think about it

    A clipped gradient still points the right way. A vanished gradient has lost the part that came from distant steps, so rescaling only amplifies what the recent steps contributed.

  4. Your model learns a 2-step delay easily and fails at 15 steps. Diagnose where the signal is lost, and suggest two different remedies.
    A way to think about it

    Trace the factor ∂hT/∂ht\partial \mathbf{h}_T / \partial \mathbf{h}_t across 15 steps. One remedy changes the cell so the state has an additive path, another lets the output look back directly.