Regularization in networks: dropout, noise and early stopping
Study inverted dropout, its ensemble and adaptive-regularization interpretations, interaction with batch norm, input noise, early stopping, and controlled regularizer ablations.
After this lesson you can
- Implement inverted dropout in forward and backward passes and explain evaluation scaling.
- Derive dropout's adaptive L2 regularizer for a linear model.
- Derive the small-Gaussian-input-noise expansion and its relationship to Jacobian penalties.
- Apply early stopping with patience and restoration of the best checkpoint.
- Design an ablation measuring each regularizer's contribution.
Before you start
- 15AdamW timescaleLabel smoothingMultilayer perceptronBatch normalizationBatch norm running statistics
- 13OverfittingBias-variance decompositionEarly stopping as regularization
- 11Ridge regressionHoldout train, validation and test split
- 14Scalable Bayesian neural network approximations
- 00Full training checkpoint
More capacity than examples
A network can fit patterns that do not generalize. Memorization capacity alone does not say which solution training will choose: data, optimization, and imposed constraints also matter. This lesson compares dropout, noise, and early stopping with familiar regularizers, keeping validation separate from training and test.
A different network at each step
In dropout, each activation is multiplied by an independent mask , with and . Inverted dropout uses
The backward mask is the same as the forward mask. Conditional on , . In evaluation the mask is disabled and remains unscaled. This differs from the original convention of Srivastava and colleagues, where scaling can occur in evaluation; either convention must be used consistently, never mixed.
With neurons up to masks can be sampled, but subnetworks share weights: they are not independently trained models. The full network is interpreted as an approximation to the subnetwork average, not a general equality. A nonlinearity can break equality: with , , and , the unmasked network gives 0.2 while the exact average of the two masks is 0.6. The identities cell reproduces the calculation.
Variance and adaptive regularization
If the mask is independent of an activation with mean and variance , then
The mean is preserved and variance increases except in degenerate cases. With , , and the result is 6; the cell’s example exactly enumerates the equiprobable distribution .
In linear regression with squared error and independent feature masks, for a fixed observation we obtain
Averaging observations penalizes each weight according to its feature’s second moment. The equality is exact for this model with a mask independent of data; it does not turn every nonlinear network into ridge regression. For generalized linear models, Wager, Wang and Liang study an adaptive interpretation using an approximation tied to Fisher information.
To prove it, separate prediction into its deterministic part and mask perturbation: . Each sum term has zero expectation and variance . Squaring eliminates the residual cross term in expectation and, by independence, products between distinct features. If masks share randomness, covariances appear and this diagonal sum no longer suffices.
There is no universal optimal rate. In the short Fashion-MNIST check with 1024 training examples, 512 validation examples, and three seeds, the lowest mean final validation loss among rates 0, 0.2, 0.5, and 0.8 corresponds to ; accuracy could rank runs differently from loss. The local cell reproduces selection. Points share the validation set, so selecting a rate on it is not an independent final test estimate.
Dropout alongside batch norm
If dropout precedes batch norm, its running statistics can reflect a different variance from what arrives when dropout is turned off. For the previous distribution, BN with ideal buffer 6 and receives a variance-1 variable in evaluation and produces variance 1/6 before its affine transform. These are values from an explicit model, not a prediction for every layer.
Li and colleagues study this mismatch in several networks and datasets. In their Table 3, for DenseNet and CIFAR-10 with dropout 0.5 at the studied position, recalibrating statistics with training data changes error from 8.70% to 6.82%, averaged over five seeds. This does not prove every positional change increases accuracy. In our short run, running and clean variance differ clearly when dropout precedes BN, but accuracy does not uniformly improve when it is placed after. A later BN can also receive a dropout-affected signal.
For MC dropout, masks are enabled during multiple inference passes and their predictions summarized. Keep BN in evaluation and enable only dropout layers; calling model.train() would also change other layers and buffers. Gal and Ghahramani propose an approximate Bayesian interpretation under their assumptions: samples are not the exact posterior and do not guarantee calibration.
Input noise and smoothing
Noise injection changes the examples seen by the optimizer. Its effect depends on where it is introduced, the distribution, and loss; here we isolate additive Gaussian input noise.
For a smooth scalar model , loss , and , Taylor expansion and expectation give, under sufficient regularity,
The Jacobian term alone is not the complete expansion: the residual multiplied by also appears. Near a fit with small residual, or for linear , a positive penalty proportional to can remain. Bishop analyzes these conditions and the relationship to Tikhonov regularization. ReLU kinks require additional treatment; do not simply apply an expansion assuming smoothness there.
To see where both terms come from, differentiate loss with respect to input: its first derivative is and second is . The linear Taylor term vanishes because noise has zero mean; the quadratic contributes variance times that second derivative divided by two. A small remainder requires assumptions permitting expansion and expectation to be exchanged. In multiple dimensions, the second-order correction is half the trace of noise covariance times the loss Hessian.
The regression cell trains a tanh network on with 19 points. It compares expectation approximated by five Gauss-Hermite nodes with penalty . After 800 steps, RMS differences between curves on the grid are approximately 0.00269 for and 0.07939 for . This result depends on data, quadrature, and optimization; it does not guarantee agreement or separation on another task. Noise can also be added to activations or weights, but induced penalties and prediction distributions change.
Stop and restore
Early stopping monitors a validation metric, saves the best state, and stops when enough checks pass without improvement. Patience counts checks, not necessarily epochs. At the end, restore parameters and required buffers, such as BN running means. To resume an exact trajectory, also save optimizer, counter, and random states. Test data choose neither the best step nor patience.
The from-scratch cell uses the same tensor engine to train with and without dropout on 160 stratified examples of load_digits; it reserves validation before choosing them. It measures both losses in evaluation mode so curves do not mistakenly compare a noisy training output with a deterministic one. In the short run, stopping with and does not trigger before step 120: code restores the best checkpoint, but those results do not prove early stopping improved validation.
Reproducible labs
The first cell enumerates masks and checks the expansion with quadrature; the second uses current tensor autograd and the third integrates dropout into the engine. The fourth reproduces the figure’s two regression training runs.
"""Identidades exactas de dropout y expansión de ruido gaussiano.
Todos los ejemplos se definen explícitamente y se ejecutan sin entrenamiento;
no representan resultados reales de una red entrenada.
"""
from itertools import product
import numpy as np
def dropout_linear_expectation(x, w, y, p):
if not 0 <= p < 1: raise ValueError('se exige 0 ≤ p < 1')
q = 1-p
expected = 0.
for mask in product((0,1),repeat=len(x)):
probability = np.prod([q if bit else p for bit in mask])
prediction = np.dot(w,x*np.asarray(mask)/q)
expected += probability*(prediction-y)**2
base = (np.dot(w,x)-y)**2
penalty = p/q*np.sum(w*w*x*x)
return expected, base, penalty
for p in (0., .2, .5, .9):
x, w, y = np.array([2.,-1.]), np.array([.7,-.4]), .3
expected, base, penalty = dropout_linear_expectation(x,w,y,p)
assert abs(expected-base-penalty) < 1e-12
print('dropout',p,'MSE esperada',expected,'MSE sin dropout',base,'penalización',penalty)
# Media preservada, pero una no linealidad no conmuta con la esperanza.
baseline = max(0.,1.-.8)
ensemble = .5*max(0.,0.-.8)+.5*max(0.,2.-.8)
assert np.isclose(baseline,.2) and np.isclose(ensemble,.6)
print('ReLU de activación media:',baseline,'media de ReLU de subredes:',ensemble)
# Distribución exacta de X: P(X=1)=P(X=3)=1/2; p=1/2.
train_values, probabilities = np.array([0.,2.,6.]),np.array([.5,.25,.25])
train_mean = float(np.dot(train_values,probabilities))
train_var = float(np.dot((train_values-train_mean)**2,probabilities))
eval_values = np.array([1.,3.])
eval_mean, eval_var = float(eval_values.mean()), float(eval_values.var())
assert train_mean == eval_mean == 2 and train_var == 6 and eval_var == 1
print('Dropout antes de BN: train media/var',train_mean,train_var,'eval',eval_mean,eval_var,
'varianza eval normalizada con buffer ideal:',eval_var/train_var)
# Pérdida 1/2*(f(x)-y)^2 con f(x)=x²; integra Gauss-Hermite exactamente.
def loss_with_noise(x,y,sigma):
nodes, weights = np.polynomial.hermite.hermgauss(12)
noisy = x+np.sqrt(2)*sigma*nodes
return float(np.dot(weights,.5*(noisy*noisy-y)**2)/np.sqrt(np.pi))
def expansion(x,y,sigma):
residual = x*x-y
baseline = .5*residual**2
jacobian_only = baseline+.5*sigma*sigma*(2*x)**2
second_order = baseline+.5*sigma*sigma*((2*x)**2+2*residual)
exact = second_order+1.5*sigma**4
return baseline,jacobian_only,second_order,exact
for y in (.1,.64):
for sigma in (.05,.2):
estimates = expansion(.8,y,sigma)
measured = loss_with_noise(.8,y,sigma)
assert np.isclose(measured,estimates[-1],rtol=0,atol=1e-12)
print('ruido sigma',sigma,'y',y,'cuadratura',measured,'solo jacobiano',estimates[1],
'segundo orden completo',estimates[2])import numpy as np
from copy import deepcopy
def unbroadcast(grad, shape):
grad = np.asarray(grad)
while grad.ndim > len(shape):
grad = grad.sum(axis=0)
for axis, size in enumerate(shape):
if size == 1 and grad.shape[axis] != 1:
grad = grad.sum(axis=axis, keepdims=True)
if grad.shape != tuple(shape):
raise ValueError('formas incompatibles')
return grad
class Tensor:
def __init__(self, data, parents=(), backward=None):
self.data = np.array(data, dtype=np.float64, copy=True)
self.grad = np.zeros_like(self.data)
self.parents = tuple(parents)
self._backward = backward or (lambda: None)
@staticmethod
def wrap(x): return x if isinstance(x, Tensor) else Tensor(x)
def __add__(self, other):
other = Tensor.wrap(other)
a_shape, b_shape = self.data.shape, other.data.shape
out = Tensor(self.data + other.data, (self, other))
def backward():
self.grad += unbroadcast(out.grad, a_shape)
other.grad += unbroadcast(out.grad, b_shape)
out._backward = backward
return out
__radd__ = __add__
def __mul__(self, other):
other = Tensor.wrap(other)
a, b = self.data.copy(), other.data.copy()
out = Tensor(a*b, (self, other))
def backward():
self.grad += unbroadcast(out.grad*b, a.shape)
other.grad += unbroadcast(out.grad*a, b.shape)
out._backward = backward
return out
__rmul__ = __mul__
def __neg__(self): return self * -1
def __sub__(self, other): return self + (-Tensor.wrap(other))
def __rsub__(self, other): return Tensor.wrap(other) - self
def __matmul__(self, other):
other = Tensor.wrap(other)
a, b = self.data.copy(), other.data.copy()
if a.ndim != 2 or b.ndim != 2:
raise ValueError('matmul admite matrices 2D')
out = Tensor(a @ b, (self, other))
def backward():
self.grad += out.grad @ b.T
other.grad += a.T @ out.grad
out._backward = backward
return out
def tanh(self):
y = np.tanh(self.data)
out = Tensor(y, (self,))
out._backward = lambda: self._accumulate(out.grad*(1-y*y))
return out
def sigmoid(self):
x = self.data
y = np.exp(-np.logaddexp(0, -x))
out = Tensor(y, (self,))
out._backward = lambda: self._accumulate(out.grad*y*(1-y))
return out
def relu(self):
mask = self.data > 0
out = Tensor(np.maximum(self.data, 0), (self,))
out._backward = lambda: self._accumulate(out.grad*mask)
return out
def exp(self):
y = np.exp(self.data)
out = Tensor(y, (self,))
out._backward = lambda: self._accumulate(out.grad*y)
return out
def log(self):
x = self.data.copy()
if np.any(x <= 0): raise ValueError('log exige entrada positiva')
out = Tensor(np.log(x), (self,))
out._backward = lambda: self._accumulate(out.grad/x)
return out
def _accumulate(self, value): self.grad += value
def sum(self, axis=None, keepdims=False):
shape = self.data.shape
axes = tuple(range(len(shape))) if axis is None else ((axis,) if isinstance(axis, int) else tuple(axis))
axes = tuple(a % len(shape) for a in axes) if shape else ()
out = Tensor(self.data.sum(axis=axis, keepdims=keepdims), (self,))
def backward():
g = out.grad
if not keepdims:
for a in sorted(axes): g = np.expand_dims(g, a)
self.grad += np.broadcast_to(g, shape)
out._backward = backward
return out
def mean(self, axis=None, keepdims=False):
axes = tuple(range(self.data.ndim)) if axis is None else ((axis,) if isinstance(axis, int) else tuple(axis))
count = int(np.prod([self.data.shape[a] for a in axes]))
return self.sum(axis, keepdims) * (1.0/count)
def max(self, axis=None, keepdims=False):
shape = self.data.shape
axes = tuple(range(len(shape))) if axis is None else ((axis,) if isinstance(axis, int) else tuple(axis))
axes = tuple(a % len(shape) for a in axes) if shape else ()
maxima = self.data.max(axis=axis, keepdims=True)
mask = self.data == maxima
counts = mask.sum(axis=axis, keepdims=True)
out = Tensor(self.data.max(axis=axis, keepdims=keepdims), (self,))
def backward():
g = out.grad
if not keepdims:
for a in sorted(axes): g = np.expand_dims(g, a)
self.grad += mask * (g/counts)
out._backward = backward
return out
def reshape(self, *shape):
original = self.data.shape
out = Tensor(self.data.reshape(*shape), (self,))
out._backward = lambda: self._accumulate(out.grad.reshape(original))
return out
def transpose(self, *axes):
perm = (tuple(axes[0]) if len(axes) == 1 and isinstance(axes[0], (tuple, list))
else tuple(axes) if axes else tuple(reversed(range(self.data.ndim))))
transposed = self.data.transpose(perm) # NumPy valida la permutación.
normalized = tuple(a % self.data.ndim for a in perm) if self.data.ndim else ()
inverse = np.argsort(normalized)
out = Tensor(transposed, (self,))
out._backward = lambda: self._accumulate(out.grad.transpose(inverse))
return out
def __getitem__(self, index):
# También pueden mutarse listas o estructuras anidadas de índices.
index = deepcopy(index)
out = Tensor(self.data[index], (self,))
def backward(): np.add.at(self.grad, index, out.grad)
out._backward = backward
return out
@staticmethod
def concat(tensors, axis=0):
tensors = tuple(tensors)
cuts = np.cumsum([t.data.shape[axis] for t in tensors])[:-1]
out = Tensor(np.concatenate([t.data for t in tensors], axis=axis), tensors)
def backward():
for tensor, g in zip(tensors, np.split(out.grad, cuts, axis=axis)):
tensor.grad += g
out._backward = backward
return out
def backward(self, seed=None):
if seed is None:
if self.data.size != 1: raise ValueError('salida no escalar: proporciona semilla')
seed = np.ones_like(self.data)
seed = np.asarray(seed, dtype=float)
if seed.shape != self.data.shape: raise ValueError('forma de semilla incorrecta')
topo, seen, stack = [], set(), [(self, False)]
while stack:
node, done = stack.pop()
if done: topo.append(node)
elif node not in seen:
seen.add(node)
stack.append((node, True))
stack.extend((p, False) for p in reversed(node.parents))
for node in topo:
if node.parents: node.grad.fill(0)
self.grad += seed
for node in reversed(topo): node._backward()
return len(topo)
def cross_entropy(logits, labels):
z = logits.data.copy()
labels = np.asarray(labels)
if (z.ndim != 2 or z.shape[0] == 0 or z.shape[1] == 0 or
labels.ndim != 1 or labels.shape[0] != z.shape[0] or
not np.issubdtype(labels.dtype, np.integer) or
np.any(labels < 0) or np.any(labels >= z.shape[1])):
raise ValueError('formas o etiquetas incorrectas')
shifted = z - np.max(z, axis=1, keepdims=True)
exp = np.exp(shifted)
probabilities = exp/exp.sum(axis=1, keepdims=True)
loss = np.mean(np.log(exp.sum(axis=1))-shifted[np.arange(len(labels)), labels])
delta = probabilities.copy()
delta[np.arange(len(labels)), labels] -= 1
delta /= len(labels)
out = Tensor(loss, (logits,))
out._backward = lambda: logits._accumulate(out.grad*delta)
return out"""Dropout invertido en Tensor y comparación reproducible en load_digits.
Se requieren la celda del motor tensorial y cross_entropy de m15-l09.
No utiliza el test oficial: aparta validación antes de tomar 160 ejemplos de
entrenamiento. Se elige el checkpoint por pérdida de validación.
"""
from sklearn.datasets import load_digits
from sklearn.model_selection import train_test_split
import numpy as np
def dropout_tensor(x, p, training, generator):
if not np.isfinite(p) or not 0 <= p < 1: raise ValueError('se exige 0 ≤ p < 1')
if not training or p == 0: return x
scale = (generator.random(x.data.shape) >= p).astype(float)/(1-p)
out = Tensor(x.data*scale, (x,))
out._backward = lambda: x._accumulate(out.grad*scale)
return out
# Un backward atraviesa exactamente la misma máscara que el forward.
check = Tensor(np.array([1.,2.,3.,4.]))
mask_rng = np.random.default_rng(1701)
out = dropout_tensor(check,.5,True,mask_rng)
out.sum().backward()
assert np.array_equal(check.grad,out.data/check.data)
assert dropout_tensor(check,.5,False,mask_rng) is check
try: dropout_tensor(check,1.,True,mask_rng)
except ValueError: pass
else: raise AssertionError('p=1 debe rechazarse')
print('Máscara del forward y backward, evaluación y p=1: verificados')
features, labels = load_digits(return_X_y=True)
features = features/16.
pool, valid_ids = train_test_split(np.arange(len(labels)),test_size=.2,stratify=labels,random_state=1702)
train_ids, _ = train_test_split(pool,train_size=160,stratify=labels[pool],random_state=1703)
train_x, train_y = features[train_ids], labels[train_ids]
valid_x, valid_y = features[valid_ids], labels[valid_ids]
assert not np.intersect1d(train_ids,valid_ids).size
class Network:
def __init__(self,p):
generator = np.random.default_rng(1704)
sizes = [64,64,64,10]
self.weights = [Tensor(generator.normal(0,np.sqrt(2/a),(a,b))) for a,b in zip(sizes[:-1],sizes[1:])]
self.biases = [Tensor(np.zeros(b)) for b in sizes[1:]]
self.params = self.weights+self.biases
self.p = p
self.masks = np.random.default_rng(1705)
def __call__(self,x,training):
h = Tensor(x)
for w,b in zip(self.weights[:-1],self.biases[:-1]):
h = dropout_tensor((h@w+b).relu(),self.p,training,self.masks)
return h@self.weights[-1]+self.biases[-1]
def evaluate(self,x,y):
logits = self(x,False).data
return (float(cross_entropy(Tensor(logits),y).data),float(np.mean(logits.argmax(axis=1)==y)))
def train(p,early=False,steps=120,check_every=10,patience=3,lr=.05):
model = Network(p)
generator = np.random.default_rng(1706)
history,best,checkpoint,best_step,bad = [],float('inf'),None,0,0
stopped_early = False
for step in range(steps+1):
if step % check_every == 0 or step == steps:
train_metrics = model.evaluate(train_x,train_y)
valid_metrics = model.evaluate(valid_x,valid_y)
history.append((step,*train_metrics,*valid_metrics))
if valid_metrics[0] < best:
best = valid_metrics[0];best_step = step;bad = 0
checkpoint = [parameter.data.copy() for parameter in model.params]
else:
bad += 1
if early and bad >= patience:
stopped_early = True
break
if step == steps: break
ids = generator.integers(0,len(train_y),size=32)
for parameter in model.params: parameter.grad.fill(0)
loss = cross_entropy(model(train_x[ids],True),train_y[ids])
if not np.isfinite(loss.data): raise RuntimeError('pérdida no finita')
loss.backward()
if any(not np.isfinite(parameter.grad).all() for parameter in model.params): raise RuntimeError('gradiente no finito')
for parameter in model.params: parameter.data -= lr*parameter.grad
final = model.evaluate(valid_x,valid_y)
for parameter,saved in zip(model.params,checkpoint): parameter.data[:] = saved
restored = model.evaluate(valid_x,valid_y)
assert abs(restored[0]-best) < 1e-12
return {'p':p,'early':early,'history':history,'final_step':step,'stopped_early':stopped_early,
'best_step':best_step,'final':final,'restored':restored}
for p in (0.,.2,.5,.8):
result = train(p)
print('dropout',p,'final validación',result['final'],'mejor paso',result['best_step'],
'mejor restaurado',result['restored'])
for p in (0.,.5):
result = train(p,early=True)
print('parada',p,'paso final',result['final_step'],'paciencia agotada',result['stopped_early'],
'mejor paso',result['best_step'],
'validación restaurada',result['restored'])"""Regresión 1D: ruido gaussiano integrado y penalización de jacobiano.
MLP tanh con ocho unidades; Adam NumPy idéntico, mismos datos e inicio.
No se fuerza igualdad de curvas: se reporta diferencia en rejilla fija.
"""
import json
from pathlib import Path
import numpy as np
X = np.linspace(-1., 1., 19)
Y = np.sin(2*X)
GRID = np.linspace(-1.25, 1.25, 101)
STEPS = 800
RATE = .02
NODES, WEIGHTS = np.polynomial.hermite.hermgauss(5)
WEIGHTS /= np.sqrt(np.pi)
def unpack(theta):
return theta[:8], theta[8:16], theta[16:24], theta[24]
def prediction(x, theta):
w, b, a, c = unpack(theta)
return np.tanh(x[...,None]*w+b) @ a+c
def objective_gradient(theta, mode, sigma):
w, b, a, c = unpack(theta)
if mode == 'ruido':
inputs = X[:,None] + np.sqrt(2)*sigma*NODES[None,:]
weights = np.broadcast_to(WEIGHTS[None,:]/len(X),inputs.shape)
targets = np.broadcast_to(Y[:,None], inputs.shape)
else:
inputs, weights, targets = X, np.ones_like(X)/len(X), Y
h = np.tanh(inputs[...,None]*w+b)
deriv = 1-h*h
residual = h@a+c-targets
objective = .5*np.sum(weights*residual*residual)
multiplier = (weights*residual)[...,None]
dw = np.sum(multiplier*a*deriv*inputs[...,None],axis=tuple(range(inputs.ndim)))
db = np.sum(multiplier*a*deriv,axis=tuple(range(inputs.ndim)))
da = np.sum(multiplier*h,axis=tuple(range(inputs.ndim)))
dc = np.sum(weights*residual)
gradient = np.r_[dw,db,da,dc]
if mode == 'jacobiano':
fprime = (a*w*deriv).sum(axis=-1)
objective += .5*sigma*sigma*np.mean(fprime*fprime)
common = sigma*sigma/len(X)*fprime[:,None]
dh = -2*h*deriv
gradient[:8] += np.sum(common*a*(deriv+w*dh*X[:,None]),axis=0)
gradient[8:16] += np.sum(common*a*w*dh,axis=0)
gradient[16:24] += np.sum(common*w*deriv,axis=0)
return float(objective), gradient
def train(mode,sigma):
initial = np.random.default_rng(1703)
theta = np.r_[initial.normal(0,.7,8),initial.normal(0,.3,8),initial.normal(0,.3,8),0.]
m,v = np.zeros_like(theta),np.zeros_like(theta)
for step in range(1,STEPS+1):
loss, gradient = objective_gradient(theta,mode,sigma)
if not np.isfinite(loss) or not np.isfinite(gradient).all(): raise RuntimeError('no finito')
m = .9*m+.1*gradient
v = .999*v+.001*gradient*gradient
theta -= RATE*(m/(1-.9**step))/(np.sqrt(v/(1-.999**step))+1e-8)
return prediction(GRID,theta), objective_gradient(theta,mode,sigma)[0]
# Gradcheck de ambas funciones objetivo, incluido el gradiente de f'.
initial = np.random.default_rng(1704).normal(0,.3,25)
for mode in ('ruido','jacobiano'):
_, grad = objective_gradient(initial,mode,.3)
numerical = np.empty_like(initial)
for j in range(len(initial)):
d = np.zeros_like(initial);d[j]=1e-6
numerical[j] = (objective_gradient(initial+d,mode,.3)[0]-objective_gradient(initial-d,mode,.3)[0])/2e-6
error = float(np.max(np.abs(grad-numerical)))
assert error < 1e-8
print('gradcheck',mode,'error máximo',error)
base, base_loss = train('jacobiano',0.)
rows = []
for sigma in (.05,.2,.5):
noisy, noisy_loss = train('ruido',sigma)
penalized, penalty_loss = train('jacobiano',sigma)
difference = float(np.sqrt(np.mean((noisy-penalized)**2)))
rows.append({'sigma':sigma,'noise_curve':noisy.tolist(),'penalty_curve':penalized.tolist(),
'noise_loss':noisy_loss,'penalty_loss':penalty_loss,'grid_difference_rms':difference})
print('sigma',sigma,'diferencia RMS entre curvas',difference,
'objetivos finales ruido y penalización',noisy_loss,penalty_loss)
output = {'train_x':X.tolist(),'train_y':Y.tolist(),'grid':GRID.tolist(),'base_curve':base.tolist(),
'base_loss':base_loss,'steps':STEPS,'lr':RATE,'seed':1703,'hidden':8,
'gauss_hermite_points':5,'records':rows}
destination = Path(__file__).with_suffix('.json') if '__file__' in globals() else Path('noise-regression.json')
destination.write_text(json.dumps(output,ensure_ascii=False,indent=2),encoding='utf-8')Local lab: regularizer ablation
The next cell uses Fashion-MNIST with disjoint splits, evaluates several dropout rates, and compares weight decay, label smoothing, noise, and early stopping in paired fashion. Within each seed it shares initial weights and batch sequence; masks and noise have separate generators. To compare with the full budget, if patience expires it keeps the best checkpoint at that point and continues the run, then restores the checkpoint to measure it. Otherwise it compares the best observed checkpoint with the final one without calling budget exhaustion early stopping. The full run uses 5000 training examples and three seeds. ORYON_VERIFY_SHORT=1 reduces data and steps to verify the flow; official test data are not consulted. It saves curves, per-seed differences, and an exploratory 95% t interval: three seeds and one fixed split cannot establish universal results.
"""Ablación reproducible de regularización en Fashion-MNIST.
ORYON_VERIFY_SHORT=1 reduce datos, anchura y pasos para verificar todo el flujo.
Se usa solo la partición oficial train, dividida en train/validación. Test no se
descarga ni consulta. ORYON_DROPOUT_OUTPUT elige la ruta del JSON y las figuras.
Los resultados de la verificación corta no sustituyen un estudio completo.
"""
import json
import math
import os
from pathlib import Path
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
import numpy as np
import torch
from scipy.stats import t
from torch import nn
from torchvision.datasets import FashionMNIST
torch.set_num_threads(1)
short = os.environ.get('ORYON_VERIFY_SHORT') == '1'
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
train_size, validation_size = (1024,512) if short else (5000,1000)
width = 64 if short else 256
steps, batch_size, every = (120,64,20) if short else (1200,64,50)
seeds = (17,31,43)
patience = 3
learning_rate = .001
configs = [
{'name':'base', 'p':0., 'weight_decay':0., 'smoothing':0., 'noise':0., 'position':'after'},
{'name':'dropout-0.2', 'p':.2, 'weight_decay':0., 'smoothing':0., 'noise':0., 'position':'after'},
{'name':'dropout-0.5', 'p':.5, 'weight_decay':0., 'smoothing':0., 'noise':0., 'position':'after'},
{'name':'dropout-0.8', 'p':.8, 'weight_decay':0., 'smoothing':0., 'noise':0., 'position':'after'},
{'name':'decay', 'p':0., 'weight_decay':.01, 'smoothing':0., 'noise':0., 'position':'after'},
{'name':'smoothing', 'p':0., 'weight_decay':0., 'smoothing':.1, 'noise':0., 'position':'after'},
{'name':'ruido', 'p':0., 'weight_decay':0., 'smoothing':0., 'noise':.1, 'position':'after'},
{'name':'combinado', 'p':.5, 'weight_decay':.01, 'smoothing':.1, 'noise':.1, 'position':'after'},
{'name':'dropout-antes-bn', 'p':.5, 'weight_decay':0., 'smoothing':0., 'noise':0., 'position':'before'},
]
FashionMNIST.mirrors = ['https://raw.githubusercontent.com/zalandoresearch/fashion-mnist/master/data/fashion/']
dataset = FashionMNIST(Path.home()/'.cache'/'atlas-data',train=True,download=True)
split = torch.randperm(len(dataset),generator=torch.Generator().manual_seed(17170))
train_ids, validation_ids = split[:train_size], split[train_size:train_size+validation_size]
assert not set(train_ids.tolist()).intersection(validation_ids.tolist())
train_x = (dataset.data[train_ids].reshape(train_size,-1).float()/255).to(device)
train_y = dataset.targets[train_ids].to(device)
valid_x = (dataset.data[validation_ids].reshape(validation_size,-1).float()/255).to(device)
valid_y = dataset.targets[validation_ids].to(device)
class Network(nn.Module):
def __init__(self,seed,p,position):
super().__init__()
torch.manual_seed(seed)
self.first = nn.Linear(784,width)
self.second = nn.Linear(width,width,bias=False)
self.norm = nn.BatchNorm1d(width)
self.dropout = nn.Dropout(p)
self.output = nn.Linear(width,10)
self.position = position
nn.init.kaiming_normal_(self.first.weight,nonlinearity='relu')
nn.init.kaiming_normal_(self.second.weight,nonlinearity='relu')
nn.init.xavier_normal_(self.output.weight)
nn.init.zeros_(self.first.bias);nn.init.zeros_(self.output.bias)
def pre_bn_clean(self,x):
return self.second(torch.relu(self.first(x)))
def forward(self,x):
z = self.pre_bn_clean(x)
if self.position == 'before': z = self.dropout(z)
z = torch.relu(self.norm(z))
if self.position == 'after': z = self.dropout(z)
return self.output(z)
def param_groups(model,decay):
matrices = [model.first.weight,model.second.weight,model.output.weight]
ids = {id(p) for p in matrices}
others = [p for p in model.parameters() if id(p) not in ids]
assert len(matrices)+len(others) == len(list(model.parameters()))
return [{'params':matrices,'weight_decay':decay},{'params':others,'weight_decay':0.}]
@torch.no_grad()
def evaluate(model,x,y):
model.eval()
loss,correct = 0.,0
for xb,yb in zip(x.split(256),y.split(256)):
logits = model(xb)
if not bool(torch.isfinite(logits).all()): return None
loss += float(nn.functional.cross_entropy(logits,yb,reduction='sum'))
correct += int((logits.argmax(dim=1)==yb).sum())
result = {'loss':loss/len(y),'accuracy':correct/len(y)}
return result if all(math.isfinite(v) for v in result.values()) else None
@torch.no_grad()
def bn_diagnostic(model,p,seed):
model.eval()
clean = model.pre_bn_clean(valid_x)
generator = torch.Generator(device=device).manual_seed(seed+17000)
mask = (torch.rand(clean.shape,device=device,generator=generator) >= p).to(clean.dtype)
dropped = clean*mask/(1-p)
clean_var = float(clean.var(dim=0,unbiased=True).mean())
dropped_var = float(dropped.var(dim=0,unbiased=True).mean())
running_var = float(model.norm.running_var.mean())
normalized_var = float(model.norm(clean).var(dim=0,unbiased=True).mean())
# En posición posterior, dropped_var es un control hipotético sobre la
# entrada previa a BN; la máscara real se aplica después de normalizar.
return {'clean_var':clean_var,'dropout_var':dropped_var,'running_var':running_var,
'eval_bn_output_var':normalized_var,'p':p}
def train(seed,config,indices):
model = Network(seed,config['p'],config['position']).to(device)
optimizer = torch.optim.AdamW(param_groups(model,config['weight_decay']),lr=learning_rate)
torch.manual_seed(seed+10000)
if device.type == 'cuda': torch.cuda.manual_seed_all(seed+10000)
noise_rng = torch.Generator(device=device).manual_seed(seed+12000)
curves = []
best_loss = float('inf'); best = None; best_step = 0; bad_checks = 0
stopped_step = None; early_state = None; early_best_step = None; status = 'complete'; completed_steps = 0
for step in range(steps+1):
if step % every == 0 or step == steps:
train_eval = evaluate(model,train_x,train_y)
valid_eval = evaluate(model,valid_x,valid_y)
if train_eval is None or valid_eval is None:
status = 'nonfinite_diagnostic'; break
curves.append({'step':step,'train':train_eval,'validation':valid_eval})
# Después de parar seguimos entrenando para comparar contra presupuesto fijo,
# pero la decisión y el checkpoint de parada quedan congelados.
if stopped_step is None:
if valid_eval['loss'] < best_loss:
best_loss = valid_eval['loss']; best_step = step; bad_checks = 0
best = {k:v.detach().cpu().clone() for k,v in model.state_dict().items()}
else:
bad_checks += 1
if bad_checks >= patience:
stopped_step = step; early_best_step = best_step; early_state = best
if step == steps: break
model.train()
ids = indices[step].to(device)
inputs = train_x[ids]
if config['noise']:
inputs = inputs + config['noise']*torch.randn(inputs.shape,device=device,generator=noise_rng)
optimizer.zero_grad(set_to_none=True)
loss = nn.functional.cross_entropy(model(inputs),train_y[ids],label_smoothing=config['smoothing'])
if not bool(torch.isfinite(loss)):
status = 'nonfinite_loss'; break
loss.backward()
if not all(p.grad is None or bool(torch.isfinite(p.grad).all()) for p in model.parameters()):
status = 'nonfinite_gradient'; break
optimizer.step()
completed_steps = step+1
final = evaluate(model,valid_x,valid_y) if status == 'complete' else None
diagnostic = bn_diagnostic(model,config['p'],seed) if final is not None else None
if early_state is None and best is not None:
early_state, early_best_step = best, best_step
if early_state is not None:
model.load_state_dict(early_state)
restored = evaluate(model,valid_x,valid_y)
expected = next(item['validation'] for item in curves if item['step']==early_best_step)
assert restored is not None and abs(restored['loss']-expected['loss'])<1e-6
else: restored = None
return {'seed':seed,'config':config,'status':status,'history':curves,'final':final,
'early':{'patience_checks':patience,'stopped_early':stopped_step is not None,
'stopped_step':stopped_step,'final_step':completed_steps,
'best_step':early_best_step,'restored':restored},
'batchnorm_diagnostic':diagnostic}
records = []
for seed in seeds:
indexes = torch.randint(train_size,(steps,batch_size),generator=torch.Generator().manual_seed(seed+1700))
for config in configs:
record = train(seed,config,indexes)
records.append(record)
print('semilla',seed,'configuración',config['name'],'estado',record['status'],
'validación final',record['final'],'mejor restaurado',record['early']['restored'],flush=True)
if device.type == 'cuda': torch.cuda.empty_cache()
def summarize_pairs(pairs):
if not pairs:
return {'pairs':[], 'mean':None, 'min':None, 'max':None, 'ci95_t':None}
mean = float(np.mean(pairs))
if len(pairs) >= 2 and np.std(pairs,ddof=1) > 0:
half = float(t.ppf(.975,len(pairs)-1)*np.std(pairs,ddof=1)/np.sqrt(len(pairs)))
interval = [mean-half,mean+half]
else:
interval = None
return {'pairs':pairs,'mean':mean,'min':float(min(pairs)),'max':float(max(pairs)),'ci95_t':interval}
def paired_differences(name, metric='accuracy'):
pairs = []
for seed in seeds:
baseline = next(r for r in records if r['seed']==seed and r['config']['name']=='base')['final']
trial = next(r for r in records if r['seed']==seed and r['config']['name']==name)['final']
if baseline is not None and trial is not None: pairs.append(trial[metric]-baseline[metric])
return summarize_pairs(pairs)
differences = {config['name']:paired_differences(config['name']) for config in configs if config['name'] != 'base'}
early_pairs = []
for seed in seeds:
baseline = next(r for r in records if r['seed']==seed and r['config']['name']=='base')
if baseline['final'] is not None and baseline['early']['restored'] is not None:
early_pairs.append(baseline['early']['restored']['accuracy']-baseline['final']['accuracy'])
differences['restaurar-mejor'] = summarize_pairs(early_pairs)
dropout_names = ('base','dropout-0.2','dropout-0.5','dropout-0.8')
selection = []
for name in dropout_names:
trials = [r for r in records if r['config']['name']==name and r['final'] is not None]
if len(trials) == len(seeds):
selection.append((float(np.mean([r['final']['loss'] for r in trials])),trials[0]['config']['p']))
best_dropout = min(selection) if selection else None
output = {'dataset':'Fashion-MNIST, partición oficial train','source':'https://github.com/zalandoresearch/fashion-mnist',
'mode':'short' if short else 'reader','device':str(device),'torch':torch.__version__,
'split_seed':17170,'train_size':train_size,'validation_size':validation_size,
'steps':steps,'batch_size':batch_size,'every':every,'width':width,'learning_rate':learning_rate,
'seeds':list(seeds),'protocol':'mismos pesos iniciales e índices por semilla; evaluación con dropout apagado; '
'ruido y máscaras tienen generadores separados; se muestrea con reemplazo; test no consultado',
'records':records,'paired_accuracy_differences':differences,
'batchnorm_diagnostic':'varianza media de canales en validación: entrada limpia, '
'entrada con máscara de diagnóstico, buffer móvil y salida en eval. '
'La entrada con máscara es hipotética si dropout va después de BN.',
'restaurar_mejor':'diferencia entre restaurar el mejor checkpoint y el final del presupuesto; '
'la paciencia puede no llegar a agotarse',
'paired_intervals':'IC t de Student al 95 % sobre diferencias entre semillas; n pequeño, partición fija; '
'no se estima si la dispersión muestral es cero',
'selected_dropout':{'criterion':'menor pérdida media final en validación, desempate por p menor',
'mean_validation_loss':best_dropout[0], 'p':best_dropout[1]} if best_dropout else None}
target = Path(os.environ.get('ORYON_DROPOUT_OUTPUT','fashion-dropout.json'))
target.parent.mkdir(parents=True,exist_ok=True)
target.write_text(json.dumps(output,ensure_ascii=False,indent=2,allow_nan=False),encoding='utf-8')
fig,axes = plt.subplots(1,2,figsize=(10,4),constrained_layout=True)
for name in ('base','dropout-0.2','dropout-0.5','dropout-0.8'):
row = next(r for r in records if r['seed']==seeds[0] and r['config']['name']==name)
for ax,split_name in zip(axes,('train','validation')):
ax.plot([p['step'] for p in row['history']],[p[split_name]['loss'] for p in row['history']],label=name)
ax.set_title(split_name+' en eval');ax.set_xlabel('Actualizaciones');ax.set_ylabel('Entropía cruzada')
ax.legend(fontsize=7)
fig.savefig(target.with_name(target.stem+'-curves.png'),dpi=130);plt.close(fig)
fig,ax = plt.subplots(figsize=(9,4),constrained_layout=True)
names = list(differences)
for i,name in enumerate(names):
for value in differences[name]['pairs']: ax.scatter(i,value,color='tab:blue',s=24)
result = differences[name]
if result['ci95_t'] is not None:
ax.errorbar(i,result['mean'],yerr=[[result['mean']-result['ci95_t'][0]],
[result['ci95_t'][1]-result['mean']]],
color='tab:orange',marker='_',capsize=3)
ax.axhline(0,color='black',linewidth=.8);ax.set_xticks(range(len(names)),names,rotation=35,ha='right')
ax.set_ylabel('Diferencia de precisión vs base');ax.set_title('Diferencias por semilla e IC t del 95 % (n pequeño)')
fig.savefig(target.with_name(target.stem+'-ablation.png'),dpi=130);plt.close(fig)
fig,axes = plt.subplots(1,2,figsize=(9,4),sharey=True,constrained_layout=True)
diagnostic_fields = ('clean_var','dropout_var','running_var','eval_bn_output_var')
for ax,name in zip(axes,('dropout-antes-bn','dropout-0.5')):
diagnostic_labels = ('Entrada limpia',
'Entrada con máscara' if name=='dropout-antes-bn' else 'Máscara hipotética antes de BN',
'Buffer móvil BN','Salida BN en eval')
selected = [r for r in records if r['config']['name']==name and r['batchnorm_diagnostic'] is not None]
for index,field in enumerate(diagnostic_fields):
vals = [r['batchnorm_diagnostic'][field] for r in selected]
if vals:
ax.bar(index,float(np.mean(vals)),color='tab:blue',alpha=.35)
ax.scatter([index]*len(vals),vals,color='tab:blue',s=20)
ax.set_xticks(range(len(diagnostic_fields)),diagnostic_labels,rotation=32,ha='right')
ax.set_title('Dropout '+('antes' if name=='dropout-antes-bn' else 'después')+' de BN')
ax.set_ylabel('Varianza media por canal')
fig.savefig(target.with_name(target.stem+'-bn-variance.png'),dpi=130);plt.close(fig)
for name in names:
result = differences[name]
print('Ablación',name,'diferencias',result['pairs'],'media',result['mean'],'IC t 95 %',result['ci95_t'],flush=True)
print('Dropout seleccionado por validación:',output['selected_dropout'],flush=True)
print('JSON y figuras guardados en',target,flush=True)
del train_x,train_y,valid_x,valid_y
if device.type == 'cuda': torch.cuda.empty_cache()npm run lab and open the connection link.Combining regularizers can improve or worsen results depending on budget and interactions. Data augmentation adds another ablation dimension: retain the same validation protocol and compare one intervention at a time before attributing an improvement.
Exercises
Step 1 of 3. What is the mean of each modified feature?
import numpy as np
def dropout_forward(x,p,training,seed):
pass
def dropout_backward(g,cache):
passStep 1 of 2. Which order-σ² term appears in the expectation?