MCPcopy Create free account
hub / github.com/CompVis/diff2flow / DiagonalGaussianDistribution

Class DiagonalGaussianDistribution

diff2flow/kl_autoencoder.py:45–83  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

43
44
45class DiagonalGaussianDistribution:
46 def __init__(self, parameters, deterministic=False):
47 self.parameters = parameters
48 self.mean, self.logvar = torch.chunk(parameters, 2, dim=1)
49 self.logvar = torch.clamp(self.logvar, -30.0, 20.0)
50 self.deterministic = deterministic
51 self.std = torch.exp(0.5 * self.logvar)
52 self.var = torch.exp(self.logvar)
53 if self.deterministic:
54 self.var = self.std = torch.zeros_like(self.mean).to(device=self.parameters.device)
55
56 def sample(self):
57 x = self.mean + self.std * torch.randn(self.mean.shape).to(device=self.parameters.device)
58 return x
59
60 def kl(self, other=None):
61 if self.deterministic:
62 return torch.Tensor([0.])
63 else:
64 if other is None:
65 return 0.5 * torch.sum(torch.pow(self.mean, 2)
66 + self.var - 1.0 - self.logvar,
67 dim=[1, 2, 3])
68 else:
69 return 0.5 * torch.sum(
70 torch.pow(self.mean - other.mean, 2) / other.var
71 + self.var / other.var - 1.0 - self.logvar + other.logvar,
72 dim=[1, 2, 3])
73
74 def nll(self, sample, dims=[1,2,3]):
75 if self.deterministic:
76 return torch.Tensor([0.])
77 logtwopi = np.log(2.0 * np.pi)
78 return 0.5 * torch.sum(
79 logtwopi + self.logvar + torch.pow(sample - self.mean, 2) / self.var,
80 dim=dims)
81
82 def mode(self):
83 return self.mean
84
85
86""" Resnet blocks """

Callers 1

encodeMethod · 0.85

Calls

no outgoing calls

Tested by

no test coverage detected