Part II · Ch. 6 — Teaching the Network

Part II · Chapter 6 of 13

Teaching the Network

Backprop, optimizers, and the art of not memorizing


Review prerequisite concepts
  • derivatives as downhill, and the gradient as a vector of slopes
  • a loss you can see, minimized by gradient descent: θ ← θ − η·∇L
  • the sigmoid, and a classification loss
  • hidden layers; a network that CAN fit any shape, trained by nudging weights

The two problems we left open

We can build a network that bends a boundary, but two questions remain: how does each buried weight find downhill, and how do we keep the network from memorizing the examples?

ProblemWhat we need
Find every slopeBackpropagation traces the loss backward through the calculation to find each weight’s slope; an optimizer uses those slopes to choose a step.
Learn a transferable patternHeld-out data means examples kept out of weight updates, so we can check new-data performance; regularizers are ways to discourage fitting noise.

We keep the gradient-descent rule from fitting a line. The distinction to hold on to through this chapter is between making the training loss fall and making a useful model.

How blame reaches a buried weight

The chain rule multiplies local slopes along a calculation. For its slow build and nudge-check, see the sister site's backpropagation chapter; we use its same numbers.

A left-to-right pipeline. Forward, along the middle: a mint chip x = 2 feeds a violet dial w1 = 1, giving a white chip h = 2, which feeds a violet dial w2 = 2, giving a chip y-hat = 4, which feeds a red-outlined box reading target y = 3 and L = (4 minus 3) squared = 1. Above the pipeline the backward story runs right to left in red: a red arrow spanning the width, blame value 2 over y-hat tagged dL/dy-hat = 2 times miss, blame value 4 over h, and two red drop-arrows descending into the two dials carrying boxed formulas partial-L/partial-w1 = 4 times 2 = 8 and partial-L/partial-w2 = 2 times 2 = 4. A bottom strip reads: step eta = 0.05, w1 goes 1 to 0.6, w2 goes 2 to 1.8, re-run, L goes 1 to 0.71.
A forward pass stores values; a backward pass reuses them to compute both weights’ slopes.

Input $x=2$ meets $w_1=1$, giving $h=w_1x$; then $w_2=2$ gives $\hat y=w_2h$, “y-hat,” our prediction; target $y=3$.

$$h = w_1 x = 2, \quad \hat{y} = w_2 h = 4, \quad L = (\hat{y} - y)^2 = 1$$

In words: the input stays at $h = 2$ through the first weight, doubles again into $\hat{y} = 4$, and since the target was $3$ the prediction is one too high, for a squared loss of $1$.

The curly $\partial$, read “partial,” means a slope while other weights stay fixed. Follow blame backward:

  1. Loss: $\partial L/\partial\hat y=2(\hat y-y)=2$, using the toolkit’s square-slope rule.
  2. Outer weight: $\partial\hat y/\partial w_2=h=2$; multiply $2\times2=4$.
  3. Hidden value: $\partial\hat y/\partial h=w_2=2$; blame arrives as $2\times2=4$.
  4. Inner weight: $\partial h/\partial w_1=x=2$; multiply $4\times2=8$.
  5. Collect: in weight order $(w_1,w_2)$, the gradient is $[8,4]$.
$$\frac{\partial L}{\partial w_2} = 2(\hat{y}-y)\cdot h = 2\times 2 = 4 \qquad \frac{\partial L}{\partial w_1} = 4 \times 2 = 8 \qquad \nabla L = \begin{bmatrix} 8 \\ 4 \end{bmatrix}$$

In words: the loss is twice as sensitive to the inner weight as to the outer one, so the gradient, the vector of both slopes, is eight over four.

WeightLocal slopeLoss slope
$w_2$$h=2$$2×2=4$
$w_1$$x=2$$4×2=8$

Let $\theta$ (“theta”) collect the weights and $\eta$ (“eta”) be the learning rate. Apply the update rule $\theta\leftarrow\theta-\eta\nabla L$ with $\eta=0.05$:

$$w_1 \leftarrow 1 - 0.05\times 8 = 0.6 \qquad w_2 \leftarrow 2 - 0.05\times 4 = 1.8 \;\Rightarrow\; L: 1 \to 0.71$$

In words: nudge each weight a little against its own blame, re-run the network, and the loss falls from $1$ to about $0.71$ in one measured step.

