-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathutils.py
More file actions
43 lines (34 loc) · 1.13 KB
/
utils.py
File metadata and controls
43 lines (34 loc) · 1.13 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
import numpy as np
import random
import torch
import torch.nn.functional as F
def set_global_seeds(i):
random.seed(i)
np.random.seed(i)
torch.manual_seed(i)
if torch.cuda.is_available():
torch.cuda.manual_seed_all(i)
def set_device():
if torch.cuda.is_available():
_device = torch.device("cuda")
else:
_device = torch.device("cpu")
print(f'Current device is {_device}', flush=True)
return _device
# Adjust learning rate and for SGD Optimizer
def adjust_learning_rate(optimizer, epoch,alpha_plan):
for param_group in optimizer.param_groups:
param_group['lr']=alpha_plan[epoch]
def accuracy(logit, target, topk=(1,)):
"""Computes the precision@k for the specified values of k"""
output = F.softmax(logit, dim=1)
maxk = max(topk)
batch_size = target.size(0)
_, pred = output.topk(maxk, 1, True, True)
pred = pred.t()
correct = pred.eq(target.reshape(1, -1).expand_as(pred))
res = []
for k in topk:
correct_k = correct[:k].reshape(-1).float().sum(0, keepdim=True)
res.append(correct_k.mul_(100.0 / batch_size))
return res