【问题标题】:Manual Implementation of PCA produces a wrong plot, where eigenvectors are not orthogonalPCA 的手动实现会产生错误的图,其中特征向量不是正交的
【发布时间】:2021-05-03 08:49:42
【问题描述】:

我需要绘制我这样计算的特征向量:

def fit(self, X):
    
    '''
    fits sorted eigenvalues and eigenvectors to class attributes. same goes for variance and explained variance.
    '''
    
    n_samples = X.shape[0]
    # We center the data and compute the sample covariance matrix.
    X -= np.mean(X, axis=0)
    self.cov_matrix_ = np.dot(X.T, X) / (n_samples-1)
    #test = np.cov(X)
    
    #Negative values are ignored with eigh
    (self.eigvalues_, self.components_) = np.linalg.eigh(self.cov_matrix_)
    
    idx = self.eigvalues_.argsort()[::-1]   
    self.eigvalues_ = self.eigvalues_[idx]
    self.components_ = self.components_[:,idx]
    self.variance_ = np.sum(self.eigvalues_)
    self.explained_variance_ = self.eigvalues_ / self.variance_
    
def transform(self, X):
    #project data onto eigenvectors
    print(self.components_.shape, X.shape)
    self.projected_ = X @ self.components_.T
    return self.projected_

进入我的数据集前 2 个特征的图。

self.components_ 的形状是 100x240 数据集的 240 个特征向量,形状为 240x240。 用最大的特征值绘制我的 2 个特征向量的前两个值后,结果如下:

pca = PCA()

pca.fit(subsample)

#pca.transform(subsample)

plt.scatter(subsample[:,0], subsample[:,1], edgecolor='none', alpha=0.5)
plt.quiver(pca.components_[0,0], pca.components_[0,1], 
       angles='xy', scale_units='xy', scale=1, width=0.002 )
plt.quiver(pca.components_[1,0], pca.components_[1,1], 
       angles='xy', scale_units='xy', scale=1, width=0.002 )

我做错了什么?

【问题讨论】:

  • 您好!我只是想提醒您一下,您应该使用反引号将代码粘贴为实际文本,以便更容易复制粘贴以便其他人调试您的代码。
  • 哦,好吧,那我就这么做 --- 完成

标签: python numpy machine-learning pca covariance


【解决方案1】:

您应该按行而不是列对特征向量进行排序

self.components_ = self.components_[:,idx]

应该是

self.components_ = self.components_[idx]

此外,您应该确保以相同的纵横比进行绘图,因为箭袋可能会错位:

plt.gca().set_aspect('equal')

在您的代码中包含一个最低限度的工作示例是一种很好的做法,因此下次请记住 :)。为了获得最小的工作示例,我不得不推断您的其余代码可能是什么。无论如何,这是我建议的代码:

import numpy as np 
from matplotlib import pyplot as plt

class PCA:
    def fit(self, X):
        
        '''
        fits sorted eigenvalues and eigenvectors to class attributes. same goes for variance and explained variance.
        '''
        
        n_samples = X.shape[0]
        # We center the data and compute the sample covariance matrix.
        X -= np.mean(X, axis=0)
        self.cov_matrix_ = np.dot(X.T, X) / (n_samples-1)
        #test = np.cov(X)
        
        #Negative values are ignored with eigh
        (self.eigvalues_, self.components_) = np.linalg.eigh(self.cov_matrix_)
        
        idx = self.eigvalues_.argsort()[::-1]   
        self.eigvalues_ = self.eigvalues_[idx]
        self.components_ = self.components_[idx]
        self.variance_ = np.sum(self.eigvalues_)
        self.explained_variance_ = self.eigvalues_ / self.variance_
        
    def transform(self, X):
        #project data onto eigenvectors
        print(self.components_.shape, X.shape)
        self.projected_ = X @ self.components_.T
        return self.projected_

pca = PCA()

# Generate some dummy data
subsample = np.random.randn(69,2)*0.1 
subsample[:,0] = subsample[:,0]*8 
subsample[:,1] = subsample[:,0]*2 + subsample[:,1] # Add some correlations

pca.fit(subsample)

plt.scatter(subsample[:,0], subsample[:,1], edgecolor='none', alpha=0.5)
plt.quiver(pca.components_[0,0]*2, pca.components_[0,1]*2, # *2 to make arrows larger
       angles='xy', scale_units='xy', scale=1, width=0.006)
plt.quiver(pca.components_[1,0]*2, pca.components_[1,1]*2, 
       angles='xy', scale_units='xy', scale=1, width=0.006)
plt.gca().set_aspect('equal')
plt.show()

【讨论】:

  • 非常感谢 Naphat,我错过了那里的一个小细节,因为我不太擅长 numpy 切片哈哈。我还发现,您的二维数据中的 pca 在二维空间中是正交的,但在我的多维数据中,当分解为二维时它们不是正交的,并且需要一些时间才能弄清楚 ¯_(ツ)_/ ¯
  • 没问题!嗯,这有点奇怪,因为它们应该是相互正交的。
猜你喜欢
  • 2022-01-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-01-17
  • 2020-05-19
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多