使用keras調用load_model時報錯ValueError: Unknown Layer:LayerName

出現該錯誤是因爲要保存的model中包含了自定義的層(Custom Layer),導致加載模型的時候無法解析該Layer。詳見can not load_model() if my model contains my own Layer

該issue下的解決方法不夠全,綜合了一下後可得完整解決方法如下:
load_model函數中添加custom_objects參數,該參數接受一個字典,鍵值爲自定義的層:

model = load_model(model_path, custom_objects={'AttLayer': 
AttLayer})  # 假設自定義的層的名字爲AttLayer

添加該語句後,可能會解決問題,也可能出現新的Error:
init() got an unexpected keyword argument ‘name’, 爲解決該Error,可以參照keras-team的寫法,在自定義的層中添加get_config函數,該函數定義形如:

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

其中,config屬性中的定義是自定義層中__init__函數的參數,__init__函數如下:

def __init__(self, attention_dim, **kwargs):    
    self.init = initializers.get('normal')    
    self.supports_masking = True    
    self.attention_dim = attention_dim    
    super(AttLayer, self).__init__()

注意:
1、__init__函數中需添加**kwargs參數

2、只需要將__init__函數的參數寫入config屬性中,__init__函數體中的內容不必加進去,get_config函數其他部分也無需改動,否則會報錯

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章