{"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"name":"python","version":"3.10.14","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":30787,"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\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":"2024-11-22T02:49:53.302053Z","iopub.execute_input":"2024-11-22T02:49:53.302760Z","iopub.status.idle":"2024-11-22T02:49:53.739096Z","shell.execute_reply.started":"2024-11-22T02:49:53.302719Z","shell.execute_reply":"2024-11-22T02:49:53.737856Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import pandas as pd\nimport numpy as np\nimport tensorflow as tf\nimport matplotlib.pyplot as plt\nfrom sklearn.model_selection import train_test_split","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-11-22T02:49:56.590430Z","iopub.execute_input":"2024-11-22T02:49:56.591844Z","iopub.status.idle":"2024-11-22T02:50:12.172378Z","shell.execute_reply.started":"2024-11-22T02:49:56.591748Z","shell.execute_reply":"2024-11-22T02:50:12.171377Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"data = pd.read_csv('/kaggle/input/digit-recognizer/train.csv')\ntest_data = pd.read_csv('/kaggle/input/digit-recognizer/test.csv')\n\nX = data.iloc[:, 1:].values.reshape(-1, 28, 28, 1)  # Reshape for Conv2D\ny = data.iloc[:, 0]\nX = X/255.0\n\nX_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.15, random_state=42)\n\n# Create a tf.data.Dataset without parallel processing\ntrain_dataset = tf.data.Dataset.from_tensor_slices((X_train, y_train)).shuffle(buffer_size=1024).batch(32)\ntest_dataset = tf.data.Dataset.from_tensor_slices((X_test, y_test)).batch(32)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-11-22T02:50:15.257833Z","iopub.execute_input":"2024-11-22T02:50:15.258600Z","iopub.status.idle":"2024-11-22T02:50:23.185257Z","shell.execute_reply.started":"2024-11-22T02:50:15.258557Z","shell.execute_reply":"2024-11-22T02:50:23.184041Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"model = tf.keras.models.Sequential([\n            tf.keras.layers.Dense(256, activation='relu'),\n            tf.keras.layers.Conv2D(128, (3, 3), activation='relu', input_shape=(28, 28, 1)),\n            tf.keras.layers.MaxPooling2D((2, 2)),\n            tf.keras.layers.Conv2D(128, (3, 3), activation='relu'),\n            tf.keras.layers.MaxPooling2D((2, 2)),\n            tf.keras.layers.Conv2D(256, (3, 3), activation='relu'),\n            tf.keras.layers.Flatten(),\n            tf.keras.layers.Reshape((64, -1)),  # Reshape for LSTM layer\n            tf.keras.layers.LSTM(256, return_sequences=True),\n            tf.keras.layers.LSTM(128),\n            tf.keras.layers.Dense(256, activation='relu'),\n            tf.keras.layers.Dropout(0.3),\n            tf.keras.layers.Dense(256, activation='relu'),\n            tf.keras.layers.Dense(10, activation='softmax')\n    ])\nmodel.summary()\n\nmodel.compile(optimizer='Adagrad', \n                loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True),\n                metrics=['accuracy'])\n\nhistory = model.fit(train_dataset, epochs=100)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-11-22T02:53:55.548207Z","iopub.execute_input":"2024-11-22T02:53:55.549074Z","iopub.status.idle":"2024-11-22T03:29:01.784450Z","shell.execute_reply.started":"2024-11-22T02:53:55.549024Z","shell.execute_reply":"2024-11-22T03:29:01.783754Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"model.evaluate(test_dataset, verbose=2)\ntrain_loss = history.history['loss']\nval_loss = history.history.get('val_loss')  # Use 'get' in case validation is not used\n\n# Plot loss over epochs\nplt.plot(train_loss, label='Training Loss')\nif val_loss:  # Check if validation loss is available\n    plt.plot(val_loss, label='Validation Loss')\nplt.xlabel('Epochs')\nplt.ylabel('Loss')\nplt.legend()\nplt.show()\nX_t = test_data.iloc[:, 0:].values.reshape(-1, 28, 28, 1)  # Reshape for Conv2D\n\nX_final = tf.data.Dataset.from_tensor_slices((X_t)).batch(32)\npredict = model.predict(X_final)\npredict_classes = np.argmax(predict, axis = 1)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-11-22T03:35:33.387368Z","iopub.execute_input":"2024-11-22T03:35:33.387714Z","iopub.status.idle":"2024-11-22T03:35:42.483048Z","shell.execute_reply.started":"2024-11-22T03:35:33.387683Z","shell.execute_reply":"2024-11-22T03:35:42.482295Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"\n# Create submission DataFrame\nsubmission_df = pd.DataFrame({\n    'ImageId': np.arange(len(predict_classes))+1,\n    'label': predict_classes\n    })\n\n# Save to CSV\nsubmission_df.to_csv('submission.csv', index=False)\n\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-11-21T04:04:00.286184Z","iopub.execute_input":"2024-11-21T04:04:00.286999Z","iopub.status.idle":"2024-11-21T04:04:00.309550Z","shell.execute_reply.started":"2024-11-21T04:04:00.286965Z","shell.execute_reply":"2024-11-21T04:04:00.308903Z"}},"outputs":[],"execution_count":null}]}