{"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\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":{"trusted":true},"cell_type":"code","source":"\nimport matplotlib.pyplot as plt\n%matplotlib inline\nfrom sklearn.model_selection import train_test_split\nfrom keras.utils.np_utils import to_categorical\nfrom keras.models import Sequential\nfrom keras.layers import Dense, Dropout, Flatten, Conv2D, MaxPool2D\nfrom keras.optimizers import RMSprop\nfrom keras.preprocessing.image import ImageDataGenerator\nfrom keras.callbacks import ReduceLROnPlateau, CSVLogger\n!pip install livelossplot\nfrom livelossplot import PlotLossesKeras\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"TRAINING_LOGS_FILE = \"training_logs.csv\"\nMODEL_SUMMARY_FILE = \"model_summary.txt\"\nMODEL_FILE = \"model.h5\"\nTRAINING_PLOT_FILE = \"training.png\"\nVALIDATION_PLOT_FILE = \"validation.png\"\nKAGGLE_SUBMISSION_FILE = \"kaggle_submission.csv\"\n\nVERBOSITY = 1\nEPOCHS = 100\nBATCH_SIZE = 1024\nCLASSES = 10\nCHANNELS = 1\nIMAGE_SIZE = 28\nIMAGE_WIDTH, IMAGE_HEIGHT = IMAGE_SIZE, IMAGE_SIZE\nVALIDATION_RATIO = 0.1\n","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"d629ff2d2480ee46fbb7e2d37f6b5fab8052498a","_cell_guid":"79c7e3d0-c299-4dcb-8224-4455121ee9b0","trusted":true},"cell_type":"code","source":"# Load data\ntrain = pd.read_csv(\"../input/digit-recognizer/train.csv\")\ntest = pd.read_csv(\"../input/digit-recognizer/test.csv\")\n\ny = train[\"label\"]\nx = train.drop(labels = [\"label\"], axis = 1) \n\nx = x.values.reshape(-1, IMAGE_WIDTH, IMAGE_HEIGHT, CHANNELS)\ntest = test.values.reshape(-1, IMAGE_WIDTH, IMAGE_HEIGHT, CHANNELS)\n\ny = to_categorical(y, num_classes=CLASSES)\n\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"x_training, x_validation, y_training, y_validation = train_test_split(x,\n                                                                      y,\n                                                                      test_size=VALIDATION_RATIO,\n                                                                      shuffle=True)\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# Data augmentation\ndata_generator = ImageDataGenerator(rescale=1./255,\n                                    rotation_range=10,\n                                    zoom_range=0.15, \n                                    width_shift_range=0.1,\n                                    height_shift_range=0.1)\ndata_generator.fit(x_training)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"model = Sequential()\n\nmodel.add(Conv2D(filters=32,\n                 kernel_size=(5,5),\n                 padding='Same', \n                 activation='relu',\n                 input_shape=(IMAGE_WIDTH, IMAGE_HEIGHT, CHANNELS)))\nmodel.add(Conv2D(filters=32,\n                 kernel_size=(5,5),\n                 padding='Same', \n                 activation='relu'))\nmodel.add(MaxPool2D(pool_size=(2,2)))\nmodel.add(Dropout(0.5))\n\nmodel.add(Conv2D(filters=64, kernel_size=(3,3),padding='Same', \n                 activation='relu'))\nmodel.add(Conv2D(filters=64, kernel_size=(3,3),padding='Same', \n                 activation='relu'))\nmodel.add(MaxPool2D(pool_size=(2,2), strides=(2,2)))\nmodel.add(Dropout(0.5))\n\nmodel.add(Flatten())\nmodel.add(Dense(8192, activation='relu'))\nmodel.add(Dropout(0.5))\n\nmodel.add(Dense(2048, activation='relu'))\nmodel.add(Dropout(0.5))\n\nmodel.add(Dense(CLASSES, activation=\"softmax\"))\n\nmodel.compile(optimizer=RMSprop(lr=0.0001,\n                                rho=0.9,\n                                epsilon=1e-08,\n                                decay=0.00001),\n              loss=\"categorical_crossentropy\",\n              metrics=[\"accuracy\"])","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"history = model.fit_generator(data_generator.flow(x_training,\n                                                  y_training,\n                                                  batch_size=BATCH_SIZE),\n                              epochs=EPOCHS,\n                              validation_data=(x_validation, y_validation),\n                              verbose=VERBOSITY,\n                              steps_per_epoch=x_training.shape[0] // BATCH_SIZE,\n                              callbacks=[PlotLossesKeras(),\n                                         CSVLogger(TRAINING_LOGS_FILE,\n                                                   append=False,\n                                                   separator=\";\")])\nmodel.save_weights(MODEL_FILE)\n\n# Testing\npredictions = model.predict_classes(test, verbose=1)\npd.DataFrame({\"ImageId\":list(range(1,len(predictions)+1)),\n              \"Label\":predictions}).to_csv(KAGGLE_SUBMISSION_FILE,\n                                           index=False,\n                                           header=True)\n\n# Drawing 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('training')\nplt.xlabel('epoch')\nplt.savefig(TRAINING_PLOT_FILE, bbox_inches='tight')\nplt.close()\n","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}