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

时间:2016-04-13 13:20:02

标签: python numpy numpy-einsum

我正在使用numpy einsum来计算形状(3,N)的列向量pts数组的点积,其自身形成矩阵dotps,形状(N,N),所有点产品。这是我使用的代码:

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

这样可行,但我只需要主对角线以上的值。即。没有对角线的结果的上三角部分。是否可以使用einsum仅计算这些值?或以比使用einsum计算整个矩阵更快的任何其他方式?

我的pts数组可能非常大,所以如果我只计算我需要的值,那么我的计算速度就会翻倍。

1 个答案:

答案 0 :(得分:4)

您可以对相关列进行切片,然后使用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]))

它似乎创造了一个规则的模式,有点像移动的模式。这可以使用在35位置发生变化的累计和来编写。一般来说,我们最终会编写类似这样的代码 -

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's

计时
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's来说,基于triu_indices的自定义cumsum可能值得一看!