我试图计算矩阵的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)
答案 0 :(得分:10)
协方差矩阵是对称的,因此具有真实的特征值。由于数值误差,您可能会在某些特征值中看到一个小的虚部。通常可以忽略虚部。
答案 1 :(得分:2)
您可以将scikits python库用于PCA,这是example如何使用它