Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/tensorflow/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 安全地检查tf.张量是否满足某些条件_Python_Tensorflow - Fatal编程技术网

Python 安全地检查tf.张量是否满足某些条件

Python 安全地检查tf.张量是否满足某些条件,python,tensorflow,Python,Tensorflow,如果我想检查tnsr=tf.constant(…)中的所有元素是否大于3,我可以tf.reduce\u all(tnsr>3)得到一个标量布尔张量。如果我使用的是急切执行,或者@tf.function,那么我可以将其用作正常的bool: @tf.function def foo(tnsr): if tf.reduce_all(tnsr > 3): ... 但是这个。那我该怎么办 我尝试过的其他事情: tf.cond返回tf.Tensor即使对于true\u fn

如果我想检查
tnsr=tf.constant(…)
中的所有元素是否大于3,我可以
tf.reduce\u all(tnsr>3)
得到一个标量布尔张量。如果我使用的是急切执行,或者
@tf.function
,那么我可以将其用作正常的
bool

@tf.function
def foo(tnsr):
    if tf.reduce_all(tnsr > 3):
        ...
但是这个。那我该怎么办

我尝试过的其他事情:

  • tf.cond
    返回
    tf.Tensor
    即使对于
    true\u fn=lambda:true
  • bool(tf.reduce_all(tnsr>3))
    失败的原因与上述相同

tf.cond
不允许将
tf.Tensor
作为这种情况下的第一个参数”-如何?是专门为这个目的设计的,你能举例说明你不能使用它吗?@jdehesa我错了。我认为问题在于
tf.cond
返回一个
tf.Tensor
,这并不能解决我的问题。对,但这就是
tf.cond
的工作原理,其思想是在
true\u fn
callable中执行在
if
的第一部分中要执行的操作,在
false\fn
中执行
else
部分。也许你可以给出一个完整的小例子,说明你不知道如何从
if
转换到
tf.cond
?@jdehesa好的,我明白你的意思,但这并不总是可能的。特别是,我定义了一个
\uuuu contains\uuu
方法,它接受一个参数并返回
bool
(尽管我的方法有时返回标量布尔张量)。无法将
tf.cond
放在
\uuuuuu包含的方法中:这必须由调用方决定