如何为预训练的 Glove 词嵌入处理看不见的词以避免 keyerror?

How to handle unseen words for pre-trained Glove word-embedding to avoid keyerror?

我想从预训练的 Glove 嵌入中提取特征。但是我遇到了某些单词的 Keyerror。这是单词标记的列表。

words1=['nuclear','described', 'according', 'called','physics', 'account','interesting','holes','theoretical','like','space','radiation','property','impulsed','darkfield']

我从 'impulsed'、'darkfield' 个词中得到了 Keyerror,因为这些词可能是看不见的。我怎样才能避免这个错误? .

这是我的完整代码:

gloveFile = "glove.6B.50d.txt"
import numpy as np
def loadGloveModel(gloveFile):
    print ("Loading Glove Model")
    with open(gloveFile, encoding="utf8" ) as f:
        content = f.readlines()
    model = {}
    for line in content:
        splitLine = line.split()
        word = splitLine[0]
        embedding = np.array([float(val) for val in splitLine[1:]])
        model[word] = embedding
    print ("Done.",len(model)," words loaded!")
    return model

model = loadGloveModel(gloveFile)

words1=['nuclear','described', 'according', 'called','physics', 'account','interesting','holes','theoretical','like','space','radiation','property','impulsed','darkfield']

import numpy as np
vector_2 = np.mean([model[word] for word in words1],axis=0) ## Got error message

'impulsed' 个词

的错误消息

有什么办法可以跳过这些看不见的词吗?

我会在下面提出建议

  • 分配给某个唯一向量的所有缺失词(比如全零)
  • 找到与其相似的词并使用它们的嵌入:
    • 尝试单词的 ngrams(前缀或后缀)并检查它是否在词汇表中
    • 词干并检查它是否在词汇表中
  • 最简单的解决方案:使用 FastText。它从子词 n-grams 中组装词向量,这使得它能够处理词汇表之外的词。