Worked examples — Feature creation and interaction terms
This page is the "no scenario left behind" drill for feature creation. The parent note showed you the ideas; here we hit every case class that feature engineering can throw at you — with numbers you can check by hand.
Before we start, one plain-words reminder so nothing is assumed:
The scenario matrix
Every worked example below is tagged with the cell of this matrix it covers. The goal: by the last example you have seen at least one number from each row.
| Cell | Case class | What makes it tricky |
|---|---|---|
| A | Polynomial, positive inputs | ordinary expansion, count features |
| B | Interaction with a 0/1 (binary) flag | term switches ON/OFF |
| C | Interaction with a negative input | sign flips the joint effect |
| D | Ratio feature, safe denominator | scale-invariance |
| E | Ratio feature, denominator → 0 | degenerate / divide-by-zero |
| F | Both inputs zero (degenerate) | interaction collapses, main effects vanish |
| G | Limiting value (feature → very large) | which term dominates, overfitting smell |
| H | Real-world word problem | translate English → features |
| I | Exam-style twist | "drop main effects" trap, interpretation |
Let's fill every cell.
Cell A — Polynomial features, all positive
Step 1 — List the degree-2 features. Why this step? A degree-2 expansion adds every product you can build using at most two of the originals, counting repeats: , , , plus the two degree-1 terms and .
Step 2 — Multiply each by its weight and sum. Why this step? This is literally what the linear model computes: dot the weights into the features, add bias.
Step 3 — Arithmetic. Why this step? Keep signs honest: the and terms are negative (too hot / too much rain hurts), the interaction is the big positive contributor.
Verify: Recompute grouped by sign: positives , negatives , difference . ✓ Answer sits near 250, as the forecast anchor suggested.
Cell B — Interaction with a binary flag (switch ON/OFF)
Step 1 — Set (weekday). Why this step? Multiplying by switches the interaction and the weekend main effect off. Slope of is .
Step 2 — Set (weekend). Why this step? Now the interaction term is alive, so it adds to the slope, not just the intercept. Slope of is .
Step 3 — Ratio of slopes. Why this step? "How much more effective" is a comparison of slopes, not intercepts.
Step 4 — Predict at . Weekday: . Weekend: .
Verify: The gap should equal the weekend-only terms: . ✓

Look at the figure: two straight lines share nothing but the same -axis. The interaction tilts the weekend line upward — its steeper slope is the whole point.
Cell C — Interaction with a negative input (sign flip)
Step 1 — Plug the numbers. Why this step? is negative because it's colder than pleasant. The interaction inherits that sign.
Step 2 — Evaluate term by term. Why this step? The interaction is negative, so a positive weight produces a negative contribution. High humidity on a cold day reduces the (heat-based) discomfort score in this model — the sign of flipped the joint effect's direction.
Verify: Flip to a hot day , same : . Same magnitudes, opposite interaction sign. ✓ This is exactly why we never assume interaction terms are positive.
Cell D — Ratio feature, safe denominator
Step 1 — Build the ratio for X.
Step 2 — Build the ratio for Y. Why this step? Division normalizes by scale. The raw debt is identical (), so a model on raw features sees them as equal — the ratio is what reveals Y carries a heavier relative burden.
Verify: Units cancel: dollars ÷ dollars = dimensionless. A ratio means debt exceeds income; , so Y is flagged riskier. ✓ Scale-invariance confirmed — see Feature Scaling and Normalization for why unit-free features behave nicely.
Cell E — Ratio feature, denominator → 0 (degenerate)
Step 1 — Try the naive formula. Why this step? You must see the failure. A NaN silently poisons gradients — the whole model can produce NaN loss.
Step 2 — Add a smoothing prior (pseudocounts ). Here: . Why this step? Adding to the denominator guarantees it is never zero, and the prior is a sensible "unknown ad" baseline click rate. Note this is not classical Laplace (add-one) smoothing, which would use the same constant top and bottom (); here we deliberately pick so the prior encodes a realistic 1% click rate rather than 50%.
Step 3 — Check it converges to the raw ratio for big data. With clicks=500, impressions=10000: , vs raw .
Why this step? The smoothing must vanish as data grows — otherwise you'd bias real measurements.
Verify: Smoothed value differs from raw by about — negligible at scale, life-saving at zero. ✓
Cell F — Both inputs zero (interaction collapses)
Step 1 — Substitute zeros. Why this step? Every feature term, including the interaction, is multiplied by a zero factor, so all vanish. Only the bias survives.
Verify: This is the definition of the bias : the prediction with no signal. . ✓ Whenever you doubt a model, plug all-zeros — you should recover exactly .
Cell G — Limiting value (which term dominates)
Step 1 — Evaluate at three scales. Why this step? The quadratic term grows faster than the linear term . Doubling quadruples the term but only doubles the term.
Step 2 — Find the turning point with a derivative. The peak of a smooth curve is where its slope is zero. The slope of is its derivative Why a derivative? The derivative measures the instantaneous slope of the curve; at a maximum the curve momentarily stops rising, so its slope is exactly . Setting gives , and . Why this matters? Beyond the slope goes negative and falls — a warning that high-degree features extrapolate wildly and invite overfitting. Tame them with Regularization (L1, L2).
Verify: is larger than and (which are symmetric about the peak). ✓ Symmetry of a parabola confirms is the max.

