Contents/ Part XXXIV · Reflection & Next Steps/ Chapter 205

The Whole Pipeline: Reflection and Next Steps

Two hundred and four chapters in one place. The order the work happens in, the decision tables for every stage, the mistakes that kept recurring across forty-one capstones, and an honest account of what to learn next and in what order.

⏱️ ~45 min read
🎯 Reference, review and route map
📊 Chapter 205
What this chapter is
A review
Every stage of an analysis, in the order it happens, with the decision that has to be made at each one and where in the book it was worked through.
A reference
The tables you will actually come back for: which test, which distribution, which check, which metric, which model. Built to be scanned rather than read.
A debrief
The mistakes that recurred across forty-one capstones, collected in one place, each with the chapter where it did real damage.
A route map
What to learn next, in what order, and what to build with it.

Nothing here is new material. Everything here is a decision you now know how to make, arranged so you can find it under pressure on a Tuesday afternoon.

1

The Shape of a Project

Every project in this book, from a two-sample t-test to a reinforcement learning agent, followed the same path. The path is a loop and not a line, and the loop is the honest part: you clean, you look, you discover the grain is wrong, you go back.

THE LOOP Each box is a decision, not a task. The dashed arrows are the ones people pretend do not happen. Question what decides Collect design, sample Clean and record it Describe look, then look Check assumptions Model or test Validate on fresh data Communicate and then monitor Cleaning sends you back to collection. Describing sends you back to cleaning. Checking sends you back to the model.
The loop. The solid arrows are the plan. The dashed ones are the project, and a plan with no dashed arrows in it is a plan that has not met any data yet.

The book is organized along that loop, and it is worth seeing the whole arc at once.

Chapters 1 to 30

Foundations and data

What statistics is for, types and levels of measurement, describing, visualizing, cleaning, and exploratory analysis. The unglamorous half of every project.

Chapters 31 to 61

Probability and distributions

Probability rules, random variables, the discrete and continuous families, the Central Limit Theorem, and the distributions that inference is built on.

Chapters 62 to 91

Sampling and inference

How data gets collected and what that does to what you can conclude. Estimation, intervals, hypothesis testing, and the case studies that put them together.

Chapters 92 to 107

Association and regression

Covariance through correlation to causation, the regression workflow, diagnostics, logistic and generalized linear models, and four end-to-end regression projects.

Chapters 108 to 131

Machine learning

The workflow, supervised and unsupervised methods, evaluation, pitfalls, interpretability, reinforcement learning, and a full ML case study.

Chapters 132 to 158

Time, tools and consequences

Time series and forecasting, advanced topics from Bayesian to MLOps, the tools chapters, and then communicating results and data ethics.

Chapters 159 to 204

Forty-one capstones

Complete projects on deliberately messy data: testing, sampling, causal design, regression, machine learning, forecasting, and the specialized methods.

This chapter

The whole pipeline

All of it in one place, plus the mistakes that recurred often enough to be worth naming.

2

Before the Data: The Question

The most expensive errors in this book were not statistical. They were answering a question nobody asked, or answering a different question from the one that was asked and not noticing.

The four sentences to write before opening the file

  • The decision. What will someone do differently depending on the answer? If nothing, stop now, and say so, because that is a useful finding too.
  • The estimand. What exactly is being estimated, in one sentence, with units and a population. "Whether the new page is better" is not an estimand. "The difference in seven-day retention between arms, in percentage points, among new signups" is.
  • The threshold. How big does the effect have to be before the decision changes? This is a business question and it has to be answered before the data is seen, not after.
  • The falsifier. What result would change your mind? An analysis with no answer to this is an exercise in confirmation.
If the question isYou needWhere it was covered
What is typical, and how much does it vary?Descriptive statistics and a distributionCh 8 to 13
How confident can I be about a number?An interval, not a pointCh 71 to 75
Is this difference real or is it noise?A hypothesis test plus an effect sizeCh 76 to 84
How do these things move together?Correlation, then regressionCh 92 to 102
Did X cause Y?A design, not a modelCh 143, Ch 181 to 184
What will happen to this individual?A predictive model and honest validationCh 108 to 131
What will happen next month?A forecast with an origin and a horizonCh 132 to 141
How long until the event?Survival analysis, because of censoringCh 144, Ch 203
Who is being affected, and unequally?A fairness audit against the right yardstickCh 158, Ch 204
3

The Shape of the Data

Before any statistic, two structural questions decide what is even possible.

What is one row? That is the grain, and getting it wrong invalidates everything downstream. One row per customer, per customer-month, per order, per order-line: these are four different datasets with four different answers to the same question. A count of rows only means something once the grain is named.

What kind of variable is each column? The level of measurement decides which summaries and which tests are legitimate, and it is not the same thing as the storage type. A postal code stored as an integer is nominal, and its mean is meaningless.

