Feature creation and interaction terms
2.1.10· AI-ML › Data Preprocessing & Feature Engineering
What Are We Really Doing?
Goal yeh hai: apne feature space ki expressive power badhaana taaki linear models nonlinear relationships capture kar sakein, aur complex models kam data mein jaldi seekh sakein.
Why Feature Creation Matters
The Representation Bottleneck: Zyaatar ML algorithms features par coefficients/weights seekhte hain. Agar tumhare features sahi relationships encode nahi karte, toh kitni bhi training help nahi karegi.

Mathematical Reality: Ek linear model kabhi bhi nahi seekh sakta, chahe kitna bhi data ho—multiplicative relationship hypothesis space mein hai hi nahi. Lekin agar tum create karo, toh achanak perfectly kaam karta hai.
Types of Feature Creation
1. Polynomial Features
Scratch se derivation:
- Kyun? Real-world relationships rarely linear hote hain. Physics: (kinetic energy), (area).
- Kitne features? features ke liye degree par:
- ke liye: new features:
- 1 kyun subtract karte hain? Constant term 1 bias ke saath redundant hai.
Lekin yield moderate temperature par peak kar sakta hai (bahut zyada garam/thanda bura hai) aur temperature aur water availability ke combination par depend kar sakta hai.
Solution: Degree-2 polynomial features create karo:
Model ban jaata hai:
Yeh kyun kaam karta hai:
- Negative ke saath inverted-U shape capture karta hai (optimal temperature)
- interaction capture karta hai: rain tab zyada help karta hai jab warm ho
- diminishing returns capture kar sakta hai (bahut zyada rain crops ko flood kar deta hai)
Concrete numbers:
- Original: → features
- Expanded:
- Agar learned weights hain :
2. Interaction Terms
Multiplication kyun? Yeh joint effect encode karta hai jahan ek feature ka impact doosre feature ki value par depend karta hai.
Mathematical intuition: Interaction ke saath ek model consider karo:
Rearrange karo:
ka effective coefficient hai —yeh ke saath change karta hai! Yahi moderation/synergy hai.
Naive model:
Issue: Yeh kehta hai ki ads ka weekdays aur weekends par same impact hai. Lekin weekend shoppers zyada responsive ho sakte hain!
Interaction add karo:
New model:
Interpretation:
- Weekday (): sales
- Har ad dollar → +$50 sales
- Weekend (): sales
- Simplify karo: sales
- Har ad dollar → +$130 sales (2.6× zyada effective!)
Yeh step kyun? Interaction term sirf weekends par activate hota hai, ad_spend effect mein extra slope add karta hai.
3. Ratio and Difference Features
Kab use karein:
- Ratios: Scale se normalize karo (price-to-earnings ratio, clicks-per-impression)
- Differences: Change capture karo (temperature delta, account balance change)
- Rates: Efficiency metrics (revenue per employee, error per request)
Model seekh sakta hai: high debt → high risk. Lekin 50k debt alag hai 50k se!
Create karo:
Ab model relative burden dekhta hai, absolute numbers nahi. 0.625 ratio wala banda 1.8 ratio wale se safer hai, actual dollar amounts chahe kuch bhi hon.
Yeh step kyun? Division denominator se normalize karta hai, ek scale-invariant feature create karta hai.
4. Domain-Specific Features
Create karo:
price_lag1= kal ka priceprice_diff= aaj ka price - kal ka price (daily change)rolling_mean_7= pichhle 7 din ka average price (trend)volatility= std(last 7 days) (risk measure)
Kyun? Yeh temporal patterns capture karte hain: trends, mean-reversion, volatility clustering.
Haversine distance create karo:
jahan = latitude, = longitude, = Earth radius.
Kyun? Distance fare ka primary driver hai. Raw coordinates directly yeh encode nahi karte.
Common Mistakes
[!recall]- Ise Ek 12-Saal-Ke Bachche Ko Explain Karo
Socho tum predict karna chahte ho ki ek video game kitna fun hai, sirf do numbers use karke: graphics quality (1-10) aur story quality (1-10).
Agar tum bas inhe add kar do (), tum keh rahe ho ki great graphics par no story wala game (10 + 2) utna hi fun hai jitna okay graphics aur story wala (6 + 6). Lekin yeh galat hai!
Feature creation aise ek NAYA number create karna hai jo capture kare jo tumhare liye actually matter karta hai:
- = ek "synergy score." Agar DONO achhe hain, toh yeh number huge hai (10 × 10 = 100). Agar ek terrible hai, chahe doosra great ho, yeh chhota hai (10 × 2 = 20). Yeh interaction capture karta hai ki dono ko milke achha hona chahiye.
- capture karta hai ki graphics quality mein 9→10 jaana shayad 2→3 jaane se ZYADA matter kare (low end par diminishing returns, high end par excitement).
Purane numbers se yeh naye numbers create karke, tum computer ko woh patterns dekhne mein help karte ho jo woh pehle nahi dekh sakta tha. Yeh usse new "senses" dene jaisa hai duniya samajhne ke liye.
[!mnemonic] PRIME Features
Polynomial (curves ke liye powers) Ratios (scale se normalize karo) 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
Polynomial features tab use karo jab:
- Tumhare paas chhote feature sets hain (< 20 features) explosion se bachne ke liye
- Nonlinear relationships suspect kiye jaate hain (physics, economics, biology)
- Linear models use kar rahe ho jinhe curves capture karne mein help chahiye
- Tumhare paas sufficient data hai ( new feature count) overfitting se bachne ke liye
Interaction terms tab use karo jab:
- Domain knowledge synergy suggest kare (medication + diet, temperature + humidity)
- A/B testing different segments ke liye different effects reveal kare
- Exploratory data analysis plots mein crossing effects dikhaye
- Moderating variables model kar rahe ho (X ka Y par effect Z par depend karta hai)
Domain features tab use karo jab:
- Tumhare paas temporal data hai (lags, rolling stats, seasonality)
- Tumhare paas spatial data hai (distances, coordinates, neighborhoods)
- Tumhare paas text/categorical data hai (encoding tricks, embeddings)
- Known physical laws encode karne hain (conservation laws, rate equations)
Feature creation tab avoid karo jab:
- Tree-based models (XGBoost, Random Forest) use kar rahe ho polynomial features ke liye—woh splits ke through interactions aur nonlinearity naturally capture karte hain
- Tumhare paas bahut zyada features already hain (high-dimensional, genomics)—aur features cautiously add karo
- Tumhara model already overfitting kar raha hai—pehle simplify karo, baad mein features add karo
- Tumhare paas domain expertise nahi hai aur tum blindly features create kar rahe ho—yeh feature engineering roulette hai
Connections
- Exploratory Data Analysis - feature ideas inspire karne ke liye relationships visualize karo
- Feature Scaling and Normalization - polynomial/interaction features create karne ke baad hamesha scale karo
- Regularization (L1, L2) - jab bahut saare features add kar liye hain toh overfitting control karo
- Feature Selection Methods - irrelevant created features prune karo
- Overfitting and Underfitting - zyada features overfitting risk badhate hain
- Linear Regression - polynomial features linear models ko nonlinear bana dete hain
- Decision Trees and Random Forests - interactions naturally capture karte hain, manual feature engineering ki kam zaroorat
- Cross-Validation - evaluate karo ki naye features actually generalization improve karte hain ya nahi
#flashcards/ai-ml
Machine learning mein feature creation ka primary goal kya hai? :: Feature space ki expressive power badhana existing variables ko transform aur combine karke, taaki models woh relationships capture kar sakein jo raw data mein present nahi hain.
Ek linear model kabhi bhi multiplicative relationship kyun nahi seekh sakta? :: Kyunki multiplication linear combinations ke hypothesis space mein nahi hai. Model sirf additive weighted sums seekh sakta hai, features ke products nahi. Interaction term explicitly create karna yeh relationship add karta hai.