首先要说的是,不要使用eigh
来测试正定性,因为eigh
假定输入矩阵是 Hermite 矩阵。这可能是你认为你引用的答案不起作用的原因。
我不喜欢那个答案,因为它有一个迭代过程(而且我无法理解它的示例),也不喜欢其他答案,因为它不能保证给出最好的正定矩阵,即在 Frobenius 范数(元素平方和)意义下与输入最接近的矩阵。(我绝对不知道你在问题中的代码应该做什么。)
我很喜欢这篇 Higham 在1988年发表的文章的 Matlab 实现:https://www.mathworks.com/matlabcentral/fileexchange/42885-nearestspd,所以我把它移植到 Python (编辑已更新至 Python 3):
from numpy import linalg as la
import numpy as np
def nearestPD(A):
"""Find the nearest positive-definite matrix to input
A Python/Numpy port of John D'Errico's `nearestSPD` MATLAB code [1], which
credits [2].
[1] https://www.mathworks.com/matlabcentral/fileexchange/42885-nearestspd
[2] N.J. Higham, "Computing a nearest symmetric positive semidefinite
matrix" (1988): https://doi.org/10.1016/0024-3795(88)90223-6
"""
B = (A + A.T) / 2
_, s, V = la.svd(B)
H = np.dot(V.T, np.dot(np.diag(s), V))
A2 = (B + H) / 2
A3 = (A2 + A2.T) / 2
if isPD(A3):
return A3
spacing = np.spacing(la.norm(A))
# The above is different from [1]. It appears that MATLAB's `chol` Cholesky
# decomposition will accept matrixes with exactly 0-eigenvalue, whereas
# Numpy's will not. So where [1] uses `eps(mineig)` (where `eps` is Matlab
# for `np.spacing`), we use the above definition. CAVEAT: our `spacing`
# will be much larger than [1]'s `eps(mineig)`, since `mineig` is usually on
# the order of 1e-16, and `eps(1e-16)` is on the order of 1e-34, whereas
# `spacing` will, for Gaussian random matrixes of small dimension, be on
# othe order of 1e-16. In practice, both ways converge, as the unit test
# below suggests.
I = np.eye(A.shape[0])
k = 1
while not isPD(A3):
mineig = np.min(np.real(la.eigvals(A3)))
A3 += I * (-mineig * k**2 + spacing)
k += 1
return A3
def isPD(B):
"""Returns true when input is positive-definite, via Cholesky"""
try:
_ = la.cholesky(B)
return True
except la.LinAlgError:
return False
if __name__ == '__main__':
import numpy as np
for i in range(10):
for j in range(2, 100):
A = np.random.randn(j, j)
B = nearestPD(A)
assert (isPD(B))
print('unit test passed!')
除了仅查找最近的正定矩阵外,上述库还包括isPD
,它使用Cholesky分解来确定矩阵是否为正定。这样,您就不需要任何公差 - 任何想要正定的函数都会在其上运行Cholesky,因此这是确定正定性的绝佳方法。
它还有一个基于蒙特卡洛的单元测试,如果您将其放入posdef.py
并运行python posdef.py
,它将在我的笔记本电脑上在大约一秒钟内通过单元测试。然后在您的代码中,您可以import posdef
并调用posdef.nearestPD
或posdef.isPD
。
如果您需要的话,该代码也在Gist上。