2

I want to loop over a Tensorflow tensor, my code is something like this:

elements = tf.constant([1,2,3])
x = tf.constant([1.000001, 1.1, 2.1, 2.00004, 3.001])
EPSILON = 0.0001
for elem in elements:
    mask = tf.experimental.numpy.isclose(x, elem, atol=EPSILON, rtol=0)
    x = tf.boolean_mask(x, ~mask)

How can I do it in Tensorflow under graph mode? I got following error:

    OperatorNotAllowedInGraphError: iterating over `tf.Tensor` is not allowed: AutoGraph did convert this function. This might indicate you are trying to use an unsupported feature.

I'm running it with TF 2.4.1 but I am doing it under Beam context (for TFX purpose) which means the operations are done under graph operation.

Thanks!

eng2019
  • 953
  • 10
  • 26
  • Would something like this help? `elements = [tf.constant(t) for t in [1, 2, 3]]` – xdhmoore May 10 '21 at 21:26
  • This also looks relevant: https://stackoverflow.com/questions/35330117/how-can-i-run-a-loop-with-a-tensor-as-its-range-in-tensorflow – xdhmoore May 10 '21 at 21:32
  • And possibly this: https://github.com/tensorflow/tensorflow/blob/master/tensorflow/python/autograph/g3doc/reference/control_flow.md#for-statements – xdhmoore May 10 '21 at 21:43

1 Answers1

1

It's solved this way:

    mask = tf.map_fn(fn=lambda t: ~tf.experimental.numpy.isclose(
        x, t, atol=EPSILON, rtol=0
    ), elems=elements)

    mask = tf.reduce_min(mask, axis=0)
    x = tf.boolean_mask(x, mask)
eng2019
  • 953
  • 10
  • 26