Stop 07 · Supervised Learning: RegressionTopics · 3/8

The Normal Equation & Regression Math

Part of the Machine Learning Roadmap

In short

Linear regression is the 'hello world' of modelling, and its maths shows up everywhere later. Understand how it picks the best line and half of ML gets easier.

For linear regression the best weights can be computed directly with the normal equation, which solves the least-squares problem using matrix algebra. Seeing the maths shows what scikit-learn does behind fit().

The mascot stands next to a yellow and black auto-rickshaw, writing in a small notebook.

Think of it like this

Working out auto fares

An auto charges a fixed base amount plus some rupees per kilometre. You don't know either number, but you have your last four rides and their fares. Linear regression finds the base and per-km rate that fit your rides best.

Watch it happen

Scoring one guess: fare = 30 + 13 × km

60
0
80
1
110
2
145
3

1/5Actual fares for rides of 2, 4, 6 and 9 km.

The big ideas

What you need to know

y = w·x + b

w is the slope (rupees per km), b is the intercept (base fare). With more features, w becomes a vector.

Least squares

The best line minimises the sum of squared errors between actual and predicted values.

Two ways to solve it

A direct formula, the normal equation, for small data, or gradient descent for very large data.

Assumptions behind it

A roughly straight-line relationship, independent errors and no wild outliers dominating the fit.

See it in code

Walk through the code

python
1import numpy as np2 3km = np.array([2, 4, 6, 9])4fare = np.array([60, 80, 110, 145])5 6X = np.column_stack([np.ones_like(km), km])   # [1, km] per ride7b, w = np.linalg.lstsq(X, fare, rcond=None)[0]8print(f"fare = {b:.1f} + {w:.1f} * km")       # about 33.7 + 12.4 * km

1/3Four rides: distance and what you paid.

NumPy solves least squares directly. The column of ones lets the model learn the base fare.

Save yourself the pain

Common mistakes

Oops

Reading a big slope as proof that x causes y.

Do this instead

Regression finds association. Causation needs an experiment or careful causal reasoning.

Oops

Forgetting the intercept.

Do this instead

Without b, the line must pass through zero. Most real relationships, like a base fare, don't.

Your mission

Fit your own fares

~20 min

Quick check

Why does least squares square the errors instead of just adding them?

Go deeper

  1. 1Compute weights with the normal equation in NumPy and compare with scikit-learn's coef_.
  2. 2Derive the gradient of mean squared error for one weight on paper.
  3. 3Learn why the normal equation gets slow with very many features.

More topics at this stop

Stuck on this topic? Ask an Insider

Get 1:1 guidance from people who've walked this exact path — on the InsideEdge app.

Download
InsideEdge