{"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":"gpu","dataSources":[{"sourceId":3004,"databundleVersionId":861823,"sourceType":"competition"}],"dockerImageVersionId":30919,"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\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":"2025-02-27T09:40:24.609366Z","iopub.execute_input":"2025-02-27T09:40:24.609717Z","iopub.status.idle":"2025-02-27T09:40:24.909073Z","shell.execute_reply.started":"2025-02-27T09:40:24.609690Z","shell.execute_reply":"2025-02-27T09:40:24.908375Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import numpy as np\nimport pandas as pd\nimport tensorflow as tf\nfrom tensorflow import keras\nfrom tensorflow.keras.models import Sequential\nfrom tensorflow.keras.layers import Conv2D, MaxPooling2D, Flatten, Dense, Dropout\nfrom tensorflow.keras.utils import to_categorical\nimport matplotlib.pyplot as plt\nfrom sklearn.model_selection import train_test_split\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-27T09:40:24.910077Z","iopub.execute_input":"2025-02-27T09:40:24.910478Z","iopub.status.idle":"2025-02-27T09:40:36.759211Z","shell.execute_reply.started":"2025-02-27T09:40:24.910457Z","shell.execute_reply":"2025-02-27T09:40:36.758313Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# Load dataset\ntrain_df = pd.read_csv(\"/kaggle/input/digit-recognizer/train.csv\")\ntest_df = pd.read_csv(\"/kaggle/input/digit-recognizer/test.csv\")\n\n# Split labels and features\ny = train_df[\"label\"].values\nX = train_df.drop(\"label\", axis=1).values\n\n# Normalize pixel values (0-255 → 0-1)\nX = X / 255.0\ntest_data = test_df.values / 255.0\n\n# Reshape into (28,28,1) for CNN\nX = X.reshape(-1, 28, 28, 1)\ntest_data = test_data.reshape(-1, 28, 28, 1)\n\n# Convert labels to categorical (One-hot encoding)\ny = to_categorical(y, num_classes=10)\n\n# Split into training and validation sets\nX_train, X_val, y_train, y_val = train_test_split(X, y, test_size=0.1, random_state=42)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-27T09:40:36.760836Z","iopub.execute_input":"2025-02-27T09:40:36.761411Z","iopub.status.idle":"2025-02-27T09:40:41.462681Z","shell.execute_reply.started":"2025-02-27T09:40:36.761387Z","shell.execute_reply":"2025-02-27T09:40:41.462033Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"model = Sequential([\n    Conv2D(32, (3,3), activation='relu', input_shape=(28,28,1)),\n    MaxPooling2D((2,2)),\n    Conv2D(64, (3,3), activation='relu'),\n    MaxPooling2D((2,2)),\n    Flatten(),\n    Dense(128, activation='relu'),\n    Dropout(0.5),\n    Dense(10, activation='softmax')\n])\n\nmodel.compile(optimizer='adam', loss='categorical_crossentropy', metrics=['accuracy'])\n\n# Model Summary\nmodel.summary()\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-27T09:40:41.463849Z","iopub.execute_input":"2025-02-27T09:40:41.464083Z","iopub.status.idle":"2025-02-27T09:40:43.591131Z","shell.execute_reply.started":"2025-02-27T09:40:41.464064Z","shell.execute_reply":"2025-02-27T09:40:43.590456Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"history = model.fit(\n    X_train, y_train,\n    epochs=15,\n    validation_data=(X_val, y_val),\n    batch_size=64\n)\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-27T09:40:43.592002Z","iopub.execute_input":"2025-02-27T09:40:43.592252Z","iopub.status.idle":"2025-02-27T09:41:11.027086Z","shell.execute_reply.started":"2025-02-27T09:40:43.592233Z","shell.execute_reply":"2025-02-27T09:41:11.026363Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# Evaluate Model\ntest_loss, test_acc = model.evaluate(X_val, y_val)\nprint(f\"Validation Accuracy: {test_acc:.4f}\")\n\n# Predict on test data\npredictions = model.predict(test_data)\npredicted_labels = np.argmax(predictions, axis=1)\n\n# Create submission file\nsubmission = pd.DataFrame({\"ImageId\": np.arange(1, len(predicted_labels) + 1), \"Label\": predicted_labels})\nsubmission.to_csv(\"submission.csv\", index=False)\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-27T09:41:11.028123Z","iopub.execute_input":"2025-02-27T09:41:11.028442Z","iopub.status.idle":"2025-02-27T09:41:14.058676Z","shell.execute_reply.started":"2025-02-27T09:41:11.028410Z","shell.execute_reply":"2025-02-27T09:41:14.058029Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"plt.figure(figsize=(10,5))\nfor i in range(10):\n    plt.subplot(2, 5, i+1)\n    plt.imshow(X_val[i].reshape(28,28), cmap=\"gray\")\n    plt.title(f\"Pred: {np.argmax(model.predict(X_val[i].reshape(1,28,28,1)))}\")\n    plt.axis(\"off\")\nplt.show()\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-27T09:41:14.059505Z","iopub.execute_input":"2025-02-27T09:41:14.059743Z","iopub.status.idle":"2025-02-27T09:41:15.395664Z","shell.execute_reply.started":"2025-02-27T09:41:14.059716Z","shell.execute_reply":"2025-02-27T09:41:15.394769Z"}},"outputs":[],"execution_count":null}]}