LevelWhat it supportsCenterTypical test
NominalCategories with no orderModeChi-square
OrdinalOrder, but unequal gapsMedianRank-based tests
IntervalEqual gaps, arbitrary zeroMeant, ANOVA
RatioEqual gaps, true zero, so ratios mean somethingMean, geometric meant, ANOVA, log models

Alongside that sit the reshaping questions: long against wide, one table or a join, and what a join does to your row count. A join that changes the row count unexpectedly is a bug until proven otherwise, and checking counts before and after every merge catches a large share of quiet disasters. See Chapters 4 and 5 and Chapter 23.

4

Cleaning: What Actually Goes Wrong

Across forty-one capstones the same faults kept arriving. This is the catalog, built from what was actually planted and actually found.

FaultHow to find itWhat it costs if missed
Duplicate rowsduplicated() on the key, not just on the whole rowEvery count and mean is wrong, silently and slightly
Sentinel codes: -1, 999, 9999Look at min, max and the 1st and 99th percentiles of every numeric columnWorse than a blank. It is analyzed as data and nothing warns you
Text in a numeric columnCheck dtypes. An object column of numbers has a string in itThe whole column is text, and the blank count comes out wrong
Category drift: Ops and OperationsValue counts on every categorical, sorted alphabeticallyGroups split in two, and a group comparison is quietly wrong
A partial final periodCompare the last period to the same period a year earlierReads as a collapse, and it sits where the model is most sensitive
Decimal slips and unit changesRatio to the same period last year. A value 9.9 times its history is a keystrokeOne point dominates every statistic in the column
Impossible valuesRange checks against what the world allows: age 214, negative costDistorts the tail, which is often where the decision lives
Records out of orderCross-field logic: exit before hire, delivery before orderNegative durations, and a silent sign error downstream
Gaps in a time indexReindex onto a complete calendar and count what appearsAnything reaching back twelve positions instead of twelve months compares the wrong periods
A negative that is really an adjustmentAsk what a negative means in this system before deciding what to doA refund read as demand of minus eleven units
Two rules that would have caught most of these. Reconcile the row count at every step and print it. And print every repair as it is made, because a cleaning step nobody can see is a cleaning step nobody can check, including you in six months. Worked through in Chapter 18 and Chapter 19; the companion notebook below implements both as first_look and clean_report.

Outliers are a decision, not a cleaning step. A value can be wrong, or rare and real, and those need opposite treatment. The question is never "is this an outlier" but "is this a measurement error, and if not, does my method tolerate it." See Chapter 21.

5

Describing: The First Look

The first look is not a formality and it is not a table of means. It is the step that tells you which of the later steps are legitimate.

PropertyMeasuresWhen the usual choice misleads
CenterMean, median, mode, geometric meanThe mean on skewed or heavy-tailed data describes nobody
SpreadSD, variance, IQR, range, MAD, CVSD understates risk when tails are heavy; use quantiles
PositionPercentiles, quartiles, z-scoresA z-score assumes the SD is meaningful, which skew undermines
ShapeSkewness, kurtosisBoth are unstable in small samples; look at the histogram too
RelationshipCovariance, correlation, cross-tabsA single correlation hides non-linearity and subgroup reversal

Compute the summary, then plot the thing. Anscombe's quartet is the classic warning, and every capstone in this book opened with a visual first look for the same reason: the number that would have misled was visible in the picture. Chapters 8 to 13.

Simpson's paradox is a first-look problem. An aggregate relationship can reverse inside every subgroup, so a comparison that has not been broken down by the obvious confounder is not finished. It cost a conclusion in Chapter 186 and it is the reason Chapter 94 exists.
6

Visualizing: Choosing the Picture

What you are showingReach forAvoid
One numeric distributionHistogram, density, box, violinA bar of the mean, which hides everything
Numeric by a few categoriesBox or violin side by side, strip plot if n is smallBar plus error bar, which hides the shape
Two numericsScatter, with a smootherA correlation quoted without the plot
Category countsHorizontal bars, sorted by valuePie charts beyond three slices
Part to whole over timeStacked area, or small multiplesStacked bars when the reader needs the middle series
Change over timeLine, with the origin marked if it is a forecastTruncated y axes on a line that implies a trend
Many variables at onceSmall multiples, pair plot, parallel coordinatesA single chart with five encodings
UncertaintyBands, fans, interval dotsA point estimate on its own
A model's errorsResidual plots, calibration curvesReporting only the headline metric

The default chart is the one that shows every observation. Summarize only when the count makes that impossible, and then say what was summarized. Chapter 17 is the decision tree, and Chapter 157 is what changes when the audience is not you.

7

Distributions: The Catalog

A distribution is a claim about the process that generated the data. Choosing one is choosing a story about mechanism, which is why the middle column matters more than the name.

DistributionArises whenTypical use
BernoulliOne trial, two outcomesA single click, a single conversion
Binomialn independent trials, constant probabilityDefects per batch, conversions per cohort
PoissonEvents in continuous time at a constant rateArrivals, faults, claims per period
Negative binomialCounts with more spread than Poisson allowsOverdispersed counts, which is most real count data
GeometricTrials until the first successAttempts before conversion
HypergeometricSampling without replacement from a finite poolQuality inspection of a shipment
NormalMany small independent additive effectsMeasurement error, and sample means via the CLT
Log-normalMany small independent multiplicative effectsIncome, cost, session length, price
ExponentialWaiting time at a constant hazardTime between arrivals, memoryless lifetimes
Gamma / WeibullWaiting time with a changing hazardLifetimes, failure and survival times
BetaA proportion constrained to zero and oneRates, and Bayesian priors on probabilities
UniformEqual density across a rangeSimulation, and p-values under the null
Student's tA mean standardized by an estimated SDInference on means with unknown variance
Chi-squareSum of squared standard normalsVariance inference, goodness of fit, independence
FRatio of two scaled chi-squaresANOVA and comparing nested models
The Central Limit Theorem is why the normal distribution keeps appearing where the data is not normal. It is a statement about the distribution of the sample mean, not about the data. That distinction resolves most confusion about when normality matters: a test about a mean usually inherits normality from the CLT even when the raw data is heavily skewed, while a prediction interval for an individual observation does not. Chapter 41, and Chapter 42 for the three test distributions.

Two practical habits. When data is positive and right-skewed, try a log scale before trying a more complicated model, because multiplicative processes are extremely common and a log turns them into additive ones. And when counts are overdispersed, move from Poisson to negative binomial rather than pretending the variance assumption held, which is what Chapter 189 was about.

8

Checking the Data Before Testing It

Every method rests on assumptions, and the assumptions are testable. What follows is the battery, what failure looks like, and what to do about it, which is almost never "abandon the analysis."

AssumptionHow to checkIf it fails
NormalityQ-Q plot first; Shapiro-Wilk or D'Agostino as supportWith n above about 30, tests about means are usually fine anyway. Otherwise transform, or use a rank-based test
Equal variancesLevene's test, and residuals against fittedUse Welch's t or Welch's ANOVA, which cost almost nothing and assume less
Homoscedasticity in regressionBreusch-Pagan, scale-location plotRobust standard errors. The coefficients are fine; the standard errors were not
LinearityResiduals against fitted, partial residual plots, RESETAdd a term, transform a variable, or use a spline. Fix this before the other checks
IndependenceDurbin-Watson, ACF, and knowing how the data was collectedCluster-robust errors, mixed models, or a time series method
MulticollinearityVIF, correlation matrix, condition numberIt harms interpretation, not prediction. Drop, combine, or regularize
InfluenceCook's distance, leverage, DFBETAInvestigate the point. Refit without it and report both if it matters
Expected countsThe smallest expected cell in a chi-square tableBelow 5, use Fisher's exact test
Proportional hazardsSchoenfeld residuals against timeSplit follow-up, stratify, or fit a time-varying coefficient
Missingness mechanismCompare observed variables across missing and presentMAR is untestable. Use multiple imputation and a sensitivity analysis
The four regression checks are a sequence, not a checklist. A missing curve shows up as non-linearity, as non-constant variance and as non-normal residuals all at once, so fixing the linearity first and re-running is the difference between one repair and three wrong ones. Chapter 98 sets out the order; Chapter 187 is a case where each failure hid the next.

And a warning about normality tests specifically. With a large sample they reject departures too small to care about; with a small one they miss departures that matter. They answer "is this exactly normal," which is never the question. The Q-Q plot answers "is this normal enough for what I am about to do," which is.

9

Sampling and Study Design

Everything downstream inherits whatever the collection did. No model repairs a sample that never contained the people the conclusion is about.

SchemeHow it worksWhat it buys, and costs
Simple randomEvery unit equally likelyThe baseline. Often impractical and rarely the most efficient
StratifiedSplit into strata, sample within eachMore precision for the same n when strata differ. Needs weights on the way out
ClusterSample groups, measure everyone insideMuch cheaper, and less precise than n suggests. Correct with the design effect
SystematicEvery k-th unit from a listEasy, and dangerous if the list has a period matching k
MultistageClusters, then units within themHow most large surveys actually run. Variance is not textbook
Convenience / opt-inWhoever respondsCheapest, and the selection is unknowable. Weighting helps and does not fix it
The design effect is the number people forget. A clustered sample of 1,000 can carry the precision of 300 independent observations, and treating it as 1,000 produces confidence intervals that are far too narrow. Anything collected in groups, by school, store, household or region, needs this. Chapter 63, and Chapter 178 where the correction changed the conclusion.

Then the design hierarchy, which decides what kind of claim is available at the end.

DesignWhat it supportsThe main threat
Randomized experimentCausal claims about the average effectNon-compliance, attrition, and peeking at the results
Regression discontinuityCausal, local to the cutoffManipulation of the running variable
Instrumental variablesCausal, for the compliersWeak or invalid instruments, which are hard to detect
Difference in differencesCausal under parallel trendsParallel trends is an assumption, not a finding
Matching / propensityCausal only if all confounders are observedThe confounder you did not measure
Plain observational regressionAssociation, adjustedEverything above, plus collider bias from bad controls

Sample size is a decision made before collection, not a justification made after. Power depends on the effect size you would not want to miss, the variability, the significance level and the power you want. Running the calculation after a null result to explain it is a well-known way to say nothing. Chapter 65, and Chapter 181 for what sequential peeking does to the error rate.

10

Estimation and Uncertainty

A point estimate without an interval is an opinion with decimal places.

IntervalAnswersWidth driven by
Confidence intervalWhere the population parameter plausibly sitsStandard error, which shrinks with the square root of n
Prediction intervalWhere the next individual observation will fallStandard error plus the residual spread. Always much wider
Tolerance intervalWhere a stated proportion of the population sitsBoth, plus the coverage you demand
Credible intervalWhere the parameter is, given prior and dataThe posterior, and therefore the prior as well
Bootstrap intervalAny of the above, without a formulaResampling variability, and the assumption that your sample resembles the population

Confusing the first two is one of the most common errors in applied work. A 95 percent confidence interval for a mean says nothing about where an individual will land, and quoting it to someone who needs to plan for individuals will systematically understate their risk.

An interval is a claim about frequency, and it is cheap to check. A nominal 95 percent interval should contain the truth 95 percent of the time, and when that was measured in this book it often did not: 67.9 percent for a forecasting band in Chapter 201, and 2.7 percent for a widely used imputation method in Chapter 202. Coverage is the property that matters and almost nobody measures it.

The bootstrap is the general-purpose escape hatch. When the formula does not exist, the assumptions do not hold, or the statistic is something odd like a ratio of medians, resample and look at the spread. Chapter 75.

11

Hypothesis Testing: Which Test, and When

The test follows from four things: what kind of outcome, how many groups, whether observations are paired, and whether the distributional assumptions hold.

CHOOSING A TEST Start from the outcome. Nonparametric alternatives in the right-hand column apply when n is small and the shape is wrong. What outcome? Numeric Categorical Two numerics 1 group 2 groups 3+ groups 2 proportions r x c table association one-sample t Welch's t (paired t if paired) one-way ANOVA, then Tukey HSD two-proportion z chi-square (Fisher if any expected < 5) Pearson r Wilcoxon signed-rank Mann-Whitney U Kruskal-Wallis exact binomial Fisher's exact Spearman or Kendall IF ASSUMPTIONS FAIL DEFAULT Every branch ends with the same instruction: report an effect size and an interval, not only a p-value.
The decision tree. The left column is the default and the right column is what to use when the sample is small and the distributional assumption is genuinely violated. With a reasonable sample size, the defaults are more robust than their reputation suggests.
SituationTestEffect size to report with it
One mean against a valueOne-sample tCohen's d, and the raw difference
Two independent meansWelch's tCohen's d, difference with CI
Two paired measurementsPaired t on the differencesMean difference with CI
Three or more meansOne-way ANOVA, then TukeyEta-squared or omega-squared
Two factors at onceTwo-way ANOVAPartial eta-squared per effect and interaction
Repeated measures on the same unitsRepeated-measures ANOVA or a mixed modelEffect size plus the within-unit correlation
Two proportionsTwo-proportion z, or chi-squareRisk difference, relative risk, odds ratio
Independence in a tableChi-square, Fisher if sparseCramer's V
Two variancesLevene's testRatio of variances
Linear associationPearson rr and r-squared with CI
Monotone association, or outliers presentSpearman rho, Kendall tauThe coefficient itself
Ordinal outcome across groupsMann-Whitney or Kruskal-WallisRank-biserial correlation, epsilon-squared
Time to an eventLog-rank, then CoxHazard ratio with CI

Discipline that applies to every test on that list

  • State the hypothesis before seeing the data. A hypothesis formed after looking at the result is a description, and its p-value means nothing.
  • A p-value is not the probability the hypothesis is true, and it is not an effect size. It is the probability of data at least this extreme if the null were true, and with enough n everything is significant.
  • Report the effect size and its interval. If the interval spans values that would lead to different decisions, the honest conclusion is that the study did not settle it.
  • Correct for multiplicity when you run many tests: Bonferroni when there are few and they matter, Benjamini-Hochberg when there are many and you can tolerate some false discoveries. Chapter 163 shows what happens without it.
  • Not significant does not mean no effect. It means this study could not distinguish the effect from zero, which is a statement about the study as much as about the world.
