-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathutils.py
More file actions
92 lines (71 loc) · 2.19 KB
/
utils.py
File metadata and controls
92 lines (71 loc) · 2.19 KB
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
import os
import os.path as osp
import time
import math
import yaml
import torch
import random
import numpy as np
from types import SimpleNamespace
from sklearn.metrics import f1_score, classification_report
def set_seeds(random_seed):
random.seed(random_seed)
np.random.seed(random_seed)
np.random.default_rng(random_seed)
torch.manual_seed(random_seed)
torch.cuda.manual_seed(random_seed)
torch.cuda.manual_seed_all(random_seed)
torch.backends.cudnn.deterministic = True
torch.backends.cudnn.benchmark = False
def get_exp_dir(work_dir):
work_dir = work_dir.split('./')[-1]
if not osp.exists(osp.join(os.getcwd(), work_dir)):
exp_dir = osp.join(os.getcwd(), work_dir, 'exp0')
else:
idx = 1
exp_dir = osp.join(os.getcwd(), work_dir, f'exp{idx}')
while osp.exists(exp_dir):
idx += 1
exp_dir = osp.join(os.getcwd(), work_dir, f'exp{idx}')
os.makedirs(exp_dir)
return exp_dir
def save_config(args, save_dir):
with open(save_dir, 'w') as f:
yaml.safe_dump(args.__dict__, f)
def load_config(config_dir):
with open(config_dir, 'r') as f:
config = yaml.safe_load(f)
return SimpleNamespace(**config)
def calc_tour_acc(pred, label, report=False):
_, idx = pred.max(1)
acc = torch.eq(idx, label).sum().item() / idx.size()[0]
x = label.cpu().numpy()
y = idx.cpu().numpy()
f1_acc = f1_score(x, y, average='weighted')
if report:
print(classification_report(x, y, zero_division=1))
return acc,f1_acc
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 asMinutes(s):
m = math.floor(s / 60)
s -= m * 60
return '%dm %ds' % (m, s)
def timeSince(since, percent):
now = time.time()
s = now - since
es = s / (percent)
rs = es - s
return '%s (remain %s)' % (asMinutes(s), asMinutes(rs))