【问题标题】:Cannot save keras model with custom layers to tf lite file无法将具有自定义图层的 keras 模型保存到 tf lite 文件
【发布时间】:2019-07-23 12:34:50
【问题描述】:

我想将 Mask-RCNN 移植到 tensorflow lite 以便能够在我的 android 设备上使用它。 Tensorflow lite 有一些教程展示了如何执行此操作,但是当您的模型具有扩展 keras 层类的层时,它们的说明会失败。特别是,这是我得到的错误:

/usr/local/lib/python3.5/dist-packages/tensorflow/python/keras/layers/serialization.py in deserialize(config, custom_objects)
     87       module_objects=globs,
     88       custom_objects=custom_objects,
---> 89       printable_module_name='layer')

/usr/local/lib/python3.5/dist-packages/tensorflow/python/keras/utils/generic_utils.py in deserialize_keras_object(identifier, module_objects, custom_objects, printable_module_name)
    179     config = identifier
    180     (cls, cls_config) = class_and_config_for_serialized_keras_object(
--> 181         config, module_objects, custom_objects, printable_module_name)
    182 
    183     if hasattr(cls, 'from_config'):

/usr/local/lib/python3.5/dist-packages/tensorflow/python/keras/utils/generic_utils.py in class_and_config_for_serialized_keras_object(config, module_objects, custom_objects, printable_module_name)
    164     cls = module_objects.get(class_name)
    165     if cls is None:
--> 166       raise ValueError('Unknown ' + printable_module_name + ': ' + class_name)
    167   return (cls, config['config'])
    168 

ValueError: Unknown layer: ProposalLayer

我用来导入keras模型的代码是:

converter = tf.lite.TFLiteConverter.from_keras_model_file('mrcnn.h5')

你知道如何解决这个问题吗?

【问题讨论】:

    标签: python tensorflow keras tensorflow-lite


    【解决方案1】:

    Keras-h5 保存只知道标准层。

    这里有三种可能的修复方法:

    1) from_keras_model 方法有一个名为 custom_objects 的参数。如果您的类正确实现了get_config,并且您将其传递给您的类:custom_objects={"ProposalLayer":my_layers.ProposalLayer},那么它可能会起作用。

    比如需要重新加载模型here

    2) 另一种选择是使用functional api 定义模型,keras 保存和加载更好地支持它。

    3) 如果您可以使用不同的文件格式:试试save_format="tf" 参数。 TensorFlow-SavedModel 可能没有这个问题,因为它保存了较低级别的表示。

    【讨论】:

    • 我尝试了您提出的第一个解决方案,但它抱怨构造函数参数。该层采用两个位置参数。我尝试创建对象(使用正确的参数),然后将其传递到地图中,但它仍然抱怨构造函数参数
    • 对于您建议工作的第 3 个解决方案,模型应该是 tf.keras.model,而我的是 keras.model 文件(保存方法没有该参数)
    • 好点。我认为您需要检查层的get_config 方法。 AFAIK 需要将 args 转换为 json,并且在重建模型时,正是该 json **解包到构造函数中。更新了答案。
    【解决方案2】:
    custom_objects={"ProposalLayer":ProposalLayer}
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-09-28
      • 1970-01-01
      • 2023-01-03
      • 1970-01-01
      • 1970-01-01
      • 2022-12-17
      • 1970-01-01
      • 2021-02-22
      相关资源
      最近更新 更多