重塑 PyTorch 张量,使矩阵水平

Reshape PyTorch tensor so that matrices are horizontal

我正在尝试将形状为 (n, i, j) 的 3 维 PyTorch 张量中的 n 矩阵组合为形状为 (i, j*n) 的单个二维矩阵。这是一个简单的例子,其中 n=2, i=2, j=2:

m = torch.tensor([[[2, 3],
                   [5, 7]],
                  [[11, 13],
                   [17, 19]]])
m.reshape(2, 4)

我希望这会产生:

tensor([[ 2,  3, 11, 13],
        [ 5,  7, 17, 19]])

但它却产生了:

tensor([[ 2,  3,  5,  7],
        [11, 13, 17, 19]])

我该怎么做?我尝试了 torch.cattorch.stack,但它们需要张量元组。我可以尝试创建元组,但这似乎效率不高。有没有更好的方法?

要将 n + jreshape 结合起来,您需要它们的形状。可以用 swapaxes:

修复它
m = torch.tensor([[[2, 3],
               [5, 7]],
              [[11, 13],
               [17, 19]]])
m=m.swapaxes( 0,1 ) 
m.reshape(2, 4)

tensor([[ 2,  3, 11, 13],
        [ 5,  7, 17, 19]])