torch
Before
Lua is pretty close to javascript(var are global by default, unless local keyword is used)
only has one data structure: table {}. hash table and an array.
indexing from 1
foo:bar() is equal to foo:bar(foo)
Start
- String: like python: 英文状态下单双引号都可以。
- print: 输出函数,需要加括号,函数名后直接加括号,也可以加空格再加括号。
- table: 定义一个变量为table类型通过:a = {}.a[1] = ‘hello’,a[2] = 30.
- length:’#b’代表b的长度。经过试验,可以获取string和table的长度,不能获取整数的长度。
for循环:
输出table:b中的每一项
for i=1,#b do print(b[i]) end
Tensors: 张量(矩阵都用张量来表示)
a = torch.Tensor(5,3) -- 创建5*3的随机矩阵矩阵,未初始化 b= torch.rand(3,3) --创建随机矩阵 a*b torch.mm(a,b) --跟a*b一样的效果 c = torch.Tensor(5,3) c:mm(a,b) --store the result of a*b in c 并输出c的值。乘法 --加法不需要维数相同,只需要个数相同,比如2\*2矩阵和1\*4矩阵也可以相加。 y = torch.add(a, b)-- returns a new Tensor. torch.add(y, a, b) --puts a + b in y. a:add(b) --accumulates all elements of b into a. y:add(a, b) --puts a + b in y. x:add(2, y) -- 两个y相加,相当于×2 [res] torch.mul([res,] tensor1, value) --跟加法原理一样,result的值是tensor1×value
注释: 两个短横线注释一行 - - dash
CUDA tensors: Tensors can be moved onto GPU using the :cuda function (cutorch)
require 'cutorch'; a = a:cuda() b = b:cuda() c = c:cuda() c:mm(a,b) --done on GPU
重点来了——网络篇 require ‘nn’ 利用nn package 构建 网络模型框架
LeNet
这是一个简单的网络结构,这个网络的容器是nn,序列能够通过几层layers反馈给输入。net = nn.Sequential() --指定网络net的容器类型 后面就是给net添加网络参数 net:add(nn.SpatialConvolution(1, 6, 5, 5)) -- 1 input image channel, 6 output channels, 5x5 convolution kernel net:add(nn.ReLU()) -- non-linearity net:add(nn.SpatialMaxPooling(2,2,2,2)) -- A max-pooling operation that looks at 2x2 windows and finds the max. net:add(nn.SpatialConvolution(6, 16, 5, 5)) net:add(nn.ReLU()) -- non-linearity net:add(nn.SpatialMaxPooling(2,2,2,2)) net:add(nn.View(16*5*5)) -- reshapes from a 3D tensor of 16x5x5 into 1D tensor of 16*5*5 net:add(nn.Linear(16*5*5, 120)) -- fully connected layer (matrix multiplication between input and weights) net:add(nn.ReLU()) -- non-linearity net:add(nn.Linear(120, 84)) net:add(nn.ReLU()) -- non-linearity net:add(nn.Linear(84, 10)) -- 10 is the number of outputs of the network (in this case, 10 digits) net:add(nn.LogSoftMax()) -- converts the output to a log-probability. Useful for classification problems print('Lenet5\n'