Week 04 · Train linear regression from scratch
Check gradient descent against the least-squares solution.
← Week 3 · Subject contents · Week 5 →
Check gradient descent against the least-squares solution.
Work through the problem
For n examples and prediction Xw, use L=‖Xw−y‖²/(2n). Differentiating gives ∇L=Xᵀ(Xw−y)/n. An all-ones column represents the intercept. For x=[1,2], y=[2,4], and a single weight without intercept, ∇L at zero is (−2−8)/2=−5. A step of size 0.1 moves w to 0.5.
The full-batch gradient update is w ← w−η∇L. Use a small enough step for the scale of the features and compare to an independent least-squares solver. A match establishes that the two procedures find the same optimum on these data.
Training loss approaches the least-squares solution.
Run the Python lab
import numpy as np
x = np.array([-2.,-1,0,1,2])
X = np.c_[np.ones(len(x)),x]
y = np.array([-2.,0,1,3,5])
w = np.zeros(2)
loss = []
for _ in range(100):
err = X@w-y
loss.append(np.mean(err**2)/2)
w -= .15 * X.T@err / len(X)
reference = np.linalg.lstsq(X,y,rcond=None)[0]
print("Gradient descent:", w.round(5))
print("Least squares:", reference.round(5))
assert np.allclose(w,reference,atol=1e-6)
Output from the lab
Gradient descent: [1.4 1.7]
Least squares: [1.4 1.7]
Practice
- Why does feature scale matter?
Check your reasoning
- It changes the curvature of the loss. Large feature magnitudes can make the same update unstable.