Search code examples
pythonpytorchtensor

How to operate torch.dot() in matrix consist of vectors in pytorch?


I have tensor like this:

arr1 = np.array([[ 1.6194, -0.6058, -0.8012], [ 1.1483,  1.6538, -0.8062]])
arr2 = np.array([[-0.3180, -1.8249,  0.0499], [-0.4184,  0.6495, -0.4911]])
X = torch.Tensor(arr1)
Y = torch.Tensor(arr2)

I want to do torch.dot on every tensor 1D (2 vectors) inside my 2D tensor

torch.dot(X, Y)   

I want to get the result like this tensor([dotResult1, dotResult2]). But I got the error like this:

RuntimeError: 1D tensors expected, but got 2D and 2D tensors

My main purpose is to do "something" operation on every vector inside my matrix but I don't want to use looping here, does anyone know how to do that?


Solution

  • Assuming what you are looking for is the tensor : [torch.dot(X[0], Y[0]), torch.dot(X[1], Y[1])]

    Then you can do:

    (X*Y).sum(axis = 1)
    

    Test:

    (X*Y).sum(axis = 1) == torch.tensor([torch.dot(X[0], Y[0]),torch.dot(X[1], Y[1])])
    

    outputs:

    tensor([True, True])