Keras--儲存model檔案和載入model檔案
儲存keras的model檔案和載入keras檔案的方法有很多。keras中的模型主要包括model和weight兩個部分。Json檔案、Yaml檔案、HDF5檔案
儲存model部分的主要方法:一是通過json檔案
Json檔案
- # serialize model to JSON
- model_json = model.to_json()
- with open("model.json", "w") as json_file:
- json_file.write(model_json)
Yaml檔案
- # save as YAML
- yaml_string = model.to_yaml()
儲存權重的方法:通過儲存權重(係數)
HDF5檔案
- # serialize weights to HDF5
- model.save_weights("model.h5")
- print("Saved model to disk")
同時儲存model和權重的方式:
- from keras.models import load_model
- model.save('model_weight.h5') # creates a HDF5 file 'my_model.h5'
載入model的方法
json&hdf5
- # load json and create model
- json_file = open('model.json', 'r')
- loaded_model_json = json_file.read()
- json_file.close()
- loaded_model = model_from_json(loaded_model_json
- from keras.models import load_model
- model = load_model('model.h5')
- # load weights into new model
- loaded_model.load_weights("model.h5")
- print("Loaded model from disk")