-
Notifications
You must be signed in to change notification settings - Fork 0
/
MultilabelCrossEntropyCriterion.lua
96 lines (83 loc) · 2.86 KB
/
MultilabelCrossEntropyCriterion.lua
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
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
local THNN = require 'nn.THNN'
local MultilabelCrossEntropyCriterion, parent = torch.class('nn.MultilabelCrossEntropyCriterion', 'nn.Criterion')
function MultilabelCrossEntropyCriterion:__init(loss_weight, weights, sizeAverage)
parent.__init(self)
if sizeAverage ~= nil then
self.sizeAverage = sizeAverage
else
self.sizeAverage = true
end
if weights then
assert(weights:dim() == 1, "weights input should be 1-D Tensor")
self.weights = weights
end
self.output_tensor = torch.zeros(1)
self.total_weight_tensor = torch.ones(1)
self.target = torch.zeros(1):long()
-- support caffe loss weight
if loss_weight then
self.loss_weight = loss_weight
else
self.loss_weight = 1
end
assert(self.loss_weight > 0)
end
function MultilabelCrossEntropyCriterion:__len()
if (self.weights) then
return #self.weights
else
return 0
end
end
--[[
this implementation only penalizes correct labels
--]]
function MultilabelCrossEntropyCriterion:updateOutput(input, target)
if target:type() == 'torch.CudaTensor' then
-- check that input and target have the same shape
assert(input:size(1) == target:size(1)) -- batch_size
assert(input:size(2) == target:size(2)) -- num_target
local eps = 1e-5
local loss = 0
local l = 0
for i=1,input:size(1) do
for j=1,input:size(2) do
if target[i][j] == 1 then
l = -torch.log(math.max(input[i][j], eps))
else
l = -torch.log(math.max(1-input[i][j], eps))
end
loss = loss + l
end
end
loss = loss/input:nElement()
self.output = loss
else
error('Only support target type of CudaTensor')
end
return self.output, self.total_weight_tensor[1]
end
-- Note that loss_weight is multipiled at element-wise
function MultilabelCrossEntropyCriterion:updateGradInput(input, target)
if target:type() == 'torch.CudaTensor' then
-- check that input and target have the same shape
assert(input:size(1) == target:size(1)) -- batch_size
assert(input:size(2) == target:size(2)) -- num_target
self.gradInput:resizeAs(input):zero()
local eps = 1e-5
local val = 0
for i=1,input:size(1) do
for j=1,input:size(2) do
if target[i][j] == 1 then
val = -self.loss_weight/(math.max(input[i][j], eps) * input:nElement())
else
val = self.loss_weight/(math.max(1-input[i][j], eps) * input:nElement())
end
self.gradInput[i][j] = val
end
end
else
error('Only support target type of CudaTensor')
end
return self.gradInput
end