使用Python numpy einsum获得2个矩阵之间的点积 [英] Using Python numpy einsum to obtain dot product between 2 Matrices
问题描述
只是碰到了这一点:
这个numpy.einsum确实很棒,但是使用起来有些混乱.假设我有:
This numpy.einsum is really awesome but its a little confusing to use. Suppose I have:
import numpy as np
a = np.array([[1,2,3], [3,4,5]])
b = np.array([[0,1,2], [1,1,7]])
我如何在einsum中使用"ij"来获得a和b之间的交叉点积"?
How would i use the "ij" in einsum to get a "cross dot product" between a and b?
基本上使用示例,我想计算的点积
Using the example basically I would like to compute dot product of
[1,2,3]和[0,1,2]
[1,2,3] and [0,1,2]
[1,2,3]和[1,2,7]
[1,2,3] and [1,2,7]
[3,4,5]和[0,1,2]
[3,4,5] and [0,1,2]
[3,4,5]和[1,1,7]
[3,4,5] and [1,1,7]
最后以[[8,26],[14,42]]
and end up with [[8,26],[14,42]]
我知道我是否使用
np.einsum("ij,ij->i",a,b)
我只会得到[8,42],这意味着我错过了十字"元素
I would just end up with [8, 42] which means I am missing the "cross" elements
推荐答案
您的结果仍然是二维的,因此您需要两个索引.您需要的是将第二个数组转置的矩阵乘法,因此,您可以用ij,kj->ik
代替第二个矩阵ij,jk->ik
:
Your result is still 2 dimensional, so you need two indices. What you need is a matrix multiplication with the second array transposed, so instead of normal ij,jk->ik
, you transpose the second matrix by ij,kj->ik
:
np.einsum('ij,kj->ik', a, b)
#array([[ 8, 24],
# [14, 42]])
等效于:
np.dot(a, b.T)
#array([[ 8, 24],
# [14, 42]])
import numpy as np
a = np.array([[1,2,3], [3,4,5]])
b = np.array([[0,1,2], [1,1,7]])
这篇关于使用Python numpy einsum获得2个矩阵之间的点积的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!