All courses

Stochastic minibatch gradients

Explain why a minibatch gradient is an unbiased but noisy estimate of the full gradient. Show that its noise variance shrinks like 1/batch size.

Builds on: Gradient descent and the learning rate

▶ Watch this lesson Start the whole course

What the animation says

Why not use all the data?

Training repeats one move: nudge the weights a little way downhill, against the gradient of the loss. But that loss is an average over every training example, and there can be billions of them. Computing the exact gradient for every single step would be far too slow. So real training grabs a small random handful, a minibatch, and uses its gradient instead. Does that still go downhill on average? And how wrong is each step?

A gradient is a poll

Here's the key: because the loss is an average, its gradient is an average too. Each example casts a vote, its own gradient arrow, and the true gradient is the mean of all the votes. A minibatch is an opinion poll: pick a few votes at random and average them. Random polls don't lean any particular way, so they're right on average. But each single poll misses by a bit. Now suppose every poll takes more votes. What changes?

Four examples by hand

Same center, less scatter. Let's measure it with four examples. Their gradients are one, three, five and seven, so the true gradient is four. With a batch of one, you get one of the four. They average to four; the mean squared miss, the variance, is five. With a batch of two, drawn with replacement, sixteen pairs are equally likely. Still centered on four, but the variance is two and a half. Now a batch of four, repeats still allowed. What's the variance?

Why the variance is Σ / B

One point two five: doubling the batch halved the variance again. Here's why. Each random draw is a fair sample, so the minibatch average is unbiased. Call the spread of a single draw sigma. Add B independent draws and their spreads add up to B times sigma; the cross terms are zero. Then divide the sum by B. That scales the variance by one over B squared, leaving sigma over B. The typical error is its square root, so it shrinks only like one over root B.

Simulate it

Now check it on a real model: one weight, squared-error loss, ten thousand examples. These lines build the data and every example's gradient. The full gradient is their mean. Then, for each batch size, we draw five thousand minibatches and record each average. Every batch size keeps the mean at the full gradient, and the measured variance tracks the prediction. Your turn: tap the line that draws a random minibatch.

Can a tiny sample of data steer training?

The full loss is an average over all $n$ training examples: $\mathcal{L}(\theta)=\frac1n\sum_{i=1}^n \ell_i(\theta)$. With billions of examples, computing the exact $\nabla\mathcal{L}$ for **every** step of $\theta \leftarrow \theta-\eta\nabla\mathcal{L}$ is far too slow. Real training uses the gradient from a random handful of $B$ examples instead. Why does that still go downhill on average, and how wrong is each step?

A gradient is an average, so poll it

Since $\mathcal{L}$ is an average, its gradient is too: the mean of per-example gradients $\nabla\ell_i$. Each example "votes" for a direction. A minibatch is an opinion poll: a random sample of $B$ votes, averaged. A random sample is right **on average** (no systematic lean), but any single poll is off by some random amount. Polling more examples does not change the average answer. It only makes each poll scatter less.

Unbiased, with variance $\Sigma/B$

Let $g=\nabla\mathcal{L}$. Draw indices $i_1,\dots,i_B$ uniformly and independently (with replacement), and set $\hat g=\frac1B\sum_{j=1}^B\nabla\ell_{i_j}$. **Unbiased:** each term has expectation $\frac1n\sum_i\nabla\ell_i=g$, so $\mathbb{E}[\hat g]=g$. **Noise:** let $\Sigma=\mathbb{E}[(\nabla\ell_i-g)(\nabla\ell_i-g)^\top]$ be the covariance of one sampled gradient. The covariance of the sum $\sum_j\nabla\ell_{i_j}$ splits into $B$ self-terms, each $\Sigma$, plus cross-terms between different draws, which are zero because the draws are independent. So the sum has covariance $B\Sigma$. Dividing by $B$ scales covariance by $1/B^2$: $$\mathrm{Cov}(\hat g)=\frac{B\Sigma}{B^2}=\frac{\Sigma}{B},\qquad \mathbb{E}\|\hat g-g\|^2=\frac{\mathrm{tr}\,\Sigma}{B}.$$ The typical error size (standard deviation) shrinks like $1/\sqrt B$.

Four examples, worked by hand

Take scalar per-example gradients $1,3,5,7$, so the full gradient is $g=4$. $B=1$: $\hat g$ is $1,3,5,7$ with equal chance. The mean is $4$, so it is unbiased. Deviations are $-3,-1,1,3$, so the variance is $(9+1+1+9)/4=5$. $B=2$: drawing with replacement gives 16 equally likely ordered pairs, including ones like $(1,1)$. Their averages still have mean $4$, and the variance is $5/2=2.5$. $B=4$: the variance is $1.25$. Doubling $B$ halves the variance but cuts the typical error only by $\sqrt2$.

Simulate it: variance tracks $\Sigma/B$

This is a one-number model $w$ with squared-error loss per example. We draw many minibatches at each $B$ and compare the measured variance of $\hat g$ with the prediction (per-example variance)/$B$. The mean stays at the full gradient for every $B$.
import numpy as np
rng = np.random.default_rng(0)
n = 10000
x = rng.normal(2.0, 1.0, n); y = 3*x + rng.normal(0, 1, n)
w = 0.0                      # loss_i = (w*x_i - y_i)^2
g_i = 2*(w*x - y)*x          # per-example gradients
print("full gradient:", g_i.mean().round(2))
for B in [1, 10, 100, 1000]:
    est = np.array([g_i[rng.integers(0, n, B)].mean() for _ in range(5000)])
    print(B, est.mean().round(2), est.var().round(3), (g_i.var()/B).round(3))

Remember this

A minibatch gradient is a random-sample average of per-example gradients. Its expectation equals the full gradient (unbiased), whatever $B$ is. Its variance is $\Sigma/B$, so the typical error (standard deviation) falls only like $1/\sqrt B$. A $4\times$ bigger batch quarters the variance and halves the typical error, while costing $4\times$ the work per step.

On Bytewise this lesson comes in small steps with a check at the end, and the app brings it back right before you would forget it.