{"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"name":"python","version":"3.11.13","mimetype":"text/x-python","codemirror_mode":{"name":"ipython","version":3},"pygments_lexer":"ipython3","nbconvert_exporter":"python","file_extension":".py"},"kaggle":{"accelerator":"nvidiaTeslaT4","dataSources":[{"sourceId":3004,"databundleVersionId":861823,"sourceType":"competition"}],"dockerImageVersionId":31090,"isInternetEnabled":true,"language":"python","sourceType":"notebook","isGpuEnabled":true}},"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","trusted":true,"execution":{"iopub.status.busy":"2025-07-13T22:53:57.704243Z","iopub.execute_input":"2025-07-13T22:53:57.704774Z","iopub.status.idle":"2025-07-13T22:53:57.710932Z","shell.execute_reply.started":"2025-07-13T22:53:57.704755Z","shell.execute_reply":"2025-07-13T22:53:57.710224Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"# Library ","metadata":{}},{"cell_type":"code","source":"import pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nfrom sklearn.metrics import confusion_matrix\nfrom sklearn.model_selection import train_test_split\nfrom tensorflow.keras.utils import to_categorical\nfrom tensorflow.keras.models import Sequential\nfrom tensorflow.keras.layers import Input, Conv2D, MaxPooling2D, Dense, Flatten, Dropout\nfrom tensorflow.keras.regularizers import l2\nfrom tensorflow.keras.preprocessing.image import ImageDataGenerator\nfrom tensorflow.keras.callbacks import EarlyStopping","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-07-13T22:53:57.712075Z","iopub.execute_input":"2025-07-13T22:53:57.712389Z","iopub.status.idle":"2025-07-13T22:53:57.721242Z","shell.execute_reply.started":"2025-07-13T22:53:57.712372Z","shell.execute_reply":"2025-07-13T22:53:57.720559Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"# Load 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":{"trusted":true,"execution":{"iopub.status.busy":"2025-07-13T22:53:57.722403Z","iopub.execute_input":"2025-07-13T22:53:57.722798Z","iopub.status.idle":"2025-07-13T22:54:00.237428Z","shell.execute_reply.started":"2025-07-13T22:53:57.722781Z","shell.execute_reply":"2025-07-13T22:54:00.236842Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"# Featuring and splitting data","metadata":{}},{"cell_type":"code","source":"X = train.drop('label', axis=1).values\ny = train['label'].values\nX_test = test.values\n\nX = X.reshape(-1, 28, 28, 1) / 255.0\nX_test = X_test.reshape(-1, 28, 28, 1) / 255.0\n\ny = to_categorical(y, 10)\n\nX_train, X_val, y_train, y_val = train_test_split(X, y, test_size=0.2, random_state=42)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-07-13T22:54:00.238159Z","iopub.execute_input":"2025-07-13T22:54:00.238404Z","iopub.status.idle":"2025-07-13T22:54:00.893328Z","shell.execute_reply.started":"2025-07-13T22:54:00.238380Z","shell.execute_reply":"2025-07-13T22:54:00.892503Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"# Data Augmentation ","metadata":{}},{"cell_type":"code","source":"datagen = ImageDataGenerator(\n    rotation_range=10,\n    zoom_range=0.1,\n    width_shift_range=0.1,\n    height_shift_range=0.1\n)\ndatagen.fit(X_train)\n\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-07-13T22:54:00.894802Z","iopub.execute_input":"2025-07-13T22:54:00.895035Z","iopub.status.idle":"2025-07-13T22:54:00.976677Z","shell.execute_reply.started":"2025-07-13T22:54:00.895010Z","shell.execute_reply":"2025-07-13T22:54:00.976040Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"# Model ","metadata":{}},{"cell_type":"code","source":"model = Sequential([\n    Input(shape=(28, 28, 1)),\n    Conv2D(32, (3, 3), activation='relu'),\n    MaxPooling2D((2, 2)),\n    Conv2D(64, (3, 3), activation='relu'),\n    MaxPooling2D((2, 2)),\n    Flatten(),\n    Dense(64, activation='relu', kernel_regularizer=l2(0.01)),  \n    Dropout(0.6),  \n    Dense(10, activation='softmax')\n])","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-07-13T22:54:00.977366Z","iopub.execute_input":"2025-07-13T22:54:00.977609Z","iopub.status.idle":"2025-07-13T22:54:01.016455Z","shell.execute_reply.started":"2025-07-13T22:54:00.977586Z","shell.execute_reply":"2025-07-13T22:54:01.015901Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"early_stopping = EarlyStopping(\n    monitor='val_loss',\n    patience=3,  # Stop if no improvement for 3 epochs\n    restore_best_weights=True\n)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-07-13T22:54:14.682361Z","iopub.execute_input":"2025-07-13T22:54:14.682620Z","iopub.status.idle":"2025-07-13T22:54:14.686184Z","shell.execute_reply.started":"2025-07-13T22:54:14.682600Z","shell.execute_reply":"2025-07-13T22:54:14.685559Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"model.compile(optimizer='adam', loss='categorical_crossentropy', metrics=['accuracy'])","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-07-13T22:54:15.410381Z","iopub.execute_input":"2025-07-13T22:54:15.410920Z","iopub.status.idle":"2025-07-13T22:54:15.418383Z","shell.execute_reply.started":"2025-07-13T22:54:15.410901Z","shell.execute_reply":"2025-07-13T22:54:15.417801Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"history = model.fit(\n    datagen.flow(X_train, y_train, batch_size=64),  \n    epochs=20,  \n    validation_data=(X_val, y_val),\n    callbacks=[early_stopping]\n)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-07-13T22:54:16.247405Z","iopub.execute_input":"2025-07-13T22:54:16.248047Z","iopub.status.idle":"2025-07-13T22:57:33.356055Z","shell.execute_reply.started":"2025-07-13T22:54:16.248024Z","shell.execute_reply":"2025-07-13T22:57:33.355306Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"# Visualization ","metadata":{}},{"cell_type":"code","source":"plt.figure(figsize=(12, 4))\n\nplt.subplot(1, 2, 1)\nplt.plot(history.history['accuracy'], label='Training Accuracy')\nplt.plot(history.history['val_accuracy'], label='Validation Accuracy')\nplt.title('Training and Validation Accuracy')\nplt.xlabel('Epoch')\nplt.ylabel('Accuracy')\nplt.legend()\n\n# Plot loss\nplt.subplot(1, 2, 2)\nplt.plot(history.history['loss'], label='Training Loss')\nplt.plot(history.history['val_loss'], label='Validation Loss')\nplt.title('Training and Validation Loss')\nplt.xlabel('Epoch')\nplt.ylabel('Loss')\nplt.legend()\n\nplt.tight_layout()\nplt.show()\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-07-13T22:57:41.695757Z","iopub.execute_input":"2025-07-13T22:57:41.696293Z","iopub.status.idle":"2025-07-13T22:57:42.068129Z","shell.execute_reply.started":"2025-07-13T22:57:41.696270Z","shell.execute_reply":"2025-07-13T22:57:42.067372Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"y_val_pred = model.predict(X_val)\ny_val_pred_classes = np.argmax(y_val_pred, axis=1)\ny_val_true = np.argmax(y_val, axis=1)\n\ncm = confusion_matrix(y_val_true, y_val_pred_classes)\n\nplt.figure(figsize=(8, 6))\nsns.heatmap(cm, annot=True, fmt='d', cmap='Blues', xticklabels=range(10), yticklabels=range(10))\nplt.title('Confusion Matrix')\nplt.xlabel('Predicted Label')\nplt.ylabel('True Label')\nplt.show()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-07-13T22:57:42.396784Z","iopub.execute_input":"2025-07-13T22:57:42.397241Z","iopub.status.idle":"2025-07-13T22:57:43.737746Z","shell.execute_reply.started":"2025-07-13T22:57:42.397214Z","shell.execute_reply":"2025-07-13T22:57:43.736949Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"n_samples = 10\nindices = np.random.choice(len(X_val), n_samples, replace=False)\nX_samples = X_val[indices]\ny_samples_true = y_val_true[indices]\ny_samples_pred = y_val_pred_classes[indices]\n\n# Plot sample images with predictions\nplt.figure(figsize=(15, 3))\nfor i, idx in enumerate(indices):\n    plt.subplot(2, 5, i + 1)\n    plt.imshow(X_samples[i].reshape(28, 28), cmap='gray')\n    plt.title(f'True: {y_samples_true[i]}\\nPred: {y_samples_pred[i]}')\n    plt.axis('off')\nplt.tight_layout()\nplt.show()\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-07-13T22:57:43.738770Z","iopub.execute_input":"2025-07-13T22:57:43.739046Z","iopub.status.idle":"2025-07-13T22:57:44.161076Z","shell.execute_reply.started":"2025-07-13T22:57:43.739022Z","shell.execute_reply":"2025-07-13T22:57:44.160311Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"predictions = model.predict(X_test)\npredicted_labels = np.argmax(predictions, axis=1)\n\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-07-13T22:57:44.161840Z","iopub.execute_input":"2025-07-13T22:57:44.162086Z","iopub.status.idle":"2025-07-13T22:57:45.910425Z","shell.execute_reply.started":"2025-07-13T22:57:44.162068Z","shell.execute_reply":"2025-07-13T22:57:45.909789Z"}},"outputs":[],"execution_count":null},{"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":{"trusted":true,"execution":{"iopub.status.busy":"2025-07-13T22:57:45.960424Z","iopub.execute_input":"2025-07-13T22:57:45.960632Z","iopub.status.idle":"2025-07-13T22:57:45.983461Z","shell.execute_reply.started":"2025-07-13T22:57:45.960615Z","shell.execute_reply":"2025-07-13T22:57:45.982966Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"","metadata":{"trusted":true},"outputs":[],"execution_count":null}]}