Elastic Net via Coordinate Descent

Quick Overview

Implement the soft-thresholding operator and an elastic net solver that minimizes squared error plus mixed L1 and L2 penalties by cyclic coordinate descent in NumPy. It tests the closed-form coordinate update, incremental residuals, unpenalized intercept handling, exact zeros and agreement with scikit-learn.

Elastic Net via Coordinate Descent

Role: Machine Learning Engineer

Category: Machine Learning

Difficulty: hard

Interview Round: Other

Implement `soft_threshold(z, gamma)` (elementwise `sign(z) * max(|z| - gamma, 0)`) and `elastic_net_cd(X, y, alpha, l1_ratio, max_iter=10000, tol=1e-10, fit_intercept=True)`, which minimizes the objective below by cyclic coordinate descent. It returns `(coef, intercept)`: a length-`p` array and a `float`. ```text 1/(2n) * ||y - b0 - X w||^2 + alpha * l1_ratio * ||w||_1 + 0.5 * alpha * (1 - l1_ratio) * ||w||_2^2 ``` Examples: ```python soft_threshold([-3.0, -0.5, 0.0, 0.2, 1.0, 4.0], 0.5) # -> [-2.5, 0.0, 0.0, 0.0, 0.5, 3.5] elastic_net_cd([[1], [2], [3]], [1, 2, 3], alpha=0.5, l1_ratio=0.5) # -> (array([0.454545...]), 1.090909...) coef = 5/11, intercept = 12/11 elastic_net_cd([[1], [2], [3]], [1, 2, 3], alpha=2.0, l1_ratio=0.5) # -> (array([0.0]), 2.0) the penalty is large enough to zero the only coefficient ``` Entries with `|z| <= gamma` map to zero and the rest move toward zero by `gamma`. In the second call the centered feature and target are both `[-1, 0, 1]`, so the single coefficient is a shrunken version of the least-squares slope 1, and the intercept is `mean(y) - mean(X) * coef`. ```hint One coordinate at a time Hold every coefficient except `w_j` fixed and write the objective as a function of `w_j` alone. It is a one-dimensional quadratic plus an absolute value term. ``` ```hint Keep the residual current Recomputing `y - X @ w` for every coordinate makes each update cost `O(n*p)`. Adjust the residual by the change in `w_j` instead. ``` ```hint Exact zeros Check what your update returns when the partial correlation lies inside the threshold, and whether that value is a true zero. ``` ### Constraints & Assumptions - Start at `w = 0` and sweep `j = 0..p-1` in order. Stop when the largest absolute coefficient change in a sweep is below `tol`, or after `max_iter` sweeps. - `b0` is unpenalized. If `fit_intercept`, center the data and return `mean(y) - mean(X) @ coef` as the intercept. Otherwise do not center, and return `0.0`. - Inactive coefficients must be exactly `0`. A coordinate with a zero denominator (a constant column with `l1_ratio = 1`) stays `0`. - `alpha < 0` or `l1_ratio` outside `[0, 1]` raises `ValueError`. - Results must match `sklearn.linear_model.ElasticNet` to rtol `1e-4`. With `l1_ratio = 0` they must match the ridge closed form. ### What a Strong Answer Covers - The closed-form coordinate update: the L1 part as a soft-threshold of the partial correlation and the L2 part added to the denominator. - An incremental residual update so that one sweep costs `O(n*p)`. - Centering to keep the intercept unpenalized, recovering it at the end, and skipping centering when `fit_intercept=False`. - Exact zeros, zero-denominator coordinates, input validation and the specified stopping rule. - How the result lines up with sklearn's `ElasticNet` and with the ridge closed form at `l1_ratio = 0`. ### Follow-up Questions - How would you compute a full regularization path efficiently? - What happens with two identical features, and why does it differ from lasso? - How could you avoid updating coordinates that will stay at zero?

Overview: Implement the soft-thresholding operator and an elastic net solver that minimizes squared error plus mixed L1 and L2 penalties by cyclic coordinate descent in NumPy. It tests the closed-form coordinate update, incremental residuals, unpenalized intercept handling, exact zeros and agreement with scikit-learn.

PracHub logo
General
Nov 25, 2026
hardMachine Learning EngineerOtherMachine Learning
0
0

Implement soft_threshold(z, gamma) (elementwise sign(z) * max(|z| - gamma, 0)) and elastic_net_cd(X, y, alpha, l1_ratio, max_iter=10000, tol=1e-10, fit_intercept=True), which minimizes the objective below by cyclic coordinate descent. It returns (coef, intercept): a length-p array and a float.

1/(2n) * ||y - b0 - X w||^2
  + alpha * l1_ratio * ||w||_1
  + 0.5 * alpha * (1 - l1_ratio) * ||w||_2^2

Examples:

soft_threshold([-3.0, -0.5, 0.0, 0.2, 1.0, 4.0], 0.5)
# -> [-2.5, 0.0, 0.0, 0.0, 0.5, 3.5]

elastic_net_cd([[1], [2], [3]], [1, 2, 3], alpha=0.5, l1_ratio=0.5)
# -> (array([0.454545...]), 1.090909...)   coef = 5/11, intercept = 12/11

elastic_net_cd([[1], [2], [3]], [1, 2, 3], alpha=2.0, l1_ratio=0.5)
# -> (array([0.0]), 2.0)   the penalty is large enough to zero the only coefficient

Entries with |z| <= gamma map to zero and the rest move toward zero by gamma. In the second call the centered feature and target are both [-1, 0, 1], so the single coefficient is a shrunken version of the least-squares slope 1, and the intercept is mean(y) - mean(X) * coef.

Constraints & Assumptions

  • Start at w = 0 and sweep j = 0..p-1 in order. Stop when the largest absolute coefficient change in a sweep is below tol , or after max_iter sweeps.
  • b0 is unpenalized. If fit_intercept , center the data and return mean(y) - mean(X) @ coef as the intercept. Otherwise do not center, and return 0.0 .
  • Inactive coefficients must be exactly 0 . A coordinate with a zero denominator (a constant column with l1_ratio = 1 ) stays 0 .
  • alpha < 0 or l1_ratio outside [0, 1] raises ValueError .
  • Results must match sklearn.linear_model.ElasticNet to rtol 1e-4 . With l1_ratio = 0 they must match the ridge closed form.

What a Strong Answer Covers Guidance

  • The closed-form coordinate update: the L1 part as a soft-threshold of the partial correlation and the L2 part added to the denominator.
  • An incremental residual update so that one sweep costs O(n*p) .
  • Centering to keep the intercept unpenalized, recovering it at the end, and skipping centering when fit_intercept=False .
  • Exact zeros, zero-denominator coordinates, input validation and the specified stopping rule.
  • How the result lines up with sklearn's ElasticNet and with the ridge closed form at l1_ratio = 0 .

Follow-up Questions Guidance

  • How would you compute a full regularization path efficiently?
  • What happens with two identical features, and why does it differ from lasso?
  • How could you avoid updating coordinates that will stay at zero?