PVD/modules/functional/loss.py

18 lines
482 B
Python
Raw Normal View History

2021-10-19 20:54:46 +00:00
import torch
import torch.nn.functional as F
2023-04-11 09:12:58 +00:00
__all__ = ["kl_loss", "huber_loss"]
2021-10-19 20:54:46 +00:00
def kl_loss(x, y):
x = F.softmax(x.detach(), dim=1)
y = F.log_softmax(y, dim=1)
return torch.mean(torch.sum(x * (torch.log(x) - y), dim=1))
def huber_loss(error, delta):
abs_error = torch.abs(error)
quadratic = torch.min(abs_error, torch.full_like(abs_error, fill_value=delta))
2023-04-11 09:12:58 +00:00
losses = 0.5 * (quadratic**2) + delta * (abs_error - quadratic)
2021-10-19 20:54:46 +00:00
return torch.mean(losses)