DEV Community

Cover image for Linear Regression
saksham780
saksham780

Posted on

Linear Regression

Linear Regression: Drawing the Best Line Through Messy Data

If you've ever tried to guess what a flat should rent for, you've already done a rough version of linear regression in your head. Bigger flat, higher rent. Closer to the station, higher rent again. You weigh those things, add them up, and land on a number.

Linear regression is just that habit, made precise. It's usually the first model people learn, and honestly, it's one I still reach for before anything fancier.

The idea

You have inputs (size, age, distance to the metro) and one number you want to predict (rent). Linear regression says the answer is a weighted sum of the inputs, plus a starting value:

y = w1*x1 + w2*x2 + ... + b

Each weight tells you how much the prediction moves when that input goes up by one unit, with everything else held still. The b is the baseline, what you'd predict if every input were zero.

With a single input, this is the line from school: y = mx + c. With many inputs, it's a flat surface in higher dimensions. You can't picture it, but the maths doesn't care.

What does "best line" even mean?

Plot your data and you'll see that no single line passes through every point. Some sit above, some below. The gap between a point and the line is called a residual.

So we need a rule for judging lines. The usual choice is mean squared error (MSE): take every residual, square it, and average them. Squaring does two useful things. It stops positive and negative errors from cancelling out, and it punishes big misses much harder than small ones. One prediction that's off by 10 hurts more than ten predictions that are each off by 1.

The "best" line is the one with the lowest MSE. This approach is called ordinary least squares.

How the model finds its weights

There are two common routes.

  1. Solve it directly. For linear regression there's a neat formula (the normal equation) that gives the ideal weights in one shot. It's fast for small problems, but gets slow and numerically touchy when you have thousands of features.

  2. Gradient descent. Start with random weights. Check which direction makes the error smaller, take a small step that way, and repeat. It's like walking down a hill in thick fog: you can't see the valley, but you can feel the slope under your feet. The size of each step is the learning rate. Too big and you overshoot, too small and you'll be waiting all day.

Because the error surface for linear regression is a smooth bowl with one bottom, gradient descent always gets there.

A quick example in Python

python

import numpy as np
from sklearn.linear_model import LinearRegression

size in sq. metres, age in years

X = np.array([[50, 10], [65, 5], [80, 8], [95, 2], [120, 1]])
y = np.array([22000, 30000, 33000, 45000, 58000]) # monthly rent

model = LinearRegression().fit(X, y)
print(model.coef_, model.intercept_)
print(model.predict([[75, 4]]))

The printed coefficients are the weights. If the one for size comes out at around 500, that reads as "each extra square metre adds roughly 500 to the rent." That readability is a big part of why people love this model.

How do you know it's any good?

Two numbers show up constantly:

  • RMSE (root mean squared error): the typical size of your miss, in the same units as what you're predicting. Easy to explain to non-technical people.
  • R²: the share of the variation in the data your model explains. 1 means perfect, 0 means you may as well have predicted the average every time. Always measure these on data the model hasn't seen. A model that looks brilliant on its own training data and falls apart on new data hasn't learned anything useful.

Where it goes wrong

Linear regression makes some assumptions, and when they're badly broken the results get shaky.

  • The relationship has to be roughly linear. If rent shoots up faster as flats get bigger, a straight line will under-predict the big ones. You can sometimes fix this by transforming a feature (say, taking its square or its log).
  • Outliers pull the line hard. Because errors are squared, one wildly wrong data point can drag the whole fit toward it. Always look at your data first.
  • Features that are near-copies of each other (say, size in square feet and size in square metres) make the individual weights unstable and hard to interpret, even if the predictions stay fine.
  • Residuals should look like random noise. If you plot them and see a clear curve or a funnel shape, the model is missing something. When you have lots of features, Ridge and Lasso regression add a penalty on large weights. That keeps the model from chasing noise, and Lasso goes further by pushing unhelpful weights all the way to zero.

When to use it

Reach for linear regression when you want a quick baseline, when you need to explain exactly why the model predicted what it did, or when your data is small. Plenty of real-world forecasting, pricing and scientific analysis still runs on it, and for good reason: it's simple, it's honest, and it's very hard to get embarrassingly wrong.

Takeaways

  • It predicts a number as a weighted sum of inputs.
  • "Best" means lowest squared error.
  • Weights can be found directly or with gradient descent.
  • Check it on unseen data, and look at your residuals.
  • Its biggest strength is that you can read it.

Top comments (0)