-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathcifar.py
225 lines (197 loc) · 6.58 KB
/
cifar.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
import os.path as osp
import pickle
import numpy as np
from PIL import Image
import torch
from torch.utils.data import Dataset
from sampler import RandomSampler, BatchSampler
import torchvision
import transform as T
def load_data_train(L=250, dspth='./dataset'):
datalist = [
osp.join(dspth, 'cifar-10-batches-py', 'data_batch_{}'.format(i+1))
for i in range(5)
]
data, labels = [], []
for data_batch in datalist:
with open(data_batch, 'rb') as fr:
entry = pickle.load(fr, encoding='latin1')
lbs = entry['labels'] if 'labels' in entry.keys() else entry['fine_labels']
data.append(entry['data'])
labels.append(lbs)
data = np.concatenate(data, axis=0)
labels = np.concatenate(labels, axis=0)
n_labels = L // 10
data_x, label_x, data_u, label_u = [], [], [], []
for i in range(10):
indices = np.where(labels == i)[0]
np.random.shuffle(indices)
inds_x, inds_u = indices[:n_labels], indices[n_labels:]
data_x += [
data[i].reshape(3, 32, 32).transpose(1, 2, 0)
for i in inds_x
]
label_x += [labels[i] for i in inds_x]
data_u += [
data[i].reshape(3, 32, 32).transpose(1, 2, 0)
for i in inds_u
]
label_u += [labels[i] for i in inds_u]
return data_x, label_x, data_u, label_u
def load_data_val(dspth='./dataset'):
datalist = [
osp.join(dspth, 'cifar-10-batches-py', 'test_batch')
]
data, labels = [], []
for data_batch in datalist:
with open(data_batch, 'rb') as fr:
entry = pickle.load(fr, encoding='latin1')
lbs = entry['labels'] if 'labels' in entry.keys() else entry['fine_labels']
data.append(entry['data'])
labels.append(lbs)
data = np.concatenate(data, axis=0)
labels = np.concatenate(labels, axis=0)
data = [
el.reshape(3, 32, 32).transpose(1, 2, 0)
for el in data
]
return data, labels
def compute_mean_var():
data_x, label_x, data_u, label_u = load_data_train()
data = data_x + data_u
data = np.concatenate([el[None, ...] for el in data], axis=0)
mean, var = [], []
for i in range(3):
channel = (data[:, :, :, i].ravel() / 127.5) - 1
# channel = (data[:, :, :, i].ravel() / 255)
mean.append(np.mean(channel))
var.append(np.std(channel))
print('mean: ', mean)
print('var: ', var)
class Cifar10(Dataset):
def __init__(self, data, labels, n_guesses=1, is_train=True):
super(Cifar10, self).__init__()
self.data, self.labels = data, labels
self.n_guesses = n_guesses
assert len(self.data) == len(self.labels)
assert self.n_guesses >= 1
# mean, std = (0.4914, 0.4822, 0.4465), (0.2471, 0.2435, 0.2616) # [0, 1]
mean, std = (-0.0172, -0.0356, -0.1069), (0.4940, 0.4869, 0.5231) # [-1, 1]
if is_train:
self.trans = T.Compose([
T.Resize((32, 32)),
T.PadandRandomCrop(border=4, cropsize=(32, 32)),
T.RandomHorizontalFlip(p=0.5),
T.Normalize(mean, std),
T.ToTensor(),
])
else:
self.trans = T.Compose([
T.Resize((32, 32)),
T.Normalize(mean, std),
T.ToTensor(),
])
def __getitem__(self, idx):
im, lb = self.data[idx], self.labels[idx]
ims = []
for _ in range(self.n_guesses):
im_trans = self.trans(im)
ims.append(im_trans)
return ims, lb
def __len__(self):
return len(self.data)
def get_train_loader(batch_size, n_iters_per_epoch, L, K, pin_memory=True, root='dataset'):
data_x, label_x, data_u, label_u = load_data_train(L=L, dspth=root)
ds_x = Cifar10(
data=data_x,
labels=label_x,
n_guesses=1,
is_train=True
)
ds_u = Cifar10(
data=data_u,
labels=label_u,
n_guesses=K,
is_train=True
)
sampler_x = RandomSampler(ds_x, replacement=True,
num_samples=n_iters_per_epoch * batch_size)
batch_sampler_x = BatchSampler(sampler_x, batch_size, drop_last=True)
dl_x = torch.utils.data.DataLoader(
ds_x,
batch_sampler=batch_sampler_x,
num_workers=1,
pin_memory=pin_memory
)
sampler_u = RandomSampler(ds_u, replacement=True,
num_samples=n_iters_per_epoch * batch_size)
batch_sampler_u = BatchSampler(sampler_u, batch_size, drop_last=True)
dl_u = torch.utils.data.DataLoader(
ds_u,
batch_sampler=batch_sampler_u,
num_workers=2,
pin_memory=pin_memory
)
return dl_x, dl_u
def get_val_loader(batch_size, num_workers, pin_memory=True, root='cifar10'):
data, labels = load_data_val()
ds = Cifar10(
data=data,
labels=labels,
n_guesses=1,
is_train=False
)
dl = torch.utils.data.DataLoader(
ds,
shuffle=False,
batch_size=batch_size,
drop_last=False,
num_workers=num_workers,
pin_memory=pin_memory
)
return dl
class OneHot(object):
def __init__(
self,
n_labels,
lb_ignore=255,
):
super(OneHot, self).__init__()
self.n_labels = n_labels
self.lb_ignore = lb_ignore
def __call__(self, label):
N, *S = label.size()
size = [N, self.n_labels] + S
lb_one_hot = torch.zeros(size)
if label.is_cuda:
lb_one_hot = lb_one_hot.cuda()
ignore = label.data.cpu() == self.lb_ignore
label[ignore] = 0
lb_one_hot.scatter_(1, label.unsqueeze(1), 1)
ignore = ignore.nonzero()
_, M = ignore.size()
a, *b = ignore.chunk(M, dim=1)
lb_one_hot[[a, torch.arange(self.n_labels), *b]] = 0
return lb_one_hot
if __name__ == "__main__":
compute_mean_var()
# dl_x, dl_u = get_train_loader(64, 250, 2, 2)
# dl_x2 = iter(dl_x)
# dl_u2 = iter(dl_u)
# ims, lb = next(dl_u2)
# print(type(ims))
# print(len(ims))
# print(ims[0].size())
# print(len(dl_u2))
# for i in range(1024):
# try:
# ims_x, lbs_x = next(dl_x2)
# # ims_u, lbs_u = next(dl_u2)
# print(i, ": ", ims_x[0].size())
# except StopIteration:
# dl_x2 = iter(dl_x)
# dl_u2 = iter(dl_u)
# ims_x, lbs_x = next(dl_x2)
# # ims_u, lbs_u = next(dl_u2)
# print('recreate iterator')
# print(i, ": ", ims_x[0].size())