-
Notifications
You must be signed in to change notification settings - Fork 13
/
dataloader_clothing1M.py
321 lines (297 loc) · 11.1 KB
/
dataloader_clothing1M.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
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
from torch.utils.data import Dataset, DataLoader
import torchvision.transforms as transforms
import random
import numpy as np
from PIL import Image
import json
import torch
from autoaugment import CIFAR10Policy, ImageNetPolicy
transform_weak_c1m_c10_compose = transforms.Compose(
[
transforms.Resize(256),
transforms.RandomCrop(224),
transforms.RandomHorizontalFlip(),
transforms.ToTensor(),
transforms.Normalize((0.6959, 0.6537, 0.6371), (0.3113, 0.3192, 0.3214)),
]
)
def transform_weak_c1m(x):
return transform_weak_c1m_c10_compose(x)
transform_strong_c1m_c10_compose = transforms.Compose(
[
transforms.Resize(256),
transforms.RandomCrop(224),
transforms.RandomHorizontalFlip(),
CIFAR10Policy(),
transforms.ToTensor(),
transforms.Normalize((0.6959, 0.6537, 0.6371), (0.3113, 0.3192, 0.3214)),
]
)
def transform_strong_c1m_c10(x):
return transform_strong_c1m_c10_compose(x)
transform_strong_c1m_in_compose = transforms.Compose(
[
transforms.Resize(256),
transforms.RandomCrop(224),
transforms.RandomHorizontalFlip(),
ImageNetPolicy(),
transforms.ToTensor(),
transforms.Normalize((0.6959, 0.6537, 0.6371), (0.3113, 0.3192, 0.3214)),
]
)
def transform_strong_c1m_in(x):
return transform_strong_c1m_in_compose(x)
class clothing_dataset(Dataset):
def __init__(
self,
root,
transform,
mode,
num_samples=0,
pred=[],
probability=[],
paths=[],
num_class=14,
):
self.root = root
self.transform = transform
self.mode = mode
self.train_labels = {}
self.test_labels = {}
self.val_labels = {}
with open("%s/noisy_label_kv.txt" % self.root, "r") as f:
lines = f.read().splitlines()
for l in lines:
entry = l.split()
img_path = "%s/" % self.root + entry[0][7:]
self.train_labels[img_path] = int(entry[1])
with open("%s/clean_label_kv.txt" % self.root, "r") as f:
lines = f.read().splitlines()
for l in lines:
entry = l.split()
img_path = "%s/" % self.root + entry[0][7:]
self.test_labels[img_path] = int(entry[1])
if mode == "all":
train_imgs = []
with open("%s/noisy_train_key_list.txt" % self.root, "r") as f:
lines = f.read().splitlines()
for l in lines:
img_path = "%s/" % self.root + l[7:]
train_imgs.append(img_path)
random.shuffle(train_imgs)
class_num = torch.zeros(num_class)
self.train_imgs = []
for impath in train_imgs:
label = self.train_labels[impath]
if (
class_num[label] < (num_samples / 14)
and len(self.train_imgs) < num_samples
):
self.train_imgs.append(impath)
class_num[label] += 1
random.shuffle(self.train_imgs)
elif self.mode == "labeled":
train_imgs = paths
pred_idx = pred.nonzero()[0]
self.train_imgs = [train_imgs[i] for i in pred_idx]
self.probability = [probability[i] for i in pred_idx]
print("%s data has a size of %d" % (self.mode, len(self.train_imgs)))
elif self.mode == "unlabeled":
train_imgs = paths
pred_idx = (1 - pred).nonzero()[0]
self.train_imgs = [train_imgs[i] for i in pred_idx]
self.probability = [probability[i] for i in pred_idx]
print("%s data has a size of %d" % (self.mode, len(self.train_imgs)))
elif mode == "test":
self.test_imgs = []
with open("%s/clean_test_key_list.txt" % self.root, "r") as f:
lines = f.read().splitlines()
for l in lines:
img_path = "%s/" % self.root + l[7:]
self.test_imgs.append(img_path)
elif mode == "val":
self.val_imgs = []
with open("%s/clean_val_key_list.txt" % self.root, "r") as f:
lines = f.read().splitlines()
for l in lines:
img_path = "%s/" % self.root + l[7:]
self.val_imgs.append(img_path)
def __getitem__(self, index):
if self.mode == "labeled":
img_path = self.train_imgs[index]
target = self.train_labels[img_path]
prob = self.probability[index]
image = Image.open(img_path).convert("RGB")
img1 = self.transform[0](image)
img2 = self.transform[1](image)
if self.transform[2] == None:
img3 = img1
img4 = img2
else:
img3 = self.transform[2](image)
img4 = self.transform[3](image)
return img1, img2, img3, img4, target, prob
elif self.mode == "unlabeled":
img_path = self.train_imgs[index]
image = Image.open(img_path).convert("RGB")
img1 = self.transform[0](image)
img2 = self.transform[1](image)
if self.transform[2] == None:
img3 = img1
img4 = img2
else:
img3 = self.transform[2](image)
img4 = self.transform[3](image)
return img1, img2, img3, img4
elif self.mode == "all":
img_path = self.train_imgs[index]
target = self.train_labels[img_path]
image = Image.open(img_path).convert("RGB")
img = self.transform(image)
return img, target, img_path
elif self.mode == "test":
img_path = self.test_imgs[index]
target = self.test_labels[img_path]
image = Image.open(img_path).convert("RGB")
img = self.transform(image)
return img, target
elif self.mode == "val":
img_path = self.val_imgs[index]
target = self.test_labels[img_path]
image = Image.open(img_path).convert("RGB")
img = self.transform(image)
return img, target
def __len__(self):
if self.mode == "test":
return len(self.test_imgs)
if self.mode == "val":
return len(self.val_imgs)
else:
return len(self.train_imgs)
class clothing_dataloader:
def __init__(
self,
root,
batch_size,
warmup_batch_size,
num_batches,
num_workers,
augmentation_strategy={},
):
self.batch_size = batch_size
self.warmup_batch_size = warmup_batch_size
self.num_workers = num_workers
self.num_batches = num_batches
self.root = root
self.augmentation_strategy = augmentation_strategy
self.transforms = {
"warmup": globals()[augmentation_strategy.warmup_transform],
"unlabeled": [None for i in range(4)],
"labeled": [None for i in range(4)],
"test": None,
}
# workaround so it works on both windows and linux
for i in range(len(augmentation_strategy.unlabeled_transforms)):
self.transforms["unlabeled"][i] = globals()[
augmentation_strategy.unlabeled_transforms[i]
]
for i in range(len(augmentation_strategy.labeled_transforms)):
self.transforms["labeled"][i] = globals()[
augmentation_strategy.labeled_transforms[i]
]
self.transforms["test"] = transforms.Compose(
[
transforms.Resize(256),
transforms.CenterCrop(224),
transforms.ToTensor(),
transforms.Normalize(
(0.6959, 0.6537, 0.6371), (0.3113, 0.3192, 0.3214)
),
]
)
def run(self, mode, pred=[], prob=[], paths=[]):
if mode == "warmup":
warmup_dataset = clothing_dataset(
self.root,
transform=self.transforms["warmup"],
mode="all",
num_samples=self.num_batches * self.warmup_batch_size,
)
warmup_loader = DataLoader(
dataset=warmup_dataset,
batch_size=self.warmup_batch_size,
shuffle=True,
num_workers=self.num_workers,
)
return warmup_loader
elif mode == "train":
labeled_dataset = clothing_dataset(
self.root,
transform=self.transforms["labeled"],
mode="labeled",
pred=pred,
probability=prob,
paths=paths,
)
labeled_loader = DataLoader(
dataset=labeled_dataset,
batch_size=self.batch_size,
shuffle=True,
num_workers=self.num_workers,
)
unlabeled_dataset = clothing_dataset(
self.root,
transform=self.transforms["unlabeled"],
mode="unlabeled",
pred=pred,
probability=prob,
paths=paths,
)
unlabeled_loader = DataLoader(
dataset=unlabeled_dataset,
batch_size=self.batch_size,
shuffle=True,
num_workers=self.num_workers,
)
return labeled_loader, unlabeled_loader
elif mode == "eval_train":
eval_dataset = clothing_dataset(
self.root,
transform=self.transforms["test"],
# ^- this is a small mistake in our implementation!
# augmentations for eval_train should be weak, not none.
# although this has a neglibible effect on performance,
# we feel it is important to note for future readers of this code.
# see: https://github.com/KentoNishi/Augmentation-for-LNL/issues/4
mode="all",
num_samples=self.num_batches * self.batch_size,
)
eval_loader = DataLoader(
dataset=eval_dataset,
batch_size=self.batch_size,
shuffle=False,
num_workers=self.num_workers,
)
return eval_loader
elif mode == "test":
test_dataset = clothing_dataset(
self.root, transform=self.transforms["test"], mode="test"
)
test_loader = DataLoader(
dataset=test_dataset,
batch_size=self.batch_size,
shuffle=False,
num_workers=self.num_workers,
)
return test_loader
elif mode == "val":
val_dataset = clothing_dataset(
self.root, transform=self.transforms["test"], mode="val"
)
val_loader = DataLoader(
dataset=val_dataset,
batch_size=self.batch_size,
shuffle=False,
num_workers=self.num_workers,
)
return val_loader