{"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":30664,"isInternetEnabled":true,"language":"python","sourceType":"notebook","isGpuEnabled":false}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"code","source":"import numpy as np \nimport pandas as pd \nimport keras \nfrom keras.models import Sequential\nfrom keras.layers import Conv2D, Dense, MaxPool2D, Dropout, Flatten\nfrom keras.optimizers import Adam\nfrom keras.callbacks import ReduceLROnPlateau\nfrom sklearn.model_selection import train_test_split\nimport matplotlib.pyplot as plt\nimport seaborn as sns","metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","execution":{"iopub.status.busy":"2024-03-13T08:10:05.574737Z","iopub.execute_input":"2024-03-13T08:10:05.575756Z","iopub.status.idle":"2024-03-13T08:10:05.58412Z","shell.execute_reply.started":"2024-03-13T08:10:05.575708Z","shell.execute_reply":"2024-03-13T08:10:05.58286Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df_train = pd.read_csv('/kaggle/input/digit-recognizer/train.csv')\nX_train = df_train.iloc[:, 1:]\nY_train = df_train.iloc[:, 0]","metadata":{"execution":{"iopub.status.busy":"2024-03-13T08:10:05.586624Z","iopub.execute_input":"2024-03-13T08:10:05.587114Z","iopub.status.idle":"2024-03-13T08:10:09.153154Z","shell.execute_reply.started":"2024-03-13T08:10:05.587071Z","shell.execute_reply":"2024-03-13T08:10:09.151759Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"X_train.head()","metadata":{"execution":{"iopub.status.busy":"2024-03-13T08:10:09.155408Z","iopub.execute_input":"2024-03-13T08:10:09.155805Z","iopub.status.idle":"2024-03-13T08:10:09.176902Z","shell.execute_reply.started":"2024-03-13T08:10:09.155773Z","shell.execute_reply":"2024-03-13T08:10:09.175897Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"Y_train.head()","metadata":{"execution":{"iopub.status.busy":"2024-03-13T08:10:09.178592Z","iopub.execute_input":"2024-03-13T08:10:09.179829Z","iopub.status.idle":"2024-03-13T08:10:09.191369Z","shell.execute_reply.started":"2024-03-13T08:10:09.179782Z","shell.execute_reply":"2024-03-13T08:10:09.190176Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"X_train = np.array(X_train)\nY_train = np.array(Y_train)\n# Normalize inputs\nX_train = X_train / 255.0","metadata":{"execution":{"iopub.status.busy":"2024-03-13T08:10:09.194044Z","iopub.execute_input":"2024-03-13T08:10:09.194442Z","iopub.status.idle":"2024-03-13T08:10:09.615168Z","shell.execute_reply.started":"2024-03-13T08:10:09.194409Z","shell.execute_reply":"2024-03-13T08:10:09.614047Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def plot_digits(X, Y):\n    for i in range(16):\n        plt.subplot(5, 4, i+1)\n        plt.tight_layout()\n        plt.imshow(X[i].reshape(28, 28), cmap='gray')\n        plt.title('Digit:{}'.format(Y[i]))\n        plt.xticks([])\n        plt.yticks([])\n    plt.show()","metadata":{"execution":{"iopub.status.busy":"2024-03-13T08:10:09.620223Z","iopub.execute_input":"2024-03-13T08:10:09.620625Z","iopub.status.idle":"2024-03-13T08:10:09.627905Z","shell.execute_reply.started":"2024-03-13T08:10:09.620595Z","shell.execute_reply":"2024-03-13T08:10:09.626629Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"plot_digits(X_train, Y_train)","metadata":{"execution":{"iopub.status.busy":"2024-03-13T08:10:09.629582Z","iopub.execute_input":"2024-03-13T08:10:09.630542Z","iopub.status.idle":"2024-03-13T08:10:12.251024Z","shell.execute_reply.started":"2024-03-13T08:10:09.630507Z","shell.execute_reply":"2024-03-13T08:10:12.249657Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"#Train-Test Split\nX_dev, X_val, Y_dev, Y_val = train_test_split(X_train, Y_train, test_size=0.03, shuffle=True, random_state=2019)","metadata":{"execution":{"iopub.status.busy":"2024-03-13T08:10:57.93363Z","iopub.execute_input":"2024-03-13T08:10:57.934053Z","iopub.status.idle":"2024-03-13T08:10:58.72057Z","shell.execute_reply.started":"2024-03-13T08:10:57.934023Z","shell.execute_reply":"2024-03-13T08:10:58.719277Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"T_dev = pd.get_dummies(Y_dev).values\nT_val = pd.get_dummies(Y_val).values","metadata":{"execution":{"iopub.status.busy":"2024-03-13T08:11:00.111077Z","iopub.execute_input":"2024-03-13T08:11:00.111759Z","iopub.status.idle":"2024-03-13T08:11:00.120075Z","shell.execute_reply.started":"2024-03-13T08:11:00.111725Z","shell.execute_reply":"2024-03-13T08:11:00.118827Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"#Reshape the input \nX_dev = X_dev.reshape(X_dev.shape[0], 28, 28, 1)\nX_val = X_val.reshape(X_val.shape[0], 28, 28, 1)","metadata":{"execution":{"iopub.status.busy":"2024-03-13T08:11:01.583369Z","iopub.execute_input":"2024-03-13T08:11:01.584081Z","iopub.status.idle":"2024-03-13T08:11:01.589739Z","shell.execute_reply.started":"2024-03-13T08:11:01.584039Z","shell.execute_reply":"2024-03-13T08:11:01.588647Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"model = Sequential()\nmodel.add(Conv2D(filters=32, kernel_size=(5,5), padding='same', activation='relu', input_shape=(28, 28, 1)))\nmodel.add(MaxPool2D(strides=2))\nmodel.add(Conv2D(filters=48, kernel_size=(5,5), padding='valid', activation='relu'))\nmodel.add(MaxPool2D(strides=2))\nmodel.add(Flatten())\nmodel.add(Dense(256, activation='relu'))\nmodel.add(Dense(84, activation='relu'))\nmodel.add(Dense(10, activation='softmax'))\nmodel.build()\nmodel.summary()","metadata":{"execution":{"iopub.status.busy":"2024-03-13T08:11:03.513936Z","iopub.execute_input":"2024-03-13T08:11:03.514708Z","iopub.status.idle":"2024-03-13T08:11:03.645827Z","shell.execute_reply.started":"2024-03-13T08:11:03.514671Z","shell.execute_reply":"2024-03-13T08:11:03.644634Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"adam = Adam(learning_rate=5e-4)  \nmodel.compile(loss='categorical_crossentropy', metrics=['accuracy'], optimizer=adam)\n","metadata":{"execution":{"iopub.status.busy":"2024-03-13T08:11:43.426137Z","iopub.execute_input":"2024-03-13T08:11:43.426951Z","iopub.status.idle":"2024-03-13T08:11:43.448342Z","shell.execute_reply.started":"2024-03-13T08:11:43.426896Z","shell.execute_reply":"2024-03-13T08:11:43.447173Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Set a learning rate annealer\nreduce_lr = ReduceLROnPlateau(monitor='val_acc', \n                                patience=3, \n                                verbose=1, \n                                factor=0.2, \n                                min_lr=1e-6)","metadata":{"execution":{"iopub.status.busy":"2024-03-13T08:11:45.549676Z","iopub.execute_input":"2024-03-13T08:11:45.550501Z","iopub.status.idle":"2024-03-13T08:11:45.557428Z","shell.execute_reply.started":"2024-03-13T08:11:45.550445Z","shell.execute_reply":"2024-03-13T08:11:45.555985Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from tensorflow.keras.preprocessing.image import ImageDataGenerator\n\n# Data Augmentation\ndatagen = ImageDataGenerator(\n            rotation_range=10, \n            width_shift_range=0.1, \n            height_shift_range=0.1, \n            zoom_range=0.1)","metadata":{"execution":{"iopub.status.busy":"2024-03-13T08:13:23.135791Z","iopub.execute_input":"2024-03-13T08:13:23.136817Z","iopub.status.idle":"2024-03-13T08:13:23.147569Z","shell.execute_reply.started":"2024-03-13T08:13:23.136775Z","shell.execute_reply":"2024-03-13T08:13:23.146406Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"datagen.fit(X_dev)\nmodel.fit(datagen.flow(X_dev, T_dev, batch_size=100), steps_per_epoch=int(len(X_dev)/100), \n          epochs=30, validation_data=(X_val, T_val), callbacks=[reduce_lr])","metadata":{"execution":{"iopub.status.busy":"2024-03-13T08:14:15.872692Z","iopub.execute_input":"2024-03-13T08:14:15.873197Z","iopub.status.idle":"2024-03-13T08:23:24.861457Z","shell.execute_reply.started":"2024-03-13T08:14:15.87316Z","shell.execute_reply":"2024-03-13T08:23:24.860074Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"score = model.evaluate(X_val, T_val, batch_size=32)\nscore","metadata":{"execution":{"iopub.status.busy":"2024-03-13T08:23:31.505678Z","iopub.execute_input":"2024-03-13T08:23:31.5061Z","iopub.status.idle":"2024-03-13T08:23:32.234145Z","shell.execute_reply.started":"2024-03-13T08:23:31.506069Z","shell.execute_reply":"2024-03-13T08:23:32.233193Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df_test = pd.read_csv('/kaggle/input/digit-recognizer/test.csv')","metadata":{"execution":{"iopub.status.busy":"2024-03-13T08:23:48.826059Z","iopub.execute_input":"2024-03-13T08:23:48.826473Z","iopub.status.idle":"2024-03-13T08:23:51.528091Z","shell.execute_reply.started":"2024-03-13T08:23:48.826444Z","shell.execute_reply":"2024-03-13T08:23:51.526686Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"X_test = np.array(df_test)\nX_test = X_test/255.0","metadata":{"execution":{"iopub.status.busy":"2024-03-13T08:23:58.498602Z","iopub.execute_input":"2024-03-13T08:23:58.499101Z","iopub.status.idle":"2024-03-13T08:23:58.702993Z","shell.execute_reply.started":"2024-03-13T08:23:58.499063Z","shell.execute_reply":"2024-03-13T08:23:58.701129Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import matplotlib.pyplot as plt\n\n# Define a function to display images and their predictions\ndef display_images(images, predictions, num_images=5):\n    plt.figure(figsize=(10, 4))\n    for i in range(num_images):\n        plt.subplot(1, num_images, i+1)\n        plt.imshow(images[i].reshape(28, 28), cmap='gray')\n        plt.title(f'Predicted: {predictions[i]}', fontsize=12)\n        plt.axis('off')\n    plt.show()\n\n# Display the first 5 images along with their predictions\ndisplay_images(X_test[:5], Y_test[:5])\n","metadata":{"execution":{"iopub.status.busy":"2024-03-13T08:26:06.368534Z","iopub.execute_input":"2024-03-13T08:26:06.368994Z","iopub.status.idle":"2024-03-13T08:26:06.793867Z","shell.execute_reply.started":"2024-03-13T08:26:06.368963Z","shell.execute_reply":"2024-03-13T08:26:06.792901Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# If you find this notebook helpful, please **upvote**. Your support will be highly appreciated!.","metadata":{}}]}