1. 程式人生 > 程式設計 >在Keras中實現儲存和載入權重及模型結構

在Keras中實現儲存和載入權重及模型結構

1. 儲存和載入模型結構

(1)儲存為JSON字串

json_string = model.to_json()

(2)從JSON字串重構模型

from keras.models import model_from_json
model = model_from_json(json_string)

(3)儲存為YAML字串

yaml_string = model.to_yaml()

(4)從YAML字串重構模型

model = model_from_yaml(yaml_string)

2. 儲存和載入模型權重(引數)

from keras.models import load_model
 
# 建立HDF5檔案'my_model.h5',儲存模型引數
model.save('my_model.h5')
 
# 載入模型引數
load_model('my_model.h5')

2.1 處理已儲存模型中的自定義層(或其他自定義物件)

如果要載入的模型包含自定義層或其他自定義類或函式,則可以通過 custom_objects 引數將它們傳遞給載入機制:

from keras.models import load_model
 
# 假設你的模型包含一個 AttentionLayer 類的例項
model = load_model('my_model.h5',custom_objects={'AttentionLayer': AttentionLayer})

或者,你可以使用 自定義物件作用域:

from keras.utils import CustomObjectScope
with CustomObjectScope({'AttentionLayer': AttentionLayer}):
  model = load_model('my_model.h5')

自定義物件的處理與 load_model,model_from_json,model_from_yaml 的工作方式相同:

from keras.models import model_from_json
model = model_from_json(json_string,custom_objects={'AttentionLayer': AttentionLayer})

2019年6月1號更新:

更詳細的使用方法:

如何儲存Keras模型?

(1)一個HDF5檔案即儲存模型的結構又儲存模型的權重

我們不推薦使用pickle或cPickle來儲存Keras模型。

你可以使用model.save(filepath)將Keras模型和權重儲存在一個HDF5檔案中,該檔案將包含:

模型的結構,以便重構該模型

模型的權重

訓練配置(損失函式,優化器等)

優化器的狀態,以便於從上次訓練中斷的地方開始

使用keras.models.load_model(filepath)來重新例項化你的模型,如果檔案中儲存了訓練配置的話,該函式還會同時完成模型的編譯。

例子:

from keras.models import load_model
 
model.save('my_model.h5') # creates a HDF5 file 'my_model.h5'
del model # deletes the existing model
 
# returns a compiled model
# identical to the previous one
model = load_model('my_model.h5')

(2)只儲存模型的結構

如果你只是希望儲存模型的結構,而不包含其權重或配置資訊,可以使用:

# save as JSON
json_string = model.to_json()
 
# save as YAML
yaml_string = model.to_yaml()

這項操作將把模型序列化為json或yaml檔案,這些檔案對人而言也是友好的,如果需要的話你甚至可以手動開啟這些檔案並進行編輯。

當然,你也可以從儲存好的json檔案或yaml檔案中載入模型:

# model reconstruction from JSON:
from keras.models import model_from_json
model = model_from_json(json_string)
 
# model reconstruction from YAML
model = model_from_yaml(yaml_string)

(3)只儲存模型的權重

如果需要儲存模型的權重,可通過下面的程式碼利用HDF5進行儲存。注意,在使用前需要確保你已安裝了HDF5和其Python庫h5py。

model.save_weights('my_model_weights.h5')

如果你需要在程式碼中初始化一個完全相同的模型,請使用:

model.load_weights('my_model_weights.h5')

如果你需要載入權重到不同的網路結構(有些層一樣)中,例如fine-tune或transfer-learning,你可以通過層名字來載入模型:

model.load_weights('my_model_weights.h5',by_name=True)

例如:

"""
假如原模型為:
  model = Sequential()
  model.add(Dense(2,input_dim=3,name="dense_1"))
  model.add(Dense(3,name="dense_2"))
  ...
  model.save_weights(fname)
"""
# new model
model = Sequential()
model.add(Dense(2,name="dense_1")) # will be loaded
model.add(Dense(10,name="new_dense")) # will not be loaded
 
# load weights from first model; will only affect the first layer,dense_1.
model.load_weights(fname,by_name=True)

以上這篇在Keras中實現儲存和載入權重及模型結構就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支援我們。