How Machines Learn Guide 1 of 6 · tap to switch
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.
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.
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.
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.
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:
Multiple linear regression (one weight per feature):
Mean Squared Error (average area of the orange mistake squares):
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:
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 becomes too expensive.
Coefficient of Determination (): Fraction of squared error erased compared to predicting the sample mean :
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 , so always inspect a residual plot before citing a fit.
See how tiny this is in PythonOptional Code
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:
- 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).
- 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.
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:
- 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.
- 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.
- 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.
- 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.
Quick Intuition Check
Four quick real-world scenarios. No scores, just test your intuition.
A coffee shop uses linear regression to predict daily iced-latte sales from outside temperature. What are the two knobs the computer learns?
A model predicting home prices gets R² = 0.88. What does that mean in plain English?
While gradient descent is stepping down the Mistake Bowl, the total error starts bouncing wildly and getting worse. What should you adjust?
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.
Common Questions
What is linear regression in simple terms?
What does R-squared (R²) mean in linear regression?
Can linear regression use more than one input feature?
Why do outliers affect linear regression so strongly?
When should you not use linear regression?
Related Visual Guides
Gradient Descent, Learning Rate & Adam Optimizer
Master the engine that trains every deep model: tune learning rates, race SGD vs. Momentum vs. Adam, pick mini-batches, and schedule cosine decay.
Overfitting vs Underfitting & Bias-Variance
How to tell real learning apart from blind memorization, understand the bias-variance tradeoff, and cure overfit models.
Feature Engineering and Selection
How turning raw columns into smarter clues and cutting redundant or noisy junk often beats switching to a bigger model.
Written & illustrated by Muhammad Aashir Irshad · Updated December 2026 · Free open-access reference
Cite this guide in a paper, thesis, or course (BibTeX & APA)
@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}
} Irshad, M. A. (2026). Linear Regression: Interactive Visual Guide. SeeingML. https://seeingml.com/learn/linear-regression/