← Big Ideas of Data Analysis & Modeling
An interactive field guide

The big ideas of data analysis and modeling

A model is a simplified story that fits the data you have and is meant to be right about data you haven't seen. Getting from one to the other takes habits more than formulas: look first, know how your data got to you, and check the model against something it hasn't memorized. Here are twelve ideas, each with an experiment you can run in your browser.

Anscombe's quartet. Four very different data sets, one identical set of summary statistics.
Part I

Look before you model

Most failed analyses went wrong before any model was fitted. Four habits catch the usual trouble: draw the data, distrust the average, ask why values are missing, and ask how well the inputs were measured.

01

Plot it first

Summary numbers throw information away. Different data can give identical means, spreads, correlations and fitted lines, and only a picture shows which one you have.

In 1973 the statistician Francis Anscombe published four small data sets of eleven points each. All four have the same mean of x (9), the same mean of y (7.5), the same correlation (0.82) and the same fitted regression line, y = 3 + 0.5x. A regression table for them is identical, line by line.

Plotted, the first is a plain noisy line. The second is a smooth curve, so a straight line is the wrong model. The third is a perfect line with one outlier that tilts the fit. The fourth has a single point at x = 19 that alone creates the whole slope. Each needs a different response: leave it, fit a curve, check the outlier, or admit you have one data point.

r = 0.816,   ŷ = 3.00 + 0.50 x,   R² = 0.67 The same for all four of Anscombe's data sets

History

Anscombe complained in 1973 that textbooks and statistical programs paid too little attention to graphs, and that many people were taught that numerical calculations are exact but graphs are rough. His quartet was the rebuttal. In 2017 Matejka and Fitzmaurice used simulated annealing to build a "Datasaurus Dozen": thirteen data sets, including a dinosaur and a star, that share the same summary statistics to two decimal places.

Watch out

Drawing one scatter plot is not enough once you have many variables. Plot each variable alone, each pair, and the residuals after fitting. Do it before you model and again after.

Try it · Anscombe's quartet
Mean x Mean y Correlation Fit
02

Robust summaries

The mean and standard deviation can be moved arbitrarily far by a single value. The median and the median absolute deviation can't, which is why they're called robust.

The breakdown point of a statistic is the fraction of the data you'd have to corrupt to push it to any value you like. For the mean it is 1 in n: change one number and the average follows. For the median it is nearly one half: you must corrupt half the sample before it can be dragged away.

Robust doesn't mean the outlier is wrong. It may be a typo, a sensor glitch or a data-entry unit error, or it may be the most important observation you have. A robust summary tells you what the bulk looks like, and the gap between robust and ordinary summaries tells you how much one or two values are doing.

MAD = median(|xi − median(x)|)    σ̂ ≈ 1.48 × MAD The median absolute deviation, scaled to match the standard deviation for normal data

Watch out

Dropping outliers because they're inconvenient is not robust statistics. Decide the rule before you see the effect on your result, and report both versions.

Try it · Move the biggest value
Observations Mean Median
The other observations never change. Slide the largest value up and watch the mean and standard deviation run away while the median and MAD stay put.
03

Missing data

What matters is the mechanism, not the amount. If values go missing at random the loss is only precision. If missingness depends on the value itself, no amount of data fixes the bias.

Donald Rubin's taxonomy has three cases. Missing completely at random (MCAR): a coin decided who skipped the question. Throwing away incomplete rows loses information but not accuracy. Missing at random (MAR): missingness depends on something you observed, such as age. You can correct for it by modeling on the observed variable. Missing not at random (MNAR): missingness depends on the unseen value itself, as when high earners decline to state their income. The data alone can't tell you this has happened.

The lab below has a survey where income rises with age. Because no mechanism is visible in the data you keep, you have to argue from how the data were collected.

History