12

Association and Regression

Correlation asks whether two things move together. Regression asks by how much, holding other things fixed, and that phrase is where all the difficulty lives.

OutcomeModelWhat the coefficient means
Continuous, roughly symmetricLinear regression (OLS)Change in y per unit of x
Continuous, positive and skewedLog-linear, or a gamma GLMApproximate percentage change in y
BinaryLogistic regressionLog-odds; exponentiate for an odds ratio
CountPoisson, or negative binomial if overdispersedLog rate; exponentiate for a rate ratio
Count with varying exposurePoisson with an offsetThe offset decides whether you model counts or rates
Proportion or rate bounded 0 to 1Beta regression, or binomial GLMEffect on the transformed scale
Ordered categoriesOrdinal logisticProportional odds across thresholds
Time to event with censoringCox proportional hazardsMultiplier on the hazard rate
Many correlated predictorsRidge, lasso, elastic netShrunk, and biased on purpose for stability
Grouped or repeated observationsMixed model, or cluster-robust errorsFixed effects plus explicit group variation
The hardest decision in regression is which variables to include, and it is not statistical. Controlling for a mediator removes the effect you were trying to measure. Controlling for a collider creates an association that does not exist. Neither shows up as a bad fit statistic, and no automated selection procedure can distinguish them, because the distinction lives in the causal structure rather than the data. Chapter 186 is a case where one extra control deleted the finding; Chapter 143 is the framework.

R-squared is not a measure of correctness. It measures variance explained in the sample, it never decreases when you add a variable, and a high value on a misspecified model is common. Adjusted R-squared, AIC and out-of-sample error are all better, and the residual plots are better than any of them. Chapters 95 to 102.

13

Machine Learning

The methods change; the discipline does not. Almost every machine learning failure in this book was a validation failure rather than a modeling one.

TaskStart withThen tryJudge on
Binary classificationLogistic regressionGradient boosting, random forestPR AUC and calibration, not accuracy
Multi-classMultinomial logisticBoosting, neural nets if the data is largeMacro F1, per-class confusion
RegressionLinear, then regularizedGradient boostingMAE or RMSE, and residual plots
RankingLogistic scoresLearning to rankNDCG, precision at k
Clusteringk-means with scaled featuresHierarchical, DBSCAN, GMMSilhouette, stability, and whether the clusters mean anything
Dimensionality reductionPCAUMAP or t-SNE for visualization onlyVariance retained, and downstream performance
Anomaly detectionRobust z-scores, IQR rulesIsolation forest, autoencodersPrecision at the alert volume you can action
RecommendationPopularity baselineMatrix factorization, hybridsRanking metrics, coverage, and cold start
TextTF-IDF plus linearTransformers, fine-tuningTask metric, and a held-out set of real examples

The rules that mattered more than the algorithm

  • Split before you touch anything. Scaling, imputation and encoding all learn from the data and all leak if they are fitted before the split. Fit inside the pipeline, inside the fold.
  • Beat a baseline that costs nothing. The majority class, the previous value, the overall mean. If the model cannot beat it, the model is not the finding.
  • Accuracy on imbalanced data is a trap. At a 3 percent base rate, predicting "no" scores 97 percent. Read the base rate first, then PR AUC.
  • Calibration is a separate property from ranking. A model with excellent AUC can produce probabilities that mean nothing, which matters the moment a threshold or a cost is attached (Chapter 188).
  • Tuning on the test set spends it. Data used to choose can no longer measure. Use nested validation, or seal a set and open it once.
  • Explain the model before deploying it with SHAP or permutation importance, and treat a feature that is suspiciously predictive as a leak until proven otherwise (Chapter 117).
The most consequential ML decision is what you ask the model to predict. A perfectly accurate, perfectly calibrated, thoroughly validated model that predicts the wrong quantity is a well-built machine for doing the wrong thing, and no amount of model validation detects it because every check is run against that same label. Chapter 204 is the worked case.
14

Time Series

Time changes three things: the observations are not independent, the order is information, and validation has to respect the arrow of time.

SituationMethodNote
A baseline to beatNaive, seasonal naive, driftHarder to beat than expected. Keep them in the comparison permanently
Trend and seasonality, no exogenous driversExponential smoothing (ETS)Fast, robust, and often the winner
Autocorrelation structure mattersARIMA, SARIMADifference to stationarity first, and check with ADF or KPSS
Multiple related seriesVAR, or hierarchical reconciliationForecasts that must add up need reconciling
Volatility is the quantity of interestARCH, GARCHThe mean model and the variance model are separate
Mostly zerosCroston, SBA, or a quantile targetPercentage errors are undefined; the metric's optimum may be zero
Many series, shared patternsGlobal models, gradient boosting on lagsRequires careful feature construction to avoid leakage

The four rules that apply whatever the model is

  • Never shuffle. Random k-fold on a time series trains on the future and reports an accuracy nobody will ever see again.
  • Respect the origin. Every forecast must use only what was genuinely available at the moment it is made, including any feature that was revised later.
  • Score at the horizon the decision needs. A one-step-ahead error is irrelevant to a twelve-month plan.
  • Use many origins. One holdout is one draw, and the spread across origins is usually more informative than the average (Chapter 201).

And check that the interval covers. Forecast uncertainty usually grows with the horizon, so a band of constant width is over-confident about the far end. Measuring empirical coverage per horizon takes a few lines and is almost never done.

15

Specialized Situations and Their Tells

Some problems look like ordinary ones and are not. Recognizing the tell is most of the work.

The tellWhat it actually isThe right tool
Rows with gaps, and dropping them loses half the dataA missing-data problem with a mechanismMultiple imputation, plus sensitivity if the mechanism may be MNAR (Ch 202)
The event has not happened yet for most unitsCensoring, which is not missingnessKaplan-Meier and Cox (Ch 203)
Two events compete for the same unitCompeting risksCause-specific hazards or Fine and Gray
Observations arrive in groupsClustering, so the effective sample is smallerMixed models, cluster-robust errors, design effects
The outcome is a proxy for what you care aboutLabel biasAudit against the target quantity, not the label (Ch 204)
Treatment was not assigned at randomConfoundingA design: RDD, IV, difference in differences, matching
You have real prior informationA Bayesian problemPriors, posteriors, credible intervals (Ch 142)
Constructs measured by several imperfect itemsLatent variablesFactor analysis, SEM (Ch 145)
Positives are 0.1 percent of the dataExtreme imbalancePR curves, resampling, cost-sensitive thresholds, anomaly methods
The data does not fit in memoryAn engineering problem before a statistical oneSampling, chunking, columnar formats, distributed compute (Ch 149)
16

Communicating, Shipping and Watching

An analysis nobody acts on and a model nobody monitors are the same failure at different points in the pipeline.

Writing the result

  • Lead with the decision, not the method. The first sentence should be what to do and why, and the method belongs where the people who need it will look for it.
  • Put the uncertainty in the headline. A range in the summary and a point estimate in the appendix is the wrong way round.
  • Write the falsifier down. What would change this conclusion is the most useful paragraph in any report and the one most often missing.
  • Two documents, not one. A plain-language brief for the decision and a technical report for the method. Every capstone in this book shipped both, because they have different readers and merging them serves neither.

Making it survive

  • Version control everything, including the analysis. A result that cannot be regenerated is an anecdote (Chapter 156).
  • Pin the environment. A notebook that ran last year and does not run today is a dependency problem, and it is usually discovered at the worst moment.
  • Separate the pipeline from the exploration. Notebooks are for thinking; modules and scripts are for anything that runs twice.
  • Monitor the inputs, not just the outputs. Data drift arrives before performance drops, and by the time the metric moves the damage is done (Chapter 150).
  • Keep the free baseline running in production. The day the maintained model stops beating it is the day something broke, and that is the cheapest alarm you will ever build.
17

The Mistakes That Kept Recurring

Across forty-one capstones the same handful of errors did nearly all the damage. They are worth naming because none of them are exotic, and every one produced a confident, plausible, wrong answer.

1. Using data twice. Once to choose and once to judge. A model selected from thirty-two candidates on one holdout reported 3.34 percent error and delivered 5.57. The overstatement grows with the size of the search and nothing in the output reveals it. Chapter 201
2. Conditioning on the outcome. Averaging the tenure of people who left, analyzing only completed cases, restricting to the subset where the event happened. It always shortens, always flatters, and always looks like a reasonable filter. Chapter 203, Chapter 202
3. Filling a gap with a prediction and analyzing it as a measurement. The most reasonable-looking fix in the whole book, and the worst: its confidence interval contained the right answer three times in 150 while being the narrowest of any method. Chapter 202
4. Averaging over a reversal. A single hazard ratio of 1.08 that was a 0.49 and a 2.02 stacked together. Any one-number summary of an effect that changes sign will report approximately nothing, and the assumption test that catches it takes one line. Chapter 203
5. Trusting a metric that cannot be computed. A percentage error is undefined when the actual is zero, and the tool drops those rows without saying so. Three weeks in five, in that case. Chapter 200
6. Optimizing a metric whose optimum is absurd. Absolute error is minimized at the median, and when the median is zero the best-scoring forecast is one that never orders anything. When the winning entry is a policy nobody would run, the scoreboard is wrong rather than the entrants. Chapter 200
7. Auditing against the thing that is wrong. Every fairness check on a care-management model came back clean because they all compared predictions to cost, and cost was the biased quantity. Chapter 204
8. Analyzing a sentinel as data. A -1, a 999, a 9999. Twenty-one points of a survey were missing in disguise, and unlike a blank they average, regress and report without complaint. Chapter 202
9. Controlling for the wrong variable. A mediator removes the effect you were measuring; a collider manufactures one that does not exist. Neither appears as a bad fit statistic and no automated procedure can tell them apart. Chapter 186
10. Comparing groups with different amounts of follow-up. A department created eighteen months ago ranked worst on mean tenure and best on retention. Any duration statistic partly measures how long the group has existed. Chapter 203
11. Ignoring the design. A clustered sample of a thousand can carry the precision of three hundred. Treating it as a thousand produces intervals that are far too narrow and a conclusion that is far too confident. Chapter 178
12. Believing an interval without measuring it. Nominal 95 percent bands that delivered 67.9 percent, and 2.7 percent. Coverage is a claim about frequency, it is cheap to check, and almost nobody checks it. Chapter 201

