使用 sklearn 的主成分分析

PCA using sklearn

我有一个很大的输入矩阵,大小为 (20, 20000),我正在尝试使用 sklearn Python 包执行 PCA。这里20指的是20个subject,20000指的是20000个features。下面是示例代码:

import numpy as np
from sklearn.decomposition import PCA

rng = np.random.RandomState(1)
X = rng.randn(20, 20000)
pca.fit(X)
X.shape = 

>> (20, 20000)

pca = PCA(n_components=21)
pca.fit(X)
X_pca = pca.transform(X)
print("Original shape: ", X.shape)
print("Transformed shape: ", X_pca.shape)

>> Original shape: (20, 20000)
>> Transformed shape: (20, 20)

使用 PCA,我是否无法取回比我的 x 值数量更多的组件(为什么我们在获取 pca 组件时会受到 x 值长度的限制)?

与 sklearn 相比,这更多地与 PCA 实现有关,但是:

if n_samples <= n_features:
    maxn_pc = n_samples - 1
else:
    maxn_pc = n_features

即,如果您的样本数 (n) 小于或等于特征数 (f),则您可以提取的非平凡成分的最大数量为 n-1。否则,最大数量的非平凡组件是 n。

PCA implementation performs a singular value decomposition in order to identify the singular values associated with the principal directional components. In your case this singular value matrix is a 20x20000 rectangular diagonal matrix 最多可以有 20 个组件。