SeeingML
How Machines Learn Guide 1 of 6 · tap to switch
✦ Interactive Visual Guide 8 min · 5 hands-on labs · Beginner friendly

Linear Regression

How a machine learns to draw the best prediction line from real examples, and when that line can be fooled.

Linear regression is the simplest and most widely used tool in machine learning for predicting a number, such as a home’s price, tomorrow’s coffee sales, or a delivery time, from real-world clues.

Imagine a friend is house-hunting in London and spots a 75 m² two-bedroom flat. They ask: “What’s a fair price for this?” You pull up ten nearby sales, from a 34 m² Hackney studio (£265k) to a 134 m² Richmond family home (£645k).

Before touching a single formula, try fitting the line yourself. Grab either glowing ring on the chart below (or move the sliders) until the dashed vertical miss lines look as short as possible. Tap or hover any dot to inspect that home.

Interactive Lab 1: Drag the Line Yourself
Your average miss: £59k
Your linePrediction missesSold homes (tap or hover)
£200k£300k£400k£500k£600k£700k40 m²60 m²80 m²100 m²120 m²140 m²Floor area (square meters)Sold price (£ thousands)↕ Drag the two rings on the line
+£1.6k / m²
£340k
Pretty far off right now. Grab either glowing circle on the line and pull it through the homes.For a 75 m² flat, your rule guesses £460k

Notice what you just did with nothing but your eyes: you balanced the line so it wasn’t wildly too high for small flats or wildly too low for larger homes.

That straight line is a linear regression model. It turns an input (floor area) into a price guess using just two adjustable knobs: a starting baseline (intercept) and how much each extra square meter adds (slope).


How a computer finds the best line automatically

Your eyes can judge a line at a glance. A computer cannot, so it needs a single mistake score to shrink.

If you turn every vertical miss into an orange square, tiny misses stay small while one big miss balloons into a massive block. Averaging the areas of all those squares gives Mean Squared Error (MSE). The best line is simply the one with the smallest total orange area.

Once the computer can score any line, learning becomes a game of hot-and-cold: start with a terrible guess, check which way goes downhill on the Mistake Bowl, and step downward until the ball settles at the bottom. Click Take 1 Step, hit Let It Learn, then try Too reckless! to see what happens when the step size (learning rate) is too big.

Interactive Lab 2: Watch the Computer Learn
£200k£350k£500k£650k40 m²70 m²100 m²130 m²Home size (m²)Sold price (£k)Step 0 · Miss £107k
The Mistake Bowl£0k£50k£100k£150k02468Line steepness (£k per m²)Average Mistake ScoreLowest mistake
Step size:
Start from a terrible flat line. Click "Take 1 Step" or "Let It Learn" to watch the orange mistake squares shrink.

That downhill stepping loop is gradient descent, the same core learning engine used inside deep neural networks and modern AI, just with millions of knobs instead of two.


How good is your line? Understanding R² visually

Suppose you fit a line and get an average miss of £15k. Is that amazing, or terrible? That depends on how wild the prices were to begin with.

A clever way to grade any linear regression line is to compare it against the laziest rule on Earth: ignore floor area completely and just guess the average price (£459k) for every home.

Switch between Just Guess Average and Use Linear Regression below, then drag the market-messiness slider to watch R² (R-squared) move in real time.

Interactive Lab 3: How Good Is the Fit? (R² Visualized)
Mistake area erased by using floor area instead of the plain average:R² = 0.91 (91%)
Flat average guess (£458k)Linear regression lineAverage-guess mistake squares
£200k£350k£500k£650k40 m²60 m²80 m²100 m²120 m²140 m²Floor area (m²)Sold price (£ thousands)
Very tidy
Viewing the lazy baseline: blindly guessing £458k for every home creates large amber mistake squares. Click "Use Linear Regression" to see 91% of that mistake area disappear (R² = 0.91).

That is all R² means, with zero intimidation needed:

  • R² = 0.95 means your line erased 95% of the squared mistake area compared to just guessing the average.
  • R² = 0.20 means prices are mostly driven by clues your line doesn’t see yet.

What if price depends on more than just size?

In real life, nobody prices a London flat using floor area alone. Bedrooms and walking distance to the Tube matter hugely too.

Multiple linear regression handles multiple clues (called features) with zero change to the core idea: instead of one slope knob, the computer learns one weight knob per feature and adds them up. Try building a flat below and watch each clue contribute its slice to the predicted price.

Interactive Lab 4: Using Multiple Clues at Once
Predicted price: £491k
Starting base
£90k
Fixed baseline
Floor area
+£270k
75 m² × £3.6k
Bedrooms
+£76k
2 × £38k
Near Tube
+£55k
Under 5 min walk
75 m²
2
Near Tube station
The learned weights stay fixed (£3.6k per m², £38k per bedroom, +£55k near the Tube); your sliders simply plug this 75 m², 2-bedroom flat (near Tube) into the same recipe for £491k.

Whether a model uses 1 clue or 50 clues, linear regression is always doing the exact same thing: taking a starting baseline and adding up weighted contributions from each feature.

See the exact math, closed-form solution & statistical assumptionsThesis / Reference

Single-feature line:

y^=b+m⋅x\hat{y} = b + m \cdot x

Multiple linear regression (one weight wjw_j per feature):

y^=b+w1x1+w2x2+⋯+wpxp=x⊤β\hat{y} = b + w_1 x_1 + w_2 x_2 + \dots + w_p x_p = \mathbf{x}^\top \boldsymbol{\beta}

Mean Squared Error (average area of the orange mistake squares):

MSE=1n∑i=1n(yi−y^i)2\text{MSE} = \frac{1}{n} \sum_{i=1}^{n} (y_i - \hat{y}_i)^2

Closed-form Exact Solution (Normal Equation): Because MSE for a straight line is a single smooth bowl with one bottom, you don’t have to step downhill on small or medium datasets. Linear algebra jumps straight to the exact optimum in one shot:

β^=(X⊤X)−1X⊤y\hat{\boldsymbol{\beta}} = (\mathbf{X}^\top \mathbf{X})^{-1}\mathbf{X}^\top \mathbf{y}

In practice, tabular tools use this exact solve (via QR/SVD decomposition) when datasets fit comfortably in memory, and switch to gradient descent when there are millions of rows or thousands of features where inverting X⊤X\mathbf{X}^\top \mathbf{X} becomes too expensive.

Coefficient of Determination (R2R^2): Fraction of squared error erased compared to predicting the sample mean yˉ\bar{y}:

R2=1−SSresSStot=1−∑(yi−y^i)2∑(yi−yˉ)2R^2 = 1 - \frac{\text{SS}_{\text{res}}}{\text{SS}_{\text{tot}}} = 1 - \frac{\sum (y_i - \hat{y}_i)^2}{\sum (y_i - \bar{y})^2}

Classical OLS assumptions (LINE): (1) Linearity of the mean relationship, (2) Independence of errors, (3) Normality of residuals (needed for exact confidence intervals and p-values, not for point predictions), and (4) Equal variance (homoscedasticity) across the input range. As Anscombe’s Quartet famously proved, four completely different datasets can share the exact same slope, intercept, and R2R^2, so always inspect a residual plot before citing a fit.

See how tiny this is in PythonOptional Code
python
import numpy as np

sizes  = np.array([34, 46, 54, 66, 76, 86, 98, 110, 122, 134])
prices = np.array([265, 310, 375, 390, 460, 455, 530, 540, 615, 645])

# Fit linear regression (slope m, intercept b)
m, b = np.polyfit(sizes, prices, deg=1)
preds = b + m * sizes

# Compute R² directly from squared mistakes
ss_res = np.sum((prices - preds) ** 2)
ss_tot = np.sum((prices - prices.mean()) ** 2)
r2 = 1 - ss_res / ss_tot

print(f"Rule: £{b:.0f}k + £{m:.1f}k per m²  (R² = {r2:.2f})")
print(f"Predicted price for a 75 m² flat: £{b + m * 75:.0f}k")

When linear regression breaks

