Neural Networks • Neural Network Foundations • 17 min read

Training Neural Networks: Loss, Optimizers, and Regularization

Training is more than pressing Run

Consider a network that recognizes different kinds of leaves. You supply labeled images and run a training loop. The program will generate predictions and update weights, but that alone does not guarantee the model will learn a useful representation.

The loss function tells the system what counts as a mistake. The optimizer decides how parameters should move based on gradients. The learning rate controls update size. Regularization and other training choices help reduce overfitting and improve behavior on unfamiliar examples. These parts work together, but they do different jobs.

For example, a learning rate that is far too large can make a model jump past good parameter values; one that is extremely small can lead to painfully slow progress. And even if training loss keeps decreasing, validation performance may stop improving. That is why training requires monitoring, comparison, and sensible stopping criteria.

The sections below examine loss functions, optimizers, initialization, normalization, dropout, batch size, and practical troubleshooting. Keep the central question in mind: Does each training choice help the model learn patterns that remain useful on new data?

A neural network starts with trainable parameters, usually weights and biases, that do not yet reliably solve its intended task. Training adjusts those parameters using examples and an objective that measures how well the network performs. Three ideas organize the process: a loss function describes the error to reduce, an optimizer determines how parameters change, and regularization helps the resulting model generalize beyond the examples it has seen.

Training is not the same as inference. Training generally requires target data, loss computation, gradients, and parameter updates. Inference uses learned parameters to produce outputs without those updates.

1. The training loop

A typical supervised training iteration performs the following operations:

  1. Read a mini-batch of inputs XX and targets yy.
  2. Compute predictions y^=fθ(X)\hat{y}=f_\theta(X) using the current parameters θ\theta.
  3. Calculate a scalar loss L(y^,y)L(\hat{y},y).
  4. Compute gradients ∇θL\nabla_\theta L with automatic differentiation or backpropagation.
  5. Update parameters with an optimizer.
  6. Repeat over further batches and epochs, then evaluate on data not used for parameter updates.
Neural network training loop from batch through prediction, loss, gradients, optimizer update, and back to model
Backpropagation calculates gradients; the optimizer applies updates. Validation measures progress separately, without using validation examples to update parameters.

The arrows describe a conceptual sequence; actual libraries may fuse operations and perform some steps in parallel. The central distinction remains: backpropagation computes derivatives, while the optimizer changes parameters.

2. Loss functions: defining what the network should learn

A loss function assigns a numerical penalty to the difference between model outputs and desired outcomes. In ordinary supervised learning, the training objective often averages individual-example losses and may add regularization terms.

J(θ)=1N∑i=1Nℓ(fθ(xi),yi)+λR(θ)J(\theta)=\frac{1}{N}\sum_{i=1}^{N}\ell\big(f_\theta(x_i),y_i\big)+\lambda R(\theta)

Here NN is the number of training examples, ℓ\ell is the per-example loss, RR is an optional regularization penalty, and λ\lambda controls its strength. Some regularization methods, such as dropout or data augmentation, affect training without appearing as an additive term in this equation.

2.1 Mean squared error for regression

For continuous targets, mean squared error (MSE) is a common choice:

MSE⁡=1N∑i=1N(y^i−yi)2\operatorname{MSE}=\frac{1}{N}\sum_{i=1}^{N}(\hat y_i-y_i)^2

Suppose the target values are [2,4][2,4] and the predictions are [3,2][3,2]. The squared errors are 11 and 44, so MSE⁡=(1+4)/2=2.5\operatorname{MSE}=(1+4)/2=2.5. Squaring makes large errors contribute more than small errors. This can be useful, but it can also make training sensitive to extreme observations.

Mean absolute error (MAE), which averages ∣y^i−yi∣|\hat y_i-y_i|, is an alternative when the absolute size of errors is more relevant and reduced sensitivity to large residuals is desirable. Loss and evaluation metric need not be identical.

2.2 Binary cross-entropy for two-class prediction

For a binary target y∈{0,1}y\in\{0,1\} and predicted probability pp, binary cross-entropy is:

ℓBCE(p,y)=−[ylog⁡p+(1−y)log⁡(1−p)]\ell_{\mathrm{BCE}}(p,y)=-\left[y\log p+(1-y)\log(1-p)\right]

A confident correct prediction has low loss. A confident incorrect prediction has high loss. For numerical stability, deep-learning libraries commonly accept logits (unnormalized scores) and combine the sigmoid transformation with binary cross-entropy in one operation, for example BCEWithLogitsLoss in PyTorch.

2.3 Multiclass cross-entropy

For mutually exclusive classes with true-class label cc and predicted class probabilities pkp_k:

ℓCE=−log⁡pc\ell_{\mathrm{CE}}=-\log p_c

This favors a high predicted probability for the correct class. In PyTorch, CrossEntropyLoss typically receives raw logits and integer class indices; do not apply softmax before passing these logits to that loss function.

ProblemCommon training lossModel output expected by typical PyTorch implementation
Numerical regressionMSELossContinuous values
Binary classificationBCEWithLogitsLossOne raw logit per example
Multiclass classificationCrossEntropyLossA logit for each class

Choosing a loss is a modeling decision. A loss function is not automatically a measure of business success, safety, or real-world usefulness. Evaluate the model with metrics that match the deployment objective.

3. Gradients and parameter updates

After the forward pass and loss calculation, backpropagation applies the chain rule to compute the partial derivatives of the loss with respect to parameters:

∇θJ=[∂J∂θ1,…,∂J∂θm]\nabla_\theta J=\left[\frac{\partial J}{\partial\theta_1},\ldots,\frac{\partial J}{\partial\theta_m}\right]

For a parameter θj\theta_j, the derivative indicates the local direction and sensitivity of the objective. A negative gradient direction is a local descent direction for a differentiable objective, although a finite update does not guarantee a decrease for every step.

3.1 Gradient descent and mini-batches

Basic gradient descent updates parameters as:

θt+1=θt−η∇θJ(θt)\theta_{t+1}=\theta_t-\eta\nabla_\theta J(\theta_t)

The learning rate η>0\eta>0 controls the update scale.

  • Batch gradient descent estimates the gradient using all training examples at each update.
  • Stochastic gradient descent (SGD) in its strict mathematical sense uses a single randomly chosen example per update.
  • Mini-batch SGD uses a subset of examples per update; this is the common training setup for neural networks and is frequently called SGD in practice.

Mini-batches reduce per-update computation and often make efficient use of GPUs, but their gradient estimates vary across batches. Batch size also affects memory requirements and training dynamics.

3.2 Worked one-parameter update

Suppose the model is y^=wx\hat y=wx with x=2x=2, target y=6y=6, initial w=1w=1, and loss:

L(w)=12(wx−y)2L(w)=\frac{1}{2}(wx-y)^2

The prediction is 22, and the derivative is:

dLdw=(wx−y)x=(2−6)⋅2=−8\frac{dL}{dw}=(wx-y)x=(2-6)\cdot2=-8

At learning rate η=0.1\eta=0.1, the update gives:

wnew=1−0.1(−8)=1.8w_{\mathrm{new}}=1-0.1(-8)=1.8

The new prediction is 3.63.6, closer to the target 66, and the loss falls from 88 to 2.882.88. This is one illustrative step, not proof that an arbitrary learning rate or network will always improve.

4. Optimizers: SGD, momentum, and Adam

An optimizer uses gradients and its update rule to adjust trainable parameters. Different optimizers can converge at different speeds and yield different generalization behavior even on the same model and dataset.

4.1 SGD

For basic SGD without additional features:

θt+1=θt−ηgt\theta_{t+1}=\theta_t-\eta g_t

where gtg_t is the gradient estimated from the current batch. SGD is relatively simple, often memory-efficient, and widely used for neural network training. It may require thoughtful learning-rate selection.

4.2 Momentum

A common momentum convention is:

vt=μvt−1+gt,θt+1=θt−ηvtv_t=\mu v_{t-1}+g_t,\qquad \theta_{t+1}=\theta_t-\eta v_t

The momentum coefficient μ\mu controls how much previous update direction is retained. Momentum can reduce oscillation in some directions and accelerate progress along persistent ones. Different sources define the velocity with slightly different scaling conventions, so compare equations before assuming two implementations are identical.

4.3 Adam

Adam maintains exponentially weighted estimates of the gradient and its squared value:

mt=β1mt−1+(1−β1)gtm_t=\beta_1m_{t-1}+(1-\beta_1)g_t vt=β2vt−1+(1−β2)gt2v_t=\beta_2v_{t-1}+(1-\beta_2)g_t^2

With bias corrections m^t=mt/(1−β1t)\hat m_t=m_t/(1-\beta_1^t) and v^t=vt/(1−β2t)\hat v_t=v_t/(1-\beta_2^t), the simplified update is:

θt+1=θt−ηm^tv^t+ϵ\theta_{t+1}=\theta_t-\eta\frac{\hat m_t}{\sqrt{\hat v_t}+\epsilon}

Operations on vectors are elementwise. Adam adjusts effective step sizes separately for each parameter. It is a common starting point, but not a universal best choice.

AdamW is a related optimizer that applies decoupled weight decay. Its weight decay behaves differently from simply adding an L2 penalty to Adam’s loss. That distinction matters when comparing optimizers and tuning regularization.

OptimizerCore ideaMain consideration
SGDFollow a batch gradientSimple, often requires learning-rate tuning
SGD with momentumAccumulate directional informationMomentum coefficient affects dynamics
AdamAdapt steps from gradient momentsAdditional optimizer state, usually convenient for initial experiments
AdamWAdam-style adaptation with decoupled weight decayOften useful when weight decay is part of the training configuration

5. Learning-rate selection and scheduling

A learning rate that is too large can cause the objective to oscillate or diverge. One that is too small can make progress extremely slow. The effective choice depends on model architecture, optimizer, batch size, feature scaling, and the problem itself.

Learning-rate scheduling changes the learning rate during training. Common strategies include:

  • Step decay: Reduce the learning rate at specified epochs.
  • Cosine decay: Gradually decrease it following a cosine-shaped schedule.
  • Warmup: Start with a small learning rate and increase it over early steps.
  • Reduce on plateau: Lower it when a monitored validation metric stops improving.

A schedule may operate per epoch or per optimizer step. Follow the documented order of optimizer.step() and scheduler.step() for the particular library and scheduler.

6. Regularization: controlling overfitting

Overfitting occurs when a model adapts to training-specific patterns that do not carry over well to unseen examples. A network can achieve very low training loss while giving poor predictions on new data. Regularization broadly refers to practices that constrain or influence learning in ways intended to improve generalization.

6.1 L2 regularization and weight decay

An L2-penalized objective adds a term such as:

J(θ)=Ldata(θ)+λ2∥θ∥22J(\theta)=L_{\mathrm{data}}(\theta)+\frac{\lambda}{2}\lVert\theta\rVert_2^2

This discourages large parameter values. For ordinary SGD, the L2 gradient contributes λθ\lambda\theta, which closely corresponds to multiplicative weight decay under conventional settings. For adaptive optimizers such as Adam, coupled L2 and decoupled weight decay should not be treated as interchangeable.

Some training configurations exclude biases or normalization parameters from weight decay. The appropriate choice depends on the architecture.

6.2 Dropout

Dropout randomly zeroes selected activations during training, usually scaling retained activations to keep their expected magnitude comparable. The random masks encourage the network not to depend too strongly on specific activation pathways.

At evaluation time, standard dropout is disabled. Therefore, model.train() and model.eval() are important in PyTorch: they control dropout and certain other modules, including batch normalization.

6.3 Early stopping

Early stopping ends training when validation performance no longer improves according to a specified rule, usually after a patience period. A sound implementation stores or restores the best validation checkpoint rather than automatically retaining the final epoch’s weights.

Validation data guides training decisions; the untouched test set should not be reused repeatedly for optimizer selection or early stopping.

6.4 Data augmentation

Data augmentation creates meaningful training variations, such as flips or crops for suitable image tasks or other transformations that preserve the intended label. It can expose the model to more variation without requiring new independently collected examples.

Augmentation must respect the task: flipping a medical image or changing time-series order may alter its meaning. Augmentation should generally be applied to training data, not used to contaminate test evaluation.

TechniqueHow it influences trainingCommon caution
L2 penalty / weight decayDiscourages certain large parameter valuesExcess strength can underfit
DropoutRandomly suppresses training activationsDisable for normal evaluation
Early stoppingSelects a checkpoint before excessive fittingRequires a separate validation signal
Data augmentationAdds label-preserving training variationTransformations must truly preserve meaning

