AI from scratch · Deep CNNs · Stage 5: seeing and reading
Deep CNNs and transfer learning
Chapter 6's network had one layer of 8 filters and read digits drawn in fonts. The networks that read real photos have 50 to 150 layers, were trained for days on a million images, and are free to download. This lesson covers what changed between the two (depth, and the tricks that made depth trainable), how to make a little data go further with augmentation, and the most useful move in applied deep learning: take a network someone else trained and teach it your own categories with a few dozen examples. You'll do that last part in this page, on live NYC traffic cameras.
1. A decade of ImageNet
ImageNet's 1.2 million photos in 1,000 categories were the benchmark that drove a decade of vision research. Every row below is a model you can load in one line of torchvision, with the accuracy torchvision reports on ImageNet's validation set.
| Model (year) | Layers | Parameters | Top-1 accuracy | The idea |
|---|---|---|---|---|
| AlexNet (2012) | 8 | 61 M | 56.5% | Chapter 6 on GPUs, with ReLU and dropout |
| VGG-16 (2014) | 16 | 138 M | 71.6% | Only 3 × 3 filters, stacked deep |
| ResNet-50 (2015) | 50 | 25.6 M | 76.1% | Residual blocks and batch norm (the toolkit lesson) |
| MobileNetV2 (2018) | 53 | 3.5 M | 71.9% | Cheap "depthwise" convolutions, for phones |
| EfficientNet-B0 (2019) | 82 | 5.3 M | 77.7% | Depth, width and resolution scaled together |
Two trends: deeper, and more accuracy per parameter. ResNet-50 beats VGG-16 with a fifth of the weights; MobileNetV2 nearly matches VGG with 2.5% of them, which is why it's the one that runs in this page.
Two stacked 3 × 3 convolutions see a 5 × 5 patch of the image. How many weights do they need per input-output channel pair, compared with one 5 × 5 filter's 25?
Vision networks got deeper and leaner: stacks of small filters, residual blocks to make depth trainable, cheap convolutions for phones.
2. What each depth learns
Each layer's filters look at the previous layer's maps, so the patch of the photo a neuron "sees" (its receptive field) grows with depth, and so does what it responds to. Researchers who visualized trained networks (Zeiler and Fergus in 2013, Olah and others at Distill later) found the same ladder in every one:
| Depth | Sees | Responds to |
|---|---|---|
| First layer | 3 × 3 to 11 × 11 pixels | Edges at angles, color blobs: chapter 6's hand-made filters, found on their own |
| Early layers | a few dozen pixels | Textures: stripes, grids, fur, brick |
| Middle layers | a quarter of the image | Parts: eyes, wheels, windows, petals |
| Last layers | most of the image | Whole objects and scenes: dog faces, cars, storefronts |
The early and middle layers are useful for almost any photo task: edges and textures are the same in a cat photo, an X-ray and a traffic camera. Only the last layers are specific to ImageNet's 1,000 categories. That's what makes the next two sections work.
Early layers learn general features (edges, textures) and late layers specific ones (objects), so the bottom of a trained network is reusable.
3. Data augmentation: more photos for free
A cat flipped left to right is still a cat; a slightly darker, slightly zoomed cat too. Augmentation shows the network a random variation of each photo every time it sees it, so it learns to ignore what doesn't matter instead of memorizing pixels: chapter 11's best regularizer, more data, without collecting any. Press the button for new random draws:
from torchvision import transforms as T
train_tf = T.Compose([T.RandomResizedCrop(224, scale=(0.6, 1.0)), T.RandomHorizontalFlip(),
T.ColorJitter(0.3, 0.3, 0.3), T.RandomRotation(10), T.ToTensor(), T.Normalize(mean, std)])
test_tf = T.Compose([T.Resize(256), T.CenterCrop(224), T.ToTensor(), T.Normalize(mean, std)]) # no randomness at test time
Which augmentation would hurt a model that reads handwritten digits?
- A random crop of 90–100% of the image
- A random left-right flip: a mirrored 2 isn't a 2, and a flipped 7 looks like nothing
- Random stroke thickness
Augmentation shows random label-preserving variations of each photo, so the network learns to ignore what doesn't matter.
4. Transfer learning: borrow the eyes, train the decision
Take a network trained on ImageNet, cut off its last layer (the 1,000-way classifier), and what's left turns any photo into a vector of numbers, an embedding (1,280 numbers for MobileNetV2). Photos that look alike get nearby vectors. To teach it your own categories you only need a small new classifier on top of those vectors. Below, MobileNetV2 runs in your browser on live NYC traffic cameras. Name two categories, label a few frames, and it starts guessing: a k-nearest-neighbors vote (clusters and anomalies) on the embeddings of your examples.
Loading MobileNetV2 (about 14 MB, once)…
Ideas: busy / quiet, day / night, wet road / dry road, bridge / street. After 5 or so examples each, it usually gets new frames right, from a network that was never shown a traffic camera, because "lots of cars" and "dark sky" are made of the edges, textures and parts it already knows. Your examples never leave the browser.
In code there are three ways to use a pretrained network, from least to most training:
| Approach | What trains | When |
|---|---|---|
| Embeddings + a simple model (this page) | Only kNN or logistic regression on the vectors | Tens to hundreds of examples; fastest |
| Freeze the backbone, new head | The last layer: for p in model.parameters(): p.requires_grad = False, then model.fc = nn.Linear(512, n_classes) | Hundreds to thousands of examples |
| Fine-tune everything | All layers, with a learning rate about 10 times smaller than from scratch | Thousands of examples, or photos unlike ImageNet's (X-rays, satellites) |
How much does borrowing buy? In the practice notebook, on 2,000 small CIFAR-10 photos (10 kinds: planes, cars, birds, cats…): a small CNN trained from scratch reaches about 51% on new photos; frozen ResNet-18 embeddings with a logistic regression on top reach about 77%, in less time. With only 20 labeled photos, 2 per kind, the borrowed embeddings still get 42%, four times chance.
When fine-tuning all layers, why use a much smaller learning rate than for training from scratch?
- The pretrained weights are already good: big steps would wreck the general features you're borrowing before the new head learns anything
- Because the model is smaller
- To train faster
A pretrained network's body turns photos into meaningful vectors; teaching it new categories only needs a small model on top, trained on a few examples.
Why a few examples are enough
- Training from scratch must learn every weight from your data: millions of numbers from a few hundred photos, a recipe for chapter 11's overfitting.
- The pretrained body already maps photos to vectors where "looks alike" means "nearby": ImageNet's million photos paid for that.
- In that space your two categories are often already separated, or nearly. All that's left to learn is where the line between them goes: with a 1,280-number embedding, a logistic regression has 1,281 weights, and kNN has none.
- Fewer numbers to fit means far less data needed (the same reason chapter 6's shared filters beat a dense layer).
- It fails when your photos look nothing like ImageNet's: then the borrowed vectors don't separate your categories, and you need to fine-tune deeper layers, or more data (below).
Where it breaks: borrowed eyes have borrowed blind spots
- A different kind of image. Medical scans, satellite images and microscope slides have textures ImageNet never had. Frozen features do much worse there; fine-tuning more layers, or a model pretrained on similar images, does better.
- Shortcuts in your few examples. If every "busy" frame you label is from the same camera, the model may learn "this camera" rather than "busy". Spread examples over cameras, times and weather, and test on cameras you didn't train on.
- Inherited biases. A pretrained network carries its training set's habits: ImageNet is mostly photos from North America and Europe, so objects and scenes from elsewhere are recognized less well. Measure accuracy per group (chapter 12's slices) before shipping.
5. What to carry forward
- Deep CNNs: stacks of 3 × 3 filters, residual blocks, batch norm; MobileNet-style cheap convolutions for small devices.
- Early layers learn general features, late layers task-specific ones.
- Augment with variations that keep the label true; none at test time.
- Transfer: embeddings + a simple model, then a new head on a frozen body, then fine-tuning everything at a small rate, as data grows.
- Check for shortcuts and test on data unlike your examples.
All lessons: AI from scratch. Model: MobileNet for TensorFlow.js (Apache 2.0). Cameras: NYC DOT. Accuracies: torchvision's model documentation. Fast.ai's lesson 1 is the companion: a pretrained classifier in a few lines.
Last updated