协方差矩阵的特征值使用QR分解

时间:2019-03-12 15:53:21

标签: numpy linear-algebra pca matrix-factorization

鉴于维度为X的矩阵D x N,我有兴趣使用QR分解来计算C = np.dot(X, X.T)/N的特征值。基于以下内容:

enter image description here

我们期望使用以下内容,C的特征值将为np.diag(r.T,r)

q, r=np.linalg.qr(np.dot(X.T, V))
lambdas2=np.diag(np.dot(r.T, r)) / N

但是,我使用以下代码获取的lambdas2中的值与lambda1中的值不同。

from sklearn.decomposition import PCA
pca = PCA()
pca.fit(X)
lambdas1=pca.explained_variance_

完整的示例是:

import numpy as np
from sklearn.decomposition import PCA
if __name__ == "__main__":
    N = 1000
    D = 20
    X = np.random.rand(D, N)

    X_train_mean = X.mean(axis=0)
    X_train_std = X.std(axis=0)
    X_normalized = (X - X_train_mean) / X_train_std

    pca = PCA(n_components=D)
    cov_ = np.cov(X_normalized) # A D x D array.
    pca.fit(cov_)
    lambdas1 = pca.explained_variance_

    projected_data = np.dot(pca.components_, X_normalized).T # An N x n_components array.

    q, r = np.linalg.qr(projected_data)
    lambdas2 = np.sort(np.diag(np.dot(r.T, r)) / N)[::-1]

0 个答案:

没有答案