{"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":30804,"isInternetEnabled":true,"language":"python","sourceType":"notebook","isGpuEnabled":false}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"code","source":"import numpy as np\nimport matplotlib.pyplot as plt\nfrom tensorflow.keras.models import Sequential\nfrom tensorflow.keras.layers import Dense\nfrom tensorflow.keras.utils import to_categorical\nfrom keras.datasets import mnist\nfrom sklearn.metrics import confusion_matrix, ConfusionMatrixDisplay, classification_report\nfrom PIL import Image\nfrom tensorflow.keras import Input\nimport tensorflow as tf\nfrom tensorflow.keras.models import Sequential\nfrom tensorflow.keras.layers import Dense, Input\nfrom tensorflow.keras.utils import to_categorical\nfrom tensorflow.keras.datasets import mnist\nimport io\nimport numpy as np\nfrom PIL import Image\nimport matplotlib.pyplot as plt\nimport ipywidgets as widgets\nfrom IPython.display import display\n","metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","trusted":true,"execution":{"iopub.status.busy":"2024-12-09T19:00:47.782717Z","iopub.execute_input":"2024-12-09T19:00:47.783088Z","iopub.status.idle":"2024-12-09T19:00:47.790458Z","shell.execute_reply.started":"2024-12-09T19:00:47.783057Z","shell.execute_reply":"2024-12-09T19:00:47.789032Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# Load dataset\n(x_train, y_train), (x_test, y_test) = mnist.load_data()\n\n# Display dataset shapes\nprint(\"Training data shape:\", x_train.shape)\nprint(\"Testing data shape:\", x_test.shape)\n\n# Plot 9 random samples\nplt.figure(figsize=(6, 6))\nfor i in range(9):\n    plt.subplot(3, 3, i+1)\n    plt.imshow(x_train[i], cmap='gray')\n    plt.axis('off')\nplt.show()\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-09T19:00:47.792773Z","iopub.execute_input":"2024-12-09T19:00:47.793187Z","iopub.status.idle":"2024-12-09T19:00:48.320186Z","shell.execute_reply.started":"2024-12-09T19:00:47.793158Z","shell.execute_reply":"2024-12-09T19:00:48.318965Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# Normalize the pixel values\nx_train = x_train.astype('float32') / 255.0\nx_test = x_test.astype('float32') / 255.0\n\n# Reshape the data\nx_train = x_train.reshape(-1, 28*28)\nx_test = x_test.reshape(-1, 28*28)\n\n# One-hot encode the labels\ny_train = to_categorical(y_train, num_classes=10)\ny_test = to_categorical(y_test, num_classes=10)\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-09T19:00:48.322746Z","iopub.execute_input":"2024-12-09T19:00:48.323224Z","iopub.status.idle":"2024-12-09T19:00:48.407610Z","shell.execute_reply.started":"2024-12-09T19:00:48.323178Z","shell.execute_reply":"2024-12-09T19:00:48.406671Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# Define the model\nmodel = Sequential([\n    Input(shape=(28*28,)),  # Explicit Input layer\n    Dense(256, activation='relu'),\n    Dense(256, activation='relu'),\n    Dense(10, activation='softmax')\n])\n\n# Compile the model\nmodel.compile(optimizer='adam', \n              loss='categorical_crossentropy', \n              metrics=['accuracy'])\n\n# Print model summary\nmodel.summary()\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-09T19:00:48.408861Z","iopub.execute_input":"2024-12-09T19:00:48.409247Z","iopub.status.idle":"2024-12-09T19:00:48.453883Z","shell.execute_reply.started":"2024-12-09T19:00:48.409217Z","shell.execute_reply":"2024-12-09T19:00:48.452819Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# Load the MNIST dataset\n(x_train, y_train), (x_test, y_test) = mnist.load_data()\n\n# Reshape and normalize the input data\nx_train = x_train.reshape(-1, 28*28).astype(\"float32\") / 255.0\nx_test = x_test.reshape(-1, 28*28).astype(\"float32\") / 255.0\n\n# One-hot encode the labels\ny_train = to_categorical(y_train, num_classes=10)\ny_test = to_categorical(y_test, num_classes=10)\n\n# Define the model using an Input layer\nmodel = Sequential([\n    Input(shape=(28*28,)),  # Define input shape here\n    Dense(256, activation='relu'),\n    Dense(256, activation='relu'),\n    Dense(10, activation='softmax')\n])\n\n# Compile the model\nmodel.compile(optimizer='adam',\n              loss='categorical_crossentropy',\n              metrics=['accuracy'])\n\n# Train the model\nhistory = model.fit(\n    x_train, y_train,\n    validation_split=0.1,\n    epochs=20,\n    batch_size=128\n)\n\n# Evaluate the model\ntest_loss, test_accuracy = model.evaluate(x_test, y_test, verbose=2)\nprint(f\"Test accuracy: {test_accuracy}\")","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-09T19:00:48.456027Z","iopub.execute_input":"2024-12-09T19:00:48.456338Z","iopub.status.idle":"2024-12-09T19:01:45.474057Z","shell.execute_reply.started":"2024-12-09T19:00:48.456308Z","shell.execute_reply":"2024-12-09T19:01:45.472551Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# Evaluate on test data\ntest_loss, test_acc = model.evaluate(x_test, y_test, verbose=0)\nprint(f\"Test Accuracy: {test_acc*100:.2f}%\")\n\n# Plot accuracy and loss\nplt.figure(figsize=(12, 5))\nplt.subplot(1, 2, 1)\nplt.plot(history.history['accuracy'], label='Train Accuracy')\nplt.plot(history.history['val_accuracy'], label='Validation Accuracy')\nplt.legend()\nplt.title('Accuracy')\n\nplt.subplot(1, 2, 2)\nplt.plot(history.history['loss'], label='Train Loss')\nplt.plot(history.history['val_loss'], label='Validation Loss')\nplt.legend()\nplt.title('Loss')\nplt.show()\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-09T19:01:45.475506Z","iopub.execute_input":"2024-12-09T19:01:45.475817Z","iopub.status.idle":"2024-12-09T19:01:46.503234Z","shell.execute_reply.started":"2024-12-09T19:01:45.475789Z","shell.execute_reply":"2024-12-09T19:01:46.502054Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# Predict on test data\ny_pred = model.predict(x_test)\ny_pred_classes = np.argmax(y_pred, axis=1)\ny_true_classes = np.argmax(y_test, axis=1)\n\n# Confusion matrix\ncm = confusion_matrix(y_true_classes, y_pred_classes)\ndisp = ConfusionMatrixDisplay(confusion_matrix=cm, display_labels=np.arange(10))\ndisp.plot(cmap=plt.cm.Blues)\nplt.show()\n\n# Classification report\nprint(classification_report(y_true_classes, y_pred_classes))\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-09T19:01:46.504794Z","iopub.execute_input":"2024-12-09T19:01:46.505299Z","iopub.status.idle":"2024-12-09T19:01:47.945827Z","shell.execute_reply.started":"2024-12-09T19:01:46.505246Z","shell.execute_reply":"2024-12-09T19:01:47.944692Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# Define the file upload widget\nfile_upload = widgets.FileUpload(accept='.png', multiple=False)\ndisplay(file_upload)\n\n# Function to predict the uploaded image\ndef predict_uploaded_image(change):\n    if len(file_upload.value) == 0:\n        print(\"No file uploaded!\")\n        return\n\n    # Load the image\n    uploaded_file = next(iter(file_upload.value.values()))\n    img = Image.open(io.BytesIO(uploaded_file['content'])).convert('L').resize((28, 28))\n    \n    # Preprocess the image\n    img_array = np.array(img).astype('float32') / 255.0\n    img_array = img_array.reshape(-1, 28*28)\n\n    # Predict the digit\n    prediction = model.predict(img_array)\n    predicted_digit = np.argmax(prediction, axis=1)[0]\n\n    # Display the image and prediction\n    plt.imshow(img, cmap='gray')\n    plt.axis('off')\n    plt.title(f\"Predicted Digit: {predicted_digit}\")\n    plt.show()\n\n# Add an observer to the widget to trigger prediction on file upload\nfile_upload.observe(predict_uploaded_image, names='value')","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-09T19:01:47.947127Z","iopub.execute_input":"2024-12-09T19:01:47.947426Z","iopub.status.idle":"2024-12-09T19:01:47.960595Z","shell.execute_reply.started":"2024-12-09T19:01:47.947398Z","shell.execute_reply":"2024-12-09T19:01:47.959096Z"}},"outputs":[],"execution_count":null}]}