Hara Hara Mahadevaki Hara Hara Mahadevaki - 1 month ago 11
Python Question

Using two different models in tensorflow

Im trying to use two different mobilenet models. Following is the code as of how I initialize the model.

def initialSetup():
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'
start_time = timeit.default_timer()

# This takes 2-5 seconds to run
# Unpersists graph from file
with tf.gfile.FastGFile('age/output_graph.pb', 'rb') as f:
age_graph_def = tf.GraphDef()
age_graph_def.ParseFromString(f.read())
tf.import_graph_def(age_graph_def, name='')

with tf.gfile.FastGFile('output_graph.pb', 'rb') as f:
gender_graph_def = tf.GraphDef()
gender_graph_def.ParseFromString(f.read())
tf.import_graph_def(gender_graph_def, name='')

print ('Took {} seconds to unpersist the graph'.format(timeit.default_timer() - start_time))


since both are two different models, how do I use it for predictions?

UPDATE

initialSetup()

age_session = tf.Session(graph=age_graph_def)
gender_session = tf.Session(graph=gender_graph_def)

with tf.Session() as sess:
start_time = timeit.default_timer()

# Feed the image_data as input to the graph and get first prediction
softmax_tensor = age_session.graph.get_tensor_by_name('final_result:0')

print ('Took {} seconds to feed data to graph'.format(timeit.default_timer() - start_time))

while True:
# Capture frame-by-frame
ret, frame = video_capture.read()


ERROR


Traceback (most recent call last): File
"C:/Users/Desktop/untitled/testimg/testimg/combo.py", line 48, in

age_session = tf.Session(graph=age_graph_def) File "C:\Program Files\Anaconda3\lib\site-packages\tensorflow\python\client\session.py",
line 1292, in init
super(Session, self).init(target, graph, config=config) File "C:\Program
Files\Anaconda3\lib\site-packages\tensorflow\python\client\session.py",
line 529, in init
raise TypeError('graph must be a tf.Graph, but got %s' % type(graph)) TypeError: graph must be a tf.Graph, but got Exception ignored in:
> Traceback (most recent call last): File
"C:\Program
Files\Anaconda3\lib\site-packages\tensorflow\python\client\session.py",
line 587, in del
if self._session is not None: AttributeError: 'Session' object has no attribute '_session'

Answer Source

tf.Session requires a tf.Graph instance not tf.GraphDef, following step fix the issue.

def initialSetup():
    with tf.gfile.FastGFile('age/output_graph.pb', 'rb') as f:
        age_graph_def = tf.GraphDef()
        age_graph_def.ParseFromString(f.read())
        with tf.Graph().as_default() as graph:
            tf.import_graph_def(age_graph_def, name='')
            age_graph = graph

   ...
   return age_graph, gender_graph

age_graph, gender_graph = initial_setup() 
age_session = tf.Session(graph=age_graph)
...
# also delete the following line, as it creates another new context 
with tf.Session() as sess: