Skip to content

Instantly share code, notes, and snippets.

@btel
Created December 10, 2012 10:56
Show Gist options
  • Save btel/4249939 to your computer and use it in GitHub Desktop.
Save btel/4249939 to your computer and use it in GitHub Desktop.
PCA
def PCA(data,ncomps=2):
"""Perfrom a principle component analysis.
Parameters
----------
data : array
(n_vars, n_obs) array where `n_vars` is the number of
variables (vector dimensions) and `n_obs` the number of
observations
Returns
-------
evals : array
sorted eigenvalues
evecs : array
sorted eigenvectors
score : array
projection of the data on `ncomps` components
"""
#norm=data/np.std(data,1)[:,np.newaxis]
#norm[np.isnan(norm)]=0
#norm = data
data = data.astype(np.float64)
K=np.cov(data)
evals,evecs=np.linalg.eig(K)
order=np.argsort(evals)[::-1]
evecs=np.real(evecs[:,order])
evals=np.abs(evals[order])
score= np.dot(evecs[:,:ncomps].T,data)
score = score/np.sqrt(evals[:ncomps, np.newaxis])
return evals,evecs,score
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment