通过gModule向后火炬

时间:2015-11-05 13:04:20

标签: lua neural-network torch backpropagation

我有一个如下图表,其中输入x有两条到达y的路径。它们与使用cMulTable的gModule结合使用。现在,如果我执行gModule:backward(x,y),我会得到一个包含两个值的表。它们是否对应于从两条路径导出的误差导数? enter image description here

但是由于path2包含其他nn层,我想我需要以逐步的方式在此路径中派生派生。但为什么我得到dy / dx的两个值的表格?

为了使事情更清楚,测试它的代码如下:

input1 = nn.Identity()()
input2 = nn.Identity()()
score = nn.CAddTable()({nn.Linear(3, 5)(input1),nn.Linear(3, 5)(input2)})
g = nn.gModule({input1, input2}, {score})  #gModule

mlp = nn.Linear(3,3) #path2 layer

x = torch.rand(3,3)
x_p = mlp:forward(x)
result = g:forward({x,x_p})
error = torch.rand(result:size())
gradient1 = g:backward(x, error)  #this is a table of 2 tensors
gradient2 = g:backward(x_p, error)  #this is also  a table of 2 tensors

我的步骤出了什么问题?

P.S,也许我已经找到了原因,因为g:backward({x,x_p},error)导致同一个表。所以我猜这两个值分别代表dy / dx和dy / dx_p。

1 个答案:

答案 0 :(得分:1)

我认为你在构建gModule时犯了一个错误。每个gradInput的{​​{1}}必须与其nn.Module具有完全相同的结构 - 这就是backprop的工作方式。

以下是使用input创建与您类似的模块的示例:

nngraph

<强>更新

正如我所说,每个require 'torch' require 'nn' require 'nngraph' function CreateModule(input_size) local input = nn.Identity()() -- network input local nn_module_1 = nn.Linear(input_size, 100)(input) local nn_module_2 = nn.Linear(100, input_size)(nn_module_1) local output = nn.CMulTable()({input, nn_module_2}) -- pack a graph into a convenient module with standard API (:forward(), :backward()) return nn.gModule({input}, {output}) end input = torch.rand(30) my_module = CreateModule(input:size(1)) output = my_module:forward(input) criterion_err = torch.rand(output:size()) gradInput = my_module:backward(input, criterion_err) print(gradInput) 的{​​{1}}必须与其gradInput具有完全相同的结构。因此,如果您将模块定义为nn.Module,则input(向后传递的结果)将是一个渐变表w.r.t. nn.gModule({input1, input2}, {score})gradOutput,在您的情况下为input1input2

唯一的问题仍然是:为什么地球上的电话不会出现错误:

x

必须引发异常,因为第一个参数必须不是张量,而是两个张量的表。好吧,大多数(也许全部)火炬模块在计算x_p时不使用gradient1 = g:backward(x, error) gradient2 = g:backward(x_p, error) 参数(他们通常会存储上次:backward(input, gradOutput)来电中的input副本)。事实上,这个论点是如此无用,以至于模块甚至不必费心去验证它。