Expand features into degree-2 polynomial and interaction terms

Why it matters Polynomial features are the textbook way to let linear and logistic regression model curves, and the column order must match between training and serving.

A linear model on squared and pairwise product features can fit curves and interactions.

Write poly2_features(X, include_bias=True, interaction_only=False). X is a 2D array (n, d). Return a float array whose columns are, in order: a column of ones (if include_bias), each original feature x_0 .. x_{d-1}, then products x_i * x_j for i <= j in order (i outer, j inner). If interaction_only is True, use only i < j (no squares).

Signaturedef poly2_features(X, include_bias=True, interaction_only=False)

Example

X [[2, 3]] gives [[1, 2, 3, 4, 6, 9]].

Understand the idea

A straight line cannot follow a curve, but a linear model can still fit one if we give it extra columns like x^2. With several features we also add products such as x1 * x2, which let the effect of one feature depend on another (rain matters more for delivery time at rush hour).

Worked example: one row with x0 = 2 and x1 = 3. The degree-2 expansion is: bias 1, then 2 and 3, then x0^2 = 4, x0 x1 = 6, x1^2 = 9. So [1, 2, 3, 4, 6, 9]. With interaction_only we keep only the cross term 6, giving [1, 2, 3, 6].

Rule: columns = [1] + [x_i] + [x_i * x_j for i <= j], ordered by i then j.

For d features this adds d(d + 1)/2 columns, so it grows fast. It is used for curve fitting, for factorisation-style interaction features in click models, and as a quick check of whether a model is underfitting.

Shapes and data flow

X (n, d) -> (n, 1 + d + d(d + 1)/2) with bias
solution.pyPython idle
Ctrl/Cmd + Enter runs sample tests

Run checks the first 2 tests. Submit checks all 4.

  • Sample 1: examplepoly2_features([[2, 3]])
  • Sample 2: three featurespoly2_features([[1, 2, 3], [0, -1, 2]])
  • Test 3: interaction only no biaspoly2_features([[1, 2, 3], [4, 5, 6]], include_bias=False, interaction_only=True)
  • Test 4: single featurepoly2_features([[3], [-2]], include_bias=False)