{"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":30804,"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\nimport numpy as np # linear algebra\nimport pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)\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","trusted":true,"execution":{"iopub.status.busy":"2024-12-15T20:51:39.887801Z","iopub.execute_input":"2024-12-15T20:51:39.888213Z","iopub.status.idle":"2024-12-15T20:51:39.894755Z","shell.execute_reply.started":"2024-12-15T20:51:39.888178Z","shell.execute_reply":"2024-12-15T20:51:39.893403Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import os\n\n# List all files in the /kaggle/input directory\nfor dirname, _, filenames in os.walk('/kaggle/input'):\n    for filename in filenames:\n        print(os.path.join(dirname, filename))\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-15T20:52:38.680408Z","iopub.execute_input":"2024-12-15T20:52:38.680829Z","iopub.status.idle":"2024-12-15T20:52:38.687460Z","shell.execute_reply.started":"2024-12-15T20:52:38.680788Z","shell.execute_reply":"2024-12-15T20:52:38.685788Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"train_csv_path: str = \"../input/digit-recognizer/train.csv\"\ntest_csv_path: str = \"../input/digit-recognizer/test.csv\"","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-15T20:54:52.531440Z","iopub.execute_input":"2024-12-15T20:54:52.531900Z","iopub.status.idle":"2024-12-15T20:54:52.536801Z","shell.execute_reply.started":"2024-12-15T20:54:52.531864Z","shell.execute_reply":"2024-12-15T20:54:52.535610Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"**1. Import Necessary Libraries**\n\nBegin by importing all required libraries:","metadata":{}},{"cell_type":"code","source":"import cv2\nimport numpy as np\nimport pandas as pd\nimport seaborn as sns\nfrom sklearn.model_selection import cross_val_score\nfrom sklearn.model_selection import StratifiedKFold\nfrom sklearn.naive_bayes import BernoulliNB\nfrom matplotlib import pyplot as plt\nfrom typing import List\n%matplotlib inline\nsns.set_style(\"darkgrid\")","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-15T20:55:03.786631Z","iopub.execute_input":"2024-12-15T20:55:03.787017Z","iopub.status.idle":"2024-12-15T20:55:03.795117Z","shell.execute_reply.started":"2024-12-15T20:55:03.786984Z","shell.execute_reply":"2024-12-15T20:55:03.793550Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"**2. Load the Data**\n\nUse the correct paths to load the train.csv and test.csv files into Pandas DataFrames.","metadata":{}},{"cell_type":"code","source":"import pandas as pd\n\n# File paths (adjust these paths based on the above checks)\ntrain_csv_path = '/kaggle/input/digit-recognizer/train.csv'\ntest_csv_path = '/kaggle/input/digit-recognizer/test.csv'\n\n# Load the data\ntrain_df = pd.read_csv(train_csv_path)\ntest_df = pd.read_csv(test_csv_path)\n\n# Display the first few rows to confirm successful loading\nprint(train_df.head())\nprint(test_df.head())\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-15T21:00:04.479765Z","iopub.execute_input":"2024-12-15T21:00:04.480939Z","iopub.status.idle":"2024-12-15T21:00:10.106676Z","shell.execute_reply.started":"2024-12-15T21:00:04.480886Z","shell.execute_reply":"2024-12-15T21:00:10.105504Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"**3. Preprocess the Data**\n\nExtract features (X) and labels (y) from the training dataset.\nNormalize the pixel values to a range of [0, 1].\nNormalize the test data as well.","metadata":{}},{"cell_type":"code","source":"# Separate features and labels\nX = train_df.iloc[:, 1:].values / 255.0  # Normalize pixel values to [0, 1]\ny = train_df.iloc[:, 0].values           # Labels (digits)\n\n# Normalize the test dataset\nX_test = test_df.values / 255.0\n\n# Check the shapes of datasets\nprint(f\"Training Data Shape: {X.shape}\")\nprint(f\"Training Labels Shape: {y.shape}\")\nprint(f\"Test Data Shape: {X_test.shape}\")","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-15T21:01:22.606299Z","iopub.execute_input":"2024-12-15T21:01:22.606723Z","iopub.status.idle":"2024-12-15T21:01:22.840560Z","shell.execute_reply.started":"2024-12-15T21:01:22.606686Z","shell.execute_reply":"2024-12-15T21:01:22.839439Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"**4. Split Data into Training and Validation Sets**\n\nSplit the training data into a training set and a validation set to evaluate the model's performance.","metadata":{}},{"cell_type":"code","source":"from sklearn.model_selection import train_test_split\n\n# Ensure X and y are consistent\nprint(f\"X shape: {X.shape}, y shape: {y.shape}\")\n\n# Test the train-test split\nX_train, X_val, y_train, y_val = train_test_split(X, y, test_size=0.2, random_state=42)\n\n# Check the shapes of the splits\nprint(f\"Training Set Shape: {X_train.shape}\")\nprint(f\"Validation Set Shape: {X_val.shape}\")\nprint(f\"Training Labels Shape: {y_train.shape}\")\nprint(f\"Validation Labels Shape: {y_val.shape}\")","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-15T21:05:10.322382Z","iopub.execute_input":"2024-12-15T21:05:10.323368Z","iopub.status.idle":"2024-12-15T21:05:11.465693Z","shell.execute_reply.started":"2024-12-15T21:05:10.323326Z","shell.execute_reply":"2024-12-15T21:05:11.464568Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"**5. Train the Gaussian Naive Bayes Model**\n\nTrain the model using the GaussianNB class from Scikit-Learn.","metadata":{}},{"cell_type":"code","source":"# Import necessary libraries\nimport numpy as np\nimport pandas as pd\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.naive_bayes import GaussianNB\nfrom sklearn.metrics import accuracy_score\n\n# Assuming you have already preprocessed the data\n# X: Feature matrix (normalized pixel values)\n# y: Labels (digits)\n\n# Split the 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\n# Initialize the Gaussian Naive Bayes model\nmodel = GaussianNB()\n\n# Train the model\nmodel.fit(X_train, y_train)\n\n# Validate the model\ny_val_pred = model.predict(X_val)\nval_accuracy = accuracy_score(y_val, y_val_pred)\n\n# Print the validation accuracy\nprint(f\"Validation Accuracy: {val_accuracy:.4f}\")","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-15T21:07:21.643153Z","iopub.execute_input":"2024-12-15T21:07:21.643578Z","iopub.status.idle":"2024-12-15T21:07:22.874491Z","shell.execute_reply.started":"2024-12-15T21:07:21.643530Z","shell.execute_reply":"2024-12-15T21:07:22.873304Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"**6. Train the Gaussian Naive Bayes Model**\n\nTrain the model on the training set using the GaussianNB class.","metadata":{}},{"cell_type":"code","source":"# Train the Gaussian Naive Bayes model\nmodel = GaussianNB()\nmodel.fit(X_train, y_train)\n\n# Validate the model\ny_val_pred = model.predict(X_val)\n\n# Calculate validation accuracy\nfrom sklearn.metrics import accuracy_score\n\nval_accuracy = accuracy_score(y_val, y_val_pred)\nprint(f\"Validation Accuracy: {val_accuracy:.4f}\")\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-15T21:08:30.466627Z","iopub.execute_input":"2024-12-15T21:08:30.467085Z","iopub.status.idle":"2024-12-15T21:08:31.272605Z","shell.execute_reply.started":"2024-12-15T21:08:30.467047Z","shell.execute_reply":"2024-12-15T21:08:31.271497Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"**7. Evaluate the Model Performance**\n\nCheck for potential performance issues or areas of improvement using a confusion matrix.","metadata":{}},{"cell_type":"code","source":"from sklearn.metrics import confusion_matrix\nimport seaborn as sns\nimport matplotlib.pyplot as plt\n\n# Confusion Matrix\nconf_matrix = confusion_matrix(y_val, y_val_pred)\n\n# Visualize the confusion matrix\nplt.figure(figsize=(10, 8))\nsns.heatmap(conf_matrix, annot=True, fmt='d', cmap='Blues', xticklabels=range(10), yticklabels=range(10))\nplt.xlabel('Predicted Label')\nplt.ylabel('True Label')\nplt.title('Confusion Matrix for Validation Set')\nplt.show()\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-15T21:09:10.339662Z","iopub.execute_input":"2024-12-15T21:09:10.340062Z","iopub.status.idle":"2024-12-15T21:09:11.384303Z","shell.execute_reply.started":"2024-12-15T21:09:10.340029Z","shell.execute_reply":"2024-12-15T21:09:11.383001Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"**8. Make Predictions on the Test Set**\n\nUse the trained model to make predictions on the test dataset (X_test).","metadata":{}},{"cell_type":"code","source":"# Predict the test set labels\ntest_predictions = model.predict(X_test)\n\n# Display the first few predictions\nprint(test_predictions[:10])","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-15T21:09:48.210191Z","iopub.execute_input":"2024-12-15T21:09:48.211546Z","iopub.status.idle":"2024-12-15T21:09:49.748238Z","shell.execute_reply.started":"2024-12-15T21:09:48.211471Z","shell.execute_reply":"2024-12-15T21:09:49.747021Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"**9. Create the Submission File**\nFormat the predictions according to Kaggle’s requirements:\n\nImageId: Sequential ID starting from 1.\nLabel: Predicted digit.","metadata":{}},{"cell_type":"code","source":"# Prepare the submission DataFrame\nsubmission = pd.DataFrame({'ImageId': np.arange(1, len(test_predictions) + 1), 'Label': test_predictions})\n\n# Save the submission file\nsubmission.to_csv('submission.csv', index=False)\nprint(\"Submission file created successfully!\")","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-15T21:11:15.859265Z","iopub.execute_input":"2024-12-15T21:11:15.859696Z","iopub.status.idle":"2024-12-15T21:11:15.892988Z","shell.execute_reply.started":"2024-12-15T21:11:15.859664Z","shell.execute_reply":"2024-12-15T21:11:15.891733Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"","metadata":{"trusted":true},"outputs":[],"execution_count":null}]}