1. 程式人生 > 程式設計 >keras load model時出現Missing Layer錯誤的解決方式

keras load model時出現Missing Layer錯誤的解決方式

問題描述:訓練結束後,儲存model為hdf5和yaml格式的檔案

yamlFilename = os.path.join(dir,filename)
yamlModel = model.toyaml()
with open(yamlFilename,"w") as yamlFile:
 yamlFile.write(yamlModel)

隨後load model

with open(chkptFilename,'r') as f:
 model_yaml = f.read()
model = KM.model_from_yaml(model_yaml,customs_objects={"dict":dict})
model.load_weights(weightFilename)

但是報錯

問題分析:

經過debug分析,原因出在model建立過程中前面lambda層的inbound_node列表中含有後面層,因此從上到下load時,會找不到後面層。重新建立一次model,然後用model.summary() 可以看出其中的原因。

出現這種情況,可能的原因在於,該lambda層在其他py檔案中定義,然後import進來,前後多次用到這個lambda層的話,在模型編譯過程中,該lambda層可能只編譯了一次,前後層共用之,導致後面層結點出現在前面層的inbound_node列表中。

解決辦法:

不要在其他py檔案中自定義lambda層,直接將其定義在model建立的檔案中。或者直接繼承Layer層,在其他py檔案中重新自定義該層。

補充知識:載入keras模型'tf' is not defined on load_model() - using lambda NameError: name 'tf' is not defined報錯

解決方法如下:

import tensorflow as tf
import keras
model = keras.models.load_model('my_model.h5',custom_objects={'tf': tf})

以上這篇keras load model時出現Missing Layer錯誤的解決方式就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支援我們。