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)LayersParametersTop-1 accuracyThe idea
AlexNet (2012)861 M56.5%Chapter 6 on GPUs, with ReLU and dropout
VGG-16 (2014)16138 M71.6%Only 3 × 3 filters, stacked deep
ResNet-50 (2015)5025.6 M76.1%Residual blocks and batch norm (the toolkit lesson)
MobileNetV2 (2018)533.5 M71.9%Cheap "depthwise" convolutions, for phones
EfficientNet-B0 (2019)825.3 M77.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?

\(2 \times 9 = 18\) against 25: the same view for fewer weights, plus an extra ReLU in between. Three 3 × 3 layers see 7 × 7 for 27 weights instead of 49. That's VGG's whole idea.

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:

DepthSeesResponds to
First layer3 × 3 to 11 × 11 pixelsEdges at angles, color blobs: chapter 6's hand-made filters, found on their own
Early layersa few dozen pixelsTextures: stripes, grids, fur, brick
Middle layersa quarter of the imageParts: eyes, wheels, windows, petals
Last layersmost of the imageWhole 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?

An augmentation must keep the label true. Flips are free for cats and cars, wrong for text and digits; vertical flips are wrong for most street scenes (the sky goes down). Choose them from what the task says can vary.

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.

A live NYC traffic camera frame

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:

ApproachWhat trainsWhen
Embeddings + a simple model (this page)Only kNN or logistic regression on the vectorsTens to hundreds of examples; fastest
Freeze the backbone, new headThe 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 everythingAll layers, with a learning rate about 10 times smaller than from scratchThousands 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?

At the start the new head is random, so its gradients are large and noisy; with a big rate they flow back and scramble the borrowed layers. A common recipe: train the head alone for an epoch, then unfreeze everything at a small rate.

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
  1. 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.
  2. The pretrained body already maps photos to vectors where "looks alike" means "nearby": ImageNet's million photos paid for that.
  3. 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.
  4. Fewer numbers to fit means far less data needed (the same reason chapter 6's shared filters beat a dense layer).
  5. 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

5. What to carry forward

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