{"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"name":"python","version":"3.11.11","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":31040,"isInternetEnabled":true,"language":"python","sourceType":"notebook","isGpuEnabled":false}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"code","source":"import os\nos.environ['CUDA_VISIBLE_DEVICES'] = '-1'\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport tensorflow as tf\nfrom tensorflow.keras.datasets import mnist\nfrom tensorflow.keras.utils import to_categorical\nfrom tensorflow.keras.models import Model\nfrom tensorflow.keras.layers import Input, Conv2D, MaxPooling2D, Flatten, Dense, Dropout","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-06-14T17:34:30.715620Z","iopub.execute_input":"2025-06-14T17:34:30.715926Z","iopub.status.idle":"2025-06-14T17:34:30.722018Z","shell.execute_reply.started":"2025-06-14T17:34:30.715907Z","shell.execute_reply":"2025-06-14T17:34:30.720935Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import pandas as pd\nfrom sklearn.model_selection import train_test_split\nfrom tensorflow.keras.utils import to_categorical\n\ntrain_df = pd.read_csv('/kaggle/input/digit-recognizer/train.csv')\ntest_df = pd.read_csv('/kaggle/input/digit-recognizer/test.csv')\n\ny_train_full = train_df['label']\nX_train_full = train_df.drop(columns=['label'])\n\nX_train_full = X_train_full / 255.0\nX_test = test_df / 255.0  \n\nX_train_full = X_train_full.values.reshape(-1, 28, 28, 1)\nX_test = X_test.values.reshape(-1, 28, 28, 1)\n\ny_train_full_one_hot = to_categorical(y_train_full, num_classes=10)\n\nX_train, X_val, y_train, y_val = train_test_split(\n    X_train_full, y_train_full_one_hot,\n    test_size=0.1,  # 10% for validation\n    random_state=42, # For reproducible results\n    stratify=y_train_full\n)\n\nprint(f\"X_train shape: {X_train.shape}\")\nprint(f\"X_val shape: {X_val.shape}\")\nprint(f\"y_train shape: {y_train.shape}\")\nprint(f\"y_val shape: {y_val.shape}\")","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-06-14T17:34:30.723489Z","iopub.execute_input":"2025-06-14T17:34:30.723749Z","iopub.status.idle":"2025-06-14T17:34:35.394734Z","shell.execute_reply.started":"2025-06-14T17:34:30.723727Z","shell.execute_reply":"2025-06-14T17:34:35.393834Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"from tensorflow.keras.layers import Input\nimport tensorflow as tf\n\ninputs = Input(shape=(28, 28, 1))\n\nx = Conv2D(32, (3, 3), activation='relu')(inputs)\nx = MaxPooling2D((2, 2))(x)\nx = Conv2D(64, (3, 3), activation='relu')(x)\nx = MaxPooling2D((2, 2))(x)\nx = Dropout(0.25)(x)\nx = Flatten()(x)\nx = Dense(128, activation='relu')(x)\nx = Dropout(0.5)(x)\noutputs = Dense(10, activation='softmax')(x)\n\nmodel = tf.keras.Model(inputs=inputs, outputs=outputs)\n\nmodel.compile(optimizer='adam', loss='categorical_crossentropy', metrics=['accuracy'])\n\nmodel.summary()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-06-14T18:02:52.076787Z","iopub.execute_input":"2025-06-14T18:02:52.077903Z","iopub.status.idle":"2025-06-14T18:02:52.169209Z","shell.execute_reply.started":"2025-06-14T18:02:52.077868Z","shell.execute_reply":"2025-06-14T18:02:52.168062Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"history = model.fit(\n    X_train, y_train,\n    epochs=15,\n    batch_size=128,\n    validation_data=(X_val, y_val), \n    verbose=2\n)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-06-14T17:34:35.472063Z","iopub.execute_input":"2025-06-14T17:34:35.472326Z","iopub.status.idle":"2025-06-14T17:38:14.687713Z","shell.execute_reply.started":"2025-06-14T17:34:35.472306Z","shell.execute_reply":"2025-06-14T17:38:14.686816Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import numpy as np\nimport matplotlib.pyplot as plt\n\npredictions = model.predict(X_val)\npredicted_classes = np.argmax(predictions, axis=1)\ntrue_classes = np.argmax(y_val, axis=1)\n\nplt.figure(figsize=(12, 6))\nplt.suptitle(\"Model Predictions on Validation Images\", fontsize=16)\nfor i in range(10):\n    plt.subplot(2, 5, i + 1)\n    plt.imshow(X_val[i].reshape(28, 28), cmap='gray')\n    \n    # Set the title color to green for correct predictions and red for incorrect ones\n    color = \"green\" if predicted_classes[i] == true_classes[i] else \"red\"\n    plt.title(f\"Pred: {predicted_classes[i]}\\nTrue: {true_classes[i]}\", color=color)\n    \n    plt.axis('off')\nplt.tight_layout(rect=[0, 0.03, 1, 0.95]) # Adjust layout to make room for the suptitle\nplt.show()\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-06-14T17:38:14.689211Z","iopub.execute_input":"2025-06-14T17:38:14.689467Z","iopub.status.idle":"2025-06-14T17:38:16.561678Z","shell.execute_reply.started":"2025-06-14T17:38:14.689448Z","shell.execute_reply":"2025-06-14T17:38:16.560620Z"}},"outputs":[],"execution_count":null}]}