Code / AI & ML Basics / Unit 3: Learning a line

Predicting numbers with a line रेखा से संख्याओं का अनुमान

Lesson 7 of 13 · about 15 minutes · y = m·x + c and mean squared error.

⚡ 0 XP

Step 1 of 1

A line and its error

Some questions want a number, not a group: “If I study 4 hours, what marks might I get?” This is regression.

The simplest model is a straight line: marks = m × hours + c

  • m (slope): extra marks for each extra hour
  • c (intercept): marks with zero hours of study

How good is a line? For each student, error = predicted − actual. Square it (so minus signs don’t cancel and big misses count extra), then take the average. That is the mean squared error (MSE). Lower is better; 0 means a perfect fit.

Try it above: drag the two handles of the line and watch the MSE. Can you beat the “best fit” button?

▶ Try it Fit the line: study hours → marks (sample data)
hours →marks ↑
y = 3.0·x + 30.0MSE = 298.7

Drag the two round handles. Red lines are each point’s error; the average of their squares is the MSE. Smallest MSE = best line.

🎯 Challenge: Predict and measure the error +15 XP

Write two functions:

  • predict(m, c, x) returns m * x + c
  • mse(m, c, xs, ys) returns the mean squared error of that line on the data: the average of (predict(m, c, xs[i]) - ys[i]) ** 2

Try twice to unlock the solution (0/2)

script.jsCtrl ⏎
Console

Output from console.log appears here.

Checklist

Press Run to check your code.

  • predict(5, 30, 4) is 50
  • A perfect line has MSE 0
  • Errors are squared and averaged
Lesson notes (text version)

1. A line and its error

Some questions want a number, not a group: “If I study 4 hours, what marks might I get?” This is regression.

The simplest model is a straight line: marks = m × hours + c

  • m (slope): extra marks for each extra hour
  • c (intercept): marks with zero hours of study

How good is a line? For each student, error = predicted − actual. Square it (so minus signs don’t cancel and big misses count extra), then take the average. That is the mean squared error (MSE). Lower is better; 0 means a perfect fit.

Try it above: drag the two handles of the line and watch the MSE. Can you beat the “best fit” button?

Challenge: Predict and measure the error

Write two functions:

  • predict(m, c, x) returns m * x + c
  • mse(m, c, xs, ys) returns the mean squared error of that line on the data: the average of (predict(m, c, xs[i]) - ys[i]) ** 2

Search by task, format or tool name.