-
Notifications
You must be signed in to change notification settings - Fork 111
/
Copy pathhyperspherical_uniform.py
56 lines (43 loc) · 1.58 KB
/
hyperspherical_uniform.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
import math
import torch
class HypersphericalUniform(torch.distributions.Distribution):
support = torch.distributions.constraints.real
has_rsample = False
_mean_carrier_measure = 0
@property
def dim(self):
return self._dim
@property
def device(self):
return self._device
@device.setter
def device(self, val):
self._device = val if isinstance(val, torch.device) else torch.device(val)
def __init__(self, dim, validate_args=None, device="cpu"):
super(HypersphericalUniform, self).__init__(
torch.Size([dim]), validate_args=validate_args
)
self._dim = dim
self.device = device
def sample(self, shape=torch.Size()):
output = (
torch.distributions.Normal(0, 1)
.sample(
(shape if isinstance(shape, torch.Size) else torch.Size([shape]))
+ torch.Size([self._dim + 1])
)
.to(self.device)
)
return output / output.norm(dim=-1, keepdim=True)
def entropy(self):
return self.__log_surface_area()
def log_prob(self, x):
return -torch.ones(x.shape[:-1], device=self.device) * self.__log_surface_area()
def __log_surface_area(self):
if torch.__version__ >= "1.0.0":
lgamma = torch.lgamma(torch.tensor([(self._dim + 1) / 2]).to(self.device))
else:
lgamma = torch.lgamma(
torch.Tensor([(self._dim + 1) / 2], device=self.device)
)
return math.log(2) + ((self._dim + 1) / 2) * math.log(math.pi) - lgamma