Math Transforms, Ratios and Interactions
A model only sees the columns you give it. A linear model given debt and income separately cannot discover that what really matters is debt relative to income; a tree can approximate it, but only with many splits and lots of data. Feature engineering is the step where you write such relationships down as new columns, so the model gets them for free. This lesson covers the first three families of the curriculum's list: mathematical transformations, ratios and interactions. The basics with pandas are in Feature Engineering; here we measure what each family buys and how to put it inside a pipeline.
Three families
| Family | Examples | Helps when |
|---|---|---|
| Mathematical transform | log, square root, square, reciprocal, clipping, binning | the effect is curved, or a feature is skewed (see log and power transforms) |
| Ratio | debt / income, price / area, clicks / views, distance / time | the meaning lives in the proportion, not in either raw number |
| Interaction | product of two features, polynomial terms, "both conditions true" | the effect of one feature depends on the value of another |
A good engineered feature usually comes from a sentence a domain expert would say: "what matters is how much of their income goes to debt", "a big house is only expensive in the city centre". Write the sentence first, then the column.
A ratio a shallow tree cannot build
Here the true risk depends only on the debt-to-income ratio. We compare a depth-2 decision tree on the raw columns with the same tree given the ratio as well, scored with 5-fold cross-validated ROC AUC:
import numpy as np
from sklearn.tree import DecisionTreeClassifier
from sklearn.model_selection import cross_val_score
rng = np.random.default_rng(0)
n = 1000
income = rng.lognormal(10.5, 0.8, n) # yearly income
debt = income * rng.uniform(0.05, 0.9, n) # debt as a share of income
dti = debt / income
default = (rng.random(n) < 1 / (1 + np.exp(-12 * (dti - 0.6)))).astype(int)
raw = np.column_stack([income, debt])
with_ratio = np.column_stack([income, debt, dti])
tree = DecisionTreeClassifier(max_depth=2, random_state=0)
for name, X in [("income, debt", raw), ("income, debt, debt/income", with_ratio)]:
auc = cross_val_score(tree, X, default, cv=5, scoring="roc_auc")
print(f"{name:28s} ROC AUC {auc.mean():.3f}")
print("default rate:", round(default.mean(), 3))income, debt ROC AUC 0.741
income, debt, debt/income ROC AUC 0.926
default rate: 0.342
On the raw columns the tree reaches a ROC AUC of 0.741, with the ratio 0.926. The boundary "debt above 0.6 times income" is a diagonal line through the origin of the income-debt plane, and a tree can only cut parallel to the axes, so with two levels it draws a crude staircase. Given the ratio, one split does the job. (A logistic regression happens to manage here, because that particular boundary is a straight line; the ratio still makes the model simpler to read, and with a curved effect, such as risk rising sharply only above 40 %, a linear model needs the ratio too.)
Interactions: when one feature changes another's effect
An interaction is a product (or a logical AND) of features. In the next example a house's price per square metre depends on whether it is central, so the effect of area is different in the two locations. A linear model with only area and central fits one slope for everyone; adding area * central lets it fit two:
import numpy as np
from sklearn.linear_model import LinearRegression
from sklearn.model_selection import cross_val_score
from sklearn.preprocessing import PolynomialFeatures
rng = np.random.default_rng(1)
n = 400
area = rng.uniform(30, 150, n)
central = rng.integers(0, 2, n)
price = 50 + area * np.where(central == 1, 6.0, 2.5) + rng.normal(0, 25, n) # in thousands
X_plain = np.column_stack([area, central])
X_inter = np.column_stack([area, central, area * central])
for name, X in [("area, central", X_plain), ("+ area*central", X_inter)]:
r2 = cross_val_score(LinearRegression(), X, price, cv=5, scoring="r2").mean()
print(f"{name:15s} R2 = {r2:.3f}")
poly = PolynomialFeatures(degree=2, interaction_only=True, include_bias=False)
poly.fit(X_plain)
print(poly.get_feature_names_out(["area", "central"]).tolist())
fit = LinearRegression().fit(X_inter, price)
print("slopes: outside", round(fit.coef_[0], 2), "| central", round(fit.coef_[0] + fit.coef_[2], 2))area, central R2 = 0.915
+ area*central R2 = 0.987
['area', 'central', 'area central']
slopes: outside 2.47 | central 5.99
The interaction raises the cross-validated R2 from 0.915 to 0.987, and the fitted slopes recover the two prices per square metre we built in (about 2.5 and 6). PolynomialFeatures(interaction_only=True) generates every pairwise product automatically, which is handy for a few columns, but with 50 columns it makes 1,225 products: generate interactions you can explain, then let feature selection prune.
From scratch, then inside a pipeline
Engineered features are a preprocessing step like any other, so they belong inside the pipeline. That way the same code runs at training time, in cross-validation and in production, and nothing is computed from data the model should not see. FunctionTransformer wraps a plain NumPy function as a scikit-learn step:
import numpy as np
import pandas as pd
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import FunctionTransformer, StandardScaler
from sklearn.linear_model import LogisticRegression
def add_features(df):
out = df.copy()
out["dti"] = out["debt"] / out["income"] # ratio
out["log_income"] = np.log1p(out["income"]) # math transform
out["young_x_dti"] = (out["age"] < 25) * out["dti"] # interaction with a condition
return out
loans = pd.DataFrame({"income": [42000, 85000, 23000, 61000],
"debt": [21000, 9000, 18000, 30000],
"age": [23, 41, 22, 35]})
print(add_features(loans).round(3))
pipe = make_pipeline(FunctionTransformer(add_features), StandardScaler(), LogisticRegression())
pipe.fit(loans, [1, 0, 1, 0])
print("columns seen by the model:", pipe[0].transform(loans).columns.tolist()) income debt age dti log_income young_x_dti
0 42000 21000 23 0.500 10.645 0.500
1 85000 9000 41 0.106 11.350 0.000
2 23000 18000 22 0.783 10.043 0.783
3 61000 30000 35 0.492 11.019 0.000
columns seen by the model: ['income', 'debt', 'age', 'dti', 'log_income', 'young_x_dti']
A stateless function like this one (each row computed from itself) cannot leak. It becomes risky when a feature uses other rows: a ratio to the column mean, a rank, a group average. Those statistics must be learned on the training folds only, which is what group aggregation features and target encoding are about.
Pitfalls
- Division by zero: a ratio with a zero denominator gives
inforNaN. Decide what zero means (no income at all? missing?) and handle it explicitly, often with a flag column. - Ratios of noisy small numbers: clicks / views with 1 view gives 0 or 1. Add a smoothing count (
(clicks + 1) / (views + 2)) or require a minimum denominator. - Feature explosion: all products of many columns overfit and slow everything down. Generate few, meaningful ones.
- Trees vs linear models: trees capture interactions by themselves through successive splits, but still benefit from ratios, which need many axis-aligned splits to approximate.
- Using the label or the future: a feature computed from information unavailable at prediction time (a "total spent this year" for a prediction made in March) looks brilliant in validation and fails in production. See the leakage rules.
Practice
- A delivery dataset has
distance_kmandduration_min. Which engineered feature would help a model that flags suspiciously slow deliveries, and what edge case must you handle?
Answer
Average speed, distance_km / (duration_min / 60) in km/h. Handle duration_min == 0 (a data error or an instant cancellation): set the speed to missing and add a flag, rather than letting inf reach the model.
- Why does a random forest need fewer interaction columns than a linear regression?
Answer
Each path from root to leaf is a conjunction of conditions ("central and area above 100"), so trees model interactions through their structure. A linear model adds up independent terms and can only express an interaction if a product column exists.
Test yourself
Risk depends only on debt divided by income. Why does a depth-2 tree on raw income and debt score lower than with a debt / income column?
- Trees cannot use two features
- The boundary is a diagonal line, and a tree only cuts parallel to the axes, so it needs many splits to approximate it
- The columns are not scaled
- Ratios always leak
What does an interaction feature area * central let a linear model do?
- Ignore area
- Fit a different slope for area in central and non-central houses
- Scale area
- Encode the category
Which engineered feature can leak if computed before splitting?
log1p(income)debt / incomein the same row- Each row's income divided by the mean income of the whole dataset
age < 25
Why put feature engineering inside a scikit-learn pipeline with FunctionTransformer?
- It makes the features faster
- The same code runs in training, cross-validation and production, applied to each split correctly
- It is required by StandardScaler
- It removes missing values