Pytorch reshape tensor dimension
Use torch.unsqueeze(input, dim, out=None)
>>> import torch>>> a = torch.Tensor([1,2,3,4,5])>>> a 1 2 3 4 5[torch.FloatTensor of size 5]>>> a = a.unsqueeze(0)>>> a 1 2 3 4 5[torch.FloatTensor of size 1x5]
you might use
a.view(1,5)Out: 1 2 3 4 5[torch.FloatTensor of size 1x5]
For in-place modification of the shape of the tensor, you should use tensor.resize_()
:
In [23]: a = torch.Tensor([1, 2, 3, 4, 5])In [24]: a.shapeOut[24]: torch.Size([5])# tensor.resize_((`new_shape`)) In [25]: a.resize_((1,5))Out[25]: 1 2 3 4 5[torch.FloatTensor of size 1x5]In [26]: a.shapeOut[26]: torch.Size([1, 5])
In PyTorch, if there's an underscore at the end of an operation (like tensor.resize_()
) then that operation does in-place
modification to the original tensor.
Also, you can simply use np.newaxis
in a torch Tensor to increase the dimension. Here is an example:
In [34]: list_ = range(5)In [35]: a = torch.Tensor(list_)In [36]: a.shapeOut[36]: torch.Size([5])In [37]: new_a = a[np.newaxis, :]In [38]: new_a.shapeOut[38]: torch.Size([1, 5])