← Blog/How Linear Regression Works: The Math and Intuition, Explained for Marketers
Machine LearningLinear RegressionPythonStatisticsMarketing Analytics
Machine Learning · 35 min read

How Linear Regression Works: The Math and Intuition, Explained for Marketers

Linear regression explained for marketers: least squares, the formulas, confounding, intervals and overfitting, with interactive charts and Python.

· Martin Guzman

Linear regression predicts a number, such as next week's revenue, as a starting value plus a weight for each input, and it chooses the weights that make the squared errors on past data as small as possible. This guide explains it from the ground up: the idea, every formula, how to judge a model, how sure to be about it, and the ways it misleads people who use it to measure marketing.

The business cases that apply it will be separate guides, so this one can focus on the model. Every example here uses one table: three years of weekly ad spend and revenue at Northpine Software, an invented company. Because the data is made up, we know the true effect of every channel, so you can see when the method gets it right and when it does not. Every number and chart is real output from a notebook you can download.

How linear regression works

The whole method fits in one sentence: predict the outcome as a starting value plus a weight times each input, and choose the weights so that the squared differences between predictions and reality, added up over the past, are as small as they can be.

How linear regression learns from past weeks
Step 1
Line up the weeks
Each week: the inputs (spend, promotions, demand) and the outcome (revenue)
Step 2
Propose weights
Prediction = a starting value + a weight × each input
Step 3
Measure the misses
Square each week’s error and add them up
Step 4
Keep the best weights
The ones with the smallest total; each reads as dollars of revenue per unit of input
Fitting is one calculation, not a search: the weights with the smallest squared error have a formula.

Three consequences follow, and you will meet each of them later in this guide:

  • Every weight can be read in business units. A weight of 1.67 on search spend means "one more dollar of search goes with 1.67 more dollars of revenue, if the other inputs stay the same". Few methods are this easy to read.
  • "If the other inputs stay the same" only covers the inputs you include. Leave out something that drives both spend and sales, such as seasonal demand, and the weights quietly absorb its effect. On Northpine's data that mistake turns a true return of 2.2 into an estimate of 7.33. It is one of the most common and costly mistakes in marketing analytics, and a large part of this guide is about it.
  • It draws straight lines. The model assumes each input adds the same amount per unit, whether it is the first dollar or the ten-thousandth. Curves and diminishing returns are possible, but only if you build them in.

The running example: Northpine's weekly data

Northpine Software sells a business software subscription. Its marketing team spends on three paid channels each week and runs occasional promotions. The table northpine_weekly.csv has 156 weeks, from January 2023 to December 2025. Here are the first five:

weeksearch interestpaid searchpaid socialdisplaypromotionrevenue
2023-01-0281.23,9103,7904,190019,600
2023-01-0984.94,4009,7002,990022,490
2023-01-1692.88,6903,8202,830035,440
2023-01-2389.210,9805,4102,570037,450
2023-01-3096.77,6706,6901,530036,110
ColumnWhat it isRange
search_interest_indexHow much people searched for this kind of software that week, an index of market demand81.2 to 134.3
paid_search_spendDollars spent on search ads3,910 to 15,280
paid_social_spendDollars spent on social media ads500 to 12,200
display_spendDollars spent on display ads400 to 8,580
promotion_week1 if a promotion ran that week, 0 if not24 of 156 weeks
revenueNew revenue booked that week, in dollars6,710 to 120,220, average 66,283

Two facts about this data drive most of what follows:

  • Demand moves everything. Search interest rises and falls with the seasons and grows slowly over the three years. When it is high, more people buy, and the marketing team also spends more on search, because there are more searches to bid on. The correlation between demand and search spend is 0.80.
  • We know the right answers. The data was generated with known rules: every dollar of search adds 2.2 dollars of revenue, social 1.4, display 0.6, and a promotion adds 9,000 dollars a week. A real company never gets to check its model against the truth. Here we can.

The math behind linear regression

There are six pieces: the equation, the errors, how the best weights are found, how to read them, how to judge the fit, and how sure to be. After those come the ways it goes wrong: confounding, broken assumptions, correlated inputs, overfitting and extrapolation.

One input: a line

Start with a single input, search spend, written xx, and the outcome, revenue, written yy. The model is a straight line:

y^=β0+β1x\hat{y} = \beta_0 + \beta_1 x

y^\hat{y} (read "y-hat") is the prediction. β0\beta_0 is the intercept, the prediction when xx is zero. β1\beta_1 is the slope, how much the prediction changes when xx goes up by one. The Greek letters are the weights the model has to learn.

For each past week ii, the gap between what happened and what the line predicts is the residual, or error:

ei=yi−y^ie_i = y_i - \hat{y}_i

A worked example. The least-squares line for Northpine, found in the next sections, has β0=−11,164\beta_0 = -11{,}164 and β1=8.121\beta_1 = 8.121. In the first week of 2023, search spend was 3,910, so the line predicts −11,164+8.121×3,910≈20,590-11{,}164 + 8.121 \times 3{,}910 \approx 20{,}590. Revenue was 19,600, so the residual is 19,600−20,590=−99019{,}600 - 20{,}590 = -990: the line was 990 dollars too high.

Least squares: the definition of "best"

A line is only as good as its errors, so we need one number that sums them up. Adding the errors does not work, because positive and negative ones cancel. Linear regression adds their squares instead, giving the sum of squared errors:

SSE(β0,β1)=∑i=1n(yi−β0−β1xi)2\text{SSE}(\beta_0, \beta_1) = \sum_{i=1}^{n} \left( y_i - \beta_0 - \beta_1 x_i \right)^2

where nn is the number of weeks, 156 here. The least-squares line is the pair (β0,β1)(\beta_0, \beta_1) that makes this sum as small as possible. Why squares?

  • Big misses count more. A week off by 20,000 adds 400 million; two weeks off by 10,000 add 200 million between them. For revenue forecasts, where one very wrong week hurts more than two slightly wrong ones, that is usually the right priority.
  • There is always exactly one best answer, and a formula for it. The squared error is a smooth bowl with a single lowest point, and calculus finds it directly.
  • The answer has a natural meaning. With no inputs at all, the number that minimizes squared error is the average. Least squares extends "predict the average" to "predict the average for weeks like this one".

The cost of squaring is sensitivity to odd weeks: one week with a huge error pulls the whole line towards it. You can try that in the playground further down.

Solving it: the slope is covariance over variance

Setting the derivatives of SSE to zero gives the least-squares line in closed form:

β^1=∑i(xi−xˉ)(yi−yˉ)∑i(xi−xˉ)2=cov⁡(x,y)var⁡(x),β^0=yˉ−β^1xˉ\hat{\beta}_1 = \frac{\sum_{i}(x_i - \bar{x})(y_i - \bar{y})}{\sum_{i}(x_i - \bar{x})^2} = \frac{\operatorname{cov}(x, y)}{\operatorname{var}(x)}, \qquad \hat{\beta}_0 = \bar{y} - \hat{\beta}_1 \bar{x}

xˉ\bar{x} and yˉ\bar{y} are the averages. The top of the fraction, the covariance, measures how much spend and revenue move together: it is large when weeks with above-average spend also have above-average revenue. The bottom, the variance, measures how much spend moves at all. The slope is how much revenue moves together with spend, per unit of spend movement. The hat on β^\hat{\beta} marks it as an estimate from data, not the true value.

On Northpine's weeks:

β^1=53,405,5146,576,135=8.121,β^0=66,283−8.121×9,536≈−11,164\hat{\beta}_1 = \frac{53{,}405{,}514}{6{,}576{,}135} = 8.121, \qquad \hat{\beta}_0 = 66{,}283 - 8.121 \times 9{,}536 \approx -11{,}164

The second formula says the line always passes through the point of averages: a week with average spend, 9,536, gets the average revenue, 66,283.

Taken at face value, this says every dollar of search brings back 8.12 dollars. Remember that the true effect is 2.2. The section on confounding explains the gap. And the intercept, minus 11,164 dollars of revenue in a week with no search spend, is impossible. It is what the line says at a spend of zero, far outside the 3,910 to 15,280 range the data covers. An intercept often has no business meaning, and it does not need one; its job is to put the line at the right height.

Many inputs: the matrix form

With pp inputs the line becomes a flat surface in more dimensions, but the equation is the same idea:

y^=β0+β1x1+β2x2+⋯+βpxp\hat{y} = \beta_0 + \beta_1 x_1 + \beta_2 x_2 + \cdots + \beta_p x_p

Writing all 156 weeks at once is easier with matrices. Stack the outcomes into a column y\mathbf{y}, and the inputs into a table X\mathbf{X} with one row per week and a first column of ones for the intercept. Then

y=Xβ+ε\mathbf{y} = \mathbf{X}\boldsymbol{\beta} + \boldsymbol{\varepsilon}

where β\boldsymbol{\beta} is the column of weights and ε\boldsymbol{\varepsilon} the column of errors. Minimising the squared error gives the normal equations, and solving them gives every weight at once:

X⊤X β^=X⊤y⟹β^=(X⊤X)−1X⊤y\mathbf{X}^\top \mathbf{X} \, \hat{\boldsymbol{\beta}} = \mathbf{X}^\top \mathbf{y} \quad \Longrightarrow \quad \hat{\boldsymbol{\beta}} = (\mathbf{X}^\top \mathbf{X})^{-1} \mathbf{X}^\top \mathbf{y}

X⊤\mathbf{X}^\top is X\mathbf{X} turned on its side, and the −1-1 means the matrix inverse, the matrix version of dividing. X⊤X\mathbf{X}^\top\mathbf{X} holds the sums of squares and cross-products of the inputs; X⊤y\mathbf{X}^\top\mathbf{y} holds how each input moves with the outcome. It is the covariance-over-variance formula, generalized. With search spend as the only input, the notebook builds both matrices and solves them, and gets back exactly the line above: an intercept of minus 11,164 and a slope of 8.121.

The inverse exists only if no input is an exact combination of the others. Put both "spend in dollars" and "spend in thousands" into a model and there is no single answer, because any split between the two predicts equally well. Near-exact combinations cause a milder version of the same problem, covered under correlated inputs.

Gradient descent: another way down

Most machine learning models have no closed-form answer, so they are fitted by gradient descent: start with any weights, work out which direction makes the error fall fastest, take a small step that way, and repeat. Linear regression does not need it, but it is the clearest place to see how it works. For the mean squared error, MSE=SSE/n\text{MSE} = \text{SSE}/n, the directions are the derivatives:

∂ MSE∂β0=2n∑i(y^i−yi),∂ MSE∂β1=2n∑i(y^i−yi) xi\frac{\partial\, \text{MSE}}{\partial \beta_0} = \frac{2}{n}\sum_i (\hat{y}_i - y_i), \qquad \frac{\partial\, \text{MSE}}{\partial \beta_1} = \frac{2}{n}\sum_i (\hat{y}_i - y_i)\, x_i

and each step moves the weights a small distance η\eta, the learning rate, against them:

βj←βj−η ∂ MSE∂βj\beta_j \leftarrow \beta_j - \eta \, \frac{\partial\, \text{MSE}}{\partial \beta_j}

The chart shows the error for every possible intercept and slope as a contour map: each ring is a level of error, and the white cross is the bottom. The amber path starts at zero and takes steps of size 0.005, with spend and revenue in thousands of dollars.

