KatInterview

Implement Mini-Batch Gradient Descent for Linear Regression

Machine LearningModel answer
MediumModel answerMachine Learningoptimizationgradient-descentnumpy

Last 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) and y (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