{"cells":[{"metadata":{"_cell_guid":"84d4608d-4cc3-fcbb-57fb-61f07ad7d020","_uuid":"29ad35a6bb02af053a059b1393643afaacb1419a"},"cell_type":"markdown","source":"*Poonam Ligade*\n\n*1st Feb 2017*\n\n\n----------\n\n\nThis notebook is like note to self.\n\nI am trying to understand various components of Artificial Neural Networks aka Deep Learning.\n\nHope it might be useful for someone else here.\n\nI am designing neural net on MNIST handwritten digits images to identify their correct label i.e number in image.\n\nYou must have guessed its an image recognition task.\n\nMNIST is called Hello world of Deep learning.\n\nLets start!!\n\nThis notebook is inspired from [Jeremy's][1] [Deep Learning][2] mooc and [Deep learning with python][3] book by Keras author [François Chollet][4] .\n\n\n  [1]: https://www.linkedin.com/in/howardjeremy/\n  [2]: http://course.fast.ai/\n  [3]: https://www.manning.com/books/deep-learning-with-python\n  [4]: https://research.google.com/pubs/105096.html"},{"metadata":{"_cell_guid":"654456b6-e648-0379-0d66-1cc97af6d00d","_uuid":"78a76738dba52b03db6732564641c95bbf77ea52"},"cell_type":"markdown","source":"**Import all required libraries**\n==============================="},{"metadata":{"_cell_guid":"e5b02688-c589-5a89-e11c-837c6a99eb6e","_uuid":"bdfbb3de1e35840913c43010a114035733fc82a1","trusted":true},"cell_type":"code","source":"    # This Python 3 environment comes with many helpful analytics libraries installed\n# It is defined by the kaggle/python docker image: https://github.com/kaggle/docker-python\n# For example, here's several helpful packages to load in \n\nimport numpy as np # linear algebra\nimport pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)\n\nimport matplotlib.pyplot as plt\n%matplotlib inline\n\nfrom keras.models import Sequential\nfrom keras.layers import Dense , Dropout , Lambda, Flatten\nfrom keras.optimizers import Adam ,RMSprop\nfrom sklearn.model_selection import train_test_split\n\n# Input data files are available in the \"../input/\" directory.\n# For example, running this (by clicking run or pressing Shift+Enter) will list the files in the input directory\n\nfrom subprocess import check_output\nprint(check_output([\"ls\", \"../input\"]).decode(\"utf8\"))\n\n# Any results you write to the current directory are saved as output.","execution_count":1,"outputs":[]},{"metadata":{"_cell_guid":"22a7fd70-ab61-432d-24cb-93e558414495","_uuid":"158271ea290b06e8efb3f3253d064b5022010c76"},"cell_type":"markdown","source":"**Load Train and Test data**\n============================"},{"metadata":{"_cell_guid":"05226b08-226a-1a00-044d-a0e6b2101388","_uuid":"26e424f80f45b867ab6e793be9b63c953aeaddbe","trusted":true},"cell_type":"code","source":"# create the training & test sets, skipping the header row with [1:]\ntrain = pd.read_csv(\"../input/train.csv\")\nprint(train.shape)\ntrain.head()","execution_count":2,"outputs":[]},{"metadata":{"_cell_guid":"2ec570a6-b41a-2139-5e0e-4941c4f0a9d0","_uuid":"04a07731dceb126917652b02f0d581703dacac3f","trusted":true},"cell_type":"code","source":"test= pd.read_csv(\"../input/test.csv\")\nprint(test.shape)\ntest.head()","execution_count":3,"outputs":[]},{"metadata":{"_cell_guid":"1ae10fe0-dde9-7659-f53d-1a1bd625cfb1","_uuid":"4da6c9e3f1cf8667916c3cb00a8f1c36b754b52a","trusted":true},"cell_type":"code","source":"X_train = (train.ix[:,1:].values).astype('float32') # all pixel values\ny_train = train.ix[:,0].values.astype('int32') # only labels i.e targets digits\nX_test = test.values.astype('float32')","execution_count":4,"outputs":[]},{"metadata":{"_cell_guid":"250b1126-ce1d-6d3f-9736-2504f7a1e098","_uuid":"1b88aa8c26604382c11aee784bb641ce41633067","trusted":true},"cell_type":"code","source":"X_train","execution_count":5,"outputs":[]},{"metadata":{"_cell_guid":"e0f15f8a-ac08-540a-58db-dab989cc687c","_uuid":"bb1c5e661a40e854356ce2d8558814ccae14b5ea","trusted":true},"cell_type":"code","source":"y_train","execution_count":6,"outputs":[]},{"metadata":{"_cell_guid":"c2c91588-5547-353a-7f92-39600027438e","_uuid":"7ec474b7893fdccaab25810f64113ae2601479b4"},"cell_type":"markdown","source":"The output variable is an integer from 0 to 9. This is a **multiclass** classification problem."},{"metadata":{"_cell_guid":"60957d82-c76f-4822-28ff-def7011a34fa","_uuid":"7758b0c3e13c18874099f65bab8eedeacbe4068d"},"cell_type":"markdown","source":"Lets look at 3 images from data set with their labels."},{"metadata":{"_cell_guid":"1541678d-a08b-d2b2-1e1e-eabf882baaec","_uuid":"23e789c80e3d5baf6ee912cca5f50cbff8f76212","trusted":true},"cell_type":"code","source":"#Convert train datset to (num_images, img_rows, img_cols) format \nX_train = X_train.reshape(X_train.shape[0], 28, 28)\n\nfor i in range(6, 9):\n    plt.subplot(330 + (i+1))\n    plt.imshow(X_train[i], cmap=plt.get_cmap('gray'))\n    plt.title(y_train[i]);","execution_count":7,"outputs":[]},{"metadata":{"_cell_guid":"6be2f3e9-42eb-85b6-9162-c25e4d706155","_uuid":"8fe84884c8955acf2e508da635844fa1eaf83194","collapsed":true,"trusted":true},"cell_type":"code","source":"#expand 1 more dimention as 1 for colour channel gray\nX_train = X_train.reshape(X_train.shape[0], 28, 28,1)\nX_train.shape","execution_count":null,"outputs":[]},{"metadata":{"_cell_guid":"6949468c-fd27-19c5-15c7-0b357a961003","_uuid":"e059fb4c19fa4576060de5fc98c3fd1a0a0ee0b3","collapsed":true,"trusted":true},"cell_type":"code","source":"X_test = X_test.reshape(X_test.shape[0], 28, 28,1)\nX_test.shape","execution_count":null,"outputs":[]},{"metadata":{"_cell_guid":"1232c385-3cb2-56fd-4d1d-f027df7bc78e","_uuid":"5355b09df94bae663d1d36c4cb608563916619c0"},"cell_type":"markdown","source":"**Preprocessing the digit images**\n=================================="},{"metadata":{"_cell_guid":"6fcc1f9e-1586-e393-49ba-50c73564e0ed","_uuid":"29f028081e534e6b106c52de4e0c12f2a32e32cd"},"cell_type":"markdown","source":"**Feature Standardization**\n-------------------------------------\n\nIt is important preprocessing step.\nIt is used to centre the data around zero mean and unit variance."},{"metadata":{"_cell_guid":"a3f837ef-0373-8d91-46e6-30992cf73166","_uuid":"79023e7d6a4543e4bbd805db7948a0d2a409b490","collapsed":true,"trusted":true},"cell_type":"code","source":"mean_px = X_train.mean().astype(np.float32)\nstd_px = X_train.std().astype(np.float32)\n\ndef standardize(x): \n    return (x-mean_px)/std_px","execution_count":null,"outputs":[]},{"metadata":{"_cell_guid":"725c55fc-9742-a63c-9822-c67ab0c773ee","_uuid":"64539f0ce93a15a850b55c8fd67ba43f729bc434"},"cell_type":"markdown","source":"*One Hot encoding of labels.*\n-----------------------------\n\nA one-hot vector is a vector which is 0 in most dimensions, and 1 in a single dimension. In this case, the nth digit will be represented as a vector which is 1 in the nth dimension. \n\nFor example, 3 would be [0,0,0,1,0,0,0,0,0,0]."},{"metadata":{"_cell_guid":"c879f076-b3dd-6cb1-e2d9-2f404f2ed132","_uuid":"d58c394d0e22f2d7ba9770ca1c8618cf7ee38030","collapsed":true,"trusted":true},"cell_type":"code","source":"from keras.utils.np_utils import to_categorical\ny_train= to_categorical(y_train)\nnum_classes = y_train.shape[1]\nnum_classes","execution_count":null,"outputs":[]},{"metadata":{"_cell_guid":"4d76fb04-57fc-e802-6d91-06ece552686b","_uuid":"4036fb62d254eb62d984ecbc340d3e2ff1eff175"},"cell_type":"markdown","source":"Lets plot 10th label."},{"metadata":{"_cell_guid":"1c927e75-08d2-d539-54f3-71ab0308fec1","_uuid":"5284c7c7c79b4aabb5d51ce5698871c6b6c5d4fd","collapsed":true,"trusted":true},"cell_type":"code","source":"plt.title(y_train[9])\nplt.plot(y_train[9])\nplt.xticks(range(10));","execution_count":null,"outputs":[]},{"metadata":{"_cell_guid":"4e130661-9f09-d9a9-d49b-7274ef13927f","_uuid":"94f6dba5b6eb3a50485f9fc9cc63277db47fc8a8"},"cell_type":"markdown","source":"Oh its 3 !"},{"metadata":{"_cell_guid":"6a89dcdd-7b68-6ed1-2c39-b3a1edb3e7be","_uuid":"3ade83ef4b15c5d05ed881b66326c9e74801fc33"},"cell_type":"markdown","source":"**Designing Neural Network Architecture**\n========================================="},{"metadata":{"_cell_guid":"39107235-d87a-af4d-44fb-80c9c3aa0212","_uuid":"d145caa59c7e9008a7136a2b7cec4c2573898a1f","collapsed":true,"trusted":true},"cell_type":"code","source":"# fix random seed for reproducibility\nseed = 43\nnp.random.seed(seed)","execution_count":null,"outputs":[]},{"metadata":{"_cell_guid":"a8b65f54-398b-267f-e31a-313210450f54","_uuid":"fd2aa0cbb6c79b154199e75ce4c5794a04e5f361"},"cell_type":"markdown","source":"*Linear Model*\n--------------"},{"metadata":{"_cell_guid":"5dbe450c-845f-aaa2-dbde-21414a91d8c1","_uuid":"357819e32e27da3148fcec73b8ac921938d35d57","collapsed":true,"trusted":true},"cell_type":"code","source":"from keras.models import  Sequential\nfrom keras.layers.core import  Lambda , Dense, Flatten, Dropout\nfrom keras.callbacks import EarlyStopping\nfrom keras.layers import BatchNormalization, Convolution2D , MaxPooling2D","execution_count":null,"outputs":[]},{"metadata":{"_cell_guid":"5c3f674f-f3fc-9614-f2d4-056c3e3ad633","_uuid":"71c74aad5b136071058e2c9ec34864f5153910be"},"cell_type":"markdown","source":"Lets create a simple model from Keras Sequential layer.\n\n1. Lambda layer performs simple arithmetic operations like sum, average, exponentiation etc.\n\n In 1st layer of the model we have to define input dimensions of our data in (rows,columns,colour channel) format.\n (In theano colour channel comes first)\n\n\n2. Flatten will transform input into 1D array.\n\n\n3. Dense is fully connected layer that means all neurons in previous layers will be connected to all neurons in fully connected layer.\n In the last layer we have to specify output dimensions/classes of the model.\n Here it's 10, since we have to output 10 different digit labels."},{"metadata":{"_cell_guid":"a2c27783-3cfa-e907-4749-1e340a513f26","_uuid":"1289c1c3dedc79d6470837b05124c304ab638593","collapsed":true,"trusted":true},"cell_type":"code","source":"model= Sequential()\nmodel.add(Lambda(standardize,input_shape=(28,28,1)))\nmodel.add(Flatten())\nmodel.add(Dense(10, activation='softmax'))\nprint(\"input shape \",model.input_shape)\nprint(\"output shape \",model.output_shape)","execution_count":null,"outputs":[]},{"metadata":{"_cell_guid":"260645fb-61b7-68e9-6826-047b97436c14","_uuid":"8fd4a020c9c81ec2af1a1982a9c28b651f1efe58"},"cell_type":"markdown","source":"***Compile network***\n-------------------\n\nBefore making network ready for training we have to make sure to add below things:\n\n 1.  A loss function: to measure how good the network is\n    \n 2.  An optimizer: to update network as it sees more data and reduce loss\n    value\n    \n 3.  Metrics: to monitor performance of network"},{"metadata":{"_cell_guid":"9d1d1af9-b2a8-e3b9-6eaf-100d08fe83aa","_uuid":"479b9dba1fc200e5953185d5ff9905485925b62b","collapsed":true,"trusted":true},"cell_type":"code","source":"from keras.optimizers import RMSprop\nmodel.compile(optimizer=RMSprop(lr=0.001),\n loss='categorical_crossentropy',\n metrics=['accuracy'])","execution_count":null,"outputs":[]},{"metadata":{"_cell_guid":"db3b4be6-4f72-c6cc-65cd-b45978db2462","_uuid":"c5f6ba11edff2fc4037cae03a8bcbd8e88db67a2","collapsed":true,"trusted":true},"cell_type":"code","source":"from keras.preprocessing import image\ngen = image.ImageDataGenerator()","execution_count":null,"outputs":[]},{"metadata":{"_cell_guid":"9071d720-da50-8530-e9f3-1f0c37aac7ff","_uuid":"9d8b56954bd2c48204fd6f5d3eb061d4d0b479ef","collapsed":true,"trusted":true},"cell_type":"code","source":"from sklearn.model_selection import train_test_split\nX_train, X_val, y_train, y_val = train_test_split(X_train, y_train, test_size=0.10, random_state=42)\nbatches = gen.flow(X_train, y_train, batch_size=64)\nval_batches=gen.flow(X_val, y_val, batch_size=64)","execution_count":null,"outputs":[]},{"metadata":{"_cell_guid":"20e08e2a-a394-bb70-69f1-be0fdab4f9ab","_uuid":"61bb0f67aefefbb3334be23fc76f9ce5e2c50b84","collapsed":true,"trusted":true},"cell_type":"code","source":"history=model.fit_generator(batches, batches.n, nb_epoch=1, \n                    validation_data=val_batches, nb_val_samples=val_batches.n)","execution_count":null,"outputs":[]},{"metadata":{"_cell_guid":"9f344366-c372-0b04-b7e0-860778d4bfd3","_uuid":"56ec17f5bc3849e911b82c62d3023eedc2f05de4","collapsed":true,"trusted":true},"cell_type":"code","source":"history_dict = history.history\nhistory_dict.keys()","execution_count":null,"outputs":[]},{"metadata":{"_cell_guid":"df40f5fc-586a-1fae-025e-ee508a8d9b71","_uuid":"0472f5b6856cc07e84f5893310b786e850df555e","collapsed":true,"trusted":true},"cell_type":"code","source":"import matplotlib.pyplot as plt\n%matplotlib inline\nloss_values = history_dict['loss']\nval_loss_values = history_dict['val_loss']\nepochs = range(1, len(loss_values) + 1)\n\n# \"bo\" is for \"blue dot\"\nplt.plot(epochs, loss_values, 'bo')\n# b+ is for \"blue crosses\"\nplt.plot(epochs, val_loss_values, 'b+')\nplt.xlabel('Epochs')\nplt.ylabel('Loss')\n\nplt.show()","execution_count":null,"outputs":[]},{"metadata":{"_cell_guid":"1ed6b756-00c2-d08c-c596-0ce496ec3d04","_uuid":"60940248e84e39c50f9896d232541b77f2ca903c","collapsed":true,"trusted":true},"cell_type":"code","source":"plt.clf()   # clear figure\nacc_values = history_dict['acc']\nval_acc_values = history_dict['val_acc']\n\nplt.plot(epochs, acc_values, 'bo')\nplt.plot(epochs, val_acc_values, 'b+')\nplt.xlabel('Epochs')\nplt.ylabel('Accuracy')\n\nplt.show()","execution_count":null,"outputs":[]},{"metadata":{"_cell_guid":"e9c49f42-26af-73dc-9061-90c50c06f16e","_uuid":"4954c891d3926968ad33917719d6706533f94f08","collapsed":true,"trusted":true},"cell_type":"code","source":"model.optimizer.lr=0.01\ngen = image.ImageDataGenerator()\nbatches = gen.flow(X_train, y_train, batch_size=64)\nhistory=model.fit_generator(batches, batches.n, nb_epoch=1)","execution_count":null,"outputs":[]},{"metadata":{"_cell_guid":"c2841d54-f3dd-1ee8-a30d-4457dec0a67a","_uuid":"3e3fb4c8c6d1c20b91679ed24892da6d7e67805f","collapsed":true,"trusted":true},"cell_type":"code","source":"predictions = model.predict_classes(X_test, verbose=0)\n\nsubmissions=pd.DataFrame({\"ImageId\": list(range(1,len(predictions)+1)),\n                         \"Label\": predictions})\nsubmissions.to_csv(\"DR.csv\", index=False, header=True)","execution_count":null,"outputs":[]},{"metadata":{"_cell_guid":"d74ac4ce-9fd5-f8d7-fa1c-b6b64b25e882","_uuid":"d70d5804e6008aa22d155acfd6da4a4461bd9d6f"},"cell_type":"markdown","source":"More to come . Please upvote if you find it useful."},{"metadata":{"_cell_guid":"0e6213b0-fc56-658d-46e3-4a5dcb7148ce","_uuid":"549200f4bf5422c6a19e8a496025f9eb8a881feb"},"cell_type":"markdown","source":"You can increase number of epochs on your local machine to get better results."}],"metadata":{"_change_revision":0,"_is_fork":false,"kernelspec":{"display_name":"Python 3","language":"python","name":"python3"},"language_info":{"name":"python","version":"3.6.4","mimetype":"text/x-python","codemirror_mode":{"name":"ipython","version":3},"pygments_lexer":"ipython3","nbconvert_exporter":"python","file_extension":".py"}},"nbformat":4,"nbformat_minor":1}