第一篇博客是從torch7提取出來最常用的知識。 初始化Tensor/rand/zeros/fillz = 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的內容以及信息
z = torch.Tensor(3,4)x = z:nDimension() -- 2y = z:size() -- y的值為size2的一維數組。3和4t = z:nElement() -- 12
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就是取出一塊,是對取出的所有維進行裁剪。 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呢? 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
x = torch.rand(10,2,1)y = x:expand(10,2,3) --將三維的size變成了3-- expand即為“擴展”,擴展某個size為1的那一維度
x = torch.rand(5)y = x:repeatTensor(3,2) --size變成了3x10
View/transpose/permute
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維進行重排列。
|
|