{"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":"nvidiaTeslaT4","dataSources":[{"sourceId":3004,"databundleVersionId":861823,"sourceType":"competition"}],"dockerImageVersionId":30648,"isInternetEnabled":true,"language":"python","sourceType":"notebook","isGpuEnabled":true}},"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\nfrom sklearn.model_selection import train_test_split\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        \nimport numpy as np\nimport os\n\nos.environ[\"KERAS_BACKEND\"] = \"tensorflow\"\n\n# Note that Keras should only be imported after the backend\n# has been configured. The backend cannot be changed once the\n# package is imported.\nimport keras\nimport tensorflow as tf\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-02-19T13:29:56.100525Z","iopub.execute_input":"2024-02-19T13:29:56.101174Z","iopub.status.idle":"2024-02-19T13:30:19.544727Z","shell.execute_reply.started":"2024-02-19T13:29:56.101141Z","shell.execute_reply":"2024-02-19T13:30:19.543709Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train_data = pd.read_csv(\"/kaggle/input/digit-recognizer/train.csv\")\ntrain_data.head()\n\ntest_data = pd.read_csv(\"/kaggle/input/digit-recognizer/test.csv\")\ntest_data.head()","metadata":{"execution":{"iopub.status.busy":"2024-02-19T13:30:25.464737Z","iopub.execute_input":"2024-02-19T13:30:25.466087Z","iopub.status.idle":"2024-02-19T13:30:31.417242Z","shell.execute_reply.started":"2024-02-19T13:30:25.466043Z","shell.execute_reply":"2024-02-19T13:30:31.416285Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"X = train_data.values\ny = train_data['label']\nX = X[:, 1:]\n\nX_train, X_val, y_train, y_val = train_test_split(X, y, test_size=0.1, random_state=42)\n\nX_train = X_train.reshape((37800, 28, 28, 1))\nX_val = X_val.reshape((4200, 28, 28, 1))\n\nprint(\"X_train shape:\", X_train.shape)\nprint(\"y_train shape:\", y_train.shape)\n\nprint(\"X_val shape:\", X_val.shape)\nprint(\"y_val shape:\", y_val.shape)\n\nX_test = test_data.values\nX_test = X_test.reshape((28000, 28, 28, 1))\n\nprint(\"X_test shape:\", X_test.shape)\n\n","metadata":{"execution":{"iopub.status.busy":"2024-02-19T13:30:40.556938Z","iopub.execute_input":"2024-02-19T13:30:40.557769Z","iopub.status.idle":"2024-02-19T13:30:40.974262Z","shell.execute_reply.started":"2024-02-19T13:30:40.557726Z","shell.execute_reply":"2024-02-19T13:30:40.973009Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Model parameters\nnum_classes = 10\ninput_shape = (28, 28, 1)\n\nmodel = keras.Sequential(\n    [\n        keras.layers.Input(shape=input_shape),\n        keras.layers.Conv2D(64, kernel_size=(3, 3), activation=\"relu\"),\n        keras.layers.Conv2D(64, kernel_size=(3, 3), activation=\"relu\"),\n        keras.layers.MaxPooling2D(pool_size=(2, 2)),\n        keras.layers.Conv2D(128, kernel_size=(3, 3), activation=\"relu\"),\n        keras.layers.Conv2D(128, kernel_size=(3, 3), activation=\"relu\"),\n        keras.layers.GlobalAveragePooling2D(),\n        keras.layers.Dropout(0.5),\n        keras.layers.Dense(num_classes, activation=\"softmax\"),\n    ]\n)","metadata":{"execution":{"iopub.status.busy":"2024-02-19T13:30:43.925246Z","iopub.execute_input":"2024-02-19T13:30:43.925913Z","iopub.status.idle":"2024-02-19T13:30:45.094408Z","shell.execute_reply.started":"2024-02-19T13:30:43.925881Z","shell.execute_reply":"2024-02-19T13:30:45.093542Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"model.summary()","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"model.compile(\n    loss=keras.losses.SparseCategoricalCrossentropy(),\n    optimizer=keras.optimizers.Adam(learning_rate=1e-3),\n    metrics=[\n        keras.metrics.SparseCategoricalAccuracy(name=\"acc\"),\n    ],\n)","metadata":{"execution":{"iopub.status.busy":"2024-02-19T13:30:56.112550Z","iopub.execute_input":"2024-02-19T13:30:56.113388Z","iopub.status.idle":"2024-02-19T13:30:56.143516Z","shell.execute_reply.started":"2024-02-19T13:30:56.113340Z","shell.execute_reply":"2024-02-19T13:30:56.142554Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"batch_size = 128\nepochs = 20\n\ncallbacks = [\n    keras.callbacks.ModelCheckpoint(filepath=\"model_at_epoch_{epoch}.keras\"),\n    keras.callbacks.EarlyStopping(monitor=\"val_loss\", patience=2),\n]\n\nmodel.fit(\n    X_train,\n    y_train,\n    batch_size=batch_size,\n    epochs=epochs,\n    validation_split=0.15,\n    callbacks=callbacks,\n)\nscore = model.evaluate(X_val, y_val, verbose=0)","metadata":{"execution":{"iopub.status.busy":"2024-02-19T13:31:04.548034Z","iopub.execute_input":"2024-02-19T13:31:04.548937Z","iopub.status.idle":"2024-02-19T13:31:48.135967Z","shell.execute_reply.started":"2024-02-19T13:31:04.548896Z","shell.execute_reply":"2024-02-19T13:31:48.134964Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"print(score)","metadata":{"execution":{"iopub.status.busy":"2024-02-19T13:34:27.892692Z","iopub.execute_input":"2024-02-19T13:34:27.893050Z","iopub.status.idle":"2024-02-19T13:34:27.897981Z","shell.execute_reply.started":"2024-02-19T13:34:27.893023Z","shell.execute_reply":"2024-02-19T13:34:27.897073Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"predictions = model.predict(X_test)","metadata":{"execution":{"iopub.status.busy":"2024-02-19T13:34:07.312992Z","iopub.execute_input":"2024-02-19T13:34:07.313405Z","iopub.status.idle":"2024-02-19T13:34:09.997842Z","shell.execute_reply.started":"2024-02-19T13:34:07.313372Z","shell.execute_reply":"2024-02-19T13:34:09.996984Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"print(predictions)","metadata":{"execution":{"iopub.status.busy":"2024-02-19T13:35:03.999074Z","iopub.execute_input":"2024-02-19T13:35:03.999795Z","iopub.status.idle":"2024-02-19T13:35:04.005156Z","shell.execute_reply.started":"2024-02-19T13:35:03.999764Z","shell.execute_reply":"2024-02-19T13:35:04.004213Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"print(predictions.shape)\nmax_index = np.argmax(predictions, axis=1)\nresult_array = np.expand_dims(max_index, axis=1)\nprint(result_array.shape)\nprint(result_array)","metadata":{"execution":{"iopub.status.busy":"2024-02-19T13:52:17.128453Z","iopub.execute_input":"2024-02-19T13:52:17.128837Z","iopub.status.idle":"2024-02-19T13:52:17.136327Z","shell.execute_reply.started":"2024-02-19T13:52:17.128805Z","shell.execute_reply":"2024-02-19T13:52:17.135144Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"output = pd.DataFrame(result_array, columns=[\"Label\"])\noutput[\"ImageId\"] = output.index + 1\noutput = output.reindex(columns=[\"ImageId\", \"Label\"])\nprint(output)","metadata":{"execution":{"iopub.status.busy":"2024-02-19T13:58:09.505515Z","iopub.execute_input":"2024-02-19T13:58:09.506313Z","iopub.status.idle":"2024-02-19T13:58:09.515398Z","shell.execute_reply.started":"2024-02-19T13:58:09.506277Z","shell.execute_reply":"2024-02-19T13:58:09.514420Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# OUTPUT","metadata":{}},{"cell_type":"code","source":"output.to_csv('submission.csv', index=False)\nprint(\"Your submission was successfully saved!\")","metadata":{"execution":{"iopub.status.busy":"2024-02-19T13:58:12.308607Z","iopub.execute_input":"2024-02-19T13:58:12.308963Z","iopub.status.idle":"2024-02-19T13:58:12.347194Z","shell.execute_reply.started":"2024-02-19T13:58:12.308937Z","shell.execute_reply":"2024-02-19T13:58:12.346273Z"},"trusted":true},"execution_count":null,"outputs":[]}]}