[英]Loading the saved models from tf.keras in different versions (From tf 2.3.0 to tf 1.12)
問題:我已經在 tf 2.3.0 中創建並訓練了一個 keras 模型,我需要在 tf 1.12.0 中加載這個模型,以便與需要舊版本 tf. 有什么方法可以將模型從新版本的 tf 格式轉換為舊版本,以便我可以使用 tf 1.12.0 加載模型?
到目前為止我嘗試過的:一個類似的討論展示了如何將模型從 tf 1.15 - 2.1 轉換為 tf.10,但是當我嘗試這個解決方案時,我得到了一個錯誤“未知層:功能”。 鏈接: 從不同版本的 tf.keras 加載保存的模型
我嘗試使用另一個問題建議的以下行來解決此問題:
new_model = tf.keras.models.model_from_json(json_config, custom_objects {'Functional':tf.keras.models.Model})
但是,如果我使用它,我會收到一個錯誤: ('Unrecognized keyword arguments:', dict_keys(['ragged'])) ,這與我在上面鏈接的第一個討論中討論的錯誤相同。
我嘗試的另一種方法是使用 Onnx 庫將 keras 模型轉換為 Onnx 模型,然后再轉換回不同版本的 keras 模型。 但是,我很快意識到 keras2onnx 庫需要 tf 2.x。
鏈接: https : //github.com/onnx/tensorflow-onnx和https://github.com/gmalivenko/onnx2keras
關於如何解決這個問題而不必在舊版本的 tensorflow 中重新訓練我的模型的任何建議將不勝感激! 謝謝
這是我嘗試實現以加載模型的簡單代碼:
保存在 tf 2.3.0
import tensorflow as tf
CNN_model=tf.keras.models.load_model('Real_Image_XAI_Models/Test_10_DC_R_Image.h5')
CNN_model.save_weights("Real_Image_XAI_Models/weights_only.h5")
json_config = CNN_model.to_json()
with open('Real_Image_XAI_Models/model_config.json', 'w') as json_file:
json_file.write(json_config)
在 tf 1.12.0 中加載
with open('Real_Image_XAI_Models/model_config.json') as json_file:
json_config = json_file.read()
new_model = tf.keras.models.model_from_json(json_config)
#or implement the line to acount for the functional class
#new_model = tf.keras.models.model_from_json(json_config, custom_objects={'Functional':tf.keras.models.Model})
new_model.load_weights('Real_Image_XAI_Models/weights_only.h5')
從 tf-1.12.0 到 tf-2.3.0,模型配置主要有兩個重大變化:
您可以嘗試編輯從 tf-2.3.0 保存的模型配置 json 文件,以反轉這些更改的效果,如下所示:
"class_name": "Functional"
替換為"class_name": "Model"
。 這將逆轉上述更改#1 的效果。"ragged": false,
(以及"ragged": true,
如果存在的話)。 這將逆轉上述更改#2 的效果。您可能會嘗試找到一種在 json 字典中或在模型加載時以編程方式進行這些更改的方法,但我發現對 json 文件本身進行這些一次性更改更容易。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.