Sign in

Feature engineering

Builds new input columns from existing ones: polynomial and interaction terms, bins, date parts, lags and rolling means.

Overview

A model can only use the information in the form it is given. A linear model cannot discover that price depends on length times width unless a column holds that product. A raw date is one long number, but the weekday inside it may be what matters. Feature engineering rewrites the raw columns into forms that make the useful pattern easy to pick up. Each tool here does one such rewrite. None of them adds information that was not in the data: they only expose it.

A short history

Building inputs by hand is as old as statistical modelling: polynomial terms were fitted in the 1800s, and economists have used lagged variables for about a century. The name became common in the 2000s, when machine learning competitions showed that well-chosen features often mattered more than the choice of model. Deep learning later automated much of it for images, audio and text, but it remains central for tabular data.

How it works

  1. FeatureEngineer.fit fixes the list of polynomial terms for the given number of columns and degree, and stores the exponents in powers_.
  2. With interaction_only on, only products of different columns are kept, such as x0x1x_0 x_1, and powers such as x02x_0^2 are left out.
  3. If n_bins is 2 or more, fit also learns the bin edges per column from the training data, by quantiles or by equal width.
  4. transform computes every term as a product of column powers, then appends one bin-index column per input column.
  5. date_parts splits each date into year, month, day, weekday, day of year and a weekend flag, plus sine and cosine pairs for month and weekday.
  6. lag_features and rolling_mean build columns from earlier values of an ordered series, using only the past.
  7. safe_ratio divides two columns and writes a fill value wherever the divisor is zero.

Watch out for

  • The number of polynomial terms grows very fast with the degree and the column count. Many terms on few rows lets the model fit noise.
  • Powers of unscaled columns span huge ranges, and xx and x2x^2 are strongly correlated. Scale the inputs first, or training becomes numerically unstable.
  • Bin edges, like any learned quantity, must come from the training split. Edges learned on all rows leak the test distribution.
  • A lag or rolling feature that includes the current or a future value leaks the target. The functions here use only earlier values, so keep the rows in time order before calling them.
  • Lags and rolling means are NaN at the start of the series, where no past exists. Those rows must be dropped or filled before training.

Use cases

When to use it

When a simple model underfits because the relation is curved or depends on a combination of columns, and for any table with dates or time-ordered measurements.

In industry

Fraud detection
Card fraud models use engineered counts and sums, such as the number of transactions on a card in the last hour, beside the raw transaction.
Demand forecasting
Retail and energy forecasters add day of week, holiday flags, lags and rolling means so a model can see seasonality.
Credit scoring
Lenders bin continuous variables such as age and income, and build ratios such as debt to income, for scorecards.

Choosing it: what must hold

  • An understanding of the domain, or an exploration of the data, that suggests which combinations matter.
  • Features computed only from information available at prediction time. Lags and rolling means must not look into the future.
  • Any fitted parts, such as bin edges, learned on the training data only.
  • A way to validate that each new feature helps, since every added column also adds noise.

When to choose something else

IfUse instead
The inputs are images, audio or text with plenty of dataA deep network that learns its own features, such as a CNN or Transformer
You already have too many columnsFeature selection, or PCA
The model is a boosted tree and the relation is a simple threshold or interactionRaw columns, since trees find splits and interactions themselves

Math foundations

  1. A polynomial term

    ϕt(x)=∏j=1dxj ptj,∑j=1dptj≤D\phi_t(x) = \prod_{j=1}^{d} x_j^{\,p_{tj}}, \qquad \sum_{j=1}^{d} p_{tj} \le D

    Each new column is a product of input columns raised to whole-number exponents. Row tt of powers_ holds the exponents, and their sum is the degree of the term.

  2. How many terms

    N(d,D)=(d+DD)−1N(d, D) = \binom{d + D}{D} - 1

    The number of terms of degree 1 to DD in dd columns, without the constant column. It grows roughly like dD/D!d^D / D!, which is why high degrees are expensive.

  3. Interactions only

    Nint(d,D)=∑k=1D(dk)N_{\text{int}}(d, D) = \sum_{k=1}^{D} \binom{d}{k}

    When only products of distinct columns are allowed, a term of degree kk is a choice of kk different columns.

  4. Cyclic encoding

    (sin⁡2πvP, cos⁡2πvP)\big(\sin\tfrac{2\pi v}{P},\ \cos\tfrac{2\pi v}{P}\big)

    A value vv on a cycle of length PP is placed on a circle. The last value of the cycle then sits next to the first, as December sits next to January. For months the template uses v=month−1v = \text{month} - 1 and P=12P = 12.

  5. Lag and rolling mean

    ℓt(s)=xt−s,rt=1w∑i=1wxt−i\ell_t^{(s)} = x_{t-s}, \qquad r_t = \frac{1}{w} \sum_{i=1}^{w} x_{t-i}

    A lag copies the value from ss steps ago. The rolling mean averages the previous ww values. Both sums start at i=1i = 1, so the current value is never used.

Symbols

xjx_j
the value of input column j in one row
dd
the number of input columns
DD
the degree setting
ptjp_{tj}
the exponent of column j in term t (one entry of powers_)
ϕt\phi_t
output term t
N, NintN,\ N_{\text{int}}
the number of output terms, in full and with interaction_only
v, Pv,\ P
a position on a cycle and the length of the cycle
xtx_t
the value of an ordered series at time t
s, ws,\ w
the lag and the rolling window length

Worked by hand

Count the terms for d=3d = 3 columns and degree D=2D = 2. Then compare December and January, as the raw month number and on the circle. December has v=11v = 11 and January has v=0v = 0.

N(3,2)=(52)−1=10−1=9N(3, 2) = \binom{5}{2} - 1 = 10 - 1 = 9
Dec=(sin⁡22π12, cos⁡22π12)=(−0.5, 0.866),Jan=(0, 1)\text{Dec} = \big(\sin\tfrac{22\pi}{12},\ \cos\tfrac{22\pi}{12}\big) = (-0.5,\ 0.866), \qquad \text{Jan} = (0,\ 1)
(−0.5−0)2+(0.866−1)2=0.268≈0.52\sqrt{(-0.5 - 0)^2 + (0.866 - 1)^2} = \sqrt{0.268} \approx 0.52

Nine terms: three of degree 1 and six of degree 2. As month numbers, December and January are 11 apart. On the circle they are 0.52 apart, the same as any two neighbouring months.

Visual example

Loading the example.

Try this

  • Lower the degree D to 1: the model has only x0 and x1, and its predictions bend away from the line.
  • At degree 2, press the x0*x1 term to take it away from the model, then put it back.
  • Turn interaction_only on and compare the number of terms with the formula in the readout.

Code sample

import numpy as np
from impl import FeatureEngineer, date_parts, lag_features
from config import FeatureEngineerConfig

X = np.array([[1.0, 2.0], [3.0, 4.0], [5.0, 6.0]])
fe = FeatureEngineer(FeatureEngineerConfig(degree=2)).fit(X)
print(fe.feature_names())       # ['x0', 'x1', 'x0^2', 'x0*x1', 'x1^2']
print(fe.transform(X)[0])       # [1. 2. 1. 2. 4.]
print(date_parts(["2024-03-05"])[0, :4])            # [2024. 3. 5. 1.]  (a Tuesday)
print(lag_features([10.0, 11.0, 12.0], [1])[:, 0])  # [nan 10. 11.]
Read the implementation (145 lines)
"""Feature engineering: polynomial and interaction terms, binning, date parts, lags and rolling means.

Standard library and NumPy only. `FeatureEngineer` expands a numeric table with polynomial terms and optional
bin indices (bin edges are learned on the training data). The module functions derive features from dates
and from ordered series.
"""
from __future__ import annotations

import math
from datetime import date, datetime
from itertools import combinations, combinations_with_replacement

import numpy as np

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

DATE_PART_NAMES = ("year", "month", "day", "weekday", "day_of_year", "is_weekend",
                   "month_sin", "month_cos", "weekday_sin", "weekday_cos")


def date_parts(dates) -> np.ndarray:
    """Split dates into numeric parts. dates: n ISO strings ("2024-03-05") or date / datetime objects.

    Returns shape (n, 10) with the columns of `DATE_PART_NAMES`. weekday is 0 for Monday. The sin / cos pairs
    place month and weekday on a circle, so December is next to January and Sunday next to Monday.
    """
    rows = []
    for value in dates:
        d = value if isinstance(value, (date, datetime)) else datetime.fromisoformat(str(value))
        weekday = d.weekday()
        rows.append([
            d.year, d.month, d.day, weekday, d.timetuple().tm_yday, float(weekday >= 5),
            math.sin(2 * math.pi * (d.month - 1) / 12), math.cos(2 * math.pi * (d.month - 1) / 12),
            math.sin(2 * math.pi * weekday / 7), math.cos(2 * math.pi * weekday / 7),
        ])
    return np.array(rows, dtype=float).reshape(-1, len(DATE_PART_NAMES))


def lag_features(series, lags) -> np.ndarray:
    """Past values of an ordered series. series: (n,). lags: positive ints.

    Returns (n, len(lags)); column j holds series shifted by lags[j] steps, NaN where no past value exists.
    """
    series = np.asarray(series, dtype=float)
    out = np.full((series.shape[0], len(lags)), np.nan)
    for j, lag in enumerate(lags):
        if lag < 1:
            raise ValueError("lags must be positive, a lag of 0 or less would leak the present or the future")
        out[lag:, j] = series[:-lag] if lag < len(series) else []
    return out


def rolling_mean(series, window: int) -> np.ndarray:
    """Mean of the previous `window` values, excluding the current one. series: (n,). Returns (n,).

    NaN for the first `window` positions. Excluding the current value keeps the feature free of leakage when
    the series itself is the prediction target.
    """
    if window < 1:
        raise ValueError("window must be at least 1")
    series = np.asarray(series, dtype=float)
    out = np.full(series.shape[0], np.nan)
    if series.shape[0] > window:
        total = np.concatenate([[0.0], np.cumsum(series)])
        out[window:] = (total[window:-1] - total[:-window - 1]) / window
    return out


def safe_ratio(a, b, fill: float = 0.0) -> np.ndarray:
    """Element-wise a / b with `fill` where b is 0. a, b: arrays of the same shape."""
    a, b = np.asarray(a, dtype=float), np.asarray(b, dtype=float)
    return np.divide(a, b, out=np.full(np.broadcast(a, b).shape, float(fill)), where=b != 0)


class FeatureEngineer:
    """Polynomial expansion plus optional binning.

    After `fit`: `powers_` is an int array (n_terms, n_features) with the exponent of every input column in
    every output term, and `bin_edges_` a list of inner bin edges per column (when `n_bins` is on).
    """

    def __init__(self, config: FeatureEngineerConfig | None = None) -> None:
        self.config = config or FeatureEngineerConfig()
        self.powers_: np.ndarray | None = None
        self.bin_edges_: list[np.ndarray] | None = None

    def fit(self, X) -> "FeatureEngineer":
        """Fix the list of terms for X, shape (n_samples, n_features), and learn the bin edges."""
        X = np.asarray(X, dtype=float)
        if X.ndim != 2:
            raise ValueError("X must be 2-D: (n_samples, n_features)")
        d = X.shape[1]
        pick = combinations if self.config.interaction_only else combinations_with_replacement
        terms = [()] if self.config.include_bias else []
        for degree in range(1, self.config.degree + 1):
            terms.extend(pick(range(d), degree))
        powers = np.zeros((len(terms), d), dtype=int)
        for t, columns in enumerate(terms):
            for c in columns:
                powers[t, c] += 1
        self.powers_ = powers
        self.bin_edges_ = None
        if self.config.n_bins:
            inner = np.linspace(0.0, 1.0, self.config.n_bins + 1)[1:-1]
            if self.config.bin_strategy == "quantile":
                self.bin_edges_ = [np.quantile(X[:, j], inner) for j in range(d)]
            else:
                self.bin_edges_ = [X[:, j].min() + inner * (X[:, j].max() - X[:, j].min()) for j in range(d)]
        return self

    def transform(self, X) -> np.ndarray:
        """Return the engineered table: polynomial terms, then one bin-index column per input column.

        X: (n_samples, n_features). Output: (n_samples, n_terms [+ n_features]).
        """
        if self.powers_ is None:
            raise RuntimeError("call fit before transform")
        X = np.asarray(X, dtype=float)
        if X.ndim != 2 or X.shape[1] != self.powers_.shape[1]:
            raise ValueError(f"X must have {self.powers_.shape[1]} columns")
        columns = [np.prod(X ** p, axis=1) for p in self.powers_]
        if self.bin_edges_ is not None:
            columns += [np.searchsorted(edges, X[:, j], side="right").astype(float)
                        for j, edges in enumerate(self.bin_edges_)]
        return np.column_stack(columns) if columns else np.empty((X.shape[0], 0))

    def fit_transform(self, X) -> np.ndarray:
        """Fit on X and return the engineered X."""
        return self.fit(X).transform(X)

    def feature_names(self, names=None) -> list[str]:
        """Readable name of every output column, for example ["x0", "x1", "x0^2", "x0*x1", "x1^2"]."""
        if self.powers_ is None:
            raise RuntimeError("call fit before feature_names")
        names = list(names) if names is not None else [f"x{j}" for j in range(self.powers_.shape[1])]
        out = []
        for p in self.powers_:
            parts = [n if e == 1 else f"{n}^{e}" for n, e in zip(names, p) if e > 0]
            out.append("*".join(parts) if parts else "1")
        if self.bin_edges_ is not None:
            out += [f"{n}_bin" for n in names]
        return out
Repository
Not published yet
Needs
Python 3.10 and NumPy
Tests
8, run with python3 -m unittest -v

Practice

Generate 300 rows with two columns and a target y=3x0x1+noisey = 3 x_0 x_1 + \text{noise}. Fit a plain least-squares line on the raw columns and note the error. Then run FeatureEngineer with degree 2 through FeatureEngineerConfig, print feature_names, and fit again. Switch on interaction_only and compare the column count. Finally call rolling_mean and lag_features on a short series and locate the NaN entries.

Check on learning

  1. A tree model and a linear model get the same extra column x0x1x_0 x_1. Which one gains more from it, and why?
    A way to think about it

    Ask what each model can build on its own. A tree can split on one column and then the other. A linear model can only add weighted columns.

  2. With 50 columns and degree 3 the expansion has more than 20000 terms. If you have 1000 rows, what will happen when a linear model is fitted, and what could you do instead?
    A way to think about it

    Compare the number of unknown weights with the number of equations. Then think about interaction_only, a lower degree, or selecting columns first.

  3. Why does the month need both a sine and a cosine? What goes wrong with the sine alone?
    A way to think about it

    Evaluate the sine for two different months that sit at the same height on the circle. One coordinate cannot tell them apart.

  4. You predict tomorrow's sales and add a 7-day rolling mean that includes today's sales. Training error drops sharply but live error does not. What happened?
    A way to think about it

    Check what is known at the moment the prediction is made. Compare that with what the training rows were given.