Rubin's 1976 paper "Inference and missing data" introduced the MCAR/MAR/MNAR language. In the 1940s, Abraham Wald applied the same logic to aircraft armor. Bombers returning from missions showed bullet holes in the wings and tail, and the military wanted to add armor there. Wald pointed out that the planes that never returned were the ones hit elsewhere, so the armor belonged where the survivors had no holes.

Watch out

Filling a gap with the column mean never adds information. It shrinks the variance and weakens every correlation involving that column.

Try it · A survey with nonresponse
Responded Didn't respond
True mean income Mean of respondents Error Adjusted for age
04

Measurement error

Noise in the predictor doesn't average out. It flattens the fitted slope toward zero, so real effects look smaller than they are.

Ordinary regression assumes the x values are exact and puts all the noise in y. When x is measured with error, the fitted slope is multiplied by the reliability ratio: the share of the variance in the observed x that is signal rather than noise. Half the variance is noise, and you recover half the slope. This is called regression dilution or attenuation.

bobserved = β × Var(x)Var(x) + Var(e) Slope shrinks by the reliability ratio

Noise in y only widens the scatter. Noise in x biases the result, and a bigger sample makes you more sure of the wrong slope. The same thing happens to controls: if you adjust for a confounder you measured badly, you only partly remove its effect.

Watch out

Attenuation makes a "no effect" finding less convincing. A noisy blood-pressure reading or a self-reported diet questionnaire can hide a real relationship.

Try it · Add noise to the predictor
Observations True relationship Fitted line
True slope 2.00 Fitted slope Reliability
Part II

Fit a model

Fitting a line is the oldest modeling tool and still the one that most others are built on. Two ideas make it useful: define "best" with a loss function, and inspect what the fit leaves behind.

05

Least squares & residuals

The best-fitting line minimizes the sum of squared vertical misses. What's left over, the residuals, is where you find out what the model got wrong.

Legendre published the method of least squares in 1805 and Gauss claimed to have used it since 1795, while predicting the orbit of the asteroid Ceres. The recipe is to choose the intercept a and slope b that make the sum of squared residuals as small as possible. Squaring makes big misses count more, and it makes the answer a closed-form formula.

b = Σ(xi − x̄)(yi − ȳ)Σ(xi − x̄)²,   a = ȳ − b x̄ The least-squares slope and intercept

A good fit leaves residuals that look like shapeless noise around zero. If the residuals bend, you've used a straight line on a curve. If they fan out, the noise grows with the size of x. If one point sits far from the rest, it may be steering the line. The residual plot is the most valuable diagnostic in regression because it shows what the model didn't explain.

Watch out

R² says how much variance the line explains, not whether the line is right. A curved relationship can have a high R² and obviously wrong predictions at the ends.

Try it · Fit by hand, then by least squares
Data Your line Least-squares line
Your squared error Best possible R²
06

Transformations

Many quantities grow by multiplication, not addition. On a log scale, exponential growth becomes a straight line and a spread that grew with the level becomes even.

A line says "each step adds the same amount." Prices, populations, infection counts and incomes more often say "each step multiplies by the same factor." Taking logarithms turns multiplication into addition, so such data fit a straight line on the log scale and the slope becomes a growth rate.

Logs also fix a second problem. When errors are proportional to the level, the raw scale shows a cone of scatter that violates the assumptions of ordinary least squares, while on the log scale the scatter is even. Fit in the scale where the noise is steady, then convert predictions back.

log y = a + b x  ⇒  y = ea · (eb)x A straight line on the log scale is exponential growth at rate eb − 1 per step

Watch out

Back-transforming a log-scale prediction gives the median of y, not its mean, and the mean is larger. Zeros and negative values can't be logged, so decide what they mean before you transform.

Try it · Straight line or exponential?
True growth 20% per step Fitted Forecast, 5 steps on Truth
Part III

Will it generalize?

A model can be tuned until it fits what it has seen. The test that matters is what it does next. These three ideas are about measuring that honestly, restraining a model so that it generalizes, and reading its answers correctly.

07

Hold-out data & leakage

