OperatorNotAllowedInGraphError:不允许迭代`tf.Tensor`

问题描述

我的 LSTM 层的这个定义工作正常

self._shared_rnns = []
for layer_idx in range(self._num_shared_layers):
     self._shared_rnns.append(
           tf.keras.layers.LSTM(1024)                
     )

但是当我将定义更改为

    self._shared_rnns = []
    for layer_idx in range(self._num_shared_layers):
         self._shared_rnns.append(
               tf.keras.layers.RNN(
                    tf.keras.layers.LSTMCell(1024),return_sequences=True,time_major=True
              )                
         )

我在图构建阶段遇到以下错误

TypeError: You are attempting to use Python control flow in a layer that was not declared to be dynamic. Pass `dynamic=True` to the class constructor.
Encountered error:
"""
in user code:
/home/ec2-user/phasa_root/package-src-root/src/phasa/layers/layers.py:3110 call  *
    x,*states = self._shared_rnns(
/home/ec2-user/phasa_root/testrun.runtimefarm/python3.6/lib/python3.6/site-packages/tensorflow/python/framework/ops.py:561 __iter__
    self._disallow_iteration()
/home/ec2-user/phasa_root/testrun.runtimefarm/python3.6/lib/python3.6/site-packages/tensorflow/python/framework/ops.py:554 _disallow_iteration
    self._disallow_when_autograph_enabled("iterating over `tf.Tensor`")
/home/ec2-user/phasa_root/testrun.runtimefarm/python3.6/lib/python3.6/site-packages/tensorflow/python/framework/ops.py:532 _disallow_when_autograph_enabled
    " decorating it directly with @tf.function.".format(task))

OperatorNotAllowedInGraphError: iterating over `tf.Tensor` is not allowed: AutoGraph did not convert this function. Try decorating it directly with @tf.function.

我进行此更改的原因是因为我想使用自定义的 LSTM 单元并且 tf.keras.layers.RNN 可以接受它而 tf.keras.layers.LSTM 不能。

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)