Control flow operations: conditionals and loops

When building complex models such as recurrent neural networks you may need to control the flow of operations through conditionals and loops. In this section we introduce a number of commonly used control flow ops.

Let’s assume you want to decide whether to multiply to or add two given tensors based on a predicate. This can be simply implemented with tf.cond which acts as a python “if” function:

a = tf.constant(1)
b = tf.constant(2) p = tf.constant(True) x = tf.cond(p, lambda: a + b, lambda: a * b) print(tf.Session().run(x))

Since the predicate is True in this case, the output would be the result of the addition, which is 3.

Most of the times when using TensorFlow you are using large tensors and want to perform operations in batch. A related conditional operation is tf.where, which like tf.cond takes a predicate, but selects the output based on the condition in batch.

a = tf.constant([1, 1])
b = tf.constant([2, 2]) p = tf.constant([True, False]) x = tf.where(p, a + b, a * b) print(tf.Session().run(x))

This will return [3, 2].

Another widely used control flow operation is tf.while_loop. It allows building dynamic loops in TensorFlow that operate on sequences of variable length. Let’s see how we can generate Fibonacci sequence with tf.while_loops:

n = tf.constant(5)

def cond(i, a, b):
return i < n def body(i, a, b):
return i + 1, b, a + b i, a, b = tf.while_loop(cond, body, (2, 1, 1)) print(tf.Session().run(b))

This will print 5. tf.while_loops takes a condition function, and a loop body function, in addition to initial values for loop variables. These loop variables are then updated by multiple calls to the body function until the condition returns false.

Now imagine we want to keep the whole series of Fibonacci sequence. We may update our body to keep a record of the history of current values:

n = tf.constant(5)

def cond(i, a, b, c):
return i < n def body(i, a, b, c):
return i + 1, b, a + b, tf.concat([c, [a + b]], 0) i, a, b, c = tf.while_loop(cond, body, (2, 1, 1, tf.constant([1, 1]))) print(tf.Session().run(c))

Now if you try running this, TensorFlow will complain that the shape of the the fourth loop variable is changing. So you must make that explicit that it’s intentional:

i, a, b, c = tf.while_loop(
cond, body, (2, 1, 1, tf.constant([1, 1])),
shape_invariants=(tf.TensorShape([]),
tf.TensorShape([]),
tf.TensorShape([]),
tf.TensorShape([None])))

This is not only getting ugly, but is also somewhat inefficient. Note that we are building a lot of intermediary tensors that we don’t use. TensorFlow has a better solution for this kind of growing arrays. Meet tf.TensorArray. Let’s do the same thing this time with tensor arrays:

n = tf.constant(5)

c = tf.TensorArray(tf.int32, n)
c = c.write(0, 1)
c = c.write(1, 1) def cond(i, a, b, c):
return i < n def body(i, a, b, c):
c = c.write(i, a + b)
return i + 1, b, a + b, c i, a, b, c = tf.while_loop(cond, body, (2, 1, 1, c)) c = c.stack() print(tf.Session().run(c))

TensorFlow while loops and tensor arrays are essential tools for building complex recurrent neural networks. As an exercise try implementing beam search using tf.while_loops. Can you make it more efficient with tensor arrays?

更多教程:http://www.tensorflownews.com/

最新文章

  1. JDBC操作步骤及数据库连接操作
  2. 回调函数透彻理解Java
  3. NDK问题总结
  4. 一键QQ聊天与一键加群QQ功能
  5. ecshop运行超过30秒超时的限制解决办法
  6. python中的实例方法、静态方法、类方法、类变量和实例变量
  7. docker居然需要3.10以上的内核
  8. Leetcode#78 Subsets
  9. Js获取fileupload的绝对路径时总是的到C:\fakepath\+文件名称的 解决方案
  10. 关于 ORA - 01861 文字与格式字符串不匹配问题(oracle存储过程)
  11. 缓冲运动-1-[解决1].html
  12. Linux防火墙配置
  13. HDU 4421 Bit Magic(奇葩式解法)
  14. [Design Pattern] Adapter Pattern 简单案例
  15. cf D. Levko and Array
  16. 使用require.js和backbone实现简单单页应用实践
  17. 获取鼠标点击相对于Canva位置的2种方法
  18. 【剑指Offer学习】【面试题:二维数组中的查找】PHP实现
  19. Nowcoder84D
  20. Linux之nginx入门

热门文章

  1. ElasticSearch系列四 CURD
  2. OpenCV使用:加载图片时报错 0x00007FFC1084A839 处(位于 test1.exe 中)有未经处理的异常: Microsoft C++ 异常: cv::Exception,位于内存位置 0x00000026ABAFF1A8 处。
  3. 达拉草201771010105《面向对象程序设计(java)》第十六周学习总结
  4. js轮询及踩过的坑
  5. win10查看本机mac地址的详细操作
  6. 前端H5,点击选择图片控件,图片直接在页面上展示~
  7. npm项目创建初始过程详解
  8. 05 JPAUtil工具类
  9. 编写程序实现根据考试成绩将成绩分为A,B,C,D四档。
  10. CSS--transform相关属性实现2d到3d的具体变化