正如最近的语言建模论文所建议的那样,我想在我的 RNN 语言模型中使用权重绑定。也就是说,我想在嵌入层和 softmax 层之间共享权重。但是,我不确定如何在 TensorFlow 中做到这一点。
我的网络接收 shape 的输入(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])
我的问题是:
- 必须更改为使用嵌入权重的矩阵是
softmax_w
,对吗? softmax_w
有形状(n_hidden, vocab_size)
。这如何适合嵌入矩阵的大小?还是我必须确保 n_hidden = embedding_size?- 如何在 TensorFlow 中重用嵌入权重?我知道我必须
reuse=True
在 variable_scope 中使用。