TExcelTAD

Filter Methods

A table with 500 columns where only 10 matter is a problem: noise features slow training, make models harder to explain and, with few rows, let the model fit chance patterns. Feature selection keeps a useful subset. It comes in three families: filters score each feature on its own with a statistic, wrappers (next lesson) search over subsets by training models, and embedded methods (after that) select while the model trains. Filters are the fastest and the simplest; the scikit-learn basics are in Feature Selection.

The idea

A filter asks, for each feature separately, "does this column carry information about the label?" and keeps the best kk columns (or those above a threshold). It never trains the final model, so it is cheap even for thousands of features, and it does not depend on which model comes next. The price: it looks at one feature at a time, so it misses features that are only useful together, and it happily keeps ten copies of the same information.

The common scores

Score For Measures
variance any numeric feature does the column vary at all? (constant columns carry nothing)
Pearson correlation rr numeric feature, numeric label linear relationship
ANOVA FF numeric feature, class label how far apart the class means are, relative to the spread inside classes
χ2\chi^2 non-negative counts or one-hot features, class label dependence between counts and classes
mutual information anything any kind of dependence, also non-linear

The Pearson correlation of a feature xx with the label yy over nn rows is

r=∑i=1n(xi−xˉ)(yi−yˉ)∑i=1n(xi−xˉ)2∑i=1n(yi−yˉ)2r = \frac{\sum_{i=1}^{n} (x_i - \bar{x})(y_i - \bar{y})}{\sqrt{\sum_{i=1}^{n} (x_i - \bar{x})^2} \sqrt{\sum_{i=1}^{n} (y_i - \bar{y})^2}}

and the mutual information of two discrete variables is

I(X;Y)=∑x,yp(x,y)log⁡p(x,y)p(x) p(y)I(X; Y) = \sum_{x, y} p(x, y) \log \frac{p(x, y)}{p(x)\, p(y)}

which is zero exactly when XX and YY are independent (see Entropy and KL Divergence). For continuous features scikit-learn estimates it from nearest-neighbour distances.

From scratch: variance and correlation

python · try it yourself
import numpy as np

rng = np.random.default_rng(0)
n = 300
informative = rng.normal(0, 1, (n, 3))
y = (informative @ np.array([1.5, -1.0, 0.8]) + rng.normal(0, 1, n) > 0).astype(int)
noise = rng.normal(0, 1, (n, 5))
constant = np.full((n, 1), 7.0)
X = np.hstack([informative, noise, constant])
names = ["inf_0", "inf_1", "inf_2"] + [f"noise_{i}" for i in range(5)] + ["constant"]

var = X.var(axis=0)
def corr(col, target):
    c, t = col - col.mean(), target - target.mean()
    denom = np.sqrt((c ** 2).sum() * (t ** 2).sum())
    return float((c * t).sum() / denom) if denom > 0 else 0.0
r = np.array([corr(X[:, j], y) for j in range(X.shape[1])])

order = np.argsort(-np.abs(r))
for j in order:
    print(f"{names[j]:9s} variance {var[j]:5.2f}   r = {r[j]:+.3f}")
inf_0     variance  0.95   r = +0.557
inf_2     variance  0.93   r = +0.315
inf_1     variance  0.96   r = -0.311
noise_3   variance  0.99   r = +0.082
noise_4   variance  0.99   r = +0.079
noise_0   variance  1.15   r = -0.057
noise_1   variance  1.02   r = -0.035
noise_2   variance  0.93   r = +0.031
constant  variance  0.00   r = +0.000

The three informative features come out on top, the constant column has variance 0 and is the first to go, and the noise features have correlations close to zero (the largest by chance is +0.082 with 300 rows). With fewer rows and more noise columns, some noise feature will always look good by luck, which is why the selection must be validated.

The scikit-learn filters, and what correlation misses

VarianceThreshold drops near-constant columns, SelectKBest keeps the kk best by any score function. Here the label depends on x12x_1^2, a U-shape: large positive and large negative values both mean class 1. Its correlation and its FF score are near zero, mutual information sees it:

python · try it yourself
import numpy as np
from sklearn.feature_selection import VarianceThreshold, SelectKBest, f_classif, mutual_info_classif

rng = np.random.default_rng(1)
n = 500
x0 = rng.normal(0, 1, n)                        # linear effect
x1 = rng.normal(0, 1, n)                        # U-shaped effect
x2 = rng.normal(0, 1, n)                        # noise
x3 = np.where(rng.random(n) < 0.99, 0.0, 1.0)   # almost constant
y = ((0.8 * x0 + x1 ** 2 + rng.normal(0, 0.5, n)) > 1).astype(int)
X = np.column_stack([x0, x1, x2, x3])
names = np.array(["x0 linear", "x1 U-shape", "x2 noise", "x3 rare"])

vt = VarianceThreshold(threshold=0.02).fit(X)
print("variances:", X.var(axis=0).round(3).tolist(), "-> kept:", names[vt.get_support()].tolist())
F, p = f_classif(X, y)
mi = mutual_info_classif(X, y, random_state=0)
for name, f_, mi_ in zip(names, F, mi):
    print(f"{name:11s} F = {f_:7.1f}   MI = {mi_:.3f}")
best2 = SelectKBest(mutual_info_classif, k=2).fit(X, y)
print("SelectKBest(MI, k=2):", names[best2.get_support()].tolist())
variances: [0.833, 1.111, 1.101, 0.008] -> kept: ['x0 linear', 'x1 U-shape', 'x2 noise']
x0 linear   F =   139.4   MI = 0.122
x1 U-shape  F =     1.1   MI = 0.253
x2 noise    F =     0.2   MI = 0.000
x3 rare     F =     1.9   MI = 0.007
SelectKBest(MI, k=2): ['x0 linear', 'x1 U-shape']

By the FF score the U-shaped feature looks like noise (FF of 1.1, against 139.4 for the linear one), because its class means are almost equal; by mutual information it is the strongest feature (0.253). Choose the score that matches the dependence you expect, and prefer mutual information when you do not know.

Selection belongs inside cross-validation

A filter looks at the labels, so it is a fitted step: run on all rows before splitting, it picks the features that happen to fit the test rows too. With 60 rows of pure noise and 1,000 features, the leaky procedure reports an excellent score for a model that can only guess:

python · try it yourself
import numpy as np
from sklearn.feature_selection import SelectKBest, f_classif
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import cross_val_score, StratifiedKFold
from sklearn.pipeline import make_pipeline

rng = np.random.default_rng(2)
X = rng.normal(0, 1, (60, 1000))          # pure noise
y = np.array([0, 1] * 30)                 # labels unrelated to X
cv = StratifiedKFold(5, shuffle=True, random_state=0)

X_sel = SelectKBest(f_classif, k=20).fit_transform(X, y)          # WRONG: selection saw every row
leaky = cross_val_score(LogisticRegression(), X_sel, y, cv=cv).mean()
pipe = make_pipeline(SelectKBest(f_classif, k=20), LogisticRegression())
honest = cross_val_score(pipe, X, y, cv=cv).mean()
print(f"selection before CV: accuracy {leaky:.2f}")
print(f"selection inside CV: accuracy {honest:.2f}   (chance is 0.50)")
selection before CV: accuracy 0.85
selection inside CV: accuracy 0.53   (chance is 0.50)

An accuracy of 0.85 against 0.53 on data with no signal at all. The leakage lab in The Leakage Rules shows this case step by step.

Pitfalls

  • Redundancy: filters keep correlated copies (temperature in Celsius and in Fahrenheit both score high). Drop near-duplicates by their mutual correlation, or use a wrapper or embedded method.
  • Interactions: a feature useless alone but decisive together with another (the XOR pattern) is dropped by every univariate filter.
  • χ2\chi^2 needs non-negative inputs (counts, one-hot columns, frequencies); it fails on standardised features.
  • The number kk is a hyperparameter: tune it with cross-validation like any other, inside the pipeline.
  • Variance depends on the unit: a threshold on raw variance treats millimetres and kilometres differently. Apply it to scaled data or use it only for (near-)constant columns.

Practice

  1. Why does the U-shaped feature have an ANOVA FF near zero?
Answer

FF compares the class means. Class 1 contains both large positive and large negative values of x1x_1, so its mean is close to 0, like the mean of class 0. The classes differ in spread, not in mean.

  1. In the leakage example, would the honest score improve if you raised kk from 20 to 200?
Answer

No. The features are pure noise, so any honest procedure stays around 0.5 accuracy on average. Only the leaky procedure "improves", because with more selected features it can fit the chance patterns of the rows it saw.

Test yourself

What does a filter method use to rank features?

  1. The final model's accuracy on subsets
  2. A statistic computed for each feature separately, such as correlation or mutual information
  3. The model's coefficients during training
  4. Random choice

The label depends on the square of a feature. Which score will notice it?

  1. Pearson correlation
  2. ANOVA FF
  3. Mutual information
  4. Variance

Which input does the χ2\chi^2 filter require?

  1. Standardised features
  2. Non-negative values such as counts or one-hot columns
  3. Text
  4. Exactly two features

Why must SelectKBest be inside the pipeline that is cross-validated?

  1. It is faster
  2. It uses the labels, so fitting it on all rows lets test labels choose the features
  3. Pipelines require it
  4. It needs scaled data