-
Notifications
You must be signed in to change notification settings - Fork 3
/
utils.py
101 lines (83 loc) · 2.44 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
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
import torch
from torch.utils import data
class Digits(data.Dataset):
def __init__(self, digits, labels, mask=None, binarize=False):
self.labels = labels
if binarize:
self.data = (torch.rand_like(digits) < digits).type(torch.float)
else:
self.data = digits.type(torch.float)
def __len__(self):
return len(self.data)
def __getitem__(self, index):
"Generates one sample of data"
# Select sample
X = self.data[index]
y = self.labels[index]
return X, y
def create_metric(model, device='cpu'):
"""
Metric creation for RHVAE model
"""
def G(z):
return torch.inverse(
(
model.M_tens.unsqueeze(0)
* torch.exp(
-torch.norm(
model.centroids_tens.unsqueeze(0) - z.unsqueeze(1), dim=-1
)
** 2
/ (model.T ** 2)
)
.unsqueeze(-1)
.unsqueeze(-1)
).sum(dim=1)
+ model.lbd * torch.eye(model.latent_dim).to(device)
)
return G
def create_metric_inv(model, device='cpu'):
"""
Metric creation for RHVAE model
"""
def G_inv(z):
return (
model.M_tens.unsqueeze(0)
* torch.exp(
-torch.norm(model.centroids_tens.unsqueeze(0) - z.unsqueeze(1), dim=-1)
** 2
/ (model.T ** 2)
)
.unsqueeze(-1)
.unsqueeze(-1)
).sum(dim=1) + model.lbd * torch.eye(model.latent_dim).to(device)
return G_inv
def create_dH_dz(model):
"""
Computation of derivative of Hamiltonian for RHVAE model
"""
def dH_dz(z, q):
a = (
torch.transpose(q.unsqueeze(-1).unsqueeze(1), 2, 3)
@ model.M_tens.unsqueeze(0)
@ q.unsqueeze(-1).unsqueeze(1)
)
b = centroids_tens.unsqueeze(0) - z.unsqueeze(1)
return (
-1
/ (model.T ** 2)
* b.unsqueeze(-1)
@ a
* (
torch.exp(
-torch.norm(
model.centroids_tens.unsqueeze(0) - z.unsqueeze(1), dim=-1
)
** 2
/ (model.T ** 2)
)
)
.unsqueeze(-1)
.unsqueeze(-1)
).sum(dim=1)
return dH_dz