john joy
john joy

Reputation: 31

i have trained MNIST with accuracy 99.2% but with wrong predictions

I have been using this program to predict my handwritten images to predict a number using previously trained data. The following is the program. please help me out.im new to this

This code is used for image processing:

 import numpy as np
 import matplotlib.image as mpimg
 img=mpimg.imread(/images.png')
 def rgb2gray(rgb):
...   return np.dot(rgb[...,:3], [0.299, 0.587, 0.114])
...
>>> gray=rgb2gray(img)
>>> resized_image=cv2.resize(gray,(28,28))
>>> cv2.imwrite("/test.png",resized_image)
True

This is the code fragment I used. Variables have been already trained, saved and restored.

from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

import argparse
import sys

import tensorflow as tf
import matplotlib.image as mpimg
import numpy as np

FLAGS = None

def deepnn(x):

  # Reshape to use within a convolutional neural net.
  # Last dimension is for "features" - there is only one here, since images are
  # grayscale -- it would be 3 for an RGB image, 4 for RGBA, etc.
  with tf.name_scope('reshape'):
    x_image = tf.reshape(x,[-1, 28, 28, 1])

  # First convolutional layer - maps one grayscale image to 32 feature maps.
  with tf.name_scope('conv1'):
    W_conv1 = weight_variable([5, 5, 1, 32])
    b_conv1 = bias_variable([32])
    h_conv1 = tf.nn.relu(conv2d(x_image, W_conv1) + b_conv1)

  # Pooling layer - downsamples by 2X.
  with tf.name_scope('pool1'):
    h_pool1 = max_pool_2x2(h_conv1)

  # Second convolutional layer -- maps 32 feature maps to 64.
  with tf.name_scope('conv2'):
    W_conv2 = weight_variable([5, 5, 32, 64])
    b_conv2 = bias_variable([64])
    h_conv2 = tf.nn.relu(conv2d(h_pool1, W_conv2) + b_conv2)

  # Second pooling layer.
  with tf.name_scope('pool2'):
    h_pool2 = max_pool_2x2(h_conv2)

  # Fully connected layer 1 -- after 2 round of downsampling, our 28x28 image
  # is down to 7x7x64 feature maps -- maps this to 1024 features.
  with tf.name_scope('fc1'):
    W_fc1 = weight_variable([7 * 7 * 64, 1024])
    b_fc1 = bias_variable([1024])

    h_pool2_flat = tf.reshape(h_pool2, [-1, 7*7*64])
    h_fc1 = tf.nn.relu(tf.matmul(h_pool2_flat, W_fc1) + b_fc1)

  # Dropout - controls the complexity of the model, prevents co-adaptation of
  # features.
  with tf.name_scope('dropout'):
    keep_prob = tf.placeholder(tf.float32)
    h_fc1_drop = tf.nn.dropout(h_fc1, keep_prob)

  # Map the 1024 features to 10 classes, one for each digit
  with tf.name_scope('fc2'):
    W_fc2 = weight_variable([1024, 10])
    b_fc2 = bias_variable([10])

    y_conv = tf.matmul(h_fc1_drop, W_fc2) + b_fc2
  return y_conv, keep_prob


def conv2d(x, W):
  """conv2d returns a 2d convolution layer with full stride."""
  return tf.nn.conv2d(x, W, strides=[1, 1, 1, 1], padding='SAME')


def max_pool_2x2(x):
  """max_pool_2x2 downsamples a feature map by 2X."""
  return tf.nn.max_pool(x, ksize=[1, 2, 2, 1],
                        strides=[1, 2, 2, 1], padding='SAME')


def weight_variable(shape):
  """weight_variable generates a weight variable of a given shape."""
  initial = tf.truncated_normal(shape, stddev=0.1)
  return tf.Variable(initial)


def bias_variable(shape):
  """bias_variable generates a bias variable of a given shape."""
  initial = tf.constant(0.1, shape=shape)
  return tf.Variable(initial)


def main(_):

  # Create the model
  x = tf.placeholder(tf.float32, [None, 784])


  # Build the graph for the deep net
  y_conv, keep_prob = deepnn(x)



  saver=tf.train.Saver()

  with tf.Session() as sess:
    saver.restore(sess,"C:/Users/Joe_John/Desktop/model.ckpt")
    print("Model restored.")
    img = mpimg.imread('C:/Users/Joe_John/Desktop/test.png')
    p = np.asarray(img).reshape(1, 784)
    print(p)
    z=sess.run(y_conv
               ,feed_dict={x:p,keep_prob:1.0})
    print('this is z',z)
    prediction=tf.argmax(y_conv,1)
    print(sess.run(prediction,feed_dict={x:p,keep_prob:1.0}))
    predict_=tf.nn.softmax(y_conv)
    print(sess.run(predict_,feed_dict={x:p,keep_prob:1.0}))


if __name__ == '__main__':
  parser = argparse.ArgumentParser()
  parser.add_argument('--data_dir', type=str,
                      default='/tmp/tensorflow/mnist/input_data',
                      help='Directory for storing input data')
  FLAGS, unparsed = parser.parse_known_args()
  tf.app.run(main=main, argv=[sys.argv[0]] + unparsed'


following is the output

after accuracy [-0.10007022  0.19623001 -0.03660678 -0.08034142  0.05941308  0.25028974
 -0.02256322  0.14994892 -0.3642419  -0.05205835]
[[ 0.09007561  0.11646919  0.09577192  0.09184043  0.10344592  0.12991495
   0.09663657  0.11345788  0.06937791  0.0930096 ]]
6

Here are the image files I used:

enter image description here

Upvotes: 2

Views: 1220

Answers (2)

Josh Payne
Josh Payne

Reputation: 373

It looks like your image is white-on-black. However, the MNIST dataset is black on white, so you may want to invert the pixel values. Also, if you're normalizing the mnist data to a scale of [0,1], you may also have to normalize your pixel values to that scale by dividing by 255.0. Hope this helps!

Upvotes: 1

Ari Kanevsky
Ari Kanevsky

Reputation: 63

I'm not very familiar with TF, but some quick online research leads me to believe that you don't pass the result of argmax into sess.run(), but rather:

prediction=tf.argmax(y_conv,1)
print prediction.eval(feed_dict={x:p,keep_prob:1.0})

Another option, which I believe you may have been going for:

prediction=tf.argmax(logits,1)
best = sess.run([prediction],feed_dict)

Again, i'm not super familiar, but maybe this is a step in the right direction.

Source for my answer: https://github.com/tensorflow/tensorflow/issues/97

Happy deep learning :)

Upvotes: 0

Related Questions