{"cells":[{"metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","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\n\nimport numpy as np # linear algebra\nimport pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)\nimport matplotlib.pyplot as plt\nimport tensorflow as tf\nfrom tensorflow.keras.models import Sequential\nfrom  tensorflow.keras.layers import Dense, Dropout, Flatten, Conv2D, MaxPool2D, BatchNormalization\nfrom tensorflow.keras.optimizers import RMSprop\nfrom tensorflow.keras.preprocessing.image import ImageDataGenerator\nfrom tensorflow.keras.callbacks import EarlyStopping\n\n# Input data files are available in the read-only \"../input/\" directory\n# For example, running this (by clicking run or pressing Shift+Enter) will list all files under the input directory\n\nimport os\nfor dirname, _, filenames in os.walk('/kaggle/input'):\n    for filename in filenames:\n        print(os.path.join(dirname, filename))\n\n# You can write up to 20GB to the current directory (/kaggle/working/) that gets preserved as output when you create a version using \"Save & Run All\" \n# You can also write temporary files to /kaggle/temp/, but they won't be saved outside of the current session","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"## Get the train/test Data"},{"metadata":{"_uuid":"d629ff2d2480ee46fbb7e2d37f6b5fab8052498a","_cell_guid":"79c7e3d0-c299-4dcb-8224-4455121ee9b0","trusted":true},"cell_type":"code","source":"train = pd.read_csv('../input/digit-recognizer/train.csv')\ntest = pd.read_csv('../input/digit-recognizer/test.csv')\n\nprint(\"Train Shape:\", train.shape)\nprint(\"Test Shape:\", test.shape)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"X_train = (train.iloc[:,1:].values).astype('float32') # Convert Pixel values to floating point\ny_train = train.iloc[:,0].values.astype('int32') # Convert Labels to integers\n\nX_test = test.values.astype('float32') # Convert Pixel values to floating point","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"## Visualize the data"},{"metadata":{"trusted":true},"cell_type":"code","source":"# Reshape the data into (m, 28, 28) for plotting\nX_train = X_train.reshape(X_train.shape[0], 28, 28)\nX_test = X_test.reshape(X_test.shape[0], 28, 28)\n\nprint(X_train.shape)\nprint(X_test.shape)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"plt.title(\"Label: {}\".format(y_train[300]))\nplt.imshow(X_train[300])","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"plt.title(\"Label: {}\".format(y_train[50]))\nplt.imshow(X_train[50])","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"## Image preprocessing"},{"metadata":{"trusted":true},"cell_type":"code","source":"# Reshape into (m, 28, 28, 1) for the NN\nX_train = X_train.reshape(X_train.shape[0], 28, 28, 1)\nX_test = X_test.reshape(X_test.shape[0], 28, 28, 1)\n\nprint(X_train.shape)\nprint(X_test.shape)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"### Normalize the pixels\n\nScale down the pixel values into (0..1) using the Rescale (Min-Max Normalization) technique.  \n*Z_Score Standardization can also be used.*\n\n[Feature Scaling](https://en.wikipedia.org/wiki/Feature_scaling)"},{"metadata":{"trusted":true},"cell_type":"code","source":"X_train = X_train / 255\nX_test = X_test / 255","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"**We only divided by 255 becauses the min value is 0. Thus `(x-0)/(255-0) == x/255`**"},{"metadata":{},"cell_type":"markdown","source":"### One-hot encode the labels\n\nEach label is represented as a binary array with the corresponding index = 1 and all others  = 0.  \nEg. number 4 will be represented as `[0, 0, 0, 0, 1, 0, 0, 0, 0, 0]`.\n\n[One Hot Encoding](https://machinelearningmastery.com/why-one-hot-encode-data-in-machine-learning/)"},{"metadata":{"trusted":true},"cell_type":"code","source":"y_train = tf.keras.utils.to_categorical(y_train)\n\nprint(y_train.shape)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# Visualize one of the labels\nplt.title(\"Num {}: {}\".format(np.argmax(y_train[16]), y_train[16]))\nplt.plot(y_train[16])\nplt.xticks(range(y_train.shape[1]))","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"### Split the train set into Train and Validation Sets for cross validation\n\nIn Cross Validation, we evaluate the model's performance on the validation set (unseen data) after each epoch.\n\n[Cross Validation](https://machinelearningmastery.com/k-fold-cross-validation/)"},{"metadata":{"trusted":true},"cell_type":"code","source":"from sklearn.model_selection import train_test_split\n\nX_train, X_val, y_train, y_val = train_test_split(X_train, y_train, train_size=0.90, test_size=0.10, random_state=16)\n\nprint(X_train.shape)\nprint(X_val.shape)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train_num = X_train.shape[0] # Number of training examples\nval_num = X_val.shape[0] # Number of validation examples\n\nprint(train_num)\nprint(val_num)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"### Create a generator for feeding data to the model"},{"metadata":{"trusted":true},"cell_type":"code","source":"generator = ImageDataGenerator()\nbatch_size = 64\n\ntrain_set = generator.flow(X_train, y_train, batch_size = batch_size)\nval_set = generator.flow(X_val, y_val, batch_size = batch_size)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"## Build the NN Model"},{"metadata":{"trusted":true},"cell_type":"code","source":"model = Sequential()\n\nmodel.add(Conv2D(32, 3, input_shape=(28, 28, 1), activation='relu'))\nmodel.add(MaxPool2D(strides=2))\nmodel.add(BatchNormalization(axis=1))\n\nmodel.add(Conv2D(64, 3, padding='same', activation='relu'))\nmodel.add(MaxPool2D(strides=2))\nmodel.add(BatchNormalization(axis=1))\n\nmodel.add(Conv2D(64, 3, padding='same', activation='relu'))\nmodel.add(BatchNormalization(axis=1))\n\nmodel.add(Conv2D(128, 3, padding='same', activation='relu'))\nmodel.add(MaxPool2D(strides=2))\nmodel.add(BatchNormalization())\n\nmodel.add(Flatten())\n\nmodel.add(Dense(1152, activation='relu'))\nmodel.add(Dropout(0.5))\n\nmodel.add(Dense(10, activation='softmax'))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"model.summary()","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"## Compile the model\n\n[RMSProp](https://towardsdatascience.com/understanding-rmsprop-faster-neural-network-learning-62e116fcf29a)"},{"metadata":{"trusted":true},"cell_type":"code","source":"# Use 'categorical_crossentropy' because the labels are one-hot encoded\nmodel.compile(optimizer='rmsprop', loss='categorical_crossentropy', metrics=['accuracy'])","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"## Train the model"},{"metadata":{"trusted":true},"cell_type":"code","source":"# Monitor and early-stop after 2 epochs with no improvements\nearly_stop = EarlyStopping(monitor='val_loss', patience=2, mode='min')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"epochs = 10\n\nhistory = model.fit(\n    train_set,\n    epochs = epochs,\n    steps_per_epoch = train_num // batch_size,\n    validation_data = val_set,\n    validation_steps = val_num // batch_size,\n    callbacks = [early_stop]\n)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"## Visualize the training process\n\nPlot the accuracy and loss agains the epochs"},{"metadata":{"trusted":true},"cell_type":"code","source":"# Plot the graph\nacc = history.history['accuracy']\nval_acc = history.history['val_accuracy']\nloss = history.history['loss']\nval_loss = history.history['val_loss']\nepochs = range(1, len(loss) + 1)\n\n# plt.ioff()\n\n#accuracy plot\nplt.plot(epochs, acc, color='green', label='Training Accuracy')\nplt.plot(epochs, val_acc, color='blue', label='Validation Accuracy')\nplt.title('Training and Validation Accuracy')\nplt.ylabel('Accuracy')\nplt.xlabel('Epoch')\nplt.legend(['Train', 'Test'], loc='upper left')\n\nplt.figure()\n# #loss plot\nplt.plot(epochs, loss, color='pink', label='Training Loss')\nplt.plot(epochs, val_loss, color='red', label='Validation Loss')\nplt.title('Training and Validation Loss')\nplt.xlabel('Epoch')\nplt.ylabel('Loss')\nplt.legend()\n\nplt.show()\nplt.close()","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"## Make predictions on Test data"},{"metadata":{"trusted":true},"cell_type":"code","source":"# Run the model on the test data for predictions\npredictions = model.predict(X_test)\n# Convert the output to corresponding class (0..9)\npredictions = np.argmax(predictions, axis = -1)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"print(predictions)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"## Visualize the 1st and 3rd Test data"},{"metadata":{"trusted":true},"cell_type":"code","source":"# Plot the 1st test data\nfirst_test_img = X_test[0]\nplt.title(\"Predicted Label: {}\".format(predictions[0]))\nplt.imshow(first_test_img.reshape(28, 28 * 1))","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"### It is 2 just as the model predicted."},{"metadata":{"trusted":true},"cell_type":"code","source":"# Plot the 3rd test data\nthird_test_img = X_test[2]\nplt.title(\"Predicted Label: {}\".format(predictions[2]))\nplt.imshow(third_test_img.reshape(28, 28 * 1))","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"### It is 9 just as the model predicted."},{"metadata":{},"cell_type":"markdown","source":"## Submit results"},{"metadata":{"trusted":true},"cell_type":"code","source":"submissions = pd.DataFrame({\n    \"ImageId\": range(1, len(predictions)+1),\n    \"Label\": predictions\n})\nsubmissions.to_csv(\"DKB_Mnist.csv\", index=False, header=True)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"","execution_count":null,"outputs":[]}],"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"pygments_lexer":"ipython3","nbconvert_exporter":"python","version":"3.6.4","file_extension":".py","codemirror_mode":{"name":"ipython","version":3},"name":"python","mimetype":"text/x-python"}},"nbformat":4,"nbformat_minor":4}