forked from clementfarabet/lua---nnx
-
Notifications
You must be signed in to change notification settings - Fork 0
/
SuperCriterion.lua
45 lines (41 loc) · 1.44 KB
/
SuperCriterion.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
local SuperCriterion, parent = torch.class('nn.SuperCriterion', 'nn.Criterion')
function SuperCriterion:__init()
parent.__init(self)
self.criterions = {}
self.weights = {}
self.gradInput = {}
end
function SuperCriterion:add(criterion, weight)
weight = weight or 1
table.insert(self.criterions, criterion)
table.insert(self.weights, weight)
end
function SuperCriterion:forward(input, target)
self.output = 0
if type(target) == 'table' then
for i,criterion in ipairs(self.criterions) do
self.output = self.output + self.weights[i]*criterion:forward(input[i],target[i])
end
else
for i,criterion in ipairs(self.criterions) do
self.output = self.output + self.weights[i]*criterion:forward(input[i],target)
end
end
return self.output
end
function SuperCriterion:backward(input, target)
if type(target) == 'table' then
for i,criterion in ipairs(self.criterions) do
self.gradInput[i] = torch.Tensor() or self.gradInput[i]
self.gradInput[i]:resizeAs(input[i]):zero()
self.gradInput[i]:add(self.weights[i], criterion:backward(input[i],target[i]))
end
else
for i,criterion in ipairs(self.criterions) do
self.gradInput[i] = torch.Tensor() or self.gradInput[i]
self.gradInput[i]:resizeAs(input[i]):zero()
self.gradInput[i]:add(self.weights[i], criterion:backward(input[i],target))
end
end
return self.gradInput
end