简体   繁体   English

如何将形状(3、1、2)的3D张量重塑为(1、2、3)

[英]How reshape 3D tensor of shape (3, 1, 2) to (1, 2, 3)

I intended 我打算

(Pdb) aa = torch.tensor([[[1,2]], [[3,4]], [[5,6]]])
(Pdb) aa.shape
torch.Size([3, 1, 2])
(Pdb) aa
tensor([[[ 1,  2]],

        [[ 3,  4]],

        [[ 5,  6]]])
(Pdb) aa.view(1, 2, 3)
tensor([[[ 1,  2,  3],
         [ 4,  5,  6]]])

But what I really want is 但是我真正想要的是

tensor([[[ 1,  3,  5],
         [ 2,  4,  6]]])

How? 怎么样?

In my application, I am trying to transform my input data of shape (L, N, C_in) to (N, C_in, L) in order to use Conv1d , where 在我的应用程序中,我试图将形状为(L,N,C_in)的输入数据转换为(N,C_in,L)以便使用Conv1d ,其中

  • L: sequence length L:序列长度
  • N: batch size N:批量
  • C_in: number of channels in the input, I also understand it as the dimensionality of the input at each position of a sequence. C_in:输入中通道的数量,我也将其理解为序列在每个位置上输入的维数。

I am also wondering the input of Conv1d doesn't have the same input shape as GRU ? 我也想知道Conv1d的输入与GRU的输入形状不一样吗?

You can permute the axes to the desired shape. 您可以将轴置换为所需的形状。 (This is in some sense similar to np.rollaxis operation). (这在某种意义上类似于np.rollaxis操作)。

In [90]: aa
Out[90]: 
tensor([[[ 1,  2]],

        [[ 3,  4]],

        [[ 5,  6]]])

In [91]: aa.shape
Out[91]: torch.Size([3, 1, 2])

# pass the desired ordering of the axes as argument
# assign the result back to some tensor since permute returns a "view"
In [97]: permuted = aa.permute(1, 2, 0)

In [98]: permuted.shape
Out[98]: torch.Size([1, 2, 3])

In [99]: permuted
Out[99]: 
tensor([[[ 1,  3,  5],
         [ 2,  4,  6]]])

This is one way to do it, still hope to see a solution with a single operation. 这是一种实现方法,仍然希望通过一次操作即可看到解决方案。

(Pdb) torch.transpose(aa, 0, 2).t()
tensor([[[ 1,  3,  5],
         [ 2,  4,  6]]])
(Pdb) torch.transpose(aa, 0, 2).t().shape
torch.Size([1, 2, 3])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM