Overview
A recurrent network reads a sequence one step at a time and keeps a running summary called the hidden state. A plain recurrent network overwrites that state at every step, so information from early steps fades quickly. A GRU adds two gates, each a set of values between 0 and 1 computed from the current input and the old state. The update gate decides, for each unit of the state, whether to keep the old value or replace it with a new candidate. The reset gate decides how much of the old state the candidate is allowed to use. When the update gate stays near 1, a unit carries its value unchanged over many steps.
A short history
Kyunghyun Cho and colleagues introduced the gated recurrent unit in 2014 as part of an encoder-decoder model for machine translation. It kept the central idea of the LSTM, gates that control what is remembered, but merged the cell and hidden state and used two gates in place of three. Comparisons published soon after found it performed about as well as the LSTM on many tasks with fewer parameters.
How it works
- Start with a hidden state of zeros.
- At each step compute the update gate and the reset gate from the input and the previous state.
- Compute the candidate state with tanh, letting it see the previous state only through .
- Blend: .
- After the last step, pass the final hidden state through a dense layer: softmax for classification or a linear output for regression.
- Backpropagate through time, from the last step to the first, to get the gradients.
- Rescale the gradients if their overall norm exceeds
clip_norm, then update with Adam.
Watch out for
- Only the last hidden state feeds the output, so everything the model needs must survive to the final step. Very long sequences still lose early information.
- Gradients can still grow very large on some batches, which makes training jump. That is why the template clips the gradient norm.
- All sequences must have the same length, because this template has no masking. Padding short sequences with zeros makes the model process the padding as real input.
- Steps are processed one after another, so training cannot be parallelised over time and gets slow on long sequences.
Use cases
When to use it
Sequence problems where order matters and the sequences are short to medium: sensor windows, short texts, event streams. It is a little cheaper than an LSTM and often as accurate.
In industry
- E-commerce
- Session-based recommendation: predicting the next item from the clicks in the current visit; GRU4Rec is a well-known published model.
- Energy and utilities
- Short-term load forecasting from recent consumption and weather readings.
- Industrial monitoring
- Predicting equipment failure from streams of sensor readings over time.
Choosing it: what must hold
- Data that arrives in order, where earlier steps affect the meaning of later ones.
- Sequences of moderate length, up to a few hundred steps.
- Enough sequences to train on; a few dozen short series is rarely enough.
When to choose something else
| If | Use instead |
|---|---|
| Sequences are very long or you have a large corpus and parallel hardware | A Transformer |
| You want a separate memory cell and can afford more parameters | An LSTM |
| The series is short with clear trend and seasonality | A classical forecasting model, or gradient boosted trees on lag features |
Math foundations
Update gate
One value between 0 and 1 per hidden unit. In this template's convention a value near 1 means: keep the old state.
Reset gate
Controls how much of the old state the candidate may read. Near 0, the candidate is built from the current input alone.
Candidate state
The proposed new content, with values between -1 and 1. The reset gate is applied to the old state before the recurrent weights.
New hidden state
A unit-by-unit weighted average of the candidate and the old state. Some libraries swap the roles of and , and the two forms are equivalent.
The direct gradient path
The blend contributes a term that is simply , with no weight matrix and no squashing. When the update gate is near 1, the gradient passes back almost unchanged. The remaining terms go through the gates and the candidate.
Gradient clipping
If the norm of all gradients together exceeds , they are scaled down to that norm. The direction is kept and only the step length is limited.
Symbols
- input at step t
- hidden state after step t
- update gate
- reset gate
- candidate state
- input weights, recurrent weights and biases, one set per gate
- the sigmoid function
- element-wise product
- all gradients, viewed as one vector
- clip_norm
Worked by hand
One hidden unit with previous state . At this step the gates come out as and the candidate as . Then repeat with .
With the update gate at 0.8 the state barely moves, and at 0.1 it is almost replaced by the candidate. The last line shows the direct gradient factor over 10 steps: a gate held at 0.99 keeps 90 percent of the signal.
Visual example
Loading the example.
Try this
- Move the mark to step 1 and follow unit 3 of the update gate: it opens once to write the value, then stays near 1 to hold it for seven steps.
- Raise the size of the other inputs to 1 and see that the answer still tracks the marked value.
- Inspect the marked step, then the step after it, and compare z in the diagram.
Code sample
import numpy as np
from impl import GRU
from config import GRUConfig
rng = np.random.default_rng(0)
y = rng.integers(0, 3, size=300)
X = rng.normal(0, 0.3, size=(300, 10, 3)) # (n, steps, features)
X[:, 0, :] = np.eye(3)[y] # the label is shown only at the first step
net = GRU(GRUConfig(hidden_size=16, epochs=30)).fit(X, y)
print((net.predict(X) == y).mean()) # it has to remember across 10 steps
print(net.hidden_states(X[:2]).shape) # (2, 10, 16)Read the implementation (163 lines)
"""GRU: gated recurrent unit network for sequences.
NumPy only, backpropagation through time written by hand. One GRU layer reads a sequence step by step and a
dense layer maps its last hidden state to the output.
z_t = sigmoid(x_t Wz + h_{t-1} Uz + bz) update gate
r_t = sigmoid(x_t Wr + h_{t-1} Ur + br) reset gate
n_t = tanh(x_t Wn + (r_t * h_{t-1}) Un + bn) candidate state
h_t = (1 - z_t) * n_t + z_t * h_{t-1}
"""
from __future__ import annotations
import numpy as np
try:
from .config import GRUConfig
except ImportError: # run from the template's own folder
from config import GRUConfig
def _sigmoid(z: np.ndarray) -> np.ndarray:
return 1.0 / (1.0 + np.exp(-np.clip(z, -60.0, 60.0)))
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 GRU:
"""Sequence model: GRU layer, then a dense output on the last hidden state.
task "classification": softmax and cross-entropy. task "regression": linear output and squared error.
Parameters live in `params`: W (d, 3H), U (H, 3H), b (3H,) with the gates stacked in the order z, r, n,
and the output layer V (H, k), c (k,).
"""
def __init__(self, config: GRUConfig | None = None) -> None:
self.config = config or GRUConfig()
self.params: dict[str, np.ndarray] = {}
self.classes_: np.ndarray | None = None
self.loss_history: list[float] = []
def _init_params(self, n_in: int, n_out: int) -> None:
H = self.config.hidden_size
rng = np.random.default_rng(self.config.seed)
self.params = {
"W": rng.normal(0.0, np.sqrt(1.0 / n_in), size=(n_in, 3 * H)),
"U": rng.normal(0.0, np.sqrt(1.0 / H), size=(H, 3 * H)),
"b": np.zeros(3 * H),
"V": rng.normal(0.0, np.sqrt(1.0 / H), size=(H, n_out)),
"c": np.zeros(n_out),
}
def forward(self, X: np.ndarray) -> tuple[np.ndarray, list]:
"""X: (n, T, d) -> (output (n, k) before any softmax, per-step cache). The initial state is zero."""
X = np.asarray(X, dtype=float)
H = self.config.hidden_size
W, U, b = self.params["W"], self.params["U"], self.params["b"]
h = np.zeros((X.shape[0], H))
cache = []
for t in range(X.shape[1]):
x = X[:, t, :]
ax = x @ W + b
ah = h @ U[:, :2 * H]
z = _sigmoid(ax[:, :H] + ah[:, :H])
r = _sigmoid(ax[:, H:2 * H] + ah[:, H:])
n = np.tanh(ax[:, 2 * H:] + (r * h) @ U[:, 2 * H:])
h_new = (1.0 - z) * n + z * h
cache.append((x, h, z, r, n))
h = h_new
return h @ self.params["V"] + self.params["c"], cache + [h]
def hidden_states(self, X: np.ndarray) -> np.ndarray:
"""Hidden state after every step. X: (n, T, d) -> (n, T, H)."""
_, cache = self.forward(X)
return np.stack([step[1] for step in cache[1:-1]] + [cache[-1]], axis=1)
def loss_and_grads(self, X: np.ndarray, T: np.ndarray) -> tuple[float, dict]:
"""Loss on a batch and its gradients by backpropagation through time.
X: (n, T, d). T: (n, k) one-hot rows (classification) or values (regression).
Returns (loss, {parameter name: gradient}).
"""
H = self.config.hidden_size
U = self.params["U"]
out, cache = self.forward(X)
h_last = cache[-1]
n_rows = len(out)
if self.config.task == "classification":
P = _softmax(out)
loss = float(-np.sum(T * np.log(P + 1e-12)) / n_rows)
d_out = (P - T) / n_rows
else:
loss = float(np.sum((out - T) ** 2) / n_rows)
d_out = 2.0 * (out - T) / n_rows
grads = {"V": h_last.T @ d_out, "c": d_out.sum(axis=0), "W": np.zeros_like(self.params["W"]),
"U": np.zeros_like(U), "b": np.zeros_like(self.params["b"])}
dh = d_out @ self.params["V"].T
for x, h_prev, z, r, n in reversed(cache[:-1]):
da_n = dh * (1.0 - z) * (1.0 - n**2)
da_z = dh * (h_prev - n) * z * (1.0 - z)
d_rh = da_n @ U[:, 2 * H:].T
da_r = d_rh * h_prev * r * (1.0 - r)
da = np.hstack([da_z, da_r, da_n])
grads["W"] += x.T @ da
grads["b"] += da.sum(axis=0)
grads["U"][:, :2 * H] += h_prev.T @ da[:, :2 * H]
grads["U"][:, 2 * H:] += (r * h_prev).T @ da_n
dh = dh * z + d_rh * r + da[:, :2 * H] @ U[:, :2 * H].T
return loss, grads
def fit(self, X: np.ndarray, y: np.ndarray) -> "GRU":
"""Train with mini-batch Adam and gradient-norm clipping.
X: (n, T, d) sequences. y: (n,) class labels, or (n,) / (n, k) values for regression.
"""
cfg = self.config
X = np.asarray(X, dtype=float)
if X.ndim != 3:
raise ValueError(f"X must have shape (n, steps, features), got {X.shape}")
if cfg.task == "classification":
self.classes_, idx = np.unique(np.asarray(y), return_inverse=True)
T = np.eye(len(self.classes_))[idx]
else:
T = np.asarray(y, dtype=float).reshape(len(X), -1)
self._init_params(X.shape[2], T.shape[1])
rng = np.random.default_rng(cfg.seed + 1)
m = {k: np.zeros_like(p) for k, p in self.params.items()}
v = {k: np.zeros_like(p) for k, p in self.params.items()}
step = 0
self.loss_history = []
for _ in range(cfg.epochs):
order = rng.permutation(len(X))
total = 0.0
for start in range(0, len(X), cfg.batch_size):
rows = order[start:start + cfg.batch_size]
loss, grads = self.loss_and_grads(X[rows], T[rows])
total += loss * len(rows)
norm = np.sqrt(sum(np.sum(g**2) for g in grads.values()))
scale = min(1.0, cfg.clip_norm / (norm + 1e-12))
step += 1
for name, g in grads.items():
g = g * scale
m[name] = 0.9 * m[name] + 0.1 * g
v[name] = 0.999 * v[name] + 0.001 * g * g
self.params[name] -= cfg.learning_rate * (m[name] / (1 - 0.9**step)) / (
np.sqrt(v[name] / (1 - 0.999**step)) + 1e-8)
self.loss_history.append(total / len(X))
return self
def predict_proba(self, X: np.ndarray) -> np.ndarray:
"""Class probabilities. X: (n, T, d) -> (n, n_classes). Classification only."""
if self.config.task != "classification":
raise ValueError("predict_proba is only defined for task='classification'")
return _softmax(self.forward(X)[0])
def predict(self, X: np.ndarray) -> np.ndarray:
"""Class labels (n,), or regression values (n,) / (n, k). X: (n, T, d)."""
out = self.forward(X)[0]
if self.config.task == "classification":
return self.classes_[out.argmax(axis=1)]
return out[:, 0] if out.shape[1] == 1 else out- Repository
- Not published yet
- Needs
- Python 3.10 and NumPy
- Tests
- 6, run with
python3 -m unittest -v
Practice
Train GRU on the README task, where the class is shown only at the first of 10 steps. Check the accuracy, then lengthen the sequences to 40 steps and train again. Use hidden_states on a few sequences to see which units hold their value from step 0 to the end.
Check on learning
- In the README task the label is visible only at step 0, followed by noise. What must the update gate learn to do at the later steps for the model to succeed?
A way to think about it
Look at the blend formula and ask which gate value leaves a unit unchanged. Then think about what the gate needs to detect in the input.
- Why is the new state a weighted average of old and candidate, and not their sum? What would go wrong with a sum over many steps?
A way to think about it
Track the possible range of the state under each rule after 100 steps. The candidate is bounded by tanh, but a running sum is not.
- If the reset gate were fixed at 1 and the update gate at 0, what familiar model would the GRU reduce to?
A way to think about it
Substitute those values into the candidate and blend formulas and read off what is left.
- Gradient clipping changes the size of the step but not its direction. Why is that preferable to simply using a much smaller learning rate?
A way to think about it
Most batches have ordinary gradients and a few have huge ones. Consider how each remedy treats the ordinary batches.