Home > front end >  How to extend one tensor with another. So the result contains all the elements from the 2 tensors, s
How to extend one tensor with another. So the result contains all the elements from the 2 tensors, s

Time:01-13

a =  tensor([   [101,  103],
            [101,  1045]
        ])


b =  tensor([   [101,  777],
            [101,  888]
        ])

How to I get this tensor c from a and b:

c = a   b =  tensor([   [101,  103],
            [101,  1045],
            [101,  777],
            [101,  888]
            
        ])

With python lists this would be simply c = a b, but with pytorch it just simply adds the elements and does not extends the list.

CodePudding user response:

You can use the torch.cat function:

c = torch.cat((a, b), dim=0)

Such as in the following example:

from torch import tensor
import torch
a =  tensor([   [101,  103],
            [101,  1045]
        ])


b =  tensor([   [101,  777],
            [101,  888]
        ])
c = torch.cat((a, b), dim=0)
print(c)

with output:

tensor([[ 101,  103],
        [ 101, 1045],
        [ 101,  777],
        [ 101,  888]])
  • Related