Sub topic 9
Interaction and polynomial features
This chapter assumes you can build a scikit-learn Pipeline, and that you know why scaling and skew-reducing transforms matter. An interaction or polynomial feature is a new column computed from existing numeric columns. It lets a model that is linear in its inputs capture curved or combined effects.
Why add them
A linear model gives each feature one fixed weight. That is a poor fit in two common cases:
- Curvature. The effect of age on risk may rise slowly and then sharply. A squared term,
age^2, lets a straight-line model bend. - Combined effects. The effect of one feature may depend on another. Price per square metre depends on both price and area. A product term,
price * area, lets the model weight the two together.
Tree-based models find many of these patterns by splitting, so they gain less from hand-built terms. Linear models, logistic regression and support vector machines gain the most.
Build them with PolynomialFeatures
PolynomialFeatures(degree=2) creates squares and all pairwise products. With interaction_only=True it creates only products and skips the squares. The example below applies a log1p transform first, so the squares and products are built from less skewed values.
import numpy as np
from sklearn.preprocessing import FunctionTransformer, PolynomialFeatures
from sklearn.pipeline import make_pipeline
log_then_poly = make_pipeline(
FunctionTransformer(np.log1p, feature_names_out="one-to-one"),
PolynomialFeatures(degree=2, interaction_only=False, include_bias=False),
)
X_new = log_then_poly.fit_transform([[10.0, 200.0], [20.0, 5000.0]])
print(log_then_poly.get_feature_names_out(["age", "income"]))
print(X_new.shape)The names printed are age, income, age^2, age income and income^2. The shape is (2, 5). Set include_bias=False because linear models already add their own intercept.
Common errors
- Column explosion. With
nfeatures, degreedcreatesC(n + d, d) - 1columns, excluding the bias. Ten features at degree 3 give 285 columns. Keep the degree at 2 or 3 and expand only the columns you have a reason to expand. - Scale blow-up. Squaring a column with values near 5000 gives values near 25,000,000. Scale after expanding, or apply the log transform first. Put a
StandardScalerafterPolynomialFeaturesfor regularized or gradient-based models. - Overfitting. More columns give the model more room to memorize noise. Pair polynomial features with regularization such as
RidgeorLogisticRegression(C=...), and compare scores with cross-validation. - Leakage and inconsistency. Keep the expansion inside the pipeline. Then every fold and every serving request uses the same steps. Never hand-build the terms on the full dataset before splitting.
- Wrong inputs. Do not pass one-hot columns through
PolynomialFeatureswithout thought. Squaring a 0/1 column changes nothing, and products between dummy columns from the same category are always zero.
Choose features from domain knowledge
Blind expansion is rarely the best option. A hand-made ratio such as debt / income or a product such as length * width often beats a full degree-2 expansion. It adds one meaningful column instead of dozens of arbitrary ones.
Exercise
A dataset has 3 numeric features. You apply PolynomialFeatures(degree=2, include_bias=False). How many output columns do you get, and which kinds are they?
Show answer
9 columns. There are 3 original features, 3 squared terms and 3 pairwise products. The count follows C(3 + 2, 2) - 1 = 9.