-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcifar100.py
199 lines (166 loc) · 7.22 KB
/
cifar100.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
from __future__ import print_function
import os
import numpy as np
from torch.utils.data import DataLoader
from torchvision import datasets, transforms
from PIL import Image
class CIFAR100Instance(datasets.CIFAR100):
"""CIFAR100Instance Dataset.
"""
def __getitem__(self, index):
if self.train:
img, target = self.train_data[index], self.train_labels[index]
else:
img, target = self.test_data[index], self.test_labels[index]
# doing this so that it is consistent with all other datasets
# to return a PIL Image
img = Image.fromarray(img)
if self.transform is not None:
img = self.transform(img)
if self.target_transform is not None:
target = self.target_transform(target)
return img, target, index
def get_cifar100_dataloaders(data_folder, batch_size=128, num_workers=8, is_instance=False):
"""
cifar 100
"""
train_transform = transforms.Compose([
transforms.RandomCrop(32, padding=4),
transforms.RandomHorizontalFlip(),
transforms.ToTensor(),
transforms.Normalize((0.5071, 0.4867, 0.4408), (0.2675, 0.2565, 0.2761)),
])
test_transform = transforms.Compose([
transforms.ToTensor(),
transforms.Normalize((0.5071, 0.4867, 0.4408), (0.2675, 0.2565, 0.2761)),
])
if is_instance:
train_set = CIFAR100Instance(root=data_folder,
download=True,
train=True,
transform=train_transform)
n_data = len(train_set)
else:
train_set = datasets.CIFAR100(root=data_folder,
download=True,
train=True,
transform=train_transform)
train_loader = DataLoader(train_set,
batch_size=batch_size,
shuffle=True,
num_workers=num_workers)
test_set = datasets.CIFAR100(root=data_folder,
download=True,
train=False,
transform=test_transform)
test_loader = DataLoader(test_set,
batch_size=int(batch_size/2),
shuffle=False,
num_workers=int(num_workers/2))
if is_instance:
return train_loader, test_loader, n_data
else:
return train_loader, test_loader
class CIFAR100InstanceSample(datasets.CIFAR100):
"""
CIFAR100Instance+Sample Dataset
"""
def __init__(self, root, train=True,
transform=None, target_transform=None,
download=False, k=4096, mode='exact', is_sample=True, percent=1.0):
super().__init__(root=root, train=train, download=download,
transform=transform, target_transform=target_transform)
self.k = k
self.mode = mode
self.is_sample = is_sample
num_classes = 100
if self.train:
num_samples = len(self.data)
label = self.targets
else:
num_samples = len(self.data)
label = self.targets
# [[],[],[]], each sub-list contains all sample ids of the class
self.cls_positive = [[] for i in range(num_classes)]
for i in range(num_samples):
self.cls_positive[label[i]].append(i)
# [[],[],[]],each sub-list contains all negative sample ids of the class
self.cls_negative = [[] for i in range(num_classes)]
for i in range(num_classes):
for j in range(num_classes):
if j == i:
continue
self.cls_negative[i].extend(self.cls_positive[j])
self.cls_positive = [np.asarray(self.cls_positive[i]) for i in range(num_classes)]
self.cls_negative = [np.asarray(self.cls_negative[i]) for i in range(num_classes)]
if 0 < percent < 1:
n = int(len(self.cls_negative[0]) * percent)
self.cls_negative = [np.random.permutation(self.cls_negative[i])[0:n]
for i in range(num_classes)]
self.cls_positive = np.asarray(self.cls_positive)
self.cls_negative = np.asarray(self.cls_negative)
def __getitem__(self, index):
if self.train:
img, target = self.data[index], self.targets[index]
else:
img, target = self.data[index], self.targets[index]
# doing this so that it is consistent with all other datasets
# to return a PIL Image
img = Image.fromarray(img)
if self.transform is not None:
img = self.transform(img)
if self.target_transform is not None:
target = self.target_transform(target)
if not self.is_sample:
# directly return
return img, target, index
else:
# sample contrastive examples
if self.mode == 'exact':
pos_idx = index
elif self.mode == 'relax':
pos_idx = np.random.choice(self.cls_positive[target], 1)
pos_idx = pos_idx[0]
else:
raise NotImplementedError(self.mode)
replace = True if self.k > len(self.cls_negative[target]) else False
neg_idx = np.random.choice(self.cls_negative[target], self.k, replace=replace)
sample_idx = np.hstack((np.asarray([pos_idx]), neg_idx))
return img, target, index, sample_idx
def get_cifar100_dataloaders_sample(data_folder, batch_size=128, num_workers=8, k=4096, mode='exact',
is_sample=True, percent=1.0):
"""
cifar 100
"""
train_transform = transforms.Compose([
transforms.RandomCrop(32, padding=4),
transforms.RandomHorizontalFlip(),
transforms.ToTensor(),
transforms.Normalize((0.5071, 0.4867, 0.4408), (0.2675, 0.2565, 0.2761)),
])
test_transform = transforms.Compose([
transforms.ToTensor(),
transforms.Normalize((0.5071, 0.4867, 0.4408), (0.2675, 0.2565, 0.2761)),
])
train_set = CIFAR100InstanceSample(root=data_folder,
download=True,
train=True,
transform=train_transform,
k=k,
mode=mode,
is_sample=is_sample,
percent=percent)
n_data = len(train_set)
train_loader = DataLoader(train_set,
batch_size=batch_size,
shuffle=True,
num_workers=num_workers)
test_set = datasets.CIFAR100(root=data_folder,
download=True,
train=False,
transform=test_transform)
test_loader = DataLoader(test_set,
batch_size=int(batch_size/2),
shuffle=False,
num_workers=int(num_workers/2))
return train_loader, test_loader, n_data