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
|
local WeightedEuclidean, parent = torch.class('nn.WeightedEuclidean', 'nn.Module')
function WeightedEuclidean:__init(inputSize,outputSize)
parent.__init(self)
self.templates = torch.Tensor(inputSize,outputSize)
self.gradTemplates = torch.Tensor(inputSize,outputSize)
self.diagCov = torch.Tensor(inputSize,outputSize)
self.gradDiagCov = torch.Tensor(inputSize,outputSize)
self.gradInput:resize(inputSize)
self.output:resize(outputSize)
self.temp = torch.Tensor(inputSize)
-- for compat with Torch's modules (it's bad we have to do that)
do
self.weight = self.templates
self.gradWeight = self.gradTemplates
self.bias = self.diagCov
self.gradBias = self.gradDiagCov
end
self:reset()
end
function WeightedEuclidean:reset(stdv)
if stdv then
stdv = stdv * math.sqrt(3)
else
stdv = 1./math.sqrt(self.templates:size(1))
end
self.templates:uniform(-stdv, stdv)
self.diagCov:fill(1)
end
function WeightedEuclidean:updateOutput(input)
self.output:zero()
for o = 1,self.templates:size(2) do
self.temp:copy(input):add(-1,self.templates:select(2,o))
self.temp:cmul(self.temp)
self.temp:cmul(self.diagCov:select(2,o)):cmul(self.diagCov:select(2,o))
self.output[o] = math.sqrt(self.temp:sum())
end
return self.output
end
function WeightedEuclidean:updateGradInput(input, gradOutput)
self:forward(input)
self.gradInput:zero()
for o = 1,self.templates:size(2) do
if self.output[o] ~= 0 then
self.temp:copy(input):add(-1,self.templates:select(2,o))
self.temp:cmul(self.diagCov:select(2,o)):cmul(self.diagCov:select(2,o))
self.temp:mul(gradOutput[o]/self.output[o])
self.gradInput:add(self.temp)
end
end
return self.gradInput
end
function WeightedEuclidean:accGradParameters(input, gradOutput, scale)
self:forward(input)
scale = scale or 1
for o = 1,self.templates:size(2) do
if self.output[o] ~= 0 then
self.temp:copy(self.templates:select(2,o)):add(-1,input)
self.temp:cmul(self.diagCov:select(2,o)):cmul(self.diagCov:select(2,o))
self.temp:mul(gradOutput[o]/self.output[o])
self.gradTemplates:select(2,o):add(self.temp)
self.temp:copy(self.templates:select(2,o)):add(-1,input)
self.temp:cmul(self.temp)
self.temp:cmul(self.diagCov:select(2,o))
self.temp:mul(gradOutput[o]/self.output[o])
self.gradDiagCov:select(2,o):add(self.temp)
end
end
end
|