{"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","execution":{"iopub.status.busy":"2022-01-15T12:21:06.771085Z","iopub.execute_input":"2022-01-15T12:21:06.771604Z","iopub.status.idle":"2022-01-15T12:21:06.802101Z","shell.execute_reply.started":"2022-01-15T12:21:06.771495Z","shell.execute_reply":"2022-01-15T12:21:06.801088Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import numpy as np # linear algebra\nimport pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)\nimport seaborn as sns\nimport matplotlib.pyplot as plt\nfrom sklearn.metrics import accuracy_score\n\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.preprocessing import LabelEncoder\n\nfrom tensorflow.keras.models import Sequential\nfrom tensorflow.keras.layers import Dense, InputLayer, Flatten, BatchNormalization, Dropout\nfrom tensorflow.keras.layers import Conv2D, MaxPooling2D\nfrom tensorflow.keras.utils import to_categorical\nfrom tensorflow.keras.regularizers import l2","metadata":{"execution":{"iopub.status.busy":"2022-01-15T12:47:59.322078Z","iopub.execute_input":"2022-01-15T12:47:59.322500Z","iopub.status.idle":"2022-01-15T12:48:06.705970Z","shell.execute_reply.started":"2022-01-15T12:47:59.322397Z","shell.execute_reply":"2022-01-15T12:48:06.705004Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df_train = pd.read_csv(\"/kaggle/input/digit-recognizer/train.csv\")\ndf_test = pd.read_csv(\"/kaggle/input/digit-recognizer/test.csv\")","metadata":{"execution":{"iopub.status.busy":"2022-01-15T12:48:06.707857Z","iopub.execute_input":"2022-01-15T12:48:06.708223Z","iopub.status.idle":"2022-01-15T12:48:13.336650Z","shell.execute_reply.started":"2022-01-15T12:48:06.708189Z","shell.execute_reply":"2022-01-15T12:48:13.335733Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df_train.head()","metadata":{"execution":{"iopub.status.busy":"2022-01-15T12:48:14.950452Z","iopub.execute_input":"2022-01-15T12:48:14.951142Z","iopub.status.idle":"2022-01-15T12:48:14.982828Z","shell.execute_reply.started":"2022-01-15T12:48:14.951104Z","shell.execute_reply":"2022-01-15T12:48:14.981873Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df_train.label.unique()","metadata":{"execution":{"iopub.status.busy":"2022-01-15T12:48:16.255752Z","iopub.execute_input":"2022-01-15T12:48:16.256755Z","iopub.status.idle":"2022-01-15T12:48:16.269778Z","shell.execute_reply.started":"2022-01-15T12:48:16.256702Z","shell.execute_reply":"2022-01-15T12:48:16.268618Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from matplotlib.pyplot import imshow\n\nwidth=5\nheight=5\nrows = 3\ncols = 3\naxes=[]\n\nfig=plt.figure()\nfig.set_size_inches(6,8)\n\nfor i in range(rows*cols):\n    sample=np.reshape(df_train[df_train.columns[1:]].iloc[i].values/255,(28,28))\n    axes.append(fig.add_subplot(rows,cols,i+1))\n    plt.title(\"Labeled class : {}\".format(df_train[\"label\"].iloc[i]))\n    plt.imshow(sample, 'gray')\nfig.tight_layout()\nplt.show()","metadata":{"execution":{"iopub.status.busy":"2022-01-15T12:48:17.777415Z","iopub.execute_input":"2022-01-15T12:48:17.778020Z","iopub.status.idle":"2022-01-15T12:48:19.855837Z","shell.execute_reply.started":"2022-01-15T12:48:17.777983Z","shell.execute_reply":"2022-01-15T12:48:19.854836Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"#Explanatory Data Analysis\n\nplt.figure(figsize=(8,6))\nax = sns.countplot(x='label',data=df_train)\n\nplt.title(\"Label Distribution\")\ntotal= len(df_train.label)\nfor p in ax.patches:\n    percentage = f'{100 * p.get_height() / total:.1f}%\\n'\n    x = p.get_x() + p.get_width() / 2\n    y = p.get_height()\n    ax.annotate(percentage, (x, y), ha='center', va='center')","metadata":{"execution":{"iopub.status.busy":"2022-01-15T12:48:21.929510Z","iopub.execute_input":"2022-01-15T12:48:21.930136Z","iopub.status.idle":"2022-01-15T12:48:22.274426Z","shell.execute_reply.started":"2022-01-15T12:48:21.930103Z","shell.execute_reply":"2022-01-15T12:48:22.273313Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# separate target values from df_train\ntargets = df_train.label\nfeatures = df_train.drop(\"label\",axis=1)","metadata":{"execution":{"iopub.status.busy":"2022-01-15T12:48:23.921653Z","iopub.execute_input":"2022-01-15T12:48:23.922536Z","iopub.status.idle":"2022-01-15T12:48:24.028643Z","shell.execute_reply.started":"2022-01-15T12:48:23.922498Z","shell.execute_reply":"2022-01-15T12:48:24.027505Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"**PreProcessing**","metadata":{}},{"cell_type":"code","source":"features = features/255\ndf_test = df_test/255","metadata":{"execution":{"iopub.status.busy":"2022-01-15T12:48:26.827215Z","iopub.execute_input":"2022-01-15T12:48:26.827516Z","iopub.status.idle":"2022-01-15T12:48:27.051307Z","shell.execute_reply.started":"2022-01-15T12:48:26.827484Z","shell.execute_reply":"2022-01-15T12:48:27.050254Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"X_train , X_val , Y_train , Y_val = train_test_split(features , targets , test_size=0.2 ,random_state = 1)","metadata":{"execution":{"iopub.status.busy":"2022-01-15T12:48:28.436237Z","iopub.execute_input":"2022-01-15T12:48:28.436557Z","iopub.status.idle":"2022-01-15T12:48:28.689687Z","shell.execute_reply.started":"2022-01-15T12:48:28.436527Z","shell.execute_reply":"2022-01-15T12:48:28.688294Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from tensorflow.keras.utils import to_categorical\n\ny_train = to_categorical(Y_train,10)\ny_val =  to_categorical(Y_val,10)\n\nprint(y_train[2])\nprint(len(y_train))","metadata":{"execution":{"iopub.status.busy":"2022-01-15T12:54:05.045336Z","iopub.execute_input":"2022-01-15T12:54:05.045694Z","iopub.status.idle":"2022-01-15T12:54:05.057174Z","shell.execute_reply.started":"2022-01-15T12:54:05.045645Z","shell.execute_reply":"2022-01-15T12:54:05.055621Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"X_train = X_train.values.reshape(len(X_train),28,28,1)\nX_val = X_val.values.reshape(len(X_val),28,28,1)\n\ndf_test = df_test.values.reshape(len(df_test),28,28,1)\n\ninput_shape = (28,28,1)","metadata":{"execution":{"iopub.status.busy":"2022-01-15T12:52:23.946108Z","iopub.execute_input":"2022-01-15T12:52:23.947015Z","iopub.status.idle":"2022-01-15T12:52:23.971405Z","shell.execute_reply.started":"2022-01-15T12:52:23.946966Z","shell.execute_reply":"2022-01-15T12:52:23.969824Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import tensorflow as tf\n\nmodel = tf.keras.Sequential()\n\n#Conv1\nmodel.add(tf.keras.layers.Conv2D(32 , 3 , input_shape=input_shape , activation = 'relu' , padding = 'same') )\nmodel.add(tf.keras.layers.MaxPool2D(2))\n\n#Conv2\nmodel.add(tf.keras.layers.Conv2D(64 , 3  , activation = 'relu' , padding = 'same') )\nmodel.add(tf.keras.layers.MaxPool2D(2))\n\n#Conv3\nmodel.add(tf.keras.layers.Conv2D(128 , 3  , activation = 'relu' , padding = 'same') )\nmodel.add(tf.keras.layers.MaxPool2D(2))\nmodel.add(tf.keras.layers.Dropout(0.3))\n\n#Conv4\nmodel.add(tf.keras.layers.Conv2D(128 , 3  , activation = 'relu' , padding = 'same') )\nmodel.add(tf.keras.layers.MaxPool2D(2))\nmodel.add(tf.keras.layers.Dropout(0.25))\n\n\nmodel.add(tf.keras.layers.Flatten())\nmodel.add(tf.keras.layers.Dense(256 , activation = 'relu'))\nmodel.add(tf.keras.layers.Dropout(0.25))\n\nmodel.add(tf.keras.layers.Dense(10 , activation = 'softmax'))\n\n\nmodel.summary()","metadata":{"execution":{"iopub.status.busy":"2022-01-15T12:48:34.407719Z","iopub.execute_input":"2022-01-15T12:48:34.408526Z","iopub.status.idle":"2022-01-15T12:48:37.369765Z","shell.execute_reply.started":"2022-01-15T12:48:34.408462Z","shell.execute_reply":"2022-01-15T12:48:37.368850Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"#Take a look at any layer in the model by changing layer_name below.\n\nlayer_name = 'conv2d_2'\nlayer_dict = {layer.name : layer for layer in model.layers}\nmodelslice = tf.keras.Model(model.inputs, layer_dict[layer_name].output)\nimage = np.reshape(df_train[df_train.columns[1:]].iloc[2].values/255,(28,28))\nimage = np.expand_dims(image, axis=0)\nfeature_maps = modelslice.predict(image)\nplt.figure(figsize=(20, 10))\n\nfor i in range(16): # This is itterating through the 16 filter of the convolution!\n    plt.subplot(4,8,i+1)\n    plt.axis('off')\n    plt.imshow(feature_maps[0, :, :, i-1], cmap='inferno')\n    plt.tight_layout(pad=0.0)","metadata":{"execution":{"iopub.status.busy":"2022-01-15T12:49:19.769466Z","iopub.execute_input":"2022-01-15T12:49:19.770390Z","iopub.status.idle":"2022-01-15T12:49:21.643670Z","shell.execute_reply.started":"2022-01-15T12:49:19.770351Z","shell.execute_reply":"2022-01-15T12:49:21.642653Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# COMPILING\nmodel.compile(loss = 'categorical_crossentropy' , optimizer = 'adamax' , metrics=['accuracy'])\n\nmodel.summary()","metadata":{"execution":{"iopub.status.busy":"2022-01-15T12:55:55.845138Z","iopub.execute_input":"2022-01-15T12:55:55.845446Z","iopub.status.idle":"2022-01-15T12:55:55.871658Z","shell.execute_reply.started":"2022-01-15T12:55:55.845406Z","shell.execute_reply":"2022-01-15T12:55:55.870641Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"history = model.fit(X_train , y_train , batch_size = 42 , epochs = 30 , validation_data = (X_val,y_val))","metadata":{"execution":{"iopub.status.busy":"2022-01-15T12:56:01.414375Z","iopub.execute_input":"2022-01-15T12:56:01.414859Z","iopub.status.idle":"2022-01-15T12:58:24.344637Z","shell.execute_reply.started":"2022-01-15T12:56:01.414823Z","shell.execute_reply":"2022-01-15T12:58:24.343291Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"fig = plt.figure(figsize=(20,12))\n\nplt.subplot(211)\nplt.style.use('dark_background')\nplt.plot(history.history['accuracy'], color='c', label=\"Training accuracy\")\nplt.plot(history.history['val_accuracy'], color='r', label=\"Validation accuracy\")\n\nplt.ylabel('Accuracy')\nplt.xlabel('Epochs')\nplt.legend(loc='best')\n\nplt.subplot(212)\nplt.style.use('dark_background')\nplt.plot(history.history['loss'], color='m', label=\"Training loss\")\nplt.plot(history.history['val_loss'], color='r', label=\"Validation loss\")\nplt.ylabel('Loss')\nplt.legend(loc='best')","metadata":{"execution":{"iopub.status.busy":"2022-01-15T12:58:40.779897Z","iopub.execute_input":"2022-01-15T12:58:40.780197Z","iopub.status.idle":"2022-01-15T12:58:41.325733Z","shell.execute_reply.started":"2022-01-15T12:58:40.780165Z","shell.execute_reply":"2022-01-15T12:58:41.324743Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"predictions = model.predict(df_test)\npredictions = [np.argmax(a) for a in predictions]","metadata":{"execution":{"iopub.status.busy":"2022-01-15T12:58:48.729620Z","iopub.execute_input":"2022-01-15T12:58:48.729912Z","iopub.status.idle":"2022-01-15T12:58:51.951167Z","shell.execute_reply.started":"2022-01-15T12:58:48.729881Z","shell.execute_reply":"2022-01-15T12:58:51.950193Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"output = pd.read_csv(\"../input/digit-recognizer/sample_submission.csv\")\noutput['Label'] = predictions\noutput.to_csv('submission.csv',index=False)","metadata":{"execution":{"iopub.status.busy":"2022-01-15T12:58:53.495406Z","iopub.execute_input":"2022-01-15T12:58:53.495718Z","iopub.status.idle":"2022-01-15T12:58:53.591634Z","shell.execute_reply.started":"2022-01-15T12:58:53.495687Z","shell.execute_reply":"2022-01-15T12:58:53.590799Z"},"trusted":true},"execution_count":null,"outputs":[]}]}