Skip to content

Instantly share code, notes, and snippets.

@nmichlo
Created March 22, 2021 20:32
Show Gist options
  • Save nmichlo/aa78b98fd3602056b727826c418a3785 to your computer and use it in GitHub Desktop.
Save nmichlo/aa78b98fd3602056b727826c418a3785 to your computer and use it in GitHub Desktop.
PCA with SVD using pytorch
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