{"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"name":"python","version":"3.10.13","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":30698,"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","execution":{"iopub.status.busy":"2024-05-30T02:15:02.214054Z","iopub.execute_input":"2024-05-30T02:15:02.214461Z","iopub.status.idle":"2024-05-30T02:15:03.421217Z","shell.execute_reply.started":"2024-05-30T02:15:02.214419Z","shell.execute_reply":"2024-05-30T02:15:03.420018Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport tensorflow as tf\nfrom tensorflow.keras import layers, models\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.preprocessing import MinMaxScaler\nfrom sklearn.metrics import classification_report, confusion_matrix\nimport seaborn as sns\n","metadata":{"execution":{"iopub.status.busy":"2024-05-30T02:30:57.005474Z","iopub.execute_input":"2024-05-30T02:30:57.005892Z","iopub.status.idle":"2024-05-30T02:30:57.012378Z","shell.execute_reply.started":"2024-05-30T02:30:57.005859Z","shell.execute_reply":"2024-05-30T02:30:57.011190Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Load 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# Preprocess data\nscaler = MinMaxScaler()\nX_train = scaler.fit_transform(train_df.drop('label', axis=1))\nX_test = scaler.transform(test_df)\n\n# Reshape for CNN input\nX_train = X_train.reshape((-1, 28, 28, 1))  # Reshape into (n_images, img_rows, img_cols, 1)\nX_test = X_test.reshape((-1, 28, 28, 1))\n\n# Labels\ny_train = train_df['label']\n\n# Split data\nX_train, X_val, y_train, y_val = train_test_split(X_train, y_train, test_size=0.1, random_state=42)\n","metadata":{"execution":{"iopub.status.busy":"2024-05-30T02:30:59.196977Z","iopub.execute_input":"2024-05-30T02:30:59.197392Z","iopub.status.idle":"2024-05-30T02:31:05.246591Z","shell.execute_reply.started":"2024-05-30T02:30:59.197358Z","shell.execute_reply":"2024-05-30T02:31:05.245548Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"model = models.Sequential([\n    layers.Conv2D(32, (3, 3), activation='relu', input_shape=(28, 28, 1)),\n    layers.MaxPooling2D((2, 2)),\n    layers.Conv2D(64, (3, 3), activation='relu'),\n    layers.MaxPooling2D((2, 2)),\n    layers.Flatten(),\n    layers.Dense(64, activation='relu'),\n    layers.Dense(10, activation='softmax')\n])\n\nmodel.compile(optimizer='adam',\n              loss='sparse_categorical_crossentropy',\n              metrics=['accuracy'])\n","metadata":{"execution":{"iopub.status.busy":"2024-05-30T02:31:09.692791Z","iopub.execute_input":"2024-05-30T02:31:09.693316Z","iopub.status.idle":"2024-05-30T02:31:09.770977Z","shell.execute_reply.started":"2024-05-30T02:31:09.693274Z","shell.execute_reply":"2024-05-30T02:31:09.769630Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"history = model.fit(X_train, y_train, epochs=10, validation_data=(X_val, y_val))\n","metadata":{"execution":{"iopub.status.busy":"2024-05-30T02:31:12.779276Z","iopub.execute_input":"2024-05-30T02:31:12.780278Z","iopub.status.idle":"2024-05-30T02:34:20.549323Z","shell.execute_reply.started":"2024-05-30T02:31:12.780243Z","shell.execute_reply":"2024-05-30T02:34:20.548291Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Plot training & validation accuracy values\nplt.plot(history.history['accuracy'])\nplt.plot(history.history['val_accuracy'])\nplt.title('Model accuracy')\nplt.ylabel('Accuracy')\nplt.xlabel('Epoch')\nplt.legend(['Train', 'Val'], loc='upper left')\nplt.show()\n\n# Plot training & validation loss values\nplt.plot(history.history['loss'])\nplt.plot(history.history['val_loss'])\nplt.title('Model loss')\nplt.ylabel('Loss')\nplt.xlabel('Epoch')\nplt.legend(['Train', 'Val'], loc='upper left')\nplt.show()\n\n# Predict on validation set\nval_predictions = model.predict(X_val)\ny_pred = np.argmax(val_predictions, axis=1)\n\n# Compute and plot the confusion matrix\ncm = confusion_matrix(y_val, y_pred)\nplt.figure(figsize=(10, 7))\nsns.heatmap(cm, annot=True, fmt='d', cmap='Blues')\nplt.ylabel('Actual')\nplt.xlabel('Predicted')\nplt.title('Confusion Matrix')\nplt.show()\n\n","metadata":{"execution":{"iopub.status.busy":"2024-05-30T02:34:25.725836Z","iopub.execute_input":"2024-05-30T02:34:25.726252Z","iopub.status.idle":"2024-05-30T02:34:27.730476Z","shell.execute_reply.started":"2024-05-30T02:34:25.726221Z","shell.execute_reply":"2024-05-30T02:34:27.729327Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Predict the test set\npredictions = model.predict(X_test)\ntest_predictions = np.argmax(predictions, axis=1)\n\n# Prepare submission\nsubmission_df = pd.DataFrame({\n    \"ImageId\": range(1, len(test_predictions) + 1),\n    \"Label\": test_predictions\n})\nsubmission_df.to_csv('submission.csv', index=False)\n\n","metadata":{"execution":{"iopub.status.busy":"2024-05-30T02:34:53.824356Z","iopub.execute_input":"2024-05-30T02:34:53.825211Z","iopub.status.idle":"2024-05-30T02:34:58.924165Z","shell.execute_reply.started":"2024-05-30T02:34:53.825176Z","shell.execute_reply":"2024-05-30T02:34:58.923206Z"},"trusted":true},"execution_count":null,"outputs":[]}]}