加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Python > 正文

python – tensorflow:检查标量布尔张量是否为True

发布时间:2020-12-20 11:59:19 所属栏目:Python 来源:网络整理
导读:我想使用占位符控制函数的执行,但不断收到错误“不允许使用tf.Tensor作为 Python bool”.以下是产生此错误的代码: import tensorflow as tfdef foo(c): if c: print('This is true') #heavy code here return 10 else: print('This is false') #different c
我想使用占位符控制函数的执行,但不断收到错误“不允许使用tf.Tensor作为 Python bool”.以下是产生此错误的代码:

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()

我改变了,如果c,如果c不是没有运气没有.如何通过打开和关闭占位符a来控制foo?

更新:当@nessuno和@nemo指出时,我们必须使用tf.cond而不是if..else.我的问题的答案是重新设计我的功能,如下所示:

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()

解决方法

您必须使用 tf.cond在图表中定义条件操作,并因此更改张量的流程.

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读