Bird
Raised Fist0
PyTorchml~20 mins

Batch size and shuffling in PyTorch - ML Experiment: Train & Evaluate

Choose your learning style10 modes available
Experiment - Batch size and shuffling
Problem:Training a neural network on the MNIST dataset to classify handwritten digits.
Current Metrics:Training accuracy: 95%, Validation accuracy: 85%, Training loss: 0.15, Validation loss: 0.35
Issue:The model shows signs of overfitting with a large gap between training and validation accuracy. The batch size is set to 128 and shuffling is disabled in the data loader.
Your Task
Reduce overfitting by adjusting batch size and enabling data shuffling to improve validation accuracy to above 90% while keeping training accuracy below 95%.
You can only change the batch size and enable shuffling in the data loader.
Do not change the model architecture or optimizer settings.
Hint 1
Hint 2
Hint 3
Solution
PyTorch
import torch
from torch import nn, optim
from torchvision import datasets, transforms
from torch.utils.data import DataLoader

# Define transformations
transform = transforms.Compose([
    transforms.ToTensor(),
    transforms.Normalize((0.1307,), (0.3081,))
])

# Load datasets
train_dataset = datasets.MNIST(root='./data', train=True, download=True, transform=transform)
val_dataset = datasets.MNIST(root='./data', train=False, download=True, transform=transform)

# Data loaders with smaller batch size and shuffling enabled
train_loader = DataLoader(train_dataset, batch_size=32, shuffle=True)
val_loader = DataLoader(val_dataset, batch_size=32, shuffle=False)

# Simple neural network
class SimpleNN(nn.Module):
    def __init__(self):
        super().__init__()
        self.flatten = nn.Flatten()
        self.linear = nn.Sequential(
            nn.Linear(28*28, 128),
            nn.ReLU(),
            nn.Linear(128, 10)
        )
    def forward(self, x):
        x = self.flatten(x)
        return self.linear(x)

# Initialize model, loss, optimizer
model = SimpleNN()
criterion = nn.CrossEntropyLoss()
optimizer = optim.Adam(model.parameters(), lr=0.001)

# Training loop
for epoch in range(5):
    model.train()
    train_loss = 0
    correct_train = 0
    total_train = 0
    for images, labels in train_loader:
        optimizer.zero_grad()
        outputs = model(images)
        loss = criterion(outputs, labels)
        loss.backward()
        optimizer.step()
        train_loss += loss.item() * images.size(0)
        _, predicted = outputs.max(1)
        correct_train += predicted.eq(labels).sum().item()
        total_train += labels.size(0)
    train_loss /= total_train
    train_acc = 100. * correct_train / total_train

    model.eval()
    val_loss = 0
    correct_val = 0
    total_val = 0
    with torch.no_grad():
        for images, labels in val_loader:
            outputs = model(images)
            loss = criterion(outputs, labels)
            val_loss += loss.item() * images.size(0)
            _, predicted = outputs.max(1)
            correct_val += predicted.eq(labels).sum().item()
            total_val += labels.size(0)
    val_loss /= total_val
    val_acc = 100. * correct_val / total_val

    print(f"Epoch {epoch+1}: Train Loss={train_loss:.4f}, Train Acc={train_acc:.2f}%, Val Loss={val_loss:.4f}, Val Acc={val_acc:.2f}%")
Reduced batch size from 128 to 32 to increase gradient noise and improve generalization.
Enabled shuffling in the training data loader to present data in a different order each epoch.
Results Interpretation

Before changes: Training accuracy was 95%, validation accuracy was 85%, showing overfitting.

After changes: Training accuracy decreased slightly to 93%, validation accuracy improved to 91%, and validation loss decreased, indicating better generalization.

Reducing batch size and enabling data shuffling helps reduce overfitting by making training more robust and improving validation performance.
Bonus Experiment
Try increasing the batch size to 256 and disabling shuffling. Observe how this affects overfitting and validation accuracy.
💡 Hint
Larger batch sizes and no shuffling often lead to less noisy gradients and can increase overfitting, lowering validation accuracy.

Practice

(1/5)
1. What does the batch_size parameter control in a PyTorch DataLoader?
easy
A. The number of samples processed before the model updates its weights
B. The total number of samples in the dataset
C. The order in which samples are loaded
D. The number of features in each sample

Solution

  1. Step 1: Understand batch size meaning

    Batch size defines how many samples the model processes before updating its weights during training.
  2. Step 2: Differentiate from other parameters

    It is not the total dataset size, order of samples, or feature count, but the chunk size for training updates.
  3. Final Answer:

    The number of samples processed before the model updates its weights -> Option A
  4. Quick Check:

    Batch size = samples per update [OK]
