[英]Scipy / Numpy : Cholesky while checking if positive definite
I am translating a script from Matlab to Python where I have a matrix VarCov and I get the Cholesky decomposition of it.我正在将一个脚本从 Matlab 翻译成 Python,其中我有一个矩阵 VarCov,我得到了它的 Cholesky 分解。 Sometimes, due to float approximation, a matrix that should be positive devinite (PD) is not, and i have to add a small number to the diagonal.有时,由于浮点逼近,应该是正定性 (PD) 的矩阵不是,我必须在对角线上添加一个小数。 Here is the Matlab code:这是Matlab代码:
[CholeskyUpper,pd] = chol(VarCov);
while pd
VarCov = VarCov + 0.0001 * eye(size(VarCov,1));
[CholeskyUpper,pd] = chol(VarCov);
end
Matlab is convenient because it can return if a matrix is PD while doing the Cholesky decomposition. Matlab 很方便,因为它可以在进行 Cholesky 分解时返回矩阵是否为 PD。 It doesn't raise an error while doing so.这样做时不会引发错误。 It seems that in Python (scipy), it will just return an error.似乎在 Python (scipy) 中,它只会返回一个错误。 Is there a way to do something similar to Matlab without having to compute the eigenvalues first ?有没有办法做类似于 Matlab 的事情而不必先计算特征值?
Edit: Following sascha's tip I tried this:编辑:按照 sascha 的提示,我尝试了这个:
MyMatrix = np.array([[1,2],[1,2]])
PD = False
while PD == False:
PD = True
try:
MyCholDec = sp.linalg.cholesky(MyMatrix)
except np.linalg.LinAlgError:
PD = False
MyMatrix = MyMatrix + np.eye(2) * 0.001
print("done")
Is this the best way ?这是最好的方法吗?
The fastest and easiest method I finally found is to directly use the scipy's lapack function:我最后找到的最快最简单的方法是直接使用scipy的lapack函数:
MyMatrix = np.array([[1,2],[1,2]])
(MyCholDec ,pd) = sp.linalg.lapack.dpotrf(MyMatrix )
while pd > 0:
MyMatrix= MyMatrix + np.eye(2) * 0.01
(MyCholDec ,pd) = sp.linalg.lapack.dpotrf( MyMatrix )
This function works like the Matlab version retunring both the decomposition and an int > 0 if the matrix is not positive definite.如果矩阵不是正定矩阵,则此函数的工作方式类似于 Matlab 版本,同时重新调整分解和 int > 0。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.