Check: $2\times0.6=1.2=h$; $1.2\times1.8=2.16=\hat y$; the miss is $2.16-3=-0.84$, whose square is about $0.71$.

After the stepCalculationValue
Hidden value$2×0.6$$1.2$
Prediction$1.2×1.8$$2.16$
Loss$(2.16-3)^2$$0.7056$

One forward pass stores values; one backward pass computes all weight slopes from them.

One wrong guess is split into a share of blame for every weight, and the blame travels backwards along the wires that carried the signal. (3:06)

Better ways downhill

A bird's-eye contour map of a long narrow elliptical valley, its floor running left to right toward a violet star at the origin. Three descent paths start from the same white dot at upper right labeled start. A blue SGD path zigzags violently up and down across the narrow direction while creeping along the floor. A mint momentum path makes one gentle damped wave and settles at the star. An amber Adam path descends almost straight down the diagonal to the star. Labels: SGD zigzags, momentum smoother, Adam adaptive, and a note reading a long narrow valley: plain steps zigzag across it.
On this illustrative valley, momentum smooths zigzags and Adam adapts the step size by direction.

On the toolkit's bowl, plain downhill steps work well; narrow valleys and flat plateaus make the walk harder.

Picture a ball rolling downhill rather than a hiker re-deciding at every footstep. The ball crosses a plateau because it arrives carrying speed, and it stops zigzagging across a narrow valley because the sideways pushes alternate and cancel while the gentle downhill push points the same way every step and builds up.

  1. SidewaysAlternating pushes cancel.
  2. DownhillConsistent pushes accumulate.
  3. PlateauArrive carrying speed.

For momentum, $\beta$ (“beta”) is the momentum coefficient, usually about $0.9$: nine-tenths of the previous velocity survives each step. Its memory spans roughly ten steps, smoothing wobble while still responding to change.

$$\mathbf{v} \leftarrow \beta\,\mathbf{v} + \nabla L \qquad \theta \leftarrow \theta - \eta\,\mathbf{v}$$

In words: build up speed in directions the slope keeps pointing, and let disagreeing wiggles cancel out. Then step along that accumulated velocity rather than the raw gradient.

Adam scales each weight's step in proportion to (average gradient) divided by the square root of (average squared gradient). Large squared gradients reduce the scale; smaller ones increase it. The learning rate $\eta$ still matters, and tuned SGD with momentum can win.

NameWhat it remembersWhen it helps
stochastic gradient descent (SGD)No past gradients; estimate the slope from a small random batch.Cheaper than grading the full dataset every step; jitter can help escape shallow traps.
MomentumA velocity $\mathbf v$ accumulating recent gradients.Alternating sideways slopes cancel; consistent slopes build speed through valleys and plateaus.
AdamPer-weight averages of gradients and squared gradients.Adaptive scaling when weights have very different gradient magnitudes; often needs less tuning.

Memorizing instead of learning

CurveCapacityRisk on seven points
LineNo bendsMiss the trend
Degree 3Up to two bendsFollow the gentle trend
Degree 9Up to eight bendsChase the noise

Picture seven noisy points around a gentle trend. A straight line underfits: it misses the bend even on training data. A degree-3 curve allows up to two bends and follows the trend; a degree-9 curve allows up to eight and can pass through all seven points while swinging wildly between them. That curve overfits: it fits noise as though it were signal.

Three panels sharing the same seven blue scatter points that follow a gentle bend with noise. Left panel, labeled underfit a straight line: a mint straight line that misses the bend, noted misses the pattern. Middle panel, labeled good fit a gentle curve: a mint degree-3 curve tracking the trend, noted follows the trend ignores the noise. Right panel, labeled overfit a wild curve: a mint degree-9 curve threading every point exactly and oscillating wildly, noted hits every point learns nothing.
The same seven points support an underfit line, a useful gentle curve, or an overfit curve that chases noise.

Generalization means performance on new data, which is our goal. A network's power to fit complicated shapes also gives it the capacity to memorize.

Hold out examples that never update the weights. Plot their loss alongside training loss over epochs, meaning complete passes through the training set. At first both fall; later, training loss keeps falling while held-out loss rises.

A loss-versus-epochs plot. A mint training-loss curve falls smoothly and keeps falling toward about 0.05. An amber validation-loss curve falls with it at first, reaches a minimum near epoch 27 at about 0.30, then rises steadily to about 0.56. A violet dashed vertical line and dot mark the minimum, labeled early stop best generalization. The region to the right is faintly shaded red and labeled overfitting: training keeps improving, validation gets worse. A double arrow on the right marks the vertical gap between the curves, labeled this gap = memorization.
The validation minimum marks the useful stopping point in this example; further training improves the training score while worsening held-out performance.

In the figure, validation loss bottoms near epoch 27 at about $0.30$, then rises toward $0.56$ while training loss approaches $0.05$. Early stopping keeps the model from the best validation checkpoint rather than chasing the lowest training loss.

Three piles of data

Before training, separate three jobs:

PileUseBoundary
training setFit the weights.These examples drive gradients.
validation setChoose learning rate, size, optimizer, and stopping point.Development choices can overfit this set too.
test setEstimate final performance once.Never use its results to choose the model.

Each validation-guided choice leaks information into the design, making that score more optimistic. The untouched test set checks the whole selection process. Tune against it once and it stops measuring anything.

A common split is 80/10/10. What matters more is that all three piles represent the world the model will face, with no disguised duplicates crossing the split. With scarce data, cross-validation rotates the held-out slice and averages results.

Discouraging memorization

A regularizer discourages fitting noise, trading some training accuracy for better performance on new data.

MethodWhat changesWhy
Weight decay / L2Add a penalty for large weights.Favors gentler functions unless larger weights earn their cost.
DropoutRandomly zero some neuron outputs each training step, say half.Discourages dependence on one fragile shortcut; resembles sharing weights across an ensemble.
Early stoppingKeep the best validation checkpoint.Stops before further fitting damages held-out performance.
More relevant dataAdd varied, representative examples.Makes accidental training patterns less persuasive.

For L2, $\lambda$ (“lambda”) controls the penalty strength and $\mathbf w$ collects the weights:

$$L_{\text{total}} = L + \lambda\,\lVert \mathbf{w} \rVert^2$$

In words: pay the usual loss, plus a fee that grows with how big the weights get, so the network keeps them small unless a big weight earns its keep. The double bars are the vector length from the toolkit, so $\lVert \mathbf{w} \rVert^2$ is that length squared: every weight squared and added up.

WeightsSquared lengthFee at $\lambda=0.1$
$[1,1]$$1+1=2$$0.2$
$[2,2]$$4+4=8$$0.8$
$[3,3]$$9+9=18$$1.8$

Raising $\lambda$ makes the fee bite harder, favoring the gentle degree-3 curve over violent wiggles. Too much regularization underfits, so choose its strength using validation performance. The most reliable cure for overfitting is a bigger, more varied training set that represents the task, and every regularizer above is partly a substitute for data you did not have. More data makes accidental patterns harder to rely on; it does not make memorization impossible.

The whole training loop

The full training loop for every neural network in this book fits in three steps. The order matters: split before fitting, use validation for development, and save the untouched test set for the final grade.

  1. FitForward → loss → backward → step; repeat on training batches.
  2. ChooseUse validation to choose settings and the stopping point.
  3. GradeTest once, after those choices are settled.

You have hand-graded a two-weight network ($\nabla L = [8, 4]$, loss $1 \to 0.71$), watched a wiggly curve memorize seven points, and seen the discipline of three piles and one final test.

Where you'll meet this

WhereWhat it looks likeChapter link
Language pretrainingThe same forward/loss/backward/step loop over trillions of tokensThe training run
ImagesConvolutional wiring changes the model; the training discipline is the sameSeeing machines
Sequences and graphsOrdered or linked inputs; still validate and regularizeRemembering machines / Networks of relationships

What you now know

  • Backpropagation reuses stored values to compute every weight’s local slope.
  • Momentum accumulates direction; Adam also adapts scaling by weight.
  • Generalization measures performance on unseen data, not the training score.
  • Training fits weights, validation guides choices, and an untouched test set grades the result.
  • Regularization and early stopping discourage memorization; validation reveals whether they help.

Where we’re headed. We can train a network and measure it. Next, the classical toolbox shows when a different model earns its place, before we match network wiring to grids, sequences, and graphs.