TExcelTAD

Embedded Methods

Filters ignore the model and wrappers retrain it hundreds of times. Embedded methods sit in between: the selection happens during one training run, as a side effect of how the model learns. The two classic examples are the L1 penalty of the Lasso, which pushes useless coefficients to exactly zero, and the feature importances of tree ensembles. scikit-learn's SelectFromModel turns either into a selection step for a pipeline.

L1 regularisation: selection by the loss function

The Lasso fits a linear model by minimising the squared error plus the sum of absolute coefficients:

min⁡w,b  12n∑i=1n(yi−b−xi⊤w)2+α∑j=1p∣wj∣\min_{w, b} \; \frac{1}{2n} \sum_{i=1}^{n} \left(y_i - b - x_i^\top w\right)^2 + \alpha \sum_{j=1}^{p} \lvert w_j \rvert

The penalty's kink at zero makes it cheaper, for a weak feature, to set its weight to exactly 0 than to keep a small value; the squared penalty of Ridge only shrinks weights towards zero. Larger α\alpha means more zeros. The geometry (the L1 ball has corners on the axes) is explained in MAP Estimation and Regularisation.

Coordinate descent solves the Lasso one weight at a time. For standardised features each update is a soft threshold: compute the correlation ρj\rho_j of feature jj with the current residual (with feature jj's own contribution added back) and set

wj←S(ρj,α)=sign⁡(ρj)max⁡(∣ρj∣−α,0)w_j \leftarrow S(\rho_j, \alpha) = \operatorname{sign}(\rho_j) \max(\lvert \rho_j \rvert - \alpha, 0)

Any feature whose correlation with the residual is smaller than α\alpha gets weight 0.

From scratch: Lasso by coordinate descent

python · try it yourself
import numpy as np

rng = np.random.default_rng(0)
n, p = 200, 6
X = rng.normal(0, 1, (n, p))
X = (X - X.mean(0)) / X.std(0)                     # standardised features
true_w = np.array([3.0, -2.0, 1.0, 0.0, 0.0, 0.0])
y = X @ true_w + rng.normal(0, 1, n)
y = y - y.mean()

def lasso_cd(X, y, alpha, sweeps=200):
    n, p = X.shape
    w = np.zeros(p)
    for _ in range(sweeps):
        for j in range(p):
            residual = y - X @ w + X[:, j] * w[j]          # leave feature j out
            rho = X[:, j] @ residual / n
            w[j] = np.sign(rho) * max(abs(rho) - alpha, 0.0)
    return w

for alpha in [0.0, 0.1, 0.5, 1.5]:
    w = lasso_cd(X, y, alpha)
    print(f"alpha {alpha:3.1f}: w = {(np.round(w, 2) + 0.0).tolist()}  non-zero: {int((w != 0).sum())}")
alpha 0.0: w = [3.0, -1.97, 1.06, 0.09, 0.08, -0.23]  non-zero: 6
alpha 0.1: w = [2.88, -1.88, 0.96, 0.0, 0.0, -0.11]  non-zero: 4
alpha 0.5: w = [2.44, -1.47, 0.59, 0.0, 0.0, 0.0]  non-zero: 3
alpha 1.5: w = [1.37, -0.4, 0.0, 0.0, 0.0, 0.0]  non-zero: 2

With α=0\alpha = 0 it is ordinary least squares and all six weights are non-zero (the three useless ones small but not zero). At α=0.1\alpha = 0.1 two of the three useless features are exactly zero and the third is down to -0.11; from α=0.5\alpha = 0.5 all three are zero, and at α=1.5\alpha = 1.5 even the weakest true feature is gone. The true weights also shrink by about α\alpha, the price of the penalty, which is why people often refit an unpenalised model on the selected features.

In scikit-learn: LassoCV and SelectFromModel

LassoCV chooses α\alpha by cross-validation; SelectFromModel keeps the features with non-zero (or large enough) coefficients. Because the penalty treats all weights alike, the features must be on the same scale, so a StandardScaler comes first, inside the pipeline:

python · try it yourself
import numpy as np
from sklearn.datasets import load_diabetes
from sklearn.feature_selection import SelectFromModel
from sklearn.linear_model import LassoCV, LinearRegression
from sklearn.model_selection import cross_val_score, KFold
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler

data = load_diabetes()
X, y, names = data.data, data.target, np.array(data.feature_names)
cv = KFold(5, shuffle=True, random_state=0)

lasso = make_pipeline(StandardScaler(), LassoCV(cv=cv, random_state=0)).fit(X, y)
coef = lasso[-1].coef_
print("alpha chosen:", round(float(lasso[-1].alpha_), 3))
print("coefficients:", dict(zip(names.tolist(), (np.round(coef, 1) + 0.0).tolist())))

pipe = make_pipeline(StandardScaler(), SelectFromModel(LassoCV(cv=cv, random_state=0)), LinearRegression())
pipe.fit(X, y)
print("kept:", names[pipe[1].get_support()].tolist())
print("CV R2 with selection:", round(cross_val_score(pipe, X, y, cv=cv, scoring="r2").mean(), 3))
alpha chosen: 0.846
coefficients: {'age': 0.0, 'sex': -9.6, 'bmi': 24.9, 'bp': 14.3, 's1': -5.6, 's2': 0.0, 's3': -10.2, 's4': 0.7, 's5': 24.6, 's6': 2.7}
kept: ['sex', 'bmi', 'bp', 's1', 's3', 's4', 's5', 's6']
CV R2 with selection: 0.489

The Lasso set 2 of the 10 (age and s2; s2 is strongly correlated with s1, so the Lasso keeps one of the pair) coefficients to zero. In the last line the whole pipeline (scaling, the inner LassoCV, the selection, the final regression) is refitted inside each outer fold, so the score is honest.

Tree importances, and why to check them with permutation

Tree ensembles report feature_importances_: how much each feature reduced impurity over all splits. It comes free with training, but it is measured on the training data and is biased towards features with many distinct values, which offer many split points to fit noise. Permutation importance is the remedy: shuffle one column of a held-out set and measure how much the score drops. A useless column, however many values it has, does not hurt when shuffled.

python · try it yourself
import numpy as np
from sklearn.ensemble import RandomForestClassifier
from sklearn.inspection import permutation_importance
from sklearn.model_selection import train_test_split

rng = np.random.default_rng(1)
n = 1000
signal = rng.normal(0, 1, n)
weak = rng.normal(0, 1, n)
row_id = rng.permutation(n).astype(float)        # unique per row, no information
coin = rng.integers(0, 2, n).astype(float)       # two values, no information
y = (signal + 0.3 * weak + rng.normal(0, 1, n) > 0).astype(int)
X = np.column_stack([signal, weak, row_id, coin])
names = ["signal", "weak", "row_id", "coin"]

X_tr, X_va, y_tr, y_va = train_test_split(X, y, test_size=0.3, random_state=0, stratify=y)
rf = RandomForestClassifier(n_estimators=200, random_state=0).fit(X_tr, y_tr)
perm = permutation_importance(rf, X_va, y_va, n_repeats=10, random_state=0)
print(f"{'feature':8s} {'impurity':>9s} {'permutation':>12s}")
for name, imp, pm in zip(names, rf.feature_importances_, perm.importances_mean):
    print(f"{name:8s} {imp:9.3f} {pm:12.3f}")
feature   impurity  permutation
signal       0.518        0.194
weak         0.249        0.006
row_id       0.205       -0.001
coin         0.028       -0.022

By impurity, the meaningless row_id looks almost as important as weak (0.205 against 0.249), because the forest used its 700 unique values to memorise training rows. On the validation rows, shuffling it changes nothing (-0.001; small negative values are noise, as for coin). Use impurity importances for a quick look, permutation importances on held-out data for decisions. Both split credit between correlated features, so a feature can look unimportant only because a near-copy is present.

Pitfalls

  • Unscaled inputs with L1: the penalty then depends on the units; a feature in millimetres needs a huge weight and gets penalised, in kilometres a tiny one. Standardise first.
  • Correlated features with the Lasso: it tends to keep one of a group and drop the others, somewhat arbitrarily; the choice can flip between folds. Elastic net (L1 plus L2) keeps groups together.
  • Selecting on all data: SelectFromModel fitted before the split is as leaky as any filter. Keep it in the pipeline.
  • Importance is not causation: a high importance means the model relies on the feature, not that changing it changes the outcome.

Practice

  1. The soft-threshold update gives ρj=0.3\rho_j = 0.3. What is wjw_j for α=0.1\alpha = 0.1 and for α=0.5\alpha = 0.5?
Answer

S(0.3,0.1)=0.3−0.1=0.2S(0.3, 0.1) = 0.3 - 0.1 = 0.2. For α=0.5\alpha = 0.5, ∣0.3∣−0.5<0\lvert 0.3 \rvert - 0.5 < 0, so wj=0w_j = 0: the feature is dropped.

  1. Why is permutation importance computed on validation data rather than on the training data?
Answer

On training data an overfitted model relies on noise features (like row_id) to reproduce memorised labels, so shuffling them hurts the training score. On held-out data that memorisation is useless, so only features that generalise show an importance.

Test yourself

Why does the L1 penalty produce exactly zero weights while L2 does not?

  1. L1 is larger
  2. The absolute value has a kink at zero, so for weak features the optimum sits exactly at 0
  3. L2 cannot be optimised
  4. L1 uses fewer rows

Why must features be standardised before a Lasso used for selection?

  1. Lasso needs positive inputs
  2. The penalty is the same for every weight, so it would depend on each feature's unit
  3. To remove outliers
  4. It is faster

A random forest ranks a unique customer ID among its most important features. What should you check?

  1. Nothing, IDs are predictive
  2. Permutation importance on held-out data; impurity importance favours high-cardinality features
  3. Increase the number of trees
  4. Scale the ID

What does SelectFromModel(LassoCV()) inside a pipeline do at fit time?

  1. Nothing until predict
  2. Fits a Lasso on the training rows and keeps the features with non-zero coefficients
  3. Removes rows with missing values
  4. Chooses features at random