2.2.1 · D3Linear & Logistic Regression

Worked examples — Simple linear regression model

3,703 words17 min readBack to topic

This page is a worked-example gym for the parent model. The parent gave you two clean, friendly examples where the slope came out positive and the numbers were tidy. Real data is messier. Here we hunt down every kind of case the OLS (Ordinary Least Squares) formulas can throw at you — negative slopes, zero slopes, degenerate inputs where the formula breaks, tiny datasets, and exam twists — and we work each one fully.

Before we start: recall the two formulas we will use over and over. Everything on this page is just these two lines applied to different data.

First, the symbols that appear inside those formulas, defined in plain words:

  • ==== ::: the number of data points you have (if you measured 5 houses, ).
  • ==== ::: a counter that walks through the points one at a time — is the first point, the second, up to , the last. So means "the and of point number ."
  • ==== ::: "add up the thing to my right, once for each point, from the first () to the last ()."
  • ==== (read "x-bar") ::: the mean (average) of all the values, — the balance point of the inputs.
  • ==== (read "y-bar") ::: the mean (average) of all the values, — the balance point of the outputs.
  • ==== (the slope) ::: how many units changes when goes up by exactly one unit.
  • ==== (the intercept) ::: the height of the line at ; it slides the whole line up or down.

The scenario matrix

Every simple-linear-regression problem falls into one of these cells. The examples below are each tagged with the cell they cover, so by the end you will have seen all of them.

Cell What makes it special Example
A. Positive slope , top of is positive Ex 1
B. Negative slope , top of is negative Ex 2
C. Zero slope and unrelated, top of Ex 3
D. Degenerate: all equal bottom of → formula undefined Ex 4
E. Two points only (limiting case) line fits perfectly, error Ex 5
F. Outlier distortion one bad point drags the slope Ex 6
G. Real-world word problem translate words → numbers → interpret units Ex 7
H. Exam twist + degenerate given summary stats; also the all--equal () trap Ex 8

Throughout, we use two handy shorthands:

  • ==== ::: the sum — the top of the slope formula.
  • ==== ::: the sum — the bottom of the slope formula.

So compactly, .


[!example] Ex 1 — Cell A: Positive slope (the friendly base case)

Statement. Predict weekly sales (in $1000s) from ad spend (in $1000s), with points:

1 2 3 4 5
3 4 6 7 10

Forecast: More ads → more sales, so guess a positive slope, somewhere near 1.5–2.

Steps.

  1. Means: , . Why this step? Both formulas need the center point first — everything is measured relative to it.
  2. Deviations : . Deviations : . Why this step? The slope only cares how each point deviates from the center, not the raw values.
  3. . Why this step? This is the co-movement — the top of the slope; a positive result signals and rise together.
  4. . Why this step? This is the spread of — the bottom of the slope; it rescales the co-movement into "per unit of ."
  5. , and . Why this step? Dividing gives the slope; then places the line through the center so it is properly positioned.

Model: .

Verify: At (the mean), ✓ — a correct OLS line always passes through . Slope matches our guess. Units: $1000 sales per $1000 ad spend.


[!example] Ex 2 — Cell B: Negative slope

Statement. Predict ice-cream stock left from temperature (°C), with points:

10 20 30 40
90 70 50 30

Forecast: Hotter days → less stock left. Slope should be negative.

Steps.

  1. , . Why this step? We always locate the center point before measuring deviations.
  2. ; . Why this step? Deviations are what the slope formula multiplies together; notice and deviations have opposite signs.
  3. . Why this step? When goes up while goes down, each product is negative, so their sum is negative → negative slope. This is the whole story of Cell B.
  4. . Why this step? We still need the spread of in the denominator to turn co-movement into a per-unit rate.
  5. , . Why this step? Dividing gives the negative slope; then re-centers the line through .

Model: .

Verify: At : ✓. Each 1 °C rise sells 2 more units (stock drops by 2). Sign is negative, matching the forecast.


[!example] Ex 3 — Cell C: Zero slope (no relationship)

Statement. A label (just an ID number ) is suspected to carry no information about a score . We design a dataset that is symmetric about its center so we can see cleanly what regression does when there is truly no trend. Data ():

1 2 3 4 5
4 8 6 8 4

Why this data? Notice is a mirror image: the ends ( and ) both sit at , the near-ends () both at . For every point that pulls the line up on the left, there is a twin pulling it down by the same amount on the right. Those pulls cancel exactly, forcing the co-movement to — the textbook picture of "no relationship."

