Implementation:Fastai Fastbook Export Load Learner
| Knowledge Sources | |
|---|---|
| Domains | Deep_Learning, MLOps, Computer_Vision |
| Last Updated | 2026-02-09 17:00 GMT |
Overview
Concrete tools for serializing a trained model to disk and loading it for inference provided by Learner.export, load_learner, and Learner.predict from fastai.learner.
Description
Learner.export serializes the model architecture, trained weights, and the complete data pipeline (including all transforms and the vocabulary) into a single pickle file. load_learner deserializes that file into a fully functional Learner ready for inference. Learner.predict runs the full inference pipeline on a single item, returning the predicted class, its index, and the probability distribution over all classes.
Usage
Call learn.export() after training and interpretation are complete. Transfer the resulting pickle file to the production environment. In production, call load_learner(fname) once at startup, then call learn.predict(item) for each inference request.
Code Reference
Source Location
- Repository: fastbook
- File: translations/cn/02_production.md (lines 487-523)
Signature
# Export the Learner to a pickle file
Learner.export(
fname='export.pkl', # Output filename (saved in learn.path)
pickle_module=pickle, # Pickle module to use
pickle_protocol=2 # Pickle protocol version
)
# Load a previously exported Learner
load_learner(
fname, # Path to the .pkl file
cpu=True, # Load to CPU (default: True)
pickle_module=pickle # Pickle module to use
)
# Run inference on a single item
Learner.predict(
item, # A single input item (file path, PIL Image, or tensor)
rm_type_tfms=None, # Number of type transforms to remove
with_input=False # If True, also return the transformed input
)
Import
from fastai.vision.all import load_learner, Learner
from pathlib import Path
I/O Contract
Inputs
| Name | Type | Required | Description |
|---|---|---|---|
| fname (export) | str or Path | No | Filename for the exported pickle file (default: 'export.pkl') |
| fname (load) | str or Path | Yes | Path to the pickle file to load |
| cpu | bool | No | Whether to load model weights to CPU (default: True) |
| item | Path, str, PIL.Image, or Tensor | Yes | A single input for inference (image path, URL, PIL Image, or preprocessed tensor) |
Outputs
| Name | Type | Description |
|---|---|---|
| export file | .pkl file on disk | Serialized Learner containing architecture, weights, and data pipeline |
| loaded learner | Learner | Fully reconstructed Learner ready for inference |
| prediction | tuple | 3-tuple of (predicted_class: str, class_index: Tensor, probabilities: Tensor) |
Usage Examples
Basic Usage: Export After Training
from fastai.vision.all import *
# After training...
learn = cnn_learner(dls, resnet34, metrics=error_rate)
learn.fine_tune(4)
# Export the model
learn.export('bear_classifier.pkl')
print(f'Model exported to: {learn.path / "bear_classifier.pkl"}')
Loading and Running Inference
from fastai.vision.all import load_learner
from pathlib import Path
# Load the exported model (typically in a production script)
learn = load_learner(Path('bears') / 'bear_classifier.pkl')
# Run inference on a single image
pred_class, pred_idx, probs = learn.predict('test_grizzly.jpg')
print(f'Prediction: {pred_class}')
print(f'Class index: {pred_idx}')
print(f'Probabilities: {probs}')
# Example output:
# Prediction: grizzly
# Class index: tensor(1)
# Probabilities: tensor([0.0023, 0.9941, 0.0036])
# Access vocabulary to map indices to class names
print(f'Classes: {learn.dls.vocab}')
# Classes: ['black', 'grizzly', 'teddy']
Integration with a Web Application
from fastai.vision.all import load_learner, PILImage
# Load model once at application startup
learn = load_learner('export.pkl')
def classify_image(image_bytes):
"""Classify an uploaded image and return results."""
img = PILImage.create(image_bytes)
pred_class, pred_idx, probs = learn.predict(img)
# Build response with all class probabilities
results = {}
for i, cls_name in enumerate(learn.dls.vocab):
results[cls_name] = float(probs[i])
return {
'prediction': pred_class,
'confidence': float(probs[pred_idx]),
'all_probabilities': results
}
Checking Export Contents
from fastai.vision.all import load_learner
learn = load_learner('export.pkl')
# Inspect the loaded model
print(f'Architecture: {learn.arch.__name__}')
print(f'Number of classes: {learn.dls.c}')
print(f'Class vocabulary: {learn.dls.vocab}')
print(f'Item transforms: {learn.dls.after_item}')
print(f'Batch transforms: {learn.dls.after_batch}')