{"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_minor":4,"nbformat":4,"cells":[{"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 20GB 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","metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import seaborn as sns\nimport matplotlib.pyplot as plt\nfrom sklearn import model_selection\nimport tensorflow as tf\n\nfrom tensorflow.keras.preprocessing.image import ImageDataGenerator\nfrom tensorflow.keras.models import Sequential\nfrom tensorflow.keras.layers import Dense,Flatten,Input,BatchNormalization,Dropout, Conv2D,MaxPooling2D","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train_data = pd.read_csv(\"/kaggle/input/digit-recognizer/train.csv\")\ntest_data = pd.read_csv(\"/kaggle/input/digit-recognizer/test.csv\")\n\ntrain_data.head()","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"x_train = train_data.iloc[:,1:]\ny_train = train_data.iloc[:,0]","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"","metadata":{}},{"cell_type":"code","source":"y_train.unique()","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"y_train.value_counts()","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"sns.barplot(x=y_train.unique(),y=y_train.value_counts())\nplt.xlabel(\"Digits\")\nplt.ylabel(\"Frequency\")\nplt.show()","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"Looking at the class distribution graph, we can say that the classes are evenly distributed. Therefore, there is not need of resampling.","metadata":{}},{"cell_type":"code","source":"def visualize_helper(index):\n    plt.imshow(np.array(x_train.iloc[index,:]).reshape((28,28)),cmap='binary_r')\n    plt.axis('off')\n    plt.show()   ","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"visualize_helper(786)","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"I just visualized the image here. Since images are given in csv format,I reshaped it into the images format (ie 28X28 = 784). For this purpose, I wrote a helper code. ","metadata":{}},{"cell_type":"code","source":"y_train[786]","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"## reshaping the data from 784 1D to 28*28*1 3D.\n\nx_train_3d = np.array(x_train).reshape(-1,28,28,1)","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"we are reshaping the data into images:\n- -1 is given for the number of rows in the dataset\n- 28X28 is the size of the image\n- 1 is the channel as image is black and white,","metadata":{}},{"cell_type":"code","source":"## Data Augmentation\nfrom tensorflow.keras.preprocessing.image import ImageDataGenerator\n\ntrain_datagen = ImageDataGenerator(rescale = 1./255,rotation_range=20,\n                              zoom_range = 0.2,width_shift_range=0.1,\n                              height_shift_range = 0.1,validation_split=0.2)\n\ntrain_generator = train_datagen.flow(x_train_3d,y_train,batch_size=64,subset='training')\nvalidation_generator = train_datagen.flow(x_train_3d,y_train,batch_size=64,subset='validation')","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"Data Augmentation is performed in order to introduce variation that we may encounter in the test set. These variations are domain specific. So please pick and choose the variation according to your problem domain. Here I have used the following variations:\n- Rescale - rescales the image in the range 0 to 1\n- Rotation range - rotates for upto +/- 20 degress\n- Zoom range - Zooms into the image for upto 20% randomly\n- Height shift range - shifts the height of the image by 10%\n- Width shift range - Shift width of image by +/- 10%","metadata":{}},{"cell_type":"code","source":"## Building model\n\nnn_model = Sequential([\n    Input(shape = (28,28,1)),\n    Conv2D(16,8,activation='relu',padding='same'),\n    MaxPooling2D(),\n    BatchNormalization(),\n    Dropout(0.4),\n    \n    Conv2D(32,6,activation='relu',padding='same'),\n    MaxPooling2D(),\n    BatchNormalization(),\n    Dropout(0.3),\n    \n    Flatten(),\n    \n    Dense(256,activation='relu'),\n    BatchNormalization(),\n    Dropout(0.2),\n    \n    Dense(128,activation='relu'),\n    BatchNormalization(),\n    Dropout(0.1),\n    \n    Dense(10,activation='softmax')   \n])\n\nnn_model.compile(optimizer='adam',\n                loss = 'sparse_categorical_crossentropy',\n                metrics = ['accuracy'])\n\nnn_model.summary()","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# early stopping\nearly_stopping = tf.keras.callbacks.EarlyStopping(patience=10)","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"history = nn_model.fit(train_generator,\n                       validation_data=validation_generator,\n                       epochs=100,\n                       batch_size=4096,\n                       callbacks=[early_stopping])","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def acc_loss_plot():\n    fig, ax = plt.subplots(1,2,figsize=(15,7))\n    ax[0].plot(history.history['accuracy'])\n    ax[0].plot(history.history['val_accuracy'])\n    ax[0].set_title('Accuracy')\n    ax[0].set_ylabel('Accuracy')\n    ax[0].set_xlabel('Epoch')\n    ax[0].legend(['train', 'validation'], loc='lower right')\n    ax[0].grid()\n    ax[1].plot(history.history['loss'])\n    ax[1].plot(history.history['val_loss'])\n    ax[1].set_title('Loss')\n    ax[1].set_ylabel('Loss')\n    ax[1].set_xlabel('Epoch')\n    ax[1].legend(['train', 'validation'], loc='upper right')\n    ax[1].grid()\n    plt.show()\n\nacc_loss_plot()\n","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]}]}