Week 07 · CNNs and transfer learning

Fine-tune a small visual encoder and test it under a lighting change.

← Week 6 · Subject contents · Week 8 →

Fine-tune a small visual encoder and test it under a lighting change.

Work through the problem

A convolution reuses a small spatial filter at every location. This weight sharing allows a learned edge detector to respond in different parts of the image. Global pooling makes the pooled statistic less sensitive to exactly where the response occurs.

Pretrain on bright bars whose positions vary. Reuse the convolutional weights to classify bars in a new brightness range. Use a few target examples and test on independently generated examples from a dimmer range. The test measures illumination transfer for a controlled shape task.

Run the Python lab

from copy import deepcopy
import torch
from torch import nn
torch.set_num_threads(1)
torch.manual_seed(25)
def batch(n,level):
    x = .07*torch.randn(n,1,12,12)
    y = torch.arange(n)%2
    for i in range(n):
        j = 2+(i*5)%7
        if y[i]==0:
            x[i,0,j:j+2,1:11]+=level
        else:
            x[i,0,1:11,j:j+2]+=level
    return x,y
encoder = nn.Sequential(nn.Conv2d(1,8,3,padding=1),nn.ReLU(),nn.AdaptiveMaxPool2d(1),nn.Flatten())
def train(model,x,y):
    opt = torch.optim.Adam((p for p in model.parameters() if p.requires_grad),lr=.025)
    for _ in range(65):
        opt.zero_grad()
        nn.functional.cross_entropy(model(x),y).backward()
        opt.step()
source = nn.Sequential(encoder,nn.Linear(8,2))
train(source,*batch(96,1.0))
target, labels = batch(32,.55)
test, truth = batch(100,.25)
for frozen in [True,False]:
    enc = deepcopy(encoder).requires_grad_(not frozen)
    model = nn.Sequential(enc,nn.Linear(8,2))
    train(model,target,labels)
    print("Frozen",frozen,"dim accuracy",round((model(test).argmax(1)==truth).float().mean().item(),3))

Output from the lab

Frozen True dim accuracy 0.71
Frozen False dim accuracy 0.92

Practice

  1. What should you add before drawing a conclusion about real cameras?

Check your reasoning

  1. Hold out real cameras and lighting conditions. Synthetic bars test one controlled failure mode.

← Week 6 · Subject contents · Week 8 →

Further reading · Szeliski · Computer Vision: Algorithms and Applications