Initialization: breaking symmetry and preserving variance
Derive forward and backward moment propagation and the Xavier, He, LeCun and orthogonal initializations. Examine symmetry breaking, dynamical isometry and practical output-layer choices.
After this lesson you can
- Explain and demonstrate when symmetric initialization prevents neurons from differentiating.
- Derive preactivation moment propagation and Xavier and He scaling conditions.
- Implement Xavier, He, LeCun and orthogonal initialization and examine 50-layer signal propagation.
- Choose output-layer and bias initialization with the expected initial loss in mind.
- Explain norm preservation in orthogonal linear networks and limitations in nonlinear networks.
Before you start
Before the first step
Two networks with identical architecture and data can start in very different regimes. If signals attenuate, early layers receive weak corrections; if they grow too much, activations can saturate or loss become non-finite. The previous lesson showed the product of Jacobians. Now we choose an initial distribution that makes the first forward and backward paths reasonable, without confusing an average result with a guarantee for each network.
This figure computes a finite realization: square matrices, one fixed batch, and one seed. Xavier and LeCun coincide here because input and output widths match. A scale preserving a moment in expectation under an idealized model need not keep this particular trajectory flat; spread can accumulate and an activation can introduce a nonzero mean.
Breaking symmetry
Symmetry breaking allows neurons in the same layer to receive different corrections. Consider two units and an output . If , , and , both activations coincide for every input. By the chain rule their incoming gradients are equal, as are gradients of outgoing connections. With deterministic SGD, identical initial momentum states, and identical treatment, equality is preserved by induction after each step.
Equal incoming weights alone are insufficient: if , the backpropagation factor can differ from the first step. Different optimizer states or independent dropout masks can also break symmetry. Adding noise distinguishes units but does not guarantee specialization or growing distance for every task.
What is preserved in the forward pass
For a layer with inputs, . Assume zero biases, zero-mean weights independent of one another and of their input activations, with common variance . If activations have the same second moment , cross terms vanish when averaging over weights and
This moment propagation equation does not require zero-mean activations because it uses , not . Independence concerns the new matrix and its incoming signal; after training, weights and signals may be correlated. This is also an average over initializations and data under these assumptions, not a promise for a fixed matrix.
If has a symmetric distribution and finite second moment, . Thus, under the homogeneous-layer approximation, choosing preserves preactivation second moment from layer to layer. This is the He condition for ReLU; the corresponding normal standard deviation is . If is centered Gaussian with variance , output has mean and variance , not . One half corresponds to the second moment.
With an approximately linear activation and centered inputs, , and preserves forward scale. This is LeCun’s rule in this idealized case. Tanh is approximately linear only near zero; sigmoid has nonzero mean and saturation, so neither formula ensures exact stability at every scale.
The backward direction and Xavier
Backpropagation introduces and one derivative per unit. Under a mean-field approximation treating weights, error signal, and activation gates as sufficiently independent, gradient variance is multiplied approximately by . Independence is not exact in a general network: the gate depends on its preactivations and error comes from the same network.
For an almost linear activation, preserving forward scale suggests and preserving backward scale suggests . If sizes differ, both equalities cannot hold with the same variance. Xavier or Glorot takes the compromise
because a symmetric uniform distribution with limit has variance . It matches both linear conditions when sizes are equal. For square ReLU layers, Xavier has variance and the idealized model halves the second moment per layer; this does not imply every realization or gradient falls by exactly that factor. Glorot and Bengio analyze propagation and propose the compromise; He and colleagues derive the scale adapted to rectifiers.
Orthogonality and isometry
A square matrix with exactly preserves and also preserves norm during backpropagation. A product of square orthogonal matrices remains orthogonal. A rectangular matrix with orthonormal columns preserves norms of all input vectors under the column convention; if it has only orthonormal rows, it can discard null-space components. With gain , preserved norms are multiplied by .
Orthogonal initialization uses QR of a Gaussian matrix and sign correction on the diagonal of ; the cell and exercise cover both rectangular shapes. In a nonlinear network each Jacobian includes activation derivatives: orthogonality of does not imply the complete product is an isometry. Pennington and colleagues study that spectrum in specific regimes; for ReLU, even with critical orthogonal weights, they find the spectrum widens with depth. The previous lesson’s figure lets you inspect the product, not merely each isolated matrix.
Preparing the output layer
Output initialization controls logits before learning. If the logits are equal for each example, softmax assigns and cross-entropy is : with ten classes, . A common constant across logits does not change softmax; scaling one class bias can. If labels have positive prior and a constant prediction equal to that prior is desired, use . Expected loss under that prior is , equal to only for equiprobable classes.
Setting the output matrix exactly to zero gives equal logits if biases are also equal, but the gradient toward earlier layers is zero on that first step. A small nonzero output allows signal to reach them from the start. The decision depends on task and prior: high initial loss can suggest excessive logits but does not by itself prove initialization is wrong.
Practice and diagnosis
In torch.nn.init, kaiming_normal_ accepts mode='fan_in' or mode='fan_out'; check the matrix shape convention and the activation actually applied. Default nn.Linear uses kaiming_uniform_ with , equivalent to for its weights. Its variance is : not the He variance for ReLU. For input width 512, the corresponding standard deviation is approximately 0.02552 versus 0.0625 for He normal.
LSUV starts with orthogonal weights and adjusts layer by layer using minibatch statistics. Mishkin and Matas report that adjustment required one to five iterations in their experiments and study tolerances between 0.01 and 0.1. This is data-dependent initial calibration, not equivalent to keeping batch normalization active during training. Normalization can relieve scale problems but does not guarantee good training with every initialization.
Lab from scratch: fifty layers
Build Xavier, He, LeCun, and orthogonal initializations with NumPy and propagate a batch through 50 layers. The convention is of shape (fan_in, fan_out) and row vectors. The terminal backpropagation direction is fixed and does not come from a loss: we measure the Jacobian response, not classifier quality. Each combination uses the same initial seed, and results are sample moments from one realization.
"""Inicializadores y medición en una red de 50 capas, compatible con Pyodide.
Convención de forma: (fan_in, fan_out), vectores fila y z = h @ W.
Los momentos son muestrales, no garantías para toda realización finita.
"""
import numpy as np
def orthogonal_init(shape, gain, generator):
fan_in, fan_out = shape
if fan_in < 1 or fan_out < 1 or not np.isfinite(gain):
raise ValueError('forma o ganancia inválida')
matrix = generator.normal(size=(max(fan_in, fan_out), min(fan_in, fan_out)))
q, r = np.linalg.qr(matrix, mode='reduced')
q *= np.where(np.diag(r) < 0, -1., 1.)
return gain * (q if fan_in >= fan_out else q.T)
def initialize(shape, kind, generator):
fan_in, fan_out = shape
if min(shape) < 1: raise ValueError('forma vacía')
if kind == 'xavier': std = np.sqrt(2. / (fan_in + fan_out))
elif kind == 'he': std = np.sqrt(2. / fan_in)
elif kind == 'lecun': std = np.sqrt(1. / fan_in)
elif kind == 'ortogonal': return orthogonal_init(shape, 1., generator)
else: raise ValueError('inicializador desconocido')
return generator.normal(0., std, size=shape)
def activate(z, kind):
if kind == 'lineal': return z, np.ones_like(z)
if kind == 'tanh':
a = np.tanh(z)
return a, 1.-a*a
if kind == 'relu': return np.maximum(0., z), (z > 0).astype(float)
if kind == 'sigmoide':
a = np.exp(-np.logaddexp(0., -z))
return a, a*(1.-a)
raise ValueError('activación desconocida')
def experiment(activation, initializer, width=16, batch=32, depth=50):
generator = np.random.default_rng(1401)
data_rng = np.random.default_rng(1402)
h = data_rng.normal(size=(batch, width))
# Misma dirección terminal para todas las combinaciones, no un gradiente de pérdida.
terminal = data_rng.normal(size=(batch, width))
terminal /= np.sqrt(np.mean(terminal*terminal))
layers, moments = [], []
for layer in range(1, depth+1):
w = initialize((width, width), initializer, generator)
z = h @ w
h, derivative = activate(z, activation)
layers.append((w, derivative))
moments.append({'layer': layer, 'z_mean': float(z.mean()),
'z_second_moment': float(np.mean(z*z)),
'activation_mean': float(h.mean()), 'activation_std': float(h.std())})
gradient = terminal
gradient_rms = [0.]*(depth+1)
gradient_rms[-1] = float(np.sqrt(np.mean(gradient*gradient)))
for i in range(depth-1, -1, -1):
w, derivative = layers[i]
gradient = (gradient*derivative) @ w.T
gradient_rms[i] = float(np.sqrt(np.mean(gradient*gradient)))
assert np.isfinite(gradient).all() and all(np.isfinite(x) for x in gradient_rms)
return moments, gradient_rms
# Comprobaciones independientes sobre formas rectangulares y escala esperada.
test_rng = np.random.default_rng(1403)
for shape in ((7, 3), (3, 7), (4, 4)):
q = orthogonal_init(shape, 1.5, test_rng)
gram = q.T @ q if shape[0] >= shape[1] else q @ q.T
assert np.max(np.abs(gram-2.25*np.eye(min(shape)))) < 1e-12
big = initialize((512, 256), 'he', np.random.default_rng(1404))
expected = np.sqrt(2/512)
assert abs(big.std()/expected-1) < .02
print('He esperado y medido:', expected, float(big.std()))
print('ln 10:', np.log(10), 'desviación predeterminada Linear fan_in=512:', 1/np.sqrt(3*512))
print('QR rectangular: columnas o filas ortogonales, gain 1,5: comprobado')
# VJP independiente en una red tanh pequeña mediante diferencias centrales.
check_rng = np.random.default_rng(1405)
check_weights = [initialize((4, 4), 'xavier', check_rng) for _ in range(3)]
check_x, check_terminal = check_rng.normal(size=(1,4)), check_rng.normal(size=(1,4))
def evaluate_tanh(x):
for w in check_weights: x = np.tanh(x @ w)
return x
saved = []
h = check_x.copy()
for w in check_weights:
h = np.tanh(h @ w); saved.append(h)
gradient = check_terminal.copy()
for w, a in zip(reversed(check_weights), reversed(saved)):
gradient = (gradient*(1-a*a)) @ w.T
epsilon = 1e-6
direction = check_rng.normal(size=(1,4))
numerical = np.sum(check_terminal * (evaluate_tanh(check_x+epsilon*direction)-
evaluate_tanh(check_x-epsilon*direction))) / (2*epsilon)
error = abs(float(np.sum(gradient*direction))-float(numerical))
assert error < 1e-8
print('Error VJP frente a diferencia finita:', error)
results = {}
for activation in ('lineal', 'tanh', 'relu', 'sigmoide'):
for scheme in ('xavier', 'he', 'lecun', 'ortogonal'):
moments, backward = experiment(activation, scheme)
results[(activation, scheme)] = (moments, backward)
first, last = moments[0], moments[-1]
print(activation, scheme, 'std activaciones capas 1 y 50',
f"{first['activation_std']:.4e}", f"{last['activation_std']:.4e}",
'RMS gradiente entrada', f'{backward[0]:.4e}')
# Ortogonal cuadrada + lineal: preserva exactamente la norma matricial hacia atrás.
linear_backward = results[('lineal', 'ortogonal')][1]
assert max(abs(x-1.) for x in linear_backward) < 1e-12
print('Error máximo de RMS hacia atrás, lineal ortogonal:',
max(abs(x-1.) for x in linear_backward))The cell shows that a square orthogonal matrix and linear activation preserve backward norm up to numerical error. For ReLU with He in a narrow network, observed statistics can deviate greatly from the theoretical average. Compare histograms and repeat with greater width or more seeds before concluding a formula failed.
Reproducing symmetry
This experiment calculates all trajectories in the figure and checks their gradients with finite differences. Each neuron receives the same five synthetic points and the optimizer has explicit momentum.
"""MLP 1→2→1 con tanh, pérdida MSE media y SGD con momentum explícito.
Todos los experimentos usan los mismos cinco puntos y la misma tasa. Se
comparan igualdad completa, perturbación de entrada, peso de salida desigual
y estado de momentum desigual. No usa aleatoriedad ni datos externos.
"""
import json
from pathlib import Path
import numpy as np
X = np.array([-1., -.5, 0., .5, 1.])
Y = X**2
ETA = .05
MOMENTUM = .8
STEPS = 200
def loss_gradient(p):
# p = [w1, w2, b1, b2, v1, v2, c]
w, b, v, c = p[:2], p[2:4], p[4:6], p[6]
h = np.tanh(X[:, None]*w + b)
prediction = h @ v + c
error = prediction-Y
loss = .5*np.mean(error**2)
d = error[:, None] * v * (1-h*h) / len(X)
grad = np.r_[np.sum(d*X[:, None], axis=0), np.sum(d, axis=0),
np.mean(error[:, None]*h, axis=0), np.mean(error)]
return float(loss), grad
def trajectory(case):
p = np.array([1., 1., .4, .4, .8, .8, 0.])
momentum = np.zeros(7)
if case == 'ruido_entrada': p[0] += .05
elif case == 'salidas_distintas': p[4] += .2
elif case == 'momento_distinto': momentum[0] = .2
elif case != 'simetrica': raise ValueError('caso desconocido')
rows = []
for step in range(STEPS+1):
loss, g = loss_gradient(p)
rows.append({'step':step, 'loss':loss, 'weights':p.tolist(),
'momentum':momentum.tolist(), 'gradient':g.tolist()})
if step < STEPS:
momentum = MOMENTUM*momentum + g
p = p - ETA*momentum
return rows
def validate():
p = np.array([.4, .45, .2, .17, .8, .5, .1])
eps = 1e-6
_, grad = loss_gradient(p)
basis = np.eye(len(p))
numerical = np.array([(loss_gradient(p+eps*e)[0]-loss_gradient(p-eps*e)[0])/(2*eps) for e in basis])
error = float(np.max(np.abs(numerical-grad)))
assert error < 1e-9
records = {name: trajectory(name) for name in ('simetrica', 'ruido_entrada', 'salidas_distintas', 'momento_distinto')}
for row in records['simetrica']:
for vals in (row['weights'], row['momentum'], row['gradient']):
assert vals[0] == vals[1] and vals[2] == vals[3] and vals[4] == vals[5]
for name in ('ruido_entrada', 'salidas_distintas', 'momento_distinto'):
assert abs(records[name][1]['weights'][0]-records[name][1]['weights'][1]) > 1e-8
return error, records
if __name__ == '__main__':
error, records = validate()
path = Path('symmetry-prototype.json')
path.write_text(json.dumps({'x':X.tolist(),'y':Y.tolist(),'eta':ETA,'momentum':MOMENTUM,
'finite_difference_max_error':error,'records':records},
ensure_ascii=False, indent=2), encoding='utf-8')
print('Error máximo por diferencias finitas:', error)
for name, rows in records.items():
print(name, 'diferencia inicial', abs(rows[0]['weights'][0]-rows[0]['weights'][1]),
'diferencia paso 1', abs(rows[1]['weights'][0]-rows[1]['weights'][1]),
'diferencia paso 200', abs(rows[-1]['weights'][0]-rows[-1]['weights'][1]),
'pérdida final', rows[-1]['loss'])Local lab: initialization and training
On Fashion-MNIST, a deep network compares He at half and double scale with default nn.Linear values. All conditions use the same splits and minibatch sequences per seed; validation loss and gradient norms are recorded. Official test data are reserved. Short mode checks implementation and normal mode provides the complete experiment to the reader.
In the short check, with two seeds and 120 steps, He at scale 1 ends with validation losses 0.8754 and 0.8694; scale 0.5 ends at 2.3014 and 2.3008. Scale 2 produces non-finite loss at steps 4 and 5. The default configuration ends at 2.3040 and 2.3027. Here the default also includes its initial biases and output is common to all conditions. These observations describe one architecture and budget; they do not prove one rule always wins.
"""Comparación reproducible de escalas de He en Fashion-MNIST.
Con ORYON_VERIFY_SHORT=1 ejecuta un ensayo reducido para verificar el flujo.
Sin esa variable, prepara el presupuesto destinado al lector; no se ejecuta aquí.
La validación se reserva para comparar configuraciones; no se consulta el test oficial.
"""
import json
import math
import os
from pathlib import Path
import torch
from torch import nn
from torchvision.datasets import FashionMNIST
torch.set_num_threads(1)
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
short = os.getenv('ORYON_VERIFY_SHORT') == '1'
train_size, valid_size = (4096, 1024) if short else (50000, 10000)
steps = 120 if short else 5000
batch_size = 64 if short else 128
width = 96 if short else 256
depth = 8
learning_rate = 0.01
scales = ('default', 0.5, 1.0, 2.0)
seeds = (11, 29) if short else (11, 29, 47)
eval_every = 10 if short else 100
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(14140))
train_ids = split[:train_size]
valid_ids = split[train_size:train_size + valid_size]
assert not set(train_ids.tolist()).intersection(valid_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[valid_ids].reshape(valid_size, -1).float() / 255).to(device)
valid_y = dataset.targets[valid_ids].to(device)
class Network(nn.Module):
def __init__(self, seed, scale):
super().__init__()
torch.manual_seed(seed)
self.hidden = nn.ModuleList()
size = 784
for _ in range(depth):
self.hidden.append(nn.Linear(size, width))
size = width
self.output = nn.Linear(width, 10)
defaults = [(layer.weight.detach().clone(), layer.bias.detach().clone()) for layer in self.hidden]
# Idénticos números de partida en las tres escalas: solo cambia el
# multiplicador de las matrices ocultas. Para default se ejecuta la
# misma secuencia aleatoria antes de restaurar los parámetros originales.
for layer in self.hidden:
nn.init.kaiming_normal_(layer.weight, mode='fan_in', nonlinearity='relu')
with torch.no_grad():
layer.weight.mul_(1.0 if scale == 'default' else scale)
layer.bias.zero_()
nn.init.xavier_normal_(self.output.weight)
nn.init.zeros_(self.output.bias)
if scale == 'default':
with torch.no_grad():
for layer, (weight, bias) in zip(self.hidden, defaults):
layer.weight.copy_(weight)
layer.bias.copy_(bias)
def forward(self, x):
for layer in self.hidden:
x = torch.relu(layer(x))
return self.output(x)
def check_initialization(seed):
reference = Network(seed, 1.0)
default = Network(seed, 'default')
for scale in (0.5, 2.0, 'default'):
candidate = Network(seed, scale)
assert torch.equal(candidate.output.weight, reference.output.weight)
assert torch.equal(candidate.output.bias, reference.output.bias)
if scale != 'default':
for target, base in zip(candidate.hidden, reference.hidden):
assert torch.equal(target.weight, base.weight * scale)
assert torch.count_nonzero(target.bias) == 0
# Reconstruye el orden original de las capas para contrastar los defaults.
torch.manual_seed(seed)
original = []
in_size = 784
for _ in range(depth):
original.append(nn.Linear(in_size, width))
in_size = width
nn.Linear(width, 10)
for restored, layer in zip(default.hidden, original):
assert torch.equal(restored.weight, layer.weight)
assert torch.equal(restored.bias, layer.bias)
@torch.no_grad()
def evaluate(model):
model.eval()
logits = model(valid_x)
if not torch.isfinite(logits).all():
return None
loss = nn.functional.cross_entropy(logits, valid_y)
if not torch.isfinite(loss):
return None
return {'loss': float(loss.item()), 'accuracy': float((logits.argmax(1) == valid_y).float().mean().item())}
records = []
for seed in seeds:
check_initialization(seed)
batch_rng = torch.Generator().manual_seed(seed + 900)
batches = torch.randint(train_size, (steps, batch_size), generator=batch_rng)
for scale in scales:
model = Network(seed, scale).to(device)
optimizer = torch.optim.SGD(model.parameters(), lr=learning_rate)
initial = evaluate(model)
points = [{'step': 0, **initial}] if initial else []
gradient_points = []
status = 'complete' if initial is not None else 'nonfinite_initial'
for step in range(1, steps + 1):
if status != 'complete':
break
model.train()
idx = batches[step - 1].to(device)
optimizer.zero_grad(set_to_none=True)
loss = nn.functional.cross_entropy(model(train_x[idx]), train_y[idx])
if not torch.isfinite(loss):
status = 'nonfinite_loss'
break
loss.backward()
gradients = [layer.weight.grad for layer in model.hidden]
if not all(p.grad is None or torch.isfinite(p.grad).all() for p in model.parameters()):
status = 'nonfinite_gradient'
break
first_grad = float(gradients[0].double().norm().item())
last_grad = float(gradients[-1].double().norm().item())
if not math.isfinite(first_grad) or not math.isfinite(last_grad):
status = 'nonfinite_gradient_norm'
break
gradient_points.append({'step': step, 'first': first_grad, 'last': last_grad})
optimizer.step()
if step == 1 or step % eval_every == 0 or step == steps:
validation = evaluate(model)
if validation is None:
status = 'nonfinite_validation'
break
points.append({'step': step, **validation,
'train_batch_loss_before_update': float(loss.item()),
'first_hidden_gradient_norm': first_grad,
'last_hidden_gradient_norm': last_grad})
records.append({'seed': seed, 'scale': scale, 'status': status,
'last_attempted_step': step if initial is not None else 0,
'points': points, 'gradient_points': gradient_points})
print(f'seed={seed} scale={scale} status={status} step={records[-1]["last_attempted_step"]} '
f'initial={initial} final={points[-1] if points else None}', flush=True)
del model, optimizer
if device.type == 'cuda':
torch.cuda.empty_cache()
output = {
'source': 'https://github.com/zalandoresearch/fashion-mnist',
'mode': 'short' if short else 'reader', 'device': str(device),
'torch': torch.__version__, 'split_seed': 14140,
'train_examples': train_size, 'validation_examples': valid_size,
'batch_size': batch_size, 'steps': steps, 'depth': depth, 'width': width,
'optimizer': 'SGD', 'learning_rate': learning_rate,
'scales': list(scales), 'seeds': list(seeds),
'split_policy': 'disjuntos de train oficial; test oficial sin consultar',
'batches': 'con reemplazo, semilla de lote = semilla de pesos + 900; secuencia común por escala',
'init': 'ocultas por defecto de nn.Linear o He normal multiplicada por escala; salida Xavier normal común y bias de salida cero',
'records': records,
}
target = Path(os.getenv('ORYON_INIT_OUTPUT', 'fashion-init.json'))
target.parent.mkdir(parents=True, exist_ok=True)
target.write_text(json.dumps(output, indent=2, ensure_ascii=False, allow_nan=False), encoding='utf-8')
print('Datos guardados en', target, flush=True)
del train_x, train_y, valid_x, valid_y
if device.type == 'cuda':
torch.cuda.empty_cache()
# Cada curva termina en su último valor finito; no se interpolan ni conectan
# ejecuciones distintas y no se representa log(0).
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
colors = {'default': 'tab:gray', 0.5: 'tab:blue', 1.0: 'tab:green', 2.0: 'tab:red'}
line_styles = {seed: style for seed, style in zip(seeds, ('-', '--', ':'))}
fig, axes = plt.subplots(1, 3, figsize=(16, 4.8), constrained_layout=True)
for record in records:
label = f"{record['scale']}, semilla {record['seed']}"
if record['status'] != 'complete':
label += f" (detenido en {record['last_attempted_step']})"
kwargs = {'color': colors[record['scale']], 'linestyle': line_styles[record['seed']], 'linewidth': 1.5, 'label': label}
validation = [(p['step'], p['loss']) for p in record['points'] if math.isfinite(p['loss']) and p['loss'] > 0]
if validation:
axes[0].plot([p[0] for p in validation], [p[1] for p in validation], marker='.', **kwargs)
if record['status'] != 'complete':
axes[0].plot(validation[-1][0], validation[-1][1], marker='x', color=colors[record['scale']], markersize=7)
for axis, name in zip(axes[1:], ('first', 'last')):
values = [(p['step'], p[name] if math.isfinite(p[name]) and p[name] > 0 else float('nan'))
for p in record['gradient_points']]
if any(math.isfinite(value) for _, value in values):
axis.plot([p[0] for p in values], [p[1] for p in values], **kwargs)
for ax, title in zip(axes, ('Pérdida de validación', 'Norma gradiente: primera capa', 'Norma gradiente: última capa oculta')):
ax.set_title(title)
ax.set_xlabel('Paso')
ax.set_yscale('log')
ax.grid(alpha=0.25)
axes[0].set_ylabel('Valor, escala logarítmica')
axes[0].legend(title='Inicialización y semilla', fontsize=7, loc='best')
fig.suptitle('Fashion-MNIST: inicialización y estabilidad (' + ('ensayo corto' if short else 'entrenamiento del lector') + '); gradientes antes del paso')
figure_path = target.with_suffix('.png')
fig.savefig(figure_path, dpi=140)
plt.close(fig)
print('Gráfica guardada en', figure_path, flush=True)npm run lab and open the connection link.Exercises
In the last question, the self-normalizing network of Klambauer and colleagues uses architectural and distributional assumptions. The PyTorch initialization documentation distinguishes the default SELU gain from the variance reproducing that fixed point.
Step 1 of 3. What is the second moment of h?
Step 1 of 3. How do the hidden activations compare?
import numpy as np
def orthogonal_init(shape, gain=1.0, rng=None):
pass