簡體   English   中英

tensorflow:檢查標量布爾張量是否為True

[英]tensorflow: check if a scalar boolean tensor is True

我想使用占位符控制函數的執行,但不斷收到錯誤“不允許使用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()

我改變了, if cif c is not None運氣沒有。 如何通過打開和關閉占位符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

實際的執行不是在Python中完成的,而是在TensorFlow后端中提供的計算圖,它應該執行。 這意味着您要應用的每個條件和流量控制都必須表示為計算圖中的節點。

if條件有cond操作:

b = tf.cond(c, 
           lambda: tf.constant(10), 
           lambda: tf.constant(0))

一種更簡單的解決方法:

In [50]: a = tf.placeholder(tf.bool)                                                                                                                                                                                 

In [51]: is_true = tf.count_nonzero([a])                                                                                                                                                                             

In [52]: sess.run(is_true, {a: True})                                                                                                                                                                                
Out[52]: 1

In [53]: sess.run(is_true, {a: False})
Out[53]: 0

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM