What does .view(-1) do?

I see this line of code

lab=lab.view(-1)

I am wondering what this code does? I put a breakpoint on it, and as far as I can see the contents of lab are the same both before and after I execute the code. So does this code make any difference?

The view(-1) operation flattens the tensor, if it wasn’t already flattened as seen here:

x = torch.randn(2, 3, 4)
print(x.shape)
> torch.Size([2, 3, 4])
x = x.view(-1)
print(x.shape)
> torch.Size([24])

It’ll modify the tensor metadata and will not create a copy of it.

1 Like