In [1]:
import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data
mnist = input_data.read_data_sets("/tmp/data/", one_hot=True)
In [3]:
learning_rate = 0.001
batch_size = 100
display_step = 1
model_path = "./data/model.ckpt"
n_hidden_1 = 256
n_hidden_2 = 256
n_input =784
n_classes = 10
X = tf.placeholder(tf.float32, [None, n_input])
Y = tf.placeholder(tf.float32, [None, n_classes])
# Create model
def multilayer_perceptron(X, weights, biases):
# Hidden layer with RELU activation
layer_1 = tf.add(tf.matmul(X, weights['h1']), biases['b1'])
layer_1 = tf.nn.relu(layer_1)
# Hidden layer with RELU activation
layer_2 = tf.add(tf.matmul(layer_1, weights['h2']), biases['b2'])
layer_2 = tf.nn.relu(layer_2)
# Output layer with linear activation
out_layer = tf.matmul(layer_2, weights['out']) + biases['out']
return out_layer
# Store layers weight & bias
weights = {
'h1': tf.Variable(tf.random_normal([n_input, n_hidden_1])),
'h2': tf.Variable(tf.random_normal([n_hidden_1, n_hidden_2])),
'out': tf.Variable(tf.random_normal([n_hidden_2, n_classes]))
}
biases = {
'b1': tf.Variable(tf.random_normal([n_hidden_1])),
'b2': tf.Variable(tf.random_normal([n_hidden_2])),
'out': tf.Variable(tf.random_normal([n_classes]))
}
# Construct model
pred = multilayer_perceptron(X, weights, biases)
# Define loss and optimizer
cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(pred, Y))
optimizer = tf.train.AdamOptimizer(learning_rate=learning_rate).minimize(cost)
# Initializing the variables
init = tf.initialize_all_variables()
In [4]:
# 'Saver' op to save and restore all the variables
saver = tf.train.Saver()
In [5]:
with tf.Session() as sess:
sess.run(init)
for epoch in range(100):
avg_cost = 0.
total_batch = int(mnist.train.num_examples/batch_size)
for i in range(batch_size):
batch_X, batch_Y = mnist.train.next_batch(batch_size)
_, c = sess.run([optimizer, cost], feed_dict={X:batch_X, Y:batch_Y})
avg_cost += c/total_batch
if epoch % display_step == 0:
print( "Epoch:", '%04d' % (epoch+1), "cost=", \
"{:.9f}".format(avg_cost))
print("First Optimization Finished!")
correct_prediction = tf.equal(tf.argmax(pred, 1 ), tf.argmax(y,1))
accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))
print("Accuracy : "+ str(accuracy.eval({X:mnist.test.images, Y:mnist.test.labels})) )
save_path = saver.save(sess,model_path)
print("Model saved in file : %s" % save_path)
In [ ]:
print("restore!")
with tf.Session() as sess:
sess.run(init)
load_path = save.restore(sess, model_path)
for epoch in range(10):