Simple Algorithm
Machine Learning · Convergence · 26 min

The i.i.d. Assumption & Its Failures

Exchangeability, dependence and what breaks when data is not i.i.d.

Nearly every guarantee in this course begins "let the examples be i.i.d." This lesson takes the assumption apart: what each half of it buys, the weaker symmetry, exchangeability, that de Finetti showed is almost the same thing, how dependence in groups, time and space shrinks the effective sample size and flatters naive error estimates, how to validate dependent data, and what learning theory can still promise when examples are mixing rather than independent.

What you’ll learn

  • Separate what identical distribution and independence each buy, and explain why dependence leaves a fixed model's test error unbiased but its standard error wrong.
  • Define exchangeability, build exchangeable but dependent sequences, and state de Finetti's theorem and the finite version of Diaconis and Freedman.
  • Compute effective sample sizes for clustered and autocorrelated data, and explain why random cross-validation is optimistic on dependent data.
  • Design grouped, blocked and spatial validation, and derive a concentration bound for β-mixing sequences from Yu's independent-blocks lemma.

What i.i.d. buys

To say that examples Zi=(xi,yi)Z_i=(\mathbf x_i,y_i) are i.i.d. from PP is to say that their joint law is the product P⊗nP^{\otimes n}. The assumption has two halves, and they fail in different ways.

HalfWhat it buysHow it failsCovered in
Identically distributed: training, test and deployment data share one PPtest error estimates the risk you will meet in usedistribution shift: covariate, label or concept shiftlesson Covariate, Label & Concept Shift
Independentvariances of averages fall like 1/n1/n; Hoeffding-type bounds; training and test sets independent of each otherrepeated measurements of one subject, time series, spatial data, duplicatesthis lesson

Independence is the subtler half. If every test example has the right marginal distribution, the test error of a fixed model is still unbiased, by linearity of expectation, whatever the dependence. What dependence breaks is everything else: the standard error is larger than the i.i.d. formula says, and when test examples are correlated with training examples, a model can score by exploiting that correlation instead of solving the task.

Think first A fixed model is scored on 1,000 test examples from the right distribution, but they come in 50 clusters of 20 strongly correlated examples, and the model was trained on separate data. Is the test error biased? Is the usual standard error right?

Unbiased: each example has the right marginal distribution, and expectation is linear. But the usual standard error p(1−p)/1000\sqrt{p(1-p)/1000} is too small. Correlated examples carry less information, and with strong within-cluster correlation the test set is worth closer to 50 independent examples than to 1,000, so the confidence interval must widen by up to a factor of 20≈4.5\sqrt{20}\approx4.5. The third step of this lesson computes the exact factor.

Exchangeability and de Finetti

i.i.d. sequences are exchangeable; the converse fails. Draws without replacement from an urn are exchangeable but negatively correlated. A coin of unknown bias gives the opposite sign: draw p∼Uniform(0,1)p\sim\mathrm{Uniform}(0,1), then flip the coin repeatedly. Given pp the flips are i.i.d.; unconditionally they are exchangeable but positively correlated, with Cov⁡(Z1,Z2)=Var⁡(p)=1/12\Cov(Z_1,Z_2)=\Var(p)=1/12, because every head is evidence that the coin favors heads.

Predict before you look

With p∼Uniform(0,1)p\sim\mathrm{Uniform}(0,1) and Z1,Z2,…Z_1,Z_2,\dots i.i.d. Bernoulli(pp) given pp, what is P(Z2=1∣Z1=1)P(Z_2=1\mid Z_1=1), in percent?

Show the answer

67 %

P(Z1=Z2=1)=E[p2]=1/3P(Z_1=Z_2=1)=\E[p^2]=1/3 and P(Z1=1)=E[p]=1/2P(Z_1=1)=\E[p]=1/2, so the conditional probability is 2/32/3. This is Laplace's rule of succession: after ss heads in nn flips, the next is a head with probability (s+1)/(n+2)(s+1)/(n+2). The first flip changed the odds of the second, so the flips are not independent.

For finite sequences the representation can fail. Two draws without replacement from an urn holding one red and one blue ball always differ, and no mixture of i.i.d. coins can avoid two equal draws with probability one. But it holds approximately: Diaconis and Freedman (1980) showed that if Z1,…,ZnZ_1,\dots,Z_n is exchangeable with values in a set of cc elements, the law of the first kk variables is within 2ck/n2ck/n of a mixture of i.i.d. laws in variation distance, and within k(k−1)/nk(k-1)/n with no restriction on the values. A short prefix of a long exchangeable sequence is nearly conditionally i.i.d.

Exchangeability is often the assumption actually needed. Bayesian models treat data as i.i.d. given parameters, and de Finetti's theorem is the justification. Permutation tests and conformal prediction are valid under exchangeability alone (lesson Conformal Prediction). And splitting a fixed dataset at random is sampling without replacement, exchangeable but not independent; Hoeffding (1963) showed that his inequality still holds in that case.

Dependence shrinks your sample

Correlated observations repeat part of one another's information. The effective sample size neffn_{\text{eff}} is the number of independent observations that would give the sample mean the same variance.

DerivationEffective sample sizes
  1. Var⁡(∑j=1mYj)=mσ2+m(m−1)ρσ2⟹Var⁡(Yˉ)=σ2n(1+(m−1)ρ)\Var\Big(\sum_{j=1}^mY_j\Big)=m\sigma^2+m(m-1)\rho\sigma^2\quad\Longrightarrow\quad\Var(\bar Y)=\frac{\sigma^2}{n}\big(1+(m-1)\rho\big)

    Clusters. Let n=Kmn=Km observations come in KK independent clusters of size mm, with common variance σ2\sigma^2 and correlation ρ\rho between any two observations of the same cluster. A cluster's sum has mm variance terms and m(m−1)m(m-1) covariance terms:

  2. neff=n1+(m−1)ρn_{\text{eff}}=\frac{n}{1+(m-1)\rho}

    So the data are worth n/(1+(m−1)ρ)n/(1+(m-1)\rho) independent observations. The factor 1+(m−1)ρ1+(m-1)\rho is Kish's design effect from survey sampling.

  3. Var⁡(∑t=1nYt)=σ2[n+2∑k=1n−1(n−k)ρk]∼nσ2 1+ρ1−ρ(n→∞)\Var\Big(\sum_{t=1}^nY_t\Big)=\sigma^2\Big[n+2\sum_{k=1}^{n-1}(n-k)\rho^k\Big]\sim n\sigma^2\,\frac{1+\rho}{1-\rho}\qquad(n\to\infty)

    Time series. For a stationary AR(1) series with Corr⁡(Yt,Yt+k)=ρk\operatorname{Corr}(Y_t,Y_{t+k})=\rho^k, there are n−kn-k pairs at lag kk, and the geometric series sums:

  4. neff≈n 1−ρ1+ρn_{\text{eff}}\approx n\,\frac{1-\rho}{1+\rho}

    Hence, for long series, the formula below. With ρ=0.9\rho=0.9, a thousand daily readings carry the information of about 53 independent ones.

Predict before you look

A study has 100 patients with 20 scans each, and scans of the same patient have correlation ρ=0.5\rho=0.5. How many independent scans are the 2,000 scans worth for estimating a mean?

Show the answer

190 scans

The design effect is 1+(20−1)×0.5=10.51+(20-1)\times0.5=10.5, so neff=2000/10.5≈190n_{\text{eff}}=2000/10.5\approx190. The data behave more like 190 independent scans than 2,000, and an i.i.d. standard error would be too small by a factor of 10.5≈3.2\sqrt{10.5}\approx3.2.

Dependence damages error estimates in three ways. Standard errors computed as if the data were i.i.d. are too small, by the factor n/neff\sqrt{n/n_{\text{eff}}}. When correlated examples straddle the train–test boundary (the same patient, adjacent minutes, neighboring field plots), a model can score by recognizing or interpolating its neighbors instead of learning the task, so the estimate is optimistic for new patients, for the future, or for new regions. And model selection on such estimates favors flexible models that exploit exactly that.

How much this matters depends on the model as well as the data. Bergmeir, Hyndman and Koo (2018) showed that for purely autoregressive models whose errors are uncorrelated, a common situation when a flexible model nests a suitable one, ordinary KK-fold cross-validation is valid for time series; the trouble starts when the model leaves correlation in its residuals.

