Gradient Descent
Gradient descent is the method almost every neural network uses to learn. It starts with some weights, measures the loss (how wrong the predictions are), computes the gradient (which direction makes the loss grow fastest), and takes a small step the opposite way. Repeating this walks the weights downhill until the loss stops falling.
The size of each step is the learning rate, the single most important setting in training. This lesson uses the derivatives from "Derivatives and Gradients".
The Update Rule
| Piece | Description |
|---|---|
| Loss | It is used to measure how wrong the model is; here mean squared error |
| Gradient | The slope of the loss for each weight; it points uphill |
| Learning rate | It is used to set how big each step is |
| Update | weight = weight - learning_rate × gradient, for every weight |
| Step (iteration) | One update of all the weights |
Example: Fitting a Line Step by Step
This program fits price = w × size + b to the 200 houses by gradient descent, starting from a flat line at zero. This program uses houses.csv from "Linear Regression".
import numpy as np
import pandas as pd
houses = pd.read_csv("houses.csv")
x, y = houses["size"].to_numpy(), houses["price"].to_numpy() # thousands of sq ft, thousands of dollars
w, b = 0.0, 0.0 # start with a flat line at zero
learning_rate = 0.1
for step in range(1, 1001):
error = (w * x + b) - y
loss = np.mean(error ** 2) # mean squared error
grad_w = np.mean(2 * error * x) # slope of the loss with respect to w
grad_b = np.mean(2 * error) # slope of the loss with respect to b
w -= learning_rate * grad_w # step downhill
b -= learning_rate * grad_b
if step in (1, 10, 100, 1000):
print(f"step {step:4}: loss {loss:9.1f} w {w:6.1f} b {b:6.1f}")
print("Exact best fit (np.polyfit):", np.polyfit(x, y, 1).round(1))step 1: loss 155850.3 w 186.2 b 76.0
step 10: loss 1325.7 w 141.6 b 59.6
step 100: loss 1317.3 w 138.6 b 66.9
step 1000: loss 1316.8 w 137.7 b 69.1
Exact best fit (np.polyfit): [137.7 69.1]Explanation:
- The gradients are the derivatives of the mean squared error:
mean(2 × error × x)forwandmean(2 × error)forb. A positive gradient means "increasing this weight increases the loss", so the update subtracts it. - Step 1 has a huge loss (155,850) because a line at zero predicts every house costs $0. The first step jumps
wto 186.2, overshooting a little. - By step 10 the loss has fallen to 1,325.7, and the remaining steps fine-tune.
- After 1,000 steps,
w = 137.7andb = 69.1, exactly whatnp.polyfitcomputes directly. Gradient descent found the best line without being told the formula.
For a straight line there's a direct formula, so gradient descent isn't needed. Neural networks have no such formula, and gradient descent is how they're trained.
Example: Choosing the Learning Rate
This program runs 100 steps with four learning rates. This program uses houses.csv from "Linear Regression".
import numpy as np
import pandas as pd
houses = pd.read_csv("houses.csv")
x, y = houses["size"].to_numpy(), houses["price"].to_numpy()
def train(learning_rate, steps=100):
w, b = 0.0, 0.0
for _ in range(steps):
error = (w * x + b) - y
w -= learning_rate * np.mean(2 * error * x)
b -= learning_rate * np.mean(2 * error)
return np.mean(((w * x + b) - y) ** 2)
for learning_rate in [0.001, 0.01, 0.1, 0.2]:
loss = train(learning_rate)
print(f"learning rate {learning_rate:<5}: loss after 100 steps", f"{loss:,.1f}" if loss < 1e6 else f"{loss:.1e} (blew up)")learning rate 0.001: loss after 100 steps 12,399.0
learning rate 0.01 : loss after 100 steps 1,325.4
learning rate 0.1 : loss after 100 steps 1,317.3
learning rate 0.2 : loss after 100 steps 1.1e+47 (blew up)Explanation:
| Learning rate | What happened | Why |
|---|---|---|
| 0.001 | Loss still 12,399 after 100 steps | Steps too small: correct direction, far too slow |
| 0.01 | 1,325.4, close to the best | Good, a little slower |
| 0.1 | 1,317.3, the best possible after 100 steps | Well chosen |
| 0.2 | Blew up to 1.1 × 10⁴⁷ | Steps too big: each one overshoots the valley further than the last |
The gap between 0.1 working and 0.2 exploding is small, which is typical. Too big is worse than too small, so when training fails with a loss that grows or becomes nan, lower the learning rate first.
Kinds of Gradient Descent
| Kind | Gradient computed from | Trade-off |
|---|---|---|
| Batch | All the training data | Accurate steps, but slow on big data; used in this lesson |
| Stochastic (SGD) | One example | Fast, noisy steps |
| Mini-batch | A batch of, say, 32 examples | The usual choice for neural networks |
| Adam and other optimizers | Mini-batches, with adaptive step sizes per weight | Often trains faster with less tuning (see "Training a Network in PyTorch") |
Common Mistakes
Learning rate too high. The loss grows or becomes nan; lower it.
Learning rate too low. The loss falls painfully slowly; raise it.
Stopping too early. Watch the loss curve and stop when it levels off, or when the validation loss starts rising.
Unscaled features. Features on very different scales make one learning rate too big for some weights and too small for others; scale them first.
Interview Corner
How does gradient descent work?
It repeatedly computes the gradient of the loss with respect to each parameter and moves each parameter a small step in the opposite direction, scaled by the learning rate, until the loss stops improving.
What happens if the learning rate is too large or too small?
Too large and training overshoots, oscillates or diverges; too small and it converges very slowly or stalls.
Practice
Exercise: count the steps. Change the first program to stop when the loss improves by less than 0.01 between steps. How many steps does learning rate 0.1 need? And 0.01?
Check your understanding:
- Why does the update subtract the gradient?
- Why was the loss so large at step 1?
- What happened with learning rate 0.2, and why?
Key Takeaways
Quick reference
| Need | Code |
|---|---|
| Loss (mean squared error) | np.mean((predictions - y) ** 2) |
| Gradient for a slope | np.mean(2 * error * x) |
| Update | w -= learning_rate * grad_w |
Was this tutorial helpful?