用keras调用load_model时报错ValueError: Unknown Layer:LayerName

出现该错误原因: 保存的model中包含了自定义的层(Custom Layer),导致加载模型的时候无法解析该Layer。参考https://github.com/keras-team/keras/issues/8612

以加入SelfAttention层为例

1. 在load_model函数中添加custom_objects参数,该参数接受一个字典,键值为自定义的层:
model = load_model(model_path, custom_objects={'AttLayer': AttLayer})  # 假设自定义的层的名字为AttLayer

解释:此处 第一个AttLayer 应该替换成打印模型我们看到的该层的名字,即所定义层的类名,如以加入SelfAttention模块为例。
在训练模型时,我们的用法是conv1 = SelfAttention(ch)(x)

from ...  import SelfAttention
attention = SelfAttention()
model = load_model(model_path, custom_objects={'SelfAttention': attention})  
2. 继续报错 ValueError: Unknown Layer:LayerName 这种形式,可尝试使用对象的方法,可能是keras版本不一样的问题,我使用的是keras 2.2.4用的是这个方法:
from keras.utils import CustomObjectScope
with CustomObjectScope({'SelfAttention': attention}):
    model = load_model('my_model.h5')
  1. 可能还会碰到的问题,在SelfAttention( )类定义中,初始化时应该给ch默认值,且需要与传入值一致,比如,层定义时我们对ch传入默认值
    编写自己的层,参考keras官方文档https://keras-cn.readthedocs.io/en/latest/layers/writting_layer/
class SelfAttention(Layer):

   def __init__(self, ch=256, **kwargs):
       super(SelfAttention, self).__init__(**kwargs)
       self.channels = ch
       self.filters_f_g = self.channels // 8
       self.filters_h = self.channels
       super(SelfAttention, self).__init__()

def build(self, input_shape):
def call(self, x):
def compute_output_shape(self, input_shape):

否则加载模型时会告诉你无法完成初始化类错误。

Type Error: __ init__() takes exactly 2 arguments (1 given ) 或者是 通道数维度不匹配等问题

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

友情链接更多精彩内容