python-仅使用NumPy einsum处理上三角元素

我正在使用numpy einsum来计算形状为(3,N)的列向量pts数组的点积,并得出所有点积为形状(N,N)的矩阵点.这是我使用的代码:

dotps = np.einsum('ij,ik->jk', pts, pts)

这可行,但是我只需要主对角线上方的值.即.结果的上三角部分,不包括对角线.是否可以用einsum计算这些值?还是以比使用einsum来计算整个矩阵更快的任何其他方式?

我的pts数组可能很大,因此,如果我只能计算所需的值,那将使计算速度加倍.

最佳答案

您可以切片相关列,然后使用np.einsum

R,C = np.triu_indices(N,1)
out = np.einsum('ij,ij->j',pts[:,R],pts[:,C])

样品运行-

In [109]: N = 5
     ...: pts = np.random.rand(3,N)
     ...: dotps = np.einsum('ij,ik->jk', pts, pts)
     ...: 

In [110]: dotps
Out[110]: 
array([[ 0.26529103,  0.30626052,  0.18373867,  0.13602931,  0.51162729],
       [ 0.30626052,  0.56132272,  0.5938057 ,  0.28750708,  0.9876753 ],
       [ 0.18373867,  0.5938057 ,  0.84699103,  0.35788749,  1.04483158],
       [ 0.13602931,  0.28750708,  0.35788749,  0.18274288,  0.4612556 ],
       [ 0.51162729,  0.9876753 ,  1.04483158,  0.4612556 ,  1.82723949]])

In [111]: R,C = np.triu_indices(N,1)
     ...: out = np.einsum('ij,ij->j',pts[:,R],pts[:,C])
     ...: 

In [112]: out
Out[112]: 
array([ 0.30626052,  0.18373867,  0.13602931,  0.51162729,  0.5938057 ,
        0.28750708,  0.9876753 ,  0.35788749,  1.04483158,  0.4612556 ])

进一步优化-

让我们为我们的方法计时,看看是否有任何改进性能的余地.

In [126]: N = 5000

In [127]: pts = np.random.rand(3,N)

In [128]: %timeit np.triu_indices(N,1)
1 loops, best of 3: 413 ms per loop

In [129]: R,C = np.triu_indices(N,1)

In [130]: %timeit np.einsum('ij,ij->j',pts[:,R],pts[:,C])
1 loops, best of 3: 1.47 s per loop

处于内存限制之内,我们似乎无法在优化np.einsum上做很多事情.因此,让我们将焦点转移到np.triu_indices.

对于N = 4,我们有:

In [131]: N = 4

In [132]: np.triu_indices(N,1)
Out[132]: (array([0, 0, 0, 1, 1, 2]), array([1, 2, 3, 2, 3, 3]))

它似乎正在创建一个规则的模式,尽管有点像是不断变化的模式.可以用在这3个位置和5个位置偏移的累积总和来写.从一般的角度考虑,我们最终会像这样进行编码-

def triu_indices_cumsum(N):

    # Length of R and C index arrays
    L = (N*(N-1))/2

    # Positions along the R and C arrays that indicate 
    # shifting to the next row of the full array
    shifts_idx = np.arange(2,N)[::-1].cumsum()

    # Initialize "shift" arrays for finally leading to R and C
    shifts1_arr = np.zeros(L,dtype=int)
    shifts2_arr = np.ones(L,dtype=int)

    # At shift positions along the shifts array set appropriate values, 
    # such that when cumulative summed would lead to desired R and C arrays.
    shifts1_arr[shifts_idx] = 1
    shifts2_arr[shifts_idx] = -np.arange(N-2)[::-1]

    # Finall cumsum to give R, C
    R_arr = shifts1_arr.cumsum()
    C_arr = shifts2_arr.cumsum()
    return R_arr, C_arr

让我们为各种N计时吧!

In [133]: N = 100

In [134]: %timeit np.triu_indices(N,1)
10000 loops, best of 3: 122 µs per loop

In [135]: %timeit triu_indices_cumsum(N)
10000 loops, best of 3: 61.7 µs per loop

In [136]: N = 1000

In [137]: %timeit np.triu_indices(N,1)
100 loops, best of 3: 17 ms per loop

In [138]: %timeit triu_indices_cumsum(N)
100 loops, best of 3: 16.3 ms per loop

因此,对于体面的N来说,基于cumum定制的triu_indices可能值得一看!