Spaces:
Sleeping
Sleeping
File size: 15,053 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 | """Data pipeline for the Oxford-IIIT Pet dataset.
Handles loading the raw Oxford-IIIT Pet images, transforming them into
PyTorch tensors, creating balanced data splits, and packaging them into
batches ready for model training and evaluation.
"""
# region
# __future__ annotations:
## Tells python to not evaluate type annotation when the file is being imported and treat them as text strings
## This avoids circular import errors and speeds up module initialization.
## I found that this is a defensive best practice
# endregion
from __future__ import annotations
import numpy as np
# region
# used to split training vs validation data; keeps testing data separate
# train is for learning model weights; Validations is for monitoring loss early (deterministic);
# Test is the final benchmark (deterministic)
# endregion
from torch.utils.data import DataLoader, Subset
# region
# transforms allows for image processing, transformation, and data augmentation
# endregion
from torchvision import transforms
from torchvision.datasets import OxfordIIITPet
# region
# resiize images to be the same so the tensor shapes are the same. 224x224 is industry standard
# endregion
IMAGE_SIZE = 224
# region
# later will be using the model ResNet18 which was trained on these numbers
# endregion
IMAGENET_MEAN = [0.485, 0.456, 0.406]
IMAGENET_STD = [0.229, 0.224, 0.225]
# region
# random generator - guarantees that your train/validation split, weight initializations,
# and baseline results are identical no matter where the code is ran
# endregion
SEED = 42
def build_train_transform(image_size: int = IMAGE_SIZE) -> transforms.Compose:
"""Training transform: resize, light augmentation, tensor conversion, normalization for TRAINING images."""
return transforms.Compose(
[
# region
## In tis function I am augmenting the picture so the model can learn from different angles.
## Resize: scales photo to 124x124 px
## RandomHorizontalFlip: mirroring image so model knows it's the same pet, no matter the dirction
## RandomRotation:eaches model it's the same pet, even if there is a 10degress angle
## ToTensor: converts the PIL image (image in memory), to a floading-point tensor. shape = (3, 244, 244) 3 is rgb color channels
## Normalize: centers and scales rgb so gradients - this is for the ResNet18 model
#endregion
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 for VALIDATION and TESTING images."""
return transforms.Compose(
[
# region
## Resize: scale images to 224 x 224 for uniform tensor shapes
## ToTensor: converts images to (3,224, 224) shape. 3 is rgb
## Normalize: matches what is expected for the ResNet18 model
# endregion
transforms.Resize((image_size, image_size)),
transforms.ToTensor(),
transforms.Normalize(mean=IMAGENET_MEAN, std=IMAGENET_STD),
]
)
def stratified_split_indices(
# region
# stratified - means to split the data
# labels: tells the function what breed each photo belongs to. Images are assined a number already (catagory id)
# labels: breed IDs (0-36) for every image in the dataset.
# Used here to group photos by breed so each class gets split 80/20.
# Note: Returns photo position indices (not label IDs), which build_datasets
# passes into torch.utils.data.Subset to carve out train and val splits.
# endregion
labels: list[int],
validation_fraction: float = 0.2, # 20% of data goes to the validation set
seed: int = SEED, # seed = 42
# region
# the arrow will return a type hint of what the data will send back.
# a tuple with 2 items that are integers. The 1st will be training data, the 2nd will be validation.
# endregion
) -> 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.
"""
# region
## label_array: converts the python list to a numpy array because lists do not suport vectorized boolean comparisons
## random_state: pass a fixed seed (42) for reproducibility because will yeild the same permutation every time.
## train_indices: creating an empty list that will accumulate. We have 37 breeds and the row will append to the list. list[int] is jsut a type hint
## validation_indices: creating an empty list, just like train_indicies, but for the validation (20% portion of data)
# endregion
label_array = np.asarray(labels)
random_state = np.random.default_rng(seed)
train_indices: list[int] = []
validation_indices: list[int] = []
# region
## for loop: takes the values in label_array and loops through them, 37 times, once for every pet breed
# class_indices: where label array and class_id are equal (true), retruns indicies of true values
## random_state.shuffle: shuffles the class_indicies, above it was set to use 42. Helps to eliminate bias.
## validation_count: calculates how many images from the specific breed should go into the validation set. validation_fraction as set to 20% earlier
## validation_indices.extend: Takes the first validation_count elements from the shuffled array converts numpy array to a list
## train_indices.extend: same as validation_indices.extend, but for train
## return sorted: orders the indicies and returns two elements in the tuple (the function returns two int tuples).
# endregion
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(
# region
## This function will download the Oxford-IIIT data, apply the transform pipelines, spliting the dataset, and return object for pytorch DataLoader
## data_root: the data folder is where images and annotations are stored
## image_size: defaults to 224 (previously declared variable)
## validation_fraction: defaults to 20%, (previously declared variable)
## seed: defaulted to 42. Forwards to random seed to stratified_split_indices()
## download: Boolean flag of True passed to torchvision constructor because pytorch will check if th dataset exists in the data folder. Only will extract if missing.
# endregion
data_root: str = "data",
image_size: int = IMAGE_SIZE,
validation_fraction: float = 0.2,
seed: int = SEED,
download: bool = True,
# region
## the union '|' indicated that either the function will return a Pytorch Subset
### instance or data from OxfordIIITPet. Subset is for 'train' and 'val' datasets.
### OxfordIIITPet is used for the test set because test data is loaded directly without index slicing.
### note test data in OxfordIIITPet already comes partitioned as its own self-contained dataset.
# endregion
) -> 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.
"""
# region
## trainval_augmented = OxfordIIITPet(: Instanciates the PyTorch dataset object from torchvision’s
### built-in OxfordIIITPet class and assigns it to the variable trainval_augmented
## root: The data is in the data_root folder for the OxfordIIITPet dataset
## split: gets the combined training and validation partition in the OxfordIIITPet dataset
## target_types: Passing "category" ensures the dataset returns an integer class ID (0 through 36) representing the pet breed for each photo.
## transform: calls the helper function to assign the image transformation to this dataset
## download: passes in the True or False vale to see if dataset exists locally. (variable declared as True above)
# endregion
trainval_augmented = OxfordIIITPet(
root=data_root,
split="trainval",
target_types="category",
transform=build_train_transform(image_size),
download=download,
)
# region
## Performs the same as the trainval_augmented, but for plain images
# endregion
trainval_plain = OxfordIIITPet(
root=data_root,
split="trainval",
target_types="category",
transform=build_eval_transform(image_size),
download=download,
)
# region
## Performs the same as the trainval_augmented, but for test images. Note that Oxford has test data reserved already
# endregion
test_dataset = OxfordIIITPet(
root=data_root,
split="test",
target_types="category",
transform=build_eval_transform(image_size),
download=download,
)
# region
## unpack the tuple from stratified_split_indices and assign them variables: train_indices, validation_indices
### these will be passed into aonother torch.util.data.Subset to partition the dataset into two distict sets
### calls stratified_split_indices() to perform class-by-class grouping, deterministic shuffling, and proportional slicing
## trainval_plain._labels: trainval_plain was defined above, ._labels is torchvision's list containing breed ID for ever image in trainval
## validation_fraction=validation_fraction: defauted to 20% in previous variable. Tells the splitter that 20% of photos
### should be allocated to validation, leaving 80% for training.
### seed = seed: 42...random shuffle produces the exact same split index list everytime the function funs.
# endregion
train_indices, validation_indices = stratified_split_indices(
trainval_plain._labels, validation_fraction=validation_fraction, seed=seed
)
# region
## Returns a python dictionary with three values, train. validation, and test as the Keys. Makes reading easier later
## train subset: the training data will have the randomized augmetations, train_indicies is 80% portion of row indices
### Later the DataLoader will request item 0 from this train split, Subset looks up the catalog position in train_indices to get
### the image through trainval_agmented.
## vadisation subset: is deterministic evaluation with 20% row indicies for validation
## test dataset: assigns the benchmark test dataset directly to 'test' key. THis data is already isolated, so didn't need subset.
# endregion
return {
"train": Subset(trainval_augmented, train_indices),
"validation": Subset(trainval_plain, validation_indices),
"test": test_dataset,
}
def build_dataloaders(
# region
## This function is responsible for creating the PyTorch DataLoader objects
## datasets: variable expects a dictionary of either 'train', 'validation',
### or 'test' and the values are either from Subset or OxfordIIITPet objects. expects data from build_datasets()
## batch_size: Dictates how many images are groupd together into a single tensor during each training, or evaluation loop
## If batch size is 32, the output tensor fed into ResNet-18 will have 4D Shape
### (Batch, Channels(rbg), 224(height), 224(width)). This fits with the GPU Memory of NVIDIA T4
## num_workers: Specifies how many subprocesses CPU threads use to preload and preprocess images async while GPU trains
## pin_memory: When set to True, the DataLoader allocates the loaded batch tensors into 'pinned' host memor.
### This enables faster dirct memory trainsfers. Ture when training on NVIDIA GPU
## dict[str, DataLoader]:
## Note, DataLoader is a function in the pytorch utils.py file
# endregion
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."""
# region
## loaders: Initialze an empty python dict (includes type hints) and the values are from the Pytorch DataLoader instances
## loop: itterates through each each key value in datasets() dictionary (these come from build_datasets())
## loaders[split_name] : Instanciates a new PyTorch DataLoader for the current split and maps to split_name inside loaders
## split_dataset: passes in the value of split_dataset into the loader (variable in the for loop - train, validate, test)
## batch_size: already set to 32, dictates how many samples are stacked into each batch tensor.
### The model will look at a set of 32 and then calculate its error and update.
## shuffle: if the data is 'train' this will be True, else False. Training data must be shuffed every epock so the
### model doesn't memorize image order and gradient updates remain stochastic. (Gradient update is the step a model
### takes to correct its internal settings - weights abd biases, so it can be more accurate. In this case, every batch_size=32)
## num_workers: set for processing. Forwards the worker thread count (default 2) so multiple
### subprocesses read and transform image files in parallel.
## pin_memory: When using CUDA setup, it locks RAM to speed up the PCIe data transfer dirctly to GPU VRAM. This is more to do
### with the hardware for the GPU and how it allocated memory.
## persistent_workers: Checks if num_workers is > 0. If > 0, then persistent_workers = True, else False.
### PyTorch kills and respons worker subprocesses at the end of each epoch. If Ture, then keeps the backgroud
### worker processes in memory between epochs. This helps speed up the training loops.
## the function will return a dict of rtrain, validation, test <dataloader ...>.
# endregion
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
|