{ "cells": [ { "cell_type": "markdown", "metadata": { "colab_type": "text", "id": "5hIbr52I7Z7U" }, "source": [ "Deep Learning with TensorFlow\n", "=============\n", "\n", "Credits: Forked from [TensorFlow](https://github.com/tensorflow/tensorflow) by Google\n", "\n", "Setup\n", "------------\n", "\n", "Refer to the [setup instructions](https://github.com/donnemartin/data-science-ipython-notebooks/tree/feature/deep-learning/deep-learning/tensor-flow-exercises/README.md).\n", "\n", "Exercise 1\n", "------------\n", "\n", "The objective of this exercise is to learn about simple data curation practices, and familiarize you with some of the data we'll be reusing later.\n", "\n", "This notebook uses the [notMNIST](http://yaroslavvb.blogspot.com/2011/09/notmnist-dataset.html) dataset to be used with python experiments. This dataset is designed to look like the classic [MNIST](http://yann.lecun.com/exdb/mnist/) dataset, while looking a little more like real data: it's a harder task, and the data is a lot less 'clean' than MNIST." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "cellView": "both", "colab": { "autoexec": { "startup": false, "wait_interval": 0 } }, "colab_type": "code", "collapsed": true, "id": "apJbCsBHl-2A" }, "outputs": [], "source": [ "# These are all the modules we'll be using later. Make sure you can import them\n", "# before proceeding further.\n", "import matplotlib.pyplot as plt\n", "import numpy as np\n", "import os\n", "import tarfile\n", "import urllib\n", "from IPython.display import display, Image\n", "from scipy import ndimage\n", "from sklearn.linear_model import LogisticRegression\n", "import cPickle as pickle" ] }, { "cell_type": "markdown", "metadata": { "colab_type": "text", "id": "jNWGtZaXn-5j" }, "source": [ "First, we'll download the dataset to our local machine. The data consists of characters rendered in a variety of fonts on a 28x28 image. The labels are limited to 'A' through 'J' (10 classes). The training set has about 500k and the testset 19000 labelled examples. Given these sizes, it should be possible to train models quickly on any machine." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "cellView": "both", "colab": { "autoexec": { "startup": false, "wait_interval": 0 }, "output_extras": [ { "item_id": 1 } ] }, "colab_type": "code", "collapsed": false, "executionInfo": { "elapsed": 186058, "status": "ok", "timestamp": 1444485672507, "user": { "color": "#1FA15D", "displayName": "Vincent Vanhoucke", "isAnonymous": false, "isMe": true, "permissionId": "05076109866853157986", "photoUrl": "//lh6.googleusercontent.com/-cCJa7dTDcgQ/AAAAAAAAAAI/AAAAAAAACgw/r2EZ_8oYer4/s50-c-k-no/photo.jpg", "sessionId": "2a0a5e044bb03b66", "userId": "102167687554210253930" }, "user_tz": 420 }, "id": "EYRJ4ICW6-da", "outputId": "0d0f85df-155f-4a89-8e7e-ee32df36ec8d" }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Found and verified notMNIST_large.tar.gz\n", "Found and verified notMNIST_small.tar.gz\n" ] } ], "source": [ "url = 'http://yaroslavvb.com/upload/notMNIST/'\n", "\n", "def maybe_download(filename, expected_bytes):\n", " \"\"\"Download a file if not present, and make sure it's the right size.\"\"\"\n", " if not os.path.exists(filename):\n", " filename, _ = urllib.urlretrieve(url + filename, filename)\n", " statinfo = os.stat(filename)\n", " if statinfo.st_size == expected_bytes:\n", " print 'Found and verified', filename\n", " else:\n", " raise Exception(\n", " 'Failed to verify' + filename + '. Can you get to it with a browser?')\n", " return filename\n", "\n", "train_filename = maybe_download('notMNIST_large.tar.gz', 247336696)\n", "test_filename = maybe_download('notMNIST_small.tar.gz', 8458043)" ] }, { "cell_type": "markdown", "metadata": { "colab_type": "text", "id": "cC3p0oEyF8QT" }, "source": [ "Extract the dataset from the compressed .tar.gz file.\n", "This should give you a set of directories, labelled A through J." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "cellView": "both", "colab": { "autoexec": { "startup": false, "wait_interval": 0 }, "output_extras": [ { "item_id": 1 } ] }, "colab_type": "code", "collapsed": false, "executionInfo": { "elapsed": 186055, "status": "ok", "timestamp": 1444485672525, "user": { "color": "#1FA15D", "displayName": "Vincent Vanhoucke", "isAnonymous": false, "isMe": true, "permissionId": "05076109866853157986", "photoUrl": "//lh6.googleusercontent.com/-cCJa7dTDcgQ/AAAAAAAAAAI/AAAAAAAACgw/r2EZ_8oYer4/s50-c-k-no/photo.jpg", "sessionId": "2a0a5e044bb03b66", "userId": "102167687554210253930" }, "user_tz": 420 }, "id": "H8CBE-WZ8nmj", "outputId": "ef6c790c-2513-4b09-962e-27c79390c762" }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "['notMNIST_large/A', 'notMNIST_large/B', 'notMNIST_large/C', 'notMNIST_large/D', 'notMNIST_large/E', 'notMNIST_large/F', 'notMNIST_large/G', 'notMNIST_large/H', 'notMNIST_large/I', 'notMNIST_large/J']\n", "['notMNIST_small/A', 'notMNIST_small/B', 'notMNIST_small/C', 'notMNIST_small/D', 'notMNIST_small/E', 'notMNIST_small/F', 'notMNIST_small/G', 'notMNIST_small/H', 'notMNIST_small/I', 'notMNIST_small/J']\n" ] } ], "source": [ "num_classes = 10\n", "\n", "def extract(filename):\n", " tar = tarfile.open(filename)\n", " tar.extractall()\n", " tar.close()\n", " root = os.path.splitext(os.path.splitext(filename)[0])[0] # remove .tar.gz\n", " data_folders = [os.path.join(root, d) for d in sorted(os.listdir(root))]\n", " if len(data_folders) != num_classes:\n", " raise Exception(\n", " 'Expected %d folders, one per class. Found %d instead.' % (\n", " num_folders, len(data_folders)))\n", " print data_folders\n", " return data_folders\n", " \n", "train_folders = extract(train_filename)\n", "test_folders = extract(test_filename)" ] }, { "cell_type": "markdown", "metadata": { "colab_type": "text", "id": "4riXK3IoHgx6" }, "source": [ "---\n", "Problem 1\n", "---------\n", "\n", "Let's take a peek at some of the data to make sure it looks sensible. Each exemplar should be an image of a character A through J rendered in a different font. Display a sample of the images that we just downloaded. Hint: you can use the package IPython.display.\n", "\n", "---" ] }, { "cell_type": "markdown", "metadata": { "colab_type": "text", "id": "PBdkjESPK8tw" }, "source": [ "Now let's load the data in a more manageable format.\n", "\n", "We'll convert the entire dataset into a 3D array (image index, x, y) of floating point values, normalized to have approximately zero mean and standard deviation ~0.5 to make training easier down the road. The labels will be stored into a separate array of integers 0 through 9.\n", "\n", "A few images might not be readable, we'll just skip them." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "cellView": "both", "colab": { "autoexec": { "startup": false, "wait_interval": 0 }, "output_extras": [ { "item_id": 30 } ] }, "colab_type": "code", "collapsed": false, "executionInfo": { "elapsed": 399874, "status": "ok", "timestamp": 1444485886378, "user": { "color": "#1FA15D", "displayName": "Vincent Vanhoucke", "isAnonymous": false, "isMe": true, "permissionId": "05076109866853157986", "photoUrl": "//lh6.googleusercontent.com/-cCJa7dTDcgQ/AAAAAAAAAAI/AAAAAAAACgw/r2EZ_8oYer4/s50-c-k-no/photo.jpg", "sessionId": "2a0a5e044bb03b66", "userId": "102167687554210253930" }, "user_tz": 420 }, "id": "h7q0XhG3MJdf", "outputId": "92c391bb-86ff-431d-9ada-315568a19e59" }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "notMNIST_large/A\n", "Could not read: notMNIST_large/A/SG90IE11c3RhcmQgQlROIFBvc3Rlci50dGY=.png : cannot identify image file - it's ok, skipping.\n", "Could not read: notMNIST_large/A/RnJlaWdodERpc3BCb29rSXRhbGljLnR0Zg==.png : cannot identify image file - it's ok, skipping.\n", "Could not read: notMNIST_large/A/Um9tYW5hIEJvbGQucGZi.png : cannot identify image file - it's ok, skipping.\n", "notMNIST_large/B\n", "Could not read: notMNIST_large/B/TmlraXNFRi1TZW1pQm9sZEl0YWxpYy5vdGY=.png : cannot identify image file - it's ok, skipping.\n", "notMNIST_large/C\n", "notMNIST_large/D\n", "Could not read: notMNIST_large/D/VHJhbnNpdCBCb2xkLnR0Zg==.png : cannot identify image file - it's ok, skipping.\n", "notMNIST_large/E\n", "notMNIST_large/F\n", "notMNIST_large/G\n", "notMNIST_large/H\n", "notMNIST_large/I\n", "notMNIST_large/J\n", "Full dataset tensor: (529114, 28, 28)\n", "Mean: -0.0816593\n", "Standard deviation: 0.454232\n", "Labels: (529114,)\n", "notMNIST_small/A\n", "Could not read: notMNIST_small/A/RGVtb2NyYXRpY2FCb2xkT2xkc3R5bGUgQm9sZC50dGY=.png : cannot identify image file - it's ok, skipping.\n", "notMNIST_small/B\n", "notMNIST_small/C\n", "notMNIST_small/D\n", "notMNIST_small/E\n", "notMNIST_small/F\n", "Could not read: notMNIST_small/F/Q3Jvc3NvdmVyIEJvbGRPYmxpcXVlLnR0Zg==.png : cannot identify image file - it's ok, skipping.\n", "notMNIST_small/G\n", "notMNIST_small/H\n", "notMNIST_small/I\n", "notMNIST_small/J\n", "Full dataset tensor: (18724, 28, 28)\n", "Mean: -0.0746364\n", "Standard deviation: 0.458622\n", "Labels: (18724,)\n" ] } ], "source": [ "image_size = 28 # Pixel width and height.\n", "pixel_depth = 255.0 # Number of levels per pixel.\n", "\n", "def load(data_folders, min_num_images, max_num_images):\n", " dataset = np.ndarray(\n", " shape=(max_num_images, image_size, image_size), dtype=np.float32)\n", " labels = np.ndarray(shape=(max_num_images), dtype=np.int32)\n", " label_index = 0\n", " image_index = 0\n", " for folder in data_folders:\n", " print folder\n", " for image in os.listdir(folder):\n", " if image_index >= max_num_images:\n", " raise Exception('More images than expected: %d >= %d' % (\n", " num_images, max_num_images))\n", " image_file = os.path.join(folder, image)\n", " try:\n", " image_data = (ndimage.imread(image_file).astype(float) -\n", " pixel_depth / 2) / pixel_depth\n", " if image_data.shape != (image_size, image_size):\n", " raise Exception('Unexpected image shape: %s' % str(image_data.shape))\n", " dataset[image_index, :, :] = image_data\n", " labels[image_index] = label_index\n", " image_index += 1\n", " except IOError as e:\n", " print 'Could not read:', image_file, ':', e, '- it\\'s ok, skipping.'\n", " label_index += 1\n", " num_images = image_index\n", " dataset = dataset[0:num_images, :, :]\n", " labels = labels[0:num_images]\n", " if num_images < min_num_images:\n", " raise Exception('Many fewer images than expected: %d < %d' % (\n", " num_images, min_num_images))\n", " print 'Full dataset tensor:', dataset.shape\n", " print 'Mean:', np.mean(dataset)\n", " print 'Standard deviation:', np.std(dataset)\n", " print 'Labels:', labels.shape\n", " return dataset, labels\n", "train_dataset, train_labels = load(train_folders, 450000, 550000)\n", "test_dataset, test_labels = load(test_folders, 18000, 20000)" ] }, { "cell_type": "markdown", "metadata": { "colab_type": "text", "id": "vUdbskYE2d87" }, "source": [ "---\n", "Problem 2\n", "---------\n", "\n", "Let's verify that the data still looks good. Displaying a sample of the labels and images from the ndarray. Hint: you can use matplotlib.pyplot.\n", "\n", "---" ] }, { "cell_type": "markdown", "metadata": { "colab_type": "text", "id": "GPTCnjIcyuKN" }, "source": [ "Next, we'll randomize the data. It's important to have the labels well shuffled for the training and test distributions to match." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "cellView": "both", "colab": { "autoexec": { "startup": false, "wait_interval": 0 } }, "colab_type": "code", "collapsed": true, "id": "6WZ2l2tN2zOL" }, "outputs": [], "source": [ "np.random.seed(133)\n", "def randomize(dataset, labels):\n", " permutation = np.random.permutation(labels.shape[0])\n", " shuffled_dataset = dataset[permutation,:,:]\n", " shuffled_labels = labels[permutation]\n", " return shuffled_dataset, shuffled_labels\n", "train_dataset, train_labels = randomize(train_dataset, train_labels)\n", "test_dataset, test_labels = randomize(test_dataset, test_labels)" ] }, { "cell_type": "markdown", "metadata": { "colab_type": "text", "id": "puDUTe6t6USl" }, "source": [ "---\n", "Problem 3\n", "---------\n", "Convince yourself that the data is still good after shuffling!\n", "\n", "---" ] }, { "cell_type": "markdown", "metadata": { "colab_type": "text", "id": "cYznx5jUwzoO" }, "source": [ "---\n", "Problem 4\n", "---------\n", "Another check: we expect the data to be balanced across classes. Verify that.\n", "\n", "---" ] }, { "cell_type": "markdown", "metadata": { "colab_type": "text", "id": "LA7M7K22ynCt" }, "source": [ "Prune the training data as needed. Depending on your computer setup, you might not be able to fit it all in memory, and you can tune train_size as needed.\n", "\n", "Also create a validation dataset for hyperparameter tuning." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "cellView": "both", "colab": { "autoexec": { "startup": false, "wait_interval": 0 }, "output_extras": [ { "item_id": 1 } ] }, "colab_type": "code", "collapsed": false, "executionInfo": { "elapsed": 411281, "status": "ok", "timestamp": 1444485897869, "user": { "color": "#1FA15D", "displayName": "Vincent Vanhoucke", "isAnonymous": false, "isMe": true, "permissionId": "05076109866853157986", "photoUrl": "//lh6.googleusercontent.com/-cCJa7dTDcgQ/AAAAAAAAAAI/AAAAAAAACgw/r2EZ_8oYer4/s50-c-k-no/photo.jpg", "sessionId": "2a0a5e044bb03b66", "userId": "102167687554210253930" }, "user_tz": 420 }, "id": "s3mWgZLpyuzq", "outputId": "8af66da6-902d-4719-bedc-7c9fb7ae7948" }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Training (200000, 28, 28) (200000,)\n", "Validation (10000, 28, 28) (10000,)\n" ] } ], "source": [ "train_size = 200000\n", "valid_size = 10000\n", "\n", "valid_dataset = train_dataset[:valid_size,:,:]\n", "valid_labels = train_labels[:valid_size]\n", "train_dataset = train_dataset[valid_size:valid_size+train_size,:,:]\n", "train_labels = train_labels[valid_size:valid_size+train_size]\n", "print 'Training', train_dataset.shape, train_labels.shape\n", "print 'Validation', valid_dataset.shape, valid_labels.shape" ] }, { "cell_type": "markdown", "metadata": { "colab_type": "text", "id": "tIQJaJuwg5Hw" }, "source": [ "Finally, let's save the data for later reuse:" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "cellView": "both", "colab": { "autoexec": { "startup": false, "wait_interval": 0 } }, "colab_type": "code", "collapsed": true, "id": "QiR_rETzem6C" }, "outputs": [], "source": [ "pickle_file = 'notMNIST.pickle'\n", "\n", "try:\n", " f = open(pickle_file, 'wb')\n", " save = {\n", " 'train_dataset': train_dataset,\n", " 'train_labels': train_labels,\n", " 'valid_dataset': valid_dataset,\n", " 'valid_labels': valid_labels,\n", " 'test_dataset': test_dataset,\n", " 'test_labels': test_labels,\n", " }\n", " pickle.dump(save, f, pickle.HIGHEST_PROTOCOL)\n", " f.close()\n", "except Exception as e:\n", " print 'Unable to save data to', pickle_file, ':', e\n", " raise" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "cellView": "both", "colab": { "autoexec": { "startup": false, "wait_interval": 0 }, "output_extras": [ { "item_id": 1 } ] }, "colab_type": "code", "collapsed": false, "executionInfo": { "elapsed": 413065, "status": "ok", "timestamp": 1444485899688, "user": { "color": "#1FA15D", "displayName": "Vincent Vanhoucke", "isAnonymous": false, "isMe": true, "permissionId": "05076109866853157986", "photoUrl": "//lh6.googleusercontent.com/-cCJa7dTDcgQ/AAAAAAAAAAI/AAAAAAAACgw/r2EZ_8oYer4/s50-c-k-no/photo.jpg", "sessionId": "2a0a5e044bb03b66", "userId": "102167687554210253930" }, "user_tz": 420 }, "id": "hQbLjrW_iT39", "outputId": "b440efc6-5ee1-4cbc-d02d-93db44ebd956" }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Compressed pickle size: 718193801\n" ] } ], "source": [ "statinfo = os.stat(pickle_file)\n", "print 'Compressed pickle size:', statinfo.st_size" ] }, { "cell_type": "markdown", "metadata": { "colab_type": "text", "id": "gE_cRAQB33lk" }, "source": [ "---\n", "Problem 5\n", "---------\n", "\n", "By construction, this dataset might contain a lot of overlapping samples, including training data that's also contained in the validation and test set! Overlap between training and test can skew the results if you expect to use your model in an environment where there is never an overlap, but are actually ok if you expect to see training samples recur when you use it.\n", "Measure how much overlap there is between training, validation and test samples.\n", "Optional questions:\n", "- What about near duplicates between datasets? (images that are almost identical)\n", "- Create a sanitized validation and test set, and compare your accuracy on those in subsequent exercises.\n", "---" ] }, { "cell_type": "markdown", "metadata": { "colab_type": "text", "id": "L8oww1s4JMQx" }, "source": [ "---\n", "Problem 6\n", "---------\n", "\n", "Let's get an idea of what an off-the-shelf classifier can give you on this data. It's always good to check that there is something to learn, and that it's a problem that is not so trivial that a canned solution solves it.\n", "\n", "Train a simple model on this data using 50, 100, 1000 and 5000 training samples. Hint: you can use the LogisticRegression model from sklearn.linear_model.\n", "\n", "Optional question: train an off-the-shelf model on all the data!\n", "\n", "---" ] } ], "metadata": { "colabVersion": "0.3.2", "colab_default_view": {}, "colab_views": {}, "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.4.3" } }, "nbformat": 4, "nbformat_minor": 0 }