I have written a code in lua for PCA. Any one help to convert this code into Pytorch, please?
function unsup.pcacov(x)
local mean = torch.mean(x,1)
local xm = x - mean:expandAs(x)
local c = torch.mm(xm:t(),xm)
c:div(x:size(1)-1)
local ce,cv = torch.symeig(c,‘V’)
return ce,cv
end
This should translate pretty cleanly to python. Pytorch and regular torch have a very similar API.
In particular, if you’re not familiar with python syntax, here’s how you define a function:
def unsup.pacov(x):
mean = torch.mean(x, 1)
xm = x - mean.expand(x)
# etc etc
Disclaimer: I haven’t tried the above code out but you can find the corresponding pytorch functions in the documentations page: http://pytorch.org/docs/master/torch.html
Another possible way to import numpy. But I am getting error as well. I am not sure how numpy is used with pytorch.
import numpy as np
def pca(x):
x = torch.from_numpy(np.cov(x))
ev_s , eig_s = torch.from_numpy(np.linalg.eig(x))
return ev_s , eig_s
Can I use numpy for calculating eigenvectors. But I think the problem is that x is not a numpy matrix. It’s a pytorch tensor. So how can I use numpy with pytorch?
import numpy as np
def pca(x):
x = torch.from_numpy(np.cov(x))
ev_s , eig_s = torch.from_numpy(np.linalg.eig(x))
return ev_s , eig_s
def pca(data, var_fraction):
""" principal components, retaining as many components as required to
retain var_fraction of the variance
Returns projected data, projection mapping, inverse mapping, mean"""
from numpy.linalg import eigh
u, v = eigh(numpy.cov(data, rowvar=1, bias=1))
v = v[:, numpy.argsort(u)[::-1]]
u.sort()
u = u[::-1]
u = u[u.cumsum()<u.sum()*var_fraction]
numprincomps = u.shape[0]
V = ((u**(-0.5))[:numprincomps][numpy.newaxis,:]*v[:,:numprincomps]).T
W = (u**0.5)[:numprincomps][numpy.newaxis,:]*v[:,:numprincomps]
return numpy.dot(V,data), V, W