Created
July 24, 2019 20:28
-
-
Save nasimrahaman/26704172cc081d3f74567e65ece73c5b to your computer and use it in GitHub Desktop.
Continoulli with Logits
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import torch | |
import torch.nn as nn | |
class ContinoulliWithLogitsLoss(nn.BCEWithLogitsLoss): | |
""" | |
Numerically stable implementation of the objective function defined in [1]. | |
[1] https://arxiv.org/abs/1907.06845 | |
""" | |
def forward(self, input, target): | |
bce = super(ContinoulliWithLogitsLoss, self).forward(input, target) | |
logZ = torch.log(self.Z(input)) | |
if self.reduction == 'mean': | |
logZ = logZ.mean() | |
elif self.reduction == 'sum': | |
logZ = logZ.sum() | |
else: | |
return NotImplementedError | |
return bce + logZ | |
@staticmethod | |
def Z(x): | |
t = (0.5 * x).tanh() | |
return x.div(t + t.detach().eq(0).to(t)).clamp_min(2) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment