-
Notifications
You must be signed in to change notification settings - Fork 82
/
SpatialFeatNormalization.lua
73 lines (69 loc) · 2.39 KB
/
SpatialFeatNormalization.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
--[[
Color normalization (mean zeroing and dividing by standard deviation).
Basic preprocessing step widely used in training classifier with images.
--]]
local SpatialFeatNormalization, Parent = torch.class('nn.SpatialFeatNormalization', 'nn.Module')
function SpatialFeatNormalization:__init(mean, std)
Parent.__init(self)
if mean:dim() ~= 1 then
error('<SpatialFeatNormalization> Mean/Std should be 1D.')
end
self.mean = torch.Tensor()
self.mean:resizeAs(mean):copy(mean)
self.std = torch.Tensor()
self.std:resizeAs(mean)
if std ~= nil then self.std:copy(std) else self.std:fill(1) end
self.noOfFeats = mean:size(1)
end
function SpatialFeatNormalization:updateOutput(input)
self.output:resizeAs(input):copy(input)
if input:dim() == 4 then
-- Batch of image/s
if input:size(2) ~= self.noOfFeats then
error('<SpatialFeatNormalization> No. of Feats dont match.')
else
for i=1, self.noOfFeats do
self.output[{{}, i, {}, {}}]:add(-self.mean[i])
self.output[{{}, i, {}, {}}]:div(self.std[i])
end
end
elseif input:dim() == 3 then
-- single image
if input:size(1) ~= self.noOfFeats then
error('<SpatialFeatNormalization> No. of Feats dont match.')
else
for i=1, self.noOfFeats do
self.output[{i, {}, {}}]:add(-self.mean[i])
self.output[{i, {}, {}}]:div(self.std[i])
end
end
else
error('<SpatialFeatNormalization> invalid input dims.')
end
return self.output
end
function SpatialFeatNormalization:updateGradInput(input, gradOutput)
self.gradInput:resizeAs(gradOutput):copy(gradOutput)
if self.gradInput:dim() == 4 then
-- Batch of image/s
if self.gradInput:size(2) ~= self.noOfFeats then
error('<SpatialFeatNormalization> No. of Feats dont match.')
else
for i=1, self.noOfFeats do
self.gradInput[{{}, i, {}, {}}]:div(self.std[i])
end
end
elseif self.gradInput:dim() == 3 then
-- single image
if self.gradInput:size(1) ~= self.noOfFeats then
error('<SpatialFeatNormalization> No. of Feats dont match.')
else
for i=1, self.noOfFeats do
self.gradInput[{i, {}, {}}]:div(self.std[i])
end
end
else
error('<SpatialFeatNormalization> invalid self.gradInput dims.')
end
return self.gradInput
end