Repository navigation
Expand file tree
/
Copy pathutils.py
More file actions
84 lines (67 loc) · 2.55 KB
/
Copy pathutils.py
File metadata and controls
84 lines (67 loc) · 2.55 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
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
import numpy as np
import torch
import random
from torch.utils.data import TensorDataset, DataLoader
import math
from torch import nn
from torch.utils.data import Dataset
def calculate_weighted_loss(preds, labels, weight, Epsilon):
loss1 = torch.mean(weight * nn.BCEWithLogitsLoss(reduction='none')(preds, labels))
loss2 = nn.BCEWithLogitsLoss()(preds, labels)
return loss1 + loss2*Epsilon
def set_requires_grad(model, requires_grad=True):
for param in model.parameters():
param.requires_grad = requires_grad
def loop_iterable(iterable):
while True:
yield from iterable
def fix_randomness(SEED):
random.seed(SEED)
np.random.seed(SEED)
torch.manual_seed(SEED)
torch.cuda.manual_seed(SEED)
torch.backends.cudnn.deterministic = True
def scoring_func(error_arr):
pos_error_arr = error_arr[error_arr >= 0]
neg_error_arr = error_arr[error_arr < 0]
score = 0
for error in neg_error_arr:
score = math.exp(-(error / 13)) - 1 + score
for error in pos_error_arr:
score = math.exp(error / 10) - 1 + score
return score
def roll(x, shift: int, dim: int = -1, fill_pad: int = None):
if 0 == shift:
return x
elif shift < 0:
shift = -shift
gap = x.index_select(dim, torch.arange(shift))
if fill_pad is not None:
gap = fill_pad * torch.ones_like(gap, device=x.device)
return torch.cat([x.index_select(dim, torch.arange(shift, x.size(dim))), gap], dim=dim)
else:
shift = x.size(dim) - shift
gap = x.index_select(dim, torch.arange(shift, x.size(dim)))
if fill_pad is not None:
gap = fill_pad * torch.ones_like(gap, device=x.device)
return torch.cat([gap, x.index_select(dim, torch.arange(shift))], dim=dim)
def init_weights(m):
for name, param in m.named_parameters():
nn.init.uniform_(param.data, -0.08, 0.08)
# if name=='weight':
# nn.init.kaiming_uniform_(param.data)
# else:
# torch.nn.init.zeros_(param.data)
def count_parameters(model):
return sum(p.numel() for p in model.parameters() if p.requires_grad)
class RMSELoss(nn.Module):
def __init__(self):
super().__init__()
self.mse = nn.MSELoss()
def forward(self,yhat,y):
return torch.sqrt(self.mse(yhat,y))
def epoch_time(start_time, end_time):
elapsed_time = end_time - start_time
elapsed_mins = int(elapsed_time / 60)
elapsed_secs = int(elapsed_time - (elapsed_mins * 60))
return elapsed_mins, elapsed_secs