-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdata.py
70 lines (59 loc) · 1.75 KB
/
data.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
import torch
from inf.utils import *
from inf.optim import *
import numpy as np
from torch.utils.data import Subset
import torch.utils.data as data_utils
def to_one_hot(target, num_cls=10, center=True):
'''
one-hot encoding.
'''
oh_target = target.new_zeros(target.shape[0], num_cls).type(torch.get_default_dtype())
oh_target.scatter_(1, target.unsqueeze(-1), 1)
if center:
# oh_target -= 0.1
oh_target -= 0.5
return oh_target
def remove_extra_cls_cifar10(dataset, keep_cls):
'''
function to remove excess classes from cifar10 (for testing).
'''
map = {}
i = 0
for n in range(10):
if n in keep_cls:
map[n] = i
i += 1
else:
map[n] = -1
targets = np.array(dataset.targets)
idx = np.array(range(len(targets)))
idx_to_keep = np.isin(targets, keep_cls)
idx = idx[idx_to_keep]
dataset.targets = torch.from_numpy(np.array(dataset.targets)).apply_(map.get).tolist()
return Subset(dataset, idx)
def remove_extra_cls_imagenet(dataset, keep_cls):
'''
function to remove excess classes from a imagenet.
'''
map = {}
i = 0
for n in range(1001):
if n in keep_cls:
map[n] = i
i += 1
else:
map[n] = -1
if dataset.train:
targets = np.array(dataset.train_labels)
idx = np.array(range(len(targets)))
idx_to_keep = np.isin(targets, keep_cls)
idx = idx[idx_to_keep]
dataset.train_labels = torch.from_numpy(np.array(dataset.train_labels)).apply_(map.get).tolist()
else:
targets = np.array(dataset.val_labels)
idx = np.array(range(len(targets)))
idx_to_keep = np.isin(targets, keep_cls)
idx = idx[idx_to_keep]
dataset.val_labels = torch.from_numpy(np.array(dataset.val_labels)).apply_(map.get).tolist()
return Subset(dataset, idx)