PCA计算中的复特征值

Ahm*_*otb 6 python numpy eigenvalue eigenvector pca

我试图计算矩阵的PCA.

有时,得到的特征值/向量是复数值,因此当试图通过将特征向量矩阵与点坐标相乘来将点投影到较低维度平面时,得到以下警告

ComplexWarning: Casting complex values to real discards the imaginary part
Run Code Online (Sandbox Code Playgroud)

在那行代码中 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)
Run Code Online (Sandbox Code Playgroud)

Mic*_*ber 13

协方差矩阵是对称的,因此具有真实的特征值.由于数值误差,您可能会在某些特征值中看到一个小的虚部.通常可以忽略虚部.