numpy:按列的点积 [英] numpy: column-wise dot product
问题描述
给定2D numpy
数组,我需要计算每列与其自身的点积,并将结果存储在1D数组中.以下作品:
Given a 2D numpy
array, I need to compute the dot product of every column with itself, and store the result in a 1D array. The following works:
In [45]: A = np.array([[1,2,3,4],[5,6,7,8]])
In [46]: np.array([np.dot(A[:,i], A[:,i]) for i in xrange(A.shape[1])])
Out[46]: array([26, 40, 58, 80])
是否有避免Python循环的简单方法?上面的内容几乎不是世界末日,但是如果有一个numpy
原语,我想使用它.
Is there a simple way to avoid the Python loop? The above is hardly the end of the world, but if there's a numpy
primitive for this, I'd like to use it.
编辑实际上,矩阵有很多行,而列却相对较少.因此,我不太热衷于创建大于O(A.shape[1])
的临时数组.我也无法就地修改A
.
edit In practice the matrix has many rows and relatively few columns. I am therefore not overly keen on creating temporary arrays larger than O(A.shape[1])
. I also can't modify A
in place.
推荐答案
怎么样:
>>> A = np.array([[1,2,3,4],[5,6,7,8]])
>>> (A*A).sum(axis=0)
array([26, 40, 58, 80])
嗯,好的,您不需要中间的大对象.也许:
Hmm, okay, you don't want intermediate large objects. Maybe:
>>> from numpy.core.umath_tests import inner1d
>>> A = np.array([[1,2,3,4],[5,6,7,8]])
>>> inner1d(A.T, A.T)
array([26, 40, 58, 80])
反正似乎快一点.这应该在幕后做您想做的事情,因为A.T是一个视图(它不创建自己的副本IIUC),并且inner1d 似乎可以循环所需的方式.
which seems a little faster anyway. This should do what you want behind the scenes, as A.T is a view (which doesn't make its own copy, IIUC), and inner1d seems to loop the way it needs to.
非常迟的更新:另一种选择是使用np.einsum
:
VERY BELATED UPDATE: Another alternative would be to use np.einsum
:
>>> A = np.array([[1,2,3,4],[5,6,7,8]])
>>> np.einsum('ij,ij->j', A, A)
array([26, 40, 58, 80])
>>> timeit np.einsum('ij,ij->j', A, A)
100000 loops, best of 3: 3.65 us per loop
>>> timeit inner1d(A.T, A.T)
100000 loops, best of 3: 5.02 us per loop
>>> A = np.random.randint(0, 100, (2, 100000))
>>> timeit np.einsum('ij,ij->j', A, A)
1000 loops, best of 3: 363 us per loop
>>> timeit inner1d(A.T, A.T)
1000 loops, best of 3: 848 us per loop
>>> (np.einsum('ij,ij->j', A, A) == inner1d(A.T, A.T)).all()
True
这篇关于numpy:按列的点积的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!