版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/bla234/article/details/89322311
开始前
- 基于Lua并在Lua-JIT(just in time compiler,快)上进行运行
- Lua非常接近JavaScript,变量默认是全局的,除非使用local关键字
- 索引是从1开始的
- foo:bar()等价于foo.bar(foo)
- 只有一个内建数据结构,表:{},doubles作为一个哈希表和一个数组
正文
- strings,numbers,tables
- c=torch.Tensor(5,4)
c:mm(a,b) % c=a*b - require ‘cutorch’;
a=a:cuda()%张量移入GPU
b=b:cuda()
c=c:cuda()
c:mm(a,b) - b=torch.Tensor(2,5):fill(4)%赋值
- c=torch.Tensor(5,4)
- 定义网络
require ‘nn’;
net=nn.Sequential()
net:add(nn.SpatialConvolution(1,6,5,5)) %1-input,6-output,55
net:add(nn.view(1655)) %reshape 3D into 1D
net:add(nn.Linear(165*5,120)) %全连层
net:add(nn.LogSoftMax()) %softmax分类层
print(‘Lenet5\n’ … net:__tostring()); %打印网络
input = torch.rand(1,32,32)
output=net:forward(input)
print(output)
net:zeroGradParameters()
gradInput=net:backward(input,torch.rand(10))%input,gradient
print(#gradInput) - 定义损失函数
criterion=nn.ClassNLLCriterion()%多分类问题,负值的对数似然
criterion:forward(output,3)#GT label is 3
gradients=criterion:backward(output,3)
gradInput=net:backward(input,gradients)
%具有可学习参数的层,m.weights和m.bias,gradWeight和biasWeight - CIFAR分类问题
- 数据集,输入大小及GT,train和test的数量
- 训练的5个步骤:
(1)数据加载和预处理(归一化)
(2)定义神经网络
(3)定义损失函数
(4)训练网络
(5)测试网络
3.tensor indexing operator
redChannel = trainset.data[{ {3,5},{1},{},{} }]
#redChannel指的是数组的第一维值,即取出大小