Learn practical skills, build real-world projects, and advance your career
Updated 4 years ago
!pip install fastai2 -q
Training an Image Classification model using FastAI v2
All it takes is 6 lines of code!
# Import the library
from fastai2.vision.all import *
# Download the dataset
path = untar_data(URLs.PETS)/'images'
# Function for determining labels of images
def is_cat(x): return x[0].isupper()
# Create data loaders
dls = ImageDataLoaders.from_name_func(
path, # working directory
get_image_files(path), # list of filenames
valid_pct=0.2, # validation set (20%)
seed=42, # fix random number generator
label_func=is_cat, # provide label_func
item_tfms=Resize(224)) # image size
# Create learner
learn = cnn_learner(dls, resnet34, metrics=error_rate)
# Fine tune the top layers
learn.fine_tune(1)
Downloading: "https://download.pytorch.org/models/resnet34-333f7ec4.pth" to /root/.cache/torch/checkpoints/resnet34-333f7ec4.pth
HBox(children=(FloatProgress(value=0.0, max=87306240.0), HTML(value='')))
Let's take a quick look into the files that were downloaded. You will notice that breeds of cats start with an uppercase letter e.g. Maine, Persian etc. and breeds of dogs start with lowercase e.g. boxer, beagle etc. This is why the labeling function label_func
checks the first character of the filename.
import os
os.listdir(path)[:10]
['beagle_115.jpg',
'boxer_18.jpg',
'Maine_Coon_157.jpg',
'scottish_terrier_28.jpg',
'english_setter_6.jpg',
'american_pit_bull_terrier_79.jpg',
'boxer_128.jpg',
'Persian_265.jpg',
'Maine_Coon_182.jpg',
'keeshond_89.jpg']