Load tensorflow 1 graph and use it as a keras model

So basically i am trying to load a tensorflow model saved as a .pb file (which is a generic type model and not keras model) and would like to use it as a kerras model using tensorflow 2 API , make amendments to the original graph by adding layers etc (using tensorflow 2 API ) and train my model accordingly

@haider_ali Welcome to the TF Forum !!

To use a TensorFlow 1.x model saved as a .pb file in TensorFlow 2.x and make amendments to the original graph by adding layers, you can follow these steps:

Step 1: Load the TensorFlow 1.x model
Step 2: Convert TensorFlow 1.x model to a TensorFlow 2.x model
Step 3: Add layers to the model and train

#
import tensorflow as tf

# Convert the TensorFlow 1.x model to a TensorFlow 2.x model
tf.compat.v1.keras.backend.set_session(tf.compat.v1.Session())
model = tf.compat.v1.keras.models.model_from_tf(tf.compat.v1.keras.backend.get_session(),
                                                tf.compat.v1.train.Saver().as_saver_def())


Please note that the TensorFlow 1.x to TensorFlow 2.x conversion may not always be straightforward, especially for complex models. You may encounter compatibility issues or limitations in certain operations. In such cases, it may be necessary to rebuild the model from scratch using TensorFlow 2.x APIs or consider alternative methods like using the TensorFlow 1.x framework itself.

I got the following error during the execution of my code aftter integrating the snippet of the code provided :

  • AttributeError: module ‘keras.api._v1.keras.models’ has no attribute 'model_from_tf

gist:

import numpy as np
import tensorflow as tf

pb_filepath = “/home/naveed/Desktop/Haider/visemenet-inference/”

model = tf.saved_model.load(pb_filepath)
print(f"type(model): {type(model)}")
tf.compat.v1.keras.backend.set_session(tf.compat.v1.Session())
model = tf.compat.v1.keras.models.model_from_tf(tf.compat.v1.keras.backend.get_session(),
tf.compat.v1.train.Saver().as_saver_def())