Created
March 22, 2021 20:32
-
-
Save nmichlo/aa78b98fd3602056b727826c418a3785 to your computer and use it in GitHub Desktop.
PCA with SVD using pytorch
This file contains hidden or 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
def torch_pca_svd(X, center=True): | |
n, _ = X.shape | |
# center points along axes | |
if center: | |
X = X - X.mean(dim=0) | |
# perform singular value decomposition | |
u, s, v = torch.svd(X) | |
# extract components | |
components = v.T | |
explained_variance = torch.mul(s, s) / (n-1) | |
return components, explained_variance |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment