簡體   English   中英

從子陣列中的numpy 2D數組中提取交叉數組的索引

[英]Extract indices of intersecting array from numpy 2D array in subarray

我有兩個2D numpy方陣,A和B.B是從A中提取的數組,其中已經剝離了一定數量的列和行(具有相同的索引)。 它們都是對稱的。 例如,A和B可以是:

A = np.array([[1,2,3,4,5],
              [2,7,8,9,10],
              [3,8,13,14,15],
              [4,9,14,19,20],
              [5,10,15,20,25]])
B = np.array([[1,3,5],
              [3,13,15],
              [5,15,25]])

這樣缺失的指數是[1,3],交叉指數是[0,2,4]。

是否有一種“智能”方法來提取A中的索引,這些索引對應於B中存在的涉及高級索引的行/列等等? 我能想出的就是:

        import numpy as np
        index = np.array([],dtype=int)
        n,m = len(A),len(B)
        for j in range(n):
            k = 0
            while set(np.intersect1d(B[j],A[k])) != set(B[j]) and k<m:
                k+=1
            np.append(index,k)

我知道在處理大型數組時,它很慢且耗費資源。

謝謝!

編輯:我找到了一個更聰明的方法。 我從兩個數組中提取對角線,並通過簡單的相等檢查在其上執行上述循環:

        index = []
        a = np.diag(A)
        b = np.diag(B)
        for j in range(len(b)):
            k = 0
            while a[j+k] != b[j] and k<n:
                k+=1
            index.append(k+j)

雖然它仍然沒有使用高級索引並且仍在一個可能很長的列表中進行迭代,但這個部分解決方案看起來更清晰,我將暫時堅持使用它。

考慮所有值不同的簡單情況:

A = np.arange(25).reshape(5,5)
ans = [1,3,4]
B = A[np.ix_(ans, ans)]

In [287]: A
Out[287]: 
array([[ 0,  1,  2,  3,  4],
       [ 5,  6,  7,  8,  9],
       [10, 11, 12, 13, 14],
       [15, 16, 17, 18, 19],
       [20, 21, 22, 23, 24]])

In [288]: B
Out[288]: 
array([[ 6,  8,  9],
       [16, 18, 19],
       [21, 23, 24]])

如果我們用A的每一行測試B的第一行,我們最終將[6, 8, 9][5, 6, 7, 8, 9] 5,6,7,8,9 [5, 6, 7, 8, 9]進行比較,我們可以從中收集候選解決方案。指數[1, 3, 4] 1,3,4 [1, 3, 4]

我們可以通過將第一行 B與A的每一行配對來生成一組所有可能的候選解。

如果只有一個候選者,那么我們就完成了,因為我們得到的是B是A的子矩陣,因此總有一個解決方案。

如果有多個候選者,那么我們可以對B的第二行做同樣的事情, 並采用候選解決方案的交集 - 畢竟,解決方案必須是B的每一行的解決方案。

因此,一旦我們發現只有一個候選者,我們就可以遍歷B行和短路 同樣,我們假設B總是A的子矩陣。

下面的find_idx函數實現了上述思想:

import itertools as IT
import numpy as np

def find_idx_1d(rowA, rowB):
    result = []
    if np.in1d(rowB, rowA).all():
        result = [tuple(sorted(idx)) 
                  for idx in IT.product(*[np.where(rowA==b)[0] for b in rowB])]
    return result

def find_idx(A, B):
    candidates = set([idx for row in A for idx in find_idx_1d(row, B[0])])
    for Bi in B[1:]:
        if len(candidates) == 1:
            # stop when there is a unique candidate
            return candidates.pop()
        new = [idx for row in A for idx in find_idx_1d(row, Bi)]  
        candidates = candidates.intersection(new)
    if candidates:
        return candidates.pop()
    raise ValueError('no solution found')

正確性 :您提出的兩個解決方案可能並不總是返回正確的結果,尤其是在存在重復值時。 例如,

def is_solution(A, B, idx):
    return np.allclose(A[np.ix_(idx, idx)], B)

def find_idx_orig(A, B):
    index = []
    for j in range(len(B)):
        k = 0
        while k<len(A) and set(np.intersect1d(B[j],A[k])) != set(B[j]):
            k+=1
        index.append(k)
    return index

def find_idx_diag(A, B):
    index = []
    a = np.diag(A)
    b = np.diag(B)
    for j in range(len(b)):
        k = 0
        while a[j+k] != b[j] and k<len(A):
            k+=1
        index.append(k+j)
    return index

def counterexample():
    """
    Show find_idx_diag, find_idx_orig may not return the correct result
    """
    A = np.array([[1,2,0],
                  [2,1,0],
                  [0,0,1]])
    ans = [0,1]
    B = A[np.ix_(ans, ans)]
    assert not is_solution(A, B, find_idx_orig(A, B))
    assert is_solution(A, B, find_idx(A, B))

    A = np.array([[1,2,0],
                  [2,1,0],
                  [0,0,1]])
    ans = [1,2]
    B = A[np.ix_(ans, ans)]

    assert not is_solution(A, B, find_idx_diag(A, B))
    assert is_solution(A, B, find_idx(A, B))

counterexample()

基准 :忽視我們的危險正確性問題,出於好奇,讓我們在速度的基礎上比較這些功能。

def make_AB(n, m):
    A = symmetrize(np.random.random((n, n)))
    ans = np.sort(np.random.choice(n, m, replace=False))
    B = A[np.ix_(ans, ans)]
    return A, B

def symmetrize(a):
    "http://stackoverflow.com/a/2573982/190597 (EOL)"
    return a + a.T - np.diag(a.diagonal())

if __name__ == '__main__':
    counterexample()
    A, B = make_AB(500, 450)
    assert is_solution(A, B, find_idx(A, B))

In [283]: %timeit find_idx(A, B)
10 loops, best of 3: 74 ms per loop

In [284]: %timeit find_idx_orig(A, B)
1 loops, best of 3: 14.5 s per loop

In [285]: %timeit find_idx_diag(A, B)
100 loops, best of 3: 2.93 ms per loop

所以find_idx比快得多find_idx_orig ,但速度不及find_idx_diag

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM