简体   繁体   中英

Add two torch tensor list

I want to add two PyTorch tensors together, for example, let

a = tensor([[1., 1., 2.],
            [1., 1., 2.],
            [1., 1., 2.],
            [1., 1., 2.],
            [1., 1., 2.],
            [1., 1., 2.]])

b = tensor([[4., 5., 6., 7., 8., 9.],
            [4., 5., 6., 7., 8., 9.],
            [4., 5., 6., 7., 8., 9.],
            [4., 5., 6., 7., 8., 9.],
            [4., 5., 6., 7., 8., 9.],
            [4., 5., 6., 7., 8., 9.]])

And I would like the resulting tensor c to be:

c = tensor([[5., 6., 8., 8., 9., 11.],
            [5., 6., 8., 8., 9., 11.],
            [5., 6., 8., 8., 9., 11.],
            [5., 6., 8., 8., 9., 11.],
            [5., 6., 8., 8., 9., 11.],
            [5., 6., 8., 8., 9., 11.]])

Note: b.shape[1] is always a multiple of a.shape[1] .

is there any better way than the solution below solution?

fin =  torch.Tensor()
for i in range(int(b.shape[1]/a.shape[1])):
    target = b[:,batch*i:batch*(i+1)]
    temp = torch.add(target, a)
    fin = torch.cat([fin, temp], dim =1)
c = fin

You can repeat the columns of a to match the shape of b with torch.Tensor.repeat , then add the resulting tensor to b :

>>> b + a.repeat(1, b.size(1)//a.size(1))
tensor([[ 5.,  6.,  8.,  8.,  9., 11.],
        [ 5.,  6.,  8.,  8.,  9., 11.],
        [ 5.,  6.,  8.,  8.,  9., 11.],
        [ 5.,  6.,  8.,  8.,  9., 11.],
        [ 5.,  6.,  8.,  8.,  9., 11.],
        [ 5.,  6.,  8.,  8.,  9., 11.]])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM