whole-model_saving(整个模型保存)
You can save a model built with the Functional API into a single file. You can later recreate the same model from this file, even if you no longer have access to the code that created the model.
This file includes:
The model’s architecture
The model’s weight values (which were learned during training)
The model’s training config (what you passed to compile), if any
The optimizer and its state, if any (this enables you to restart training where you left)
a Functional model or a Sequential model的保存方式
# Save the model
model.save('path_to_my_model.h5')
# Recreate the exact same model purely from the file
new_model = keras.models.load_model('path_to_my_model.h5')
import numpy as np
# Check that the state is preserved
new_predictions = new_model.predict(x_test)
np.testing.assert_allclose(predictions, new_predictions, rtol=1e-6, atol=1e-6)
# Note that the optimizer state is preserved as well:
# you can resume training where you left off.
NotImplementedError: Saving the model to HDF5 format requires the model to be a Functional model or a Sequential model. It does not work for subclassed models, because such models are defined via the body of a Python method, which isn’t safely serializable. Consider saving to the Tensorflow SavedModel format (by setting save_format=“tf”) or using save_weights
.
Second approach is by using model.save to save whole model and by using load_model to restore previously stored subclassed model. The following code snippets describe how to implement them.
# Save the model
model.save('path_to_my_model',save_format='tf')
# Recreate the exact same model purely from the file
new_model = keras.models.load_model('path_to_my_model')
subclass 的模型保存
Third approach is by using tf.saved_model.save. This is equivalent to the tf format in model.save. You can once again call load_model to restore the previously saved subclassed model. The following code snippets describe how to implement them.
# Save the model
tf.saved_model.save(model,'my_saved_model')
# Restoring the model
restored_saved_model = keras.models.load_model('my_saved_model')