Forecast: With trend-free, symmetric data, the slope should be exactly 0 and the line should just sit at the average height.

Steps.

  1. , . Why this step? We need the center before measuring any deviations.
  2. ; . Why this step? The mirror symmetry now shows up as symmetric -deviations that will cancel in pairs.
  3. . Why this step? This is the payoff of the symmetric design — the top of the slope is exactly .
  4. . Why this step? We still compute the bottom explicitly — it is a perfectly ordinary, non-zero . This matters: unlike Cell D below, the denominator here is fine, so the slope is a genuine , not an undefined one.
  5. . Then . Why this step? A zero numerator over a healthy denominator gives a real, definite slope of ; the intercept then just becomes the mean height.

Model: (a flat horizontal line).

Verify: With zero slope the best guess for any is just the mean ✓. That is exactly what regression should do when carries no information: fall back to the average. Note , so this is a true zero slope (contrast Cell D, where the slope is undefined).


[!example] Ex 4 — Cell D: Degenerate — all equal (formula undefined)

Statement. Someone recorded 4 houses () that are all the same size, , with prices . Fit a line.

Forecast: If never changes, we cannot possibly learn "how changes with ." Expect the formula to blow up.

Steps.

  1. . Every deviation . Why this step? The mean of identical values is that value, so every point sits exactly at the center in the -direction.
  2. . Why this step? is the only thing in the denominator of — checking it first tells us whether the formula is even usable.
  3. division by zero → undefined. Why this step? Dividing by zero has no answer; mathematically the slope simply does not exist, which is our signal the data cannot support a line.

Verify (read the figure — s01). Alt-text: four magenta dots stacked vertically at , with three differently-sloped dashed lines (violet, orange, navy) all drawn through the same stack. Look at the four prices plotted at the single size : they form a vertical stack. Now trace each dashed line in turn — the violet one tilts up, the orange one tilts down, the navy one is steep — yet every one of them passes through the stack equally well, because the points give no left-right information to prefer one over another. That visual "many equally-good lines" is exactly what "undefined slope" means: the data does not pick a winner. This is why software throws a "singular matrix" error. The cure: you need variation in .

Figure — Simple linear regression model

[!example] Ex 5 — Cell E: Two points only (limiting case, perfect fit)

Statement. Just two measurements (): and . Fit a line.

Forecast: Two points determine exactly one line, so the fit should be perfect (zero error).

Steps.

  1. , . Why this step? The center of just two points is their midpoint — we need it before deviations.
  2. Deviations: : ; : . Why this step? With only two points the deviations are mirror images, which will make the arithmetic clean.
  3. . . Why this step? We compute top and bottom together here since each is a quick two-term sum.
  4. , . Why this step? Divide for the slope, then set the intercept so the line runs through the midpoint.

Model: .

Verify: ✓ and ✓ — both points hit exactly, so RSS . This is the limiting boundary of regression: with there are no "leftover errors," which also means you have no way to detect noise. This is the extreme end of the overfitting spectrum — a model that fits its (tiny) data perfectly but tells you nothing about reliability.


[!example] Ex 6 — Cell F: One outlier hijacks the slope

Statement. Clean data follows : . Now add a typo point , giving . Compare the fitted slope with and without the outlier.

Forecast: The single wild point at will pull the slope way up above the true value of .

Steps (with the outlier, all 5 points).

  1. , . Why this step? The outlier already shows its power here — it drags the mean of from a natural up to .
  2. ; . Why this step? Deviations reveal the outlier's huge gap, which will dominate the co-movement sum.
  3. . Why this step? The single term swamps everything else — this is the outlier hijacking the numerator.
  4. . Why this step? The -spread is untouched by the -outlier, so the denominator stays the ordinary .
  5. , . Why this step? Dividing gives a slope of — ten times the true value — showing how one point distorts the whole fit.

Model (contaminated): — slope , not the true !

Without the outlier (points ): , , , , so , : .

Verify (read the figure — s02). Alt-text: four violet dots lying exactly on a gentle line , one orange X far above at , and a steep dashed magenta line tilted up toward the X. First look at the four violet points — they sit perfectly on the gentle violet line , the honest trend. Now follow the orange X at and watch the dashed magenta line: it is yanked steeply upward to chase that one point, giving slope . Check the outlier's own residual on the contaminated line: at , , so the residual is — still the largest error in the dataset, and because the loss squares residuals, that term dominates the total and is what tilted the line so far. (Even after tilting, the point refuses to be fit — that is the outlier's grip.) This is why residual plots and outlier checks live in diagnostics. Sanity: with the outlier gone, the line passes through every clean point exactly.

Figure — Simple linear regression model

[!example] Ex 7 — Cell G: Real-world word problem

Statement. A coffee shop tracks daily outdoor temperature (°C) and iced-coffee cups sold over days:

15 18 21 24 27
40 55 62 78 95

Predict sales on a forecast 30 °C day, and state the meaning of both coefficients in plain words.

Forecast: Warmer → more iced coffee. Positive slope; near 30 °C expect ~100+ cups.

Steps.

  1. , . Why this step? Translate the word problem into numbers by finding the center of the data.
  2. ; . Why this step? Deviations strip out the raw scale so we can measure how temperature and sales move together.
  3. . Why this step? All products are positive → warm days really do come with more sales (co-movement is strongly positive).
  4. . Why this step? We need the temperature spread to convert co-movement into "cups per °C."
  5. , . Why this step? Dividing gives the per-degree rate; the intercept then anchors the line through .
  6. Predict at : cups. Why this step? Plugging the target temperature into the finished model is the entire point of building it.

Verify (units + sanity):

  • Slope cups/°C: each 1 °C warmer sells about 4.4 extra cups — plausible.
  • Intercept cups: at 0 °C the model predicts negative cups. Nonsense literally, but 0 °C is outside the observed 15–27 °C range — a classic extrapolation warning (the parent's Mistake 1).
  • The 30 °C prediction is just outside the data, so ~106 cups is a mild, defensible extrapolation. Passes through : ✓.

[!example] Ex 8 — Cell H: Exam twist (given summary stats) + the trap

Statement. An exam gives you only: , , , , . It also reports two "spread" numbers, defined next. Find the line and its — then answer a follow-up: what happens to if instead every had been identical?

First, the two symbols the exam hands you:

  • ==== (Total Sum of Squares) ::: add up, over all points, how far each sits from the average , squared — the total wiggle in before any model. Here .
  • ==== (Residual Sum of Squares) ::: add up, over all points, how far each real sits from the line's prediction , squared — the wiggle the line could not explain (the leftover error). Here .

And the metric they ask for:

  • ==== (coefficient of determination) ::: the fraction of 's total wiggle that the line successfully explained; is a perfect fit, means the line did no better than guessing .

Forecast: With and you can get the line directly — no need for raw points. Since RSS () is much smaller than TSS (), the line explains most of the variation, so should be high-ish.

Steps.

  1. . Why this step? The slope formula is — the raw data was only ever a way to compute these two sums, so summary stats are enough.
  2. . Why this step? The intercept formula needs only the slope and the two means, all of which we now have.
  3. . Why this step? is the fraction of 's total wiggle (TSS) that the line removed; whatever is left as error (RSS) over the total is the fraction it missed, so minus that is the fraction explained.

Model: , with .

Follow-up — the degenerate case. 4. Suppose instead every were the same value, say for all points. Then too, so every and . Why this step? sits in the denominator of ; before trusting we must check it is not zero, exactly as we checked in Cell D. 5. division by zero → undefined. Why this step? With no variation in there is nothing for the model to "explain," so the very question "what fraction of the variation did we capture?" is meaningless.

Verify: For the main problem, sits in ✓, and the line passes through : ✓. For the follow-up, indeed gives an undefined ✓. Interpretation of the main case: 75 % of the variation in is captured by ; the remaining 25 % is noise or missing features — a bridge to adding more predictors and, when is a yes/no label instead of a number, to the logistic model.


Wrap-up recall

Recall Which sum being zero makes the slope

undefined vs zero? (all equal) makes undefined (Cell D). (no co-movement) makes exactly zero — a flat line at (Cell C).

Recall When is

itself undefined? When , i.e. every is identical (Cell H follow-up): the denominator of is zero, so there is no variation to explain.

Recall Where does every OLS line always pass, no matter the data?

Through the center point , because forces it.

Recall Why does one outlier move the slope so much?

The loss squares residuals, so a far-away point's large squared error dominates and drags the line toward it (Cell F).

The whole slope is
co-movement of divided by the spread of .
Fitting engine that finds these betas by iterating instead of formula
Gradient descent.