{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "33d5e1d6",
   "metadata": {},
   "source": [
    "# Practical 9 — Multilayer perceptrons\n",
    "\n",
    "**Objectives**: calculate a small forward/backward pass, complete the essential\n",
    "backpropagation and training expressions, learn a continuous XOR dataset, then\n",
    "train and select an MLP with scikit-learn. Approximately **70 minutes**.\n",
    "\n",
    "The NumPy model, initialization, data handling and plots are supplied. Fill only\n",
    "**four backpropagation expressions and two training-loop expressions**, plus the\n",
    "introductory calculation. Then complete the sklearn exercises. Submit the calculations,\n",
    "XOR learning plot, development CV comparison and final test-performance table.\n",
    "Use NumPy and matplotlib; pandas is not needed.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "4b4e5efb",
   "metadata": {},
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "import matplotlib.pyplot as plt\n",
    "from sklearn.datasets import load_breast_cancer\n",
    "from sklearn.dummy import DummyClassifier\n",
    "from sklearn.tree import DecisionTreeClassifier\n",
    "from sklearn.ensemble import AdaBoostClassifier, GradientBoostingClassifier\n",
    "from xgboost import XGBClassifier\n",
    "from sklearn.metrics import (accuracy_score, ConfusionMatrixDisplay, f1_score,\n",
    "                             log_loss, precision_score, recall_score, roc_auc_score)\n",
    "from sklearn.model_selection import GridSearchCV, StratifiedKFold, train_test_split\n",
    "from sklearn.neural_network import MLPClassifier\n",
    "from sklearn.pipeline import Pipeline\n",
    "from sklearn.preprocessing import StandardScaler\n",
    "\n",
    "SEED = 42\n",
    "BLUE, RED = \"#2474b5\", \"#e30613\"\n",
    "plt.rcParams.update({\"figure.figsize\": (7, 4), \"font.size\": 11})\n",
    "\n",
    "def sigmoid(score):\n",
    "    return np.exp(-np.logaddexp(0., -score))  # Stable sigmoid.\n",
    "\n",
    "def positive_probability(model, X):\n",
    "    column = np.flatnonzero(model.classes_ == 1)[0]\n",
    "    return model.predict_proba(X)[:, column]\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "26ee7842",
   "metadata": {},
   "source": [
    "## 1. One forward and backward pass by hand — 15 min\n",
    "\n",
    "Use the fixed two-unit ReLU network below, with target y=1:\n",
    "\n",
    "$$z=xW_1+b_1,\\quad h=\\max(0,z),\\quad s=hw_2+b_2,\\quad p=\\sigma(s).$$\n",
    "\n",
    "1. Compute z, h, s, p and the predicted class (1 if p>.5, 0 otherwise).\n",
    "2. For binary log loss, calculate the output signal $\\delta_{out}=p-y$, then:\n",
    "\n",
    "$$\\nabla_{w_2}\\ell=h^\\top\\delta_{out},\\quad \\partial_{b_2}\\ell=\\delta_{out},$$\n",
    "$$\\delta_h=(\\delta_{out}w_2)\\odot\\mathbf1_{z>0},\\quad\n",
    "\\nabla_{W_1}\\ell=x^\\top\\delta_h,\\quad \\nabla_{b_1}\\ell=\\delta_h.$$\n",
    "\n",
    "Here $x^\\top\\delta_h$ is an **outer product**: one row per input, one column per hidden unit.\n",
    "3. Count the parameters. Which hidden unit has zero gradient on this observation, and why?\n",
    "4. Update **all** parameters with learning rate .1, using the old weights to compute\n",
    "   every gradient. Check that the new loss is smaller.\n",
    "\n",
    "The forward function is supplied below. Complete the four marked expressions in\n",
    "`backward`; the same function will train the larger XOR sample in Section 2.\n",
    "For a batch of B observations, `delta_out=(p-y)/B` includes the mean-loss factor once.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "e8a9168f",
   "metadata": {},
   "outputs": [],
   "source": [
    "x = np.array([1., 2.])\n",
    "y_example = 1.\n",
    "parameters_example = {\n",
    "    \"W1\": np.array([[1., -1.], [.5, .5]]),\n",
    "    \"b1\": np.array([-1., -1.]),\n",
    "    \"w2\": np.array([2., -1.]),\n",
    "    \"b2\": np.array(-1.),\n",
    "}\n",
    "\n",
    "# Supplied model and inference. X always has shape (B, d), even when B=1.\n",
    "def forward(parameters, X):\n",
    "    z = X @ parameters[\"W1\"] + parameters[\"b1\"]\n",
    "    h = np.maximum(0., z)\n",
    "    score = h @ parameters[\"w2\"] + parameters[\"b2\"]\n",
    "    return z, h, score, sigmoid(score)\n",
    "\n",
    "def mean_loss(parameters, X, y):\n",
    "    _, _, score, _ = forward(parameters, X)\n",
    "    return np.mean(np.logaddexp(0., score) - y * score)\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "3bfb05a2",
   "metadata": {
    "tags": [
     "exercise"
    ]
   },
   "outputs": [],
   "source": [
    "# TODO: write down z, h, score, probability, delta_out and all four gradients.\n",
    "# TODO: compare your calculations with the supplied check cell after completing backward.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "8da7409e",
   "metadata": {
    "tags": [
     "exercise"
    ]
   },
   "outputs": [],
   "source": [
    "def backward(parameters, X, y):\n",
    "    z, h, score, probability = forward(parameters, X)\n",
    "    delta_out = ...  # TODO 1: derivative w.r.t. scores for MEAN log loss, shape (B,).\n",
    "    grad_w2 = ...  # TODO 2: hidden activations times the output signal, shape (H,).\n",
    "    delta_hidden = ...  # TODO 3: propagate through w2 and the ReLU derivative, shape (B,H).\n",
    "    grad_W1 = ...  # TODO 4: inputs times the hidden signal, shape (d,H).\n",
    "    gradients = {\"W1\": grad_W1, \"b1\": delta_hidden.sum(axis=0),\n",
    "                 \"w2\": grad_w2, \"b2\": delta_out.sum()}\n",
    "    return gradients\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "2089a980",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Supplied check: compute all gradients before updating any parameter.\n",
    "X_example = x[None, :]\n",
    "y_batch_example = np.array([y_example])\n",
    "z, h, score, probability = forward(parameters_example, X_example)\n",
    "gradients = backward(parameters_example, X_example, y_batch_example)\n",
    "print(\"z:\", z, \"h:\", h, \"score:\", score, \"probability:\", probability)\n",
    "print(\"Predicted class:\", (probability > .5).astype(int))\n",
    "print(\"Parameters:\", sum(value.size for value in parameters_example.values()))\n",
    "for name, gradient in gradients.items():\n",
    "    print(name, gradient)\n",
    "updated = {name: value.copy() for name, value in parameters_example.items()}\n",
    "for name in updated:\n",
    "    updated[name] -= .1 * gradients[name]\n",
    "print(\"Loss before / after one step:\",\n",
    "      mean_loss(parameters_example, X_example, y_batch_example),\n",
    "      mean_loss(updated, X_example, y_batch_example))\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "09fbf014",
   "metadata": {},
   "source": [
    "## 2. Learn XOR from 400 observations — 20 min\n",
    "\n",
    "The supplied sample has continuous inputs drawn uniformly from [-1,1]². Its label is\n",
    "**XOR of the two sign tests**: class 1 when exactly one coordinate is positive,\n",
    "class 0 otherwise. This gives four quadrants, rather than four isolated corners.\n",
    "\n",
    "We reserve 100 observations for validation and train on 300. This experiment is\n",
    "independent of the breast-cancer benchmark below. Inputs already have comparable scales.\n",
    "Use eight hidden ReLU units, 300 epochs, mini-batches of 32 and learning rate .1.\n",
    "The scaffold handles initialization, shuffling and the last incomplete batch.\n",
    "\n",
    "1. Complete only the two TODO expressions in the loop: calculate gradients on the\n",
    "   current batch, then update the parameters. Reuse your `backward` function.\n",
    "2. Run the supplied cell to plot training/validation loss and the learned boundary.\n",
    "   Report both accuracies. Does learning generalize beyond the training observations?\n",
    "3. How many updates occur per epoch? Why calculate all gradients before updating weights?\n",
    "   Why can an individual mini-batch step increase loss on other observations?\n",
    "\n",
    "The budget and validation split are fixed for this exercise. If you explore other\n",
    "settings, this validation set becomes selection data, not an independent final test.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "903352d1",
   "metadata": {},
   "outputs": [],
   "source": [
    "rng_xor = np.random.default_rng(SEED)\n",
    "X_xor = rng_xor.uniform(-1., 1., size=(400, 2))\n",
    "y_xor = np.logical_xor(X_xor[:, 0] > 0, X_xor[:, 1] > 0).astype(float)\n",
    "X_xor_fit, X_xor_val, y_xor_fit, y_xor_val = train_test_split(\n",
    "    X_xor, y_xor, test_size=.25, stratify=y_xor, random_state=SEED)\n",
    "print(\"XOR learning / validation:\", X_xor_fit.shape, X_xor_val.shape)\n",
    "\n",
    "def initialize(d, width, rng):\n",
    "    return {\"W1\": rng.normal(0., np.sqrt(2/d), size=(d, width)),\n",
    "            \"b1\": np.zeros(width), \"w2\": rng.normal(0., np.sqrt(1/width), size=width),\n",
    "            \"b2\": np.array(0.)}\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "f8b3824f",
   "metadata": {
    "tags": [
     "exercise"
    ]
   },
   "outputs": [],
   "source": [
    "def train_xor(X, y, X_val, y_val, epochs=300, batch_size=32, rate=.1):\n",
    "    rng = np.random.default_rng(SEED)\n",
    "    parameters = initialize(X.shape[1], width=8, rng=rng)\n",
    "    train_losses, validation_losses = [], []\n",
    "    for epoch in range(epochs):\n",
    "        order = rng.permutation(len(y))\n",
    "        for start in range(0, len(y), batch_size):\n",
    "            batch = order[start:start+batch_size]\n",
    "            X_batch, y_batch = X[batch], y[batch]\n",
    "            gradients = ...  # TODO 1: call backward on the current batch.\n",
    "            for name in parameters:\n",
    "                parameters[name] -= ...  # TODO 2: learning rate times the matching gradient.\n",
    "        train_losses.append(mean_loss(parameters, X, y))\n",
    "        validation_losses.append(mean_loss(parameters, X_val, y_val))\n",
    "    return parameters, np.array(train_losses), np.array(validation_losses)\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "0cc19354",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Supplied execution, evaluation and plots.\n",
    "xor_parameters, xor_train_loss, xor_val_loss = train_xor(\n",
    "    X_xor_fit, y_xor_fit, X_xor_val, y_xor_val)\n",
    "for label, inputs, targets in [(\"Train\", X_xor_fit, y_xor_fit),\n",
    "                                (\"Validation\", X_xor_val, y_xor_val)]:\n",
    "    probability = forward(xor_parameters, inputs)[-1]\n",
    "    print(label, \"accuracy:\", accuracy_score(targets, probability > .5))\n",
    "fig, axes = plt.subplots(1, 2, figsize=(11, 4))\n",
    "epochs = np.arange(1, len(xor_train_loss)+1)\n",
    "axes[0].plot(epochs, xor_train_loss, color=BLUE, label=\"Train\")\n",
    "axes[0].plot(epochs, xor_val_loss, color=RED, label=\"Validation\")\n",
    "axes[0].set(xlabel=\"Epoch\", ylabel=\"Mean log loss\")\n",
    "axes[0].legend()\n",
    "xx, yy = np.meshgrid(np.linspace(-1, 1, 150), np.linspace(-1, 1, 150))\n",
    "grid = np.column_stack((xx.ravel(), yy.ravel()))\n",
    "p_grid = forward(xor_parameters, grid)[-1].reshape(xx.shape)\n",
    "axes[1].contourf(xx, yy, p_grid, levels=np.linspace(0, 1, 11), cmap=\"RdBu_r\", alpha=.45)\n",
    "axes[1].contour(xx, yy, p_grid, levels=[.5], colors=\"black\")\n",
    "axes[1].scatter(*X_xor_val.T, c=np.where(y_xor_val == 1, RED, BLUE), s=18,\n",
    "                edgecolors=\"white\", linewidths=.4)\n",
    "axes[1].axhline(0, color=\"gray\", ls=\":\", lw=.8)\n",
    "axes[1].axvline(0, color=\"gray\", ls=\":\", lw=.8)\n",
    "axes[1].set(xlabel=\"x1\", ylabel=\"x2\", title=\"Learned boundary; validation observations\")\n",
    "plt.tight_layout()\n",
    "plt.show()\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "6c5c80aa",
   "metadata": {},
   "source": [
    "## 3. Train an MLP with scikit-learn — 10 min\n",
    "\n",
    "Use the breast-cancer dataset and the same stratified 20% test split as TP8:\n",
    "**malignant=1, benign=0**. Keep the test unused until Section 5.\n",
    "\n",
    "1. Build a `Pipeline` with `StandardScaler` and `MLPClassifier`, naming the steps\n",
    "   \"scale\" and \"model\". Use one hidden layer of 8 ReLU units, solver=\"adam\",\n",
    "   batch_size=32, learning_rate_init=.001, alpha=.0001, max_iter=600,\n",
    "   early_stopping=True, validation_fraction=.15, n_iter_no_change=20, random_state=SEED.\n",
    "2. Fit on development data. Inspect `coefs_`, `intercepts_` and `n_iter_`.\n",
    "   Count parameters; compare with (d+1)H+(H+1).\n",
    "3. Plot `loss_curve_`. What is an epoch? Why standardize the inputs?\n",
    "\n",
    "`alpha` is the L2 penalty, not the learning rate. Early stopping monitors internal\n",
    "validation **accuracy**; `loss_curve_` records the training objective.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "333d6157",
   "metadata": {},
   "outputs": [],
   "source": [
    "data = load_breast_cancer()\n",
    "X = data.data\n",
    "y = (data.target == 0).astype(int)\n",
    "X_dev, X_test, y_dev, y_test = train_test_split(\n",
    "    X, y, test_size=.2, stratify=y, random_state=SEED)\n",
    "cv = StratifiedKFold(3, shuffle=True, random_state=SEED)\n",
    "print(\"Development:\", X_dev.shape, \"test:\", X_test.shape)\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "6543386e",
   "metadata": {
    "tags": [
     "exercise"
    ]
   },
   "outputs": [],
   "source": [
    "# TODO: build mlp_pipeline with the supplied settings and fit on X_dev/y_dev.\n",
    "# TODO: inspect its \"model\" step: weight/bias shapes, parameter count and n_iter_.\n",
    "# TODO: plot its training loss_curve_.\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "a2db1650",
   "metadata": {},
   "source": [
    "## 4. Add the MLP to the TP8 benchmark — 15 min\n",
    "\n",
    "The **TP8 benchmark is supplied below**, unchanged: Dummy, Tree, AdaBoost,\n",
    "GradientBoosting and XGBoost, with the same grids, stratified folds and ROC-AUC scoring.\n",
    "The breast-cancer data and held-out test split are also the same.\n",
    "\n",
    "**Your only code addition:** insert an entry `specs[\"MLP\"] = (estimator, grid)`.\n",
    "Reuse `mlp_pipeline` from Section 3, with this grid:\n",
    "\n",
    "- `model__hidden_layer_sizes`: [(8,), (32,)]\n",
    "- `model__alpha`: [.0001, .01]\n",
    "- `model__learning_rate_init`: [.001, .01]\n",
    "\n",
    "Then run the supplied CV and display code without modifying it. It automatically\n",
    "includes the added MLP and selects `winner` using development CV only.\n",
    "Compare the MLP with the five previous procedures. What do its three parameters control?\n",
    "Internal MLP stopping monitors accuracy; outer CV compares ROC-AUC.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "30629049",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Supplied: the five procedures and grids from TP8.\n",
    "specs = {\n",
    "    \"Dummy\": (DummyClassifier(strategy=\"prior\"), {}),\n",
    "    \"Tree\": (DecisionTreeClassifier(random_state=SEED), {\"max_depth\": [1, 2, 3]}),\n",
    "    \"AdaBoost\": (AdaBoostClassifier(\n",
    "        estimator=DecisionTreeClassifier(random_state=SEED), random_state=SEED),\n",
    "        {\"estimator__max_depth\": [1, 2], \"n_estimators\": [50, 150], \"learning_rate\": [.1, 1.]}),\n",
    "    \"GradientBoosting\": (GradientBoostingClassifier(random_state=SEED),\n",
    "        {\"max_depth\": [1, 2], \"n_estimators\": [50, 150], \"learning_rate\": [.05, .2]}),\n",
    "    \"XGBoost\": (XGBClassifier(\n",
    "        objective=\"binary:logistic\", eval_metric=\"logloss\", tree_method=\"hist\",\n",
    "        gamma=0., n_jobs=1, random_state=SEED),\n",
    "        {\"max_depth\": [1, 2], \"n_estimators\": [50, 150],\n",
    "         \"learning_rate\": [.05, .2], \"reg_lambda\": [1., 5.]}),\n",
    "}\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "c645df1a",
   "metadata": {
    "tags": [
     "exercise"
    ]
   },
   "outputs": [],
   "source": [
    "# TODO: add only the MLP entry to specs, using mlp_pipeline and the grid above.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "468df9e7",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Supplied: reuse the TP8 CV loop and development table unchanged.\n",
    "searches, development_table = {}, []\n",
    "for name, (estimator, parameters) in specs.items():\n",
    "    search = GridSearchCV(estimator, parameters, cv=cv, scoring=\"roc_auc\",\n",
    "                          return_train_score=True, n_jobs=1, error_score=\"raise\")\n",
    "    search.fit(X_dev, y_dev)\n",
    "    searches[name] = search\n",
    "    i = search.best_index_\n",
    "    development_table.append({\"model\": name, \"cv_auc\": search.best_score_,\n",
    "        \"cv_std\": search.cv_results_[\"std_test_score\"][i],\n",
    "        \"train_auc\": search.cv_results_[\"mean_train_score\"][i],\n",
    "        \"parameters\": search.best_params_})\n",
    "development_table.sort(key=lambda row: row[\"cv_auc\"], reverse=True)\n",
    "print(f\"{'Model':<18} {'Train AUC':>10} {'CV AUC':>10} {'CV std':>10}  Parameters\")\n",
    "for row in development_table:\n",
    "    print(f\"{row['model']:<18} {row['train_auc']:10.4f} {row['cv_auc']:10.4f} \"\n",
    "          f\"{row['cv_std']:10.4f}  {row['parameters']}\")\n",
    "winner = development_table[0][\"model\"]\n",
    "print(\"Procedure frozen before test evaluation:\", winner)\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "75dd0f07",
   "metadata": {},
   "source": [
    "## 5. Reuse the TP8 test comparison — 10 min\n",
    "\n",
    "Run the supplied **TP8 evaluation code without changing it**. It now evaluates the\n",
    "five previous procedures plus the MLP, frozen after development CV, on the same test set.\n",
    "It prints selected parameters, ROC-AUC, accuracy, malignant precision, recall and F1,\n",
    "then displays the CV winner's confusion matrix and false-negative indices.\n",
    "\n",
    "**No additional code to write.** Does the MLP improve the comparison? Do AUC and recall\n",
    "tell the same story? Explain any difference between the CV ranking and test ranking.\n",
    "Keep `winner` from CV; do not change parameters or thresholds after reading test scores.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "435465e7",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Supplied: reuse the TP8 final table and error analysis unchanged.\n",
    "test_table = []\n",
    "for name, search in searches.items():\n",
    "    model = search.best_estimator_\n",
    "    prediction = model.predict(X_test)\n",
    "    probability = positive_probability(model, X_test)\n",
    "    test_table.append({\"model\": name, \"parameters\": search.best_params_,\n",
    "        \"auc\": roc_auc_score(y_test, probability),\n",
    "        \"accuracy\": accuracy_score(y_test, prediction),\n",
    "        \"precision\": precision_score(y_test, prediction, pos_label=1, zero_division=0),\n",
    "        \"recall\": recall_score(y_test, prediction, pos_label=1, zero_division=0),\n",
    "        \"f1\": f1_score(y_test, prediction, pos_label=1, zero_division=0)})\n",
    "print(f\"{'Model':<18} {'AUC':>8} {'Accuracy':>9} {'Precision':>10} {'Recall':>8} {'F1':>8}\")\n",
    "for row in test_table:\n",
    "    print(f\"{row['model']:<18} {row['auc']:8.4f} {row['accuracy']:9.4f} \"\n",
    "          f\"{row['precision']:10.4f} {row['recall']:8.4f} {row['f1']:8.4f}\")\n",
    "    print(\"  Parameters:\", row[\"parameters\"])\n",
    "frozen_model = searches[winner].best_estimator_\n",
    "test_predictions = frozen_model.predict(X_test)\n",
    "ConfusionMatrixDisplay.from_predictions(\n",
    "    y_test, test_predictions, labels=[0, 1],\n",
    "    display_labels=[\"Benign (0)\", \"Malignant (1)\"], cmap=\"Blues\")\n",
    "plt.title(f\"CV-selected procedure: {winner}\")\n",
    "plt.tight_layout()\n",
    "plt.show()\n",
    "print(\"False-negative test-row indices:\", np.flatnonzero((y_test == 1) & (test_predictions == 0)))\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "a09315b6",
   "metadata": {},
   "source": [
    "## Documentation\n",
    "\n",
    "[MLPClassifier](https://scikit-learn.org/1.7/modules/generated/sklearn.neural_network.MLPClassifier.html) ·\n",
    "[MLP guide](https://scikit-learn.org/1.7/modules/neural_networks_supervised.html)\n"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "insa-iml-practicals (3.10.20)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.10.20"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
