tensorflow world language model

时间:2023-03-10 04:26:08
tensorflow world language model

上文提到了pytorch里的world language model,那么怎么能不说tensorflow的实现呢,还是以tensorflow ptb的代码为例说说。

地址:

https://github.com/tensorflow/models/tree/master/tutorials/rnn/ptb

大概处理流程是,一大段文章,然后转成ids,然后根据batchsize切割成。batchsize * M

num_steps是一个sequence的长度

epoch_size 就是进行多少轮训练,算法就是一个batch内文本的长度,除以sequence的长度。一个文本都切成多少个sequence就训练多少轮。

用strided_slice切割也很有意思,接受两个参数,第一个参数是左上角的点,第二个参数是右下角的点,你感受下下面是怎么切割,的横坐标不变,永远是一个batchsize,然后纵坐标开始从左到右开始切割。非常直观。

epoch_size = (batch_len - 1) // num_steps

i = tf.train.range_input_producer(epoch_size, shuffle=False).dequeue()
x = tf.strided_slice(data, [0, i * num_steps],
[batch_size, (i + 1) * num_steps])
x.set_shape([batch_size, num_steps])
y = tf.strided_slice(data, [0, i * num_steps + 1],
[batch_size, (i + 1) * num_steps + 1])
y.set_shape([batch_size, num_steps])
return x, y

训练的代码也比较直观

inputs = tf.nn.embedding_lookup(embedding, input_.input_data)

input_data的维度是batchsize * sequence,进行embding_lookup之后就是

batchsize * sequence*embsize

因为sequence上每一个词都有一个embding结果(每个词都去查表了)

下面的代码是核心:

对于num_steps也就是sequence上每一个词,进行循环。每一个time_step取出一个batchsize *embsize 和一个hidden作为输入,

然后输出一个batchsize *embsize 和一个hidden,这里把每一个时刻的输出都存到一个outputs 数组里面。所有outputs 的维度应该是:sequence*batchsize *embsize。

outputs = []
state = self._initial_state
with tf.variable_scope("RNN"):
for time_step in range(num_steps):
if time_step > 0: tf.get_variable_scope().reuse_variables()
(cell_output, state) = cell(inputs[:, time_step, :], state)
outputs.append(cell_output)

这边把outputs进行一个变换,变成output的维度是value *embsize二维矩阵 。其中value长度等于sequence*batchsize。

在有了output之后,就可以根据wx+b生成一个logits,最后根据这个logits去和这个target进行求loss,很显然,这个logits的维度是

value*vocabsize 。这里很坑爹。logits的第一维度是sequence*batchsize的乘积,我们用起来就不是很爽了,所以如果你想拿某个词的具体的logit的话,可以固定batchsize =1

output = tf.reshape(tf.stack(axis=1, values=outputs), [-1, size])

softmax_w = tf.get_variable(
"softmax_w", [size, vocab_size], dtype=data_type())
softmax_b = tf.get_variable("softmax_b", [vocab_size], dtype=data_type())
logits = tf.matmul(output, softmax_w) + softmax_b
loss = tf.contrib.legacy_seq2seq.sequence_loss_by_example(
[logits],
[tf.reshape(input_.targets, [-1])],
[tf.ones([batch_size * num_steps], dtype=data_type())])
self._cost = cost = tf.reduce_sum(loss) / batch_size
self._final_state = state