Regularización en DL
3.6.2kata 2 de 7

Batch Normalization Details

Normalización, running stats, training vs eval

Batch Normalization normaliza la entrada a una capa a media 0 y varianza 1 usando estadísticas del batch actual. Esto estabiliza el training y permite learning rates más altos. Mantiene parámetros aprendibles γ (scale) y β (shift) que permiten a la red aprender si quiere mantener o cambiar la distribución normalizada.

Durante training, BatchNorm calcula media y varianza del batch actual y normaliza. También mantiene running_mean y running_var (exponential moving average) de estadísticas entre batches. Durante eval, usa los running_mean y running_var acumulados para normalizar, no estadísticas del batch actual (que sería incorrecto).

Batch size pequeño (< 16) hace que estadísticas del batch sean ruidosas, causando BatchNorm inestable. LayerNorm normaliza por ejemplo (no por batch), evitando este problema. En transformers, LayerNorm es estándar.

structure.txt
import torch
import torch.nn as nn

# Batch Normalization in a network
class Net(nn.Module):
    def __init__(self):
        super().__init__()
        self.fc1 = nn.Linear(256, 128)
        self.bn1 = nn.BatchNorm1d(128)  # normaliza 128 features
        self.fc2 = nn.Linear(128, 10)
    def forward(self, x):
        x = self.fc1(x)  # shape (batch, 128)
        x = self.bn1(x)  # normalize to mean=0, var=1
        x = torch.relu(x)
        return self.fc2(x)

# Training: uses batch statistics
model.train()
for batch_x, batch_y in train_loader:
    logits = model(batch_x)  # BN uses batch mean/var

# Evaluation: uses running statistics
model.eval()
with torch.no_grad():
    for batch_x in test_loader:
        logits = model(batch_x)  # BN uses running_mean/running_var

Debugging lab

Detecta y corrige el error en el código.

0/2 tests passing0%
  1. 01

    # Batch norm after activation (WRONG) self.fc1 = nn.Linear(256, 128) self.bn = nn.BatchNorm1d(128) def forward(self, x): x = torch.relu(self.fc1(x)) x = self.bn(x) # batchnorm after relu

  2. 02

    # Very small batch size with BatchNorm train_loader = DataLoader(train_dataset, batch_size=4) # too small