EasyFeature Engineering

Polynomial Features

Feature Engineering

Easy

Problem

Polynomial feature expansion represents one numeric value using successive powers. This allows a linear model to learn relationships such as curves when the expanded values are supplied as separate features.

For each input value, generate powers from zero through degree:

\phi(x) = [1, x, x^2, \ldots, x^d]

Here, x is an input value, d is the maximum degree, and the resulting vector is the expanded feature row. The first element is always 1 and serves as the intercept feature. Return one row containing degree + 1 values for every input value.

Theory

Polynomial features are new features created by raising existing features to powers and computing all cross-products up to a specified degree. This allows linear models to learn non-linear relationships by fitting a polynomial function to the data.

For a single feature x, degree-2 polynomial features are: $ x, x^2$

For two features x_1, x_2, degree-2 polynomial features are: $ x_1, x_2, x_1^2, x_1 x_2, x_2^2$


Why Use Polynomial Features?

1. Capture non-linear relationships:

Real-world relationships are often non-linear. Polynomial features allow linear models to fit curves.

2. Model interactions:

Cross-product terms (x_1 x_2) capture how features interact.

3. Improve model flexibility:

Adding polynomial features increases the hypothesis space of the model.

4. Simple implementation:

Feature engineering that does not require domain expertise.


Mathematical Foundation

A polynomial of degree d in one variable:

f(x) = \beta_0 + \beta_1 x + \beta_2 x^2 + ... + \beta_d x^d

This is linear in the coefficients \beta_i but non-linear in x.

By treating each x^k as a separate feature, we can use linear regression to fit polynomial curves.


Single Variable Example

Original feature: x

Degree 2 polynomial features:

[1, x, x^2]

Degree 3 polynomial features:

[1, x, x^2, x^3]

Degree d polynomial features:

[1, x, x^2, ..., x^d]


Worked Example: Single Variable

Original data: x = [1, 2, 3, 4, 5]

Degree 2 transformation:

For x = 2:

Full transformation:


Two Variables: Degree 2

Original features: x_1, x_2

Degree 2 polynomial features:

[1, x_1, x_2, x_1^2, x_1 x_2, x_2^2]

Components:


Worked Example: Two Variables

Original features: x_1 = 2, x_2 = 3

Degree 2 polynomial features:

Result: [1, 2, 3, 4, 6, 9]


General Formula for Feature Count

For n input features and degree d:

Number of polynomial features (including bias):

\binom{n + d}{d} = \frac{(n + d)!}{n! \cdot d!}

Examples:


Feature Explosion Warning

Polynomial features grow rapidly with degree and number of input features:

n = 20 features:

Consequences:


Degree 2: Most Common Choice

Degree 2 is the most commonly used because:

1. Captures most important non-linearities:

Quadratic terms and pairwise interactions handle many real-world patterns.

2. Manageable feature count:

Growth is O(n^2) rather than higher.

3. Interpretable:

Squared terms and interactions have clear meanings.

4. Less prone to overfitting:

Higher degrees often memorize training data.


Polynomial Regression Model

With degree-2 polynomial features for one variable:

y = \beta_0 + \beta_1 x + \beta_2 x^2

This fits a parabola to the data.

Interpretation:


With Interactions

For two variables with degree 2:

y = \beta_0 + \beta_1 x_1 + \beta_2 x_2 + \beta_3 x_1^2 + \beta_4 x_1 x_2 + \beta_5 x_2^2

\beta_4 x_1 x_2 captures:

How the effect of x_1 on y changes depending on the value of x_2 (and vice versa).


Interaction-Only Option

Sometimes you want interactions without squared terms:

Original: x_1, x_2, x_3

Interaction-only (no powers):

[1, x_1, x_2, x_3, x_1 x_2, x_1 x_3, x_2 x_3]

This is useful when individual feature effects are already captured but interactions are needed.


Scaling Before Polynomial Transformation

Important: Scale features before computing polynomial features.

Without scaling:

Large values can cause numerical instability.

With scaling to [0, 1] first:

Values remain manageable.


Regularization with Polynomial Features

More features increase overfitting risk. Use regularization:

Ridge regression (L2):

\text{minimize } ||y - X\beta||^2 + \lambda ||\beta||^2

Lasso (L1):

\text{minimize } ||y - X\beta||^2 + \lambda ||\beta||_1

Lasso can set some polynomial coefficients to zero, performing feature selection.


Bias-Variance Tradeoff

Low degree (underfitting):

High degree (overfitting):

Optimal degree:

Use cross-validation to find the right balance.


Choosing the Degree

Methods:

  1. Cross-validation: Test degrees 1, 2, 3, ... and select based on validation error

  2. Domain knowledge: Physics or domain constraints may suggest appropriate degree

  3. Visual inspection: Plot data and fitted curves to assess fit quality

  4. Information criteria: AIC or BIC penalize model complexity


Polynomial Features vs Other Non-Linear Models

Polynomial features + Linear model:

Decision trees:

Neural networks:


Computational Considerations

Memory:

Polynomial transformation can vastly increase data size.

Sparse data:

If original data is sparse, polynomial features may still be sparse (products of zeros are zero).

Online computation:

For streaming data, polynomial features can be computed on the fly.


Example Application: Price Prediction

Original features:

Polynomial degree 2:

Model can learn:

Large houses might not benefit as much from additional bedrooms (captured by interaction term).


Centered Polynomial Features

To reduce correlation between terms, center features first:

x' = x - \bar{x}

Then compute polynomials of x'.

Benefit:


Orthogonal Polynomials

An alternative to raw polynomials:

Raw polynomials: 1, x, x^2, x^3, ...

Orthogonal polynomials: P_0(x), P_1(x), P_2(x), ...

Examples: Legendre, Chebyshev, Hermite polynomials

Benefit: Orthogonal features are uncorrelated, improving numerical stability and interpretability.


When to Use Polynomial Features

Good scenarios:

Avoid when:


Common Mistakes

1. Not scaling first:

Large polynomial terms cause numerical issues.

2. Too high degree:

Degree 10 polynomial almost always overfits.

3. Ignoring multicollinearity:

Polynomial terms are highly correlated; use regularization.

4. All features with high degree:

Apply polynomial only to features where non-linearity is suspected.

5. Forgetting to apply to test data:

Same transformation must be applied to new data.


Best Practices

1. Start with degree 2:

Most non-linear patterns can be captured with quadratic terms.

2. Scale features first:

Normalize or standardize before polynomial expansion.

3. Use regularization:

Ridge or Lasso to prevent overfitting.

4. Cross-validate the degree:

Do not assume higher is better.

5. Consider selective expansion:

Apply polynomials only to features that need it.

Examples

Example 1

Input
values = [2, 3], degree = 2
Output
[[1, 2, 4], [1, 3, 9]]
Explanation
Each row contains powers zero, one, and two of its input value.

Example 2

Input
values = [-2], degree = 3
Output
[[1, -2, 4, -8]]

Hints

  1. Use range through degree inclusive for each input value.
  2. Raise the value to every exponent, including zero for the intercept feature.

Requirements

Constraints

Starter Code

def polynomial_features(values: list, degree: int) -> list:
    """
    Returns powers from zero through degree for every value.
    """
    # Write code here
    pass

Test Cases

CaseMatches
deg2public
negpublic