{"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"pygments_lexer":"ipython3","nbconvert_exporter":"python","version":"3.6.4","file_extension":".py","codemirror_mode":{"name":"ipython","version":3},"name":"python","mimetype":"text/x-python"}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"code","source":"import numpy as np\nimport pandas as pd\n\n%matplotlib inline\nimport matplotlib.pyplot as plt\nimport matplotlib.cm as cm\n\nimport tensorflow as tf\n\n# settings\nLEARNING_RATE = 1e-4\n# set to 20000 on local environment to get 0.99 accuracy\nTRAINING_ITERATIONS = 2500        \n    \nDROPOUT = 0.5\nBATCH_SIZE = 50\n\n# set to 0 to train on all available data\nVALIDATION_SIZE = 2000\n\n# image number to output\nIMAGE_TO_DISPLAY = 10","metadata":{"collapsed":false,"jupyter":{"outputs_hidden":false},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# read training data from CSV file \ndata = pd.read_csv('../input/digit-recognizer/train.csv')\n\nprint('data({0[0]},{0[1]})'.format(data.shape))\nprint (data.head())","metadata":{"collapsed":false,"jupyter":{"outputs_hidden":false},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"images = data.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)\n\nprint('images({0[0]},{0[1]})'.format(images.shape))","metadata":{"collapsed":false,"jupyter":{"outputs_hidden":false},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"image_size = images.shape[1]\nprint ('image_size => {0}'.format(image_size))\n\n# in this case all images are square\nimage_width = image_height = np.ceil(np.sqrt(image_size)).astype(np.uint8)\n\nprint ('image_width => {0}\\nimage_height => {1}'.format(image_width,image_height))","metadata":{"collapsed":false,"jupyter":{"outputs_hidden":false},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# display image\ndef display(img):\n    \n    # (784) => (28,28)\n    one_image = img.reshape(image_width,image_height)\n    \n    plt.axis('off')\n    plt.imshow(one_image, cmap=cm.binary)\n\n# output image     \ndisplay(images[IMAGE_TO_DISPLAY])","metadata":{"collapsed":false,"jupyter":{"outputs_hidden":false},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"labels_flat = data[[0]].values.ravel()\n\nprint('labels_flat({0})'.format(len(labels_flat)))\nprint ('labels_flat[{0}] => {1}'.format(IMAGE_TO_DISPLAY,labels_flat[IMAGE_TO_DISPLAY]))","metadata":{"collapsed":false,"jupyter":{"outputs_hidden":false},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"labels_count = np.unique(labels_flat).shape[0]\n\nprint('labels_count => {0}'.format(labels_count))","metadata":{"collapsed":false,"jupyter":{"outputs_hidden":false},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","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]\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[{0}] => {1}'.format(IMAGE_TO_DISPLAY,labels[IMAGE_TO_DISPLAY]))","metadata":{"collapsed":false,"jupyter":{"outputs_hidden":false},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# split data into training & validation\nvalidation_images = images[:VALIDATION_SIZE]\nvalidation_labels = labels[:VALIDATION_SIZE]\n\ntrain_images = images[VALIDATION_SIZE:]\ntrain_labels = labels[VALIDATION_SIZE:]\n\n\nprint('train_images({0[0]},{0[1]})'.format(train_images.shape))\nprint('validation_images({0[0]},{0[1]})'.format(validation_images.shape))","metadata":{"collapsed":false,"jupyter":{"outputs_hidden":false},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# weight initialization\ndef weight_variable(shape):\n    initial = tf.truncated_normal(shape, stddev=0.1)\n    return tf.Variable(initial)\n\ndef bias_variable(shape):\n    initial = tf.constant(0.1, shape=shape)\n    return tf.Variable(initial)","metadata":{"collapsed":false,"jupyter":{"outputs_hidden":false},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# convolution\ndef conv2d(x, W):\n    return tf.nn.conv2d(x, W, strides=[1, 1, 1, 1], padding='SAME')","metadata":{"collapsed":false,"jupyter":{"outputs_hidden":false},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# pooling\n# [[0,3],\n#  [4,2]] => 4\n\n# [[0,1],\n#  [1,1]] => 1\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')","metadata":{"collapsed":false,"jupyter":{"outputs_hidden":false},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","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])","metadata":{"collapsed":false,"jupyter":{"outputs_hidden":false},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","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)\nimage = tf.reshape(x, [-1,image_width , image_height,1])\n#print (image.get_shape()) # =>(40000,28,28,1)\n\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\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\n# reorder so the channels are in the first dimension, x and y follow.\nlayer1 = tf.transpose(layer1, (0, 3, 1, 4,2))\n\nlayer1 = tf.reshape(layer1, (-1, image_height*4, image_width*8)) ","metadata":{"collapsed":false,"jupyter":{"outputs_hidden":false},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","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\n# reorder so the channels are in the first dimension, x and y follow.\nlayer2 = tf.transpose(layer2, (0, 3, 1, 4,2))\n\nlayer2 = tf.reshape(layer2, (-1, 14*4, 14*16)) ","metadata":{"collapsed":false,"jupyter":{"outputs_hidden":false},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# densely 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\nh_fc1 = tf.nn.relu(tf.matmul(h_pool2_flat, W_fc1) + b_fc1)\n#print (h_fc1.get_shape()) # => (40000, 1024)","metadata":{"collapsed":false,"jupyter":{"outputs_hidden":false},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# dropout\nkeep_prob = tf.placeholder('float')\nh_fc1_drop = tf.nn.dropout(h_fc1, keep_prob)","metadata":{"collapsed":false,"jupyter":{"outputs_hidden":false},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","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)","metadata":{"collapsed":false,"jupyter":{"outputs_hidden":false},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# cost function\ncross_entropy = -tf.reduce_sum(y_*tf.log(y))\n\n\n# optimisation function\ntrain_step = tf.train.AdamOptimizer(LEARNING_RATE).minimize(cross_entropy)\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'))","metadata":{"collapsed":false,"jupyter":{"outputs_hidden":false},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","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)","metadata":{"collapsed":false,"jupyter":{"outputs_hidden":false},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"epochs_completed = 0\nindex_in_epoch = 0\nnum_examples = train_images.shape[0]\n\n# serve data by batches\ndef next_batch(batch_size):\n    \n    global train_images\n    global train_labels\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        train_images = train_images[perm]\n        train_labels = train_labels[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]","metadata":{"collapsed":false,"jupyter":{"outputs_hidden":false},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# start TensorFlow session\ninit = tf.initialize_all_variables()\nsess = tf.InteractiveSession()\n\nsess.run(init)","metadata":{"collapsed":false,"jupyter":{"outputs_hidden":false},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# visualisation variables\ntrain_accuracies = []\nvalidation_accuracies = []\nx_range = []\n\ndisplay_step=1\n\nfor i in range(TRAINING_ITERATIONS):\n\n    #get new batch\n    batch_xs, batch_ys = next_batch(BATCH_SIZE)        \n\n    # check progress on every 1st,2nd,...,10th,20th,...,100th... step\n    if i%display_step == 0 or (i+1) == TRAINING_ITERATIONS:\n        \n        train_accuracy = accuracy.eval(feed_dict={x:batch_xs, \n                                                  y_: batch_ys, \n                                                  keep_prob: 1.0})       \n        if(VALIDATION_SIZE):\n            validation_accuracy = accuracy.eval(feed_dict={ x: validation_images[0:BATCH_SIZE], \n                                                            y_: validation_labels[0:BATCH_SIZE], \n                                                            keep_prob: 1.0})                                  \n            print('training_accuracy / validation_accuracy => %.2f / %.2f for step %d'%(train_accuracy, validation_accuracy, i))\n            \n            validation_accuracies.append(validation_accuracy)\n            \n        else:\n             print('training_accuracy => %.4f for step %d'%(train_accuracy, i))\n        train_accuracies.append(train_accuracy)\n        x_range.append(i)\n        \n        # increase display_step\n        if i%(display_step*10) == 0 and i:\n            display_step *= 10\n    # train on batch\n    sess.run(train_step, feed_dict={x: batch_xs, y_: batch_ys, keep_prob: DROPOUT})","metadata":{"collapsed":false,"jupyter":{"outputs_hidden":false},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# check final accuracy on validation set  \nif(VALIDATION_SIZE):\n    validation_accuracy = accuracy.eval(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.7)\n    plt.ylabel('accuracy')\n    plt.xlabel('step')\n    plt.show()","metadata":{"collapsed":false,"jupyter":{"outputs_hidden":false},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","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)\n\nprint('test_images({0[0]},{0[1]})'.format(test_images.shape))\n\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(feed_dict={x: test_images[i*BATCH_SIZE : (i+1)*BATCH_SIZE], \n                                                                                keep_prob: 1.0})\n\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\nnp.savetxt('submission_softmax.csv', \n           np.c_[range(1,len(test_images)+1),predicted_lables], \n           delimiter=',', \n           header = 'ImageId,Label', \n           comments = '', \n           fmt='%d')","metadata":{"collapsed":false,"jupyter":{"outputs_hidden":false},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"layer1_grid = layer1.eval(feed_dict={x: test_images[IMAGE_TO_DISPLAY:IMAGE_TO_DISPLAY+1], keep_prob: 1.0})\nplt.axis('off')\nplt.imshow(layer1_grid[0], cmap=cm.seismic )","metadata":{"collapsed":false,"jupyter":{"outputs_hidden":false},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"sess.close()","metadata":{"collapsed":false,"jupyter":{"outputs_hidden":false},"trusted":true},"execution_count":null,"outputs":[]}]}