The Lawfare Academy

Lawfare Group → Knowledge Institute → Lawfare Academy

← Back to program

← AI 301 — Machine Learning, Neural Networks and Language

Weeks 9–11

Neural networks, backpropagation and generalization

Learning objectives

  • Explain and trace the mechanisms in neural networks, backpropagation and generalization.
  • Apply the method to the worked example and changed-condition exercise.
  • Identify assumptions, failure cases and the evidence needed to justify a result.

Current study directions: use the original Academy preparation chapters, preserved teaching and complete optional worked reasoning on LawfareGroup.com. Retained attributed readings, source exercises and historical assignment directions are optional further study. This notice supersedes earlier textbook-supported directions preserved below and in historical companions. Independent subject review and observed learner testing remain pending.

A neural network composes parameterized transformations with nonlinearities. A layer forms weighted combinations; an activation allows the composition to represent more than a single linear map. Stacking linear transformations without nonlinearities remains linear, regardless of how many layers are used. Architecture determines representation capacity, but training data and optimization determine what is actually learned.

Backpropagation applies the chain rule through the computation graph to obtain gradients. A zero gradient through an inactive ReLU can prevent a unit from changing for that example. Initialization, scaling and numerical stability influence whether learning proceeds. Use small synthetic examples where expected behavior is known before training a large network whose failures are difficult to diagnose.

Generalization still requires held-out evaluation. More parameters can memorize noise. Weight decay, dropout, data augmentation and early stopping address different mechanisms and are not interchangeable guarantees. Early stopping uses validation behavior to choose a training duration, so the validation set is part of development. A large model with impressive demonstrations may still fail on the task's difficult cases. Measure latency, memory and training cost alongside predictive quality.

Worked reasoning The hidden units capture positive and negative differences separately. Their sum equals the absolute difference of the two inputs. A single linear function cannot represent absolute difference over the whole plane. The example demonstrates representational structure, not that gradient descent will necessarily discover these exact weights from arbitrary training data.

Extended teaching and laboratory

A neural network composes functions. Backpropagation applies the chain rule to local derivatives and accumulates contributions along paths. For h=ReLU(wx+b) and output v·h, a negative preactivation makes the derivative through that ReLU path zero. It does not prove the entire network has zero gradient or that no other input can activate that unit.

Distinguish representation from learning. Supplying weights that realize a function demonstrates expressiveness; it does not establish that an optimizer will discover those weights from limited data. Training evidence requires a specified loss, data, initialization, updates and independent evaluation.

Worked problem Let x=2,w=1,b=−1,v=3,y=0, output=v·ReLU(wx+b), and loss=.5(output−y)². Compute output and gradients with respect to v and w.

Step-by-step reasoning 1. Preactivation is 1, so h=1 and output=3. The loss is 4.5; dL/doutput=3.

  1. doutput/dv=h=1, so dL/dv=3.
  1. The active ReLU derivative is 1. doutput/dw=v×1×x=6, hence dL/dw=18. Similarly dL/db=9.
  1. If w becomes 0 with the other parameters unchanged, preactivation is −1 and this path’s gradients with respect to w,b and v are zero for this example. The statement is local to this input and path.

Backpropagation is a calculation over paths

A gradient describes how a specified numerical objective changes under a local change in a parameter. It is not an instruction that a parameter must be causal in the real world, and it is not a guarantee that reducing the objective improves the intended task. Before differentiating, state the input, computation, target and loss. Otherwise two people can calculate different gradients while correctly differentiating different objectives.

Consider a scalar input x and hidden units zi=wix+bi, hi=max(0,zi). Their scalar output is o=Σvihi, and squared-error loss is L=(o−y)²/2. The output residual e=o−y supplies dL/do=e. The derivative with respect to output weight vi is ehi. For a hidden preactivation strictly above zero, dhi/dzi=1; below zero it is zero. Consequently dL/dwi=evi1[zi>0]x and dL/dbi=evi1[zi>0]. The indicator records which side of the activation boundary the computation occupies.

The factors have distinct roles. The residual measures the loss sensitivity to output, vi transmits it back along one branch, the activation derivative gates the branch, and x connects the preactivation to its weight. Omitting a factor can produce a plausible-looking number with the wrong meaning. The derivative do/dw is not the same quantity as dL/dw because the latter also includes the loss derivative. When a parameter feeds several branches, add its path contributions; do not keep only the last branch visited by an implementation.

At z=0 the ordinary ReLU derivative is not uniquely defined. An implementation must choose a convention for optimization. The supplied laboratory uses zero at this point and avoids treating a central finite-difference comparison at the kink as proof that the chosen convention is wrong. Away from a kink, a central difference [L(w+ε)−L(w−ε)]/(2ε) provides an independent numerical check. Choose ε small enough to approximate a local change, but not so small that subtraction and floating-point error dominate. Check more than one parameter and more than one example.

Worked record: an inactive branch does not freeze the whole network

