Linear Regression with Gradient Descent
Key idea: MSE loss (1/N)‖Xw + b − y‖²; gradient dw = (2/N)·Xᵀ(ŷ − y). Compare with the closed form (XᵀX)⁻¹Xᵀy.
import numpy as np
def fit_linear(X, y, lr=0.1, epochs=2000):
N, D = X.shape
w, b = np.zeros(D), 0.0
for _ in range(epochs):
err = X @ w + b - y # (N,)
w -= lr * 2 / N * (X.T @ err)
b -= lr * 2 / N * err.sum()
return w, b
rng = np.random.default_rng(0)
X = rng.normal(size=(500, 3))
true_w = np.array([2.0, -1.0, 0.5])
y = X @ true_w + 3 + 0.01 * rng.normal(size=500)
w, b = fit_linear(X, y)
assert np.allclose(w, true_w, atol=0.01) and abs(b - 3) < 0.01
print("ok", w.round(3), round(b, 3))