Transfer Learning

Updated · 14 min read
hardPython 3.13aideep-learningtransfer-learningfine-tuningresnetcomputer-vision

Transfer learning means starting from a model that was already trained on a large dataset and adapting it to your own task. A CNN trained on millions of photos has already learned to see edges, textures, shapes and parts of objects. Your task only needs to teach it the last step: which of your categories a photo belongs to.

This is how most real image projects are built, because it works with a few dozen photos per category instead of millions. This lesson completes the chapter's checkpoint: fine-tune a pretrained image model to sort photos of school notices into categories. The target is at least 95% on test photos the model has never seen.

Feature Extraction and Fine-Tuning

ApproachDescription
Feature extractionIt is used to freeze all pretrained layers and train only a new last layer on their output
Fine-tuningIt is used to also update some or all of the pretrained layers, with a small learning rate
Training from scratchEvery weight starts random; needs far more data and time
The headThe new last layer that replaces the old 1,000-class output with your own classes

The Data: Photos of School Notices

Navika's school posts five kinds of notice: exam timetables, lunch menus, letters to parents, permission slips and event posters. Navika wants an app that sorts photos of them automatically.

This program draws practice photos of the five kinds, made to look like phone photos: each page is placed on a desk at an angle, with uneven lighting and a little blur. Generating them means the lesson runs anywhere without a download, and the same seed gives the same photos every time. For a real app you would collect and label real photos instead. You don't need to follow every drawing command; save the program as make_notices.py and run it once.

Python
# make_notices.py: draws practice "phone photos" of five kinds of school notice
import random
from pathlib import Path
from PIL import Image, ImageDraw, ImageFilter, ImageFont
 
CATEGORIES = ["timetable", "menu", "letter", "form", "poster"]
WORDS = "school exam math science room grade class fee due date parent student club field trip bus lunch library".split()
 
def font(size):
    return ImageFont.load_default(size=size)
 
def words(rng, n):
    return " ".join(rng.choice(WORDS) for _ in range(n)).capitalize()
 
def draw_notice(kind, rng):
    page = Image.new("RGB", (300, 400), "white")
    d = ImageDraw.Draw(page)
    ink = tuple(rng.randint(0, 70) for _ in range(3))
    if kind == "timetable":                            # a title and a grid of cells
        d.text((20, 15), "Exam Timetable", fill=ink, font=font(24))
        rows, cols = rng.randint(5, 9), rng.randint(3, 5)
        h, w = 320 // rows, 260 // cols
        for r in range(rows + 1):
            d.line((20, 60 + r * h, 20 + cols * w, 60 + r * h), fill=ink, width=2)
        for c in range(cols + 1):
            d.line((20 + c * w, 60, 20 + c * w, 60 + rows * h), fill=ink, width=2)
        for r in range(rows):
            for c in range(cols):
                d.text((25 + c * w, 65 + r * h), rng.choice(WORDS), fill=ink, font=font(12))
    elif kind == "letter":                             # paragraphs of running text
        d.text((20, 15), "Dear Parents,", fill=ink, font=font(18))
        y = 50
        while y < 280:
            for _ in range(rng.randint(3, 5)):
                d.text((20, y), words(rng, 6), fill=ink, font=font(13))
                y += 18
            y += 12
        d.text((20, y), "Principal", fill=ink, font=font(16))
        if rng.random() < 0.4:                         # some letters include a small table
            for r in range(4):
                d.line((150, 300 + r * 20, 280, 300 + r * 20), fill=ink, width=1)
    elif kind == "poster":                             # big colored shapes and a large title
        color = tuple(rng.randint(60, 255) for _ in range(3))
        d.rectangle((0, 0, 300, rng.randint(120, 220)), fill=color)
        for _ in range(rng.randint(2, 5)):
            x, y, r = rng.randint(0, 300), rng.randint(100, 380), rng.randint(15, 50)
            d.ellipse((x - r, y - r, x + r, y + r), fill=tuple(rng.randint(40, 255) for _ in range(3)))
        d.text((20, 40), rng.choice(["Science Fair", "Spring Concert", "Field Day", "Book Week"]),
               fill="white", font=font(34))
        d.text((20, 300), words(rng, 3), fill=ink, font=font(20))
    elif kind == "menu":                               # a colored band and a list with prices
        d.rectangle((0, 0, 300, 50), fill=tuple(rng.randint(60, 255) for _ in range(3)))
        d.text((20, 12), "Lunch Menu", fill=ink, font=font(24))
        y = 70
        while y < 370:
            d.text((20, y), words(rng, 2), fill=ink, font=font(13))
            d.text((230, y), f"${rng.randint(2, 6)}.{rng.choice(['00', '50', '75'])}", fill=ink, font=font(13))
            y += rng.randint(22, 32)
            d.line((20, y - 6, 280, y - 6), fill=ink, width=1)
    else:                                              # a form: labels, blank lines, check boxes
        d.text((20, 15), "Permission Slip", fill=ink, font=font(22))
        y = 60
        if rng.random() < 0.4:                         # some forms start with a paragraph
            for _ in range(4):
                d.text((20, y), words(rng, 6), fill=ink, font=font(13))
                y += 18
            y += 10
        for _ in range(rng.randint(4, 7)):
            d.text((20, y), rng.choice(WORDS).capitalize() + ":", fill=ink, font=font(14))
            d.line((110, y + 16, 280, y + 16), fill=ink, width=1)
            y += 38
        for i in range(rng.randint(2, 3)):
            d.rectangle((20, y + i * 25, 34, y + 14 + i * 25), outline=ink, width=2)
            d.text((42, y + i * 25), words(rng, 2), fill=ink, font=font(13))
    return page
 
def as_phone_photo(page, rng):
    """Put the page on a desk at a slight angle, with uneven light and a little blur."""
    desk = Image.new("RGB", (480, 480), tuple(rng.randint(90, 200) for _ in range(3)))
    scale = rng.uniform(0.55, 0.95)
    page = page.resize((int(300 * scale), int(400 * scale)))
    angle = rng.uniform(-20, 20)
    mask = Image.new("L", page.size, 255).rotate(angle, expand=True)
    page = page.rotate(angle, expand=True)
    desk.paste(page, (rng.randint(0, 480 - page.width), rng.randint(0, 480 - page.height)), mask)
    light = Image.linear_gradient("L").resize((480, 480)).rotate(rng.uniform(0, 360))
    shade = Image.new("RGB", desk.size, (30, 30, 30))
    desk = Image.composite(desk, shade, light.point(lambda v: 150 + v // 3))
    return desk.filter(ImageFilter.GaussianBlur(rng.uniform(0, 2.5))).resize((224, 224))
 
rng = random.Random(27)                               # the same photos every run
for split, count in [("train", 16), ("test", 20)]:
    for kind in CATEGORIES:
        folder = Path("notices") / split / kind
        folder.mkdir(parents=True, exist_ok=True)
        for i in range(count):
            as_phone_photo(draw_notice(kind, rng), rng).save(folder / f"{kind}_{i:02}.jpg", quality=85)
        print(f"{split:5} {kind:9} {count} photos")
 
Path("notices/new").mkdir(exist_ok=True)              # one more photo of each kind, for later
for kind in CATEGORIES:
    as_phone_photo(draw_notice(kind, rng), rng).save(f"notices/new/{kind}.jpg", quality=85)
Output
train timetable 16 photos
train menu      16 photos
train letter    16 photos
train form      16 photos
train poster    16 photos
test  timetable 20 photos
test  menu      20 photos
test  letter    20 photos
test  form      20 photos
test  poster    20 photos

Explanation: The program makes 80 training photos (16 of each kind) and 100 test photos (20 of each kind) in folders named after their category, such as notices/train/menu/. It also saves one extra photo of each kind in notices/new/ for the last example. Lunch menus are made to look a little like timetables, and some letters and forms share features, so the task is not trivial.

Example: Pretrained Features vs Starting from Scratch

This program compares two ways to learn from the 80 training photos: a small CNN that starts from random weights, and ResNet-18 with its pretrained layers frozen plus a new last layer.

Python
from pathlib import Path
 
import torch
from PIL import Image
from torch import nn
from transformers import AutoImageProcessor, AutoModel
 
CATEGORIES = ["timetable", "menu", "letter", "form", "poster"]
processor = AutoImageProcessor.from_pretrained("microsoft/resnet-18")
 
def load(split):
    paths = sorted(Path("notices", split).glob("*/*.jpg"))
    images = [Image.open(p).convert("RGB") for p in paths]
    labels = torch.tensor([CATEGORIES.index(p.parent.name) for p in paths])
    return processor(images=images, return_tensors="pt")["pixel_values"], labels
 
X_train, y_train = load("train")
X_test, y_test = load("test")
print("Training photos:", len(X_train), "| test photos:", len(X_test))
 
def fit(model, X, epochs, lr=0.001):
    optimizer = torch.optim.Adam([p for p in model.parameters() if p.requires_grad], lr=lr)
    for _ in range(epochs):
        for i in torch.randperm(len(X)).split(16):     # batches of 16
            optimizer.zero_grad()
            nn.functional.cross_entropy(model(X[i]), y_train[i]).backward()
            optimizer.step()
    return model.eval()
 
def accuracy(model, X):
    with torch.no_grad():
        return (model(X).argmax(dim=1) == y_test).float().mean().item()
 
# 1. A small CNN that starts from random weights and learns only from the training photos
torch.manual_seed(0)
scratch = nn.Sequential(
    nn.Conv2d(3, 16, 3, stride=2), nn.ReLU(), nn.MaxPool2d(2),
    nn.Conv2d(16, 32, 3, stride=2), nn.ReLU(), nn.MaxPool2d(2),
    nn.Flatten(), nn.LazyLinear(5),
)
scratch(X_train[:1])                                  # let LazyLinear work out its input size
fit(scratch, X_train, epochs=15)
print(f"CNN from scratch:             test accuracy {accuracy(scratch, X_test):.1%}")
 
# 2. Feature extraction: ResNet-18's pretrained layers stay frozen, a new last layer learns
backbone = AutoModel.from_pretrained("microsoft/resnet-18")
backbone.eval()
with torch.no_grad():
    f_train = backbone(X_train).pooler_output.flatten(1)   # 512 features per photo
    f_test = backbone(X_test).pooler_output.flatten(1)
print("Features per photo:", f_train.shape[1])
torch.manual_seed(0)
head = fit(nn.Linear(512, 5), f_train, epochs=15, lr=0.01)
print(f"Pretrained features + new head: test accuracy {accuracy(head, f_test):.1%}")
Output
Training photos: 80 | test photos: 100
CNN from scratch:             test accuracy 38.0%
Features per photo: 512
Pretrained features + new head: test accuracy 98.0%

Explanation:

  • The CNN from scratch reaches only 38.0% on the test photos, better than guessing (20% with five categories) but far from useful. Eighty photos are not enough to learn to see from nothing.
  • AutoModel loads ResNet-18 without its 1,000-class head. Its pooler_output is 512 numbers per photo that describe what the photo contains, like the embeddings in "What Are Embeddings" but for images.
  • A single Linear(512, 5) layer trained on those features reaches 98.0%. Nothing in ResNet-18 changed; the 512 features it learned from ImageNet photos were already enough to tell the notices apart.
  • The features are computed once with torch.no_grad(), so training the head takes only a moment.

Example: The Checkpoint

Fine-tuning goes one step further: it also updates the last part of ResNet-18, so its features adapt to notices.

Reuse what a big model already sees; train only what is new
Python
from pathlib import Path
 
import torch
from PIL import Image
from sklearn.metrics import confusion_matrix
from transformers import AutoImageProcessor, AutoModelForImageClassification
 
CATEGORIES = ["timetable", "menu", "letter", "form", "poster"]
processor = AutoImageProcessor.from_pretrained("microsoft/resnet-18")
 
def load(split):
    paths = sorted(Path("notices", split).glob("*/*.jpg"))
    images = [Image.open(p).convert("RGB") for p in paths]
    labels = torch.tensor([CATEGORIES.index(p.parent.name) for p in paths])
    return processor(images=images, return_tensors="pt")["pixel_values"], labels
 
X_train, y_train = load("train")
X_test, y_test = load("test")
 
torch.manual_seed(0)
model = AutoModelForImageClassification.from_pretrained(
    "microsoft/resnet-18",
    num_labels=len(CATEGORIES),                       # replace the 1,000-class layer with 5 classes
    id2label=dict(enumerate(CATEGORIES)),
    label2id={c: i for i, c in enumerate(CATEGORIES)},
    ignore_mismatched_sizes=True,
)
for name, p in model.named_parameters():              # freeze everything except the last stage and the head
    p.requires_grad = name.startswith(("resnet.encoder.stages.3", "classifier"))
trainable = sum(p.numel() for p in model.parameters() if p.requires_grad)
total = sum(p.numel() for p in model.parameters())
print(f"Training {trainable:,} of {total:,} parameters ({trainable / total:.0%})")
 
optimizer = torch.optim.Adam([p for p in model.parameters() if p.requires_grad], lr=0.0005)
 
def test_accuracy():
    model.eval()
    with torch.no_grad():
        return (model(pixel_values=X_test).logits.argmax(dim=1) == y_test).float().mean().item()
 
print(f"before fine-tuning: test {test_accuracy():.1%}")
for epoch in range(1, 6):
    model.train()
    for i in torch.randperm(len(X_train)).split(16):
        optimizer.zero_grad()
        loss = model(pixel_values=X_train[i], labels=y_train[i]).loss
        loss.backward()
        optimizer.step()
    print(f"epoch {epoch}: last batch loss {loss.item():.4f}  test {test_accuracy():.1%}")
 
with torch.no_grad():
    predicted = model(pixel_values=X_test).logits.argmax(dim=1)
print(confusion_matrix(y_test, predicted))
model.save_pretrained("notice-classifier")            # save the fine-tuned model in a folder
Output
Training 8,396,293 of 11,179,077 parameters (75%)
before fine-tuning: test 32.0%
epoch 1: last batch loss 0.2214  test 95.0%
epoch 2: last batch loss 0.0199  test 99.0%
epoch 3: last batch loss 0.0030  test 99.0%
epoch 4: last batch loss 0.0054  test 100.0%
epoch 5: last batch loss 0.0057  test 100.0%
[[20  0  0  0  0]
 [ 0 20  0  0  0]
 [ 0  0 20  0  0]
 [ 0  0  0 20  0]
 [ 0  0  0  0 20]]

Explanation:

  • num_labels=5 with ignore_mismatched_sizes=True replaces ResNet-18's 1,000-class head with a new, randomly started 5-class head. id2label stores the category names inside the model.
  • The loop over named_parameters() freezes the early stages, which find edges and textures that are useful for any photo, and trains only the last stage and the head. The last stage is ResNet-18's largest, so that is still 8.4 million of 11.2 million parameters (75%).
  • The learning rate is small (0.0005) so fine-tuning adjusts the pretrained weights instead of wiping them out. Passing labels makes the model compute the cross-entropy loss itself.
  • Before fine-tuning, the random head scores 32.0%. After one epoch the model reaches 95.0%, and from epoch 4 it sorts all 100 test photos correctly. The confusion matrix has 20 on each diagonal cell and no mistakes, so the checkpoint target of 95% is met.
  • save_pretrained() writes the fine-tuned model to the notice-classifier folder.

With torch.manual_seed(0) and the generated photos, the program gives the same numbers every run on the same machine and library versions; other setups may differ slightly.

Example: Using the Classifier

This program loads the saved model and sorts the five extra photos it has never seen, plus one photo that is not a notice at all: the dog from "Computer Vision".

Python
import torch
from PIL import Image
from transformers import AutoImageProcessor, AutoModelForImageClassification
 
processor = AutoImageProcessor.from_pretrained("microsoft/resnet-18")
model = AutoModelForImageClassification.from_pretrained("notice-classifier")   # the saved folder
model.eval()
 
files = [f"notices/new/{kind}.jpg" for kind in ["menu", "form", "poster", "letter", "timetable"]]
for path in files + ["dog.jpg"]:                      # new notices, plus something that is not a notice
    photo = Image.open(path)
    with torch.no_grad():
        probs = model(**processor(images=photo, return_tensors="pt")).logits.softmax(dim=1)[0]
    best = probs.argmax().item()
    print(f"{path.split('/')[-1]:14} -> {model.config.id2label[best]:9} ({probs[best]:.1%} sure)")
Output
menu.jpg       -> menu      (100.0% sure)
form.jpg       -> form      (99.7% sure)
poster.jpg     -> poster    (99.8% sure)
letter.jpg     -> letter    (100.0% sure)
timetable.jpg  -> timetable (100.0% sure)
dog.jpg        -> menu      (37.4% sure)

Explanation: from_pretrained("notice-classifier") loads the fine-tuned model from its folder, ready to use in an app. All five new notices are sorted correctly with 99.7% to 100% confidence. The dog photo is labeled menu, because a classifier must always choose one of its classes, but with only 37.4% confidence.

When to Use Transfer Learning

SituationApproach
Few labeled examples (tens to hundreds per class)Feature extraction, or fine-tune only the last stage
Thousands of examples, similar to everyday photosFine-tune more layers, with a small learning rate
Very different images (X-rays, satellite, microscope)Fine-tuning still helps, but more layers need to change
Millions of examples and a large budgetTraining from scratch becomes possible

The same idea drives large language models: a model pretrained on huge amounts of text is fine-tuned for a narrower job. See "RAG vs Fine-Tuning vs Long Context".

Common Mistakes

Using a large learning rate. It destroys the pretrained features in the first few steps. Start around 0.0001 to 0.001.

Forgetting the model's preprocessing. The pretrained layers expect images resized and scaled exactly as in their original training; use the model's processor.

Testing on photos the model trained on. Keep a separate test set, as in "Overfitting, Underfitting and Cross-Validation". Here the 100 test photos were never used for training.

Trusting results on easy practice data. These generated notices are cleaner than real phone photos. Expect lower accuracy on real photos, and test on them before using the model.

Interview Corner

What is transfer learning, and why does it work?

Reusing a model trained on a large dataset as the starting point for a new task. The early layers have learned general features like edges, textures and shapes that are useful for almost any images, so only the later layers need to learn the new task.

What is the difference between feature extraction and fine-tuning?

Feature extraction freezes the pretrained model and trains only a new head; fine-tuning also updates some or all pretrained layers with a small learning rate. Fine-tuning usually scores higher but needs more data and computation.

Practice

Exercise: fewer photos. Change make_notices.py to make only 4 training photos of each kind, then rerun the comparison and the checkpoint. How do the three approaches compare now?

Check your understanding:

  1. Why did the CNN from scratch reach only 38.0%?
  2. Which parameters did the checkpoint train, and which stayed frozen?
  3. Why was the dog photo labeled menu?

Quick check: transfer learning

4 questions
1What did the fine-tuned model score on the 100 test photos?
2What does feature extraction train?
3Why use a small learning rate for fine-tuning?
4What did the classifier say about the dog photo?

Key Takeaways

Quick reference

NeedCode
New head for your classesAutoModelForImageClassification.from_pretrained(name, num_labels=5, ignore_mismatched_sizes=True)
Pretrained features onlyAutoModel.from_pretrained(name)(pixels).pooler_output
Freeze a parameterp.requires_grad = False
Optimize only trainable weightsAdam([p for p in model.parameters() if p.requires_grad], lr=0.0005)
Loss from the modelmodel(pixel_values=x, labels=y).loss
Save and reloadmodel.save_pretrained("folder"), from_pretrained("folder")

Was this tutorial helpful?

Lesson 142 of 186