Implement Mini-Batch Gradient Descent for Linear Regression
Machine LearningModel answerLast updated
Build mini-batch gradient descent from scratch using NumPy to train a linear regression model with MSE loss.
You need to implement mini-batch gradient descent from scratch to train a linear regression model. Use only NumPy for your implementation.
Your function should accept:
- Training data
X(features) andy(targets) - A learning rate (step size for parameter updates)
- Batch size (number of samples per gradient computation)
- Number of epochs (complete passes through the dataset)
- A random seed for reproducibility
The model should predict using the equation ŷ = Xw + b, where w are the weights and b is the bias term. Optimize using mean squared error loss.
Return the learned weight vector, bias term, and a list containing the full-dataset loss after each epoch.
Your implementation should handle:
- Proper data shuffling each epoch
- Correct gradient computation for weight and bias
- Appropriate handling of the final batch when it's smaller than the specified batch size
- Input validation for edge cases
Hints
Hint 1
Shuffle the data indices once per epoch, then partition into consecutive batches to ensure every sample is seen exactly once per pass
Hint 2
The gradient for MSE with respect to weights is (2/m) * X^T * residual, where m is the actual batch size and residual is predictions minus targets
Hint 3
When the final batch has fewer samples than the batch size, make sure to divide gradients by the actual number of samples in that batch, not the nominal batch size
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Mini-batch gradient descent is a parameter optimization algorithm that balances computational efficiency with gradient estimation quality. It updates model parameters by computing gradients on small subsets (batches) of the training data.
Core Algorithm Structure
The fundamental parameter update rule follows:
θ = θ - learning_rate * ∇L(θ)
where ∇L(θ) is the gradient of the loss with respect to parameters.
Comparison of gradient descent variants:
- Full-batch: Uses all samples for each gradient; exact but computationally expensive per step
- Stochastic (SGD): Uses one sample; fast but extremely noisy
- Mini-batch: Uses a moderate number of samples (typically 32-512); balances noise reduction with computational efficiency and enables GPU vectorization
Implementation Steps
Each training epoch executes four key operations:
- Shuffle: Randomize sample order to prevent correlated batches that could bias learning
- Partition: Divide data into consecutive chunks of the specified batch size
- Compute gradients: For each batch, calculate the gradient of the average loss
- Update parameters: Adjust weights and bias in the direction that reduces loss
Mathematical Derivation
For mean squared error loss with predictions ŷ = Xw + b and a batch of size m:
L = (1/m) * Σ(ŷᵢ - yᵢ)²
Define the residual: r = Xw + b - y
Taking derivatives:
∂L/∂w = (2/m) * X^T * r
∂L/∂b = (2/m) * sum(r)
The factor of 2 comes from the chain rule; many implementations absorb it into the learning rate.
Complexity Analysis
For n samples, d features, E epochs, and batch size B:
Time: O(E * n * d)
- Each batch requires
O(B * d)for matrix operations - One epoch processes all
nsamples:O(n * d) - Number of batches per epoch
⌈n/B⌉affects update frequency but not total arithmetic
Space: O(n + B*d + d)
O(n)for shuffled indicesO(B * d)for batch dataO(d)for parameters and gradients
Critical Implementation Details
Shape handling: Ensure y is 1-D. If y has shape (n, 1) and predictions are (n,), broadcasting creates an (n, n) matrix—a silent bug that's easy to miss.
Last batch: When n is not divisible by B, the final batch is smaller. Always divide gradients by the actual batch size, not the nominal batch size.
Shuffling: Create a permuted index array and apply it to both X and y. Never shuffle them independently—that destroys the correspondence between features and targets.
Divergence detection: Unstable learning rates or poorly scaled features can cause loss to become infinite or NaN. Check for finite values after computing epoch loss.
Reproducibility: Use a seeded random number generator rather than global random state.
Edge Cases
- Batch size ≥ n: Degenerates to full-batch gradient descent
- Batch size = 1: Becomes pure SGD
- Empty data or mismatched shapes: Reject with clear errors
- Non-positive hyperparameters: Invalid configurations should raise errors
- 1-D feature array: Reshape to
(n, 1)to ensure consistent matrix operations
Code Implementation
import numpy as np
def minibatch_gradient_descent(X, y, lr=0.01, batch_size=32, epochs=100, seed=0):
"""
Train linear regression using mini-batch gradient descent with MSE loss.
Parameters
----------
X : array-like, shape (n, d) or (n,)
Feature matrix
y : array-like, shape (n,) or (n, 1)
Target values
lr : float
Learning rate, must be positive
batch_size : int
Number of samples per gradient update, must be positive
epochs : int
Number of complete passes through the dataset, must be positive
seed : int
Random seed for shuffling
Returns
-------
w : np.ndarray, shape (d,)
Learned weight vector
b : float
Learned bias term
losses : list[float]
MSE loss on full dataset after each epoch
"""
# Convert and validate inputs
X = np.asarray(X, dtype=float)
y = np.asarray(y, dtype=float).ravel() # Ensure 1-D
if X.ndim == 1:
X = X.reshape(-1, 1)
n, d = X.shape
if n == 0:
raise ValueError("X must contain at least one sample")
if y.shape[0] != n:
raise ValueError("X and y must have matching sample counts")
if lr <= 0 or batch_size <= 0 or epochs <= 0:
raise ValueError("lr, batch_size, and epochs must be positive")
# Initialize parameters and RNG
rng = np.random.default_rng(seed)
w = np.zeros(d)
b = 0.0
losses = []
# Training loop
for _ in range(epochs):
# Shuffle data indices for this epoch
indices = rng.permutation(n)
# Process each mini-batch
for start_idx in range(0, n, batch_size):
batch_indices = indices[start_idx:start_idx + batch_size]
X_batch = X[batch_indices]
y_batch = y[batch_indices]
m = len(batch_indices) # Actual batch size (may be smaller for last batch)
# Forward pass: compute predictions and residual
predictions = X_batch @ w + b
residual = predictions - y_batch
# Compute gradients
grad_w = (2.0 / m) * (X_batch.T @ residual)
grad_b = (2.0 / m) * residual.sum()
# Update parameters
w -= lr * grad_w
b -= lr * grad_b
# Compute and record full-dataset loss
full_predictions = X @ w + b
epoch_loss = float(np.mean((full_predictions - y) ** 2))
if not np.isfinite(epoch_loss):
raise FloatingPointError(
"Training diverged (loss is inf/nan). "
"Try reducing learning rate or scaling features."
)
losses.append(epoch_loss)
return w, b, losses
# Verification with synthetic data
if __name__ == "__main__":
rng = np.random.default_rng(42)
# Generate synthetic data with known parameters
n_samples, n_features = 1000, 3
X = rng.normal(size=(n_samples, n_features))
true_w = np.array([2.0, -1.0, 0.5])
true_b = 3.0
noise = 0.1 * rng.normal(size=n_samples)
y = X @ true_w + true_b + noise
# Train model
w, b, losses = minibatch_gradient_descent(
X, y, lr=0.05, batch_size=64, epochs=50
)
print(f"Learned weights: {w}") # Should be close to [2, -1, 0.5]
print(f"Learned bias: {b}") # Should be close to 3
print(f"Final loss: {losses[-1]}") # Should be close to 0.01 (noise variance)
Common Mistakes to Avoid
- Independent shuffling: Shuffling
Xandyseparately destroys the training pairs - Wrong batch size in gradient: Using nominal batch size instead of actual size for partial batches
- Shape mismatches: Not flattening
yleads to broadcasting errors - Global random state: Using
np.random.shuffle()instead of a seeded generator - Ignoring divergence: Not checking for infinite or NaN losses
Convergence Considerations
MSE for linear regression is convex, guaranteeing convergence to the global optimum with an appropriate learning rate. However, mini-batch noise prevents exact convergence—iterates oscillate near the optimum. In practice, learning rate decay or early stopping based on validation loss is common.
Time Complexity: O(E × n × d)
Space Complexity: O(n + B×d + d)