Linear regression is fast, transparent, and surprisingly powerful, until you hand it data that breaks its assumptions. Test the two biggest traps yourself below:

  1. Extreme outliers: Drop a tiny £910k Mayfair studio into normal neighborhood sales and watch the squared-error line panic and tilt upward (then compare with an outlier-calm rule).
  2. Curved data & extrapolation: Switch to 2. Curved Data & Extrapolation to see a straight ruler try to predict used car resale value and crash below £0 when asked about older cars. Below the main car chart, watch the residual plot (a chart of leftover misses, actual minus predicted): when those leftover misses form a U-shape instead of random scatter around zero, it is a clear signal that a straight line is the wrong shape.
Interactive Lab 5: When Linear Regression Breaks
Try it: Drop the £910k Mayfair studio below, drag any dot up or down, or click empty space to watch the line tilt.
£200k£400k£600k£800k40 m²60 m²80 m²100 m²120 m²140 m²Floor area (square meters)Sold price (£ thousands)Standard (squared error)
Click empty space to add a home, drag any dot, or drop the Mayfair studio to watch one extreme sale bend the line.

Knowing when not to trust a straight line is half of real-world machine learning. Before relying on any linear regression model, run four fast sanity checks:

  1. Is the pattern actually straight? Check the residual plot. Random scatter around zero is healthy, while a clear U-shape or wave means you need curves, trees, or a non-linear model.
  2. Are your examples independent? Repeated measurements from the same person or consecutive stock prices aren’t independent, and they can trick a model into overconfidence.
  3. Is the scatter roughly even left-to-right? If predictions are tight for small flats but wildly spread out for mansions (a “fan” shape), confidence ranges become unreliable.
  4. Are extreme outliers or unseen ranges distorting the rule? Use a gentler scorer (called Huber regression, which stops letting one giant outlier dominate the squaring penalty) when rare extremes skew the line, and never blindly trust predictions far outside the range your data actually covered.
✓ Self-Check

Quick Intuition Check

Four quick real-world scenarios. No scores, just test your intuition.

1

A coffee shop uses linear regression to predict daily iced-latte sales from outside temperature. What are the two knobs the computer learns?

Pick an option first, or peek anytime
2

A model predicting home prices gets R² = 0.88. What does that mean in plain English?

Pick an option first, or peek anytime
3

While gradient descent is stepping down the Mistake Bowl, the total error starts bouncing wildly and getting worse. What should you adjust?

Pick an option first, or peek anytime
4

A linear regression model trained on 0-to-10-year-old used cars can safely predict the resale price of a 15-year-old car.

Pick an option first, or peek anytime
Quick Reference

Common Questions

What is linear regression in simple terms?
Linear regression is a machine learning method that predicts a number (such as a house price or daily sales) by finding the straight line, or weighted sum of clues, that passes as closely as possible through past examples.
What does R-squared (R²) mean in linear regression?
R² measures how much better your regression line is than simply guessing the average value every time. An R² of 0.90 means the line erased 90% of the squared mistake area compared to the flat average.
Can linear regression use more than one input feature?
Yes. Multiple linear regression simply gives each clue its own weight knob (such as price per square metre, price per bedroom, and a bonus for being near transit) and adds them to a starting baseline.
Why do outliers affect linear regression so strongly?
Standard linear regression minimizes squared errors, so a single extreme miss creates a massive square that dominates the score. The line tilts aggressively toward the outlier just to shrink that one square.
When should you not use linear regression?
Avoid plain linear regression when the true relationship is curved (like used car depreciation over time), when predicting far outside the range of past data (extrapolation), or when predicting yes/no categories instead of numbers.

Written & illustrated by Muhammad Aashir Irshad · Updated December 2026 · Free open-access reference

https://seeingml.com/learn/linear-regression/ Open GitHub issue Suggest an edit
Cite this guide in a paper, thesis, or course (BibTeX & APA)
BibTeX
@misc{irshad2026linearregression,
  author       = {Irshad, Muhammad Aashir},
  title        = {Linear Regression: Interactive Visual Guide},
  howpublished = {SeeingML},
  year         = {2026},
  month        = {dec},
  url          = {https://seeingml.com/learn/linear-regression/},
  note         = {Interactive visual guide}
}
APA

Irshad, M. A. (2026). Linear Regression: Interactive Visual Guide. SeeingML. https://seeingml.com/learn/linear-regression/