检查高维数组在 Python 中的两个 ndarray 中是否重叠的有效方法



例如,我有两个ndarray,train_dataset的形状是(10000, 28, 28)的,val_dateset的形状是(2000, 28, 28)

除了使用迭代之外,是否有任何有效的方法可以使用 numpy 数组函数来查找两个 ndarray 之间的重叠?

我从 Jaime 的出色答案中学到的一个技巧是使用 np.void dtype 将输入数组中的每一行视为单个元素。这允许您将它们视为 1D 数组,然后可以将其传递给 np.in1d 或其他设置例程之一。

import numpy as np
def find_overlap(A, B):
    if not A.dtype == B.dtype:
        raise TypeError("A and B must have the same dtype")
    if not A.shape[1:] == B.shape[1:]:
        raise ValueError("the shapes of A and B must be identical apart from "
                         "the row dimension")
    # reshape A and B to 2D arrays. force a copy if neccessary in order to
    # ensure that they are C-contiguous.
    A = np.ascontiguousarray(A.reshape(A.shape[0], -1))
    B = np.ascontiguousarray(B.reshape(B.shape[0], -1))
    # void type that views each row in A and B as a single item
    t = np.dtype((np.void, A.dtype.itemsize * A.shape[1]))
    # use in1d to find rows in A that are also in B
    return np.in1d(A.view(t), B.view(t))

例如:

gen = np.random.RandomState(0)
A = gen.randn(1000, 28, 28)
dupe_idx = gen.choice(A.shape[0], size=200, replace=False)
B = A[dupe_idx]
A_in_B = find_overlap(A, B)
print(np.all(np.where(A_in_B)[0] == np.sort(dupe_idx)))
# True

这种方法比Divakar的方法内存效率高得多,因为它不需要广播到(m, n, ...)布尔数组。事实上,如果 AB 是行主的,则根本不需要复制。


为了进行比较,我稍微调整了Divakar和B.M.的解决方案。

def divakar(A, B):
    A.shape = A.shape[0], -1
    B.shape = B.shape[0], -1
    return (B[:,None] == A).all(axis=(2)).any(0)
def bm(A, B):
    t = 'S' + str(A.size // A.shape[0] * A.dtype.itemsize)
    ma = np.frombuffer(np.ascontiguousarray(A), t)
    mb = np.frombuffer(np.ascontiguousarray(B), t)
    return (mb[:, None] == ma).any(0)

基准:

In [1]: na = 1000; nb = 200; rowshape = 28, 28
In [2]: %%timeit A = gen.randn(na, *rowshape); idx = gen.choice(na, size=nb, replace=False); B = A[idx]
divakar(A, B)
   ....: 
1 loops, best of 3: 244 ms per loop
In [3]: %%timeit A = gen.randn(na, *rowshape); idx = gen.choice(na, size=nb, replace=False); B = A[idx]
bm(A, B)
   ....: 
100 loops, best of 3: 2.81 ms per loop
In [4]: %%timeit A = gen.randn(na, *rowshape); idx = gen.choice(na, size=nb, replace=False); B = A[idx]
find_overlap(A, B)
   ....: 
100 loops, best of 3: 15 ms per loop

如您所见,对于小n,B.M.的解决方案比我的略快,但np.in1d扩展性比测试所有元素的相等性(O(n log n)而不是O(n²)复杂度)更好。

In [5]: na = 10000; nb = 2000; rowshape = 28, 28
In [6]: %%timeit A = gen.randn(na, *rowshape); idx = gen.choice(na, size=nb, replace=False); B = A[idx]
bm(A, B)
   ....: 
1 loops, best of 3: 271 ms per loop
In [7]: %%timeit A = gen.randn(na, *rowshape); idx = gen.choice(na, size=nb, replace=False); B = A[idx]
find_overlap(A, B)
   ....: 
10 loops, best of 3: 123 ms per loop

Divakar的解决方案在我的笔记本电脑上对于这种大小的阵列来说很棘手,因为它需要生成一个15GB的中间阵列,而我只有8GB RAM。

内存允许你可以使用broadcasting,就像这样 -

val_dateset[(train_dataset[:,None] == val_dateset).all(axis=(2,3)).any(0)]

示例运行 -

In [55]: train_dataset
Out[55]: 
array([[[1, 1],
        [1, 1]],
       [[1, 0],
        [0, 0]],
       [[0, 0],
        [0, 1]],
       [[0, 1],
        [0, 0]],
       [[1, 1],
        [1, 0]]])
In [56]: val_dateset
Out[56]: 
array([[[0, 1],
        [1, 0]],
       [[1, 1],
        [1, 1]],
       [[0, 0],
        [0, 1]]])
In [57]: val_dateset[(train_dataset[:,None] == val_dateset).all(axis=(2,3)).any(0)]
Out[57]: 
array([[[1, 1],
        [1, 1]],
       [[0, 0],
        [0, 1]]])

如果元素是整数,则可以将输入数组中的每个axis=(1,2)块折叠为标量,假设它们是线性可索引的数字,然后有效地使用np.in1dnp.intersect1d来查找匹配项。

完全广播在这里生成一个 10000*2000*28*28 =150 Mo 布尔数组。

为了提高效率,您可以:

  • 打包数据,对于 200 Ko 数组:

    from pylab import *
    N=10000
    a=rand(N,28,28)
    b=a[[randint(0,N,N//5)]]
    packedtype='S'+ str(a.size//a.shape[0]*a.dtype.itemsize) # 'S6272' 
    ma=frombuffer(a,packedtype)  # ma.shape=10000
    mb=frombuffer(b,packedtype)  # mb.shape=2000
    %timeit a[:,None]==b   : 102 s
    %timeit ma[:,None]==mb   : 800 ms
    allclose((a[:,None]==b).all((2,3)),(ma[:,None]==mb)) : True
    

    延迟字符串比较在这里帮助减少了内存,在第一次差异时打破

    In [31]: %timeit a[:100]==b[:100]
    10000 loops, best of 3: 175 µs per loop
    In [32]: %timeit a[:100]==a[:100]
    10000 loops, best of 3: 133 µs per loop
    In [34]: %timeit ma[:100]==mb[:100]
    100000 loops, best of 3: 7.55 µs per loop
    In [35]: %timeit ma[:100]==ma[:100]
    10000 loops, best of 3: 156 µs per loop
    

这里给出了解决方案,(ma[:,None]==mb).nonzero().

  • 使用 in1d ,以获得(Na+Nb) ln(Na+Nb)复杂性,反对 Na*Nb完整比较:

    %timeit in1d(ma,mb).nonzero()  : 590ms 
    

这里没有很大的收获,但渐近更好。

解决方案

def overlap(a,b):
    """
    returns a boolean index array for input array b representing
    elements in b that are also found in a
    """
    a.repeat(b.shape[0],axis=0)
    b.repeat(a.shape[0],axis=0)
    c = aa == bb
    c = c[::a.shape[0]]
    return c.all(axis=1)[:,0]

您可以使用返回的索引数组来索引b以提取在 a 中找到的元素

b[overlap(a,b)]

解释

为了简单起见,我假设您已经从numpy导入了此示例中的所有内容:

from numpy import *

因此,例如,给定两个 ndarray

a = arange(4*2*2).reshape(4,2,2)
b = arange(3*2*2).reshape(3,2,2)

我们重复ab,使它们具有相同的形状

aa = a.repeat(b.shape[0],axis=0)
bb = b.repeat(a.shape[0],axis=0)

然后,我们可以简单地比较aabb的元素

c = aa == bb

最后,通过查看每 4 个或实际上每 shape(a)[0] 个元素来获取b元素的索引,这些索引也存在于a c

cc == c[::a.shape[0]]

最后,我们提取一个索引数组,其中只有子数组中所有元素都True

c.all(axis=1)[:,0]

在我们的示例中,我们得到

array([True,  True,  True], dtype=bool)

要进行检查,请更改b的第一个元素

b[0] = array([[50,60],[70,80]])

我们得到

array([False,  True,  True], dtype=bool)

这个问题来自谷歌的在线深度学习课程?以下是我的解决方案:

sum = 0 # number of overlapping rows
for i in range(val_dataset.shape[0]): # iterate over all rows of val_dataset
    overlap = (train_dataset == val_dataset[i,:,:]).all(axis=1).all(axis=1).sum()
    if overlap:
        sum += 1
print(sum)

使用自动广播而不是迭代。您可以测试性能差异。

最新更新