-
Notifications
You must be signed in to change notification settings - Fork 0
/
active_loss.py
38 lines (33 loc) · 1.05 KB
/
active_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
30
31
32
33
34
35
36
37
38
''' Loss functions for active Learning.
'''
import os
import sys
import time
import math
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.nn.init as init
class LossPredictionLoss(nn.Module):
def __init__(self, margin=1.0):
super(LossPredictionLoss, self).__init__()
self.margin = margin
def forward(self, input, target):
# print(input.shape)
# print(input)
input = (
input - input.flip(0)
)[:len(input) // 2
] # [l_1 - l_2B, l_2 - l_2B-1, ... , l_B - l_B+1], where batch_size = 2B
# print(input.shape)
# print(target.shape)
target = (target - target.flip(0))[:len(target) // 2]
target = target.detach()
one = 2 * torch.sign(
torch.clamp(target, min=0)
) - 1 # 1 operation which is defined by the authors
loss = torch.sum(torch.clamp(self.margin - one * input, min=0))
loss = loss / input.size(
0
) # Note that the size of input is already halved
return loss