-
Notifications
You must be signed in to change notification settings - Fork 11
/
utils.py
55 lines (40 loc) · 1.49 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
"""utils.py"""
import argparse
import subprocess
import torch
import torch.nn as nn
from torch.autograd import Variable
def cuda(tensor, uses_cuda):
return tensor.cuda() if uses_cuda else 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 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)
def grid2gif(image_str, output_gif, delay=100):
"""Make GIF from images.
code from:
https://stackoverflow.com/questions/753190/programmatically-generate-video-or-animated-gif-in-python/34555939#34555939
"""
str1 = 'convert -delay '+str(delay)+' -loop 0 ' + image_str + ' ' + output_gif
subprocess.call(str1, shell=True)
def Cor_CoeLoss( y_pred, y_target):
x = y_pred
y = y_target
x_var = x - torch.mean(x)
y_var = y - torch.mean(y)
r_num = torch.sum(x_var * y_var)
r_den = torch.sqrt(torch.sum(x_var ** 2)) * torch.sqrt(torch.sum(y_var ** 2))
r = r_num / r_den
# return 1 - r # best are 0
return 1 - r ** 2 # abslute constrain