【问题标题】:Using pretrained word2vector model使用预训练的 word2vector 模型
【发布时间】:2020-07-24 06:25:57
【问题描述】:

我正在尝试使用预训练的 word2vector 模型来创建词嵌入,但是当我尝试从 word2vec genism 模型创建权重矩阵时出现以下错误:

代码:

import gensim
w2v_model = gensim.models.KeyedVectors.load_word2vec_format("/content/drive/My Drive/GoogleNews-vectors-negative300.bin.gz", binary=True)

vocab_size = len(tokenizer.word_index) + 1
print(vocab_size)
EMBEDDING_DIM=300
# Function to create weight matrix from word2vec gensim model
def get_weight_matrix(model, vocab):
    # total vocabulary size plus 0 for unknown words
    vocab_size = len(vocab) + 1
    # define weight matrix dimensions with all 0
    weight_matrix = np.zeros((vocab_size, EMBEDDING_DIM))
    # step vocab, store vectors using the Tokenizer's integer mapping
    for word, i in vocab.items():
        weight_matrix[i] = model[word]
    return weight_matrix

embedding_vectors = get_weight_matrix(w2v_model, tokenizer.word_index)

我收到以下错误:

Error

【问题讨论】:

    标签: nlp lstm word2vec


    【解决方案1】:

    注意:最好将完整的错误粘贴为格式化文本而不是文本图像。 (有关原因的完整列表,请参阅Why not upload images of code/errors when asking a question?。)

    但是关于你的问题:

    如果您收到KeyError: word 'didnt' not in vocabulary 错误,您可以相信您请求的单词不在您请求的单词向量集中。 (在这种情况下,Google 训练并在 2012 年左右发布的 GoogleNews 向量。)

    您可以在查找之前检查 - 'didnt' in w2v_model,这将返回 False,然后执行其他操作。或者你可以使用 Python try: ... catch: ... 公式让它发生,但当它发生时再做其他事情。

    但是,如果您提供的 model 没有您希望的词向量,您的代码应该做什么取决于您。

    (注意:GoogleNews 向量确实包含 "didn't" 的向量,with 其内部撇号。因此,在这种情况下,问题可能是您的标记化正在剥离此类internal-punctuation-marks 来自缩写,但 Google 在制作这些向量时选择不这样做。但是您的代码应该准备好在任何情况下处理丢失的单词,除非您确定通过其他永远不会发生的步骤。)

    【讨论】:

      猜你喜欢
      • 2017-08-19
      • 2019-07-12
      • 1970-01-01
      • 2017-08-15
      • 2019-04-10
      • 1970-01-01
      • 2021-07-09
      • 2022-10-19
      • 1970-01-01
      相关资源
      最近更新 更多