我正在使用 tensorflow 2.1 和 python 3.7
以下代码片段用于构建 tensorflow 图。当作为独立的 python 脚本执行时,代码运行没有错误。 (可能 tensorflow 正在以 Eager 模式运行?我不确定。)
import tensorflow as tf
patches = tf.random.uniform(shape=(1, 10, 50, 300), dtype=tf.dtypes.float32)
s = tf.shape(patches)
patches = [patches[0][x][y] - tf.reduce_mean(patches[0][x][y]) for y in tf.range(s[2]) for x in tf.range(s[1])]
但是,当这是 tensorflow 图的一部分时,代码会失败。我收到以下错误:
tensorflow 。
python.framework.errors_impl.OperatorNotAllowedInGraphError: iterating over
tf.Tensor
is not allowed: AutoGraph is disabled in this function. Try decorating it directly with @tf.function.
我还添加了装饰器
@tf.function
到包装上述代码行的方法。它没有帮助。不知道我是否完全理解用@tf.function
装饰的意义.我还检查了这可能是在 tensorflow 图中使用 python 列表理解的问题。我不知道如何使用 tf.map_fn或 tf.while_loop就我而言,因为我有嵌套循环。提前致谢!
最佳答案
亲笔签名尚不支持列表推导式。提出的错误也需要改进。堆积在https://github.com/tensorflow/tensorflow/issues/32546应该有助于尽快解决它。
在支持理解之前,您必须使用 map_fn,在这种情况下,它看起来像这样:
def outer_comp(x):
def inner_comp(y):
return patches[0][x][y] - tf.reduce_mean(patches[0][x][y])
return tf.map_fn(inner_comp, tf.range(s[2]), dtype=tf.float32)
patches = tf.map_fn(outer_comp, tf.range(s[1]), dtype=tf.float32)
也就是说,我相信你可以直接使用 reduce_mean :
patches = patches - tf.expand_dims(tf.reduce_mean(patches, axis=3), -1)
关于python - 不允许迭代 tf.Tensor : AutoGraph is disabled in this function,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62068323/