How to pass images to the model for classification in Tensorflow
Question: I have created a model using the following code below:

    
    
    # Deep Learning    
    # In[25]:
    
    from __future__ import print_function
    import numpy as np
    import tensorflow as tf
    from six.moves import cPickle as pickle
    from six.moves import range
    
    
    # In[37]:
    
    pickle_file = 'notMNIST.pickle'
    
    with open(pickle_file, 'rb') as f:
      save = pickle.load(f)
      train_dataset = save['train_dataset']
      train_labels = save['train_labels']
      valid_dataset = save['valid_dataset']
      valid_labels = save['valid_labels']
      test_dataset = save['test_dataset']
      test_labels = save['test_labels']
      del save  # hint to help gc free up memory
      print('Training set', train_dataset.shape, train_labels.shape)
      print('Validation set', valid_dataset.shape, valid_labels.shape)
      print('Test set', test_dataset.shape, test_labels.shape)
      print(test_labels)
    
    
    # Reformat into a TensorFlow-friendly shape:
    # - convolutions need the image data formatted as a cube (width by height by #channels)
    # - labels as float 1-hot encodings.
    
    # In[38]:
    
    image_size = 28
    num_labels = 10
    num_channels = 1 # grayscale
    
    import numpy as np
    
    def reformat(dataset, labels):
      dataset = dataset.reshape(
        (-1, image_size, image_size, num_channels)).astype(np.float32)
      #print(np.arange(num_labels))
      labels = (np.arange(num_labels) == labels[:,None]).astype(np.float32)
      #print(labels[0,:])
      print(labels[0])
      return dataset, labels
    train_dataset, train_labels = reformat(train_dataset, train_labels)
    valid_dataset, valid_labels = reformat(valid_dataset, valid_labels)
    test_dataset, test_labels = reformat(test_dataset, test_labels)
    print('Training set', train_dataset.shape, train_labels.shape)
    print('Validation set', valid_dataset.shape, valid_labels.shape)
    print('Test set', test_dataset.shape, test_labels.shape)
    #print(labels[0])
    
    
    # In[39]:
    
    def accuracy(predictions, labels):
      return (100.0 * np.sum(np.argmax(predictions, 1) == np.argmax(labels, 1))
              / predictions.shape[0])
    
    
    # Let's build a small network with two convolutional layers, followed by one fully connected layer. Convolutional networks are more expensive computationally, so we'll limit its depth and number of fully connected nodes.
    
    # In[47]:
    
    batch_size = 16
    patch_size = 5
    depth = 16
    num_hidden = 64
    
    graph = tf.Graph()
    
    with graph.as_default():
    
      # Input data.
      tf_train_dataset = tf.placeholder(
        tf.float32, shape=(batch_size, image_size, image_size, num_channels))
      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.
      layer1_weights = tf.Variable(tf.truncated_normal(
          [patch_size, patch_size, num_channels, depth], stddev=0.1),name="layer1_weights")
      layer1_biases = tf.Variable(tf.zeros([depth]),name = "layer1_biases")
      layer2_weights = tf.Variable(tf.truncated_normal(
          [patch_size, patch_size, depth, depth], stddev=0.1),name = "layer2_weights")
      layer2_biases = tf.Variable(tf.constant(1.0, shape=[depth]),name ="layer2_biases")
      layer3_weights = tf.Variable(tf.truncated_normal(
          [image_size // 4 * image_size // 4 * depth, num_hidden], stddev=0.1),name="layer3_biases")
      layer3_biases = tf.Variable(tf.constant(1.0, shape=[num_hidden]),name = "layer3_biases")
      layer4_weights = tf.Variable(tf.truncated_normal(
          [num_hidden, num_labels], stddev=0.1),name = "layer4_weights")
      layer4_biases = tf.Variable(tf.constant(1.0, shape=[num_labels]),name = "layer4_biases")
    
      # Model.
      def model(data):
        conv = tf.nn.conv2d(data, layer1_weights, [1, 2, 2, 1], padding='SAME')
        hidden = tf.nn.relu(conv + layer1_biases)
        conv = tf.nn.conv2d(hidden, layer2_weights, [1, 2, 2, 1], padding='SAME')
        hidden = tf.nn.relu(conv + layer2_biases)
        shape = hidden.get_shape().as_list()
        reshape = tf.reshape(hidden, [shape[0], shape[1] * shape[2] * shape[3]])
        hidden = tf.nn.relu(tf.matmul(reshape, layer3_weights) + layer3_biases)
        return tf.matmul(hidden, layer4_weights) + layer4_biases
    
      # Training computation.
      logits = model(tf_train_dataset)
      loss = tf.reduce_mean(
        tf.nn.softmax_cross_entropy_with_logits(logits, tf_train_labels))
    
      # Optimizer.
      optimizer = tf.train.GradientDescentOptimizer(0.05).minimize(loss)
    
      # Predictions for the training, validation, and test data.
      train_prediction = tf.nn.softmax(logits)
      valid_prediction = tf.nn.softmax(model(tf_valid_dataset))
      test_prediction = tf.nn.softmax(model(tf_test_dataset))
    
    
    # In[48]:
    
    num_steps = 1001
    #saver = tf.train.Saver()
    with tf.Session(graph=graph) as session:
      tf.initialize_all_variables().run()
      print('Initialized')
      for step in range(num_steps):
        offset = (step * batch_size) % (train_labels.shape[0] - batch_size)
        batch_data = train_dataset[offset:(offset + batch_size), :, :, :]
        batch_labels = train_labels[offset:(offset + batch_size), :]
        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 % 50 == 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))
      save_path = tf.train.Saver().save(session, "/tmp/model.ckpt")
      print("Model saved in file: %s" % save_path)
    

I have saved the model and wrote another python program where i am trying to
restore the model and use it for classification of my images , but i am not
being able to create a 4D tensor of the image , that i have to pass as input
to the model.

The code of the python file is as follows :

    
    
    # In[8]:
    
    from __future__ import print_function
    import numpy as np
    import tensorflow as tf
    from six.moves import cPickle as pickle
    from six.moves import range
    from scipy import ndimage   
    
    # In[9]:
    
    image_size = 28
    num_labels = 10
    num_channels = 1 # grayscale
    import numpy as np
    
    
    # In[10]:
    
    def accuracy(predictions, labels):
      return (100.0 * np.sum(np.argmax(predictions, 1) == np.argmax(labels, 1))
              / predictions.shape[0])
    
    
    # In[15]:
    
    batch_size = 16
    patch_size = 5
    depth = 16
    num_hidden = 64
    pixel_depth =255
    
    graph = tf.Graph()
    
    with graph.as_default():
    
      '''# Input data.
      tf_train_dataset = tf.placeholder(
        tf.float32, shape=(batch_size, image_size, image_size, num_channels))
      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)'''
      tf_train_dataset = tf.placeholder(
        tf.float32, shape=(batch_size, image_size, image_size, num_channels))
      # Variables.
      layer1_weights = tf.Variable(tf.truncated_normal(
          [patch_size, patch_size, num_channels, depth], stddev=0.1),name="layer1_weights")
      layer1_biases = tf.Variable(tf.zeros([depth]),name = "layer1_biases")
      layer2_weights = tf.Variable(tf.truncated_normal(
          [patch_size, patch_size, depth, depth], stddev=0.1),name = "layer2_weights")
      layer2_biases = tf.Variable(tf.constant(1.0, shape=[depth]),name ="layer2_biases")
      layer3_weights = tf.Variable(tf.truncated_normal(
          [image_size // 4 * image_size // 4 * depth, num_hidden], stddev=0.1),name="layer3_biases")
      layer3_biases = tf.Variable(tf.constant(1.0, shape=[num_hidden]),name = "layer3_biases")
      layer4_weights = tf.Variable(tf.truncated_normal(
          [num_hidden, num_labels], stddev=0.1),name = "layer4_weights")
      layer4_biases = tf.Variable(tf.constant(1.0, shape=[num_labels]),name = "layer4_biases")
      saver = tf.train.Saver()
      tf_
      # Model.
      def model(data):
        conv = tf.nn.conv2d(data, layer1_weights, [1, 2, 2, 1], padding='SAME')
        hidden = tf.nn.relu(conv + layer1_biases)
        conv = tf.nn.conv2d(hidden, layer2_weights, [1, 2, 2, 1], padding='SAME')
        hidden = tf.nn.relu(conv + layer2_biases)
        shape = hidden.get_shape().as_list()
        reshape = tf.reshape(hidden, [shape[0], shape[1] * shape[2] * shape[3]])
        hidden = tf.nn.relu(tf.matmul(reshape, layer3_weights) + layer3_biases)
        return tf.matmul(hidden, layer4_weights) + layer4_biases
    
      valid_prediction = tf.nn.softmax(model(tf_valid_dataset))
      #test_prediction = tf.nn.softmax(model(tf_test_dataset))
    
    
    # In[19]:
    
    with tf.Session(graph=graph) as sess:
      # Restore variables from disk.
      saver.restore(sess, "/tmp/model.ckpt")
      print("Model restored.")
      image_data = (ndimage.imread('notMNIST_small/A/QXJyaWJhQXJyaWJhU3RkLm90Zg==.png').astype(float) - 
                        pixel_depth / 2) / pixel_depth
      data = [0:,image_data:,]
      sess.run(valid_prediction,feed_dict={tf_valid_dataset:data})
      # Do some work with the model
    

As you can see in ln[19] i have restored my model and want to pass an image to
the model by creating a 4d Tensor , I am reading the image and then trying to
convert it to a 4d tensor but the ysntax for creating it is wrong in my code ,
thus need help in correcting it .


Answer: Assuming that `image_data` is a _grayscale_ image, it should be a 2-D NumPy
array. You can convert it to a 4-D array with the following:

    
    
    data = image_data[np.newaxis, ..., np.newaxis]
    

The
[`np.newaxis`](http://docs.scipy.org/doc/numpy/reference/arrays.indexing.html#numpy.newaxis)
adds a new dimension of size 1 in the first (batch size) and last (channels)
dimensions. It is equivalent to the following, using
[`np.expand_dims()`](http://docs.scipy.org/doc/numpy-1.10.1/reference/generated/numpy.expand_dims.html):

    
    
    data = np.expand_dims(np.expand_dims(image_data, 0), -1)
    

On the other hand, if you are working with RGB data, you will need to convert
it to fit the model. You could for example define a placeholder for the image
input:

    
    
    input_placeholder = tf.placeholder(tf.float32, shape=[None, image_size, image_size, 3])
    input_grayscale = tf.image.rgb_to_grayscale(input_placeholder)
    
    prediction = tf.nn.softmax(model(input_grayscale))
    
    image_data = ...  # Load from file
    data = image_data[np.newaxis, ...]  # Only add a batch dimension.
    
    prediction_val = sess.run(prediction, feed_dict={input_placeholder: data})
    

