Tensorflow2.x 模型保存和加载(ValueError: No model found in config file.)

Tensorflow2.x 模型保存和加载

Tensorflow官网教程给出了两种保存整个模型的方法:

  1. SavedModel format
  2. HDF5 format

在自定义模型时遇到了一个问题:

Traceback (most recent call last):
  File "/data/projects/sysml/resNetAll/main.py", line 100, in <module>
    'learning_rate':learning_rate,'decay_rate':decay_rate,
  File "/usr/local/lib/python3.6/dist-packages/tensorflow_core/python/keras/saving/save.py", line 146, in load_model
    return hdf5_format.load_model_from_hdf5(filepath, custom_objects, compile)
  File "/usr/local/lib/python3.6/dist-packages/tensorflow_core/python/keras/saving/hdf5_format.py", line 165, in load_model_from_hdf5
    raise ValueError('No model found in config file.')
ValueError: No model found in config file.

官方给出了解释:

Saving custom objects
If you are using the SavedModel format, you can skip this section. The key difference between HDF5 and SavedModel is that HDF5 uses object configs to save the model architecture, while SavedModel saves the execution graph. Thus, SavedModels are able to save custom objects like subclassed models and custom layers without requiring the orginal code.
To save custom objects to HDF5, you must do the following:

  1. Define a get_config method in your object, and optionally a from_config classmethod.
  • get_config(self) returns a JSON-serializable dictionary of parameters needed to recreate the object.
  • from_config(cls, config) uses the returned config from get_config to create a new object. By default, this function will use the config as initialization kwargs (return cls(**config)).
  1. Pass the object to the custom_objects argument when loading the model. The argument must be a dictionary mapping the string class name to the Python class. E.g. tf.keras.models.load_model(path, custom_objects={‘CustomLayer’: CustomLayer})

大致意思是:当使用自定义的对象时,使用SavedModel不会有问题,但HDF5方法保存模型需要自定义 get_config 方法,否则无法正确加载模型。

你可能感兴趣的:(tensorflow,python)