如何展开 PyTorch 张量?

How can I unroll a PyTorch Tensor?

我有一个张量:

t1 = torch.randn(564, 400)

我想将其展开为 225600 长的一维张量。

我该怎么做?

Pytorch 很像 numpy,所以你可以简单地做,

t1 = t1.view(-1) or t1 = t1.reshape(-1)

请注意 Kris 所建议的 viewreshape 之间的区别 - 来自 reshape 的文档字符串:

When possible, the returned tensor will be a view of input. Otherwise, it will be a copy. Contiguous inputs and inputs with compatible strides can be reshaped without copying...

因此,如果您的张量不是连续的,调用 reshape 应该处理如果使用 view 而必须处理的内容;即调用t1.contiguous().view(...)来处理non-contiguous张量。

此外,可以使用 faltten: t1 = t1.flatten() 作为 view(-1) 的等价物,这样更具可读性。