torch.tensor.view()

torch.tensor.view()

形式:Tensor.view(*shape) → Tensor

作用:返回一个新的张量,其数据与自张量相同,但形状不同。

说明:返回的张量共享相同的数据,并且必须具有相同数量的元素,但可能具有不同的大小。

当不清楚是否可以执行 view() 时,建议使用 reshape(),如果形状兼容则返回视图,否则复制(相当于调用 contiguous())。

参数:
shape (torch.Size or int…) – the desired size

使用案例:

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

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

 

posted @ 2022-12-31 22:37  Yuxi001  阅读(112)  评论(0编辑  收藏  举报