-
Notifications
You must be signed in to change notification settings - Fork 4
/
utils.py
85 lines (65 loc) · 2.07 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
"""utils.py"""
import argparse
from pathlib import Path
import torch
from torch import nn
from torch.autograd import Variable
class One_Hot(nn.Module):
# from :
# https://lirnli.wordpress.com/2017/09/03/one-hot-encoding-in-pytorch/
def __init__(self, depth):
super(One_Hot, self).__init__()
self.depth = depth
self.ones = torch.sparse.torch.eye(depth)
def forward(self, X_in):
X_in = X_in.long()
return Variable(self.ones.index_select(0, X_in.data))
def __repr__(self):
return self.__class__.__name__ + "({})".format(self.depth)
def cuda(tensor, is_cuda):
if is_cuda:
return tensor.cuda()
else:
return tensor
def str2bool(v):
# codes from : https://stackoverflow.com/questions/15008758/parsing-boolean-values-with-argparse
if v.lower() in ('yes', 'true', 't', 'y', '1'):
return True
elif v.lower() in ('no', 'false', 'f', 'n', '0'):
return False
else:
raise argparse.ArgumentTypeError('Boolean value expected.')
def print_network(net):
num_params = 0
for param in net.parameters():
num_params += param.numel()
print(net)
print('Total number of parameters: %d' % num_params)
def rm_dir(dir_path, silent=True):
p = Path(dir_path)
if (not p.is_file()) and (not p.is_dir()):
print('It is not path for file nor directory :', p)
return
paths = list(p.iterdir())
if not paths and p.is_dir():
p.rmdir()
if not silent:
print('removed empty dir :', p)
else:
for path in paths:
if path.is_file():
path.unlink()
if not silent:
print('removed file :', path)
else:
rm_dir(path)
p.rmdir()
if not silent:
print('removed empty dir :', p)
def where(cond, x, y):
"""Do same operation as np.where
code from:
https://discuss.pytorch.org/t/how-can-i-do-the-operation-the-same-as-np-where/1329/8
"""
cond = cond.float()
return (cond*x) + ((1-cond)*y)