Implement elastic net by coordinate descent and compare lasso vs elastic net grouping stability

Quick Overview

Implement elastic net with cyclic coordinate descent in NumPy, then compare how lasso and elastic net select features from a correlated group across bootstrap resamples. Tests the soft-thresholding update, intercept handling, reproducible bootstrapping and the grouping effect of the L2 penalty.

Implement elastic net by coordinate descent and compare lasso vs elastic net grouping stability

Role: Machine Learning Engineer

Category: Machine Learning

Difficulty: medium

Interview Round: Other

Implement elastic net by coordinate descent, then measure how lasso and elastic net select features from a strongly correlated group across bootstrap resamples. Implement the four functions in this starter using NumPy only. ```python import numpy as np def elastic_net_cd(X, y, alpha, l1_ratio, max_iter=10000, tol=1e-10): ... def bootstrap_selection_frequency(X, y, alpha, l1_ratio, n_boot, seed, threshold=1e-8, max_iter=10000, tol=1e-10): ... def selection_instability(freq): ... def group_participation(coef, groups): ... ``` - `elastic_net_cd` minimises `1/(2n)||y - b0 - Xw||² + alpha*l1_ratio*||w||₁ + 0.5*alpha*(1-l1_ratio)*||w||²` with an unpenalised intercept `b0`, which matches scikit-learn's `ElasticNet`. Use cyclic coordinate descent over `j = 0..p-1` starting from `w = 0`, and stop when the largest coefficient change in a sweep is below `tol`. Return `(coef, intercept)` with the intercept as a Python `float`. - `bootstrap_selection_frequency` creates `rng = np.random.default_rng(seed)`, draws `idx = rng.integers(0, n, size=n)` for each of the `n_boot` fits, counts a feature as selected when `|coef| > threshold`, and returns counts / `n_boot` as an array of shape `(p,)`. It passes `max_iter` and `tol` through to `elastic_net_cd`. - `selection_instability` returns `4 * mean(f * (1 - f))` as a float. - `group_participation` returns, for each group of column indices, `(Σ|w_g|)² / Σw_g²`, and `0.0` for a group whose coefficients are all zero. With an exactly duplicated column, lasso keeps only the first copy and elastic net splits the weight equally between the two copies. Example: ```python group_participation([3, -1, 0, 0, 2, 2, 2, 0], [[0, 1], [2, 3], [4, 5, 6], [7]]) # -> [1.6, 0.0, 3.0, 0.0] selection_instability([1.0, 0.0, 0.5]) # -> 0.3333... selection_instability([0.5, 0.5]) # -> 1.0 ``` ```hint Coordinate update Fix every coefficient except one and write the one-dimensional objective using the residual with that feature's contribution added back. Then ask what the L1 term and the L2 term each do to its minimiser. ``` ```hint Intercept The intercept is unpenalised. Centering `X` and `y` lets you ignore it during the sweeps and recover it once at the end. ``` ```hint Duplicated columns Trace the first sweep on two identical columns. After feature 0 is updated, compare its twin's correlation with the residual to the L1 threshold. ``` ### Constraints & Assumptions - `0 < l1_ratio ≤ 1`, where `l1_ratio = 1.0` is lasso, and `alpha > 0`. - Only NumPy may be used in the solution. - `X` has shape `(n, p)` and `y` has shape `(n,)`. A column can be constant inside a bootstrap resample. ### What a Strong Answer Covers - A coordinate update that matches the stated objective, including the 0.5 on the ridge term, with the residual kept in sync and the intercept handled by centering. - A bootstrap that uses one generator and the stated draw for every fit, so the frequencies are reproducible from the seed. - Correct instability and participation formulas, including the all-zero group. - An explanation of why lasso puts all the weight on the first duplicate while elastic net splits it equally. - Handling of constant columns in a resample, rounding residue near zero, and the stopping rule. ### Follow-up Questions - How would you turn bootstrap frequencies into a feature-selection rule? - How would you compute a full regularisation path efficiently? - When the columns in a group are highly correlated but not identical, how does lasso's choice inside the group behave across resamples?

Overview: Implement elastic net with cyclic coordinate descent in NumPy, then compare how lasso and elastic net select features from a correlated group across bootstrap resamples. Tests the soft-thresholding update, intercept handling, reproducible bootstrapping and the grouping effect of the L2 penalty.

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

Implement elastic net by coordinate descent, then measure how lasso and elastic net select features from a strongly correlated group across bootstrap resamples. Implement the four functions in this starter using NumPy only.

import numpy as np


def elastic_net_cd(X, y, alpha, l1_ratio, max_iter=10000, tol=1e-10):
    ...


def bootstrap_selection_frequency(X, y, alpha, l1_ratio, n_boot, seed,
                                  threshold=1e-8, max_iter=10000, tol=1e-10):
    ...


def selection_instability(freq):
    ...


def group_participation(coef, groups):
    ...
  • elastic_net_cd minimises 1/(2n)||y - b0 - Xw||² + alpha*l1_ratio*||w||₁ + 0.5*alpha*(1-l1_ratio)*||w||² with an unpenalised intercept b0 , which matches scikit-learn's ElasticNet . Use cyclic coordinate descent over j = 0..p-1 starting from w = 0 , and stop when the largest coefficient change in a sweep is below tol . Return (coef, intercept) with the intercept as a Python float .
  • bootstrap_selection_frequency creates rng = np.random.default_rng(seed) , draws idx = rng.integers(0, n, size=n) for each of the n_boot fits, counts a feature as selected when |coef| > threshold , and returns counts / n_boot as an array of shape (p,) . It passes max_iter and tol through to elastic_net_cd .
  • selection_instability returns 4 * mean(f * (1 - f)) as a float.
  • group_participation returns, for each group of column indices, (Σ|w_g|)² / Σw_g² , and 0.0 for a group whose coefficients are all zero.

With an exactly duplicated column, lasso keeps only the first copy and elastic net splits the weight equally between the two copies.

Example:

group_participation([3, -1, 0, 0, 2, 2, 2, 0], [[0, 1], [2, 3], [4, 5, 6], [7]])
# -> [1.6, 0.0, 3.0, 0.0]
selection_instability([1.0, 0.0, 0.5])  # -> 0.3333...
selection_instability([0.5, 0.5])       # -> 1.0

Constraints & Assumptions

  • 0 < l1_ratio ≤ 1 , where l1_ratio = 1.0 is lasso, and alpha > 0 .
  • Only NumPy may be used in the solution.
  • X has shape (n, p) and y has shape (n,) . A column can be constant inside a bootstrap resample.

What a Strong Answer Covers Guidance

  • A coordinate update that matches the stated objective, including the 0.5 on the ridge term, with the residual kept in sync and the intercept handled by centering.
  • A bootstrap that uses one generator and the stated draw for every fit, so the frequencies are reproducible from the seed.
  • Correct instability and participation formulas, including the all-zero group.
  • An explanation of why lasso puts all the weight on the first duplicate while elastic net splits it equally.
  • Handling of constant columns in a resample, rounding residue near zero, and the stopping rule.

Follow-up Questions Guidance

  • How would you turn bootstrap frequencies into a feature-selection rule?
  • How would you compute a full regularisation path efficiently?
  • When the columns in a group are highly correlated but not identical, how does lasso's choice inside the group behave across resamples?