tensorflowtensorflow-slim

Tensorflow SLIM: feature extraction


I want to extract the features of a slim Inception v4 using Tensorflow, and after hours trying to figure out what's wrong, here am I.

NB_FEATURES_v4 = 1536
IMAGE_SIZE = inception.inception_v4.default_image_size
CHANNELS = 3

def create_graph_v4(model_ckpt):
    input_image = tf.placeholder(tf.float32, shape=(None, None, CHANNELS))
    processed_image = inception_preprocessing.preprocess_image(input_image, IMAGE_SIZE, IMAGE_SIZE, is_training=False)
    processed_images  = tf.expand_dims(processed_image, 0)

    with slim.arg_scope(inception.inception_v4_arg_scope()):
        logits, _ = inception.inception_v4(processed_images, is_training=False)

    init_fn = slim.assign_from_checkpoint_fn(
        model_ckpt,
        slim.get_model_variables('InceptionV4'))
    return input_image


def get_properties_v4(paths, model_ckpt):
    input_image = create_graph_v4(model_ckpt)
    features = np.empty((len(paths), 1536))

    with tf.Session() as sess:
        next_to_last_tensor = sess.graph.get_tensor_by_name('InceptionV4/Logits/PreLogitsFlatten/Reshape:0')
        for ind, image in enumerate(paths):
            if ind % 100 == 0:
                print('Processing %s...' % (image))

            image_file = Image.open(image)
            predictions = sess.run(next_to_last_tensor,
                                   feed_dict={input_image: image_file})
            features[ind, :] = np.squeeze(predictions)
    return features

model_ckpt = 'inception_v4.ckpt'

paths = ['A.jpg',
         'B.jpg']

features = get_properties_v4(paths, model_ckpt)

I get the following error:

FailedPreconditionError: Attempting to use uninitialized value InceptionV4/Conv2d_1a_3x3/weights
     [[Node: InceptionV4/Conv2d_1a_3x3/weights/read = Identity[T=DT_FLOAT, _class=["loc:@InceptionV4/Conv2d_1a_3x3/weights"], _device="/job:localhost/replica:0/task:0/gpu:0"](InceptionV4/Conv2d_1a_3x3/weights)]]
     [[Node: InceptionV4/Logits/PreLogitsFlatten/Reshape/_15 = _Recv[client_terminated=false, recv_device="/job:localhost/replica:0/task:0/cpu:0", send_device="/job:localhost/replica:0/task:0/gpu:0", send_device_incarnation=1, tensor_name="edge_2794_InceptionV4/Logits/PreLogitsFlatten/Reshape", tensor_type=DT_FLOAT, _device="/job:localhost/replica:0/task:0/cpu:0"]()]]

When I don't factor the code into functions, everything seems to be working. Can someone see what I'm doing wrong here?

Thanks a lot!


Solution

  • You setup an init function but you never call it. I'd move the init_fn to get_properties, then call init_fn(sess) right after you create the session.