The scientific method applied to machine learning
Scientific claims in ML and the evidence required for existence, comparison, mechanism, generality, and theoretical guarantees. Falsifiable hypotheses, Platt's strong inference, exploratory and confirmatory research, and a research cycle begin with a hypothesis plan as code.
After this lesson you can
- Classify real claims from paper abstracts and state the minimum evidence each type requires.
- Rewrite a vague claim as a falsifiable hypothesis with a population, intervention, comparator, metric, expected effect size, and refuting outcome.
- Design a crucial experiment to discriminate between rival hypotheses about the same phenomenon.
- Distinguish exploratory from confirmatory analyses and quantify by simulation the cost of presenting one as the other (HARKing).
- Describe the module's research cycle and the artifacts produced at each stage.
Before you start
An improvement does not explain itself
A new training recipe scores better than its predecessor. Have you discovered a mechanism, an improvement across a population of tasks, or simply a configuration that won on one split? The number can be correct and still leave your question unanswered. The scientific method starts before execution: separate what you observe, what you predict, and what would make you change your mind.
In a review of neural recommendation systems, Ferrari Dacrema and colleagues reported that conceptually simple methods outperformed 11 of the 12 neural approaches they managed to reproduce. Their findings concern the papers, data, and protocols in that study; they do not establish that a universal fraction of all ML improvements disappears. The practical lesson is general: a comparison only informs us about alternatives that were actually tested.
The distinction between “I could not reproduce it” and “a simple method obtained a better result” matters. The first observation can result from data, code, environment, or missing details; the second also depends on how both alternatives are tuned and on the metric. A replication should record discrepancies before turning either observation into a causal explanation. This distinction also protects the original result: a failed replication does not automatically show that the paper was wrong.
What kind of claim are you making?
Scientific claims can overlap; the classification helps you ask what evidence is missing rather than assign a single label to an entire paper.
| Type | Question | Evidence needed |
|---|---|---|
| Existence | Can it happen at least once under precise conditions? | A verifiable example; an impossibility claim requires more than failing to find one. |
| Comparison | Does A outperform B under a protocol? | The same tasks, metrics, and budgets, uncertainty, and strong baselines. |
| Mechanism | Does C produce the observed improvement? | Interventions that distinguish C from rival causes without changing other relevant factors. |
| Generality | Does it hold beyond the chosen cases? | Tasks, populations, or conditions chosen to test the scope. |
| Guarantee | Does a property hold under explicit assumptions? | A mathematical statement and proof; its assumptions must match the proposed use. |
The Adam abstract combines an empirical comparison with a claimed regret bound in an online convex optimization setting. That claim needs scrutiny: Reddi and colleagues identified problems in the earlier analysis and provided a convex counterexample where convergence fails. It does not follow that every non-convex network trained with Adam converges or that Adam always fails. The Batch Normalization abstract reports the same accuracy with 14 times fewer training steps for a specific image classification model. That comparison alone does not establish the proposed causal explanation. ResNet reports 3.57% ImageNet test error for an ensemble; do not attribute that figure to a single model. Lottery Ticket claims the existence of trainable subnetworks under its procedure and conditions, not that every sparse subnetwork or initialization works.
Read each result as a pair of sentences: “this was observed” and “therefore this claim is supported”. The first must name what was measured; the second should not extend to a broader population without further evidence. For Lottery Ticket, the abstract describes experiments on specific MNIST and CIFAR-10 architectures and subnetworks tied to particular initializations. Finding one such subnetwork supports an existence claim in that context; it does not establish a success rate across all architectures.
The Batch Normalization explanation is another reason to follow subsequent literature. Santurkar and colleagues examined the internal distribution shift hypothesis and proposed another interpretation related to optimization smoothness. That study offers evidence and alternative explanations in its own experiments; it does not turn a mechanistic explanation into a universal truth for every architecture.
Turn an intuition into a prediction
“Normalization improves training” does not specify which models, data, budget, or measure should change. A falsifiable hypothesis makes a prediction that rules out at least one possible outcome under a fixed protocol. For example: across a family and set of tasks listed in advance, with the optimizer, tuning budget, and seeds held constant, adding normalization will reduce mean validation error by at least two percentage points compared with the same architecture without it.
Define as error with the intervention minus error for the comparator. The point prediction is when error is expressed as a proportion. An observed effect of contradicts that point prediction; an uncertainty interval crossing the threshold calls for a predefined decision rule, not a retrospective reading of its sign. Falsifiability and experimental power are different: an insensitive test may be unable to discriminate effects that matter.
To turn the example into an experiment, also define the unit of analysis. If the ten tasks are units and each method is run with paired seeds, specify how you aggregate by task, which splits are held out, and which variation you want to generalize over. An interval for the mean across tasks answers a different question from one that only resamples examples from a single test set. Decide in advance how to treat run failures and what evidence would be sufficient to claim the minimum magnitude, not just a nonzero difference.
A plan predicting a reduction of at least 0.02 can produce four useful outcomes: an interval sufficiently below the threshold; one ruling out that magnitude without ruling out every improvement; one compatible with meaningful effects in both directions; or evidence of harm. The second and third are not the same “negative result”. The exact construction of intervals, the population, and error control are studied later; here, record what observation would support each conclusion before opening the test set.
Rival hypotheses and strong inference
Strong inference, introduced by Platt, organizes alternatives and designs tests capable of distinguishing them. It does not make an experiment an infallible logical proof: a result also depends on implementation, measurements, and auxiliary assumptions. If the control fails, you do not know which branch to discard.
Suppose gradual learning-rate warmup stabilizes Adam in an experiment. One explanation relates the phenomenon to initial variability in the adaptive rate, as proposed by Liu and colleagues; another attributes the benefit to update size, as argued by Ma and Yarats. In transformers, normalization placement and initial gradients can matter under the conditions studied by Xiong and colleagues. These proposals can coexist and interventions do not necessarily isolate a single cause.
To design a test, write down beforehand what each explanation predicts if you alter the second-moment estimate while keeping the update size as comparable as possible. Then measure both, record what actually changed, and allow for mixed results. Simply reducing the initial learning rate can help both explanations and by itself distinguishes little. An outcome tree maps conditional predictions; it does not present measured facts.
In a real test, matching update size does not ensure that all components or directions are equal. Add controls measuring the norm and distribution per layer, initial loss, and optimizer state; record whether the intervention also changes noise or trajectory. If the proposed test cannot hold those variables constant, do not call it crucial merely because of its name. A useful rival prediction includes an outcome on which the explanations disagree and specifies what you will do if the manipulation check fails.
Explore, confirm, and contribute
A contribution can be a method, measurement, proof, dataset, replication, or negative result that delineates conditions. The value of a negative result depends on sensitivity and scope: “I did not detect an improvement” does not mean “I proved none exists”.
An informative negative result states which relevant effect it could detect, with what uncertainty, and under which conditions. If an interval still includes both a large improvement and a large harm, the observation is compatible with both. To establish practical equivalence, define in advance a region of sufficiently small differences and design the analysis for that claim; a p-value above 0.05 in a difference test does not establish equivalence.
Exploration proposes questions from data; confirmation evaluates a prediction and analysis fixed before seeing the confirmatory data. Formulating a hypothesis after observing a result and presenting it as prior is known as HARKing. Exploration is useful, but concealing selection changes how p-values should be interpreted. Analysis flexibility can make the best result look more convincing than it is when discarded attempts are ignored.
A lightweight preregistration can include the question, units of analysis, inclusion criteria, intervention, metric, meaningful effect, intended sample, stopping rule, and analysis. Nosek and colleagues describe preregistration as a way to distinguish prior decisions from data-dependent analyses. If an exception is necessary, document when and why the plan changed and present the modified analysis with its actual status. A record does not automatically validate a test or prevent exploratory data from informing the next hypothesis.
If independent tests are run under null hypotheses and each has false-positive probability , the probability of at least one false positive is . Independence is an assumption of the calculation, not an automatic property of analyses on the same dataset. A holdout helps if selection is made without looking at it and a single prediction is evaluated there; repeatedly consulting the holdout turns it back into exploratory data. Review type I and II errors and p-values before interpreting the result.
The derivation uses the complement: each test fails to reject with probability under its null; for independent tests, the probability that none rejects is . Its complement is the probability of at least one false rejection. Under those assumptions, the calculation describes the whole family of tests, not the probability that a specific hypothesis is true after observing its p-value.
Lab: selection under the null
Suppose each analysis produces the mean of independent normal observations with mean zero and known variance one. Its standardized statistic is exactly standard normal. To simulate thousands of projects you need not generate every observation: generate that statistic directly and divide it by to obtain the mean. The analyses in this lab are independent by construction; with correlated analyses the formula above does not apply without modification.
In each project select the analysis with the largest absolute statistic. In the first column you reuse that same statistic; in the second you look once at the independent holdout statistic for the same option. Because selection does not use the holdout, its null rate is under this protocol. If you also require the initial result to be significant before opening the holdout, the joint rate changes: here, the decision to check the holdout is always made.
import numpy as np
from scipy.stats import norm
rng = np.random.default_rng(31)
projects, k, n, alpha = 12000, 10, 40, 0.05
explore = rng.standard_normal((projects, k))
holdout = rng.standard_normal((projects, k))
choice = np.argmax(np.abs(explore), axis=1)
rows = np.arange(projects)
critical = norm.ppf(1-alpha/2)
reused = np.mean(np.abs(explore[rows, choice]) > critical)
reserved = np.mean(np.abs(holdout[rows, choice]) > critical)
mean_selected = np.mean(np.abs(explore[rows, choice])) / np.sqrt(n)
print('misma muestra', round(reused, 4), 'reserva', round(reserved, 4))
print('teoría misma muestra', round(1-(1-alpha)**k, 6), 'teoría reserva', alpha)
print('media absoluta del efecto seleccionado', round(mean_selected, 4))The simulation estimates proportions: changing the seed produces fluctuations. Increasing reduces the scale of observed effects under the null, but the threshold of a standardized test changes on that scale too. Thus, in this model, the false-positive probability per test remains ; increasing alone does not fix multiple selection.
The research cycle connects question and literature search, formalization and predictions, design and pilot, execution and analysis, failure critique, and communication. Save the plan, code version, data, seeds, and changes in the lab notebook; a hash detects changes to content but does not by itself establish when it was created or prevent edits.
| Stage | Question to answer | Artifact |
|---|---|---|
| Search and formulation | What is known and what result would distinguish my idea? | Literature map and predictions. |
| Design and pilot | What do I compare, with what budget and unit of analysis? | Dated plan, configuration, and stopping rule. |
| Execution and analysis | What happened under the intended protocol? | Seeds, logs, metrics, and decisions. |
| Critique and communication | What alternatives and limitations remain? | Failure log, figures, uncertainty, and bounded claims. |
The cycle is not a straight line. A pilot may reveal a faulty metric and lead you to reformulate the question; register the new prediction as new. An exploratory finding can start another cycle with independent data. The provenance record lets you reconstruct which version produced each result without pretending that every decision was made at the start.
First researchkit module
Download researchkit.py. The file contains the classes from this lesson and can be placed in a local project. Browser sessions are independent across pages: a module run here is not assumed to be automatically available in another lesson.
"""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)
question = ResearchQuestion('¿Reduce el error?', 'Diez tareas fijadas', 'Normalización', 'Sin normalización')
prediction = Prediction('Error medio, proporción', 'decrease', 0.02, 'Diferencia mayor que -0.02', (-0.05, 0, 0.05))
hypothesis = Hypothesis('La intervención reduce el error al menos 0.02', question, (prediction,))
print(hypothesis.checks())
print(hypothesis.markdown('2026-11-17'))Differences are defined as intervention minus comparator. increase requires at least min_effect; decrease requires a decrease of that magnitude; two_sided accepts either sign. The possible_effects values are witnesses chosen to verify that the rule admits and excludes at least one outcome. The validator does not understand the text of refutation, prove that the witnesses cover all outcomes, or decide statistical significance. Review them alongside the population and protocol before interpreting the plan.
The refuting-condition text and the executable rule must agree. For example, for an error to minimize and a difference defined as intervention minus control, decrease with magnitude 0.02 accepts and more negative values; the incompatible condition is a difference greater than . If you reverse the subtraction, you must also change the direction. The program does not know whether “error” is expressed as a percentage or proportion, so that unit belongs in the metric name and the experimental plan.
The hash is calculated over canonical JSON containing the date and structured content. Repeating serialization of the same plan produces the same identifier; changing a field normally changes the digest. Retaining only the hash does not let you reconstruct the plan, and putting a date in the document does not prove it existed then. For a verifiable timestamp you need a repository, a registration service, or an appropriate external procedure; also retain the document and its revisions.
Exercises
valid_hypothesis(spec) for a dictionary with metric, direction, min_effect, refutation, and possible_effects. Return True only if the texts are nonempty, the direction is increase, decrease, or two_sided, the magnitude is positive and finite, and there are at least two distinct finite candidate effects including one compatible and one incompatible effect. An effect is intervention minus comparator; do not infer that larger is always better.def valid_hypothesis(spec):
passSummary
- A performance comparison, a causal explanation, and a mathematical guarantee require different evidence.
- An operational hypothesis fixes population, intervention, comparator, metric, magnitude, and refuting condition; it also needs a plan for uncertainty.
- Exploration is legitimate. Confirmation requires a prediction and rule fixed before examining held-out evidence.
- A file and its hash help establish provenance; they do not replace a reliable dated record or critical scrutiny of decisions.