【问题标题】:Matplotlib PCA sample not working after altering dimensionsMatplotlib PCA 示例在更改尺寸后不起作用
【发布时间】:2015-03-26 21:19:19
【问题描述】:

我正在尝试学习如何使用 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')
...    

我生成的情节看起来完全不对劲!

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

【问题讨论】:

    标签: python numpy matplotlib pca


    【解决方案1】:

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

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

    【讨论】:

      猜你喜欢
      • 2019-10-27
      • 1970-01-01
      • 2017-08-29
      • 2020-03-11
      • 2013-03-23
      • 2015-08-14
      • 1970-01-01
      • 2016-02-08
      • 2013-08-20
      相关资源
      最近更新 更多