我需要绘制我这样计算的特征向量:
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 )
我做错了什么?
回答:
你应该按行而不是按列对特征向量进行排序,也就是说
self.components_ = self.components_[:,idx]
应该改为
self.components_ = self.components_[idx]
另外,你应该确保以相等的纵横比进行绘图,因为箭头可能会错位:
plt.gca().set_aspect('equal')
在你的代码中包含一个最小的工作示例是个好习惯,所以下次记得这样做 :)。我不得不推测你的其他代码可能是什么样子的,以便得到一个最小的工作示例。不管怎样,这是我建议的代码: