Implementation:Fastai Fastbook Cnn Learner
| Knowledge Sources | |
|---|---|
| Domains | Computer_Vision, Deep_Learning, Transfer_Learning |
| Last Updated | 2026-02-09 17:00 GMT |
Overview
Concrete tool for creating a transfer-learning Learner with a pretrained CNN backbone and custom classification head provided by fastai.vision.learner.cnn_learner (also available as vision_learner in newer fastai versions).
Description
The cnn_learner function combines three operations in a single call:
- Loads a pretrained architecture (e.g., ResNet34) from torchvision with ImageNet weights.
- Removes the original classification head and replaces it with a new head sized for the target number of categories (inferred from the DataLoaders vocabulary).
- Wraps everything into a Learner object that manages the training loop, loss function, optimizer, and metrics.
The resulting Learner has its body frozen by default, so initial training only updates the head weights.
Usage
Call cnn_learner after creating DataLoaders and before any training calls (lr_find, fine_tune, fit_one_cycle). Choose the architecture based on the complexity of your task: ResNet34 is the recommended default; use ResNet50 or larger for harder problems.
Code Reference
Source Location
- Repository: fastbook
- File: translations/cn/01_intro.md (line 291), translations/cn/05_pet_breeds.md (lines 628-830)
Signature
cnn_learner(
dls, # DataLoaders object
arch, # Model architecture (e.g., resnet34, resnet50)
metrics=None, # List of metrics to track (e.g., [accuracy, error_rate])
pretrained=True, # Whether to use pretrained ImageNet weights
loss_func=None, # Loss function (auto-detected from DataLoaders if None)
opt_func=Adam, # Optimizer function
lr=0.001, # Default learning rate
splitter=None, # Function to split model into parameter groups
cbs=None, # Additional callbacks
path=None, # Path for saving models
model_dir='models', # Directory name for saved models
wd=None, # Weight decay
wd_bn_bias=False, # Apply weight decay to batch norm and bias params
train_bn=True, # Train batch norm layers even when frozen
moms=(0.95, 0.85, 0.95), # Momentum range for one-cycle training
n_out=None # Number of output classes (auto-detected if None)
)
Import
from fastai.vision.all import cnn_learner, resnet34, resnet50, accuracy, error_rate
I/O Contract
Inputs
| Name | Type | Required | Description |
|---|---|---|---|
| dls | DataLoaders | Yes | DataLoaders object containing training and validation data streams |
| arch | callable | Yes | Torchvision model constructor (e.g., resnet34, resnet50, resnet18) |
| metrics | list | No | List of metric functions to compute after each epoch (e.g., [accuracy, error_rate]) |
| pretrained | bool | No | Use ImageNet pretrained weights (default: True) |
| loss_func | callable | No | Loss function; auto-detected as CrossEntropyLoss for single-label classification |
| n_out | int | No | Number of output classes; auto-detected from DataLoaders vocabulary if None |
Outputs
| Name | Type | Description |
|---|---|---|
| learn | Learner | A Learner object with pretrained body (frozen) and randomly initialized head, ready for training |
Usage Examples
Basic Usage: Cat vs Dog Classifier (Chapter 1)
from fastai.vision.all import *
path = untar_data(URLs.PETS) / 'images'
dls = ImageDataLoaders.from_name_func(
path, get_image_files(path),
valid_pct=0.2, seed=42,
label_func=lambda x: x[0].isupper(),
item_tfms=Resize(224)
)
learn = cnn_learner(dls, resnet34, metrics=error_rate)
Pet Breed Classifier (Chapter 5)
from fastai.vision.all import *
path = untar_data(URLs.PETS) / 'images'
pets = DataBlock(
blocks=(ImageBlock, CategoryBlock),
get_items=get_image_files,
splitter=RandomSplitter(valid_pct=0.2, seed=42),
get_y=using_attr(RegexLabeller(r'^(.+)_\d+.jpg$'), 'name'),
item_tfms=Resize(460),
batch_tfms=aug_transforms(size=224, min_scale=0.75)
)
dls = pets.dataloaders(path, bs=64)
learn = cnn_learner(dls, resnet34, metrics=[accuracy, error_rate])
# The learner is now ready for lr_find() or fine_tune()
print(f'Model architecture: {learn.arch.__name__}')
print(f'Number of classes: {learn.dls.c}')
print(f'Class names: {learn.dls.vocab}')
Using a Larger Architecture
from fastai.vision.all import *
# For more complex classification tasks, use ResNet50
learn = cnn_learner(dls, resnet50, metrics=[accuracy, error_rate])
# Inspect the model head
print(learn.model[-1]) # Shows the custom head layers
Related Pages
Implements Principle
Requires Environment
- Environment:Fastai_Fastbook_Python_FastAI_Environment
- Environment:Fastai_Fastbook_CUDA_GPU_Environment