Bird
Raised Fist0
PyTorchml~20 mins

Why pre-trained models accelerate development in PyTorch - Experiment to Prove It

Choose your learning style10 modes available

Start learning this pattern below

Jump into concepts and practice - no test required

or
Recommended
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Experiment - Why pre-trained models accelerate development
Problem:You want to build an image classifier but training a model from scratch takes a long time and needs a lot of data.
Current Metrics:Training accuracy: 95%, Validation accuracy: 60%, Training loss: 0.15, Validation loss: 1.2
Issue:The model overfits the training data and performs poorly on new images because it has not learned general features well.
Your Task
Use a pre-trained model to improve validation accuracy to above 85% while reducing training time.
You must use PyTorch and a pre-trained model from torchvision.
You can only fine-tune the last layer of the model.
Do not change the dataset or add more data.
Hint 1
Hint 2
Hint 3
Hint 4
Solution
PyTorch
import torch
import torch.nn as nn
import torch.optim as optim
from torchvision import datasets, transforms, models
from torch.utils.data import DataLoader

# Data transforms
transform = transforms.Compose([
    transforms.Resize((224, 224)),
    transforms.ToTensor(),
    transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])
])

# Load dataset (example: CIFAR-10)
train_dataset = datasets.CIFAR10(root='./data', train=True, download=True, transform=transform)
val_dataset = datasets.CIFAR10(root='./data', train=False, download=True, transform=transform)

train_loader = DataLoader(train_dataset, batch_size=32, shuffle=True)
val_loader = DataLoader(val_dataset, batch_size=32, shuffle=False)

# Load pre-trained ResNet18
model = models.resnet18(pretrained=True)

# Freeze all layers
for param in model.parameters():
    param.requires_grad = False

# Replace the final layer
num_features = model.fc.in_features
model.fc = nn.Linear(num_features, 10)  # CIFAR-10 has 10 classes

# Only parameters of final layer are trainable
params_to_update = model.fc.parameters()

# Use GPU if available
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
model = model.to(device)

criterion = nn.CrossEntropyLoss()
optimizer = optim.Adam(params_to_update, lr=0.001)

# Training loop
for epoch in range(5):  # small number of epochs for demo
    model.train()
    running_loss = 0.0
    correct = 0
    total = 0
    for inputs, labels in train_loader:
        inputs, labels = inputs.to(device), labels.to(device)
        optimizer.zero_grad()
        outputs = model(inputs)
        loss = criterion(outputs, labels)
        loss.backward()
        optimizer.step()

        running_loss += loss.item() * inputs.size(0)
        _, predicted = torch.max(outputs, 1)
        total += labels.size(0)
        correct += (predicted == labels).sum().item()

    train_loss = running_loss / total
    train_acc = 100 * correct / total

    # Validation
    model.eval()
    val_loss = 0.0
    val_correct = 0
    val_total = 0
    with torch.no_grad():
        for inputs, labels in val_loader:
            inputs, labels = inputs.to(device), labels.to(device)
            outputs = model(inputs)
            loss = criterion(outputs, labels)
            val_loss += loss.item() * inputs.size(0)
            _, predicted = torch.max(outputs, 1)
            val_total += labels.size(0)
            val_correct += (predicted == labels).sum().item()

    val_loss /= val_total
    val_acc = 100 * val_correct / val_total

    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}%')
Loaded a pre-trained ResNet18 model instead of training from scratch.
Froze all layers except the last fully connected layer.
Replaced the last layer to match the number of classes in the dataset.
Trained only the last layer with a small learning rate.
Used standard image normalization and resizing to fit the pre-trained model input.
Results Interpretation

Before: Training accuracy 95%, Validation accuracy 60%, high overfitting.

After: Training accuracy 88%, Validation accuracy 87%, much better generalization.

Using a pre-trained model helps the model learn general features from a large dataset. Fine-tuning only the last layer reduces training time and overfitting, improving validation accuracy quickly.
Bonus Experiment
Try unfreezing some of the earlier layers and fine-tune more layers to see if validation accuracy improves further.
💡 Hint
Unfreeze the last few layers and use a smaller learning rate for them to avoid destroying learned features.

Practice

(1/5)
1. Why do pre-trained models help speed up AI development in PyTorch?
easy
A. They always produce perfect results without any training.
B. They start with knowledge learned from other data, reducing training time.
C. They require more data to train from scratch.
D. They avoid the need for any coding or model building.

Solution

  1. Step 1: Understand pre-trained model concept

    Pre-trained models have already learned patterns from large datasets, so they don't start from zero.
  2. Step 2: Relate to training time

    Because they start with learned features, training on new tasks is faster and needs less data.
  3. Final Answer:

    They start with knowledge learned from other data, reducing training time. -> Option B
  4. Quick Check:

    Pre-trained models speed development by reusing learned knowledge [OK]
