forked from koraykv/unsup
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpca.lua
More file actions
24 lines (22 loc) · 857 Bytes
/
pca.lua
File metadata and controls
24 lines (22 loc) · 857 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
-- PCA using covariance matrix
-- x is supposed to be MxN matrix, where M samples(trials) and each sample(trial) is N dim
-- returns the eigen values and vecotrs of the covariance matrix in increasing order
function unsup.pcacov(x)
local mean = torch.mean(x,1)
local xm = x - torch.ger(torch.ones(x:size(1)),mean:squeeze())
local c = torch.mm(xm:t(),xm)
c:div(x:size(1)-1)
local ce,cv = torch.symeig(c,'V')
return ce,cv
end
-- PCA using SVD
-- x is supposed to be MxN matrix, where M samples(trials) and each sample(trial) is N dim
-- returns the eigen values and vecotrs of the covariance matrix in decreasing order
function unsup.pca(x)
local mean = torch.mean(x,1)
local xm = x - torch.ger(torch.ones(x:size(1)),mean:squeeze())
xm:div(math.sqrt(x:size(1)-1))
local w,s,v = torch.svd(xm:t())
s:cmul(s)
return s,w
end