Recursive Feature Elimination From Scratch

Quick Overview

Implement recursive feature elimination from scratch: refit a cloned estimator each round, drop the features with the smallest squared coefficients or importances, and return the kept indices and a ranking. It tests parameter validation, index bookkeeping and tie handling.

Recursive Feature Elimination From Scratch

Role: Machine Learning Engineer

Category: Machine Learning

Difficulty: medium

Interview Round: Other

Implement `recursive_feature_elimination(estimator, X, y, n_features_to_select=None, step=1)`. Each round, fit a fresh `clone` of `estimator` on the surviving columns (in original order), score the features, and drop the weakest. Return `(selected_indices, ranking)` as `int64` arrays: the original indices of the kept columns in ascending order, and one rank per original column. Requirements: - Importance is the squared `coef_` (summed over rows when `coef_` is 2-D), otherwise the squared `feature_importances_`. Ties drop the lowest original index first. - Target `k`: `None` gives `n // 2`, a float `f` in (0, 1) gives `int(f * n)`, and an int is used as given. A `k` outside [1, n] raises `ValueError`. - Step: a float in (0, 1) gives `max(1, int(step * n))`, where `n` is the original column count. Otherwise the step must be an int of at least 1. Anything else (for example `0` or `2.5`) raises `ValueError`. - Each round removes `min(step, remaining - k)` features, then adds 1 to the rank of every feature eliminated so far. Selected features have rank 1. - Do not mutate `X`, and do not fit the passed `estimator` itself. Example: ```python # est is an estimator whose fit sets coef_ = X.mean(axis=0) X = [[2, -2, 4, 0, 1], [4, 0, 6, 1, 3]] # column means (3, -1, 5, 0.5, 2) recursive_feature_elimination(est, X, y, 2, 1) # Output: (array([0, 2]), array([1, 3, 1, 4, 2])) ``` The squared means are (9, 1, 25, 0.25, 4), so column 3 goes first, then column 1, then column 4 on the refit over columns 0, 2 and 4. Column 3 was bumped in all three rounds, so it ends at rank 4. ```hint State to keep A boolean mask of surviving columns and an integer ranking array are enough. Each round's importances refer to positions in the current subset, so map them back to original columns. ``` ```hint Tie order Check whether your sort keeps equal importances in their original column order. ``` ### Constraints & Assumptions - `X` is 2-D with at least one column, and the estimator follows the scikit-learn `fit` API, so `sklearn.base.clone` works on it. - When no two importances tie within a round, `selected_indices` and `ranking` must match `support_` and `ranking_` from `sklearn.feature_selection.RFE` with the same estimator, target and step. ### Clarifying Questions to Ask - What should happen when the estimator exposes neither `coef_` nor `feature_importances_`? - Can `X` be a pandas DataFrame, and do the column names need to survive? - Are there fit parameters, such as sample weights, that every round must receive? ### What a Strong Answer Covers - Resolution and validation of `k` and `step`, including fractions, zero and booleans. - A fresh clone per round, fitted on the surviving columns in original order, with importances mapped back to original indices. - A capped final round that lands exactly on `k`, and a ranking update that gives features dropped in the same round the same rank. - Deterministic tie-breaking. - The number of fits and the cost of each. ### Follow-up Questions - How would you choose `k` automatically instead of fixing it? - Why can raw coefficient magnitudes be a misleading importance signal? - How does the cost scale, and how would you speed it up?

Overview: Implement recursive feature elimination from scratch: refit a cloned estimator each round, drop the features with the smallest squared coefficients or importances, and return the kept indices and a ranking. It tests parameter validation, index bookkeeping and tie handling.

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

Implement recursive_feature_elimination(estimator, X, y, n_features_to_select=None, step=1). Each round, fit a fresh clone of estimator on the surviving columns (in original order), score the features, and drop the weakest. Return (selected_indices, ranking) as int64 arrays: the original indices of the kept columns in ascending order, and one rank per original column.

Requirements:

  • Importance is the squared coef_ (summed over rows when coef_ is 2-D), otherwise the squared feature_importances_ . Ties drop the lowest original index first.
  • Target k : None gives n // 2 , a float f in (0, 1) gives int(f * n) , and an int is used as given. A k outside [1, n] raises ValueError .
  • Step: a float in (0, 1) gives max(1, int(step * n)) , where n is the original column count. Otherwise the step must be an int of at least 1. Anything else (for example 0 or 2.5 ) raises ValueError .
  • Each round removes min(step, remaining - k) features, then adds 1 to the rank of every feature eliminated so far. Selected features have rank 1.
  • Do not mutate X , and do not fit the passed estimator itself.

Example:

# est is an estimator whose fit sets coef_ = X.mean(axis=0)
X = [[2, -2, 4, 0, 1],
     [4,  0, 6, 1, 3]]          # column means (3, -1, 5, 0.5, 2)
recursive_feature_elimination(est, X, y, 2, 1)
# Output: (array([0, 2]), array([1, 3, 1, 4, 2]))

The squared means are (9, 1, 25, 0.25, 4), so column 3 goes first, then column 1, then column 4 on the refit over columns 0, 2 and 4. Column 3 was bumped in all three rounds, so it ends at rank 4.

Constraints & Assumptions

  • X is 2-D with at least one column, and the estimator follows the scikit-learn fit API, so sklearn.base.clone works on it.
  • When no two importances tie within a round, selected_indices and ranking must match support_ and ranking_ from sklearn.feature_selection.RFE with the same estimator, target and step.

Clarifying Questions to Ask Guidance

  • What should happen when the estimator exposes neither coef_ nor feature_importances_ ?
  • Can X be a pandas DataFrame, and do the column names need to survive?
  • Are there fit parameters, such as sample weights, that every round must receive?

What a Strong Answer Covers Guidance

  • Resolution and validation of k and step , including fractions, zero and booleans.
  • A fresh clone per round, fitted on the surviving columns in original order, with importances mapped back to original indices.
  • A capped final round that lands exactly on k , and a ranking update that gives features dropped in the same round the same rank.
  • Deterministic tie-breaking.
  • The number of fits and the cost of each.

Follow-up Questions Guidance

  • How would you choose k automatically instead of fixing it?
  • Why can raw coefficient magnitudes be a misleading importance signal?
  • How does the cost scale, and how would you speed it up?