Module contents
Lesson 7 of 23Core 105 min

Experimental design in machine learning

Classical experimental design for model training: experimental units, variance sources, confounders, controls, plans written before execution, and pilots for estimating variability and sizing the main experiment.

After this lesson you can

  • Identify the experimental unit and replication level appropriate to a question.
  • List and measure training variance sources and decompose total variance into components.
  • Detect confounders including compute, tuning budget, data, and implementation details in a comparison.
  • Use shared seeds as blocks to reduce variance of paired comparisons.
  • Write an experimental plan with hypothesis, design, planned analysis, and pilot-justified seed count.

Before you start

What was actually repeated?

Two runs of the same code may differ because of initialization, data order, augmentation, splitting, tuning, or implementation. Bouthillier and colleagues studied several sources of variation in benchmarks; Picard showed that exploring many seeds can find extreme accuracy values. A reproducible seed permits repeating one run, but choosing the best after seeing results does not estimate a recipe’s typical performance.

The experimental unit is the unit receiving an independent intervention about which inference is intended. For training variation on a fixed task and split, a run with an independent initialization can be a unit. For vision tasks generally, ten seeds on one dataset are not ten independent tasks. If splits share examples or methods run on the same block, results may be correlated and analysis must preserve that structure.

QuestionRelevant unitWhat does not automatically follow
Stability on a fixed taskRun with declared randomized sourcesVariation between tasks.
Comparison on one splitPaired difference by seed block and protocolGeneralization to other splits.
Performance across tasksTask or dataset selected for the target populationIndependence of all per-seed metrics within each task.
Change to another datasetTarget dataset and its samplingPerformance on every future domain.

Repeated evaluation of the same model on the same test does not create new trainings. A finite test adds measurement uncertainty that may be shared between methods. Decide whether the population of interest includes new seeds, splits, projects, or tasks, and design replication at that level. An aggregate mean without that decision can have a narrow interval describing only part of the variability.

Units, population, and pseudoreplication

Suppose you train each method five times on each of ten datasets and obtain fifty scores per method. There are fifty runs, but not necessarily fifty independent tasks. To infer the mean difference across tasks, one option is to summarize seeds within each task and analyze the ten per-task differences, provided those tasks represent the population of interest. A hierarchical model can retain more structure but must specify dependence and effect distributions.

Pseudoreplication occurs when observations sharing an important source of variation are counted as independent units. For example, ten checkpoints from one training are not ten trainings; their errors share data, initialization, and trajectory. Ten images from one patient do not represent ten independent patients for a question about generalization across patients. The solution is not simply to discard data, but to identify the randomization level and use aggregation or a model respecting that dependence.

When methods share a test, their per-example errors are paired. When they share a split, method differences can be paired by split. But reusing the same test to choose among many recipes makes the test part of selection. Keep a holdout for final evaluation or declare the comparison exploratory. No universal seed count turns a question about one task into evidence about every task.

Variance sources and components

Sources of variance include initial parameters, minibatch order, augmentation, data sampling, splits, hyperparameter search, and nondeterministic operations. Some interact: an initialization’s effect may change with the split. Fixing a source measures variability conditional on that value; it does not imply equal recipe stability as the source varies. The following model is synthetic, additive, and independent, with deviations chosen for illustration; its numbers are not attributed to the cited study.

InteractiveVariance budget

In this model components are independent and additive, so their variances add. Fixing a source reduces conditional variation; that does not prove that the conclusion generalizes to other configurations.

Initialization: 0.090
Order: 0.040
Augmentations: 0.063
Split: 0.160
Tuning: 0.122

A real distribution may include interactions and covariances; the proportions in this example are not universal values and do not reproduce Bouthillier’s quantitative results.

Conditional variance0.475
Deviation0.689
Activate or fix sources and observe conditional variance under a simple additive model. Real components may interact.

For a balanced design with aa splits and bb independent initializations per split, consider Yij=μ+ui+ϵijY_{ij}=\mu+u_i+\epsilon_{ij}, with independent components of variance σp2\sigma_p^2 and σe2\sigma_e^2. Expected mean squares are E[MSW]=σe2E[MS_W]=\sigma_e^2 and E[MSB]=σe2+bσp2E[MS_B]=\sigma_e^2+b\sigma_p^2. The method of moments estimates σ^e2=MSW\hat\sigma_e^2=MS_W and σ^p2=(MSB−MSW)/b\hat\sigma_p^2=(MS_B-MS_W)/b. A negative estimate can be truncated to zero to present a nonnegative variance, but retain the untruncated value: it does not prove the true component is exactly zero.

This model requires balance, unit definitions, and assumptions about independence and effects. Overlapping splits or reused seeds can violate these through covariance; the estimate loses the simple interpretation above. Within-split variation includes everything changed between runs in that design, not necessarily initialization alone if order or augmentation also varied. A source decomposition requires controlling the rest or a factorial design that can identify interactions.

Read the mean squares

Each row mean summarizes a split. MSBMS_B measures dispersion of those means, multiplied by seed count; MSWMS_W measures dispersion of runs around their split mean. Subtracting MSWMS_W from MSBMS_B corrects for within-split variation that also affects the means. Dividing by bb gives the method-of-moments estimate of between-split variance under the balanced model. With only one split or one run per split, some quantities cannot be estimated by that formula.

Truncating to zero avoids reporting a negative variance, but introduces a boundary in the estimator and does not prove absence of variation. With few splits, mean squares are noisy; an appropriate interval may be wide even when the point estimate is small. The conclusion also depends on what counts as a random split and how observations were selected. Five splits of a fixed dataset can overlap and do not represent five new independent datasets.

A crossed design combining the same seeds with every split can study both factors and their interaction, but cannot simply be analyzed with the nested formula. A nested design assigns different seed levels within each split; that estimates within-split variation but does not separate seed-split interaction without more structure. Before calculating ANOVA, draw the assignment table and name what each component includes.

Compare under a protocol

A controlled comparison deliberately fixes or randomizes conditions. Define data, split, base architecture, optimizer, compute and tuning budget, trial count, stopping rule, and checkpoint selection. If the new method needs more compute, you can compare at equal budget and also describe the best result at its actual cost. These are different questions; report both if relevant.

A confounder changes along with the intervention and may explain part of the difference. If architecture, augmentation, and schedule all change, the comparison measures the whole package but does not isolate architecture. Henderson and colleagues document the importance of implementations, hyperparameters, and variability when interpreting reinforcement-learning results. The following example is constructed and does not provide measured causal effects.

InteractiveConfiguration detective

On mobile, scroll the table horizontally to see all columns.

FieldBaselineProposedMark
Datav1v2
SplitAA
Preprocessingstandardstandard
Augmentationsnonecrop + rotation
Epochs2040
Initial rate0.010.01
Scheduleconstantcosine
OptimizerSGDSGD
Batch6464
Decay0.0010.001
Tuning trials1050
Selection metricvalidationvalidation
Checkpointlastbest validation
Seeds1–51–5
HardwareGPU AGPU A
Precisionfp32fp32
Library version11
Time per trial1 h1 h
Architecturebaselineproposed
Evaluation codev1v2

Architecture is the intended intervention; the other differences can be confounded with it. This record does not quantify causal contributions: that requires further interventions and controls.

Matches with annotationnot reviewed
Mark differing fields and review the annotation. Architecture is the deliberate intervention; other differences can confound attribution.

An ablation can retain the new schedule and remove the component of interest, but if removal requires different tuning that change must be stated. Keep traces of every attempt, including failures, rather than reporting only the best. Check that both methods used equivalent data, metrics, and evaluation versions. Budget fairness has no single definition: equal trial counts do not equalize cost when trials take different times; equal time can permit different numbers of configurations.

Design controls that distinguish causes

If a new recipe changes architecture, regularization, and epochs together, a package comparison may be useful for deciding what to deploy. To attribute a gain to architecture, add a comparison holding the other decisions fixed and apply a reasonable tuning budget to both. If the old architecture needs a different schedule to work well, one shared hyperparameter set may be unfair. Document search space, selection criterion, and cost of both procedures.

Randomization reduces systematic associations between conditions and uncontrolled factors but does not replace an appropriate control. If all baseline trials run on one day and all new-method trials another, a library update or hardware change may be confounded with method. Interleaving or randomizing execution order helps detect that problem. Retain data version, code hash, and environment; a record helps replication but does not guarantee correct measurement.

The selection metric belongs in the protocol. Choosing a checkpoint by best validation and comparing with a baseline evaluated only at the end changes selection opportunity. Test evaluation must remain outside the tuning loop. If a method requires more experiments to find a good configuration, report total search cost as well as the cost of one chosen training. Do not silently remove out-of-memory failures: they are part of the recipe’s practical scope.

Shared seeds as blocks

Blocking compares A and B within shared conditions. For differences Di=Bi−AiD_i=B_i-A_i, uncertainty of the mean depends on Var⁡(Di)=σA2+σB2−2Cov⁡(Ai,Bi)\operatorname{Var}(D_i)=\sigma_A^2+\sigma_B^2-2\operatorname{Cov}(A_i,B_i). If both deviations are σ\sigma and correlation is ρ\rho, the ratio to an independent-sample difference of the same size is 1−ρ1-\rho. With ρ=0.8\rho=0.8, variance falls to 0.2 of the reference under this model. Negative correlation can make pairing increase variance.

InteractiveBlock by seed

The variance of each difference is 2(1−ρ) in this model. The ratio relative to independent samples is 1−ρ: positive correlation means blocking reduces variation; negative correlation can increase it.

Approximate total normal interval width for the difference: paired 0.78, unpaired 1.75. With few blocks or estimated variance use an appropriate interval; sharing a seed number does not guarantee corresponding random sources.

0.8
10
Paired variance of the mean0.040
Unpaired variance of the mean0.200
Ratio0.20
The hypothetical model keeps unit variance per method. Adjust correlation and number of blocks, and compare variances and approximate normal intervals.

Sharing a seed integer does not guarantee the same order, augmentations, or initialization if methods consume random numbers differently. Use independent generators per source and record pairing. Sometimes sharing split and order but not weights makes sense because architectures differ. Analyze differences by block rather than two lists as independent; correlation should be estimated from data or justified, not assumed positive for convenience.

What sharing randomness means

A block is a common condition that can affect both methods. If a difficult split harms both, comparing differences within it removes some shared variation. The covariance formula shows why: Var⁡(B−A)\operatorname{Var}(B-A) subtracts twice the covariance. If responses to the common condition move in opposite directions, negative covariance can make pairing less efficient. Blocking’s usefulness is empirical and depends on how pairs are generated.

In code, reserve separate streams for split, initialization, and order. This lets you fix one without freezing the others and repeat a run without depending on random calls elsewhere in the program. Different architectures can consume different numbers of random values; calling manual_seed with the same integer at the start of each does not ensure every later operation uses the same draw. To share order, generate and save the permutation explicitly or use a dedicated generator.

A paired interval is calculated from block differences, not the visual subtraction of two individual mean intervals. If differences are not independent across blocks, for example because test sets overlap heavily, that dependence must enter analysis or limit interpretation. With few observations, normal approximation may be poor; consider a t interval or a resampling method compatible with block structure and state its assumptions.

From pilot to plan

A pilot checks the pipeline and estimates orders of magnitude for time and variability. It can also uncover metric or loss errors. For a mean of nn independent units with deviation ss, estimated standard error is s/ns/\sqrt n: with s=0.4s=0.4 and target 0.1, n≥16n\geq16. This is not a power calculation and does not include uncertainty in ss.

For an approximate two-sided paired test at 5% level, 80% power, and minimum difference δ\delta, a normal approximation is n≈(1.96+0.842)2σD2/δ2n\approx(1.96+0.842)^2\sigma_D^2/\delta^2. Use the deviation of the differences and round up. A deviation estimated by a small pilot fluctuates, so calculated size fluctuates too. The panel simulates that variation under normality; it is not an interval for the unknown deviation of your own pilot.

InteractiveFrom pilot to sample size

The normal approximation for a two-sided 5% test and 80% power is n ≈ (1.96 + 0.842)² σ²/δ². Use the deviation of differences, not that of a single method. This approximates independent units; with few samples or non-normality a tailored power simulation is preferable.

The percentiles describe 1000 simulated pilots with the assumed deviation known. They are not a confidence interval for a real pilot and do not justify stopping the experiment based on significance.

0.40
0.50
5
Size with assumed sd6
Pilots: 5th–95th percentiles2 – 12
Change assumed deviation, minimum magnitude, and pilot size. Percentiles describe 1000 synthetic pilots, not a guarantee for a real experiment.

The experimental plan records question, hypothesis, unit, factors, levels, blocks, metrics, data, seeds, size, budget, analysis, and decision rule before seeing the confirmatory result. If the plan changes, record date and reason; a hash detects changes in canonical content but does not itself prove when it was created or prevent edits. An independent holdout and external record support the distinction between exploration and confirmation.

What to record before starting

