【问题标题】:How to use pretrained Word2Vec model in Tensorflow如何在 Tensorflow 中使用预训练的 Word2Vec 模型
【发布时间】:2023-03-17 05:57:01
【问题描述】:

我有一个在Gensim 中训练的Word2Vec 模型。我如何在Tensorflow 中为Word Embeddings 使用它。我不想在 Tensorflow 中从头开始训练嵌入。有人能告诉我如何用一些示例代码来做吗?

【问题讨论】:

    标签: python tensorflow gensim word2vec word-embedding


    【解决方案1】:

    假设您有一个字典和 inverse_dict 列表,列表中的索引对应于最常用的单词:

    vocab = {'hello': 0, 'world': 2, 'neural':1, 'networks':3}
    inv_dict = ['hello', 'neural', 'world', 'networks']
    

    注意 inverse_dict 索引如何对应字典值。现在声明您的嵌入矩阵并获取值:

    vocab_size = len(inv_dict)
    emb_size = 300 # or whatever the size of your embeddings
    embeddings = np.zeroes((vocab_size, emb_size))
    
    from gensim.models.keyedvectors import KeyedVectors                         
    model = KeyedVectors.load_word2vec_format('embeddings_file', binary=True)
    
    for k, v in vocab.items():
      embeddings[v] = model[k]
    

    您已经获得了嵌入矩阵。好的。现在让我们假设您要在样本上进行训练:x = ['hello', 'world']。但这不适用于我们的神经网络。我们需要整数化:

    x_train = []
    for word in x:  
      x_train.append(vocab[word]) # integerize
    x_train = np.array(x_train) # make into numpy array
    

    现在我们可以即时嵌入我们的样本了

    x_model = tf.placeholder(tf.int32, shape=[None, input_size])
    with tf.device("/cpu:0"):
      embedded_x = tf.nn.embedding_lookup(embeddings, x_model)
    

    现在embedded_x 进入您的卷积或其他任何内容。我还假设您没有重新训练嵌入,而只是使用它们。希望对你有帮助

    【讨论】:

    • 我很确定 embeddings[v] = model[k] 应该替换为 embeddings[v] = model.word_vec(k)
    • 我也想到了这种更手动的方法(即迭代整个词汇表并使用model.word_vec(k)逐个查找它们。但是有没有办法使用tf.nn.embedding_lookup,看起来会更有效率吗?一篇使用 GloVe guillaumegenthial.github.io/… 的 Tensorflow 的帖子基本上生成了一个自定义 GloVe 文件,可用于执行直接索引到嵌入查找。我想知道是否可以对 Word2Vec(二进制)文件做类似的事情。
    • @JIXIang 在实践中,您可以从 Word2Vec 中获取所有想要的单词,并将其保存在 numpy 数组、pickle 或其他任何东西中。每次从 Gensim 加载 word2vec 都非常昂贵。 tf.nn.embedding_lookup 需要一个矩阵,因此您不能即时使用 model.word_vec(k)。而tf 效率更高。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-08-09
    • 2019-07-12
    • 1970-01-01
    • 2018-09-02
    • 1970-01-01
    相关资源
    最近更新 更多