Module contents
Lesson 12 of 23Core 115 min

Statistical significance in ML I: comparing two models

Statistical significance in ML comparisons depends on which variability is generalized: sampled test items, data splits, or training runs. Study paired example tests, 5×2cv and corrected resampled t, hierarchical bootstrap, almost stochastic dominance, and practical equivalence.

After this lesson you can

  • Choose a two-model comparison test according to the source of variability to generalize.
  • Apply exact McNemar, paired bootstrap, and paired permutation to per-example predictions.
  • Explain why naive paired t on cross-validation folds underestimates variance and apply 5×2cv and corrected resampled t.
  • Combine seeds and examples with hierarchical bootstrap and compare score distributions using almost stochastic dominance.
  • Separate statistical significance from practical relevance with a ROPE and write a comparison report.

Before you start

Which population do you want to compare?

One model scores 94.4% and another 93.6% on the same test. The observed difference is 0.8 points, but its precision depends on which questions they miss and what is repeatable. Do you want inference about new items for these two trained models, new trainings of the same algorithm, or different training sets? These estimands differ and are linked to the experimental unit and sources of variation. A metric as an estimator needs a defined population before testing.

For two fixed models and a common random test, use per-item results while retaining pairs. Studying retrained algorithms requires training repetitions; an item test of one pair does not measure that variation. For repeated splits, training sets overlap and differences are not independent. With multiple seeds and a common test, the design is crossed: all seeds share the same items and both models are compared at each seed-item combination.

Only disagreements

The continuity-corrected chi-square approximation uses (∣b−c∣−1)2/(b+c)(|b-c|-1)^2/(b+c) when disagreements exist, with the figure’s variant truncating at zero before squaring. The exact two-sided test sums both binomial tails and avoids relying on approximation with few disagreements. If items share a document, conditional independence can fail; cluster or resample documents. Accuracy difference is (b−c)/n(b-c)/n, but uncertainty depends on both counts, not just their subtraction.

InteractiveOnly disagreements count
B correctB wrong
A correct20030
A wrong15100

Off-diagonal cells determine the test under the conditional null of equal probabilities for both disagreements.

30
15
200
100
Disagreements45
Corrected McNemar4.356
Two-sided exact p0.0357
Change the four cells. Agreements alter the accuracy denominator but not the conditional test. The exact p-value is two-sided.

The paired bootstrap resamples joint indices (ai,bi)(a_i,b_i) and recalculates the difference. For a nondecomposable metric such as F1, resample predictions and labels together and recalculate the full metric; do not average a supposed per-example F1. This lesson’s percentile interval is approximate; the BCa interval corrects bias and asymmetry under its assumptions. A centered bootstrap can build an approximate null distribution; do not confuse the proportion of ordinary bootstrap replicates crossing zero with an exact test.

The paired permutation swaps A and B within each item, equivalent to changing each difference’s sign. Exact validity requires exchangeability under the null, such as appropriate random assignment, not merely equal means for arbitrary distributions. For BB random permutations use (1+#{∣T∗∣≥∣T∣})/(B+1)(1+\#\{|T^*|\ge |T|\})/(B+1): never report p=0p=0 simply because no extreme was observed in finite simulation. Pairs and groups must be retained.

Shared splits: why the naive t-test fails

Cross-validation comparison tests seek to generalize beyond one fixed model pair. Folds train on overlapping data. Suppose JJ differences have common variance σ2\sigma^2 and pairwise correlation ρ\rho. Expanding variance of their mean gives JJ variance terms and J(J−1)J(J-1) covariances:

Var⁡(Dˉ)=Jσ2+J(J−1)ρσ2J2=σ2[ρ+1−ρJ].\Var(\bar D)=\frac{J\sigma^2+J(J-1)\rho\sigma^2}{J^2}=\sigma^2\left[\rho+\frac{1-\rho}{J}\right].

If ρ>0\rho>0, not all uncertainty vanishes as JJ grows. The naive paired t-test uses s/Js/\sqrt J and treats differences as independent; it can underestimate variance and raise type I error. Correlation need not always be positive or equal across all pairs: the formula illustrates the mechanism and does not prove a rate for a particular dataset.

In 5×2cv, five independent half-splits are formed and both directions of each are evaluated. If di1,di2d_{i1},d_{i2} are differences for split ii, take si2=(di1−di2)2/2s_i^2=(d_{i1}-d_{i2})^2/2. Dietterich’s t statistic uses d11/∑isi2/5d_{11}/\sqrt{\sum_i s_i^2/5} and a t reference with five degrees of freedom. Combined F uses ∑i,jdij2/(2∑isi2)\sum_{i,j}d_{ij}^2/(2\sum_i s_i^2) and an F reference with 10 and 5 degrees of freedom. These are approximations with assumptions, not universal guarantees. When the denominator is zero, do not invent a p-value: report the statistic as undefined. See Dietterich.

The corrected resampled t-test uses dˉ/(1/J+ntest/ntrain)sd2\bar d/\sqrt{(1/J+n_{test}/n_{train})s_d^2} and a t reference with J−1J-1 degrees of freedom. The correction approximates dependence from reusing data; it does not make splits independent or cover every design. With ten 90/10 splits, the variance factor relative to naive is (0.1+1/9)/0.1=2.1111(0.1+1/9)/0.1=2.1111. See Nadeau and Bengio for formula and limits.

InteractiveThe test depends on the design
naive t
0.08
t 5×2
0.02
F 5×2
0.01
corrected t
0.00

The dashed line marks 0.05. The scale ends at 0.15. These rates do not show monotonic inflation with k and have Monte Carlo uncertainty: each uses 100 repetitions.

Dataset size
Folds for naive t
Experiment
Repetitions per condition100
Change size and folds. Results were actually calculated with decision trees on synthetic data: 100 experiments per combination. The nominal reference line is 0.05; Monte Carlo noise is substantial.

The simulation does not show monotonic inflation with kk: with 100 repetitions rates are imprecise and depend on generator, algorithm, and size. Corrected t and 5×2cv are conservative in several conditions of this trial. Conservatism here does not guarantee control in other distributions. Choose unit and test before seeing results; Dror and colleagues present a selection protocol for NLP.

Seeds and items: hierarchical or crossed structure

The hierarchical bootstrap first resamples upper units and then lower units while respecting dependence. If each seed evaluates a different item set, items can be resampled within seed. If all evaluate the same test, items are crossed with seeds: resample seeds and one shared set of item indices for every row. If A and B use a valid seed pair, use the same seed indices for both. Removing pairing changes estimated variance.

InteractiveResample both levels
0.004Difference B−A0.039

Paired seeds are resampled and then the same items for all seeds; the test set is shared. Single-level intervals hold the other level fixed.

0.02
0.04
200
Seeds only, CI0.012 to 0.033
Items only, CI0.017 to 0.029
Both levels, CI0.010 to 0.037
Adjust variation at each level and increase resamples. The synthetic additive model is not from real training; compare intervals when one level is fixed or both are resampled.

A shared seed forms a useful block only with a documented shared mechanism. Architectures may consume generators in different orders; the same label does not mean matching initialization. The local lab shares split and batch order but does not claim identical weights for architectures of different sizes. The interval covers the mean under the adopted design and resampling, not performance on every future task.

Almost stochastic dominance compares score distributions, not just means. If QA(u)Q_A(u) and QB(u)Q_B(u) are quantiles, the violation index of A relative to B from Dror et al. divides the integral of (QA−QB)2(Q_A-Q_B)^2 over quantiles where QA<QBQ_A<Q_B by the total integral of the same squared difference. Zero indicates empirical stochastic dominance of A in that direction; if distributions are identical, the ratio is undefined. The descriptive index alone is not a test: the paper’s method estimates uncertainty and fixes tolerance beforehand. Ten seeds give limited tail information.

Significance and usefulness

Practical significance asks whether an effect is large enough to matter, not only whether zero is compatible with a hypothesis. Fix a region of practical equivalence (ROPE) [−δ,δ][-\delta,\delta] before seeing results. If an appropriate interval lies entirely above δ\delta, improvement is relevant; entirely below −δ-\delta, deterioration is relevant; entirely inside, there is evidence of equivalence at that margin; crossing a boundary is inconclusive for that decision. Formal frequentist equivalence inference uses two one-sided tests with appropriate interval and level, not an arbitrary interval chosen afterward.

InteractiveFour conclusions
0 at the dashed line; band = ROPE
0.02
0.01
0.01
Interval0.008 to 0.032
Conclusioninconclusive for relevance
Move center, width, and margin. An interval can exclude zero yet cross the relevance margin.

A comparison report identifies population, unit, splits, seeds, metric, difference direction, test, and assumptions; it reports estimate, interval, pp where appropriate, prespecified margin, costs, and limits. Failing to conclude a difference does not prove equivalence. Do not change ROPE because the observed estimate is just outside it.

To decide where to start, follow these five questions:

SituationAnalysis answering the question
One pair of already trained large models, one prediction per itemMcNemar for binary correctness or paired resampling for the metric; conclude about items conditional on those models.
Cheap algorithms and little training dataRepeat splits, use 5×2cv or a corrected test, and report that these are approximate.
Ten paired seeds and a common testResample seeds and test as crossed factors; document which random sources are paired.
A global metric such as F1Resample paired units and recalculate the full metric; do not fabricate per-item F1.
Several questions per documentTreat document as the independent resampling unit and retain its questions and both systems’ predictions together.

These paths can combine. For example, a shared document-clustered test and ten seeds require resampling seeds and documents with all their items and both models. If training sets also change, the design must capture another level. With only one fixed model, no statistical procedure invents the distribution of other training results.

Lab: a comparison library

The following functions are self-contained and can be copied to your library. Paired bootstrap returns A−B difference, percentile interval, and approximate two-sided p-value from centered bootstrap. Permutation retains pairs. For a grouped test, replace indices with complete groups and recalculate the metric. The percentile interval is implemented from scratch; scipy.stats supplies reference distributions whose interpretation needs the described assumptions.

[ ]Tests on pairs and splitsBrowser
import numpy as np
from scipy.stats import binomtest, t, f, norm

def mcnemar_exact(a,b):
    a=np.asarray(a,dtype=bool); b=np.asarray(b,dtype=bool)
    if a.ndim!=1 or a.shape!=b.shape or len(a)==0: raise ValueError('pares inválidos')
    ab=int(np.sum(a & ~b)); ba=int(np.sum(~a & b)); m=ab+ba
    return ab,ba,(binomtest(ab,m,.5).pvalue if m else 1.)

def paired_bootstrap(a,b,n_boot=2000,seed=0):
    a=np.asarray(a,float); b=np.asarray(b,float)
    if a.ndim!=1 or a.shape!=b.shape or len(a)<2 or not np.isfinite(a).all() or not np.isfinite(b).all(): raise ValueError('pares inválidos')
    d=a-b; rng=np.random.default_rng(seed)
    indices=rng.integers(0,len(d),size=(n_boot,len(d)))
    samples=d[indices].mean(axis=1)
    centered=(d-d.mean())[indices].mean(axis=1)
    p=(1+np.sum(np.abs(centered)>=abs(d.mean())))/(n_boot+1)
    return float(d.mean()),np.quantile(samples,[.025,.975]),float(p)

def paired_permutation(a,b,n_perm=9999,seed=0):
    a=np.asarray(a,float); b=np.asarray(b,float)
    if a.ndim!=1 or a.shape!=b.shape or len(a)<2 or not np.isfinite(a).all() or not np.isfinite(b).all(): raise ValueError('pares inválidos')
    d=a-b
    signs=np.random.default_rng(seed).choice([-1,1],(n_perm,len(d)))
    return float((1+np.sum(np.abs((signs*d).mean(axis=1))>=abs(d.mean())-1e-15))/(n_perm+1))

def five_by_two(d):
    d=np.asarray(d,float)
    if d.shape!=(5,2) or not np.isfinite(d).all(): raise ValueError('se requieren cinco pares')
    s2=(d[:,0]-d[:,1])**2/2; den=np.sum(s2)
    if den==0: return np.nan,np.nan
    stat=d[0,0]/np.sqrt(den/5); ft=np.sum(d*d)/(2*den)
    return float(2*t.sf(abs(stat),5)),float(f.sf(ft,10,5))

def corrected_t(d,n_train,n_test):
    d=np.asarray(d,float)
    if d.ndim!=1 or len(d)<2 or n_train<=0 or n_test<=0: raise ValueError('entrada inválida')
    se=np.sqrt((1/len(d)+n_test/n_train)*np.var(d,ddof=1))
    return float(2*t.sf(abs(d.mean()/se),len(d)-1)) if se else np.nan

def crossed_bootstrap(a,b,n_boot=2000,seed=0):
    a=np.asarray(a,float);b=np.asarray(b,float)
    if a.shape!=b.shape or a.ndim!=2 or min(a.shape)<2: raise ValueError('matrices semilla x ítem incompatibles')
    d=b-a; R,N=d.shape; rng=np.random.default_rng(seed); out=np.empty(n_boot)
    for i in range(n_boot):
        seeds=rng.integers(R,size=R); items=rng.integers(N,size=N)
        out[i]=d[np.ix_(seeds,items)].mean()
    return float(d.mean()),np.quantile(out,[.025,.975])

def almost_dominance(a,b):
    a=np.sort(np.asarray(a,float));b=np.sort(np.asarray(b,float))
    if not len(a) or not len(b) or not np.isfinite(a).all() or not np.isfinite(b).all(): raise ValueError('muestras inválidas')
    grid=np.unique(np.r_[np.linspace(0,1,len(a)+1),np.linspace(0,1,len(b)+1)])
    mid=(grid[:-1]+grid[1:])/2
    qa=a[np.minimum((mid*len(a)).astype(int),len(a)-1)]
    qb=b[np.minimum((mid*len(b)).astype(int),len(b)-1)]
    weights=np.diff(grid)*(qa-qb)**2; total=weights.sum()
    return float(weights[qa<qb].sum()/total) if total>0 else np.nan

def almost_dominance_test(a,b,epsilon=.5,alpha=.05,reps=500,seed=0):
    a=np.asarray(a,float); b=np.asarray(b,float)
    if a.ndim!=1 or b.ndim!=1 or len(a)<2 or len(b)<2 or not 0<epsilon<1 or not 0<alpha<1 or reps<2: raise ValueError('parámetros inválidos')
    estimate=almost_dominance(a,b);rng=np.random.default_rng(seed)
    draws=np.array([almost_dominance(rng.choice(a,len(a),replace=True),rng.choice(b,len(b),replace=True)) for _ in range(reps)])
    if not np.isfinite(estimate) or not np.isfinite(draws).all(): return estimate,np.nan,np.nan
    se=draws.std(ddof=1)
    if se==0: return estimate,np.nan,np.nan
    return float(estimate),float(estimate+norm.ppf(1-alpha)*se),float(norm.cdf((estimate-epsilon)/se))

a=np.r_[np.ones(30),np.zeros(15),np.ones(50)]
b=np.r_[np.zeros(30),np.ones(15),np.ones(50)]
print('McNemar:',mcnemar_exact(a,b))
print('Bootstrap A−B:',paired_bootstrap(a,b,2000,31))
print('Permutación:',paired_permutation(a,b,9999,31))
print('Índice de violación A frente a B:',almost_dominance([.8,.9],[.7,.85]))
print('ASO, índice/límite/p:',almost_dominance_test([.81,.83,.87,.91,.94],[.76,.79,.84,.86,.90],.5,reps=500,seed=31))
assert np.isclose(mcnemar_exact(a,b)[2],binomtest(30,45,.5).pvalue)

The almost_dominance function exactly calculates the piecewise integral of empirical quantiles, even for different observation counts. almost_dominance_test estimates standard error by independent bootstrap and uses a one-sided normal approximation for the null of violation index at least ε; it rejects if the upper limit falls below ε. If a resample yields identical distributions or standard error is zero, it returns undefined values rather than feigning certainty. Independent bootstrap suits independent score samples; it does not automatically preserve paired seeds or a shared test. Population dominance is not claimed merely because the sample is ordered.

Now measure an item-controlled case. Half the pairs share one Bernoulli outcome with probability 0.8; the rest have independent outcomes, with B probability 0.8 under the null and 0.9 under the alternative. Population B−A difference under the alternative is 0.05. Run 200 benchmarks of 80 items per scenario and 199 resamples or permutations per benchmark. Exact McNemar p is conditional; the other two have additional Monte Carlo error. Rates are approximate, not a universal method evaluation.

[ ]Type I error and per-item powerBrowser
from scipy.stats import binom
import numpy as np
rng=np.random.default_rng(2026)
for q in (.8,.9):
    R,N,B=200,80,199
    common=rng.random((R,N))<.5
    a=rng.random((R,N))<.8
    b=np.where(common,a,rng.random((R,N))<q)
    d=b.astype(int)-a.astype(int); delta=d.mean(axis=1)
    ab=np.sum(d==1,axis=1);ba=np.sum(d==-1,axis=1);m=ab+ba
    pm=np.minimum(1,2*binom.cdf(np.minimum(ab,ba),m,.5))
    idx=rng.integers(N,size=(R,B,N))
    boot=np.take_along_axis(d[:,None,:],idx,axis=2).mean(axis=2)
    centered=boot-delta[:,None]
    pb=(1+np.sum(np.abs(centered)>=np.abs(delta[:,None])-1e-12,axis=1))/(B+1)
    signs=rng.choice([-1,1],size=(R,B,N))
    perm=(signs*d[:,None,:]).mean(axis=2)
    pp=(1+np.sum(np.abs(perm)>=np.abs(delta[:,None])-1e-12,axis=1))/(B+1)
    print('q independiente de B',q,'rechazos McNemar/bootstrap/permutación',np.mean(np.column_stack([pm,pb,pp])<.05,axis=0))

Dependence structure also matters in the two-level bootstrap. In the next example, differences are crossed synthetic data with independent seed, item, and residual effects; the null has mean difference zero and the alternative 0.12. Count exclusions of zero in 95% percentile intervals. One hundred repetitions allow only a rough estimate. Crossed resampling uses seeds and items common to both variants.

[ ]Crossed uncertainty simulationBrowser
import numpy as np
rng=np.random.default_rng(720)
for effect in (0.,.12):
    reject=0
    for r in range(100):
        d=effect+rng.normal(0,.10,(10,1))+rng.normal(0,.15,(1,30))+rng.normal(0,.05,(10,30))
        _,ci=crossed_bootstrap(np.zeros_like(d),d,n_boot=199,seed=1000+r)
        reject += ci[0]>0 or ci[1]<0
    print('efecto',effect,'fracción de intervalos que excluye cero',reject/100)

For almost dominance the null must also be specified. A is compared with B for ε = 0.5, using 100 pairs of independent samples of 30 scores. If A has mean −0.3 and B mean 0, both normal with variance one, B dominates in the population and the null that A’s violation index is at least 0.5 is true. With A mean +0.3, A dominates and this is an alternative. The inferential index is approximate; bootstrap can be unstable with small samples. Undefined result count is reported separately, never silently counted as nonrejection.

[ ]Illustrative ASO test calibrationBrowser
import numpy as np
rng=np.random.default_rng(721)
for shift in (-.3,.3):
    ps=[]
    for r in range(100):
        a=rng.normal(shift,1,30);b=rng.normal(0,1,30)
        _,upper,p=almost_dominance_test(a,b,epsilon=.5,reps=99,seed=2000+r)
        ps.append(p)
    ps=np.asarray(ps);valid=np.isfinite(ps)
    print('desplazamiento A',shift,'rechazos entre válidos',np.mean(ps[valid]<.05),'válidos',valid.sum())

Type I error and power on synthetic data

Classification data are generated with make_classification and decision trees with feature randomness are compared. Under the null both variants have depth 3 and the same training distribution, with different seeds; the alternative changes B’s depth to 5. The full code below repeats each experiment 100 times per condition and records how many statistics are defined. The figure result is a local run of this code. This trial shows one scenario, not proof that one depth is always better.

First check browser flow with five small null experiments. Five repetitions cannot usefully estimate type I error: they check implementation. Then run the full campaign of 100 per condition locally to generate the figure.

[ ]Check browser flowBrowser
from sklearn.datasets import make_classification
from sklearn.model_selection import KFold
from sklearn.tree import DecisionTreeClassifier
from scipy.stats import t
import numpy as np
ps=[]
for seed in range(5):
    X,y=make_classification(n_samples=120,n_features=8,n_informative=4,n_redundant=0,random_state=1000+seed)
    d=[]
    for j,(tr,te) in enumerate(KFold(5,shuffle=True,random_state=seed).split(X)):
        a=DecisionTreeClassifier(max_depth=3,max_features='sqrt',random_state=seed+10*j)
        b=DecisionTreeClassifier(max_depth=3,max_features='sqrt',random_state=seed+10*j+10000)
        a.fit(X[tr],y[tr]);b.fit(X[tr],y[tr]);d.append(b.score(X[te],y[te])-a.score(X[te],y[te]))
    d=np.asarray(d);se=d.std(ddof=1)/np.sqrt(len(d))
    ps.append(float(2*t.sf(abs(d.mean()/se),len(d)-1)) if se else 1.)
print('Cinco valores p de prueba:',np.round(ps,4))
[ ]Simulate cross-validation testsLocal GPU
import numpy as np
from scipy.stats import t, f
from sklearn.datasets import make_classification
from sklearn.model_selection import KFold, ShuffleSplit
from sklearn.tree import DecisionTreeClassifier

def five_by_two(d):
    d=np.asarray(d,float); s2=(d[:,0]-d[:,1])**2/2; den=np.sum(s2)
    if den==0: return np.nan,np.nan
    return float(2*t.sf(abs(d[0,0]/np.sqrt(den/5)),5)),float(f.sf(np.sum(d*d)/(2*den),10,5))

def corrected_t(d,n_train,n_test):
    d=np.asarray(d,float); se=np.sqrt((1/len(d)+n_test/n_train)*np.var(d,ddof=1))
    return float(2*t.sf(abs(d.mean()/se),len(d)-1)) if se else np.nan

def score_diff(X,y,train,test,seed,alternative):
    a=DecisionTreeClassifier(max_depth=3,max_features='sqrt',random_state=seed)
    b=DecisionTreeClassifier(max_depth=5 if alternative else 3,max_features='sqrt',random_state=seed+10000)
    a.fit(X[train],y[train]);b.fit(X[train],y[train])
    return b.score(X[test],y[test])-a.score(X[test],y[test])

def one_experiment(n,k,seed,alternative=False):
    X,y=make_classification(n_samples=n,n_features=8,n_informative=4,n_redundant=0,class_sep=1,random_state=seed)
    cv=KFold(k,shuffle=True,random_state=seed+3)
    ds=np.array([score_diff(X,y,tr,te,seed+10*i,alternative) for i,(tr,te) in enumerate(cv.split(X))])
    sd=ds.std(ddof=1); p_naive=float(2*t.sf(abs(ds.mean()/(sd/np.sqrt(k))),k-1)) if sd else 1.
    splitter=ShuffleSplit(n_splits=5,test_size=.5,random_state=seed+7)
    pairs=[]
    for i,(tr,te) in enumerate(splitter.split(X)):
        pairs.append([score_diff(X,y,tr,te,seed+20*i,alternative),score_diff(X,y,te,tr,seed+20*i+1,alternative)])
    p5,pf=five_by_two(pairs)
    splitter=ShuffleSplit(n_splits=10,test_size=.1,random_state=seed+11)
    ds=np.array([score_diff(X,y,tr,te,seed+30*i,alternative) for i,(tr,te) in enumerate(splitter.split(X))])
    return np.array([p_naive,p5,pf,corrected_t(ds,n-int(np.ceil(.1*n)),int(np.ceil(.1*n)))])

for n in (120,300):
    for k in (5,10):
        for alternative in (False,True):
            rows=np.array([one_experiment(n,k,1000+i,alternative) for i in range(100)])
            valid=np.isfinite(rows)
            rates=np.sum((rows<.05)&valid,axis=0)/np.maximum(valid.sum(axis=0),1)
            print(n,k,'alternativa' if alternative else 'nula',rates,'válidos',valid.sum(axis=0),flush=True)
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

This local cell takes longer than a browser example because it runs every condition. The null here means two algorithms with the same distribution, not identical concrete predictions. The alternative changes one hyperparameter, but magnitude and even sign of improvement depend on the sample. Rejection rates under that alternative are power only for this generator and rule. A rate of 0.08 in 100 replicates has approximate Monte Carlo standard error 0.027; it does not precisely distinguish a true rate of 0.05.

Two real networks, ten seeds

The digits dataset included in scikit-learn contains digit images. A fixed stratified split is held out before training and MLPs with 64 and 128 hidden units, 20 epochs, and ten seeds are compared. After an exploratory pilot with split 42, an illustrative ROPE of ±0.01 was fixed for the split-43 run. Since splits share data and the pilot was observed, this is not an independent confirmatory study. Minibatch orders are shared by seed; layer size changes initialization, so identical weights are not claimed. The compressed file stores predictions, labels, indices, and correctness for later audit. You need PyTorch with CUDA and scikit-learn; state an environment change if using another platform.

[ ]Train, save predictions, and analyzeLocal GPU
import numpy as np
import torch
from sklearn.datasets import load_digits
from sklearn.model_selection import train_test_split
torch.set_num_threads(1)
if not torch.cuda.is_available(): raise RuntimeError('Esta ejecución requiere CUDA')
device=torch.device('cuda'); digits=load_digits()
x=digits.data.astype(np.float32)/16; y=digits.target.astype(np.int64)
train,test=train_test_split(np.arange(len(y)),test_size=.2,stratify=y,random_state=43)
X=torch.tensor(x,device=device);Y=torch.tensor(y,device=device);predictions=[]
for seed in range(10):
    row=[]; order_rng=np.random.default_rng(seed+1000)
    orders=[order_rng.permutation(train) for _ in range(20)]
    for width in (64,128):
        torch.manual_seed(seed)
        net=torch.nn.Sequential(torch.nn.Linear(64,width),torch.nn.ReLU(),torch.nn.Linear(width,10)).to(device)
        opt=torch.optim.Adam(net.parameters(),lr=.001)
        for order in orders:
            for start in range(0,len(order),128):
                batch=order[start:start+128];opt.zero_grad(set_to_none=True)
                loss=torch.nn.functional.cross_entropy(net(X[batch]),Y[batch]);loss.backward();opt.step()
        net.eval()
        with torch.no_grad(): pred=net(X[test]).argmax(1).cpu().numpy()
        row.append(pred)
    predictions.append(row)
    print('semilla',seed,'precisiones',*(float(np.mean(v==y[test])) for v in row),flush=True)
predictions=np.asarray(predictions)
scores=(predictions==y[test][None,None,:]).astype(np.int8)
np.savez_compressed('digits_comparacion.npz',predictions=predictions,truth=y[test],test_indices=test,scores=scores)
R,N=scores.shape[0],scores.shape[2]; d=scores[:,1,:]-scores[:,0,:]
rng=np.random.default_rng(31); boot=np.empty(10000)
for i in range(len(boot)):
    si=rng.integers(R,size=R);ti=rng.integers(N,size=N)
    boot[i]=d[np.ix_(si,ti)].mean()
print('dispositivo',torch.cuda.get_device_name(),'train/test',len(train),len(test))
print('B−A e IC percentil cruzado:',float(d.mean()),np.quantile(boot,[.025,.975]))
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

In our RTX 3060 run with 1437 training examples and 360 test examples, B−A was 0.01694 and the 95% crossed percentile-bootstrap interval was [0.00611, 0.02944]. This interval excludes zero but crosses the upper margin 0.01: under the fixed rule, practical relevance is inconclusive. Calculation resamples test seeds and items and does not measure variation of training split, population change, or hyperparameter tuning. For seed 0, exact McNemar had one A-only correct and eleven B-only correct, p=0.00635p=0.00635; it answers a different question about that fixed pair. Figures may vary by version and hardware.

Exercises

Numeric
A is correct and B wrong on 30 items; B is correct and A wrong on 15. Calculate the continuity-corrected McNemar statistic.
Numeric
There are 10 splits with 90% training and 10% test. By what factor is the naive t-test variance estimate multiplied in the corrected resampled t-test?
Proof
Prove: The mean of J differences with variance σ² and common correlation ρ has variance σ²(ρ + (1−ρ)/J).
0
Pairwise correlation implies Cov(D_i,D_j)=ρσ² for distinct i and j.

Step 1 of 3. How many off-diagonal covariances are in the expansion of the sum?

Code
Implement paired_bootstrap(a,b,n_boot,seed): mean difference A−B, 95% percentile interval, and two-sided p-value by centered bootstrap with +1 correction. Use joint indices in NumPy.
def paired_bootstrap(a,b,n_boot,seed):
  pass
Shift+Enter to run
Quiz
You have ten training pairs and a common test. You want uncertainty over seeds and items from that population. Which analysis respects the design?
Quiz
You want to compare two systems on F1 for questions grouped by document. Which procedure preserves unit and metric?
Key idea
Choosing a test means choosing what repeats and which uncertainty to generalize. Preserve pairs and groups; communicate magnitude, interval, and relevance in addition to p-value.