AI & MLDeep
Beginner

Linear Regression

11 min read

Learn
Deep Reading
Estimated 11 mins
Prereq
Foundational
No experience required
Interactive
Static Playbook
Static guide & reference tables

What linear regression actually does

Linear regression learns a function that maps input features to a numeric output. Given historical house data — size, number of rooms, location — it learns to predict price. Given patient vitals, it predicts a blood pressure reading. The relationship it learns is always a weighted sum of the inputs.

For a single input x, the hypothesis is: h(x) = w₁x + w₀

For multiple inputs (multivariate), it becomes: h(x) = w₀ + w₁x₁ + w₂x₂ + ... + wₙxₙ

Every w is a weight — a number the model learns. w₀ is the intercept (also called bias) — the baseline prediction when all features are zero. Training is the process of finding the weight values that make the predictions as accurate as possible.

The loss function: measuring how wrong you are

To train the model, we need a way to measure its error. Linear regression uses squared error loss — for each training example, compute the difference between the prediction and the true value, then square it:

Loss = (y_predicted - y_true)²

Squaring does two things: it makes all errors positive (so over-predictions and under-predictions don't cancel out), and it penalises large errors more heavily than small ones. The total loss over all training examples is the Mean Squared Error (MSE).

The goal of training is to find weights w that minimise MSE.

Note

Absolute error (|predicted - actual|) is arguably more intuitive — it's the average size of your mistakes. But squared error has a smooth gradient everywhere, making it mathematically convenient for gradient descent. Absolute error has a kink at zero where the gradient is undefined. In practice, both work; squared error is the default for regression.

Finding the optimal weights

There are two ways to find the best weights:

Closed-form solution (analytical): Calculus gives us the exact formula: w* = (XᵀX)⁻¹ Xᵀy — where X is the matrix of training inputs and y is the vector of true outputs. This is exact and fast for small datasets, but computing (XᵀX)⁻¹ becomes very expensive for large datasets or many features.

Gradient descent (iterative): Start with random weights, compute the loss, compute which direction would reduce the loss (the gradient), and take a small step in that direction. Repeat until the loss stops improving. This is slower per step but scales to millions of examples.

python

Multivariate linear regression

Real problems have many features. A house price model might use size, rooms, age, distance to transport, and neighbourhood rating all at once. Multivariate linear regression handles this naturally — each feature gets its own weight.

With multiple features, the update rule for each weight wᵢ becomes:

wᵢ ← wᵢ + α × Σ(yⱼ - h(xⱼ)) × xⱼᵢ

where α is the learning rate and the sum is over all training examples j. In practice, this is computed as a matrix multiplication, which GPUs handle extremely efficiently.

Overfitting and regularisation

With many features, linear regression can overfit — fitting the noise in training data so precisely that it fails on new examples. The fix is regularisation: add a penalty to the loss function for large weights.

L2 regularisation (Ridge): adds λ × Σwᵢ² to the loss. Shrinks all weights towards zero proportionally. Better when many features contribute a little.

L1 regularisation (Lasso): adds λ × Σ|wᵢ| to the loss. Tends to set irrelevant feature weights to exactly zero, producing a sparse model — effectively doing feature selection for you. Better when you suspect only a few features actually matter.

λ (lambda) controls the strength of regularisation. Tune it with cross-validation.

Note

If the true relationship between your features and target is non-linear (e.g. salary doesn't scale linearly with age — it curves), linear regression will systematically under- or over-predict. Common fixes: add polynomial features (, ), use feature transformations (log, sqrt), or switch to a non-linear model like a decision tree or neural network.

When to use linear regression

Linear regression is your first tool to try when the target is a continuous number. It is fast to train, easy to interpret (each weight tells you the marginal effect of that feature), and provides a strong baseline. If a more complex model can't beat it significantly, the data may genuinely be close to linear.

Use it for: price prediction, demand forecasting, scoring models, any task where you need an explainable model and a linear relationship is plausible.

What's next

Linear regression predicts continuous values. Logistic regression adapts the same framework to predict probabilities — turning it into a classifier. The next lesson covers how the sigmoid function and cross-entropy loss transform regression into the building block of most classification pipelines.

I build these systems professionally.

Whether it's a RAG pipeline, analytics migration, or AI workflow — let's talk.

Need custom AI or MarTech setup? Let's build together.