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.
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.
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:
| week | search interest | paid search | paid social | display | promotion | revenue |
|---|---|---|---|---|---|---|
| 2023-01-02 | 81.2 | 3,910 | 3,790 | 4,190 | 0 | 19,600 |
| 2023-01-09 | 84.9 | 4,400 | 9,700 | 2,990 | 0 | 22,490 |
| 2023-01-16 | 92.8 | 8,690 | 3,820 | 2,830 | 0 | 35,440 |
| 2023-01-23 | 89.2 | 10,980 | 5,410 | 2,570 | 0 | 37,450 |
| 2023-01-30 | 96.7 | 7,670 | 6,690 | 1,530 | 0 | 36,110 |
| Column | What it is | Range |
|---|---|---|
search_interest_index | How much people searched for this kind of software that week, an index of market demand | 81.2 to 134.3 |
paid_search_spend | Dollars spent on search ads | 3,910 to 15,280 |
paid_social_spend | Dollars spent on social media ads | 500 to 12,200 |
display_spend | Dollars spent on display ads | 400 to 8,580 |
promotion_week | 1 if a promotion ran that week, 0 if not | 24 of 156 weeks |
revenue | New revenue booked that week, in dollars | 6,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 , and the outcome, revenue, written . The model is a straight line:
(read "y-hat") is the prediction. is the intercept, the prediction when is zero. is the slope, how much the prediction changes when goes up by one. The Greek letters are the weights the model has to learn.
For each past week , the gap between what happened and what the line predicts is the residual, or error:
A worked example. The least-squares line for Northpine, found in the next sections, has and . In the first week of 2023, search spend was 3,910, so the line predicts . Revenue was 19,600, so the residual is : 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:
where is the number of weeks, 156 here. The least-squares line is the pair 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:
and 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 marks it as an estimate from data, not the true value.
On Northpine's weeks:
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 inputs the line becomes a flat surface in more dimensions, but the equation is the same idea:
Writing all 156 weeks at once is easier with matrices. Stack the outcomes into a column , and the inputs into a table with one row per week and a first column of ones for the intercept. Then
where is the column of weights and the column of errors. Minimising the squared error gives the normal equations, and solving them gives every weight at once:
is turned on its side, and the means the matrix inverse, the matrix version of dividing. holds the sums of squares and cross-products of the inputs; 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, , the directions are the derivatives:
and each step moves the weights a small distance , the learning rate, against them:
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.
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:
| Input | Coefficient | Standard error | 95% interval | True value |
|---|---|---|---|---|
| Paid search (per dollar) | 1.665 | 0.317 | 1.039 to 2.292 | 2.2 |
| Paid social (per dollar) | 1.375 | 0.210 | 0.961 to 1.789 | 1.4 |
| Display (per dollar) | 1.058 | 0.382 | 0.303 to 1.813 | 0.6 |
| Promotion week | 8,474 | 1,347 | 5,812 to 11,136 | 9,000 |
| Demand (per index point) | 1,479 | 61 | 1,358 to 1,600 | |
| Intercept | −125,503 | 4,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:
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:
For the one-input model, : search spend alone accounts for two thirds of the variation in weekly revenue. Switch between models in the chart to see the errors shrink.
| Model | R² | Residual standard error |
|---|---|---|
| Search spend only | 0.667 | 14,761 |
| All spend and promotions | 0.740 | 13,171 |
| All spend, promotions and demand | 0.947 | 5,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:
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 instead of :
The model used 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, 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:
Three things make an estimate more precise: less noise ( smaller), more weeks (the sums in 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:
where is a value from the t distribution, 1.976 for 150 degrees of freedom. For search:
The t-statistic, , 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.
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.
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 , doing the same for revenue to get , and fitting a line between the two sets of leftovers:
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 on the omitted variable, and 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:
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 (), and each extra dollar of search spend goes with 0.00383 more points of demand ():
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 ( positive) and rises with the input ( 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.
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.
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.
- Linearity. The outcome really is a weighted sum of the inputs, so no curve or interaction is missing.
- Independent errors. One week's error says nothing about the next week's.
- Constant variance. Errors are about the same size in big weeks and small weeks.
- Normal errors. The errors roughly follow a bell curve. This matters mostly for small samples and for prediction intervals.
- No exact collinearity. No input is an exact combination of the others, so exists.
- 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:
It is about 2 when consecutive errors are unrelated, below 2 when errors come in runs, and above 2 when they alternate.
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 on all the other inputs, call the R² of that regression , and:
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.
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.
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.
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:
Lasso penalizes the sum of their absolute values:
(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 added to the diagonal:
Adding 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 are not comparable, because the two formulas are written differently.
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 is just the equation, . How sure it is depends on the question. For the average revenue of all weeks with those inputs, the confidence interval is:
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:
The term grows as 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.
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, , 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:
- Logarithms model diminishing returns, as above. A log of the outcome makes coefficients read as percentage changes.
- Squares () model a curve with a peak or a trough.
- Interactions () let one input change the effect of another, such as a promotion working better in high-demand weeks. The effect of then depends on : it is .
- 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.
Four things to try:
- 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.
- 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.
- 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.
- 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:
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.
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.07These 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.
| Method | What it gives you | Strength | Watch out for |
|---|---|---|---|
| KNN | A score from similar examples | Explains itself with real examples | Scaling, slow at large scale |
| Linear regression (this guide) | How much one number moves another | Simple, readable effects with intervals | Mistaking correlation for cause |
| Logistic regression | A probability for a yes or no outcome | Accurate, clear weights per column | Straight-line assumptions |
| Decision tree | Rules that split customers into groups | Rules anyone can read | Unstable, overfits if allowed |
| XGBoost | Strong predictions from many trees | Usually the most accurate | Needs 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:
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.