Use x=2 and target y=0. Unit 1 has w1=1,b1=−1,v1=3. Unit 2 has w2=−1,b2=0,v2=5. Preactivations are 1 and −2; hidden outputs are 1 and 0. Output is 3×1+5×0=3 and loss is 4.5. The residual is 3.

For unit 1, dL/dv1=3, dL/dw1=3×3×1×2=18 and dL/db1=9. For unit 2, its hidden output and activation derivative are both zero, so these three parameter gradients are zero on this example. The active branch can nevertheless change. Updating only v1 by learning rate 0.01 gives v1=2.97 and lowers this example’s loss to 2.97²/2=4.41045. This is a local improvement in the stated objective, not held-out evidence that the model became more useful.

A parameter update is itself a choice. Updating all parameters simultaneously means using gradients computed at the same old parameter values. Updating one parameter and then accidentally using its new value to compute another gradient implements a different procedure. Larger steps can cross activation boundaries or increase loss; a successful tiny step is not evidence that every learning rate works. Record the objective, reduction convention, input scaling and update rule before debugging a disagreement.

Independent transfer

Use the same two-unit record, but replace squared-error loss with (o−y)², without the factor one half. Predict every gradient and an output-weight-only update at learning rate 0.01. Then change x to −2 while restoring the original parameters and half-squared loss. Identify the active unit and calculate output, loss and all six parameter gradients. Finally describe a finite-difference test that avoids crossing a ReLU kink.

Compare the reasoning

Removing the factor one half doubles the gradients at the same forward state. They become 6,36,18 for v1,w1,b1, with zeros for unit 2. Updating only v1 gives 2.94; the changed loss is 2.94²=8.6436, down from 9. With x=−2 and restored parameters, z1=−3 and z2=2, so h1=0,h2=2, output=10 and half-squared loss=50. Unit 1 gradients are zero. Unit 2 has dL/dv2=20, dL/dw2=10×5×1×(−2)=−100 and dL/db2=50. The negative input gives a negative weight gradient even though the residual is positive. For numerical verification, perturb one parameter at a time with an ε that leaves its preactivation on the same nonzero side, compare against the analytic derivative, and report the loss definition used.

Training is a stateful numerical experiment

The retained chain-rule investigation already computes every path through active and inactive ReLUs. The published NumPy project additionally trains a tanh network and computes every parameter gradient before mutating weights. To interpret those updates, separate the objective, gradient estimator, optimizer state and evaluation policy. An epoch means a pass through the training examples under a declared sampling scheme; an update means one parameter change. They need not have the same count.

For a mean objective J(θ)=Σℓᵢ(θ)/n, the full gradient is the mean of individual gradients. Uniformly sampling one training row gives an unbiased gradient estimate at the fixed current parameters. A minibatch uses the mean over its sampled rows. This changes computation and sampling variability; it does not make every step lower full loss. Nonuniform sampling without appropriate weighting can target a different objective. If batches have different sizes, averaging their losses equally differs from weighting every example equally.

Use two fictional half-squared losses, ℓ₁(θ)=(θ−1)²/2 and ℓ₂(θ)=(θ−3)²/2. At θ=0 their gradients are −1 and −3, with full mean−2. A rate .1 full-gradient step reaches .2. Drawing one row uniformly reaches either .1 or .3, with expected new value .2. That equality concerns one update at a fixed starting state. Running the two rows sequentially gives θ=.1 after the first, then .39 after the second, because its gradient is now .1−3=−2.9. Reversing the order gives .37. These are two updates, not the original one-step minibatch calculation.

Momentum and adaptive state

One momentum convention is mₜ=βmₜ₋₁+(1−β)gₜ and θₜ=θₜ₋₁−ηmₜ. Other implementations omit the factor 1−β or use different lookahead updates; write the convention instead of comparing parameter values by optimizer name. With m₀=0, β=.5 and gradients 2 then−2, the states are 1 then−.5. The history smooths the changing direction, but does not certify that a finite step is safe.

A common Adam convention tracks mₜ=β₁mₜ₋₁+(1−β₁)gₜ and vₜ=β₂vₜ₋₁+(1−β₂)gₜ² coordinatewise. Starting from zero, use corrected states m̂ₜ=mₜ/(1−β₁ᵗ) and v̂ₜ=vₜ/(1−β₂ᵗ), then subtract ηm̂ₜ/(√v̂ₜ+ε). The squared-gradient average is a second-moment estimate, not by itself a centered variance. With g₁=2, β₁=.9 and β₂=.999, the raw states are .2 and .004; correction yields 2 and 4. For η=.1 the step is .2/(2+ε), approximately .1, rather than the plain-gradient step .2. Restoring weights without these state variables or the step count does not reproduce a resumed Adam run. Adaptive scaling supplies no universal convergence guarantee. Coupled L2 penalties and decoupled weight decay can implement different procedures under an adaptive optimizer.

Initialization, dropout and stopping

