Key terms for this tutorial
Here are the words that matter most in this tutorial. Come back here if a term feels fuzzy.
- learning rate
- How far the optimizer moves the weights each step. Too big and training explodes; too small and it crawls.
- model
- A function with learnable parameters that maps inputs to outputs.
- neural network
- A stack of layers that transform data through learned weights and non-linearities.
- parameters
- The collection of learnable numbers inside a model.
- ReLU
- A common activation function that outputs the input directly if it is positive, and zero otherwise.
- transfer learning
- Using a model trained on one task as the starting point for a related task.
How a CNN works
Convolutional layers slide learnable filters over an image, producing feature maps. Pooling downsamples those maps, and stacking layers lets the network learn edges, textures, shapes, and objects.
import torch
import torch.nn as nn
class TinyCNN(nn.Module):
def __init__(self):
super().__init__()
self.conv = nn.Sequential(
nn.Conv2d(3, 8, 3, padding=1),
nn.ReLU(),
nn.MaxPool2d(2),
nn.Conv2d(8, 16, 3, padding=1),
nn.ReLU(),
nn.MaxPool2d(2),
)
self.fc = nn.Linear(16 * 8 * 8, 10)
def forward(self, x):
x = self.conv(x)
x = x.view(x.size(0), -1)
return self.fc(x)
model = TinyCNN()
out = model(torch.randn(2, 3, 32, 32))
print('logits shape:', out.shape)
logits shape: torch.Size([2, 10])
Line-by-line: cnn.py
Read this slowly. Each line does one small, concrete thing.
import torch— Import thetorchlibrary so we can use its built-in tools.import torch.nn as nn— Import thetorchlibrary so we can use its built-in tools.class TinyCNN(nn.Module):— Define a customTinyCNNclass that tells PyTorch how to fetch one example.def __init__(self):— Define the__init__function, which describes a step in the data or model pipeline.self.conv = nn.Sequential(— Perform a convolution, sliding small filters over the image to detect patterns.self.fc = nn.Linear(16 * 8 * 8, 10)— Add a linear layer that multiplies inputs by a weight matrix and adds a bias.def forward(self, x):— Define theforwardfunction, which describes a step in the data or model pipeline.x = self.conv(x)— Perform a convolution, sliding small filters over the image to detect patterns.out = model(torch.randn(2, 3, 32, 32))— Create a tensor filled with random numbers to use as fake data or initial weights.print('logits shape:', out.shape)— Print a result so we can see what the model learned.
Pop-in: Read the code one block at a time
Industry code imports many libraries. Focus on the sequence: prepare data, define the model, run the training loop, and evaluate. The rest is setup.
Stuck or curious? Explain this to me on ChatGPT
Prompt: I am a beginner AI engineer working through the CodeHS tutorial 'AI Engineer: Computer Vision and Transfer Learning'. Explain the section 'How a CNN works' in plain English. Include simple analogies, vocabulary definitions, and a short example. Also walk through the code example in this section step by step.
Fine-tune a pre-trained ResNet
Pre-trained models on ImageNet already know low-level features. Replace the final classifier with a new one for your task, freeze the backbone for a few epochs, then unfreeze and train with a small learning rate.
import torchvision.models as models
import torch.nn as nn
resnet = models.resnet18(weights=models.ResNet18_Weights.DEFAULT)
num_ftrs = resnet.fc.in_features
resnet.fc = nn.Linear(num_ftrs, 2)
for param in resnet.parameters():
param.requires_grad = False
for param in resnet.fc.parameters():
param.requires_grad = True
print('trainable params:', sum(p.numel() for p in resnet.parameters() if p.requires_grad))
trainable params: 1026
Line-by-line: transfer.py
Read this slowly. Each line does one small, concrete thing.
import torchvision.models as models— Import thetorchvisionlibrary so we can use its built-in tools.import torch.nn as nn— Import thetorchlibrary so we can use its built-in tools.resnet.fc = nn.Linear(num_ftrs, 2)— Add a linear layer that multiplies inputs by a weight matrix and adds a bias.for param in resnet.parameters():— Loop over the data one batch at a time.for param in resnet.fc.parameters():— Loop over the data one batch at a time.print('trainable params:', sum(p.numel() for p in resnet.parameters() if p.requires_grad))— Loop over the data one batch at a time.
Pop-in: Read the code one block at a time
Industry code imports many libraries. Focus on the sequence: prepare data, define the model, run the training loop, and evaluate. The rest is setup.
Stuck or curious? Explain this to me on ChatGPT
Prompt: I am a beginner AI engineer working through the CodeHS tutorial 'AI Engineer: Computer Vision and Transfer Learning'. Explain the section 'Fine-tune a pre-trained ResNet' in plain English. Include simple analogies, vocabulary definitions, and a short example. Also walk through the code example in this section step by step.
Check yourself
Why freeze the backbone first?
In transfer learning, why train only the new head at the start?
Randomly initialised gradients from the new head can destroy the useful pre-trained features in the backbone before they are fine-tuned.
Stuck or curious? Explain this to me on ChatGPT
Prompt: I am a beginner AI engineer studying 'AI Engineer: Computer Vision and Transfer Learning'. The practice question 'Why freeze the backbone first?' asks: In transfer learning, why train only the new head at the start? The answer is: Randomly initialised gradients from the new head can destroy the useful pre-trained features in the backbone before they are fine-tuned.. Explain the concept behind this in simple terms.
Stuck or curious? Explain this to me on ChatGPT
Prompt: I am a beginner AI engineer working through the CodeHS tutorial 'AI Engineer: Computer Vision and Transfer Learning'. Explain the section 'Check yourself' in plain English. Include simple analogies, vocabulary definitions, and a short example.
Three questions
1. What does a convolutional layer learn?
Stuck or curious? Explain this question to me on ChatGPT
Prompt: I am a beginner AI engineer studying 'AI Engineer: Computer Vision and Transfer Learning'. The quiz asks: What does a convolutional layer learn? The correct answer is: Spatial features like edges and textures. Explain why that answer is right and why the other choices are wrong, using a simple example.
2. Why use transfer learning?
Stuck or curious? Explain this question to me on ChatGPT
Prompt: I am a beginner AI engineer studying 'AI Engineer: Computer Vision and Transfer Learning'. The quiz asks: Why use transfer learning? The correct answer is: To reuse features learned on large datasets and train faster. Explain why that answer is right and why the other choices are wrong, using a simple example.
3. What is the head of a transfer model?
Stuck or curious? Explain this question to me on ChatGPT
Prompt: I am a beginner AI engineer studying 'AI Engineer: Computer Vision and Transfer Learning'. The quiz asks: What is the head of a transfer model? The correct answer is: The new final classifier replaced for the target task. Explain why that answer is right and why the other choices are wrong, using a simple example.
Keep learning
Next: modern NLP with Hugging Face tokenizers and transformers.
Part of the CodeHS tutorial library.