forked from torch/nngraph
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathModuleFromCriterion.lua
28 lines (24 loc) · 1012 Bytes
/
ModuleFromCriterion.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
--[[ A wrapper to turn a criterion into a module.
The gradient with respect to the target will be zero.
--]]
local ModuleFromCriterion, parent = torch.class('nn.ModuleFromCriterion','nn.Module')
function ModuleFromCriterion:__init(criterion)
self.criterion = criterion
self.output = torch.Tensor(1)
self.gradInput = {torch.Tensor(), torch.Tensor()}
end
--[[ The input is a {prediction, target} pair.
The output is a tensor with one number: the criterion output.
--]]
function ModuleFromCriterion:updateOutput(input)
local prediction, target = unpack(input)
self.output[1] = self.criterion:updateOutput(prediction, target)
return self.output
end
function ModuleFromCriterion:updateGradInput(input, gradOutput)
local prediction, target = unpack(input)
local gradPrediction = self.criterion:updateGradInput(prediction, target)
self.gradInput[1]:resizeAs(gradPrediction):copy(gradPrediction):mul(gradOutput[1])
self.gradInput[2]:resizeAs(target):zero()
return self.gradInput
end