使用带有Gensim的西班牙语预训练模型会导致引发KeyError("word '%s' not in vocabulary"%字)



我正在努力解决以下问题:

我为西班牙语下载了一个预训练的单词嵌入模型(西班牙语超过100万个单词300维单词向量(我成功地加载了它,我甚至成功地进行了几个实验,比如西班牙语中最相似的单词和基本的类比(a对B的意思,C对什么的意思(,但当我尝试以下内容时:

for pais in 'Italia', 'Francia', 'India', 'China':
print(' is the capital of '  
(A_is_to_B_as_C_is_to('Alemania','Berlín',pais),pais))

它引发了错误:

KeyError: "word 'Berlín' not in vocabulary"

我已经检查了单词是否真的在单词嵌入中。我还排除了编码错误的可能性。

根据我的研究,这种类型的错误是在令牌/单词应该包装在列表[]中时产生的,但我不知道如何将其应用于这个特定的问题。此外,该代码块与第3章(Word2vecMath(中">深度学习食谱"中使用的代码相同

这是完整的脚本:

import os
from keras.utils import get_file
import gensim
from gensim.models.keyedvectors import KeyedVectors
import subprocess
import numpy as np
import matplotlib.pyplot as plt
from IPython.core.pylabtools import figsize

from sklearn.manifold import TSNE
import json
from collections import Counter
from itertools import chain
from keras.models import load_model
path = ("D:Pretrained_wordEmbeddings_ESPembeddings-l-model.vec")

model = gensim.models.KeyedVectors.load_word2vec_format(path, binary=False)

data=model.most_similar(positive=["muerte"])
print(data[:])

def A_is_to_B_as_C_is_to(a, b, c, topn=1):
a, b, c = map(lambda x:x if type(x) == list else [x], (a, b, c))
res = model.most_similar(positive=b + c, negative=a, topn=topn)
if len(res):
if topn == 1:
return res[0][0]
return [x[0] for x in res]
return None
A_is_to_B_as_C_is_to('hombre', 'mujer', 'rey')
## for pais in 'Italia', 'Francia', 'India', 'China':
##    print(' is the capital of '  
##          (A_is_to_B_as_C_is_to('Alemania', 'Berlín', pais), pais))

感谢您对的支持

如果你遇到像KeyError: "word 'Berlín' not in vocabulary"这样的错误,那么你可以相信这个错误:这个词真的不在词汇表中。(这并不是因为没有在列表中指定。(

您可以通过以下代码直接检查。。。

print(model['Berlín'])

其将可能显示相同的错误。

如果你认为你"已经检查了单词是否真的在单词嵌入中",请编辑你的问题,显示你在代码和输出中执行的检查,以验证它的存在。

您可以在列表model.index2entity中查看模型中的实际单词。例如,您可以通过以下方式显示模型中的前10个单词:

model.index2entity[:10]

或者通过…查找单词列表中的位置。。。

model.index2entity.index('Berlín')

但是,对于一个不存在的单词,你会得到一个ValueError

我注意到你引用的单词是西班牙语字母í(I-acute(,而不是其他字母中使用的普通点-Ii字母。

根据单词向量的构造方式,单词可能有去重音形式('Berlin'(、大小写扁平形式('berlín'(或两者都有('berlin'(,或者根本没有。

如果根本没有,那么在尝试将其用于模拟求解代码之前,您应该检查其可用性,或者设置try: ... except: ...错误捕获构造来处理任何出现的错误。

最新更新