加载word2vec时出现UnicodeDecodeError错误

时间:2018-05-28 20:25:36

标签: python word2vec gensim python-unicode polyglot

完整说明

我开始使用word嵌入,并找到了大量有关它的信息。我理解,到目前为止,我可以训练自己的单词向量或使用以前训练过的单词向量,例如谷歌或维基百科,它们可用于英语并且对我没用,因为我正在处理巴西葡萄牙语。因此,我用葡萄牙语寻找预先训练过的单词向量,最后我找到了Hirosan's List of Pretrained Word Embeddings,这使我找到了Kyubyong的WordVectors,我从中了解了Rami Al-Rfou的Polyglot。下载两者之后,我一直试图简单地加载单词向量。

简短说明

我无法加载预先训练过的单词向量;我正在尝试WordVectorsPolyglot

下载

加载尝试次数

Kyubyong的WordVectors 第一次尝试:使用Hirosan建议的Gensim;

from gensim.models import KeyedVectors
kyu_path = '.../pre-trained_word_vectors/kyubyong_pt/pt.bin'
word_vectors = KeyedVectors.load_word2vec_format(kyu_path, binary=True)

错误返回:

[...]
File "/Users/luisflavio/anaconda3/lib/python3.6/site-packages/gensim/utils.py", line 359, in any2unicode
return unicode(text, encoding, errors=errors)

UnicodeDecodeError: 'utf-8' codec can't decode byte 0x80 in position 0: invalid start byte

下载的zip文件还包含其他文件,但所有文件都返回类似的错误。

Polyglot 第一次尝试:跟随Al-Rfous's instructions;

import pickle
import numpy
pol_path = '.../pre-trained_word_vectors/polyglot/polyglot-pt.pkl'
words, embeddings = pickle.load(open(pol_path, 'rb'))

错误返回:

File "/Users/luisflavio/Desktop/Python/w2v_loading_tries.py", line 14, in <module>
    words, embeddings = pickle.load(open(polyglot_path, "rb"))

UnicodeDecodeError: 'ascii' codec can't decode byte 0xd4 in position 1: ordinal not in range(128)

第二次尝试:使用Polyglot's word embedding load function;

首先,我们必须通过pip安装polyglot:

pip install polyglot

现在我们可以导入它了:

from polyglot.mapping import Embedding
pol_path = '.../pre-trained_word_vectors/polyglot/polyglot-pt.pkl'
embeddings = Embedding.load(polyglot_path)

错误返回:

File "/Users/luisflavio/anaconda3/lib/python3.6/codecs.py", line 321, in decode
(result, consumed) = self._buffer_decode(data, self.errors, final)

UnicodeDecodeError: 'utf-8' codec can't decode byte 0x80 in position 0: invalid start byte

额外信息

我在MacOS High Sierra上使用python 3.

解决方案

Kyubyong的WordVectors 正如Aneesh Joshi所指出的,加载Kyubyong模型的正确方法是调用Word2Vec的本机加载函数。

from gensim.models import Word2Vec
kyu_path = '.../pre-trained_word_vectors/kyubyong_pt/pt.bin'
model = Word2Vec.load(kyu_path)

尽管我对Aneesh Joshi解决方案非常感激,但多语言似乎是与葡萄牙语合作的更好模式。关于那个的任何想法?

1 个答案:

答案 0 :(得分:1)

对于Kyubyong预先训练过的word2vector .bin文件: 它可能是使用gensim的保存功能保存的。

&#34;使用load()加载模型。不是load_word2vec_format(对于C工具兼容性而言)。&#34;

即,model = Word2Vec.load(fname)

如果有效,请告诉我。

参考:Gensim mailing list

相关问题