Ablation studies: which component produces the gain
Ablation as an attribution experiment: compare leave-one-out, add-one, full and fractional factorial designs, and dose sweeps; understand how interactions make order matter and how component Shapley allocates improvement; distinguish component ablation from mechanism ablation. Apply these ideas to real tables and a locally trained network.
After this lesson you can
- Choose a leave-one-out, add-one, full or fractional factorial, or dose-sweep ablation for the budget and question.
- Estimate main effects and component interactions with uncertainty across seeds.
- Calculate each component's Shapley attribution and prove that they allocate total improvement exactly.
- Detect the retuning confound where components seem important because other hyperparameters are not retuned after removal.
- Design a mechanism ablation testing the proposed explanation rather than only the component.
Before you start
Removing a component does not automatically allocate the improvement
An ablation intervenes on parts of a system and measures how an outcome changes. If a recipe has components A and B, removing A from the full system measures ; adding A to the empty system measures . These are different questions when A and B interact. Do not add the differences from removing each component and present them as exclusive percentages of total improvement without checking that dependence.
For , , , and , adding A first contributes 2 and adding it after B contributes 5. Removing A from the full system costs 5 and removing B costs 4: together they sum to 9, although total improvement is 6. The interaction is counted twice when removing one. These numbers are a constructed example, not a real experiment table.
Specify the intervention
Before running, define what “remove” means for each component. Removing a layer can change parameter count, cost, and activation scale; replacing it with identity preserves some dimensions but not necessarily signal distribution. Disabling augmentation can change data diversity; reducing example count to equalize time changes another property. Write the treatment and which variables are held fixed or retuned.
The metric also determines attribution. A component can improve accuracy and worsen calibration or latency. If a table contains a minimized loss, decide whether utility is defined as the negative of that loss; otherwise contribution signs reverse. Specify whether numbers are seed averages, best checkpoints, or one run. An exact sum of contributions to a poorly measured table does not make the table correct.
A combination may be infeasible: for example, B may require A to be defined. In that case a full factorial of independent switches does not represent the real system. You can define an alternative intervention making the combination feasible, restrict the coalition family, or ask a different question, but explain how interpretation changes. Filling impossible combinations with invented values would invalidate both interaction and Shapley.
Choose a design
Ablation designs address different questions and budgets. Removing one holds the rest of the full system fixed and tests local dependence. Adding one to empty measures isolated contribution. A full factorial with binary components observes combinations and estimates interactions; it costs times the seed count, excluding tuning. A dose sweep examines continuous values or levels of one component but remains conditional on the other factors.
A regular fraction reduces combinations by sacrificing separate identification. For three factors A, B, and C with in ±1 coding, the defining relation is . A is aliased with BC, B with AC, and C with AB; the intercept is also aliased with ABC. If the main effect appears large, this design cannot tell whether it comes from A, BC, or both. A fraction is useful when its aliases are acceptable for the question, not a free way to obtain the full factorial.
In a full factorial, A’s effect can be defined as the mean difference between configurations with and without A, averaged over other factors. The two-factor interaction is a difference of differences: . If zero, A’s effect is equal at both B levels in that table; this does not imply no interaction with a third factor. With seeds, calculate the difference of differences within each block and analyze variation rather than treating every paired cell as independent.
Interactions and measurement error
With two factors, plot response against A for each B level. If slopes differ, the table’s difference of differences is nonzero. With noisy data, estimated slopes may differ even when the population interaction is zero. A paired replication allows an interaction to be calculated per seed and variation of those contrasts estimated; superficially sharing a seed does not guarantee every random source is paired.
In a balanced factorial with 0/1 coding, A’s coefficient in a regression with A×B interaction is A’s effect when B=0. A’s effect when B=1 is that coefficient plus the interaction coefficient. With -1/+1 coding, coefficient scales and interpretations change; report coding before comparing coefficients across tables. An average main effect is not necessarily the component’s effect in the full system.
With three factors, an A×B interaction can depend on C. The three-way term measures how the difference of differences changes when C is enabled. Observing only the full system and three removals gives too few equations to separate every effect and interaction of the eight coalitions. A fractional design adds alias structure: it estimates certain combined contrasts but requires assumptions or additional runs to separate them.
Shapley and total improvement
Shapley attribution averages a component’s marginal contribution over every permutation. For components and coalition not containing ,
In each order, increments telescope from to . Averaging orders gives . In the two-component example, and . Shapley allocates interaction by this symmetric rule; it does not prove each component alone causes its attribution outside the defined protocol.
Without interactions, removing one sums to total improvement. The converse is not generally true: interactions can cancel. For example, with three components define if A and B are present, minus if A, B, and C are present. Total improvement is 0.5 and the three removals contribute 0.5, 0.5, and -0.5, also summing to 0.5 despite interactions. For two components, equality of sums is equivalent to zero second-order interaction. This distinction avoids inferring no interaction from a matching sum.
Exact Shapley calculation needs all relevant coalitions and grows exponentially. With only a fraction, unique attributions cannot be reconstructed without additional assumptions. Sampling permutations reduces evaluations but introduces Monte Carlo uncertainty and must define how seeds are shared across coalitions. Attribution depends on metric, empty reference, data, and tuning regime.
What Shapley provides
The Shapley rule satisfies efficiency, symmetry, nullity of a component that never changes value, and additivity across games. These properties characterize one way to allocate improvement under its assumptions. Symmetry means two components with identical marginals receive the same value; it does not mean they are physically interchangeable. Attribution is relative to and evaluated coalitions.
A contribution can be negative: a component can worsen mean system metric and still be useful under another condition or metric. If total improvement is almost zero, dividing attributions by it to obtain percentages can produce huge, unstable figures. Report contributions in original units and their uncertainty as well as percentages. If the empty value is not a functional system, explain the reference used and the resulting allocation’s meaning.
For uncertainty across paired seeds, resample a seed block and take its results across all coalitions together. Resampling each cell independently breaks design covariance and can change estimated uncertainty of differences. To generalize splits too, a hierarchical bootstrap must resample splits and then seeds within each split; one split supplies no information on that source. The lab implements paired seed resampling and does not claim to estimate uncertainty across datasets.
Retuning and mechanism
The retuning confound appears when removing a component while retaining hyperparameters chosen for the full system. If removing normalization changes the optimal rate, the fixed-rate difference mixes removal’s effect with an unfavorable rate choice. Retuning each variant with comparable budgets asks what performance each system can reach; holding everything fixed asks about a local intervention. Both can be useful if clearly identified.
A mechanism ablation attempts to alter a proposed property while keeping other aspects as comparable as possible. Removing a component and observing worse performance shows the package changed; it does not prove why. Santurkar and colleagues added variable noise after BatchNorm and observed similar training in their configuration despite unstable distributions. That intervention challenges a particular stability explanation without proving every distribution mechanism irrelevant in all networks.
Table 3 of Vaswani and colleagues reports development BLEU of 25.8 for eight heads and 24.9 for one, with key and value dimensions changed to keep compute approximately constant; 16 heads also obtained 25.8. These are observations on that set and configuration, not proof that eight is universally optimal. The table does not provide a seed distribution for that difference or show equal retuning of each variant. A comparison changing head count and dimensions does not isolate each factor separately.
Interpret an architecture ablation
The Transformer table illustrates the difference between useful variation and causal isolation. Changing head count also changes dimensions to keep total cost approximately constant. This answers a question about configurations under a compute constraint; it cannot establish how much difference is due only to head count with everything else fixed. The comparison of key dimensions also retains other base-model choices.
A development table helps choose variants but does not replace held-out evaluation of the chosen variant. When many architecture decisions are tried on the same development set, some differences may reflect selection and noise. Before claiming a small advantage, look for seeds, intervals, tuning budget, and stability on other sets. Missing information in a table does not make the experiment useless: it limits what can be claimed from it.
For an explanation involving gradient variance, an informative intervention could change that variance while attempting to keep mean update size comparable; then measure whether manipulation achieved its purpose and whether performance changed. Also consider an alternative explanation, such as a change in gradient norm or direction. If the intervention changes both properties together, the outcome does not separate causes. State these limits even if component ablation shows a clear difference.
Local lab: factorial on CIFAR-10
The cell requires PyTorch, torchvision, pandas, statsmodels, CUDA, and CIFAR-10 already downloaded in data/ or available in the project environment. It uses a fixed subset of 512 training and 512 evaluation images, a small CNN, and eight epochs. A = learning-rate warmup for two epochs, B = label smoothing 0.1, C = random horizontal flip. It runs all eight masks with three paired seeds, retains the same order and augmentation streams, and calculates effects, Shapley, leave-one-out, and bootstrap over seed columns.
In an RTX 3060 run, mean accuracy without components was 0.19596 and with all three 0.17969: the difference is negative, approximately -0.01628. Shapley attributions were -0.00347, -0.00770, and -0.00510; they sum to that difference. Leave-one-out gave -0.00195, -0.00456, and -0.00456. These are results from one split, three seeds, and a lightly trained recipe: they do not show those components are generally harmful. Bootstrap intervals with only three blocks are particularly unstable.
A factorial regression with seed indicators is also fitted using statsmodels, and NumPy is checked to reproduce its coefficients. The ANOVA table and p-values are printed for inspection but should not be treated as confirmatory without justifying independence, homoscedasticity, and design selection. This run does not retune each combination, so it measures removal or addition effects under fixed hyperparameters.
import json,time,itertools,sys
from pathlib import Path
import numpy as np
import torch
from torch import nn
from torchvision.datasets import CIFAR10
import pandas as pd
import statsmodels.formula.api as smf
import statsmodels.api as sm
torch.set_num_threads(2);torch.backends.cudnn.benchmark=False
if not torch.cuda.is_available(): raise RuntimeError('CUDA requerida')
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)
order=np.random.default_rng(31).permutation(len(X));tr=order[:512];va=order[512:1024]
def run(mask,seed):
torch.manual_seed(seed);torch.cuda.manual_seed_all(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)
order_rng=np.random.default_rng(seed+1000);aug_rng=np.random.default_rng(seed+2000)
warm=bool(mask&1);smooth=bool(mask&2);augment=bool(mask&4)
for epoch in range(8):
opt.param_groups[0]['lr']=.1*min(1.,(epoch+1)/2) if warm else .1
for batch in np.array_split(order_rng.permutation(tr),8):
xb=X[batch];flips=torch.as_tensor(aug_rng.random(len(batch))<.5,device='cuda')
if augment:xb=torch.where(flips[:,None,None,None],xb.flip(-1),xb)
opt.zero_grad(set_to_none=True);loss=nn.functional.cross_entropy(model(xb),Y[batch],label_smoothing=.1 if smooth else 0.);loss.backward();opt.step()
with torch.no_grad():return float((model(X[va]).argmax(1)==Y[va]).float().mean())
def shapley(v):
k=3;out=np.zeros(k)
for i in range(k):
for mask in range(8):
if not mask&(1<<i):out[i]+=(v[mask|(1<<i)]-v[mask])/(k*__import__('math').comb(k-1,mask.bit_count()))
return out
start=time.perf_counter();table=np.array([[run(mask,seed) for seed in (31,32,33)] for mask in range(8)]);means=table.mean(axis=1);phi=shapley(means)
rng=np.random.default_rng(31);boot=np.array([shapley(table[:,rng.integers(0,3,size=3)].mean(axis=1)) for _ in range(2000)])
rows=[{'mask':m,'seed':s,'warm':m&1,'smooth':(m>>1)&1,'augment':(m>>2)&1,'score':table[m,j]} for m in range(8) for j,s in enumerate((31,32,33))]
frame=pd.DataFrame(rows);fit=smf.ols('score ~ C(seed) + warm*smooth*augment',data=frame).fit();anova=sm.stats.anova_lm(fit,typ=2)
result={'table':table.tolist(),'means':means.tolist(),'shapley':phi.tolist(),'ci':np.quantile(boot,[.025,.975],axis=0).tolist(),'loo':(means[7]-means[[6,5,3]]).tolist(),'coefficients':fit.params.to_dict(),'anova':anova.to_dict(),'gpu':torch.cuda.get_device_name(0),'seconds':round(time.perf_counter()-start,2)}
print(json.dumps(result,indent=2))
manual=np.linalg.lstsq(fit.model.exog,frame['score'].to_numpy(),rcond=None)[0]
print('diferencia coeficientes NumPy/statsmodels:',float(np.max(np.abs(manual-fit.params.to_numpy()))))
assert abs(phi.sum()-(means[-1]-means[0]))<1e-12
npm run lab and open the connection link.Read the CNN experiment
The three seeds share the split, and each mask reuses the same initialization and order sequence associated with that seed. Flip draws use a separate generator so enabling or disabling augmentation does not accidentally change minibatch order. Even so, trajectories diverge after intervention and operations are not identical; paired streams do not make trainings identical.
Evaluation accuracy is a proportion over 512 images and changes in increments of 1/512. Per-seed results vary greatly and the model receives only eight epochs; that scale explains why a general conclusion would be excessive. Bootstrap of three columns has few possible combinations and its percentiles should not be confused with guaranteed coverage. For research, repeat with more seeds and splits, record losses and costs, and consider an appropriate nested or crossed design.
In regression, factors use 0/1 coding and seeds are indicators. Each main-factor coefficient corresponds to its effect in the reference combination where other factors are off; it is not automatically its Shapley value. The statsmodels fit lets you check sums of squares and least-squares implementation, but p-values depend on the error model and design. Numerical agreement with NumPy checks a calculation, not statistical assumptions.
Lab: attribution and aliases in researchkit
Download the extended researchkit.py. The cell contains earlier classes and adds shapley_components, fractional_factorial, and bootstrap_shapley. Generator indices are zero-based and refer to base columns; each derived column is their product. Bootstrap jointly resamples seed columns to preserve pairing across coalitions. The file and cell contain the same code; each lesson has its own session.
"""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)}
def shapley_components(values):
"""Tabla de valores por máscara binaria; atribución exacta de Shapley."""
import numpy as np
values=np.asarray(values,dtype=float)
if values.ndim!=1 or len(values)<2 or not np.isfinite(values).all() or len(values)&(len(values)-1):
raise ValueError('tabla finita de longitud potencia de dos')
k=len(values).bit_length()-1; result=np.zeros(k)
for i in range(k):
bit=1<<i
for mask in range(len(values)):
if mask&bit:continue
size=mask.bit_count();weight=1/(k*math.comb(k-1,size))
result[i]+=weight*(values[mask|bit]-values[mask])
return result
def fractional_factorial(k, generators):
"""Columnas finales son productos de columnas base con índices desde cero.
Devuelve matriz ±1 y grupos de alias (máscara, signo relativo). Incluye
el intercepto máscara 0; no separa efectos que compartan columna.
"""
import numpy as np
if isinstance(k,bool) or not isinstance(k,int) or k<1 or k>10:raise ValueError('k debe estar entre 1 y 10')
if not isinstance(generators,(tuple,list)):raise ValueError('generadores inválidos')
base=k-len(generators)
if base<1:raise ValueError('se necesita al menos una columna base')
for gen in generators:
if not isinstance(gen,(tuple,list)) or not gen or len(set(gen))!=len(gen) or any(isinstance(i,bool) or not isinstance(i,int) or i<0 or i>=base for i in gen):
raise ValueError('cada generador usa índices base distintos')
design=np.array([[1 if row & (1<<i) else -1 for i in range(base)] for row in range(1<<base)],dtype=int)
if generators:design=np.column_stack([design]+[np.prod(design[:,list(gen)],axis=1) for gen in generators])
groups={}
for mask in range(1<<k):
cols=[i for i in range(k) if mask&(1<<i)]
column=np.prod(design[:,cols],axis=1) if cols else np.ones(len(design),dtype=int)
sign=int(column[0]);key=tuple((column*sign).tolist());groups.setdefault(key,[]).append((mask,sign))
return design,list(groups.values())
def bootstrap_shapley(table, repetitions=1000, seed=31):
"""Remuestrea columnas de semillas emparejadas en todas las coaliciones."""
import numpy as np
x=np.asarray(table,dtype=float)
if x.ndim!=2 or x.shape[1]<2 or not np.isfinite(x).all() or repetitions<1:raise ValueError('tabla o repeticiones inválidas')
point=shapley_components(x.mean(axis=1));rng=np.random.default_rng(seed)
samples=np.array([shapley_components(x[:,rng.integers(0,x.shape[1],size=x.shape[1])].mean(axis=1)) for _ in range(repetitions)])
return point,np.quantile(samples,[.025,.975],axis=0)
The following example is synthetic, with three seeds for each of eight coalitions. Masks use bits A, B, and C; the full table is necessary for exact Shapley. A bootstrap interval describes block variation under that procedure, not a guarantee with only three seeds. The fractional design prints mask groups producing the same column, with sign relative to a canonical orientation.
import numpy as np
# Juego de tres componentes, valor de cada coalición por máscara A + 2B + 4C.
table=np.array([[70,69,71],[72,71,73],[71,70,72],[76,74,77],
[70.5,70,71],[74,72,75],[73,71,74],[80,77,82]],dtype=float)
mean=table.mean(axis=1);phi,interval=bootstrap_shapley(table,2000,31)
print('Shapley:',phi,'suma:',phi.sum(),'mejora:',mean[-1]-mean[0])
print('Intervalo bootstrap pareado:',interval)
design,aliases=fractional_factorial(3,[(0,1)])
print('Diseño:',design,'alias (máscara, signo):',aliases)
From design to decision
An ablation plan should list combinations, seeds, metrics, budget per combination, and whether hyperparameters are retuned. Mark effects as confirmatory or exploratory; testing many components and highlighting only the largest raises selection risk. Also retain failures, infeasible configurations, and each training’s cost. If budget cannot support a factorial, use a fraction knowing which effects are aliased and describe a second stage to resolve relevant aliases.
Before interpreting the table, check accounting: every expected combination should be present, paired seeds should correspond, and reference values should use the same metric. Verify Shapley efficiency numerically as an implementation check, but do not use it alone: an incorrect permutation of masks can preserve the sum while assigning values to the wrong components. An additive game with known contributions and another with interaction provide complementary controls.
Exercises
Step 1 of 2. What happens when increments are summed in a fixed order?
import numpy as np
def fractional_factorial(k, generators):
passSummary
An ablation defines an intervention and context; interactions make order matter. Factorials and Shapley make the structure explicit, while fractional designs confound effects according to their aliases. Retuning changes the question, and testing a mechanism requires intervening on and measuring the proposed property.