Spaces:
Sleeping
Sleeping
Damaris Adora
Cursor
Add sample photo gallery to the Gradio interface, annotated code, and updated documentation
2952455 Download codeWithNotes/utilsWIthNotes.py from deeAdora/pet_classifier: direct link, hf CLI and curl.
- Browser
- Download file 22.5 kB
-
https://huggingface.co/spaces/deeAdora/pet_classifier/resolve/main/codeWithNotes/utilsWIthNotes.py
- Command line
-
hf download hf://spaces/deeAdora/pet_classifier/codeWithNotes/utilsWIthNotes.py
-
curl -L -o utilsWIthNotes.py https://huggingface.co/spaces/deeAdora/pet_classifier/resolve/main/codeWithNotes/utilsWIthNotes.py
22.5 kB
| """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 | |