Skip to content

Instantly share code, notes, and snippets.

@wangz10
Created March 16, 2019 14:25
Show Gist options
  • Select an option

  • Save wangz10/ba54f89ebcad21b04beb95622679116c to your computer and use it in GitHub Desktop.

Select an option

Save wangz10/ba54f89ebcad21b04beb95622679116c to your computer and use it in GitHub Desktop.
Perform PCA by eigen decomposition
def pca(X):
# Data matrix X, assumes 0-centered
n, m = X.shape
assert np.allclose(X.mean(axis=0), np.zeros(m))
# Compute covariance matrix
C = np.dot(X.T, X) / (n-1)
# Eigen decomposition
eigen_vals, eigen_vecs = np.linalg.eig(C)
# Project X onto PC space
X_pca = np.dot(X, eigen_vecs)
return X_pca
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment