Sub topic 9
Interaction and polynomial features
This chapter assumes you know how to fit a scikit-learn model, how a Pipeline and ColumnTransformer fit together, and why scaling matters for linear models. It also assumes you have read the chapters on data leakage and scaling.
Why add features that are made from other features
A linear model predicts with a weighted sum of its inputs. Each feature has its own effect, and the effects add up. Many real relationships do not work that way:
- The effect of one feature depends on another. Ad spend matters more in a large market than in a small one.
- The relationship curves. Risk may rise slowly with age and then sharply after a certain point.
You can give a linear model these shapes by adding columns that encode them. Two kinds of column cover most cases:
- An interaction feature is a product of two or more columns, such as
x1 * x2. It lets the effect ofx1change with the level ofx2. - A polynomial feature is a power of a column, such as
x1 ** 2. It lets the model fit a curve while it remains linear in its coefficients.
Tree-based models such as random forests and gradient boosting find interactions on their own by splitting on one feature and then another. Explicit interaction columns help them less, but they still help when the true signal is a ratio or a product. A tree needs many splits to approximate debt / income. A single column gives it directly.
A model that fails without interactions
The target below is a pure product of two inputs. A linear model cannot represent it, because for a fixed x2 the effect of x1 flips sign as x2 changes sign.
import numpy as np
from sklearn.linear_model import Ridge
from sklearn.model_selection import cross_val_score
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import PolynomialFeatures, StandardScaler
rng = np.random.default_rng(0)
X = rng.uniform(-2, 2, size=(500, 2))
y = 3 * X[:, 0] * X[:, 1] + rng.normal(0, 0.5, size=500)
plain = make_pipeline(StandardScaler(), Ridge(alpha=1.0))
with_inter = make_pipeline(
PolynomialFeatures(degree=2, include_bias=False),
StandardScaler(),
Ridge(alpha=1.0),
)
for name, m in [("plain", plain), ("with interactions", with_inter)]:
score = cross_val_score(m, X, y, cv=5, scoring="r2").mean()
print(name, round(score, 3))The plain model scores an R² near zero, since it can explain almost none of the variance. The model with interactions scores above 0.9. The model is the same Ridge in both cases. Only the feature set changed.
How PolynomialFeatures expands columns
PolynomialFeatures(degree=2) creates every product of the input columns whose total power is at most 2. For columns a and b that means a, b, a^2, a b and b^2.
from sklearn.preprocessing import PolynomialFeatures
names_full = PolynomialFeatures(degree=2, include_bias=False).fit(
[[1.0, 2.0]]
).get_feature_names_out(["a", "b"])
names_inter = PolynomialFeatures(
degree=2, interaction_only=True, include_bias=False
).fit([[1.0, 2.0]]).get_feature_names_out(["a", "b"])
print(list(names_full)) # ['a', 'b', 'a^2', 'a b', 'b^2']
print(list(names_inter)) # ['a', 'b', 'a b']The main parameters are:
| Parameter | Effect |
|---|---|
| `degree` | Highest total power. Degree 3 adds `a^3`, `a^2 b`, `a b^2` and so on. |
| `interaction_only` | Keeps products of distinct columns and drops pure powers such as `a^2`. |
| `include_bias` | Adds a constant column of ones. Set it to `False` when the downstream model already fits an intercept, which is the usual case. |
Always call get_feature_names_out when you inspect or debug the result. Without it, the output is an unlabeled array.
The column count grows fast
The number of output columns without a bias column is C(n + d, d) - 1, where n is the number of input columns and d is the degree.
| Input columns | Degree 2 | Degree 3 |
|---|---|---|
| 10 | 65 | 285 |
| 50 | 1,325 | 23,425 |
| 100 | 5,150 | 176,850 |
Each extra column raises the risk of overfitting and the cost of fitting. A few habits keep this under control:
- Apply polynomial expansion only to a small, chosen set of numeric columns, not to the whole table.
- Prefer
interaction_only=Truewhen you do not expect curvature. - Stay at degree 2 unless cross-validation shows a gain from degree 3.
- Use a regularized model such as
RidgeorLasso, and scale the expanded columns first.
Combining with other transforms
Polynomial features amplify skew. If income is right-skewed, income ** 2 is far more skewed. Reduce the skew first, then expand:
import numpy as np
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import FunctionTransformer, PolynomialFeatures
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(X_new.shape) # (2, 5)The two input columns become five: the two logged columns, their squares and their product.
Order also matters for scaling. If you scale after expansion, as in the first example, the squares and products are standardized and a penalized model treats them fairly. If you scale before expansion, the inputs are centered, so each product measures how far both values sit from their means. That makes the product easier to interpret and reduces its correlation with the originals. Both orders are valid. Pick one deliberately and check it with cross-validation.
Using it inside a ColumnTransformer
Apply expansion to numeric columns only. Squaring a one-hot column returns the same column, and the product of two one-hot columns from the same variable is always zero. Both add useless columns.
The data below hides an age-by-income interaction in the label. The code compares the same pipeline with and without the expansion step.
import numpy as np
import pandas as pd
from sklearn.compose import ColumnTransformer
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import cross_val_score
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import OneHotEncoder, PolynomialFeatures, StandardScaler
rng = np.random.default_rng(1)
n = 600
X = pd.DataFrame({
"age": rng.integers(20, 70, n).astype(float),
"income": rng.lognormal(10.5, 0.5, n),
"city": rng.choice(["A", "B", "C"], n),
})
y = (
(X["age"] - 45) * (np.log(X["income"]) - 10.5) + rng.normal(0, 3, n) > 0
).astype(int)
numeric_cols = ["age", "income"]
categorical_cols = ["city"]
def make_model(use_poly):
num_steps = [("scale", StandardScaler())]
if use_poly:
num_steps.append(
("poly", PolynomialFeatures(degree=2, include_bias=False))
)
prep = ColumnTransformer([
("num", Pipeline(num_steps), numeric_cols),
("cat", OneHotEncoder(handle_unknown="ignore"), categorical_cols),
])
return Pipeline([
("prep", prep),
("clf", LogisticRegression(max_iter=1000)),
])
for use_poly in (False, True):
scores = cross_val_score(
make_model(use_poly), X, y, cv=5, scoring="roc_auc"
)
print(use_poly, round(scores.mean(), 3), round(scores.std(), 3))Here the scaler runs before the expansion, so the age-by-income product is a product of centered values. The False run should score close to 0.5 ROC AUC, since the label depends on the product and not on either column alone. The True run should score clearly higher.
PolynomialFeatures learns nothing from the data, so it cannot leak by itself. The scaler placed before or after it does learn from data. That is why the whole chain belongs inside the pipeline that cross_val_score refits on each training fold.
Features from domain knowledge
Automatic expansion is a blunt tool. A handful of features chosen from domain knowledge often beats thousands of generated ones. Common patterns:
- Ratios: debt to income, clicks per impression, price per square meter.
- Products: price times quantity, length times width.
- Differences: time since last purchase, balance minus limit.
- Group flags: "is a weekend and is a holiday" as a product of two binary columns.
Ratios need a guard against zero denominators. Handle that case explicitly, for example by returning missing for those rows and letting the imputer deal with it.
import numpy as np
import pandas as pd
df = pd.DataFrame({"debt": [100.0, 50.0], "income": [400.0, 0.0]})
df["debt_to_income"] = (df["debt"] / df["income"]).replace(
[np.inf, -np.inf], np.nan
)
print(df["debt_to_income"].tolist()) # [0.25, nan]Deciding when to add them
Common errors
- Expanding every column. The column count explodes and the model overfits. Choose the columns.
- Forgetting to scale. Squares and cubes of unscaled values reach very different magnitudes, which breaks penalties and slows solvers.
- Expanding one-hot columns. This adds duplicates and all-zero columns.
- Fitting on the full dataset. Any scaler or selector around the expansion must be fitted inside each training fold.
- Extrapolating. A degree 3 polynomial can swing wildly outside the range of the training data. Check predictions at the edges of your input ranges.
- Judging by training score. Added columns always raise the training score. Only the cross-validated score tells you whether they help.
Exercise
A table has 40 numeric columns. You apply PolynomialFeatures(degree=2, include_bias=False) to all of them and the cross-validated score drops compared with the baseline. How many columns does the expansion produce, and what two changes would you try first?
Show answer
The expansion produces C(42, 2) - 1 = 861 - 1 = 860 columns (40 originals plus 820 squares and pairwise products). First, restrict the expansion to a small set of numeric columns chosen with domain knowledge, or use interaction_only=True to drop pure squares. Second, scale the expanded columns and use a regularized model such as Ridge or Lasso, then compare by cross-validation again.
Exercise
Why is it a mistake to apply PolynomialFeatures to the one-hot columns that come from a single categorical variable?
Show answer
Each one-hot column holds only 0 and 1, so its square equals the column itself and adds a duplicate. The product of two one-hot columns from the same variable is always 0, because a row can belong to only one category. Both outputs add columns with no information. Apply the expansion only to the numeric branch of the ColumnTransformer.