自定义函数编译时出现上述错误的原因在于tf2.x的keras.compile默认不支持具体数值的操作
问题
在使用包裹法自定义keras模型的损失函数时,需要计算precision或recall等精度指标,或需要提取输入y_true、y_prd的具体值(诸如y_true.numpy()的操作) 时,出现报错信息:
OperatorNotAllowedInGraphError: using a `tf.Tensor` as a Python `bool` is not allowed: AutoGraph did convert this function. This might indicate you are trying to use an unsupported feature.
或者
AttributeError: 'Tensor' object has no attribute 'numpy'
解决方法
在compile函数中传入参数:
run_eagerly=True
原因
tf2.x默认开启eager模式,即eager excution,亦即动态计算图,相比于tf1.x的静态计算图,eager模式的优势在于方便调试,可以很方便的打印张量值,评价结果;与numpy交互良好,tensor与ndarray的转化方便,甚至可以通用。代价就是运行速度显著变慢。而静态计算图在定义了计算图后,由于几乎都在tensorflow内核上使用C++代码执行,所以运算效率更高,速度更快。
虽然如此,model.compile方法中 run_eagerly默认False,