In [1]:
from __future__ import print_function
import tensorflow as tf
tf.__version__
Out[1]:
In [ ]:
#Pseudocode to basic usage in batch mode
# Define a graph
graph = tf.Graph()
with graph.as_default():
# graph definition
saver = tf.train.Saver()
# Execute a graph to train a network
gpu_options = tf.GPUOptions(per_process_gpu_memory_fraction=0.333, allow_growth = True)
with tf.Session(graph=graph, config=tf.ConfigProto(gpu_options=gpu_options)) as session:
print('Initializing')
tf.initialize_all_variables().run()
for epoch in range(nEpochs):
for batch in batch_list:
feedDict = {} # dictionary of batch data to run the graph
_, param1_out, param2_out = session.run([train_step, param1_tensor, param2_tensor], feed_dict=feedDict)
saver.save(session, 'path_to_model')
# Load & execute the trained graph to score new data
with tf.Session(graph=graph, config=tf.ConfigProto(gpu_options=gpu_options)) as session:
#Load model
loader = tf.train.import_meta_graph('path_to_model.meta')
loader.restore(session, 'path_to_model')
# Score data
feedDict = {} # dictionary of batch data to score
my_predictions = predicts.eval(feed_dict=feedDict)
In [3]:
# Load data
from tensorflow.examples.tutorials.mnist import input_data
mnist = input_data.read_data_sets('/tmp/MNIST_data', one_hot=True)
# Define a graph
graph = tf.Graph()
with graph.as_default():
# graph definition
x = tf.placeholder(tf.float32, shape=[None, 784])
y = tf.placeholder(tf.float32, shape=[None, 10])
W = tf.Variable(tf.zeros([784,10]))
b = tf.Variable(tf.zeros([10]))
y_pred = tf.nn.softmax(tf.matmul(x,W) + b)
cross_entropy = tf.reduce_mean(-tf.reduce_sum(y * tf.log(y_pred), reduction_indices=[1]))
train_step = tf.train.GradientDescentOptimizer(0.5).minimize(cross_entropy)
saver = tf.train.Saver()
# Execute a graph to train a network
nEpochs = 10
gpu_options = tf.GPUOptions(per_process_gpu_memory_fraction=0.333, allow_growth = True)
with tf.Session(graph=graph, config=tf.ConfigProto(gpu_options=gpu_options)) as session:
print('Initializing')
tf.global_variables_initializer().run()
for epoch in range(nEpochs):
for i in range(10):
batch = mnist.train.next_batch(500)
_, ce = session.run([train_step, cross_entropy], feed_dict={x: batch[0], y: batch[1]})
print(epoch, ce)
saver.save(session, '/tmp/mnist_model')
# Load & execute the trained graph to score new data
with tf.Session(graph=graph, config=tf.ConfigProto(gpu_options=gpu_options)) as session:
#Load model
loader = tf.train.import_meta_graph('/tmp/mnist_model.meta')
loader.restore(session, '/tmp/mnist_model')
# Score test data
feedDict = {x: mnist.test.images[:200], y: mnist.test.labels[:200]} # dictionary of batch data to score
my_predictions = y_pred.eval(feed_dict=feedDict)
# Evaluate test data
print('Test ce: ', cross_entropy.eval(feed_dict=feedDict))
In [ ]: