Spaces:
Sleeping
Sleeping
Download src/dataset.py from deeAdora/pet_classifier: direct link, hf CLI and curl.
- Browser
- Download file 4.54 kB
-
https://huggingface.co/spaces/deeAdora/pet_classifier/resolve/main/src/dataset.py
- Command line
-
hf download hf://spaces/deeAdora/pet_classifier/src/dataset.py
-
curl -L -o dataset.py https://huggingface.co/spaces/deeAdora/pet_classifier/resolve/main/src/dataset.py
4.54 kB
| """Data pipeline for the Oxford-IIIT Pet dataset. | |
| Provides the preprocessing transforms, a stratified train/validation split of | |
| the official ``trainval`` partition, and the PyTorch ``DataLoader`` objects. | |
| The official ``test`` partition is never used for training or model selection. | |
| """ | |
| from __future__ import annotations | |
| import numpy as np | |
| from torch.utils.data import DataLoader, Subset | |
| from torchvision import transforms | |
| from torchvision.datasets import OxfordIIITPet | |
| IMAGE_SIZE = 224 | |
| IMAGENET_MEAN = [0.485, 0.456, 0.406] | |
| IMAGENET_STD = [0.229, 0.224, 0.225] | |
| SEED = 42 | |
| def build_train_transform(image_size: int = IMAGE_SIZE) -> transforms.Compose: | |
| """Training transform: resize, light augmentation, tensor conversion, normalization.""" | |
| return transforms.Compose( | |
| [ | |
| transforms.Resize((image_size, image_size)), | |
| transforms.RandomHorizontalFlip(), | |
| transforms.RandomRotation(10), | |
| transforms.ToTensor(), | |
| transforms.Normalize(mean=IMAGENET_MEAN, std=IMAGENET_STD), | |
| ] | |
| ) | |
| def build_eval_transform(image_size: int = IMAGE_SIZE) -> transforms.Compose: | |
| """Deterministic transform for validation, testing, and inference.""" | |
| return transforms.Compose( | |
| [ | |
| transforms.Resize((image_size, image_size)), | |
| transforms.ToTensor(), | |
| transforms.Normalize(mean=IMAGENET_MEAN, std=IMAGENET_STD), | |
| ] | |
| ) | |
| def stratified_split_indices( | |
| labels: list[int], | |
| validation_fraction: float = 0.2, | |
| seed: int = SEED, | |
| ) -> tuple[list[int], list[int]]: | |
| """Split sample indices into train and validation sets, preserving class balance. | |
| Each class contributes ``validation_fraction`` of its samples to the | |
| validation set, so every breed is represented in both partitions. | |
| """ | |
| label_array = np.asarray(labels) | |
| random_state = np.random.default_rng(seed) | |
| train_indices: list[int] = [] | |
| validation_indices: list[int] = [] | |
| for class_id in np.unique(label_array): | |
| class_indices = np.flatnonzero(label_array == class_id) | |
| random_state.shuffle(class_indices) | |
| validation_count = max(1, int(round(len(class_indices) * validation_fraction))) | |
| validation_indices.extend(class_indices[:validation_count].tolist()) | |
| train_indices.extend(class_indices[validation_count:].tolist()) | |
| return sorted(train_indices), sorted(validation_indices) | |
| def build_datasets( | |
| data_root: str = "data", | |
| image_size: int = IMAGE_SIZE, | |
| validation_fraction: float = 0.2, | |
| seed: int = SEED, | |
| download: bool = True, | |
| ) -> dict[str, Subset | OxfordIIITPet]: | |
| """Create the train, validation, and test datasets. | |
| The ``trainval`` partition is instantiated twice: once with augmentation | |
| (for the training subset) and once with the deterministic transform (for the | |
| validation subset), so validation images are never augmented. | |
| """ | |
| trainval_augmented = OxfordIIITPet( | |
| root=data_root, | |
| split="trainval", | |
| target_types="category", | |
| transform=build_train_transform(image_size), | |
| download=download, | |
| ) | |
| trainval_plain = OxfordIIITPet( | |
| root=data_root, | |
| split="trainval", | |
| target_types="category", | |
| transform=build_eval_transform(image_size), | |
| download=download, | |
| ) | |
| test_dataset = OxfordIIITPet( | |
| root=data_root, | |
| split="test", | |
| target_types="category", | |
| transform=build_eval_transform(image_size), | |
| download=download, | |
| ) | |
| train_indices, validation_indices = stratified_split_indices( | |
| trainval_plain._labels, validation_fraction=validation_fraction, seed=seed | |
| ) | |
| return { | |
| "train": Subset(trainval_augmented, train_indices), | |
| "validation": Subset(trainval_plain, validation_indices), | |
| "test": test_dataset, | |
| } | |
| def build_dataloaders( | |
| datasets: dict[str, Subset | OxfordIIITPet], | |
| batch_size: int = 32, | |
| num_workers: int = 2, | |
| pin_memory: bool = False, | |
| ) -> dict[str, DataLoader]: | |
| """Wrap each dataset in a ``DataLoader``; only the training loader shuffles.""" | |
| loaders: dict[str, DataLoader] = {} | |
| for split_name, split_dataset in datasets.items(): | |
| loaders[split_name] = DataLoader( | |
| split_dataset, | |
| batch_size=batch_size, | |
| shuffle=(split_name == "train"), | |
| num_workers=num_workers, | |
| pin_memory=pin_memory, | |
| persistent_workers=num_workers > 0, | |
| ) | |
| return loaders | |