%load_ext watermark
%watermark -a 'Sebastian Raschka' -v -p tensorflow,numpy,h5py

"""
Explanation: Accompanying code examples of the book "Introduction to Artificial Neural Networks and Deep Learning: A Practical Guide with Applications in Python" by Sebastian Raschka. All code examples are released under the MIT license. If you find this content useful, please consider supporting the work by buying a copy of the book.
Other code examples and content are available on GitHub. The PDF and ebook versions of the book are available through Leanpub.
End of explanation
"""


# Note that executing the following code 
# cell will download the MNIST dataset
# and save all the 60,000 images as separate JPEG
# files. This might take a few minutes depending
# on your machine.

import numpy as np
from helper import mnist_export_to_jpg

np.random.seed(123)
mnist_export_to_jpg(path='./')

import os

for i in ('train', 'valid', 'test'):
    print('mnist_%s subdirectories' % i, os.listdir('mnist_%s' % i))

"""
Explanation: Storing an Image Dataset for Minibatch Training using HDF5
This notebook provides an example for how to save a large dataset of images as Hierarchical Data Format (HDF) for quick access during minibatch learning. This approach uses the common HDF5 format and should be accessible to any programming language or tool with an HDF5 API.
While this approach performs reasonably well (sufficiently well for my applications), you may also be interested in TensorFlow's "Reading Data" guide to work with TfRecords and file queues.
0. The Dataset
Let's pretend we have a directory of images containing two subdirectories with images for training, validation, and testing. The following function will create such a dataset of images in PNG format locally for demonstration purposes.
End of explanation
"""


%matplotlib inline
import matplotlib.image as mpimg
import matplotlib.pyplot as plt
import os

some_img = os.path.join('./mnist_train/9/', os.listdir('./mnist_train/9/')[0])

img = mpimg.imread(some_img)
print(img.shape)
plt.imshow(img, cmap='binary');

"""
Explanation: Note that the names of the subdirectories correspond directly to the class label of the images that are stored under it.
To make sure that the images look okay, the snippet below plots an example image from the subdirectory mnist_train/9/:
End of explanation
"""


import numpy as np
import h5py
import glob


def images_to_h5(data_stempath='./mnist_',
                 width=28, height=28, channels=1,
                 shuffle=False, random_seed=None):
    
    with h5py.File('mnist_batches.h5', 'w') as h5f:
    
        for s in ['train', 'valid', 'test']:
            img_paths = [p for p in glob.iglob('%s%s/**/*.jpg' % 
                                       (data_stempath, s), 
                                        recursive=True)]

            dset1 = h5f.create_dataset('%s/images' % s, 
                                       shape=[len(img_paths), 
                                              width, height, channels], 
                                       compression=None,
                                       dtype='uint8')
            dset2 = h5f.create_dataset('%s/labels' % s, 
                                       shape=[len(img_paths)], 
                                       compression=None,
                                       dtype='uint8')
            dset3 = h5f.create_dataset('%s/file_ids' % s, 
                                       shape=[len(img_paths)], 
                                       compression=None,
                                       dtype='S5')
            
            rand_indices = np.arange(len(img_paths))
            
            if shuffle:
                rng = np.random.RandomState(random_seed)
                rng.shuffle(rand_indices)

            for idx, path in enumerate(img_paths):

                rand_idx = rand_indices[idx]
                label = int(os.path.basename(os.path.dirname(path)))
                image = mpimg.imread(path)
                dset1[rand_idx] = image.reshape(width, height, channels)
                dset2[rand_idx] = label
                dset3[rand_idx] = np.array([os.path.basename(path)], dtype='S6')

"""
Explanation: Note: The JPEG format introduces a few artifacts that we can see in the image above. In this case, we use JPEG instead of PNG. Here, JPEG is used for demonstration purposes since that's still format many image datasets are stored in.
1. Saving images as HDF5
The following wrapper function creates .h5 file containing training, testing, and validation datasets. It will group images together into larger integer arrays that are then saved as subgroups in the HDF5 file. For instance, the training images will be saved as 'train/images' and the corresponding labels as 'train/labels' subgroup.
End of explanation
"""


images_to_h5(shuffle=True, random_seed=123)

"""
Explanation: Note that we didn't specify any compression format. The reason is that non-compressed HDF5 datasets are much faster to read, which is an important factor for training deep learning systems. In this case, the dataset is about ~47 Mb in size. However, we are working with larger datasets, compressing the HDF5 dataset might be one easy way to deal with hardware storage limitations.
End of explanation
"""


with h5py.File('mnist_batches.h5', 'r') as h5f:
    print(h5f['train/images'].shape)
    print(h5f['train/labels'].shape)
    print(h5f['train/file_ids'].shape)

with h5py.File('mnist_batches.h5', 'r') as h5f:

    plt.imshow(h5f['train/images'][0][:, :, -1], cmap='binary');
    print('Class label:', h5f['train/labels'][0])
    print('File ID:', h5f['train/file_ids'][0])

"""
Explanation: To check that the archiving worked correctly, we will now load the training images and print the array shape. Note that we can now access each archive similar to a python dictionary. Here the 'data' key contains the image data and the 'labels' key stores an array containing the corresponding class labels:
End of explanation
"""


class BatchLoader():
    def __init__(self, minibatches_path, 
                 normalize=True):
        
        self.minibatches_path = minibatches_path
        self.normalize = normalize
        self.num_train = 45000
        self.num_valid = 5000
        self.num_test = 10000
        self.n_classes = 10


    def load_train_epoch(self, batch_size=50, onehot=False,
                         shuffle_batch=False, prefetch_batches=1, seed=None):
        for batch_x, batch_y in self._load_epoch(which='train',
                                                 batch_size=batch_size,
                                                 onehot=onehot,
                                                 shuffle_batch=shuffle_batch,
                                                 prefetch_batches=prefetch_batches, 
                                                 seed=seed):
            yield batch_x, batch_y

    def load_test_epoch(self, batch_size=50, onehot=False,
                        shuffle_batch=False, prefetch_batches=1, seed=None):
        for batch_x, batch_y in self._load_epoch(which='test',
                                                 batch_size=batch_size,
                                                 onehot=onehot,
                                                 shuffle_batch=shuffle_batch,
                                                 prefetch_batches=prefetch_batches,
                                                 seed=seed):
            yield batch_x, batch_y
            
    def load_validation_epoch(self, batch_size=50, onehot=False,
                              shuffle_batch=False, prefetch_batches=1, seed=None):
        for batch_x, batch_y in self._load_epoch(which='valid',
                                                 batch_size=batch_size,
                                                 onehot=onehot,
                                                 shuffle_batch=shuffle_batch,
                                                 prefetch_batches=prefetch_batches, 
                                                 seed=seed):
            yield batch_x, batch_y

    def _load_epoch(self, which='train', batch_size=50, onehot=False,
                    shuffle_batch=False, prefetch_batches=1, seed=None):
        
        prefetch_size = prefetch_batches * batch_size
        
        if shuffle_batch:
            rgen = np.random.RandomState(seed)

        with h5py.File(self.minibatches_path, 'r') as h5f:
            indices = np.arange(h5f['%s/images' % which].shape[0])
            
            for start_idx in range(0, indices.shape[0] - prefetch_size + 1,
                                   prefetch_size):           
            

                x_batch = h5f['%s/images' % which][start_idx:start_idx + prefetch_size]
                x_batch = x_batch.astype(np.float32)
                y_batch = h5f['%s/labels' % which][start_idx:start_idx + prefetch_size]

                if onehot:
                    y_batch = (np.arange(self.n_classes) == 
                               y_batch[:, None]).astype(np.uint8)

                if self.normalize:
                    # normalize to [0, 1] range
                    x_batch = x_batch.astype(np.float32) / 255.

                if shuffle_batch:
                    rand_indices = np.arange(prefetch_size)
                    rgen.shuffle(rand_indices)
                    x_batch = x_batch[rand_indices]
                    y_batch = y_batch[rand_indices]

                for batch_idx in range(0, x_batch.shape[0] - batch_size + 1,
                                       batch_size):
                    
                    yield (x_batch[batch_idx:batch_idx + batch_size], 
                           y_batch[batch_idx:batch_idx + batch_size])

"""
Explanation: 2. Loading Minibatches
The following cell implements a class for iterating over the MNIST images, based on the .h5 file, conveniently. 
Via the normalize parameter we additionally scale the image pixels to [0, 1] range, which typically helps with gradient-based optimization in practice.
The key functions (here: generators) are

load_train_epoch
load_valid_epoch
load_test_epoch

These let us iterate over small chunks (determined via minibatch_size) and yield minibatches via memory-efficient Python generators. Via the two shuffle parameters, we can further control if the images within each batch to be shuffled. By setting onehot=True, the labels are converted into a onehot representation for convenience.
End of explanation
"""


batch_loader = BatchLoader(minibatches_path='./mnist_batches.h5', 
                           normalize=True)

for batch_x, batch_y in batch_loader.load_train_epoch(batch_size=50, onehot=True):
    print(batch_x.shape)
    print(batch_y.shape)
    break

cnt = 0
for batch_x, batch_y in batch_loader.load_train_epoch(
        batch_size=100, onehot=True):
    cnt += batch_x.shape[0]
    
print('One training epoch contains %d images' % cnt)

def one_epoch():
    for batch_x, batch_y in batch_loader.load_train_epoch(
            batch_size=100, onehot=True):
        pass
    
% timeit one_epoch()

"""
Explanation: The following for loop will iterate over the 45,000 training examples in our MNIST training set, yielding 50 images and labels at a time (note that we previously set aside 5000 training example as our validation datast).
End of explanation
"""


def one_epoch():
    for batch_x, batch_y in batch_loader.load_train_epoch(
            batch_size=100, shuffle_batch=True, prefetch_batches=4, 
            seed=123, onehot=True):
        pass
    
% timeit one_epoch()

"""
Explanation: As we can see from the benchmark above, an iteration over one training epoch (45k images) is relatively fast.
Similarly, we could iterate over validation and test data via 

batch_loader.load_validation_epoch
batch_loader.load_test_epoch

Note that increasing the batch_size can substantially improve the computationally efficiency loading an epoch, since it would lower the number of iterations. Further, we used two nested for loops in _load_epoch, where the inner one yields the actual batches. The purpose of the outer loop in this function is to prefetch multiple batches for shuffling -- otherwise, the shuffling won't have any effect on the gradients.
End of explanation
"""


import tensorflow as tf

##########################
### SETTINGS
##########################

# Hyperparameters
learning_rate = 0.1
training_epochs = 15
batch_size = 100

# Architecture
n_hidden_1 = 128
n_hidden_2 = 256
height, width = 28, 28
n_classes = 10


##########################
### GRAPH DEFINITION
##########################

g = tf.Graph()
with g.as_default():
    
    tf.set_random_seed(123)

    # Input data
    tf_x = tf.placeholder(tf.float32, [None, height, width, 1], name='features')
    tf_x_flat = tf.reshape(tf_x, shape=[-1, height*width])
    tf_y = tf.placeholder(tf.int32, [None, n_classes], name='targets')

    # Model parameters
    weights = {
        'h1': tf.Variable(tf.truncated_normal([width*height, n_hidden_1], stddev=0.1)),
        'h2': tf.Variable(tf.truncated_normal([n_hidden_1, n_hidden_2], stddev=0.1)),
        'out': tf.Variable(tf.truncated_normal([n_hidden_2, n_classes], stddev=0.1))
    }
    biases = {
        'b1': tf.Variable(tf.zeros([n_hidden_1])),
        'b2': tf.Variable(tf.zeros([n_hidden_2])),
        'out': tf.Variable(tf.zeros([n_classes]))
    }

    # Multilayer perceptron
    layer_1 = tf.add(tf.matmul(tf_x_flat, weights['h1']), biases['b1'])
    layer_1 = tf.nn.relu(layer_1)
    layer_2 = tf.add(tf.matmul(layer_1, weights['h2']), biases['b2'])
    layer_2 = tf.nn.relu(layer_2)
    out_layer = tf.matmul(layer_2, weights['out']) + biases['out']

    # Loss and optimizer
    loss = tf.nn.softmax_cross_entropy_with_logits(logits=out_layer, labels=tf_y)
    cost = tf.reduce_mean(loss, name='cost')
    optimizer = tf.train.GradientDescentOptimizer(learning_rate=learning_rate)
    train = optimizer.minimize(cost, name='train')

    # Prediction
    correct_prediction = tf.equal(tf.argmax(tf_y, 1), tf.argmax(out_layer, 1))
    accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32), name='accuracy')

"""
Explanation: Also, as we can see from the benchmark, prefetching multiple batches from the HDF5 database can speed up the loading of an epoch. Note that this could not always practicable (for example, when we are working with high-resolution images) due to memory constraints.
3. Training a Model using TensorFlow's feed_dict
The following code demonstrate how we can feed our minibatches into a TensorFlow graph using a TensorFlow session's feed_dict.
Multilayer Perceptron Graph
End of explanation
"""


##########################
### TRAINING & EVALUATION
##########################

batch_loader = BatchLoader(minibatches_path='./mnist_batches.h5', 
                           normalize=True)

# preload small validation set
# by unpacking the generator
[valid_data] = batch_loader.load_validation_epoch(batch_size=5000, 
                                                   onehot=True)
valid_x, valid_y = valid_data[0], valid_data[1]
del valid_data

with tf.Session(graph=g) as sess:
    sess.run(tf.global_variables_initializer())

    for epoch in range(training_epochs):
        avg_cost = 0.

        n_batches = 0
        for batch_x, batch_y in batch_loader.load_train_epoch(batch_size=batch_size, 
                                                              onehot=True,
                                                              shuffle_batch=True,
                                                              prefetch_batches=10,
                                                              seed=epoch):
            n_batches += 1
            _, c = sess.run(['train', 'cost:0'], feed_dict={'features:0': batch_x,
                                                            'targets:0': batch_y.astype(np.int)})
            avg_cost += c
        
        train_acc = sess.run('accuracy:0', feed_dict={'features:0': batch_x,
                                                      'targets:0': batch_y})
        
        valid_acc = sess.run('accuracy:0', feed_dict={'features:0': valid_x,
                                                      'targets:0': valid_y})  
        
        print("Epoch: %03d | AvgCost: %.3f" % (epoch + 1, avg_cost / n_batches), end="")
        print(" | MbTrain/Valid ACC: %.3f/%.3f" % (train_acc, valid_acc))
        
        
    # imagine test set is too large to fit into memory:
    test_acc, cnt = 0., 0
    for test_x, test_y in batch_loader.load_test_epoch(batch_size=100, 
                                                       onehot=True):   
        cnt += 1
        acc = sess.run(accuracy, feed_dict={'features:0': test_x,
                                            'targets:0': test_y})
        test_acc += acc
    print('Test ACC: %.3f' % (test_acc / cnt))

"""
Explanation: Training the Neural Network with Minibatches
End of explanation
"""


