Multiply 2D NumPy arrays element-wise and sum Multiply 2D NumPy arrays element-wise and sum numpy numpy

Multiply 2D NumPy arrays element-wise and sum


You can use np.tensordot -

np.tensordot(A,B, axes=((0,1),(0,1)))

Another way with np.dot after flattening the inputs -

A.ravel().dot(B.ravel())

Another with np.einsum -

np.einsum('ij,ij',A,B)

Sample run -

In [14]: m,n = 4,5In [15]: A = np.random.rand(m,n)In [16]: B = np.random.rand(m,n)In [17]: np.sum(np.multiply(A, B))Out[17]: 5.1783176986341335In [18]: np.tensordot(A,B, axes=((0,1),(0,1)))Out[18]: array(5.1783176986341335)In [22]: A.ravel().dot(B.ravel())Out[22]: 5.1783176986341335In [21]: np.einsum('ij,ij',A,B)Out[21]: 5.1783176986341326

Runtime test

In [23]: m,n = 5000,5000In [24]: A = np.random.rand(m,n)    ...: B = np.random.rand(m,n)    ...: In [25]: %timeit np.sum(np.multiply(A, B))    ...: %timeit np.tensordot(A,B, axes=((0,1),(0,1)))    ...: %timeit A.ravel().dot(B.ravel())    ...: %timeit np.einsum('ij,ij',A,B)    ...: 10 loops, best of 3: 52.2 ms per loop100 loops, best of 3: 19.5 ms per loop100 loops, best of 3: 19.5 ms per loop100 loops, best of 3: 19 ms per loop