Lesson 19 of 19 · Statistics for AI, GenAI & LLMs

Beyond a Single Line: Multiple Regression, Logistic Regression & ANOVA

Real systems have many inputs, many outcomes, and more than two things to compare. This lesson stretches the one-line fit from Lesson 6 in three directions, and ends where every sigmoid output in a neural network begins.

Lesson 6 fit one line to one feature. Production never looks like that: quality depends on retrieval depth and prompt length and model version, a moderation score is a probability rather than a point on a line, and a prompt test often has three arms, not two. Three tools cover those cases: multiple linear regression, logistic regression, and one-way ANOVA. The second is the model sitting at the end of almost every classifier you will build.

1. Multiple regression: several features, one fit

Multiple regression is Lesson 6's line with more terms:

score = b0 + b1 × (passages retrieved) + b2 × (prompt length) + error

Each coefficient is read the same way as a slope, with one phrase added: b1 is the change in score per extra passage, holding prompt length fixed. That phrase is the whole point. The coefficient is not "the relationship between passages and score." It is the relationship that remains after the other features have been accounted for.

Here is a small, made-up evaluation. A team scores 8 RAG answers with an automated judge (0–100) and logs how many passages were retrieved and how long the prompt was, in hundreds of tokens:

RunPassages (x1)Prompt length, 100s of tokens (x2)Judge score (y)
11252
22158
32457
43366
53564
64473
75676
85580

Fit prompt length alone, as in Lesson 6, and it looks useful: slope 4.28 points per 100 tokens, t = 2.54, p = 0.044 on 6 degrees of freedom. A team reading only that would conclude that longer prompts help. Now fit both features together:

score = 45.42 + 7.41 × passages − 0.75 × length

The length coefficient changed sign. Holding passages fixed, an extra 100 tokens is worth −0.75 points, and (section 5) that estimate is statistically indistinguishable from zero. Prompt length looked helpful only because longer prompts tended to come with more passages (their correlation here is r = 0.78), and passages are what moves the score. This is the same confounding trap from Lesson 6, now with a tool that partly handles it: a regression can separate the effects of features it has measured. It cannot separate effects of things it has not measured, which is the topic of Lesson 17 (study design and confounding).

Key Insight A coefficient depends on which other features are in the model. The same feature can have slope +4.28 alone and −0.75 beside a better explanation. Never quote a coefficient without saying what was held fixed.

2. The matrix form, in one short step

Write every run as a row. Put a column of 1s first (for the intercept), then the features. That grid is a matrix X; the scores are a vector y; the coefficients are a vector β. The whole model is one line:

y = Xβ + error

Minimizing the sum of squared residuals (Lesson 6's least squares) has a closed-form answer called the normal equations: (XTX) β = XTy. For the 8 runs above, XTX and XTy are small enough to write out. The entries are just counts and sums of products: 8 runs, Σx1 = 25, Σx2 = 30, Σx1² = 93, Σx1x2 = 107, Σx2² = 132, Σy = 526, Σx1y = 1744, Σx2y = 2056.

[ 8 25 30 ] [ 526 ]
XTX = [ 25 93 107 ] XTy = [ 1744 ]
[ 30 107 132 ] [ 2056 ]
β = (XTX)-1 XTy = [ 45.417, 7.410, −0.753 ]

Solving it in Python (a linear solver, and separately a hand-written elimination) gives the same three numbers. Plug a run back in to check the fit: run 4 (3 passages, 300 tokens) predicts 45.417 + 7.410×3 − 0.753×3 = 65.39, against an actual 66, a residual of +0.61.

The matrix form scales to ten features or ten thousand: still a weighted sum of inputs, still the weights that minimize squared error. A neural network's layers are this same weighted sum, repeated and bent by nonlinearities.

3. R² versus adjusted R²

Lesson 6 defined R² = 1 − SSE/SST: the share of variation the model explains. Here SSE = 9.50 and SST = 689.5, so R² = 1 − 9.50/689.5 = 0.9862.

The weakness of R² is that it can only go up when you add a feature, even a useless one. Add a column of pure noise (say, the hour of day each run was logged: 9, 14, 11, 16, 10, 15, 13, 12) and the fit gets slightly better by accident:

ModelR²Adjusted R²
passages + length0.98620.9807
passages + length + hour of day0.98640.9763

Adjusted R² charges a penalty for each added coefficient: it replaces SSE and SST with their per-degree-of-freedom versions.

adj R² = 1 − [SSE / (n − p)] / [SST / (n − 1)] (p = number of coefficients incl. intercept)
= 1 − (9.498 / 5) / (689.5 / 7) = 1 − 1.8996 / 98.50
= 0.9807

The junk feature raised R² and lowered adjusted R², which is the signal you want. This is Lesson 8's overfitting in miniature: more parameters always fit the training data at least as well. Adjusted R² is a cheap guard; a held-out validation set is the real one.

4. Collinearity: when two features say the same thing

The length feature above was correlated with passages (r = 0.78) and the coefficients were still stable (the variance inflation factor, VIF, was 2.5). Now add a feature that is nearly a copy of one already present: prompt length measured in hundreds of characters (x3), which tracks token length almost exactly (r = 0.9985 with x2). Refit all three:

CoefficientWithout x3: estimate (SE)With x3: estimate (SE)
passages (b1)7.41 (0.57)5.03 (1.17)
length in tokens (b2)−0.75 (0.50)26.47 (12.44)
length in characters (b3)n/a−6.30 (2.88)
R²0.98620.9937
VIF of b2, b32.5about 2,800 and 2,500

These are the symptoms of collinearity:

The VIF measures this: VIF = 1/(1 − R²j), where R²j is how well the other features predict feature j. Above about 5–10 is a warning. Drop or combine the redundant features, or accept that you can predict but not attribute. Overlapping measurements are common in AI work: token and character counts, several similarity scores from one embedding, a model's confidence and its entropy (Lesson 7).

5. Inference on a coefficient

Every coefficient is an estimate from a sample of 8 runs, so it has sampling error, exactly as a sample mean did in Lesson 5. The regression gives each coefficient a standard error, and from it a t statistic and confidence interval, using the machinery from Lessons 5 and 15. The SE comes from the residual variance and the matrix you already built:

s² = SSE / (n − p) = 9.498 / 5 = 1.8996 (s = 1.378 judge points)
SE(b_j) = sqrt( s² × [(XTX)-1]jj )
length (b2): [(XTX)-1]22 = 0.1299
SE = sqrt(1.8996 × 0.1299) = 0.4968
t = −0.7533 / 0.4968 = −1.52 (5 degrees of freedom)
95% CI = −0.7533 ± 2.571 × 0.4968 = −0.7533 ± 1.2770 = [−2.03, +0.52]
two-sided p = 0.19 → cannot rule out zero
passages (b1): SE = 0.5688, t = 7.4105 / 0.5688 = 13.03, p = 0.00005
95% CI = 7.41 ± 2.571 × 0.5688 = 7.41 ± 1.46 = [5.95, 8.87]

The critical value 2.571 is the t distribution's 97.5th percentile at 5 degrees of freedom (n − p = 8 − 3). Read the results the way Lesson 15 taught: passages has a clear, sizeable effect, between roughly 6 and 9 points per extra passage. Length has an interval that straddles zero, so once passages are accounted for there is no evidence length matters. With only 8 runs, "no evidence" is also partly "not enough data to tell."

Residual checks, in one paragraph. The inference above assumes the errors are roughly independent, have constant spread, and are not systematically bent away from your line. Check by plotting residuals (actual minus predicted, Lesson 6) against the fitted values: a curve means a missing nonlinear term, a funnel shape (spread growing with the prediction) means the error variance is not constant, and a pattern across run order means runs are not independent, for instance because latency drifted over the day. Normality of the residuals matters least with a reasonable number of rows. Here the 8 residuals run from −1.95 to +1.30 with no obvious shape, though 8 points hide a lot.

6. Logistic regression: the classifier behind every sigmoid

Suppose the target is not a score but a yes/no outcome: did this answer contain an unsupported claim (1) or not (0)? A straight-line model is the wrong tool. Its predictions are unbounded, so it can output −0.3 or 1.4 as a "probability." Logistic regression keeps the weighted sum of features and fixes the output in two steps.

Odds and log-odds

Probability p can be restated as odds = p / (1 − p), the ratio of "happens" to "doesn't." The log-odds (the logit) is the natural log of that. It runs over the whole number line, which is exactly what a weighted sum does.

Probability pOdds p/(1−p)Log-odds
0.020.0204−3.89
0.100.111−2.20
0.310.449−0.80
0.5010
0.909+2.20
0.9849+3.89

The model is linear in the log-odds: z = b0 + b1x1 + b2x2. To get back to a probability, invert the logit with the sigmoid: p = 1 / (1 + e−z). Any z, however large, lands strictly between 0 and 1.

00.10.310.51-6-4-20246 log-odds z = b0 + b1·x1 + b2·x2 predicted probability p default threshold 0.5 cost-based threshold 0.10 (z = −2.20) worked example: z = −0.8, p = 0.31

The sigmoid turns any log-odds, however large or small, into a probability. A decision threshold is a horizontal line across the curve; where it crosses is the log-odds cutoff.

One worked prediction

Say a fitted model for "answer contains an unsupported claim" has these coefficients (illustrative): intercept −2.0; −0.9 per supporting passage retrieved; +0.7 per 100 tokens of answer length. For an answer with 1 supporting passage and 300 tokens:

z = −2.0 + (−0.9)(1) + (0.7)(3) = −0.8
p = 1 / (1 + e0.8) = 1 / (1 + 2.2255) = 0.310
predicted probability of an unsupported claim: 31%

Reading a coefficient as an odds ratio

A logistic coefficient is a change in log-odds per unit of the feature. Exponentiate it and you get a multiplier on the odds:

+1 supporting passage: odds multiply by e−0.9 = 0.407
before: odds = e−0.8 = 0.449 (p = 0.310)
after: odds = e−1.7 = 0.183 (p = 0.154) check: 0.449 × 0.407 = 0.183
+100 answer tokens: odds multiply by e0.7 = 2.014 (0.449 → 0.905, p = 0.475)

So one more supporting passage cuts the odds of an unsupported claim by about 59%, and 100 more answer tokens roughly doubles them. Two cautions. First, the odds ratio is constant, but the change in probability is not: that same passage moved p from 0.31 to 0.15 here, and would move it by far less near 0.01 or 0.99. Second, "doubles the odds" is not "doubles the probability" (0.31 to 0.475, not 0.62). Reports that say "twice as likely" when they mean twice the odds are a common error.

7. Why cross-entropy, not least squares

How are the coefficients chosen? Not by the normal equations: with a sigmoid in the way there is no closed form. Logistic regression is fit by maximum likelihood (Lesson 5): choose the coefficients that make the observed 0/1 labels most probable under Bernoulli outcomes (Lesson 4). Taking the negative log of that likelihood gives exactly the cross-entropy loss from Lesson 7, with a one-hot truth and two classes. The optimizer is the gradient descent of Lesson 8 (or a close cousin).

Could you instead keep minimizing squared error, as in linear regression? You could, and it trains badly. Compare what the two losses do when the model is confidently wrong: the true label is 1 (unsupported claim) and the model says p = 0.01.

loss gradient of loss w.r.t. z
cross-entropy: −ln(0.01) = 4.61 nats p − y = 0.01 − 1 = −0.990
(= 6.64 bits)
squared error: (1 − 0.01)² = 0.980 2(p − y) × p(1 − p) = 2(−0.99)(0.0099) = −0.0196
cross-entropy pushes 0.990 / 0.0196 = about 50 times harder at this mistake

With squared error, the sigmoid's own slope (p(1 − p)) multiplies the gradient, and that slope is nearly zero at the flat ends of the curve. So the worse the confident mistake, the weaker the correction: the model gets stuck exactly where it is most wrong. Cross-entropy's gradient with respect to z is just p − y, which grows with the error. Squared error on a sigmoid is also non-convex in the weights, while cross-entropy keeps logistic regression convex. That is why cross-entropy trains every classifier from a spam filter to a language model.

8. Thresholds, base rates, and the last layer of a neural network

Back to Lesson 3's base rates

The model outputs a probability; something must still decide. The default cutoff p > 0.5 has no special status. Let a wasted human review of a clean answer cost 1 unit and a missed unsupported claim cost 9. Flag an answer when the expected cost of not flagging exceeds the cost of flagging: p × 9 > (1 − p) × 1, which gives p > 1/(1 + 9) = 0.10. That is the lower dashed line on the curve above, at log-odds −2.20. Lesson 9 then asks what precision and recall that threshold buys you.

Log-odds also make Lesson 3's Bayes update additive. The hallucination detector there had a 2% base rate and a likelihood ratio of 0.90/0.05 = 18 for a flag:

prior log-odds: ln(0.02 / 0.98) = −3.892 ← this is what an intercept-only model learns
evidence: ln(18) = +2.890
posterior log-odds: −3.892 + 2.890 = −1.002 → sigmoid = 0.269

That is Lesson 3's 27%, reached by addition. The intercept is the base rate, expressed as log-odds. Practical consequence: train on a rebalanced 50/50 sample but deploy where the real rate is 2%, and the predicted probabilities are far too high until you shift the intercept by ln(0.02/0.98) − ln(0.5/0.5) = −3.89.

The last layer of a neural network

Open any binary classifier built on a neural network and its final layer is logistic regression. Every earlier layer turns the input (text, an image, embeddings) into a feature vector h. The last layer computes z = w · h + b and passes it through a sigmoid. Training it with binary cross-entropy is the loss from section 7. The only difference from this lesson is that the network learns the features instead of you supplying passages and token counts. With more than two classes, the sigmoid becomes the softmax from Lesson 4, and the two-class softmax is the sigmoid: softmax over logits (z, 0) gives ez/(ez + 1) = 0.310 for z = −0.8, the same number as above. A language model's next-token layer is the same idea at scale: one logit per vocabulary token, softmax, cross-entropy against the token that appeared (Lessons 7 and 10).

9. One-way ANOVA: is any group different?

Lesson 15 compared two groups with a t-test. A team testing three prompt variants has three groups. One-way ANOVA (analysis of variance) answers a single question: are all the group means equal, or is at least one different?

It works by splitting the total variation in the scores into two parts and comparing them. Say each of three prompt variants is run on 5 inputs and graded by a judge (0–100):

VariantScoresMean
Prompt A727570746972
Prompt B788076827979
Prompt C737775717474
6670758084grand mean 75Prompt A (mean 72)Prompt B (mean 79)Prompt C (mean 74) judge quality score

Thick bars are group means. How far the dots sit from their own bar is the within-group spread (SSW); how far the bars sit from the dashed grand mean is the between-group spread (SSB).

The grand mean of all 15 scores is 75. Two kinds of spread exist:

SSB = 5(72−75)² + 5(79−75)² + 5(74−75)² = 45 + 80 + 5 = 130
SSW = A: (0²+3²+2²+2²+3²) + B: (1+1+9+9+0) + C: (1+9+1+9+0) = 26 + 20 + 20 = 66
SST = 130 + 66 = 196 (matches summing (score − 75)² over all 15 scores)
degrees of freedom: between = 3 − 1 = 2, within = 15 − 3 = 12
MSB = 130 / 2 = 65.0 MSW = 66 / 12 = 5.5
F = MSB / MSW = 65.0 / 5.5 = 11.82

F is a ratio of signal to noise: the spread between group means, per degree of freedom, divided by the spread inside groups. If the null (all means equal) were true, F would hover near 1. For the F distribution with 2 and 12 degrees of freedom, the tail probability has a closed form, P(F > f) = (12 / (12 + 2f))6, so no statistics library is needed:

p = (12 / (12 + 2 × 11.82))6 = (12 / 35.636)6 = 0.33676
p = 0.0015
5% critical value: F = 6 × (0.05−1/6 − 1) = 3.89; 11.82 is well beyond it

Numerically integrating the F density gives the same 0.0015. Reject "all three prompts score the same." The share of total variation explained by the prompt is SSB/SST = 130/196 = 0.66.

Why not just run three t-tests?

Because of the multiple-comparisons problem from Lesson 15. Three pairwise tests at 5% each give about a 1 − 0.953 = 14% chance of at least one false positive if the prompts are identical (the tests overlap, so the exact figure is a little lower, but still well above 5%). Add a fourth and fifth prompt and it climbs fast. ANOVA asks one question with one test at one 5% error rate, so the chance of falsely declaring "something differs" stays at 5% however many groups you have. Running ANOVA first is the protected way in.

What ANOVA cannot tell you

A significant F says only that the means are not all equal. It does not say which prompt is different, by how much, or which is best. To find out you need follow-up comparisons, and those reopen the multiple-comparisons problem, so correct for them. With pooled s = sqrt(MSW) = 2.345, each pairwise standard error is 2.345 × sqrt(2/5) = 1.483:

PairDifferencet (12 df)pBelow 0.05/3 = 0.0167?
B − A+74.720.0005yes
B − C+53.370.0056yes
C − A+21.350.20no

Prompt B beats both others; A and C cannot be told apart. Dedicated post-hoc procedures (Tukey's is the common one) do this more efficiently than the Bonferroni division used here. ANOVA also assumes roughly normal scores within each group, similar spread across groups, and independent observations. With 5 scores per group these are hard to verify. A significant F is the start of the analysis, not the verdict; report the group means and the size of the gaps.

10. Why this matters for building AI systems

Why This Matters These three tools are how you move from "this metric moved" to "this input caused it, and here is how sure we are."

Attribution. Metrics depend on many levers at once: retrieval depth, prompt length, model version, temperature. A regression that includes them all separates their effects, provided you check VIFs and remember that anything unmeasured can still confound.

Probability models. Quality gates, hallucination flags, routing and reward models all end in "probability that X." The logit, the odds ratio and a cost-based threshold let you explain a gate, retune it when the base rate shifts, and avoid confusing odds with probability. A well-built logistic regression is also the baseline any heavier model has to beat.

Experiments with three or more arms. Run one omnibus test, then corrected pairwise follow-ups, and report effect sizes with intervals, not only the winner.

11. Where this leaves you

This is the last lesson of the course, so here is how the pieces connect and where to go from here.

Next, practice on your own data: a multiple regression on logged eval scores (check the VIFs), a logistic regression on a flagged-or-not label with a threshold set from real review costs, an ANOVA on your next three-way prompt test. Beyond this course, the natural next steps are regularized and generalized linear models (ridge, lasso, Poisson regression), mixed-effects models for repeated measures on the same inputs, and causal inference for the question regression alone cannot answer.

Recap

✅ Check Yourself

1. Alone, prompt length has slope +4.28 on the judge score. In a model that also includes passages retrieved, its coefficient is −0.75. What is the best explanation?

The regression made an arithmetic error because adding a feature should never change an existing coefficient
Longer prompts really do hurt, and the one-feature fit was wrong
Longer prompts tended to come with more passages, so alone the length coefficient was picking up the passages' effect; holding passages fixed it has little left

2. Adding a useless feature (hour of day) moved R² from 0.9862 to 0.9864 and adjusted R² from 0.9807 to 0.9763. What does that show?

R² rises whenever a feature is added, even noise, while adjusted R² penalizes the extra coefficient and correctly falls
The hour of day is the most important feature because R² went up
Adjusted R² is broken because it should always be at least as high as R²

3. A logistic regression has a coefficient of +0.7 on answer length (per 100 tokens). Which statement is correct?

Each extra 100 tokens raises the probability by 0.7
Each extra 100 tokens multiplies the odds by e0.7, about 2.0; the change in probability depends on where you start
Each extra 100 tokens doubles the probability

4. Why is squared error a poor loss for fitting a sigmoid output, compared with cross-entropy?

Squared error can only be computed on continuous targets, never on 0/1 labels
Cross-entropy is always smaller, so models train faster on the smaller number
Its gradient is multiplied by the sigmoid's slope, which is near zero when the model is confidently wrong, so the correction vanishes where it is needed most

5. A one-way ANOVA on three prompt variants gives F = 11.82, p = 0.0015. What can you conclude?

At least one variant's mean differs from the others; a corrected follow-up comparison is needed to say which
Every variant differs from every other variant
The variant with the highest mean is the best, with p = 0.0015 of being wrong