Identically initialized hidden units can receive identical updates and remain redundant. Random initialization breaks this symmetry; controlling its scale helps avoid tiny or exploding activations and gradients. Initialization schemes depend on fan-in, fan-out and activation assumptions, not a universal magic variance. Inspect activation and gradient magnitudes and retain the seed and actual parameter arrays needed to reproduce the run.

In inverted dropout, retain a hidden activation h with probability q>0 and use h/q when retained, zero otherwise. Its expectation is h. For h=4 and q=.5 the possible outputs are 0 and 8 with equal probabilities. Squaring gives expected value 32, whereas squaring the mean gives 16: preservation of an activation's expectation does not imply an unchanged nonlinear network output or loss. Conventional evaluation disables this training noise. A model accidentally left in training mode can produce stochastic predictions; an intentional uncertainty procedure needs its own specification and validation.

Validation-based early stopping selects a training duration, so validation is development evidence. Record the selected epoch, restore its weights and relevant state, and keep final test evaluation separate. Augmentation should represent justified task-preserving transformations; changing a label's meaning while retaining the label introduces incorrect training examples. Compare generalization, latency and failure behavior rather than treating a lower training loss as sufficient.

Optional changed batch and complete reasoning

Start the two-loss fixture at θ=2. Individual gradients are 1 and−1; the full mean is 0, so its full-gradient step stays 2. Sequential rate-.1 updates in order 1 then 2 give 1.9 then 2.01; reversing gives 2.1 then 1.99. A stationary full objective can therefore move under a particular sampled sequence. For dropout h=4,q=.25, retained output 16 occurs with probability.25: expected activation 4 and expected square 64. For Adam's first gradient−2, corrected states are−2 and 4, so the parameter moves upward by approximately .1. A zero first gradient instead yields zero numerator; ε prevents the denominator from being zero. These checks verify the stated conventions on synthetic records, not the quality of a trained model.

Optional criteria, one point each: distinguish batch weighting and update counts; trace optimizer state with the stated convention; calculate dropout expectations without commuting nonlinear functions; preserve validation/test and restart-state boundaries. Explain all four for four points.

Apply the idea

Let x=2,w=1,b=−1,v=3,y=0, output=v·ReLU(wx+b), and loss=.5(output−y)². Compute output and gradients with respect to v and w.

Two hidden units contribute to the output; one is inactive and the other active. Does the inactive unit prove the model cannot learn from this example?

Further computation — complete record

New complete record: x=2, target y=0; unit 1 parameters w1=1,b1=−1,v1=3; unit 2 parameters w2=−1,b2=0,v2=5. Preactivation zi=wix+bi, hidden hi=max(0,zi), output Σvihi and baseline loss (output−target)²/2.

Use the same two-unit record, but replace squared-error loss with (o−y)², without the factor one half. Predict every gradient and an output-weight-only update at learning rate 0.01. Then change x to −2 while restoring the original parameters and half-squared loss. Identify the active unit and calculate output, loss and all six parameter gradients. Finally describe a finite-difference test that avoids crossing a ReLU kink.

Read the worked reasoning

No. The active unit can transmit nonzero gradients, and any output bias can also update. Compute each path’s derivative and sum contributions for shared parameters. Avoid replacing a local zero derivative with a global training claim. Inspect gradient values and loss changes numerically on a small example.

Further computation reasoning

Removing the factor one half doubles the gradients at the same forward state. They become 6,36,18 for v1,w1,b1, with zeros for unit 2. Updating only v1 gives 2.94; the changed loss is 2.94²=8.6436, down from 9. With x=−2 and restored parameters, z1=−3 and z2=2, so h1=0,h2=2, output=10 and half-squared loss=50. Unit 1 gradients are zero. Unit 2 has dL/dv2=20, dL/dw2=10×5×1×(−2)=−100 and dL/db2=50. The negative input gives a negative weight gradient even though the residual is positive. For numerical verification, perturb one parameter at a time with an ε that leaves its preactivation on the same nonzero side, compare against the analytic derivative, and report the loss definition used.

Check understanding

Let x=2, w=1, b=−1, v=3, y=0, output=v·ReLU(wx+b), and L=(output−y)²/2. The ReLU is active. What is dL/dw?

  1. 6
    Feedback

    6 is doutput/dw, before multiplying by the loss derivative dL/doutput=3.

  2. 18
    Feedback

    The chain rule gives residual 3 × output weight 3 × active derivative 1 × input 2 = 18.

  3. 3
    Feedback

    3 is the residual and also dL/dv in this record; it omits the hidden-path factors needed for w.

Further reading

Current study directions: use the original Academy preparation chapters, preserved teaching and complete optional worked reasoning on LawfareGroup.com. Retained attributed readings, source exercises and historical assignment directions are optional further study. This notice supersedes earlier textbook-supported directions preserved below and in historical companions. Independent subject review and observed learner testing remain pending.

Use the preserved original investigation and connected Academy preparation/application below. Compare your reasoning with its optional complete model. Historical source directions remain in immutable edition4.

My learning →