KatInterview

Implementing Optimization via Gradient Descent for Regression

Machine LearningModel answer
MediumModel answerMachine Learningoptimizationgradient-descentlinear-regression

Last updated

Derive and implement batch gradient descent to minimize squared error for linear models, covering convergence criteria, step size selection, and regularization.

Your task is to implement batch gradient descent for optimizing a linear model using mean squared error.

Write vectorized pseudocode (Python-style notation) that accepts:

  • Design matrix X with shape (m, n) where the first column contains all ones for the bias term
  • Target vector y with shape (m,)
  • Step size parameter α
  • Maximum iteration count
  • Convergence threshold
  • Optional: regularization coefficient λ

Your implementation should return the optimized parameter vector θ with shape (n,) and a history of objective values.

Part 1: Mathematical Foundation

Starting from the objective function J(θ) = (1/(2m)) ||Xθ − y||², derive the gradient expression. Show your work using matrix calculus and explain what each term represents.

Part 2: Implementation

Write complete pseudocode that:

  • Computes the gradient vectorially
  • Updates parameters iteratively
  • Tracks objective values

Part 3: Convergence Analysis

Implement and discuss at least two stopping conditions:

  • Maximum iteration budget
  • Gradient magnitude threshold
  • Relative objective improvement

Explain when each condition is most appropriate and their limitations.

Part 4: Step Size Strategy

Address these questions:

  • How do you select α to ensure the algorithm doesn't diverge?
  • Compare fixed versus decaying step size schedules
  • Explain how feature preprocessing (standardization) impacts convergence speed and the eigenvalue spread of XᵀX

Part 5: Regularization Extension

Modify your objective to incorporate L2 penalties: J(θ) = (1/(2m))||Xθ − y||² + (λ/(2m))||θ_{1:n}||²

Note that the bias parameter should not be penalized. Derive the modified gradient and discuss how to choose λ.

Hints

Hint 1

Start by expressing the squared error as a quadratic form in θ, then apply standard matrix derivative rules

Hint 2

The Hessian matrix (1/m)XᵀX determines stability—your step size must respect its largest eigenvalue

Hint 3

Standardizing features transforms XᵀX into something close to a correlation matrix, dramatically reducing its condition number