{"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":"2023-04-24T18:32:47.737837Z","iopub.execute_input":"2023-04-24T18:32:47.738262Z","iopub.status.idle":"2023-04-24T18:32:47.746530Z","shell.execute_reply.started":"2023-04-24T18:32:47.738224Z","shell.execute_reply":"2023-04-24T18:32:47.745392Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport seaborn as sns","metadata":{"execution":{"iopub.status.busy":"2023-04-24T18:32:47.749109Z","iopub.execute_input":"2023-04-24T18:32:47.749523Z","iopub.status.idle":"2023-04-24T18:32:47.762707Z","shell.execute_reply.started":"2023-04-24T18:32:47.749465Z","shell.execute_reply":"2023-04-24T18:32:47.761434Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train = pd.read_csv(\"/kaggle/input/digit-recognizer/train.csv\")\ntest = pd.read_csv(\"/kaggle/input/digit-recognizer/test.csv\")","metadata":{"execution":{"iopub.status.busy":"2023-04-24T18:32:47.765159Z","iopub.execute_input":"2023-04-24T18:32:47.765670Z","iopub.status.idle":"2023-04-24T18:32:52.259548Z","shell.execute_reply.started":"2023-04-24T18:32:47.765612Z","shell.execute_reply":"2023-04-24T18:32:52.258299Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train","metadata":{"execution":{"iopub.status.busy":"2023-04-24T18:32:52.261003Z","iopub.execute_input":"2023-04-24T18:32:52.261435Z","iopub.status.idle":"2023-04-24T18:32:52.289923Z","shell.execute_reply.started":"2023-04-24T18:32:52.261397Z","shell.execute_reply":"2023-04-24T18:32:52.288564Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"y_train = train['label']\nx_train = train.iloc[:, 1:]\nx_train","metadata":{"execution":{"iopub.status.busy":"2023-04-24T18:32:52.293570Z","iopub.execute_input":"2023-04-24T18:32:52.294540Z","iopub.status.idle":"2023-04-24T18:32:52.322286Z","shell.execute_reply.started":"2023-04-24T18:32:52.294496Z","shell.execute_reply":"2023-04-24T18:32:52.320898Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"sns.countplot(x=y_train)\ny_train.value_counts()","metadata":{"execution":{"iopub.status.busy":"2023-04-24T18:32:52.324198Z","iopub.execute_input":"2023-04-24T18:32:52.324688Z","iopub.status.idle":"2023-04-24T18:32:52.587101Z","shell.execute_reply.started":"2023-04-24T18:32:52.324637Z","shell.execute_reply":"2023-04-24T18:32:52.585870Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"x_train = x_train / 255.0\ntest = test / 255.0","metadata":{"execution":{"iopub.status.busy":"2023-04-24T18:32:52.589149Z","iopub.execute_input":"2023-04-24T18:32:52.589520Z","iopub.status.idle":"2023-04-24T18:32:52.714550Z","shell.execute_reply.started":"2023-04-24T18:32:52.589484Z","shell.execute_reply":"2023-04-24T18:32:52.713433Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"x_train = x_train.values.reshape(-1, 28, 28, 1)\ntest = test.values.reshape(-1, 28, 28, 1)","metadata":{"execution":{"iopub.status.busy":"2023-04-24T18:32:52.715509Z","iopub.execute_input":"2023-04-24T18:32:52.715814Z","iopub.status.idle":"2023-04-24T18:32:52.723018Z","shell.execute_reply.started":"2023-04-24T18:32:52.715785Z","shell.execute_reply":"2023-04-24T18:32:52.722141Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from sklearn.model_selection import train_test_split\nfrom sklearn.preprocessing import OneHotEncoder","metadata":{"execution":{"iopub.status.busy":"2023-04-24T18:32:52.724227Z","iopub.execute_input":"2023-04-24T18:32:52.727660Z","iopub.status.idle":"2023-04-24T18:32:52.736209Z","shell.execute_reply.started":"2023-04-24T18:32:52.727602Z","shell.execute_reply":"2023-04-24T18:32:52.735144Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"encoder = OneHotEncoder(sparse=False)\n# encoder.fit_transform(y_train.reshape())\ny_train = np.asarray(encoder.fit_transform(y_train.to_numpy().reshape(-1, 1)))","metadata":{"execution":{"iopub.status.busy":"2023-04-24T18:32:52.738524Z","iopub.execute_input":"2023-04-24T18:32:52.739679Z","iopub.status.idle":"2023-04-24T18:32:52.754840Z","shell.execute_reply.started":"2023-04-24T18:32:52.739627Z","shell.execute_reply":"2023-04-24T18:32:52.753673Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"x_train_data, x_test_data, y_train_data, y_test_data = train_test_split(x_train, y_train, test_size=0.1, random_state=0)","metadata":{"execution":{"iopub.status.busy":"2023-04-24T18:32:52.759719Z","iopub.execute_input":"2023-04-24T18:32:52.760535Z","iopub.status.idle":"2023-04-24T18:32:53.184000Z","shell.execute_reply.started":"2023-04-24T18:32:52.760490Z","shell.execute_reply":"2023-04-24T18:32:53.182644Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"plt.imshow(x_train_data[10][:, :, 0])\nprint(np.argmax(y_train_data[10]))","metadata":{"execution":{"iopub.status.busy":"2023-04-24T18:32:53.185529Z","iopub.execute_input":"2023-04-24T18:32:53.186104Z","iopub.status.idle":"2023-04-24T18:32:53.422624Z","shell.execute_reply.started":"2023-04-24T18:32:53.186050Z","shell.execute_reply":"2023-04-24T18:32:53.421388Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from 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\n","metadata":{"execution":{"iopub.status.busy":"2023-04-24T18:32:53.424331Z","iopub.execute_input":"2023-04-24T18:32:53.424770Z","iopub.status.idle":"2023-04-24T18:32:53.433238Z","shell.execute_reply.started":"2023-04-24T18:32:53.424730Z","shell.execute_reply":"2023-04-24T18:32:53.431501Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"Convolutional layers are layers that contain filters or kernels that are applied to the input and there parameters are learned during training\n\nMax Pool layers is there to reduce the size of the input by choosing the maximum pixel in every pool to reduce the computation cost and avoid overfitting\n\nDropout layers sets some neurons to zero, which helps overfitting\n\nDense layer is a layer of neurons where each neurons is connected to all previous neurons","metadata":{}},{"cell_type":"code","source":"model = Sequential()\n\nmodel.add(Conv2D(filters = 32, kernel_size = (5,5),padding = 'Same', \n                 activation ='relu', input_shape = (28,28,1)))\nmodel.add(Conv2D(filters = 32, kernel_size = (5,5),padding = 'Same', \n                 activation ='relu'))\nmodel.add(MaxPool2D(pool_size=(2,2)))\nmodel.add(Dropout(0.25))\n\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.25))\n\n\nmodel.add(Flatten())\nmodel.add(Dense(256, activation = \"relu\"))\nmodel.add(Dropout(0.5))\nmodel.add(Dense(10, activation = \"softmax\"))","metadata":{"execution":{"iopub.status.busy":"2023-04-24T18:32:53.435482Z","iopub.execute_input":"2023-04-24T18:32:53.435933Z","iopub.status.idle":"2023-04-24T18:32:53.562714Z","shell.execute_reply.started":"2023-04-24T18:32:53.435896Z","shell.execute_reply":"2023-04-24T18:32:53.561578Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"optimizer = RMSprop(learning_rate=0.001, rho=0.9, epsilon=1e-08, decay=0.0)","metadata":{"execution":{"iopub.status.busy":"2023-04-24T18:32:53.564354Z","iopub.execute_input":"2023-04-24T18:32:53.564766Z","iopub.status.idle":"2023-04-24T18:32:53.570778Z","shell.execute_reply.started":"2023-04-24T18:32:53.564727Z","shell.execute_reply":"2023-04-24T18:32:53.569397Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"model.compile(optimizer = optimizer , loss = \"categorical_crossentropy\", metrics=[\"accuracy\"])","metadata":{"execution":{"iopub.status.busy":"2023-04-24T18:32:53.572125Z","iopub.execute_input":"2023-04-24T18:32:53.572480Z","iopub.status.idle":"2023-04-24T18:32:53.595629Z","shell.execute_reply.started":"2023-04-24T18:32:53.572447Z","shell.execute_reply":"2023-04-24T18:32:53.594626Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"!pip install visualkeras\nimport visualkeras\nvisualkeras.layered_view(model)","metadata":{"execution":{"iopub.status.busy":"2023-04-24T18:32:53.597223Z","iopub.execute_input":"2023-04-24T18:32:53.597665Z","iopub.status.idle":"2023-04-24T18:33:05.106336Z","shell.execute_reply.started":"2023-04-24T18:32:53.597617Z","shell.execute_reply":"2023-04-24T18:33:05.104818Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"learning_rate_reduction = ReduceLROnPlateau(monitor='val_acc', \n                                            patience=3, \n                                            verbose=1, \n                                            factor=0.5, \n                                            min_lr=0.00001)","metadata":{"execution":{"iopub.status.busy":"2023-04-24T18:33:05.107968Z","iopub.execute_input":"2023-04-24T18:33:05.108351Z","iopub.status.idle":"2023-04-24T18:33:05.116583Z","shell.execute_reply.started":"2023-04-24T18:33:05.108298Z","shell.execute_reply":"2023-04-24T18:33:05.115036Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"epochs = 1 # Turn epochs to 30 to get 0.9967 accuracy\nbatch_size = 86\n","metadata":{"execution":{"iopub.status.busy":"2023-04-24T18:33:05.118252Z","iopub.execute_input":"2023-04-24T18:33:05.118823Z","iopub.status.idle":"2023-04-24T18:33:05.132784Z","shell.execute_reply.started":"2023-04-24T18:33:05.118786Z","shell.execute_reply":"2023-04-24T18:33:05.131368Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"history = model.fit(x_train_data, y_train_data, batch_size = batch_size, epochs = epochs, \nvalidation_data = (x_test_data, y_test_data), verbose = 2)\n","metadata":{"execution":{"iopub.status.busy":"2023-04-24T18:33:05.134200Z","iopub.execute_input":"2023-04-24T18:33:05.134821Z","iopub.status.idle":"2023-04-24T18:36:28.332587Z","shell.execute_reply.started":"2023-04-24T18:33:05.134779Z","shell.execute_reply":"2023-04-24T18:36:28.331558Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from sklearn.metrics import confusion_matrix\nimport itertools\n\ndef plot_confusion_matrix(cm, classes,\n                          normalize=False,\n                          title='Confusion matrix',\n                          cmap=plt.cm.Blues):\n    \"\"\"\n    This function prints and plots the confusion matrix.\n    Normalization can be applied by setting `normalize=True`.\n    \"\"\"\n    plt.imshow(cm, interpolation='nearest', cmap=cmap)\n    plt.title(title)\n    plt.colorbar()\n    tick_marks = np.arange(len(classes))\n    plt.xticks(tick_marks, classes, rotation=45)\n    plt.yticks(tick_marks, classes)\n\n    if normalize:\n        cm = cm.astype('float') / cm.sum(axis=1)[:, np.newaxis]\n\n    thresh = cm.max() / 2.\n    for i, j in itertools.product(range(cm.shape[0]), range(cm.shape[1])):\n        plt.text(j, i, cm[i, j],\n                 horizontalalignment=\"center\",\n                 color=\"white\" if cm[i, j] > thresh else \"black\")\n\n    plt.tight_layout()\n    plt.ylabel('True label')\n    plt.xlabel('Predicted label')\n\n# Predict the values from the validation dataset\nY_pred = model.predict(x_test_data)\n# Convert predictions classes to one hot vectors \nY_pred_classes = np.argmax(Y_pred,axis = 1) \n# Convert validation observations to one hot vectors\nY_true = np.argmax(y_test_data,axis = 1) \n# compute the confusion matrix\nconfusion_mtx = confusion_matrix(Y_true, Y_pred_classes) \n# plot the confusion matrix\nplot_confusion_matrix(confusion_mtx, classes = range(10))","metadata":{"execution":{"iopub.status.busy":"2023-04-24T18:36:28.333886Z","iopub.execute_input":"2023-04-24T18:36:28.334221Z","iopub.status.idle":"2023-04-24T18:36:34.401319Z","shell.execute_reply.started":"2023-04-24T18:36:28.334189Z","shell.execute_reply":"2023-04-24T18:36:34.399791Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]}]}