Spaces:
Sleeping
Sleeping
File size: 2,518 Bytes
8ce6557 618ca1d 8ce6557 618ca1d 8ce6557 618ca1d 8ce6557 618ca1d 8ce6557 | 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 | from __future__ import annotations
from dataclasses import dataclass
from pathlib import Path
from typing import Tuple
import torch
from torch.utils.data import DataLoader, Dataset, random_split
from torchvision import datasets, transforms
from .preprocess import MNIST_MEAN, MNIST_STD
@dataclass(frozen=True)
class DataLoaders:
train: DataLoader
val: DataLoader
test: DataLoader
def _build_transforms(use_augmentation: bool) -> Tuple[transforms.Compose, transforms.Compose]:
base = [transforms.ToTensor()]
aug = []
if use_augmentation:
aug = [transforms.RandomAffine(degrees=15, translate=(0.1, 0.1), scale=(0.9, 1.1))]
train_tf = transforms.Compose(aug + base)
eval_tf = transforms.Compose(base)
return train_tf, eval_tf
def _maybe_normalize(tf: transforms.Compose, normalize: bool) -> transforms.Compose:
if not normalize:
return tf
return transforms.Compose(list(tf.transforms) + [transforms.Normalize((MNIST_MEAN,), (MNIST_STD,))])
def make_mnist_loaders(
data_root: Path,
batch_size: int,
seed: int,
num_workers: int,
use_augmentation: bool,
normalize: bool = True,
val_ratio: float = 0.1,
) -> DataLoaders:
data_root.mkdir(parents=True, exist_ok=True)
train_tf, eval_tf = _build_transforms(use_augmentation)
train_tf = _maybe_normalize(train_tf, normalize=normalize)
eval_tf = _maybe_normalize(eval_tf, normalize=normalize)
full_train = datasets.MNIST(root=str(data_root), train=True, download=True, transform=train_tf)
test_ds = datasets.MNIST(root=str(data_root), train=False, download=True, transform=eval_tf)
n_total = len(full_train)
n_val = int(n_total * val_ratio)
n_train = n_total - n_val
generator = torch.Generator().manual_seed(seed)
train_ds, val_ds = random_split(full_train, [n_train, n_val], generator=generator)
train_loader = DataLoader(
train_ds,
batch_size=batch_size,
shuffle=True,
num_workers=num_workers,
pin_memory=torch.cuda.is_available(),
)
val_loader = DataLoader(
val_ds,
batch_size=batch_size,
shuffle=False,
num_workers=num_workers,
pin_memory=torch.cuda.is_available(),
)
test_loader = DataLoader(
test_ds,
batch_size=batch_size,
shuffle=False,
num_workers=num_workers,
pin_memory=torch.cuda.is_available(),
)
return DataLoaders(train=train_loader, val=val_loader, test=test_loader)
|