Advertisement
Guest User

Untitled

a guest
Jun 25th, 2017
78
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.34 KB | None | 0 0
  1. def pca(X, nb_components=0):
  2.  
  3. mu=np.mean(X,axis=0)
  4. #subtract mean from data
  5. Y=X.copy()
  6. for row in range(0,28):
  7. Y[row,:]-=mu
  8.  
  9. #calculate covariance matrix
  10. C=np.cov(Y,rowvar=False)
  11.  
  12. Eigva,Eigve=np.linalg.eigh(C)
  13. sort_indices = Eigva.argsort()[::-1] # getting their correct order - decreasing
  14.  
  15. Eigva = Eigva[sort_indices] # puttin the evalues in that order
  16. Eigve = Eigve[:,sort_indices] # same for the evectors
  17.  
  18. totvar1=np.sum(Eigva)
  19.  
  20. Eigva=Eigva[0:nb_components]
  21. Eigve=Eigve[:,0:nb_components]
  22. print "eigva"
  23. print Eigva
  24. print
  25. totvar2=np.sum(Eigva)
  26. verh=totvar2/totvar1
  27. print verh
  28.  
  29. norms = np.linalg.norm(Eigve, axis=0) # find the norm of each eigenvector
  30.  
  31. Eigve = Eigve / norms # normalize all eigenvectors
  32.  
  33. b=np.dot(Eigve.T,Y.T)
  34. print b
  35. X2=np.dot(b.T,Eigve.T)
  36.  
  37. for row in range(0,28):
  38. X2[row,:]+=mu
  39.  
  40. #de B-parameters aanpassen en testen op het mean model
  41. b2=np.zeros([nb_components,1])
  42. b2[2]=0+2*np.sqrt(Eigva[2])
  43. mu2=np.dot(Eigve,b2)
  44. mu2=mu2.flatten()
  45. mu2+=mu
  46. print mu2
  47. print mu2.shape
  48. return X2,mu2
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement