Implement gradient descent for linear regression from scratch
Written by the mlprep team · Updated
Implement gradient descent for linear regression from scratch in NumPy. No sklearn, no autograd. Compute the gradient manually, implement the update rule, and show it converging. Then extend to mini-batch SGD.
The setup#
Linear regression: predict y = Xw + b, minimize mean squared error.
Loss = (1/n) × ||Xw + b - y||²
The gradient tells us which direction increases the loss — we step in the opposite direction.
Full implementation#
import numpy as np
class LinearRegressionGD:
def __init__(self, learning_rate=0.01, n_iters=1000):
self.lr = learning_rate
self.n_iters = n_iters
self.weights = None
self.bias = None
self.loss_history = []
def fit(self, X, y):
n_samples, n_features = X.shape
self.weights = np.zeros(n_features)
self.bias = 0.0
for i in range(self.n_iters):
# Forward pass
y_pred = X @ self.weights + self.bias
# Compute loss (MSE)
loss = np.mean((y_pred - y) ** 2)
self.loss_history.append(loss)
# Compute gradients
error = y_pred - y # (n_samples,)
dw = (2 / n_samples) * (X.T @ error) # (n_features,)
db = (2 / n_samples) * np.sum(error) # scalar
# Update parameters
self.weights -= self.lr * dw
self.bias -= self.lr * db
return self
def predict(self, X):
return X @ self.weights + self.biasGradient derivation#
Starting from L = (1/n) Σ(xᵢᵀw + b - yᵢ)²:
∂L/∂w = (2/n) Σ (xᵢᵀw + b - yᵢ) · xᵢ = (2/n) · Xᵀ(Xw + b - y)
∂L/∂b = (2/n) Σ (xᵢᵀw + b - yᵢ) = (2/n) · 1ᵀ(Xw + b - y)
In matrix form: dw = (2/n) * X.T @ error where error = y_pred - y.
Verification with closed-form solution#
# Generate synthetic data
np.random.seed(42)
X = np.random.randn(100, 3)
true_w = np.array([2.0, -1.0, 0.5])
y = X @ true_w + 0.1 * np.random.randn(100)
# Gradient descent
model = LinearRegressionGD(learning_rate=0.1, n_iters=500)
model.fit(X, y)
print(f"GD weights: {model.weights}") # Should be close to [2, -1, 0.5]
# Closed-form: w* = (XᵀX)⁻¹Xᵀy
w_exact = np.linalg.solve(X.T @ X, X.T @ y)
print(f"Exact weights: {w_exact}")Extension to mini-batch SGD#
class LinearRegressionSGD:
def __init__(self, learning_rate=0.01, n_iters=1000, batch_size=32):
self.lr = learning_rate
self.n_iters = n_iters
self.batch_size = batch_size
self.weights = None
self.bias = None
def fit(self, X, y):
n_samples, n_features = X.shape
self.weights = np.zeros(n_features)
self.bias = 0.0
for i in range(self.n_iters):
# Sample a mini-batch
indices = np.random.choice(n_samples, self.batch_size, replace=False)
X_batch = X[indices]
y_batch = y[indices]
# Forward + gradient on mini-batch
y_pred = X_batch @ self.weights + self.bias
error = y_pred - y_batch
dw = (2 / self.batch_size) * (X_batch.T @ error)
db = (2 / self.batch_size) * np.sum(error)
# Update
self.weights -= self.lr * dw
self.bias -= self.lr * db
return selfBatch size tradeoff#
| Batch Size | Gradient Estimate | Convergence | Memory | |-----------|------------------|-------------|--------| | Full batch (n) | Exact gradient | Smooth, deterministic | O(n × d) | | Mini-batch (32-256) | Noisy estimate | Faster per-step, noisier | O(batch × d) | | SGD (1) | Very noisy | Can escape local minima, high variance | O(d) |
Mini-batch SGD is the standard in deep learning because:
- Full gradient is expensive for large datasets
- Noise helps escape saddle points and sharp minima
- GPU hardware is designed for batch parallelism (batch_size=1 wastes GPU)
Learning rate diagnostics#
- Loss decreasing smoothly → LR is good
- Loss decreasing very slowly → LR too low, increase 3-10x
- Loss oscillating or increasing → LR too high, decrease 3-10x
- Loss decreases then plateaus → LR was good initially but needs decay
Interview red flags#
- Getting the gradient's sign or scale wrong (for MSE, ∇ = (2/n)·Xᵀ(Xw − y)) and never checking it numerically.
- Looping over examples in Python instead of vectorizing the gradient as matrix operations.
- Taking mini-batches in a fixed order instead of shuffling or sampling randomly, which biases updates when the data is sorted.
- Picking a learning rate without plotting the loss curve or recognizing divergence and oscillation.
You used a constant learning rate. Implement learning rate decay and momentum — and explain why momentum helps SGD converge faster.
Learning rate decay#
Reduce the learning rate over time so early steps make big progress and later steps fine-tune:
def get_lr(self, step):
# Cosine annealing
return self.lr * 0.5 * (1 + np.cos(np.pi * step / self.n_iters))
# Or simple step decay
# return self.lr * (0.1 ** (step // (self.n_iters // 3)))Momentum#
Standard SGD update: w = w - lr * gradient
With momentum: accumulate a velocity that smooths out noisy gradients:
def fit_with_momentum(self, X, y, momentum=0.9):
n_samples, n_features = X.shape
self.weights = np.zeros(n_features)
self.bias = 0.0
velocity_w = np.zeros(n_features)
velocity_b = 0.0
for i in range(self.n_iters):
indices = np.random.choice(n_samples, self.batch_size, replace=False)
X_batch, y_batch = X[indices], y[indices]
y_pred = X_batch @ self.weights + self.bias
error = y_pred - y_batch
dw = (2 / self.batch_size) * (X_batch.T @ error)
db = (2 / self.batch_size) * np.sum(error)
# Momentum: velocity = momentum * velocity + gradient
velocity_w = momentum * velocity_w + dw
velocity_b = momentum * velocity_b + db
# Update using velocity instead of raw gradient
self.weights -= self.lr * velocity_w
self.bias -= self.lr * velocity_bWhy momentum helps#
Imagine optimizing in a narrow ravine — the loss surface is steep in one direction (across the ravine) and shallow in another (along the ravine).
Without momentum: the gradient oscillates back and forth across the ravine. Each step overshoots laterally, and progress along the ravine is slow because the gradient component in that direction is small.
With momentum: the lateral oscillations cancel out (they flip sign each step, so the accumulated velocity in that direction stays small). The along-ravine components consistently point the same direction, so velocity builds up. Net result: fast smooth progress along the ravine with damped oscillations across it.
Mathematically: momentum is a low-pass filter on the gradient sequence. It amplifies consistent gradient directions (signal) and dampens oscillating directions (noise). This is exactly why SGD with momentum converges faster than plain SGD in practice — the noise from mini-batches is dampened while the true gradient direction is amplified.
Go deeper: Gradient descent variants covers SGD, momentum, Adam, and how to discuss their trade-offs.
The key takeaway unlocks after you reveal an expert answer.
Key Takeaway
Gradient descent for linear regression: gradient is (2/n)Xᵀ(Xw - y). Mini-batch SGD samples random subsets for noisy but faster updates. Batch size trades off gradient noise (helps escape bad minima) vs. stability (smooth convergence). Momentum accumulates velocity across steps, acting as a low-pass filter that amplifies consistent gradient signal and dampens oscillating noise. Learning rate decay lets you take large steps early and fine-tune later.
Follow-up Questions to Test Yourself
Interviewers often pivot here once you cover the core concept.
- Implement Adam optimizer from scratch — what does it do differently from SGD with momentum, and why is it the default for deep learning?
- Your gradient descent converges to a loss of 0.5 but the closed-form solution achieves 0.3. What went wrong?
- Explain why feature scaling (normalization) is critical for gradient descent but irrelevant for the closed-form solution.
How confident do you feel explaining this?
Track your understanding or flag it to revisit before your next loop.
Related Questions