Yamaneko
Yamaneko

Reputation: 3563

How can I retrieve the output from both fc and softmax layers from Inception-v3 in a single run?

I would like to extract the output of both 'pool_3:0' and 'softmax:0' layers. I could run the model twice and, for each run, extract the output of a single layer, but it's a bit wasteful. Is it possible to do it running the model only once?

I'm using the example provided by classify_image.py. Here is the relevant snippet:

def run_inference_on_image(image_data):
  create_graph()
  with tf.Session() as sess:
    # Some useful tensors:
    # 'softmax:0': A tensor containing the normalized prediction across
    #   1000 labels.
    # 'pool_3:0': A tensor containing the next-to-last layer containing 2048
    #   float description of the image.
    # 'DecodeJpeg/contents:0': A tensor containing a string providing JPEG
    #   encoding of the image.
    # Runs the softmax tensor by feeding the image_data as input to the graph.
    softmax_tensor = sess.graph.get_tensor_by_name('softmax:0')
    predictions = sess.run(softmax_tensor,
                           {'DecodeJpeg:0': image_data})
    predictions = np.squeeze(predictions)

    # Creates node ID --> English string lookup.
    node_lookup = NodeLookup()

    top_k = predictions.argsort()[-FLAGS.num_top_predictions:][::-1]
    for node_id in top_k:
      human_string = node_lookup.id_to_string(node_id)
      score = predictions[node_id]
      print('%s (score = %.5f)' % (human_string, score))

    return predictions

Upvotes: 3

Views: 1853

Answers (1)

mrry
mrry

Reputation: 126184

You can pass a list of tensors to Session.run() and TensorFlow will share the work done to compute them:

softmax_tensor = sess.graph.get_tensor_by_name('softmax:0')
pool_3 = sess.graph.get_tensor_by_name('pool_3:0')
predictions, pool3_val = sess.run([softmax_tensor, pool_3],
                                  {'DecodeJpeg:0': image_data})

Upvotes: 6

Related Questions