-
Notifications
You must be signed in to change notification settings - Fork 2
/
ClassNLLCriterion.lua
75 lines (64 loc) · 1.73 KB
/
ClassNLLCriterion.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
local ClassNLLCriterion, parent = torch.class(
'nn.ClassNLLCriterion',
'nn.Criterion'
)
function ClassNLLCriterion:__init(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()
end
function ClassNLLCriterion:__len()
if (self.weights) then
return #self.weights
else
return 0
end
end
function ClassNLLCriterion:updateOutput(input, target)
if type(target) == 'number' then
self.target[1] = target
elseif target:type() == 'torch.CudaTensor' then
self.target = target
else
self.target = target:long()
end
input.nn.ClassNLLCriterion_updateOutput(
input,
self.target,
self.weights,
self.sizeAverage,
self.output_tensor,
self.total_weight_tensor
)
self.output = self.output_tensor[1]
return self.output, self.total_weight_tensor[1]
end
function ClassNLLCriterion:updateGradInput(input, target)
if type(target) == 'number' then
self.target[1] = target
elseif target:type() == 'torch.CudaTensor' then
self.target = target
else
self.target = target:long()
end
self.gradInput:resizeAs(input):zero()
input.nn.ClassNLLCriterion_updateGradInput(
input,
self.target,
self.weights,
self.sizeAverage,
self.total_weight_tensor,
self.gradInput
)
return self.gradInput
end