0

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 的倍数。为什么?

4

1 回答 1

0

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
于 2019-04-26T16:02:17.943 回答