{"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)\nimport matplotlib.pyplot as plt\n\nfrom sklearn.model_selection import train_test_split\n\nfrom tensorflow import keras\nfrom keras.preprocessing.image import ImageDataGenerator\nfrom keras.models import Sequential\nfrom keras.layers import Conv2D, MaxPooling2D, BatchNormalization, Dropout, Flatten, Dense\nfrom keras.optimizers import Adam\nfrom keras.callbacks import ReduceLROnPlateau, EarlyStopping, ModelCheckpoint, TensorBoard\nfrom keras.utils.np_utils import to_categorical # convert to one-hot-encoding\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\nimport os\nprint(os.listdir(\"../input\"))\n\nseed = 4529\nnp.random.seed(seed)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"base_dir = os.path.join(\"..\", \"input\")\ntrain_df = pd.read_csv(os.path.join(base_dir, \"train.csv\"))\ntest_df = pd.read_csv(os.path.join(base_dir, \"test.csv\"))\n\nlen(train_df)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Tensorboard Visualizations \nHelps visualizing the training loss and accuracy after each epoch."},{"metadata":{"trusted":true},"cell_type":"code","source":"%load_ext tensorboard.notebook\n%tensorboard --logdir logs","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Input preprocessing"},{"metadata":{"trusted":true},"cell_type":"code","source":"x = train_df.drop(['label'], axis=1).values\ny = train_df['label'].values\ntest_x = test_df.values","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"x = x.reshape(-1, 28, 28, 1)\nx = x / 255.0\n\ntest_x = test_x.reshape(-1, 28, 28, 1)\ntest_x = test_x / 255.0\n\n# one-hot encoding\ny = to_categorical(y, num_classes=10)\n\nx_train, x_val, y_train, y_val = train_test_split(x, y, test_size = 0.1, random_state=seed)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Build the model using Keras"},{"metadata":{"trusted":true},"cell_type":"code","source":"model = Sequential([\n    Conv2D(128, (3,3), activation=\"relu\", input_shape=(28, 28, 1)),\n    BatchNormalization(),\n    Conv2D(128, (3,3), activation=\"relu\"),\n    BatchNormalization(),\n    MaxPooling2D(2,2),\n    Dropout(0.2),\n    Conv2D(64, (3,3), activation=\"relu\"),\n    BatchNormalization(),\n    Conv2D(64, (3,3), activation=\"relu\"),\n    BatchNormalization(),\n    MaxPooling2D(2,2),\n    Dropout(0.2),\n    Flatten(),\n    Dense(units=256, activation='relu'),\n    Dropout(0.4),\n    Dense(units=256, activation='relu'),\n    Dropout(0.4),\n    Dense(units=10, activation='softmax')\n])\n\nmodel.compile(optimizer=Adam(lr=0.001), \n                 loss='categorical_crossentropy',\n                 metrics=['acc'])\nmodel.summary()","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"## Callbacks"},{"metadata":{"trusted":true},"cell_type":"code","source":"ckpt_path = 'mnist.hdf5'\n\nearlystop = EarlyStopping(monitor='val_acc', patience=10, verbose=1, restore_best_weights=False)\nreducelr = ReduceLROnPlateau(monitor='val_acc', factor=0.5, patience=3, verbose=1, min_lr=1e-6)\nmodelckpt_cb = ModelCheckpoint(ckpt_path, monitor='val_acc', verbose=1, save_best_only=True, mode='max')\ntb = TensorBoard()\n\ncallbacks = [earlystop, reducelr, modelckpt_cb, tb]","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Train the model"},{"metadata":{"trusted":true},"cell_type":"code","source":"batch_size = 128\nepochs = 30\n\n# Using Data augmentation\ndatagen = ImageDataGenerator(rotation_range=15,\n                             width_shift_range=0.2,\n                             height_shift_range=0.2,\n                             zoom_range=0.15, \n                             shear_range=0.15)\ndatagen.fit(x_train)\n\n# Without data augmentation\n# history = model.fit(x_train, \n#               y_train, \n#               batch_size=batch_size, \n#               validation_data = (x_val, y_val),\n#               epochs=epochs, \n#               callbacks=callbacks)\n\nhistory = model.fit_generator(datagen.flow(x_train, y_train, batch_size=batch_size),\n                                 validation_data=(x_val, y_val),\n                                 steps_per_epoch = x_train.shape[0] // batch_size,\n                                 epochs=epochs, callbacks=callbacks)\n","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Visualizations\nVisualizing training and validation accuracy."},{"metadata":{"trusted":true},"cell_type":"code","source":"# Training plots\nepochs = [i for i in range(1, len(history.history['loss'])+1)]\n\nplt.plot(epochs, history.history['loss'], color='blue', label=\"training_loss\")\nplt.plot(epochs, history.history['val_loss'], color='red', label=\"validation_loss\")\nplt.legend(loc='best')\nplt.title('loss')\nplt.xlabel('epoch')\nplt.show()\n\nplt.plot(epochs, history.history['acc'], color='blue', label=\"training_accuracy\")\nplt.plot(epochs, history.history['val_acc'], color='red',label=\"validation_accuracy\")\nplt.legend(loc='best')\nplt.title('accuracy')\nplt.xlabel('epoch')\nplt.show()","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Make predictions on test set"},{"metadata":{"trusted":true},"cell_type":"code","source":"pred = model.predict(test_x)\npred = np.argmax(pred, axis=1)\npred = pd.Series(pred, name=\"Label\")\ntest_df = pd.concat([pd.Series(range(1,28001), name = \"ImageId\"), pred],axis = 1)\ntest_df.to_csv('mnist-submission.csv', index = False)","execution_count":null,"outputs":[]}],"metadata":{"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}