如何在python中建立二维图像降维的PCA函数

2024-09-27 02:17:14 发布

您现在位置:Python中文网/ 问答频道 /正文

Currently using this function to calculate eigen value and vectors
**np.linalg.eigh**


CODE
cov_mat = image_2d - np.mean(image_2d , axis = 1)
    eig_val, eig_vec = np.linalg.eigh(np.cov(cov_mat)) # USING "eigh", SO THAT PROPRTIES OF HERMITIAN MATRIX CAN BE USED
    p = np.size(eig_vec, axis =1)
    idx = np.argsort(eig_val)
    idx = idx[::-1]
    eig_vec = eig_vec[:,idx]
    eig_val = eig_val[idx]
    numpc = 3 
    if numpc <p or numpc >0:
        eig_vec = eig_vec[:, range(numpc)]
    score = np.dot(eig_vec.T, cov_mat)
    recon = np.dot(eig_vec, score) + np.mean(image_2d, axis = 1).T 
    recon_img_mat = np.uint8(np.absolute(recon))
    return recon_img_mat

这段代码虽然使用了numpy函数,但它给了我降维。如何为PCA构建自定义函数


Tags: imagenpvalmeancovscorematidx

热门问题