←Blog

Linear Regression: How It Works and Where It Hides in Machine Learning

Linear Regression: How It Works and Where It Hides in Machine Learning

Linear regression is usually the first thing you learn in any machine learning course, and it's also the first thing a lot of people skip past because it seems too simple to matter. You draw a line through some points. Big deal. But it turns out that line is hiding inside almost everything else in machine learning. Logistic regression, support vector machines, and every layer of a neural network (including the giant ones behind ChatGPT and Claude) are all built around the same little equation. So in this post, I wanna go over what linear regression actually is, how it finds the "best" line (including the math, both the exact way and the gradient descent way), and where it shows up in the algorithms people use every day.

What linear regression is

Linear regression is a way to predict a number from one or more other numbers, assuming the relationship between them is roughly a straight line. The classic example is house prices. Say you have a list of houses with their size and what they sold for:

size (1000s of sq ft)   0.8   1.1   1.4   1.6   1.9   2.2   2.5   3.0
price ($1000s)          155   190   230   245   290   315   350   410

If you plot those, they make a pretty clear upward trend, and you'd like a formula that says "a house this big probably costs about this much." The simplest formula is a line:

ŷ = w·x + b

Here x is the input (the size), ŷ (pronounced "y hat") is the predicted price, w is the slope, and b is the intercept, which is where the line crosses zero. In machine learning, w is usually called the weight and b the bias, and those names will come back later when we get to neural networks. "Training" a linear regression just means picking the values of w and b that fit the data best.

For this data, the best line turns out to be w = 115 and b = 64.7. In plain English, every extra 1,000 square feet adds about $115k to the price, on top of a $64.7k baseline. A 2,000 square foot house would be predicted at 115 × 2 + 64.7, or about $295k.

More than one input

Real houses have more than one thing going for them. Maybe you also know the number of bedrooms, the age of the house, and the distance to downtown. Linear regression handles that by giving each input its own weight and adding them up:

ŷ = w₁x₁ + w₂x₂ + w₃x₃ + … + b

That's a dot product, so it's usually written as ŷ = w · x + b, where w and x are lists (vectors) of numbers. With two inputs, the "line" becomes a flat plane, and with more it becomes a hyperplane, which is hard to picture but works exactly the same way mathematically. Each weight tells you how much the prediction changes when that one input goes up by one and the others stay the same, which is a big part of why people like linear models: you can actually read them.

If you stack every house into a matrix X, with one row per house and one column per input, you can predict all of them at once:

ŷ = Xw

The bias is folded in by adding a column of 1s to X, so its weight acts as b. Keep that matrix form in mind, because it's exactly what a neural network layer looks like.

What "best" means: least squares

There are infinitely many lines you could draw through those points, so we need a way to score them. For each house, the residual is how far off the prediction was: y − ŷ, the actual price minus the predicted one. Some residuals are positive (we guessed too low) and some are negative (too high), so we can't just add them up, because they'd cancel out. Instead, linear regression squares each one and takes the average. That's the mean squared error, or MSE:

L(w, b) = (1/n) · Σ (w·xᵢ + b − yᵢ)²

The "best" line is the one with the smallest L. That's why ordinary linear regression is also called least squares, and the idea is old. Adrien-Marie Legendre published it in 1805, and Carl Friedrich Gauss published his version in 1809 (he claimed he'd been using it since 1795, which started a long argument about who got there first).

The squaring is literal, which is easy to forget. Each squared error is the area of an actual square whose side is the residual, so least squares is finding the line where the total area of those squares is as small as it can be:

The same eight points fit by two lines, with each residual drawn as a square. A hand-picked guess has a total square area of 8.3. The least squares line, y = 0.76x + 1.50, has a total area of 3.5, the smallest any line can get.
Least squares, literally: the best line is the one with the least total square area.

Why squares and not just the absolute value of each miss? A few reasons:

  • Big misses get punished a lot more than small ones. Being off by 10 costs 100, while being off by 1 costs 1. So the line works hard to avoid any really bad predictions. That's mostly a good thing, but it also means a single crazy outlier can drag the whole line toward it, which we'll come back to.
  • It's smooth. A squared function has a nice clean slope everywhere, which makes it easy to minimize with calculus. The absolute value has a sharp corner at zero.
  • It has an exact answer. Because of that smoothness, you can solve for the best w and b directly, with no trial and error.
  • It has a statistical justification. If you assume the noise in your data is random and follows a bell curve (a normal distribution), then the least squares line is also the most likely line given your data. That's the "maximum likelihood" estimate, if you've heard that term.