What to see in the figure. The magenta curve rises steeply near , flattens to its top at the orange dot ( — the dashed violet line marks it), then bends back down and crosses zero near . Trace the curve left to right and notice the slope shrinking to zero at the peak and then turning negative: that visual "bend" is exactly what the derivative computes. The plunge on the right is the quadratic term overpowering the linear one — the geometric picture of why unchecked polynomial features extrapolate to nonsense.
Cell H — Real-world word problem
Step 1 — Convert degree gaps to radians. Why this step? Trig functions () take radians, not degrees. This is the #1 silent bug in geo features.
Step 2 — Haversine core. Why this step? Cities lie on a sphere; straight-line coordinate differences would ignore curvature. Haversine gives true great-circle distance.
Step 3 — Distance. Why this step? The raw four coordinates never encode "distance" — this single engineered feature is the primary driver of fare (parent note, geospatial example).
Verify (back-of-envelope): Break the trip into a north–south leg and an east–west leg.
- North–south: of latitude is always km, so gives km.
- East–west: at latitude , lines of longitude are squeezed together by a factor (they meet at the poles), so of longitude spans only km. With , the gap ( rad) gives km.
Combine the two perpendicular legs with Pythagoras: km. ✓ Lands near the "15 km" forecast anchor and within about km of the exact Haversine value km (the small gap comes from our flat-plane approximation of a curved surface). The factor is essential — without it you'd overcount the east–west distance.
Cell I — Exam-style twist (the "drop the main effects" trap)
Step 1 — Compute the true value.
Step 2 — Show the interaction alone cannot separate two points. The interaction feature value is . The same arises from , , — all give the same feature but different true . True at is . Why this step? Both points force the model to output the same , but the truths differ.
Step 3 — Quantify the unavoidable error. Whatever the student chooses, both points get the identical prediction . The kindest choice is the midpoint of the two truths, With that best-possible , the absolute error at each point is Why this step? Because a single number () must serve two different targets, the best it can do is sit halfway, leaving an error of at each point. The irreducible spread the interaction-only model can never resolve is units — that is precisely the information the dropped main effects carried. See Linear Regression hypothesis space and the parent note's Mistake 2.
Verify: while both have ; the irreducible spread is , and the best-case error at the split point is . ✓ No single fits both.
Recall Self-test: which cell?
A model outputs exactly its bias term. Which matrix cell? ::: Cell F (all inputs zero)
You feed impressions = 0 into clicks/impressions. Which cell, and the fix? ::: Cell E; add a smoothing prior so the denominator is never zero
Two people have identical raw debt but the model ranks them differently. What feature made that possible? ::: Cell D — a ratio (debt-to-income), which is scale-invariant
Why does a degree-2 poly on 2 features give 5 new columns, not 6? ::: ; we subtract the constant term because it duplicates the bias
An interaction term went negative even with a positive weight. What caused it? ::: Cell C — one input was negative, flipping the product's sign
See also: Feature Selection Methods and Cross-Validation to decide which of these engineered features actually earn their place; Decision Trees and Random Forests can learn some interactions automatically; start every project with Exploratory Data Analysis to know which cells you'll even face.