SpaCy:如何加载Google新闻word2vec向量?

贾斯珀:

我尝试了几种加载Google新闻word2vec向量(https://code.google.com/archive/p/word2vec/)的方法:

en_nlp = spacy.load('en',vector=False)
en_nlp.vocab.load_vectors_from_bin_loc('GoogleNews-vectors-negative300.bin')

上面给出:

MemoryError: Error assigning 18446744072820359357 bytes

我也尝试过使用.gz压缩向量;或通过将它们与gensim一起加载并保存为新格式:

from gensim.models.word2vec import Word2Vec
model = Word2Vec.load_word2vec_format('GoogleNews-vectors-negative300.bin', binary=True)
model.save_word2vec_format('googlenews2.txt')

然后,此文件在每行上包含单词及其单词向量。我试图用它们加载:

en_nlp.vocab.load_vectors('googlenews2.txt')

但它返回“ 0”。

正确的方法是什么?

更新:

我可以将自己创建的文件加载到spacy中。我在每行上使用带有“字符串0.0 0.0 ....”的test.txt文件。然后使用.bzip2将这个txt压缩到test.txt.bz2。然后,我创建一个spacy兼容的二进制文件:

spacy.vocab.write_binary_vectors('test.txt.bz2', 'test.bin')

我可以载入spacy:

nlp.vocab.load_vectors_from_bin_loc('test.bin')

这可行!但是,当我对googlenews2.txt执行相同的过程时,出现以下错误:

lib/python3.6/site-packages/spacy/cfile.pyx in spacy.cfile.CFile.read_into (spacy/cfile.cpp:1279)()

OSError: 
贾斯珀:

对于spacy 1.x,请将Google新闻矢量加载到gensim中并转换为新格式(.txt中的每一行都包含一个矢量:string,vec):

from gensim.models.word2vec import Word2Vec
from gensim.models import KeyedVectors
model = KeyedVectors.load_word2vec_format('GoogleNews-vectors-negative300.bin', binary=True)
model.wv.save_word2vec_format('googlenews.txt')

删除.txt的第一行:

tail -n +2 googlenews.txt > googlenews.new && mv -f googlenews.new googlenews.txt

将txt压缩为.bz2:

bzip2 googlenews.txt

创建与SpaCy兼容的二进制文件:

spacy.vocab.write_binary_vectors('googlenews.txt.bz2','googlenews.bin')

将googlenews.bin移至python环境的/lib/python/site-packages/spacy/data/en_google-1.0.0/vocab/googlenews.bin。

然后加载单词向量:

import spacy
nlp = spacy.load('en',vectors='en_google')

或稍后再加载它们:

nlp.vocab.load_vectors_from_bin_loc('googlenews.bin')

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章