Click4Ai

53.

Medium

Implement a **create_polynomial_features(X, degree)** function that transforms a 1D input array into a matrix of polynomial features.

Transformation:

Given X = [x1, x2, ...] and degree = d

Output a matrix where each row i is: [x_i, x_i^2, x_i^3, ..., x_i^d]

The output should be a 2D numpy array of shape (n_samples, degree).

Example:

X = [2, 3]

degree = 3

Output:

[[2, 4, 8], # [2^1, 2^2, 2^3]

[3, 9, 27]] # [3^1, 3^2, 3^3]

**Explanation:** Each sample x is expanded into [x, x^2, x^3, ..., x^degree]. This allows a linear model to fit polynomial curves.

Constraints:

  • X is a 1D numpy array of length n
  • degree is a positive integer >= 1
  • Return shape must be (n, degree)
  • The first column is x^1 (not x^0)
  • Test Cases

    Test Case 1
    Input: X=[2, 3], degree=3
    Expected: [[2, 4, 8], [3, 9, 27]]
    Test Case 2
    Input: X=[1, 2, 3], degree=2
    Expected: [[1, 1], [2, 4], [3, 9]]
    Test Case 3
    Input: X=[5], degree=1
    Expected: [[5]]
    + 2 hidden test cases