Lesson 11.3 · 10 min read · about 1 h to master at a very slow pace
Neural Networks in PyTorch
Define a network, choose a loss and optimiser, and write the training loop. A 100 → 50 → 10 classifier line by line, the logits rule, train and eval modes, and a custom activation function.
Defining the network
A classifier with 100 input features, 50 ReLU hidden units and 10 classes:
import torch
import torch.nn as nn
class MLP(nn.Module):
def __init__(self):
super().__init__()
self.fc1 = nn.Linear(100, 50) # 100*50 + 50 = 5,050 parameters
self.fc2 = nn.Linear(50, 10) # 50*10 + 10 = 510 parameters
def forward(self, x):
return self.fc2(torch.relu(self.fc1(x))) # logits: no softmax here
The logits rule
nn.CrossEntropyLoss applies log-softmax itself, so the model must return raw logits. A question may ask for "an output layer with softmax": for training with CrossEntropyLoss, leave it out and say why, then apply torch.softmax(logits, dim=1) only when you need probabilities.
Training
model = MLP()
loss_fn = nn.CrossEntropyLoss()
optimizer = torch.optim.SGD(model.parameters(), lr=0.01) # or torch.optim.Adam
for epoch in range(num_epochs):
model.train() # training mode (dropout on)
for xb, yb in train_loader: # mini-batches
optimizer.zero_grad() # 1. clear old gradients
loss = loss_fn(model(xb), yb) # 2. forward pass and loss
loss.backward() # 3. backpropagation
optimizer.step() # 4. gradient descent update
model.eval() # evaluation mode (dropout off)
with torch.no_grad(): # no gradients needed
val_loss = sum(loss_fn(model(xb), yb).item() for xb, yb in val_loader)
zero_grad(): PyTorch adds gradients by default, so clear them each step.backward()is backpropagation;step()is the update. L2 weight decay:torch.optim.SGD(..., weight_decay=1e-4).- Record training and validation loss every epoch to watch for overfitting.
A custom activation function
Activations are just modules. For example "LeakySigmoid": for and for :
class LeakySigmoid(nn.Module):
def forward(self, x):
s = torch.sigmoid(x)
return torch.where(x >= 0, s, 0.01 * s)
Use it like any layer, e.g. self.act = LeakySigmoid() and self.fc2(self.act(self.fc1(x))). Autograd differentiates torch.where and torch.sigmoid automatically, so no hand-written backward is needed.
Stuck? Common doubts
Questions real learners asked while studying this lesson. They stay closed so they don't spoil your own thinking: open only the ones you need.
First passWhat happens if I forget optimizer.zero_grad()?
Gradients from every previous batch keep adding up, so each step uses a growing sum of old gradients instead of the current one. Training behaves erratically or diverges. Clear them at the start of every iteration.
Going deeperDoes the LeakySigmoid fix the vanishing-gradient problem?
Not really. For negative inputs it's , so its gradient there is even smaller than the sigmoid's, and for large positive inputs it saturates just like a sigmoid. It's a coding exercise more than a recommended activation; ReLU or Leaky ReLU are the practical choices.
Cheatsheet
Training loop
zero_grad() → forward + loss → loss.backward() → optimizer.step(). model.train() / model.eval() + torch.no_grad() for validation.Classifier output
nn.Linear; nn.CrossEntropyLoss applies log-softmax. Softmax only for reporting probabilities.Check your understanding
Score 75% or more to master this lesson and earn XP. Answer first, then check.