如何从.h5文件正确加载带有自定义图层的Keras模型?

时间:2019-08-15 08:12:18

标签: python-3.x keras keras-layer

我建立了一个具有自定义图层的Keras模型,并通过回调.h5将其保存到ModelCheckPoint文件中。 在训练后尝试加载此模型时,出现以下错误消息:

__init__() missing 1 required positional argument: 'pool_size'

这是自定义层及其__init__方法的定义:

class MyMeanPooling(Layer):
    def __init__(self, pool_size, axis=1, **kwargs):
        self.supports_masking = True
        self.pool_size = pool_size
        self.axis = axis
        self.y_shape = None
        self.y_mask = None
        super(MyMeanPooling, self).__init__(**kwargs)

这是将图层添加到模型中的方法:

x = MyMeanPooling(globalvars.pool_size)(x)

这是我加载模型的方式:

from keras.models import load_model

model = load_model(model_path, custom_objects={'MyMeanPooling': MyMeanPooling})

这些是完整的错误消息:

Traceback (most recent call last):
  File "D:/My Projects/Attention_BLSTM/script3.py", line 9, in <module>
    model = load_model(model_path, custom_objects={'MyMeanPooling': MyMeanPooling})
  File "D:\ProgramData\Anaconda3\envs\tf\lib\site-packages\keras\engine\saving.py", line 419, in load_model
    model = _deserialize_model(f, custom_objects, compile)
  File "D:\ProgramData\Anaconda3\envs\tf\lib\site-packages\keras\engine\saving.py", line 225, in _deserialize_model
    model = model_from_config(model_config, custom_objects=custom_objects)
  File "D:\ProgramData\Anaconda3\envs\tf\lib\site-packages\keras\engine\saving.py", line 458, in model_from_config
    return deserialize(config, custom_objects=custom_objects)
  File "D:\ProgramData\Anaconda3\envs\tf\lib\site-packages\keras\layers\__init__.py", line 55, in deserialize
    printable_module_name='layer')
  File "D:\ProgramData\Anaconda3\envs\tf\lib\site-packages\keras\utils\generic_utils.py", line 145, in deserialize_keras_object
    list(custom_objects.items())))
  File "D:\ProgramData\Anaconda3\envs\tf\lib\site-packages\keras\engine\network.py", line 1022, in from_config
    process_layer(layer_data)
  File "D:\ProgramData\Anaconda3\envs\tf\lib\site-packages\keras\engine\network.py", line 1008, in process_layer
    custom_objects=custom_objects)
  File "D:\ProgramData\Anaconda3\envs\tf\lib\site-packages\keras\layers\__init__.py", line 55, in deserialize
    printable_module_name='layer')
  File "D:\ProgramData\Anaconda3\envs\tf\lib\site-packages\keras\utils\generic_utils.py", line 147, in deserialize_keras_object
    return cls.from_config(config['config'])
  File "D:\ProgramData\Anaconda3\envs\tf\lib\site-packages\keras\engine\base_layer.py", line 1109, in from_config
    return cls(**config)
TypeError: __init__() missing 1 required positional argument: 'pool_size'

3 个答案:

答案 0 :(得分:0)

摘自“ LiamHe在2017年9月27日发表评论”的以下问题:https://github.com/keras-team/keras/issues/4871

我今天遇到了同样的问题:** TypeError:init()缺少1个必需的位置参数**。这是我解决问题的方法:(Keras 2.0.2)

  1. 为图层的位置参数提供一些默认值
  2. 用诸如此类的东西将get_config函数覆盖到该层上
def get_config(self):
    config = super().get_config()
    config['pool_size'] = # say self._pool_size  if you store the argument in __init__
    return config
  1. 在加载模型时将图层类添加到custom_objects。

答案 1 :(得分:0)

实际上,我认为您无法加载此模型。

最可能的问题是您没有在图层中实现get_config()方法。此方法返回应保存的配置值字典:

def get_config(self):
    config = {'pool_size': self.pool_size,
              'axis': self.axis}
    base_config = super(MyMeanPooling, self).get_config()
    return dict(list(base_config.items()) + list(config.items()))

将这种方法添加到图层后,您必须重新训练模型,因为先前保存的模型没有将此图层的配置保存到其中。这就是为什么您不能加载它的原因,进行此更改后需要重新培训。

答案 2 :(得分:0)

如果您没有足够的时间以Matias Valdenegro的解决方法来重新训练模型。您可以在类 MyMeanPooling 中设置 pool_size 的默认值,如以下代码所示。请注意, pool_size 的值应与训练模型时的值一致。然后可以加载模型。

class MyMeanPooling(Layer):
    def __init__(self, pool_size, axis=1, **kwargs):
        self.supports_masking = True
        self.pool_size = 2  # The value should be consistent with the value while training the model
        self.axis = axis
        self.y_shape = None
        self.y_mask = None
        super(MyMeanPooling, self).__init__(**kwargs)

ref:https://www.jianshu.com/p/e97112c34e43