Spaces:
Sleeping
Sleeping
File size: 22,455 Bytes
2952455 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 | """Shared helpers: class metadata, timed inference, training loop, and metrics.
The inference helpers (``predict_image`` and the species mapping) depend only on
``torch``, ``torchvision``, and ``Pillow`` (Pythons image pricessing library to open, manipulate, convert (to RGB foo ex) and save images)
so that ``app.py`` can import this module in the deployment environment. Training-time metrics rely on
``scikit-learn`` and ``matplotlib``, which are imported lazily inside the
functions that need them.
"""
from __future__ import annotations
import copy
import random
import time
from typing import Any
import numpy as np
import torch
from PIL import Image
from torch import nn
from torch.utils.data import DataLoader
from .dataset import build_eval_transform
# Class names in the label order used by torchvision.datasets.OxfordIIITPet.
# If the predicted breed is in CAT_BREEDS, it's a "Cat"; otherwise, it's a "Dog".
CLASS_NAMES: tuple[str, ...] = (
"Abyssinian",
"American Bulldog",
"American Pit Bull Terrier",
"Basset Hound",
"Beagle",
"Bengal",
"Birman",
"Bombay",
"Boxer",
"British Shorthair",
"Chihuahua",
"Egyptian Mau",
"English Cocker Spaniel",
"English Setter",
"German Shorthaired",
"Great Pyrenees",
"Havanese",
"Japanese Chin",
"Keeshond",
"Leonberger",
"Maine Coon",
"Miniature Pinscher",
"Newfoundland",
"Persian",
"Pomeranian",
"Pug",
"Ragdoll",
"Russian Blue",
"Saint Bernard",
"Samoyed",
"Scottish Terrier",
"Shiba Inu",
"Siamese",
"Sphynx",
"Staffordshire Bull Terrier",
"Wheaten Terrier",
"Yorkshire Terrier",
)
# frozen set used to limit O value (O(1) vs (O(N) --> which scans one by one and all of them)). Frozen set is immutable.
CAT_BREEDS: frozenset[str] = frozenset(
{
"Abyssinian",
"Bengal",
"Birman",
"Bombay",
"British Shorthair",
"Egyptian Mau",
"Maine Coon",
"Persian",
"Ragdoll",
"Russian Blue",
"Siamese",
"Sphynx",
}
)
# Reproducibility and class metadata
# region
## set_seed function: sets pseudo-random number generators (PRNG) for
### Python's builting PRNG --> random.seed(seed); NumPy's PRNG; Pytorches CPU (PRNG); and PyTorch GPU (PRNG)
## seed: 42 --> reproducibility for training and evaluation
## This allows for a higher level of randomness.
# endregion
def set_seed(seed: int = 42) -> None:
"""Seed Python, NumPy, and PyTorch (CPU and CUDA) for reproducible runs."""
random.seed(seed)
np.random.seed(seed)
torch.manual_seed(seed)
if torch.cuda.is_available():
torch.cuda.manual_seed_all(seed)
# Accepts a single string representing the predicted breed name
def get_species(predicted_breed: str) -> str:
"""Resolve species from a predicted breed using the fixed cat-breed set."""
return "Cat" if predicted_breed in CAT_BREEDS else "Dog"
# Capitalizes the first letter of each word and lowers all other letters
def format_breed_name(breed: str) -> str:
"""Convert a dataset class name (for example 'american bulldog') to display form."""
return breed.title()
# Single-image inference with latency measurement
# region
## predict_image function: handles single-image inference by taking a raw image,
### formatting it for the model, executing a forward pass, and computing prediction metrics alongside runtime latency.
## network: nn.Module: Passing in which model to use to evaluate (either my custom PetBreedCNN or ResNet18)
## image: Image.Image: input the picture as a Pillow image
## device: torch.device: will pass in either cuda or cpu
## transform: Any = None: Vision preprocessing pipeline. WIll use default evaluation if transforms no passed
## class_names: tuple[str, ...] = CLASS_NAMES: Passing in the 37 breed tuple
## top_k: int = 3: will return top three candidates
## dict[str, Any]: Returns a dict of packaging predictions, confidence scores, species, and latency numbers
# endregion
def predict_image(
network: nn.Module,
image: Image.Image,
device: torch.device | str,
transform: Any = None,
class_names: tuple[str, ...] = CLASS_NAMES,
top_k: int = 3,
) -> dict[str, Any]:
"""Classify one PIL image and measure the forward-pass latency.
The reported ``inference_seconds`` covers the forward pass and softmax, as
specified in the project guidelines. Preprocessing time is reported
separately as ``preprocessing_seconds`` so that both figures are available.
Returns:
A dictionary with the predicted breed, species, the top-k predictions,
the full probability dictionary, and the timing measurements.
"""
# region
## strongly type the cuda or cpu for torch.device objects
## transform: if a custom 'transform' is not provided, will imports an dbuilds standard evaulation (resizing,
## center, ImageNet normalization)
### Imagenet normalilzation: cpmverts pixal brightnessfrom numbers 0-255 to decimals between 0-1 (transform.totensor)
### For ResNet weights were trained on photos scalled
# endregion
device = torch.device(device)
transform = transform if transform is not None else build_eval_transform()
# region
## transform(...) yields a (3, H, W) tensor; unsqueeze(0) prepends the batch
## dimension so the network receives (1, 3, H, W).
## image.convert("RGB"): Strips alpha transparency channels (RGBA) or expands grayscale images into 3
### color channels.image.convert("RGB"): Strips alpha transparency channels (RGBA) or expands grayscale images
### into 3 color channels.
## .unsqueeze(0): Prepends a batch dimension, converting (3, H, W) into (1, 3, H, W) because convolutional
### layers strictly expect a 4D batch tensor.
## time.perf_counter(): tracks how long in soconds for data prep
# endregion
preprocessing_start = time.perf_counter()
image_tensor = transform(image.convert("RGB")).unsqueeze(0).to(device)
preprocessing_seconds = time.perf_counter() - preprocessing_start
# region
## network.eval(): Shuts off training-specific mechanics like Dropout and switches BatchNorm to population statistics.
###
## with torch.inference_mode(): Temp. disabled pytorch autograd tracking to reduce compute
## logits = network(image_tensor): produces raw 37 class output numbers
## probs = torch.softmax(logits, dim=1): normalizes raw logits into positive probabilities
### that sum to 1.0 along class dimension
# endregion
network.eval()
if device.type == "cuda":
torch.cuda.synchronize()
start_time = time.perf_counter()
with torch.inference_mode():
logits = network(image_tensor)
probs = torch.softmax(logits, dim=1)
if device.type == "cuda":
torch.cuda.synchronize()
inference_time = time.perf_counter() - start_time
# region
## probs.squeeze(0).cpu(): Removes the batch dimension to make a 1D vector of
### 37 probabilities and moves it to CPU memory for Python operations.
## torch.topk(..., k=top_k): Extracts the $k$ highest probability values
### along with their corresponding class index positions.
## top_predictions: Creates a list of (breed_name, confidence_score) tuples
### (e.g., [("Beagle", 0.92), ("Basset Hound", 0.05), ...]), where index 0 represents the primary prediction.
# endregion
probability_vector = probs.squeeze(0).cpu()
top_values, top_indices = torch.topk(probability_vector, k=top_k)
top_predictions = [
(class_names[index], float(value))
for value, index in zip(top_values.tolist(), top_indices.tolist())
]
predicted_breed = top_predictions[0][0]
# Returns a dict with breed, species, confidence score, top_predictions, probabilities, processing time
return {
"breed": predicted_breed,
"species": get_species(predicted_breed),
"confidence": top_predictions[0][1],
"top_predictions": top_predictions,
"probabilities": {
class_names[index]: float(value)
for index, value in enumerate(probability_vector.tolist())
},
"inference_seconds": inference_time,
"preprocessing_seconds": preprocessing_seconds,
}
# region
## benchmark_latency function measures execution speed across multiple test
### images and calculates statistical metrics (mean, standard deviation, median, max)
### to assess real-world inference performance.
## ResNet-18 will likely achieve higher accuracy, but it has ~11.2 million parameters.
## PetBreedCNN has far fewer convolutional layers and may run with lower latency depending on the batch size and hardware.
## This function generates the concrete latency metrics needed to build a comparison table contrasting Accuracy vs.
### Computational Efficiency (FPS/latency).
# endregion
def benchmark_latency(
network: nn.Module,
images: list[Image.Image],
device: torch.device | str,
warmup: int = 3,
) -> dict[str, float]:
"""Measure single-image latency statistics over a list of PIL images."""
for warmup_image in images[:warmup]:
predict_image(network, warmup_image, device)
timings = np.array(
[predict_image(network, sample, device)["inference_seconds"] for sample in images]
)
return {
"mean_seconds": float(timings.mean()),
"std_seconds": float(timings.std()),
"median_seconds": float(np.median(timings)),
"max_seconds": float(timings.max()),
"samples": int(len(timings)),
}
# Training and evaluation loops
# region
## train_one_epoch function: manages a complete iteration over the training dataset,
### computing predictions, calculating error, backpropagating gradients, and updating parameters
# endregion
def train_one_epoch(
network: nn.Module,
loader: DataLoader,
criterion: nn.Module,
optimizer: torch.optim.Optimizer,
device: torch.device | str,
) -> dict[str, float]:
"""Run one optimization pass over ``loader`` and return mean loss and accuracy."""
network.train()
loss_sum, correct, seen = 0.0, 0, 0
for batch_images, batch_labels in loader:
batch_images = batch_images.to(device, non_blocking=True)
batch_labels = batch_labels.to(device, non_blocking=True)
optimizer.zero_grad(set_to_none=True)
logits = network(batch_images)
loss_value = criterion(logits, batch_labels)
loss_value.backward()
optimizer.step()
batch_size = batch_labels.size(0)
loss_sum += loss_value.item() * batch_size
correct += (logits.argmax(dim=1) == batch_labels).sum().item()
seen += batch_size
return {"loss": loss_sum / seen, "accuracy": correct / seen}
# region
## evaluate_loader evaluates a model across an entire validation or test dataset without
### updating weights or tracking gradients
# endregion
def evaluate_loader(
network: nn.Module,
loader: DataLoader,
criterion: nn.Module,
device: torch.device | str,
) -> dict[str, Any]:
"""Evaluate ``network`` on ``loader`` without gradient tracking.
Returns the mean loss, accuracy, and the true and predicted label arrays so
that downstream code can compute precision, recall, F1, and the confusion
matrix.
"""
network.eval()
loss_sum, seen = 0.0, 0
true_batches: list[np.ndarray] = []
predicted_batches: list[np.ndarray] = []
with torch.inference_mode():
for batch_images, batch_labels in loader:
batch_images = batch_images.to(device, non_blocking=True)
batch_labels = batch_labels.to(device, non_blocking=True)
logits = network(batch_images)
loss_value = criterion(logits, batch_labels)
loss_sum += loss_value.item() * batch_labels.size(0)
seen += batch_labels.size(0)
true_batches.append(batch_labels.cpu().numpy())
predicted_batches.append(logits.argmax(dim=1).cpu().numpy())
true_labels = np.concatenate(true_batches)
predicted_labels = np.concatenate(predicted_batches)
return {
"loss": loss_sum / seen,
"accuracy": float((true_labels == predicted_labels).mean()),
"y_true": true_labels,
"y_pred": predicted_labels,
}
# region
## fit_model function acts as the central training conductor, tying
### together epoch loops, learning rate scheduling, validation checks,
### deep-copy model checkpointing, and early stopping
## Returns a dictionary containing training history, top performance
### numbers, total elapsed training time, and the best state weights for saving to disk (e.g., pet_breed_model.pth).
# endregion
def fit_model(
network: nn.Module,
loaders: dict[str, DataLoader],
criterion: nn.Module,
optimizer: torch.optim.Optimizer,
scheduler: torch.optim.lr_scheduler.ReduceLROnPlateau,
device: torch.device | str,
max_epochs: int,
early_stopping_patience: int,
run_name: str = "model",
) -> dict[str, Any]:
"""Train with validation-loss monitoring, LR scheduling, and early stopping.
``scheduler`` is stepped on the validation loss. Training stops when the
validation loss has not improved for ``early_stopping_patience`` epochs. The
weights from the epoch with the lowest validation loss are returned.
"""
history: dict[str, list[float]] = {
"train_loss": [],
"train_accuracy": [],
"validation_loss": [],
"validation_accuracy": [],
"learning_rate": [],
}
best_validation_loss = float("inf")
best_validation_accuracy = 0.0
best_epoch = 0
best_state: dict[str, torch.Tensor] = {}
epochs_without_improvement = 0
training_start = time.perf_counter()
for epoch in range(1, max_epochs + 1):
train_scores = train_one_epoch(network, loaders["train"], criterion, optimizer, device)
validation_scores = evaluate_loader(network, loaders["validation"], criterion, device)
scheduler.step(validation_scores["loss"])
history["train_loss"].append(train_scores["loss"])
history["train_accuracy"].append(train_scores["accuracy"])
history["validation_loss"].append(validation_scores["loss"])
history["validation_accuracy"].append(validation_scores["accuracy"])
history["learning_rate"].append(optimizer.param_groups[0]["lr"])
improved = validation_scores["loss"] < best_validation_loss
if improved:
best_validation_loss = validation_scores["loss"]
best_validation_accuracy = validation_scores["accuracy"]
best_epoch = epoch
best_state = copy.deepcopy(
{key: value.detach().cpu() for key, value in network.state_dict().items()}
)
epochs_without_improvement = 0
else:
epochs_without_improvement += 1
print(
f"[{run_name}] epoch {epoch:02d}/{max_epochs} | "
f"train loss {train_scores['loss']:.4f} acc {train_scores['accuracy']:.4f} | "
f"val loss {validation_scores['loss']:.4f} acc {validation_scores['accuracy']:.4f} | "
f"lr {history['learning_rate'][-1]:.2e}" + (" *" if improved else "")
)
if epochs_without_improvement >= early_stopping_patience:
print(f"[{run_name}] early stopping at epoch {epoch} (best epoch {best_epoch}).")
break
network.load_state_dict(best_state)
return {
"history": history,
"best_epoch": best_epoch,
"best_validation_loss": best_validation_loss,
"best_validation_accuracy": best_validation_accuracy,
"epochs_run": len(history["train_loss"]),
"training_seconds": time.perf_counter() - training_start,
"best_state": best_state,
}
# Metrics and plots (training environment only)
# region
## compute_classification_metrics takes the flat NumPy arrays of ground-truth
### targets and model predictions generated during evaluation and computes fine-grained
### breed-level metrics alongside derived binary species-level metrics.
## A formatted text table generated by scikit-learn displaying precision, recall,
### and F1-score for each of the 37 breeds individually, formatted using format_breed_name, formatted nicely
# endregion
def compute_classification_metrics(
y_true: np.ndarray,
y_pred: np.ndarray,
class_names: tuple[str, ...] = CLASS_NAMES,
) -> dict[str, Any]:
"""Compute breed-level and derived species-level classification metrics."""
from sklearn.metrics import (
accuracy_score,
classification_report,
confusion_matrix,
precision_recall_fscore_support,
)
label_ids = list(range(len(class_names)))
macro_precision, macro_recall, macro_f1, _ = precision_recall_fscore_support(
y_true, y_pred, labels=label_ids, average="macro", zero_division=0
)
weighted_precision, weighted_recall, weighted_f1, _ = precision_recall_fscore_support(
y_true, y_pred, labels=label_ids, average="weighted", zero_division=0
)
species_true = np.array([get_species(class_names[index]) for index in y_true])
species_pred = np.array([get_species(class_names[index]) for index in y_pred])
return {
"accuracy": float(accuracy_score(y_true, y_pred)),
"macro_precision": float(macro_precision),
"macro_recall": float(macro_recall),
"macro_f1": float(macro_f1),
"weighted_precision": float(weighted_precision),
"weighted_recall": float(weighted_recall),
"weighted_f1": float(weighted_f1),
"species_accuracy": float(accuracy_score(species_true, species_pred)),
"confusion_matrix": confusion_matrix(y_true, y_pred, labels=label_ids),
"species_confusion_matrix": confusion_matrix(
species_true, species_pred, labels=["Cat", "Dog"]
),
"report": classification_report(
y_true,
y_pred,
labels=label_ids,
target_names=[format_breed_name(name) for name in class_names],
zero_division=0,
),
}
# region
## Instead of squinting at a giant 37 X 37 grid of numbers to find where the
### model failed, top_confusions surfaces the exact visual blind spots of the network
### in plain text, making it straightforward to analyze visually
# endregion
def top_confusions(
confusion: np.ndarray,
class_names: tuple[str, ...] = CLASS_NAMES,
count: int = 10,
) -> list[tuple[str, str, int]]:
"""Return the most frequent off-diagonal (true, predicted, count) breed pairs."""
off_diagonal = confusion.copy()
np.fill_diagonal(off_diagonal, 0)
flat_order = np.argsort(off_diagonal, axis=None)[::-1][:count]
pairs: list[tuple[str, str, int]] = []
for flat_index in flat_order:
true_index, predicted_index = np.unravel_index(flat_index, off_diagonal.shape)
if off_diagonal[true_index, predicted_index] == 0:
break
pairs.append(
(
format_breed_name(class_names[true_index]),
format_breed_name(class_names[predicted_index]),
int(off_diagonal[true_index, predicted_index]),
)
)
return pairs
# region
## plot_confusion_matrix visualizes model predictions against true labels as an annotated heat map using matplotlib
## Returns the matplotlib.figure.Figure object directly so I can display it in a notebook
# endregion
def plot_confusion_matrix(
confusion: np.ndarray,
class_names: tuple[str, ...] | list[str],
title: str,
normalize: bool = True,
):
"""Render a confusion matrix heat map and return the matplotlib figure."""
import matplotlib.pyplot as plt
matrix = confusion.astype(float)
if normalize:
row_totals = matrix.sum(axis=1, keepdims=True)
matrix = np.divide(matrix, row_totals, out=np.zeros_like(matrix), where=row_totals > 0)
large = len(class_names) > 10
figure, axes = plt.subplots(figsize=(14, 12) if large else (5, 4))
image_artist = axes.imshow(matrix, cmap="Blues", vmin=0.0, vmax=1.0 if normalize else None)
figure.colorbar(image_artist, ax=axes, fraction=0.046, pad=0.04)
axes.set_xticks(range(len(class_names)))
axes.set_yticks(range(len(class_names)))
labels = [format_breed_name(name) for name in class_names] if large else list(class_names)
axes.set_xticklabels(labels, rotation=90, fontsize=7 if large else 10)
axes.set_yticklabels(labels, fontsize=7 if large else 10)
axes.set_xlabel("Predicted label")
axes.set_ylabel("True label")
axes.set_title(title)
if not large:
for row in range(matrix.shape[0]):
for column in range(matrix.shape[1]):
axes.text(
column,
row,
f"{confusion[row, column]}",
ha="center",
va="center",
color="white" if matrix[row, column] > 0.5 else "black",
)
figure.tight_layout()
return figure
def plot_training_curves(fit_results: dict[str, dict[str, Any]]):
"""Plot loss and accuracy curves for each named training run."""
import matplotlib.pyplot as plt
figure, (loss_axes, accuracy_axes) = plt.subplots(1, 2, figsize=(13, 4.5))
for run_name, result in fit_results.items():
run_history = result["history"]
epochs = range(1, len(run_history["train_loss"]) + 1)
loss_axes.plot(epochs, run_history["train_loss"], linestyle="--", label=f"{run_name} train")
loss_axes.plot(epochs, run_history["validation_loss"], label=f"{run_name} validation")
accuracy_axes.plot(
epochs, run_history["train_accuracy"], linestyle="--", label=f"{run_name} train"
)
accuracy_axes.plot(
epochs, run_history["validation_accuracy"], label=f"{run_name} validation"
)
loss_axes.set_title("Cross-entropy loss")
loss_axes.set_xlabel("Epoch")
loss_axes.set_ylabel("Loss")
accuracy_axes.set_title("Accuracy")
accuracy_axes.set_xlabel("Epoch")
accuracy_axes.set_ylabel("Accuracy")
for axes in (loss_axes, accuracy_axes):
axes.grid(alpha=0.3)
axes.legend()
figure.tight_layout()
return figure
|