Skip to main content
 首页 » 编程设计

python之Matplotlib PCA 示例在更改尺寸后不起作用

2024年10月25日11虾米姐

我正在尝试学习如何使用 matplotlib.mlabPCA。下面我有以下代码:

import numpy as np 
from matplotlib import pyplot as plt 
from matplotlib.mlab import PCA as mlabPCA 
from mpl_toolkits.mplot3d import Axes3D, proj3d 
 
np.random.seed(234234782384239784) 
 
DIMENSIONS = 3 
 
mu_vec1 = np.array([0 for i in xrange(DIMENSIONS)]) 
cov_mat1 = np.identity(DIMENSIONS) 
class1_sample = np.random.multivariate_normal(mu_vec1, cov_mat1, 20).T 
assert class1_sample.shape == (DIMENSIONS, 20) 
 
mu_vec2 = np.array([3 for i in xrange(DIMENSIONS)]) 
cov_mat2 = np.identity(DIMENSIONS) 
class2_sample = np.random.multivariate_normal(mu_vec2, cov_mat2, 20).T 
assert class2_sample.shape == (DIMENSIONS, 20) 
 
# Combine the two together 
all_samples = np.vstack([class1_sample.T, class2_sample.T]) 
all_samples = all_samples.T 
assert all_samples.shape == (DIMENSIONS, 40) 
 
mlab_pca = mlabPCA(all_samples.T) 
 
# 2d plotting 
plt.plot(mlab_pca.Y[0:20, 0], 
         mlab_pca.Y[0:20, 1], 
         'o', markersize=7, color='blue', alpha=0.5, label='class1') 
plt.plot(mlab_pca.Y[20:40, 0], 
         mlab_pca.Y[20:40, 1], 
         '^', markersize=7, color='red', alpha=0.5, label='class2') 
 
plt.xlabel('x_values') 
plt.ylabel('y_values') 
plt.xlim([-4, 4]) 
plt.ylim([-4, 4]) 
plt.legend() 
plt.title('Transformed samples with class labels from matplotlib.mlab.PCA()') 
 
plt.show() 

如您所见,PCA 运行良好,我得到了下图:

但是,当我尝试更改 DIMENSIONS = 100(我正在尝试模拟光谱数据分析)时,出现此错误:

RuntimeError: we assume data in a is organized with numrows>numcols 

“好的,我可以将 PCA 应用到这个矩阵的转置上。”我天真地告诉自己。

DIMENSIONS = 100 
...         
mlab_pca = mlabPCA(all_samples) 
 
plt.plot(mlab_pca.Y[0, 0:20], 
         mlab_pca.Y[1, 0:20], 
         'o', markersize=7, color='blue', alpha=0.5, label='class1') 
plt.plot(mlab_pca.Y[0, 20:40], 
         mlab_pca.Y[1, 20:40], 
         '^', markersize=7, color='red', alpha=0.5, label='class2') 
...     

我的结果图看起来完全不对劲!

我做错了什么吗?还是添加那么多维度实际上弄乱了我的数据?

请您参考如下方法:

我不希望这些点分开。 PCA(X) 和 PCA(X.T).T 不是一回事

似乎要求 numrows > numcols 是 matplotlib PCA 的限制。 R 的 prcomp 和 Python 的 sklearn PCA可以采用 numrows > numcols 或 numcols > numrows 的矩阵。