{"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"name":"python","version":"3.10.13","mimetype":"text/x-python","codemirror_mode":{"name":"ipython","version":3},"pygments_lexer":"ipython3","nbconvert_exporter":"python","file_extension":".py"},"kaggle":{"accelerator":"none","dataSources":[{"sourceId":3004,"databundleVersionId":861823,"sourceType":"competition"}],"dockerImageVersionId":30646,"isInternetEnabled":true,"language":"python","sourceType":"notebook","isGpuEnabled":false}},"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":"2024-02-20T23:31:31.177369Z","iopub.execute_input":"2024-02-20T23:31:31.178254Z","iopub.status.idle":"2024-02-20T23:31:31.187931Z","shell.execute_reply.started":"2024-02-20T23:31:31.178173Z","shell.execute_reply":"2024-02-20T23:31:31.186827Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Importing libraries","metadata":{}},{"cell_type":"code","source":"import pandas as pd\nimport seaborn as sns\nimport matplotlib.pyplot as plt\n\nimport tensorflow as tf\nfrom tensorflow.keras.models import Sequential\nfrom tensorflow.keras.layers import Conv2D, MaxPooling2D, Flatten, Dense\nfrom tensorflow.keras.models import Sequential\nfrom tensorflow.keras.optimizers import Adam\nfrom tensorflow.keras.callbacks import ModelCheckpoint,ReduceLROnPlateau,EarlyStopping\n\nfrom sklearn.model_selection import train_test_split","metadata":{"execution":{"iopub.status.busy":"2024-02-20T23:31:31.190011Z","iopub.execute_input":"2024-02-20T23:31:31.190738Z","iopub.status.idle":"2024-02-20T23:31:31.199913Z","shell.execute_reply.started":"2024-02-20T23:31:31.190699Z","shell.execute_reply":"2024-02-20T23:31:31.198923Z"},"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')\nsubmission = pd.read_csv('/kaggle/input/digit-recognizer/sample_submission.csv')","metadata":{"execution":{"iopub.status.busy":"2024-02-20T23:37:59.549550Z","iopub.execute_input":"2024-02-20T23:37:59.549978Z","iopub.status.idle":"2024-02-20T23:38:04.217252Z","shell.execute_reply.started":"2024-02-20T23:37:59.549944Z","shell.execute_reply":"2024-02-20T23:38:04.216198Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Understanding the data","metadata":{}},{"cell_type":"code","source":"train.shape, test.shape","metadata":{"execution":{"iopub.status.busy":"2024-02-20T23:31:36.189341Z","iopub.execute_input":"2024-02-20T23:31:36.189800Z","iopub.status.idle":"2024-02-20T23:31:36.197688Z","shell.execute_reply.started":"2024-02-20T23:31:36.189759Z","shell.execute_reply":"2024-02-20T23:31:36.196262Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train.head()","metadata":{"execution":{"iopub.status.busy":"2024-02-20T23:31:36.199307Z","iopub.execute_input":"2024-02-20T23:31:36.199703Z","iopub.status.idle":"2024-02-20T23:31:36.223446Z","shell.execute_reply.started":"2024-02-20T23:31:36.199673Z","shell.execute_reply":"2024-02-20T23:31:36.222056Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"test.head()","metadata":{"execution":{"iopub.status.busy":"2024-02-20T23:31:36.224878Z","iopub.execute_input":"2024-02-20T23:31:36.225218Z","iopub.status.idle":"2024-02-20T23:31:36.246386Z","shell.execute_reply.started":"2024-02-20T23:31:36.225190Z","shell.execute_reply":"2024-02-20T23:31:36.245059Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"X = train.drop('label', axis = 1)\ny = train['label']","metadata":{"execution":{"iopub.status.busy":"2024-02-20T23:31:36.248655Z","iopub.execute_input":"2024-02-20T23:31:36.249022Z","iopub.status.idle":"2024-02-20T23:31:36.338708Z","shell.execute_reply.started":"2024-02-20T23:31:36.248985Z","shell.execute_reply":"2024-02-20T23:31:36.337649Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Distribution of the target variable\nsns.countplot(data = train, x='label')\nplt.title(\"Distribution of target variable\")\nplt.show()","metadata":{"execution":{"iopub.status.busy":"2024-02-20T23:31:36.340080Z","iopub.execute_input":"2024-02-20T23:31:36.340454Z","iopub.status.idle":"2024-02-20T23:31:36.572765Z","shell.execute_reply.started":"2024-02-20T23:31:36.340419Z","shell.execute_reply":"2024-02-20T23:31:36.571603Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"We can observe that the target variable is more or less uniformly distributed across all the classes. So there is no class imbalance.","metadata":{}},{"cell_type":"markdown","source":"# Preprocessing","metadata":{}},{"cell_type":"code","source":"# Normalizing the data\nX = X/255.0\ntest = test/255.0","metadata":{"execution":{"iopub.status.busy":"2024-02-20T23:31:36.575176Z","iopub.execute_input":"2024-02-20T23:31:36.575574Z","iopub.status.idle":"2024-02-20T23:31:36.677725Z","shell.execute_reply.started":"2024-02-20T23:31:36.575542Z","shell.execute_reply":"2024-02-20T23:31:36.676859Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Reshaping the train and test data\nX = X.values.reshape(-1,28,28,1)\ntest = test.values.reshape(-1,28,28,1)\nX.shape, test.shape","metadata":{"execution":{"iopub.status.busy":"2024-02-20T23:31:36.681020Z","iopub.execute_input":"2024-02-20T23:31:36.681710Z","iopub.status.idle":"2024-02-20T23:31:36.690337Z","shell.execute_reply.started":"2024-02-20T23:31:36.681669Z","shell.execute_reply":"2024-02-20T23:31:36.689289Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Splitting the train data into train and validation sets\nX_train, X_val, y_train, y_val = train_test_split(X, y, test_size=0.2, random_state=42)\nprint(\"X_train shape: \", X_train.shape)\nprint(\"X_val shape: \", X_val.shape)","metadata":{"execution":{"iopub.status.busy":"2024-02-20T23:31:36.691576Z","iopub.execute_input":"2024-02-20T23:31:36.692336Z","iopub.status.idle":"2024-02-20T23:31:37.109585Z","shell.execute_reply.started":"2024-02-20T23:31:36.692299Z","shell.execute_reply":"2024-02-20T23:31:37.108401Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Building the model","metadata":{}},{"cell_type":"code","source":"EPOCHS = 10\nBATCH_SIZE = 64","metadata":{"execution":{"iopub.status.busy":"2024-02-20T23:31:37.111400Z","iopub.execute_input":"2024-02-20T23:31:37.111837Z","iopub.status.idle":"2024-02-20T23:31:37.117258Z","shell.execute_reply.started":"2024-02-20T23:31:37.111786Z","shell.execute_reply":"2024-02-20T23:31:37.116007Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Build the CNN Model\nmodel = Sequential([\n    Conv2D(32, (3,3), activation = 'relu', input_shape = (28,28,1)),\n    MaxPooling2D((2,2)),\n    Conv2D(64, (3,3), activation = 'relu'),\n    MaxPooling2D((2,2)),\n    Flatten(),\n    Dense(128, activation = 'relu'),\n    Dense(10, activation = 'softmax') # 10 output classes for 10 digits\n])","metadata":{"execution":{"iopub.status.busy":"2024-02-20T23:31:37.118861Z","iopub.execute_input":"2024-02-20T23:31:37.119428Z","iopub.status.idle":"2024-02-20T23:31:37.202754Z","shell.execute_reply.started":"2024-02-20T23:31:37.119398Z","shell.execute_reply":"2024-02-20T23:31:37.201432Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"model.compile(optimizer = Adam(),\n             loss = 'sparse_categorical_crossentropy',\n             metrics = ['accuracy'])","metadata":{"execution":{"iopub.status.busy":"2024-02-20T23:31:37.204243Z","iopub.execute_input":"2024-02-20T23:31:37.205074Z","iopub.status.idle":"2024-02-20T23:31:37.219542Z","shell.execute_reply.started":"2024-02-20T23:31:37.205031Z","shell.execute_reply":"2024-02-20T23:31:37.218197Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Reduce learning rate when a metric has stopped improving\nlr_reduction = ReduceLROnPlateau(monitor='val_loss',\n                                 patience=5,\n                                 verbose=2,\n                                 factor=.75)\n\n# If score doesn't improve during patience=10 epochs, stop learning\nestopping = EarlyStopping(monitor='val_loss',\n                          patience=10,\n                          verbose=2)\n","metadata":{"execution":{"iopub.status.busy":"2024-02-20T23:31:37.220762Z","iopub.execute_input":"2024-02-20T23:31:37.221098Z","iopub.status.idle":"2024-02-20T23:31:37.228197Z","shell.execute_reply.started":"2024-02-20T23:31:37.221069Z","shell.execute_reply":"2024-02-20T23:31:37.226634Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"history = model.fit(X_train, y_train, \n                    epochs=EPOCHS, \n                    batch_size=BATCH_SIZE,\n                    validation_data = (X_val, y_val),\n                    callbacks = [lr_reduction, estopping]\n                   )","metadata":{"execution":{"iopub.status.busy":"2024-02-20T23:31:37.229880Z","iopub.execute_input":"2024-02-20T23:31:37.230321Z","iopub.status.idle":"2024-02-20T23:34:00.468601Z","shell.execute_reply.started":"2024-02-20T23:31:37.230278Z","shell.execute_reply":"2024-02-20T23:34:00.467767Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Plot the loss and accuracy curves for training and validation \nplt.plot(history.history['val_loss'], color='b', label=\"validation loss\")\nplt.title(\"Validation Loss\")\nplt.xlabel(\"Number of Epochs\")\nplt.ylabel(\"Loss\")\nplt.legend()\nplt.show()","metadata":{"execution":{"iopub.status.busy":"2024-02-20T23:34:00.469847Z","iopub.execute_input":"2024-02-20T23:34:00.470640Z","iopub.status.idle":"2024-02-20T23:34:00.695337Z","shell.execute_reply.started":"2024-02-20T23:34:00.470609Z","shell.execute_reply":"2024-02-20T23:34:00.694223Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Making Predictions","metadata":{}},{"cell_type":"code","source":"predictions = model.predict(test)","metadata":{"execution":{"iopub.status.busy":"2024-02-20T23:34:00.698144Z","iopub.execute_input":"2024-02-20T23:34:00.698511Z","iopub.status.idle":"2024-02-20T23:34:05.770961Z","shell.execute_reply.started":"2024-02-20T23:34:00.698481Z","shell.execute_reply":"2024-02-20T23:34:05.769981Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"predictions = np.argmax(predictions,axis = 1)\npredictions = pd.Series(predictions,name = \"Label\")","metadata":{"execution":{"iopub.status.busy":"2024-02-20T23:34:20.434409Z","iopub.execute_input":"2024-02-20T23:34:20.434830Z","iopub.status.idle":"2024-02-20T23:34:20.441106Z","shell.execute_reply.started":"2024-02-20T23:34:20.434798Z","shell.execute_reply":"2024-02-20T23:34:20.439807Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"predictions.head()","metadata":{"execution":{"iopub.status.busy":"2024-02-20T23:34:33.347844Z","iopub.execute_input":"2024-02-20T23:34:33.348583Z","iopub.status.idle":"2024-02-20T23:34:33.355398Z","shell.execute_reply.started":"2024-02-20T23:34:33.348544Z","shell.execute_reply":"2024-02-20T23:34:33.354628Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Submission","metadata":{}},{"cell_type":"code","source":"submission['Label'] = predictions\nsubmission.head()","metadata":{"execution":{"iopub.status.busy":"2024-02-20T23:38:54.953942Z","iopub.execute_input":"2024-02-20T23:38:54.954360Z","iopub.status.idle":"2024-02-20T23:38:54.964808Z","shell.execute_reply.started":"2024-02-20T23:38:54.954329Z","shell.execute_reply":"2024-02-20T23:38:54.963587Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"submission.to_csv(\"submission.csv\", index = False)","metadata":{"execution":{"iopub.status.busy":"2024-02-20T23:39:23.818107Z","iopub.execute_input":"2024-02-20T23:39:23.818507Z","iopub.status.idle":"2024-02-20T23:39:23.863673Z","shell.execute_reply.started":"2024-02-20T23:39:23.818476Z","shell.execute_reply":"2024-02-20T23:39:23.862659Z"},"trusted":true},"execution_count":null,"outputs":[]}]}