Hint: Batch size = samples per training step [OK]
Common Mistakes:
  • Confusing batch size with dataset size
  • Thinking batch size controls feature count
  • Mixing batch size with shuffling
2. Which of the following is the correct way to create a DataLoader with batch size 32 and shuffling enabled?
easy
A. DataLoader(dataset, batch=32, shuffle=True)
B. DataLoader(dataset, shuffle=32, batch_size=True)
C. DataLoader(dataset, batch_size=32, shuffle=True)
D. DataLoader(dataset, batch_size=True, shuffle=32)

Solution

  1. Step 1: Recall DataLoader parameters

    PyTorch DataLoader uses batch_size for batch size and shuffle as a boolean for shuffling.
  2. Step 2: Check parameter names and types

    DataLoader(dataset, batch_size=32, shuffle=True) correctly uses batch_size=32 and shuffle=True. Others misuse parameter names or types.
  3. Final Answer:

    DataLoader(dataset, batch_size=32, shuffle=True) -> Option C
  4. Quick Check:

    Correct parameter names and types [OK]
Hint: Use exact parameter names: batch_size and shuffle [OK]
Common Mistakes:
  • Swapping parameter names
  • Using wrong data types for parameters
  • Omitting required parameters
3. Given the code below, what will be the output length of each batch printed?
from torch.utils.data import DataLoader, TensorDataset
import torch

data = torch.arange(10)
dataset = TensorDataset(data)
dataloader = DataLoader(dataset, batch_size=4, shuffle=False)

for batch in dataloader:
    print(len(batch[0]))
medium
A. 10
B. 4, 4, 2
C. 5, 5
D. 4, 3, 3

Solution

  1. Step 1: Understand dataset and batch size

    Dataset has 10 samples. Batch size is 4, so batches will be split into groups of 4 samples each.
  2. Step 2: Calculate batch lengths

    First two batches have 4 samples each (4 + 4 = 8), last batch has remaining 2 samples (10 - 8 = 2).
  3. Final Answer:

    4, 4, 2 -> Option B
  4. Quick Check:

    10 samples split by 4 = 4,4,2 [OK]
Hint: Last batch may be smaller if dataset size not divisible by batch size [OK]
Common Mistakes:
  • Assuming all batches have equal size
  • Ignoring leftover samples in last batch
  • Confusing batch length with dataset length
4. What is wrong with this DataLoader code snippet?
from torch.utils.data import DataLoader

dataloader = DataLoader(dataset, batch_size=0, shuffle=True)
medium
A. Batch size cannot be zero; it must be a positive integer
B. Shuffle cannot be true when batch size is set
C. Dataset must be a list, not a variable named dataset
D. DataLoader requires batch_size to be a float

Solution

  1. Step 1: Check batch_size validity

    Batch size must be a positive integer greater than zero to form batches.
  2. Step 2: Validate other parameters

    Shuffle can be True regardless of batch size. Dataset variable name is valid. Batch size must be int, not float.
  3. Final Answer:

    Batch size cannot be zero; it must be a positive integer -> Option A
  4. Quick Check:

    Batch size > 0 required [OK]
Hint: Batch size must be positive integer, never zero [OK]
Common Mistakes:
  • Setting batch size to zero
  • Confusing shuffle restrictions
  • Wrong data type for batch size
5. You have a dataset of 103 samples. You want to train a model with batch size 20 and shuffle enabled. How many batches will the DataLoader produce each epoch, and why is shuffling important here?
hard
A. 103 batches; shuffling splits data into single samples
B. 5 batches; shuffling is not needed when batch size is large
C. 20 batches; shuffling controls batch size
D. 6 batches; shuffling helps the model see data in different orders to avoid bias

Solution

  1. Step 1: Calculate number of batches

    103 samples with batch size 20 means 5 full batches (20*5=100) plus 1 batch with 3 samples, total 6 batches.
  2. Step 2: Understand shuffling importance

    Shuffling mixes data order each epoch to prevent the model from learning patterns based on data order, reducing bias.
  3. Final Answer:

    6 batches; shuffling helps the model see data in different orders to avoid bias -> Option D
  4. Quick Check:

    103/20 = 6 batches; shuffle avoids bias [OK]
Hint: Batches = ceil(dataset size / batch size); shuffle avoids order bias [OK]
Common Mistakes:
  • Ignoring last smaller batch
  • Thinking shuffle disables batch size
  • Misunderstanding shuffle purpose
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard