模型結構存檔:以下程式將結構存到 model.config 檔案,檔案為
JSON或YAML格式。
fromkeras.models import model_from_json
json_string = model.to_json() with open("model.config", "w") as
text_file:
text_file.write(json_string)
權重(W)存檔:以權重(W)存檔:以下程式將權重存到 model.weight
檔案下程式將權重存到 model.weight 檔案
model.save_weights("model.weight")
同時儲存結構與權重,檔案的類別為HDF5
from keras.models import load_model
model.save('model.h5') # creates a HDF5 file 'model.h5'
18.
模型載入,我們要使用時,可輸入下列程式碼,載入模型結構及權重(W)。
import numpy asnp
from keras.models import Sequential
from keras.models import model_from_json
with open("model.config", "r") as text_file:
json_string = text_file.read()
model = Sequential()
model = model_from_json(json_string)
model.load_weights("model.weight", by_name=False)
或者直接載入HDF5檔案
from keras.models import load_model
# 刪除既有模型變數
del model
# 載入模型
model = load_model('my_model.h5')