TenserFlow Serving


In [1]:
import tensorflow as tf

In [2]:
from tensorflow.examples.tutorials.mnist import input_data
mnist = input_data.read_data_sets('/tmp/tensorflow/alex/mnist/input_data', one_hot=True)


Extracting /tmp/tensorflow/alex/mnist/input_data/train-images-idx3-ubyte.gz
Extracting /tmp/tensorflow/alex/mnist/input_data/train-labels-idx1-ubyte.gz
Extracting /tmp/tensorflow/alex/mnist/input_data/t10k-images-idx3-ubyte.gz
Extracting /tmp/tensorflow/alex/mnist/input_data/t10k-labels-idx1-ubyte.gz

Graph


In [3]:
x = tf.placeholder(dtype=tf.float32, shape=[None, 784], name='input')
W = tf.Variable(initial_value=tf.zeros([784, 10], dtype=tf.float32), name='weights', trainable=True)
b = tf.Variable(initial_value=tf.zeros([10]), dtype=tf.float32, name='bias', trainable=True)
out = tf.matmul(x, W) + b
y = tf.placeholder(tf.float32, [None, 10])

loss = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(labels=y, logits=out))
optimizer = tf.train.GradientDescentOptimizer(learning_rate=0.5).minimize(loss)

Initialize


In [4]:
sess = tf.Session()
sess.run(tf.global_variables_initializer())

Train


In [5]:
for _ in range(1000):
    xs, ys = mnist.train.next_batch(100)
    sess.run(optimizer, feed_dict={x: xs, y: ys})

Test


In [6]:
# Graph
prediction = tf.argmax(out, 1)
target = tf.argmax(y, 1)
correct_prediction = tf.equal(prediction, target)
accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))

# Execute
test_result = sess.run(accuracy, feed_dict={x: mnist.test.images, y: mnist.test.labels})
print('Test accuracy: {0}'.format(test_result))


Test accuracy: 0.9110999703407288

Export the model


In [7]:
import os

export_path_base = '/home/jovyan/work/models/alex/'
model_version = '2'

export_path = os.path.join(export_path_base, model_version)
builder = tf.saved_model.builder.SavedModelBuilder(export_path)

tensor_info_x = tf.saved_model.utils.build_tensor_info(x)
tensor_info_out = tf.saved_model.utils.build_tensor_info(out)

prediction_signature = (
      tf.saved_model.signature_def_utils.build_signature_def(
          inputs={'images': tensor_info_x},
          outputs={'scores': tensor_info_out},
          method_name=tf.saved_model.signature_constants.PREDICT_METHOD_NAME))

legacy_init_op = tf.group(tf.tables_initializer(), name='legacy_init_op')
builder.add_meta_graph_and_variables(
      sess, [tf.saved_model.tag_constants.SERVING],
      signature_def_map={
          'predict_images':
              prediction_signature
      },
      legacy_init_op=legacy_init_op)

builder.save()


INFO:tensorflow:No assets to save.
INFO:tensorflow:No assets to write.
INFO:tensorflow:SavedModel written to: b'/home/jovyan/work/models/alex/2/saved_model.pb'
Out[7]:
b'/home/jovyan/work/models/alex/2/saved_model.pb'

In [8]:
sess.close()