forked from nguyenvo09/EMNLP2020
-
Notifications
You must be signed in to change notification settings - Fork 0
/
losses.py
42 lines (34 loc) · 1.11 KB
/
losses.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
import torch
import numpy as np
import torch.nn.functional as F
from torch.autograd import Variable
from torch_utils import assert_no_grad
def hinge_loss(positive_predictions, negative_predictions, mask=None, average=False):
"""
Hinge pairwise loss function.
Parameters
----------
positive_predictions: tensor
Tensor containing predictions for known positive items.
negative_predictions: tensor
Tensor containing predictions for sampled negative items.
mask: tensor, optional
A binary tensor used to zero the loss from some entries
of the loss tensor.
Returns
-------
loss, float
The mean value of the loss function.
"""
# checked, usually we need to use a threshold as soft-margin (but this function does not have it)
loss = torch.clamp(negative_predictions -
positive_predictions +
1.0, 0.0)
if mask is not None:
mask = mask.float()
loss = loss * mask
return loss.sum() / mask.sum()
if average:
return loss.mean()
else:
return loss.sum()