Spaces:
Sleeping
Sleeping
Download src/utils.py from deeAdora/pet_classifier: direct link, hf CLI and curl.
- Browser
- Download file 17.3 kB
-
https://huggingface.co/spaces/deeAdora/pet_classifier/resolve/main/src/utils.py
- Command line
-
hf download hf://spaces/deeAdora/pet_classifier/src/utils.py
-
curl -L -o utils.py https://huggingface.co/spaces/deeAdora/pet_classifier/resolve/main/src/utils.py
17.3 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`` 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. | |
| 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", | |
| ) | |
| 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 | |
| # --------------------------------------------------------------------------- | |
| 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) | |
| 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" | |
| 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 | |
| # --------------------------------------------------------------------------- | |
| 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. | |
| """ | |
| device = torch.device(device) | |
| transform = transform if transform is not None else build_eval_transform() | |
| preprocessing_start = time.perf_counter() | |
| # transform(...) yields a (3, H, W) tensor; unsqueeze(0) prepends the batch | |
| # dimension so the network receives (1, 3, H, W). | |
| image_tensor = transform(image.convert("RGB")).unsqueeze(0).to(device) | |
| preprocessing_seconds = time.perf_counter() - preprocessing_start | |
| 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 | |
| # probs has shape (1, num_classes); squeeze(0) removes only the batch axis. | |
| 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] | |
| 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, | |
| } | |
| 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 | |
| # --------------------------------------------------------------------------- | |
| 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} | |
| 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, | |
| } | |
| 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) | |
| # --------------------------------------------------------------------------- | |
| 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, | |
| ), | |
| } | |
| 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 | |
| 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 | |