I am trying to calculate the PCA matrix.
Sometimes the resulting eigenvalues / vectors are complex values, so when I try to project a point onto a lower dimensional plan, multiplying the matrix of eigenvectors by the coordinates of the point, I get the following warning
ComplexWarning: Casting complex values to real discards the imaginary part
In this line of code np.dot(self.u[0:components,:],vector)
All the code I used to calculate the PCA
import numpy as np
import numpy.linalg as la
class PCA:
def __init__(self,inputData):
data = inputData.copy()
self.m = data.shape[0]
self.n = data.shape[1]
data -= np.mean(data,axis=0)
c = np.cov(data, rowvar=0)
eval, evec = la.eig(c)
self.u = evec.transpose()
def getPCA(self,vector,components):
if components > self.n:
raise Exception("components must be > 0 and <= n")
return np.dot(self.u[0:components,:],vector)
source
share