使用PCA缩小尺寸:AttributeError:'numpy.ndarray'对象没有属性'items'

时间:2018-06-24 09:50:16

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

我正在尝试在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'

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

2 个答案:

答案 0 :(得分:1)

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

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

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

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

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

答案 1 :(得分:0)

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

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