Validating dependent data

The principle of the Descent lesson applies with full force: validation must reproduce the relationship between the data a model learns from and the data it will be used on.

StructureValidation schemeCaveat
Groups: patients, users, sessionsgroup KK-fold: each group in exactly one foldestimates performance on new groups; if deployment is on known groups, a within-group split answers that question instead
Time series, forecastingrolling origin: train on everything up to time tt, test on the next horizon, advance ttearly data are used little; leave a gap so that autocorrelation does not leak across the boundary
Time series, using all the datablocked KK-fold with hh observations removed on each side of each test block, as the h-block cross-validation of Burman, Chow and Nolan (1994) does around each single held-out observationrelies on stationarity; the gap must exceed the range of the dependence
Spatial datablocks larger than the range of the residual spatial autocorrelation (Roberts et al., 2017)blocks can force extrapolation and overstate the error when the real task is interpolation
python
from sklearn.model_selection import GroupKFold, TimeSeriesSplit, cross_val_score

# New patients: no patient appears on both sides of any split
scores_groups = cross_val_score(model, X, y, groups=patient_id,
                                cv=GroupKFold(n_splits=5))

# Forecasting: train on the past, skip 24 steps, test on the next block
# (rows of X_t and y_t must be in time order)
scores_time = cross_val_score(model, X_t, y_t,
                              cv=TimeSeriesSplit(n_splits=5, gap=24))

The gap argument drops the observations between each training block and its test block, so that strongly autocorrelated neighbors do not straddle the boundary.

Learning from mixing processes

For a stationary sequence, dependence can be measured by how quickly the future forgets the past. The β-mixing coefficient at gap aa is

β(a)=sup⁡t E[sup⁡A∈σ(Zt+a,Zt+a+1,… )∣P(A∣Z1,…,Zt)−P(A)∣],\beta(a)=\sup_t\ \E\Big[\sup_{A\in\sigma(Z_{t+a},Z_{t+a+1},\dots)}\big|P(A\mid Z_1,\dots,Z_t)-P(A)\big|\Big],

and the sequence is β-mixing if β(a)→0\beta(a)\to0 as a→∞a\to\infty. A stationary Gaussian AR(1) process with ∣ρ∣<1\abs\rho<1 mixes exponentially fast.

DerivationA concentration bound for one hypothesis
  1. Pindep(∣R^odd(h)−R(h)∣>ε)≤2e−2με2P_{\text{indep}}\Big(\big|\hat R_{\text{odd}}(h)-R(h)\big|>\varepsilon\Big)\le2e^{-2\mu\varepsilon^2}

    Fix hh with loss in [0,1][0,1] and let R^odd(h)\hat R_{\text{odd}}(h) be its average loss over the odd blocks. Under the independent-block law it is an average of μ\mu independent block averages with mean R(h)R(h), so Hoeffding's inequality applies with μ\mu in place of nn:

  2. P(∣R^n(h)−R(h)∣>ε)≤4e−2με2+2(μ−1) β(a),μ=n2aP\Big(\big|\hat R_n(h)-R(h)\big|>\varepsilon\Big)\le4e^{-2\mu\varepsilon^2}+2(\mu-1)\,\beta(a),\qquad\mu=\frac n{2a}

    Apply the lemma to the indicator of that event (M=1M=1) to move the bound to the real sequence, and do the same for the even blocks. The full empirical risk is the mean of the two halves, so it is within ε\varepsilon whenever both are:

  3. The block length trades the two terms: longer blocks shrink β(a)\beta(a) but leave fewer blocks. For exponentially mixing sequences, blocks of length of order log⁡n\log n suffice and the rate is within logarithmic factors of the i.i.d. one; for slowly mixing sequences it is genuinely slower. Mohri and Rostamizadeh (2010) combined blocking with algorithmic stability to obtain generalization bounds for stationary φ-mixing and β-mixing data that apply to all stable learning algorithms, including support vector regression, kernel ridge regression and support vector machines.

Key takeaways

  • i.i.d. = identical distribution (its failure is distribution shift) + independence (its failure is groups, time series, spatial data, duplicates). With the right marginals, a fixed model's test error stays unbiased under dependence, but its standard error grows, and train–test correlation flatters the estimate.
  • Exchangeability is the symmetry behind i.i.d.: infinite exchangeable sequences are mixtures of i.i.d. sequences (de Finetti; Hewitt & Savage), and finite ones nearly so (within 2ck/n2ck/n: Diaconis & Freedman). Permutation tests and conformal prediction need only exchangeability.
  • Dependence shrinks the effective sample size: n/(1+(m−1)ρ)n/(1+(m-1)\rho) for clusters of size mm, about n(1−ρ)/(1+ρ)n(1-\rho)/(1+\rho) for an AR(1) series.
  • Validate dependent data the way the model will be used: group KK-fold for new groups, rolling origin or blocked folds with gaps for time series, spatial blocks for new regions, remembering that blocks can overstate error when the task is interpolation.
  • For β-mixing sequences, independent blocks give i.i.d.-style bounds with μ=n/(2a)\mu=n/(2a) blocks and a penalty (μ−1)β(a)(\mu-1)\beta(a); stability-based bounds extend this to all stable algorithms (Mohri & Rostamizadeh, 2010).

Check yourself

In the interactive lesson these are scored with your confidence, and what you miss comes back for review.

Question 1

Which sequence is exchangeable but not independent?

  1. Successive draws without replacement from an urn with 5 red and 5 blue balls
  2. Independent flips of a fair coin
  3. The positions of a random walk at times 1,2,3,…1,2,3,\dots
  4. Daily temperatures in one city over a year
Show the answer

A. Successive draws without replacement from an urn with 5 red and 5 blue balls

Any reordering of the draws has the same probability, so the sequence is exchangeable, but a red draw makes the next red less likely, so the draws are dependent.

Question 2

Daily measurements follow a stationary AR(1) process with lag-one correlation ρ=0.8\rho=0.8. Roughly how many independent observations are 365 days worth for estimating the mean?

  1. 365
  2. 203
  3. 41
  4. 4
Show the answer

C. 41

neff≈n(1−ρ)/(1+ρ)=365×0.2/1.8≈41n_{\text{eff}}\approx n(1-\rho)/(1+\rho)=365\times0.2/1.8\approx41. Strong autocorrelation leaves a year of daily data with the information of about six weeks of independent days.

Question 3

Random 5-fold cross-validation on minute-by-minute sensor data reports a much lower error than the model achieves on next week's data. What is the most likely reason?

  1. The model underfits
  2. Five folds are too few; ten would fix it
  3. The sensor must have drifted between the two periods
  4. Each test minute has nearly identical neighbors in training, so cross-validation measured interpolation, not forecasting
Show the answer

D. Each test minute has nearly identical neighbors in training, so cross-validation measured interpolation, not forecasting

Random folds scatter adjacent, highly correlated minutes across training and test sets. Forward-chaining validation with a gap, training on the past and testing on a later block, measures what deployment needs.

Question 4

In the independent-blocks argument for a β-mixing sequence of length nn with blocks of length aa, what plays the role of the sample size in the Hoeffding exponent?

  1. nn
  2. n/(2a)n/(2a), the number of blocks in each half
  3. aa
  4. n\sqrt n
Show the answer

B. n/(2a)n/(2a), the number of blocks in each half

Concentration comes from the μ=n/(2a)\mu=n/(2a) nearly independent blocks of one parity, not from the nn dependent observations; the price of treating the blocks as independent is the additive term (μ−1)β(a)(\mu-1)\beta(a).

Further reading

  • B. Yu, "Rates of convergence for empirical processes of stationary mixing sequences," Annals of Probability 22(1), 94–116 (1994).
  • P. Diaconis & D. Freedman, "Finite exchangeable sequences," Annals of Probability 8(4), 745–764 (1980).
  • D. R. Roberts et al., "Cross-validation strategies for data with temporal, spatial, hierarchical, or phylogenetic structure," Ecography 40(8), 913–929 (2017).
  • C. Bergmeir, R. J. Hyndman & B. Koo, "A note on the validity of cross-validation for evaluating autoregressive time series prediction," Computational Statistics & Data Analysis 120, 70–83 (2018).
  • M. Mohri & A. Rostamizadeh, "Stability bounds for stationary φ-mixing and β-mixing processes," Journal of Machine Learning Research 11, 789–814 (2010).