Unit 4, lesson 23

Polynomial Features and Interactions

How feature engineering adds polynomial features, indicator variables, interaction terms and spline basis functions to a linear model, why the model stays linear in parameters, and how to build them without leakage.

  • Video 23
  • Feature Engineering and Regularization

Daily demand for a constructed product rises with temperature, curves upward, and climbs faster in summer than in winter. A straight line in temperature cannot draw that, yet ordinary least squares can still fit it once the design matrix contains the right columns. This lesson builds those columns from temperature and season, explains why the model stays linear in its coefficients while its predictions curve, and shows which construction steps must be learned from training data alone.

Key terms

Feature engineering

Definition Feature engineering is the construction of the columns of the design matrix from the raw inputs. A feature map ϕ\boldsymbol{\phi} sends each raw input x\mathbf{x} to a feature vector ϕ(x)\boldsymbol{\phi}(\mathbf{x}) in Rp\mathbb{R}^p, and the model is then fitted on the rows ϕ(xi)\boldsymbol{\phi}(\mathbf{x}_i). Every quantity the map takes from data, such as means and scales, a category vocabulary or knot locations, is part of the fitted procedure. It is learned from the training rows only, inside each training fold when cross-validation is used, saved, and applied unchanged to validation, test and future rows. Construction choices such as the polynomial degree or which interactions to include are made with validation data, never with the test set. Fixed arithmetic with constants chosen in advance needs no data, and every raw input that the map uses has to be available at prediction time.

In plain words A linear model can only combine the columns it is given, so choosing the columns decides which shapes of relationship it can express. Building them is part of training, and anything learned while building them must come from the same rows as the coefficients.

Example For demand with temperature TT in degrees Celsius and a season of winter, summer or spring, let u=(T−20)/10u = (T - 20)/10, where 2020 and 1010 are reference values fixed in advance rather than statistics of the data. The feature vector is ϕ=(1,u,u2,S,P,uS)\boldsymbol{\phi} = (1, u, u^2, S, P, uS), where SS and PP indicate summer and spring. A constructed model on these features is

y^=30+4u+2u2+8S−3P+5uS.\begin{aligned} \hat{y} &= 30 + 4u + 2u^2 \\[0.4em] &\quad + 8S - 3P + 5uS . \end{aligned}

Because uu has no unit, each coefficient is in demand units. If uu were instead standardized with the mean and standard deviation of temperature, those two numbers would have to come from the training rows.

Basis function

Definition Basis functions are fixed functions ϕ0,ϕ1,…,ϕp−1\phi_0, \phi_1, \dots, \phi_{p-1} of the raw input, and a basis expansion model predicts

f(x;β)=∑j=0p−1βjϕj(x).f(\mathbf{x}; \boldsymbol{\beta}) = \sum_{j=0}^{p-1} \beta_j \phi_j(\mathbf{x}) .

Such a model is linear in parameters, meaning that for every fixed input the prediction is a linear function of the coefficient vector β\boldsymbol{\beta}. Its dependence on the raw input can be strongly nonlinear. Let Φ\Phi be the design matrix with entries Φij=ϕj(xi)\Phi_{ij} = \phi_j(\mathbf{x}_i). Fitting by squared error is then ordinary least squares on Φ\Phi, its objective is a convex quadratic in β\boldsymbol{\beta}, and the coefficients are unique exactly when Φ\Phi has full column rank. A model such as f(x)=β0+eβ1xf(x) = \beta_0 + e^{\beta_1 x} is not linear in parameters.

In plain words Each basis function supplies one column, and the model is a weighted sum of columns. Linearity refers to the weights, not to the shape of the curve, so curved predictions can still be fitted with the linear algebra of least squares.

Example The demand model has the six basis functions 11, uu, u2u^2, SS, PP and uSuS. Its summer predictions at 1010, 2020 and 3030 degrees are 3131, 3838 and 4949, which rise by 77 and then by 1111, so they do not lie on a straight line in temperature. Nine constructed rows, one for each season at each of the three temperatures, give a 9×69 \times 6 design matrix of rank 66, and least squares on targets generated without noise from the model returns exactly the coefficients 3030, 44, 22, 88, −3-3 and 55. That recovery checks the construction. It says nothing about whether real demand follows this formula.

Polynomial feature

Definition A polynomial feature is a power of an input, such as u2u^2 or u3u^3, or a product of powers of several inputs. A polynomial model of degree dd in one input uses the basis 1,u,…,ud1, u, \dots, u^d. With qq raw inputs, all products of powers with total degree at most dd give (q+dd)\binom{q + d}{d} columns including the constant, so the count grows quickly, to 6666 columns for q=10q = 10 and d=2d = 2. The coefficient of a single power is not a slope. The rate of change is a derivative that combines several coefficients, for example β1+2β2u\beta_1 + 2\beta_2 u for the model β0+β1u+β2u2\beta_0 + \beta_1 u + \beta_2 u^2.

In plain words Squares and higher powers let a fitted curve bend. When an input’s values lie far from zero compared with their spread, its powers are nearly collinear, so it helps to center and scale the input before taking powers. Outside the observed range a polynomial is driven by its highest power and can quickly become implausible.

Example Winter demand is 30+4u+2u230 + 4u + 2u^2, which is 2828, 3030 and 3636 at 1010, 2020 and 3030 degrees. Its rate of change is 4+4u4 + 4u per unit of uu, which is 00, 44 and 88 at those temperatures, or 00, 0.40.4 and 0.80.8 demand units per degree, since one unit of uu is ten degrees. Over the nine rows the raw temperature and its square have correlation about 0.990.99, while uu and u2u^2 have correlation 00. At 6060 degrees, far outside the observed range of 1010 to 3030 degrees, u=4u = 4 and the summer prediction is 106106, a number with no data behind it.

Interaction term

Definition An interaction term is the product of two features, such as uSuS. In a model containing uu, SS and uSuS, the change in prediction that goes with one of them depends on the value of the other. For the demand model

∂y^∂u=4+4u+5S,\frac{\partial \hat{y}}{\partial u} = 4 + 4u + 5S,

and the summer minus winter difference at the same temperature is 8+5u8 + 5u. Without the product, the difference between seasons would be the same at every temperature. A model with an interaction usually also keeps both features of the product, because dropping one imposes a restriction whose meaning depends on where the zero of the other is placed. An interaction describes how predictions vary, and it has a causal reading only when the design of the study or further assumptions support one.

In plain words The product switches on an extra temperature effect only in summer, so the summer curve can be steeper than the winter curve. The season coefficient then gives the gap at one temperature only, the one where u=0u = 0.

Example The gap 8+5u8 + 5u equals 33, 88 and 1313 at 1010, 2020 and 3030 degrees, so the coefficient 88 is the gap at 2020 degrees only. At 2020 degrees the temperature slope is 44 per unit of uu in winter and 99 in summer, which is 0.40.4 and 0.90.9 demand units per degree. The model has no spring interaction, so the spring and winter curves have the same shape and differ by 33 at every temperature. That is a modeling restriction, and adding uPuP would remove it at the cost of one more coefficient.

Indicator variable

Definition An indicator variable equals 11 when a condition holds and 00 otherwise. A categorical input with KK categories enters a model with an intercept through K−1K - 1 indicators, and the omitted category is the reference. Adding an indicator for the reference category as well makes the KK indicators sum to the column of ones, so the design matrix loses full column rank. The fitted values stay unique, but the coefficients do not. Dropping the intercept and keeping all KK indicators is the other valid coding. The vocabulary of categories is fixed during training and saved in order. A category that never appeared in training needs an explicit policy, such as raising an error or routing it to a designated category for rare or unknown values that already exists in training, because silently setting all indicators to 00 treats it as the reference category.

In plain words Indicators let each category have its own level without pretending the labels are numbers. With an intercept one category is left out, and every indicator coefficient is a difference from that baseline.

Example Winter is the reference, S=1S = 1 for summer and P=1P = 1 for spring. A spring day has S=0S = 0 and P=1P = 1, and its prediction is 33 below winter at the same temperature. If a winter indicator WW is added next to the intercept, then W+S+P=1W + S + P = 1 on every row, and the nine-row design matrix with seven columns has rank 66. Adding 44 to the intercept and subtracting 44 from each of the three season coefficients then leaves every prediction for a known season unchanged. A test row labeled autumn has no indicator of its own, and encoding it as all zeros under the two-indicator coding would quietly give it the winter prediction.

Spline

Definition A spline in one input is a function built from polynomial pieces on the intervals between chosen points ξ1<⋯<ξK\xi_1 < \dots < \xi_K, called knots, with the pieces joined so that the function, and possibly some of its derivatives, is continuous at each knot. With the hinge functions (u−ξk)+=max⁡(0,u−ξk)(u - \xi_k)_+ = \max(0, u - \xi_k), every continuous piecewise linear function with these knots can be written as

