{"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":false,"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},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# Import required libraries\nimport numpy as np\nimport pandas as pd\nimport tensorflow as tf\nfrom tensorflow.keras import layers, models\nimport matplotlib.pyplot as plt\n\n# Load data from Kaggle dataset\ntrain_data = pd.read_csv(\"/kaggle/input/digit-recognizer/train.csv\")\ntest_data = pd.read_csv(\"/kaggle/input/digit-recognizer/test.csv\")  # Kaggle test set has no labels\n\n# Separate labels and images from training data\ntrain_labels = train_data[\"label\"].values\ntrain_images = train_data.drop(\"label\", axis=1).values\n\n# Reshape images to 28x28 grayscale and normalize pixel values (0-1)\ntrain_images = train_images.reshape(-1, 28, 28, 1) / 255.0\ntest_images = test_data.values.reshape(-1, 28, 28, 1) / 255.0  # Same preprocessing for test data\n\n# Print dataset shapes\nprint(f\"Training set: {train_images.shape}, Labels: {train_labels.shape}\")\nprint(f\"Test set: {test_images.shape}\")  # No labels in test set\n\n# Define CNN model with Dropout, Strides, and Padding\ndef create_model():\n    model = models.Sequential([\n        layers.Conv2D(32, (3, 3), strides=(1, 1), padding='same', activation='relu', input_shape=(28, 28, 1)),\n        layers.Dropout(0.2),  # Drop 20% of neurons to prevent overfitting\n\n        layers.Conv2D(64, (3, 3), strides=(1, 1), padding='same', activation='relu'),\n        layers.MaxPooling2D((2, 2), strides=(2, 2), padding='same'),  # Pool with stride 2\n        layers.Dropout(0.3),  # Dropout after pooling\n\n        layers.Conv2D(128, (3, 3), strides=(1, 1), padding='same', activation='relu'),\n        layers.MaxPooling2D((2, 2), strides=(2, 2), padding='same'),\n        layers.Dropout(0.4),\n\n        layers.Flatten(),\n        layers.Dense(256, activation='relu'),\n        layers.Dropout(0.5),  # Drop 50% of neurons before final layer\n\n        layers.Dense(10, activation='softmax')  # 10 output classes (digits 0-9)\n    ])\n    return model\n\n# Create and compile model\nmodel = create_model()\nmodel.compile(optimizer='adam', loss='sparse_categorical_crossentropy', metrics=['accuracy'])\n\n# Train the model\nhistory = model.fit(train_images, train_labels, epochs=10, validation_split=0.2, batch_size=32)\n\n# Evaluate the model on training data\ntrain_loss, train_acc = model.evaluate(train_images, train_labels, verbose=2)\nprint(f\"Training Accuracy: {train_acc:.4f}\")\n\n# Plot training history\nplt.plot(history.history['accuracy'], label='Train Accuracy')\nplt.plot(history.history['val_accuracy'], label='Validation Accuracy')\nplt.xlabel('Epoch')\nplt.ylabel('Accuracy')\nplt.legend()\nplt.title('Training and Validation Accuracy')\nplt.show()\n\n# Make predictions on test set\npredictions = model.predict(test_images)\npredicted_labels = np.argmax(predictions, axis=1)\n\n# Create submission file for Kaggle competition\nsubmission = pd.DataFrame({\"ImageId\": np.arange(1, len(predicted_labels) + 1), \"Label\": predicted_labels})\nsubmission.to_csv(\"submission.csv\", index=False)\n\nprint(\"Submission file saved: submission.csv ✅\")\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-04-16T07:25:41.853374Z","iopub.execute_input":"2025-04-16T07:25:41.853681Z","iopub.status.idle":"2025-04-16T07:44:46.512089Z","shell.execute_reply.started":"2025-04-16T07:25:41.853648Z","shell.execute_reply":"2025-04-16T07:44:46.510825Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"","metadata":{"trusted":true},"outputs":[],"execution_count":null}]}