有Tensorflow2.1兼容性问题的Mask RCNN的github项目:
https://github.com/matterport/Mask_RCNN
报错信息:
ValueError: The following Variables were created within a Lambda layer (anchors) but are not tracked by said layer: <tf.Variable 'anchors/Variable:0' shape=(1, 261888, 4) dtype=float32> The layer cannot safely ensure proper Variable reuse across multiple calls, and consquently this behavior is disallowed for safety. Lambda layers are not well suited to stateful computation; instead, writing a subclassed Layer is the recommend way to define layers with Variables.
问题原因:
从Tensorflow2.0开始,由于安全性原因,官方不推荐使用Lambda layer,需要使用subclass(Layer子类)方式实现。
解决方案:
重写:
anchors = KL.Lambda(lambda x: tf.Variable(anchors), name="anchors")(input_image)
为:
class AnchorsLayer(tf.keras.layers.Layer):
def __init__(self, name="anchors", **kwargs):
super(AnchorsLayer, self).__init__(name=name, **kwargs)
def call(self, anchor):
return anchor
def get_config(self) :
config = super(AnchorsLayer, self).get_config()
return config
anchor_layer = AnchorsLayer(name="anchors")
anchors = anchor_layer(anchors)
Tensorflow2.1 文档关于Lambda layer的详细说明:
https://www.tensorflow.org/api_docs/python/tf/keras/layers/Lambda
关于在keras下编写自定义layer的详细说明:
https://www.tensorflow.org/guide/keras/custom_layers_and_models