f(u)=β0+β1u+∑k=1Kγk(u−ξk)+,\begin{aligned} f(u) &= \beta_0 + \beta_1 u \\[0.4em] &\quad + \sum_{k=1}^{K} \gamma_k (u - \xi_k)_+ , \end{aligned}

whose slope changes by γk\gamma_k at the knot ξk\xi_k. Cubic splines use pieces of degree three whose values and first two derivatives agree at each knot. Once the knots are fixed, a spline is linear in parameters and is fitted by least squares like any other basis. Knots placed using data, for example at quantiles of the input, are learned from the training rows only.

In plain words A spline lets the curve change its shape at chosen places without jumping. With the other coefficients fixed, changing the coefficient of a hinge changes predictions only to the right of its knot, while changing the coefficient of a power in a global polynomial changes predictions at every input where that power is not zero. Local bases such as B-splines go further, since each of their basis functions is nonzero only over a few neighboring intervals between knots.

Example With one knot at u=0u = 0, the spline 30+4u+6max⁡(0,u)30 + 4u + 6\max(0, u) has slope 44 per unit of uu below 2020 degrees and slope 1010 above, and both pieces give 3030 at the knot. Its values at u=−1u = -1, 00 and 11 are 2626, 3030 and 4040. Beyond the range of the data its last piece simply continues as a straight line, which is no more trustworthy than the polynomial’s extrapolation.

Check yourself

  1. Using the demand model, build the feature row and the prediction for a 1515-degree summer day and for a 1515-degree spring day. Why is their difference not the same as at 2020 degrees?
Show the answer

At 1515 degrees u=−0.5u = -0.5 and u2=0.25u^2 = 0.25. The summer row is (1,−0.5,0.25,1,0,−0.5)(1, -0.5, 0.25, 1, 0, -0.5), and the prediction is 30−2+0.5+8−2.5=3430 - 2 + 0.5 + 8 - 2.5 = 34. The spring row is (1,−0.5,0.25,0,1,0)(1, -0.5, 0.25, 0, 1, 0), and the prediction is 30−2+0.5−3=25.530 - 2 + 0.5 - 3 = 25.5. The difference is 8.58.5. Only summer has an interaction with uu, so the summer minus spring difference is 8+5u−(−3)=11+5u8 + 5u - (-3) = 11 + 5u, which is 1111 at 2020 degrees and 8.58.5 at 1515 degrees.

  1. An analyst encodes the season with an intercept and indicators for all three seasons, and the solver reports that the 9×79 \times 7 design matrix has rank 66. Explain why, and say what goes wrong when a test row labeled autumn is encoded with all three season indicators equal to 00.
Show the answer

Every row belongs to exactly one season, so the three indicators add up to the column of ones and one column is a combination of the others. The other six columns are independent, so the rank is 66. The fitted values are still unique, but the coefficients are not. Adding any number cc to the intercept and subtracting cc from all three season coefficients changes no prediction for a winter, summer or spring row. One least-squares solution has intercept 23.7523.75 and season coefficients 6.256.25, 14.2514.25 and 3.253.25 for winter, summer and spring, and with c=4c = 4 another has 27.7527.75, 2.252.25, 10.2510.25 and −0.75-0.75. Both reproduce the training data exactly. An autumn row with all indicators 00 receives the intercept plus the temperature terms, so at 2020 degrees it gets 23.7523.75 from the first solution and 27.7527.75 from the second. Its prediction depends on an arbitrary choice of the solver, not on the data. Keep an intercept with two indicators, or drop the intercept, and handle a category unseen in training with an explicit policy such as raising an error.

  1. A workflow does four things. It computes u=(T−20)/10u = (T - 20)/10 with the fixed constants 2020 and 1010. It standardizes u2u^2 with the mean and standard deviation of all rows before the test set is split off. It chooses the polynomial degree among 11, 22 and 33 by the smallest test error. It places spline knots at the quartiles of the training temperatures. Which steps are safe, and how would you repair the others?
Show the answer

The first step is safe, because fixed arithmetic on an input available at prediction time uses no information from held-out rows. The second step leaks, since the test rows influence the scaling that the training rows see. Compute the mean and standard deviation from the training rows, inside each training fold under cross-validation, and apply the saved values to every other row. The third step makes the test set part of development, so the test error of the chosen degree is optimistically biased. Choose the degree on validation data or by cross-validation within the training data, then evaluate the frozen choice once on the test set. The fourth step is safe as long as the quartiles are computed from the training rows only, and recomputed inside each training fold when cross-validation is used.

How this lesson connects