forked from PolinaKirichenko/deep_feature_reweighting
-
Notifications
You must be signed in to change notification settings - Fork 0
/
utils.py
142 lines (112 loc) · 3.69 KB
/
utils.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
import sys
import os
import torch
import torch.nn as nn
import numpy as np
import tqdm
class Logger(object):
def __init__(self, fpath=None, mode='w'):
self.console = sys.stdout
self.file = None
if fpath is not None:
self.file = open(fpath, mode)
def __del__(self):
self.close()
def __enter__(self):
pass
def __exit__(self, *args):
self.close()
def write(self, msg):
self.console.write(msg)
if self.file is not None:
self.file.write(msg)
def flush(self):
self.console.flush()
if self.file is not None:
self.file.flush()
os.fsync(self.file.fileno())
def close(self):
self.console.close()
if self.file is not None:
self.file.close()
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 set_seed(seed):
"""Sets seed"""
if torch.cuda.is_available():
torch.cuda.manual_seed(seed)
torch.manual_seed(seed)
np.random.seed(seed)
torch.backends.cudnn.benchmark = False
torch.backends.cudnn.deterministic = True
def get_y_p(g, n_places):
y = g // n_places
p = g % n_places
return y, p
def update_dict(acc_groups, y, g, logits):
preds = torch.argmax(logits, axis=1)
correct_batch = (preds == y)
g = g.cpu()
for g_val in np.unique(g):
mask = g == g_val
n = mask.sum().item()
corr = correct_batch[mask].sum().item()
acc_groups[g_val].update(corr / n, n)
def write_dict_to_tb(writer, dict, prefix, step):
for key, value in dict.items():
writer.add_scalar(f"{prefix}{key}", value, step)
def get_results(acc_groups, get_yp_func):
groups = acc_groups.keys()
results = {
f"accuracy_{get_yp_func(g)[0]}_{get_yp_func(g)[1]}": acc_groups[g].avg
for g in groups
}
all_correct = sum([acc_groups[g].sum for g in groups])
all_total = sum([acc_groups[g].count for g in groups])
results.update({"mean_accuracy" : all_correct / all_total})
results.update({"worst_accuracy" : min(results.values())})
return results
def evaluate(model, loader, get_yp_func, multitask=False, predict_place=False):
model.eval()
acc_groups = {g_idx : AverageMeter() for g_idx in range(loader.dataset.n_groups)}
if multitask:
acc_place_groups = {g_idx: AverageMeter() for g_idx in range(trainset.n_groups)}
with torch.no_grad():
for x, y, g, p in tqdm.tqdm(loader):
x, y, p = x.cuda(), y.cuda(), p.cuda()
if predict_place:
y = p
logits = model(x)
if multitask:
logits, logits_place = logits
update_dict(acc_place_groups, p, g, logits_place)
update_dict(acc_groups, y, g, logits)
model.train()
if multitask:
return get_results(acc_groups, get_yp_func), get_results(acc_place_groups, get_yp_func)
return get_results(acc_groups, get_yp_func)
class MultiTaskHead(nn.Module):
def __init__(self, n_features, n_classes_list):
super(MultiTaskHead, self).__init__()
self.fc_list = [
nn.Linear(n_features, n_classes).cuda()
for n_classes in n_classes_list
]
def forward(self, x):
outputs = []
for head in self.fc_list:
out = head(x)
outputs.append(out)
return outputs