Training Deep Networks

Backpropagation gives gradients. Training techniques decide how to use those gradients without making the network unstable.

The Big Question

At this point, the learning loop looks simple: make a prediction, compute the loss, run backpropagation, update the weights, and repeat.

If backpropagation tells every weight which direction to move, why is training deep networks still difficult?

Because knowing the direction is not enough. The step can be too large, too small, too noisy, badly scaled, or pointed through a network whose activations are already unstable. The model can also memorize the training set while getting worse on new examples.

This chapter is about the practical techniques that make the training loop stable, efficient, and useful.

The Full Training Loop

1Sample a mini-batch
2Run the forward pass
3Compute the loss
4Run backpropagation
5Let the optimizer update weights
6Monitor training and validation behavior

Earlier chapters often said gradient descent updates the weights. In modern deep learning, an optimizer usually performs the update. The optimizer decides how to use the gradients.

Core Intuition

Backpropagation is like a compass. It points downhill on the loss surface. Training techniques decide how you move while following that compass.

A careful hiker takes reasonable steps, remembers the direction of previous motion, adapts when the terrain becomes steep, keeps their equipment balanced, and stops before walking past the best point. That is the role of learning rates, optimizers, initialization, normalization, dropout, and early stopping.

The Training Toolkit

TechniqueProblemCore idea
Learning rateSteps are too tiny, unstable, or divergentControls update size
Mini-batchesFull-batch training is slowEstimate gradients from small batches
MomentumSGD zigzags across narrow valleysSmooths updates with velocity
AdamDifferent parameters need different step sizesCombines momentum with adaptive scaling
InitializationSignals vanish, explode, or neurons learn identical featuresStarts weights at useful random scales
Batch NormalizationLayer input distributions shift during trainingNormalizes activations within mini-batches
DropoutNetwork overfits or relies on specific neuronsRandomly disables neurons during training
Early stoppingValidation performance worsens after continued trainingStops at the best validation epoch

This is why the chapter feels different. We are no longer asking what a neural network is. We are asking how to make one train reliably.

Interactive Demo

Training stability lab

Optimizer path

weight direction

The same gradients can produce very different paths depending on step size and optimizer.

Early stopping curve

training lossvalidation lossbest epoch: 27
Training diagnosis
Final optimizer state
w = 2.193
b = -0.822
loss = -0.153

Learning rate controls step size

Too small crawls. Too large can bounce across the valley or diverge. The right value is often the first thing practitioners tune.

Optimizers change how gradients are used

Momentum smooths zigzags by remembering past updates. Adam adds adaptive step sizes, so parameters with different gradient scales can train together.

Validation loss decides when to stop

Training loss can keep falling while validation loss worsens. Early stopping saves the model at the best validation epoch.

Change the learning rate and optimizer to see how the same gradient landscape can produce slow, smooth, or unstable paths. Toggle dropout to see how validation behavior can change even when training loss falls.

Mathematics And Mechanics

Learning Rate

A basic gradient update is:

wwηLww\leftarrow w-\eta\frac{\partial L}{\partial w}

The learning rate η\eta controls the size of the step. If it is too small, training crawls. If it is too large, training may oscillate or diverge.

For example, if w=4w=4 and Lw=2\frac{\partial L}{\partial w}=2:

η=1:wnew=41(2)=2\eta=1:\quad w_{\text{new}}=4-1(2)=2
η=0.1:wnew=40.1(2)=3.8\eta=0.1:\quad w_{\text{new}}=4-0.1(2)=3.8
η=0.0001:wnew=40.0001(2)=3.9998\eta=0.0001:\quad w_{\text{new}}=4-0.0001(2)=3.9998

Tuning the learning rate remains one of the first things practitioners do when a neural network fails to train.

Mini-Batches

Deep learning almost always uses mini-batches. Instead of computing the gradient on the entire dataset, we compute an average gradient on a small batch:

Lbatch=1Bi=1BLi\nabla L_{\text{batch}}=\frac{1}{B}\sum_{i=1}^{B}\nabla L_i

Mini-batches balance three needs: gradients are less noisy than single-example SGD, updates happen much faster than full-batch gradient descent, and GPUs can process many examples in parallel.

Momentum

Plain SGD can zigzag when the loss surface is narrow in one direction and shallow in another. Momentum keeps a running velocity:

vt=βvt1ηLv_t=\beta v_{t-1}-\eta\nabla L
ww+vtw\leftarrow w+v_t

The optimizer develops inertia. Directions that persist accumulate speed, while directions that alternate back and forth cancel out.

Adaptive Learning Rates And Adam

Different parameters can receive gradients at very different scales. Adaptive optimizers adjust each parameter's effective step size.

RMSProp divides by a running estimate of recent squared gradients. Parameters with consistently huge gradients get smaller effective steps; parameters with tiny gradients get relatively larger ones.

Adam combines momentum and adaptive scaling. It tracks both an average gradient and an average squared gradient, which is why it often works well as a strong default optimizer.

Weight Initialization

If every weight starts at zero, neurons in the same layer receive identical gradients and learn identical features. Random initialization breaks this symmetry.

The scale of the random weights also matters. Too large can make activations and gradients explode. Too small can make signals vanish. Xavier and He initialization choose scales that keep information flowing through layers.

Batch Normalization

As earlier layers change, the inputs to later layers also change. Batch Normalization stabilizes those inputs during training by normalizing activations within a mini-batch:

x^=xμbatchσbatch2+ϵ\hat x=\frac{x-\mu_{\text{batch}}}{\sqrt{\sigma_{\text{batch}}^2+\epsilon}}
y=γx^+βy=\gamma\hat x+\beta

The learned scale γ\gamma and shift β\beta let the network recover whatever distribution is useful after normalization.

Dropout

Dropout randomly disables a fraction of neurons during training. This prevents the network from relying too heavily on any one neuron.

adrop=ma,mjBernoulli(p)a_{\text{drop}}=m\odot a,\qquad m_j\sim\text{Bernoulli}(p)

At inference time, dropout is turned off and all neurons are used. This distinction matters: dropout is a training-time regularization technique, not a prediction-time behavior.

Early Stopping

Training loss often keeps falling. Validation loss may fall at first and then rise as the model begins to overfit. Early stopping saves the model at the best validation performance rather than the final epoch.

This is why validation curves are not decoration. They are one of the main instruments for deciding whether training is working.

Implementation

A modern PyTorch training loop separates the model, optimizer, training batches, and validation monitoring. This sketch shows where the techniques fit.

import torch
from torch import nn

model = nn.Sequential(
    nn.Linear(30, 128),
    nn.BatchNorm1d(128),
    nn.ReLU(),
    nn.Dropout(p=0.3),
    nn.Linear(128, 64),
    nn.ReLU(),
    nn.Linear(64, 1),
)

criterion = nn.BCEWithLogitsLoss()
optimizer = torch.optim.Adam(model.parameters(), lr=1e-3)

best_val_loss = float("inf")
patience = 5
epochs_without_improvement = 0

for epoch in range(100):
    model.train()

    for X_batch, y_batch in train_loader:
        optimizer.zero_grad()

        logits = model(X_batch)
        loss = criterion(logits, y_batch)

        loss.backward()
        optimizer.step()

    model.eval()
    val_losses = []

    with torch.no_grad():
        for X_val, y_val in val_loader:
            val_logits = model(X_val)
            val_loss = criterion(val_logits, y_val)
            val_losses.append(val_loss.item())

    mean_val_loss = sum(val_losses) / len(val_losses)

    if mean_val_loss < best_val_loss:
        best_val_loss = mean_val_loss
        best_state = model.state_dict()
        epochs_without_improvement = 0
    else:
        epochs_without_improvement += 1

    if epochs_without_improvement >= patience:
        break

model.load_state_dict(best_state)

Notice the mode switches. model.train()\text{model.train()} turns on training-time behavior such as dropout and batch-normalization batch statistics. model.eval()\text{model.eval()} turns off dropout and uses evaluation behavior.

Interview Discussion

What role does the learning rate play?

It controls the size of each parameter update. Too small is slow; too large can cause oscillation or divergence.

Why do deep networks usually use mini-batches?

Mini-batches make updates efficient, provide reasonably stable gradient estimates, and use GPU parallelism well.

What problem does momentum solve?

Momentum reduces zigzagging by accumulating velocity in directions where gradients consistently point.

Why is Adam widely used?

Adam combines momentum with adaptive learning rates, so it often converges quickly across many problems with limited tuning.

Why should weights not all start at zero?

Identical weights create identical neurons that receive identical gradients, so the layer fails to learn diverse features.

What does Batch Normalization do?

It normalizes activations within a mini-batch and then learns a scale and shift, making optimization more stable.

Why is dropout turned off during inference?

Dropout is meant to regularize training by randomly disabling neurons. At inference, the full learned network should be used.

Why monitor validation loss for early stopping?

Training loss may keep improving even while generalization worsens. Validation loss reveals when overfitting begins.

Active Recall

1. Why is backpropagation not enough by itself to guarantee successful training?

2. What symptoms suggest the learning rate is too high?

3. Why are mini-batches preferred over full-batch updates in deep learning?

4. How does momentum differ from plain SGD?

5. What two ideas does Adam combine?

6. Why is random initialization necessary?

7. What changes between model.train() and model.eval()?

8. Why can validation loss rise while training loss falls?

Common Mistakes

  • Treating Adam as magic instead of an optimizer that still depends on learning rate and data quality.
  • Watching only training loss and missing overfitting.
  • Forgetting to switch the model into evaluation mode before validation or inference.
  • Initializing all weights to the same value.
  • Adding dropout everywhere without checking whether the model is actually overfitting.

Connection To Convolutional Neural Networks

So far, our neural networks have treated inputs as flat vectors. That works for many tabular problems, but images have spatial structure. The next chapter introduces convolutional neural networks, which learn local visual patterns such as edges, corners, textures, and objects.