Skip to content Skip to sidebar Skip to footer

Np.dot Of Two 2d Arrays

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 (

Solution 1:

You can do this

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

Solution 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

Post a Comment for "Np.dot Of Two 2d Arrays"