歡迎您光臨本站 註冊首頁

解決Tensorflow2.0 tf.keras.Model.load

←手機掃碼閱讀     ml5rwbikls @ 2020-06-13 , reply:0

錯誤描述:

1、保存模型:model.save_weights('./model.h5')

2、腳本重啟

3、加載模型:model.load_weights('./model.h5')

4、模型報錯:ValueError: You are trying to load a weight file containing 12 layers into a model with 0 layers.

問題分析:

模型創建後還沒有編譯,一般是在模型加載前調用model.build(input_shape), 但我通過Dataset將輸入已經變為dict格式了,暫時沒找這樣輸入怎麼匹配input_shape參數

解決方法:

model.fit(train_dataset, epochs=0)

將epochs設為0,這樣模型在編譯的同時不會訓練數據,減少耗費的時間,之後就可以正常加載保存的參數了

補充知識:調用Kears中kears.model.load_model方法遇到的問題和解決方法

之前一直使用tf和pytorch,就算是tf也是tf.estimator用得比較多,很少使用keras,最近嘗試使用kears快速訓練和部署一些分類任務,在使用load_model的時候遇到一些問題

問題1:

SystemError: unknown opcode

原因是因為模型定義用到了lambda

gap = Lambda(lambda x: x[0]/x[1], name = 'RescaleGAP')([gap_features, gap_mask])

我在python3.5的環境訓練的模型,python3.6的環境load模型。兩個環境的lambda有差異,這個問題。

問題2:

ValueError: Unknown metric function:****

我的錯誤是

ValueError: Unknown metric function:top_2_accuracy

因為在構建模型時,使用了自己定義的top_2_accuracy方法,所以在load_model時需要將top_2_accuracy做為參數傳進去

  from keras.models import load_model  from keras.metrics import top_k_categorical_accuracy     def top_2_accuracy(in_gt, in_pred):    return top_k_categorical_accuracy(in_gt, in_pred, k=2)     model = load_model("model.h5",custom_objects={'top_2_accuracy': top_2_accuracy})

 

         

   


[ml5rwbikls ] 解決Tensorflow2.0 tf.keras.Model.load已經有534次圍觀

http://coctec.com/docs/python/shhow-post-238388.html