-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdataloader.py
68 lines (61 loc) · 2.27 KB
/
dataloader.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
# coding: utf-8
import torch
from torch.utils.data import DataLoader, random_split
from torchvision import transforms
from torchvision.datasets import MNIST, CIFAR10
def get_mnist_dataloader(_mode: str = "train", batch_size: int = 32) -> DataLoader:
transform = transforms.Compose([
transforms.ToTensor(),
transforms.Normalize((0.1307,), (0.3081,)),
transforms.Lambda(lambda x: torch.flatten(x)),
])
if _mode == "train":
_dataset = MNIST("", train=True, download=True, transform=transform)
_dataset, _ = random_split(
_dataset,
(
int(len(_dataset) * 0.9),
len(_dataset) - int(len(_dataset) * 0.9),
),
)
elif _mode == "val":
_dataset = MNIST("", train=True, download=True, transform=transform)
_, _dataset = random_split(
_dataset,
(
int(len(_dataset) * 0.9),
len(_dataset) - int(len(_dataset) * 0.9),
),
)
elif _mode == "test":
_dataset = MNIST("", train=False, download=True, transform=transform)
return DataLoader(_dataset, batch_size=batch_size)
def get_cifar10_dataloader(_mode: str = "train", batch_size: int = 32) -> DataLoader:
mean = (0.4914, 0.4822, 0.4465)
std = (0.247, 0.243, 0.261)
transform = transforms.Compose([
transforms.ToTensor(),
transforms.Normalize(mean=mean, std=std),
transforms.Lambda(lambda x: torch.flatten(x)),
])
if _mode == "train":
_dataset = CIFAR10("CIFAR10", train=True, download=True, transform=transform)
_dataset, _ = random_split(
_dataset,
(
int(len(_dataset) * 0.9),
len(_dataset) - int(len(_dataset) * 0.9),
),
)
elif _mode == "val":
_dataset = CIFAR10("CIFAR10", train=True, download=True, transform=transform)
_, _dataset = random_split(
_dataset,
(
int(len(_dataset) * 0.9),
len(_dataset) - int(len(_dataset) * 0.9),
),
)
elif _mode == "test":
_dataset = CIFAR10("CIFAR10", train=False, download=True, transform=transform)
return DataLoader(_dataset, batch_size=batch_size)