Neural Networks
Batch Norm & Dropout
Change the batch statistics and dropout mask to see how they affect the same network.
A 2-10-10-1 network. Dropout is off, so every hidden unit is active and every weight is drawn. Epoch 0. Selected observation 1, layer 1, unit 1; raw 1.0107091980100253, centred 1.0107091980100253, normalised 1.0107091980100253, affine 1.0107091980100253, ReLU 1.0107091980100253, mask 1, scale 1, final 1.0107091980100253.
Post-update inference loss on both sets; edits retain history
Training loss 0.745 and held-out loss 0.900 after 0 epochs at learning rate 0.5. The gap is 0.156, held-out above training. Current losses are inside the plot ceiling.
- Training loss
- Held-out loss
Incoming rate for the next simultaneous mean-gradient update; edits pause and retain history.
Selected observation 1, layer 1, unit 1: raw 1.0107091980100253; centred 1.0107091980100253; normalised 1.0107091980100253; affine 1.0107091980100253; ReLU 1.0107091980100253; mask 1; scale 1; final 1.0107091980100253.
Do both losses measure the same procedure?
Does lower training loss guarantee lower held-out loss?
Step applies one real full-batch update. Both current evaluation losses use inference; history records post-update parameters. Training fit is not a generalisation guarantee.
Evaluation mode
Stored BN statistics and dropout disabled for both evaluation sets.
Check this stage
Check your understanding
Inspect batch statistics, learned affine values and realised dropout masks from the same current network, then switch between training and inference.
What changes in this experiment?
Batch normalisation standardises each hidden unit across observations, then learns its scale and shift. Dropout randomly removes hidden units during training and scales survivors. Neither operation guarantees better optimisation or generalisation.
The network has two inputs, two hidden layers of ten ReLU units and one sigmoid output. It fits forty fixed noisy-ring observations; three hundred separately generated observations provide exploratory held-out evaluation. Labels are 0/1. Seeded Gaussian weights use fan-in scaling, biases a small uniform draw, and gamma/beta start at one/zero.
Step performs one full-batch simultaneous mean-gradient update. Play repeats at a readable interval until the update budget or nonfinite parameters. A completed budget is not convergence. Current training and held-out losses both use inference mode and stable mean binary cross entropy from logits. Curves record clean losses immediately after actual updates; edits retain history and pause. Reused held-out observations are not an untouched final test.
Follow one observation and unit
Choose an observation, hidden layer and unit. Only the twenty hidden nodes are graph selection buttons; inputs and the output are structural marks. The selected graph node, histogram and inspection ledger share that identity. The histogram counts one unit over the forty observations rather than pooling features. The graph illustrates connectivity; labels round and omit numbers when vertical spacing is compressed, node radii shrink to avoid overlap, edge widths cap at three weight units, and dropout removes connections from the drawn active subnetwork. Loss geometry caps at five; raw losses remain in inspection.
Hidden order is linear sum → optional BN → ReLU → optional dropout. The output is linear then sigmoid. Inspection separates raw sums, centred values, normalised values, learned affine values, ReLU, binary keep masks, multipliers, final hidden outputs and network scores. Last applied gradients are labelled incoming derivatives from the pre-update parameters, separately from the current preview.
Which statistics does BN use?
For each hidden unit, training normalises across the complete batch, independently of other units:
The variance divisor is B. Epsilon is inside the root. Gamma/beta are learned per unit. Normalised training variance is v/(v+epsilon); affine variance is gamma² times that, not necessarily one. Zero gamma makes the current affine values constant; negative gamma reverses order. Epsilon prevents exact scale invariance, especially near zero variance.
For raw [1,3], mean is 2, centred values [-1,1], population variance 1. With epsilon 0.00001, normalised values are plus/minus 1/sqrt(1.00001). Gamma −2 and beta 0.5 give affine values 0.5+2/sqrt(1.00001) and 0.5−2/sqrt(1.00001). A singleton or constant batch gives normalised zero and affine beta.
Batchmates affect outputs through both statistics. Reverse accumulation includes the same paths. For gradient g at the affine output and s=sqrt(v+epsilon):
Parameter derivatives accumulate over observations and divide by batch size once for the mean loss. All gradients for an update use the same pre-update parameters and mask. ReLU chooses derivative zero at zero by convention; the kink is not smooth.
Inference uses stored running statistics, including before training. Running mean/variance start at zero/one. Each actual training forward with BN enabled retains 0.9 old and adds 0.1 current population batch statistic. Momentum means old-statistic retention here. There is no B/(B−1) variance correction or EMA bias correction. A singleton raw 3 gives running mean 0.3 and variance 0.9 after one pass; inference uses those, not singleton statistics. Inspection previews never update the stored statistics.
This is standardisation, not whitening: cross-feature covariance remains. Layer normalisation instead takes statistics across features within one observation. Internal covariate shift was an original motivation, not an established complete explanation of BN's benefits. Later research studies optimisation geometry; no such claim makes every learning rate safe.
What does the dropout mask mean?
Drop Probability is p, supported from zero through 0.9; keep probability is 1−p. The endpoint p=1 is unsupported. This lab retains a shared-unit variant: one draw per hidden unit is shared across every observation in the batch. Units and layers draw separately in layer/unit order from Mulberry32. Views reuse the same draw. This is not independent per-observation dropout.
Inverted dropout multiplies kept activations by 1/(1−p), dropped ones by zero. Inference uses all units with multiplier one. At p=0, activations are preserved exactly. At p=0.9 a survivor multiplies by ten; an entire finite layer can still happen to be dropped.
For fixed activation a, the expectation of mask*a/(1−p) is a. A realised value is zero or scaled, so it need not equal a. Preserving this intermediate expectation does not preserve the output or loss of a nonlinear network. A dropped path's local zero gradient applies to that pass, not permanent inability to learn.
Step uses seed 42 plus the number of already completed updates. Afterwards the preview replays that update’s seed under the current controls and parameters. Before any update it previews index zero. Edits recompute the same index; changing p can deterministically change the mask at that seed. Inspection and rendering never advance randomness; only an actual update advances the experiment clock.
Why does order matter?
For a kept unit with raw [1,3] at p=0.5, applying the shared multiplier two before BN gives [2,6], mean four and variance four instead of mean two and variance one. Epsilon means even the standardised values differ slightly. Dropping that shared unit produces a constant zero batch. BN followed by ReLU and dropout is a different computation. First-layer dropout also changes the second layer's input statistics.
These mechanism examples are not manufactured generalisation comparisons from independently resampled activations. Use the actual training/evaluation protocol. Large finite loss, all-dropped masks, sampling variability and nonfinite arithmetic are distinct outcomes. An unsuccessful run proves neither representational impossibility nor generalisation.
Restore and share
Reset controls restores the original network and settings, retains stage, returns guided and clears guesses/recovery. The failure preset saves a complete in-memory experiment; Restore experiment returns its parameters, running statistics, masks, history, settings, inspection, mode and prediction, paused, even after later edits.
Share stores current settings/inspection and a bounded per-update settings schedule. Deterministic replay reproduces parameters, statistics and realised randomness, opening guided/paused. Invalid schedules visibly discard the run. Guesses, recovery and progress stay out of links. Mark explored records exploration locally without assessing answers.
Sources
The original BN algorithm, dropout paper and optimisation analysis inform the mechanisms and limits. Framework conventions differ; official BatchNorm1d documentation is a comparison, not this lab's implementation contract.
Stage recap
Training and evaluation
Step applies one real full-batch update. Both current evaluation losses use inference; history records post-update parameters. Training fit is not a generalisation guarantee.
Dropout
One unit mask is shared across observations here. Survivors scale by 1/(1−p); inference keeps all without scaling. Expectation preservation is not realised equality.
Batch normalisation
Inspect one unit across observations, then switch to inference EMA. Normalised variance is v/(v+epsilon); learned affine parameters change it further. BN is not whitening or an optimisation guarantee.
Reference
- Normalise
- Each hidden unit across 40 observations: mean=sum(z)/B; v=sum((z−mean)²)/B; xhat=(z−mean)/sqrt(v+epsilon). Epsilon is inside the root.
- Scale and shift
- Learned gamma*xhat+beta; initially gamma=1, beta=0. Training variance is gamma²*v/(v+epsilon), not necessarily one.
- Batch statistics
- Batchmates affect outputs and coupled derivatives. Standardisation is neither whitening nor layer normalisation.
- At inference
- Stored running mean/variance, initially 0/1; actual training passes retain 0.9 old plus 0.1 population batch statistic. No variance or EMA bias correction.
- Inverted dropout
- Drop probability p in 0..0.9. Mulberry32 draws per hidden unit, shared across observations. Kept multiplier 1/(1−p) in training; inference one.
- Dropout backward
- The same realised multiplier scales the local gradient. Zero for this pass is not permanent inability to learn.
- Generalisation gap
- Current held-out minus training loss uses inference on both sets. An exploratory gap is not a generalisation guarantee.
- BN backward
- g=dL/d(affine), s=sqrt(v+epsilon): dz=gamma/(B*s)*(B*g−sum(g)−xhat*sum(g*xhat)). Updates use incoming mean gradients simultaneously.
- This lab
- 2–10–10–1; linear → BN → ReLU → dropout; sigmoid output, stable mean logit BCE, 40 training and 300 held-out fixed noisy-ring observations.
Break it on purpose
The high-rate/high-dropout preset produces finite losses above the plotted ceiling and sparse masks. Plot overflow, nonfinite arithmetic and completed budgets are different conditions; none proves convergence or generalisation.
Explore next
- Ridge & Lasso RegularisationA coefficient penalty changes the fitted curve; its benefit on new observations must be measured.
- SGD, momentum and AdamAn optimiser combines the current gradient with its own memory to choose an actual displacement.
- BackpropagationMultiply local Jacobians along each path; add contributions where a value feeds multiple paths.