Sign in

Feature selection

Feature selection (filter methods)

Scores every input column by how much it tells about the target and keeps the best few, without training a model.

Overview

Not every column helps. Some are constant, some are noise, and some repeat what another column already says. Extra columns cost training time and give the model more ways to fit noise. A filter method gives each column a score computed from the data alone, then keeps the columns with the highest scores. The scores differ in what kind of relation they can see. Correlation sees straight-line relations, the F statistic sees differences between class means, and mutual information sees any dependence at all.

A short history

Choosing variables has been part of regression since stepwise procedures in the 1960s. The scores used by filter methods are older statistics: Karl Pearson's correlation, Ronald Fisher's F statistic, and mutual information from Claude Shannon's 1948 theory. The topic was organised for machine learning by Isabelle Guyon and Andre Elisseeff in a 2003 survey that set out the split into filter, wrapper and embedded methods.

How it works

  1. Choose a method: variance needs no target, correlation suits a numeric target, f_classif suits class labels, and mutual_info suits either.
  2. Call fit with the training table and target. It computes one score per column and stores them in scores_.
  3. For variance, every column whose variance is above variance_threshold is kept.
  4. For the other methods, the columns are walked from the best score to the worst and taken until k are chosen.
  5. If max_redundancy is below 1, a column is skipped when its absolute correlation with an already chosen column is above that value.
  6. transform returns only the chosen columns, in their original order. support gives the same choice as a true or false mask.

Watch out for

  • Each column is scored alone. Two columns that are useless one at a time but informative together, as in an exclusive-or pattern, both get a low score and are dropped.
  • Selecting columns on the full table before splitting or cross-validating leaks the test targets into the choice. Fit the selector inside each training fold.
  • With thousands of columns, some pure-noise columns score well by chance. A high score among many candidates is weaker evidence than it looks.
  • Correlation and the F statistic see only linear relations and shifts in the mean. A column related to the target through a curve can score near zero.
  • Mutual information here is estimated from bins. With few rows or many bins the estimate is biased upward, so noise columns get a positive score.

Use cases

When to use it

When a table has many more columns than the model needs, as a fast first cut before training. It is also a quick way to see which columns carry signal.

In industry

Genomics
Studies with thousands of gene expression columns and few patients use filter scores to shortlist genes before fitting a classifier.
Text classification
Spam and topic classifiers keep the words with the highest mutual information or similar scores with the label, and drop the rest.
Credit and risk modelling
Modellers remove near-constant and highly correlated columns so scorecards stay stable and explainable.

Choosing it: what must hold

  • A target column for the supervised scores. Variance filtering works without one.
  • Scores computed on the training data only, inside each cross-validation fold.
  • Acceptance that each column is scored alone, so features that only help in combination can be missed.
  • A score matched to the data: correlation for numeric targets, F statistic for class labels, mutual information for nonlinear links.

When to choose something else

IfUse instead
Features matter only in combinationA wrapper or model-based method, such as importance from a Random Forest or XGBoost
You fit a linear model and want selection during trainingL1 regularisation (lasso)
You want fewer dimensions but need not keep the original columnsPCA

