Minibatches: noise, sampling and one real update
小批量训练
Enumerate replacement and subset gradients, derive the finite-population correction and distinguish reshuffling from fresh sampling.
minibatchesEstimate a gradient without reading every example
A training objective often averages many per-example losses. A minibatch computes an update from a smaller group. This can reduce the work needed before each update and make array operations efficient, while introducing sampling variation. Batch size therefore affects both statistics and execution cost.
Deep Learning, Sections 8.1.3 and 8.3.1 describes gradient estimates from examples. D2L, Section 12.5.2 gives the minibatch average and the independent-sampling standard-error argument. We compare two sampling laws exactly so that “random batch” does not hide the assumptions.
Read empirical risk and expectation and variance. All calculations below concern a finite training objective at a specified parameter, not an estimate of test performance.
Unbiasedness refers to a sampling law and a fixed point
For N differentiable per-example losses, write:
If each index Iⱼ is an independent uniform draw from the dataset, E[ĝ]=ḡ. A uniformly chosen subset of size b without replacement also gives an unbiased average at fixed θ, even though its selected values are dependent. Independence is sufficient for the simple variance formula below, not necessary for unbiasedness itself.
For a scalar gradient, define the finite-population variance V=(1/N)Σ(gᵢ−ḡ)². Then:
WR denotes independent sampling with replacement; WOR denotes a uniform subset without replacement. For independent draws, the variance of the sum is bV. Without replacement, two distinct draws have covariance−V/(N−1): expanding the sum over unequal population indices gives that value. Adding the b diagonal and b(b−1) off-diagonal terms, then dividing by b², yields the finite-population correction. For vector gradients the same identities hold with covariance matrices.
A four-example quadratic makes every outcome visible
Choose targets a=(−3,−1,1,3), individual losses(θ−aᵢ)²/2 and start θ=1. Gradients are(4,2,0,−2), with mean 1 and population variance 5. A size-two minibatch has gradient variance 5/2 with replacement or 5/3 without replacement.
The full objective is L(θ)=θ²/2+5/2. A minibatch step θ′=θ−ηĝ has:
This identity follows by expanding the quadratic and using E[ĝ]=ḡ. At η=1/4, the full-gradient step has θ′=3/4 and loss 89/32. The expected minibatch losses are 183/64 with replacement and 17/6 without replacement. Both include a noise penalty relative to the full step. This is a one-step finite-objective result, not a statement that full-batch training always wins on wall-clock time or generalization.
Enumerate all draws and execute each update
The complete Python 3.12 program performs a real gradient update for every possible batch. With replacement it enumerates 16 ordered pairs; without replacement it enumerates 6 equally likely unordered pairs. Order is irrelevant to each batch average.
from fractions import Fraction as F
from itertools import product, combinations
TARGETS=(-3,-1,1,3)
def batch_step(theta, indices, rate=F(1,4)):
indices=list(indices)
if type(theta) not in (int,F) or abs(theta)>16 or type(rate) not in (int,F) or not 0<=rate<=1:
raise ValueError('bounded rational parameter and rate required')
if not 1<=len(indices)<=4 or any(type(i) is not int or not 0<=i<4 for i in indices):
raise ValueError('one to four valid sample indices required')
gradient=sum((F(theta)-TARGETS[i] for i in indices),F(0))/len(indices)
return F(theta)-rate*gradient,gradient
def full_loss(theta):
return sum(((theta-a)**2 for a in TARGETS),F(0))/8
def audit(theta=1, batch_size=2, replacement=True):
if type(batch_size) is not int or not 1<=batch_size<=4 or type(replacement) is not bool:
raise ValueError('batch size from 1 to 4 and a Boolean replacement policy required')
draws=product(range(4),repeat=batch_size) if replacement else combinations(range(4),batch_size)
outcomes=[batch_step(theta,indices) for indices in draws]
mean=sum(g for _,g in outcomes)/len(outcomes)
variance=sum((g-mean)**2 for _,g in outcomes)/len(outcomes)
expected_loss=sum(full_loss(updated) for updated,_ in outcomes)/len(outcomes)
return len(outcomes),mean,variance,expected_loss
if __name__=='__main__':
for replacement in (True,False):
print('replacement:',replacement,'draws, mean gradient, gradient variance, expected next loss:',
*[str(v) for v in audit(replacement=replacement)])
updated,gradient=batch_step(1,range(4))
print('full-gradient step: parameter',updated,'loss',full_loss(updated))
theta=-F(1,2)
print('two-label reshuffle after first label -1: remaining gradient',theta-1,'full gradient',theta)
Actual output:
replacement: True draws, mean gradient, gradient variance, expected next loss: 16 1 5/2 183/64
replacement: False draws, mean gradient, gradient variance, expected next loss: 6 1 5/3 17/6
full-gradient step: parameter 3/4 loss 89/32
two-label reshuffle after first label -1: remaining gradient -3/2 full gradient -1/2
Every result is rational, so the discrepancy between the two variances is exact. Tests also cover batch size 1, the full size-four subset, several parameter values and invalid indices. The exhaustive audit costs O(bNᵇ) with replacement or O(b·choose(N,b)) without replacement, with N fixed at 4. A single batch update costs O(b); production SGD samples a batch rather than enumerating all possibilities.
The gradient and expected loss are separate quantities: an unbiased gradient does not imply that a noisy update has the same expected loss as the deterministic update. At the quadratic’s optimum, a constant-step noisy gradient can move the parameter away from that optimum.
Random reshuffling has a different conditional statement
Consider a separate two-label dataset a=(−1,1), starting at θ=0 with step 1/2. If the first shuffled label is−1, the parameter becomes−1/2. The remaining label is now known to be 1, so its gradient is−3/2, whereas the full gradient at θ=−1/2 is−1/2. Conditional on the history, the next gradient is not a fresh uniform estimate of the full gradient.
This does not make reshuffling invalid. It means that a theorem assuming conditionally independent draws cannot be applied unchanged. Fixed-parameter uniform-subset unbiasedness and an evolving reshuffled training trajectory are different claims.
Bigger batches change more than noise
Larger batches reduce the displayed sampling variance but require more examples per update and more activation memory if processed together. Vectorization, data loading and device utilization affect elapsed time. No batch size is universally optimal from the variance formula alone, and this program contains no hardware benchmark.
The objective must decompose into per-example terms for the simple gradient average used here. Batch-dependent normalization, contrastive losses and cross-example interactions can make changing the batch change the function being differentiated, not only its estimator. Unequal sample weights, missing labels and partial batches also require explicit denominators.
Gradient clipping is nonlinear and can bias an otherwise unbiased gradient. Accumulating gradients across microbatches matches a larger batch only under suitable fixed-parameter, loss-scaling and model-behavior conditions. The epoch and step chapter makes those counts explicit.
Which expectation is being taken?
- What is the population variance of gradients(4,2,0,−2)?
Answer 1: Five, using denominator 4 and mean 1.
- What are the size-two gradient variances with and without replacement?
Answer 2: 5/2 and 5/3, respectively, under the stated uniform sampling laws.
- Why does an unbiased gradient still add expected loss in this quadratic one-step calculation?
Answer 3: Squaring the noisy parameter adds η²Var(ĝ)/2; expectation does not commute with the nonlinear loss.
- After seeing the first label in the two-label reshuffle example, is the next label still uniformly drawn from the whole dataset?
Answer 4: No. The history determines the one remaining label, so the fresh-uniform conditional argument does not apply.
Keep sampling and optimization assumptions separate
The sources explain minibatch averages, statistical accuracy and computational motivation. Our finite-population correction, exhaustive quadratic updates and reshuffling counterexample are original. We do not adopt a blanket claim that independence is necessary for an unbiased sample mean, or that smaller batches must improve generalization.
A reproducible report specifies batch size, replacement or reshuffling, loss reduction, learning-rate schedule and total examples processed. Continue to epochs and steps to distinguish reading data from actually applying a parameter update.
Make a prediction, then check
Does a uniform subset without replacement have an unbiased mean gradient at fixed parameters?
Learning objectives
- Derive minibatch variance under two sampling laws.
- Distinguish fixed-point unbiasedness from an evolving reshuffle.
Prerequisites & connections
Explore related knowledge →References
- Deep Learning — Chapter 8: Optimization for Training Deep Models
Ian Goodfellow; Yoshua Bengio; Aaron Courville · 2016 - Minibatch Stochastic Gradient Descent — Dive into Deep Learning 1.0.3
D2L authors · 2023
Version1 · Editorial status: Recorded technical checks completed
View technical check record (AI)
Codex · 2026-09-06 · Codex single-agent authored technical review: cited primary-source scope, explicit assumptions, original calculations and counterexamples, runnable tests and bilingual review; not independent human or second-agent review.
- Single-agent authored technical review: bounded primary-source locations, assumptions, original derivations, exact/literal references and matching bilingual equations/examples/exercises. Not independent human or second-agent review.
- Four focused CPython3.12.4 tests passed per chapter. Shared recurrent gradients, transient powers, stable clipping, exact minibatch distributions and accumulated-update traces are checked against literal references, analytic identities and finite differences. All four examples use the standard library.
- Promoted the full prose, equations, code and exercises. Tests read formal MDX only; removed temporary fallbacks/draft skips and updated review assertion to checked. Algorithm and independent references are unchanged; final record binds both locale hashes.
- Publication navigation points published topics to complete articles and removes corresponding pending wording, retaining directory entries for unwritten targets. Principles, equations, programs and exercises are unchanged; final article SHA values rebound.
Source locations checked:
- Deep Learning — Chapter 8: Optimization for Training Deep Models · Chapter8 Sections8.1.3 printed274–277 and8.3.1 gradient estimator; independence and generalization remarks qualified rather than imported universally.
- Minibatch Stochastic Gradient Descent — Dive into Deep Learning 1.0.3 · CurrentSection12.5.2 equations12.5.1–12.5.2 and independent-gradient standard-error argument; no timing or data preprocessing copied.
Related topics