如何使用布尔张量进行 if 语句 [英] How to make an if statement using a boolean Tensor

查看:56
本文介绍了如何使用布尔张量进行 if 语句的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何使用布尔张量进行 if 语句?更准确地说,我试图将大小为 1 的张量与常量进行比较,检查张量中的值是否小于常量.我想我必须使常量自己的大小为 1 张量并使用 this 检查第一个张量是否小于第二个张量的方法,但我不确定如何使生成的布尔张量正确地适合 if 语句.只需将其作为 if 语句的查询放入,即可使 if 语句始终返回 true.

How do I make an if statement using a boolean tensor? To be more precise, I'm trying to compare a tensor of size 1 to a constant, checking to see if the value in the tensor is less than the constant. I figured out I have to make the constant its own size 1 tensor and use this method to check if the first tensor is less than the second tensor, but I'm not sure how to make the resulting boolean tensor fit correctly into an if statement. Just putting it in as the query for the if statement makes if statement always return true.

这或多或少是代码的样子.但是,我收到错误 'bool' object has no attribute 'name' 不管它是否有参数,这让我认为问题在于它没有返回 TensorFlow 对象.

This is more or less what the code looked like. However, I'm getting the error 'bool' object has no attribute 'name' regardless of whether it has parameters or not, which makes me think the problem is instead that it's not returning a TensorFlow object.

pred = tf.placeholder(tf.bool)

def if_true(x, y, z):
  #act on x, y, and z
  return True

def if_false():
  return False

# Will be `tf.cond()` in the next release.
from tensorflow.python.ops import control_flow_ops
from functools import partial
x = ...
y = ...
z = ...

result = control_flow_ops.cond(pred, partial(if_true, x, y, z), if_false)

推荐答案

TL;DR: 你需要使用 Session.run() 获取 Python 布尔值,但还有其他方法可以实现相同的功能结果可能更有效.

TL;DR: You need to use Session.run() to get a Python boolean, but there are other ways to achieve the same result that might be more efficient.

看起来您已经想出了如何从您的值中获取布尔张量,但为了其他读者的利益,它看起来像这样:

It looks like you've already figured out how to get a boolean tensor from your value, but for the benefit of other readers, it would look something like this:

computed_val = ...
constant_val = tf.constant(37.0)
pred = tf.less(computed_val, constant_val)  # N.B. Types of the two args must match

下一部分是如何使用它作为条件.最简单的方法是使用 Python if 语句,但要做到这一点,您必须使用 Session.run():

The next part is how to use it as a conditional. The simplest thing to do is to use a Python if statement, but to do that you must evaluate the tensor pred using Session.run():

sess = tf.Session()

if sess.run(pred):
  # Do something.
else:
  # Do something else.

关于使用 Python if 语句的一个警告是,您必须评估整个表达式直到 pred,这使得重用已经过的中间值变得很棘手.计算.我想提请您注意使用 TensorFlow 计算条件表达式的另外两种方法,它们不需要您评估谓词并返回 Python 值.

One caveat about using a Python if statement is that you have to evaluate the whole expression up to pred, which makes it tricky to reuse intermediate values that have already been computed. I'd like to draw your attention to two other ways you can compute conditional expressions using TensorFlow, which don't require you to evaluate the predicate and get a Python value back.

第一种方法使用 tf.select() op 有条件地传递来自作为参数传递的两个张量的值:

The first way uses the tf.select() op to conditionally pass through values from two tensors passed as arguments:

pred = tf.placeholder(tf.bool)  # Can be any computed boolean expression.
val_if_true = tf.constant(28.0)
val_if_false = tf.constant(12.0)
result = tf.select(pred, val_if_true, val_if_false)

sess = tf.Session()
sess.run(result, feed_dict={pred: True})   # ==> 28.0
sess.run(result, feed_dict={pred: False})  # ==> 12.0

tf.select() 操作在其所有参数上按元素工作,这允许您组合来自两个输入张量的值.有关更多详细信息,请参阅其文档.tf.select() 的缺点是它在计算结果之前同时评估 val_if_trueval_if_false,如果它们很复杂,这可能会很昂贵表达.

The tf.select() op works element-wise on all of its arguments, which allows you to combine values from the two input tensors. See its documentation for more details. The drawback of tf.select() is that it evaluates both val_if_true and val_if_false before computing the result, which might be expensive if they are complicated expressions.

第二种方式使用 tf.cond() op,它有条件地评估两个表达式之一.如果表达式很昂贵,这尤其有用,如果它们有副作用.基本模式是指定两个 Python 函数(或 lambda 表达式)来构建将在 true 或 false 分支上执行的子图:

The second way uses the tf.cond() op, which conditionally evaluates one of two expressions. This is particularly useful if the expressions are expensive, and it is essential if they have side effects. The basic pattern is to specify two Python functions (or lambda expressions) that build subgraphs that will execute on the true or false branches:

# Define some large matrices
a = ...
b = ...
c = ...

pred = tf.placeholder(tf.bool)

def if_true():
  return tf.matmul(a, b)

def if_false():
  return tf.matmul(b, c)

# Will be `tf.cond()` in the next release.
from tensorflow.python.ops import control_flow_ops

result = tf.cond(pred, if_true, if_false)

sess = tf.Session()
sess.run(result, feed_dict={pred: True})   # ==> executes only (a x b)
sess.run(result, feed_dict={pred: False})  # ==> executes only (b x c)

这篇关于如何使用布尔张量进行 if 语句的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