Finding the best line, way 1: just solve it

Here's where the math comes in, but stick with me, because it's only one idea. At the bottom of a smooth valley, the ground is flat. So the lowest point of L is where its slope (its derivative) is zero with respect to both w and b. Taking those derivatives:

∂L/∂w = (2/n) · Σ (w·xᵢ + b − yᵢ) · xᵢ
∂L/∂b = (2/n) · Σ (w·xᵢ + b − yᵢ)

Set both to zero and solve, and you get two formulas you can compute directly:

w = Σ (xᵢ − x̄)(yᵢ − ȳ) / Σ (xᵢ − x̄)²
b = ȳ − w·x̄

Here x̄ and ȳ are just the averages of x and y. The formula for w is the covariance of x and y divided by the variance of x, which sounds fancy but just means "how much do x and y move together, compared to how much x moves on its own." And the formula for b says the best line always passes through the point (x̄, ȳ), the center of the data.

With multiple inputs, the same idea in matrix form gives you what's called the normal equation:

w = (XᵀX)⁻¹ Xᵀy

One small practical note: libraries don't actually compute that inverse, because it can be numerically unstable when inputs are closely related to each other. They use a more careful method (like a QR decomposition or SVD) that gives the same answer. That's what np.linalg.lstsq and scikit-learn's LinearRegression do under the hood.

Finding the best line, way 2: gradient descent

If there's an exact formula, why would you ever do anything else? Because the formula doesn't scale forever. Solving the normal equation costs roughly d³ operations for d inputs, and it needs all your data in memory at once. That's fine for a few thousand features, but it falls apart for something with millions or billions of weights. And for almost every model more complicated than linear regression, there's no exact formula at all.

So instead, you can find the bottom of the valley by walking downhill. Those same derivatives from above, ∂L/∂w and ∂L/∂b, together make up the gradient, which points in the direction the error goes up fastest. Take a small step the opposite way, recompute, and repeat:

w ← w − η · ∂L/∂w
b ← b − η · ∂L/∂b

The η (the Greek letter eta) is the learning rate, which controls the size of each step. That's gradient descent, and it's the same algorithm (with some upgrades) that trains every large neural network today.

Here's the thing that makes linear regression a perfect place to learn it. If you plot the error L for every possible combination of w and b, you get a bowl. It has exactly one bottom and no other dips to get stuck in (mathematicians call that convex), so gradient descent will always find the best line as long as the steps aren't too big. You can try it yourself below. Drag the points around to change the data, then hit "run gradient descent" and watch the line on the left and its path through the error bowl on the right:

Interactive: tap anywhere on the bowl to start from a different line, or push the learning rate past the limit shown and watch it blow up.

A few things worth noticing if you play with it:

  • The learning rate matters a lot. Too small and it takes forever. Too big and each step overshoots the bottom of the bowl by more than the last one, so the error blows up instead of shrinking. For least squares you can actually calculate the cutoff: the learning rate has to be less than 2 divided by the steepest curvature of the bowl. For the house data in this post, that cutoff is about 0.21. At 0.1 it matches the exact answer to two decimal places in about 350 steps, and at 0.25 it diverges.
  • The path curves. The bowl is usually a long, narrow valley rather than a round dish, because changing the slope has a much bigger effect on the error than changing the intercept does. Gradient descent goes straight down the steep walls first and then slowly crawls along the valley floor. This is why people scale their inputs (subtract the average and divide by the spread) before training. It makes the bowl rounder and gradient descent a lot faster.
  • It ends up at the same place as the formula. On a convex problem, both methods find the same line, just in different ways.

Here's all of that in code. All three methods land on the same answer:

import numpy as np

# square footage (in thousands) and sale price (in $1000s)
x = np.array([0.8, 1.1, 1.4, 1.6, 1.9, 2.2, 2.5, 3.0])
y = np.array([155, 190, 230, 245, 290, 315, 350, 410])

# 1. closed form
w = np.sum((x - x.mean()) * (y - y.mean())) / np.sum((x - x.mean()) ** 2)
b = y.mean() - w * x.mean()
print(f"closed form:      w = {w:.2f}, b = {b:.2f}")

