{"cells":[{"cell_type":"markdown","metadata":{"_cell_guid":"2b259663-cbdb-69ed-70f3-2d0bee1bdefc"},"source":"Deep Neural Networks with TensorFlow\n\n- based on https://www.kaggle.com/kakauandme/digit-recognizer/tensorflow-deep-nn \n- extended and achieved **0.99157** score\n- added documentations to tensorflow built-in functions"},{"cell_type":"code","execution_count":null,"metadata":{"_cell_guid":"aee84856-1c55-ff2f-6c0e-74b14832124c"},"outputs":[],"source":"# import packages\n\nimport numpy as np\nimport pandas as pd\nimport tensorflow as tf\nimport matplotlib.pyplot as plt\nimport matplotlib.cm as cm\nfrom subprocess import check_output\n\n# Learning rate for learning algorithm\nLEARNING_RATE = 5e-4\n\n# number of training iterations\nTRAINING_ITERATIONS = 10000\nITERATIONS_PER_RUN = 100\n\n# dropout. Dropout is an extremely effective and simple regularization technique\n# based on keeping a neuron active with some probability p (a hyperparameter, here is DROPOUT), \n# or setting it to zero otherwise.\n# More about dropout http://cs231n.github.io/neural-networks-2/ \nDROPOUT = 0.5\n# training is made by selecting batches of size 50\nBATCH_SIZE = 100\n\n# validation set size. Validation set is a set of examples used to tune the parameters .\n# set to 0 to train on all available data\nVALIDATION_SIZE = 2000\n\n# image number to output\nIMAGE_TO_DISPLAY = 25"},{"cell_type":"code","execution_count":null,"metadata":{"_cell_guid":"6dd4e899-deb1-d869-78fe-e3b482e46eba"},"outputs":[],"source":"# Strutified shuffle is used insted of simple shuffle in order to achieve sample balancing\n    # or equal number of examples in each of 10 classes.\n# Since there are different number of examples for each 10 classes in the MNIST data you may\n    # also use simple shuffle.\n\ndef stratified_shuffle(labels, num_classes):\n    ix = np.argsort(labels).reshape((num_classes,-1))\n    for i in range(len(ix)):\n        np.random.shuffle(ix[i])\n    return ix.T.reshape((-1))"},{"cell_type":"code","execution_count":null,"metadata":{"_cell_guid":"c5eb4fd4-26af-08b8-e090-be6958981258"},"outputs":[],"source":"# preload train and test data\ndataset = pd.read_csv(\"../input/train.csv\")\ntest = pd.read_csv(\"../input/test.csv\").values\n\nimages = dataset.iloc[:,1:].values\nimages = images.astype(np.float)\n\n# convert from [0:255] => [0.0:1.0]\nimages = np.multiply(images, 1.0 / 255.0)\nprint('data size: (%g, %g)' % images.shape)\n\n# size of one image - 784 values which can be transformed to 28 by 28 image\nimage_size = images.shape[1]\nprint ('image_size => {0}'.format(image_size))\n\n# in this case all images are square (28x28)\nimage_width = image_height = np.ceil(np.sqrt(image_size)).astype(np.uint8)\nprint ('image_width => {0}\\nimage_height => {1}'.format(image_width,image_height))"},{"cell_type":"code","execution_count":null,"metadata":{"_cell_guid":"6083f494-c491-d98d-5239-bfe54f362705"},"outputs":[],"source":"# display an image\ndef display(img):\n    \n    # (784) => (28x28)\n    one_image = img.reshape(image_width,image_height)\n    \n    plt.axis('off')\n    plt.imshow(one_image, cmap=cm.binary)\n\n# display an image. IMAGE_TO_DISPLAY = 25\ndisplay(images[IMAGE_TO_DISPLAY])"},{"cell_type":"code","execution_count":null,"metadata":{"_cell_guid":"77ee1345-2b88-fb04-cea2-380a99f2455a"},"outputs":[],"source":"# print information about image size, label of image-to-display and number of labels\nlabels_flat = dataset[[0]].values.ravel()\nprint('length of one image ({0})'.format(len(labels_flat)))\nprint ('label of image [{0}] => {1}'.format(IMAGE_TO_DISPLAY,labels_flat[IMAGE_TO_DISPLAY]))\n\nlabels_count = np.unique(labels_flat).shape[0]\nprint('number of labes => {0}'.format(labels_count))"},{"cell_type":"code","execution_count":null,"metadata":{"_cell_guid":"88c77ef9-2801-7b09-c152-9b5306ecde25"},"outputs":[],"source":"# convert class labels from scalars to one-hot vectors\n# 0 => [1 0 0 0 0 0 0 0 0 0]\n# 1 => [0 1 0 0 0 0 0 0 0 0]\n# ...\n# 9 => [0 0 0 0 0 0 0 0 0 1]\n\ndef dense_to_one_hot(labels_dense, num_classes):\n    num_labels = labels_dense.shape[0]\n    index_offset = np.arange(num_labels) * num_classes\n    labels_one_hot = np.zeros((num_labels, num_classes))\n    labels_one_hot.flat[index_offset + labels_dense.ravel()] = 1\n    return labels_one_hot\n\nlabels = dense_to_one_hot(labels_flat, labels_count)\nlabels = labels.astype(np.uint8)\n\nprint('labels({0[0]},{0[1]})'.format(labels.shape))\nprint ('labels vector for image [{0}] => {1}'.format(IMAGE_TO_DISPLAY,labels[IMAGE_TO_DISPLAY]))"},{"cell_type":"code","execution_count":null,"metadata":{"_cell_guid":"886f637d-b9ae-ee72-bd34-91e23ea0af20"},"outputs":[],"source":"# split data into training & validation sets\nvalidation_images = images[:VALIDATION_SIZE]\nvalidation_labels = labels[:VALIDATION_SIZE]\n\ntrain_images = images[VALIDATION_SIZE:]\ntrain_labels = labels[VALIDATION_SIZE:]\ntrain_labels_flat = labels_flat[VALIDATION_SIZE:]\n\n#train_images = images\n#train_labels = labels\n#train_labels_flat = labels_flat\n\nprint('train data size({0[0]},{0[1]})'.format(train_images.shape))\nprint('validation data size({0[0]},{0[1]})'.format(validation_images.shape))"},{"cell_type":"code","execution_count":null,"metadata":{"_cell_guid":"f25c4279-a723-3b3f-47f2-b444f2b66cc7"},"outputs":[],"source":"# weights initialization.\n# tf.truncated_normal: Outputs random values from a truncated normal distribution.\n# The generated values follow a normal distribution with specified standard deviation.\n\ndef weight_variable(shape):\n    initial = tf.truncated_normal(shape, stddev=0.1)\n    return tf.Variable(initial)\n\n# tf.constant: Creates a constant tensor. \n# The resulting tensor is populated with values of type dtype, as specified by arguments value and shape\ndef bias_variable(shape):\n    initial = tf.constant(0.1, shape=shape)\n    return tf.Variable(initial)"},{"cell_type":"code","execution_count":null,"metadata":{"_cell_guid":"14a7eec3-d624-c01d-a8ea-2b51d92bd003"},"outputs":[],"source":"# convolution\n# Computes a 2-D convolution given 4-D input and filter tensors.\n# tf.nn.conv2d(input, filter, strides, padding, use_cudnn_on_gpu=None, data_format=None, name=None)\n# input: A Tensor. Must be one of the following types: half, float32, float64.\n# filter: A Tensor. Must have the same type as input.\n# strides: A list of ints. 1-D of length 4. The stride of the sliding window for each dimension \n            # of input. Must be in the same order as the dimension specified with format.\n# padding: A string from: \"SAME\", \"VALID\". The type of padding algorithm to use.\n\ndef conv2d(x, W):\n    return tf.nn.conv2d(x, W, strides=[1, 1, 1, 1], padding='SAME')"},{"cell_type":"code","execution_count":null,"metadata":{"_cell_guid":"ac4b0c8f-3f94-5bbd-20d3-cb91c374596f"},"outputs":[],"source":"# Performs the max pooling on the input.\n# tf.nn.max_pool(value, ksize, strides, padding, data_format='NHWC', name=None)\n# value: A 4-D Tensor with shape [batch, height, width, channels] and type tf.float32.\n# ksize: A list of ints that has length >= 4. The size of the window for each dimension \n        # of the input tensor.\n# strides: A list of ints that has length >= 4. The stride of the sliding window for \n            # each dimension of the input tensor.\n# padding: A string, either 'VALID' or 'SAME'. \n\ndef max_pool_2x2(x):\n    return tf.nn.max_pool(x, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding='SAME')"},{"cell_type":"code","execution_count":null,"metadata":{"_cell_guid":"7896ced3-b214-0ba8-a1c2-27bbeb4f9e60"},"outputs":[],"source":"# input & output of NN\n\n# images\nx = tf.placeholder('float', shape=[None, image_size])\n# labels\ny_ = tf.placeholder('float', shape=[None, labels_count])"},{"cell_type":"code","execution_count":null,"metadata":{"_cell_guid":"8f284c89-f890-75ed-9281-5299fefd8389"},"outputs":[],"source":"# first convolutional layer\nW_conv1 = weight_variable([5, 5, 1, 32])\nb_conv1 = bias_variable([32])\n\n# (40000,784) => (40000,28,28,1)]\n# tf.reshape(tensor, shape, name=None)\n# Given tensor, this operation returns a tensor that has the same values as tensor with shape shape.\nimage = tf.reshape(x, [-1,image_width , image_height,1])\n#print (image.get_shape()) # =>(40000,28,28,1)\n\nh_conv1 = tf.nn.relu(conv2d(image, W_conv1) + b_conv1)\n#print (h_conv1.get_shape()) # => (40000, 28, 28, 32)\nh_pool1 = max_pool_2x2(h_conv1)\n#print (h_pool1.get_shape()) # => (40000, 14, 14, 32)\n\n# Prepare for visualization\n# display 32 fetures in 4 by 8 grid\nlayer1 = tf.reshape(h_conv1, (-1, image_height, image_width, 4 ,8))  \n# reorder so the channels are in the first dimension, x and y follow.\nlayer1 = tf.transpose(layer1, (0, 3, 1, 4,2))\nlayer1 = tf.reshape(layer1, (-1, image_height*4, image_width*8)) "},{"cell_type":"code","execution_count":null,"metadata":{"_cell_guid":"81baa5d3-84d9-1e87-5210-170dcf1da26a"},"outputs":[],"source":"# second convolutional layer\nW_conv2 = weight_variable([5, 5, 32, 64])\nb_conv2 = bias_variable([64])\n\nh_conv2 = tf.nn.relu(conv2d(h_pool1, W_conv2) + b_conv2)\n#print (h_conv2.get_shape()) # => (40000, 14,14, 64)\nh_pool2 = max_pool_2x2(h_conv2)\n#print (h_pool2.get_shape()) # => (40000, 7, 7, 64)\n\n# Prepare for visualization\n# display 64 fetures in 4 by 16 grid\nlayer2 = tf.reshape(h_conv2, (-1, 14, 14, 4 ,16))  \n# reorder so the channels are in the first dimension, x and y follow.\nlayer2 = tf.transpose(layer2, (0, 3, 1, 4,2))\nlayer2 = tf.reshape(layer2, (-1, 14*4, 14*16)) "},{"cell_type":"code","execution_count":null,"metadata":{"_cell_guid":"288b4d3c-e82e-daf5-eb4a-af45c99f6679"},"outputs":[],"source":"# fully-connected layer\nW_fc1 = weight_variable([7 * 7 * 64, 1024])\nb_fc1 = bias_variable([1024])\n\n# (40000, 7, 7, 64) => (40000, 3136)\nh_pool2_flat = tf.reshape(h_pool2, [-1, 7*7*64])\n\n#tf.matmul(a, b, transpose_a=False, transpose_b=False, a_is_sparse=False, b_is_sparse=False, name=None)\n# Multiplies matrix a by matrix b, producing a * b.\nh_fc1 = tf.nn.relu(tf.matmul(h_pool2_flat, W_fc1) + b_fc1)\n#print (h_fc1.get_shape()) # => (40000, 1024)"},{"cell_type":"code","execution_count":null,"metadata":{"_cell_guid":"d096f94d-021a-6b6a-3766-148057344ba2"},"outputs":[],"source":"# dropout\n# tf.nn.dropout(x, keep_prob, noise_shape=None, seed=None, name=None)\n# Computes dropout.\n# With probability keep_prob, outputs the input element scaled up by 1 / keep_prob, otherwise outputs 0. \n    # The scaling is so that the expected sum is unchanged.\nkeep_prob = tf.placeholder('float')\nh_fc1_drop = tf.nn.dropout(h_fc1, keep_prob)"},{"cell_type":"code","execution_count":null,"metadata":{"_cell_guid":"247dd8de-d8e7-70ef-29e9-906f8baa9963"},"outputs":[],"source":"# readout layer for deep net\nW_fc2 = weight_variable([1024, labels_count])\nb_fc2 = bias_variable([labels_count])\n\ny = tf.nn.softmax(tf.matmul(h_fc1_drop, W_fc2) + b_fc2)\n\n#print (y.get_shape()) # => (40000, 10)"},{"cell_type":"code","execution_count":null,"metadata":{"_cell_guid":"13992fbb-9696-e881-6ecb-bc0f648e75b0"},"outputs":[],"source":"# cost function\ncross_entropy = -tf.reduce_sum(y_*tf.log(y))\n\n# optimisation function\nglobal_step = tf.Variable(0, name='global_step', trainable=False)\ntrain_step = tf.train.AdamOptimizer(LEARNING_RATE).minimize(cross_entropy, global_step=global_step)\n\n# evaluation\ncorrect_prediction = tf.equal(tf.argmax(y,1), tf.argmax(y_,1))\n\naccuracy = tf.reduce_mean(tf.cast(correct_prediction, 'float'))"},{"cell_type":"code","execution_count":null,"metadata":{"_cell_guid":"3dbbbf92-ec8c-8a6e-9db2-eefc66f17fc7"},"outputs":[],"source":"# prediction function\n#[0.1, 0.9, 0.2, 0.1, 0.1 0.3, 0.5, 0.1, 0.2, 0.3] => 1\npredict = tf.argmax(y,1)\nprint(predict)"},{"cell_type":"code","execution_count":null,"metadata":{"_cell_guid":"c101e1cb-961a-0419-4a2f-dca346b024af"},"outputs":[],"source":"# Training\nepochs_completed = 0\nindex_in_epoch = 0\nnum_examples = train_images.shape[0]\n\n# visualisation variables\ntrain_accuracies = []\nvalidation_accuracies = []\nx_range = []\n\ndisplay_step=100\n\n# serve data by batches\ndef next_batch(batch_size):\n    \n    global train_images\n    global train_labels\n    global train_labels_flat\n    global index_in_epoch\n    global epochs_completed\n    \n    start = index_in_epoch\n    index_in_epoch += batch_size\n    \n    # when all trainig data have been already used, it is reorder randomly    \n    if index_in_epoch > num_examples:\n        # finished epoch\n        epochs_completed += 1\n        # shuffle the data\n        #perm = np.arange(num_examples)\n        #np.random.shuffle(perm)\n        perm = stratified_shuffle(train_labels_flat, 10)\n        train_images = train_images[perm]\n        train_labels = train_labels[perm]\n        train_labels_flat = train_labels_flat[perm]\n        # start next epoch\n        start = 0\n        index_in_epoch = batch_size\n        assert batch_size <= num_examples\n    end = index_in_epoch\n    return train_images[start:end], train_labels[start:end]"},{"cell_type":"code","execution_count":null,"metadata":{"_cell_guid":"b0995616-17b0-5410-9881-4b66c14273be"},"outputs":[],"source":"# displays the progress of the training\n# Training accuracy, validation accuracy and iterations\n\ndef check_progress(sess, accuracy, batch_xs, batch_ys, i):\n    import datetime\n    train_accuracy = accuracy.eval(session=sess, feed_dict={x: batch_xs, y_: batch_ys, keep_prob: 1.0})       \n    if(VALIDATION_SIZE):\n        validation_accuracy = accuracy.eval(session=sess, feed_dict={x: validation_images,\n                                                                     y_: validation_labels,\n                                                                     keep_prob: 1.0})                                  \n        print('%s: trn / val => %.4f / %.4f for step %d'\n              % (str(datetime.datetime.now()), train_accuracy, validation_accuracy, i+1))\n    else:\n        print('training_accuracy => %.4f for step %d' % (train_accuracy, i+1))\n        validation_accuracy = []\n    return (train_accuracy, validation_accuracy)"},{"cell_type":"code","execution_count":null,"metadata":{"_cell_guid":"e9f4489c-70d2-4c35-cff2-83df5d9ab8d4"},"outputs":[],"source":"# In this part we save model after a certain number of iterations and use the saved model\n# for the next round\n# By this we achieve 10 epochs on the entire training data (validation data included)\n\nsaver = tf.train.Saver(max_to_keep=5)\nsess = tf.Session()\nsess.run(tf.initialize_all_variables())\n\nckpt = tf.train.get_checkpoint_state('.')\nif ckpt and ckpt.model_checkpoint_path:\n    saver.restore(sess, ckpt.model_checkpoint_path)\n    print(\"Restored session from: %s\" % ckpt.model_checkpoint_path)\nelse:\n    print(\"No checkpoint found.\")\n\nstart_step = global_step.eval(sess)\nfor i in range(start_step, min(start_step + ITERATIONS_PER_RUN, TRAINING_ITERATIONS)):\n    #get new batch\n    batch_xs, batch_ys = next_batch(BATCH_SIZE)\n\n    # train on batch\n    sess.run(train_step, feed_dict={x: batch_xs, y_: batch_ys, keep_prob: DROPOUT})\n\n    # check progress and create a checkpoint\n    if (i+1) % display_step == 0 or (i+1) == TRAINING_ITERATIONS:\n        train_accuracy, validation_accuracy = check_progress(sess, accuracy, batch_xs, batch_ys, i)\n        train_accuracies.append(train_accuracy)\n        validation_accuracies.append(validation_accuracy)\n        x_range.append(i)\n\n        saver.save(sess, 'model', global_step=i+1)\n\n        # increase display_step\n        #if i % (display_step*10) == 0 and i:\n        #    display_step *= 2"},{"cell_type":"code","execution_count":null,"metadata":{"_cell_guid":"c7be9290-71d1-f2ea-61e0-745067e7ea08"},"outputs":[],"source":"#ckpt = tf.train.get_checkpoint_state('.')\n#ckpt.model_checkpoint_path\n#saver.restore(sess, './model-3800')"},{"cell_type":"code","execution_count":null,"metadata":{"_cell_guid":"d59a83f2-3be1-55da-b0b9-0b8ad83172a1"},"outputs":[],"source":"# check final accuracy on validation set.\n# Since we may use validation data set in training data set the accuracy is around 0.99\n\nif(VALIDATION_SIZE):\n    validation_accuracy = accuracy.eval(session=sess, feed_dict={x: validation_images,\n                                                                 y_: validation_labels,\n                                                                 keep_prob: 1.0})\n    print('validation_accuracy => %.4f' % validation_accuracy)\n    plt.plot(x_range, train_accuracies,'-b', label='Training')\n    plt.plot(x_range, validation_accuracies,'-g', label='Validation')\n    plt.legend(loc='lower right', frameon=False)\n    plt.ylim(ymax = 1.1, ymin = 0.9)\n    plt.ylabel('accuracy')\n    plt.xlabel('step')\n    plt.grid()\n    plt.show()"},{"cell_type":"code","execution_count":null,"metadata":{"_cell_guid":"1d6a5b15-6099-65f3-e2a1-8c1e3a74a161"},"outputs":[],"source":"# read test data from CSV file \ntest_images = pd.read_csv('../input/test.csv').values\ntest_images = test_images.astype(np.float)\n\n# convert from [0:255] => [0.0:1.0]\ntest_images = np.multiply(test_images, 1.0 / 255.0)\nprint('test_images({0[0]},{0[1]})'.format(test_images.shape))\n\n# predict test set\n#predicted_lables = predict.eval(feed_dict={x: test_images, keep_prob: 1.0})\n\n# using batches is more resource efficient\npredicted_lables = np.zeros(test_images.shape[0])\nfor i in range(0,test_images.shape[0]//BATCH_SIZE):\n    predicted_lables[i*BATCH_SIZE : (i+1)*BATCH_SIZE] = predict.eval(\n        session=sess, feed_dict={x: test_images[i*BATCH_SIZE : (i+1)*BATCH_SIZE],\n                                 keep_prob: 1.0})\n\nprint('predicted_lables({0})'.format(len(predicted_lables)))\n\n# output test image and prediction\ndisplay(test_images[IMAGE_TO_DISPLAY])\nprint ('predicted_lables[{0}] => {1}'.format(IMAGE_TO_DISPLAY,predicted_lables[IMAGE_TO_DISPLAY]))\n\n# save results\nfile_name = 'submission_softmax_%s.csv' % global_step.eval(sess)\nnp.savetxt(file_name, \n           np.c_[range(1,len(test_images)+1),predicted_lables], \n           delimiter=',', \n           header = 'ImageId,Label', \n           comments = '', \n           fmt='%d')\nprint('saved: %s' % file_name)"},{"cell_type":"code","execution_count":null,"metadata":{"_cell_guid":"76c36fc9-4d4a-e7f7-39e8-87812472841a"},"outputs":[],"source":"layer1_grid = layer1.eval(session=sess, feed_dict={x: test_images[IMAGE_TO_DISPLAY:IMAGE_TO_DISPLAY+1], \n                                                   keep_prob: 1.0})\nplt.axis('off')\nplt.imshow(layer1_grid[0], cmap=cm.seismic )"},{"cell_type":"code","execution_count":null,"metadata":{"_cell_guid":"2f4dcca5-5153-e7b8-fcd9-8b9fb1f42c18"},"outputs":[],"source":"sess.close()"},{"cell_type":"code","execution_count":null,"metadata":{"_cell_guid":"8c251f6a-512a-21f6-2b65-0c90f80b964b"},"outputs":[],"source":"#!rm model-6*\n!ls -ahl"},{"cell_type":"code","execution_count":null,"metadata":{"_cell_guid":"8a6f9f5d-8b96-aa02-6e25-927a130d43e1"},"outputs":[],"source":"#!cp model-8200 model-submission-8200\n#!cp model-8200.meta model-submission-8200.meta\n#!cat submission_softmax_8200.csv"}],"metadata":{"_change_revision":0,"_is_fork":false,"kernelspec":{"display_name":"Python 3","language":"python","name":"python3"},"language_info":{"codemirror_mode":{"name":"ipython","version":3},"file_extension":".py","mimetype":"text/x-python","name":"python","nbconvert_exporter":"python","pygments_lexer":"ipython3","version":"3.5.2"}},"nbformat":4,"nbformat_minor":0}