Skip to content

Instantly share code, notes, and snippets.

@Z30G0D
Created January 17, 2018 08:59
Show Gist options
  • Save Z30G0D/c9eb86824dc0de6adb6e1d2ca27dd266 to your computer and use it in GitHub Desktop.
Save Z30G0D/c9eb86824dc0de6adb6e1d2ca27dd266 to your computer and use it in GitHub Desktop.
FIrst Exercise of the Udacity deep learning course
{
"cells": [
{
"cell_type": "markdown",
"metadata": {
"colab_type": "text",
"id": "5hIbr52I7Z7U"
},
"source": [
"Deep Learning\n",
"=============\n",
"\n",
"Assignment 1\n",
"------------\n",
"\n",
"The 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",
"\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": 12,
"metadata": {
"cellView": "both",
"colab": {
"autoexec": {
"startup": false,
"wait_interval": 0
}
},
"colab_type": "code",
"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",
"from __future__ import print_function\n",
"from IPython.display import display\n",
"import PIL\n",
"from PIL import Image\n",
"import matplotlib.pyplot as plt\n",
"import imageio\n",
"import numpy as np\n",
"import os\n",
"import sys\n",
"import tarfile\n",
"from sklearn.linear_model import LogisticRegression\n",
"from six.moves.urllib.request import urlretrieve\n",
"from six.moves import cPickle as pickle\n",
"\n",
"# Config the matplotlib backend as plotting inline in IPython\n",
"%matplotlib inline"
]
},
{
"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 labeled examples. Given these sizes, it should be possible to train models quickly on any machine."
]
},
{
"cell_type": "code",
"execution_count": 4,
"metadata": {
"cellView": "both",
"colab": {
"autoexec": {
"startup": false,
"wait_interval": 0
},
"output_extras": [
{
"item_id": 1
}
]
},
"colab_type": "code",
"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": [
"Attempting to download: notMNIST_large.tar.gz\n",
"0%....5%....10%....15%....20%....25%....30%....35%....40%....45%....50%....55%....60%....65%....70%....75%....80%....85%....90%....95%....100%\n",
"Download Complete!\n",
"Found and verified .\\notMNIST_large.tar.gz\n",
"Attempting to download: notMNIST_small.tar.gz\n",
"0%....5%....10%....15%....20%....25%....30%....35%....40%....45%....50%....55%....60%....65%....70%....75%....80%....85%....90%....95%....100%\n",
"Download Complete!\n",
"Found and verified .\\notMNIST_small.tar.gz\n"
]
}
],
"source": [
"url = 'https://commondatastorage.googleapis.com/books1000/'\n",
"last_percent_reported = None\n",
"data_root = '.' # Change me to store data elsewhere\n",
"\n",
"def download_progress_hook(count, blockSize, totalSize):\n",
" \"\"\"A hook to report the progress of a download. This is mostly intended for users with\n",
" slow internet connections. Reports every 5% change in download progress.\n",
" \"\"\"\n",
" global last_percent_reported\n",
" percent = int(count * blockSize * 100 / totalSize)\n",
"\n",
" if last_percent_reported != percent:\n",
" if percent % 5 == 0:\n",
" sys.stdout.write(\"%s%%\" % percent)\n",
" sys.stdout.flush()\n",
" else:\n",
" sys.stdout.write(\".\")\n",
" sys.stdout.flush()\n",
" \n",
" last_percent_reported = percent\n",
" \n",
"def maybe_download(filename, expected_bytes, force=True):\n",
" \"\"\"Download a file if not present, and make sure it's the right size.\"\"\"\n",
" dest_filename = os.path.join(data_root, filename)\n",
" if force or not os.path.exists(dest_filename):\n",
" print('Attempting to download:', filename) \n",
" filename, _ = urlretrieve(url + filename, dest_filename, reporthook=download_progress_hook)\n",
" print('\\nDownload Complete!')\n",
" statinfo = os.stat(dest_filename)\n",
" if statinfo.st_size == expected_bytes:\n",
" print('Found and verified', dest_filename)\n",
" else:\n",
" raise Exception(\n",
" 'Failed to verify ' + dest_filename + '. Can you get to it with a browser?')\n",
" return dest_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, labeled A through J."
]
},
{
"cell_type": "code",
"execution_count": 24,
"metadata": {
"cellView": "both",
"colab": {
"autoexec": {
"startup": false,
"wait_interval": 0
},
"output_extras": [
{
"item_id": 1
}
]
},
"colab_type": "code",
"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": [
"Extracting data for .\\notMNIST_large. This may take a while. Please wait.\n",
"['.\\\\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",
"Extracting data for .\\notMNIST_small. This may take a while. Please wait.\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",
"np.random.seed(133)\n",
"\n",
"def maybe_extract(filename, force=False):\n",
" root = os.path.splitext(os.path.splitext(filename)[0])[0] # remove .tar.gz\n",
" if os.path.isdir(root) and not force:\n",
" # You may override by setting force=True.\n",
" print('%s already present - Skipping extraction of %s.' % (root, filename))\n",
" else:\n",
" print('Extracting data for %s. This may take a while. Please wait.' % root)\n",
" tar = tarfile.open(filename)\n",
" sys.stdout.flush()\n",
" tar.extractall(data_root)\n",
" tar.close()\n",
" data_folders = [\n",
" os.path.join(root, d) for d in sorted(os.listdir(root))\n",
" if os.path.isdir(os.path.join(root, d))]\n",
" if len(data_folders) != num_classes:\n",
" raise Exception(\n",
" 'Expected %d folders, one per class. Found %d instead.' % (\n",
" num_classes, len(data_folders)))\n",
" print(data_folders)\n",
" return data_folders\n",
" \n",
"train_folders = maybe_extract(train_filename)\n",
"test_folders = maybe_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": "code",
"execution_count": 25,
"metadata": {},
"outputs": [
{
"data": {
"image/png": "iVBORw0KGgoAAAANSUhEUgAAABwAAAAcCAAAAABXZoBIAAACsUlEQVR4nDWSS0hUYRzFz/+734wzd5xxRp2aGZOUnmomRYZhghhFJFGrogcVREQgtGzbPoMiaRURRYs2QZYEulB7IFppSYW9rIYejjM6cUdveu/9vn8L7Wx/nLM45wAUCAHxAMqLAECQQfgvSYZ5cNuI7d8U6vu5zsz3VPxeIPASJDRGL9VmsytiXsAaXKzKfnv1cM6hJUr1B2e7FAnt+RkEAPPDd15+dJfMZumYzUppVjz3V7PrKW2Pb1uKFbaeCGohSAtPBBYswxAs61vXlksAEgfkfIjJKbzNPVjZVlRdzWLRt6/mQTcACf5pkenZhWNqxr3d2jF0FEFU//CDGCL0NgYTFB1dM6190886G8GwKDdhMCBWZSIJBiH4KxlQxcnNDOiIO2IoAsSHhesFYsL2Q3UNxsaG9vWaxIwzlwswIEuOZwyAED6UmuzYKKtA2pvvGiwQAJnKtksQwBsamADA87qf9hT+FzzgaWZmT7F2NSvX+n21ORYAAImtn5oJABvKEsVps5zCwTORqbuzv4glWsP5UgOefD4sijeULXoJR/pO/pkbqHhBQPvFtMOK+49sSbTUrt59fmpcsdZ8IVoJrK3t/8Fa8f0avyADWNP5Js9auXYTSEx/f5wCCPFEMgot5Bcr6SkS6nMLTGBnW441a3VahImIhHzJihX3bk2cEvV76ksBRX23UoWIaUTpZHxKsNC7d8yOy8lrPXYIhq4493VvNrNqXfxszgTTkwz7XgOhm6yZlcP5Ozfej+aV4yp2eOxyggRw4l6BlWKt5+0sa/Y0e3m2uusgIEGOzWFmkAn/36AiPTPedOXFm3dCQ9JQfFfYykSi7Eh/MOslrde9E11pJTRARf7WysOjM2FfumRFunFzZxU9+oJZd/nWKI4itL8MsVQyhHAJ4DOxPNg/HwVPlq8jcpoAAAAASUVORK5CYII=\n",
"text/plain": [
"<IPython.core.display.Image object>"
]
},
"execution_count": 25,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"from IPython.display import Image\n",
"Image(filename=\"notMNIST_small\\B\\MDEtMDEtMDAudHRm.png\")"
]
},
{
"cell_type": "markdown",
"metadata": {
"colab_type": "text",
"id": "PBdkjESPK8tw"
},
"source": [
"Now let's load the data in a more manageable format. Since, depending on your computer setup you might not be able to fit it all in memory, we'll load each class into a separate dataset, store them on disk and curate them independently. Later we'll merge them into a single dataset of manageable size.\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. \n",
"\n",
"A few images might not be readable, we'll just skip them."
]
},
{
"cell_type": "code",
"execution_count": 26,
"metadata": {
"cellView": "both",
"colab": {
"autoexec": {
"startup": false,
"wait_interval": 0
},
"output_extras": [
{
"item_id": 30
}
]
},
"colab_type": "code",
"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": [
"Pickling .\\notMNIST_large\\A.pickle.\n",
".\\notMNIST_large\\A\n",
"Could not read: .\\notMNIST_large\\A\\RnJlaWdodERpc3BCb29rSXRhbGljLnR0Zg==.png : Could not find a format to read the specified file in mode 'i' - it's ok, skipping.\n",
"Could not read: .\\notMNIST_large\\A\\SG90IE11c3RhcmQgQlROIFBvc3Rlci50dGY=.png : Could not find a format to read the specified file in mode 'i' - it's ok, skipping.\n",
"Could not read: .\\notMNIST_large\\A\\Um9tYW5hIEJvbGQucGZi.png : Could not find a format to read the specified file in mode 'i' - it's ok, skipping.\n",
"Full dataset tensor: (52909L, 28L, 28L)\n",
"Mean: -0.12825\n",
"Standard deviation: 0.443121\n",
"Pickling .\\notMNIST_large\\B.pickle.\n",
".\\notMNIST_large\\B\n",
"Could not read: .\\notMNIST_large\\B\\TmlraXNFRi1TZW1pQm9sZEl0YWxpYy5vdGY=.png : Could not find a format to read the specified file in mode 'i' - it's ok, skipping.\n",
"Full dataset tensor: (52911L, 28L, 28L)\n",
"Mean: -0.00756303\n",
"Standard deviation: 0.454491\n",
"Pickling .\\notMNIST_large\\C.pickle.\n",
".\\notMNIST_large\\C\n",
"Full dataset tensor: (52912L, 28L, 28L)\n",
"Mean: -0.142258\n",
"Standard deviation: 0.439806\n",
"Pickling .\\notMNIST_large\\D.pickle.\n",
".\\notMNIST_large\\D\n",
"Could not read: .\\notMNIST_large\\D\\VHJhbnNpdCBCb2xkLnR0Zg==.png : Could not find a format to read the specified file in mode 'i' - it's ok, skipping.\n",
"Full dataset tensor: (52911L, 28L, 28L)\n",
"Mean: -0.0573678\n",
"Standard deviation: 0.455648\n",
"Pickling .\\notMNIST_large\\E.pickle.\n",
".\\notMNIST_large\\E\n",
"Full dataset tensor: (52912L, 28L, 28L)\n",
"Mean: -0.069899\n",
"Standard deviation: 0.452942\n",
"Pickling .\\notMNIST_large\\F.pickle.\n",
".\\notMNIST_large\\F\n",
"Full dataset tensor: (52912L, 28L, 28L)\n",
"Mean: -0.125583\n",
"Standard deviation: 0.44709\n",
"Pickling .\\notMNIST_large\\G.pickle.\n",
".\\notMNIST_large\\G\n",
"Full dataset tensor: (52912L, 28L, 28L)\n",
"Mean: -0.0945814\n",
"Standard deviation: 0.44624\n",
"Pickling .\\notMNIST_large\\H.pickle.\n",
".\\notMNIST_large\\H\n",
"Full dataset tensor: (52912L, 28L, 28L)\n",
"Mean: -0.0685221\n",
"Standard deviation: 0.454232\n",
"Pickling .\\notMNIST_large\\I.pickle.\n",
".\\notMNIST_large\\I\n",
"Full dataset tensor: (52912L, 28L, 28L)\n",
"Mean: 0.0307862\n",
"Standard deviation: 0.468899\n",
"Pickling .\\notMNIST_large\\J.pickle.\n",
".\\notMNIST_large\\J\n",
"Full dataset tensor: (52911L, 28L, 28L)\n",
"Mean: -0.153358\n",
"Standard deviation: 0.443656\n",
"Pickling .\\notMNIST_small\\A.pickle.\n",
".\\notMNIST_small\\A\n",
"Could not read: .\\notMNIST_small\\A\\RGVtb2NyYXRpY2FCb2xkT2xkc3R5bGUgQm9sZC50dGY=.png : Could not find a format to read the specified file in mode 'i' - it's ok, skipping.\n",
"Full dataset tensor: (1872L, 28L, 28L)\n",
"Mean: -0.132626\n",
"Standard deviation: 0.445128\n",
"Pickling .\\notMNIST_small\\B.pickle.\n",
".\\notMNIST_small\\B\n",
"Full dataset tensor: (1873L, 28L, 28L)\n",
"Mean: 0.00535609\n",
"Standard deviation: 0.457115\n",
"Pickling .\\notMNIST_small\\C.pickle.\n",
".\\notMNIST_small\\C\n",
"Full dataset tensor: (1873L, 28L, 28L)\n",
"Mean: -0.141521\n",
"Standard deviation: 0.44269\n",
"Pickling .\\notMNIST_small\\D.pickle.\n",
".\\notMNIST_small\\D\n",
"Full dataset tensor: (1873L, 28L, 28L)\n",
"Mean: -0.0492167\n",
"Standard deviation: 0.459759\n",
"Pickling .\\notMNIST_small\\E.pickle.\n",
".\\notMNIST_small\\E\n",
"Full dataset tensor: (1873L, 28L, 28L)\n",
"Mean: -0.0599148\n",
"Standard deviation: 0.45735\n",
"Pickling .\\notMNIST_small\\F.pickle.\n",
".\\notMNIST_small\\F\n",
"Could not read: .\\notMNIST_small\\F\\Q3Jvc3NvdmVyIEJvbGRPYmxpcXVlLnR0Zg==.png : Could not find a format to read the specified file in mode 'i' - it's ok, skipping.\n",
"Full dataset tensor: (1872L, 28L, 28L)\n",
"Mean: -0.118185\n",
"Standard deviation: 0.452279\n",
"Pickling .\\notMNIST_small\\G.pickle.\n",
".\\notMNIST_small\\G\n",
"Full dataset tensor: (1872L, 28L, 28L)\n",
"Mean: -0.0925503\n",
"Standard deviation: 0.449006\n",
"Pickling .\\notMNIST_small\\H.pickle.\n",
".\\notMNIST_small\\H\n",
"Full dataset tensor: (1872L, 28L, 28L)\n",
"Mean: -0.0586893\n",
"Standard deviation: 0.458759\n",
"Pickling .\\notMNIST_small\\I.pickle.\n",
".\\notMNIST_small\\I\n",
"Full dataset tensor: (1872L, 28L, 28L)\n",
"Mean: 0.0526451\n",
"Standard deviation: 0.471894\n",
"Pickling .\\notMNIST_small\\J.pickle.\n",
".\\notMNIST_small\\J\n",
"Full dataset tensor: (1872L, 28L, 28L)\n",
"Mean: -0.151689\n",
"Standard deviation: 0.448014\n"
]
}
],
"source": [
"image_size = 28 # Pixel width and height.\n",
"pixel_depth = 255.0 # Number of levels per pixel.\n",
"\n",
"def load_letter(folder, min_num_images):\n",
" \"\"\"Load the data for a single letter label.\"\"\"\n",
" image_files = os.listdir(folder)\n",
" dataset = np.ndarray(shape=(len(image_files), image_size, image_size),\n",
" dtype=np.float32)\n",
" print(folder)\n",
" num_images = 0\n",
" for image in image_files:\n",
" image_file = os.path.join(folder, image)\n",
" try:\n",
" image_data = (imageio.imread(image_file).astype(float) - 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[num_images, :, :] = image_data\n",
" num_images = num_images + 1\n",
" except (IOError, ValueError) as e:\n",
" print('Could not read:', image_file, ':', e, '- it\\'s ok, skipping.')\n",
" \n",
" dataset = dataset[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",
" \n",
" print('Full dataset tensor:', dataset.shape)\n",
" print('Mean:', np.mean(dataset))\n",
" print('Standard deviation:', np.std(dataset))\n",
" return dataset\n",
" \n",
"def maybe_pickle(data_folders, min_num_images_per_class, force=False):\n",
" dataset_names = []\n",
" for folder in data_folders:\n",
" set_filename = folder + '.pickle'\n",
" dataset_names.append(set_filename)\n",
" if os.path.exists(set_filename) and not force:\n",
" # You may override by setting force=True.\n",
" print('%s already present - Skipping pickling.' % set_filename)\n",
" else:\n",
" print('Pickling %s.' % set_filename)\n",
" dataset = load_letter(folder, min_num_images_per_class)\n",
" try:\n",
" with open(set_filename, 'wb') as f:\n",
" pickle.dump(dataset, f, pickle.HIGHEST_PROTOCOL)\n",
" except Exception as e:\n",
" print('Unable to save data to', set_filename, ':', e)\n",
" \n",
" return dataset_names\n",
"\n",
"train_datasets = maybe_pickle(train_folders, 45000)\n",
"test_datasets = maybe_pickle(test_folders, 1800)"
]
},
{
"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": "code",
"execution_count": 41,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"(['.\\\\notMNIST_small\\\\A.pickle',\n",
" '.\\\\notMNIST_small\\\\B.pickle',\n",
" '.\\\\notMNIST_small\\\\C.pickle',\n",
" '.\\\\notMNIST_small\\\\D.pickle',\n",
" '.\\\\notMNIST_small\\\\E.pickle',\n",
" '.\\\\notMNIST_small\\\\F.pickle',\n",
" '.\\\\notMNIST_small\\\\G.pickle',\n",
" '.\\\\notMNIST_small\\\\H.pickle',\n",
" '.\\\\notMNIST_small\\\\I.pickle',\n",
" '.\\\\notMNIST_small\\\\J.pickle'],\n",
" ['.\\\\notMNIST_large\\\\A.pickle',\n",
" '.\\\\notMNIST_large\\\\B.pickle',\n",
" '.\\\\notMNIST_large\\\\C.pickle',\n",
" '.\\\\notMNIST_large\\\\D.pickle',\n",
" '.\\\\notMNIST_large\\\\E.pickle',\n",
" '.\\\\notMNIST_large\\\\F.pickle',\n",
" '.\\\\notMNIST_large\\\\G.pickle',\n",
" '.\\\\notMNIST_large\\\\H.pickle',\n",
" '.\\\\notMNIST_large\\\\I.pickle',\n",
" '.\\\\notMNIST_large\\\\J.pickle'])"
]
},
"execution_count": 41,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"test_datasets, train_datasets"
]
},
{
"cell_type": "code",
"execution_count": 48,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"(52912L, 28L, 28L)"
]
},
"execution_count": 48,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"file = open(train_datasets[8], 'rb')# 8 equivalent to letter 'I', 0-9 are possible values\n",
"testing = pickle.load(file)\n",
"testing.shape"
]
},
{
"cell_type": "code",
"execution_count": 50,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"<matplotlib.image.AxesImage at 0x6012e358>"
]
},
"execution_count": 50,
"metadata": {},
"output_type": "execute_result"
},
{
"data": {
"image/png": "iVBORw0KGgoAAAANSUhEUgAAAP8AAAD8CAYAAAC4nHJkAAAABHNCSVQICAgIfAhkiAAAAAlwSFlzAAALEgAACxIB0t1+/AAAADl0RVh0U29mdHdhcmUAbWF0cGxvdGxpYiB2ZXJzaW9uIDIuMS4wLCBodHRwOi8vbWF0cGxvdGxpYi5vcmcvpW3flQAADoBJREFUeJzt3W2MXOV5xvHr2hevwXYcG9fGIS6E4LShkWqirUlK1VIlRIDUQNSmij9ErprW+UAkIkVtkb8EVUJCUfNWqYrkBDeOlIAiEQpSURREiUiUBGGoix2cFEJNcGxswAlgwPbu7N0Pe4w2sOeZ8bydgfv/k1Yzc+5z5tw7M9e8PefMcUQIQD5jTTcAoBmEH0iK8ANJEX4gKcIPJEX4gaQIP5AU4QeSIvxAUhPDXNn48mUxcc6qwgzlrQ2XT52qrS0bP1lc9uyxcn2J5or1Cdc/T7q4pNRS+f9qtdnK8lSMF+snY7K29spcfU2SZtpcd2uu/Pow5nLvS8dnamtTrq9J0t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bpSOeN1E+B+UtNH2O2wvkfQxSXc10Mfr2F5WfREj28skfUijd/ThuyRtrc5vlXRng738llE5cnPdkaXV8G03ake8bmQjn2oo40uaPwTszoi4aehNLML2hZp/tZfmf9n4W032ZvtWSZdrfq+vI5I+K+k/JH1b0u9K+qWkj0bE0L94q+ntcs2/dX31yM2nP2MPubc/kfQDSXslnf5p5O2a/3zd2G1X6GuLGrjd2MIPSIot/ICkCD+QFOEHkiL8QFKEH0iK8ANJEX4gKcIPJPX/VAQC7Ipcr8oAAAAASUVORK5CYII=\n",
"text/plain": [
"<matplotlib.figure.Figure at 0xbda5ac8>"
]
},
"metadata": {},
"output_type": "display_data"
}
],
"source": [
"plt.imshow(testing[1601,:,:])"
]
},
{
"cell_type": "markdown",
"metadata": {
"colab_type": "text",
"id": "cYznx5jUwzoO"
},
"source": [
"---\n",
"Problem 3\n",
"---------\n",
"Another check: we expect the data to be balanced across classes. Verify that.\n",
"\n",
"---"
]
},
{
"cell_type": "code",
"execution_count": 36,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
".\\notMNIST_large\\A.pickle size: 52909\n",
".\\notMNIST_large\\B.pickle size: 52911\n",
".\\notMNIST_large\\C.pickle size: 52912\n",
".\\notMNIST_large\\D.pickle size: 52911\n",
".\\notMNIST_large\\E.pickle size: 52912\n",
".\\notMNIST_large\\F.pickle size: 52912\n",
".\\notMNIST_large\\G.pickle size: 52912\n",
".\\notMNIST_large\\H.pickle size: 52912\n",
".\\notMNIST_large\\I.pickle size: 52912\n",
".\\notMNIST_large\\J.pickle size: 52911\n",
".\\notMNIST_small\\A.pickle size: 1872\n",
".\\notMNIST_small\\B.pickle size: 1873\n",
".\\notMNIST_small\\C.pickle size: 1873\n",
".\\notMNIST_small\\D.pickle size: 1873\n",
".\\notMNIST_small\\E.pickle size: 1873\n",
".\\notMNIST_small\\F.pickle size: 1872\n",
".\\notMNIST_small\\G.pickle size: 1872\n",
".\\notMNIST_small\\H.pickle size: 1872\n",
".\\notMNIST_small\\I.pickle size: 1872\n",
".\\notMNIST_small\\J.pickle size: 1872\n"
]
}
],
"source": [
"for letter in train_datasets:\n",
" file = open(letter, 'rb')\n",
" dataset = pickle.load(file)\n",
" print(letter + ' size: ' + str(dataset.shape[0]))\n",
"for letter in test_datasets:\n",
" file = open(letter, 'rb')\n",
" dataset = pickle.load(file)\n",
" print(letter + ' size: ' + str(dataset.shape[0]))"
]
},
{
"cell_type": "markdown",
"metadata": {
"colab_type": "text",
"id": "LA7M7K22ynCt"
},
"source": [
"Merge and 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. The labels will be stored into a separate array of integers 0 through 9.\n",
"\n",
"Also create a validation dataset for hyperparameter tuning."
]
},
{
"cell_type": "code",
"execution_count": 53,
"metadata": {
"cellView": "both",
"colab": {
"autoexec": {
"startup": false,
"wait_interval": 0
},
"output_extras": [
{
"item_id": 1
}
]
},
"colab_type": "code",
"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: (2000L, 28L, 28L) (2000L,)\n",
"Validation: (100L, 28L, 28L) (100L,)\n",
"Testing: (100L, 28L, 28L) (100L,)\n"
]
}
],
"source": [
"def make_arrays(nb_rows, img_size):\n",
" if nb_rows:\n",
" dataset = np.ndarray((nb_rows, img_size, img_size), dtype=np.float32)\n",
" labels = np.ndarray(nb_rows, dtype=np.int32)\n",
" else:\n",
" dataset, labels = None, None\n",
" return dataset, labels\n",
"\n",
"def merge_datasets(pickle_files, train_size, valid_size=0):\n",
" num_classes = len(pickle_files)\n",
" valid_dataset, valid_labels = make_arrays(valid_size, image_size)\n",
" train_dataset, train_labels = make_arrays(train_size, image_size)\n",
" vsize_per_class = valid_size // num_classes\n",
" tsize_per_class = train_size // num_classes\n",
" \n",
" start_v, start_t = 0, 0\n",
" end_v, end_t = vsize_per_class, tsize_per_class\n",
" end_l = vsize_per_class+tsize_per_class\n",
" for label, pickle_file in enumerate(pickle_files): \n",
" try:\n",
" with open(pickle_file, 'rb') as f:\n",
" letter_set = pickle.load(f)\n",
" # let's shuffle the letters to have random validation and training set\n",
" np.random.shuffle(letter_set)\n",
" if valid_dataset is not None:\n",
" valid_letter = letter_set[:vsize_per_class, :, :]\n",
" valid_dataset[start_v:end_v, :, :] = valid_letter\n",
" valid_labels[start_v:end_v] = label\n",
" start_v += vsize_per_class\n",
" end_v += vsize_per_class\n",
" \n",
" train_letter = letter_set[vsize_per_class:end_l, :, :]\n",
" train_dataset[start_t:end_t, :, :] = train_letter\n",
" train_labels[start_t:end_t] = label\n",
" start_t += tsize_per_class\n",
" end_t += tsize_per_class\n",
" except Exception as e:\n",
" print('Unable to process data from', pickle_file, ':', e)\n",
" raise\n",
" \n",
" return valid_dataset, valid_labels, train_dataset, train_labels\n",
" \n",
" \n",
"train_size = 2000 # changed all categories by factor of 10^-2 for short runtime\n",
"valid_size = 100\n",
"test_size = 100\n",
"\n",
"valid_dataset, valid_labels, train_dataset, train_labels = merge_datasets(\n",
" train_datasets, train_size, valid_size)\n",
"_, _, test_dataset, test_labels = merge_datasets(test_datasets, test_size)\n",
"\n",
"print('Training:', train_dataset.shape, train_labels.shape)\n",
"print('Validation:', valid_dataset.shape, valid_labels.shape)\n",
"print('Testing:', test_dataset.shape, test_labels.shape)"
]
},
{
"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": 58,
"metadata": {
"cellView": "both",
"colab": {
"autoexec": {
"startup": false,
"wait_interval": 0
}
},
"colab_type": "code",
"id": "6WZ2l2tN2zOL"
},
"outputs": [],
"source": [
"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",
"\n",
"\n",
"train_dataset, train_labels = randomize(train_dataset, train_labels)\n",
"test_dataset, test_labels = randomize(test_dataset, test_labels)\n",
"valid_dataset, valid_labels = randomize(valid_dataset, valid_labels)"
]
},
{
"cell_type": "markdown",
"metadata": {
"colab_type": "text",
"id": "puDUTe6t6USl"
},
"source": [
"---\n",
"Problem 4\n",
"---------\n",
"Convince yourself that the data is still good after shuffling!\n",
"\n",
"---"
]
},
{
"cell_type": "code",
"execution_count": 76,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"train dimensions are: (2000L, 28L, 28L) , val dimensions are: (100L, 28L, 28L), and test dimensions are:(100L, 28L, 28L)\n"
]
}
],
"source": [
"print('train dimensions are: %s , val dimensions are: %s, and test dimensions are:%s'%(train_dataset.shape, valid_dataset.shape, test_dataset.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": 77,
"metadata": {
"cellView": "both",
"colab": {
"autoexec": {
"startup": false,
"wait_interval": 0
}
},
"colab_type": "code",
"id": "QiR_rETzem6C"
},
"outputs": [],
"source": [
"pickle_file = os.path.join(data_root, '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": 78,
"metadata": {
"cellView": "both",
"colab": {
"autoexec": {
"startup": false,
"wait_interval": 0
},
"output_extras": [
{
"item_id": 1
}
]
},
"colab_type": "code",
"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: 6908445\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",
"\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 assignments.\n",
"---"
]
},
{
"cell_type": "code",
"execution_count": 82,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Inside training: 22\n",
"Between training and validation sets: 0\n",
"Between training and test: 1\n"
]
}
],
"source": [
"train_dataset.flags.writeable = False\n",
"valid_dataset.flags.writeable = False\n",
"test_dataset.flags.writeable = False\n",
"\n",
"train_hash = [hash(e.tobytes()) for e in train_dataset]\n",
"valid_hash = [hash(e.tobytes()) for e in valid_dataset]\n",
"test_hash = [hash(e.tobytes()) for e in test_dataset]\n",
"\n",
"unique_train_hash = set(train_hash)\n",
"\n",
"print('Inside training: ', len(train_hash) - len(unique_train_hash))\n",
"print('Between training and validation sets:', len(unique_train_hash.intersection(set(valid_hash))))\n",
"print('Between training and test:', len(unique_train_hash.intersection(set(test_hash))))"
]
},
{
"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",
"---"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"I took 50 samples from the original array and tried to apply linear regression"
]
},
{
"cell_type": "code",
"execution_count": 163,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"(50L, 28L, 28L)"
]
},
"execution_count": 163,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"from sklearn import linear_model\n",
"regr = linear_model.LogisticRegression('l1',C=1000.0)\n",
"\n",
"samples = train_dataset[:50,:,:]\n",
"samples1 = test_dataset[:50,:,:]\n",
"samples.shape\n"
]
},
{
"cell_type": "code",
"execution_count": 164,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"array([4, 5, 3, 7, 0, 2, 9, 8, 2, 8, 3, 1, 1, 5, 6, 3, 0, 8, 5, 9, 0, 9, 5,\n",
" 4, 2, 0, 4, 3, 4, 0, 7, 0, 6, 8, 4, 9, 3, 4, 2, 0, 0, 2, 9, 8, 8, 0,\n",
" 0, 9, 3, 0])"
]
},
"execution_count": 164,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"samples_labels = train_labels[:50]\n",
"samples1_labels = test_labels[:50]\n",
"\n",
"samples_labels"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"We need to shape all the pixels in one vector for input purpose."
]
},
{
"cell_type": "code",
"execution_count": 165,
"metadata": {},
"outputs": [],
"source": [
"samples = np.reshape(samples, (samples.shape[0], samples.shape[1] * samples.shape[2]))\n",
"samples1 = np.reshape(samples1, (samples1.shape[0], samples1.shape[1] * samples1.shape[2]))"
]
},
{
"cell_type": "code",
"execution_count": 166,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"LogisticRegression(C=1000.0, class_weight=None, dual=False,\n",
" fit_intercept=True, intercept_scaling=1, max_iter=100,\n",
" multi_class='ovr', n_jobs=1, penalty='l1', random_state=None,\n",
" solver='liblinear', tol=0.0001, verbose=0, warm_start=False)"
]
},
"execution_count": 166,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"regr.fit(samples,samples_labels)# training our model"
]
},
{
"cell_type": "code",
"execution_count": 167,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
" The score for our logistic regression is on the training is : 1.0\n",
" The score for our logistic regression is : 0.72\n"
]
}
],
"source": [
"print(' The score for our logistic regression is on the training is : ',(regr.score(samples, samples_labels)))\n",
"print(' The score for our logistic regression is : ',(regr.score(samples1, samples1_labels)))"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Well, that kinda suck, we have definitely overfitting here (perfect score for the training and 64% for the test).\n",
"I raised the regularization coefficient to 1000, and changed the penalty to 'l1' norm.\n",
"Basically bigger dataset could help, but I don't have the resources to implement it."
]
}
],
"metadata": {
"colab": {
"default_view": {},
"name": "1_notmnist.ipynb",
"provenance": [],
"version": "0.3.2",
"views": {}
},
"kernelspec": {
"display_name": "Python 2",
"language": "python",
"name": "python2"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 2
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython2",
"version": "2.7.14"
}
},
"nbformat": 4,
"nbformat_minor": 1
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment