{"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)\nimport tensorflow as tf\nfrom tensorflow.keras import layers\nfrom tensorflow.keras.utils import to_categorical\nfrom sklearn.model_selection import train_test_split\nfrom tensorflow.keras import callbacks\nimport matplotlib.pyplot as plt\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-29T19:34:24.924552Z","iopub.execute_input":"2024-05-29T19:34:24.924990Z","iopub.status.idle":"2024-05-29T19:34:24.935830Z","shell.execute_reply.started":"2024-05-29T19:34:24.924958Z","shell.execute_reply":"2024-05-29T19:34:24.934559Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Load the training data\ntrain_data = pd.read_csv(\"/kaggle/input/digit-recognizer/train.csv\")\ntest_data = pd.read_csv(\"/kaggle/input/digit-recognizer/test.csv\")","metadata":{"execution":{"iopub.status.busy":"2024-05-29T19:34:28.167886Z","iopub.execute_input":"2024-05-29T19:34:28.169233Z","iopub.status.idle":"2024-05-29T19:34:33.370961Z","shell.execute_reply.started":"2024-05-29T19:34:28.169189Z","shell.execute_reply":"2024-05-29T19:34:33.369598Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"print(train_data.shape)\ntrain_data.head()","metadata":{"execution":{"iopub.status.busy":"2024-05-29T19:34:36.167946Z","iopub.execute_input":"2024-05-29T19:34:36.168368Z","iopub.status.idle":"2024-05-29T19:34:36.190007Z","shell.execute_reply.started":"2024-05-29T19:34:36.168338Z","shell.execute_reply":"2024-05-29T19:34:36.188763Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"print(test_data.shape)\ntest_data.head()","metadata":{"execution":{"iopub.status.busy":"2024-05-29T19:34:40.360888Z","iopub.execute_input":"2024-05-29T19:34:40.361281Z","iopub.status.idle":"2024-05-29T19:34:40.383594Z","shell.execute_reply.started":"2024-05-29T19:34:40.361250Z","shell.execute_reply":"2024-05-29T19:34:40.382266Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Split into labels and features \ny_train = train_data['label']\ntrain_data.drop(\"label\", inplace=True, axis=\"columns\")","metadata":{"execution":{"iopub.status.busy":"2024-05-29T19:34:45.112118Z","iopub.execute_input":"2024-05-29T19:34:45.112508Z","iopub.status.idle":"2024-05-29T19:34:45.225755Z","shell.execute_reply.started":"2024-05-29T19:34:45.112479Z","shell.execute_reply":"2024-05-29T19:34:45.224696Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"#Reshape the data\nX_train = train_data.values.reshape((len(train_data), 28, 28))\nX_test = test_data.values.reshape((len(test_data), 28, 28))\n","metadata":{"execution":{"iopub.status.busy":"2024-05-29T19:35:06.674191Z","iopub.execute_input":"2024-05-29T19:35:06.674631Z","iopub.status.idle":"2024-05-29T19:35:06.682762Z","shell.execute_reply.started":"2024-05-29T19:35:06.674597Z","shell.execute_reply":"2024-05-29T19:35:06.681524Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Normalize the features to be between 0 and 1\nX_train = X_train / 255.0\nX_test = X_test / 255.0","metadata":{"execution":{"iopub.status.busy":"2024-05-29T19:35:09.721676Z","iopub.execute_input":"2024-05-29T19:35:09.722793Z","iopub.status.idle":"2024-05-29T19:35:09.963018Z","shell.execute_reply.started":"2024-05-29T19:35:09.722755Z","shell.execute_reply":"2024-05-29T19:35:09.961749Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"#expand 1 more dimension for the color channel gray\nX_train = np.expand_dims(X_train, axis=-1)\nX_test = np.expand_dims(X_test, axis=-1)","metadata":{"execution":{"iopub.status.busy":"2024-05-29T19:35:11.396079Z","iopub.execute_input":"2024-05-29T19:35:11.396705Z","iopub.status.idle":"2024-05-29T19:35:11.401284Z","shell.execute_reply.started":"2024-05-29T19:35:11.396672Z","shell.execute_reply":"2024-05-29T19:35:11.400371Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Split the data into training and validation sets\nX_train, X_val, y_train, y_val = train_test_split(X_train, y_train, train_size=0.8, random_state=42)\n\nprint(f\"Training data shape: {X_train.shape}\")\nprint(f\"Training labels shape: {y_train.shape}\\n\")\nprint(f\"Validation data shape: {X_val.shape}\")\nprint(f\"Validation labels shape: {y_val.shape}\\n\")\nprint(f\"Testing data shape: {X_test.shape}\")\n\n","metadata":{"execution":{"iopub.status.busy":"2024-05-29T19:35:15.538568Z","iopub.execute_input":"2024-05-29T19:35:15.539357Z","iopub.status.idle":"2024-05-29T19:35:16.019593Z","shell.execute_reply.started":"2024-05-29T19:35:15.539321Z","shell.execute_reply":"2024-05-29T19:35:16.018223Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"\ndef build_model():\n    model = tf.keras.Sequential(\n        layers=[\n                tf.keras.layers.Conv2D(6, (5, 5), activation='relu', padding='same', input_shape=(28, 28, 1)),\n                tf.keras.layers.MaxPooling2D((2, 2)),\n\n\n                tf.keras.layers.Conv2D(16, (5, 5), activation='relu', padding='valid'),\n                tf.keras.layers.MaxPooling2D((2, 2)),\n\n                tf.keras.layers.Flatten(),\n                tf.keras.layers.Dense(120, activation='relu'),\n                tf.keras.layers.Dense(84, activation='relu'),\n\n                tf.keras.layers.Dense(10, activation='softmax'),\n                ]\n    )\n\n    model.build()\n    return model\n","metadata":{"execution":{"iopub.status.busy":"2024-05-29T19:35:40.291340Z","iopub.execute_input":"2024-05-29T19:35:40.291742Z","iopub.status.idle":"2024-05-29T19:35:40.300958Z","shell.execute_reply.started":"2024-05-29T19:35:40.291712Z","shell.execute_reply":"2024-05-29T19:35:40.299916Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"model = build_model()\nmodel.compile(optimizer=tf.keras.optimizers.Adam(),\n              loss=\"sparse_categorical_crossentropy\",\n              metrics=['accuracy'])\n","metadata":{"execution":{"iopub.status.busy":"2024-05-29T19:35:55.878717Z","iopub.execute_input":"2024-05-29T19:35:55.879136Z","iopub.status.idle":"2024-05-29T19:35:55.943061Z","shell.execute_reply.started":"2024-05-29T19:35:55.879105Z","shell.execute_reply":"2024-05-29T19:35:55.941919Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"callbacks = [\n    tf.keras.callbacks.ReduceLROnPlateau(monitor='loss', patience=2, verbose=1),\n    tf.keras.callbacks.EarlyStopping(monitor='loss', patience=5, verbose=1),\n]","metadata":{"execution":{"iopub.status.busy":"2024-05-29T19:36:47.480518Z","iopub.execute_input":"2024-05-29T19:36:47.480913Z","iopub.status.idle":"2024-05-29T19:36:47.487383Z","shell.execute_reply.started":"2024-05-29T19:36:47.480885Z","shell.execute_reply":"2024-05-29T19:36:47.486038Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"history = model.fit(X_train, y_train, validation_data=(X_val, y_val),\n                    batch_size=64,\n                    epochs=50,\n                    callbacks=[callbacks])\n","metadata":{"execution":{"iopub.status.busy":"2024-05-29T19:37:02.073635Z","iopub.execute_input":"2024-05-29T19:37:02.074028Z","iopub.status.idle":"2024-05-29T19:49:00.343952Z","shell.execute_reply.started":"2024-05-29T19:37:02.073997Z","shell.execute_reply":"2024-05-29T19:49:00.342862Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"\n# Extract accuracy and loss history\naccuracy = history.history['accuracy']\nval_accuracy = history.history['val_accuracy']\nloss = history.history['loss']\nval_loss = history.history['val_loss']\nepochs = range(1, len(accuracy) + 1)\n\n# Plotting the training and validation accuracy\nplt.figure(figsize=(12, 4))\nplt.subplot(1, 2, 1)\nplt.plot(epochs, accuracy, 'bo-', label='Training accuracy')\nplt.plot(epochs, val_accuracy, 'ro-', label='Validation accuracy')\nplt.title('Training and Validation Accuracy')\nplt.xlabel('Epoch')\nplt.ylabel('Accuracy')\nplt.legend()\n\n# Plotting the training and validation loss\nplt.subplot(1, 2, 2)\nplt.plot(epochs, loss, 'bo-', label='Training loss')\nplt.plot(epochs, val_loss, 'ro-', label='Validation loss')\nplt.title('Training and Validation Loss')\nplt.xlabel('Epoch')\nplt.ylabel('Loss')\nplt.legend()\n\nplt.tight_layout()\nplt.show()\n","metadata":{"execution":{"iopub.status.busy":"2024-05-29T19:49:59.441872Z","iopub.execute_input":"2024-05-29T19:49:59.442320Z","iopub.status.idle":"2024-05-29T19:50:00.139989Z","shell.execute_reply.started":"2024-05-29T19:49:59.442285Z","shell.execute_reply":"2024-05-29T19:50:00.138656Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"\n# Evaluate the model\npredictions = model.predict(X_test)","metadata":{"execution":{"iopub.status.busy":"2024-05-29T19:50:30.349865Z","iopub.execute_input":"2024-05-29T19:50:30.350979Z","iopub.status.idle":"2024-05-29T19:50:36.596446Z","shell.execute_reply.started":"2024-05-29T19:50:30.350942Z","shell.execute_reply":"2024-05-29T19:50:36.595486Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"\n# Prepare output\nsubmission = pd.DataFrame({\n    'ImageId': range(1, len(predictions) + 1),\n    'Label': np.argmax(predictions, axis=1)\n})\nsubmission.to_csv('submission.csv', index=False)\n","metadata":{"execution":{"iopub.status.busy":"2024-05-29T19:50:49.179380Z","iopub.execute_input":"2024-05-29T19:50:49.179798Z","iopub.status.idle":"2024-05-29T19:50:49.228472Z","shell.execute_reply.started":"2024-05-29T19:50:49.179767Z","shell.execute_reply":"2024-05-29T19:50:49.227129Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]}]}