Module contents
Lesson 24 of 27Core 115 min

Design of experiments and ANOVA

Design experiments with valid, precise conclusions. Study Fisher’s principles of randomization, replication and blocking, one- and two-factor ANOVA as linear models, block and fractional factorial designs, aliasing, adjustment with pre-experiment covariates, and threats to A/B test validity.

After this lesson you can

  • Apply randomization, replication and blocking, and explain how they protect validity or improve precision.
  • Run one- and two-factor ANOVA as a linear model, interpret interactions and apply Tukey comparisons.
  • Design 2ᵏ and fractional factorial experiments, estimate main effects and interactions, and explain aliasing.
  • Reduce variance with pre-experiment covariate adjustment, such as ANCOVA or CUPED, without introducing bias.
  • Design and analyze an A/B test, specifying the randomization unit, ratio metrics, sample size, sample ratio mismatch checks and novelty effects.

Before you start

Motivation: analysis cannot fix a poorly designed experiment

A platform team has written a new request scheduler and wants to know whether it increases server throughput (thousands of requests per second). It has twelve machines: six old ones, averaging 100, and six new ones, averaging 112. The easiest route is to install the scheduler on the six new machines, already in the test rack, and compare. The observed difference will be large, have a tiny pp value, and mean nothing: scheduler and hardware age occur together, and no subsequent analysis can separate them, because the data contain no old machine with the scheduler or new machine without it. In a famous 1938 remark, Ronald Fisher compared consulting a statistician after an experiment is finished to asking for an autopsy: perhaps they can say what it died of.

The next cell repeats the experiment 20 000 times with three ways of assigning treatments. The scheduler’s true effect is τ=2\tau = 2. Each machine’s noise is σ=6\sigma = 6. All three designs treat six servers and leave six as controls; only who receives treatment changes.

[ ]Three ways to assign treatment to twelve serversBrowser
import numpy as np
from scipy import stats

rng = np.random.default_rng(24)
R = 20000
base = np.r_[np.full(6, 100.0), np.full(6, 112.0)]       # 6 servidores viejos (0 a 5) y 6 nuevos (6 a 11)
sigma = 6.0
ruido = rng.normal(0, sigma, (R, 12))

def estimar(trat, tau):
    """Estimador (media de tratados menos media de control) y estadístico t de Welch en R experimentos."""
    y = base + ruido + tau * trat
    mt = (y * trat).sum(1) / 6
    mc = (y * ~trat).sum(1) / 6
    vt = (((y - mt[:, None]) ** 2) * trat).sum(1) / 5
    vc = (((y - mc[:, None]) ** 2) * ~trat).sum(1) / 5
    return mt - mc, (mt - mc) / np.sqrt(vt / 6 + vc / 6)

sistematica = np.tile(np.arange(12) >= 6, (R, 1))                                    # los nuevos reciben el planificador
completa = np.argsort(rng.random((R, 12)), axis=1) < 6                              # 6 al azar entre los 12
por_bloques = np.concatenate([np.argsort(rng.random((R, 6)), axis=1) < 3 for _ in range(2)], axis=1)  # 3 de 6 en cada generación

tcrit = stats.t.ppf(0.975, 10)
print(f"{'diseño':22s} {'media':>7s} {'desv. típica':>13s}   {'% rechazos con tau = 0':>24s}")
for nombre, T in [("sistemática", sistematica), ("aleatoria completa", completa), ("aleatoria por bloques", por_bloques)]:
    d, _ = estimar(T, 2.0)
    if nombre == "aleatoria por bloques":
        rech = "(se analiza por bloques)"
    else:
        _, t0 = estimar(T, 0.0)
        rech = f"{100 * np.mean(np.abs(t0) > tcrit):.1f} %"
    print(f"{nombre:22s} {d.mean():7.2f} {d.std():13.2f}   {rech:>24s}")

Systematic assignment estimates 13.9613.96 instead of 22: a bias of 11.9611.96 that does not shrink however often the experiment is repeated, and rejects the hypothesis that the scheduler does nothing when it is true in 87.3 %87.3\ \% of cases. The two randomized assignments are centered on the true value (means 1.981.98 and 2.052.05), and the complete-randomization test maintains 5.4 %5.4\ \% false rejections. But the complete design pays a standard deviation of 5.035.03 versus 3.503.50 for the blocked design: randomization gives validity, and blocking gives precision. That is the lesson in one sentence; the rest develops it in three directions: how to analyze each design (ANOVA), how to combine several factors (factorials), and how to apply it to experiments a software company runs every day (A/B tests).

This lesson uses without further explanation the Gaussian linear model and its nested-model FF test, randomization inference, the power function and sample-size calculation, the paired test, the delta method, Pearson’s χ2\chi^2 test, FWER control, and the orthonormal basis used to prove the coefficients’ distribution in lesson 19.

Fisher’s three principles

The three principles solve different problems and do not replace one another. Let us see exactly what randomization guarantees. Each unit i=1,…,Ni = 1, \dots, N has two fixed numbers, its response with treatment, yi(1)y_i(1), and without it, yi(0)y_i(0), of which only one is observed. The average effect over the NN units is τˉ=1N∑i(yi(1)−yi(0))\bar\tau = \frac{1}{N}\sum_i \big(y_i(1) - y_i(0)\big). There is no probability model for the responses: the only randomness is the assignment draw.

Proof

(1) By symmetry, E[Wi]=n1/N\E[W_i] = n_1/N for each ii. Then E[yˉT]=E[1n1∑iWi yi(1)]=1n1∑in1N yi(1)=yˉ(1)\E[\bar y_T] = \E\big[\tfrac{1}{n_1}\sum_i W_i\,y_i(1)\big] = \tfrac{1}{n_1}\sum_i \tfrac{n_1}{N}\,y_i(1) = \bar y(1), the mean of yi(1)y_i(1) across the population. Similarly E[yˉC]=yˉ(0)\E[\bar y_C] = \bar y(0), and the difference is yˉ(1)−yˉ(0)=τˉ\bar y(1) - \bar y(0) = \bar\tau. (2) This calculation uses indicator covariances, Var⁡(Wi)=n1n0N2\Var(W_i) = \tfrac{n_1 n_0}{N^2} and Cov⁡(Wi,Wj)=−n1n0N2(N−1)\Cov(W_i, W_j) = -\tfrac{n_1 n_0}{N^2(N-1)} for i≠ji \ne j; the algebra is omitted, as it is the same as in sampling without replacement in lesson 3 and permutation tests. The term −Sτ2/N-S_\tau^2/N appears because yi(1)y_i(1) and yi(0)y_i(0) are not observed simultaneously for the same unit, so the variance estimator cannot estimate their covariance.

∎

Two practical consequences. First: with a known random mechanism, the distribution of τ^\hat\tau under the null-effect hypothesis (no individual effect, yi(1)=yi(0)y_i(1) = y_i(0)) can be enumerated by permuting assignments, giving Fisher’s test from lesson 14: the pp value comes from the design, not a model. Second, as seen in the cell: if assignment depends on the potential response (new servers go to treatment), point 1 no longer holds.

Replication requires real independence. Measuring latency 100 times on the same server gives a very precise estimate of that server’s performance and no information about variation between servers, the error against which treatment effect must be compared when treatment is assigned per server. This confusion of units is called pseudoreplication and is the source of the most common design error in practice; it returns in A/B tests, where the unit of randomization and analysis must match.

Blocking deserves an exact calculation, since the next figure shows its effect. There are bb racks of ss servers (n=bsn = bs servers in total, with n/2n/2 treated). Untreated server performance is βr+ei\beta_r + e_i, with βr∼N(0,σb2)\beta_r \sim \Normal(0, \sigma_b^2) the rack effect and ei∼N(0,σe2)e_i \sim \Normal(0, \sigma_e^2) its own noise, and treatment adds τ\tau.

Proof

Write τ^−τ=2n∑iωi (βr(i)+ei)\hat\tau - \tau = \frac{2}{n}\sum_i \omega_i\,(\beta_{r(i)} + e_i) with ωi=+1\omega_i = +1 if server ii is treated and −1-1 if it is a control. The noise part, independent of assignment, contributes 4n2 n σe2=4σe2/n\frac{4}{n^2}\,n\,\sigma_e^2 = 4\sigma_e^2/n in both designs. Rewrite the rack part as 2n∑rβrdr\frac{2}{n}\sum_r \beta_r d_r, with dr=Tr−Crd_r = T_r - C_r the difference between treated and control units in rack rr. Conditional on assignment, its variance is 4n2σb2∑rdr2\frac{4}{n^2}\sigma_b^2\sum_r d_r^2. With blocking, dr=0d_r = 0 in every rack, and the contribution vanishes. With complete assignment, TrT_r is hypergeometric (from nn, with n/2n/2 successes, ss draws), with mean s/2s/2 and variance s4n−sn−1\frac{s}{4}\frac{n - s}{n - 1}, and since dr=2Tr−sd_r = 2T_r - s, E[dr2]=Var⁡(dr)=s n−sn−1\E[d_r^2] = \Var(d_r) = s\,\frac{n - s}{n - 1}. Summing over the n/sn/s racks gives contribution 4n2σb2ns s n−sn−1=4σb2(n−s)n(n−1)\frac{4}{n^2}\sigma_b^2\frac{n}{s}\,s\,\frac{n - s}{n - 1} = \frac{4\sigma_b^2(n - s)}{n(n - 1)}. Both designs are unbiased because E[ωi]=0\E[\omega_i] = 0 and effects have zero mean.

∎

The figure shows the theorem, and also what it does not cover, the third design: systematic assignment (the higher-performing, new racks all receive treatment). Its variance is small, but that is no help: it is centered elsewhere.

InteractiveBlocking to see the effect
One repetition of the completely randomized design: each point is a server, grouped by rack
racks in physical order
Estimated effect τ^=yˉtrat−yˉctrl\hat\tau = \bar y_{\text{trat}} - \bar y_{\text{ctrl}} in 2000 repeated experiments (truth: τ=5\tau = 5)
truth
  • treated (+τ)
  • control
  • rack baseline
  • completely randomized
  • blocked
  • systematic
Design shown above
8.0
4.0
6 (n = 24)
Complete randomization: mean | SD (theory)5.11 | 3.50 (3.46)
Blocked: mean | SD (theory)5.01 | 1.64 (1.63)
Systematic: mean | SD16.37 | 4.22
CRD / blocked variance: simulated (theory)4.55 (4.48)
Savings: blocking with nn equals CRD with107 servers
Both randomized designs are centered at τ=5\tau = 5, but complete randomization carries between-rack variation (standard deviation 3.50) and blocking does not (1.64). The systematic design is also precise but biased by 11.37: precision without validity.
Servers in racks of four, with unequal baseline performance across racks (σb\sigma_b) and individual noise (σe\sigma_e). Above, one repetition of the chosen design: each point is a server (orange if it receives the scheduler, blue for control) and the dashed line is its rack baseline. Below, the distribution of the estimated effect in 2000 repetitions of each of the three designs. Increase σb\sigma_b from 0 to 15: which curve widens and which does not change width? With σb=σe\sigma_b = \sigma_e, how many servers in a complete design are equivalent to those in the blocked design? Which design fails by being centered incorrectly, and by how much?

Three observations. The blocked design’s width depends only on σe\sigma_e: changing σb\sigma_b does not move it, because between-rack differences cancel by construction in each comparison. The complete design’s width grows with σb\sigma_b (the horizontal scale adjusts, so the blocked curve appears narrower: it is the complete one that widens), but its center is always the true value: only precision is lost. The systematic design illustrates why validity comes before precision: being precise does not help a design centered incorrectly. In cost terms, blocking is free (it costs no runs) provided the blocking variable is known before assignment. The cost is lost error degrees of freedom when units are few, an effect seen with complete blocks.

