{"cells":[{"metadata":{},"cell_type":"markdown","source":"![](https://miro.medium.com/max/584/1*2lSjt9YKJn9sxK7DSeGDyw.jpeg)"},{"metadata":{"trusted":true},"cell_type":"code","source":"import keras\nfrom keras.datasets import cifar10\nfrom keras.models import Sequential\nfrom keras.layers import Dense, Dropout, Flatten, Conv2D, MaxPooling2D\nfrom keras.layers.normalization import BatchNormalization\nimport pydot\nfrom IPython.display import SVG\nfrom keras.utils.vis_utils import model_to_dot\nfrom keras.utils import plot_model\nfrom keras.preprocessing.image import ImageDataGenerator\nfrom sklearn.preprocessing import LabelBinarizer\nfrom keras.callbacks import ReduceLROnPlateau\n\n\nimport pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom sklearn.model_selection import train_test_split","execution_count":null,"outputs":[]},{"metadata":{"_execution_state":"idle","_uuid":"84bbd5ab8d7895bd430d5ecfe2f7ddf77baa7b74","_cell_guid":"5e51d00e-62fd-4141-bf73-50ac4f2da7d0","trusted":true},"cell_type":"code","source":"# Load the data\ntrain = pd.read_csv(\"../input/digit-recognizer/train.csv\")\ntest = pd.read_csv(\"../input/digit-recognizer/test.csv\")","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"\ntrain.head()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"\ntest.head()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"x_train = train.drop(labels = [\"label\"],axis = 1) \ny_train = train[\"label\"]","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"\n# Normalize data set to 0-to-1 range\nx_train = x_train.astype('float32')\ntest = test.astype('float32')\nx_train /= 255\ntest /= 255","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"y_train = keras.utils.to_categorical(y_train, 10)\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"test.values","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"x_train","execution_count":null,"outputs":[]},{"metadata":{"_execution_state":"idle","_uuid":"f0a6ad80dab8e0f2c2e46165ccd9cd82dd162bc3","_cell_guid":"34b6a5f7-8fd2-4387-8ef4-c9dc19584fed","trusted":true},"cell_type":"code","source":"### Reshaping\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":"dataAug = ImageDataGenerator(\n        rotation_range=10,  # randomly rotate images in the range (degrees, 0 to 180)\n        zoom_range = 0.1, # Randomly zoom image \n        width_shift_range=0.1,  # randomly shift images horizontally (fraction of total width)\n        height_shift_range=0.1,  # randomly shift images vertically (fraction of total height)\n        horizontal_flip=False)  # randomly flip images\n\ndataAug.fit(x_train)","execution_count":null,"outputs":[]},{"metadata":{"_execution_state":"idle","_uuid":"b779ac76d8317647db92d5a88b4098d212d72884","_cell_guid":"dcd25ebb-d845-4d32-9867-082e352b1396","trusted":true},"cell_type":"code","source":"### Splitting into training and validation set\nx_train, x_val, y_train, y_val = train_test_split(x_train, y_train, test_size = 0.2, random_state=42)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"lr_reduce = ReduceLROnPlateau(monitor='val_accuracy', patience = 2, verbose=1,factor=0.5, min_lr=0.000001)","execution_count":null,"outputs":[]},{"metadata":{"_execution_state":"idle","_uuid":"f7991ef6871a26f9fa57acdcd460a69bab53e804","_cell_guid":"1e0f3f88-2ad7-459e-8e02-aecc5f3511ae","trusted":true},"cell_type":"code","source":"### Designing the model\nmodel = Sequential()\n\nmodel.add(Conv2D(64, (3, 3), input_shape=(28,28,1), activation=\"relu\"))\nmodel.add(BatchNormalization())\nmodel.add(Conv2D(64, (3, 3),activation=\"relu\"))\nmodel.add(BatchNormalization())\nmodel.add(MaxPooling2D(pool_size=(2, 2),strides = (2,2)))\nmodel.add(Dropout(0.15))\n\nmodel.add(Conv2D(128, (3, 3), activation=\"relu\"))\nmodel.add(BatchNormalization())\nmodel.add(Conv2D(128, (3, 3),activation=\"relu\"))\nmodel.add(BatchNormalization())\nmodel.add(MaxPooling2D(pool_size=(2, 2),strides = (2,2)))\nmodel.add(Dropout(0.25))\n\nmodel.add(Conv2D(filters=256, kernel_size = (3,3), activation=\"relu\"))\nmodel.add(BatchNormalization())\nmodel.add(MaxPooling2D(pool_size=(2,2)))\n\nmodel.add(Flatten())\nmodel.add(BatchNormalization())\nmodel.add(Dropout(0.5))\nmodel.add(Dense(512, activation=\"relu\"))\n\nmodel.add(Dense(10, activation=\"softmax\"))\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"model.compile(\n    loss='categorical_crossentropy',\n    optimizer=\"adam\",\n    metrics=['accuracy']\n)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"model.fit(\n    x_train,\n    y_train,\n    batch_size=64,\n    epochs=30,\n    validation_data=(x_val, y_val),\n    shuffle=True,\n    callbacks = [lr_reduce]\n)\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":"plot_model(model, to_file='Model.png')\nSVG(model_to_dot(model).create(prog='dot', format='svg'))","execution_count":null,"outputs":[]},{"metadata":{"_execution_state":"idle","_uuid":"7f17e7bf0a54a01a52fef2d554780f6bc6580dc6","_cell_guid":"05ff3b9f-c3bb-4cec-a8c2-2c128e8f15b3","trusted":true},"cell_type":"code","source":"results = model.predict(test)\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"results = np.argmax(results,axis = 1)\nresults = pd.Series(results,name=\"Label\")","execution_count":null,"outputs":[]},{"metadata":{"_execution_state":"idle","_uuid":"369dfaab09240f3f12bcff91953ffd315ab84985","_cell_guid":"b5f1f39f-13b8-439a-8913-0f120e3d47a9","trusted":true},"cell_type":"code","source":"submission = pd.concat([pd.Series(range(1,28001),name = \"ImageId\"),results],axis = 1)\n\nsubmission.to_csv(\"submission.csv\",index=False)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"submission","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":4}