{"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"name":"python","version":"3.10.14","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":30786,"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)\nimport matplotlib.pyplot as plt\nfrom sklearn.model_selection import train_test_split\nfrom tensorflow.keras.models import Sequential\nfrom tensorflow.keras.layers import Conv2D, MaxPooling2D, Flatten, Dense\nfrom tensorflow.keras.utils import to_categorical\nfrom sklearn.metrics import confusion_matrix\nimport seaborn as sns\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-10-23T04:41:39.127179Z","iopub.execute_input":"2024-10-23T04:41:39.128641Z","iopub.status.idle":"2024-10-23T04:42:00.115986Z","shell.execute_reply.started":"2024-10-23T04:41:39.128578Z","shell.execute_reply":"2024-10-23T04:42:00.114729Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df = pd.read_csv('/kaggle/input/digit-recognizer/train.csv')","metadata":{"execution":{"iopub.status.busy":"2024-10-23T04:42:00.118639Z","iopub.execute_input":"2024-10-23T04:42:00.119530Z","iopub.status.idle":"2024-10-23T04:42:05.105536Z","shell.execute_reply.started":"2024-10-23T04:42:00.119470Z","shell.execute_reply":"2024-10-23T04:42:05.103925Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df.head()","metadata":{"execution":{"iopub.status.busy":"2024-10-23T04:42:05.107329Z","iopub.execute_input":"2024-10-23T04:42:05.107823Z","iopub.status.idle":"2024-10-23T04:42:05.141967Z","shell.execute_reply.started":"2024-10-23T04:42:05.107776Z","shell.execute_reply":"2024-10-23T04:42:05.140672Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"X = df.drop(columns=['label']) \ny = df['label'].values               ","metadata":{"execution":{"iopub.status.busy":"2024-10-23T04:42:05.143628Z","iopub.execute_input":"2024-10-23T04:42:05.144032Z","iopub.status.idle":"2024-10-23T04:42:05.310115Z","shell.execute_reply.started":"2024-10-23T04:42:05.143992Z","shell.execute_reply":"2024-10-23T04:42:05.307649Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"X = X.values.reshape(X.shape[0], 28, 28, 1)\nX = X / 255.0","metadata":{"execution":{"iopub.status.busy":"2024-10-23T04:42:05.314183Z","iopub.execute_input":"2024-10-23T04:42:05.314667Z","iopub.status.idle":"2024-10-23T04:42:05.444995Z","shell.execute_reply.started":"2024-10-23T04:42:05.314620Z","shell.execute_reply":"2024-10-23T04:42:05.443504Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"index = 6\nplt.imshow(X[6], cmap='gray')\nplt.title(f\"Digit: {y[index]}\")\nplt.show()","metadata":{"execution":{"iopub.status.busy":"2024-10-23T04:42:05.446893Z","iopub.execute_input":"2024-10-23T04:42:05.447470Z","iopub.status.idle":"2024-10-23T04:42:05.842678Z","shell.execute_reply.started":"2024-10-23T04:42:05.447408Z","shell.execute_reply":"2024-10-23T04:42:05.840484Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"y = to_categorical(y, num_classes=10)\nprint(y.shape)","metadata":{"execution":{"iopub.status.busy":"2024-10-23T04:42:05.845114Z","iopub.execute_input":"2024-10-23T04:42:05.846832Z","iopub.status.idle":"2024-10-23T04:42:05.860062Z","shell.execute_reply.started":"2024-10-23T04:42:05.846754Z","shell.execute_reply":"2024-10-23T04:42:05.857274Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)","metadata":{"execution":{"iopub.status.busy":"2024-10-23T04:42:05.862421Z","iopub.execute_input":"2024-10-23T04:42:05.863607Z","iopub.status.idle":"2024-10-23T04:42:06.422555Z","shell.execute_reply.started":"2024-10-23T04:42:05.863539Z","shell.execute_reply":"2024-10-23T04:42:06.421077Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"model = Sequential()\nmodel.add(Conv2D(32, kernel_size=(3, 3), activation='relu', input_shape=(28, 28, 1)))\nmodel.add(MaxPooling2D(pool_size=(2, 2)))\nmodel.add(Conv2D(64, kernel_size=(3, 3), activation='relu'))\nmodel.add(MaxPooling2D(pool_size=(2, 2)))\nmodel.add(Flatten())\nmodel.add(Dense(128, activation='relu'))\nmodel.add(Dense(10, activation='softmax')) ","metadata":{"execution":{"iopub.status.busy":"2024-10-23T04:42:06.424364Z","iopub.execute_input":"2024-10-23T04:42:06.424811Z","iopub.status.idle":"2024-10-23T04:42:06.607311Z","shell.execute_reply.started":"2024-10-23T04:42:06.424765Z","shell.execute_reply":"2024-10-23T04:42:06.605731Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"history = model.compile(optimizer='adam', loss='categorical_crossentropy', metrics=['accuracy'])","metadata":{"execution":{"iopub.status.busy":"2024-10-23T04:42:06.609696Z","iopub.execute_input":"2024-10-23T04:42:06.610316Z","iopub.status.idle":"2024-10-23T04:42:06.635183Z","shell.execute_reply.started":"2024-10-23T04:42:06.610252Z","shell.execute_reply":"2024-10-23T04:42:06.633805Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"model.fit(X_train, y_train, epochs=10, batch_size=32, validation_split=0.2)","metadata":{"execution":{"iopub.status.busy":"2024-10-23T04:42:06.637056Z","iopub.execute_input":"2024-10-23T04:42:06.637668Z","iopub.status.idle":"2024-10-23T04:45:09.998620Z","shell.execute_reply.started":"2024-10-23T04:42:06.637604Z","shell.execute_reply":"2024-10-23T04:45:09.997136Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"y_pred = model.predict(X_test)\ny_pred_classes = np.argmax(y_pred, axis=1)","metadata":{"execution":{"iopub.status.busy":"2024-10-23T04:45:10.000702Z","iopub.execute_input":"2024-10-23T04:45:10.001292Z","iopub.status.idle":"2024-10-23T04:45:12.324002Z","shell.execute_reply.started":"2024-10-23T04:45:10.001213Z","shell.execute_reply":"2024-10-23T04:45:12.322213Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"y_true = np.argmax(y_test, axis=1)","metadata":{"execution":{"iopub.status.busy":"2024-10-23T04:45:12.326259Z","iopub.execute_input":"2024-10-23T04:45:12.326742Z","iopub.status.idle":"2024-10-23T04:45:12.333884Z","shell.execute_reply.started":"2024-10-23T04:45:12.326697Z","shell.execute_reply":"2024-10-23T04:45:12.332404Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"cm = confusion_matrix(y_true, y_pred_classes)","metadata":{"execution":{"iopub.status.busy":"2024-10-23T04:45:12.337972Z","iopub.execute_input":"2024-10-23T04:45:12.338646Z","iopub.status.idle":"2024-10-23T04:45:12.352515Z","shell.execute_reply.started":"2024-10-23T04:45:12.338594Z","shell.execute_reply":"2024-10-23T04:45:12.351055Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"plt.figure(figsize=(8, 6))\nsns.heatmap(cm, annot=True, fmt='d', cmap='Blues', \n            xticklabels=range(10), yticklabels=range(10))\nplt.title('Confusion Matrix')\nplt.xlabel('Predicted Label')\nplt.ylabel('True Label')\nplt.show()","metadata":{"execution":{"iopub.status.busy":"2024-10-23T04:45:12.354635Z","iopub.execute_input":"2024-10-23T04:45:12.355299Z","iopub.status.idle":"2024-10-23T04:45:13.027767Z","shell.execute_reply.started":"2024-10-23T04:45:12.355232Z","shell.execute_reply":"2024-10-23T04:45:13.025663Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Testing with Test Dataset to Submit","metadata":{}},{"cell_type":"code","source":"test_data = pd.read_csv('/kaggle/input/digit-recognizer/test.csv')\ntest_data.head()","metadata":{"execution":{"iopub.status.busy":"2024-10-23T04:54:18.846527Z","iopub.execute_input":"2024-10-23T04:54:18.847232Z","iopub.status.idle":"2024-10-23T04:54:21.182710Z","shell.execute_reply.started":"2024-10-23T04:54:18.847172Z","shell.execute_reply":"2024-10-23T04:54:21.181072Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"test_data_reshaped = test_data.values.reshape(-1, 28, 28, 1)\n\ntest_data_scaled = test_data_reshaped / 255.0","metadata":{"execution":{"iopub.status.busy":"2024-10-23T04:54:28.335791Z","iopub.execute_input":"2024-10-23T04:54:28.336290Z","iopub.status.idle":"2024-10-23T04:54:28.452858Z","shell.execute_reply.started":"2024-10-23T04:54:28.336247Z","shell.execute_reply":"2024-10-23T04:54:28.451432Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"predictions = model.predict(test_data_scaled)\npredicted_labels = np.argmax(predictions, axis=1)\nprint(predicted_labels[:10])","metadata":{"execution":{"iopub.status.busy":"2024-10-23T04:55:08.950901Z","iopub.execute_input":"2024-10-23T04:55:08.951507Z","iopub.status.idle":"2024-10-23T04:55:15.884109Z","shell.execute_reply.started":"2024-10-23T04:55:08.951452Z","shell.execute_reply":"2024-10-23T04:55:15.882402Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"submission_df = pd.DataFrame({\n    'ImageId': range(1, len(test_data) + 1),  # ImageId starts from 1\n    'Label': predicted_labels\n})\nsubmission_df.to_csv('submission.csv', index=False)\nprint(\"Submission CSV file with labels saved successfully!\")","metadata":{"execution":{"iopub.status.busy":"2024-10-23T04:55:38.906314Z","iopub.execute_input":"2024-10-23T04:55:38.906893Z","iopub.status.idle":"2024-10-23T04:55:38.960733Z","shell.execute_reply.started":"2024-10-23T04:55:38.906843Z","shell.execute_reply":"2024-10-23T04:55:38.959026Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from IPython.display import FileLink\nFileLink(r'submission.csv')","metadata":{"execution":{"iopub.status.busy":"2024-10-23T04:57:44.146012Z","iopub.execute_input":"2024-10-23T04:57:44.146585Z","iopub.status.idle":"2024-10-23T04:57:44.156025Z","shell.execute_reply.started":"2024-10-23T04:57:44.146535Z","shell.execute_reply":"2024-10-23T04:57:44.154584Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]}]}