One-way ANOVA as a linear model

Compare kk treatments (four cache policies, four compiler versions), with nin_i units randomly assigned to treatment ii and N=∑iniN = \sum_i n_i. The model is

yij=μi+εij,εij∼iidN(0,σ2),i=1,…,k, j=1,…,ni.y_{ij} = \mu_i + \varepsilon_{ij}, \qquad \varepsilon_{ij} \iid \Normal(0, \sigma^2), \qquad i = 1, \dots, k,\ j = 1, \dots, n_i.

This is the Gaussian linear model with design matrix X∈RN×k\mat{X} \in \R^{N \times k} of group-indicator columns (one per treatment), of rank kk. Its coefficients are means μi\mu_i, and their least-squares estimator is μ^i=yˉi⋅\hat\mu_i = \bar y_{i\cdot}. The usual parameterization, μi=μ+αi\mu_i = \mu + \alpha_i with ∑iniαi=0\sum_i n_i\alpha_i = 0, separates an overall mean from treatment effects αi\alpha_i; both describe the same subspace col⁡(X)\col(\mat{X}) of RN\R^N, and test the same hypothesis, H0 ⁣:μ1=⋯=μkH_0\!: \mu_1 = \dots = \mu_k (that is, all αi=0\alpha_i = 0).

Proof

Let P\mat{P} be the orthogonal projection of RN\R^N onto col⁡(X)\col(\mat{X}) and P1\mat{P}_1 the projection onto span⁡{1}\spn\{\vb{1}\}, with 1∈col⁡(X)\vb{1} \in \col(\mat{X}) (the sum of the indicator columns). Applied to y\vb{y}, Py\mat{P}\vb{y} has entry yˉi⋅\bar y_{i\cdot} in positions for group ii, and P1y=yˉ 1\mat{P}_1\vb{y} = \bar y\,\vb{1}. Since span⁡{1}⊂col⁡(X)\spn\{\vb{1}\} \subset \col(\mat{X}), PP1=P1\mat{P}\mat{P}_1 = \mat{P}_1. The difference P−P1\mat{P} - \mat{P}_1 is the projection onto the orthogonal complement of 1\vb{1} within col⁡(X)\col(\mat{X}), of dimension k−1k - 1, and I−P\mat{I} - \mat{P} projects onto col⁡(X)⊥\col(\mat{X})^\perp, of dimension N−kN - k. The two projections annihilate each other, (I−P)(P−P1)=0(\mat{I} - \mat{P})(\mat{P} - \mat{P}_1) = \mat{0}.

(1) y−yˉ1=(y−Py)+(Py−P1y)\vb{y} - \bar y\vb{1} = (\vb{y} - \mat{P}\vb{y}) + (\mat{P}\vb{y} - \mat{P}_1\vb{y}) is a sum of orthogonal vectors; by Pythagoras, SST=∥y−Py∥2+∥Py−P1y∥2=SSW+SSB\mathrm{SST} = \norm{\vb{y} - \mat{P}\vb{y}}^2 + \norm{\mat{P}\vb{y} - \mat{P}_1\vb{y}}^2 = \mathrm{SSW} + \mathrm{SSB}. (2) With y=Xμ+ε\vb{y} = \mat{X}\vb{\mu} + \vb{\varepsilon} and (I−P)X=0(\mat{I} - \mat{P})\mat{X} = \mat{0} we obtain SSW=∥(I−P)ε∥2\mathrm{SSW} = \norm{(\mat{I} - \mat{P})\vb{\varepsilon}}^2. Also (P−P1)y=m+(P−P1)ε(\mat{P} - \mat{P}_1)\vb{y} = \vb{m} + (\mat{P} - \mat{P}_1)\vb{\varepsilon}, with m=(P−P1)Xμ\vb{m} = (\mat{P} - \mat{P}_1)\mat{X}\vb{\mu}, the vector equal to μi−μˉ\mu_i - \bar\mu in group ii (giving P1Xμ=μˉ1\mat{P}_1\mat{X}\vb{\mu} = \bar\mu\vb{1}) whose squared norm is ∑ini(μi−μˉ)2=σ2λ\sum_i n_i(\mu_i - \bar\mu)^2 = \sigma^2\lambda. Complete an orthonormal basis of RN\R^N adapted to the three subspaces (orthonormal basis, as in lesson 19): in those coordinates ε/σ\vb{\varepsilon}/\sigma remains N(0,I)\Normal(\vb{0}, \mat{I}), components on orthogonal subspaces are independent, and the sum of squares of rr normal components of mean mjm_j and variance 1 is χr2\chi^2_r with noncentrality ∑mj2\sum m_j^2. This gives the distributions and independence. (3) is the definition of a noncentral FF, the ratio of two independent χ2\chi^2 divided by their degrees of freedom, with a noncentral numerator. (4) The single-mean model has RSS0=SST\mathrm{RSS}_0 = \mathrm{SST} and the kk-means model has RSS1=SSW\mathrm{RSS}_1 = \mathrm{SSW}, so F=(RSS0−RSS1)/(k−1)RSS1/(N−k)F = \frac{(\mathrm{RSS}_0 - \mathrm{RSS}_1)/(k - 1)}{\mathrm{RSS}_1/(N - k)}, the statistic from lesson 19.

∎

Two special cases are worth remembering. With k=2k = 2, F=t2F = t^2, the square of the two-sample tt statistic with common variance, and the tests coincide. The fraction of explained variation η2=SSB/SST\eta^2 = \mathrm{SSB}/\mathrm{SST} measures effect size (without bias correction: ω2=SSB−(k−1)MSWSST+MSW\omega^2 = \frac{\mathrm{SSB} - (k - 1)\mathrm{MSW}}{\mathrm{SST} + \mathrm{MSW}} is a less biased version). The figure lets you explore the decomposition: dragging a mean changes only SSB\mathrm{SSB}, since group points move together and their within-group deviations do not change.

InteractiveSplitting the sum of squares
Observations by group: within (blue) and between (orange)
grand mean
Total sum-of-squares decomposition
SSB between groups 42 %SSW within 58 %
Density of F2, 21F_{2,\,21} under H0H_0: observed FF and 5 % tail
F = 7.56
  • within group (SSW)
  • between groups (SSB)
  • grand mean
  • rejection region (5 %)
3
8
6.0
SSB | SSW | SST388 | 538 | 926
Mean squares: SSB/2 | SSW/21193.9 | 25.6
FF with (2, 21) df | pp-value7.56 | 0.003
Explained fraction η2=SSB/SST\eta^2 = \text{SSB}/\text{SST}41.9 %
F=7.56F = 7.56 exceeds critical value 3.47: reject H0H_0. Between-group variation (42 % of total) is large relative to within-group variation.
Observations from kk groups with noise σ\sigma in each. Blue lines are deviations of each point from its group mean (they sum to SSW); orange segments run from each group mean to the grand mean (their squares multiplied by nn sum to SSB). Drag the mean bars. At right, the partition of SST and the density of FF under H0H_0 with the observed value. With “No effect”, press “Other data” 20 times: how often does FF exceed the critical value? With n=3n = 3 and a moderate effect, is it detected? Raise nn to 20.

The cell implements ANOVA from the linear model: it calculates sums of squares from means, recalculates them as the difference in residual sums of squares of the two nested models (fitted by least squares on the design matrices), and checks the theorem’s distribution by simulation under H0H_0 and an alternative, with the power given by the noncentral FF.

[ ]One-way ANOVA from the linear model and its exact distributionBrowser
import numpy as np
from scipy import stats

rng = np.random.default_rng(5)
k, n, sigma = 4, 8, 6.0
mu = np.array([100.0, 104.0, 98.0, 110.0])                 # medias verdaderas de cuatro políticas de caché
y = mu[:, None] + sigma * rng.standard_normal((k, n))      # una fila por política
N = k * n

gm, grand = y.mean(1), y.mean()
ssb = n * ((gm - grand) ** 2).sum()
ssw = ((y - gm[:, None]) ** 2).sum()
sst = ((y - grand) ** 2).sum()
F = (ssb / (k - 1)) / (ssw / (N - k))
print(f"SSB = {ssb:.1f}, SSW = {ssw:.1f}, SST = {sst:.1f}  (SSB + SSW - SST = {ssb + ssw - sst:.1e})")
print(f"F = {F:.3f} con ({k - 1}, {N - k}) gl, p = {stats.f.sf(F, k - 1, N - k):.4f}   scipy.f_oneway: {stats.f_oneway(*y)}")

# el mismo test, como comparación de dos modelos lineales anidados
yv = y.ravel()
X1 = np.kron(np.eye(k), np.ones((n, 1)))                   # k columnas indicadoras
X0 = np.ones((N, 1))
def rss(X):
    b, *_ = np.linalg.lstsq(X, yv, rcond=None)
    r = yv - X @ b
    return r @ r
F2 = ((rss(X0) - rss(X1)) / (k - 1)) / (rss(X1) / (N - k))
print(f"F de modelos anidados: {F2:.3f}")

# distribución bajo H0 y bajo la alternativa, con 20000 réplicas del experimento
def f_estadistico(Y):
    g = Y.mean(2)
    b = n * ((g - g.mean(1, keepdims=True)) ** 2).sum(1)
    w = ((Y - g[:, :, None]) ** 2).sum((1, 2))
    return (b / (k - 1)) / (w / (N - k))
R = 20000
rng = np.random.default_rng(50)
F0 = f_estadistico(sigma * rng.standard_normal((R, k, n)))
F1 = f_estadistico(mu[None, :, None] + sigma * rng.standard_normal((R, k, n)))
fc = stats.f.ppf(0.95, k - 1, N - k)
lam = n * ((mu - mu.mean()) ** 2).sum() / sigma ** 2
print(f"\nBajo H0: KS contra F({k - 1},{N - k}): p = {stats.kstest(F0, 'f', args=(k - 1, N - k)).pvalue:.3f};  media {F0.mean():.3f} (teoría {(N - k) / (N - k - 2):.3f});  rechazos al 5 %: {np.mean(F0 > fc):.4f}")
print(f"Bajo la alternativa: lambda = {lam:.2f};  potencia simulada {np.mean(F1 > fc):.4f},  potencia con la F no central {stats.ncf.sf(fc, k - 1, N - k, lam):.4f}")

The decomposition holds to machine rounding, the nested-model FF matches the classical one (F=8.29F = 8.29, p=0.0004p = 0.0004: the four policies do not perform equally), and 20 000 experiments confirm the theorem: under H0H_0 the simulated FF is indistinguishable from F3,28F_{3,28} (Kolmogorov–Smirnov test, p=0.76p = 0.76; mean 1.0761.076, theoretical 1.0771.077), and rejects 5.0 %5.0\ \% of the time; under the cell’s alternative (λ=18.67\lambda = 18.67), simulated power is 0.9370.937 and the noncentral FF gives 0.9370.937. With 8 servers per policy, σ=6\sigma = 6 and differences up to 12 points between policies, the experiment has good power, yet one in sixteen (6.3 %6.3\ \%) would detect nothing. Noncentrality λ=n∑i(μi−μˉ)2/σ2\lambda = n\sum_i(\mu_i - \bar\mu)^2/\sigma^2 is the design lever: it increases with nn and decreases with σ\sigma, and is used to calculate sample sizes (FTestAnovaPower of statsmodels or ncf of scipy.stats).

Contrasts and pairwise comparisons. ANOVA answers “is there any difference?”, rarely the question one actually wants answered. A contrast is a combination ψ=∑iciμi\psi = \sum_i c_i\mu_i with ∑ici=0\sum_i c_i = 0 (for example, μ4−13(μ1+μ2+μ3)\mu_4 - \frac{1}{3}(\mu_1 + \mu_2 + \mu_3), the fourth versus the mean of the others). Its estimator ψ^=∑iciyˉi⋅\hat\psi = \sum_i c_i\bar y_{i\cdot} has variance σ2∑ici2/ni\sigma^2\sum_i c_i^2/n_i and statistic t=ψ^/(s∑ici2/ni)t = \hat\psi/(s\sqrt{\sum_i c_i^2/n_i}) follows tN−kt_{N-k}. Two contrasts are orthogonal if ∑icici′/ni=0\sum_i c_i c_i'/n_i = 0, and a family of k−1k - 1 orthogonal contrasts decomposes SSB\mathrm{SSB} into k−1k - 1 independent one-degree-of-freedom sums, SSψ=ψ^2/∑i(ci2/ni)\mathrm{SS}_\psi = \hat\psi^2/\sum_i(c_i^2/n_i). This idea—one effect, one contrast, one degree of freedom—governs the factorial designs later.

For the (k2)\binom{k}{2} pairwise differences with a simultaneous guarantee, use Tukey’s procedure from lesson 18: intervals yˉi⋅−yˉj⋅±qk, N−k; 1−α s/n\bar y_{i\cdot} - \bar y_{j\cdot} \pm q_{k,\,N-k;\,1-\alpha}\,s/\sqrt n, with qq the studentized-range quantile, cover all true differences simultaneously with exact probability 1−α1 - \alpha in the balanced design. It does not require a significant overall FF and uses the same FWER control correction. The cell implements it from the studentized-range distribution and checks simultaneous coverage.

[ ]Tukey HSD from the studentized range and its simultaneous coverageBrowser
from itertools import combinations
from scipy.stats import studentized_range

s = np.sqrt(ssw / (N - k))                                 # raíz del cuadrado medio dentro
q = studentized_range.ppf(0.95, k, N - k)
hsd = q * s / np.sqrt(n)
print(f"q(0.95; {k}, {N - k}) = {q:.3f};  HSD = {hsd:.2f}   (t sin corregir: {stats.t.ppf(0.975, N - k) * s * np.sqrt(2 / n):.2f})")
for i, j in combinations(range(k), 2):
    d = gm[j] - gm[i]
    print(f"  política {j + 1} - política {i + 1}: {d:6.2f}  IC [{d - hsd:6.2f}, {d + hsd:6.2f}]  {'distinta' if abs(d) > hsd else ''}")

# cobertura simultánea con H0 cierta y con la alternativa: todos los intervalos a la vez
def cobertura(medias, R=20000):
    Y = medias[None, :, None] + sigma * rng.standard_normal((R, k, n))
    g = Y.mean(2)
    w = ((Y - g[:, :, None]) ** 2).sum((1, 2)) / (N - k)
    h = q * np.sqrt(w / n)
    d = g[:, :, None] - g[:, None, :]                       # R x k x k, diferencias estimadas
    verdad = medias[:, None] - medias[None, :]
    return np.mean((np.abs(d - verdad) <= h[:, None, None]).all(axis=(1, 2)))
print(f"cobertura simultánea de los 6 intervalos: {cobertura(mu):.4f} (nominal 0.95)")

The intervals for the six differences cover simultaneously 94.8 %94.8\ \% of the time, despite there being six (in 20 000 experiments, with Monte Carlo error 0.150.15 points). The constant q/2=2.73q/\sqrt{2} = 2.73 exceeds the uncorrected tt (2.052.05): the price of bounding the error across all six comparisons. In this experiment policy 4 (μ4=110\mu_4 = 110) is separated from 1 and 3, but not 2 (estimated difference 3.33.3, with true difference 66), and 3 is separated from 2. Policy 2 versus 1, with true difference 44, is not separated: “not different” does not mean “equal”.

ANOVA assumptions, in order of importance: independence of observations (guaranteed by randomization by unit and violated by pseudoreplication), homoscedasticity (the test is robust with equally sized groups; with unequal sizes and variances it is not, so use Welch’s version, anova_oneway(use_var="unequal") in statsmodels), and normality (least critical: the FF test is robust to distribution shape at moderate sample sizes, and alternatives without a shape assumption are the Kruskal–Wallis test or an FF permutation test, justified directly by randomized assignment).

Randomized complete blocks, paired designs and Latin squares

When there is a known source of variation between units (rack, day, customer type), it is useful to compare treatments within similar units. This is the simplest design that achieves that.

Proof

The design is orthogonal: since each block contains each treatment exactly once, centered treatment-indicator columns are orthogonal to block columns (for treatment i0i_0 and block j0j_0, their inner product is ∑i,j(1[i=i0]−1k)(1[j=j0]−1b)=1−1−1+1=0\sum_{i,j}\big(\mathbb 1[i = i_0] - \tfrac{1}{k}\big)\big(\mathbb 1[j = j_0] - \tfrac{1}{b}\big) = 1 - 1 - 1 + 1 = 0). Then col⁡(X)=span⁡{1}⊕T⊕B\col(\mat{X}) = \spn\{\vb{1}\} \oplus \mathcal{T} \oplus \mathcal{B}, with T\mathcal{T} and B\mathcal{B} of dimensions k−1k - 1 and b−1b - 1, orthogonal to each other and to 1\vb{1}. Projections onto each give SSTr\mathrm{SS}_{\mathrm{Tr}} and SSBl\mathrm{SS}_{\mathrm{Bl}}, and the residual, of dimension kb−1−(k−1)−(b−1)=(k−1)(b−1)kb - 1 - (k - 1) - (b - 1) = (k - 1)(b - 1), gives SSE\mathrm{SSE}. Pythagoras and the previous theorem’s projection argument (the same proof, with three orthogonal subspaces) give (1) and (2); noncentrality is the squared norm of the projection of the mean onto T\mathcal{T}, b∑iτi2b\sum_i\tau_i^2, divided by σ2\sigma^2. For (3), E[MSBl]=σ2+kb−1∑jβj2\E[\mathrm{MS}_{\mathrm{Bl}}] = \sigma^2 + \frac{k}{b-1}\sum_j\beta_j^2 and E[MSE]=σ2\E[\mathrm{MSE}] = \sigma^2; the error variance of a completely randomized design with bkbk units would be σ2+k∑jβj2bk−1\sigma^2 + \frac{k\sum_j\beta_j^2}{bk - 1} (the mean of the unblocked squares), which is E[(b−1)MSBl+b(k−1)MSE]/(bk−1)\E[(b - 1)\mathrm{MS}_{\mathrm{Bl}} + b(k - 1)\mathrm{MSE}]/(bk - 1). Replacing mean squares by their expectations gives the ratio.

∎

With one comparison treatment, k=2k = 2, the block is a pair, and RCBD is the paired design: statistic FTrF_{\mathrm{Tr}} is the square of the paired tt for within-pair differences (the same server before and after, two users with the same profile). The cell builds an RCBD with k=4k = 4 configurations and b=6b = 6 very different racks, analyzes it with and without blocks, and verifies by simulation that RE^\widehat{\mathrm{RE}} predicts the gain.

[ ]Complete blocks: decomposition, relative efficiency and the paired caseBrowser
rng = np.random.default_rng(12)
k, b = 4, 6
tau = np.array([0.0, 3.0, -2.0, 6.0])                       # efectos de cuatro configuraciones
sigma_b, sigma_e = 10.0, 4.0                                # desigualdad entre racks y ruido propio
beta = rng.normal(0, sigma_b, b)
y = 100 + tau[:, None] + beta[None, :] + sigma_e * rng.standard_normal((k, b))    # k x b, un dato por tratamiento y bloque

def anova_bloques(y):
    """Sumas de cuadrados y F de tratamientos de un RCBD (y es k x b: una observación por tratamiento y bloque)."""
    k, b = y.shape
    gr = y.mean()
    sstr = b * ((y.mean(1) - gr) ** 2).sum()
    ssbl = k * ((y.mean(0) - gr) ** 2).sum()
    sse = ((y - y.mean(1, keepdims=True) - y.mean(0, keepdims=True) + gr) ** 2).sum()
    return sstr, ssbl, sse, (sstr / (k - 1)) / (sse / ((k - 1) * (b - 1)))

sstr, ssbl, sse, F_blq = anova_bloques(y)
sst = ((y - y.mean()) ** 2).sum()
dfe = (k - 1) * (b - 1)
F_crd = (sstr / (k - 1)) / ((ssbl + sse) / (k * (b - 1)))   # el mismo experimento analizado sin bloques
print(f"SST = {sst:.1f} = Tr {sstr:.1f} + Bl {ssbl:.1f} + Error {sse:.1f}")
print(f"F por bloques = {F_blq:.2f} (p = {stats.f.sf(F_blq, k - 1, dfe):.4f});  F sin bloques = {F_crd:.2f} (p = {stats.f.sf(F_crd, k - 1, k * (b - 1)):.4f})")
msbl, mse = ssbl / (b - 1), sse / dfe
RE = ((b - 1) * msbl + b * (k - 1) * mse) / ((b * k - 1) * mse)
print(f"eficiencia relativa estimada del bloqueo: {RE:.2f}")

# comprobación por simulación: varianza de (media del trat. 4 - media del trat. 1) con y sin bloquear
R = 20000
bet = rng.normal(0, sigma_b, (R, b))
rack = np.repeat(np.arange(b), k)                           # rack de cada una de las 24 unidades
nivel = bet[:, rack] + sigma_e * rng.standard_normal((R, b * k))           # rendimiento sin tratar de cada unidad
orden = np.argsort(np.argsort(rng.random((R, b * k)), axis=1), axis=1)
trat_crd = orden // b                                       # asignación completa: 6 unidades por tratamiento
d_crd = (nivel * (trat_crd == 3)).sum(1) / b - (nivel * (trat_crd == 0)).sum(1) / b
e = sigma_e * rng.standard_normal((R, k, b))
d_rcbd = (e[:, 3] - e[:, 0]).mean(1)                        # por bloques: el rack se cancela dentro de cada bloque
teor = 1 + sigma_b**2 * (b * k - k) / ((b * k - 1) * sigma_e**2)   # exacto con 24 unidades en racks de k = 4
print(f"Var(diferencia): sin bloquear {d_crd.var():.2f}, con bloques {d_rcbd.var():.2f}; cociente {d_crd.var() / d_rcbd.var():.2f}  (exacto {teor:.2f}; límite 1 + sb^2/se^2 = {1 + sigma_b**2 / sigma_e**2:.2f})")

# el caso k = 2 es el t pareado: F = t^2
t_par = stats.ttest_rel(y[3], y[0])
F2 = anova_bloques(y[[0, 3]])[3]
print(f"k = 2: t pareado = {t_par.statistic:.3f}, t^2 = {t_par.statistic ** 2:.3f};  F de bloques completos = {F2:.3f}")

The decomposition divides SST=2579\mathrm{SST} = 2579 into treatments, blocks and error, and most of what is not treatments is between-rack variation (22232223 versus error 205205). Thus the same experiment gives F=3.69F = 3.69 analyzed by blocks and F=0.42F = 0.42 if they are ignored: blocking turns an invisible effect (p=0.74p = 0.74) into a significant one (p=0.036p = 0.036), without a single extra unit. The price is small: error has (k−1)(b−1)=15(k - 1)(b - 1) = 15 degrees of freedom rather than k(b−1)=20k(b - 1) = 20. Estimated relative efficiency is 7.857.85, and simulation confirms the order of magnitude: an unblocked comparison has variance 34.334.3 and a blocked one 5.315.31, a ratio of 6.466.46. The exact value, using the same calculation as the blocking theorem (now with N=24N = 24 units in racks of s=4s = 4), is 1+σb2σe2N−sN−1=6.431 + \frac{\sigma_b^2}{\sigma_e^2}\frac{N - s}{N - 1} = 6.43, tending to 1+σb2/σe2=7.251 + \sigma_b^2/\sigma_e^2 = 7.25 with many racks. On the last line, with two treatments the blocked analysis is the paired tt: t2=Ft^2 = F.

Two sources of variation: the Latin square. If two nuisance factors are known (rack and time of day), both can be blocked with a Latin square p×pp \times p: rows and columns index the two blocking factors, and the pp treatments are arranged so each appears exactly once in each row and column. With p2p^2 units, p−1p - 1 treatment effects are estimated, leaving (p−1)(p−2)(p - 1)(p - 2) error degrees of freedom. This economy requires no interactions among the three sources (rows, columns and treatments enter additively), an assumption that must be justified by knowledge of the problem because data from a single square cannot check it. Randomization chooses a square at random: start with any square and randomly permute rows, columns and symbols. (This does not necessarily reach all Latin squares with equal probability; for p≥4p \ge 4 several classes are not equivalent under permutations, and Fisher and Yates suggested starting from a reduced square selected at random from all of them. For validity of analysis, permutation of rows, columns and symbols suffices.) The cell constructs one and checks the degrees-of-freedom count.

[ ]A randomized Latin square and its analysisBrowser
def cuadrado_latino(p, rng):
    L = (np.arange(p)[:, None] + np.arange(p)[None, :]) % p       # cíclico: cada símbolo una vez por fila y columna
    return rng.permutation(p)[L[rng.permutation(p)][:, rng.permutation(p)]]   # permutar filas, columnas y símbolos

p = 4
L = cuadrado_latino(p, rng)
print(L)
latino = all(sorted(L[i]) == list(range(p)) and sorted(L[:, i]) == list(range(p)) for i in range(p))
print("cada símbolo una vez por fila y por columna:", latino)

fila, col = np.repeat(np.arange(p), p), np.tile(np.arange(p), p)
trat = L.ravel()
def dummies(v, q):
    return np.eye(q)[v][:, 1:]
X = np.column_stack([np.ones(p * p), dummies(fila, p), dummies(col, p), dummies(trat, p)])
print(f"unidades {p * p}, rango del diseño {np.linalg.matrix_rank(X)} = 1 + 3(p - 1) = {1 + 3 * (p - 1)}  =>  gl de error {p * p - np.linalg.matrix_rank(X)} = (p-1)(p-2) = {(p - 1) * (p - 2)}")

yl = 50 + 2 * np.arange(p)[trat] + 3 * rng.normal(size=p)[fila] + 4 * rng.normal(size=p)[col] + rng.normal(0, 1, p * p)   # efecto lineal de tratamiento
def rss_l(M):
    bb, *_ = np.linalg.lstsq(M, yl, rcond=None)
    r = yl - M @ bb
    return r @ r
M0 = X[:, : 1 + 2 * (p - 1)]                                    # sin tratamientos
Fl = ((rss_l(M0) - rss_l(X)) / (p - 1)) / (rss_l(X) / ((p - 1) * (p - 2)))
print(f"test F de tratamientos: F = {Fl:.1f} con ({p - 1}, {(p - 1) * (p - 2)}) gl, p = {stats.f.sf(Fl, p - 1, (p - 1) * (p - 2)):.5f}")

With p=4p = 4, 16 units are needed and only 6 error degrees of freedom remain: a small square has little power unless replicated (several squares with new rows and columns). These are design limitations in general, so the practical rule is block on what you know matters and is known beforehand; leave everything else to randomization.

Two-way ANOVA and interactions

So far there has been one factor. With two, AA with aa levels and BB with bb levels, applied in every combination with nn replicates in each cell, the model (with yijky_{ijk} the response of replicate kk in cell (i,j)(i, j)) is

yijk=μ+αi+βj+(αβ)ij+εijk,εijk∼iidN(0,σ2),y_{ijk} = \mu + \alpha_i + \beta_j + (\alpha\beta)_{ij} + \varepsilon_{ijk}, \qquad \varepsilon_{ijk} \iid \Normal(0, \sigma^2),

with constraints ∑iαi=∑jβj=0\sum_i\alpha_i = \sum_j\beta_j = 0 and ∑i(αβ)ij=∑j(αβ)ij=0\sum_i(\alpha\beta)_{ij} = \sum_j(\alpha\beta)_{ij} = 0. If cell means are μij\mu_{ij}, the terms are αi=μi⋅−μ⋅⋅\alpha_i = \mu_{i\cdot} - \mu_{\cdot\cdot}, βj=μ⋅j−μ⋅⋅\beta_j = \mu_{\cdot j} - \mu_{\cdot\cdot} and the interaction (αβ)ij=μij−μi⋅−μ⋅j+μ⋅⋅(\alpha\beta)_{ij} = \mu_{ij} - \mu_{i\cdot} - \mu_{\cdot j} + \mu_{\cdot\cdot}, what remains of the cell mean after row and column effects are removed. All interactions being zero means exactly that the simple effects (the effect of AA at each level of BB) are equal, that is, the AA profiles for each level of BB are parallel.

Proof

This is one-way ANOVA with abab cell levels, SSBceldas=SSA+SSB+SSAB\mathrm{SSB}_{\text{celdas}} = \mathrm{SS}_A + \mathrm{SS}_B + \mathrm{SS}_{AB}, and the partition of that subspace of dimension ab−1ab - 1 into three orthogonal subspaces of dimensions a−1a - 1, b−1b - 1 and (a−1)(b−1)(a - 1)(b - 1). Orthogonality follows from balance: row, column and interaction effects have zero means across rows and columns, and the inner product of two decomposes into sums that vanish. The rest is the projection argument from the one-way theorem.

∎

With n=1n = 1 there is no error: SSE=0\mathrm{SSE} = 0 and interaction cannot be separated from noise (one must assume it does not exist; see the warning on unreplicated experiments). With unequal cell sizes, factor sums of squares cease to be orthogonal and their values depend on fitting order (types I, II and III of statsmodels): with interaction in the model, the safe approach is to test explicit nested models, as lesson 19 does.

Above all, what matters is what the terms mean. With 2×22 \times 2, writing μij\mu_{ij} with ii the scheduler (1 old, 2 new) and jj the load (1 CPU, 2 I/O), the main effect of AA is 12[(μ21−μ11)+(μ22−μ12)]\frac{1}{2}[(\mu_{21} - \mu_{11}) + (\mu_{22} - \mu_{12})], the average of the simple effects, and the interaction is 12[(μ22−μ12)−(μ21−μ11)]\frac{1}{2}[(\mu_{22} - \mu_{12}) - (\mu_{21} - \mu_{11})], half their difference. A main effect summarizes an experiment well only if there is no interaction. If there is, there are as many effects of AA as levels of BB, and averaging them is a decision (which may not correspond to the population of interest), not a result.

InteractiveInteraction plot
Mean p95 latency (ms) for each combination: drag the points
CPUI/Omarginal mean of A
Effect of changing scheduler at each level of the other factor, and its average
−20.020.00.0A with CPUA with I/Omain effect
  • CPU load
  • I/O load
  • marginal mean (main effect)
Effect shown in right panel
10
10
Main effect A | B | interaction AB0.0 | −20.0 | 20.0
Noncentrality λ=n effect2/σ2\lambda = n\,\text{effect}^2/\sigma^2 of A | B | AB0.0 | 40.0 | 40.0
F-test power (5 %, df 1 and 36) for A | B | AB5 % | 100 % | 100 %
Qualitative interaction. The effect of A changes sign across levels (−20.0 and 20.0). Its main effect, 0.0, averages effects that cancel; do not interpret it alone.
Mean p95 latency (ms) of a service for the four combinations of scheduler (old or new) and load type (CPU or I/O). Drag the four points. The dashed black line joins the marginal means for each scheduler: its slope is the main effect. At right are the two simple effects and their average. Start with “Crossing”: what is the scheduler's main effect, and what happens to each load? Switch to “Additive” and lower the noise: how much power does the interaction test have? With “One cell”, what main effect and interaction does it have?

The “Crossing” case is most instructive: the marginal means of both schedulers are identical (100 and 100), the main effect is zero, and its test will reject only 5 %5\ \% of the time (its level) regardless of replication, yet the new scheduler reduces latency by 20 ms on CPU loads and increases it by 20 ms on I/O loads. A decision based only on the main effect would be “it makes no difference”, when the truth is “it depends greatly on the load”. Interaction is also as hard (or easy) to detect as a main effect of the same size: in design 2×22 \times 2 both are orthogonal contrasts with the same variance. If interaction is large, the units of analysis are no longer the two factors separately, but their combinations.

[ ]Two factors with crossing interaction: the main effect disappearsBrowser
rng = np.random.default_rng(1)
a, b, n = 2, 2, 10
mu2 = np.array([[120.0, 80.0],                              # filas: planificador viejo / nuevo; columnas: carga CPU / E/S
                [100.0, 100.0]])
y = mu2[:, :, None] + 10 * rng.standard_normal((a, b, n))
gr = y.mean()
mi, mj, mij = y.mean((1, 2)), y.mean((0, 2)), y.mean(2)
ssa = b * n * ((mi - gr) ** 2).sum()
ssb = a * n * ((mj - gr) ** 2).sum()
ssab = n * ((mij - mi[:, None] - mj[None, :] + gr) ** 2).sum()
sse = ((y - mij[:, :, None]) ** 2).sum()
sst = ((y - gr) ** 2).sum()
dfe = a * b * (n - 1)
mse = sse / dfe
print(f"SST {sst:.0f} = A {ssa:.0f} + B {ssb:.0f} + AB {ssab:.0f} + error {sse:.0f}")
for nom, ss, gl in [("planificador A", ssa, a - 1), ("carga B", ssb, b - 1), ("interacción AB", ssab, (a - 1) * (b - 1))]:
    F = ss / gl / mse
    print(f"  {nom:15s} F = {F:7.2f}  p = {stats.f.sf(F, gl, dfe):.4g}")
# efectos simples del planificador en cada carga (diferencia nuevo - viejo), con IC al 95 %
for j, carga in enumerate(["CPU", "E/S"]):
    d = mij[1, j] - mij[0, j]
    se = np.sqrt(2 * mse / n)
    tq = stats.t.ppf(0.975, dfe)
    print(f"  efecto del planificador con carga {carga}: {d:6.1f}  IC95 [{d - tq * se:6.1f}, {d + tq * se:6.1f}]")
print(f"  efecto principal del planificador: {mij[1].mean() - mij[0].mean():.1f}")

The analysis says the same as the plot: the scheduler has no main effect (p=0.82p = 0.82), load does (p=1.7×10−7p = 1.7 \times 10^{-7}), and interaction is enormous (p=1.4×10−9p = 1.4 \times 10^{-9}). Simple effects and their intervals give the full story: −25.0-25.0 ms for CPU load and +23.6+23.6 ms for I/O load, with intervals excluding zero and pointing in opposite directions. Interpreting a main effect without looking at interaction answers a question nobody asked.

2ᵏ factorial designs

With kk factors, changing them one at a time is inefficient (each effect is estimated using only some runs) and cannot reveal interactions. The alternative is to vary all at once.

Proof

(1) Since xrj2=1x_{rj}^2 = 1, χuχv=χu △ v\chi_u\chi_v = \chi_{u\,\triangle\,v} (the product of two columns is the column of the symmetric difference). For u≠∅u \ne \varnothing there is a factor j∈uj \in u, and in the balanced design half the runs have xrj=+1x_{rj} = +1 and half −1-1, for each combination of the other factors, so ∑rχu(r)=0\sum_r\chi_u(r) = 0. With u=v △ wu = v\,\triangle\,w we obtain χv⊤χw=∑rχv△w(r)=0\chi_v\T\chi_w = \sum_r\chi_{v\triangle w}(r) = 0 if v≠wv \ne w, and NN if v=wv = w. (2) The design matrix has orthogonal columns of norm 2^2 NN, so X⊤X=NI\mat{X}\T\mat{X} = N\mat{I}, and β^=X⊤y/N\hat{\vb{\beta}} = \mat{X}\T\vb{y}/N: each coefficient θw/2\theta_w/2 is estimated by 1Nχw⊤y\frac{1}{N}\chi_w\T\vb{y}, which is θ^w/2\hat\theta_w/2, with variance σ2/N\sigma^2/N and zero covariances; hence Var⁡(θ^w)=4σ2/N\Var(\hat\theta_w) = 4\sigma^2/N. (3) In the one-factor-at-a-time alternative, the effect of AA compares the baseline configuration with AA changed: each receives N/(k+1)N/(k + 1) runs, and the variance of the difference is 2σ2(k+1)/N2\sigma^2(k + 1)/N. The ratio to 4σ2/N4\sigma^2/N is (k+1)/2(k + 1)/2. The factorial design also estimates all interactions, which the alternative cannot.

∎

Point (3) explains hidden replication: without repeating any combination, every run participates in estimating every effect. The price is that an unreplicated 2k2^k factorial (m=1m = 1) has no degrees of freedom to estimate σ2\sigma^2: all 2k−12^k - 1 contrasts are estimated, leaving nothing for error. The effect sparsity principle is then used (a few effects are active and the rest noise): plot effects on a Daniel half-normal plot (the absolute value of each effect against its half-normal quantile if all were noise), where null effects lie on a line from the origin and active effects rise away from it. Lenth’s estimator also provides a standard error without replicates: s0=1.5 mediana ∣θ^w∣s_0 = 1.5\,\mathrm{mediana}\,\lvert\hat\theta_w\rvert and PSE=1.5 mediana{∣θ^w∣:∣θ^w∣<2.5s0}\mathrm{PSE} = 1.5\,\mathrm{mediana}\{\lvert\hat\theta_w\rvert : \lvert\hat\theta_w\rvert < 2.5 s_0\}, discarding active effects. The cell implements it.

[ ]An unreplicated 2^4 factorial: effects, Lenth and a half-normal plotBrowser
from itertools import product
import matplotlib.pyplot as plt

rng = np.random.default_rng(5)
k = 4
runs = np.array(list(product([-1, 1], repeat=k)))[:, ::-1]        # A varía más rápido; 16 corridas
N = len(runs)
letras = "ABCD"
def columna(w):
    return np.prod([runs[:, i] for i in range(k) if w >> i & 1], axis=0) if w else np.ones(N)
def nombre(w):
    return "".join(letras[i] for i in range(k) if w >> i & 1)

verdad = {1: 10.0, 4: -6.0, 5: 5.0, 8: 2.0}                       # A = 10, C = -6, AC = 5, D = 2; el resto, cero
y = 50 + sum(th / 2 * columna(w) for w, th in verdad.items()) + 1.5 * rng.standard_normal(N)
ef = {w: 2 / N * columna(w) @ y for w in range(1, 2 ** k)}          # los 15 efectos: A, B, AB, C, ...
c = np.abs(np.array(list(ef.values())))
s0 = 1.5 * np.median(c)
pse = 1.5 * np.median(c[c < 2.5 * s0])
me = stats.t.ppf(0.975, len(c) / 3) * pse                          # margen de error de Lenth (gl = m/3)
print(f"PSE de Lenth = {pse:.2f};  margen de error al 95 % = {me:.2f};  (sd verdadera de un efecto: 2 sigma/sqrt(N) = {2 * 1.5 / np.sqrt(N):.2f})")
for w in sorted(ef, key=lambda w: -abs(ef[w]))[:7]:
    print(f"  {nombre(w):4s} estimado {ef[w]:6.2f}   verdad {verdad.get(w, 0.0):5.1f}   {'ACTIVO' if abs(ef[w]) > me else ''}")

orden = np.argsort(c)
cuant = stats.norm.ppf(0.5 + 0.5 * (np.arange(1, len(c) + 1) - 0.5) / len(c))
plt.figure(figsize=(5.6, 3.4))
plt.plot(cuant, c[orden], "o", color="#2a78d6")
for pos in range(len(c) - 4, len(c)):
    plt.annotate(nombre(orden[pos] + 1), (cuant[pos], c[orden[pos]]), textcoords="offset points", xytext=(-16, 3))
plt.plot([0, cuant[-1]], [0, pse * cuant[-1]], "--", color="#52514e")             # recta del ruido: |efecto| = PSE * cuantil
plt.xlabel("cuantil seminormal"); plt.ylabel("|efecto|"); plt.tight_layout(); plt.show()

The estimated effects recover the true structure: A, C and interaction AC stand out clearly (9.89.8, −6.1-6.1 and 5.05.0 versus 1010, −6-6 and 55); D (2.52.5 versus 22) falls below Lenth’s margin of error and appears inactive, a real but small effect this experiment cannot distinguish from noise; and the other eleven effects, all null, form the cloud near the origin. Each effect’s standard deviation, 2σ/N=0.752\sigma/\sqrt{N} = 0.75, should govern their spread; Lenth’s PSE (1.281.28), obtained without a single replicate, is of that order (somewhat larger because of contamination by active effects and variability of a median of 15 values). The half-normal plot’s line starts at the origin with slope close to PSE, and effects departing from it are active.

Fractions: paying with aliases. With k=7k = 7 factors, a complete 272^7 requires 128 runs to estimate 127 effects, almost all high-order interactions that, by the hierarchy principle, probably do not exist. A regular fraction 2k−p2^{k-p} keeps a fraction 2−p2^{-p} of runs, defined by pp generators: run the full factorial of k−pk - p base factors and define each of the remaining pp as a product of columns, for example D=ABCD = ABC in 24−12^{4-1}. The consequences are algebraic. If D=ABCD = ABC in all runs, multiplying by DD gives I=ABCDI = ABCD: the defining relation. The set GG of words with χg≡1\chi_g \equiv \vb{1} in the fraction (those generated by relations and their products) is the defining group, closed under symmetric difference, with ∣G∣=2p|G| = 2^p.

Proof

(1) With u=v△wu = v\triangle w, χvχw=χu\chi_v\chi_w = \chi_u; hence χv=χw\chi_v = \chi_w on the fraction if and only if χu≡1\chi_u \equiv 1 there. Words in GG satisfy χg≡1\chi_g \equiv 1 by construction. Conversely, fraction HH is a subgroup of the group {±1}k\{\pm 1\}^k of 2k2^k combinations, of index 2p2^p, and characters χu\chi_u equal to 11 throughout HH form its annihilator, of size 2k/∣H∣=2p2^k/|H| = 2^p; since GG is contained in it and has the same size, they coincide. (2) Write the full model and notice that on the fraction χv=χw\chi_v = \chi_w for v,wv, w in the same class: coefficients of a class appear only summed, and by orthogonality of distinct columns, ℓ^w=2Nfχw⊤y\hat\ell_w = \frac{2}{N_f}\chi_w\T\vb{y} has expectation ∑v∈w△Gθv\sum_{v \in w\triangle G}\theta_v and variance 4σ2/Nf4\sigma^2/N_f. (3) If vv and ww are aliases, v△w∈Gv\triangle w \in G has length ≥R\ge R, and ∣v△w∣≤∣v∣+∣w∣=a+b|v\triangle w| \le |v| + |w| = a + b.

∎

The theorem says what is being paid: with a resolution-III fraction one measures, instead of main effect AA, the sum A+BDA + BD (for example), and if a real interaction BDBD exists, the “effect of AA” is contaminated by exactly that amount. The figure shows it: select the generator and a real interaction, and compare the estimated contrast with the true main effect.

InteractiveAliasing in a fractional factorial
Design table D = AB: 8 runs
runABCDy
1−−−+46.8
2+−−−56.3
3−+−−40.5
4++−+55.3
5−−++45.9
6+−+−58.9
7−++−38.7
8++++58.2
Column D (magenta) is the product of columns A and B: it is therefore not independent of them.
What each contrast measures (bar) versus the target (diamond: true main effect)
−15−10−5051015ℓA = A + BD14.2ℓB = B + AD−3.8ℓC = C + ABCD0.7ℓD = D + AB3.0ℓAC = AC + BCD2.0ℓBC = BC + ACD−0.1ℓCD = CD + ABC0.3
  • clean main effect
  • contaminated main effect
  • class with real interaction
  • other contrasts (interactions)
  • true main effect
Fraction generator
8.0
1.00
Defining relationI = ABD
Resolution | runs | estimable effectsIII | 8 of 16 | 7 + mean
Aliases of A | BA + BD | B + AD
A contrast: estimated | true main effect14.20 | 6.0
Contamination. With generator D = AB (resolution III), the contrast of A measures A + BD. Real interaction BD = 8.0 enters a main effect, biasing it by 8.0.
An eight-run 24−12^{4-1} fraction. At left, the design table: column D (magenta) is the product of columns for other factors. At right, the seven estimable contrasts, with the alias sum each measures (for example, ℓA=A+BD\ell_A = A + BD), the estimate (bar) and, for main effects, the true value (diamond). True main effects are A=6A = 6, B=−4B = -4, C=0C = 0 and D=3D = 3, and you choose one real interaction. Start with D=ABD = AB (resolution III) and real interaction BD=8BD = 8: what does ℓA\ell_A measure? Switch to D=ABCD = ABC (resolution IV): where did the contamination go? With D=ABCD = ABC, which real interaction contaminates which contrast?

With D=ABD = AB (I=ABDI = ABD, resolution III), the contrast for AA measures A+BD=6+8=14A + BD = 6 + 8 = 14, more than twice the true effect. Switching to D=ABCD = ABC (I=ABCDI = ABCD, resolution IV), ℓA=A+BCD\ell_A = A + BCD: interaction BDBD now contaminates interaction ACAC (its alias), and all four main effects remain clean as long as there are no three-factor interactions. This is the screening-design tradeoff: many factors, few runs, betting that high-order interactions are small. When a fraction gives an ambiguous signal, it is completed: add the complementary fraction (I=−ABCDI = -ABCD here, obtained by changing the sign of the generated column), and together the halves form the complete 242^4 without aliases. Smaller fractions use foldover: repeating the fraction with the signs of all columns changed converts resolution III to resolution IV, separating each main effect from the two-factor interactions confounded with it. (Folding a resolution-IV fraction like this does not help: its defining words have even length and do not change sign, so the same runs would be repeated.) In machine learning, hyperparameter grid search is a complete factorial, and fractions and random designs make it cheaper without losing what matters.

