Skip to content

Instantly share code, notes, and snippets.

@isayev
Forked from julienr/pca_svds.py
Created May 12, 2014 20:08
Show Gist options
  • Select an option

  • Save isayev/8ea7bcbbb682ae53bce2 to your computer and use it in GitHub Desktop.

Select an option

Save isayev/8ea7bcbbb682ae53bce2 to your computer and use it in GitHub Desktop.
def pca(X, npc):
n_samples, n_features = X.shape
Xmean = np.mean(X, axis=0)
U, s, Vt = scipy.sparse.linalg.svds(X - Xmean, k=npc)
order = np.argsort(-s) # sort s in descending order
# svds returns U, s, Vt sorder in ascending order. We want descending
s = s[order]
W = Vt[order,:]
explained_variance = (s**2) / float(n_samples)
return Xmean, W, explained_variance
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment