2012-05-02 199 views
3

IAM的尝试计算的矩阵的PCA。复杂特征值在PCA计算

有时得到的特征值/向量是复杂的值,因此试图通过特征向量矩阵点乘以投射点到较低的维度计划时坐标我碰到下面的警告

ComplexWarning: Casting complex values to real discards the imaginary part 

在这种行代码np.dot(self.u[0:components,:],vector)

整个代码我用来计算PCA

import numpy as np 
import numpy.linalg as la 

class PCA: 
    def __init__(self,inputData): 
     data = inputData.copy() 
     #m = no of points 
     #n = no of features per point 
     self.m = data.shape[0] 
     self.n = data.shape[1] 
     #mean center the data 
     data -= np.mean(data,axis=0) 

     # calculate the covariance matrix 
     c = np.cov(data, rowvar=0) 

     # get the eigenvalues/eigenvectors of c 
     eval, evec = la.eig(c) 
     # u = eigen vectors (transposed) 
     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) 

回答

7

协方差矩阵是对称的,因而具有实特征值的example。您可能会看到一些特征值小虚部由于数值误差。虚部通常可以忽略不计。

+0

@Micael J.理发什么样的数值的错误会导致这样的异常? –

2

您可以使用SCI对于PCA包Python库,这是一个如何使用它