Created
March 16, 2019 14:25
-
-
Save wangz10/ba54f89ebcad21b04beb95622679116c to your computer and use it in GitHub Desktop.
Perform PCA by eigen decomposition
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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