{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {
    "hide_input": true,
    "slideshow": {
     "slide_type": "slide"
    }
   },
   "source": [
    "# Introduction into Machine Learning\n",
    "\n",
    "Hans Dembinski"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "slideshow": {
     "slide_type": "slide"
    }
   },
   "source": [
    "## Overview"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "slideshow": {
     "slide_type": "slide"
    }
   },
   "source": [
    "<img src=\"https://external-content.duckduckgo.com/iu/?u=https%3A%2F%2Fwww.toysense.ca%2Fcomponents%2Fcom_virtuemart%2Fshop_image%2Fproduct%2Ffull%2Fspin_prod_85232641259a4676049cd1_r1.jpg&f=1&nofb=1&ipt=2fbb01f01e582ac217911a1cba8785cce7fa9b55533e1e368b62e7e94f233cca&ipo=images\" width=20%\\>\n",
    "\n",
    "* Caution: Field is riddled with buzzwords\n",
    "  * Machine learning, artificial intelligence, deep learning, belief networks, attention-based networks, long short-term memory, features, hyperparameters ...\n",
    "* Anthropomorphized and technical names hide what are usually basic mathematical algorithms\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "slideshow": {
     "slide_type": "slide"
    }
   },
   "source": [
    "* Machine learning: umbrella term for multivariate statistical methods for classification and regression\n",
    "  * *Multivariate*: algorithms use more than one variable as input, e.g. (x, y, z)\n",
    "  * *Statistical*: algorithms can handle noisy input and are founded on statistical theory\n",
    "  * *Classification*: sort inputs based on input variables into categories\n",
    "  * *Regression*: find a mapping of input vectors to output vectors (fitting)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "slideshow": {
     "slide_type": "slide"
    }
   },
   "source": [
    "<img src=\"https://images-na.ssl-images-amazon.com/images/M/MV5BMTk5NzM1ODgyN15BMl5BanBnXkFtZTcwMzA5MjAzMw@@._V1_UY1200_CR91,0,630,1200_AL_.jpg\" width=15%>\n",
    "\n",
    "* Rise of the machines: Why do we need them?\n",
    "  * Humans good at working with 1D or 2D data, because we can visualize it\n",
    "  * Humans bad at working with higer-dimensional data\n",
    "  * Algorithms (\"machines\") scale well to high-dimensional data"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "slideshow": {
     "slide_type": "slide"
    }
   },
   "source": [
    "### Notable software\n",
    "* Multiple algorithms and utilities\n",
    "  * [Scikit-Learn](https://scikit-learn.org/stable/index.html)\n",
    "  * [ROOT TMVA](https://root.cern/manual/tmva)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "slideshow": {
     "slide_type": "fragment"
    }
   },
   "source": [
    "* Gradient-boosted decision trees (aka gradient boosting machines)\n",
    "  * [XGBoost](https://xgboost.readthedocs.io/en/stable)\n",
    "  * [LightGBM](https://github.com/microsoft/LightGBM)\n",
    "  * [CatBoost](https://catboost.ai)\n",
    "  * ..."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "slideshow": {
     "slide_type": "fragment"
    }
   },
   "source": [
    "* Neural networks\n",
    "  * [Tensorflow](https://www.tensorflow.org)\n",
    "  * [Keras](https://keras.io) (high-level interface to Tensorflow)\n",
    "  * [PyTorch](https://github.com/pytorch/pytorch)\n",
    "  * ..."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "slideshow": {
     "slide_type": "slide"
    }
   },
   "source": [
    "### Learning resources\n",
    "\n",
    "* Internet provides excellent resources for autodidactic learning\n",
    "  * Example code\n",
    "  * Tutorials\n",
    "  * Documentation\n",
    "<br/><br/>\n",
    "* [Scikit-Learn](https://scikit-learn.org/stable/index.html)\n",
    "* [Kaggle](https://www.kaggle.com/)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "slideshow": {
     "slide_type": "slide"
    }
   },
   "source": [
    "* All methods can do classification and regression and work with any input\n",
    "* What to use?"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "slideshow": {
     "slide_type": "fragment"
    }
   },
   "source": [
    "  * Structured data (i.e. tables of numbers): Ensembles of decision trees\n",
    "    * Good results with default settings\n",
    "    * Can process continuous and categorical input (m/w, red/green/blue, ...)\n",
    "    * No data preprocessing required\n",
    "    * Compute feature importance\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "slideshow": {
     "slide_type": "fragment"
    }
   },
   "source": [
    "  * Unstructured data (i.e. images, waveforms, text...): Neural networks\n",
    "    * Deep networks learn to extract features automatically\n",
    "    * Requires data preprocessing\n",
    "    * Networks difficult to optimize for non-experts\n",
    "    * Often need very large data sets for training"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "slideshow": {
     "slide_type": "slide"
    }
   },
   "source": [
    "Some definitions\n",
    "* *sample*: one or more numbers which describe outcome of stochastic process\n",
    "* *dataset*: consists of *samples*\n",
    "* *features*: subset of numbers from each sample which carry interesting information, also numbers computed from each sample\n",
    "* *signal*: samples which originate from stochastic process of interest, typically particle decay\n",
    "* *background*: samples which do not originate from process of interest"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "slideshow": {
     "slide_type": "notes"
    }
   },
   "source": [
    "*Discuss how the typical decay $K^0_S \\to \\pi^+ \\pi^-$ is reconstructed and why in general there is always some background*.\n",
    "\n",
    "*Clarify how the previous terms would be used in the context of this example.*"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "slideshow": {
     "slide_type": "slide"
    }
   },
   "source": [
    "## Classification\n",
    "\n",
    "* Setting: dataset is mix of two or more components, typically signal + one or more backgrounds\n",
    "* Want only signal component, invert a cut to select signal candidates\n",
    "* Features are variables which allow to discriminate between signal and background, for example, reconstructed mass of decay candidate"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "slideshow": {
     "slide_type": "slide"
    }
   },
   "outputs": [],
   "source": [
    "#!pip install scipy matplotlib numpy scikit-learn xgboost"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import scipy\n",
    "import matplotlib\n",
    "import numpy\n",
    "import sklearn\n",
    "import xgboost\n",
    "\n",
    "print(f\"scipy {scipy.__version__}\")\n",
    "print(f\"matplotlib {matplotlib.__version__}\")\n",
    "print(f\"numpy {numpy.__version__}\")\n",
    "print(f\"sklearn {sklearn.__version__}\")\n",
    "print(f\"xgboost {xgboost.__version__}\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "slideshow": {
     "slide_type": "slide"
    }
   },
   "outputs": [],
   "source": [
    "from scipy.stats import norm\n",
    "from matplotlib import pyplot as plt\n",
    "import numpy as np\n",
    "\n",
    "background = norm(0, 1).rvs(1000, random_state=1)\n",
    "signal = norm(1, 0.1).rvs(500, random_state=1)\n",
    "\n",
    "x = np.append(signal, background)\n",
    "y = np.append(np.ones(len(signal)), np.zeros(len(background)))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "slideshow": {
     "slide_type": "slide"
    }
   },
   "outputs": [],
   "source": [
    "def plot(x, y):\n",
    "    signal = x[y == 1]\n",
    "    background = x[y == 0]\n",
    "    t, xe = np.histogram(x, bins=100)\n",
    "    s = np.histogram(signal, bins=xe)[0]\n",
    "    b = np.histogram(background, bins=xe)[0]\n",
    "    plt.stairs(b, xe, fill=True, label=\"background\")\n",
    "    plt.stairs(t, xe, baseline=b, fill=True, label=\"signal\")\n",
    "    plt.xlabel(\"x\")\n",
    "    plt.legend();\n",
    "    return xe\n",
    "\n",
    "plot(x, y);"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "slideshow": {
     "slide_type": "slide"
    }
   },
   "source": [
    "Exercise:\n",
    "* Propose simple selection (\"cut\") that keeps most of the signal and removes most of the background\n",
    "* Is it possible to eliminate the background completely?"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "slideshow": {
     "slide_type": "slide"
    }
   },
   "source": [
    "### Efficiency and purity of a selection\n",
    "\n",
    "* Efficiency: fraction of signal left after applying selection\n",
    "  * Number of true signal samples after cut / Number of all true signal samples\n",
    "* Purity: fraction of background still contained in selected sample\n",
    "  * Number of true signal samples after cut / Number of selected samples\n",
    "* Want to maximize efficiency and purity"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "slideshow": {
     "slide_type": "slide"
    }
   },
   "source": [
    "#### Single-parameter cut"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "slideshow": {
     "slide_type": "-"
    }
   },
   "outputs": [],
   "source": [
    "xmin = 0.7\n",
    "\n",
    "selected_signal = np.sum(x[y==1] > xmin)\n",
    "total_signal = np.sum(y==1)\n",
    "selected = np.sum(x > xmin)\n",
    "\n",
    "efficiency = selected_signal / total_signal\n",
    "purity = selected_signal / selected\n",
    "\n",
    "plot(x, y)\n",
    "plt.axvspan(-3.5, xmin, facecolor=\"k\", alpha=0.5)\n",
    "plt.legend(title=f\"efficiency={efficiency:.2f}\\npurity={purity:.2f}\");"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "slideshow": {
     "slide_type": "slide"
    }
   },
   "outputs": [],
   "source": [
    "xmin = np.linspace(-3, 3, 100)\n",
    "efficiency = []\n",
    "purity = []\n",
    "for xm in xmin:\n",
    "    selected_signal = np.sum(signal > xm)\n",
    "    total_signal = len(signal)\n",
    "    selected = np.sum(x > xm)\n",
    "    e = selected_signal / total_signal\n",
    "    p = selected_signal / selected\n",
    "    efficiency.append(e)\n",
    "    purity.append(p)\n",
    "plt.plot(xmin, efficiency, label=\"efficiency\")\n",
    "plt.plot(xmin, purity, label=\"purity\")\n",
    "plt.xlabel(\"xmin\")\n",
    "plt.legend();"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "slideshow": {
     "slide_type": "slide"
    }
   },
   "outputs": [],
   "source": [
    "plt.scatter(efficiency, purity, c=xmin);\n",
    "plt.xlim(0, 1)\n",
    "plt.ylim(0, 1)\n",
    "plt.xlabel(\"efficiency\")\n",
    "plt.ylabel(\"purity\")\n",
    "plt.colorbar().set_label(\"xmin\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "slideshow": {
     "slide_type": "slide"
    }
   },
   "outputs": [],
   "source": [
    "arg = np.argmax(purity)\n",
    "print(\"efficiency at max purity\", efficiency[arg])"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "slideshow": {
     "slide_type": "slide"
    }
   },
   "source": [
    "* How to choose cut?\n",
    "  * Want to maximize efficiency and purity, but what trade-off between the two?\n",
    "* Often subjective choice is acceptable, because exact answer is difficult"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "slideshow": {
     "slide_type": "fragment"
    }
   },
   "source": [
    "* Objective answer given by figure-of-merit (FOM)\n",
    "  * Popular is [Punzi FOM](https://inspirehep.net/literature/634798)\n",
    "  * Most FOM (including Punzi FOM) **only** minimize statistical uncertainty\n",
    "  * Correct FOM has to minimize total uncertainty = statistical ⊕ systematic\n",
    "  * Systematic uncertainty often difficult to quantify: fallback to Punzi or subjective choice"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "slideshow": {
     "slide_type": "slide"
    }
   },
   "source": [
    "#### BDT-based cut\n",
    "\n",
    "* We can do better with two cuts, on xmin and xmax\n",
    "* Space of cut parameters then already two-dimensional\n",
    "* With 2D data\n",
    "  * Four rectangular cuts possible (4 cut parameters)\n",
    "  * Infinitely many non-rectangular cuts possible\n",
    "* Use machine instead, needs to be trained on labeled data"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "slideshow": {
     "slide_type": "slide"
    }
   },
   "source": [
    "* Use BDT classifier from [XGBoost](https://xgboost.readthedocs.io/en/stable/)\n",
    "* [Gradient boosting machines regularly win Kaggle competitions](https://www.kaggle.com/code/antgoldbloom/what-algorithms-are-most-successful-on-kaggle?scriptVersionId=0)\n",
    "* Well documented, fast, parallizable, tunable"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "slideshow": {
     "slide_type": "slide"
    }
   },
   "outputs": [],
   "source": [
    "from xgboost.sklearn import XGBClassifier\n",
    "from sklearn.model_selection import train_test_split\n",
    "\n",
    "# generate training data, ideally we have more than actual data\n",
    "background = norm(0, 1).rvs(100000, random_state=2)\n",
    "signal = norm(1, 0.1).rvs(50000, random_state=2)\n",
    "x2 = np.append(signal, background)\n",
    "\n",
    "# features in general matrix [N, K] for N samples and K features\n",
    "X = x2.reshape((len(x2), 1))\n",
    "# labels: signal=1, background=0\n",
    "y = np.append(np.ones_like(signal), np.zeros_like(background))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "slideshow": {
     "slide_type": "slide"
    }
   },
   "outputs": [],
   "source": [
    "# ALWAYS do this: split into train and test datasets\n",
    "X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=3)\n",
    "\n",
    "# actual magic happens here\n",
    "clf = XGBClassifier(random_state=4)\n",
    "clf.fit(X_train, y_train);"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "slideshow": {
     "slide_type": "slide"
    }
   },
   "outputs": [],
   "source": [
    "fig, ax = plt.subplots(2, sharex=True)\n",
    "\n",
    "plt.sca(ax[0])\n",
    "xe = plot(X_test[:, 0], y_test)\n",
    "plt.xlabel(None)  # unset label set by `plot`\n",
    "\n",
    "plt.sca(ax[1])\n",
    "score = clf.score(X_test, y_test)\n",
    "xm = np.linspace(xe[0], xe[-1], 200)\n",
    "ps, pb = clf.predict_proba(xm).T\n",
    "\n",
    "plt.xlabel(\"x\")\n",
    "plt.plot(xm, ps, \"C0-\", label=\"background probability\")\n",
    "plt.plot(xm, pb, \"C1-\", label=\"signal probability\")\n",
    "plt.legend(title=f\"score={score:.2f}\", frameon=False);"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "slideshow": {
     "slide_type": "slide"
    }
   },
   "source": [
    "Exercise:\n",
    "* Vary some hyperparameters in `XGBClassifier` to see how score, runtime, and predicted probability changes\n",
    "  * `n_estimators` try e.g. 2, 5, 10\n",
    "  * `max_depth` try e.g. 1, 5, 10\n",
    "  * `learning_rate` try e.g. 0.001, 0.05, 0.5, 1"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "slideshow": {
     "slide_type": "slide"
    }
   },
   "source": [
    "* BDT predicts signal probability\n",
    "* We use this to implement our cut: select regions with high signal probability"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "slideshow": {
     "slide_type": "slide"
    }
   },
   "outputs": [],
   "source": [
    "ps = clf.predict_proba(X_test[y_test==1])[:, 1]\n",
    "pb = clf.predict_proba(X_test[y_test==0])[:, 1]\n",
    "xe = plt.hist(ps, bins=20, alpha=0.5, label=\"true signal\")[1]\n",
    "plt.hist(pb, bins=xe, alpha=0.5, label=\"true background\")\n",
    "plt.legend()\n",
    "plt.xlabel(\"predicted signal probability\")\n",
    "plt.ylim(0, 5e3);"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "slideshow": {
     "slide_type": "slide"
    }
   },
   "outputs": [],
   "source": [
    "xe = plot(X_test[:, 0], y_test)\n",
    "\n",
    "# chosen cut: signal probability > 0.6\n",
    "# visualize accepted region\n",
    "xm = np.linspace(xe[0], xe[-1], 200)\n",
    "mask = clf.predict_proba(xm)[:, 1] > 0.6\n",
    "plt.plot(xm, mask * 5000, \"k-\");"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "slideshow": {
     "slide_type": "slide"
    }
   },
   "outputs": [],
   "source": [
    "pmin = np.linspace(0, 1, 100)\n",
    "efficiency = []\n",
    "purity = []\n",
    "for pm in pmin:\n",
    "    mask = clf.predict_proba(X_test)[:, 1] > pm\n",
    "    selected = np.sum(mask)\n",
    "    selected_signal = np.sum(y_test[mask])\n",
    "    total_signal = np.sum(y_test)\n",
    "    efficiency.append(selected_signal / total_signal)\n",
    "    with np.errstate(divide=\"ignore\", invalid=\"ignore\"):\n",
    "        purity.append(selected_signal / selected)\n",
    "plt.plot(pmin, efficiency, label=\"efficiency\")\n",
    "plt.plot(pmin, purity, label=\"purity\")\n",
    "plt.xlabel(\"pmin\")\n",
    "plt.legend();"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "slideshow": {
     "slide_type": "slide"
    }
   },
   "outputs": [],
   "source": [
    "plt.scatter(efficiency, purity, c=pmin);\n",
    "plt.xlim(0, 1)\n",
    "plt.ylim(0, 1)\n",
    "plt.xlabel(\"efficiency\")\n",
    "plt.ylabel(\"purity\")\n",
    "plt.colorbar().set_label(\"pmin\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "slideshow": {
     "slide_type": "slide"
    }
   },
   "source": [
    "* Physicists like efficiency and purity, but ROC curve is standard\n",
    "* Receiver-operator characteristic\n",
    "* ROC plots *true positive rate* (fraction of signal that passes cut) over *false positive rate* (fraction of background that passes cut)\n",
    "* Scikit-Learn provides a quick way to generate this plot"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "slideshow": {
     "slide_type": "slide"
    }
   },
   "outputs": [],
   "source": [
    "from sklearn.metrics import RocCurveDisplay\n",
    "\n",
    "RocCurveDisplay.from_estimator(clf, X_test, y_test);"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "slideshow": {
     "slide_type": "slide"
    }
   },
   "source": [
    "* area under curve (AUC) is a common metric to compare the performance of two different classifiers\n",
    "* can also use Scikit-Learn to compute ROC points and AUC and plot these ourselves"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "slideshow": {
     "slide_type": "slide"
    }
   },
   "outputs": [],
   "source": [
    "from sklearn.metrics import roc_curve, auc\n",
    "\n",
    "# plot XGBoost curve again\n",
    "fpr, tpr, thresholds = roc_curve(y_test, clf.predict_proba(X_test)[:, 1])\n",
    "plt.plot(fpr, tpr, label=f\"XGBoost AUC={auc(fpr, tpr):.2f}\")\n",
    "\n",
    "# plot ROC curve for our simple x > 0.7 cut for comparison\n",
    "fpr2, tpr2, _ = roc_curve(y_test, X_test[:, 0] > 0.7)\n",
    "plt.plot(fpr2, tpr2, label=f\"x > 0.7 AUC={auc(fpr2, tpr2):.2f}\")\n",
    "\n",
    "plt.xlabel(\"False positive rate\")\n",
    "plt.ylabel(\"True positive rate\")\n",
    "plt.legend();"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "slideshow": {
     "slide_type": "slide"
    }
   },
   "source": [
    "* Exercise: [run scikit-learn example](https://scikit-learn.org/stable/auto_examples/classification/plot_classifier_comparison.html)\n",
    "* Try adding XGBClassifier into the comparison\n",
    "* Play around with the hyperparameters of the classifiers"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "slideshow": {
     "slide_type": "slide"
    }
   },
   "source": [
    "## Regression\n",
    "\n",
    "* Regression (aka fitting): \"learn\" function y = f(x) from points(x, y), where both x and y can be vectors\n",
    "* Machines can do this, but we rarely need this in HEP\n",
    "* We usually prefer to use theoretically motivated models or hand-crafted low-order polynoms"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "slideshow": {
     "slide_type": "slide"
    }
   },
   "source": [
    "* Let's try regression on one-dimensional function"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "slideshow": {
     "slide_type": "-"
    }
   },
   "outputs": [],
   "source": [
    "def model(x, a, b, c, d):\n",
    "    return a + b * np.sin(c * x) * np.exp(- d * x)\n",
    "\n",
    "truth = 0.2, 1, 2, 0.5\n",
    "\n",
    "x = np.linspace(0, 10, 1000)\n",
    "plt.plot(x, model(x, *truth))\n",
    "plt.xlabel(\"x\")\n",
    "plt.ylabel(\"y\");"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "slideshow": {
     "slide_type": "slide"
    }
   },
   "source": [
    "* generate random points on this curve and add some noise to make it more realistic"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "slideshow": {
     "slide_type": "-"
    }
   },
   "outputs": [],
   "source": [
    "rng = np.random.default_rng(1)\n",
    "\n",
    "x = rng.uniform(0, 10, 1000)\n",
    "y = model(x, 0.2, 1, 2, 0.5)\n",
    "y += rng.normal(0, 0.05, len(y))\n",
    "\n",
    "X = np.reshape(x, (-1, 1))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "slideshow": {
     "slide_type": "-"
    }
   },
   "source": [
    "* (X, y) are inputs for regression similar to before, but y is a real number now, not a label (integer)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "slideshow": {
     "slide_type": "slide"
    }
   },
   "source": [
    "### Neural network\n",
    "\n",
    "* We use [MLPRegressor](https://scikit-learn.org/stable/modules/generated/sklearn.neural_network.MLPRegressor.html#sklearn.neural_network.MLPRegressor) from Scikit-Learn, a basic neural network\n",
    "* Neural networks always need preprocessing\n",
    "* Scikit-Learn offers pipelines to automate this, use them"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "slideshow": {
     "slide_type": "slide"
    }
   },
   "outputs": [],
   "source": [
    "from sklearn.neural_network import MLPRegressor\n",
    "from sklearn.preprocessing import StandardScaler\n",
    "from sklearn.pipeline import make_pipeline\n",
    "\n",
    "# network with 5 hidden layers with 100 nodes each\n",
    "regressor = MLPRegressor(\n",
    "    hidden_layer_sizes=(100,)*5,\n",
    "    random_state=1)\n",
    "\n",
    "# we use basic StandardScaler for preprocessing\n",
    "pipeline = make_pipeline(StandardScaler(), regressor)\n",
    "pipeline.fit(X, y);"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "slideshow": {
     "slide_type": "slide"
    }
   },
   "outputs": [],
   "source": [
    "# compute fitted curve\n",
    "X2 = np.reshape(np.linspace(0, 10, 1000), (-1, 1))\n",
    "y2 = pipeline.predict(X2)\n",
    "\n",
    "plt.plot(x, y, \".\")\n",
    "plt.plot(X2[:, 0], y2, color=\"r\", label=\"Neural net\")\n",
    "plt.plot(X2[:, 0], model(X2[:, 0], *truth), color=\"k\", label=\"truth\")\n",
    "plt.legend()\n",
    "plt.xlabel(\"x\")\n",
    "plt.ylabel(\"y\");"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "slideshow": {
     "slide_type": "slide"
    }
   },
   "source": [
    "* Exercise: play around with hyperparameters of MLPRegressor\n",
    "* What happens if you remove the StandardScaler?\n",
    "* What performs better, deep or wide networks?"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "slideshow": {
     "slide_type": "slide"
    }
   },
   "source": [
    "### Gaussian Process\n",
    "\n",
    "* For low-dimensional data, Gaussian Process Regression can work well\n",
    "* Not easy to set up: need to select suitable kernels and configure them\n",
    "* Advantage: Predicts uncertainty and automatically provides smooth solution"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "slideshow": {
     "slide_type": "slide"
    }
   },
   "outputs": [],
   "source": [
    "from sklearn.gaussian_process import GaussianProcessRegressor\n",
    "from sklearn.gaussian_process.kernels import RBF, WhiteKernel\n",
    "\n",
    "kernel = RBF() + WhiteKernel()\n",
    "\n",
    "gpr = GaussianProcessRegressor(kernel=kernel)\n",
    "gpr.fit(X, y)\n",
    "y3, y3err = gpr.predict(X2, return_std=True)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "slideshow": {
     "slide_type": "slide"
    }
   },
   "outputs": [],
   "source": [
    "plt.plot(x, y, \".\")\n",
    "plt.plot(X2[:, 0], model(X2[:, 0], *truth), color=\"k\", label=\"truth\")\n",
    "plt.plot(X2[:, 0], y2, color=\"r\", label=\"Neural net\")\n",
    "l = plt.plot(X2[:, 0], y3, label=\"Gaussian Process\")[0]\n",
    "plt.fill_between(X2[:, 0], y3 - y3err, y3 + y3err, alpha=0.8, color=l.get_color())\n",
    "plt.legend();"
   ]
  }
 ],
 "metadata": {
  "celltoolbar": "Slideshow",
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "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.9"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
