Single logo
  • Courses
  • Blog
  • About
Join for freeJoin free
Learning pathPredict a Number: Regression from Scratch to Regularisation
  1. 1
    Linear Regression and the Cost Function: Draw a Line, Score It
  2. 2
    Gradient Descent Explained: Feel the Slope, Step Downhill
  3. 3
    Linear Regression in scikit-learn: Fit, Predict and Read the Price Tags
  4. 4
    Regression Metrics: MAE, RMSE, R-squared and the Baseline to Beat
  5. 5
    Polynomial Regression, Overfitting and Underfitting: Bend the Line, Watch the Test Score
  6. 6
    Regularisation with Ridge and Lasso: Put a Price on Big Weights
  1. Blog
  2. /
  3. Machine Learning
  4. /
  5. Supervised Learning

Learning path: Predict a Number: Regression from Scratch to Regularisation · Step 1 of 6

Linear Regression and the Cost Function: Draw a Line, Score It

Draw a straight line through six kids' ages and weights, measure every miss, and turn the misses into one score, the mean squared error. Then let np.polyfit find the line with the lowest score.

Chaand Sheikh

·27 November 2026Regression

What you will learn

  • Write a straight line as y_hat = w * x + b and explain both knobs
  • Compute residuals as real minus guess
  • Turn the residuals into one score, the mean squared error (MSE)
  • Find the best-fit line with np.polyfit and use it to predict

Before you start

  • Basic Python
  • Reading a CSV with pandas

Imagine a cork board with age along the bottom and weight up the side. You push in one pin for every kid. Then you take a piece of string, pull it tight in one straight line, and move it until it passes as close as possible to every pin.

Finding that best string is linear regression. The pins are the data, the string is the line. In this lesson you'll write the line in code, measure how badly it misses, turn the misses into one score, and find the line with the lowest score.

The data: six kids

import numpy as np
import pandas as pd
df = pd.read_csv("kids_age_weight.csv")
df
     name  age  weight
0    Emma    2      12
1    Liam    3      15
2  Olivia    5      18
3    Noah    6      22
4     Ava    8      25
5    Jack    9      30

One input (age) and one number to predict (weight). That's a regression problem: the answer is a number, not a group.

One line, two knobs

A straight line in maths looks like this:

y_hat = w * x + b

  • x is the input, the age.
  • y_hat is the line's guess for the weight.
  • w is the slope: how many kilos we add for every extra year.
  • b is where the line starts, at age 0.

So the line has two knobs, w and b. Some books write them as θ1 and θ0. Same line, different letters.

Let's turn the knobs to a first guess, w = 5 and b = 0:

x, y = df["age"], df["weight"]
w, b = 5, 0
y_hat = w * x + b

y is the real weight. y_hat now holds one guess per kid.

How far does each point miss?

For every kid, look at the gap between the real weight and the guess. That gap is called the residual:

residual = real - guess = y - y_hat

residual = y - y_hat
df.assign(y_hat=y_hat, residual=residual)
     name  age  weight  y_hat  residual
0    Emma    2      12     10         2
1    Liam    3      15     15         0
2  Olivia    5      18     25        -7
3    Noah    6      22     30        -8
4     Ava    8      25     40       -15
5    Jack    9      30     45       -15

Emma really weighs 12 kg and the line says 10, so the miss is 2. Liam is a perfect 0. Ava weighs 25 but the line says 40, so the miss is -15. A minus sign simply means the line guessed too high. Four of the six residuals are negative: this line is far too steep.

Six misses become one score

We want one number for the whole line. Two steps:

  1. Square every residual.
  2. Average the squares.
squares = residual ** 2
print(squares.tolist())
print(squares.sum(), squares.mean())
[4, 0, 49, 64, 225, 225]
567 94.5
KidResidualSquared
Emma24
Liam00
Olivia-749
Noah-864
Ava-15225
Jack-15225
Sum / mean567 / 94.5

567 divided by 6 kids is 94.5. This is the mean squared error, or MSE:

MSE = average of (y - y_hat)2

Why square? If we just added the misses, a +2 and a -2 would cancel out and a bad line could look perfect. Squaring makes every miss positive, and it makes a big miss count much more than a small one: a miss of 15 costs 225, a miss of 2 costs only 4.

This score is our cost function. The lower the cost, the better the line.

Score any line with one call

Wrap the same steps in a small function, so you can score any pair of knobs:

def mse(w, b):
    y_hat = w * x + b
    return np.mean((y - y_hat) ** 2)

print(mse(5, 0), mse(2.5, 7))
94.5 1.125

Every call does the same four things: guess, miss, square, average. The line w = 2.5, b = 7 scores 1.125, far lower than 94.5.

The line with the lowest MSE

Which line is the best one? NumPy has a helper. np.polyfit(x, y, 1) returns the straight line (the 1 means degree one) with the lowest MSE:

