aboutsummaryrefslogtreecommitdiffhomepage
path: root/tensorflow/examples/udacity/1_notmnist.ipynb
diff options
context:
space:
mode:
authorGravatar Vincent Vanhoucke <vanhoucke@google.com>2015-12-17 10:27:05 -0800
committerGravatar Vijay Vasudevan <vrv@google.com>2015-12-17 10:27:05 -0800
commitcc6a6e92b5c12bdf5d4a7806b5acd37ede740fea (patch)
tree14f9c3ac1d254e57262b88d57d7a65d38f69edc3 /tensorflow/examples/udacity/1_notmnist.ipynb
parentacc0efa9f4190d3f44f9dbf645af120edc8f1adb (diff)
Initial notebooks and Docker spec for the Udacity course assignments.
Note: these are not final. Change: 110420744
Diffstat (limited to 'tensorflow/examples/udacity/1_notmnist.ipynb')
-rw-r--r--tensorflow/examples/udacity/1_notmnist.ipynb396
1 files changed, 396 insertions, 0 deletions
diff --git a/tensorflow/examples/udacity/1_notmnist.ipynb b/tensorflow/examples/udacity/1_notmnist.ipynb
new file mode 100644
index 0000000000..9c9888664c
--- /dev/null
+++ b/tensorflow/examples/udacity/1_notmnist.ipynb
@@ -0,0 +1,396 @@
+{
+ "worksheets": [
+ {
+ "cells": [
+ {
+ "metadata": {
+ "id": "5hIbr52I7Z7U",
+ "colab_type": "text"
+ },
+ "cell_type": "markdown",
+ "source": "Deep Learning\n=============\n\nAssignment 1\n------------\n\nThe objective of this assignment is to learn about simple data curation practices, and familiarize you with some of the data we'll be reusing later.\n\nThis 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."
+ },
+ {
+ "metadata": {
+ "id": "apJbCsBHl-2A",
+ "colab_type": "code",
+ "colab": {
+ "autoexec": {
+ "startup": false,
+ "wait_interval": 0
+ }
+ },
+ "cellView": "both"
+ },
+ "cell_type": "code",
+ "input": "# These are all the modules we'll be using later. Make sure you can import them\n# before proceeding further.\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport os\nimport tarfile\nimport urllib\nfrom IPython.display import display, Image\nfrom scipy import ndimage\nfrom sklearn.linear_model import LogisticRegression\nimport cPickle as pickle",
+ "language": "python",
+ "outputs": []
+ },
+ {
+ "metadata": {
+ "id": "jNWGtZaXn-5j",
+ "colab_type": "text"
+ },
+ "cell_type": "markdown",
+ "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."
+ },
+ {
+ "metadata": {
+ "id": "EYRJ4ICW6-da",
+ "colab_type": "code",
+ "colab": {
+ "autoexec": {
+ "startup": false,
+ "wait_interval": 0
+ },
+ "output_extras": [
+ {
+ "item_id": 1
+ }
+ ]
+ },
+ "cellView": "both",
+ "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
+ },
+ "outputId": "0d0f85df-155f-4a89-8e7e-ee32df36ec8d"
+ },
+ "cell_type": "code",
+ "input": "url = 'http://yaroslavvb.com/upload/notMNIST/'\n\ndef 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\ntrain_filename = maybe_download('notMNIST_large.tar.gz', 247336696)\ntest_filename = maybe_download('notMNIST_small.tar.gz', 8458043)",
+ "language": "python",
+ "outputs": [
+ {
+ "output_type": "stream",
+ "stream": "stdout",
+ "text": "Found and verified notMNIST_large.tar.gz\nFound and verified notMNIST_small.tar.gz\n"
+ }
+ ]
+ },
+ {
+ "metadata": {
+ "id": "cC3p0oEyF8QT",
+ "colab_type": "text"
+ },
+ "cell_type": "markdown",
+ "source": "Extract the dataset from the compressed .tar.gz file.\nThis should give you a set of directories, labelled A through J."
+ },
+ {
+ "metadata": {
+ "id": "H8CBE-WZ8nmj",
+ "colab_type": "code",
+ "colab": {
+ "autoexec": {
+ "startup": false,
+ "wait_interval": 0
+ },
+ "output_extras": [
+ {
+ "item_id": 1
+ }
+ ]
+ },
+ "cellView": "both",
+ "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
+ },
+ "outputId": "ef6c790c-2513-4b09-962e-27c79390c762"
+ },
+ "cell_type": "code",
+ "input": "num_classes = 10\n\ndef 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 \ntrain_folders = extract(train_filename)\ntest_folders = extract(test_filename)",
+ "language": "python",
+ "outputs": [
+ {
+ "output_type": "stream",
+ "stream": "stdout",
+ "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"
+ }
+ ]
+ },
+ {
+ "metadata": {
+ "id": "4riXK3IoHgx6",
+ "colab_type": "text"
+ },
+ "cell_type": "markdown",
+ "source": "---\nProblem 1\n---------\n\nLet'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---"
+ },
+ {
+ "metadata": {
+ "id": "PBdkjESPK8tw",
+ "colab_type": "text"
+ },
+ "cell_type": "markdown",
+ "source": "Now let's load the data in a more manageable format.\n\nWe'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\nA few images might not be readable, we'll just skip them."
+ },
+ {
+ "metadata": {
+ "id": "h7q0XhG3MJdf",
+ "colab_type": "code",
+ "colab": {
+ "autoexec": {
+ "startup": false,
+ "wait_interval": 0
+ },
+ "output_extras": [
+ {
+ "item_id": 30
+ }
+ ]
+ },
+ "cellView": "both",
+ "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
+ },
+ "outputId": "92c391bb-86ff-431d-9ada-315568a19e59"
+ },
+ "cell_type": "code",
+ "input": "image_size = 28 # Pixel width and height.\npixel_depth = 255.0 # Number of levels per pixel.\n\ndef 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\ntrain_dataset, train_labels = load(train_folders, 450000, 550000)\ntest_dataset, test_labels = load(test_folders, 18000, 20000)",
+ "language": "python",
+ "outputs": [
+ {
+ "output_type": "stream",
+ "stream": "stdout",
+ "text": "notMNIST_large/A\nCould not read: notMNIST_large/A/SG90IE11c3RhcmQgQlROIFBvc3Rlci50dGY=.png : cannot identify image file - it's ok, skipping.\nCould not read: notMNIST_large/A/RnJlaWdodERpc3BCb29rSXRhbGljLnR0Zg==.png : cannot identify image file - it's ok, skipping.\nCould not read: notMNIST_large/A/Um9tYW5hIEJvbGQucGZi.png : cannot identify image file - it's ok, skipping.\nnotMNIST_large/B\nCould not read: notMNIST_large/B/TmlraXNFRi1TZW1pQm9sZEl0YWxpYy5vdGY=.png : cannot identify image file - it's ok, skipping.\nnotMNIST_large/C\nnotMNIST_large/D\nCould not read: notMNIST_large/D/VHJhbnNpdCBCb2xkLnR0Zg==.png : cannot identify image file - it's ok, skipping.\nnotMNIST_large/E\nnotMNIST_large/F\nnotMNIST_large/G\nnotMNIST_large/H\nnotMNIST_large/I\nnotMNIST_large/J\nFull dataset tensor: (529114, 28, 28)\nMean: -0.0816593\nStandard deviation: 0.454232\nLabels: (529114,)\nnotMNIST_small/A\nCould not read: notMNIST_small/A/RGVtb2NyYXRpY2FCb2xkT2xkc3R5bGUgQm9sZC50dGY=.png : cannot identify image file - it's ok, skipping.\nnotMNIST_small/B\nnotMNIST_small/C\nnotMNIST_small/D\nnotMNIST_small/E\nnotMNIST_small/F\nCould not read: notMNIST_small/F/Q3Jvc3NvdmVyIEJvbGRPYmxpcXVlLnR0Zg==.png : cannot identify image file - it's ok, skipping.\nnotMNIST_small/G\nnotMNIST_small/H\nnotMNIST_small/I\nnotMNIST_small/J\nFull dataset tensor: (18724, 28, 28)\nMean: -0.0746364\nStandard deviation: 0.458622\nLabels: (18724,)\n"
+ }
+ ]
+ },
+ {
+ "metadata": {
+ "id": "vUdbskYE2d87",
+ "colab_type": "text"
+ },
+ "cell_type": "markdown",
+ "source": "---\nProblem 2\n---------\n\nLet'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---"
+ },
+ {
+ "metadata": {
+ "id": "GPTCnjIcyuKN",
+ "colab_type": "text"
+ },
+ "cell_type": "markdown",
+ "source": "Next, we'll randomize the data. It's important to have the labels well shuffled for the training and test distributions to match."
+ },
+ {
+ "metadata": {
+ "id": "6WZ2l2tN2zOL",
+ "colab_type": "code",
+ "colab": {
+ "autoexec": {
+ "startup": false,
+ "wait_interval": 0
+ }
+ },
+ "cellView": "both"
+ },
+ "cell_type": "code",
+ "input": "np.random.seed(133)\ndef 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\ntrain_dataset, train_labels = randomize(train_dataset, train_labels)\ntest_dataset, test_labels = randomize(test_dataset, test_labels)",
+ "language": "python",
+ "outputs": []
+ },
+ {
+ "metadata": {
+ "id": "puDUTe6t6USl",
+ "colab_type": "text"
+ },
+ "cell_type": "markdown",
+ "source": "---\nProblem 3\n---------\nConvince yourself that the data is still good after shuffling!\n\n---"
+ },
+ {
+ "metadata": {
+ "id": "cYznx5jUwzoO",
+ "colab_type": "text"
+ },
+ "cell_type": "markdown",
+ "source": "---\nProblem 4\n---------\nAnother check: we expect the data to be balanced across classes. Verify that.\n\n---"
+ },
+ {
+ "metadata": {
+ "id": "LA7M7K22ynCt",
+ "colab_type": "text"
+ },
+ "cell_type": "markdown",
+ "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\nAlso create a validation dataset for hyperparameter tuning."
+ },
+ {
+ "metadata": {
+ "id": "s3mWgZLpyuzq",
+ "colab_type": "code",
+ "colab": {
+ "autoexec": {
+ "startup": false,
+ "wait_interval": 0
+ },
+ "output_extras": [
+ {
+ "item_id": 1
+ }
+ ]
+ },
+ "cellView": "both",
+ "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
+ },
+ "outputId": "8af66da6-902d-4719-bedc-7c9fb7ae7948"
+ },
+ "cell_type": "code",
+ "input": "train_size = 200000\nvalid_size = 10000\n\nvalid_dataset = train_dataset[:valid_size,:,:]\nvalid_labels = train_labels[:valid_size]\ntrain_dataset = train_dataset[valid_size:valid_size+train_size,:,:]\ntrain_labels = train_labels[valid_size:valid_size+train_size]\nprint 'Training', train_dataset.shape, train_labels.shape\nprint 'Validation', valid_dataset.shape, valid_labels.shape",
+ "language": "python",
+ "outputs": [
+ {
+ "output_type": "stream",
+ "stream": "stdout",
+ "text": "Training (200000, 28, 28) (200000,)\nValidation (10000, 28, 28) (10000,)\n"
+ }
+ ]
+ },
+ {
+ "metadata": {
+ "id": "tIQJaJuwg5Hw",
+ "colab_type": "text"
+ },
+ "cell_type": "markdown",
+ "source": "Finally, let's save the data for later reuse:"
+ },
+ {
+ "metadata": {
+ "id": "QiR_rETzem6C",
+ "colab_type": "code",
+ "colab": {
+ "autoexec": {
+ "startup": false,
+ "wait_interval": 0
+ }
+ },
+ "cellView": "both"
+ },
+ "cell_type": "code",
+ "input": "pickle_file = 'notMNIST.pickle'\n\ntry:\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()\nexcept Exception as e:\n print 'Unable to save data to', pickle_file, ':', e\n raise",
+ "language": "python",
+ "outputs": []
+ },
+ {
+ "metadata": {
+ "id": "hQbLjrW_iT39",
+ "colab_type": "code",
+ "colab": {
+ "autoexec": {
+ "startup": false,
+ "wait_interval": 0
+ },
+ "output_extras": [
+ {
+ "item_id": 1
+ }
+ ]
+ },
+ "cellView": "both",
+ "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
+ },
+ "outputId": "b440efc6-5ee1-4cbc-d02d-93db44ebd956"
+ },
+ "cell_type": "code",
+ "input": "statinfo = os.stat(pickle_file)\nprint 'Compressed pickle size:', statinfo.st_size",
+ "language": "python",
+ "outputs": [
+ {
+ "output_type": "stream",
+ "stream": "stdout",
+ "text": "Compressed pickle size: 718193801\n"
+ }
+ ]
+ },
+ {
+ "metadata": {
+ "id": "gE_cRAQB33lk",
+ "colab_type": "text"
+ },
+ "cell_type": "markdown",
+ "source": "---\nProblem 5\n---------\n\nBy 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.\nMeasure how much overlap there is between training, validation and test samples.\nOptional 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 assignments.\n---"
+ },
+ {
+ "metadata": {
+ "id": "L8oww1s4JMQx",
+ "colab_type": "text"
+ },
+ "cell_type": "markdown",
+ "source": "---\nProblem 6\n---------\n\nLet'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\nTrain 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\nOptional question: train an off-the-shelf model on all the data!\n\n---"
+ }
+ ]
+ }
+ ],
+ "metadata": {
+ "name": "1_notmnist.ipynb",
+ "colabVersion": "0.3.2",
+ "colab_views": {},
+ "colab_default_view": {}
+ },
+ "nbformat": 3,
+ "nbformat_minor": 0
+} \ No newline at end of file