转载自: https://blog.youkuaiyun.com/hejunqing14/article/details/52162970
通常,一个网络在torch中被称为一个模块Module.里面主要有4个函数:forward(),backward(),zeroGradParameters()和updateParameters()。这些函数的使用方法如下:
forward(input) 给定输入,计算这个网络模块的输出
backward(input, gradOutput)给定输入和当前的参数,计算这个网络中参数的梯度.
zeroGradParameters()将网络模块中的参数的梯度置0
updateParameters(learningRate) 在执行完backward之后用它返回的梯度更新参数
转载自:https://blog.youkuaiyun.com/hejunqing14/article/details/52162970#nngmodel
nn.gModel()
nngraph(nn) 是一个基于有向无环图的模块,所有的节点建立完后,需要使用nn.gModel()组成一个图。
module=nn.gModule(input,output)
这里的input 和output既可以是元素,也可以是列表。这个函数会生成一个从input到output的图。其中此前的每一个模块后面加上该模块输入,成为这个图中的节点。
给出一个简单的例子:
x1 = nn.Identity()()
x2 = nn.Identity()()
a = nn.CAddTable()({x1, x2})
m = nn.gModule({x1, x2}, {a})
这里只是对两个输入进行了合并,然后进行输出,一个有3个模块,对应3个图节点,其中两个是输入节点。这样会生成一个如下图的计算图,这样在调用m的时候会根据这个图进行计算,输出a的值。
__|__ __|__
| | | |
|____| |____|
| x1 | x2
\ /
\z /
_\ /_
| |
|____|
|a
nn.JoinTable()
module = JoinTable(dimension, nInputDims)
这个函数创建了一个模块,将输入的张量数组在dimension维度上进行合并并输出。可选的参数nInputDims表示接收的输入的维数,这样可以使得minibatch 或者非batch的输入同样可以通过这个模块。下面是dimension=1(按列)时的图示:
+----------+ +-----------+
| {input1, +-------------> output[1] |
| | +-----------+-+
| input2, +-----------> output[2] |
| | +-----------+-+
| input3} +---------> output[3] |
+----------+ +-----------+
x = torch.randn(5, 1)
y = torch.randn(5, 1)
z = torch.randn(2, 1)
print(nn.JoinTable(1):forward{x, y})
print(nn.JoinTable(2):forward{x, y})
print(nn.JoinTable(1):forward{x, z})
>1.3965
0.5146
-1.5244
-0.9540
0.4256
0.1575
0.4491
0.6580
0.1784
-1.7362
[torch.DoubleTensor of dimension 10x1]
1.3965 0.1575
0.5146 0.4491
-1.5244 0.6580
-0.9540 0.1784
0.4256 -1.7362
[torch.DoubleTensor of dimension 5x2]
1.3965
0.5146
-1.5244
-0.9540
0.4256
-1.2660
1.0869
[torch.Tensor of dimension 7x1]
nn.CMulTable():
th> nn.CMulTable():forward({a,b})
它就是把a和b的矩阵相乘
nn.CAddTable()
th> nn.CAddTable():forward({a,b})
它就是把a和b的矩阵相加