torch7学习(一)——Tensor

来源:互联网 发布:js 正则匹配 编辑:程序博客网 时间:2024/05/21 18:32

torch7学习(一)——Tensor
Torch7学习(二) —— Torch与Matlab的语法对比
Torch7学习(三)——学习神经网络包的用法(1)
Torch7学习(四)——学习神经网络包的用法(2)
Torch7学习(五)——学习神经网路包的用法(3)
Torch7学习(六)——学习神经网络包的用法(4)——利用optim进行训练
Torch7学习(七)——从neural-style代码中看自定义重载函数的训练方式

第一篇博客是从torch7提取出来最常用的知识。
主要讲Tensor的用法及其一些函数。
**先说一嘴:**torch中一般有这个东西,就是
y = torch.func(x,…)等价于y = x:func(…),就是说如果用”torch”,那么“src”是第一个参数。否则就”src:”

初始化

Tensor/rand/zeros/fill

z = torch.Tensor(3,4,2,3,5)  --可以创建多维数组。里面是随机的数。s = torch.Tensor(2,3):fill(1) --用1填充t = torch.rand(3,3)m = torch.zeros(3,3

其他的初始化方法

t = torch.rand(4,4):mul(3):floor():int()t = torch.Tensor(3,4):zero()  --注意这里Tensor的每个元素赋值为0的zero没有s

Tensor的内容以及信息

  1. Dimension/size/nElement
z = torch.Tensor(3,4)x = z:nDimension()  -- 2y = z:size()  -- y的值为size2的一维数组。3和4t = z:nElement() -- 12
  1. 用’[ ]’来取数。而不是像matlab的用’( )’。

Tensor的存储方式

数组的第一个数存储位置为storageOffset(), 从1开始。

x = torch.Tensor(7,7,7)x[3][4][5]等价于x:storage()[x:storageOffset()+(3-1)*x:stride(1)+(4-1)*x:stride(2)+(5-1)*x:stride(3)]-- stride(1),stride(2)和stride(3)分别是49,7,1

Tensor的复制

x = torch.Tensor(4):fill(1)y = torch.Tensor(2,2):copy(x) --也可以实现不同Tensor的复制。

Tensor的提取

select/narrow/sub

总说:select是直接提取某一维;narrow是取出某一维并进行裁剪; sub就是取出一块,是对取出的所有维进行裁剪。
语法: select(dim, index); narrow(dim, index, num); sub(dim1s, dim1e, dim2s, dim2e,…)

x = torch.Tensor(3,4)i = 0 x:apply(function()i = i+1 return i end)--[[x 为  1   2   3   4  5   6   7   8  9  10  11  12]]selected = x:select(1,2)  --第一维的第二个。就是第二行。相当于x[2]narrowed = x:narrow(2,1,2)--[[th> narrowed  1   2  5   6  9  10]]subbed = x:sub(1,3,2,3)--[[ 一维到3为止,二维也到3为止。th> subbed  2   3  6   7 10  11]]

用”{ }”来提取

上面的用函数的方式可能还是有点儿麻烦。matlab有类似(:, : ,1:2)的写法。那么lua呢?
语法:
1. [ {dim1 , dim2, …} ]来获取某些维度。类似select
2. [ { {dim1s, dim1e}, {dim2s, dim2e},… } ] 来进行类似narrow或是sub的裁剪。

x = torch.Tensor(5,6):zero()x[{1,3}] = 1 --等价于matlab的 x(1,3) = 1x[ {2, {2,4}} ] = 2 --等价于matlab的 x(2,2:4) = 2x[ { {}, 4}] = -1 --等价于matlab的 x(:,4) = -1

Expand/RepeatTensor/Squeeze

  1. expand
x = torch.rand(10,2,1)y = x:expand(10,2,3) --将三维的size变成了3-- expand即为“扩展”,扩展某个size为1的那一维度
  1. repeatTensor:将Tensor看成一个元素,按照特定方式进行排列。
x = torch.rand(5)y = x:repeatTensor(3,2) --size变成了3x10
  1. squeeze :将size为1的维度压缩掉。

View/transpose/permute

  1. view:将Tensor看成特定空间维数.

    x = torch.zeros(2,2,3)x:view(3,4) --等价于x:view(3, -1)--  -1 表示将剩余元素全部看成这一维度
  2. transpose:是permute的精简版本。transpose(dim1, dim2)只能将两个维度进行互换
x = torch.Tensor(3,4):zero()y1 = x:t() --如果是2D数据等价于transpose(1,2)y2 = x:transpose(1,2)

3.permute

x = torch.Tensor(3,4,2,5)y = x:permute(2,3,1,4) -- 按照2,3,1,4维进行重排列。
1 0