Tensor的组合与分块

>>> a = torch.Tensor([[1,2],[3,4]])
>>> a
tensor([[1., 2.],
[3., 4.]])

>>> b = torch.Tensor([[7,8],[9,10]])
>>> b
tensor([[ 7., 8.],
[ 9., 10.]])

>>> torch.cat([a,b]) #不输入0则默认按第一维拼接,变成4x2的矩阵
tensor([[ 1., 2.],
[ 3., 4.],
[ 7., 8.],
[ 9., 10.]])
>>> torch.cat([a,b],0)
tensor([[ 1., 2.],
[ 3., 4.],
[ 7., 8.],
[ 9., 10.]])
>>> torch.cat([a,b],1) #按第二维进行拼接,变成一个2x4的矩阵
tensor([[ 1., 2., 7., 8.],
[ 3., 4., 9., 10.]])

torch.stack()

>>> a
tensor([[1., 2.],
[3., 4.]])
>>> b
tensor([[ 7., 8.],
[ 9., 10.]])
>>> torch.stack([a,b],0)
tensor([[[ 1., 2.],
[ 3., 4.]],

[[ 7., 8.],
[ 9., 10.]]])
>>> torch.stack([a,b],2)
tensor([[[ 1., 7.],
[ 2., 8.]],

[[ 3., 9.],
[ 4., 10.]]])
>>> torch.stack([a,b],1)
tensor([[[ 1., 2.],
[ 7., 8.]],

[[ 3., 4.],
[ 9., 10.]]])

 

Tensor的分块

>>> a = torch.Tensor([[1,2,5],[3,4,6]])
>>> a
tensor([[1., 2., 5.],
[3., 4., 6.]])
>>> torch.chunk(a,2,0)一维分割
(tensor([[1., 2., 5.]]), tensor([[3., 4., 6.]]))
>>> torch.chunk(a,2,1)二维分割
(tensor([[1., 2.],
[3., 4.]]), tensor([[5.],
[6.]]))

>>> torch.split(a,2,0) 第一维
(tensor([[1., 2., 5.],
[3., 4., 6.]]),)
>>> torch.split(a,2,1) 第二维
(tensor([[1., 2.],
[3., 4.]]), tensor([[5.],
[6.]]))
>>> torch.split(a,[1,2],1)  已第二维按照列表中的数(列表中的数代表了分块的维数即第一块为一维 第二块为二维)
(tensor([[1.],
[3.]]), tensor([[2., 5.],
[4., 6.]]))

posted @ 2021-01-18 15:47  _八级大狂风  阅读(191)  评论(0编辑  收藏  举报