在pytorch中view函数的作用为重构张量的维度,相当于numpy中resize()的功能
>>> import torch
>>> t1 = torch.tensor([1,2,3,4,5,6])
>>> result = tt1.view(3,2)
>>> result
tensor([[1, 2],
[3, 4],
[5, 6]])
创建一个6维的向量,view(3,2)将其转化为3x2规模的矩阵
>>> t2 = torch.tensor([1,2,3],[4,5,6],[7,8,9])
>>> result = t2.view(-1)
tensor([1, 2, 3, 4, 5, 6, 7, 8, 9])
当view(-1)时,其作用是将一个矩阵展开为一个向量
>>> t3 = torch.tensor([1,2,3],[4,5,6],[7,8,9])
>>> result = t2.view(3,-1)
>>> result
tensor([[1, 2, 3],
[4, 5, 6],
[7, 8, 9]])
>>> result.size()
torch.Size([3, 3])
>>> t4 = torch.tensor([[1,2,3],[4,5,6]])
>>> t4.size()
torch.Size([2,3])
>>> result = t4.view(3,-1)
>>> result
tensor([[1, 2],
[3, 4],
[5, 6]])
>>> result.size()
torch.Size([3, 2])
当view()参数不止一个,且其中一个为-1时,则-1的作用相当于占位符,其大小由torch根据矩阵元素个数和其他维大小来自动计算
注意:torch中的矩阵顺序为[batch_size, channels, x, y]