5 Copyright (c) 2016 Idiap Research Institute, http://www.idiap.ch/
6 Written by Francois Fleuret <francois.fleuret@idiap.ch>
8 This file is free software: you can redistribute it and/or modify
9 it under the terms of the GNU General Public License version 3 as
10 published by the Free Software Foundation.
12 It is distributed in the hope that it will be useful, but WITHOUT
13 ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
14 or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public
15 License for more details.
17 You should have received a copy of the GNU General Public License
18 along with this file. If not, see <http://www.gnu.org/licenses/>.
26 -- torch.setnumthreads(params.nbThreads)
27 torch.setdefaulttensortype('torch.DoubleTensor')
30 function checkGrad(model, criterion, input, target)
31 local params, gradParams = model:getParameters()
35 local output = model:forward(input)
36 local loss = criterion:forward(output, target)
37 local gradOutput = criterion:backward(output, target)
39 model:backward(input, gradOutput)
40 local analyticalGradParam = gradParams:clone()
42 for i = 1, params:size(1) do
45 params[i] = x - epsilon
46 local output0 = model:forward(input)
47 local loss0 = criterion:forward(output0, target)
49 params[i] = x + epsilon
50 local output1 = model:forward(input)
51 local loss1 = criterion:forward(output1, target)
55 local ana = analyticalGradParam[i]
56 local num = (loss1 - loss0) / (2 * epsilon)
62 err = torch.abs(num - ana) / torch.abs(num)
69 .. ' analytical ' .. ana
70 .. ' numerical ' .. num
76 function printTensorTable(t)
77 if torch.type(t) == 'table' then
78 for i, t in pairs(t) do
79 print('-- ELEMENT [' .. i .. '] --')
90 -- input --> a --> b ---> d ----+ g --> output
100 f = nn.Linear(15, 15)
106 model:addEdge(b, nn.Linear(10, 5), nn.ReLU(), nn.Linear(5, 10), c)
112 model:addEdge(f, nn.Mul(-1), g)
117 local input = torch.Tensor(30, 50):uniform()
118 local output = model:updateOutput(input):clone()
122 checkGrad(model, nn.MSECriterion(), input, output)