how to use restored model with tensorflow 2.0

Viewed 2123

The model is built as

    class MyModel(tf.keras.Model):
    
        def __init__(self, num_states, hidden_units, num_actions):
            super(MyModel, self).__init__()
    
            ## btach_size * size_state
            self.input_layer = tf.keras.layers.InputLayer(input_shape=(num_states,))
            self.hidden_layers = []
            for i in hidden_units:
                self.hidden_layers.append(tf.keras.layers.Dense(
                    i, activation='tanh', kernel_initializer='RandomNormal'))
            self.output_layer = tf.keras.layers.Dense(
                num_actions, activation='linear', kernel_initializer='RandomNormal')
    
        
        @tf.function
        def call(self, inputs):
            z = self.input_layer(inputs)
            for layer in self.hidden_layers:
                z = layer(z)
            output = self.output_layer(z)
            return output

after training, the model was saved as:

tf.saved_model.save(self.model, model_path_dir='saved_model/model_checkpoint')

Now, I'm trying to restore the model and then do inference as:

train_agent = tf.saved_model.load('saved_model/model_checkpoint')

## input_state is an array with shape of (num_states, ) 
action = train_agent(np.atleast_2d(input_state)) 

However, I keep getting this error:

TypeError: '_UserObject' object is not callable

How can I exactly use the restored model?

3 Answers

You correctly decorated the call method with tf.function, thus, your SavedModel will have the very same method serialized inside.

Thus, you can just call your model by calling the call method:

action = train_agent.call(np.atleast_2d(input_state)) 

I haven't figure out how to use the tf.saved_model.save() and tf.saved_model.load() properly, if anyone could help, it would be great! Current solution is to use save_weights() instead. For example:

model = Model()
mode.train()
...
model.save_weights(checkpoint_dir)
input_s = np.random.normal(1, 128)
output = model(input_s) ## output a tensor

Required code given below

tf.keras.models.save_model(model_name,path)

import tensorflow as tf
#save the model for later use

tf.keras.models.save_model(classifier_model,'F:/Face_Recognition/face_classifier_model.h5')

#Reload the model
classifier_model=tf.keras.models.load_model('F:/Face_Recognition/face_classifier_model.h5')
Related