[ ]A 2^(4-1) half fraction: D = AB versus D = ABC with a real BD interactionBrowser
runs3 = np.array(list(product([-1, 1], repeat=3)))[:, ::-1]        # factorial completo en A, B, C
def palabra(w):
    return "".join(sorted(w))
def alias(w, relacion):                                            # w * relación definidora (diferencia simétrica)
    return palabra(set(w) ^ set(relacion))

theta_A, theta_BD = 6.0, 8.0                                       # solo existen un efecto principal y UNA interacción
for gen in ("AB", "ABC"):
    cols = {c: runs3[:, "ABC".index(c)] for c in "ABC"}
    cols["D"] = np.prod([cols[c] for c in gen], axis=0)           # D = producto de las columnas del generador
    rel = palabra("D" + gen)
    ya = 50 + theta_A / 2 * cols["A"] + theta_BD / 2 * cols["B"] * cols["D"]
    estim = []
    for _ in range(3000):
        y = ya + rng.standard_normal(8)
        estim.append(2 / 8 * cols["A"] @ y)                        # contraste de A en 8 corridas
    print(f"D = {gen}: I = {rel};  alias de A: {alias('A', rel)};  alias de BD: {alias('BD', rel)}")
    print(f"   contraste de A: media {np.mean(estim):6.2f} (verdad: A = {theta_A}); sd {np.std(estim):.2f}  (teoría: 2 sigma/sqrt(8) = {2 / np.sqrt(8):.2f})")

Simulation confirms this: with D=ABD = AB the AA contrast averages 13.9813.98 (6+8=146 + 8 = 14), and with D=ABCD = ABC it averages 6.036.03, the true value; in both cases its standard deviation is the theoretical 2σ/8=0.712\sigma/\sqrt{8} = 0.71 (0.690.69 and 0.720.72 in simulation), so aliasing changes the center, not the spread.

Covariate adjustment: ANCOVA and CUPED

Randomization guarantees that, on average, groups are equal in everything, including unmeasured factors. “On average” does not mean “in this experiment”: in a particular realization the two groups’ prior means differ by chance, and that difference enters the estimated effect as noise. If a variable XX measured before treatment and correlated with the response is known for each unit (last week’s throughput, a user’s historical spending), the part attributable to this chance imbalance can be subtracted from the estimate.

Proof

(1) Since XiX_i is independent of WiW_i, E[Xˉ1−Xˉ0]=0\E[\bar X_1 - \bar X_0] = 0; and E[Yˉ1−Yˉ0]=τ\E[\bar Y_1 - \bar Y_0] = \tau. (2) τ^θ\hat\tau_\theta is the difference in means of Zi=Yi−θXiZ_i = Y_i - \theta X_i between independent arms of nn units, so Var⁡(τ^θ)=2Var⁡(Z)/n\Var(\hat\tau_\theta) = 2\Var(Z)/n, and Var⁡(Z)=Var⁡(Y(0)−θX)=σY2−2θσXY+θ2σX2\Var(Z) = \Var(Y(0) - \theta X) = \sigma_Y^2 - 2\theta\sigma_{XY} + \theta^2\sigma_X^2 (the term τW\tau W is constant within each arm). (3) It is a quadratic in θ\theta minimized at σXY/σX2\sigma_{XY}/\sigma_X^2, and substitution gives σY2−σXY2/σX2=σY2(1−ρ2)\sigma_Y^2 - \sigma_{XY}^2/\sigma_X^2 = \sigma_Y^2(1 - \rho^2). (4) θ^\hat\theta is a continuous function of sample moments, which converge by the law of large numbers; since Xˉ1−Xˉ0=Op(n−1/2)\bar X_1 - \bar X_0 = \bigO_p(n^{-1/2}), error (θ^−θ∗)(Xˉ1−Xˉ0)(\hat\theta - \theta^*)(\bar X_1 - \bar X_0) is op(n−1/2)o_p(n^{-1/2}) and does not alter the limiting distribution (Slutsky’s lemma).

∎

Interpret this as conditioning: if treatment users in this experiment had, by bad luck, higher historical spending (Xˉ1>Xˉ0\bar X_1 > \bar X_0) and historical spending predicts current spending, part of the observed difference is that imbalance, which adjustment removes. The larger ρ\rho, the more of the difference is predictable and the less noise remains. Two useful readings: with ρ=0.7\rho = 0.7, 49 %49\ \% of variance is removed, and dependence is quadratic, so ρ=0.3\rho = 0.3 removes only 9 %9\ \% and is not worth the effort; and the sample size needed for given power is multiplied by (1−ρ2)(1 - \rho^2) because it is proportional to variance.

InteractiveCUPED: the variance that disappears
Prior metric XX versus experiment metric YY (one sample)
fitted slope θ = 0.75
Estimated effect across 400 repeated experiments (line: true effect)
  • control arm
  • treatment arm
  • unadjusted
  • CUPED
  • true effect
0.70
200
0.20
Standard error, unadjusted | CUPED (theory)0.100 | 0.071
Simulated SD, unadjusted | CUPED0.095 | 0.069
95 % CI half-width: unadjusted | CUPED±0.196 | ±0.140
nn per arm for 80 % power: unadjusted | CUPED393 | 201
Mean estimates: unadjusted | CUPED (truth)0.192 | 0.192 (0.20)
Unbiased and more precise. With ρ=0.70\rho = 0.70 variance is multiplied by 1−ρ2=0.5101 - \rho^2 = 0.510 (simulated: 0.521). The same power needs 49 % fewer users.
Two arms of nn users with a prior metric XX and experiment metric YY, with correlation ρ\rho. At left, a sample with the line of slope θ^\hat\theta. At right, the estimated effect distribution in 400 repeated experiments, unadjusted (violet) and with CUPED (aquamarine). Increase ρ\rho from 0 to 0.95: how does the aquamarine curve's width change relative to violet, and how much does the sample size needed to detect δ\delta change? With ρ=0\rho = 0, does adjustment gain or lose? Now turn on post-treatment covariate measurement, shifted by treatment: where does the adjusted estimator move?

Besides reducing variance, adjustment costs nothing with ρ=0\rho = 0: there is no gain, but no bias either (with small samples it loses one degree of freedom estimating θ\theta, an effect of order 1/n1/n). What destroys the method is the same condition that justifies it: XX must be independent of assignment, guaranteed only if measured before. If XX is a consequence of treatment (time on page, measured during the experiment), E[Xˉ1−Xˉ0]=γ≠0\E[\bar X_1 - \bar X_0] = \gamma \ne 0 and adjustment subtracts θγ\theta\gamma from the effect: E[τ^θ]=τ−θγ\E[\hat\tau_\theta] = \tau - \theta\gamma. This is the same mistake as controlling for a mediator in an observational study (bad controls), and randomization does not fix it.

ANCOVA and CUPED agree in essentials. Regression Y∼1+W+XY \sim 1 + W + X estimates θ\theta using the within-group slope and is the same adjustment; with a centered covariate and an interaction W⋅XW \cdot X, the estimator is asymptotically as good as or better than the unadjusted estimator even if the relationship between XX and YY is neither linear nor constant (Lin, 2013, following Freedman’s 2008 criticisms), unlike regression without interaction. XX need not be the same metric: any predictor of YY built using pre-experiment data (even a machine-learning model) works, and variance reduction is the fraction of Var⁡(Y)\Var(Y) explained by the predictor, the ρ2\rho^2 of the theorem.

[ ]CUPED: more precision without bias, and the bias of adjusting for a post-treatment covariateBrowser
rng = np.random.default_rng(8)

def experimento(n, rho, delta, rng, posterior=False):
    t = np.r_[np.zeros(n), np.ones(n)]
    x = rng.standard_normal(2 * n)                                   # métrica previa
    y = rho * x + np.sqrt(1 - rho ** 2) * rng.standard_normal(2 * n) + delta * t
    if posterior:
        x = x + 0.8 * t                                              # medida DESPUÉS y desplazada por el tratamiento
    return t, x, y

def efecto(t, x, y, cuped):
    if cuped:
        theta = np.cov(x, y)[0, 1] / x.var(ddof=1)                   # Cov(X, Y) / Var(X) con los dos brazos
        y = y - theta * (x - x.mean())
    a, c = y[t == 1], y[t == 0]
    return a.mean() - c.mean(), np.sqrt(a.var(ddof=1) / len(a) + c.var(ddof=1) / len(c))

n, rho, delta = 2000, 0.7, 0.1
t, x, y = experimento(n, rho, delta, rng)
for nombre, cuped in [("sin ajuste", False), ("CUPED", True)]:
    d, se = efecto(t, x, y, cuped)
    print(f"{nombre:10s} efecto {d:6.3f}  EE {se:.4f}  IC95 [{d - 1.96 * se:6.3f}, {d + 1.96 * se:6.3f}]")
Xr = np.column_stack([np.ones(2 * n), t, x])
print(f"ANCOVA (regresión y ~ 1 + t + x): efecto {np.linalg.lstsq(Xr, y, rcond=None)[0][1]:.4f}   (CUPED: {efecto(t, x, y, True)[0]:.4f})")

R = 1500
def par(post):
    d = experimento(500, rho, delta, rng, post)
    return [efecto(*d, False)[0], efecto(*d, True)[0]]
for post in (False, True):
    est = np.array([par(post) for _ in range(R)])
    print(f"covariable {'posterior' if post else 'previa   '}: media sin ajuste {est[:, 0].mean():.3f}, media CUPED {est[:, 1].mean():.3f}  (verdad {delta});  var CUPED / var sin ajuste = {est[:, 1].var() / est[:, 0].var():.3f}")
print(f"1 - rho^2 = {1 - rho ** 2:.3f}")

In the experiment with 20002000 users per arm, standard error drops from 0.03210.0321 to 0.02210.0221, and the confidence interval narrows by 31 %31\ \% (from half-width 0.0630.063 to 0.0430.043) without collecting another user. The point estimate also changes, from 0.1170.117 to 0.0820.082: adjustment corrected the chance imbalance of XX between the two arms, which here pushed the effect upward. ANCOVA regression gives the same effect (0.08250.0825 versus 0.08250.0825). Across 1500 repetitions, with a prior covariate both estimators are centered at 0.10.1 (0.1020.102 and 0.1010.101) and the variance ratio is 0.5140.514, very close to 1−ρ2=0.511 - \rho^2 = 0.51. With the post-treatment covariate, the unadjusted estimator does not change, but the adjusted one averages −0.396-0.396 instead of 0.10.1: treatment shifted XX by 0.80.8, estimated slope is θ^≈0.62\hat\theta \approx 0.62, and adjustment subtracts θ^×0.8≈0.5\hat\theta \times 0.8 \approx 0.5 from an effect that was real and positive, reversing its sign.

A/B tests in practice

An online experiment applies all of the above at industrial scale, with pitfalls of its own.

The unit of randomization is the unit of analysis. If assignment is by user, but each user generates twenty requests and requests are analyzed as independent, the standard error is too small. Requests by the same user resemble one another: if intraclass correlation is ρic\rho_{\mathrm{ic}} and each user contributes mm observations, the variance of the mean of nmnm observations across nn users is

Var⁡(yˉ)=σ2nm [1+(m−1)ρic]=σ2nm DEFF,\Var(\bar y) = \frac{\sigma^2}{nm}\,\big[1 + (m - 1)\rho_{\mathrm{ic}}\big] = \frac{\sigma^2}{nm}\,\mathrm{DEFF},

