-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathdataset.py
105 lines (82 loc) · 2.77 KB
/
dataset.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
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
import numpy as np
import torch
from torchvision import datasets
from torch.utils.data import Dataset
from PIL import Image
def get_dataset(name):
if name == 'FashionMNIST':
return get_FashionMNIST()
elif name == 'SVHN':
return get_SVHN()
elif name == 'CIFAR10':
return get_CIFAR10()
def get_FashionMNIST():
raw_tr = datasets.FashionMNIST('data/FashionMNIST', train=True, download=True)
raw_te = datasets.FashionMNIST('data/FashionMNIST', train=False, download=True)
X_tr = raw_tr.train_data
Y_tr = raw_tr.train_labels
X_te = raw_te.test_data
Y_te = raw_te.test_labels
return X_tr, Y_tr, X_te, Y_te
def get_SVHN():
data_tr = datasets.SVHN('data/SVHN', split='train', download=True)
data_te = datasets.SVHN('data/SVHN', split='test', download=True)
X_tr = data_tr.data
Y_tr = torch.from_numpy(data_tr.labels)
X_te = data_te.data
Y_te = torch.from_numpy(data_te.labels)
return X_tr, Y_tr, X_te, Y_te
def get_CIFAR10():
data_tr = datasets.CIFAR10('data/CIFAR10', train=True, download=True)
data_te = datasets.CIFAR10('data/CIFAR10', train=False, download=True)
X_tr = data_tr.data
Y_tr = torch.from_numpy(np.array(data_tr.targets))
X_te = data_te.data
Y_te = torch.from_numpy(np.array(data_te.targets))
return X_tr, Y_tr, X_te, Y_te
def get_handler(name):
if name == 'FashionMNIST':
return DataHandler1
elif name == 'SVHN':
return DataHandler2
elif name == 'CIFAR10':
return DataHandler3
class DataHandler1(Dataset):
def __init__(self, X, Y, transform=None):
self.X = X
self.Y = Y
self.transform = transform
def __getitem__(self, index):
x, y = self.X[index], self.Y[index]
if self.transform is not None:
x = Image.fromarray(x.numpy(), mode='L')
x = self.transform(x)
return x, y, index
def __len__(self):
return len(self.X)
class DataHandler2(Dataset):
def __init__(self, X, Y, transform=None):
self.X = X
self.Y = Y
self.transform = transform
def __getitem__(self, index):
x, y = self.X[index], self.Y[index]
if self.transform is not None:
x = Image.fromarray(np.transpose(x, (1, 2, 0)))
x = self.transform(x)
return x, y, index
def __len__(self):
return len(self.X)
class DataHandler3(Dataset):
def __init__(self, X, Y, transform=None):
self.X = X
self.Y = Y
self.transform = transform
def __getitem__(self, index):
x, y = self.X[index], self.Y[index]
if self.transform is not None:
x = Image.fromarray(x)
x = self.transform(x)
return x, y, index
def __len__(self):
return len(self.X)