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

标签 python numpy matplotlib pca

我正在尝试学习如何使用 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 工作得很好,我得到了下图: enter image description here

但是,当我尝试更改 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')
...    

我的结果情节看起来完全不对劲! enter image description here

我做错了什么吗?或者添加这么多维度实际上会弄乱我的数据吗?

最佳答案

我不希望这些点分开。 PCA(X) 与 PCA(X.T).T 不同

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

关于python - Matplotlib PCA 示例在更改尺寸后不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29289064/

相关文章:

Python 线程返回值

python - 导入错误 : No module named cv2

python - 将序列转换为数组元素

python - matplotlib.pyplot.draw() 和 matplotlib.pyplot.show() 没有效果

python - matplotlib 中是否有制作散点图矩阵的功能?

python - MongoEngine 中如何让引用字段接受多个文档模式?

python - 如何通过迭代批量数组来创建多维结果

python - 在 SQLAlchemy 中延迟加载 column_property

python - 在Python中导入颜色科学模块时出现"TypeError"

python - 在 matplotlib 中自定义颜色 - 热图