简体   繁体   English

张量流中的if语句(无其他)

[英]If statement (without else) in tensorflow

I want to have an if statement in tensorflow; 我想在tensorflow中有一个if语句; and if the condition is not fulfilled nothing should happen. 如果条件不满足,就不会发生任何事情。

I tried to use both tf.case and tf.cond but both require a specification of a function it the statement evaluates False. 我试图同时使用tf.case和tf.cond,但是两者都需要一个函数的说明,该语句的评估结果为False。

op = tf.cond(tf.equal(x, y), true_fn=f1(), false_fn=lambda: None)

gives me an error: ValueError: false_fn must have a return value. 给我一个错误:ValueError:false_fn必须具有返回值。

On TF 1.x, I would use tf.no_op to specify a dummy OP that does nothing: 在TF 1.x上,我将使用tf.no_op指定不执行任何操作的虚拟OP:

ops = tf.cond(tf.equal(x, y), true_fn=f, false_fn=lambda: tf.no_op()) 

On TF 2.x, you can just pass lambda: None to false_fn , thanks to eager execution. 在TF 2.x上,您可以只将lambda: None传递给false_fn ,这要归功于执行的热情。


Minimal Code Sample 最少的代码样本

import tensorflow as tf

x, y, z = tf.constant(1), tf.constant(1), tf.constant(2)
op1 = tf.cond(
    tf.equal(x, y), true_fn=lambda: tf.print(x), false_fn=lambda: tf.no_op())
op2 = tf.cond(
    tf.equal(x, z), true_fn=lambda: tf.print(x), false_fn=lambda: tf.no_op())

with tf.Session() as sess:
    sess.run(op1)  # 1
    sess.run(op2)  # does nothing

You can use tf.identy(tf) 您可以使用tf.identy(tf)

namely

op = tf.cond(tf.equal(x, y), true_fn=f1(), false_fn=tf.identy(tf))

@see https://www.tensorflow.org/api_docs/python/tf/identity @请参阅https://www.tensorflow.org/api_docs/python/tf/identity

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM