首页 > 解决方案 > 使用带有 Gensim 的西班牙预训练模型会导致引发 KeyError("word '%s' not in words" % word)

问题描述

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

我下载了一个预训练西班牙语单词嵌入模型(超过 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)的“<strong>深度学习食谱”中使用的代码相同

这是完整的脚本:

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_ESP\embeddings-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))

感谢您的支持

标签: pythondeep-learninggensimword-embeddingkeyerror

解决方案


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

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

print(model['Berlín'])

...这可能会显示相同的错误。

如果您认为您“已经检查过该词实际上是否在词嵌入中”,请编辑您的问题以在代码和输出中显示您执行的检查,以验证其存在。

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

model.index2entity[:10]

...或通过...查找该单词列表中的位置...

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

但是,对于一个 word-not-present,你会得到一个ValueError.

我确实注意到您用西班牙语字母í( i-acute ) 引用了这个词,而不是其他字母表中使用的普通点 ii字母。

根据词向量的构造方式,该词可能以非重音形式 ( 'Berlin') 或大小写扁平形式 ( 'berlín') 或两者兼而有之 ( 'berlin') 或根本不可用。

如果根本没有,那么您需要在尝试在类比解决代码中使用它之前检查它的可用性,或者设置一个try: ... except: ...错误捕获构造来处理出现的错误。


推荐阅读