[英]Can you explain difference between tensorflow loading and hdf5 loading in keras model
我試圖加載我在培訓期間保存的 keras model。所以我去了keras 文檔,在那里我看到了這個。
從 TensorFlow 格式加載權重時,僅支持拓撲加載 (by_name=False)。 Note that topological loading differs slightly between TensorFlow and HDF5 formats for user-defined classes inheriting from tf.keras.Model: HDF5 loads based on a flattened list of weights, while the TensorFlow format loads based on the object-local names of attributes to which圖層在模型的構造函數中分配。
你能解釋一下上面的嗎?
為了清楚起見,讓我們考慮兩種情況。
案例 1:簡單 model 和
案例 2:復雜的 model,其中使用了從tf.keras.Model
繼承的用戶定義類。
當您保存 model 權重(使用model.save_weights
)然后加載權重(使用model.load_weights
)時,默認情況下使用load_weights
加載方法這與 Tensorflow saved_model ('tf') 格式和 'h5' 格式相同。 例如,
loadedh5_model.load_weights('./MyModel_h5.h5')
# the line above is same as the line below (as second and third arguments are default)
#loadedh5_model.load_weights('./MyModel_h5.h5',by_name=False, skip_mismatch=False)
如果要加載已保存 model 的特定層的權重,則需要使用by_name=True
。 有些用例需要這種類型的加載。
loadedh5_model.load_weights('./MyModel_h5.h5',by_name=True, skip_mismatch=False)
到目前為止,僅當在 model 創建中使用從tf.keras.Model
繼承的用戶定義類時,才支持“tf”格式。
從 TensorFlow 格式加載權重時,僅支持拓撲加載 (by_name=False)。 Note that topological loading differs slightly between TensorFlow and HDF5 formats for user-defined classes inheriting from tf.keras.Model: HDF5 loads based on a flattened list of weights, while the TensorFlow format loads based on the object-local names of attributes to which圖層在模型的構造函數中分配。
主要原因是權重采用h5
格式和tf
格式。 例如,考慮Case 1
,其中 HDF5 基於扁平化的權重列表進行加載。 重量加載沒有任何錯誤。 但是,在Case 2
中,model 具有user defined classes
,這需要與僅加載扁平權重不同的方法。 為了照顧分配自定義類的權重,'tf' 格式根據模型構造函數中分配層的屬性的對象本地名稱加載權重。
keras網站中提到的以下段落,進一步闡明
加載 TensorFlow 格式的權重文件時,返回與 tf.train.Checkpoint.restore 相同的狀態 object。 構建圖形時,一旦構建網絡,恢復操作就會自動運行(第一次調用從 Model 繼承的用戶定義類,如果它已經構建,則立即)。
要理解的另一點是 keras Functional
或Sequential
模型是 static 層圖,可以毫無問題地使用展平權重。 Keras 子類 model(在我們的案例 2 中)是一段 Python 代碼(調用方法)。 沒有圖層圖。 因此,一旦使用自定義類構建網絡,就會運行恢復操作來更新狀態對象。 希望能幫助到你。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.