7. Normalization, initialization, and gradient stability

Regularization does not address every training problem. Some techniques primarily make optimization more stable or efficient.

Weight initialization sets initial parameter values before training. Poor initial values can create very small or very large activations and gradients. Common schemes include Xavier/Glorot initialization for some activation choices and He/Kaiming initialization for ReLU-like networks.

Batch normalization normalizes intermediate activations using batch statistics during training, with learned scale and shift parameters. Its running statistics are used during ordinary evaluation. Batch normalization can affect optimization and may have a regularizing side effect, but it is not identical to dropout or L2 penalty.

Gradient clipping caps gradient magnitude, often by global norm, to address unusually large updates. It is particularly useful in some recurrent or otherwise unstable training settings. Clipping does not repair an unsuitable objective or permanently fix every exploding-gradient problem.

Vanishing gradients make early-layer parameters update very slowly; exploding gradients can make updates unstable. Activation choice, initialization, normalization, residual connections, and clipping may help, depending on the architecture and cause.

8. A complete PyTorch training example

This example fits a small nonlinear binary classifier to synthetic two-dimensional data. It demonstrates mini-batches, logits-based loss, AdamW, gradient clearing, validation, and the distinction between training and evaluation modes. It uses no downloaded dataset.

import torch
from torch import nn
from torch.utils.data import DataLoader, TensorDataset

# Reproducible random initialization and synthetic data.
torch.manual_seed(42)

n = 800
X = torch.randn(n, 2)
# Nonlinear target: points outside a circle belong to class 1.
y = ((X[:, 0] ** 2 + X[:, 1] ** 2) > 1.5).float().unsqueeze(1)

# Separate training and validation examples before fitting.
indices = torch.randperm(n)
train_idx, val_idx = indices[:640], indices[640:]
train_loader = DataLoader(
    TensorDataset(X[train_idx], y[train_idx]),
    batch_size=32,
    shuffle=True,
)
X_val, y_val = X[val_idx], y[val_idx]

model = nn.Sequential(
    nn.Linear(2, 32),
    nn.ReLU(),
    nn.Dropout(p=0.10),
    nn.Linear(32, 1),  # Output a raw logit, not a probability.
)

criterion = nn.BCEWithLogitsLoss()
optimizer = torch.optim.AdamW(model.parameters(), lr=0.01, weight_decay=0.001)

for epoch in range(40):
    model.train()
    total_loss = 0.0
    examples = 0

    for inputs, targets in train_loader:
        optimizer.zero_grad()
        logits = model(inputs)
        loss = criterion(logits, targets)
        loss.backward()
        optimizer.step()

        total_loss += loss.item() * len(inputs)
        examples += len(inputs)

    model.eval()
    with torch.no_grad():
        val_logits = model(X_val)
        val_loss = criterion(val_logits, y_val).item()
        val_pred = (torch.sigmoid(val_logits) >= 0.5).float()
        val_accuracy = (val_pred == y_val).float().mean().item()

    if epoch == 0 or (epoch + 1) % 10 == 0:
        print(
            f"epoch={epoch + 1:02d} "
            f"train_loss={total_loss / examples:.4f} "
            f"val_loss={val_loss:.4f} "
            f"val_acc={val_accuracy:.3f}"
        )

The printed values depend on library version and numerical execution details; the purpose is to inspect whether training and validation improve, not to guarantee an exact score. A separate test split would be needed before reporting a final unbiased performance estimate. The artificial labels are derived from the same simple rule used to generate the data; success here does not establish performance on real data.

Observe these important details:

  1. optimizer.zero_grad() clears gradients accumulated from previous iterations.
  2. criterion(logits, targets) receives raw logits, avoiding a redundant sigmoid in the loss calculation.
  3. loss.backward() computes gradients, while optimizer.step() updates parameters.
  4. model.train() enables dropout; model.eval() switches it off for validation.
  5. torch.no_grad() avoids storing gradient information during validation.
  6. No optimizer update uses the validation examples.

9. Diagnosing training behavior

Track both training loss and a validation metric selected for the task. Look for patterns rather than trusting a single training number.

