{"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":"# 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 pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport tensorflow as tf\nfrom tensorflow.keras.models import Sequential\nfrom tensorflow.keras.layers import Conv2D, MaxPooling2D, Flatten, Dense, Dropout\nfrom tensorflow.keras.utils import to_categorical\nfrom sklearn.model_selection import train_test_split\n\n# Load the data\ntrain_df = pd.read_csv(\"/kaggle/input/digit-recognizer/train.csv\")\ntest_df = pd.read_csv(\"/kaggle/input/digit-recognizer/test.csv\")\n\n# Extract features and labels\nX = train_df.drop(columns=['label']).values\ny = train_df['label'].values\n\n# Reshape data for CNN input (28x28 images, 1 channel for grayscale)\nX = X.reshape(-1, 28, 28, 1) / 255.0  # Normalize pixel values\ny = to_categorical(y, num_classes=10)  # One-hot encode labels\n\n# Split into train 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# Define the CNN model\nmodel = 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')  # 10 output classes (digits 0-9)\n])\n\n# Compile the model\nmodel.compile(optimizer='adam', loss='categorical_crossentropy', metrics=['accuracy'])\n\n# Train the model\nmodel.fit(X_train, y_train, validation_data=(X_val, y_val), epochs=10, batch_size=32)\n\n# Load test data and reshape\nX_test = test_df.values.reshape(-1, 28, 28, 1) / 255.0\n\n# Make predictions\ntest_preds = np.argmax(model.predict(X_test), axis=1)\n\n# Create submission file\nsubmission = pd.DataFrame({'ImageId': np.arange(1, len(test_preds) + 1), 'Label': test_preds})\nsubmission.to_csv(\"submission.csv\", index=False)\nprint(\"Submission file saved.\")\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-03-18T20:07:21.786375Z","iopub.execute_input":"2025-03-18T20:07:21.786805Z","iopub.status.idle":"2025-03-18T20:11:23.239323Z","shell.execute_reply.started":"2025-03-18T20:07:21.786762Z","shell.execute_reply":"2025-03-18T20:11:23.238118Z"}},"outputs":[],"execution_count":null}]}