报错原因

gensim 4 版本与 gensim3使用方法不同。

解决方法

降低版本(不推荐)

安装gensim3版本

pip install gensim==3.2

按照gensim4的使用方法来用

目的是为了获得某个词的词向量

model = Word2Vec(sentences, min_count=1)

## 原来的代码:出现报错的地方
print(model['sentence'])

## 修改后的代码
print(model.wv['sentence'])

整体代码(用gensim模块训练得到词向量)

from gensim.models import Word2Vec
# define training data
sentences = [['this', 'is', 'the', 'first', 'sentence', 'for', 'word2vec'],
            ['this', 'is', 'the', 'second', 'sentence'],
            ['yet', 'another', 'sentence'],
            ['one', 'more', 'sentence'],
            ['and', 'the', 'final', 'sentence']]
# train model
model = Word2Vec(sentences, min_count=1)
# summarize the loaded model
print(model)
# summarize vocabulary
words = list(model.wv.key_to_index)
print(words)
# access vector for one word
print(model.wv['sentence'])   
# save model
model.save('model.bin')
# load model
new_model = Word2Vec.load('model.bin')
print(new_model)

参考文档

https://github.com/RaRe-Technologies/gensim/wiki/Migrating-from-Gensim-3.x-to-4

Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