tensorflow中的语言建模-如何结合嵌入和softmax权重

tensorflow中的语言建模-如何结合嵌入和softmax权重,tensorflow,nlp,language-model,Tensorflow,Nlp,Language Model,正如最近的语言建模论文所建议的,我想在我的RNN语言模型中使用权重绑定。也就是说,我想在嵌入层和softmax层之间共享权重。然而,我不确定如何在TensorFlow中实现这一点 我的网络接收形状(批次大小、序列长度)的输入。嵌入矩阵具有shape(vocab\u size,embedding\u size),并按如下方式创建(我使用预先训练好的word2vec嵌入): Logit的计算如下所示: output, self.final_state = tf.nn.dyna

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

我的网络接收形状
(批次大小、序列长度)
的输入。嵌入矩阵具有shape
(vocab\u size,embedding\u size)
,并按如下方式创建(我使用预先训练好的word2vec嵌入):

Logit的计算如下所示:

            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])
我的问题是:

  • 必须更改为使用嵌入权重的矩阵是
    softmax\u w
    ,对吗
  • softmax\u w
    具有形状
    (n\u隐藏,声音大小)
    。这与嵌入矩阵的大小有什么关系?或者我必须确保n_hidden=嵌入大小
  • 如何在TensorFlow中重用嵌入权重?我知道我必须在变量范围内使用
    reuse=True

  • 我已经找到了如何正确实施权重分配的方法:

            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")
    

    当你想在一个模型中使用一个网络两次时,你知道作为一个函数该怎么做吗?
            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")