smartyfy.mrindigi.com

AI & Machine Learning Master Course — 044. Feature interactions and polynomial models

Smartyfy AI & Machine Learning Master Course

Course ID: smartyfy-ai-ml-master-200

Lesson 044: Feature interactions and polynomial models

Prerequisites: Lesson 043. Learning outcome: Build interactions and assess whether added flexibility generalizes.

1. Linear coefficients can describe nonlinear shapes

A linear model is linear in its fitted coefficients, not necessarily in the raw input. The equation prediction = b + w₁x + w₂x² is a quadratic curve as x varies, yet remains a linear combination of three fixed feature functions. Least squares can fit its coefficients using the same machinery as an ordinary multifeature model.

This distinction lets us improve a limited representation without immediately adopting a more complicated estimator. The curved residual pattern from Lesson 043 suggests that x² may contain missing structure. Feature expansion proposes a richer vocabulary of shapes. Validation must still decide whether that richer vocabulary improves predictions beyond the training sample.

2. Interactions make one association depend on another input

An additive model b + w₁x₁ + w₂x₂ assigns the same change per unit of x₁ regardless of x₂. Adding w₁₂x₁x₂ allows the slope with respect to x₁ to become w₁ + w₁₂x₂. For a parcel, mass may have a different association with handling duration depending on route difficulty. An interaction can represent that dependence.

Consider prediction =1 +2m +3r +4 mr. At mass m=2 and route score r=3, the prediction is 1+4+9+24=38. Increasing mass by one changes the fitted prediction by 2+4r=14 at that route score. A coefficient of two on mass now describes its slope when r=0, rather than a universal mass effect.

Keep main effects when including an interaction unless the application provides a reason for another structure. Centering inputs can make the main-effect interpretation more useful: a zero centered route value corresponds to the training reference level rather than necessarily a physically absent route. Centering statistics must be learned from the relevant training partition.

Input mass 2 and route 3 expands to features mass, route, mass squared, mass times route, route squared with values 2, 3, 4, 6, 9. A plot shows p = 1 + 2m for route 0 and p = 10 + 14m for route 3. On the latter line, mass 2 predicts 38 and mass 3 predicts 52, a rise of 14.
The product feature makes the mass slope depend on route score. A model can remain linear in its coefficients while expressing context-dependent slopes. Open full-size diagram

3. Inspect the expansion before fitting

With two inputs and degree two, a full polynomial expansion contains a constant, both original inputs, their squares, and their product. If the estimator already fits an intercept, set include_bias=False to avoid a duplicate constant column. The code then produces mass, route, mass², mass×route, route² in a documented order.

For input [2, 3], these features are[2, 3, 4, 6, 9]. With interaction_only=True, squares are excluded while products of distinct input features remain. That option does not mean the model contains only product terms: the original degree-one inputs also remain under the ordinary configuration.

The number of terms grows rapidly with feature count and degree. Ten inputs expanded through degree three produce 286 terms including the constant. This is a combinatorial growth issue, not just a few extra columns. High powers can also create large numerical scales and correlated columns. Use a restrained candidate set, appropriate scaling, and regularization where justified.

4. Flexibility can fit noise and extrapolate badly

A higher-degree curve can reduce training error by following random fluctuations. That does not show better prediction on new observations. Compare a small, prespecified range of degrees using development validation, keeping the feature expansion and any learned preprocessing inside the evaluated pipeline.

Polynomial extrapolation can be especially unstable. A curve that behaves smoothly within the observed range may grow rapidly outside it because its highest power dominates. Mark the training support and assess whether new inputs lie outside it. Clipping predictions or limiting inputs is a separate policy requiring validation; it should not be silently added after observing a failure.

Expanded coefficients also depend on the chosen basis. Raw polynomial terms, centered terms, and other bases can describe the same family with different coefficient values. Avoid ranking importance by coefficient magnitude across these representations. Focus on predictions, suitable contrasts, stability, and the substantive meaning of the proposed feature relationships.

CPU lab: recover a quadratic signal

This CPU example uses NumPy and scikit-learn and was executed with versions 2.3.5 and 1.8.0. It first verifies the two-input expansion exactly, then compares degree one and degree two on thirty noiseless observations generated by y=1+2x+3x². Five fixed development folds evaluate each complete pipeline.

Mean validation MSE is about 15.9198 for degree one and effectively zero for degree two. The result is expected because the second representation contains the exact synthetic formula and there is no noise. It demonstrates representational capacity, not a claim that quadratic models reliably achieve zero error or outperform other methods on real datasets.

