定位矩阵中的不对称性

2024-10-06 12:14:09 发布

您现在位置:Python中文网/ 问答频道 /正文

我已经生成了列表项之间成对距离的矩阵,但出现了一些问题,它是不对称的。你知道吗

如果矩阵如下所示:

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)

Tags: 函数距离列表returndefchecknp矩阵
3条回答

以下是快速和缓慢,但如果对象是调试可能会做。你知道吗

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

您可以简单地使用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]))

很晚了,但这里会有一个替代的方式。。。你知道吗

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]])

相关问题 更多 >