{"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":30746,"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-08-18T09:56:50.646509Z","iopub.execute_input":"2024-08-18T09:56:50.647591Z","iopub.status.idle":"2024-08-18T09:56:50.659392Z","shell.execute_reply.started":"2024-08-18T09:56:50.647541Z","shell.execute_reply":"2024-08-18T09:56:50.658249Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import tensorflow as tf\nfrom tensorflow import keras\nfrom tensorflow.keras import layers, models\nfrom sklearn.model_selection import train_test_split","metadata":{"execution":{"iopub.status.busy":"2024-08-18T09:56:50.661405Z","iopub.execute_input":"2024-08-18T09:56:50.662039Z","iopub.status.idle":"2024-08-18T09:56:50.666756Z","shell.execute_reply.started":"2024-08-18T09:56:50.662009Z","shell.execute_reply":"2024-08-18T09:56:50.665767Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# LOADING THE DATASET","metadata":{}},{"cell_type":"code","source":"train = pd.read_csv('/kaggle/input/digit-recognizer/train.csv')\ntest = pd.read_csv('/kaggle/input/digit-recognizer/test.csv')","metadata":{"execution":{"iopub.status.busy":"2024-08-18T09:56:50.668019Z","iopub.execute_input":"2024-08-18T09:56:50.668336Z","iopub.status.idle":"2024-08-18T09:56:54.564085Z","shell.execute_reply.started":"2024-08-18T09:56:50.668310Z","shell.execute_reply":"2024-08-18T09:56:54.562975Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# SEPARATING FEATURES AND LABELS AND NORMALIZING DATA","metadata":{}},{"cell_type":"code","source":"X = train.drop('label', axis=1).values\nY = train['label'].values\n\n# Reshape and normalize the data\nX = X.reshape(-1, 28, 28, 1).astype('float32') / 255.0\ntest = test.values.reshape(-1, 28, 28, 1).astype('float32') / 255.0","metadata":{"execution":{"iopub.status.busy":"2024-08-18T09:56:54.566363Z","iopub.execute_input":"2024-08-18T09:56:54.566722Z","iopub.status.idle":"2024-08-18T09:56:54.791640Z","shell.execute_reply.started":"2024-08-18T09:56:54.566693Z","shell.execute_reply":"2024-08-18T09:56:54.790489Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# SPLITTING INTO TRAINING AND TESTING SETS","metadata":{}},{"cell_type":"code","source":"x_train, x_val, y_train, y_val = train_test_split(X, Y, test_size=0.2, random_state=42)\n","metadata":{"execution":{"iopub.status.busy":"2024-08-18T09:56:54.792840Z","iopub.execute_input":"2024-08-18T09:56:54.793167Z","iopub.status.idle":"2024-08-18T09:56:55.150592Z","shell.execute_reply.started":"2024-08-18T09:56:54.793140Z","shell.execute_reply":"2024-08-18T09:56:55.149472Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Data augmentation\ndata_augmentation = keras.Sequential([\n    layers.RandomRotation(0.2),\n    layers.RandomZoom(0.2),\n])\n","metadata":{"execution":{"iopub.status.busy":"2024-08-18T09:56:55.151946Z","iopub.execute_input":"2024-08-18T09:56:55.152300Z","iopub.status.idle":"2024-08-18T09:56:55.166499Z","shell.execute_reply.started":"2024-08-18T09:56:55.152271Z","shell.execute_reply":"2024-08-18T09:56:55.165265Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# BUILDING THE MODEL","metadata":{}},{"cell_type":"code","source":"from keras.models import Sequential\nfrom keras.layers import Dense,Flatten\nfrom tensorflow.keras.layers import InputLayer, Conv2D, MaxPool2D, BatchNormalization, Dropout\n\nmodel = models.Sequential([\n    data_augmentation,\n    layers.Conv2D(32, (3, 3), activation='relu', input_shape=(28, 28, 1)),\n    layers.BatchNormalization(),\n    layers.MaxPooling2D((2, 2)),\n    layers.Conv2D(64, (3, 3), activation='relu'),\n    layers.BatchNormalization(),\n    layers.MaxPooling2D((2, 2)),\n    layers.Conv2D(128, (3, 3), activation='relu'),\n    layers.BatchNormalization(),\n    layers.Flatten(),\n    layers.Dense(128, activation='relu'),\n    layers.Dropout(0.5),  # Increased dropout for better regularization\n    layers.Dense(10, activation='softmax')\n])\n","metadata":{"execution":{"iopub.status.busy":"2024-08-18T09:56:55.167897Z","iopub.execute_input":"2024-08-18T09:56:55.170943Z","iopub.status.idle":"2024-08-18T09:56:55.195535Z","shell.execute_reply.started":"2024-08-18T09:56:55.170890Z","shell.execute_reply":"2024-08-18T09:56:55.194460Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# COMPILING THE MODEL","metadata":{}},{"cell_type":"code","source":"model.compile(optimizer=keras.optimizers.Adam(learning_rate=1e-4),\n              loss='sparse_categorical_crossentropy',\n              metrics=['accuracy'])\n\n# Add callbacks for better training\nearly_stopping = keras.callbacks.EarlyStopping(monitor='val_loss', patience=5, restore_best_weights=True)\nreduce_lr = keras.callbacks.ReduceLROnPlateau(monitor='val_loss', factor=0.5, patience=3)\n\n# Train the model\nmodel.fit(x_train, y_train, batch_size=64, epochs=25, verbose=1, \n          validation_data=(x_val, y_val), callbacks=[early_stopping, reduce_lr])\n\n# Evaluate the model\nmodel.evaluate(x_val, y_val, batch_size=64, verbose=1)\n","metadata":{"execution":{"iopub.status.busy":"2024-08-18T10:02:00.100354Z","iopub.execute_input":"2024-08-18T10:02:00.100789Z","iopub.status.idle":"2024-08-18T10:13:21.490624Z","shell.execute_reply.started":"2024-08-18T10:02:00.100756Z","shell.execute_reply":"2024-08-18T10:13:21.489464Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"predicted_labels = np.argmax(model.predict(test), axis=-1)\nsubmission = pd.DataFrame({'ImageId': range(1, len(predicted_labels) + 1), 'Label': predicted_labels})","metadata":{"execution":{"iopub.status.busy":"2024-08-18T10:13:28.130021Z","iopub.execute_input":"2024-08-18T10:13:28.130610Z","iopub.status.idle":"2024-08-18T10:13:34.645406Z","shell.execute_reply.started":"2024-08-18T10:13:28.130548Z","shell.execute_reply":"2024-08-18T10:13:34.644239Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"submission.to_csv(\"submission.csv\",index=False)\n","metadata":{"execution":{"iopub.status.busy":"2024-08-18T10:14:16.770416Z","iopub.execute_input":"2024-08-18T10:14:16.770831Z","iopub.status.idle":"2024-08-18T10:14:16.799954Z","shell.execute_reply.started":"2024-08-18T10:14:16.770801Z","shell.execute_reply":"2024-08-18T10:14:16.798671Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]}]}