Score a model on data it never touched, and keep every modeling decision, including which features to use, inside the training fold. Otherwise pure noise can look like a discovery.

Training error rewards memorization. The fix is to hold some data back: fit on one part and score on the other. Cross-validation repeats this so every row serves once as the test set, and it gives an error estimate with less luck in it.

The estimate is only honest if the held-out rows are really unseen. Leakage is any way that information from the test rows reaches the model: selecting features on the full data before splitting, normalizing with statistics from all rows, or having the same patient in both folds. Leakage is subtle because the code runs and the score looks excellent.

The lab uses data where the labels are coin flips and the features are noise, so the right accuracy is 50%. Pick the "best" features using every row first and then cross-validate, and you'll see a brilliant score for a model that knows nothing.

History

Ambroise and McLachlan (2002) re-examined published gene-expression classifiers and showed that selecting genes on all samples before cross-validating gives near-perfect error rates even when the class labels are randomly permuted. With thousands of genes and dozens of patients, some genes will correlate with the labels by chance.

Try it · Cross-validate pure noise
Cross-validated accuracy Truth: 50%
Typical accuracy Best of 40
08

Regularization

When there are many predictors and little data, unconstrained fitting is unstable. Pulling the coefficients toward zero adds a little bias and removes a lot of variance.

Least squares is unbiased: on average it recovers the true coefficients. But with 15 correlated predictors and 30 rows, any single fit swings wildly, and the unbiased answer is far from the truth in nearly every sample. Ridge regression adds a penalty on the size of the coefficients, which shrinks them all toward zero and stabilizes them.

β̂ridge = argmin Σ(yi − xiβ)² + λ Σβj² The penalty strength λ is chosen by cross-validation

Too little penalty and the fit is noisy. Too much and every coefficient collapses toward zero and the model underfits. The best λ sits between, and test error against λ is a U shape. The lasso replaces the squared penalty with absolute values, which sets some coefficients exactly to zero and so selects variables.

Watch out

Penalties depend on the units of the predictors, so standardize them first. And shrunken coefficients are for prediction. They are biased estimates of effects, so don't read them as causal.

Try it · Turn the penalty up
Test error Estimated coefficient True coefficient
Test error now Unpenalized Best
09

Base rates & thresholds

A classifier outputs a score, and you choose a threshold. Whether a positive result is believable depends on how common the condition was in the first place.

Most classifiers give a score, and a threshold turns it into a yes or no. Move the threshold up and you catch fewer false alarms but also miss more cases. Sensitivity is the share of real cases flagged. Specificity is the share of non-cases cleared. Neither tells you what a flag means.

That is the positive predictive value, and it depends on prevalence. If one person in a thousand has the condition, even a test that is 95% sensitive and 95% specific produces about 50 false alarms for every true one. This is Bayes' rule, and it is the usual reason that screening and fraud flags disappoint.

PPV = sens × prevsens × prev + (1 − spec) × (1 − prev) The chance a positive result is real

Watch out

"Accuracy" is misleading with rare outcomes. A rule that always says "no fraud" is 99.9% accurate when fraud is 0.1% of cases, and useless.

Try it · Rare condition, good test
Has condition Does not Threshold Curves are drawn at equal height so the rare group stays visible.
Sensitivity Specificity Chance a positive is real
Part IV

Structure & time

Not every analysis has an outcome to predict. Sometimes the job is to find groups or directions in the data, and with time series the trap is that a trend looks like a relationship.

10

Clustering

Ask an algorithm for k groups and it returns k groups, whether or not the data has any. The number of clusters is a modeling choice that has to be justified.

The k-means algorithm alternates two steps: assign each point to its nearest center, then move each center to the mean of its points. It always converges, quickly, to something. Where it ends up depends on the starting centers, and the result is only a local optimum.

