Epoch-based training helps a model learn by showing it the entire dataset multiple times. This improves the model's ability to understand patterns.
Epoch-based training in PyTorch
for epoch in range(num_epochs): for inputs, labels in dataloader: # forward pass outputs = model(inputs) loss = loss_function(outputs, labels) # backward pass and optimization optimizer.zero_grad() loss.backward() optimizer.step() print(f"Epoch {epoch+1}/{num_epochs}, Loss: {loss.item():.4f}")
The outer loop runs over the number of epochs (full passes).
The inner loop runs over batches of data for each epoch.
num_epochs = 5 for epoch in range(num_epochs): print(f"Starting epoch {epoch+1}")
for epoch in range(3): for batch in dataloader: # training steps here pass print(f"Completed epoch {epoch+1}")
This program trains a simple linear model to fit a line y = 3x + 2 with some noise. It runs for 5 epochs, printing the loss after each epoch.
import torch import torch.nn as nn import torch.optim as optim from torch.utils.data import DataLoader, TensorDataset # Create a simple dataset x = torch.linspace(-1, 1, 100).unsqueeze(1) y = 3 * x + 2 + 0.1 * torch.randn(x.size()) # Dataset and DataLoader dataset = TensorDataset(x, y) dataloader = DataLoader(dataset, batch_size=10, shuffle=True) # Simple linear model model = nn.Linear(1, 1) # Loss and optimizer loss_function = nn.MSELoss() optimizer = optim.SGD(model.parameters(), lr=0.1) num_epochs = 5 for epoch in range(num_epochs): for inputs, labels in dataloader: outputs = model(inputs) loss = loss_function(outputs, labels) optimizer.zero_grad() loss.backward() optimizer.step() print(f"Epoch {epoch+1}/{num_epochs}, Loss: {loss.item():.4f}")
Loss usually decreases after each epoch if the model is learning well.
Shuffling data each epoch helps the model learn better by mixing data order.
Too many epochs can cause overfitting, where the model learns noise instead of patterns.
Epoch-based training means showing the whole dataset multiple times to the model.
Each epoch has many batches; the model updates after each batch.
Monitoring loss after each epoch helps track learning progress.
Practice
Solution
Step 1: Understand the definition of an epoch
An epoch means the model sees every example in the training dataset once.Step 2: Differentiate epoch from batch and update
A batch is a subset of data; multiple batches make an epoch. Weight updates happen after each batch, not the whole dataset.Final Answer:
One full pass through the entire training dataset -> Option AQuick Check:
Epoch = full dataset pass [OK]
- Confusing batch with epoch
- Thinking epoch is one weight update
- Mixing test evaluation with training epoch
Solution
Step 1: Recall Python range behavior
range(5) generates 0,1,2,3,4 which is 5 iterations.Step 2: Check other options for iteration count
range(1,5) gives 4 iterations; range(0,6) gives 6; range(5,10) gives 5 but starts at 5, not zero.Final Answer:
for epoch in range(5): -> Option DQuick Check:
range(5) = 5 loops [OK]
- Using range(1,5) which loops 4 times
- Using range(0,6) which loops 6 times
- Starting loop at 5 instead of 0
for epoch in range(2):
total_loss = 0
for batch in dataloader:
output = model(batch)
loss = loss_fn(output, batch.labels)
optimizer.zero_grad()
loss.backward()
optimizer.step()
total_loss += loss.item()
print(f"Epoch {epoch+1} loss: {total_loss}")Solution
Step 1: Analyze the outer loop and print statement
The outer loop runs 2 times (epochs 0 and 1). After each epoch, it prints total_loss.Step 2: Understand total_loss accumulation and printing
total_loss sums batch losses per epoch, so print shows loss after each epoch.Final Answer:
Loss values for epoch 1 and epoch 2 printed -> Option BQuick Check:
Print inside epoch loop prints each epoch loss [OK]
- Thinking only last epoch loss prints
- Confusing batch loss with epoch loss
- Assuming print causes error
for epoch in range(3):
for batch in dataloader:
output = model(batch)
loss = loss_fn(output, batch.labels)
loss.backward()
optimizer.step()
optimizer.zero_grad()
print(f"Epoch {epoch+1} done")Solution
Step 1: Recall correct order of optimizer calls
Zero gradients before backward pass to avoid accumulating gradients.Step 2: Check code order
Code calls loss.backward() before optimizer.zero_grad(), which is wrong.Final Answer:
optimizer.zero_grad() should be called before loss.backward() -> Option CQuick Check:
Zero grads before backward [OK]
- Zeroing gradients after backward
- Swapping optimizer.step() and zero_grad() order
- Thinking no zero_grad needed
Solution
Step 1: Understand early stopping concept
Early stopping monitors validation loss after each epoch to decide if training should continue.Step 2: Match early stopping with epoch-based training
Checking validation loss after each epoch and stopping if no improvement for 3 epochs fits epoch-based training.Final Answer:
After each epoch, check validation loss and stop if no improvement for 3 epochs -> Option AQuick Check:
Early stopping checks validation loss per epoch [OK]
- Checking after batches instead of epochs
- Ignoring validation loss during training
- Waiting until all epochs finish to check
Ready to prove it?
Pass the test and this pattern moves unknown
