簡體   English   中英

將行重塑為列組

[英]Reshape rows into groups of columns

我有許多行向量,我想將它們批處理為列向量並用作Conv1d的輸入。 作為一個例子,我想將張量x重塑為y ,即制作兩組兩個列向量。

# size = [4, 3]
x = torch.tensor([
    [0,  1,  2],
    [3,  4,  5],
    [6,  7,  8],
    [9, 10, 11]
])
# size = [2, 3, 2]
y = torch.tensor([
    [[0,  3],
     [1,  4],
     [2,  5]],
    [[6,  9],
     [7, 10],
     [8, 11]]
])

有沒有辦法只用reshape和類似的功能來做到這一點? 我能想到的唯一方法是使用循環並復制到一個新的張量中。

您需要使用permutereshape

x.reshape(2, 2, 3).permute(0, 2, 1)
Out[*]:
tensor([[[ 0,  3],
         [ 1,  4],
         [ 2,  5]],

        [[ 6,  9],
         [ 7, 10],
         [ 8, 11]]])

首先,將向量拆分為 2 x.reshape(2,2,3) ,將額外的維度放在中間。 然后使用permute將維度的順序更改為您所期望的。

您也可以使用torch.splittorch.stack類的

torch.stack(x.split(2), dim=2)      # or torch.stack(x.T.split(2, dim=1))
tensor([[[ 0,  3],
         [ 1,  4],
         [ 2,  5]],

        [[ 6,  9],
         [ 7, 10],
         [ 8, 11]]])

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM