-
Notifications
You must be signed in to change notification settings - Fork 0
/
utils.py
66 lines (48 loc) · 1.37 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
import random
import numpy as np
import torch
import torch.nn as nn
class AvgMeter():
def __init__(self):
self.reset()
def reset(self):
self.val = 0.
self.n = 0
self.avg = 0.
def update(self, val, n=1):
assert n > 0
self.val += val
self.n += n
self.avg = self.val / self.n
def get(self):
return self.avg
class BestMeter():
def __init__(self):
self.reset()
def reset(self):
self.val = 0.
self.n = -1
def update(self, val, n):
assert n > self.n
if val > self.val:
self.val = val
self.n = n
def get(self):
return self.val, self.n
def weights_init(m):
classname = m.__class__.__name__
if classname.find('Conv') != -1:
nn.init.normal_(m.weight.data, 0.0, 0.02)
elif classname.find('BatchNorm') != -1:
nn.init.normal_(m.weight.data, 1.0, 0.02)
nn.init.constant_(m.bias.data, 0)
def add_gaussian_noise(tensor, mean, std):
return torch.randn(tensor.size()) * std + mean
def set_seed(manual_seed):
random.seed(manual_seed)
np.random.seed(manual_seed)
torch.manual_seed(manual_seed)
if torch.cuda.is_available():
torch.cuda.manual_seed_all(manual_seed)
torch.backends.cudnn.benchmark = False
torch.backends.cudnn.deterministic = True