{"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":30786,"isInternetEnabled":true,"language":"python","sourceType":"notebook","isGpuEnabled":false}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"code","source":"import numpy as np\nimport pandas as pd\nfrom tensorflow.keras.models import Sequential\nfrom tensorflow.keras.layers import Conv2D, MaxPooling2D, Flatten, Dense\nfrom tensorflow.keras.utils import to_categorical\nimport matplotlib.pyplot as plt\nfrom sklearn.model_selection import train_test_split","metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","execution":{"iopub.status.busy":"2024-10-26T09:43:36.991509Z","iopub.execute_input":"2024-10-26T09:43:36.991919Z","iopub.status.idle":"2024-10-26T09:43:52.175110Z","shell.execute_reply.started":"2024-10-26T09:43:36.991877Z","shell.execute_reply":"2024-10-26T09:43:52.173766Z"},"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":"2024-10-26T09:43:52.177267Z","iopub.execute_input":"2024-10-26T09:43:52.177856Z","iopub.status.idle":"2024-10-26T09:43:57.573368Z","shell.execute_reply.started":"2024-10-26T09:43:52.177814Z","shell.execute_reply":"2024-10-26T09:43:57.572384Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"X_train = train.drop(\"label\", axis=1)\ny_train = train[\"label\"]","metadata":{"execution":{"iopub.status.busy":"2024-10-26T09:43:57.574702Z","iopub.execute_input":"2024-10-26T09:43:57.575063Z","iopub.status.idle":"2024-10-26T09:43:57.682921Z","shell.execute_reply.started":"2024-10-26T09:43:57.575015Z","shell.execute_reply":"2024-10-26T09:43:57.681996Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## Preprocessing the Data\nIn this section we will be doing:\n- Normalization: Scale pixel values to the range [0, 1] by dividing by 255.\n- Reshaping: Reshape the data into its original 28x28 format.\n- One-hot Encoding: Convert the labels into one-hot encoded vectors.","metadata":{}},{"cell_type":"code","source":"X_train = X_train / 255.0\ntest = test / 255.0","metadata":{"execution":{"iopub.status.busy":"2024-10-26T09:43:57.684087Z","iopub.execute_input":"2024-10-26T09:43:57.684446Z","iopub.status.idle":"2024-10-26T09:43:57.795065Z","shell.execute_reply.started":"2024-10-26T09:43:57.684408Z","shell.execute_reply":"2024-10-26T09:43:57.794043Z"},"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":"2024-10-26T09:43:57.798091Z","iopub.execute_input":"2024-10-26T09:43:57.798782Z","iopub.status.idle":"2024-10-26T09:43:57.803924Z","shell.execute_reply.started":"2024-10-26T09:43:57.798740Z","shell.execute_reply":"2024-10-26T09:43:57.802624Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"#display the first 9 images in the dataset\nplt.figure(figsize=(6, 6))\nfor i in range(9):\n    plt.subplot(3, 3, i+1)\n    plt.imshow(X_train[i].reshape(28, 28), cmap='gray') \n    plt.title(f\"Label: {y_train[i]}\") \n    plt.axis('off')\n\nplt.tight_layout()\nplt.show()","metadata":{"execution":{"iopub.status.busy":"2024-10-26T09:43:57.805590Z","iopub.execute_input":"2024-10-26T09:43:57.806396Z","iopub.status.idle":"2024-10-26T09:43:58.675345Z","shell.execute_reply.started":"2024-10-26T09:43:57.806340Z","shell.execute_reply":"2024-10-26T09:43:58.674266Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"y_train = to_categorical(y_train, num_classes=10)","metadata":{"execution":{"iopub.status.busy":"2024-10-26T09:43:58.677130Z","iopub.execute_input":"2024-10-26T09:43:58.677458Z","iopub.status.idle":"2024-10-26T09:43:58.683444Z","shell.execute_reply.started":"2024-10-26T09:43:58.677421Z","shell.execute_reply":"2024-10-26T09:43:58.682321Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"X_train_new, X_val, y_train_new, y_val = train_test_split(X_train, y_train, test_size=0.2, random_state=42)","metadata":{"execution":{"iopub.status.busy":"2024-10-26T09:43:58.684776Z","iopub.execute_input":"2024-10-26T09:43:58.685167Z","iopub.status.idle":"2024-10-26T09:43:59.069398Z","shell.execute_reply.started":"2024-10-26T09:43:58.685092Z","shell.execute_reply":"2024-10-26T09:43:59.068169Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"print(f\"Training set size: {X_train_new.shape}\")\nprint(f\"Validation set size: {X_val.shape}\")","metadata":{"execution":{"iopub.status.busy":"2024-10-26T09:43:59.070641Z","iopub.execute_input":"2024-10-26T09:43:59.070994Z","iopub.status.idle":"2024-10-26T09:43:59.077337Z","shell.execute_reply.started":"2024-10-26T09:43:59.070956Z","shell.execute_reply":"2024-10-26T09:43:59.075989Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## Model Training\nFor this part, we will be building a Convolutional Neural Network (CNN) model using Keras, designed for image classification tasks.\nOur CNN model is composed of 7 layers:\n1. Conv2D(32, (3, 3)): Extract low-level features like edges from the input image.\n2. MaxPooling2D(pool_size=(2, 2)): Reduce the size of the feature maps (downsampling) to retain important information while reducing computational complexity.\n3. Conv2D(64, (3, 3)): Learn more complex features from the downsampled data.\n4. MaxPooling2D(pool_size=(2, 2)): Further reduce the dimensionality of the feature maps.\n5. Flatten(): Convert the 2D feature maps into a 1D vector to pass into fully connected layers.\n6. Dense(128): Fully connected layer for learning high-level features.\n7. Dense(10, softmax): Output layer that gives the probability distribution for the 10 possible digit classes (0-9).","metadata":{}},{"cell_type":"code","source":"model = Sequential([\n    Conv2D(32, (3, 3), activation='relu', input_shape=(28, 28, 1)),\n    MaxPooling2D(pool_size=(2, 2)),\n    Conv2D(64, (3, 3), activation='relu'),\n    MaxPooling2D(pool_size=(2, 2)),\n    Flatten(),\n    Dense(128, activation='relu'),\n    Dense(10, activation='softmax')\n])","metadata":{"execution":{"iopub.status.busy":"2024-10-26T09:43:59.078735Z","iopub.execute_input":"2024-10-26T09:43:59.079101Z","iopub.status.idle":"2024-10-26T09:43:59.183349Z","shell.execute_reply.started":"2024-10-26T09:43:59.079062Z","shell.execute_reply":"2024-10-26T09:43:59.182083Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"model.summary()","metadata":{"execution":{"iopub.status.busy":"2024-10-26T09:43:59.184589Z","iopub.execute_input":"2024-10-26T09:43:59.184908Z","iopub.status.idle":"2024-10-26T09:43:59.212013Z","shell.execute_reply.started":"2024-10-26T09:43:59.184871Z","shell.execute_reply":"2024-10-26T09:43:59.210934Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"model.compile(optimizer='adam', loss='categorical_crossentropy', metrics=['accuracy'])\nmodel.fit(X_train_new, y_train_new, epochs=10, batch_size=64)","metadata":{"execution":{"iopub.status.busy":"2024-10-26T09:43:59.213403Z","iopub.execute_input":"2024-10-26T09:43:59.213868Z","iopub.status.idle":"2024-10-26T09:46:47.991496Z","shell.execute_reply.started":"2024-10-26T09:43:59.213814Z","shell.execute_reply":"2024-10-26T09:46:47.990240Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## Evaluating the Model\nAfter training, we will evaluate the model on a validation set to see how well it generalizes to unseen data.","metadata":{}},{"cell_type":"code","source":"score = model.evaluate(X_val, y_val, verbose=0)\nprint(f\"Validation Loss: {score[0]}\")\nprint(f\"Validation Accuracy: {score[1]}\")","metadata":{"execution":{"iopub.status.busy":"2024-10-26T09:46:47.992793Z","iopub.execute_input":"2024-10-26T09:46:47.993173Z","iopub.status.idle":"2024-10-26T09:46:49.586036Z","shell.execute_reply.started":"2024-10-26T09:46:47.993134Z","shell.execute_reply":"2024-10-26T09:46:49.584919Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## Making Predictions","metadata":{}},{"cell_type":"code","source":"predictions = model.predict(test)\n#get the class with the highest probability\npredictions = np.argmax(predictions, axis=1)","metadata":{"execution":{"iopub.status.busy":"2024-10-26T09:46:49.589422Z","iopub.execute_input":"2024-10-26T09:46:49.589806Z","iopub.status.idle":"2024-10-26T09:46:54.817537Z","shell.execute_reply.started":"2024-10-26T09:46:49.589765Z","shell.execute_reply":"2024-10-26T09:46:54.816499Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"#display the first 9 images with their predicted labels\nplt.figure(figsize=(6, 6))\nfor i in range(9):\n    plt.subplot(3, 3, i + 1)\n    plt.imshow(test[i].reshape(28, 28), cmap='gray') \n    plt.title(f\"Predicted: {predictions[i]}\") \n    plt.axis('off') \n\nplt.tight_layout()\nplt.show()","metadata":{"execution":{"iopub.status.busy":"2024-10-26T09:46:54.818861Z","iopub.execute_input":"2024-10-26T09:46:54.819216Z","iopub.status.idle":"2024-10-26T09:46:55.488678Z","shell.execute_reply.started":"2024-10-26T09:46:54.819178Z","shell.execute_reply":"2024-10-26T09:46:55.487386Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"submission = pd.DataFrame({\"ImageId\": list(range(1, len(predictions) + 1)), \"Label\": predictions})\nsubmission.to_csv('/kaggle/working/submission.csv', index=False)","metadata":{"execution":{"iopub.status.busy":"2024-10-26T09:46:55.490235Z","iopub.execute_input":"2024-10-26T09:46:55.490606Z","iopub.status.idle":"2024-10-26T09:46:55.532061Z","shell.execute_reply.started":"2024-10-26T09:46:55.490568Z","shell.execute_reply":"2024-10-26T09:46:55.531075Z"},"trusted":true},"execution_count":null,"outputs":[]}]}