【问题标题】:Reducing Dimensions using PCA: AttributeError: 'numpy.ndarray' object has no attribute 'items'使用 PCA 减少维度:AttributeError:“numpy.ndarray”对象没有属性“items”
【发布时间】:2018-12-03 03:50:43
【问题描述】:

我正在尝试在 DZone (https://dzone.com/articles/cv-r-cvs-retrieval-system-based-on-job-description) 上实施示例项目并遇到问题。在这种情况下,我设置了

dir_pca_we_EWE = 'pickle_model_pca.pkl'

并且正在执行以下操作:

def reduce_dimensions_WE(dir_we_EWE, dir_pca_we_EWE):
    m1 = KeyedVectors.load_word2vec_format('./wiki.en/GoogleNews.bin', binary=True)
    model1 = {}
    # normalize vectors
    for string in m1.wv.vocab:
        model1[string] = m1.wv[string] / np.linalg.norm(m1.wv[string])
    # reduce dimensionality
    pca = decomposition.PCA(n_components=200)
    pca.fit(np.array(list(model1.values())))
    model1 = pca.transform(np.array(list(model1.values())))
    i = 0
    for key, value in model1.items():
        model1[key] = model1[i] / np.linalg.norm(model1[i])
        i = i + 1
    with open(dir_pca_we_EWE, 'wb') as handle:
        pickle.dump(model1, handle, protocol=pickle.HIGHEST_PROTOCOL)
return model1

这会产生以下错误:

Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 12, in reduce_dimensions_WE
AttributeError: 'numpy.ndarray' object has no attribute 'items'

一如既往,非常感谢所有帮助!

【问题讨论】:

  • 您将 PCA 转换结果保存到 model1 变量中。 pca.transform 返回 np.array 而不是 dict
  • 感谢 Andreas 和下面的 datasailor - 我如何更改上面的代码才能成功地将尺寸减小到 200?

标签: python numpy machine-learning pca numpy-ndarray


【解决方案1】:

@datasailor 回答您的问题并告诉您出了什么问题。在 cmets 中,您询问如何将数据维度减少到 200,我认为最简单的方法是使用 sklearn.decomposition.PCA 中的 .fit_transform,而不是您当前使用的 .transform

from sklearn.decomposition import PCA
pca = PCA(n_components=200)
lower_dim_Data=pca.fit_transform(data)

【讨论】:

    【解决方案2】:

    首先将model1 = {} 初始化为空字典。通过在

    中使用transform
    model1 = pca.transform(np.array(list(model1.values())))
    

    变量model1变成了numpy.ndarray,这是pca的transform方法的返回类型。在行中

    for key, value in model1.items():
        ...
    

    你仍然使用model1,就好像它是一个字典一样,它不再是。

    【讨论】:

    • 发完才看到
    • 好的,没关系。只是想阻止窃取答案,因为它可能看起来像:)
    • 感谢 datasailor 和上面的 Andreas - 我该如何更改上面的代码才能成功地将尺寸减小到 200?
    • 通过 pca.transform 方法,您已经执行了缩减。转换后数组的大小为 (n_samples, n_components)。
    猜你喜欢
    • 2020-12-03
    • 2020-11-29
    • 2020-10-06
    • 2018-01-25
    • 2016-06-29
    • 2020-03-25
    • 2013-12-07
    • 2017-10-16
    • 2020-02-23
    相关资源
    最近更新 更多