Statistical Inference & Applied Statistics
A Complete 10-Chapter Maths for Programmers Course
Table of Contents
- From Descriptive to Inferential: What This Course Adds
- Sampling & the Sampling Distribution
- Confidence Intervals
- Hypothesis Testing Fundamentals
- The t-test & Comparing Two Groups
- A/B Testing in Practice
- Correlation vs. Causation
- Linear Regression as Statistical Inference
- Bayesian Inference & Updating Beliefs
- Capstone — Designing and Analyzing a Real Experiment
From Descriptive to Inferential: What This Course Adds
Statistical Inference & Applied Statistics
Chapter 1 · From Descriptive to Inferential: What This Course Adds
Probability & Statistics Fundamentals' own Chapter 1 opened with a direction: model known, predict the outcome. Its Chapter 9 flipped that briefly — summarize data you already have. This course goes one step further than either: given only a limited, incomplete sample of data, how confidently can you say anything about the full, unobserved reality behind it? That's inference, and it's the genuinely hard, genuinely useful part of applied statistics.
Descriptive vs. Inferential — A Direction Change
| Probability & Statistics Fundamentals | This course | |
|---|---|---|
| Direction | Known model → predicted outcomes; real data → a summary of that data | A limited sample → a confident, quantified claim about the true, unobserved population |
| Example question | "What's the mean of these 7 response times?" (Ch.9) | "Given these 7 response times, what can we honestly say the true average response time is, across every request that will ever happen?" |
| Core tools | Probability rules, distributions, expected value, descriptive statistics | Sampling distributions, confidence intervals, hypothesis tests, regression, Bayesian updating |
Chapter 9's own worked example computed a mean and median from exactly seven sampled response times. It never asked the harder question this course opens with: how much should anyone actually trust a number computed from just seven data points? That's the entire subject of this course.
Five Concrete Connections to Real Work
| Inferential topic | Where it actually shows up |
|---|---|
| Sampling & sampling distributions (Ch.2) | Every metric ever computed from "the last 10,000 sessions" rather than every session that will ever occur — which is nearly always the real situation |
| Confidence intervals (Ch.3) | Reporting "conversion rate: 5.2% ± 0.4%" instead of a falsely precise single number that hides how much uncertainty the sample size actually leaves |
| Hypothesis testing & A/B testing (Ch.4–6) | Deciding whether a new feature genuinely moved a metric, or whether the observed difference is just ordinary sample-to-sample noise |
| Correlation, causation & regression (Ch.7–8) | Analytics dashboards showing "X correlates with Y," and the classic mistake of assuming that means X causes Y; predicting a continuous outcome from real data |
| Bayesian updating (Ch.9) | Formally revising a belief as new evidence arrives over time — extending Probability & Statistics Fundamentals' own Bayes' Theorem chapter from a single fixed calculation into an ongoing, evidence-accumulating process |
What This Course Builds Directly On
What This Course Won't Cover
A few genuinely related topics stay deliberately out of scope, to keep this course focused on the core inferential toolkit rather than sprawling into adjacent specialties:
- Advanced experimental design — multi-armed bandits, sequential testing, and other more sophisticated A/B testing variants beyond the fixed-sample-size approach Chapter 6 covers
- Machine learning model evaluation — cross-validation, precision/recall, and related ML-specific metrics belong to Data Science & ML's own
ds1/ml1courses, not here - Full computational Bayesian methods — MCMC sampling and similar techniques for genuinely complex Bayesian models stay out of scope; Chapter 9 covers Bayesian reasoning, not Bayesian computation at scale
Where This Course Is Headed
| Chapter | Topic |
|---|---|
| 2 | Sampling & the Sampling Distribution |
| 3 | Confidence Intervals |
| 4 | Hypothesis Testing Fundamentals |
| 5 | The t-test & Comparing Two Groups |
| 6 | A/B Testing in Practice |
| 7 | Correlation vs. Causation |
| 8 | Linear Regression as Statistical Inference |
| 9 | Bayesian Inference & Updating Beliefs |
| 10 | Capstone — Designing and Analyzing a Real Experiment |
Hands-On Exercises
Classify each of the following as belonging more to Probability & Statistics Fundamentals (a known model, or a plain summary of data in hand) or to this course (drawing a conclusion about an unobserved population from limited data): (a) computing the average of 50 measured response times, (b) claiming, from those same 50 measurements, that the true average across all future requests is likely between 190ms and 210ms, (c) given a known fair coin, finding the probability of 3 heads in 5 flips, (d) deciding whether a 2% lift in conversion rate seen in a 2-week experiment reflects a real effect or random noise.
📄 View solutionA colleague says "we don't need confidence intervals — we computed the mean directly from our data, so we already know the real answer." Using this chapter's own descriptive-vs-inferential distinction, explain what's wrong with this reasoning.
📄 View solutionExplain, in your own words, how this course's Chapter 2 (sampling distributions) depends directly on Probability & Statistics Fundamentals' own Chapter 8 (the Central Limit Theorem), and how this course's Chapter 9 (Bayesian updating) depends directly on that same course's Chapter 4 (Bayes' Theorem) — using this chapter's own "not starting from zero" finding.
📄 View solutionChapter 1 Quick Reference
- Descriptive statistics (Fundamentals Ch.9) summarizes data you already have; inferential statistics (this course) uses that data to draw a confident, quantified conclusion about the unobserved whole
- Five direct connections: sampling → any real metric from a subset of data, confidence intervals → honest uncertainty reporting, hypothesis/A-B testing → "is this difference real," correlation/regression → dashboards and prediction, Bayesian updating → revising beliefs over time
- Built directly on two forward references from the sibling course: the CLT (Ch.8 there) feeds sampling distributions here; Bayes' Theorem (Ch.4 there) feeds Bayesian updating here
- Deliberately out of scope: advanced experimental design, ML model evaluation, and full computational Bayesian methods
- Next chapter: Sampling and the sampling distribution
Sampling & the Sampling Distribution
Statistical Inference & Applied Statistics
Chapter 2 · Sampling & the Sampling Distribution
Chapter 1 promised this chapter would build directly on Probability & Statistics Fundamentals' own Central Limit Theorem. Here's the payoff: the CLT isn't just a curiosity about averages — it's the entire mathematical foundation for saying anything trustworthy about a limited sample.
Population vs. Sample
The population is the complete set of everything you'd ideally want to know about — every request that will ever be made, every user who will ever sign up. The sample is the limited subset actually collected and measured. Almost every real measurement in engineering is a sample, not the full population — you never have every request that will ever occur, only the ones logged so far.
x̄ estimating the true population mean μ, for instance.
Sampling Error — Not a Mistake, Just Randomness
Sampling error is the natural, expected difference between a point estimate and the true population value, arising purely from which subset happened to be sampled — not from anything done wrong. Two different samples of the same size, drawn from the exact same population, will almost always produce two slightly different sample means, purely by chance.
The Sampling Distribution
Imagine repeating the sampling process many times — draw a fresh sample of size n, compute its mean, and repeat. The distribution of all those sample means is the sampling distribution of the sample mean — a genuinely different object from the distribution of individual data points.
μ, σ²/n) as n grows — regardless of the shape of the original population. Its own standard error formula, SE = σ/√n, is the standard deviation of this sampling distribution. Nothing new needs deriving here — this chapter is that formula, put to direct use.
Worked Example: Response Times, Revisited
Reusing Probability & Statistics Fundamentals' own response-time model — true population mean μ = 200ms, true population standard deviation σ = 30ms (values a team would rarely know for certain in reality, but useful here to see sampling behavior clearly):
| Sample size n | Standard error (σ/√n) |
|---|---|
| 25 | 6.0ms |
| 100 | 3.0ms |
| 900 | 1.0ms |
Suppose a team samples n = 25 requests and gets a sample mean of 204ms — 4ms above the true 200ms. Standardizing this as a z-score against the sampling distribution (not individual requests): z = (204 − 200) / 6 = 0.667. That's a thoroughly unremarkable result — well within a single standard error, exactly the kind of harmless wobble sampling error alone would produce. Nothing here suggests anything actually changed.
Sampling Error vs. Sampling Bias — A Critical Distinction
Collecting more data shrinks sampling error, per the σ/√n formula above — but only if the sampling method itself is sound. If the method itself systematically excludes part of the population, more data doesn't fix anything.
Sampling & the Sampling Distribution in Code
Hands-On Exercises
A metric's true population standard deviation is σ = 200 users. A sample of n = 25 days gives a sample mean 90 users above the assumed population mean. Compute the standard error, then the z-score for this sample mean against the sampling distribution. Is this result unremarkable (well within 1–2 standard errors) or notably large?
A metric has population standard deviation σ = 80. Compute the standard error for sample sizes n = 4, n = 16, and n = 64. Describe the pattern in how much n must grow to halve the standard error, connecting it back to Probability & Statistics Fundamentals' own Chapter 8 finding.
A company estimates customer satisfaction using only responses from an optional online contact form — a small, self-selected fraction of all customers. Their estimated satisfaction score is very high. Using this chapter's own sampling-error-vs-sampling-bias distinction, explain why collecting 10 times more responses through that exact same method would not fix the underlying problem with this estimate.
📄 View solutionChapter 2 Quick Reference
- Population = everything you'd ideally want to know; sample = the limited subset actually collected
- Point estimate: a single sample statistic (e.g.,
x̄) used to estimate an unknown population parameter (e.g.,μ) - Sampling error is the natural, expected sample-to-sample variation — not a mistake
- Sampling distribution of the sample mean: approaches Normal(μ, σ²/n) per the CLT —
SE = σ/√nis its standard deviation - Sampling error shrinks with more data; sampling bias (a systematically unrepresentative method) does not — more biased data is just more precisely wrong
- Next chapter: Confidence intervals
Confidence Intervals
Statistical Inference & Applied Statistics
Chapter 3 · Confidence Intervals
Chapter 2 established that a point estimate always carries sampling error. A confidence interval is the direct, practical fix: instead of reporting a single number as if it were exact, report a range of plausible values, together with how confident that range actually is.
Building a Confidence Interval
CI = point estimate ± (critical value × standard error)
The critical value (z*) comes straight from Probability & Statistics Fundamentals' own standard normal distribution — how many standard errors wide the interval needs to be to capture the stated percentage of the sampling distribution:
| Confidence level | Critical value (z*) |
|---|---|
| 90% | 1.645 |
| 95% | 1.960 |
| 99% | 2.576 |
Worked Example: The Response-Time Sample, Revisited
Reusing Chapter 2's own sample: n = 25 requests, sample mean x̄ = 204ms, σ = 30ms (still assumed known here — Chapter 5's own t-test covers the more realistic case where σ itself must be estimated). Standard error: SE = 30/√25 = 6ms.
| Confidence level | Interval | Width |
|---|---|---|
| 90% | [194.13, 213.87] | 19.74ms |
| 95% | [192.24, 215.76] | 23.52ms |
| 99% | [188.54, 219.46] | 30.91ms |
Width Shrinks With Sample Size
Reusing Chapter 2's own three sample sizes, at a fixed 95% confidence level:
| n | SE | 95% CI width |
|---|---|---|
| 25 | 6.0ms | 23.52ms |
| 100 | 3.0ms | 11.76ms |
| 900 | 1.0ms | 3.92ms |
More data doesn't change the confidence level — it tightens the interval at whatever confidence level was chosen, exactly Chapter 2's own σ/√n shrinkage, now made directly visible in the width of the reported range.
What a Confidence Interval Actually Means
A Forward Note: Proportions
Everything above used a sample mean. Chapter 6's A/B testing material needs confidence intervals for a proportion instead — a conversion rate, not an average response time. The idea is identical; only the standard error formula changes, to SE = √(p(1−p)/n). The confidence interval itself still follows the exact same estimate ± z* × SE shape.
Confidence Intervals in Code
Hands-On Exercises
A sample of n = 16 gives a sample mean of 550, with a known σ = 48. Compute the standard error, then the 95% confidence interval.
Given a fixed standard error of SE = 10, compute the width of the confidence interval at the 90%, 95%, and 99% confidence levels, using this chapter's own critical values. Confirm the widths increase as confidence increases, matching this chapter's own confidence-vs-width tradeoff.
A teammate says "we're 95% confident the true average is between 190ms and 210ms, so there's a 95% chance the real value is in that range." Using this chapter's own correct interpretation, explain specifically what's wrong with the teammate's restatement, and give the statistically correct version of the claim.
📄 View solutionChapter 3 Quick Reference
- CI formula:
point estimate ± (z* × SE), reusing Chapter 2's own standard error directly - Critical values: 90% → 1.645, 95% → 1.96, 99% → 2.576
- Higher confidence requires a wider interval — the confidence-vs-width tradeoff, with no way around it
- Interval width shrinks with sample size at any fixed confidence level, following Chapter 2's own
σ/√nshrinkage exactly - A 95% CI means: if this method were repeated many times, ~95% of the resulting intervals would contain the true value — not "95% probability this specific interval contains it"
- The same
estimate ± z* × SEshape applies to proportions too, withSE = √(p(1−p)/n)— Chapter 6's own A/B testing material - Next chapter: Hypothesis testing fundamentals
Hypothesis Testing Fundamentals
Statistical Inference & Applied Statistics
Chapter 4 · Hypothesis Testing Fundamentals
Chapter 2 ended on an unresolved tension: a z-score of 2.25 was called "notably large," but the chapter admitted it didn't yet have "the formal tool to make that determination with real statistical rigor." This chapter is that tool.
The Null and Alternative Hypothesis
H₁ (alternative hypothesis): the claim that there genuinely is an effect or difference.
A hypothesis test never proves H₁ — it only asks whether the observed data provides strong enough evidence to reject H₀. Failing to reject H₀ isn't the same as proving it true; it just means the evidence wasn't strong enough to rule it out.
Significance Level — Directly Tied to Chapter 3's Confidence Level
The significance level (α) is the threshold risk of a false rejection a team is willing to accept — conventionally α = 0.05 (5%). It's not a new idea: α = 1 − confidence level, exactly Chapter 3's own 95% confidence level restated from the opposite direction.
The Test Statistic and P-Value
z = (x̄ − μ₀) / SE p-value = 2 × (1 − Φ(|z|)) for a two-tailed test, using the same standard normal CDF Φ from Probability & Statistics Fundamentals Chapter 8.
The p-value answers a precise question: if H₀ were actually true, how likely is a result at least this extreme, purely from sampling error? A small p-value means the observed data would be a genuinely unusual coincidence under H₀ — evidence favoring H₁ instead.
p-value < α, reject H₀ ("statistically significant"). Otherwise, fail to reject H₀.
Resolving Chapter 2's Own Two Examples
Testing H₀: μ = 200ms against H₁: μ ≠ 200ms, reusing Chapter 2's own two scenarios:
| Scenario | z | p-value | Decision at α=0.05 |
|---|---|---|---|
| x̄=204ms, n=25, σ=30 (Ch.2's main example) | 0.667 | 0.505 | Fail to reject H₀ — confirms Ch.2's "unremarkable" call |
| 90-unit shift, n=25, σ=200 (Ch.2's Exercise 1) | 2.25 | 0.024 | Reject H₀ — formally confirms Ch.2's "notably large" call |
Chapter 2 could only eyeball these results informally. This chapter turns that instinct into a precise, defensible number.
Type I and Type II Errors
Every hypothesis test can go wrong in two distinct ways:
| H₀ is actually true | H₀ is actually false | |
|---|---|---|
| Reject H₀ | Type I error (false positive) — rate controlled directly by α | Correct decision |
| Fail to reject H₀ | Correct decision | Type II error (false negative) — a real effect gets missed |
Lowering α reduces Type I errors directly, but — with a fixed sample size — tends to increase Type II errors, since a stricter threshold makes real effects harder to detect too. Neither error can be eliminated without more data.
Two Real Cautions
α = 0.05, testing 15 genuinely null hypotheses (no real effect in any of them) still produces, on average, 15 × 0.05 = 0.75 "statistically significant" results purely by chance. Running many tests and reporting only the "significant" ones — without correcting for how many tests were actually run — is a direct path to false conclusions, exactly the base-rate reasoning Probability & Statistics Fundamentals' own Bayes' Theorem chapter warned about from a different angle.
n shrinks the standard error enough that even trivial effects produce a small p-value. A significant result answers "is there probably a real effect," not "is this effect big enough to matter." Both questions need answering separately.
Hypothesis Testing in Code
Hands-On Exercises
Testing H₀: μ = 50 against H₁: μ ≠ 50, a sample of n = 36 gives x̄ = 54, with known σ = 12. Compute the standard error, the z-statistic, and the p-value. State the decision at α = 0.05.
A team runs a hypothesis test and rejects H₀, concluding their new feature improved conversion. It later turns out the feature had no real effect at all — the observed difference was just sampling noise. Which type of error occurred: Type I or Type II? Now describe a second, different scenario where the opposite error type occurs instead.
📄 View solutionA team runs 20 independent A/B tests in a single quarter, all at α = 0.05, and none of the 20 features actually has any real effect. Using this chapter's own multiple-testing finding, compute the expected number of tests that will show a "statistically significant" result purely by chance, and explain what this implies for how the team should interpret a report claiming "3 out of 20 tests were significant this quarter."
Chapter 4 Quick Reference
- H₀ (null, "no effect") vs H₁ (alternative, "real effect") — a test can reject H₀, never prove H₁
- Significance level α = 1 − confidence level (Chapter 3) — conventionally 0.05
- Z-statistic:
z = (x̄ − μ₀)/SE; p-value:2(1 − Φ(|z|))— reject H₀ when p-value < α - Type I error: false positive (rejecting a true H₀), rate = α; Type II error: false negative (missing a real effect)
- Running many tests inflates the expected number of false positives purely by chance — the multiple-testing trap
- Statistical significance ("probably a real effect") is not the same question as practical significance ("is it big enough to matter")
- Next chapter: The t-test and comparing two groups
The t-test & Comparing Two Groups
Statistical Inference & Applied Statistics
Chapter 5 · The t-test & Comparing Two Groups
Every z-test in Chapter 4 quietly assumed the population standard deviation, σ, was already known. In real work, that's almost never true — only the sample standard deviation s is available, computed exactly the way Probability & Statistics Fundamentals' own Chapter 9 defined it, with Bessel's n−1 correction. That single substitution changes the math more than it might seem.
Why Estimating σ Changes the Distribution
When σ is estimated from the same limited sample as s, the resulting test statistic carries extra uncertainty on top of ordinary sampling error — and its true sampling distribution is no longer exactly normal. It follows the t-distribution instead: shaped like the normal bell curve, but with heavier tails, reflecting that extra layer of uncertainty from estimating s itself.
df = n − 1 — exactly the denominator of the sample variance formula, Probability & Statistics Fundamentals Chapter 9's own Bessel's correction, reused here as the t-distribution's own shape parameter.
df (and therefore n) grows, the t-distribution's tails thin out and it converges toward the standard normal — the extra uncertainty from estimating s matters less and less with more data, exactly the CLT's own "more data, more predictable" pattern from Chapter 8 of the sibling course, now applied to the act of estimating σ itself.
The One-Sample t-test
t = (x̄ − μ₀) / (s/√n) — identical in shape to Chapter 4's z-statistic, but built from the sample standard deviation s, and compared against a t-distribution with df = n − 1, not the standard normal.
Worked example: a team doesn't know the true σ, only their sample — n = 25, x̄ = 204ms, s = 32ms. Testing H₀: μ = 200:
| Quantity | Value |
|---|---|
| SE = s/√n | 32/5 = 6.4ms |
| t | (204−200)/6.4 = 0.625 |
| df | 25 − 1 = 24 |
| Critical value (two-tailed, α=0.05, df=24) | 2.064 |
| Decision | |0.625| < 2.064 → fail to reject H₀ |
Same conclusion as Chapter 4's own z-test on similar numbers — unsurprising, since a t-distribution with 24 degrees of freedom is already close to normal.
Comparing Two Groups: The Two-Sample t-test
Comparing two independent groups' means — exactly the shape of an A/B test — uses Welch's t-test, which doesn't assume the two groups share the same variance (a more honest default than assuming equal variances, and the version most statistical software now uses by default):
t = (x̄₁ − x̄₂) / √(s₁²/n₁ + s₂²/n₂)
df = min(n₁, n₂) − 1, which tends to slightly understate the true df and therefore errs toward being more cautious about rejecting H₀ — a reasonable simplification for this course's own scope.
Worked example: Group A (control), n₁=20, x̄₁=205ms, s₁=25ms; Group B (treatment), n₂=22, x̄₂=190ms, s₂=28ms.
| Quantity | Value |
|---|---|
| SE_diff = √(25²/20 + 28²/22) | ≈ 8.178 |
| t = (205−190)/8.178 | ≈ 1.834 |
| df = min(20,22) − 1 | 19 |
| Critical value (two-tailed, α=0.05, df=19) | 2.093 |
| Decision | |1.834| < 2.093 → fail to reject H₀ |
The t-test in Code
Hands-On Exercises
Testing H₀: μ = 50, a sample of n = 16 gives x̄ = 54, s = 10. Compute the standard error, the t-statistic, and the degrees of freedom. Using the critical value 2.131 (two-tailed, α=0.05, df=15), state the decision.
Group 1: n₁=15, x̄₁=48, s₁=6. Group 2: n₂=18, x̄₂=53, s₂=7. Compute Welch's t-statistic, the conservative degrees of freedom, and using the critical value 2.145 (two-tailed, α=0.05, df=14), state the decision.
Explain, in your own words, why the t-distribution needs heavier tails than the normal distribution when σ is unknown and estimated by s, and why a small-sample t-test's critical value (like 2.262 at df=9) is noticeably larger than the z-test's fixed 1.96. Then explain why that gap shrinks as sample size grows.
Chapter 5 Quick Reference
- When
σis unknown and estimated by samples, use the t-distribution — heavier tails than normal, reflecting the extra uncertainty from estimatingsitself - Degrees of freedom (one-sample):
df = n − 1— the exact same denominator as Chapter 9's own Bessel's correction - One-sample t:
t = (x̄ − μ₀)/(s/√n)— same shape as the z-statistic, compared against a t-distribution instead - Welch's two-sample t:
t = (x̄₁−x̄₂)/√(s₁²/n₁ + s₂²/n₂), with a conservativedf = min(n₁,n₂)−1 - The t-distribution converges to the normal distribution as
n(and therefore df) grows - A visible descriptive difference between two groups doesn't automatically mean a statistically significant one — Chapter 6's own A/B testing chapter builds directly on this
- Next chapter: A/B testing in practice
A/B Testing in Practice
Statistical Inference & Applied Statistics
Chapter 6 · A/B Testing in Practice
Chapter 5's own visible-but-not-significant response-time gap set up the exact question this chapter answers properly. Real A/B tests almost always compare a proportion — a conversion rate, a click-through rate — not a continuous mean. That needs the proportion-specific version of everything built so far.
The Two-Proportion Z-Test
Comparing two independent conversion rates uses two different standard error formulas, depending on the question:
p̂ = (x₁+x₂)/(n₁+n₂) SE_pooled = √(p̂(1−p̂)(1/n₁ + 1/n₂)) z = (p₁−p₂)/SE_pooled
SE_diff = √(p₁(1−p₁)/n₁ + p₂(1−p₂)/n₂) CI = (p₁−p₂) ± z* × SE_diff
The distinction matters: the hypothesis test assumes H₀ is true (the two groups share one real rate, so it's honest to pool them into a single best estimate for that shared rate). The confidence interval makes no such assumption — it uses each group's own separate observed rate, since it's estimating how different the two groups genuinely are, not testing whether they're the same.
n·p and n·(1−p) should be at least 5 in each group, or the approximation can break down for rare events.
Worked Example: A Conversion-Rate A/B Test
Control (A): n₁=1000, 80 conversions (p₁=8%). Treatment (B): n₂=1000, 100 conversions (p₂=10%). Validity check: 1000×0.08=80, 1000×0.92=920, both comfortably above 5 for both groups — the normal approximation is safe to use.
| Quantity | Value |
|---|---|
| p̂ (pooled) | 180/2000 = 0.09 |
| SE_pooled | ≈ 0.01280 |
| z | (0.10−0.08)/0.01280 ≈ 1.563 |
| p-value (two-tailed) | ≈ 0.118 |
| Decision at α=0.05 | 0.118 > 0.05 → fail to reject H₀ |
The 95% confidence interval for the true difference, using the unpooled SE: 0.02 ± 1.96 × 0.01279 ≈ [−0.005, 0.045] — a range spanning from a small negative effect to a fairly large positive one, consistent with the test's own failure to reach significance. The interval crossing zero and the non-significant p-value are two views of the exact same conclusion.
Sample Size Planning — Was This Test Big Enough?
Statistical power (1 − β, where β is Chapter 4's own Type II error rate) is the probability a test correctly detects a real effect of a given size, if one truly exists. Before running a test, sample size can be planned to hit a target power (conventionally 80%):
n ≈ 2(z_α/2 + z_β)² × p̄(1−p̄) / (p₁−p₂)², with z_α/2 = 1.96 (95% confidence) and z_β ≈ 0.84 (80% power) as standard published constants
For the same 8%→10% effect actually being tested above (p̄ = 0.09):
n ≈ 2(1.96+0.84)² × 0.09(0.91) / (0.02)² ≈ 3,210 per group. The actual test only had n = 1,000 per group — less than a third of what proper planning would have called for. This is almost certainly why the test failed to reach significance, even if the treatment genuinely does help: the sample was simply too small to reliably detect a real 2-percentage-point effect at this base rate, not proof that no real effect exists.
Why Smaller Effects Need Dramatically More Data
The effect size sits squared in the denominator of the sample size formula — a small change in the effect being detected has an outsized impact on the data required.
| Effect to detect | Required n per group (80% power, α=0.05) |
|---|---|
| 8% → 10% (2 percentage points) | ≈ 3,210 |
| 8% → 9% (1 percentage point) | ≈ 12,195 |
Halving the effect size to detect very nearly quadrupled the required sample size — a direct consequence of that squared denominator, and a genuinely important planning reality: reliably detecting small improvements is expensive in data, often far more than intuition suggests.
A Real Trap: Peeking at Results Early
α — related to, but distinct from, Chapter 4's own multiple-testing trap. A p-value naturally wanders up and down as data accumulates; checking it many times gives many chances for it to randomly dip below 0.05 at some point, even with zero real effect. The correct practice is to decide the sample size before the test starts (using the planning formula above) and only check the result once that predetermined size is reached.
A/B Testing in Code
Hands-On Exercises
Control: n₁=500, 60 conversions. Treatment: n₂=500, 85 conversions. First check the normal-approximation validity condition, then compute the pooled proportion, the z-statistic, and the p-value. State the decision at α=0.05.
Using this chapter's own sample size formula, compute the required sample size per group (80% power, α=0.05) to detect a change from a 5% baseline conversion rate to a 6% conversion rate (a 1-percentage-point effect).
📄 View solutionA team plans a test for a fixed 4-week sample size, but decides to check the p-value every single day and stop the test as soon as it first drops below 0.05. Using this chapter's own peeking finding, explain why this practice produces a real false-positive rate higher than the intended 5%, even if the team genuinely stops testing the instant they see a "significant" result.
📄 View solutionChapter 6 Quick Reference
- Two-proportion z-test: pooled SE for the hypothesis test (
H₀: p₁=p₂), unpooled SE for the confidence interval on the difference - Validity check:
n·p ≥ 5andn·(1−p) ≥ 5in each group before trusting the normal approximation - Statistical power (1−β) is the probability of correctly detecting a real effect — plan sample size for it before running a test
- Sample size formula:
n ≈ 2(z_α/2+z_β)²p̄(1−p̄)/(p₁−p₂)²— effect size is squared in the denominator, so halving the effect roughly quadruples the required data - A non-significant result on an underpowered test doesn't prove there's no effect — it may just mean there wasn't enough data to detect one
- Never peek and stop early — checking repeatedly and stopping at the first "significant" reading inflates the true false-positive rate well above α
- Next chapter: Correlation vs. causation
Correlation vs. Causation
Statistical Inference & Applied Statistics
Chapter 7 · Correlation vs. Causation
Every chapter so far tested a single variable, or compared two groups on one metric. This chapter asks a different question: do two different variables move together? And — the far more important half of the chapter — what an honest "yes" actually does and doesn't let you conclude.
The Pearson Correlation Coefficient
r = Σ((x−x̄)(y−ȳ)) / √(Σ(x−x̄)² × Σ(y−ȳ)²) — ranges from −1 (perfect negative linear relationship) through 0 (no linear relationship) to +1 (perfect positive linear relationship)
Worked example: CPU usage (%) and response time (ms) across six servers:
| CPU (%) | 40 | 55 | 60 | 45 | 70 | 50 |
|---|---|---|---|---|---|---|
| Response (ms) | 120 | 150 | 165 | 130 | 190 | 140 |
r ≈ 0.997 — an extremely strong positive linear relationship: as CPU usage rises, response time rises right along with it, almost perfectly linearly across this data.
The Question This Number Can't Answer
A correlation this strong is tempting to read as "high CPU usage causes slow responses." That might well be true here — but the number r = 0.997 itself doesn't establish it. Any observed correlation between two variables has four possible explanations:
| Explanation | What it would mean here |
|---|---|
| X causes Y | High CPU usage genuinely slows down response handling |
| Y causes X (reverse causation) | Slow-running requests themselves consume more CPU while they're stuck processing |
| A confounder Z causes both | A traffic surge drives both more CPU load and slower responses independently |
| Coincidence | With only 6 data points, a strong-looking correlation can arise from chance alone |
The Classic Confounding Example
A more directly engineering-relevant version: "time spent on a page" correlates positively with "conversion rate" — but this is a strong candidate for reverse causation, not X causing Y. Users who are already leaning toward converting tend to read more carefully and spend longer on the page because they're interested — the extra time is a symptom of interest, not necessarily a cause of the sale.
What Actually Establishes Causation
Correlation in Code
Hands-On Exercises
A developer logs hours of sleep and number of bugs introduced the next day across six days: sleep = [7, 5, 8, 4, 6, 7], bugs = [1, 4, 0, 6, 3, 2]. Compute the Pearson correlation coefficient, and state whether it's a strong positive, strong negative, or weak relationship.
A team observes that teams with more Slack messages per day also close more tickets per day, with a strong positive correlation. Using this chapter's own four explanations, propose one plausible story for each of "X causes Y," "Y causes X," and "a confounder Z causes both" for this specific observation.
📄 View solutionExplain, using this chapter's own finding, exactly why randomly assigning users to control and treatment groups (Chapter 6's A/B testing) rules out confounding as an explanation for an observed difference, in a way that simply observing two already-correlated variables in the wild never can.
📄 View solutionChapter 7 Quick Reference
- Pearson's r: ranges −1 to +1, measuring the strength and direction of a linear relationship between two variables
- Any correlation has four possible explanations: X causes Y, Y causes X (reverse causation), a confounder Z causes both, or coincidence
- The classic example: ice cream sales and drowning deaths correlate strongly — both driven by hot weather, neither causing the other
- "Time on page" correlating with conversion is a strong candidate for reverse causation, not X causing Y
- Only randomization (Chapter 6's A/B test) rules out confounding by construction — pure observational correlation, however strong, cannot
- Next chapter: Linear regression as statistical inference
Linear Regression as Statistical Inference
Statistical Inference & Applied Statistics
Chapter 8 · Linear Regression as Statistical Inference
Linear Algebra Fundamentals' own Chapter 6 planted a forward reference: "fitting a straight line through a set of data points is solving a system of linear equations for the best-fit slope and intercept." This chapter is where that promise is finally kept — and it builds directly on Chapter 7's own correlation work, not separately from it.
Least Squares — Fitting the Best Line
Linear regression fits a line y = mx + b that best predicts y from x. "Best" means minimizing the sum of squared vertical distances between each actual point and the line — least squares.
m = Σ((x−x̄)(y−ȳ)) / Σ((x−x̄)²) b = ȳ − m·x̄
Worked Example: Fitting a Line to Chapter 7's Own Dataset
Reusing Chapter 7's exact CPU/response-time data:
| Quantity | Value |
|---|---|
| Slope (m) | ≈ 2.343 |
| Intercept (b) | ≈ 24.21 |
| Fitted line | response ≈ 2.343 × CPU + 24.21 |
Residuals — What the Line Doesn't Capture
A residual is actual − predicted for each point — the vertical gap the line missed.
| CPU | Actual | Predicted | Residual |
|---|---|---|---|
| 40 | 120 | 117.93 | +2.07 |
| 55 | 150 | 153.07 | −3.07 |
| 60 | 165 | 164.79 | +0.21 |
| 45 | 130 | 129.64 | +0.36 |
| 70 | 190 | 188.21 | +1.79 |
| 50 | 140 | 141.36 | −1.36 |
Small, mixed-sign residuals across the board — the line fits this data closely, with no obvious pattern left unexplained.
R² — The Square of Chapter 7's Own r
R² = r² — the proportion of variance in y "explained" by the linear relationship with x.
Chapter 7 already computed r ≈ 0.997 for this exact dataset — no new calculation needed: R² ≈ 0.997² ≈ 0.994. About 99.4% of the variation in response time across these six servers is explained by CPU usage alone in this linear model, leaving only about 0.6% unexplained.
Making a Prediction
Using the fitted line for a CPU value not in the original data, CPU = 65%: response ≈ 2.343 × 65 + 24.21 ≈ 176.5ms.
CPU = 65% sits comfortably inside the observed range (40–70%), so this prediction is reasonable. Plugging in CPU = 100% gives ≈ 258.5ms — but nothing in the actual data says the relationship stays linear that far outside the observed range. A server pushed to 100% CPU might degrade far more sharply (or hit a hard ceiling) than a straight line extrapolated from 40–70% data could ever predict. Trust a fitted line only within the range of x-values it was actually built from.
R² = 0.994 is a genuinely excellent fit — and still says nothing about causation. High CPU usage causing slow responses remains only the most plausible of Chapter 7's own four explanations, not a proven one, regardless of how well the line fits.
Linear Regression in Code
Hands-On Exercises
Reusing Chapter 7's own sleep/bugs dataset (sleep = [7,5,8,4,6,7], bugs = [1,4,0,6,3,2]), fit a least-squares regression line, and use it to predict the number of bugs for 6.5 hours of sleep.
Chapter 7 computed r ≈ −0.985 for the sleep/bugs dataset. Using this chapter's own R² = r² relationship, compute R² and state, in plain terms, what percentage of the variation in bugs introduced is explained by hours of sleep in this model.
Using this chapter's own main worked example (CPU vs. response time, data ranging from 40% to 70% CPU), explain specifically why predicting response time at CPU = 5% is just as risky as the chapter's own CPU = 100% extrapolation example, even though 5% is a much smaller, seemingly more "reasonable" number.
Chapter 8 Quick Reference
- Least squares:
m = Σ((x−x̄)(y−ȳ))/Σ((x−x̄)²),b = ȳ − m·x̄— the same numerator as Chapter 7's Pearson r, repurposed to build a predictive line - This is literally Linear Algebra Fundamentals Chapter 6's own forward reference: fitting a line is solving a small system of linear equations (the normal equations)
- Residual = actual − predicted, for each point
- R² = r² — the proportion of variance in y explained by the linear relationship with x
- Extrapolation risk: a fitted line is only trustworthy within the range of x-values actually observed
- A high R² is still not proof of causation — Chapter 7's own correlation-vs-causation caution applies in full
- Next chapter: Bayesian inference and updating beliefs
Bayesian Inference & Updating Beliefs
Statistical Inference & Applied Statistics
Chapter 9 · Bayesian Inference & Updating Beliefs
Chapter 1 promised this chapter would generalize Probability & Statistics Fundamentals' own Bayes' Theorem — applied there to a single, fixed piece of evidence — into an ongoing process. Here's the whole idea in one sentence: yesterday's posterior is today's prior.
Two Genuinely Different Philosophies
Every chapter of this course except this one has quietly worked in the frequentist framework: a population parameter (a true mean, a true conversion rate) is a fixed, unknown constant, and probability describes the long-run behavior of the estimation method across repeated sampling — precisely Chapter 3's own correct interpretation of a confidence interval. The Bayesian framework treats the parameter itself as uncertain, with its own probability distribution representing genuine belief — a distribution that gets updated, piece by piece, as evidence arrives.
Building an actual numeric credible interval needs machinery beyond this course's own scope (conjugate priors, the Beta distribution for proportions) — genuinely out of scope here, per Chapter 1's own boundary. This chapter covers Bayesian reasoning, not Bayesian computation at that level.
Sequential Updating: Yesterday's Posterior, Today's Prior
Reusing Probability & Statistics Fundamentals Chapter 4's own spam-filter numbers exactly: P(spam) = 0.40, P("free"|spam) = 0.30, P("free"|not spam) = 0.05. That chapter computed the posterior once: P(spam|"free") = 0.80.
Now a second, independent signal arrives on the same email — a suspicious link, with P(link|spam) = 0.60, P(link|not spam) = 0.02. The trick: the 0.80 posterior from round one becomes the prior for round two.
| Round | Prior going in | Evidence | Posterior |
|---|---|---|---|
| 1 | 0.40 | Contains "free" | 0.80 |
| 2 | 0.80 (round 1's posterior) | Contains a suspicious link | ≈ 0.992 |
Two pieces of corroborating evidence, applied one at a time, drove belief from a 40% baseline all the way to over 99% — each round using nothing more than Fundamentals Chapter 4's own Bayes' Theorem, applied again with an updated starting point.
ml1 covers this as an actual classification algorithm; here it's the same underlying math, without the ML framing.
A/B Testing Results, Read the Bayesian Way
Some modern experimentation platforms report results as "94% probability B beats A" rather than Chapter 6's own p-value framing. That's a genuinely Bayesian statement — a direct probability about which variant is actually better — distinct from, and not directly interchangeable with, a frequentist p-value. Both are legitimate, real tools in active use; knowing which framework a specific number came from is what makes it possible to interpret it correctly.
The Honest Tradeoff: Where the Prior Comes From
Sequential Bayesian Updating in Code
Hands-On Exercises
Reusing Probability & Statistics Fundamentals Chapter 4's own fraud-detection example (P(fraud) = 0.001, P(flagged|fraud) = 0.95, P(flagged|not fraud) = 0.02, giving a posterior of P(fraud|flagged) ≈ 0.0454), a second signal now fires on the same transaction: an unusual login location, with P(location|fraud) = 0.70, P(location|not fraud) = 0.10. Using this chapter's own sequential-updating method, compute the new posterior after both pieces of evidence.
A colleague says "a 90% confidence interval and a 90% credible interval mean the same thing, just from two different calculation methods." Using this chapter's own frequentist-vs-Bayesian distinction, explain specifically what's wrong with this claim.
📄 View solutionTwo analysts investigate the same new fraud-detection signal. Analyst A, who has seen many false alarms from similar signals before, starts with a skeptical prior. Analyst B, newer to the team, starts with a more neutral prior. Given the exact same evidence, explain why they could reasonably reach different posteriors, and why this doesn't mean one of them made a mathematical error.
📄 View solutionChapter 9 Quick Reference
- Frequentist: parameters are fixed constants; probability describes the estimation method's long-run behavior (Chapter 3's own CI interpretation)
- Bayesian: parameters have their own probability distribution, representing genuine belief, updated as evidence arrives
- A 95% credible interval genuinely does mean "95% probability the true value is here" — the intuitive interpretation Chapter 3 warned doesn't apply to a frequentist CI
- Sequential updating: yesterday's posterior becomes today's prior — repeated application of Fundamentals Chapter 4's own Bayes' Theorem
- This same mechanism, applied to many signals, is the basis of a naive Bayes classifier — real ML tooling, same underlying math
- A Bayesian analysis depends on the prior chosen — a real, honest tradeoff against frequentist methods' own less intuitive interpretation, not a flaw
- Next chapter: Capstone — designing and analyzing a real experiment
Capstone — Designing and Analyzing a Real Experiment
Statistical Inference & Applied Statistics
Chapter 10 · Capstone — Designing and Analyzing a Real Experiment
One continuous worked experiment, touching every chapter of this course in the order a real analyst would actually reach for each idea: testing whether a redesigned checkout button genuinely improves conversion, from a historical baseline through a properly powered experiment to a closing Bayesian reframing.
A Full Worked Experiment — Testing a Redesigned Checkout Button
Before designing anything, the team pulls 400 historical sessions: 32 conversions, p = 8%. This is a sample of past traffic, not a guaranteed future rate — it carries genuine sampling error, and past traffic mix may not perfectly match what the actual test window will see. This number is a starting estimate, not a fact to design blindly around.
Treating 8% as a proportion estimate: SE = √(0.08×0.92/400) ≈ 0.0136. The 95% confidence interval: 0.08 ± 1.96×0.0136 ≈ [5.3%, 10.7%]. The true baseline conversion rate could honestly be anywhere in that fairly wide range — a useful, humbling number to have before committing to a test design built on the single point estimate of 8%.
H₀: p_control = p_treatment (the button color makes no real difference) against H₁: p_control ≠ p_treatment, at the standard α = 0.05. Nothing about the experiment's own numbers is examined yet — the rules are fixed first, deliberately, to avoid the peeking trap Chapter 6 warned about.
Before trusting the traffic-splitting mechanism itself, the team runs an A/A test — two groups, both shown the old button, compared on average session duration to confirm the split itself introduces no artificial bias. Group 1: n=30, mean 145s, s=40s. Group 2: n=32, mean 138s, s=38s. Welch's t-test: SE_diff ≈ 9.92, t ≈ 0.705, df = 29, critical value ≈ 2.045. |0.705| < 2.045 → fail to reject, exactly the desired outcome — the split mechanism itself shows no detectable bias, so the actual A/B test can proceed with confidence in the infrastructure.
Using Step 1's own 8% baseline and wanting to detect a lift to 10% (Chapter 6's own worked effect size), proper sample-size planning calls for ≈3,210 per group — not the smaller, underpowered pilot Chapter 6's own example ran with. This time, the team runs the test to that full planned size: control n=3,210, 257 conversions (≈8.01%); treatment n=3,210, 321 conversions (10.00%).
| Quantity | Value |
|---|---|
| Pooled p̂ | ≈ 0.0900 |
| SE_pooled | ≈ 0.00714 |
| z | ≈ 2.791 |
| p-value | ≈ 0.0053 |
0.0053 < 0.05 — this time, reject H₀. The exact same 8%→10% effect that Chapter 6's own underpowered n=1,000 pilot failed to detect (p≈0.118) becomes clearly significant once the sample size is actually planned properly. Nothing about the real effect changed — only whether there was enough data to reliably see it.
Digging into the treatment group's data, engaged sessions (more product pages viewed) also tend to run longer — r ≈ 0.998 between pages viewed and session duration across a sample. It's tempting to conclude "showing users more product pages makes them stay longer," but per Chapter 7's own caution, this observational correlation could just as easily be reverse causation: genuinely interested users naturally view more pages and stay longer, with neither driving the other. Only Step 5's own randomized comparison — not this correlation — can support a causal claim.
Fitting a least-squares line to the same pages-viewed/duration data: duration ≈ 40.77 × pages + (−24.62), with R² ≈ 0.996 — a striking fit. Predicting duration for a session viewing 7 pages: ≈ 260.8s. Since the observed data only ranged up to 6 pages viewed, this prediction is already a mild extrapolation, per Chapter 8's own caution — worth flagging honestly rather than reporting with false confidence.
Step 5's result is a frequentist one: H₀ rejected at α=0.05, a binary decision. A Bayesian analyst, starting from a skeptical prior (most small UI tweaks historically move conversion very little), would update that prior using this experiment's own strong evidence (p≈0.0053, a properly powered result) and land on a substantially higher posterior belief the button change genuinely helps — a graded probability statement rather than a reject/fail-to-reject binary. Per Chapter 9's own honest scope boundary, computing that exact posterior number needs machinery (a specified prior distribution, conjugate updating) beyond this course — but the qualitative direction is clear either way: strong, properly powered evidence moves a skeptical starting belief substantially, regardless of which framework reports the final number.
This is, in essence, exactly what a rigorous, real A/B test looks like end to end — every step traceable to a specific chapter of this course, none of it a shortcut around the planning and honesty each one demanded.
What This Course Doesn't Cover
In the interest of an honest accounting: advanced experimental design (multi-armed bandits, sequential testing), machine learning model evaluation, and full computational Bayesian methods were all named in Chapter 1 as deliberately out of scope. This course built the core inferential toolkit those more specialized areas each build on, not a substitute for them.
This Course's Throughline, Restated
Where This Course Connects
Together with its sibling course, this completes the Probability & Statistics arc within Maths for Programmers — Probability & Statistics Fundamentals built the forward-reasoning vocabulary and distributions; this course built the backward-reasoning discipline for drawing honest conclusions from real, limited data. Both connect directly to Technical Support's own diagnostic material (`perfdiag1`/`incident1`) and to Data Science & ML's own `ds1`/`ml1`, where this exact inferential toolkit gets applied at production scale.
Hands-On Exercises
A different historical baseline shows 45 conversions out of 500 sessions. Using this chapter's own Steps 1–2 technique, compute the point estimate and its 95% confidence interval.
📄 View solutionA team runs an A/A test comparing two groups both shown the same design: Group 1 n=25, mean=200, s=30; Group 2 n=28, mean=215, s=35. Using this chapter's own Step 4 technique, compute Welch's t-statistic and the conservative degrees of freedom. Using the critical value 2.064 (df=24), state whether this A/A test passes its own sanity check.
For each of the eight steps in this chapter's own worked experiment, name the specific inferential-statistics topic it relied on, without looking back at the step labels — just from the description of what each step actually does.
📄 View solutionChapter 10 Quick Reference
- Full worked experiment: a sampled baseline (Ch.2) → a confidence interval on it (Ch.3) → formal hypotheses (Ch.4) → an A/A sanity check via t-test (Ch.5) → a properly powered A/B test (Ch.6) → resisting an observational shortcut (Ch.7) → a regression follow-up (Ch.8) → a Bayesian reframing (Ch.9)
- Out of scope: advanced experimental design, ML model evaluation, and full computational Bayesian methods — each reserved for its own specialized study
- This course's throughline: a disciplined process for reasoning honestly under incomplete information, catching its own mistakes (underpowered pilots, tempting correlations) before they become false conclusions
- This course, together with Probability & Statistics Fundamentals, is the direct foundation under Technical Support's diagnostic material and Data Science & ML's own applied work
- Course complete — Statistical Inference & Applied Statistics, 10 chapters, from sampling to Bayesian updating