{"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,"execution":{"iopub.status.busy":"2025-04-01T16:06:01.840873Z","iopub.execute_input":"2025-04-01T16:06:01.841315Z","iopub.status.idle":"2025-04-01T16:06:01.852403Z","shell.execute_reply.started":"2025-04-01T16:06:01.841284Z","shell.execute_reply":"2025-04-01T16:06:01.850780Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"\n\nimport numpy as np # linear algebra\nimport pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)\n\ntrain = pd.read_csv(\"/kaggle/input/digit-recognizer/train.csv\")\ntest = pd.read_csv(\"/kaggle/input/digit-recognizer/test.csv\")\n\nprint(f\"Train shape: {train.shape}, Test shape: {test.shape}\")\ntrain.head()","metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","trusted":true,"execution":{"iopub.status.busy":"2025-04-01T16:06:01.854163Z","iopub.execute_input":"2025-04-01T16:06:01.854659Z","iopub.status.idle":"2025-04-01T16:06:05.889621Z","shell.execute_reply.started":"2025-04-01T16:06:01.854591Z","shell.execute_reply":"2025-04-01T16:06:05.888406Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"#Preprocessing the data\n\nimport numpy as np\n\n#separate labels and features\n\nX = train.drop(\"label\", axis=1).values\ny = train[\"label\"].values\n\n#normalize pixel values \ntest = test/255.0\n\n#reshape data for CNN input, 28x28 images w/ 1 channel\n\nX = X.reshape(-1, 28, 28, 1)\ntest = test.to_numpy().reshape(-1, 28, 28, 1)\n\n#convert labels to categorical (one-hot)\n\nfrom tensorflow.keras.utils import to_categorical\ny = to_categorical(y, num_classes=10)\n\n#split into training and validation sets\n\nfrom sklearn.model_selection import train_test_split\n\nX_train, X_val, y_train, y_val = train_test_split(X, y, test_size=0.2, random_state=42)\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-04-01T16:06:05.891893Z","iopub.execute_input":"2025-04-01T16:06:05.892263Z","iopub.status.idle":"2025-04-01T16:06:06.480968Z","shell.execute_reply.started":"2025-04-01T16:06:05.892221Z","shell.execute_reply":"2025-04-01T16:06:06.479835Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# we will build a CNN for this\nimport tensorflow as tf\nfrom tensorflow import keras\nmodel = keras.Sequential([\n    keras.layers.Conv2D(32, (3,3), activation='relu', input_shape=(28,28,1)),\n    keras.layers.MaxPooling2D(2,2),\n    keras.layers.Conv2D(64, (3,3), activation= 'relu'),\n    keras.layers.Flatten(),\n    keras.layers.Dense(128, activation='relu'),\n    keras.layers.Dense(10, activation='softmax')\n])\n\n#compile the model\n\nmodel.compile(optimizer='adam', loss='categorical_crossentropy', metrics=['accuracy'])\n\n#train the model \nhistory = model.fit(X_train, y_train, epochs=10, validation_data=(X_val, y_val), batch_size=64)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-04-01T16:06:06.482583Z","iopub.execute_input":"2025-04-01T16:06:06.483040Z","iopub.status.idle":"2025-04-01T16:09:12.600723Z","shell.execute_reply.started":"2025-04-01T16:06:06.482997Z","shell.execute_reply":"2025-04-01T16:09:12.599700Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"val_loss, val_acc = model.evaluate(X_val, y_val)\nprint(f\"Validation Accuracy: {val_acc:.4f}\")\n\nimport matplotlib.pyplot as plt\nplt.plot(history.history['accuracy'], label='Train Accuracy')\nplt.plot(history.history['val_accuracy'], label='Validation Accuracy')\nplt.legend()\nplt.title(\"Model Accuracy Over Epochs\")\nplt.show","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-04-01T16:09:12.601973Z","iopub.execute_input":"2025-04-01T16:09:12.602282Z","iopub.status.idle":"2025-04-01T16:09:14.857239Z","shell.execute_reply.started":"2025-04-01T16:09:12.602255Z","shell.execute_reply":"2025-04-01T16:09:14.856001Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"test_predictions = model.predict(test)\ntest_predictions = np.argmax(test_predictions, axis=1)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-04-01T16:09:14.858281Z","iopub.execute_input":"2025-04-01T16:09:14.858665Z","iopub.status.idle":"2025-04-01T16:09:21.579619Z","shell.execute_reply.started":"2025-04-01T16:09:14.858602Z","shell.execute_reply":"2025-04-01T16:09:21.578471Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"submission = pd.DataFrame({\"ImageId\": list(range(1, len(test_predictions) + 1)), \"Label\": test_predictions})\nsubmission.to_csv(\"/kaggle/working/submission.csv\", index=False)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-04-01T16:18:42.258410Z","iopub.execute_input":"2025-04-01T16:18:42.258808Z","iopub.status.idle":"2025-04-01T16:18:42.294876Z","shell.execute_reply.started":"2025-04-01T16:18:42.258779Z","shell.execute_reply":"2025-04-01T16:18:42.293728Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import os\nprint(\"current directory:\", os.getcwd())\nprint(os.listdir(\"/kaggle/working\"))","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-04-01T16:21:04.726814Z","iopub.execute_input":"2025-04-01T16:21:04.727190Z","iopub.status.idle":"2025-04-01T16:21:04.735085Z","shell.execute_reply.started":"2025-04-01T16:21:04.727163Z","shell.execute_reply":"2025-04-01T16:21:04.733962Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"from IPython.display import FileLink\nFileLink(\"/kaggle/working/submission.csv\")","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-04-01T16:22:18.536923Z","iopub.execute_input":"2025-04-01T16:22:18.537301Z","iopub.status.idle":"2025-04-01T16:22:18.544504Z","shell.execute_reply.started":"2025-04-01T16:22:18.537269Z","shell.execute_reply":"2025-04-01T16:22:18.543226Z"}},"outputs":[],"execution_count":null}]}