1

I have a tensor:

t1 = torch.randn(564, 400)

I want to unroll it to a 1-d tensor that's 225600 long.

How can I do this?

Shamoon
  • 41,293
  • 91
  • 306
  • 570
  • Does this answer your question? [How do I flatten a tensor in pytorch?](https://stackoverflow.com/questions/55546873/how-do-i-flatten-a-tensor-in-pytorch) – jodag Oct 18 '20 at 18:05

2 Answers2

2

Note the difference between view and reshape as suggested by Kris - From reshape's docstring:

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...

So in case your tensor is not contiguous calling reshape should handle what one would have had to handle had one used view instead; That is, call t1.contiguous().view(...) to handle non-contiguous tensors.

Also, one could use faltten: t1 = t1.flatten() as an equivalent of view(-1), which is more readable.

Gil Pinsky
  • 2,388
  • 1
  • 12
  • 17
1

Pytorch is much like numpy so you can simply do,

t1 = t1.view(-1) or t1 = t1.reshape(-1)
Kris
  • 518
  • 3
  • 13