Python OperatorNotAllowedInGraphError仍然存在,启用了急切执行并添加了decorator

Python OperatorNotAllowedInGraphError仍然存在,启用了急切执行并添加了decorator,python,python-3.x,keras,tensorflow2.0,Python,Python 3.x,Keras,Tensorflow2.0,我正在用tensorflow复制一个简单的代码 我有自己定义的函数作为模型的度量 这是一个简单的三重态损耗函数(稍加修改),但如果我使用一个普通函数,问题仍然是一样的 将熊猫作为pd导入 将numpy作为np导入 导入tensorflow作为tf 从tensorflow.keras.activations导入sigmoid 从tensorflow.keras导入后端 从tensorflow.keras.models导入模型,顺序 从tensorflow.keras.layers导入输入、嵌入、展

我正在用tensorflow复制一个简单的代码

我有自己定义的函数作为模型的度量

这是一个简单的三重态损耗函数(稍加修改),但如果我使用一个普通函数,问题仍然是一样的

将熊猫作为pd导入
将numpy作为np导入
导入tensorflow作为tf
从tensorflow.keras.activations导入sigmoid
从tensorflow.keras导入后端
从tensorflow.keras.models导入模型,顺序
从tensorflow.keras.layers导入输入、嵌入、展平、密集、丢失、Lambda、点、连接
@功能
def bpr_三重态_损耗(输入):
锚定潜在、正项目潜在、负项目潜在=输入
#BPR损失
损失=1.0-backend.sigmoid(
sum(anchor\u潜伏期*positive\u item\u潜伏期,axis=-1,keepdims=True)-
sum(anchor\u潜伏期*negative\u item\u潜伏期,axis=-1,keepdims=True))
回波损耗
def getModel(n个用户,n个项目,emb\u dim=20):
#输入层
用户输入=输入(形状=[1],名称='user\u input')
位置项输入=输入(形状=[1],名称='位置项输入')
负项输入=输入(形状=[1],名称='负项输入')
#嵌入层
#正负项的共享嵌入层
用户\u嵌入=嵌入(输出\u dim=emb\u dim,输入\u dim=n\u users+1,输入\u length=1,name='user\u emb')(用户\u输入)
项目嵌入=嵌入(输出尺寸=emb尺寸,输入尺寸=n个项目+1,输入长度=1,名称='item\u emb')
pos\u item\u嵌入=item\u嵌入(pos\u item\u输入)
负项嵌入=项嵌入(负项输入)
user\u vecs=Flatten()(user\u嵌入)
pos\u item\u vecs=展平()(pos\u item\u嵌入)
负项向量=展平()(负项嵌入)
#三重态损失函数
输出=串联([用户向量、正项向量、负项向量])
损耗=λ(bpr\u三重态损耗,(1,)(输出)
模型=模型(输入=[锚定,正,负],输出=损失)
model.compile(优化器='Adam',loss='mse',
指标=[“mae”])
#定义和编译模型
#模型=模型(输入=[用户输入,正项输入,负项输入],输出=输出)
#compile(optimizer='Adam',loss=bpr\u triplet\u loss,metrics=[bpr\u triplet\u loss])
回归模型
model=getModel(n_用户,n_项目)#67063040
当我运行这段代码时,我得到以下(开始令人沮丧)错误

---------------------------------------------------------------------------
OperatorNotAllowedInGraphError回溯(最近一次呼叫最后一次)
/opt/conda/lib/python3.7/site-packages/tensorflow\u core/python/keras/engine/base\u layer.py in\uuuuuu调用(self,input,*args,**kwargs)
841将auto_control_deps.AutomaticControlDependencies()作为acd:
-->842输出=呼叫fn(转换输入,*args,**kwargs)
843#在`tf.identity`中的`outputs`中包裹张量以避免
/调用中的opt/conda/lib/python3.7/site-packages/tensorflow_core/python/keras/layers/core.py(self、input、mask、training)
794带变量\u范围。变量\u创建者\u范围(self.\u变量\u创建者):
-->795返回self.函数(输入,**参数)
796
/opt/conda/lib/python3.7/site-packages/tensorflow_core/python/eager/def_function.py in __调用(self,*args,**kwds)
456跟踪\u计数=自。\u获取\u跟踪\u计数()
-->457结果=自调用(*args,**kwds)
458如果跟踪计数==self.\u获取跟踪计数():
/opt/conda/lib/python3.7/site-packages/tensorflow_core/python/eager/def_function.py in_调用(self,*args,**kwds)
502初始值设定项\u map=object\u identity.ObjectIdentityDictionary()
-->503自我初始化(参数、KWD、添加初始值设定项到=初始值设定项映射)
504最后:
/opt/conda/lib/python3.7/site-packages/tensorflow_core/python/eager/def_function.py in_initialize(self、args、kwds、add_initializers_to)
407 self._stateful_fn._get_concrete_function_internal_garbage_collected(#pylint:disable=protected access
-->408*args,**科威特第纳尔)
409
/opt/conda/lib/python3.7/site-packages/tensorflow\u core/python/eager/function.py in\u get\u concrete\u function\u internal\u garbage\u collected(self,*args,**kwargs)
1847 args,kwargs=None,None
->1848图形函数,u,u=self._可能定义函数(args,kwargs)
1849返回图函数
/opt/conda/lib/python3.7/site-packages/tensorflow\u core/python/eager/function.py in\u maybe\u define\u function(self、args、kwargs)
2149如果图形_函数为无:
->2150图形函数=自身。创建图形函数(args、kwargs)
2151 self.\u function\u cache.primary[cache\u key]=图形\u函数
/opt/conda/lib/python3.7/site-packages/tensorflow\u core/python/eager/function.py in\u create\u graph\u function(self、args、kwargs、override\u flat\u arg\u shapes)
2040覆盖平面形状=覆盖平面形状,
->2041按值捕获=自身。_按值捕获),
2042自我功能属性,
/opt/conda/lib/python3.7/site-packages/tensorflow_core/python/framework/func_graph.py in func_graph_from_py func(name,python_func,args,kwargs,signature,func_graph,autograph,autograph_options,add_control_依赖项,arg_名称,op_返回_值,集合,按值捕获,覆盖平面__arg_形状)
914
-->915 func_outputs=python_func(*func_args,**func_kwargs)
916
/opt/conda/lib/python3.7/site-packages/tensorflow_core/python/eager/def_function.py in wrapped_fn(*args,**kwds)
357#函数对自身进行弱引用,以避免引用循环。
-->358返回弱_-wrapped_-fn()
359弱包裹的=weakref.ref(包裹的)
/包装器中的opt/conda/lib/python3.7/site-packages/tensorflow_core/python/framework/func_graph.py(*args,**kwargs)
904如果hasattr(e,“ag\u错误\u元数据”):
---------------------------------------------------------------------------
OperatorNotAllowedInGraphError            Traceback (most recent call last)
/opt/conda/lib/python3.7/site-packages/tensorflow_core/python/keras/engine/base_layer.py in __call__(self, inputs, *args, **kwargs)
    841                   with auto_control_deps.AutomaticControlDependencies() as acd:
--> 842                     outputs = call_fn(cast_inputs, *args, **kwargs)
    843                     # Wrap Tensors in `outputs` in `tf.identity` to avoid

/opt/conda/lib/python3.7/site-packages/tensorflow_core/python/keras/layers/core.py in call(self, inputs, mask, training)
    794     with variable_scope.variable_creator_scope(self._variable_creator):
--> 795       return self.function(inputs, **arguments)
    796 

/opt/conda/lib/python3.7/site-packages/tensorflow_core/python/eager/def_function.py in __call__(self, *args, **kwds)
    456     tracing_count = self._get_tracing_count()
--> 457     result = self._call(*args, **kwds)
    458     if tracing_count == self._get_tracing_count():

/opt/conda/lib/python3.7/site-packages/tensorflow_core/python/eager/def_function.py in _call(self, *args, **kwds)
    502       initializer_map = object_identity.ObjectIdentityDictionary()
--> 503       self._initialize(args, kwds, add_initializers_to=initializer_map)
    504     finally:

/opt/conda/lib/python3.7/site-packages/tensorflow_core/python/eager/def_function.py in _initialize(self, args, kwds, add_initializers_to)
    407         self._stateful_fn._get_concrete_function_internal_garbage_collected(  # pylint: disable=protected-access
--> 408             *args, **kwds))
    409 

/opt/conda/lib/python3.7/site-packages/tensorflow_core/python/eager/function.py in _get_concrete_function_internal_garbage_collected(self, *args, **kwargs)
   1847       args, kwargs = None, None
-> 1848     graph_function, _, _ = self._maybe_define_function(args, kwargs)
   1849     return graph_function

/opt/conda/lib/python3.7/site-packages/tensorflow_core/python/eager/function.py in _maybe_define_function(self, args, kwargs)
   2149         if graph_function is None:
-> 2150           graph_function = self._create_graph_function(args, kwargs)
   2151           self._function_cache.primary[cache_key] = graph_function

/opt/conda/lib/python3.7/site-packages/tensorflow_core/python/eager/function.py in _create_graph_function(self, args, kwargs, override_flat_arg_shapes)
   2040             override_flat_arg_shapes=override_flat_arg_shapes,
-> 2041             capture_by_value=self._capture_by_value),
   2042         self._function_attributes,

/opt/conda/lib/python3.7/site-packages/tensorflow_core/python/framework/func_graph.py in func_graph_from_py_func(name, python_func, args, kwargs, signature, func_graph, autograph, autograph_options, add_control_dependencies, arg_names, op_return_value, collections, capture_by_value, override_flat_arg_shapes)
    914 
--> 915       func_outputs = python_func(*func_args, **func_kwargs)
    916 

/opt/conda/lib/python3.7/site-packages/tensorflow_core/python/eager/def_function.py in wrapped_fn(*args, **kwds)
    357         # the function a weak reference to itself to avoid a reference cycle.
--> 358         return weak_wrapped_fn().__wrapped__(*args, **kwds)
    359     weak_wrapped_fn = weakref.ref(wrapped_fn)

/opt/conda/lib/python3.7/site-packages/tensorflow_core/python/framework/func_graph.py in wrapper(*args, **kwargs)
    904             if hasattr(e, "ag_error_metadata"):
--> 905               raise e.ag_error_metadata.to_exception(e)
    906             else:

OperatorNotAllowedInGraphError: in converted code:

    <ipython-input-2-d2d9c7117621>:15 bpr_triplet_loss  *
        anchor_latent, positive_item_latent, negative_item_latent  = inputs
    /opt/conda/lib/python3.7/site-packages/tensorflow_core/python/framework/ops.py:547 __iter__
        self._disallow_iteration()
    /opt/conda/lib/python3.7/site-packages/tensorflow_core/python/framework/ops.py:540 _disallow_iteration
        self._disallow_when_autograph_enabled("iterating over `tf.Tensor`")
    /opt/conda/lib/python3.7/site-packages/tensorflow_core/python/framework/ops.py:518 _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.


During handling of the above exception, another exception occurred:

TypeError                                 Traceback (most recent call last)
<ipython-input-8-083f67ca66a0> in <module>
----> 1 model = getModel(n_users, n_items)

<ipython-input-6-75edf8b5cf85> in getModel(n_users, n_items, emb_dim)
     20     # Triplet loss function
     21     output = concatenate([user_vecs, pos_item_vecs, neg_item_vecs])
---> 22     loss = Lambda(bpr_triplet_loss, (1,))(output)
     23 
     24     model = Model(inputs=[anchor, positive, negative], outputs=loss)

/opt/conda/lib/python3.7/site-packages/tensorflow_core/python/keras/engine/base_layer.py in __call__(self, inputs, *args, **kwargs)
    852                               'dynamic. Pass `dynamic=True` to the class '
    853                               'constructor.\nEncountered error:\n"""\n' +
--> 854                               str(e) + '\n"""')
    855           else:
    856             # We will use static shape inference to return symbolic tensors

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 converted code:

    <ipython-input-2-d2d9c7117621>:15 bpr_triplet_loss  *
        anchor_latent, positive_item_latent, negative_item_latent  = inputs
    /opt/conda/lib/python3.7/site-packages/tensorflow_core/python/framework/ops.py:547 __iter__
        self._disallow_iteration()
    /opt/conda/lib/python3.7/site-packages/tensorflow_core/python/framework/ops.py:540 _disallow_iteration
        self._disallow_when_autograph_enabled("iterating over `tf.Tensor`")
    /opt/conda/lib/python3.7/site-packages/tensorflow_core/python/framework/ops.py:518 _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.

"""

    <ipython-input-2-d2d9c7117621>:15 bpr_triplet_loss  *
        anchor_latent, positive_item_latent, negative_item_latent  = inputs