How to run multiple graphs in a Session - Tensorflow API

后端 未结 3 1692
情歌与酒
情歌与酒 2021-02-02 14:00

Tensorflow API has provided few pre-trained models and allowed us to trained them with any dataset.

I would like to know how to initialize and use multiple graphs in on

3条回答
  •  醉酒成梦
    2021-02-02 14:14

    I faced the same challenge and after several months of research I was finally able to resolve the issue. I did with tf.graph_util.import_graph_def. According to the documentation:

    name: (Optional.) A prefix that will be prepended to the names in graph_def. Note that this does not apply to imported function names. Defaults to "import".

    Thus by adding this prefix, it is possible to distinguish different sessions.

    For exemple:

    first_graph_def = tf.compat.v1.GraphDef()
    second_graph_def = tf.compat.v1.GraphDef()
    
    # Import the TF graph : first
    first_file = tf.io.gfile.GFile(first_MODEL_FILENAME, 'rb')
    first_graph_def.ParseFromString(first_file.read())
    first_graph = tf.import_graph_def(first_graph_def, name='first')
    
    # Import the TF graph : second
    second_file = tf.io.gfile.GFile(second_MODEL_FILENAME, 'rb')
    second_graph_def.ParseFromString(second_file.read())
    second_graph = tf.import_graph_def(second_graph_def, name='second')
    
    # These names are part of the model and cannot be changed.
    first_output_layer = 'first/loss:0'
    first_input_node = 'first/Placeholder:0'
    
    second_output_layer = 'second/loss:0'
    second_input_node = 'second/Placeholder:0'
    
    # initialize probability tensor
    first_sess = tf.compat.v1.Session(graph=first_graph)
    first_prob_tensor = first_sess.graph.get_tensor_by_name(first_output_layer)
    
    second_sess = tf.compat.v1.Session(graph=second_graph)
    second_prob_tensor = second_sess.graph.get_tensor_by_name(second_output_layer)
    
    first_predictions, = first_sess.run(
            first_prob_tensor, {first_input_node: [adapted_image]})
        first_highest_probability_index = np.argmax(first_predictions)
    
    second_predictions, = second_sess.run(
            second_prob_tensor, {second_input_node: [adapted_image]})
        second_highest_probability_index = np.argmax(second_predictions)
    

    As you see, you are now able to initialize and use multiple graphs in one tensorflow session.

    Hope this will be helpful

提交回复
热议问题