我正在尝试学习使用scikit库(特别是sklearn.decomposition和sklearn.preprocessing)使用Python进行PCA分析的基础知识。其目的是将图像中的数据导入矩阵X(每一行是一个样本,每列都是一个特征),然后标准化X,使用PCA提取主成分(2个最重要,6个最重要.6个不太重要),对这些主成分进行投影X,反转先前的变换并绘制结果,以查看与原始图像/图像的差异。
现在假设我不想考虑2,3,4.最重要的主成分,但我想考虑N个不太相关的组件,比如说N=6。
应如何进行分析?我的意思是,我不能简单地标准化,然后调用PCA().fit_transform,然后返回到inverse_transform()来绘制结果。
现在我正在做这样的事情:
X_std = StandardScaler().fit_transform(X) # standardize original data
pca = PCA()
model = pca.fit(X_std) # create model with all components
Xprime = model.components_[range(dim-6, dim, 1),:] # get last 6 PC然后我停了下来,因为我知道我应该调用transform(),但是我不知道怎么做.我试过几次,因为我已经成功了。
有没有人能告诉我前面的步骤是否正确,并指出下一步的方向?
非常感谢
编辑:目前我已经按照我的问题的第一个答案所建议的那样调整了这个解决方案:
model = PCA().fit(X_std)
model2pc = model
model2pc.components_[range(2, img_count, 1), :] = 0
Xp_2pc = model2pc.transform(X_std)
Xr_2pc = model2pc.inverse_transform(Xp_2pc)然后,我对6 pc,60 pc,最后6 pc也做了同样的操作。我注意到这是很费时的。我希望得到一个模型,直接提取我需要的主组件(不对其他组件进行归零),然后对该模型执行transform()和inverse_transform()。
发布于 2018-11-26 17:16:28
如果你想忽略所有的,除了最后的6个主成分,你可以把那些你不想保留的都给零了。
N = 6
X_std = StandardScaler().fit_transform(X)
pca = PCA()
model = pca.fit(X_std) # create model with all components
model.components_[:-N] = 0然后,要从数据中删除除最后一个N组件之外的所有组件,只需对数据进行正向和逆变换:
Xprime = model.inverse_transform(model.transform(X_std))下面是一个示例:
>>> X = np.random.rand(18).reshape(6, 3)
>>> model = PCA().fit(X)往返转换应该返回原始数据:
>>> X
array([[0.16594796, 0.02366958, 0.8403745 ],
[0.25219425, 0.22879029, 0.07950927],
[0.69636084, 0.4410933 , 0.97431828],
[0.50121079, 0.44835563, 0.95236146],
[0.6793044 , 0.53847562, 0.27882302],
[0.32886931, 0.0643043 , 0.10597973]])
>>> model.inverse_transform(model.transform(X))
array([[0.16594796, 0.02366958, 0.8403745 ],
[0.25219425, 0.22879029, 0.07950927],
[0.69636084, 0.4410933 , 0.97431828],
[0.50121079, 0.44835563, 0.95236146],
[0.6793044 , 0.53847562, 0.27882302],
[0.32886931, 0.0643043 , 0.10597973]])现在,去掉第一个主成分:
>>> model.components_
array([[ 0.22969899, 0.21209762, 0.94986998],
[-0.67830467, -0.66500728, 0.31251894],
[ 0.69795497, -0.71608653, -0.0088847 ]])
>>> model.components_[:-2] = 0
>>> model.components_
array([[ 0. , 0. , 0. ],
[-0.67830467, -0.66500728, 0.31251894],
[ 0.69795497, -0.71608653, -0.0088847 ]])由于删除了第一个主成分(包含最大的方差),往返变换现在给出了不同的结果:
>>> model.inverse_transform(model.transform(X))
array([[ 0.12742811, -0.01189858, 0.68108405],
[ 0.36513945, 0.33308073, 0.54656949],
[ 0.58029482, 0.33392119, 0.49435263],
[ 0.39987803, 0.35478779, 0.53332196],
[ 0.71114004, 0.56787176, 0.41047233],
[ 0.44000711, 0.16692583, 0.56556581]])https://stackoverflow.com/questions/53485070
复制相似问题