不允许迭代 tf.Tensor:此函数中禁用 AutoGraph [英] Iterating over tf.Tensor is not allowed: AutoGraph is disabled in this function
问题描述
我正在使用 tensorflow 2.1 和 python 3.7
I am using tensorflow 2.1 along with python 3.7
以下代码片段用于构建张量流图.当作为独立的 python 脚本执行时,代码运行没有错误.(可能 tensorflow 正在以 Eager 模式运行?我不确定.)
The following snippet of code is being used to build a tensorflow graph. The code runs without errors when executed as a standalone python script. (Probably tensorflow is running in eager mode? I am not sure.)
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])]
但是,当这是张量流图的一部分时,代码会失败.我收到以下错误:张量流.
However, the code fails when this is part of a tensorflow graph. I receive the following error: tensorflow.
python.framework.errors_impl.OperatorNotAllowedInGraphError:迭代不允许超过 tf.Tensor
:在此功能中禁用 AutoGraph.尝试直接用@tf.function 装饰它.
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
装饰的含义.我还检查了这可能是在张量流图中使用 python 列表理解的问题.我不确定如何使用 tf.map_fn 或 tf.while_loop 就我而言,因为我有嵌套循环.
I also added the decorator @tf.function
to the method which wraps the above lines of code. It didn't help. I am not sure if I fully understand the meaning of decorating with @tf.function
. I also checked that this could be a problem with using python list comprehension inside the tensorflow graph. I am not sure how to use tf.map_fn or tf.while_loop for my case, since I have nested loops.
提前致谢!
推荐答案
签名尚不支持列表推导式.提出的错误也需要改进.堆积在 https://github.com/tensorflow/tensorflow/issues/32546 应该帮助尽快解决.
List comprehensions are not yet supported in autograph. The error that's raised needs to be improved, too. Piling up on https://github.com/tensorflow/tensorflow/issues/32546 should help resolve it sooner.
在支持理解之前,您必须使用 map_fn,在这种情况下,它看起来像这样:
Until comprehensions are supported, you have to use map_fn, which in this case would look something like this:
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:
That said, I believe you can just use reduce_mean directly:
patches = patches - tf.expand_dims(tf.reduce_mean(patches, axis=3), -1)
这篇关于不允许迭代 tf.Tensor:此函数中禁用 AutoGraph的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!