【问题标题】:numpy: cumulative multiplicity countnumpy:累积多重性计数
【发布时间】:2018-01-01 10:03:33
【问题描述】:

我有一个排序的整数数组,可能有重复。我想计算连续相等的值,当一个值与前一个不同时从零开始。这是用一个简单的 python 循环实现的预期结果:

import numpy as np

def count_multiplicities(a):
    r = np.zeros(a.shape, dtype=a.dtype)
    for i in range(1, len(a)):
        if a[i] == a[i-1]:
            r[i] = r[i-1]+1
        else:
            r[i] = 0
    return r

a = (np.random.rand(20)*5).astype(dtype=int)
a.sort()

print "given sorted array: ", a
print "multiplicity count: ", count_multiplicities(a)

输出:

given sorted array:  [0 0 0 0 0 1 1 1 2 2 2 2 3 3 3 3 4 4 4 4]
multiplicity count:  [0 1 2 3 4 0 1 2 0 1 2 3 0 1 2 3 0 1 2 3]

如何使用 numpy 以有效的方式获得相同的结果?数组很长,但重复次数很少(比如说不超过十次)。

在我的特殊情况下,我还知道值从零开始,并且连续值之间的差异是 0 或 1(值中没有间隙)。

【问题讨论】:

  • 进一步思考:也许一个可能的解决方案可以通过使用具有给定对角线和上对角线的精心选择的矩阵的乘法来实现。

标签: python performance numpy


【解决方案1】:

这是一种基于 cumsum 的矢量化方法 -

def count_multiplicities_cumsum_vectorized(a):      
    out = np.ones(a.size,dtype=int)
    idx = np.flatnonzero(a[1:] != a[:-1])+1
    out[idx[0]] = -idx[0] + 1
    out[0] = 0
    out[idx[1:]] = idx[:-1] - idx[1:] + 1
    np.cumsum(out, out=out)
    return out

示例运行 -

In [58]: a
Out[58]: array([0, 0, 0, 0, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 3, 3, 3, 4, 4, 4])

In [59]: count_multiplicities(a) # Original approach
Out[59]: array([0, 1, 2, 3, 0, 1, 2, 3, 4, 0, 1, 2, 3, 4, 0, 1, 2, 0, 1, 2])

In [60]: count_multiplicities_cumsum_vectorized(a)
Out[60]: array([0, 1, 2, 3, 0, 1, 2, 3, 4, 0, 1, 2, 3, 4, 0, 1, 2, 0, 1, 2])

运行时测试-

In [66]: a = (np.random.rand(200000)*1000).astype(dtype=int)
    ...: a.sort()
    ...: 

In [67]: a
Out[67]: array([  0,   0,   0, ..., 999, 999, 999])

In [68]: %timeit count_multiplicities(a)
10 loops, best of 3: 87.2 ms per loop

In [69]: %timeit count_multiplicities_cumsum_vectorized(a)
1000 loops, best of 3: 739 µs per loop

Related post.

【讨论】:

  • 谢谢!我缺少的是“flatnonzero”
【解决方案2】:

我会在此类问题上使用 numba

import numba
nb_count_multiplicities = numba.njit("int32[:](int32[:])")(count_multiplicities)
X=nb_count_multiplicities(a)

完全不重写代码,它比 Divakar 的矢量化解决方案快约 50%。

如果矢量化可以生成更短且更容易理解的代码,那么它会很多时候有用,但如果您必须强制对代码进行矢量化,这对于经验丰富的程序员来说也可能是个问题,那么就走这条路了。

【讨论】:

  • 很高兴了解 numba!
猜你喜欢
  • 2017-08-03
  • 2019-02-04
  • 2017-03-23
  • 1970-01-01
  • 2012-05-31
  • 1970-01-01
  • 2018-08-17
  • 1970-01-01
  • 2021-08-19
相关资源
最近更新 更多