I’m using the loss function suggested here for weighted loss in binary classification :
def weighted_binary_cross_entropy(output, target, weights=None):
        
    if weights is not None:
        assert len(weights) == 2
        
        loss = weights[1] * (target * torch.log(output)) + \
               weights[0] * ((1 - target) * torch.log(1 - output))
    else:
        loss = target * torch.log(output) + (1 - target) * torch.log(1 - output)

    return torch.neg(torch.mean(loss))

but after certain epochs, the loss goes NaN :
tensor(0.1091, device='cuda:0', grad_fn=<NegBackward>)
17.43889331445098

tensor(nan, device='cuda:0', grad_fn=<NegBackward>)
nan

This is the output i get when i use BCEloss instead of custom loss  :
tensor(0.1180, device='cuda:0', grad_fn=<BinaryCrossEntropyBackward>)
23.021491292864084

what is causing this ?