In [6]:
from tensorflow.examples.tutorials.mnist import input_data
import tensorflow as tf
import numpy as np
import math

def batches(batch_size, features, labels):
    """
    Create batches of features and labels
    :param batch_size: The batch size
    :param features: List of features
    :param labels: List of labels
    :return: Batches of (Features, Labels)
    """
    assert len(features) == len(labels)
    output_batches = []
    
    sample_size = len(features)
    for start_i in range(0, sample_size, batch_size):
        end_i = start_i + batch_size
        batch = [features[start_i:end_i], labels[start_i:end_i]]
        output_batches.append(batch)
        
    return output_batches


def print_epoch_stats(epoch_i, sess, last_features, last_labels):
    """
    Print cost and validation accuracy of an epoch
    """
    current_cost = sess.run(
        cost,
        feed_dict={features: last_features, labels: last_labels})
    valid_accuracy = sess.run(
        accuracy,
        feed_dict={features: valid_features, labels: valid_labels})
    print('Epoch: {:<4} - Cost: {:<8.3} Valid Accuracy: {:<5.3}'.format(
        epoch_i,
        current_cost,
        valid_accuracy))

n_input = 784  # MNIST data input (img shape: 28*28)
n_classes = 10  # MNIST total classes (0-9 digits)

# Import MNIST data
mnist = input_data.read_data_sets('./datasets/ud730/mnist', one_hot=True)

# The features are already scaled and the data is shuffled
train_features = mnist.train.images
valid_features = mnist.validation.images
test_features = mnist.test.images

train_labels = mnist.train.labels.astype(np.float32)
valid_labels = mnist.validation.labels.astype(np.float32)
test_labels = mnist.test.labels.astype(np.float32)

# Features and Labels
features = tf.placeholder(tf.float32, [None, n_input])
labels = tf.placeholder(tf.float32, [None, n_classes])

# Weights & bias
weights = tf.Variable(tf.random_normal([n_input, n_classes]))
bias = tf.Variable(tf.random_normal([n_classes]))

# Logits - xW + b
logits = tf.add(tf.matmul(features, weights), bias)

# Define loss and optimizer
learning_rate = tf.placeholder(tf.float32)
cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits=logits, labels=labels))
optimizer = tf.train.GradientDescentOptimizer(learning_rate=learning_rate).minimize(cost)

# Calculate accuracy
correct_prediction = tf.equal(tf.argmax(logits, 1), tf.argmax(labels, 1))
accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))

init = tf.global_variables_initializer()

batch_size = 128
epochs = 100
learn_rate = 0.25

train_batches = batches(batch_size, train_features, train_labels)

with tf.Session() as sess:
    sess.run(init)

    # Training cycle
    for epoch_i in range(epochs):

        # Loop over all batches
        for batch_features, batch_labels in train_batches:
            train_feed_dict = {
                features: batch_features,
                labels: batch_labels,
                learning_rate: learn_rate}
            sess.run(optimizer, feed_dict=train_feed_dict)

        # Print cost and validation accuracy of an epoch
        print_epoch_stats(epoch_i, sess, batch_features, batch_labels)

    # Calculate accuracy for test dataset
    test_accuracy = sess.run(
        accuracy,
        feed_dict={features: test_features, labels: test_labels})

print('Test Accuracy: {}'.format(test_accuracy))


Extracting ./datasets/ud730/mnist/train-images-idx3-ubyte.gz
Extracting ./datasets/ud730/mnist/train-labels-idx1-ubyte.gz
Extracting ./datasets/ud730/mnist/t10k-images-idx3-ubyte.gz
Extracting ./datasets/ud730/mnist/t10k-labels-idx1-ubyte.gz
Epoch: 0    - Cost: 1.36     Valid Accuracy: 0.816
Epoch: 1    - Cost: 1.06     Valid Accuracy: 0.856
Epoch: 2    - Cost: 0.92     Valid Accuracy: 0.871
Epoch: 3    - Cost: 0.831    Valid Accuracy: 0.881
Epoch: 4    - Cost: 0.767    Valid Accuracy: 0.885
Epoch: 5    - Cost: 0.716    Valid Accuracy: 0.889
Epoch: 6    - Cost: 0.674    Valid Accuracy: 0.892
Epoch: 7    - Cost: 0.637    Valid Accuracy: 0.894
Epoch: 8    - Cost: 0.606    Valid Accuracy: 0.898
Epoch: 9    - Cost: 0.578    Valid Accuracy: 0.899
Epoch: 10   - Cost: 0.554    Valid Accuracy: 0.9  
Epoch: 11   - Cost: 0.532    Valid Accuracy: 0.901
Epoch: 12   - Cost: 0.513    Valid Accuracy: 0.901
Epoch: 13   - Cost: 0.495    Valid Accuracy: 0.902
Epoch: 14   - Cost: 0.48     Valid Accuracy: 0.904
Epoch: 15   - Cost: 0.466    Valid Accuracy: 0.903
Epoch: 16   - Cost: 0.453    Valid Accuracy: 0.905
Epoch: 17   - Cost: 0.441    Valid Accuracy: 0.905
Epoch: 18   - Cost: 0.43     Valid Accuracy: 0.905
Epoch: 19   - Cost: 0.421    Valid Accuracy: 0.906
Epoch: 20   - Cost: 0.412    Valid Accuracy: 0.906
Epoch: 21   - Cost: 0.403    Valid Accuracy: 0.907
Epoch: 22   - Cost: 0.396    Valid Accuracy: 0.908
Epoch: 23   - Cost: 0.389    Valid Accuracy: 0.908
Epoch: 24   - Cost: 0.382    Valid Accuracy: 0.908
Epoch: 25   - Cost: 0.376    Valid Accuracy: 0.909
Epoch: 26   - Cost: 0.37     Valid Accuracy: 0.909
Epoch: 27   - Cost: 0.365    Valid Accuracy: 0.91 
Epoch: 28   - Cost: 0.359    Valid Accuracy: 0.91 
Epoch: 29   - Cost: 0.355    Valid Accuracy: 0.91 
Epoch: 30   - Cost: 0.35     Valid Accuracy: 0.91 
Epoch: 31   - Cost: 0.346    Valid Accuracy: 0.911
Epoch: 32   - Cost: 0.342    Valid Accuracy: 0.911
Epoch: 33   - Cost: 0.338    Valid Accuracy: 0.912
Epoch: 34   - Cost: 0.335    Valid Accuracy: 0.912
Epoch: 35   - Cost: 0.331    Valid Accuracy: 0.912
Epoch: 36   - Cost: 0.328    Valid Accuracy: 0.913
Epoch: 37   - Cost: 0.325    Valid Accuracy: 0.913
Epoch: 38   - Cost: 0.322    Valid Accuracy: 0.913
Epoch: 39   - Cost: 0.319    Valid Accuracy: 0.913
Epoch: 40   - Cost: 0.316    Valid Accuracy: 0.913
Epoch: 41   - Cost: 0.314    Valid Accuracy: 0.913
Epoch: 42   - Cost: 0.311    Valid Accuracy: 0.914
Epoch: 43   - Cost: 0.309    Valid Accuracy: 0.914
Epoch: 44   - Cost: 0.307    Valid Accuracy: 0.914
Epoch: 45   - Cost: 0.305    Valid Accuracy: 0.914
Epoch: 46   - Cost: 0.302    Valid Accuracy: 0.914
Epoch: 47   - Cost: 0.3      Valid Accuracy: 0.915
Epoch: 48   - Cost: 0.298    Valid Accuracy: 0.916
Epoch: 49   - Cost: 0.297    Valid Accuracy: 0.916
Epoch: 50   - Cost: 0.295    Valid Accuracy: 0.917
Epoch: 51   - Cost: 0.293    Valid Accuracy: 0.917
Epoch: 52   - Cost: 0.291    Valid Accuracy: 0.917
Epoch: 53   - Cost: 0.29     Valid Accuracy: 0.917
Epoch: 54   - Cost: 0.288    Valid Accuracy: 0.917
Epoch: 55   - Cost: 0.286    Valid Accuracy: 0.917
Epoch: 56   - Cost: 0.285    Valid Accuracy: 0.917
Epoch: 57   - Cost: 0.283    Valid Accuracy: 0.917
Epoch: 58   - Cost: 0.282    Valid Accuracy: 0.917
Epoch: 59   - Cost: 0.281    Valid Accuracy: 0.918
Epoch: 60   - Cost: 0.279    Valid Accuracy: 0.918
Epoch: 61   - Cost: 0.278    Valid Accuracy: 0.918
Epoch: 62   - Cost: 0.277    Valid Accuracy: 0.918
Epoch: 63   - Cost: 0.275    Valid Accuracy: 0.919
Epoch: 64   - Cost: 0.274    Valid Accuracy: 0.919
Epoch: 65   - Cost: 0.273    Valid Accuracy: 0.919
Epoch: 66   - Cost: 0.272    Valid Accuracy: 0.919
Epoch: 67   - Cost: 0.271    Valid Accuracy: 0.919
Epoch: 68   - Cost: 0.269    Valid Accuracy: 0.919
Epoch: 69   - Cost: 0.268    Valid Accuracy: 0.92 
Epoch: 70   - Cost: 0.267    Valid Accuracy: 0.92 
Epoch: 71   - Cost: 0.266    Valid Accuracy: 0.921
Epoch: 72   - Cost: 0.265    Valid Accuracy: 0.921
Epoch: 73   - Cost: 0.264    Valid Accuracy: 0.921
Epoch: 74   - Cost: 0.263    Valid Accuracy: 0.921
Epoch: 75   - Cost: 0.262    Valid Accuracy: 0.921
Epoch: 76   - Cost: 0.261    Valid Accuracy: 0.921
Epoch: 77   - Cost: 0.26     Valid Accuracy: 0.921
Epoch: 78   - Cost: 0.259    Valid Accuracy: 0.921
Epoch: 79   - Cost: 0.258    Valid Accuracy: 0.921
Epoch: 80   - Cost: 0.257    Valid Accuracy: 0.921
Epoch: 81   - Cost: 0.256    Valid Accuracy: 0.921
Epoch: 82   - Cost: 0.256    Valid Accuracy: 0.921
Epoch: 83   - Cost: 0.255    Valid Accuracy: 0.921
Epoch: 84   - Cost: 0.254    Valid Accuracy: 0.921
Epoch: 85   - Cost: 0.253    Valid Accuracy: 0.921
Epoch: 86   - Cost: 0.252    Valid Accuracy: 0.921
Epoch: 87   - Cost: 0.251    Valid Accuracy: 0.921
Epoch: 88   - Cost: 0.251    Valid Accuracy: 0.921
Epoch: 89   - Cost: 0.25     Valid Accuracy: 0.921
Epoch: 90   - Cost: 0.249    Valid Accuracy: 0.921
Epoch: 91   - Cost: 0.248    Valid Accuracy: 0.921
Epoch: 92   - Cost: 0.248    Valid Accuracy: 0.922
Epoch: 93   - Cost: 0.247    Valid Accuracy: 0.921
Epoch: 94   - Cost: 0.246    Valid Accuracy: 0.922
Epoch: 95   - Cost: 0.245    Valid Accuracy: 0.922
Epoch: 96   - Cost: 0.245    Valid Accuracy: 0.922
Epoch: 97   - Cost: 0.244    Valid Accuracy: 0.922
Epoch: 98   - Cost: 0.243    Valid Accuracy: 0.922
Epoch: 99   - Cost: 0.243    Valid Accuracy: 0.922
Test Accuracy: 0.9171000123023987

In [ ]: