Usage of view in pytorch (refactoring tensor)

View is used to change the shape of tensor in pytorch, which is simple and easy to use.

The usage of view in pytorch is usually to call .view directly after the tensor name, and then put the shape you want. Such as

tensor_name.view(shape)

Example:

1. Direct usage:

 >>> x = torch.randn(4, 4)
 >>> x.size()
 torch.Size([4, 4])
 >>> y = x.view(16)
 >>> y.size()
 torch.Size([16])

2. Emphasize the size of a certain dimension:

>>> z = x.view(-1, 8)  # the size -1 is inferred from other dimensions
>>> z.size()
torch.Size([2, 8])

3. Straighten the tensor: (directly fill in -1 means straighten, equivalent to tensor_name.flatten())

 >>> y = x.view(-1)
 >>> y.size()
 torch.Size([16])

4. Do not change the memory arrangement when doing dimension transformation            

>>> a = torch.randn(1, 2, 3, 4)
>>> a.size()
torch.Size([1, 2, 3, 4])
>>> b = a.transpose(1, 2)  # Swaps 2nd and 3rd dimension
>>> b.size()
torch.Size([1, 3, 2, 4])
>>> c = a.view(1, 3, 2, 4)  # Does not change tensor layout in memory
>>> c.size()
torch.Size([1, 3, 2, 4])
>>> torch.equal(b, c)

False

Note that the final False is not equivalent in the tensors b and c . From this we can see that the view function, as its name suggests, only changes the "look", but does not change the arrangement of tensors in memory .

Guess you like

Origin blog.csdn.net/leviopku/article/details/108470760