-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathTrueNLLCriterion.lua
More file actions
57 lines (49 loc) · 1.38 KB
/
TrueNLLCriterion.lua
File metadata and controls
57 lines (49 loc) · 1.38 KB
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
-- Copyright 2004-present Facebook. All Rights Reserved.
--[[
`TrueNLLCriterion` computes the negative log-loss criterion directly.
]]
if nn.TrueNLLCriterion then
return
end
local TrueNLLCriterion, parent = torch.class('nn.TrueNLLCriterion',
'nn.Criterion')
-- For numerical stability
--local eps = 0.00000001
local eps = 1.0e-15
function TrueNLLCriterion:__init()
parent.__init(self)
self.sizeAverage = true
end
function TrueNLLCriterion:updateOutput(input, target)
if input:dim() == 1 then
self.output = -math.log(input[target] + eps)
elseif input:dim() == 2 then
local output = 0
for i=1,target:size(1) do
output = output - math.log(input[i][target[i]] + eps)
end
if self.sizeAverage then
output = output / target:size(1)
end
self.output = output
else
error('matrix or vector expected')
end
return self.output
end
function TrueNLLCriterion:updateGradInput(input, target)
self.gradInput:resizeAs(input)
self.gradInput:zero()
if input:dim() == 1 then
self.gradInput[target] = -1 / (input[target] + eps)
else
local z = -1
if self.sizeAverage then
z = z / target:size(1)
end
for i=1,target:size(1) do
self.gradInput[i][target[i]] = z / (input[i][target[i]] + eps)
end
end
return self.gradInput
end