Loss Functions
Measuring how wrong a model is: MSE for regression and cross-entropy for classification.
The Autograd section established how to compute for every weight matrix in a network. The remaining question is: what is ? Training cannot begin until we can measure whether the model's predictions are good or bad. A loss function provides that measurement.
What Is a Loss Function?
A loss function takes the model's predictions and the ground-truth labels , and returns a single non-negative scalar:
Three properties are required:
- Scalar output. Backpropagation starts with . This requires to be a single number, not a vector.
- Non-negative, with zero at perfect predictions. A loss of zero means the model has nothing left to improve. Any positive value signals room for improvement.
- Differentiable. We need to flow backward through the network. Discontinuities would break the gradient computation.
The loss is the root node of the computation graph — the single value from which the entire backward pass begins.
Mean Squared Error
Mean Squared Error (MSE) is the standard loss for regression: problems where the output is a continuous value.
Each term is the squared prediction error for one example. Squaring serves two purposes: it makes every term non-negative regardless of the sign of the error, and it penalizes large errors more than small ones — an error of contributes four times as much as an error of .
Example. With predictions and targets :
The partial derivative with respect to prediction is:
When , this gradient is positive: the loss decreases if we reduce the prediction. When , it is negative: the loss decreases if we increase the prediction. At , the gradient is zero and the loss is at its minimum.
MSE works well when the output is unbounded and errors in both directions carry the same importance. Typical use cases: estimating a price, predicting a temperature, regressing on any continuous quantity.
Cross-Entropy
Cross-entropy is the standard loss for classification: problems where the output is a discrete category. Unlike regression, the network's raw output must first be converted to a probability — a number between and — before the loss can be applied.
Binary Cross-Entropy
For binary classification (two possible classes), the loss for a single example is:
where is the true label and is the predicted probability of class .
When the true label is , only the first term survives: . This decreases toward zero as (correct prediction) and grows to infinity as (confidently wrong prediction). When , the second term applies symmetrically.
Example. True label , predicted probability :
The model was confident and correct, so the loss is small. With instead (confident but wrong): .
Categorical Cross-Entropy
For multi-class classification ( classes), the loss generalizes to:
where is a one-hot vector (all zeros except a single at the true class) and is a probability vector summing to (typically produced by a softmax layer). Because only the true class has , this reduces to : the negative log-probability assigned to the correct class.
Example. Three classes, true class is , predicted probabilities :
Only the probability at the correct class enters the sum. A model that assigns would incur ; one that assigns would incur .
The shape of the curve explains why cross-entropy works well for classification. A model that assigns probability to the correct class incurs a loss near zero — confident and right. A model that assigns incurs a loss near — confident and wrong. The steep slope near creates a strong gradient signal exactly when the model most needs correction.
The partial derivative with respect to the predicted probability of the correct class is:
This grows large as , giving a strong correction gradient for badly wrong predictions.
The Loss as a Landscape
For a network with weight matrices , the loss is a function of all weights at once: . Evaluated over all possible weight configurations, this defines a high-dimensional surface.
Good weight configurations sit in valleys of this surface; bad configurations sit on peaks or plateaus. The goal of training is to find a valley. The gradient points toward higher ground at the current position, and the next article shows how to use it to descend.
Connection to Backpropagation
The loss computation adds one final node to the computation graph built during the forward pass. When .backward() is called:
- The seed gradient is .
- The loss's backward function immediately computes — the gradient of the loss with respect to the network's predictions.
- This gradient flows backward through every operation in the network, ultimately reaching the weight matrices.
The choice of loss function determines , which in turn shapes how every weight is updated. A different loss function produces a different gradient signal, leading to different learned representations.
In Code
import torch
import torch.nn.functional as F
# MSE — regression
pred = torch.tensor([1.0, 2.0, 3.0], requires_grad=True)
target = torch.tensor([2.0, 2.0, 2.0])
mse = F.mse_loss(pred, target)
mse.backward()
print(mse) # tensor(0.6667, grad_fn=...) — mean((pred − target)²)
print(pred.grad) # tensor([-0.6667, 0.0000, 0.6667]) — 2·(pred − target) / 3
# Categorical cross-entropy — 3 classes, single example
# F.cross_entropy takes raw logits and the index of the true class, and applies softmax internally.
# Using logits = log([0.1, 0.7, 0.2]) so that softmax recovers [0.1, 0.7, 0.2],
# matching the numerical example from the article text.
logits = torch.log(torch.tensor([[0.1, 0.7, 0.2]])).requires_grad_() # shape (1, 3)
label = torch.tensor([1]) # the true class is 1
ce = F.cross_entropy(logits, label)
ce.backward()
print(ce) # ≈ tensor(0.3567) — −log(0.7): negative log-prob of the true class
print(logits.grad) # ≈ tensor([[ 0.1000, -0.3000, 0.2000]]) — softmax − one_hot
# Binary cross-entropy — one probability, written out by hand
p = torch.tensor([0.9], requires_grad=True)
y = torch.tensor([1.0])
bce = -(y * torch.log(p) + (1 - y) * torch.log(1 - p))
bce.backward()
print(bce) # tensor([0.1054]) — −log(0.9): confident and correct
print(p.grad) # tensor([-1.1111]) — −1/p: the loss falls steeply as p rises toward 1
A loss function measures where the model stands. Its gradient, propagated backward through the network, tells every weight how much it contributed to that error. The next step is to use this information to adjust those weights in a direction that reduces the loss.