存个代码,以后参考。
numpy次成分分析和PCA降维
SVD分解做次成分分析
原图:
次成分复原图:
代码:
import numpy as np
from numpy import linalg
import cv2 as cv
src = cv.imread("/home/xueaoru/图片/output_3_0.png")
gray = cv.cvtColor(src,cv.COLOR_BGR2GRAY)
S,V,D = linalg.svd(gray)
vv = np.zeros(shape = gray.shape)
h = min(S.shape[0],D.shape[0])
for i in range(int(h * 0.7)):
vv[h-i-1,h-i-1] = V[h-i-1]
out = np.dot(np.dot(S,vv),D)
cv.imshow("out",out.astype(np.uint8))
cv.waitKey(0)
PCA对随机10000个数据降维分析
基于霍特林变换。
dataset = np.random.rand(1000,10) * 10 + 5 #(1000,10)
X = dataset
Ex = np.mean(X,axis = 0).reshape(-1,10).T # (p,1)
Rx = np.cov(X.T)
#S,V,D = linalg.svd(Rx)
eigs,D = linalg.eig(Rx) # val(,10) and vec(10,10)
indices = np.argsort(eigs)
U = D[indices[:-6:-1],:] # 5个 (5,10)
Y = U.dot((X.T - Ex)) # (5,1000) 霍特林变换(5,1000)
print(Y.T)
本程序将10维数据降维成5维,基于霍特林变换。、