{"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"name":"python","version":"3.10.14","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":30788,"isInternetEnabled":true,"language":"python","sourceType":"notebook","isGpuEnabled":false}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"markdown","source":"  ## <h2 style=\"color:#3498db; font-weight:bold; font-family:Arial, sans-serif;\">Problem Statement</h2> \n<p style=\"font-size:17px; color:#34495e; font-family:Verdana, sans-serif;\">\n  The goal of this notebook is to build a model to accurately identify digits from a dataset of tens of thousands \n  of handwritten images. Using both the Kaggle and Keras-provided MNIST datasets, this project will explore \n  neural network approaches to determine effective techniques in digit recognition.\n</p>\n\n <h3 style=\"color:#3498db; font-weight:bold; font-family:Arial, sans-serif;\">Acknowledgements</h3>\n<p style=\"font-size:17px; color:#34495e; font-family:Verdana, sans-serif;\">\n  More details about the MNIST dataset, including algorithms that have been tried on it and their levels of \n  success, can be found at <a href=\"http://yann.lecun.com/exdb/mnist/index.html\" style=\"color:#e74c3c; text-decoration:none;\">this link</a>. \n  The dataset is made available under a Creative Commons Attribution-Share Alike 3.0 license.\n</p>\n","metadata":{}},{"cell_type":"code","source":"import pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom keras.datasets import mnist\nfrom tensorflow.keras.utils import to_categorical\nimport matplotlib.cm as cm\nfrom keras.models import Sequential,load_model\nfrom keras.layers import Dense,Dropout,Flatten,Conv2D,MaxPooling2D\nfrom keras.callbacks import ReduceLROnPlateau,ModelCheckpoint\n\nimport warnings \nwarnings.filterwarnings('ignore')\n%matplotlib inline","metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","execution":{"iopub.status.busy":"2024-10-30T11:57:36.668813Z","iopub.execute_input":"2024-10-30T11:57:36.669960Z","iopub.status.idle":"2024-10-30T11:57:50.816625Z","shell.execute_reply.started":"2024-10-30T11:57:36.669884Z","shell.execute_reply":"2024-10-30T11:57:50.815420Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df=pd.read_csv('/kaggle/input/digit-recognizer/train.csv')\ndt=pd.read_csv('/kaggle/input/digit-recognizer/test.csv')\ndf.shape,dt.shape","metadata":{"execution":{"iopub.status.busy":"2024-10-30T11:57:50.818462Z","iopub.execute_input":"2024-10-30T11:57:50.819124Z","iopub.status.idle":"2024-10-30T11:57:56.028307Z","shell.execute_reply.started":"2024-10-30T11:57:50.819084Z","shell.execute_reply":"2024-10-30T11:57:56.027279Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"  ## <h2 style=\"color:#3498db; font-weight:bold; font-family:Arial, sans-serif; \">Data Preparation</h2>\n\n<p style=\"font-size:17px; color:#34495e; ; font-family:Verdana, sans-serif;\">\n  Before feeding our data into a neural network, we need to format it to match the input requirements. \n  Since neural networks expect a consistent format and data type, the following transformations are applied:\n</p>\n\n<ul style=\"font-size:17px; color:#2c3e50; font-family:Verdana, sans-serif; \">\n  <li style=\"margin-bottom:8px;\">\n    <strong style=\"color:#e67e22;\">Data Type Conversion:</strong> We convert the dataset values to <code style=\"background-color:#ecf0f1; padding:3px; border-radius:4px;\">float32</code> \n    to ensure compatibility with the neural network’s processing and optimize memory usage during training.\n  </li>\n  <li style=\"margin-bottom:8px;\">\n    <strong style=\"color:#27ae60;\">Reshaping the Dataset:</strong> The data is reshaped to \n    <code style=\"background-color:#ecf0f1; padding:3px; border-radius:4px;\">(28, 28, 1)</code> to match the structure of \n    the MNIST images—28x28 pixels and a single grayscale channel—so the neural network can interpret each image correctly.\n  </li>\n</ul>\n\n<p style=\"font-size:17px; color:#34495e;  font-family:Verdana, sans-serif;\">\n  For validation data, we similarly convert to <code style=\"background-color:#ecf0f1; padding:3px; border-radius:4px;\">float32</code>, \n  reshape it to fit the 28x28 image format, and extract the labels as integer values. The final shape of \n  <code style=\"background-color:#ecf0f1; padding:3px; border-radius:4px;\">X_val</code> and \n  <code style=\"background-color:#ecf0f1; padding:3px; border-radius:4px;\">y_val</code> is printed to confirm the data preparation.\n</p>\n","metadata":{}},{"cell_type":"code","source":"dt = dt.values.astype('float32')\ndt = dt.reshape(-1, 28, 28, 1)\nX_val = df.iloc[:, 1:].values.astype('float32') \nX_val = X_val.reshape(-1, 28, 28, 1) \ny_val = df.iloc[:, 0].values.astype('int32')      \nprint(X_val.shape, y_val.shape)     \n","metadata":{"execution":{"iopub.status.busy":"2024-10-30T11:57:56.029473Z","iopub.execute_input":"2024-10-30T11:57:56.029819Z","iopub.status.idle":"2024-10-30T11:57:56.138980Z","shell.execute_reply.started":"2024-10-30T11:57:56.029781Z","shell.execute_reply":"2024-10-30T11:57:56.137770Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"  ## <h2 style=\"color:#3498db; font-weight:bold; font-family:Arial, sans-serif;\">Data Loading and Preparation</h2>\n\n<p style=\"font-size:17px; color:#34495e; font-family:Verdana, sans-serif;\">\n  In this section, we are loading the MNIST dataset and preparing it for our neural network model. \n  The goal is to create a unified training dataset that combines both training and testing data, allowing us to leverage \n  the full range of available handwritten digit images for better model training.\n</p>\n\n<ul style=\"font-size:17px; color:#2c3e50; font-family:Verdana, sans-serif;\">\n \n  <li style=\"margin-bottom:8px;\">\n    <strong style=\"color:#27ae60;\">Combining Datasets:</strong> \n    We stack the training and testing images into a single dataset to provide our model with more examples.\n  </li>\n  <li style=\"margin-bottom:8px;\">\n    <strong style=\"color:#8e44ad;\">Concatenating Labels:</strong> \n    We combine the labels of the training and testing sets to match the merged dataset of images.\n  </li>\n  \n</ul>\n\n<p style=\"font-size:17px; color:#34495e; font-family:Verdana, sans-serif;\">\n  Finally, we check the shapes of the merged dataset and labels to confirm everything is prepared correctly for training.\n</p>\n","metadata":{}},{"cell_type":"code","source":"(X_train,y_train),(X_test,y_test)=mnist.load_data()\nX_train=np.vstack((X_train,X_test))\ny_train=np.concatenate([y_train,y_test])\nX_train=X_train.reshape(-1,28,28,1)\nX_train.shape,y_train.shape","metadata":{"execution":{"iopub.status.busy":"2024-10-30T11:57:56.141468Z","iopub.execute_input":"2024-10-30T11:57:56.141938Z","iopub.status.idle":"2024-10-30T11:57:57.552300Z","shell.execute_reply.started":"2024-10-30T11:57:56.141889Z","shell.execute_reply":"2024-10-30T11:57:57.551003Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"  ## <h2 style=\"color:#3498db; font-weight:bold; font-family:Arial, sans-serif;\">Visualizing Different Images Of Dataset</h2>\n","metadata":{}},{"cell_type":"code","source":"fig, axes = plt.subplots(1, 6, figsize=(20, 20))  \nfor i in range(6):\n    axes[i].imshow(X_train[i].reshape(28, 28), cmap='gray')\n    axes[i].axis('off') \nplt.tight_layout()\n","metadata":{"execution":{"iopub.status.busy":"2024-10-30T11:57:57.553630Z","iopub.execute_input":"2024-10-30T11:57:57.553962Z","iopub.status.idle":"2024-10-30T11:57:58.002609Z","shell.execute_reply.started":"2024-10-30T11:57:57.553929Z","shell.execute_reply":"2024-10-30T11:57:58.001255Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"fig,ax=plt.subplots(1,6,figsize=(20,20))\nfor u in range(6):\n    ax[u].imshow(X_val[u],cmap='gray')\n    ax[u].axis('off')\nplt.tight_layout()\n","metadata":{"execution":{"iopub.status.busy":"2024-10-30T11:58:53.345838Z","iopub.execute_input":"2024-10-30T11:58:53.346375Z","iopub.status.idle":"2024-10-30T11:58:53.813548Z","shell.execute_reply.started":"2024-10-30T11:58:53.346316Z","shell.execute_reply":"2024-10-30T11:58:53.812155Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"  ## <h2 style=\"color:#e67e22; font-weight:bold; font-family:Arial, sans-serif;\">Visualizing Handwritten Digits</h2>\n\n<p style=\"font-size:17px; color:#34495e; font-family:Verdana, sans-serif;\">\n  In this section, we create a function to visualize handwritten digits from the dataset. This is crucial for understanding \n  how well our model is performing in recognizing different numbers. By displaying the images alongside their predicted \n  values, we can evaluate the model's accuracy visually.\n</p>\n\n<ul style=\"font-size:17px; color:#2c3e50; font-family:Verdana, sans-serif;\">\n  <li style=\"margin-bottom:8px;\">\n    <strong style=\"color:#3498db;\">Function Purpose:</strong> \n    The <code style=\"background-color:#ecf0f1; padding:3px; border-radius:4px;\">img_to_num</code> function displays an \n    image of the digit, annotating it with its pixel values for better insight into the data being processed.\n  </li>\n  <li style=\"margin-bottom:8px;\">\n    <strong style=\"color:#27ae60;\">Visual Representation:</strong> \n    By using color contrast based on pixel intensity, we ensure that the digit is easily readable, helping us analyze \n    the model's predictions effectively.\n  </li>\n</ul>\n\n<p style=\"font-size:17px; color:#34495e; font-family:Verdana, sans-serif;\">\n  After defining the function, we visualize one of the images from the validation set, allowing us to confirm that \n  the input data is being processed correctly.\n</p>\n","metadata":{}},{"cell_type":"code","source":"def img_to_num(img, ax):\n    ax.imshow(img, cmap='gray')\n    w, h = img.shape\n    thresh = img.max() / 2.5\n    for x in range(w):\n        for y in range(h):\n            ax.annotate(\n                str(round(img[x, y])),\n                xy=(y, x),\n                horizontalalignment='center',\n                verticalalignment='center',\n                color='white' if img[x, y] < thresh else 'black'\n            )\n\nfig = plt.figure(figsize=(12, 12))\nax = fig.add_subplot(111)\nimg_to_num(X_val[3].reshape(28, 28), ax)  \nplt.show()\n    ","metadata":{"execution":{"iopub.status.busy":"2024-10-30T12:00:19.275717Z","iopub.execute_input":"2024-10-30T12:00:19.276306Z","iopub.status.idle":"2024-10-30T12:00:22.389976Z","shell.execute_reply.started":"2024-10-30T12:00:19.276260Z","shell.execute_reply":"2024-10-30T12:00:22.388089Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"  ## <h2 style=\"color:#e67e22; font-weight:bold; font-family:Arial, sans-serif;\">Data Normalization</h2>\n\n<p style=\"font-size:17px; color:#34495e; font-family:Verdana, sans-serif;\">\n  In this section, we normalize our datasets by scaling the pixel values to a range of [0, 1]. \n  This step is crucial for training neural networks as it helps in faster convergence and improved \n  performance by ensuring that all input features contribute equally during training.\n</p>\n\n<ul style=\"font-size:17px; color:#2c3e50; font-family:Verdana, sans-serif;\">\n  <li style=\"margin-bottom:8px;\">\n    <strong style=\"color:#3498db;\">Scaling Pixel Values:</strong> \n    We divide the pixel values of <code style=\"background-color:#ecf0f1; padding:3px; border-radius:4px;\">X_train</code>, \n    <code style=\"background-color:#ecf0f1; padding:3px; border-radius:4px;\">dt</code>, and <code style=\"background-color:#ecf0f1; padding:3px; border-radius:4px;\">X_val</code> by 255.\n    This transformation changes the pixel values from a range of [0, 255] to [0, 1], enhancing numerical stability.\n  </li>\n  <li style=\"margin-bottom:8px;\">\n    <strong style=\"color:#27ae60;\">Improved Model Training:</strong> \n    Normalization helps the model learn more effectively by preventing features with larger ranges from dominating the learning process.\n  </li>\n</ul>\n\n<p style=\"font-size:17px; color:#34495e; font-family:Verdana, sans-serif;\">\n  Overall, this normalization step is essential for optimizing the performance of our neural network model.\n</p>\n","metadata":{}},{"cell_type":"code","source":"X_train=X_train/255\ndt=dt/255\nX_val=X_val/255","metadata":{"execution":{"iopub.status.busy":"2024-10-29T12:15:56.353440Z","iopub.execute_input":"2024-10-29T12:15:56.353917Z","iopub.status.idle":"2024-10-29T12:15:56.576837Z","shell.execute_reply.started":"2024-10-29T12:15:56.353846Z","shell.execute_reply":"2024-10-29T12:15:56.575829Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"  ## <h2 style=\"color:#e67e22; font-weight:bold; font-family:Arial, sans-serif;\">One-Hot Encoding of Labels</h2>\n\n<p style=\"font-size:17px; color:#34495e; font-family:Verdana, sans-serif;\">\n  In this section, we transform the integer labels into one-hot encoded vectors. Each digit (0-9) is represented as a vector of 10 elements, where only the index corresponding to the digit is set to 1, and all other indices are set to 0.\n</p>\n\n<p style=\"font-size:17px; color:#34495e; font-family:Verdana, sans-serif;\">\n  For example, the digit <strong>3</strong> is transformed as follows:\n</p>\n\n\n<ul style=\"font-size:17px; color:#2c3e50; font-family:Verdana, sans-serif;\">\n  <li style=\"margin-bottom:8px;\">\n    The original label <code style=\"background-color:#ecf0f1; padding:3px; border-radius:4px;\">3</code> becomes \n    the vector <code style=\"background-color:#ecf0f1; padding:3px; border-radius:4px;\">[0, 0, 0, 1, 0, 0, 0, 0, 0, 0]</code>.\n  </li>\n</ul>\n\n<p style=\"font-size:17px; color:#34495e; font-family:Verdana, sans-serif;\">\n  This encoding method allows our model to output probabilities for each digit during training and is essential \n  for multi-class classification tasks.\n</p>\n","metadata":{}},{"cell_type":"code","source":"print(\"Before catagorizing \",y_train[0])\ny_train=to_categorical(y_train,10)\ny_val=to_categorical(y_val,10)\nprint(\"Before catagorizing \" ,y_train[0])","metadata":{"execution":{"iopub.status.busy":"2024-10-30T12:01:54.637426Z","iopub.execute_input":"2024-10-30T12:01:54.638027Z","iopub.status.idle":"2024-10-30T12:01:54.653191Z","shell.execute_reply.started":"2024-10-30T12:01:54.637982Z","shell.execute_reply":"2024-10-30T12:01:54.651748Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"  ## <h2 style=\"color:#e67e22; font-weight:bold; font-family:Arial, sans-serif;\">Model Architecture Overview</h2>\n\n<p style=\"font-size:17px; color:#34495e; font-family:Verdana, sans-serif;\">\n  The architecture of our convolutional neural network (CNN) is designed to efficiently learn and classify handwritten digits from the MNIST dataset. Below are the key types of layers used in the model:\n</p>\n\n<ul style=\"font-size:17px; color:#2c3e50; font-family:Verdana, sans-serif;\">\n  <li style=\"margin-bottom:8px;\">\n    <strong style=\"color:#3498db;\">Convolutional Layers:</strong> \n    These layers are the backbone of the CNN. They apply convolutional filters to the input images, allowing the network to automatically detect and learn various features, such as edges, textures, and shapes. The initial layers capture simple features, while deeper layers learn more complex patterns. \n  </li>\n  \n  <li style=\"margin-bottom:8px;\">\n    <strong style=\"color:#27ae60;\">MaxPooling Layers:</strong> \n    Max pooling layers reduce the spatial dimensions of the feature maps by retaining only the most significant values, which helps to down-sample the feature maps. This not only decreases the computational load but also aids in controlling overfitting by providing a form of translation invariance.\n  </li>\n  \n  <li style=\"margin-bottom:8px;\">\n    <strong style=\"color:#8e44ad;\">Flatten Layer:</strong> \n    The flatten layer transforms the two-dimensional feature maps into a one-dimensional vector, making it suitable for input into the dense layers. This step is crucial for transitioning from the convolutional part of the network to the classification part.\n  </li>\n\n  <li style=\"margin-bottom:8px;\">\n    <strong style=\"color:#3498db;\">Dense Layers:</strong> \n    These fully connected layers perform the final classification by connecting every neuron from the previous layer to every neuron in the next layer. The last dense layer uses the softmax activation function to produce probabilities for each digit class (0-9), allowing the model to predict the digit represented in the input image.\n  </li>\n</ul>\n\n<p style=\"font-size:17px; color:#34495e; font-family:Verdana, sans-serif;\">\n  Each layer type plays a distinct and essential role in transforming the input data through feature extraction and classification, ultimately enabling accurate digit recognition.\n</p>\n","metadata":{}},{"cell_type":"code","source":"model=Sequential()\nmodel.add(Conv2D(filters=64,kernel_size=3,padding='same',activation='relu',input_shape=(28,28,1)))\nmodel.add(Conv2D(filters=128,kernel_size=3,padding='same',activation='relu'))\nmodel.add(Conv2D(filters=128,kernel_size=3,padding='same',activation='relu'))\nmodel.add(MaxPooling2D(pool_size=2))\nmodel.add(Conv2D(filters=128,kernel_size=3,padding='same',activation='relu'))\nmodel.add(Conv2D(filters=192,kernel_size=3,padding='same',activation='relu'))\nmodel.add(MaxPooling2D(pool_size=2))\nmodel.add(Conv2D(filters=192,kernel_size=5,padding='same',activation='relu'))\nmodel.add(MaxPooling2D(pool_size=2,padding='same'))\nmodel.add(Flatten())\nmodel.add(Dense(256,activation='relu'))\nmodel.add(Dense(10,activation='softmax'))\nmodel.summary()\n","metadata":{"execution":{"iopub.status.busy":"2024-10-29T12:15:56.591847Z","iopub.execute_input":"2024-10-29T12:15:56.592169Z","iopub.status.idle":"2024-10-29T12:15:57.652637Z","shell.execute_reply.started":"2024-10-29T12:15:56.592137Z","shell.execute_reply":"2024-10-29T12:15:57.651738Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"  ## <h2 style=\"color:#e67e22; font-weight:bold; font-family:Arial, sans-serif;\">Model Summary</h2>\n\n\n| Layer Type                     | Output Shape          | Param #   |\n|--------------------------------|-----------------------|-----------|\n| Conv2D                         | (None, 28, 28, 64)    | 640       |\n| Conv2D                         | (None, 28, 28, 128)   | 73,856    |\n| Conv2D                         | (None, 28, 28, 128)   | 147,584   |\n| MaxPooling2D                  | (None, 14, 14, 128)   | 0         |\n| Conv2D                         | (None, 14, 14, 128)   | 147,584   |\n| Conv2D                         | (None, 14, 14, 192)   | 221,376   |\n| MaxPooling2D                  | (None, 7, 7, 192)     | 0         |\n| Conv2D                         | (None, 7, 7, 192)     | 921,792   |\n| MaxPooling2D                  | (None, 4, 4, 192)     | 0         |\n| Flatten                        | (None, 3072)          | 0         |\n| Dense                          | (None, 256)           | 786,688   |\n| Dense                          | (None, 10)            | 2,570     |\n| **Total Parameters**           |                       | **1,307,682** |\n","metadata":{}},{"cell_type":"markdown","source":"  ## <h2 style=\"color:#e67e22; font-weight:bold; font-family:Arial, sans-serif;\">Model Compilation and Training</h2>\n\n<p style=\"font-size:17px; color:#34495e; font-family:Verdana, sans-serif;\">\n  In this section, we compile and train our convolutional neural network model. The following steps are performed:\n</p>\n\n<ul style=\"font-size:17px; color:#2c3e50; font-family:Verdana, sans-serif;\">\n  <li style=\"margin-bottom:8px;\">\n    <strong style=\"color:#3498db;\">Model Compilation:</strong> \n    We use <code style=\"background-color:#ecf0f1; padding:3px; border-radius:4px;\">model.compile()</code> to set up the model for training. The loss function <code style=\"background-color:#ecf0f1; padding:3px; border-radius:4px;\">categorical_crossentropy</code> is suitable for multi-class classification problems, while the <code style=\"background-color:#ecf0f1; padding:3px; border-radius:4px;\">adam</code> optimizer efficiently updates the model weights during training based on the loss.\n  </li>\n\n  <li style=\"margin-bottom:8px;\">\n    <strong style=\"color:#27ae60;\">Learning Rate Adjustment:</strong> \n    The <code style=\"background-color:#ecf0f1; padding:3px; border-radius:4px;\">ReduceLROnPlateau</code> callback monitors the validation loss, reducing the learning rate by a factor of 0.3 if there is no improvement for a specified number of epochs. This helps the model converge better by allowing it to take smaller steps when approaching optimal weights.\n  </li>\n\n  <li style=\"margin-bottom:8px;\">\n    <strong style=\"color:#8e44ad;\">Model Training:</strong> \n    We train the model using <code style=\"background-color:#ecf0f1; padding:3px; border-radius:4px;\">model.fit()</code>, specifying the training data and labels, batch size, number of epochs, and validation data. The training process allows the model to learn from the data, adjusting weights based on the computed loss and improving accuracy over time.\n  </li>\n\n  <li style=\"margin-bottom:8px;\">\n    <strong style=\"color:#3498db;\">Model Saving:</strong> \n    After training, we save the model to a file using <code style=\"background-color:#ecf0f1; padding:3px; border-radius:4px;\">model.save('my_model.h5')</code>. This enables us to reuse the trained model in future applications without needing to retrain it.\n  </li>\n</ul>\n\n<p style=\"font-size:17px; color:#34495e; font-family:Verdana, sans-serif;\">\n  These steps are crucial for ensuring our model is effectively trained and can be utilized later for predictions.\n</p>\n","metadata":{}},{"cell_type":"code","source":"model.compile(loss='categorical_crossentropy',optimizer='adam',metrics=['accuracy'])","metadata":{"execution":{"iopub.status.busy":"2024-10-29T12:15:57.653880Z","iopub.execute_input":"2024-10-29T12:15:57.654258Z","iopub.status.idle":"2024-10-29T12:15:57.667822Z","shell.execute_reply.started":"2024-10-29T12:15:57.654221Z","shell.execute_reply":"2024-10-29T12:15:57.666932Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"lr=ReduceLROnPlateau(monitir='loss',factor=.3,verbose=1,patience=2,min_lr=10e-8)\nhistory=model.fit(X_train,y_train,batch_size=128,epochs=21,validation_data=(X_val,y_val),callbacks=[lr],verbose=1,shuffle=True)\nmodel.save('my_model.h5') ","metadata":{"execution":{"iopub.status.busy":"2024-10-29T12:15:57.669056Z","iopub.execute_input":"2024-10-29T12:15:57.670152Z","iopub.status.idle":"2024-10-29T12:16:38.640454Z","shell.execute_reply.started":"2024-10-29T12:15:57.670114Z","shell.execute_reply":"2024-10-29T12:16:38.639553Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"  ## <h2 style=\"color:#2980b9;; font-weight:bold; font-family:Arial, sans-serif;\">Ploting Loss</h2>","metadata":{}},{"cell_type":"code","source":"plt.figure(figsize=(12, 5))\n\nplt.subplot(1, 2, 1)\nplt.plot(history.history['loss'], label='Training Loss')\nplt.plot(history.history['val_loss'], label='Validation Loss')\nplt.title('Loss over Epochs')\nplt.xlabel('Epochs')\nplt.ylabel('Loss')\nplt.legend()","metadata":{"execution":{"iopub.status.busy":"2024-10-29T12:16:38.641564Z","iopub.execute_input":"2024-10-29T12:16:38.641856Z","iopub.status.idle":"2024-10-29T12:16:38.957245Z","shell.execute_reply.started":"2024-10-29T12:16:38.641823Z","shell.execute_reply":"2024-10-29T12:16:38.956227Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"  ## <h2 style=\"color:#2980b9; font-weight:bold; font-family:Arial, sans-serif;\">Predicting The Output For Test Dataset</h2>\n","metadata":{}},{"cell_type":"code","source":"pred=model.predict(dt,verbose=2)\npred_classes = np.argmax(pred, axis=1)","metadata":{"execution":{"iopub.status.busy":"2024-10-29T12:16:38.958692Z","iopub.execute_input":"2024-10-29T12:16:38.959171Z","iopub.status.idle":"2024-10-29T12:16:43.566421Z","shell.execute_reply.started":"2024-10-29T12:16:38.959120Z","shell.execute_reply":"2024-10-29T12:16:43.565583Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"  ## <h2 style=\"color:#2980b9; font-weight:bold; font-family:Arial, sans-serif;\">Saving Submission File</h2>\n","metadata":{}},{"cell_type":"code","source":"sb=pd.read_csv('/kaggle/input/digit-recognizer/sample_submission.csv')\nsb[\"Label\"]=pred_classes\nsb.to_csv('submission.csv',index=False)\nprint(\"Submission file created\")\n","metadata":{"execution":{"iopub.status.busy":"2024-10-29T12:16:43.567583Z","iopub.execute_input":"2024-10-29T12:16:43.567877Z","iopub.status.idle":"2024-10-29T12:16:43.639694Z","shell.execute_reply.started":"2024-10-29T12:16:43.567844Z","shell.execute_reply":"2024-10-29T12:16:43.638778Z"},"trusted":true},"execution_count":null,"outputs":[]}]}