forked from eladhoffer/TripletNet
-
Notifications
You must be signed in to change notification settings - Fork 0
/
TripletNetBatch.lua
84 lines (68 loc) · 2.38 KB
/
TripletNetBatch.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
83
require 'nn'
local TripletNetBatch, parent = torch.class('nn.TripletNetBatch', 'nn.Module')
local function SizeSquashed(x)
local sz = x:size():totable()
local first = table.remove(sz,1)
sz[1] = sz[1]*first
return torch.LongStorage(sz)
end
function TripletNetBatch:__init(net, dist)
self.dist = dist or nn.PairwiseDistance(2)
self.Net = net or nn.Sequential()
self.output = torch.Tensor()
self.netOutput = torch.Tensor()
self.distGradInput = torch.Tensor()
end
function TripletNetBatch:add(module)
self.Net:add(module)
end
function TripletNetBatch:updateOutput(input)
local x = input:view(SizeSquashed(input))
self.output:resize(input:size(2), input:size(1)- 1):typeAs(x)
self.netOutput = self.Net:updateOutput(x)
self.sub_output = torch.chunk(self.netOutput, input:size(1))
for i=1, input:size(1)-1 do
self.output[{{},i}]:copy(self.dist:updateOutput({self.sub_output[1],self.sub_output[i+1]}))
end
return self.output
end
function TripletNetBatch:updateGradInput(input,gradOutput)
local sz = self.netOutput:size():totable()
sz[1] = input:size(2)
table.insert(sz,1,input:size(1))
self.distGradInput:resize(unpack(sz))
self.distGradInput:zero()
for i=1, input:size(1)-1 do
local dyi = gradOutput[{{},i}]
local dEi = self.dist:updateGradInput({self.sub_output[1],self.sub_output[i+1]},dyi)
self.distGradInput[1]:add(dEi[1])
self.distGradInput[i+1]:copy(dEi[2])
end
local x = input:view(SizeSquashed(input))
self.gradInput = self.Net:updateGradInput(x, self.distGradInput:view(SizeSquashed(self.distGradInput)))
return self.gradInput
end
function TripletNetBatch:accGradParameters(input, gradOutput, scale)
local x = input:view(SizeSquashed(input))
self.Net:accGradParameters(x, self.distGradInput:view(SizeSquashed(self.distGradInput)), scale)
end
function TripletNetBatch:training()
self.Net:training()
end
function TripletNetBatch:evaluate()
self.Net:evaluate()
end
function TripletNetBatch:getParameters()
local w, g = self.Net:getParameters()
return w,g
end
function TripletNetBatch:parameters()
return self.Net:parameters()
end
function TripletNetBatch:type(t)
self.Net:type(t)
self.dist:type(t)
self.output = self.output:type(t)
self.netOutput = self.netOutput:type(t)
self.distGradInput = self.distGradInput:type(t)
end