【问题标题】:Value error while generating indexes using PCA in scikit-learn在 scikit-learn 中使用 PCA 生成索引时出现值错误
【发布时间】:2016-05-13 20:38:33
【问题描述】:

我正在尝试使用以下函数从数据中生成索引:

功能:

import numpy as np
from sklearn.decomposition import PCA   

def pca_index(data,components=1,indx=1):
    corrs = np.asarray(data.cov())
    pca   = PCA(n_components = components).fit(corrs)
    trns = pca.transform(data)
    index=np.dot(trns[0:indx],pca.explained_variance_ratio_[0:indx])
    return index

索引:从主成分生成

index = pca_index(data=mydata,components=3,indx=2)

调用函数时出现以下错误:

Traceback (most recent call last):

File "<ipython-input-411-35115ef28e61>", line 1, in <module>
index = pca_index(data=mydata,components=3,indx=2)

File "<ipython-input-410-49c0174a047a>", line 15, in pca_index
index=np.dot(trns[0:indx],pca.explained_variance_ratio_[0:indx])

ValueError: shapes (2,3) and (2,) not aligned: 3 (dim 1) != 2 (dim 0)

任何人都可以帮助解决错误。

据我了解,当我将下标索引作为变量 (indx) 传递时,以下点会出现一些错误:

trns[0:indx],pca.explained_variance_ratio_[0:**indx**]

【问题讨论】:

    标签: python-3.x scikit-learn pca


    【解决方案1】:

    在np.dot 中,您试图将具有 (2,3) 维度的矩阵与具有 (2,) 维度的矩阵相乘,即向量。

    但是,您只能将 NxM 乘以 MxP,例如(3,2) 到 (2,1) 或 (2,3) 到 (3,1)。

    在您的示例中,第二个矩阵的维度为 (2,),在 numpy 术语中,它与 (2,1) 相似但不同。您可以使用vector.reshape([2,1]) 将向量重塑为矩阵

    您还可以转置第一个矩阵,从而将其维度从 (2,3) 转换为 (3,2)。

    但是,请确保将适当的矩阵相乘,因为结果会与您预期的不同。

    【讨论】:

    • 感谢您的快速回答。我什至没有正确阅读错误。
    猜你喜欢
    • 2021-05-28
    • 1970-01-01
    • 2019-03-05
    • 2017-12-24
    • 2016-02-28
    • 2019-11-26
    • 2015-07-26
    • 2019-04-28
    • 1970-01-01
    相关资源
    最近更新 更多