python - 有和没有@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 的倍数。为什么?
解决方案
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
推荐阅读
- ansible - Ansible 循环返回输出整个对象
- php - 动态加载包含变量的变量,这些变量包含php中文件中的值
- gwt - 同一页面有多个 MVP?
- openssl - 同时从 OpenSSL 生成 EC KeyPair
- python - 如何通过图访问作为图节点的类实例的属性?
- ios - 我在 SwiftUI 中遇到了动态列表的问题。我无法使用选择器动态更新列表
- r - R PCA:使用 fviz_pca_ind 函数,我们可以有两个分类变量:一个点形状和一个填充颜色?
- python - 使用 Pandas 将日期转换为天数
- python - Tensorboard 页面错误:MimeType 文本/纯文本不可执行
- jquery - 将数组值转换为 RGB 格式