The plan should state the primary result and aggregation level. A hypothesis about mean difference per task needs a rule for summarizing seeds and selecting tasks; a hypothesis about one fixed dataset does not automatically extend to others. Fix difference direction and metric units to avoid reversing a sign. If there are multiple metrics or subsets, distinguish primary from exploratory analyses and agree how to handle multiplicity.

Include a failure policy: what happens if a seed runs out of memory, fails to converge, or a dataset is unavailable. Removing only one method’s failures can bias comparison; counting them as an extreme value also needs justification. One alternative is to report failure rate and the metric conditional on success separately. Record hardware changes, versions, and resumptions so each observation’s provenance is auditable.

A pilot may show that time per trial exceeds expectations or that deviation is uncertain. Updating a plan before the main experiment is legitimate if recorded. If pilot data are reused in confirmatory analysis or the sample is enlarged after inspecting the p-value, the inference procedure must account for that decision; calling data a pilot is insufficient. A valid sequential rule must be designed before observing the results that trigger it.

Local lab: splitting and initialization on CIFAR-10

This cell requires PyTorch, torchvision, CUDA, and CIFAR-10 already downloaded in data/ or available in the project environment. It selects five splits from the first 2000 examples: each uses 512 to train and 512 to evaluate; subsets may overlap between splits. Within each, it trains five different initializations of an eight-channel CNN for eight epochs with order fixed by the same order seed. It also varies only order five times in one fixed split and initialization, and repeats one identical run five times.

In an RTX 3060 run, the method of moments yielded a between-split component of 0.000720 and a within-split component of 0.000420 for accuracy as a proportion. Order varied between 0.1934 and 0.2383 in the control; five identical repetitions gave 0.2461. Splits overlap data and change training and evaluation samples together; independence assumptions of the random-effects model are not guaranteed. The between-split component separates neither effect nor estimates a universal variance. Five identical values do not prove determinism of the entire GPU or other metrics; it shows only rounded accuracy under this protocol.

[ ]Variance on CIFAR-10Local GPU
import json,time
from pathlib import Path
import numpy as np
import torch
from torch import nn
from torchvision.datasets import CIFAR10

torch.set_num_threads(2);torch.backends.cudnn.benchmark=False
if not torch.cuda.is_available(): raise RuntimeError('Esta ejecución requiere CUDA')
candidates=[Path('data')]
root=next((p for p in candidates if (p/'cifar-10-batches-py').exists()),Path('data'))
data=CIFAR10(root=str(root),train=True,download=False)
X=torch.tensor(data.data[:2000],device='cuda',dtype=torch.float32).permute(0,3,1,2)/255
Y=torch.tensor(data.targets[:2000],device='cuda',dtype=torch.long)

def train(split_seed, init_seed, order_seed):
    perm=np.random.default_rng(split_seed).permutation(len(X));tr=perm[:512];va=perm[512:1024]
    torch.manual_seed(init_seed);torch.cuda.manual_seed_all(init_seed)
    model=nn.Sequential(nn.Conv2d(3,8,3,padding=1),nn.ReLU(),nn.AvgPool2d(4),nn.Flatten(),nn.Linear(8*8*8,10)).cuda()
    opt=torch.optim.SGD(model.parameters(),lr=.1)
    rng=np.random.default_rng(order_seed)
    for epoch in range(8):
        for batch in np.array_split(rng.permutation(tr),8):
            opt.zero_grad(set_to_none=True);loss=nn.functional.cross_entropy(model(X[batch]),Y[batch]);loss.backward();opt.step()
    with torch.no_grad():
        logits=model(X[va]);acc=float((logits.argmax(1)==Y[va]).float().mean());val_loss=float(nn.functional.cross_entropy(logits,Y[va]))
    return acc,val_loss

def variance_components(values):
    x=np.asarray(values,dtype=float);a,b=x.shape;means=x.mean(axis=1);grand=x.mean()
    between=b*np.sum((means-grand)**2)/(a-1);within=np.sum((x-means[:,None])**2)/(a*(b-1))
    return {'between_ms':float(between),'within_ms':float(within),'partition':float(max((between-within)/b,0)),'within':float(within),'partition_raw':float((between-within)/b)}

start=time.perf_counter();nested=[]
for split in range(5):
    row=[train(100+split,200+5*split+init,300)[0] for init in range(5)];nested.append(row)
order=[train(100,200,400+i)[0] for i in range(5)]
repeat=[train(100,200,300)[0] for _ in range(5)]
result={'nested':nested,'components':variance_components(nested),'order':order,'identical':repeat,'gpu':torch.cuda.get_device_name(0),'seconds':round(time.perf_counter()-start,2)}
print(json.dumps(result,indent=2))