# 2. the same thing with matrices (a column of 1s gives us b)
X = np.column_stack([x, np.ones_like(x)])
(w2, b2), *_ = np.linalg.lstsq(X, y, rcond=None)
print(f"least squares:    w = {w2:.2f}, b = {b2:.2f}")

# 3. gradient descent
w3, b3, lr = 0.0, 0.0, 0.1
for step in range(20_000):
    err = (w3 * x + b3) - y
    w3 -= lr * 2 * np.mean(err * x)
    b3 -= lr * 2 * np.mean(err)
print(f"gradient descent: w = {w3:.2f}, b = {b3:.2f}")
closed form:      w = 115.00, b = 64.70
least squares:    w = 115.00, b = 64.70
gradient descent: w = 115.00, b = 64.70

"Linear" doesn't mean the line has to be straight

This one trips people up. The "linear" in linear regression means the prediction is a weighted sum of the inputs you give it. It doesn't care what those inputs are. So if your data curves, you can add x², x³, and so on as extra inputs:

ŷ = w₁x + w₂x² + w₃x³ + b

That's still linear regression, solved with the exact same formula, because it's still a weighted sum. It just has three inputs that happen to be computed from the same x. This is called polynomial regression, and the general trick of transforming your inputs before fitting is called feature engineering. You can do the same with logs, products of two inputs, yes/no flags, or whatever else describes the problem well.

But there's a catch. Give the model enough extra features and it can bend itself through every single point, noise included. It fits the data you trained it on perfectly and predicts new data terribly. That's overfitting, and the standard fix is regularization: add a penalty to the error for having large weights, so the model has to "pay" for every bit of wiggle.

L = MSE + λ · Σ wⱼ²     (ridge regression, also called L2)
L = MSE + λ · Σ |wⱼ|    (lasso regression, also called L1)

The λ (lambda) controls how strong the penalty is. Ridge still has an exact solution, w = (XᵀX + λI)⁻¹Xᵀy, and it shrinks all the weights toward zero. Lasso tends to push some weights to exactly zero, which makes it useful for figuring out which inputs actually matter. Here's what that looks like with a degree 12 polynomial fit to 14 noisy points:

Three fits to the same 14 noisy points. A straight line misses the curve, with an error of 0.215 on new points. A degree 12 polynomial with no penalty passes through nearly every point but swings wildly between them, with an error of 4.196 on new points. The same degree 12 polynomial with ridge regularization follows the true curve, with an error of 0.049 on new points.
The unpenalized fit nails the training points and is wildly wrong everywhere else. Ridge keeps the same features and fixes it.

That L2 penalty shows up again later under a different name. When you hear "weight decay" in neural network training, it's basically the same idea.

Where linear regression shows up in other algorithms

This is the part I think is actually the most interesting. Once you know linear regression, a huge chunk of machine learning turns out to be the same weighted sum, w · x + b, with something different wrapped around it. Either the output gets passed through a function, or the error is measured a different way, or both:

Inputs x1, x2 and x3 feed a weighted sum z = w·x + b. Passing z straight through gives linear regression. Passing it through a sigmoid gives logistic regression. Taking its sign gives the perceptron and linear SVM. Running many in parallel through ReLU gives a neural network layer.
Same linear core, different wrappers and different ways of measuring the error.

Logistic regression

Despite the name, logistic regression is used for classification, like "is this email spam or not?" A straight line is a bad fit for a yes/no answer, since it'll happily predict 1.7 or −0.4. So logistic regression computes the same weighted sum and then squashes it through the sigmoid function, which turns any number into something between 0 and 1:

z = w · x + b
p = σ(z) = 1 / (1 + e^(−z))

Now p can be read as a probability. Another way to look at it: logistic regression is a linear regression on the log-odds of the answer. Because the outputs are probabilities, it's trained with a different error (called cross-entropy or log loss) instead of MSE. There's no exact formula anymore, so it's trained with gradient descent. And here's the fun part. The gradient you end up with is (1/n)·Xᵀ(p − y), which is the exact same shape as the gradient for linear regression, just with predicted probabilities in place of predicted values. Same machinery, different wrapper.

The perceptron and linear SVMs

