-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathutil.py
97 lines (77 loc) · 2.63 KB
/
util.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
# Copyright (c) 2017-present, Facebook, Inc.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
#
import os
import pickle
import numpy as np
from torch.utils.data.sampler import Sampler
class UnifLabelSampler(Sampler):
"""Samples elements uniformely accross pseudolabels.
Args:
N (int): size of returned iterator.
images_lists: dict of key (target), value (list of data with this target)
"""
def __init__(self, N, images_lists):
self.N = N
self.images_lists = images_lists
self.indexes = self.generate_indexes_epoch()
def generate_indexes_epoch(self):
nmb_non_empty_clusters = 0
for i in range(len(self.images_lists)):
if len(self.images_lists[i]) != 0:
nmb_non_empty_clusters += 1
size_per_pseudolabel = int(self.N / nmb_non_empty_clusters) + 1
res = np.array([])
for i in range(len(self.images_lists)):
# skip empty clusters
if len(self.images_lists[i]) == 0:
continue
indexes = np.random.choice(
self.images_lists[i],
size_per_pseudolabel,
replace=(len(self.images_lists[i]) <= size_per_pseudolabel)
)
res = np.concatenate((res, indexes))
np.random.shuffle(res)
res = list(res.astype('int'))
if len(res) >= self.N:
return res[:self.N]
res += res[: (self.N - len(res))]
return res
def __iter__(self):
return iter(self.indexes)
def __len__(self):
return len(self.indexes)
class AverageMeter(object):
"""Computes and stores the average and current value"""
def __init__(self):
self.reset()
def reset(self):
self.val = 0
self.avg = 0
self.sum = 0
self.count = 0
def update(self, val, n=1):
self.val = val
self.sum += val * n
self.count += n
self.avg = self.sum / self.count
def learning_rate_decay(optimizer, t, lr_0):
for param_group in optimizer.param_groups:
lr = lr_0 / np.sqrt(1 + lr_0 * param_group['weight_decay'] * t)
param_group['lr'] = lr
class Logger(object):
""" Class to update every epoch to keep trace of the results
Methods:
- log() log and save
"""
def __init__(self, path):
self.path = path
self.data = []
def log(self, train_point):
self.data.append(train_point)
with open(os.path.join(self.path), 'wb') as fp:
pickle.dump(self.data, fp, -1)