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:
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 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 of feature with the current residual (with feature 's own contribution added back) and set
Any feature whose correlation with the residual is smaller than gets weight 0.
From scratch: Lasso by coordinate descent
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 it is ordinary least squares and all six weights are non-zero (the three useless ones small but not zero). At two of the three useless features are exactly zero and the third is down to -0.11; from all three are zero, and at even the weakest true feature is gone. The true weights also shrink by about , 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 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:
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.
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:
SelectFromModelfitted 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
- The soft-threshold update gives . What is for and for ?
Answer
. For , , so : the feature is dropped.
- 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?
- L1 is larger
- The absolute value has a kink at zero, so for weak features the optimum sits exactly at 0
- L2 cannot be optimised
- L1 uses fewer rows
Why must features be standardised before a Lasso used for selection?
- Lasso needs positive inputs
- The penalty is the same for every weight, so it would depend on each feature's unit
- To remove outliers
- It is faster
A random forest ranks a unique customer ID among its most important features. What should you check?
- Nothing, IDs are predictive
- Permutation importance on held-out data; impurity importance favours high-cardinality features
- Increase the number of trees
- Scale the ID
What does SelectFromModel(LassoCV()) inside a pipeline do at fit time?
- Nothing until predict
- Fits a Lasso on the training rows and keeps the features with non-zero coefficients
- Removes rows with missing values
- Chooses features at random