代码之家  ›  专栏  ›  技术社区  ›  Lemon

tensorflow中的语言建模-如何将嵌入和softmax权重联系起来

  •  0
  • Lemon  · 技术社区  · 7 年前

    正如最近的语言建模论文所建议的那样,我想在我的RNN语言模型中使用权重绑定。也就是说,我想在嵌入层和softmax层之间共享权重。然而,我不确定如何在TensorFlow中实现这一点。

    我的网络接收形状输入 (batch_size, sequence_length) . 嵌入矩阵具有形状 (vocab_size, embedding_size) 创建如下(我使用预先训练好的word2vec嵌入):

            with tf.variable_scope('embedding'):
                self.embedding_matrix = tf.Variable(tf.constant(0.0, shape=[self.vocab_size, self.embd_size]), trainable=False, name='embedding')
                self.embed_placeholder = tf.placeholder(tf.float32, [self.vocab_size, self.embd_size])
                self.embed_init = self.embedding_matrix.assign(self.embed_placeholder)
    

    对数计算如下:

                output, self.final_state = tf.nn.dynamic_rnn(
                    cell,
                    inputs=self.inputs,
                    initial_state=self.init_state)
    
                self.output_flat = tf.reshape(output, [-1, cell.output_size])
                softmax_w = tf.get_variable("softmax_w", [self.n_hidden, self.vocab_size], dtype=tf.float32)
    
                softmax_b = tf.get_variable("softmax_b", [self.vocab_size], dtype=tf.float32)
                logits = tf.nn.xw_plus_b(self.output_flat, softmax_w, softmax_b)
                # Reshape logits to be a 3-D tensor
                self.logits = tf.reshape(logits, [self.batch_size, self.seq_length, self.vocab_size])
    

    我的问题是:

    1. 必须更改为使用嵌入权重的矩阵为 softmax_w 对的
    2. softmax\u w (n_hidden, vocab_size) . 这与嵌入矩阵的大小有什么关系?还是我必须确保n\u hidden=嵌入大小?
    3. reuse=True 在variable_范围内。
    1 回复  |  直到 7 年前
        1
  •  1
  •   Lemon    7 年前

    我已经找到了如何正确实现权重共享的方法:

            with tf.variable_scope('embedding'):
                self.embedding_matrix = tf.get_variable( "embedding", shape=[self.vocab_size, self.n_hidden], dtype=tf.float32, initializer=self.initializer)
    
                [...]
    
                # tie input embedding weights to output embedding weights
                with tf.variable_scope("embedding", reuse=True):
                    self.softmax_w = tf.transpose(tf.get_variable('embedding'))
    
                # Set output bias vector to zero as outlined paper
                softmax_b = tf.zeros(shape=[self.vocab_size], dtype=tf.float32, name="softmax_b")
    
    推荐文章