pythontensorflowkerastf.keras

Saving meta data/information in Keras model


Is it possible to save meta data/meta information in Keras model? My goal is to save input pre-processing parameters, train/test set used, class label maps etc. which I can use while loading model again.
I went through Keras documentation and did not find anything. I found similar issue on GitHub but it was closed two years back without any resolution.
Currently I am saving all these information in separate file, and using this file while loading the model.
Although probably not relevant but I am using tf.keras functional model and saving my model as h5 file using model.save().


Solution

  • This is working for me:

    from tensorflow.python.keras.saving import hdf5_format
    import h5py
    
    
    # Save model
    with h5py.File(model_path, mode='w') as f:
        hdf5_format.save_model_to_hdf5(my_keras_model, f)
        f.attrs['param1'] = param1
        f.attrs['param2'] = param2
    
    # Load model
    with h5py.File(model_path, mode='r') as f:
        param1 = f.attrs['param1']
        param2 = f.attrs['param2']
        my_keras_model = hdf5_format.load_model_from_hdf5(f)