Restoring a model

In a second file, we create the following script to restore the deployed network.

Let's start by loading the required libraries:

import matplotlib.pyplot as plt 
import tensorflow as tf
import input_data
import numpy as np
import mnist_data

And then by adding the MNIST dataset using the following:

mnist = mnist_data.read_data_sets('data', one_hot=True) 

Implement an interactive session:

sess = tf.InteractiveSession() 

The following line imports the meta graph saved, which contains all the information we need on the topology of the model and its variables:

new_saver = tf.train.import_meta_graph('softmax_mnist.ckpt.meta') 

Then import the checkpoint file, which contains the weights we developed during training:

new_saver.restore(sess, 'softmax_mnist.ckpt') 

To run the loaded model, we need the computation graph, which we call through the following function:

tf.get_default_graph().  

The following function will return the default graph being used in the current thread:

tf.get_default_graph().as_graph_def() 

We then define the x and y_conv variables and associate them with the nodes that we need to handle in order to feed input and retrieve output:

x = sess.graph.get_tensor_by_name("input:0") 
y_conv = sess.graph.get_tensor_by_name("output:0")

To test the restored model, we take a single image from the MNIST database:

image_b = mnist.test.images[100] 

Then we run the restored model, on the selected input:

result = sess.run(y_conv, feed_dict={x:image_b})  

The result varaible is the output tensor of 10 items, each of which represents the probability for each digit to be classified. So we print our result and the index with the highest probability, which is just the classified digit:

print(result) 
print(sess.run(tf.argmax(result, 1)))

We show the classified image using the plt function imported from matplotlib:

plt.imshow(image_b.reshape([28, 28]), cmap='Greys') 
plt.show()

Running the network, we should have the following output:

>>>  
Loading data/train-images-idx3-ubyte.mnist
Loading data/train-labels-idx1-ubyte.mnist
Loading data/t10k-images-idx3-ubyte.mnist
Loading data/t10k-labels-idx1-ubyte.mnist
[[ 5.37428750e-05 6.65060536e-04 1.42298099e-02 3.05720314e-04
2.49665667e-04 6.00658204e-05 9.83844459e-01 4.97680194e-05
4.59994393e-04 8.17739274e-05]]

[6]

The higher array item is 9.83844459e-01 (= 90%), which corresponds to the digit 6, represented as follows:

Classified image

However, the confirmation of the goodness of the simulation is verified by drawing the classified image.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset