Python 函数将矩阵作为输入,并使用 np.linalg.cholesky 识别哪些不是正定的

Python function that takes matrices in as inputs, and identifies which ones are not positive-definite using np.linalg.cholesky

要检查矩阵是否正定(即可逆),人们经常使用 np.linalg.cholesky,如果矩阵不是正定的,returns 会出现以下错误:

LinAlgError: Matrix is not positive definite

另一方面,如果矩阵是正定的,则​​相同的函数将输出一个 numpy 数组。

我想使用 cholesky 函数检查多个矩阵是否为正定矩阵,而不是只有一个矩阵。我想编写一个将多个矩阵作为输入(A、B、C)的函数,将它们按顺序输入 cholesky,然后 returns 声明

"Matrices B and C are not positive definite".

我认为这很难做到,因为 cholesky 要么 returns 一个错误,要么 returns 一个数组,如上所述。当它遇到错误时,整个代码 运行 被中止,这主要是我希望函数能够 avoid/side-step。因此,该函数必须识别 cholesky 对于每个矩阵 的输出是错误还是数组,并且能够识别所有错误矩阵 name (A, B, C),同时没有被 cholesky

中止

判断矩阵是否正定的函数是捕获异常,然后判断异常是否为矩阵非正定引起的。此函数检查矩阵是否为正定矩阵:

import numpy as np
def matrix_is_positive_definite(m):
     try:
         ch = np.linalg.cholesky(m)
         return True
     except np.linalg.LinAlgError as e:
         if e.args[0] == 'Matrix is not positive definite':
             return False
         else:
             raise e

对于作为输入的矩阵列表,只需使用循环或列表推导将函数应用于列表中的每个矩阵:

def matrices_are_positive_definite(l):
    return [matrix_is_positive_definite(m) for m in l]

如果你想以人类可读的方式打印它,你可以这样做:

def print_not_positive_definite_matrices (l, names):
    not_positive_definite_matrices = [names[i] for i, m in enumerate(l) if not matrix_is_positive_definite(m)]
    if len(not_positive_definite_matrices) == 0:
        print('All matrices are positive definite')
    elif len(not_positive_definite_matrices) == 1:
        print('Matrix {} is not positive definite'.format(not_positive_definite_matrices[0]))
    else:
        print('Matrices {} and {} are not positive definite'.format(', '.join(not_positive_definite_matrices[:-1]),not_positive_definite_matrices[-1]))