In [17]:
import numpy as np 
import tensorflow as tf 
import matplotlib.pyplot as plt


% matplotlib inline
plt.style.use('ggplot')

Import MNIST Data


In [18]:
from tensorflow.examples.tutorials.mnist import input_data
mnist = input_data.read_data_sets("MNIST_data", one_hot = True)


Extracting MNIST_data/train-images-idx3-ubyte.gz
Extracting MNIST_data/train-labels-idx1-ubyte.gz
Extracting MNIST_data/t10k-images-idx3-ubyte.gz
Extracting MNIST_data/t10k-labels-idx1-ubyte.gz
  • 55k data points in mnist.train
  • 10k data points in mnist.test
  • 5k data points in mnist.validation

In [19]:
print(mnist.train.images.shape)


(55000, 784)

Plot an Example


In [20]:
plt.imshow(mnist.train.images[0].reshape(28,28))
for i in range(0,9):
    if mnist.train.labels[0][i] == 1:
        print('LABEL:{}' .format(i))


LABEL:7

Create the Simple Model


In [21]:
input_nodes = 28*28
output_nodes = 10
learning_rate = 0.001

# Creating the graph
tf.reset_default_graph()

with tf.name_scope('Placeholders'):
    x = tf.placeholder(dtype=tf.float32, shape=[None, input_nodes], name ='Input')
    y = tf.placeholder(dtype=tf.float32, shape=[None, output_nodes], name = 'Labels')
    x_image = tf.reshape(x, [-1, 28, 28, 1])
tf.summary.image('Input_images', x_image, 3)

with tf.name_scope('Operations'):
    W = tf.get_variable(dtype=tf.float32,
                initializer=tf.random_normal_initializer(mean = 0, stddev=0.1),
                shape=[input_nodes, output_nodes],
                   name = 'W')
    b = tf.get_variable(dtype=tf.float32,
                   initializer=tf.constant_initializer(0.0),
                    shape =[output_nodes],
                    name = 'b'
                   )
    h = tf.nn.softmax(tf.matmul(x,W) + b)

# Cross Entropy 
with tf.name_scope('xEnt'):
    cross_entropy = tf.reduce_mean(-tf.reduce_sum(y * tf.log(h), reduction_indices=[1]))
tf.summary.scalar('Cross_Entropy', cross_entropy) # TB

# Optimiser 
with tf.name_scope('Train'):
    optimiser = tf.train.GradientDescentOptimizer(learning_rate).minimize(cross_entropy)
    
# Accuracy
with tf.name_scope('Accuracy'):
    correct_pediction = tf.equal(tf.arg_max(y,1), tf.arg_max(h,1))
    accuracy = tf.reduce_mean(tf.cast(correct_pediction, tf.float32))
tf.summary.scalar('Accuracy', accuracy) # TB


Out[21]:
<tf.Tensor 'Accuracy_1:0' shape=() dtype=string>

Main Session


In [22]:
%%time 

sess = tf.Session()
sess.run(tf.global_variables_initializer())

# TensorBoard Filewriter 
merged_summary = tf.summary.merge_all()
writer = tf.summary.FileWriter("./tmp/mnist/1")
writer.add_graph(sess.graph)

# Train
batch_size = 100
epoch = 10
epoch_size = 500
n_iter = epoch * epoch_size

for iter in range(n_iter+1):
    xs, ys = mnist.train.next_batch(batch_size)
    sess.run(optimiser, feed_dict={x: xs, y: ys})
    
    if iter % 5 ==0:
        s = sess.run(merged_summary, feed_dict={x:xs, y:ys})
        writer.add_summary(s,iter)
    
    if iter%epoch_size ==0:
        print("Epoch: {} Cross Entropy: {:.2f} " .format(int(iter/epoch_size),
              cross_entropy.eval(feed_dict={x:xs, y:ys}, session=sess)))


---------------------------------------------------------------------------
InvalidArgumentError                      Traceback (most recent call last)
/usr/local/lib/python3.5/dist-packages/tensorflow/python/client/session.py in _do_call(self, fn, *args)
   1021     try:
-> 1022       return fn(*args)
   1023     except errors.OpError as e:

/usr/local/lib/python3.5/dist-packages/tensorflow/python/client/session.py in _run_fn(session, feed_dict, fetch_list, target_list, options, run_metadata)
   1003                                  feed_dict, fetch_list, target_list,
-> 1004                                  status, run_metadata)
   1005 

/usr/lib/python3.5/contextlib.py in __exit__(self, type, value, traceback)
     65             try:
---> 66                 next(self.gen)
     67             except StopIteration:

/usr/local/lib/python3.5/dist-packages/tensorflow/python/framework/errors_impl.py in raise_exception_on_not_ok_status()
    465           compat.as_text(pywrap_tensorflow.TF_Message(status)),
--> 466           pywrap_tensorflow.TF_GetCode(status))
    467   finally:

InvalidArgumentError: only one input size may be -1, not both 0 and 3
	 [[Node: Placeholders/Reshape = Reshape[T=DT_FLOAT, Tshape=DT_INT32, _device="/job:localhost/replica:0/task:0/gpu:0"](_recv_Placeholders/Input_0/_17, Placeholders/Reshape/shape)]]
	 [[Node: Placeholders/Reshape/_23 = _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_34_Placeholders/Reshape", tensor_type=DT_FLOAT, _device="/job:localhost/replica:0/task:0/cpu:0"]()]]

During handling of the above exception, another exception occurred:

InvalidArgumentError                      Traceback (most recent call last)
<ipython-input-22-b53b3f8552d2> in <module>()
----> 1 get_ipython().run_cell_magic('time', '', '\nsess = tf.Session()\nsess.run(tf.global_variables_initializer())\n\n# TensorBoard Filewriter \nmerged_summary = tf.summary.merge_all()\nwriter = tf.summary.FileWriter("./tmp/mnist/1")\nwriter.add_graph(sess.graph)\n\n# Train\nbatch_size = 100\nepoch = 10\nepoch_size = 500\nn_iter = epoch * epoch_size\n\nfor iter in range(n_iter+1):\n    xs, ys = mnist.train.next_batch(batch_size)\n    sess.run(optimiser, feed_dict={x: xs, y: ys})\n    \n    if iter % 5 ==0:\n        s = sess.run(merged_summary, feed_dict={x:xs, y:ys})\n        writer.add_summary(s,iter)\n    \n    if iter%epoch_size ==0:\n        print("Epoch: {} Cross Entropy: {:.2f} " .format(int(iter/epoch_size),\n              cross_entropy.eval(feed_dict={x:xs, y:ys}, session=sess)))')

/usr/local/lib/python3.5/dist-packages/IPython/core/interactiveshell.py in run_cell_magic(self, magic_name, line, cell)
   2113             magic_arg_s = self.var_expand(line, stack_depth)
   2114             with self.builtin_trap:
-> 2115                 result = fn(magic_arg_s, cell)
   2116             return result
   2117 

<decorator-gen-59> in time(self, line, cell, local_ns)

/usr/local/lib/python3.5/dist-packages/IPython/core/magic.py in <lambda>(f, *a, **k)
    186     # but it's overkill for just that one bit of state.
    187     def magic_deco(arg):
--> 188         call = lambda f, *a, **k: f(*a, **k)
    189 
    190         if callable(arg):

/usr/local/lib/python3.5/dist-packages/IPython/core/magics/execution.py in time(self, line, cell, local_ns)
   1183         else:
   1184             st = clock2()
-> 1185             exec(code, glob, local_ns)
   1186             end = clock2()
   1187             out = None

<timed exec> in <module>()

/usr/local/lib/python3.5/dist-packages/tensorflow/python/client/session.py in run(self, fetches, feed_dict, options, run_metadata)
    765     try:
    766       result = self._run(None, fetches, feed_dict, options_ptr,
--> 767                          run_metadata_ptr)
    768       if run_metadata:
    769         proto_data = tf_session.TF_GetBuffer(run_metadata_ptr)

/usr/local/lib/python3.5/dist-packages/tensorflow/python/client/session.py in _run(self, handle, fetches, feed_dict, options, run_metadata)
    963     if final_fetches or final_targets:
    964       results = self._do_run(handle, final_targets, final_fetches,
--> 965                              feed_dict_string, options, run_metadata)
    966     else:
    967       results = []

/usr/local/lib/python3.5/dist-packages/tensorflow/python/client/session.py in _do_run(self, handle, target_list, fetch_list, feed_dict, options, run_metadata)
   1013     if handle is None:
   1014       return self._do_call(_run_fn, self._session, feed_dict, fetch_list,
-> 1015                            target_list, options, run_metadata)
   1016     else:
   1017       return self._do_call(_prun_fn, self._session, handle, feed_dict,

/usr/local/lib/python3.5/dist-packages/tensorflow/python/client/session.py in _do_call(self, fn, *args)
   1033         except KeyError:
   1034           pass
-> 1035       raise type(e)(node_def, op, message)
   1036 
   1037   def _extend_graph(self):

InvalidArgumentError: only one input size may be -1, not both 0 and 3
	 [[Node: Placeholders/Reshape = Reshape[T=DT_FLOAT, Tshape=DT_INT32, _device="/job:localhost/replica:0/task:0/gpu:0"](_recv_Placeholders/Input_0/_17, Placeholders/Reshape/shape)]]
	 [[Node: Placeholders/Reshape/_23 = _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_34_Placeholders/Reshape", tensor_type=DT_FLOAT, _device="/job:localhost/replica:0/task:0/cpu:0"]()]]

Caused by op 'Placeholders/Reshape', defined at:
  File "/usr/lib/python3.5/runpy.py", line 184, in _run_module_as_main
    "__main__", mod_spec)
  File "/usr/lib/python3.5/runpy.py", line 85, in _run_code
    exec(code, run_globals)
  File "/usr/local/lib/python3.5/dist-packages/ipykernel/__main__.py", line 3, in <module>
    app.launch_new_instance()
  File "/usr/local/lib/python3.5/dist-packages/traitlets/config/application.py", line 658, in launch_instance
    app.start()
  File "/usr/local/lib/python3.5/dist-packages/ipykernel/kernelapp.py", line 474, in start
    ioloop.IOLoop.instance().start()
  File "/usr/local/lib/python3.5/dist-packages/zmq/eventloop/ioloop.py", line 177, in start
    super(ZMQIOLoop, self).start()
  File "/usr/local/lib/python3.5/dist-packages/tornado/ioloop.py", line 887, in start
    handler_func(fd_obj, events)
  File "/usr/local/lib/python3.5/dist-packages/tornado/stack_context.py", line 275, in null_wrapper
    return fn(*args, **kwargs)
  File "/usr/local/lib/python3.5/dist-packages/zmq/eventloop/zmqstream.py", line 440, in _handle_events
    self._handle_recv()
  File "/usr/local/lib/python3.5/dist-packages/zmq/eventloop/zmqstream.py", line 472, in _handle_recv
    self._run_callback(callback, msg)
  File "/usr/local/lib/python3.5/dist-packages/zmq/eventloop/zmqstream.py", line 414, in _run_callback
    callback(*args, **kwargs)
  File "/usr/local/lib/python3.5/dist-packages/tornado/stack_context.py", line 275, in null_wrapper
    return fn(*args, **kwargs)
  File "/usr/local/lib/python3.5/dist-packages/ipykernel/kernelbase.py", line 276, in dispatcher
    return self.dispatch_shell(stream, msg)
  File "/usr/local/lib/python3.5/dist-packages/ipykernel/kernelbase.py", line 228, in dispatch_shell
    handler(stream, idents, msg)
  File "/usr/local/lib/python3.5/dist-packages/ipykernel/kernelbase.py", line 390, in execute_request
    user_expressions, allow_stdin)
  File "/usr/local/lib/python3.5/dist-packages/ipykernel/ipkernel.py", line 196, in do_execute
    res = shell.run_cell(code, store_history=store_history, silent=silent)
  File "/usr/local/lib/python3.5/dist-packages/ipykernel/zmqshell.py", line 501, in run_cell
    return super(ZMQInteractiveShell, self).run_cell(*args, **kwargs)
  File "/usr/local/lib/python3.5/dist-packages/IPython/core/interactiveshell.py", line 2717, in run_cell
    interactivity=interactivity, compiler=compiler, result=result)
  File "/usr/local/lib/python3.5/dist-packages/IPython/core/interactiveshell.py", line 2821, in run_ast_nodes
    if self.run_code(code, result):
  File "/usr/local/lib/python3.5/dist-packages/IPython/core/interactiveshell.py", line 2881, in run_code
    exec(code_obj, self.user_global_ns, self.user_ns)
  File "<ipython-input-21-f77a18654b76>", line 11, in <module>
    x_image = tf.reshape(x, [-1, 28, 28, -1])
  File "/usr/local/lib/python3.5/dist-packages/tensorflow/python/ops/gen_array_ops.py", line 2630, in reshape
    name=name)
  File "/usr/local/lib/python3.5/dist-packages/tensorflow/python/framework/op_def_library.py", line 763, in apply_op
    op_def=op_def)
  File "/usr/local/lib/python3.5/dist-packages/tensorflow/python/framework/ops.py", line 2327, in create_op
    original_op=self._default_original_op, op_def=op_def)
  File "/usr/local/lib/python3.5/dist-packages/tensorflow/python/framework/ops.py", line 1226, in __init__
    self._traceback = _extract_stack()

InvalidArgumentError (see above for traceback): only one input size may be -1, not both 0 and 3
	 [[Node: Placeholders/Reshape = Reshape[T=DT_FLOAT, Tshape=DT_INT32, _device="/job:localhost/replica:0/task:0/gpu:0"](_recv_Placeholders/Input_0/_17, Placeholders/Reshape/shape)]]
	 [[Node: Placeholders/Reshape/_23 = _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_34_Placeholders/Reshape", tensor_type=DT_FLOAT, _device="/job:localhost/replica:0/task:0/cpu:0"]()]]

Accuracy


In [ ]:
t_accur = sess.run(accuracy, feed_dict={x:mnist.train.images, y:mnist.train.labels})
print('Test Accuracy: {:4.2f}%' .format(100*t_accur))

In [ ]:
v_accur = sess.run(accuracy, feed_dict={x:mnist.validation.images, y: mnist.validation.labels})
print('Valid Accuracy: {:4.2f}%' .format(100*v_accur))

In [ ]:
t_accur = sess.run(accuracy, feed_dict={x:mnist.test.images, y: mnist.test.labels})
print('Test Accuracy: {:4.2f}%' .format(100*t_accur))