Skip to content

MLDay 9 of 50Supervised and Unsupervised Learning

Gradient Descent, and Why Scaling Matters

Day 7's bike-share model got its weights from one exact formula.

8 min read

Day 7's bike-share model got its weights from one exact formula. A neural network with a million weights has no such formula, so it has to search for them. Gradient descent is that search, and it trains most models you'll meet in this course.

The idea

Think of the loss, the model's error on its training data, as a landscape. Each spot is one choice of weights, and its height is the loss there. Training means finding the lowest spot.

You can't see the whole landscape. You're a hiker lost in fog who can only feel the ground underfoot. So you feel which way is downhill, take a step that way, and repeat. That's gradient descent.

  • The gradient is the slope underfoot: for each weight, how fast the loss rises when that weight grows a little. You step the opposite way.
  • The learning rate η\eta ("eta") sets the step size. Too small, and you crawl. Too big, and you leap past the valley floor, land higher on the far side, and climb out.

The features shape the landscape. Day 7's features come in different units: humidity runs 0–100 %, wind 0–57 km/h and the hour 0–23. A weight on a feature with big values moves the loss fast. So the landscape is steep along some weights and nearly flat along others: a long, narrow canyon. One learning rate must suit every direction. A step small enough to stay off the steep walls crawls along the flat floor, zig-zagging.

Standardizing fixes the shape. It rescales each feature to a mean of 0 and a spread of 1, so the canyon becomes a nearly round bowl, and one good step size works in every direction.

A tiny example

Take one weight and the loss L=(w−2)2L = (w - 2)^2, lowest at w=2w = 2. Start at w=0w = 0. The slope there is 2(w−2)=−42(w - 2) = -4: negative, so the loss falls as ww grows, and the step goes right.

Three steps with three learning rates:

Step η=0.01\eta = 0.01 η=0.1\eta = 0.1 η=1.1\eta = 1.1
start 0 0 0
1 0.04 0.4 4.4
2 0.079 0.72 −0.88
3 0.118 0.98 5.46

At η=0.1\eta = 0.1, each step closes 20% of the gap to 2. At η=0.01\eta = 0.01, the walk has barely left the start. At η=1.1\eta = 1.1, it overshoots: the distance from 2 grows from 2 to 2.4, 2.88 and 3.46.

The formula

Each step moves every weight against its slope:

w←w−η∂L∂ww \leftarrow w - \eta \frac{\partial L}{\partial w}
Symbol Meaning
ww one weight (the bias bb gets the same update)
←\leftarrow "becomes": the new value replaces the old one
η\eta the learning rate, a small positive number you choose
∂L∂w\frac{\partial L}{\partial w} the slope of the loss LL when only ww changes; together, the slopes form the gradient

Worked: w=0w = 0, slope −4-4 and η=0.1\eta = 0.1 give w=0−0.1×(−4)=0.4w = 0 - 0.1 \times (-4) = 0.4.

Standardizing turns each value of a feature into its distance from the feature's mean, counted in standard deviations:

z=x−μσz = \frac{x - \mu}{\sigma}
Symbol Meaning
xx one value of a feature, such as a humidity of 80 %
μ\mu the feature's mean ("mu")
σ\sigma the feature's standard deviation ("sigma"): the typical distance of its values from the mean
zz the standardized value

Worked: humidity x=80x = 80, with μ=50\mu = 50 and σ=15\sigma = 15, gives z=80−5015=2z = \frac{80 - 50}{15} = 2.

Try it

Walk down the loss curve

Each step moves w against the slope: w ← w − η·dL/dw. Pick a learning rate η and take steps toward the lowest point, w* = 3.

-50510020406080weight wloss Lw*SGD: w = -4, L = 49
Changing η starts again from w = -4.
  • SGD: step 0, w = -4, L = 49, heading for w* = 3
0510152002040steploss L

The walk starts at w=−4w = -4, far from the bottom at 3, with a learning rate that creeps. Press Run 20, then Reset, raise η\eta and run again until it lands in a few steps. Then push η\eta to the top: the steps zig-zag across the bottom, each landing higher than the last, until the walk is flagged as diverging.

In code

This is gradient descent in NumPy for Day 7's model: rentals from temperature, humidity, wind and hour. It fits all 17,379 hours, because the question is how fast the walk reaches the bottom, not how well the model predicts. LinearRegression finds the bottom exactly. The walk descends the MSE from Day 5. Each run stops once its RMSE is within 0.1 of that lowest value, or when the loss blows up. RMSE is the typical miss, in rentals (Day 5).

# script_id: day_009_gradient_descent_and_scaling/descent
import os
from pathlib import Path

import numpy as np
import pandas as pd
from sklearn.linear_model import LinearRegression
from sklearn.metrics import root_mean_squared_error

DATA_DIR = Path(os.environ.get("ML_DATA", "datasets"))
df = pd.read_csv(DATA_DIR / "bike_sharing" / "hour.csv", parse_dates=["dteday"])
X = np.column_stack([df["temp"] * 41, df["hum"] * 100, df["windspeed"] * 67, df["hr"]])  # °C, %, km/h, hour
y = df["cnt"].to_numpy(dtype=float)
best = root_mean_squared_error(y, LinearRegression().fit(X, y).predict(X))  # the bottom of the bowl
print(f"lowest possible RMSE: {best:.2f}")


def descend(X, lr, max_steps=20_000):
    w, b = np.zeros(X.shape[1]), 0.0                  # start with every weight at 0
    for step in range(1, max_steps + 1):
        err = X @ w + b - y                           # prediction minus truth, for every hour
        w = w - lr * 2 * X.T @ err / len(y)           # w <- w - lr * (slope of the MSE for each weight)
        b = b - lr * 2 * err.mean()
        rmse = np.sqrt(np.mean((X @ w + b - y) ** 2))
        if rmse < best + 0.1 or rmse > 1e6:           # close enough, or flying off
            break
    return step, rmse
lowest possible RMSE: 149.02

Now the same walk on the raw features and on standardized ones, at a few learning rates:

# script_id: day_009_gradient_descent_and_scaling/descent
Z = (X - X.mean(axis=0)) / X.std(axis=0)              # standardize: z = (x - mean) / std, per column
for name, data, lr in [("raw", X, 0.0001), ("raw", X, 0.0003),
                       ("scaled", Z, 0.01), ("scaled", Z, 0.1), ("scaled", Z, 0.9)]:
    step, rmse = descend(data, lr)
    print(f"{name:6}  η = {lr:<6}  {step:>6} steps  RMSE {'diverged' if rmse > 1e6 else f'{rmse:.2f}'}")
raw     η = 0.0001   20000 steps  RMSE 149.41
raw     η = 0.0003      13 steps  RMSE diverged
scaled  η = 0.01       178 steps  RMSE 149.12
scaled  η = 0.1         17 steps  RMSE 149.08
scaled  η = 0.9         18 steps  RMSE diverged

On raw features, η=0.0003\eta = 0.0003 blows up in 13 steps, and the smaller η=0.0001\eta = 0.0001 still hasn't reached the bottom after 20,000. Standardized, η=0.1\eta = 0.1 gets there in 17 steps. The learning rate still matters: 0.01 takes 178 steps, and 0.9 diverges.

Quick check

Quick check

1. A weight is w = 1, its slope is +2, and η = 0.1. What is w after one step?

2. The loss grows each step, and w jumps from one side of the minimum to the other. What should you change?

3. Why did the raw bike-share features need a tiny learning rate and still crawl?

Next

Day 10: Spot Overfitting with Cross-Validation asks whether a model that reaches the bottom of its training loss also predicts new data well.

Data: Bike Sharing Dataset (UCI Machine Learning Repository, dataset 275), CC BY 4.0; cite Fanaee-T, H. and Gama, J. (2013), "Event labeling combining ensemble detectors and background knowledge", Progress in Artificial Intelligence, doi:10.1007/s13748-013-0040-3.

Next · Day 10 · 8 minSpot Overfitting with Cross-Validation← Previous: Day 8 · Project 1: a Bike-Share Demand Baseline
Not tapped yet