Gradient descent: walking down the error surface
Try it
-20020406080024681012intercept: revenue at $0 spend ($k)slope ($ per $1)
10
slope after these steps
6.969
target 8.121
mean squared error vs the minimum
1.043×
1.000× = at the bottom
Raw: the valley is a long, thin trench. The first steps drop into it fast, then crawl along its floor towards the white cross.
Mean squared error of the one-input model, in thousands of dollars, for every intercept and slope. Steps of size 0.005 from zero, as in the notebook.

With raw spend, the valley is a long, narrow trench. The first steps find a slope near 7 quickly (6.969 after 10 steps), because that is the steep direction. Then progress along the bottom of the trench is painfully slow: 7.036 after 100 steps, 7.524 after 1,000, and 8.120 only after 10,000. The trench is narrow because the intercept and slope are tangled: spend never gets near zero, so raising the intercept and lowering the slope give almost the same line.

Centre the spend, by subtracting its average from every week, and the trench becomes a much rounder bowl. Now the slope reaches 8.112 in 100 steps and 8.121 in 1,000. The lesson carries over to every method fitted by gradient descent, such as logistic regression and neural networks: put inputs on comparable scales, centred near zero, and fitting gets faster and more reliable. (Tree-based methods, such as the boosted trees in part 5, are the exception: rescaling an input does not change where a tree splits.)

Reading a coefficient

Now fit the model with all five inputs: the three channels, the promotion flag, and demand. The notebook does this with the statsmodels library, which also reports how certain each estimate is:

InputCoefficientStandard error95% intervalTrue value
Paid search (per dollar)1.6650.3171.039 to 2.2922.2
Paid social (per dollar)1.3750.2100.961 to 1.7891.4
Display (per dollar)1.0580.3820.303 to 1.8130.6
Promotion week8,4741,3475,812 to 11,1369,000
Demand (per index point)1,479611,358 to 1,600
Intercept−125,5034,633

The standard error and the interval are explained in the section after next. Read each coefficient as the change in predicted revenue when that input rises by one unit and every other input in the model stays the same:

  • Search: 1.665. Compare two weeks with the same demand, social, display and promotion. If one had a dollar more of search spend, the model expects it to have 1.67 dollars more revenue.
  • Promotion: 8,474. The promotion column is a yes-or-no flag, coded 1 or 0, a so-called dummy variable. Its coefficient is the difference between a promotion week and an otherwise identical week without one.
  • Demand: 1,479. Each extra point of search interest goes with 1,479 dollars of revenue a week, holding ad spend and promotions fixed. The true value in the simulation is 1,450.
  • Intercept: minus 125,503. The prediction for a week with zero demand and no marketing at all. The lowest demand in the data is 81.2, so this is far outside anything observed, and it has no meaning. Its job is to set the height of the surface.

Every true value sits inside its 95 percent interval. Search and display are the furthest off, 1.67 against 2.2 and 1.06 against 0.6. Misses of that size are what chance produces; what the link to demand does is make these two estimates less precise, with wider intervals, because both channels' budgets move with demand and the model has less independent movement to learn from. Paid social, whose spend moves independently of everything else, is estimated most precisely, and here also lands closest, at 1.375 against 1.4.

That last point carries a surprise. Paid social's correlation with revenue is 0.04, almost none, yet it has a real effect, which the model recovers. A channel's effect can be hidden in raw correlations by everything else going on, and a channel can look strong in raw correlations without causing anything. The model untangles them only when the right inputs are in it.

Judging the fit: R², RMSE and MAE

How much of the week-to-week variation does a model explain? Start with the total variation, the sum of squares around the average:

SST=∑i(yi−yˉ)2\text{SST} = \sum_i (y_i - \bar{y})^2

A model that always predicts the average leaves all of it unexplained. A model leaves its SSE unexplained. R², the coefficient of determination, is the share it explains:

R2=1−SSESSTR^2 = 1 - \frac{\text{SSE}}{\text{SST}}

For the one-input model, R2=1−3.356×1010/1.008×1011=0.667R^2 = 1 - 3.356 \times 10^{10} / 1.008 \times 10^{11} = 0.667: search spend alone accounts for two thirds of the variation in weekly revenue. Switch between models in the chart to see the errors shrink.

R²: how much of the week-to-week variation a model explains
Try it
$0k$40k$80k$120k202320242025
total variation (sum of squares)
100.8 bn
around the average week
left unexplained
33.6 bn
sum of squared errors
R²
0.667
1 − unexplained ÷ total
Grey dots: actual revenue. Green: the model. Red: each week’s error. Hover for a week.
All 156 weeks, each model fitted on all of them. R² values from the notebook.
ModelR²Residual standard error
Search spend only0.66714,761
All spend and promotions0.74013,171
All spend, promotions and demand0.9475,979

A high R² is not the same as a correct model. The search-only model has a respectable 0.667 and a badly wrong coefficient. R² measures how well a model predicts, not whether its coefficients mean what you want them to mean. Adding any input, even pure noise, can never lower R² on the data the model was fitted on. Adjusted R² charges a small price per input to correct for that; for the full model it is 0.945, against 0.947.

R² has no units, so you also need an error in dollars. The root mean squared error, RMSE, is the typical size of a miss, with big misses weighted more; the mean absolute error, MAE, is the plain average miss:

RMSE=1n∑iei2,MAE=1n∑i∣ei∣\text{RMSE} = \sqrt{\frac{1}{n}\sum_i e_i^2}, \qquad \text{MAE} = \frac{1}{n}\sum_i |e_i|

For the one-input model, RMSE is 14,667 dollars and MAE is 11,473. RMSE is always at least as large as MAE; the gap grows when a few weeks have very large errors.

The table above reports a close cousin, the residual standard error, which divides by n−p−1n - p - 1 instead of nn:

σ^=SSEn−p−1\hat{\sigma} = \sqrt{\frac{\text{SSE}}{n - p - 1}}

The model used p+1p + 1 weights to fit the data, and each one lets it bend towards the noise a little, so the raw average understates the errors. Dividing by the remaining degrees of freedom corrects for that: 14,761 instead of 14,667 for the one-input model. For the full model, σ^\hat{\sigma} is 5,979, close to the 6,000 dollars of pure random noise the data was generated with. The full model explains essentially everything that can be explained.

Standard errors and confidence intervals

The coefficients come from 156 weeks. A different three years would have given slightly different numbers. The standard error measures how much they would vary. For linear regression it has a formula:

Var⁡(β^)=σ^2 (X⊤X)−1,SE(β^j)=[σ^2(X⊤X)−1]jj\operatorname{Var}(\hat{\boldsymbol{\beta}}) = \hat{\sigma}^2 \, (\mathbf{X}^\top\mathbf{X})^{-1}, \qquad \text{SE}(\hat{\beta}_j) = \sqrt{\left[\hat{\sigma}^2 (\mathbf{X}^\top\mathbf{X})^{-1}\right]_{jj}}

Three things make an estimate more precise: less noise (σ^\hat{\sigma} smaller), more weeks (the sums in X⊤X\mathbf{X}^\top\mathbf{X} grow), and more independent movement in that input (its diagonal entry in the inverse shrinks). The 95 percent confidence interval is the estimate plus or minus about two standard errors:

β^j±t0.975, n−p−1×SE(β^j)\hat{\beta}_j \pm t_{0.975,\, n-p-1} \times \text{SE}(\hat{\beta}_j)

where tt is a value from the t distribution, 1.976 for 150 degrees of freedom. For search:

1.665±1.976×0.317=1.039 to 2.2921.665 \pm 1.976 \times 0.317 = 1.039 \text{ to } 2.292

The t-statistic, t=β^j/SE(β^j)t = \hat{\beta}_j / \text{SE}(\hat{\beta}_j), asks how many standard errors the estimate is from zero. For search it is 5.25, far beyond the 1.976 that would make it "statistically significant at 5 percent". That tells you the effect is unlikely to be zero; it does not tell you it is the right size. The confounded model in the next section is just as sure that search is not zero, and its estimate is more than three times the true value.

The formula rests on assumptions, checked later. A check that rests on fewer is the bootstrap: draw 156 weeks at random from the 156, with replacement, so some weeks appear twice and some not at all; refit; record the coefficient; repeat many times. The spread of the results is the standard error. With 1,000 resamples the notebook gets 0.321, against 0.317 from the formula, and a middle 95 percent of 1.01 to 2.29. Agreement is reassuring about the formula's arithmetic, but it is not a test of the assumptions: this bootstrap also treats weeks as independent, so it cannot detect errors that carry over from one week to the next. That is what the Durbin–Watson check below is for.

The chart repeats the bootstrap with fewer weeks in each resample. With 26 weeks the estimates spread from below zero to above 4: half a year's worth of weeks cannot tell you much. (Resamples that happen to contain no promotion week are skipped, because the promotion coefficient cannot be estimated without one.) The standard deviation falls from 0.887 at 26 weeks to 0.628 at 52, 0.405 at 104 and 0.321 at 156. Four times the data halves the uncertainty: precision grows with the square root of the number of weeks.

How sure is the estimate? Resampling the weeks
Try it
0%10%20%30%−$2$0$2$4$6true 2.2estimated revenue per $1 of searchshare of resamples
standard deviation of the estimates
0.321
the standard error
middle 95% of the estimates
1.01 to 2.29
shaded
Four times the data halves the spread: 26 → 104 weeks takes it from 0.89 to 0.41.
Bootstrap: weeks drawn at random with replacement, the model refitted each time, and the search coefficient recorded. 600 resamples for 26, 52 and 104 weeks; the 1,000 from the notebook for 156.

Confounding: why the simple slope was wrong

Back to the question that matters for budgets: what does a dollar of search return? The one-input model says 8.12. The full model says 1.67. The truth is 2.2. Here is why the first is so far off.

Demand drives revenue, and demand also drives search spend, because the team bids on more searches in busy weeks. So weeks with high search spend are mostly weeks with high demand, and they would have had high revenue anyway. The one-input model has no way to tell "more revenue because of more search" from "more revenue because it was a busy week". It credits search with both. A variable that drives both the input and the outcome is called a confounder.

You can see it in the data. Colour the weeks by demand and the warm, high-demand weeks sit at the top right, with high spend and high revenue. Then switch to the second view, which takes demand and the other inputs out of both axes: what is left is how revenue moves with the part of search spend that demand does not explain. The slope drops to 1.665, close to the dashed line at the true 2.2.

Confounding: why the simple slope is wrong
Try it
$0k$20k$40k$60k$80k$100k$120k$0k$2k$4k$6k$8k$10k$12k$14k$16kpaid search spendrevenue
slope you see
$8.12
revenue per $1 of search
true effect built into the data
$2.20
dashed line
low demandhigh demand
Each dot is a week. Hover one. The warm colours sit top right: busy weeks get more budget and more sales.
All 156 weeks, coloured by the search interest index. The second view plots what is left of revenue and search spend after the other four inputs are taken out.

The second view is a theorem, not a trick. The Frisch–Waugh–Lovell theorem says that the coefficient on search in the full model is exactly the slope you get by regressing search spend on all the other inputs, keeping the leftovers x~\tilde{x}, doing the same for revenue to get y~\tilde{y}, and fitting a line between the two sets of leftovers:

β^search=∑ix~iy~i∑ix~i2\hat{\beta}_{\text{search}} = \frac{\sum_i \tilde{x}_i \tilde{y}_i}{\sum_i \tilde{x}_i^2}

The notebook checks it: the slope of leftover revenue on leftover search spend is 1.665, identical to the full model. That is what "holding the other inputs fixed" means in practice: the model uses only the part of each input that moves independently of the others.

How big will the error be if you leave a confounder out? The omitted-variable bias formula gives it exactly. If the full ("long") model has a coefficient γ\gamma on the omitted variable, and δ\delta is how much that variable moves with the input when you regress it on the inputs you kept, then the coefficient in the model without it (the "short" model) is:

β~short=β^long+γ δ\tilde{\beta}_{\text{short}} = \hat{\beta}_{\text{long}} + \gamma \, \delta

For Northpine, compare the model with all spend and promotions (short) against the same model plus demand (long). Each extra point of demand goes with 1,479.28 dollars of revenue (γ\gamma), and each extra dollar of search spend goes with 0.00383 more points of demand (δ\delta):

7.333≈1.665+1,479.28×0.003837.333 \approx 1.665 + 1{,}479.28 \times 0.00383

Of the 7.33 dollars the short model credits to search, 5.67 belong to demand. The formula also tells you the direction of the bias before you fit anything: a confounder that raises the outcome (γ\gamma positive) and rises with the input (δ\delta positive) makes the input look better than it is. That is the usual situation in marketing, where budgets follow demand.

The chart compares all three models against the true values. Adding the other channels and promotions barely helps search, 8.12 to 7.33. Display is distorted too, 3.84 without demand against a true 0.6, because display spend also follows demand. Only the model with demand lands near the truth for every channel.

The same data, three models, three answers
Try it
012345678910revenue per $1 of spendPaid searchPaid socialDisplay
search onlyall spendall spend + demand
◇ true value
Promotion week, same three models: $10,996, $8,474 (true $9,000). Hover a bar.
Coefficients with 95% confidence intervals, fitted on all 156 weeks. The true values are the ones used to generate the data.

More data does not fix it. The next chart refits both models on the first 26, 39, 52 and more weeks. The interval narrows in both, but the model without demand narrows around the wrong answer, about 7, and becomes more confidently wrong with every week. Precision and correctness are different things.

More data narrows the interval, but does not remove the bias
Try it
$0$2$4$6$8$10265278104130156weeks of data used (from January 2023)revenue per $1 of search
156
without demand
$7.33
95%: 6.41 to 8.26
with demand
$1.67
95%: 1.04 to 2.29
without demandwith demandtrue $2.20
The search coefficient and its 95% interval, fitted on the first n weeks, with and without demand.

The fix worked here because the confounder was known and measured. In real data some confounders are neither: a competitor's outage, a mention in the press, a sales team's push. A regression can only hold fixed what is in it. That is why, for decisions about where to spend, a regression on observational data should be checked against an experiment, such as a holdout test that switches spend off in some regions or weeks (Incrementality Meaning, With a Marketing Example explains how).

Checking the assumptions

The coefficients are least-squares estimates whatever the data looks like. The standard errors, intervals and t-statistics need more. The usual assumptions are below. The first five concern the intervals; the sixth concerns what a coefficient means.

  1. Linearity. The outcome really is a weighted sum of the inputs, so no curve or interaction is missing.
  2. Independent errors. One week's error says nothing about the next week's.
  3. Constant variance. Errors are about the same size in big weeks and small weeks.
  4. Normal errors. The errors roughly follow a bell curve. This matters mostly for small samples and for prediction intervals.
  5. No exact collinearity. No input is an exact combination of the others, so (X⊤X)−1(\mathbf{X}^\top\mathbf{X})^{-1} exists.
  6. No omitted confounders. Nothing left out of the model drives both an input and the outcome. This one is not needed for good predictions, but it is needed to read a coefficient as the effect of that input. No residual plot can check it; only knowledge of the business, or an experiment, can.

You check most of them by plotting the residuals. In a good model they look like noise: no pattern over time, no pattern against the prediction. Weekly marketing data has a specific trap, assumption 2. Its usual measure is the Durbin–Watson statistic:

DW=∑t=2n(et−et−1)2∑t=1net2\text{DW} = \frac{\sum_{t=2}^{n} (e_t - e_{t-1})^2}{\sum_{t=1}^{n} e_t^2}

It is about 2 when consecutive errors are unrelated, below 2 when errors come in runs, and above 2 when they alternate.

Reading the residuals
Try it
−$40k−$20k$0k$20k$40k202320242025error (actual − predicted)
correlation of each error with the week before
0.28
0 = no pattern
Durbin-Watson
1.44
2 = no pattern; under 2 = runs
Red dots miss by more than two typical errors. Hover a week.
Errors of each model on the 156 weeks it was fitted on.

Without demand, the residuals drift in long seasonal waves: the model is too low for months at a time, then too high. The correlation between each week's error and the previous week's is 0.28 and Durbin–Watson is 1.44. With demand, the waves disappear: the correlation is minus 0.17 and Durbin–Watson is 2.32.

So the pattern in the residuals was not really a problem with the errors. It was the missing confounder, showing up as a seasonal rhythm the model could not explain. That is the most useful thing a residual plot does: structure in the errors is a sign of something missing from the model. If you see seasonal waves, a trend or a jump, ask what drives revenue at those times and whether it should be an input.

Correlated inputs

When two inputs move together, the data has little information about how to split the credit between them. The variance inflation factor, VIF, measures how much that costs. Regress input jj on all the other inputs, call the R² of that regression Rj2R_j^2, and:

VIFj=11−Rj2\text{VIF}_j = \frac{1}{1 - R_j^2}

A VIF of 1 means the input moves independently and its standard error is as small as the data allows. A VIF of 4 means the standard error is twice what it would be with an independent input (the square root of 4). For Northpine, search has a VIF of 2.87 and demand 3.10, because they move together; social has 1.02 and the promotion flag 1.03. Values under 5 are usually fine, and these are.

The bootstrap shows what a VIF means in practice. Across 1,000 resamples, the search and demand estimates have a correlation of minus 0.78: when a resample happens to credit search more, it credits demand less. The data is more certain about their combined effect than about the split. Slide the cut-off to see the trade.

Correlated inputs: two estimates that move together
Try it
$1,300$1,400$1,500$1,600$1,700$0.5$1$1.5$2$2.5$3search effect ($ per $1)demand effect ($ per point)
$2.2
demand effect, 49 highlighted
$1,373
demand effect, other 951
$1,482
Correlation between the two estimates across resamples: -0.78. The data can tell how much search and demand explain together better than how to split it between them.
1,000 bootstrap resamples of all 156 weeks. Each dot is one refit of the full model.

Overfitting and the honest test

A model's errors on the weeks it was fitted on are an optimistic guide to its errors on new weeks, because the fitting has tuned it to those exact weeks, noise included. The honest test is to hold some data back. With weekly data, hold back the most recent weeks, not a random sample: the question is how well a model built on the past predicts the future, and a random split would let it peek at weeks surrounding each test week.

Here the model is fitted on the first 130 weeks and tested on the last 26, from June 30 to December 2025. With demand in the model, the test RMSE is 5,776 dollars, the test MAE 4,940 and the test R² 0.946, almost exactly as good as on the training weeks (an RMSE of 5,895). 25 of the 26 test weeks fall inside the model's 95 percent prediction interval, about what a 95 percent interval should do. Without demand, the test RMSE is 16,649 and the test R² falls to 0.551: the seasonal pattern it cannot explain hurts more in a new half-year.

The honest test: weeks the model has never seen
Try it
test weeks$0k$40k$80k$120k202320242025
test RMSE
$5,776
typical miss, unseen weeks
test R²
0.946
inside the 95% interval
25 of 26
test weeks
actual revenueprediction, with 95% prediction interval
Hover a week. The shaded area on the right is the 26 weeks the model never saw.
Fitted on the first 130 weeks; the last 26 (June 30 to December 2025) are held out.

Overfitting is what happens when a model has enough freedom to fit the noise. Every input adds freedom. To show it plainly, the next chart adds columns of pure random numbers to the five real inputs. On the training weeks, R² climbs with every noise column, from 0.947 to 0.989 with 100 of them, because the extra columns let the model chase each week's random wiggle. On the test weeks, R² falls from 0.946 to 0.642. The model has learned noise that does not repeat.

Overfitting, measured
Try it
0.60.70.80.91.0020406080100columns of random noise added to the five real inputsR²
100
training R²
0.989
test R²
0.642
ridge test R²
0.769
penalty 8.532
least squares, training weeksleast squares, test weeksridge, test weeks
Columns of random numbers added to the five real inputs. Fitted on the first 130 weeks, tested on the last 26. Ridge’s penalty chosen by time-series cross-validation.

With 105 inputs and 130 training weeks, there are barely more weeks than weights. A common rule of thumb is to have at least 10 to 20 observations per input, which for weekly data is a real limit: three years of weeks supports perhaps 8 to 15 inputs, not 50.

Regularization: ridge and lasso

Regularization fights overfitting by adding a penalty for large coefficients to the quantity being minimized. Ridge regression penalizes the sum of squared coefficients:

min⁡β  ∑i(yi−y^i)2+λ∑j=1pβj2\min_{\boldsymbol{\beta}} \; \sum_i (y_i - \hat{y}_i)^2 + \lambda \sum_{j=1}^{p} \beta_j^2

Lasso penalizes the sum of their absolute values:

min⁡β  12n∑i(yi−y^i)2+λ∑j=1p∣βj∣\min_{\boldsymbol{\beta}} \; \frac{1}{2n}\sum_i (y_i - \hat{y}_i)^2 + \lambda \sum_{j=1}^{p} |\beta_j|

λ\lambda (lambda, called alpha in scikit-learn) sets how strong the penalty is. At zero both are ordinary least squares. As it grows, coefficients are pulled towards zero. The intercept is not penalized, and the inputs are standardized first, rescaled to an average of 0 and a standard deviation of 1, so the penalty treats them equally whatever their units. Ridge also has a closed form, the least-squares formula with λ\lambda added to the diagonal:

β^ridge=(X⊤X+λI)−1X⊤y\hat{\boldsymbol{\beta}}_{\text{ridge}} = (\mathbf{X}^\top\mathbf{X} + \lambda \mathbf{I})^{-1} \mathbf{X}^\top \mathbf{y}

Adding λ\lambda to the diagonal is what keeps the inverse well behaved when inputs are correlated, and it is why ridge copes with many inputs. The difference between the two penalties is in their shapes. Ridge shrinks every coefficient smoothly and never quite to zero. Lasso pushes the weakest coefficients to exactly zero, so it also selects inputs: at a penalty of 3,000, it keeps only search and demand. The two scales of λ\lambda are not comparable, because the two formulas are written differently.

Ridge and lasso: shrinking the coefficients
Try it
$0k$5k$10k$15k$20k0.010.11101001,00010,000penalty strength (log scale)effect of 1 SD of the input
1
cross-validated RMSE
$6,437
lowest $6,416 (amber line)
inputs still in the model
5 of 5
Paid searchPaid socialDisplayPromotion weekDemand (search interest)
Inputs standardised, fitted on the first 130 weeks. Cross-validated RMSE from five time-ordered folds.

The penalty strength is chosen by cross-validation, which tests each value on data the model did not train on. With time-ordered data, use time-ordered folds: scikit-learn's TimeSeriesSplit trains on the earliest weeks and tests on the weeks right after, five times, moving forward. On Northpine's five real inputs, the best penalty is the smallest one tried, with a cross-validated RMSE of 6,416: with five good inputs and 130 weeks, there is no overfitting to prevent, and regularization only adds bias.

Where it does help is the noise experiment. With 100 noise columns, ridge with a tuned penalty holds a test R² of 0.769 against 0.642 for least squares, and with 80 it holds 0.806 against 0.785. With 40 or 60 noise columns it does slightly worse than least squares, so it is not free.

One more thing the paths show, and it matters for marketing. As the ridge penalty grows, search's coefficient rises: from 4,618 per standard deviation at a penalty of 0.01 to 6,385 at 10, while demand's falls from 19,982 to 16,803. Ridge spreads credit across correlated inputs, so it moves credit from demand back to search, towards the confounded answer. Regularization is a tool for prediction. It is not a tool for measuring what each channel causes.

Predictions, intervals and the edge of the data

A prediction for new inputs x0\mathbf{x}_0 is just the equation, y^0=x0⊤β^\hat{y}_0 = \mathbf{x}_0^\top \hat{\boldsymbol{\beta}}. How sure it is depends on the question. For the average revenue of all weeks with those inputs, the confidence interval is:

y^0±t⋅σ^x0⊤(X⊤X)−1x0\hat{y}_0 \pm t \cdot \hat{\sigma} \sqrt{\mathbf{x}_0^\top (\mathbf{X}^\top\mathbf{X})^{-1} \mathbf{x}_0}

For one actual week, which also has its own random noise, the prediction interval adds a 1 under the square root and is always wider:

y^0±t⋅σ^1+x0⊤(X⊤X)−1x0\hat{y}_0 \pm t \cdot \hat{\sigma} \sqrt{1 + \mathbf{x}_0^\top (\mathbf{X}^\top\mathbf{X})^{-1} \mathbf{x}_0}

The term x0⊤(X⊤X)−1x0\mathbf{x}_0^\top (\mathbf{X}^\top\mathbf{X})^{-1} \mathbf{x}_0 grows as x0\mathbf{x}_0 moves away from the centre of the data, so both intervals widen at the edges. For a week with average demand, average social and display spend, no promotion, and 9,500 dollars of search, the model predicts 64,919 dollars of revenue: the average for such weeks is between 63,887 and 65,950, and a single such week will fall between 53,059 and 76,778.

Predictions, intervals and the edge of the data
Try it
the data covers this range$40k$80k$120k$0k$10k$20k$30k$40kpaid search spend in a weekpredicted revenue
$15,000
average week at this spend
$74,078
95%: $70,535 to $77,620
one actual week, 95% prediction interval
$61,743 to $86,412
confidence interval for the averageprediction interval for one week
Inside the range of the data: the line is backed by real weeks.
The full model, with the other inputs at their averages and no promotion. Intervals from the notebook.

Now push search spend to 30,000, twice the most Northpine has ever spent in a week (15,280). The model answers without hesitation: 99,057 dollars, with a confidence interval of 86,226 to 111,888. The widening interval is honest about the statistical uncertainty. It says nothing about the bigger risk: that the straight line stops being straight. Real channels show diminishing returns, as the cheapest, most relevant searches are bought first. The data stops at 15,280, so it contains no evidence either way about what happens at 30,000. A linear model cannot warn you about that; only the range of your data can.

If you expect diminishing returns, build them into the inputs. Using the logarithm of spend, βlog⁡(x)\beta \log(x), makes each doubling of spend add the same amount, not each dollar. Marketing mix models use more flexible saturation curves and carry-over effects from one week to the next (What Is Marketing Mix Modeling? explains them). The fitting is still least squares or a close relative; the change is in what the inputs are.

Beyond straight lines: transformations and interactions

"Linear" means linear in the weights, not in the inputs. You can feed the model any transformation of the inputs you choose, and it is still a linear regression:

y^=β0+β1log⁡(x1)+β2x2+β3 x1x2\hat{y} = \beta_0 + \beta_1 \log(x_1) + \beta_2 x_2 + \beta_3 \, x_1 x_2
  • Logarithms model diminishing returns, as above. A log of the outcome makes coefficients read as percentage changes.
  • Squares (x2x^2) model a curve with a peak or a trough.
  • Interactions (x1x2x_1 x_2) let one input change the effect of another, such as a promotion working better in high-demand weeks. The effect of x2x_2 then depends on x1x_1: it is β2+β3x1\beta_2 + \beta_3 x_1.
  • Dummies for categories, such as one column per quarter or region, each coded 0 or 1, with one category left out as the baseline.

Each addition is another input, with the same costs: more freedom to overfit, and more correlated inputs. Add them when you have a reason, and check each against held-out weeks.

Try it

Now fit a line yourself. The chart shows all 156 weeks, revenue against search spend. Move the slope and intercept and watch the errors. The green dashed line is the least-squares fit.

Fit a line by hand: revenue against search spend
Try it
$0k$20k$40k$60k$80k$100k$120k$0k$2k$4k$6k$8k$10k$12k$14k$16kpaid search spend that weekrevenue that week
$3.0
$30,000
your squared errors, vs the best
2.07×
1.00× is the least-squares line
your typical miss (RMSE)
$21,103
best possible $14,667
best slope
$8.12
per $1 of search
best intercept
−$11,164
White: your line. Dashed green: the least-squares line. Each red mark is one week’s error.
Northpine’s 156 weeks, January 2023 to December 2025. The dashed line is the least-squares fit, computed in your browser.

Four things to try:

  1. Beat least squares. Try to get "your squared errors" to 1.00×. You can get close, but never below: that is what "least squares" means. Use the button to jump to the answer, a slope of 8.12.
  2. Switch to squared errors. Each square's area is that week's contribution to SSE. The big squares dominate: a few badly missed weeks matter more than many slightly missed ones.
  3. Add an odd week, then drag it. Put one week with very high spend and very low revenue at the bottom right, and watch one week out of 157 drag the slope down. That is the price of squaring. Check outliers before trusting a fit.
  4. Look for the confounder. The weeks with the most search spend are mostly high-demand weeks. Nothing in this chart can tell you that, which is why the slope you found is 8.12 and not 2.2. The confounding chart above shows the same weeks with demand added.

