9.1 CNN for MNIST with TensorFlow and Keras

import os

import numpy as np
np.random.seed(123)
print("NumPy:{}".format(np.__version__))

import tensorflow as tf
tf.set_random_seed(123)
print("TensorFlow:{}".format(tf.__version__))
NumPy:1.13.1
TensorFlow:1.4.1
DATASETSLIB_HOME = '../datasetslib'
import sys
if not DATASETSLIB_HOME in sys.path:
    sys.path.append(DATASETSLIB_HOME)
%reload_ext autoreload
%autoreload 2
import datasetslib

datasetslib.datasets_root = os.path.join(os.path.expanduser('~'),'datasets')

Get the MNIST data

from tensorflow.examples.tutorials.mnist import input_data
mnist = input_data.read_data_sets(os.path.join(datasetslib.datasets_root,'mnist'), one_hot=True)

X_train = mnist.train.images
X_test = mnist.test.images
Y_train = mnist.train.labels
Y_test = mnist.test.labels
Extracting /home/armando/datasets/mnist/train-images-idx3-ubyte.gz
Extracting /home/armando/datasets/mnist/train-labels-idx1-ubyte.gz
Extracting /home/armando/datasets/mnist/t10k-images-idx3-ubyte.gz
Extracting /home/armando/datasets/mnist/t10k-labels-idx1-ubyte.gz

CNN with TensorFlow for MNIST Data

tf.reset_default_graph()
# parameters
n_classes = 10  # 0-9 digits
n_width = 28
n_height = 28
n_depth = 1
n_inputs = n_height * n_width * n_depth  # total pixels

learning_rate = 0.001
n_epochs = 10
batch_size = 100
n_batches = int(mnist.train.num_examples/batch_size)
# input images in shape n_samples,n_pixels
x = tf.placeholder(dtype=tf.float32, name="x", shape=[None, n_inputs]) 
# output labels
y = tf.placeholder(dtype=tf.float32, name="y", shape=[None, n_classes]) 

# reshape input to (n_samples,n_width,n_height,n_depth)
x_ = tf.reshape(x, shape=[-1, n_width, n_height, n_depth])

# create first set of convolutional layers
layer1_w = tf.Variable(tf.random_normal(shape=[4,4,n_depth,32],
                                        stddev=0.1),
                       name='l1_w')
layer1_b = tf.Variable(tf.random_normal([32]),
                       name='l1_b')
layer1_conv = tf.nn.relu(tf.nn.conv2d(x_,
                                      layer1_w,
                                      strides=[1,1,1,1],
                                      padding='SAME'
                                     ) + 
                         layer1_b 
                        )
layer1_pool = tf.nn.max_pool(layer1_conv,
                             ksize=[1,2,2,1],
                             strides=[1,2,2,1],
                             padding='SAME'
                            )

layer2_w = tf.Variable(tf.random_normal(shape=[4,4,32,64],
                                        stddev=0.1),
                       name='l2_w')
layer2_b = tf.Variable(tf.random_normal([64]),
                       name='l2_b')
layer2_conv = tf.nn.relu(tf.nn.conv2d(layer1_pool,
                                      layer2_w,
                                      strides=[1,1,1,1],
                                      padding='SAME'
                                     ) + 
                         layer2_b 
                        )
layer2_pool = tf.nn.max_pool(layer2_conv,
                             ksize=[1,2,2,1],
                             strides=[1,2,2,1],
                             padding='SAME'
                            )


layer3_w = tf.Variable(tf.random_normal(shape=[64*7*7*1,1024],
                                        stddev=0.1),
                       name='l3_w')
layer3_b = tf.Variable(tf.random_normal([1024]),
                       name='l3_b')
layer3_fc = tf.nn.relu(tf.matmul(tf.reshape(layer2_pool,
                                            [-1, 64*7*7*1]),
                                 layer3_w) +
                       layer3_b
                      )

layer4_w = tf.Variable(tf.random_normal(shape=[1024, n_classes],
                                        stddev=0.1),
                       name='l4_w'
                      )
layer4_b = tf.Variable(tf.random_normal([n_classes]),name='l4_b')

layer4_out = tf.matmul(layer3_fc,layer4_w)+layer4_b

model = layer4_out

# loss function
entropy = tf.nn.softmax_cross_entropy_with_logits(logits=model, labels=y)
loss = tf.reduce_mean(entropy)
# optimizer function
optimizer = tf.train.AdamOptimizer(learning_rate=learning_rate).minimize(loss)
# train and evaluate
with tf.Session() as tfs:
    tf.global_variables_initializer().run()
    for epoch in range(n_epochs):
        total_loss = 0.0
        for batch in range(n_batches):
            batch_x,batch_y = mnist.train.next_batch(batch_size)
            feed_dict={x:batch_x, y: batch_y}
            batch_loss,_ = tfs.run([loss, optimizer],
                                   feed_dict=feed_dict
                                  )
            total_loss += batch_loss 
        average_loss = total_loss / n_batches
        print("Epoch: {0:04d}   loss = {1:0.6f}".format(epoch,average_loss))
    print("Model Trained.")

    predictions_check = tf.equal(tf.argmax(model,1),tf.argmax(y,1))
    accuracy = tf.reduce_mean(tf.cast(predictions_check, tf.float32))
    feed_dict = {x:mnist.test.images, y:mnist.test.labels}
    print("Accuracy:", accuracy.eval(feed_dict=feed_dict))
