### 手动实现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_

将其绘制到数据集的前两个特征上。

我的self.components_的形状是240×240,它是我100×240数据集的240个特征向量。在绘制具有最大特征值的前两个特征向量的前两个值后,得到的结果如下:

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 )

enter image description here

我做错了什么?


回答:

你应该按行而不是按列对特征向量进行排序,也就是说

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

应该改为

self.components_ = self.components_[idx]

另外,你应该确保以相等的纵横比进行绘图,因为箭头可能会错位:

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

在你的代码中包含一个最小的工作示例是个好习惯,所以下次记得这样做 :)。我不得不推测你的其他代码可能是什么样子的,以便得到一个最小的工作示例。不管怎样,这是我建议的代码:

Related Posts

使用LSTM在Python中预测未来值

这段代码可以预测指定股票的当前日期之前的值,但不能预测…

如何在gensim的word2vec模型中查找双词组的相似性

我有一个word2vec模型,假设我使用的是googl…

dask_xgboost.predict 可以工作但无法显示 – 数据必须是一维的

我试图使用 XGBoost 创建模型。 看起来我成功地…

ML Tuning – Cross Validation in Spark

我在https://spark.apache.org/…

如何在React JS中使用fetch从REST API获取预测

我正在开发一个应用程序,其中Flask REST AP…

如何分析ML.NET中多类分类预测得分数组?

我在ML.NET中创建了一个多类分类项目。该项目可以对…

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注