Linear Regression Explained: 5 Simple Steps for Beginners

⚡ TL;DR: Linear regression fits a straight line through your data and uses it to predict a number. It finds the line by making the total squared vertical distance from the points to the line as small as possible. It is the first algorithm worth learning properly.

Linear regression is where almost every machine learning course begins, and for good reason: it is simple enough to work through by hand, yet it contains nearly every idea you will meet later — parameters, a loss function, gradient descent, and evaluation. Understand this one properly and the rest gets much easier.

What linear regression actually does

Linear regression predicts a number — a house price, a temperature, an exam score — from one or more input features. It does this by assuming the relationship is roughly a straight line:

$$\hat{y} = wx + b$$

✅ Reading that equation: x is your input (floor area). ŷ is the prediction (price). w is the slope — how much the price rises per extra square metre. b is the intercept — where the line crosses the axis. Linear regression’s whole job is to choose good values for w and b.

If that looks like the y = mx + c from school, it is exactly that. The difference is that you are not given w and b — the algorithm works them out from data. That is what makes it a machine learning model.

How linear regression chooses the line

Infinitely many lines could be drawn through a cloud of points. Linear regression picks one specific line, using a rule called least squares.

Linear regression best-fit line through house price data with red residual lines showing the vertical error at each point
Each red line is a residual — the gap between what actually happened and what the line predicted. Linear regression minimises the sum of those gaps, squared.

For each house, take the vertical distance between the real price and the line’s prediction. That distance is the residual. Square it, add up all the squares, and you have the total error:

$$\text{MSE} = \frac{1}{n}\sum_{i=1}^{n}(y_i – \hat{y}_i)^2$$

That is mean squared error, and it is the loss function linear regression minimises.

🧪 Why square the errors?

Two reasons. First, squaring makes every error positive, so a miss of +10 and a miss of −10 do not cancel out to zero.

Second, squaring punishes big misses disproportionately: being wrong by 20 costs four times as much as being wrong by 10, not twice as much. That pushes the line towards avoiding large errors, which is usually what you want. When it is not what you want — because outliers are dragging the line around — use Huber loss or mean absolute error instead.

Five steps to fit a linear regression by hand

With one feature you can compute the answer exactly, no iteration required. Here is the whole procedure on four data points.

1
Find the mean of x and of y
2
Subtract the means from each value
3
Multiply the pairs and sum
4
Divide to get the slope w
5
Back out the intercept b

The slope formula is:

$$w = \frac{\sum (x_i – \bar{x})(y_i – \bar{y})}{\sum (x_i – \bar{x})^2}, \qquad b = \bar{y} – w\bar{x}$$

🧪 Worked example: four houses

Area xPrice yx − x̄y − ȳproduct(x − x̄)²
50150−25−601500625
60180−15−30450225
902401530450225
10027025601500625
x̄ = 75ȳ = 210Σ = 3900Σ = 1700
w = 3900 ÷ 1700 = 2.294  ·  b = 210 − (2.294 × 75) = 37.9
So the fitted line is price = 2.294 × area + 37.9. A 75 m² house predicts £210k — exactly the mean, which is always true: the least-squares line passes through (x̄, ȳ).

Check it yourself with the linear regression calculator.

Multiple linear regression: more than one feature

Real problems have several inputs. The idea does not change — each feature gets its own weight:

$$\hat{y} = w_1x_1 + w_2x_2 + \dots + w_nx_n + b$$

With two features you are fitting a plane rather than a line; beyond that, a hyperplane you cannot picture. The arithmetic stays identical, which is exactly why it is expressed with matrices — one dot product handles all features at once. This is where your linear algebra starts paying off.

⚠️ With multiple features, scale them first

If one feature is measured in square metres and another in pounds, their weights are not comparable and gradient descent struggles. See feature scaling.

The assumptions linear regression makes

Linear regression is not magic — it assumes things about your data, and when those assumptions break, the predictions quietly become unreliable.

AssumptionWhat breaks itHow to spot it
LinearityThe real relationship curvesPlot residuals — a pattern means curvature
IndependenceRows influence each other (time series)Residuals correlated in order
Constant varianceErrors grow with the predictionResidual plot fans out like a cone
No strong collinearityTwo features carry the same informationCheck the correlation matrix

How to tell if your linear regression is any good

  • R² (coefficient of determination) — the share of the variation in y your model explains. 0 means no better than predicting the average; 1 means perfect. On real data, 0.6 is often respectable.
  • RMSE — average error in the original units. If RMSE is £24,000, your price predictions are typically about £24k out. Far more interpretable than R² for explaining results to someone else.
  • MAE — the same idea but less sensitive to a few large misses.

Whichever you choose, measure it on held-out test data. R² on the training set will only ever flatter you.

Linear regression vs logistic regression

✅ The one-line difference: Linear regression predicts a number (how much?). Logistic regression predicts a probability of a category (which one?). If your answer is a price, use linear regression; if it is yes-or-no, use logistic regression.

Common linear regression mistakes

⚠️ Four traps

  • Reading correlation as cause. A positive weight on ice-cream sales when predicting drownings does not mean ice cream drowns people. Both rise in summer.
  • Extrapolating beyond your data. A model fitted on 50–150 m² houses says nothing trustworthy about a 900 m² mansion.
  • Ignoring outliers. Because errors are squared, a single wild point can visibly tilt the whole line.
  • Trusting R² alone. Adding any feature — even random noise — never decreases R² on training data. Use adjusted R², or check the test set.

🔑 Key Takeaways

  • Linear regression predicts a number by fitting a straight line, ŷ = wx + b.
  • It chooses the line by minimising the sum of squared residuals — least squares.
  • With one feature you can solve it exactly by hand; with many, it becomes matrix arithmetic.
  • Judge it with RMSE or MAE on test data, not R² on training data.
  • Check the assumptions — especially linearity and outliers — before trusting the coefficients.

Further reading

scikit-learn’s linear models guide documents ordinary least squares alongside its regularised cousins, Ridge and Lasso, and Wikipedia’s article on ordinary least squares gives the full derivation if you want the algebra behind the formula above.

Where to go next

Scroll to Top