定位矩阵中的不对称

Locate asymmetries in a matrix

我已经生成了列表项之间成对距离的矩阵,但是出了点问题,它不是对称的。

如果矩阵如下所示:

array = np.array([
    [0, 3, 4],
    [3, 0, 2],
    [1, 2, 0]
])

如何定位实际的不对称?在这种情况下,索引 4 和 1.

我已经通过 scipy 平方函数压缩矩阵,然后使用

来确认不对称性
def check_symmetric(a, rtol=1e-05, atol=1e-08):
    return np.allclose(a, a.T, rtol=rtol, atol=atol)

以下是快慢的,但如果对象是调试可能会。

a  #  nearly symmetric array.
Out:
array([[8, 1, 6, 5, 3],
       [1, 9, 4, 4, 4],
       [6, 4, 3, 7, 1],
       [5, 4, 7, 5, 2],
       [3, 4, 1, 3, 7]])

定义查找和打印差异的函数。

ERROR_LIMIT = 0.00001
def find_asymmetries( a ):
    """ Prints the row and column indices with the difference 
        where abs(a[r,c] - a[c,r]) > ERROR_LIMIT """
    res = a-a.T
    for r, row in enumerate(res):
        for c, cell in enumerate(row):
            if abs(cell) > ERROR_LIMIT : print( r, c, cell )

find_asymmetries( a )
3 4 -1
4 3 1

此版本将结果量减半。

def find_asymmetries( a ):
    res = a-a.T
    for r, row in enumerate(res):
        for c, cell in enumerate(row):
            if c == r: break #   Stop column search once c == r
            if abs(cell) > ERROR_LIMIT : print( r, c, cell )

find_asymmetries( a )
4 3 1   # Row number always greater than column number

很晚了,但这里有一个替代的 numpy 方式......

import numpy as np

m = np.array([[0, 3, 4 ],
             [ 3, 0, 2 ],
             [ 1, 2, 0 ]])

def check_symmetric(a):

    diff = a - a.T

    boolmatrix = np.isclose(a, a.T) # play around with your tolerances here...

    output = np.argwhere(boolmatrix == False)

    return output 

输出:

check_symmetric(m)

>>> array([[0, 2],
           [2, 0]])

你可以简单地使用np.isclose()的否定:

mask = ~np.isclose(array, array.T)
mask
# array([[False, False,  True],
#        [False, False, False],
#        [ True, False, False]])

使用该值作为索引来获取值:

array[mask]
# array([4, 1])

如果您需要索引,请使用 np.where()

np.where(mask)
# (array([0, 2]), array([2, 0]))