正如最近的语言建模论文所建议的那样,我想在我的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)
logits计算如下:
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?reuse=True
。答案 0 :(得分:1)
我已经弄清楚如何正确实施重量分配:
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")