Skip to content
Tech Atlas, home
Search
Esc
  • All roadmapsBrowse every learning path
  • ExploreFind a technology area
  • ProjectsGuided projects and builds
  • My AtlasYour learning dashboard
Lesson 5 of 6 · Lab · 30 min · revision 2

Lab: Fit a Linear Model with Hand-Written Gradient Descent

Fit linear regression on the diabetes dataset in pure NumPy, first with a least-squares solve and then with your own batch gradient descent, match scikit-learn to four decimals, and measure how the learning rate and feature scaling decide whether training converges.

Contentsand lesson path

What you will learn

  • Represent a dataset and a linear model as matrix-vector operations in NumPy, predicting result shapes before running the code.
  • Implement gradient descent for linear regression and explain how learning rate and feature scale affect convergence.

01. Goal and setup

In this lab you fit a linear regression model twice on a real medical dataset. First you compute the exact answer with a least-squares solver. Then you write batch gradient descent yourself: start from zero weights and repeatedly step against the gradient of the mean squared error, using the whole training set at every step. When both answers agree with scikit-learn to four decimals, you run controlled experiments: three learning rates on standardised features, three on raw features, and a loss defined as a sum instead of a mean. Each one shows a way training fails that you can predict from the data.

The dataset is the diabetes data that ships with scikit-learn, so no download is needed: 442 patients, 10 measurements each (age, sex, body-mass index, blood pressure and six blood tests), and a target that measures disease progression one year later.

You need: Python 3.12, NumPy 2.5, scikit-learn 1.9 and Matplotlib 3.11. The lab uses the gradient you derived in From Slopes to Gradients.

Project layout at the end of the lab
gd-lab/
├── data.py            step 1: load, split and standardise
├── closed_form.py     step 2: the exact least-squares answer
├── gd.py              step 3: your gradient descent
├── fit.py             step 3: run it and compare
├── curves.py          steps 4 and 5: learning-rate experiments and plots
└── sum_vs_mean.py     step 6: why the loss is a mean
Terminal
mkdir gd-lab && cd gd-lab
python3.12 -m venv .venv
source .venv/bin/activate      # Windows: .venv\Scripts\activate
python -m pip install numpy scikit-learn matplotlib

02. Step 1: Load, split and standardise the data

Load the raw measurements with scaled=False (by default scikit-learn returns a pre-scaled copy, which would hide the scaling problem you study later). Hold back 20% of the rows as a test set. Then standardise each column with the mean and standard deviation of the training rows only, and apply the same numbers to the test rows. Using test statistics would let information from the test set leak into training. Before you run the script, predict the shapes it prints.

Python · data.py
import numpy as np
from sklearn.datasets import load_diabetes
from sklearn.model_selection import train_test_split

# scaled=False gives the raw measurements: age in years, BMI, blood pressure...
X, y = load_diabetes(return_X_y=True, scaled=False)
X_train, X_test, y_train, y_test = train_test_split(
    X, y, test_size=0.2, random_state=0
)

# Standardise with statistics from the training rows only
mean, std = X_train.mean(axis=0), X_train.std(axis=0)
Z_train, Z_test = (X_train - mean) / std, (X_test - mean) / std

if __name__ == "__main__":
    print("X:", X.shape, "y:", y.shape)
    print("train:", X_train.shape, "test:", X_test.shape)
    print("column min:", X.min(axis=0).round(1))
    print("column max:", X.max(axis=0).round(1))
Terminal
python data.py
Expected output
X: (442, 10) y: (442,)
train: (353, 10) test: (89, 10)
column min: [19.   1.  18.  62.  97.  41.6 22.   2.   3.3 58. ]
column max: [ 79.    2.   42.2 133.  301.  242.4  99.    9.1   6.1 124. ]

The columns live on very different scales: sex is coded 1 or 2, while one blood test (column 4) runs from 97 to 301. Keep that in mind for step 5.

03. Step 2: The exact answer with a least-squares solve

Linear regression has a closed-form answer: the weights that minimise the squared error solve the normal equations XᵀX θ = Xᵀy. To include the bias, add a column of ones to X, so θ holds the 10 weights followed by the bias. A textbook writes the solution as θ = (XᵀX)⁻¹Xᵀy, but computing the inverse is slower and less accurate than solving the system directly. np.linalg.lstsq solves the least-squares problem with a numerically stable method (based on the SVD from lesson 2). It also copes when the matrix does not have full rank, for example when one column is an exact copy of another and the inverse does not exist.

The script also prints the condition number of the design matrix, the ratio of its largest to its smallest singular value. A large condition number means some directions in the data are far more stretched than others; you will see in steps 4 and 5 why that matters.

Python · closed_form.py
import numpy as np
from sklearn.linear_model import LinearRegression

from data import X_train, Z_train, y_train


def add_ones(X):
    return np.column_stack([X, np.ones(len(X))])   # last column multiplies the bias


A = add_ones(Z_train)                              # (353, 11)
theta, *_ = np.linalg.lstsq(A, y_train, rcond=None)  # least squares, no inverse
w_closed, b_closed = theta[:-1], theta[-1]

sk = LinearRegression().fit(Z_train, y_train)
print("bias (ours, sklearn):", round(b_closed, 4), round(sk.intercept_, 4))
same = np.allclose(w_closed, sk.coef_, atol=5e-5)  # equal to 4 decimals
print("weights match sklearn to 4 decimals:", same)
print("weights:", w_closed.round(2))
print("train MSE at the optimum:", round(np.mean((A @ theta - y_train) ** 2), 2))
print("condition number raw:", f"{np.linalg.cond(add_ones(X_train)):.1e}")
print("condition number standardised:", round(np.linalg.cond(A), 1))
np.save("theta_closed.npy", theta)
Terminal
python closed_form.py
Expected output
bias (ours, sklearn): 151.6062 151.6062
weights match sklearn to 4 decimals: True
weights: [ -1.72 -11.59  27.51  14.37 -31.22  15.27   1.17   8.18  35.84   2.12]
train MSE at the optimum: 2734.75
condition number raw: 7.2e+03
condition number standardised: 21.0

Your solve and scikit-learn agree, which is expected: LinearRegression solves the same least-squares problem. The script saves θ to theta_closed.npy as the target for gradient descent. Standardising cut the condition number from about 7,200 to 21.

04. Step 3: Write batch gradient descent

The loss is L(w, b) = mean((Xw + b − y)²). With the residual vector r = Xw + b − y, the chain rule gives ∂L/∂w = 2Xᵀr / n and ∂L/∂b = 2·mean(r). Check the shapes: Xᵀ is (d, n) and r is (n,), so the gradient for w has one entry per feature. Each step moves the parameters by the learning rate times the negative gradient. The function records the training loss after every step, and stops early if the loss explodes past 10¹², so a bad learning rate ends quickly instead of filling the screen with overflow warnings.

Python · gd.py
import numpy as np


def mse(X, y, w, b):
    return np.mean((X @ w + b - y) ** 2)


def gradient_descent(X, y, lr, steps):
    n, d = X.shape
    w, b = np.zeros(d), 0.0
    history = []
    for _ in range(steps):
        residual = X @ w + b - y                 # (n,)
        grad_w = 2 * X.T @ residual / n          # (d,): mean-squared-error gradient
        grad_b = 2 * residual.mean()
        w, b = w - lr * grad_w, b - lr * grad_b
        history.append(mse(X, y, w, b))
        if history[-1] > 1e12:                   # stop once the loss has blown up
            break
    return w, b, history
Python · fit.py
import numpy as np

from data import Z_test, Z_train, y_test, y_train
from gd import gradient_descent, mse

theta = np.load("theta_closed.npy")
w, b, history = gradient_descent(Z_train, y_train, lr=0.2, steps=5000)
for step in [1, 10, 100, 1000, 5000]:
    print(f"step {step:4d}: train MSE {history[step - 1]:9.2f}")
