{"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\nimport tensorflow as tf\nfrom sklearn.model_selection import train_test_split\nimport keras\nfrom tensorflow.keras.optimizers import RMSprop\nfrom tensorflow.keras.preprocessing.image import ImageDataGenerator\nfrom keras.layers import LeakyReLU\nfrom keras.layers.normalization import BatchNormalization\nfrom tensorflow.keras.callbacks import LearningRateScheduler\n\nimport matplotlib.pyplot as plt \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":"train = pd.read_csv('/kaggle/input/digit-recognizer/train.csv')\ntest = pd.read_csv(\"/kaggle/input/digit-recognizer/test.csv\")","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"print(\"Train set shape = \" +str(train.shape))\nprint(\"Test set shape = \" +str(test.shape))","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Preprocessing data"},{"metadata":{"trusted":true},"cell_type":"code","source":"X=train.iloc[:,1:].values \nY=train.iloc[:,0].values ","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"We reshape the images from the training set, and convert the labels to categorical."},{"metadata":{"trusted":true},"cell_type":"code","source":"X = X.reshape(X.shape[0], 28, 28,1) \nprint(X.shape)\nY = keras.utils.to_categorical(Y, 10) \nprint(Y.shape)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"Now we reshape the test set."},{"metadata":{"trusted":true},"cell_type":"code","source":"x_test=test.iloc[:,:].values\nx_test = x_test.reshape(x_test.shape[0], 28, 28,1)\nx_test.shape","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"Now we split the training set into train and validation."},{"metadata":{"trusted":true},"cell_type":"code","source":"X_train, X_valid, Y_train, Y_valid = train_test_split(X, Y, test_size = 0.15, random_state=42) ","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"We use Kares data augmentation to have a larger training set. We also normalize the trainig a test sets."},{"metadata":{"trusted":true},"cell_type":"code","source":"train_datagen = ImageDataGenerator(rescale = 1./255.,\n                                   rotation_range = 10,\n                                   width_shift_range = 0.15,\n                                   height_shift_range = 0.15,\n                                   shear_range = 0.1,\n                                   zoom_range = 0.2,\n                                   horizontal_flip = False)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"valid_datagen = ImageDataGenerator(rescale=1./255) ","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Model"},{"metadata":{"trusted":true},"cell_type":"code","source":"model = tf.keras.models.Sequential([\n    tf.keras.layers.Conv2D(64, (3,3), padding='same', input_shape=(28, 28, 1)),\n    tf.keras.layers.LeakyReLU(alpha=0.1),\n    tf.keras.layers.Conv2D(64,  (3,3), padding='same'),\n    tf.keras.layers.LeakyReLU(alpha=0.1),\n\n    tf.keras.layers.MaxPooling2D(2, 2),\n    tf.keras.layers.Dropout(0.2),\n    \n    tf.keras.layers.Conv2D(64, (3,3), padding='same'),\n    tf.keras.layers.LeakyReLU(alpha=0.1),\n    tf.keras.layers.Conv2D(128, (3,3), padding='same'),\n    tf.keras.layers.LeakyReLU(alpha=0.1),\n    \n    tf.keras.layers.MaxPooling2D(2,2),\n    tf.keras.layers.Dropout(0.2),    \n    \n    tf.keras.layers.Conv2D(128, (3,3), padding='same'),\n    tf.keras.layers.LeakyReLU(alpha=0.1),\n\n    tf.keras.layers.Conv2D(256, (3,3), padding='same'),\n    tf.keras.layers.LeakyReLU(alpha=0.1),\n\n    \n    tf.keras.layers.MaxPooling2D(2,2),\n    tf.keras.layers.Dropout(0.2),\n    \n    \n    tf.keras.layers.Flatten(),\n    tf.keras.layers.Dense(256),\n    tf.keras.layers.LeakyReLU(alpha=0.1),\n    tf.keras.layers.BatchNormalization(),\n    tf.keras.layers.Dense(10, activation='softmax')\n])","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"model.summary()","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"Now we define the hyperparameters. For this notebook I set smaller batch size and epochs, and larger initial learning rate. The best results are achieved with different parameters but it takes a lot of time and resources."},{"metadata":{"trusted":true},"cell_type":"code","source":"initial_learningrate=1e-3 \nbatch_size = 128\nepochs = 40\ninput_shape = (28, 28, 1)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"We define a function that reduces the learning rate with the epochs."},{"metadata":{"trusted":true},"cell_type":"code","source":"def lr_decay(epoch):#lrv\n    return initial_learningrate * 0.9 ** epoch","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"model.compile(loss=\"categorical_crossentropy\",\n              optimizer=RMSprop(lr=initial_learningrate),\n              metrics=['accuracy'])","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Training"},{"metadata":{"trusted":true},"cell_type":"code","source":"history = model.fit_generator(\n      train_datagen.flow(X_train,Y_train, batch_size=batch_size),\n      steps_per_epoch=100,\n      epochs=epochs,\n      callbacks=[LearningRateScheduler(lr_decay) \n               ],\n      validation_data=valid_datagen.flow(X_valid,Y_valid),\n      validation_steps=50,  \n      verbose=2)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Plot"},{"metadata":{"trusted":true},"cell_type":"code","source":"accuracy = history.history['acc']\nval_accuracy = history.history['val_acc']\nloss = history.history['loss']\nval_loss = history.history['val_loss']\nepochs = range(len(accuracy))\nplt.plot(epochs, accuracy, 'b', label='Training accuracy')\nplt.plot(epochs, val_accuracy, 'r', label='Test accuracy')\nplt.title('Accuracy')\nplt.legend()\nplt.show()\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"plt.figure()\nplt.plot(epochs, loss, 'b', label='Training loss')\nplt.plot(epochs, val_loss, 'r', label='Test loss')\nplt.title('Loss')\nplt.legend()\nplt.show()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"predictions = model.predict_classes(x_test/255.)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"final=pd.DataFrame({\"ImageId\": list(range(1,len(predictions)+1)),\n                         \"Label\": predictions})","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"final.to_csv(\"cnn_submission.csv\",index=False)\n","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":1}