-2

My aim is to classify images into ten categories. I have a tfrecord file as input. You can download it here (30 MB). My modified the code according to the answer:

import tensorflow as tf
import tensorflow.contrib.slim as slim
import numpy as np

def my_cnn(images, num_classes, is_training):  # is_training is not used...
    with slim.arg_scope([slim.max_pool2d], kernel_size=[3, 3], stride=2):
        net = slim.conv2d(images, 64, [5, 5])
        net = slim.max_pool2d(net)
        net = slim.conv2d(net, 64, [5, 5])
        net = slim.max_pool2d(net)
        net = slim.flatten(net)
        net = slim.fully_connected(net, 192)
        net = slim.fully_connected(net, num_classes, activation_fn=None)       
        return net

data_path = 'train-some.tfrecords' 

with tf.Graph().as_default():
    batch_size, height, width, channels = 10, 224, 224, 3  
    feature = {'train/image': tf.FixedLenFeature([], tf.string),
               'train/label': tf.FixedLenFeature([], tf.int64)}
    filename_queue = tf.train.string_input_producer([data_path], num_epochs=1)
    reader = tf.TFRecordReader()
    _, serialized_example = reader.read(filename_queue)
    features = tf.parse_single_example(serialized_example, features=feature)
    image = tf.decode_raw(features['train/image'], tf.float32)
    label = tf.cast(features['train/label'], tf.int32)
    image = tf.reshape(image, [224, 224, 3])
    images, labels = tf.train.shuffle_batch([image, label], batch_size, capacity=30, num_threads=1, min_after_dequeue=10)

    num_classes = 10
    logits = my_cnn(images, num_classes, is_training=True)
    probabilities = tf.nn.softmax(logits)


with tf.Session() as sess:
    init_op = [tf.global_variables_initializer(), tf.local_variables_initializer()]
    # Run the init_op, evaluate the model outputs and print the results:
    sess.run(init_op)
    #probabilities = sess.run(probabilities)

    # Create a coordinator, launch the queue runner threads.
    coord = tf.train.Coordinator()
    threads = tf.train.start_queue_runners(sess=sess, coord=coord)
    try:
        while not coord.should_stop():
            while True:
                prob = sess.run(probabilities)
                print('Probabilities Shape:')
                print(prob.shape) 

    except tf.errors.OutOfRangeError:
        # When done, ask the threads to stop.
        print('Done training -- epoch limit reached')
    finally:
        coord.request_stop()
        # Wait for threads to finish.
    coord.join(threads)

    # Save the model
    saver = tf.train.Saver()
    saver.save(sess, './slim_model/custom_model')

Unfortunately, I still have error messages:

ValueError: Tensor Tensor("Softmax:0", shape=(10, 10), dtype=float32) is not an element of this graph.

ValueError: Fetch argument cannot be interpreted as a Tensor. (Tensor Tensor("Softmax:0", shape=(10, 10), dtype=float32) is not an element of this graph.)

poetyi
  • 236
  • 4
  • 13
  • Next step is to save the model and then restore it for inference: https://stackoverflow.com/questions/33759623/tensorflow-how-to-save-restore-a-model – Vijay Mariappan Jun 06 '18 at 22:45
  • what is exactly the problem here?i doesn't print probabilities?do you get an error? – Eliethesaiyan Jun 07 '18 at 02:57
  • The problem is that if I run the model with the tfrecord images there is no result, the process never stops. So it doesn't print anything. – poetyi Jun 08 '18 at 09:22

1 Answers1

2

The issue is with your training. You need to start the queues using tf.train.start_queue_runners that will run a few threads to process and enqueue examples. Create a Coordinator and ask the queue runner to start its threads with the coordinator.

Check the code changes:


with tf.Session() as sess:
    init_op = [tf.global_variables_initializer(), tf.local_variables_initializer()]
    # Run the init_op, evaluate the model outputs and print the results:
    sess.run(init_op)
    #probabilities = sess.run(probabilities)

    # Create a coordinator, launch the queue runner threads.
    coord = tf.train.Coordinator()
    threads = tf.train.start_queue_runners(sess=sess, coord=coord)
    try:
        while not coord.should_stop():
            while True:
                prob = sess.run(probabilities)
                print('Probabilities Shape:')
                print(prob.shape) 

    except tf.errors.OutOfRangeError:
        # When done, ask the threads to stop.
        print('Done training -- epoch limit reached')
    finally:
        coord.request_stop()
        # Wait for threads to finish.
    coord.join(threads)

    # Save the model
    saver = tf.train.Saver()
    saver.save(sess, './slim_model/custom_model'

Output:

 Probabilities Shape:
 (10, 10)
 Probabilities Shape:
 (10, 10)
 Probabilities Shape:
 (10, 10)
 Probabilities Shape:
 (10, 10)
 Probabilities Shape:
 (10, 10)
Done training -- epoch limit reached

Code with the above fixes along with saving and restoring the model can be downloaded from here.

Vijay Mariappan
  • 16,921
  • 3
  • 40
  • 59
  • Thank you so much for your advise, I modified the Question according to your Answer. Unfortunately, it is still not good (Error messages at the end of the question). – poetyi Jun 10 '18 at 15:05
  • Looks like the session you are running is not using the graph defined. Put your ` with tf.Session() as sess:` within `with tf.Graph().as_default():`. Check the complete code here: https://drive.google.com/open?id=1VZdA75Wdl745P-HOf1zMlZOkoxdHWqh_ – Vijay Mariappan Jun 10 '18 at 15:18
  • Don't you have any advice how can I use it for classification? – poetyi Jun 10 '18 at 17:25
  • I have added the code for saving and restoring it back for classification in my answer. – Vijay Mariappan Jun 10 '18 at 18:12
  • Do you have any idea how to solve this problem? ValueError: Cannot feed value of shape () for Tensor 'input:0', which has shape '(?,)' I got this, when I try to restore the model. – poetyi Jun 14 '18 at 09:05
  • I assume this is not related to this code as it does not have a feed input. Check the shape of the input your feeding to input0, if numpy using .shape. They should be same size as the tensor placeholder. – Vijay Mariappan Jun 14 '18 at 09:13