import numpy as np
from sklearn.preprocessing import PolynomialFeatures, StandardScaler
from sklearn.pipeline import make_pipeline
from sklearn.linear_model import LinearRegression
from sklearn.model_selection import KFold, cross_val_score
small = np.array([[2.,3.]])
poly = PolynomialFeatures(degree=2, include_bias=False)
print('Names:',poly.fit(small).get_feature_names_out(['mass','route']).tolist())
print('Values:',poly.transform(small).tolist())
assert poly.transform(small).tolist()==[[2.,3.,4.,6.,9.]]
x = np.linspace(-2,2,30)[:,None]
y = 1 + 2*x[:,0] + 3*x[:,0]**2
cv = KFold(5,shuffle=True,random_state=4)
for degree in [1,2]:
    model = make_pipeline(PolynomialFeatures(degree=degree,include_bias=False),
                          StandardScaler(),LinearRegression())
    errors = -cross_val_score(model,x,y,cv=cv,scoring='neg_mean_squared_error')
    print('Degree',degree,'mean validation MSE',round(errors.mean(),8))
interaction = 1 + 2*small[0,0] + 3*small[0,1] + 4*small[0,0]*small[0,1]
print('Interaction prediction:',interaction)

Four practice questions with worked answers

Practice 1

Expand inputs[2, 3] through degree two without a constant column.

Answer: Keep the original values 2 and 3, then add 2²=4, the product 2×3=6, and 3²=9. The resulting row is[2, 3, 4, 6, 9]. Confirm the transformer’s feature-name output so these values are aligned with the intended columns rather than guessed from memory.

Practice 2

For prediction 1+2m+3r+4 mr, what is the change when mass increases from 2 to 3 at route score 3?

Answer: At mass 2 the prediction is 38. At mass 3 it is 1+6+9+36=52, so the difference is 14. Equivalently, the mass slope is 2+4r=14. This shows that a main-effect coefficient does not represent a constant slope once interactions are present.

Practice 3

A degree-seven model has smaller training error than degree two. What additional evidence is needed?

Answer: Compare them on appropriately separated development validation using the same target and metric. Inspect variation across folds, extrapolation behavior, and numerical stability. If model choice uses those results, reserve final assessment for independent data or a valid outer evaluation loop rather than reporting training fit as generalization.

Practice 4

Why might centering route score help interpretation when an interaction is included?

Answer: The main mass coefficient describes the mass slope where the represented route score equals zero. Centering at the training mean moves that reference to an observed typical route score. It changes coefficient interpretation without necessarily changing the model family, while requiring that the learned center remain fixed for held-out transformations.

Five multiple-choice questions

Question 1

Is a quadratic feature model linear in its coefficients?

  • A. Only without an intercept
  • B. No
  • C. Yes

Correct: C. The coefficients multiply fixed features such as x and x². The resulting function can be nonlinear in the raw input.

Question 2

What does an interaction term allow?

  • A. Unlimited reliable extrapolation
  • B. Guaranteed causality
  • C. One feature’s fitted slope to depend on another

Correct: C. A product term changes conditional slopes. It does not establish causal mechanisms or out-of-range validity.

Question 3

Why set include_bias=False with an intercept-fitting estimator?

  • A. To avoid a duplicate constant column
  • B. To improve every score automatically
  • C. To remove every coefficient

Correct: A. The estimator already supplies the constant term. This avoids unnecessary redundancy in the design.

Question 4

What does interaction_only exclude in a degree-two expansion?

  • A. All original features
  • B. Squared individual features
  • C. Products of distinct features

Correct: B. It retains interactions between distinct inputs but excludes powers such as x₁² under this configuration.

Question 5

Which statement about higher degree is sound?

  • A. More terms increase capacity and require validation
  • B. Extrapolation becomes automatically safer
  • C. Training improvement proves future improvement

Correct: A. Additional flexibility can represent useful structure or fit noise; validation and support checks distinguish the possibilities.

Common pitfalls

Do not expand arbitrary identifiers into polynomial powers. Do not choose degree on the final test set. Avoid forgetting that feature expansion changes dimensions, scales, and interpretation; a successful matrix transformation alone does not justify the represented relationships.

Summary

Polynomial features and interactions extend a linear estimator’s vocabulary. Inspect exact terms, interpret slopes conditionally, and validate restrained complexity. A richer basis can capture real structure while increasing instability, overfitting risk, and extrapolation hazards.

Primary sources and further reading