{"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":30702,"isInternetEnabled":true,"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)\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-04-21T09:51:20.953793Z","iopub.execute_input":"2024-04-21T09:51:20.954610Z","iopub.status.idle":"2024-04-21T09:51:21.965237Z","shell.execute_reply.started":"2024-04-21T09:51:20.954572Z","shell.execute_reply":"2024-04-21T09:51:21.963929Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import tensorflow as tf\nfrom sklearn.model_selection import train_test_split\nfrom tensorflow.keras.preprocessing.image import ImageDataGenerator\nfrom tensorflow.keras.callbacks import ReduceLROnPlateau, EarlyStopping, ModelCheckpoint\n\n# Load train data\ntrain_data = pd.read_csv('/kaggle/input/digit-recognizer/train.csv')\n\n# Splitting into features and target\nX = train_data.drop('label', axis=1)\ny = train_data['label']\n\n# Reshape data for CNN\nX = X.values.reshape(-1, 28, 28, 1)\n\n# Normalize pixel values\nX = X.astype('float32') / 255.0\n\n# Load test data\ntest_data = pd.read_csv('/kaggle/input/digit-recognizer/test.csv')\ntest_data = test_data.values.reshape(-1, 28, 28, 1)\ntest_data = test_data.astype('float32') / 255.0","metadata":{"execution":{"iopub.status.busy":"2024-04-21T09:55:58.851401Z","iopub.execute_input":"2024-04-21T09:55:58.851935Z","iopub.status.idle":"2024-04-21T09:56:19.838594Z","shell.execute_reply.started":"2024-04-21T09:55:58.851903Z","shell.execute_reply":"2024-04-21T09:56:19.837379Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Splitting data into train and validation sets\nX_train, X_val, y_train, y_val = train_test_split(X, y, test_size=0.2, random_state=42)\n\n# Data augmentation for training data\ntrain_datagen = ImageDataGenerator(\n    rotation_range=15,\n    width_shift_range=0.1,\n    height_shift_range=0.1,\n    zoom_range=0.2,\n    shear_range=0.1\n)\n\ntrain_datagen.fit(X_train)\n\n# Data augmentation for validation data\nval_datagen = ImageDataGenerator()\n\nval_datagen.fit(X_val)\n","metadata":{"execution":{"iopub.status.busy":"2024-04-21T09:56:19.840429Z","iopub.execute_input":"2024-04-21T09:56:19.840806Z","iopub.status.idle":"2024-04-21T09:56:20.465963Z","shell.execute_reply.started":"2024-04-21T09:56:19.840775Z","shell.execute_reply":"2024-04-21T09:56:20.464857Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Define CNN model\nmodel = tf.keras.models.Sequential([\n    tf.keras.layers.Conv2D(64, (3, 3), activation='relu', input_shape=(28, 28, 1)),\n    tf.keras.layers.BatchNormalization(),\n    tf.keras.layers.Conv2D(64, (3, 3), activation='relu'),\n    tf.keras.layers.BatchNormalization(),\n    tf.keras.layers.MaxPooling2D((2, 2)),\n    tf.keras.layers.Dropout(0.25),\n    \n    tf.keras.layers.Conv2D(128, (3, 3), activation='relu'),\n    tf.keras.layers.BatchNormalization(),\n    tf.keras.layers.Conv2D(128, (3, 3), activation='relu'),\n    tf.keras.layers.BatchNormalization(),\n    tf.keras.layers.MaxPooling2D((2, 2)),\n    tf.keras.layers.Dropout(0.25),\n    \n    tf.keras.layers.Flatten(),\n    tf.keras.layers.Dense(512, activation='relu'),\n    tf.keras.layers.BatchNormalization(),\n    tf.keras.layers.Dropout(0.5),\n    tf.keras.layers.Dense(256, activation='relu'),\n    tf.keras.layers.BatchNormalization(),\n    tf.keras.layers.Dropout(0.5),\n    tf.keras.layers.Dense(10, activation='softmax')\n])\n\nmodel.compile(optimizer='adam',\n              loss='sparse_categorical_crossentropy',\n              metrics=['accuracy'])\n\n# Define callbacks\nreduce_lr = ReduceLROnPlateau(monitor='val_loss', factor=0.2, patience=3, min_lr=0.00001)\nearly_stop = EarlyStopping(monitor='val_loss', patience=10, restore_best_weights=True)\ncheckpoint = ModelCheckpoint('best_model.keras', save_best_only=True, verbose=1)\n","metadata":{"execution":{"iopub.status.busy":"2024-04-21T09:56:24.664385Z","iopub.execute_input":"2024-04-21T09:56:24.665495Z","iopub.status.idle":"2024-04-21T09:56:24.886077Z","shell.execute_reply.started":"2024-04-21T09:56:24.665457Z","shell.execute_reply":"2024-04-21T09:56:24.884702Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Train the model\nhistory = model.fit(train_datagen.flow(X_train, y_train, batch_size=128),\n                    epochs=50,\n                    validation_data=val_datagen.flow(X_val, y_val, batch_size=128),\n                    callbacks=[reduce_lr, early_stop, checkpoint])\n\n# Load best model\nbest_model = tf.keras.models.load_model('best_model.keras')\n\n# Predict on test data\npredictions = best_model.predict(test_data)\n\n# Convert predictions to labels\npredicted_labels = np.argmax(predictions, axis=1)","metadata":{"execution":{"iopub.status.busy":"2024-04-21T09:56:28.210604Z","iopub.execute_input":"2024-04-21T09:56:28.211036Z","iopub.status.idle":"2024-04-21T11:18:32.526068Z","shell.execute_reply.started":"2024-04-21T09:56:28.211006Z","shell.execute_reply":"2024-04-21T11:18:32.524704Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Save predicted labels to a CSV file\noutput_df = pd.DataFrame({'ImageId': range(1, len(predicted_labels) + 1), 'Label': predicted_labels})\noutput_df.to_csv('best_predicted_labels.csv', index=False)","metadata":{"execution":{"iopub.status.busy":"2024-04-21T11:21:12.630379Z","iopub.execute_input":"2024-04-21T11:21:12.630891Z","iopub.status.idle":"2024-04-21T11:21:12.672433Z","shell.execute_reply.started":"2024-04-21T11:21:12.630856Z","shell.execute_reply":"2024-04-21T11:21:12.671313Z"},"trusted":true},"execution_count":null,"outputs":[]}]}