The total within-cluster squared distance always falls as k grows, down to zero when every point is its own cluster, so it can't choose k for you. The usual heuristic is the "elbow": the value of k where adding another cluster stops paying for itself. On data with clear groups the elbow is sharp. On a single smooth blob, there is none, and any partition is just an arbitrary slicing.

Watch out

Clusters in a plot aren't evidence of types in nature. Run the algorithm on data you know has no groups, as in the lab, and compare the look of the output.

Try it · How many groups are there?
Within-cluster distance Share of total variance explained
11

Principal components

When variables move together, a few directions carry most of the variation. Principal components find them, and let you describe the data with far fewer numbers.

Imagine a cloud of points shaped like a tilted ellipse. Height and weight of adults, or two highly correlated test scores, are like that. The long axis of the ellipse is a better single summary than either original variable: projecting each point onto it keeps as much of the spread as any one direction can.

That axis is the first principal component. The second is perpendicular to it and carries the most remaining variance, and so on. Mathematically they are the eigenvectors of the covariance matrix, and the eigenvalues give the variance each carries. With 100 correlated measurements, the first three components might hold 90% of the information.

Variance along unit direction u = uᵀ Σ u  ⇒  maximized by the top eigenvector of Σ Σ is the covariance matrix of the data

Watch out

PCA finds directions of high variance, which are not necessarily directions of high relevance. If one variable is measured in grams and another in kilometers, the large numbers dominate unless you standardize first.

Try it · Rotate the axis
Points Your axis First principal component
Variance along your axis Share of total Largest possible
12

Trends & spurious correlation

Two series that wander, with no connection at all, usually look strongly correlated. Comparing levels over time is a trap, and comparing changes is the check.

A random walk adds a random step each period and never returns to a mean. Any two of them will drift, and over a stretch of time they'll move together or apart purely by chance. The usual correlation test assumes independent observations, but consecutive points of a random walk are nearly the same, so there are far fewer independent pieces of evidence than rows.

Granger and Newbold showed in 1974 that regressing one independent random walk on another produces "significant" results far more often than the 5% a test promises. The cure is to difference: look at the period-to-period changes. If the changes in two series move together, there's a relationship. If only the levels do, there probably isn't.

History

In 1926 G. Udny Yule published "Why do we sometimes get nonsense-correlations between time series?" showing that the correlation between the proportion of Church of England marriages and the death rate across 1866–1911 was 0.95. Tyler Vigen's site of spurious correlations is the modern version: US cheese consumption against deaths by bedsheet tangling.

Try it · Two unrelated random walks
This pair, correlation Pairs with |r| > 0.5
Putting it together

Three threads run through all twelve ideas

The data are not the world

Plots, outliers, missing values and noisy measurements (ideas 1–4) are all about the gap between what was recorded and what happened. Know how your data got to you before you trust anything computed from it.

Fit is cheap, generalization isn't

Least squares, hold-out data and regularization (ideas 5, 7, 8) separate fitting what you have from predicting what you don't. Every modeling choice should be judged on data the choice never saw.

Patterns arrive for free

Clusters, components, base-rate artifacts and trends (ideas 9–12) show that patterns appear in noise on demand. Ask what the pattern would look like if nothing were there, and run that experiment.

Further reading

  • John Tukey, Exploratory Data Analysis (1977). The case for looking first, from the person who named the practice.
  • Edward Tufte, The Visual Display of Quantitative Information (2nd ed., 2001). How to draw the picture so it tells the truth.
  • Andrew Gelman, Jennifer Hill & Aki Vehtari, Regression and Other Stories (2020). Modeling for people who will use the results.
  • Gareth James, Daniela Witten, Trevor Hastie & Rob Tibshirani, An Introduction to Statistical Learning (2nd ed., 2021; free online). Cross-validation, ridge, lasso, clustering and PCA.
  • Max Kuhn & Kjell Johnson, Feature Engineering and Selection (2019; free online). Leakage, resampling and preprocessing done right.
  • Nate Silver, The Signal and the Noise (2012). Prediction in practice, and why forecasters fail.