Search code examples
pythontensorflowmachine-learningprediction

Predict single Image after training model in tensorflow


I have trained model in tensorflow as follows :

batch_size = 128

graph = tf.Graph()
with graph.as_default():
# Input data. For the training data, we use a placeholder that will be fed
# at run time with a training minibatch.
tf_train_dataset = tf.placeholder(tf.float32,
                                  shape=(batch_size, image_size * image_size))
tf_train_labels = tf.placeholder(tf.float32, shape=(batch_size, num_labels))
tf_valid_dataset = tf.constant(valid_dataset)
tf_test_dataset = tf.constant(test_dataset)

# Variables.
weights = tf.Variable(
    tf.truncated_normal([image_size * image_size, num_labels]))
biases = tf.Variable(tf.zeros([num_labels]))

# Training computation.
logits = tf.matmul(tf_train_dataset, weights) + biases
loss = tf.reduce_mean(
    tf.nn.softmax_cross_entropy_with_logits(labels=tf_train_labels, logits=logits))

# Optimizer.
optimizer = tf.train.GradientDescentOptimizer(0.5).minimize(loss)

# Predictions for the training, validation, and test data.
train_prediction = tf.nn.softmax(logits)
valid_prediction = tf.nn.softmax(
    tf.matmul(tf_valid_dataset, weights) + biases)
test_prediction = tf.nn.softmax(tf.matmul(tf_test_dataset, weights) + biases)

num_steps = 3001
with tf.Session(graph=graph) as session:
  tf.global_variables_initializer().run()
  print("Initialized")
    for step in range(num_steps):
     # Pick an offset within the training data, which has been randomized.
     # Note: we could use better randomization across epochs.
     offset = (step * batch_size) % (train_labels.shape[0] - batch_size)
     # Generate a minibatch.
     batch_data = train_dataset[offset:(offset + batch_size), :]
     batch_labels = train_labels[offset:(offset + batch_size), :]
     # Prepare a dictionary telling the session where to feed the minibatch.
     # The key of the dictionary is the placeholder node of the graph to be fed,
     # and the value is the numpy array to feed to it.
     feed_dict = {tf_train_dataset : batch_data, tf_train_labels : batch_labels}
     _, l, predictions = session.run(
    [optimizer, loss, train_prediction], feed_dict=feed_dict)
    if (step % 500 == 0):
      print("Minibatch loss at step %d: %f" % (step, l))
      print("Minibatch accuracy: %.1f%%" % accuracy(predictions, batch_labels))
      print("Validation accuracy: %.1f%%" % accuracy(
      valid_prediction.eval(), valid_labels))
   print("Test accuracy: %.1f%%" % accuracy(test_prediction.eval(), test_labels))

Now I want to use a single image as input which is going to be reshaped to same format as my training image and get prediction for 10 classes as probabilities. This question has been asked multiple times and I have hard time understating their solutions, one of the best answers is to use this code :

feed_dict = {x: [your_image]}
classification = tf.run(y, feed_dict)
print classification

What is x and y equivalent in my code? lets assume I pick one of images from test dataset to predict as:

img = train_dataset[678]

And I am expecting an array with 10 probabilities.


Solution

  • Let me answer to my own question: First these lines of code must be changed, we have to use None instead of const batch size so we later can feed single image as input:

    tf_train_dataset = tf.placeholder(tf.float32, shape=(None, image_size * image_size),name="train_to_restore")
    tf_train_labels = tf.placeholder(tf.float32, shape=(None, num_labels))
    

    and inside the session I used this code to feed new image to the model:

    from skimage import io
    img = io.imread('newimage.png', as_grey=True)
    nx, ny = img.shape
    img_flat = img.reshape(nx * ny)
    IMG = np.reshape(img,(1,784))
    answer = session.run(train_prediction, feed_dict={tf_train_dataset: IMG})
    print(answer)
    

    My images are 28*28 in training set so make sure your new image is also 28*28 the you have to flatten it to 1*784 and give it to your model and receive probabilities for prediction