Exercises — Feature creation and interaction terms
Before we start, three tiny reminders so no symbol is unearned:
Level 1 — Recognition
L1.1
Problem. You have a linear model and the true relationship in the data is (a pure product). Can this model ever fit it perfectly, no matter how much data you give it? Answer yes/no and say what single new feature would fix it.
Recall Solution
No. A linear model can only build weighted sums of the features you hand it. The product is multiplicative — it is simply not expressible as for any fixed weights. Here is the counterexample in full, so nothing is left on faith. Suppose weights did fit exactly. Evaluate at four points:
- : need .
- : need .
- : need .
- : need , but we just forced , giving . Contradiction — no such weights exist. (This exact contradiction is machine-checked in VERIFY.)
Fix: create the interaction feature . Then with fits exactly. The multiplication was moved out of the model and into the feature.
L1.2
Problem. Match each goal to the right feature operation: (a) "make a feature scale-invariant", (b) "capture a peak/optimum shape", (c) "capture that two features only matter together".
Recall Solution
- (a) scale-invariant → ratio . Dividing cancels the units/scale of the denominator.
- (b) peak/optimum shape → squared term (with a negative weight it makes an inverted-U ∩).
- (c) "only matter together" → interaction .
Level 2 — Application
L2.1
Problem. You have raw features. A full degree polynomial expansion produces the constant term, the originals, and all degree-2 combinations. (a) Using the count formula , how many total terms (excluding the redundant constant) does it produce? (b) Of those, how many are genuinely new features you did not already have? List them.
Recall Solution
(a) Total terms (minus the constant). Plug in: . These 9 are the 3 originals plus 6 higher-order terms: (We subtract 1 because the constant term is redundant with the bias .)
(b) Genuinely new features. You already had , so subtract those 3: new features, namely Watch the wording: the formula counts all expansion terms except the constant (here 9); the count of new columns you must add to your existing table is that minus your originals (here ).
L2.2
Problem. Crop-yield model uses features (temperature, rainfall) expanded to with learned weights and bias . Compute predicted yield for .
Recall Solution
Build the expanded row first: Now the weighted sum plus bias: Yield = 229.6. Notice the from : the negative weight on the squared term is pulling yield down as it gets too hot — that is the inverted-U in action.
Level 3 — Analysis
L3.1
Problem. An ad-sales model is where . (a) What is the effective per-dollar ad slope on weekdays vs weekends? (b) By what factor is a weekend ad dollar more effective?
Recall Solution
Group the terms that multiply : The effective ad slope is the thing in the parentheses, — it changes with weekend status. That is exactly what an interaction does.
- Weekday (): slope per dollar.
- Weekend (): slope per dollar.
- (b) Factor .
Figure 1 — interaction as a change in slope. Two straight sales-vs-ad lines; the interaction term is the gap in steepness that tilts the weekend line (amber) up relative to the weekday line (cyan).

L3.2
Problem. Credit-risk data: total_debt = $50,000, annual_income = $80,000. (a) Compute the debt-to-income ratio. (b) Person B has debt \27{,}000$15{,}000$. Who is riskier by this feature, and why does the ratio reveal something the raw dollars hide?
Recall Solution
- (a) Person A: .
- (b) Person B: . Person B is far riskier: their debt is their yearly income, versus A's .
Why the ratio matters: raw dollars would rank A as "more debt" () and possibly flag A as riskier. But the relative burden is what predicts default. Division by income makes the feature scale-invariant — a \100$15$k earner are compared on the same footing.
Level 4 — Synthesis
L4.1
Problem. A colleague builds a model with the interaction but drops the main effects and : . Suppose the true process is . Show numerically that no single can fit even three simple points, so the model is doomed.
Recall Solution
Take three points and compute the true :
- : true , but .
- : true , but .
- : true , and .
The interaction-only model gives . At the first two points , so both must predict the same value . But the truth says one is and the other is — impossible to match with a single . The main effects carry information the pure interaction throws away. Always keep main effects when you add their interaction.
L4.2
Problem. Uber-fare model needs distance from raw coordinates. The Haversine formula gives the great-circle distance between two points on a sphere. First, the symbols:
- (Greek "phi") = latitude in radians — how far north/south a point is.
- (Greek "lambda") = longitude in radians — how far east/west a point is.
- = the sphere's radius (Earth radius km).
- = the inverse of sine: "which angle has this sine?"
The full formula for the distance between point and point is
For a short trip, pickup , dropoff (same longitude), km. Compute , then explain why raw lat/lon columns fail to encode this.
Recall Solution
Since , the longitude difference is , so and that whole second term vanishes. The formula collapses to a pure latitude arc: Convert the latitude difference to radians: rad, half of that rad. of a tiny angle the angle, so Why raw columns fail: fare depends on distance travelled, a nonlinear combination of four coordinates. A linear model on can only weight each separately — it cannot compute a square root of squared differences. The engineered distance feature is the physics the model needs.
Level 5 — Mastery
L5.1
Problem. You are given price, sqft, bedrooms, year_built, lot_size for house-price prediction with a linear model, where price is the target you must predict (so it may never appear inside a feature). Design four engineered features — one each of the four operations from the taxonomy above (ratio, difference, interaction, polynomial) — justify each in one line, and name the tool from the connections list you'd use to prevent the resulting feature blow-up.
Recall Solution
A defensible set (many valid answers — the reasoning is graded). Crucially, none of these use price, because feeding the target into a feature is data leakage that makes the model look perfect in training and useless in production:
- Ratio —
sqft_per_bedroom = sqft / (bedrooms + 1): exposes how spacious each room is, scale-invariant to house size. (The guards against dividing by zero for a listing recorded with bedrooms.) - Difference —
age = current_year − year_built: rawyear_builtis a meaningless absolute number; the age (a difference of two years) is what depreciates value. This is the difference operation from the taxonomy. - Interaction —
sqft × bedrooms: extra floor area is worth more when there are more rooms to place it in — a joint effect a plain sum can't express. - Polynomial —
age²: value often drops fast then levels off (or historic homes regain value) — an inverted-U/curved effect needs the squared term.
Blow-up control: apply Regularization (L1, L2) — specifically L1 to zero-out useless engineered columns — and validate the whole pipeline with Cross-Validation so you never judge features on the training set alone. For a tree-based baseline, Decision Trees and Random Forests can find some interactions automatically, giving you a sanity check on which engineered terms actually help.
L5.2
Problem. Prove the general claim behind interactions: for the model , show algebraically that the rate of change of with respect to depends on , and state what "moderation" means in one sentence.
Recall Solution
Factor out : The coefficient multiplying is . Because sits inside it, the slope of in the direction is — it moves as moves. (Formally, the partial derivative .)
Moderation: when the effect of one variable on the outcome depends on the level of a second variable, the second variable is said to moderate the first — and the interaction term is exactly how a linear model encodes it.
Figure 2 — moderation as fanning lines. A family of -vs- lines, one per value of : as grows the lines fan out (different slopes). Flat, parallel lines would mean no interaction; the fanning is the moderation.