Hint: Pre-trained means already learned, so less training needed [OK]
Common Mistakes:
  • Thinking pre-trained models need more data
  • Believing pre-trained models don't require any training
  • Assuming pre-trained models are perfect without fine-tuning
2. Which PyTorch code snippet correctly loads a pre-trained ResNet model?
easy
A. model = torchvision.models.resnet50(weights='IMAGENET1K_V1')
B. model = torchvision.models.resnet50(pretrained=False)
C. model = torchvision.models.resnet50(pretrained=false)
D. model = torchvision.models.resnet50(load_pretrained=True)

Solution

  1. Step 1: Check PyTorch's current API for loading pre-trained models

    Recent PyTorch versions use the 'weights' parameter to specify pre-trained weights, e.g., weights='IMAGENET1K_V1'.
  2. Step 2: Identify correct syntax

    model = torchvision.models.resnet50(weights='IMAGENET1K_V1') uses 'weights="IMAGENET1K_V1"', which is the correct way to load pre-trained weights in PyTorch 1.12+.
  3. Final Answer:

    model = torchvision.models.resnet50(weights='IMAGENET1K_V1') -> Option A
  4. Quick Check:

    Use weights='IMAGENET1K_V1' to load pre-trained models [OK]
Hint: Use weights='IMAGENET1K_V1' for pre-trained models in PyTorch 1.12+ [OK]
Common Mistakes:
  • Using deprecated pretrained=True parameter
  • Using nonexistent load_pretrained argument
  • Setting pretrained=False which loads untrained model
3. What will be the output shape of the final layer when fine-tuning a pre-trained ResNet50 model for 10 classes in PyTorch?
medium
A. [batch_size, 10]
B. [batch_size, 512]
C. [10, batch_size]
D. [batch_size, 1000]

Solution

  1. Step 1: Understand ResNet50 default output

    By default, ResNet50 outputs 1000 classes for ImageNet classification.
  2. Step 2: Fine-tuning changes final layer output size

    When fine-tuning for 10 classes, the final fully connected layer is replaced to output 10 values per input.
  3. Final Answer:

    [batch_size, 10] -> Option A
  4. Quick Check:

    Fine-tuned model outputs match new class count [OK]
Hint: Final layer output matches number of classes [OK]
Common Mistakes:
  • Assuming output stays 1000 classes after fine-tuning
  • Confusing batch size and class dimension order
  • Using feature size (512) as output shape
4. You tried to fine-tune a pre-trained model but get a shape mismatch error on the last layer. What is the likely cause?
medium
A. The model was not loaded with pre-trained weights.
B. The optimizer learning rate is too high.
C. The input images are not normalized correctly.
D. The final layer's output size does not match the new task's number of classes.

Solution

  1. Step 1: Identify cause of shape mismatch error

    Shape mismatch usually happens when the model's last layer output size differs from the target labels size.
  2. Step 2: Relate to fine-tuning process

    When fine-tuning, you must replace the last layer to match the new number of classes; otherwise, shapes won't align.
  3. Final Answer:

    The final layer's output size does not match the new task's number of classes. -> Option D
  4. Quick Check:

    Shape mismatch means output layer size differs from labels [OK]
Hint: Check last layer output size matches target classes [OK]
Common Mistakes:
  • Blaming optimizer or input normalization for shape errors
  • Forgetting to replace the final layer for new tasks
  • Assuming pre-trained weights cause shape mismatch
5. You have a small dataset and limited GPU power. How does using a pre-trained model in PyTorch help you build an accurate classifier faster?
hard
A. It automatically generates more data to train on.
B. It trains the entire model from scratch faster than a new model.
C. It allows you to fine-tune only the last layers, reducing training time and data needs.
D. It removes the need for validation and testing.

Solution

  1. Step 1: Understand constraints of small data and limited GPU

    Training a full model from scratch requires lots of data and computing power, which are limited here.
  2. Step 2: Explain benefit of fine-tuning pre-trained models

    Pre-trained models have learned features already, so you can train only the last layers, saving time and data.
  3. Step 3: Why other options are incorrect

    It trains the entire model from scratch faster than a new model. is wrong because training from scratch is slower. It automatically generates more data to train on. is false; pre-trained models don't generate data. It removes the need for validation and testing. is incorrect; validation/testing are always needed.
  4. Final Answer:

    It allows you to fine-tune only the last layers, reducing training time and data needs. -> Option C
  5. Quick Check:

    Fine-tuning last layers saves time and data [OK]
Hint: Fine-tune last layers to save time and data [OK]
Common Mistakes:
  • Thinking pre-trained models generate more data
  • Believing full training is faster than fine-tuning
  • Skipping validation/testing phases