高效使用 numpy_indexed 输出

Efficient use of numpy_indexed output

>>> import numpy_indexed as npi
>>> import numpy as np
>>> a = np.array([[0,0,1,1,2,2], [4,4,8,8,10,10]]).T
>>> a
array([[ 0,  4],
       [ 0,  4],
       [ 1,  8],
       [ 1,  8],
       [ 2, 10],
       [ 2, 10]])
>>> npi.group_by(a[:, 0]).sum(a[:,1])

(array([0, 1, 2]), array([ 8, 16, 20], dtype=int32))

我想在大型集合(~1m 行)上对由第一列聚集的第二列的子集执行计算。是否有一种有效的(and/or 向量化)方法来使用 numpy_indexedgroup_by 的输出,以便添加一个包含这些计算输出的新列?在上面 sum 的示例中,我想生成以下输出。

如果有一种无需首先使用 numpy_indexed 即可执行此操作的有效方法,那也会非常有帮助。

array([[ 0,  4,  8],
       [ 0,  4,  8],
       [ 1,  8, 16],
       [ 1,  8, 16],
       [ 2, 10, 20],
       [ 2, 10, 20]])

np.unique to generate those unique tags and the interval shifting indices and then np.add.reduceat 的一种方法 intervaled-summing -

_,idx,tags = np.unique(a[:,0], return_index=1, return_inverse=1)
out = np.c_[a, np.add.reduceat(a[:,1],idx)[tags]]

另一种避免使用 np.unique 并可能对性能有益的方法是这样的 -

idx = np.r_[0,np.flatnonzero(a[1:,0] > a[:-1,0])+1]
tag_arr = np.zeros(a.shape[0], dtype=int)
tag_arr[idx[1:]] = 1
tags = tag_arr.cumsum()
out = np.c_[a, np.add.reduceat(a[:,1],idx)[tags]]

为了进一步提升性能,我们应该使用 np.bincount。因此,np.add.reduceat(a[:,1],idx) 可以替换为 np.bincount(tags, a[:,1])

示例 运行 -

In [271]: a    # Using a more generic sample
Out[271]: 
array([[11,  4],
       [11,  4],
       [14,  8],
       [14,  8],
       [16, 10],
       [16, 10]])

In [272]: _,idx,tags = np.unique(a[:,0], return_index=1, return_inverse=1)

In [273]: np.c_[a, np.add.reduceat(a[:,1],idx)[tags]]
Out[273]: 
array([[11,  4,  8],
       [11,  4,  8],
       [14,  8, 16],
       [14,  8, 16],
       [16, 10, 20],
       [16, 10, 20]])]

现在,列出的方法假设第一列已经排序。如果不是这种情况,我们需要按第一列 argsort 对数组进行排序,然后使用建议的方法。因此,对于未排序的情况,我们需要以下内容作为预处理 -

a = a[a[:,0].argsort()]

对抗np.unique

让我们将基于自定义 flatnonzero + cumsum 的方法与内置 np.unique 进行计时,以创建移动索引:idx 和基于唯一性的 IDs/tags:tags。对于这种情况,我们事先知道标签列已经排序,我们避免任何排序,就像 np.unique 所做的那样。这使我们在性能上具有优势。那么,让我们来验证一下吧。

接近 -

def nonzero_cumsum_based(A):
    idx = np.concatenate(( [0] ,np.flatnonzero(A[1:] > A[:-1])+1 ))
    tags = np.zeros(len(A), dtype=int)
    tags[idx[1:]] = 1
    np.cumsum(tags, out = tags)
    return idx, tags

def unique_based(A):
    _,idx,tags = np.unique(A, return_index=1, return_inverse=1)
    return idx, tags

示例 运行 使用自定义函数 -

In [438]: a
Out[438]: 
array([[11,  4],
       [11,  4],
       [14,  8],
       [14,  8],
       [16, 10],
       [16, 10]])

In [439]: idx, tags = nonzero_cumsum_based(a[:,0])

In [440]: idx
Out[440]: array([0, 2, 4])

In [441]: tags
Out[441]: array([0, 0, 1, 1, 2, 2])

计时 -

In [444]: a = np.c_[np.sort(randi(10,10000,(100000))), randi(0,10000,(100000))]

In [445]: %timeit unique_based(a[:,0])
100 loops, best of 3: 4.3 ms per loop

In [446]: %timeit nonzero_cumsum_based(a[:,0])
1000 loops, best of 3: 486 µs per loop

In [447]: a = np.c_[np.sort(randi(10,10000,(1000000))), randi(0,10000,(1000000))]

In [448]: %timeit unique_based(a[:,0])
10 loops, best of 3: 50.2 ms per loop

In [449]: %timeit nonzero_cumsum_based(a[:,0])
100 loops, best of 3: 3.98 ms per loop

每个索引对象都有一个逆属性,它将减少的值映射回它们的原始范围;为了说明,我们可以写:

index = npi.as_index(keys)
unique_keys = index.unique
unique_keys[index.inverse] == keys  # <- should be all true

并且这个 属性 也暴露在 GroupBy 对象上;因为确实将分组值映射回其输入范围是一种常用的操作:

groups = npi.group_by(a[:, 0])
unique, sums = groups.sum(a[:, 1])
new_column = sums[groups.inverse]

总的来说,numpy_indexed 的来源可以为如何执行此类常见操作提供灵感; group_by.var 面临着同样的问题,例如,将每组的均值广播回组成它的组的每个元素,以计算每个组中的错误。但更好的教程当然也不会有害。

您能否对您要解决的问题给出更高层次的描述?当您对 npi 提供的方便的设计模式进行更舒适的思考时,您可能会从更高的层次进一步简化您的代码。