首页 > 解决方案 > 有和没有@tf.function 的不同行为

问题描述

i当 的值为3 的倍数时,以下代码不会产生“Fizz” :

@tf.function
def fizzbuzz(n):
  msg = tf.constant('')
  for i in tf.range(n):
    if int(i % 3) == 0:
      msg += 'Fizz'
    elif tf.equal(i % 5, 0):
      msg += 'Buzz'
    else:
      msg += tf.as_string(i)
    msg += '\n'
  return msg

print(fizzbuzz(tf.constant(15)).numpy().decode())

但是如果有人评论了@tf.function装饰器,它可以正常工作为 3 的倍数。为什么?

标签: pythontensorfloweager-execution

解决方案


Following fix worked for me: Use a combination of tf.mod and tf.equal instead of % and ==.

I encountered this problem some days ago and I am not sure, if it's a bug or desired behaviour.

@tf.function
def fizzbuzz(n):
    msg = tf.constant('')
    for i in tf.range(n):
        if tf.equal(tf.mod(i, 3), 0):
            msg += 'Fizz'
        elif tf.equal(i % 5, 0):
            msg += 'Buzz'
        else:
            msg += tf.as_string(i)
        msg += '\n'
    return msg
print(fizzbuzz(tf.constant(15)).numpy().decode())
# Output
#Fizz
#1
#2
#Fizz
#4
#Buzz
#Fizz
#7
#8
#Fizz
#Buzz
#11
#Fizz
#13
#14

推荐阅读