There is a poste on checking if a matrix is PSD in Python. I am wondering how we can check it in PyTorch? is there a function for that?
Asked
Active
Viewed 1,367 times
1 Answers
6
Haven't found a PyTorch function for that, but you should be able to determine it easily, and similarly to the post you've linked, by checking whether the matrix is symmetric and all eigenvalues are non-negative:
def is_psd(mat):
return bool((mat == mat.T).all() and (torch.linalg.eigvals(mat).real>=0).all())
#Test:
is_psd(torch.randn(2,2))

vsimkus
- 335
- 1
- 10

Gil Pinsky
- 2,388
- 1
- 12
- 17
-
2A better solution is to check for symmetry first and then run a Cholesky decomposition. – marnix Oct 16 '21 at 16:24
-
@marnix Thanks for commenting. I missed the symmetry check so added it. I agree Cholesky decomposition should be faster (though for some ill-conditioned matrices numerical stability may be an issue) – Gil Pinsky Oct 16 '21 at 20:16