在PyTorch中没有N维转置

jhu*_*ang 10 torch pytorch

PyTorch的torch.transpose功能仅转换2D输入.文档在这里.

另一方面,Tensorflow的tf.transpose功能允许您转置N任意尺寸的张量.

有人可以解释为什么PyTorch没有/不能具有N维转置功能吗?这是否是由于PyTorch中的计算图构造与Tensorflow的Define-then-Run范式的动态特性?

eta*_*ion 13

它只是在pytorch中被称为不同.torch.Tensor.permute将允许您在TtororFlow中像tf.transpose那样交换pytorch中的维度.

作为如何将4D图像张量从NHWC转换为NCHW的示例(未经测试,因此可能包含错误):

>>> img_nhwc = torch.randn(10, 480, 640, 3)
>>> img_nhwc.size()
torch.Size([10, 480, 640, 3])
>>> img_nchw = img_nhwc.permute(0, 3, 1, 2)
>>> img_nchw.size()
torch.Size([10, 3, 480, 640])
Run Code Online (Sandbox Code Playgroud)

  • 现在是 2022 年,他们将其更改为 [`torch.permute`](https://pytorch.org/docs/master/ generated/torch.permute.html#torch.permute)。 (2认同)

All*_*leo 7

Einops支持任意数量维度的详细转置:

from einops import rearrange
x  = torch.zeros(10, 3, 100, 100)
y  = rearrange(x, 'b c h w -> b h w c')
x2 = rearrange(y, 'b h w c -> b c h w') # inverse to the first
Run Code Online (Sandbox Code Playgroud)

(同样的代码也适用于tensorfow)