## The usage of view in python (reconstruction tensor)

Wooden calyx 2020-11-13 08:47:29
usage view python reconstruction tensor

view stay pytorch Chinese is used to Changing the tensor shape Of , Simple and easy to use .

pytorch in view It is usually used directly after the tensor name .view call , Then put in what you want shape. Such as

tensor_name.view(shape)

Example:

1. Direct use ：

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

2. Emphasize the size of a 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 It means straightening , Equivalent to tensor_name.flatten())

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

4. Do not change the memory arrangement when doing dimensional 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

Pay attention to the last False, In tensor b and c It's not equivalent . From here we can see that ,view Functions are as they are called , Only change “ look ” The appearance of , Does not change the permutation of tensors in memory .