Pytorch reshape tensor dimension

前端 未结 10 529
忘掉有多难
忘掉有多难 2021-02-03 17:56

For example, I have 1D vector with dimension (5). I would like to reshape it into 2D matrix (1,5).

Here is how I do it with numpy

>>> import num         


        
10条回答
  •  北海茫月
    2021-02-03 18:23

    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.shape
    Out[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.shape
    Out[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.shape
    Out[36]: torch.Size([5])
    
    In [37]: new_a = a[np.newaxis, :]
    In [38]: new_a.shape
    Out[38]: torch.Size([1, 5])
    

提交回复
热议问题