Observed patternPossible explanationWhat to investigate
Training and validation performance are both poorUnderfitting, inadequate features, insufficient training, or optimization problemsModel capacity, learning rate, objective and data quality
Training improves but validation deterioratesOverfitting, leakage in development decisions, or distribution mismatchRegularization, split integrity, early stopping, dataset differences
Loss becomes NaN or extremely largeNumerical instability or problematic inputsInvalid values, learning rate, gradient norms, loss implementation
Training loss barely changesWeak gradients, learning rate mismatch, disconnected parameters, or incorrect codeAutograd usage, optimizer parameter list, initializations and scales
Accuracy is high but positive cases are missedImbalanced classes or unsuitable decision thresholdRecall, precision, confusion matrix, threshold and class distribution

A training curve is evidence, not a diagnosis by itself. For instance, a training-validation gap may be affected by dropout being active only during training; compute comparison metrics in equivalent evaluation modes when making fine-grained comparisons.

10. Practical choices before training

A reliable initial workflow is to:

  1. Define the prediction target and choose a loss aligned with it.
  2. Split data appropriately and prevent leakage before preprocessing or tuning.
  3. Establish a simple baseline before increasing network complexity.
  4. Choose a small initial network and a reasonable optimizer, such as AdamW or SGD.
  5. Check that the loss decreases on a tiny batch; a model that cannot fit even a tiny sample may have a code or modeling problem.
  6. Monitor training loss and separate validation metrics.
  7. Add regularization only in response to relevant evidence, and tune it using validation data.
  8. Save reproducible configurations and the checkpoint selected during development.
  9. Evaluate once on an untouched test set when the design is finalized.

Also record random seeds, relevant package versions, data provenance, and hardware when reproducibility matters. A fixed random seed helps but does not guarantee identical results across all devices or operations.

11. Common misconceptions

“Backpropagation trains the network by itself.” Backpropagation computes gradients; an optimizer uses them to update parameters.

“Lower training loss always means a better model.” Training loss can decrease while performance on unseen examples worsens.

“Adam always beats SGD.” Neither optimizer is universally superior. Dataset, architecture, hyperparameters, compute budget, and validation results determine the choice.

“Dropout randomly removes neurons permanently.” Standard dropout suppresses activations temporarily during training; it does not permanently delete network units.

“More regularization is always safer.” Excessive regularization can underfit, and some techniques may be inappropriate for the data or architecture.

“The loss is the same as accuracy.” Loss is the optimization target. Accuracy and other metrics evaluate behavior from another perspective and can move differently.

12. Check your understanding

  1. What does the loss function specify that the optimizer does not?
  2. Why are gradients cleared before the next mini-batch in the example?
  3. What differs between SGD with momentum and Adam?
  4. Why is BCEWithLogitsLoss preferable to manually applying sigmoid before binary cross-entropy?
  5. How do dropout and early stopping differ?
  6. What is wrong with using a test set to decide when to stop training?
Show worked answers
  1. The loss defines the objective or penalty to reduce; the optimizer defines the parameter update procedure.
  2. PyTorch accumulates parameter gradients by default, so clearing prevents unintended mixing with a previous batch’s gradients.
  3. Momentum accumulates directional gradient information; Adam uses estimates of both first and second gradient moments for per-parameter adaptive updates.
  4. The combined logits-based implementation is more numerically stable and avoids redundant nonlinear transformations.
  5. Dropout introduces stochastic activation suppression during training; early stopping selects when to stop or which checkpoint to retain based on validation performance.
  6. Repeatedly consulting the test set for training decisions contaminates the final estimate and turns the test set into part of development.

Prerequisites

Continue learning

The future article links follow the planned routes in the PlainCS AI Knowledge Map and will become active when the corresponding pages are published.

14. References and further reading

Related articles in

  • Convolutional and Recurrent Neural Networks — Understand convolutional networks for spatial data and recurrent networks for sequences, including CNN filters, RNN state, LSTMs, GRUs, and practical PyTorch examples.
  • Deep Learning with PyTorch — Build, train, evaluate, and save a neural network with PyTorch using tensors, automatic differentiation, datasets, and optimization loops.
  • Forward Propagation and Backpropagation — Learn how neural networks compute predictions with forward propagation and calculate parameter gradients with backpropagation, using the chain rule and a worked example.

Image preview

Fit