{"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":"markdown","source":"# Imports","metadata":{}},{"cell_type":"code","source":"import numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\n\nfrom sklearn.model_selection import train_test_split\nfrom tensorflow.keras.models import Sequential\nfrom tensorflow.keras.layers import Dense, Flatten, Conv2D, MaxPooling2D, Dropout\nfrom tensorflow.keras.callbacks import EarlyStopping\n\nimport warnings\nwarnings.filterwarnings(\"ignore\")","metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","execution":{"iopub.status.busy":"2024-07-30T13:06:58.909752Z","iopub.execute_input":"2024-07-30T13:06:58.910108Z","iopub.status.idle":"2024-07-30T13:06:58.915745Z","shell.execute_reply.started":"2024-07-30T13:06:58.910079Z","shell.execute_reply":"2024-07-30T13:06:58.914699Z"},"trusted":true},"execution_count":null,"outputs":[]},{"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-07-30T13:07:00.089917Z","iopub.execute_input":"2024-07-30T13:07:00.090941Z","iopub.status.idle":"2024-07-30T13:07:03.891367Z","shell.execute_reply.started":"2024-07-30T13:07:00.090888Z","shell.execute_reply":"2024-07-30T13:07:03.890480Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"y_train = train['label']\nx_train = train.drop(columns=['label'])\n\nx_train = x_train / 255.0\ntest = test / 255.0\n\nx_train = x_train.values.reshape(-1, 28, 28, 1)\ntest = test.values.reshape(-1, 28, 28, 1)","metadata":{"execution":{"iopub.status.busy":"2024-07-30T13:07:03.893203Z","iopub.execute_input":"2024-07-30T13:07:03.894057Z","iopub.status.idle":"2024-07-30T13:07:04.073171Z","shell.execute_reply.started":"2024-07-30T13:07:03.894017Z","shell.execute_reply":"2024-07-30T13:07:04.072281Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Creating the Model","metadata":{}},{"cell_type":"code","source":"model = Sequential([\n    Conv2D(32, (3, 3), activation='relu', input_shape=(28, 28, 1)),\n    MaxPooling2D((2, 2)),\n    Dropout(0.25),\n    Conv2D(64, (3, 3), activation='relu'),\n    MaxPooling2D((2, 2)),\n    Dropout(0.25),\n    Flatten(),\n    Dense(128, activation='relu'),\n    Dropout(0.5),\n    Dense(10, activation='softmax')\n])\n\nmodel.compile(optimizer='adam',\n              loss='sparse_categorical_crossentropy',\n              metrics=['accuracy'])\n\nmodel.summary()","metadata":{"execution":{"iopub.status.busy":"2024-07-30T13:07:05.176034Z","iopub.execute_input":"2024-07-30T13:07:05.176774Z","iopub.status.idle":"2024-07-30T13:07:05.310273Z","shell.execute_reply.started":"2024-07-30T13:07:05.176738Z","shell.execute_reply":"2024-07-30T13:07:05.309238Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Splitting and Training the Data","metadata":{}},{"cell_type":"code","source":"x_train, x_val, y_train, y_val = train_test_split(x_train, y_train, test_size=0.2, random_state=42)\n\nearly_stopping = EarlyStopping(monitor='val_loss', patience=3, restore_best_weights=True)\nhistory = model.fit(x_train, y_train, epochs=20, validation_data=(x_val, y_val), callbacks=[early_stopping])","metadata":{"execution":{"iopub.status.busy":"2024-07-30T13:07:07.023750Z","iopub.execute_input":"2024-07-30T13:07:07.024190Z","iopub.status.idle":"2024-07-30T13:11:28.593077Z","shell.execute_reply.started":"2024-07-30T13:07:07.024159Z","shell.execute_reply":"2024-07-30T13:11:28.592092Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Making Predictions on the Test Data","metadata":{}},{"cell_type":"code","source":"predictions = model.predict(test)\n\npredicted_labels = np.argmax(predictions, axis=1)","metadata":{"execution":{"iopub.status.busy":"2024-07-30T13:11:59.010921Z","iopub.execute_input":"2024-07-30T13:11:59.011328Z","iopub.status.idle":"2024-07-30T13:12:04.050052Z","shell.execute_reply.started":"2024-07-30T13:11:59.011300Z","shell.execute_reply":"2024-07-30T13:12:04.049068Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"submission = pd.DataFrame({'ImageId': np.arange(1, len(predicted_labels) + 1), 'Label': predicted_labels})\nsubmission.to_csv('submission.csv', index=False)","metadata":{"execution":{"iopub.status.busy":"2024-07-30T13:12:11.913393Z","iopub.execute_input":"2024-07-30T13:12:11.913777Z","iopub.status.idle":"2024-07-30T13:12:11.946151Z","shell.execute_reply.started":"2024-07-30T13:12:11.913748Z","shell.execute_reply":"2024-07-30T13:12:11.945231Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"plt.figure(figsize=(12, 4))\n\nplt.subplot(1, 2, 1)\nplt.plot(history.history['loss'], label='Training Loss')\nplt.plot(history.history['val_loss'], label='Validation Loss')\nplt.title('Loss')\nplt.xlabel('Epochs')\nplt.ylabel('Loss')\nplt.legend()\n\nplt.subplot(1, 2, 2)\nplt.plot(history.history['accuracy'], label='Training Accuracy')\nplt.plot(history.history['val_accuracy'], label='Validation Accuracy')\nplt.title('Accuracy')\nplt.xlabel('Epochs')\nplt.ylabel('Accuracy')\nplt.legend()","metadata":{"execution":{"iopub.status.busy":"2024-07-30T13:12:14.471669Z","iopub.execute_input":"2024-07-30T13:12:14.472072Z","iopub.status.idle":"2024-07-30T13:12:15.010713Z","shell.execute_reply.started":"2024-07-30T13:12:14.472044Z","shell.execute_reply":"2024-07-30T13:12:15.009645Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"submission","metadata":{"execution":{"iopub.status.busy":"2024-07-30T13:12:17.571067Z","iopub.execute_input":"2024-07-30T13:12:17.571456Z","iopub.status.idle":"2024-07-30T13:12:17.587187Z","shell.execute_reply.started":"2024-07-30T13:12:17.571427Z","shell.execute_reply":"2024-07-30T13:12:17.586160Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Visualisation of Predicted Images","metadata":{}},{"cell_type":"code","source":"def plot_predictions(images, labels, num_images=10):\n    plt.figure(figsize=(10, 10))\n    for i in range(num_images):\n        plt.subplot(5, 5, i+1)\n        plt.xticks([])\n        plt.yticks([])\n        plt.grid(False)\n        plt.imshow(images[i].reshape(28, 28), cmap=plt.cm.binary)\n        plt.xlabel(labels[i])","metadata":{"execution":{"iopub.status.busy":"2024-07-30T13:12:23.384700Z","iopub.execute_input":"2024-07-30T13:12:23.385130Z","iopub.status.idle":"2024-07-30T13:12:23.391525Z","shell.execute_reply.started":"2024-07-30T13:12:23.385096Z","shell.execute_reply":"2024-07-30T13:12:23.390546Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"plot_predictions(test, predicted_labels, num_images=25)\nplot_predictions(test[50:75], predicted_labels[50:75], num_images=25)","metadata":{"execution":{"iopub.status.busy":"2024-07-30T13:12:25.879594Z","iopub.execute_input":"2024-07-30T13:12:25.879988Z","iopub.status.idle":"2024-07-30T13:12:28.408936Z","shell.execute_reply.started":"2024-07-30T13:12:25.879958Z","shell.execute_reply":"2024-07-30T13:12:28.407709Z"},"trusted":true},"execution_count":null,"outputs":[]}]}