# Lab 11 MNIST and Convolutional Neural Network
import tensorflow as tf
import random
import scipy.io as scio
# import matplotlib.pyplot as plt
from tensorflow.examples.tutorials.mnist import input_data
tf.set_random_seed(777) # reproducibility
mnist = input_data.read_data_sets("MNIST_data/", one_hot=True)
# Check out https://www.tensorflow.org/get_started/mnist/beginners for
# more information about the mnist dataset
# hyper parameters
learning_rate = 0.002
training_epochs = 3
batch_size = 50
# input place holders
X = tf.placeholder(tf.float32, [None, 784])
X_img = tf.reshape(X, [-1, 28, 28, 1]) # img 28x28x1 (black/white)
Y = tf.placeholder(tf.float32, [None, 10])
# L1 ImgIn shape=(?, 28, 28, 1)
W1 = tf.Variable(tf.random_normal([5, 5, 1, 6], stddev=0.01))
b1 = tf.Variable(tf.random_normal([6]))
# Conv -> (?, 24, 24, 6)
# Pool -> (?, 12, 12, 6)
L1 = tf.nn.conv2d(X_img, W1, strides=[1, 1, 1, 1], padding='VALID')
L1 = tf.nn.relu(L1 + b1)
L1 = tf.nn.avg_pool(L1, ksize=[1, 2, 2, 1],
strides=[1, 2, 2, 1], padding='SAME')
'''
Tensor("Conv2D:0", shape=(?, 24, 24, 6), dtype=float32)
Tensor("Relu:0", shape=(?, 24, 24, 6), dtype=float32)
Tensor("avgPool:0", shape=(?, 12, 12, 6), dtype=float32)
'''
# L2 ImgIn shape=(?, 12, 12, 6)
W2 = tf.Variable(tf.random_normal([5, 5, 6, 16], stddev=0.01))
b2 = tf.Variable(tf.random_normal([16]))
# Conv ->(?, 8, 8, 16)
# Pool ->(?, 4, 4, 16)
L2 = tf.nn.conv2d(L1, W2, strides=[1, 1, 1, 1], padding='VALID')
L2 = tf.nn.relu(L2 + b2)
L2 = tf.nn.avg_pool(L2, ksize=[1, 2, 2, 1],
strides=[1, 2, 2, 1], padding='SAME')
L2_flat = tf.reshape(L2, [-1, 4 * 4 * 16])
#L2_flat = tf.nn.relu(L2_flat)
'''
Tensor("Conv2D_1:0", shape=(?, 14, 14, 64), dtype=float32)
Tensor("Relu_1:0", shape=(?, 14, 14, 64), dtype=float32)
Tensor("MaxPool_1:0", shape=(?, 7, 7, 64), dtype=float32)
Tensor("Reshape_1:0", shape=(?, 3136), dtype=float32)
'''
# Final FC 7x7x64 inputs -> 10 outputs
W3 = tf.Variable(tf.random_normal([4*4*16, 10], stddev=0.01))
#W3 = tf.get_variable("W3", shape=[4 * 4 * 16, 10],
# initializer=tf.contrib.layers.xavier_initializer())
b3 = tf.Variable(tf.random_normal([10]))
logits = tf.matmul(L2_flat, W3) + b3
#logits = tf.nn.relu(logits)
# define cost/loss & optimizer
cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(
logits=logits, labels=Y))
optimizer = tf.train.AdamOptimizer(learning_rate=learning_rate).minimize(cost)
#creat a saver
saver = tf.train.Saver()
# initialize
with tf.Session() as sess:
sess.run(tf.global_variables_initializer())
# train my model
print('Learning started. It takes sometime.')
for epoch in range(training_epochs):
avg_cost = 0
total_batch = int(mnist.train.num_examples / batch_size)
for i in range(total_batch):
batch_xs, batch_ys = mnist.train.next_batch(batch_size)
feed_dict = {X: batch_xs, Y: batch_ys}
c, _ = sess.run([cost, optimizer], feed_dict=feed_dict)
avg_cost += c / total_batch
print('Epoch:', '%04d' % (epoch + 1), 'cost =', '{:.9f}'.format(avg_cost))
print('Learning Finished!')
# save the model
saver.save(sess, "model/save_net.ckpt")
# save_mat
# dataW1 = 'w1.mat'
# scio.savemat(dataW1, {'W1':sess.run(W1)})
# dataW2 = 'w2.mat'
# scio.savemat(dataW2, {'W2':sess.run(W2)})
# dataW3 = 'w3.mat'
# scio.savemat(dataW3, {'W3':sess.run(W3)})
# datab1 = 'b1.mat'
# scio.savemat(datab1, {'b1':sess.run(b1)})
# datab2 = 'b2.mat'
# scio.savemat(datab2, {'b2':sess.run(b2)})
# datab3 = 'b3.mat'
# scio.savemat(datab3, {'b3':sess.run(b3)})
# Test model and check accuracy
correct_prediction = tf.equal(tf.argmax(logits, 1), tf.argmax(Y, 1))
accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))
print('Accuracy:', sess.run(accuracy, feed_dict={
X: mnist.test.images, Y: mnist.test.labels}))
# Get one and predict
r = random.randint(0, mnist.test.num_examples - 1)
print("Label: ", sess.run(tf.argmax(mnist.test.labels[r:r + 1], 1)))
print("Prediction: ", sess.run(
tf.argmax(logits, 1), feed_dict={X: mnist.test.images[r:r + 1]}))
# plt.imshow(mnist.test.images[r:r + 1].
# reshape(28, 28), cmap='Greys', interpolation='nearest')
# plt.show()
'''
Epoch: 0001 cost = 0.340291267
Epoch: 0002 cost = 0.090731326
Epoch: 0003 cost = 0.064477619
Epoch: 0004 cost = 0.050683064
Epoch: 0005 cost = 0.041864835
Epoch: 0006 cost = 0.035760704
Epoch: 0007 cost = 0.030572132
Epoch: 0008 cost = 0.026207981
Epoch: 0009 cost = 0.022622454
Epoch: 0010 cost = 0.019055919
Epoch: 0011 cost = 0.017758641
Epoch: 0012 cost = 0.014156652
Epoch: 0013 cost = 0.012397016
Epoch: 0014 cost = 0.010693789
Epoch: 0015 cost = 0.009469977
Learning Finished!
Accuracy: 0.9885
'''
'''
Epoch: 0001 cost = 0.318063878
Epoch: 0002 cost = 0.105674432
Epoch: 0003 cost = 0.077878999
Epoch: 0004 cost = 0.066057363
Epoch: 0005 cost = 0.057512918
Epoch: 0006 cost = 0.052459399
Epoch: 0007 cost = 0.046069056
Epoch: 0008 cost = 0.042238329
Epoch: 0009 cost = 0.039322835
Epoch: 0010 cost = 0.034931831
Epoch: 0011 cost = 0.033192076
Epoch: 0012 cost = 0.030914000
Epoch: 0013 cost = 0.028490152
Epoch: 0014 cost = 0.026866245
Epoch: 0015 cost = 0.025608637
Epoch: 0016 cost = 0.024366001
Epoch: 0017 cost = 0.021244116
Epoch: 0018 cost = 0.022134637
Epoch: 0019 cost = 0.020379513
Epoch: 0020 cost = 0.018623088
Epoch: 0021 cost = 0.018348278
Epoch: 0022 cost = 0.017074608
Epoch: 0023 cost = 0.016454066
Epoch: 0024 cost = 0.014578759
Epoch: 0025 cost = 0.016178100
Epoch: 0026 cost = 0.013665723
Epoch: 0027 cost = 0.013868410
Epoch: 0028 cost = 0.013506715
Epoch: 0029 cost = 0.012520027
Epoch: 0030 cost = 0.011752283
Epoch: 0031 cost = 0.012224808
Epoch: 0032 cost = 0.009687688
Epoch: 0033 cost = 0.011666438
Epoch: 0034 cost = 0.010130068
Epoch: 0035 cost = 0.009605887
Epoch: 0036 cost = 0.009520990
Epoch: 0037 cost = 0.009449142
Epoch: 0038 cost = 0.009283410
Epoch: 0039 cost = 0.007676879
Epoch: 0040 cost = 0.008369593
Epoch: 0041 cost = 0.009352039
Epoch: 0042 cost = 0.007622884
Epoch: 0043 cost = 0.008005746
Epoch: 0044 cost = 0.006593210
Epoch: 0045 cost = 0.006523430
Epoch: 0046 cost = 0.007701061
Epoch: 0047 cost = 0.005825046
Epoch: 0048 cost = 0.007374606
Epoch: 0049 cost = 0.006955691
Epoch: 0050 cost = 0.005048158
Epoch: 0051 cost = 0.006731462
Epoch: 0052 cost = 0.006690387
Epoch: 0053 cost = 0.004819284
Epoch: 0054 cost = 0.005591960
Epoch: 0055 cost = 0.005885528
Epoch: 0056 cost = 0.005811614
Epoch: 0057 cost = 0.005956684
Epoch: 0058 cost = 0.004923902
Epoch: 0059 cost = 0.005496770
Epoch: 0060 cost = 0.005378819
Learning Finished!
Accuracy: 0.99
'''