如果 tf.cond 在 Tensorflow 中检查失败,如何停止图形执行或更改控制流?

How to stop the graph execution or change control flow if the tf.cond check fails in Tensorflow?

我正在构建一个图形,我需要在其中检查输入张量的形状。我尝试在张量的形状上使用 tf.cond 。但我发现 tf.cond 期望 true_fnfalse_fn到 return 相同类型的输出。我的问题是当输入形状检查失败时如何停止执行。通常,如何在图执行阶段更改控制流?我的代码如下所示。谢谢

 input_img = tf.image.decode_jpeg(input_str, channels = 3)
 img_shape = tf.shape(input_img)
 valid_img = tf.cond(tf.not_equal(img_shape[2], 3), STOP, input_img)

也许 tf.Assert 适合。您可以选择所需的条件,在基本情况下使用

with tf.control_dependencies([tf.assert_equal(a, b)]):
    c = some_func(a, b)

如果不满足条件,则会抛出 Condition x == y did not hold element-wise 错误