{"cells":[{"metadata":{"_uuid":"7ed04b1e7a00a7ad31ee98a7d8e55880e6274f29"},"cell_type":"markdown","source":"**Import all Necessary Libraries**","execution_count":null},{"metadata":{"trusted":true,"_uuid":"0f935bddcc5ca02702578e712bf7f396ba7154ef"},"cell_type":"code","source":"import pandas as pd\nimport numpy as np\n\nimport matplotlib.pyplot as plt\nimport seaborn as sns\n\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.metrics import confusion_matrix\n\nfrom keras.models import Sequential\nfrom keras.layers import Conv2D, Lambda, MaxPooling2D # convolution layers\nfrom keras.layers import Dense, Dropout, Flatten # core layers\n\nfrom keras.layers.normalization import BatchNormalization\n\nfrom keras.preprocessing.image import ImageDataGenerator\n\nfrom keras.utils.np_utils import to_categorical\n\n#from keras.datasets import mnist","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"import os\nprint(os.listdir('../input'))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#load data\ntrain = pd.read_csv('../input/train.csv')\ntest = pd.read_csv('../input/test.csv')\nsub = pd.read_csv('../input/sample_submission.csv')\nprint(\"Data are Ready!!\")","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"print(train.shape,test.shape)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"**Set data features and labels**","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"X = train.drop(['label'], 1).values\ny = train['label'].values\n\ntest_x = test.values","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"X = X / 255.0\ntest_x = test_x / 255.0","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"##  Reshape","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"# Reshape image in 3 dimensions (height = 28px, width = 28px , canal = 1)\n# canal = 1 => For gray scale\nX = X.reshape(-1,28,28,1)\ntest_x = test_x.reshape(-1,28,28,1)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"## Label encoding","execution_count":null},{"metadata":{},"cell_type":"markdown","source":"**One-Hot Encoding**","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"# Encode labels to one hot vectors (ex : 2 -> [0,0,1,0,0,0,0,0,0,0])\ny = to_categorical(y)\n\nprint(f\"Label size {y.shape}\")","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"Labels are 10 digits numbers from 0 to 9. We need to encode these lables to one hot vectors (ex : 2 -> [0,0,1,0,0,0,0,0,0,0]).","execution_count":null},{"metadata":{},"cell_type":"markdown","source":"## Split training and valdiation set","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"# Split the train and the validation set for the fitting\nX_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.1, random_state=0)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"X_train.shape, X_test.shape, y_train.shape, y_test.shape","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"a4f73e65842423bae7cfce945cd4dc0e367c180a"},"cell_type":"markdown","source":"**Normalization**","execution_count":null},{"metadata":{"trusted":true,"_uuid":"82bddf135bfad1d3f91b52cd0cadb62e55db964b"},"cell_type":"code","source":"mean = np.mean(X_train)\nstd = np.std(X_train)\n\ndef standardize(x):\n    return (x-mean)/std","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"epochs = 50\nbatch_size = 64","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"\n## Define the model","execution_count":null},{"metadata":{"trusted":true,"_uuid":"e935c979b0715a68bc8739e6a31f5d9a8189a750"},"cell_type":"code","source":"model=Sequential()\n\n#model.add(Lambda(standardize,input_shape=(28,28,1)))    \nmodel.add(Conv2D(filters=64, kernel_size = (3,3), activation=\"relu\", input_shape=(28,28,1)))\nmodel.add(Conv2D(filters=64, kernel_size = (3,3), activation=\"relu\"))\n\nmodel.add(MaxPooling2D(pool_size=(2,2)))\nmodel.add(BatchNormalization())\nmodel.add(Conv2D(filters=128, kernel_size = (3,3), activation=\"relu\"))\nmodel.add(Conv2D(filters=128, kernel_size = (3,3), activation=\"relu\"))\n\nmodel.add(MaxPooling2D(pool_size=(2,2)))\nmodel.add(BatchNormalization())    \nmodel.add(Conv2D(filters=256, kernel_size = (3,3), activation=\"relu\"))\n    \nmodel.add(MaxPooling2D(pool_size=(2,2)))\n    \nmodel.add(Flatten())\nmodel.add(BatchNormalization())\nmodel.add(Dense(512,activation=\"relu\"))\n    \nmodel.add(Dense(10,activation=\"softmax\"))\n    \nmodel.compile(loss=\"categorical_crossentropy\", optimizer=\"adam\", metrics=[\"accuracy\"])","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"##  Data augmentation","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"# With data augmentation to prevent overfitting\n\ndatagen = ImageDataGenerator(\n        featurewise_center=False,  # set input mean to 0 over the dataset\n        samplewise_center=False,  # set each sample mean to 0\n        featurewise_std_normalization=False,  # divide inputs by std of the dataset\n        samplewise_std_normalization=False,  # divide each input by its std\n        zca_whitening=False,  # apply ZCA whitening\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        vertical_flip=False)  # randomly flip images\n\n\n#datagen.fit(X_train)\ntrain_gen = datagen.flow(X_train, y_train, batch_size=batch_size)\ntest_gen = datagen.flow(X_test, y_test, batch_size=batch_size)","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"5a9a1f37ef33b24887f97e7992b7d24567602eb8"},"cell_type":"markdown","source":"## Model training","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"# Fit the model\nhistory = model.fit_generator(train_gen, \n                              epochs = epochs, \n                              steps_per_epoch = X_train.shape[0] // batch_size,\n                              validation_data = test_gen,\n                              validation_steps = X_test.shape[0] // batch_size)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"**Plot CNN model**","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"from keras.utils.vis_utils import plot_model\nplot_model(model, to_file='model_plot.png', show_shapes=True, show_layer_names=True)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"##  Prediction validation results","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"y_pred = model.predict(X_test)\nX_test__ = X_test.reshape(X_test.shape[0], 28, 28)\n\nfig, axis = plt.subplots(4, 4, figsize=(12, 14))\nfor i, ax in enumerate(axis.flat):\n    ax.imshow(X_test__[i], cmap='binary')\n    ax.set(title = f\"Real Number is {y_test[i].argmax()}\\nPredict Number is {y_pred[i].argmax()}\");","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"##  Submition","execution_count":null},{"metadata":{"trusted":true,"_uuid":"afcacfa4a023a9e01a61b5d7dcd051f0a439fa38"},"cell_type":"code","source":"pred = model.predict_classes(test_x, verbose=1)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"sub['Label'] = pred\nsub.to_csv(\"dig_recg_sub.csv\", index=False)\nsub.head()","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}