-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathprepare_datasets_fmnist.py
229 lines (182 loc) · 9.73 KB
/
prepare_datasets_fmnist.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
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
'''MIT License. Copyright (c) 2020 Ivan Sosnovik, Michał Szmaja'''
import os
import random
import hashlib
from glob import glob
import numpy as np
from sklearn.model_selection import train_test_split
from torch.utils.data import DataLoader, ConcatDataset
from torchvision import datasets, transforms
BUF_SIZE = 65536
def get_md5_from_source_path(source_path):
pattern = os.path.join(source_path, '**', '**', '*.png')
files = sorted(list(glob(pattern)))
assert len(files)
md5 = hashlib.md5()
for file_path in files:
with open(file_path, 'rb') as f:
while True:
data = f.read(BUF_SIZE)
if not data:
break
md5.update(data)
return md5.hexdigest()
def _save_images_to_folder(dataset, transform, path, split_name, idx, format_='.png'):
scales = {}
for el in dataset:
img = transform(el[0])
out = os.path.join(path, split_name, str(el[1]))
if not os.path.exists(out):
os.makedirs(out)
img_path = os.path.join(out, str(idx) + format_)
img.save(img_path)
idx += 1
return idx
def make_mnist_scale_50k(source, dest, min_scale, max_scale, download=False, seed=0, **kwargs):
'''
We follow the procedure described in
https://arxiv.org/pdf/1807.11783.pdf
https://arxiv.org/pdf/1906.03861.pdf
'''
MNIST_TRAIN_SIZE = 10000
MNIST_VAL_SIZE = 2000
MNIST_TEST_SIZE = 50000
np.random.seed(seed)
random.seed(seed)
# 3 stands for PIL.Image.BICUBIC
transform = transforms.RandomAffine(0, scale=(min_scale, max_scale), resample=3)
dataset_train = datasets.MNIST(root=source, train=True, download=download)
dataset_test = datasets.MNIST(root=source, train=False, download=download)
concat_dataset = ConcatDataset([dataset_train, dataset_test])
labels = [el[1] for el in concat_dataset]
train_val_size = MNIST_TRAIN_SIZE + MNIST_VAL_SIZE
train_val, test = train_test_split(concat_dataset, train_size=train_val_size,
test_size=MNIST_TEST_SIZE, stratify=labels)
labels = [el[1] for el in train_val]
train, val = train_test_split(train_val, train_size=MNIST_TRAIN_SIZE,
test_size=MNIST_VAL_SIZE, stratify=labels)
dest = os.path.expanduser(dest)
dataset_path = os.path.join(dest, 'MNIST_scale', "seed_{}".format(seed))
dataset_path = os.path.join(dataset_path, "scale_{}_{}".format(min_scale, max_scale))
print('OUTPUT: {}'.format(dataset_path))
idx = _save_images_to_folder(train, transform, dataset_path, 'train', 0, '.png')
idx = _save_images_to_folder(test, transform, dataset_path, 'test', idx, '.png')
idx = _save_images_to_folder(val, transform, dataset_path, 'val', idx, '.png')
def make_mnist_rotation_scale_50k(source, dest, min_rot, max_rot, min_scale, max_scale, download=False, seed=0, **kwargs):
'''
We follow the procedure described in
https://arxiv.org/pdf/1807.11783.pdf
https://arxiv.org/pdf/1906.03861.pdf
'''
MNIST_TRAIN_SIZE = 2000
MNIST_VAL_SIZE = 2000
MNIST_TEST_SIZE = 50000
np.random.seed(seed)
random.seed(seed)
# 3 stands for PIL.Image.BICUBIC
transform = transforms.RandomAffine([min_rot, max_rot], scale=(min_scale, max_scale), resample=3)
dataset_train = datasets.MNIST(root=source, train=True, download=download)
dataset_test = datasets.MNIST(root=source, train=False, download=download)
concat_dataset = ConcatDataset([dataset_train, dataset_test])
labels = [el[1] for el in concat_dataset]
train_val_size = MNIST_TRAIN_SIZE + MNIST_VAL_SIZE
train_val, test = train_test_split(concat_dataset, train_size=train_val_size,
test_size=MNIST_TEST_SIZE, stratify=labels)
labels = [el[1] for el in train_val]
train, val = train_test_split(train_val, train_size=MNIST_TRAIN_SIZE,
test_size=MNIST_VAL_SIZE, stratify=labels)
dest = os.path.expanduser(dest)
dataset_path = os.path.join(dest, 'MNIST_scale', "seed_{}".format(seed))
dataset_path = os.path.join(dataset_path, "scale_{}_{}".format(min_scale, max_scale))
print('OUTPUT: {}'.format(dataset_path))
idx = _save_images_to_folder(train, transform, dataset_path, 'train', 0, '.png')
idx = _save_images_to_folder(test, transform, dataset_path, 'test', idx, '.png')
idx = _save_images_to_folder(val, transform, dataset_path, 'val', idx, '.png')
def make_fmnist_rotation_scale_50k(source, dest, min_rot, max_rot, min_scale, max_scale, download=False, seed=0, **kwargs):
'''
Following a similar procedure to the previous function (make_mnist_rotation_scale_50k)
'''
FMNIST_TRAIN_SIZE = 2000
FMNIST_VAL_SIZE = 2000
FMNIST_TEST_SIZE = 50000
np.random.seed(seed)
random.seed(seed)
# 3 stands for PIL.Image.BICUBIC
transform = transforms.RandomAffine([min_rot, max_rot], scale=(min_scale, max_scale), resample=3)
identity_transform = transforms.RandomAffine([0, 0], scale=(1.0, 1.0), resample=3)
dataset_train = datasets.FashionMNIST(root=source, train=True, download=download)
dataset_test = datasets.FashionMNIST(root=source, train=False, download=download)
concat_dataset = ConcatDataset([dataset_train, dataset_test])
labels = [el[1] for el in concat_dataset]
train_val_size = FMNIST_TRAIN_SIZE + FMNIST_VAL_SIZE
train_val, test = train_test_split(concat_dataset, train_size=train_val_size,
test_size=FMNIST_TEST_SIZE, stratify=labels)
labels = [el[1] for el in train_val]
train, val = train_test_split(train_val, train_size=FMNIST_TRAIN_SIZE,
test_size=FMNIST_VAL_SIZE, stratify=labels)
dest = os.path.expanduser(dest)
dataset_path = os.path.join(dest, 'FMNIST_scale', "seed_{}".format(seed))
dataset_path = os.path.join(dataset_path, "scale_{}_{}".format(min_scale, max_scale))
print('OUTPUT: {}'.format(dataset_path))
# idx = _save_images_to_folder(train, transform, dataset_path, 'train', 0, '.png')
idx = _save_images_to_folder(train, identity_transform, dataset_path, 'train', 0, '.png')
idx = _save_images_to_folder(test, transform, dataset_path, 'test', idx, '.png')
idx = _save_images_to_folder(val, transform, dataset_path, 'val', idx, '.png')
def make_cifar_rotation_scale_50k(source, dest, min_rot, max_rot, min_scale, max_scale, download=False, seed=0, **kwargs):
'''
Following a similar procedure to the previous function (make_mnist_rotation_scale_50k)
'''
CIFAR_TRAIN_SIZE = 10000
CIFAR_VAL_SIZE = 2000
CIFAR_TEST_SIZE = 40000
np.random.seed(seed)
random.seed(seed)
# 3 stands for PIL.Image.BICUBIC
transform = transforms.RandomAffine([min_rot, max_rot], scale=(min_scale, max_scale), resample=3)
identity_transform = transforms.RandomAffine([0, 0], scale=(1.0, 1.0), resample=3)
dataset_train = datasets.CIFAR10(root=source, train=True, download=download)
dataset_test = datasets.CIFAR10(root=source, train=False, download=download)
concat_dataset = ConcatDataset([dataset_train, dataset_test])
labels = [el[1] for el in concat_dataset]
train_val_size = CIFAR_TRAIN_SIZE + CIFAR_VAL_SIZE
train_val, test = train_test_split(concat_dataset, train_size=train_val_size,
test_size=CIFAR_TEST_SIZE, stratify=labels)
labels = [el[1] for el in train_val]
train, val = train_test_split(train_val, train_size=CIFAR_TRAIN_SIZE,
test_size=CIFAR_VAL_SIZE, stratify=labels)
dest = os.path.expanduser(dest)
dataset_path = os.path.join(dest, 'CIFAR_scale', "seed_{}".format(seed))
dataset_path = os.path.join(dataset_path, "scale_{}_{}".format(min_scale, max_scale))
print('OUTPUT: {}'.format(dataset_path))
# idx = _save_images_to_folder(train, transform, dataset_path, 'train', 0, '.png')
idx = _save_images_to_folder(train, transform, dataset_path, 'train', 0, '.png')
idx = _save_images_to_folder(test, transform, dataset_path, 'test', idx, '.png')
idx = _save_images_to_folder(val, transform, dataset_path, 'val', idx, '.png')
if __name__ == '__main__':
from argparse import ArgumentParser
parser = ArgumentParser()
parser.add_argument('--source', type=str, required=True, help='source folder of the dataset')
parser.add_argument('--dest', type=str, required=True, help='destination folder for the output')
parser.add_argument('--min_rot', type=float, required=True,
help='min scale for the generated dataset')
parser.add_argument('--max_rot', type=float, default=1.0,
help='max scale for the generated dataset')
parser.add_argument('--min_scale', type=float, required=True,
help='min scale for the generated dataset')
parser.add_argument('--max_scale', type=float, default=1.0,
help='max scale for the generated dataset')
parser.add_argument('--download', action='store_true',
help='donwload stource dataset if needed.')
parser.add_argument('--seed', type=int, default=0, help='random seed')
parser.add_argument('--validate', action='store_true', default=False)
args = parser.parse_args()
if args.validate:
dest = os.path.expanduser(args.dest)
dataset_path = os.path.join(dest, 'MNIST_scale', "seed_{}".format(args.seed))
dataset_path = os.path.join(dataset_path,
"scale_{}_{}".format(args.min_scale, args.max_scale))
print(get_md5_from_source_path(dataset_path))
else:
for k, v in vars(args).items():
print('{}={}'.format(k, v))
make_fmnist_rotation_scale_50k(**vars(args))