首页 文章

Pytorch重塑张量维度

提问于
浏览
18

例如,我有1维向量的维度(5) . 我想将其重塑为2D矩阵(1,5) .

这是我如何用numpy做的

>>> import numpy as np
>>> a = np.array([1,2,3,4,5])
>>> a.shape
(5,)
>>> a = np.reshape(a, (1,5))
>>> a.shape
(1, 5)
>>> a
array([[1, 2, 3, 4, 5]])
>>>

但是我怎么能用Pytorch Tensor(和Variable)做到这一点 . 我不想切换回numpy并再次切换到Torch变量,因为它会丢失反向传播信息 .

这是我在Pytorch中所拥有的

>>> import torch
>>> from torch.autograd import Variable
>>> a = torch.Tensor([1,2,3,4,5])
>>> a

 1
 2
 3
 4
 5
[torch.FloatTensor of size 5]

>>> a.size()
(5L,)
>>> a_var = variable(a)
>>> a_var = Variable(a)
>>> a_var.size()
(5L,)
.....do some calculation in forward function
>>> a_var.size()
(5L,)

现在我希望它的大小为(1,5) . 如何在不丢失梯度信息的情况下调整变量张量的大小或重新整形 . (因为我会在向后进入另一个模型)

6 回答

  • 1

    使用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]
    
  • 4

    你可能会用

    a.view(1,5)
    Out: 
    
     1  2  3  4  5
    [torch.FloatTensor of size 1x5]
    
  • 12

    或者您可以使用它,' - 1表示您不必指定元素的数量 .

    In [3]: a.view(1,-1)
    Out[3]:
    
     1  2  3  4  5
    [torch.FloatTensor of size 1x5]
    
  • 13

    对于张量的就地修改,你一定要使用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])
    

    在PyTorch中,如果在操作结束时有一个下划线(如 tensor.resize_() ),那么该操作会对原始张量进行 in-place 修改 .


    此外,您只需在割炬张量中使用 np.newaxis 来增加尺寸 . 这是一个例子:

    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])
    
  • 2

    这个问题已经得到了彻底的解答,但是我想为经验较少的python开发人员添加一些,你可能会发现 * 运算符与 view() 一起使用是有帮助的 .

    例如,如果您有一个特定的张量大小,您希望不同的张量数据符合,您可以尝试:

    img = Variable(tensor.randn(20,30,3)) # tensor with goal shape
    flat_size = 20*30*3
    X = Variable(tensor.randn(50, flat_size)) # data tensor
    
    X = X.view(-1, *img.size()) # sweet maneuver
    print(X.size()) # size is (50, 20, 30, 3)
    

    这也适用于numpy shape

    img = np.random.randn(20,30,3)
    flat_size = 20*30*3
    X = Variable(tensor.randn(50, flat_size))
    X = X.view(-1, *img.shape)
    print(X.size()) # size is (50, 20, 30, 3)
    
  • 4
    import torch
    >>>a = torch.Tensor([1,2,3,4,5])
    >>>a.size()
    torch.Size([5])
    #use view to reshape
    
    >>>b = a.view(1,a.shape[0])
    >>>b
    tensor([[1., 2., 3., 4., 5.]])
    >>>b.size()
    torch.Size([1, 5])
    >>>b.type()
    'torch.FloatTensor'
    

相关问题