-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmy_data_loader.py
211 lines (173 loc) · 6.9 KB
/
my_data_loader.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
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
"""
[1]: https://discuss.pytorch.org/t/feedback-on-pytorch-for-kaggle-competitions/2252/4
[2]: https://gist.github.com/kevinzakka/d33bf8d6c7f06a9d8c76d97a7879f5cb
"""
import torch
import numpy as np
from torchvision import datasets
from torchvision import transforms
from torch.utils.data.sampler import SubsetRandomSampler
import torchvision
import utils
class FromIndexSampler(torch.utils.data.sampler.Sampler):
def __init__(self, indices, max_sample_num=None):
self.indices = indices
self.max_sample_num = int(max_sample_num)
def __iter__(self):
if not self.max_sample_num:
return iter(self.indices)
else:
return iter(self.indices[:self.max_sample_num])
def __len__(self):
if not self.max_sample_num:
return len(self.indices)
else:
return self.max_sample_num
def get_train_valid_loader(data_dir, batch_size, augment, random_seed, valid_size=0.1, shuffle=True, show_sample=False, num_workers=4, pin_memory=False,
data_num=500):
error_msg = "[!] valid_size should be in the range [0, 1]."
assert ((valid_size >= 0) and (valid_size <= 1)), error_msg
train_transform, valid_transform = utils._data_transforms_cifar10(
False, 16)
# load the dataset
train_dataset = datasets.CIFAR10(
root=data_dir, train=True, download=True, transform=train_transform)
valid_dataset = datasets.CIFAR10(
root=data_dir, train=True, download=True, transform=valid_transform)
# To be able to train on the full CIFAR10 dataset
if 50000 == data_num:
balanced_train_sampler = None
balanced_valid_sampler = None
else:
print('./sample_indices/training_sample_list_%d.npy' % (data_num))
print('./sample_indices/valid_sample_list_%d.npy' % (data_num))
balanced_train_indices = np.load(
'./sample_indices/training_sample_list_%d.npy' % (data_num))
balanced_train_sampler = SubsetRandomSampler(
balanced_train_indices.tolist())
balanced_valid_indices = np.load(
'./sample_indices/valid_sample_list_%d.npy' % (data_num))
balanced_valid_sampler = SubsetRandomSampler(
balanced_valid_indices.tolist())
train_loader = torch.utils.data.DataLoader(
train_dataset,
batch_size=batch_size,
shuffle=False,
num_workers=num_workers,
pin_memory=pin_memory,
drop_last=True,
sampler=balanced_train_sampler)
valid_loader = torch.utils.data.DataLoader(
valid_dataset,
batch_size=batch_size,
shuffle=False,
num_workers=num_workers,
pin_memory=pin_memory,
drop_last=True,
sampler=balanced_valid_sampler)
# # visualize some images
# data_iter = iter(train_loader)
# images, labels = data_iter.next()
# X = images.numpy().transpose([0, 2, 3, 1])
# plot_images(X, labels)
# data_iter = iter(valid_loader)
# images, labels = data_iter.next()
# X = images.numpy().transpose([0, 2, 3, 1])
# plot_images(X, labels)
return (train_loader, valid_loader)
def get_train_valid_loader_tinyimagenet(data_dir, batch_size, augment, random_seed, valid_size=0.1, shuffle=True, show_sample=False, num_workers=4, pin_memory=False,
data_num=20000):
error_msg = "[!] valid_size should be in the range [0, 1]."
assert ((valid_size >= 0) and (valid_size <= 1)), error_msg
transform_train = transforms.Compose([
transforms.RandomCrop(64, padding=4),
transforms.RandomHorizontalFlip(),
transforms.ToTensor(),
transforms.Normalize((0.4914, 0.4822, 0.4465),
(0.2023, 0.1994, 0.2010)),
])
transform_test = transforms.Compose([
transforms.ToTensor(),
transforms.Normalize((0.4914, 0.4822, 0.4465),
(0.2023, 0.1994, 0.2010)),
])
# load the dataset
train_dataset = torchvision.datasets.ImageFolder(
root='/home/suganuma/dataset/tiny-imagenet-200/train', transform=transform_train)
testset = torchvision.datasets.ImageFolder(
root='/home/suganuma/dataset/tiny-imagenet-200/train', transform=transform_test)
print('./sample_indices/training_sample_list_%d.npy' % (data_num))
print('./sample_indices/valid_sample_list_%d.npy' % (data_num))
balanced_train_indices = np.load(
'./sample_indices/training_sample_list_%d.npy' % (data_num))
balanced_train_sampler = SubsetRandomSampler(
balanced_train_indices.tolist())
balanced_valid_indices = np.load(
'./sample_indices/valid_sample_list_%d.npy' % (data_num))
balanced_valid_sampler = SubsetRandomSampler(
balanced_valid_indices.tolist())
train_loader = torch.utils.data.DataLoader(
train_dataset,
batch_size=batch_size,
shuffle=False,
num_workers=num_workers,
pin_memory=pin_memory,
drop_last=True,
sampler=balanced_train_sampler)
valid_loader = torch.utils.data.DataLoader(
testset,
batch_size=batch_size,
shuffle=False,
num_workers=num_workers,
pin_memory=pin_memory,
drop_last=True,
sampler=balanced_valid_sampler)
# # visualize some images
# data_iter = iter(train_loader)
# images, labels = data_iter.next()
# X = images.numpy().transpose([0, 2, 3, 1])
# plot_images(X, labels)
# data_iter = iter(valid_loader)
# images, labels = data_iter.next()
# X = images.numpy().transpose([0, 2, 3, 1])
# plot_images(X, labels)
return (train_loader, valid_loader)
def get_test_loader(data_dir,
batch_size,
shuffle=True,
num_workers=0,
pin_memory=True):
"""
Utility function for loading and returning a multi-process
test iterator over the CIFAR-10 dataset.
If using CUDA, num_workers should be set to 1 and pin_memory to True.
Params
------
- data_dir: path directory to the dataset.
- batch_size: how many samples per batch to load.
- shuffle: whether to shuffle the dataset after every epoch.
- num_workers: number of subprocesses to use when loading the dataset.
- pin_memory: whether to copy tensors into CUDA pinned memory. Set it to
True if using GPU.
Returns
-------
- data_loader: test set iterator.
"""
normalize = transforms.Normalize(
mean=[0.485, 0.456, 0.406],
std=[0.229, 0.224, 0.225],
)
# define transform
transform = transforms.Compose([
transforms.ToTensor(),
normalize,
])
dataset = datasets.CIFAR10(
root=data_dir, train=False,
download=True, transform=transform,
)
data_loader = torch.utils.data.DataLoader(
dataset, batch_size=batch_size, shuffle=shuffle,
num_workers=num_workers, pin_memory=pin_memory,
)
return data_loader