Implementing Optimization via Gradient Descent for Regression
Machine LearningModel answerLast 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
Xwith shape(m, n)where the first column contains all ones for the bias term - Target vector
ywith 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
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Model Answer: Gradient Descent for Linear Model Optimization
Part 1: Gradient Derivation
Define the residual as e = Xθ − y, where e ∈ R^m. The objective becomes:
J(θ) = (1/(2m)) eᵀe = (1/(2m)) (Xθ − y)ᵀ(Xθ − y)
Expanding the quadratic:
J(θ) = (1/(2m)) (θᵀXᵀXθ − 2yᵀXθ + yᵀy)
Apply matrix calculus rules:
- For
θᵀAθwhere A is symmetric: gradient is2Aθ - For
bᵀθ: gradient isb
This yields:
∇J(θ) = (1/(2m)) (2XᵀXθ − 2Xᵀy) = (1/m) Xᵀ(Xθ − y)
Interpretation: Each gradient component ∂J/∂θ_j equals the average residual weighted by feature j. The factor 1/2 in the objective cancels out during differentiation, simplifying the gradient formula.
The Hessian ∇²J(θ) = (1/m) XᵀX is positive semidefinite, confirming J is convex with a unique global minimum (assuming full column rank).
Part 2: Vectorized Pseudocode
def optimize_linear_model(X, y, alpha, max_iterations, tolerance,
regularization_lambda=0.0, step_decay=0.0):
"""
X: (m, n) with first column = [1, 1, ..., 1] for bias
y: (m,) target values
alpha: initial step size
max_iterations: iteration limit
tolerance: threshold for convergence checks
regularization_lambda: L2 penalty strength (0 = no penalty)
step_decay: coefficient for time-based step reduction
Returns: theta (n,), objective_history (list)
"""
m, n = X.shape
theta = initialize_zeros(n)
objective_history = []
previous_objective = infinity
for iteration in range(max_iterations):
# Compute predictions and residuals
predictions = X @ theta # (m,)
residuals = predictions - y # (m,)
# Mask bias from regularization
theta_penalized = copy(theta)
theta_penalized[0] = 0
# Objective value
squared_error = (residuals @ residuals) / (2 * m)
penalty = (regularization_lambda / (2 * m)) * (theta_penalized @ theta_penalized)
current_objective = squared_error + penalty
objective_history.append(current_objective)
# Divergence check
if not is_finite(current_objective) or current_objective > previous_objective:
raise ValueError("Optimization diverging - reduce step size")
# Compute gradient
data_gradient = (X.T @ residuals) / m # (n,)
regularization_gradient = (regularization_lambda / m) * theta_penalized
full_gradient = data_gradient + regularization_gradient
# Stopping criteria
if l2_norm(full_gradient) < tolerance:
break # Optimality reached
if previous_objective < infinity:
relative_change = (previous_objective - current_objective) / max(previous_objective, 1e-10)
if relative_change < tolerance:
break # Progress stalled
# Update with potentially decayed step size
effective_alpha = alpha / (1 + step_decay * iteration)
theta = theta - effective_alpha * full_gradient
previous_objective = current_objective
return theta, objective_history
Computational complexity: Each iteration requires O(mn) operations for matrix-vector products. Memory usage is O(n) beyond the input data. The algorithm never materializes XᵀX, which is critical when n is large.
Part 3: Convergence Criteria
| Criterion | Best Use Case | Limitation |
|---|---|---|
| Iteration limit | Always include as a safety mechanism to bound computation time | Provides no quality guarantee |
Gradient norm ‖∇J‖ < ε | When you need a strict optimality certificate; since J is convex, small gradient means near-optimal | Scale-dependent; requires choosing ε based on problem units, or use relative form ‖∇J‖ / ‖∇J(θ₀)‖ |
| Relative objective change | For practical applications where objective value matters more than parameter precision | Can trigger prematurely on flat regions; poorly conditioned problems have tiny per-step progress even far from optimum |
Recommendation: Combine the iteration limit with one quality-based criterion. Log which condition triggered to detect silent non-convergence.
Part 4: Step Size Strategy
Stability analysis: For quadratic objectives, the iterative error satisfies e_{k+1} = (I − αH)e_k where H = XᵀX/m. Convergence requires:
0 < α < 2/λ_max(H)
where λ_max is the largest eigenvalue of H.
Practical selection approaches:
- Power iteration: Estimate
λ_maxusing a few iterations of the power method onXᵀX/m(cost: several matrix-vector products) - Grid search: Try α values in geometric progression (0.001, 0.003, 0.01, 0.03, ...) and select the largest producing monotone decrease
- Backtracking: If objective increases, halve α and retry
The optimal fixed step is α* = 2/(λ_max + λ_min), giving convergence in O(κ log(1/ε)) iterations where κ = λ_max/λ_min is the condition number.
Fixed vs decaying schedules:
- Fixed step: For full-batch optimization of smooth convex functions, a constant step below the stability threshold already provides geometric convergence. Decay is unnecessary and counterproductive.
- Decaying step (
α_t = α₀/(1+kt)or exponential): Essential for stochastic or mini-batch variants where gradient noise prevents convergence. For batch methods, decay acts as insurance whenλ_maxis uncertain.
Feature standardization impact:
Raw features with different scales (e.g., dollars vs percentages) create ill-conditioned XᵀX with huge κ. This forces tiny step sizes to handle steep directions, causing slow progress in flat directions—the classic elongated ellipse problem.
Solution: Standardize non-bias features to zero mean and unit variance. This:
- Transforms
XᵀX/mapproximately into a correlation matrix - Reduces
κdramatically (often to near 1 for weakly correlated features) - Decouples bias from other parameters since the bias column becomes orthogonal to centered features
- Never standardize the bias column itself
- Fit standardization parameters on training data only; transform learned coefficients back for interpretation
Part 5: L2 Regularization
Modified objective:
J(θ) = (1/(2m)) ||Xθ − y||² + (λ/(2m)) Σ_{j=1}^{n-1} θ_j²
Let D = diag(0, 1, 1, ..., 1) mask the bias. The gradient becomes:
∇J(θ) = (1/m) Xᵀ(Xθ − y) + (λ/m) Dθ
Component form:
- Bias:
∂J/∂θ₀ = (1/m) Σᵢ eᵢ(no penalty) - Others:
∂J/∂θⱼ = (1/m) Σᵢ eᵢxᵢⱼ + (λ/m)θⱼfor j ≥ 1
The update can be written as θⱼ ← θⱼ(1 − αλ/m) − α·(data_gradient), revealing the "weight decay" interpretation.
Why exclude bias: Penalizing the bias shrinks predictions toward zero rather than toward the empirical mean of y, making the solution dependent on arbitrary target shifts.
Optimization benefits:
- Regularization increases the smallest eigenvalues of the Hessian, improving conditioning
- Guarantees uniqueness even when
XᵀXis singular (collinear features or n > m) - Speeds convergence by reducing κ
- Closed form
θ = (XᵀX + λD)⁻¹Xᵀyserves as a validation reference
Choosing λ: Use cross-validation with a logarithmic grid (0.001, 0.01, 0.1, 1, 10, 100). Start with features already standardized so λ values have consistent meaning across problems. Monitor both training and validation error to detect the sweet spot between underfitting and overfitting.