Restoring A Trained TensorFlow Model And Predict Using That

thumbnail

So you have trained your first machine learning model using Tensorflow. Now you want to use your model to do prediction of independent data but you don't know how to do it? The tutorial you were following online ends with lots of evaluation and validation scores and graphs but does not give any hint about the next step? You know what, I always faced the same problem when I started working on machine learning. So, here is what we need to do after we are done training our model using Tensorflow.

I have trained a model to detect clothing type on Fashion MNIST dataset. I guess that info will help you to understand the following source codes.

Make sure you have trained the model using specific name so that when required you can load them by name and use them to predict. For example,

x = tf.placeholder(tf.float32, shape=[None, 784], name='x')
y_ = tf.placeholder(tf.float32, shape=[None, 10])
W = tf.Variable(tf.zeros([784,10]))
b = tf.Variable(tf.zeros([10]))
y = tf.nn.softmax(tf.matmul(x,W) + b, name='y')
cross_entropy = tf.reduce_mean(-tf.reduce_sum(y_ * tf.log(y), reduction_indices=[1]))

Here, we will need the x variable and y operation for the prediction, so we give them a specific name during the training.

Once we are done, then we can load that x and y into our prediction script by name, run the y operation in the current session and send the x variable as we load image from the disk. Check out the complete code here.

import tensorflow as tf
import os
import cv2
import numpy as np
import glob

ROOT_DIR = os.getcwd()
DATA_DIR = ROOT_DIR + '/data'
RESOURCE_DIR = ROOT_DIR + '/images'
MODEL_DIR = ROOT_DIR + '/model'

# class info
classes = ['T-shirt/top', 'Trouser', 'Pullover', 'Dress', 
            'Coat', 'Sandal', 'Shirt', 'Sneaker', 'Bag', 
            'Ankle boot']

sess = tf.Session()
saver = tf.train.import_meta_graph('model/model.ckpt.meta')
saver.restore(sess, tf.train.latest_checkpoint('model'))

graph = tf.get_default_graph()

x = graph.get_tensor_by_name('x:0')
y = graph.get_tensor_by_name('y:0')

img_size = 28

path = os.path.join('images', 'test', '*g')
files = glob.glob(path)
for img_file in files:
    test_im = cv2.imread(img_file, cv2.IMREAD_GRAYSCALE)

    # invert grayscale
    test_im = 255 - cv2.resize(test_im, (img_size, img_size), cv2.INTER_LINEAR)

    test_im = test_im.flatten().reshape(1, 784)

    prediction = sess.run(y, feed_dict={x: test_im})
    prediction = prediction.argmax()

    print(classes[prediction])</code></pre>

Now you know how to load and predict using a trained model in Tensorflow.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Back To Top