Level 5 · ExplorerLesson 5.1 36 min read 10 question quiz 11 marks of written practice

Loss Functions and Gradients: Measuring Wrongness

What a loss function is

To improve, a model needs to know how wrong it is, as one number. That number is the loss (also called the cost or error), and the formula that produces it is the loss function. Training means changing the parameters to make the loss as small as possible.

The crucial shift in thinking: during training the data is fixed and the parameters vary. So the loss is a function of the parameters. Each choice of w gives a different line, and each line has a different loss.

Loss as a function of a parameterOn the left, three small plots of the revision data with three candidate lines, all with b equal to 33.2: w equal to 3 is far too shallow, w equal to 6.5 fits well, and w equal to 10 is far too steep. On the right, the mean squared error plotted against w is a U-shaped bowl. The three lines appear as points on it: w equal to 3 has loss 306, w equal to 6.5 has loss 4 at the bottom of the bowl, and w equal to 10 has loss 299.Each value of w is a different line, with a different lossw = 3w = 6.5w = 100100200300400500234567891011the weight wloss (MSE)w = 3: loss 306w = 6.5: loss 4the bottom of the bowlw = 10: loss 299
Training is the search for the bottom of this bowl.

For the revision data from Level 4, with b held at 33.2, a slope of 3 badly underestimates, a slope of 10 badly overestimates, and the loss is lowest at w ≈ 6.5. Plotted against w, the mean squared error makes a bowl, and training means finding the bottom of the bowl.

Common loss functions

TaskLoss functionFormula for one example
RegressionMean squared error(y − prediction)²
Regression with outliersMean absolute errorthe size of (y − prediction)
Yes or no classificationBinary cross-entropy (log loss)−[y × log p + (1 − y) × log(1 − p)]
Choosing one of many classesCategorical cross-entropy−log(probability given to the correct class)

Here p is the probability the model gave to "yes", and y is 1 for yes and 0 for no. The loss over a dataset is the average over all the examples.

Why cross-entropy?

Cross-entropy only looks at the probability the model gave to the right answer, and takes the negative logarithm.

The cross-entropy loss curveA graph of cross-entropy loss, minus the natural log of p, against p, the probability the model gave the correct answer. The curve is near zero at p equal to 1 and shoots upwards as p approaches 0. Marked points: confident and right, p equal to 0.9, loss 0.11; unsure, p equal to 0.5, loss 0.69; confident and wrong, p equal to 0.05, loss 3.00. A table lists p of 0.99, 0.9, 0.5, 0.1 and 0.01 with losses 0.01, 0.11, 0.69, 2.30 and 4.61.Cross-entropy: −ln(probability given to the right answer)01234500.20.40.60.81probability the model gave the correct answerlossconfident and rightloss 0.11unsureloss 0.69confident and wrongloss 3.00ploss0.990.010.90.110.50.690.12.300.014.61
Halving an already small probability costs far more than halving a large one.
Probability given to the right answerLoss, −ln p
0.990.01
0.90.11
0.50.69
0.12.30
0.014.61

Being confidently wrong is punished brutally: the loss heads to infinity as p heads to 0. That pushes a classifier to be honest about uncertainty. A language model's training loss is exactly this, averaged over every next-word prediction it makes.

The loss landscape

With two parameters, w and b, the loss is a surface over the w-b plane: a landscape whose height at each point is the loss of that line.

A loss landscape in 3DA 3D surface shaped like a tilted oval bowl, coloured by height from yellow for high loss at the rim down through pink and purple to deep blue for low loss at the bottom. The floor axes are the weight w and the bias b. A path of cyan dots starts high on the rim at a random model and steps downhill, with long steps on the steep sides and shorter steps as the bowl flattens, ending at a green star at the bottom, the minimum: the best model.Two parameters: the loss is a landscape, and training rolls downhillstart: a random modelminimum: the best modelhigh losslow lossheight = lossfloor = w and b
Every point on the floor is one model. Its height is how wrong it is.
  • Every point on the floor is one possible model.
  • The height above it is how wrong that model is.
  • Training is a search for the lowest point.

