torch7学习(一)——Tensor 总说上篇博客已经初步介绍了Module类。这里将更加仔细的介绍。并且还将介绍Container, Transfer Functions Layers和 Simple Layers模块。 Module主要有4个函数。 Container复杂的神经网络可以用container类进行构建。 用法就是,一般是用一个Sequential,然后不断add(module),而module有simple layers和卷积层。在后面进行说明。 Transfer Functions Layers就是激活函数,在第上一篇博客已经说明了,torch中讲神经网络看成是module(或是container)的组合。你可以加入层模块,或是激活函数的层模块,最后还可以加上criterion层模块。如此一来,整个网络就构建好了。 ii=torch.linspace(-3,3)m=nn.Tanh()oo=m:forward(ii)go=torch.ones(100)gi=m:backward(ii,go)gnuplot.plot({'f(x)',ii,oo,'+-'},{'df/dx',ii,gi,'+-'})gnuplot.grid(true)
Simple Layers简单层有很多,一些是提供仿射变换的,一些是进行Tensor method的。
下面调重要常见的几个 Linearmodule = nn.Linear(inputDim, outputDim, [bias = true])
Linear就是全连接呗。 module = nn.Linear(10,5)mlp = nn.Sequential()mlp:add(module)print(module.weight)print(module.bias)print(module.gradWeight)print(module.gradBias)x = torch.Tensor(10) -- 10 inputsy = module:forward(x)
运行后发现,只要初始化后网络,里面就有初始权值和偏置。但是gradBias和gradGradient不是很大就是很小,显然这是垃圾数据。现在有个问题,网络权值的初始化对整个网络的训练非常重要,torch是怎样自定义初始化权值的呢?我现在还没发现!先做个标记! Dropoutmodule = nn.Dropout(p)
这个就是Dropout层。简单的说每一个神经元的输入将会以p的概率丢弃。这个方法是一个避免过拟合的正规化方法。可参见Improving neural networks by preventing co-adaptation of feature detectors module = nn.Dropout()> x = torch.Tensor{{1, 2, 3, 4}, {5, 6, 7, 8}}> module:forward(x) 2 0 0 8 10 0 14 0[torch.DoubleTensor of dimension 2x4]> module:forward(x) 0 0 6 0 10 0 0 0[torch.DoubleTensor of dimension 2x4]
可以看出,上面一些值被丢弃。 View这个主要是改变网络输出的tensor的sizes,就是reshape一下。 module = nn.View(sizes)
如果是用view(-1)则可特别地用作minibatch的输入。 x = torch.Tensor(4, 4)for i = 1, 4 do for j = 1, 4 do x[i][j] = (i-1)*4+j end end print(nn.View(2, 8):forward(x))--[[ 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 ]]
作为minibatch的输入! > input = torch.Tensor(2, 3)> minibatch = torch.Tensor(5, 2, 3)> m = nn.View(-1):setNumInputDims(2)> print(#m:forward(minibatch)) 5 6[torch.LongStorage of size 2] --每一行就是一个example的结果。
Normalizemodule = nn.Normalize(p, [eps])
L-p范式进行归一化,eps默认是1e-10,防止输入全为0时除0的情况。 MMmodule = nn.MM(transA,transB)
transA/transB 为true时,则对应的矩阵进行转置。 module = nn.MM(true, false)A = torch.randn(b,n,m)B = torch.randn(b,n,p)c = module:forward({A, B})--[[c是 b * m * p的]]
简单层一个常见的Module是Add,放在下篇博客讲。因为会用简单层的Add模块讲手动挡训练演示。 |
|