Estimating the gradient from a few samples
Most fitting problems minimise an average over data, f(w)=n1∑i=1nℓi(w), for instance squared errors over n observations. The exact gradient needs all n terms at every step, which is too slow when n is millions of ticks. Stochastic gradient descent draws a random mini-batch B of b observations and uses their average gradient gB instead. This estimate is unbiased, meaning that on average it equals the true gradient.
gB=b1i∈B∑∇ℓi(w),w←w−ηgB,E[gB]=∇f,Var(gB)=bσ2(1) The price of the shortcut is noise. The variance of the batch gradient falls like 1/b, so halving its standard deviation needs a four times larger batch, a steeply diminishing return. One epoch is a full pass over the data and holds n/b updates. With a constant step the iterates never settle: they keep jittering in a small ball around the minimum, because even at the minimum the batch gradient is not zero. The fix is a step that shrinks. The classical Robbins-Monro conditions ask that ∑tηt=∞, so the walk can travel as far as needed, and ∑tηt2<∞, so the noise dies out. The schedule ηt=η0/t satisfies both.
Four data pointsFit a level
w to the data
x=2,4,6,12 with the loss
ℓi=21(w−xi)2, whose gradient is
w−xi. At
w=0 the four single-sample gradients are
−2,−4,−6,−12, and their average, the full gradient, is
−6. The single-sample gradients have variance
416+4+0+36=14 around that average. A batch of
b=7 drawn with replacement therefore has gradient variance
14/7=2.
- Unbiased: a random batch gradient equals the full gradient on average.
- Noisy: variance σ2/b, so four times the batch halves the standard deviation.
- Shrinking steps: ∑ηt=∞ and ∑ηt2<∞, e.g. ηt=η0/t, give convergence.
Time-ordered data is not a random sampleThe unbiasedness above relies on drawing the batch at random. A batch of consecutive days comes from one market regime, so its gradient is biased toward that regime, and training on the data in time order can drift with the regime. Shuffle the sample indices at the start of each epoch. When the order itself matters, as in a time-series model, keep the sequence inside each example and shuffle the examples.
Lab · what's graded
- The full gradient15 pts
- The noise of one sample15 pts
- The noise of a batch15 pts
- Updates per epoch15 pts
- A step schedule that converges15 pts
- The mini-batch loop10 pts
- Why a constant step does not settle15 pts