在 TensorFlow 中使用预训练的词嵌入(word2vec 或 Glove)

Using a pre-trained word embedding (word2vec or Glove) in TensorFlow

我最近回顾了 convolutional text classification 的一个有趣的实现。然而,我审查过的所有 TensorFlow 代码都使用随机(未预训练)嵌入向量,如下所示:

with tf.device('/cpu:0'), tf.name_scope("embedding"):
    W = tf.Variable(
        tf.random_uniform([vocab_size, embedding_size], -1.0, 1.0),
        name="W")
    self.embedded_chars = tf.nn.embedding_lookup(W, self.input_x)
    self.embedded_chars_expanded = tf.expand_dims(self.embedded_chars, -1)

有人知道如何使用 Word2vec 或 GloVe 预训练词嵌入的结果而不是随机词嵌入吗?

您可以通过多种方式在 TensorFlow 中使用预训练嵌入。假设您在一个名为 embedding 的 NumPy 数组中嵌入了 vocab_size 行和 embedding_dim 列,并且您想要创建一个张量 W 可用于致电 tf.nn.embedding_lookup().

  1. 只需将 W 创建为一个 tf.constant(),它的值是 embedding

    W = tf.constant(embedding, name="W")
    

    这是最简单的方法,但内存效率不高,因为 tf.constant() 的值在内存中存储了多次。由于 embedding 可能非常大,您应该只将这种方法用于玩具示例。

  2. 创建 W 作为 tf.Variable 并通过 tf.placeholder():

    从 NumPy 数组初始化它
    W = tf.Variable(tf.constant(0.0, shape=[vocab_size, embedding_dim]),
                    trainable=False, name="W")
    
    embedding_placeholder = tf.placeholder(tf.float32, [vocab_size, embedding_dim])
    embedding_init = W.assign(embedding_placeholder)
    
    # ...
    sess = tf.Session()
    
    sess.run(embedding_init, feed_dict={embedding_placeholder: embedding})
    

    这避免了在图中存储 embedding 的副本,但它确实需要足够的内存来同时在内存中保留矩阵的两个副本(一个用于 NumPy 数组,一个用于 tf.Variable).请注意,我假设您希望在训练期间保持嵌入矩阵不变,因此 W 是使用 trainable=False.

  3. 创建的
  4. 如果嵌入是作为另一个 TensorFlow 模型的一部分进行训练的,您可以使用 tf.train.Saver 从另一个模型的检查点文件加载值。这意味着嵌入矩阵可以完全绕过 Python。按照选项 2 创建 W,然后执行以下操作:

    W = tf.Variable(...)
    
    embedding_saver = tf.train.Saver({"name_of_variable_in_other_model": W})
    
    # ...
    sess = tf.Session()
    embedding_saver.restore(sess, "checkpoint_filename.ckpt")
    

我使用这个方法来加载和共享嵌入。

W = tf.get_variable(name="W", shape=embedding.shape, initializer=tf.constant_initializer(embedding), trainable=False)

@mrry 的回答是不正确的,因为它会导致覆盖每个网络的嵌入权重 运行,因此如果您采用小批量方法训练网络,您将覆盖权重的嵌入。因此,在我看来,预训练嵌入的正确方法是:

embeddings = tf.get_variable("embeddings", shape=[dim1, dim2], initializer=tf.constant_initializer(np.array(embeddings_matrix))

我也面临嵌入问题,所以我用数据集写了详细的教程。 在这里我想补充一下我试过的你也可以试试这个方法,

import tensorflow as tf

tf.reset_default_graph()

input_x=tf.placeholder(tf.int32,shape=[None,None])

#you have to edit shape according to your embedding size


Word_embedding = tf.get_variable(name="W", shape=[400000,100], initializer=tf.constant_initializer(np.array(word_embedding)), trainable=False)
embedding_loopup= tf.nn.embedding_lookup(Word_embedding,input_x)

with tf.Session() as sess:
        sess.run(tf.global_variables_initializer())
        for ii in final_:
            print(sess.run(embedding_loopup,feed_dict={input_x:[ii]}))

这里有详细的工作教程Ipython example如果你想从头开始了解,请看一看。

2.0 Compatible Answer: 有很多Pre-Trained Embeddings,由Google开发,已经开源。

其中一些是 Universal Sentence Encoder (USE), ELMO, BERT,等等。在您的代码中重用它们非常容易。

重用 Pre-Trained EmbeddingUniversal Sentence Encoder 的代码如下所示:

  !pip install "tensorflow_hub>=0.6.0"
  !pip install "tensorflow>=2.0.0"

  import tensorflow as tf
  import tensorflow_hub as hub

  module_url = "https://tfhub.dev/google/universal-sentence-encoder/4"
  embed = hub.KerasLayer(module_url)
  embeddings = embed(["A long sentence.", "single-word",
                      "http://example.com"])
  print(embeddings.shape)  #(3,128)

有关 Google 开发和开源的预训练嵌入的更多信息,请参阅 TF Hub Link

使用 tensorflow 版本 2 如果你使用嵌入层就很容易了

X=tf.keras.layers.Embedding(input_dim=vocab_size,
                            output_dim=300,
                            input_length=Length_of_input_sequences,
                            embeddings_initializer=matrix_of_pretrained_weights
                            )(ur_inp)