Skip to content
AI-grafen
CBuilderLab· about 40 min· in the browser

Lab: the best line with least squares

Compute the MSE for a given line, find the best line with the closed-form formula, and predict new values.

Theory

MSE = mean of (actual − guess)². Best k = Σ(xᵢ−x̄)(yᵢ−ȳ) / Σ(xᵢ−x̄)², m = ȳ − k·x̄. No search is needed — the formula gives the optimum directly (gradient descent is what generalises when there is no formula).

Sub-tasks

  1. mse — mse(k, m, xs, ys).
  2. anpassa (fit) — anpassa(xs, ys) returns (k, m) using least squares.
  3. forutsag (predict) — forutsag(k, m, x).

The starter code

runs in your browser
def mse(k, m, xs, ys):
    # TODO
    ...


def anpassa(xs, ys):
    # TODO: minsta kvadratmetoden (sluten formel)
    ...


def forutsag(k, m, x):
    # TODO
    ...

You write the code; tests you cannot see decide whether it holds up. Create a free account to run the lab.

Try the diagnosticCreate a free account

Expected results

anpassa([15,20,25],[20,35,50]) = (3, −25) exactly; mse(3,-25,...) = 0; forutsag(3,-25,30) = 65.

Common mistakes

  • Computes deviations from 0 instead of from the mean.
  • Mixes up k and m in the return order.