Numpy 将一个矩阵的每一行与另一个矩阵的每一行相乘

Numpy 将一个矩阵的每一行与另一个矩阵的每一行相乘,numpy,pytorch,numpy-ndarray,Numpy,Pytorch,Numpy Ndarray,在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 = n

在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
对矩阵进行转置,这在本例中是乘法所必需的(因为点积的方式)<代码>打印(产品)将输出:

[[ 3  6]
 [ 7 14]
 [11 22]]

使用
einsum

np.einsum('ij,kj->ik', X, Y)


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)
tensor([[ 3,  6],
        [ 7, 14],
        [11, 22]], dtype=torch.int32)