AI Wiki中文/EN

Dropout: the mean stays, the loss changes

Dropout

Enumerate four masks to derive inverted dropout, an exact expected-loss gradient and a counterexample to nonlinear model averaging.

On this pageIntuitionMathematics & methodImplementationLimitationsExercisesResearch connections

Remove a feature, then compensate for its absence

Suppose two features contribute +2 and −2 to a prediction. Together they cancel. If each is independently dropped half the time, the prediction sometimes becomes strongly positive and sometimes strongly negative. Matching the average prediction does not remove that extra uncertainty—and a squared loss will notice it.

Dropout inserts random masks into training. The 2014 paper, Sections 1 and 4 describes independently retaining units and sharing parameters across the resulting subnetworks. Its basic convention rescales outgoing weights for inference. The fixed PyTorch 2.8 Dropout documentation instead rescales retained activations during training, leaving the dropout operation as identity during evaluation.

We use that second convention, called inverted dropout. To avoid a common notation trap, q always means keep probability here. The PyTorch argument p means drop probability, so p=1−q. The original paper uses p for retention.

Preserving the mean does not preserve the loss

Hold an activation vector h fixed. Draw independent masks mⱼ, each one with probability q and zero otherwise, with strictly positive q at most one. Define the masked activation and its moments:

h~j=mjhjq,mj∼Bernoulli⁡(q),E[h~j]=hj,Var⁡(h~j)=1−qqhj2.\widetilde h_j=\frac{m_jh_j}{q},\quad m_j\sim\operatorname{Bernoulli}(q),\qquad \mathbb E[\widetilde h_j]=h_j,\qquad \operatorname{Var}(\widetilde h_j)=\frac{1-q}{q}h_j^2.

The mean follows from E[mⱼ]=q. Because the mask is binary, its square equals itself; subtracting the squared mean then gives the variance. These statements concern a fixed input and the randomness of the mask, not uncertainty about the dataset.

For a linear prediction wᵀh and half squared loss against a fixed target y, independence removes cross-coordinate covariance terms:

Em[12(w⊤h~−y)2]=12(w⊤h−y)2+1−q2q∑j(wjhj)2.\mathbb E_m\left[\frac12(w^\top\widetilde h-y)^2\right] =\frac12(w^\top h-y)^2 +\frac{1-q}{2q}\sum_j(w_jh_j)^2.

To derive this, write the random prediction as its mean plus a zero-mean fluctuation, expand the square, and observe that the linear cross term averages to zero. The remaining extra term is half the prediction variance. It resembles a coordinate-weighted quadratic penalty for this fixed linear example; it is not a universal equivalence between dropout and ordinary L 2 regularization in a deep network.

Four masks tell the whole story

Take h=(1, 2), w=(2, −1), y=1 and q=1/2. The four equally likely masks (0,0), (0,1), (1,0), (1,1) produce predictions 0, −4, 4 and 0. The average is zero, the variance is eight. The ordinary half squared loss is 1/2; the expected dropout loss is 9/2.

Differentiating the finite expectation gives the exact gradient with respect to w:

∇wEm[ℓ]=(w⊤h−y)h+1−qq(w⊙h⊙h).\nabla_w\mathbb E_m[\ell] =(w^\top h-y)h+\frac{1-q}{q}(w\odot h\odot h).

The data term is (−1, −2), the additional term (2, −4), giving (1, −6). One step with learning rate 1/10 reaches w=(19/10, −2/5) and expected loss 213/100. This is a gradient step on the exact mask-averaged objective, not one random SGD realization.

There is also a small counterexample to exact network averaging. Apply ReLU after the random prediction: the four outputs are 0, 0, 4 and 0, averaging to one. Applying ReLU to the mean prediction gives zero. An expectation generally cannot be moved through a nonlinear layer.

Enumerate every possible mask

The complete Python 3.12 program enumerates masks using standard-library fractions. It computes the masked forward value, loss and gradient using the same mask, then combines them with exact probabilities. With at most eight coordinates, all possibilities fit comfortably into this teaching audit. Inputs are bounded integers or fractions; q=0 is rejected because the inverted expression divides by q.

from fractions import Fraction as F
from itertools import product


def scalar(x, bound=32):
    if type(x) not in (int,F) or abs(x)>bound:raise ValueError('bounded rational required')
    return F(x)


def audit(h, w, target, keep):
    if not 1<=len(h)<=8 or len(h)!=len(w):raise ValueError('matching vectors of length 1 through 8 required')
    h,w=[tuple(scalar(x) for x in v) for v in (h,w)]
    y,q=scalar(target),scalar(keep,1)
    if q<=0:raise ValueError('keep probability must be in (0,1]')
    rows=[];mean=second=loss=relu=F(0);gradient=[F(0)]*len(h)
    for mask in product((0,1),repeat=len(h)):
        ones=sum(mask);prob=q**ones*(1-q)**(len(h)-ones)
        masked=tuple(F(m)*x/q for m,x in zip(mask,h))
        prediction=sum((v*x for v,x in zip(w,masked)),F(0))
        residual=prediction-y
        mean+=prob*prediction;second+=prob*prediction**2
        loss+=prob*residual**2/2;relu+=prob*max(F(0),prediction)
        for j,x in enumerate(masked):gradient[j]+=prob*residual*x
        rows.append((mask,prob,prediction))
    return dict(rows=rows,mean=mean,variance=second-mean**2,
                loss=loss,gradient=tuple(gradient),expected_relu=relu)


if __name__=='__main__':
    h,w,y,q=(1,2),(2,-1),1,F(1,2)
    result=audit(h,w,y,q)
    for mask,prob,pred in result['rows']:print('mask:',mask,'probability:',prob,'prediction:',pred)
    for key in ('mean','variance','loss','gradient','expected_relu'):print(key+':',result[key])
    updated=tuple(F(v)-F(1,10)*g for v,g in zip(w,result['gradient']))
    print('updated weights:',tuple(str(v) for v in updated),'expected loss:',audit(h,updated,y,q)['loss'])

Actual output:

mask: (0, 0) probability: 1/4 prediction: 0
mask: (0, 1) probability: 1/4 prediction: -4
mask: (1, 0) probability: 1/4 prediction: 4
mask: (1, 1) probability: 1/4 prediction: 0
mean: 0
variance: 8
loss: 9/2
gradient: (Fraction(1, 1), Fraction(-6, 1))
expected_relu: 1
updated weights: ('19/10', '-2/5') expected loss: 213/100

The tests check the four literal predictions, their moments, the expected gradient and the updated loss. They also compare the gradient against symmetric finite differences of the exact expected objective, and verify that q=1 gives the deterministic result. The full audit costs O(d·2ᵈ) arithmetic and trace storage; one sampled dropout mask costs O(d). Enumeration is useful for checking the mechanism, not for training a wide layer.

Random masking is not a promise of robustness

The ordinary evaluation operation under inverted dropout is identity. Leaving training masks active makes repeated predictions random. That can be intentional in a separately specified uncertainty procedure, but it should not happen just because the model was left in training mode. Other stateful layers also respond to that mode switch.

The keep probability, placement and independence pattern are part of the algorithm. Masking individual elements, whole channels or a shared sequence feature are different choices. The present example uses independent feature masks for one fixed input, without batch normalization or recurrent state.

As q approaches zero, the rescaling and variance grow. More aggressive masking may damage useful information and make optimization harder. The toy loss improvement above provides no evidence that a particular rate improves test performance. Such a conclusion needs a held-out evaluation and a comparable training budget.

The language of “many subnetworks” is a way to describe shared masked computations. It does not mean every subnetwork has been independently optimized, nor that a deterministic nonlinear network computes their exact average. Our four-mask ReLU example makes that distinction visible.

What survives averaging?

  1. What PyTorch drop probability p corresponds to keep probability q=3/4?

Answer 1: p=1/4; retained activations are scaled by 4/3 during training.

  1. What are the expected prediction and expected half squared loss in the four-mask example?

Answer 2: Zero and 9/2, respectively.

  1. Why is the loss evaluated at the mean prediction only 1/2?

Answer 3: It omits half the prediction variance, which is four here.

  1. Does applying ReLU after replacing the random prediction by its mean give the exact average ReLU output?

Answer 4: No. It gives zero, whereas the four masked ReLU outputs average to one.

Separate a convention from a mechanism

The original paper supplies the masking model and approximate model-combination interpretation. The fixed API document supplies the inverted scaling and evaluation convention. The finite-distribution calculations, gradient step and nonlinear counterexample here are original; the paper’s benchmark experiments and library implementation were not run or copied.

Compare weight decay with the input-dependent penalty derived here, and early stopping with changing how long parameters are trained. These interventions act in different places even when all are described as regularization.

Make a prediction, then check

In the four-mask example, what is the expected half squared loss?

Choose one answer

Learning objectives

  • Derive masking moments and explain the keep/drop convention.
  • Distinguish mean predictions from expected losses.

Prerequisites & connections

Explore related knowledge →

References

  1. Dropout: A Simple Way to Prevent Neural Networks from Overfitting
    Nitish Srivastava; Geoffrey Hinton; Alex Krizhevsky; Ilya Sutskever; Ruslan Salakhutdinov · 2014
  2. Dropout — PyTorch 2.8
    PyTorch contributors

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. Decay paths, exact dropout distributions, checkpoint restoration and batch-normalization derivatives/state are checked against literal references, analytic identities and finite differences. Three examples use the standard library; BatchNorm uses NumPy1.26.4.
  • 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:

Related topics

No matches. Try a synonym or acronym.

0 results shown

Wrap the whole query in double quotes for a phrase match.