-
Notifications
You must be signed in to change notification settings - Fork 966
/
ClassNLLCriterion.lua
82 lines (73 loc) · 2.49 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
76
77
78
79
80
81
82
local THNN = require 'nn.THNN'
local ClassNLLCriterion, parent = torch.class('nn.ClassNLLCriterion', 'nn.Criterion')
function ClassNLLCriterion:__init(weights, sizeAverage, ignoreIndex)
parent.__init(self)
self.sizeAverage = (sizeAverage == nil) and true or sizeAverage
self.ignoreIndex = ignoreIndex or -100 -- this target index will be ignored
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
if torch.typename(input):find('torch%.Cuda.*Tensor') then
self.target = torch.CudaLongTensor and self.target:cudaLong() or self.target:cuda()
else
self.target = self.target:long()
end
self.target:resize(1)
self.target[1] = target
elseif torch.typename(input):find('torch%.Cuda.*Tensor') then
self.target = torch.CudaLongTensor and target:cudaLong() or target
else
self.target = target:long()
end
input.THNN.ClassNLLCriterion_updateOutput(
input:cdata(),
self.target:cdata(),
self.output_tensor:cdata(),
self.sizeAverage,
THNN.optionalTensor(self.weights),
self.total_weight_tensor:cdata(),
self.ignoreIndex
)
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
if torch.typename(input):find('torch%.Cuda.*Tensor') then
self.target = torch.CudaLongTensor and self.target:cudaLong() or self.target:cuda()
else
self.target = self.target:long()
end
self.target:resize(1)
self.target[1] = target
elseif torch.typename(input):find('torch%.Cuda.*Tensor') then
self.target = torch.CudaLongTensor and target:cudaLong() or target
else
self.target = target:long()
end
self.gradInput:resizeAs(input):zero()
input.THNN.ClassNLLCriterion_updateGradInput(
input:cdata(),
self.target:cdata(),
self.gradInput:cdata(),
self.sizeAverage,
THNN.optionalTensor(self.weights),
self.total_weight_tensor:cdata(),
self.ignoreIndex
)
return self.gradInput
end