Weird results with if-else in a tf.data.map

Viewed 81

Why does the else block run when the below script is executed in TF.2.3.1?

DEFAULT_STR = "*"

def add_na_cols(example:Dict, col:str):
    if example[col] == DEFAULT_STR:
        tf.print(example)
        example[f'{col}_na'] = "True"
    else:
        tf.print("Came to false")
        example[f"{col}_na"] = "False"
    return example

t = tf.data.Dataset.from_tensor_slices({"a": [DEFAULT_STR]})
for r in t.map(partial(add_na_cols, col="a")):
    print(r)

Expect to print

{'a': "*"}
{'a': <tf.Tensor: shape=(), dtype=string, numpy=b'*'>, 'a_na': <tf.Tensor: shape=(), dtype=string, numpy=True'>}

but see

{'a': "*"}
{'a': <tf.Tensor: shape=(), dtype=string, numpy=b'*'>, 'a_na': <tf.Tensor: shape=(), dtype=string, numpy=b'False'>}

Created a collab https://colab.research.google.com/drive/1ZgLF0ytiRJ4_VwfMMpVRP1TVkV-cFdDc?usp=sharing

def add_na_cols(example:Dict, col:str):
  example[f'{col}_na'] = tf.cond(example[col] == DEFAULT_STR, lambda: "True", lambda: "False")
  return example

works but I am trying to know why in graph mode, the if-else approach doesn't work as expected

0 Answers
Related