{"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"name":"python","version":"3.10.12","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":30626,"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\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-09T16:14:21.881428Z","iopub.execute_input":"2024-02-09T16:14:21.881827Z","iopub.status.idle":"2024-02-09T16:14:21.929102Z","shell.execute_reply.started":"2024-02-09T16:14:21.881795Z","shell.execute_reply":"2024-02-09T16:14:21.927558Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# 1. Importing the Libraries","metadata":{}},{"cell_type":"code","source":"import pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\n%matplotlib inline\nimport seaborn as sns\nimport tensorflow as tf\nfrom tensorflow import keras\nfrom keras.models import Sequential\nfrom keras.layers import Dense,Dropout\nfrom keras.utils import to_categorical\nfrom keras.callbacks import EarlyStopping\nfrom keras import regularizers\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.neural_network import MLPClassifier\nfrom sklearn.metrics import confusion_matrix,classification_report,accuracy_score\n","metadata":{"execution":{"iopub.status.busy":"2024-02-09T16:41:46.387814Z","iopub.execute_input":"2024-02-09T16:41:46.388249Z","iopub.status.idle":"2024-02-09T16:41:46.398342Z","shell.execute_reply.started":"2024-02-09T16:41:46.388218Z","shell.execute_reply":"2024-02-09T16:41:46.397239Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"### Load Dataset","metadata":{}},{"cell_type":"code","source":"train = pd.read_csv('/kaggle/input/digit-recognizer/train.csv')\ntrain.head()","metadata":{"execution":{"iopub.status.busy":"2024-02-09T16:14:41.678319Z","iopub.execute_input":"2024-02-09T16:14:41.679080Z","iopub.status.idle":"2024-02-09T16:14:46.182829Z","shell.execute_reply.started":"2024-02-09T16:14:41.679040Z","shell.execute_reply":"2024-02-09T16:14:46.181571Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Let's see the shape of our Dataset\nprint(f'Shape of our Dataset :{train.shape}')","metadata":{"execution":{"iopub.status.busy":"2024-02-09T16:14:46.184533Z","iopub.execute_input":"2024-02-09T16:14:46.185049Z","iopub.status.idle":"2024-02-09T16:14:46.194343Z","shell.execute_reply.started":"2024-02-09T16:14:46.185004Z","shell.execute_reply":"2024-02-09T16:14:46.192267Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Let's try and visualize few pixels\nfeatures = [\"pixel{}\".format(pixel_num) for pixel_num in range(0, 784)]\nrow_to_examine = 2\nimage_data = np.reshape(train[features][row_to_examine:row_to_examine+1].to_numpy(), (28, 28))\n_ = plt.imshow(image_data, cmap=\"gray\")","metadata":{"execution":{"iopub.status.busy":"2024-02-09T16:14:46.197853Z","iopub.execute_input":"2024-02-09T16:14:46.198465Z","iopub.status.idle":"2024-02-09T16:14:46.780727Z","shell.execute_reply.started":"2024-02-09T16:14:46.198427Z","shell.execute_reply":"2024-02-09T16:14:46.779369Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# splitting our data into x and y\nx = train.drop('label',axis=1)\ny = train['label']","metadata":{"execution":{"iopub.status.busy":"2024-02-09T16:14:46.782074Z","iopub.execute_input":"2024-02-09T16:14:46.782501Z","iopub.status.idle":"2024-02-09T16:14:46.939921Z","shell.execute_reply.started":"2024-02-09T16:14:46.782468Z","shell.execute_reply":"2024-02-09T16:14:46.938360Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Splitting training data into train and test\nx_train,x_val,y_train,y_val = train_test_split(x,y,test_size=0.2,random_state=42)","metadata":{"execution":{"iopub.status.busy":"2024-02-09T16:14:46.941633Z","iopub.execute_input":"2024-02-09T16:14:46.942102Z","iopub.status.idle":"2024-02-09T16:14:47.248645Z","shell.execute_reply.started":"2024-02-09T16:14:46.942065Z","shell.execute_reply":"2024-02-09T16:14:47.247214Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"print(x_train.shape)\nprint(x_val.shape)\nprint(y_train.shape)\nprint(y_val.shape)","metadata":{"execution":{"iopub.status.busy":"2024-02-09T16:14:47.250308Z","iopub.execute_input":"2024-02-09T16:14:47.250708Z","iopub.status.idle":"2024-02-09T16:14:47.257316Z","shell.execute_reply.started":"2024-02-09T16:14:47.250673Z","shell.execute_reply":"2024-02-09T16:14:47.256170Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"y_train_transformed = to_categorical(y_train)\ny_val_transformed = to_categorical(y_val)","metadata":{"execution":{"iopub.status.busy":"2024-02-09T16:14:47.258998Z","iopub.execute_input":"2024-02-09T16:14:47.259456Z","iopub.status.idle":"2024-02-09T16:14:47.278693Z","shell.execute_reply.started":"2024-02-09T16:14:47.259419Z","shell.execute_reply":"2024-02-09T16:14:47.277485Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## Model Building","metadata":{}},{"cell_type":"code","source":"# Let's define our Model, I amm using a Sequential model with Dense Layers\n\nmodel = Sequential()\nmodel.add(Dense(512,activation='relu',input_dim=784)) # Layer 1\nmodel.add(Dropout(0.3))\nmodel.add(Dense(256,activation='relu')) # 2 layer\nmodel.add(Dropout(0.3))\nmodel.add(Dense(128,activation='relu')) # 3 layer\nmodel.add(Dropout(0.3))\nmodel.add(Dense(64,activation='relu')) # 4 layer\nmodel.add(Dropout(0.3))\nmodel.add(Dense(10,activation='softmax'))\nmodel.summary()","metadata":{"execution":{"iopub.status.busy":"2024-02-09T17:13:28.190068Z","iopub.execute_input":"2024-02-09T17:13:28.190539Z","iopub.status.idle":"2024-02-09T17:13:28.333224Z","shell.execute_reply.started":"2024-02-09T17:13:28.190504Z","shell.execute_reply":"2024-02-09T17:13:28.331757Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"model.compile(\n    optimizer='adam',\n    loss='categorical_crossentropy',\n    metrics=['accuracy'],\n)","metadata":{"execution":{"iopub.status.busy":"2024-02-09T17:13:34.020737Z","iopub.execute_input":"2024-02-09T17:13:34.021195Z","iopub.status.idle":"2024-02-09T17:13:34.036527Z","shell.execute_reply.started":"2024-02-09T17:13:34.021158Z","shell.execute_reply":"2024-02-09T17:13:34.034979Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"\nearly_stopping = EarlyStopping(\n    patience=10,\n    min_delta=0.001,\n    restore_best_weights=True,\n)","metadata":{"execution":{"iopub.status.busy":"2024-02-09T17:13:37.249712Z","iopub.execute_input":"2024-02-09T17:13:37.250678Z","iopub.status.idle":"2024-02-09T17:13:37.255224Z","shell.execute_reply.started":"2024-02-09T17:13:37.250640Z","shell.execute_reply":"2024-02-09T17:13:37.254341Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"history = model.fit(\n    x_train, y_train_transformed,\n    validation_data=(x_val, y_val_transformed),\n    batch_size=512,\n    epochs=500,\n    callbacks=[early_stopping],\n    verbose=1,\n)","metadata":{"execution":{"iopub.status.busy":"2024-02-09T17:13:40.437138Z","iopub.execute_input":"2024-02-09T17:13:40.437560Z","iopub.status.idle":"2024-02-09T17:15:23.863517Z","shell.execute_reply.started":"2024-02-09T17:13:40.437528Z","shell.execute_reply":"2024-02-09T17:15:23.862092Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"history_df=pd.DataFrame(history.history)\nfig, axes = plt.subplots(1, 2, figsize=(15, 7))\n\n# Plot loss and validation loss on the first subplot\nhistory_df[['loss', 'val_loss']].plot(ax=axes[0])\naxes[0].set_title('Loss and Validation Loss')\naxes[0].set_xlabel('Epoch')\naxes[0].set_ylabel('Loss')\n\n# Plot accuracy and validation binary accuracy on the second subplot\nhistory_df[['accuracy', 'val_accuracy']].plot(ax=axes[1])\naxes[1].set_title('Accuracy and Validation Accuracy')\naxes[1].set_xlabel('Epoch')\naxes[1].set_ylabel('Accuracy')\nplt.tight_layout()\nplt.show()\n\nprint((\"Best Validation Loss: {:0.4f}\" +\\\n      \"\\nBest Validation Accuracy: {:0.4f}\")\\\n      .format(history_df['val_loss'].min(), \n              history_df['val_accuracy'].max()))","metadata":{"execution":{"iopub.status.busy":"2024-02-09T17:40:25.155193Z","iopub.execute_input":"2024-02-09T17:40:25.155608Z","iopub.status.idle":"2024-02-09T17:40:25.946613Z","shell.execute_reply.started":"2024-02-09T17:40:25.155577Z","shell.execute_reply":"2024-02-09T17:40:25.945505Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train_preds_dense = model.predict(x_train)\nval_preds_dense = model.predict(x_val)","metadata":{"execution":{"iopub.status.busy":"2024-02-09T17:40:45.263021Z","iopub.execute_input":"2024-02-09T17:40:45.263496Z","iopub.status.idle":"2024-02-09T17:40:52.020833Z","shell.execute_reply.started":"2024-02-09T17:40:45.263460Z","shell.execute_reply":"2024-02-09T17:40:52.019209Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train_preds_dense[1]","metadata":{"execution":{"iopub.status.busy":"2024-02-09T17:40:55.569326Z","iopub.execute_input":"2024-02-09T17:40:55.569787Z","iopub.status.idle":"2024-02-09T17:40:55.578756Z","shell.execute_reply.started":"2024-02-09T17:40:55.569752Z","shell.execute_reply":"2024-02-09T17:40:55.577339Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"y_train_transformed[1]","metadata":{"execution":{"iopub.status.busy":"2024-02-09T17:40:58.592232Z","iopub.execute_input":"2024-02-09T17:40:58.592734Z","iopub.status.idle":"2024-02-09T17:40:58.602440Z","shell.execute_reply.started":"2024-02-09T17:40:58.592696Z","shell.execute_reply":"2024-02-09T17:40:58.601284Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train_preds_dense_class = np.argmax(train_preds_dense,axis=1)\nval_preds_dense_class = np.argmax(val_preds_dense,axis=1)","metadata":{"execution":{"iopub.status.busy":"2024-02-09T17:41:02.137809Z","iopub.execute_input":"2024-02-09T17:41:02.138300Z","iopub.status.idle":"2024-02-09T17:41:02.145809Z","shell.execute_reply.started":"2024-02-09T17:41:02.138263Z","shell.execute_reply":"2024-02-09T17:41:02.144069Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Let's see the confusion matrix\nconfusion_matrix(y_train,train_preds_dense_class)","metadata":{"execution":{"iopub.status.busy":"2024-02-09T17:41:04.982184Z","iopub.execute_input":"2024-02-09T17:41:04.982702Z","iopub.status.idle":"2024-02-09T17:41:05.004075Z","shell.execute_reply.started":"2024-02-09T17:41:04.982664Z","shell.execute_reply":"2024-02-09T17:41:05.001974Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"confusion_matrix(y_val,val_preds_dense_class)","metadata":{"execution":{"iopub.status.busy":"2024-02-09T17:41:08.801897Z","iopub.execute_input":"2024-02-09T17:41:08.802406Z","iopub.status.idle":"2024-02-09T17:41:08.817713Z","shell.execute_reply.started":"2024-02-09T17:41:08.802368Z","shell.execute_reply":"2024-02-09T17:41:08.816087Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"print(classification_report(y_train,train_preds_dense_class))","metadata":{"execution":{"iopub.status.busy":"2024-02-09T17:41:12.355598Z","iopub.execute_input":"2024-02-09T17:41:12.356090Z","iopub.status.idle":"2024-02-09T17:41:12.479245Z","shell.execute_reply.started":"2024-02-09T17:41:12.356052Z","shell.execute_reply":"2024-02-09T17:41:12.477618Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"print(classification_report(y_val,val_preds_dense_class))","metadata":{"execution":{"iopub.status.busy":"2024-02-09T17:41:17.058751Z","iopub.execute_input":"2024-02-09T17:41:17.059396Z","iopub.status.idle":"2024-02-09T17:41:17.098365Z","shell.execute_reply.started":"2024-02-09T17:41:17.059349Z","shell.execute_reply":"2024-02-09T17:41:17.096673Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"### Real Test Dataset","metadata":{}},{"cell_type":"code","source":"# Let's look at our real test dataset\ndf_test = pd.read_csv('/kaggle/input/digit-recognizer/test.csv')\ndf_test.head()","metadata":{"execution":{"iopub.status.busy":"2024-02-09T17:41:27.588722Z","iopub.execute_input":"2024-02-09T17:41:27.589153Z","iopub.status.idle":"2024-02-09T17:41:30.023159Z","shell.execute_reply.started":"2024-02-09T17:41:27.589097Z","shell.execute_reply":"2024-02-09T17:41:30.021881Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"predictions = model.predict(df_test)","metadata":{"execution":{"iopub.status.busy":"2024-02-09T17:41:30.026326Z","iopub.execute_input":"2024-02-09T17:41:30.026822Z","iopub.status.idle":"2024-02-09T17:41:33.579217Z","shell.execute_reply.started":"2024-02-09T17:41:30.026778Z","shell.execute_reply":"2024-02-09T17:41:33.577849Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"predictions[1]","metadata":{"execution":{"iopub.status.busy":"2024-02-09T17:41:33.580637Z","iopub.execute_input":"2024-02-09T17:41:33.580982Z","iopub.status.idle":"2024-02-09T17:41:33.589584Z","shell.execute_reply.started":"2024-02-09T17:41:33.580954Z","shell.execute_reply":"2024-02-09T17:41:33.588203Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"predictions_class = np.argmax(predictions,axis=1)","metadata":{"execution":{"iopub.status.busy":"2024-02-09T17:41:33.591227Z","iopub.execute_input":"2024-02-09T17:41:33.592380Z","iopub.status.idle":"2024-02-09T17:41:33.602968Z","shell.execute_reply.started":"2024-02-09T17:41:33.592342Z","shell.execute_reply":"2024-02-09T17:41:33.601436Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"sub = pd.read_csv('/kaggle/input/digit-recognizer/sample_submission.csv')\nsub.head()","metadata":{"execution":{"iopub.status.busy":"2024-02-09T17:41:33.607324Z","iopub.execute_input":"2024-02-09T17:41:33.608042Z","iopub.status.idle":"2024-02-09T17:41:33.634426Z","shell.execute_reply.started":"2024-02-09T17:41:33.607998Z","shell.execute_reply":"2024-02-09T17:41:33.633117Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"id = sub['ImageId']","metadata":{"execution":{"iopub.status.busy":"2024-02-09T17:41:33.635768Z","iopub.execute_input":"2024-02-09T17:41:33.636102Z","iopub.status.idle":"2024-02-09T17:41:33.642058Z","shell.execute_reply.started":"2024-02-09T17:41:33.636073Z","shell.execute_reply":"2024-02-09T17:41:33.640686Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"submission_df = pd.DataFrame({\n    'ImageId': id,\n    'Label':predictions_class\n})","metadata":{"execution":{"iopub.status.busy":"2024-02-09T17:41:33.643789Z","iopub.execute_input":"2024-02-09T17:41:33.644283Z","iopub.status.idle":"2024-02-09T17:41:33.657749Z","shell.execute_reply.started":"2024-02-09T17:41:33.644240Z","shell.execute_reply":"2024-02-09T17:41:33.656470Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"submission_df.head()","metadata":{"execution":{"iopub.status.busy":"2024-02-09T17:41:33.659539Z","iopub.execute_input":"2024-02-09T17:41:33.660440Z","iopub.status.idle":"2024-02-09T17:41:33.677767Z","shell.execute_reply.started":"2024-02-09T17:41:33.660393Z","shell.execute_reply":"2024-02-09T17:41:33.676630Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"submission_df.to_csv('submission.csv', index=False)","metadata":{"execution":{"iopub.status.busy":"2024-02-09T17:41:33.679385Z","iopub.execute_input":"2024-02-09T17:41:33.682037Z","iopub.status.idle":"2024-02-09T17:41:33.761619Z","shell.execute_reply.started":"2024-02-09T17:41:33.681992Z","shell.execute_reply":"2024-02-09T17:41:33.760517Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"**Thankyou**","metadata":{}},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]}]}