Safe lab preview
Classification of Oxford Pets using Transfer Learning
This is a sanitized, read-only preview. Nothing executes in this page.
Lab instructions
Classification of Oxford Pets using Transfer Learning
Use this guided lab to apply the lesson concepts.
Task
Imagine you need to develop an application for pet nursery to catalog all pets. One of the great features of such an application would be automatically discovering the breed from a photograph. In this assignment, we will use transfer learning to classify real-life pet images from Oxford-IIIT pets dataset.
The Dataset
We will use the original Oxford-IIIT pets dataset, which contains 35 different breeds of dogs and cats.
To download the dataset, use this code snippet:
Read-only
Notebook preview
Oxford Pets
# Generated pet images for deterministic, rights-safe execution.
from pathlib import Path
from PIL import Image
import numpy as np
image_root = Path("images")
image_root.mkdir(parents=True, exist_ok=True)
for breed_index, breed in enumerate(("Abyssinian", "Maine_Coon", "beagle", "pug")):
for image_index in range(1, 4):
yy, xx = np.mgrid[:64, :64]
pixels = np.zeros((64, 64, 3), dtype=np.uint8)
pixels[..., 0] = (xx * (2 + breed_index) + 23 * image_index) % 256
pixels[..., 1] = (yy * (3 + image_index) + 31 * breed_index) % 256
pixels[..., 2] = ((xx + yy) * 2 + 47 * breed_index) % 256
Image.fromarray(pixels).save(image_root / f"{breed}_{image_index}.jpg")
print("Prepared 12 generated pet images")import matplotlib.pyplot as plt
import os
from PIL import Image
import numpy as np
def display_images(images, titles=None, fontsize=12):
images = list(images)[:24]
if not images:
return
columns = min(len(images), 6)
rows = (len(images) + columns - 1) // columns
fig, axes = plt.subplots(rows, columns, squeeze=False, figsize=(columns * 2.5, rows * 2.5))
flat_axes = axes.reshape(-1)
for index, image in enumerate(images):
flat_axes[index].imshow(image)
flat_axes[index].axis("off")
if titles is not None and index < len(titles):
flat_axes[index].set_title(titles[index], fontsize=fontsize)
for axis in flat_axes[len(images):]:
axis.axis("off")
plt.tight_layout()
plt.show()fnames = os.listdir('images')[:5]
display_images([Image.open(os.path.join('images',x)) for x in fnames],titles=fnames,fontsize=30)for fn in os.listdir('images'):
cls = fn[:fn.rfind('_')].lower()
os.makedirs(os.path.join('images',cls),exist_ok=True)
os.replace(os.path.join('images',fn),os.path.join('images',cls,fn))num_classes = len(os.listdir('images'))
num_classes# PREPARE THE DATASET# SPLIT INTO TRAIN-TEST DATASETS# DEFINE DATA LOADERS if needed# [OPTIONAL] Plot the dataset# DEFINE NEURAL NETWORK ARCHITECTURE# TRAIN THE NEURAL NETWORK# PLOT THE RESULT: Train and Test Accuracy# LOAD THE DATASET
# Perform standard transformations for VGG-16/VGG-19 if needed# vgg = ...# BUILD MODEL for your problem with your own linear layers# MAKE VGG Layers not trainable# TRAIN THE MODEL# CALCULATE TOP-3 Accuracy of the modelOutputs, execution counts, widgets, and active content were removed during import. Run notebooks only in an external environment you trust.
Record your practice
Optional self-reporting helps you remember what you practiced and never gates course completion.