将行重塑为列组

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 和类似的功能来做到这一点?我能想到的唯一方法是使用循环并复制到一个新的张量中。

您需要使用permute as well as reshape:

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.split and torch.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]]])