pytorch中view的用法(重构张量)

view在pytorch中是用来改变张量的shape的,简单又好用。

pytorch中view的用法通常是直接在张量名后用.view调用,然后放入自己想要的shape。如

tensor_name.view(shape)

Example:

1. 直接用法:

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

2. 强调某一维度的尺寸:

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

3. 拉直张量:(直接填-1表示拉直, 等价于tensor_name.flatten())

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

4. 做维度变换时不改变内存排列            

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

注意最后的False,在张量b和c是不等价的。从这里我们可以看得出来,view函数如其名,只改变“看起来”的样子,不会改变张量在内存中的排列

猜你喜欢

转载自blog.csdn.net/leviopku/article/details/108470760