Calculate vector of dot products

91 Views Asked by At

how do i do the following dot product preferably using pytorch tensordot()

Let say i have vector A and vector B :

[a1,a2] . [b1,b2,b3] =

I want to get as a result :

[
  a1 * b1 + a2 * b1,

  a1 * b2 + a2 * b2,

  a1 * b3 + a2 * b3
]

vector by vector = vector of dot products

2

There are 2 best solutions below

0
dx2-66 On BEST ANSWER

Einsum might be handy:

torch.einsum('i,j->j', torch.Tensor(a), torch.Tensor(b))
0
core_not_dumped On

The code below converts vector to matrix multiplication and sums all the values in one row.

import torch
tensor1 = torch.tensor([1,2]).unsqueeze(0)
tensor2 = torch.tensor([3,4,5]).unsqueeze(0)

result = torch.sum(tensor2.t() @ tensor1, dim=1)
print(result)

result:

tensor([ 9, 12, 15])