我正在尝试学习如何使用 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 的矩阵。
关于python - Matplotlib PCA 示例在更改尺寸后不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29289064/