簡體   English   中英

使用帶有 Gensim 的西班牙預訓練 model 導致引發 KeyError(“單詞'%s'不在詞匯表中”% word)

[英]using a Spanish pretrained model with Gensim causes raise KeyError(“word '%s' not in vocabulary” % word)

我正在努力解決以下問題:

我下載了一個用於西班牙語預訓練詞嵌入 model (超過 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_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))

感謝您的支持

如果你得到一個像KeyError: "word 'Berlín' not in vocabulary"這樣的錯誤,那么你可以相信這個錯誤:這個詞真的不在詞匯表中。 (這不是因為沒有在列表中指定它。)

您可以通過以下代碼直接檢查...

print(model['Berlín'])

...這可能會顯示相同的錯誤。

如果您認為您“已經檢查過該詞實際上是否在詞嵌入中”,請編輯您的問題以顯示您在代碼和 output 中執行的檢查,以驗證其存在。

您可以在列表model.index2entity內的 model 中查看實際的單詞。 例如,您可以通過以下方式顯示 model 中的前 10 個字:

model.index2entity[:10]

...或通過...在單詞列表中查找 position

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

但是,對於不存在的單詞,您會得到一個ValueError

我確實注意到您用西班牙語字母í ( i-acute ) 引用了這個詞,而不是在其他字母表中使用的普通點 i i字母。

根據詞向量的構造方式,該詞可能以去重音形式( 'Berlin' )或大小寫扁平形式( 'berlín' )或兩者( 'berlin' )可用,或者不在全部。

如果根本沒有,那么您需要在嘗試在類比解決代碼中使用它之前檢查它的可用性,或者設置一個try: ... except: ...錯誤捕獲構造來處理錯誤過來。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM