{"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":"none","dataSources":[{"sourceId":3004,"databundleVersionId":861823,"sourceType":"competition"}],"dockerImageVersionId":30918,"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\nimport matplotlib.pyplot as plt\nfrom sklearn.model_selection import train_test_split\nfrom tensorflow.keras.utils import to_categorical\nfrom tensorflow.keras.models import Sequential\nfrom tensorflow.keras.layers import Conv2D, MaxPooling2D, Flatten, Dense, Dropout\nfrom tensorflow.keras.optimizers import Adam\nimport seaborn as sns","metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","trusted":true,"execution":{"iopub.status.busy":"2025-02-26T10:57:19.264175Z","iopub.execute_input":"2025-02-26T10:57:19.264480Z","iopub.status.idle":"2025-02-26T10:57:22.739056Z","shell.execute_reply.started":"2025-02-26T10:57:19.264455Z","shell.execute_reply":"2025-02-26T10:57:22.738235Z"}},"outputs":[],"execution_count":null},{"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":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-26T10:57:22.740022Z","iopub.execute_input":"2025-02-26T10:57:22.740645Z","iopub.status.idle":"2025-02-26T10:57:24.795653Z","shell.execute_reply.started":"2025-02-26T10:57:22.740620Z","shell.execute_reply":"2025-02-26T10:57:24.794166Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"train.head()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-26T10:57:24.797499Z","iopub.execute_input":"2025-02-26T10:57:24.797805Z","iopub.status.idle":"2025-02-26T10:57:24.812891Z","shell.execute_reply.started":"2025-02-26T10:57:24.797779Z","shell.execute_reply":"2025-02-26T10:57:24.811892Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"test.head()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-26T10:57:24.814400Z","iopub.execute_input":"2025-02-26T10:57:24.814714Z","iopub.status.idle":"2025-02-26T10:57:24.841942Z","shell.execute_reply.started":"2025-02-26T10:57:24.814680Z","shell.execute_reply":"2025-02-26T10:57:24.840613Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"def show_sample_images(df, num_images=5):\n    fig, axes = plt.subplots(1, num_images, figsize=(10, 2))\n    pixel_cols = [col for col in df.columns if col != 'label']\n    for i, ax in enumerate(axes):\n        # get one image (first num_images rows)\n        image = df.iloc[i][pixel_cols].values.astype(np.float32)\n        # Normalize for visualization (if not already 0-255)\n        image = image.reshape(28, 28)\n        ax.imshow(image, cmap='gray')\n        ax.axis('off')\n        if 'label' in df.columns:\n            ax.set_title(f\"Label: {df.iloc[i]['label']}\")\n    plt.show()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-26T10:57:24.842919Z","iopub.execute_input":"2025-02-26T10:57:24.843246Z","iopub.status.idle":"2025-02-26T10:57:24.864839Z","shell.execute_reply.started":"2025-02-26T10:57:24.843219Z","shell.execute_reply":"2025-02-26T10:57:24.863267Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"show_sample_images(train, num_images=5)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-26T10:57:24.865856Z","iopub.execute_input":"2025-02-26T10:57:24.866146Z","iopub.status.idle":"2025-02-26T10:57:25.311992Z","shell.execute_reply.started":"2025-02-26T10:57:24.866097Z","shell.execute_reply":"2025-02-26T10:57:25.311135Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"sns.set_theme(style=\"darkgrid\", palette=\"muted\")\nplt.figure(figsize=(10, 5))\nsns.countplot(x=train[\"label\"], palette=\"viridis\")\nplt.title(\"Class Distribution in Training Data\", fontsize=14)\nplt.xlabel(\"Label\")\nplt.ylabel(\"Count\")\nplt.show()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-26T10:57:25.312910Z","iopub.execute_input":"2025-02-26T10:57:25.313266Z","iopub.status.idle":"2025-02-26T10:57:25.523615Z","shell.execute_reply.started":"2025-02-26T10:57:25.313243Z","shell.execute_reply":"2025-02-26T10:57:25.522065Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"X = train.drop(\"label\", axis=1).values.astype(np.float32)\ny = train[\"label\"].values","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-26T10:57:25.526268Z","iopub.execute_input":"2025-02-26T10:57:25.526533Z","iopub.status.idle":"2025-02-26T10:57:25.605296Z","shell.execute_reply.started":"2025-02-26T10:57:25.526511Z","shell.execute_reply":"2025-02-26T10:57:25.603923Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"X = X / 255.0\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-26T10:57:25.606636Z","iopub.execute_input":"2025-02-26T10:57:25.606985Z","iopub.status.idle":"2025-02-26T10:57:25.637431Z","shell.execute_reply.started":"2025-02-26T10:57:25.606871Z","shell.execute_reply":"2025-02-26T10:57:25.635518Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"X_test = test.values.astype(np.float32) / 255.0\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-26T10:57:25.638588Z","iopub.execute_input":"2025-02-26T10:57:25.638854Z","iopub.status.idle":"2025-02-26T10:57:25.690340Z","shell.execute_reply.started":"2025-02-26T10:57:25.638831Z","shell.execute_reply":"2025-02-26T10:57:25.689451Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"X = X.reshape(-1, 28, 28, 1)\nX_test = X_test.reshape(-1, 28, 28, 1)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-26T10:57:25.691059Z","iopub.execute_input":"2025-02-26T10:57:25.691263Z","iopub.status.idle":"2025-02-26T10:57:25.694950Z","shell.execute_reply.started":"2025-02-26T10:57:25.691244Z","shell.execute_reply":"2025-02-26T10:57:25.694085Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"num_classes = len(np.unique(y))\ny_cat = to_categorical(y, num_classes)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-26T10:57:25.695761Z","iopub.execute_input":"2025-02-26T10:57:25.695983Z","iopub.status.idle":"2025-02-26T10:57:25.718626Z","shell.execute_reply.started":"2025-02-26T10:57:25.695960Z","shell.execute_reply":"2025-02-26T10:57:25.717049Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"X_train, X_val, y_train, y_val = train_test_split(X, y_cat, test_size=0.2, random_state=42)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-26T10:57:25.719912Z","iopub.execute_input":"2025-02-26T10:57:25.720363Z","iopub.status.idle":"2025-02-26T10:57:25.966768Z","shell.execute_reply.started":"2025-02-26T10:57:25.720323Z","shell.execute_reply":"2025-02-26T10:57:25.965633Z"}},"outputs":[],"execution_count":null},{"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(num_classes, activation='softmax')\n])","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-26T10:57:25.967778Z","iopub.execute_input":"2025-02-26T10:57:25.968034Z","iopub.status.idle":"2025-02-26T10:57:26.043430Z","shell.execute_reply.started":"2025-02-26T10:57:25.968014Z","shell.execute_reply":"2025-02-26T10:57:26.042338Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"model.compile(optimizer=Adam(), loss='categorical_crossentropy', metrics=['accuracy'])\nmodel.summary()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-26T10:57:26.044177Z","iopub.execute_input":"2025-02-26T10:57:26.044423Z","iopub.status.idle":"2025-02-26T10:57:26.074424Z","shell.execute_reply.started":"2025-02-26T10:57:26.044402Z","shell.execute_reply":"2025-02-26T10:57:26.073629Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"history = model.fit(X_train, y_train, validation_data=(X_val, y_val),\n                    epochs=10, batch_size=64)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-26T10:57:26.075166Z","iopub.execute_input":"2025-02-26T10:57:26.075437Z","iopub.status.idle":"2025-02-26T10:59:33.572605Z","shell.execute_reply.started":"2025-02-26T10:57:26.075410Z","shell.execute_reply":"2025-02-26T10:59:33.571207Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"plt.figure(figsize=(12, 5))","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-26T10:59:33.573913Z","iopub.execute_input":"2025-02-26T10:59:33.574277Z","iopub.status.idle":"2025-02-26T10:59:33.585007Z","shell.execute_reply.started":"2025-02-26T10:59:33.574249Z","shell.execute_reply":"2025-02-26T10:59:33.583698Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# Plot accuracy\nplt.subplot(1, 2, 1)\nplt.plot(history.history['accuracy'], label='Train Accuracy')\nplt.plot(history.history['val_accuracy'], label='Validation Accuracy')\nplt.title(\"Accuracy over Epochs\")\nplt.xlabel(\"Epoch\")\nplt.ylabel(\"Accuracy\")\nplt.legend()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-26T10:59:33.586237Z","iopub.execute_input":"2025-02-26T10:59:33.586631Z","iopub.status.idle":"2025-02-26T10:59:33.845534Z","shell.execute_reply.started":"2025-02-26T10:59:33.586596Z","shell.execute_reply":"2025-02-26T10:59:33.844360Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"plt.subplot(1, 2, 2)\nplt.plot(history.history['loss'], label='Train Loss')\nplt.plot(history.history['val_loss'], label='Validation Loss')\nplt.title(\"Loss over Epochs\")\nplt.xlabel(\"Epoch\")\nplt.ylabel(\"Loss\")\nplt.legend()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-26T10:59:33.846386Z","iopub.execute_input":"2025-02-26T10:59:33.846685Z","iopub.status.idle":"2025-02-26T10:59:34.125836Z","shell.execute_reply.started":"2025-02-26T10:59:33.846656Z","shell.execute_reply":"2025-02-26T10:59:34.124374Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"predictions_prob = model.predict(X_test)\npredictions = np.argmax(predictions_prob, axis=1)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-26T10:59:34.126948Z","iopub.execute_input":"2025-02-26T10:59:34.127355Z","iopub.status.idle":"2025-02-26T10:59:39.202173Z","shell.execute_reply.started":"2025-02-26T10:59:34.127319Z","shell.execute_reply":"2025-02-26T10:59:39.201200Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"submission_df = pd.DataFrame({\n    \"ImageId\": np.arange(1, len(predictions) + 1),\n    \"Prediction\": predictions\n})","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-26T10:59:39.203178Z","iopub.execute_input":"2025-02-26T10:59:39.203456Z","iopub.status.idle":"2025-02-26T10:59:39.208416Z","shell.execute_reply.started":"2025-02-26T10:59:39.203433Z","shell.execute_reply":"2025-02-26T10:59:39.207207Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"submission_df.to_csv(\"submissionp.csv\", index=False)\nprint(\"Submission saved to submission.csv\")","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-26T10:59:39.209296Z","iopub.execute_input":"2025-02-26T10:59:39.209569Z","iopub.status.idle":"2025-02-26T10:59:39.253562Z","shell.execute_reply.started":"2025-02-26T10:59:39.209539Z","shell.execute_reply":"2025-02-26T10:59:39.252353Z"}},"outputs":[],"execution_count":null}]}