簡體   English   中英

如何將形狀(3、1、2)的3D張量重塑為(1、2、3)

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

我打算

(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]]])

但是我真正想要的是

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

怎么樣?

在我的應用程序中,我試圖將形狀為(L,N,C_in)的輸入數據轉換為(N,C_in,L)以便使用Conv1d ,其中

  • L:序列長度
  • N:批量
  • C_in:輸入中通道的數量,我也將其理解為序列在每個位置上輸入的維數。

我也想知道Conv1d的輸入與GRU的輸入形狀不一樣嗎?

您可以將軸置換為所需的形狀。 (這在某種意義上類似於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]]])

這是一種實現方法,仍然希望通過一次操作即可看到解決方案。

(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