Art of DS

Appearance

Palette
Theme
Unlock $20 one time
Sign in, or create an account

Sign in to Art of DSCreate your Art of DS account

We email you a link and a six-digit code. Either one signs you in; there is no password.Enter your email. We send a link and a six-digit code to confirm it — no password to remember. The account is free.

  • You come back to this page, right where you were.
  • Already have an account? The same email simply signs you in.

By continuing you accept the Terms and the Privacy policy.

Your account

Free accountLifetime access

difficulty 2/5 Free

Linear regression

Definition

A model that predicts a numeric outcome as a weighted sum of the input features, fitted by choosing the weights that make the squared prediction errors as small as possible.

Formula
y^=β0+β1x1+⋯+βpxp\hat{y} = \beta_0 + \beta_1 x_1 + \dots + \beta_p x_p

Intuition

You have a cloud of points and you want one straight line through it that is wrong by as little as possible. Linear regression is that line, generalised to any number of inputs.

Each input gets a weight. The prediction is the inputs multiplied by their weights and added up. Fitting the model means searching for the set of weights that makes the total squared error smallest [2, §3.1.1.2].

The word "linear" describes the weights, not the picture. The model is linear because the prediction is a weighted sum — you can still feed it a squared or logged feature and get a curve.

Formal definition

For an observation with features x1x_1 through xpx_p, the model predicts a weighted sum plus an intercept. The coefficients are chosen to minimise the residual sum of squares — the total of the squared gaps between what was observed and what the line predicts.

In matrix form, scikit-learn states the objective that LinearRegression minimises as the squared Euclidean norm of the residual vector [1, §1.1.1].

How it works

02468102468feature xtarget yresidualsquared residualSum of squared residualsfitted line4.49a steeper line6.45
Least squares picks the line whose squares add up to the smallest total. Each dashed segment is a residual — the gap between an observed point and what the line predicts — and each square has that residual as its side. Squaring is what makes one long segment cost more than several short ones: the longest here is less than half as long as the six shortest put together, yet its square outweighs all six of theirs. Tilt the line and the total grows.

The fitting procedure is direct, not iterative. Because squared error is a smooth bowl-shaped function of the coefficients, it has exactly one lowest point as long as no input is a linear combination of the others, and that point can be solved for in closed form [2, §3.1.1.3]. There is no learning rate and no random initialisation — the same data always produces the same coefficients.

That closed-form solution is what makes linear regression cheap to fit. It is by far the most widely used modelling method [3, §4.1.4.1], and the baseline that everything else usually has to beat.

Where it's used

Linear regression turns up wherever a numeric prediction has to be explained to someone, not just produced [3, Advantages]:

  • Pricing and valuation — estimating a house price from floor area, number of rooms and location, where a buyer expects to see which factor moved the number.
  • Credit and risk scoring — settings where a model's influence on a decision has to be explained coefficient by coefficient.
  • Dose–response studies — estimating how an outcome changes per unit of exposure, with a confidence interval on that estimate.
  • Forecasting baselines — the first model fitted on a new problem, to establish the error a more complex model has to improve on.
  • Feature screening — reading coefficient magnitudes and significance to decide which inputs are worth keeping.

Why & when

Choose it when interpretability matters as much as accuracy. Each coefficient has a plain-language reading: holding everything else constant, one more unit of this input moves the prediction by this much [5, §5.1.4]. Very few model families offer that.

It also assumes a lot, and those assumptions are the decision criteria:

  • the relationship between inputs and target is genuinely additive and linear [3, §4.1.4.1]
  • the errors are roughly independent, with roughly constant spread [4, §4.2.1]
  • the inputs are not near-duplicates of one another [1, §1.1.1]

Reach for something else when the relationship is visibly curved or has interactions the features don't encode (gradient boosting, splines) [3, Disadvantages], when the inputs vastly outnumber the observations (ridge or lasso) [5, §7.3], or when accuracy matters far more than being able to explain the model.

Worked example

Python 17 lines Show the code Hide the code
from sklearn.datasets import fetch_california_housing
from sklearn.linear_model import LinearRegression
from sklearn.metrics import mean_squared_error
from sklearn.model_selection import train_test_split

X, y = fetch_california_housing(return_X_y=True)
X_train, X_test, y_train, y_test = train_test_split(
    X, y, test_size=0.2, random_state=0
)

model = LinearRegression().fit(X_train, y_train)
pred = model.predict(X_test)

print(f"MSE {mean_squared_error(y_test, pred):.3f}")
names = fetch_california_housing().feature_names
for name, coef in zip(names, model.coef_):
    print(f"{name:>10} {coef:+.3g}")

Output

MSE 0.529
    MedInc +0.433
  HouseAge +0.00929
  AveRooms -0.0986
 AveBedrms +0.593
Population -7.56e-06
  AveOccup -0.00475
  Latitude -0.421
 Longitude -0.434

The first line is the MSE on held-out data — the quantity the fit was minimising, now measured on rows the model never saw [1, §1.1.1].

The coefficients are the whole point of the output. The positive weight on median income (+0.433) says that, holding the other features fixed, higher-income districts carry higher house values — a claim you can take to someone and defend.

Not every sign reads that cleanly. Average rooms gets a negative weight and average bedrooms a large positive one, each the opposite of its sign when fitted alone. The two columns correlate at 0.85, the near-duplicate inputs warned about above, and with such features the least-squares estimate "becomes highly sensitive to random errors in the observed target" [1, §1.1.1].

Variants & extensions

VariantWhat changesReach for it when
RidgeAdds a penalty on squared coefficient sizeFeatures are correlated, or you have more features than rows
LassoAdds a penalty on absolute coefficient sizeYou want the model to zero out useless features outright
Elastic netBlends the two penaltiesCorrelated groups of features you want selected together
Polynomial regressionAdds powers of the featuresThe relationship is curved but still smooth

All four stay linear in their coefficients, so each coefficient keeps its reading. Ridge keeps a closed-form solution [5, §7.1.1], and so does polynomial regression, which is least squares on expanded features [1, §1.1.16]. The lasso gives it up and is fitted iteratively, by coordinate descent [1, §1.1.3], and so is the elastic net, which in exchange keeps correlated features together rather than picking one at random [1, §1.1.5].

Pitfalls

A coefficient is not a cause. The model reports association given the features it was shown. Omit a confounder and the coefficient absorbs its effect.

A high score is not a good fit. Adding any feature — including pure noise — never decreases the training score. A model can score well and still be wrong in every way that matters.

Extrapolation is unsupported. The fit describes the range of the training data. Predicting far outside it is arithmetic, not evidence.

Not read yetReach the end of the page and it counts as read.

Keep your progressWith lifetime access, every page you finish is marked and you pick up where you stopped, on all your devices.

Unlock

Check yourself

3 questions

Each answer is explained, with the section it tests and its source.

On the cheat sheet: Linear models →

Sources

  1. scikit-learn User Guide — Linear Modelsdocs · retrieved 2026-08-29https://scikit-learn.org/stable/modules/linear_model.html
  2. Zhang, Lipton, Li, Smola. Dive into Deep Learning — 3.1 Linear Regressionbookhttps://d2l.ai/chapter_linear-regression/linear-regression.html
  3. NIST/SEMATECH. e-Handbook of Statistical Methods — 4.1.4.1 Linear Least Squares Regressionstandard · retrieved 2026-10-04https://www.itl.nist.gov/div898/handbook/pmd/section1/pmd141.htm
  4. NIST/SEMATECH. e-Handbook of Statistical Methods — 4.2.1 Typical underlying assumptions in process modelingstandard · retrieved 2026-10-04https://www.itl.nist.gov/div898/handbook/pmd/section2/pmd21.htm
  5. Goodfellow, Bengio, Courville. Deep Learning (2016)bookhttps://www.deeplearningbook.org/

Have a promo code?

A code that takes 100% off unlocks everything at once. A smaller one takes its share off the price in the payment window: enter the same code there.

Write to support

A question, a problem with access, a refund? Write to us and we answer by email.

What is it about?

Your address is used only to answer you.

Message sent

Thank you. We will reply to the address you gave, by email.

Or write to us directly

support@artofds.com

Message sent Thank you. We will reply to the address you gave, by email.

Check the email address: we need it to reply.

That is our own address. Enter yours, so the reply reaches you.

This address cannot receive email. Check it for a typo.

Write a little more: at least 10 characters.

Too many messages in a short time. Try again in a few minutes.

The message could not be sent. Please write to us directly: support@artofds.com