{"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":"none","dataSources":[{"sourceId":3004,"databundleVersionId":861823,"isSourceIdPinned":false,"sourceType":"competition"},{"sourceId":13104739,"sourceType":"datasetVersion","datasetId":8301087}],"dockerImageVersionId":31089,"isInternetEnabled":false,"language":"python","sourceType":"notebook","isGpuEnabled":false}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"code","source":"# CNN on MNIST (Full 70,000 samples from mnist-dataset-complete)\n# -------------------------------------------------------------\n\nimport tensorflow as tf\nfrom tensorflow.keras import layers, models\nimport matplotlib.pyplot as plt\nfrom sklearn.model_selection import train_test_split\nimport numpy as np\nimport os\n\n# 1. Confirm uploaded dataset\nprint(\"Files in dataset:\", os.listdir(\"../input/mnist-dataset-complete\"))\n\n# 2. Load MNIST npz file\npath = \"../input/mnist-dataset-complete/mnist.npz\"\n\nwith np.load(path) as data:\n    x_train, y_train = data[\"x_train\"], data[\"y_train\"]\n    x_test, y_test = data[\"x_test\"], data[\"y_test\"]\n\nprint(\"Train:\", x_train.shape, y_train.shape)\nprint(\"Test:\", x_test.shape, y_test.shape)\nprint(\"Total samples:\", x_train.shape[0] + x_test.shape[0])\n\n# 3. Reshape and normalize\nx_train = x_train.reshape(-1, 28, 28, 1).astype(\"float32\") / 255.0\nx_test  = x_test.reshape(-1, 28, 28, 1).astype(\"float32\") / 255.0\n\n# Split train into train/validation\nx_train, x_val, y_train, y_val = train_test_split(\n    x_train, y_train, test_size=0.1, random_state=42\n)\n\nprint(\"Final Training:\", x_train.shape)\nprint(\"Validation:\", x_val.shape)\nprint(\"Test:\", x_test.shape)\n\n# 4. Build CNN\nmodel = models.Sequential([\n    layers.Conv2D(32, (3,3), activation='relu', input_shape=(28,28,1)),\n    layers.MaxPooling2D((2,2)),\n    layers.Conv2D(64, (3,3), activation='relu'),\n    layers.MaxPooling2D((2,2)),\n    layers.Conv2D(64, (3,3), activation='relu'),\n    layers.Flatten(),\n    layers.Dense(64, activation='relu'),\n    layers.Dense(10, activation='softmax')\n])\n\n# 5. Compile\nmodel.compile(optimizer='adam',\n              loss='sparse_categorical_crossentropy',\n              metrics=['accuracy'])\n\n# 6. Train\nhistory = model.fit(\n    x_train, y_train,\n    epochs=5,\n    validation_data=(x_val, y_val)\n)\n\n# 7. Evaluate on test set\ntest_loss, test_acc = model.evaluate(x_test, y_test, verbose=2)\nprint(\"\\n✅ Test accuracy:\", test_acc)\n\n# 8. Plot training history\nplt.plot(history.history['accuracy'], label='Train Accuracy')\nplt.plot(history.history['val_accuracy'], label='Val Accuracy')\nplt.xlabel('Epoch')\nplt.ylabel('Accuracy')\nplt.legend()\nplt.show()\n\n# 9. Confusion Matrix & Classification Report\nimport seaborn as sns\nfrom sklearn.metrics import confusion_matrix, classification_report\n\ny_pred = model.predict(x_test)\ny_pred_classes = np.argmax(y_pred, axis=1)\n\ncm = confusion_matrix(y_test, y_pred_classes)\n\nplt.figure(figsize=(10,8))\nsns.heatmap(cm, annot=True, fmt=\"d\", cmap=\"Blues\")\nplt.title(\"Confusion Matrix - MNIST CNN (Test Set)\")\nplt.xlabel(\"Predicted Label\")\nplt.ylabel(\"True Label\")\nplt.show()\n\nprint(\"\\nClassification Report (Test Set):\")\nprint(classification_report(y_test, y_pred_classes))\n","metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","trusted":true,"execution":{"iopub.status.busy":"2025-09-19T04:27:27.017194Z","iopub.execute_input":"2025-09-19T04:27:27.017636Z","iopub.status.idle":"2025-09-19T04:30:08.408558Z","shell.execute_reply.started":"2025-09-19T04:27:27.017612Z","shell.execute_reply":"2025-09-19T04:30:08.407420Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# 9. Individual Random Sample Prediction\n#import numpy as np\nimport random\n#import matplotlib.pyplot as plt\n\n# Pick a random image from test set\nindex = random.randint(0, len(x_test)-1)\nsample = x_test[index]\n\n# Show the image\nplt.imshow(sample.reshape(28,28), cmap='gray')\nplt.title(\"Ground Truth: {}\".format(y_test[index]))\nplt.axis(\"off\")\nplt.show()\n\n# Prepare sample for prediction\nsample_input = np.expand_dims(sample, axis=0)  # shape (1, 28, 28, 1)\npred = model.predict(sample_input)\npredicted_class = np.argmax(pred)\n\nprint(\"Predicted Digit:\", predicted_class)\nprint(\"True Label:\", y_test[index])","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-09-19T04:38:18.679027Z","iopub.execute_input":"2025-09-19T04:38:18.679377Z","iopub.status.idle":"2025-09-19T04:38:18.889822Z","shell.execute_reply.started":"2025-09-19T04:38:18.679352Z","shell.execute_reply":"2025-09-19T04:38:18.888505Z"}},"outputs":[],"execution_count":null}]}