Sign in

Feature engineering

A feature builder that derives new columns from numeric ones: log transforms, polynomial and interaction terms, bin indices, lags and rolling means.

Overview

A linear model can only add up its inputs, each times a weight. If the truth bends, or depends on two inputs together, the model cannot follow unless you hand it the bend as a column of its own. Feature engineering does that: it adds squares and products, squeezes long-tailed columns with a logarithm, cuts ranges into coarse bins, and for time series supplies earlier values and moving averages. The model stays simple and the new columns carry the shape.

A short history

Feature engineering has no single origin. Statisticians transformed variables long before machine learning: George Box and David Cox published their family of power transformations in 1964, and polynomial and interaction terms are standard in regression. Lagged values come from time series analysis, formalised by Box and Jenkins in 1970. Hand-built features decided many prediction competitions in the 2000s and 2010s, and they remain central for tabular data even though deep networks learn features for images and text.

How it works

  1. Replace each column listed in log_columns by ln⁡(1+x)\ln(1 + x). This compresses large values and keeps zero at zero.
  2. Build every product of columns up to total degree degree. With interaction_only, keep only products of distinct columns.
  3. If n_bins is above zero, learn bin edges per column in fit, by quantiles (equal counts) or uniformly (equal widths).
  4. In transform, compute the same terms for new rows and append one bin index per column using the stored edges.
  5. For a time series, call lag_features to place earlier values beside the current one and rolling_mean for a moving average. Rows without enough history hold NaN.
  6. Call feature_names to label every output column.

Watch out for

  • The number of polynomial terms grows very fast with the degree and the number of columns, so a high degree makes a huge table and an overfitted model. Keep the degree at 2 or 3.
  • Powers of unscaled columns can be enormous (a value of 1,000 cubed is a billion), which makes the fit numerically unstable. Scale before or after building the terms.
  • The log transform needs values above −1-1, and the template raises an error otherwise.
  • Lags and rolling means must use only the past. Computing them after a random shuffle, or with a window that includes future rows, leaks the answer into the features.
  • Bin edges come from the training data, so new values beyond the training range all land in the first or last bin.

Use cases

When to use it

When a linear or other simple model needs curvature or interactions it cannot learn alone, when a skewed positive column should be compressed, or when a forecasting model needs past values as inputs.

In industry

Demand forecasting
Retailers add lagged sales and rolling means over recent weeks as input columns, so a regression or tree model can see trend and seasonality.
Credit risk
Lenders bin income and age into bands and add ratios such as debt to income, which makes a logistic regression scorecard both stronger and easier to explain.
Web analytics
Counts such as page views are heavily skewed. A log transform compresses the long tail so that a few heavy users do not dominate a linear model.

Choosing it: what must hold

  • Numeric input columns, already cleaned of missing values.
  • A simple model, such as linear or logistic regression, that cannot learn curvature or interactions without help.
  • For lags and rolling means, rows in time order and features that use only past values.
  • Enough rows to support the added columns, since polynomial terms grow quickly with the degree.

When to choose something else

IfUse instead
You would rather have the model find interactions itselfA tree ensemble such as Random Forest, XGBoost or LightGBM
The inputs are images, audio or raw textA network that learns its own features, such as a CNN or a Transformer
There are too many features and you want fewer, not morePCA or an Autoencoder

Math foundations

  1. Log transform

    x′=ln⁡(1+x)x' = \ln(1 + x)

    Turns multiplication into addition: going from 10 to 100 moves x′x' about as far as going from 100 to 1,000. Adding 1 keeps x=0x = 0 at x′=0x' = 0.

  2. A polynomial term

    ϕp(x)=∏j=1nxj pj,1≤∑j=1npj≤d\phi_{p}(x) = \prod_{j=1}^{n} x_j^{\,p_j}, \qquad 1 \le \sum_{j=1}^{n} p_j \le d

    Each output column is a product of input columns raised to whole-number powers. The powers of one term add up to at most the degree dd. The fitted powers_ array stores one row of exponents per term.

  3. How many terms

    #terms=(n+dd)−1\#\text{terms} = \binom{n + d}{d} - 1

    The count of all terms of degree 1 to dd in nn columns, without the constant column. This is the number that explodes when dd or nn grows.

  4. Uniform bin edges and the bin index

    ek=xmin⁡+kB (xmax⁡−xmin⁡),k=1,…,B−1,bin⁡(x)=#{k:ek≤x}e_k = x_{\min} + \frac{k}{B}\,(x_{\max} - x_{\min}), \quad k = 1, \dots, B - 1, \qquad \operatorname{bin}(x) = \#\{k : e_k \le x\}

    The training range is cut into BB equal widths. The index of a value is the number of edges at or below it, from 0 to B−1B - 1. The quantile strategy places the edges at equal shares of the data instead.

  5. Lag feature

    ℓk(t)=xt−k\ell_k(t) = x_{t-k}

    The value kk steps earlier, placed in the row for time tt. It lets a model that sees one row at a time use the recent past.

  6. Rolling mean

    xˉt(w)=1w∑i=0w−1xt−i\bar{x}_t^{(w)} = \frac{1}{w} \sum_{i=0}^{w-1} x_{t-i}

    The average of the current value and the w−1w - 1 values before it. It smooths noise and shows the local level of the series.

Symbols

xjx_j
value of input column j in one row
nn
number of input columns
dd
degree, the highest total power
pjp_j
power of column j in one term
BB
n_bins, the number of bins
eke_k
the k-th inner bin edge
xmin⁡, xmax⁡x_{\min},\, x_{\max}
smallest and largest training value of the column
xtx_t
value of a series at time t
kk
lag, a number of steps into the past
ww
window length of the rolling mean

Worked by hand

Take one row with x0=1x_0 = 1 and x1=2x_1 = 2 and degree 2. Then count the terms for 10 columns at degree 3, and take a rolling mean of the series 1, 2, 3, 4 with w=2w = 2.

(x0,  x1,  x02,  x0x1,  x12)=(1,  2,  1,  2,  4)(x_0,\; x_1,\; x_0^2,\; x_0 x_1,\; x_1^2) = (1,\; 2,\; 1,\; 2,\; 4)
(2+22)−1=6−1=5\binom{2 + 2}{2} - 1 = 6 - 1 = 5
(10+33)−1=286−1=285\binom{10 + 3}{3} - 1 = 286 - 1 = 285
xˉ2(2)=1+22=1.5,xˉ3(2)=2+32=2.5,xˉ4(2)=3+42=3.5\bar{x}_2^{(2)} = \frac{1 + 2}{2} = 1.5, \quad \bar{x}_3^{(2)} = \frac{2 + 3}{2} = 2.5, \quad \bar{x}_4^{(2)} = \frac{3 + 4}{2} = 3.5

Two columns at degree 2 give 5 outputs. Ten columns at degree 3 already give 285. The rolling mean has no value for the first row, so the template puts NaN there.

Visual example

Loading the example.

Try this

  • Raise degree from 2 to 3 and count how many columns the same two inputs become.
  • Turn on log1p for x1, then move x1 from 2 to 60: the large value is compressed.
  • Set n_bins to 4 and click the Bin index stage to see the edges the row is compared with.

Code sample

import numpy as np
from impl import FeatureEngineer, lag_features, rolling_mean
from config import FeatureEngineeringConfig

X = np.array([[1.0, 2.0], [3.0, 4.0], [5.0, 6.0]])
fe = FeatureEngineer(FeatureEngineeringConfig(degree=2)).fit(X)
print(fe.feature_names(["a", "b"]))   # ['a', 'b', 'a^2', 'a*b', 'b^2']
print(fe.transform(X)[0])             # [1. 2. 1. 2. 4.]

series = np.array([1.0, 2.0, 3.0, 4.0])
print(lag_features(series, [1]).ravel())   # [nan  1.  2.  3.]
print(rolling_mean(series, 2))             # [nan 1.5 2.5 3.5]
Read the implementation (138 lines)
"""Feature engineering for a numeric table: log transform, polynomial and interaction terms, binning,
plus lag and rolling-mean features for a time series.

NumPy only. `FeatureEngineer.fit` learns what depends on the data (the bin edges), `transform` builds the
new columns, and `feature_names` says what each output column is.
"""
from __future__ import annotations

from itertools import combinations, combinations_with_replacement

import numpy as np

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


def lag_features(x, lags) -> np.ndarray:
    """Past values of a series as columns.

    x:    series, shape (n,).
    lags: positive integers. Column k holds x shifted down by lags[k], so row t holds x[t - lags[k]].
    Returns shape (n, len(lags)). Rows that would need values from before the start hold NaN.
    """
    x = np.asarray(x, dtype=float).reshape(-1)
    out = np.full((x.shape[0], len(lags)), np.nan)
    for k, lag in enumerate(lags):
        if lag < 1:
            raise ValueError(f"lags must be positive, got {lag}")
        if lag < x.shape[0]:
            out[lag:, k] = x[:-lag]
    return out


def rolling_mean(x, window: int) -> np.ndarray:
    """Mean of the current and the previous window - 1 values.

    x: series, shape (n,). Returns shape (n,), NaN for the first window - 1 rows.
    """
    x = np.asarray(x, dtype=float).reshape(-1)
    if window < 1:
        raise ValueError(f"window must be at least 1, got {window}")
    out = np.full(x.shape[0], np.nan)
    if window <= x.shape[0]:
        total = np.cumsum(np.concatenate([[0.0], x]))
        out[window - 1:] = (total[window:] - total[:-window]) / window
    return out


class FeatureEngineer:
    """Log transform, then polynomial terms, then one bin-index column per input column.

    After `fit`:
        powers_     int array (n_poly_outputs, n_columns): the exponent of each column in each polynomial term
        bin_edges_  list with one array of n_bins - 1 inner edges per column (empty list when binning is off)
    """

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

    def _log(self, X: np.ndarray) -> np.ndarray:
        """Copy of X with log(1 + x) applied to the configured columns."""
        X = np.array(X, dtype=float)
        if X.ndim != 2:
            raise ValueError(f"expected shape (n_rows, n_columns), got {X.shape}")
        for c in self.config.log_columns:
            if c >= X.shape[1]:
                raise ValueError(f"log column {c} does not exist, the table has {X.shape[1]} columns")
            if (X[:, c] <= -1.0).any():
                raise ValueError(f"column {c} has values at or below -1, log(1 + x) is undefined there")
            X[:, c] = np.log1p(X[:, c])
        return X

    def fit(self, X) -> "FeatureEngineer":
        """Learn the term list and the bin edges from X, shape (n_rows, n_columns)."""
        cfg = self.config
        X = self._log(X)
        n_cols = X.shape[1]
        pick = combinations if cfg.interaction_only else combinations_with_replacement
        terms: list[tuple[int, ...]] = [()] if cfg.include_bias else []
        for degree in range(1, cfg.degree + 1):
            terms.extend(pick(range(n_cols), degree))
        powers = np.zeros((len(terms), n_cols), dtype=int)
        for i, term in enumerate(terms):
            for column in term:
                powers[i, column] += 1
        self.powers_ = powers
        self.n_columns_ = n_cols

        self.bin_edges_ = []
        if cfg.n_bins:
            inner = np.arange(1, cfg.n_bins) / cfg.n_bins  # for 4 bins: 0.25, 0.5, 0.75
            for j in range(n_cols):
                if cfg.bin_strategy == "quantile":
                    edges = np.quantile(X[:, j], inner)
                else:
                    low, high = X[:, j].min(), X[:, j].max()
                    edges = low + inner * (high - low)
                self.bin_edges_.append(edges)
        return self

    def transform(self, X) -> np.ndarray:
        """Build the features for X, shape (n_rows, n_columns).

        Returns shape (n_rows, n_poly_outputs + n_bin_outputs): the polynomial terms in order of degree,
        then (when binning is on) one bin-index column per input column.
        """
        if self.powers_ is None:
            raise RuntimeError("call fit before transform")
        X = self._log(X)
        if X.shape[1] != self.n_columns_:
            raise ValueError(f"fitted on {self.n_columns_} columns, got {X.shape[1]}")
        columns = [np.prod(X ** power, axis=1) for power in self.powers_]
        for j, edges in enumerate(self.bin_edges_):
            # side="right": a value equal to an edge goes to the upper bin, values past the ends stay in the end bins
            columns.append(np.searchsorted(edges, X[:, j], side="right").astype(float))
        return np.stack(columns, axis=1) if columns else np.zeros((X.shape[0], 0))

    def fit_transform(self, X) -> np.ndarray:
        """`fit(X)` then `transform(X)`."""
        return self.fit(X).transform(X)

    def feature_names(self, names=None) -> list[str]:
        """Name of every output column, for example ["a", "b", "a^2", "a*b", "b^2", "bin(a)", "bin(b)"]."""
        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.n_columns_)]
        names = [f"log1p({n})" if j in self.config.log_columns else n for j, n in enumerate(names)]
        out = []
        for power in self.powers_:
            parts = [n if p == 1 else f"{n}^{p}" for n, p in zip(names, power) if p > 0]
            out.append("*".join(parts) if parts else "1")
        out.extend(f"bin({n})" for n in names[: len(self.bin_edges_)])
        return out
Repository
Not published yet
Needs
Python 3.10 and NumPy
Tests
8, run with python3 -m unittest -v

Practice

Fit FeatureEngineer(FeatureEngineeringConfig(degree=3)) on a table with 4 columns and compare transform(X).shape[1] with the term-count formula. Repeat with interaction_only=True, read feature_names(), and explain which terms disappeared.

Check on learning

  1. With degree 2 a linear model on the new features can fit a parabola. Is the model still linear? In what sense yes and in what sense no?
    A way to think about it

    Separate two things: how the prediction depends on the weights, and how it depends on the original inputs.

  2. You have 50 columns and are tempted to use degree 3. Estimate the number of features and predict what happens to training error and to validation error.
    A way to think about it

    Use the term-count formula, then compare the number of features with the number of rows you are likely to have.

  3. Why does ln⁡(1+x)\ln(1 + x) help with a column such as income or page views, and what would it do to a column that is already roughly symmetric?
    A way to think about it

    Sketch both histograms before and after. Look at what happens to the gap between the largest values and the bulk.

  4. A colleague builds a rolling mean with a window centred on the current row. The forecast scores very well offline and badly live. What went wrong?
    A way to think about it

    Write out which time steps enter the average for row tt. Ask which of them exist at the moment a real forecast is made.

  5. Quantile bins and uniform bins give different edges on a skewed column. Which bins end up nearly empty in each case, and why does that matter for a model?
    A way to think about it

    With equal widths, count how many rows fall into the bins that cover the long tail. With equal counts, look at how wide the last bin has to be.