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
On this page
- Goal and setup
- Step 1: Load, split and standardise the data
- Step 2: The exact answer with a least-squares solve
- Step 3: Write batch gradient descent
- Step 4: Three learning rates on standardised features
- Step 5: The same experiment without scaling
- Step 6: Why the loss is a mean, not a sum
- Check your understanding
- Apply it: stretch tasks
- Review prompt
Lessons of Linear Algebra & Calculus for ML
- Data as Arrays: Vectors, Matrices and Shapes Concept · 20 min
- Similarity and Structure: Distances, Eigenvectors and the SVD Concept · 30 min
- From Slopes to Gradients: Derivatives, the Chain Rule and Jacobians Concept · 25 min
- Worked Example: Checking a Gradient Numerically Worked example · 15 min
- Lab: Fit a Linear Model with Hand-Written Gradient Descent Lab · 30 min
- Check: Shapes, Gradients and Step Sizes Knowledge check · 10 questions
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.
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 meanmkdir 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 matplotlib02. 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.
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))python data.pyX: (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.
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)python closed_form.pybias (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.0Your 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.
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, historyimport 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))python fit.pystep 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.26The 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).
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)python curves.py scaledlargest 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.pngThe 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.
python curves.py rawlargest 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.pngThe 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.
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")python sum_vs_mean.pyn = 353 | gradient length ratio, sum / mean: 353.0
a stable rate for the mean becomes 0.00056657223796034 for the sumWith 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
09. Apply it: stretch tasks
- Finish the practice project. Combine the plots of
curves_scaled.pngandcurves_raw.pnginto one figure withplt.subplots(1, 2), and write two sentences explaining the difference from the printed curvatures. - Mini-batch descent. Change
gradient_descentto 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. - 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.
Prove this skill
10 questions · about 8 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.