将矩阵的每一行与另一个矩阵的每一行相乘
Multiply every row of a matrix with every row of another matrix
在 numpy / PyTorch 中,我有两个矩阵,例如X=[[1,2],[3,4],[5,6]]
、Y=[[1,1],[2,2]]
。我想将 X 的每一行与 Y 的每一行进行点积,并得到结果
[[3, 6],[7, 14], [11,22]]
我该如何实现?谢谢!
我想这就是您要找的:
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
转置矩阵,在这种情况下这是乘法所必需的(因为点积的方式是 defined)。 print(product)
将输出:
[[ 3 6]
[ 7 14]
[11 22]]
使用einsum
np.einsum('ij,kj->ik', X, Y)
array([[ 3, 6],
[ 7, 14],
[11, 22]])
在PyTorch
中,可以使用torch.mm(a, b)
或torch.matmul(a, b)
实现,如下图:
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)))
输出:
tensor([[ 3, 6],
[ 7, 14],
[11, 22]], dtype=torch.int32)
在 numpy / PyTorch 中,我有两个矩阵,例如X=[[1,2],[3,4],[5,6]]
、Y=[[1,1],[2,2]]
。我想将 X 的每一行与 Y 的每一行进行点积,并得到结果
[[3, 6],[7, 14], [11,22]]
我该如何实现?谢谢!
我想这就是您要找的:
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
转置矩阵,在这种情况下这是乘法所必需的(因为点积的方式是 defined)。 print(product)
将输出:
[[ 3 6]
[ 7 14]
[11 22]]
使用einsum
np.einsum('ij,kj->ik', X, Y)
array([[ 3, 6],
[ 7, 14],
[11, 22]])
在PyTorch
中,可以使用torch.mm(a, b)
或torch.matmul(a, b)
实现,如下图:
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)))
输出:
tensor([[ 3, 6],
[ 7, 14],
[11, 22]], dtype=torch.int32)