Lesson 17
Linear Regression
Learn linear regression step by step: the least-squares proof in plain words, the sklearn workflow, error metrics, and under/overfitting with live labs.
What You Will Learn
Click a topic to jump to that section. Every idea is explained in plain words first, then with numbers, then with a live lab you can change.
- Before You Start
- The Big Idea
- Meet the Dataset
- The Math, Step by Step
- Try It Yourself: Fit a Line
- The Workflow in Five Steps
- scikit-learn Functions and Sources
- When the Line Is Not Perfect
- Underfit, Good Fit, Overfit
- Metrics: How Good Is the Line?
- Conditions: When Linear Regression Works
- If You Get an Error
- Common Mistakes
- Interview Questions
- Practice Problems
- Mindmap
- Summary
- What to Learn Next
Before You Start
Linear regression is the first algorithm in this course, so this page goes slowly and explains every symbol. Every later algorithm lesson follows the same layout: idea, dataset, math, lab, five-step workflow, metrics, errors, quiz. Learn the pattern here once and it will feel familiar every time.
You do not need to master the lessons below first. Skim them if you like. Each idea is explained again where we use it.
| Lesson | What we borrow from it |
|---|---|
| What Is Machine Learning | Inputs, targets, and what "training" means |
| Supervised Learning | Learning from rows that already have the right answer |
| ML Workflow | The big picture: data, split, train, test, improve |
| Gradient Descent | Another way to find the best line: walk downhill in small steps |
| Bias and Variance | Why models can be too simple or too flexible |
| Statistics | Mean, spread, and what a typical miss looks like |
| Calculus | The slope of a curve is zero at its lowest point |
| Linear Algebra | Tables of numbers (matrices) for the second proof |
| Optimization | Finding the lowest point of a loss |
The Big Idea
Think of a taxi. The meter starts at ₹30 the moment you sit down. Then it adds ₹6 for every kilometre.
fare = 30 + 6 × kilometresThat is a straight-line rule. Give it any distance and it gives you a fare. Linear regression finds a rule like this from data instead of from a price list.
Our data is about study. Ten students told us how many hours they studied per day and what they scored. We ask:
If a new student studies 6.5 hours, what mark should we expect?
The answer is a line with two numbers:
- c (the intercept) is where the line starts, like the taxi's ₹30.
- m (the slope) is how much it climbs for each extra hour, like the taxi's ₹6 per km.
ŷ = m · x + c (read ŷ as "y-hat": the prediction, not the real answer)Two words you will see everywhere:
- Regression means predicting a number (marks, price, temperature). Predicting a label such as spam or not spam is called classification.
- Linear means the pattern is a straight line (or a flat plane when there are many inputs).
One question remains: out of all possible lines, which one is the best? The next two sections answer it with a proof anyone can follow.
Meet the Dataset
We use the same ten students for the proof, the labs, and the code. That way every number in this lesson can be checked.
| Student | Hours studied (x) | Marks (y) |
|---|---|---|
| 1 | 1 | 39 |
| 2 | 2 | 40 |
| 3 | 3 | 49 |
| 4 | 4 | 50 |
| 5 | 5 | 57 |
| 6 | 6 | 68 |
| 7 | 7 | 77 |
| 8 | 8 | 79 |
| 9 | 9 | 80 |
| 10 | 10 | 91 |
- x is the input (also called a feature). In code we write it as a capital
Xbecause scikit-learn wants a table, even when there is only one column. - y is the target: the number we want to predict. In code it is a lowercase
ybecause it is a single list. - The mean (average) hours is 5.5 and the mean marks is 63. Remember these two. They matter in the proof.
The Math, Step by Step
Goal: find the m and c that make the line miss the real marks by as little as possible.
You do not need to be good at maths. You need to follow five small ideas in order. After each idea we use the real numbers from the table above.
The symbols, in plain words
| Symbol | Say it as | Meaning |
|---|---|---|
| x, y | "x, y" | One student's hours and marks |
| ŷ | "y-hat" | The line's prediction for that student |
| m, c | "slope, intercept" | The two numbers we are searching for |
| n | "n" | How many students: here 10 |
| x̄, ȳ | "x-bar, y-bar" | The averages: here 5.5 and 63 |
| Σ | "sigma" | "Add them all up" |
| dx, dy | "d-x, d-y" | How far a student is from the average: dx = x − x̄, dy = y − ȳ |
| miss | "the miss" | Real minus predicted: y − ŷ |
Idea 1: Measure how wrong a line is
Pick any line and predict every student. The miss for one student is y − ŷ. A miss of +4 means the line guessed 4 marks too low. A miss of −4 means 4 too high.
Here are two lines side by side. The guess line is 5x + 35 (a random try). The best line is 6x + 30 (we will prove why it is best).
| Hours | Marks | Guess ŷ | Guess miss² | Best ŷ | Best miss² |
|---|---|---|---|---|---|
| 1 | 39 | 40 | 1 | 36 | 9 |
| 2 | 40 | 45 | 25 | 42 | 4 |
| 3 | 49 | 50 | 1 | 48 | 1 |
| 4 | 50 | 55 | 25 | 54 | 16 |
| 5 | 57 | 60 | 9 | 60 | 9 |
| 6 | 68 | 65 | 9 | 66 | 4 |
| 7 | 77 | 70 | 49 | 72 | 25 |
| 8 | 79 | 75 | 16 | 78 | 1 |
| 9 | 80 | 80 | 0 | 84 | 16 |
| 10 | 91 | 85 | 36 | 90 | 1 |
| Total | 171 | 86 |
The "miss²" columns are the misses multiplied by themselves (squared). The totals are called the sum of squared errors (SSE). A smaller total means a better line: 86 beats 171.
Idea 2: Why square the misses?
Three reasons, from easiest to most important:
- No cancelling. A +5 miss and a −5 miss would add up to 0 and look perfect. Squares are never negative, so every miss counts. A completely flat line at the average mark (63) has raw misses that add to exactly 0, yet its squared total is 3056, which is terrible.
- Big misses hurt more. Missing by 10 costs 100. Missing by 1 costs 1. One big mistake is worse than several tiny ones.
- It makes a smooth bowl. Squares give a curve with one lowest point and no corners. Calculus can find that lowest point exactly.
Idea 3: The best line is the bottom of a bowl
Fix the line so that it passes through the average point. Now try different slopes m and add up the squared misses for each one. We get this picture:
- Too flat (m = 0) gives 3056. Too steep (m = 12) also gives 3056.
- m = 4 and m = 8 both give 416.
- m = 6 gives 86, the lowest. We never have to try every number. The bottom of a bowl is the one place where the slope of the bowl itself is zero (flat). Finding where a curve's slope is zero is exactly what derivatives do. See Calculus.
Gradient Descent finds that bottom by walking downhill in small steps. For a straight line we can do better and jump straight to the bottom with algebra. That is the proof.
The proof, in five moves
Call the total squared miss S. It depends on the two numbers we control:
S(m, c) = Σ (y − m·x − c)²We want the m and c that make S as small as possible.
Move 1: the best c, for any slope. Treat m as fixed. S is a bowl in c. Its slope is zero at the bottom, so take the derivative with respect to c and set it to zero:
dS/dc = −2 Σ (y − m·x − c) = 0
Σy − m·Σx − n·c = 0
c = ȳ − m·x̄In words: the best line always passes through the average point (x̄, ȳ). For us the average point is (5.5, 63), so c = 63 − 5.5·m.
Move 2: rewrite every miss using the averages. Put c = ȳ − m·x̄ back into one student's miss:
y − m·x − c = (y − ȳ) − m·(x − x̄) = dy − m·dxNow S depends on m only:
S(m) = Σ (dy − m·dx)²Move 3: open the bracket. Remember (a − b)² = a² − 2ab + b². Apply it to each student and add up:
S(m) = Σdy² − 2m · Σdx·dy + m² · Σdx²Give the three sums short names so they are easier to read:
Sxy = Σ (x − x̄)(y − ȳ) "how x and y move together"
Sxx = Σ (x − x̄)² "how spread out x is"
Syy = Σ (y − ȳ)² "how spread out y is"Then S(m) = Syy − 2m·Sxy + m²·Sxx. This is the exact bowl drawn above.
Move 4: find the bottom. The slope of the bowl is its derivative. Set it to zero:
dS/dm = −2·Sxy + 2m·Sxx = 0
m = Sxy ÷ SxxHere is the whole calculation with real numbers. Every column is easy to check by hand:
| Hours x | Marks y | dx = x − 5.5 | dy = y − 63 | dx · dy | dx² |
|---|---|---|---|---|---|
| 1 | 39 | −4.5 | −24 | 108 | 20.25 |
| 2 | 40 | −3.5 | −23 | 80.5 | 12.25 |
| 3 | 49 | −2.5 | −14 | 35 | 6.25 |
| 4 | 50 | −1.5 | −13 | 19.5 | 2.25 |
| 5 | 57 | −0.5 | −6 | 3 | 0.25 |
| 6 | 68 | 0.5 | 5 | 2.5 | 0.25 |
| 7 | 77 | 1.5 | 14 | 21 | 2.25 |
| 8 | 79 | 2.5 | 16 | 40 | 6.25 |
| 9 | 80 | 3.5 | 17 | 59.5 | 12.25 |
| 10 | 91 | 4.5 | 28 | 126 | 20.25 |
| Total | Sxy = 495 | Sxx = 82.5 |
m = Sxy ÷ Sxx = 495 ÷ 82.5 = 6
c = ȳ − m·x̄ = 63 − 6 × 5.5 = 30
best line: ŷ = 6x + 30Move 5: check that it is the bottom, not the top. A slope of zero could also be the top of a hill. Here it cannot be, because the m² term has Sxx in front of it, and Sxx is a sum of squares, so it is positive. A bowl with a positive m² term opens upwards and has exactly one lowest point. (The same check works for c: its c² term has n in front, and n is positive.)
There is one exception. If every x is the same, Sxx = 0, there is no bowl, and no unique slope exists. A vertical stack of dots has no best sloping line. That is why the lab below warns you when every x is equal.
Proof complete. The best line for our data is ŷ = 6x + 30, and the total squared miss is 86.
A second route: matrices (what scikit-learn does inside)
Real data often has many inputs, not one. Matrices handle any number of inputs with one formula. Put a column of ones next to x so the intercept c gets a column too:
XᵀX · [c, m] = Xᵀy (called the normal equations)For our data the pieces are small:
XᵀX = [[10, 55], [55, 385]] (n = 10, Σx = 55, Σx² = 385)
Xᵀy = [630, 3960] (Σy = 630, Σxy = 3960)Solve it by multiplying with the inverse (determinant = 10·385 − 55·55 = 825):
c = (385·630 − 55·3960) ÷ 825 = 24750 ÷ 825 = 30
m = (−55·630 + 10·3960) ÷ 825 = 4950 ÷ 825 = 6The same answer, c = 30 and m = 6. Two different proofs agree, which is a good sign. Matrices are explained in Linear Algebra, and the derivative-of-a-matrix step is in Matrix Calculus.
Check the proof with code
import numpy as np
from sklearn.linear_model import LinearRegression
hours = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10], dtype=float).reshape(-1, 1)
marks = np.array([39, 40, 49, 50, 57, 68, 77, 79, 80, 91], dtype=float)
dx = hours.ravel() - hours.mean()
dy = marks - marks.mean()
m = (dx * dy).sum() / (dx ** 2).sum()
c = marks.mean() - m * hours.mean()
print(f"by hand : m = {m:.4f}, c = {c:.4f}")
full = LinearRegression().fit(hours, marks)
print(f"sklearn : m = {full.coef_[0]:.4f}, c = {full.intercept_:.4f}")
print(f"R2 on all 10 rows = {full.score(hours, marks):.5f}")Output:
by hand : m = 6.0000, c = 30.0000
sklearn : m = 6.0000, c = 30.0000
R2 on all 10 rows = 0.97186The proof and scikit-learn match to four decimals.
Where does R² come from?
R² compares your line with the laziest possible guess: always predict the average mark.
SSE = 86 (our line's total squared miss)
SST = Syy = 3056 (the lazy "always predict 63" total squared miss)
R² = 1 − SSE ÷ SST = 1 − 86 ÷ 3056 = 0.97186So the line removes about 97% of the lazy guess's error. For one input, R² also equals the square of the correlation r = Sxy ÷ √(Sxx·Syy) = 495 ÷ 502.1 = 0.9858, and 0.9858² = 0.9719.
Sources and further reading
- Least squares history: first published by Legendre in 1805, and by Gauss in 1809. Wikipedia: Least squares, History
- Simple regression formulas and derivation: Wikipedia: Simple linear regression
- Matrix form, normal equations, and the Gauss–Markov theorem: Wikipedia: Ordinary least squares and Hastie, Tibshirani and Friedman, The Elements of Statistical Learning, Chapter 3, Section 3.2
- A university lecture-note version with LMS and the normal equations: Stanford CS229 notes, Part I
- How scikit-learn defines it: User guide: Ordinary least squares
- R²: Wikipedia: Coefficient of determination
Try It Yourself: Fit a Line
The lab below runs the same math you just read, live, on any numbers you type. Do these four things, in order:
- Start with the lesson table. Check that the slope is 6 and the intercept is 30. Scroll to The hand calculation, on your numbers and find the two totals, 495 and 82.5, from the proof. Their ratio is the slope.
- Change one mark. Edit a Y value. Watch the line move and the gaps (red bars) change.
- Press "Add an outlier". One wrong number drags the line and R² drops sharply. That is the number one reason a line looks "wrong".
- Type a new X in the prediction box. Try 6.5, then try 24. The lab warns you when you ask about a value far outside the data.
Loading interactive lab…
The Workflow in Five Steps
Every scikit-learn algorithm follows the same five steps. Linear regression is the simplest example, so learn the pattern here.
Think of preparing for an exam: you practise with some questions (train) and keep a separate paper you have never seen for the real test (test). Models need the same honesty.
Step 1: Create the model with model = LinearRegression()
This builds an empty object. It knows the recipe (least squares) but has learned nothing yet, like a student who has not opened the book.
from sklearn.linear_model import LinearRegression
model = LinearRegression()
print(model)
print("learned anything yet?", hasattr(model, "coef_"))Output:
LinearRegression()
learned anything yet? Falsecoef_ (the slope) does not exist until training. Asking for it now would fail.
Step 2: Split the data into train and test
We hide 30% of the rows. The model will never see them during training. They stand in for the real world.
import numpy as np
from sklearn.model_selection import train_test_split
hours = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10], dtype=float).reshape(-1, 1)
marks = np.array([39, 40, 49, 50, 57, 68, 77, 79, 80, 91], dtype=float)
X_train, X_test, y_train, y_test = train_test_split(
hours, marks, test_size=0.3, random_state=42
)
print("train hours:", X_train.ravel())
print("test hours :", X_test.ravel())
print("train rows:", len(X_train), "| test rows:", len(X_test))Output:
train hours: [ 1. 8. 3. 10. 5. 4. 7.]
test hours : [9. 2. 6.]
train rows: 7 | test rows: 3test_size=0.3means 30% of 10 rows, so 3 rows are hidden.random_state=42fixes the shuffle so you get the same split every time.- The order of the four outputs is always
X_train, X_test, y_train, y_test.
Now pick your own test rows in the lab. You will see how the trained line changes when different students are hidden.
Loading interactive lab…
An honest warning about tiny tests. Our test set has only 3 rows. When we repeated the split with 20 different random_state values, the test RMSE ranged from 1.97 to 5.37, and the test R² ranged from 0.60 to 0.99. Same data, same algorithm, very different scores. With ten rows you can learn the workflow, but you cannot trust the exact decimals. Real projects keep hundreds or thousands of test rows.
Step 3: Train the model with .fit()
This is the moment learning happens. .fit runs the least-squares proof from earlier, using only the training rows.
model.fit(X_train, y_train)
print(f"slope m = {model.coef_[0]:.4f}")
print(f"intercept c = {model.intercept_:.4f}")Output:
slope m = 6.1089
intercept c = 29.9802The slope is 6.1089, not exactly 6, because the model saw only 7 of the 10 students. A different set of training rows gives a slightly different line. That is normal.
Step 4: Test the model with .predict()
Now we ask the trained model about the three hidden students and compare its guesses with the real marks.
y_pred = model.predict(X_test)
for hour, guess, truth in zip(X_test.ravel(), y_pred, y_test):
print(f"{hour:>4.0f} h predicted {guess:6.2f} actual {truth:3.0f} miss {truth - guess:+.2f}")Output:
9 h predicted 84.96 actual 80 miss -4.96
2 h predicted 42.20 actual 40 miss -2.20
6 h predicted 66.63 actual 68 miss +1.37The misses are −4.96, −2.20 and +1.37. Small compared with marks in the 40s to 80s, so the line generalises well.
Step 5: Measure the misses with metrics
One number summarises all the misses. The next sections explain each one, and this is the code:
from sklearn.metrics import mean_absolute_error, mean_squared_error, r2_score
mae = mean_absolute_error(y_test, y_pred)
mse = mean_squared_error(y_test, y_pred)
print(f"MAE = {mae:.3f}")
print(f"MSE = {mse:.3f}")
print(f"RMSE = {mse ** 0.5:.3f}")
print(f"R2 = {r2_score(y_test, y_pred):.3f}")
print(f"6.5 hours -> {model.predict([[6.5]])[0]:.2f} marks")Output:
MAE = 2.842
MSE = 10.435
RMSE = 3.230
R2 = 0.963
6.5 hours -> 69.69 marksRead it as: on students it has never seen, the model is off by about 2.8 marks on average, and it explains about 96% of the ups and downs. Always pass the real values first and the predictions second: metric(y_true, y_pred).
Then repeat: improve
If the test scores are poor, change something and run steps 2 to 5 again: more rows, better inputs, a different model, or fix bad data. Never change the model by peeking at the test rows over and over, or they stop being a fair test.
The whole workflow is in the playground below the lesson. Press Run to see these exact numbers.
scikit-learn Functions and Sources
Every function used in this lesson, in plain words, with the official page that documents it.
| Function | What it does, in plain words | Official source |
|---|---|---|
LinearRegression() |
Creates an empty least-squares model | API: LinearRegression |
.fit(X, y) |
Learns the best m and c from the rows you give it | API: LinearRegression |
.predict(X) |
Computes ŷ = m·x + c for each row | API: LinearRegression |
.coef_ and .intercept_ |
The learned m and c. coef_ is a list because there can be many inputs |
User guide: Ordinary least squares |
.score(X, y) |
R² on the rows you give it | API: LinearRegression |
train_test_split(...) |
Shuffles the rows and cuts them into a train part and a test part | API: train_test_split |
mean_absolute_error(y_true, y_pred) |
MAE: the average size of the misses | API: mean_absolute_error |
mean_squared_error(y_true, y_pred) |
MSE: the average squared miss. Take ** 0.5 for RMSE |
API: mean_squared_error |
r2_score(y_true, y_pred) |
R²: how much of the up-and-down in y the model explains | API: r2_score |
PolynomialFeatures(degree) |
Adds x², x³, … as extra inputs so a "linear" model can draw a curve | API: PolynomialFeatures |
array.reshape(-1, 1) (NumPy) |
Turns a flat list into one column, the shape X must have |
NumPy: reshape |
More official reading:
- All regression metrics in one place: User guide: Regression metrics
- Why we split data: User guide: Cross-validation
- A runnable official example: Ordinary least squares example
- The
.fitsolver inside scikit-learn isscipy.linalg.lstsq, the matrix route from the proof section.
Where the proof's symbols went in code
| In the proof | In scikit-learn |
|---|---|
| m | model.coef_[0] |
| c | model.intercept_ |
| ŷ | model.predict(X) |
| SSE | ((y - y_pred) ** 2).sum() (you compute it yourself) |
| R² | model.score(X, y) or r2_score(y, y_pred) |
When the Line Is Not Perfect
Real data is never a perfect line, and that is fine. Regression does not have an "accuracy percentage" like a quiz score. Instead we say:
- "The typical miss is about 2.9 marks" (RMSE), or
- "The line explains 97% of the ups and downs" (R²).
If you ever see R² = 1.000 on real data, be suspicious. It usually means the answer leaked into the inputs.
Here is every reason a line can be imperfect, with numbers you can reproduce in the lab above:
| Reason | What you see | Real numbers from our data | What to do |
|---|---|---|---|
| Noise (sleep, health, luck are not in the table) | Dots scatter widely around the line | "Noisy marks" preset: R² = 0.43, RMSE = 15.6 | Add the missing inputs; accept some error |
| No real link between x and y | Almost flat line | "No link at all" preset: R² = 0.02 | This input cannot predict y. Try another |
| A curved pattern | Dots curve away from the line at both ends | Curved data: line RMSE = 9.4 | Add x² (polynomial regression) |
| One outlier | The line tilts toward one far dot | Change the last mark from 91 to 26: slope 6.0 to 2.5, R² 0.97 to 0.15 | Plot the data, fix typos, or use a robust method |
| Too few rows or an unlucky split | Scores jump around between splits | 20 splits: test RMSE 1.97 to 5.37 | Get more rows, or average over many splits (cross-validation) |
| Asking outside the data (extrapolation) | A prediction that makes no sense | 24 hours gives 174 marks, above the maximum of 100 | Only predict inside the range you trained on |
| Typing or measurement errors | Isolated points far from the pattern | Same as an outlier | Clean the data first |
| Broken conditions | Gaps fan out or follow a pattern | See the conditions section below | Transform the data or change the model |
The section Why is the line not perfect? Automatic checks at the bottom of the lab reads your numbers and says which of these is probably happening.
Underfit, Good Fit, Overfit
Picture three students before an exam:
- Underfit: read only the chapter titles. Too simple. Fails on the practice questions and the exam.
- Overfit: memorised last year's answer sheet word for word. Scores full marks on practice, then fails when the questions change.
- Good fit: understood the ideas. Does well on both.
A model behaves the same way. Our straight line is the simplest curve there is. Give it data that bends and it underfits. Give a model too much freedom and it overfits by memorising the noise.
| Underfit | Good fit | Overfit | |
|---|---|---|---|
| Training error | High | Low | Almost zero |
| Test error | High (about the same) | Low (a bit above training) | Much higher than training |
| What the curve does | Too stiff; misses the pattern | Follows the pattern | Wiggles through every dot |
| Fix | Add x², more inputs, or a more flexible model | Keep it. Check on fresh data | More rows, a simpler model, or regularization |
In the lab, every third student is hidden as a test row. The slider adds bends to the curve (the polynomial degree). Watch both errors as you move it.
Loading interactive lab…
Here is the same experiment in scikit-learn, on the curved data (15 students):
import numpy as np
from sklearn.linear_model import LinearRegression
from sklearn.metrics import mean_squared_error
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import PolynomialFeatures
curve_hours = np.array([0.5, 1, 1.5, 2, 2.5, 3, 3.5, 4, 4.5, 5, 5.5, 6, 6.5, 7, 7.5]).reshape(-1, 1)
curve_marks = np.array([42, 47, 62, 64, 74, 72, 81, 85, 82, 88, 81, 84, 78, 80, 70], dtype=float)
is_test = np.arange(len(curve_hours)) % 3 == 1 # every third student is hidden
X_train, y_train = curve_hours[~is_test], curve_marks[~is_test]
X_test, y_test = curve_hours[is_test], curve_marks[is_test]
for degree in (1, 2, 3, 5, 9):
model = make_pipeline(PolynomialFeatures(degree, include_bias=False), LinearRegression())
model.fit(X_train, y_train)
train_rmse = mean_squared_error(y_train, model.predict(X_train)) ** 0.5
test_rmse = mean_squared_error(y_test, model.predict(X_test)) ** 0.5
print(f"degree {degree}: train RMSE {train_rmse:5.2f} | test RMSE {test_rmse:5.2f}")Output:
degree 1: train RMSE 9.42 | test RMSE 9.16
degree 2: train RMSE 2.33 | test RMSE 3.37
degree 3: train RMSE 2.21 | test RMSE 3.70
degree 5: train RMSE 1.67 | test RMSE 5.56
degree 9: train RMSE 0.00 | test RMSE 21.18Read it row by row:
- Degree 1 (underfit): both errors are high and close together (9.4 and 9.2). The straight line cannot bend.
- Degree 2 (good fit): both errors drop to about 2 to 3. A gentle curve matches the real pattern.
- Degree 5 to 9 (overfit): training error keeps falling toward 0.00 while test error climbs to 21.18. The model memorised its training rows.
Plain linear regression is degree 1. The fixes belong to the next lessons: Polynomial Regression (add bends), Regularization and Ridge Regression (stop it getting too wild). See the idea in more depth in Bias and Variance and Learning Curves.
Official example with the same idea: scikit-learn: Underfitting vs. Overfitting.
Metrics: How Good Is the Line?
A metric turns all the misses into one number. We use four. First, the misses of the best line on all 10 students (ŷ = 6x + 30):
| Hours | Marks | ŷ | Miss (y − ŷ) | Absolute miss | Squared miss |
|---|---|---|---|---|---|
| 1 | 39 | 36 | 3 | 3 | 9 |
| 2 | 40 | 42 | −2 | 2 | 4 |
| 3 | 49 | 48 | 1 | 1 | 1 |
| 4 | 50 | 54 | −4 | 4 | 16 |
| 5 | 57 | 60 | −3 | 3 | 9 |
| 6 | 68 | 66 | 2 | 2 | 4 |
| 7 | 77 | 72 | 5 | 5 | 25 |
| 8 | 79 | 78 | 1 | 1 | 1 |
| 9 | 80 | 84 | −4 | 4 | 16 |
| 10 | 91 | 90 | 1 | 1 | 1 |
| Total | 26 | 86 |
| Metric | Formula in words | Our number | How to read it | Watch out |
|---|---|---|---|---|
| MAE (mean absolute error) | Average of the absolute misses | 26 ÷ 10 = 2.6 marks | "On average the line is off by 2.6 marks" | Treats a miss of 10 as just ten times a miss of 1 |
| MSE (mean squared error) | Average of the squared misses | 86 ÷ 10 = 8.6 | The number the proof minimised | Units are marks², so it is hard to picture |
| RMSE (root mean squared error) | Square root of MSE | √8.6 = 2.933 marks | "A typical miss is about 2.9 marks" | Bigger than MAE when a few misses are large |
| R² (R-squared) | 1 − SSE ÷ SST | 1 − 86 ÷ 3056 = 0.972 | "Explains 97% of the ups and downs in marks" | Can mislead on its own: always look at the plot |
Rules of thumb:
- RMSE and MAE are in the same unit as y. Judge them against what a miss costs. A 2.9 mark miss is small for a 100-mark exam, but a 2.9 degree miss may be huge in a medical device.
- R² = 1 is perfect, R² = 0 is no better than always guessing the average, and on test data R² can go negative, meaning the model is worse than guessing the average.
- RMSE ≥ MAE always. If RMSE is much larger than MAE, a few big misses are hiding in the data.
- Training R² always flatters. Add enough inputs and training R² creeps up even when the new inputs are junk. Trust the test R².
Training vs test, for our workflow: all 10 rows with the best line give R² = 0.972 and RMSE = 2.933. The 3 hidden test rows give R² = 0.963 and RMSE = 3.230. The two are close, which tells us the model generalises.
Sources: User guide: Regression metrics · Wikipedia: Coefficient of determination
Conditions: When Linear Regression Works
The line is always computed. Whether you can trust it depends on these conditions. Check them before you report a result.
| Condition | In plain words | How to check | If it fails |
|---|---|---|---|
| Linearity | The pattern is roughly a straight line | Scatter plot; the gaps (red bars) should look random | Add x² or another model |
| Independent rows | One row does not influence another | Ask how the data was collected (the same student twice? a time series?) | Group the data or use time-series methods |
| Equal spread | The misses are about the same size for small and large x | Gaps should not fan out like a funnel | Transform y (such as a log) or weight the rows |
| Roughly normal errors | Misses are mostly small, with a few big ones | Histogram of the misses. Only needed for confidence intervals and p-values, not to get the line | Use more rows or a different method for intervals |
| No wild outliers | No single point controls the line | Plot, then remove the point and refit | Fix typos or use a robust method |
| Inputs not copies of each other (many inputs only) | Two inputs that say the same thing confuse the weights | Correlation table between inputs | Drop one of them |
| Numbers only | Text must be turned into numbers first | Check the column types | Encode categories first |
The theory behind these: the Gauss–Markov theorem says that when the misses have an average of zero, equal spread, and are not related to each other, least squares has the lowest variance of all linear unbiased estimators. Normality is not needed for that. Always plot first: the famous Anscombe's quartet is four very different datasets that share the same slope, intercept and correlation. Only a picture tells them apart.
Sources: Wikipedia: Gauss–Markov theorem · Wikipedia: Ordinary least squares, assumptions
If You Get an Error
These are the real messages from scikit-learn 1.8. The wording may differ a little in your version, but the meaning is the same.
| You see | What it means | Fix |
|---|---|---|
ValueError: Expected 2D array, got 1D array instead |
X is a flat list. scikit-learn wants a table, even with one column |
hours.reshape(-1, 1) |
ValueError: Found input variables with inconsistent numbers of samples: [10, 9] |
X has 10 rows but y has 9 |
Make both the same length. Print X.shape and y.shape |
ValueError: Input X contains NaN |
A missing value is in the data | Remove or fill the missing rows before .fit |
NotFittedError: This LinearRegression instance is not fitted yet |
You called .predict before .fit |
Run model.fit(X_train, y_train) first |
ValueError: X has 2 features, but LinearRegression is expecting 1 features as input |
You passed a different number of columns than you trained with | Pass the same columns, in the same order |
ValueError: dtype='numeric' is not compatible with arrays of bytes/strings |
The data has text such as "yes" | Convert the text to numbers first |
A debugging routine that finds most errors in under a minute:
- Read the last line of the error. It names the problem.
- Print the shapes:
Xshould be(rows, columns)andyshould be(rows,). - Check for missing values.
- Check the order: create, split, fit, predict, measure.
print(hours.shape, marks.shape)
print(np.isnan(hours).any(), np.isnan(marks).any())Output:
(10, 1) (10,)
False FalseSilent mistakes are worse than errors because nothing crashes:
- Swapping the order in
r2_score(y_pred, y_test)gives 0.966 instead of the right 0.963. Alwaysmetric(y_true, y_pred). - Calling
.fit(X_test, y_test)makes the test rows part of training, so the test score is no longer honest. - Trusting a great training score without checking the test score.
Common Mistakes
- Treating a high R² as proof the model is right. Plot it. Anscombe's quartet has the same R² for very different shapes.
- Predicting outside the training range. A line keeps going forever: 24 hours of study gives 174 marks.
- Fitting on the test rows. The test set must stay unseen until the end.
- Judging the model on the training score. Always report the test score too.
- Ignoring one outlier. One wrong mark moved R² from 0.97 to 0.15.
- Reading the slope as cause and effect. The slope says "students who studied more scored more", not "studying caused it". Sleep or interest could drive both.
- Forgetting to reshape X. One input is still a table with one column.
- Comparing metrics across different y units. An RMSE of 3 means different things for marks and for house prices.
Interview Questions
- What does linear regression do? It fits a straight line (or flat plane) that predicts a number from inputs by choosing the weights that minimise the sum of squared errors.
- Why squared error instead of absolute error? Squares stop positive and negative misses cancelling, punish large misses more, and give a smooth curve with a single lowest point that can be solved exactly.
- Why does the best line pass through (x̄, ȳ)? Setting the derivative of the squared error with respect to c to zero gives
c = ȳ − m·x̄. - What is the closed-form solution for one input?
m = Σ(x−x̄)(y−ȳ) ÷ Σ(x−x̄)²andc = ȳ − m·x̄. With many inputs it isβ = (XᵀX)⁻¹Xᵀy. - When can the normal equations fail? When columns of X are exact copies of each other, so XᵀX has no inverse. scikit-learn uses
lstsq, which still returns an answer. - How do MAE and RMSE differ? Both are in the unit of y. RMSE punishes big misses more, so it is always at least as big as MAE.
- What does R² = 0 mean? What does a negative R² mean? 0 means no better than predicting the average of y. Negative means worse than that, which can happen on test data.
- How do you tell overfitting from underfitting? Underfit: training and test errors are both high. Overfit: training error is tiny but test error is much larger.
- Name the assumptions. Linearity, independent rows, equal spread, roughly normal errors (only for intervals), and no wild outliers.
- Why must
Xbe 2D in scikit-learn? Every model expects a table of rows and columns so the same code works for one input or a thousand.
Practice Problems
Try each one before opening the answers underneath.
- By hand. Three students: (1, 2), (2, 4), (3, 5). Find m and c with the Sxy ÷ Sxx method. Predict x = 4.
- Read a line. The line is
ŷ = 6x + 30. What mark does it predict for 8.5 hours? A student scored 85 for 8.5 hours. What is the miss? Why is asking about 20 hours a bad idea? - Metrics by hand. A model's misses on four test rows are 3, −4, 2, −1. Find MAE, MSE and RMSE.
- Explain. A model has R² = 0 on the test set. What does that tell you?
- Lab task. In the Fit a Line lab type X
1, 2, 3, 4and Y2, 4, 6, 20. Predict the slope, intercept and R², then check. What would the slope have been if the last mark was 8? - Code task. In the playground change
random_state=42to0and run it. Do the test rows change? Does the RMSE?
Answers
- x̄ = 2, ȳ = 11/3 ≈ 3.667, dx = −1, 0, 1, dy ≈ −1.667, 0.333, 1.333. So Sxy = 3, Sxx = 2, m = 1.5, c ≈ 0.667. At x = 4 the prediction is about 6.67.
- 6 × 8.5 + 30 = 81. The miss is 85 − 81 = +4. At 20 hours the line says 150 marks, above the maximum of 100, so it is extrapolation.
- MAE = (3 + 4 + 2 + 1) ÷ 4 = 2.5. MSE = (9 + 16 + 4 + 1) ÷ 4 = 7.5. RMSE = √7.5 ≈ 2.739.
- The model is no better than always predicting the average value of y. It has learned nothing useful from the inputs.
- m = 5.6, c = −6, R² ≈ 0.784. One large mark pulls the line a long way. If the last mark was 8, the points lie exactly on
y = 2xwith m = 2, c = 0 and R² = 1. - Yes. With
random_state=0the test hours are 3, 9 and 5 and the test RMSE is about 3.97. A different split gives different numbers, which is why a tiny test set is unreliable.
Mindmap
The same map as a list, for screen readers and small phones:
- Idea: ŷ = m·x + c. One input gives one number. The best straight line.
- Math: least squares. The line hits (x̄, ȳ). c = ȳ − m·x̄. m = Sxy ÷ Sxx.
- Workflow: 1 create the model, 2 split, 3 fit, 4 predict, 5 measure.
- Metrics: MAE is the average miss. RMSE is the typical miss. R² is the share explained.
- Problems: underfit (too stiff), overfit (memorises), outliers drag the line, extrapolation is risky.
- Conditions: a straight-ish pattern, independent rows, similar spread, few wild outliers.
Summary
- Linear regression predicts a number with a straight line
ŷ = m·x + c. - The best line makes the total squared miss as small as possible.
- That total is a bowl. Its lowest point gives
c = ȳ − m·x̄andm = Sxy ÷ Sxx. For our data the line isŷ = 6x + 30. - scikit-learn does the same job with a matrix solver. The answers match.
- The workflow never changes: create, split, fit, predict, measure.
- Judge the model with MAE, RMSE, R² on the test rows.
- A line can be imperfect because of noise, outliers, curves, tiny data or extrapolation. Plot first.
- Too simple means underfit. Too flexible means overfit. Look for the lowest test error.
What to Learn Next
You now own the template that every other algorithm follows: idea, data, math, lab, five steps, metrics, errors.
- Polynomial Regression: bend the line when the data curves.
- Ridge Regression and Lasso Regression: keep a flexible model from overfitting.
- Logistic Regression: the same idea, but for yes or no answers.
- Model Selection and Learning Curves: choose between models fairly.
Loading playground…
Check your understanding
Linear Regression Quiz
In the line ŷ = m·x + c, what does c tell you?
1 / 12