Layers, forward passes, and what nn.Linear does under the hood.
nn.Linear(in_features, out_features) computes the affine transform
y = x @ W.T + b internally, with W and b as learnable parameters. Every
model is a subclass of nn.Module that defines its layers in __init__ and
how data flows through them in forward.
importtorchimporttorch.nn as nn
classNet(nn.Module):
def__init__(self):
super().__init__()
self.fc1 = nn.Linear(4, 8)
self.relu = nn.ReLU()
self.fc2 = nn.Linear(8, 2)
defforward(self, x):
returnself.fc2(self.relu(self.fc1(x)))
model = Net()
x = torch.randn(3, 4) # batch of 3 samples, 4 features each
out = model(x) # calls forward() internallyprint(out.shape) # (3, 2)
importtorch
x = torch.tensor([[1.0, 2.0]])
W = torch.tensor([[0.5, -0.5], [1.0, 2.0]])
b = torch.tensor([0.1, 0.2])
print(x @ W.t() + b) # exactly what nn.Linear(2, 2) computes internally
Layer
Use
Example
nn.Linear(in, out)
fully-connected (dense) layer
nn.Linear(4, 2) maps a length-4 input to a length-2 output