AttributeError The vocab attribute was removed from KeyedVector in Gensim 400Use KeyedVectors key_to_index dict index_to_key list and methods get_vecattrkey attr and set_vecattrkey attr new_val instea
该报错提示在 Gensim 4.0.0 中,KeyedVector 类的 vocab 属性被移除了,需要使用 .key_to_index 和 .index_to_key 属性,以及 .get_vecattr() 和 .set_vecattr() 方法来替代。如果要查询某个词是否在模型中,可以使用以下代码:
if 'word' in model.wv.key_to_index:
print('Word is in the model.')
else:
print('Word is not in the model.')
为了得到词的相似度,可以使用 model.wv.similarity(w1, w2) 方法,其中 w1 和 w2 分别是两个词。例如:
similarity = model.wv.similarity('dog', 'cat')
print('Similarity between "dog" and "cat":', similarity)
要添加属性或词向量,可以使用 model.wv.get_vecattr() 和 model.wv.set_vecattr() 方法。例如,要为词 'dog' 添加一个名为 'color' 的属性,并将其值设置为 'brown',可以使用以下代码:
model.wv.set_vecattr('dog', 'color', 'brown')
color = model.wv.get_vecattr('dog', 'color')
print('Color of "dog":', color)
注意,添加属性只对当前实例有效,而不会在保存模型时被保存。如果要在保存模型时保存属性,请使用 KeyedVectors.add_vectors() 方法将属性向量添加到模型中
原文地址: http://www.cveoy.top/t/topic/fH1O 著作权归作者所有。请勿转载和采集!