• 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

  • 相关阅读:
    ‘==’运算符和equals方法的区别
    ‘==’与equals的使用
    重写equals()方法的原则
    三目运算符---自动转换数据类型
    Spring安全框架——细粒度权限控制实现步骤
    Http协议学习笔记---Http协议介绍、协议格式、响应码说明
    Xml&Tomcat学习笔记03-----javaweb介绍、Tomcat介绍和使用
    Xml&Tomcat学习笔记02-----IDEA配置TomCat服务器
    Xml&Tomcat学习笔记01-----XML简介、语法、元素、属性、dom4j
    MVC概念
  • 原文地址:https://www.cnblogs.com/dmesg/p/6882579.html
Copyright © 2020-2023  润新知