【问题标题】:PCA -- Calculating Reduced Size Matrix With NumpyPCA -- 使用 Numpy 计算缩减大小的矩阵
【发布时间】:2019-12-13 02:55:27
【问题描述】:

我正在尝试使用 PCA 将输入图像的大小从 4096 x 4096 减小到 4096 x 163,同时保留其重要属性。但是,我的方法有些问题,因为我得到了不正确的结果。我相信这是在构建我的矩阵 U 时。下面列出了我的结果与正确结果。 开始代码:

# Reshape data to 4096 x 163
X_reshape = np.transpose(X_all, (1,2,3,0)).reshape(-1, X_all.shape[0])
X = X_reshape[:, :163]

mean_array = np.mean(X, axis = 1)
X_tilde = np.reshape(mean_array, (4096,1))
X_tilde = X - X_tilde   

# Construct the covariance matrix for computing u'_i
covmat = np.cov(X_tilde.T)

# Compute u'_i, which is stored in the variable v
w, v = np.linalg.eig(covmat)

# Compute u_i from u'_i, and store it in the variable U
U = np.dot(X_tilde, v)

# Normalize u_i, i.e., each column of U
U = U / np.linalg.norm(U)

我的结果:

PC1 explains 0.08589754681312775% of the total variance
PC2 explains 0.07613195994874819% of the total variance
First 100 PCs explains 0.943423133356313% of the total variance

Shape of U: (4096, 163)
First 5 elements of first column of U: [-0.00908046 -0.00905446 -0.00887831 -0.00879843 -0.00850907]
First 5 elements of last column of U: [0.00047628 0.00048451 0.00045043 0.00035762 0.00025785]

预期结果:

PC1 explains 14.32% of the total variance
PC2 explains 7.08% of the total variance
First 100 PCs explains 94.84% of the total variance

Shape of U: (4096, 163)
First 5 elements of first column of U:  [0.03381537 0.03353881 0.03292298 0.03238798 0.03146345]
First 5 elements of last column of U:   [-0.00672667 -0.00496044 -0.00672151 -0.00759426 
-0.00543667]

我的计算一定有问题,我就是想不通。如果您需要更多信息,请告诉我。

我正在使用的证明:

【问题讨论】:

  • 为什么不使用奇异值分解 (SVD)?在任何情况下都包括 MWE 以产生您的输出。
  • 我很好奇的一件事是为什么要在单个图像上进行 PCA?您是否尝试实现压缩算法?
  • @lbragile 应该提到这是我正在学习的 CS 课程的作业。我无法选择我使用的方法。教授希望我们使用 numpy 并弄清楚如何从头开始实现它。我将编辑帖子以包含我正在关注的证据。
  • @jhill515 见以上评论
  • @z.rubi,我知道教授希望你以某种方式做事。有趣的是,numpy.linalg.svd() 返回 U 矩阵,它是 AA' 的特征向量,而 V 矩阵是 A'A 的特征向量。也就是说,你有理由要求教授激发这个问题。这就是为什么我要问您是否正在尝试实施压缩或正在为另一个学习者进行预处理降维。从某种意义上说,如果您试图将 4096x4096 图像缩小为具有相同行空间的图像,这似乎很奇怪,即使对于宠物示例也是如此。

标签: python numpy machine-learning pca eigenvector


【解决方案1】:

在我看来,您的步骤有问题。在计算特征向量和特征值之前,您从输入中删除了维度,因此您在此阶段有效地随机删除了一堆输入,没有任何理由。

# Reshape data to 4096 x 163
X_reshape = np.transpose(X_all, (1,2,3,0)).reshape(-1, X_all.shape[0])
X = X_reshape[:, :163]

我不太理解上面对transpose 的调用背后的意图,但我认为这并不重要。在计算协方差矩阵的特征向量和特征值后,您只能从输入中删除维度。而且您不会明确地从数据中删除维度;您截断特征向量矩阵,然后将简化的特征向量矩阵用于投影步骤。

本例中的协方差矩阵应为 4096x4096 矩阵。依次返回特征值和特征向量,最大的特征值和对应的特征向量在开头。然后,您可以将特征向量的数量截断为 163,并创建降维投影。

我可能对作业有误解,但我很确定这就是问题所在。由于是作业,我不愿多说。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-10-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多