{"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":"nvidiaTeslaT4","dataSources":[{"sourceId":3004,"databundleVersionId":861823,"sourceType":"competition"}],"dockerImageVersionId":30626,"isInternetEnabled":true,"language":"python","sourceType":"notebook","isGpuEnabled":true}},"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-03-09T00:04:45.058359Z","iopub.execute_input":"2024-03-09T00:04:45.059086Z","iopub.status.idle":"2024-03-09T00:04:45.065374Z","shell.execute_reply.started":"2024-03-09T00:04:45.059052Z","shell.execute_reply":"2024-03-09T00:04:45.064455Z"},"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 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 sklearn.model_selection import train_test_split\nfrom sklearn.metrics import confusion_matrix,classification_report,accuracy_score\n","metadata":{"execution":{"iopub.status.busy":"2024-03-09T00:04:45.070117Z","iopub.execute_input":"2024-03-09T00:04:45.070535Z","iopub.status.idle":"2024-03-09T00:04:45.079384Z","shell.execute_reply.started":"2024-03-09T00:04:45.070435Z","shell.execute_reply":"2024-03-09T00:04:45.078269Z"},"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-03-09T00:04:45.081026Z","iopub.execute_input":"2024-03-09T00:04:45.081354Z","iopub.status.idle":"2024-03-09T00:04:47.793581Z","shell.execute_reply.started":"2024-03-09T00:04:45.081324Z","shell.execute_reply":"2024-03-09T00:04:47.792496Z"},"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-03-09T00:04:47.795308Z","iopub.execute_input":"2024-03-09T00:04:47.795638Z","iopub.status.idle":"2024-03-09T00:04:47.800376Z","shell.execute_reply.started":"2024-03-09T00:04:47.795609Z","shell.execute_reply":"2024-03-09T00:04:47.799406Z"},"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-03-09T00:04:47.801805Z","iopub.execute_input":"2024-03-09T00:04:47.802156Z","iopub.status.idle":"2024-03-09T00:04:48.083667Z","shell.execute_reply.started":"2024-03-09T00:04:47.802129Z","shell.execute_reply":"2024-03-09T00:04:48.082709Z"},"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-03-09T00:04:48.086556Z","iopub.execute_input":"2024-03-09T00:04:48.087057Z","iopub.status.idle":"2024-03-09T00:04:48.172275Z","shell.execute_reply.started":"2024-03-09T00:04:48.086998Z","shell.execute_reply":"2024-03-09T00:04:48.171403Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Splitting training data into train and test\nx_train,x_test,y_train,y_test=train_test_split(x,y,test_size=0.2,random_state=123)","metadata":{"execution":{"iopub.status.busy":"2024-03-09T00:04:48.173396Z","iopub.execute_input":"2024-03-09T00:04:48.173705Z","iopub.status.idle":"2024-03-09T00:04:48.389084Z","shell.execute_reply.started":"2024-03-09T00:04:48.173678Z","shell.execute_reply":"2024-03-09T00:04:48.388245Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"print(x_train.shape)\nprint(x_test.shape)\nprint(y_train.shape)\nprint(y_test.shape)","metadata":{"execution":{"iopub.status.busy":"2024-03-09T00:04:48.390227Z","iopub.execute_input":"2024-03-09T00:04:48.390547Z","iopub.status.idle":"2024-03-09T00:04:48.396247Z","shell.execute_reply.started":"2024-03-09T00:04:48.390518Z","shell.execute_reply":"2024-03-09T00:04:48.395160Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"y_train = to_categorical(y_train)\ny_test = to_categorical(y_test)","metadata":{"execution":{"iopub.status.busy":"2024-03-09T00:04:48.397712Z","iopub.execute_input":"2024-03-09T00:04:48.398646Z","iopub.status.idle":"2024-03-09T00:04:48.407451Z","shell.execute_reply.started":"2024-03-09T00:04:48.398607Z","shell.execute_reply":"2024-03-09T00:04:48.406651Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"x_train = x_train.to_numpy()\nx_test = x_test.to_numpy()\nX_train = x_train.reshape(33600,28,28,1)\nX_test = x_test.reshape(8400,28,28,1)","metadata":{"execution":{"iopub.status.busy":"2024-03-09T00:04:48.408714Z","iopub.execute_input":"2024-03-09T00:04:48.409095Z","iopub.status.idle":"2024-03-09T00:04:48.419394Z","shell.execute_reply.started":"2024-03-09T00:04:48.409066Z","shell.execute_reply":"2024-03-09T00:04:48.418512Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## Model Building","metadata":{}},{"cell_type":"code","source":"from keras.layers import Conv2D,MaxPooling2D,Flatten","metadata":{"execution":{"iopub.status.busy":"2024-03-09T00:04:48.420553Z","iopub.execute_input":"2024-03-09T00:04:48.420866Z","iopub.status.idle":"2024-03-09T00:04:48.427936Z","shell.execute_reply.started":"2024-03-09T00:04:48.420840Z","shell.execute_reply":"2024-03-09T00:04:48.427171Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Let's define our Model, I amm using a Sequential model with Dense Layers\n\nmodel = Sequential()\n# Block 1\nmodel.add(Conv2D(filters = 512 , kernel_size = 3,padding='same', activation='relu',input_shape= (28,28,1),name='firstConv2D'))\nmodel.add(MaxPooling2D(pool_size=(2,2),strides=(2,2)))\nmodel.add(Dropout(0.25))\n\n# Block 2\nmodel.add(Conv2D(filters=256,kernel_size=3,padding = 'same', activation = 'relu'))\nmodel.add(MaxPooling2D(pool_size=(2,2),strides=(2,2)))\nmodel.add(Dropout(0.3))\n\n\n\n\n# Flatten Layer\nmodel.add(Flatten())\n\n# Dense Model\n\nmodel.add(Dense(512,activation = 'relu'))\nmodel.add(Dense(256,activation = 'relu'))\nmodel.add(Dense(128,activation = 'relu'))\nmodel.add(Dense(10,activation='softmax'))\nmodel.summary()","metadata":{"execution":{"iopub.status.busy":"2024-03-09T00:04:48.431543Z","iopub.execute_input":"2024-03-09T00:04:48.431819Z","iopub.status.idle":"2024-03-09T00:04:48.553892Z","shell.execute_reply.started":"2024-03-09T00:04:48.431796Z","shell.execute_reply":"2024-03-09T00:04:48.553053Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"model.compile(\n    optimizer='adam',\n    loss='categorical_crossentropy',\n    metrics=['accuracy'],\n     run_eagerly = True,\n)","metadata":{"execution":{"iopub.status.busy":"2024-03-09T00:04:48.554915Z","iopub.execute_input":"2024-03-09T00:04:48.555197Z","iopub.status.idle":"2024-03-09T00:04:48.565826Z","shell.execute_reply.started":"2024-03-09T00:04:48.555173Z","shell.execute_reply":"2024-03-09T00:04:48.564846Z"},"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-03-09T00:04:48.567236Z","iopub.execute_input":"2024-03-09T00:04:48.567903Z","iopub.status.idle":"2024-03-09T00:04:48.572340Z","shell.execute_reply.started":"2024-03-09T00:04:48.567867Z","shell.execute_reply":"2024-03-09T00:04:48.571425Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"history = model.fit(\n    X_train, y_train,\n    validation_data=(X_test, y_test),\n    batch_size=256,\n    epochs = 70,\n    callbacks=[early_stopping],\n    verbose=1,\n)","metadata":{"execution":{"iopub.status.busy":"2024-03-09T00:04:48.573750Z","iopub.execute_input":"2024-03-09T00:04:48.574154Z","iopub.status.idle":"2024-03-09T00:08:46.381699Z","shell.execute_reply.started":"2024-03-09T00:04:48.574118Z","shell.execute_reply":"2024-03-09T00:08:46.380744Z"},"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-03-09T00:08:46.383294Z","iopub.execute_input":"2024-03-09T00:08:46.383694Z","iopub.status.idle":"2024-03-09T00:08:47.101369Z","shell.execute_reply.started":"2024-03-09T00:08:46.383654Z","shell.execute_reply":"2024-03-09T00:08:47.100439Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"y_preds_train = np.argmax(model.predict(X_train),axis=1)\ny_preds_test = np.argmax(model.predict(X_test),axis=1)","metadata":{"execution":{"iopub.status.busy":"2024-03-09T00:08:47.102475Z","iopub.execute_input":"2024-03-09T00:08:47.102757Z","iopub.status.idle":"2024-03-09T00:08:58.731191Z","shell.execute_reply.started":"2024-03-09T00:08:47.102731Z","shell.execute_reply":"2024-03-09T00:08:58.729973Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Let's see the confusion matrix\nprint(confusion_matrix(np.argmax(y_train, axis=1), y_preds_train))","metadata":{"execution":{"iopub.status.busy":"2024-03-09T00:08:58.732921Z","iopub.execute_input":"2024-03-09T00:08:58.733708Z","iopub.status.idle":"2024-03-09T00:08:58.747853Z","shell.execute_reply.started":"2024-03-09T00:08:58.733674Z","shell.execute_reply":"2024-03-09T00:08:58.746864Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"print(classification_report(np.argmax(y_train, axis=1), y_preds_train))","metadata":{"execution":{"iopub.status.busy":"2024-03-09T00:08:58.749167Z","iopub.execute_input":"2024-03-09T00:08:58.749477Z","iopub.status.idle":"2024-03-09T00:08:58.833660Z","shell.execute_reply.started":"2024-03-09T00:08:58.749434Z","shell.execute_reply":"2024-03-09T00:08:58.832638Z"},"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-03-09T00:08:58.834952Z","iopub.execute_input":"2024-03-09T00:08:58.835256Z","iopub.status.idle":"2024-03-09T00:09:00.462157Z","shell.execute_reply.started":"2024-03-09T00:08:58.835230Z","shell.execute_reply":"2024-03-09T00:09:00.461222Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df_test = df_test.to_numpy().reshape(-1, 28, 28, 1)","metadata":{"execution":{"iopub.status.busy":"2024-03-09T00:09:00.463429Z","iopub.execute_input":"2024-03-09T00:09:00.464128Z","iopub.status.idle":"2024-03-09T00:09:00.468744Z","shell.execute_reply.started":"2024-03-09T00:09:00.464088Z","shell.execute_reply":"2024-03-09T00:09:00.467855Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"predictions = model.predict(df_test)","metadata":{"execution":{"iopub.status.busy":"2024-03-09T00:09:00.469925Z","iopub.execute_input":"2024-03-09T00:09:00.470269Z","iopub.status.idle":"2024-03-09T00:09:08.093711Z","shell.execute_reply.started":"2024-03-09T00:09:00.470237Z","shell.execute_reply":"2024-03-09T00:09:08.092689Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"predictions[1]","metadata":{"execution":{"iopub.status.busy":"2024-03-09T00:09:08.097750Z","iopub.execute_input":"2024-03-09T00:09:08.098402Z","iopub.status.idle":"2024-03-09T00:09:08.105186Z","shell.execute_reply.started":"2024-03-09T00:09:08.098371Z","shell.execute_reply":"2024-03-09T00:09:08.104127Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"predictions_class = np.argmax(predictions,axis=1)","metadata":{"execution":{"iopub.status.busy":"2024-03-09T00:09:08.106396Z","iopub.execute_input":"2024-03-09T00:09:08.106698Z","iopub.status.idle":"2024-03-09T00:09:08.114190Z","shell.execute_reply.started":"2024-03-09T00:09:08.106672Z","shell.execute_reply":"2024-03-09T00:09:08.113182Z"},"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-03-09T00:09:08.115414Z","iopub.execute_input":"2024-03-09T00:09:08.115690Z","iopub.status.idle":"2024-03-09T00:09:08.135888Z","shell.execute_reply.started":"2024-03-09T00:09:08.115662Z","shell.execute_reply":"2024-03-09T00:09:08.135045Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"id = sub['ImageId']","metadata":{"execution":{"iopub.status.busy":"2024-03-09T00:09:08.136922Z","iopub.execute_input":"2024-03-09T00:09:08.137225Z","iopub.status.idle":"2024-03-09T00:09:08.141321Z","shell.execute_reply.started":"2024-03-09T00:09:08.137200Z","shell.execute_reply":"2024-03-09T00:09:08.140333Z"},"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-03-09T00:09:08.142765Z","iopub.execute_input":"2024-03-09T00:09:08.143130Z","iopub.status.idle":"2024-03-09T00:09:08.150184Z","shell.execute_reply.started":"2024-03-09T00:09:08.143098Z","shell.execute_reply":"2024-03-09T00:09:08.149267Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"submission_df.head()","metadata":{"execution":{"iopub.status.busy":"2024-03-09T00:09:08.151479Z","iopub.execute_input":"2024-03-09T00:09:08.151758Z","iopub.status.idle":"2024-03-09T00:09:08.161930Z","shell.execute_reply.started":"2024-03-09T00:09:08.151733Z","shell.execute_reply":"2024-03-09T00:09:08.161048Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"submission_df.to_csv('submission.csv', index=False)","metadata":{"execution":{"iopub.status.busy":"2024-03-09T00:09:08.163125Z","iopub.execute_input":"2024-03-09T00:09:08.163445Z","iopub.status.idle":"2024-03-09T00:09:08.223143Z","shell.execute_reply.started":"2024-03-09T00:09:08.163414Z","shell.execute_reply":"2024-03-09T00:09:08.222473Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"**Thankyou**","metadata":{}},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]}]}