python - 不允许迭代 tf.Tensor : AutoGraph is disabled in this function

标签 python tensorflow

我正在使用 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_fntf.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/

相关文章:

python - Keras LSTM 中隐藏状态的含义

python - 带有 numpy 的二维数组

python - 在Python数据框中创建宏变量

python - 通过基于随机值的过滤,使用列表理解生成 10 个(或更少)均匀分布的随机 float

python - tensorflow 中的批量图像增强

python - Keras 中 sigmoid 激活函数的使用

php - 在处理来自 ffmpeg 的输入时将数据推送到网络浏览器

python - 在 SymPy 中从分块矩阵构建矩阵

tensorflow - 非确定性梯度计算

tensorflow - 为什么不使用 Flatten 和 Dense 层来代替 TimeDistributed?