Reading those twelve together, only two are about choosing the wrong method. The rest are about measuring the wrong thing, measuring it on the wrong data, or believing a number that was never checked. That ratio has been the most useful thing in the book to know.

18

What This Book Did Not Cover

Being explicit about the edges is more useful than a summary that implies completeness.

Mathematical depth. The advanced part covers moments, MGFs and conditional expectation, but this is an applied book. Proofs of the theorems being used, measure-theoretic probability and the asymptotic theory behind the estimators are all somewhere else, and eventually worth going to.

Experimental design as a discipline. Factorial designs appear once. Response surface methods, optimal design, blocking beyond the basics and sequential designs are a field of their own.

Deep learning in earnest. There is a primer and an application chapter. Training modern architectures, distributed training, and the practical craft of it are a different book.

Data engineering. Pipelines, orchestration, streaming, warehouse modeling and cost control decide whether analysis is possible at all, and they get one chapter here.

Domain knowledge. The largest gap by far. Every method in this book is worth less than knowing what a plausible value looks like in your field, and that cannot be transferred by a textbook.

19

Where to Go From Here

Four routes. They are not exclusive and most careers are a mixture, but the first choice worth making is which one you are deliberately deepening this year.

Route 1

The applied statistician

Design, causal inference, mixed and hierarchical models, Bayesian methods. Learn R properly. Read Gelman and Hill. Go deeper into Chapter 143 and the design capstones.

Route 2

The machine learning engineer

Software engineering first, then deep learning and MLOps. Serving, monitoring, feature stores, testing. The gap for most analysts is engineering, not modeling.

Route 3

The analytics leader

Experimentation platforms, metric design, decision frameworks, and communication. The scarce skill is turning an ambiguous business question into an estimand.

Route 4

The researcher

Mathematical statistics, the literature in a specific area, and writing. Reproducibility and pre-registration matter more here than anywhere else.

The next five things to learn, in a defensible order

  • 1. SQL, to a level you would not describe as basic. Window functions, CTEs, query plans. More analysis time is spent getting data than analyzing it, and this is the largest single multiplier on your speed (Chapter 154).
  • 2. Causal inference, properly. DAGs, potential outcomes, and the identification strategies. It is the difference between describing and explaining, and most business questions are causal whether or not anyone says so.
  • 3. Software engineering habits. Version control, tests, packaging, code review. Not to become an engineer, but because analysis that cannot be rerun is analysis that has to be redone.
  • 4. Bayesian methods. Not as an ideology but as a second toolkit, particularly for small samples, hierarchical structure and genuine prior information.
  • 5. One domain, deeply. Finance, health, marketing, operations, policy. Generic skill plus domain knowledge beats more generic skill, and it compounds.

How to practice, in descending order of value

  • Analyze data you care about and nobody has cleaned. Your own spending, your team's tickets, a public dataset on something you follow. The mess is the education, and the caring is what makes you check the answer.
  • Redo an analysis someone published and try to break it. Reproducing a result and testing its sensitivity teaches more than a new tutorial, and it builds exactly the reflex this book has been arguing for.
  • Write it up for a reader who will push back. Nothing exposes a weak analysis faster than having to defend it in writing to someone with a stake in the answer.
  • Compete, but read the winners. Kaggle teaches modeling and validation and teaches nothing about problem definition or data collection. The write-ups are worth more than the leaderboard.
  • Teach one thing. A blog post, an internal talk, a colleague. The chapters in this book that were hardest to write are the ones I understood least well going in, which is the general case.