w_best, b_best = np.polyfit(x, y, 1)
score = mse(w_best, b_best)
print(round(w_best, 2), round(b_best, 2))
print(round(score, 3))
2.4 7.13
0.889

About 2.4 kg per year, starting at 7.13 kg. The score is 0.889, lower than both of our guesses.

Three lines through the six kids 0 2 4 6 8 10 0 10 20 30 40 50 age (years) weight (kg) Emma Liam Olivia Noah Ava Jack w = 5, b = 0: MSE 94.5 w = 2.5, b = 7: MSE 1.125 best fit 2.4, 7.13: MSE 0.889
The six kids with three lines. The red line (w = 5, b = 0) is far too steep, and the orange bars show its misses. The orange dashed line scores 1.125 and the green best fit scores 0.889. They look almost the same, but the score says green is a little better.

Predict with the best line

Now the line can answer a question it has never seen. How heavy is a 7-year-old?

print(round(w_best * 7 + b_best, 1))
23.9

About 23.9 kg. That's all a prediction is here: 2.4 times 7, plus 7.13.

Common mistakes

  • Mixing up the sign of the residual. It's real minus guess. A negative residual means the line guessed too high.
  • Adding the raw misses. Plus and minus cancel out. Square them first.
  • Trusting your eyes. The orange and green lines look the same on the chart. The MSE tells them apart.
  • Reading MSE in kilos. MSE is in squared units (kg2). It's for comparing lines, not for saying "off by 0.889 kg".

Quick recap

IdeaCodeKids example
A line has two knobsy_hat = w * x + bw = 5, b = 0
Residual = real minus guessy - y_hat2, 0, -7, -8, -15, -15
MSE = mean of the squaresnp.mean((y - y_hat) ** 2)94.5
Best fit = lowest MSEnp.polyfit(x, y, 1)w 2.4, b 7.13, MSE 0.889
Predictw_best * 7 + b_best23.9 kg

polyfit handed us the answer here. Next, in Gradient Descent, the computer walks to the same line step by step.

Try it yourself

Score the line w = 3, b = 5 with mse(3, 5). Is it better or worse than w = 2.5, b = 7?

The notebook and the dataset are in the StudyEasy AI Community, free to join.

Built this? Share your solution in the StudyEasy AI Community.

Join free on Skool →
Next →
Gradient Descent Explained: Feel the Slope, Step Downhill
Single logo

StudyEasy AI Community

Hosted onSkool

Learn AI engineering, share what you build, and connect with other learners.

  • Free resources: lesson files, notebooks and code

  • Ask questions and join engineering discussions

  • Meet real people learning and building with AI

Join free on Skool
Go deeper with a course

Machine Learning Engineer: From First Model to ML Engineer

Learn machine learning in Python, then ship it: data analysis, regression, classification, tuning, deployment and MLOps.View on Udemy ↗: Machine Learning Engineer: From First Model to ML Engineer (opens in a new tab)

Related articles
Gradient Descent Explained: Feel the Slope, Step Downhill

Instead of handing over the best line, let the computer walk to it: measure the slope of the cost, step downhill with a learning rate, repeat. Shown step by step on six kids' ages and weights.

Linear Regression in scikit-learn: Fit, Predict and Read the Price Tags

Predict a yearly medical bill with scikit-learn's LinearRegression: first from age alone, then from every column inside a pipeline. Each coefficient reads like a price tag, and smoker_yes is by far the biggest.

Regression Metrics: MAE, RMSE, R-squared and the Baseline to Beat

Score a regression model honestly: MAE, MSE and RMSE from four darts, then the insurance model on 268 test people, a DummyRegressor baseline to beat, R-squared and adjusted R-squared, and a residual plot.

Polynomial Regression, Overfitting and Underfitting: Bend the Line, Watch the Test Score

Give a linear model extra columns with PolynomialFeatures and it can bend. Then watch train and test scores split apart: degrees 1, 2 and 16 on Canada's income per person, and degrees 1 to 5 on the insurance model.

On this page
  • The data: six kids
  • One line, two knobs
  • How far does each point miss?
  • Six misses become one score
  • Score any line with one call
  • The line with the lowest MSE
  • Predict with the best line
  • Common mistakes
  • Quick recap
  • Try it yourself
Single logo

StudyEasy AI Community

Hosted onSkool

Learn AI engineering, share what you build, and connect with other learners.

  • Free resources: lesson files, notebooks and code

  • Ask questions and join engineering discussions

  • Meet real people learning and building with AI

Join free on Skool
Go deeper with a course

Machine Learning Engineer: From First Model to ML Engineer

Learn machine learning in Python, then ship it: data analysis, regression, classification, tuning, deployment and MLOps.View on Udemy ↗: Machine Learning Engineer: From First Model to ML Engineer (opens in a new tab)

Single logo

Empowering Education, One Course at a Time

About
About usContact usFAQs
Legal
Terms of ServicePrivacy Policy

© 2026 StudyEasy Organization. All rights reserved.