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/

tensorflow 控制流操作,条件判断和循环操作的更多相关文章

  1. Python学习笔记——基础篇【第一周】——变量与赋值、用户交互、条件判断、循环控制、数据类型、文本操作

    目录 Python第一周笔记 1.学习Python目的 2.Python简史介绍 3.Python3特性 4.Hello World程序 5.变量与赋值 6.用户交互 7.条件判断与缩进 8.循环控制 ...

  2. python自学-day2(变量、if条件判断、运算符操作)

    1.变量 变量只是用于保存内存位置,将变量存储在内存中的作用,方便后面调用,这意味着,在创建变量时会在内存中开辟一个空间. 变量命名规则: 由字母.数字.下划线(_)组成 不能以数字开头 不能使用 P ...

  3. 5-3 bash脚本编程之二 条件判断

    1. 条件测试的表达式 1. [ expression ]  :注意这个中括号的前后都有一个空格 2. [[ expression ]] 3. test expression 2.条件判断的类型 1. ...

  4. python Django教程 之模板渲染、循环、条件判断、常用的标签、过滤器

    python3.5 manage.py runserver python Django教程 之模板渲染.循环.条件判断.常用的标签.过滤器 一.Django模板渲染模板 1. 创建一个 zqxt_tm ...

  5. shell 条件判断语句整理

    常用系统变量 1)         $0 当前程式的名称 2)         $n 当前程式的第n个参数,n=1,2,…9 3)         $* 当前程式的任何参数(不包括程式本身) 4)   ...

  6. python基础-编码_if条件判断

    一.第一句Python代码 在 /home/dev/ 目录下创建 hello.py 文件,内容如下: [root@python-3 scripts]# cat hello.py #!/usr/bin/ ...

  7. oracle触发器加条件判断

    oracle触发器加条件判断,如果某个字段,isnode=0,那么不执行下面的方法,数据如下: create or replace trigger tr_basestation_insert_emp ...

  8. bash脚本编程之二 条件判断and 逻辑运算

    1.条件测试结构 1) if/then结构: 判断命令列表的退出码是否为0,0为成功. 如果if和then在条件判断的同一行上的话, 必须使用分号来结束if表达式: if和then都是关键字. 关键字 ...

  9. [Shell]条件判断与流程控制:if, case, for, while, until

    ---------------------------------------------------------------------------------------------------- ...

随机推荐

  1. C#连接Informix数据库

    最近在工作中遇到了需要连接Informix数据库的问题,在通过研究后发现了可以通过多种方式实现,我选择的是通过IBM Informix .NET Provider.该方式需要引用IBM.Data.In ...

  2. LeetCode 32,并不Hard的难题,解法超级经典,带你领略动态规划的精彩

    本文始发于个人公众号:TechFlow,原创不易,求个关注 今天给大家分享的是LeetCode当中的32题,这是一道Hard难度的题.也是一道经典的字符串处理问题,在接下来的文章当中,我们会详细地解读 ...

  3. python基础-流程控制语句

    所谓流程控制,就是在程序里面设定一些条件判断语句,满足哪条,就执行哪条 #if 单分支 if 条件: 满足条件后执行的代码 #例子 > : print()#结果为666 双分支 if 条件: 满 ...

  4. ASP.NET CORE 内置的IOC解读及使用

    在我接触IOC和DI 概念的时候是在2016年有幸倒腾Java的时候第一次接触,当时对这两个概念很是模糊:后来由于各种原因又回到.net 大本营,又再次接触了IOC和DI,也算终于搞清楚了IOC和DI ...

  5. js监听离开或刷新页面时的弹窗提示

    一.看图 二.使用场景. 填写表单时内容,当离开页面或者刷新的时候回丢失页面的内容,因此人性化的设计该有一个提示.所以这样的功能也就应用而生了. 三.思路. 1,页面内容改变.2,离开或刷新浏览器触发 ...

  6. 高性能MySQL之锁详解

    一.背景 MySQL里面的锁大致可以分成全局锁.表级锁和行锁三类.数据库锁的设计的初衷是处理并发问题.我们知道多用户共享资源的时候,就有可能会出现并发访问的时候,数据库就需要合理的控制资源的访问规则, ...

  7. 微信小程序接入百度OCR(身份证识别)

    微信小程序接入百度OCR(身份证识别) 1.接口描述 支持对二代居民身份证正反面所有8个字段进行结构化识别,包括姓名.性别.民族.出生日期.住址.身份证号.签发机关.有效期限,识别准确率超过99%:同 ...

  8. WEB渗透 - XSS

    听说这个时间点是人类这种生物很重要的一个节点 cross-site scripting 跨站脚本漏洞 类型 存储型(持久) 反射型(非持久) DOM型 利用 先检测,看我们输入的内容是否有返回以及有无 ...

  9. 深度学习与人类语言处理-语音识别(part1)

    语音识别 语音识别该何去何从? 1969年,J.R. PIERCE:"语音识别就像把水变成汽油.从大海中淘金.治疗癌症.人类登陆月球" 当然,这是50年前的想法,那么语音识别该如何 ...

  10. 作为一个Tester,你在客户环境能保证质量吗?

    公司严格地按照“产品-项目”模式来架构技术部门. 我又测产品,又测项目,所以一方面可以从项目测试的角度发现产品bug,并且给产品提供改进意见,一方面还能测产品为项目赋能,保证项目质量,让项目经理轻松些 ...