Linear Regression by Gradient Descent
The normal equation solves linear regression in one step, but it needs , a matrix, and a solve that costs about operations. With a million features, or data that does not fit in memory, or a loss without a closed-form minimum (logistic regression, neural networks), you need an iterative method instead. Gradient descent is the one almost everything else is built on, and linear regression is the cleanest place to see it work.
The update
Start from any weights, compute the gradient of the loss, take a small step against it, repeat. For the mean squared error from the previous lesson:
is the learning rate. Each update moves the weights a step against the residuals, weighted by the features that produced them.
How big may be? The loss is a quadratic with Hessian . Gradient descent on a quadratic converges exactly when , and it converges slowly along directions with small eigenvalues. The ratio (the condition number) therefore decides how many steps you need: the proofs are in Gradient Descent, Step Size and Momentum and Smoothness, Strong Convexity and Conditioning.
See it on a loss surface
The lab shows gradient descent on a two-parameter quadratic loss shaped like a narrow valley, the shape a least-squares loss takes when two features are correlated. Start with : the path drops quickly to the valley floor (the steep direction) and then creeps along it (the flat direction). Raise towards 0.2: the steps start to overshoot across the valley and zig-zag, and past 0.2 (which is for this valley) the path diverges. Switch the optimiser to momentum to see how remembering the previous step damps the zig-zag.
From scratch
The same data as before, , now fitted by gradient descent from :
import numpy as np
rng = np.random.default_rng(0)
n = 200
X = rng.normal(size=(n, 2))
y = 3.0 + 2.0 * X[:, 0] - 1.0 * X[:, 1] + rng.normal(scale=0.5, size=n)
Xb = np.column_stack([np.ones(n), X])
w_exact = np.linalg.lstsq(Xb, y, rcond=None)[0]
def gradient_descent(Xb, y, lr, steps):
w = np.zeros(Xb.shape[1])
for t in range(steps + 1):
resid = Xb @ w - y
if t in (0, 10, 50, 200):
print(f" step {t:3d} MSE {np.mean(resid ** 2):9.4f} w {w.round(3)}")
grad = 2 / len(y) * Xb.T @ resid # gradient of the mean squared error
w = w - lr * grad
return w
print("learning rate 0.05:")
w = gradient_descent(Xb, y, lr=0.05, steps=200)
print("exact solution ", w_exact.round(3))
print("learning rate 1.2:")
gradient_descent(Xb, y, lr=1.2, steps=10)
lam = np.linalg.eigvalsh(2 / n * Xb.T @ Xb)
print("largest eigenvalue of the Hessian:", lam.max().round(3), " stable if lr <", (2 / lam.max()).round(3))learning rate 0.05:
step 0 MSE 12.4251 w [0. 0. 0.]
step 10 MSE 2.1581 w [ 1.86 1.122 -0.546]
step 50 MSE 0.2471 w [ 2.973 1.949 -0.929]
step 200 MSE 0.2458 w [ 2.999 1.975 -0.94 ]
exact solution [ 2.999 1.975 -0.94 ]
learning rate 1.2:
step 0 MSE 12.4251 w [0. 0. 0.]
step 10 MSE 14634.2091 w [-90.947 70.297 3.404]
largest eigenvalue of the Hessian: 2.174 stable if lr < 0.92
With the MSE falls from 12.4 to 0.2471 in 50 steps and after 200 steps the weights equal the exact solution to three decimals. With , above the limit , the error grows to 14 634 in ten steps: each step overshoots further than the last.
Mini-batch SGD and the library version
On large data, computing the full gradient every step is wasteful. Stochastic gradient descent estimates it from a small random batch of rows, so each step is cheap and one pass over the data (an epoch) makes many steps (Stochastic Gradient Descent). Features must be on similar scales, otherwise one learning rate is too big for some directions and too small for others; the scaler is fitted on the training part only.
import numpy as np
from sklearn.datasets import load_diabetes
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
from sklearn.linear_model import SGDRegressor, LinearRegression
from sklearn.pipeline import make_pipeline
from sklearn.metrics import r2_score
X, y = load_diabetes(return_X_y=True)
X_tr, X_te, y_tr, y_te = train_test_split(X, y, test_size=0.25, random_state=0)
def minibatch_sgd(X, y, lr=0.01, epochs=50, batch=32, seed=0):
rng = np.random.default_rng(seed)
w, b = np.zeros(X.shape[1]), 0.0
for epoch in range(epochs):
order = rng.permutation(len(y))
for start in range(0, len(y), batch):
idx = order[start:start + batch]
resid = X[idx] @ w + b - y[idx]
w -= lr * 2 * X[idx].T @ resid / len(idx)
b -= lr * 2 * resid.mean()
return w, b
scaler = StandardScaler().fit(X_tr) # fitted on the training part only
Xs_tr, Xs_te = scaler.transform(X_tr), scaler.transform(X_te)
w, b = minibatch_sgd(Xs_tr, y_tr)
print("from-scratch mini-batch SGD test R^2:", round(r2_score(y_te, Xs_te @ w + b), 3))
sgd = make_pipeline(StandardScaler(), SGDRegressor(max_iter=1000, tol=1e-4, random_state=0)).fit(X_tr, y_tr)
print("SGDRegressor test R^2:", round(sgd.score(X_te, y_te), 3), " epochs:", sgd[-1].n_iter_)
print("LinearRegression (exact) test R^2:", round(LinearRegression().fit(X_tr, y_tr).score(X_te, y_te), 3))from-scratch mini-batch SGD test R^2: 0.353
SGDRegressor test R^2: 0.351 epochs: 33
LinearRegression (exact) test R^2: 0.359
Both stochastic versions land near the exact solution's test of 0.359 without ever forming . They are not identical: SGD stops near the minimum, and SGDRegressor also adds a tiny L2 penalty by default (alpha=0.0001) and uses a decaying learning rate. For a problem this small the exact solver is the right tool; SGD pays off with millions of rows or when data arrives as a stream (partial_fit).
Hyperparameters
| Hyperparameter | Effect |
|---|---|
| learning rate | too small: slow; too large: oscillates or diverges |
| batch size | larger: smoother but costlier steps; smaller: noisier, more steps per epoch |
| epochs / tolerance | when to stop |
| learning-rate schedule | decaying lets SGD settle instead of bouncing around the minimum |
Strengths, weaknesses, when to use it
Gradient descent scales to any number of rows (one batch in memory at a time), works for any differentiable loss and is the engine of every neural network. It needs tuning (learning rate, schedule, stopping), scaled features, and gives an approximate answer. For linear least squares on data that fits in memory, use the exact solver; use SGD for very large or streaming data, and remember the method for logistic regression and beyond.
Pitfalls
- Unscaled features. One feature in thousands and one in fractions make the valley extremely narrow: either diverge or crawl.
- Judging convergence by the weights moving slowly. On an ill-conditioned problem the weights can drift for thousands of steps; watch the loss on a validation set.
- Shuffling once. Reshuffle every epoch, as
minibatch_sgddoes; sorted data (by date, by class) gives biased batches.
Practice
- Using the output, how many times larger than the stable limit was , and why does the error grow geometrically?
Answer
times. Along the top eigenvector the error is multiplied by every step, so after ten steps it has grown by about in that direction, and the squared error by its square.
- You double every feature value. What happens to the stable learning rate?
Answer
is multiplied by 4 (apart from the intercept column), so grows about four times and the largest stable learning rate shrinks about four times. This is why scaling matters for gradient methods.
Test yourself
Gradient descent on a quadratic loss with Hessian eigenvalues between 0.1 and 4 converges for which learning rates?
- any
What does one epoch of mini-batch SGD mean?
- One gradient step
- One pass over all training rows, in many small batches
- One run until convergence
- One evaluation on the test set
Why is the scaler fitted on X_tr and only applied to X_te?
- Fitting it on the test set is slower
- So the test set stays unseen; its mean and spread must not influence training
- Because
X_tehas fewer rows - StandardScaler cannot be fitted twice