forked from icantnamemyself/FormerTime
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathloss.py
29 lines (23 loc) · 764 Bytes
/
loss.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
import torch
import torch.nn as nn
class CE:
def __init__(self, model):
self.model = model
self.ce = nn.CrossEntropyLoss()
def compute(self, batch):
seqs, labels = batch
outputs = self.model(seqs) # B * N
labels = labels.view(-1).long()
loss = self.ce(outputs, labels)
return loss
class BCE:
def __init__(self, model):
self.model = model
self.bce = nn.BCELoss(reduction='none')
def compute(self, batch):
seqs, labels = batch
outputs = self.model(seqs) # B * N
weight = torch.ones(outputs.shape[0]).float().to(outputs.device)
loss = self.bce(outputs.view(-1), labels.float())
loss = torch.mean(weight * loss)
return loss