TExcelTAD
Home › Classical ML Algorithms: Supervised & Unsupervised › Linear Regression by Gradient Descent

Linear Regression by Gradient Descent

The normal equation solves linear regression in one step, but it needs X⊤XX^\top X, a d×dd \times d matrix, and a solve that costs about d3d^3 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:

L(w)=1n∥Xw−y∥2∇L(w)=2nX⊤(Xw−y)wt+1=wt−η ∇L(wt)\begin{aligned} L(\mathbf{w}) &= \frac{1}{n} \lVert X\mathbf{w} - \mathbf{y} \rVert^2 \\ \nabla L(\mathbf{w}) &= \frac{2}{n} X^\top (X\mathbf{w} - \mathbf{y}) \\ \mathbf{w}_{t+1} &= \mathbf{w}_t - \eta \, \nabla L(\mathbf{w}_t) \end{aligned}

η\eta is the learning rate. Each update moves the weights a step against the residuals, weighted by the features that produced them.

How big may η\eta be? The loss is a quadratic with Hessian H=2nX⊤XH = \frac{2}{n} X^\top X. Gradient descent on a quadratic converges exactly when η<2/λmax⁡(H)\eta < 2/\lambda_{\max}(H), and it converges slowly along directions with small eigenvalues. The ratio λmax⁡/λmin⁡\lambda_{\max}/\lambda_{\min} (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 η=0.08\eta = 0.08: the path drops quickly to the valley floor (the steep direction) and then creeps along it (the flat direction). Raise η\eta towards 0.2: the steps start to overshoot across the valley and zig-zag, and past 0.2 (which is 2/λmax⁡2/\lambda_{\max} for this valley) the path diverges. Switch the optimiser to momentum to see how remembering the previous step damps the zig-zag.

−2−1012−202Loss contours: narrow valleyxy10−610−410−211001040204060stepLoss f(x, y), log scalepath / lossstartminimumGD stable for η < 0.2

From scratch

The same data as before, y=3+2x1−x2+noisey = 3 + 2x_1 - x_2 + \text{noise}, now fitted by gradient descent from w=0\mathbf{w} = \mathbf{0}:

python · try it yourself
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 η=0.05\eta = 0.05 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 η=1.2\eta = 1.2, above the limit 2/2.174=0.922/2.174 = 0.92, 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.

python · try it yourself
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 R2R^2 of 0.359 without ever forming X⊤XX^\top X. 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 η\eta 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 η\eta 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_sgd does; sorted data (by date, by class) gives biased batches.

Practice

  1. Using the output, how many times larger than the stable limit was η=1.2\eta = 1.2, and why does the error grow geometrically?
Answer

1.2/0.92≈1.31.2 / 0.92 \approx 1.3 times. Along the top eigenvector the error is multiplied by ∣1−ηλmax⁡∣=∣1−1.2⋅2.174∣≈1.61\lvert 1 - \eta\lambda_{\max} \rvert = \lvert 1 - 1.2 \cdot 2.174 \rvert \approx 1.61 every step, so after ten steps it has grown by about 1.6110≈1171.61^{10} \approx 117 in that direction, and the squared error by its square.

  1. You double every feature value. What happens to the stable learning rate?
Answer

X⊤XX^\top X is multiplied by 4 (apart from the intercept column), so λmax⁡\lambda_{\max} 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?

  1. η<0.5\eta < 0.5
  2. η<2\eta < 2
  3. η<20\eta < 20
  4. any η>0\eta > 0

What does one epoch of mini-batch SGD mean?

  1. One gradient step
  2. One pass over all training rows, in many small batches
  3. One run until convergence
  4. One evaluation on the test set

Why is the scaler fitted on X_tr and only applied to X_te?

  1. Fitting it on the test set is slower
  2. So the test set stays unseen; its mean and spread must not influence training
  3. Because X_te has fewer rows
  4. StandardScaler cannot be fitted twice