{"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"name":"python","version":"3.10.12","mimetype":"text/x-python","codemirror_mode":{"name":"ipython","version":3},"pygments_lexer":"ipython3","nbconvert_exporter":"python","file_extension":".py"},"kaggle":{"accelerator":"none","dataSources":[],"dockerImageVersionId":30626,"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 sklearn import datasets\nfrom sklearn.semi_supervised import LabelSpreading\nfrom sklearn.metrics import classification_report, confusion_matrix\nfrom sklearn.model_selection import train_test_split\n\n# 1. Load MNIST Digits dataset\ndigits = datasets.load_digits()\nX = digits.data\ny = digits.target\n\n# 2. Split into train and test\nX_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\n\n# 3. Hide labels (simulate unlabeled data) — keep only 10% of labels\nn_total = len(y_train)\nn_labeled = int(0.1 * n_total)\n\ny_train_semi = np.copy(y_train)\nunlabeled_indices = np.random.choice(n_total, n_total - n_labeled, replace=False)\ny_train_semi[unlabeled_indices] = -1  # -1 means \"unlabeled\" for sklearn\n\n# 4. Create and train the Label Spreading model\nlabel_spread = LabelSpreading(kernel='knn', n_neighbors=7, alpha=0.2)\nlabel_spread.fit(X_train, y_train_semi)\n\n# 5. Evaluate on the test set\ny_pred = label_spread.predict(X_test)\nprint(\"Classification Report:\\n\", classification_report(y_test, y_pred))\n\n# 6. Confusion Matrix\nplt.figure(figsize=(8, 6))\nplt.imshow(confusion_matrix(y_test, y_pred), cmap='Blues')\nplt.title(\"Confusion Matrix\")\nplt.xlabel(\"Predicted Label\")\nplt.ylabel(\"True Label\")\nplt.colorbar()\nplt.show()\n\n# 7. Visualize some predictions\nplt.figure(figsize=(10, 4))\nfor i in range(10):\n    ax = plt.subplot(2, 5, i + 1)\n    plt.imshow(X_test[i].reshape(8, 8), cmap='gray')\n    plt.title(f\"Pred: {y_pred[i]}\")\n    plt.axis('off')\nplt.tight_layout()\nplt.show()\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-05-14T20:59:09.125506Z","iopub.execute_input":"2025-05-14T20:59:09.126192Z","iopub.status.idle":"2025-05-14T20:59:10.067918Z","shell.execute_reply.started":"2025-05-14T20:59:09.126161Z","shell.execute_reply":"2025-05-14T20:59:10.067076Z"}},"outputs":[],"execution_count":null}]}