将2D NumPy数组乘以元素和和 [英] Multiply 2D NumPy arrays element-wise and sum

查看:177
本文介绍了将2D NumPy数组乘以元素和和的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道是否有更快的方法/专用NumPy函数来执行二维NumPy数组的元素乘法,然后求和所有元素。
我现在使用 np.sum(np.multiply(A,B))其中A,B是等维数的NumPy数组 mxn

解决方案

您可以使用 np.tensordot -

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

np.dot 将输入展平 -

<$ p $ > A.ravel()。dot(B.ravel())

另有 np.einsum

code> -

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

运行示例 -

  In [14]:m,n = 4,5 

在[15]中:A = np.random.rand(m,n)

在[16]中:B = np.random.rand(m,n)

在[17]中:np.sum(np.multiply(A,B))
Out [17]:5.1783176986341335

在[18]中:np.tensordot(A,B, =((0,1),(0,1)))
Out [18]:array(5.1783176986341335)

在[22]中:A.ravel()。dot(B .ravel())
Out [22]:5.1783176986341335

In [21]:np.einsum('ij,ij',A,B)
Out [21] :5.1783176986341326

运行时测试
$ b在[23]中:m,n = 5000,5000

在[24]中:A = np.random.rand(m,n )
...:B = np.random.rand(m,n)
...:

在[25]中:%timeit np.sum(np。 (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个循环,最好3个循环:每个循环52.2 ms
100个循环,最好3个:每个循环19.5 ms
100个循环,最好3个:每个循环19.5 ms
100个循环,bes每个循环3:19ms t


I am wondering if there is a quicker way/dedicated NumPy function to perform element-wise multiplication of 2D NumPy arrays and then sum all the elements. I currently use np.sum(np.multiply(A, B)) where A, B are NumPy arrays of equal dimension m x n.

解决方案

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,5

In [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.1783176986341335

In [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.1783176986341335

In [21]: np.einsum('ij,ij',A,B)
Out[21]: 5.1783176986341326

Runtime test

In [23]: m,n = 5000,5000

In [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 loop
100 loops, best of 3: 19.5 ms per loop
100 loops, best of 3: 19.5 ms per loop
100 loops, best of 3: 19 ms per loop

这篇关于将2D NumPy数组乘以元素和和的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