简体   繁体   English

重塑 PyTorch 张量,使矩阵水平

[英]Reshape PyTorch tensor so that matrices are horizontal

I'm trying to combine n matrices in a 3-dimensional PyTorch tensor of shape (n, i, j) into a single 2-dimensional matrix of shape (i, j*n) .我正在尝试将形状为(n, i, j)的 3 维 PyTorch 张量中的n矩阵合并为形状为(i, j*n)的单个二维矩阵。 Here's a simple example where n=2, i=2, j=2 :这是一个简单的例子,其中n=2, i=2, j=2

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

I was hoping this would produce:我希望这会产生:

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

But instead it produced:但它产生了:

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

How do I do this?我该怎么做呢? I tried torch.cat and torch.stack , but they require tuples of tensors.我尝试torch.cattorch.stack ,但它们需要张量元组。 I could try and create tuples, but that seems inefficient.我可以尝试创建元组,但这似乎效率不高。 Is there a better way?有没有更好的办法?

To combine n + j with reshape you need them consequent in shape.要将n + jreshape结合起来,您需要它们的形状。 One can fix it with swapaxes :可以用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]])

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

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