Spaces:
Sleeping
Sleeping
Damaris Adora commited on
Commit ·
a014e55
1
Parent(s): efd7519
First Commit”
Browse files- .gitignore +29 -0
- .python-version +1 -0
- README.md +45 -4
- app.py +82 -0
- data/.gitignore +3 -0
- docs/SETUP_LOG.md +110 -0
- notebooks/train.ipynb +773 -0
- pet_breed_model.pth +0 -0
- pyproject.toml +30 -0
- requirements.txt +5 -0
- src/__init__.py +1 -0
- src/dataset.py +130 -0
- src/model.py +105 -0
- src/utils.py +475 -0
- uv.lock +0 -0
.gitignore
ADDED
|
@@ -0,0 +1,29 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Python-generated files
|
| 2 |
+
__pycache__/
|
| 3 |
+
*.py[oc]
|
| 4 |
+
build/
|
| 5 |
+
dist/
|
| 6 |
+
wheels/
|
| 7 |
+
*.egg-info
|
| 8 |
+
|
| 9 |
+
# Virtual environments
|
| 10 |
+
.venv/
|
| 11 |
+
|
| 12 |
+
# Notebook artifacts
|
| 13 |
+
.ipynb_checkpoints/
|
| 14 |
+
|
| 15 |
+
# Dataset cache (downloaded by torchvision)
|
| 16 |
+
data/*
|
| 17 |
+
!data/.gitignore
|
| 18 |
+
|
| 19 |
+
# Training checkpoints (the final pet_breed_model.pth is tracked via Git LFS)
|
| 20 |
+
checkpoints/
|
| 21 |
+
*.ckpt
|
| 22 |
+
|
| 23 |
+
# Coursework references and project instruction files
|
| 24 |
+
previous_assignment_contents/
|
| 25 |
+
final_project_guidelines/
|
| 26 |
+
CLAUDE.md
|
| 27 |
+
|
| 28 |
+
# OS files
|
| 29 |
+
.DS_Store
|
.python-version
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
3.14
|
README.md
CHANGED
|
@@ -1,13 +1,54 @@
|
|
| 1 |
---
|
| 2 |
-
title: Pet Classifier
|
| 3 |
-
emoji: 🏢
|
| 4 |
colorFrom: green
|
| 5 |
colorTo: yellow
|
| 6 |
sdk: gradio
|
| 7 |
sdk_version: 6.30.0
|
| 8 |
-
python_version: '3.
|
| 9 |
app_file: app.py
|
| 10 |
pinned: false
|
| 11 |
---
|
| 12 |
|
| 13 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
---
|
| 2 |
+
title: Pet Breed Classifier
|
|
|
|
| 3 |
colorFrom: green
|
| 4 |
colorTo: yellow
|
| 5 |
sdk: gradio
|
| 6 |
sdk_version: 6.30.0
|
| 7 |
+
python_version: '3.14'
|
| 8 |
app_file: app.py
|
| 9 |
pinned: false
|
| 10 |
---
|
| 11 |
|
| 12 |
+
# Pet Breed Classifier
|
| 13 |
+
|
| 14 |
+
An image classification web application that identifies the breed of a pet from a photograph and reports whether the animal is a cat or a dog.
|
| 15 |
+
|
| 16 |
+
## Problem Statement
|
| 17 |
+
|
| 18 |
+
- **Task type:** Multi-class image classification.
|
| 19 |
+
- **Dataset:** Oxford-IIIT Pet (`torchvision.datasets.OxfordIIITPet`).
|
| 20 |
+
- **Input:** An RGB photograph of a cat or dog, resized and normalized to a fixed tensor size.
|
| 21 |
+
- **Output:** A predicted breed from 37 classes (25 dog breeds and 12 cat breeds), plus the species derived from the predicted breed.
|
| 22 |
+
- **Core challenge:** Breeds within a species are visually similar, and the dataset provides roughly 100 images per class with variation in pose, lighting, and background.
|
| 23 |
+
|
| 24 |
+
## Application Outputs
|
| 25 |
+
|
| 26 |
+
- Top three predicted breeds with confidence scores.
|
| 27 |
+
- Detected species (cat or dog).
|
| 28 |
+
- Single-image inference latency in seconds.
|
| 29 |
+
|
| 30 |
+
## Repository Structure
|
| 31 |
+
|
| 32 |
+
```text
|
| 33 |
+
app.py Gradio application entry point
|
| 34 |
+
pet_breed_model.pth Trained model weights (state_dict)
|
| 35 |
+
requirements.txt Runtime dependencies for deployment
|
| 36 |
+
src/model.py Model architecture
|
| 37 |
+
src/dataset.py Transforms, splits, and DataLoaders
|
| 38 |
+
src/utils.py Species mapping, timed inference, and metrics helpers
|
| 39 |
+
notebooks/train.ipynb Training and evaluation workflow
|
| 40 |
+
docs/SETUP_LOG.md Setup decisions, troubleshooting notes, and remaining steps
|
| 41 |
+
```
|
| 42 |
+
|
| 43 |
+
## Local Setup
|
| 44 |
+
|
| 45 |
+
The project uses Python 3.14 and [uv](https://docs.astral.sh/uv/).
|
| 46 |
+
|
| 47 |
+
```bash
|
| 48 |
+
uv sync
|
| 49 |
+
uv run python app.py
|
| 50 |
+
```
|
| 51 |
+
|
| 52 |
+
## Training
|
| 53 |
+
|
| 54 |
+
Training is performed in `notebooks/train.ipynb` on a Google Colab NVIDIA T4 GPU. The resulting weights are saved to `pet_breed_model.pth` and loaded by `app.py` for CPU inference.
|
app.py
ADDED
|
@@ -0,0 +1,82 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Gradio application for the Oxford-IIIT Pet breed and species classifier.
|
| 2 |
+
|
| 3 |
+
This script is independent of the training workflow. It rebuilds the deployed
|
| 4 |
+
architecture (ResNet18 with a 37-class head), loads the fine-tuned weights from
|
| 5 |
+
``pet_breed_model.pth``, and serves single-image predictions with latency.
|
| 6 |
+
"""
|
| 7 |
+
|
| 8 |
+
from __future__ import annotations
|
| 9 |
+
|
| 10 |
+
import os
|
| 11 |
+
from pathlib import Path
|
| 12 |
+
|
| 13 |
+
import gradio as gr
|
| 14 |
+
import torch
|
| 15 |
+
from PIL import Image
|
| 16 |
+
|
| 17 |
+
from src.dataset import build_eval_transform
|
| 18 |
+
from src.model import NUM_CLASSES, build_resnet18_classifier
|
| 19 |
+
from src.utils import CLASS_NAMES, format_breed_name, predict_image
|
| 20 |
+
|
| 21 |
+
DEVICE = "cuda" if torch.cuda.is_available() else "cpu"
|
| 22 |
+
MODEL_PATH = Path(os.environ.get("PET_MODEL_PATH", Path(__file__).parent / "pet_breed_model.pth"))
|
| 23 |
+
EVAL_TRANSFORM = build_eval_transform()
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
def load_deployed_model(weights_path: Path, device: str) -> torch.nn.Module:
|
| 27 |
+
"""Build the ResNet18 classifier and load the saved state_dict in evaluation mode."""
|
| 28 |
+
if not weights_path.is_file() or weights_path.stat().st_size == 0:
|
| 29 |
+
raise FileNotFoundError(
|
| 30 |
+
f"Model weights not found or empty at '{weights_path}'. "
|
| 31 |
+
"Train the model with notebooks/train.ipynb and save pet_breed_model.pth."
|
| 32 |
+
)
|
| 33 |
+
network = build_resnet18_classifier(num_classes=NUM_CLASSES, pretrained=False)
|
| 34 |
+
state_dict = torch.load(weights_path, map_location=device)
|
| 35 |
+
network.load_state_dict(state_dict)
|
| 36 |
+
network.to(device)
|
| 37 |
+
network.eval()
|
| 38 |
+
return network
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
DEPLOYED_MODEL = load_deployed_model(MODEL_PATH, DEVICE)
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
def classify_pet(image: Image.Image | None) -> tuple[dict[str, float], str, float]:
|
| 45 |
+
"""Predict breed probabilities, species, and inference latency for one image."""
|
| 46 |
+
if image is None:
|
| 47 |
+
raise gr.Error("Please upload a pet photo before running the classifier.")
|
| 48 |
+
|
| 49 |
+
result = predict_image(
|
| 50 |
+
DEPLOYED_MODEL,
|
| 51 |
+
image,
|
| 52 |
+
device=DEVICE,
|
| 53 |
+
transform=EVAL_TRANSFORM,
|
| 54 |
+
class_names=CLASS_NAMES,
|
| 55 |
+
top_k=3,
|
| 56 |
+
)
|
| 57 |
+
breed_probabilities = {
|
| 58 |
+
format_breed_name(breed): probability
|
| 59 |
+
for breed, probability in result["probabilities"].items()
|
| 60 |
+
}
|
| 61 |
+
return breed_probabilities, result["species"], round(result["inference_seconds"], 6)
|
| 62 |
+
|
| 63 |
+
|
| 64 |
+
demo = gr.Interface(
|
| 65 |
+
fn=classify_pet,
|
| 66 |
+
inputs=gr.Image(type="pil", label="Upload Pet Photo"),
|
| 67 |
+
outputs=[
|
| 68 |
+
gr.Label(num_top_classes=3, label="Top Predicted Breeds"),
|
| 69 |
+
gr.Textbox(label="Detected Species (Cat vs. Dog)"),
|
| 70 |
+
gr.Number(label="Inference Latency (seconds)"),
|
| 71 |
+
],
|
| 72 |
+
title="Pet Breed Classifier",
|
| 73 |
+
description=(
|
| 74 |
+
"Upload a photograph of a cat or dog. The model predicts the breed among the "
|
| 75 |
+
"37 Oxford-IIIT Pet categories, infers the species from the predicted breed, "
|
| 76 |
+
"and reports the forward-pass latency for the single image."
|
| 77 |
+
),
|
| 78 |
+
flagging_mode="never",
|
| 79 |
+
)
|
| 80 |
+
|
| 81 |
+
if __name__ == "__main__":
|
| 82 |
+
demo.launch()
|
data/.gitignore
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Ignore downloaded torchvision archives and extracted images
|
| 2 |
+
*
|
| 3 |
+
!.gitignore
|
docs/SETUP_LOG.md
ADDED
|
@@ -0,0 +1,110 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Project Setup and Troubleshooting Log
|
| 2 |
+
|
| 3 |
+
Record of the setup work, design decisions, problems encountered, and remaining steps for the Oxford-IIIT Pet breed and species classifier. Last updated October 17, 2026.
|
| 4 |
+
|
| 5 |
+
## 1. Design Decisions
|
| 6 |
+
|
| 7 |
+
| Decision | Choice | Rationale |
|
| 8 |
+
|---|---|---|
|
| 9 |
+
| Models | Scratch CNN (`PetBreedCNN`) plus pretrained ResNet18 baseline | Both satisfy the rubric (at least 2 layers). Training both allows a direct, documented comparison. |
|
| 10 |
+
| Deployed model | ResNet18 (pretrained, fine-tuned) | Expected to generalize better from roughly 100 images per breed. The notebook checks this against validation results before export. |
|
| 11 |
+
| Python version | 3.14 | Project preference. Local `.venv` runs 3.14.0. Colab runs 3.13, and the code is compatible with both. |
|
| 12 |
+
| Packaging | Application project, no build backend (`package = false`) | The code lives in `src/` and is imported directly. It is not a distributable package. |
|
| 13 |
+
| Model selection | Validation metrics, never the test set | Keeps the test set an unbiased estimate of generalization. |
|
| 14 |
+
| ResNet18 learning rates | 0.001 for the new head, 0.0001 for the pretrained backbone | A rate of 0.001 on the backbone risks damaging pretrained features. The head still starts at the specified 0.001. |
|
| 15 |
+
| Latency definition | Forward pass plus softmax, per `CLAUDE.md` | Preprocessing time is returned separately by `predict_image`. |
|
| 16 |
+
|
| 17 |
+
## 2. Repository Fixes
|
| 18 |
+
|
| 19 |
+
1. **Python version.** `.python-version` and `pyproject.toml` use 3.14. The README Space metadata sets `python_version: '3.14'`.
|
| 20 |
+
2. **Packaging.** Removed the `uv_build` backend and the broken `pet_classifier:main` script entry from `pyproject.toml`. Listed the real dependencies. Replaced the `src/__init__.py` stub with a docstring-only package marker.
|
| 21 |
+
3. **`.gitignore`.**
|
| 22 |
+
- Stopped ignoring `pyproject.toml` and `.python-version`.
|
| 23 |
+
- Added `data/`, `checkpoints/`, `*.ckpt`, `.ipynb_checkpoints/`, and `.DS_Store`.
|
| 24 |
+
- Corrected the `claude.markdown` entry to `CLAUDE.md`.
|
| 25 |
+
- Added `data/.gitignore`.
|
| 26 |
+
4. **README.** Removed the emoji and rewrote it as project documentation. The Hugging Face Space YAML header is preserved.
|
| 27 |
+
|
| 28 |
+
## 3. Files Created
|
| 29 |
+
|
| 30 |
+
| File | Purpose |
|
| 31 |
+
|---|---|
|
| 32 |
+
| `src/model.py` | `PetBreedCNN` (four double-convolution blocks, adaptive pooling, Linear and Dropout head) and `build_resnet18_classifier` |
|
| 33 |
+
| `src/dataset.py` | Transforms, stratified 80/20 train/validation split of `trainval`, and DataLoaders (batch size 32, 2 workers) |
|
| 34 |
+
| `src/utils.py` | Class names, `CAT_BREEDS`, species mapping, timed `predict_image`, training loop with `ReduceLROnPlateau` and early stopping, metrics, and plots |
|
| 35 |
+
| `notebooks/train.ipynb` | Full training and evaluation workflow for Colab, including design justification |
|
| 36 |
+
| `app.py` | Gradio interface that loads `pet_breed_model.pth` (ResNet18) |
|
| 37 |
+
| `requirements.txt` | Pinned production dependencies: `torch`, `torchvision`, `gradio`, `Pillow`, `numpy` |
|
| 38 |
+
|
| 39 |
+
## 4. Verification Performed
|
| 40 |
+
|
| 41 |
+
- Imported `torch`, `torchvision`, `gradio`, `Pillow`, and `numpy` successfully on Python 3.14.
|
| 42 |
+
- Confirmed the 37 class names and label order against the downloaded `torchvision.datasets.OxfordIIITPet`.
|
| 43 |
+
- Confirmed that the static `CAT_BREEDS` mapping agrees with the dataset's own cat/dog annotation for all 37 breeds (12 cat, 25 dog).
|
| 44 |
+
- Ran synthetic tests of model output shapes, the stratified split, the training loop with early stopping, metrics, plots, and timed inference, including RGBA image input.
|
| 45 |
+
- Ran `app.py` with temporary random weights. It returns the top-3 breeds, species, and latency, handles an empty upload with a clear message, and reports a clear error when the weights file is empty.
|
| 46 |
+
- Ran the entire notebook end to end with `PET_QUICK_RUN=1` (tiny subset, 1 epoch per model). The reloaded weights reproduced the trained network's outputs. Accuracy values from that run are not meaningful.
|
| 47 |
+
|
| 48 |
+
## 5. Problems Encountered and Solutions
|
| 49 |
+
|
| 50 |
+
### 5.1 SSL certificate error when downloading the dataset (macOS)
|
| 51 |
+
|
| 52 |
+
- **Symptom:** `CERTIFICATE_VERIFY_FAILED: unable to get local issuer certificate` from `OxfordIIITPet(download=True)`.
|
| 53 |
+
- **Cause:** The python.org build of Python on macOS does not ship with a certificate bundle.
|
| 54 |
+
- **Fix:** Run the "Install Certificates.command" script that comes with that Python installation. As a one-off alternative, set `SSL_CERT_FILE` to the `certifi` bundle:
|
| 55 |
+
```bash
|
| 56 |
+
SSL_CERT_FILE="$(.venv/bin/python -c 'import certifi; print(certifi.where())')" <command>
|
| 57 |
+
```
|
| 58 |
+
|
| 59 |
+
### 5.2 Notebook error in Colab: `No module named 'src'`
|
| 60 |
+
|
| 61 |
+
- **Symptom:** `ModuleNotFoundError: No module named 'src'` in the imports cell.
|
| 62 |
+
- **Cause:** The setup cell clones the Hugging Face Space repository to obtain `src/`, but `src/` had not been pushed to the Space yet.
|
| 63 |
+
- **Fix:** Push `src/` and the notebook to the Space, or upload a zip of `src/` to `/content/pet_classifier/` in Colab and unzip it.
|
| 64 |
+
- **Notebook change:** The setup cell now stops with a clear message if `src/model.py` is missing.
|
| 65 |
+
|
| 66 |
+
### 5.3 Notebook error in Colab: `git clone` exit status 128
|
| 67 |
+
|
| 68 |
+
- **Symptom:** `CalledProcessError` from `git clone` on re-running the setup cell.
|
| 69 |
+
- **Cause:** The first run created `/content/pet_classifier` without `src/`. Each re-run saw no `src/` and attempted to clone again. Git refuses to clone into an existing non-empty folder.
|
| 70 |
+
- **Fix:** The setup cell now runs `git pull` when the folder is already a clone and clones only on the first run.
|
| 71 |
+
|
| 72 |
+
### 5.4 `git add .` fails: `git-lfs: command not found`
|
| 73 |
+
|
| 74 |
+
- **Symptom:**
|
| 75 |
+
```text
|
| 76 |
+
git-lfs filter-process: git-lfs: command not found
|
| 77 |
+
fatal: the remote end hung up unexpectedly
|
| 78 |
+
```
|
| 79 |
+
- **Cause:** `.gitattributes` routes `*.pth` (and other model file types) through Git LFS, and `git-lfs` was not installed locally. Hugging Face also requires LFS for files over 10 MB.
|
| 80 |
+
- **Fix:** `git-lfs` is a standalone program, not a Python package, so `uv` cannot install it. Use Homebrew:
|
| 81 |
+
```bash
|
| 82 |
+
brew install git-lfs
|
| 83 |
+
git lfs install
|
| 84 |
+
git lfs version
|
| 85 |
+
```
|
| 86 |
+
|
| 87 |
+
## 6. Remaining Steps
|
| 88 |
+
|
| 89 |
+
1. Install Git LFS (section 5.4).
|
| 90 |
+
2. Push the code to the Space, leaving out the empty placeholder `pet_breed_model.pth`:
|
| 91 |
+
```bash
|
| 92 |
+
git add .gitignore .python-version pyproject.toml uv.lock README.md requirements.txt app.py src notebooks docs
|
| 93 |
+
git commit -m "Add model, data pipeline, training notebook, and Gradio app"
|
| 94 |
+
git push origin main
|
| 95 |
+
```
|
| 96 |
+
Hugging Face prompts for a username and a write access token (create one at huggingface.co/settings/tokens). The Space shows a startup error until the trained weights are added. This is expected.
|
| 97 |
+
3. Open `notebooks/train.ipynb` in Google Colab with a T4 GPU runtime and run all cells. The notebook downloads `pet_breed_model.pth` at the end.
|
| 98 |
+
4. Place `pet_breed_model.pth` in the repository root, then add and push it:
|
| 99 |
+
```bash
|
| 100 |
+
git add pet_breed_model.pth
|
| 101 |
+
git commit -m "Add trained ResNet18 weights"
|
| 102 |
+
git push origin main
|
| 103 |
+
```
|
| 104 |
+
5. Confirm the Space builds and test it with several pet photos.
|
| 105 |
+
6. Record the final test metrics, confusion-matrix findings, and latency figures from the notebook for the course write-up.
|
| 106 |
+
|
| 107 |
+
## 7. Open Items
|
| 108 |
+
|
| 109 |
+
- The Space metadata sets `python_version: '3.14'`. It has not been confirmed that Hugging Face Spaces accepts 3.14. If the Space build fails on the Python version, change it in the README header.
|
| 110 |
+
- Final accuracy, the cat-versus-dog result, and the scratch-versus-pretrained comparison are not yet known. They come from running the notebook on Colab.
|
notebooks/train.ipynb
ADDED
|
@@ -0,0 +1,773 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"cells": [
|
| 3 |
+
{
|
| 4 |
+
"cell_type": "markdown",
|
| 5 |
+
"id": "0965d864",
|
| 6 |
+
"metadata": {},
|
| 7 |
+
"source": [
|
| 8 |
+
"# Oxford-IIIT Pet Breed and Species Classification\n",
|
| 9 |
+
"\n",
|
| 10 |
+
"**Objective.** Develop, train, and evaluate an end-to-end image classification pipeline in PyTorch, then export the best model for deployment in a Gradio application on Hugging Face Spaces.\n",
|
| 11 |
+
"\n",
|
| 12 |
+
"**Project type.** Classifier (multi-class image classification), not a regressor.\n",
|
| 13 |
+
"\n",
|
| 14 |
+
"**Dataset.** `torchvision.datasets.OxfordIIITPet`: 7,349 labelled photographs of cats and dogs across 37 breeds (25 dog breeds and 12 cat breeds), with roughly 100 images per breed.\n",
|
| 15 |
+
"\n",
|
| 16 |
+
"**Problem statement.**\n",
|
| 17 |
+
"\n",
|
| 18 |
+
"| Element | Definition |\n",
|
| 19 |
+
"|---|---|\n",
|
| 20 |
+
"| Input | An RGB photograph of a single pet, resized to 224 x 224 and normalized with ImageNet statistics |\n",
|
| 21 |
+
"| Output | A predicted breed (37 classes) and a species (Cat or Dog) derived from the predicted breed |\n",
|
| 22 |
+
"| Core challenge | Fine-grained discrimination between visually similar breeds from a small number of images per class, with variation in pose, lighting, scale, and background |\n",
|
| 23 |
+
"\n",
|
| 24 |
+
"**Experimental design.** Two models are trained under an identical data pipeline and training protocol so that they can be compared directly:\n",
|
| 25 |
+
"\n",
|
| 26 |
+
"1. `PetBreedCNN`, a convolutional network trained from scratch.\n",
|
| 27 |
+
"2. `ResNet18 (pretrained)`, an ImageNet-pretrained network fine-tuned for the 37 breeds (transfer-learning baseline).\n",
|
| 28 |
+
"\n",
|
| 29 |
+
"The better-performing model on validation data is the one exported to `pet_breed_model.pth` for deployment. The test partition is used only for the final, unbiased evaluation."
|
| 30 |
+
]
|
| 31 |
+
},
|
| 32 |
+
{
|
| 33 |
+
"cell_type": "markdown",
|
| 34 |
+
"id": "1d3dd182",
|
| 35 |
+
"metadata": {},
|
| 36 |
+
"source": [
|
| 37 |
+
"## 1. Environment Setup\n",
|
| 38 |
+
"\n",
|
| 39 |
+
"When run in Google Colab, the notebook clones the project repository so that the shared modules in `src/` are available. Select a GPU runtime (Runtime > Change runtime type > T4 GPU) before running. Commit and push `src/` to the repository first, or upload the `src/` folder to `/content/pet_classifier/` manually."
|
| 40 |
+
]
|
| 41 |
+
},
|
| 42 |
+
{
|
| 43 |
+
"cell_type": "code",
|
| 44 |
+
"execution_count": 4,
|
| 45 |
+
"id": "46da8978",
|
| 46 |
+
"metadata": {},
|
| 47 |
+
"outputs": [
|
| 48 |
+
{
|
| 49 |
+
"ename": "FileNotFoundError",
|
| 50 |
+
"evalue": "The shared modules in src/ were not found in /content/pet_classifier. Push src/ to the repository and re-run this cell, or upload the src folder to this directory.",
|
| 51 |
+
"output_type": "error",
|
| 52 |
+
"traceback": [
|
| 53 |
+
"\u001b[0;31m---------------------------------------------------------------------------\u001b[0m",
|
| 54 |
+
"\u001b[0;31mFileNotFoundError\u001b[0m Traceback (most recent call last)",
|
| 55 |
+
"\u001b[0;32m/tmp/ipykernel_1661/939368842.py\u001b[0m in \u001b[0;36m<cell line: 0>\u001b[0;34m()\u001b[0m\n\u001b[1;32m 26\u001b[0m \u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 27\u001b[0m \u001b[0;32mif\u001b[0m \u001b[0;32mnot\u001b[0m \u001b[0mPath\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m\"src/model.py\"\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mexists\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m---> 28\u001b[0;31m raise FileNotFoundError(\n\u001b[0m\u001b[1;32m 29\u001b[0m \u001b[0;34mf\"The shared modules in src/ were not found in {Path.cwd()}. \"\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 30\u001b[0m \u001b[0;34m\"Push src/ to the repository and re-run this cell, or upload the src folder to this directory.\"\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n",
|
| 56 |
+
"\u001b[0;31mFileNotFoundError\u001b[0m: The shared modules in src/ were not found in /content/pet_classifier. Push src/ to the repository and re-run this cell, or upload the src folder to this directory."
|
| 57 |
+
]
|
| 58 |
+
}
|
| 59 |
+
],
|
| 60 |
+
"source": [
|
| 61 |
+
"import os\n",
|
| 62 |
+
"import subprocess\n",
|
| 63 |
+
"import sys\n",
|
| 64 |
+
"from pathlib import Path\n",
|
| 65 |
+
"\n",
|
| 66 |
+
"REPO_URL = \"https://huggingface.co/spaces/deeAdora/pet_classifier\"\n",
|
| 67 |
+
"IN_COLAB = \"google.colab\" in sys.modules\n",
|
| 68 |
+
"\n",
|
| 69 |
+
"if IN_COLAB:\n",
|
| 70 |
+
" clone_directory = Path(\"/content/pet_classifier\")\n",
|
| 71 |
+
" git_environment = {**os.environ, \"GIT_LFS_SKIP_SMUDGE\": \"1\"}\n",
|
| 72 |
+
" if (clone_directory / \".git\").exists():\n",
|
| 73 |
+
" # A previous run already cloned the repository; update it instead of cloning again.\n",
|
| 74 |
+
" subprocess.run([\"git\", \"-C\", str(clone_directory), \"pull\"], check=False, env=git_environment)\n",
|
| 75 |
+
" else:\n",
|
| 76 |
+
" clone_directory.mkdir(parents=True, exist_ok=True)\n",
|
| 77 |
+
" subprocess.run(\n",
|
| 78 |
+
" [\"git\", \"clone\", REPO_URL, \".\"],\n",
|
| 79 |
+
" cwd=clone_directory,\n",
|
| 80 |
+
" check=True,\n",
|
| 81 |
+
" env=git_environment,\n",
|
| 82 |
+
" )\n",
|
| 83 |
+
" os.chdir(clone_directory)\n",
|
| 84 |
+
"elif Path.cwd().name == \"notebooks\":\n",
|
| 85 |
+
" os.chdir(Path.cwd().parent)\n",
|
| 86 |
+
"\n",
|
| 87 |
+
"if not Path(\"src/model.py\").exists():\n",
|
| 88 |
+
" raise FileNotFoundError(\n",
|
| 89 |
+
" f\"The shared modules in src/ were not found in {Path.cwd()}. \"\n",
|
| 90 |
+
" \"Push src/ to the repository and re-run this cell, or upload the src folder to this directory.\"\n",
|
| 91 |
+
" )\n",
|
| 92 |
+
"\n",
|
| 93 |
+
"sys.path.insert(0, str(Path.cwd()))\n",
|
| 94 |
+
"print(\"Working directory:\", Path.cwd())"
|
| 95 |
+
]
|
| 96 |
+
},
|
| 97 |
+
{
|
| 98 |
+
"cell_type": "code",
|
| 99 |
+
"execution_count": 2,
|
| 100 |
+
"id": "42519f9a",
|
| 101 |
+
"metadata": {},
|
| 102 |
+
"outputs": [
|
| 103 |
+
{
|
| 104 |
+
"ename": "ModuleNotFoundError",
|
| 105 |
+
"evalue": "No module named 'src'",
|
| 106 |
+
"output_type": "error",
|
| 107 |
+
"traceback": [
|
| 108 |
+
"\u001b[0;31m---------------------------------------------------------------------------\u001b[0m",
|
| 109 |
+
"\u001b[0;31mModuleNotFoundError\u001b[0m Traceback (most recent call last)",
|
| 110 |
+
"\u001b[0;32m/tmp/ipykernel_1661/1012654778.py\u001b[0m in \u001b[0;36m<cell line: 0>\u001b[0;34m()\u001b[0m\n\u001b[1;32m 11\u001b[0m \u001b[0;32mfrom\u001b[0m \u001b[0mtorchvision\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mdatasets\u001b[0m \u001b[0;32mimport\u001b[0m \u001b[0mOxfordIIITPet\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 12\u001b[0m \u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m---> 13\u001b[0;31m \u001b[0;32mfrom\u001b[0m \u001b[0msrc\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mdataset\u001b[0m \u001b[0;32mimport\u001b[0m \u001b[0mbuild_dataloaders\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mbuild_datasets\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mstratified_split_indices\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m\u001b[1;32m 14\u001b[0m \u001b[0;32mfrom\u001b[0m \u001b[0msrc\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mmodel\u001b[0m \u001b[0;32mimport\u001b[0m \u001b[0mNUM_CLASSES\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mPetBreedCNN\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mbuild_resnet18_classifier\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mcount_parameters\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 15\u001b[0m from src.utils import (\n",
|
| 111 |
+
"\u001b[0;31mModuleNotFoundError\u001b[0m: No module named 'src'",
|
| 112 |
+
"",
|
| 113 |
+
"\u001b[0;31m---------------------------------------------------------------------------\u001b[0;32m\nNOTE: If your import is failing due to a missing package, you can\nmanually install dependencies using either !pip or !apt.\n\nTo view examples of installing some common dependencies, click the\n\"Open Examples\" button below.\n\u001b[0;31m---------------------------------------------------------------------------\u001b[0m\n"
|
| 114 |
+
]
|
| 115 |
+
}
|
| 116 |
+
],
|
| 117 |
+
"source": [
|
| 118 |
+
"import copy\n",
|
| 119 |
+
"import time\n",
|
| 120 |
+
"\n",
|
| 121 |
+
"import matplotlib.pyplot as plt\n",
|
| 122 |
+
"import numpy as np\n",
|
| 123 |
+
"import pandas as pd\n",
|
| 124 |
+
"import torch\n",
|
| 125 |
+
"from IPython.display import display\n",
|
| 126 |
+
"from torch import nn, optim\n",
|
| 127 |
+
"from torch.utils.data import Subset\n",
|
| 128 |
+
"from torchvision.datasets import OxfordIIITPet\n",
|
| 129 |
+
"\n",
|
| 130 |
+
"from src.dataset import build_dataloaders, build_datasets, stratified_split_indices\n",
|
| 131 |
+
"from src.model import NUM_CLASSES, PetBreedCNN, build_resnet18_classifier, count_parameters\n",
|
| 132 |
+
"from src.utils import (\n",
|
| 133 |
+
" CLASS_NAMES,\n",
|
| 134 |
+
" benchmark_latency,\n",
|
| 135 |
+
" compute_classification_metrics,\n",
|
| 136 |
+
" evaluate_loader,\n",
|
| 137 |
+
" fit_model,\n",
|
| 138 |
+
" format_breed_name,\n",
|
| 139 |
+
" get_species,\n",
|
| 140 |
+
" plot_confusion_matrix,\n",
|
| 141 |
+
" plot_training_curves,\n",
|
| 142 |
+
" predict_image,\n",
|
| 143 |
+
" set_seed,\n",
|
| 144 |
+
" top_confusions,\n",
|
| 145 |
+
")\n",
|
| 146 |
+
"\n",
|
| 147 |
+
"# Set PET_QUICK_RUN=1 to execute the full notebook on a tiny subset for verification.\n",
|
| 148 |
+
"QUICK_RUN = os.environ.get(\"PET_QUICK_RUN\") == \"1\"\n",
|
| 149 |
+
"\n",
|
| 150 |
+
"CONFIG = {\n",
|
| 151 |
+
" \"seed\": 42,\n",
|
| 152 |
+
" \"image_size\": 224,\n",
|
| 153 |
+
" \"batch_size\": 32,\n",
|
| 154 |
+
" \"num_workers\": 0 if QUICK_RUN else 2,\n",
|
| 155 |
+
" \"validation_fraction\": 0.2,\n",
|
| 156 |
+
" \"data_root\": \"data\",\n",
|
| 157 |
+
" \"weight_decay\": 1e-4,\n",
|
| 158 |
+
" \"scheduler\": {\"factor\": 0.5, \"patience\": 2},\n",
|
| 159 |
+
" \"scratch_cnn\": {\"learning_rate\": 1e-3, \"dropout\": 0.5, \"max_epochs\": 40, \"patience\": 8},\n",
|
| 160 |
+
" \"resnet18\": {\n",
|
| 161 |
+
" \"head_learning_rate\": 1e-3,\n",
|
| 162 |
+
" \"backbone_learning_rate\": 1e-4,\n",
|
| 163 |
+
" \"dropout\": 0.3,\n",
|
| 164 |
+
" \"max_epochs\": 15,\n",
|
| 165 |
+
" \"patience\": 4,\n",
|
| 166 |
+
" },\n",
|
| 167 |
+
" \"latency_samples\": 50,\n",
|
| 168 |
+
"}\n",
|
| 169 |
+
"if QUICK_RUN:\n",
|
| 170 |
+
" CONFIG[\"scratch_cnn\"].update({\"max_epochs\": 1, \"patience\": 1})\n",
|
| 171 |
+
" CONFIG[\"resnet18\"].update({\"max_epochs\": 1, \"patience\": 1})\n",
|
| 172 |
+
" CONFIG[\"latency_samples\"] = 6\n",
|
| 173 |
+
" CONFIG[\"quick_run_sizes\"] = {\"train\": 96, \"validation\": 64, \"test\": 74}\n",
|
| 174 |
+
"\n",
|
| 175 |
+
"DEVICE = \"cuda\" if torch.cuda.is_available() else \"cpu\"\n",
|
| 176 |
+
"set_seed(CONFIG[\"seed\"])\n",
|
| 177 |
+
"\n",
|
| 178 |
+
"SCRATCH_NAME = \"Scratch CNN\"\n",
|
| 179 |
+
"PRETRAINED_NAME = \"ResNet18 (pretrained)\"\n",
|
| 180 |
+
"\n",
|
| 181 |
+
"if QUICK_RUN:\n",
|
| 182 |
+
" MODEL_OUTPUT_PATH = Path(\"checkpoints/quick_run/pet_breed_model.pth\")\n",
|
| 183 |
+
" SCRATCH_OUTPUT_PATH = Path(\"checkpoints/quick_run/pet_breed_cnn_scratch.pth\")\n",
|
| 184 |
+
"else:\n",
|
| 185 |
+
" MODEL_OUTPUT_PATH = Path(\"pet_breed_model.pth\")\n",
|
| 186 |
+
" SCRATCH_OUTPUT_PATH = Path(\"checkpoints/pet_breed_cnn_scratch.pth\")\n",
|
| 187 |
+
"MODEL_OUTPUT_PATH.parent.mkdir(parents=True, exist_ok=True)\n",
|
| 188 |
+
"SCRATCH_OUTPUT_PATH.parent.mkdir(parents=True, exist_ok=True)\n",
|
| 189 |
+
"\n",
|
| 190 |
+
"print(f\"Device: {DEVICE} | PyTorch {torch.__version__} | quick run: {QUICK_RUN}\")\n",
|
| 191 |
+
"if DEVICE == \"cuda\":\n",
|
| 192 |
+
" print(\"GPU:\", torch.cuda.get_device_name(0))"
|
| 193 |
+
]
|
| 194 |
+
},
|
| 195 |
+
{
|
| 196 |
+
"cell_type": "markdown",
|
| 197 |
+
"id": "705454a9",
|
| 198 |
+
"metadata": {},
|
| 199 |
+
"source": [
|
| 200 |
+
"## 2. Data Pipeline and Exploratory Checks\n",
|
| 201 |
+
"\n",
|
| 202 |
+
"The official `trainval` partition (3,680 images) is split 80/20, stratified by breed, into training and validation subsets using a fixed seed. The official `test` partition (3,669 images) is held out entirely. Augmentation (random horizontal flip and rotation up to 10 degrees) is applied to the training subset only; validation and test images receive only resizing and normalization.\n",
|
| 203 |
+
"\n",
|
| 204 |
+
"The checks below confirm the split sizes, the class balance, that `CLASS_NAMES` matches the dataset's label order, and that the static `CAT_BREEDS` species mapping agrees with the dataset's own binary cat/dog annotation."
|
| 205 |
+
]
|
| 206 |
+
},
|
| 207 |
+
{
|
| 208 |
+
"cell_type": "code",
|
| 209 |
+
"execution_count": null,
|
| 210 |
+
"id": "0fe45e81",
|
| 211 |
+
"metadata": {},
|
| 212 |
+
"outputs": [],
|
| 213 |
+
"source": [
|
| 214 |
+
"DATASETS = build_datasets(\n",
|
| 215 |
+
" data_root=CONFIG[\"data_root\"],\n",
|
| 216 |
+
" image_size=CONFIG[\"image_size\"],\n",
|
| 217 |
+
" validation_fraction=CONFIG[\"validation_fraction\"],\n",
|
| 218 |
+
" seed=CONFIG[\"seed\"],\n",
|
| 219 |
+
" download=True,\n",
|
| 220 |
+
")\n",
|
| 221 |
+
"\n",
|
| 222 |
+
"if QUICK_RUN:\n",
|
| 223 |
+
" for split_name, split_size in CONFIG[\"quick_run_sizes\"].items():\n",
|
| 224 |
+
" full_length = len(DATASETS[split_name])\n",
|
| 225 |
+
" subset_indices = np.linspace(0, full_length - 1, split_size).astype(int).tolist()\n",
|
| 226 |
+
" DATASETS[split_name] = Subset(DATASETS[split_name], subset_indices)\n",
|
| 227 |
+
"\n",
|
| 228 |
+
"LOADERS = build_dataloaders(\n",
|
| 229 |
+
" DATASETS,\n",
|
| 230 |
+
" batch_size=CONFIG[\"batch_size\"],\n",
|
| 231 |
+
" num_workers=CONFIG[\"num_workers\"],\n",
|
| 232 |
+
" pin_memory=(DEVICE == \"cuda\"),\n",
|
| 233 |
+
")\n",
|
| 234 |
+
"\n",
|
| 235 |
+
"split_summary = pd.DataFrame(\n",
|
| 236 |
+
" {\n",
|
| 237 |
+
" \"split\": list(DATASETS.keys()),\n",
|
| 238 |
+
" \"images\": [len(split_dataset) for split_dataset in DATASETS.values()],\n",
|
| 239 |
+
" \"batches\": [len(split_loader) for split_loader in LOADERS.values()],\n",
|
| 240 |
+
" \"shuffled\": [split_name == \"train\" for split_name in LOADERS],\n",
|
| 241 |
+
" }\n",
|
| 242 |
+
")\n",
|
| 243 |
+
"display(split_summary)\n",
|
| 244 |
+
"\n",
|
| 245 |
+
"batch_images, batch_labels = next(iter(LOADERS[\"train\"]))\n",
|
| 246 |
+
"print(\"Training batch tensor shape:\", tuple(batch_images.shape), \"(batch, channels, height, width)\")\n",
|
| 247 |
+
"print(\"Training batch label shape:\", tuple(batch_labels.shape))"
|
| 248 |
+
]
|
| 249 |
+
},
|
| 250 |
+
{
|
| 251 |
+
"cell_type": "code",
|
| 252 |
+
"execution_count": null,
|
| 253 |
+
"id": "91a5a81d",
|
| 254 |
+
"metadata": {},
|
| 255 |
+
"outputs": [],
|
| 256 |
+
"source": [
|
| 257 |
+
"RAW_TRAINVAL = OxfordIIITPet(\n",
|
| 258 |
+
" root=CONFIG[\"data_root\"], split=\"trainval\", target_types=(\"category\", \"binary-category\")\n",
|
| 259 |
+
")\n",
|
| 260 |
+
"RAW_TEST = OxfordIIITPet(root=CONFIG[\"data_root\"], split=\"test\", target_types=\"category\")\n",
|
| 261 |
+
"\n",
|
| 262 |
+
"assert tuple(RAW_TRAINVAL.classes) == CLASS_NAMES, \"CLASS_NAMES does not match the dataset label order.\"\n",
|
| 263 |
+
"\n",
|
| 264 |
+
"# Species mapping check: the dataset encodes cat as 0 and dog as 1 in its binary annotation.\n",
|
| 265 |
+
"dataset_species_by_class = {}\n",
|
| 266 |
+
"for category_label, binary_label in zip(RAW_TRAINVAL._labels, RAW_TRAINVAL._bin_labels):\n",
|
| 267 |
+
" dataset_species_by_class[category_label] = \"Cat\" if binary_label == 0 else \"Dog\"\n",
|
| 268 |
+
"mapping_mismatches = [\n",
|
| 269 |
+
" CLASS_NAMES[class_id]\n",
|
| 270 |
+
" for class_id, dataset_species in dataset_species_by_class.items()\n",
|
| 271 |
+
" if get_species(CLASS_NAMES[class_id]) != dataset_species\n",
|
| 272 |
+
"]\n",
|
| 273 |
+
"assert not mapping_mismatches, f\"Species mapping disagrees with dataset annotation: {mapping_mismatches}\"\n",
|
| 274 |
+
"cat_class_count = sum(1 for name in CLASS_NAMES if get_species(name) == \"Cat\")\n",
|
| 275 |
+
"print(f\"Species mapping verified: {cat_class_count} cat breeds and {NUM_CLASSES - cat_class_count} dog breeds.\")\n",
|
| 276 |
+
"\n",
|
| 277 |
+
"trainval_labels = np.array(RAW_TRAINVAL._labels)\n",
|
| 278 |
+
"test_labels = np.array(RAW_TEST._labels)\n",
|
| 279 |
+
"split_train_indices, split_validation_indices = stratified_split_indices(\n",
|
| 280 |
+
" RAW_TRAINVAL._labels, CONFIG[\"validation_fraction\"], CONFIG[\"seed\"]\n",
|
| 281 |
+
")\n",
|
| 282 |
+
"class_count_table = pd.DataFrame(\n",
|
| 283 |
+
" {\n",
|
| 284 |
+
" \"train\": np.bincount(trainval_labels[split_train_indices], minlength=NUM_CLASSES),\n",
|
| 285 |
+
" \"validation\": np.bincount(trainval_labels[split_validation_indices], minlength=NUM_CLASSES),\n",
|
| 286 |
+
" \"test\": np.bincount(test_labels, minlength=NUM_CLASSES),\n",
|
| 287 |
+
" },\n",
|
| 288 |
+
" index=[format_breed_name(name) for name in CLASS_NAMES],\n",
|
| 289 |
+
")\n",
|
| 290 |
+
"print(\"\\nImages per breed (summary across the 37 classes):\")\n",
|
| 291 |
+
"display(class_count_table.describe().loc[[\"min\", \"mean\", \"max\"]].round(1))"
|
| 292 |
+
]
|
| 293 |
+
},
|
| 294 |
+
{
|
| 295 |
+
"cell_type": "code",
|
| 296 |
+
"execution_count": null,
|
| 297 |
+
"id": "678efce1",
|
| 298 |
+
"metadata": {},
|
| 299 |
+
"outputs": [],
|
| 300 |
+
"source": [
|
| 301 |
+
"sample_generator = np.random.default_rng(CONFIG[\"seed\"])\n",
|
| 302 |
+
"sample_indices = sample_generator.choice(len(RAW_TRAINVAL), size=12, replace=False)\n",
|
| 303 |
+
"\n",
|
| 304 |
+
"sample_figure, sample_axes = plt.subplots(3, 4, figsize=(12, 9))\n",
|
| 305 |
+
"for axes_item, sample_index in zip(sample_axes.ravel(), sample_indices):\n",
|
| 306 |
+
" sample_image, (sample_label, _) = RAW_TRAINVAL[int(sample_index)]\n",
|
| 307 |
+
" axes_item.imshow(sample_image)\n",
|
| 308 |
+
" axes_item.set_title(\n",
|
| 309 |
+
" f\"{format_breed_name(CLASS_NAMES[sample_label])}\\n({get_species(CLASS_NAMES[sample_label])})\",\n",
|
| 310 |
+
" fontsize=9,\n",
|
| 311 |
+
" )\n",
|
| 312 |
+
" axes_item.axis(\"off\")\n",
|
| 313 |
+
"sample_figure.suptitle(\"Random training samples\", y=1.0)\n",
|
| 314 |
+
"sample_figure.tight_layout()\n",
|
| 315 |
+
"plt.show()"
|
| 316 |
+
]
|
| 317 |
+
},
|
| 318 |
+
{
|
| 319 |
+
"cell_type": "markdown",
|
| 320 |
+
"id": "8cecd3db",
|
| 321 |
+
"metadata": {},
|
| 322 |
+
"source": [
|
| 323 |
+
"## 3. Model Architectures and Design Justification\n",
|
| 324 |
+
"\n",
|
| 325 |
+
"### 3.1 Scratch CNN (`PetBreedCNN`)\n",
|
| 326 |
+
"\n",
|
| 327 |
+
"Four convolutional blocks (32, 64, 128, and 256 channels), each consisting of two 3x3 convolutions with batch normalization and ReLU followed by 2x2 max pooling, feed an adaptive average pooling layer that reduces the feature map to a fixed 4 x 4 grid. A fully connected head (`Linear(4096, 512)`, ReLU, `Dropout(0.5)`, `Linear(512, 37)`) produces the logits.\n",
|
| 328 |
+
"\n",
|
| 329 |
+
"- Stacked small convolutions provide a hierarchy from edges and textures (early blocks) to fur patterns and facial structure (later blocks), which is appropriate for fine-grained breed recognition.\n",
|
| 330 |
+
"- Batch normalization stabilizes optimization and permits a learning rate of 0.001 with Adam.\n",
|
| 331 |
+
"- Dropout in the dense head and weight decay in the optimizer counteract overfitting, which is a significant risk with approximately 2,900 training images spread over 37 classes.\n",
|
| 332 |
+
"\n",
|
| 333 |
+
"### 3.2 Transfer-learning baseline (ResNet18)\n",
|
| 334 |
+
"\n",
|
| 335 |
+
"An ImageNet-pretrained ResNet18 is fine-tuned end to end with a new `Dropout(0.3)` and `Linear(512, 37)` head. Residual connections allow stable training of a deeper network, and ImageNet pretraining already encodes features (animal textures, shapes, and parts) that transfer directly to this domain. The new head uses a learning rate of 0.001, while the pretrained backbone uses a lower rate of 0.0001 so that fine-tuning refines, rather than destroys, the pretrained features.\n",
|
| 336 |
+
"\n",
|
| 337 |
+
"### 3.3 Shared training choices\n",
|
| 338 |
+
"\n",
|
| 339 |
+
"| Component | Choice | Justification |\n",
|
| 340 |
+
"|---|---|---|\n",
|
| 341 |
+
"| Loss | `nn.CrossEntropyLoss` on raw logits | Standard objective for single-label multi-class classification; combines log-softmax and negative log-likelihood in a numerically stable form |\n",
|
| 342 |
+
"| Optimizer | Adam (weight decay 1e-4) | Adaptive per-parameter step sizes converge reliably with little tuning on small datasets |\n",
|
| 343 |
+
"| Scheduler | `ReduceLROnPlateau` on validation loss (factor 0.5, patience 2) | Lowers the learning rate when validation loss stalls, allowing finer convergence |\n",
|
| 344 |
+
"| Early stopping | Stop when validation loss does not improve for a fixed patience; restore best weights | Prevents memorizing training images and determines the epoch count empirically |\n",
|
| 345 |
+
"| Augmentation | Horizontal flip, rotation up to 10 degrees | Increases effective data diversity without changing the label |\n",
|
| 346 |
+
"| Metrics | Loss, accuracy, precision, recall, F1 (macro and weighted), confusion matrix | Macro averages weight all breeds equally; the confusion matrix identifies which breeds are confused |"
|
| 347 |
+
]
|
| 348 |
+
},
|
| 349 |
+
{
|
| 350 |
+
"cell_type": "code",
|
| 351 |
+
"execution_count": null,
|
| 352 |
+
"id": "d4cdced8",
|
| 353 |
+
"metadata": {},
|
| 354 |
+
"outputs": [],
|
| 355 |
+
"source": [
|
| 356 |
+
"NETWORKS = {\n",
|
| 357 |
+
" SCRATCH_NAME: PetBreedCNN(\n",
|
| 358 |
+
" num_classes=NUM_CLASSES, dropout=CONFIG[\"scratch_cnn\"][\"dropout\"]\n",
|
| 359 |
+
" ).to(DEVICE),\n",
|
| 360 |
+
" PRETRAINED_NAME: build_resnet18_classifier(\n",
|
| 361 |
+
" num_classes=NUM_CLASSES, pretrained=True, dropout=CONFIG[\"resnet18\"][\"dropout\"]\n",
|
| 362 |
+
" ).to(DEVICE),\n",
|
| 363 |
+
"}\n",
|
| 364 |
+
"\n",
|
| 365 |
+
"# Dimension check: a batch of 2 images must produce logits of shape (2, 37).\n",
|
| 366 |
+
"dimension_probe = torch.zeros(2, 3, CONFIG[\"image_size\"], CONFIG[\"image_size\"], device=DEVICE)\n",
|
| 367 |
+
"parameter_rows = []\n",
|
| 368 |
+
"for network_name, network_instance in NETWORKS.items():\n",
|
| 369 |
+
" network_instance.eval()\n",
|
| 370 |
+
" with torch.inference_mode():\n",
|
| 371 |
+
" probe_logits = network_instance(dimension_probe)\n",
|
| 372 |
+
" assert probe_logits.shape == (2, NUM_CLASSES)\n",
|
| 373 |
+
" counts = count_parameters(network_instance)\n",
|
| 374 |
+
" parameter_rows.append(\n",
|
| 375 |
+
" {\n",
|
| 376 |
+
" \"model\": network_name,\n",
|
| 377 |
+
" \"total parameters\": counts[\"total\"],\n",
|
| 378 |
+
" \"trainable parameters\": counts[\"trainable\"],\n",
|
| 379 |
+
" \"output shape\": tuple(probe_logits.shape),\n",
|
| 380 |
+
" }\n",
|
| 381 |
+
" )\n",
|
| 382 |
+
"display(pd.DataFrame(parameter_rows))"
|
| 383 |
+
]
|
| 384 |
+
},
|
| 385 |
+
{
|
| 386 |
+
"cell_type": "markdown",
|
| 387 |
+
"id": "f3146175",
|
| 388 |
+
"metadata": {},
|
| 389 |
+
"source": [
|
| 390 |
+
"## 4. Training\n",
|
| 391 |
+
"\n",
|
| 392 |
+
"Both models are trained with the same loss, data loaders, validation-based scheduling, and early stopping. The weights from the epoch with the lowest validation loss are restored at the end of each run."
|
| 393 |
+
]
|
| 394 |
+
},
|
| 395 |
+
{
|
| 396 |
+
"cell_type": "code",
|
| 397 |
+
"execution_count": null,
|
| 398 |
+
"id": "f2f4e38a",
|
| 399 |
+
"metadata": {},
|
| 400 |
+
"outputs": [],
|
| 401 |
+
"source": [
|
| 402 |
+
"CRITERION = nn.CrossEntropyLoss()\n",
|
| 403 |
+
"FIT_RESULTS = {}\n",
|
| 404 |
+
"\n",
|
| 405 |
+
"scratch_settings = CONFIG[\"scratch_cnn\"]\n",
|
| 406 |
+
"scratch_optimizer = optim.Adam(\n",
|
| 407 |
+
" NETWORKS[SCRATCH_NAME].parameters(),\n",
|
| 408 |
+
" lr=scratch_settings[\"learning_rate\"],\n",
|
| 409 |
+
" weight_decay=CONFIG[\"weight_decay\"],\n",
|
| 410 |
+
")\n",
|
| 411 |
+
"scratch_scheduler = optim.lr_scheduler.ReduceLROnPlateau(\n",
|
| 412 |
+
" scratch_optimizer,\n",
|
| 413 |
+
" mode=\"min\",\n",
|
| 414 |
+
" factor=CONFIG[\"scheduler\"][\"factor\"],\n",
|
| 415 |
+
" patience=CONFIG[\"scheduler\"][\"patience\"],\n",
|
| 416 |
+
")\n",
|
| 417 |
+
"FIT_RESULTS[SCRATCH_NAME] = fit_model(\n",
|
| 418 |
+
" network=NETWORKS[SCRATCH_NAME],\n",
|
| 419 |
+
" loaders=LOADERS,\n",
|
| 420 |
+
" criterion=CRITERION,\n",
|
| 421 |
+
" optimizer=scratch_optimizer,\n",
|
| 422 |
+
" scheduler=scratch_scheduler,\n",
|
| 423 |
+
" device=DEVICE,\n",
|
| 424 |
+
" max_epochs=scratch_settings[\"max_epochs\"],\n",
|
| 425 |
+
" early_stopping_patience=scratch_settings[\"patience\"],\n",
|
| 426 |
+
" run_name=SCRATCH_NAME,\n",
|
| 427 |
+
")"
|
| 428 |
+
]
|
| 429 |
+
},
|
| 430 |
+
{
|
| 431 |
+
"cell_type": "code",
|
| 432 |
+
"execution_count": null,
|
| 433 |
+
"id": "45b44d4e",
|
| 434 |
+
"metadata": {},
|
| 435 |
+
"outputs": [],
|
| 436 |
+
"source": [
|
| 437 |
+
"pretrained_settings = CONFIG[\"resnet18\"]\n",
|
| 438 |
+
"pretrained_network = NETWORKS[PRETRAINED_NAME]\n",
|
| 439 |
+
"pretrained_head_parameters = list(pretrained_network.fc.parameters())\n",
|
| 440 |
+
"pretrained_backbone_parameters = [\n",
|
| 441 |
+
" parameter\n",
|
| 442 |
+
" for parameter_name, parameter in pretrained_network.named_parameters()\n",
|
| 443 |
+
" if not parameter_name.startswith(\"fc.\")\n",
|
| 444 |
+
"]\n",
|
| 445 |
+
"pretrained_optimizer = optim.Adam(\n",
|
| 446 |
+
" [\n",
|
| 447 |
+
" {\"params\": pretrained_head_parameters, \"lr\": pretrained_settings[\"head_learning_rate\"]},\n",
|
| 448 |
+
" {\"params\": pretrained_backbone_parameters, \"lr\": pretrained_settings[\"backbone_learning_rate\"]},\n",
|
| 449 |
+
" ],\n",
|
| 450 |
+
" weight_decay=CONFIG[\"weight_decay\"],\n",
|
| 451 |
+
")\n",
|
| 452 |
+
"pretrained_scheduler = optim.lr_scheduler.ReduceLROnPlateau(\n",
|
| 453 |
+
" pretrained_optimizer,\n",
|
| 454 |
+
" mode=\"min\",\n",
|
| 455 |
+
" factor=CONFIG[\"scheduler\"][\"factor\"],\n",
|
| 456 |
+
" patience=CONFIG[\"scheduler\"][\"patience\"],\n",
|
| 457 |
+
")\n",
|
| 458 |
+
"FIT_RESULTS[PRETRAINED_NAME] = fit_model(\n",
|
| 459 |
+
" network=pretrained_network,\n",
|
| 460 |
+
" loaders=LOADERS,\n",
|
| 461 |
+
" criterion=CRITERION,\n",
|
| 462 |
+
" optimizer=pretrained_optimizer,\n",
|
| 463 |
+
" scheduler=pretrained_scheduler,\n",
|
| 464 |
+
" device=DEVICE,\n",
|
| 465 |
+
" max_epochs=pretrained_settings[\"max_epochs\"],\n",
|
| 466 |
+
" early_stopping_patience=pretrained_settings[\"patience\"],\n",
|
| 467 |
+
" run_name=PRETRAINED_NAME,\n",
|
| 468 |
+
")"
|
| 469 |
+
]
|
| 470 |
+
},
|
| 471 |
+
{
|
| 472 |
+
"cell_type": "code",
|
| 473 |
+
"execution_count": null,
|
| 474 |
+
"id": "f0e93f85",
|
| 475 |
+
"metadata": {},
|
| 476 |
+
"outputs": [],
|
| 477 |
+
"source": [
|
| 478 |
+
"curve_figure = plot_training_curves(FIT_RESULTS)\n",
|
| 479 |
+
"plt.show()\n",
|
| 480 |
+
"\n",
|
| 481 |
+
"fit_summary = pd.DataFrame(\n",
|
| 482 |
+
" {\n",
|
| 483 |
+
" run_name: {\n",
|
| 484 |
+
" \"epochs run\": fit_result[\"epochs_run\"],\n",
|
| 485 |
+
" \"best epoch\": fit_result[\"best_epoch\"],\n",
|
| 486 |
+
" \"best validation loss\": fit_result[\"best_validation_loss\"],\n",
|
| 487 |
+
" \"validation accuracy at best epoch\": fit_result[\"best_validation_accuracy\"],\n",
|
| 488 |
+
" \"training time (min)\": fit_result[\"training_seconds\"] / 60,\n",
|
| 489 |
+
" }\n",
|
| 490 |
+
" for run_name, fit_result in FIT_RESULTS.items()\n",
|
| 491 |
+
" }\n",
|
| 492 |
+
").T\n",
|
| 493 |
+
"display(fit_summary.round(4))"
|
| 494 |
+
]
|
| 495 |
+
},
|
| 496 |
+
{
|
| 497 |
+
"cell_type": "markdown",
|
| 498 |
+
"id": "0afa753d",
|
| 499 |
+
"metadata": {},
|
| 500 |
+
"source": [
|
| 501 |
+
"## 5. Evaluation on the Unseen Test Set\n",
|
| 502 |
+
"\n",
|
| 503 |
+
"Each network is placed in evaluation mode (`model.eval()` is applied inside `evaluate_loader`) and evaluated under `torch.inference_mode()`. Reported metrics are test loss, accuracy, precision, recall, and F1 (macro-averaged, which weights every breed equally, and support-weighted), the 37 x 37 confusion matrix, and the species-level accuracy obtained by mapping each breed prediction to Cat or Dog."
|
| 504 |
+
]
|
| 505 |
+
},
|
| 506 |
+
{
|
| 507 |
+
"cell_type": "code",
|
| 508 |
+
"execution_count": null,
|
| 509 |
+
"id": "35f1c2a0",
|
| 510 |
+
"metadata": {},
|
| 511 |
+
"outputs": [],
|
| 512 |
+
"source": [
|
| 513 |
+
"TEST_RESULTS = {}\n",
|
| 514 |
+
"for run_name, network_instance in NETWORKS.items():\n",
|
| 515 |
+
" test_scores = evaluate_loader(network_instance, LOADERS[\"test\"], CRITERION, DEVICE)\n",
|
| 516 |
+
" test_metrics = compute_classification_metrics(test_scores[\"y_true\"], test_scores[\"y_pred\"])\n",
|
| 517 |
+
" TEST_RESULTS[run_name] = {\"loss\": test_scores[\"loss\"], **test_metrics}\n",
|
| 518 |
+
"\n",
|
| 519 |
+
"comparison_table = pd.DataFrame(\n",
|
| 520 |
+
" {\n",
|
| 521 |
+
" run_name: {\n",
|
| 522 |
+
" \"test loss\": test_result[\"loss\"],\n",
|
| 523 |
+
" \"accuracy\": test_result[\"accuracy\"],\n",
|
| 524 |
+
" \"macro precision\": test_result[\"macro_precision\"],\n",
|
| 525 |
+
" \"macro recall\": test_result[\"macro_recall\"],\n",
|
| 526 |
+
" \"macro F1\": test_result[\"macro_f1\"],\n",
|
| 527 |
+
" \"weighted F1\": test_result[\"weighted_f1\"],\n",
|
| 528 |
+
" \"species accuracy (cat vs. dog)\": test_result[\"species_accuracy\"],\n",
|
| 529 |
+
" \"trainable parameters\": count_parameters(NETWORKS[run_name])[\"trainable\"],\n",
|
| 530 |
+
" }\n",
|
| 531 |
+
" for run_name, test_result in TEST_RESULTS.items()\n",
|
| 532 |
+
" }\n",
|
| 533 |
+
").T\n",
|
| 534 |
+
"display(comparison_table.round(4))"
|
| 535 |
+
]
|
| 536 |
+
},
|
| 537 |
+
{
|
| 538 |
+
"cell_type": "code",
|
| 539 |
+
"execution_count": null,
|
| 540 |
+
"id": "e69c2da8",
|
| 541 |
+
"metadata": {},
|
| 542 |
+
"outputs": [],
|
| 543 |
+
"source": [
|
| 544 |
+
"for run_name, test_result in TEST_RESULTS.items():\n",
|
| 545 |
+
" print(\"=\" * 90)\n",
|
| 546 |
+
" print(f\"{run_name}: per-breed classification report (test set)\")\n",
|
| 547 |
+
" print(\"=\" * 90)\n",
|
| 548 |
+
" print(test_result[\"report\"])"
|
| 549 |
+
]
|
| 550 |
+
},
|
| 551 |
+
{
|
| 552 |
+
"cell_type": "code",
|
| 553 |
+
"execution_count": null,
|
| 554 |
+
"id": "f22db371",
|
| 555 |
+
"metadata": {},
|
| 556 |
+
"outputs": [],
|
| 557 |
+
"source": [
|
| 558 |
+
"for run_name, test_result in TEST_RESULTS.items():\n",
|
| 559 |
+
" plot_confusion_matrix(\n",
|
| 560 |
+
" test_result[\"confusion_matrix\"],\n",
|
| 561 |
+
" CLASS_NAMES,\n",
|
| 562 |
+
" title=f\"{run_name}: normalized breed confusion matrix (test set)\",\n",
|
| 563 |
+
" normalize=True,\n",
|
| 564 |
+
" )\n",
|
| 565 |
+
" plt.show()\n",
|
| 566 |
+
"\n",
|
| 567 |
+
" plot_confusion_matrix(\n",
|
| 568 |
+
" test_result[\"species_confusion_matrix\"],\n",
|
| 569 |
+
" [\"Cat\", \"Dog\"],\n",
|
| 570 |
+
" title=f\"{run_name}: species confusion matrix (counts)\",\n",
|
| 571 |
+
" normalize=False,\n",
|
| 572 |
+
" )\n",
|
| 573 |
+
" plt.show()"
|
| 574 |
+
]
|
| 575 |
+
},
|
| 576 |
+
{
|
| 577 |
+
"cell_type": "code",
|
| 578 |
+
"execution_count": null,
|
| 579 |
+
"id": "190df6ee",
|
| 580 |
+
"metadata": {},
|
| 581 |
+
"outputs": [],
|
| 582 |
+
"source": [
|
| 583 |
+
"for run_name, test_result in TEST_RESULTS.items():\n",
|
| 584 |
+
" confusion_pairs = top_confusions(test_result[\"confusion_matrix\"], CLASS_NAMES, count=8)\n",
|
| 585 |
+
" print(f\"{run_name}: most frequent breed confusions on the test set\")\n",
|
| 586 |
+
" display(pd.DataFrame(confusion_pairs, columns=[\"true breed\", \"predicted breed\", \"count\"]))"
|
| 587 |
+
]
|
| 588 |
+
},
|
| 589 |
+
{
|
| 590 |
+
"cell_type": "markdown",
|
| 591 |
+
"id": "35115013",
|
| 592 |
+
"metadata": {},
|
| 593 |
+
"source": [
|
| 594 |
+
"## 6. Single-Image Inference Latency\n",
|
| 595 |
+
"\n",
|
| 596 |
+
"Latency is measured with `time.perf_counter()` around the forward pass and softmax for one image at a time (`predict_image`), after a short warm-up. Hugging Face Spaces serves the application on CPU in the free tier, so CPU latency is the figure most relevant to deployment. GPU latency is reported as well when a GPU is available."
|
| 597 |
+
]
|
| 598 |
+
},
|
| 599 |
+
{
|
| 600 |
+
"cell_type": "code",
|
| 601 |
+
"execution_count": null,
|
| 602 |
+
"id": "2bcbc032",
|
| 603 |
+
"metadata": {},
|
| 604 |
+
"outputs": [],
|
| 605 |
+
"source": [
|
| 606 |
+
"latency_generator = np.random.default_rng(CONFIG[\"seed\"])\n",
|
| 607 |
+
"latency_indices = latency_generator.choice(\n",
|
| 608 |
+
" len(RAW_TEST), size=CONFIG[\"latency_samples\"], replace=False\n",
|
| 609 |
+
")\n",
|
| 610 |
+
"latency_images = [RAW_TEST[int(index)][0] for index in latency_indices]\n",
|
| 611 |
+
"\n",
|
| 612 |
+
"latency_devices = [\"cpu\"] + ([\"cuda\"] if DEVICE == \"cuda\" else [])\n",
|
| 613 |
+
"latency_rows = []\n",
|
| 614 |
+
"for run_name, network_instance in NETWORKS.items():\n",
|
| 615 |
+
" for latency_device in latency_devices:\n",
|
| 616 |
+
" latency_network = copy.deepcopy(network_instance).to(latency_device)\n",
|
| 617 |
+
" latency_stats = benchmark_latency(latency_network, latency_images, latency_device)\n",
|
| 618 |
+
" latency_rows.append({\"model\": run_name, \"device\": latency_device, **latency_stats})\n",
|
| 619 |
+
"display(pd.DataFrame(latency_rows).round(5))"
|
| 620 |
+
]
|
| 621 |
+
},
|
| 622 |
+
{
|
| 623 |
+
"cell_type": "markdown",
|
| 624 |
+
"id": "245b9a5d",
|
| 625 |
+
"metadata": {},
|
| 626 |
+
"source": [
|
| 627 |
+
"## 7. Model Selection and Export\n",
|
| 628 |
+
"\n",
|
| 629 |
+
"Model selection is based on validation accuracy and validation loss, not test results, so that the test set remains an unbiased estimate of generalization. The pretrained ResNet18 is the model exported for deployment; the cell below confirms that this choice is supported by the validation results and reports the test comparison. The scratch CNN weights are saved separately for reference."
|
| 630 |
+
]
|
| 631 |
+
},
|
| 632 |
+
{
|
| 633 |
+
"cell_type": "code",
|
| 634 |
+
"execution_count": null,
|
| 635 |
+
"id": "669f661d",
|
| 636 |
+
"metadata": {},
|
| 637 |
+
"outputs": [],
|
| 638 |
+
"source": [
|
| 639 |
+
"validation_ranking = sorted(\n",
|
| 640 |
+
" FIT_RESULTS.items(), key=lambda item: item[1][\"best_validation_accuracy\"], reverse=True\n",
|
| 641 |
+
")\n",
|
| 642 |
+
"best_validation_name = validation_ranking[0][0]\n",
|
| 643 |
+
"print(\"Validation ranking (accuracy at the best epoch):\")\n",
|
| 644 |
+
"for ranked_name, ranked_result in validation_ranking:\n",
|
| 645 |
+
" print(f\" {ranked_name}: {ranked_result['best_validation_accuracy']:.4f}\")\n",
|
| 646 |
+
"\n",
|
| 647 |
+
"if best_validation_name != PRETRAINED_NAME:\n",
|
| 648 |
+
" print(\n",
|
| 649 |
+
" \"\\nWARNING: the scratch CNN outperformed the pretrained ResNet18 on validation data. \"\n",
|
| 650 |
+
" \"Review the results before deploying the ResNet18 weights.\"\n",
|
| 651 |
+
" )\n",
|
| 652 |
+
"\n",
|
| 653 |
+
"torch.save(FIT_RESULTS[PRETRAINED_NAME][\"best_state\"], MODEL_OUTPUT_PATH)\n",
|
| 654 |
+
"torch.save(FIT_RESULTS[SCRATCH_NAME][\"best_state\"], SCRATCH_OUTPUT_PATH)\n",
|
| 655 |
+
"print(f\"\\nSaved deployment weights to {MODEL_OUTPUT_PATH} ({MODEL_OUTPUT_PATH.stat().st_size / 1e6:.1f} MB)\")\n",
|
| 656 |
+
"print(f\"Saved scratch CNN weights to {SCRATCH_OUTPUT_PATH} ({SCRATCH_OUTPUT_PATH.stat().st_size / 1e6:.1f} MB)\")"
|
| 657 |
+
]
|
| 658 |
+
},
|
| 659 |
+
{
|
| 660 |
+
"cell_type": "code",
|
| 661 |
+
"execution_count": null,
|
| 662 |
+
"id": "39ae385f",
|
| 663 |
+
"metadata": {},
|
| 664 |
+
"outputs": [],
|
| 665 |
+
"source": [
|
| 666 |
+
"# Deployment check: rebuild the architecture exactly as app.py does and reload the saved weights.\n",
|
| 667 |
+
"reloaded_network = build_resnet18_classifier(num_classes=NUM_CLASSES, pretrained=False)\n",
|
| 668 |
+
"reloaded_network.load_state_dict(torch.load(MODEL_OUTPUT_PATH, map_location=\"cpu\"))\n",
|
| 669 |
+
"reloaded_network.eval()\n",
|
| 670 |
+
"\n",
|
| 671 |
+
"check_image, (check_label, _) = RAW_TRAINVAL[0]\n",
|
| 672 |
+
"reloaded_prediction = predict_image(reloaded_network, check_image, device=\"cpu\")\n",
|
| 673 |
+
"reference_prediction = predict_image(\n",
|
| 674 |
+
" copy.deepcopy(NETWORKS[PRETRAINED_NAME]).to(\"cpu\"), check_image, device=\"cpu\"\n",
|
| 675 |
+
")\n",
|
| 676 |
+
"\n",
|
| 677 |
+
"probability_gap = max(\n",
|
| 678 |
+
" abs(reloaded_prediction[\"probabilities\"][name] - reference_prediction[\"probabilities\"][name])\n",
|
| 679 |
+
" for name in CLASS_NAMES\n",
|
| 680 |
+
")\n",
|
| 681 |
+
"assert reloaded_prediction[\"breed\"] == reference_prediction[\"breed\"]\n",
|
| 682 |
+
"assert probability_gap < 1e-5, f\"Reloaded weights differ from the trained network ({probability_gap}).\"\n",
|
| 683 |
+
"\n",
|
| 684 |
+
"print(\"True breed: \", format_breed_name(CLASS_NAMES[check_label]))\n",
|
| 685 |
+
"print(\"Predicted breed: \", format_breed_name(reloaded_prediction[\"breed\"]))\n",
|
| 686 |
+
"print(\"Detected species: \", reloaded_prediction[\"species\"])\n",
|
| 687 |
+
"print(f\"Inference latency: {reloaded_prediction['inference_seconds']:.4f} s\")\n",
|
| 688 |
+
"print(\"Top 3:\", [(format_breed_name(name), round(prob, 3)) for name, prob in reloaded_prediction[\"top_predictions\"]])\n",
|
| 689 |
+
"print(\"Reloaded weights reproduce the trained network's outputs.\")"
|
| 690 |
+
]
|
| 691 |
+
},
|
| 692 |
+
{
|
| 693 |
+
"cell_type": "code",
|
| 694 |
+
"execution_count": null,
|
| 695 |
+
"id": "4e3b94be",
|
| 696 |
+
"metadata": {},
|
| 697 |
+
"outputs": [],
|
| 698 |
+
"source": [
|
| 699 |
+
"if IN_COLAB:\n",
|
| 700 |
+
" from google.colab import files\n",
|
| 701 |
+
"\n",
|
| 702 |
+
" files.download(str(MODEL_OUTPUT_PATH))\n",
|
| 703 |
+
"else:\n",
|
| 704 |
+
" print(f\"Copy {MODEL_OUTPUT_PATH} to the repository root before deploying.\")"
|
| 705 |
+
]
|
| 706 |
+
},
|
| 707 |
+
{
|
| 708 |
+
"cell_type": "markdown",
|
| 709 |
+
"id": "56b3712a",
|
| 710 |
+
"metadata": {},
|
| 711 |
+
"source": [
|
| 712 |
+
"## 8. Summary of Results"
|
| 713 |
+
]
|
| 714 |
+
},
|
| 715 |
+
{
|
| 716 |
+
"cell_type": "code",
|
| 717 |
+
"execution_count": null,
|
| 718 |
+
"id": "fa044fa1",
|
| 719 |
+
"metadata": {},
|
| 720 |
+
"outputs": [],
|
| 721 |
+
"source": [
|
| 722 |
+
"summary_lines = []\n",
|
| 723 |
+
"for run_name, test_result in TEST_RESULTS.items():\n",
|
| 724 |
+
" summary_lines.append(\n",
|
| 725 |
+
" f\"{run_name}: test accuracy {test_result['accuracy']:.4f}, macro F1 {test_result['macro_f1']:.4f}, \"\n",
|
| 726 |
+
" f\"species accuracy {test_result['species_accuracy']:.4f}, \"\n",
|
| 727 |
+
" f\"best epoch {FIT_RESULTS[run_name]['best_epoch']} of {FIT_RESULTS[run_name]['epochs_run']} run.\"\n",
|
| 728 |
+
" )\n",
|
| 729 |
+
"accuracy_gap = (\n",
|
| 730 |
+
" TEST_RESULTS[PRETRAINED_NAME][\"accuracy\"] - TEST_RESULTS[SCRATCH_NAME][\"accuracy\"]\n",
|
| 731 |
+
")\n",
|
| 732 |
+
"summary_lines.append(\n",
|
| 733 |
+
" f\"Transfer learning changed breed test accuracy by {accuracy_gap:+.4f} relative to the scratch CNN.\"\n",
|
| 734 |
+
")\n",
|
| 735 |
+
"print(\"\\n\".join(summary_lines))"
|
| 736 |
+
]
|
| 737 |
+
},
|
| 738 |
+
{
|
| 739 |
+
"cell_type": "markdown",
|
| 740 |
+
"id": "85873357",
|
| 741 |
+
"metadata": {},
|
| 742 |
+
"source": [
|
| 743 |
+
"### Interpretation notes\n",
|
| 744 |
+
"\n",
|
| 745 |
+
"- **Why transfer learning is expected to help.** The Oxford-IIIT Pet training partition provides only about 100 images per breed. A network trained from scratch must learn all visual features from this limited data, whereas the pretrained network starts from features learned on over one million ImageNet images, several classes of which are cat and dog breeds.\n",
|
| 746 |
+
"- **Species accuracy is bounded below by breed accuracy.** A breed error between two breeds of the same species (for example, two terriers) does not produce a species error, so species accuracy is at least as high as breed accuracy. Cat-versus-dog errors arise only when the predicted breed belongs to the other species.\n",
|
| 747 |
+
"- **Limitations.** Images contain a single labelled animal against varied backgrounds, so performance on photographs with multiple animals, heavy occlusion, or breeds outside the 37 classes is not characterized. Mixed-breed animals are forced into one of the 37 labels."
|
| 748 |
+
]
|
| 749 |
+
}
|
| 750 |
+
],
|
| 751 |
+
"metadata": {
|
| 752 |
+
"accelerator": "GPU",
|
| 753 |
+
"kernelspec": {
|
| 754 |
+
"display_name": "Python 3 (ipykernel)",
|
| 755 |
+
"language": "python",
|
| 756 |
+
"name": "python3"
|
| 757 |
+
},
|
| 758 |
+
"language_info": {
|
| 759 |
+
"codemirror_mode": {
|
| 760 |
+
"name": "ipython",
|
| 761 |
+
"version": 3
|
| 762 |
+
},
|
| 763 |
+
"file_extension": ".py",
|
| 764 |
+
"mimetype": "text/x-python",
|
| 765 |
+
"name": "python",
|
| 766 |
+
"nbconvert_exporter": "python",
|
| 767 |
+
"pygments_lexer": "ipython3",
|
| 768 |
+
"version": "3.13.15"
|
| 769 |
+
}
|
| 770 |
+
},
|
| 771 |
+
"nbformat": 4,
|
| 772 |
+
"nbformat_minor": 5
|
| 773 |
+
}
|
pet_breed_model.pth
ADDED
|
File without changes
|
pyproject.toml
ADDED
|
@@ -0,0 +1,30 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
[project]
|
| 2 |
+
name = "pet-classifier"
|
| 3 |
+
version = "0.1.0"
|
| 4 |
+
description = "Oxford-IIIT Pet breed and species classifier with a Gradio interface"
|
| 5 |
+
readme = "README.md"
|
| 6 |
+
authors = [
|
| 7 |
+
{ name = "Damaris Adora", email = "42323614+dascott2007@users.noreply.github.com" }
|
| 8 |
+
]
|
| 9 |
+
requires-python = ">=3.14"
|
| 10 |
+
dependencies = [
|
| 11 |
+
"gradio",
|
| 12 |
+
"huggingface-hub",
|
| 13 |
+
"matplotlib",
|
| 14 |
+
"numpy",
|
| 15 |
+
"pandas",
|
| 16 |
+
"pillow",
|
| 17 |
+
"scikit-learn",
|
| 18 |
+
"torch",
|
| 19 |
+
"torchvision",
|
| 20 |
+
]
|
| 21 |
+
|
| 22 |
+
[dependency-groups]
|
| 23 |
+
dev = [
|
| 24 |
+
"ipykernel",
|
| 25 |
+
]
|
| 26 |
+
|
| 27 |
+
# This is an application, not a distributable package, so no build backend is
|
| 28 |
+
# configured. Modules in src/ are imported directly (for example, `from src.model import ...`).
|
| 29 |
+
[tool.uv]
|
| 30 |
+
package = false
|
requirements.txt
ADDED
|
@@ -0,0 +1,5 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
torch==2.14.1
|
| 2 |
+
torchvision==0.29.1
|
| 3 |
+
gradio==6.30.0
|
| 4 |
+
Pillow==12.3.0
|
| 5 |
+
numpy==2.5.4
|
src/__init__.py
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
"""Reusable modules for the Oxford-IIIT Pet breed and species classifier."""
|
src/dataset.py
ADDED
|
@@ -0,0 +1,130 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Data pipeline for the Oxford-IIIT Pet dataset.
|
| 2 |
+
|
| 3 |
+
Provides the preprocessing transforms, a stratified train/validation split of
|
| 4 |
+
the official ``trainval`` partition, and the PyTorch ``DataLoader`` objects.
|
| 5 |
+
The official ``test`` partition is never used for training or model selection.
|
| 6 |
+
"""
|
| 7 |
+
|
| 8 |
+
from __future__ import annotations
|
| 9 |
+
|
| 10 |
+
import numpy as np
|
| 11 |
+
from torch.utils.data import DataLoader, Subset
|
| 12 |
+
from torchvision import transforms
|
| 13 |
+
from torchvision.datasets import OxfordIIITPet
|
| 14 |
+
|
| 15 |
+
IMAGE_SIZE = 224
|
| 16 |
+
IMAGENET_MEAN = [0.485, 0.456, 0.406]
|
| 17 |
+
IMAGENET_STD = [0.229, 0.224, 0.225]
|
| 18 |
+
SEED = 42
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
def build_train_transform(image_size: int = IMAGE_SIZE) -> transforms.Compose:
|
| 22 |
+
"""Training transform: resize, light augmentation, tensor conversion, normalization."""
|
| 23 |
+
return transforms.Compose(
|
| 24 |
+
[
|
| 25 |
+
transforms.Resize((image_size, image_size)),
|
| 26 |
+
transforms.RandomHorizontalFlip(),
|
| 27 |
+
transforms.RandomRotation(10),
|
| 28 |
+
transforms.ToTensor(),
|
| 29 |
+
transforms.Normalize(mean=IMAGENET_MEAN, std=IMAGENET_STD),
|
| 30 |
+
]
|
| 31 |
+
)
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
def build_eval_transform(image_size: int = IMAGE_SIZE) -> transforms.Compose:
|
| 35 |
+
"""Deterministic transform for validation, testing, and inference."""
|
| 36 |
+
return transforms.Compose(
|
| 37 |
+
[
|
| 38 |
+
transforms.Resize((image_size, image_size)),
|
| 39 |
+
transforms.ToTensor(),
|
| 40 |
+
transforms.Normalize(mean=IMAGENET_MEAN, std=IMAGENET_STD),
|
| 41 |
+
]
|
| 42 |
+
)
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
def stratified_split_indices(
|
| 46 |
+
labels: list[int],
|
| 47 |
+
validation_fraction: float = 0.2,
|
| 48 |
+
seed: int = SEED,
|
| 49 |
+
) -> tuple[list[int], list[int]]:
|
| 50 |
+
"""Split sample indices into train and validation sets, preserving class balance.
|
| 51 |
+
|
| 52 |
+
Each class contributes ``validation_fraction`` of its samples to the
|
| 53 |
+
validation set, so every breed is represented in both partitions.
|
| 54 |
+
"""
|
| 55 |
+
label_array = np.asarray(labels)
|
| 56 |
+
random_state = np.random.default_rng(seed)
|
| 57 |
+
train_indices: list[int] = []
|
| 58 |
+
validation_indices: list[int] = []
|
| 59 |
+
for class_id in np.unique(label_array):
|
| 60 |
+
class_indices = np.flatnonzero(label_array == class_id)
|
| 61 |
+
random_state.shuffle(class_indices)
|
| 62 |
+
validation_count = max(1, int(round(len(class_indices) * validation_fraction)))
|
| 63 |
+
validation_indices.extend(class_indices[:validation_count].tolist())
|
| 64 |
+
train_indices.extend(class_indices[validation_count:].tolist())
|
| 65 |
+
return sorted(train_indices), sorted(validation_indices)
|
| 66 |
+
|
| 67 |
+
|
| 68 |
+
def build_datasets(
|
| 69 |
+
data_root: str = "data",
|
| 70 |
+
image_size: int = IMAGE_SIZE,
|
| 71 |
+
validation_fraction: float = 0.2,
|
| 72 |
+
seed: int = SEED,
|
| 73 |
+
download: bool = True,
|
| 74 |
+
) -> dict[str, Subset | OxfordIIITPet]:
|
| 75 |
+
"""Create the train, validation, and test datasets.
|
| 76 |
+
|
| 77 |
+
The ``trainval`` partition is instantiated twice: once with augmentation
|
| 78 |
+
(for the training subset) and once with the deterministic transform (for the
|
| 79 |
+
validation subset), so validation images are never augmented.
|
| 80 |
+
"""
|
| 81 |
+
trainval_augmented = OxfordIIITPet(
|
| 82 |
+
root=data_root,
|
| 83 |
+
split="trainval",
|
| 84 |
+
target_types="category",
|
| 85 |
+
transform=build_train_transform(image_size),
|
| 86 |
+
download=download,
|
| 87 |
+
)
|
| 88 |
+
trainval_plain = OxfordIIITPet(
|
| 89 |
+
root=data_root,
|
| 90 |
+
split="trainval",
|
| 91 |
+
target_types="category",
|
| 92 |
+
transform=build_eval_transform(image_size),
|
| 93 |
+
download=download,
|
| 94 |
+
)
|
| 95 |
+
test_dataset = OxfordIIITPet(
|
| 96 |
+
root=data_root,
|
| 97 |
+
split="test",
|
| 98 |
+
target_types="category",
|
| 99 |
+
transform=build_eval_transform(image_size),
|
| 100 |
+
download=download,
|
| 101 |
+
)
|
| 102 |
+
|
| 103 |
+
train_indices, validation_indices = stratified_split_indices(
|
| 104 |
+
trainval_plain._labels, validation_fraction=validation_fraction, seed=seed
|
| 105 |
+
)
|
| 106 |
+
return {
|
| 107 |
+
"train": Subset(trainval_augmented, train_indices),
|
| 108 |
+
"validation": Subset(trainval_plain, validation_indices),
|
| 109 |
+
"test": test_dataset,
|
| 110 |
+
}
|
| 111 |
+
|
| 112 |
+
|
| 113 |
+
def build_dataloaders(
|
| 114 |
+
datasets: dict[str, Subset | OxfordIIITPet],
|
| 115 |
+
batch_size: int = 32,
|
| 116 |
+
num_workers: int = 2,
|
| 117 |
+
pin_memory: bool = False,
|
| 118 |
+
) -> dict[str, DataLoader]:
|
| 119 |
+
"""Wrap each dataset in a ``DataLoader``; only the training loader shuffles."""
|
| 120 |
+
loaders: dict[str, DataLoader] = {}
|
| 121 |
+
for split_name, split_dataset in datasets.items():
|
| 122 |
+
loaders[split_name] = DataLoader(
|
| 123 |
+
split_dataset,
|
| 124 |
+
batch_size=batch_size,
|
| 125 |
+
shuffle=(split_name == "train"),
|
| 126 |
+
num_workers=num_workers,
|
| 127 |
+
pin_memory=pin_memory,
|
| 128 |
+
persistent_workers=num_workers > 0,
|
| 129 |
+
)
|
| 130 |
+
return loaders
|
src/model.py
ADDED
|
@@ -0,0 +1,105 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Model definitions for the Oxford-IIIT Pet breed classifier.
|
| 2 |
+
|
| 3 |
+
Two architectures are provided:
|
| 4 |
+
|
| 5 |
+
* ``PetBreedCNN``: a convolutional network trained from scratch.
|
| 6 |
+
* ``build_resnet18_classifier``: an ImageNet-pretrained ResNet18 with a new
|
| 7 |
+
classification head, used as a transfer-learning baseline and as the
|
| 8 |
+
deployed model.
|
| 9 |
+
"""
|
| 10 |
+
|
| 11 |
+
from __future__ import annotations
|
| 12 |
+
|
| 13 |
+
import torch
|
| 14 |
+
from torch import nn
|
| 15 |
+
from torchvision import models
|
| 16 |
+
|
| 17 |
+
NUM_CLASSES = 37
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
def _conv_block(in_channels: int, out_channels: int) -> nn.Sequential:
|
| 21 |
+
"""Two 3x3 convolutions followed by 2x2 max pooling.
|
| 22 |
+
|
| 23 |
+
Each convolution is followed by batch normalization and a ReLU. The pooling
|
| 24 |
+
layer halves the spatial resolution, so the receptive field grows with depth
|
| 25 |
+
while the channel count increases.
|
| 26 |
+
"""
|
| 27 |
+
return nn.Sequential(
|
| 28 |
+
nn.Conv2d(in_channels, out_channels, kernel_size=3, padding=1, bias=False),
|
| 29 |
+
nn.BatchNorm2d(out_channels),
|
| 30 |
+
nn.ReLU(inplace=True),
|
| 31 |
+
nn.Conv2d(out_channels, out_channels, kernel_size=3, padding=1, bias=False),
|
| 32 |
+
nn.BatchNorm2d(out_channels),
|
| 33 |
+
nn.ReLU(inplace=True),
|
| 34 |
+
nn.MaxPool2d(kernel_size=2),
|
| 35 |
+
)
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
class PetBreedCNN(nn.Module):
|
| 39 |
+
"""Convolutional neural network for 37-way breed classification.
|
| 40 |
+
|
| 41 |
+
Architecture:
|
| 42 |
+
4 convolutional blocks (32, 64, 128, 256 channels)
|
| 43 |
+
-> adaptive average pooling to a fixed 4x4 grid
|
| 44 |
+
-> Linear(4096, 512) + ReLU + Dropout
|
| 45 |
+
-> Linear(512, num_classes)
|
| 46 |
+
|
| 47 |
+
The adaptive pooling layer makes the classifier head independent of the
|
| 48 |
+
input resolution. The model outputs unnormalized logits, which is the input
|
| 49 |
+
format expected by ``nn.CrossEntropyLoss``.
|
| 50 |
+
"""
|
| 51 |
+
|
| 52 |
+
def __init__(self, num_classes: int = NUM_CLASSES, dropout: float = 0.5) -> None:
|
| 53 |
+
super().__init__()
|
| 54 |
+
self.features = nn.Sequential(
|
| 55 |
+
_conv_block(3, 32),
|
| 56 |
+
_conv_block(32, 64),
|
| 57 |
+
_conv_block(64, 128),
|
| 58 |
+
_conv_block(128, 256),
|
| 59 |
+
)
|
| 60 |
+
self.pool = nn.AdaptiveAvgPool2d((4, 4))
|
| 61 |
+
self.classifier = nn.Sequential(
|
| 62 |
+
nn.Flatten(),
|
| 63 |
+
nn.Linear(256 * 4 * 4, 512),
|
| 64 |
+
nn.ReLU(inplace=True),
|
| 65 |
+
nn.Dropout(p=dropout),
|
| 66 |
+
nn.Linear(512, num_classes),
|
| 67 |
+
)
|
| 68 |
+
|
| 69 |
+
def forward(self, x: torch.Tensor) -> torch.Tensor:
|
| 70 |
+
"""Map a batch of images (N, 3, H, W) to logits (N, num_classes)."""
|
| 71 |
+
x = self.features(x)
|
| 72 |
+
x = self.pool(x)
|
| 73 |
+
return self.classifier(x)
|
| 74 |
+
|
| 75 |
+
|
| 76 |
+
def build_resnet18_classifier(
|
| 77 |
+
num_classes: int = NUM_CLASSES,
|
| 78 |
+
pretrained: bool = True,
|
| 79 |
+
dropout: float = 0.3,
|
| 80 |
+
) -> nn.Module:
|
| 81 |
+
"""Create a ResNet18 whose final layer is replaced for ``num_classes`` outputs.
|
| 82 |
+
|
| 83 |
+
Args:
|
| 84 |
+
num_classes: Number of output classes.
|
| 85 |
+
pretrained: If True, initialize the backbone with ImageNet weights
|
| 86 |
+
(requires a download on first use). Use False at inference time,
|
| 87 |
+
because the fine-tuned weights are loaded from ``pet_breed_model.pth``.
|
| 88 |
+
dropout: Dropout probability applied before the new linear layer.
|
| 89 |
+
"""
|
| 90 |
+
weights = models.ResNet18_Weights.IMAGENET1K_V1 if pretrained else None
|
| 91 |
+
network = models.resnet18(weights=weights)
|
| 92 |
+
network.fc = nn.Sequential(
|
| 93 |
+
nn.Dropout(p=dropout),
|
| 94 |
+
nn.Linear(network.fc.in_features, num_classes),
|
| 95 |
+
)
|
| 96 |
+
return network
|
| 97 |
+
|
| 98 |
+
|
| 99 |
+
def count_parameters(network: nn.Module) -> dict[str, int]:
|
| 100 |
+
"""Return the total and trainable parameter counts of ``network``."""
|
| 101 |
+
total = sum(parameter.numel() for parameter in network.parameters())
|
| 102 |
+
trainable = sum(
|
| 103 |
+
parameter.numel() for parameter in network.parameters() if parameter.requires_grad
|
| 104 |
+
)
|
| 105 |
+
return {"total": total, "trainable": trainable}
|
src/utils.py
ADDED
|
@@ -0,0 +1,475 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Shared helpers: class metadata, timed inference, training loop, and metrics.
|
| 2 |
+
|
| 3 |
+
The inference helpers (``predict_image`` and the species mapping) depend only on
|
| 4 |
+
``torch``, ``torchvision``, and ``Pillow`` so that ``app.py`` can import this
|
| 5 |
+
module in the deployment environment. Training-time metrics rely on
|
| 6 |
+
``scikit-learn`` and ``matplotlib``, which are imported lazily inside the
|
| 7 |
+
functions that need them.
|
| 8 |
+
"""
|
| 9 |
+
|
| 10 |
+
from __future__ import annotations
|
| 11 |
+
|
| 12 |
+
import copy
|
| 13 |
+
import random
|
| 14 |
+
import time
|
| 15 |
+
from typing import Any
|
| 16 |
+
|
| 17 |
+
import numpy as np
|
| 18 |
+
import torch
|
| 19 |
+
from PIL import Image
|
| 20 |
+
from torch import nn
|
| 21 |
+
from torch.utils.data import DataLoader
|
| 22 |
+
|
| 23 |
+
from .dataset import build_eval_transform
|
| 24 |
+
|
| 25 |
+
# Class names in the label order used by torchvision.datasets.OxfordIIITPet.
|
| 26 |
+
CLASS_NAMES: tuple[str, ...] = (
|
| 27 |
+
"Abyssinian",
|
| 28 |
+
"American Bulldog",
|
| 29 |
+
"American Pit Bull Terrier",
|
| 30 |
+
"Basset Hound",
|
| 31 |
+
"Beagle",
|
| 32 |
+
"Bengal",
|
| 33 |
+
"Birman",
|
| 34 |
+
"Bombay",
|
| 35 |
+
"Boxer",
|
| 36 |
+
"British Shorthair",
|
| 37 |
+
"Chihuahua",
|
| 38 |
+
"Egyptian Mau",
|
| 39 |
+
"English Cocker Spaniel",
|
| 40 |
+
"English Setter",
|
| 41 |
+
"German Shorthaired",
|
| 42 |
+
"Great Pyrenees",
|
| 43 |
+
"Havanese",
|
| 44 |
+
"Japanese Chin",
|
| 45 |
+
"Keeshond",
|
| 46 |
+
"Leonberger",
|
| 47 |
+
"Maine Coon",
|
| 48 |
+
"Miniature Pinscher",
|
| 49 |
+
"Newfoundland",
|
| 50 |
+
"Persian",
|
| 51 |
+
"Pomeranian",
|
| 52 |
+
"Pug",
|
| 53 |
+
"Ragdoll",
|
| 54 |
+
"Russian Blue",
|
| 55 |
+
"Saint Bernard",
|
| 56 |
+
"Samoyed",
|
| 57 |
+
"Scottish Terrier",
|
| 58 |
+
"Shiba Inu",
|
| 59 |
+
"Siamese",
|
| 60 |
+
"Sphynx",
|
| 61 |
+
"Staffordshire Bull Terrier",
|
| 62 |
+
"Wheaten Terrier",
|
| 63 |
+
"Yorkshire Terrier",
|
| 64 |
+
)
|
| 65 |
+
|
| 66 |
+
CAT_BREEDS: frozenset[str] = frozenset(
|
| 67 |
+
{
|
| 68 |
+
"Abyssinian",
|
| 69 |
+
"Bengal",
|
| 70 |
+
"Birman",
|
| 71 |
+
"Bombay",
|
| 72 |
+
"British Shorthair",
|
| 73 |
+
"Egyptian Mau",
|
| 74 |
+
"Maine Coon",
|
| 75 |
+
"Persian",
|
| 76 |
+
"Ragdoll",
|
| 77 |
+
"Russian Blue",
|
| 78 |
+
"Siamese",
|
| 79 |
+
"Sphynx",
|
| 80 |
+
}
|
| 81 |
+
)
|
| 82 |
+
|
| 83 |
+
|
| 84 |
+
# ---------------------------------------------------------------------------
|
| 85 |
+
# Reproducibility and class metadata
|
| 86 |
+
# ---------------------------------------------------------------------------
|
| 87 |
+
def set_seed(seed: int = 42) -> None:
|
| 88 |
+
"""Seed Python, NumPy, and PyTorch (CPU and CUDA) for reproducible runs."""
|
| 89 |
+
random.seed(seed)
|
| 90 |
+
np.random.seed(seed)
|
| 91 |
+
torch.manual_seed(seed)
|
| 92 |
+
if torch.cuda.is_available():
|
| 93 |
+
torch.cuda.manual_seed_all(seed)
|
| 94 |
+
|
| 95 |
+
|
| 96 |
+
def get_species(predicted_breed: str) -> str:
|
| 97 |
+
"""Resolve species from a predicted breed using the fixed cat-breed set."""
|
| 98 |
+
return "Cat" if predicted_breed in CAT_BREEDS else "Dog"
|
| 99 |
+
|
| 100 |
+
|
| 101 |
+
def format_breed_name(breed: str) -> str:
|
| 102 |
+
"""Convert a dataset class name (for example 'american bulldog') to display form."""
|
| 103 |
+
return breed.title()
|
| 104 |
+
|
| 105 |
+
|
| 106 |
+
# ---------------------------------------------------------------------------
|
| 107 |
+
# Single-image inference with latency measurement
|
| 108 |
+
# ---------------------------------------------------------------------------
|
| 109 |
+
def predict_image(
|
| 110 |
+
network: nn.Module,
|
| 111 |
+
image: Image.Image,
|
| 112 |
+
device: torch.device | str,
|
| 113 |
+
transform: Any = None,
|
| 114 |
+
class_names: tuple[str, ...] = CLASS_NAMES,
|
| 115 |
+
top_k: int = 3,
|
| 116 |
+
) -> dict[str, Any]:
|
| 117 |
+
"""Classify one PIL image and measure the forward-pass latency.
|
| 118 |
+
|
| 119 |
+
The reported ``inference_seconds`` covers the forward pass and softmax, as
|
| 120 |
+
specified in the project guidelines. Preprocessing time is reported
|
| 121 |
+
separately as ``preprocessing_seconds`` so that both figures are available.
|
| 122 |
+
|
| 123 |
+
Returns:
|
| 124 |
+
A dictionary with the predicted breed, species, the top-k predictions,
|
| 125 |
+
the full probability dictionary, and the timing measurements.
|
| 126 |
+
"""
|
| 127 |
+
device = torch.device(device)
|
| 128 |
+
transform = transform if transform is not None else build_eval_transform()
|
| 129 |
+
|
| 130 |
+
preprocessing_start = time.perf_counter()
|
| 131 |
+
# transform(...) yields a (3, H, W) tensor; unsqueeze(0) prepends the batch
|
| 132 |
+
# dimension so the network receives (1, 3, H, W).
|
| 133 |
+
image_tensor = transform(image.convert("RGB")).unsqueeze(0).to(device)
|
| 134 |
+
preprocessing_seconds = time.perf_counter() - preprocessing_start
|
| 135 |
+
|
| 136 |
+
network.eval()
|
| 137 |
+
if device.type == "cuda":
|
| 138 |
+
torch.cuda.synchronize()
|
| 139 |
+
start_time = time.perf_counter()
|
| 140 |
+
with torch.inference_mode():
|
| 141 |
+
logits = network(image_tensor)
|
| 142 |
+
probs = torch.softmax(logits, dim=1)
|
| 143 |
+
if device.type == "cuda":
|
| 144 |
+
torch.cuda.synchronize()
|
| 145 |
+
inference_time = time.perf_counter() - start_time
|
| 146 |
+
|
| 147 |
+
# probs has shape (1, num_classes); squeeze(0) removes only the batch axis.
|
| 148 |
+
probability_vector = probs.squeeze(0).cpu()
|
| 149 |
+
top_values, top_indices = torch.topk(probability_vector, k=top_k)
|
| 150 |
+
top_predictions = [
|
| 151 |
+
(class_names[index], float(value))
|
| 152 |
+
for value, index in zip(top_values.tolist(), top_indices.tolist())
|
| 153 |
+
]
|
| 154 |
+
predicted_breed = top_predictions[0][0]
|
| 155 |
+
return {
|
| 156 |
+
"breed": predicted_breed,
|
| 157 |
+
"species": get_species(predicted_breed),
|
| 158 |
+
"confidence": top_predictions[0][1],
|
| 159 |
+
"top_predictions": top_predictions,
|
| 160 |
+
"probabilities": {
|
| 161 |
+
class_names[index]: float(value)
|
| 162 |
+
for index, value in enumerate(probability_vector.tolist())
|
| 163 |
+
},
|
| 164 |
+
"inference_seconds": inference_time,
|
| 165 |
+
"preprocessing_seconds": preprocessing_seconds,
|
| 166 |
+
}
|
| 167 |
+
|
| 168 |
+
|
| 169 |
+
def benchmark_latency(
|
| 170 |
+
network: nn.Module,
|
| 171 |
+
images: list[Image.Image],
|
| 172 |
+
device: torch.device | str,
|
| 173 |
+
warmup: int = 3,
|
| 174 |
+
) -> dict[str, float]:
|
| 175 |
+
"""Measure single-image latency statistics over a list of PIL images."""
|
| 176 |
+
for warmup_image in images[:warmup]:
|
| 177 |
+
predict_image(network, warmup_image, device)
|
| 178 |
+
timings = np.array(
|
| 179 |
+
[predict_image(network, sample, device)["inference_seconds"] for sample in images]
|
| 180 |
+
)
|
| 181 |
+
return {
|
| 182 |
+
"mean_seconds": float(timings.mean()),
|
| 183 |
+
"std_seconds": float(timings.std()),
|
| 184 |
+
"median_seconds": float(np.median(timings)),
|
| 185 |
+
"max_seconds": float(timings.max()),
|
| 186 |
+
"samples": int(len(timings)),
|
| 187 |
+
}
|
| 188 |
+
|
| 189 |
+
|
| 190 |
+
# ---------------------------------------------------------------------------
|
| 191 |
+
# Training and evaluation loops
|
| 192 |
+
# ---------------------------------------------------------------------------
|
| 193 |
+
def train_one_epoch(
|
| 194 |
+
network: nn.Module,
|
| 195 |
+
loader: DataLoader,
|
| 196 |
+
criterion: nn.Module,
|
| 197 |
+
optimizer: torch.optim.Optimizer,
|
| 198 |
+
device: torch.device | str,
|
| 199 |
+
) -> dict[str, float]:
|
| 200 |
+
"""Run one optimization pass over ``loader`` and return mean loss and accuracy."""
|
| 201 |
+
network.train()
|
| 202 |
+
loss_sum, correct, seen = 0.0, 0, 0
|
| 203 |
+
for batch_images, batch_labels in loader:
|
| 204 |
+
batch_images = batch_images.to(device, non_blocking=True)
|
| 205 |
+
batch_labels = batch_labels.to(device, non_blocking=True)
|
| 206 |
+
|
| 207 |
+
optimizer.zero_grad(set_to_none=True)
|
| 208 |
+
logits = network(batch_images)
|
| 209 |
+
loss_value = criterion(logits, batch_labels)
|
| 210 |
+
loss_value.backward()
|
| 211 |
+
optimizer.step()
|
| 212 |
+
|
| 213 |
+
batch_size = batch_labels.size(0)
|
| 214 |
+
loss_sum += loss_value.item() * batch_size
|
| 215 |
+
correct += (logits.argmax(dim=1) == batch_labels).sum().item()
|
| 216 |
+
seen += batch_size
|
| 217 |
+
return {"loss": loss_sum / seen, "accuracy": correct / seen}
|
| 218 |
+
|
| 219 |
+
|
| 220 |
+
def evaluate_loader(
|
| 221 |
+
network: nn.Module,
|
| 222 |
+
loader: DataLoader,
|
| 223 |
+
criterion: nn.Module,
|
| 224 |
+
device: torch.device | str,
|
| 225 |
+
) -> dict[str, Any]:
|
| 226 |
+
"""Evaluate ``network`` on ``loader`` without gradient tracking.
|
| 227 |
+
|
| 228 |
+
Returns the mean loss, accuracy, and the true and predicted label arrays so
|
| 229 |
+
that downstream code can compute precision, recall, F1, and the confusion
|
| 230 |
+
matrix.
|
| 231 |
+
"""
|
| 232 |
+
network.eval()
|
| 233 |
+
loss_sum, seen = 0.0, 0
|
| 234 |
+
true_batches: list[np.ndarray] = []
|
| 235 |
+
predicted_batches: list[np.ndarray] = []
|
| 236 |
+
with torch.inference_mode():
|
| 237 |
+
for batch_images, batch_labels in loader:
|
| 238 |
+
batch_images = batch_images.to(device, non_blocking=True)
|
| 239 |
+
batch_labels = batch_labels.to(device, non_blocking=True)
|
| 240 |
+
|
| 241 |
+
logits = network(batch_images)
|
| 242 |
+
loss_value = criterion(logits, batch_labels)
|
| 243 |
+
|
| 244 |
+
loss_sum += loss_value.item() * batch_labels.size(0)
|
| 245 |
+
seen += batch_labels.size(0)
|
| 246 |
+
true_batches.append(batch_labels.cpu().numpy())
|
| 247 |
+
predicted_batches.append(logits.argmax(dim=1).cpu().numpy())
|
| 248 |
+
true_labels = np.concatenate(true_batches)
|
| 249 |
+
predicted_labels = np.concatenate(predicted_batches)
|
| 250 |
+
return {
|
| 251 |
+
"loss": loss_sum / seen,
|
| 252 |
+
"accuracy": float((true_labels == predicted_labels).mean()),
|
| 253 |
+
"y_true": true_labels,
|
| 254 |
+
"y_pred": predicted_labels,
|
| 255 |
+
}
|
| 256 |
+
|
| 257 |
+
|
| 258 |
+
def fit_model(
|
| 259 |
+
network: nn.Module,
|
| 260 |
+
loaders: dict[str, DataLoader],
|
| 261 |
+
criterion: nn.Module,
|
| 262 |
+
optimizer: torch.optim.Optimizer,
|
| 263 |
+
scheduler: torch.optim.lr_scheduler.ReduceLROnPlateau,
|
| 264 |
+
device: torch.device | str,
|
| 265 |
+
max_epochs: int,
|
| 266 |
+
early_stopping_patience: int,
|
| 267 |
+
run_name: str = "model",
|
| 268 |
+
) -> dict[str, Any]:
|
| 269 |
+
"""Train with validation-loss monitoring, LR scheduling, and early stopping.
|
| 270 |
+
|
| 271 |
+
``scheduler`` is stepped on the validation loss. Training stops when the
|
| 272 |
+
validation loss has not improved for ``early_stopping_patience`` epochs. The
|
| 273 |
+
weights from the epoch with the lowest validation loss are returned.
|
| 274 |
+
"""
|
| 275 |
+
history: dict[str, list[float]] = {
|
| 276 |
+
"train_loss": [],
|
| 277 |
+
"train_accuracy": [],
|
| 278 |
+
"validation_loss": [],
|
| 279 |
+
"validation_accuracy": [],
|
| 280 |
+
"learning_rate": [],
|
| 281 |
+
}
|
| 282 |
+
best_validation_loss = float("inf")
|
| 283 |
+
best_validation_accuracy = 0.0
|
| 284 |
+
best_epoch = 0
|
| 285 |
+
best_state: dict[str, torch.Tensor] = {}
|
| 286 |
+
epochs_without_improvement = 0
|
| 287 |
+
training_start = time.perf_counter()
|
| 288 |
+
|
| 289 |
+
for epoch in range(1, max_epochs + 1):
|
| 290 |
+
train_scores = train_one_epoch(network, loaders["train"], criterion, optimizer, device)
|
| 291 |
+
validation_scores = evaluate_loader(network, loaders["validation"], criterion, device)
|
| 292 |
+
scheduler.step(validation_scores["loss"])
|
| 293 |
+
|
| 294 |
+
history["train_loss"].append(train_scores["loss"])
|
| 295 |
+
history["train_accuracy"].append(train_scores["accuracy"])
|
| 296 |
+
history["validation_loss"].append(validation_scores["loss"])
|
| 297 |
+
history["validation_accuracy"].append(validation_scores["accuracy"])
|
| 298 |
+
history["learning_rate"].append(optimizer.param_groups[0]["lr"])
|
| 299 |
+
|
| 300 |
+
improved = validation_scores["loss"] < best_validation_loss
|
| 301 |
+
if improved:
|
| 302 |
+
best_validation_loss = validation_scores["loss"]
|
| 303 |
+
best_validation_accuracy = validation_scores["accuracy"]
|
| 304 |
+
best_epoch = epoch
|
| 305 |
+
best_state = copy.deepcopy(
|
| 306 |
+
{key: value.detach().cpu() for key, value in network.state_dict().items()}
|
| 307 |
+
)
|
| 308 |
+
epochs_without_improvement = 0
|
| 309 |
+
else:
|
| 310 |
+
epochs_without_improvement += 1
|
| 311 |
+
|
| 312 |
+
print(
|
| 313 |
+
f"[{run_name}] epoch {epoch:02d}/{max_epochs} | "
|
| 314 |
+
f"train loss {train_scores['loss']:.4f} acc {train_scores['accuracy']:.4f} | "
|
| 315 |
+
f"val loss {validation_scores['loss']:.4f} acc {validation_scores['accuracy']:.4f} | "
|
| 316 |
+
f"lr {history['learning_rate'][-1]:.2e}" + (" *" if improved else "")
|
| 317 |
+
)
|
| 318 |
+
if epochs_without_improvement >= early_stopping_patience:
|
| 319 |
+
print(f"[{run_name}] early stopping at epoch {epoch} (best epoch {best_epoch}).")
|
| 320 |
+
break
|
| 321 |
+
|
| 322 |
+
network.load_state_dict(best_state)
|
| 323 |
+
return {
|
| 324 |
+
"history": history,
|
| 325 |
+
"best_epoch": best_epoch,
|
| 326 |
+
"best_validation_loss": best_validation_loss,
|
| 327 |
+
"best_validation_accuracy": best_validation_accuracy,
|
| 328 |
+
"epochs_run": len(history["train_loss"]),
|
| 329 |
+
"training_seconds": time.perf_counter() - training_start,
|
| 330 |
+
"best_state": best_state,
|
| 331 |
+
}
|
| 332 |
+
|
| 333 |
+
|
| 334 |
+
# ---------------------------------------------------------------------------
|
| 335 |
+
# Metrics and plots (training environment only)
|
| 336 |
+
# ---------------------------------------------------------------------------
|
| 337 |
+
def compute_classification_metrics(
|
| 338 |
+
y_true: np.ndarray,
|
| 339 |
+
y_pred: np.ndarray,
|
| 340 |
+
class_names: tuple[str, ...] = CLASS_NAMES,
|
| 341 |
+
) -> dict[str, Any]:
|
| 342 |
+
"""Compute breed-level and derived species-level classification metrics."""
|
| 343 |
+
from sklearn.metrics import (
|
| 344 |
+
accuracy_score,
|
| 345 |
+
classification_report,
|
| 346 |
+
confusion_matrix,
|
| 347 |
+
precision_recall_fscore_support,
|
| 348 |
+
)
|
| 349 |
+
|
| 350 |
+
label_ids = list(range(len(class_names)))
|
| 351 |
+
macro_precision, macro_recall, macro_f1, _ = precision_recall_fscore_support(
|
| 352 |
+
y_true, y_pred, labels=label_ids, average="macro", zero_division=0
|
| 353 |
+
)
|
| 354 |
+
weighted_precision, weighted_recall, weighted_f1, _ = precision_recall_fscore_support(
|
| 355 |
+
y_true, y_pred, labels=label_ids, average="weighted", zero_division=0
|
| 356 |
+
)
|
| 357 |
+
|
| 358 |
+
species_true = np.array([get_species(class_names[index]) for index in y_true])
|
| 359 |
+
species_pred = np.array([get_species(class_names[index]) for index in y_pred])
|
| 360 |
+
|
| 361 |
+
return {
|
| 362 |
+
"accuracy": float(accuracy_score(y_true, y_pred)),
|
| 363 |
+
"macro_precision": float(macro_precision),
|
| 364 |
+
"macro_recall": float(macro_recall),
|
| 365 |
+
"macro_f1": float(macro_f1),
|
| 366 |
+
"weighted_precision": float(weighted_precision),
|
| 367 |
+
"weighted_recall": float(weighted_recall),
|
| 368 |
+
"weighted_f1": float(weighted_f1),
|
| 369 |
+
"species_accuracy": float(accuracy_score(species_true, species_pred)),
|
| 370 |
+
"confusion_matrix": confusion_matrix(y_true, y_pred, labels=label_ids),
|
| 371 |
+
"species_confusion_matrix": confusion_matrix(
|
| 372 |
+
species_true, species_pred, labels=["Cat", "Dog"]
|
| 373 |
+
),
|
| 374 |
+
"report": classification_report(
|
| 375 |
+
y_true,
|
| 376 |
+
y_pred,
|
| 377 |
+
labels=label_ids,
|
| 378 |
+
target_names=[format_breed_name(name) for name in class_names],
|
| 379 |
+
zero_division=0,
|
| 380 |
+
),
|
| 381 |
+
}
|
| 382 |
+
|
| 383 |
+
|
| 384 |
+
def top_confusions(
|
| 385 |
+
confusion: np.ndarray,
|
| 386 |
+
class_names: tuple[str, ...] = CLASS_NAMES,
|
| 387 |
+
count: int = 10,
|
| 388 |
+
) -> list[tuple[str, str, int]]:
|
| 389 |
+
"""Return the most frequent off-diagonal (true, predicted, count) breed pairs."""
|
| 390 |
+
off_diagonal = confusion.copy()
|
| 391 |
+
np.fill_diagonal(off_diagonal, 0)
|
| 392 |
+
flat_order = np.argsort(off_diagonal, axis=None)[::-1][:count]
|
| 393 |
+
pairs: list[tuple[str, str, int]] = []
|
| 394 |
+
for flat_index in flat_order:
|
| 395 |
+
true_index, predicted_index = np.unravel_index(flat_index, off_diagonal.shape)
|
| 396 |
+
if off_diagonal[true_index, predicted_index] == 0:
|
| 397 |
+
break
|
| 398 |
+
pairs.append(
|
| 399 |
+
(
|
| 400 |
+
format_breed_name(class_names[true_index]),
|
| 401 |
+
format_breed_name(class_names[predicted_index]),
|
| 402 |
+
int(off_diagonal[true_index, predicted_index]),
|
| 403 |
+
)
|
| 404 |
+
)
|
| 405 |
+
return pairs
|
| 406 |
+
|
| 407 |
+
|
| 408 |
+
def plot_confusion_matrix(
|
| 409 |
+
confusion: np.ndarray,
|
| 410 |
+
class_names: tuple[str, ...] | list[str],
|
| 411 |
+
title: str,
|
| 412 |
+
normalize: bool = True,
|
| 413 |
+
):
|
| 414 |
+
"""Render a confusion matrix heat map and return the matplotlib figure."""
|
| 415 |
+
import matplotlib.pyplot as plt
|
| 416 |
+
|
| 417 |
+
matrix = confusion.astype(float)
|
| 418 |
+
if normalize:
|
| 419 |
+
row_totals = matrix.sum(axis=1, keepdims=True)
|
| 420 |
+
matrix = np.divide(matrix, row_totals, out=np.zeros_like(matrix), where=row_totals > 0)
|
| 421 |
+
|
| 422 |
+
large = len(class_names) > 10
|
| 423 |
+
figure, axes = plt.subplots(figsize=(14, 12) if large else (5, 4))
|
| 424 |
+
image_artist = axes.imshow(matrix, cmap="Blues", vmin=0.0, vmax=1.0 if normalize else None)
|
| 425 |
+
figure.colorbar(image_artist, ax=axes, fraction=0.046, pad=0.04)
|
| 426 |
+
axes.set_xticks(range(len(class_names)))
|
| 427 |
+
axes.set_yticks(range(len(class_names)))
|
| 428 |
+
labels = [format_breed_name(name) for name in class_names] if large else list(class_names)
|
| 429 |
+
axes.set_xticklabels(labels, rotation=90, fontsize=7 if large else 10)
|
| 430 |
+
axes.set_yticklabels(labels, fontsize=7 if large else 10)
|
| 431 |
+
axes.set_xlabel("Predicted label")
|
| 432 |
+
axes.set_ylabel("True label")
|
| 433 |
+
axes.set_title(title)
|
| 434 |
+
if not large:
|
| 435 |
+
for row in range(matrix.shape[0]):
|
| 436 |
+
for column in range(matrix.shape[1]):
|
| 437 |
+
axes.text(
|
| 438 |
+
column,
|
| 439 |
+
row,
|
| 440 |
+
f"{confusion[row, column]}",
|
| 441 |
+
ha="center",
|
| 442 |
+
va="center",
|
| 443 |
+
color="white" if matrix[row, column] > 0.5 else "black",
|
| 444 |
+
)
|
| 445 |
+
figure.tight_layout()
|
| 446 |
+
return figure
|
| 447 |
+
|
| 448 |
+
|
| 449 |
+
def plot_training_curves(fit_results: dict[str, dict[str, Any]]):
|
| 450 |
+
"""Plot loss and accuracy curves for each named training run."""
|
| 451 |
+
import matplotlib.pyplot as plt
|
| 452 |
+
|
| 453 |
+
figure, (loss_axes, accuracy_axes) = plt.subplots(1, 2, figsize=(13, 4.5))
|
| 454 |
+
for run_name, result in fit_results.items():
|
| 455 |
+
run_history = result["history"]
|
| 456 |
+
epochs = range(1, len(run_history["train_loss"]) + 1)
|
| 457 |
+
loss_axes.plot(epochs, run_history["train_loss"], linestyle="--", label=f"{run_name} train")
|
| 458 |
+
loss_axes.plot(epochs, run_history["validation_loss"], label=f"{run_name} validation")
|
| 459 |
+
accuracy_axes.plot(
|
| 460 |
+
epochs, run_history["train_accuracy"], linestyle="--", label=f"{run_name} train"
|
| 461 |
+
)
|
| 462 |
+
accuracy_axes.plot(
|
| 463 |
+
epochs, run_history["validation_accuracy"], label=f"{run_name} validation"
|
| 464 |
+
)
|
| 465 |
+
loss_axes.set_title("Cross-entropy loss")
|
| 466 |
+
loss_axes.set_xlabel("Epoch")
|
| 467 |
+
loss_axes.set_ylabel("Loss")
|
| 468 |
+
accuracy_axes.set_title("Accuracy")
|
| 469 |
+
accuracy_axes.set_xlabel("Epoch")
|
| 470 |
+
accuracy_axes.set_ylabel("Accuracy")
|
| 471 |
+
for axes in (loss_axes, accuracy_axes):
|
| 472 |
+
axes.grid(alpha=0.3)
|
| 473 |
+
axes.legend()
|
| 474 |
+
figure.tight_layout()
|
| 475 |
+
return figure
|
uv.lock
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|