-
Notifications
You must be signed in to change notification settings - Fork 0
/
dataloader_animal10N.py
259 lines (247 loc) · 10.5 KB
/
dataloader_animal10N.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
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
import os
import matplotlib
from autoaugment import CIFAR10Policy
def unpickle(file):
fo = open(file, 'rb').read()
size = 64 * 64 * 3 + 1
for i in range(50000):
arr = np.fromstring(fo[i * size:(i + 1) * size], dtype=np.uint8)
lab = np.identity(10)[arr[0]]
img = arr[1:].reshape((3, 64, 64)).transpose((1, 2, 0))
return img, lab
class animal_dataset(Dataset):
def __init__(self, root, transform, mode, pred=[], path=[], probability=[], num_class=10):
self.root = root
self.transform = transform
self.mode = mode
self.noise_label = []
self.train_dir = root + '/training/'
self.test_dir = root + '/testing/'
train_imgs = os.listdir(self.train_dir)
test_imgs = os.listdir(self.test_dir)
self.test_data = []
self.test_labels = []
noise_file1 = './training_batch.json'
noise_file2 = './testing_batch.json'
if mode == 'test':
if os.path.exists(noise_file2):
dict = json.load(open(noise_file2, "r"))
self.test_labels = dict['data']
self.test_data = dict['label']
else:
for img in test_imgs:
self.test_data.append(self.test_dir+img)
self.test_labels.append(int(img[0]))
dicts = {}
dicts['data'] = self.test_data
dicts['label'] = self.test_labels
# json.dump(dicts, open(noise_file2, "w"))
else:
if os.path.exists(noise_file1):
dict = json.load(open(noise_file1, "r"))
train_data = dict['data']
train_labels = dict['label']
for ip in train_data:
self.noise_label.append(train_labels[ip])
else:
train_data = []
train_labels = {}
for img in train_imgs:
img_path = self.train_dir+img
train_data.append(img_path)
train_labels[img_path] = (int(img[0]))
self.noise_label.append((int(img[0])))
self.noise_label = np.array(self.noise_label).astype(np.int64)
dicts = {}
dicts['data'] = train_data
dicts['label'] = train_labels
# json.dump(dicts, open(noise_file1, "w"))
if self.mode == "all":
self.train_data = train_data
self.train_labels = train_labels
elif self.mode == "labeled":
pred_idx = pred.nonzero()[0]
# train_img = path
train_img = train_data
self.train_data = [train_img[i] for i in pred_idx]
self.probability = probability[pred_idx]
# self.train_labels = train_labels[pred_idx]
self.train_labels = train_labels
print("%s data has a size of %d" % (self.mode, len(self.train_data)))
elif self.mode == "unlabeled":
pred_idx = (1 - pred).nonzero()[0]
# train_img = path
train_img = train_data
self.train_data = [train_img[i] for i in pred_idx]
self.probability = probability[pred_idx]
# self.train_labels = train_labels[pred_idx]
print("%s data has a size of %d" % (self.mode, len(self.train_data)))
self.train_labels = train_labels
def __getitem__(self, index):
if self.mode == 'labeled':
img_path = self.train_data[index]
target = self.train_labels[img_path]
prob = self.probability[index]
image = Image.open(img_path).convert('RGB')
#weak da
img1 = self.transform[0](image)
img2 = self.transform[1](image)
# strong da
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, index
elif self.mode == 'unlabeled':
img_path = self.train_data[index]
image = Image.open(img_path).convert('RGB')
# weak da
img1 = self.transform[0](image)
img2 = self.transform[1](image)
# strong da
if self.transform[2] == None:
img3 = img1
img4 = img2
else:
img3 = self.transform[2](image)
img4 = self.transform[3](image)
try:
return img1, img2, img3, img4, self.train_labels[img_path], index
except:
raise print('error\n')
elif self.mode == 'all':
img_path = self.train_data[index]
target = self.train_labels[img_path]
img = Image.open(img_path).convert('RGB')
if isinstance(self.transform, list):
img1 = self.transform[0](img)
img2 = self.transform[1](img)
img3 = self.transform[1](img)
return img1, img2, img3, target, index
else:
img = self.transform(img)
return img, target, index
elif self.mode == 'test':
img_path = self.test_data[index]
target = self.test_labels[index]
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_data)
else:
return len(self.train_data)
class animal_dataloader():
def __init__(self, root='C:/Users/Administrator/Desktop/DatasetAll/Animal-10N', batch_size=32, num_workers=0):
self.batch_size = batch_size
self.num_workers = num_workers
self.root = root
self.transform_strong_train = transforms.Compose([
transforms.Resize(64),
transforms.RandomCrop(64),
transforms.RandomHorizontalFlip(),
CIFAR10Policy(),
transforms.ToTensor(),
transforms.Normalize((0.6959, 0.6537, 0.6371), (0.3113, 0.3192, 0.3214)),])
self.transform_weak_train = transforms.Compose([
transforms.Resize(64),
transforms.RandomCrop(64),
transforms.RandomHorizontalFlip(),
transforms.ToTensor(),
transforms.Normalize((0.6959, 0.6537, 0.6371), (0.3113, 0.3192, 0.3214)),
])
self.transform_test = transforms.Compose([
# transforms.Resize(64),
# transforms.CenterCrop(64),
transforms.ToTensor(),
transforms.Normalize((0.6959, 0.6537, 0.6371), (0.3113, 0.3192, 0.3214)),
])
self.transforms = {
"warmup": [self.transform_weak_train,
self.transform_strong_train
],
"unlabeled": [
self.transform_weak_train,
self.transform_weak_train,
self.transform_strong_train,
self.transform_strong_train
],
"labeled": [
self.transform_weak_train,
self.transform_weak_train,
self.transform_strong_train,
self.transform_strong_train
],
"test": self.transform_test,
}
def run(self, mode, pred=[], prob=[], paths=[]):
if mode == 'warmup':
warmup_dataset = animal_dataset(self.root, transform=self.transforms["warmup"], mode='all')
warmup_loader = DataLoader(
dataset=warmup_dataset,
batch_size=self.batch_size,
shuffle=True,
num_workers=self.num_workers,
pin_memory=True)
return warmup_loader
elif mode == 'train':
labeled_dataset = animal_dataset(self.root, transform=self.transforms["labeled"], mode='labeled', pred=pred, path=paths,
probability=prob)
labeled_loader = DataLoader(
dataset=labeled_dataset,
batch_size=self.batch_size,
shuffle=True,drop_last=True,
num_workers=self.num_workers,
pin_memory=True)
unlabeled_dataset = animal_dataset(self.root, transform=self.transforms["unlabeled"], mode='unlabeled', pred=pred,path=paths,
probability=prob)
unlabeled_loader = DataLoader(
dataset=unlabeled_dataset,
batch_size=int(self.batch_size),
shuffle=True,drop_last=True,
num_workers=self.num_workers,
pin_memory=True)
return labeled_loader, unlabeled_loader, 0
elif mode == 'eval_train':
eval_dataset = animal_dataset(self.root, transform=self.transforms["test"], mode='all')
eval_loader = DataLoader(
dataset=eval_dataset,
batch_size=self.batch_size,
shuffle=False,
num_workers=self.num_workers,
pin_memory=True)
return eval_loader
elif mode == 'test':
test_dataset = animal_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,
pin_memory=True)
return test_loader
# if __name__ == '__main__':
# loader = animal_dataloader()
# train_loader = loader.run('warmup')
# import matplotlib.pyplot as plt
# for batch_idx, (inputs, labels, idx, img_path) in enumerate(train_loader):
# print(img_path[0])
# plt.figure(dpi=300)
# # plt.imshow(inputs[0])
# plt.imshow(inputs[0].reshape(64, 64, 3))
# plt.show()
# plt.close()
# print(inputs.shape())
# print(idx)
# print(labels, len(labels))
# # print(train_loader.dataset.__len__())