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
- 05Gaussian linear modelF-test for nested linear modelsRandomization inferenceSample size calculation and minimum detectable effectPower and power functionFamilywise error rate control: Bonferroni, Šidák and HolmPaired design and paired testDelta methodPearson chi-squared tests and G-test
- 02Orthonormal basis
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 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 . Each machine’s noise is . All three designs treat six servers and leave six as controls; only who receives treatment changes.
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 instead of : a bias of that does not shrink however often the experiment is repeated, and rejects the hypothesis that the scheduler does nothing when it is true in of cases. The two randomized assignments are centered on the true value (means and ), and the complete-randomization test maintains false rejections. But the complete design pays a standard deviation of versus 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 test, randomization inference, the power function and sample-size calculation, the paired test, the delta method, Pearson’s 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 has two fixed numbers, its response with treatment, , and without it, , of which only one is observed. The average effect over the units is . There is no probability model for the responses: the only randomness is the assignment draw.
Proof
(1) By symmetry, for each . Then , the mean of across the population. Similarly , and the difference is . (2) This calculation uses indicator covariances, and for ; the algebra is omitted, as it is the same as in sampling without replacement in lesson 3 and permutation tests. The term appears because and 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 under the null-effect hypothesis (no individual effect, ) can be enumerated by permuting assignments, giving Fisher’s test from lesson 14: the 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 racks of servers ( servers in total, with treated). Untreated server performance is , with the rack effect and its own noise, and treatment adds .
Proof
Write with if server is treated and if it is a control. The noise part, independent of assignment, contributes in both designs. Rewrite the rack part as , with the difference between treated and control units in rack . Conditional on assignment, its variance is . With blocking, in every rack, and the contribution vanishes. With complete assignment, is hypergeometric (from , with successes, draws), with mean and variance , and since , . Summing over the racks gives contribution . Both designs are unbiased because 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.
Three observations. The blocked design’s width depends only on : changing does not move it, because between-rack differences cancel by construction in each comparison. The complete design’s width grows with (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 treatments (four cache policies, four compiler versions), with units randomly assigned to treatment and . The model is
This is the Gaussian linear model with design matrix of group-indicator columns (one per treatment), of rank . Its coefficients are means , and their least-squares estimator is . The usual parameterization, with , separates an overall mean from treatment effects ; both describe the same subspace of , and test the same hypothesis, (that is, all ).
Proof
Let be the orthogonal projection of onto and the projection onto , with (the sum of the indicator columns). Applied to , has entry in positions for group , and . Since , . The difference is the projection onto the orthogonal complement of within , of dimension , and projects onto , of dimension . The two projections annihilate each other, .
(1) is a sum of orthogonal vectors; by Pythagoras, . (2) With and we obtain . Also , with , the vector equal to in group (giving ) whose squared norm is . Complete an orthonormal basis of adapted to the three subspaces (orthonormal basis, as in lesson 19): in those coordinates remains , components on orthogonal subspaces are independent, and the sum of squares of normal components of mean and variance 1 is with noncentrality . This gives the distributions and independence. (3) is the definition of a noncentral , the ratio of two independent divided by their degrees of freedom, with a noncentral numerator. (4) The single-mean model has and the -means model has , so , the statistic from lesson 19.
∎Two special cases are worth remembering. With , , the square of the two-sample statistic with common variance, and the tests coincide. The fraction of explained variation measures effect size (without bias correction: is a less biased version). The figure lets you explore the decomposition: dragging a mean changes only , since group points move together and their within-group deviations do not change.
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 and an alternative, with the power given by the noncentral .
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 matches the classical one (, : the four policies do not perform equally), and 20 000 experiments confirm the theorem: under the simulated is indistinguishable from (Kolmogorov–Smirnov test, ; mean , theoretical ), and rejects of the time; under the cell’s alternative (), simulated power is and the noncentral gives . With 8 servers per policy, and differences up to 12 points between policies, the experiment has good power, yet one in sixteen () would detect nothing. Noncentrality is the design lever: it increases with and decreases with , 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 with (for example, , the fourth versus the mean of the others). Its estimator has variance and statistic follows . Two contrasts are orthogonal if , and a family of orthogonal contrasts decomposes into independent one-degree-of-freedom sums, . This idea—one effect, one contrast, one degree of freedom—governs the factorial designs later.
For the pairwise differences with a simultaneous guarantee, use Tukey’s procedure from lesson 18: intervals , with the studentized-range quantile, cover all true differences simultaneously with exact probability in the balanced design. It does not require a significant overall and uses the same FWER control correction. The cell implements it from the studentized-range distribution and checks simultaneous coverage.
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 of the time, despite there being six (in 20 000 experiments, with Monte Carlo error points). The constant exceeds the uncorrected (): the price of bounding the error across all six comparisons. In this experiment policy 4 () is separated from 1 and 3, but not 2 (estimated difference , with true difference ), and 3 is separated from 2. Policy 2 versus 1, with true difference , 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 test is robust to distribution shape at moderate sample sizes, and alternatives without a shape assumption are the Kruskal–Wallis test or an 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 and block , their inner product is ). Then , with and of dimensions and , orthogonal to each other and to . Projections onto each give and , and the residual, of dimension , gives . 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 , , divided by . For (3), and ; the error variance of a completely randomized design with units would be (the mean of the unblocked squares), which is . Replacing mean squares by their expectations gives the ratio.
∎With one comparison treatment, , the block is a pair, and RCBD is the paired design: statistic is the square of the paired for within-pair differences (the same server before and after, two users with the same profile). The cell builds an RCBD with configurations and very different racks, analyzes it with and without blocks, and verifies by simulation that predicts the gain.
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 into treatments, blocks and error, and most of what is not treatments is between-rack variation ( versus error ). Thus the same experiment gives analyzed by blocks and if they are ignored: blocking turns an invisible effect () into a significant one (), without a single extra unit. The price is small: error has degrees of freedom rather than . Estimated relative efficiency is , and simulation confirms the order of magnitude: an unblocked comparison has variance and a blocked one , a ratio of . The exact value, using the same calculation as the blocking theorem (now with units in racks of ), is , tending to with many racks. On the last line, with two treatments the blocked analysis is the paired : .
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 : rows and columns index the two blocking factors, and the treatments are arranged so each appears exactly once in each row and column. With units, treatment effects are estimated, leaving 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 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.
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 , 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, with levels and with levels, applied in every combination with replicates in each cell, the model (with the response of replicate in cell ) is
with constraints and . If cell means are , the terms are , and the interaction , 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 at each level of ) are equal, that is, the profiles for each level of are parallel.
Proof
This is one-way ANOVA with cell levels, , and the partition of that subspace of dimension into three orthogonal subspaces of dimensions , and . 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 there is no error: 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 , writing with the scheduler (1 old, 2 new) and the load (1 CPU, 2 I/O), the main effect of is , the average of the simple effects, and the interaction is , 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 as levels of , and averaging them is a decision (which may not correspond to the population of interest), not a result.
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 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 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.
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 (), load does (), and interaction is enormous (). Simple effects and their intervals give the full story: ms for CPU load and 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 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 , (the product of two columns is the column of the symmetric difference). For there is a factor , and in the balanced design half the runs have and half , for each combination of the other factors, so . With we obtain if , and if . (2) The design matrix has orthogonal columns of norm , so , and : each coefficient is estimated by , which is , with variance and zero covariances; hence . (3) In the one-factor-at-a-time alternative, the effect of compares the baseline configuration with changed: each receives runs, and the variance of the difference is . The ratio to is . 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 factorial () has no degrees of freedom to estimate : all 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: and , discarding active effects. The cell implements it.
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 (, and versus , and ); D ( versus ) 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, , should govern their spread; Lenth’s PSE (), 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 factors, a complete requires 128 runs to estimate 127 effects, almost all high-order interactions that, by the hierarchy principle, probably do not exist. A regular fraction keeps a fraction of runs, defined by generators: run the full factorial of base factors and define each of the remaining as a product of columns, for example in . The consequences are algebraic. If in all runs, multiplying by gives : the defining relation. The set of words with in the fraction (those generated by relations and their products) is the defining group, closed under symmetric difference, with .
Proof
(1) With , ; hence on the fraction if and only if there. Words in satisfy by construction. Conversely, fraction is a subgroup of the group of combinations, of index , and characters equal to throughout form its annihilator, of size ; since is contained in it and has the same size, they coincide. (2) Write the full model and notice that on the fraction for in the same class: coefficients of a class appear only summed, and by orthogonality of distinct columns, has expectation and variance . (3) If and are aliases, has length , and .
∎The theorem says what is being paid: with a resolution-III fraction one measures, instead of main effect , the sum (for example), and if a real interaction exists, the “effect of ” 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.
With (, resolution III), the contrast for measures , more than twice the true effect. Switching to (, resolution IV), : interaction now contaminates interaction (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 ( here, obtained by changing the sign of the generated column), and together the halves form the complete 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.
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 the contrast averages (), and with it averages , the true value; in both cases its standard deviation is the theoretical ( and 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 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 is independent of , ; and . (2) is the difference in means of between independent arms of units, so , and (the term is constant within each arm). (3) It is a quadratic in minimized at , and substitution gives . (4) is a continuous function of sample moments, which converge by the law of large numbers; since , error is 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 () and historical spending predicts current spending, part of the observed difference is that imbalance, which adjustment removes. The larger , the more of the difference is predictable and the less noise remains. Two useful readings: with , of variance is removed, and dependence is quadratic, so removes only and is not worth the effort; and the sample size needed for given power is multiplied by because it is proportional to variance.
Besides reducing variance, adjustment costs nothing with : there is no gain, but no bias either (with small samples it loses one degree of freedom estimating , an effect of order ). What destroys the method is the same condition that justifies it: must be independent of assignment, guaranteed only if measured before. If is a consequence of treatment (time on page, measured during the experiment), and adjustment subtracts from the effect: . 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 estimates using the within-group slope and is the same adjustment; with a centered covariate and an interaction , the estimator is asymptotically as good as or better than the unadjusted estimator even if the relationship between and is neither linear nor constant (Lin, 2013, following Freedman’s 2008 criticisms), unlike regression without interaction. need not be the same metric: any predictor of built using pre-experiment data (even a machine-learning model) works, and variance reduction is the fraction of explained by the predictor, the of the theorem.
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 users per arm, standard error drops from to , and the confidence interval narrows by (from half-width to ) without collecting another user. The point estimate also changes, from to : adjustment corrected the chance imbalance of between the two arms, which here pushed the effect upward. ANCOVA regression gives the same effect ( versus ). Across 1500 repetitions, with a prior covariate both estimators are centered at ( and ) and the variance ratio is , very close to . With the post-treatment covariate, the unadjusted estimator does not change, but the adjusted one averages instead of : treatment shifted by , estimated slope is , and adjustment subtracts 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 and each user contributes observations, the variance of the mean of observations across users is
with the design effect (proved by summing each user’s covariances: variances and covariances ). Ignoring it multiplies false positives. The cell measures this with an A/A test (no true effect) analyzed by request and by user.
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 instead of 1, and calls an experiment with no effect “significant” of the time, eleven times the nominal 5 %. With user-level analysis (each user’s mean as one independent observation), false positives are . The square root of the design effect () 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 is not a mean of independent units. The delta method (lesson 8) gives its standard error.
Proof
By the multivariate central limit theorem, . Function has gradient at , and the delta method gives a normal with variance . The estimator of replaces by 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 the expected count and observed,
This is Pearson’s test from lesson 13. A very small 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 (, 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 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 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 in a mean with standard deviation at level and power , each arm needs
the “16 sigma squared over delta squared” rule, multiplied by with CUPED. The minimum detectable effect for given is . 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.
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 (, no SRM), and estimates a CTR increase of with standard error (the true value is ): an of , with bootstrap confirming the delta-method error ( versus , within Monte Carlo error of a 200-replicate bootstrap, around ). For the mean metric (“clicks per user”), CUPED lowers standard error from to () using last week’s views: little, because correlation with clicks is only , and . Power for the effect of interest, , is , and the minimum detectable effect at this size is , somewhat higher. This experiment being significant () does not contradict moderate power: the estimate () landed above the true effect (), and experiments with power 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 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.
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 (nominal ) and estimates are centered at . SRM, with , gives no false alarms without loss (), almost always detects loss of (), and does not detect loss of (): 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.
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 for cache policy (), crossing interaction and complete blocks agree to rounding; library Tukey half-width matches the studentized-range calculation (); and power with FTestAnovaPower () is that of the noncentral . At this effect size, reaching 80 % power requires total observations, about 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
Step 1 of 4. What vectors are and ?
diseno_fraccionado(k, generadores), which constructs the regular fraction with = len(generadores). The first factors (letters ABC...) are the base and form a complete factorial; the -th remaining factor is the product of columns in the word generadores[i] (for example, with and ['AB', 'AC'], and ). Return (X, alias, resolucion): X is the matrix of rows and columns of ; 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