当前位置:网站首页>How keras saves and loads the keras model
How keras saves and loads the keras model
2022-04-23 07:21:00 【sunshinecxm_ BJTU】
One 、 How to save Keras Model ?
1. preservation / Load the whole model ( structure + The weight + Optimizer status )
Not recommended pickle or cPickle To preserve Keras Model .
You can use model.save(filepath) take Keras Save the model to a single file HDF5 In file , The file will contain :
- Structure of model , Allows you to recreate the model
- Model weight Training configuration item ( Loss function , Optimizer )
- Optimizer status , Allow you to continue training exactly where you ended last time .
You can use keras.models.load_model(filepath) Re instantiate the model .load_model You will also be responsible for compiling the model using the saved training configuration items ( Unless the model has never been compiled ).
Example :
from keras.models import load_model
model.save('my_model.h5') # establish HDF5 file 'my_model.h5'
del model # Delete existing model
# Return a compiled model
# Same as the one before
model = load_model('my_model.h5')
See also How to install HDF5 or h5py In the Keras Save my model in ?, See how to install h5py Explanation .
2. Save only / Load the structure of the model
If you only need to save the structure of the model , Instead of its weight or training configuration item , You can do the following :
# Save as JSON
json_string = model.to_json()
# Save as YAML
yaml_string = model.to_yaml()
Generated JSON/YAML Files are human readable , You can also edit it manually if necessary .
You can build a new model from this data :
# from JSON Reconstruction model :
from keras.models import model_from_json
model = model_from_json(json_string)
# from YAML Reconstruction model :
from keras.models import model_from_yaml
model = model_from_yaml(yaml_string)
3. Save only / Load the weight of the model
If you only need Model weight , You can use the following code to HDF5 Format to save .
Please note that , We need to install... First HDF5 and Python library h5py, They are not included in Keras in .
model.save_weights('my_model_weights.h5')
Suppose you have code for instantiating the model , Then the saved weights can be loaded into the model with the same structure :
model.load_weights('my_model_weights.h5')
If you need to load weights into different structures ( There are some common layers ) In the model of , For example, fine tune or transfer learning , You can load the weight by the name of the layer :
model.load_weights('my_model_weights.h5', by_name=True)
Example :
"""
Suppose the original model is as follows :
model = Sequential()
model.add(Dense(2, input_dim=3, name='dense_1'))
model.add(Dense(3, name='dense_2'))
...
model.save_weights(fname)
"""
# The new model
model = Sequential()
model.add(Dense(2, input_dim=3, name='dense_1')) # Will be loaded
model.add(Dense(10, name='new_dense')) # Will not be loaded
# Load weights from the first model ; It will only affect the first layer ,dense_1
model.load_weights(fname, by_name=True)
4. Working with custom layers in a saved model ( Or other custom objects )
If the model to be loaded contains custom layers or other custom classes or functions , You can use the custom_objects Parameters are passed to the loading mechanism :
from keras.models import load_model
# Suppose your model contains a AttentionLayer Class
model = load_model('my_model.h5', custom_objects={
'AttentionLayer': AttentionLayer})
perhaps , You can use Custom object scope :
from keras.utils import CustomObjectScope
with CustomObjectScope({
'AttentionLayer': AttentionLayer}):
model = load_model('my_model.h5')
Processing and of custom objects load_model, model_from_json, model_from_yaml They work the same way :
from keras.models import model_from_json
model = model_from_json(json_string, custom_objects={
'AttentionLayer': AttentionLayer})
版权声明
本文为[sunshinecxm_ BJTU]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/04/202204230610529676.html
边栏推荐
猜你喜欢

C language, a number guessing game

【点云系列】Neural Opacity Point Cloud(NOPC)

红外传感器控制开关
![[recommendation of new books in 2021] practical IOT hacking](/img/9a/13ea1e7df14a53088d4777d21ab1f6.png)
[recommendation of new books in 2021] practical IOT hacking

第4章 Pytorch数据处理工具箱

【点云系列】Multi-view Neural Human Rendering (NHR)
![[recommendation for new books in 2021] professional azure SQL managed database administration](/img/f1/b38cce1dc328a5b534011169909127.png)
[recommendation for new books in 2021] professional azure SQL managed database administration

Machine learning notes 1: learning ideas

MySQL installation and configuration - detailed tutorial

Component based learning (1) idea and Implementation
随机推荐
MySQL5. 7 insert Chinese data and report an error: ` incorrect string value: '\ xb8 \ XDF \ AE \ xf9 \ X80 at row 1`
去掉状态栏
Pymysql connection database
Machine learning II: logistic regression classification based on Iris data set
【点云系列】Learning Representations and Generative Models for 3D pointclouds
[2021 book recommendation] learn winui 3.0
[dynamic programming] different binary search trees
[Point Cloud Series] SG - Gan: Adversarial Self - attachment GCN for Point Cloud Topological parts Generation
Compression and acceleration technology of deep learning model (I): parameter pruning
Miscellaneous learning
[dynamic programming] longest increasing subsequence
Bottom navigation bar based on bottomnavigationview
【2021年新书推荐】Red Hat Certified Engineer (RHCE) Study Guide
[point cloud series] pnp-3d: a plug and play for 3D point clouds
【動態規劃】不同路徑2
第4章 Pytorch数据处理工具箱
[recommendation of new books in 2021] practical IOT hacking
SSL/TLS应用示例
Gobang games
第3章 Pytorch神经网络工具箱