{"cells": [{"source": ["## Digit Recognizer using tensorflow"], "cell_type": "markdown", "metadata": {"_uuid": "8d915ef97f7a20f1ddac4e26a357e7933cdaadd0", "_cell_guid": "ebd3397d-9609-ae21-594f-71dda28959ca"}}, {"source": ["import numpy as np\n", "import pandas as pd\n", "import seaborn as sns\n", "import matplotlib.pyplot as plt\n", "import matplotlib.cm as cm\n", "import tensorflow as tf\n", "\n", "def warn(*args, **kwargs): pass\n", "import warnings\n", "warnings.warn = warn"], "outputs": [], "cell_type": "code", "metadata": {"_uuid": "a2b2f8b9ecf172d525fd1f2ab25d3c93ea78fbcc", "_cell_guid": "aa2afb69-c66e-e003-9bd5-368605ee5138", "collapsed": true}, "execution_count": null}, {"source": ["train = pd.read_csv('../input/train.csv')\n", "test = pd.read_csv('../input/test.csv')"], "outputs": [], "cell_type": "code", "metadata": {"_uuid": "0ba474b35cdc538aaf67a70354c20e8041211161", "_cell_guid": "f2aec815-56ae-5e39-4f8e-a5c5f4a1a438", "collapsed": true}, "execution_count": null}, {"source": ["x = tf.placeholder(tf.float32, [None, 784])\n", "W = tf.Variable(tf.zeros([784, 10]))\n", "b = tf.Variable(tf.zeros([10]))\n", "y = tf.nn.softmax(tf.matmul(x, W) + b)"], "outputs": [], "cell_type": "code", "metadata": {"_uuid": "9a1f03b365362c56baee757df6e548dc69bf6d54", "_cell_guid": "9dc5ea9c-5aa1-e7ad-efe6-4b2cd3d8d3b7", "collapsed": true}, "execution_count": null}, {"source": ["# settings\n", "LEARNING_RATE = 1e-4\n", "# set to 20000 on local environment to get 0.99 accuracy\n", "TRAINING_ITERATIONS = 2500        \n", "    \n", "DROPOUT = 0.5\n", "BATCH_SIZE = 50\n", "\n", "# set to 0 to train on all available data\n", "VALIDATION_SIZE = 2000\n", "\n", "# image number to output\n", "IMAGE_TO_DISPLAY = 3"], "outputs": [], "cell_type": "code", "metadata": {"_uuid": "58279ab9d41331b77ef42bba849cf69d0e0d3684", "_cell_guid": "f3bf48e9-b7dd-695b-f922-5f14380dbbab", "collapsed": true}, "execution_count": null}, {"source": ["images = train.iloc[:,1:].values\n", "images = images.astype(np.float)\n", "\n", "# convert from [0:255] => [0.0:1.0]\n", "images = np.multiply(images, 1.0 / 255.0)\n", "\n", "print('images({0[0]},{0[1]})'.format(images.shape))"], "outputs": [], "cell_type": "code", "metadata": {"_uuid": "6ef38fed6d300276c7270abe1b0ed21106b9f4f8", "_cell_guid": "5e7b6504-d8a5-133a-7174-27352fafbe6a", "collapsed": true}, "execution_count": null}, {"source": ["image_size = images.shape[1]\n", "print ('image_size => {0}'.format(image_size))\n", "\n", "# in this case all images are square\n", "image_width = image_height = np.ceil(np.sqrt(image_size)).astype(np.uint8)\n", "\n", "print ('image_width => {0}\\nimage_height => {1}'.format(image_width,image_height))"], "outputs": [], "cell_type": "code", "metadata": {"_uuid": "751778d3aeb708da7751a883d91acac6661bdff8", "_cell_guid": "aace730d-470c-c3ed-419d-669770aa960d", "collapsed": true}, "execution_count": null}, {"source": ["# display image\n", "def 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     \n", "display(images[IMAGE_TO_DISPLAY])"], "outputs": [], "cell_type": "code", "metadata": {"_uuid": "ea3d79d47e31167f05a07cb5579430bdd175f0ae", "_cell_guid": "0fd4401a-798a-ea8d-67eb-d33401682ed9", "collapsed": true}, "execution_count": null}, {"source": ["labels_flat = train[[0]].values.ravel()\n", "\n", "print('labels_flat({0})'.format(len(labels_flat)))\n", "print ('labels_flat[{0}] => {1}'.format(IMAGE_TO_DISPLAY,labels_flat[IMAGE_TO_DISPLAY]))"], "outputs": [], "cell_type": "code", "metadata": {"_uuid": "e90841813f35cc716a8065298f7e94051e6cefbd", "_cell_guid": "56b77fdb-6f37-4694-c8f7-ebe6c9c8b5dc", "collapsed": true}, "execution_count": null}, {"source": ["labels_count = np.unique(labels_flat).shape[0]\n", "\n", "print('labels_count => {0}'.format(labels_count))"], "outputs": [], "cell_type": "code", "metadata": {"_uuid": "911aa6c690302271594541e7513685492af6fc2c", "_cell_guid": "0b494298-bce7-1540-9182-d64f47a1853f", "collapsed": true}, "execution_count": null}, {"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", "def 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", "\n", "labels = dense_to_one_hot(labels_flat, labels_count)\n", "labels = labels.astype(np.uint8)\n", "\n", "print('labels({0[0]},{0[1]})'.format(labels.shape))\n", "print ('labels[{0}] => {1}'.format(IMAGE_TO_DISPLAY,labels[IMAGE_TO_DISPLAY]))"], "outputs": [], "cell_type": "code", "metadata": {"_uuid": "3d1d31794358586becb5b3c81485b39efeb59b35", "_cell_guid": "44848367-ac7a-91bb-10e0-274c00d56c6b", "collapsed": true}, "execution_count": null}, {"source": ["# Training"], "cell_type": "markdown", "metadata": {"_uuid": "9c6404273a90d2e2945f060c7795dc9657c41e26", "_cell_guid": "0eba6620-e597-be94-ea2c-25ec559a4963"}}, {"source": ["y_ = tf.placeholder(tf.float32, [None, 10])\n", "cross_entropy = tf.reduce_mean(-tf.reduce_sum(y_ * tf.log(y), reduction_indices=[1]))\n", "train_step = tf.train.GradientDescentOptimizer(LEARNING_RATE).minimize(cross_entropy)"], "outputs": [], "cell_type": "code", "metadata": {"_uuid": "179ecb13913cc2eaefa8df7abc308bf3cbc82e51", "_cell_guid": "3e72bca6-5b6c-9f01-b6d4-9215e1ccbd82", "collapsed": true}, "execution_count": null}, {"source": ["init = tf.initialize_all_variables()"], "outputs": [], "cell_type": "code", "metadata": {"_uuid": "7faf0a7dbfc8cf8ed3f3609bacf09205704ce4c8", "_cell_guid": "6498d665-8878-47ed-5d74-b87ce0cce152", "collapsed": true}, "execution_count": null}, {"source": ["sess = tf.InteractiveSession()\n", "sess.run(init)"], "outputs": [], "cell_type": "code", "metadata": {"_uuid": "41537d5c9f2352fb8032e1b61b11084fb73bc6bb", "_cell_guid": "ab10349e-ae2a-355b-de08-f1f007e69a94", "collapsed": true}, "execution_count": null}, {"source": ["# split data into training & validation\n", "validation_images = images[:VALIDATION_SIZE]\n", "validation_labels = labels[:VALIDATION_SIZE]\n", "\n", "train_images = images[VALIDATION_SIZE:]\n", "train_labels = labels[VALIDATION_SIZE:]\n", "\n", "\n", "print('train_images({0[0]},{0[1]})'.format(train_images.shape))\n", "print('validation_images({0[0]},{0[1]})'.format(validation_images.shape))"], "outputs": [], "cell_type": "code", "metadata": {"_uuid": "4f0f07980007bd0986643d7964760eaafd05661a", "_cell_guid": "9dc2cf2b-cad6-ffe4-d57f-e023818772ca", "collapsed": true}, "execution_count": null}, {"source": ["# evaluation\n", "correct_prediction = tf.equal(tf.argmax(y,1), tf.argmax(y_,1))\n", "accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))"], "outputs": [], "cell_type": "code", "metadata": {"_uuid": "722f321c1495d08a7ab6b20eeabd7ae82483c474", "_cell_guid": "d3f16bd0-3e6e-23b3-2980-ad3aa6397209", "collapsed": true}, "execution_count": null}, {"source": ["epochs_completed = 0\n", "index_in_epoch = 0\n", "num_examples = train_images.shape[0]\n", "\n", "# serve data by batches\n", "def 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]"], "outputs": [], "cell_type": "code", "metadata": {"_uuid": "8514d758734691a7015aba80f23fa1407125bf05", "_cell_guid": "43b9e3f8-bb2c-2769-a010-785339eb03a1", "collapsed": true}, "execution_count": null}, {"source": ["# visualisation variables\n", "train_accuracies = []\n", "validation_accuracies = []\n", "x_range = []\n", "display_step=1\n", "\n", "for i in range(TRAINING_ITERATIONS):\n", "    batch_xs, batch_ys = next_batch(BATCH_SIZE)\n", "    # check progress on every 1st,2nd,...,10th,20th,...,100th... step\n", "    if i%display_step == 0 or (i+1) == TRAINING_ITERATIONS:      \n", "        train_accuracy = accuracy.eval(feed_dict={x:batch_xs, \n", "                                                  y_: batch_ys})\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", "            print('training_accuracy / validation_accuracy => %.2f / %.2f for step %d'%(train_accuracy, validation_accuracy, i))\n", "            validation_accuracies.append(validation_accuracy)        \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", "        \n", "    # train on batch\n", "    sess.run(train_step, feed_dict={x: batch_xs, y_: batch_ys})"], "outputs": [], "cell_type": "code", "metadata": {"_uuid": "b39a175ed9c6e2cd6c04e55e5e753b229c591a25", "_cell_guid": "9726ed18-015b-9013-18c0-e4e36c2079f0", "collapsed": true}, "execution_count": null}, {"source": ["# check final accuracy on validation set  \n", "if(VALIDATION_SIZE):\n", "    validation_accuracy = accuracy.eval(feed_dict={x: validation_images, \n", "                                                   y_: validation_labels})\n", "    print('validation_accuracy => %.4f'%validation_accuracy)"], "outputs": [], "cell_type": "code", "metadata": {"_uuid": "292cc88d2fc32013b6123ab955fe9a19dcbb20b8", "_cell_guid": "a8f5b4fa-2e84-5508-64fc-5832d78c5b9b", "collapsed": true}, "execution_count": null}, {"source": ["# LETS DO BETTER"], "cell_type": "markdown", "metadata": {"_uuid": "174e04b393610e5cd6137cf2b16104ae2830729f", "_cell_guid": "2ba77b17-8298-fe43-709b-a349de01083a"}}, {"source": ["# weight initialization\n", "def weight_variable(shape):\n", "    initial = tf.truncated_normal(shape, stddev=0.1)\n", "    return tf.Variable(initial)\n", "\n", "def bias_variable(shape):\n", "    initial = tf.constant(0.1, shape=shape)\n", "    return tf.Variable(initial)\n", "\n", "# convolution\n", "def conv2d(x, W):\n", "    return tf.nn.conv2d(x, W, strides=[1, 1, 1, 1], padding='SAME')\n", "# pooling\n", "# [[0,3],\n", "#  [4,2]] => 4\n", "\n", "# [[0,1],\n", "#  [1,1]] => 1\n", "\n", "def max_pool_2x2(x):\n", "    return tf.nn.max_pool(x, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding='SAME')"], "outputs": [], "cell_type": "code", "metadata": {"_uuid": "d2a270cffecf0e838c7e8b0c8412e74a5946e8e9", "_cell_guid": "0992fb5b-cffa-8cd4-02e0-cf8afeb2b0f0", "collapsed": true}, "execution_count": null}, {"source": ["# input & output of NN\n", "\n", "# images\n", "x = tf.placeholder('float', shape=[None, image_size])\n", "# labels\n", "y_ = tf.placeholder('float', shape=[None, labels_count])"], "outputs": [], "cell_type": "code", "metadata": {"_uuid": "29d2b13520b5fba326e060d47d1cda58ed207369", "_cell_guid": "6a87c65a-d809-3609-14dc-d636b2c95c52", "collapsed": true}, "execution_count": null}, {"source": ["# first convolutional layer\n", "W_conv1 = weight_variable([5, 5, 1, 32])\n", "b_conv1 = bias_variable([32])\n", "\n", "# (40000,784) => (40000,28,28,1)\n", "image = tf.reshape(x, [-1,image_width , image_height,1])\n", "print (image.get_shape()) # =>(40000,28,28,1)\n", "\n", "\n", "h_conv1 = tf.nn.relu(conv2d(image, W_conv1) + b_conv1)\n", "print (h_conv1.get_shape()) # => (40000, 28, 28, 32)\n", "h_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\n", "layer1 = 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.\n", "layer1 = tf.transpose(layer1, (0, 3, 1, 4,2))\n", "\n", "layer1 = tf.reshape(layer1, (-1, image_height*4, image_width*8)) "], "outputs": [], "cell_type": "code", "metadata": {"_uuid": "6bc04ecd0edaafe800d51d8e36df0bb8b76ab4a8", "_cell_guid": "9ee6603a-e6ac-e6d9-2930-fb5bc4dd28fb", "collapsed": true}, "execution_count": null}, {"source": ["# second convolutional layer\n", "W_conv2 = weight_variable([5, 5, 32, 64])\n", "b_conv2 = bias_variable([64])\n", "\n", "h_conv2 = tf.nn.relu(conv2d(h_pool1, W_conv2) + b_conv2)\n", "#print (h_conv2.get_shape()) # => (40000, 14,14, 64)\n", "h_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\n", "layer2 = tf.reshape(h_conv2, (-1, 14, 14, 4 ,16))  \n", "\n", "# reorder so the channels are in the first dimension, x and y follow.\n", "layer2 = tf.transpose(layer2, (0, 3, 1, 4,2))\n", "\n", "layer2 = tf.reshape(layer2, (-1, 14*4, 14*16)) "], "outputs": [], "cell_type": "code", "metadata": {"_uuid": "37deacea2e6dd95fc6653bb6b76d9d8992e09fd4", "_cell_guid": "434c3a88-b2f6-5c8c-fe20-5b2e998fa98f", "collapsed": true}, "execution_count": null}, {"source": ["# densely connected layer\n", "W_fc1 = weight_variable([7 * 7 * 64, 1024])\n", "b_fc1 = bias_variable([1024])\n", "\n", "# (40000, 7, 7, 64) => (40000, 3136)\n", "h_pool2_flat = tf.reshape(h_pool2, [-1, 7*7*64])\n", "\n", "h_fc1 = tf.nn.relu(tf.matmul(h_pool2_flat, W_fc1) + b_fc1)\n", "#print (h_fc1.get_shape()) # => (40000, 1024)"], "outputs": [], "cell_type": "code", "metadata": {"_uuid": "b65c6369d5168cd50739355a9e196127098bd0c2", "_cell_guid": "37329292-03c4-fe89-ea60-f26e0c2fe7bf", "collapsed": true}, "execution_count": null}, {"source": ["# dropout\n", "keep_prob = tf.placeholder('float')\n", "h_fc1_drop = tf.nn.dropout(h_fc1, keep_prob)"], "outputs": [], "cell_type": "code", "metadata": {"_uuid": "552a3cae8cb89aff62e9fb20ccbf8a3ba0ac3870", "_cell_guid": "f43000d4-8dff-572f-f7b5-1386a92472f5", "collapsed": true}, "execution_count": null}, {"source": ["# readout layer for deep net\n", "W_fc2 = weight_variable([1024, labels_count])\n", "b_fc2 = bias_variable([labels_count])\n", "\n", "y = tf.nn.softmax(tf.matmul(h_fc1_drop, W_fc2) + b_fc2)\n", "\n", "#print (y.get_shape()) # => (40000, 10)"], "outputs": [], "cell_type": "code", "metadata": {"_uuid": "0456bd3eb6e84740eeaecce2d234642cf52f3ae4", "_cell_guid": "11236224-98f7-9505-5e0b-9030a809081a", "collapsed": true}, "execution_count": null}, {"source": ["# cost function\n", "cross_entropy = -tf.reduce_sum(y_*tf.log(y))\n", "\n", "\n", "# optimisation function\n", "train_step = tf.train.AdamOptimizer(LEARNING_RATE).minimize(cross_entropy)\n", "\n", "# evaluation\n", "correct_prediction = tf.equal(tf.argmax(y,1), tf.argmax(y_,1))\n", "\n", "accuracy = tf.reduce_mean(tf.cast(correct_prediction, 'float'))"], "outputs": [], "cell_type": "code", "metadata": {"_uuid": "552fdac99b36eac3d07f599c562b1d96ed10d8e9", "_cell_guid": "798de7d7-71c1-b961-bd80-1b2278a2ddad", "collapsed": true}, "execution_count": null}, {"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\n", "predict = tf.argmax(y,1)"], "outputs": [], "cell_type": "code", "metadata": {"_uuid": "b58f6dcd09ce39f187b9c8ba0737a8e3b77eb69a", "_cell_guid": "ef8dd5f9-5128-4718-fcc8-3f56a314724a", "collapsed": true}, "execution_count": null}, {"source": ["epochs_completed = 0\n", "index_in_epoch = 0\n", "num_examples = train_images.shape[0]\n", "# start TensorFlow session\n", "init = tf.initialize_all_variables()\n", "sess = tf.InteractiveSession()\n", "\n", "sess.run(init)"], "outputs": [], "cell_type": "code", "metadata": {"_uuid": "105dc08f66002ab1229aded4f6e93bbf0341f47c", "_cell_guid": "30b5821e-1f13-ba40-736e-2748713b176b", "collapsed": true}, "execution_count": null}, {"source": ["# visualisation variables\n", "train_accuracies = []\n", "validation_accuracies = []\n", "x_range = []\n", "\n", "display_step=1\n", "\n", "for 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})"], "outputs": [], "cell_type": "code", "metadata": {"_uuid": "405c4eee42b504b74ab50da8ff8a882e77309a33", "_cell_guid": "18ad3df8-8051-b4df-fe19-20ed811a22f8", "collapsed": true}, "execution_count": null}, {"source": ["# check final accuracy on validation set  \n", "if(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()"], "outputs": [], "cell_type": "code", "metadata": {"_uuid": "76f9a466f875a2feda06c105c4e05cd88d2937e7", "_cell_guid": "60074137-c908-13c7-d673-07f013b2ad37", "collapsed": true}, "execution_count": null}, {"source": ["# read test data from CSV file \n", "test_images = test.astype(np.float)\n", "\n", "# convert from [0:255] => [0.0:1.0]\n", "test_images = np.multiply(test_images, 1.0 / 255.0)\n", "\n", "print('test_images({0[0]},{0[1]})'.format(test_images.shape))"], "outputs": [], "cell_type": "code", "metadata": {"_uuid": "a79319f001c3d9a4e641a0bf179b588a5bcdf9fd", "_cell_guid": "ebfb42e1-0e56-fee7-85f2-c2c866223d80", "collapsed": true}, "execution_count": null}, {"source": ["# 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\n", "predicted_lables = np.zeros(test_images.shape[0])\n", "for 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", "print('predicted_lables({0})'.format(len(predicted_lables)))"], "outputs": [], "cell_type": "code", "metadata": {"_uuid": "d616b72a71d6193714daaa247f197729fe4ee69b", "_cell_guid": "4134f67a-a3fe-0357-24fc-bb9d33743e30", "collapsed": true}, "execution_count": null}, {"source": ["# read test data from CSV file \n", "test_images = pd.read_csv('../input/test.csv').values\n", "test_images = test_images.astype(np.float)\n", "\n", "# convert from [0:255] => [0.0:1.0]\n", "test_images = np.multiply(test_images, 1.0 / 255.0)\n", "\n", "print('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\n", "predicted_lables = np.zeros(test_images.shape[0])\n", "for 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", "\n", "print('predicted_lables({0})'.format(len(predicted_lables)))\n", "\n", "# output test image and prediction\n", "display(test_images[IMAGE_TO_DISPLAY])\n", "print ('predicted_lables[{0}] => {1}'.format(IMAGE_TO_DISPLAY,predicted_lables[IMAGE_TO_DISPLAY]))\n", "\n", "# save results\n", "np.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')"], "outputs": [], "cell_type": "code", "metadata": {"_uuid": "ea5c64ca7273bce2302a3c9ead5d5aedf1ea54ee", "_cell_guid": "8dd89004-319b-baad-2146-f0134e807678", "collapsed": true}, "execution_count": null}, {"source": ["layer1_grid = layer1.eval(feed_dict={x: test_images[IMAGE_TO_DISPLAY:IMAGE_TO_DISPLAY+1], keep_prob: 1.0})\n", "plt.axis('off')\n", "plt.imshow(layer1_grid[0], cmap=cm.seismic )"], "outputs": [], "cell_type": "code", "metadata": {"_uuid": "8c71900b2229372169e79f02c380d7f3a259472b", "_cell_guid": "1186a6cb-cd29-7f3d-7c6a-fea78581a2c2", "collapsed": true}, "execution_count": null}, {"source": ["sess.close()"], "outputs": [], "cell_type": "code", "metadata": {"_uuid": "b1ee41162fa3f8aa5238406de9736f59b5941b42", "_cell_guid": "3040b19c-8dc0-2d2a-6717-0df3ccd9c0a7", "collapsed": true}, "execution_count": null}, {"source": [], "outputs": [], "cell_type": "code", "metadata": {"_uuid": "4aa276e8792d753fda8d4ea323efb1bf657308c2", "_cell_guid": "b6415e57-f1a0-acd4-1b04-0246bb5dfa59", "collapsed": true}, "execution_count": null}], "nbformat_minor": 1, "nbformat": 4, "metadata": {"language_info": {"file_extension": ".py", "codemirror_mode": {"name": "ipython", "version": 3}, "pygments_lexer": "ipython3", "name": "python", "nbconvert_exporter": "python", "version": "3.6.3", "mimetype": "text/x-python"}, "_change_revision": 0, "_is_fork": false, "kernelspec": {"name": "python3", "language": "python", "display_name": "Python 3"}}}