Lesson 2 of 9
Interaction Terms, Non-Linear Binnings & Spline Basis Expansions
Linear algorithms assume the effect of feature x1 on target y is independent of feature x2. In real-world phenomena, features exhibit synergy: the impact of credit score depends on debt load; the impact of website time-on-page depends on cart value. Explicitly synthesizing multiplicative interaction terms (x1 * x2), non-linear quantile binnings, and B-Spline basis expansions allows linear and tree models to capture complex multi-dimensional surfaces.
Interaction Terms & Quantile Binning in Scikit-Learn
import numpy as np
import pandas as pd
from sklearn.preprocessing import PolynomialFeatures, KBinsDiscretizer
from sklearn.linear_model import Ridge
from sklearn.metrics import r2_score
# Non-linear synergistic relationship: y = 2*x1 - 3*x2 + 4*(x1*x2) + noise
np.random.seed(42)
n = 800
x1 = np.random.uniform(1, 10, n)
x2 = np.random.uniform(1, 10, n)
y = 2.0 * x1 - 3.0 * x2 + 4.0 * (x1 * x2) + np.random.normal(0, 5, n)
X_raw = np.column_stack([x1, x2])
# 1. BASELINE LINEAR MODEL (Cannot capture synergistic x1*x2 interaction)
linear_model = Ridge().fit(X_raw, y)
print("=== INTERACTION TERM IMPACT BENCHMARK ===")
print(f"Linear Model (No Interactions) R^2 Score: {r2_score(y, linear_model.predict(X_raw)):.4f} (Poor fit)")
# 2. POLYNOMIAL INTERACTION EXPANSION (interaction_only=True)
# Generates [x1, x2, x1*x2] without useless x1^2, x2^2 terms
poly = PolynomialFeatures(degree=2, interaction_only=True, include_bias=False)
X_inter = poly.fit_transform(X_raw)
inter_model = Ridge().fit(X_inter, y)
print(f"Interaction Model (Explicit x1*x2) R^2 Score: {r2_score(y, inter_model.predict(X_inter)):.4f} (Near perfect!)")
print(f"Fitted Interaction Coefficient: {inter_model.coef_[2]:.4f} (True: 4.000)")
# 3. NON-LINEAR QUANTILE DISCRETIZATION (KBinsDiscretizer)
# Transforms continuous non-linear features into one-hot indicator bins
kbd = KBinsDiscretizer(n_bins=5, encode='onehot-dense', strategy='quantile')
X_binned = kbd.fit_transform(X_raw)
print(f"\nQuantile Binned Feature Matrix shape: {X_binned.shape} (5 bins per continuous feature)")Pro Tip: When to Use `interaction_only=True`
Always specify `PolynomialFeatures(interaction_only=True, include_bias=False)` when searching for synergistic variables. Setting `interaction_only=False` generates square terms (`x1^2, x2^2`) which introduce extreme collinearity with the linear terms and double the feature count unnecessarily.
MlInteractionFeatures Visual Representation
Hands-On Challenge: Build a Decision Tree Feature Binner
Use a shallow `DecisionTreeRegressor(max_depth=3)` fitted to a single continuous feature to discover optimal non-linear split bin thresholds automatically, converting the continuous variable into discrete categorical intervals based on target variance.
Quick Quiz & Key Concept Checks
Common Pitfall: Combinatorial Feature Explosion
Computing polynomial interactions on 100 features creates 4,950 pairwise interaction columns. This triggers the curse of dimensionality and slows down training. Always perform feature selection (e.g. Mutual Information or Lasso) BEFORE generating pairwise interactions.