same = np.allclose(w, theta[:-1], atol=5e-5)
print("weights match the closed form to 4 decimals:", same)
print("bias:", round(b, 4), "closed form:", round(theta[-1], 4))
print("test MSE:", round(mse(Z_test, y_test, w, b), 2))
Terminal
python fit.py
Expected output
step    1: train MSE  12367.49
step   10: train MSE   2752.50
step  100: train MSE   2742.36
step 1000: train MSE   2734.76
step 5000: train MSE   2734.75
weights match the closed form to 4 decimals: True
bias: 151.6062 closed form: 151.6062
test MSE: 3424.26

The loss drops fast in the first 10 steps and then crawls: from step 100 to step 1,000 it moves by less than 8. After 5,000 steps every weight matches the closed form to four decimals. The early drop comes from directions in which the loss surface is steep; the slow tail comes from a flat direction, where the gradient is tiny. Steps 4 and 5 make that precise.

05. Step 4: Three learning rates on standardised features

For mean squared error the curvature of the loss is the same everywhere: its Hessian (the matrix of second derivatives from lesson 3) is 2AᵀA / n, where A is X with the column of ones. The eigenvalues of that matrix are the curvatures along its eigenvector directions. Gradient descent on this loss is stable only when the learning rate is below 2 divided by the largest curvature: a bigger step overshoots the minimum in the steepest direction by more than it started from, and every step makes it worse. The reason is simple arithmetic: along an eigenvector direction with curvature λ, one step multiplies the remaining distance to the minimum by (1 − lr·λ). If that factor is between −1 and 1 the distance shrinks; with lr above 2/λ it is below −1, and the distance grows and flips sign at every step. The smallest curvature decides how slowly the flattest direction converges, because there the factor is closest to 1. curves.py prints both, runs three learning rates for 5,000 steps and saves the loss curves to a PNG file (Matplotlib uses the Agg backend, so no window opens).

Python · curves.py
import sys

import matplotlib
import numpy as np

matplotlib.use("Agg")                     # write files, no window needed
import matplotlib.pyplot as plt

from data import X_train, Z_train, y_train
from gd import gradient_descent

scaled = sys.argv[1] == "scaled"
X = Z_train if scaled else X_train
rates = [0.02, 0.2, 0.25] if scaled else [1e-6, 1e-5, 2e-5]

A = np.column_stack([X, np.ones(len(X))])
curvature = np.linalg.eigvalsh(2 * A.T @ A / len(A))  # Hessian eigenvalues
print(f"largest curvature {curvature.max():.4g}, smallest {curvature.min():.4g}")
print(f"stable learning rates are below 2 / largest = {2 / curvature.max():.4g}")

for lr in rates:
    _, _, history = gradient_descent(X, y_train, lr=lr, steps=5000)
    if history[-1] > 1e12:
        print(f"lr {lr:g}: diverged, loss above 1e12 at step {len(history)}")
    else:
        print(f"lr {lr:g}: train MSE after 5000 steps {history[-1]:.2f}")
    plt.plot(history, label=f"lr = {lr:g}")

plt.yscale("log")
plt.ylim(2000, 1e6)
plt.xlabel("step")
plt.ylabel("train MSE (log scale)")
plt.legend()
name = "curves_scaled.png" if scaled else "curves_raw.png"
plt.savefig(name, dpi=100)
print("saved", name)
Terminal
python curves.py scaled
Expected output
largest curvature 8.289, smallest 0.01877
stable learning rates are below 2 / largest = 0.2413
lr 0.02: train MSE after 5000 steps 2735.13
lr 0.2: train MSE after 5000 steps 2734.75
lr 0.25: diverged, loss above 1e12 at step 144
saved curves_scaled.png

The prediction from the data holds. 0.2 is just below the bound of 0.2413 and converges. 0.02 is stable but ten times slower: after 5,000 steps it is still 0.38 above the optimum. 0.25 is only 4% above the bound, yet the loss passes 10¹² within 144 steps. Open curves_scaled.png: the stable curves fall and flatten, while the unstable one shoots up. A loss that rises from the first steps is the classic sign of a learning rate that is too large; a rate below the bound can make progress slow, but it does not make this convex loss go up.

06. Step 5: The same experiment without scaling

Now run gradient descent on the raw columns. The learning rates must be far smaller, as the printed bound shows.

