Search code examples
tensorflowkerashdf5tf.keras

Convert TensorFlow model to Keras hdf5


Hey I am new to tensorflow and keras. I am wondering if there are any way to convert my tensorflow model which has four files:

  • checkpoint
  • model
  • model-18540.data-00000-of-00001
  • model-18540.index

Are there any way to convert these four files into a single keras file format to hdf5


Solution

  • Currently, there is no direct in-built support in Tensorflow or Keras to convert the frozen model or the checkpoint file to hdf5 format.

    But you can do it in this way.The ckpt file can be saved by TF with:

    saver = tf.train.Saver()
    saver.save(sess, checkpoint_name)
    

    and to load checkpoint in Keras, you need a callback class as follow:

    class RestoreCkptCallback(keras.callbacks.Callback):
        def __init__(self, pretrained_file):
            self.pretrained_file = pretrained_file
            self.sess = keras.backend.get_session()
            self.saver = tf.train.Saver()
        def on_train_begin(self, logs=None):
            if self.pretrian_model_path:
                self.saver.restore(self.sess, self.pretrian_model_path)
                print('load weights: OK.')
    

    Then in your keras script:

     model.compile(loss='categorical_crossentropy', optimizer='rmsprop')
     restore_ckpt_callback = RestoreCkptCallback(pretrian_model_path='./XXXX.ckpt') 
     model.fit(x_train, y_train, batch_size=128, epochs=20, callbacks=[restore_ckpt_callback])