Skip to content

← Regression from Scratch step 1 of 4

Easy End-to-End

Linear Regression

A one-feature linear model predicts a target from an input using a weight and a bias. This exercise evaluates supplied parameters; it does not fit weights or run an optimizer.

Your task

Implement linear_regression(x, w, b, y) for floating-point arrays:

  • x and y have shape (N, 1), with N positive.
  • w has shape (1, 1) and contains one weight.
  • b has shape (1,) and contains one bias.

Compute predictions and mean squared error:

prediction = x @ w + b
loss = mean((y - prediction)**2)

Return a dictionary with exactly two keys:

  • "prediction": an array of shape (N, 1).
  • "loss": the scalar mean squared error.

Keep the column dimension in prediction and leave inputs unchanged. The bias broadcasts across all N rows. Square each error before averaging; squaring the average error would let opposite-sign errors cancel.

Example

With x = [[1], [2]], w = [[2]] and b = [1], predictions are [[3], [5]]. If targets are [[4], [3]], the errors are 1 and -2, so the loss is (1**2 + (-2)**2) / 2 = 2.5.

This is a mean over examples, with no square root, regularization or extra factor of one-half. Perfect predictions give zero loss.