with DEFF=1+(m−1)ρic\mathrm{DEFF} = 1 + (m - 1)\rho_{\mathrm{ic}} the design effect (proved by summing each user’s m2m^2 covariances: mm variances σ2\sigma^2 and m(m−1)m(m - 1) covariances ρicσ2\rho_{\mathrm{ic}}\sigma^2). Ignoring it multiplies false positives. The cell measures this with an A/A test (no true effect) analyzed by request and by user.

[ ]An A/A randomized by user: analysis by request or userBrowser
rng = np.random.default_rng(9)
U, m, R = 150, 20, 600                    # usuarios por brazo, peticiones por usuario, experimentos A/A
su, se = 1.0, 1.0                         # desv. típica entre usuarios y dentro de cada usuario
u = rng.normal(0, su, (R, 2, U, 1))       # efecto de usuario, común a sus peticiones
y = u + rng.normal(0, se, (R, 2, U, m))   # R x brazo x usuario x petición; la verdad: no hay efecto

a, c = y[:, 0].reshape(R, -1), y[:, 1].reshape(R, -1)
z_pet = (a.mean(1) - c.mean(1)) / np.sqrt(a.var(1, ddof=1) / a.shape[1] + c.var(1, ddof=1) / c.shape[1])
ua, uc = y[:, 0].mean(2), y[:, 1].mean(2)                            # medias por usuario: la unidad de aleatorización
t_usr = (ua.mean(1) - uc.mean(1)) / np.sqrt(ua.var(1, ddof=1) / U + uc.var(1, ddof=1) / U)
icc = su ** 2 / (su ** 2 + se ** 2)
deff = 1 + (m - 1) * icc
print(f"correlación intraclase {icc:.2f}, efecto de diseño {deff:.2f}, raíz {np.sqrt(deff):.2f}")
print(f"analizando peticiones: desv. típica de z = {z_pet.std():.2f} (debería ser 1),  falsos positivos {100 * np.mean(np.abs(z_pet) > 1.96):.1f} %")
print(f"analizando usuarios:   desv. típica de t = {t_usr.std():.2f},  falsos positivos {100 * np.mean(np.abs(t_usr) > stats.t.ppf(0.975, 2 * U - 2)):.1f} %")

Analyzing 6000 requests per arm as independent gives a statistic with standard deviation 3.203.20 instead of 1, and calls an experiment with no effect “significant” 53.5 %53.5\ \% of the time, eleven times the nominal 5 %. With user-level analysis (each user’s mean as one independent observation), false positives are 5.7 %5.7\ \%. The square root of the design effect (10.5=3.24\sqrt{10.5} = 3.24) is the exact factor by which error was underestimated. The opposite mistake, randomizing by request and analyzing by user, breaks the design differently: each user receives a mixture of both variants, their experience is no longer either one (and what they saw on one request influences the next), and the user mean no longer compares two treatments.

Ratio metrics. The metric of interest is often a ratio of totals, such as CTR (clicks divided by views), mean latency per request, or revenue per session. Assignment is by user, but numerator and denominator are sums over users, and estimator R^=yˉ/xˉ\hat R = \bar y/\bar x is not a mean of independent units. The delta method (lesson 8) gives its standard error.

Proof

By the multivariate central limit theorem, n ((yˉ,xˉ)−(μy,μx))→N(0,Σ)\sqrt{n}\,\big((\bar y, \bar x) - (\mu_y, \mu_x)\big) \to \Normal(\vb{0}, \mat{\Sigma}). Function g(u,v)=u/vg(u, v) = u/v has gradient (1/μx, −μy/μx2)=(1,−R)/μx(1/\mu_x,\ -\mu_y/\mu_x^2) = (1, -R)/\mu_x at (μy,μx)(\mu_y, \mu_x), and the delta method gives a normal with variance ∇g⊤Σ∇g=Var⁡(yi−Rxi)/μx2\nabla g\T\mat{\Sigma}\nabla g = \Var(y_i - Rx_i)/\mu_x^2. The estimator of EE\mathrm{EE} replaces RR by R^\hat R and the variance by the sample variance, both consistent.

∎

Sample ratio mismatch (SRM). If the design assigns 50 % to each arm and 50 500 control users and 49 500 treatment users are observed, the difference looks small (1 %), but is it consistent with chance? A Pearson goodness-of-fit test against the design proportions tells us: with EjE_j the expected count and OjO_j observed,

χ2=∑j(Oj−Ej)2Ej∼χJ−12bajo el disen˜o (J brazos).\chi^2 = \sum_j\frac{(O_j - E_j)^2}{E_j} \sim \chi^2_{J-1}\quad\text{bajo el diseño}\ (J \text{ brazos}).

This is Pearson’s χ2\chi^2 test from lesson 13. A very small pp value indicates SRM (sample ratio mismatch): observed allocation differs from the design. It is an implementation problem (bots filtered after assignment, a redirect losing treatment users, a logging failure affecting one variant), and invalidates the experiment: missing users are not a random subset, so comparing those remaining no longer compares equivalent groups. A strict threshold is common (p<0.001p < 0.001, Kohavi, Tang and Xu, 2020), because the test is applied to all experiments and each false alarm requires investigation, while real implementation failures usually yield much smaller pp values; investigate before looking at the result, rather than “fixing” it by trimming data.

The remaining threats concern design:

  • Novelty and primacy effects. The first week’s measured effect may not be the steady-state effect: users explore a new button (novelty, effect decays) or resist change (primacy, effect grows). Detect it by plotting effect by exposure day and avoid it with experiments spanning several weekly cycles that do not stop upon seeing a low pp value (lesson 25 treats sequential experiments properly).
  • Interference between units. A user’s outcome is assumed independent of others’ assignments (SUTVA). This fails in markets (a treated buyer takes control stock), social networks (content spreads between arms), and shared resources: if treatment consumes more cache, control performance falls and the difference inflates. Mitigate it by cluster randomization (regions, communities, cluster nodes), temporal alternation designs (switchbacks), or direct measurement of indirect effects.
  • Multiple metrics, segments and comparisons. Each additional metric examined is another test, so apply lesson 18: one predetermined decision metric, with the rest corrected or treated as guardrails.

An A/B test’s sample size comes from power: to detect a difference δ\delta in a mean with standard deviation σ\sigma at level α\alpha and power 1−β1 - \beta, each arm needs

n=2 (z1−α/2+z1−β)2 σ2δ2≈15.7 σ2δ2(α=0.05, 1−β=0.8),n = \frac{2\,(z_{1-\alpha/2} + z_{1-\beta})^2\,\sigma^2}{\delta^2} \approx \frac{15.7\,\sigma^2}{\delta^2}\quad(\alpha = 0.05,\ 1 - \beta = 0.8),

the “16 sigma squared over delta squared” rule, multiplied by (1−ρ2)(1 - \rho^2) with CUPED. The minimum detectable effect for given nn is δmin⁡=(z1−α/2+z1−β) EE\delta_{\min} = (z_{1-\alpha/2} + z_{1-\beta})\,\mathrm{EE}. If the effect of interest is halved, four times as many users are needed: slightly more sensitive experiments are not cheap unless variance is reduced.

The cell builds a complete analyzer: SRM, effect on a mean metric with and without CUPED, effect on a ratio metric using the delta method (checked with bootstrap), and achieved power.

[ ]An A/B test analyzer: SRM, mean, ratio by delta method, CUPED and powerBrowser
def simular_ab(n, rng, efecto_ctr=0.003, p_trat=0.5, perdida_trat=0.0):
    """n usuarios. prev = vistas de la semana anterior; vistas y clics, durante el experimento."""
    t = (rng.random(n) < p_trat).astype(int)
    prev = rng.gamma(2.0, 5.0, n)
    vistas = rng.poisson(0.7 * prev + 3.0 * rng.gamma(2.0, 1.0, n))
    clics = rng.binomial(vistas, 0.10 + efecto_ctr * t)
    visible = ~((t == 1) & (rng.random(n) < perdida_trat))            # usuarios del tratamiento que no se registran
    return t[visible], prev[visible], vistas[visible], clics[visible]

def srm(n_c, n_t, p_t=0.5):
    esperado = np.array([1 - p_t, p_t]) * (n_c + n_t)
    chi2 = (((np.array([n_c, n_t]) - esperado) ** 2) / esperado).sum()
    return chi2, stats.chi2.sf(chi2, 1)

def razon_delta(num, den):
    """Razón de medias mean(num)/mean(den) y su error estándar por el método delta."""
    R = num.mean() / den.mean()
    z = (num - R * den) / den.mean()                                     # variable linealizada
    return R, z.std(ddof=1) / np.sqrt(len(num))

def cuped_ajuste(y, x):
    theta = np.cov(x, y)[0, 1] / x.var(ddof=1)
    return y - theta * (x - x.mean())

def analizar(t, prev, vistas, clics, delta_interes=0.003, alpha=0.05):
    za, zb = stats.norm.ppf(1 - alpha / 2), stats.norm.ppf(0.8)
    c, a = t == 0, t == 1
    res = {"srm": srm(c.sum(), a.sum())}
    for nombre, y in [("clics por usuario", clics.astype(float)), ("clics por usuario (CUPED)", cuped_ajuste(clics.astype(float), prev))]:
        res[nombre] = (y[a].mean() - y[c].mean(), np.sqrt(y[a].var(ddof=1) / a.sum() + y[c].var(ddof=1) / c.sum()))
    Ra, sa = razon_delta(clics[a], vistas[a])
    Rc, sc = razon_delta(clics[c], vistas[c])
    se = np.hypot(sa, sc)
    res["CTR (razón, delta)"] = (Ra - Rc, se)
    res["potencia"] = stats.norm.cdf(delta_interes / se - za) + stats.norm.cdf(-delta_interes / se - za)
    res["mde"] = (za + zb) * se
    return res

rng = np.random.default_rng(10)
datos = simular_ab(20000, rng)
res = analizar(*datos)
print(f"SRM: chi2 = {res['srm'][0]:.2f}, p = {res['srm'][1]:.3f}   (reparto {np.bincount(datos[0])})")
for nombre in ("clics por usuario", "clics por usuario (CUPED)", "CTR (razón, delta)"):
    d, se = res[nombre]
    print(f"{nombre:28s} efecto {d:8.4f}  EE {se:.4f}  IC95 [{d - 1.96 * se:8.4f}, {d + 1.96 * se:8.4f}]  z = {d / se:5.2f}")
print(f"potencia para detectar un efecto de 0.003 en el CTR: {res['potencia']:.2f};  efecto mínimo detectable (80 %): {res['mde']:.4f}")

# comprobación del error del método delta con bootstrap de usuarios
t_, prev_, v_, c_ = datos
ia, ic = np.where(t_ == 1)[0], np.where(t_ == 0)[0]
bs = []
for _ in range(200):
    ja, jc = rng.choice(ia, len(ia)), rng.choice(ic, len(ic))
    bs.append(c_[ja].sum() / v_[ja].sum() - c_[jc].sum() / v_[jc].sum())
print(f"EE del CTR: delta {res['CTR (razón, delta)'][1]:.5f}  frente a bootstrap {np.std(bs, ddof=1):.5f}")

The analyzer validates allocation (p=0.404p = 0.404, no SRM), and estimates a CTR increase of 0.00400.0040 with standard error 0.00120.0012 (the true value is 0.0030.003): an zz of 3.363.36, with bootstrap confirming the delta-method error (0.001260.00126 versus 0.001180.00118, within Monte Carlo error of a 200-replicate bootstrap, around 5 %5\ \%). For the mean metric (“clicks per user”), CUPED lowers standard error from 0.01880.0188 to 0.01740.0174 (7 %7\ \%) using last week’s views: little, because correlation with clicks is only 0.380.38, and 1−0.382=0.861 - 0.38^2 = 0.86. Power for the effect of interest, 0.0030.003, is 0.720.72, and the minimum detectable effect at this size is 0.00330.0033, somewhat higher. This experiment being significant (z=3.36z = 3.36) does not contradict moderate power: the estimate (0.00400.0040) landed above the true effect (0.0030.003), and experiments with power 72 %72\ \% fail to detect the effect of interest one in three or four times. An analyzer should always report minimum detectable effect and power, not only the pp value.

It remains to validate it with known effects: repeating the experiment many times checks that the ratio interval covers the true effect at the nominal rate, that SRM gives no false alarms and does warn when a fraction of treatment users is lost.

[ ]Validating the analyzer with simulated data and known effectBrowser
cub, ests, srm_p = 0, [], []
for _ in range(300):
    t_, prev_, v_, c_ = simular_ab(4000, rng, efecto_ctr=0.003)
    r = analizar(t_, prev_, v_, c_)
    d, se = r["CTR (razón, delta)"]
    cub += abs(d - 0.003) <= 1.96 * se
    ests.append(d)
print(f"cobertura del IC95 de la razón en 300 experimentos: {cub / 300:.3f};  media de las estimaciones {np.mean(ests):.4f} (verdad 0.003)")

# SRM: falsas alarmas y potencia con una pérdida de usuarios del tratamiento (solo recuentos)
Nn, Rr = 40000, 20000
n_c = rng.binomial(Nn, 0.5, Rr)
n_t = Nn - n_c
for perdida in (0.0, 0.01, 0.05):
    nt2 = rng.binomial(n_t, 1 - perdida)
    esperado = (n_c + nt2) / 2
    chi2 = ((n_c - esperado) ** 2 + (nt2 - esperado) ** 2) / esperado
    print(f"pérdida del {100 * perdida:3.0f} % del tratamiento: SRM (p < 0.001) en el {100 * np.mean(stats.chi2.sf(chi2, 1) < 0.001):5.1f} % de los experimentos")

The interval covers the true effect at rate 0.9400.940 (nominal 0.950.95) and estimates are centered at 0.00320.0032. SRM, with p<0.001p < 0.001, gives no false alarms without loss (0.1 %0.1\ \%), almost always detects loss of 5 %5\ \% (96 %96\ \%), and does not detect loss of 1 %1\ \% (1.2 %1.2\ \%): a test with limited power does not prove there are no problems, and a small but nonrandom loss (the slowest users, those who fail) can bias the effect even if never detected.

With libraries: anova_lm, Tukey and power in statsmodels

After building analyses from formulas, in practice use statsmodels: ols fits the linear model with a formula, anova_lm computes the sums-of-squares table, pairwise_tukeyhsd pairwise comparisons, and FTestAnovaPower power. The cell regenerates data from previous cells (same seed) and checks that the scratch and library formulas agree. With balanced designs, types I, II and III sums of squares are equal.

[ ]statsmodels: anova_lm, pairwise_tukeyhsd and FTestAnovaPower versus formulas from scratchBrowser
import pandas as pd
import statsmodels.api as sm
from statsmodels.formula.api import ols
from statsmodels.stats.multicomp import pairwise_tukeyhsd
from statsmodels.stats.power import FTestAnovaPower

# 1) un factor: los datos de las cuatro políticas de caché
rng = np.random.default_rng(5)
k, n = 4, 8
mu_pol = np.array([100.0, 104.0, 98.0, 110.0])
y1 = mu_pol[:, None] + 6.0 * rng.standard_normal((k, n))
d1 = pd.DataFrame({"y": y1.ravel(), "politica": np.repeat(list("ABCD"), n)})
tabla = sm.stats.anova_lm(ols("y ~ C(politica)", data=d1).fit(), typ=2)
print(tabla.round(3))
tuk = pairwise_tukeyhsd(d1["y"], d1["politica"], alpha=0.05)
semi = (tuk.confint[:, 1] - tuk.confint[:, 0]) / 2
print(f"semianchura de Tukey en statsmodels: {semi[0]:.3f}  (desde cero: {studentized_range.ppf(0.95, k, k * (n - 1)) * np.sqrt(((y1 - y1.mean(1, keepdims=True)) ** 2).sum() / (k * (n - 1)) / n):.3f})")

# potencia: no centralidad desde cero y FTestAnovaPower (Cohen f = sqrt(lambda / N))
lam = n * ((mu_pol - mu_pol.mean()) ** 2).sum() / 6.0 ** 2
f_cohen = np.sqrt(lam / (k * n))
pot_sm = FTestAnovaPower().solve_power(effect_size=f_cohen, nobs=k * n, alpha=0.05, k_groups=k)
nobs80 = FTestAnovaPower().solve_power(effect_size=f_cohen, power=0.8, alpha=0.05, k_groups=k)
print(f"potencia: ncf {stats.ncf.sf(stats.f.ppf(0.95, k - 1, k * (n - 1)), k - 1, k * (n - 1), lam):.4f}  statsmodels {pot_sm:.4f};  observaciones totales para 80 %: {nobs80:.0f} ({nobs80 / k:.1f} por política)")

# 2) dos factores con interacción (celda del cruce)
rng = np.random.default_rng(1)
mu2 = np.array([[120.0, 80.0], [100.0, 100.0]])
y2 = mu2[:, :, None] + 10 * rng.standard_normal((2, 2, 10))
d2 = pd.DataFrame({"y": y2.ravel(), "plan": np.repeat(["viejo", "nuevo"], 20), "carga": np.tile(np.repeat(["cpu", "es"], 10), 2)})
print(sm.stats.anova_lm(ols("y ~ C(plan) * C(carga)", data=d2).fit(), typ=2).round(3))

# 3) bloques completos (celda de los racks)
rng = np.random.default_rng(12)
tau = np.array([0.0, 3.0, -2.0, 6.0])
beta = rng.normal(0, 10, 6)
y3 = 100 + tau[:, None] + beta[None, :] + 4.0 * rng.standard_normal((4, 6))
d3 = pd.DataFrame({"y": y3.ravel(), "trat": np.repeat(list("ABCD"), 6), "rack": np.tile(np.arange(6), 4)})
print(sm.stats.anova_lm(ols("y ~ C(trat) + C(rack)", data=d3).fit(), typ=2).round(3))

The anova_lm tables reproduce the hand-written cells’ numbers: sums of squares and FF for cache policy (F=8.29F = 8.29), crossing interaction and complete blocks agree to rounding; library Tukey half-width matches the studentized-range calculation (7.377.37); and power with FTestAnovaPower (0.9370.937) is that of the noncentral FF. At this effect size, reaching 80 % power requires 2323 total observations, about 5.75.7 per policy: with 8 per policy, the first cell’s experiment had room to spare because the effect was large relative to noise. Small effects, such as in A/B tests, change the calculation.

Common mistakes

Exercises

ProofSum-of-squares decomposition and the F distribution
Prove: In the model yij=μi+εijy_{ij} = \mu_i + \varepsilon_{ij}, εij∼iidN(0,σ2)\varepsilon_{ij} \iid \Normal(0, \sigma^2), with kk groups and NN observations, prove (a) SST=SSB+SSW\mathrm{SST} = \mathrm{SSB} + \mathrm{SSW} and (b) under H0 ⁣:μ1=⋯=μkH_0\!: \mu_1 = \dots = \mu_k, F=SSB/(k−1)SSW/(N−k)∼Fk−1, N−kF = \dfrac{\mathrm{SSB}/(k-1)}{\mathrm{SSW}/(N-k)} \sim F_{k-1,\,N-k}.
0
Let P\mat{P} be the orthogonal projection onto col⁡(X)\col(\mat{X}) (the matrix of kk group-indicator columns) and P1\mat{P}_1 the projection onto span⁡{1}\spn\{\vb{1}\}.

Step 1 of 4. What vectors are Py\mat{P}\vb{y} and P1y\mat{P}_1\vb{y}?

NumericThe fraction of variance CUPED removes
With correlation ρ=0.7\rho = 0.7 between the prior covariate and experiment metric, what fraction of the effect estimator's variance does CUPED remove with the optimal coefficient?
NumericThe SRM test statistic
An A/B test with 50/50 allocation records 50 500 control users and 49 500 treatment users. What is the χ2\chi^2 statistic for the sample ratio mismatch (SRM) test?
NumericA/B test sample size with CUPED
We want to detect an increase of δ=0.5\delta = 0.5 seconds in a time metric with standard deviation σ=20\sigma = 20 seconds, at two-sided α=0.05\alpha = 0.05 and 80 %80\,\% power. The prior metric has correlation 0.60.6 with the experiment metric and CUPED is used. How many users are needed per arm?
CodeA 2^(k-p) fraction and its aliases
Implement diseno_fraccionado(k, generadores), which constructs the regular fraction 2k−p2^{k-p} with pp = len(generadores). The first k−pk - p factors (letters ABC...) are the base and form a complete factorial; the ii-th remaining factor is the product of columns in the word generadores[i] (for example, with k=5k = 5 and ['AB', 'AC'], D=ABD = AB and E=ACE = AC). Return (X, alias, resolucion): X is the matrix of 2k−p2^{k-p} rows and kk columns of ±1\pm 1; alias is a dictionary mapping each main effect ('A', 'B', ...) to the list of words with which it is confounded (excluding itself), with letters of each word in alphabetical order and the list sorted by length and then alphabetically; resolucion is the length of the shortest word in the defining group. Hint: represent each word as a set of letters and multiply words using symmetric difference.
import numpy as np
from itertools import product

def diseno_fraccionado(k, generadores):
  """Devuelve (X, alias, resolucion) de la fraccion regular 2^(k-p)."""
  letras = "ABCDEFGH"[:k]
  p = len(generadores)
  base = k - p
  # tu código: X (factorial completo en los factores base y columnas generadas),
  # grupo definidor (todas las combinaciones de las palabras D+AB, E+AC, ...), alias y resolución
  X = np.ones((2 ** base, k))
  alias = {}
  resolucion = 0
  return X, alias, resolucion
Shift+Enter to run
QuizFour experiments, only one valid design
Four teams test a change. Which is the only one whose conclusions are valid as designed and analyzed?
QuizA zero main effect
In a 2 × 2 experiment (old or new scheduler, CPU or I/O load), with 10 replicates per cell, two-way ANOVA gives p=0.93p = 0.93 for the scheduler main effect, p<0.001p < 0.001 for load and p<0.001p < 0.001 for interaction. Cell means are 120 (old, CPU), 100 (new, CPU), 80 (old, I/O) and 100 (new, I/O). Which conclusion is correct?

Summary

Key idea
An experiment is won in its design: randomization gives validity (the average effect is unbiased without a response model), replication of independent units provides the error for comparison, and blocking gives precision (with large σb2/σe2\sigma_b^2/\sigma_e^2 it is worth many additional units). ANOVA is the Gaussian linear model with an orthogonal sum-of-squares decomposition, and F=MSB/MSWF = \mathrm{MSB}/\mathrm{MSW} has an exact distribution (noncentral under the alternative, giving power); with two factors, a main effect averages simple effects and is interpretable only without interaction. 2k2^k factorials estimate all effects using all runs, and regular fractions trade runs for aliases: resolution says which effects are confounded. Adjustment for a prior covariate (ANCOVA, CUPED) is unbiased and multiplies variance by 1−ρ21 - \rho^2; adjustment for a later one biases it. A valid A/B test requires the analysis unit to match the randomization unit, ratio errors by the delta method, controlled SRM, predetermined duration and no interference.