torch:)——PyTorch: view( )用法详解
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]])
2. view(-1)
```python
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])
i.e.view(-1)将张量重构成了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])
i.e.torch.view(-1, 参数b),则表示在参数a未知,参数b已知的情况下自动补齐行向量长度,在这个例子中b=3,re总共含有6个元素,则a=6/2=3。
注意:torch中的矩阵顺序为[batch_size, channels, x, y]