{"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)\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 5GB 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":{"_uuid":"d629ff2d2480ee46fbb7e2d37f6b5fab8052498a","_cell_guid":"79c7e3d0-c299-4dcb-8224-4455121ee9b0","trusted":true},"cell_type":"code","source":"import pandas as pd\ntrain_data = pd.read_csv('../input/digit-recognizer/train.csv')\ntest_data = pd.read_csv('../input/digit-recognizer/test.csv')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"y = train_data[['label']]\ntrain_data = train_data.drop(['label'], axis = 1)\nX = train_data\nX_test = test_data","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#Normalizing the data\nX = X / 255.0\nX_test = X_test / 255.0","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#Reshaping the data from 28 * 28 to 28 * 28 *1\nX = X.values.reshape(-1, 28, 28, 1)\nX_test = X_test.values.reshape(-1, 28, 28, 1)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#One hot encoding\nfrom tensorflow.keras.utils import to_categorical\ny = to_categorical(y, num_classes = 10)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#DATA AUGMENTATION\nfrom tensorflow.keras.preprocessing.image import ImageDataGenerator\n\nimage_gen = ImageDataGenerator(\n               rotation_range = 40,\n               width_shift_range = 0.2,\n               height_shift_range = 0.2,\n               shear_range = 0.2,\n               zoom_range = 0.2,\n               horizontal_flip = False,\n               vertical_flip = False,\n               fill_mode = 'nearest')\n\nimage_gen.fit(X)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#display multiple images using subplot\nimport numpy as np\nfrom matplotlib import pyplot as plt\nrows = 4\ncols = 3\nax = []\nfig = plt.figure(figsize = (10,10))\nfor i in range(rows * cols):\n    ax.append(fig.add_subplot(rows, cols, i+1))\n    ax[-1].set_title(\"Label\" + str(y[i]))\n    plt.imshow(X[i][:,:,0], cmap = 'gray')\nfig.tight_layout()\nplt.show()    ","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#split the data into training and validation sets\nfrom sklearn.model_selection import train_test_split\nX_train, X_val, Y_train, Y_val = train_test_split(X, y, test_size = 0.1, random_state = 4)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# CNN architechture\n\nimport tensorflow as tf\nfrom tensorflow import keras\nfrom tensorflow.keras import layers\nfrom tensorflow.keras.callbacks import ReduceLROnPlateau\n\nmodel = keras.Sequential(\n     [\n         layers.Conv2D(filters = 32, kernel_size = (5,5), padding = 'same', activation = 'relu', input_shape = (28,28,1)),\n         layers.Conv2D(filters = 32, kernel_size = (5,5), padding = 'same', activation = 'relu'),\n         layers.MaxPool2D(pool_size = (2,2)),\n         layers.Dropout(0.25),\n         \n         layers.Conv2D(filters = 64, kernel_size = (3,3), padding = 'same', activation = 'relu'),\n         layers.Conv2D(filters = 64, kernel_size = (3,3), padding = 'same', activation = 'relu'),\n         layers.MaxPool2D(pool_size = (2,2), strides = (2,2)),\n         layers.Dropout(0.25),\n         \n         layers.Flatten(),\n         layers.Dense(256, activation = 'relu'),\n         layers.Dropout(0.50),\n         layers.Dense(10, activation = 'softmax')\n         \n     ])","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#optimizers\noptimizer = tf.keras.optimizers.RMSprop(lr=0.001, rho=0.9, epsilon=1e-08, decay=0.0)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#compiling the model by choosing optimizers, loss and metrics.\nmodel.compile(\n    optimizer = optimizer,\n    loss = 'categorical_crossentropy',\n    metrics = ['accuracy']\n)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# set a learning rate annealer\nlearning_rate_annealer = ReduceLROnPlateau(\n                             monitor = 'val_acc',\n                             patience = 3,\n                             verbose = 1,\n                             factor = 0.5,\n                             min_lr = 0.00001)\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#set epochs and batch size\nepochs = 30\nbatch_size = 64","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#Model checkpoint callback\nmodel_checkpoint = keras.callbacks.ModelCheckpoint(\n                           'my_checkpoint.h5', monitor = 'val_loss', save_best_only = True)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"'''history = model.fit_generator( image_gen.flow(X_train, Y_train, batch_size = batch_size),\n                               epochs = epochs,\n                               validation_data = (X_val, Y_val),\n                               verbose = 2,\n                               steps_per_epoch = int(X_train.shape[0]//batch_size),\n                               callbacks = [learning_rate_annealer,\n                                            model_checkpoint])'''\n                                            ","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# saving model using joblib\n'''from sklearn.externals import joblib\njoblib.dump(best_model, 'kaggle_model.pkl')'''","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"\nfilename = '../input/checkpoint/my_checkpoint.h5'\nbest_model = keras.models.load_model(filename)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#plot loss and accuracy curves\n'''\nfig, ax = plt.subplots(2,1)\nax[0].plot(history.history['loss'], color = 'b', label = 'Training loss')\nax[0].plot(history.history['val_loss'], color = 'r', label = 'Validation loss')\nlegend = ax[0].legend(loc = 'best', shadow = True)\n\nax[1].plot(history.history['acc'], color = 'b', label = 'Training Accuracy')\nax[1].plot(history.history['val_acc'], color = 'r', label = 'Validation Accuracy')\nlegend = ax[1].legend(loc = 'best', shadow = True)'''","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#plot confusion matrix\nimport seaborn as sns\nfrom sklearn.metrics import confusion_matrix\nimport numpy as np\nY_pred = best_model.predict(X_val)\nY_pred_classes = np.argmax(Y_pred, axis = 1)\nY_true = np.argmax(Y_val, axis = 1)\nconfusion_mtx = confusion_matrix(Y_true, Y_pred_classes)\nsns.heatmap(confusion_mtx, annot = True, fmt = 'd')\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#predict the results \nresults = best_model.predict(X_test)\n\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}