Word2vec 保存的模型不是 UTF-8 编码的,但是输入到 Word2vec 模型的句子是 UTF-8 编码的

Word2vec saved model is not UTF-8 encoded but the sentence input to the Word2vec model is UTF-8 encoded

我使用 gensim 包训练了一个 word2vec 模型,并用以下名称保存了它。

model_name = "300features_1minwords_10context"
model.save(model_name)

我得到了这些日志消息信息。正在对模型进行训练和保存。

INFO : not storing attribute syn0norm
INFO : not storing attribute cum_table

然后,我尝试使用它加载模型,

from gensim.models import Word2Vec
model = Word2Vec.load("300features_1minwords_10context")

我收到以下错误。

2017-06-22 21:27:14,975 : INFO : loading Word2Vec object from 300features_1minwords_10context
2017-06-22 21:27:15,496 : INFO : loading wv recursively from 300features_1minwords_10context.wv.* with mmap=None
2017-06-22 21:27:15,497 : INFO : setting ignored attribute syn0norm to None
2017-06-22 21:27:15,498 : INFO : setting ignored attribute cum_table to None
2017-06-22 21:27:15,499 : INFO : loaded 300features_1minwords_10context
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-25-9d90db0f07c0> in <module>()
      1 from gensim.models import Word2Vec
      2 model = Word2Vec.load("300features_1minwords_10context")
----> 3 model.syn0.shape

AttributeError: 'Word2Vec' object has no attribute 'syn0'

此外,在文件“300features_1minwords_10context”中,显示

"300features_1minwords_10context" is not UTF-8 encoded
Saving disabled.
Open console for more details 

为了修复上述属性错误,我还尝试了 google 论坛中的以下内容,

import gensim
model = gensim.models.KeyedVectors.load_word2vec_format("300features_1minwords_10context")
model.syn0.shape

它导致了另一个错误,即

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

该模型是用 UTF-8 编码的句子训练的。我不确定为什么会抛出此错误?

更多信息:

df = pd.read_csv('UNSPSCdataset.csv',encoding='mac_roman',low_memory=False)
features = ['MaterialDescription']
temp_features = df[features]
temp_features.to_csv('materialDescription', encoding='UTF-8')
X = pd.read_csv('materialDescription',encoding='UTF-8')

在这里,我必须使用 'mac_roman' 编码才能使用 pandas 数据帧访问它。由于在训练模型时数据框中的文本必须采用 UTF-8 格式,因此我通过使用 UTF-8 编码将该特定特征保存在单独的 csv 文件中,之后,我访问了该特定列。

任何帮助都是可观的

您使用的是最新的gensim吗?如果没有,请务必尝试 - 旧版本中有时会出现 save()/load() 错误。

INFO "not storing" 日志行是正常的——它们并不表示有任何问题(因此可以从您的问题中删除。)

您是否直接在 load() 上收到 "has no attribute" 错误? (这里的完整错误堆栈会很有用,并澄清这一点。)


更新: 从现在显示的错误堆栈中,错误是 而不是 发生在 load() 行中,但是在下一行中,当您尝试访问 model.syn0.shape 时。最新版本的 gensim 不再有 syn0 作为 Word2Vec class 对象的 属性 – 该信息被移动到组成 KeyedVectors 对象,在 wv 属性。因此 model.wv.syn0.shape 很可能会无误地访问您正在寻找的内容。


当您的模型较大时,save() 可以为模型的大型数组属性(如 syn0)生成多个带有额外扩展名的文件。这些文件必须与要重新load()编辑的模型的主文件名一起保存。是否有可能您已将 300features_1minwords_10context 文件而不是任何此类随附文件移动到 load() 不完整的新位置?

你不能 load_word2vec_format() 一个 native-gensim save()d 的文件——它们完全不同的格式,所以编码错误只是试图读取二进制文件的产物 Python pickle 文件(来自 save())完全作为另一种格式。