KL(N(\mu, \sigma), N(0, 1)) = \log \frac{1}{\sigma} + \frac{\sigma^2 + \mu^2}{2} - \frac{1}{2} :param args: :param kwargs: :return:
(self,
*args,
**kwargs)
| 127 | return [self.decode(z), input, mu, log_var, z, eps] |
| 128 | |
| 129 | def loss_function(self, |
| 130 | *args, |
| 131 | **kwargs) -> dict: |
| 132 | """ |
| 133 | KL(N(\mu, \sigma), N(0, 1)) = \log \frac{1}{\sigma} + \frac{\sigma^2 + \mu^2}{2} - \frac{1}{2} |
| 134 | :param args: |
| 135 | :param kwargs: |
| 136 | :return: |
| 137 | """ |
| 138 | recons = args[0] |
| 139 | input = args[1] |
| 140 | mu = args[2] |
| 141 | log_var = args[3] |
| 142 | z = args[4] |
| 143 | eps = args[5] |
| 144 | |
| 145 | input = input.repeat(self.num_samples, 1, 1, 1, 1).permute(1, 0, 2, 3, 4) #[B x S x C x H x W] |
| 146 | |
| 147 | kld_weight = kwargs['M_N'] # Account for the minibatch samples from the dataset |
| 148 | |
| 149 | log_p_x_z = ((recons - input) ** 2).flatten(2).mean(-1) # Reconstruction Loss [B x S] |
| 150 | kld_loss = -0.5 * torch.sum(1 + log_var - mu ** 2 - log_var.exp(), dim=2) ## [B x S] |
| 151 | # Get importance weights |
| 152 | log_weight = (log_p_x_z + kld_weight * kld_loss) #.detach().data |
| 153 | |
| 154 | # Rescale the weights (along the sample dim) to lie in [0, 1] and sum to 1 |
| 155 | weight = F.softmax(log_weight, dim = -1) |
| 156 | # kld_loss = torch.mean(kld_loss, dim = 0) |
| 157 | |
| 158 | loss = torch.mean(torch.sum(weight * log_weight, dim=-1), dim = 0) |
| 159 | |
| 160 | return {'loss': loss, 'Reconstruction_Loss':log_p_x_z.mean(), 'KLD':-kld_loss.mean()} |
| 161 | |
| 162 | def sample(self, |
| 163 | num_samples:int, |
nothing calls this directly
no outgoing calls
no test coverage detected