numpy的“智能”对称矩阵

numpy的“智能”对称矩阵,第1张

numpy的“智能”对称矩阵

如果您有能力在进行计算之前就对称矩阵,则以下 *** 作应相当快:

def symmetrize(a):    """    Return a symmetrized version of NumPy array a.    Values 0 are replaced by the array value at the symmetric    position (with respect to the diagonal), i.e. if a_ij = 0,    then the returned array a' is such that a'_ij = a_ji.    Diagonal values are left untouched.    a -- square NumPy array, such that a_ij = 0 or a_ji = 0,     for i != j.    """    return a + a.T - numpy.diag(a.diagonal())

这在合理的假设下有效(例如,在运行之前不做任何事情

a[0, 1] = 42
并且矛盾)。
a[1, 0] = 123``symmetrize

如果您确实需要透明的对称化,则可以考虑子类化numpy.ndarray并简单地重新定义

__setitem__

class SymNDArray(numpy.ndarray):    """    NumPy array subclass for symmetric matrices.    A SymNDArray arr is such that doing arr[i,j] = value    automatically does arr[j,i] = value, so that array    updates remain symmetrical.    """    def __setitem__(self, (i, j), value):        super(SymNDArray, self).__setitem__((i, j), value)      super(SymNDArray, self).__setitem__((j, i), value)def symarray(input_array):    """    Return a symmetrized version of the array-like input_array.    The returned array has class SymNDArray. Further assignments to the array    are thus automatically symmetrized.    """    return symmetrize(numpy.asarray(input_array)).view(SymNDArray)# Example:a = symarray(numpy.zeros((3, 3)))a[0, 1] = 42print a  # a[1, 0] == 42 too!

(或等价于矩阵而不是数组,具体取决于您的需求)。这种方法甚至可以处理更复杂的分配,例如

a[:, 1] = -1
,可以正确设置
a[1, :]
元素。

请注意,Python 3消除了编写的可能性

def …(…, (i, j),…)
,因此在使用Python 3进行运行之前,必须对代码进行些微调整
def__setitem__(self, indexes, value): (i, j) = indexes



欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/5508248.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-13
下一篇 2022-12-13

发表评论

登录后才能评论

评论列表(0条)

保存