Skip to content

Instantly share code, notes, and snippets.

@bkj
Created June 22, 2018 03:28
Show Gist options
  • Save bkj/eead8b8a55a4b09527c74166882da84f to your computer and use it in GitHub Desktop.
Save bkj/eead8b8a55a4b09527c74166882da84f to your computer and use it in GitHub Desktop.
#!/usr/bin/env python
"""
pca_svd.py
"""
from sklearn.decomposition import TruncatedSVD, PCA
import numpy as np
X = np.random.normal(0, 1, (100, 10))
X -= X.mean(axis=0)
pca = PCA(svd_solver='full').fit(X)
u, s, v = np.linalg.svd(X, full_matrices=False)
np.allclose(np.abs(pca.components_), np.abs(v)) # True
p = PCA(svd_solver='full').fit_transform(X)
np.allclose(X.dot(pca.components_.T), p) # True
np.allclose(np.abs(u.dot(np.diag(s))), np.abs(p)) # True
p2 = PCA(svd_solver='full', whiten=True).fit_transform(X)
np.allclose(np.abs(p2), np.abs(u * np.sqrt(100 - 1))) # True
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment