【发布时间】:2019-08-09 02:06:42
【问题描述】:
我尝试使用 Gensim 导入 GoogelNews 预训练模型的一些英文单词(这里抽样 15 个仅存储在一个 txt 文件中,每行每行,并且没有更多的上下文作为语料库)。然后我可以使用“model.most_similar()”为他们获取相似的单词/短语。但实际上从 Python-Pickle 方法加载的文件不能直接用于 gensim 内置的 model.load() 和 model.most_similar() 函数。
由于我无法从一开始就训练、保存和加载模型,我应该如何对 15 个英文单词(以及未来更多)进行聚类?
import gensim
from gensim.models import Word2Vec
from gensim.models.keyedvectors import KeyedVectors
GOOGLE_WORD2VEC_MODEL = '../GoogleNews-vectors-negative300.bin'
GOOGLE_ENGLISH_WORD_PATH = '../testwords.txt'
GOOGLE_WORD_FEATURE = '../word.google.vector'
model = gensim.models.KeyedVectors.load_word2vec_format(GOOGLE_WORD2VEC_MODEL, binary=True)
word_vectors = {}
#load 15 words as a test to word_vectors
with open(GOOGLE_ENGLISH_WORD_PATH) as f:
lines = f.readlines()
for line in lines:
line = line.strip('\n')
if line:
word = line
print(line)
word_vectors[word]=None
try:
import cPickle
except :
import _pickle as cPickle
def save_model(clf,modelpath):
with open(modelpath, 'wb') as f:
cPickle.dump(clf, f)
def load_model(modelpath):
try:
with open(modelpath, 'rb') as f:
rf = cPickle.load(f)
return rf
except Exception as e:
return None
for word in word_vectors:
try:
v= model[word]
word_vectors[word] = v
except:
pass
save_model(word_vectors,GOOGLE_WORD_FEATURE)
words_set = load_model(GOOGLE_WORD_FEATURE)
words_set.most_similar("knit", topn=3)
---------------error message-------- AttributeError Traceback (most recent call last) <ipython-input-8-86c15e366696> in <module> ----> 1 words_set.most_similar("knit", topn=3) AttributeError: 'dict' object has no attribute 'most_similar' ---------------error message--------
【问题讨论】: