Search code examples
torchtensor

Pytorch. How I can expand dimension in tensor (from [[1, 2, 3]] to [[1, 2, 3, 4]])?


x = torch.tensor([1, 2, 3])
print(x)
# some operatons?
print(x)

Out:

tensor([[ 1,  2,  3]])
tensor([[ 1,  2,  3,  4]])

I tried tensor.expand() method, but nor success...


Solution

  • I find solution...

    >>> x = torch.tensor([[1, 2, 3]])
    >>> print(x)
    >>> print(x.size())
    
    tensor([[1, 2, 3]])
    torch.Size([1, 3])
    
    >>> x = x.repeat_interleave(torch.tensor([1, 1, 2]))
    >>> print(x)
    >>> print(x.size())
    
    tensor([1, 2, 3, 3])
    torch.Size([4])
    
    >>> x[3] = 4
    >>> x = x.unsqueeze(0)
    >>> print(x)
    >>> print(x.size())
    
    tensor([[1, 2, 3, 4]])
    torch.Size([1, 4])