{"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 in \n\nimport numpy as np # linear algebra\nimport pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)\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 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# Any results you write to the current directory are saved as output.","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"d629ff2d2480ee46fbb7e2d37f6b5fab8052498a","_cell_guid":"79c7e3d0-c299-4dcb-8224-4455121ee9b0","trusted":true},"cell_type":"code","source":"import matplotlib.pyplot as plt\nimport matplotlib.image as mpimg\n\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.metrics import confusion_matrix\nimport itertools\n\nimport tensorflow as tf\nimport keras","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"from tensorflow.keras.layers import Dense, Dropout, Conv2D, MaxPool2D, Flatten\n\nfrom tensorflow.keras.optimizers import RMSprop\nfrom tensorflow.keras.preprocessing.image import ImageDataGenerator\nfrom tensorflow.keras.callbacks import ReduceLROnPlateau","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"test = pd.read_csv(\"/kaggle/input/digit-recognizer/test.csv\")\ntrain = pd.read_csv(\"/kaggle/input/digit-recognizer/train.csv\")","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train.shape","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"y_train = train[\"label\"]\nx_train = train.drop(labels = [\"label\"], axis=1)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# normalisation\nx_train = x_train/255\ntest = test/255","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# convert to tensor\nx_train = x_train.values.reshape(-1,28,28,1)\ntest = test.values.reshape(-1, 28, 28, 1)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#y_train = keras.utils.np_utils.to_categorical(y_train, num_classes=10)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"y_train[0]","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"x_tr, x_val, y_tr, y_val = train_test_split(x_train, y_train, test_size = 0.1, random_state=5)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"plt.imshow(x_tr[0][:,:,0])","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"model = tf.keras.models.Sequential([\n    Conv2D(filters = 32, kernel_size = (5,5), activation=\"relu\", padding = \"Same\", input_shape=(28,28,1)),\n    MaxPool2D(pool_size=(2,2)),\n    \n    Conv2D(filters = 32, kernel_size = (4,4), activation=\"relu\", padding = \"Same\"),\n    MaxPool2D(pool_size=(2,2)),\n    Dropout(0.25),\n    \n    Conv2D(filters=64, kernel_size = (3,3), activation=\"relu\", padding = \"Same\"),\n    MaxPool2D(pool_size=(2,2)),\n    \n    Conv2D(filters = 64, kernel_size = (3,3), activation=\"relu\", padding = \"Same\"),\n    MaxPool2D(pool_size=(2,2)),\n    Dropout(0.25),\n    \n    Flatten(),\n    \n    Dense(256, activation=\"relu\"),\n    Dropout(0.25),\n    \n    Dense(10, activation = \"softmax\")\n])","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"model.compile(optimizer=\"adam\",\n              loss=tf.keras.losses.sparse_categorical_crossentropy,\n              metrics=[\"accuracy\"])","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"EPOCHS = 15\nBATCH_SIZE = 32","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#history = model.fit(x_tr, y_tr,\n#          batch_size=BATCH_SIZE,\n#          epochs=EPOCHS,\n#          verbose=1,\n#          validation_data=(x_val, y_val))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# 5 Epochs scored: 0.98557 on public LB","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"def plot_history(history):\n    acc = history.history['accuracy']\n    val_acc = history.history['val_accuracy']\n\n    loss = history.history['loss']\n    val_loss = history.history['val_loss']\n\n    epochs_range = range(EPOCHS)\n\n    plt.figure(figsize=(8, 8))\n    plt.subplot(1, 2, 1)\n    plt.plot(epochs_range, acc, label='Training Accuracy')\n    plt.plot(epochs_range, val_acc, label='Validation Accuracy')\n    plt.legend(loc='lower right')\n    plt.title('Training and Validation Accuracy')\n\n    plt.subplot(1, 2, 2)\n    plt.plot(epochs_range, loss, label='Training Loss')\n    plt.plot(epochs_range, val_loss, label='Validation Loss')\n    plt.legend(loc='upper right')\n    plt.title('Training and Validation Loss')\n    plt.show()","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"## Data augmentation"},{"metadata":{"trusted":true},"cell_type":"code","source":"datagen = ImageDataGenerator(rotation_range=20,\n                              width_shift_range=0.2,\n                              height_shift_range=0.2,\n                              zoom_range=0.2)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"datagen.fit(x_tr)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"history = model.fit_generator(datagen.flow(x_tr, y_tr, batch_size = BATCH_SIZE),\n                   steps_per_epoch = len(x_tr) / BATCH_SIZE,\n                   epochs = EPOCHS,\n                   validation_data = (x_val, y_val))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"plot_history(history)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"model.summary()","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"Problem with this model - too many max pooling layers. In the end its left with 1px per filter.\n\nnew structure:"},{"metadata":{"trusted":true},"cell_type":"code","source":"model = tf.keras.models.Sequential([\n    Conv2D(filters = 32, kernel_size = (5,5), activation=\"relu\", padding = \"Same\", input_shape=(28,28,1)),\n    Conv2D(filters = 32, kernel_size = (4,4), activation=\"relu\", padding = \"Same\"),\n    MaxPool2D(pool_size=(2,2)),\n    Dropout(0.25),\n    \n    Conv2D(filters=64, kernel_size = (3,3), activation=\"relu\", padding = \"Same\"),    \n    Conv2D(filters = 64, kernel_size = (2,2), activation=\"relu\", padding = \"Same\"),\n    MaxPool2D(pool_size=(2,2)),\n    Dropout(0.25),\n    \n    Flatten(),\n    \n    Dense(256, activation=\"relu\"),\n    Dropout(0.25),\n    \n    Dense(10, activation = \"softmax\")\n])","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"model.summary()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"model.compile(optimizer=\"adam\",\n             loss = tf.keras.losses.sparse_categorical_crossentropy,\n             metrics=[\"accuracy\"])","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"history = model.fit_generator(datagen.flow(x_tr, y_tr, batch_size=BATCH_SIZE),\n                             epochs = EPOCHS,\n                             validation_data = (x_val, y_val))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"plot_history(history)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Submission"},{"metadata":{"trusted":true},"cell_type":"code","source":"results = model.predict(test)\n\n# select the indix with the maximum probability\nresults = np.argmax(results,axis = 1)\n\nresults = pd.Series(results,name=\"Label\")","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"submission = pd.concat([pd.Series(range(1,28001),name = \"ImageId\"),results],axis = 1)\n\nsubmission.to_csv(\"cnn_mnist_datagen.csv\",index=False)","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}