Fully Connected Layers (Linear)
Capas completamente conectadas y transformaciones lineales
nn.Linear implementa la transformación y = xW^T + b, donde W es una matriz de pesos shape (out_features, in_features) y b es el bias shape (out_features). PyTorch inicializa W uniformemente por defecto. La entrada tiene shape (..., in_features) y la salida (..., out_features). Lineal es la capa más simple: sin no-linealidad. Para redes no triviales, encadena lineal → activación → dropout.
Los parámetros de una capa Linear son .weight y .bias, ambos entrenables por defecto. Accede con model.fc1.weight para una capa llamada self.fc1. Usa model.named_parameters() para iterar sobre pares (nombre, parámetro). Para debugging, imprime shapes: print(model.fc1.weight.shape) debe ser (out, in).
Para redes profundas, la inicialización importa. Xavier/Glorot initialization mantiene varianza entre capas: nn.init.xavier_uniform_(layer.weight). Kaiming/He es para ReLU: nn.init.kaiming_normal_(layer.weight, nonlinearity='relu'). Sin inicialización cuidadosa, activaciones explotan o desaparecen en capas profundas.
# Linear layer
fc = nn.Linear(in_features=256, out_features=128)
x = torch.randn(32, 256) # batch_size=32
y = fc(x) # shape (32, 128)
# Accessing parameters
print(fc.weight.shape) # (128, 256)
print(fc.bias.shape) # (128,)
# Weight initialization
import torch.nn.init as init
init.xavier_uniform_(fc.weight)
init.constant_(fc.bias, 0)
# Stacking linear layers
layers = nn.Sequential(
nn.Linear(256, 128),
nn.ReLU(),
nn.Linear(128, 64),
nn.ReLU(),
nn.Linear(64, 10)
)Debugging lab
Detecta y corrige el error en el código.
- 01
fc = nn.Linear(10, 5) print(fc.weight.shape) # What is the shape?
- 02
fc1 = nn.Linear(256, 128) fc2 = nn.Linear(128, 10) # Two linear layers without activation between # Is the composition still linear?