Looking inside the model

One week's prediction, taken apart

Because the model is a sum, each prediction splits exactly into one part per input. The cleanest way to show it is to start from an average week. With least squares, a week with every input at its average gets the average revenue, 66,283 dollars. Each input then adds its coefficient times how far this week is from the average:

y^=yˉ+∑jβ^j (xj−xˉj)\hat{y} = \bar{y} + \sum_{j} \hat{\beta}_j \, (x_j - \bar{x}_j)

Take Northpine's best week, June 16, 2025, with 120,220 dollars of revenue. Starting from 66,283, demand adds 34,954 because it was a high-interest week, the promotion that ran adds 7,170, search adds 6,467, display adds 21, and below-average social spend takes away 5,013. The prediction is 109,882. Slide through the weeks to see what drove each one.

One week’s prediction, taken apart
Try it
$0k$40k$80k$120kAn average week$66,283Paid search+$6,467Paid social−$5,013Display+$21Promotion week+$7,170Demand (search interest)+$34,954Prediction$109,882
2025-06-16
prediction
$109,882
actual revenue
$120,220
dashed line
miss
$10,338
Each bar is coefficient × (this week’s value − the average). They add up from an average week to the prediction.

This is the basis of the contribution charts in marketing mix modelling: revenue split into a baseline and a slice per channel. The slices are only as trustworthy as the coefficients, which is why the confounding section comes first.

Which inputs matter, and how much data it needs

The KNN guide in this series uses two extra charts here: permutation importance, to see which inputs a model relies on, and a learning curve, to see how much data it needs. Linear regression answers both more directly. Its coefficients, with their intervals, already say how much each input moves revenue and how sure the estimate is; the coefficient chart shows them against the truth. And the chart of the search estimate as more weeks are added, in the same section, is this model's learning curve: the interval narrows with the square root of the number of weeks, and leaving demand out stays wrong however much data you add.

Linear regression in Python

The model itself is a few lines of scikit-learn. Here it is fitted on the first 130 weeks:

from sklearn.linear_model import LinearRegression
 
features = ["paid_search_spend", "paid_social_spend", "display_spend",
            "promotion_week", "search_interest_index"]
train, test = weekly.iloc[:130], weekly.iloc[130:]
 
model = LinearRegression()
model.fit(train[features], train["revenue"])
 
pd.Series(model.coef_, index=features).round(2)
paid_search_spend           1.76
paid_social_spend           1.33
display_spend               1.06
promotion_week           8232.41
search_interest_index    1441.07

These differ slightly from the table earlier, which used all 156 weeks. model.predict(test[features]) gives predictions for the held-out weeks.

scikit-learn does not report standard errors or intervals. For those, use statsmodels, which takes the model as a formula and prints the full table:

spend = "paid_search_spend + paid_social_spend + display_spend + promotion_week"
models = {
    "search only": smf.ols("revenue ~ paid_search_spend", weekly).fit(),
    "all spend": smf.ols(f"revenue ~ {spend}", weekly).fit(),
    "all spend + demand": smf.ols(f"revenue ~ {spend} + search_interest_index", weekly).fit(),
}
pd.DataFrame({name: m.params for name, m in models.items()}).round(2)

smf is statsmodels.formula.api, imported at the top of the notebook. Each fitted model has .summary() for the full table, and .bse and .conf_int() for standard errors and intervals.

The notebook runs every calculation on this page, including the omitted-variable bias check, the bootstrap, the Durbin–Watson and VIF checks, and the ridge and lasso paths.

When to use linear regression, and when not to

Linear regression is a good choice when:

  • You need to explain the answer. Each coefficient is a number in business units that anyone can check against their intuition.
  • You want an effect, not just a prediction, and you can measure the confounders. With the right inputs and enough independent movement in each, it estimates effects with honest intervals, as it did here.
  • Data is limited. With a few hundred rows, a simple model with sensible inputs usually predicts as well as anything more complex, and fails in ways you can see.
  • You need a baseline. Even when another method wins, a linear model tells you how much the extra complexity is buying.

Choose something else, or extend it, when:

  • The relationship is curved or full of interactions you cannot specify in advance. Tree-based methods, later in this series, find thresholds and interactions on their own.
  • The outcome is a yes or no, such as whether a lead converts. Logistic regression, part 3, is the version built for that.
  • You need the effect of spend, and the confounders are unknown or unmeasured. No regression can hold fixed what it does not contain. Run an experiment.
  • You will predict outside the range of your data, such as doubling a budget. Treat the answer as a guess, not a forecast.
MethodWhat it gives youStrengthWatch out for
KNNA score from similar examplesExplains itself with real examplesScaling, slow at large scale
Linear regression (this guide)How much one number moves anotherSimple, readable effects with intervalsMistaking correlation for cause
Logistic regressionA probability for a yes or no outcomeAccurate, clear weights per columnStraight-line assumptions
Decision treeRules that split customers into groupsRules anyone can readUnstable, overfits if allowed
XGBoostStrong predictions from many treesUsually the most accurateNeeds extra tools to explain

Business cases

Each case applies linear regression to one marketing job, from the business problem to a working model, with the code and data:

Case 1Ad spend and salescoming soon

Download the data and the notebook

The notebook runs every calculation on this page in order, prints each number quoted here, and computes the data behind every chart in its appendix.

To run it: install Python, then run pip install pandas scikit-learn statsmodels jupyter, put both files in one folder, and open the notebook with Jupyter.

Want this on your own data?

If you would like to know what your own channels return, and whether your data can answer that question, get in touch and we can talk it through on a short call.