This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

Lab: plan and ANOVA in the browser

Download the extended researchkit.py. It retains earlier classes and adds ExperimentPlan, seeds_for_se, and variance_components; the cell creates the same logical file in the current session. Each page has its own session. The hash is of canonical JSON, not an external timestamp. Seed calculation refers to the standard error of a mean of independent units; power requires an appropriate design and variance.

[ ]Extend researchkitBrowser
"""Planes de hipótesis comprobables para el cuaderno de investigación.

La comprobación lógica trabaja sobre efectos candidatos explícitos; no
demuestra por sí sola la calidad científica ni la validez de un contraste.
"""
from dataclasses import asdict, dataclass
from datetime import date
import hashlib
import json
import math


def _text(value, name):
    if not isinstance(value, str) or not value.strip():
        raise ValueError(f'{name} debe ser texto no vacío')
    return value.strip()


def _finite(value, name):
    if isinstance(value, bool) or not isinstance(value, (int, float)):
        raise ValueError(f'{name} debe ser un número finito')
    try:
        converted = float(value)
    except OverflowError as exc:
        raise ValueError(f'{name} debe ser un número finito') from exc
    if not math.isfinite(converted):
        raise ValueError(f'{name} debe ser un número finito')
    return converted


@dataclass(frozen=True)
class ResearchQuestion:
    question: str
    population: str
    intervention: str
    comparator: str

    def __post_init__(self):
        for name in ('question', 'population', 'intervention', 'comparator'):
            object.__setattr__(self, name, _text(getattr(self, name), name))


@dataclass(frozen=True)
class Prediction:
    metric: str
    direction: str
    min_effect: float
    refutation: str
    possible_effects: tuple[float, ...]

    def __post_init__(self):
        object.__setattr__(self, 'metric', _text(self.metric, 'metric'))
        object.__setattr__(self, 'refutation', _text(self.refutation, 'refutation'))
        if self.direction not in ('increase', 'decrease', 'two_sided'):
            raise ValueError('direction debe ser increase, decrease o two_sided')
        size = _finite(self.min_effect, 'min_effect')
        if size <= 0:
            raise ValueError('min_effect debe ser positivo')
        object.__setattr__(self, 'min_effect', size)
        if not isinstance(self.possible_effects, (tuple, list)):
            raise ValueError('possible_effects debe ser una lista o tupla de efectos')
        effects = tuple(_finite(x, 'possible_effects') for x in self.possible_effects)
        if len(set(effects)) < 2:
            raise ValueError('se requieren al menos dos efectos posibles distintos')
        object.__setattr__(self, 'possible_effects', effects)
        statuses = {self.supports(x) for x in effects}
        if statuses != {False, True}:
            raise ValueError('los efectos candidatos deben incluir apoyo y refutación')

    def supports(self, effect):
        """La diferencia es intervención menos comparador, en unidades de metric."""
        value = _finite(effect, 'effect')
        if self.direction == 'increase':
            return value >= self.min_effect
        if self.direction == 'decrease':
            return value <= -self.min_effect
        return abs(value) >= self.min_effect


@dataclass(frozen=True)
class Hypothesis:
    claim: str
    question: ResearchQuestion
    predictions: tuple[Prediction, ...]

    def __post_init__(self):
        object.__setattr__(self, 'claim', _text(self.claim, 'claim'))
        if not isinstance(self.question, ResearchQuestion):
            raise ValueError('question debe ser ResearchQuestion')
        if not isinstance(self.predictions, (tuple, list)) or not self.predictions:
            raise ValueError('predictions debe contener al menos una predicción')
        predictions = tuple(self.predictions)
        if not all(isinstance(p, Prediction) for p in predictions):
            raise ValueError('cada predicción debe ser Prediction')
        object.__setattr__(self, 'predictions', predictions)

    def checks(self):
        """Enumera efectos candidatos y su compatibilidad, sin evaluar incertidumbre."""
        return [[(x, p.supports(x)) for x in p.possible_effects] for p in self.predictions]

    def markdown(self, day):
        """Documento fechado; hash de contenido canónico, no sello temporal externo."""
        if not isinstance(day, str):
            raise ValueError('day debe ser una fecha ISO')
        try:
            parsed = date.fromisoformat(day)
        except ValueError as exc:
            raise ValueError('day debe ser una fecha ISO válida') from exc
        if parsed.isoformat() != day:
            raise ValueError('day debe tener formato AAAA-MM-DD')
        payload = {'date': day, 'hypothesis': asdict(self)}
        canonical = json.dumps(payload, ensure_ascii=False, sort_keys=True, separators=(',', ':'), allow_nan=False)
        digest = hashlib.sha256(canonical.encode('utf-8')).hexdigest()
        q = self.question
        lines = [f'# Plan de hipótesis ({day})', '', f'Pregunta: {q.question}',
                 f'Población: {q.population}', f'Intervención: {q.intervention}',
                 f'Comparación: {q.comparator}', f'Hipótesis: {self.claim}', '']
        for i, p in enumerate(self.predictions, 1):
            lines.extend([f'## Predicción {i}', f'Métrica: {p.metric}',
                          f'Dirección: {p.direction}; magnitud mínima: {p.min_effect}',
                          f'Condición refutadora: {p.refutation}',
                          f'Efectos candidatos: {list(p.possible_effects)}', ''])
        lines.append(f'SHA-256 del contenido canónico: {digest}')
        return '\n'.join(lines)

