{"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":"gpu","dataSources":[{"sourceId":3004,"databundleVersionId":861823,"sourceType":"competition"}],"dockerImageVersionId":30734,"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","execution":{"iopub.status.busy":"2024-06-27T14:47:36.079341Z","iopub.execute_input":"2024-06-27T14:47:36.079983Z","iopub.status.idle":"2024-06-27T14:47:36.087180Z","shell.execute_reply.started":"2024-06-27T14:47:36.079953Z","shell.execute_reply":"2024-06-27T14:47:36.086233Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom sklearn.model_selection import train_test_split\nfrom tensorflow.keras.utils import to_categorical\nfrom tensorflow.keras.models import Sequential\nfrom tensorflow.keras.layers import Conv2D, MaxPooling2D, Flatten, Dense, Dropout, BatchNormalization\nfrom tensorflow.keras.preprocessing.image import ImageDataGenerator\nfrom tensorflow.keras.callbacks import LearningRateScheduler","metadata":{"execution":{"iopub.status.busy":"2024-06-27T14:47:36.093526Z","iopub.execute_input":"2024-06-27T14:47:36.094259Z","iopub.status.idle":"2024-06-27T14:47:36.104325Z","shell.execute_reply.started":"2024-06-27T14:47:36.094227Z","shell.execute_reply":"2024-06-27T14:47:36.103468Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Load the 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-06-27T14:47:36.105682Z","iopub.execute_input":"2024-06-27T14:47:36.105968Z","iopub.status.idle":"2024-06-27T14:47:40.313236Z","shell.execute_reply.started":"2024-06-27T14:47:36.105946Z","shell.execute_reply":"2024-06-27T14:47:40.312181Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train_data.shape","metadata":{"execution":{"iopub.status.busy":"2024-06-27T14:47:40.316455Z","iopub.execute_input":"2024-06-27T14:47:40.316837Z","iopub.status.idle":"2024-06-27T14:47:40.323185Z","shell.execute_reply.started":"2024-06-27T14:47:40.316804Z","shell.execute_reply":"2024-06-27T14:47:40.322280Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train_data.label.value_counts()","metadata":{"execution":{"iopub.status.busy":"2024-06-27T14:47:40.324520Z","iopub.execute_input":"2024-06-27T14:47:40.324926Z","iopub.status.idle":"2024-06-27T14:47:40.349656Z","shell.execute_reply.started":"2024-06-27T14:47:40.324894Z","shell.execute_reply":"2024-06-27T14:47:40.348716Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train_data.dtypes","metadata":{"execution":{"iopub.status.busy":"2024-06-27T14:47:40.351696Z","iopub.execute_input":"2024-06-27T14:47:40.352012Z","iopub.status.idle":"2024-06-27T14:47:40.362887Z","shell.execute_reply.started":"2024-06-27T14:47:40.351988Z","shell.execute_reply":"2024-06-27T14:47:40.361942Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"test_data.dtypes","metadata":{"execution":{"iopub.status.busy":"2024-06-27T14:47:40.364019Z","iopub.execute_input":"2024-06-27T14:47:40.364880Z","iopub.status.idle":"2024-06-27T14:47:40.375220Z","shell.execute_reply.started":"2024-06-27T14:47:40.364847Z","shell.execute_reply":"2024-06-27T14:47:40.374242Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Prepare training data\nX_train = train_data.drop(columns=['label'], axis=1).values.astype('float32') / 255.0\ny_train = train_data['label'].values.astype('int32')\nX_test = test_data.values.astype('float32') / 255.0\n\n# Reshape data into 28x28 images\nX_train = X_train.reshape((-1, 28, 28, 1))\nX_test = X_test.reshape((-1, 28, 28, 1))\n\n# Convert labels to categorical one-hot encoding\ny_train = to_categorical(y_train)\n\n# Split training data into training and validation sets\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-06-27T14:47:40.376387Z","iopub.execute_input":"2024-06-27T14:47:40.376784Z","iopub.status.idle":"2024-06-27T14:47:40.902092Z","shell.execute_reply.started":"2024-06-27T14:47:40.376757Z","shell.execute_reply":"2024-06-27T14:47:40.901316Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Data augmentation\ndatagen = ImageDataGenerator(\n    rotation_range=10,\n    width_shift_range=0.1,\n    height_shift_range=0.1,\n    shear_range=0.2,\n    zoom_range=0.2,\n    fill_mode='nearest'\n)\n\ndatagen.fit(X_train)\n\n","metadata":{"execution":{"iopub.status.busy":"2024-06-27T14:47:40.903145Z","iopub.execute_input":"2024-06-27T14:47:40.903434Z","iopub.status.idle":"2024-06-27T14:47:40.950958Z","shell.execute_reply.started":"2024-06-27T14:47:40.903410Z","shell.execute_reply":"2024-06-27T14:47:40.950173Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Define the CNN model\nmodel = Sequential([\n    Conv2D(32, (3, 3), activation='relu', input_shape=(28, 28, 1)),\n    BatchNormalization(),\n    \n    Conv2D(32, (3, 3), activation='relu'),\n    BatchNormalization(),\n    MaxPooling2D((2, 2)),\n    Dropout(0.25),\n    \n    Conv2D(64, (3, 3), activation='relu'),\n    BatchNormalization(),\n    \n    Conv2D(64, (3, 3), activation='relu'),\n    BatchNormalization(),\n    MaxPooling2D((2, 2)),\n    Dropout(0.25),\n    \n    Flatten(),\n    Dense(256, activation='relu'),\n    Dropout(0.25),\n    Dense(256, activation='relu'),\n    Dropout(0.25),\n    Dense(10, activation='softmax')\n])\n\n# Compile the model\nmodel.compile(optimizer='adam', loss='categorical_crossentropy', metrics=['accuracy'])\n\n# Learning rate scheduler\ndef lr_scheduler(epoch):\n    return 0.001 * (0.99 ** epoch)\n\nscheduler = LearningRateScheduler(lr_scheduler)\n\n# Train the model\nhistory = model.fit(datagen.flow(X_train, y_train, batch_size=64),\n                    epochs=50, validation_data=(X_val, y_val), callbacks=[scheduler])\n\n","metadata":{"execution":{"iopub.status.busy":"2024-06-27T14:47:40.951931Z","iopub.execute_input":"2024-06-27T14:47:40.952204Z","iopub.status.idle":"2024-06-27T14:58:06.833086Z","shell.execute_reply.started":"2024-06-27T14:47:40.952158Z","shell.execute_reply":"2024-06-27T14:58:06.832117Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Plot training history\nplt.figure(figsize=(10, 5))\n\nplt.subplot(1, 2, 1)\nplt.plot(history.history['accuracy'], label='Training Accuracy')\nplt.plot(history.history['val_accuracy'], label='Validation Accuracy')\nplt.xlabel('Epoch')\nplt.ylabel('Accuracy')\nplt.legend()\n\nplt.subplot(1, 2, 2)\nplt.plot(history.history['loss'], label='Training Loss')\nplt.plot(history.history['val_loss'], label='Validation Loss')\nplt.xlabel('Epoch')\nplt.ylabel('Loss')\nplt.legend()\n\nplt.tight_layout()\nplt.show()\n\n","metadata":{"execution":{"iopub.status.busy":"2024-06-27T14:58:06.834472Z","iopub.execute_input":"2024-06-27T14:58:06.834762Z","iopub.status.idle":"2024-06-27T14:58:07.357003Z","shell.execute_reply.started":"2024-06-27T14:58:06.834737Z","shell.execute_reply":"2024-06-27T14:58:07.356126Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Make predictions on test set\npredictions = model.predict(X_test)\npredicted_labels = np.argmax(predictions, axis=1)\n\n# Prepare submission file\nsubmission = pd.DataFrame({'ImageId': range(1, len(predicted_labels) + 1), 'Label': predicted_labels})\nsubmission.to_csv('submission.csv', index=False)","metadata":{"execution":{"iopub.status.busy":"2024-06-27T14:58:07.359943Z","iopub.execute_input":"2024-06-27T14:58:07.360790Z","iopub.status.idle":"2024-06-27T14:58:09.768542Z","shell.execute_reply.started":"2024-06-27T14:58:07.360755Z","shell.execute_reply":"2024-06-27T14:58:09.767693Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]}]}