Learning path: Predict a Number: Regression from Scratch to Regularisation · Step 2 of 6
Gradient Descent Explained: Feel the Slope, Step Downhill
Instead of handing over the best line, let the computer walk to it: measure the slope of the cost, step downhill with a learning rate, repeat. Shown step by step on six kids' ages and weights.
What you will learn
- Explain the gradient as the slope of the cost and read its sign
- Apply the update rule w = w - learning_rate * gradient by hand and in a loop
- Pick a learning rate that is not too small and not too big
- Train both w and b together and explain what a local minimum is
Before you start
- Basic Python and NumPy
- Linear Regression and the Cost Function
Imagine you're standing on a hill in thick fog. You can't see the bottom, but you can feel the ground under your feet. It slopes down this way. So you take a step downhill, feel again, step again, and keep going until the ground feels flat. Flat means you've reached the bottom.
That's gradient descent. The hill is the cost, where you stand is the value of w, and the slope under your feet is the gradient.
In Linear Regression and the Cost Function, np.polyfit simply handed us the best line for six kids: w = 2.4, b = 7.13. Now the computer walks there by itself.
Setup: the same six kids
import numpy as np
import pandas as pd
df = pd.read_csv("kids_age_weight.csv")
x = df["age"]
y = df["weight"]
def mse(w, b):
y_hat = w * x + b
return np.mean((y - y_hat) ** 2)
print(mse(5, 0))
94.5
Same data, same mse function as last time.
The cost is a valley
To see the hill, start with one knob. Freeze b at 7.13 and score a few values of w:
b = 7.13
for w in [0, 1, 2, 2.4, 3, 4, 5]:
print(w, round(mse(w, b), 2))
0 211.22
1 72.48
2 6.74
2.4 0.89
3 14.01
4 94.27
5 247.53
High on the left, high on the right, lowest at w = 2.4. Put these on a graph and it's a valley, with the best w right at the bottom. (Note that w = 5 scores 247.53 here, not 94.5, because b is now 7.13, not 0.)
The gradient: the slope of the cost
The gradient tells you how steep the cost is at the point where you stand. You don't need to work out the formula yourself; here it is in code:
def gradient(w, b):
y_hat = w * x + b
return -2 * np.mean(x * (y - y_hat))
print(round(gradient(5, b), 1))
print(round(gradient(1, b), 1))
189.8
-102.2
- At
w = 5the gradient is +189.8. Positive means the cost rises to the right, so we walk left. - At
w = 1it's -102.2. Negative means the cost falls to the right, so we walk right.
The sign says which way to go. The size says how steep it is.
One step: the update rule
Every step uses the same rule:
w_new = w - learning_rate * gradient
w is where you stand, the gradient is the slope, and the learning rate is how big a step you take. One step by hand, from w = 5 with a learning rate of 0.01:
5 - 0.01 * 189.8 = 3.102
Notice the minus sign. It turns uphill into downhill: a positive slope makes w smaller, a negative slope makes it bigger.
Five steps down the valley
Now put the rule in a loop. Find the gradient, update w, print:
w = 5
learning_rate = 0.01
for step in range(1, 6):
g = gradient(w, b)
w = w - learning_rate * g
print(step, round(g, 1), round(w, 3),
round(mse(w, b), 3))
1 189.8 3.102 18.869
2 51.2 2.59 2.2
3 13.8 2.452 0.984
4 3.7 2.414 0.896
5 1.0 2.404 0.889
The columns are step, gradient, new w and MSE. The first step jumps from 5 to 3.102 and the MSE drops from 247.53 to 18.869. By step 5, w is 2.404 and the MSE is 0.889, the same score as the best line.
Why do the steps get smaller? The rate stays at 0.01, but the gradient shrinks (189.8, 51.2, 13.8, 3.7, 1.0) because the ground gets flatter near the bottom. When w stops changing, we say it has converged.
b frozen at 7.13 (grey dots are the seven scores from the table). Gradient descent starts at w = 5 and the first step jumps to 3.102. Each step after that is smaller, because the slope gets flatter near the bottom.Learning rate: how big a step
The learning rate is a number you choose. Try three of them, ten steps each, all starting at w = 5:
for lr in [0.001, 0.01, 0.03]:
w = 5
for step in range(10):
w = w - lr * gradient(w, b)
print(lr, round(w, 2), round(mse(w, b), 1))
0.001 3.62 55.0
0.01 2.4 0.9
0.03 17.2 7999.4
- 0.001: after ten steps
wis only 3.62 and the MSE is still 55. Too slow. - 0.01:
wreaches 2.4, MSE 0.9. Just right. - 0.03:
wends at 17.2 and the MSE is 7999.4. It blew up.
To see why, print the path of w for each rate:
for lr in [0.001, 0.01, 0.03]:
w, path = 5, [5]
for step in range(10):
w = w - lr * gradient(w, b)
path.append(round(float(w), 2))
print(lr, path)
0.001 [5, 4.81, 4.63, 4.47, 4.32, 4.18, 4.05, 3.93, 3.82, 3.71, 3.62]
0.01 [5, 3.1, 2.59, 2.45, 2.41, 2.4, 2.4, 2.4, 2.4, 2.4, 2.4]
0.03 [5, -0.69, 6.08, -1.98, 7.61, -3.8, 9.78, -6.38, 12.85, -10.04, 17.2]
With 0.03, the first step overshoots from 5 to -0.69, the other side of the valley. There the slope is even steeper, so the next step overshoots further, and it keeps growing. Too small is slow, too big jumps over the valley.
Both knobs together
So far b was frozen. Now turn both knobs. Each knob gets its own gradient and the same update rule. Start at w = 5, b = 0, learning rate 0.02, and run 2000 steps:
w, b, lr = 5, 0, 0.02
for step in range(1, 2001):
y_hat = w * x + b
grad_w = -2 * np.mean(x * (y - y_hat))
grad_b = -2 * np.mean(y - y_hat)
w = w - lr * grad_w
b = b - lr * grad_b
if step in (1, 100, 2000):
print(step, round(w, 2), round(b, 2),
round(mse(w, b), 3))
1 2.77 -0.29 30.561
100 2.97 3.38 3.308
2000 2.4 7.13 0.889
The MSE falls from 30.561 after step 1 to 3.308 at step 100. At step 2000, w is 2.4 and b is 7.13. Check against polyfit:
print(np.round(np.polyfit(x, y, 1), 2))
[2.4 7.13]
The same line, and this time the computer walked there by itself.
A walk can get stuck
The linear regression cost is one smooth bowl. Start anywhere and every walk ends at the same bottom.
Some costs are bumpy, with many dips. A walk can go down into a small dip, feel flat ground, and stop. That's a local minimum: the real lowest point is somewhere else, but the walker never sees it. A common fix is to start from a few random spots and keep the lowest result. Neural networks train with this same walk.
Common mistakes
- Adding the gradient instead of subtracting it. That walks uphill. The rule is
w - learning_rate * gradient. - A learning rate that's too big. If the MSE grows from step to step, lower the rate.
- A learning rate that's too small. The walk is heading the right way, but you run out of steps before you arrive.
- Updating
wbefore computinggrad_b. Compute both gradients from the samey_hat, then update both knobs, as in the loop above.
Quick recap
| Idea | Meaning | Kids example |
|---|---|---|
| Gradient | Slope of the cost; sign = direction | +189.8 at w = 5, -102.2 at w = 1 |
| Update rule | w - learning_rate * gradient | 5 - 0.01 * 189.8 = 3.102 |
| Converged | w stops changing | 2.404, MSE 0.889 after 5 steps |
| Learning rate | Step size | 0.001 slow, 0.01 right, 0.03 blows up |
| Both knobs | One gradient per knob | 2000 steps: w 2.4, b 7.13 |
| Local minimum | A dip that isn't the lowest point | Fix: several random starts |
Next, Linear Regression in scikit-learn does this search for you on a real dataset.
Try it yourself
Start at w = 0 with b frozen at 7.13 and a learning rate of 0.01. Which way does the first step go? How many steps until the MSE is below 1? Then try 0.02.
The notebook and the dataset are in the StudyEasy AI Community, free to join.
Built this? Share your solution in the StudyEasy AI Community.
Join free on Skool →Linear Regression and the Cost Function: Draw a Line, Score It
Next →Linear Regression in scikit-learn: Fit, Predict and Read the Price Tags
StudyEasy AI Community
Learn AI engineering, share what you build, and connect with other learners.
Free resources: lesson files, notebooks and code
Ask questions and join engineering discussions
Meet real people learning and building with AI
Machine Learning Engineer: From First Model to ML Engineer
Learn machine learning in Python, then ship it: data analysis, regression, classification, tuning, deployment and MLOps.View on Udemy ↗: Machine Learning Engineer: From First Model to ML Engineer (opens in a new tab)Related articles
Linear Regression and the Cost Function: Draw a Line, Score It
Draw a straight line through six kids' ages and weights, measure every miss, and turn the misses into one score, the mean squared error. Then let np.polyfit find the line with the lowest score.
Linear Regression in scikit-learn: Fit, Predict and Read the Price Tags
Predict a yearly medical bill with scikit-learn's LinearRegression: first from age alone, then from every column inside a pipeline. Each coefficient reads like a price tag, and smoker_yes is by far the biggest.
Regression Metrics: MAE, RMSE, R-squared and the Baseline to Beat
Score a regression model honestly: MAE, MSE and RMSE from four darts, then the insurance model on 268 test people, a DummyRegressor baseline to beat, R-squared and adjusted R-squared, and a residual plot.
Polynomial Regression, Overfitting and Underfitting: Bend the Line, Watch the Test Score
Give a linear model extra columns with PolynomialFeatures and it can bend. Then watch train and test scores split apart: degrees 1, 2 and 16 on Canada's income per person, and degrees 1 to 5 on the insurance model.