简体   繁体   English

如何展开 PyTorch 张量?

[英]How can I unroll a PyTorch Tensor?

I have a tensor:我有一个张量:

t1 = torch.randn(564, 400)

I want to unroll it to a 1-d tensor that's 225600 long.我想把它展开成一个225600长的一维张量。

How can I do this?我怎样才能做到这一点?

Note the difference between view and reshape as suggested by Kris - From reshape 's docstring:请注意 Kris 建议的viewreshape之间的区别 - 来自reshape的文档字符串:

When possible, the returned tensor will be a view of input .如果可能,返回的张量将是input的视图。 Otherwise, it will be a copy.否则,它将是一个副本。 Contiguous inputs and inputs with compatible strides can be reshaped without copying...连续输入和具有兼容步幅的输入可以在不复制的情况下重塑...

So in case your tensor is not contiguous calling reshape should handle what one would have had to handle had one used view instead;因此,如果您的张量不是连续的,则调用reshape应该处理人们必须处理的内容,而不是使用一个view That is, call t1.contiguous().view(...) to handle non-contiguous tensors.也就是说,调用t1.contiguous().view(...)来处理不连续的张量。

Also, one could use faltten : t1 = t1.flatten() as an equivalent of view(-1) , which is more readable.此外,可以使用faltten : t1 = t1.flatten()作为view(-1)的等价物,它更具可读性。

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

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

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

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