Skip to content

← Regression from Scratch step 2 of 4

Medium End-to-End

Polynomial Regression

A polynomial model predicts an output by adding weighted powers of its input. For example, weights [2, -3, 1] describe 2 - 3*x + x**2. The coefficients are supplied in this exercise: compute predictions and their mean squared error without fitting or updating the weights.

Your task

Implement polynomial_regression(x, w, y) for floating-point inputs:

  • x has shape (N,), with N >= 1.
  • w has shape (d + 1,), with at least one coefficient.
  • y contains targets of shape (N,).

Infer d from the length of w; there is no separate degree argument. Coefficients are ordered by increasing power: w[0] is the constant term, w[1] multiplies x, and w[d] multiplies x**d.

Build a feature matrix phi of shape (N, d + 1). Row i is [1, x[i], x[i]**2, ..., x[i]**d]. Its first column is always one, including when x[i] is zero. Then compute:

prediction = phi @ w
loss = mean((prediction - y)**2)

Return a dictionary with "prediction" of shape (N,) and "loss" as a scalar number. Average over all N examples, with no square root or one-half factor. Preserve the inputs.

Example

For x = [-1, 0, 2] and w = [2, -3, 1], predictions are [6, 2, 0]. With targets [5, 4, 0], squared errors are [1, 4, 0], so the loss is 5/3.

The constant term already acts as an intercept; do not add another bias. If w contains only one value, every prediction is that value. Although powers allow a curved relationship with x, the prediction remains linear in the coefficients: each coefficient multiplies one fixed feature.