-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathloaders.py
89 lines (78 loc) · 2.37 KB
/
loaders.py
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
import torchvision
import torch
from torch.utils.data import Dataset, random_split
from torch.utils.data.dataloader import DataLoader
class DatasetSubset(Dataset):
def __init__(self, subset, transform=None):
self.subset = subset
self.transform = transform
def __getitem__(self, index):
x, y = self.subset[index]
if self.transform:
x = self.transform(x)
return x, y
def __len__(self):
return len(self.subset)
normalization_transform = torchvision.transforms.Compose([
torchvision.transforms.ToTensor(),
torchvision.transforms.Normalize(
(0.1307,), (0.3081,))
])
rotation_and_normalization_transform = torchvision.transforms.Compose([
torchvision.transforms.ToTensor(),
torchvision.transforms.RandomRotation(
[0, 360],
torchvision.transforms.InterpolationMode.BILINEAR,
fill=0),
torchvision.transforms.Normalize(
(0.1307,), (0.3081,))
])
def get_loaders(datasets_root_path: str, experiment_config: dict):
seed = experiment_config["seed"]
rotate_train = experiment_config["rotate_train"]
rotate_test = experiment_config["rotate_test"]
batch_size = experiment_config["batch_size"]
train_transform = rotation_and_normalization_transform if rotate_train else normalization_transform
test_transform = rotation_and_normalization_transform if rotate_test else normalization_transform
train_dataset = torchvision.datasets.MNIST(
root=datasets_root_path,
train=True,
transform=None,
download=False
)
test_dataset = torchvision.datasets.MNIST(
root=datasets_root_path,
train=False,
transform=test_transform,
download=False
)
train_subset, val_subset = random_split(
dataset=train_dataset,
lengths=[50000, 10000],
generator=torch.Generator().manual_seed(seed)
)
train_loader = DataLoader(
dataset=DatasetSubset(
subset=train_subset,
transform=train_transform
),
batch_size=batch_size,
pin_memory=True,
shuffle=True
)
val_loader = DataLoader(
dataset=DatasetSubset(
subset=val_subset,
transform=test_transform
),
batch_size=2048,
pin_memory=True,
shuffle=False
)
test_loader = DataLoader(
dataset=test_dataset,
batch_size=2048,
pin_memory=True,
shuffle=False
)
return train_loader, val_loader, test_loader