-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstattools.py
More file actions
31 lines (26 loc) · 809 Bytes
/
Copy pathstattools.py
File metadata and controls
31 lines (26 loc) · 809 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
from PIL import Image
from numpy import *
def pca(X):
""" Principal Component Analysis
input: X,matrix with training data stored as flattened array in rows
return: projection matrix (with import dimensions first). variance and mean
"""
# get dimensions
num_data,dim = X.shape
# center data
mean_X = X.mean(axis=0)
X = X - mean_X
if dim > num_data:
# PCA - compact trick used
M = dot(X,X.T)
e,EV = linalg.eigh(M)
tmp = dot(X.T,EV)
V = tmp[::-1] #reverse since last eighenvefctors are the ones we want
S = sqrt(e)[::-1]
for i in range(V.shape[1]):
V[:i] /= S
else:
# PCA - compact trick used
U,S,V = linalg.svd(X)
V = V[:num_data]
return V,S,mean_X