tensorflow:检查标量布尔张量是否为真 [英] tensorflow: check if a scalar boolean tensor is True

查看:36
本文介绍了tensorflow:检查标量布尔张量是否为真的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用占位符控制函数的执行,但不断收到错误不允许将 tf.Tensor 用作 Python bool".这是产生此错误的代码:

 将 tensorflow 导入为 tf定义 foo(c):如果 c:print('这是真的')#重代码在这里返回 10别的:print('这是假的')#这里的代码不同返回 0a = tf.placeholder(tf.bool) #单个布尔值的占位符b = foo(a)sess = tf.InteractiveSession()res = sess.run(b, feed_dict = {a: True})sess.close()

我将 if c 更改为 if c is not None 没有运气.那么如何通过打开和关闭占位符 a 来控制 foo 呢?

更新:正如@nessuno 和@nemo 指出的,我们必须使用tf.cond 而不是if..else.我的问题的答案是像这样重新设计我的功能:

 将 tensorflow 导入为 tf定义 foo(c):返回 tf.cond(c, func1, func2)a = tf.placeholder(tf.bool) #单个布尔值的占位符b = foo(a)sess = tf.InteractiveSession()res = sess.run(b, feed_dict = {a: True})sess.close()

解决方案

你必须使用 tf.cond 来定义图中的条件操作并改变张量的流动.

 将 tensorflow 导入为 tfa = tf.placeholder(tf.bool) #单个布尔值的占位符b = tf.cond(tf.equal(a, tf.constant(True)), lambda: tf.constant(10), lambda: tf.constant(0))sess = tf.InteractiveSession()res = sess.run(b, feed_dict = {a: True})sess.close()打印(资源)

<块引用>

10

I want to control the execution of a function using a placeholder, but keep getting an error "Using a tf.Tensor as a Python bool is not allowed". Here is the code that produces this error:

import tensorflow as tf
def foo(c):
  if c:
    print('This is true')
    #heavy code here
    return 10
  else:
    print('This is false')
    #different code here
    return 0

a = tf.placeholder(tf.bool)  #placeholder for a single boolean value
b = foo(a)
sess = tf.InteractiveSession()
res = sess.run(b, feed_dict = {a: True})
sess.close()

I changed if c to if c is not None without luck. How can I control foo by turning on and off the placeholder a then?

Update: as @nessuno and @nemo point out, we must use tf.cond instead of if..else. The answer to my question is to re-design my function like this:

import tensorflow as tf
def foo(c):
  return tf.cond(c, func1, func2)

a = tf.placeholder(tf.bool)  #placeholder for a single boolean value
b = foo(a)
sess = tf.InteractiveSession()
res = sess.run(b, feed_dict = {a: True})
sess.close() 

解决方案

You have to use tf.cond to define a conditional operation within the graph and change, thus, the flow of the tensors.

import tensorflow as tf

a = tf.placeholder(tf.bool)  #placeholder for a single boolean value
b = tf.cond(tf.equal(a, tf.constant(True)), lambda: tf.constant(10), lambda: tf.constant(0))
sess = tf.InteractiveSession()
res = sess.run(b, feed_dict = {a: True})
sess.close()
print(res)

10

这篇关于tensorflow:检查标量布尔张量是否为真的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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