[PYTHON] [TensorFlow] Extract features from trained model Inception-v3

In TensorFlow, feature extraction is performed using the Inception-v3 model.

  1. Download the trained model from http://download.tensorflow.org/models/image/imagenet/inception-2015-12-05.tgz
  2. Unzip the above file and extract classify_image_graph_def.pb
  3. Source code feature_extraction.py

ʻRewrite IMG_PATHandMODEL_PATH` according to your environment.

import tensorflow as tf
import numpy as np

IMG_PATH = 'path/to/input/image.jpg'
MODEL_PATH = 'path/to/classify_image_graph_def.pb'

# Loading trained model
inception_v3 = tf.gfile.FastGFile(MODEL_PATH, 'rb')
graph_def =tf.GraphDef()
graph_def.ParseFromString(inception_v3.read())
tf.import_graph_def(graph_def, name='')

with tf.Session() as sess:
 #Specify sampling layer
    pool3 = sess.graph.get_tensor_by_name('pool_3:0')

 #Read input image
    image_data = tf.gfile.FastGFile(IMG_PATH, 'rb').read()

 # Extraction of features
    features = sess.run(pool3, {'DecodeJpeg/contents:0': image_data})
    print(np.squeeze(features))

When inputting a PNG file

The above only accepts JPEG file input. If you want to input a PNG file, specify the'DecodeJpeg: 0'node as shown below when extracting features.

features = sess.run(pool3, {'DecodeJpeg:0':image_data})

Recommended Posts

[TensorFlow] Extract features from trained model Inception-v3
Extract features (features) from sentences.
Use fastText trained model from Python
Extract mobile phone model name from User Agent
Extract data from S3
Extract table from wikipedia