np.dot of two 2D arrays

↘锁芯ラ 提交于 2020-12-12 05:43:55

问题


I am new to using numpy so sorry if this sounds obvious, I did try to search through stackoverflow before I post this though..

I have two "list of lists" numpy arrays of length n (n = 3 in the example below)

a = np.array([[1, 2], [3, 4], [5, 6]])
b = np.array([[2, 2], [3, 3], [4, 4]])

I want to get a 1d array with the dot product of the lists at each corresponding index, i.e.

[(1*2 + 2*2), (3*3 + 4*3), (5*4 + 6*4)]
[6, 21, 44]

how should I go about doing it? thanks in advance!


回答1:


You can do this

np.sum(a*b,axis=1)



回答2:


The sum method in the other answer is the most straight forward method:

In [19]: a = np.array([[1, 2], [3, 4], [5, 6]])
    ...: b = np.array([[2, 2], [3, 3], [4, 4]])
In [20]: a*b
Out[20]: 
array([[ 2,  4],
       [ 9, 12],
       [20, 24]])
In [21]: _.sum(1)
Out[21]: array([ 6, 21, 44])

With dot we have think a bit outside the box. einsum is easiest way of specifying a dot like action with less-than-obvious dimension combinations:

In [22]: np.einsum('ij,ij->i',a,b)
Out[22]: array([ 6, 21, 44])

Note that the i dimension is carried through. dot does ij,jk->ik, which would require extracting the diagonal (throwing away extra terms). In matmul/@ terms, the i dimension is a 'batch' one, that doesn't actually participate in the sum-of-products. To use that:

In [23]: a[:,None,:]@b[:,:,None]
Out[23]: 
array([[[ 6]],

       [[21]],

       [[44]]])

and then remove the extra size 1 dimensions:

In [24]: _.squeeze()
Out[24]: array([ 6, 21, 44])

In einsum terms this is i1j,ij1->i11



来源:https://stackoverflow.com/questions/65059860/np-dot-of-two-2d-arrays

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!