加载word2vec时出现UnicodeDecodeError错误

UnicodeDecodeError error when loading word2vec

完整描述

我开始使用词嵌入并找到了大量关于它的信息。我明白,到目前为止,我可以训练自己的词向量或使用以前训练过的词向量,例如 Google 或维基百科的,它们适用于英语,但对我没有用,因为我使用 巴西葡萄牙语 的文本。因此,我继续寻找预训练的葡萄牙语词向量,最终找到 Hirosan's List of Pretrained Word Embeddings which led me to Kyubyong's WordVectors from which I learned about Rami Al-Rfou's Polyglot。两者都下载后,我一直在尝试简单地加载词向量,但没有成功。

简短说明

我无法加载预训练词向量;我正在尝试 WordVectors and Polyglot

下载量

加载尝试

圭炳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)

错误 returned:

[...]
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 还包含其他文件,但所有文件都 return 类似错误。

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'))

错误 returned:

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)

错误 returned:

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。

解决方案

圭炳WordVectors 正如所指出的,加载Kyubyong模型的正确方法是调用Word2Vec的原生加载函数。

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

尽管我非常感谢 Aneesh Joshi 解决方案,但多语言似乎是使用葡萄牙语工作的更好模型。关于那个有什么想法吗?

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

"load the model with load(). Not load_word2vec_format (that's for the C-tool compatibility)."

model = Word2Vec.load(fname)

如果可行,请告诉我。

参考:Gensim mailing list