v9.1.1
Menu

Polynomial Feature Expansion

mediumFREELinear RegressionMachine Learning 1

Implement polynomial feature expansion for a single-feature input.

Given a list of values xx and a degree dd, create the expanded feature matrix where each row contains [xi,xi2,xi3,...,xid][x_i, x_i^2, x_i^3, ..., x_i^d].

For example, if x=[2,3]x = [2, 3] and degree =3= 3, the output matrix is: [2483927]\begin{bmatrix} 2 & 4 & 8 \\ 3 & 9 & 27 \end{bmatrix}

Return the feature matrix as a 2D list, with each value rounded to 4 decimal places.

Example

Input
x = [2, 3]
degree = 3
Output
[[2, 4, 8], [3, 9, 27]]
Reasoning
  • Inputs: x holds two samples of a single feature, x1=2x_1 = 2 and x2=3x_2 = 3, and degree d=3d = 3 says how many power terms each sample is expanded into.
  • Row 1 (x1=2x_1 = 2): the powers 11 through 33 give 21=22^1 = 2, 22=42^2 = 4, 23=82^3 = 8, so the row is [2,4,8][2, 4, 8].
  • Row 2 (x2=3x_2 = 3): likewise 31=33^1 = 3, 32=93^2 = 9, 33=273^3 = 27, giving [3,9,27][3, 9, 27].
  • Output: a 2×32 \times 3 matrix [[2, 4, 8], [3, 9, 27]]: one row per sample, one column per power. Column jj is the feature xjx^j, so a linear model on these columns can fit a cubic in xx.
  • Notice: there is no column of ones (x0x^0); the exponents start at 11. The output has dd columns no matter how many samples there are, and fractional inputs such as 0.50.5 shrink with each power (0.5,0.25,0.1250.5, 0.25, 0.125), which is where the 4-decimal rounding matters.

Constraints

  • x is a list of numbers, degree is a positive integer >= 1
  • Return a 2D list where row i has [x_i, x_i^2, ..., x_i^degree]
  • Round each value to 4 decimal places
  • Do NOT include a bias column of ones

Learn this in

More from Machine Learning 1

solution.py

Test results

Sign in to run your code against the test cases.