Math foundations

  1. Variance

    Var⁡(xj)=1n∑i=1n(xij−xˉj)2\operatorname{Var}(x_j) = \frac{1}{n} \sum_{i=1}^{n} (x_{ij} - \bar{x}_j)^2

    A column that barely changes cannot explain a target that does. A variance of exactly zero means the column is constant. The score depends on the units of the column.

  2. Pearson correlation

    rj=∑i(xij−xˉj)(yi−yˉ)∑i(xij−xˉj)2 ∑i(yi−yˉ)2r_j = \frac{\sum_i (x_{ij} - \bar{x}_j)(y_i - \bar{y})}{\sqrt{\sum_i (x_{ij} - \bar{x}_j)^2}\ \sqrt{\sum_i (y_i - \bar{y})^2}}

    It measures how well a straight line relates the column to the target, from −1-1 to 11. The score is ∣rj∣\lvert r_j \rvert, since a strong negative relation is as useful as a positive one.

  3. The ANOVA F statistic

    F=∑cnc (xˉc−xˉ)2 / (C−1)∑c∑i∈c(xi−xˉc)2 / (n−C)F = \frac{\sum_{c} n_c\,(\bar{x}_c - \bar{x})^2 \,/\, (C - 1)}{\sum_{c} \sum_{i \in c} (x_i - \bar{x}_c)^2 \,/\, (n - C)}

    The spread of the class means around the overall mean, divided by the spread of values inside the classes. It is large when the classes sit far apart compared with their own width.

  4. Mutual information

    I(X;Y)=∑a∑bp(a,b) ln⁡p(a,b)p(a) p(b)I(X; Y) = \sum_{a} \sum_{b} p(a, b)\, \ln \frac{p(a, b)}{p(a)\,p(b)}

    How much knowing the binned column reduces uncertainty about the target, in nats. It is zero exactly when the two are independent, and it sees relations of any shape.

  5. The redundancy check

    max⁡s∈S∣r(xj,xs)∣>ρ ⇒ skip j\max_{s \in S} \lvert r(x_j, x_s) \rvert > \rho \ \Rightarrow\ \text{skip } j

    A candidate that is nearly a copy of an already chosen column adds little. It is skipped so the kk places go to columns that say something new.

Symbols

xijx_{ij}
the value of column j in row i
yiy_i
the target of row i
xˉj, yˉ\bar{x}_j,\ \bar{y}
the means of column j and of the target
n, Cn,\ C
the number of rows and the number of classes
nc, xˉcn_c,\ \bar{x}_c
the number of rows in class c and the column's mean within that class
rjr_j
the Pearson correlation of column j with the target
p(a,b)p(a, b)
the share of rows with column bin a and target bin b
p(a), p(b)p(a),\ p(b)
the shares of rows in column bin a and in target bin b
S, ρS,\ \rho
the set of columns chosen so far and the max_redundancy setting

Worked by hand

One column, two classes. Class A holds the values 1, 2, 3 and class B holds 5, 6, 7. Compute the F statistic with n=6n = 6 and C=2C = 2.

xˉA=2,xˉB=6,xˉ=4\bar{x}_A = 2, \quad \bar{x}_B = 6, \quad \bar{x} = 4
between=3 (2−4)2+3 (6−4)2=24\text{between} = 3\,(2 - 4)^2 + 3\,(6 - 4)^2 = 24
within=(1+0+1)+(1+0+1)=4\text{within} = (1 + 0 + 1) + (1 + 0 + 1) = 4
F=24/(2−1)4/(6−2)=241=24F = \frac{24 / (2 - 1)}{4 / (6 - 2)} = \frac{24}{1} = 24

F is 24. The class means are 4 apart while values inside a class vary by about 1, so this column separates the classes well.

Visual example

Loading the example.

Try this

  • With f_classif, lower max_redundancy to 0.9: the copy column is skipped because it repeats what strong already says.
  • Inspect the ends column, then switch between f_classif and mutual_info. The class means are equal, so F is near zero, but mutual information sees it.
  • Choose variance and raise the threshold: it removes the flat column without ever looking at the target.

Code sample

import numpy as np
from impl import FeatureSelector
from config import FeatureSelectorConfig

rng = np.random.default_rng(0)
y = rng.integers(0, 2, size=300)
X = rng.normal(size=(300, 6))
X[:, 2] += 2.0 * y                        # only column 2 depends on the class
sel = FeatureSelector(FeatureSelectorConfig(method="f_classif", k=1)).fit(X, y)
print(sel.selected_)                      # [2]
X_small = sel.transform(X)                # shape (300, 1)
Read the implementation (141 lines)
"""Filter feature selection: variance threshold, correlation, ANOVA F and mutual information scores.

NumPy only. Each column gets a relevance score computed from the training data; the best `k` are kept,
optionally skipping columns that nearly repeat a better one. The scoring functions are public, so they can be
used on their own.
"""
from __future__ import annotations

import numpy as np

try:
    from .config import FeatureSelectorConfig
except ImportError:  # run from the template's own folder
    from config import FeatureSelectorConfig


def correlation_scores(X: np.ndarray, y: np.ndarray) -> np.ndarray:
    """Absolute Pearson correlation of every column with y. X: (n, d), y: (n,). Returns (d,); 0 for constants."""
    Xc = X - X.mean(axis=0)
    yc = y - y.mean()
    denom = np.sqrt((Xc**2).sum(axis=0) * (yc**2).sum())
    return np.abs(np.divide(Xc.T @ yc, denom, out=np.zeros(X.shape[1]), where=denom > 0))


def f_classif_scores(X: np.ndarray, y: np.ndarray) -> np.ndarray:
    """One-way ANOVA F statistic of every column across the classes in y. X: (n, d), y: (n,). Returns (d,).

    F = (between-class sum of squares / (c - 1)) / (within-class sum of squares / (n - c)).
    """
    classes = np.unique(y)
    n, c = X.shape[0], len(classes)
    if c < 2 or n <= c:
        raise ValueError("f_classif needs at least two classes and more rows than classes")
    grand = X.mean(axis=0)
    between = np.zeros(X.shape[1])
    within = np.zeros(X.shape[1])
    for cls in classes:
        rows = X[y == cls]
        mean = rows.mean(axis=0)
        between += rows.shape[0] * (mean - grand) ** 2
        within += ((rows - mean) ** 2).sum(axis=0)
    ms_between, ms_within = between / (c - 1), within / (n - c)
    perfect = np.where(ms_between > 0, np.inf, 0.0)  # zero within-class spread
    return np.divide(ms_between, ms_within, out=perfect, where=ms_within > 0)


def _discretise(v: np.ndarray, n_bins: int) -> np.ndarray:
    """Integer codes for a 1-D array: its distinct values when there are at most n_bins, else quantile bins."""
    unique, codes = np.unique(v, return_inverse=True)
    if len(unique) <= n_bins:
        return codes
    edges = np.unique(np.quantile(v, np.linspace(0.0, 1.0, n_bins + 1)[1:-1]))
    return np.searchsorted(edges, v, side="right")


def mutual_information(a: np.ndarray, b: np.ndarray) -> float:
    """Mutual information in nats between two integer-coded 1-D arrays of equal length."""
    joint = np.zeros((a.max() + 1, b.max() + 1))
    np.add.at(joint, (a, b), 1.0)
    joint /= joint.sum()
    outer = joint.sum(axis=1, keepdims=True) @ joint.sum(axis=0, keepdims=True)
    nz = joint > 0
    return float((joint[nz] * np.log(joint[nz] / outer[nz])).sum())


def mutual_info_scores(X: np.ndarray, y: np.ndarray, n_bins: int = 10) -> np.ndarray:
    """Mutual information (nats) of every binned column with the binned target. X: (n, d), y: (n,)."""
    y_codes = _discretise(y, n_bins)
    return np.array([mutual_information(_discretise(X[:, j], n_bins), y_codes) for j in range(X.shape[1])])


class FeatureSelector:
    """Keeps the most relevant columns.

    After `fit`: `scores_` (n_features,) holds the score of every column and `selected_` the sorted indices
    of the columns kept.
    """

    def __init__(self, config: FeatureSelectorConfig | None = None) -> None:
        self.config = config or FeatureSelectorConfig()
        self.scores_: np.ndarray | None = None
        self.selected_: np.ndarray | None = None

    def fit(self, X, y=None) -> "FeatureSelector":
        """Score the columns of X, shape (n_samples, n_features), against y, shape (n_samples,)."""
        X = np.asarray(X, dtype=float)
        if X.ndim != 2:
            raise ValueError("X must be 2-D: (n_samples, n_features)")
        method = self.config.method
        if method == "variance":
            self.scores_ = X.var(axis=0)
            self.selected_ = np.flatnonzero(self.scores_ > self.config.variance_threshold)
            return self
        if y is None:
            raise ValueError(f"{method} needs the target y")
        y = np.asarray(y)
        if y.shape[0] != X.shape[0]:
            raise ValueError(f"y has {y.shape[0]} rows, X has {X.shape[0]}")
        if method == "correlation":
            self.scores_ = correlation_scores(X, y.astype(float))
        elif method == "f_classif":
            self.scores_ = f_classif_scores(X, y)
        else:
            self.scores_ = mutual_info_scores(X, y, self.config.n_bins)
        self.selected_ = np.sort(self._pick(X))
        return self

    def _pick(self, X: np.ndarray) -> list[int]:
        """Walk the columns from best to worst score and take up to k, skipping near-copies of chosen ones."""
        order = np.argsort(-np.nan_to_num(self.scores_, nan=-np.inf, posinf=np.finfo(float).max), kind="stable")
        chosen: list[int] = []
        check = self.config.max_redundancy < 1.0
        for j in order:
            if len(chosen) == self.config.k:
                break
            if check and chosen:
                if correlation_scores(X[:, chosen], X[:, j]).max() > self.config.max_redundancy:
                    continue
            chosen.append(int(j))
        return chosen

    def transform(self, X) -> np.ndarray:
        """Return only the selected columns of X: (n_samples, n_selected)."""
        if self.selected_ is None:
            raise RuntimeError("call fit before transform")
        X = np.asarray(X, dtype=float)
        if X.ndim != 2 or X.shape[1] != self.scores_.shape[0]:
            raise ValueError(f"X must have {self.scores_.shape[0]} columns")
        return X[:, self.selected_]

    def fit_transform(self, X, y=None) -> np.ndarray:
        """Fit on (X, y) and return the selected columns of X."""
        return self.fit(X, y).transform(X)

    def support(self) -> np.ndarray:
        """Boolean mask (n_features,): True for the selected columns."""
        if self.selected_ is None:
            raise RuntimeError("call fit before support")
        mask = np.zeros(self.scores_.shape[0], dtype=bool)
        mask[self.selected_] = True
        return mask
Repository
Not published yet
Needs
Python 3.10 and NumPy
Tests
8, run with python3 -m unittest -v

Practice

Build a table of 500 rows and 20 columns in which only 3 columns drive a two-class target and one more column is a near copy of one of those 3. Fit a FeatureSelector with method f_classif and k set to 4 through FeatureSelectorConfig and print selected_ and scores_. Then set max_redundancy to 0.9 and see which column leaves. Compare with f_classif_scores and mutual_info_scores called directly.

Check on learning

  1. The target is 1 when exactly one of two 0 or 1 columns is 1. What score does each column get from correlation and from mutual information, and what does that reveal about filter methods?
    A way to think about it

    Tabulate the four combinations. Look at the target's average for each value of one column alone. Then ask what a score for a pair of columns would show.

  2. You select the best 20 of 5000 columns on all the data, then cross-validate a model on those 20 and get a high score, even though the target is random. How is that possible?
    A way to think about it

    The selection already saw every target value, including those of the validation folds. Think about what the 20 luckiest noise columns look like.

  3. A column has a perfect U-shaped relation with a numeric target. Which of the four methods would keep it, and which would not?
    A way to think about it

    Draw the U and fit a straight line through it. Then ask whether knowing the bin of the column narrows down the target.

  4. Why might you prefer to keep two highly correlated columns in some cases, even though the redundancy check would remove one?
    A way to think about it

    Consider measurement noise. Averaging two noisy readings of the same thing is more precise than either one.