Epoch: 0000   loss = 2.142813
Epoch: 0001   loss = 0.108121
Epoch: 0002   loss = 0.077320
Epoch: 0003   loss = 0.062054
Epoch: 0004   loss = 0.050821
Epoch: 0005   loss = 0.044723
Epoch: 0006   loss = 0.034373
Epoch: 0007   loss = 0.030643
Epoch: 0008   loss = 0.029777
Epoch: 0009   loss = 0.024144
Model Trained.
Accuracy: 0.9854

CNN with Keras for MNIST Data

import keras
from keras.models import Sequential
from keras.layers import Conv2D,MaxPooling2D, Dense, Flatten, Reshape
from keras.optimizers import SGD
Using TensorFlow backend.
tf.reset_default_graph()
keras.backend.clear_session()

n_filters=[32,64]

learning_rate = 0.01
n_epochs = 10
batch_size = 100

model = Sequential()

model.add(Reshape(target_shape=(n_width,n_height,n_depth), 
                  input_shape=(n_inputs,)
                 )
         )

model.add(Conv2D(filters=n_filters[0], 
                 kernel_size=4, 
                 padding='SAME', 
                 activation='relu' 
                ) 
         )

model.add(MaxPooling2D(pool_size=(2,2), 
                       strides=(2,2) 
                      ) 
         )

model.add(Conv2D(filters=n_filters[1], 
                 kernel_size=4, 
                 padding='SAME', 
                 activation='relu', 
                ) 
         )

model.add(MaxPooling2D(pool_size=(2,2), 
                       strides=(2,2) 
                      ) 
         )

model.add(Flatten())

model.add(Dense(units=1024, activation='relu'))
model.add(Dense(units=n_classes, activation='softmax'))
model.summary()

model.compile(loss='categorical_crossentropy',
              optimizer=SGD(lr=learning_rate),
              metrics=['accuracy'])

model.fit(X_train, Y_train,
                    batch_size=batch_size,
                    epochs=n_epochs)

score = model.evaluate(X_test, Y_test)
print('\nTest loss:', score[0])
print('Test accuracy:', score[1])
_________________________________________________________________
Layer (type)                 Output Shape              Param #   
=================================================================
reshape_1 (Reshape)          (None, 28, 28, 1)         0         
_________________________________________________________________
conv2d_1 (Conv2D)            (None, 28, 28, 32)        544       
_________________________________________________________________
max_pooling2d_1 (MaxPooling2 (None, 14, 14, 32)        0         
_________________________________________________________________
conv2d_2 (Conv2D)            (None, 14, 14, 64)        32832     
_________________________________________________________________
max_pooling2d_2 (MaxPooling2 (None, 7, 7, 64)          0         
_________________________________________________________________
flatten_1 (Flatten)          (None, 3136)              0         
_________________________________________________________________
dense_1 (Dense)              (None, 1024)              3212288   
_________________________________________________________________
dense_2 (Dense)              (None, 10)                10250     
=================================================================
Total params: 3,255,914
Trainable params: 3,255,914
Non-trainable params: 0
_________________________________________________________________
Epoch 1/10
55000/55000 [==============================] - 5s 86us/step - loss: 0.9424 - acc: 0.7545
Epoch 2/10
55000/55000 [==============================] - 5s 86us/step - loss: 0.2490 - acc: 0.9253
Epoch 3/10
55000/55000 [==============================] - 5s 84us/step - loss: 0.1760 - acc: 0.9473
Epoch 4/10
55000/55000 [==============================] - 5s 83us/step - loss: 0.1368 - acc: 0.9597
Epoch 5/10
55000/55000 [==============================] - 4s 81us/step - loss: 0.1125 - acc: 0.9661
Epoch 6/10
55000/55000 [==============================] - 5s 86us/step - loss: 0.0961 - acc: 0.9712
Epoch 7/10
55000/55000 [==============================] - 5s 85us/step - loss: 0.0842 - acc: 0.9752
Epoch 8/10
55000/55000 [==============================] - 4s 81us/step - loss: 0.0751 - acc: 0.9778
Epoch 9/10
55000/55000 [==============================] - 5s 82us/step - loss: 0.0686 - acc: 0.9800
Epoch 10/10
55000/55000 [==============================] - 5s 90us/step - loss: 0.0623 - acc: 0.9811
10000/10000 [==============================] - 1s 57us/step

Test loss: 0.0613170108855
Test accuracy: 0.9796

results matching ""

    No results matching ""