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)


Successfully downloaded train-images-idx3-ubyte.gz 9912422 bytes.
Extracting /tmp/data/train-images-idx3-ubyte.gz
Successfully downloaded train-labels-idx1-ubyte.gz 28881 bytes.
Extracting /tmp/data/train-labels-idx1-ubyte.gz
Successfully downloaded t10k-images-idx3-ubyte.gz 1648877 bytes.
Extracting /tmp/data/t10k-images-idx3-ubyte.gz
Successfully downloaded t10k-labels-idx1-ubyte.gz 4542 bytes.
Extracting /tmp/data/t10k-labels-idx1-ubyte.gz

In [2]:
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()

Save


In [3]:
# 'Saver' op to save and restore all the variables
saver = tf.train.Saver()

In [4]:
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)


Epoch: 0001 cost= 98.927903609
Epoch: 0002 cost= 26.225927866
Epoch: 0003 cost= 18.514694106
Epoch: 0004 cost= 13.817546532
Epoch: 0005 cost= 12.934680890
Epoch: 0006 cost= 8.261287063
Epoch: 0007 cost= 8.973457217
Epoch: 0008 cost= 7.485161913
Epoch: 0009 cost= 6.911409857
Epoch: 0010 cost= 6.598327430
Epoch: 0011 cost= 6.419381376
Epoch: 0012 cost= 5.111067943
Epoch: 0013 cost= 5.082075245
Epoch: 0014 cost= 4.685605249
Epoch: 0015 cost= 4.388187779
Epoch: 0016 cost= 4.205841089
Epoch: 0017 cost= 3.882994150
Epoch: 0018 cost= 3.372019638
Epoch: 0019 cost= 3.112797648
Epoch: 0020 cost= 3.102711377
Epoch: 0021 cost= 3.180817396
Epoch: 0022 cost= 3.258240452
Epoch: 0023 cost= 2.356369968
Epoch: 0024 cost= 2.443923872
Epoch: 0025 cost= 2.174295551
Epoch: 0026 cost= 2.410746910
Epoch: 0027 cost= 2.290733940
Epoch: 0028 cost= 1.869466666
Epoch: 0029 cost= 1.909222934
Epoch: 0030 cost= 1.633284212
Epoch: 0031 cost= 1.797206610
Epoch: 0032 cost= 1.584597216
Epoch: 0033 cost= 1.859798947
Epoch: 0034 cost= 1.199188767
Epoch: 0035 cost= 1.433872705
Epoch: 0036 cost= 1.401335066
Epoch: 0037 cost= 1.249681925
Epoch: 0038 cost= 1.182758297
Epoch: 0039 cost= 1.237812533
Epoch: 0040 cost= 0.940209877
Epoch: 0041 cost= 0.937762752
Epoch: 0042 cost= 0.912939186
Epoch: 0043 cost= 1.011214965
Epoch: 0044 cost= 0.982488549
Epoch: 0045 cost= 0.644078301
Epoch: 0046 cost= 0.687255460
Epoch: 0047 cost= 0.725569225
Epoch: 0048 cost= 0.641393077
Epoch: 0049 cost= 0.902149870
Epoch: 0050 cost= 0.604175871
Epoch: 0051 cost= 0.483898756
Epoch: 0052 cost= 0.577129643
Epoch: 0053 cost= 0.554609014
Epoch: 0054 cost= 0.654789514
Epoch: 0055 cost= 0.586119598
Epoch: 0056 cost= 0.333269800
Epoch: 0057 cost= 0.398864852
Epoch: 0058 cost= 0.377482452
Epoch: 0059 cost= 0.485579187
Epoch: 0060 cost= 0.432511825
Epoch: 0061 cost= 0.372346716
Epoch: 0062 cost= 0.313601994
Epoch: 0063 cost= 0.310432873
Epoch: 0064 cost= 0.235805236
Epoch: 0065 cost= 0.277293868
Epoch: 0066 cost= 0.345024078
Epoch: 0067 cost= 0.266812238
Epoch: 0068 cost= 0.258770226
Epoch: 0069 cost= 0.198435604
Epoch: 0070 cost= 0.237045754
Epoch: 0071 cost= 0.257215172
Epoch: 0072 cost= 0.228292666
Epoch: 0073 cost= 0.184712832
Epoch: 0074 cost= 0.205241406
Epoch: 0075 cost= 0.169815378
Epoch: 0076 cost= 0.206476328
Epoch: 0077 cost= 0.215597940
Epoch: 0078 cost= 0.112527570
Epoch: 0079 cost= 0.166480651
Epoch: 0080 cost= 0.118750694
Epoch: 0081 cost= 0.159132588
Epoch: 0082 cost= 0.165428695
Epoch: 0083 cost= 0.102588642
Epoch: 0084 cost= 0.110559591
Epoch: 0085 cost= 0.096841263
Epoch: 0086 cost= 0.100130986
Epoch: 0087 cost= 0.115918048
Epoch: 0088 cost= 0.132420755
Epoch: 0089 cost= 0.071411484
Epoch: 0090 cost= 0.098538571
Epoch: 0091 cost= 0.116107074
Epoch: 0092 cost= 0.083367100
Epoch: 0093 cost= 0.160614913
Epoch: 0094 cost= 0.114636368
Epoch: 0095 cost= 0.082743931
Epoch: 0096 cost= 0.117179579
Epoch: 0097 cost= 0.101913439
Epoch: 0098 cost= 0.106047518
Epoch: 0099 cost= 0.100909283
Epoch: 0100 cost= 0.060488002
First Optimization Finished!
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-4-c6112e65b811> in <module>()
     15     print("First Optimization Finished!")
     16 
---> 17     correct_prediction = tf.equal(tf.argmax(pred, 1 ), tf.argmax(y,1))
     18 
     19     accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))

NameError: name 'y' is not defined

Restore


In [ ]:
print("restore!")

with tf.Session() as sess:
    sess.run(init)
    
    load_path = save.restore(sess, model_path)
    
    for epoch in range(10):
        avg_cost = 0.
        total_batch = int(mnist.train.num_examples / batch_size)
        
        for i in range(total_batch):
            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("retrain done")
    
    correct_prediction = tf.equal(tf.argmax(pred, 1), tf.argmax(y, 1))
    accuracy = tf.reduce_mean(tf.cast(correct_prediction, "float"))
    print("Accuracy: ", accuracy.eval({x: mnist.test.images, y: mnist.test.labels}))

In [ ]: