上文提到了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

最新文章

  1. Python中使用递归输出嵌套列表并转化为大写
  2. 咱们来聊聊JS中的异步,以及如何异步,菜鸟版
  3. django 操作 下载 excel xls xlsx csv
  4. 删除ubuntu旧版本内核
  5. 正确理解DTO、值对象和POCO
  6. HDU2227Find the nondecreasing subsequences(树状数组+DP)
  7. 树链剖分||dfs序 各种题
  8. Java开发中文件读取方式总结
  9. webservice 发布到外网的时候
  10. JS~字符串长度判断,超出进行自动截取(支持中文)
  11. Spring+SpringMVC+MyBatis深入学习及搭建(十)——MyBatis逆向工程
  12. 深入Redis持久化
  13. 【拓扑排序】烦人的幻灯片(slides)
  14. 并发编程---死锁||递归锁---信号量---Event事件---定时器
  15. ORACLE环境变量定义.md
  16. matlab运行中出现“Caught "std::exception" Exception message is: Message Catalog MATLAB:builtins was not loaded from the file."
  17. 解决 div 设为 inline-block 后标题不对齐
  18. 常用CSS备忘
  19. 远程访问Centos6.5上的mysql或者mariadb(navicat)
  20. python数据分析的工具环境

热门文章

  1. SpringBoot2.0整合mybatis、shiro、redis实现基于数据库权限管理系统
  2. Spring 学习教程(三):Spring MVC
  3. javaweb(2)之Servlet入门
  4. python if 和 else
  5. 从零开始一起学习SLAM | 理解图优化,一步步带你看懂g2o代码
  6. centos7中安装、配置jdk(转载)
  7. 重写select样式
  8. window中普通用户无法登录远程桌面
  9. web前端学习历程--排序
  10. Openstack-Namespaces