-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathutils.py
47 lines (35 loc) · 1.11 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
import os
import random
import numpy as np
import torch
class AverageMeter(object):
def __init__(self):
self.count = 0
self.sum = 0
self.avg = 0
self.val = 0
def update(self, val, n=1):
self.val = val
self.sum += val * n
self.count += n
self.avg = self.sum / self.count if self.count != 0 else 0
def set_seed(seed):
random.seed(seed)
os.environ["PYTHONSEED"] = str(seed)
np.random.seed(seed)
torch.cuda.manual_seed(seed)
torch.cuda.manual_seed_all(seed)
torch.backends.cudnn.deterministic = True
torch.backends.cudnn.benchmark = False
torch.backends.cudnn.enabled = True
torch.manual_seed(seed)
def count_parameters(model):
params = sum(p.numel() for p in model.parameters() if p.requires_grad)
return params / 1e6
def clip_gradient(optimizer, grad_clip):
for group in optimizer.param_groups:
for param in group["params"]:
if param.grad is not None:
param.grad.data.clamp_(-grad_clip, grad_clip)
def mean_square_error(gt, sm):
return torch.mean(torch.abs(sm - gt))