A ninety-day plan, if you want one

  • Weeks 1 to 2. Take the toolkit notebook below, put it in a repository of your own, and use it on a dataset from your work. Fix what does not fit your data.
  • Weeks 3 to 6. Run one complete project end to end on messy data you sourced yourself: question, collection, cleaning, analysis, validation, and both write-ups. Not a tutorial dataset.
  • Weeks 7 to 10. Pick the largest gap from the five above and work only on it. Deliberate practice on one weakness beats broad review.
  • Weeks 11 to 12. Go back to a piece of work you did before reading this book and audit it. Find what you would now do differently and write that down. That document is the most honest measure of what changed.
Where to read next

For statistics: Gelman and Hill on regression and hierarchical models, Gelman et al. on Bayesian data analysis, and Efron and Hastie for how the modern methods relate to the classical ones. For causal work: Pearl's Book of Why to build the intuition, then Hernan and Robins for rigor, with Angrist and Pischke for the econometric tradition. For machine learning: Hastie, Tibshirani and Friedman remains the reference, with Murphy for the probabilistic view. For forecasting, Hyndman and Athanasopoulos is free online and excellent. For communication, Tufte and Cairo. And for the habits rather than the mathematics, Vanderplas on Python and Wickham on R and tidy data.

A note on staying current. The methods in the first two thirds of this book have been stable for decades and will outlast anything you learn this year about a specific library. The tooling changes constantly and matters less than it appears to. Spend your attention accordingly: read papers and textbooks for the ideas, and documentation for the tools, and do not confuse the two.

20

The One Thing

If a single habit had to survive from two hundred and four chapters, it is this: check the thing you are about to believe.

Not the assumption you were taught to check, though those matter. The number itself. Does the interval cover at the rate it claims? Was this data used to choose the thing it is now judging? Is this metric computable on the data it is being computed on? Would this conclusion survive the one obvious objection?

Almost every failure collected in this book would have been caught by someone spending twenty minutes trying to break their own result before presenting it. That is not a statistical technique. It is a habit, and it is the one worth keeping.

What the book was for

  1. Chapters 1 to 30 were about the data itself: what kind of thing it is, what it looks like, and what is wrong with it. Most projects fail here.
  2. Chapters 31 to 91 were about uncertainty: where it comes from, how to quantify it, and what can honestly be concluded from a sample.
  3. Chapters 92 to 141 were about relationships and prediction: regression, machine learning, forecasting, and the validation each of them needs.
  4. Chapters 142 to 158 were about the harder cases and the consequences: advanced methods, the tools, communication and ethics.
  5. Chapters 159 to 204 were forty-one complete projects on deliberately broken data, because knowing the method and finishing the project are different skills.

Every capstone here planted its faults on purpose and then found them, which is a luxury real work does not offer. The point of doing it forty-one times was never the individual answers. It was to make finding them automatic.

🐍

The analyst's toolkit, to keep

The companion notebook is not a worked example. It is nine reusable functions that do the things every project needs doing: first_look for the ten minutes before anything else, clean_report so every repair is printed, describe_plus which warns when the mean is not a fair summary, check_distribution and check_model for the assumption batteries, choose_test which prints its reasoning, evaluate_classifier including calibration and group disparity, rolling_backtest for forecasts, and a project checklist. Written plainly, with no classes and no configuration, so they can be lifted straight into a module of your own.

📓 View Notebook (code & outputs) ▶ Open in Colab ⬇ View / Download on GitHub
Where everything else lives

This chapter links out to the rest of the book rather than shipping a dataset of its own. The full contents lists all 205 chapters, and every capstone from Chapter 159 onward ships its own messy dataset, notebook, plain-language brief and technical report. Those datasets are the best practice material here, because the faults in them are known and findable.

🎓 Key Takeaways

  • The pipeline is a loop, not a line. Cleaning sends you back to collection, describing sends you back to cleaning, and a plan with no backward arrows in it has not met any data yet.
  • The question comes before the data. A decision, an estimand with units, a threshold that matters, and a result that would change your mind. Written down before the file is opened.
  • Method follows from four properties. The type of outcome, the number of groups, whether observations are paired, and whether the assumptions hold. Every test table in this chapter is that same decision in a different domain.
  • Assumptions are checkable and failures are signposts. Non-constant variance means use robust errors, not abandon the model. Fix linearity first, because one missing curve shows up as three separate failures.
  • Of the twelve recurring mistakes, only two were choosing the wrong method. The rest were measuring the wrong thing, measuring it on the wrong data, or believing a number nobody checked.
  • Coverage is the property almost nobody measures. Nominal 95 percent intervals in this book delivered 67.9 percent and 2.7 percent, and both were found with a few lines of code.
  • Next: SQL properly, causal inference properly, engineering habits, Bayesian methods, and one domain deeply. In that order, and the last one compounds fastest.

Quiz: Test Yourself