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
- FeatureEngineer.fit fixes the list of polynomial terms for the given number of columns and degree, and stores the exponents in powers_.
- With interaction_only on, only products of different columns are kept, such as , and powers such as are left out.
- 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.
- transform computes every term as a product of column powers, then appends one bin-index column per input column.
- 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.
- lag_features and rolling_mean build columns from earlier values of an ordered series, using only the past.
- 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 and 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
| If | Use instead |
|---|---|
| The inputs are images, audio or text with plenty of data | A deep network that learns its own features, such as a CNN or Transformer |
| You already have too many columns | Feature selection, or PCA |
| The model is a boosted tree and the relation is a simple threshold or interaction | Raw columns, since trees find splits and interactions themselves |
Math foundations
A polynomial term
Each new column is a product of input columns raised to whole-number exponents. Row of powers_ holds the exponents, and their sum is the degree of the term.
How many terms
The number of terms of degree 1 to in columns, without the constant column. It grows roughly like , which is why high degrees are expensive.
Interactions only
When only products of distinct columns are allowed, a term of degree is a choice of different columns.
Cyclic encoding
A value on a cycle of length 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 and .
Lag and rolling mean
A lag copies the value from steps ago. The rolling mean averages the previous values. Both sums start at , so the current value is never used.
Symbols
- the value of input column j in one row
- the number of input columns
- the degree setting
- the exponent of column j in term t (one entry of powers_)
- output term t
- the number of output terms, in full and with interaction_only
- a position on a cycle and the length of the cycle
- the value of an ordered series at time t
- the lag and the rolling window length
Worked by hand
Count the terms for columns and degree . Then compare December and January, as the raw month number and on the circle. December has and January has .
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 . 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
- A tree model and a linear model get the same extra column . 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.
- 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.
- 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.
- 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.