{"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\nimport matplotlib.pyplot as plt\n\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-25T18:35:52.313810Z","iopub.execute_input":"2024-05-25T18:35:52.314377Z","iopub.status.idle":"2024-05-25T18:35:53.366920Z","shell.execute_reply.started":"2024-05-25T18:35:52.314335Z","shell.execute_reply":"2024-05-25T18:35:53.365539Z"},"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\")\nprint(train_data.shape)\ntrain_data.head()","metadata":{"execution":{"iopub.status.busy":"2024-05-25T18:36:02.431898Z","iopub.execute_input":"2024-05-25T18:36:02.432367Z","iopub.status.idle":"2024-05-25T18:36:05.900885Z","shell.execute_reply.started":"2024-05-25T18:36:02.432334Z","shell.execute_reply":"2024-05-25T18:36:05.899531Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Load the test data\ntest_data = pd.read_csv(\"/kaggle/input/digit-recognizer/test.csv\")\nprint(test_data.shape)\ntest_data.head()","metadata":{"execution":{"iopub.status.busy":"2024-05-25T18:36:14.833900Z","iopub.execute_input":"2024-05-25T18:36:14.834381Z","iopub.status.idle":"2024-05-25T18:36:16.954651Z","shell.execute_reply.started":"2024-05-25T18:36:14.834348Z","shell.execute_reply":"2024-05-25T18:36:16.953034Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Split into labels and features\ny_train = train_data['label']\nX_train = train_data.drop(columns=['label'])","metadata":{"execution":{"iopub.status.busy":"2024-05-25T18:36:25.451458Z","iopub.execute_input":"2024-05-25T18:36:25.451999Z","iopub.status.idle":"2024-05-25T18:36:25.674903Z","shell.execute_reply.started":"2024-05-25T18:36:25.451959Z","shell.execute_reply":"2024-05-25T18:36:25.673012Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"\n# Plotting some training data in the same plot\nplt.figure(figsize=(15, 3))\nfor i in range(5):\n    plt.subplot(1, 5, i + 1)\n    plt.imshow(X_train.iloc[i].values.reshape(28, 28), cmap='gray')\n    plt.title(f'Label: {y_train.iloc[i]}')\n    plt.axis('off')\nplt.tight_layout()\nplt.show()","metadata":{"execution":{"iopub.status.busy":"2024-05-25T18:36:30.424086Z","iopub.execute_input":"2024-05-25T18:36:30.424652Z","iopub.status.idle":"2024-05-25T18:36:31.023312Z","shell.execute_reply.started":"2024-05-25T18:36:30.424600Z","shell.execute_reply":"2024-05-25T18:36:31.022005Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"\n# Normalize the features to be between 0 and 1\nfrom sklearn.preprocessing import StandardScaler\nscaler = StandardScaler()\nX_train = scaler.fit_transform(X_train)\nX_test = scaler.transform(test_data)\n\n# 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\"No of data train: {X_train.shape[0]}\")\nprint(f\"No of data val: {X_val.shape[0]}\")\nprint(f\"No of data test: {X_test.shape[0]}\")","metadata":{"execution":{"iopub.status.busy":"2024-05-25T18:37:13.233153Z","iopub.execute_input":"2024-05-25T18:37:13.233700Z","iopub.status.idle":"2024-05-25T18:37:14.568061Z","shell.execute_reply.started":"2024-05-25T18:37:13.233656Z","shell.execute_reply":"2024-05-25T18:37:14.566734Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Define the model\nfrom tensorflow.keras import regularizers\nmodel = tf.keras.models.Sequential([\n    layers.Dense(512, activation='relu', kernel_regularizer=regularizers.l2(0.001)),\n    layers.Dropout(0.2),\n    layers.Dense(256, activation='relu', kernel_regularizer=regularizers.l2(0.001)),\n    layers.Dropout(0.2),\n    layers.Dense(128, activation='relu', kernel_regularizer=regularizers.l2(0.001)),\n    layers.Dropout(0.2),\n    layers.Dense(64, activation='relu', kernel_regularizer=regularizers.l2(0.001)),\n    layers.Dropout(0.2),\n    layers.Dense(10, activation='softmax')\n])","metadata":{"execution":{"iopub.status.busy":"2024-05-25T18:38:18.299354Z","iopub.execute_input":"2024-05-25T18:38:18.299895Z","iopub.status.idle":"2024-05-25T18:38:18.372276Z","shell.execute_reply.started":"2024-05-25T18:38:18.299860Z","shell.execute_reply":"2024-05-25T18:38:18.370764Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"\n# Compile the model\nmodel.compile(optimizer='adam',\n              loss='sparse_categorical_crossentropy',\n              metrics=['accuracy'])\n\n# Train the model\nhistory = model.fit(X_train, y_train, epochs=50, validation_data=(X_val, y_val), verbose=2)","metadata":{"execution":{"iopub.status.busy":"2024-05-25T18:38:31.030516Z","iopub.execute_input":"2024-05-25T18:38:31.031057Z","iopub.status.idle":"2024-05-25T18:46:47.224551Z","shell.execute_reply.started":"2024-05-25T18:38:31.031014Z","shell.execute_reply":"2024-05-25T18:46:47.223155Z"},"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-25T18:47:15.507926Z","iopub.execute_input":"2024-05-25T18:47:15.509193Z","iopub.status.idle":"2024-05-25T18:47:16.232443Z","shell.execute_reply.started":"2024-05-25T18:47:15.509136Z","shell.execute_reply":"2024-05-25T18:47:16.231177Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Evaluate the model\npredictions = model.predict(X_test)\n\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)","metadata":{"execution":{"iopub.status.busy":"2024-05-25T18:47:25.142856Z","iopub.execute_input":"2024-05-25T18:47:25.143353Z","iopub.status.idle":"2024-05-25T18:47:28.291713Z","shell.execute_reply.started":"2024-05-25T18:47:25.143315Z","shell.execute_reply":"2024-05-25T18:47:28.290422Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]}]}