我想测试PCA的工作流程,为此,我想创建一个数据集,其中包含3个要素,并且这些要素之间具有设定的关系。然后应用PCA并检查这些关系是否被捕获,在Python中最直接的方法是什么?
谢谢!
您可以创建样本,其中两个要素彼此独立,而第三个要素是另两个要素的线性组合。
例如:
import numpy as np
from numpy.random import random
N_SAMPLES = 1000
samples = random((N_SAMPLES, 3))
# Let us suppose that the column `1` will have the dependent feature, the other two being independent
samples[:, 1] = 3 * samples[:, 0] - 2 * samples[:, 2]
现在,如果运行PCA在该样本上找到两个主要成分,则“解释方差”应等于1。
例如:
from sklearn.decomposition import PCA
pca2 = PCA(2)
pca2.fit(samples)
assert sum(pca2.explained_variance_ratio_) == 1.0 # this should be true