Last active
April 10, 2022 13:49
-
-
Save nguyenhaidang94/cd26d0ebb4e29f314471c74902a75b84 to your computer and use it in GitHub Desktop.
Implement pseudo inverse
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import numpy as np | |
def pinv(x: np.ndarray, singular_threshold: float = 1e-10): | |
""" | |
Pseudo inverse.\n | |
Params: | |
x: matrix to inverse | |
singular_threshold: threshold to remove singularvalues | |
""" | |
u, s, vt = np.linalg.svd(x, full_matrices=True) | |
n_remaining_singularvalues = sum(s > singular_threshold) | |
if not n_remaining_singularvalues: | |
raise ArithmeticError("Can't inverse matrix," | |
+ " all singularvalues are lower than singular_threshold.") | |
s = s[:n_remaining_singularvalues] | |
ut = u[:,:n_remaining_singularvalues].T | |
v = vt[:n_remaining_singularvalues,:].T | |
# take the inverse of singularvalues to compute the inverse matrix | |
s_i = 1 / s * np.identity(n_remaining_singularvalues) | |
return v @ s_i @ ut |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment