Guest User

Untitled

a guest
Jan 21st, 2019
64
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.68 KB | None | 0 0
  1. import numpy as np
  2. from sklearn import datasets
  3. from sklearn.decomposition import PCA
  4. def PCA_eig(X,k, center=True, scale=False):
  5. n,p = X.shape
  6. ones = np.ones([n,1])
  7. h = ((1/n) * np.matmul(ones, ones.transpose())) if center else np.zeros([n,n])
  8. H = np.eye(n) - h
  9. X_center = np.matmul(H, X)
  10. covariance = 1/(n-1) * np.matmul(X_center.transpose(), X_center)
  11. scaling = np.sqrt(1/np.diag(covariance)) if scale else np.ones(p)
  12. scaled_covariance = np.matmul(np.diag(scaling), covariance)
  13. w,v = np.linalg.eig(scaled_covariance)
  14. components = v[:, :k]
  15. explained_variance = w[:k]
  16. return { 'X':X, 'k':k, 'components':components,
  17. 'explained_variance':explained_variance }
Add Comment
Please, Sign In to add comment