Concepts / Sparse Linear Models and L1 Penalties

Sparse Linear Models and L1 Penalties

The selection model is a tool for judging features, and the final model is the one you deploy.

  • Programming

Too Many Columns, Too Little Signal

A supervised dataset often contains more columns than a useful model needs. Some features carry real signal about the target. Others add noise, duplicate information that another column already provides, or simply make the model harder to train. Before a model can be trained well, someone has to decide which columns deserve to stay.

This article follows one question through the whole discussion: what does a model need to hand back so that we can rank its features? The answer shapes everything else. We will first look at the general idea, then at the two families of models the source highlights, then at how L1 penalties make some weights exactly zero, and finally at the transformer that performs the selection in code.

Letting a Model Sort the Features

One way to deal with too many columns is to let a supervised machine learning model do the sorting. Instead of judging each feature on its own, you fit a model and ask it how much each feature contributes. The features can then be ranked by that measure, and only the strongest ones kept.

Definition

Model-based feature selection uses a supervised model to judge each feature's importance and keeps only the most important ones.

The phrase keeps only the most important ones describes the goal, but the mechanism has two distinct parts. First, a model produces a measure of importance for every feature. Second, those measures are used to rank the features and decide which to retain. If a candidate model cannot produce a per-feature importance measure, it cannot drive selection in this way.

Where Importance Scores Come From

Different model families expose importance in different ways. The source highlights two routes: decision tree-based models provide a ready-made attribute, while linear models require one extra interpretation step. The two routes below both end in the same operation, ordering the features by a measure of importance.

How an L1 Penalty Zeroes Out Weights

The source also connects linear models to sparsity. Linear models with an L1 penalty learn sparse coefficients, meaning that only a small subset of features receives nonzero weight. Every other feature ends up with a coefficient of exactly zero. This sparsity can be viewed as a form of feature selection built into the model itself.

What do you think happens?

After an L1-penalized linear model is fitted on ten features, what happens to the features that the model does not need?

  • Their coefficients shrink but stay nonzero

  • Their coefficients become exactly zero

  • Their coefficients flip sign

Reveal answer
Answer:

Their coefficients become exactly zero.

The source states that an L1 penalty learns sparse coefficients, so only a small subset of features receives nonzero weight. Features outside that subset are left with zero weight.

Feature Anonzero weightFeature Bzero weightFeature Czero weightFeature Dnonzero weightFeature Ezero weight
Which features keep a nonzero weight after L1 regularization, and which are dropped to zero?

Read the diagram as a state trace. Each feature is a key, and its sublabel is the state its weight ends up in after fitting. Features A and D keep nonzero weights, so they survive. Features B, C, and E are driven to zero and are dropped. The selection is a side effect of fitting the penalized model, not a separate step that someone runs afterward.

Using SelectFromModel in a Workflow

Computing importance scores is only half the job. To use model-based feature selection in a workflow, the source points to the SelectFromModel transformer. A transformer, in the scikit-learn style, is an object that learns something from training data and then transforms data. Here the thing it learns is which features pass an importance test, and the transformation removes the features that fail.

Full feature matrixall columns of XSelection modelfittedone importance per featureImportancesthresholdedfeatures pass or failReduced matrixfewer columns, same rowsFinal modeltrained on kept featuresfit on X, yimportance valueskeep passing columnssecond model
What happens to the feature matrix when a fitted model's importances are thresholded, and how does the reduced matrix flow into a second model?

The pipeline shows the flow. The transformer fits a selection model, uses its importance values to decide which features pass, and then outputs a matrix with fewer columns. The decision step depends on a threshold. The exact threshold options are part of the transformer's configuration and are worth reading in its documentation for the version you have installed.

python
Walk through it
  1. 1
    Create the selector around a tree-based model so that feature_importances_ drives the decision.
  2. 2
    fit_transform learns which features pass the threshold and removes the rest.
  3. 3
    Printing both shapes shows the number of rows is unchanged while the number of columns may drop.
Notes on the code
  • The selection model is passed in as the estimator; it must provide an importance measure for each feature.
  • threshold="mean" is one of the threshold options; check the documentation for your installed version.
  • fit_transform both fits the selection model and returns the reduced matrix.

Run this code yourself on your own dataset to see how many columns were kept. The source does not give specific numbers, and the count depends on the data and settings. What you can rely on is the shape change: the number of rows stays the same because the transformer removes features, not observations.

Model-Based Versus Univariate Selection

The source contrasts model-based selection with univariate selection. Univariate methods judge each feature separately, one at a time. Model-based selection instead considers all features at once, because the model is fitted on the full feature set. This is why the source says model-based selection can capture interactions, provided the model is able to capture them.

Feature 1 alonescored by itselfAll features togetherfull feature setFeature 2 alonescored by itselfOne fitted modelweighs features jointlyRanking by own scoreno shared fitImportance perfeatureranked after one fit
How does a univariate test score each feature in isolation, while a model-based method weighs all features together in one fit?
AspectUnivariate selectionModel-based selection
Features considered at onceOne feature at a timeAll features together in one fit
Basis of the scoreEach feature judged separatelyImportance measure from the fitted model
InteractionsNot captured by judging features separatelyCan be captured, if the model is able to capture them

Two routes to choosing features

Mistakes Learners Make With Importance Scores

  • Common mistake

    Treating the sign of a coefficient as its importance

    What it looks like

    A coefficient of -2.1 is read as less important than +0.8.

    Why it fails

    The sign gives the direction of the effect. Importance under the source's measure is based on magnitude.

    Do this instead

    Take the absolute value first, then rank: |-2.1| = 2.1 is larger than 0.8.

  • Common mistake

    Assuming every model exposes feature_importances_

    What it looks like

    Calling model.feature_importances_ on a linear model and expecting a result.

    Why it fails

    The source says linear models do not expose that attribute. They have coefficients instead.

    Do this instead

    For linear models, compute scores from the absolute values of the coefficients.

  • Common mistake

    Expecting fewer rows after selection

    What it looks like

    Thinking SelectFromModel removes observations that do not fit the pattern.

    Why it fails

    The transformer removes features, not observations.

    Do this instead

    Expect the same number of rows and a smaller number of columns.

  • Common mistake

    Assuming the selection model must be the final model

    What it looks like

    Refusing to train a different model on the features selected by a tree-based ranking.

    Why it fails

    The source says the selection model is a tool for judging features and need not be the deployed model.

    Do this instead

    Use one model to rank features and another to predict, if that suits the problem.

  • Common mistake

    Comparing unscaled coefficients across features measured in very different units

Trace the Mechanism Yourself

EASY

A linear model with an L1 penalty is fitted on six features. Four of them end with coefficients of exactly zero. Which features does SelectFromModel keep, and why would it not keep the other four?

Hints
  • Recall that the source ties sparsity to nonzero weights.
  • Think about what the threshold does to importance values, and what a zero coefficient means for the absolute-value score.
MEDIUM

Given coefficients +0.4, -1.7, +0.0, and -0.9 for four features, write the importance ranking using absolute values, then state which features an L1-penalized model would keep if the zero coefficient is the only one dropped.

Hints
  • Compute the absolute value of each coefficient before sorting.
  • A coefficient of exactly zero is the sparse outcome the source describes.

Key Takeaways From the Mechanism

  1. 1
    Model-based feature selection asks a supervised model to produce an importance measure for each feature, then ranks and keeps the strongest ones.
  2. 2
    Decision tree-based models supply importance directly through feature_importances_, while linear models require taking absolute values of their coefficients.
  3. 3
    An L1 penalty drives some coefficients to exactly zero, so the fitted model is sparse and its nonzero features act as a built-in selection.
  4. 4
    SelectFromModel thresholds the importances and outputs a reduced matrix with the same rows and fewer columns, and it considers all features together rather than one at a time.

At a glance

  • Model-based feature selection asks a supervised model to produce an importance measure for each feature, then ranks and keeps the strongest ones.
  • Decision tree-based models supply importance directly through feature_importances_, while linear models require taking absolute values of their coefficients.
  • An L1 penalty drives some coefficients to exactly zero, so the fitted model is sparse and its nonzero features act as a built-in selection.
  • SelectFromModel thresholds the importances and outputs a reduced matrix, considering all features together rather than one at a time.

Related concepts

More concepts starting with S