Feature creation and interaction terms
What Are We Really Doing?
The goal: increase the expressive power of your feature space so linear models can capture nonlinear relationships, and complex models can learn faster with less data.
Why Feature Creation Matters
The Representation Bottleneck: Most ML algorithms learn coefficients/weights on features. If your features don't encode the right relationships, no amount of training will help.

Mathematical Reality: A linear model can NEVER learn no matter how much data you have—the multiplicative relationship isn't in the hypothesis space. But if you create , suddenly works perfectly.
Types of Feature Creation
1. Polynomial Features
Derivation from scratch:
- Why? Real-world relationships are rarely linear. Physics: (kinetic energy), (area).
- How many features? For features at degree :
- For : new features:
- Why subtract 1? The constant term 1 is redundant with the bias.
But yield might peak at moderate temperature (too hot/cold is bad) and depend on the combination of temperature and water availability.
Solution: Create degree-2 polynomial features:
Model becomes:
Why this works:
- with negative captures the inverted-U shape (optimal temperature)
- captures interaction: rain helps more when it's warm
- might capture diminishing returns (too much rain floods crops)
Concrete numbers:
- Original: → features
- Expanded:
- If learned weights are :
2. Interaction Terms
Why multiplication? It encodes joint effect where the impact of one feature depends on the value of another.
Mathematical intuition: Consider a model with interaction:
Rearrange:
The effective coefficient of is —it changes with ! This is moderation/synergy.
Naive model:
Issue: This says ads have the same impact on weekdays and weekends. But weekend shopers might be more responsive!
Add interaction:
New model:
Interpretation:
- Weekday (): sales
- Each ad dollar → +$50 sales
- Weekend (): sales
- Simplify: sales
- Each ad dollar → +$130 sales (2.6× more effective!)
Why this step? The interaction term only activates on weekends, adding extra slope to the ad_spend effect.
3. Ratio and Difference Features
When to use:
- Ratios: Normalize by scale (price-to-earnings ratio, clicks-per-impression)
- Differences: Capture change (temperature delta, account balance change)
- Rates: Efficiency metrics (revenue per employee, error per request)
A model might learn: high debt → high risk. But 80k income is different from 30k income!
Create:
Now the model sees relative burden, not absolute numbers. Someone with 0.625 ratio is safer than someone with 1.8 ratio, regardless of actual dollar amounts.
Why this step? Division normalizes by the denominator, creating a scale-invariant feature.
4. Domain-Specific Features
Create:
price_lag1= yesterday's priceprice_diff= today's price - yesterday's price (daily change)rolling_mean_7= average price over last 7 days (trend)volatility= std(last 7 days) (risk measure)
Why? These capture temporal patterns: trends, mean-reversion, volatility clustering.
Create Haversine distance:
where = latitude, = longitude, = Earth radius.
Why? Distance is the primary driver of fare. Raw coordinates don't directly encode this.
Common Mistakes
[!recall]- Explain It to a 12-Year-Old
Imagine you're trying to predict how fun a video game is using just two numbers: graphics quality (1-10) and story quality (1-10).
If you just add them up (), you're saying a game with great graphics but no story (10 + 2) is just as fun as a game with okay graphics and story (6 + 6). But that's wrong!
Feature creation is like creating a NEW number that captures what you really care about:
- = a "synergy score." If BOTH are good, this number is huge (10 × 10 = 100). If one is terrible, even if the other is great, this is small (10 × 2 = 20). This interaction captures that both need to be good together.
- captures that going from 9→10 in graphics quality might matter MORE than going from 2→3 (diminishing returns at the low end, excitement at the high end).
By creating these new numbers from the old ones, you help the computer see patterns it couldn't see before. It's like giving it new "senses" to understand the world.
[!mnemonic] PRIME Features
Polynomial (powers for curves) Ratios (normalize by scale) Interactions (joint effects, products) Mathematical (logs, sqrt, domain transforms) Engineered (lags, rolling, domain-specific)
Practical Implementation
import numpy as np
from sklearn.preprocessing import PolynomialFeatures, StandardScaler
from sklearn.pipeline import Pipeline
from sklearn.linear_model import Ridge
# Sample data: predicting sales from ad_spend and website_traffic
X_train = np.array([[100, 500], [150, 800], [200, 1200], [80, 400]])
y_train = np.array([5000, 7500, 12000, 3800])
# Create polynomial features with interactions
poly = PolynomialFeatures(degree=2, include_bias=False, interaction_only=False)
X_poly = poly.fit_transform(X_train)
# Features are now: [ad, traffic, ad^2, ad*traffic, traffic^2]
print("Original shape:", X_train.shape) # (4, 2)
print("Polynomial shape:", X_poly.shape) # (4, 5)
print("Feature names:", poly.get_feature_names_out(['ad_spend', 'traffic']))
# ['ad_spend', 'traffic', 'ad_spend^2', 'ad_spend*traffic', 'traffic^2']
# Always scale after creating features!
scaler = StandardScaler()
X_scaled = scaler.fit_transform(X_poly)
# Train model
model = Ridge(alpha=1.0)
model.fit(X_scaled, y_train)
# Manual interaction creation example
X_manual = X_train.copy()
interaction = X_train[:, 0] * X_train[:, 1] # ad_spend * traffic
X_with_interaction = np.column_stack([X_train, interaction])
print("With manual interaction:", X_with_interaction.shape) # (4, 3)When to Use Feature Creation
Use polynomial features when:
- You have small feature sets (< 20 features) to avoid explosion
- Nonlinear relationships are suspected (physics, economics, biology)
- Using linear models that need help capturing curves
- You have sufficient data ( new feature count) to avoid overfitting
Use interaction terms when:
- Domain knowledge suggests synergy (medication + diet, temperature + humidity)
- A/B testing reveals different effects for different segments
- Exploratory data analysis shows crossing effects in plots
- Modeling moderating variables (the effect of X on Y depends on Z)
Use domain features when:
- You have temporal data (lags, rolling stats, seasonality)
- You have spatial data (distances, coordinates, neighborhoods)
- You have text/categorical data (encoding tricks, embedings)
- There are known physical laws to encode (conservation laws, rate equations)
Avoid feature creation when:
- Using tree-based models (XGBoost, Random Forest) for polynomial features—they capture interactions and nonlinearity naturally through splits
- You have too many features already (high-dimensional, genomics)—add more features cautiously
- Your model is already overfitting—simplify first, add features later
- You lack domain expertise and are creating features blindly—this is feature engineering roulette
Connections
- Exploratory Data Analysis - visualize relationships to inspire feature ideas
- Feature Scaling and Normalization - always scale after creating polynomial/interaction features
- Regularization (L1, L2) - control overfitting when you've added many features
- Feature Selection Methods - prune irrelevant created features
- Overfitting and Underfitting - more features increases overfitting risk
- Linear Regression - polynomial features turn linear models into nonlinear ones
- Decision Trees and Random Forests - capture interactions naturally, less need for manual feature engineering
- Cross-Validation - evaluate whether new features actually improve generalization
#flashcards/ai-ml
What is the primary goal of feature creation in machine learning? :: To increase the expressive power of the feature space by transforming and combining existing variables, allowing models to capture relationships that aren't present in the raw data.
Why can't a linear model ever learn a multiplicative relationship ? :: Because multiplication is not in the hypothesis space of linear combinations. The model can only learn additive weighted sums, not products of features. Creating the interaction term explicitly adds this relationship.
How many features result from applying degree-2 polynomial expansion to 3 original features?
What does an interaction term capture that individual features and cannot?
Why should you create ratio features like debt-to-income instead of using absolute values?
State the hierarchical principle for interaction terms.
Why must you scale features after creating polynomial or interaction terms?
When should you avoid creating polynomial features for tree-based models like Random Forest?
What is the correct order: split data then create features, or create features then split data?
For time-series prediction, why create lag features like price_lag_1 and rolling averages?
Concept Map
Hinglish (regional understanding)
Intuition Hinglish mein samjho
Feature creation ka matlab hai ke hum apne existing data se naye variables banate hain jo hidden patterns ko expose karte hain. Socho agar tumhe ghar ki price predict karni hai sirf square footage aur number of bedrooms se—ye pura picture nahi dete. Agar tum create karo "price per square foot" (price / sqft), tab suddenly model ko efficiency ka idea mil gaya. Ye transformation data ko model ke liye "digestible" bana deta hai.
Interaction terms bohot powerful hain kyunki ye capture karte hain ke do features sath milkar kaise kaam karte hain. Example: temperature akela aur sunny weather akela ice cream sales ko fully explain nahi kar sakte, lekin "temperature × is_sunny" ye compound effect capture kar leta hai. Jab dono high hain, tab interaction term ka value explode hota hai, jo model ko bata hai ke ye combination special hai.
Domain knowledge inject karna bhi zaroori hai. Agar tum time-series data pe kaam kar rahe ho, tab "lag features" (kal ki value) aur "rolling averages" (pichle 7 din ka mean) banao. Agar geospatial data hai, tab latitude-longitude se Haversine distance calculate karo. Physics ya business rules ko explicitly features mein encode karne se model ko seekhna easy ho jata hai—warna wo raw numbers se ye relationships discover karne mein struggle karega. Feature engineering wahi hai jo average models ko great banata hai, kyunki sahi features ke sath even simple linear regression bhi nonlinear patterns capture kar sakti hai!