Reputation: 1404
In numpy / PyTorch, I have two matrices, e.g. X=[[1,2],[3,4],[5,6]]
, Y=[[1,1],[2,2]]
. I would like to dot product every row of X with every row of Y, and have the results
[[3, 6],[7, 14], [11,22]]
How do I achieve this?, Thanks!
Upvotes: 2
Views: 359
Reputation: 8719
In PyTorch
, you can achieve this using torch.mm(a, b)
or torch.matmul(a, b)
, as shown below:
x = np.array([[1,2],[3,4],[5,6]])
y = np.array([[1,1],[2,2]])
x = torch.from_numpy(x)
y = torch.from_numpy(y)
# print(torch.matmul(x, torch.t(y)))
print(torch.mm(x, torch.t(y)))
output:
tensor([[ 3, 6],
[ 7, 14],
[11, 22]], dtype=torch.int32)
Upvotes: 1
Reputation: 51185
Using einsum
np.einsum('ij,kj->ik', X, Y)
array([[ 3, 6],
[ 7, 14],
[11, 22]])
Upvotes: 1
Reputation: 170
I think this is what you are looking for:
import numpy as np
x= [[1,2],[3,4],[5,6]]
y= [[1,1],[2,2]]
x = np.asarray(x) #convert list to numpy array
y = np.asarray(y) #convert list to numpy array
product = np.dot(x, y.T)
.T
transposes the matrix, which is neccessary in this case for the multiplication (because of the way dot products are defined). print(product)
will output:
[[ 3 6]
[ 7 14]
[11 22]]
Upvotes: 4