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
- Replace each column listed in
log_columnsby . This compresses large values and keeps zero at zero. - Build every product of columns up to total degree
degree. Withinteraction_only, keep only products of distinct columns. - If
n_binsis above zero, learn bin edges per column infit, by quantiles (equal counts) or uniformly (equal widths). - In
transform, compute the same terms for new rows and append one bin index per column using the stored edges. - For a time series, call
lag_featuresto place earlier values beside the current one androlling_meanfor a moving average. Rows without enough history hold NaN. - Call
feature_namesto 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 , 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
| If | Use instead |
|---|---|
| You would rather have the model find interactions itself | A tree ensemble such as Random Forest, XGBoost or LightGBM |
| The inputs are images, audio or raw text | A network that learns its own features, such as a CNN or a Transformer |
| There are too many features and you want fewer, not more | PCA or an Autoencoder |
Math foundations
Log transform
Turns multiplication into addition: going from 10 to 100 moves about as far as going from 100 to 1,000. Adding 1 keeps at .
A polynomial term
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 . The fitted
powers_array stores one row of exponents per term.How many terms
The count of all terms of degree 1 to in columns, without the constant column. This is the number that explodes when or grows.
Uniform bin edges and the bin index
The training range is cut into equal widths. The index of a value is the number of edges at or below it, from 0 to . The quantile strategy places the edges at equal shares of the data instead.
Lag feature
The value steps earlier, placed in the row for time . It lets a model that sees one row at a time use the recent past.
Rolling mean
The average of the current value and the values before it. It smooths noise and shows the local level of the series.
Symbols
- value of input column j in one row
- number of input columns
- degree, the highest total power
- power of column j in one term
- n_bins, the number of bins
- the k-th inner bin edge
- smallest and largest training value of the column
- value of a series at time t
- lag, a number of steps into the past
- window length of the rolling mean
Worked by hand
Take one row with and 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 .
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
- 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.
- 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.
- Why does 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.
- 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 . Ask which of them exist at the moment a real forecast is made.
- 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.