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. Python爬虫-scrapyd

    1.什么是scrapyd Scrapyd是一个服务,用来运行scrapy爬虫的. 它允许你部署你的scrapy项目以及通过HTTP JSON的方式控制你的爬虫. 官方文档:http://scrapyd ...

  2. python 读取 execl 文件 之 xlrd 模块

    1. 安装 xlrd模块 pip install xlrd 2. 读取文件内容 #!/usr/bin/env python3 import xlrd name = r"E:\excel\yo ...

  3. swoole(6)Task异步任务

    一:什么是task进程? task进程是独立与worker进程的一组进程  ,他主要处理耗时较长的业务逻辑,并且不影响worker进程处理客户端的请求.worker进程通过task()函数把数据投递到 ...

  4. 关于CSS居中问题的一些总结

    前端页面开发中关于内容居中的需求应用概率很大,自己搜集一些资料和总结关于css里的几种居中效果实现 第一常用text-align:center先将子元素将块级元素改为行内元素,即display:inl ...

  5. Sketchup二次开发教程

    Sketchup提供了两套API: C API,主要用于读写SU文件.我们的SU文件导入功能就是用这套API做的 Ruby API,用于开发SU插件 这次我们主要关注Ruby API,因为它是实现更丰 ...

  6. spring——AOP原理及源码(五)

    前情回顾: 在上一篇中,通过 wrapIfNecessary 方法,我们获取到了合适的增强器(日志方法)与业务类进行包装,最终返回了我们业务类的代理对象. 本篇我们将从业务方法的执行开始,看看增强器( ...

  7. javascript中的中介者模式——迪米特法则

    ”迪米特法则“——最少知识原则,不和陌生人说话,就是说,一个对象应当对其他对象有尽可能少的了解.talk only to your immediate friends.初衷是:降低对象之间的耦合度. ...

  8. JDK8内存模型—消失的PermGen

    一.JVM 内存模型 根据 JVM 规范,JVM 内存共分为虚拟机栈.堆.方法区.程序计数器.本地方法栈五个部分. 1.虚拟机栈:每个线程有一个私有的栈,随着线程的创建而创建.栈里面存着的是一种叫“栈 ...

  9. 前端Tips#6 - 在 async iterator 上使用 for-await-of 语法糖

    视频讲解 前往原文 前端Tips 专栏#6,点击观看 文字讲解 本期主要是讲解如何使用 for-await-of 语法糖进行异步操作迭代,让组织异步操作的代码更加简洁易读. 1.场景简述 以下代码中的 ...

  10. 助力SpringBoot自动配置的条件注解ConditionalOnXXX分析--SpringBoot源码(三)

    注:该源码分析对应SpringBoot版本为2.1.0.RELEASE 1 前言 本篇接 如何分析SpringBoot源码模块及结构?--SpringBoot源码(二) 上一篇分析了SpringBoo ...