Terminal
python curves.py raw
Expected output
largest curvature 1.465e+05, smallest 0.002825
stable learning rates are below 2 / largest = 1.365e-05
lr 1e-06: train MSE after 5000 steps 3652.08
lr 1e-05: train MSE after 5000 steps 3050.03
lr 2e-05: diverged, loss above 1e12 at step 14
saved curves_raw.png

The largest curvature is now about 146,000, because the raw columns hold large values that are far from zero. So the learning rate must stay below 0.0000137, and 0.00002 diverges within 14 steps. The smallest curvature is 0.0028. The ratio between the two (about 50 million, the square of the condition number from step 2) is what hurts: a learning rate small enough for the steepest direction barely moves the flattest one. After 5,000 steps the best stable run is still at 3,050, far above the optimum of 2,734.75 that the scaled run reached. Scaling did not change the best model (the closed form gives the same predictions on raw or scaled features); it changed the shape of the loss surface, from a long narrow valley into a rounder bowl, so gradient descent can take large, safe steps.

07. Step 6: Why the loss is a mean, not a sum

Some code minimises the sum of squared errors instead of the mean. Both have the same minimum, so it looks like a harmless choice. It is not harmless for gradient descent: the gradient of the sum is n times the gradient of the mean, so the same learning rate takes n times bigger steps.

Python · sum_vs_mean.py
import numpy as np

from data import Z_train, y_train

n = len(y_train)
residual = 0 - y_train                    # at w = 0 and b = 0
grad_mean = 2 * Z_train.T @ residual / n  # gradient of the mean of squared errors
grad_sum = 2 * Z_train.T @ residual       # gradient of their sum
ratio = np.linalg.norm(grad_sum) / np.linalg.norm(grad_mean)
print("n =", n, "| gradient length ratio, sum / mean:", round(ratio, 6))
print("a stable rate for the mean becomes", 0.2 / n, "for the sum")
Terminal
python sum_vs_mean.py
Expected output
n = 353 | gradient length ratio, sum / mean: 353.0
a stable rate for the mean becomes 0.00056657223796034 for the sum

With 353 training rows, a learning rate of 0.2 on the summed loss behaves like 70.6 on the mean, far beyond the bound of 0.24. Using the mean keeps a good learning rate roughly independent of the dataset size, which is also why mini-batch training averages over the batch.

08. Check your understanding

Practice check · 3 questions

Reading your lab results

Answer from what you measured in this lab.

Q1. On a new standardised dataset, the largest eigenvalue of the Hessian 2AᵀA / n is 5.0. Which learning rate is the largest one in this list that gradient descent can use without diverging?
Q2. You append an exact copy of the BMI column to X, so XᵀX has no inverse. What happens to the two approaches of this lab?
Q3. On standardised features, the smallest Hessian eigenvalue is 0.01877 and you use lr = 0.2. By roughly what factor does the error along that flattest direction shrink at each step?
Practice only: not graded, not saved, not evidence.

09. Apply it: stretch tasks

  1. Finish the practice project. Combine the plots of curves_scaled.png and curves_raw.png into one figure with plt.subplots(1, 2), and write two sentences explaining the difference from the printed curvatures.
  2. Mini-batch descent. Change gradient_descent to use a random batch of 32 rows per step (np.random.default_rng(0).choice). Compare how close it gets to the closed form after 5,000 steps, and explain why its loss curve is noisy.
  3. Undo the scaling. Convert the weights learned on standardised features back to weights for the raw features (divide each weight by its column standard deviation and adjust the bias), and check that they give the same predictions as a closed-form fit on the raw columns.

10. Review prompt

Without looking back, explain: why np.linalg.lstsq is preferred to computing (XᵀX)⁻¹; how to compute the largest stable learning rate for linear regression from the data; why unscaled features make gradient descent slow even with the best stable learning rate; and what happens to a working learning rate if you switch the loss from a mean to a sum.

References

Your progress

Reading state

Sign in to save that you finished reading this lesson.

Sign in to mark reading complete

Prove this skill

10 questions · about 8 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.
Take the skill check