{"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":"#Importing Libraries\n\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nfrom sklearn.model_selection import train_test_split\nfrom tensorflow.keras.models import Sequential\nfrom tensorflow.keras.layers import Dense, Conv2D, MaxPooling2D, Flatten, Dropout\nfrom tensorflow.keras.utils import to_categorical","metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","trusted":true,"execution":{"iopub.status.busy":"2024-11-24T08:57:19.880716Z","iopub.execute_input":"2024-11-24T08:57:19.881483Z","iopub.status.idle":"2024-11-24T08:57:37.560313Z","shell.execute_reply.started":"2024-11-24T08:57:19.881414Z","shell.execute_reply":"2024-11-24T08:57:37.559082Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"# **Loading the Data**","metadata":{}},{"cell_type":"code","source":"# Load the training and test datasets\ntrain_data = pd.read_csv(\"/kaggle/input/digit-recognizer/train.csv\")\ntest_data = pd.read_csv(\"/kaggle/input/digit-recognizer/test.csv\")\n\n# Separate labels and features\nX = train_data.iloc[:, 1:].values  # All columns except the first (label)\ny = train_data['label'].values    # Labels column","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-11-24T09:13:57.423017Z","iopub.execute_input":"2024-11-24T09:13:57.423437Z","iopub.status.idle":"2024-11-24T09:14:02.855035Z","shell.execute_reply.started":"2024-11-24T09:13:57.423399Z","shell.execute_reply":"2024-11-24T09:14:02.853646Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"# **Pre-processing the Data**","metadata":{}},{"cell_type":"code","source":"# Normalize pixel values to the range [0, 1]\nX = X / 255.0\ntest_data = test_data / 255.0\n\n# Reshape the data into 28x28x1 for CNN\nX = X.reshape(-1, 28, 28, 1)  # -1 automatically calculates the number of rows\ntest_data = test_data.values.reshape(-1, 28, 28, 1)\n\n# One-hot encode the labels\ny = to_categorical(y, num_classes=10)\n\n# Split the training data into training and validation sets\nX_train, X_val, y_train, y_val = train_test_split(X, y, test_size=0.2, random_state=42)\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-11-24T09:16:35.632616Z","iopub.execute_input":"2024-11-24T09:16:35.633068Z","iopub.status.idle":"2024-11-24T09:16:36.283132Z","shell.execute_reply.started":"2024-11-24T09:16:35.633029Z","shell.execute_reply":"2024-11-24T09:16:36.281759Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"# **Defining the CNN Model**","metadata":{}},{"cell_type":"code","source":"model = Sequential([\n    Conv2D(32, kernel_size=(3, 3), activation='relu', input_shape=(28, 28, 1)),\n    MaxPooling2D(pool_size=(2, 2)),\n    Dropout(0.25),\n\n    Conv2D(64, kernel_size=(3, 3), activation='relu'),\n    MaxPooling2D(pool_size=(2, 2)),\n    Dropout(0.25),\n\n    Flatten(),\n    Dense(128, activation='relu'),\n    Dropout(0.5),\n    Dense(10, activation='softmax')  # 10 classes for digits 0-9\n])","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-11-24T09:17:35.105119Z","iopub.execute_input":"2024-11-24T09:17:35.105546Z","iopub.status.idle":"2024-11-24T09:17:35.406177Z","shell.execute_reply.started":"2024-11-24T09:17:35.105492Z","shell.execute_reply":"2024-11-24T09:17:35.405013Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"# **Compiling the Model**","metadata":{}},{"cell_type":"code","source":"model.compile(optimizer='adam', \n              loss='categorical_crossentropy', \n              metrics=['accuracy'])","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-11-24T09:17:50.341371Z","iopub.execute_input":"2024-11-24T09:17:50.342152Z","iopub.status.idle":"2024-11-24T09:17:50.359150Z","shell.execute_reply.started":"2024-11-24T09:17:50.342108Z","shell.execute_reply":"2024-11-24T09:17:50.357934Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"# **Training the Model**","metadata":{}},{"cell_type":"code","source":"history = model.fit(\n    X_train, y_train,\n    validation_data=(X_val, y_val),\n    epochs=20,\n    batch_size=64,\n    verbose=2\n)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-11-24T09:20:28.993158Z","iopub.execute_input":"2024-11-24T09:20:28.993595Z","iopub.status.idle":"2024-11-24T09:25:46.341058Z","shell.execute_reply.started":"2024-11-24T09:20:28.993549Z","shell.execute_reply":"2024-11-24T09:25:46.339848Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"# **Evaluating the Model**","metadata":{}},{"cell_type":"code","source":"# Plot training and validation accuracy\nplt.plot(history.history['accuracy'], label='Train Accuracy')\nplt.plot(history.history['val_accuracy'], label='Validation Accuracy')\nplt.legend()\nplt.show()\n\n# Evaluate on validation set\nval_loss, val_accuracy = model.evaluate(X_val, y_val, verbose=0)\nprint(f\"Validation Accuracy: {val_accuracy:.2f}\")\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-11-24T09:25:48.720327Z","iopub.execute_input":"2024-11-24T09:25:48.720844Z","iopub.status.idle":"2024-11-24T09:25:50.568798Z","shell.execute_reply.started":"2024-11-24T09:25:48.720733Z","shell.execute_reply":"2024-11-24T09:25:50.567391Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"# **Predicting on Test Data**","metadata":{}},{"cell_type":"code","source":"predictions = model.predict(test_data)\npredicted_labels = np.argmax(predictions, axis=1)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-11-24T09:28:08.270993Z","iopub.execute_input":"2024-11-24T09:28:08.271402Z","iopub.status.idle":"2024-11-24T09:28:13.863565Z","shell.execute_reply.started":"2024-11-24T09:28:08.271367Z","shell.execute_reply":"2024-11-24T09:28:13.862419Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"# **Preparing Submission File**","metadata":{}},{"cell_type":"code","source":"submission = pd.DataFrame({\n    \"ImageId\": np.arange(1, len(predicted_labels) + 1),\n    \"Label\": predicted_labels\n})\nsubmission.to_csv(\"submission.csv\", index=False)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-11-24T09:31:35.362315Z","iopub.execute_input":"2024-11-24T09:31:35.362749Z","iopub.status.idle":"2024-11-24T09:31:35.391857Z","shell.execute_reply.started":"2024-11-24T09:31:35.362710Z","shell.execute_reply":"2024-11-24T09:31:35.390625Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"","metadata":{"trusted":true},"outputs":[],"execution_count":null}]}