For linear regression the landscape is a single smooth bowl. For a neural network it is a landscape in millions or billions of dimensions, with valleys, ridges, plateaus and saddles. Nobody can picture that, but the maths of finding the way down is the same in any number of dimensions.

A contour map of the landscape, like a walking map of a hill, joins points of equal loss. The rings close in on the minimum.

Slopes and derivatives

To walk downhill you need to know which way is down. In one dimension, that is the slope, and in calculus the slope of a curve at a point is its derivative.

Slopes of the loss curveA U-shaped curve, the loss L of w equals w minus 3 squared, for w from 0 to 6. Dashed tangent lines touch it at three points. At w equal to 1 the tangent slopes down with slope minus 4, and an arrow points right: move right to go downhill. At w equal to 3, the bottom, the tangent is flat, slope 0. At w equal to 5 it slopes up with slope plus 4, and an arrow points left. The derivative is dL by dw equals 2 times w minus 3.The derivative is the slope of the tangent0246810120123456wloss L(w) = (w − 3)²at w = 1slope −4: move rightat w = 3slope 0: the bottomat w = 5slope +4: move leftdL/dw = 2(w − 3)
Move against the slope: that is the whole idea of gradient descent.

For the loss L(w) = (w − 3)², the derivative is dL/dw = 2(w − 3):

wSlope 2(w − 3)Meaning
1−4Downhill is to the right: increase w
30The bottom: no slope at all
5+4Downhill is to the left: decrease w

So the derivative tells us two things: its sign says which way is uphill, so we move the other way, and its size says how steep the slope is.

Three rules you will use

  • Power rule: the derivative of x² is 2x, of x³ is 3x², of xⁿ is nx to the power n − 1.
  • Constant multiple: the derivative of 5x² is 5 × 2x = 10x.
  • Chain rule: for a function inside a function, multiply the derivatives. The derivative of (w − 3)² is 2(w − 3) × 1. Level 7 shows that backpropagation is the chain rule applied over and over.

Gradients: slopes in many directions

With many parameters, we take the slope in each direction separately. Each one is a partial derivative, written ∂L/∂w, "the rate the loss changes as w changes, with everything else held still". Collected into a vector, they make the gradient, written ∇L.

Gradients on a contour mapA contour map of a bowl-shaped loss: nested tilted ovals around the minimum, marked with a green dot. A grid of small arrows shows the negative gradient at each point; they all point downhill towards the minimum and are longer where the slope is steeper. At one highlighted point two arrows leave in opposite directions: a red arrow, the gradient, pointing steepest uphill, and a green arrow, the negative gradient, pointing steepest downhill, which is the way gradient descent steps.A contour map of the loss, with arrows pointing downhillminimumweight wthe gradient ∇Lpoints uphill, steepest way upthe negative gradient −∇Lpoints downhill: the way to stepsmall arrows−∇L across the map; longer where steeperringscontours: every point on a ring has equal lossbias b
The arrows always cross the contours at right angles: the steepest way down.
The gradient points uphill

The gradient points in the direction in which the loss increases fastest. So the negative gradient points steepest downhill. Every learning step in deep learning moves the parameters a little way along the negative gradient.

The gradient of the mean squared error

For the line prediction = wx + b, with error = prediction − y for each example:

Gradients of MSE

∂L/∂w = the average of 2 × error × x, and ∂L/∂b = the average of 2 × error

These are easy to read. If the predictions are too high, the errors are positive, both gradients are positive, and stepping against them lowers w and b. The bigger an example's x, the more it pushes on w.

Numerical gradients: checking with tiny nudges

You can estimate a derivative without any calculus: nudge the parameter a tiny amount h up and down, and see how much the loss changes.

Central difference

slope ≈ [L(w + h) − L(w − h)] ÷ 2h, with h very small, such as 0.0001

This is how engineers check that their gradient code is correct, called gradient checking. But it is far too slow to train with: a model with a billion parameters would need two billion loss calculations for a single step. Backpropagation (Level 7) gets every partial derivative at once for the cost of about one extra pass through the model, which is what makes deep learning possible at all.

Hands-on: losses and gradients in code

The loss curve, drawn in text

Python
hours = [1, 2, 2, 3, 4, 5, 6, 6, 7, 8]
score = [38, 45, 50, 52, 61, 64, 70, 75, 78, 86]
b = 33.2

def loss(w):
    return sum((w * x + b - y) ** 2 for x, y in zip(hours, score)) / len(hours)

for w in [3, 4, 5, 6, 6.5, 7, 8, 9, 10]:
    L = loss(w)
    print(f"w = {w:4}: loss {L:7.1f} " + "#" * int(L / 10))

Calculus versus nudging

Python
def L(w):
    return (w - 3) ** 2

def exact_slope(w):
    return 2 * (w - 3)

def nudge_slope(w, h=0.0001):
    return (L(w + h) - L(w - h)) / (2 * h)

for w in [1, 3, 5, 10]:
    print(f"w = {w:2}: exact {exact_slope(w):6.2f}   by nudging {nudge_slope(w):6.2f}")

The gradient of the revision model

Python
hours = [1, 2, 2, 3, 4, 5, 6, 6, 7, 8]
score = [38, 45, 50, 52, 61, 64, 70, 75, 78, 86]

def gradients(w, b):
    n = len(hours)
    dw = sum(2 * (w * x + b - y) * x for x, y in zip(hours, score)) / n
    db = sum(2 * (w * x + b - y) for x, y in zip(hours, score)) / n
    return dw, db

for w, b in [(0, 0), (10, 40), (6.52, 33.23)]:
    dw, db = gradients(w, b)
    print(f"at w={w:5}, b={b:5}: dL/dw = {dw:8.2f}, dL/db = {db:7.2f}")

At (0, 0) both gradients are large and negative, so increasing w and b reduces the loss. At (10, 40) they are positive: the line is too high. At the least squares answer they are almost exactly zero, which is how you recognise the bottom of the bowl.

Cross-entropy

Python
import math

for p in [0.99, 0.9, 0.7, 0.5, 0.3, 0.1, 0.01]:
    print(f"p(correct) = {p:4}: loss = {-math.log(p):.3f}")

Level check

  • Explain what a loss function is and why it is a function of the parameters
  • Choose a suitable loss for regression and for classification
  • Calculate cross-entropy for a prediction and explain why confident mistakes cost so much
  • Describe a loss landscape and what its lowest point represents
  • Calculate a derivative with the power rule and explain what its sign and size mean
  • Explain what the gradient is and why we step in the opposite direction

Key terms you must be able to define

Loss function
A formula giving one number that measures how wrong a model's predictions are; training minimises it.
Mean squared error
The average of the squared differences between predictions and true values.
Cross-entropy
A classification loss: the negative logarithm of the probability given to the correct answer.
Loss landscape
The surface formed by the loss over every possible setting of the parameters.
Minimum
The lowest point of the loss: the best parameters for the training data.
Derivative
The slope of a function at a point: how fast its output changes as its input changes.
Partial derivative
The slope with respect to one parameter while all the others are held fixed.
Gradient
The vector of all the partial derivatives; it points in the direction of steepest increase.
Chain rule
The derivative of a function of a function is the product of their derivatives.
Gradient checking
Comparing gradients from code with estimates made by nudging each parameter slightly.

Flashcards

DefineLoss function
AnswerA formula giving one number that measures how wrong a model's predictions are; training minimises it.
DefineMean squared error
AnswerThe average of the squared differences between predictions and true values.
DefineCross-entropy
AnswerA classification loss: the negative logarithm of the probability given to the correct answer.
DefineLoss landscape
AnswerThe surface formed by the loss over every possible setting of the parameters.
DefineMinimum
AnswerThe lowest point of the loss: the best parameters for the training data.
DefineDerivative
AnswerThe slope of a function at a point: how fast its output changes as its input changes.
DefinePartial derivative
AnswerThe slope with respect to one parameter while all the others are held fixed.
DefineGradient
AnswerThe vector of all the partial derivatives; it points in the direction of steepest increase.

Go further: notes for future AI engineers

Where cross-entropy comes from

Cross-entropy comes from information theory, founded by Claude Shannon in 1948. The information in an event with probability p is −log₂ p bits: a fair coin flip carries 1 bit, a 1 in 1,024 event carries 10. Cross-entropy measures how many bits, on average, you would need to encode what really happened using the model's probabilities. A perfect model needs the fewest. So when a language model's loss falls, it is literally becoming a better compressor of text, which is why some researchers describe prediction and compression as two sides of the same coin.

Maximum likelihood

Minimising cross-entropy is the same as choosing the parameters that make the training data most probable under the model, called maximum likelihood estimation. Minimising mean squared error is maximum likelihood too, if the noise is assumed to follow a normal distribution. Behind the formulas sits one idea: choose the model under which what you saw was most likely.

Misconceptions to avoid

Avoid these
  • Thinking the loss is a function of the input data. During training the data is fixed and the loss changes with the parameters.
  • Stepping in the direction of the gradient. The gradient points uphill; descent goes the opposite way.
  • Using mean squared error for a classifier that outputs probabilities. Cross-entropy trains them far better.
  • Assuming a zero gradient always means the best answer. It can also be a saddle point or a local minimum.
  • Believing numerical gradients are used for training. They are only used to check code, because they are far too slow.
Fun fact

Every large language model is trained by making one number smaller: the average cross-entropy loss of its next-word predictions. Months of computing and billions of parameters, all in the service of nudging that single number down.

Knowledge check

0 of 10 answered
1During training, what is the loss a function of?
2Which loss is the usual choice for a classifier that outputs probabilities?
3A model gives the correct class a probability of 0.5. What is its cross-entropy loss, −ln 0.5?
4What happens to cross-entropy loss as the probability given to the right answer approaches 0?
5What is the derivative of L(w) = (w − 3)² at w = 5?
6The derivative of the loss at the current w is negative. What should training do to w?
7In which direction does the gradient point?
8What is a partial derivative?
9Why are numerical gradients not used to train large models?
10What does a contour on a loss contour map join?
Score 0 / 10

Check you could explain this

11 marks
1Explain why cross-entropy is a better loss than accuracy for training a classifier.4 marks
Explain

Mark scheme0 / 4
  • LCross-entropy uses the predicted probability of the correct class
  • LIt gives larger loss for confident wrong answers
  • LIt changes smoothly, so gradients exist / small improvements are rewarded
  • LAccuracy only counts right or wrong / is flat so gives no gradient
Model answer

Cross-entropy uses the probability the model gave to the correct class, so it measures how confident the model was as well as whether it was right, and it punishes confident wrong answers very heavily. Because it changes smoothly as the probabilities change, it has a gradient, so even a small improvement lowers the loss and gradient descent knows which way to move. Accuracy only counts right or wrong, so it stays flat while the model improves slightly, giving no gradient to learn from.

The marker looks for key phrases. If you said it another way and it is still right, give yourself the mark.

Think this answer or mark scheme is wrong? Report it

2For L(w) = (w − 4)², calculate dL/dw at w = 1 and explain what the answer tells you.3 marks
Calculate

Mark scheme0 / 3
  • LdL/dw = 2(w − 4)
  • LAt w = 1 it is −6
  • LNegative, so the loss falls as w increases: increase w
Model answer

dL/dw = 2(w − 4), so at w = 1 it is 2 × (1 − 4) = −6. The slope is negative, which means the loss decreases as w increases, so to reduce the loss w should be increased, towards the minimum at w = 4. The size, 6, shows the slope is fairly steep, so w is a long way from the minimum.

The marker looks for key phrases. If you said it another way and it is still right, give yourself the mark.

Think this answer or mark scheme is wrong? Report it

3Describe what the gradient of a loss function is and how it is used in training.4 marks
Describe

Mark scheme0 / 4
  • LThe vector of partial derivatives of the loss for every parameter
  • LIt points in the direction of steepest increase in loss
  • LTraining moves the parameters in the opposite direction
  • LBy a small step, scaled by the learning rate, repeatedly
Model answer

The gradient is the vector of partial derivatives of the loss with respect to every parameter. It points in the direction in which the loss increases most steeply. In training, each parameter is moved a small step in the opposite direction, along the negative gradient, with the size of the step set by the learning rate. Repeating this many times walks the parameters downhill towards a minimum of the loss.

The marker looks for key phrases. If you said it another way and it is still right, give yourself the mark.

Think this answer or mark scheme is wrong? Report it

Machine mark 0 / 11