@dataclass(frozen=True)
class Evidence:
    id: str
    location: str
    description: str
    scope: tuple[str, ...]

    def __post_init__(self):
        for name in ('id', 'location', 'description'):
            object.__setattr__(self, name, _text(getattr(self, name), name))
        if not isinstance(self.scope, (list, tuple)) or not self.scope:
            raise ValueError('scope debe enumerar condiciones no vacías')
        object.__setattr__(self, 'scope', tuple(_text(x, 'scope') for x in self.scope))


@dataclass(frozen=True)
class Claim:
    id: str
    text: str
    scope: tuple[str, ...]
    evidence_ids: tuple[str, ...] = ()
    unsupported_reason: str = ''

    def __post_init__(self):
        for name in ('id', 'text'):
            object.__setattr__(self, name, _text(getattr(self, name), name))
        if not isinstance(self.scope, (list, tuple)) or not self.scope:
            raise ValueError('scope debe enumerar condiciones no vacías')
        object.__setattr__(self, 'scope', tuple(_text(x, 'scope') for x in self.scope))
        if not isinstance(self.evidence_ids, (list, tuple)):
            raise ValueError('evidence_ids debe ser una lista o tupla')
        object.__setattr__(self, 'evidence_ids', tuple(_text(x, 'evidence_id') for x in self.evidence_ids))
        if not isinstance(self.unsupported_reason, str):
            raise ValueError('unsupported_reason debe ser texto')
        if not self.evidence_ids and not self.unsupported_reason.strip():
            raise ValueError('sin evidencia debe declararse el motivo')


@dataclass(frozen=True)
class ClaimEvidenceMap:
    claims: tuple[Claim, ...]
    evidence: tuple[Evidence, ...]

    def __post_init__(self):
        if not all(isinstance(x, Claim) for x in self.claims) or not all(isinstance(x, Evidence) for x in self.evidence):
            raise ValueError('tipos de afirmación o evidencia inválidos')
        cids = [x.id for x in self.claims]; eids = [x.id for x in self.evidence]
        if len(set(cids)) != len(cids) or len(set(eids)) != len(eids):
            raise ValueError('identificadores duplicados')
        if any(ref not in eids for claim in self.claims for ref in claim.evidence_ids):
            raise ValueError('referencia de evidencia desconocida')
        object.__setattr__(self, 'claims', tuple(self.claims))
        object.__setattr__(self, 'evidence', tuple(self.evidence))

    def unsupported(self):
        return [c.id for c in self.claims if not c.evidence_ids]

    def coverage_report(self):
        """Condiciones explícitas por las que no hay evidencia enlazada.

        Cada elemento de scope es un caso concreto; la unión de evidencias
        enlazadas debe cubrir los casos declarados. No verifica causalidad.
        """
        evidence = {e.id:e for e in self.evidence}
        report = {}
        for c in self.claims:
            covered = {case for ref in c.evidence_ids for case in evidence[ref].scope}
            report[c.id] = {'without_evidence': not c.evidence_ids,
                            'uncovered_scope': sorted(set(c.scope) - covered)}
        return report


@dataclass(frozen=True)
class ReadingCard:
    title: str
    citation: str
    question: str
    contribution: str
    limitations: str
    claim_map: ClaimEvidenceMap

    def __post_init__(self):
        for name in ('title','citation','question','contribution','limitations'):
            object.__setattr__(self, name, _text(getattr(self, name), name))
        if not isinstance(self.claim_map, ClaimEvidenceMap):
            raise ValueError('claim_map inválido')

    def to_markdown(self):
        def clean(value): return value.replace('\n',' ').replace('|','\\|')
        lines = [f'# {self.title}', '', f'Fuente: {self.citation}', '',
                 f'Pregunta: {self.question}', '', f'Contribución: {self.contribution}', '',
                 f'Límites: {self.limitations}', '', '| Afirmación | Evidencia | Alcance sin cubrir |', '|---|---|---|']
        report = self.claim_map.coverage_report()
        evidence = {e.id:e for e in self.claim_map.evidence}
        for c in self.claim_map.claims:
            refs = '; '.join(evidence[r].location for r in c.evidence_ids) or c.unsupported_reason
            missing = ', '.join(report[c.id]['uncovered_scope']) or 'ninguno declarado'
            lines.append(f'| {clean(c.text)} | {clean(refs)} | {clean(missing)} |')
        return '\n'.join(lines)

    def literature_row(self):
        return {'title':self.title, 'citation':self.citation, 'question':self.question,
                'contribution':self.contribution, 'limitations':self.limitations,
                'unsupported_claims':self.claim_map.unsupported()}

@dataclass(frozen=True)
class ExperimentPlan:
    question: str
    hypothesis: str
    unit: str
    factors: tuple[str, ...]
    blocks: tuple[str, ...]
    metrics: tuple[str, ...]
    analysis: str
    seeds: tuple[int, ...]
    decision: str
    date: str

    def __post_init__(self):
        for name in ('question','hypothesis','unit','analysis','decision'):
            object.__setattr__(self,name,_text(getattr(self,name),name))
        for name in ('factors','blocks','metrics'):
            values=getattr(self,name)
            if not isinstance(values,(list,tuple)) or not values:
                raise ValueError(f'{name} necesita una lista no vacía')
            object.__setattr__(self,name,tuple(_text(v,name) for v in values))
        if not isinstance(self.seeds,(list,tuple)) or not self.seeds or any(isinstance(s,bool) or not isinstance(s,int) for s in self.seeds):
            raise ValueError('seeds debe contener enteros')
        if len(set(self.seeds)) != len(self.seeds): raise ValueError('semillas repetidas')
        object.__setattr__(self,'seeds',tuple(self.seeds))
        try: parsed=date.fromisoformat(self.date)
        except (ValueError,TypeError) as exc: raise ValueError('fecha ISO inválida') from exc
        if parsed.isoformat()!=self.date: raise ValueError('fecha debe ser AAAA-MM-DD')

    def markdown(self):
        payload=asdict(self); canonical=json.dumps(payload,ensure_ascii=False,sort_keys=True,separators=(',',':'),allow_nan=False)
        digest=hashlib.sha256(canonical.encode('utf8')).hexdigest()
        lines=[f'# Plan experimental ({self.date})',f'Pregunta: {self.question}',f'Hipótesis: {self.hypothesis}',f'Unidad: {self.unit}',
               f'Factores: {", ".join(self.factors)}',f'Bloques: {", ".join(self.blocks)}',f'Métricas: {", ".join(self.metrics)}',
               f'Análisis: {self.analysis}',f'Semillas: {", ".join(map(str,self.seeds))}',f'Decisión: {self.decision}',
               f'SHA-256 del contenido canónico: {digest}']
        return '\n\n'.join(lines)


def seeds_for_se(sd, target_se):
    """Tamaño aproximado para SE de una media con unidades independientes."""
    sd=_finite(sd,'sd');target_se=_finite(target_se,'target_se')
    if sd<0 or target_se<=0: raise ValueError('sd no negativa y target_se positivo')
    return max(1,math.ceil((sd/target_se)**2))


def variance_components(results):
    """ANOVA anidado equilibrado partición > semilla; varianzas truncadas en cero."""
    import numpy as np
    x=np.asarray(results,dtype=float)
    if x.ndim!=2 or min(x.shape)<2 or not np.isfinite(x).all(): raise ValueError('matriz finita de al menos 2 x 2')
    a,b=x.shape; means=x.mean(axis=1);grand=x.mean()
    ms_between=b*np.sum((means-grand)**2)/(a-1)
    ms_within=np.sum((x-means[:,None])**2)/(a*(b-1))
    raw=(ms_between-ms_within)/b
    return {'partition':float(max(0,raw)), 'within':float(ms_within),
            'partition_raw':float(raw),'between_ms':float(ms_between)}
[ ]Build a planBrowser
plan=ExperimentPlan(
    question='¿Reduce B el error frente a A en esta tarea?',
    hypothesis='La diferencia media B menos A es como máximo -0.02.',
    unit='diferencia por bloque de partición y semilla',
    factors=('método: A, B', 'partición: 10 bloques'),
    blocks=('misma partición y semilla por pareja',),
    metrics=('error de test reservado',),
    analysis='Media de diferencias y su intervalo bilateral; pruebas predefinidas.',
    seeds=tuple(range(10)),
    decision='Apoyar magnitud si el límite superior del intervalo está por debajo de -0.02.',
    date='2026-11-17')
print(plan.markdown())
print('semillas para SE <= 0.1 con sd 0.4:',seeds_for_se(.4,.1))
with open('experiment_plan.md','w',encoding='utf8') as f: f.write(plan.markdown())

In scikit-learn’s digits, the following cell trains a small MLP over five splits and five initializations without shuffling each epoch. It is a browser analysis example, not a comparison of methods or a general vision benchmark. Splits share data and training is limited to 50 iterations; the nested estimate is illustrative and depends on design.

[ ]ANOVA on digitsBrowser
import warnings
import numpy as np
from sklearn.datasets import load_digits
from sklearn.neural_network import MLPClassifier
from sklearn.exceptions import ConvergenceWarning

X,y=load_digits(return_X_y=True);X=X/16
results=[]
with warnings.catch_warnings():
    warnings.simplefilter('ignore',ConvergenceWarning)
    for split in range(5):
        order=np.random.default_rng(100+split).permutation(len(y));train,test=order[:400],order[400:600]
        row=[]
        for seed in range(5):
            model=MLPClassifier(hidden_layer_sizes=(16,),max_iter=50,learning_rate_init=.01,shuffle=False,random_state=200+5*split+seed)
            model.fit(X[train],y[train]);row.append(float(model.score(X[test],y[test])))
        results.append(row)
print('exactitudes por partición e inicialización:',np.round(results,3))
print('componentes:',variance_components(results))

Interpret the decomposition

The lab’s between-split component summarizes differences associated with changing training and validation composition within the first 2000 examples. It does not separately measure training-set effect, validation-set difficulty, and possible interactions. The within component combines initialization effects with any uncontrolled variation in that procedure. Although the order generator is fixed, changing the split changes the examples to which the permutation applies.

The order control uses one split and one initialization: its range shows sensitivity under those conditions, not a representative estimate of all splits. Identical repetitions return the same accuracy in steps of 1/512 but may differ in losses or parameters without changing any class decision. To study GPU nondeterminism, also record losses and hashes or weight differences, repeat under different determinism options, and specify hardware and versions. Zero variation on a coarse metric does not prove bitwise equality.

Components are in squared metric units: if accuracy is a proportion, variance 0.0004 corresponds to deviation approximately 0.02, or two percentage points. Do not add deviations as if they were variances; under independence variances are added and then the square root is taken. With covariance or interactions, simple addition can fail. Use the model to describe a particular design, not as a recipe for assigning causal percentages to arbitrary training.

Exercises

Numeric
If the standard deviation across seeds is 0.4 points, how many independent seeds are needed for standard error at most 0.1 points?
Quiz
You want to infer whether a method improves vision tasks generally. Which unit needs replication for that question?
Code
Implement variance_components(results) for a finite balanced matrix of a splits by b seeds, with a,b >= 2. Return (split_variance, within_variance) by method of moments: MSB = b sum(row_mean - grand_mean)^2/(a-1), MSW = sum((x-row_mean)^2)/(a(b-1)); truncate the split component at zero.
import numpy as np

def variance_components(results):
  pass
Shift+Enter to run
Quiz
You compare an RL method with a baseline from another repository using a different environment version and more tuning. What do you conclude?
Numeric
With unit deviation for each method and correlation 0.8 within each pair, what is the paired-to-unpaired variance ratio of the difference with the same number of pairs?

Summary

The experimental unit determines which variation can be generalized. Fixing sources reduces conditional variation, while blocking can improve precision of differences if it induces positive correlation. A pilot and prior plan expose uncertainty, budgets, and decisions; ANOVA components depend on a particular design and assumptions.