Unit 4 · Tutorial 4 of 8
The Cost Function and the Loss Surface
In Tutorial 3 you found the least-squares solution by solving the normal equations. That worked because linear regression has a closed form. Almost nothing else in machine learning does. This tutorial reframes fitting as a search over a landscape — and shows that for linear regression the landscape is a bowl with exactly one bottom.
1 Learning objectives
By the end of this tutorial you will be able to
- Distinguish a loss function (one example) from a cost function (the whole dataset).
- Convert RSS into mean squared error and explain three reasons the division by n matters.
- Describe the loss surface — what its axes are, what its height means, and how to read a contour plot of it.
- Define convexity, verify that the MSE cost function is convex, and explain why this is the single most valuable property a cost function can have.
- Compute the gradient of MSE with respect to the parameters, and interpret it as the direction of steepest ascent.
- Explain how feature scaling changes the shape of the loss surface, and why that matters for iterative fitting.
- Sketch the path that gradient descent takes on a convex surface, and explain why it can zig-zag even when there is only one minimum.
Estimated time
30 minutes of reading, plus 20–25 minutes for the practice exercises and problem set. The visualisations in Section 4 carry a lot of the intuition — look at them before reading Section 3.4.
2 Motivating example
Tutorial 3 left you with a formula. Given the sums Sxy and Sxx, the least-squares slope is Sxy/Sxx and that is that. So why not move on to the next algorithm?
Because the formula only works here. Logistic regression — the very next unit — has no closed-form solution. Decision trees, neural networks, support vector machines, and essentially every model that has been built since the 1970s: no closed-form solution. If the only fitting technique you possess is "solve the normal equations", you can fit exactly one model.
So this tutorial does something that looks at first like a step backwards. Instead of solving for the best parameters, we will search for them — the way you would search for the lowest point in a foggy valley, by feeling the slope of the ground under your feet and stepping downhill. It is slower than the formula and it needs a starting point and a step size. But it works when no formula exists, which is almost always.
Before you can walk downhill, you need a landscape. That is what this tutorial builds.
The question we are answering
For every possible pair of parameters (w, b), how bad is the resulting line? If we could plot badness against every possible parameter choice, what would that picture look like?
Why it matters beyond Unit 4
Every model you train for the rest of this course is fitted by minimising some cost function. The vocabulary introduced here — loss surface, convexity, gradient, learning rate, conditioning — is the shared language of all of it.
The valley metaphor, taken seriously
Imagine standing in a foggy valley and wanting to reach the lowest point. You cannot see more than a metre. But you can feel which way the ground slopes. So you take a small step in the downhill direction, feel again, and repeat. If the valley has one basin, you will reach the bottom. If it has many, you will reach a bottom — and it may not be the deepest one.
That metaphor is not decoration. It is a precise description of gradient descent, and the "one basin or many" question is exactly the question of convexity.
3 Concept explanation
3.1 From RSS to mean squared error
In Tutorial 3 the criterion was the residual sum of squares:
RSS(w, b) = Σi=1n (yi − w xi − b)²
The least-squares solution minimises this. But RSS has an awkward property: it grows with the size of the dataset. Fit the same model to 100 examples and to 100,000 examples drawn from the same process, and the RSS will be roughly a thousand times larger in the second case — even though the model is no worse.
Dividing by n fixes this. The result is the mean squared error:
Mean squared error (MSE) cost function
J(w, b) = (1/n) Σi=1n (yi − w xi − b)²
J is used throughout this course for the cost function. Other common names in the literature are C, L, or 𝒥. The choice of letter is arbitrary; the meaning is not.
Minimising J and minimising RSS give exactly the same parameters, because dividing by the positive constant n does not move the location of the minimum. It only rescales the vertical axis of the picture we are about to draw.
3.2 Why divide by n?
Three reasons, in increasing order of importance:
| Reason | Explanation |
|---|---|
| Comparability | MSE is on the same scale regardless of dataset size, so you can compare the fit quality of two models trained on different amounts of data — and compare training error against validation error computed on a differently sized split. |
| Interpretability | MSE is the average squared error per prediction, in squared units of the target. With rentals, MSE is measured in "rentals squared" — awkward, but the square root (RMSE) is in rentals, which is directly meaningful. |
| Mathematical convenience | The 1/n cancels cleanly when you differentiate, and it makes the gradient an average rather than a sum — which means stochastic and mini-batch gradient descent (Module 5) are natural extensions rather than ad-hoc fixes. |
3.3 Loss versus cost versus objective
These three words are used loosely in practice, but they name three distinct things, and the distinction becomes important when you read papers.
- Loss function
- A measure of error for one example. For linear regression, the squared error ℓ(w, b; xi, yi) = (yi − ŷi)².
- Cost function
- A measure of error for the whole training set, usually the average of the per-example losses. MSE is the cost function for linear regression.
- Objective function
- The thing you actually optimise. It is usually the cost function, but it may include extra terms — a regularisation penalty, for instance. In Module 3 you will meet ridge regression, whose objective is MSE plus a penalty on the size of the weights.
So the loss is per-example, the cost is the aggregate, and the objective is whatever you hand to the optimiser. In this unit they coincide closely enough that the distinction is a formality — but it is a formality that will save you confusion later.
3.4 The loss surface
Here is the conceptual leap of this tutorial. J(w, b) is a function of the parameters, not of the data. The data is fixed; we are varying the model.
That means we can plot it:
- The horizontal axes are the parameters — one axis per parameter. For simple linear regression there are two, w and b, so the plot lives in three dimensions.
- The vertical axis is the cost J: how badly that particular parameter setting fits the training data.
- Each point on the surface corresponds to one complete model. A point high on the surface is a bad model; the lowest point is the best one.
The shape of this surface is called the loss surface or cost surface. Training a model means finding the lowest point on it.
Reading a contour plot
Three-dimensional surfaces are hard to read on a screen, so we usually flatten them. A contour plot draws lines of equal cost, exactly like a topographic map. Each closed curve is a set of parameter pairs that produce identical MSE. The innermost ring surrounds the minimum.
Two things to read from a contour plot: the location of the centre (where the best parameters are) and the shape of the rings (how easy the surface is to navigate). Circular rings mean an easy surface; long narrow ellipses mean a hard one.
3.5 Convexity
Now the crucial property. A function is convex if the line segment joining any two points on its graph lies on or above the graph. Informally: the surface is shaped like a bowl, never like a mountain range with multiple valleys.
Two consequences follow immediately, and they are the reason convexity is prized:
- Any local minimum is a global minimum. There are no false bottoms to get trapped in. If you walk downhill and stop, you have arrived at the best possible answer.
- The minimum is unique (assuming the features are not perfectly collinear). There is exactly one best parameter vector, and every correct algorithm will find it.
Is the MSE cost function for linear regression convex? Yes. Expanding the square shows that J is a quadratic function of the parameters, with a positive coefficient on the squared terms:
J(w, b) = (1/n) Σ ( yᵢ − w xᵢ − b )²
= (1/n) Σ ( yᵢ² − 2 yᵢ(w xᵢ + b) + (w xᵢ + b)² )
= (1/n) Σ yᵢ² − (2/n) w Σ xᵢyᵢ − (2/n) b Σ yᵢ
+ (1/n) w² Σ xᵢ² + (2/n) wb Σ xᵢ + (1/n) n b²
Every parameter appears at most squared, and the coefficients on w² and b² — namely (1/n)Σxi² and 1 — are positive. That is precisely the algebraic signature of a convex quadratic. Geometrically, the surface is an upward-opening paraboloid: a bowl.
Convexity is not guaranteed in general
Linear regression is convex. Logistic regression, surprisingly, is also convex. But neural networks are not convex — their loss surfaces genuinely have many local minima, plateaus and saddle points. This is why Module 5 spends considerable time on optimisation. Everything you learn about the convex case here is the baseline against which the hard cases are understood.
3.6 The gradient
If the loss surface is a landscape, the gradient is the compass. The gradient of J is the vector of its partial derivatives with respect to each parameter:
∇J = ( ∂J/∂w , ∂J/∂b )
For MSE, differentiating with respect to each parameter in turn:
Gradient of the MSE cost function
∂J/∂w = −(2/n) Σ xi (yi − ŷi) = −(2/n) Σ xi ei
∂J/∂b = −(2/n) Σ (yi − ŷi) = −(2/n) Σ ei
Two things to notice about these expressions:
- Each derivative is proportional to a residual-weighted sum. The derivative with respect to w weights each residual by its feature value xi; the derivative with respect to b weights them all equally. That makes sense: w controls how steeply the prediction changes with the input, so an error on a large-x example is more informative about w than an error on a small-x example.
- Both derivatives are zero exactly when the normal equations hold. Setting ∂J/∂b = 0 gives Σei = 0, and setting ∂J/∂w = 0 gives Σxiei = 0. These are the two normal equations from Tutorial 3. The calculus and the algebra are the same statement.
The gradient has a geometric meaning that you should internalise: it points in the direction of steepest ascent. Stand at a point on the loss surface and the gradient tells you which way is most sharply uphill. Which means the negative gradient points most sharply downhill — and that is the direction a minimiser wants to move.
3.7 The shape of the surface depends on the data
The loss surface is not a property of the algorithm. It is a property of the data. Change the data and you change the landscape — sometimes dramatically.
The most important way this happens in practice is through feature scaling. Suppose you have two features in a multiple regression: one measured in metres, ranging from 0 to 3, and one measured in millimetres, ranging from 0 to 3000. A one-unit change in the first is a large physical change; a one-unit change in the second is barely anything. The cost surface becomes extremely elongated along one axis, forming a long narrow valley rather than a round bowl.
| Surface shape | Contours | Gradient descent behaviour |
|---|---|---|
| Well-conditioned | Nearly circular | Moves almost directly to the minimum. Large learning rates are safe. |
| Ill-conditioned | Long narrow ellipses | Zig-zags back and forth across the narrow valley, making slow progress along it. Requires a small learning rate to avoid diverging. |
This is the practical reason StandardScaler exists. Rescaling the
features so they have comparable ranges makes the contours rounder, which makes
iterative fitting faster and more stable. Tutorial 5 will show the effect
numerically; the point here is that it is a property of the
landscape, visible before you run a single optimisation step.
Zig-zag is not a bug
On a long narrow valley, the steepest direction at any point is nearly perpendicular to the valley floor. So gradient descent keeps crossing the valley and bouncing off the sides rather than heading straight down it. This happens on a perfectly convex surface with a single minimum — it has nothing to do with local minima. It is purely a consequence of the shape of the bowl. If you see a zig-zagging loss curve, the fix is rescaling the features or tuning the learning rate, not switching to a different algorithm.
3.8 What convexity does and does not buy you
Convexity is a strong guarantee, so it is worth being precise about its scope.
Guaranteed
- No local minima other than the global one.
- No saddle points that trap a minimiser.
- Any algorithm that reaches a stationary point has found the optimum.
- The optimum is unique if the features are linearly independent.
Not guaranteed
- That gradient descent will reach the minimum in finite time — it may only approach it asymptotically.
- That it will reach it quickly — the conditioning of the surface still matters.
- That the minimum is a good model — a convex objective can still be the wrong objective for your problem.
- Anything about generalisation. Training error and test error are different questions.
That third point deserves emphasis. You can minimise MSE perfectly and still have a model that is useless, because MSE may not be the quantity you actually care about. Tutorial 6 takes this up in detail.
4 Visual illustration
5 Worked example
We continue with the bike-share data from Tutorials 1 and 3, and this time we evaluate the cost function at several parameter settings, then compute the gradient at one of them.
Step 1 — Evaluate J(w, b) at four candidate models
Recall the eight observations: x = [8, 12, 15, 18, 21, 24, 27, 30] °C, y = [120, 180, 240, 300, 360, 430, 510, 560] rentals, and n = 8. From Tutorial 3, the least-squares solution is ŵ ≈ 20.65 and b̂ ≈ −62.60.
Below, each candidate pair is scored by Computing all eight predictions, all eight residuals, squaring them, summing, and dividing by 8.
| w | b | Predictions at the eight temperatures | RSS | MSE = RSS/8 |
|---|---|---|---|---|
| 20.0 | 0.0 | 160, 240, 300, 360, 420, 480, 540, 600 | 21,000.0 | 2,625.00 |
| 20.0 | −50.0 | 110, 190, 250, 310, 370, 430, 490, 550 | 1,000.0 | 125.00 |
| 20.5 | −60.0 | 104, 186, 247.5, 309, 370.5, 432, 493.5, 555 | 840.75 | 105.09 |
| 20.65 | −62.60 | 102.6, 185.2, 247.2, 309.1, 371.1, 433.0, 495.0, 556.9 | 830.9 | 103.87 |
| Least-squares solution (from Tutorial 3) | ≈831 | ≈103.9 | ||
The numbers tell the story of the surface. Moving from (20, 0) to (20, −50) cuts the cost by a factor of 21 — a huge improvement from a small change in the intercept. From there to (20.5, −60) it falls another 16%. From there to the optimum it falls only 1.2%. The surface is steep far from the minimum and almost flat near it.
That flattening is general, and it is why optimisation converges quickly at first and then slows down. It is also why you should not judge progress by the size of the improvement in the last few iterations.
Step 2 — Compute the gradient at (w, b) = (21, −70)
Start from a point that is near the minimum but not at it. Compute the predictions and residuals:
| x | y | ŷ = 21x − 70 | e = y − ŷ | x · e | e² |
|---|---|---|---|---|---|
| 8 | 120 | 98 | +22 | 176 | 484 |
| 12 | 180 | 182 | −2 | −24 | 4 |
| 15 | 240 | 245 | −5 | −75 | 25 |
| 18 | 300 | 308 | −8 | −144 | 64 |
| 21 | 360 | 371 | −11 | −231 | 121 |
| 24 | 430 | 434 | −4 | −96 | 16 |
| 27 | 510 | 497 | +13 | 351 | 169 |
| 30 | 560 | 560 | 0 | 0 | 0 |
| Sum | +5 | −43 | 883 | ||
Applying the gradient formulas:
∂J/∂w = −(2/n) Σ xᵢ eᵢ
= −(2/8) × (−43)
= +10.75
∂J/∂b = −(2/n) Σ eᵢ
= −(2/8) × (+5)
= −1.25
∇J(21, −70) = ( +10.75 , −1.25 )
Step 3 — Interpret the gradient
The gradient is (+10.75, −1.25). Both components are small relative to the MSE values we computed earlier, which already tells us we are close to the bottom — recall that at (20, 0) the gradient with respect to w was around +1,872, roughly 175 times larger.
Reading the signs:
- ∂J/∂w is positive, so increasing the slope slightly would increase the cost. To reduce the cost we should decrease the slope. And indeed, the optimum slope is 20.65, slightly less than the current 21.
- ∂J/∂b is negative, so decreasing the intercept slightly would increase the cost. To reduce the cost we should increase the intercept. The optimum is −62.60, which is larger than the current −70.
So the direction of steepest descent, −∇J = (−10.75, +1.25), points toward a smaller slope and a larger intercept. That is the right general direction. Check it explicitly with a small step, using a learning rate α = 0.001:
w_new = 21 − 0.001 × 10.75 = 20.98925
b_new = −70 − 0.001 × (−1.25) = −69.99875
MSE(21, −70) = 883 / 8 = 110.375
MSE(20.98925, −69.99875) ≈ 110.370
The cost decreases, by a tiny amount. Repeating this step many times, with a suitable learning rate, is gradient descent — and it is the subject of Tutorial 5.
Step 4 — Verify the gradient vanishes at the optimum
At the least-squares solution the two normal equations hold, which means both partial derivatives are zero:
At w = 20.6502, b = −62.5976:
Σ eᵢ ≈ 0 → ∂J/∂b = −(2/8) × 0 = 0
Σ xᵢeᵢ ≈ 0 → ∂J/∂w = −(2/8) × 0 = 0
The gradient is the zero vector, so the surface is flat underfoot. This is the signature of a stationary point. Because the surface is convex, a stationary point must be the global minimum — there is nowhere else for it to be.
The same computation in code
import numpy as np
import pandas as pd
df = pd.DataFrame({
"temp_c": [ 8, 12, 15, 18, 21, 24, 27, 30],
"rentals": [120, 180, 240, 300, 360, 430, 510, 560],
})
x = df["temp_c"].to_numpy()
y = df["rentals"].to_numpy()
n = len(x)
def mse(w, b):
"""Mean squared error for the line y = w*x + b."""
return ((y - (w * x + b)) ** 2).mean()
def gradient(w, b):
"""Gradient of MSE with respect to (w, b)."""
e = y - (w * x + b)
return -2 * (x * e).mean(), -2 * e.mean()
print(f"{'w':>8} {'b':>9} {'MSE':>12}")
for w, b in [(20.0, 0.0), (20.0, -50.0), (20.5, -60.0), (21.0, -70.0)]:
print(f"{w:8.2f} {b:9.2f} {mse(w, b):12.2f}")
print(f"\nleast-squares optimum: MSE = {mse(20.6502, -62.5976):.2f}")
gw, gb = gradient(21.0, -70.0)
print(f"\ngradient at (21, -70) : dJ/dw = {gw:+.2f}, dJ/db = {gb:+.2f}")
gw0, gb0 = gradient(20.0, 0.0)
print(f"gradient at (20, 0) : dJ/dw = {gw0:+.2f}, dJ/db = {gb0:+.2f}")
gwo, gbo = gradient(20.6502, -62.5976)
print(f"gradient at optimum : dJ/dw = {gwo:+.4f}, dJ/db = {gbo:+.4f}")
w b MSE
20.00 0.00 2625.00
20.00 -50.00 125.00
20.50 -60.00 105.09
21.00 -70.00 110.38
least-squares optimum: MSE = 103.87
gradient at (21, -70) : dJ/dw = +10.75, dJ/db = -1.25
gradient at (20, 0) : dJ/dw = +1872.50, dJ/db = +100.00
gradient at optimum : dJ/dw = -0.0000, dJ/db = +0.0000
Compare the two gradients. At (20, 0), far from the optimum, the gradient components are in the thousands. At (21, −70), close to the optimum, they are in the single digits. At the optimum itself they are zero to four decimal places. The magnitude of the gradient is a direct measure of how far you are from the bottom — which is exactly what makes it useful as a stopping criterion.
6 Interactive activity
Draw the landscape, then walk on it
In the Tutorial 4 notebook, build the loss surface for the bike-share data and explore it systematically. Work through the following and record what you find:
-
Build the grid. Evaluate
mse(w, b)for every combination of w innp.linspace(15, 26, 120)and b innp.linspace(-120, 20, 120). Store the results in a 120 × 120 array. -
Plot the contours. Use
plt.contour(W, B, J, levels=30). Mark the least-squares solution with a star. Are the rings circular or elongated? What does that tell you? - Confirm the shape. Slice the surface along b = −62.6 (holding w at the optimum intercept value) and plot J against w. Is it a parabola? Now slice along w = 20.65. Is that a parabola too?
- Walk downhill. Starting from (21, −70), run gradient descent for 200 iterations with a learning rate of 0.0005. Plot the path on top of the contours. How many steps does it take to get within 1% of the optimal MSE?
- Change the step size. Repeat with learning rates of 0.0001, 0.001 and 0.005. Which ones converge? Which overshoot? What happens at α = 0.01?
- Change the scaling. Now convert temperature to Fahrenheit (xF = 1.8xC + 32) and rebuild the surface. Compare the contour shapes before and after. Run gradient descent with the same learning rates and compare the convergence.
Show the discussion
-
Grid and storage. Use broadcasting:
W, B = np.meshgrid(w_vals, b_vals)and then computeJas a 2-D array. Doing this with a loop over 14,400 points is slow; the vectorised version is instant. - Elongated rings. The contours are noticeably elongated, tilted ellipses rather than circles. That means the surface is ill-conditioned: the cost changes much more rapidly in some directions than others. This is why gradient descent zig-zags rather than heading straight for the centre.
- Both slices are parabolas. That is the definition of a convex quadratic in two variables — any one-dimensional slice through it is an upward-opening parabola. The curvatures of the two parabolas differ, which is precisely what the elongated contours were telling you.
- Convergence. With α = 0.0005, several hundred iterations are needed to get within 1% of the optimal MSE. The path curves in a spiral rather than travelling straight to the centre, reflecting the elongated shape of the contours. Notice that the first few iterations make enormous progress and the later ones barely move — the surface flattens near the bottom.
- Learning rates. α = 0.0001 converges but takes thousands of iterations. α = 0.0005 is workable. α = 0.001 is faster but starting to oscillate. α = 0.005 overshoots and diverges — the cost grows without bound until it overflows. α = 0.01 diverges immediately. The relationship between the largest safe learning rate and the curvature of the surface is the single most important practical fact about gradient descent.
- Scaling. In Fahrenheit, the optimal slope becomes approximately 20.65/1.8 ≈ 11.47 and the intercept changes accordingly, but crucially the contours become rounder — or more elongated, depending on which direction you scaled. What matters is the ratio of the curvatures, not the absolute values. The largest safe learning rate changes when the scaling changes, which is why you must always retune it after rescaling features.
The two numbers that govern everything
The behaviour of gradient descent on a quadratic surface is governed by the curvature in each direction. The largest curvature sets the maximum safe learning rate; the ratio of largest to smallest curvature (the condition number) sets how slowly you crawl along the flat direction. A surface with a condition number of 1000 takes roughly a thousand times longer to converge than one with a condition number of 1. Feature scaling reduces the condition number, and that is its entire practical purpose.
7 Self-check questions
Answer each question in your own words before revealing the answer.
Question 1
What is the difference between a loss function and a cost function, and which one is MSE?
Show answer
Question 2
A colleague computes the RSS of a model on a 1,000-row training set and gets 12,500. You compute the RSS of what you believe is a comparable model on a 10,000-row set and get 118,000. Which model fits better? What should you have computed instead?
Show answer
Question 3
The MSE cost surface for linear regression is convex. State two guarantees this provides, and two things it does not guarantee.
Show answer
Guaranteed:
- There is exactly one minimum, and it is global — no local minima to get trapped in.
- Any point where the gradient is zero is that global minimum, so reaching a stationary point means you have solved the problem.
Not guaranteed: that gradient descent will reach the minimum quickly (ill-conditioning can make it slow), and that the resulting model will be good for your actual purpose — a convex objective can still be the wrong objective, and training error says nothing about generalisation.
Question 4
At some point on the loss surface, ∂J/∂w = +50 and ∂J/∂b = −8. In which direction should you move to reduce the cost most rapidly, and what does each sign tell you?
Show answer
The signs tell you about the local slope: a positive ∂J/∂w means increasing the slope raises the cost, so the current slope is too large. A negative ∂J/∂b means decreasing the intercept raises the cost, so the current intercept is too small.