The perceptron, from 1958, is one of the oldest machine learning algorithms. It computes the same weighted sum and just checks whether it's above or below zero to pick a class. A linear support vector machine (SVM) does the same thing at prediction time, but trains with a "hinge loss" that tries to put as much space as possible between the two classes and the boundary line. In both cases, the decision boundary is the set of points where w · x + b = 0, which is a line, a plane, or a hyperplane, depending on how many inputs you have.

Neural networks

A single "neuron" in a neural network is a weighted sum plus a bias, passed through an activation function like ReLU (which just turns negative numbers into 0). In other words, it's a linear regression with a little twist at the end. A layer of neurons is a whole bunch of those running side by side on the same input, which is exactly the matrix form from earlier:

h = activation(Wx + b)

That's why they're called "dense" or "linear" layers. In PyTorch, it's literally nn.Linear. A network is these layers stacked up, with each layer's output feeding into the next.

The activation function in between is what makes the stack powerful, and you can see why with a bit of algebra. Without it, two linear layers in a row, W₂(W₁x), are the same as one linear layer with the weight matrix W₂W₁. You could stack a hundred of them and it would still just be one big linear regression. The nonlinearity in between is what lets each layer build curved, more complicated features out of the previous layer's output.

Large language models are no exception. In a transformer, the attention mechanism uses linear layers to create its queries, keys, and values. Each block has a feed-forward network that's two big linear layers with an activation in between, and the very last step that scores every possible next word is one more linear layer. Most of the billions of parameters in an LLM live in those weight matrices. (That's also why LoRA works the way it does. It fine-tunes a model by learning a small change to exactly those matrices.)

There's an even more direct connection, too. A very common way to train a neural network is to take one that's already trained, freeze it, and train just a new linear layer on top of its output. That's called a linear probe, or transfer learning. Researchers also use linear probes to test what a model "knows." If a simple linear regression on a model's internal numbers can predict something (like whether a sentence is true, or where a city is on a map), that information must be in there.

Gradient boosting and residuals

Gradient boosted trees (like XGBoost and LightGBM) aren't linear models, but they borrow the idea of residuals directly. With a squared error, each new tree is trained to predict the residuals of all the trees before it, the same y − ŷ leftovers from the squares picture above, and its predictions get added in to shrink them. In general, each tree is fit to the negative gradient of the error, which for squared error is exactly the residual. That's where the "gradient" in the name comes from.

As the baseline

And finally, the most common use of all: it's the thing you try first. Linear regression trains in milliseconds, you can read every weight, and it tells you how much of the problem a simple model can already handle. If a giant gradient boosting model or neural network can't clearly beat a linear regression on your data, that's a good sign the fancier model isn't worth the extra complexity (or that something's wrong with your data).

When linear regression goes wrong

It's simple, but it's not magic, and it fails in pretty predictable ways:

  • The relationship isn't actually linear. A straight line through a curve will be wrong in a consistent pattern. Plotting the residuals is the quickest check. If they look like random noise, you're good. If they form a shape, the model is missing something. Adding features (like the polynomial ones above) can help.
  • Outliers. Because errors are squared, one wild point can pull the whole line toward it. If your data has those, look into robust alternatives like Huber loss, which acts like squared error for small misses and absolute error for big ones.
  • Inputs that move together. If two inputs are nearly copies of each other (like square feet and square meters), the model can't tell which one deserves the credit, and the weights become unstable. The predictions might still be fine, but you can't trust what the individual weights are telling you. Ridge regression helps a lot here.
  • Extrapolation. The line keeps going forever, but your data doesn't. The house model has no idea what a 10,000 square foot house costs, and it'll confidently tell you anyway.
  • Correlation isn't causation. A weight tells you how the prediction changes with an input in your data. It doesn't tell you that changing that input in the real world would cause the outcome to change.

Wrapping up

Linear regression is a weighted sum of inputs plus a bias, with the weights chosen to make the total squared error as small as possible. You can solve for those weights exactly, or find them by walking downhill with gradient descent, and on a problem shaped like a bowl, both give you the same answer.

But the bigger reason it's worth understanding is that it never really goes away. Pass the output through a sigmoid and you have logistic regression. Swap the error for a hinge loss and you have a linear SVM. Stack a few hundred of them with activation functions in between and you have a neural network, trained with the same gradient descent you can watch in the demo above. Most of what the giant models are doing comes down to an enormous number of w · x + b.

#Discussion · 0 comments

Leave a comment

By submitting a comment, you verify that you agree to our Privacy Policy and Terms of Service.