From 1b5934da6ea4a12d7e8ea5b1e0991fa00bbdc1a7 Mon Sep 17 00:00:00 2001 From: Morten Hjorth-Jensen Date: Sun, 18 Aug 2024 21:52:31 +0200 Subject: [PATCH] update --- doc/LectureNotes/exercisesweek34.ipynb | 302 - doc/LectureNotes/exercisesweek36.ipynb | 394 - doc/LectureNotes/exercisesweek37.ipynb | 268 - doc/LectureNotes/exercisesweek38.ipynb | 183 - doc/LectureNotes/exercisesweek39.ipynb | 59 - doc/LectureNotes/exercisesweek41.ipynb | 1144 --- doc/LectureNotes/exercisesweek42.ipynb | 73 - doc/LectureNotes/exercisesweek43.ipynb | 1940 ----- doc/LectureNotes/exercisesweek47.ipynb | 214 - doc/LectureNotes/week34.ipynb | 4962 ----------- doc/LectureNotes/week35.ipynb | 6044 ------------- doc/LectureNotes/week36.ipynb | 4242 ---------- doc/LectureNotes/week37.ipynb | 3538 -------- doc/LectureNotes/week38.ipynb | 3014 ------- doc/LectureNotes/week39.ipynb | 4889 ----------- doc/LectureNotes/week40.ipynb | 3545 -------- doc/LectureNotes/week41.ipynb | 3537 -------- doc/LectureNotes/week42.ipynb | 2643 ------ doc/LectureNotes/week43.ipynb | 7528 ----------------- doc/LectureNotes/week44.ipynb | 5951 ------------- doc/LectureNotes/week45.ipynb | 1997 ----- doc/LectureNotes/week46.ipynb | 3131 ------- doc/LectureNotes/week47.ipynb | 3018 ------- doc/src/week35/exercisesweek35.do.txt | 4 +- .../week35}/exercisesweek35.ipynb | 66 +- 25 files changed, 35 insertions(+), 62651 deletions(-) delete mode 100644 doc/LectureNotes/exercisesweek34.ipynb delete mode 100644 doc/LectureNotes/exercisesweek36.ipynb delete mode 100644 doc/LectureNotes/exercisesweek37.ipynb delete mode 100644 doc/LectureNotes/exercisesweek38.ipynb delete mode 100644 doc/LectureNotes/exercisesweek39.ipynb delete mode 100644 doc/LectureNotes/exercisesweek41.ipynb delete mode 100644 doc/LectureNotes/exercisesweek42.ipynb delete mode 100644 doc/LectureNotes/exercisesweek43.ipynb delete mode 100644 doc/LectureNotes/exercisesweek47.ipynb delete mode 100644 doc/LectureNotes/week34.ipynb delete mode 100644 doc/LectureNotes/week35.ipynb delete mode 100644 doc/LectureNotes/week36.ipynb delete mode 100644 doc/LectureNotes/week37.ipynb delete mode 100644 doc/LectureNotes/week38.ipynb delete mode 100644 doc/LectureNotes/week39.ipynb delete mode 100644 doc/LectureNotes/week40.ipynb delete mode 100644 doc/LectureNotes/week41.ipynb delete mode 100644 doc/LectureNotes/week42.ipynb delete mode 100644 doc/LectureNotes/week43.ipynb delete mode 100644 doc/LectureNotes/week44.ipynb delete mode 100644 doc/LectureNotes/week45.ipynb delete mode 100644 doc/LectureNotes/week46.ipynb delete mode 100644 doc/LectureNotes/week47.ipynb rename doc/{LectureNotes => src/week35}/exercisesweek35.ipynb (93%) diff --git a/doc/LectureNotes/exercisesweek34.ipynb b/doc/LectureNotes/exercisesweek34.ipynb deleted file mode 100644 index 48f94ceda..000000000 --- a/doc/LectureNotes/exercisesweek34.ipynb +++ /dev/null @@ -1,302 +0,0 @@ -{ - "cells": [ - { - "cell_type": "markdown", - "id": "241c4a61", - "metadata": { - "editable": true - }, - "source": [ - "\n", - "" - ] - }, - { - "cell_type": "markdown", - "id": "a33815b9", - "metadata": { - "editable": true - }, - "source": [ - "# Exercises week 34\n", - "**FYS-STK3155/4155**\n", - "\n", - "Date: **August 21-25, 2023**" - ] - }, - { - "cell_type": "markdown", - "id": "2990585c", - "metadata": { - "editable": true - }, - "source": [ - "## Exercises\n", - "\n", - "Here are three possible exercises for week 34" - ] - }, - { - "cell_type": "markdown", - "id": "be056de0", - "metadata": { - "editable": true - }, - "source": [ - "## Exercise 1: Setting up various Python environments\n", - "\n", - "The first exercise here is of a mere technical art. We want you to have \n", - "* git as a version control software and to establish a user account on a provider like GitHub. Other providers like GitLab etc are equally fine. You can also use the University of Oslo [GitHub facilities](https://www.uio.no/tjenester/it/maskin/filer/versjonskontroll/github.html). \n", - "\n", - "* Install various Python packages\n", - "\n", - "We will make extensive use of Python as programming language and its\n", - "myriad of available libraries. You will find\n", - "IPython/Jupyter notebooks invaluable in your work. You can run **R**\n", - "codes in the Jupyter/IPython notebooks, with the immediate benefit of\n", - "visualizing your data. You can also use compiled languages like C++,\n", - "Rust, Fortran etc if you prefer. The focus in these lectures will be\n", - "on Python.\n", - "\n", - "If you have Python installed (we recommend Python3) and you feel\n", - "pretty familiar with installing different packages, we recommend that\n", - "you install the following Python packages via **pip** as \n", - "\n", - "1. pip install numpy scipy matplotlib ipython scikit-learn sympy pandas pillow \n", - "\n", - "For **Tensorflow**, we recommend following the instructions in the text of \n", - "[Aurelien Geron, Hands‑On Machine Learning with Scikit‑Learn and TensorFlow, O'Reilly](http://shop.oreilly.com/product/0636920052289.do)\n", - "\n", - "We will come back to **tensorflow** later. \n", - "\n", - "For Python3, replace **pip** with **pip3**.\n", - "\n", - "For OSX users we recommend, after having installed Xcode, to\n", - "install **brew**. Brew allows for a seamless installation of additional\n", - "software via for example \n", - "\n", - "1. brew install python3\n", - "\n", - "For Linux users, with its variety of distributions like for example the widely popular Ubuntu distribution,\n", - "you can use **pip** as well and simply install Python as \n", - "\n", - "1. sudo apt-get install python3 (or python for Python2.7)\n", - "\n", - "If you don't want to perform these operations separately and venture\n", - "into the hassle of exploring how to set up dependencies and paths, we\n", - "recommend two widely used distrubutions which set up all relevant\n", - "dependencies for Python, namely \n", - "\n", - "* [Anaconda](https://docs.anaconda.com/), \n", - "\n", - "which is an open source\n", - "distribution of the Python and R programming languages for large-scale\n", - "data processing, predictive analytics, and scientific computing, that\n", - "aims to simplify package management and deployment. Package versions\n", - "are managed by the package management system **conda**. \n", - "\n", - "* [Enthought canopy](https://www.enthought.com/product/canopy/) \n", - "\n", - "is a Python\n", - "distribution for scientific and analytic computing distribution and\n", - "analysis environment, available for free and under a commercial\n", - "license.\n", - "\n", - "We recommend using **Anaconda** if you are not too familiar with setting paths in a terminal environment." - ] - }, - { - "cell_type": "markdown", - "id": "f0f4ffae", - "metadata": { - "editable": true - }, - "source": [ - "## Exercise 2: making your own data and exploring scikit-learn\n", - "\n", - "We will generate our own dataset for a function $y(x)$ where $x \\in [0,1]$ and defined by random numbers computed with the uniform distribution. The function $y$ is a quadratic polynomial in $x$ with added stochastic noise according to the normal distribution $\\cal {N}(0,1)$.\n", - "The following simple Python instructions define our $x$ and $y$ values (with 100 data points)." - ] - }, - { - "cell_type": "code", - "execution_count": 1, - "id": "93d6a2b2", - "metadata": { - "collapsed": false, - "editable": true - }, - "outputs": [], - "source": [ - "x = np.random.rand(100,1)\n", - "y = 2.0+5*x*x+0.1*np.random.randn(100,1)" - ] - }, - { - "cell_type": "markdown", - "id": "45392145", - "metadata": { - "editable": true - }, - "source": [ - "1. Write your own code (following the examples under the [regression notes](https://compphysics.github.io/MachineLearning/doc/LectureNotes/_build/html/chapter1.html)) for computing the parametrization of the data set fitting a second-order polynomial. \n", - "\n", - "2. Use thereafter **scikit-learn** (see again the examples in the regression slides) and compare with your own code. \n", - "\n", - "3. Using scikit-learn, compute also the mean square error, a risk metric corresponding to the expected value of the squared (quadratic) error defined as" - ] - }, - { - "cell_type": "markdown", - "id": "3eed315b", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "MSE(\\boldsymbol{y},\\boldsymbol{\\tilde{y}}) = \\frac{1}{n}\n", - "\\sum_{i=0}^{n-1}(y_i-\\tilde{y}_i)^2,\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "26038071", - "metadata": { - "editable": true - }, - "source": [ - "and the $R^2$ score function.\n", - "If $\\tilde{\\boldsymbol{y}}_i$ is the predicted value of the $i-th$ sample and $y_i$ is the corresponding true value, then the score $R^2$ is defined as" - ] - }, - { - "cell_type": "markdown", - "id": "4c750d55", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "R^2(\\boldsymbol{y}, \\tilde{\\boldsymbol{y}}) = 1 - \\frac{\\sum_{i=0}^{n - 1} (y_i - \\tilde{y}_i)^2}{\\sum_{i=0}^{n - 1} (y_i - \\bar{y})^2},\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "30b4731e", - "metadata": { - "editable": true - }, - "source": [ - "where we have defined the mean value of $\\boldsymbol{y}$ as" - ] - }, - { - "cell_type": "markdown", - "id": "49afe51d", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\bar{y} = \\frac{1}{n} \\sum_{i=0}^{n - 1} y_i.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "81f16b80", - "metadata": { - "editable": true - }, - "source": [ - "You can use the functionality included in scikit-learn. If you feel for it, you can use your own program and define functions which compute the above two functions. \n", - "Discuss the meaning of these results. Try also to vary the coefficient in front of the added stochastic noise term and discuss the quality of the fits." - ] - }, - { - "cell_type": "markdown", - "id": "cb71cb1c", - "metadata": { - "editable": true - }, - "source": [ - "## Exercise 3: Split data in test and training data\n", - "\n", - "In this exercise we want you to to compute the MSE for the training\n", - "data and the test data as function of the complexity of a polynomial,\n", - "that is the degree of a given polynomial.\n", - "\n", - "The aim is to reproduce Figure 2.11 of [Hastie et al](https://github.com/CompPhysics/MLErasmus/blob/master/doc/Textbooks/elementsstat.pdf).\n", - "\n", - "Our data is defined by $x\\in [-3,3]$ with a total of for example $n=100$ data points. You should try to vary the number of data points $n$ in your analysis." - ] - }, - { - "cell_type": "code", - "execution_count": 2, - "id": "b8c919e5", - "metadata": { - "collapsed": false, - "editable": true - }, - "outputs": [], - "source": [ - "np.random.seed()\n", - "n = 100\n", - "# Make data set.\n", - "x = np.linspace(-3, 3, n).reshape(-1, 1)\n", - "y = np.exp(-x**2) + 1.5 * np.exp(-(x-2)**2)+ np.random.normal(0, 0.1, x.shape)" - ] - }, - { - "cell_type": "markdown", - "id": "50629e14", - "metadata": { - "editable": true - }, - "source": [ - "where $y$ is the function we want to fit with a given polynomial." - ] - }, - { - "cell_type": "markdown", - "id": "0578f08c", - "metadata": { - "editable": true - }, - "source": [ - "**a)**\n", - "Write a first code which sets up a design matrix $X$ defined by a fifth-order polynomial and split your data set in training and test data." - ] - }, - { - "cell_type": "markdown", - "id": "125ec9a1", - "metadata": { - "editable": true - }, - "source": [ - "**b)**\n", - "Write thereafter (using either **scikit-learn** or your matrix inversion code using for example **numpy**)\n", - "and perform an ordinary least squares fitting and compute the mean squared error for the training data and the test data. These calculations should apply to a model given by a fifth-order polynomial." - ] - }, - { - "cell_type": "markdown", - "id": "e5bb2036", - "metadata": { - "editable": true - }, - "source": [ - "**c)**\n", - "Add now a model which allows you to make polynomials up to degree $15$. Perform a standard OLS fitting of the training data and compute the MSE for the training and test data and plot both test and training data MSE as functions of the polynomial degree. Compare what you see with Figure 2.11 of Hastie et al. Comment your results. For which polynomial degree do you find an optimal MSE (smallest value)?" - ] - } - ], - "metadata": {}, - "nbformat": 4, - "nbformat_minor": 5 -} diff --git a/doc/LectureNotes/exercisesweek36.ipynb b/doc/LectureNotes/exercisesweek36.ipynb deleted file mode 100644 index 405343ad2..000000000 --- a/doc/LectureNotes/exercisesweek36.ipynb +++ /dev/null @@ -1,394 +0,0 @@ -{ - "cells": [ - { - "cell_type": "markdown", - "id": "fb4d27e1", - "metadata": { - "editable": true - }, - "source": [ - "\n", - "" - ] - }, - { - "cell_type": "markdown", - "id": "c3ef468d", - "metadata": { - "editable": true - }, - "source": [ - "# Exercises week 36\n", - "**September 4-8, 2023**\n", - "\n", - "Date: **Deadline is Sunday September 10 at midnight**" - ] - }, - { - "cell_type": "markdown", - "id": "b81273ff", - "metadata": { - "editable": true - }, - "source": [ - "## Overarching aims of the exercises this week\n", - "\n", - "This set of exercises form an important part of the first project. The\n", - "analytical exercises deal with the material covered last week on the\n", - "mathematical interpretations of ordinary least squares and of Ridge\n", - "regression. The numerical exercises can be seen as a continuation of\n", - "exercise 3 from week 35, with the inclusion of Ridge regression. This\n", - "material enters also the discussions of the first project." - ] - }, - { - "cell_type": "markdown", - "id": "53c4e245", - "metadata": { - "editable": true - }, - "source": [ - "## Exercise 1: Analytical exercises\n", - "\n", - "The aim here is to derive the expression for the optimal parameters\n", - "using Ridge regression. Furthermore, using the singular value\n", - "decomposition, we will analyze the difference between the ordinary\n", - "least squares approach and Ridge regression.\n", - "\n", - "The expression for the standard Mean Squared Error (MSE) which we used to define our cost function and the equations for the ordinary least squares (OLS) method, was given by the\n", - "optimization problem" - ] - }, - { - "cell_type": "markdown", - "id": "e5813e09", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "{\\displaystyle \\min_{\\boldsymbol{\\beta}\\in {\\mathbb{R}}^{p}}}\\frac{1}{n}\\left\\{\\left(\\boldsymbol{y}-\\boldsymbol{X}\\boldsymbol{\\beta}\\right)^T\\left(\\boldsymbol{y}-\\boldsymbol{X}\\boldsymbol{\\beta}\\right)\\right\\}.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "f8af4862", - "metadata": { - "editable": true - }, - "source": [ - "which we can also write as" - ] - }, - { - "cell_type": "markdown", - "id": "8a114760", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "{\\displaystyle \\min_{\\boldsymbol{\\beta}\\in\n", - "{\\mathbb{R}}^{p}}}\\frac{1}{n}\\sum_{i=0}^{n-1}\\left(y_i-\\tilde{y}_i\\right)^2=\\frac{1}{n}\\vert\\vert \\boldsymbol{y}-\\boldsymbol{X}\\boldsymbol{\\beta}\\vert\\vert_2^2,\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "c4610a33", - "metadata": { - "editable": true - }, - "source": [ - "where we have used the definition of a norm-2 vector, that is" - ] - }, - { - "cell_type": "markdown", - "id": "a3608d5c", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\vert\\vert \\boldsymbol{x}\\vert\\vert_2 = \\sqrt{\\sum_i x_i^2}.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "5dcf5daa", - "metadata": { - "editable": true - }, - "source": [ - "By minimizing the above equation with respect to the parameters\n", - "$\\boldsymbol{\\beta}$ we could then obtain an analytical expression for the\n", - "parameters $\\boldsymbol{\\beta}$.\n", - "\n", - "We can add a regularization parameter $\\lambda$ by\n", - "defining a new cost function to be optimized, that is" - ] - }, - { - "cell_type": "markdown", - "id": "0cbd93fd", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "{\\displaystyle \\min_{\\boldsymbol{\\beta}\\in\n", - "{\\mathbb{R}}^{p}}}\\frac{1}{n}\\vert\\vert \\boldsymbol{y}-\\boldsymbol{X}\\boldsymbol{\\beta}\\vert\\vert_2^2+\\lambda\\vert\\vert \\boldsymbol{\\beta}\\vert\\vert_2^2\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "6fba5d18", - "metadata": { - "editable": true - }, - "source": [ - "which leads to the Ridge regression minimization problem. One can require as part of the optimization problem \n", - "that $\\vert\\vert \\boldsymbol{\\beta}\\vert\\vert_2^2\\le t$, where $t$ is\n", - "a finite number larger than zero. We will not implement that here." - ] - }, - { - "cell_type": "markdown", - "id": "bec3e21d", - "metadata": { - "editable": true - }, - "source": [ - "### a) Expression for Ridge regression\n", - "\n", - "Show that the optimal parameters" - ] - }, - { - "cell_type": "markdown", - "id": "380e526b", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\hat{\\boldsymbol{\\beta}}_{\\mathrm{Ridge}} = \\left(\\boldsymbol{X}^T\\boldsymbol{X}+\\lambda\\boldsymbol{I}\\right)^{-1}\\boldsymbol{X}^T\\boldsymbol{y},\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "97a04d2d", - "metadata": { - "editable": true - }, - "source": [ - "with $\\boldsymbol{I}$ being a $p\\times p$ identity matrix with the constraint that" - ] - }, - { - "cell_type": "markdown", - "id": "a378590f", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\sum_{i=0}^{p-1} \\beta_i^2 \\leq t,\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "f2d2d7ae", - "metadata": { - "editable": true - }, - "source": [ - "with $t$ a finite positive number. In the optimization, we will not require that the latter is satisfied.\n", - "\n", - "The ordinary least squares result is" - ] - }, - { - "cell_type": "markdown", - "id": "b2ffd80f", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\hat{\\boldsymbol{\\beta}}_{\\mathrm{OLS}} = \\left(\\boldsymbol{X}^T\\boldsymbol{X}\\right)^{-1}\\boldsymbol{X}^T\\boldsymbol{y},\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "3c3a9191", - "metadata": { - "editable": true - }, - "source": [ - "### b) The singular value decomposition\n", - "\n", - "Here we will use the singular value decomposition of an $n\\times p$ matrix $\\boldsymbol{X}$ (our design matrix)" - ] - }, - { - "cell_type": "markdown", - "id": "4e3f0bb8", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\boldsymbol{X}=\\boldsymbol{U}\\boldsymbol{\\Sigma}\\boldsymbol{V}^T,\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "040a6f88", - "metadata": { - "editable": true - }, - "source": [ - "to study properties of Ridge regression and ordinary least squares regression.\n", - "Here $\\boldsymbol{U}$ and $\\boldsymbol{V}$ are orthogonal matrices of dimensions\n", - "$n\\times n$ and $p\\times p$, respectively, and $\\boldsymbol{\\Sigma}$ is an\n", - "$n\\times p$ matrix which contains the singular values only. This material was discussed during the lectures of week 35.\n", - "\n", - "Show that you can write the \n", - "OLS solutions in terms of the eigenvectors (the columns) of the orthogonal matrix $\\boldsymbol{U}$ as" - ] - }, - { - "cell_type": "markdown", - "id": "0107597b", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\tilde{\\boldsymbol{y}}_{\\mathrm{OLS}}=\\boldsymbol{X}\\boldsymbol{\\beta} = \\sum_{j=0}^{p-1}\\boldsymbol{u}_j\\boldsymbol{u}_j^T\\boldsymbol{y}.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "55fd1a9a", - "metadata": { - "editable": true - }, - "source": [ - "For Ridge regression, show that the corresponding equation is" - ] - }, - { - "cell_type": "markdown", - "id": "8a05634c", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\tilde{\\boldsymbol{y}}_{\\mathrm{Ridge}}=\\boldsymbol{X}\\boldsymbol{\\beta}_{\\mathrm{Ridge}} = \\boldsymbol{U\\Sigma V^T}\\left(\\boldsymbol{V}\\boldsymbol{\\Sigma}^2\\boldsymbol{V}^T+\\lambda\\boldsymbol{I} \\right)^{-1}(\\boldsymbol{U\\Sigma V^T})^T\\boldsymbol{y}=\\sum_{j=0}^{p-1}\\boldsymbol{u}_j\\boldsymbol{u}_j^T\\frac{\\sigma_j^2}{\\sigma_j^2+\\lambda}\\boldsymbol{y},\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "5d46ab65", - "metadata": { - "editable": true - }, - "source": [ - "with the vectors $\\boldsymbol{u}_j$ being the columns of $\\boldsymbol{U}$ from the SVD of the matrix $\\boldsymbol{X}$. \n", - "\n", - "Give an interpretation of the results. [Section 3.4 of Hastie et al's textbook gives a good discussion of the above results](https://link.springer.com/book/10.1007/978-0-387-84858-7)." - ] - }, - { - "cell_type": "markdown", - "id": "478a39d8", - "metadata": { - "editable": true - }, - "source": [ - "## Exercise 2: Adding Ridge Regression\n", - "\n", - "This exercise is a continuation of exercise 3 from week 35, see . We will use the same function to\n", - "generate our data set, still staying with a simple function $y(x)$\n", - "which we want to fit using linear regression, but now extending the\n", - "analysis to include the Ridge regression method.\n", - "\n", - "In this exercise you need to include the same elements from last week, that is\n", - "1. scale your data by subtracting the mean value from each column in the design matrix.\n", - "\n", - "2. perform a split of the data in a training set and a test set.\n", - "\n", - "The addition to the analysis this time is the introduction of the hyperparameter $\\lambda$ when introducing Ridge regression.\n", - "\n", - "Extend the code from exercise 3 from [week 35](https://compphysics.github.io/MachineLearning/doc/LectureNotes/_build/html/exercisesweek35.html) to include Ridge regression with the hyperparameter $\\lambda$. The optimal parameters $\\hat{\\beta}$ for Ridge regression can be obtained by matrix inversion in a similar way as done for ordinary least squares. You need to add to your code the following equations" - ] - }, - { - "cell_type": "markdown", - "id": "ed28dbd2", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\hat{\\boldsymbol{\\beta}}_{\\mathrm{Ridge}} = \\left(\\boldsymbol{X}^T\\boldsymbol{X}+\\lambda\\boldsymbol{I}\\right)^{-1}\\boldsymbol{X}^T\\boldsymbol{y}.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "1939c401", - "metadata": { - "editable": true - }, - "source": [ - "The ordinary least squares result you encoded last week is given by" - ] - }, - { - "cell_type": "markdown", - "id": "10877c2d", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\hat{\\boldsymbol{\\beta}}_{\\mathrm{OLS}} = \\left(\\boldsymbol{X}^T\\boldsymbol{X}\\right)^{-1}\\boldsymbol{X}^T\\boldsymbol{y},\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "a7adfe54", - "metadata": { - "editable": true - }, - "source": [ - "Use these results to compute the mean squared error for ordinary least\n", - "squares and Ridge regression first for a polynomial of degree five\n", - "with $n=100$ data points and five selected values of\n", - "$\\lambda=[0.0001,0.001, 0.01,0.1,1.0]$. Compute thereafter the mean\n", - "squared error for the same values of $\\lambda$ for polynomials of degree ten\n", - "and $15$. Discuss your results for the training MSE and test MSE with\n", - "Ridge regression and ordinary least squares." - ] - } - ], - "metadata": {}, - "nbformat": 4, - "nbformat_minor": 5 -} diff --git a/doc/LectureNotes/exercisesweek37.ipynb b/doc/LectureNotes/exercisesweek37.ipynb deleted file mode 100644 index 2753e48bf..000000000 --- a/doc/LectureNotes/exercisesweek37.ipynb +++ /dev/null @@ -1,268 +0,0 @@ -{ - "cells": [ - { - "cell_type": "markdown", - "id": "8b21a389", - "metadata": { - "editable": true - }, - "source": [ - "\n", - "" - ] - }, - { - "cell_type": "markdown", - "id": "10a3b32a", - "metadata": { - "editable": true - }, - "source": [ - "# Exercises week 37\n", - "**September 11-15, 2023**\n", - "\n", - "Date: **Deadline is Sunday September 17 at midnight**" - ] - }, - { - "cell_type": "markdown", - "id": "940daa26", - "metadata": { - "editable": true - }, - "source": [ - "## Overarching aims of the exercises this week\n", - "\n", - "This exercise deals with various mean values and variances in linear\n", - "regression method (here it may be useful to look up chapter 3,\n", - "equation (3.8) of [Trevor Hastie, Robert Tibshirani, Jerome\n", - "H. Friedman, The Elements of Statistical Learning,\n", - "Springer](https://www.springer.com/gp/book/9780387848570)). The\n", - "exercise is also a part of project 1 and can be reused in the theory\n", - "part of the project.\n", - "\n", - "For more discussions on Ridge regression and calculation of\n", - "expectation values, [Wessel van\n", - "Wieringen's](https://arxiv.org/abs/1509.09169) article is highly\n", - "recommended.\n", - "\n", - "The assumption we have made is that there exists a continuous function\n", - "$f(\\boldsymbol{x})$ and a normal distributed error $\\boldsymbol{\\varepsilon}\\sim N(0,\n", - "\\sigma^2)$ which describes our data" - ] - }, - { - "cell_type": "markdown", - "id": "d51b0da4", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\boldsymbol{y} = f(\\boldsymbol{x})+\\boldsymbol{\\varepsilon}\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "40a14559", - "metadata": { - "editable": true - }, - "source": [ - "We then approximate this function $f(\\boldsymbol{x})$ with our model $\\boldsymbol{\\tilde{y}}$ from the solution of the linear regression equations (ordinary least squares OLS), that is our\n", - "function $f$ is approximated by $\\boldsymbol{\\tilde{y}}$ where we minimized $(\\boldsymbol{y}-\\boldsymbol{\\tilde{y}})^2$, with" - ] - }, - { - "cell_type": "markdown", - "id": "e4afb2ea", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\boldsymbol{\\tilde{y}} = \\boldsymbol{X}\\boldsymbol{\\beta}.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "b0153681", - "metadata": { - "editable": true - }, - "source": [ - "The matrix $\\boldsymbol{X}$ is the so-called design or feature matrix." - ] - }, - { - "cell_type": "markdown", - "id": "17b98331", - "metadata": { - "editable": true - }, - "source": [ - "## Exercise 1: Expectation values for ordinary least squares expressions\n", - "\n", - "Show that the expectation value of $\\boldsymbol{y}$ for a given element $i$" - ] - }, - { - "cell_type": "markdown", - "id": "0e35faa1", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\mathbb{E}(y_i) =\\sum_{j}x_{ij} \\beta_j=\\mathbf{X}_{i, \\ast} \\, \\boldsymbol{\\beta},\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "c1c7837e", - "metadata": { - "editable": true - }, - "source": [ - "and that\n", - "its variance is" - ] - }, - { - "cell_type": "markdown", - "id": "0ab57c17", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\mbox{Var}(y_i) = \\sigma^2.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "345dbeca", - "metadata": { - "editable": true - }, - "source": [ - "Hence, $y_i \\sim N( \\mathbf{X}_{i, \\ast} \\, \\boldsymbol{\\beta}, \\sigma^2)$, that is $\\boldsymbol{y}$ follows a normal distribution with \n", - "mean value $\\boldsymbol{X}\\boldsymbol{\\beta}$ and variance $\\sigma^2$.\n", - "\n", - "With the OLS expressions for the optimal parameters $\\boldsymbol{\\hat{\\beta}}$ show that" - ] - }, - { - "cell_type": "markdown", - "id": "fea2ddcf", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\mathbb{E}(\\boldsymbol{\\hat{\\beta}}) = \\boldsymbol{\\beta}.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "683a72cf", - "metadata": { - "editable": true - }, - "source": [ - "Show finally that the variance of $\\boldsymbol{\\boldsymbol{\\beta}}$ is" - ] - }, - { - "cell_type": "markdown", - "id": "0dfd010a", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\mbox{Var}(\\boldsymbol{\\hat{\\beta}}) = \\sigma^2 \\, (\\mathbf{X}^{T} \\mathbf{X})^{-1}.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "d4e4aa80", - "metadata": { - "editable": true - }, - "source": [ - "We can use the last expression when we define a [so-called confidence interval](https://en.wikipedia.org/wiki/Confidence_interval) for the parameters $\\beta$. \n", - "A given parameter $\\beta_j$ is given by the diagonal matrix element of the above matrix." - ] - }, - { - "cell_type": "markdown", - "id": "acb128a7", - "metadata": { - "editable": true - }, - "source": [ - "## Exercise 2: Expectation values for Ridge regression\n", - "\n", - "Show that" - ] - }, - { - "cell_type": "markdown", - "id": "83af53d9", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\mathbb{E} \\big[ \\hat{\\boldsymbol{\\beta}}^{\\mathrm{Ridge}} \\big]=(\\mathbf{X}^{T} \\mathbf{X} + \\lambda \\mathbf{I}_{pp})^{-1} (\\mathbf{X}^{\\top} \\mathbf{X})\\boldsymbol{\\beta}.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "1bbd0f50", - "metadata": { - "editable": true - }, - "source": [ - "We see clearly that\n", - "$\\mathbb{E} \\big[ \\hat{\\boldsymbol{\\beta}}^{\\mathrm{Ridge}} \\big] \\not= \\mathbb{E} \\big[\\hat{\\boldsymbol{\\beta}}^{\\mathrm{OLS}}\\big ]$ for any $\\lambda > 0$.\n", - "\n", - "Show also that the variance is" - ] - }, - { - "cell_type": "markdown", - "id": "617deac1", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\mbox{Var}[\\hat{\\boldsymbol{\\beta}}^{\\mathrm{Ridge}}]=\\sigma^2[ \\mathbf{X}^{T} \\mathbf{X} + \\lambda \\mathbf{I} ]^{-1} \\mathbf{X}^{T}\\mathbf{X} \\{ [ \\mathbf{X}^{\\top} \\mathbf{X} + \\lambda \\mathbf{I} ]^{-1}\\}^{T},\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "bee378b0", - "metadata": { - "editable": true - }, - "source": [ - "and it is easy to see that if the parameter $\\lambda$ goes to infinity then the variance of the Ridge parameters $\\boldsymbol{\\beta}$ goes to zero." - ] - } - ], - "metadata": {}, - "nbformat": 4, - "nbformat_minor": 5 -} diff --git a/doc/LectureNotes/exercisesweek38.ipynb b/doc/LectureNotes/exercisesweek38.ipynb deleted file mode 100644 index bc0c0a7fb..000000000 --- a/doc/LectureNotes/exercisesweek38.ipynb +++ /dev/null @@ -1,183 +0,0 @@ -{ - "cells": [ - { - "cell_type": "markdown", - "id": "ce05d309", - "metadata": { - "editable": true - }, - "source": [ - "\n", - "" - ] - }, - { - "cell_type": "markdown", - "id": "5b7c1442", - "metadata": { - "editable": true - }, - "source": [ - "# Exercises week 38\n", - "**September 18-22, 2023**\n", - "\n", - "Date: **Deadline is Sunday September 24 at midnight**" - ] - }, - { - "cell_type": "markdown", - "id": "02e09b06", - "metadata": { - "editable": true - }, - "source": [ - "## Overarching aims of the exercises this week\n", - "\n", - "The aim of the exercises this week is to derive the equations for the bias-variance tradeoff to be used in project 1 as well as testing this for a simpler function using the bootstrap method. The exercises here can be reused in project 1 as well.\n", - "\n", - "Consider a\n", - "dataset $\\mathcal{L}$ consisting of the data\n", - "$\\mathbf{X}_\\mathcal{L}=\\{(y_j, \\boldsymbol{x}_j), j=0\\ldots n-1\\}$.\n", - "\n", - "We assume that the true data is generated from a noisy model" - ] - }, - { - "cell_type": "markdown", - "id": "babb7346", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\boldsymbol{y}=f(\\boldsymbol{x}) + \\boldsymbol{\\epsilon}.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "a5ee908c", - "metadata": { - "editable": true - }, - "source": [ - "Here $\\epsilon$ is normally distributed with mean zero and standard\n", - "deviation $\\sigma^2$.\n", - "\n", - "In our derivation of the ordinary least squares method we defined \n", - "an approximation to the function $f$ in terms of the parameters\n", - "$\\boldsymbol{\\beta}$ and the design matrix $\\boldsymbol{X}$ which embody our model,\n", - "that is $\\boldsymbol{\\tilde{y}}=\\boldsymbol{X}\\boldsymbol{\\beta}$.\n", - "\n", - "The parameters $\\boldsymbol{\\beta}$ are in turn found by optimizing the mean\n", - "squared error via the so-called cost function" - ] - }, - { - "cell_type": "markdown", - "id": "afa3df2c", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "C(\\boldsymbol{X},\\boldsymbol{\\beta}) =\\frac{1}{n}\\sum_{i=0}^{n-1}(y_i-\\tilde{y}_i)^2=\\mathbb{E}\\left[(\\boldsymbol{y}-\\boldsymbol{\\tilde{y}})^2\\right].\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "9665df80", - "metadata": { - "editable": true - }, - "source": [ - "Here the expected value $\\mathbb{E}$ is the sample value. \n", - "\n", - "Show that you can rewrite this in terms of a term which contains the variance of the model itself (the so-called variance term), a\n", - "term which measures the deviation from the true data and the mean value of the model (the bias term) and finally the variance of the noise.\n", - "That is, show that" - ] - }, - { - "cell_type": "markdown", - "id": "25391aba", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\mathbb{E}\\left[(\\boldsymbol{y}-\\boldsymbol{\\tilde{y}})^2\\right]=\\mathrm{Bias}[\\tilde{y}]+\\mathrm{var}[\\tilde{y}]+\\sigma^2,\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "b6e8652c", - "metadata": { - "editable": true - }, - "source": [ - "with" - ] - }, - { - "cell_type": "markdown", - "id": "77755270", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\mathrm{Bias}[\\tilde{y}]=\\mathbb{E}\\left[\\left(\\boldsymbol{y}-\\mathbb{E}\\left[\\boldsymbol{\\tilde{y}}\\right]\\right)^2\\right],\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "fa94db90", - "metadata": { - "editable": true - }, - "source": [ - "and" - ] - }, - { - "cell_type": "markdown", - "id": "4ecda624", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\mathrm{var}[\\tilde{y}]=\\mathbb{E}\\left[\\left(\\tilde{\\boldsymbol{y}}-\\mathbb{E}\\left[\\boldsymbol{\\tilde{y}}\\right]\\right)^2\\right]=\\frac{1}{n}\\sum_i(\\tilde{y}_i-\\mathbb{E}\\left[\\boldsymbol{\\tilde{y}}\\right])^2.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "2dcb3e9a", - "metadata": { - "editable": true - }, - "source": [ - "Explain what the terms mean and discuss their interpretations.\n", - "\n", - "Perform then a bias-variance analysis of a simple one-dimensional (or other models of your choice) function by\n", - "studying the MSE value as function of the complexity of your model. Use ordinary least squares only.\n", - "\n", - "Discuss the bias and variance trade-off as function\n", - "of your model complexity (the degree of the polynomial) and the number\n", - "of data points, and possibly also your training and test data using the **bootstrap** resampling method.\n", - "You can follow the code example in the jupyter-book at .\n", - "\n", - "See also the whiteboard notes from week 37 at " - ] - } - ], - "metadata": {}, - "nbformat": 4, - "nbformat_minor": 5 -} diff --git a/doc/LectureNotes/exercisesweek39.ipynb b/doc/LectureNotes/exercisesweek39.ipynb deleted file mode 100644 index d685e82d8..000000000 --- a/doc/LectureNotes/exercisesweek39.ipynb +++ /dev/null @@ -1,59 +0,0 @@ -{ - "cells": [ - { - "cell_type": "markdown", - "id": "f35930ac", - "metadata": { - "editable": true - }, - "source": [ - "\n", - "" - ] - }, - { - "cell_type": "markdown", - "id": "8cb567a0", - "metadata": { - "editable": true - }, - "source": [ - "# Exercises week 39\n", - "**September 25-29, 2023**\n", - "\n", - "Date: **Deadline is Sunday October 1 at midnight**" - ] - }, - { - "cell_type": "markdown", - "id": "934324b3", - "metadata": { - "editable": true - }, - "source": [ - "## Overarching aims of the exercises this week\n", - "\n", - "The aim of the exercises this week is to aid you in getting started\n", - "with writing the report. This will be discussed during the lab\n", - "sessions as well. One of the lab sessions will be recorded.\n", - "\n", - "A general guideline can be found at .\n", - "\n", - "Similarly, an example of an earlier project can be found at \n", - "\n", - "Your task this week is to\n", - "1. Write an abstract for your project\n", - "\n", - "2. Write an introduction\n", - "\n", - "3. Include references\n", - "\n", - "Ashort feedback to the this exercise will be available after the deadline. And you can reuse these elements in your final report." - ] - } - ], - "metadata": {}, - "nbformat": 4, - "nbformat_minor": 5 -} diff --git a/doc/LectureNotes/exercisesweek41.ipynb b/doc/LectureNotes/exercisesweek41.ipynb deleted file mode 100644 index 341ad034c..000000000 --- a/doc/LectureNotes/exercisesweek41.ipynb +++ /dev/null @@ -1,1144 +0,0 @@ -{ - "cells": [ - { - "cell_type": "markdown", - "id": "e3354581", - "metadata": { - "editable": true - }, - "source": [ - "\n", - "" - ] - }, - { - "cell_type": "markdown", - "id": "8d5fc499", - "metadata": { - "editable": true - }, - "source": [ - "# Exercises week 41\n", - "**October 9-13, 2023**\n", - "\n", - "Date: **Deadline is Sunday October 15 at midnight**" - ] - }, - { - "cell_type": "markdown", - "id": "d3ef3596", - "metadata": { - "editable": true - }, - "source": [ - "# Overarching aims of the exercises this week\n", - "\n", - "The aim of the exercises this week is to get started with implementing\n", - "gradient methods of relevance for project 2. This exercise will also\n", - "be continued next week with the addition of automatic differentation.\n", - "Everything you develop here will be used in project 2. \n", - "\n", - "In order to get started, we will now replace in our standard ordinary\n", - "least squares (OLS) and Ridge regression codes (from project 1) the\n", - "matrix inversion algorithm with our own gradient descent (GD) and SGD\n", - "codes. You can use the Franke function or the terrain data from\n", - "project 1. **However, we recommend using a simpler function like**\n", - "$f(x)=a_0+a_1x+a_2x^2$ or higher-order one-dimensional polynomials.\n", - "You can obviously test your final codes against for example the Franke\n", - "function. Automatic differentiation will be discussed next week.\n", - "\n", - "You should include in your analysis of the GD and SGD codes the following elements\n", - "1. A plain gradient descent with a fixed learning rate (you will need to tune it) using the analytical expression of the gradients\n", - "\n", - "2. Add momentum to the plain GD code and compare convergence with a fixed learning rate (you may need to tune the learning rate), again using the analytical expression of the gradients.\n", - "\n", - "3. Repeat these steps for stochastic gradient descent with mini batches and a given number of epochs. Use a tunable learning rate as discussed in the lectures from week 39. Discuss the results as functions of the various parameters (size of batches, number of epochs etc)\n", - "\n", - "4. Implement the Adagrad method in order to tune the learning rate. Do this with and without momentum for plain gradient descent and SGD.\n", - "\n", - "5. Add RMSprop and Adam to your library of methods for tuning the learning rate.\n", - "\n", - "The lecture notes from weeks 39 and 40 contain more information and code examples. Feel free to use these examples.\n", - "\n", - "In summary, you should \n", - "perform an analysis of the results for OLS and Ridge regression as\n", - "function of the chosen learning rates, the number of mini-batches and\n", - "epochs as well as algorithm for scaling the learning rate. You can\n", - "also compare your own results with those that can be obtained using\n", - "for example **Scikit-Learn**'s various SGD options. Discuss your\n", - "results. For Ridge regression you need now to study the results as functions of the hyper-parameter $\\lambda$ and \n", - "the learning rate $\\eta$. Discuss your results.\n", - "\n", - "You will need your SGD code for the setup of the Neural Network and\n", - "Logistic Regression codes. You will find the Python [Seaborn\n", - "package](https://seaborn.pydata.org/generated/seaborn.heatmap.html)\n", - "useful when plotting the results as function of the learning rate\n", - "$\\eta$ and the hyper-parameter $\\lambda$ when you use Ridge\n", - "regression.\n", - "\n", - "We recommend reading chapter 8 on optimization from the textbook of [Goodfellow, Bengio and Courville](https://www.deeplearningbook.org/). This chapter contains many useful insights and discussions on the optimization part of machine learning." - ] - }, - { - "cell_type": "markdown", - "id": "9940e21b", - "metadata": { - "editable": true - }, - "source": [ - "# Code examples from week 39 and 40" - ] - }, - { - "cell_type": "markdown", - "id": "6559d6d2", - "metadata": { - "editable": true - }, - "source": [ - "## Code with a Number of Minibatches which varies, analytical gradient\n", - "\n", - "In the code here we vary the number of mini-batches." - ] - }, - { - "cell_type": "code", - "execution_count": 1, - "id": "021b66d2", - "metadata": { - "collapsed": false, - "editable": true - }, - "outputs": [], - "source": [ - "%matplotlib inline\n", - "\n", - "# Importing various packages\n", - "from math import exp, sqrt\n", - "from random import random, seed\n", - "import numpy as np\n", - "import matplotlib.pyplot as plt\n", - "\n", - "n = 100\n", - "x = 2*np.random.rand(n,1)\n", - "y = 4+3*x+np.random.randn(n,1)\n", - "\n", - "X = np.c_[np.ones((n,1)), x]\n", - "XT_X = X.T @ X\n", - "theta_linreg = np.linalg.inv(X.T @ X) @ (X.T @ y)\n", - "print(\"Own inversion\")\n", - "print(theta_linreg)\n", - "# Hessian matrix\n", - "H = (2.0/n)* XT_X\n", - "EigValues, EigVectors = np.linalg.eig(H)\n", - "print(f\"Eigenvalues of Hessian Matrix:{EigValues}\")\n", - "\n", - "theta = np.random.randn(2,1)\n", - "eta = 1.0/np.max(EigValues)\n", - "Niterations = 1000\n", - "\n", - "\n", - "for iter in range(Niterations):\n", - " gradients = 2.0/n*X.T @ ((X @ theta)-y)\n", - " theta -= eta*gradients\n", - "print(\"theta from own gd\")\n", - "print(theta)\n", - "\n", - "xnew = np.array([[0],[2]])\n", - "Xnew = np.c_[np.ones((2,1)), xnew]\n", - "ypredict = Xnew.dot(theta)\n", - "ypredict2 = Xnew.dot(theta_linreg)\n", - "\n", - "n_epochs = 50\n", - "M = 5 #size of each minibatch\n", - "m = int(n/M) #number of minibatches\n", - "t0, t1 = 5, 50\n", - "\n", - "def learning_schedule(t):\n", - " return t0/(t+t1)\n", - "\n", - "theta = np.random.randn(2,1)\n", - "\n", - "for epoch in range(n_epochs):\n", - "# Can you figure out a better way of setting up the contributions to each batch?\n", - " for i in range(m):\n", - " random_index = M*np.random.randint(m)\n", - " xi = X[random_index:random_index+M]\n", - " yi = y[random_index:random_index+M]\n", - " gradients = (2.0/M)* xi.T @ ((xi @ theta)-yi)\n", - " eta = learning_schedule(epoch*m+i)\n", - " theta = theta - eta*gradients\n", - "print(\"theta from own sdg\")\n", - "print(theta)\n", - "\n", - "plt.plot(xnew, ypredict, \"r-\")\n", - "plt.plot(xnew, ypredict2, \"b-\")\n", - "plt.plot(x, y ,'ro')\n", - "plt.axis([0,2.0,0, 15.0])\n", - "plt.xlabel(r'$x$')\n", - "plt.ylabel(r'$y$')\n", - "plt.title(r'Random numbers ')\n", - "plt.show()" - ] - }, - { - "cell_type": "markdown", - "id": "d8e7110b", - "metadata": { - "editable": true - }, - "source": [ - "In the above code, we have use replacement in setting up the\n", - "mini-batches. The discussion\n", - "[here](https://sebastianraschka.com/faq/docs/sgd-methods.html) may be\n", - "useful." - ] - }, - { - "cell_type": "markdown", - "id": "74a7859a", - "metadata": { - "editable": true - }, - "source": [ - "## Momentum based GD\n", - "\n", - "The stochastic gradient descent (SGD) is almost always used with a\n", - "*momentum* or inertia term that serves as a memory of the direction we\n", - "are moving in parameter space. This is typically implemented as\n", - "follows" - ] - }, - { - "cell_type": "markdown", - "id": "619df8e8", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\mathbf{v}_{t}=\\gamma \\mathbf{v}_{t-1}+\\eta_{t}\\nabla_\\theta E(\\boldsymbol{\\theta}_t) \\nonumber\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "c759cfc4", - "metadata": { - "editable": true - }, - "source": [ - "\n", - "
\n", - "\n", - "$$\n", - "\\begin{equation} \n", - "\\boldsymbol{\\theta}_{t+1}= \\boldsymbol{\\theta}_t -\\mathbf{v}_{t},\n", - "\\label{_auto1} \\tag{1}\n", - "\\end{equation}\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "0a4571f9", - "metadata": { - "editable": true - }, - "source": [ - "where we have introduced a momentum parameter $\\gamma$, with\n", - "$0\\le\\gamma\\le 1$, and for brevity we dropped the explicit notation to\n", - "indicate the gradient is to be taken over a different mini-batch at\n", - "each step. We call this algorithm gradient descent with momentum\n", - "(GDM). From these equations, it is clear that $\\mathbf{v}_t$ is a\n", - "running average of recently encountered gradients and\n", - "$(1-\\gamma)^{-1}$ sets the characteristic time scale for the memory\n", - "used in the averaging procedure. Consistent with this, when\n", - "$\\gamma=0$, this just reduces down to ordinary SGD as discussed\n", - "earlier. An equivalent way of writing the updates is" - ] - }, - { - "cell_type": "markdown", - "id": "9bebfdd9", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\Delta \\boldsymbol{\\theta}_{t+1} = \\gamma \\Delta \\boldsymbol{\\theta}_t -\\ \\eta_{t}\\nabla_\\theta E(\\boldsymbol{\\theta}_t),\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "c9e635e8", - "metadata": { - "editable": true - }, - "source": [ - "where we have defined $\\Delta \\boldsymbol{\\theta}_{t}= \\boldsymbol{\\theta}_t-\\boldsymbol{\\theta}_{t-1}$." - ] - }, - { - "cell_type": "markdown", - "id": "eb544f8b", - "metadata": { - "editable": true - }, - "source": [ - "## Algorithms and codes for Adagrad, RMSprop and Adam\n", - "\n", - "The algorithms we have implemented are well described in the text by [Goodfellow, Bengio and Courville, chapter 8](https://www.deeplearningbook.org/contents/optimization.html).\n", - "\n", - "The codes which implement these algorithms are discussed after our presentation of automatic differentiation." - ] - }, - { - "cell_type": "markdown", - "id": "d088ad85", - "metadata": { - "editable": true - }, - "source": [ - "## Practical tips\n", - "\n", - "* **Randomize the data when making mini-batches**. It is always important to randomly shuffle the data when forming mini-batches. Otherwise, the gradient descent method can fit spurious correlations resulting from the order in which data is presented.\n", - "\n", - "* **Transform your inputs**. Learning becomes difficult when our landscape has a mixture of steep and flat directions. One simple trick for minimizing these situations is to standardize the data by subtracting the mean and normalizing the variance of input variables. Whenever possible, also decorrelate the inputs. To understand why this is helpful, consider the case of linear regression. It is easy to show that for the squared error cost function, the Hessian of the cost function is just the correlation matrix between the inputs. Thus, by standardizing the inputs, we are ensuring that the landscape looks homogeneous in all directions in parameter space. Since most deep networks can be viewed as linear transformations followed by a non-linearity at each layer, we expect this intuition to hold beyond the linear case.\n", - "\n", - "* **Monitor the out-of-sample performance.** Always monitor the performance of your model on a validation set (a small portion of the training data that is held out of the training process to serve as a proxy for the test set. If the validation error starts increasing, then the model is beginning to overfit. Terminate the learning process. This *early stopping* significantly improves performance in many settings.\n", - "\n", - "* **Adaptive optimization methods don't always have good generalization.** Recent studies have shown that adaptive methods such as ADAM, RMSPorp, and AdaGrad tend to have poor generalization compared to SGD or SGD with momentum, particularly in the high-dimensional limit (i.e. the number of parameters exceeds the number of data points). Although it is not clear at this stage why these methods perform so well in training deep neural networks, simpler procedures like properly-tuned SGD may work as well or better in these applications.\n", - "\n", - "Geron's text, see chapter 11, has several interesting discussions." - ] - }, - { - "cell_type": "markdown", - "id": "937063d3", - "metadata": { - "editable": true - }, - "source": [ - "## Using Automatic differentation with OLS\n", - "\n", - "We conclude the part on optmization by showing how we can make codes\n", - "for linear regression and logistic regression using **autograd**. The\n", - "first example shows results with ordinary leats squares." - ] - }, - { - "cell_type": "code", - "execution_count": 2, - "id": "e08215a6", - "metadata": { - "collapsed": false, - "editable": true - }, - "outputs": [], - "source": [ - "# Using Autograd to calculate gradients for OLS\n", - "from random import random, seed\n", - "import numpy as np\n", - "import autograd.numpy as np\n", - "import matplotlib.pyplot as plt\n", - "from autograd import grad\n", - "\n", - "def CostOLS(beta):\n", - " return (1.0/n)*np.sum((y-X @ beta)**2)\n", - "\n", - "n = 100\n", - "x = 2*np.random.rand(n,1)\n", - "y = 4+3*x+np.random.randn(n,1)\n", - "\n", - "X = np.c_[np.ones((n,1)), x]\n", - "XT_X = X.T @ X\n", - "theta_linreg = np.linalg.pinv(XT_X) @ (X.T @ y)\n", - "print(\"Own inversion\")\n", - "print(theta_linreg)\n", - "# Hessian matrix\n", - "H = (2.0/n)* XT_X\n", - "EigValues, EigVectors = np.linalg.eig(H)\n", - "print(f\"Eigenvalues of Hessian Matrix:{EigValues}\")\n", - "\n", - "theta = np.random.randn(2,1)\n", - "eta = 1.0/np.max(EigValues)\n", - "Niterations = 1000\n", - "# define the gradient\n", - "training_gradient = grad(CostOLS)\n", - "\n", - "for iter in range(Niterations):\n", - " gradients = training_gradient(theta)\n", - " theta -= eta*gradients\n", - "print(\"theta from own gd\")\n", - "print(theta)\n", - "\n", - "xnew = np.array([[0],[2]])\n", - "Xnew = np.c_[np.ones((2,1)), xnew]\n", - "ypredict = Xnew.dot(theta)\n", - "ypredict2 = Xnew.dot(theta_linreg)\n", - "\n", - "plt.plot(xnew, ypredict, \"r-\")\n", - "plt.plot(xnew, ypredict2, \"b-\")\n", - "plt.plot(x, y ,'ro')\n", - "plt.axis([0,2.0,0, 15.0])\n", - "plt.xlabel(r'$x$')\n", - "plt.ylabel(r'$y$')\n", - "plt.title(r'Random numbers ')\n", - "plt.show()" - ] - }, - { - "cell_type": "markdown", - "id": "623ad923", - "metadata": { - "editable": true - }, - "source": [ - "## Same code but now with momentum gradient descent" - ] - }, - { - "cell_type": "code", - "execution_count": 3, - "id": "b7fe53c1", - "metadata": { - "collapsed": false, - "editable": true - }, - "outputs": [], - "source": [ - "# Using Autograd to calculate gradients for OLS\n", - "from random import random, seed\n", - "import numpy as np\n", - "import autograd.numpy as np\n", - "import matplotlib.pyplot as plt\n", - "from autograd import grad\n", - "\n", - "def CostOLS(beta):\n", - " return (1.0/n)*np.sum((y-X @ beta)**2)\n", - "\n", - "n = 100\n", - "x = 2*np.random.rand(n,1)\n", - "y = 4+3*x#+np.random.randn(n,1)\n", - "\n", - "X = np.c_[np.ones((n,1)), x]\n", - "XT_X = X.T @ X\n", - "theta_linreg = np.linalg.pinv(XT_X) @ (X.T @ y)\n", - "print(\"Own inversion\")\n", - "print(theta_linreg)\n", - "# Hessian matrix\n", - "H = (2.0/n)* XT_X\n", - "EigValues, EigVectors = np.linalg.eig(H)\n", - "print(f\"Eigenvalues of Hessian Matrix:{EigValues}\")\n", - "\n", - "theta = np.random.randn(2,1)\n", - "eta = 1.0/np.max(EigValues)\n", - "Niterations = 30\n", - "\n", - "# define the gradient\n", - "training_gradient = grad(CostOLS)\n", - "\n", - "for iter in range(Niterations):\n", - " gradients = training_gradient(theta)\n", - " theta -= eta*gradients\n", - " print(iter,gradients[0],gradients[1])\n", - "print(\"theta from own gd\")\n", - "print(theta)\n", - "\n", - "# Now improve with momentum gradient descent\n", - "change = 0.0\n", - "delta_momentum = 0.3\n", - "for iter in range(Niterations):\n", - " # calculate gradient\n", - " gradients = training_gradient(theta)\n", - " # calculate update\n", - " new_change = eta*gradients+delta_momentum*change\n", - " # take a step\n", - " theta -= new_change\n", - " # save the change\n", - " change = new_change\n", - " print(iter,gradients[0],gradients[1])\n", - "print(\"theta from own gd wth momentum\")\n", - "print(theta)" - ] - }, - { - "cell_type": "markdown", - "id": "749000b3", - "metadata": { - "editable": true - }, - "source": [ - "## But noen of these can compete with Newton's method" - ] - }, - { - "cell_type": "code", - "execution_count": 4, - "id": "e7b4abe1", - "metadata": { - "collapsed": false, - "editable": true - }, - "outputs": [], - "source": [ - "# Using Newton's method\n", - "from random import random, seed\n", - "import numpy as np\n", - "import autograd.numpy as np\n", - "import matplotlib.pyplot as plt\n", - "from autograd import grad\n", - "\n", - "def CostOLS(beta):\n", - " return (1.0/n)*np.sum((y-X @ beta)**2)\n", - "\n", - "n = 100\n", - "x = 2*np.random.rand(n,1)\n", - "y = 4+3*x+np.random.randn(n,1)\n", - "\n", - "X = np.c_[np.ones((n,1)), x]\n", - "XT_X = X.T @ X\n", - "beta_linreg = np.linalg.pinv(XT_X) @ (X.T @ y)\n", - "print(\"Own inversion\")\n", - "print(beta_linreg)\n", - "# Hessian matrix\n", - "H = (2.0/n)* XT_X\n", - "# Note that here the Hessian does not depend on the parameters beta\n", - "invH = np.linalg.pinv(H)\n", - "EigValues, EigVectors = np.linalg.eig(H)\n", - "print(f\"Eigenvalues of Hessian Matrix:{EigValues}\")\n", - "\n", - "beta = np.random.randn(2,1)\n", - "Niterations = 5\n", - "\n", - "# define the gradient\n", - "training_gradient = grad(CostOLS)\n", - "\n", - "for iter in range(Niterations):\n", - " gradients = training_gradient(beta)\n", - " beta -= invH @ gradients\n", - " print(iter,gradients[0],gradients[1])\n", - "print(\"beta from own Newton code\")\n", - "print(beta)" - ] - }, - { - "cell_type": "markdown", - "id": "d47c2b1c", - "metadata": { - "editable": true - }, - "source": [ - "## Including Stochastic Gradient Descent with Autograd\n", - "In this code we include the stochastic gradient descent approach discussed above. Note here that we specify which argument we are taking the derivative with respect to when using **autograd**." - ] - }, - { - "cell_type": "code", - "execution_count": 5, - "id": "e2b04ba9", - "metadata": { - "collapsed": false, - "editable": true - }, - "outputs": [], - "source": [ - "# Using Autograd to calculate gradients using SGD\n", - "# OLS example\n", - "from random import random, seed\n", - "import numpy as np\n", - "import autograd.numpy as np\n", - "import matplotlib.pyplot as plt\n", - "from autograd import grad\n", - "\n", - "# Note change from previous example\n", - "def CostOLS(y,X,theta):\n", - " return np.sum((y-X @ theta)**2)\n", - "\n", - "n = 100\n", - "x = 2*np.random.rand(n,1)\n", - "y = 4+3*x+np.random.randn(n,1)\n", - "\n", - "X = np.c_[np.ones((n,1)), x]\n", - "XT_X = X.T @ X\n", - "theta_linreg = np.linalg.pinv(XT_X) @ (X.T @ y)\n", - "print(\"Own inversion\")\n", - "print(theta_linreg)\n", - "# Hessian matrix\n", - "H = (2.0/n)* XT_X\n", - "EigValues, EigVectors = np.linalg.eig(H)\n", - "print(f\"Eigenvalues of Hessian Matrix:{EigValues}\")\n", - "\n", - "theta = np.random.randn(2,1)\n", - "eta = 1.0/np.max(EigValues)\n", - "Niterations = 1000\n", - "\n", - "# Note that we request the derivative wrt third argument (theta, 2 here)\n", - "training_gradient = grad(CostOLS,2)\n", - "\n", - "for iter in range(Niterations):\n", - " gradients = (1.0/n)*training_gradient(y, X, theta)\n", - " theta -= eta*gradients\n", - "print(\"theta from own gd\")\n", - "print(theta)\n", - "\n", - "xnew = np.array([[0],[2]])\n", - "Xnew = np.c_[np.ones((2,1)), xnew]\n", - "ypredict = Xnew.dot(theta)\n", - "ypredict2 = Xnew.dot(theta_linreg)\n", - "\n", - "plt.plot(xnew, ypredict, \"r-\")\n", - "plt.plot(xnew, ypredict2, \"b-\")\n", - "plt.plot(x, y ,'ro')\n", - "plt.axis([0,2.0,0, 15.0])\n", - "plt.xlabel(r'$x$')\n", - "plt.ylabel(r'$y$')\n", - "plt.title(r'Random numbers ')\n", - "plt.show()\n", - "\n", - "n_epochs = 50\n", - "M = 5 #size of each minibatch\n", - "m = int(n/M) #number of minibatches\n", - "t0, t1 = 5, 50\n", - "def learning_schedule(t):\n", - " return t0/(t+t1)\n", - "\n", - "theta = np.random.randn(2,1)\n", - "\n", - "for epoch in range(n_epochs):\n", - "# Can you figure out a better way of setting up the contributions to each batch?\n", - " for i in range(m):\n", - " random_index = M*np.random.randint(m)\n", - " xi = X[random_index:random_index+M]\n", - " yi = y[random_index:random_index+M]\n", - " gradients = (1.0/M)*training_gradient(yi, xi, theta)\n", - " eta = learning_schedule(epoch*m+i)\n", - " theta = theta - eta*gradients\n", - "print(\"theta from own sdg\")\n", - "print(theta)" - ] - }, - { - "cell_type": "markdown", - "id": "f6d7455a", - "metadata": { - "editable": true - }, - "source": [ - "## Same code but now with momentum gradient descent" - ] - }, - { - "cell_type": "code", - "execution_count": 6, - "id": "40a68e4f", - "metadata": { - "collapsed": false, - "editable": true - }, - "outputs": [], - "source": [ - "# Using Autograd to calculate gradients using SGD\n", - "# OLS example\n", - "from random import random, seed\n", - "import numpy as np\n", - "import autograd.numpy as np\n", - "import matplotlib.pyplot as plt\n", - "from autograd import grad\n", - "\n", - "# Note change from previous example\n", - "def CostOLS(y,X,theta):\n", - " return np.sum((y-X @ theta)**2)\n", - "\n", - "n = 100\n", - "x = 2*np.random.rand(n,1)\n", - "y = 4+3*x+np.random.randn(n,1)\n", - "\n", - "X = np.c_[np.ones((n,1)), x]\n", - "XT_X = X.T @ X\n", - "theta_linreg = np.linalg.pinv(XT_X) @ (X.T @ y)\n", - "print(\"Own inversion\")\n", - "print(theta_linreg)\n", - "# Hessian matrix\n", - "H = (2.0/n)* XT_X\n", - "EigValues, EigVectors = np.linalg.eig(H)\n", - "print(f\"Eigenvalues of Hessian Matrix:{EigValues}\")\n", - "\n", - "theta = np.random.randn(2,1)\n", - "eta = 1.0/np.max(EigValues)\n", - "Niterations = 100\n", - "\n", - "# Note that we request the derivative wrt third argument (theta, 2 here)\n", - "training_gradient = grad(CostOLS,2)\n", - "\n", - "for iter in range(Niterations):\n", - " gradients = (1.0/n)*training_gradient(y, X, theta)\n", - " theta -= eta*gradients\n", - "print(\"theta from own gd\")\n", - "print(theta)\n", - "\n", - "\n", - "n_epochs = 50\n", - "M = 5 #size of each minibatch\n", - "m = int(n/M) #number of minibatches\n", - "t0, t1 = 5, 50\n", - "def learning_schedule(t):\n", - " return t0/(t+t1)\n", - "\n", - "theta = np.random.randn(2,1)\n", - "\n", - "change = 0.0\n", - "delta_momentum = 0.3\n", - "\n", - "for epoch in range(n_epochs):\n", - " for i in range(m):\n", - " random_index = M*np.random.randint(m)\n", - " xi = X[random_index:random_index+M]\n", - " yi = y[random_index:random_index+M]\n", - " gradients = (1.0/M)*training_gradient(yi, xi, theta)\n", - " eta = learning_schedule(epoch*m+i)\n", - " # calculate update\n", - " new_change = eta*gradients+delta_momentum*change\n", - " # take a step\n", - " theta -= new_change\n", - " # save the change\n", - " change = new_change\n", - "print(\"theta from own sdg with momentum\")\n", - "print(theta)" - ] - }, - { - "cell_type": "markdown", - "id": "d1f7f38d", - "metadata": { - "editable": true - }, - "source": [ - "## AdaGrad algorithm, taken from [Goodfellow et al](https://www.deeplearningbook.org/contents/optimization.html)\n", - "\n", - "\n", - "\n", - "\n", - "

Figure 1:

\n", - "" - ] - }, - { - "cell_type": "markdown", - "id": "b85cc96c", - "metadata": { - "editable": true - }, - "source": [ - "## Similar (second order function now) problem but now with AdaGrad" - ] - }, - { - "cell_type": "code", - "execution_count": 7, - "id": "3ced9e13", - "metadata": { - "collapsed": false, - "editable": true - }, - "outputs": [], - "source": [ - "# Using Autograd to calculate gradients using AdaGrad and Stochastic Gradient descent\n", - "# OLS example\n", - "from random import random, seed\n", - "import numpy as np\n", - "import autograd.numpy as np\n", - "import matplotlib.pyplot as plt\n", - "from autograd import grad\n", - "\n", - "# Note change from previous example\n", - "def CostOLS(y,X,theta):\n", - " return np.sum((y-X @ theta)**2)\n", - "\n", - "n = 1000\n", - "x = np.random.rand(n,1)\n", - "y = 2.0+3*x +4*x*x\n", - "\n", - "X = np.c_[np.ones((n,1)), x, x*x]\n", - "XT_X = X.T @ X\n", - "theta_linreg = np.linalg.pinv(XT_X) @ (X.T @ y)\n", - "print(\"Own inversion\")\n", - "print(theta_linreg)\n", - "\n", - "\n", - "# Note that we request the derivative wrt third argument (theta, 2 here)\n", - "training_gradient = grad(CostOLS,2)\n", - "# Define parameters for Stochastic Gradient Descent\n", - "n_epochs = 50\n", - "M = 5 #size of each minibatch\n", - "m = int(n/M) #number of minibatches\n", - "# Guess for unknown parameters theta\n", - "theta = np.random.randn(3,1)\n", - "\n", - "# Value for learning rate\n", - "eta = 0.01\n", - "# Including AdaGrad parameter to avoid possible division by zero\n", - "delta = 1e-8\n", - "for epoch in range(n_epochs):\n", - " Giter = 0.0\n", - " for i in range(m):\n", - " random_index = M*np.random.randint(m)\n", - " xi = X[random_index:random_index+M]\n", - " yi = y[random_index:random_index+M]\n", - " gradients = (1.0/M)*training_gradient(yi, xi, theta)\n", - " Giter += gradients*gradients\n", - " update = gradients*eta/(delta+np.sqrt(Giter))\n", - " theta -= update\n", - "print(\"theta from own AdaGrad\")\n", - "print(theta)" - ] - }, - { - "cell_type": "markdown", - "id": "ed1fa9e4", - "metadata": { - "editable": true - }, - "source": [ - "Running this code we note an almost perfect agreement with the results from matrix inversion." - ] - }, - { - "cell_type": "markdown", - "id": "787b2b5e", - "metadata": { - "editable": true - }, - "source": [ - "## RMSProp algorithm, taken from [Goodfellow et al](https://www.deeplearningbook.org/contents/optimization.html)\n", - "\n", - "\n", - "\n", - "\n", - "

Figure 1:

\n", - "" - ] - }, - { - "cell_type": "markdown", - "id": "ac61b6e0", - "metadata": { - "editable": true - }, - "source": [ - "## RMSprop for adaptive learning rate with Stochastic Gradient Descent" - ] - }, - { - "cell_type": "code", - "execution_count": 8, - "id": "5febac4f", - "metadata": { - "collapsed": false, - "editable": true - }, - "outputs": [], - "source": [ - "# Using Autograd to calculate gradients using RMSprop and Stochastic Gradient descent\n", - "# OLS example\n", - "from random import random, seed\n", - "import numpy as np\n", - "import autograd.numpy as np\n", - "import matplotlib.pyplot as plt\n", - "from autograd import grad\n", - "\n", - "# Note change from previous example\n", - "def CostOLS(y,X,theta):\n", - " return np.sum((y-X @ theta)**2)\n", - "\n", - "n = 1000\n", - "x = np.random.rand(n,1)\n", - "y = 2.0+3*x +4*x*x# +np.random.randn(n,1)\n", - "\n", - "X = np.c_[np.ones((n,1)), x, x*x]\n", - "XT_X = X.T @ X\n", - "theta_linreg = np.linalg.pinv(XT_X) @ (X.T @ y)\n", - "print(\"Own inversion\")\n", - "print(theta_linreg)\n", - "\n", - "\n", - "# Note that we request the derivative wrt third argument (theta, 2 here)\n", - "training_gradient = grad(CostOLS,2)\n", - "# Define parameters for Stochastic Gradient Descent\n", - "n_epochs = 50\n", - "M = 5 #size of each minibatch\n", - "m = int(n/M) #number of minibatches\n", - "# Guess for unknown parameters theta\n", - "theta = np.random.randn(3,1)\n", - "\n", - "# Value for learning rate\n", - "eta = 0.01\n", - "# Value for parameter rho\n", - "rho = 0.99\n", - "# Including AdaGrad parameter to avoid possible division by zero\n", - "delta = 1e-8\n", - "for epoch in range(n_epochs):\n", - " Giter = 0.0\n", - " for i in range(m):\n", - " random_index = M*np.random.randint(m)\n", - " xi = X[random_index:random_index+M]\n", - " yi = y[random_index:random_index+M]\n", - " gradients = (1.0/M)*training_gradient(yi, xi, theta)\n", - "\t# Accumulated gradient\n", - "\t# Scaling with rho the new and the previous results\n", - " Giter = (rho*Giter+(1-rho)*gradients*gradients)\n", - "\t# Taking the diagonal only and inverting\n", - " update = gradients*eta/(delta+np.sqrt(Giter))\n", - "\t# Hadamard product\n", - " theta -= update\n", - "print(\"theta from own RMSprop\")\n", - "print(theta)" - ] - }, - { - "cell_type": "markdown", - "id": "ee8a6301", - "metadata": { - "editable": true - }, - "source": [ - "## ADAM algorithm, taken from [Goodfellow et al](https://www.deeplearningbook.org/contents/optimization.html)\n", - "\n", - "\n", - "\n", - "\n", - "

Figure 1:

\n", - "" - ] - }, - { - "cell_type": "markdown", - "id": "b2d0f16b", - "metadata": { - "editable": true - }, - "source": [ - "## And finally [ADAM](https://arxiv.org/pdf/1412.6980.pdf)" - ] - }, - { - "cell_type": "code", - "execution_count": 9, - "id": "59349e6f", - "metadata": { - "collapsed": false, - "editable": true - }, - "outputs": [], - "source": [ - "# Using Autograd to calculate gradients using RMSprop and Stochastic Gradient descent\n", - "# OLS example\n", - "from random import random, seed\n", - "import numpy as np\n", - "import autograd.numpy as np\n", - "import matplotlib.pyplot as plt\n", - "from autograd import grad\n", - "\n", - "# Note change from previous example\n", - "def CostOLS(y,X,theta):\n", - " return np.sum((y-X @ theta)**2)\n", - "\n", - "n = 1000\n", - "x = np.random.rand(n,1)\n", - "y = 2.0+3*x +4*x*x# +np.random.randn(n,1)\n", - "\n", - "X = np.c_[np.ones((n,1)), x, x*x]\n", - "XT_X = X.T @ X\n", - "theta_linreg = np.linalg.pinv(XT_X) @ (X.T @ y)\n", - "print(\"Own inversion\")\n", - "print(theta_linreg)\n", - "\n", - "\n", - "# Note that we request the derivative wrt third argument (theta, 2 here)\n", - "training_gradient = grad(CostOLS,2)\n", - "# Define parameters for Stochastic Gradient Descent\n", - "n_epochs = 50\n", - "M = 5 #size of each minibatch\n", - "m = int(n/M) #number of minibatches\n", - "# Guess for unknown parameters theta\n", - "theta = np.random.randn(3,1)\n", - "\n", - "# Value for learning rate\n", - "eta = 0.01\n", - "# Value for parameters beta1 and beta2, see https://arxiv.org/abs/1412.6980\n", - "beta1 = 0.9\n", - "beta2 = 0.999\n", - "# Including AdaGrad parameter to avoid possible division by zero\n", - "delta = 1e-7\n", - "iter = 0\n", - "for epoch in range(n_epochs):\n", - " first_moment = 0.0\n", - " second_moment = 0.0\n", - " iter += 1\n", - " for i in range(m):\n", - " random_index = M*np.random.randint(m)\n", - " xi = X[random_index:random_index+M]\n", - " yi = y[random_index:random_index+M]\n", - " gradients = (1.0/M)*training_gradient(yi, xi, theta)\n", - " # Computing moments first\n", - " first_moment = beta1*first_moment + (1-beta1)*gradients\n", - " second_moment = beta2*second_moment+(1-beta2)*gradients*gradients\n", - " first_term = first_moment/(1.0-beta1**iter)\n", - " second_term = second_moment/(1.0-beta2**iter)\n", - "\t# Scaling with rho the new and the previous results\n", - " update = eta*first_term/(np.sqrt(second_term)+delta)\n", - " theta -= update\n", - "print(\"theta from own ADAM\")\n", - "print(theta)" - ] - }, - { - "cell_type": "markdown", - "id": "1d490115", - "metadata": { - "editable": true - }, - "source": [ - "## Introducing [JAX](https://jax.readthedocs.io/en/latest/)\n", - "\n", - "Presently, instead of using **autograd**, we recommend using [JAX](https://jax.readthedocs.io/en/latest/)\n", - "\n", - "**JAX** is Autograd and [XLA (Accelerated Linear Algebra))](https://www.tensorflow.org/xla),\n", - "brought together for high-performance numerical computing and machine learning research.\n", - "It provides composable transformations of Python+NumPy programs: differentiate, vectorize, parallelize, Just-In-Time compile to GPU/TPU, and more." - ] - }, - { - "cell_type": "markdown", - "id": "3bc7785a", - "metadata": { - "editable": true - }, - "source": [ - "### Getting started with Jax, note the way we import numpy" - ] - }, - { - "cell_type": "code", - "execution_count": 10, - "id": "f1090d5e", - "metadata": { - "collapsed": false, - "editable": true - }, - "outputs": [], - "source": [ - "import jax\n", - "import jax.numpy as jnp\n", - "import numpy as np\n", - "import matplotlib.pyplot as plt\n", - "\n", - "from jax import grad as jax_grad" - ] - }, - { - "cell_type": "markdown", - "id": "ac6bf976", - "metadata": { - "editable": true - }, - "source": [ - "### A warm-up example" - ] - }, - { - "cell_type": "code", - "execution_count": 11, - "id": "ed55121d", - "metadata": { - "collapsed": false, - "editable": true - }, - "outputs": [], - "source": [ - "def function(x):\n", - " return x**2\n", - "\n", - "def analytical_gradient(x):\n", - " return 2*x\n", - "\n", - "def gradient_descent(starting_point, learning_rate, num_iterations, solver=\"analytical\"):\n", - " x = starting_point\n", - " trajectory_x = [x]\n", - " trajectory_y = [function(x)]\n", - "\n", - " if solver == \"analytical\":\n", - " grad = analytical_gradient \n", - " elif solver == \"jax\":\n", - " grad = jax_grad(function)\n", - " x = jnp.float64(x)\n", - " learning_rate = jnp.float64(learning_rate)\n", - "\n", - " for _ in range(num_iterations):\n", - " \n", - " x = x - learning_rate * grad(x)\n", - " trajectory_x.append(x)\n", - " trajectory_y.append(function(x))\n", - "\n", - " return trajectory_x, trajectory_y\n", - "\n", - "x = np.linspace(-5, 5, 100)\n", - "plt.plot(x, function(x), label=\"f(x)\")\n", - "\n", - "descent_x, descent_y = gradient_descent(5, 0.1, 10, solver=\"analytical\")\n", - "jax_descend_x, jax_descend_y = gradient_descent(5, 0.1, 10, solver=\"jax\")\n", - "\n", - "plt.plot(descent_x, descent_y, label=\"Gradient descent\", marker=\"o\")\n", - "plt.plot(jax_descend_x, jax_descend_y, label=\"JAX\", marker=\"x\")" - ] - }, - { - "cell_type": "markdown", - "id": "4a994430", - "metadata": { - "editable": true - }, - "source": [ - "### A more advanced example" - ] - }, - { - "cell_type": "code", - "execution_count": 12, - "id": "863db98d", - "metadata": { - "collapsed": false, - "editable": true - }, - "outputs": [], - "source": [ - "backend = np\n", - "\n", - "def function(x):\n", - " return x*backend.sin(x**2 + 1)\n", - "\n", - "def analytical_gradient(x):\n", - " return backend.sin(x**2 + 1) + 2*x**2*backend.cos(x**2 + 1)\n", - "\n", - "\n", - "x = np.linspace(-5, 5, 100)\n", - "plt.plot(x, function(x), label=\"f(x)\")\n", - "\n", - "descent_x, descent_y = gradient_descent(1, 0.01, 300, solver=\"analytical\")\n", - "\n", - "# Change the backend to JAX\n", - "backend = jnp\n", - "jax_descend_x, jax_descend_y = gradient_descent(1, 0.01, 300, solver=\"jax\")\n", - "\n", - "plt.scatter(descent_x, descent_y, label=\"Gradient descent\", marker=\"v\", s=10, color=\"red\") \n", - "plt.scatter(jax_descend_x, jax_descend_y, label=\"JAX\", marker=\"x\", s=5, color=\"black\")" - ] - } - ], - "metadata": {}, - "nbformat": 4, - "nbformat_minor": 5 -} diff --git a/doc/LectureNotes/exercisesweek42.ipynb b/doc/LectureNotes/exercisesweek42.ipynb deleted file mode 100644 index f64e52145..000000000 --- a/doc/LectureNotes/exercisesweek42.ipynb +++ /dev/null @@ -1,73 +0,0 @@ -{ - "cells": [ - { - "cell_type": "markdown", - "id": "be117070", - "metadata": { - "editable": true - }, - "source": [ - "\n", - "" - ] - }, - { - "cell_type": "markdown", - "id": "6f7356c3", - "metadata": { - "editable": true - }, - "source": [ - "# Exercises week 42\n", - "**October 9-13, 2023**\n", - "\n", - "Date: **Deadline is Sunday October 22 at midnight**\n", - "\n", - "You can hand in the exercises from week 41 and week 42 as one exercise and get a total score of two additional points." - ] - }, - { - "cell_type": "markdown", - "id": "aa378ef2", - "metadata": { - "editable": true - }, - "source": [ - "# Overarching aims of the exercises this week\n", - "\n", - "The aim of the exercises this week is to get started with implementing\n", - "gradient methods of relevance for project 2. The exercise this week is a simple\n", - "continuation from the previous week with the addition of automatic differentation.\n", - "Everything you develop here will be used in project 2. \n", - "\n", - "In order to get started, we will now replace in our standard ordinary\n", - "least squares (OLS) and Ridge regression codes (from project 1) the\n", - "matrix inversion algorithm with our own gradient descent (GD) and SGD\n", - "codes. You can use the Franke function or the terrain data from\n", - "project 1. **However, we recommend using a simpler function like**\n", - "$f(x)=a_0+a_1x+a_2x^2$ or higher-order one-dimensional polynomials.\n", - "You can obviously test your final codes against for example the Franke\n", - "function. Automatic differentiation will be discussed next week.\n", - "\n", - "You should include in your analysis of the GD and SGD codes the following elements\n", - "1. A plain gradient descent with a fixed learning rate (you will need to tune it) using automatic differentiation. Compare this with the analytical expression of the gradients you obtained last week. Feel free to use **Autograd** as Python package or **JAX**. You can use the examples form last week.\n", - "\n", - "2. Add momentum to the plain GD code and compare convergence with a fixed learning rate (you may need to tune the learning rate). Compare this with the analytical expression of the gradients you obtained last week.\n", - "\n", - "3. Repeat these steps for stochastic gradient descent with mini batches and a given number of epochs. Use a tunable learning rate as discussed in the lectures from week 39. Discuss the results as functions of the various parameters (size of batches, number of epochs etc)\n", - "\n", - "4. Implement the Adagrad method in order to tune the learning rate. Do this with and without momentum for plain gradient descent and SGD using automatic differentiation..\n", - "\n", - "5. Add RMSprop and Adam to your library of methods for tuning the learning rate. Again using automatic differentiation.\n", - "\n", - "The lecture notes from weeks 39 and 40 contain more information and code examples. Feel free to use these examples.\n", - "\n", - "We recommend reading chapter 8 on optimization from the textbook of [Goodfellow, Bengio and Courville](https://www.deeplearningbook.org/). This chapter contains many useful insights and discussions on the optimization part of machine learning." - ] - } - ], - "metadata": {}, - "nbformat": 4, - "nbformat_minor": 5 -} diff --git a/doc/LectureNotes/exercisesweek43.ipynb b/doc/LectureNotes/exercisesweek43.ipynb deleted file mode 100644 index aea945187..000000000 --- a/doc/LectureNotes/exercisesweek43.ipynb +++ /dev/null @@ -1,1940 +0,0 @@ -{ - "cells": [ - { - "cell_type": "markdown", - "id": "d5ebb4c0", - "metadata": {}, - "source": [ - "\n", - "" - ] - }, - { - "cell_type": "markdown", - "id": "812b4e46", - "metadata": {}, - "source": [ - "# Exercises weeks 43 and 44 \n", - "**October 23-27, 2023**\n", - "\n", - "Date: **Deadline is Sunday November 5 at midnight**\n", - "\n", - "You can hand in the exercises from week 43 and week 44 as one exercise and get a total score of two additional points." - ] - }, - { - "cell_type": "markdown", - "id": "3230cd2f", - "metadata": {}, - "source": [ - "# Overarching aims of the exercises weeks 43 and 44\n", - "\n", - "The aim of the exercises this week and next week is to get started with writing a neural network code\n", - "of relevance for project 2. \n", - "\n", - "During week 41 we discussed three different types of gates, the\n", - "so-called XOR, the OR and the AND gates. In order to develop a code\n", - "for neural networks, it can be useful to set up a simpler system with\n", - "only two inputs and one output. This can make it easier to debug and\n", - "study the feed forward pass and the back propagation part. In the\n", - "exercise this and next week, we propose to study this system with just\n", - "one hidden layer and two hidden nodes. There is only one output node\n", - "and we can choose to use either a simple regression case (fitting a\n", - "line) or just a binary classification case with the cross-entropy as\n", - "cost function.\n", - "\n", - "Their inputs and outputs can be\n", - "summarized using the following tables, first for the OR gate with\n", - "inputs $x_1$ and $x_2$ and outputs $y$:\n", - "\n", - "\n", - "\n", - "\n", - "\n", - "\n", - "\n", - "\n", - "\n", - "\n", - "\n", - "
$x_1$ $x_2$ $y$
0 0 0
0 1 1
1 0 1
1 1 1
" - ] - }, - { - "cell_type": "markdown", - "id": "e3617d4e", - "metadata": {}, - "source": [ - "## The AND and XOR Gates\n", - "\n", - "The AND gate is defined as\n", - "\n", - "\n", - "\n", - "\n", - "\n", - "\n", - "\n", - "\n", - "\n", - "\n", - "\n", - "
$x_1$ $x_2$ $y$
0 0 0
0 1 0
1 0 0
1 1 1
\n", - "\n", - "And finally we have the XOR gate\n", - "\n", - "\n", - "\n", - "\n", - "\n", - "\n", - "\n", - "\n", - "\n", - "\n", - "\n", - "
$x_1$ $x_2$ $y$
0 0 0
0 1 1
1 0 1
1 1 0
" - ] - }, - { - "cell_type": "markdown", - "id": "54e1e7fc", - "metadata": {}, - "source": [ - "## Representing the Data Sets\n", - "\n", - "Our design matrix is defined by the input values $x_1$ and $x_2$. Since we have four possible outputs, our design matrix reads" - ] - }, - { - "cell_type": "markdown", - "id": "6b3c15cb", - "metadata": {}, - "source": [ - "$$\n", - "\\boldsymbol{X}=\\begin{bmatrix} 0 & 0 \\\\\n", - " 0 & 1 \\\\\n", - "\t\t 1 & 0 \\\\\n", - "\t\t 1 & 1 \\end{bmatrix},\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "acc25271", - "metadata": {}, - "source": [ - "while the vector of outputs is $\\boldsymbol{y}^T=[0,1,1,0]$ for the XOR gate, $\\boldsymbol{y}^T=[0,0,0,1]$ for the AND gate and $\\boldsymbol{y}^T=[0,1,1,1]$ for the OR gate.\n", - "\n", - "Your tasks here are\n", - "\n", - "1. Set up the design matrix with the inputs as discussed above and a vector containing the output, the so-called targets. Note that the design matrix is the same for all gates. You need just to define different outputs.\n", - "\n", - "2. Construct a neural network with only one hidden layer and two hidden nodes using the Sigmoid function as activation function.\n", - "\n", - "3. Set up the output layer with only one output node and use again the Sigmoid function as activation function for the output.\n", - "\n", - "4. Initialize the weights and biases and perform a feed forward pass and compare the outputs with the targets.\n", - "\n", - "5. Set up the cost function (cross entropy for classification of binary cases).\n", - "\n", - "6. Calculate the gradients needed for the back propagation part.\n", - "\n", - "7. Use the gradients to train the network in the back propagation part. Think of using automatic differentiation.\n", - "\n", - "8. Train the network and study your results and compare with results obtained either with **scikit-learn** or **TensorFlow**.\n", - "\n", - "Everything you develop here can be used directly into the code for the project." - ] - }, - { - "cell_type": "markdown", - "id": "ffe0a840", - "metadata": {}, - "source": [ - "## Setting up dimensionalities by hand\n", - "\n", - "It can be useful to test the dimensionalities for the network. Let us assume we have performed an optimization for XOR gate and found that the weights for the hidden layer are given by" - ] - }, - { - "cell_type": "markdown", - "id": "46abf545", - "metadata": {}, - "source": [ - "$$\n", - "\\boldsymbol{W_h}=\\begin{bmatrix} 1 & 1 \\\\\n", - " 1 & 1 \\end{bmatrix},\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "86e105cc", - "metadata": {}, - "source": [ - "Multiplying $\\boldsymbol{X}$ and $\\boldsymbol{W}$ gives" - ] - }, - { - "cell_type": "markdown", - "id": "5e1d21f1", - "metadata": {}, - "source": [ - "$$\n", - "\\boldsymbol{X}{W}_h=\\begin{bmatrix} 0 & 0 \\\\\n", - " 1 & 1 \\\\\n", - "\t\t 1 & 1 \\\\\n", - "\t\t 2 & 2 \\end{bmatrix},\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "692c6cbf", - "metadata": {}, - "source": [ - "Assume also that the bias vector for the hidden layer is" - ] - }, - { - "cell_type": "markdown", - "id": "5d81e641", - "metadata": {}, - "source": [ - "$$\n", - "\\boldsymbol{b}_h=\\begin{bmatrix} 0 \\\\\n", - " -1\\end{bmatrix},\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "a42bdee4", - "metadata": {}, - "source": [ - "Adding it gives us the input to the activation function of the hidden layer" - ] - }, - { - "cell_type": "markdown", - "id": "5116b854", - "metadata": {}, - "source": [ - "$$\n", - "\\boldsymbol{z}_h=\\boldsymbol{X}\\boldsymbol{W}_h+\\boldsymbol{b}_h=\\begin{bmatrix} 0 & -1 \\\\\n", - " 1 & 0 \\\\\n", - "\t\t 1 & 0 \\\\\n", - "\t\t 2 & 1 \\end{bmatrix},\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "8dd26d09", - "metadata": {}, - "source": [ - "Let us then assume that our activation function is the RELU function, which simply means that we take the max of $0$ and the elements of the input argument $\\boldsymbol{z}_h$, that is we have" - ] - }, - { - "cell_type": "markdown", - "id": "ebf97c03", - "metadata": {}, - "source": [ - "$$\n", - "\\boldsymbol{a}_h=\\mathrm{RELU}(\\boldsymbol{z}_h=\\boldsymbol{X}\\boldsymbol{W}_h+\\boldsymbol{b}_h)=\\begin{bmatrix} 0 & 0 \\\\\n", - " 1 & 0 \\\\\n", - "\t\t 1 & 0 \\\\\n", - "\t\t 2 & 1 \\end{bmatrix},\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "262a4a3a", - "metadata": {}, - "source": [ - "Assume also that the bias of the output layer is zero and that the weights of the output layer are" - ] - }, - { - "cell_type": "markdown", - "id": "f03ad8e7", - "metadata": {}, - "source": [ - "$$\n", - "\\boldsymbol{w}_o=\\begin{bmatrix} 1 \\\\\n", - " -2\\end{bmatrix},\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "36fe00c0", - "metadata": {}, - "source": [ - "and multiplying with $\\boldsymbol{a}_h$ gives the output" - ] - }, - { - "cell_type": "markdown", - "id": "80ab43ac", - "metadata": {}, - "source": [ - "$$\n", - "\\boldsymbol{a}_o=\\begin{bmatrix} 0 & 0 \\\\\n", - " 1 & 0 \\\\\n", - "\t\t 1 & 0 \\\\\n", - "\t\t 2 & 1 \\end{bmatrix}\\begin{bmatrix} 1 \\\\\n", - " -2\\end{bmatrix}=\\begin{bmatrix} 0 \\\\ 1 \\\\ 1 \\\\0\\end{bmatrix},\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "86bcfe49", - "metadata": {}, - "source": [ - "the wanted result. Pay attention to the dimensionalities as well." - ] - }, - { - "cell_type": "markdown", - "id": "f19a899e", - "metadata": {}, - "source": [ - "## Setting up the Neural Network\n", - "\n", - "We define first our design matrix and the various output vectors for the different gates." - ] - }, - { - "cell_type": "code", - "execution_count": 1, - "id": "901ddca7", - "metadata": {}, - "outputs": [], - "source": [ - "%matplotlib inline\n", - "\n", - "\"\"\"\n", - "Simple code that tests XOR, OR and AND gates with linear regression\n", - "\"\"\"\n", - "\n", - "# import necessary packages\n", - "import numpy as np\n", - "import matplotlib.pyplot as plt\n", - "from sklearn import datasets\n", - "\n", - "def sigmoid(x):\n", - " return 1/(1 + np.exp(-x))\n", - "\n", - "def feed_forward(X):\n", - " # weighted sum of inputs to the hidden layer\n", - " z_h = np.matmul(X, hidden_weights) + hidden_bias\n", - " # activation in the hidden layer\n", - " a_h = sigmoid(z_h)\n", - " \n", - " # weighted sum of inputs to the output layer\n", - " z_o = np.matmul(a_h, output_weights) + output_bias\n", - " # softmax output\n", - " # axis 0 holds each input and axis 1 the probabilities of each category\n", - " probabilities = sigmoid(z_o)\n", - " return probabilities\n", - "\n", - "\n", - "# ensure the same random numbers appear every time\n", - "np.random.seed(0)\n", - "\n", - "# Design matrix\n", - "X = np.array([ [0, 0], [0, 1], [1, 0],[1, 1]],dtype=np.float64)\n", - "\n", - "# The XOR gate\n", - "yXOR = np.array( [ 0, 1 ,1, 0])\n", - "# The OR gate\n", - "yOR = np.array( [ 0, 1 ,1, 1])\n", - "# The AND gate\n", - "yAND = np.array( [ 0, 0 ,0, 1])\n", - "\n", - "# Defining the neural network\n", - "n_inputs, n_features = X.shape\n", - "n_hidden_neurons = 2\n", - "n_categories = 1\n", - "n_features = 2\n", - "\n", - "# we make the weights normally distributed using numpy.random.randn\n", - "\n", - "# weights and bias in the hidden layer\n", - "hidden_weights = np.random.randn(n_features, n_hidden_neurons)\n", - "hidden_bias = np.zeros(n_hidden_neurons) + 0.01\n", - "\n", - "# weights and bias in the output layer\n", - "output_weights = np.random.randn(n_hidden_neurons, n_categories)\n", - "output_bias = np.zeros(n_categories) + 0.01\n", - "\n", - "probabilities = feed_forward(X)\n", - "print(probabilities)" - ] - }, - { - "cell_type": "markdown", - "id": "53f22266", - "metadata": {}, - "source": [ - "Not an impressive result, but this was our first forward pass with randomly assigned weights. Let us now add the full network with the back-propagation algorithm discussed above." - ] - }, - { - "cell_type": "markdown", - "id": "5f665ac6", - "metadata": {}, - "source": [ - "## The Code using Scikit-Learn" - ] - }, - { - "cell_type": "code", - "execution_count": 1, - "id": "cb396cda", - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "Learning rate = 1e-05\n", - "Lambda = 1e-05\n", - "Accuracy score on data set: 0.5\n", - "\n", - "Learning rate = 1e-05\n", - "Lambda = 0.0001\n", - "Accuracy score on data set: 0.5\n", - "\n", - "Learning rate = 1e-05\n", - "Lambda = 0.001\n", - "Accuracy score on data set: 0.5\n", - "\n", - "Learning rate = 1e-05\n", - "Lambda = 0.01\n", - "Accuracy score on data set: 0.5\n", - "\n", - "Learning rate = 1e-05\n", - "Lambda = 0.1\n", - "Accuracy score on data set: 0.5\n", - "\n", - "Learning rate = 1e-05\n", - "Lambda = 1.0\n", - "Accuracy score on data set: 0.5\n", - "\n", - "Learning rate = 1e-05\n", - "Lambda = 10.0\n", - "Accuracy score on data set: 0.5\n", - "\n", - "Learning rate = 0.0001\n", - "Lambda = 1e-05\n", - "Accuracy score on data set: 0.5\n", - "\n", - "Learning rate = 0.0001\n", - "Lambda = 0.0001\n", - "Accuracy score on data set: 0.5\n", - "\n", - "Learning rate = 0.0001\n", - "Lambda = 0.001\n", - "Accuracy score on data set: 0.5\n", - "\n", - "Learning rate = 0.0001\n", - "Lambda = 0.01\n", - "Accuracy score on data set: 0.5\n", - "\n", - "Learning rate = 0.0001\n", - "Lambda = 0.1\n", - "Accuracy score on data set: 0.5\n", - "\n", - "Learning rate = 0.0001\n", - "Lambda = 1.0\n", - "Accuracy score on data set: 0.5\n", - "\n", - "Learning rate = 0.0001\n", - "Lambda = 10.0\n", - "Accuracy score on data set: 0.5\n", - "\n", - "Learning rate = 0.001\n", - "Lambda = 1e-05\n", - "Accuracy score on data set: 0.5\n", - "\n", - "Learning rate = 0.001\n", - "Lambda = 0.0001\n", - "Accuracy score on data set: 0.5\n", - "\n", - "Learning rate = 0.001\n", - "Lambda = 0.001\n", - "Accuracy score on data set: 0.5\n", - "\n", - "Learning rate = 0.001\n", - "Lambda = 0.01\n", - "Accuracy score on data set: 0.5\n", - "\n", - "Learning rate = 0.001\n", - "Lambda = 0.1\n", - "Accuracy score on data set: 0.5\n", - "\n", - "Learning rate = 0.001\n", - "Lambda = 1.0\n", - "Accuracy score on data set: 0.5\n", - "\n", - "Learning rate = 0.001\n", - "Lambda = 10.0\n", - "Accuracy score on data set: 0.5\n", - "\n", - "Learning rate = 0.01\n", - "Lambda = 1e-05\n", - "Accuracy score on data set: 0.25\n", - "\n", - "Learning rate = 0.01\n", - "Lambda = 0.0001\n", - "Accuracy score on data set: 0.75\n", - "\n", - "Learning rate = 0.01\n", - "Lambda = 0.001\n", - "Accuracy score on data set: 0.5\n", - "\n", - "Learning rate = 0.01\n", - "Lambda = 0.01\n", - "Accuracy score on data set: 0.75\n", - "\n", - "Learning rate = 0.01\n", - "Lambda = 0.1\n", - "Accuracy score on data set: 0.5\n", - "\n", - "Learning rate = 0.01\n", - "Lambda = 1.0\n", - "Accuracy score on data set: 0.5\n", - "\n", - "Learning rate = 0.01\n", - "Lambda = 10.0\n", - "Accuracy score on data set: 0.5\n", - "\n", - "Learning rate = 0.1\n", - "Lambda = 1e-05\n", - "Accuracy score on data set: 0.5\n", - "\n", - "Learning rate = 0.1\n", - "Lambda = 0.0001\n", - "Accuracy score on data set: 0.5\n", - "\n", - "Learning rate = 0.1\n", - "Lambda = 0.001\n", - "Accuracy score on data set: 1.0\n", - "\n", - "Learning rate = 0.1\n", - "Lambda = 0.01\n", - "Accuracy score on data set: 1.0\n", - "\n", - "Learning rate = 0.1\n", - "Lambda = 0.1\n", - "Accuracy score on data set: 0.5\n", - "\n", - "Learning rate = 0.1\n", - "Lambda = 1.0\n", - "Accuracy score on data set: 0.5\n", - "\n", - "Learning rate = 0.1\n", - "Lambda = 10.0\n", - "Accuracy score on data set: 0.5\n", - "\n", - "Learning rate = 1.0\n", - "Lambda = 1e-05\n", - "Accuracy score on data set: 0.75\n", - "\n", - "Learning rate = 1.0\n", - "Lambda = 0.0001\n", - "Accuracy score on data set: 0.75\n", - "\n", - "Learning rate = 1.0\n", - "Lambda = 0.001\n", - "Accuracy score on data set: 0.75\n", - "\n", - "Learning rate = 1.0\n", - "Lambda = 0.01\n", - "Accuracy score on data set: 0.5\n", - "\n", - "Learning rate = 1.0\n", - "Lambda = 0.1\n", - "Accuracy score on data set: 0.5\n", - "\n", - "Learning rate = 1.0\n", - "Lambda = 1.0\n", - "Accuracy score on data set: 0.5\n", - "\n" - ] - }, - { - "name": "stderr", - "output_type": "stream", - "text": [ - "/Users/mhjensen/miniforge3/envs/myenv/lib/python3.9/site-packages/sklearn/neural_network/_multilayer_perceptron.py:692: ConvergenceWarning: Stochastic Optimizer: Maximum iterations (100) reached and the optimization hasn't converged yet.\n", - " warnings.warn(\n", - "/Users/mhjensen/miniforge3/envs/myenv/lib/python3.9/site-packages/sklearn/neural_network/_multilayer_perceptron.py:692: ConvergenceWarning: Stochastic Optimizer: Maximum iterations (100) reached and the optimization hasn't converged yet.\n", - " warnings.warn(\n", - "/Users/mhjensen/miniforge3/envs/myenv/lib/python3.9/site-packages/sklearn/neural_network/_multilayer_perceptron.py:692: ConvergenceWarning: Stochastic Optimizer: Maximum iterations (100) reached and the optimization hasn't converged yet.\n", - " warnings.warn(\n", - "/Users/mhjensen/miniforge3/envs/myenv/lib/python3.9/site-packages/sklearn/neural_network/_multilayer_perceptron.py:692: ConvergenceWarning: Stochastic Optimizer: Maximum iterations (100) reached and the optimization hasn't converged yet.\n", - " warnings.warn(\n", - "/Users/mhjensen/miniforge3/envs/myenv/lib/python3.9/site-packages/sklearn/neural_network/_multilayer_perceptron.py:692: ConvergenceWarning: Stochastic Optimizer: Maximum iterations (100) reached and the optimization hasn't converged yet.\n", - " warnings.warn(\n", - "/Users/mhjensen/miniforge3/envs/myenv/lib/python3.9/site-packages/sklearn/neural_network/_multilayer_perceptron.py:692: ConvergenceWarning: Stochastic Optimizer: Maximum iterations (100) reached and the optimization hasn't converged yet.\n", - " warnings.warn(\n", - "/Users/mhjensen/miniforge3/envs/myenv/lib/python3.9/site-packages/sklearn/neural_network/_multilayer_perceptron.py:692: ConvergenceWarning: Stochastic Optimizer: Maximum iterations (100) reached and the optimization hasn't converged yet.\n", - " warnings.warn(\n", - "/Users/mhjensen/miniforge3/envs/myenv/lib/python3.9/site-packages/sklearn/neural_network/_multilayer_perceptron.py:692: ConvergenceWarning: Stochastic Optimizer: Maximum iterations (100) reached and the optimization hasn't converged yet.\n", - " warnings.warn(\n", - "/Users/mhjensen/miniforge3/envs/myenv/lib/python3.9/site-packages/sklearn/neural_network/_multilayer_perceptron.py:692: ConvergenceWarning: Stochastic Optimizer: Maximum iterations (100) reached and the optimization hasn't converged yet.\n", - " warnings.warn(\n", - "/Users/mhjensen/miniforge3/envs/myenv/lib/python3.9/site-packages/sklearn/neural_network/_multilayer_perceptron.py:692: ConvergenceWarning: Stochastic Optimizer: Maximum iterations (100) reached and the optimization hasn't converged yet.\n", - " warnings.warn(\n" - ] - }, - { - "name": "stdout", - "output_type": "stream", - "text": [ - "Learning rate = 1.0\n", - "Lambda = 10.0\n", - "Accuracy score on data set: 0.5\n", - "\n", - "Learning rate = 10.0\n", - "Lambda = 1e-05\n", - "Accuracy score on data set: 0.5\n", - "\n", - "Learning rate = 10.0\n", - "Lambda = 0.0001\n", - "Accuracy score on data set: 0.5\n", - "\n", - "Learning rate = 10.0\n", - "Lambda = 0.001\n", - "Accuracy score on data set: 0.5\n", - "\n", - "Learning rate = 10.0\n", - "Lambda = 0.01\n", - "Accuracy score on data set: 0.5\n", - "\n", - "Learning rate = 10.0\n", - "Lambda = 0.1\n", - "Accuracy score on data set: 0.5\n", - "\n", - "Learning rate = 10.0\n", - "Lambda = 1.0\n", - "Accuracy score on data set: 0.5\n", - "\n", - "Learning rate = 10.0\n", - "Lambda = 10.0\n", - "Accuracy score on data set: 0.5\n", - "\n" - ] - }, - { - "data": { - "image/png": "iVBORw0KGgoAAAANSUhEUgAAAyAAAANbCAYAAAC6lftqAAAAOXRFWHRTb2Z0d2FyZQBNYXRwbG90bGliIHZlcnNpb24zLjUuMSwgaHR0cHM6Ly9tYXRwbG90bGliLm9yZy/YYfK9AAAACXBIWXMAAA9hAAAPYQGoP6dpAABrR0lEQVR4nO3dd3xUddbH8e9QJgMpQISQSOgEYpQSDEVpIqDriuIKPsqKC4tEmrCCCzYUUGwLigKCq1J0kQWlWigi7q4U6ShCCE1aME0gCSE9mecPJLvjBBhg7r2Z5PN+XvN6mN/cO/fk7BA5c8691+Z0Op0CAAAAABNUsDoAAAAAAOUHBQgAAAAA01CAAAAAADANBQgAAAAA01CAAAAAADANBQgAAAAA01CAAAAAADANBQgAAAAA01CAAICBuNcrAACuKlkdAACY6emnn9ayZcsuuU2dOnX0zTffXPOxPv30Ux0+fFhPP/30ZbddvHixnnvuOXXq1EkffPDBNR8bAIDSyubk6zkA5cjx48d1+vTp4uczZ85UXFycZsyYUbxmt9sVFRV1zce6/fbb1bZtW7322muX3bZv377KzMzUoUOH9NVXX6lu3brXfHwAAEojOiAAypV69eqpXr16xc+Dg4Nlt9vVqlUry2I6cuSIdu7cqffee09jxozRJ598oieffNKyeAAAMBLngABACQ4cOKDBgwerdevWat26tYYPH64TJ064bPOPf/xDv/vd79S8eXN16tRJEyZMUGZmpqTz3Y+TJ09q2bJlatasmRISEi56rCVLligwMFC33HKLfve732nJkiXKy8tz227Pnj0aNGiQbr75ZrVv316jRo1SYmJi8eunTp3Ss88+q1tvvVXR0dF6+OGHtWPHjuLXmzVrpunTp7u85/Tp09WsWbPi508//bT69++v8ePHKyYmRn/4wx9UUFCg06dPa+LEieratatuuukmtW3bVsOHD3f7ub788kvdf//9atmypW677TZNnjxZeXl5OnjwoJo1a6ZFixa5bJ+cnKwbbrjhsmNxAICygwIEAH7jyJEjeuihh3Tq1Cm99tprevnll3XixAn17dtXp06dknT+H9qvv/66Hn74Yc2ePVvDhw/XihUrNGnSJEnSjBkzVKtWLXXp0kWLFi1SSEhIiccqLCzUihUr9Pvf/152u13333+/Tp06pa+//tplu/j4ePXt21fZ2dl67bXX9OKLLyouLk4DBw5Ufn6+srKy9NBDD2nTpk168sknNWPGDPn7+2vQoEE6fPjwFf3827dv17FjxzR9+nQNHz5cFStW1ODBg7Vx40Y9+eSTmj17toYNG6ZNmzbphRdeKN5v4cKFGj16tG644QbNmDFDgwcP1oIFCzRhwgRFRESoZcuWWrFihcuxVqxYIYfDoTvvvPOKYgQA+C5GsADgN2bMmCGHw6F58+YpICBAknTLLbeoe/fu+uCDD/TUU09py5YtqlOnjh5++GFVqFBBbdu2VdWqVXXmzBlJUlRUlOx2u4KDgy853vXtt98qJSVFvXv3liS1atVKTZo00T//+U/9/ve/L95u5syZqlatmubMmSM/Pz9JUmhoqJ544gnt379fP/zwg06cOKHly5crMjJSkhQTE6P77rtP27ZtU+PGjT3++QsKCjRx4kTVr19f0vkuRZUqVfTUU08pJiZGktSuXTslJCRo4cKFkqSioiJNnz5dPXr00Msvv1z8Xrm5uVq2bJny8vLUu3dvvfDCCzpx4kTxOS7Lly/XXXfdpapVq3ocHwDAt9EBAYDf2Lx5s9q1ayeHw6GCggIVFBQoICBAMTEx2rRpkySpffv2Onr0qO6///7iE9nvuece9e/f/4qOtWTJEtWvX18NGzZURkaGMjIydNddd2nr1q0unYsdO3aoc+fOxcWHJLVo0ULffPONbrrpJm3fvl3h4eHFxYck+fn5adWqVXrooYeuKCaHw+Fynkzt2rX10UcfKSYmRj///LO+++47zZ8/Xzt37lR+fr6k812jX375Rd27d3d5rwEDBmjFihWy2+26++67VaVKleIuyO7du3X48GHdf//9VxQfAMC30QEBgN9IS0vTypUrtXLlSrfXgoODJUm///3vVVRUpAULFmjGjBl6++23VadOHT355JO6++67PTrO6dOn9e9//1v5+flq06aN2+uLFi3Ss88+WxzTddddd8mYL/X6lbjuuutks9lc1j777DO9+eabSkxMVPXq1RUZGSmHw+Fy/Av7XkxAQIB+97vf6bPPPtPjjz+uZcuWqX79+sVdFQBA+UABAgC/ERgYqFtvvVV//vOf3V6rVOm/vzZ79uypnj176uzZs9qwYYPef/99jRkzRjExMapdu/Zlj7NixQrl5+drxowZCgoKcnntnXfe0fLlyzV69Gg5HA4FBga6XD74gv/85z+KjIxUYGBgiSe679q1SwEBAYqIiJB0/pyT/5WVlXXZOLdv366nnnpK/fr106OPPqrQ0FBJ0t/+9rfik9wvxP/bGNPS0rR37161atVK/v7+6t27t5YtW6bdu3drzZo1euSRRy57fABA2cIIFgD8Rtu2bXXo0CHdcMMNat68uZo3b66bbrpJ8+bN09q1ayVJTzzxhB5//HFJ5wuWu+66S8OGDVNhYaFSUlIkSRUqXPpX7NKlS9WqVSv16NFD7dq1c3n07dtX6enpWrVqlaTz53OsX7/e5epY+/fv12OPPaYff/xRMTExOnHihPbv31/8el5enkaMGKFPPvlE0vkORFJSkksMO3fuvGw+du3apaKiIo0cObK4+CgsLCweRysqKlKjRo1Uo0YNrVu3zmXfzz//XLGxscrNzZUktWnTRg0aNNDkyZN15swZ3XfffZc9PgCgbKEAAYDfGDZsmI4fP67Bgwfr66+/1vr16zVixAh9+eWXxedYtG/fXmvXrtXrr7+u7777TmvWrNHbb7+tBg0aFG8TFBSkuLg4bd26VTk5OS7H2L17tw4cOHDRca1u3bqpWrVqxSd5Dxs2TGfOnFFsbKy++eYbrV69Wk888YRuvPFGde7cWffff7/q1q2roUOHasWKFVq/fr1GjhypnJyc4i7Dbbfdpi+//FILFizQd999p7Fjx+rYsWOXzUeLFi0kSS+++KI2b96sr776Sn/+858VHx8v6XwXpWLFihoxYoTWrFmjCRMmaOPGjfr444/11ltvqW/fvsWja5LUu3dvbd26VbfccovCwsKu5H8aAEAZQAECAL8RGRmpjz/+WDabTWPHjtXIkSOVmpqqd955R3fccYck6aGHHtK4ceP07bffasiQIXrhhRfUuHFjzZkzR5UrV5YkDRw4UL/88oseffRR7dmzx+UYS5YsUcWKFV2udPW/7Ha77rrrLn3//ffat2+foqKi9I9//ENFRUUaNWqUXnzxRbVq1Urvv/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X379sVrQUFBioqK0rZt20rcZ//+/WrSpMk1HZcCBAAAAPCAzVk6H1crKSlJkhQWFuayHhISosTERLftT58+rV9++UXbtm1Tz5491bFjRw0fPlxHjhy5ouNyDggAAADgw7p163bJ19etW1fienZ2tiS5nevh5+en9PR0t+0PHDggSapYsaJef/11ZWVlaebMmfrjH/+ozz//XDVr1vQoXgoQAAAAoBxyOBySzp8LcuHPkpSbm6sqVaq4bd++fXtt3bpV1apVK15755131LVrVy1dulSPPfaYR8elAAEAAAA8UUqvgnWxDsflXBi9SklJUb169YrXU1JSFBkZWeI+/1t8SFLVqlUVHh6u5ORkj4/LOSAAAABAORQZGamAgABt2bKleC0jI0NxcXGKiYlx237BggVq166dcnJyitcyMzN19OjRKzoxnQIEAAAAKIfsdrv69eunKVOmaN26dYqPj9eoUaMUGhqqHj16qLCwUKmpqcUFR9euXeV0OjV27FgdPHhQP/74o0aMGKHg4GD94Q9/8Pi4FCAAAACAJ5yl9HENRo4cqT59+mjcuHHq27evKlasqNmzZ8tutysxMVEdO3bUypUrJZ0f2frwww917tw59e3bVwMGDFBgYKA++ugjl3NILodzQAAAAIByqmLFihozZozGjBnj9lp4eLj279/vsnbDDTdo9uzZ13RMOiAAAAAATEMHBAAAAPDAtdz0D/9FBwQAAACAaShAAAAAAJiGESwAAADAE4xgeQUdEAAAAACmoQABAAAAYBpGsAAAAAAP2JzMYHkDHRAAAAAApqEAAQAAAGAaRrAAAAAATzCB5RV0QAAAAACYhgIEAAAAgGkYwQIAAAA8YGMEyyvogAAAAAAwDQUIAAAAANMwggUAAAB4ghEsr6ADAgAAAMA0FCAAAAAATMMIFgAAAOABroLlHXRAAAAAAJiGAgQAAACAaRjBAgAAADzBCJZX0AEBAAAAYBoKEAAAAACmYQQLAAAA8ABXwfIOOiAAAAAATEMBAgAAAMA0jGABAAAAnmAEyyvogAAAAAAwTbnqgFTqlWp1CMA1af99H6tDKNMKVtSyOgQAAMq8clWAAAAAAFeLq2B5ByNYAAAAAExDAQIAA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ADwGAUIAPiYjIwMPfvss+rWrZv69u2r06dPKzk52eqwAADwCAUIAPiYiRMnqqCgQJMmTVJUVJQkxrAAAL6DAgQAfMjq1av1xRdf6OWXX1ZwcHBxAcKJ6AAAX0EBAgA+IjU1VePHj9eDDz6orl27SpLq1q2roKAgzgMBAPgMChAA8BHPP/+8qlWrpqefftpl/YYbbmAECwDgMyhAAMAHfPrpp/r222/1t7/9TVWrVnV5LSoqSsePH1dmZqZF0QEA4Dmb0+l0Wh0EAAAAgPKBDggAAAAA01CAAAAAADANBQgAAAAA01CAAAAAADANBQgAAAAA01CAAAAAADANBQgAAAAA01CAAAAAADANBQgAAAAA01CAAAAAADANBQgAAAAA01CAAAAAADDN/wOpUE87FNLINAAAAABJRU5ErkJggg==\n", - "text/plain": [ - "
" - ] - }, - "metadata": {}, - "output_type": "display_data" - } - ], - "source": [ - "# import necessary packages\n", - "import numpy as np\n", - "import matplotlib.pyplot as plt\n", - "from sklearn.neural_network import MLPClassifier\n", - "from sklearn.metrics import accuracy_score\n", - "import seaborn as sns\n", - "\n", - "# ensure the same random numbers appear every time\n", - "np.random.seed(0)\n", - "\n", - "# Design matrix\n", - "X = np.array([ [0, 0], [0, 1], [1, 0],[1, 1]],dtype=np.float64)\n", - "\n", - "# The XOR gate\n", - "yXOR = np.array( [ 0, 1 ,1, 0])\n", - "# The OR gate\n", - "yOR = np.array( [ 0, 1 ,1, 1])\n", - "# The AND gate\n", - "yAND = np.array( [ 0, 0 ,0, 1])\n", - "\n", - "# Defining the neural network\n", - "n_hidden_neurons = 2\n", - "\n", - "eta_vals = np.logspace(-5, 1, 7)\n", - "lmbd_vals = np.logspace(-5, 1, 7)\n", - "# store models for later use\n", - "DNN_scikit = np.zeros((len(eta_vals), len(lmbd_vals)), dtype=object)\n", - "epochs = 100\n", - "\n", - "for i, eta in enumerate(eta_vals):\n", - " for j, lmbd in enumerate(lmbd_vals):\n", - " dnn = MLPClassifier(hidden_layer_sizes=(n_hidden_neurons), activation='logistic',\n", - " alpha=lmbd, learning_rate_init=eta, max_iter=epochs)\n", - " dnn.fit(X, yXOR)\n", - " DNN_scikit[i][j] = dnn\n", - " print(\"Learning rate = \", eta)\n", - " print(\"Lambda = \", lmbd)\n", - " print(\"Accuracy score on data set: \", dnn.score(X, yXOR))\n", - " print()\n", - "\n", - "sns.set()\n", - "test_accuracy = np.zeros((len(eta_vals), len(lmbd_vals)))\n", - "for i in range(len(eta_vals)):\n", - " for j in range(len(lmbd_vals)):\n", - " dnn = DNN_scikit[i][j]\n", - " test_pred = dnn.predict(X)\n", - " test_accuracy[i][j] = accuracy_score(yXOR, test_pred)\n", - "\n", - "fig, ax = plt.subplots(figsize = (10, 10))\n", - "sns.heatmap(test_accuracy, annot=True, ax=ax, cmap=\"viridis\")\n", - "ax.set_title(\"Test Accuracy\")\n", - "ax.set_ylabel(\"$\\eta$\")\n", - "ax.set_xlabel(\"$\\lambda$\")\n", - "plt.show()" - ] - }, - { - "cell_type": "markdown", - "id": "c5978471", - "metadata": {}, - "source": [ - "## Building a neural network code\n", - "\n", - "Here we present a flexible object oriented codebase\n", - "for a feed forward neural network, along with a demonstration of how\n", - "to use it. Before we get into the details of the neural network, we\n", - "will first present some implementations of various schedulers, cost\n", - "functions and activation functions that can be used together with the\n", - "neural network.\n", - "\n", - "The codes here were developed by Eric Reber and Gregor Kajda during spring 2023." - ] - }, - { - "cell_type": "markdown", - "id": "7b82dc46", - "metadata": {}, - "source": [ - "### Learning rate methods\n", - "\n", - "The code below shows object oriented implementations of the Constant,\n", - "Momentum, Adagrad, AdagradMomentum, RMS prop and Adam schedulers. All\n", - "of the classes belong to the shared abstract Scheduler class, and\n", - "share the update_change() and reset() methods allowing for any of the\n", - "schedulers to be seamlessly used during the training stage, as will\n", - "later be shown in the fit() method of the neural\n", - "network. Update_change() only has one parameter, the gradient\n", - "($δ^l_ja^{l−1}_k$), and returns the change which will be subtracted\n", - "from the weights. The reset() function takes no parameters, and resets\n", - "the desired variables. For Constant and Momentum, reset does nothing." - ] - }, - { - "cell_type": "code", - "execution_count": 3, - "id": "de4dedfb", - "metadata": {}, - "outputs": [], - "source": [ - "import autograd.numpy as np\n", - "\n", - "class Scheduler:\n", - " \"\"\"\n", - " Abstract class for Schedulers\n", - " \"\"\"\n", - "\n", - " def __init__(self, eta):\n", - " self.eta = eta\n", - "\n", - " # should be overwritten\n", - " def update_change(self, gradient):\n", - " raise NotImplementedError\n", - "\n", - " # overwritten if needed\n", - " def reset(self):\n", - " pass\n", - "\n", - "\n", - "class Constant(Scheduler):\n", - " def __init__(self, eta):\n", - " super().__init__(eta)\n", - "\n", - " def update_change(self, gradient):\n", - " return self.eta * gradient\n", - " \n", - " def reset(self):\n", - " pass\n", - "\n", - "\n", - "class Momentum(Scheduler):\n", - " def __init__(self, eta: float, momentum: float):\n", - " super().__init__(eta)\n", - " self.momentum = momentum\n", - " self.change = 0\n", - "\n", - " def update_change(self, gradient):\n", - " self.change = self.momentum * self.change + self.eta * gradient\n", - " return self.change\n", - "\n", - " def reset(self):\n", - " pass\n", - "\n", - "\n", - "class Adagrad(Scheduler):\n", - " def __init__(self, eta):\n", - " super().__init__(eta)\n", - " self.G_t = None\n", - "\n", - " def update_change(self, gradient):\n", - " delta = 1e-8 # avoid division ny zero\n", - "\n", - " if self.G_t is None:\n", - " self.G_t = np.zeros((gradient.shape[0], gradient.shape[0]))\n", - "\n", - " self.G_t += gradient @ gradient.T\n", - "\n", - " G_t_inverse = 1 / (\n", - " delta + np.sqrt(np.reshape(np.diagonal(self.G_t), (self.G_t.shape[0], 1)))\n", - " )\n", - " return self.eta * gradient * G_t_inverse\n", - "\n", - " def reset(self):\n", - " self.G_t = None\n", - "\n", - "\n", - "class AdagradMomentum(Scheduler):\n", - " def __init__(self, eta, momentum):\n", - " super().__init__(eta)\n", - " self.G_t = None\n", - " self.momentum = momentum\n", - " self.change = 0\n", - "\n", - " def update_change(self, gradient):\n", - " delta = 1e-8 # avoid division ny zero\n", - "\n", - " if self.G_t is None:\n", - " self.G_t = np.zeros((gradient.shape[0], gradient.shape[0]))\n", - "\n", - " self.G_t += gradient @ gradient.T\n", - "\n", - " G_t_inverse = 1 / (\n", - " delta + np.sqrt(np.reshape(np.diagonal(self.G_t), (self.G_t.shape[0], 1)))\n", - " )\n", - " self.change = self.change * self.momentum + self.eta * gradient * G_t_inverse\n", - " return self.change\n", - "\n", - " def reset(self):\n", - " self.G_t = None\n", - "\n", - "\n", - "class RMS_prop(Scheduler):\n", - " def __init__(self, eta, rho):\n", - " super().__init__(eta)\n", - " self.rho = rho\n", - " self.second = 0.0\n", - "\n", - " def update_change(self, gradient):\n", - " delta = 1e-8 # avoid division ny zero\n", - " self.second = self.rho * self.second + (1 - self.rho) * gradient * gradient\n", - " return self.eta * gradient / (np.sqrt(self.second + delta))\n", - "\n", - " def reset(self):\n", - " self.second = 0.0\n", - "\n", - "\n", - "class Adam(Scheduler):\n", - " def __init__(self, eta, rho, rho2):\n", - " super().__init__(eta)\n", - " self.rho = rho\n", - " self.rho2 = rho2\n", - " self.moment = 0\n", - " self.second = 0\n", - " self.n_epochs = 1\n", - "\n", - " def update_change(self, gradient):\n", - " delta = 1e-8 # avoid division ny zero\n", - "\n", - " self.moment = self.rho * self.moment + (1 - self.rho) * gradient\n", - " self.second = self.rho2 * self.second + (1 - self.rho2) * gradient * gradient\n", - "\n", - " moment_corrected = self.moment / (1 - self.rho**self.n_epochs)\n", - " second_corrected = self.second / (1 - self.rho2**self.n_epochs)\n", - "\n", - " return self.eta * moment_corrected / (np.sqrt(second_corrected + delta))\n", - "\n", - " def reset(self):\n", - " self.n_epochs += 1\n", - " self.moment = 0\n", - " self.second = 0" - ] - }, - { - "cell_type": "markdown", - "id": "bb621fce", - "metadata": {}, - "source": [ - "### Usage of the above learning rate schedulers\n", - "\n", - "To initalize a scheduler, simply create the object and pass in the\n", - "necessary parameters such as the learning rate and the momentum as\n", - "shown below. As the Scheduler class is an abstract class it should not\n", - "called directly, and will raise an error upon usage." - ] - }, - { - "cell_type": "code", - "execution_count": 4, - "id": "34ddb829", - "metadata": {}, - "outputs": [], - "source": [ - "momentum_scheduler = Momentum(eta=1e-3, momentum=0.9)\n", - "adam_scheduler = Adam(eta=1e-3, rho=0.9, rho2=0.999)" - ] - }, - { - "cell_type": "markdown", - "id": "e43498d4", - "metadata": {}, - "source": [ - "Here is a small example for how a segment of code using schedulers\n", - "could look. Switching out the schedulers is simple." - ] - }, - { - "cell_type": "code", - "execution_count": 5, - "id": "f05b9625", - "metadata": {}, - "outputs": [], - "source": [ - "weights = np.ones((3,3))\n", - "print(f\"Before scheduler:\\n{weights=}\")\n", - "\n", - "epochs = 10\n", - "for e in range(epochs):\n", - " gradient = np.random.rand(3, 3)\n", - " change = adam_scheduler.update_change(gradient)\n", - " weights = weights - change\n", - " adam_scheduler.reset()\n", - "\n", - "print(f\"\\nAfter scheduler:\\n{weights=}\")" - ] - }, - { - "cell_type": "markdown", - "id": "19cf9841", - "metadata": {}, - "source": [ - "### Cost functions\n", - "\n", - "Here we discuss cost functions that can be used when creating the\n", - "neural network. Every cost function takes the target vector as its\n", - "parameter, and returns a function valued only at $x$ such that it may\n", - "easily be differentiated." - ] - }, - { - "cell_type": "code", - "execution_count": 6, - "id": "993efa8d", - "metadata": {}, - "outputs": [], - "source": [ - "import autograd.numpy as np\n", - "\n", - "def CostOLS(target):\n", - " \n", - " def func(X):\n", - " return (1.0 / target.shape[0]) * np.sum((target - X) ** 2)\n", - "\n", - " return func\n", - "\n", - "\n", - "def CostLogReg(target):\n", - "\n", - " def func(X):\n", - " \n", - " return -(1.0 / target.shape[0]) * np.sum(\n", - " (target * np.log(X + 10e-10)) + ((1 - target) * np.log(1 - X + 10e-10))\n", - " )\n", - "\n", - " return func\n", - "\n", - "\n", - "def CostCrossEntropy(target):\n", - " \n", - " def func(X):\n", - " return -(1.0 / target.size) * np.sum(target * np.log(X + 10e-10))\n", - "\n", - " return func" - ] - }, - { - "cell_type": "markdown", - "id": "011c734c", - "metadata": {}, - "source": [ - "Below we give a short example of how these cost function may be used\n", - "to obtain results if you wish to test them out on your own using\n", - "AutoGrad's automatics differentiation." - ] - }, - { - "cell_type": "code", - "execution_count": 7, - "id": "9e1b97f5", - "metadata": {}, - "outputs": [], - "source": [ - "from autograd import grad\n", - "\n", - "target = np.array([[1, 2, 3]]).T\n", - "a = np.array([[4, 5, 6]]).T\n", - "\n", - "cost_func = CostCrossEntropy\n", - "cost_func_derivative = grad(cost_func(target))\n", - "\n", - "valued_at_a = cost_func_derivative(a)\n", - "print(f\"Derivative of cost function {cost_func.__name__} valued at a:\\n{valued_at_a}\")" - ] - }, - { - "cell_type": "markdown", - "id": "4acd87b2", - "metadata": {}, - "source": [ - "### Activation functions\n", - "\n", - "Finally, before we look at the neural network, we will look at the\n", - "activation functions which can be specified between the hidden layers\n", - "and as the output function. Each function can be valued for any given\n", - "vector or matrix X, and can be differentiated via derivate()." - ] - }, - { - "cell_type": "code", - "execution_count": 8, - "id": "befa86ae", - "metadata": {}, - "outputs": [], - "source": [ - "import autograd.numpy as np\n", - "from autograd import elementwise_grad\n", - "\n", - "def identity(X):\n", - " return X\n", - "\n", - "\n", - "def sigmoid(X):\n", - " try:\n", - " return 1.0 / (1 + np.exp(-X))\n", - " except FloatingPointError:\n", - " return np.where(X > np.zeros(X.shape), np.ones(X.shape), np.zeros(X.shape))\n", - "\n", - "\n", - "def softmax(X):\n", - " X = X - np.max(X, axis=-1, keepdims=True)\n", - " delta = 10e-10\n", - " return np.exp(X) / (np.sum(np.exp(X), axis=-1, keepdims=True) + delta)\n", - "\n", - "\n", - "def RELU(X):\n", - " return np.where(X > np.zeros(X.shape), X, np.zeros(X.shape))\n", - "\n", - "\n", - "def LRELU(X):\n", - " delta = 10e-4\n", - " return np.where(X > np.zeros(X.shape), X, delta * X)\n", - "\n", - "\n", - "def derivate(func):\n", - " if func.__name__ == \"RELU\":\n", - "\n", - " def func(X):\n", - " return np.where(X > 0, 1, 0)\n", - "\n", - " return func\n", - "\n", - " elif func.__name__ == \"LRELU\":\n", - "\n", - " def func(X):\n", - " delta = 10e-4\n", - " return np.where(X > 0, 1, delta)\n", - "\n", - " return func\n", - "\n", - " else:\n", - " return elementwise_grad(func)" - ] - }, - { - "cell_type": "markdown", - "id": "c20aa75e", - "metadata": {}, - "source": [ - "Below follows a short demonstration of how to use an activation\n", - "function. The derivative of the activation function will be important\n", - "when calculating the output delta term during backpropagation. Note\n", - "that derivate() can also be used for cost functions for a more\n", - "generalized approach." - ] - }, - { - "cell_type": "code", - "execution_count": 9, - "id": "e209f9e5", - "metadata": {}, - "outputs": [], - "source": [ - "z = np.array([[4, 5, 6]]).T\n", - "print(f\"Input to activation function:\\n{z}\")\n", - "\n", - "act_func = sigmoid\n", - "a = act_func(z)\n", - "print(f\"\\nOutput from {act_func.__name__} activation function:\\n{a}\")\n", - "\n", - "act_func_derivative = derivate(act_func)\n", - "valued_at_z = act_func_derivative(a)\n", - "print(f\"\\nDerivative of {act_func.__name__} activation function valued at z:\\n{valued_at_z}\")" - ] - }, - { - "cell_type": "markdown", - "id": "524b409b", - "metadata": {}, - "source": [ - "### The Neural Network\n", - "\n", - "Now that we have gotten a good understanding of the implementation of\n", - "some important components, we can take a look at an object oriented\n", - "implementation of a feed forward neural network. The feed forward\n", - "neural network has been implemented as a class named FFNN, which can\n", - "be initiated as a regressor or classifier dependant on the choice of\n", - "cost function. The FFNN can have any number of input nodes, hidden\n", - "layers with any amount of hidden nodes, and any amount of output nodes\n", - "meaning it can perform multiclass classification as well as binary\n", - "classification and regression problems. Although there is a lot of\n", - "code present, it makes for an easy to use and generalizeable interface\n", - "for creating many types of neural networks as will be demonstrated\n", - "below." - ] - }, - { - "cell_type": "code", - "execution_count": 10, - "id": "083116d3", - "metadata": {}, - "outputs": [], - "source": [ - "import math\n", - "import autograd.numpy as np\n", - "import sys\n", - "import warnings\n", - "from autograd import grad, elementwise_grad\n", - "from random import random, seed\n", - "from copy import deepcopy, copy\n", - "from typing import Tuple, Callable\n", - "from sklearn.utils import resample\n", - "\n", - "warnings.simplefilter(\"error\")\n", - "\n", - "\n", - "class FFNN:\n", - " \"\"\"\n", - " Description:\n", - " ------------\n", - " Feed Forward Neural Network with interface enabling flexible design of a\n", - " nerual networks architecture and the specification of activation function\n", - " in the hidden layers and output layer respectively. This model can be used\n", - " for both regression and classification problems, depending on the output function.\n", - "\n", - " Attributes:\n", - " ------------\n", - " I dimensions (tuple[int]): A list of positive integers, which specifies the\n", - " number of nodes in each of the networks layers. The first integer in the array\n", - " defines the number of nodes in the input layer, the second integer defines number\n", - " of nodes in the first hidden layer and so on until the last number, which\n", - " specifies the number of nodes in the output layer.\n", - " II hidden_func (Callable): The activation function for the hidden layers\n", - " III output_func (Callable): The activation function for the output layer\n", - " IV cost_func (Callable): Our cost function\n", - " V seed (int): Sets random seed, makes results reproducible\n", - " \"\"\"\n", - "\n", - " def __init__(\n", - " self,\n", - " dimensions: tuple[int],\n", - " hidden_func: Callable = sigmoid,\n", - " output_func: Callable = lambda x: x,\n", - " cost_func: Callable = CostOLS,\n", - " seed: int = None,\n", - " ):\n", - " self.dimensions = dimensions\n", - " self.hidden_func = hidden_func\n", - " self.output_func = output_func\n", - " self.cost_func = cost_func\n", - " self.seed = seed\n", - " self.weights = list()\n", - " self.schedulers_weight = list()\n", - " self.schedulers_bias = list()\n", - " self.a_matrices = list()\n", - " self.z_matrices = list()\n", - " self.classification = None\n", - "\n", - " self.reset_weights()\n", - " self._set_classification()\n", - "\n", - " def fit(\n", - " self,\n", - " X: np.ndarray,\n", - " t: np.ndarray,\n", - " scheduler: Scheduler,\n", - " batches: int = 1,\n", - " epochs: int = 100,\n", - " lam: float = 0,\n", - " X_val: np.ndarray = None,\n", - " t_val: np.ndarray = None,\n", - " ):\n", - " \"\"\"\n", - " Description:\n", - " ------------\n", - " This function performs the training the neural network by performing the feedforward and backpropagation\n", - " algorithm to update the networks weights.\n", - "\n", - " Parameters:\n", - " ------------\n", - " I X (np.ndarray) : training data\n", - " II t (np.ndarray) : target data\n", - " III scheduler (Scheduler) : specified scheduler (algorithm for optimization of gradient descent)\n", - " IV scheduler_args (list[int]) : list of all arguments necessary for scheduler\n", - "\n", - " Optional Parameters:\n", - " ------------\n", - " V batches (int) : number of batches the datasets are split into, default equal to 1\n", - " VI epochs (int) : number of iterations used to train the network, default equal to 100\n", - " VII lam (float) : regularization hyperparameter lambda\n", - " VIII X_val (np.ndarray) : validation set\n", - " IX t_val (np.ndarray) : validation target set\n", - "\n", - " Returns:\n", - " ------------\n", - " I scores (dict) : A dictionary containing the performance metrics of the model.\n", - " The number of the metrics depends on the parameters passed to the fit-function.\n", - "\n", - " \"\"\"\n", - "\n", - " # setup \n", - " if self.seed is not None:\n", - " np.random.seed(self.seed)\n", - "\n", - " val_set = False\n", - " if X_val is not None and t_val is not None:\n", - " val_set = True\n", - "\n", - " # creating arrays for score metrics\n", - " train_errors = np.empty(epochs)\n", - " train_errors.fill(np.nan)\n", - " val_errors = np.empty(epochs)\n", - " val_errors.fill(np.nan)\n", - "\n", - " train_accs = np.empty(epochs)\n", - " train_accs.fill(np.nan)\n", - " val_accs = np.empty(epochs)\n", - " val_accs.fill(np.nan)\n", - "\n", - " self.schedulers_weight = list()\n", - " self.schedulers_bias = list()\n", - "\n", - " batch_size = X.shape[0] // batches\n", - "\n", - " X, t = resample(X, t)\n", - "\n", - " # this function returns a function valued only at X\n", - " cost_function_train = self.cost_func(t)\n", - " if val_set:\n", - " cost_function_val = self.cost_func(t_val)\n", - "\n", - " # create schedulers for each weight matrix\n", - " for i in range(len(self.weights)):\n", - " self.schedulers_weight.append(copy(scheduler))\n", - " self.schedulers_bias.append(copy(scheduler))\n", - "\n", - " print(f\"{scheduler.__class__.__name__}: Eta={scheduler.eta}, Lambda={lam}\")\n", - "\n", - " try:\n", - " for e in range(epochs):\n", - " for i in range(batches):\n", - " # allows for minibatch gradient descent\n", - " if i == batches - 1:\n", - " # If the for loop has reached the last batch, take all thats left\n", - " X_batch = X[i * batch_size :, :]\n", - " t_batch = t[i * batch_size :, :]\n", - " else:\n", - " X_batch = X[i * batch_size : (i + 1) * batch_size, :]\n", - " t_batch = t[i * batch_size : (i + 1) * batch_size, :]\n", - "\n", - " self._feedforward(X_batch)\n", - " self._backpropagate(X_batch, t_batch, lam)\n", - "\n", - " # reset schedulers for each epoch (some schedulers pass in this call)\n", - " for scheduler in self.schedulers_weight:\n", - " scheduler.reset()\n", - "\n", - " for scheduler in self.schedulers_bias:\n", - " scheduler.reset()\n", - "\n", - " # computing performance metrics\n", - " pred_train = self.predict(X)\n", - " train_error = cost_function_train(pred_train)\n", - "\n", - " train_errors[e] = train_error\n", - " if val_set:\n", - " \n", - " pred_val = self.predict(X_val)\n", - " val_error = cost_function_val(pred_val)\n", - " val_errors[e] = val_error\n", - "\n", - " if self.classification:\n", - " train_acc = self._accuracy(self.predict(X), t)\n", - " train_accs[e] = train_acc\n", - " if val_set:\n", - " val_acc = self._accuracy(pred_val, t_val)\n", - " val_accs[e] = val_acc\n", - "\n", - " # printing progress bar\n", - " progression = e / epochs\n", - " print_length = self._progress_bar(\n", - " progression,\n", - " train_error=train_errors[e],\n", - " train_acc=train_accs[e],\n", - " val_error=val_errors[e],\n", - " val_acc=val_accs[e],\n", - " )\n", - " except KeyboardInterrupt:\n", - " # allows for stopping training at any point and seeing the result\n", - " pass\n", - "\n", - " # visualization of training progression (similiar to tensorflow progression bar)\n", - " sys.stdout.write(\"\\r\" + \" \" * print_length)\n", - " sys.stdout.flush()\n", - " self._progress_bar(\n", - " 1,\n", - " train_error=train_errors[e],\n", - " train_acc=train_accs[e],\n", - " val_error=val_errors[e],\n", - " val_acc=val_accs[e],\n", - " )\n", - " sys.stdout.write(\"\")\n", - "\n", - " # return performance metrics for the entire run\n", - " scores = dict()\n", - "\n", - " scores[\"train_errors\"] = train_errors\n", - "\n", - " if val_set:\n", - " scores[\"val_errors\"] = val_errors\n", - "\n", - " if self.classification:\n", - " scores[\"train_accs\"] = train_accs\n", - "\n", - " if val_set:\n", - " scores[\"val_accs\"] = val_accs\n", - "\n", - " return scores\n", - "\n", - " def predict(self, X: np.ndarray, *, threshold=0.5):\n", - " \"\"\"\n", - " Description:\n", - " ------------\n", - " Performs prediction after training of the network has been finished.\n", - "\n", - " Parameters:\n", - " ------------\n", - " I X (np.ndarray): The design matrix, with n rows of p features each\n", - "\n", - " Optional Parameters:\n", - " ------------\n", - " II threshold (float) : sets minimal value for a prediction to be predicted as the positive class\n", - " in classification problems\n", - "\n", - " Returns:\n", - " ------------\n", - " I z (np.ndarray): A prediction vector (row) for each row in our design matrix\n", - " This vector is thresholded if regression=False, meaning that classification results\n", - " in a vector of 1s and 0s, while regressions in an array of decimal numbers\n", - "\n", - " \"\"\"\n", - "\n", - " predict = self._feedforward(X)\n", - "\n", - " if self.classification:\n", - " return np.where(predict > threshold, 1, 0)\n", - " else:\n", - " return predict\n", - "\n", - " def reset_weights(self):\n", - " \"\"\"\n", - " Description:\n", - " ------------\n", - " Resets/Reinitializes the weights in order to train the network for a new problem.\n", - "\n", - " \"\"\"\n", - " if self.seed is not None:\n", - " np.random.seed(self.seed)\n", - "\n", - " self.weights = list()\n", - " for i in range(len(self.dimensions) - 1):\n", - " weight_array = np.random.randn(\n", - " self.dimensions[i] + 1, self.dimensions[i + 1]\n", - " )\n", - " weight_array[0, :] = np.random.randn(self.dimensions[i + 1]) * 0.01\n", - "\n", - " self.weights.append(weight_array)\n", - "\n", - " def _feedforward(self, X: np.ndarray):\n", - " \"\"\"\n", - " Description:\n", - " ------------\n", - " Calculates the activation of each layer starting at the input and ending at the output.\n", - " Each following activation is calculated from a weighted sum of each of the preceeding\n", - " activations (except in the case of the input layer).\n", - "\n", - " Parameters:\n", - " ------------\n", - " I X (np.ndarray): The design matrix, with n rows of p features each\n", - "\n", - " Returns:\n", - " ------------\n", - " I z (np.ndarray): A prediction vector (row) for each row in our design matrix\n", - " \"\"\"\n", - "\n", - " # reset matrices\n", - " self.a_matrices = list()\n", - " self.z_matrices = list()\n", - "\n", - " # if X is just a vector, make it into a matrix\n", - " if len(X.shape) == 1:\n", - " X = X.reshape((1, X.shape[0]))\n", - "\n", - " # Add a coloumn of zeros as the first coloumn of the design matrix, in order\n", - " # to add bias to our data\n", - " bias = np.ones((X.shape[0], 1)) * 0.01\n", - " X = np.hstack([bias, X])\n", - "\n", - " # a^0, the nodes in the input layer (one a^0 for each row in X - where the\n", - " # exponent indicates layer number).\n", - " a = X\n", - " self.a_matrices.append(a)\n", - " self.z_matrices.append(a)\n", - "\n", - " # The feed forward algorithm\n", - " for i in range(len(self.weights)):\n", - " if i < len(self.weights) - 1:\n", - " z = a @ self.weights[i]\n", - " self.z_matrices.append(z)\n", - " a = self.hidden_func(z)\n", - " # bias column again added to the data here\n", - " bias = np.ones((a.shape[0], 1)) * 0.01\n", - " a = np.hstack([bias, a])\n", - " self.a_matrices.append(a)\n", - " else:\n", - " try:\n", - " # a^L, the nodes in our output layers\n", - " z = a @ self.weights[i]\n", - " a = self.output_func(z)\n", - " self.a_matrices.append(a)\n", - " self.z_matrices.append(z)\n", - " except Exception as OverflowError:\n", - " print(\n", - " \"OverflowError in fit() in FFNN\\nHOW TO DEBUG ERROR: Consider lowering your learning rate or scheduler specific parameters such as momentum, or check if your input values need scaling\"\n", - " )\n", - "\n", - " # this will be a^L\n", - " return a\n", - "\n", - " def _backpropagate(self, X, t, lam):\n", - " \"\"\"\n", - " Description:\n", - " ------------\n", - " Performs the backpropagation algorithm. In other words, this method\n", - " calculates the gradient of all the layers starting at the\n", - " output layer, and moving from right to left accumulates the gradient until\n", - " the input layer is reached. Each layers respective weights are updated while\n", - " the algorithm propagates backwards from the output layer (auto-differentation in reverse mode).\n", - "\n", - " Parameters:\n", - " ------------\n", - " I X (np.ndarray): The design matrix, with n rows of p features each.\n", - " II t (np.ndarray): The target vector, with n rows of p targets.\n", - " III lam (float32): regularization parameter used to punish the weights in case of overfitting\n", - "\n", - " Returns:\n", - " ------------\n", - " No return value.\n", - "\n", - " \"\"\"\n", - " out_derivative = derivate(self.output_func)\n", - " hidden_derivative = derivate(self.hidden_func)\n", - "\n", - " for i in range(len(self.weights) - 1, -1, -1):\n", - " # delta terms for output\n", - " if i == len(self.weights) - 1:\n", - " # for multi-class classification\n", - " if (\n", - " self.output_func.__name__ == \"softmax\"\n", - " ):\n", - " delta_matrix = self.a_matrices[i + 1] - t\n", - " # for single class classification\n", - " else:\n", - " cost_func_derivative = grad(self.cost_func(t))\n", - " delta_matrix = out_derivative(\n", - " self.z_matrices[i + 1]\n", - " ) * cost_func_derivative(self.a_matrices[i + 1])\n", - "\n", - " # delta terms for hidden layer\n", - " else:\n", - " delta_matrix = (\n", - " self.weights[i + 1][1:, :] @ delta_matrix.T\n", - " ).T * hidden_derivative(self.z_matrices[i + 1])\n", - "\n", - " # calculate gradient\n", - " gradient_weights = self.a_matrices[i][:, 1:].T @ delta_matrix\n", - " gradient_bias = np.sum(delta_matrix, axis=0).reshape(\n", - " 1, delta_matrix.shape[1]\n", - " )\n", - "\n", - " # regularization term\n", - " gradient_weights += self.weights[i][1:, :] * lam\n", - "\n", - " # use scheduler\n", - " update_matrix = np.vstack(\n", - " [\n", - " self.schedulers_bias[i].update_change(gradient_bias),\n", - " self.schedulers_weight[i].update_change(gradient_weights),\n", - " ]\n", - " )\n", - "\n", - " # update weights and bias\n", - " self.weights[i] -= update_matrix\n", - "\n", - " def _accuracy(self, prediction: np.ndarray, target: np.ndarray):\n", - " \"\"\"\n", - " Description:\n", - " ------------\n", - " Calculates accuracy of given prediction to target\n", - "\n", - " Parameters:\n", - " ------------\n", - " I prediction (np.ndarray): vector of predicitons output network\n", - " (1s and 0s in case of classification, and real numbers in case of regression)\n", - " II target (np.ndarray): vector of true values (What the network ideally should predict)\n", - "\n", - " Returns:\n", - " ------------\n", - " A floating point number representing the percentage of correctly classified instances.\n", - " \"\"\"\n", - " assert prediction.size == target.size\n", - " return np.average((target == prediction))\n", - " def _set_classification(self):\n", - " \"\"\"\n", - " Description:\n", - " ------------\n", - " Decides if FFNN acts as classifier (True) og regressor (False),\n", - " sets self.classification during init()\n", - " \"\"\"\n", - " self.classification = False\n", - " if (\n", - " self.cost_func.__name__ == \"CostLogReg\"\n", - " or self.cost_func.__name__ == \"CostCrossEntropy\"\n", - " ):\n", - " self.classification = True\n", - "\n", - " def _progress_bar(self, progression, **kwargs):\n", - " \"\"\"\n", - " Description:\n", - " ------------\n", - " Displays progress of training\n", - " \"\"\"\n", - " print_length = 40\n", - " num_equals = int(progression * print_length)\n", - " num_not = print_length - num_equals\n", - " arrow = \">\" if num_equals > 0 else \"\"\n", - " bar = \"[\" + \"=\" * (num_equals - 1) + arrow + \"-\" * num_not + \"]\"\n", - " perc_print = self._format(progression * 100, decimals=5)\n", - " line = f\" {bar} {perc_print}% \"\n", - "\n", - " for key in kwargs:\n", - " if not np.isnan(kwargs[key]):\n", - " value = self._format(kwargs[key], decimals=4)\n", - " line += f\"| {key}: {value} \"\n", - " sys.stdout.write(\"\\r\" + line)\n", - " sys.stdout.flush()\n", - " return len(line)\n", - "\n", - " def _format(self, value, decimals=4):\n", - " \"\"\"\n", - " Description:\n", - " ------------\n", - " Formats decimal numbers for progress bar\n", - " \"\"\"\n", - " if value > 0:\n", - " v = value\n", - " elif value < 0:\n", - " v = -10 * value\n", - " else:\n", - " v = 1\n", - " n = 1 + math.floor(math.log10(v))\n", - " if n >= decimals - 1:\n", - " return str(round(value))\n", - " return f\"{value:.{decimals-n-1}f}\"" - ] - }, - { - "cell_type": "markdown", - "id": "e4ba55d0", - "metadata": {}, - "source": [ - "Before we make a model, we will quickly generate a dataset we can use\n", - "for our linear regression problem as shown below" - ] - }, - { - "cell_type": "code", - "execution_count": 11, - "id": "c72a22c6", - "metadata": {}, - "outputs": [], - "source": [ - "import autograd.numpy as np\n", - "from sklearn.model_selection import train_test_split\n", - "\n", - "def SkrankeFunction(x, y):\n", - " return np.ravel(0 + 1*x + 2*y + 3*x**2 + 4*x*y + 5*y**2)\n", - "\n", - "def create_X(x, y, n):\n", - " if len(x.shape) > 1:\n", - " x = np.ravel(x)\n", - " y = np.ravel(y)\n", - "\n", - " N = len(x)\n", - " l = int((n + 1) * (n + 2) / 2) # Number of elements in beta\n", - " X = np.ones((N, l))\n", - "\n", - " for i in range(1, n + 1):\n", - " q = int((i) * (i + 1) / 2)\n", - " for k in range(i + 1):\n", - " X[:, q + k] = (x ** (i - k)) * (y**k)\n", - "\n", - " return X\n", - "\n", - "step=0.5\n", - "x = np.arange(0, 1, step)\n", - "y = np.arange(0, 1, step)\n", - "x, y = np.meshgrid(x, y)\n", - "target = SkrankeFunction(x, y)\n", - "target = target.reshape(target.shape[0], 1)\n", - "\n", - "poly_degree=3\n", - "X = create_X(x, y, poly_degree)\n", - "\n", - "X_train, X_test, t_train, t_test = train_test_split(X, target)" - ] - }, - { - "cell_type": "markdown", - "id": "25b63b47", - "metadata": {}, - "source": [ - "Now that we have our dataset ready for the regression, we can create\n", - "our regressor. Note that with the seed parameter, we can make sure our\n", - "results stay the same every time we run the neural network. For\n", - "inititialization, we simply specify the dimensions (we wish the amount\n", - "of input nodes to be equal to the datapoints, and the output to\n", - "predict one value)." - ] - }, - { - "cell_type": "code", - "execution_count": 12, - "id": "b6b4e461", - "metadata": {}, - "outputs": [], - "source": [ - "input_nodes = X_train.shape[1]\n", - "output_nodes = 1\n", - "\n", - "linear_regression = FFNN((input_nodes, output_nodes), output_func=identity, cost_func=CostOLS, seed=2023)" - ] - }, - { - "cell_type": "markdown", - "id": "d7860b74", - "metadata": {}, - "source": [ - "We then fit our model with our training data using the scheduler of our choice." - ] - }, - { - "cell_type": "code", - "execution_count": 13, - "id": "00522c73", - "metadata": {}, - "outputs": [], - "source": [ - "linear_regression.reset_weights() # reset weights such that previous runs or reruns don't affect the weights\n", - "\n", - "scheduler = Constant(eta=1e-3)\n", - "scores = linear_regression.fit(X_train, t_train, scheduler)" - ] - }, - { - "cell_type": "markdown", - "id": "a57bfb12", - "metadata": {}, - "source": [ - "Due to the progress bar we can see the MSE (train_error) throughout\n", - "the FFNN's training. Note that the fit() function has some optional\n", - "parameters with defualt arguments. For example, the regularization\n", - "hyperparameter can be left ignored if not needed, and equally the FFNN\n", - "will by default run for 100 epochs. These can easily be changed, such\n", - "as for example:" - ] - }, - { - "cell_type": "code", - "execution_count": 14, - "id": "35259e41", - "metadata": {}, - "outputs": [], - "source": [ - "linear_regression.reset_weights() # reset weights such that previous runs or reruns don't affect the weights\n", - "\n", - "scores = linear_regression.fit(X_train, t_train, scheduler, lam=1e-4, epochs=1000)" - ] - }, - { - "cell_type": "markdown", - "id": "4a403370", - "metadata": {}, - "source": [ - "We see that given more epochs to train on, the regressor reaches a lower MSE.\n", - "\n", - "Let us then switch to a binary classification. We use a binary\n", - "classification dataset, and follow a similar setup to the regression\n", - "case." - ] - }, - { - "cell_type": "code", - "execution_count": 15, - "id": "6c791130", - "metadata": {}, - "outputs": [], - "source": [ - "from sklearn.datasets import load_breast_cancer\n", - "from sklearn.preprocessing import MinMaxScaler\n", - "\n", - "wisconsin = load_breast_cancer()\n", - "X = wisconsin.data\n", - "target = wisconsin.target\n", - "target = target.reshape(target.shape[0], 1)\n", - "\n", - "X_train, X_val, t_train, t_val = train_test_split(X, target)\n", - "\n", - "scaler = MinMaxScaler()\n", - "scaler.fit(X_train)\n", - "X_train = scaler.transform(X_train)\n", - "X_val = scaler.transform(X_val)" - ] - }, - { - "cell_type": "code", - "execution_count": 16, - "id": "0ac0258d", - "metadata": {}, - "outputs": [], - "source": [ - "input_nodes = X_train.shape[1]\n", - "output_nodes = 1\n", - "\n", - "logistic_regression = FFNN((input_nodes, output_nodes), output_func=sigmoid, cost_func=CostLogReg, seed=2023)" - ] - }, - { - "cell_type": "markdown", - "id": "a9c74baa", - "metadata": {}, - "source": [ - "We will now make use of our validation data by passing it into our fit function as a keyword argument" - ] - }, - { - "cell_type": "code", - "execution_count": 17, - "id": "e5021bbf", - "metadata": {}, - "outputs": [], - "source": [ - "logistic_regression.reset_weights() # reset weights such that previous runs or reruns don't affect the weights\n", - "\n", - "scheduler = Adam(eta=1e-3, rho=0.9, rho2=0.999)\n", - "scores = logistic_regression.fit(X_train, t_train, scheduler, epochs=1000, X_val=X_val, t_val=t_val)" - ] - }, - { - "cell_type": "markdown", - "id": "ae0148bb", - "metadata": {}, - "source": [ - "Finally, we will create a neural network with 2 hidden layers with activation functions." - ] - }, - { - "cell_type": "code", - "execution_count": 18, - "id": "bb7e4340", - "metadata": {}, - "outputs": [], - "source": [ - "input_nodes = X_train.shape[1]\n", - "hidden_nodes1 = 100\n", - "hidden_nodes2 = 30\n", - "output_nodes = 1\n", - "\n", - "dims = (input_nodes, hidden_nodes1, hidden_nodes2, output_nodes)\n", - "\n", - "neural_network = FFNN(dims, hidden_func=RELU, output_func=sigmoid, cost_func=CostLogReg, seed=2023)" - ] - }, - { - "cell_type": "code", - "execution_count": 19, - "id": "d0655afb", - "metadata": {}, - "outputs": [], - "source": [ - "neural_network.reset_weights() # reset weights such that previous runs or reruns don't affect the weights\n", - "\n", - "scheduler = Adam(eta=1e-4, rho=0.9, rho2=0.999)\n", - "scores = neural_network.fit(X_train, t_train, scheduler, epochs=1000, X_val=X_val, t_val=t_val)" - ] - }, - { - "cell_type": "markdown", - "id": "dc8a90af", - "metadata": {}, - "source": [ - "### Multiclass classification\n", - "\n", - "Finally, we will demonstrate the use case of multiclass classification\n", - "using our FFNN with the famous MNIST dataset, which contain images of\n", - "digits between the range of 0 to 9." - ] - }, - { - "cell_type": "code", - "execution_count": 20, - "id": "9305c08a", - "metadata": {}, - "outputs": [], - "source": [ - "from sklearn.datasets import load_digits\n", - "\n", - "def onehot(target: np.ndarray):\n", - " onehot = np.zeros((target.size, target.max() + 1))\n", - " onehot[np.arange(target.size), target] = 1\n", - " return onehot\n", - "\n", - "digits = load_digits()\n", - "\n", - "X = digits.data\n", - "target = digits.target\n", - "target = onehot(target)\n", - "\n", - "input_nodes = 64\n", - "hidden_nodes1 = 100\n", - "hidden_nodes2 = 30\n", - "output_nodes = 10\n", - "\n", - "dims = (input_nodes, hidden_nodes1, hidden_nodes2, output_nodes)\n", - "\n", - "multiclass = FFNN(dims, hidden_func=LRELU, output_func=softmax, cost_func=CostCrossEntropy)\n", - "\n", - "multiclass.reset_weights() # reset weights such that previous runs or reruns don't affect the weights\n", - "\n", - "scheduler = Adam(eta=1e-4, rho=0.9, rho2=0.999)\n", - "scores = multiclass.fit(X, target, scheduler, epochs=1000)" - ] - }, - { - "cell_type": "markdown", - "id": "8e208051", - "metadata": {}, - "source": [ - "## Testing the XOR gate and other gates\n", - "\n", - "Let us now use our code to test the XOR gate." - ] - }, - { - "cell_type": "code", - "execution_count": 21, - "id": "db016d41", - "metadata": {}, - "outputs": [], - "source": [ - "X = np.array([ [0, 0], [0, 1], [1, 0],[1, 1]],dtype=np.float64)\n", - "\n", - "# The XOR gate\n", - "yXOR = np.array( [[ 0], [1] ,[1], [0]])\n", - "\n", - "input_nodes = X.shape[1]\n", - "output_nodes = 1\n", - "\n", - "logistic_regression = FFNN((input_nodes, output_nodes), output_func=sigmoid, cost_func=CostLogReg, seed=2023)\n", - "logistic_regression.reset_weights() # reset weights such that previous runs or reruns don't affect the weights\n", - "scheduler = Adam(eta=1e-1, rho=0.9, rho2=0.999)\n", - "scores = logistic_regression.fit(X, yXOR, scheduler, epochs=1000)" - ] - }, - { - "cell_type": "markdown", - "id": "d1384449", - "metadata": {}, - "source": [ - "Not bad, but the results depend strongly on the learning reate. Try different learning rates." - ] - } - ], - "metadata": { - "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.9.10" - } - }, - "nbformat": 4, - "nbformat_minor": 5 -} diff --git a/doc/LectureNotes/exercisesweek47.ipynb b/doc/LectureNotes/exercisesweek47.ipynb deleted file mode 100644 index d897dd60b..000000000 --- a/doc/LectureNotes/exercisesweek47.ipynb +++ /dev/null @@ -1,214 +0,0 @@ -{ - "cells": [ - { - "cell_type": "markdown", - "id": "29616fbf", - "metadata": {}, - "source": [ - "\n", - "" - ] - }, - { - "cell_type": "markdown", - "id": "e4f3fe3f", - "metadata": {}, - "source": [ - "# Exercise week 47\n", - "**November 20-24, 2023**\n", - "\n", - "Date: **Deadline is Sunday November 26 at midnight**" - ] - }, - { - "cell_type": "markdown", - "id": "c1f597b7", - "metadata": {}, - "source": [ - "# Overarching aims of the exercises this week\n", - "\n", - "The exercise this week is a simple course survey and feedback. This\n", - "is important for us in order to improve our teaching material, the\n", - "active learning format and anything else related to a succesful\n", - "mastering of central machine learning methods and their applications." - ] - }, - { - "cell_type": "markdown", - "id": "7497591b", - "metadata": {}, - "source": [ - "### Why did you choose this course?" - ] - }, - { - "cell_type": "markdown", - "id": "1c08143f", - "metadata": {}, - "source": [ - "### What was your programming knowledge before you started?\n", - "\n", - "And do you feel this course added to your programming competences and skills?" - ] - }, - { - "cell_type": "markdown", - "id": "9783d8a7", - "metadata": {}, - "source": [ - "### How do you judge your own level of knowledge on machine learning before and after this course?\n", - "\n", - "Here you can discuss your level of skill/knowledge at start of course\n", - "and at the end of the course and how these matched the level of\n", - "skill/knowledge needed to complete the projects." - ] - }, - { - "cell_type": "markdown", - "id": "8b0d5c47", - "metadata": {}, - "source": [ - "### Did the projects and the teaching material allow you to deepen your insights about Machine Learning?\n", - "\n", - "Feel free to comment here." - ] - }, - { - "cell_type": "markdown", - "id": "1ead8d47", - "metadata": {}, - "source": [ - "### Project based teaching and active learning\n", - "\n", - "This is a project based course and we as teachers would like to keep\n", - "it as it is since we see very clearly that people who attend this\n", - "course have a very good learning outcome. Project based courses are\n", - "however demanding (and expensive seen from the university admin) when\n", - "it comes to proper feedback and evaluations. Feel free to discuss\n", - "whether you found a project-based and active learning approach\n", - "useful. Feel also free to comment upon things we can improve upon or\n", - "alternative ways to assess whether the learning outcomes have been\n", - "achieved. Would you for example a standard 4 hours written exam\n", - "be something you would prefer? Or other alternatives to projects? We\n", - "would very much value your thoughts here since projects are an\n", - "essential part of this course." - ] - }, - { - "cell_type": "markdown", - "id": "746bd238", - "metadata": {}, - "source": [ - "### Usefulness of the weekly exercises\n", - "\n", - "Did the weekly exercises help in getting started with the projects?\n", - "How relevant where they for solving the projects? Feel free to\n", - "elaborate" - ] - }, - { - "cell_type": "markdown", - "id": "2ce96822", - "metadata": {}, - "source": [ - "### Active learning/lab sessions and lectures\n", - "\n", - "Was there a good link between lectures and active learning sessions?\n", - "Would you prefer an active learning environment only with no lectures\n", - "or would you prefer a more lecture based format with lab sessions only\n", - "(that is no discussion at the beginning of the lab sessions)? Feel\n", - "free to comment." - ] - }, - { - "cell_type": "markdown", - "id": "5dc0637a", - "metadata": {}, - "source": [ - "### How would you improve this course?\n", - "\n", - "Are there topics which are missing, topics which could have been\n", - "omitted and/or discussed in more depth? Feel free to add your comments\n", - "here such as how to improve to teaching material and more." - ] - }, - { - "cell_type": "markdown", - "id": "a98adf6c", - "metadata": {}, - "source": [ - "## Then some basic questions" - ] - }, - { - "cell_type": "markdown", - "id": "3a935279", - "metadata": {}, - "source": [ - "### Which is your preferred information chanel, Canvas, Discord, mail or other?" - ] - }, - { - "cell_type": "markdown", - "id": "41592552", - "metadata": {}, - "source": [ - "### Was the weekly update with plans etc useful?" - ] - }, - { - "cell_type": "markdown", - "id": "e79a2360", - "metadata": {}, - "source": [ - "### Was it easy to access the course material?" - ] - }, - { - "cell_type": "markdown", - "id": "8bc4dfc9", - "metadata": {}, - "source": [ - "### Which resources and tools did you use? Jupyter-notebooks, GitHub, the various textbooks we have recommended, etc etc" - ] - }, - { - "cell_type": "markdown", - "id": "bf415075", - "metadata": {}, - "source": [ - "### If you did not attend the lectures or the active learning/lab sessions, which resources did you use?" - ] - }, - { - "cell_type": "markdown", - "id": "db3db20a", - "metadata": {}, - "source": [ - "### Any other topics, impressions, ideas etc you would like to share with us?" - ] - } - ], - "metadata": { - "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.9.10" - } - }, - "nbformat": 4, - "nbformat_minor": 5 -} diff --git a/doc/LectureNotes/week34.ipynb b/doc/LectureNotes/week34.ipynb deleted file mode 100644 index 83d9cbf62..000000000 --- a/doc/LectureNotes/week34.ipynb +++ /dev/null @@ -1,4962 +0,0 @@ -{ - "cells": [ - { - "cell_type": "markdown", - "id": "390f1bd7", - "metadata": { - "editable": true - }, - "source": [ - "\n", - "" - ] - }, - { - "cell_type": "markdown", - "id": "2c8cea05", - "metadata": { - "editable": true - }, - "source": [ - "# Week 34: Introduction to the course, Logistics and Practicalities\n", - "**Morten Hjorth-Jensen**, Department of Physics and Center for Computing in Science Education, University of Oslo, Norway and Department of Physics and Astronomy and Facility for Rare Isotope Beams, Michigan State University, USA\n", - "\n", - "Date: **Week 34, August 21-25, 2023**" - ] - }, - { - "cell_type": "markdown", - "id": "725240be", - "metadata": { - "editable": true - }, - "source": [ - "## Overview of first week\n", - "\n", - "1. The sessions on Tuesdays and Wednesdays last four hours for each group (four groups in total) and will include lectures in a flipped mode (promoting active learning) and work on exercices and projects.\n", - "\n", - "2. The sessions will begin with lectures, discussions, questions and answers about the material to be covered every week. Videos and teaching material will be announced in due time.\n", - "\n", - "3. There are four groups:\n", - "\n", - " * Tuesdays 815am-12pm and 1215pm-4pm\n", - "\n", - " * Wednesdays 815am-12pm and 1215pm-4pm.\n", - "\n", - "4. On Thursdays we have a regular lecture. These lectures start at 1215pm and end at 2pm and serve the aims of giving an overview over various topics. These lectures will also be recorded.\n", - "\n", - "The labs are also available till 6pm Tuesdays and Wednesdays. Videos and learning material with reading suggestions will be made available before each week starts." - ] - }, - { - "cell_type": "markdown", - "id": "c18f9a3c", - "metadata": { - "editable": true - }, - "source": [ - "## Schedule first week\n", - "\n", - " * August 22: Presentation of the course, aims and content. Introduction to software and repetition of Python Programming, linear algebra and basic elements of statistics. Please select group.\n", - "\n", - " * August 23: Presentation of the course, aims and content. Introduction to software and repetition of Python Programming, linear algebra and basic elements of statistics. Please select group.\n", - "\n", - " * August 24: Lecture: Linear regression, examples and theory" - ] - }, - { - "cell_type": "markdown", - "id": "769cbfc6", - "metadata": { - "editable": true - }, - "source": [ - "## Lectures and ComputerLab\n", - "\n", - " * The sessions on Tuesdays and Wednesdays last four hours and will include partly lectures in a flipped mode (promoting active learning) and work on exercices and projects.\n", - "\n", - " * Thursdays: regular lectures (12.15pm-2pm) \n", - "\n", - " * Weekly reading assignments and videos needed to solve projects and exercises.\n", - "\n", - " * Weekly exercises. You can hand in exercises if you want and get an extra score, see below.\n", - "\n", - " * Detailed lecture notes, exercises, all programs presented, projects etc can be found at the homepage of the course.\n", - "\n", - " * Weekly plans and all other information are on the official website. This info will also be conveyed via weekly emails.\n", - "\n", - " * No final exam, three projects that are graded and have to be approved." - ] - }, - { - "cell_type": "markdown", - "id": "5040ec52", - "metadata": { - "editable": true - }, - "source": [ - "## Communication channels\n", - "\n", - "* Chat and communications via \n", - "\n", - "* **Discord** channel will be added asap" - ] - }, - { - "cell_type": "markdown", - "id": "867e5431", - "metadata": { - "editable": true - }, - "source": [ - "## Course Format\n", - "\n", - " * Three compulsory projects. Electronic reports only using [Canvas](https://www.uio.no/english/services/it/education/canvas/) to hand in projects and [git](https://git-scm.com/) as version control software and [GitHub](https://github.com/) for repository (or [GitLab](https://about.gitlab.com/)) of all your material.\n", - "\n", - " * Evaluation and grading: The three projects are graded and each counts 1/3 of the final mark. No final written or oral exam.\n", - "\n", - "a. For the last project each group/participant submits a proposal or works with suggested (by us) proposals for the project.\n", - "\n", - "b. If possible, we would like to organize the last project as a workshop where each group presents this to all other participants of the course\n", - "\n", - "c. Based on feedback etc, each group finalizes the report and submits for grading. \n", - "\n", - " * Python is the default programming language, but feel free to use C/C++, Julia and/or Fortran or other programming languages. All source codes discussed during the lectures can be found at the webpage and [github address](https://github.com/CompPhysics/MachineLearning/tree/master/doc/Programs) of the course." - ] - }, - { - "cell_type": "markdown", - "id": "61ff07a3", - "metadata": { - "editable": true - }, - "source": [ - "## Teachers\n", - "\n", - "* Morten Hjorth-Jensen, morten.hjorth-jensen@fys.uio.no\n", - "\n", - " * **Phone**: +47-48257387\n", - "\n", - " * **Office**: Department of Physics, University of Oslo, Eastern wing, room FØ470 \n", - "\n", - " * **Office hours**: *Anytime*! Individual or group office hours can be arranged either in person or via zoom. Feel free to send an email for planning. \n", - "\n", - "* Ida Torkjellsdatter Storehaug, i.t.storehaug@fys.uio.no\n", - "\n", - "* Fahimeh Najafi, fahimeh.najafi@fys.uio.no\n", - "\n", - "* Mia-Katrin Ose Kvalsund, m.k.o.kvalsund@fys.uio.no\n", - "\n", - "* Karl Henrik Fredly, k.h.fredly@fys.uio.no\n", - "\n", - "* Adam Jakobsen, adam.jakobsen@fys.uio.no\n", - "\n", - "* Daniel Haas Beccatini Lima, d.h.b.lima@fys.uio.no" - ] - }, - { - "cell_type": "markdown", - "id": "afa7d17c", - "metadata": { - "editable": true - }, - "source": [ - "## Deadlines for projects (tentative)\n", - "\n", - "1. Project 1: October 9 (available September 4) graded with feedback)\n", - "\n", - "2. Project 2: November 6 (available October 6, graded with feedback)\n", - "\n", - "3. Project 3: December 11 (available November 10, graded with feedback)\n", - "\n", - "Extra Credit (not mandatory), weekly exercise assignments, 10 in total (due Friday same week), 10% additional score. The extra credit assignments are due each Friday and can be uploaed to **Canvas** in your preferred format (although we prefer jupyter-notebooks). First assignment is for week 35. Each weekly exercise set counts 1%." - ] - }, - { - "cell_type": "markdown", - "id": "37a46b20", - "metadata": { - "editable": true - }, - "source": [ - "## Grading\n", - "\n", - "Grades are awarded on a scale from A to F, where A is the best grade and F is a fail. There are three projects which are graded and each project counts 1/3 of the final grade. The total score is thus the average from all three projects.\n", - "\n", - "The final number of points is based on the average of all projects and the grade follows the following table:\n", - "\n", - " * 92-100 points: A\n", - "\n", - " * 77-91 points: B\n", - "\n", - " * 58-76 points: C\n", - "\n", - " * 46-57 points: D\n", - "\n", - " * 40-45 points: E\n", - "\n", - " * 0-39 points: F-failed\n", - "\n", - "In addition you can get an extra 10% score for weekly assignments (10 in total and due each Friday). Each weekly assignment counts 1%." - ] - }, - { - "cell_type": "markdown", - "id": "40b50d78", - "metadata": { - "editable": true - }, - "source": [ - "## Reading material\n", - "\n", - "The lecture notes are collected as a jupyter-book at .\n", - "\n", - "In addition to the lecture notes, we recommend the books of Bishop, Hastie et al, Murphy and Goodfellow et al. We will follow these texts closely and the weekly reading assignments refer to these texts. The text by Hastie et al is also widely used in the Machine Learning community. Finally, we also recommend the hands-on text by Geron, see next slide for links." - ] - }, - { - "cell_type": "markdown", - "id": "1ac7f5fa", - "metadata": { - "editable": true - }, - "source": [ - "## Textbooks\n", - "\n", - "* [Goodfellow, Bengio, and Courville (GBC), Deep Learning](https://www.deeplearningbook.org/)\n", - "\n", - "* Christopher M. Bishop (CB), Pattern Recognition and Machine Learning\n", - "\n", - "* [Hastie, Tibshirani, and Friedman (HTF), The Elements of Statistical Learning, Springer](https://www.springer.com/gp/book/9780387848570).\n", - "\n", - "* [Aurelien Geron (AG), Hands‑On Machine Learning with Scikit‑Learn and TensorFlow, O'Reilly](https://www.oreilly.com/library/view/hands-on-machine-learning/9781492032632/). This text is very useful since it contains many code examples and hands-on applications of all algorithms discussed in this course.\n", - "\n", - "* [Kevin Murphy (KM), Probabilistic Machine Learning, an Introduction](https://probml.github.io/pml-book/book1.html)" - ] - }, - { - "cell_type": "markdown", - "id": "c74dc137", - "metadata": { - "editable": true - }, - "source": [ - "## Reading suggestions week 34\n", - "\n", - "This week: Refresh linear algebra, GBC chapters 1 and 2. HTF chapters 2 and 3. Install scikit-learn. See lecture notes for week 34 at (these notes)." - ] - }, - { - "cell_type": "markdown", - "id": "6af0d013", - "metadata": { - "editable": true - }, - "source": [ - "## Prerequisites\n", - "\n", - "Basic knowledge in programming and mathematics, with an emphasis on\n", - "linear algebra. Knowledge of Python or/and C++ as programming\n", - "languages is strongly recommended and experience with Jupiter notebook\n", - "is recommended. Required courses are the equivalents to the University\n", - "of Oslo mathematics courses MAT1100, MAT1110, MAT1120 and at least one\n", - "of the corresponding computing and programming courses INF1000/INF1110\n", - "or MAT-INF1100/MAT-INF1100L/BIOS1100/KJM-INF1100. Most universities\n", - "offer nowadays a basic programming course (often compulsory) where\n", - "Python is the recurring programming language." - ] - }, - { - "cell_type": "markdown", - "id": "628fb74c", - "metadata": { - "editable": true - }, - "source": [ - "## Topics covered in this course: Statistical analysis and optimization of data\n", - "\n", - "The course has two central parts\n", - "\n", - "1. Statistical analysis and optimization of data\n", - "\n", - "2. Machine learning\n", - "\n", - "These topics will be scattered thorughout the course and may not necessarily be taught separately. Rather, we will often take an approach (during the lectures and project/exercise sessions) where say elements from statistical data analysis are mixed with specific Machine Learning algorithms." - ] - }, - { - "cell_type": "markdown", - "id": "bcfe0b24", - "metadata": { - "editable": true - }, - "source": [ - "## Statistical analysis and optimization of data\n", - "\n", - "We plan to cover the following topics:\n", - "* Basic concepts, expectation values, variance, covariance, correlation functions and errors;\n", - "\n", - "* Simpler models, binomial distribution, the Poisson distribution, simple and multivariate normal distributions;\n", - "\n", - "* Central elements of Bayesian statistics and modeling;\n", - "\n", - "* Gradient methods for data optimization;\n", - "\n", - "* Monte Carlo methods, Markov chains, Gibbs sampling and Metropolis-Hastings sampling (tentative);\n", - "\n", - "* Estimation of errors and resampling techniques such as the cross-validation, blocking, bootstrapping and jackknife methods;\n", - "\n", - "* Principal Component Analysis (PCA) and its mathematical foundation;" - ] - }, - { - "cell_type": "markdown", - "id": "f153abef", - "metadata": { - "editable": true - }, - "source": [ - "## Machine Learning\n", - "\n", - "* Pre deep-learning revolution (2008 approx)\n", - "\n", - " * Linear Regression and Logistic Regression, classification and regression problems;\n", - "\n", - " * Bayesian linear and logistic regression, kernel regression;\n", - "\n", - " * Decisions trees, Random Forests, Bagging and Boosting methods;\n", - "\n", - " * Support vector machines (only survey);\n", - "\n", - " * Unsupervised learning and dimensionality reduction, from PCA to clustering; \n", - "\n", - "* Deep learning \n", - "\n", - " * Neural networks and deep learning;\n", - "\n", - " * Convolutional neural networks;\n", - "\n", - " * Recurrent neural networks;\n", - "\n", - " * Autoencoders\n", - "\n", - " * Generative methods with an emphasis on Boltzmann Machines, Variational Autoencoders and Generalized Adversarial Networks;\n", - "\n", - "Hands-on demonstrations, exercises and projects aim at deepening your understanding of these topics." - ] - }, - { - "cell_type": "markdown", - "id": "a6b0c4b8", - "metadata": { - "editable": true - }, - "source": [ - "## Extremely useful tools, strongly recommended\n", - "\n", - "**and discussed at the lab sessions.**\n", - "\n", - " * GIT for version control, and GitHub or GitLab as repositories, highly recommended. This will be discussed during the first exercise session\n", - "\n", - " * Anaconda and other Python environments, see intro slides and links to programming resources at " - ] - }, - { - "cell_type": "markdown", - "id": "48eb8817", - "metadata": { - "editable": true - }, - "source": [ - "## Other courses on Data science and Machine Learning at UiO\n", - "\n", - "* [FYS5419 Quantum Computing and Quantum Machine Learning](https://www.uio.no/studier/emner/matnat/fys/FYS5419/index-eng.html)\n", - "\n", - "* [FYS5429 Advanced Machine Learning for the Physical Sciences](https://www.uio.no/studier/emner/matnat/fys/FYS5429/index-eng.html)\n", - "\n", - "* [STK2100 Machine learning and statistical methods for prediction and classification](http://www.uio.no/studier/emner/matnat/math/STK2100/index-eng.html). \n", - "\n", - "* [IN3050/4050 Introduction to Artificial Intelligence and Machine Learning](https://www.uio.no/studier/emner/matnat/ifi/IN3050/index-eng.html). Introductory course in machine learning and AI with an algorithmic approach. \n", - "\n", - "* [STK-INF3000/4000 Selected Topics in Data Science](http://www.uio.no/studier/emner/matnat/math/STK-INF3000/index-eng.html). The course provides insight into selected contemporary relevant topics within Data Science. \n", - "\n", - "* [IN4080 Natural Language Processing](https://www.uio.no/studier/emner/matnat/ifi/IN4080/index.html). Probabilistic and machine learning techniques applied to natural language processing." - ] - }, - { - "cell_type": "markdown", - "id": "e8889321", - "metadata": { - "editable": true - }, - "source": [ - "## Other courses on Data science and Machine Learning at UiO, contn\n", - "\n", - "* [STK-IN4300 Statistical learning methods in Data Science](https://www.uio.no/studier/emner/matnat/math/STK-IN4300/index-eng.html). An advanced introduction to statistical and machine learning. For students with a good mathematics and statistics background.\n", - "\n", - "* [IN3310/4310 Deep Learnig for Image Analysis](https://www.uio.no/studier/emner/matnat/ifi/IN4310/index.html)\n", - "\n", - "* [STK4051 Computational Statistics](https://www.uio.no/studier/emner/matnat/math/STK4051/index-eng.html)\n", - "\n", - "* [STK4021 Applied Bayesian Analysis and Numerical Methods](https://www.uio.no/studier/emner/matnat/math/STK4021/index-eng.html)" - ] - }, - { - "cell_type": "markdown", - "id": "4ad1f253", - "metadata": { - "editable": true - }, - "source": [ - "## Learning outcomes\n", - "\n", - "This course aims at giving you insights and knowledge about many of\n", - "the central algorithms used in Data Analysis and Machine Learning.\n", - "The course is project based and through various numerical projects,\n", - "normally three, you will be exposed to fundamental research problems\n", - "in these fields, with the aim to reproduce state of the art scientific\n", - "results. Both supervised and unsupervised methods will be covered. The\n", - "emphasis is on a frequentist approach, although we will try to link it\n", - "with a Bayesian approach as well. You will learn to develop and\n", - "structure large codes for studying different cases where Machine\n", - "Learning is applied to, get acquainted with computing facilities and\n", - "learn to handle large scientific projects. A good scientific and\n", - "ethical conduct is emphasized throughout the course. More\n", - "specifically, after this course you will\n", - "\n", - "* Learn about basic data analysis, statistical analysis, Bayesian statistics, Monte Carlo sampling, data optimization and machine learning;\n", - "\n", - "* Be capable of extending the acquired knowledge to other systems and cases;\n", - "\n", - "* Have an understanding of central algorithms used in data analysis and machine learning;\n", - "\n", - "* Understand linear methods for regression and classification, from ordinary least squares, via Lasso and Ridge to Logistic regression;\n", - "\n", - "* Learn about neural networks and deep learning methods for supervised and unsupervised learning. Emphasis on feed forward neural networks, convolutional and recurrent neural networks; \n", - "\n", - "* Learn about about decision trees, random forests, bagging and boosting methods;\n", - "\n", - "* Learn about support vector machines and kernel transformations;\n", - "\n", - "* Reduction of data sets, from PCA to clustering;\n", - "\n", - "* Generative models\n", - "\n", - "* Work on numerical projects to illustrate the theory. The projects play a central role and you are expected to know modern programming languages like Python or C++ and/or Fortran (Fortran2003 or later) or Julia or other." - ] - }, - { - "cell_type": "markdown", - "id": "ed3eddab", - "metadata": { - "editable": true - }, - "source": [ - "## Introduction\n", - "\n", - "Our emphasis throughout this series of lectures \n", - "is on understanding the mathematical aspects of\n", - "different algorithms used in the fields of data analysis and machine learning. \n", - "\n", - "However, where possible we will emphasize the\n", - "importance of using available software. We start thus with a hands-on\n", - "and top-down approach to machine learning. The aim is thus to start with\n", - "relevant data or data we have produced \n", - "and use these to introduce statistical data analysis\n", - "concepts and machine learning algorithms before we delve into the\n", - "algorithms themselves. The examples we will use in the beginning, start with simple\n", - "polynomials with random noise added. We will use the Python\n", - "software package [Scikit-Learn](http://scikit-learn.org/stable/) and\n", - "introduce various machine learning algorithms to make fits of\n", - "the data and predictions. We move thereafter to more interesting\n", - "cases such as data from say experiments (below we will look at experimental nuclear binding energies as an example).\n", - "These are examples where we can easily set up the data and\n", - "then use machine learning algorithms included in for example\n", - "**Scikit-Learn**. \n", - "\n", - "These examples will serve us the purpose of getting\n", - "started. Furthermore, they allow us to catch more than two birds with\n", - "a stone. They will allow us to bring in some programming specific\n", - "topics and tools as well as showing the power of various Python \n", - "libraries for machine learning and statistical data analysis. \n", - "\n", - "Although we have projects where you write your own codes, we will also focus on two\n", - "specific Python packages for Machine Learning, Scikit-Learn and\n", - "Tensorflow with Keras (see below for links etc). Moreover, the examples we\n", - "introduce will serve as inputs to many of our discussions later, as\n", - "well as allowing you to set up models and produce your own data and\n", - "get started with programming." - ] - }, - { - "cell_type": "markdown", - "id": "cd6f4f41", - "metadata": { - "editable": true - }, - "source": [ - "## AI/ML and some statements you may have heard (and what do they mean?)\n", - "\n", - "1. Fei-Fei Li on ImageNet: **map out the entire world of objects** ([The data that transformed AI research](https://cacm.acm.org/news/219702-the-data-that-transformed-ai-research-and-possibly-the-world/fulltext))\n", - "\n", - "2. Russell and Norvig in their popular textbook: **relevant to any intellectual task; it is truly a universal field** ([Artificial Intelligence, A modern approach](http://aima.cs.berkeley.edu/))\n", - "\n", - "3. Woody Bledsoe puts it more bluntly: **in the long run, AI is the only science** (quoted in Pamilla McCorduck, [Machines who think](https://www.pamelamccorduck.com/machines-who-think))\n", - "\n", - "If you wish to have a critical read on AI/ML from a societal point of view, see [Kate Crawford's recent text Atlas of AI](https://www.katecrawford.net/)\n", - "\n", - "**Here: with AI/ML we intend a collection of machine learning methods with an emphasis on statistical learning and data analysis**" - ] - }, - { - "cell_type": "markdown", - "id": "9bc6760a", - "metadata": { - "editable": true - }, - "source": [ - "## What is Machine Learning?\n", - "\n", - "Statistics, data science and machine learning form important fields of\n", - "research in modern science. They describe how to learn and make\n", - "predictions from data, as well as allowing us to extract important\n", - "correlations about physical process and the underlying laws of motion\n", - "in large data sets. The latter, big data sets, appear frequently in\n", - "essentially all disciplines, from the traditional Science, Technology,\n", - "Mathematics and Engineering fields to Life Science, Law, education\n", - "research, the Humanities and the Social Sciences. \n", - "\n", - "It has become more\n", - "and more common to see research projects on big data in for example\n", - "the Social Sciences where extracting patterns from complicated survey\n", - "data is one of many research directions. Having a solid grasp of data\n", - "analysis and machine learning is thus becoming central to scientific\n", - "computing in many fields, and competences and skills within the fields\n", - "of machine learning and scientific computing are nowadays strongly\n", - "requested by many potential employers. The latter cannot be\n", - "overstated, familiarity with machine learning has almost become a\n", - "prerequisite for many of the most exciting employment opportunities,\n", - "whether they are in bioinformatics, life science, physics or finance,\n", - "in the private or the public sector. This author has had several\n", - "students or met students who have been hired recently based on their\n", - "skills and competences in scientific computing and data science, often\n", - "with marginal knowledge of machine learning.\n", - "\n", - "Machine learning is a subfield of computer science, and is closely\n", - "related to computational statistics. It evolved from the study of\n", - "pattern recognition in artificial intelligence (AI) research, and has\n", - "made contributions to AI tasks like computer vision, natural language\n", - "processing and speech recognition. Many of the methods we will study are also \n", - "strongly rooted in basic mathematics and physics research. \n", - "\n", - "Ideally, machine learning represents the science of giving computers\n", - "the ability to learn without being explicitly programmed. The idea is\n", - "that there exist generic algorithms which can be used to find patterns\n", - "in a broad class of data sets without having to write code\n", - "specifically for each problem. The algorithm will build its own logic\n", - "based on the data. You should however always keep in mind that\n", - "machines and algorithms are to a large extent developed by humans. The\n", - "insights and knowledge we have about a specific system, play a central\n", - "role when we develop a specific machine learning algorithm. \n", - "\n", - "Machine learning is an extremely rich field, in spite of its young\n", - "age. The increases we have seen during the last three decades in\n", - "computational capabilities have been followed by developments of\n", - "methods and techniques for analyzing and handling large date sets,\n", - "relying heavily on statistics, computer science and mathematics. The\n", - "field is rather new and developing rapidly. Popular software packages\n", - "written in Python for machine learning like\n", - "[Scikit-learn](http://scikit-learn.org/stable/),\n", - "[Tensorflow](https://www.tensorflow.org/),\n", - "[PyTorch](http://pytorch.org/) and [Keras](https://keras.io/), all\n", - "freely available at their respective GitHub sites, encompass\n", - "communities of developers in the thousands or more. And the number of\n", - "code developers and contributors keeps increasing. Not all the\n", - "algorithms and methods can be given a rigorous mathematical\n", - "justification, opening up thereby large rooms for experimenting and\n", - "trial and error and thereby exciting new developments. However, a\n", - "solid command of linear algebra, multivariate theory, probability\n", - "theory, statistical data analysis, understanding errors and Monte\n", - "Carlo methods are central elements in a proper understanding of many\n", - "of algorithms and methods we will discuss." - ] - }, - { - "cell_type": "markdown", - "id": "17c6257a", - "metadata": { - "editable": true - }, - "source": [ - "## Types of Machine Learning\n", - "\n", - "The approaches to machine learning are many, but are often split into\n", - "two main categories. In *supervised learning* we know the answer to a\n", - "problem, and let the computer deduce the logic behind it. On the other\n", - "hand, *unsupervised learning* is a method for finding patterns and\n", - "relationship in data sets without any prior knowledge of the system.\n", - "Some authours also operate with a third category, namely\n", - "*reinforcement learning*. This is a paradigm of learning inspired by\n", - "behavioral psychology, where learning is achieved by trial-and-error,\n", - "solely from rewards and punishment.\n", - "\n", - "Another way to categorize machine learning tasks is to consider the\n", - "desired output of a system. Some of the most common tasks are:\n", - "\n", - " * Classification: Outputs are divided into two or more classes. The goal is to produce a model that assigns inputs into one of these classes. An example is to identify digits based on pictures of hand-written ones. Classification is typically supervised learning.\n", - "\n", - " * Regression: Finding a functional relationship between an input data set and a reference data set. The goal is to construct a function that maps input data to continuous output values.\n", - "\n", - " * Clustering: Data are divided into groups with certain common traits, without knowing the different groups beforehand. It is thus a form of unsupervised learning." - ] - }, - { - "cell_type": "markdown", - "id": "9f4e80cf", - "metadata": { - "editable": true - }, - "source": [ - "## Essential elements of ML\n", - "\n", - "The methods we cover have three main topics in common, irrespective of\n", - "whether we deal with supervised or unsupervised learning.\n", - "* The first ingredient is normally our data set (which can be subdivided into training, validation and test data). Many find the most difficult part of using Machine Learning to be the set up of your data in a meaningful way. \n", - "\n", - "* The second item is a model which is normally a function of some parameters. The model reflects our knowledge of the system (or lack thereof). As an example, if we know that our data show a behavior similar to what would be predicted by a polynomial, fitting our data to a polynomial of some degree would then determin our model. \n", - "\n", - "* The last ingredient is a so-called **cost/loss** function (or error or risk function) which allows us to present an estimate on how good our model is in reproducing the data it is supposed to train." - ] - }, - { - "cell_type": "markdown", - "id": "828f3ad9", - "metadata": { - "editable": true - }, - "source": [ - "## An optimization/minimization problem\n", - "\n", - "At the heart of basically all Machine Learning algorithms we will encounter so-called minimization or optimization algorithms. A large family of such methods are so-called **gradient methods**." - ] - }, - { - "cell_type": "markdown", - "id": "8b12df05", - "metadata": { - "editable": true - }, - "source": [ - "## A Frequentist approach to data analysis\n", - "\n", - "When you hear phrases like **predictions and estimations** and\n", - "**correlations and causations**, what do you think of? May be you think\n", - "of the difference between classifying new data points and generating\n", - "new data points.\n", - "Or perhaps you consider that correlations represent some kind of symmetric statements like\n", - "if $A$ is correlated with $B$, then $B$ is correlated with\n", - "$A$. Causation on the other hand is directional, that is if $A$ causes $B$, $B$ does not\n", - "necessarily cause $A$.\n", - "\n", - "These concepts are in some sense the difference between machine\n", - "learning and statistics. In machine learning and prediction based\n", - "tasks, we are often interested in developing algorithms that are\n", - "capable of learning patterns from given data in an automated fashion,\n", - "and then using these learned patterns to make predictions or\n", - "assessments of newly given data. In many cases, our primary concern\n", - "is the quality of the predictions or assessments, and we are less\n", - "concerned about the underlying patterns that were learned in order\n", - "to make these predictions.\n", - "\n", - "In machine learning we normally use [a so-called frequentist approach](https://en.wikipedia.org/wiki/Frequentist_inference),\n", - "where the aim is to make predictions and find correlations. We focus\n", - "less on for example extracting a probability distribution function (PDF). The PDF can be\n", - "used in turn to make estimations and find causations such as given $A$\n", - "what is the likelihood of finding $B$." - ] - }, - { - "cell_type": "markdown", - "id": "6656791e", - "metadata": { - "editable": true - }, - "source": [ - "## What is a good model?\n", - "\n", - "In science and engineering we often end up in situations where we want to infer (or learn) a\n", - "quantitative model $M$ for a given set of sample points $\\boldsymbol{X} \\in [x_1, x_2,\\dots x_N]$.\n", - "\n", - "As we will see repeatedely in these lectures, we could try to fit these data points to a model given by a\n", - "straight line, or if we wish to be more sophisticated to a more complex\n", - "function.\n", - "\n", - "The reason for inferring such a model is that it\n", - "serves many useful purposes. On the one hand, the model can reveal information\n", - "encoded in the data or underlying mechanisms from which the data were generated. For instance, we could discover important\n", - "corelations that relate interesting physics interpretations.\n", - "\n", - "In addition, it can simplify the representation of the given data set and help\n", - "us in making predictions about future data samples.\n", - "\n", - "A first important consideration to keep in mind is that inferring the *correct* model\n", - "for a given data set is an elusive, if not impossible, task. The fundamental difficulty\n", - "is that if we are not specific about what we mean by a *correct* model, there\n", - "could easily be many different models that fit the given data set *equally well*." - ] - }, - { - "cell_type": "markdown", - "id": "85f146c9", - "metadata": { - "editable": true - }, - "source": [ - "## What is a good model? Can we define it?\n", - "\n", - "The central question is this: what leads us to say that a model is correct or\n", - "optimal for a given data set? To make the model inference problem well posed, i.e.,\n", - "to guarantee that there is a unique optimal model for the given data, we need to\n", - "impose additional assumptions or restrictions on the class of models considered. To\n", - "this end, we should not be looking for just any model that can describe the data.\n", - "Instead, we should look for a **model** $M$ that is the best among a restricted class\n", - "of models. In addition, to make the model inference problem computationally\n", - "tractable, we need to specify how restricted the class of models needs to be. A\n", - "common strategy is to start \n", - "with the simplest possible class of models that is just necessary to describe the data\n", - "or solve the problem at hand. More precisely, the model class should be rich enough\n", - "to contain at least one model that can fit the data to a desired accuracy and yet be\n", - "restricted enough that it is relatively simple to find the best model for the given data.\n", - "\n", - "Thus, the most popular strategy is to start from the\n", - "simplest class of models and increase the complexity of the models only when the\n", - "simpler models become inadequate. For instance, if we work with a regression problem to fit a set of sample points, one\n", - "may first try the simplest class of models, namely linear models, followed obviously by more complex models.\n", - "\n", - "How to evaluate which model fits best the data is something we will come back to over and over again in these sets of lectures." - ] - }, - { - "cell_type": "markdown", - "id": "51f73840", - "metadata": { - "editable": true - }, - "source": [ - "## Software and needed installations\n", - "\n", - "We will make extensive use of Python as programming language and its\n", - "myriad of available libraries. You will find\n", - "Jupyter notebooks invaluable in your work. You can run **R**\n", - "codes in the Jupyter/IPython notebooks, with the immediate benefit of\n", - "visualizing your data. You can also use compiled languages like C++,\n", - "Rust, Julia, Fortran etc if you prefer. The focus in these lectures will be\n", - "on Python.\n", - "\n", - "If you have Python installed (we strongly recommend Python3) and you feel\n", - "pretty familiar with installing different packages, we recommend that\n", - "you install the following Python packages via **pip** as \n", - "\n", - "1. pip install numpy scipy matplotlib ipython scikit-learn mglearn sympy pandas pillow \n", - "\n", - "For Python3, replace **pip** with **pip3**.\n", - "\n", - "For OSX users we recommend, after having installed Xcode, to\n", - "install **brew**. Brew allows for a seamless installation of additional\n", - "software via for example \n", - "\n", - "1. brew install python3\n", - "\n", - "For Linux users, with its variety of distributions like for example the widely popular Ubuntu distribution,\n", - "you can use **pip** as well and simply install Python as \n", - "\n", - "1. sudo apt-get install python3 (or python for pyhton2.7)\n", - "\n", - "etc etc." - ] - }, - { - "cell_type": "markdown", - "id": "404f8680", - "metadata": { - "editable": true - }, - "source": [ - "## Python installers\n", - "\n", - "If you don't want to perform these operations separately and venture\n", - "into the hassle of exploring how to set up dependencies and paths, we\n", - "recommend two widely used distrubutions which set up all relevant\n", - "dependencies for Python, namely \n", - "\n", - "* [Anaconda](https://docs.anaconda.com/), \n", - "\n", - "which is an open source\n", - "distribution of the Python and R programming languages for large-scale\n", - "data processing, predictive analytics, and scientific computing, that\n", - "aims to simplify package management and deployment. Package versions\n", - "are managed by the package management system **conda**. \n", - "\n", - "* [Enthought canopy](https://www.enthought.com/product/canopy/) \n", - "\n", - "is a Python\n", - "distribution for scientific and analytic computing distribution and\n", - "analysis environment, available for free and under a commercial\n", - "license.\n", - "\n", - "Furthermore, [Google's Colab](https://colab.research.google.com/notebooks/welcome.ipynb) is a free Jupyter notebook environment that requires \n", - "no setup and runs entirely in the cloud. Try it out!" - ] - }, - { - "cell_type": "markdown", - "id": "1b74192a", - "metadata": { - "editable": true - }, - "source": [ - "## Useful Python libraries\n", - "Here we list several useful Python libraries we strongly recommend (if you use anaconda many of these are already there)\n", - "\n", - "* [NumPy](https://www.numpy.org/) is a highly popular library for large, multi-dimensional arrays and matrices, along with a large collection of high-level mathematical functions to operate on these arrays\n", - "\n", - "* [The pandas](https://pandas.pydata.org/) library provides high-performance, easy-to-use data structures and data analysis tools \n", - "\n", - "* [Xarray](http://xarray.pydata.org/en/stable/) is a Python package that makes working with labelled multi-dimensional arrays simple, efficient, and fun!\n", - "\n", - "* [Scipy](https://www.scipy.org/) (pronounced “Sigh Pie”) is a Python-based ecosystem of open-source software for mathematics, science, and engineering. \n", - "\n", - "* [Matplotlib](https://matplotlib.org/) is a Python 2D plotting library which produces publication quality figures in a variety of hardcopy formats and interactive environments across platforms.\n", - "\n", - "* [Autograd](https://github.com/HIPS/autograd) can automatically differentiate native Python and Numpy code. It can handle a large subset of Python's features, including loops, ifs, recursion and closures, and it can even take derivatives of derivatives of derivatives\n", - "\n", - "* [JAX](https://jax.readthedocs.io/en/latest/index.html) has now more or less replaced **Autograd**. JAX is Autograd and XLA, brought together for high-performance numerical computing and machine learning research. It provides composable transformations of Python+NumPy programs: differentiate, vectorize, parallelize, Just-In-Time compile to GPU/TPU, and more.\n", - "\n", - "* [SymPy](https://www.sympy.org/en/index.html) is a Python library for symbolic mathematics. \n", - "\n", - "* [scikit-learn](https://scikit-learn.org/stable/) has simple and efficient tools for machine learning, data mining and data analysis\n", - "\n", - "* [TensorFlow](https://www.tensorflow.org/) is a Python library for fast numerical computing created and released by Google\n", - "\n", - "* [Keras](https://keras.io/) is a high-level neural networks API, written in Python and capable of running on top of TensorFlow, CNTK, or Theano\n", - "\n", - "* And many more such as [pytorch](https://pytorch.org/), [Theano](https://pypi.org/project/Theano/) etc" - ] - }, - { - "cell_type": "markdown", - "id": "32b6b09c", - "metadata": { - "editable": true - }, - "source": [ - "## Installing R, C++, cython or Julia\n", - "\n", - "You will also find it convenient to utilize **R**. We will mainly\n", - "use Python during our lectures and in various projects and exercises.\n", - "Those of you\n", - "already familiar with **R** should feel free to continue using **R**, keeping\n", - "however an eye on the parallel Python set ups. Similarly, if you are a\n", - "Python afecionado, feel free to explore **R** as well. Jupyter(Julia, Python and R) /Ipython\n", - "notebook allows you to run **R** codes and **Julia** codes interactively in your\n", - "browser. The software library **R** is really tailored for statistical data analysis\n", - "and allows for an easy usage of the tools and algorithms we will discuss in these\n", - "lectures.\n", - "\n", - "To install **R** with Jupyter notebook \n", - "[follow the link here](https://mpacer.org/maths/r-kernel-for-ipython-notebook)" - ] - }, - { - "cell_type": "markdown", - "id": "0c8344b1", - "metadata": { - "editable": true - }, - "source": [ - "## Installing R, C++, cython, Numba etc\n", - "\n", - "For the C++ aficionados, Jupyter/IPython notebook allows you also to\n", - "install C++ and run codes written in this language interactively in\n", - "the browser. Since we will emphasize writing many of the algorithms\n", - "yourself, you can thus opt for either Python or C++ (or Fortran or other compiled languages) as programming\n", - "languages.\n", - "\n", - "To add more entropy, **cython** can also be used when running your\n", - "notebooks. It means that Python with the jupyter notebook\n", - "setup allows you to integrate widely popular softwares and tools for\n", - "scientific computing. Similarly, the \n", - "[Numba Python package](https://numba.pydata.org/) delivers increased performance\n", - "capabilities with minimal rewrites of your codes. With its\n", - "versatility, including symbolic operations, Python offers a unique\n", - "computational environment. Your jupyter notebook can easily be\n", - "converted into a nicely rendered **PDF** file or a Latex file for\n", - "further processing. For example, convert to latex as" - ] - }, - { - "cell_type": "markdown", - "id": "40a41b04", - "metadata": { - "editable": true - }, - "source": [ - " pycod jupyter nbconvert filename.ipynb --to latex \n" - ] - }, - { - "cell_type": "markdown", - "id": "367b0b81", - "metadata": { - "editable": true - }, - "source": [ - "And to add more versatility, the Python package [SymPy](http://www.sympy.org/en/index.html) is a Python library for symbolic mathematics. It aims to become a full-featured computer algebra system (CAS) and is entirely written in Python. \n", - "\n", - "Finally, we recommend strongly using Autograd or JAX for automatic differentiation." - ] - }, - { - "cell_type": "markdown", - "id": "e16a079a", - "metadata": { - "editable": true - }, - "source": [ - "## Numpy examples and Important Matrix and vector handling packages\n", - "\n", - "There are several central software libraries for linear algebra and eigenvalue problems. Several of the more\n", - "popular ones have been wrapped into ofter software packages like those from the widely used text **Numerical Recipes**. The original source codes in many of the available packages are often taken from the widely used\n", - "software package LAPACK, which follows two other popular packages\n", - "developed in the 1970s, namely EISPACK and LINPACK. We describe them shortly here.\n", - "\n", - " * LINPACK: package for linear equations and least square problems.\n", - "\n", - " * LAPACK:package for solving symmetric, unsymmetric and generalized eigenvalue problems. From LAPACK's website it is possible to download for free all source codes from this library. Both C/C++ and Fortran versions are available.\n", - "\n", - " * BLAS (I, II and III): (Basic Linear Algebra Subprograms) are routines that provide standard building blocks for performing basic vector and matrix operations. Blas I is vector operations, II vector-matrix operations and III matrix-matrix operations. Highly parallelized and efficient codes, all available for download from ." - ] - }, - { - "cell_type": "markdown", - "id": "244cc56a", - "metadata": { - "editable": true - }, - "source": [ - "## Numpy and arrays\n", - "[Numpy](http://www.numpy.org/) provides an easy way to handle arrays in Python. The standard way to import this library is as" - ] - }, - { - "cell_type": "code", - "execution_count": 1, - "id": "1d8845bb", - "metadata": { - "collapsed": false, - "editable": true - }, - "outputs": [], - "source": [ - "import numpy as np" - ] - }, - { - "cell_type": "markdown", - "id": "a339aed7", - "metadata": { - "editable": true - }, - "source": [ - "Here follows a simple example where we set up an array of ten elements, all determined by random numbers drawn according to the normal distribution," - ] - }, - { - "cell_type": "code", - "execution_count": 2, - "id": "ce4b3b4e", - "metadata": { - "collapsed": false, - "editable": true - }, - "outputs": [], - "source": [ - "n = 10\n", - "x = np.random.normal(size=n)\n", - "print(x)" - ] - }, - { - "cell_type": "markdown", - "id": "307170c5", - "metadata": { - "editable": true - }, - "source": [ - "We defined a vector $x$ with $n=10$ elements with its values given by the Normal distribution $N(0,1)$.\n", - "Another alternative is to declare a vector as follows" - ] - }, - { - "cell_type": "code", - "execution_count": 3, - "id": "ea4fd74f", - "metadata": { - "collapsed": false, - "editable": true - }, - "outputs": [], - "source": [ - "import numpy as np\n", - "x = np.array([1, 2, 3])\n", - "print(x)" - ] - }, - { - "cell_type": "markdown", - "id": "6428f55d", - "metadata": { - "editable": true - }, - "source": [ - "Here we have defined a vector with three elements, with $x_0=1$, $x_1=2$ and $x_2=3$. Note that both Python and C++\n", - "start numbering array elements from $0$ and on. This means that a vector with $n$ elements has a sequence of entities $x_0, x_1, x_2, \\dots, x_{n-1}$. We could also let (recommended) Numpy to compute the logarithms of a specific array as" - ] - }, - { - "cell_type": "code", - "execution_count": 4, - "id": "84e4a8fc", - "metadata": { - "collapsed": false, - "editable": true - }, - "outputs": [], - "source": [ - "import numpy as np\n", - "x = np.log(np.array([4, 7, 8]))\n", - "print(x)" - ] - }, - { - "cell_type": "markdown", - "id": "39bd657f", - "metadata": { - "editable": true - }, - "source": [ - "In the last example we used Numpy's unary function $np.log$. This function is\n", - "highly tuned to compute array elements since the code is vectorized\n", - "and does not require looping. We normaly recommend that you use the\n", - "Numpy intrinsic functions instead of the corresponding **log** function\n", - "from Python's **math** module. The looping is done explicitely by the\n", - "**np.log** function. The alternative, and slower way to compute the\n", - "logarithms of a vector would be to write" - ] - }, - { - "cell_type": "code", - "execution_count": 5, - "id": "e5a5fe48", - "metadata": { - "collapsed": false, - "editable": true - }, - "outputs": [], - "source": [ - "import numpy as np\n", - "from math import log\n", - "x = np.array([4, 7, 8])\n", - "for i in range(0, len(x)):\n", - " x[i] = log(x[i])\n", - "print(x)" - ] - }, - { - "cell_type": "markdown", - "id": "d74eb874", - "metadata": { - "editable": true - }, - "source": [ - "We note that our code is much longer already and we need to import the **log** function from the **math** module. \n", - "The attentive reader will also notice that the output is $[1, 1, 2]$. Python interprets automagically our numbers as integers (like the **automatic** keyword in C++). To change this we could define our array elements to be double precision numbers as" - ] - }, - { - "cell_type": "code", - "execution_count": 6, - "id": "1d657e01", - "metadata": { - "collapsed": false, - "editable": true - }, - "outputs": [], - "source": [ - "import numpy as np\n", - "x = np.log(np.array([4, 7, 8], dtype = np.float64))\n", - "print(x)" - ] - }, - { - "cell_type": "markdown", - "id": "7f82621e", - "metadata": { - "editable": true - }, - "source": [ - "or simply write them as double precision numbers (Python uses 64 bits as default for floating point type variables), that is" - ] - }, - { - "cell_type": "code", - "execution_count": 7, - "id": "c4a5e02b", - "metadata": { - "collapsed": false, - "editable": true - }, - "outputs": [], - "source": [ - "import numpy as np\n", - "x = np.log(np.array([4.0, 7.0, 8.0]))\n", - "print(x)" - ] - }, - { - "cell_type": "markdown", - "id": "3af71bb0", - "metadata": { - "editable": true - }, - "source": [ - "To check the number of bytes (remember that one byte contains eight bits for double precision variables), you can use simple use the **itemsize** functionality (the array $x$ is actually an object which inherits the functionalities defined in Numpy) as" - ] - }, - { - "cell_type": "code", - "execution_count": 8, - "id": "5cf0baf0", - "metadata": { - "collapsed": false, - "editable": true - }, - "outputs": [], - "source": [ - "import numpy as np\n", - "x = np.log(np.array([4.0, 7.0, 8.0]))\n", - "print(x.itemsize)" - ] - }, - { - "cell_type": "markdown", - "id": "a70a4db0", - "metadata": { - "editable": true - }, - "source": [ - "## Matrices in Python\n", - "\n", - "Having defined vectors, we are now ready to try out matrices. We can\n", - "define a $3 \\times 3 $ real matrix $\\boldsymbol{A}$ as (recall that we user\n", - "lowercase letters for vectors and uppercase letters for matrices)" - ] - }, - { - "cell_type": "code", - "execution_count": 9, - "id": "262e8f46", - "metadata": { - "collapsed": false, - "editable": true - }, - "outputs": [], - "source": [ - "import numpy as np\n", - "A = np.log(np.array([ [4.0, 7.0, 8.0], [3.0, 10.0, 11.0], [4.0, 5.0, 7.0] ]))\n", - "print(A)" - ] - }, - { - "cell_type": "markdown", - "id": "0f43d9cd", - "metadata": { - "editable": true - }, - "source": [ - "If we use the **shape** function we would get $(3, 3)$ as output, that is verifying that our matrix is a $3\\times 3$ matrix. We can slice the matrix and print for example the first column (Python organized matrix elements in a row-major order, see below) as" - ] - }, - { - "cell_type": "code", - "execution_count": 10, - "id": "f12d591b", - "metadata": { - "collapsed": false, - "editable": true - }, - "outputs": [], - "source": [ - "import numpy as np\n", - "A = np.log(np.array([ [4.0, 7.0, 8.0], [3.0, 10.0, 11.0], [4.0, 5.0, 7.0] ]))\n", - "# print the first column, row-major order and elements start with 0\n", - "print(A[:,0])" - ] - }, - { - "cell_type": "markdown", - "id": "7c1cc7ed", - "metadata": { - "editable": true - }, - "source": [ - "We can continue this was by printing out other columns or rows. The example here prints out the second column" - ] - }, - { - "cell_type": "code", - "execution_count": 11, - "id": "1f365f00", - "metadata": { - "collapsed": false, - "editable": true - }, - "outputs": [], - "source": [ - "import numpy as np\n", - "A = np.log(np.array([ [4.0, 7.0, 8.0], [3.0, 10.0, 11.0], [4.0, 5.0, 7.0] ]))\n", - "# print the first column, row-major order and elements start with 0\n", - "print(A[1,:])" - ] - }, - { - "cell_type": "markdown", - "id": "d5cf7244", - "metadata": { - "editable": true - }, - "source": [ - "Numpy contains many other functionalities that allow us to slice, subdivide etc etc arrays. We strongly recommend that you look up the [Numpy website for more details](http://www.numpy.org/). Useful functions when defining a matrix are the **np.zeros** function which declares a matrix of a given dimension and sets all elements to zero" - ] - }, - { - "cell_type": "code", - "execution_count": 12, - "id": "907260e4", - "metadata": { - "collapsed": false, - "editable": true - }, - "outputs": [], - "source": [ - "import numpy as np\n", - "n = 10\n", - "# define a matrix of dimension 10 x 10 and set all elements to zero\n", - "A = np.zeros( (n, n) )\n", - "print(A)" - ] - }, - { - "cell_type": "markdown", - "id": "375e0579", - "metadata": { - "editable": true - }, - "source": [ - "or initializing all elements to" - ] - }, - { - "cell_type": "code", - "execution_count": 13, - "id": "79e19787", - "metadata": { - "collapsed": false, - "editable": true - }, - "outputs": [], - "source": [ - "import numpy as np\n", - "n = 10\n", - "# define a matrix of dimension 10 x 10 and set all elements to one\n", - "A = np.ones( (n, n) )\n", - "print(A)" - ] - }, - { - "cell_type": "markdown", - "id": "be6c16b2", - "metadata": { - "editable": true - }, - "source": [ - "or as unitarily distributed random numbers (see the material on random number generators in the statistics part)" - ] - }, - { - "cell_type": "code", - "execution_count": 14, - "id": "901ecfe2", - "metadata": { - "collapsed": false, - "editable": true - }, - "outputs": [], - "source": [ - "import numpy as np\n", - "n = 10\n", - "# define a matrix of dimension 10 x 10 and set all elements to random numbers with x \\in [0, 1]\n", - "A = np.random.rand(n, n)\n", - "print(A)" - ] - }, - { - "cell_type": "markdown", - "id": "be629f7b", - "metadata": { - "editable": true - }, - "source": [ - "As we will see throughout these lectures, there are several extremely useful functionalities in Numpy.\n", - "As an example, consider the discussion of the covariance matrix. Suppose we have defined three vectors\n", - "$\\boldsymbol{x}, \\boldsymbol{y}, \\boldsymbol{z}$ with $n$ elements each. The covariance matrix is defined as" - ] - }, - { - "cell_type": "markdown", - "id": "980cf441", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\boldsymbol{\\Sigma} = \\begin{bmatrix} \\sigma_{xx} & \\sigma_{xy} & \\sigma_{xz} \\\\\n", - " \\sigma_{yx} & \\sigma_{yy} & \\sigma_{yz} \\\\\n", - " \\sigma_{zx} & \\sigma_{zy} & \\sigma_{zz} \n", - " \\end{bmatrix},\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "d2ffe1f6", - "metadata": { - "editable": true - }, - "source": [ - "where for example" - ] - }, - { - "cell_type": "markdown", - "id": "4f4efdd4", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\sigma_{xy} =\\frac{1}{n} \\sum_{i=0}^{n-1}(x_i- \\overline{x})(y_i- \\overline{y}).\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "ee572849", - "metadata": { - "editable": true - }, - "source": [ - "The Numpy function **np.cov** calculates the covariance elements using the factor $1/(n-1)$ instead of $1/n$ since it assumes we do not have the exact mean values. \n", - "The following simple function uses the **np.vstack** function which takes each vector of dimension $1\\times n$ and produces a $3\\times n$ matrix $\\boldsymbol{W}$" - ] - }, - { - "cell_type": "markdown", - "id": "df0a5acc", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\boldsymbol{W} = \\begin{bmatrix} x_0 & x_1 & x_2 & \\dots & x_{n-2} & x_{n-1} \\\\\n", - " y_0 & y_1 & y_2 & \\dots & y_{n-2} & y_{n-1} \\\\\n", - "\t\t\t z_0 & z_1 & z_2 & \\dots & z_{n-2} & z_{n-1} \\\\\n", - " \\end{bmatrix},\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "7bc72a77", - "metadata": { - "editable": true - }, - "source": [ - "which in turn is converted into into the $3\\times 3$ covariance matrix\n", - "$\\boldsymbol{\\Sigma}$ via the Numpy function **np.cov()**. We note that we can also calculate\n", - "the mean value of each set of samples $\\boldsymbol{x}$ etc using the Numpy\n", - "function **np.mean(x)**. We can also extract the eigenvalues of the\n", - "covariance matrix through the **np.linalg.eig()** function." - ] - }, - { - "cell_type": "code", - "execution_count": 15, - "id": "4c493f06", - "metadata": { - "collapsed": false, - "editable": true - }, - "outputs": [], - "source": [ - "# Importing various packages\n", - "import numpy as np\n", - "\n", - "n = 100\n", - "x = np.random.normal(size=n)\n", - "print(np.mean(x))\n", - "y = 4+3*x+np.random.normal(size=n)\n", - "print(np.mean(y))\n", - "z = x**3+np.random.normal(size=n)\n", - "print(np.mean(z))\n", - "W = np.vstack((x, y, z))\n", - "Sigma = np.cov(W)\n", - "print(Sigma)\n", - "Eigvals, Eigvecs = np.linalg.eig(Sigma)\n", - "print(Eigvals)" - ] - }, - { - "cell_type": "code", - "execution_count": 16, - "id": "20bda99f", - "metadata": { - "collapsed": false, - "editable": true - }, - "outputs": [], - "source": [ - "%matplotlib inline\n", - "\n", - "import numpy as np\n", - "import matplotlib.pyplot as plt\n", - "from scipy import sparse\n", - "eye = np.eye(4)\n", - "print(eye)\n", - "sparse_mtx = sparse.csr_matrix(eye)\n", - "print(sparse_mtx)\n", - "x = np.linspace(-10,10,100)\n", - "y = np.sin(x)\n", - "plt.plot(x,y,marker='x')\n", - "plt.show()" - ] - }, - { - "cell_type": "markdown", - "id": "a9bff117", - "metadata": { - "editable": true - }, - "source": [ - "## Meet the Pandas\n", - "\n", - "\n", - "\n", - "\n", - "

Figure 1:

\n", - "\n", - "\n", - "Another useful Python package is\n", - "[pandas](https://pandas.pydata.org/), which is an open source library\n", - "providing high-performance, easy-to-use data structures and data\n", - "analysis tools for Python. **pandas** stands for panel data, a term borrowed from econometrics and is an efficient library for data analysis with an emphasis on tabular data.\n", - "**pandas** has two major classes, the **DataFrame** class with two-dimensional data objects and tabular data organized in columns and the class **Series** with a focus on one-dimensional data objects. Both classes allow you to index data easily as we will see in the examples below. \n", - "**pandas** allows you also to perform mathematical operations on the data, spanning from simple reshapings of vectors and matrices to statistical operations. \n", - "\n", - "The following simple example shows how we can, in an easy way make tables of our data. Here we define a data set which includes names, place of birth and date of birth, and displays the data in an easy to read way. We will see repeated use of **pandas**, in particular in connection with classification of data." - ] - }, - { - "cell_type": "code", - "execution_count": 17, - "id": "9ce8cf97", - "metadata": { - "collapsed": false, - "editable": true - }, - "outputs": [], - "source": [ - "import pandas as pd\n", - "from IPython.display import display\n", - "data = {'First Name': [\"Frodo\", \"Bilbo\", \"Aragorn II\", \"Samwise\"],\n", - " 'Last Name': [\"Baggins\", \"Baggins\",\"Elessar\",\"Gamgee\"],\n", - " 'Place of birth': [\"Shire\", \"Shire\", \"Eriador\", \"Shire\"],\n", - " 'Date of Birth T.A.': [2968, 2890, 2931, 2980]\n", - " }\n", - "data_pandas = pd.DataFrame(data)\n", - "display(data_pandas)" - ] - }, - { - "cell_type": "markdown", - "id": "98b2cebb", - "metadata": { - "editable": true - }, - "source": [ - "In the above we have imported **pandas** with the shorthand **pd**, the latter has become the standard way we import **pandas**. We make then a list of various variables\n", - "and reorganize the aboves lists into a **DataFrame** and then print out a neat table with specific column labels as *Name*, *place of birth* and *date of birth*.\n", - "Displaying these results, we see that the indices are given by the default numbers from zero to three.\n", - "**pandas** is extremely flexible and we can easily change the above indices by defining a new type of indexing as" - ] - }, - { - "cell_type": "code", - "execution_count": 18, - "id": "88a877c3", - "metadata": { - "collapsed": false, - "editable": true - }, - "outputs": [], - "source": [ - "data_pandas = pd.DataFrame(data,index=['Frodo','Bilbo','Aragorn','Sam'])\n", - "display(data_pandas)" - ] - }, - { - "cell_type": "markdown", - "id": "0928de6c", - "metadata": { - "editable": true - }, - "source": [ - "Thereafter we display the content of the row which begins with the index **Aragorn**" - ] - }, - { - "cell_type": "code", - "execution_count": 19, - "id": "d93baec5", - "metadata": { - "collapsed": false, - "editable": true - }, - "outputs": [], - "source": [ - "display(data_pandas.loc['Aragorn'])" - ] - }, - { - "cell_type": "markdown", - "id": "7a5b03a4", - "metadata": { - "editable": true - }, - "source": [ - "We can easily append data to this, for example" - ] - }, - { - "cell_type": "code", - "execution_count": 20, - "id": "2b5968bf", - "metadata": { - "collapsed": false, - "editable": true - }, - "outputs": [], - "source": [ - "new_hobbit = {'First Name': [\"Peregrin\"],\n", - " 'Last Name': [\"Took\"],\n", - " 'Place of birth': [\"Shire\"],\n", - " 'Date of Birth T.A.': [2990]\n", - " }\n", - "data_pandas=data_pandas.append(pd.DataFrame(new_hobbit, index=['Pippin']))\n", - "display(data_pandas)" - ] - }, - { - "cell_type": "markdown", - "id": "281789dd", - "metadata": { - "editable": true - }, - "source": [ - "Here are other examples where we use the **DataFrame** functionality to handle arrays, now with more interesting features for us, namely numbers. We set up a matrix \n", - "of dimensionality $10\\times 5$ and compute the mean value and standard deviation of each column. Similarly, we can perform mathematial operations like squaring the matrix elements and many other operations." - ] - }, - { - "cell_type": "code", - "execution_count": 21, - "id": "226cafd5", - "metadata": { - "collapsed": false, - "editable": true - }, - "outputs": [], - "source": [ - "import numpy as np\n", - "import pandas as pd\n", - "from IPython.display import display\n", - "np.random.seed(100)\n", - "# setting up a 10 x 5 matrix\n", - "rows = 10\n", - "cols = 5\n", - "a = np.random.randn(rows,cols)\n", - "df = pd.DataFrame(a)\n", - "display(df)\n", - "print(df.mean())\n", - "print(df.std())\n", - "display(df**2)" - ] - }, - { - "cell_type": "markdown", - "id": "34d1241d", - "metadata": { - "editable": true - }, - "source": [ - "Thereafter we can select specific columns only and plot final results" - ] - }, - { - "cell_type": "code", - "execution_count": 22, - "id": "66de0f40", - "metadata": { - "collapsed": false, - "editable": true - }, - "outputs": [], - "source": [ - "df.columns = ['First', 'Second', 'Third', 'Fourth', 'Fifth']\n", - "df.index = np.arange(10)\n", - "\n", - "display(df)\n", - "print(df['Second'].mean() )\n", - "print(df.info())\n", - "print(df.describe())\n", - "\n", - "from pylab import plt, mpl\n", - "plt.style.use('seaborn')\n", - "mpl.rcParams['font.family'] = 'serif'\n", - "\n", - "df.cumsum().plot(lw=2.0, figsize=(10,6))\n", - "plt.show()\n", - "\n", - "\n", - "df.plot.bar(figsize=(10,6), rot=15)\n", - "plt.show()" - ] - }, - { - "cell_type": "markdown", - "id": "fce1b00d", - "metadata": { - "editable": true - }, - "source": [ - "We can produce a $4\\times 4$ matrix" - ] - }, - { - "cell_type": "code", - "execution_count": 23, - "id": "b31ec8b2", - "metadata": { - "collapsed": false, - "editable": true - }, - "outputs": [], - "source": [ - "b = np.arange(16).reshape((4,4))\n", - "print(b)\n", - "df1 = pd.DataFrame(b)\n", - "print(df1)" - ] - }, - { - "cell_type": "markdown", - "id": "399b4f0b", - "metadata": { - "editable": true - }, - "source": [ - "and many other operations. \n", - "\n", - "The **Series** class is another important class included in\n", - "**pandas**. You can view it as a specialization of **DataFrame** but where\n", - "we have just a single column of data. It shares many of the same features as **DataFrame**. As with **DataFrame**,\n", - "most operations are vectorized, achieving thereby a high performance when dealing with computations of arrays, in particular labeled arrays.\n", - "As we will see below it leads also to a very concice code close to the mathematical operations we may be interested in.\n", - "For multidimensional arrays, we recommend strongly [xarray](http://xarray.pydata.org/en/stable/). **xarray** has much of the same flexibility as **pandas**, but allows for the extension to higher dimensions than two. We will see examples later of the usage of both **pandas** and **xarray**." - ] - }, - { - "cell_type": "markdown", - "id": "b3c66ed4", - "metadata": { - "editable": true - }, - "source": [ - "### Simple linear regression model using **scikit-learn**\n", - "\n", - "We start with perhaps our simplest possible example, using **Scikit-Learn** to perform linear regression analysis on a data set produced by us. \n", - "\n", - "What follows is a simple Python code where we have defined a function\n", - "$y$ in terms of the variable $x$. Both are defined as vectors with $100$ entries. \n", - "The numbers in the vector $\\boldsymbol{x}$ are given\n", - "by random numbers generated with a uniform distribution with entries\n", - "$x_i \\in [0,1]$ (more about probability distribution functions\n", - "later). These values are then used to define a function $y(x)$\n", - "(tabulated again as a vector) with a linear dependence on $x$ plus a\n", - "random noise added via the normal distribution.\n", - "\n", - "The Numpy functions are imported used the **import numpy as np**\n", - "statement and the random number generator for the uniform distribution\n", - "is called using the function **np.random.rand()**, where we specificy\n", - "that we want $100$ random variables. Using Numpy we define\n", - "automatically an array with the specified number of elements, $100$ in\n", - "our case. With the Numpy function **randn()** we can compute random\n", - "numbers with the normal distribution (mean value $\\mu$ equal to zero and\n", - "variance $\\sigma^2$ set to one) and produce the values of $y$ assuming a linear\n", - "dependence as function of $x$" - ] - }, - { - "cell_type": "markdown", - "id": "b7ec1f01", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "y = 2x+N(0,1),\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "5c4c6423", - "metadata": { - "editable": true - }, - "source": [ - "where $N(0,1)$ represents random numbers generated by the normal\n", - "distribution. From **Scikit-Learn** we import then the\n", - "**LinearRegression** functionality and make a prediction $\\tilde{y} =\n", - "\\alpha + \\beta x$ using the function **fit(x,y)**. We call the set of\n", - "data $(\\boldsymbol{x},\\boldsymbol{y})$ for our training data. The Python package\n", - "**scikit-learn** has also a functionality which extracts the above\n", - "fitting parameters $\\alpha$ and $\\beta$ (see below). Later we will\n", - "distinguish between training data and test data.\n", - "\n", - "For plotting we use the Python package\n", - "[matplotlib](https://matplotlib.org/) which produces publication\n", - "quality figures. Feel free to explore the extensive\n", - "[gallery](https://matplotlib.org/gallery/index.html) of examples. In\n", - "this example we plot our original values of $x$ and $y$ as well as the\n", - "prediction **ypredict** ($\\tilde{y}$), which attempts at fitting our\n", - "data with a straight line.\n", - "\n", - "The Python code follows here." - ] - }, - { - "cell_type": "code", - "execution_count": 24, - "id": "b026b228", - "metadata": { - "collapsed": false, - "editable": true - }, - "outputs": [], - "source": [ - "# Importing various packages\n", - "import numpy as np\n", - "import matplotlib.pyplot as plt\n", - "from sklearn.linear_model import LinearRegression\n", - "\n", - "x = np.random.rand(100,1)\n", - "y = 2*x+np.random.randn(100,1)\n", - "linreg = LinearRegression()\n", - "linreg.fit(x,y)\n", - "xnew = np.array([[0],[1]])\n", - "ypredict = linreg.predict(xnew)\n", - "\n", - "plt.plot(xnew, ypredict, \"r-\")\n", - "plt.plot(x, y ,'ro')\n", - "plt.axis([0,1.0,0, 5.0])\n", - "plt.xlabel(r'$x$')\n", - "plt.ylabel(r'$y$')\n", - "plt.title(r'Simple Linear Regression')\n", - "plt.show()" - ] - }, - { - "cell_type": "markdown", - "id": "121762a4", - "metadata": { - "editable": true - }, - "source": [ - "This example serves several aims. It allows us to demonstrate several\n", - "aspects of data analysis and later machine learning algorithms. The\n", - "immediate visualization shows that our linear fit is not\n", - "impressive. It goes through the data points, but there are many\n", - "outliers which are not reproduced by our linear regression. We could\n", - "now play around with this small program and change for example the\n", - "factor in front of $x$ and the normal distribution. Try to change the\n", - "function $y$ to" - ] - }, - { - "cell_type": "markdown", - "id": "60728127", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "y = 10x+0.01 \\times N(0,1),\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "acf5b63f", - "metadata": { - "editable": true - }, - "source": [ - "where $x$ is defined as before. Does the fit look better? Indeed, by\n", - "reducing the role of the noise given by the normal distribution we see immediately that\n", - "our linear prediction seemingly reproduces better the training\n", - "set. However, this testing 'by the eye' is obviouly not satisfactory in the\n", - "long run. Here we have only defined the training data and our model, and \n", - "have not discussed a more rigorous approach to the **cost** function.\n", - "\n", - "We need more rigorous criteria in defining whether we have succeeded or\n", - "not in modeling our training data. You will be surprised to see that\n", - "many scientists seldomly venture beyond this 'by the eye' approach. A\n", - "standard approach for the *cost* function is the so-called $\\chi^2$\n", - "function (a variant of the mean-squared error (MSE))" - ] - }, - { - "cell_type": "markdown", - "id": "40040656", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\chi^2 = \\frac{1}{n}\n", - "\\sum_{i=0}^{n-1}\\frac{(y_i-\\tilde{y}_i)^2}{\\sigma_i^2},\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "86948166", - "metadata": { - "editable": true - }, - "source": [ - "where $\\sigma_i^2$ is the variance (to be defined later) of the entry\n", - "$y_i$. We may not know the explicit value of $\\sigma_i^2$, it serves\n", - "however the aim of scaling the equations and make the cost function\n", - "dimensionless. \n", - "\n", - "Minimizing the cost function is a central aspect of\n", - "our discussions to come. Finding its minima as function of the model\n", - "parameters ($\\alpha$ and $\\beta$ in our case) will be a recurring\n", - "theme in these series of lectures. Essentially all machine learning\n", - "algorithms we will discuss center around the minimization of the\n", - "chosen cost function. This depends in turn on our specific\n", - "model for describing the data, a typical situation in supervised\n", - "learning. Automatizing the search for the minima of the cost function is a\n", - "central ingredient in all algorithms. Typical methods which are\n", - "employed are various variants of **gradient** methods. These will be\n", - "discussed in more detail later. Again, you'll be surprised to hear that\n", - "many practitioners minimize the above function ''by the eye', popularly dubbed as \n", - "'chi by the eye'. That is, change a parameter and see (visually and numerically) that \n", - "the $\\chi^2$ function becomes smaller. \n", - "\n", - "There are many ways to define the cost function. A simpler approach is to look at the relative difference between the training data and the predicted data, that is we define \n", - "the relative error (why would we prefer the MSE instead of the relative error?) as" - ] - }, - { - "cell_type": "markdown", - "id": "2c7af90a", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\epsilon_{\\mathrm{relative}}= \\frac{\\vert \\boldsymbol{y} -\\boldsymbol{\\tilde{y}}\\vert}{\\vert \\boldsymbol{y}\\vert}.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "aebc9af3", - "metadata": { - "editable": true - }, - "source": [ - "The squared cost function results in an arithmetic mean-unbiased\n", - "estimator, and the absolute-value cost function results in a\n", - "median-unbiased estimator (in the one-dimensional case, and a\n", - "geometric median-unbiased estimator for the multi-dimensional\n", - "case). The squared cost function has the disadvantage that it has the tendency\n", - "to be dominated by outliers.\n", - "\n", - "We can modify easily the above Python code and plot the relative error instead" - ] - }, - { - "cell_type": "code", - "execution_count": 25, - "id": "eaa61d49", - "metadata": { - "collapsed": false, - "editable": true - }, - "outputs": [], - "source": [ - "import numpy as np\n", - "import matplotlib.pyplot as plt\n", - "from sklearn.linear_model import LinearRegression\n", - "\n", - "x = np.random.rand(100,1)\n", - "y = 5*x+0.01*np.random.randn(100,1)\n", - "linreg = LinearRegression()\n", - "linreg.fit(x,y)\n", - "ypredict = linreg.predict(x)\n", - "\n", - "plt.plot(x, np.abs(ypredict-y)/abs(y), \"ro\")\n", - "plt.axis([0,1.0,0.0, 0.5])\n", - "plt.xlabel(r'$x$')\n", - "plt.ylabel(r'$\\epsilon_{\\mathrm{relative}}$')\n", - "plt.title(r'Relative error')\n", - "plt.show()" - ] - }, - { - "cell_type": "markdown", - "id": "f964fde3", - "metadata": { - "editable": true - }, - "source": [ - "Depending on the parameter in front of the normal distribution, we may\n", - "have a small or larger relative error. Try to play around with\n", - "different training data sets and study (graphically) the value of the\n", - "relative error.\n", - "\n", - "As mentioned above, **Scikit-Learn** has an impressive functionality.\n", - "We can for example extract the values of $\\alpha$ and $\\beta$ and\n", - "their error estimates, or the variance and standard deviation and many\n", - "other properties from the statistical data analysis. \n", - "\n", - "Here we show an\n", - "example of the functionality of **Scikit-Learn**." - ] - }, - { - "cell_type": "code", - "execution_count": 26, - "id": "c7fe9388", - "metadata": { - "collapsed": false, - "editable": true - }, - "outputs": [], - "source": [ - "import numpy as np \n", - "import matplotlib.pyplot as plt \n", - "from sklearn.linear_model import LinearRegression \n", - "from sklearn.metrics import mean_squared_error, r2_score, mean_squared_log_error, mean_absolute_error\n", - "\n", - "x = np.random.rand(100,1)\n", - "y = 2.0+ 5*x+0.5*np.random.randn(100,1)\n", - "linreg = LinearRegression()\n", - "linreg.fit(x,y)\n", - "ypredict = linreg.predict(x)\n", - "print('The intercept alpha: \\n', linreg.intercept_)\n", - "print('Coefficient beta : \\n', linreg.coef_)\n", - "# The mean squared error \n", - "print(\"Mean squared error: %.2f\" % mean_squared_error(y, ypredict))\n", - "# Explained variance score: 1 is perfect prediction \n", - "print('Variance score: %.2f' % r2_score(y, ypredict))\n", - "# Mean squared log error \n", - "print('Mean squared log error: %.2f' % mean_squared_log_error(y, ypredict) )\n", - "# Mean absolute error \n", - "print('Mean absolute error: %.2f' % mean_absolute_error(y, ypredict))\n", - "plt.plot(x, ypredict, \"r-\")\n", - "plt.plot(x, y ,'ro')\n", - "plt.axis([0.0,1.0,1.5, 7.0])\n", - "plt.xlabel(r'$x$')\n", - "plt.ylabel(r'$y$')\n", - "plt.title(r'Linear Regression fit ')\n", - "plt.show()" - ] - }, - { - "cell_type": "markdown", - "id": "14ad007a", - "metadata": { - "editable": true - }, - "source": [ - "The function **coef** gives us the parameter $\\beta$ of our fit while **intercept** yields \n", - "$\\alpha$. Depending on the constant in front of the normal distribution, we get values near or far from $\\alpha =2$ and $\\beta =5$. Try to play around with different parameters in front of the normal distribution. The function **meansquarederror** gives us the mean square error, a risk metric corresponding to the expected value of the squared (quadratic) error or loss defined as" - ] - }, - { - "cell_type": "markdown", - "id": "7dc68b06", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "MSE(\\boldsymbol{y},\\boldsymbol{\\tilde{y}}) = \\frac{1}{n}\n", - "\\sum_{i=0}^{n-1}(y_i-\\tilde{y}_i)^2,\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "471f97ed", - "metadata": { - "editable": true - }, - "source": [ - "The smaller the value, the better the fit. Ideally we would like to\n", - "have an MSE equal zero. The attentive reader has probably recognized\n", - "this function as being similar to the $\\chi^2$ function defined above.\n", - "\n", - "The **r2score** function computes $R^2$, the coefficient of\n", - "determination. It provides a measure of how well future samples are\n", - "likely to be predicted by the model. Best possible score is 1.0 and it\n", - "can be negative (because the model can be arbitrarily worse). A\n", - "constant model that always predicts the expected value of $\\boldsymbol{y}$,\n", - "disregarding the input features, would get a $R^2$ score of $0.0$.\n", - "\n", - "If $\\tilde{\\boldsymbol{y}}_i$ is the predicted value of the $i-th$ sample and $y_i$ is the corresponding true value, then the score $R^2$ is defined as" - ] - }, - { - "cell_type": "markdown", - "id": "65a80e19", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "R^2(\\boldsymbol{y}, \\tilde{\\boldsymbol{y}}) = 1 - \\frac{\\sum_{i=0}^{n - 1} (y_i - \\tilde{y}_i)^2}{\\sum_{i=0}^{n - 1} (y_i - \\bar{y})^2},\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "37e1d624", - "metadata": { - "editable": true - }, - "source": [ - "where we have defined the mean value of $\\boldsymbol{y}$ as" - ] - }, - { - "cell_type": "markdown", - "id": "a81b3061", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\bar{y} = \\frac{1}{n} \\sum_{i=0}^{n - 1} y_i.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "792fa6a1", - "metadata": { - "editable": true - }, - "source": [ - "Another quantity taht we will meet again in our discussions of regression analysis is \n", - " the mean absolute error (MAE), a risk metric corresponding to the expected value of the absolute error loss or what we call the $l1$-norm loss. In our discussion above we presented the relative error.\n", - "The MAE is defined as follows" - ] - }, - { - "cell_type": "markdown", - "id": "2f6df05c", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\text{MAE}(\\boldsymbol{y}, \\boldsymbol{\\tilde{y}}) = \\frac{1}{n} \\sum_{i=0}^{n-1} \\left| y_i - \\tilde{y}_i \\right|.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "9eb85874", - "metadata": { - "editable": true - }, - "source": [ - "We present the \n", - "squared logarithmic (quadratic) error" - ] - }, - { - "cell_type": "markdown", - "id": "a98d9555", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\text{MSLE}(\\boldsymbol{y}, \\boldsymbol{\\tilde{y}}) = \\frac{1}{n} \\sum_{i=0}^{n - 1} (\\log_e (1 + y_i) - \\log_e (1 + \\tilde{y}_i) )^2,\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "6766ecc9", - "metadata": { - "editable": true - }, - "source": [ - "where $\\log_e (x)$ stands for the natural logarithm of $x$. This error\n", - "estimate is best to use when targets having exponential growth, such\n", - "as population counts, average sales of a commodity over a span of\n", - "years etc. \n", - "\n", - "Finally, another cost function is the Huber cost function used in robust regression.\n", - "\n", - "The rationale behind this possible cost function is its reduced\n", - "sensitivity to outliers in the data set. In our discussions on\n", - "dimensionality reduction and normalization of data we will meet other\n", - "ways of dealing with outliers.\n", - "\n", - "The Huber cost function is defined as" - ] - }, - { - "cell_type": "markdown", - "id": "fb3a9871", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "H_{\\delta}(\\boldsymbol{a})=\\left\\{\\begin{array}{cc}\\frac{1}{2} \\boldsymbol{a}^{2}& \\text{for }|\\boldsymbol{a}|\\leq \\delta\\\\ \\delta (|\\boldsymbol{a}|-\\frac{1}{2}\\delta ),&\\text{otherwise}.\\end{array}\\right.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "57226a58", - "metadata": { - "editable": true - }, - "source": [ - "Here $\\boldsymbol{a}=\\boldsymbol{y} - \\boldsymbol{\\tilde{y}}$.\n", - "\n", - "We will discuss in more detail these and other functions in the\n", - "various lectures and lab sessions." - ] - }, - { - "cell_type": "markdown", - "id": "b333e60b", - "metadata": { - "editable": true - }, - "source": [ - "### To our real data: nuclear binding energies. Brief reminder on masses and binding energies\n", - "\n", - "Let us now dive into nuclear physics and remind ourselves briefly about some basic features about binding\n", - "energies. A basic quantity which can be measured for the ground\n", - "states of nuclei is the atomic mass $M(N, Z)$ of the neutral atom with\n", - "atomic mass number $A$ and charge $Z$. The number of neutrons is $N$. There are indeed several sophisticated experiments worldwide which allow us to measure this quantity to high precision (parts per million even). \n", - "\n", - "Atomic masses are usually tabulated in terms of the mass excess defined by" - ] - }, - { - "cell_type": "markdown", - "id": "1adb10e6", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\Delta M(N, Z) = M(N, Z) - uA,\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "77592d4e", - "metadata": { - "editable": true - }, - "source": [ - "where $u$ is the Atomic Mass Unit" - ] - }, - { - "cell_type": "markdown", - "id": "ba90405f", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "u = M(^{12}\\mathrm{C})/12 = 931.4940954(57) \\hspace{0.1cm} \\mathrm{MeV}/c^2.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "db7cef69", - "metadata": { - "editable": true - }, - "source": [ - "The nucleon masses are" - ] - }, - { - "cell_type": "markdown", - "id": "e12b557f", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "m_p = 1.00727646693(9)u,\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "6f5462e0", - "metadata": { - "editable": true - }, - "source": [ - "and" - ] - }, - { - "cell_type": "markdown", - "id": "0247179e", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "m_n = 939.56536(8)\\hspace{0.1cm} \\mathrm{MeV}/c^2 = 1.0086649156(6)u.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "cb6e7ad5", - "metadata": { - "editable": true - }, - "source": [ - "In the [2016 mass evaluation of by W.J.Huang, G.Audi, M.Wang, F.G.Kondev, S.Naimi and X.Xu](http://nuclearmasses.org/resources_folder/Wang_2017_Chinese_Phys_C_41_030003.pdf)\n", - "there are data on masses and decays of 3437 nuclei.\n", - "\n", - "The nuclear binding energy is defined as the energy required to break\n", - "up a given nucleus into its constituent parts of $N$ neutrons and $Z$\n", - "protons. In terms of the atomic masses $M(N, Z)$ the binding energy is\n", - "defined by" - ] - }, - { - "cell_type": "markdown", - "id": "b60eb119", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "BE(N, Z) = ZM_H c^2 + Nm_n c^2 - M(N, Z)c^2 ,\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "b38eb451", - "metadata": { - "editable": true - }, - "source": [ - "where $M_H$ is the mass of the hydrogen atom and $m_n$ is the mass of the neutron.\n", - "In terms of the mass excess the binding energy is given by" - ] - }, - { - "cell_type": "markdown", - "id": "d67cf525", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "BE(N, Z) = Z\\Delta_H c^2 + N\\Delta_n c^2 -\\Delta(N, Z)c^2 ,\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "2f8449b2", - "metadata": { - "editable": true - }, - "source": [ - "where $\\Delta_H c^2 = 7.2890$ MeV and $\\Delta_n c^2 = 8.0713$ MeV.\n", - "\n", - "A popular and physically intuitive model which can be used to parametrize \n", - "the experimental binding energies as function of $A$, is the so-called \n", - "**liquid drop model**. The ansatz is based on the following expression" - ] - }, - { - "cell_type": "markdown", - "id": "55ca6490", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "BE(N,Z) = a_1A-a_2A^{2/3}-a_3\\frac{Z^2}{A^{1/3}}-a_4\\frac{(N-Z)^2}{A},\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "e716655b", - "metadata": { - "editable": true - }, - "source": [ - "where $A$ stands for the number of nucleons and the $a_i$s are parameters which are determined by a fit \n", - "to the experimental data. \n", - "\n", - "To arrive at the above expression we have assumed that we can make the following assumptions:\n", - "\n", - " * There is a volume term $a_1A$ proportional with the number of nucleons (the energy is also an extensive quantity). When an assembly of nucleons of the same size is packed together into the smallest volume, each interior nucleon has a certain number of other nucleons in contact with it. This contribution is proportional to the volume.\n", - "\n", - " * There is a surface energy term $a_2A^{2/3}$. The assumption here is that a nucleon at the surface of a nucleus interacts with fewer other nucleons than one in the interior of the nucleus and hence its binding energy is less. This surface energy term takes that into account and is therefore negative and is proportional to the surface area.\n", - "\n", - " * There is a Coulomb energy term $a_3\\frac{Z^2}{A^{1/3}}$. The electric repulsion between each pair of protons in a nucleus yields less binding. \n", - "\n", - " * There is an asymmetry term $a_4\\frac{(N-Z)^2}{A}$. This term is associated with the Pauli exclusion principle and reflects the fact that the proton-neutron interaction is more attractive on the average than the neutron-neutron and proton-proton interactions.\n", - "\n", - "We could also add a so-called pairing term, which is a correction term that\n", - "arises from the tendency of proton pairs and neutron pairs to\n", - "occur. An even number of particles is more stable than an odd number." - ] - }, - { - "cell_type": "markdown", - "id": "fa63a9de", - "metadata": { - "editable": true - }, - "source": [ - "### Organizing our data\n", - "\n", - "Let us start with reading and organizing our data. \n", - "We start with the compilation of masses and binding energies from 2016.\n", - "After having downloaded this file to our own computer, we are now ready to read the file and start structuring our data.\n", - "\n", - "We start with preparing folders for storing our calculations and the data file over masses and binding energies. We import also various modules that we will find useful in order to present various Machine Learning methods. Here we focus mainly on the functionality of **scikit-learn**." - ] - }, - { - "cell_type": "code", - "execution_count": 27, - "id": "cca448dd", - "metadata": { - "collapsed": false, - "editable": true - }, - "outputs": [], - "source": [ - "# Common imports\n", - "import numpy as np\n", - "import pandas as pd\n", - "import matplotlib.pyplot as plt\n", - "import sklearn.linear_model as skl\n", - "from sklearn.model_selection import train_test_split\n", - "from sklearn.metrics import mean_squared_error, r2_score, mean_absolute_error\n", - "import os\n", - "\n", - "# Where to save the figures and data files\n", - "PROJECT_ROOT_DIR = \"Results\"\n", - "FIGURE_ID = \"Results/FigureFiles\"\n", - "DATA_ID = \"DataFiles/\"\n", - "\n", - "if not os.path.exists(PROJECT_ROOT_DIR):\n", - " os.mkdir(PROJECT_ROOT_DIR)\n", - "\n", - "if not os.path.exists(FIGURE_ID):\n", - " os.makedirs(FIGURE_ID)\n", - "\n", - "if not os.path.exists(DATA_ID):\n", - " os.makedirs(DATA_ID)\n", - "\n", - "def image_path(fig_id):\n", - " return os.path.join(FIGURE_ID, fig_id)\n", - "\n", - "def data_path(dat_id):\n", - " return os.path.join(DATA_ID, dat_id)\n", - "\n", - "def save_fig(fig_id):\n", - " plt.savefig(image_path(fig_id) + \".png\", format='png')\n", - "\n", - "infile = open(data_path(\"MassEval2016.dat\"),'r')" - ] - }, - { - "cell_type": "markdown", - "id": "aa35aba5", - "metadata": { - "editable": true - }, - "source": [ - "Before we proceed, we define also a function for making our plots. You can obviously avoid this and simply set up various **matplotlib** commands every time you need them. You may however find it convenient to collect all such commands in one function and simply call this function." - ] - }, - { - "cell_type": "code", - "execution_count": 28, - "id": "c854893a", - "metadata": { - "collapsed": false, - "editable": true - }, - "outputs": [], - "source": [ - "from pylab import plt, mpl\n", - "plt.style.use('seaborn')\n", - "mpl.rcParams['font.family'] = 'serif'\n", - "\n", - "def MakePlot(x,y, styles, labels, axlabels):\n", - " plt.figure(figsize=(10,6))\n", - " for i in range(len(x)):\n", - " plt.plot(x[i], y[i], styles[i], label = labels[i])\n", - " plt.xlabel(axlabels[0])\n", - " plt.ylabel(axlabels[1])\n", - " plt.legend(loc=0)" - ] - }, - { - "cell_type": "markdown", - "id": "74b3f235", - "metadata": { - "editable": true - }, - "source": [ - "Our next step is to read the data on experimental binding energies and\n", - "reorganize them as functions of the mass number $A$, the number of\n", - "protons $Z$ and neutrons $N$ using **pandas**. Before we do this it is\n", - "always useful (unless you have a binary file or other types of compressed\n", - "data) to actually open the file and simply take a look at it!\n", - "\n", - "In particular, the program that outputs the final nuclear masses is written in Fortran with a specific format. It means that we need to figure out the format and which columns contain the data we are interested in. Pandas comes with a function that reads formatted output. After having admired the file, we are now ready to start massaging it with **pandas**. The file begins with some basic format information." - ] - }, - { - "cell_type": "code", - "execution_count": 29, - "id": "92e8847b", - "metadata": { - "collapsed": false, - "editable": true - }, - "outputs": [], - "source": [ - "\"\"\" \n", - "This is taken from the data file of the mass 2016 evaluation. \n", - "All files are 3436 lines long with 124 character per line. \n", - " Headers are 39 lines long. \n", - " col 1 : Fortran character control: 1 = page feed 0 = line feed \n", - " format : a1,i3,i5,i5,i5,1x,a3,a4,1x,f13.5,f11.5,f11.3,f9.3,1x,a2,f11.3,f9.3,1x,i3,1x,f12.5,f11.5 \n", - " These formats are reflected in the pandas widths variable below, see the statement \n", - " widths=(1,3,5,5,5,1,3,4,1,13,11,11,9,1,2,11,9,1,3,1,12,11,1), \n", - " Pandas has also a variable header, with length 39 in this case. \n", - "\"\"\"" - ] - }, - { - "cell_type": "markdown", - "id": "8cbce288", - "metadata": { - "editable": true - }, - "source": [ - "The data we are interested in are in columns 2, 3, 4 and 11, giving us\n", - "the number of neutrons, protons, mass numbers and binding energies,\n", - "respectively. We add also for the sake of completeness the element name. The data are in fixed-width formatted lines and we will\n", - "covert them into the **pandas** DataFrame structure." - ] - }, - { - "cell_type": "code", - "execution_count": 30, - "id": "b4398581", - "metadata": { - "collapsed": false, - "editable": true - }, - "outputs": [], - "source": [ - "# Read the experimental data with Pandas\n", - "Masses = pd.read_fwf(infile, usecols=(2,3,4,6,11),\n", - " names=('N', 'Z', 'A', 'Element', 'Ebinding'),\n", - " widths=(1,3,5,5,5,1,3,4,1,13,11,11,9,1,2,11,9,1,3,1,12,11,1),\n", - " header=39,\n", - " index_col=False)\n", - "\n", - "# Extrapolated values are indicated by '#' in place of the decimal place, so\n", - "# the Ebinding column won't be numeric. Coerce to float and drop these entries.\n", - "Masses['Ebinding'] = pd.to_numeric(Masses['Ebinding'], errors='coerce')\n", - "Masses = Masses.dropna()\n", - "# Convert from keV to MeV.\n", - "Masses['Ebinding'] /= 1000\n", - "\n", - "# Group the DataFrame by nucleon number, A.\n", - "Masses = Masses.groupby('A')\n", - "# Find the rows of the grouped DataFrame with the maximum binding energy.\n", - "Masses = Masses.apply(lambda t: t[t.Ebinding==t.Ebinding.max()])" - ] - }, - { - "cell_type": "markdown", - "id": "0f21a73f", - "metadata": { - "editable": true - }, - "source": [ - "We have now read in the data, grouped them according to the variables we are interested in. \n", - "We see how easy it is to reorganize the data using **pandas**. If we\n", - "were to do these operations in C/C++ or Fortran, we would have had to\n", - "write various functions/subroutines which perform the above\n", - "reorganizations for us. Having reorganized the data, we can now start\n", - "to make some simple fits using both the functionalities in **numpy** and\n", - "**Scikit-Learn** afterwards. \n", - "\n", - "Now we define five variables which contain\n", - "the number of nucleons $A$, the number of protons $Z$ and the number of neutrons $N$, the element name and finally the energies themselves." - ] - }, - { - "cell_type": "code", - "execution_count": 31, - "id": "491e38a4", - "metadata": { - "collapsed": false, - "editable": true - }, - "outputs": [], - "source": [ - "A = Masses['A']\n", - "Z = Masses['Z']\n", - "N = Masses['N']\n", - "Element = Masses['Element']\n", - "Energies = Masses['Ebinding']\n", - "print(Masses)" - ] - }, - { - "cell_type": "markdown", - "id": "07ac2cd3", - "metadata": { - "editable": true - }, - "source": [ - "The next step, and we will define this mathematically later, is to set up the so-called **design matrix**. We will throughout call this matrix $\\boldsymbol{X}$.\n", - "It has dimensionality $p\\times n$, where $n$ is the number of data points and $p$ are the so-called predictors. In our case here they are given by the number of polynomials in $A$ we wish to include in the fit." - ] - }, - { - "cell_type": "code", - "execution_count": 32, - "id": "0462ebdd", - "metadata": { - "collapsed": false, - "editable": true - }, - "outputs": [], - "source": [ - "# Now we set up the design matrix X\n", - "X = np.zeros((len(A),5))\n", - "X[:,0] = 1\n", - "X[:,1] = A\n", - "X[:,2] = A**(2.0/3.0)\n", - "X[:,3] = A**(-1.0/3.0)\n", - "X[:,4] = A**(-1.0)" - ] - }, - { - "cell_type": "markdown", - "id": "66a31f58", - "metadata": { - "editable": true - }, - "source": [ - "With **scikitlearn** we are now ready to use linear regression and fit our data." - ] - }, - { - "cell_type": "code", - "execution_count": 33, - "id": "7d4bf033", - "metadata": { - "collapsed": false, - "editable": true - }, - "outputs": [], - "source": [ - "clf = skl.LinearRegression().fit(X, Energies)\n", - "fity = clf.predict(X)" - ] - }, - { - "cell_type": "markdown", - "id": "3b9f86de", - "metadata": { - "editable": true - }, - "source": [ - "Pretty simple! \n", - "Now we can print measures of how our fit is doing, the coefficients from the fits and plot the final fit together with our data." - ] - }, - { - "cell_type": "code", - "execution_count": 34, - "id": "b12b4d19", - "metadata": { - "collapsed": false, - "editable": true - }, - "outputs": [], - "source": [ - "# The mean squared error \n", - "print(\"Mean squared error: %.2f\" % mean_squared_error(Energies, fity))\n", - "# Explained variance score: 1 is perfect prediction \n", - "print('Variance score: %.2f' % r2_score(Energies, fity))\n", - "# Mean absolute error \n", - "print('Mean absolute error: %.2f' % mean_absolute_error(Energies, fity))\n", - "print(clf.coef_, clf.intercept_)\n", - "\n", - "Masses['Eapprox'] = fity\n", - "# Generate a plot comparing the experimental with the fitted values values.\n", - "fig, ax = plt.subplots()\n", - "ax.set_xlabel(r'$A = N + Z$')\n", - "ax.set_ylabel(r'$E_\\mathrm{bind}\\,/\\mathrm{MeV}$')\n", - "ax.plot(Masses['A'], Masses['Ebinding'], alpha=0.7, lw=2,\n", - " label='Ame2016')\n", - "ax.plot(Masses['A'], Masses['Eapprox'], alpha=0.7, lw=2, c='m',\n", - " label='Fit')\n", - "ax.legend()\n", - "save_fig(\"Masses2016\")\n", - "plt.show()" - ] - }, - { - "cell_type": "markdown", - "id": "4cf1be8b", - "metadata": { - "editable": true - }, - "source": [ - "### And what about using neural networks?\n", - "\n", - "The **seaborn** package allows us to visualize data in an efficient way. Note that we use **scikit-learn**'s multi-layer perceptron (or feed forward neural network) \n", - "functionality." - ] - }, - { - "cell_type": "code", - "execution_count": 35, - "id": "e80600eb", - "metadata": { - "collapsed": false, - "editable": true - }, - "outputs": [], - "source": [ - "from sklearn.neural_network import MLPRegressor\n", - "from sklearn.metrics import accuracy_score\n", - "import seaborn as sns\n", - "\n", - "X_train = X\n", - "Y_train = Energies\n", - "n_hidden_neurons = 100\n", - "epochs = 100\n", - "# store models for later use\n", - "eta_vals = np.logspace(-5, 1, 7)\n", - "lmbd_vals = np.logspace(-5, 1, 7)\n", - "# store the models for later use\n", - "DNN_scikit = np.zeros((len(eta_vals), len(lmbd_vals)), dtype=object)\n", - "train_accuracy = np.zeros((len(eta_vals), len(lmbd_vals)))\n", - "sns.set()\n", - "for i, eta in enumerate(eta_vals):\n", - " for j, lmbd in enumerate(lmbd_vals):\n", - " dnn = MLPRegressor(hidden_layer_sizes=(n_hidden_neurons), activation='logistic',\n", - " alpha=lmbd, learning_rate_init=eta, max_iter=epochs)\n", - " dnn.fit(X_train, Y_train)\n", - " DNN_scikit[i][j] = dnn\n", - " train_accuracy[i][j] = dnn.score(X_train, Y_train)\n", - "\n", - "fig, ax = plt.subplots(figsize = (10, 10))\n", - "sns.heatmap(train_accuracy, annot=True, ax=ax, cmap=\"viridis\")\n", - "ax.set_title(\"Training Accuracy\")\n", - "ax.set_ylabel(\"$\\eta$\")\n", - "ax.set_xlabel(\"$\\lambda$\")\n", - "plt.show()" - ] - }, - { - "cell_type": "markdown", - "id": "d49cd4ec", - "metadata": { - "editable": true - }, - "source": [ - "## A first summary\n", - "\n", - "The aim behind these introductory words was to present to you various\n", - "Python libraries and their functionalities, in particular libraries like\n", - "**numpy**, **pandas**, **xarray** and **matplotlib** and other that make our life much easier\n", - "in handling various data sets and visualizing data. \n", - "\n", - "Furthermore,\n", - "**Scikit-Learn** allows us with few lines of code to implement popular\n", - "Machine Learning algorithms for supervised learning. Later we will meet **Tensorflow**, a powerful library for deep learning. \n", - "Now it is time to dive more into the details of various methods. We will start with linear regression and try to take a deeper look at what it entails." - ] - }, - { - "cell_type": "markdown", - "id": "9a4706c7", - "metadata": { - "editable": true - }, - "source": [ - "## Why Linear Regression (aka Ordinary Least Squares and family)\n", - "\n", - "Fitting a continuous function with linear parameterization in terms of the parameters $\\boldsymbol{\\beta}$.\n", - "* Method of choice for fitting a continuous function!\n", - "\n", - "* Gives an excellent introduction to central Machine Learning features with **understandable pedagogical** links to other methods like **Neural Networks**, **Support Vector Machines** etc\n", - "\n", - "* Analytical expression for the fitting parameters $\\boldsymbol{\\beta}$\n", - "\n", - "* Analytical expressions for statistical propertiers like mean values, variances, confidence intervals and more\n", - "\n", - "* Analytical relation with probabilistic interpretations \n", - "\n", - "* Easy to introduce basic concepts like bias-variance tradeoff, cross-validation, resampling and regularization techniques and many other ML topics\n", - "\n", - "* Easy to code! And links well with classification problems and logistic regression and neural networks\n", - "\n", - "* Allows for **easy** hands-on understanding of gradient descent methods\n", - "\n", - "* and many more features\n", - "\n", - "For more discussions of Ridge and Lasso regression, [Wessel van Wieringen's](https://arxiv.org/abs/1509.09169) article is highly recommended.\n", - "Similarly, [Mehta et al's article](https://arxiv.org/abs/1803.08823) is also recommended." - ] - }, - { - "cell_type": "markdown", - "id": "b720efdc", - "metadata": { - "editable": true - }, - "source": [ - "## Regression analysis, overarching aims\n", - "\n", - "Regression modeling deals with the description of the sampling distribution of a given random variable $y$ and how it varies as function of another variable or a set of such variables $\\boldsymbol{x} =[x_0, x_1,\\dots, x_{n-1}]^T$. \n", - "The first variable is called the **dependent**, the **outcome** or the **response** variable while the set of variables $\\boldsymbol{x}$ is called the independent variable, or the predictor variable or the explanatory variable, or simply just the **inputs**. \n", - "\n", - "A regression model aims at finding a likelihood function $p(\\boldsymbol{y}\\vert \\boldsymbol{x})$ or in the more traditional sense a function $\\boldsymbol{y}(\\boldsymbol{x})$, that is the conditional distribution for $\\boldsymbol{y}$ with a given $\\boldsymbol{x}$. The estimation of $p(\\boldsymbol{y}\\vert \\boldsymbol{x})$ is made using a data set with \n", - "* $n$ cases $i = 0, 1, 2, \\dots, n-1$ \n", - "\n", - "* Response (target, dependent or outcome) variable $y_i$ with $i = 0, 1, 2, \\dots, n-1$ \n", - "\n", - "* $p$ so-called explanatory (independent or predictor or feature) variables $\\boldsymbol{x}_i=[x_{i0}, x_{i1}, \\dots, x_{ip-1}]$ with $i = 0, 1, 2, \\dots, n-1$ and explanatory variables running from $0$ to $p-1$. See below for more explicit examples. \n", - "\n", - " The goal of the regression analysis is to extract/exploit relationship between $\\boldsymbol{y}$ and $\\boldsymbol{x}$ in order to infer specific dependencies, approximations to the likelihood functions, functional relationships and to make predictions, making fits and many other things." - ] - }, - { - "cell_type": "markdown", - "id": "0cb90bb5", - "metadata": { - "editable": true - }, - "source": [ - "## Regression analysis, overarching aims II\n", - "\n", - "Consider an experiment in which $p$ characteristics/features of $n$ samples are\n", - "measured. The data from this experiment, for various explanatory variables $p$ are normally represented by a matrix \n", - "$\\mathbf{X}$.\n", - "\n", - "The matrix $\\mathbf{X}$ is called the *design\n", - "matrix*. Additional information of the samples is available in the\n", - "form of $\\boldsymbol{y}$ (also as above). The variable $\\boldsymbol{y}$ is\n", - "generally referred to as the *response variable*. The aim of\n", - "regression analysis is to explain $\\boldsymbol{y}$ in terms of\n", - "$\\boldsymbol{X}$ through a functional relationship like $y_i =\n", - "f(\\mathbf{X}_{i,\\ast})$. When no prior knowledge on the form of\n", - "$f(\\cdot)$ is available, it is common to assume a linear relationship\n", - "between $\\boldsymbol{X}$ and $\\boldsymbol{y}$. This assumption gives rise to\n", - "the *linear regression model* where $\\boldsymbol{\\beta} = [\\beta_0, \\ldots,\n", - "\\beta_{p-1}]^{T}$ are the *regression parameters*. \n", - "\n", - "Linear regression gives us a set of analytical equations for the parameters $\\beta_j$." - ] - }, - { - "cell_type": "markdown", - "id": "e45e89d3", - "metadata": { - "editable": true - }, - "source": [ - "## Examples\n", - "In order to understand the relation among the predictors (or features or properties) $p$, the set of data $n$ and the target (outcome, output etc) $\\boldsymbol{y}$,\n", - "consider the model we discussed for describing nuclear binding energies. \n", - "\n", - "There we assumed that we could parametrize the data using a polynomial approximation based on the liquid drop model.\n", - "Assuming" - ] - }, - { - "cell_type": "markdown", - "id": "f2471451", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "BE(A) = a_0+a_1A+a_2A^{2/3}+a_3A^{-1/3}+a_4A^{-1},\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "ee20b9ee", - "metadata": { - "editable": true - }, - "source": [ - "we have five predictors, that is the intercept, the $A$ dependent term, the $A^{2/3}$ term and the $A^{-1/3}$ and $A^{-1}$ terms.\n", - "This gives $p=0,1,2,3,4$. Furthermore we have $n$ entries for each predictor. It means that our design matrix is a \n", - "$p\\times n$ matrix $\\boldsymbol{X}$.\n", - "\n", - "Here the predictors are based on a model we have made. A popular data set which is widely encountered in ML applications is the\n", - "so-called [credit card default data from Taiwan](https://www.sciencedirect.com/science/article/pii/S0957417407006719?via%3Dihub). The data set contains data on $n=30000$ credit card holders with predictors like gender, marital status, age, profession, education, etc. In total there are $24$ such predictors or attributes leading to a design matrix of dimensionality $24 \\times 30000$. This is however a classification problem and we will come back to it when we discuss Logistic Regression." - ] - }, - { - "cell_type": "markdown", - "id": "ebc12338", - "metadata": { - "editable": true - }, - "source": [ - "## General linear models and linear algebra\n", - "Before we proceed let us study a case where we aim at fitting a set of data $\\boldsymbol{y}=[y_0,y_1,\\dots,y_{n-1}]$. We could think of these data as a result of an experiment or a complicated numerical experiment. These data are functions of a series of variables $\\boldsymbol{x}=[x_0,x_1,\\dots,x_{n-1}]$, that is $y_i = y(x_i)$ with $i=0,1,2,\\dots,n-1$. The variables $x_i$ could represent physical quantities like time, temperature, position etc. We assume that $y(x)$ is a smooth function. \n", - "\n", - "Since obtaining these data points may not be trivial, we want to use these data to fit a function which can allow us to make predictions for values of $y$ which are not in the present set. The perhaps simplest approach is to assume we can parametrize our function in terms of a polynomial of degree $n-1$ with $n$ points, that is" - ] - }, - { - "cell_type": "markdown", - "id": "0f5cb3d7", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "y=y(x) \\rightarrow y(x_i)=\\tilde{y}_i+\\epsilon_i=\\sum_{j=0}^{n-1} \\beta_j x_i^j+\\epsilon_i,\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "8be293e3", - "metadata": { - "editable": true - }, - "source": [ - "where $\\epsilon_i$ is the error in our approximation." - ] - }, - { - "cell_type": "markdown", - "id": "c0a2104e", - "metadata": { - "editable": true - }, - "source": [ - "## Rewriting the fitting procedure as a linear algebra problem\n", - "For every set of values $y_i,x_i$ we have thus the corresponding set of equations" - ] - }, - { - "cell_type": "markdown", - "id": "93b447fd", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\begin{align*}\n", - "y_0&=\\beta_0+\\beta_1x_0^1+\\beta_2x_0^2+\\dots+\\beta_{n-1}x_0^{n-1}+\\epsilon_0\\\\\n", - "y_1&=\\beta_0+\\beta_1x_1^1+\\beta_2x_1^2+\\dots+\\beta_{n-1}x_1^{n-1}+\\epsilon_1\\\\\n", - "y_2&=\\beta_0+\\beta_1x_2^1+\\beta_2x_2^2+\\dots+\\beta_{n-1}x_2^{n-1}+\\epsilon_2\\\\\n", - "\\dots & \\dots \\\\\n", - "y_{n-1}&=\\beta_0+\\beta_1x_{n-1}^1+\\beta_2x_{n-1}^2+\\dots+\\beta_{n-1}x_{n-1}^{n-1}+\\epsilon_{n-1}.\\\\\n", - "\\end{align*}\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "94d59403", - "metadata": { - "editable": true - }, - "source": [ - "## Rewriting the fitting procedure as a linear algebra problem, more details\n", - "Defining the vectors" - ] - }, - { - "cell_type": "markdown", - "id": "7b044c26", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\boldsymbol{y} = [y_0,y_1, y_2,\\dots, y_{n-1}]^T,\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "a4ec8b3e", - "metadata": { - "editable": true - }, - "source": [ - "and" - ] - }, - { - "cell_type": "markdown", - "id": "7e221f81", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\boldsymbol{\\beta} = [\\beta_0,\\beta_1, \\beta_2,\\dots, \\beta_{n-1}]^T,\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "729c5dd3", - "metadata": { - "editable": true - }, - "source": [ - "and" - ] - }, - { - "cell_type": "markdown", - "id": "5eb54f13", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\boldsymbol{\\epsilon} = [\\epsilon_0,\\epsilon_1, \\epsilon_2,\\dots, \\epsilon_{n-1}]^T,\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "51cad783", - "metadata": { - "editable": true - }, - "source": [ - "and the design matrix" - ] - }, - { - "cell_type": "markdown", - "id": "e38a17c1", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\boldsymbol{X}=\n", - "\\begin{bmatrix} \n", - "1& x_{0}^1 &x_{0}^2& \\dots & \\dots &x_{0}^{n-1}\\\\\n", - "1& x_{1}^1 &x_{1}^2& \\dots & \\dots &x_{1}^{n-1}\\\\\n", - "1& x_{2}^1 &x_{2}^2& \\dots & \\dots &x_{2}^{n-1}\\\\ \n", - "\\dots& \\dots &\\dots& \\dots & \\dots &\\dots\\\\\n", - "1& x_{n-1}^1 &x_{n-1}^2& \\dots & \\dots &x_{n-1}^{n-1}\\\\\n", - "\\end{bmatrix}\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "c669704a", - "metadata": { - "editable": true - }, - "source": [ - "we can rewrite our equations as" - ] - }, - { - "cell_type": "markdown", - "id": "6c2f1143", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\boldsymbol{y} = \\boldsymbol{X}\\boldsymbol{\\beta}+\\boldsymbol{\\epsilon}.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "144ef4c2", - "metadata": { - "editable": true - }, - "source": [ - "The above design matrix is called a [Vandermonde matrix](https://en.wikipedia.org/wiki/Vandermonde_matrix)." - ] - }, - { - "cell_type": "markdown", - "id": "d9da387d", - "metadata": { - "editable": true - }, - "source": [ - "## Generalizing the fitting procedure as a linear algebra problem\n", - "\n", - "We are obviously not limited to the above polynomial expansions. We\n", - "could replace the various powers of $x$ with elements of Fourier\n", - "series or instead of $x_i^j$ we could have $\\cos{(j x_i)}$ or $\\sin{(j\n", - "x_i)}$, or time series or other orthogonal functions. For every set\n", - "of values $y_i,x_i$ we can then generalize the equations to" - ] - }, - { - "cell_type": "markdown", - "id": "16d9099a", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\begin{align*}\n", - "y_0&=\\beta_0x_{00}+\\beta_1x_{01}+\\beta_2x_{02}+\\dots+\\beta_{n-1}x_{0n-1}+\\epsilon_0\\\\\n", - "y_1&=\\beta_0x_{10}+\\beta_1x_{11}+\\beta_2x_{12}+\\dots+\\beta_{n-1}x_{1n-1}+\\epsilon_1\\\\\n", - "y_2&=\\beta_0x_{20}+\\beta_1x_{21}+\\beta_2x_{22}+\\dots+\\beta_{n-1}x_{2n-1}+\\epsilon_2\\\\\n", - "\\dots & \\dots \\\\\n", - "y_{i}&=\\beta_0x_{i0}+\\beta_1x_{i1}+\\beta_2x_{i2}+\\dots+\\beta_{n-1}x_{in-1}+\\epsilon_i\\\\\n", - "\\dots & \\dots \\\\\n", - "y_{n-1}&=\\beta_0x_{n-1,0}+\\beta_1x_{n-1,2}+\\beta_2x_{n-1,2}+\\dots+\\beta_{n-1}x_{n-1,n-1}+\\epsilon_{n-1}.\\\\\n", - "\\end{align*}\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "dac4b0d4", - "metadata": { - "editable": true - }, - "source": [ - "**Note that we have $p=n$ here. The matrix is symmetric. This is generally not the case!**" - ] - }, - { - "cell_type": "markdown", - "id": "821d16ee", - "metadata": { - "editable": true - }, - "source": [ - "## Generalizing the fitting procedure as a linear algebra problem\n", - "We redefine in turn the matrix $\\boldsymbol{X}$ as" - ] - }, - { - "cell_type": "markdown", - "id": "64804e58", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\boldsymbol{X}=\n", - "\\begin{bmatrix} \n", - "x_{00}& x_{01} &x_{02}& \\dots & \\dots &x_{0,n-1}\\\\\n", - "x_{10}& x_{11} &x_{12}& \\dots & \\dots &x_{1,n-1}\\\\\n", - "x_{20}& x_{21} &x_{22}& \\dots & \\dots &x_{2,n-1}\\\\ \n", - "\\dots& \\dots &\\dots& \\dots & \\dots &\\dots\\\\\n", - "x_{n-1,0}& x_{n-1,1} &x_{n-1,2}& \\dots & \\dots &x_{n-1,n-1}\\\\\n", - "\\end{bmatrix}\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "28be47df", - "metadata": { - "editable": true - }, - "source": [ - "and without loss of generality we rewrite again our equations as" - ] - }, - { - "cell_type": "markdown", - "id": "f15f39a0", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\boldsymbol{y} = \\boldsymbol{X}\\boldsymbol{\\beta}+\\boldsymbol{\\epsilon}.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "03117774", - "metadata": { - "editable": true - }, - "source": [ - "The left-hand side of this equation is kwown. Our error vector $\\boldsymbol{\\epsilon}$ and the parameter vector $\\boldsymbol{\\beta}$ are our unknow quantities. How can we obtain the optimal set of $\\beta_i$ values?" - ] - }, - { - "cell_type": "markdown", - "id": "2dadc99e", - "metadata": { - "editable": true - }, - "source": [ - "## Optimizing our parameters\n", - "We have defined the matrix $\\boldsymbol{X}$ via the equations" - ] - }, - { - "cell_type": "markdown", - "id": "98d081e3", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\begin{align*}\n", - "y_0&=\\beta_0x_{00}+\\beta_1x_{01}+\\beta_2x_{02}+\\dots+\\beta_{n-1}x_{0n-1}+\\epsilon_0\\\\\n", - "y_1&=\\beta_0x_{10}+\\beta_1x_{11}+\\beta_2x_{12}+\\dots+\\beta_{n-1}x_{1n-1}+\\epsilon_1\\\\\n", - "y_2&=\\beta_0x_{20}+\\beta_1x_{21}+\\beta_2x_{22}+\\dots+\\beta_{n-1}x_{2n-1}+\\epsilon_1\\\\\n", - "\\dots & \\dots \\\\\n", - "y_{i}&=\\beta_0x_{i0}+\\beta_1x_{i1}+\\beta_2x_{i2}+\\dots+\\beta_{n-1}x_{in-1}+\\epsilon_1\\\\\n", - "\\dots & \\dots \\\\\n", - "y_{n-1}&=\\beta_0x_{n-1,0}+\\beta_1x_{n-1,2}+\\beta_2x_{n-1,2}+\\dots+\\beta_{n-1}x_{n-1,n-1}+\\epsilon_{n-1}.\\\\\n", - "\\end{align*}\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "02c207e3", - "metadata": { - "editable": true - }, - "source": [ - "As we noted above, we stayed with a system with the design matrix \n", - " $\\boldsymbol{X}\\in {\\mathbb{R}}^{n\\times n}$, that is we have $p=n$. For reasons to come later (algorithmic arguments) we will hereafter define \n", - "our matrix as $\\boldsymbol{X}\\in {\\mathbb{R}}^{n\\times p}$, with the predictors refering to the column numbers and the entries $n$ being the row elements." - ] - }, - { - "cell_type": "markdown", - "id": "5b3ba5aa", - "metadata": { - "editable": true - }, - "source": [ - "## Our model for the nuclear binding energies\n", - "\n", - "In our [introductory notes](https://compphysics.github.io/MachineLearning/doc/pub/How2ReadData/html/How2ReadData.html) we looked at the so-called [liquid drop model](https://en.wikipedia.org/wiki/Semi-empirical_mass_formula). Let us remind ourselves about what we did by looking at the code.\n", - "\n", - "We restate the parts of the code we are most interested in." - ] - }, - { - "cell_type": "code", - "execution_count": 36, - "id": "97a71b30", - "metadata": { - "collapsed": false, - "editable": true - }, - "outputs": [], - "source": [ - "# Common imports\n", - "import numpy as np\n", - "import pandas as pd\n", - "import matplotlib.pyplot as plt\n", - "from IPython.display import display\n", - "import os\n", - "\n", - "# Where to save the figures and data files\n", - "PROJECT_ROOT_DIR = \"Results\"\n", - "FIGURE_ID = \"Results/FigureFiles\"\n", - "DATA_ID = \"DataFiles/\"\n", - "\n", - "if not os.path.exists(PROJECT_ROOT_DIR):\n", - " os.mkdir(PROJECT_ROOT_DIR)\n", - "\n", - "if not os.path.exists(FIGURE_ID):\n", - " os.makedirs(FIGURE_ID)\n", - "\n", - "if not os.path.exists(DATA_ID):\n", - " os.makedirs(DATA_ID)\n", - "\n", - "def image_path(fig_id):\n", - " return os.path.join(FIGURE_ID, fig_id)\n", - "\n", - "def data_path(dat_id):\n", - " return os.path.join(DATA_ID, dat_id)\n", - "\n", - "def save_fig(fig_id):\n", - " plt.savefig(image_path(fig_id) + \".png\", format='png')\n", - "\n", - "infile = open(data_path(\"MassEval2016.dat\"),'r')\n", - "\n", - "\n", - "# Read the experimental data with Pandas\n", - "Masses = pd.read_fwf(infile, usecols=(2,3,4,6,11),\n", - " names=('N', 'Z', 'A', 'Element', 'Ebinding'),\n", - " widths=(1,3,5,5,5,1,3,4,1,13,11,11,9,1,2,11,9,1,3,1,12,11,1),\n", - " header=39,\n", - " index_col=False)\n", - "\n", - "# Extrapolated values are indicated by '#' in place of the decimal place, so\n", - "# the Ebinding column won't be numeric. Coerce to float and drop these entries.\n", - "Masses['Ebinding'] = pd.to_numeric(Masses['Ebinding'], errors='coerce')\n", - "Masses = Masses.dropna()\n", - "# Convert from keV to MeV.\n", - "Masses['Ebinding'] /= 1000\n", - "\n", - "# Group the DataFrame by nucleon number, A.\n", - "Masses = Masses.groupby('A')\n", - "# Find the rows of the grouped DataFrame with the maximum binding energy.\n", - "Masses = Masses.apply(lambda t: t[t.Ebinding==t.Ebinding.max()])\n", - "A = Masses['A']\n", - "Z = Masses['Z']\n", - "N = Masses['N']\n", - "Element = Masses['Element']\n", - "Energies = Masses['Ebinding']\n", - "\n", - "# Now we set up the design matrix X\n", - "X = np.zeros((len(A),5))\n", - "X[:,0] = 1\n", - "X[:,1] = A\n", - "X[:,2] = A**(2.0/3.0)\n", - "X[:,3] = A**(-1.0/3.0)\n", - "X[:,4] = A**(-1.0)\n", - "# Then nice printout using pandas\n", - "DesignMatrix = pd.DataFrame(X)\n", - "DesignMatrix.index = A\n", - "DesignMatrix.columns = ['1', 'A', 'A^(2/3)', 'A^(-1/3)', '1/A']\n", - "display(DesignMatrix)" - ] - }, - { - "cell_type": "markdown", - "id": "ed7eb3b8", - "metadata": { - "editable": true - }, - "source": [ - "With $\\boldsymbol{\\beta}\\in {\\mathbb{R}}^{p\\times 1}$, it means that we will hereafter write our equations for the approximation as" - ] - }, - { - "cell_type": "markdown", - "id": "1ac7d0e5", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\boldsymbol{\\tilde{y}}= \\boldsymbol{X}\\boldsymbol{\\beta},\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "8069a90f", - "metadata": { - "editable": true - }, - "source": [ - "throughout these lectures." - ] - }, - { - "cell_type": "markdown", - "id": "815493e0", - "metadata": { - "editable": true - }, - "source": [ - "## Optimizing our parameters, more details\n", - "With the above we use the design matrix to define the approximation $\\boldsymbol{\\tilde{y}}$ via the unknown quantity $\\boldsymbol{\\beta}$ as" - ] - }, - { - "cell_type": "markdown", - "id": "7880ef32", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\boldsymbol{\\tilde{y}}= \\boldsymbol{X}\\boldsymbol{\\beta},\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "ecb0a16f", - "metadata": { - "editable": true - }, - "source": [ - "and in order to find the optimal parameters $\\beta_i$ instead of solving the above linear algebra problem, we define a function which gives a measure of the spread between the values $y_i$ (which represent hopefully the exact values) and the parameterized values $\\tilde{y}_i$, namely" - ] - }, - { - "cell_type": "markdown", - "id": "d8782aad", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "C(\\boldsymbol{\\beta})=\\frac{1}{n}\\sum_{i=0}^{n-1}\\left(y_i-\\tilde{y}_i\\right)^2=\\frac{1}{n}\\left\\{\\left(\\boldsymbol{y}-\\boldsymbol{\\tilde{y}}\\right)^T\\left(\\boldsymbol{y}-\\boldsymbol{\\tilde{y}}\\right)\\right\\},\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "d2491d40", - "metadata": { - "editable": true - }, - "source": [ - "or using the matrix $\\boldsymbol{X}$ and in a more compact matrix-vector notation as" - ] - }, - { - "cell_type": "markdown", - "id": "1cf22842", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "C(\\boldsymbol{\\beta})=\\frac{1}{n}\\left\\{\\left(\\boldsymbol{y}-\\boldsymbol{X}\\boldsymbol{\\beta}\\right)^T\\left(\\boldsymbol{y}-\\boldsymbol{X}\\boldsymbol{\\beta}\\right)\\right\\}.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "71180218", - "metadata": { - "editable": true - }, - "source": [ - "This function is one possible way to define the so-called cost function.\n", - "\n", - "It is also common to define\n", - "the function $C$ as" - ] - }, - { - "cell_type": "markdown", - "id": "1c734def", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "C(\\boldsymbol{\\beta})=\\frac{1}{2n}\\sum_{i=0}^{n-1}\\left(y_i-\\tilde{y}_i\\right)^2,\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "85f6ff9d", - "metadata": { - "editable": true - }, - "source": [ - "since when taking the first derivative with respect to the unknown parameters $\\beta$, the factor of $2$ cancels out." - ] - }, - { - "cell_type": "markdown", - "id": "1ad66e97", - "metadata": { - "editable": true - }, - "source": [ - "## Interpretations and optimizing our parameters\n", - "\n", - "The function" - ] - }, - { - "cell_type": "markdown", - "id": "6ff8d32a", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "C(\\boldsymbol{\\beta})=\\frac{1}{n}\\left\\{\\left(\\boldsymbol{y}-\\boldsymbol{X}\\boldsymbol{\\beta}\\right)^T\\left(\\boldsymbol{y}-\\boldsymbol{X}\\boldsymbol{\\beta}\\right)\\right\\},\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "fde1cca5", - "metadata": { - "editable": true - }, - "source": [ - "can be linked to the variance of the quantity $y_i$ if we interpret the latter as the mean value. \n", - "When linking (see the discussion below) with the maximum likelihood approach below, we will indeed interpret $y_i$ as a mean value" - ] - }, - { - "cell_type": "markdown", - "id": "5b34fa19", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "y_{i}=\\langle y_i \\rangle = \\beta_0x_{i,0}+\\beta_1x_{i,1}+\\beta_2x_{i,2}+\\dots+\\beta_{n-1}x_{i,n-1}+\\epsilon_i,\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "e93804b1", - "metadata": { - "editable": true - }, - "source": [ - "where $\\langle y_i \\rangle$ is the mean value. Keep in mind also that\n", - "till now we have treated $y_i$ as the exact value. Normally, the\n", - "response (dependent or outcome) variable $y_i$ the outcome of a\n", - "numerical experiment or another type of experiment and is thus only an\n", - "approximation to the true value. It is then always accompanied by an\n", - "error estimate, often limited to a statistical error estimate given by\n", - "the standard deviation discussed earlier. In the discussion here we\n", - "will treat $y_i$ as our exact value for the response variable.\n", - "\n", - "In order to find the parameters $\\beta_i$ we will then minimize the spread of $C(\\boldsymbol{\\beta})$, that is we are going to solve the problem" - ] - }, - { - "cell_type": "markdown", - "id": "e3b2a85a", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "{\\displaystyle \\min_{\\boldsymbol{\\beta}\\in\n", - "{\\mathbb{R}}^{p}}}\\frac{1}{n}\\left\\{\\left(\\boldsymbol{y}-\\boldsymbol{X}\\boldsymbol{\\beta}\\right)^T\\left(\\boldsymbol{y}-\\boldsymbol{X}\\boldsymbol{\\beta}\\right)\\right\\}.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "88b484a0", - "metadata": { - "editable": true - }, - "source": [ - "In practical terms it means we will require" - ] - }, - { - "cell_type": "markdown", - "id": "0cae40f7", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\frac{\\partial C(\\boldsymbol{\\beta})}{\\partial \\beta_j} = \\frac{\\partial }{\\partial \\beta_j}\\left[ \\frac{1}{n}\\sum_{i=0}^{n-1}\\left(y_i-\\beta_0x_{i,0}-\\beta_1x_{i,1}-\\beta_2x_{i,2}-\\dots-\\beta_{n-1}x_{i,n-1}\\right)^2\\right]=0,\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "3e3c19f7", - "metadata": { - "editable": true - }, - "source": [ - "which results in" - ] - }, - { - "cell_type": "markdown", - "id": "c5d9738a", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\frac{\\partial C(\\boldsymbol{\\beta})}{\\partial \\beta_j} = -\\frac{2}{n}\\left[ \\sum_{i=0}^{n-1}x_{ij}\\left(y_i-\\beta_0x_{i,0}-\\beta_1x_{i,1}-\\beta_2x_{i,2}-\\dots-\\beta_{n-1}x_{i,n-1}\\right)\\right]=0,\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "49bf03c8", - "metadata": { - "editable": true - }, - "source": [ - "or in a matrix-vector form as" - ] - }, - { - "cell_type": "markdown", - "id": "acc52e20", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\frac{\\partial C(\\boldsymbol{\\beta})}{\\partial \\boldsymbol{\\beta}} = 0 = \\boldsymbol{X}^T\\left( \\boldsymbol{y}-\\boldsymbol{X}\\boldsymbol{\\beta}\\right).\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "ecfc4d77", - "metadata": { - "editable": true - }, - "source": [ - "## Interpretations and optimizing our parameters\n", - "We can rewrite" - ] - }, - { - "cell_type": "markdown", - "id": "7bc2250b", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\frac{\\partial C(\\boldsymbol{\\beta})}{\\partial \\boldsymbol{\\beta}} = 0 = \\boldsymbol{X}^T\\left( \\boldsymbol{y}-\\boldsymbol{X}\\boldsymbol{\\beta}\\right),\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "3c038483", - "metadata": { - "editable": true - }, - "source": [ - "as" - ] - }, - { - "cell_type": "markdown", - "id": "d530cc8f", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\boldsymbol{X}^T\\boldsymbol{y} = \\boldsymbol{X}^T\\boldsymbol{X}\\boldsymbol{\\beta},\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "667c132f", - "metadata": { - "editable": true - }, - "source": [ - "and if the matrix $\\boldsymbol{X}^T\\boldsymbol{X}$ is invertible we have the solution" - ] - }, - { - "cell_type": "markdown", - "id": "1a592608", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\boldsymbol{\\beta} =\\left(\\boldsymbol{X}^T\\boldsymbol{X}\\right)^{-1}\\boldsymbol{X}^T\\boldsymbol{y}.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "fe968934", - "metadata": { - "editable": true - }, - "source": [ - "We note also that since our design matrix is defined as $\\boldsymbol{X}\\in\n", - "{\\mathbb{R}}^{n\\times p}$, the product $\\boldsymbol{X}^T\\boldsymbol{X} \\in\n", - "{\\mathbb{R}}^{p\\times p}$. In the above case we have that $p \\ll n$,\n", - "in our case $p=5$ meaning that we end up with inverting a small\n", - "$5\\times 5$ matrix. This is a rather common situation, in many cases we end up with low-dimensional\n", - "matrices to invert. The methods discussed here and for many other\n", - "supervised learning algorithms like classification with logistic\n", - "regression or support vector machines, exhibit dimensionalities which\n", - "allow for the usage of direct linear algebra methods such as **LU** decomposition or **Singular Value Decomposition** (SVD) for finding the inverse of the matrix\n", - "$\\boldsymbol{X}^T\\boldsymbol{X}$.\n", - "\n", - "**Small question**: Do you think the example we have at hand here (the nuclear binding energies) can lead to problems in inverting the matrix $\\boldsymbol{X}^T\\boldsymbol{X}$? What kind of problems can we expect?" - ] - }, - { - "cell_type": "markdown", - "id": "f182ccd2", - "metadata": { - "editable": true - }, - "source": [ - "## Some useful matrix and vector expressions\n", - "\n", - "See the handwritten notes at \n", - "\n", - "These notes will be discussed during one of the lectures." - ] - }, - { - "cell_type": "markdown", - "id": "3e23c6ac", - "metadata": { - "editable": true - }, - "source": [ - "## Interpretations and optimizing our parameters\n", - "The residuals $\\boldsymbol{\\epsilon}$ are in turn given by" - ] - }, - { - "cell_type": "markdown", - "id": "2a10b1fa", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\boldsymbol{\\epsilon} = \\boldsymbol{y}-\\boldsymbol{\\tilde{y}} = \\boldsymbol{y}-\\boldsymbol{X}\\boldsymbol{\\beta},\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "753ac3da", - "metadata": { - "editable": true - }, - "source": [ - "and with" - ] - }, - { - "cell_type": "markdown", - "id": "abdc427a", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\boldsymbol{X}^T\\left( \\boldsymbol{y}-\\boldsymbol{X}\\boldsymbol{\\beta}\\right)= 0,\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "a959437a", - "metadata": { - "editable": true - }, - "source": [ - "we have" - ] - }, - { - "cell_type": "markdown", - "id": "764e589a", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\boldsymbol{X}^T\\boldsymbol{\\epsilon}=\\boldsymbol{X}^T\\left( \\boldsymbol{y}-\\boldsymbol{X}\\boldsymbol{\\beta}\\right)= 0,\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "00e50636", - "metadata": { - "editable": true - }, - "source": [ - "meaning that the solution for $\\boldsymbol{\\beta}$ is the one which minimizes the residuals. Later we will link this with the maximum likelihood approach.\n", - "\n", - "Let us now return to our nuclear binding energies and simply code the above equations." - ] - }, - { - "cell_type": "markdown", - "id": "7f1fb52c", - "metadata": { - "editable": true - }, - "source": [ - "## Own code for Ordinary Least Squares\n", - "\n", - "It is rather straightforward to implement the matrix inversion and obtain the parameters $\\boldsymbol{\\beta}$. After having defined the matrix $\\boldsymbol{X}$ we simply need to \n", - "write" - ] - }, - { - "cell_type": "code", - "execution_count": 37, - "id": "6e7ef8e3", - "metadata": { - "collapsed": false, - "editable": true - }, - "outputs": [], - "source": [ - "# matrix inversion to find beta\n", - "beta = np.linalg.inv(X.T.dot(X)).dot(X.T).dot(Energies)\n", - "# and then make the prediction\n", - "ytilde = X @ beta" - ] - }, - { - "cell_type": "markdown", - "id": "e8de20b3", - "metadata": { - "editable": true - }, - "source": [ - "Alternatively, you can use the least squares functionality in **Numpy** as" - ] - }, - { - "cell_type": "code", - "execution_count": 38, - "id": "890c0e17", - "metadata": { - "collapsed": false, - "editable": true - }, - "outputs": [], - "source": [ - "fit = np.linalg.lstsq(X, Energies, rcond =None)[0]\n", - "ytildenp = np.dot(fit,X.T)" - ] - }, - { - "cell_type": "markdown", - "id": "fa46eacd", - "metadata": { - "editable": true - }, - "source": [ - "And finally we plot our fit with and compare with data" - ] - }, - { - "cell_type": "code", - "execution_count": 39, - "id": "dd7bc08b", - "metadata": { - "collapsed": false, - "editable": true - }, - "outputs": [], - "source": [ - "Masses['Eapprox'] = ytilde\n", - "# Generate a plot comparing the experimental with the fitted values values.\n", - "fig, ax = plt.subplots()\n", - "ax.set_xlabel(r'$A = N + Z$')\n", - "ax.set_ylabel(r'$E_\\mathrm{bind}\\,/\\mathrm{MeV}$')\n", - "ax.plot(Masses['A'], Masses['Ebinding'], alpha=0.7, lw=2,\n", - " label='Ame2016')\n", - "ax.plot(Masses['A'], Masses['Eapprox'], alpha=0.7, lw=2, c='m',\n", - " label='Fit')\n", - "ax.legend()\n", - "save_fig(\"Masses2016OLS\")\n", - "plt.show()" - ] - }, - { - "cell_type": "markdown", - "id": "f1dac4cb", - "metadata": { - "editable": true - }, - "source": [ - "## Adding error analysis and training set up\n", - "\n", - "We can easily test our fit by computing the $R2$ score that we discussed in connection with the functionality of **Scikit-Learn** in the introductory slides.\n", - "Since we are not using **Scikit-Learn** here we can define our own $R2$ function as" - ] - }, - { - "cell_type": "code", - "execution_count": 40, - "id": "8253a870", - "metadata": { - "collapsed": false, - "editable": true - }, - "outputs": [], - "source": [ - "def R2(y_data, y_model):\n", - " return 1 - np.sum((y_data - y_model) ** 2) / np.sum((y_data - np.mean(y_data)) ** 2)" - ] - }, - { - "cell_type": "markdown", - "id": "25175ebc", - "metadata": { - "editable": true - }, - "source": [ - "and we would be using it as" - ] - }, - { - "cell_type": "code", - "execution_count": 41, - "id": "4106532b", - "metadata": { - "collapsed": false, - "editable": true - }, - "outputs": [], - "source": [ - "print(R2(Energies,ytilde))" - ] - }, - { - "cell_type": "markdown", - "id": "3ae3cbe1", - "metadata": { - "editable": true - }, - "source": [ - "We can easily add our **MSE** score as" - ] - }, - { - "cell_type": "code", - "execution_count": 42, - "id": "9cbc337d", - "metadata": { - "collapsed": false, - "editable": true - }, - "outputs": [], - "source": [ - "def MSE(y_data,y_model):\n", - " n = np.size(y_model)\n", - " return np.sum((y_data-y_model)**2)/n\n", - "\n", - "print(MSE(Energies,ytilde))" - ] - }, - { - "cell_type": "markdown", - "id": "1f984da0", - "metadata": { - "editable": true - }, - "source": [ - "and finally the relative error as" - ] - }, - { - "cell_type": "code", - "execution_count": 43, - "id": "91777701", - "metadata": { - "collapsed": false, - "editable": true - }, - "outputs": [], - "source": [ - "def RelativeError(y_data,y_model):\n", - " return abs((y_data-y_model)/y_data)\n", - "print(RelativeError(Energies, ytilde))" - ] - }, - { - "cell_type": "markdown", - "id": "f504b559", - "metadata": { - "editable": true - }, - "source": [ - "## The $\\chi^2$ function\n", - "\n", - "Normally, the response (dependent or outcome) variable $y_i$ is the\n", - "outcome of a numerical experiment or another type of experiment and is\n", - "thus only an approximation to the true value. It is then always\n", - "accompanied by an error estimate, often limited to a statistical error\n", - "estimate given by the standard deviation discussed earlier. In the\n", - "discussion here we will treat $y_i$ as our exact value for the\n", - "response variable.\n", - "\n", - "Introducing the standard deviation $\\sigma_i$ for each measurement\n", - "$y_i$, we define now the $\\chi^2$ function (omitting the $1/n$ term)\n", - "as" - ] - }, - { - "cell_type": "markdown", - "id": "67440280", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\chi^2(\\boldsymbol{\\beta})=\\frac{1}{n}\\sum_{i=0}^{n-1}\\frac{\\left(y_i-\\tilde{y}_i\\right)^2}{\\sigma_i^2}=\\frac{1}{n}\\left\\{\\left(\\boldsymbol{y}-\\boldsymbol{\\tilde{y}}\\right)^T\\frac{1}{\\boldsymbol{\\Sigma^2}}\\left(\\boldsymbol{y}-\\boldsymbol{\\tilde{y}}\\right)\\right\\},\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "c5190684", - "metadata": { - "editable": true - }, - "source": [ - "where the matrix $\\boldsymbol{\\Sigma}$ is a diagonal matrix with $\\sigma_i$ as matrix elements." - ] - }, - { - "cell_type": "markdown", - "id": "1b878f0e", - "metadata": { - "editable": true - }, - "source": [ - "## The $\\chi^2$ function\n", - "\n", - "In order to find the parameters $\\beta_i$ we will then minimize the spread of $\\chi^2(\\boldsymbol{\\beta})$ by requiring" - ] - }, - { - "cell_type": "markdown", - "id": "8ab0a4a3", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\frac{\\partial \\chi^2(\\boldsymbol{\\beta})}{\\partial \\beta_j} = \\frac{\\partial }{\\partial \\beta_j}\\left[ \\frac{1}{n}\\sum_{i=0}^{n-1}\\left(\\frac{y_i-\\beta_0x_{i,0}-\\beta_1x_{i,1}-\\beta_2x_{i,2}-\\dots-\\beta_{n-1}x_{i,n-1}}{\\sigma_i}\\right)^2\\right]=0,\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "e9106c8d", - "metadata": { - "editable": true - }, - "source": [ - "which results in" - ] - }, - { - "cell_type": "markdown", - "id": "03c4e9d7", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\frac{\\partial \\chi^2(\\boldsymbol{\\beta})}{\\partial \\beta_j} = -\\frac{2}{n}\\left[ \\sum_{i=0}^{n-1}\\frac{x_{ij}}{\\sigma_i}\\left(\\frac{y_i-\\beta_0x_{i,0}-\\beta_1x_{i,1}-\\beta_2x_{i,2}-\\dots-\\beta_{n-1}x_{i,n-1}}{\\sigma_i}\\right)\\right]=0,\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "0e4abfb1", - "metadata": { - "editable": true - }, - "source": [ - "or in a matrix-vector form as" - ] - }, - { - "cell_type": "markdown", - "id": "45af97a4", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\frac{\\partial \\chi^2(\\boldsymbol{\\beta})}{\\partial \\boldsymbol{\\beta}} = 0 = \\boldsymbol{A}^T\\left( \\boldsymbol{b}-\\boldsymbol{A}\\boldsymbol{\\beta}\\right).\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "9ff2fda9", - "metadata": { - "editable": true - }, - "source": [ - "where we have defined the matrix $\\boldsymbol{A} =\\boldsymbol{X}/\\boldsymbol{\\Sigma}$ with matrix elements $a_{ij} = x_{ij}/\\sigma_i$ and the vector $\\boldsymbol{b}$ with elements $b_i = y_i/\\sigma_i$." - ] - }, - { - "cell_type": "markdown", - "id": "c1593fa5", - "metadata": { - "editable": true - }, - "source": [ - "## The $\\chi^2$ function\n", - "\n", - "We can rewrite" - ] - }, - { - "cell_type": "markdown", - "id": "d34ea7db", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\frac{\\partial \\chi^2(\\boldsymbol{\\beta})}{\\partial \\boldsymbol{\\beta}} = 0 = \\boldsymbol{A}^T\\left( \\boldsymbol{b}-\\boldsymbol{A}\\boldsymbol{\\beta}\\right),\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "699612be", - "metadata": { - "editable": true - }, - "source": [ - "as" - ] - }, - { - "cell_type": "markdown", - "id": "88ae1420", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\boldsymbol{A}^T\\boldsymbol{b} = \\boldsymbol{A}^T\\boldsymbol{A}\\boldsymbol{\\beta},\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "b827d1c6", - "metadata": { - "editable": true - }, - "source": [ - "and if the matrix $\\boldsymbol{A}^T\\boldsymbol{A}$ is invertible we have the solution" - ] - }, - { - "cell_type": "markdown", - "id": "61900168", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\boldsymbol{\\beta} =\\left(\\boldsymbol{A}^T\\boldsymbol{A}\\right)^{-1}\\boldsymbol{A}^T\\boldsymbol{b}.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "eaab94fc", - "metadata": { - "editable": true - }, - "source": [ - "## The $\\chi^2$ function\n", - "\n", - "If we then introduce the matrix" - ] - }, - { - "cell_type": "markdown", - "id": "c8f542a4", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\boldsymbol{H} = \\left(\\boldsymbol{A}^T\\boldsymbol{A}\\right)^{-1},\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "c6e93dd5", - "metadata": { - "editable": true - }, - "source": [ - "we have then the following expression for the parameters $\\beta_j$ (the matrix elements of $\\boldsymbol{H}$ are $h_{ij}$)" - ] - }, - { - "cell_type": "markdown", - "id": "977ca552", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\beta_j = \\sum_{k=0}^{p-1}h_{jk}\\sum_{i=0}^{n-1}\\frac{y_i}{\\sigma_i}\\frac{x_{ik}}{\\sigma_i} = \\sum_{k=0}^{p-1}h_{jk}\\sum_{i=0}^{n-1}b_ia_{ik}\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "ff3c6b13", - "metadata": { - "editable": true - }, - "source": [ - "We state without proof the expression for the uncertainty in the parameters $\\beta_j$ as (we leave this as an exercise)" - ] - }, - { - "cell_type": "markdown", - "id": "ebbb06cf", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\sigma^2(\\beta_j) = \\sum_{i=0}^{n-1}\\sigma_i^2\\left( \\frac{\\partial \\beta_j}{\\partial y_i}\\right)^2,\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "ed6f641e", - "metadata": { - "editable": true - }, - "source": [ - "resulting in" - ] - }, - { - "cell_type": "markdown", - "id": "94c50447", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\sigma^2(\\beta_j) = \\left(\\sum_{k=0}^{p-1}h_{jk}\\sum_{i=0}^{n-1}a_{ik}\\right)\\left(\\sum_{l=0}^{p-1}h_{jl}\\sum_{m=0}^{n-1}a_{ml}\\right) = h_{jj}!\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "caa52732", - "metadata": { - "editable": true - }, - "source": [ - "## The $\\chi^2$ function\n", - "The first step here is to approximate the function $y$ with a first-order polynomial, that is we write" - ] - }, - { - "cell_type": "markdown", - "id": "721f3130", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "y=y(x) \\rightarrow y(x_i) \\approx \\beta_0+\\beta_1 x_i.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "1ecec855", - "metadata": { - "editable": true - }, - "source": [ - "By computing the derivatives of $\\chi^2$ with respect to $\\beta_0$ and $\\beta_1$ show that these are given by" - ] - }, - { - "cell_type": "markdown", - "id": "9f72bcd2", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\frac{\\partial \\chi^2(\\boldsymbol{\\beta})}{\\partial \\beta_0} = -2\\left[ \\frac{1}{n}\\sum_{i=0}^{n-1}\\left(\\frac{y_i-\\beta_0-\\beta_1x_{i}}{\\sigma_i^2}\\right)\\right]=0,\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "952c0807", - "metadata": { - "editable": true - }, - "source": [ - "and" - ] - }, - { - "cell_type": "markdown", - "id": "db7a0783", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\frac{\\partial \\chi^2(\\boldsymbol{\\beta})}{\\partial \\beta_1} = -\\frac{2}{n}\\left[ \\sum_{i=0}^{n-1}x_i\\left(\\frac{y_i-\\beta_0-\\beta_1x_{i}}{\\sigma_i^2}\\right)\\right]=0.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "03a57144", - "metadata": { - "editable": true - }, - "source": [ - "## The $\\chi^2$ function\n", - "\n", - "For a linear fit (a first-order polynomial) we don't need to invert a matrix!! \n", - "Defining" - ] - }, - { - "cell_type": "markdown", - "id": "22e8525a", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\gamma = \\sum_{i=0}^{n-1}\\frac{1}{\\sigma_i^2},\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "e7dc4b83", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\gamma_x = \\sum_{i=0}^{n-1}\\frac{x_{i}}{\\sigma_i^2},\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "5ceab08b", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\gamma_y = \\sum_{i=0}^{n-1}\\left(\\frac{y_i}{\\sigma_i^2}\\right),\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "61608838", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\gamma_{xx} = \\sum_{i=0}^{n-1}\\frac{x_ix_{i}}{\\sigma_i^2},\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "59fd7508", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\gamma_{xy} = \\sum_{i=0}^{n-1}\\frac{y_ix_{i}}{\\sigma_i^2},\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "caca22c4", - "metadata": { - "editable": true - }, - "source": [ - "we obtain" - ] - }, - { - "cell_type": "markdown", - "id": "b459c22c", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\beta_0 = \\frac{\\gamma_{xx}\\gamma_y-\\gamma_x\\gamma_y}{\\gamma\\gamma_{xx}-\\gamma_x^2},\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "3715e857", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\beta_1 = \\frac{\\gamma_{xy}\\gamma-\\gamma_x\\gamma_y}{\\gamma\\gamma_{xx}-\\gamma_x^2}.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "3ad3eeb2", - "metadata": { - "editable": true - }, - "source": [ - "This approach (different linear and non-linear regression) suffers\n", - "often from both being underdetermined and overdetermined in the\n", - "unknown coefficients $\\beta_i$. A better approach is to use the\n", - "Singular Value Decomposition (SVD) method discussed next week." - ] - }, - { - "cell_type": "markdown", - "id": "d8b193ef", - "metadata": { - "editable": true - }, - "source": [ - "## Fitting an Equation of State for Dense Nuclear Matter\n", - "\n", - "Before we continue, let us introduce yet another example. We are going to fit the\n", - "nuclear equation of state using results from many-body calculations.\n", - "The equation of state we have made available here, as function of\n", - "density, has been derived using modern nucleon-nucleon potentials with\n", - "[the addition of three-body\n", - "forces](https://www.sciencedirect.com/science/article/pii/S0370157399001106). This\n", - "time the file is presented as a standard **csv** file.\n", - "\n", - "The beginning of the Python code here is similar to what you have seen\n", - "before, with the same initializations and declarations. We use also\n", - "**pandas** again, rather extensively in order to organize our data.\n", - "\n", - "The difference now is that we use **Scikit-Learn's** regression tools\n", - "instead of our own matrix inversion implementation. Furthermore, we\n", - "sneak in **Ridge** regression (to be discussed below) which includes a\n", - "hyperparameter $\\lambda$, also to be explained below." - ] - }, - { - "cell_type": "markdown", - "id": "11007882", - "metadata": { - "editable": true - }, - "source": [ - "## The code" - ] - }, - { - "cell_type": "code", - "execution_count": 44, - "id": "ee8cdde5", - "metadata": { - "collapsed": false, - "editable": true - }, - "outputs": [], - "source": [ - "# Common imports\n", - "import os\n", - "import numpy as np\n", - "import pandas as pd\n", - "import matplotlib.pyplot as plt\n", - "import matplotlib.pyplot as plt\n", - "import sklearn.linear_model as skl\n", - "from sklearn.metrics import mean_squared_error, r2_score, mean_absolute_error\n", - "\n", - "# Where to save the figures and data files\n", - "PROJECT_ROOT_DIR = \"Results\"\n", - "FIGURE_ID = \"Results/FigureFiles\"\n", - "DATA_ID = \"DataFiles/\"\n", - "\n", - "if not os.path.exists(PROJECT_ROOT_DIR):\n", - " os.mkdir(PROJECT_ROOT_DIR)\n", - "\n", - "if not os.path.exists(FIGURE_ID):\n", - " os.makedirs(FIGURE_ID)\n", - "\n", - "if not os.path.exists(DATA_ID):\n", - " os.makedirs(DATA_ID)\n", - "\n", - "def image_path(fig_id):\n", - " return os.path.join(FIGURE_ID, fig_id)\n", - "\n", - "def data_path(dat_id):\n", - " return os.path.join(DATA_ID, dat_id)\n", - "\n", - "def save_fig(fig_id):\n", - " plt.savefig(image_path(fig_id) + \".png\", format='png')\n", - "\n", - "infile = open(data_path(\"EoS.csv\"),'r')\n", - "\n", - "# Read the EoS data as csv file and organize the data into two arrays with density and energies\n", - "EoS = pd.read_csv(infile, names=('Density', 'Energy'))\n", - "EoS['Energy'] = pd.to_numeric(EoS['Energy'], errors='coerce')\n", - "EoS = EoS.dropna()\n", - "Energies = EoS['Energy']\n", - "Density = EoS['Density']\n", - "# The design matrix now as function of various polytrops\n", - "X = np.zeros((len(Density),4))\n", - "X[:,3] = Density**(4.0/3.0)\n", - "X[:,2] = Density\n", - "X[:,1] = Density**(2.0/3.0)\n", - "X[:,0] = 1\n", - "\n", - "# We use now Scikit-Learn's linear regressor and ridge regressor\n", - "# OLS part\n", - "clf = skl.LinearRegression().fit(X, Energies)\n", - "ytilde = clf.predict(X)\n", - "EoS['Eols'] = ytilde\n", - "# The mean squared error \n", - "print(\"Mean squared error: %.2f\" % mean_squared_error(Energies, ytilde))\n", - "# Explained variance score: 1 is perfect prediction \n", - "print('Variance score: %.2f' % r2_score(Energies, ytilde))\n", - "# Mean absolute error \n", - "print('Mean absolute error: %.2f' % mean_absolute_error(Energies, ytilde))\n", - "print(clf.coef_, clf.intercept_)\n", - "\n", - "# The Ridge regression with a hyperparameter lambda = 0.1\n", - "_lambda = 0.1\n", - "clf_ridge = skl.Ridge(alpha=_lambda).fit(X, Energies)\n", - "yridge = clf_ridge.predict(X)\n", - "EoS['Eridge'] = yridge\n", - "# The mean squared error \n", - "print(\"Mean squared error: %.2f\" % mean_squared_error(Energies, yridge))\n", - "# Explained variance score: 1 is perfect prediction \n", - "print('Variance score: %.2f' % r2_score(Energies, yridge))\n", - "# Mean absolute error \n", - "print('Mean absolute error: %.2f' % mean_absolute_error(Energies, yridge))\n", - "print(clf_ridge.coef_, clf_ridge.intercept_)\n", - "\n", - "fig, ax = plt.subplots()\n", - "ax.set_xlabel(r'$\\rho[\\mathrm{fm}^{-3}]$')\n", - "ax.set_ylabel(r'Energy per particle')\n", - "ax.plot(EoS['Density'], EoS['Energy'], alpha=0.7, lw=2,\n", - " label='Theoretical data')\n", - "ax.plot(EoS['Density'], EoS['Eols'], alpha=0.7, lw=2, c='m',\n", - " label='OLS')\n", - "ax.plot(EoS['Density'], EoS['Eridge'], alpha=0.7, lw=2, c='g',\n", - " label='Ridge $\\lambda = 0.1$')\n", - "ax.legend()\n", - "save_fig(\"EoSfitting\")\n", - "plt.show()" - ] - }, - { - "cell_type": "markdown", - "id": "1ea53cff", - "metadata": { - "editable": true - }, - "source": [ - "The above simple polynomial in density $\\rho$ gives an excellent fit\n", - "to the data. \n", - "\n", - "We note also that there is a small deviation between the\n", - "standard OLS and the Ridge regression at higher densities. We discuss this in more detail\n", - "below." - ] - }, - { - "cell_type": "markdown", - "id": "4d725567", - "metadata": { - "editable": true - }, - "source": [ - "## Splitting our Data in Training and Test data\n", - "\n", - "It is normal in essentially all Machine Learning studies to split the\n", - "data in a training set and a test set (sometimes also an additional\n", - "validation set). **Scikit-Learn** has an own function for this. There\n", - "is no explicit recipe for how much data should be included as training\n", - "data and say test data. An accepted rule of thumb is to use\n", - "approximately $2/3$ to $4/5$ of the data as training data. We will\n", - "postpone a discussion of this splitting to the end of these notes and\n", - "our discussion of the so-called **bias-variance** tradeoff. Here we\n", - "limit ourselves to repeat the above equation of state fitting example\n", - "but now splitting the data into a training set and a test set." - ] - }, - { - "cell_type": "code", - "execution_count": 45, - "id": "aa6446c1", - "metadata": { - "collapsed": false, - "editable": true - }, - "outputs": [], - "source": [ - "import os\n", - "import numpy as np\n", - "import pandas as pd\n", - "import matplotlib.pyplot as plt\n", - "from sklearn.model_selection import train_test_split\n", - "# Where to save the figures and data files\n", - "PROJECT_ROOT_DIR = \"Results\"\n", - "FIGURE_ID = \"Results/FigureFiles\"\n", - "DATA_ID = \"DataFiles/\"\n", - "\n", - "if not os.path.exists(PROJECT_ROOT_DIR):\n", - " os.mkdir(PROJECT_ROOT_DIR)\n", - "\n", - "if not os.path.exists(FIGURE_ID):\n", - " os.makedirs(FIGURE_ID)\n", - "\n", - "if not os.path.exists(DATA_ID):\n", - " os.makedirs(DATA_ID)\n", - "\n", - "def image_path(fig_id):\n", - " return os.path.join(FIGURE_ID, fig_id)\n", - "\n", - "def data_path(dat_id):\n", - " return os.path.join(DATA_ID, dat_id)\n", - "\n", - "def save_fig(fig_id):\n", - " plt.savefig(image_path(fig_id) + \".png\", format='png')\n", - "\n", - "def R2(y_data, y_model):\n", - " return 1 - np.sum((y_data - y_model) ** 2) / np.sum((y_data - np.mean(y_data)) ** 2)\n", - "def MSE(y_data,y_model):\n", - " n = np.size(y_model)\n", - " return np.sum((y_data-y_model)**2)/n\n", - "\n", - "infile = open(data_path(\"EoS.csv\"),'r')\n", - "\n", - "# Read the EoS data as csv file and organized into two arrays with density and energies\n", - "EoS = pd.read_csv(infile, names=('Density', 'Energy'))\n", - "EoS['Energy'] = pd.to_numeric(EoS['Energy'], errors='coerce')\n", - "EoS = EoS.dropna()\n", - "Energies = EoS['Energy']\n", - "Density = EoS['Density']\n", - "# The design matrix now as function of various polytrops\n", - "X = np.zeros((len(Density),5))\n", - "X[:,0] = 1\n", - "X[:,1] = Density**(2.0/3.0)\n", - "X[:,2] = Density\n", - "X[:,3] = Density**(4.0/3.0)\n", - "X[:,4] = Density**(5.0/3.0)\n", - "# We split the data in test and training data\n", - "X_train, X_test, y_train, y_test = train_test_split(X, Energies, test_size=0.2)\n", - "# matrix inversion to find beta\n", - "beta = np.linalg.inv(X_train.T.dot(X_train)).dot(X_train.T).dot(y_train)\n", - "# and then make the prediction\n", - "ytilde = X_train @ beta\n", - "print(\"Training R2\")\n", - "print(R2(y_train,ytilde))\n", - "print(\"Training MSE\")\n", - "print(MSE(y_train,ytilde))\n", - "ypredict = X_test @ beta\n", - "print(\"Test R2\")\n", - "print(R2(y_test,ypredict))\n", - "print(\"Test MSE\")\n", - "print(MSE(y_test,ypredict))" - ] - }, - { - "cell_type": "markdown", - "id": "7b772723", - "metadata": { - "editable": true - }, - "source": [ - "## Exercises\n", - "\n", - "Here are three possible exercises for week 34" - ] - }, - { - "cell_type": "markdown", - "id": "3cf1d40f", - "metadata": { - "editable": true - }, - "source": [ - "## Exercise 1: Setting up various Python environments\n", - "\n", - "The first exercise here is of a mere technical art. We want you to have \n", - "* git as a version control software and to establish a user account on a provider like GitHub. Other providers like GitLab etc are equally fine. You can also use the University of Oslo [GitHub facilities](https://www.uio.no/tjenester/it/maskin/filer/versjonskontroll/github.html). \n", - "\n", - "* Install various Python packages\n", - "\n", - "We will make extensive use of Python as programming language and its\n", - "myriad of available libraries. You will find\n", - "IPython/Jupyter notebooks invaluable in your work. You can run **R**\n", - "codes in the Jupyter/IPython notebooks, with the immediate benefit of\n", - "visualizing your data. You can also use compiled languages like C++,\n", - "Rust, Fortran etc if you prefer. The focus in these lectures will be\n", - "on Python.\n", - "\n", - "If you have Python installed (we recommend Python3) and you feel\n", - "pretty familiar with installing different packages, we recommend that\n", - "you install the following Python packages via **pip** as \n", - "\n", - "1. pip install numpy scipy matplotlib ipython scikit-learn sympy pandas pillow \n", - "\n", - "For **Tensorflow**, we recommend following the instructions in the text of \n", - "[Aurelien Geron, Hands‑On Machine Learning with Scikit‑Learn and TensorFlow, O'Reilly](http://shop.oreilly.com/product/0636920052289.do)\n", - "\n", - "We will come back to **tensorflow** later. \n", - "\n", - "For Python3, replace **pip** with **pip3**.\n", - "\n", - "For OSX users we recommend, after having installed Xcode, to\n", - "install **brew**. Brew allows for a seamless installation of additional\n", - "software via for example \n", - "\n", - "1. brew install python3\n", - "\n", - "For Linux users, with its variety of distributions like for example the widely popular Ubuntu distribution,\n", - "you can use **pip** as well and simply install Python as \n", - "\n", - "1. sudo apt-get install python3 (or python for Python2.7)\n", - "\n", - "If you don't want to perform these operations separately and venture\n", - "into the hassle of exploring how to set up dependencies and paths, we\n", - "recommend two widely used distrubutions which set up all relevant\n", - "dependencies for Python, namely \n", - "\n", - "* [Anaconda](https://docs.anaconda.com/), \n", - "\n", - "which is an open source\n", - "distribution of the Python and R programming languages for large-scale\n", - "data processing, predictive analytics, and scientific computing, that\n", - "aims to simplify package management and deployment. Package versions\n", - "are managed by the package management system **conda**. \n", - "\n", - "* [Enthought canopy](https://www.enthought.com/product/canopy/) \n", - "\n", - "is a Python\n", - "distribution for scientific and analytic computing distribution and\n", - "analysis environment, available for free and under a commercial\n", - "license.\n", - "\n", - "We recommend using **Anaconda** if you are not too familiar with setting paths in a terminal environment." - ] - }, - { - "cell_type": "markdown", - "id": "59288b2d", - "metadata": { - "editable": true - }, - "source": [ - "## Exercise 2: making your own data and exploring scikit-learn\n", - "\n", - "We will generate our own dataset for a function $y(x)$ where $x \\in [0,1]$ and defined by random numbers computed with the uniform distribution. The function $y$ is a quadratic polynomial in $x$ with added stochastic noise according to the normal distribution $\\cal {N}(0,1)$.\n", - "The following simple Python instructions define our $x$ and $y$ values (with 100 data points)." - ] - }, - { - "cell_type": "code", - "execution_count": 46, - "id": "f06dd2f8", - "metadata": { - "collapsed": false, - "editable": true - }, - "outputs": [], - "source": [ - "x = np.random.rand(100,1)\n", - "y = 2.0+5*x*x+0.1*np.random.randn(100,1)" - ] - }, - { - "cell_type": "markdown", - "id": "21171361", - "metadata": { - "editable": true - }, - "source": [ - "1. Write your own code (following the examples under the [regression notes](https://compphysics.github.io/MachineLearning/doc/LectureNotes/_build/html/chapter1.html)) for computing the parametrization of the data set fitting a second-order polynomial. \n", - "\n", - "2. Use thereafter **scikit-learn** (see again the examples in the regression slides) and compare with your own code. \n", - "\n", - "3. Using scikit-learn, compute also the mean square error, a risk metric corresponding to the expected value of the squared (quadratic) error defined as" - ] - }, - { - "cell_type": "markdown", - "id": "0389374f", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "MSE(\\boldsymbol{y},\\boldsymbol{\\tilde{y}}) = \\frac{1}{n}\n", - "\\sum_{i=0}^{n-1}(y_i-\\tilde{y}_i)^2,\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "e85ae9f5", - "metadata": { - "editable": true - }, - "source": [ - "and the $R^2$ score function.\n", - "If $\\tilde{\\boldsymbol{y}}_i$ is the predicted value of the $i-th$ sample and $y_i$ is the corresponding true value, then the score $R^2$ is defined as" - ] - }, - { - "cell_type": "markdown", - "id": "6eac8058", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "R^2(\\boldsymbol{y}, \\tilde{\\boldsymbol{y}}) = 1 - \\frac{\\sum_{i=0}^{n - 1} (y_i - \\tilde{y}_i)^2}{\\sum_{i=0}^{n - 1} (y_i - \\bar{y})^2},\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "c9d88838", - "metadata": { - "editable": true - }, - "source": [ - "where we have defined the mean value of $\\boldsymbol{y}$ as" - ] - }, - { - "cell_type": "markdown", - "id": "4a767648", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\bar{y} = \\frac{1}{n} \\sum_{i=0}^{n - 1} y_i.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "3b1a7735", - "metadata": { - "editable": true - }, - "source": [ - "You can use the functionality included in scikit-learn. If you feel for it, you can use your own program and define functions which compute the above two functions. \n", - "Discuss the meaning of these results. Try also to vary the coefficient in front of the added stochastic noise term and discuss the quality of the fits." - ] - }, - { - "cell_type": "markdown", - "id": "8c8ad214", - "metadata": { - "editable": true - }, - "source": [ - "## Exercise 3: Split data in test and training data\n", - "\n", - "In this exercise we want you to to compute the MSE for the training\n", - "data and the test data as function of the complexity of a polynomial,\n", - "that is the degree of a given polynomial.\n", - "\n", - "The aim is to reproduce Figure 2.11 of [Hastie et al](https://github.com/CompPhysics/MLErasmus/blob/master/doc/Textbooks/elementsstat.pdf).\n", - "\n", - "Our data is defined by $x\\in [-3,3]$ with a total of for example $n=100$ data points. You should try to vary the number of data points $n$ in your analysis." - ] - }, - { - "cell_type": "code", - "execution_count": 47, - "id": "43caea5f", - "metadata": { - "collapsed": false, - "editable": true - }, - "outputs": [], - "source": [ - "np.random.seed()\n", - "n = 100\n", - "# Make data set.\n", - "x = np.linspace(-3, 3, n).reshape(-1, 1)\n", - "y = np.exp(-x**2) + 1.5 * np.exp(-(x-2)**2)+ np.random.normal(0, 0.1, x.shape)" - ] - }, - { - "cell_type": "markdown", - "id": "9c604beb", - "metadata": { - "editable": true - }, - "source": [ - "where $y$ is the function we want to fit with a given polynomial." - ] - }, - { - "cell_type": "markdown", - "id": "519328d9", - "metadata": { - "editable": true - }, - "source": [ - "**a)**\n", - "Write a first code which sets up a design matrix $X$ defined by a fifth-order polynomial and split your data set in training and test data." - ] - }, - { - "cell_type": "markdown", - "id": "3fdc48c8", - "metadata": { - "editable": true - }, - "source": [ - "**b)**\n", - "Write thereafter (using either **scikit-learn** or your matrix inversion code using for example **numpy**)\n", - "and perform an ordinary least squares fitting and compute the mean squared error for the training data and the test data. These calculations should apply to a model given by a fifth-order polynomial." - ] - }, - { - "cell_type": "markdown", - "id": "e6774cc5", - "metadata": { - "editable": true - }, - "source": [ - "**c)**\n", - "Add now a model which allows you to make polynomials up to degree $15$. Perform a standard OLS fitting of the training data and compute the MSE for the training and test data and plot both test and training data MSE as functions of the polynomial degree. Compare what you see with Figure 2.11 of Hastie et al. Comment your results. For which polynomial degree do you find an optimal MSE (smallest value)?" - ] - } - ], - "metadata": {}, - "nbformat": 4, - "nbformat_minor": 5 -} diff --git a/doc/LectureNotes/week35.ipynb b/doc/LectureNotes/week35.ipynb deleted file mode 100644 index 756f23c0b..000000000 --- a/doc/LectureNotes/week35.ipynb +++ /dev/null @@ -1,6044 +0,0 @@ -{ - "cells": [ - { - "cell_type": "markdown", - "id": "82630256", - "metadata": { - "editable": true - }, - "source": [ - "\n", - "" - ] - }, - { - "cell_type": "markdown", - "id": "342c9c77", - "metadata": { - "editable": true - }, - "source": [ - "# Week 35: From Ordinary Linear Regression to Ridge and Lasso Regression\n", - "**Morten Hjorth-Jensen**, Department of Physics, University of Oslo and Department of Physics and Astronomy and National Superconducting Cyclotron Laboratory, Michigan State University\n", - "\n", - "Date: **August 28-September 1**" - ] - }, - { - "cell_type": "markdown", - "id": "8d89c4f2", - "metadata": { - "editable": true - }, - "source": [ - "## Plans for week 35\n", - "\n", - "The main topics are:\n", - "\n", - "1. Brief repetition from last week\n", - "\n", - "2. Derivation of the equations for ordinary least squares\n", - "\n", - "3. Discussion on how to prepare data and examples of applications of linear regression\n", - "\n", - "4. Material for the lecture on Thursday: Mathematical interpretations of linear regression\n", - "\n", - "5. Thursday: Ridge and Lasso regression and Singular Value Decomposition\n", - "\n", - "6. [Video of lecture](https://youtu.be/qBNm-HGSxL4)\n", - "\n", - "7. [Whiteboard notes](https://github.com/CompPhysics/MachineLearning/blob/master/doc/HandWrittenNotes/2023/NotesAug31.pdf)" - ] - }, - { - "cell_type": "markdown", - "id": "4dc0b391", - "metadata": { - "editable": true - }, - "source": [ - "### Reading recommendations:\n", - "\n", - "1. See lecture notes for week 35 at \n", - "\n", - "2. Goodfellow, Bengio and Courville, Deep Learning, chapter 2 on linear algebra and sections 3.1-3.10 on elements of statistics (background)\n", - "\n", - "3. Hastie, Tibshirani and Friedman, The elements of statistical learning, sections 3.1-3.4 (on relevance for the discussion of linear regression)." - ] - }, - { - "cell_type": "markdown", - "id": "22518518", - "metadata": { - "editable": true - }, - "source": [ - "## Why Linear Regression (aka Ordinary Least Squares and family), repeat from last week\n", - "\n", - "We need first a reminder from last week about linear regression. \n", - "\n", - "Fitting a continuous function with linear parameterization in terms of the parameters $\\boldsymbol{\\beta}$.\n", - "* Method of choice for fitting a continuous function!\n", - "\n", - "* Gives an excellent introduction to central Machine Learning features with **understandable pedagogical** links to other methods like **Neural Networks**, **Support Vector Machines** etc\n", - "\n", - "* Analytical expression for the fitting parameters $\\boldsymbol{\\beta}$\n", - "\n", - "* Analytical expressions for statistical propertiers like mean values, variances, confidence intervals and more\n", - "\n", - "* Analytical relation with probabilistic interpretations \n", - "\n", - "* Easy to introduce basic concepts like bias-variance tradeoff, cross-validation, resampling and regularization techniques and many other ML topics\n", - "\n", - "* Easy to code! And links well with classification problems and logistic regression and neural networks\n", - "\n", - "* Allows for **easy** hands-on understanding of gradient descent methods\n", - "\n", - "* and many more features\n", - "\n", - "For more discussions of Ridge and Lasso regression, [Wessel van Wieringen's](https://arxiv.org/abs/1509.09169) article is highly recommended.\n", - "Similarly, [Mehta et al's article](https://arxiv.org/abs/1803.08823) is also recommended." - ] - }, - { - "cell_type": "markdown", - "id": "40a10f3c", - "metadata": { - "editable": true - }, - "source": [ - "## The equations for ordinary least squares\n", - "\n", - "Our data which we want to apply a machine learning method on, consist\n", - "of a set of inputs $\\boldsymbol{x}^T=[x_0,x_1,x_2,\\dots,x_{n-1}]$ and the\n", - "outputs we want to model $\\boldsymbol{y}^T=[y_0,y_1,y_2,\\dots,y_{n-1}]$.\n", - "We assume that the output data can be represented (for a regression case) by a continuous function $f$\n", - "through" - ] - }, - { - "cell_type": "markdown", - "id": "76f1c739", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "y_i=f(x_i)+\\epsilon_i,\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "2710298f", - "metadata": { - "editable": true - }, - "source": [ - "or in general" - ] - }, - { - "cell_type": "markdown", - "id": "f1e8bd8f", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\boldsymbol{y}=f(\\boldsymbol{x})+\\boldsymbol{\\epsilon},\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "79e795b0", - "metadata": { - "editable": true - }, - "source": [ - "where $\\boldsymbol{\\epsilon}$ represents some noise which is normally assumed to\n", - "be distributed via a normal probability distribution with zero mean\n", - "value and a variance $\\sigma^2$.\n", - "\n", - "In linear regression we approximate the unknown function with another\n", - "continuous function $\\tilde{\\boldsymbol{y}}(\\boldsymbol{x})$ which depends linearly on\n", - "some unknown parameters\n", - "$\\boldsymbol{\\beta}^T=[\\beta_0,\\beta_1,\\beta_2,\\dots,\\beta_{p-1}]$.\n", - "\n", - "Last week we introduced the so-called design matrix in order to define\n", - "the approximation $\\boldsymbol{\\tilde{y}}$ via the unknown quantity\n", - "$\\boldsymbol{\\beta}$ as" - ] - }, - { - "cell_type": "markdown", - "id": "c868570e", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\boldsymbol{\\tilde{y}}= \\boldsymbol{X}\\boldsymbol{\\beta},\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "855e1dbf", - "metadata": { - "editable": true - }, - "source": [ - "and in order to find the optimal parameters $\\beta_i$ we defined a function which\n", - "gives a measure of the spread between the values $y_i$ (which\n", - "represent the output values we want to reproduce) and the parametrized\n", - "values $\\tilde{y}_i$, namely the so-called cost/loss function." - ] - }, - { - "cell_type": "markdown", - "id": "e76339ee", - "metadata": { - "editable": true - }, - "source": [ - "## The cost/loss function\n", - "\n", - "We used the mean squared error to define the way we measure the quality of our model" - ] - }, - { - "cell_type": "markdown", - "id": "706dd49c", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "C(\\boldsymbol{\\beta})=\\frac{1}{n}\\sum_{i=0}^{n-1}\\left(y_i-\\tilde{y}_i\\right)^2=\\frac{1}{n}\\left\\{\\left(\\boldsymbol{y}-\\boldsymbol{\\tilde{y}}\\right)^T\\left(\\boldsymbol{y}-\\boldsymbol{\\tilde{y}}\\right)\\right\\},\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "d068e28e", - "metadata": { - "editable": true - }, - "source": [ - "or using the matrix $\\boldsymbol{X}$ and in a more compact matrix-vector notation as" - ] - }, - { - "cell_type": "markdown", - "id": "bb734579", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "C(\\boldsymbol{\\beta})=\\frac{1}{n}\\left\\{\\left(\\boldsymbol{y}-\\boldsymbol{X}\\boldsymbol{\\beta}\\right)^T\\left(\\boldsymbol{y}-\\boldsymbol{X}\\boldsymbol{\\beta}\\right)\\right\\}.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "aba5029f", - "metadata": { - "editable": true - }, - "source": [ - "This function represents one of many possible ways to define the so-called cost function.\n", - "\n", - "It is also common to define\n", - "the function $C$ as" - ] - }, - { - "cell_type": "markdown", - "id": "6ac8d12b", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "C(\\boldsymbol{\\beta})=\\frac{1}{2n}\\sum_{i=0}^{n-1}\\left(y_i-\\tilde{y}_i\\right)^2,\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "7d3ac82a", - "metadata": { - "editable": true - }, - "source": [ - "since when taking the first derivative with respect to the unknown parameters $\\beta$, the factor of $2$ cancels out." - ] - }, - { - "cell_type": "markdown", - "id": "1eedadb6", - "metadata": { - "editable": true - }, - "source": [ - "## Interpretations and optimizing our parameters\n", - "\n", - "The function" - ] - }, - { - "cell_type": "markdown", - "id": "61c29b5e", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "C(\\boldsymbol{\\beta})=\\frac{1}{n}\\left\\{\\left(\\boldsymbol{y}-\\boldsymbol{X}\\boldsymbol{\\beta}\\right)^T\\left(\\boldsymbol{y}-\\boldsymbol{X}\\boldsymbol{\\beta}\\right)\\right\\},\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "4cf9eba7", - "metadata": { - "editable": true - }, - "source": [ - "can be linked to the variance of the quantity $y_i$ if we interpret the latter as the mean value. \n", - "When linking (see the discussions next week) with the maximum likelihood approach below, we will indeed interpret $y_i$ as a mean value" - ] - }, - { - "cell_type": "markdown", - "id": "0761eee3", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "y_{i}=\\langle y_i \\rangle = \\beta_0x_{i,0}+\\beta_1x_{i,1}+\\beta_2x_{i,2}+\\dots+\\beta_{n-1}x_{i,n-1}+\\epsilon_i,\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "ead917bf", - "metadata": { - "editable": true - }, - "source": [ - "where $\\langle y_i \\rangle$ is the mean value. Keep in mind also that\n", - "till now we have treated $y_i$ as the exact value. Normally, the\n", - "response (dependent or outcome) variable $y_i$ is the outcome of a\n", - "numerical experiment or another type of experiment and could thus be treated itself as an\n", - "approximation to the true value. It is then always accompanied by an\n", - "error estimate, often limited to a statistical error estimate given by\n", - "the standard deviation discussed earlier. In the discussion here we\n", - "will treat $y_i$ as our exact value for the response variable.\n", - "\n", - "In order to find the parameters $\\beta_i$ we will then minimize the spread of $C(\\boldsymbol{\\beta})$, that is we are going to solve the problem" - ] - }, - { - "cell_type": "markdown", - "id": "92fe0780", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "{\\displaystyle \\min_{\\boldsymbol{\\beta}\\in\n", - "{\\mathbb{R}}^{p}}}\\frac{1}{n}\\left\\{\\left(\\boldsymbol{y}-\\boldsymbol{X}\\boldsymbol{\\beta}\\right)^T\\left(\\boldsymbol{y}-\\boldsymbol{X}\\boldsymbol{\\beta}\\right)\\right\\}.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "396bf1e2", - "metadata": { - "editable": true - }, - "source": [ - "In practical terms it means we will require" - ] - }, - { - "cell_type": "markdown", - "id": "6d5307de", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\frac{\\partial C(\\boldsymbol{\\beta})}{\\partial \\beta_j} = \\frac{\\partial }{\\partial \\beta_j}\\left[ \\frac{1}{n}\\sum_{i=0}^{n-1}\\left(y_i-\\beta_0x_{i,0}-\\beta_1x_{i,1}-\\beta_2x_{i,2}-\\dots-\\beta_{n-1}x_{i,n-1}\\right)^2\\right]=0,\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "45b68b6b", - "metadata": { - "editable": true - }, - "source": [ - "which results in" - ] - }, - { - "cell_type": "markdown", - "id": "8bec3f2b", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\frac{\\partial C(\\boldsymbol{\\beta})}{\\partial \\beta_j} = -\\frac{2}{n}\\left[ \\sum_{i=0}^{n-1}x_{ij}\\left(y_i-\\beta_0x_{i,0}-\\beta_1x_{i,1}-\\beta_2x_{i,2}-\\dots-\\beta_{n-1}x_{i,n-1}\\right)\\right]=0,\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "80dc90da", - "metadata": { - "editable": true - }, - "source": [ - "or in a matrix-vector form as (multiplying away the factor $-2/n$, see derivation below)" - ] - }, - { - "cell_type": "markdown", - "id": "64e3c687", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\frac{\\partial C(\\boldsymbol{\\beta})}{\\partial \\boldsymbol{\\beta}^T} = 0 = \\boldsymbol{X}^T\\left( \\boldsymbol{y}-\\boldsymbol{X}\\boldsymbol{\\beta}\\right).\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "510d4d4c", - "metadata": { - "editable": true - }, - "source": [ - "## Interpretations and optimizing our parameters\n", - "We can rewrite, see the derivations below," - ] - }, - { - "cell_type": "markdown", - "id": "f0b1c164", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\frac{\\partial C(\\boldsymbol{\\beta})}{\\partial \\boldsymbol{\\beta}^T} = 0 = \\boldsymbol{X}^T\\left( \\boldsymbol{y}-\\boldsymbol{X}\\boldsymbol{\\beta}\\right),\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "05896ad6", - "metadata": { - "editable": true - }, - "source": [ - "as" - ] - }, - { - "cell_type": "markdown", - "id": "bfa041c9", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\boldsymbol{X}^T\\boldsymbol{y} = \\boldsymbol{X}^T\\boldsymbol{X}\\boldsymbol{\\beta},\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "ae4e69aa", - "metadata": { - "editable": true - }, - "source": [ - "and if the matrix $\\boldsymbol{X}^T\\boldsymbol{X}$ is invertible we have the solution" - ] - }, - { - "cell_type": "markdown", - "id": "22a53165", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\boldsymbol{\\beta} =\\left(\\boldsymbol{X}^T\\boldsymbol{X}\\right)^{-1}\\boldsymbol{X}^T\\boldsymbol{y}.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "02a2b1b8", - "metadata": { - "editable": true - }, - "source": [ - "We note also that since our design matrix is defined as $\\boldsymbol{X}\\in\n", - "{\\mathbb{R}}^{n\\times p}$, the product $\\boldsymbol{X}^T\\boldsymbol{X} \\in\n", - "{\\mathbb{R}}^{p\\times p}$. In most cases we have that $p \\ll n$. In our example case below we have $p=5$ meaning. We end up with inverting a small\n", - "$5\\times 5$ matrix. This is a rather common situation, in many cases we end up with low-dimensional\n", - "matrices to invert. The methods discussed here and for many other\n", - "supervised learning algorithms like classification with logistic\n", - "regression or support vector machines, exhibit dimensionalities which\n", - "allow for the usage of direct linear algebra methods such as **LU** decomposition or **Singular Value Decomposition** (SVD) for finding the inverse of the matrix\n", - "$\\boldsymbol{X}^T\\boldsymbol{X}$. This is discussed on Thursday this week.\n", - "\n", - "**Small question**: Do you think the example we have at hand here (the nuclear binding energies) can lead to problems in inverting the matrix $\\boldsymbol{X}^T\\boldsymbol{X}$? What kind of problems can we expect?" - ] - }, - { - "cell_type": "markdown", - "id": "d1470cae", - "metadata": { - "editable": true - }, - "source": [ - "## Some useful matrix and vector expressions\n", - "\n", - "The following matrix and vector relation will be useful here and for\n", - "the rest of the course. Vectors are always written as boldfaced lower\n", - "case letters and matrices as upper case boldfaced letters. In the\n", - "following we will discuss how to calculate derivatives of various\n", - "matrices relevant for machine learning. We will often represent our\n", - "data in terms of matrices and vectors.\n", - "\n", - "Let us introduce first some conventions. We assume that $\\boldsymbol{y}$ is a\n", - "vector of length $m$, that is it has $m$ elements $y_0,y_1,\\dots,\n", - "y_{m-1}$. By convention we start labeling vectors with the zeroth\n", - "element, as are arrays in Python and C++/C, for example. Similarly, we\n", - "have a vector $\\boldsymbol{x}$ of length $n$, that is\n", - "$\\boldsymbol{x}^T=[x_0,x_1,\\dots, x_{n-1}]$.\n", - "\n", - "We assume also that $\\boldsymbol{y}$ is a function of $\\boldsymbol{x}$ through some\n", - "given function $f$" - ] - }, - { - "cell_type": "markdown", - "id": "fbc63e64", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\boldsymbol{y}=f(\\boldsymbol{x}).\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "5475f4f0", - "metadata": { - "editable": true - }, - "source": [ - "## The Jacobian\n", - "\n", - "We define the partial derivatives of the various components of $\\boldsymbol{y}$ as functions of $x_i$ in terms of the so-called [Jacobian matrix](https://en.wikipedia.org/wiki/Jacobian_matrix_and_determinant)" - ] - }, - { - "cell_type": "markdown", - "id": "7ccd0445", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\boldsymbol{J}=\\frac{\\partial \\boldsymbol{y}}{\\partial \\boldsymbol{x}}=\\begin{bmatrix} \\frac{\\partial y_0}{\\partial x_0} & \\frac{\\partial y_0}{\\partial x_1} & \\frac{\\partial y_0}{\\partial x_2} & \\dots & \\dots & \\frac{\\partial y_0}{\\partial x_{n-1}} \\\\ \\frac{\\partial y_1}{\\partial x_0} & \\frac{\\partial y_1}{\\partial x_1} & \\frac{\\partial y_1}{\\partial x_2} & \\dots & \\dots & \\frac{\\partial y_1}{\\partial x_{n-1}} \\\\\n", - "\\frac{\\partial y_2}{\\partial x_0} & \\frac{\\partial y_2}{\\partial x_1} & \\frac{\\partial y_2}{\\partial x_2} & \\dots & \\dots & \\frac{\\partial y_2}{\\partial x_{n-1}} \\\\\n", - "\\dots & \\dots & \\dots & \\dots & \\dots & \\dots \\\\\n", - "\\dots & \\dots & \\dots & \\dots & \\dots & \\dots \\\\\n", - "\\frac{\\partial y_{m-1}}{\\partial x_0} & \\frac{\\partial y_{m-1}}{\\partial x_1} & \\frac{\\partial y_{m-1}}{\\partial x_2} & \\dots & \\dots & \\frac{\\partial y_{m-1}}{\\partial x_{n-1}} \\end{bmatrix},\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "c40947ac", - "metadata": { - "editable": true - }, - "source": [ - "which is an $m\\times n$ matrix. If $\\boldsymbol{x}$ is a scalar, then the\n", - "Jacobian is only a single-column vector, or an $m\\times 1$ matrix. If\n", - "on the other hand $\\boldsymbol{y}$ is a scalar, the Jacobian becomes a\n", - "$1\\times n$ matrix.\n", - "\n", - "When this matrix is a square matrix $m=n$, its determinant is often referred to as the Jacobian\n", - "determinant. Both the matrix and (if $m=n$) the determinant are\n", - "often referred to simply as the Jacobian. The Jacobian matrix represents the differential of $\\boldsymbol{y}$ at every point where the\n", - "vector is differentiable." - ] - }, - { - "cell_type": "markdown", - "id": "18e29324", - "metadata": { - "editable": true - }, - "source": [ - "## Derivatives, example 1\n", - "\n", - "Let now $\\boldsymbol{y}=\\boldsymbol{A}\\boldsymbol{x}$, where $\\boldsymbol{A}$ is an $m\\times n$ matrix and the matrix does not depend on $\\boldsymbol{x}$. If we write out the vector $\\boldsymbol{y}$ compoment by component we have" - ] - }, - { - "cell_type": "markdown", - "id": "6069e0fa", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "y_i = \\sum_{j=0}^{n-1}a_{ij}x_j,\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "2796afe6", - "metadata": { - "editable": true - }, - "source": [ - "with $\\forall i=0,1,2,\\dots,m-1$. The individual matrix elements of $\\boldsymbol{A}$ are given by the symbol $a_{ij}$.\n", - "It follows that the partial derivatives of $y_i$ with respect to $x_k$" - ] - }, - { - "cell_type": "markdown", - "id": "2b66e25f", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\frac{\\partial y_i }{\\partial x_k}= a_{ik} \\forall i=0,1,2,\\dots,m-1.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "86f9add1", - "metadata": { - "editable": true - }, - "source": [ - "From this we have, using the definition of the Jacobian" - ] - }, - { - "cell_type": "markdown", - "id": "ae97bea9", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\frac{\\partial \\boldsymbol{y} }{\\partial \\boldsymbol{x}}= \\boldsymbol{A}.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "14510558", - "metadata": { - "editable": true - }, - "source": [ - "## Example 2\n", - "\n", - "We define a scalar (our cost/loss functions are in general also scalars,\n", - "just think of the mean squared error) as the result of some matrix vector\n", - "multiplications" - ] - }, - { - "cell_type": "markdown", - "id": "fbb54b4a", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\alpha = \\boldsymbol{y}^T\\boldsymbol{A}\\boldsymbol{x},\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "553845ce", - "metadata": { - "editable": true - }, - "source": [ - "with $\\boldsymbol{y}$ a vector of length $m$, $\\boldsymbol{A}$ an $m\\times n$ matrix and $\\boldsymbol{x}$ a vector of length $n$. We assume also that $\\boldsymbol{A}$ does not depend on any of the two vectors.\n", - "In order to find the derivative of $\\alpha$ with respect to the two vectors, we define an intermediate vector $\\boldsymbol{z}$. We define first\n", - "$\\boldsymbol{z}^T=\\boldsymbol{y}^T\\boldsymbol{A}$, a vector of length $n$. We have then, using the definition of the Jacobian," - ] - }, - { - "cell_type": "markdown", - "id": "e79fdc3c", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\alpha = \\boldsymbol{z}^T\\boldsymbol{x},\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "0713d61a", - "metadata": { - "editable": true - }, - "source": [ - "which means that (using our previous example) we have" - ] - }, - { - "cell_type": "markdown", - "id": "2e522237", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\frac{\\partial \\alpha}{\\partial \\boldsymbol{x}} = \\boldsymbol{z}=bm{A}^T\\boldsymbol{y}.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "4baadc8b", - "metadata": { - "editable": true - }, - "source": [ - "Note that the resulting vector elements are the same for $\\boldsymbol{z}^T$ and $\\boldsymbol{z}$, the only difference is that one if just the transpose of the other.\n", - "\n", - "Since $\\alpha$ is a scalar we have $\\alpha =\\alpha^T=\\boldsymbol{x}^T\\boldsymbol{A}^T\\boldsymbol{y}$. Defining now $\\boldsymbol{z}=\\boldsymbol{x}^T\\boldsymbol{A}^T$ we find that" - ] - }, - { - "cell_type": "markdown", - "id": "6e0fee06", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\frac{\\partial \\alpha}{\\partial \\boldsymbol{y}} = \\boldsymbol{z}^T=\\boldsymbol{x}^T\\boldsymbol{A}^T.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "1d85d1c1", - "metadata": { - "editable": true - }, - "source": [ - "## Example 3\n", - "\n", - "We start with a new scalar but where now the vector $\\boldsymbol{y}$ is\n", - "replaced by a vector $\\boldsymbol{x}$ and the matrix $\\boldsymbol{A}$ is a square\n", - "matrix with dimension $n\\times n$." - ] - }, - { - "cell_type": "markdown", - "id": "a6643a5f", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\alpha = \\boldsymbol{x}^T\\boldsymbol{A}\\boldsymbol{x},\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "f15d9044", - "metadata": { - "editable": true - }, - "source": [ - "with $\\boldsymbol{x}$ a vector of length $n$.\n", - "\n", - "We write out the specific sums involved in the calculation of $\\alpha$" - ] - }, - { - "cell_type": "markdown", - "id": "658745bf", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\alpha = \\sum_{i=0}^{n-1}\\sum_{j=0}^{n-1}x_i a_{ij}x_j,\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "ba8bc828", - "metadata": { - "editable": true - }, - "source": [ - "taking the derivative of $\\alpha$ with respect to a given component $x_k$ we get the two sums" - ] - }, - { - "cell_type": "markdown", - "id": "38512288", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\frac{\\partial \\alpha}{\\partial x_k} = \\sum_{i=0}^{n-1}a_{ik}x_i+\\sum_{j=0}^{n-1}a_{kj}x_j,\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "0a571ae1", - "metadata": { - "editable": true - }, - "source": [ - "for $\\forall k =0,1,2,\\dots,n-1$. We identify these sums as" - ] - }, - { - "cell_type": "markdown", - "id": "f26f46f8", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\frac{\\partial \\alpha}{\\partial \\boldsymbol{x}} = \\boldsymbol{x}^T\\left(\\boldsymbol{A}^T+\\boldsymbol{A}\\right).\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "9e6c5896", - "metadata": { - "editable": true - }, - "source": [ - "If the matrix $\\boldsymbol{A}$ is symmetric, that is $\\boldsymbol{A}=\\boldsymbol{A}^T$, we have" - ] - }, - { - "cell_type": "markdown", - "id": "fa516251", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\frac{\\partial \\alpha}{\\partial \\boldsymbol{x}} = 2\\boldsymbol{x}^T\\boldsymbol{A}.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "10db7624", - "metadata": { - "editable": true - }, - "source": [ - "## Example 4\n", - "\n", - "We let the scalar $\\alpha$ be defined by" - ] - }, - { - "cell_type": "markdown", - "id": "7cdeda2b", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\alpha = \\boldsymbol{y}^T\\boldsymbol{x},\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "2b9a8aed", - "metadata": { - "editable": true - }, - "source": [ - "where both $\\boldsymbol{y}$ and $\\boldsymbol{x}$ have the same length $n$, or if we\n", - "wish to think of them as column vectors, they have dimensions $n\\times\n", - "1$. We assume that both $\\boldsymbol{y}$ and $\\boldsymbol{x}$ depend on a vector\n", - "$\\boldsymbol{z}$ of the same length. To calculate the derivative of $\\alpha$\n", - "with respect to a given component $z_k$ we need first to write out the\n", - "inner product that defines $\\alpha$ as" - ] - }, - { - "cell_type": "markdown", - "id": "758969d3", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\alpha = \\sum_{i=0}^{n-1}y_ix_i,\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "d7203c02", - "metadata": { - "editable": true - }, - "source": [ - "and the partial derivative" - ] - }, - { - "cell_type": "markdown", - "id": "16f3ca20", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\frac{\\partial \\alpha}{\\partial z_k} = \\sum_{i=0}^{n-1}\\left(x_i\\frac{\\partial y_i}{\\partial z_k}+y_i\\frac{\\partial x_i}{\\partial z_k}\\right),\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "f7caf01e", - "metadata": { - "editable": true - }, - "source": [ - "for $\\forall k =0,1,2,\\dots,n-1$. We can rewrite the partial derivative in a more compact form as" - ] - }, - { - "cell_type": "markdown", - "id": "b1e5ad17", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\frac{\\partial \\alpha}{\\partial \\boldsymbol{z}} = \\boldsymbol{x}^T\\frac{\\partial \\boldsymbol{y}}{\\partial \\boldsymbol{z}}+\\boldsymbol{y}^T\\frac{\\partial \\boldsymbol{x}}{\\partial \\boldsymbol{z}},\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "587c347e", - "metadata": { - "editable": true - }, - "source": [ - "and if $\\boldsymbol{y}=\\boldsymbol{x}$ we have" - ] - }, - { - "cell_type": "markdown", - "id": "5279b1cb", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\frac{\\partial \\alpha}{\\partial \\boldsymbol{z}} = 2\\boldsymbol{x}^T\\frac{\\partial \\boldsymbol{x}}{\\partial \\boldsymbol{z}}.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "0c0d18ed", - "metadata": { - "editable": true - }, - "source": [ - "## The mean squared error and its derivative\n", - "\n", - "We defined earlier a possible cost function using the mean squared error" - ] - }, - { - "cell_type": "markdown", - "id": "ba1b34c9", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "C(\\boldsymbol{\\beta})=\\frac{1}{n}\\sum_{i=0}^{n-1}\\left(y_i-\\tilde{y}_i\\right)^2=\\frac{1}{n}\\left\\{\\left(\\boldsymbol{y}-\\boldsymbol{\\tilde{y}}\\right)^T\\left(\\boldsymbol{y}-\\boldsymbol{\\tilde{y}}\\right)\\right\\},\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "b859b644", - "metadata": { - "editable": true - }, - "source": [ - "or using the design/feature matrix $\\boldsymbol{X}$ we have the more compact matrix-vector" - ] - }, - { - "cell_type": "markdown", - "id": "a6451ed1", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "C(\\boldsymbol{\\beta})=\\frac{1}{n}\\left\\{\\left(\\boldsymbol{y}-\\boldsymbol{X}\\boldsymbol{\\beta}\\right)^T\\left(\\boldsymbol{y}-\\boldsymbol{X}\\boldsymbol{\\beta}\\right)\\right\\}.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "6879be83", - "metadata": { - "editable": true - }, - "source": [ - "We note that the design matrix $\\boldsymbol{X}$ does not depend on the unknown parameters defined by the vector $\\boldsymbol{\\beta}$.\n", - "We are now interested in minimizing the cost function with respect to the unknown parameters $\\boldsymbol{\\beta}$.\n", - "\n", - "The mean squared error is a scalar and if we use the results from example three above, we can define a new vector" - ] - }, - { - "cell_type": "markdown", - "id": "bda465e5", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\boldsymbol{w}=\\boldsymbol{y}-\\boldsymbol{X}\\boldsymbol{\\beta},\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "aeb97168", - "metadata": { - "editable": true - }, - "source": [ - "which depends on $\\boldsymbol{\\beta}$. We rewrite the cost function as" - ] - }, - { - "cell_type": "markdown", - "id": "d5339f3b", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "C(\\boldsymbol{\\beta})=\\frac{1}{n}\\boldsymbol{w}^T\\boldsymbol{w},\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "924aee00", - "metadata": { - "editable": true - }, - "source": [ - "with partial derivative" - ] - }, - { - "cell_type": "markdown", - "id": "856a72bf", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\frac{\\partial C(\\boldsymbol{\\beta})}{\\partial \\boldsymbol{\\beta}}=\\frac{2}{n}\\boldsymbol{w}^T\\frac{\\partial \\boldsymbol{w}}{\\partial \\boldsymbol{\\beta}},\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "ad9fe745", - "metadata": { - "editable": true - }, - "source": [ - "and using that" - ] - }, - { - "cell_type": "markdown", - "id": "5a72fd42", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\frac{\\partial \\boldsymbol{w}}{\\partial \\boldsymbol{\\beta}}=-\\boldsymbol{X},\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "569524a1", - "metadata": { - "editable": true - }, - "source": [ - "where we used the result from example two above. Inserting the last expression we obtain" - ] - }, - { - "cell_type": "markdown", - "id": "4e8d401f", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\frac{\\partial C(\\boldsymbol{\\beta})}{\\partial \\boldsymbol{\\beta}}=-\\frac{2}{n}\\left(\\boldsymbol{y}-\\boldsymbol{X}\\boldsymbol{\\beta}\\right)^T\\boldsymbol{X},\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "24230b58", - "metadata": { - "editable": true - }, - "source": [ - "or as" - ] - }, - { - "cell_type": "markdown", - "id": "fe2c5d6e", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\frac{\\partial C(\\boldsymbol{\\beta})}{\\partial \\boldsymbol{\\beta}^T}=-\\frac{2}{n}\\boldsymbol{X}^T\\left(\\boldsymbol{y}-\\boldsymbol{X}\\boldsymbol{\\beta}\\right).\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "9b68b468", - "metadata": { - "editable": true - }, - "source": [ - "## Other useful relations\n", - "\n", - "We list here some other useful relations we may encounter (recall that vectors are defined by boldfaced low-key letters)" - ] - }, - { - "cell_type": "markdown", - "id": "bf6a5077", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\frac{\\partial (\\boldsymbol{b}^T\\boldsymbol{a})}{\\partial \\boldsymbol{a}} = \\boldsymbol{b},\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "ddf09a27", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\frac{\\partial tr(\\boldsymbol{B}\\boldsymbol{A})}{\\partial \\boldsymbol{A}} = \\boldsymbol{B}^T,\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "e1665513", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\frac{\\partial \\log{\\vert\\boldsymbol{A}\\vert}}{\\partial \\boldsymbol{A}} = (\\boldsymbol{A}^{-1})^T.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "e754746c", - "metadata": { - "editable": true - }, - "source": [ - "## Meet the Hessian Matrix\n", - "\n", - "A very important matrix we will meet again and again in machine\n", - "learning is the Hessian. It is given by the second derivative of the\n", - "cost function with respect to the parameters $\\boldsymbol{\\beta}$. Using the above\n", - "expression for derivatives of vectors and matrices, we find that the\n", - "second derivative of the mean squared error as cost function is," - ] - }, - { - "cell_type": "markdown", - "id": "922d0d8c", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\frac{\\partial}{\\partial \\boldsymbol{\\beta}}\\frac{\\partial C(\\boldsymbol{\\beta})}{\\partial \\boldsymbol{\\beta}^T} =\\frac{\\partial}{\\partial \\boldsymbol{\\beta}}\\left[-\\frac{2}{n}\\boldsymbol{X}^T\\left( \\boldsymbol{y}-\\boldsymbol{X}\\boldsymbol{\\beta}\\right)\\right]=\\frac{2}{n}\\boldsymbol{X}^T\\boldsymbol{X}.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "acf89848", - "metadata": { - "editable": true - }, - "source": [ - "The Hessian matrix plays an important role and is defined here as" - ] - }, - { - "cell_type": "markdown", - "id": "12d22c90", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\boldsymbol{H}=\\boldsymbol{X}^T\\boldsymbol{X}.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "9dbcb6d7", - "metadata": { - "editable": true - }, - "source": [ - "For ordinary least squares, it is inversely proportional (derivation\n", - "next week) with the variance of the optimal parameters\n", - "$\\hat{\\boldsymbol{\\beta}}$. Furthermore, we will see later this week that it is\n", - "(aside the factor $1/n$) equal to the covariance matrix. It plays also a very\n", - "important role in optmization algorithms and Principal Component\n", - "Analysis as a way to reduce the dimensionality of a machine learning/data analysis\n", - "problem.\n", - "\n", - "**Linear algebra question:** Can we use the Hessian matrix to say something about properties of the cost function (our optmization problem)? (hint: think about convex or concave problems and how to relate these to a matrix!)." - ] - }, - { - "cell_type": "markdown", - "id": "b797b390", - "metadata": { - "editable": true - }, - "source": [ - "## Interpretations and optimizing our parameters\n", - "\n", - "The residuals $\\boldsymbol{\\epsilon}$ are in turn given by" - ] - }, - { - "cell_type": "markdown", - "id": "b78ab217", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\boldsymbol{\\epsilon} = \\boldsymbol{y}-\\boldsymbol{\\tilde{y}} = \\boldsymbol{y}-\\boldsymbol{X}\\boldsymbol{\\beta},\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "e0a0542d", - "metadata": { - "editable": true - }, - "source": [ - "and with" - ] - }, - { - "cell_type": "markdown", - "id": "fd640b28", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\boldsymbol{X}^T\\left( \\boldsymbol{y}-\\boldsymbol{X}\\boldsymbol{\\beta}\\right)= 0,\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "6a073b35", - "metadata": { - "editable": true - }, - "source": [ - "we have" - ] - }, - { - "cell_type": "markdown", - "id": "f7daf28e", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\boldsymbol{X}^T\\boldsymbol{\\epsilon}=\\boldsymbol{X}^T\\left( \\boldsymbol{y}-\\boldsymbol{X}\\boldsymbol{\\beta}\\right)= 0,\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "d8e03fdc", - "metadata": { - "editable": true - }, - "source": [ - "meaning that the solution for $\\boldsymbol{\\beta}$ is the one which minimizes the residuals." - ] - }, - { - "cell_type": "markdown", - "id": "058aed61", - "metadata": { - "editable": true - }, - "source": [ - "## Example relevant for the exercises\n", - "\n", - "In order to understand the relation among the predictors $p$, the set of data $n$ and the target (outcome, output etc) $\\boldsymbol{y}$,\n", - "we condiser a simple polynomial fit.\n", - "We assume our data can represented by a fourth-order polynomial. For the $i$th component we have" - ] - }, - { - "cell_type": "markdown", - "id": "c7d35183", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\tilde{y}_i = \\beta_0+\\beta_1x_i+\\beta_2x_i^2+\\beta_3x_i^3+\\beta_4x_i^4.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "bad6fd9a", - "metadata": { - "editable": true - }, - "source": [ - "we have five predictors/features. The first is the intercept $\\beta_0$. The other terms are $\\beta_i$ with $i=1,2,3,4$. Furthermore we have $n$ entries for each predictor. It means that our design matrix is an \n", - "$n\\times p$ matrix $\\boldsymbol{X}$." - ] - }, - { - "cell_type": "markdown", - "id": "1bd57074", - "metadata": { - "editable": true - }, - "source": [ - "## Own code for Ordinary Least Squares\n", - "\n", - "It is rather straightforward to implement the matrix inversion and obtain the parameters $\\boldsymbol{\\beta}$. After having defined the matrix $\\boldsymbol{X}$ and the outputs $\\boldsymbol{y}$ we have" - ] - }, - { - "cell_type": "code", - "execution_count": 1, - "id": "9895174d", - "metadata": { - "collapsed": false, - "editable": true - }, - "outputs": [], - "source": [ - "# matrix inversion to find beta\n", - "# First we set up the data\n", - "import numpy as np\n", - "x = np.random.rand(100)\n", - "y = 2.0+5*x*x+0.1*np.random.randn(100)\n", - "# and then the design matrix X including the intercept\n", - "# The design matrix now as function of a fourth-order polynomial\n", - "X = np.zeros((len(x),5))\n", - "X[:,0] = 1.0\n", - "X[:,1] = x\n", - "X[:,2] = x**2\n", - "X[:,3] = x**3\n", - "X[:,4] = x**4\n", - "beta = (np.linalg.inv(X.T @ X) @ X.T ) @ y\n", - "# and then make the prediction\n", - "ytilde = X @ beta" - ] - }, - { - "cell_type": "markdown", - "id": "0d7ad6dc", - "metadata": { - "editable": true - }, - "source": [ - "Alternatively, you can use the least squares functionality in **Numpy** as" - ] - }, - { - "cell_type": "code", - "execution_count": 2, - "id": "e52ec127", - "metadata": { - "collapsed": false, - "editable": true - }, - "outputs": [], - "source": [ - "fit = np.linalg.lstsq(X, y, rcond =None)[0]\n", - "ytildenp = np.dot(fit,X.T)" - ] - }, - { - "cell_type": "markdown", - "id": "c66acc10", - "metadata": { - "editable": true - }, - "source": [ - "## Adding error analysis and training set up\n", - "\n", - "We can easily test our fit by computing the $R2$ score that we discussed in connection with the functionality of **Scikit-Learn** in the introductory slides.\n", - "Since we are not using **Scikit-Learn** here we can define our own $R2$ function as" - ] - }, - { - "cell_type": "code", - "execution_count": 3, - "id": "85f5f060", - "metadata": { - "collapsed": false, - "editable": true - }, - "outputs": [], - "source": [ - "def R2(y_data, y_model):\n", - " return 1 - np.sum((y_data - y_model) ** 2) / np.sum((y_data - np.mean(y_data)) ** 2)" - ] - }, - { - "cell_type": "markdown", - "id": "ef359561", - "metadata": { - "editable": true - }, - "source": [ - "and we would be using it as" - ] - }, - { - "cell_type": "code", - "execution_count": 4, - "id": "21b8437f", - "metadata": { - "collapsed": false, - "editable": true - }, - "outputs": [], - "source": [ - "print(R2(y,ytilde))" - ] - }, - { - "cell_type": "markdown", - "id": "b1c814a4", - "metadata": { - "editable": true - }, - "source": [ - "We can easily add our **MSE** score as" - ] - }, - { - "cell_type": "code", - "execution_count": 5, - "id": "de8f1db6", - "metadata": { - "collapsed": false, - "editable": true - }, - "outputs": [], - "source": [ - "def MSE(y_data,y_model):\n", - " n = np.size(y_model)\n", - " return np.sum((y_data-y_model)**2)/n\n", - "\n", - "print(MSE(y,ytilde))" - ] - }, - { - "cell_type": "markdown", - "id": "421ff6ee", - "metadata": { - "editable": true - }, - "source": [ - "and finally the relative error as" - ] - }, - { - "cell_type": "code", - "execution_count": 6, - "id": "77d5b744", - "metadata": { - "collapsed": false, - "editable": true - }, - "outputs": [], - "source": [ - "def RelativeError(y_data,y_model):\n", - " return abs((y_data-y_model)/y_data)\n", - "print(RelativeError(y, ytilde))" - ] - }, - { - "cell_type": "markdown", - "id": "0afffa89", - "metadata": { - "editable": true - }, - "source": [ - "## Splitting our Data in Training and Test data\n", - "\n", - "It is normal in essentially all Machine Learning studies to split the\n", - "data in a training set and a test set (sometimes also an additional\n", - "validation set). **Scikit-Learn** has an own function for this. There\n", - "is no explicit recipe for how much data should be included as training\n", - "data and say test data. An accepted rule of thumb is to use\n", - "approximately $2/3$ to $4/5$ of the data as training data. We will\n", - "postpone a discussion of this splitting to the end of these notes and\n", - "our discussion of the so-called **bias-variance** tradeoff. Here we\n", - "limit ourselves to repeat the above equation of state fitting example\n", - "but now splitting the data into a training set and a test set." - ] - }, - { - "cell_type": "markdown", - "id": "83fc18dd", - "metadata": { - "editable": true - }, - "source": [ - "## The complete code with a simple data set" - ] - }, - { - "cell_type": "code", - "execution_count": 7, - "id": "c908e069", - "metadata": { - "collapsed": false, - "editable": true - }, - "outputs": [], - "source": [ - "%matplotlib inline\n", - "\n", - "import os\n", - "import numpy as np\n", - "import pandas as pd\n", - "import matplotlib.pyplot as plt\n", - "from sklearn.model_selection import train_test_split\n", - "\n", - "\n", - "def R2(y_data, y_model):\n", - " return 1 - np.sum((y_data - y_model) ** 2) / np.sum((y_data - np.mean(y_data)) ** 2)\n", - "def MSE(y_data,y_model):\n", - " n = np.size(y_model)\n", - " return np.sum((y_data-y_model)**2)/n\n", - "\n", - "x = np.random.rand(100)\n", - "y = 2.0+5*x*x+0.1*np.random.randn(100)\n", - "\n", - "\n", - "# The design matrix now as function of a fourth-order polynomial\n", - "X = np.zeros((len(x),5))\n", - "X[:,0] = 1.0\n", - "X[:,1] = x\n", - "X[:,2] = x**2\n", - "X[:,3] = x**3\n", - "X[:,4] = x**4\n", - "# We split the data in test and training data\n", - "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2)\n", - "# matrix inversion to find beta\n", - "beta = np.linalg.inv(X_train.T @ X_train) @ X_train.T @ y_train\n", - "print(beta)\n", - "# and then make the prediction\n", - "ytilde = X_train @ beta\n", - "print(\"Training R2\")\n", - "print(R2(y_train,ytilde))\n", - "print(\"Training MSE\")\n", - "print(MSE(y_train,ytilde))\n", - "ypredict = X_test @ beta\n", - "print(\"Test R2\")\n", - "print(R2(y_test,ypredict))\n", - "print(\"Test MSE\")\n", - "print(MSE(y_test,ypredict))" - ] - }, - { - "cell_type": "markdown", - "id": "f69cf8d1", - "metadata": { - "editable": true - }, - "source": [ - "## Making your own test-train splitting" - ] - }, - { - "cell_type": "code", - "execution_count": 8, - "id": "03acb6ba", - "metadata": { - "collapsed": false, - "editable": true - }, - "outputs": [], - "source": [ - "# equivalently in numpy\n", - "def train_test_split_numpy(inputs, labels, train_size, test_size):\n", - " n_inputs = len(inputs)\n", - " inputs_shuffled = inputs.copy()\n", - " labels_shuffled = labels.copy()\n", - "\n", - " np.random.shuffle(inputs_shuffled)\n", - " np.random.shuffle(labels_shuffled)\n", - "\n", - " train_end = int(n_inputs*train_size)\n", - " X_train, X_test = inputs_shuffled[:train_end], inputs_shuffled[train_end:]\n", - " Y_train, Y_test = labels_shuffled[:train_end], labels_shuffled[train_end:]\n", - "\n", - " return X_train, X_test, Y_train, Y_test" - ] - }, - { - "cell_type": "markdown", - "id": "0d8db71d", - "metadata": { - "editable": true - }, - "source": [ - "But since **scikit-learn** has its own function for doing this and since\n", - "it interfaces easily with **tensorflow** and other libraries, we\n", - "normally recommend using the latter functionality." - ] - }, - { - "cell_type": "markdown", - "id": "29fc4792", - "metadata": { - "editable": true - }, - "source": [ - "## Reducing the number of degrees of freedom, overarching view\n", - "\n", - "Many Machine Learning problems involve thousands or even millions of\n", - "features for each training instance. Not only does this make training\n", - "extremely slow, it can also make it much harder to find a good\n", - "solution, as we will see. This problem is often referred to as the\n", - "curse of dimensionality. Fortunately, in real-world problems, it is\n", - "often possible to reduce the number of features considerably, turning\n", - "an intractable problem into a tractable one.\n", - "\n", - "Later we will discuss some of the most popular dimensionality reduction\n", - "techniques: the principal component analysis (PCA), Kernel PCA, and\n", - "Locally Linear Embedding (LLE). \n", - "\n", - "Principal component analysis and its various variants deal with the\n", - "problem of fitting a low-dimensional [affine\n", - "subspace](https://en.wikipedia.org/wiki/Affine_space) to a set of of\n", - "data points in a high-dimensional space. With its family of methods it\n", - "is one of the most used tools in data modeling, compression and\n", - "visualization." - ] - }, - { - "cell_type": "markdown", - "id": "5d2323e6", - "metadata": { - "editable": true - }, - "source": [ - "## Preprocessing our data\n", - "\n", - "Before we proceed however, we will discuss how to preprocess our\n", - "data. Till now and in connection with our previous examples we have\n", - "not met so many cases where we are too sensitive to the scaling of our\n", - "data. Normally the data may need a rescaling and/or may be sensitive\n", - "to extreme values. Scaling the data renders our inputs much more\n", - "suitable for the algorithms we want to employ.\n", - "\n", - "For data sets gathered for real world applications, it is rather normal that\n", - "different features have very different units and\n", - "numerical scales. For example, a data set detailing health habits may include\n", - "features such as **age** in the range $0-80$, and **caloric intake** of order $2000$.\n", - "Many machine learning methods sensitive to the scales of the features and may perform poorly if they\n", - "are very different scales. Therefore, it is typical to scale\n", - "the features in a way to avoid such outlier values." - ] - }, - { - "cell_type": "markdown", - "id": "084a05ce", - "metadata": { - "editable": true - }, - "source": [ - "## Functionality in Scikit-Learn\n", - "\n", - "**Scikit-Learn** has several functions which allow us to rescale the\n", - "data, normally resulting in much better results in terms of various\n", - "accuracy scores. The **StandardScaler** function in **Scikit-Learn**\n", - "ensures that for each feature/predictor we study the mean value is\n", - "zero and the variance is one (every column in the design/feature\n", - "matrix). This scaling has the drawback that it does not ensure that\n", - "we have a particular maximum or minimum in our data set. Another\n", - "function included in **Scikit-Learn** is the **MinMaxScaler** which\n", - "ensures that all features are exactly between $0$ and $1$. The" - ] - }, - { - "cell_type": "markdown", - "id": "2cf236cf", - "metadata": { - "editable": true - }, - "source": [ - "## More preprocessing\n", - "\n", - "The **Normalizer** scales each data\n", - "point such that the feature vector has a euclidean length of one. In other words, it\n", - "projects a data point on the circle (or sphere in the case of higher dimensions) with a\n", - "radius of 1. This means every data point is scaled by a different number (by the\n", - "inverse of it’s length).\n", - "This normalization is often used when only the direction (or angle) of the data matters,\n", - "not the length of the feature vector.\n", - "\n", - "The **RobustScaler** works similarly to the StandardScaler in that it\n", - "ensures statistical properties for each feature that guarantee that\n", - "they are on the same scale. However, the RobustScaler uses the median\n", - "and quartiles, instead of mean and variance. This makes the\n", - "RobustScaler ignore data points that are very different from the rest\n", - "(like measurement errors). These odd data points are also called\n", - "outliers, and might often lead to trouble for other scaling\n", - "techniques." - ] - }, - { - "cell_type": "markdown", - "id": "f7ef3d03", - "metadata": { - "editable": true - }, - "source": [ - "## Frequently used scaling functions\n", - "\n", - "Many features are often scaled using standardization to improve performance. In **Scikit-Learn** this is given by the **StandardScaler** function as discussed above. It is easy however to write your own. \n", - "Mathematically, this involves subtracting the mean and divide by the standard deviation over the data set, for each feature:" - ] - }, - { - "cell_type": "markdown", - "id": "30df9a47", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "x_j^{(i)} \\rightarrow \\frac{x_j^{(i)} - \\overline{x}_j}{\\sigma(x_j)},\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "fa957ecb", - "metadata": { - "editable": true - }, - "source": [ - "where $\\overline{x}_j$ and $\\sigma(x_j)$ are the mean and standard deviation, respectively, of the feature $x_j$.\n", - "This ensures that each feature has zero mean and unit standard deviation. For data sets where we do not have the standard deviation or don't wish to calculate it, it is then common to simply set it to one." - ] - }, - { - "cell_type": "markdown", - "id": "c6b8f467", - "metadata": { - "editable": true - }, - "source": [ - "## Example of own Standard scaling\n", - "\n", - "Let us consider the following vanilla example where we use both\n", - "**Scikit-Learn** and write our own function as well. We produce a\n", - "simple test design matrix with random numbers. Each column could then\n", - "represent a specific feature whose mean value is subracted." - ] - }, - { - "cell_type": "code", - "execution_count": 9, - "id": "a2480cf9", - "metadata": { - "collapsed": false, - "editable": true - }, - "outputs": [], - "source": [ - "import sklearn.linear_model as skl\n", - "from sklearn.metrics import mean_squared_error\n", - "from sklearn.model_selection import train_test_split\n", - "from sklearn.preprocessing import MinMaxScaler, StandardScaler, Normalizer\n", - "import numpy as np\n", - "import pandas as pd\n", - "from IPython.display import display\n", - "np.random.seed(100)\n", - "# setting up a 10 x 5 matrix\n", - "rows = 10\n", - "cols = 5\n", - "X = np.random.randn(rows,cols)\n", - "XPandas = pd.DataFrame(X)\n", - "display(XPandas)\n", - "print(XPandas.mean())\n", - "print(XPandas.std())\n", - "XPandas = (XPandas -XPandas.mean())\n", - "display(XPandas)\n", - "# This option does not include the standard deviation\n", - "scaler = StandardScaler(with_std=False)\n", - "scaler.fit(X)\n", - "Xscaled = scaler.transform(X)\n", - "display(XPandas-Xscaled)" - ] - }, - { - "cell_type": "markdown", - "id": "7643608b", - "metadata": { - "editable": true - }, - "source": [ - "Small exercise: perform the standard scaling by including the standard deviation and compare with what Scikit-Learn gives." - ] - }, - { - "cell_type": "markdown", - "id": "5e6e489d", - "metadata": { - "editable": true - }, - "source": [ - "## Min-Max Scaling\n", - "\n", - "Another commonly used scaling method is min-max scaling. This is very\n", - "useful for when we want the features to lie in a certain interval. To\n", - "scale the feature $x_j$ to the interval $[a, b]$, we can apply the\n", - "transformation" - ] - }, - { - "cell_type": "markdown", - "id": "ff073975", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "x_j^{(i)} \\rightarrow (b-a)\\frac{x_j^{(i)} - \\min(x_j)}{\\max(x_j) - \\min(x_j)} - a\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "6a176186", - "metadata": { - "editable": true - }, - "source": [ - "where $\\min(x_j)$ and $\\max(x_j)$ return the minimum and maximum value of $x_j$ over the data set, respectively." - ] - }, - { - "cell_type": "markdown", - "id": "784ddba6", - "metadata": { - "editable": true - }, - "source": [ - "## Testing the Means Squared Error as function of Complexity\n", - "\n", - "One of \n", - "the aims is to reproduce Figure 2.11 of [Hastie et al](https://github.com/CompPhysics/MLErasmus/blob/master/doc/Textbooks/elementsstat.pdf).\n", - "\n", - "Our data is defined by $x\\in [-3,3]$ with a total of for example $100$ data points." - ] - }, - { - "cell_type": "code", - "execution_count": 10, - "id": "83686834", - "metadata": { - "collapsed": false, - "editable": true - }, - "outputs": [], - "source": [ - "np.random.seed()\n", - "n = 100\n", - "maxdegree = 14\n", - "# Make data set.\n", - "x = np.linspace(-3, 3, n).reshape(-1, 1)\n", - "y = np.exp(-x**2) + 1.5 * np.exp(-(x-2)**2)+ np.random.normal(0, 0.1, x.shape)" - ] - }, - { - "cell_type": "markdown", - "id": "dd641a05", - "metadata": { - "editable": true - }, - "source": [ - "where $y$ is the function we want to fit with a given polynomial.\n", - "\n", - "Write a first code which sets up a design matrix $X$ defined by a fourth-order polynomial. Scale your data and split it in training and test data." - ] - }, - { - "cell_type": "code", - "execution_count": 11, - "id": "447d12ce", - "metadata": { - "collapsed": false, - "editable": true - }, - "outputs": [], - "source": [ - "import matplotlib.pyplot as plt\n", - "import numpy as np\n", - "from sklearn.linear_model import LinearRegression\n", - "from sklearn.preprocessing import PolynomialFeatures\n", - "from sklearn.model_selection import train_test_split\n", - "from sklearn.pipeline import make_pipeline\n", - "\n", - "\n", - "np.random.seed(2018)\n", - "n = 50\n", - "maxdegree = 5\n", - "# Make data set.\n", - "x = np.linspace(-3, 3, n).reshape(-1, 1)\n", - "y = np.exp(-x**2) + 1.5 * np.exp(-(x-2)**2)+ np.random.normal(0, 0.1, x.shape)\n", - "TestError = np.zeros(maxdegree)\n", - "TrainError = np.zeros(maxdegree)\n", - "polydegree = np.zeros(maxdegree)\n", - "x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.2)\n", - "scaler = StandardScaler()\n", - "scaler.fit(x_train)\n", - "x_train_scaled = scaler.transform(x_train)\n", - "x_test_scaled = scaler.transform(x_test)\n", - "\n", - "for degree in range(maxdegree):\n", - " model = make_pipeline(PolynomialFeatures(degree=degree), LinearRegression(fit_intercept=False))\n", - " clf = model.fit(x_train_scaled,y_train)\n", - " y_fit = clf.predict(x_train_scaled)\n", - " y_pred = clf.predict(x_test_scaled) \n", - " polydegree[degree] = degree\n", - " TestError[degree] = np.mean( np.mean((y_test - y_pred)**2) )\n", - " TrainError[degree] = np.mean( np.mean((y_train - y_fit)**2) )\n", - "\n", - "plt.plot(polydegree, TestError, label='Test Error')\n", - "plt.plot(polydegree, TrainError, label='Train Error')\n", - "plt.legend()\n", - "plt.show()" - ] - }, - { - "cell_type": "markdown", - "id": "96fc590b", - "metadata": { - "editable": true - }, - "source": [ - "## More preprocessing examples, two-dimensional example, the Franke function" - ] - }, - { - "cell_type": "code", - "execution_count": 12, - "id": "8de8bbfc", - "metadata": { - "collapsed": false, - "editable": true - }, - "outputs": [], - "source": [ - "# Common imports\n", - "import os\n", - "import numpy as np\n", - "import pandas as pd\n", - "import matplotlib.pyplot as plt\n", - "import sklearn.linear_model as skl\n", - "from sklearn.metrics import mean_squared_error\n", - "from sklearn.model_selection import train_test_split\n", - "from sklearn.preprocessing import MinMaxScaler, StandardScaler, Normalizer\n", - "\n", - "# Where to save the figures and data files\n", - "PROJECT_ROOT_DIR = \"Results\"\n", - "FIGURE_ID = \"Results/FigureFiles\"\n", - "DATA_ID = \"DataFiles/\"\n", - "\n", - "if not os.path.exists(PROJECT_ROOT_DIR):\n", - " os.mkdir(PROJECT_ROOT_DIR)\n", - "\n", - "if not os.path.exists(FIGURE_ID):\n", - " os.makedirs(FIGURE_ID)\n", - "\n", - "if not os.path.exists(DATA_ID):\n", - " os.makedirs(DATA_ID)\n", - "\n", - "def image_path(fig_id):\n", - " return os.path.join(FIGURE_ID, fig_id)\n", - "\n", - "def data_path(dat_id):\n", - " return os.path.join(DATA_ID, dat_id)\n", - "\n", - "def save_fig(fig_id):\n", - " plt.savefig(image_path(fig_id) + \".png\", format='png')\n", - "\n", - "\n", - "def FrankeFunction(x,y):\n", - "\tterm1 = 0.75*np.exp(-(0.25*(9*x-2)**2) - 0.25*((9*y-2)**2))\n", - "\tterm2 = 0.75*np.exp(-((9*x+1)**2)/49.0 - 0.1*(9*y+1))\n", - "\tterm3 = 0.5*np.exp(-(9*x-7)**2/4.0 - 0.25*((9*y-3)**2))\n", - "\tterm4 = -0.2*np.exp(-(9*x-4)**2 - (9*y-7)**2)\n", - "\treturn term1 + term2 + term3 + term4\n", - "\n", - "\n", - "def create_X(x, y, n ):\n", - "\tif len(x.shape) > 1:\n", - "\t\tx = np.ravel(x)\n", - "\t\ty = np.ravel(y)\n", - "\n", - "\tN = len(x)\n", - "\tl = int((n+1)*(n+2)/2)\t\t# Number of elements in beta\n", - "\tX = np.ones((N,l))\n", - "\n", - "\tfor i in range(1,n+1):\n", - "\t\tq = int((i)*(i+1)/2)\n", - "\t\tfor k in range(i+1):\n", - "\t\t\tX[:,q+k] = (x**(i-k))*(y**k)\n", - "\n", - "\treturn X\n", - "\n", - "\n", - "# Making meshgrid of datapoints and compute Franke's function\n", - "n = 5\n", - "N = 1000\n", - "x = np.sort(np.random.uniform(0, 1, N))\n", - "y = np.sort(np.random.uniform(0, 1, N))\n", - "z = FrankeFunction(x, y)\n", - "X = create_X(x, y, n=n) \n", - "# split in training and test data\n", - "X_train, X_test, y_train, y_test = train_test_split(X,z,test_size=0.2)\n", - "\n", - "\n", - "clf = skl.LinearRegression().fit(X_train, y_train)\n", - "\n", - "# The mean squared error and R2 score\n", - "print(\"MSE before scaling: {:.2f}\".format(mean_squared_error(clf.predict(X_test), y_test)))\n", - "print(\"R2 score before scaling {:.2f}\".format(clf.score(X_test,y_test)))\n", - "\n", - "scaler = StandardScaler()\n", - "scaler.fit(X_train)\n", - "X_train_scaled = scaler.transform(X_train)\n", - "X_test_scaled = scaler.transform(X_test)\n", - "\n", - "print(\"Feature min values before scaling:\\n {}\".format(X_train.min(axis=0)))\n", - "print(\"Feature max values before scaling:\\n {}\".format(X_train.max(axis=0)))\n", - "\n", - "print(\"Feature min values after scaling:\\n {}\".format(X_train_scaled.min(axis=0)))\n", - "print(\"Feature max values after scaling:\\n {}\".format(X_train_scaled.max(axis=0)))\n", - "\n", - "clf = skl.LinearRegression().fit(X_train_scaled, y_train)\n", - "\n", - "\n", - "print(\"MSE after scaling: {:.2f}\".format(mean_squared_error(clf.predict(X_test_scaled), y_test)))\n", - "print(\"R2 score for scaled data: {:.2f}\".format(clf.score(X_test_scaled,y_test)))" - ] - }, - { - "cell_type": "markdown", - "id": "8dfe4a90", - "metadata": { - "editable": true - }, - "source": [ - "## To think about, first part\n", - "\n", - "When you are comparing your own code with for example **Scikit-Learn**'s\n", - "library, there are some technicalities to keep in mind. The examples\n", - "here demonstrate some of these aspects with potential pitfalls.\n", - "\n", - "The discussion here focuses on the role of the intercept, how we can\n", - "set up the design matrix, what scaling we should use and other topics\n", - "which tend confuse us.\n", - "\n", - "The intercept can be interpreted as the expected value of our\n", - "target/output variables when all other predictors are set to zero.\n", - "Thus, if we cannot assume that the expected outputs/targets are zero\n", - "when all predictors are zero (the columns in the design matrix), it\n", - "may be a bad idea to implement a model which penalizes the intercept.\n", - "Furthermore, in for example Ridge and Lasso regression (to be discussed in moe detail next week), the default solutions\n", - "from the library **Scikit-Learn** (when not shrinking $\\beta_0$) for the unknown parameters\n", - "$\\boldsymbol{\\beta}$, are derived under the assumption that both $\\boldsymbol{y}$ and\n", - "$\\boldsymbol{X}$ are zero centered, that is we subtract the mean values." - ] - }, - { - "cell_type": "markdown", - "id": "c0edb6d6", - "metadata": { - "editable": true - }, - "source": [ - "## More thinking\n", - "\n", - "If our predictors represent different scales, then it is important to\n", - "standardize the design matrix $\\boldsymbol{X}$ by subtracting the mean of each\n", - "column from the corresponding column and dividing the column with its\n", - "standard deviation. Most machine learning libraries do this as a default. This means that if you compare your code with the results from a given library,\n", - "the results may differ. \n", - "\n", - "The\n", - "[Standadscaler](https://scikit-learn.org/stable/modules/generated/sklearn.preprocessing.StandardScaler.html)\n", - "function in **Scikit-Learn** does this for us. For the data sets we\n", - "have been studying in our various examples, the data are in many cases\n", - "already scaled and there is no need to scale them. You as a user of different machine learning algorithms, should always perform a\n", - "survey of your data, with a critical assessment of them in case you need to scale the data.\n", - "\n", - "If you need to scale the data, not doing so will give an *unfair*\n", - "penalization of the parameters since their magnitude depends on the\n", - "scale of their corresponding predictor.\n", - "\n", - "Suppose as an example that you \n", - "you have an input variable given by the heights of different persons.\n", - "Human height might be measured in inches or meters or\n", - "kilometers. If measured in kilometers, a standard linear regression\n", - "model with this predictor would probably give a much bigger\n", - "coefficient term, than if measured in millimeters.\n", - "This can clearly lead to problems in evaluating the cost/loss functions." - ] - }, - { - "cell_type": "markdown", - "id": "ed0f6bc0", - "metadata": { - "editable": true - }, - "source": [ - "## Still thinking\n", - "\n", - "Keep in mind that when you transform your data set before training a model, the same transformation needs to be done\n", - "on your eventual new data set before making a prediction. If we translate this into a Python code, it would could be implemented as follows\n", - "(note that the lines are commented since the model function has not been defined)" - ] - }, - { - "cell_type": "code", - "execution_count": 13, - "id": "99a1133f", - "metadata": { - "collapsed": false, - "editable": true - }, - "outputs": [], - "source": [ - "#Model training, we compute the mean value of y and X\n", - "y_train_mean = np.mean(y_train)\n", - "X_train_mean = np.mean(X_train,axis=0)\n", - "X_train = X_train - X_train_mean\n", - "y_train = y_train - y_train_mean\n", - "\n", - "# The we fit our model with the training data\n", - "#trained_model = some_model.fit(X_train,y_train)\n", - "\n", - "\n", - "#Model prediction, we need also to transform our data set used for the prediction.\n", - "X_test = X_test - X_train_mean #Use mean from training data\n", - "#y_pred = trained_model(X_test)\n", - "y_pred = y_pred + y_train_mean" - ] - }, - { - "cell_type": "markdown", - "id": "5ef9b25c", - "metadata": { - "editable": true - }, - "source": [ - "## What does centering (subtracting the mean values) mean mathematically?\n", - "\n", - "Let us try to understand what this may imply mathematically when we\n", - "subtract the mean values, also known as *zero centering*. For\n", - "simplicity, we will focus on ordinary regression, as done in the above example.\n", - "\n", - "The cost/loss function for regression is" - ] - }, - { - "cell_type": "markdown", - "id": "80ca5485", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "C(\\beta_0, \\beta_1, ... , \\beta_{p-1}) = \\frac{1}{n}\\sum_{i=0}^{n} \\left(y_i - \\beta_0 - \\sum_{j=1}^{p-1} X_{ij}\\beta_j\\right)^2,.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "17ad9823", - "metadata": { - "editable": true - }, - "source": [ - "Recall also that we use the squared value since this leads to an increase of the penalty for higher differences between predicted and output/target values.\n", - "\n", - "What we have done is to single out the $\\beta_0$ term in the definition of the mean squared error (MSE).\n", - "The design matrix\n", - "$X$ does in this case not contain any intercept column.\n", - "When we take the derivative with respect to $\\beta_0$, we want the derivative to obey" - ] - }, - { - "cell_type": "markdown", - "id": "7560f426", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\frac{\\partial C}{\\partial \\beta_j} = 0,\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "a7444f64", - "metadata": { - "editable": true - }, - "source": [ - "for all $j$. For $\\beta_0$ we have" - ] - }, - { - "cell_type": "markdown", - "id": "2aad0c8b", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\frac{\\partial C}{\\partial \\beta_0} = -\\frac{2}{n}\\sum_{i=0}^{n-1} \\left(y_i - \\beta_0 - \\sum_{j=1}^{p-1} X_{ij} \\beta_j\\right).\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "de870a72", - "metadata": { - "editable": true - }, - "source": [ - "Multiplying away the constant $2/n$, we obtain" - ] - }, - { - "cell_type": "markdown", - "id": "7a6c517e", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\sum_{i=0}^{n-1} \\beta_0 = \\sum_{i=0}^{n-1}y_i - \\sum_{i=0}^{n-1} \\sum_{j=1}^{p-1} X_{ij} \\beta_j.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "753afefe", - "metadata": { - "editable": true - }, - "source": [ - "## Further Manipulations\n", - "\n", - "Let us special first to the case where we have only two parameters $\\beta_0$ and $\\beta_1$.\n", - "Our result for $\\beta_0$ simplifies then to" - ] - }, - { - "cell_type": "markdown", - "id": "3005c150", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "n\\beta_0 = \\sum_{i=0}^{n-1}y_i - \\sum_{i=0}^{n-1} X_{i1} \\beta_1.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "79eace73", - "metadata": { - "editable": true - }, - "source": [ - "We obtain then" - ] - }, - { - "cell_type": "markdown", - "id": "38d75fef", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\beta_0 = \\frac{1}{n}\\sum_{i=0}^{n-1}y_i - \\beta_1\\frac{1}{n}\\sum_{i=0}^{n-1} X_{i1}.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "60f367fa", - "metadata": { - "editable": true - }, - "source": [ - "If we define" - ] - }, - { - "cell_type": "markdown", - "id": "9131a799", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\mu_1=\\frac{1}{n}\\sum_{i=0}^{n-1} (X_{i1},\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "8cbfafa2", - "metadata": { - "editable": true - }, - "source": [ - "and if we define the mean value of the outputs as" - ] - }, - { - "cell_type": "markdown", - "id": "9d4a45df", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\mu_y=\\frac{1}{n}\\sum_{i=0}^{n-1}y_i,\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "19284bfb", - "metadata": { - "editable": true - }, - "source": [ - "we have" - ] - }, - { - "cell_type": "markdown", - "id": "e1ccefe0", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\beta_0 = \\mu_y - \\beta_1\\mu_{1}.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "e6228ac9", - "metadata": { - "editable": true - }, - "source": [ - "In the general case, that is we have more parameters than $\\beta_0$ and $\\beta_1$, we have" - ] - }, - { - "cell_type": "markdown", - "id": "474d165a", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\beta_0 = \\frac{1}{n}\\sum_{i=0}^{n-1}y_i - \\frac{1}{n}\\sum_{i=0}^{n-1}\\sum_{j=1}^{p-1} X_{ij}\\beta_j.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "01c6f359", - "metadata": { - "editable": true - }, - "source": [ - "Replacing $y_i$ with $y_i - y_i - \\overline{\\boldsymbol{y}}$ and centering also our design matrix results in a cost function (in vector-matrix disguise)" - ] - }, - { - "cell_type": "markdown", - "id": "104df9ea", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "C(\\boldsymbol{\\beta}) = (\\boldsymbol{\\tilde{y}} - \\tilde{X}\\boldsymbol{\\beta})^T(\\boldsymbol{\\tilde{y}} - \\tilde{X}\\boldsymbol{\\beta}).\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "86f33ebf", - "metadata": { - "editable": true - }, - "source": [ - "## Wrapping it up\n", - "\n", - "If we minimize with respect to $\\boldsymbol{\\beta}$ we have then" - ] - }, - { - "cell_type": "markdown", - "id": "b8893d78", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\hat{\\boldsymbol{\\beta}} = (\\tilde{X}^T\\tilde{X})^{-1}\\tilde{X}^T\\boldsymbol{\\tilde{y}},\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "cc8ec307", - "metadata": { - "editable": true - }, - "source": [ - "where $\\boldsymbol{\\tilde{y}} = \\boldsymbol{y} - \\overline{\\boldsymbol{y}}$\n", - "and $\\tilde{X}_{ij} = X_{ij} - \\frac{1}{n}\\sum_{k=0}^{n-1}X_{kj}$.\n", - "\n", - "For Ridge regression we need to add $\\lambda \\boldsymbol{\\beta}^T\\boldsymbol{\\beta}$ to the cost function and get then" - ] - }, - { - "cell_type": "markdown", - "id": "234e3f6e", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\hat{\\boldsymbol{\\beta}} = (\\tilde{X}^T\\tilde{X} + \\lambda I)^{-1}\\tilde{X}^T\\boldsymbol{\\tilde{y}}.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "d1c0397f", - "metadata": { - "editable": true - }, - "source": [ - "What does this mean? And why do we insist on all this? Let us look at some examples." - ] - }, - { - "cell_type": "markdown", - "id": "799912a7", - "metadata": { - "editable": true - }, - "source": [ - "## Linear Regression code, Intercept handling first\n", - "\n", - "This code shows a simple first-order fit to a data set using the above transformed data, where we consider the role of the intercept first, by either excluding it or including it (*code example thanks to Øyvind Sigmundson Schøyen*). Here our scaling of the data is done by subtracting the mean values only.\n", - "Note also that we do not split the data into training and test." - ] - }, - { - "cell_type": "code", - "execution_count": 14, - "id": "5a3de91e", - "metadata": { - "collapsed": false, - "editable": true - }, - "outputs": [], - "source": [ - "import numpy as np\n", - "import matplotlib.pyplot as plt\n", - "\n", - "from sklearn.linear_model import LinearRegression\n", - "\n", - "\n", - "np.random.seed(2021)\n", - "\n", - "def MSE(y_data,y_model):\n", - " n = np.size(y_model)\n", - " return np.sum((y_data-y_model)**2)/n\n", - "\n", - "\n", - "def fit_beta(X, y):\n", - " return np.linalg.pinv(X.T @ X) @ X.T @ y\n", - "\n", - "\n", - "true_beta = [2, 0.5, 3.7]\n", - "\n", - "x = np.linspace(0, 1, 11)\n", - "y = np.sum(\n", - " np.asarray([x ** p * b for p, b in enumerate(true_beta)]), axis=0\n", - ") + 0.1 * np.random.normal(size=len(x))\n", - "\n", - "degree = 3\n", - "X = np.zeros((len(x), degree))\n", - "\n", - "# Include the intercept in the design matrix\n", - "for p in range(degree):\n", - " X[:, p] = x ** p\n", - "\n", - "beta = fit_beta(X, y)\n", - "\n", - "# Intercept is included in the design matrix\n", - "skl = LinearRegression(fit_intercept=False).fit(X, y)\n", - "\n", - "print(f\"True beta: {true_beta}\")\n", - "print(f\"Fitted beta: {beta}\")\n", - "print(f\"Sklearn fitted beta: {skl.coef_}\")\n", - "ypredictOwn = X @ beta\n", - "ypredictSKL = skl.predict(X)\n", - "print(f\"MSE with intercept column\")\n", - "print(MSE(y,ypredictOwn))\n", - "print(f\"MSE with intercept column from SKL\")\n", - "print(MSE(y,ypredictSKL))\n", - "\n", - "\n", - "plt.figure()\n", - "plt.scatter(x, y, label=\"Data\")\n", - "plt.plot(x, X @ beta, label=\"Fit\")\n", - "plt.plot(x, skl.predict(X), label=\"Sklearn (fit_intercept=False)\")\n", - "\n", - "\n", - "# Do not include the intercept in the design matrix\n", - "X = np.zeros((len(x), degree - 1))\n", - "\n", - "for p in range(degree - 1):\n", - " X[:, p] = x ** (p + 1)\n", - "\n", - "# Intercept is not included in the design matrix\n", - "skl = LinearRegression(fit_intercept=True).fit(X, y)\n", - "\n", - "# Use centered values for X and y when computing coefficients\n", - "y_offset = np.average(y, axis=0)\n", - "X_offset = np.average(X, axis=0)\n", - "\n", - "beta = fit_beta(X - X_offset, y - y_offset)\n", - "intercept = np.mean(y_offset - X_offset @ beta)\n", - "\n", - "print(f\"Manual intercept: {intercept}\")\n", - "print(f\"Fitted beta (wiothout intercept): {beta}\")\n", - "print(f\"Sklearn intercept: {skl.intercept_}\")\n", - "print(f\"Sklearn fitted beta (without intercept): {skl.coef_}\")\n", - "ypredictOwn = X @ beta\n", - "ypredictSKL = skl.predict(X)\n", - "print(f\"MSE with Manual intercept\")\n", - "print(MSE(y,ypredictOwn+intercept))\n", - "print(f\"MSE with Sklearn intercept\")\n", - "print(MSE(y,ypredictSKL))\n", - "\n", - "plt.plot(x, X @ beta + intercept, \"--\", label=\"Fit (manual intercept)\")\n", - "plt.plot(x, skl.predict(X), \"--\", label=\"Sklearn (fit_intercept=True)\")\n", - "plt.grid()\n", - "plt.legend()\n", - "\n", - "plt.show()" - ] - }, - { - "cell_type": "markdown", - "id": "0f069973", - "metadata": { - "editable": true - }, - "source": [ - "The intercept is the value of our output/target variable\n", - "when all our features are zero and our function crosses the $y$-axis (for a one-dimensional case). \n", - "\n", - "Printing the MSE, we see first that both methods give the same MSE, as\n", - "they should. However, when we move to for example Ridge regression (discussed next week),\n", - "the way we treat the intercept may give a larger or smaller MSE,\n", - "meaning that the MSE can be penalized by the value of the\n", - "intercept. Not including the intercept in the fit, means that the\n", - "regularization term does not include $\\beta_0$. For different values\n", - "of $\\lambda$, this may lead to differing MSE values. \n", - "\n", - "To remind the reader, the regularization term, with the intercept in Ridge regression is given by" - ] - }, - { - "cell_type": "markdown", - "id": "e76beb96", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\lambda \\vert\\vert \\boldsymbol{\\beta} \\vert\\vert_2^2 = \\lambda \\sum_{j=0}^{p-1}\\beta_j^2,\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "4fe81d64", - "metadata": { - "editable": true - }, - "source": [ - "but when we take out the intercept, this equation becomes" - ] - }, - { - "cell_type": "markdown", - "id": "bb22d80f", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\lambda \\vert\\vert \\boldsymbol{\\beta} \\vert\\vert_2^2 = \\lambda \\sum_{j=1}^{p-1}\\beta_j^2.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "293ce41e", - "metadata": { - "editable": true - }, - "source": [ - "For Lasso regression we have" - ] - }, - { - "cell_type": "markdown", - "id": "8a969677", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\lambda \\vert\\vert \\boldsymbol{\\beta} \\vert\\vert_1 = \\lambda \\sum_{j=1}^{p-1}\\vert\\beta_j\\vert.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "d93685ad", - "metadata": { - "editable": true - }, - "source": [ - "It means that, when scaling the design matrix and the outputs/targets,\n", - "by subtracting the mean values, we have an optimization problem which\n", - "is not penalized by the intercept. The MSE value can then be smaller\n", - "since it focuses only on the remaining quantities. If we however bring\n", - "back the intercept, we will get an MSE which then contains the\n", - "intercept. This becomes more important when we discuss Ridge and Lasso\n", - "regression next week." - ] - }, - { - "cell_type": "markdown", - "id": "9abd5b44", - "metadata": { - "editable": true - }, - "source": [ - "## The Boston housing data example\n", - "\n", - "The Boston housing \n", - "data set was originally a part of UCI Machine Learning Repository\n", - "and has been removed now. The data set is now included in **Scikit-Learn**'s \n", - "library. There are 506 samples and 13 feature (predictor) variables\n", - "in this data set. The objective is to predict the value of prices of\n", - "the house using the features (predictors) listed here.\n", - "\n", - "The features/predictors are\n", - "1. CRIM: Per capita crime rate by town\n", - "\n", - "2. ZN: Proportion of residential land zoned for lots over 25000 square feet\n", - "\n", - "3. INDUS: Proportion of non-retail business acres per town\n", - "\n", - "4. CHAS: Charles River dummy variable (= 1 if tract bounds river; 0 otherwise)\n", - "\n", - "5. NOX: Nitric oxide concentration (parts per 10 million)\n", - "\n", - "6. RM: Average number of rooms per dwelling\n", - "\n", - "7. AGE: Proportion of owner-occupied units built prior to 1940\n", - "\n", - "8. DIS: Weighted distances to five Boston employment centers\n", - "\n", - "9. RAD: Index of accessibility to radial highways\n", - "\n", - "10. TAX: Full-value property tax rate per USD10000\n", - "\n", - "11. B: $1000(Bk - 0.63)^2$, where $Bk$ is the proportion of [people of African American descent] by town\n", - "\n", - "12. LSTAT: Percentage of lower status of the population\n", - "\n", - "13. MEDV: Median value of owner-occupied homes in USD 1000s" - ] - }, - { - "cell_type": "markdown", - "id": "b8bd6825", - "metadata": { - "editable": true - }, - "source": [ - "## Housing data, the code\n", - "We start by importing the libraries" - ] - }, - { - "cell_type": "code", - "execution_count": 15, - "id": "2c2b3d87", - "metadata": { - "collapsed": false, - "editable": true - }, - "outputs": [], - "source": [ - "import numpy as np\n", - "import matplotlib.pyplot as plt \n", - "\n", - "import pandas as pd \n", - "import seaborn as sns" - ] - }, - { - "cell_type": "markdown", - "id": "fea1bc2e", - "metadata": { - "editable": true - }, - "source": [ - "and load the Boston Housing DataSet from **Scikit-Learn**" - ] - }, - { - "cell_type": "code", - "execution_count": 16, - "id": "a80976dc", - "metadata": { - "collapsed": false, - "editable": true - }, - "outputs": [], - "source": [ - "from sklearn.datasets import load_boston\n", - "\n", - "boston_dataset = load_boston()\n", - "\n", - "# boston_dataset is a dictionary\n", - "# let's check what it contains\n", - "boston_dataset.keys()" - ] - }, - { - "cell_type": "markdown", - "id": "aa3b722c", - "metadata": { - "editable": true - }, - "source": [ - "Then we invoke Pandas" - ] - }, - { - "cell_type": "code", - "execution_count": 17, - "id": "828172e1", - "metadata": { - "collapsed": false, - "editable": true - }, - "outputs": [], - "source": [ - "boston = pd.DataFrame(boston_dataset.data, columns=boston_dataset.feature_names)\n", - "boston.head()\n", - "boston['MEDV'] = boston_dataset.target" - ] - }, - { - "cell_type": "markdown", - "id": "eee71c11", - "metadata": { - "editable": true - }, - "source": [ - "and preprocess the data" - ] - }, - { - "cell_type": "code", - "execution_count": 18, - "id": "7c8a5c54", - "metadata": { - "collapsed": false, - "editable": true - }, - "outputs": [], - "source": [ - "# check for missing values in all the columns\n", - "boston.isnull().sum()" - ] - }, - { - "cell_type": "markdown", - "id": "a0c893b5", - "metadata": { - "editable": true - }, - "source": [ - "We can then visualize the data" - ] - }, - { - "cell_type": "code", - "execution_count": 19, - "id": "58711c38", - "metadata": { - "collapsed": false, - "editable": true - }, - "outputs": [], - "source": [ - "# set the size of the figure\n", - "sns.set(rc={'figure.figsize':(11.7,8.27)})\n", - "\n", - "# plot a histogram showing the distribution of the target values\n", - "sns.distplot(boston['MEDV'], bins=30)\n", - "plt.show()" - ] - }, - { - "cell_type": "markdown", - "id": "d899ec3f", - "metadata": { - "editable": true - }, - "source": [ - "It is now useful to look at the correlation matrix" - ] - }, - { - "cell_type": "code", - "execution_count": 20, - "id": "59925df7", - "metadata": { - "collapsed": false, - "editable": true - }, - "outputs": [], - "source": [ - "# compute the pair wise correlation for all columns \n", - "correlation_matrix = boston.corr().round(2)\n", - "# use the heatmap function from seaborn to plot the correlation matrix\n", - "# annot = True to print the values inside the square\n", - "sns.heatmap(data=correlation_matrix, annot=True)" - ] - }, - { - "cell_type": "markdown", - "id": "083a679e", - "metadata": { - "editable": true - }, - "source": [ - "From the above coorelation plot we can see that **MEDV** is strongly correlated to **LSTAT** and **RM**. We see also that **RAD** and **TAX** are stronly correlated, but we don't include this in our features together to avoid multi-colinearity" - ] - }, - { - "cell_type": "code", - "execution_count": 21, - "id": "127a3dda", - "metadata": { - "collapsed": false, - "editable": true - }, - "outputs": [], - "source": [ - "plt.figure(figsize=(20, 5))\n", - "\n", - "features = ['LSTAT', 'RM']\n", - "target = boston['MEDV']\n", - "\n", - "for i, col in enumerate(features):\n", - " plt.subplot(1, len(features) , i+1)\n", - " x = boston[col]\n", - " y = target\n", - " plt.scatter(x, y, marker='o')\n", - " plt.title(col)\n", - " plt.xlabel(col)\n", - " plt.ylabel('MEDV')" - ] - }, - { - "cell_type": "markdown", - "id": "c72d1b7f", - "metadata": { - "editable": true - }, - "source": [ - "Now we start training our model" - ] - }, - { - "cell_type": "code", - "execution_count": 22, - "id": "a1378976", - "metadata": { - "collapsed": false, - "editable": true - }, - "outputs": [], - "source": [ - "X = pd.DataFrame(np.c_[boston['LSTAT'], boston['RM']], columns = ['LSTAT','RM'])\n", - "Y = boston['MEDV']" - ] - }, - { - "cell_type": "markdown", - "id": "d85205c1", - "metadata": { - "editable": true - }, - "source": [ - "We split the data into training and test sets" - ] - }, - { - "cell_type": "code", - "execution_count": 23, - "id": "040b1e85", - "metadata": { - "collapsed": false, - "editable": true - }, - "outputs": [], - "source": [ - "from sklearn.model_selection import train_test_split\n", - "\n", - "# splits the training and test data set in 80% : 20%\n", - "# assign random_state to any value.This ensures consistency.\n", - "X_train, X_test, Y_train, Y_test = train_test_split(X, Y, test_size = 0.2, random_state=5)\n", - "print(X_train.shape)\n", - "print(X_test.shape)\n", - "print(Y_train.shape)\n", - "print(Y_test.shape)" - ] - }, - { - "cell_type": "markdown", - "id": "32d25d47", - "metadata": { - "editable": true - }, - "source": [ - "Then we use the linear regression functionality from **Scikit-Learn**" - ] - }, - { - "cell_type": "code", - "execution_count": 24, - "id": "1b0fac0d", - "metadata": { - "collapsed": false, - "editable": true - }, - "outputs": [], - "source": [ - "from sklearn.linear_model import LinearRegression\n", - "from sklearn.metrics import mean_squared_error, r2_score\n", - "\n", - "lin_model = LinearRegression()\n", - "lin_model.fit(X_train, Y_train)\n", - "\n", - "# model evaluation for training set\n", - "\n", - "y_train_predict = lin_model.predict(X_train)\n", - "rmse = (np.sqrt(mean_squared_error(Y_train, y_train_predict)))\n", - "r2 = r2_score(Y_train, y_train_predict)\n", - "\n", - "print(\"The model performance for training set\")\n", - "print(\"--------------------------------------\")\n", - "print('RMSE is {}'.format(rmse))\n", - "print('R2 score is {}'.format(r2))\n", - "print(\"\\n\")\n", - "\n", - "# model evaluation for testing set\n", - "\n", - "y_test_predict = lin_model.predict(X_test)\n", - "# root mean square error of the model\n", - "rmse = (np.sqrt(mean_squared_error(Y_test, y_test_predict)))\n", - "\n", - "# r-squared score of the model\n", - "r2 = r2_score(Y_test, y_test_predict)\n", - "\n", - "print(\"The model performance for testing set\")\n", - "print(\"--------------------------------------\")\n", - "print('RMSE is {}'.format(rmse))\n", - "print('R2 score is {}'.format(r2))" - ] - }, - { - "cell_type": "code", - "execution_count": 25, - "id": "02279b28", - "metadata": { - "collapsed": false, - "editable": true - }, - "outputs": [], - "source": [ - "# plotting the y_test vs y_pred\n", - "# ideally should have been a straight line\n", - "plt.scatter(Y_test, y_test_predict)\n", - "plt.show()" - ] - }, - { - "cell_type": "markdown", - "id": "cd590eba", - "metadata": { - "editable": true - }, - "source": [ - "## Material for lecture Thursday, August 31" - ] - }, - { - "cell_type": "markdown", - "id": "9968e6df", - "metadata": { - "editable": true - }, - "source": [ - "## Mathematical Interpretation of Ordinary Least Squares\n", - "\n", - "What is presented here is a mathematical analysis of various regression algorithms (ordinary least squares, Ridge and Lasso Regression). The analysis is based on an important algorithm in linear algebra, the so-called Singular Value Decomposition (SVD). \n", - "\n", - "We have shown that in ordinary least squares the optimal parameters $\\beta$ are given by" - ] - }, - { - "cell_type": "markdown", - "id": "6e0b933c", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\hat{\\boldsymbol{\\beta}} = \\left(\\boldsymbol{X}^T\\boldsymbol{X}\\right)^{-1}\\boldsymbol{X}^T\\boldsymbol{y}.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "e3019867", - "metadata": { - "editable": true - }, - "source": [ - "The **hat** over $\\boldsymbol{\\beta}$ means we have the optimal parameters after minimization of the cost function.\n", - "\n", - "This means that our best model is defined as" - ] - }, - { - "cell_type": "markdown", - "id": "84b218f8", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\tilde{\\boldsymbol{y}}=\\boldsymbol{X}\\hat{\\boldsymbol{\\beta}} = \\boldsymbol{X}\\left(\\boldsymbol{X}^T\\boldsymbol{X}\\right)^{-1}\\boldsymbol{X}^T\\boldsymbol{y}.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "19a7596b", - "metadata": { - "editable": true - }, - "source": [ - "We now define a matrix" - ] - }, - { - "cell_type": "markdown", - "id": "bd703e67", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\boldsymbol{A}=\\boldsymbol{X}\\left(\\boldsymbol{X}^T\\boldsymbol{X}\\right)^{-1}\\boldsymbol{X}^T.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "123c9939", - "metadata": { - "editable": true - }, - "source": [ - "We can rewrite" - ] - }, - { - "cell_type": "markdown", - "id": "e25cd9d9", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\tilde{\\boldsymbol{y}}=\\boldsymbol{X}\\hat{\\boldsymbol{\\beta}} = \\boldsymbol{A}\\boldsymbol{y}.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "7a90c314", - "metadata": { - "editable": true - }, - "source": [ - "The matrix $\\boldsymbol{A}$ has the important property that $\\boldsymbol{A}^2=\\boldsymbol{A}$. This is the definition of a projection matrix.\n", - "We can then interpret our optimal model $\\tilde{\\boldsymbol{y}}$ as being represented by an orthogonal projection of $\\boldsymbol{y}$ onto a space defined by the column vectors of $\\boldsymbol{X}$. In our case here the matrix $\\boldsymbol{A}$ is a square matrix. If it is a general rectangular matrix we have an oblique projection matrix." - ] - }, - { - "cell_type": "markdown", - "id": "342cbb0e", - "metadata": { - "editable": true - }, - "source": [ - "## Residual Error\n", - "\n", - "We have defined the residual error as" - ] - }, - { - "cell_type": "markdown", - "id": "8174f656", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\boldsymbol{\\epsilon}=\\boldsymbol{y}-\\tilde{\\boldsymbol{y}}=\\left[\\boldsymbol{I}-\\boldsymbol{X}\\left(\\boldsymbol{X}^T\\boldsymbol{X}\\right)^{-1}\\boldsymbol{X}^T\\right]\\boldsymbol{y}.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "9d4a6e02", - "metadata": { - "editable": true - }, - "source": [ - "The residual errors are then the projections of $\\boldsymbol{y}$ onto the orthogonal component of the space defined by the column vectors of $\\boldsymbol{X}$." - ] - }, - { - "cell_type": "markdown", - "id": "6165636b", - "metadata": { - "editable": true - }, - "source": [ - "## Simple case\n", - "\n", - "If the matrix $\\boldsymbol{X}$ is an orthogonal (or unitary in case of complex values) matrix, we have" - ] - }, - { - "cell_type": "markdown", - "id": "cd5ead70", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\boldsymbol{X}^T\\boldsymbol{X}=\\boldsymbol{X}\\boldsymbol{X}^T = \\boldsymbol{I}.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "ea18f6fe", - "metadata": { - "editable": true - }, - "source": [ - "In this case the matrix $\\boldsymbol{A}$ becomes" - ] - }, - { - "cell_type": "markdown", - "id": "9b42e1cf", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\boldsymbol{A}=\\boldsymbol{X}\\left(\\boldsymbol{X}^T\\boldsymbol{X}\\right)^{-1}\\boldsymbol{X}^T)=\\boldsymbol{I},\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "ddc58b22", - "metadata": { - "editable": true - }, - "source": [ - "and we have the obvious case" - ] - }, - { - "cell_type": "markdown", - "id": "288e8e6a", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\boldsymbol{\\epsilon}=\\boldsymbol{y}-\\tilde{\\boldsymbol{y}}=0.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "4fd80694", - "metadata": { - "editable": true - }, - "source": [ - "This serves also as a useful test of our codes." - ] - }, - { - "cell_type": "markdown", - "id": "b006a8c2", - "metadata": { - "editable": true - }, - "source": [ - "## The singular value decomposition\n", - "\n", - "The examples we have looked at so far are cases where we normally can\n", - "invert the matrix $\\boldsymbol{X}^T\\boldsymbol{X}$. Using a polynomial expansion where we fit of various functions leads to\n", - "row vectors of the design matrix which are essentially orthogonal due\n", - "to the polynomial character of our model. Obtaining the inverse of the\n", - "design matrix is then often done via a so-called LU, QR or Cholesky\n", - "decomposition.\n", - "\n", - "As we will also see in the first project, \n", - "this may\n", - "however not the be case in general and a standard matrix inversion\n", - "algorithm based on say LU, QR or Cholesky decomposition may lead to singularities. We will see examples of this below.\n", - "\n", - "There is however a way to circumvent this problem and also\n", - "gain some insights about the ordinary least squares approach, and\n", - "later shrinkage methods like Ridge and Lasso regressions.\n", - "\n", - "This is given by the **Singular Value Decomposition** (SVD) algorithm,\n", - "perhaps the most powerful linear algebra algorithm. The SVD provides\n", - "a numerically stable matrix decomposition that is used in a large\n", - "swath oc applications and the decomposition is always stable\n", - "numerically.\n", - "\n", - "In machine learning it plays a central role in dealing with for\n", - "example design matrices that may be near singular or singular.\n", - "Furthermore, as we will see here, the singular values can be related\n", - "to the covariance matrix (and thereby the correlation matrix) and in\n", - "turn the variance of a given quantity. It plays also an important role\n", - "in the principal component analysis where high-dimensional data can be\n", - "reduced to the statistically relevant features." - ] - }, - { - "cell_type": "markdown", - "id": "725d878b", - "metadata": { - "editable": true - }, - "source": [ - "## Linear Regression Problems\n", - "\n", - "One of the typical problems we encounter with linear regression, in particular \n", - "when the matrix $\\boldsymbol{X}$ (our so-called design matrix) is high-dimensional, \n", - "are problems with near singular or singular matrices. The column vectors of $\\boldsymbol{X}$ \n", - "may be linearly dependent, normally referred to as super-collinearity. \n", - "This means that the matrix may be rank deficient and it is basically impossible to \n", - "to model the data using linear regression. As an example, consider the matrix" - ] - }, - { - "cell_type": "markdown", - "id": "fd5e5178", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\begin{align*}\n", - "\\mathbf{X} & = \\left[\n", - "\\begin{array}{rrr}\n", - "1 & -1 & 2\n", - "\\\\\n", - "1 & 0 & 1\n", - "\\\\\n", - "1 & 2 & -1\n", - "\\\\\n", - "1 & 1 & 0\n", - "\\end{array} \\right]\n", - "\\end{align*}\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "153ac58e", - "metadata": { - "editable": true - }, - "source": [ - "The columns of $\\boldsymbol{X}$ are linearly dependent. We see this easily since the \n", - "the first column is the row-wise sum of the other two columns. The rank (more correct,\n", - "the column rank) of a matrix is the dimension of the space spanned by the\n", - "column vectors. Hence, the rank of $\\mathbf{X}$ is equal to the number\n", - "of linearly independent columns. In this particular case the matrix has rank 2.\n", - "\n", - "Super-collinearity of an $(n \\times p)$-dimensional design matrix $\\mathbf{X}$ implies\n", - "that the inverse of the matrix $\\boldsymbol{X}^T\\boldsymbol{X}$ (the matrix we need to invert to solve the linear regression equations) is non-invertible. If we have a square matrix that does not have an inverse, we say this matrix singular. The example here demonstrates this" - ] - }, - { - "cell_type": "markdown", - "id": "3a4c4a00", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\begin{align*}\n", - "\\boldsymbol{X} & = \\left[\n", - "\\begin{array}{rr}\n", - "1 & -1\n", - "\\\\\n", - "1 & -1\n", - "\\end{array} \\right].\n", - "\\end{align*}\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "c102eee7", - "metadata": { - "editable": true - }, - "source": [ - "We see easily that $\\mbox{det}(\\boldsymbol{X}) = x_{11} x_{22} - x_{12} x_{21} = 1 \\times (-1) - 1 \\times (-1) = 0$. Hence, $\\mathbf{X}$ is singular and its inverse is undefined.\n", - "This is equivalent to saying that the matrix $\\boldsymbol{X}$ has at least an eigenvalue which is zero." - ] - }, - { - "cell_type": "markdown", - "id": "7005d428", - "metadata": { - "editable": true - }, - "source": [ - "## Fixing the singularity\n", - "\n", - "If our design matrix $\\boldsymbol{X}$ which enters the linear regression problem" - ] - }, - { - "cell_type": "markdown", - "id": "ebdbde59", - "metadata": { - "editable": true - }, - "source": [ - "\n", - "
\n", - "\n", - "$$\n", - "\\begin{equation}\n", - "\\boldsymbol{\\beta} = (\\boldsymbol{X}^{T} \\boldsymbol{X})^{-1} \\boldsymbol{X}^{T} \\boldsymbol{y},\n", - "\\label{_auto1} \\tag{1}\n", - "\\end{equation}\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "8757437b", - "metadata": { - "editable": true - }, - "source": [ - "has linearly dependent column vectors, we will not be able to compute the inverse\n", - "of $\\boldsymbol{X}^T\\boldsymbol{X}$ and we cannot find the parameters (estimators) $\\beta_i$. \n", - "The estimators are only well-defined if $(\\boldsymbol{X}^{T}\\boldsymbol{X})^{-1}$ exits. \n", - "This is more likely to happen when the matrix $\\boldsymbol{X}$ is high-dimensional. In this case it is likely to encounter a situation where \n", - "the regression parameters $\\beta_i$ cannot be estimated.\n", - "\n", - "A cheap *ad hoc* approach is simply to add a small diagonal component to the matrix to invert, that is we change" - ] - }, - { - "cell_type": "markdown", - "id": "dba77cf1", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\boldsymbol{X}^{T} \\boldsymbol{X} \\rightarrow \\boldsymbol{X}^{T} \\boldsymbol{X}+\\lambda \\boldsymbol{I},\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "2f275695", - "metadata": { - "editable": true - }, - "source": [ - "where $\\boldsymbol{I}$ is the identity matrix. When we discuss **Ridge** regression this is actually what we end up evaluating. The parameter $\\lambda$ is called a hyperparameter. More about this later." - ] - }, - { - "cell_type": "markdown", - "id": "32c17033", - "metadata": { - "editable": true - }, - "source": [ - "## Basic math of the SVD\n", - "\n", - "From standard linear algebra we know that a square matrix $\\boldsymbol{X}$ can be diagonalized if and only it is \n", - "a so-called [normal matrix](https://en.wikipedia.org/wiki/Normal_matrix), that is if $\\boldsymbol{X}\\in {\\mathbb{R}}^{n\\times n}$\n", - "we have $\\boldsymbol{X}\\boldsymbol{X}^T=\\boldsymbol{X}^T\\boldsymbol{X}$ or if $\\boldsymbol{X}\\in {\\mathbb{C}}^{n\\times n}$ we have $\\boldsymbol{X}\\boldsymbol{X}^{\\dagger}=\\boldsymbol{X}^{\\dagger}\\boldsymbol{X}$.\n", - "The matrix has then a set of eigenpairs" - ] - }, - { - "cell_type": "markdown", - "id": "13d50641", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "(\\lambda_1,\\boldsymbol{u}_1),\\dots, (\\lambda_n,\\boldsymbol{u}_n),\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "e32d182b", - "metadata": { - "editable": true - }, - "source": [ - "and the eigenvalues are given by the diagonal matrix" - ] - }, - { - "cell_type": "markdown", - "id": "566185cc", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\boldsymbol{\\Sigma}=\\mathrm{Diag}(\\lambda_1, \\dots,\\lambda_n).\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "69cc07d3", - "metadata": { - "editable": true - }, - "source": [ - "The matrix $\\boldsymbol{X}$ can be written in terms of an orthogonal/unitary transformation $\\boldsymbol{U}$" - ] - }, - { - "cell_type": "markdown", - "id": "5a62e55b", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\boldsymbol{X} = \\boldsymbol{U}\\boldsymbol{\\Sigma}\\boldsymbol{V}^T,\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "185a7b6c", - "metadata": { - "editable": true - }, - "source": [ - "with $\\boldsymbol{U}\\boldsymbol{U}^T=\\boldsymbol{I}$ or $\\boldsymbol{U}\\boldsymbol{U}^{\\dagger}=\\boldsymbol{I}$.\n", - "\n", - "Not all square matrices are diagonalizable. A matrix like the one discussed above" - ] - }, - { - "cell_type": "markdown", - "id": "b63994c4", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\boldsymbol{X} = \\begin{bmatrix} \n", - "1& -1 \\\\\n", - "1& -1\\\\\n", - "\\end{bmatrix}\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "1b5e5ea8", - "metadata": { - "editable": true - }, - "source": [ - "is not diagonalizable, it is a so-called [defective matrix](https://en.wikipedia.org/wiki/Defective_matrix). It is easy to see that the condition\n", - "$\\boldsymbol{X}\\boldsymbol{X}^T=\\boldsymbol{X}^T\\boldsymbol{X}$ is not fulfilled." - ] - }, - { - "cell_type": "markdown", - "id": "c7cba8d9", - "metadata": { - "editable": true - }, - "source": [ - "## The SVD, a Fantastic Algorithm\n", - "\n", - "However, and this is the strength of the SVD algorithm, any general\n", - "matrix $\\boldsymbol{X}$ can be decomposed in terms of a diagonal matrix and\n", - "two orthogonal/unitary matrices. The [Singular Value Decompostion\n", - "(SVD) theorem](https://en.wikipedia.org/wiki/Singular_value_decomposition)\n", - "states that a general $m\\times n$ matrix $\\boldsymbol{X}$ can be written in\n", - "terms of a diagonal matrix $\\boldsymbol{\\Sigma}$ of dimensionality $m\\times n$\n", - "and two orthognal matrices $\\boldsymbol{U}$ and $\\boldsymbol{V}$, where the first has\n", - "dimensionality $m \\times m$ and the last dimensionality $n\\times n$.\n", - "We have then" - ] - }, - { - "cell_type": "markdown", - "id": "34a321a1", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\boldsymbol{X} = \\boldsymbol{U}\\boldsymbol{\\Sigma}\\boldsymbol{V}^T\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "adeb4e2a", - "metadata": { - "editable": true - }, - "source": [ - "As an example, the above defective matrix can be decomposed as" - ] - }, - { - "cell_type": "markdown", - "id": "983c4d05", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\boldsymbol{X} = \\frac{1}{\\sqrt{2}}\\begin{bmatrix} 1& 1 \\\\ 1& -1\\\\ \\end{bmatrix} \\begin{bmatrix} 2& 0 \\\\ 0& 0\\\\ \\end{bmatrix} \\frac{1}{\\sqrt{2}}\\begin{bmatrix} 1& -1 \\\\ 1& 1\\\\ \\end{bmatrix}=\\boldsymbol{U}\\boldsymbol{\\Sigma}\\boldsymbol{V}^T,\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "30746d8f", - "metadata": { - "editable": true - }, - "source": [ - "with eigenvalues $\\sigma_1=2$ and $\\sigma_2=0$. \n", - "The SVD exits always! \n", - "\n", - "The SVD\n", - "decomposition (singular values) gives eigenvalues \n", - "$\\sigma_i\\geq\\sigma_{i+1}$ for all $i$ and for dimensions larger than $i=p$, the\n", - "eigenvalues (singular values) are zero.\n", - "\n", - "In the general case, where our design matrix $\\boldsymbol{X}$ has dimension\n", - "$n\\times p$, the matrix is thus decomposed into an $n\\times n$\n", - "orthogonal matrix $\\boldsymbol{U}$, a $p\\times p$ orthogonal matrix $\\boldsymbol{V}$\n", - "and a diagonal matrix $\\boldsymbol{\\Sigma}$ with $r=\\mathrm{min}(n,p)$\n", - "singular values $\\sigma_i\\geq 0$ on the main diagonal and zeros filling\n", - "the rest of the matrix. There are at most $p$ singular values\n", - "assuming that $n > p$. In our regression examples for the nuclear\n", - "masses and the equation of state this is indeed the case, while for\n", - "the Ising model we have $p > n$. These are often cases that lead to\n", - "near singular or singular matrices.\n", - "\n", - "The columns of $\\boldsymbol{U}$ are called the left singular vectors while the columns of $\\boldsymbol{V}$ are the right singular vectors." - ] - }, - { - "cell_type": "markdown", - "id": "15b1904e", - "metadata": { - "editable": true - }, - "source": [ - "## Economy-size SVD\n", - "\n", - "If we assume that $n > p$, then our matrix $\\boldsymbol{U}$ has dimension $n\n", - "\\times n$. The last $n-p$ columns of $\\boldsymbol{U}$ become however\n", - "irrelevant in our calculations since they are multiplied with the\n", - "zeros in $\\boldsymbol{\\Sigma}$.\n", - "\n", - "The economy-size decomposition removes extra rows or columns of zeros\n", - "from the diagonal matrix of singular values, $\\boldsymbol{\\Sigma}$, along with the columns\n", - "in either $\\boldsymbol{U}$ or $\\boldsymbol{V}$ that multiply those zeros in the expression. \n", - "Removing these zeros and columns can improve execution time\n", - "and reduce storage requirements without compromising the accuracy of\n", - "the decomposition.\n", - "\n", - "If $n > p$, we keep only the first $p$ columns of $\\boldsymbol{U}$ and $\\boldsymbol{\\Sigma}$ has dimension $p\\times p$. \n", - "If $p > n$, then only the first $n$ columns of $\\boldsymbol{V}$ are computed and $\\boldsymbol{\\Sigma}$ has dimension $n\\times n$.\n", - "The $n=p$ case is obvious, we retain the full SVD. \n", - "In general the economy-size SVD leads to less FLOPS and still conserving the desired accuracy." - ] - }, - { - "cell_type": "markdown", - "id": "825d56c0", - "metadata": { - "editable": true - }, - "source": [ - "## Codes for the SVD" - ] - }, - { - "cell_type": "code", - "execution_count": 26, - "id": "83389e7a", - "metadata": { - "collapsed": false, - "editable": true - }, - "outputs": [], - "source": [ - "import numpy as np\n", - "# SVD inversion\n", - "def SVD(A):\n", - " ''' Takes as input a numpy matrix A and returns inv(A) based on singular value decomposition (SVD).\n", - " SVD is numerically more stable than the inversion algorithms provided by\n", - " numpy and scipy.linalg at the cost of being slower.\n", - " '''\n", - " U, S, VT = np.linalg.svd(A,full_matrices=True)\n", - " print('test U')\n", - " print( (np.transpose(U) @ U - U @np.transpose(U)))\n", - " print('test VT')\n", - " print( (np.transpose(VT) @ VT - VT @np.transpose(VT)))\n", - " print(U)\n", - " print(S)\n", - " print(VT)\n", - "\n", - " D = np.zeros((len(U),len(VT)))\n", - " for i in range(0,len(VT)):\n", - " D[i,i]=S[i]\n", - " return U @ D @ VT\n", - "\n", - "\n", - "X = np.array([ [1.0,-1.0], [1.0,-1.0]])\n", - "#X = np.array([[1, 2], [3, 4], [5, 6]])\n", - "\n", - "print(X)\n", - "C = SVD(X)\n", - "# Print the difference between the original matrix and the SVD one\n", - "print(C-X)" - ] - }, - { - "cell_type": "markdown", - "id": "6c1d5c64", - "metadata": { - "editable": true - }, - "source": [ - "The matrix $\\boldsymbol{X}$ has columns that are linearly dependent. The first\n", - "column is the row-wise sum of the other two columns. The rank of a\n", - "matrix (the column rank) is the dimension of space spanned by the\n", - "column vectors. The rank of the matrix is the number of linearly\n", - "independent columns, in this case just $2$. We see this from the\n", - "singular values when running the above code. Running the standard\n", - "inversion algorithm for matrix inversion with $\\boldsymbol{X}^T\\boldsymbol{X}$ results\n", - "in the program terminating due to a singular matrix." - ] - }, - { - "cell_type": "markdown", - "id": "092d08fb", - "metadata": { - "editable": true - }, - "source": [ - "## Note about SVD Calculations\n", - "\n", - "The $U$, $S$, and $V$ matrices returned from the **svd()** function\n", - "cannot be multiplied directly.\n", - "\n", - "As you can see from the code, the $S$ vector must be converted into a\n", - "diagonal matrix. This may cause a problem as the size of the matrices\n", - "do not fit the rules of matrix multiplication, where the number of\n", - "columns in a matrix must match the number of rows in the subsequent\n", - "matrix.\n", - "\n", - "If you wish to include the zero singular values, you will need to\n", - "resize the matrices and set up a diagonal matrix as done in the above\n", - "example" - ] - }, - { - "cell_type": "markdown", - "id": "680ca861", - "metadata": { - "editable": true - }, - "source": [ - "## Mathematics of the SVD and implications\n", - "\n", - "Let us take a closer look at the mathematics of the SVD and the various implications for machine learning studies.\n", - "\n", - "Our starting point is our design matrix $\\boldsymbol{X}$ of dimension $n\\times p$" - ] - }, - { - "cell_type": "markdown", - "id": "d9109bdb", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\boldsymbol{X}=\\begin{bmatrix}\n", - "x_{0,0} & x_{0,1} & x_{0,2}& \\dots & \\dots x_{0,p-1}\\\\\n", - "x_{1,0} & x_{1,1} & x_{1,2}& \\dots & \\dots x_{1,p-1}\\\\\n", - "x_{2,0} & x_{2,1} & x_{2,2}& \\dots & \\dots x_{2,p-1}\\\\\n", - "\\dots & \\dots & \\dots & \\dots \\dots & \\dots \\\\\n", - "x_{n-2,0} & x_{n-2,1} & x_{n-2,2}& \\dots & \\dots x_{n-2,p-1}\\\\\n", - "x_{n-1,0} & x_{n-1,1} & x_{n-1,2}& \\dots & \\dots x_{n-1,p-1}\\\\\n", - "\\end{bmatrix}.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "1bc782ad", - "metadata": { - "editable": true - }, - "source": [ - "We can SVD decompose our matrix as" - ] - }, - { - "cell_type": "markdown", - "id": "fd98474c", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\boldsymbol{X}=\\boldsymbol{U}\\boldsymbol{\\Sigma}\\boldsymbol{V}^T,\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "27505b56", - "metadata": { - "editable": true - }, - "source": [ - "where $\\boldsymbol{U}$ is an orthogonal matrix of dimension $n\\times n$, meaning that $\\boldsymbol{U}\\boldsymbol{U}^T=\\boldsymbol{U}^T\\boldsymbol{U}=\\boldsymbol{I}_n$. Here $\\boldsymbol{I}_n$ is the unit matrix of dimension $n \\times n$.\n", - "\n", - "Similarly, $\\boldsymbol{V}$ is an orthogonal matrix of dimension $p\\times p$, meaning that $\\boldsymbol{V}\\boldsymbol{V}^T=\\boldsymbol{V}^T\\boldsymbol{V}=\\boldsymbol{I}_p$. Here $\\boldsymbol{I}_n$ is the unit matrix of dimension $p \\times p$.\n", - "\n", - "Finally $\\boldsymbol{\\Sigma}$ contains the singular values $\\sigma_i$. This matrix has dimension $n\\times p$ and the singular values $\\sigma_i$ are all positive. The non-zero values are ordered in descending order, that is" - ] - }, - { - "cell_type": "markdown", - "id": "97458ec0", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\sigma_0 > \\sigma_1 > \\sigma_2 > \\dots > \\sigma_{p-1} > 0.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "6a940c34", - "metadata": { - "editable": true - }, - "source": [ - "All values beyond $p-1$ are all zero." - ] - }, - { - "cell_type": "markdown", - "id": "beb7c9c1", - "metadata": { - "editable": true - }, - "source": [ - "## Example Matrix\n", - "\n", - "As an example, consider the following $3\\times 2$ example for the matrix $\\boldsymbol{\\Sigma}$" - ] - }, - { - "cell_type": "markdown", - "id": "892eca8e", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\boldsymbol{\\Sigma}=\n", - "\\begin{bmatrix}\n", - "2& 0 \\\\\n", - "0 & 1 \\\\\n", - "0 & 0 \\\\\n", - "\\end{bmatrix}\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "d716176c", - "metadata": { - "editable": true - }, - "source": [ - "The singular values are $\\sigma_0=2$ and $\\sigma_1=1$. It is common to rewrite the matrix $\\boldsymbol{\\Sigma}$ as" - ] - }, - { - "cell_type": "markdown", - "id": "d6f76ea3", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\boldsymbol{\\Sigma}=\n", - "\\begin{bmatrix}\n", - "\\boldsymbol{\\tilde{\\Sigma}}\\\\\n", - "\\boldsymbol{0}\\\\\n", - "\\end{bmatrix},\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "6cd96381", - "metadata": { - "editable": true - }, - "source": [ - "where" - ] - }, - { - "cell_type": "markdown", - "id": "3235bb2a", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\boldsymbol{\\tilde{\\Sigma}}=\n", - "\\begin{bmatrix}\n", - "2& 0 \\\\\n", - "0 & 1 \\\\\n", - "\\end{bmatrix},\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "cfb5e5fa", - "metadata": { - "editable": true - }, - "source": [ - "contains only the singular values. Note also (and we will use this below) that" - ] - }, - { - "cell_type": "markdown", - "id": "30c811c8", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\boldsymbol{\\Sigma}^T\\boldsymbol{\\Sigma}=\n", - "\\begin{bmatrix}\n", - "4& 0 \\\\\n", - "0 & 1 \\\\\n", - "\\end{bmatrix},\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "b64ff89b", - "metadata": { - "editable": true - }, - "source": [ - "which is a $2\\times 2 $ matrix while" - ] - }, - { - "cell_type": "markdown", - "id": "d2d214b1", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\boldsymbol{\\Sigma}\\boldsymbol{\\Sigma}^T=\n", - "\\begin{bmatrix}\n", - "4& 0 & 0\\\\\n", - "0 & 1 & 0\\\\\n", - "0 & 0 & 0\\\\\n", - "\\end{bmatrix},\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "1734cbea", - "metadata": { - "editable": true - }, - "source": [ - "is a $3\\times 3 $ matrix. The last row and column of this last matrix\n", - "contain only zeros. This will have important consequences for our SVD\n", - "decomposition of the design matrix." - ] - }, - { - "cell_type": "markdown", - "id": "18b87d79", - "metadata": { - "editable": true - }, - "source": [ - "## Setting up the Matrix to be inverted\n", - "\n", - "The matrix that may cause problems for us is $\\boldsymbol{X}^T\\boldsymbol{X}$. Using the SVD we can rewrite this matrix as" - ] - }, - { - "cell_type": "markdown", - "id": "7424dbeb", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\boldsymbol{X}^T\\boldsymbol{X}=\\boldsymbol{V}\\boldsymbol{\\Sigma}^T\\boldsymbol{U}^T\\boldsymbol{U}\\boldsymbol{\\Sigma}\\boldsymbol{V}^T,\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "8bfde7d9", - "metadata": { - "editable": true - }, - "source": [ - "and using the orthogonality of the matrix $\\boldsymbol{U}$ we have" - ] - }, - { - "cell_type": "markdown", - "id": "d7fae153", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\boldsymbol{X}^T\\boldsymbol{X}=\\boldsymbol{V}\\boldsymbol{\\Sigma}^T\\boldsymbol{\\Sigma}\\boldsymbol{V}^T.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "a5fe659e", - "metadata": { - "editable": true - }, - "source": [ - "We define $\\boldsymbol{\\Sigma}^T\\boldsymbol{\\Sigma}=\\tilde{\\boldsymbol{\\Sigma}}^2$ which is a diagonal matrix containing only the singular values squared. It has dimensionality $p \\times p$.\n", - "\n", - "We can now insert the result for the matrix $\\boldsymbol{X}^T\\boldsymbol{X}$ into our equation for ordinary least squares where" - ] - }, - { - "cell_type": "markdown", - "id": "0494a740", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\tilde{y}_{\\mathrm{OLS}}=\\boldsymbol{X}\\left(\\boldsymbol{X}^T\\boldsymbol{X}\\right)^{-1}\\boldsymbol{X}^T\\boldsymbol{y},\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "cd9e9a2d", - "metadata": { - "editable": true - }, - "source": [ - "and using our SVD decomposition of $\\boldsymbol{X}$ we have" - ] - }, - { - "cell_type": "markdown", - "id": "a36f09cb", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\tilde{y}_{\\mathrm{OLS}}=\\boldsymbol{U}\\boldsymbol{\\Sigma}\\boldsymbol{V}^T\\left(\\boldsymbol{V}\\tilde{\\boldsymbol{\\Sigma}}^{2}(\\boldsymbol{V}^T\\right)^{-1}\\boldsymbol{V}\\boldsymbol{\\Sigma}^T\\boldsymbol{U}^T\\boldsymbol{y},\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "c595c4ab", - "metadata": { - "editable": true - }, - "source": [ - "which gives us, using the orthogonality of the matrix $\\boldsymbol{V}$," - ] - }, - { - "cell_type": "markdown", - "id": "54ea720c", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\tilde{y}_{\\mathrm{OLS}}=\\boldsymbol{U}\\boldsymbol{U}^T\\boldsymbol{y}=\\sum_{i=0}^{p-1}\\boldsymbol{u}_i\\boldsymbol{u}^T_i\\boldsymbol{y},\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "3b8cb8cc", - "metadata": { - "editable": true - }, - "source": [ - "It means that the ordinary least square model (with the optimal\n", - "parameters) $\\boldsymbol{\\tilde{y}}$, corresponds to an orthogonal\n", - "transformation of the output (or target) vector $\\boldsymbol{y}$ by the\n", - "vectors of the matrix $\\boldsymbol{U}$. **Note that the summation ends at**\n", - "$p-1$, that is $\\boldsymbol{\\tilde{y}}\\ne \\boldsymbol{y}$. We can thus not use the\n", - "orthogonality relation for the matrix $\\boldsymbol{U}$. This can already be\n", - "when we multiply the matrices $\\boldsymbol{\\Sigma}^T\\boldsymbol{U}^T$." - ] - }, - { - "cell_type": "markdown", - "id": "e825b356", - "metadata": { - "editable": true - }, - "source": [ - "## Further properties (important for our analyses later)\n", - "\n", - "Let us study again $\\boldsymbol{X}^T\\boldsymbol{X}$ in terms of our SVD," - ] - }, - { - "cell_type": "markdown", - "id": "2cbc23f9", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\boldsymbol{X}^T\\boldsymbol{X}=\\boldsymbol{V}\\boldsymbol{\\Sigma}^T\\boldsymbol{U}^T\\boldsymbol{U}\\boldsymbol{\\Sigma}\\boldsymbol{V}^T=\\boldsymbol{V}\\boldsymbol{\\Sigma}^T\\boldsymbol{\\Sigma}\\boldsymbol{V}^T.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "8665bb8b", - "metadata": { - "editable": true - }, - "source": [ - "If we now multiply from the right with $\\boldsymbol{V}$ (using the orthogonality of $\\boldsymbol{V}$) we get" - ] - }, - { - "cell_type": "markdown", - "id": "2aedf32c", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\left(\\boldsymbol{X}^T\\boldsymbol{X}\\right)\\boldsymbol{V}=\\boldsymbol{V}\\boldsymbol{\\Sigma}^T\\boldsymbol{\\Sigma}.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "e64ed163", - "metadata": { - "editable": true - }, - "source": [ - "This means the vectors $\\boldsymbol{v}_i$ of the orthogonal matrix $\\boldsymbol{V}$ are the eigenvectors of the matrix $\\boldsymbol{X}^T\\boldsymbol{X}$\n", - "with eigenvalues given by the singular values squared, that is" - ] - }, - { - "cell_type": "markdown", - "id": "b060bb08", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\left(\\boldsymbol{X}^T\\boldsymbol{X}\\right)\\boldsymbol{v}_i=\\boldsymbol{v}_i\\sigma_i^2.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "0e9f682e", - "metadata": { - "editable": true - }, - "source": [ - "Similarly, if we use the SVD decomposition for the matrix $\\boldsymbol{X}\\boldsymbol{X}^T$, we have" - ] - }, - { - "cell_type": "markdown", - "id": "084d10ae", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\boldsymbol{X}\\boldsymbol{X}^T=\\boldsymbol{U}\\boldsymbol{\\Sigma}\\boldsymbol{V}^T\\boldsymbol{V}\\boldsymbol{\\Sigma}^T\\boldsymbol{U}^T=\\boldsymbol{U}\\boldsymbol{\\Sigma}\\boldsymbol{\\Sigma}^T\\boldsymbol{U}^T.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "322ae2b5", - "metadata": { - "editable": true - }, - "source": [ - "If we now multiply from the right with $\\boldsymbol{U}$ (using the orthogonality of $\\boldsymbol{U}$) we get" - ] - }, - { - "cell_type": "markdown", - "id": "2b934378", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\left(\\boldsymbol{X}\\boldsymbol{X}^T\\right)\\boldsymbol{U}=\\boldsymbol{U}\\boldsymbol{\\Sigma}\\boldsymbol{\\Sigma}^T.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "76fa0775", - "metadata": { - "editable": true - }, - "source": [ - "This means the vectors $\\boldsymbol{u}_i$ of the orthogonal matrix $\\boldsymbol{U}$ are the eigenvectors of the matrix $\\boldsymbol{X}\\boldsymbol{X}^T$\n", - "with eigenvalues given by the singular values squared, that is" - ] - }, - { - "cell_type": "markdown", - "id": "4ab1ab5e", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\left(\\boldsymbol{X}\\boldsymbol{X}^T\\right)\\boldsymbol{u}_i=\\boldsymbol{u}_i\\sigma_i^2.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "5c3528cd", - "metadata": { - "editable": true - }, - "source": [ - "**Important note**: we have defined our design matrix $\\boldsymbol{X}$ to be an\n", - "$n\\times p$ matrix. In most supervised learning cases we have that $n\n", - "\\ge p$, and quite often we have $n >> p$. For linear algebra based methods like ordinary least squares or Ridge regression, this leads to a matrix $\\boldsymbol{X}^T\\boldsymbol{X}$ which is small and thereby easier to handle from a computational point of view (in terms of number of floating point operations).\n", - "\n", - "In our lectures, the number of columns will\n", - "always refer to the number of features in our data set, while the\n", - "number of rows represents the number of data inputs. Note that in\n", - "other texts you may find the opposite notation. This has consequences\n", - "for the definition of for example the covariance matrix and its relation to the SVD." - ] - }, - { - "cell_type": "markdown", - "id": "99446c56", - "metadata": { - "editable": true - }, - "source": [ - "## Meet the Covariance Matrix\n", - "\n", - "Before we move on to a discussion of Ridge and Lasso regression, we want to show an important example of the above.\n", - "\n", - "We have already noted that the matrix $\\boldsymbol{X}^T\\boldsymbol{X}$ in ordinary\n", - "least squares is proportional to the second derivative of the cost\n", - "function, that is we have" - ] - }, - { - "cell_type": "markdown", - "id": "52b4ef86", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\frac{\\partial^2 C(\\boldsymbol{\\beta})}{\\partial \\boldsymbol{\\beta}\\partial \\boldsymbol{\\beta}^T} =\\frac{2}{n}\\boldsymbol{X}^T\\boldsymbol{X}.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "14d03f17", - "metadata": { - "editable": true - }, - "source": [ - "This quantity defines was what is called the Hessian matrix (the second derivative of a function we want to optimize).\n", - "\n", - "The Hessian matrix plays an important role and is defined in this course as" - ] - }, - { - "cell_type": "markdown", - "id": "08983b4e", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\boldsymbol{H}=\\boldsymbol{X}^T\\boldsymbol{X}.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "bf4aff1c", - "metadata": { - "editable": true - }, - "source": [ - "The Hessian matrix for ordinary least squares is also proportional to\n", - "the covariance matrix. This means also that we can use the SVD to find\n", - "the eigenvalues of the covariance matrix and the Hessian matrix in\n", - "terms of the singular values. Let us develop these arguments, as they will play an important role in our machine learning studies." - ] - }, - { - "cell_type": "markdown", - "id": "d1a70450", - "metadata": { - "editable": true - }, - "source": [ - "## Introducing the Covariance and Correlation functions\n", - "\n", - "Before we discuss the link between for example Ridge regression and the singular value decomposition, we need to remind ourselves about\n", - "the definition of the covariance and the correlation function. These are quantities that play a central role in machine learning methods.\n", - "\n", - "Suppose we have defined two vectors\n", - "$\\hat{x}$ and $\\hat{y}$ with $n$ elements each. The covariance matrix $\\boldsymbol{C}$ is defined as" - ] - }, - { - "cell_type": "markdown", - "id": "4441a82e", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\boldsymbol{C}[\\boldsymbol{x},\\boldsymbol{y}] = \\begin{bmatrix} \\mathrm{cov}[\\boldsymbol{x},\\boldsymbol{x}] & \\mathrm{cov}[\\boldsymbol{x},\\boldsymbol{y}] \\\\\n", - " \\mathrm{cov}[\\boldsymbol{y},\\boldsymbol{x}] & \\mathrm{cov}[\\boldsymbol{y},\\boldsymbol{y}] \\\\\n", - " \\end{bmatrix},\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "985fe9f4", - "metadata": { - "editable": true - }, - "source": [ - "where for example" - ] - }, - { - "cell_type": "markdown", - "id": "7d0b48ad", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\mathrm{cov}[\\boldsymbol{x},\\boldsymbol{y}] =\\frac{1}{n} \\sum_{i=0}^{n-1}(x_i- \\overline{x})(y_i- \\overline{y}).\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "927a1cc9", - "metadata": { - "editable": true - }, - "source": [ - "With this definition and recalling that the variance is defined as" - ] - }, - { - "cell_type": "markdown", - "id": "28fe8612", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\mathrm{var}[\\boldsymbol{x}]=\\frac{1}{n} \\sum_{i=0}^{n-1}(x_i- \\overline{x})^2,\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "643c5c24", - "metadata": { - "editable": true - }, - "source": [ - "we can rewrite the covariance matrix as" - ] - }, - { - "cell_type": "markdown", - "id": "31eb5551", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\boldsymbol{C}[\\boldsymbol{x},\\boldsymbol{y}] = \\begin{bmatrix} \\mathrm{var}[\\boldsymbol{x}] & \\mathrm{cov}[\\boldsymbol{x},\\boldsymbol{y}] \\\\\n", - " \\mathrm{cov}[\\boldsymbol{x},\\boldsymbol{y}] & \\mathrm{var}[\\boldsymbol{y}] \\\\\n", - " \\end{bmatrix}.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "ee97772f", - "metadata": { - "editable": true - }, - "source": [ - "**Note:** we have used $1/n$ in the above definitions of the *sample* variance and covariance. We assume then that we can calculate the exact mean value. \n", - "What you will find in essentially all statistics texts are equations\n", - "with a factor $1/(n-1)$. This is called [Bessel's correction](https://mathworld.wolfram.com/BesselsCorrection.html). This\n", - "method corrects the bias in the estimation of the population variance\n", - "and covariance. It also partially corrects the bias in the estimation\n", - "of the population standard deviation. If you use a library like\n", - "**Scikit-Learn** or **nunmpy's** function to calculate the covariance, this\n", - "quantity will be computed with a factor $1/(n-1)$." - ] - }, - { - "cell_type": "markdown", - "id": "fdef2a70", - "metadata": { - "editable": true - }, - "source": [ - "## Covariance and Correlation Matrix\n", - "\n", - "The covariance takes values between zero and infinity and may thus\n", - "lead to problems with loss of numerical precision for particularly\n", - "large values. It is common to scale the covariance matrix by\n", - "introducing instead the correlation matrix defined via the so-called\n", - "correlation function" - ] - }, - { - "cell_type": "markdown", - "id": "68211a1f", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\mathrm{corr}[\\boldsymbol{x},\\boldsymbol{y}]=\\frac{\\mathrm{cov}[\\boldsymbol{x},\\boldsymbol{y}]}{\\sqrt{\\mathrm{var}[\\boldsymbol{x}] \\mathrm{var}[\\boldsymbol{y}]}}.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "9a8a18e2", - "metadata": { - "editable": true - }, - "source": [ - "The correlation function is then given by values $\\mathrm{corr}[\\boldsymbol{x},\\boldsymbol{y}]\n", - "\\in [-1,1]$. This avoids eventual problems with too large values. We\n", - "can then define the correlation matrix for the two vectors $\\boldsymbol{x}$\n", - "and $\\boldsymbol{y}$ as" - ] - }, - { - "cell_type": "markdown", - "id": "e7d94e46", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\boldsymbol{K}[\\boldsymbol{x},\\boldsymbol{y}] = \\begin{bmatrix} 1 & \\mathrm{corr}[\\boldsymbol{x},\\boldsymbol{y}] \\\\\n", - " \\mathrm{corr}[\\boldsymbol{y},\\boldsymbol{x}] & 1 \\\\\n", - " \\end{bmatrix},\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "0c9c0c07", - "metadata": { - "editable": true - }, - "source": [ - "In the above example this is the function we constructed using **pandas**." - ] - }, - { - "cell_type": "markdown", - "id": "3fc933af", - "metadata": { - "editable": true - }, - "source": [ - "## Correlation Function and Design/Feature Matrix\n", - "\n", - "In our derivation of the various regression algorithms like **Ordinary Least Squares** or **Ridge regression**\n", - "we defined the design/feature matrix $\\boldsymbol{X}$ as" - ] - }, - { - "cell_type": "markdown", - "id": "e97cce9c", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\boldsymbol{X}=\\begin{bmatrix}\n", - "x_{0,0} & x_{0,1} & x_{0,2}& \\dots & \\dots x_{0,p-1}\\\\\n", - "x_{1,0} & x_{1,1} & x_{1,2}& \\dots & \\dots x_{1,p-1}\\\\\n", - "x_{2,0} & x_{2,1} & x_{2,2}& \\dots & \\dots x_{2,p-1}\\\\\n", - "\\dots & \\dots & \\dots & \\dots \\dots & \\dots \\\\\n", - "x_{n-2,0} & x_{n-2,1} & x_{n-2,2}& \\dots & \\dots x_{n-2,p-1}\\\\\n", - "x_{n-1,0} & x_{n-1,1} & x_{n-1,2}& \\dots & \\dots x_{n-1,p-1}\\\\\n", - "\\end{bmatrix},\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "d1be42f8", - "metadata": { - "editable": true - }, - "source": [ - "with $\\boldsymbol{X}\\in {\\mathbb{R}}^{n\\times p}$, with the predictors/features $p$ refering to the column numbers and the\n", - "entries $n$ being the row elements.\n", - "We can rewrite the design/feature matrix in terms of its column vectors as" - ] - }, - { - "cell_type": "markdown", - "id": "e957492f", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\boldsymbol{X}=\\begin{bmatrix} \\boldsymbol{x}_0 & \\boldsymbol{x}_1 & \\boldsymbol{x}_2 & \\dots & \\dots & \\boldsymbol{x}_{p-1}\\end{bmatrix},\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "6f4bd14c", - "metadata": { - "editable": true - }, - "source": [ - "with a given vector" - ] - }, - { - "cell_type": "markdown", - "id": "ba1b4c89", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\boldsymbol{x}_i^T = \\begin{bmatrix}x_{0,i} & x_{1,i} & x_{2,i}& \\dots & \\dots x_{n-1,i}\\end{bmatrix}.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "c9563317", - "metadata": { - "editable": true - }, - "source": [ - "With these definitions, we can now rewrite our $2\\times 2$\n", - "correlation/covariance matrix in terms of a moe general design/feature\n", - "matrix $\\boldsymbol{X}\\in {\\mathbb{R}}^{n\\times p}$. This leads to a $p\\times p$\n", - "covariance matrix for the vectors $\\boldsymbol{x}_i$ with $i=0,1,\\dots,p-1$" - ] - }, - { - "cell_type": "markdown", - "id": "ed451710", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\boldsymbol{C}[\\boldsymbol{x}] = \\begin{bmatrix}\n", - "\\mathrm{var}[\\boldsymbol{x}_0] & \\mathrm{cov}[\\boldsymbol{x}_0,\\boldsymbol{x}_1] & \\mathrm{cov}[\\boldsymbol{x}_0,\\boldsymbol{x}_2] & \\dots & \\dots & \\mathrm{cov}[\\boldsymbol{x}_0,\\boldsymbol{x}_{p-1}]\\\\\n", - "\\mathrm{cov}[\\boldsymbol{x}_1,\\boldsymbol{x}_0] & \\mathrm{var}[\\boldsymbol{x}_1] & \\mathrm{cov}[\\boldsymbol{x}_1,\\boldsymbol{x}_2] & \\dots & \\dots & \\mathrm{cov}[\\boldsymbol{x}_1,\\boldsymbol{x}_{p-1}]\\\\\n", - "\\mathrm{cov}[\\boldsymbol{x}_2,\\boldsymbol{x}_0] & \\mathrm{cov}[\\boldsymbol{x}_2,\\boldsymbol{x}_1] & \\mathrm{var}[\\boldsymbol{x}_2] & \\dots & \\dots & \\mathrm{cov}[\\boldsymbol{x}_2,\\boldsymbol{x}_{p-1}]\\\\\n", - "\\dots & \\dots & \\dots & \\dots & \\dots & \\dots \\\\\n", - "\\dots & \\dots & \\dots & \\dots & \\dots & \\dots \\\\\n", - "\\mathrm{cov}[\\boldsymbol{x}_{p-1},\\boldsymbol{x}_0] & \\mathrm{cov}[\\boldsymbol{x}_{p-1},\\boldsymbol{x}_1] & \\mathrm{cov}[\\boldsymbol{x}_{p-1},\\boldsymbol{x}_{2}] & \\dots & \\dots & \\mathrm{var}[\\boldsymbol{x}_{p-1}]\\\\\n", - "\\end{bmatrix},\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "4eabcccb", - "metadata": { - "editable": true - }, - "source": [ - "and the correlation matrix" - ] - }, - { - "cell_type": "markdown", - "id": "78678f6f", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\boldsymbol{K}[\\boldsymbol{x}] = \\begin{bmatrix}\n", - "1 & \\mathrm{corr}[\\boldsymbol{x}_0,\\boldsymbol{x}_1] & \\mathrm{corr}[\\boldsymbol{x}_0,\\boldsymbol{x}_2] & \\dots & \\dots & \\mathrm{corr}[\\boldsymbol{x}_0,\\boldsymbol{x}_{p-1}]\\\\\n", - "\\mathrm{corr}[\\boldsymbol{x}_1,\\boldsymbol{x}_0] & 1 & \\mathrm{corr}[\\boldsymbol{x}_1,\\boldsymbol{x}_2] & \\dots & \\dots & \\mathrm{corr}[\\boldsymbol{x}_1,\\boldsymbol{x}_{p-1}]\\\\\n", - "\\mathrm{corr}[\\boldsymbol{x}_2,\\boldsymbol{x}_0] & \\mathrm{corr}[\\boldsymbol{x}_2,\\boldsymbol{x}_1] & 1 & \\dots & \\dots & \\mathrm{corr}[\\boldsymbol{x}_2,\\boldsymbol{x}_{p-1}]\\\\\n", - "\\dots & \\dots & \\dots & \\dots & \\dots & \\dots \\\\\n", - "\\dots & \\dots & \\dots & \\dots & \\dots & \\dots \\\\\n", - "\\mathrm{corr}[\\boldsymbol{x}_{p-1},\\boldsymbol{x}_0] & \\mathrm{corr}[\\boldsymbol{x}_{p-1},\\boldsymbol{x}_1] & \\mathrm{corr}[\\boldsymbol{x}_{p-1},\\boldsymbol{x}_{2}] & \\dots & \\dots & 1\\\\\n", - "\\end{bmatrix},\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "5840e451", - "metadata": { - "editable": true - }, - "source": [ - "## Covariance Matrix Examples\n", - "\n", - "The Numpy function **np.cov** calculates the covariance elements using\n", - "the factor $1/(n-1)$ instead of $1/n$ since it assumes we do not have\n", - "the exact mean values. The following simple function uses the\n", - "**np.vstack** function which takes each vector of dimension $1\\times n$\n", - "and produces a $2\\times n$ matrix $\\boldsymbol{W}$\n", - "\n", - "Note that this assumes you have the features as the rows, and the inputs as columns, that is" - ] - }, - { - "cell_type": "markdown", - "id": "75f212b9", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\boldsymbol{W} = \\begin{bmatrix} x_0 & x_1 & x_2 & \\dots & x_{n-2} & x_{n-1} \\\\\n", - " y_0 & y_1 & y_2 & \\dots & y_{n-2} & y_{n-1} \\\\\n", - " \\end{bmatrix},\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "af4b97f1", - "metadata": { - "editable": true - }, - "source": [ - "which in turn is converted into into the $2\\times 2$ covariance matrix\n", - "$\\boldsymbol{C}$ via the Numpy function **np.cov()**. We note that we can also calculate\n", - "the mean value of each set of samples $\\boldsymbol{x}$ etc using the Numpy\n", - "function **np.mean(x)**. We can also extract the eigenvalues of the\n", - "covariance matrix through the **np.linalg.eig()** function." - ] - }, - { - "cell_type": "code", - "execution_count": 27, - "id": "bceeb8a6", - "metadata": { - "collapsed": false, - "editable": true - }, - "outputs": [], - "source": [ - "# Importing various packages\n", - "import numpy as np\n", - "n = 100\n", - "x = np.random.normal(size=n)\n", - "print(np.mean(x))\n", - "y = 4+3*x+np.random.normal(size=n)\n", - "print(np.mean(y))\n", - "W = np.vstack((x, y))\n", - "C = np.cov(W)\n", - "print(C)" - ] - }, - { - "cell_type": "markdown", - "id": "e438fa73", - "metadata": { - "editable": true - }, - "source": [ - "## Correlation Matrix\n", - "\n", - "The previous example can be converted into the correlation matrix by\n", - "simply scaling the matrix elements with the variances. We should also\n", - "subtract the mean values for each column. This leads to the following\n", - "code which sets up the correlations matrix for the previous example in\n", - "a more brute force way. Here we scale the mean values for each column of the design matrix, calculate the relevant mean values and variances and then finally set up the $2\\times 2$ correlation matrix (since we have only two vectors)." - ] - }, - { - "cell_type": "code", - "execution_count": 28, - "id": "01ec3279", - "metadata": { - "collapsed": false, - "editable": true - }, - "outputs": [], - "source": [ - "import numpy as np\n", - "n = 100\n", - "# define two vectors \n", - "x = np.random.random(size=n)\n", - "y = 4+3*x+np.random.normal(size=n)\n", - "#scaling the x and y vectors \n", - "x = x - np.mean(x)\n", - "y = y - np.mean(y)\n", - "variance_x = np.sum(x@x)/n\n", - "variance_y = np.sum(y@y)/n\n", - "print(variance_x)\n", - "print(variance_y)\n", - "cov_xy = np.sum(x@y)/n\n", - "cov_xx = np.sum(x@x)/n\n", - "cov_yy = np.sum(y@y)/n\n", - "C = np.zeros((2,2))\n", - "C[0,0]= cov_xx/variance_x\n", - "C[1,1]= cov_yy/variance_y\n", - "C[0,1]= cov_xy/np.sqrt(variance_y*variance_x)\n", - "C[1,0]= C[0,1]\n", - "print(C)" - ] - }, - { - "cell_type": "markdown", - "id": "fb6ba409", - "metadata": { - "editable": true - }, - "source": [ - "We see that the matrix elements along the diagonal are one as they\n", - "should be and that the matrix is symmetric. Furthermore, diagonalizing\n", - "this matrix we easily see that it is a positive definite matrix.\n", - "\n", - "The above procedure with **numpy** can be made more compact if we use **pandas**." - ] - }, - { - "cell_type": "markdown", - "id": "6c5bfe67", - "metadata": { - "editable": true - }, - "source": [ - "## Correlation Matrix with Pandas\n", - "\n", - "We whow here how we can set up the correlation matrix using **pandas**, as done in this simple code" - ] - }, - { - "cell_type": "code", - "execution_count": 29, - "id": "b2b07565", - "metadata": { - "collapsed": false, - "editable": true - }, - "outputs": [], - "source": [ - "import numpy as np\n", - "import pandas as pd\n", - "n = 10\n", - "x = np.random.normal(size=n)\n", - "x = x - np.mean(x)\n", - "y = 4+3*x+np.random.normal(size=n)\n", - "y = y - np.mean(y)\n", - "# Note that we transpose the matrix in order to stay with our ordering n x p\n", - "X = (np.vstack((x, y))).T\n", - "print(X)\n", - "Xpd = pd.DataFrame(X)\n", - "print(Xpd)\n", - "correlation_matrix = Xpd.corr()\n", - "print(correlation_matrix)" - ] - }, - { - "cell_type": "markdown", - "id": "e26d9b42", - "metadata": { - "editable": true - }, - "source": [ - "We expand this model to the Franke function discussed above." - ] - }, - { - "cell_type": "markdown", - "id": "6200c4da", - "metadata": { - "editable": true - }, - "source": [ - "## Correlation Matrix with Pandas and the Franke function" - ] - }, - { - "cell_type": "code", - "execution_count": 30, - "id": "1a0f5c54", - "metadata": { - "collapsed": false, - "editable": true - }, - "outputs": [], - "source": [ - "# Common imports\n", - "import numpy as np\n", - "import pandas as pd\n", - "\n", - "\n", - "def FrankeFunction(x,y):\n", - "\tterm1 = 0.75*np.exp(-(0.25*(9*x-2)**2) - 0.25*((9*y-2)**2))\n", - "\tterm2 = 0.75*np.exp(-((9*x+1)**2)/49.0 - 0.1*(9*y+1))\n", - "\tterm3 = 0.5*np.exp(-(9*x-7)**2/4.0 - 0.25*((9*y-3)**2))\n", - "\tterm4 = -0.2*np.exp(-(9*x-4)**2 - (9*y-7)**2)\n", - "\treturn term1 + term2 + term3 + term4\n", - "\n", - "\n", - "def create_X(x, y, n ):\n", - "\tif len(x.shape) > 1:\n", - "\t\tx = np.ravel(x)\n", - "\t\ty = np.ravel(y)\n", - "\n", - "\tN = len(x)\n", - "\tl = int((n+1)*(n+2)/2)\t\t# Number of elements in beta\n", - "\tX = np.ones((N,l))\n", - "\n", - "\tfor i in range(1,n+1):\n", - "\t\tq = int((i)*(i+1)/2)\n", - "\t\tfor k in range(i+1):\n", - "\t\t\tX[:,q+k] = (x**(i-k))*(y**k)\n", - "\n", - "\treturn X\n", - "\n", - "\n", - "# Making meshgrid of datapoints and compute Franke's function\n", - "n = 4\n", - "N = 100\n", - "x = np.sort(np.random.uniform(0, 1, N))\n", - "y = np.sort(np.random.uniform(0, 1, N))\n", - "z = FrankeFunction(x, y)\n", - "X = create_X(x, y, n=n) \n", - "\n", - "Xpd = pd.DataFrame(X)\n", - "# subtract the mean values and set up the covariance matrix\n", - "Xpd = Xpd - Xpd.mean()\n", - "covariance_matrix = Xpd.cov()\n", - "print(covariance_matrix)" - ] - }, - { - "cell_type": "markdown", - "id": "be666eb5", - "metadata": { - "editable": true - }, - "source": [ - "We note here that the covariance is zero for the first rows and\n", - "columns since all matrix elements in the design matrix were set to one\n", - "(we are fitting the function in terms of a polynomial of degree $n$).\n", - "\n", - "This means that the variance for these elements will be zero and will\n", - "cause problems when we set up the correlation matrix. We can simply\n", - "drop these elements and construct a correlation\n", - "matrix without these elements." - ] - }, - { - "cell_type": "markdown", - "id": "cc79dbf1", - "metadata": { - "editable": true - }, - "source": [ - "## Rewriting the Covariance and/or Correlation Matrix\n", - "\n", - "We can rewrite the covariance matrix in a more compact form in terms of the design/feature matrix $\\boldsymbol{X}$ as" - ] - }, - { - "cell_type": "markdown", - "id": "7aaa9582", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\boldsymbol{C}[\\boldsymbol{x}] = \\frac{1}{n}\\boldsymbol{X}^T\\boldsymbol{X}= \\mathbb{E}[\\boldsymbol{X}^T\\boldsymbol{X}].\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "3c9ca18c", - "metadata": { - "editable": true - }, - "source": [ - "To see this let us simply look at a design matrix $\\boldsymbol{X}\\in {\\mathbb{R}}^{2\\times 2}$" - ] - }, - { - "cell_type": "markdown", - "id": "7450e1de", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\boldsymbol{X}=\\begin{bmatrix}\n", - "x_{00} & x_{01}\\\\\n", - "x_{10} & x_{11}\\\\\n", - "\\end{bmatrix}=\\begin{bmatrix}\n", - "\\boldsymbol{x}_{0} & \\boldsymbol{x}_{1}\\\\\n", - "\\end{bmatrix}.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "c190057c", - "metadata": { - "editable": true - }, - "source": [ - "If we then compute the expectation value (note the $1/n$ factor instead of $1/(n-1)$)" - ] - }, - { - "cell_type": "markdown", - "id": "20f4c172", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\mathbb{E}[\\boldsymbol{X}^T\\boldsymbol{X}] = \\frac{1}{n}\\boldsymbol{X}^T\\boldsymbol{X}=\\frac{1}{n}\\begin{bmatrix}\n", - "x_{00}^2+x_{10}^2 & x_{00}x_{01}+x_{10}x_{11}\\\\\n", - "x_{01}x_{00}+x_{11}x_{10} & x_{01}^2+x_{11}^2\\\\\n", - "\\end{bmatrix},\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "746607df", - "metadata": { - "editable": true - }, - "source": [ - "which is just" - ] - }, - { - "cell_type": "markdown", - "id": "d2419f36", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\boldsymbol{C}[\\boldsymbol{x}_0,\\boldsymbol{x}_1] = \\boldsymbol{C}[\\boldsymbol{x}]=\\begin{bmatrix} \\mathrm{var}[\\boldsymbol{x}_0] & \\mathrm{cov}[\\boldsymbol{x}_0,\\boldsymbol{x}_1] \\\\\n", - " \\mathrm{cov}[\\boldsymbol{x}_1,\\boldsymbol{x}_0] & \\mathrm{var}[\\boldsymbol{x}_1] \\\\\n", - " \\end{bmatrix},\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "0c4d5713", - "metadata": { - "editable": true - }, - "source": [ - "where we wrote $$\\boldsymbol{C}[\\boldsymbol{x}_0,\\boldsymbol{x}_1] = \\boldsymbol{C}[\\boldsymbol{x}]$$ to indicate that this is the covariance of the vectors $\\boldsymbol{x}$ of the design/feature matrix $\\boldsymbol{X}$.\n", - "\n", - "It is easy to generalize this to a matrix $\\boldsymbol{X}\\in {\\mathbb{R}}^{n\\times p}$." - ] - }, - { - "cell_type": "markdown", - "id": "c51b1e85", - "metadata": { - "editable": true - }, - "source": [ - "## Linking with the SVD\n", - "\n", - "We saw earlier that" - ] - }, - { - "cell_type": "markdown", - "id": "df3d6e17", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\boldsymbol{X}^T\\boldsymbol{X}=\\boldsymbol{V}\\boldsymbol{\\Sigma}^T\\boldsymbol{U}^T\\boldsymbol{U}\\boldsymbol{\\Sigma}\\boldsymbol{V}^T=\\boldsymbol{V}\\boldsymbol{\\Sigma}^T\\boldsymbol{\\Sigma}\\boldsymbol{V}^T.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "bda15ad2", - "metadata": { - "editable": true - }, - "source": [ - "Since the matrices here have dimension $p\\times p$, with $p$ corresponding to the singular values, we defined earlier the matrix" - ] - }, - { - "cell_type": "markdown", - "id": "40ad7cbc", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\boldsymbol{\\Sigma}^T\\boldsymbol{\\Sigma} = \\begin{bmatrix} \\tilde{\\boldsymbol{\\Sigma}} & \\boldsymbol{0}\\\\ \\end{bmatrix}\\begin{bmatrix} \\tilde{\\boldsymbol{\\Sigma}} \\\\ \\boldsymbol{0}\\\\ \\end{bmatrix},\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "305bd308", - "metadata": { - "editable": true - }, - "source": [ - "where the tilde-matrix $\\tilde{\\boldsymbol{\\Sigma}}$ is a matrix of dimension $p\\times p$ containing only the singular values $\\sigma_i$, that is" - ] - }, - { - "cell_type": "markdown", - "id": "bb83e451", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\tilde{\\boldsymbol{\\Sigma}}=\\begin{bmatrix} \\sigma_0 & 0 & 0 & \\dots & 0 & 0 \\\\\n", - " 0 & \\sigma_1 & 0 & \\dots & 0 & 0 \\\\\n", - "\t\t\t\t 0 & 0 & \\sigma_2 & \\dots & 0 & 0 \\\\\n", - "\t\t\t\t 0 & 0 & 0 & \\dots & \\sigma_{p-2} & 0 \\\\\n", - "\t\t\t\t 0 & 0 & 0 & \\dots & 0 & \\sigma_{p-1} \\\\\n", - "\\end{bmatrix},\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "64d007a7", - "metadata": { - "editable": true - }, - "source": [ - "meaning we can write" - ] - }, - { - "cell_type": "markdown", - "id": "c0fe2564", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\boldsymbol{X}^T\\boldsymbol{X}=\\boldsymbol{V}\\tilde{\\boldsymbol{\\Sigma}}^2\\boldsymbol{V}^T.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "630c43cb", - "metadata": { - "editable": true - }, - "source": [ - "Multiplying from the right with $\\boldsymbol{V}$ (using the orthogonality of $\\boldsymbol{V}$) we get" - ] - }, - { - "cell_type": "markdown", - "id": "1e412f4c", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\left(\\boldsymbol{X}^T\\boldsymbol{X}\\right)\\boldsymbol{V}=\\boldsymbol{V}\\tilde{\\boldsymbol{\\Sigma}}^2.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "2294efa0", - "metadata": { - "editable": true - }, - "source": [ - "## What does it mean?\n", - "\n", - "This means the vectors $\\boldsymbol{v}_i$ of the orthogonal matrix $\\boldsymbol{V}$\n", - "are the eigenvectors of the matrix $\\boldsymbol{X}^T\\boldsymbol{X}$ with eigenvalues\n", - "given by the singular values squared, that is" - ] - }, - { - "cell_type": "markdown", - "id": "ec2d9133", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\left(\\boldsymbol{X}^T\\boldsymbol{X}\\right)\\boldsymbol{v}_i=\\boldsymbol{v}_i\\sigma_i^2.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "be85e557", - "metadata": { - "editable": true - }, - "source": [ - "In other words, each non-zero singular value of $\\boldsymbol{X}$ is a positive\n", - "square root of an eigenvalue of $\\boldsymbol{X}^T\\boldsymbol{X}$. It means also that\n", - "the columns of $\\boldsymbol{V}$ are the eigenvectors of\n", - "$\\boldsymbol{X}^T\\boldsymbol{X}$. Since we have ordered the singular values of\n", - "$\\boldsymbol{X}$ in a descending order, it means that the column vectors\n", - "$\\boldsymbol{v}_i$ are hierarchically ordered by how much correlation they\n", - "encode from the columns of $\\boldsymbol{X}$. \n", - "\n", - "Note that these are also the eigenvectors and eigenvalues of the\n", - "Hessian matrix. Note also that the Hessian matrix we are discussing here is from a cost function defined by the mean squared error only.\n", - "\n", - "If we now recall the definition of the covariance matrix (not using\n", - "Bessel's correction) we have" - ] - }, - { - "cell_type": "markdown", - "id": "61531c33", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\boldsymbol{C}[\\boldsymbol{X}]=\\frac{1}{n}\\boldsymbol{X}^T\\boldsymbol{X},\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "549a9854", - "metadata": { - "editable": true - }, - "source": [ - "meaning that every squared non-singular value of $\\boldsymbol{X}$ divided by $n$ (\n", - "the number of samples) are the eigenvalues of the covariance\n", - "matrix. Every singular value of $\\boldsymbol{X}$ is thus a positive square\n", - "root of an eigenvalue of $\\boldsymbol{X}^T\\boldsymbol{X}$. If the matrix $\\boldsymbol{X}$ is\n", - "self-adjoint, the singular values of $\\boldsymbol{X}$ are equal to the\n", - "absolute value of the eigenvalues of $\\boldsymbol{X}$." - ] - }, - { - "cell_type": "markdown", - "id": "ace8d1d3", - "metadata": { - "editable": true - }, - "source": [ - "## And finally $\\boldsymbol{X}\\boldsymbol{X}^T$\n", - "\n", - "For $\\boldsymbol{X}\\boldsymbol{X}^T$ we found" - ] - }, - { - "cell_type": "markdown", - "id": "4624e6fc", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\boldsymbol{X}\\boldsymbol{X}^T=\\boldsymbol{U}\\boldsymbol{\\Sigma}\\boldsymbol{V}^T\\boldsymbol{V}\\boldsymbol{\\Sigma}^T\\boldsymbol{U}^T=\\boldsymbol{U}\\boldsymbol{\\Sigma}^T\\boldsymbol{\\Sigma}\\boldsymbol{U}^T.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "4b8a8b55", - "metadata": { - "editable": true - }, - "source": [ - "Since the matrices here have dimension $n\\times n$, we have" - ] - }, - { - "cell_type": "markdown", - "id": "e8a41480", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\boldsymbol{\\Sigma}\\boldsymbol{\\Sigma}^T = \\begin{bmatrix} \\tilde{\\boldsymbol{\\Sigma}} \\\\ \\boldsymbol{0}\\\\ \\end{bmatrix}\\begin{bmatrix} \\tilde{\\boldsymbol{\\Sigma}} \\boldsymbol{0}\\\\ \\end{bmatrix}=\\begin{bmatrix} \\tilde{\\boldsymbol{\\Sigma}} & \\boldsymbol{0} \\\\ \\boldsymbol{0} & \\boldsymbol{0}\\\\ \\end{bmatrix},\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "6a36c786", - "metadata": { - "editable": true - }, - "source": [ - "leading to" - ] - }, - { - "cell_type": "markdown", - "id": "462349df", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\boldsymbol{X}\\boldsymbol{X}^T=\\boldsymbol{U}\\begin{bmatrix} \\tilde{\\boldsymbol{\\Sigma}} & \\boldsymbol{0} \\\\ \\boldsymbol{0} & \\boldsymbol{0}\\\\ \\end{bmatrix}\\boldsymbol{U}^T.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "f3e432cb", - "metadata": { - "editable": true - }, - "source": [ - "Multiplying with $\\boldsymbol{U}$ from the right gives us the eigenvalue problem" - ] - }, - { - "cell_type": "markdown", - "id": "20a1bdac", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "(\\boldsymbol{X}\\boldsymbol{X}^T)\\boldsymbol{U}=\\boldsymbol{U}\\begin{bmatrix} \\tilde{\\boldsymbol{\\Sigma}} & \\boldsymbol{0} \\\\ \\boldsymbol{0} & \\boldsymbol{0}\\\\ \\end{bmatrix}.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "43ac5bba", - "metadata": { - "editable": true - }, - "source": [ - "It means that the eigenvalues of $\\boldsymbol{X}\\boldsymbol{X}^T$ are again given by\n", - "the non-zero singular values plus now a series of zeros. The column\n", - "vectors of $\\boldsymbol{U}$ are the eigenvectors of $\\boldsymbol{X}\\boldsymbol{X}^T$ and\n", - "measure how much correlations are contained in the rows of $\\boldsymbol{X}$.\n", - "\n", - "Since we will mainly be interested in the correlations among the features\n", - "of our data (the columns of $\\boldsymbol{X}$, the quantity of interest for us are the non-zero singular\n", - "values and the column vectors of $\\boldsymbol{V}$." - ] - }, - { - "cell_type": "markdown", - "id": "ff1f6546", - "metadata": { - "editable": true - }, - "source": [ - "## Ridge and LASSO Regression\n", - "\n", - "Let us remind ourselves about the expression for the standard Mean Squared Error (MSE) which we used to define our cost function and the equations for the ordinary least squares (OLS) method, that is \n", - "our optimization problem is" - ] - }, - { - "cell_type": "markdown", - "id": "cf2d5142", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "{\\displaystyle \\min_{\\boldsymbol{\\beta}\\in {\\mathbb{R}}^{p}}}\\frac{1}{n}\\left\\{\\left(\\boldsymbol{y}-\\boldsymbol{X}\\boldsymbol{\\beta}\\right)^T\\left(\\boldsymbol{y}-\\boldsymbol{X}\\boldsymbol{\\beta}\\right)\\right\\}.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "0e74ad82", - "metadata": { - "editable": true - }, - "source": [ - "or we can state it as" - ] - }, - { - "cell_type": "markdown", - "id": "f0e17a56", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "{\\displaystyle \\min_{\\boldsymbol{\\beta}\\in\n", - "{\\mathbb{R}}^{p}}}\\frac{1}{n}\\sum_{i=0}^{n-1}\\left(y_i-\\tilde{y}_i\\right)^2=\\frac{1}{n}\\vert\\vert \\boldsymbol{y}-\\boldsymbol{X}\\boldsymbol{\\beta}\\vert\\vert_2^2,\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "b11ffbe6", - "metadata": { - "editable": true - }, - "source": [ - "where we have used the definition of a norm-2 vector, that is" - ] - }, - { - "cell_type": "markdown", - "id": "3f4e49db", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\vert\\vert \\boldsymbol{x}\\vert\\vert_2 = \\sqrt{\\sum_i x_i^2}.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "e22c2482", - "metadata": { - "editable": true - }, - "source": [ - "By minimizing the above equation with respect to the parameters\n", - "$\\boldsymbol{\\beta}$ we could then obtain an analytical expression for the\n", - "parameters $\\boldsymbol{\\beta}$. We can add a regularization parameter $\\lambda$ by\n", - "defining a new cost function to be optimized, that is" - ] - }, - { - "cell_type": "markdown", - "id": "a7e7dfe5", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "{\\displaystyle \\min_{\\boldsymbol{\\beta}\\in\n", - "{\\mathbb{R}}^{p}}}\\frac{1}{n}\\vert\\vert \\boldsymbol{y}-\\boldsymbol{X}\\boldsymbol{\\beta}\\vert\\vert_2^2+\\lambda\\vert\\vert \\boldsymbol{\\beta}\\vert\\vert_2^2\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "94414ad1", - "metadata": { - "editable": true - }, - "source": [ - "which leads to the Ridge regression minimization problem where we\n", - "require that $\\vert\\vert \\boldsymbol{\\beta}\\vert\\vert_2^2\\le t$, where $t$ is\n", - "a finite number larger than zero. By defining" - ] - }, - { - "cell_type": "markdown", - "id": "cbb571a8", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "C(\\boldsymbol{X},\\boldsymbol{\\beta})=\\frac{1}{n}\\vert\\vert \\boldsymbol{y}-\\boldsymbol{X}\\boldsymbol{\\beta}\\vert\\vert_2^2+\\lambda\\vert\\vert \\boldsymbol{\\beta}\\vert\\vert_1,\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "08d69de8", - "metadata": { - "editable": true - }, - "source": [ - "we have a new optimization equation" - ] - }, - { - "cell_type": "markdown", - "id": "17827d0b", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "{\\displaystyle \\min_{\\boldsymbol{\\beta}\\in\n", - "{\\mathbb{R}}^{p}}}\\frac{1}{n}\\vert\\vert \\boldsymbol{y}-\\boldsymbol{X}\\boldsymbol{\\beta}\\vert\\vert_2^2+\\lambda\\vert\\vert \\boldsymbol{\\beta}\\vert\\vert_1\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "a2606f59", - "metadata": { - "editable": true - }, - "source": [ - "which leads to Lasso regression. Lasso stands for least absolute shrinkage and selection operator. \n", - "\n", - "Here we have defined the norm-1 as" - ] - }, - { - "cell_type": "markdown", - "id": "1a261469", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\vert\\vert \\boldsymbol{x}\\vert\\vert_1 = \\sum_i \\vert x_i\\vert.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "2c25d0ff", - "metadata": { - "editable": true - }, - "source": [ - "## Deriving the Ridge Regression Equations\n", - "\n", - "Using the matrix-vector expression for Ridge regression and dropping the parameter $1/n$ in front of the standard means squared error equation, we have" - ] - }, - { - "cell_type": "markdown", - "id": "1cbbda83", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "C(\\boldsymbol{X},\\boldsymbol{\\beta})=\\left\\{(\\boldsymbol{y}-\\boldsymbol{X}\\boldsymbol{\\beta})^T(\\boldsymbol{y}-\\boldsymbol{X}\\boldsymbol{\\beta})\\right\\}+\\lambda\\boldsymbol{\\beta}^T\\boldsymbol{\\beta},\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "10e5cd79", - "metadata": { - "editable": true - }, - "source": [ - "and \n", - "taking the derivatives with respect to $\\boldsymbol{\\beta}$ we obtain then\n", - "a slightly modified matrix inversion problem which for finite values\n", - "of $\\lambda$ does not suffer from singularity problems. We obtain\n", - "the optimal parameters" - ] - }, - { - "cell_type": "markdown", - "id": "8149c527", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\hat{\\boldsymbol{\\beta}}_{\\mathrm{Ridge}} = \\left(\\boldsymbol{X}^T\\boldsymbol{X}+\\lambda\\boldsymbol{I}\\right)^{-1}\\boldsymbol{X}^T\\boldsymbol{y},\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "86370c66", - "metadata": { - "editable": true - }, - "source": [ - "with $\\boldsymbol{I}$ being a $p\\times p$ identity matrix with the constraint that" - ] - }, - { - "cell_type": "markdown", - "id": "ca970c01", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\sum_{i=0}^{p-1} \\beta_i^2 \\leq t,\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "0a6651d6", - "metadata": { - "editable": true - }, - "source": [ - "with $t$ a finite positive number. \n", - "\n", - "If we keep the $1/n$ factor, the equation for the optimal $\\beta$ changes to" - ] - }, - { - "cell_type": "markdown", - "id": "feb46caa", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\hat{\\boldsymbol{\\beta}}_{\\mathrm{Ridge}} = \\left(\\boldsymbol{X}^T\\boldsymbol{X}+n\\lambda\\boldsymbol{I}\\right)^{-1}\\boldsymbol{X}^T\\boldsymbol{y}.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "ba2ccc4c", - "metadata": { - "editable": true - }, - "source": [ - "In many textbooks the $1/n$ term is often omitted. Note that a library like **Scikit-Learn** does not include the $1/n$ factor in the setup of the cost function.\n", - "\n", - "When we compare this with the ordinary least squares result we have" - ] - }, - { - "cell_type": "markdown", - "id": "99bd5e5f", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\hat{\\boldsymbol{\\beta}}_{\\mathrm{OLS}} = \\left(\\boldsymbol{X}^T\\boldsymbol{X}\\right)^{-1}\\boldsymbol{X}^T\\boldsymbol{y},\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "122ac3fa", - "metadata": { - "editable": true - }, - "source": [ - "which can lead to singular matrices. However, with the SVD, we can always compute the inverse of the matrix $\\boldsymbol{X}^T\\boldsymbol{X}$.\n", - "\n", - "We see that Ridge regression is nothing but the standard OLS with a\n", - "modified diagonal term added to $\\boldsymbol{X}^T\\boldsymbol{X}$. The consequences, in\n", - "particular for our discussion of the bias-variance tradeoff are rather\n", - "interesting. We will see that for specific values of $\\lambda$, we may\n", - "even reduce the variance of the optimal parameters $\\boldsymbol{\\beta}$. These topics and other related ones, will be discussed after the more linear algebra oriented analysis here.\n", - "\n", - "Using our insights about the SVD of the design matrix $\\boldsymbol{X}$ \n", - "We have already analyzed the OLS solutions in terms of the eigenvectors (the columns) of the right singular value matrix $\\boldsymbol{U}$ as" - ] - }, - { - "cell_type": "markdown", - "id": "2ed2f1af", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\tilde{\\boldsymbol{y}}_{\\mathrm{OLS}}=\\boldsymbol{X}\\boldsymbol{\\beta} =\\boldsymbol{U}\\boldsymbol{U}^T\\boldsymbol{y}.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "ab6d373f", - "metadata": { - "editable": true - }, - "source": [ - "For Ridge regression this becomes" - ] - }, - { - "cell_type": "markdown", - "id": "12e89aa0", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\tilde{\\boldsymbol{y}}_{\\mathrm{Ridge}}=\\boldsymbol{X}\\boldsymbol{\\beta}_{\\mathrm{Ridge}} = \\boldsymbol{U\\Sigma V^T}\\left(\\boldsymbol{V}\\boldsymbol{\\Sigma}^2\\boldsymbol{V}^T+\\lambda\\boldsymbol{I} \\right)^{-1}(\\boldsymbol{U\\Sigma V^T})^T\\boldsymbol{y}=\\sum_{j=0}^{p-1}\\boldsymbol{u}_j\\boldsymbol{u}_j^T\\frac{\\sigma_j^2}{\\sigma_j^2+\\lambda}\\boldsymbol{y},\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "f5ad1a22", - "metadata": { - "editable": true - }, - "source": [ - "with the vectors $\\boldsymbol{u}_j$ being the columns of $\\boldsymbol{U}$ from the SVD of the matrix $\\boldsymbol{X}$." - ] - }, - { - "cell_type": "markdown", - "id": "972a591b", - "metadata": { - "editable": true - }, - "source": [ - "## Interpreting the Ridge results\n", - "\n", - "Since $\\lambda \\geq 0$, it means that compared to OLS, we have" - ] - }, - { - "cell_type": "markdown", - "id": "29b0a40c", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\frac{\\sigma_j^2}{\\sigma_j^2+\\lambda} \\leq 1.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "974b89b6", - "metadata": { - "editable": true - }, - "source": [ - "Ridge regression finds the coordinates of $\\boldsymbol{y}$ with respect to the\n", - "orthonormal basis $\\boldsymbol{U}$, it then shrinks the coordinates by\n", - "$\\frac{\\sigma_j^2}{\\sigma_j^2+\\lambda}$. Recall that the SVD has\n", - "eigenvalues ordered in a descending way, that is $\\sigma_i \\geq\n", - "\\sigma_{i+1}$.\n", - "\n", - "For small eigenvalues $\\sigma_i$ it means that their contributions become less important, a fact which can be used to reduce the number of degrees of freedom. More about this when we have covered the material on a statistical interpretation of various linear regression methods." - ] - }, - { - "cell_type": "markdown", - "id": "d32b5a75", - "metadata": { - "editable": true - }, - "source": [ - "## More interpretations\n", - "\n", - "For the sake of simplicity, let us assume that the design matrix is orthonormal, that is" - ] - }, - { - "cell_type": "markdown", - "id": "b7b0e4a9", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\boldsymbol{X}^T\\boldsymbol{X}=(\\boldsymbol{X}^T\\boldsymbol{X})^{-1} =\\boldsymbol{I}.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "00480506", - "metadata": { - "editable": true - }, - "source": [ - "In this case the standard OLS results in" - ] - }, - { - "cell_type": "markdown", - "id": "e478d349", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\boldsymbol{\\beta}^{\\mathrm{OLS}} = \\boldsymbol{X}^T\\boldsymbol{y}=\\sum_{i=0}^{n-1}\\boldsymbol{u}_i\\boldsymbol{u}_i^T\\boldsymbol{y},\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "9941badc", - "metadata": { - "editable": true - }, - "source": [ - "and" - ] - }, - { - "cell_type": "markdown", - "id": "d78d129f", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\boldsymbol{\\beta}^{\\mathrm{Ridge}} = \\left(\\boldsymbol{I}+\\lambda\\boldsymbol{I}\\right)^{-1}\\boldsymbol{X}^T\\boldsymbol{y}=\\left(1+\\lambda\\right)^{-1}\\boldsymbol{\\beta}^{\\mathrm{OLS}},\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "81e43d35", - "metadata": { - "editable": true - }, - "source": [ - "that is the Ridge estimator scales the OLS estimator by the inverse of a factor $1+\\lambda$, and\n", - "the Ridge estimator converges to zero when the hyperparameter goes to\n", - "infinity.\n", - "\n", - "We will come back to more interpreations after we have gone through some of the statistical analysis part. \n", - "\n", - "For more discussions of Ridge and Lasso regression, [Wessel van Wieringen's](https://arxiv.org/abs/1509.09169) article is highly recommended.\n", - "Similarly, [Mehta et al's article](https://arxiv.org/abs/1803.08823) is also recommended." - ] - }, - { - "cell_type": "markdown", - "id": "ab030d9f", - "metadata": { - "editable": true - }, - "source": [ - "## Deriving the Lasso Regression Equations\n", - "\n", - "Using the matrix-vector expression for Lasso regression, we have the following **cost** function" - ] - }, - { - "cell_type": "markdown", - "id": "5c1a039a", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "C(\\boldsymbol{X},\\boldsymbol{\\beta})=\\frac{1}{n}\\left\\{(\\boldsymbol{y}-\\boldsymbol{X}\\boldsymbol{\\beta})^T(\\boldsymbol{y}-\\boldsymbol{X}\\boldsymbol{\\beta})\\right\\}+\\lambda\\vert\\vert\\boldsymbol{\\beta}\\vert\\vert_1,\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "64005abb", - "metadata": { - "editable": true - }, - "source": [ - "Taking the derivative with respect to $\\boldsymbol{\\beta}$ and recalling that the derivative of the absolute value is (we drop the boldfaced vector symbol for simplicty)" - ] - }, - { - "cell_type": "markdown", - "id": "dd03458c", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\frac{d \\vert \\beta\\vert}{d \\beta}=\\mathrm{sgn}(\\beta)=\\left\\{\\begin{array}{cc} 1 & \\beta > 0 \\\\-1 & \\beta < 0, \\end{array}\\right.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "c1845e9a", - "metadata": { - "editable": true - }, - "source": [ - "we have that the derivative of the cost function is" - ] - }, - { - "cell_type": "markdown", - "id": "9daa3df6", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\frac{\\partial C(\\boldsymbol{X},\\boldsymbol{\\beta})}{\\partial \\boldsymbol{\\beta}}=-\\frac{2}{n}\\boldsymbol{X}^T(\\boldsymbol{y}-\\boldsymbol{X}\\boldsymbol{\\beta})+\\lambda sgn(\\boldsymbol{\\beta})=0,\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "add636f0", - "metadata": { - "editable": true - }, - "source": [ - "and reordering we have" - ] - }, - { - "cell_type": "markdown", - "id": "79c36fde", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\boldsymbol{X}^T\\boldsymbol{X}\\boldsymbol{\\beta}+\\frac{n}{2}\\lambda sgn(\\boldsymbol{\\beta})=2\\boldsymbol{X}^T\\boldsymbol{y}.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "d4b4abb2", - "metadata": { - "editable": true - }, - "source": [ - "We can redefine $\\lambda$ to absorb the constant $n/2$ and we rewrite the last equation as" - ] - }, - { - "cell_type": "markdown", - "id": "93a6f35c", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\boldsymbol{X}^T\\boldsymbol{X}\\boldsymbol{\\beta}+\\lambda sgn(\\boldsymbol{\\beta})=2\\boldsymbol{X}^T\\boldsymbol{y}.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "62647fc5", - "metadata": { - "editable": true - }, - "source": [ - "This equation does not lead to a nice analytical equation as in either Ridge regression or ordinary least squares. This equation can however be solved by using standard convex optimization algorithms using for example the Python package [CVXOPT](https://cvxopt.org/). We will discuss this later." - ] - } - ], - "metadata": {}, - "nbformat": 4, - "nbformat_minor": 5 -} diff --git a/doc/LectureNotes/week36.ipynb b/doc/LectureNotes/week36.ipynb deleted file mode 100644 index ededd9147..000000000 --- a/doc/LectureNotes/week36.ipynb +++ /dev/null @@ -1,4242 +0,0 @@ -{ - "cells": [ - { - "cell_type": "markdown", - "id": "2b900fea", - "metadata": { - "editable": true - }, - "source": [ - "\n", - "" - ] - }, - { - "cell_type": "markdown", - "id": "2286e211", - "metadata": { - "editable": true - }, - "source": [ - "# Week 36: Statistical interpretation of Linear Regression and Resampling techniques\n", - "**Morten Hjorth-Jensen**, Department of Physics, University of Oslo and Department of Physics and Astronomy and National Superconducting Cyclotron Laboratory, Michigan State University\n", - "\n", - "Date: **September 4-8, 2023**" - ] - }, - { - "cell_type": "markdown", - "id": "edbcd7f9", - "metadata": { - "editable": true - }, - "source": [ - "## Plans for week 36\n", - "\n", - "* Material for the active learning sessions on Tuesday and Wednesday\n", - "\n", - " * Summary from last week on discussion of SVD, Ridge and Lasso linear regression.\n", - "\n", - " * Recommended Reading: Hastie et al chapter 3, see \n", - "\n", - " * Presentation and discussion of first project\n", - "\n", - "* Material for the lecture on Thursday September 7\n", - "\n", - " * Technicalities related to scaling and other issues with data handling\n", - "\n", - " * Linear Regression and links with Statistics\n", - "\n", - " * [Recommended Reading: Goodfellow et al chapter 3 on probability theory](https://www.deeplearningbook.org/)\n", - "\n", - " * See also Murphy, sections 2.4 (Gaussian distributions) and 3.2 (Bayesian Statistics, basis)\n", - "\n", - " * [Video of lecture](https://youtu.be/Kc20CFK0z7Y) \n", - "\n", - " * [Whiteboard notes](https://github.com/CompPhysics/MachineLearning/blob/master/doc/HandWrittenNotes/2023/NotesSep7.pdf)" - ] - }, - { - "cell_type": "markdown", - "id": "5dbf3ff5", - "metadata": { - "editable": true - }, - "source": [ - "## Material for the active learning sessions Tuesday and Wednesday\n", - "\n", - "The material here contains a summary from last week and discussion of SVD, Ridge and Lasso regression with examples" - ] - }, - { - "cell_type": "markdown", - "id": "2dae8175", - "metadata": { - "editable": true - }, - "source": [ - "## Linear Regression and the SVD\n", - "\n", - "We used the SVD to analyse the matrix to invert in ordinary lineat regression" - ] - }, - { - "cell_type": "markdown", - "id": "fb3d486d", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\boldsymbol{X}^T\\boldsymbol{X}=\\boldsymbol{V}\\boldsymbol{\\Sigma}^T\\boldsymbol{U}^T\\boldsymbol{U}\\boldsymbol{\\Sigma}\\boldsymbol{V}^T=\\boldsymbol{V}\\boldsymbol{\\Sigma}^T\\boldsymbol{\\Sigma}\\boldsymbol{V}^T.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "5f8492a1", - "metadata": { - "editable": true - }, - "source": [ - "Since the matrices here have dimension $p\\times p$, with $p$ corresponding to the singular values, we defined last week the matrix" - ] - }, - { - "cell_type": "markdown", - "id": "a35422b4", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\boldsymbol{\\Sigma}^T\\boldsymbol{\\Sigma} = \\begin{bmatrix} \\tilde{\\boldsymbol{\\Sigma}} & \\boldsymbol{0}\\\\ \\end{bmatrix}\\begin{bmatrix} \\tilde{\\boldsymbol{\\Sigma}} \\\\ \\boldsymbol{0}\\end{bmatrix},\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "aef923ea", - "metadata": { - "editable": true - }, - "source": [ - "where the tilde-matrix $\\tilde{\\boldsymbol{\\Sigma}}$ is a matrix of dimension $p\\times p$ containing only the singular values $\\sigma_i$, that is" - ] - }, - { - "cell_type": "markdown", - "id": "5da8277b", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\tilde{\\boldsymbol{\\Sigma}}=\\begin{bmatrix} \\sigma_0 & 0 & 0 & \\dots & 0 & 0 \\\\\n", - " 0 & \\sigma_1 & 0 & \\dots & 0 & 0 \\\\\n", - "\t\t\t\t 0 & 0 & \\sigma_2 & \\dots & 0 & 0 \\\\\n", - "\t\t\t\t 0 & 0 & 0 & \\dots & \\sigma_{p-2} & 0 \\\\\n", - "\t\t\t\t 0 & 0 & 0 & \\dots & 0 & \\sigma_{p-1} \\\\\n", - "\\end{bmatrix},\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "eb34e530", - "metadata": { - "editable": true - }, - "source": [ - "meaning we can write" - ] - }, - { - "cell_type": "markdown", - "id": "a2a33728", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\boldsymbol{X}^T\\boldsymbol{X}=\\boldsymbol{V}\\tilde{\\boldsymbol{\\Sigma}}^2\\boldsymbol{V}^T.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "9bea1837", - "metadata": { - "editable": true - }, - "source": [ - "Multiplying from the right with $\\boldsymbol{V}$ (using the orthogonality of $\\boldsymbol{V}$) we get" - ] - }, - { - "cell_type": "markdown", - "id": "af711505", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\left(\\boldsymbol{X}^T\\boldsymbol{X}\\right)\\boldsymbol{V}=\\boldsymbol{V}\\tilde{\\boldsymbol{\\Sigma}}^2.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "f02b3738", - "metadata": { - "editable": true - }, - "source": [ - "## What does it mean?\n", - "\n", - "This means the vectors $\\boldsymbol{v}_i$ of the orthogonal matrix $\\boldsymbol{V}$\n", - "are the eigenvectors of the matrix $\\boldsymbol{X}^T\\boldsymbol{X}$ with eigenvalues\n", - "given by the singular values squared, that is" - ] - }, - { - "cell_type": "markdown", - "id": "d3fe4855", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\left(\\boldsymbol{X}^T\\boldsymbol{X}\\right)\\boldsymbol{v}_i=\\boldsymbol{v}_i\\sigma_i^2.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "7b5fa376", - "metadata": { - "editable": true - }, - "source": [ - "In other words, each non-zero singular value of $\\boldsymbol{X}$ is a positive\n", - "square root of an eigenvalue of $\\boldsymbol{X}^T\\boldsymbol{X}$. It means also that\n", - "the columns of $\\boldsymbol{V}$ are the eigenvectors of\n", - "$\\boldsymbol{X}^T\\boldsymbol{X}$. Since we have ordered the singular values of\n", - "$\\boldsymbol{X}$ in a descending order, it means that the column vectors\n", - "$\\boldsymbol{v}_i$ are hierarchically ordered by how much correlation they\n", - "encode from the columns of $\\boldsymbol{X}$. \n", - "\n", - "Note that these are also the eigenvectors and eigenvalues of the\n", - "Hessian matrix.\n", - "\n", - "If we now recall the definition of the covariance matrix (not using\n", - "Bessel's correction) we have" - ] - }, - { - "cell_type": "markdown", - "id": "d212be4e", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\boldsymbol{C}[\\boldsymbol{X}]=\\frac{1}{n}\\boldsymbol{X}^T\\boldsymbol{X},\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "eca13576", - "metadata": { - "editable": true - }, - "source": [ - "meaning that every squared non-singular value of $\\boldsymbol{X}$ divided by $n$ (\n", - "the number of samples) are the eigenvalues of the covariance\n", - "matrix. Every singular value of $\\boldsymbol{X}$ is thus a positive square\n", - "root of an eigenvalue of $\\boldsymbol{X}^T\\boldsymbol{X}$. If the matrix $\\boldsymbol{X}$ is\n", - "self-adjoint, the singular values of $\\boldsymbol{X}$ are equal to the\n", - "absolute value of the eigenvalues of $\\boldsymbol{X}$." - ] - }, - { - "cell_type": "markdown", - "id": "fbf0e2be", - "metadata": { - "editable": true - }, - "source": [ - "## And finally $\\boldsymbol{X}\\boldsymbol{X}^T$\n", - "\n", - "For $\\boldsymbol{X}\\boldsymbol{X}^T$ we found" - ] - }, - { - "cell_type": "markdown", - "id": "acbd86ec", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\boldsymbol{X}\\boldsymbol{X}^T=\\boldsymbol{U}\\boldsymbol{\\Sigma}\\boldsymbol{V}^T\\boldsymbol{V}\\boldsymbol{\\Sigma}^T\\boldsymbol{U}^T=\\boldsymbol{U}\\boldsymbol{\\Sigma}^T\\boldsymbol{\\Sigma}\\boldsymbol{U}^T.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "8887e338", - "metadata": { - "editable": true - }, - "source": [ - "Since the matrices here have dimension $n\\times n$, we have" - ] - }, - { - "cell_type": "markdown", - "id": "e95bcbda", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\boldsymbol{\\Sigma}\\boldsymbol{\\Sigma}^T = \\begin{bmatrix} \\tilde{\\boldsymbol{\\Sigma}} \\\\ \\boldsymbol{0}\\\\ \\end{bmatrix}\\begin{bmatrix} \\tilde{\\boldsymbol{\\Sigma}} \\boldsymbol{0}\\\\ \\end{bmatrix}=\\begin{bmatrix} \\tilde{\\boldsymbol{\\Sigma}} & \\boldsymbol{0} \\\\ \\boldsymbol{0} & \\boldsymbol{0}\\\\ \\end{bmatrix},\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "e66200c2", - "metadata": { - "editable": true - }, - "source": [ - "leading to" - ] - }, - { - "cell_type": "markdown", - "id": "a0c3692c", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\boldsymbol{X}\\boldsymbol{X}^T=\\boldsymbol{U}\\begin{bmatrix} \\tilde{\\boldsymbol{\\Sigma}} & \\boldsymbol{0} \\\\ \\boldsymbol{0} & \\boldsymbol{0}\\\\ \\end{bmatrix}\\boldsymbol{U}^T.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "8d13a9ff", - "metadata": { - "editable": true - }, - "source": [ - "Multiplying with $\\boldsymbol{U}$ from the right gives us the eigenvalue problem" - ] - }, - { - "cell_type": "markdown", - "id": "31c3dd91", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "(\\boldsymbol{X}\\boldsymbol{X}^T)\\boldsymbol{U}=\\boldsymbol{U}\\begin{bmatrix} \\tilde{\\boldsymbol{\\Sigma}} & \\boldsymbol{0} \\\\ \\boldsymbol{0} & \\boldsymbol{0}\\\\ \\end{bmatrix}.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "87a6b291", - "metadata": { - "editable": true - }, - "source": [ - "It means that the eigenvalues of $\\boldsymbol{X}\\boldsymbol{X}^T$ are again given by\n", - "the non-zero singular values plus now a series of zeros. The column\n", - "vectors of $\\boldsymbol{U}$ are the eigenvectors of $\\boldsymbol{X}\\boldsymbol{X}^T$ and\n", - "measure how much correlations are contained in the rows of $\\boldsymbol{X}$.\n", - "\n", - "Since we will mainly be interested in the correlations among the features\n", - "of our data (the columns of $\\boldsymbol{X}$, the quantity of interest for us are the non-zero singular\n", - "values and the column vectors of $\\boldsymbol{V}$." - ] - }, - { - "cell_type": "markdown", - "id": "3bb9eed3", - "metadata": { - "editable": true - }, - "source": [ - "## Code for SVD and Inversion of Matrices\n", - "\n", - "How do we use the SVD to invert a matrix $\\boldsymbol{X}^\\boldsymbol{X}$ which is singular or near singular?\n", - "The simple answer is to use the linear algebra function for the computation of the pseudoinverse of a given matrix $\\boldsymbol{X}$, that is" - ] - }, - { - "cell_type": "code", - "execution_count": 1, - "id": "ba123060", - "metadata": { - "collapsed": false, - "editable": true - }, - "outputs": [], - "source": [ - "import numpy as np\n", - "X = np.array( [ [1,2,3],[2,4,5],[3,5,6]])\n", - "Xinv = np.linlag.pinv(X)" - ] - }, - { - "cell_type": "markdown", - "id": "46fdfd39", - "metadata": { - "editable": true - }, - "source": [ - "Let us first look at a matrix which does not causes problems and write our own function where we just use the SVD." - ] - }, - { - "cell_type": "code", - "execution_count": 2, - "id": "36e47fde", - "metadata": { - "collapsed": false, - "editable": true - }, - "outputs": [], - "source": [ - "import numpy as np\n", - "# SVD inversion\n", - "def SVDinv(A):\n", - " ''' Takes as input a numpy matrix A and returns inv(A) based on singular value decomposition (SVD).\n", - " SVD is numerically more stable than the inversion algorithms provided by\n", - " numpy and scipy.linalg at the cost of being slower.\n", - " '''\n", - " U, s, VT = np.linalg.svd(A)\n", - " print('test U')\n", - " print( (np.transpose(U) @ U - U @np.transpose(U)))\n", - " print('test VT')\n", - " print( (np.transpose(VT) @ VT - VT @np.transpose(VT)))\n", - "\n", - "\n", - " D = np.zeros((len(U),len(VT)))\n", - " D = np.diag(s)\n", - " UT = np.transpose(U); V = np.transpose(VT); invD = np.linalg.inv(D)\n", - " return np.matmul(V,np.matmul(invD,UT))\n", - "\n", - "\n", - "#X = np.array([ [1.0, -1.0, 2.0], [1.0, 0.0, 1.0], [1.0, 2.0, -1.0], [1.0, 1.0, 0.0] ])\n", - "# Non-singular square matrix\n", - "X = np.array( [ [1,2,3],[2,4,5],[3,5,6]])\n", - "print(X)\n", - "A = np.transpose(X) @ X\n", - "# Brute force inversion\n", - "B = np.linalg.inv(A) # here we could use np.linalg.pinv(A)\n", - "C = SVDinv(A)\n", - "print(np.abs(B-C))" - ] - }, - { - "cell_type": "markdown", - "id": "53878874", - "metadata": { - "editable": true - }, - "source": [ - "## Inverse of Rectangular Matrix\n", - "\n", - "Although our matrix to invert $\\boldsymbol{X}^T\\boldsymbol{X}$ is a square matrix, our matrix may be singular. \n", - "\n", - "The pseudoinverse is the generalization of the matrix inverse for square matrices to\n", - "rectangular matrices where the number of rows and columns are not equal.\n", - "\n", - "It is also called the the Moore-Penrose Inverse after two independent discoverers of the method or the Generalized Inverse.\n", - "It is used for the calculation of the inverse for singular or near singular matrices and for rectangular matrices.\n", - "\n", - "Using the SVD we can obtain the pseudoinverse of a matrix $\\boldsymbol{A}$ (labeled here as $\\boldsymbol{A}_{\\mathrm{PI}}$)" - ] - }, - { - "cell_type": "markdown", - "id": "87546753", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\boldsymbol{A}_{\\mathrm{PI}}= \\boldsymbol{V}\\boldsymbol{D}_{\\mathrm{PI}}\\boldsymbol{U}^T,\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "d8a4669d", - "metadata": { - "editable": true - }, - "source": [ - "where $\\boldsymbol{D}_{\\mathrm{PI}}$ can be calculated by creating a diagonal matrix from $\\boldsymbol{\\Sigma}$ where we only keep the singular values (the non-zero values). The following code computes the pseudoinvers of the matrix based on the SVD." - ] - }, - { - "cell_type": "code", - "execution_count": 3, - "id": "b6523ecb", - "metadata": { - "collapsed": false, - "editable": true - }, - "outputs": [], - "source": [ - "import numpy as np\n", - "# SVD inversion\n", - "def SVDinv(A):\n", - " U, s, VT = np.linalg.svd(A)\n", - " # reciprocals of singular values of s\n", - " d = 1.0 / s\n", - " # create m x n D matrix\n", - " D = np.zeros(A.shape)\n", - " # populate D with n x n diagonal matrix\n", - " D[:A.shape[1], :A.shape[1]] = np.diag(d)\n", - " UT = np.transpose(U)\n", - " V = np.transpose(VT)\n", - " return np.matmul(V,np.matmul(D.T,UT))\n", - "\n", - "\n", - "A = np.array([ [0.3, 0.4], [0.5, 0.6], [0.7, 0.8],[0.9, 1.0]])\n", - "print(A)\n", - "# Brute force inversion of super-collinear matrix\n", - "B = np.linalg.pinv(A)\n", - "print(B)\n", - "# Compare our own algorithm with pinv\n", - "C = SVDinv(A)\n", - "print(np.abs(C-B))" - ] - }, - { - "cell_type": "markdown", - "id": "2fce573f", - "metadata": { - "editable": true - }, - "source": [ - "As you can see from this example, our own decomposition based on the SVD agrees with the pseudoinverse algorithm provided by **Numpy**." - ] - }, - { - "cell_type": "markdown", - "id": "840991d3", - "metadata": { - "editable": true - }, - "source": [ - "## Ridge and LASSO Regression\n", - "\n", - "Let us remind ourselves about the expression for the standard Mean Squared Error (MSE) which we used to define our cost function and the equations for the ordinary least squares (OLS) method, that is \n", - "our optimization problem is" - ] - }, - { - "cell_type": "markdown", - "id": "4df7aac6", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "{\\displaystyle \\min_{\\boldsymbol{\\beta}\\in {\\mathbb{R}}^{p}}}\\frac{1}{n}\\left\\{\\left(\\boldsymbol{y}-\\boldsymbol{X}\\boldsymbol{\\beta}\\right)^T\\left(\\boldsymbol{y}-\\boldsymbol{X}\\boldsymbol{\\beta}\\right)\\right\\}.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "3f3acc05", - "metadata": { - "editable": true - }, - "source": [ - "or we can state it as" - ] - }, - { - "cell_type": "markdown", - "id": "2d1218f6", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "{\\displaystyle \\min_{\\boldsymbol{\\beta}\\in\n", - "{\\mathbb{R}}^{p}}}\\frac{1}{n}\\sum_{i=0}^{n-1}\\left(y_i-\\tilde{y}_i\\right)^2=\\frac{1}{n}\\vert\\vert \\boldsymbol{y}-\\boldsymbol{X}\\boldsymbol{\\beta}\\vert\\vert_2^2,\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "01624e31", - "metadata": { - "editable": true - }, - "source": [ - "where we have used the definition of a norm-2 vector, that is" - ] - }, - { - "cell_type": "markdown", - "id": "616fe159", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\vert\\vert \\boldsymbol{x}\\vert\\vert_2 = \\sqrt{\\sum_i x_i^2}.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "27cf2acd", - "metadata": { - "editable": true - }, - "source": [ - "## From OLS to Ridge and Lasso\n", - "\n", - "By minimizing the above equation with respect to the parameters\n", - "$\\boldsymbol{\\beta}$ we could then obtain an analytical expression for the\n", - "parameters $\\boldsymbol{\\beta}$. We can add a regularization parameter $\\lambda$ by\n", - "defining a new cost function to be optimized, that is" - ] - }, - { - "cell_type": "markdown", - "id": "2ff1e0d2", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "{\\displaystyle \\min_{\\boldsymbol{\\beta}\\in\n", - "{\\mathbb{R}}^{p}}}\\frac{1}{n}\\vert\\vert \\boldsymbol{y}-\\boldsymbol{X}\\boldsymbol{\\beta}\\vert\\vert_2^2+\\lambda\\vert\\vert \\boldsymbol{\\beta}\\vert\\vert_2^2\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "aef1996b", - "metadata": { - "editable": true - }, - "source": [ - "which leads to the Ridge regression minimization problem where we\n", - "require that $\\vert\\vert \\boldsymbol{\\beta}\\vert\\vert_2^2\\le t$, where $t$ is\n", - "a finite number larger than zero. We do not include such a constraints in the discussions here.\n", - "\n", - "By defining" - ] - }, - { - "cell_type": "markdown", - "id": "75a44cc9", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "C(\\boldsymbol{X},\\boldsymbol{\\beta})=\\frac{1}{n}\\vert\\vert \\boldsymbol{y}-\\boldsymbol{X}\\boldsymbol{\\beta}\\vert\\vert_2^2+\\lambda\\vert\\vert \\boldsymbol{\\beta}\\vert\\vert_1,\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "e2ba6037", - "metadata": { - "editable": true - }, - "source": [ - "we have a new optimization equation" - ] - }, - { - "cell_type": "markdown", - "id": "95517053", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "{\\displaystyle \\min_{\\boldsymbol{\\beta}\\in\n", - "{\\mathbb{R}}^{p}}}\\frac{1}{n}\\vert\\vert \\boldsymbol{y}-\\boldsymbol{X}\\boldsymbol{\\beta}\\vert\\vert_2^2+\\lambda\\vert\\vert \\boldsymbol{\\beta}\\vert\\vert_1\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "5f15d4ea", - "metadata": { - "editable": true - }, - "source": [ - "which leads to Lasso regression. Lasso stands for least absolute shrinkage and selection operator. \n", - "\n", - "Here we have defined the norm-1 as" - ] - }, - { - "cell_type": "markdown", - "id": "68579bd0", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\vert\\vert \\boldsymbol{x}\\vert\\vert_1 = \\sum_i \\vert x_i\\vert.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "53887938", - "metadata": { - "editable": true - }, - "source": [ - "## Deriving the Ridge Regression Equations\n", - "\n", - "Using the matrix-vector expression for Ridge regression and dropping the parameter $1/n$ in front of the standard means squared error equation, we have" - ] - }, - { - "cell_type": "markdown", - "id": "469c8c35", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "C(\\boldsymbol{X},\\boldsymbol{\\beta})=\\left\\{(\\boldsymbol{y}-\\boldsymbol{X}\\boldsymbol{\\beta})^T(\\boldsymbol{y}-\\boldsymbol{X}\\boldsymbol{\\beta})\\right\\}+\\lambda\\boldsymbol{\\beta}^T\\boldsymbol{\\beta},\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "a7521a38", - "metadata": { - "editable": true - }, - "source": [ - "and \n", - "taking the derivatives with respect to $\\boldsymbol{\\beta}$ we obtain then\n", - "a slightly modified matrix inversion problem which for finite values\n", - "of $\\lambda$ does not suffer from singularity problems. We obtain\n", - "the optimal parameters" - ] - }, - { - "cell_type": "markdown", - "id": "cdfddb46", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\hat{\\boldsymbol{\\beta}}_{\\mathrm{Ridge}} = \\left(\\boldsymbol{X}^T\\boldsymbol{X}+\\lambda\\boldsymbol{I}\\right)^{-1}\\boldsymbol{X}^T\\boldsymbol{y},\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "e87c8606", - "metadata": { - "editable": true - }, - "source": [ - "with $\\boldsymbol{I}$ being a $p\\times p$ identity matrix with the constraint that" - ] - }, - { - "cell_type": "markdown", - "id": "3e06d524", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\sum_{i=0}^{p-1} \\beta_i^2 \\leq t,\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "798d77a9", - "metadata": { - "editable": true - }, - "source": [ - "with $t$ a finite positive number." - ] - }, - { - "cell_type": "markdown", - "id": "8808de88", - "metadata": { - "editable": true - }, - "source": [ - "## Note on Scikit-Learn\n", - "\n", - "Note well that a library like **Scikit-Learn** does not include the $1/n$ factor in the expression for the mean-squared error. If you include it, the optimal parameter $\\beta$ becomes" - ] - }, - { - "cell_type": "markdown", - "id": "c3825a07", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\hat{\\boldsymbol{\\beta}}_{\\mathrm{Ridge}} = \\left(\\boldsymbol{X}^T\\boldsymbol{X}+n\\lambda\\boldsymbol{I}\\right)^{-1}\\boldsymbol{X}^T\\boldsymbol{y}.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "868b6a19", - "metadata": { - "editable": true - }, - "source": [ - "In our codes where we compare our own codes with **Scikit-Learn**, we do thus not include the $1/n$ factor in the cost function." - ] - }, - { - "cell_type": "markdown", - "id": "eaba5f13", - "metadata": { - "editable": true - }, - "source": [ - "## Comparison with OLS\n", - "When we compare this with the ordinary least squares result we have" - ] - }, - { - "cell_type": "markdown", - "id": "c9cc77c3", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\hat{\\boldsymbol{\\beta}}_{\\mathrm{OLS}} = \\left(\\boldsymbol{X}^T\\boldsymbol{X}\\right)^{-1}\\boldsymbol{X}^T\\boldsymbol{y},\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "4b3e1232", - "metadata": { - "editable": true - }, - "source": [ - "which can lead to singular matrices. However, with the SVD, we can always compute the inverse of the matrix $\\boldsymbol{X}^T\\boldsymbol{X}$.\n", - "\n", - "We see that Ridge regression is nothing but the standard OLS with a\n", - "modified diagonal term added to $\\boldsymbol{X}^T\\boldsymbol{X}$. The consequences, in\n", - "particular for our discussion of the bias-variance tradeoff are rather\n", - "interesting. We will see that for specific values of $\\lambda$, we may\n", - "even reduce the variance of the optimal parameters $\\boldsymbol{\\beta}$. These topics and other related ones, will be discussed after the more linear algebra oriented analysis here." - ] - }, - { - "cell_type": "markdown", - "id": "d59ed944", - "metadata": { - "editable": true - }, - "source": [ - "## SVD analysis\n", - "\n", - "Using our insights about the SVD of the design matrix $\\boldsymbol{X}$ \n", - "We have already analyzed the OLS solutions in terms of the eigenvectors (the columns) of the right singular value matrix $\\boldsymbol{U}$ as" - ] - }, - { - "cell_type": "markdown", - "id": "e81dd0be", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\tilde{\\boldsymbol{y}}_{\\mathrm{OLS}}=\\boldsymbol{X}\\boldsymbol{\\beta} =\\boldsymbol{U}\\boldsymbol{U}^T\\boldsymbol{y}.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "f26a385c", - "metadata": { - "editable": true - }, - "source": [ - "For Ridge regression this becomes" - ] - }, - { - "cell_type": "markdown", - "id": "aa00d97a", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\tilde{\\boldsymbol{y}}_{\\mathrm{Ridge}}=\\boldsymbol{X}\\boldsymbol{\\beta}_{\\mathrm{Ridge}} = \\boldsymbol{U\\Sigma V^T}\\left(\\boldsymbol{V}\\boldsymbol{\\Sigma}^2\\boldsymbol{V}^T+\\lambda\\boldsymbol{I} \\right)^{-1}(\\boldsymbol{U\\Sigma V^T})^T\\boldsymbol{y}=\\sum_{j=0}^{p-1}\\boldsymbol{u}_j\\boldsymbol{u}_j^T\\frac{\\sigma_j^2}{\\sigma_j^2+\\lambda}\\boldsymbol{y},\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "17ba8d1c", - "metadata": { - "editable": true - }, - "source": [ - "with the vectors $\\boldsymbol{u}_j$ being the columns of $\\boldsymbol{U}$ from the SVD of the matrix $\\boldsymbol{X}$." - ] - }, - { - "cell_type": "markdown", - "id": "8cf9dc8f", - "metadata": { - "editable": true - }, - "source": [ - "## Interpreting the Ridge results\n", - "\n", - "Since $\\lambda \\geq 0$, it means that compared to OLS, we have" - ] - }, - { - "cell_type": "markdown", - "id": "f0c43d20", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\frac{\\sigma_j^2}{\\sigma_j^2+\\lambda} \\leq 1.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "5b119d73", - "metadata": { - "editable": true - }, - "source": [ - "Ridge regression finds the coordinates of $\\boldsymbol{y}$ with respect to the\n", - "orthonormal basis $\\boldsymbol{U}$, it then shrinks the coordinates by\n", - "$\\frac{\\sigma_j^2}{\\sigma_j^2+\\lambda}$. Recall that the SVD has\n", - "eigenvalues ordered in a descending way, that is $\\sigma_i \\geq\n", - "\\sigma_{i+1}$.\n", - "\n", - "For small eigenvalues $\\sigma_i$ it means that their contributions become less important, a fact which can be used to reduce the number of degrees of freedom. More about this when we have covered the material on a statistical interpretation of various linear regression methods." - ] - }, - { - "cell_type": "markdown", - "id": "1efba158", - "metadata": { - "editable": true - }, - "source": [ - "## More interpretations\n", - "\n", - "For the sake of simplicity, let us assume that the design matrix is orthonormal, that is" - ] - }, - { - "cell_type": "markdown", - "id": "e5943a40", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\boldsymbol{X}^T\\boldsymbol{X}=(\\boldsymbol{X}^T\\boldsymbol{X})^{-1} =\\boldsymbol{I}.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "167a1a9e", - "metadata": { - "editable": true - }, - "source": [ - "In this case the standard OLS results in" - ] - }, - { - "cell_type": "markdown", - "id": "924b5c9b", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\boldsymbol{\\beta}^{\\mathrm{OLS}} = \\boldsymbol{X}^T\\boldsymbol{y}=\\sum_{i=0}^{n-1}\\boldsymbol{u}_i\\boldsymbol{u}_i^T\\boldsymbol{y},\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "56ac0a65", - "metadata": { - "editable": true - }, - "source": [ - "and" - ] - }, - { - "cell_type": "markdown", - "id": "4323c860", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\boldsymbol{\\beta}^{\\mathrm{Ridge}} = \\left(\\boldsymbol{I}+\\lambda\\boldsymbol{I}\\right)^{-1}\\boldsymbol{X}^T\\boldsymbol{y}=\\left(1+\\lambda\\right)^{-1}\\boldsymbol{\\beta}^{\\mathrm{OLS}},\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "12ef13b2", - "metadata": { - "editable": true - }, - "source": [ - "that is the Ridge estimator scales the OLS estimator by the inverse of a factor $1+\\lambda$, and\n", - "the Ridge estimator converges to zero when the hyperparameter goes to\n", - "infinity.\n", - "\n", - "We will come back to more interpreations after we have gone through some of the statistical analysis part. \n", - "\n", - "For more discussions of Ridge and Lasso regression, [Wessel van Wieringen's](https://arxiv.org/abs/1509.09169) article is highly recommended.\n", - "Similarly, [Mehta et al's article](https://arxiv.org/abs/1803.08823) is also recommended." - ] - }, - { - "cell_type": "markdown", - "id": "d33c685e", - "metadata": { - "editable": true - }, - "source": [ - "## Deriving the Lasso Regression Equations\n", - "\n", - "Using the matrix-vector expression for Lasso regression, we have the following **cost** function" - ] - }, - { - "cell_type": "markdown", - "id": "b30d436d", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "C(\\boldsymbol{X},\\boldsymbol{\\beta})=\\frac{1}{n}\\left\\{(\\boldsymbol{y}-\\boldsymbol{X}\\boldsymbol{\\beta})^T(\\boldsymbol{y}-\\boldsymbol{X}\\boldsymbol{\\beta})\\right\\}+\\lambda\\vert\\vert\\boldsymbol{\\beta}\\vert\\vert_1,\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "37e47a2a", - "metadata": { - "editable": true - }, - "source": [ - "Taking the derivative with respect to $\\boldsymbol{\\beta}$ and recalling that the derivative of the absolute value is (we drop the boldfaced vector symbol for simplicity)" - ] - }, - { - "cell_type": "markdown", - "id": "3f87ff41", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\frac{d \\vert \\beta\\vert}{d \\beta}=\\mathrm{sgn}(\\beta)=\\left\\{\\begin{array}{cc} 1 & \\beta > 0 \\\\-1 & \\beta < 0, \\end{array}\\right.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "b14d10ff", - "metadata": { - "editable": true - }, - "source": [ - "we have that the derivative of the cost function is" - ] - }, - { - "cell_type": "markdown", - "id": "672b64b5", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\frac{\\partial C(\\boldsymbol{X},\\boldsymbol{\\beta})}{\\partial \\boldsymbol{\\beta}}=-\\frac{2}{n}\\boldsymbol{X}^T(\\boldsymbol{y}-\\boldsymbol{X}\\boldsymbol{\\beta})+\\lambda sgn(\\boldsymbol{\\beta})=0,\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "ef321df6", - "metadata": { - "editable": true - }, - "source": [ - "and reordering we have" - ] - }, - { - "cell_type": "markdown", - "id": "e67e683d", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\boldsymbol{X}^T\\boldsymbol{X}\\boldsymbol{\\beta}+\\lambda sgn(\\boldsymbol{\\beta})=\\boldsymbol{X}^T\\boldsymbol{y}.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "b9bd1d3f", - "metadata": { - "editable": true - }, - "source": [ - "This equation does not lead to a nice analytical equation as in Ridge regression or ordinary least squares. We have absorbed the factor $2/n$ in a redefinition of the parameter $\\lambda$. We will solve this type of problems using libraries like **scikit-learn**." - ] - }, - { - "cell_type": "markdown", - "id": "b705fb0b", - "metadata": { - "editable": true - }, - "source": [ - "## Simple example to illustrate Ordinary Least Squares, Ridge and Lasso Regression\n", - "\n", - "Let us assume that our design matrix is given by unit (identity) matrix, that is a square diagonal matrix with ones only along the\n", - "diagonal. In this case we have an equal number of rows and columns $n=p$.\n", - "\n", - "Our model approximation is just $\\tilde{\\boldsymbol{y}}=\\boldsymbol{\\beta}$ and the mean squared error and thereby the cost function for ordinary least sqquares (OLS) is then (we drop the term $1/n$)" - ] - }, - { - "cell_type": "markdown", - "id": "03679605", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "C(\\boldsymbol{\\beta})=\\sum_{i=0}^{p-1}(y_i-\\beta_i)^2,\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "b58e9ee7", - "metadata": { - "editable": true - }, - "source": [ - "and minimizing we have that" - ] - }, - { - "cell_type": "markdown", - "id": "42d8e1b3", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\hat{\\beta}_i^{\\mathrm{OLS}} = y_i.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "db624348", - "metadata": { - "editable": true - }, - "source": [ - "## Ridge Regression\n", - "\n", - "For Ridge regression our cost function is" - ] - }, - { - "cell_type": "markdown", - "id": "8d37cd9f", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "C(\\boldsymbol{\\beta})=\\sum_{i=0}^{p-1}(y_i-\\beta_i)^2+\\lambda\\sum_{i=0}^{p-1}\\beta_i^2,\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "e88bc71d", - "metadata": { - "editable": true - }, - "source": [ - "and minimizing we have that" - ] - }, - { - "cell_type": "markdown", - "id": "7bee2106", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\hat{\\beta}_i^{\\mathrm{Ridge}} = \\frac{y_i}{1+\\lambda}.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "fc1dc754", - "metadata": { - "editable": true - }, - "source": [ - "## Lasso Regression\n", - "\n", - "For Lasso regression our cost function is" - ] - }, - { - "cell_type": "markdown", - "id": "e5c6d86f", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "C(\\boldsymbol{\\beta})=\\sum_{i=0}^{p-1}(y_i-\\beta_i)^2+\\lambda\\sum_{i=0}^{p-1}\\vert\\beta_i\\vert=\\sum_{i=0}^{p-1}(y_i-\\beta_i)^2+\\lambda\\sum_{i=0}^{p-1}\\sqrt{\\beta_i^2},\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "1413c7cf", - "metadata": { - "editable": true - }, - "source": [ - "and minimizing we have that" - ] - }, - { - "cell_type": "markdown", - "id": "1b181b9b", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "-2\\sum_{i=0}^{p-1}(y_i-\\beta_i)+\\lambda \\sum_{i=0}^{p-1}\\frac{(\\beta_i)}{\\vert\\beta_i\\vert}=0,\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "ca27bd28", - "metadata": { - "editable": true - }, - "source": [ - "which leads to" - ] - }, - { - "cell_type": "markdown", - "id": "f2ce6515", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\hat{\\boldsymbol{\\beta}}_i^{\\mathrm{Lasso}} = \\left\\{\\begin{array}{ccc}y_i-\\frac{\\lambda}{2} &\\mathrm{if} & y_i> \\frac{\\lambda}{2}\\\\\n", - " y_i+\\frac{\\lambda}{2} &\\mathrm{if} & y_i< -\\frac{\\lambda}{2}\\\\\n", - "\t\t\t\t\t\t\t 0 &\\mathrm{if} & \\vert y_i\\vert\\le \\frac{\\lambda}{2}\\end{array}\\right.\\\\.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "bbe27e9c", - "metadata": { - "editable": true - }, - "source": [ - "Plotting these results shows clearly that Lasso regression suppresses (sets to zero) values of $\\beta_i$ for specific values of $\\lambda$. Ridge regression reduces on the other hand the values of $\\beta_i$ as function of $\\lambda$." - ] - }, - { - "cell_type": "markdown", - "id": "3ddfa9f9", - "metadata": { - "editable": true - }, - "source": [ - "## Yet another Example\n", - "\n", - "Let us assume we have a data set with outputs/targets given by the vector" - ] - }, - { - "cell_type": "markdown", - "id": "2d31b195", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\boldsymbol{y}=\\begin{bmatrix}4 \\\\ 2 \\\\3\\end{bmatrix},\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "4b092e9b", - "metadata": { - "editable": true - }, - "source": [ - "and our inputs as a $3\\times 2$ design matrix" - ] - }, - { - "cell_type": "markdown", - "id": "7c845085", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\boldsymbol{X}=\\begin{bmatrix}2 & 0\\\\ 0 & 1 \\\\ 0 & 0\\end{bmatrix},\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "0fb000c5", - "metadata": { - "editable": true - }, - "source": [ - "meaning that we have two features and two unknown parameters $\\beta_0$ and $\\beta_1$ to be determined either by ordinary least squares, Ridge or Lasso regression." - ] - }, - { - "cell_type": "markdown", - "id": "bd4d8817", - "metadata": { - "editable": true - }, - "source": [ - "## The OLS case\n", - "\n", - "For ordinary least squares (OLS) we know that the optimal solution is" - ] - }, - { - "cell_type": "markdown", - "id": "d0d10a69", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\hat{\\boldsymbol{\\beta}}^{\\mathrm{OLS}}=\\left( \\boldsymbol{X}^T\\boldsymbol{X}\\right)^{-1}\\boldsymbol{X}^T\\boldsymbol{y}.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "d9db36da", - "metadata": { - "editable": true - }, - "source": [ - "Inserting the above values we obtain that" - ] - }, - { - "cell_type": "markdown", - "id": "a409bd8a", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\hat{\\boldsymbol{\\beta}}^{\\mathrm{OLS}}=\\begin{bmatrix}2 \\\\ 2\\end{bmatrix},\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "c3be5f03", - "metadata": { - "editable": true - }, - "source": [ - "The code which implements this simpler case is presented after the discussion of Ridge and Lasso." - ] - }, - { - "cell_type": "markdown", - "id": "6533b635", - "metadata": { - "editable": true - }, - "source": [ - "## The Ridge case\n", - "\n", - "For Ridge regression we have" - ] - }, - { - "cell_type": "markdown", - "id": "3c6b3074", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\hat{\\boldsymbol{\\beta}}^{\\mathrm{Ridge}}=\\left( \\boldsymbol{X}^T\\boldsymbol{X}+\\lambda\\boldsymbol{I}\\right)^{-1}\\boldsymbol{X}^T\\boldsymbol{y}.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "747eecf9", - "metadata": { - "editable": true - }, - "source": [ - "Inserting the above values we obtain that" - ] - }, - { - "cell_type": "markdown", - "id": "87542c6e", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\hat{\\boldsymbol{\\beta}}^{\\mathrm{Ridge}}=\\begin{bmatrix}\\frac{8}{4+\\lambda} \\\\ \\frac{2}{1+\\lambda}\\end{bmatrix},\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "13f97260", - "metadata": { - "editable": true - }, - "source": [ - "There is normally a constraint on the value of $\\vert\\vert \\boldsymbol{\\beta}\\vert\\vert_2$ via the parameter $\\lambda$.\n", - "Let us for simplicity assume that $\\beta_0^2+\\beta_1^2=1$ as constraint. This will allow us to find an expression for the optimal values of $\\beta$ and $\\lambda$.\n", - "\n", - "To see this, let us write the cost function for Ridge regression." - ] - }, - { - "cell_type": "markdown", - "id": "bc02bc84", - "metadata": { - "editable": true - }, - "source": [ - "## Writing the Cost Function\n", - "\n", - "We define the MSE without the $1/n$ factor and have then, using that" - ] - }, - { - "cell_type": "markdown", - "id": "9f9d8193", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\boldsymbol{X}\\boldsymbol{\\beta}=\\begin{bmatrix} 2\\beta_0 \\\\ \\beta_1 \\\\0 \\end{bmatrix},\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "ba404c5e", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "C(\\boldsymbol{\\beta})=(4-2\\beta_0)^2+(2-\\beta_1)^2+\\lambda(\\beta_0^2+\\beta_1^2),\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "9af7054a", - "metadata": { - "editable": true - }, - "source": [ - "and taking the derivative with respect to $\\beta_0$ we get" - ] - }, - { - "cell_type": "markdown", - "id": "eb7fd44a", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\beta_0=\\frac{8}{4+\\lambda},\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "041b60b2", - "metadata": { - "editable": true - }, - "source": [ - "and for $\\beta_1$ we obtain" - ] - }, - { - "cell_type": "markdown", - "id": "f95dc455", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\beta_1=\\frac{2}{1+\\lambda},\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "28176b93", - "metadata": { - "editable": true - }, - "source": [ - "Using the constraint for $\\beta_0^2+\\beta_1^2=1$ we can constrain $\\lambda$ by solving" - ] - }, - { - "cell_type": "markdown", - "id": "b6f75bf7", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\left(\\frac{8}{4+\\lambda}\\right)^2+\\left(\\frac{2}{1+\\lambda}\\right)^2=1,\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "f6ad6840", - "metadata": { - "editable": true - }, - "source": [ - "which gives $\\lambda=4.571$ and $\\beta_0=0.933$ and $\\beta_1=0.359$." - ] - }, - { - "cell_type": "markdown", - "id": "fe93ca4d", - "metadata": { - "editable": true - }, - "source": [ - "## Lasso case\n", - "\n", - "For Lasso we need now, keeping a constraint on $\\vert\\beta_0\\vert+\\vert\\beta_1\\vert=1$, to take the derivative of the absolute values of $\\beta_0$\n", - "and $\\beta_1$. This gives us the following derivatives of the cost function" - ] - }, - { - "cell_type": "markdown", - "id": "4d7921c1", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "C(\\boldsymbol{\\beta})=(4-2\\beta_0)^2+(2-\\beta_1)^2+\\lambda(\\vert\\beta_0\\vert+\\vert\\beta_1\\vert),\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "d106e526", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\frac{\\partial C(\\boldsymbol{\\beta})}{\\partial \\beta_0}=-4(4-2\\beta_0)+\\lambda\\mathrm{sgn}(\\beta_0)=0,\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "2ab11733", - "metadata": { - "editable": true - }, - "source": [ - "and" - ] - }, - { - "cell_type": "markdown", - "id": "c871f92c", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\frac{\\partial C(\\boldsymbol{\\beta})}{\\partial \\beta_1}=-2(2-\\beta_1)+\\lambda\\mathrm{sgn}(\\beta_1)=0.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "4fc85aac", - "metadata": { - "editable": true - }, - "source": [ - "We have now four cases to solve besides the trivial cases $\\beta_0$ and/or $\\beta_1$ are zero, namely\n", - "1. $\\beta_0 > 0$ and $\\beta_1 > 0$,\n", - "\n", - "2. $\\beta_0 > 0$ and $\\beta_1 < 0$,\n", - "\n", - "3. $\\beta_0 < 0$ and $\\beta_1 > 0$,\n", - "\n", - "4. $\\beta_0 < 0$ and $\\beta_1 < 0$." - ] - }, - { - "cell_type": "markdown", - "id": "c66960ef", - "metadata": { - "editable": true - }, - "source": [ - "## The first Case\n", - "\n", - "If we consider the first case, we have then" - ] - }, - { - "cell_type": "markdown", - "id": "6c742a89", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "-4(4-2\\beta_0)+\\lambda=0,\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "5a6fe016", - "metadata": { - "editable": true - }, - "source": [ - "and" - ] - }, - { - "cell_type": "markdown", - "id": "63472c22", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "-2(2-\\beta_1)+\\lambda=0.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "3ede415b", - "metadata": { - "editable": true - }, - "source": [ - "which yields" - ] - }, - { - "cell_type": "markdown", - "id": "90397204", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\beta_0=\\frac{16+\\lambda}{8},\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "acd78254", - "metadata": { - "editable": true - }, - "source": [ - "and" - ] - }, - { - "cell_type": "markdown", - "id": "114e58b4", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\beta_1=\\frac{4+\\lambda}{2}.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "dc251844", - "metadata": { - "editable": true - }, - "source": [ - "Using the constraint on $\\beta_0$ and $\\beta_1$ we can then find the optimal value of $\\lambda$ for the different cases. We leave this as an exercise to you." - ] - }, - { - "cell_type": "markdown", - "id": "2fb1ac98", - "metadata": { - "editable": true - }, - "source": [ - "## Simple code for solving the above problem\n", - "\n", - "Here we set up the OLS, Ridge and Lasso functionality in order to study the above example. Note that here we have opted for a set of values of $\\lambda$, meaning that we need to perform a search in order to find the optimal values.\n", - "\n", - "First we study and compare the OLS and Ridge results. The next code compares all three methods." - ] - }, - { - "cell_type": "code", - "execution_count": 4, - "id": "8c64672d", - "metadata": { - "collapsed": false, - "editable": true - }, - "outputs": [], - "source": [ - "%matplotlib inline\n", - "\n", - "import os\n", - "import numpy as np\n", - "import pandas as pd\n", - "import matplotlib.pyplot as plt\n", - "\n", - "def R2(y_data, y_model):\n", - " return 1 - np.sum((y_data - y_model) ** 2) / np.sum((y_data - np.mean(y_data)) ** 2)\n", - "def MSE(y_data,y_model):\n", - " n = np.size(y_model)\n", - " return np.sum((y_data-y_model)**2)/n\n", - "\n", - "\n", - "# A seed just to ensure that the random numbers are the same for every run.\n", - "# Useful for eventual debugging.\n", - "\n", - "X = np.array( [ [ 2, 0], [0, 1], [0,0]])\n", - "y = np.array( [4, 2, 3])\n", - "\n", - "\n", - "# matrix inversion to find beta\n", - "OLSbeta = np.linalg.inv(X.T @ X) @ X.T @ y\n", - "print(OLSbeta)\n", - "# and then make the prediction\n", - "ytildeOLS = X @ OLSbeta\n", - "print(\"Training MSE for OLS\")\n", - "print(MSE(y,ytildeOLS))\n", - "ypredictOLS = X @ OLSbeta\n", - "\n", - "# Repeat now for Ridge regression and various values of the regularization parameter\n", - "I = np.eye(2,2)\n", - "# Decide which values of lambda to use\n", - "nlambdas = 100\n", - "MSEPredict = np.zeros(nlambdas)\n", - "lambdas = np.logspace(-4, 4, nlambdas)\n", - "for i in range(nlambdas):\n", - " lmb = lambdas[i]\n", - " Ridgebeta = np.linalg.inv(X.T @ X+lmb*I) @ X.T @ y\n", - "# print(Ridgebeta)\n", - " # and then make the prediction\n", - " ypredictRidge = X @ Ridgebeta\n", - " MSEPredict[i] = MSE(y,ypredictRidge)\n", - "# print(MSEPredict[i])\n", - " # Now plot the results\n", - "plt.figure()\n", - "plt.plot(np.log10(lambdas), MSEPredict, 'r--', label = 'MSE Ridge Train')\n", - "plt.xlabel('log10(lambda)')\n", - "plt.ylabel('MSE')\n", - "plt.legend()\n", - "plt.show()" - ] - }, - { - "cell_type": "markdown", - "id": "a87e0be8", - "metadata": { - "editable": true - }, - "source": [ - "We see here that we reach a plateau. What is actually happening?" - ] - }, - { - "cell_type": "markdown", - "id": "ac5bf925", - "metadata": { - "editable": true - }, - "source": [ - "## With Lasso Regression" - ] - }, - { - "cell_type": "code", - "execution_count": 5, - "id": "078628d7", - "metadata": { - "collapsed": false, - "editable": true - }, - "outputs": [], - "source": [ - "import os\n", - "import numpy as np\n", - "import pandas as pd\n", - "import matplotlib.pyplot as plt\n", - "from sklearn import linear_model\n", - "\n", - "def R2(y_data, y_model):\n", - " return 1 - np.sum((y_data - y_model) ** 2) / np.sum((y_data - np.mean(y_data)) ** 2)\n", - "def MSE(y_data,y_model):\n", - " n = np.size(y_model)\n", - " return np.sum((y_data-y_model)**2)/n\n", - "\n", - "\n", - "# A seed just to ensure that the random numbers are the same for every run.\n", - "# Useful for eventual debugging.\n", - "\n", - "X = np.array( [ [ 2, 0], [0, 1], [0,0]])\n", - "y = np.array( [4, 2, 3])\n", - "\n", - "\n", - "# matrix inversion to find beta\n", - "OLSbeta = np.linalg.inv(X.T @ X) @ X.T @ y\n", - "print(OLSbeta)\n", - "# and then make the prediction\n", - "ytildeOLS = X @ OLSbeta\n", - "print(\"Training MSE for OLS\")\n", - "print(MSE(y,ytildeOLS))\n", - "ypredictOLS = X @ OLSbeta\n", - "\n", - "# Repeat now for Ridge regression and various values of the regularization parameter\n", - "I = np.eye(2,2)\n", - "# Decide which values of lambda to use\n", - "nlambdas = 100\n", - "MSERidgePredict = np.zeros(nlambdas)\n", - "MSELassoPredict = np.zeros(nlambdas)\n", - "lambdas = np.logspace(-4, 4, nlambdas)\n", - "for i in range(nlambdas):\n", - " lmb = lambdas[i]\n", - " Ridgebeta = np.linalg.inv(X.T @ X+lmb*I) @ X.T @ y\n", - " print(Ridgebeta)\n", - " # and then make the prediction\n", - " ypredictRidge = X @ Ridgebeta\n", - " MSERidgePredict[i] = MSE(y,ypredictRidge)\n", - " RegLasso = linear_model.Lasso(lmb,fit_intercept=False)\n", - " RegLasso.fit(X,y)\n", - " ypredictLasso = RegLasso.predict(X)\n", - " print(RegLasso.coef_)\n", - " MSELassoPredict[i] = MSE(y,ypredictLasso)\n", - "# Now plot the results\n", - "plt.figure()\n", - "plt.plot(np.log10(lambdas), MSERidgePredict, 'r--', label = 'MSE Ridge Train')\n", - "plt.plot(np.log10(lambdas), MSELassoPredict, 'r--', label = 'MSE Lasso Train')\n", - "plt.xlabel('log10(lambda)')\n", - "plt.ylabel('MSE')\n", - "plt.legend()\n", - "plt.show()" - ] - }, - { - "cell_type": "markdown", - "id": "f035fb09", - "metadata": { - "editable": true - }, - "source": [ - "## Another Example, now with a polynomial fit" - ] - }, - { - "cell_type": "code", - "execution_count": 6, - "id": "acb14894", - "metadata": { - "collapsed": false, - "editable": true - }, - "outputs": [], - "source": [ - "import os\n", - "import numpy as np\n", - "import pandas as pd\n", - "import matplotlib.pyplot as plt\n", - "from sklearn.model_selection import train_test_split\n", - "from sklearn import linear_model\n", - "\n", - "def R2(y_data, y_model):\n", - " return 1 - np.sum((y_data - y_model) ** 2) / np.sum((y_data - np.mean(y_data)) ** 2)\n", - "def MSE(y_data,y_model):\n", - " n = np.size(y_model)\n", - " return np.sum((y_data-y_model)**2)/n\n", - "\n", - "\n", - "# A seed just to ensure that the random numbers are the same for every run.\n", - "# Useful for eventual debugging.\n", - "np.random.seed(3155)\n", - "\n", - "x = np.random.rand(100)\n", - "y = 2.0+5*x*x+0.1*np.random.randn(100)\n", - "\n", - "# number of features p (here degree of polynomial\n", - "p = 3\n", - "# The design matrix now as function of a given polynomial\n", - "X = np.zeros((len(x),p))\n", - "X[:,0] = 1.0\n", - "X[:,1] = x\n", - "X[:,2] = x*x\n", - "# We split the data in test and training data\n", - "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2)\n", - "\n", - "# matrix inversion to find beta\n", - "OLSbeta = np.linalg.inv(X_train.T @ X_train) @ X_train.T @ y_train\n", - "print(OLSbeta)\n", - "# and then make the prediction\n", - "ytildeOLS = X_train @ OLSbeta\n", - "print(\"Training MSE for OLS\")\n", - "print(MSE(y_train,ytildeOLS))\n", - "ypredictOLS = X_test @ OLSbeta\n", - "print(\"Test MSE OLS\")\n", - "print(MSE(y_test,ypredictOLS))\n", - "\n", - "# Repeat now for Lasso and Ridge regression and various values of the regularization parameter\n", - "I = np.eye(p,p)\n", - "# Decide which values of lambda to use\n", - "nlambdas = 100\n", - "MSEPredict = np.zeros(nlambdas)\n", - "MSETrain = np.zeros(nlambdas)\n", - "MSELassoPredict = np.zeros(nlambdas)\n", - "MSELassoTrain = np.zeros(nlambdas)\n", - "lambdas = np.logspace(-4, 4, nlambdas)\n", - "for i in range(nlambdas):\n", - " lmb = lambdas[i]\n", - " Ridgebeta = np.linalg.inv(X_train.T @ X_train+lmb*I) @ X_train.T @ y_train\n", - " # include lasso using Scikit-Learn\n", - " RegLasso = linear_model.Lasso(lmb,fit_intercept=False)\n", - " RegLasso.fit(X_train,y_train)\n", - " # and then make the prediction\n", - " ytildeRidge = X_train @ Ridgebeta\n", - " ypredictRidge = X_test @ Ridgebeta\n", - " ytildeLasso = RegLasso.predict(X_train)\n", - " ypredictLasso = RegLasso.predict(X_test)\n", - " MSEPredict[i] = MSE(y_test,ypredictRidge)\n", - " MSETrain[i] = MSE(y_train,ytildeRidge)\n", - " MSELassoPredict[i] = MSE(y_test,ypredictLasso)\n", - " MSELassoTrain[i] = MSE(y_train,ytildeLasso)\n", - "\n", - "# Now plot the results\n", - "plt.figure()\n", - "plt.plot(np.log10(lambdas), MSETrain, label = 'MSE Ridge train')\n", - "plt.plot(np.log10(lambdas), MSEPredict, 'r--', label = 'MSE Ridge Test')\n", - "plt.plot(np.log10(lambdas), MSELassoTrain, label = 'MSE Lasso train')\n", - "plt.plot(np.log10(lambdas), MSELassoPredict, 'r--', label = 'MSE Lasso Test')\n", - "\n", - "plt.xlabel('log10(lambda)')\n", - "plt.ylabel('MSE')\n", - "plt.legend()\n", - "plt.show()" - ] - }, - { - "cell_type": "markdown", - "id": "391b11f6", - "metadata": { - "editable": true - }, - "source": [ - "## Material for lecture Thursday September 7" - ] - }, - { - "cell_type": "markdown", - "id": "242933c8", - "metadata": { - "editable": true - }, - "source": [ - "## Important technicalities: More on Rescaling data\n", - "\n", - "When you are comparing your own code with for example **Scikit-Learn**'s\n", - "library, there are some technicalities to keep in mind. The examples\n", - "here demonstrate some of these aspects with potential pitfalls.\n", - "\n", - "The discussion here focuses on the role of the intercept, how we can\n", - "set up the design matrix, what scaling we should use and other topics\n", - "which tend confuse us.\n", - "\n", - "The intercept can be interpreted as the expected value of our\n", - "target/output variables when all other predictors are set to zero.\n", - "Thus, if we cannot assume that the expected outputs/targets are zero\n", - "when all predictors are zero (the columns in the design matrix), it\n", - "may be a bad idea to implement a model which penalizes the intercept.\n", - "Furthermore, in for example Ridge and Lasso regression, the default solutions\n", - "from the library **Scikit-Learn** (when not shrinking $\\beta_0$) for the unknown parameters\n", - "$\\boldsymbol{\\beta}$, are derived under the assumption that both $\\boldsymbol{y}$ and\n", - "$\\boldsymbol{X}$ are zero centered, that is we subtract the mean values.\n", - "\n", - "If our predictors represent different scales, then it is important to\n", - "standardize the design matrix $\\boldsymbol{X}$ by subtracting the mean of each\n", - "column from the corresponding column and dividing the column with its\n", - "standard deviation. Most machine learning libraries do this as a default. This means that if you compare your code with the results from a given library,\n", - "the results may differ. \n", - "\n", - "The\n", - "[Standardscaler](https://scikit-learn.org/stable/modules/generated/sklearn.preprocessing.StandardScaler.html)\n", - "function in **Scikit-Learn** does this for us. For the data sets we\n", - "have been studying in our various examples, the data are in many cases\n", - "already scaled and there is no need to scale them. You as a user of different machine learning algorithms, should always perform a\n", - "survey of your data, with a critical assessment of them in case you need to scale the data.\n", - "\n", - "If you need to scale the data, not doing so will give an *unfair*\n", - "penalization of the parameters since their magnitude depends on the\n", - "scale of their corresponding predictor.\n", - "\n", - "Suppose as an example that you \n", - "you have an input variable given by the heights of different persons.\n", - "Human height might be measured in inches or meters or\n", - "kilometers. If measured in kilometers, a standard linear regression\n", - "model with this predictor would probably give a much bigger\n", - "coefficient term, than if measured in millimeters.\n", - "This can clearly lead to problems in evaluating the cost/loss functions.\n", - "\n", - "Keep in mind that when you transform your data set before training a model, the same transformation needs to be done\n", - "on your eventual new data set before making a prediction. If we translate this into a Python code, it would could be implemented as" - ] - }, - { - "cell_type": "code", - "execution_count": 7, - "id": "0e71daa5", - "metadata": { - "collapsed": false, - "editable": true - }, - "outputs": [], - "source": [ - "\"\"\"\n", - "#Model training, we compute the mean value of y and X\n", - "y_train_mean = np.mean(y_train)\n", - "X_train_mean = np.mean(X_train,axis=0)\n", - "X_train = X_train - X_train_mean\n", - "y_train = y_train - y_train_mean\n", - "\n", - "# The we fit our model with the training data\n", - "trained_model = some_model.fit(X_train,y_train)\n", - "\n", - "\n", - "#Model prediction, we need also to transform our data set used for the prediction.\n", - "X_test = X_test - X_train_mean #Use mean from training data\n", - "y_pred = trained_model(X_test)\n", - "y_pred = y_pred + y_train_mean\n", - "\"\"\"" - ] - }, - { - "cell_type": "markdown", - "id": "1f0eb0d0", - "metadata": { - "editable": true - }, - "source": [ - "Let us try to understand what this may imply mathematically when we\n", - "subtract the mean values, also known as *zero centering*. For\n", - "simplicity, we will focus on ordinary regression, as done in the above example.\n", - "\n", - "The cost/loss function for regression is" - ] - }, - { - "cell_type": "markdown", - "id": "2ffc4acb", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "C(\\beta_0, \\beta_1, ... , \\beta_{p-1}) = \\frac{1}{n}\\sum_{i=0}^{n} \\left(y_i - \\beta_0 - \\sum_{j=1}^{p-1} X_{ij}\\beta_j\\right)^2,.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "2511c028", - "metadata": { - "editable": true - }, - "source": [ - "Recall also that we use the squared value. This expression can lead to an\n", - "increased penalty for higher differences between predicted and\n", - "output/target values.\n", - "\n", - "What we have done is to single out the $\\beta_0$ term in the\n", - "definition of the mean squared error (MSE). The design matrix $X$\n", - "does in this case not contain any intercept column. When we take the\n", - "derivative with respect to $\\beta_0$, we want the derivative to obey" - ] - }, - { - "cell_type": "markdown", - "id": "908beb7f", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\frac{\\partial C}{\\partial \\beta_j} = 0,\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "5fae2a94", - "metadata": { - "editable": true - }, - "source": [ - "for all $j$. For $\\beta_0$ we have" - ] - }, - { - "cell_type": "markdown", - "id": "d7729a27", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\frac{\\partial C}{\\partial \\beta_0} = -\\frac{2}{n}\\sum_{i=0}^{n-1} \\left(y_i - \\beta_0 - \\sum_{j=1}^{p-1} X_{ij} \\beta_j\\right).\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "7fbb2ded", - "metadata": { - "editable": true - }, - "source": [ - "Multiplying away the constant $2/n$, we obtain" - ] - }, - { - "cell_type": "markdown", - "id": "8cef22ce", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\sum_{i=0}^{n-1} \\beta_0 = \\sum_{i=0}^{n-1}y_i - \\sum_{i=0}^{n-1} \\sum_{j=1}^{p-1} X_{ij} \\beta_j.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "c38ab3a0", - "metadata": { - "editable": true - }, - "source": [ - "Let us specialize first to the case where we have only two parameters $\\beta_0$ and $\\beta_1$.\n", - "Our result for $\\beta_0$ simplifies then to" - ] - }, - { - "cell_type": "markdown", - "id": "c47e7bbe", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "n\\beta_0 = \\sum_{i=0}^{n-1}y_i - \\sum_{i=0}^{n-1} X_{i1} \\beta_1.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "06962abd", - "metadata": { - "editable": true - }, - "source": [ - "We obtain then" - ] - }, - { - "cell_type": "markdown", - "id": "14c0a845", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\beta_0 = \\frac{1}{n}\\sum_{i=0}^{n-1}y_i - \\beta_1\\frac{1}{n}\\sum_{i=0}^{n-1} X_{i1}.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "5f50f223", - "metadata": { - "editable": true - }, - "source": [ - "If we define" - ] - }, - { - "cell_type": "markdown", - "id": "188ed44d", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\mu_{\\boldsymbol{x}_1}=\\frac{1}{n}\\sum_{i=0}^{n-1} X_{i1},\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "0b0db7b8", - "metadata": { - "editable": true - }, - "source": [ - "and the mean value of the outputs as" - ] - }, - { - "cell_type": "markdown", - "id": "e7550136", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\mu_y=\\frac{1}{n}\\sum_{i=0}^{n-1}y_i,\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "c7cc678d", - "metadata": { - "editable": true - }, - "source": [ - "we have" - ] - }, - { - "cell_type": "markdown", - "id": "9c9abcb2", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\beta_0 = \\mu_y - \\beta_1\\mu_{\\boldsymbol{x}_1}.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "2336bf55", - "metadata": { - "editable": true - }, - "source": [ - "In the general case with more parameters than $\\beta_0$ and $\\beta_1$, we have" - ] - }, - { - "cell_type": "markdown", - "id": "e0111655", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\beta_0 = \\frac{1}{n}\\sum_{i=0}^{n-1}y_i - \\frac{1}{n}\\sum_{i=0}^{n-1}\\sum_{j=1}^{p-1} X_{ij}\\beta_j.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "709c3af5", - "metadata": { - "editable": true - }, - "source": [ - "We can rewrite the latter equation as" - ] - }, - { - "cell_type": "markdown", - "id": "a9ed060b", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\beta_0 = \\frac{1}{n}\\sum_{i=0}^{n-1}y_i - \\sum_{j=1}^{p-1} \\mu_{\\boldsymbol{x}_j}\\beta_j,\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "deb61dec", - "metadata": { - "editable": true - }, - "source": [ - "where we have defined" - ] - }, - { - "cell_type": "markdown", - "id": "dc60f20f", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\mu_{\\boldsymbol{x}_j}=\\frac{1}{n}\\sum_{i=0}^{n-1} X_{ij},\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "b43a095d", - "metadata": { - "editable": true - }, - "source": [ - "the mean value for all elements of the column vector $\\boldsymbol{x}_j$.\n", - "\n", - "Replacing $y_i$ with $y_i - y_i - \\overline{\\boldsymbol{y}}$ and centering also our design matrix results in a cost function (in vector-matrix disguise)" - ] - }, - { - "cell_type": "markdown", - "id": "050949a2", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "C(\\boldsymbol{\\beta}) = (\\boldsymbol{\\tilde{y}} - \\tilde{X}\\boldsymbol{\\beta})^T(\\boldsymbol{\\tilde{y}} - \\tilde{X}\\boldsymbol{\\beta}).\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "7c288c56", - "metadata": { - "editable": true - }, - "source": [ - "If we minimize with respect to $\\boldsymbol{\\beta}$ we have then" - ] - }, - { - "cell_type": "markdown", - "id": "72d25a93", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\hat{\\boldsymbol{\\beta}} = (\\tilde{X}^T\\tilde{X})^{-1}\\tilde{X}^T\\boldsymbol{\\tilde{y}},\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "6e4fe379", - "metadata": { - "editable": true - }, - "source": [ - "where $\\boldsymbol{\\tilde{y}} = \\boldsymbol{y} - \\overline{\\boldsymbol{y}}$\n", - "and $\\tilde{X}_{ij} = X_{ij} - \\frac{1}{n}\\sum_{k=0}^{n-1}X_{kj}$.\n", - "\n", - "For Ridge regression we need to add $\\lambda \\boldsymbol{\\beta}^T\\boldsymbol{\\beta}$ to the cost function and get then" - ] - }, - { - "cell_type": "markdown", - "id": "b0f0e6e7", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\hat{\\boldsymbol{\\beta}} = (\\tilde{X}^T\\tilde{X} + \\lambda I)^{-1}\\tilde{X}^T\\boldsymbol{\\tilde{y}}.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "6cfb015d", - "metadata": { - "editable": true - }, - "source": [ - "What does this mean? And why do we insist on all this? Let us look at some examples.\n", - "\n", - "This code shows a simple first-order fit to a data set using the above transformed data, where we consider the role of the intercept first, by either excluding it or including it (*code example thanks to Øyvind Sigmundson Schøyen*). Here our scaling of the data is done by subtracting the mean values only.\n", - "Note also that we do not split the data into training and test." - ] - }, - { - "cell_type": "code", - "execution_count": 8, - "id": "bfbf5d1d", - "metadata": { - "collapsed": false, - "editable": true - }, - "outputs": [], - "source": [ - "import numpy as np\n", - "import matplotlib.pyplot as plt\n", - "\n", - "from sklearn.linear_model import LinearRegression\n", - "\n", - "\n", - "np.random.seed(2021)\n", - "\n", - "def MSE(y_data,y_model):\n", - " n = np.size(y_model)\n", - " return np.sum((y_data-y_model)**2)/n\n", - "\n", - "\n", - "def fit_beta(X, y):\n", - " return np.linalg.pinv(X.T @ X) @ X.T @ y\n", - "\n", - "\n", - "true_beta = [2, 0.5, 3.7]\n", - "\n", - "x = np.linspace(0, 1, 11)\n", - "y = np.sum(\n", - " np.asarray([x ** p * b for p, b in enumerate(true_beta)]), axis=0\n", - ") + 0.1 * np.random.normal(size=len(x))\n", - "\n", - "degree = 3\n", - "X = np.zeros((len(x), degree))\n", - "\n", - "# Include the intercept in the design matrix\n", - "for p in range(degree):\n", - " X[:, p] = x ** p\n", - "\n", - "beta = fit_beta(X, y)\n", - "\n", - "# Intercept is included in the design matrix\n", - "skl = LinearRegression(fit_intercept=False).fit(X, y)\n", - "\n", - "print(f\"True beta: {true_beta}\")\n", - "print(f\"Fitted beta: {beta}\")\n", - "print(f\"Sklearn fitted beta: {skl.coef_}\")\n", - "ypredictOwn = X @ beta\n", - "ypredictSKL = skl.predict(X)\n", - "print(f\"MSE with intercept column\")\n", - "print(MSE(y,ypredictOwn))\n", - "print(f\"MSE with intercept column from SKL\")\n", - "print(MSE(y,ypredictSKL))\n", - "\n", - "\n", - "plt.figure()\n", - "plt.scatter(x, y, label=\"Data\")\n", - "plt.plot(x, X @ beta, label=\"Fit\")\n", - "plt.plot(x, skl.predict(X), label=\"Sklearn (fit_intercept=False)\")\n", - "\n", - "\n", - "# Do not include the intercept in the design matrix\n", - "X = np.zeros((len(x), degree - 1))\n", - "\n", - "for p in range(degree - 1):\n", - " X[:, p] = x ** (p + 1)\n", - "\n", - "# Intercept is not included in the design matrix\n", - "skl = LinearRegression(fit_intercept=True).fit(X, y)\n", - "\n", - "# Use centered values for X and y when computing coefficients\n", - "y_offset = np.average(y, axis=0)\n", - "X_offset = np.average(X, axis=0)\n", - "\n", - "beta = fit_beta(X - X_offset, y - y_offset)\n", - "intercept = np.mean(y_offset - X_offset @ beta)\n", - "\n", - "print(f\"Manual intercept: {intercept}\")\n", - "print(f\"Fitted beta (wiothout intercept): {beta}\")\n", - "print(f\"Sklearn intercept: {skl.intercept_}\")\n", - "print(f\"Sklearn fitted beta (without intercept): {skl.coef_}\")\n", - "ypredictOwn = X @ beta\n", - "ypredictSKL = skl.predict(X)\n", - "print(f\"MSE with Manual intercept\")\n", - "print(MSE(y,ypredictOwn+intercept))\n", - "print(f\"MSE with Sklearn intercept\")\n", - "print(MSE(y,ypredictSKL))\n", - "\n", - "plt.plot(x, X @ beta + intercept, \"--\", label=\"Fit (manual intercept)\")\n", - "plt.plot(x, skl.predict(X), \"--\", label=\"Sklearn (fit_intercept=True)\")\n", - "plt.grid()\n", - "plt.legend()\n", - "\n", - "plt.show()" - ] - }, - { - "cell_type": "markdown", - "id": "7dc13bd7", - "metadata": { - "editable": true - }, - "source": [ - "The intercept is the value of our output/target variable\n", - "when all our features are zero and our function crosses the $y$-axis (for a one-dimensional case). \n", - "\n", - "Printing the MSE, we see first that both methods give the same MSE, as\n", - "they should. However, when we move to for example Ridge regression,\n", - "the way we treat the intercept may give a larger or smaller MSE,\n", - "meaning that the MSE can be penalized by the value of the\n", - "intercept. Not including the intercept in the fit, means that the\n", - "regularization term does not include $\\beta_0$. For different values\n", - "of $\\lambda$, this may lead to different MSE values. \n", - "\n", - "To remind the reader, the regularization term, with the intercept in Ridge regression, is given by" - ] - }, - { - "cell_type": "markdown", - "id": "3ce23f71", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\lambda \\vert\\vert \\boldsymbol{\\beta} \\vert\\vert_2^2 = \\lambda \\sum_{j=0}^{p-1}\\beta_j^2,\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "f34b4a50", - "metadata": { - "editable": true - }, - "source": [ - "but when we take out the intercept, this equation becomes" - ] - }, - { - "cell_type": "markdown", - "id": "6c535531", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\lambda \\vert\\vert \\boldsymbol{\\beta} \\vert\\vert_2^2 = \\lambda \\sum_{j=1}^{p-1}\\beta_j^2.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "dc9bd9cc", - "metadata": { - "editable": true - }, - "source": [ - "For Lasso regression we have" - ] - }, - { - "cell_type": "markdown", - "id": "b5911fe2", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\lambda \\vert\\vert \\boldsymbol{\\beta} \\vert\\vert_1 = \\lambda \\sum_{j=1}^{p-1}\\vert\\beta_j\\vert.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "4d4103f1", - "metadata": { - "editable": true - }, - "source": [ - "It means that, when scaling the design matrix and the outputs/targets,\n", - "by subtracting the mean values, we have an optimization problem which\n", - "is not penalized by the intercept. The MSE value can then be smaller\n", - "since it focuses only on the remaining quantities. If we however bring\n", - "back the intercept, we will get a MSE which then contains the\n", - "intercept.\n", - "\n", - "Armed with this wisdom, we attempt first to simply set the intercept equal to **False** in our implementation of Ridge regression for our well-known vanilla data set." - ] - }, - { - "cell_type": "code", - "execution_count": 9, - "id": "eecec942", - "metadata": { - "collapsed": false, - "editable": true - }, - "outputs": [], - "source": [ - "import numpy as np\n", - "import pandas as pd\n", - "import matplotlib.pyplot as plt\n", - "from sklearn.model_selection import train_test_split\n", - "from sklearn import linear_model\n", - "\n", - "def MSE(y_data,y_model):\n", - " n = np.size(y_model)\n", - " return np.sum((y_data-y_model)**2)/n\n", - "\n", - "\n", - "# A seed just to ensure that the random numbers are the same for every run.\n", - "# Useful for eventual debugging.\n", - "np.random.seed(3155)\n", - "\n", - "n = 100\n", - "x = np.random.rand(n)\n", - "y = np.exp(-x**2) + 1.5 * np.exp(-(x-2)**2)\n", - "\n", - "Maxpolydegree = 20\n", - "X = np.zeros((n,Maxpolydegree))\n", - "#We include explicitely the intercept column\n", - "for degree in range(Maxpolydegree):\n", - " X[:,degree] = x**degree\n", - "# We split the data in test and training data\n", - "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2)\n", - "\n", - "p = Maxpolydegree\n", - "I = np.eye(p,p)\n", - "# Decide which values of lambda to use\n", - "nlambdas = 6\n", - "MSEOwnRidgePredict = np.zeros(nlambdas)\n", - "MSERidgePredict = np.zeros(nlambdas)\n", - "lambdas = np.logspace(-4, 2, nlambdas)\n", - "for i in range(nlambdas):\n", - " lmb = lambdas[i]\n", - " OwnRidgeBeta = np.linalg.pinv(X_train.T @ X_train+lmb*I) @ X_train.T @ y_train\n", - " # Note: we include the intercept column and no scaling\n", - " RegRidge = linear_model.Ridge(lmb,fit_intercept=False)\n", - " RegRidge.fit(X_train,y_train)\n", - " # and then make the prediction\n", - " ytildeOwnRidge = X_train @ OwnRidgeBeta\n", - " ypredictOwnRidge = X_test @ OwnRidgeBeta\n", - " ytildeRidge = RegRidge.predict(X_train)\n", - " ypredictRidge = RegRidge.predict(X_test)\n", - " MSEOwnRidgePredict[i] = MSE(y_test,ypredictOwnRidge)\n", - " MSERidgePredict[i] = MSE(y_test,ypredictRidge)\n", - " print(\"Beta values for own Ridge implementation\")\n", - " print(OwnRidgeBeta)\n", - " print(\"Beta values for Scikit-Learn Ridge implementation\")\n", - " print(RegRidge.coef_)\n", - " print(\"MSE values for own Ridge implementation\")\n", - " print(MSEOwnRidgePredict[i])\n", - " print(\"MSE values for Scikit-Learn Ridge implementation\")\n", - " print(MSERidgePredict[i])\n", - "\n", - "# Now plot the results\n", - "plt.figure()\n", - "plt.plot(np.log10(lambdas), MSEOwnRidgePredict, 'r', label = 'MSE own Ridge Test')\n", - "plt.plot(np.log10(lambdas), MSERidgePredict, 'g', label = 'MSE Ridge Test')\n", - "\n", - "plt.xlabel('log10(lambda)')\n", - "plt.ylabel('MSE')\n", - "plt.legend()\n", - "plt.show()" - ] - }, - { - "cell_type": "markdown", - "id": "7d67706b", - "metadata": { - "editable": true - }, - "source": [ - "The results here agree when we force **Scikit-Learn**'s Ridge function to include the first column in our design matrix.\n", - "We see that the results agree very well. Here we have thus explicitely included the intercept column in the design matrix.\n", - "What happens if we do not include the intercept in our fit?\n", - "Let us see how we can change this code by zero centering." - ] - }, - { - "cell_type": "code", - "execution_count": 10, - "id": "598d20bd", - "metadata": { - "collapsed": false, - "editable": true - }, - "outputs": [], - "source": [ - "import numpy as np\n", - "import pandas as pd\n", - "import matplotlib.pyplot as plt\n", - "from sklearn.model_selection import train_test_split\n", - "from sklearn import linear_model\n", - "from sklearn.preprocessing import StandardScaler\n", - "\n", - "def MSE(y_data,y_model):\n", - " n = np.size(y_model)\n", - " return np.sum((y_data-y_model)**2)/n\n", - "# A seed just to ensure that the random numbers are the same for every run.\n", - "# Useful for eventual debugging.\n", - "np.random.seed(315)\n", - "\n", - "n = 100\n", - "x = np.random.rand(n)\n", - "y = np.exp(-x**2) + 1.5 * np.exp(-(x-2)**2)\n", - "\n", - "Maxpolydegree = 20\n", - "X = np.zeros((n,Maxpolydegree-1))\n", - "\n", - "for degree in range(1,Maxpolydegree): #No intercept column\n", - " X[:,degree-1] = x**(degree)\n", - "\n", - "# We split the data in test and training data\n", - "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2)\n", - "\n", - "#For our own implementation, we will need to deal with the intercept by centering the design matrix and the target variable\n", - "X_train_mean = np.mean(X_train,axis=0)\n", - "#Center by removing mean from each feature\n", - "X_train_scaled = X_train - X_train_mean \n", - "X_test_scaled = X_test - X_train_mean\n", - "#The model intercept (called y_scaler) is given by the mean of the target variable (IF X is centered)\n", - "#Remove the intercept from the training data.\n", - "y_scaler = np.mean(y_train) \n", - "y_train_scaled = y_train - y_scaler \n", - "\n", - "p = Maxpolydegree-1\n", - "I = np.eye(p,p)\n", - "# Decide which values of lambda to use\n", - "nlambdas = 6\n", - "MSEOwnRidgePredict = np.zeros(nlambdas)\n", - "MSERidgePredict = np.zeros(nlambdas)\n", - "\n", - "lambdas = np.logspace(-4, 2, nlambdas)\n", - "for i in range(nlambdas):\n", - " lmb = lambdas[i]\n", - " OwnRidgeBeta = np.linalg.pinv(X_train_scaled.T @ X_train_scaled+lmb*I) @ X_train_scaled.T @ (y_train_scaled)\n", - " intercept_ = y_scaler - X_train_mean@OwnRidgeBeta #The intercept can be shifted so the model can predict on uncentered data\n", - " #Add intercept to prediction\n", - " ypredictOwnRidge = X_test_scaled @ OwnRidgeBeta + y_scaler \n", - " RegRidge = linear_model.Ridge(lmb)\n", - " RegRidge.fit(X_train,y_train)\n", - " ypredictRidge = RegRidge.predict(X_test)\n", - " MSEOwnRidgePredict[i] = MSE(y_test,ypredictOwnRidge)\n", - " MSERidgePredict[i] = MSE(y_test,ypredictRidge)\n", - " print(\"Beta values for own Ridge implementation\")\n", - " print(OwnRidgeBeta) #Intercept is given by mean of target variable\n", - " print(\"Beta values for Scikit-Learn Ridge implementation\")\n", - " print(RegRidge.coef_)\n", - " print('Intercept from own implementation:')\n", - " print(intercept_)\n", - " print('Intercept from Scikit-Learn Ridge implementation')\n", - " print(RegRidge.intercept_)\n", - " print(\"MSE values for own Ridge implementation\")\n", - " print(MSEOwnRidgePredict[i])\n", - " print(\"MSE values for Scikit-Learn Ridge implementation\")\n", - " print(MSERidgePredict[i])\n", - "\n", - "\n", - "# Now plot the results\n", - "plt.figure()\n", - "plt.plot(np.log10(lambdas), MSEOwnRidgePredict, 'b--', label = 'MSE own Ridge Test')\n", - "plt.plot(np.log10(lambdas), MSERidgePredict, 'g--', label = 'MSE SL Ridge Test')\n", - "plt.xlabel('log10(lambda)')\n", - "plt.ylabel('MSE')\n", - "plt.legend()\n", - "plt.show()" - ] - }, - { - "cell_type": "markdown", - "id": "cec80003", - "metadata": { - "editable": true - }, - "source": [ - "We see here, when compared to the code which includes explicitely the\n", - "intercept column, that our MSE value is actually smaller. This is\n", - "because the regularization term does not include the intercept value\n", - "$\\beta_0$ in the fitting. This applies to Lasso regularization as\n", - "well. It means that our optimization is now done only with the\n", - "centered matrix and/or vector that enter the fitting procedure." - ] - }, - { - "cell_type": "markdown", - "id": "16cdcffb", - "metadata": { - "editable": true - }, - "source": [ - "## Test Function for what happens with OLS, Ridge and Lasso\n", - "\n", - "Hitherto we have discussed Ridge and Lasso regression in terms of a\n", - "linear analysis. This may to many of you feel rather technical and\n", - "perhaps not that intuitive. The question is whether we can develop a\n", - "more intuitive way of understanding what Ridge and Lasso express.\n", - "\n", - "Before we proceed let us perform a Ridge, Lasso and OLS analysis of a polynomial fit. \n", - "\n", - "We will play around with a study of the values for the optimal\n", - "parameters $\\boldsymbol{\\beta}$ using OLS, Ridge and Lasso regression. For\n", - "OLS, you will notice as function of the noise and polynomial degree,\n", - "that the parameters $\\beta$ will fluctuate from order to order in the\n", - "polynomial fit and that for larger and larger polynomial degrees of freedom, the parameters will tend to increase in value for OLS.\n", - "\n", - "For Ridge and Lasso regression, the higher order parameters will typically be reduced, providing thereby less fluctuations from one order to another one." - ] - }, - { - "cell_type": "code", - "execution_count": 11, - "id": "e04dce1d", - "metadata": { - "collapsed": false, - "editable": true - }, - "outputs": [], - "source": [ - "import numpy as np\n", - "import matplotlib.pyplot as plt\n", - "from sklearn.model_selection import train_test_split\n", - "from sklearn import linear_model\n", - "\n", - "def R2(y_data, y_model):\n", - " return 1 - np.sum((y_data - y_model) ** 2) / np.sum((y_data - np.mean(y_data)) ** 2)\n", - "def MSE(y_data,y_model):\n", - " n = np.size(y_model)\n", - " return np.sum((y_data-y_model)**2)/n\n", - "\n", - "# Make data set.\n", - "n = 10000\n", - "x = np.random.rand(n)\n", - "y = np.exp(-x**2) + 1.5 * np.exp(-(x-2)**2)+ np.random.randn(n)\n", - "\n", - "Maxpolydegree = 5\n", - "X = np.zeros((len(x),Maxpolydegree))\n", - "X[:,0] = 1.0\n", - "\n", - "\n", - "for polydegree in range(1,Maxpolydegree):\n", - " X[:,polydegree] = x**(polydegree)\n", - "\n", - "# We split the data in test and training data\n", - "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2)\n", - "\n", - "# matrix inversion to find beta\n", - "OLSbeta = np.linalg.pinv(X_train.T @ X_train) @ X_train.T @ y_train\n", - "print(OLSbeta)\n", - "ypredictOLS = X_test @ OLSbeta\n", - "print(\"Test MSE OLS\")\n", - "print(MSE(y_test,ypredictOLS))\n", - "# Repeat now for Lasso and Ridge regression and various values of the regularization parameter using Scikit-Learn\n", - "# Decide which values of lambda to use\n", - "nlambdas = 4\n", - "MSERidgePredict = np.zeros(nlambdas)\n", - "MSELassoPredict = np.zeros(nlambdas)\n", - "lambdas = np.logspace(-3, 1, nlambdas)\n", - "for i in range(nlambdas):\n", - " lmb = lambdas[i]\n", - " # Make the fit using Ridge and Lasso\n", - " RegRidge = linear_model.Ridge(lmb,fit_intercept=False)\n", - " RegRidge.fit(X_train,y_train)\n", - " RegLasso = linear_model.Lasso(lmb,fit_intercept=False)\n", - " RegLasso.fit(X_train,y_train)\n", - " # and then make the prediction\n", - " ypredictRidge = RegRidge.predict(X_test)\n", - " ypredictLasso = RegLasso.predict(X_test)\n", - " # Compute the MSE and print it\n", - " MSERidgePredict[i] = MSE(y_test,ypredictRidge)\n", - " MSELassoPredict[i] = MSE(y_test,ypredictLasso)\n", - " print(lmb,RegRidge.coef_)\n", - " print(lmb,RegLasso.coef_)\n", - "# Now plot the results\n", - "plt.figure()\n", - "plt.plot(np.log10(lambdas), MSERidgePredict, 'b', label = 'MSE Ridge Test')\n", - "plt.plot(np.log10(lambdas), MSELassoPredict, 'r', label = 'MSE Lasso Test')\n", - "plt.xlabel('log10(lambda)')\n", - "plt.ylabel('MSE')\n", - "plt.legend()\n", - "plt.show()" - ] - }, - { - "cell_type": "markdown", - "id": "2ae202c3", - "metadata": { - "editable": true - }, - "source": [ - "How can we understand this?" - ] - }, - { - "cell_type": "markdown", - "id": "4186f9f0", - "metadata": { - "editable": true - }, - "source": [ - "## Linking the regression analysis with a statistical interpretation\n", - "\n", - "We will now couple the discussions of ordinary least squares, Ridge\n", - "and Lasso regression with a statistical interpretation, that is we\n", - "move from a linear algebra analysis to a statistical analysis. In\n", - "particular, we will focus on what the regularization terms can result\n", - "in. We will amongst other things show that the regularization\n", - "parameter can reduce considerably the variance of the parameters\n", - "$\\beta$.\n", - "\n", - "The\n", - "advantage of doing linear regression is that we actually end up with\n", - "analytical expressions for several statistical quantities. \n", - "Standard least squares and Ridge regression allow us to\n", - "derive quantities like the variance and other expectation values in a\n", - "rather straightforward way.\n", - "\n", - "It is assumed that $\\varepsilon_i\n", - "\\sim \\mathcal{N}(0, \\sigma^2)$ and the $\\varepsilon_{i}$ are\n", - "independent, i.e.:" - ] - }, - { - "cell_type": "markdown", - "id": "7293d2ab", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\begin{align*} \n", - "\\mbox{Cov}(\\varepsilon_{i_1},\n", - "\\varepsilon_{i_2}) & = \\left\\{ \\begin{array}{lcc} \\sigma^2 & \\mbox{if}\n", - "& i_1 = i_2, \\\\ 0 & \\mbox{if} & i_1 \\not= i_2. \\end{array} \\right.\n", - "\\end{align*}\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "efee3703", - "metadata": { - "editable": true - }, - "source": [ - "The randomness of $\\varepsilon_i$ implies that\n", - "$\\mathbf{y}_i$ is also a random variable. In particular,\n", - "$\\mathbf{y}_i$ is normally distributed, because $\\varepsilon_i \\sim\n", - "\\mathcal{N}(0, \\sigma^2)$ and $\\mathbf{X}_{i,\\ast} \\, \\boldsymbol{\\beta}$ is a\n", - "non-random scalar. To specify the parameters of the distribution of\n", - "$\\mathbf{y}_i$ we need to calculate its first two moments. \n", - "\n", - "Recall that $\\boldsymbol{X}$ is a matrix of dimensionality $n\\times p$. The\n", - "notation above $\\mathbf{X}_{i,\\ast}$ means that we are looking at the\n", - "row number $i$ and perform a sum over all values $p$." - ] - }, - { - "cell_type": "markdown", - "id": "85d2303d", - "metadata": { - "editable": true - }, - "source": [ - "## Assumptions made\n", - "\n", - "The assumption we have made here can be summarized as (and this is going to be useful when we discuss the bias-variance trade off)\n", - "that there exists a function $f(\\boldsymbol{x})$ and a normal distributed error $\\boldsymbol{\\varepsilon}\\sim \\mathcal{N}(0, \\sigma^2)$\n", - "which describe our data" - ] - }, - { - "cell_type": "markdown", - "id": "c1a189c0", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\boldsymbol{y} = f(\\boldsymbol{x})+\\boldsymbol{\\varepsilon}\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "0b63e61f", - "metadata": { - "editable": true - }, - "source": [ - "We approximate this function with our model from the solution of the linear regression equations, that is our\n", - "function $f$ is approximated by $\\boldsymbol{\\tilde{y}}$ where we want to minimize $(\\boldsymbol{y}-\\boldsymbol{\\tilde{y}})^2$, our MSE, with" - ] - }, - { - "cell_type": "markdown", - "id": "14acfe14", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\boldsymbol{\\tilde{y}} = \\boldsymbol{X}\\boldsymbol{\\beta}.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "681408c6", - "metadata": { - "editable": true - }, - "source": [ - "## Expectation value and variance\n", - "\n", - "We can calculate the expectation value of $\\boldsymbol{y}$ for a given element $i$" - ] - }, - { - "cell_type": "markdown", - "id": "d956e33c", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\begin{align*} \n", - "\\mathbb{E}(y_i) & =\n", - "\\mathbb{E}(\\mathbf{X}_{i, \\ast} \\, \\boldsymbol{\\beta}) + \\mathbb{E}(\\varepsilon_i)\n", - "\\, \\, \\, = \\, \\, \\, \\mathbf{X}_{i, \\ast} \\, \\beta, \n", - "\\end{align*}\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "992bee5b", - "metadata": { - "editable": true - }, - "source": [ - "while\n", - "its variance is" - ] - }, - { - "cell_type": "markdown", - "id": "fd75d1af", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\begin{align*} \\mbox{Var}(y_i) & = \\mathbb{E} \\{ [y_i\n", - "- \\mathbb{E}(y_i)]^2 \\} \\, \\, \\, = \\, \\, \\, \\mathbb{E} ( y_i^2 ) -\n", - "[\\mathbb{E}(y_i)]^2 \\\\ & = \\mathbb{E} [ ( \\mathbf{X}_{i, \\ast} \\,\n", - "\\beta + \\varepsilon_i )^2] - ( \\mathbf{X}_{i, \\ast} \\, \\boldsymbol{\\beta})^2 \\\\ &\n", - "= \\mathbb{E} [ ( \\mathbf{X}_{i, \\ast} \\, \\boldsymbol{\\beta})^2 + 2 \\varepsilon_i\n", - "\\mathbf{X}_{i, \\ast} \\, \\boldsymbol{\\beta} + \\varepsilon_i^2 ] - ( \\mathbf{X}_{i,\n", - "\\ast} \\, \\beta)^2 \\\\ & = ( \\mathbf{X}_{i, \\ast} \\, \\boldsymbol{\\beta})^2 + 2\n", - "\\mathbb{E}(\\varepsilon_i) \\mathbf{X}_{i, \\ast} \\, \\boldsymbol{\\beta} +\n", - "\\mathbb{E}(\\varepsilon_i^2 ) - ( \\mathbf{X}_{i, \\ast} \\, \\boldsymbol{\\beta})^2 \n", - "\\\\ & = \\mathbb{E}(\\varepsilon_i^2 ) \\, \\, \\, = \\, \\, \\,\n", - "\\mbox{Var}(\\varepsilon_i) \\, \\, \\, = \\, \\, \\, \\sigma^2. \n", - "\\end{align*}\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "f702411d", - "metadata": { - "editable": true - }, - "source": [ - "Hence, $y_i \\sim \\mathcal{N}( \\mathbf{X}_{i, \\ast} \\, \\boldsymbol{\\beta}, \\sigma^2)$, that is $\\boldsymbol{y}$ follows a normal distribution with \n", - "mean value $\\boldsymbol{X}\\boldsymbol{\\beta}$ and variance $\\sigma^2$ (not be confused with the singular values of the SVD)." - ] - }, - { - "cell_type": "markdown", - "id": "b86e729d", - "metadata": { - "editable": true - }, - "source": [ - "## Expectation value and variance for $\\boldsymbol{\\beta}$\n", - "\n", - "With the OLS expressions for the optimal parameters $\\boldsymbol{\\hat{\\beta}}$ we can evaluate the expectation value" - ] - }, - { - "cell_type": "markdown", - "id": "5af888a2", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\mathbb{E}(\\boldsymbol{\\hat{\\beta}}) = \\mathbb{E}[ (\\mathbf{X}^{\\top} \\mathbf{X})^{-1}\\mathbf{X}^{T} \\mathbf{Y}]=(\\mathbf{X}^{T} \\mathbf{X})^{-1}\\mathbf{X}^{T} \\mathbb{E}[ \\mathbf{Y}]=(\\mathbf{X}^{T} \\mathbf{X})^{-1} \\mathbf{X}^{T}\\mathbf{X}\\boldsymbol{\\beta}=\\boldsymbol{\\beta}.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "3d21a65e", - "metadata": { - "editable": true - }, - "source": [ - "This means that the estimator of the regression parameters is unbiased.\n", - "\n", - "We can also calculate the variance\n", - "\n", - "The variance of the optimal value $\\boldsymbol{\\hat{\\beta}}$ is" - ] - }, - { - "cell_type": "markdown", - "id": "7d8043ab", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\begin{eqnarray*}\n", - "\\mbox{Var}(\\boldsymbol{\\hat{\\beta}}) & = & \\mathbb{E} \\{ [\\boldsymbol{\\beta} - \\mathbb{E}(\\boldsymbol{\\beta})] [\\boldsymbol{\\beta} - \\mathbb{E}(\\boldsymbol{\\beta})]^{T} \\}\n", - "\\\\\n", - "& = & \\mathbb{E} \\{ [(\\mathbf{X}^{T} \\mathbf{X})^{-1} \\, \\mathbf{X}^{T} \\mathbf{Y} - \\boldsymbol{\\beta}] \\, [(\\mathbf{X}^{T} \\mathbf{X})^{-1} \\, \\mathbf{X}^{T} \\mathbf{Y} - \\boldsymbol{\\beta}]^{T} \\}\n", - "\\\\\n", - "% & = & \\mathbb{E} \\{ [(\\mathbf{X}^{T} \\mathbf{X})^{-1} \\, \\mathbf{X}^{T} \\mathbf{Y}] \\, [(\\mathbf{X}^{T} \\mathbf{X})^{-1} \\, \\mathbf{X}^{T} \\mathbf{Y}]^{T} \\} - \\boldsymbol{\\beta} \\, \\boldsymbol{\\beta}^{T}\n", - "% \\\\\n", - "% & = & \\mathbb{E} \\{ (\\mathbf{X}^{T} \\mathbf{X})^{-1} \\, \\mathbf{X}^{T} \\mathbf{Y} \\, \\mathbf{Y}^{T} \\, \\mathbf{X} \\, (\\mathbf{X}^{T} \\mathbf{X})^{-1} \\} - \\boldsymbol{\\beta} \\, \\boldsymbol{\\beta}^{T}\n", - "% \\\\\n", - "& = & (\\mathbf{X}^{T} \\mathbf{X})^{-1} \\, \\mathbf{X}^{T} \\, \\mathbb{E} \\{ \\mathbf{Y} \\, \\mathbf{Y}^{T} \\} \\, \\mathbf{X} \\, (\\mathbf{X}^{T} \\mathbf{X})^{-1} - \\boldsymbol{\\beta} \\, \\boldsymbol{\\beta}^{T}\n", - "\\\\\n", - "& = & (\\mathbf{X}^{T} \\mathbf{X})^{-1} \\, \\mathbf{X}^{T} \\, \\{ \\mathbf{X} \\, \\boldsymbol{\\beta} \\, \\boldsymbol{\\beta}^{T} \\, \\mathbf{X}^{T} + \\sigma^2 \\} \\, \\mathbf{X} \\, (\\mathbf{X}^{T} \\mathbf{X})^{-1} - \\boldsymbol{\\beta} \\, \\boldsymbol{\\beta}^{T}\n", - "% \\\\\n", - "% & = & (\\mathbf{X}^T \\mathbf{X})^{-1} \\, \\mathbf{X}^T \\, \\mathbf{X} \\, \\boldsymbol{\\beta} \\, \\boldsymbol{\\beta}^T \\, \\mathbf{X}^T \\, \\mathbf{X} \\, (\\mathbf{X}^T % \\mathbf{X})^{-1}\n", - "% \\\\\n", - "% & & + \\, \\, \\sigma^2 \\, (\\mathbf{X}^T \\mathbf{X})^{-1} \\, \\mathbf{X}^T \\, \\mathbf{X} \\, (\\mathbf{X}^T \\mathbf{X})^{-1} - \\boldsymbol{\\beta} \\boldsymbol{\\beta}^T\n", - "\\\\\n", - "& = & \\boldsymbol{\\beta} \\, \\boldsymbol{\\beta}^{T} + \\sigma^2 \\, (\\mathbf{X}^{T} \\mathbf{X})^{-1} - \\boldsymbol{\\beta} \\, \\boldsymbol{\\beta}^{T}\n", - "\\, \\, \\, = \\, \\, \\, \\sigma^2 \\, (\\mathbf{X}^{T} \\mathbf{X})^{-1},\n", - "\\end{eqnarray*}\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "4a126ec7", - "metadata": { - "editable": true - }, - "source": [ - "where we have used that $\\mathbb{E} (\\mathbf{Y} \\mathbf{Y}^{T}) =\n", - "\\mathbf{X} \\, \\boldsymbol{\\beta} \\, \\boldsymbol{\\beta}^{T} \\, \\mathbf{X}^{T} +\n", - "\\sigma^2 \\, \\mathbf{I}_{nn}$. From $\\mbox{Var}(\\boldsymbol{\\beta}) = \\sigma^2\n", - "\\, (\\mathbf{X}^{T} \\mathbf{X})^{-1}$, one obtains an estimate of the\n", - "variance of the estimate of the $j$-th regression coefficient:\n", - "$\\boldsymbol{\\sigma}^2 (\\boldsymbol{\\beta}_j ) = \\boldsymbol{\\sigma}^2 [(\\mathbf{X}^{T} \\mathbf{X})^{-1}]_{jj} $. This may be used to\n", - "construct a confidence interval for the estimates.\n", - "\n", - "In a similar way, we can obtain analytical expressions for say the\n", - "expectation values of the parameters $\\boldsymbol{\\beta}$ and their variance\n", - "when we employ Ridge regression, allowing us again to define a confidence interval. \n", - "\n", - "It is rather straightforward to show that" - ] - }, - { - "cell_type": "markdown", - "id": "7287992a", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\mathbb{E} \\big[ \\boldsymbol{\\beta}^{\\mathrm{Ridge}} \\big]=(\\mathbf{X}^{T} \\mathbf{X} + \\lambda \\mathbf{I}_{pp})^{-1} (\\mathbf{X}^{\\top} \\mathbf{X})\\boldsymbol{\\beta}^{\\mathrm{OLS}}.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "2803f793", - "metadata": { - "editable": true - }, - "source": [ - "We see clearly that \n", - "$\\mathbb{E} \\big[ \\boldsymbol{\\beta}^{\\mathrm{Ridge}} \\big] \\not= \\boldsymbol{\\beta}^{\\mathrm{OLS}}$ for any $\\lambda > 0$. We say then that the ridge estimator is biased.\n", - "\n", - "We can also compute the variance as" - ] - }, - { - "cell_type": "markdown", - "id": "d7443c20", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\mbox{Var}[\\boldsymbol{\\beta}^{\\mathrm{Ridge}}]=\\sigma^2[ \\mathbf{X}^{T} \\mathbf{X} + \\lambda \\mathbf{I} ]^{-1} \\mathbf{X}^{T} \\mathbf{X} \\{ [ \\mathbf{X}^{\\top} \\mathbf{X} + \\lambda \\mathbf{I} ]^{-1}\\}^{T},\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "a0d32eb0", - "metadata": { - "editable": true - }, - "source": [ - "and it is easy to see that if the parameter $\\lambda$ goes to infinity then the variance of Ridge parameters $\\boldsymbol{\\beta}$ goes to zero. \n", - "\n", - "With this, we can compute the difference" - ] - }, - { - "cell_type": "markdown", - "id": "cbd0143e", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\mbox{Var}[\\boldsymbol{\\beta}^{\\mathrm{OLS}}]-\\mbox{Var}(\\boldsymbol{\\beta}^{\\mathrm{Ridge}})=\\sigma^2 [ \\mathbf{X}^{T} \\mathbf{X} + \\lambda \\mathbf{I} ]^{-1}[ 2\\lambda\\mathbf{I} + \\lambda^2 (\\mathbf{X}^{T} \\mathbf{X})^{-1} ] \\{ [ \\mathbf{X}^{T} \\mathbf{X} + \\lambda \\mathbf{I} ]^{-1}\\}^{T}.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "e6de88a4", - "metadata": { - "editable": true - }, - "source": [ - "The difference is non-negative definite since each component of the\n", - "matrix product is non-negative definite. \n", - "This means the variance we obtain with the standard OLS will always for $\\lambda > 0$ be larger than the variance of $\\boldsymbol{\\beta}$ obtained with the Ridge estimator. This has interesting consequences when we discuss the so-called bias-variance trade-off below." - ] - }, - { - "cell_type": "markdown", - "id": "55630c9f", - "metadata": { - "editable": true - }, - "source": [ - "## Deriving OLS from a probability distribution\n", - "\n", - "Our basic assumption when we derived the OLS equations was to assume\n", - "that our output is determined by a given continuous function\n", - "$f(\\boldsymbol{x})$ and a random noise $\\boldsymbol{\\epsilon}$ given by the normal\n", - "distribution with zero mean value and an undetermined variance\n", - "$\\sigma^2$.\n", - "\n", - "We found above that the outputs $\\boldsymbol{y}$ have a mean value given by\n", - "$\\boldsymbol{X}\\hat{\\boldsymbol{\\beta}}$ and variance $\\sigma^2$. Since the entries to\n", - "the design matrix are not stochastic variables, we can assume that the\n", - "probability distribution of our targets is also a normal distribution\n", - "but now with mean value $\\boldsymbol{X}\\hat{\\boldsymbol{\\beta}}$. This means that a\n", - "single output $y_i$ is given by the Gaussian distribution" - ] - }, - { - "cell_type": "markdown", - "id": "745e6352", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "y_i\\sim \\mathcal{N}(\\boldsymbol{X}_{i,*}\\boldsymbol{\\beta}, \\sigma^2)=\\frac{1}{\\sqrt{2\\pi\\sigma^2}}\\exp{\\left[-\\frac{(y_i-\\boldsymbol{X}_{i,*}\\boldsymbol{\\beta})^2}{2\\sigma^2}\\right]}.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "4ec8c116", - "metadata": { - "editable": true - }, - "source": [ - "## Independent and Identically Distrubuted (iid)\n", - "\n", - "We assume now that the various $y_i$ values are stochastically distributed according to the above Gaussian distribution. \n", - "We define this distribution as" - ] - }, - { - "cell_type": "markdown", - "id": "f92be14e", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "p(y_i, \\boldsymbol{X}\\vert\\boldsymbol{\\beta})=\\frac{1}{\\sqrt{2\\pi\\sigma^2}}\\exp{\\left[-\\frac{(y_i-\\boldsymbol{X}_{i,*}\\boldsymbol{\\beta})^2}{2\\sigma^2}\\right]},\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "edbdd556", - "metadata": { - "editable": true - }, - "source": [ - "which reads as finding the likelihood of an event $y_i$ with the input variables $\\boldsymbol{X}$ given the parameters (to be determined) $\\boldsymbol{\\beta}$.\n", - "\n", - "Since these events are assumed to be independent and identicall distributed we can build the probability distribution function (PDF) for all possible event $\\boldsymbol{y}$ as the product of the single events, that is we have" - ] - }, - { - "cell_type": "markdown", - "id": "6a6903ca", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "p(\\boldsymbol{y},\\boldsymbol{X}\\vert\\boldsymbol{\\beta})=\\prod_{i=0}^{n-1}\\frac{1}{\\sqrt{2\\pi\\sigma^2}}\\exp{\\left[-\\frac{(y_i-\\boldsymbol{X}_{i,*}\\boldsymbol{\\beta})^2}{2\\sigma^2}\\right]}=\\prod_{i=0}^{n-1}p(y_i,\\boldsymbol{X}\\vert\\boldsymbol{\\beta}).\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "57680896", - "metadata": { - "editable": true - }, - "source": [ - "We will write this in a more compact form reserving $\\boldsymbol{D}$ for the domain of events, including the ouputs (targets) and the inputs. That is\n", - "in case we have a simple one-dimensional input and output case" - ] - }, - { - "cell_type": "markdown", - "id": "9309640f", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\boldsymbol{D}=[(x_0,y_0), (x_1,y_1),\\dots, (x_{n-1},y_{n-1})].\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "67fb3df9", - "metadata": { - "editable": true - }, - "source": [ - "In the more general case the various inputs should be replaced by the possible features represented by the input data set $\\boldsymbol{X}$. \n", - "We can now rewrite the above probability as" - ] - }, - { - "cell_type": "markdown", - "id": "894f0fb7", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "p(\\boldsymbol{D}\\vert\\boldsymbol{\\beta})=\\prod_{i=0}^{n-1}\\frac{1}{\\sqrt{2\\pi\\sigma^2}}\\exp{\\left[-\\frac{(y_i-\\boldsymbol{X}_{i,*}\\boldsymbol{\\beta})^2}{2\\sigma^2}\\right]}.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "13f3f705", - "metadata": { - "editable": true - }, - "source": [ - "It is a conditional probability (see below) and reads as the likelihood of a domain of events $\\boldsymbol{D}$ given a set of parameters $\\boldsymbol{\\beta}$." - ] - }, - { - "cell_type": "markdown", - "id": "6bf3edfa", - "metadata": { - "editable": true - }, - "source": [ - "## Maximum Likelihood Estimation (MLE)\n", - "\n", - "In statistics, maximum likelihood estimation (MLE) is a method of\n", - "estimating the parameters of an assumed probability distribution,\n", - "given some observed data. This is achieved by maximizing a likelihood\n", - "function so that, under the assumed statistical model, the observed\n", - "data is the most probable. \n", - "\n", - "We will assume here that our events are given by the above Gaussian\n", - "distribution and we will determine the optimal parameters $\\beta$ by\n", - "maximizing the above PDF. However, computing the derivatives of a\n", - "product function is cumbersome and can easily lead to overflow and/or\n", - "underflowproblems, with potentials for loss of numerical precision.\n", - "\n", - "In practice, it is more convenient to maximize the logarithm of the\n", - "PDF because it is a monotonically increasing function of the argument.\n", - "Alternatively, and this will be our option, we will minimize the\n", - "negative of the logarithm since this is a monotonically decreasing\n", - "function.\n", - "\n", - "Note also that maximization/minimization of the logarithm of the PDF\n", - "is equivalent to the maximization/minimization of the function itself." - ] - }, - { - "cell_type": "markdown", - "id": "be42ac0c", - "metadata": { - "editable": true - }, - "source": [ - "## A new Cost Function\n", - "\n", - "We could now define a new cost function to minimize, namely the negative logarithm of the above PDF" - ] - }, - { - "cell_type": "markdown", - "id": "b6fbab08", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "C(\\boldsymbol{\\beta}=-\\log{\\prod_{i=0}^{n-1}p(y_i,\\boldsymbol{X}\\vert\\boldsymbol{\\beta})}=-\\sum_{i=0}^{n-1}\\log{p(y_i,\\boldsymbol{X}\\vert\\boldsymbol{\\beta})},\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "33ef1983", - "metadata": { - "editable": true - }, - "source": [ - "which becomes" - ] - }, - { - "cell_type": "markdown", - "id": "7d6504da", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "C(\\boldsymbol{\\beta}=\\frac{n}{2}\\log{2\\pi\\sigma^2}+\\frac{\\vert\\vert (\\boldsymbol{y}-\\boldsymbol{X}\\boldsymbol{\\beta})\\vert\\vert_2^2}{2\\sigma^2}.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "03d8775c", - "metadata": { - "editable": true - }, - "source": [ - "Taking the derivative of the *new* cost function with respect to the parameters $\\beta$ we recognize our familiar OLS equation, namely" - ] - }, - { - "cell_type": "markdown", - "id": "176d1dab", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\boldsymbol{X}^T\\left(\\boldsymbol{y}-\\boldsymbol{X}\\boldsymbol{\\beta}\\right) =0,\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "e20e33bf", - "metadata": { - "editable": true - }, - "source": [ - "which leads to the well-known OLS equation for the optimal paramters $\\beta$" - ] - }, - { - "cell_type": "markdown", - "id": "94f73eae", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\hat{\\boldsymbol{\\beta}}^{\\mathrm{OLS}}=\\left(\\boldsymbol{X}^T\\boldsymbol{X}\\right)^{-1}\\boldsymbol{X}^T\\boldsymbol{y}!\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "f5d2cf20", - "metadata": { - "editable": true - }, - "source": [ - "Before we make a similar analysis for Ridge and Lasso regression, we need a short reminder on statistics." - ] - }, - { - "cell_type": "markdown", - "id": "c32b8f92", - "metadata": { - "editable": true - }, - "source": [ - "## More basic Statistics and Bayes' theorem\n", - "\n", - "A central theorem in statistics is Bayes' theorem. This theorem plays a similar role as the good old Pythagoras' theorem in geometry.\n", - "Bayes' theorem is extremely simple to derive. But to do so we need some basic axioms from statistics.\n", - "\n", - "Assume we have two domains of events $X=[x_0,x_1,\\dots,x_{n-1}]$ and $Y=[y_0,y_1,\\dots,y_{n-1}]$.\n", - "\n", - "We define also the likelihood for $X$ and $Y$ as $p(X)$ and $p(Y)$ respectively.\n", - "The likelihood of a specific event $x_i$ (or $y_i$) is then written as $p(X=x_i)$ or just $p(x_i)=p_i$. \n", - "\n", - "**Union of events is given by.**" - ] - }, - { - "cell_type": "markdown", - "id": "a3779fd2", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "p(X \\cup Y)= p(X)+p(Y)-p(X \\cap Y).\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "37e13b18", - "metadata": { - "editable": true - }, - "source": [ - "**The product rule (aka joint probability) is given by.**" - ] - }, - { - "cell_type": "markdown", - "id": "bd8b41f0", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "p(X \\cup Y)= p(X,Y)= p(X\\vert Y)p(Y)=p(Y\\vert X)p(X),\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "71b22e26", - "metadata": { - "editable": true - }, - "source": [ - "where we read $p(X\\vert Y)$ as the likelihood of obtaining $X$ given $Y$.\n", - "\n", - "If we have independent events then $p(X,Y)=p(X)p(Y)$." - ] - }, - { - "cell_type": "markdown", - "id": "5f6645d2", - "metadata": { - "editable": true - }, - "source": [ - "## Marginal Probability\n", - "\n", - "The marginal probability is defined in terms of only one of the set of variables $X,Y$. For a discrete probability we have" - ] - }, - { - "cell_type": "markdown", - "id": "7349fe65", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "p(X)=\\sum_{i=0}^{n-1}p(X,Y=y_i)=\\sum_{i=0}^{n-1}p(X\\vert Y=y_i)p(Y=y_i)=\\sum_{i=0}^{n-1}p(X\\vert y_i)p(y_i).\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "a6205b4f", - "metadata": { - "editable": true - }, - "source": [ - "## Conditional Probability\n", - "\n", - "The conditional probability, if $p(Y) > 0$, is" - ] - }, - { - "cell_type": "markdown", - "id": "43cb130d", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "p(X\\vert Y)= \\frac{p(X,Y)}{p(Y)}=\\frac{p(X,Y)}{\\sum_{i=0}^{n-1}p(Y\\vert X=x_i)p(x_i)}.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "9d8f1813", - "metadata": { - "editable": true - }, - "source": [ - "## Bayes' Theorem\n", - "\n", - "If we combine the conditional probability with the marginal probability and the standard product rule, we have" - ] - }, - { - "cell_type": "markdown", - "id": "d2746770", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "p(X\\vert Y)= \\frac{p(X,Y)}{p(Y)},\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "f3659d1d", - "metadata": { - "editable": true - }, - "source": [ - "which we can rewrite as" - ] - }, - { - "cell_type": "markdown", - "id": "8dfd9ec7", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "p(X\\vert Y)= \\frac{p(X,Y)}{\\sum_{i=0}^{n-1}p(Y\\vert X=x_i)p(x_i)}=\\frac{p(Y\\vert X)p(X)}{\\sum_{i=0}^{n-1}p(Y\\vert X=x_i)p(x_i)},\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "3f247ad1", - "metadata": { - "editable": true - }, - "source": [ - "which is Bayes' theorem. It allows us to evaluate the uncertainty in in $X$ after we have observed $Y$. We can easily interchange $X$ with $Y$." - ] - }, - { - "cell_type": "markdown", - "id": "a2615306", - "metadata": { - "editable": true - }, - "source": [ - "## Interpretations of Bayes' Theorem\n", - "\n", - "The quantity $p(Y\\vert X)$ on the right-hand side of the theorem is\n", - "evaluated for the observed data $Y$ and can be viewed as a function of\n", - "the parameter space represented by $X$. This function is not\n", - "necesseraly normalized and is normally called the likelihood function.\n", - "\n", - "The function $p(X)$ on the right hand side is called the prior while the function on the left hand side is the called the posterior probability. The denominator on the right hand side serves as a normalization factor for the posterior distribution.\n", - "\n", - "Let us try to illustrate Bayes' theorem through an example." - ] - }, - { - "cell_type": "markdown", - "id": "91eae9e8", - "metadata": { - "editable": true - }, - "source": [ - "## Example of Usage of Bayes' theorem\n", - "\n", - "Let us suppose that you are undergoing a series of mammography scans in\n", - "order to rule out possible breast cancer cases. We define the\n", - "sensitivity for a positive event by the variable $X$. It takes binary\n", - "values with $X=1$ representing a positive event and $X=0$ being a\n", - "negative event. We reserve $Y$ as a classification parameter for\n", - "either a negative or a positive breast cancer confirmation. (Short note on wordings: positive here means having breast cancer, although none of us would consider this being a positive thing).\n", - "\n", - "We let $Y=1$ represent the the case of having breast cancer and $Y=0$ as not.\n", - "\n", - "Let us assume that if you have breast cancer, the test will be positive with a probability of $0.8$, that is we have" - ] - }, - { - "cell_type": "markdown", - "id": "76fe1c46", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "p(X=1\\vert Y=1) =0.8.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "397d9768", - "metadata": { - "editable": true - }, - "source": [ - "This obviously sounds scary since many would conclude that if the test is positive, there is a likelihood of $80\\%$ for having cancer.\n", - "It is however not correct, as the following Bayesian analysis shows." - ] - }, - { - "cell_type": "markdown", - "id": "f2c701f5", - "metadata": { - "editable": true - }, - "source": [ - "## Doing it correctly\n", - "\n", - "If we look at various national surveys on breast cancer, the general likelihood of developing breast cancer is a very small number.\n", - "Let us assume that the prior probability in the population as a whole is" - ] - }, - { - "cell_type": "markdown", - "id": "0fdb2639", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "p(Y=1) =0.004.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "f9ae9f95", - "metadata": { - "editable": true - }, - "source": [ - "We need also to account for the fact that the test may produce a false positive result (false alarm). Let us here assume that we have" - ] - }, - { - "cell_type": "markdown", - "id": "a681f1dc", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "p(X=1\\vert Y=0) =0.1.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "4d2c6030", - "metadata": { - "editable": true - }, - "source": [ - "Using Bayes' theorem we can then find the posterior probability that the person has breast cancer in case of a positive test, that is we can compute" - ] - }, - { - "cell_type": "markdown", - "id": "67a1c582", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "p(Y=1\\vert X=1)=\\frac{p(X=1\\vert Y=1)p(Y=1)}{p(X=1\\vert Y=1)p(Y=1)+p(X=1\\vert Y=0)p(Y=0)}=\\frac{0.8\\times 0.004}{0.8\\times 0.004+0.1\\times 0.996}=0.031.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "969f368b", - "metadata": { - "editable": true - }, - "source": [ - "That is, in case of a positive test, there is only a $3\\%$ chance of having breast cancer!" - ] - }, - { - "cell_type": "markdown", - "id": "356a70c0", - "metadata": { - "editable": true - }, - "source": [ - "## Bayes' Theorem and Ridge and Lasso Regression\n", - "\n", - "Using Bayes' theorem we can gain a better intuition about Ridge and Lasso regression. \n", - "\n", - "For ordinary least squares we postulated that the maximum likelihood for the doamin of events $\\boldsymbol{D}$ (one-dimensional case)" - ] - }, - { - "cell_type": "markdown", - "id": "fa653f05", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\boldsymbol{D}=[(x_0,y_0), (x_1,y_1),\\dots, (x_{n-1},y_{n-1})],\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "d5dd1081", - "metadata": { - "editable": true - }, - "source": [ - "is given by" - ] - }, - { - "cell_type": "markdown", - "id": "731b21d4", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "p(\\boldsymbol{D}\\vert\\boldsymbol{\\beta})=\\prod_{i=0}^{n-1}\\frac{1}{\\sqrt{2\\pi\\sigma^2}}\\exp{\\left[-\\frac{(y_i-\\boldsymbol{X}_{i,*}\\boldsymbol{\\beta})^2}{2\\sigma^2}\\right]}.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "362ae4e2", - "metadata": { - "editable": true - }, - "source": [ - "In Bayes' theorem this function plays the role of the so-called likelihood. We could now ask the question what is the posterior probability of a parameter set $\\boldsymbol{\\beta}$ given a domain of events $\\boldsymbol{D}$? That is, how can we define the posterior probability" - ] - }, - { - "cell_type": "markdown", - "id": "8ba56ac5", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "p(\\boldsymbol{\\beta}\\vert\\boldsymbol{D}).\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "658e6364", - "metadata": { - "editable": true - }, - "source": [ - "Bayes' theorem comes to our rescue here since (omitting the normalization constant)" - ] - }, - { - "cell_type": "markdown", - "id": "28d6553d", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "p(\\boldsymbol{\\beta}\\vert\\boldsymbol{D})\\propto p(\\boldsymbol{D}\\vert\\boldsymbol{\\beta})p(\\boldsymbol{\\beta}).\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "8f4ec5f0", - "metadata": { - "editable": true - }, - "source": [ - "We have a model for $p(\\boldsymbol{D}\\vert\\boldsymbol{\\beta})$ but need one for the **prior** $p(\\boldsymbol{\\beta}$!" - ] - }, - { - "cell_type": "markdown", - "id": "e72b34ca", - "metadata": { - "editable": true - }, - "source": [ - "## Ridge and Bayes\n", - "\n", - "With the posterior probability defined by a likelihood which we have\n", - "already modeled and an unknown prior, we are now ready to make\n", - "additional models for the prior.\n", - "\n", - "We can, based on our discussions of the variance of $\\boldsymbol{\\beta}$ and the mean value, assume that the prior for the values $\\boldsymbol{\\beta}$ is given by a Gaussian with mean value zero and variance $\\tau^2$, that is" - ] - }, - { - "cell_type": "markdown", - "id": "0e656652", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "p(\\boldsymbol{\\beta})=\\prod_{j=0}^{p-1}\\exp{\\left(-\\frac{\\beta_j^2}{2\\tau^2}\\right)}.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "57606d08", - "metadata": { - "editable": true - }, - "source": [ - "Our posterior probability becomes then (omitting the normalization factor which is just a constant)" - ] - }, - { - "cell_type": "markdown", - "id": "cf40e3a9", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "p(\\boldsymbol{\\beta\\vert\\boldsymbol{D})}=\\prod_{i=0}^{n-1}\\frac{1}{\\sqrt{2\\pi\\sigma^2}}\\exp{\\left[-\\frac{(y_i-\\boldsymbol{X}_{i,*}\\boldsymbol{\\beta})^2}{2\\sigma^2}\\right]}\\prod_{j=0}^{p-1}\\exp{\\left(-\\frac{\\beta_j^2}{2\\tau^2}\\right)}.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "65038f20", - "metadata": { - "editable": true - }, - "source": [ - "We can now optimize this quantity with respect to $\\boldsymbol{\\beta}$. As we\n", - "did for OLS, this is most conveniently done by taking the negative\n", - "logarithm of the posterior probability. Doing so and leaving out the\n", - "constants terms that do not depend on $\\beta$, we have" - ] - }, - { - "cell_type": "markdown", - "id": "deb9890c", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "C(\\boldsymbol{\\beta})=\\frac{\\vert\\vert (\\boldsymbol{y}-\\boldsymbol{X}\\boldsymbol{\\beta})\\vert\\vert_2^2}{2\\sigma^2}+\\frac{1}{2\\tau^2}\\vert\\vert\\boldsymbol{\\beta}\\vert\\vert_2^2,\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "1a844813", - "metadata": { - "editable": true - }, - "source": [ - "and replacing $1/2\\tau^2$ with $\\lambda$ we have" - ] - }, - { - "cell_type": "markdown", - "id": "a32e4148", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "C(\\boldsymbol{\\beta})=\\frac{\\vert\\vert (\\boldsymbol{y}-\\boldsymbol{X}\\boldsymbol{\\beta})\\vert\\vert_2^2}{2\\sigma^2}+\\lambda\\vert\\vert\\boldsymbol{\\beta}\\vert\\vert_2^2,\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "4050a8ed", - "metadata": { - "editable": true - }, - "source": [ - "which is our Ridge cost function! Nice, isn't it?" - ] - }, - { - "cell_type": "markdown", - "id": "ec31e4e2", - "metadata": { - "editable": true - }, - "source": [ - "## Lasso and Bayes\n", - "\n", - "To derive the Lasso cost function, we simply replace the Gaussian prior with an exponential distribution ([Laplace in this case](https://en.wikipedia.org/wiki/Laplace_distribution)) with zero mean value, that is" - ] - }, - { - "cell_type": "markdown", - "id": "f872c397", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "p(\\boldsymbol{\\beta})=\\prod_{j=0}^{p-1}\\exp{\\left(-\\frac{\\vert\\beta_j\\vert}{\\tau}\\right)}.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "e8eeb2e5", - "metadata": { - "editable": true - }, - "source": [ - "Our posterior probability becomes then (omitting the normalization factor which is just a constant)" - ] - }, - { - "cell_type": "markdown", - "id": "54d2f39d", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "p(\\boldsymbol{\\beta}\\vert\\boldsymbol{D})=\\prod_{i=0}^{n-1}\\frac{1}{\\sqrt{2\\pi\\sigma^2}}\\exp{\\left[-\\frac{(y_i-\\boldsymbol{X}_{i,*}\\boldsymbol{\\beta})^2}{2\\sigma^2}\\right]}\\prod_{j=0}^{p-1}\\exp{\\left(-\\frac{\\vert\\beta_j\\vert}{\\tau}\\right)}.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "54cbc3a8", - "metadata": { - "editable": true - }, - "source": [ - "Taking the negative\n", - "logarithm of the posterior probability and leaving out the\n", - "constants terms that do not depend on $\\beta$, we have" - ] - }, - { - "cell_type": "markdown", - "id": "7ee728b6", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "C(\\boldsymbol{\\beta}=\\frac{\\vert\\vert (\\boldsymbol{y}-\\boldsymbol{X}\\boldsymbol{\\beta})\\vert\\vert_2^2}{2\\sigma^2}+\\frac{1}{\\tau}\\vert\\vert\\boldsymbol{\\beta}\\vert\\vert_1,\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "00e9a0eb", - "metadata": { - "editable": true - }, - "source": [ - "and replacing $1/\\tau$ with $\\lambda$ we have" - ] - }, - { - "cell_type": "markdown", - "id": "50f72b22", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "C(\\boldsymbol{\\beta}=\\frac{\\vert\\vert (\\boldsymbol{y}-\\boldsymbol{X}\\boldsymbol{\\beta})\\vert\\vert_2^2}{2\\sigma^2}+\\lambda\\vert\\vert\\boldsymbol{\\beta}\\vert\\vert_1,\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "d53fea2e", - "metadata": { - "editable": true - }, - "source": [ - "which is our Lasso cost function!" - ] - } - ], - "metadata": {}, - "nbformat": 4, - "nbformat_minor": 5 -} diff --git a/doc/LectureNotes/week37.ipynb b/doc/LectureNotes/week37.ipynb deleted file mode 100644 index d31eb4073..000000000 --- a/doc/LectureNotes/week37.ipynb +++ /dev/null @@ -1,3538 +0,0 @@ -{ - "cells": [ - { - "cell_type": "markdown", - "id": "9e3d6c33", - "metadata": { - "editable": true - }, - "source": [ - "\n", - "" - ] - }, - { - "cell_type": "markdown", - "id": "6c4bf45e", - "metadata": { - "editable": true - }, - "source": [ - "# Week 37: Statistical interpretations and Resampling Methods\n", - "**Morten Hjorth-Jensen**, Department of Physics, University of Oslo and Department of Physics and Astronomy and Facility for Rare Isotope Beams, Michigan State University\n", - "\n", - "Date: **Sep 18, 2023**\n", - "\n", - "Copyright 1999-2023, Morten Hjorth-Jensen. Released under CC Attribution-NonCommercial 4.0 license\n", - "\n", - "" - ] - }, - { - "cell_type": "markdown", - "id": "af4e71fa", - "metadata": { - "editable": true - }, - "source": [ - "## Plans for week 37\n", - "\n", - "**Material for the active learning sessions on Tuesday and Wednesday.**\n", - "\n", - " * Lecture from last week on calculations of expectation values\n", - "\n", - " * Exercise for week 37\n", - "\n", - " * Work on project 1\n", - "\n", - " * See also additional note on scaling (jupyter-notebook) sent separately. This will be discussed during the first hour of each session. This note is added at the end of these slides.\n", - "\n", - " * For more discussions of Ridge regression and calculation of averages, [Wessel van Wieringen's](https://arxiv.org/abs/1509.09169) article is highly recommended.\n", - "\n", - " \n", - "**Material for the lecture on Thursday September 7.**\n", - "\n", - " * [Video of Lecture](https://youtu.be/YOBBr_toYxc)\n", - "\n", - " * [Whiteboard notes](https://github.com/CompPhysics/MachineLearning/blob/master/doc/HandWrittenNotes/2023/NotesSep14.pdf)\n", - "\n", - " * Resampling techniques, Bootstrap and cross validation and bias-variance tradeoff\n", - "\n", - " * Statistical interpretation of Ridge and Lasso regression\n", - "\n", - " * Readings and Videos:\n", - "\n", - " * Hastie et al Chapter 7, here we recommend 7.1-7.5 and 7.10 (cross-validation) and 7.11 (bootstrap). \n", - "\n", - " * [Video on cross validation](https://www.youtube.com/watch?v=fSytzGwwBVw)\n", - "\n", - " * [Video on Bootstrapping](https://www.youtube.com/watch?v=Xz0x-8-cgaQ)\n", - "\n", - " * [Video on bias-variance tradeoff](https://www.youtube.com/watch?v=EuBBz3bI-aA)" - ] - }, - { - "cell_type": "markdown", - "id": "a30b83bd", - "metadata": { - "editable": true - }, - "source": [ - "## Material from last week and relevant for the weekly exercises" - ] - }, - { - "cell_type": "markdown", - "id": "603e5939", - "metadata": { - "editable": true - }, - "source": [ - "## Linking the regression analysis with a statistical interpretation\n", - "\n", - "We will now couple the discussions of ordinary least squares, Ridge\n", - "and Lasso regression with a statistical interpretation, that is we\n", - "move from a linear algebra analysis to a statistical analysis. In\n", - "particular, we will focus on what the regularization terms can result\n", - "in. We will amongst other things show that the regularization\n", - "parameter can reduce considerably the variance of the parameters\n", - "$\\beta$.\n", - "\n", - "The\n", - "advantage of doing linear regression is that we actually end up with\n", - "analytical expressions for several statistical quantities. \n", - "Standard least squares and Ridge regression allow us to\n", - "derive quantities like the variance and other expectation values in a\n", - "rather straightforward way.\n", - "\n", - "It is assumed that $\\varepsilon_i\n", - "\\sim \\mathcal{N}(0, \\sigma^2)$ and the $\\varepsilon_{i}$ are\n", - "independent, i.e.:" - ] - }, - { - "cell_type": "markdown", - "id": "c6d1b655", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\begin{align*} \n", - "\\mbox{Cov}(\\varepsilon_{i_1},\n", - "\\varepsilon_{i_2}) & = \\left\\{ \\begin{array}{lcc} \\sigma^2 & \\mbox{if}\n", - "& i_1 = i_2, \\\\ 0 & \\mbox{if} & i_1 \\not= i_2. \\end{array} \\right.\n", - "\\end{align*}\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "0ac423bb", - "metadata": { - "editable": true - }, - "source": [ - "The randomness of $\\varepsilon_i$ implies that\n", - "$\\mathbf{y}_i$ is also a random variable. In particular,\n", - "$\\mathbf{y}_i$ is normally distributed, because $\\varepsilon_i \\sim\n", - "\\mathcal{N}(0, \\sigma^2)$ and $\\mathbf{X}_{i,\\ast} \\, \\boldsymbol{\\beta}$ is a\n", - "non-random scalar. To specify the parameters of the distribution of\n", - "$\\mathbf{y}_i$ we need to calculate its first two moments. \n", - "\n", - "Recall that $\\boldsymbol{X}$ is a matrix of dimensionality $n\\times p$. The\n", - "notation above $\\mathbf{X}_{i,\\ast}$ means that we are looking at the\n", - "row number $i$ and perform a sum over all values $p$." - ] - }, - { - "cell_type": "markdown", - "id": "a321bc7e", - "metadata": { - "editable": true - }, - "source": [ - "## Assumptions made\n", - "\n", - "The assumption we have made here can be summarized as (and this is going to be useful when we discuss the bias-variance trade off)\n", - "that there exists a function $f(\\boldsymbol{x})$ and a normal distributed error $\\boldsymbol{\\varepsilon}\\sim \\mathcal{N}(0, \\sigma^2)$\n", - "which describe our data" - ] - }, - { - "cell_type": "markdown", - "id": "a058a44f", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\boldsymbol{y} = f(\\boldsymbol{x})+\\boldsymbol{\\varepsilon}\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "7ca5aeb9", - "metadata": { - "editable": true - }, - "source": [ - "We approximate this function with our model from the solution of the linear regression equations, that is our\n", - "function $f$ is approximated by $\\boldsymbol{\\tilde{y}}$ where we want to minimize $(\\boldsymbol{y}-\\boldsymbol{\\tilde{y}})^2$, our MSE, with" - ] - }, - { - "cell_type": "markdown", - "id": "7a064201", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\boldsymbol{\\tilde{y}} = \\boldsymbol{X}\\boldsymbol{\\beta}.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "fc70ead9", - "metadata": { - "editable": true - }, - "source": [ - "## Expectation value and variance\n", - "\n", - "We can calculate the expectation value of $\\boldsymbol{y}$ for a given element $i$" - ] - }, - { - "cell_type": "markdown", - "id": "9beae550", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\begin{align*} \n", - "\\mathbb{E}(y_i) & =\n", - "\\mathbb{E}(\\mathbf{X}_{i, \\ast} \\, \\boldsymbol{\\beta}) + \\mathbb{E}(\\varepsilon_i)\n", - "\\, \\, \\, = \\, \\, \\, \\mathbf{X}_{i, \\ast} \\, \\beta, \n", - "\\end{align*}\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "c0ab7cc5", - "metadata": { - "editable": true - }, - "source": [ - "while\n", - "its variance is" - ] - }, - { - "cell_type": "markdown", - "id": "a6900e18", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\begin{align*} \\mbox{Var}(y_i) & = \\mathbb{E} \\{ [y_i\n", - "- \\mathbb{E}(y_i)]^2 \\} \\, \\, \\, = \\, \\, \\, \\mathbb{E} ( y_i^2 ) -\n", - "[\\mathbb{E}(y_i)]^2 \\\\ & = \\mathbb{E} [ ( \\mathbf{X}_{i, \\ast} \\,\n", - "\\beta + \\varepsilon_i )^2] - ( \\mathbf{X}_{i, \\ast} \\, \\boldsymbol{\\beta})^2 \\\\ &\n", - "= \\mathbb{E} [ ( \\mathbf{X}_{i, \\ast} \\, \\boldsymbol{\\beta})^2 + 2 \\varepsilon_i\n", - "\\mathbf{X}_{i, \\ast} \\, \\boldsymbol{\\beta} + \\varepsilon_i^2 ] - ( \\mathbf{X}_{i,\n", - "\\ast} \\, \\beta)^2 \\\\ & = ( \\mathbf{X}_{i, \\ast} \\, \\boldsymbol{\\beta})^2 + 2\n", - "\\mathbb{E}(\\varepsilon_i) \\mathbf{X}_{i, \\ast} \\, \\boldsymbol{\\beta} +\n", - "\\mathbb{E}(\\varepsilon_i^2 ) - ( \\mathbf{X}_{i, \\ast} \\, \\boldsymbol{\\beta})^2 \n", - "\\\\ & = \\mathbb{E}(\\varepsilon_i^2 ) \\, \\, \\, = \\, \\, \\,\n", - "\\mbox{Var}(\\varepsilon_i) \\, \\, \\, = \\, \\, \\, \\sigma^2. \n", - "\\end{align*}\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "fe9b0d2f", - "metadata": { - "editable": true - }, - "source": [ - "Hence, $y_i \\sim \\mathcal{N}( \\mathbf{X}_{i, \\ast} \\, \\boldsymbol{\\beta}, \\sigma^2)$, that is $\\boldsymbol{y}$ follows a normal distribution with \n", - "mean value $\\boldsymbol{X}\\boldsymbol{\\beta}$ and variance $\\sigma^2$ (not be confused with the singular values of the SVD)." - ] - }, - { - "cell_type": "markdown", - "id": "be36f9aa", - "metadata": { - "editable": true - }, - "source": [ - "## Expectation value and variance for $\\boldsymbol{\\beta}$\n", - "\n", - "With the OLS expressions for the optimal parameters $\\boldsymbol{\\hat{\\beta}}$ we can evaluate the expectation value" - ] - }, - { - "cell_type": "markdown", - "id": "3717afd4", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\mathbb{E}(\\boldsymbol{\\hat{\\beta}}) = \\mathbb{E}[ (\\mathbf{X}^{\\top} \\mathbf{X})^{-1}\\mathbf{X}^{T} \\mathbf{Y}]=(\\mathbf{X}^{T} \\mathbf{X})^{-1}\\mathbf{X}^{T} \\mathbb{E}[ \\mathbf{Y}]=(\\mathbf{X}^{T} \\mathbf{X})^{-1} \\mathbf{X}^{T}\\mathbf{X}\\boldsymbol{\\beta}=\\boldsymbol{\\beta}.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "f75bbc6c", - "metadata": { - "editable": true - }, - "source": [ - "This means that the estimator of the regression parameters is unbiased.\n", - "\n", - "We can also calculate the variance\n", - "\n", - "The variance of the optimal value $\\boldsymbol{\\hat{\\beta}}$ is" - ] - }, - { - "cell_type": "markdown", - "id": "501aab1c", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\begin{eqnarray*}\n", - "\\mbox{Var}(\\boldsymbol{\\hat{\\beta}}) & = & \\mathbb{E} \\{ [\\boldsymbol{\\beta} - \\mathbb{E}(\\boldsymbol{\\beta})] [\\boldsymbol{\\beta} - \\mathbb{E}(\\boldsymbol{\\beta})]^{T} \\}\n", - "\\\\\n", - "& = & \\mathbb{E} \\{ [(\\mathbf{X}^{T} \\mathbf{X})^{-1} \\, \\mathbf{X}^{T} \\mathbf{y} - \\boldsymbol{\\beta}] \\, [(\\mathbf{X}^{T} \\mathbf{X})^{-1} \\, \\mathbf{X}^{T} \\mathbf{y} - \\boldsymbol{\\beta}]^{T} \\}\n", - "\\\\\n", - "% & = & \\mathbb{E} \\{ [(\\mathbf{X}^{T} \\mathbf{X})^{-1} \\, \\mathbf{X}^{T} \\mathbf{y}] \\, [(\\mathbf{X}^{T} \\mathbf{X})^{-1} \\, \\mathbf{X}^{T} \\mathbf{y}]^{T} \\} - \\boldsymbol{\\beta} \\, \\boldsymbol{\\beta}^{T}\n", - "% \\\\\n", - "% & = & \\mathbb{E} \\{ (\\mathbf{X}^{T} \\mathbf{X})^{-1} \\, \\mathbf{X}^{T} \\mathbf{y} \\, \\mathbf{y}^{T} \\, \\mathbf{X} \\, (\\mathbf{X}^{T} \\mathbf{X})^{-1} \\} - \\boldsymbol{\\beta} \\, \\boldsymbol{\\beta}^{T}\n", - "% \\\\\n", - "& = & (\\mathbf{X}^{T} \\mathbf{X})^{-1} \\, \\mathbf{X}^{T} \\, \\mathbb{E} \\{ \\mathbf{y} \\, \\mathbf{y}^{T} \\} \\, \\mathbf{X} \\, (\\mathbf{X}^{T} \\mathbf{X})^{-1} - \\boldsymbol{\\beta} \\, \\boldsymbol{\\beta}^{T}\n", - "\\\\\n", - "& = & (\\mathbf{X}^{T} \\mathbf{X})^{-1} \\, \\mathbf{X}^{T} \\, \\{ \\mathbf{X} \\, \\boldsymbol{\\beta} \\, \\boldsymbol{\\beta}^{T} \\, \\mathbf{X}^{T} + \\sigma^2 \\} \\, \\mathbf{X} \\, (\\mathbf{X}^{T} \\mathbf{X})^{-1} - \\boldsymbol{\\beta} \\, \\boldsymbol{\\beta}^{T}\n", - "% \\\\\n", - "% & = & (\\mathbf{X}^T \\mathbf{X})^{-1} \\, \\mathbf{X}^T \\, \\mathbf{X} \\, \\boldsymbol{\\beta} \\, \\boldsymbol{\\beta}^T \\, \\mathbf{X}^T \\, \\mathbf{X} \\, (\\mathbf{X}^T % \\mathbf{X})^{-1}\n", - "% \\\\\n", - "% & & + \\, \\, \\sigma^2 \\, (\\mathbf{X}^T \\mathbf{X})^{-1} \\, \\mathbf{X}^T \\, \\mathbf{X} \\, (\\mathbf{X}^T \\mathbf{X})^{-1} - \\boldsymbol{\\beta} \\boldsymbol{\\beta}^T\n", - "\\\\\n", - "& = & \\boldsymbol{\\beta} \\, \\boldsymbol{\\beta}^{T} + \\sigma^2 \\, (\\mathbf{X}^{T} \\mathbf{X})^{-1} - \\boldsymbol{\\beta} \\, \\boldsymbol{\\beta}^{T}\n", - "\\, \\, \\, = \\, \\, \\, \\sigma^2 \\, (\\mathbf{X}^{T} \\mathbf{X})^{-1},\n", - "\\end{eqnarray*}\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "882b7267", - "metadata": { - "editable": true - }, - "source": [ - "where we have used that $\\mathbb{E} (\\mathbf{y} \\mathbf{y}^{T}) =\n", - "\\mathbf{X} \\, \\boldsymbol{\\beta} \\, \\boldsymbol{\\beta}^{T} \\, \\mathbf{X}^{T} +\n", - "\\sigma^2 \\, \\mathbf{I}_{nn}$. From $\\mbox{Var}(\\boldsymbol{\\beta}) = \\sigma^2\n", - "\\, (\\mathbf{X}^{T} \\mathbf{X})^{-1}$, one obtains an estimate of the\n", - "variance of the estimate of the $j$-th regression coefficient:\n", - "$\\boldsymbol{\\sigma}^2 (\\boldsymbol{\\beta}_j ) = \\boldsymbol{\\sigma}^2 [(\\mathbf{X}^{T} \\mathbf{X})^{-1}]_{jj} $. This may be used to\n", - "construct a confidence interval for the estimates.\n", - "\n", - "In a similar way, we can obtain analytical expressions for say the\n", - "expectation values of the parameters $\\boldsymbol{\\beta}$ and their variance\n", - "when we employ Ridge regression, allowing us again to define a confidence interval. \n", - "\n", - "It is rather straightforward to show that" - ] - }, - { - "cell_type": "markdown", - "id": "b7993235", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\mathbb{E} \\big[ \\hat{\\boldsymbol{\\beta}}^{\\mathrm{Ridge}} \\big]=(\\mathbf{X}^{T} \\mathbf{X} + \\lambda \\mathbf{I}_{pp})^{-1} (\\mathbf{X}^{\\top} \\mathbf{X})\\boldsymbol{\\beta}.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "27dfe1f9", - "metadata": { - "editable": true - }, - "source": [ - "We see clearly that \n", - "$\\mathbb{E} \\big[ \\hat{\\boldsymbol{\\beta}}^{\\mathrm{Ridge}} \\big] \\not= \\hat{\\boldsymbol{\\beta}}^{\\mathrm{OLS}}$ for any $\\lambda > 0$.\n", - "\n", - "We can also compute the variance as" - ] - }, - { - "cell_type": "markdown", - "id": "d1ccc9c9", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\mbox{Var}[\\hat{\\boldsymbol{\\beta}}^{\\mathrm{Ridge}}]=\\sigma^2[ \\mathbf{X}^{T} \\mathbf{X} + \\lambda \\mathbf{I} ]^{-1} \\mathbf{X}^{T} \\mathbf{X} \\{ [ \\mathbf{X}^{\\top} \\mathbf{X} + \\lambda \\mathbf{I} ]^{-1}\\}^{T},\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "4b51caf8", - "metadata": { - "editable": true - }, - "source": [ - "and it is easy to see that if the parameter $\\lambda$ goes to infinity then the variance of Ridge parameters $\\boldsymbol{\\beta}$ goes to zero. \n", - "\n", - "With this, we can compute the difference" - ] - }, - { - "cell_type": "markdown", - "id": "6b6c2347", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\mbox{Var}[\\hat{\\boldsymbol{\\beta}}^{\\mathrm{OLS}}]-\\mbox{Var}(\\hat{\\boldsymbol{\\beta}}^{\\mathrm{Ridge}})=\\sigma^2 [ \\mathbf{X}^{T} \\mathbf{X} + \\lambda \\mathbf{I} ]^{-1}[ 2\\lambda\\mathbf{I} + \\lambda^2 (\\mathbf{X}^{T} \\mathbf{X})^{-1} ] \\{ [ \\mathbf{X}^{T} \\mathbf{X} + \\lambda \\mathbf{I} ]^{-1}\\}^{T}.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "7b622b81", - "metadata": { - "editable": true - }, - "source": [ - "The difference is non-negative definite since each component of the\n", - "matrix product is non-negative definite. \n", - "This means the variance we obtain with the standard OLS will always for $\\lambda > 0$ be larger than the variance of $\\boldsymbol{\\beta}$ obtained with the Ridge estimator. This has interesting consequences when we discuss the so-called bias-variance trade-off below. \n", - "\n", - "For more discussions of Ridge regression and calculation of averages, [Wessel van Wieringen's](https://arxiv.org/abs/1509.09169) article is highly recommended." - ] - }, - { - "cell_type": "markdown", - "id": "bc281f57", - "metadata": { - "editable": true - }, - "source": [ - "## Material for lecture Thursday September 14" - ] - }, - { - "cell_type": "markdown", - "id": "b1262baf", - "metadata": { - "editable": true - }, - "source": [ - "## Deriving OLS from a probability distribution\n", - "\n", - "Our basic assumption when we derived the OLS equations was to assume\n", - "that our output is determined by a given continuous function\n", - "$f(\\boldsymbol{x})$ and a random noise $\\boldsymbol{\\epsilon}$ given by the normal\n", - "distribution with zero mean value and an undetermined variance\n", - "$\\sigma^2$.\n", - "\n", - "We found above that the outputs $\\boldsymbol{y}$ have a mean value given by\n", - "$\\boldsymbol{X}\\hat{\\boldsymbol{\\beta}}$ and variance $\\sigma^2$. Since the entries to\n", - "the design matrix are not stochastic variables, we can assume that the\n", - "probability distribution of our targets is also a normal distribution\n", - "but now with mean value $\\boldsymbol{X}\\hat{\\boldsymbol{\\beta}}$. This means that a\n", - "single output $y_i$ is given by the Gaussian distribution" - ] - }, - { - "cell_type": "markdown", - "id": "a14cfe86", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "y_i\\sim \\mathcal{N}(\\boldsymbol{X}_{i,*}\\boldsymbol{\\beta}, \\sigma^2)=\\frac{1}{\\sqrt{2\\pi\\sigma^2}}\\exp{\\left[-\\frac{(y_i-\\boldsymbol{X}_{i,*}\\boldsymbol{\\beta})^2}{2\\sigma^2}\\right]}.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "56fe0849", - "metadata": { - "editable": true - }, - "source": [ - "## Independent and Identically Distrubuted (iid)\n", - "\n", - "We assume now that the various $y_i$ values are stochastically distributed according to the above Gaussian distribution. \n", - "We define this distribution as" - ] - }, - { - "cell_type": "markdown", - "id": "afed97f2", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "p(y_i, \\boldsymbol{X}\\vert\\boldsymbol{\\beta})=\\frac{1}{\\sqrt{2\\pi\\sigma^2}}\\exp{\\left[-\\frac{(y_i-\\boldsymbol{X}_{i,*}\\boldsymbol{\\beta})^2}{2\\sigma^2}\\right]},\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "e4b5884d", - "metadata": { - "editable": true - }, - "source": [ - "which reads as finding the likelihood of an event $y_i$ with the input variables $\\boldsymbol{X}$ given the parameters (to be determined) $\\boldsymbol{\\beta}$.\n", - "\n", - "Since these events are assumed to be independent and identicall distributed we can build the probability distribution function (PDF) for all possible event $\\boldsymbol{y}$ as the product of the single events, that is we have" - ] - }, - { - "cell_type": "markdown", - "id": "0c949c06", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "p(\\boldsymbol{y},\\boldsymbol{X}\\vert\\boldsymbol{\\beta})=\\prod_{i=0}^{n-1}\\frac{1}{\\sqrt{2\\pi\\sigma^2}}\\exp{\\left[-\\frac{(y_i-\\boldsymbol{X}_{i,*}\\boldsymbol{\\beta})^2}{2\\sigma^2}\\right]}=\\prod_{i=0}^{n-1}p(y_i,\\boldsymbol{X}\\vert\\boldsymbol{\\beta}).\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "113e3658", - "metadata": { - "editable": true - }, - "source": [ - "We will write this in a more compact form reserving $\\boldsymbol{D}$ for the domain of events, including the ouputs (targets) and the inputs. That is\n", - "in case we have a simple one-dimensional input and output case" - ] - }, - { - "cell_type": "markdown", - "id": "6851f92d", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\boldsymbol{D}=[(x_0,y_0), (x_1,y_1),\\dots, (x_{n-1},y_{n-1})].\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "9266f3e0", - "metadata": { - "editable": true - }, - "source": [ - "In the more general case the various inputs should be replaced by the possible features represented by the input data set $\\boldsymbol{X}$. \n", - "We can now rewrite the above probability as" - ] - }, - { - "cell_type": "markdown", - "id": "287d1ae7", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "p(\\boldsymbol{D}\\vert\\boldsymbol{\\beta})=\\prod_{i=0}^{n-1}\\frac{1}{\\sqrt{2\\pi\\sigma^2}}\\exp{\\left[-\\frac{(y_i-\\boldsymbol{X}_{i,*}\\boldsymbol{\\beta})^2}{2\\sigma^2}\\right]}.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "5b27ae15", - "metadata": { - "editable": true - }, - "source": [ - "It is a conditional probability (see below) and reads as the likelihood of a domain of events $\\boldsymbol{D}$ given a set of parameters $\\boldsymbol{\\beta}$." - ] - }, - { - "cell_type": "markdown", - "id": "05685291", - "metadata": { - "editable": true - }, - "source": [ - "## Maximum Likelihood Estimation (MLE)\n", - "\n", - "In statistics, maximum likelihood estimation (MLE) is a method of\n", - "estimating the parameters of an assumed probability distribution,\n", - "given some observed data. This is achieved by maximizing a likelihood\n", - "function so that, under the assumed statistical model, the observed\n", - "data is the most probable. \n", - "\n", - "We will assume here that our events are given by the above Gaussian\n", - "distribution and we will determine the optimal parameters $\\beta$ by\n", - "maximizing the above PDF. However, computing the derivatives of a\n", - "product function is cumbersome and can easily lead to overflow and/or\n", - "underflowproblems, with potentials for loss of numerical precision.\n", - "\n", - "In practice, it is more convenient to maximize the logarithm of the\n", - "PDF because it is a monotonically increasing function of the argument.\n", - "Alternatively, and this will be our option, we will minimize the\n", - "negative of the logarithm since this is a monotonically decreasing\n", - "function.\n", - "\n", - "Note also that maximization/minimization of the logarithm of the PDF\n", - "is equivalent to the maximization/minimization of the function itself." - ] - }, - { - "cell_type": "markdown", - "id": "9219f05a", - "metadata": { - "editable": true - }, - "source": [ - "## A new Cost Function\n", - "\n", - "We could now define a new cost function to minimize, namely the negative logarithm of the above PDF" - ] - }, - { - "cell_type": "markdown", - "id": "fba0d995", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "C(\\boldsymbol{\\beta}=-\\log{\\prod_{i=0}^{n-1}p(y_i,\\boldsymbol{X}\\vert\\boldsymbol{\\beta})}=-\\sum_{i=0}^{n-1}\\log{p(y_i,\\boldsymbol{X}\\vert\\boldsymbol{\\beta})},\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "c19bfc19", - "metadata": { - "editable": true - }, - "source": [ - "which becomes" - ] - }, - { - "cell_type": "markdown", - "id": "6de82f09", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "C(\\boldsymbol{\\beta}=\\frac{n}{2}\\log{2\\pi\\sigma^2}+\\frac{\\vert\\vert (\\boldsymbol{y}-\\boldsymbol{X}\\boldsymbol{\\beta})\\vert\\vert_2^2}{2\\sigma^2}.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "adfc6771", - "metadata": { - "editable": true - }, - "source": [ - "Taking the derivative of the *new* cost function with respect to the parameters $\\beta$ we recognize our familiar OLS equation, namely" - ] - }, - { - "cell_type": "markdown", - "id": "a1ecd0dd", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\boldsymbol{X}^T\\left(\\boldsymbol{y}-\\boldsymbol{X}\\boldsymbol{\\beta}\\right) =0,\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "91a37c0d", - "metadata": { - "editable": true - }, - "source": [ - "which leads to the well-known OLS equation for the optimal paramters $\\beta$" - ] - }, - { - "cell_type": "markdown", - "id": "11677560", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\hat{\\boldsymbol{\\beta}}^{\\mathrm{OLS}}=\\left(\\boldsymbol{X}^T\\boldsymbol{X}\\right)^{-1}\\boldsymbol{X}^T\\boldsymbol{y}!\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "8099810c", - "metadata": { - "editable": true - }, - "source": [ - "Before we make a similar analysis for Ridge and Lasso regression, we need a short reminder on statistics." - ] - }, - { - "cell_type": "markdown", - "id": "f9232f8c", - "metadata": { - "editable": true - }, - "source": [ - "## More basic Statistics and Bayes' theorem\n", - "\n", - "A central theorem in statistics is Bayes' theorem. This theorem plays a similar role as the good old Pythagoras' theorem in geometry.\n", - "Bayes' theorem is extremely simple to derive. But to do so we need some basic axioms from statistics.\n", - "\n", - "Assume we have two domains of events $X=[x_0,x_1,\\dots,x_{n-1}]$ and $Y=[y_0,y_1,\\dots,y_{n-1}]$.\n", - "\n", - "We define also the likelihood for $X$ and $Y$ as $p(X)$ and $p(Y)$ respectively.\n", - "The likelihood of a specific event $x_i$ (or $y_i$) is then written as $p(X=x_i)$ or just $p(x_i)=p_i$. \n", - "\n", - "**Union of events is given by.**" - ] - }, - { - "cell_type": "markdown", - "id": "9088ea5d", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "p(X \\cup Y)= p(X)+p(Y)-p(X \\cap Y).\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "5a43a59f", - "metadata": { - "editable": true - }, - "source": [ - "**The product rule (aka joint probability) is given by.**" - ] - }, - { - "cell_type": "markdown", - "id": "4cf876a2", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "p(X \\cup Y)= p(X,Y)= p(X\\vert Y)p(Y)=p(Y\\vert X)p(X),\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "19f3bd61", - "metadata": { - "editable": true - }, - "source": [ - "where we read $p(X\\vert Y)$ as the likelihood of obtaining $X$ given $Y$.\n", - "\n", - "If we have independent events then $p(X,Y)=p(X)p(Y)$." - ] - }, - { - "cell_type": "markdown", - "id": "f4df8724", - "metadata": { - "editable": true - }, - "source": [ - "## Marginal Probability\n", - "\n", - "The marginal probability is defined in terms of only one of the set of variables $X,Y$. For a discrete probability we have" - ] - }, - { - "cell_type": "markdown", - "id": "a137b317", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "p(X)=\\sum_{i=0}^{n-1}p(X,Y=y_i)=\\sum_{i=0}^{n-1}p(X\\vert Y=y_i)p(Y=y_i)=\\sum_{i=0}^{n-1}p(X\\vert y_i)p(y_i).\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "83858731", - "metadata": { - "editable": true - }, - "source": [ - "## Conditional Probability\n", - "\n", - "The conditional probability, if $p(Y) > 0$, is" - ] - }, - { - "cell_type": "markdown", - "id": "ee5dab96", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "p(X\\vert Y)= \\frac{p(X,Y)}{p(Y)}=\\frac{p(X,Y)}{\\sum_{i=0}^{n-1}p(Y\\vert X=x_i)p(x_i)}.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "cb03bfdd", - "metadata": { - "editable": true - }, - "source": [ - "## Bayes' Theorem\n", - "\n", - "If we combine the conditional probability with the marginal probability and the standard product rule, we have" - ] - }, - { - "cell_type": "markdown", - "id": "72b69902", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "p(X\\vert Y)= \\frac{p(X,Y)}{p(Y)},\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "8a876747", - "metadata": { - "editable": true - }, - "source": [ - "which we can rewrite as" - ] - }, - { - "cell_type": "markdown", - "id": "2424f759", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "p(X\\vert Y)= \\frac{p(X,Y)}{\\sum_{i=0}^{n-1}p(Y\\vert X=x_i)p(x_i)}=\\frac{p(Y\\vert X)p(X)}{\\sum_{i=0}^{n-1}p(Y\\vert X=x_i)p(x_i)},\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "f33b3f29", - "metadata": { - "editable": true - }, - "source": [ - "which is Bayes' theorem. It allows us to evaluate the uncertainty in in $X$ after we have observed $Y$. We can easily interchange $X$ with $Y$." - ] - }, - { - "cell_type": "markdown", - "id": "b73e0693", - "metadata": { - "editable": true - }, - "source": [ - "## Interpretations of Bayes' Theorem\n", - "\n", - "The quantity $p(Y\\vert X)$ on the right-hand side of the theorem is\n", - "evaluated for the observed data $Y$ and can be viewed as a function of\n", - "the parameter space represented by $X$. This function is not\n", - "necesseraly normalized and is normally called the likelihood function.\n", - "\n", - "The function $p(X)$ on the right hand side is called the prior while the function on the left hand side is the called the posterior probability. The denominator on the right hand side serves as a normalization factor for the posterior distribution.\n", - "\n", - "Let us try to illustrate Bayes' theorem through an example." - ] - }, - { - "cell_type": "markdown", - "id": "a2bc10db", - "metadata": { - "editable": true - }, - "source": [ - "## Example of Usage of Bayes' theorem\n", - "\n", - "Let us suppose that you are undergoing a series of mammography scans in\n", - "order to rule out possible breast cancer cases. We define the\n", - "sensitivity for a positive event by the variable $X$. It takes binary\n", - "values with $X=1$ representing a positive event and $X=0$ being a\n", - "negative event. We reserve $Y$ as a classification parameter for\n", - "either a negative or a positive breast cancer confirmation. (Short note on wordings: positive here means having breast cancer, although none of us would consider this being a positive thing).\n", - "\n", - "We let $Y=1$ represent the the case of having breast cancer and $Y=0$ as not.\n", - "\n", - "Let us assume that if you have breast cancer, the test will be positive with a probability of $0.8$, that is we have" - ] - }, - { - "cell_type": "markdown", - "id": "f41d3f9b", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "p(X=1\\vert Y=1) =0.8.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "fe20e517", - "metadata": { - "editable": true - }, - "source": [ - "This obviously sounds scary since many would conclude that if the test is positive, there is a likelihood of $80\\%$ for having cancer.\n", - "It is however not correct, as the following Bayesian analysis shows." - ] - }, - { - "cell_type": "markdown", - "id": "d003d5d8", - "metadata": { - "editable": true - }, - "source": [ - "## Doing it correctly\n", - "\n", - "If we look at various national surveys on breast cancer, the general likelihood of developing breast cancer is a very small number.\n", - "Let us assume that the prior probability in the population as a whole is" - ] - }, - { - "cell_type": "markdown", - "id": "07a5ca9c", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "p(Y=1) =0.004.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "91485638", - "metadata": { - "editable": true - }, - "source": [ - "We need also to account for the fact that the test may produce a false positive result (false alarm). Let us here assume that we have" - ] - }, - { - "cell_type": "markdown", - "id": "be6de757", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "p(X=1\\vert Y=0) =0.1.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "51263519", - "metadata": { - "editable": true - }, - "source": [ - "Using Bayes' theorem we can then find the posterior probability that the person has breast cancer in case of a positive test, that is we can compute" - ] - }, - { - "cell_type": "markdown", - "id": "5b2dc226", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "p(Y=1\\vert X=1)=\\frac{p(X=1\\vert Y=1)p(Y=1)}{p(X=1\\vert Y=1)p(Y=1)+p(X=1\\vert Y=0)p(Y=0)}=\\frac{0.8\\times 0.004}{0.8\\times 0.004+0.1\\times 0.996}=0.031.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "e241fbc1", - "metadata": { - "editable": true - }, - "source": [ - "That is, in case of a positive test, there is only a $3\\%$ chance of having breast cancer!" - ] - }, - { - "cell_type": "markdown", - "id": "42db70df", - "metadata": { - "editable": true - }, - "source": [ - "## Bayes' Theorem and Ridge and Lasso Regression\n", - "\n", - "Using Bayes' theorem we can gain a better intuition about Ridge and Lasso regression. \n", - "\n", - "For ordinary least squares we postulated that the maximum likelihood for the doamin of events $\\boldsymbol{D}$ (one-dimensional case)" - ] - }, - { - "cell_type": "markdown", - "id": "ed75a460", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\boldsymbol{D}=[(x_0,y_0), (x_1,y_1),\\dots, (x_{n-1},y_{n-1})],\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "c826a95f", - "metadata": { - "editable": true - }, - "source": [ - "is given by" - ] - }, - { - "cell_type": "markdown", - "id": "70a426f9", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "p(\\boldsymbol{D}\\vert\\boldsymbol{\\beta})=\\prod_{i=0}^{n-1}\\frac{1}{\\sqrt{2\\pi\\sigma^2}}\\exp{\\left[-\\frac{(y_i-\\boldsymbol{X}_{i,*}\\boldsymbol{\\beta})^2}{2\\sigma^2}\\right]}.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "a90b1b91", - "metadata": { - "editable": true - }, - "source": [ - "In Bayes' theorem this function plays the role of the so-called likelihood. We could now ask the question what is the posterior probability of a parameter set $\\boldsymbol{\\beta}$ given a domain of events $\\boldsymbol{D}$? That is, how can we define the posterior probability" - ] - }, - { - "cell_type": "markdown", - "id": "3f5a6f0b", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "p(\\boldsymbol{\\beta}\\vert\\boldsymbol{D}).\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "2530803f", - "metadata": { - "editable": true - }, - "source": [ - "Bayes' theorem comes to our rescue here since (omitting the normalization constant)" - ] - }, - { - "cell_type": "markdown", - "id": "34940159", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "p(\\boldsymbol{\\beta}\\vert\\boldsymbol{D})\\propto p(\\boldsymbol{D}\\vert\\boldsymbol{\\beta})p(\\boldsymbol{\\beta}).\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "1f497f2c", - "metadata": { - "editable": true - }, - "source": [ - "We have a model for $p(\\boldsymbol{D}\\vert\\boldsymbol{\\beta})$ but need one for the **prior** $p(\\boldsymbol{\\beta}$!" - ] - }, - { - "cell_type": "markdown", - "id": "c780a9b9", - "metadata": { - "editable": true - }, - "source": [ - "## Ridge and Bayes\n", - "\n", - "With the posterior probability defined by a likelihood which we have\n", - "already modeled and an unknown prior, we are now ready to make\n", - "additional models for the prior.\n", - "\n", - "We can, based on our discussions of the variance of $\\boldsymbol{\\beta}$ and the mean value, assume that the prior for the values $\\boldsymbol{\\beta}$ is given by a Gaussian with mean value zero and variance $\\tau^2$, that is" - ] - }, - { - "cell_type": "markdown", - "id": "68ddd4cc", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "p(\\boldsymbol{\\beta})=\\prod_{j=0}^{p-1}\\exp{\\left(-\\frac{\\beta_j^2}{2\\tau^2}\\right)}.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "b85ade85", - "metadata": { - "editable": true - }, - "source": [ - "Our posterior probability becomes then (omitting the normalization factor which is just a constant)" - ] - }, - { - "cell_type": "markdown", - "id": "6386a328", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "p(\\boldsymbol{\\beta\\vert\\boldsymbol{D})}=\\prod_{i=0}^{n-1}\\frac{1}{\\sqrt{2\\pi\\sigma^2}}\\exp{\\left[-\\frac{(y_i-\\boldsymbol{X}_{i,*}\\boldsymbol{\\beta})^2}{2\\sigma^2}\\right]}\\prod_{j=0}^{p-1}\\exp{\\left(-\\frac{\\beta_j^2}{2\\tau^2}\\right)}.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "316194e8", - "metadata": { - "editable": true - }, - "source": [ - "We can now optimize this quantity with respect to $\\boldsymbol{\\beta}$. As we\n", - "did for OLS, this is most conveniently done by taking the negative\n", - "logarithm of the posterior probability. Doing so and leaving out the\n", - "constants terms that do not depend on $\\beta$, we have" - ] - }, - { - "cell_type": "markdown", - "id": "f7e39504", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "C(\\boldsymbol{\\beta})=\\frac{\\vert\\vert (\\boldsymbol{y}-\\boldsymbol{X}\\boldsymbol{\\beta})\\vert\\vert_2^2}{2\\sigma^2}+\\frac{1}{2\\tau^2}\\vert\\vert\\boldsymbol{\\beta}\\vert\\vert_2^2,\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "6c3b01de", - "metadata": { - "editable": true - }, - "source": [ - "and replacing $1/2\\tau^2$ with $\\lambda$ we have" - ] - }, - { - "cell_type": "markdown", - "id": "5c4a05c9", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "C(\\boldsymbol{\\beta})=\\frac{\\vert\\vert (\\boldsymbol{y}-\\boldsymbol{X}\\boldsymbol{\\beta})\\vert\\vert_2^2}{2\\sigma^2}+\\lambda\\vert\\vert\\boldsymbol{\\beta}\\vert\\vert_2^2,\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "6f26b763", - "metadata": { - "editable": true - }, - "source": [ - "which is our Ridge cost function! Nice, isn't it?" - ] - }, - { - "cell_type": "markdown", - "id": "08efa297", - "metadata": { - "editable": true - }, - "source": [ - "## Lasso and Bayes\n", - "\n", - "To derive the Lasso cost function, we simply replace the Gaussian prior with an exponential distribution ([Laplace in this case](https://en.wikipedia.org/wiki/Laplace_distribution)) with zero mean value, that is" - ] - }, - { - "cell_type": "markdown", - "id": "97765f2c", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "p(\\boldsymbol{\\beta})=\\prod_{j=0}^{p-1}\\exp{\\left(-\\frac{\\vert\\beta_j\\vert}{\\tau}\\right)}.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "b2e48903", - "metadata": { - "editable": true - }, - "source": [ - "Our posterior probability becomes then (omitting the normalization factor which is just a constant)" - ] - }, - { - "cell_type": "markdown", - "id": "fae174cf", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "p(\\boldsymbol{\\beta}\\vert\\boldsymbol{D})=\\prod_{i=0}^{n-1}\\frac{1}{\\sqrt{2\\pi\\sigma^2}}\\exp{\\left[-\\frac{(y_i-\\boldsymbol{X}_{i,*}\\boldsymbol{\\beta})^2}{2\\sigma^2}\\right]}\\prod_{j=0}^{p-1}\\exp{\\left(-\\frac{\\vert\\beta_j\\vert}{\\tau}\\right)}.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "dc3ff171", - "metadata": { - "editable": true - }, - "source": [ - "Taking the negative\n", - "logarithm of the posterior probability and leaving out the\n", - "constants terms that do not depend on $\\beta$, we have" - ] - }, - { - "cell_type": "markdown", - "id": "af3046b7", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "C(\\boldsymbol{\\beta}=\\frac{\\vert\\vert (\\boldsymbol{y}-\\boldsymbol{X}\\boldsymbol{\\beta})\\vert\\vert_2^2}{2\\sigma^2}+\\frac{1}{\\tau}\\vert\\vert\\boldsymbol{\\beta}\\vert\\vert_1,\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "fbf017df", - "metadata": { - "editable": true - }, - "source": [ - "and replacing $1/\\tau$ with $\\lambda$ we have" - ] - }, - { - "cell_type": "markdown", - "id": "23214eb3", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "C(\\boldsymbol{\\beta}=\\frac{\\vert\\vert (\\boldsymbol{y}-\\boldsymbol{X}\\boldsymbol{\\beta})\\vert\\vert_2^2}{2\\sigma^2}+\\lambda\\vert\\vert\\boldsymbol{\\beta}\\vert\\vert_1,\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "f3c6b69a", - "metadata": { - "editable": true - }, - "source": [ - "which is our Lasso cost function!" - ] - }, - { - "cell_type": "markdown", - "id": "386493f5", - "metadata": { - "editable": true - }, - "source": [ - "## Why resampling methods\n", - "\n", - "Before we proceed, we need to rethink what we have been doing. In our\n", - "eager to fit the data, we have omitted several important elements in\n", - "our regression analysis. In what follows we will\n", - "1. look at statistical properties, including a discussion of mean values, variance and the so-called bias-variance tradeoff\n", - "\n", - "2. introduce resampling techniques like cross-validation, bootstrapping and jackknife and more\n", - "\n", - "and discuss how to select a given model (one of the difficult parts in machine learning)." - ] - }, - { - "cell_type": "markdown", - "id": "727bee7f", - "metadata": { - "editable": true - }, - "source": [ - "## Resampling methods\n", - "Resampling methods are an indispensable tool in modern\n", - "statistics. They involve repeatedly drawing samples from a training\n", - "set and refitting a model of interest on each sample in order to\n", - "obtain additional information about the fitted model. For example, in\n", - "order to estimate the variability of a linear regression fit, we can\n", - "repeatedly draw different samples from the training data, fit a linear\n", - "regression to each new sample, and then examine the extent to which\n", - "the resulting fits differ. Such an approach may allow us to obtain\n", - "information that would not be available from fitting the model only\n", - "once using the original training sample.\n", - "\n", - "Two resampling methods are often used in Machine Learning analyses,\n", - "1. The **bootstrap method**\n", - "\n", - "2. and **Cross-Validation**\n", - "\n", - "In addition there are several other methods such as the Jackknife and the Blocking methods. We will discuss in particular\n", - "cross-validation and the bootstrap method." - ] - }, - { - "cell_type": "markdown", - "id": "7e34ba8e", - "metadata": { - "editable": true - }, - "source": [ - "## Resampling approaches can be computationally expensive\n", - "\n", - "Resampling approaches can be computationally expensive, because they\n", - "involve fitting the same statistical method multiple times using\n", - "different subsets of the training data. However, due to recent\n", - "advances in computing power, the computational requirements of\n", - "resampling methods generally are not prohibitive. In this chapter, we\n", - "discuss two of the most commonly used resampling methods,\n", - "cross-validation and the bootstrap. Both methods are important tools\n", - "in the practical application of many statistical learning\n", - "procedures. For example, cross-validation can be used to estimate the\n", - "test error associated with a given statistical learning method in\n", - "order to evaluate its performance, or to select the appropriate level\n", - "of flexibility. The process of evaluating a model’s performance is\n", - "known as model assessment, whereas the process of selecting the proper\n", - "level of flexibility for a model is known as model selection. The\n", - "bootstrap is widely used." - ] - }, - { - "cell_type": "markdown", - "id": "fc35fdde", - "metadata": { - "editable": true - }, - "source": [ - "## Why resampling methods ?\n", - "**Statistical analysis.**\n", - "\n", - "* Our simulations can be treated as *computer experiments*. This is particularly the case for Monte Carlo methods which are widely used in statistical analyses.\n", - "\n", - "* The results can be analysed with the same statistical tools as we would use when analysing experimental data.\n", - "\n", - "* As in all experiments, we are looking for expectation values and an estimate of how accurate they are, i.e., possible sources for errors." - ] - }, - { - "cell_type": "markdown", - "id": "dc071fc4", - "metadata": { - "editable": true - }, - "source": [ - "## Statistical analysis\n", - "\n", - "* As in other experiments, many numerical experiments have two classes of errors:\n", - "\n", - " * Statistical errors\n", - "\n", - " * Systematical errors\n", - "\n", - "* Statistical errors can be estimated using standard tools from statistics\n", - "\n", - "* Systematical errors are method specific and must be treated differently from case to case." - ] - }, - { - "cell_type": "markdown", - "id": "ef1325b9", - "metadata": { - "editable": true - }, - "source": [ - "## Resampling methods\n", - "\n", - "With all these analytical equations for both the OLS and Ridge\n", - "regression, we will now outline how to assess a given model. This will\n", - "lead to a discussion of the so-called bias-variance tradeoff (see\n", - "below) and so-called resampling methods.\n", - "\n", - "One of the quantities we have discussed as a way to measure errors is\n", - "the mean-squared error (MSE), mainly used for fitting of continuous\n", - "functions. Another choice is the absolute error.\n", - "\n", - "In the discussions below we will focus on the MSE and in particular since we will split the data into test and training data,\n", - "we discuss the\n", - "1. prediction error or simply the **test error** $\\mathrm{Err_{Test}}$, where we have a fixed training set and the test error is the MSE arising from the data reserved for testing. We discuss also the \n", - "\n", - "2. training error $\\mathrm{Err_{Train}}$, which is the average loss over the training data.\n", - "\n", - "As our model becomes more and more complex, more of the training data tends to used. The training may thence adapt to more complicated structures in the data. This may lead to a decrease in the bias (see below for code example) and a slight increase of the variance for the test error.\n", - "For a certain level of complexity the test error will reach minimum, before starting to increase again. The\n", - "training error reaches a saturation." - ] - }, - { - "cell_type": "markdown", - "id": "340ea11c", - "metadata": { - "editable": true - }, - "source": [ - "## Resampling methods: Bootstrap\n", - "Bootstrapping is a [non-parametric approach](https://en.wikipedia.org/wiki/Nonparametric_statistics) to statistical inference\n", - "that substitutes computation for more traditional distributional\n", - "assumptions and asymptotic results. Bootstrapping offers a number of\n", - "advantages: \n", - "1. The bootstrap is quite general, although there are some cases in which it fails. \n", - "\n", - "2. Because it does not require distributional assumptions (such as normally distributed errors), the bootstrap can provide more accurate inferences when the data are not well behaved or when the sample size is small. \n", - "\n", - "3. It is possible to apply the bootstrap to statistics with sampling distributions that are difficult to derive, even asymptotically. \n", - "\n", - "4. It is relatively simple to apply the bootstrap to complex data-collection plans (such as stratified and clustered samples).\n", - "\n", - "The textbook by [Davison on the Bootstrap Methods and their Applications](https://www.cambridge.org/core/books/bootstrap-methods-and-their-application/ED2FD043579F27952363566DC09CBD6A) provides many more insights and proofs. In this course we will take a more practical approach and use the results and theorems provided in the literature. For those interested in reading more about the bootstrap methods, we recommend the above text and the one by [Efron and Tibshirani](https://www.routledge.com/An-Introduction-to-the-Bootstrap/Efron-Tibshirani/p/book/9780412042317).\n", - "\n", - "Before we proceed however, we need to remind ourselves about a central theorem in statistics, namely the so-called **central limit theorem**." - ] - }, - { - "cell_type": "markdown", - "id": "74bd7468", - "metadata": { - "editable": true - }, - "source": [ - "## The Central Limit Theorem\n", - "\n", - "Suppose we have a PDF $p(x)$ from which we generate a series $N$\n", - "of averages $\\mathbb{E}[x_i]$. Each mean value $\\mathbb{E}[x_i]$\n", - "is viewed as the average of a specific measurement, e.g., throwing \n", - "dice 100 times and then taking the average value, or producing a certain\n", - "amount of random numbers. \n", - "For notational ease, we set $\\mathbb{E}[x_i]=x_i$ in the discussion\n", - "which follows. We do the same for $\\mathbb{E}[z]=z$.\n", - "\n", - "If we compute the mean $z$ of $m$ such mean values $x_i$" - ] - }, - { - "cell_type": "markdown", - "id": "93013ca8", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "z=\\frac{x_1+x_2+\\dots+x_m}{m},\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "92fa2b15", - "metadata": { - "editable": true - }, - "source": [ - "the question we pose is which is the PDF of the new variable $z$." - ] - }, - { - "cell_type": "markdown", - "id": "1031aebe", - "metadata": { - "editable": true - }, - "source": [ - "## Finding the Limit\n", - "\n", - "The probability of obtaining an average value $z$ is the product of the \n", - "probabilities of obtaining arbitrary individual mean values $x_i$,\n", - "but with the constraint that the average is $z$. We can express this through\n", - "the following expression" - ] - }, - { - "cell_type": "markdown", - "id": "cc495848", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\tilde{p}(z)=\\int dx_1p(x_1)\\int dx_2p(x_2)\\dots\\int dx_mp(x_m)\n", - " \\delta(z-\\frac{x_1+x_2+\\dots+x_m}{m}),\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "28b2bcff", - "metadata": { - "editable": true - }, - "source": [ - "where the $\\delta$-function enbodies the constraint that the mean is $z$.\n", - "All measurements that lead to each individual $x_i$ are expected to\n", - "be independent, which in turn means that we can express $\\tilde{p}$ as the \n", - "product of individual $p(x_i)$. The independence assumption is important in the derivation of the central limit theorem." - ] - }, - { - "cell_type": "markdown", - "id": "5d3eb73d", - "metadata": { - "editable": true - }, - "source": [ - "## Rewriting the $\\delta$-function\n", - "\n", - "If we use the integral expression for the $\\delta$-function" - ] - }, - { - "cell_type": "markdown", - "id": "75b47bae", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\delta(z-\\frac{x_1+x_2+\\dots+x_m}{m})=\\frac{1}{2\\pi}\\int_{-\\infty}^{\\infty}\n", - " dq\\exp{\\left(iq(z-\\frac{x_1+x_2+\\dots+x_m}{m})\\right)},\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "a99105b0", - "metadata": { - "editable": true - }, - "source": [ - "and inserting $e^{i\\mu q-i\\mu q}$ where $\\mu$ is the mean value\n", - "we arrive at" - ] - }, - { - "cell_type": "markdown", - "id": "da28e9b0", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\tilde{p}(z)=\\frac{1}{2\\pi}\\int_{-\\infty}^{\\infty}\n", - " dq\\exp{\\left(iq(z-\\mu)\\right)}\\left[\\int_{-\\infty}^{\\infty}\n", - " dxp(x)\\exp{\\left(iq(\\mu-x)/m\\right)}\\right]^m,\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "5bd0da08", - "metadata": { - "editable": true - }, - "source": [ - "with the integral over $x$ resulting in" - ] - }, - { - "cell_type": "markdown", - "id": "8dcbd91d", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\int_{-\\infty}^{\\infty}dxp(x)\\exp{\\left(iq(\\mu-x)/m\\right)}=\n", - " \\int_{-\\infty}^{\\infty}dxp(x)\n", - " \\left[1+\\frac{iq(\\mu-x)}{m}-\\frac{q^2(\\mu-x)^2}{2m^2}+\\dots\\right].\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "3ab26352", - "metadata": { - "editable": true - }, - "source": [ - "## Identifying Terms\n", - "\n", - "The second term on the rhs disappears since this is just the mean and \n", - "employing the definition of $\\sigma^2$ we have" - ] - }, - { - "cell_type": "markdown", - "id": "9e232448", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\int_{-\\infty}^{\\infty}dxp(x)e^{\\left(iq(\\mu-x)/m\\right)}=\n", - " 1-\\frac{q^2\\sigma^2}{2m^2}+\\dots,\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "15cdad60", - "metadata": { - "editable": true - }, - "source": [ - "resulting in" - ] - }, - { - "cell_type": "markdown", - "id": "7b857d11", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\left[\\int_{-\\infty}^{\\infty}dxp(x)\\exp{\\left(iq(\\mu-x)/m\\right)}\\right]^m\\approx\n", - " \\left[1-\\frac{q^2\\sigma^2}{2m^2}+\\dots \\right]^m,\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "a7ba76a4", - "metadata": { - "editable": true - }, - "source": [ - "and in the limit $m\\rightarrow \\infty$ we obtain" - ] - }, - { - "cell_type": "markdown", - "id": "27abee5c", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\tilde{p}(z)=\\frac{1}{\\sqrt{2\\pi}(\\sigma/\\sqrt{m})}\n", - " \\exp{\\left(-\\frac{(z-\\mu)^2}{2(\\sigma/\\sqrt{m})^2}\\right)},\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "450fbae6", - "metadata": { - "editable": true - }, - "source": [ - "which is the normal distribution with variance\n", - "$\\sigma^2_m=\\sigma^2/m$, where $\\sigma$ is the variance of the PDF $p(x)$\n", - "and $\\mu$ is also the mean of the PDF $p(x)$." - ] - }, - { - "cell_type": "markdown", - "id": "583a9a42", - "metadata": { - "editable": true - }, - "source": [ - "## Wrapping it up\n", - "\n", - "Thus, the central limit theorem states that the PDF $\\tilde{p}(z)$ of\n", - "the average of $m$ random values corresponding to a PDF $p(x)$ \n", - "is a normal distribution whose mean is the \n", - "mean value of the PDF $p(x)$ and whose variance is the variance\n", - "of the PDF $p(x)$ divided by $m$, the number of values used to compute $z$.\n", - "\n", - "The central limit theorem leads to the well-known expression for the\n", - "standard deviation, given by" - ] - }, - { - "cell_type": "markdown", - "id": "cdd93e78", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\sigma_m=\n", - "\\frac{\\sigma}{\\sqrt{m}}.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "dfe218b6", - "metadata": { - "editable": true - }, - "source": [ - "The latter is true only if the average value is known exactly. This is obtained in the limit\n", - "$m\\rightarrow \\infty$ only. Because the mean and the variance are measured quantities we obtain \n", - "the familiar expression in statistics (the so-called Bessel correction)" - ] - }, - { - "cell_type": "markdown", - "id": "5d3fd1f7", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\sigma_m\\approx \n", - "\\frac{\\sigma}{\\sqrt{m-1}}.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "3b8a47f4", - "metadata": { - "editable": true - }, - "source": [ - "In many cases however the above estimate for the standard deviation,\n", - "in particular if correlations are strong, may be too simplistic. Keep\n", - "in mind that we have assumed that the variables $x$ are independent\n", - "and identically distributed. This is obviously not always the\n", - "case. For example, the random numbers (or better pseudorandom numbers)\n", - "we generate in various calculations do always exhibit some\n", - "correlations.\n", - "\n", - "The theorem is satisfied by a large class of PDFs. Note however that for a\n", - "finite $m$, it is not always possible to find a closed form /analytic expression for\n", - "$\\tilde{p}(x)$." - ] - }, - { - "cell_type": "markdown", - "id": "c57ef602", - "metadata": { - "editable": true - }, - "source": [ - "## Confidence Intervals\n", - "\n", - "Confidence intervals are used in statistics and represent a type of estimate\n", - "computed from the observed data. This gives a range of values for an\n", - "unknown parameter such as the parameters $\\boldsymbol{\\beta}$ from linear regression.\n", - "\n", - "With the OLS expressions for the parameters $\\boldsymbol{\\beta}$ we found \n", - "$\\mathbb{E}(\\boldsymbol{\\beta}) = \\boldsymbol{\\beta}$, which means that the estimator of the regression parameters is unbiased.\n", - "\n", - "We found also that the variance of the estimate of the $j$-th regression coefficient is\n", - "$\\boldsymbol{\\sigma}^2 (\\boldsymbol{\\beta}_j ) = \\boldsymbol{\\sigma}^2 [(\\mathbf{X}^{T} \\mathbf{X})^{-1}]_{jj} $.\n", - "\n", - "This quantity will be used to\n", - "construct a confidence interval for the estimates." - ] - }, - { - "cell_type": "markdown", - "id": "cdea97fa", - "metadata": { - "editable": true - }, - "source": [ - "## Standard Approach based on the Normal Distribution\n", - "\n", - "We will assume that the parameters $\\beta$ follow a normal\n", - "distribution. We can then define the confidence interval. Here we will be using as\n", - "shorthands $\\mu_{\\beta}$ for the above mean value and $\\sigma_{\\beta}$\n", - "for the standard deviation. We have then a confidence interval" - ] - }, - { - "cell_type": "markdown", - "id": "efc3abe4", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\left(\\mu_{\\beta}\\pm \\frac{z\\sigma_{\\beta}}{\\sqrt{n}}\\right),\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "1679ffac", - "metadata": { - "editable": true - }, - "source": [ - "where $z$ defines the level of certainty (or confidence). For a normal\n", - "distribution typical parameters are $z=2.576$ which corresponds to a\n", - "confidence of $99\\%$ while $z=1.96$ corresponds to a confidence of\n", - "$95\\%$. A confidence level of $95\\%$ is commonly used and it is\n", - "normally referred to as a *two-sigmas* confidence level, that is we\n", - "approximate $z\\approx 2$.\n", - "\n", - "For more discussions of confidence intervals (and in particular linked with a discussion of the bootstrap method), see chapter 5 of the textbook by [Davison on the Bootstrap Methods and their Applications](https://www.cambridge.org/core/books/bootstrap-methods-and-their-application/ED2FD043579F27952363566DC09CBD6A)\n", - "\n", - "In this text you will also find an in-depth discussion of the\n", - "Bootstrap method, why it works and various theorems related to it." - ] - }, - { - "cell_type": "markdown", - "id": "fc2481bb", - "metadata": { - "editable": true - }, - "source": [ - "## Resampling methods: Bootstrap background\n", - "\n", - "Since $\\widehat{\\beta} = \\widehat{\\beta}(\\boldsymbol{X})$ is a function of random variables,\n", - "$\\widehat{\\beta}$ itself must be a random variable. Thus it has\n", - "a pdf, call this function $p(\\boldsymbol{t})$. The aim of the bootstrap is to\n", - "estimate $p(\\boldsymbol{t})$ by the relative frequency of\n", - "$\\widehat{\\beta}$. You can think of this as using a histogram\n", - "in the place of $p(\\boldsymbol{t})$. If the relative frequency closely\n", - "resembles $p(\\vec{t})$, then using numerics, it is straight forward to\n", - "estimate all the interesting parameters of $p(\\boldsymbol{t})$ using point\n", - "estimators." - ] - }, - { - "cell_type": "markdown", - "id": "a18c7fde", - "metadata": { - "editable": true - }, - "source": [ - "## Resampling methods: More Bootstrap background\n", - "\n", - "In the case that $\\widehat{\\beta}$ has\n", - "more than one component, and the components are independent, we use the\n", - "same estimator on each component separately. If the probability\n", - "density function of $X_i$, $p(x)$, had been known, then it would have\n", - "been straightforward to do this by: \n", - "1. Drawing lots of numbers from $p(x)$, suppose we call one such set of numbers $(X_1^*, X_2^*, \\cdots, X_n^*)$. \n", - "\n", - "2. Then using these numbers, we could compute a replica of $\\widehat{\\beta}$ called $\\widehat{\\beta}^*$. \n", - "\n", - "By repeated use of the above two points, many\n", - "estimates of $\\widehat{\\beta}$ can be obtained. The\n", - "idea is to use the relative frequency of $\\widehat{\\beta}^*$\n", - "(think of a histogram) as an estimate of $p(\\boldsymbol{t})$." - ] - }, - { - "cell_type": "markdown", - "id": "4af5f00a", - "metadata": { - "editable": true - }, - "source": [ - "## Resampling methods: Bootstrap approach\n", - "\n", - "But\n", - "unless there is enough information available about the process that\n", - "generated $X_1,X_2,\\cdots,X_n$, $p(x)$ is in general\n", - "unknown. Therefore, [Efron in 1979](https://projecteuclid.org/euclid.aos/1176344552) asked the\n", - "question: What if we replace $p(x)$ by the relative frequency\n", - "of the observation $X_i$?\n", - "\n", - "If we draw observations in accordance with\n", - "the relative frequency of the observations, will we obtain the same\n", - "result in some asymptotic sense? The answer is yes." - ] - }, - { - "cell_type": "markdown", - "id": "f40537a7", - "metadata": { - "editable": true - }, - "source": [ - "## Resampling methods: Bootstrap steps\n", - "\n", - "The independent bootstrap works like this: \n", - "\n", - "1. Draw with replacement $n$ numbers for the observed variables $\\boldsymbol{x} = (x_1,x_2,\\cdots,x_n)$. \n", - "\n", - "2. Define a vector $\\boldsymbol{x}^*$ containing the values which were drawn from $\\boldsymbol{x}$. \n", - "\n", - "3. Using the vector $\\boldsymbol{x}^*$ compute $\\widehat{\\beta}^*$ by evaluating $\\widehat \\beta$ under the observations $\\boldsymbol{x}^*$. \n", - "\n", - "4. Repeat this process $k$ times. \n", - "\n", - "When you are done, you can draw a histogram of the relative frequency\n", - "of $\\widehat \\beta^*$. This is your estimate of the probability\n", - "distribution $p(t)$. Using this probability distribution you can\n", - "estimate any statistics thereof. In principle you never draw the\n", - "histogram of the relative frequency of $\\widehat{\\beta}^*$. Instead\n", - "you use the estimators corresponding to the statistic of interest. For\n", - "example, if you are interested in estimating the variance of $\\widehat\n", - "\\beta$, apply the etsimator $\\widehat \\sigma^2$ to the values\n", - "$\\widehat \\beta^*$." - ] - }, - { - "cell_type": "markdown", - "id": "c6459716", - "metadata": { - "editable": true - }, - "source": [ - "## Code example for the Bootstrap method\n", - "\n", - "The following code starts with a Gaussian distribution with mean value\n", - "$\\mu =100$ and variance $\\sigma=15$. We use this to generate the data\n", - "used in the bootstrap analysis. The bootstrap analysis returns a data\n", - "set after a given number of bootstrap operations (as many as we have\n", - "data points). This data set consists of estimated mean values for each\n", - "bootstrap operation. The histogram generated by the bootstrap method\n", - "shows that the distribution for these mean values is also a Gaussian,\n", - "centered around the mean value $\\mu=100$ but with standard deviation\n", - "$\\sigma/\\sqrt{n}$, where $n$ is the number of bootstrap samples (in\n", - "this case the same as the number of original data points). The value\n", - "of the standard deviation is what we expect from the central limit\n", - "theorem." - ] - }, - { - "cell_type": "code", - "execution_count": 1, - "id": "61ebf590", - "metadata": { - "collapsed": false, - "editable": true - }, - "outputs": [], - "source": [ - "%matplotlib inline\n", - "\n", - "import numpy as np\n", - "from time import time\n", - "from scipy.stats import norm\n", - "import matplotlib.pyplot as plt\n", - "\n", - "# Returns mean of bootstrap samples \n", - "# Bootstrap algorithm\n", - "def bootstrap(data, datapoints):\n", - " t = np.zeros(datapoints)\n", - " n = len(data)\n", - " # non-parametric bootstrap \n", - " for i in range(datapoints):\n", - " t[i] = np.mean(data[np.random.randint(0,n,n)])\n", - " # analysis \n", - " print(\"Bootstrap Statistics :\")\n", - " print(\"original bias std. error\")\n", - " print(\"%8g %8g %14g %15g\" % (np.mean(data), np.std(data),np.mean(t),np.std(t)))\n", - " return t\n", - "\n", - "# We set the mean value to 100 and the standard deviation to 15\n", - "mu, sigma = 100, 15\n", - "datapoints = 10000\n", - "# We generate random numbers according to the normal distribution\n", - "x = mu + sigma*np.random.randn(datapoints)\n", - "# bootstrap returns the data sample \n", - "t = bootstrap(x, datapoints)" - ] - }, - { - "cell_type": "markdown", - "id": "2bcfb7ee", - "metadata": { - "editable": true - }, - "source": [ - "We see that our new variance and from that the standard deviation, agrees with the central limit theorem." - ] - }, - { - "cell_type": "markdown", - "id": "bb8e2e4c", - "metadata": { - "editable": true - }, - "source": [ - "## Plotting the Histogram" - ] - }, - { - "cell_type": "code", - "execution_count": 2, - "id": "4d167410", - "metadata": { - "collapsed": false, - "editable": true - }, - "outputs": [], - "source": [ - "# the histogram of the bootstrapped data (normalized data if density = True)\n", - "n, binsboot, patches = plt.hist(t, 50, density=True, facecolor='red', alpha=0.75)\n", - "# add a 'best fit' line \n", - "y = norm.pdf(binsboot, np.mean(t), np.std(t))\n", - "lt = plt.plot(binsboot, y, 'b', linewidth=1)\n", - "plt.xlabel('x')\n", - "plt.ylabel('Probability')\n", - "plt.grid(True)\n", - "plt.show()" - ] - }, - { - "cell_type": "markdown", - "id": "5b04a99c", - "metadata": { - "editable": true - }, - "source": [ - "## The bias-variance tradeoff\n", - "\n", - "We will discuss the bias-variance tradeoff in the context of\n", - "continuous predictions such as regression. However, many of the\n", - "intuitions and ideas discussed here also carry over to classification\n", - "tasks. Consider a dataset $\\mathcal{D}$ consisting of the data\n", - "$\\mathbf{X}_\\mathcal{D}=\\{(y_j, \\boldsymbol{x}_j), j=0\\ldots n-1\\}$. \n", - "\n", - "Let us assume that the true data is generated from a noisy model" - ] - }, - { - "cell_type": "markdown", - "id": "df8b5b83", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\boldsymbol{y}=f(\\boldsymbol{x}) + \\boldsymbol{\\epsilon}\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "8b1cae6d", - "metadata": { - "editable": true - }, - "source": [ - "where $\\epsilon$ is normally distributed with mean zero and standard deviation $\\sigma^2$.\n", - "\n", - "In our derivation of the ordinary least squares method we defined then\n", - "an approximation to the function $f$ in terms of the parameters\n", - "$\\boldsymbol{\\beta}$ and the design matrix $\\boldsymbol{X}$ which embody our model,\n", - "that is $\\boldsymbol{\\tilde{y}}=\\boldsymbol{X}\\boldsymbol{\\beta}$. \n", - "\n", - "Thereafter we found the parameters $\\boldsymbol{\\beta}$ by optimizing the means squared error via the so-called cost function" - ] - }, - { - "cell_type": "markdown", - "id": "347294eb", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "C(\\boldsymbol{X},\\boldsymbol{\\beta}) =\\frac{1}{n}\\sum_{i=0}^{n-1}(y_i-\\tilde{y}_i)^2=\\mathbb{E}\\left[(\\boldsymbol{y}-\\boldsymbol{\\tilde{y}})^2\\right].\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "0536e454", - "metadata": { - "editable": true - }, - "source": [ - "We can rewrite this as" - ] - }, - { - "cell_type": "markdown", - "id": "4edf3a9e", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\mathbb{E}\\left[(\\boldsymbol{y}-\\boldsymbol{\\tilde{y}})^2\\right]=\\frac{1}{n}\\sum_i(f_i-\\mathbb{E}\\left[\\boldsymbol{\\tilde{y}}\\right])^2+\\frac{1}{n}\\sum_i(\\tilde{y}_i-\\mathbb{E}\\left[\\boldsymbol{\\tilde{y}}\\right])^2+\\sigma^2.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "95b5e144", - "metadata": { - "editable": true - }, - "source": [ - "The three terms represent the square of the bias of the learning\n", - "method, which can be thought of as the error caused by the simplifying\n", - "assumptions built into the method. The second term represents the\n", - "variance of the chosen model and finally the last terms is variance of\n", - "the error $\\boldsymbol{\\epsilon}$.\n", - "\n", - "To derive this equation, we need to recall that the variance of $\\boldsymbol{y}$ and $\\boldsymbol{\\epsilon}$ are both equal to $\\sigma^2$. The mean value of $\\boldsymbol{\\epsilon}$ is by definition equal to zero. Furthermore, the function $f$ is not a stochastics variable, idem for $\\boldsymbol{\\tilde{y}}$.\n", - "We use a more compact notation in terms of the expectation value" - ] - }, - { - "cell_type": "markdown", - "id": "4ec0202c", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\mathbb{E}\\left[(\\boldsymbol{y}-\\boldsymbol{\\tilde{y}})^2\\right]=\\mathbb{E}\\left[(\\boldsymbol{f}+\\boldsymbol{\\epsilon}-\\boldsymbol{\\tilde{y}})^2\\right],\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "3729c884", - "metadata": { - "editable": true - }, - "source": [ - "and adding and subtracting $\\mathbb{E}\\left[\\boldsymbol{\\tilde{y}}\\right]$ we get" - ] - }, - { - "cell_type": "markdown", - "id": "09d292c0", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\mathbb{E}\\left[(\\boldsymbol{y}-\\boldsymbol{\\tilde{y}})^2\\right]=\\mathbb{E}\\left[(\\boldsymbol{f}+\\boldsymbol{\\epsilon}-\\boldsymbol{\\tilde{y}}+\\mathbb{E}\\left[\\boldsymbol{\\tilde{y}}\\right]-\\mathbb{E}\\left[\\boldsymbol{\\tilde{y}}\\right])^2\\right],\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "9393b969", - "metadata": { - "editable": true - }, - "source": [ - "which, using the abovementioned expectation values can be rewritten as" - ] - }, - { - "cell_type": "markdown", - "id": "31400952", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\mathbb{E}\\left[(\\boldsymbol{y}-\\boldsymbol{\\tilde{y}})^2\\right]=\\mathbb{E}\\left[(\\boldsymbol{y}-\\mathbb{E}\\left[\\boldsymbol{\\tilde{y}}\\right])^2\\right]+\\mathrm{Var}\\left[\\boldsymbol{\\tilde{y}}\\right]+\\sigma^2,\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "fab9fd56", - "metadata": { - "editable": true - }, - "source": [ - "that is the rewriting in terms of the so-called bias, the variance of the model $\\boldsymbol{\\tilde{y}}$ and the variance of $\\boldsymbol{\\epsilon}$." - ] - }, - { - "cell_type": "markdown", - "id": "f6bbceee", - "metadata": { - "editable": true - }, - "source": [ - "## A way to Read the Bias-Variance Tradeoff\n", - "\n", - "\n", - "\n", - "\n", - "

Figure 1:

\n", - "" - ] - }, - { - "cell_type": "markdown", - "id": "2486e572", - "metadata": { - "editable": true - }, - "source": [ - "## Example code for Bias-Variance tradeoff" - ] - }, - { - "cell_type": "code", - "execution_count": 3, - "id": "af100ade", - "metadata": { - "collapsed": false, - "editable": true - }, - "outputs": [], - "source": [ - "import matplotlib.pyplot as plt\n", - "import numpy as np\n", - "from sklearn.linear_model import LinearRegression, Ridge, Lasso\n", - "from sklearn.preprocessing import PolynomialFeatures\n", - "from sklearn.model_selection import train_test_split\n", - "from sklearn.pipeline import make_pipeline\n", - "from sklearn.utils import resample\n", - "\n", - "np.random.seed(2018)\n", - "\n", - "n = 500\n", - "n_boostraps = 100\n", - "degree = 18 # A quite high value, just to show.\n", - "noise = 0.1\n", - "\n", - "# Make data set.\n", - "x = np.linspace(-1, 3, n).reshape(-1, 1)\n", - "y = np.exp(-x**2) + 1.5 * np.exp(-(x-2)**2) + np.random.normal(0, 0.1, x.shape)\n", - "\n", - "# Hold out some test data that is never used in training.\n", - "x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.2)\n", - "\n", - "# Combine x transformation and model into one operation.\n", - "# Not neccesary, but convenient.\n", - "model = make_pipeline(PolynomialFeatures(degree=degree), LinearRegression(fit_intercept=False))\n", - "\n", - "# The following (m x n_bootstraps) matrix holds the column vectors y_pred\n", - "# for each bootstrap iteration.\n", - "y_pred = np.empty((y_test.shape[0], n_boostraps))\n", - "for i in range(n_boostraps):\n", - " x_, y_ = resample(x_train, y_train)\n", - "\n", - " # Evaluate the new model on the same test data each time.\n", - " y_pred[:, i] = model.fit(x_, y_).predict(x_test).ravel()\n", - "\n", - "# Note: Expectations and variances taken w.r.t. different training\n", - "# data sets, hence the axis=1. Subsequent means are taken across the test data\n", - "# set in order to obtain a total value, but before this we have error/bias/variance\n", - "# calculated per data point in the test set.\n", - "# Note 2: The use of keepdims=True is important in the calculation of bias as this \n", - "# maintains the column vector form. Dropping this yields very unexpected results.\n", - "error = np.mean( np.mean((y_test - y_pred)**2, axis=1, keepdims=True) )\n", - "bias = np.mean( (y_test - np.mean(y_pred, axis=1, keepdims=True))**2 )\n", - "variance = np.mean( np.var(y_pred, axis=1, keepdims=True) )\n", - "print('Error:', error)\n", - "print('Bias^2:', bias)\n", - "print('Var:', variance)\n", - "print('{} >= {} + {} = {}'.format(error, bias, variance, bias+variance))\n", - "\n", - "plt.plot(x[::5, :], y[::5, :], label='f(x)')\n", - "plt.scatter(x_test, y_test, label='Data points')\n", - "plt.scatter(x_test, np.mean(y_pred, axis=1), label='Pred')\n", - "plt.legend()\n", - "plt.show()" - ] - }, - { - "cell_type": "markdown", - "id": "e4b4ea82", - "metadata": { - "editable": true - }, - "source": [ - "## Understanding what happens" - ] - }, - { - "cell_type": "code", - "execution_count": 4, - "id": "13bb228b", - "metadata": { - "collapsed": false, - "editable": true - }, - "outputs": [], - "source": [ - "import matplotlib.pyplot as plt\n", - "import numpy as np\n", - "from sklearn.linear_model import LinearRegression, Ridge, Lasso\n", - "from sklearn.preprocessing import PolynomialFeatures\n", - "from sklearn.model_selection import train_test_split\n", - "from sklearn.pipeline import make_pipeline\n", - "from sklearn.utils import resample\n", - "\n", - "np.random.seed(2018)\n", - "\n", - "n = 40\n", - "n_boostraps = 100\n", - "maxdegree = 14\n", - "\n", - "\n", - "# Make data set.\n", - "x = np.linspace(-3, 3, n).reshape(-1, 1)\n", - "y = np.exp(-x**2) + 1.5 * np.exp(-(x-2)**2)+ np.random.normal(0, 0.1, x.shape)\n", - "error = np.zeros(maxdegree)\n", - "bias = np.zeros(maxdegree)\n", - "variance = np.zeros(maxdegree)\n", - "polydegree = np.zeros(maxdegree)\n", - "x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.2)\n", - "\n", - "for degree in range(maxdegree):\n", - " model = make_pipeline(PolynomialFeatures(degree=degree), LinearRegression(fit_intercept=False))\n", - " y_pred = np.empty((y_test.shape[0], n_boostraps))\n", - " for i in range(n_boostraps):\n", - " x_, y_ = resample(x_train, y_train)\n", - " y_pred[:, i] = model.fit(x_, y_).predict(x_test).ravel()\n", - "\n", - " polydegree[degree] = degree\n", - " error[degree] = np.mean( np.mean((y_test - y_pred)**2, axis=1, keepdims=True) )\n", - " bias[degree] = np.mean( (y_test - np.mean(y_pred, axis=1, keepdims=True))**2 )\n", - " variance[degree] = np.mean( np.var(y_pred, axis=1, keepdims=True) )\n", - " print('Polynomial degree:', degree)\n", - " print('Error:', error[degree])\n", - " print('Bias^2:', bias[degree])\n", - " print('Var:', variance[degree])\n", - " print('{} >= {} + {} = {}'.format(error[degree], bias[degree], variance[degree], bias[degree]+variance[degree]))\n", - "\n", - "plt.plot(polydegree, error, label='Error')\n", - "plt.plot(polydegree, bias, label='bias')\n", - "plt.plot(polydegree, variance, label='Variance')\n", - "plt.legend()\n", - "plt.show()" - ] - }, - { - "cell_type": "markdown", - "id": "c50c02c2", - "metadata": { - "editable": true - }, - "source": [ - "## Summing up\n", - "\n", - "The bias-variance tradeoff summarizes the fundamental tension in\n", - "machine learning, particularly supervised learning, between the\n", - "complexity of a model and the amount of training data needed to train\n", - "it. Since data is often limited, in practice it is often useful to\n", - "use a less-complex model with higher bias, that is a model whose asymptotic\n", - "performance is worse than another model because it is easier to\n", - "train and less sensitive to sampling noise arising from having a\n", - "finite-sized training dataset (smaller variance). \n", - "\n", - "The above equations tell us that in\n", - "order to minimize the expected test error, we need to select a\n", - "statistical learning method that simultaneously achieves low variance\n", - "and low bias. Note that variance is inherently a nonnegative quantity,\n", - "and squared bias is also nonnegative. Hence, we see that the expected\n", - "test MSE can never lie below $Var(\\epsilon)$, the irreducible error.\n", - "\n", - "What do we mean by the variance and bias of a statistical learning\n", - "method? The variance refers to the amount by which our model would change if we\n", - "estimated it using a different training data set. Since the training\n", - "data are used to fit the statistical learning method, different\n", - "training data sets will result in a different estimate. But ideally the\n", - "estimate for our model should not vary too much between training\n", - "sets. However, if a method has high variance then small changes in\n", - "the training data can result in large changes in the model. In general, more\n", - "flexible statistical methods have higher variance.\n", - "\n", - "You may also find this recent [article](https://www.pnas.org/content/116/32/15849) of interest." - ] - }, - { - "cell_type": "markdown", - "id": "16a69276", - "metadata": { - "editable": true - }, - "source": [ - "## Another Example from Scikit-Learn's Repository" - ] - }, - { - "cell_type": "code", - "execution_count": 5, - "id": "06c4dbd1", - "metadata": { - "collapsed": false, - "editable": true - }, - "outputs": [], - "source": [ - "\"\"\"\n", - "============================\n", - "Underfitting vs. Overfitting\n", - "============================\n", - "\n", - "This example demonstrates the problems of underfitting and overfitting and\n", - "how we can use linear regression with polynomial features to approximate\n", - "nonlinear functions. The plot shows the function that we want to approximate,\n", - "which is a part of the cosine function. In addition, the samples from the\n", - "real function and the approximations of different models are displayed. The\n", - "models have polynomial features of different degrees. We can see that a\n", - "linear function (polynomial with degree 1) is not sufficient to fit the\n", - "training samples. This is called **underfitting**. A polynomial of degree 4\n", - "approximates the true function almost perfectly. However, for higher degrees\n", - "the model will **overfit** the training data, i.e. it learns the noise of the\n", - "training data.\n", - "We evaluate quantitatively **overfitting** / **underfitting** by using\n", - "cross-validation. We calculate the mean squared error (MSE) on the validation\n", - "set, the higher, the less likely the model generalizes correctly from the\n", - "training data.\n", - "\"\"\"\n", - "\n", - "print(__doc__)\n", - "\n", - "import numpy as np\n", - "import matplotlib.pyplot as plt\n", - "from sklearn.pipeline import Pipeline\n", - "from sklearn.preprocessing import PolynomialFeatures\n", - "from sklearn.linear_model import LinearRegression\n", - "from sklearn.model_selection import cross_val_score\n", - "\n", - "\n", - "def true_fun(X):\n", - " return np.cos(1.5 * np.pi * X)\n", - "\n", - "np.random.seed(0)\n", - "\n", - "n_samples = 30\n", - "degrees = [1, 4, 15]\n", - "\n", - "X = np.sort(np.random.rand(n_samples))\n", - "y = true_fun(X) + np.random.randn(n_samples) * 0.1\n", - "\n", - "plt.figure(figsize=(14, 5))\n", - "for i in range(len(degrees)):\n", - " ax = plt.subplot(1, len(degrees), i + 1)\n", - " plt.setp(ax, xticks=(), yticks=())\n", - "\n", - " polynomial_features = PolynomialFeatures(degree=degrees[i],\n", - " include_bias=False)\n", - " linear_regression = LinearRegression()\n", - " pipeline = Pipeline([(\"polynomial_features\", polynomial_features),\n", - " (\"linear_regression\", linear_regression)])\n", - " pipeline.fit(X[:, np.newaxis], y)\n", - "\n", - " # Evaluate the models using crossvalidation\n", - " scores = cross_val_score(pipeline, X[:, np.newaxis], y,\n", - " scoring=\"neg_mean_squared_error\", cv=10)\n", - "\n", - " X_test = np.linspace(0, 1, 100)\n", - " plt.plot(X_test, pipeline.predict(X_test[:, np.newaxis]), label=\"Model\")\n", - " plt.plot(X_test, true_fun(X_test), label=\"True function\")\n", - " plt.scatter(X, y, edgecolor='b', s=20, label=\"Samples\")\n", - " plt.xlabel(\"x\")\n", - " plt.ylabel(\"y\")\n", - " plt.xlim((0, 1))\n", - " plt.ylim((-2, 2))\n", - " plt.legend(loc=\"best\")\n", - " plt.title(\"Degree {}\\nMSE = {:.2e}(+/- {:.2e})\".format(\n", - " degrees[i], -scores.mean(), scores.std()))\n", - "plt.show()" - ] - }, - { - "cell_type": "markdown", - "id": "dd22f4e5", - "metadata": { - "editable": true - }, - "source": [ - "## Various steps in cross-validation\n", - "\n", - "When the repetitive splitting of the data set is done randomly,\n", - "samples may accidently end up in a fast majority of the splits in\n", - "either training or test set. Such samples may have an unbalanced\n", - "influence on either model building or prediction evaluation. To avoid\n", - "this $k$-fold cross-validation structures the data splitting. The\n", - "samples are divided into $k$ more or less equally sized exhaustive and\n", - "mutually exclusive subsets. In turn (at each split) one of these\n", - "subsets plays the role of the test set while the union of the\n", - "remaining subsets constitutes the training set. Such a splitting\n", - "warrants a balanced representation of each sample in both training and\n", - "test set over the splits. Still the division into the $k$ subsets\n", - "involves a degree of randomness. This may be fully excluded when\n", - "choosing $k=n$. This particular case is referred to as leave-one-out\n", - "cross-validation (LOOCV)." - ] - }, - { - "cell_type": "markdown", - "id": "1d78f931", - "metadata": { - "editable": true - }, - "source": [ - "## Cross-validation in brief\n", - "\n", - "For the various values of $k$\n", - "\n", - "1. shuffle the dataset randomly.\n", - "\n", - "2. Split the dataset into $k$ groups.\n", - "\n", - "3. For each unique group:\n", - "\n", - "a. Decide which group to use as set for test data\n", - "\n", - "b. Take the remaining groups as a training data set\n", - "\n", - "c. Fit a model on the training set and evaluate it on the test set\n", - "\n", - "d. Retain the evaluation score and discard the model\n", - "\n", - "5. Summarize the model using the sample of model evaluation scores" - ] - }, - { - "cell_type": "markdown", - "id": "a3e7ddb7", - "metadata": { - "editable": true - }, - "source": [ - "## Code Example for Cross-validation and $k$-fold Cross-validation\n", - "\n", - "The code here uses Ridge regression with cross-validation (CV) resampling and $k$-fold CV in order to fit a specific polynomial." - ] - }, - { - "cell_type": "code", - "execution_count": 6, - "id": "d7f6476c", - "metadata": { - "collapsed": false, - "editable": true - }, - "outputs": [], - "source": [ - "import numpy as np\n", - "import matplotlib.pyplot as plt\n", - "from sklearn.model_selection import KFold\n", - "from sklearn.linear_model import Ridge\n", - "from sklearn.model_selection import cross_val_score\n", - "from sklearn.preprocessing import PolynomialFeatures\n", - "\n", - "# A seed just to ensure that the random numbers are the same for every run.\n", - "# Useful for eventual debugging.\n", - "np.random.seed(3155)\n", - "\n", - "# Generate the data.\n", - "nsamples = 100\n", - "x = np.random.randn(nsamples)\n", - "y = 3*x**2 + np.random.randn(nsamples)\n", - "\n", - "## Cross-validation on Ridge regression using KFold only\n", - "\n", - "# Decide degree on polynomial to fit\n", - "poly = PolynomialFeatures(degree = 6)\n", - "\n", - "# Decide which values of lambda to use\n", - "nlambdas = 500\n", - "lambdas = np.logspace(-3, 5, nlambdas)\n", - "\n", - "# Initialize a KFold instance\n", - "k = 5\n", - "kfold = KFold(n_splits = k)\n", - "\n", - "# Perform the cross-validation to estimate MSE\n", - "scores_KFold = np.zeros((nlambdas, k))\n", - "\n", - "i = 0\n", - "for lmb in lambdas:\n", - " ridge = Ridge(alpha = lmb)\n", - " j = 0\n", - " for train_inds, test_inds in kfold.split(x):\n", - " xtrain = x[train_inds]\n", - " ytrain = y[train_inds]\n", - "\n", - " xtest = x[test_inds]\n", - " ytest = y[test_inds]\n", - "\n", - " Xtrain = poly.fit_transform(xtrain[:, np.newaxis])\n", - " ridge.fit(Xtrain, ytrain[:, np.newaxis])\n", - "\n", - " Xtest = poly.fit_transform(xtest[:, np.newaxis])\n", - " ypred = ridge.predict(Xtest)\n", - "\n", - " scores_KFold[i,j] = np.sum((ypred - ytest[:, np.newaxis])**2)/np.size(ypred)\n", - "\n", - " j += 1\n", - " i += 1\n", - "\n", - "\n", - "estimated_mse_KFold = np.mean(scores_KFold, axis = 1)\n", - "\n", - "## Cross-validation using cross_val_score from sklearn along with KFold\n", - "\n", - "# kfold is an instance initialized above as:\n", - "# kfold = KFold(n_splits = k)\n", - "\n", - "estimated_mse_sklearn = np.zeros(nlambdas)\n", - "i = 0\n", - "for lmb in lambdas:\n", - " ridge = Ridge(alpha = lmb)\n", - "\n", - " X = poly.fit_transform(x[:, np.newaxis])\n", - " estimated_mse_folds = cross_val_score(ridge, X, y[:, np.newaxis], scoring='neg_mean_squared_error', cv=kfold)\n", - "\n", - " # cross_val_score return an array containing the estimated negative mse for every fold.\n", - " # we have to the the mean of every array in order to get an estimate of the mse of the model\n", - " estimated_mse_sklearn[i] = np.mean(-estimated_mse_folds)\n", - "\n", - " i += 1\n", - "\n", - "## Plot and compare the slightly different ways to perform cross-validation\n", - "\n", - "plt.figure()\n", - "\n", - "plt.plot(np.log10(lambdas), estimated_mse_sklearn, label = 'cross_val_score')\n", - "plt.plot(np.log10(lambdas), estimated_mse_KFold, 'r--', label = 'KFold')\n", - "\n", - "plt.xlabel('log10(lambda)')\n", - "plt.ylabel('mse')\n", - "\n", - "plt.legend()\n", - "\n", - "plt.show()" - ] - }, - { - "cell_type": "markdown", - "id": "29f97a19", - "metadata": { - "editable": true - }, - "source": [ - "## More examples on bootstrap and cross-validation and errors" - ] - }, - { - "cell_type": "code", - "execution_count": 7, - "id": "ea778a04", - "metadata": { - "collapsed": false, - "editable": true - }, - "outputs": [], - "source": [ - "# Common imports\n", - "import os\n", - "import numpy as np\n", - "import pandas as pd\n", - "import matplotlib.pyplot as plt\n", - "from sklearn.linear_model import LinearRegression, Ridge, Lasso\n", - "from sklearn.model_selection import train_test_split\n", - "from sklearn.utils import resample\n", - "from sklearn.metrics import mean_squared_error\n", - "# Where to save the figures and data files\n", - "PROJECT_ROOT_DIR = \"Results\"\n", - "FIGURE_ID = \"Results/FigureFiles\"\n", - "DATA_ID = \"DataFiles/\"\n", - "\n", - "if not os.path.exists(PROJECT_ROOT_DIR):\n", - " os.mkdir(PROJECT_ROOT_DIR)\n", - "\n", - "if not os.path.exists(FIGURE_ID):\n", - " os.makedirs(FIGURE_ID)\n", - "\n", - "if not os.path.exists(DATA_ID):\n", - " os.makedirs(DATA_ID)\n", - "\n", - "def image_path(fig_id):\n", - " return os.path.join(FIGURE_ID, fig_id)\n", - "\n", - "def data_path(dat_id):\n", - " return os.path.join(DATA_ID, dat_id)\n", - "\n", - "def save_fig(fig_id):\n", - " plt.savefig(image_path(fig_id) + \".png\", format='png')\n", - "\n", - "infile = open(data_path(\"EoS.csv\"),'r')\n", - "\n", - "# Read the EoS data as csv file and organize the data into two arrays with density and energies\n", - "EoS = pd.read_csv(infile, names=('Density', 'Energy'))\n", - "EoS['Energy'] = pd.to_numeric(EoS['Energy'], errors='coerce')\n", - "EoS = EoS.dropna()\n", - "Energies = EoS['Energy']\n", - "Density = EoS['Density']\n", - "# The design matrix now as function of various polytrops\n", - "\n", - "Maxpolydegree = 30\n", - "X = np.zeros((len(Density),Maxpolydegree))\n", - "X[:,0] = 1.0\n", - "testerror = np.zeros(Maxpolydegree)\n", - "trainingerror = np.zeros(Maxpolydegree)\n", - "polynomial = np.zeros(Maxpolydegree)\n", - "\n", - "trials = 100\n", - "for polydegree in range(1, Maxpolydegree):\n", - " polynomial[polydegree] = polydegree\n", - " for degree in range(polydegree):\n", - " X[:,degree] = Density**(degree/3.0)\n", - "\n", - "# loop over trials in order to estimate the expectation value of the MSE\n", - " testerror[polydegree] = 0.0\n", - " trainingerror[polydegree] = 0.0\n", - " for samples in range(trials):\n", - " x_train, x_test, y_train, y_test = train_test_split(X, Energies, test_size=0.2)\n", - " model = LinearRegression(fit_intercept=False).fit(x_train, y_train)\n", - " ypred = model.predict(x_train)\n", - " ytilde = model.predict(x_test)\n", - " testerror[polydegree] += mean_squared_error(y_test, ytilde)\n", - " trainingerror[polydegree] += mean_squared_error(y_train, ypred) \n", - "\n", - " testerror[polydegree] /= trials\n", - " trainingerror[polydegree] /= trials\n", - " print(\"Degree of polynomial: %3d\"% polynomial[polydegree])\n", - " print(\"Mean squared error on training data: %.8f\" % trainingerror[polydegree])\n", - " print(\"Mean squared error on test data: %.8f\" % testerror[polydegree])\n", - "\n", - "plt.plot(polynomial, np.log10(trainingerror), label='Training Error')\n", - "plt.plot(polynomial, np.log10(testerror), label='Test Error')\n", - "plt.xlabel('Polynomial degree')\n", - "plt.ylabel('log10[MSE]')\n", - "plt.legend()\n", - "plt.show()" - ] - }, - { - "cell_type": "markdown", - "id": "f5bc26cd", - "metadata": { - "editable": true - }, - "source": [ - "Note that we kept the intercept column in the fitting here. This means that we need to set the **intercept** in the call to the **Scikit-Learn** function as **False**. Alternatively, we could have set up the design matrix $X$ without the first column of ones." - ] - }, - { - "cell_type": "markdown", - "id": "4bbb49da", - "metadata": { - "editable": true - }, - "source": [ - "## The same example but now with cross-validation\n", - "\n", - "In this example we keep the intercept column again but add cross-validation in order to estimate the best possible value of the means squared error." - ] - }, - { - "cell_type": "code", - "execution_count": 8, - "id": "89f26923", - "metadata": { - "collapsed": false, - "editable": true - }, - "outputs": [], - "source": [ - "# Common imports\n", - "import os\n", - "import numpy as np\n", - "import pandas as pd\n", - "import matplotlib.pyplot as plt\n", - "from sklearn.linear_model import LinearRegression, Ridge, Lasso\n", - "from sklearn.metrics import mean_squared_error\n", - "from sklearn.model_selection import KFold\n", - "from sklearn.model_selection import cross_val_score\n", - "\n", - "\n", - "# Where to save the figures and data files\n", - "PROJECT_ROOT_DIR = \"Results\"\n", - "FIGURE_ID = \"Results/FigureFiles\"\n", - "DATA_ID = \"DataFiles/\"\n", - "\n", - "if not os.path.exists(PROJECT_ROOT_DIR):\n", - " os.mkdir(PROJECT_ROOT_DIR)\n", - "\n", - "if not os.path.exists(FIGURE_ID):\n", - " os.makedirs(FIGURE_ID)\n", - "\n", - "if not os.path.exists(DATA_ID):\n", - " os.makedirs(DATA_ID)\n", - "\n", - "def image_path(fig_id):\n", - " return os.path.join(FIGURE_ID, fig_id)\n", - "\n", - "def data_path(dat_id):\n", - " return os.path.join(DATA_ID, dat_id)\n", - "\n", - "def save_fig(fig_id):\n", - " plt.savefig(image_path(fig_id) + \".png\", format='png')\n", - "\n", - "infile = open(data_path(\"EoS.csv\"),'r')\n", - "\n", - "# Read the EoS data as csv file and organize the data into two arrays with density and energies\n", - "EoS = pd.read_csv(infile, names=('Density', 'Energy'))\n", - "EoS['Energy'] = pd.to_numeric(EoS['Energy'], errors='coerce')\n", - "EoS = EoS.dropna()\n", - "Energies = EoS['Energy']\n", - "Density = EoS['Density']\n", - "# The design matrix now as function of various polytrops\n", - "\n", - "Maxpolydegree = 30\n", - "X = np.zeros((len(Density),Maxpolydegree))\n", - "X[:,0] = 1.0\n", - "estimated_mse_sklearn = np.zeros(Maxpolydegree)\n", - "polynomial = np.zeros(Maxpolydegree)\n", - "k =5\n", - "kfold = KFold(n_splits = k)\n", - "\n", - "for polydegree in range(1, Maxpolydegree):\n", - " polynomial[polydegree] = polydegree\n", - " for degree in range(polydegree):\n", - " X[:,degree] = Density**(degree/3.0)\n", - " OLS = LinearRegression(fit_intercept=False)\n", - "# loop over trials in order to estimate the expectation value of the MSE\n", - " estimated_mse_folds = cross_val_score(OLS, X, Energies, scoring='neg_mean_squared_error', cv=kfold)\n", - "#[:, np.newaxis]\n", - " estimated_mse_sklearn[polydegree] = np.mean(-estimated_mse_folds)\n", - "\n", - "plt.plot(polynomial, np.log10(estimated_mse_sklearn), label='Test Error')\n", - "plt.xlabel('Polynomial degree')\n", - "plt.ylabel('log10[MSE]')\n", - "plt.legend()\n", - "plt.show()" - ] - }, - { - "cell_type": "markdown", - "id": "3d39d1c9", - "metadata": { - "editable": true - }, - "source": [ - "## Notes on scaling with examples\n", - "\n", - "The programs here use both ordinrary least squares (OLS) and Ridge\n", - "regression with one value only for the hyperparameter $\\lambda$. The\n", - "first example has no scaling and includes the intercept as well and we\n", - "are trying to fit a second-order polynomial. The second code takes out\n", - "the intercept and subtracts the mean values of each column of the\n", - "design matrix and the mean value of the outputs.\n", - "\n", - "The third and final code uses **Scikit-Learn** as library in order to\n", - "calculate the optimal parameters for OLS and Ridge regression. Note\n", - "that it is highly recommended to not include the intercept in Ridge\n", - "and Lasso regression, in order to avoid penalizing the optimization by\n", - "the intercept. The second and third codes do thus not include the\n", - "intercept. In the second code we do the scaling ourselves while the\n", - "last code uses the standard scaler option included in **Scikit-Learn**, known as centering (where\n", - "we subtract the mean values)." - ] - }, - { - "cell_type": "code", - "execution_count": 9, - "id": "2470e6f1", - "metadata": { - "collapsed": false, - "editable": true - }, - "outputs": [], - "source": [ - "import matplotlib.pyplot as plt\n", - "import numpy as np\n", - "from sklearn.linear_model import LinearRegression\n", - "from sklearn.preprocessing import PolynomialFeatures\n", - "from sklearn.model_selection import train_test_split\n", - "from sklearn.preprocessing import StandardScaler\n", - "\n", - "def MSE(y_data,y_model):\n", - " n = np.size(y_model)\n", - " return np.sum((y_data-y_model)**2)/n\n", - "\n", - "def OLS_fit_beta(X, y):\n", - " return np.linalg.pinv(X.T @ X) @ X.T @ y\n", - "\n", - "def Ridge_fit_beta(X, y,L,d):\n", - " I = np.eye(d,d)\n", - " return np.linalg.pinv(X.T @ X + L*I) @ X.T @ y\n", - "\n", - "# Same random numbers for each test.\n", - "np.random.seed(2018)\n", - "n = 100\n", - "d = 3\n", - "# hyperparameter lambda\n", - "Lambda = 0.01\n", - "\n", - "# Make data set, simple second-order polynomial\n", - "x = np.linspace(-3, 3, n)\n", - "y = 2.0 + 0.5*x + 5.0*(x**2)+ np.random.randn(n)\n", - "\n", - "# The design matrix X includes the intercept and no scaling is made\n", - "X = np.zeros((len(x), d))\n", - "for p in range(d): \n", - " X[:, p] = x ** (p) \n", - "\n", - "\n", - "#Split data, no scaling is used and we include the intercept\n", - "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2)\n", - "\n", - "\n", - "#Calculate beta, own code\n", - "beta_OLS = OLS_fit_beta(X_train, y_train)\n", - "beta_Ridge = Ridge_fit_beta(X_train, y_train,Lambda,d)\n", - "print(beta_OLS)\n", - "print(beta_Ridge)\n", - "#predict value\n", - "ytilde_test_OLS = X_test @ beta_OLS\n", - "ytilde_test_Ridge = X_test @ beta_Ridge\n", - "\n", - "#Calculate MSE\n", - "print(\" \")\n", - "print(\"test MSE of OLS:\")\n", - "print(MSE(y_test,ytilde_test_OLS))\n", - "print(\" \")\n", - "print(\"test MSE of Ridge\")\n", - "print(MSE(y_test,ytilde_test_Ridge))\n", - "\n", - "plt.scatter(x,y,label='Data')\n", - "plt.plot(x, X @ beta_OLS,'*', label=\"OLS_Fit\")\n", - "plt.plot(x, X @ beta_Ridge, label=\"Ridge_Fit\")\n", - "plt.grid()\n", - "plt.legend()\n", - "plt.show()" - ] - }, - { - "cell_type": "markdown", - "id": "3e229ae7", - "metadata": { - "editable": true - }, - "source": [ - "In this example we do not include the intercept and we scale the data by subtracting the mean values. This follows the discussion in the [lecture material](https://compphysics.github.io/MachineLearning/doc/LectureNotes/_build/html/chapter3.html#more-on-rescaling-data).\n", - "see also the weekly slides [for week 36](https://compphysics.github.io/MachineLearning/doc/pub/week36/html/._week36-bs029.html).\n", - "It is recommended whrn we use Ridge and Lasso regression to not include the intercept in the optimization process.\n", - "\n", - "Before we discuss the code, we repeat some of the basic math from the slides of week 36.\n", - "\n", - "Let us try to understand what this may imply mathematically when we\n", - "subtract the mean values, also known as *zero centering* or simply *centering*. For\n", - "simplicity, we will focus on ordinary regression, as done in the above example.\n", - "\n", - "The cost/loss function for regression is" - ] - }, - { - "cell_type": "markdown", - "id": "2d43d360", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "C(\\beta_0, \\beta_1, ... , \\beta_{p-1}) = \\frac{1}{n}\\sum_{i=0}^{n} \\left(y_i - \\beta_0 - \\sum_{j=1}^{p-1} X_{ij}\\beta_j\\right)^2,.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "777c97c9", - "metadata": { - "editable": true - }, - "source": [ - "Recall also that we use the squared value. This expression can lead to an\n", - "increased penalty for higher differences between predicted and\n", - "output/target values.\n", - "\n", - "What we have done is to single out the $\\beta_0$ term in the\n", - "definition of the mean squared error (MSE). The design matrix $X$\n", - "does in this case not contain any intercept column. When we take the\n", - "derivative with respect to $\\beta_0$, we want the derivative to obey" - ] - }, - { - "cell_type": "markdown", - "id": "f464bb58", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\frac{\\partial C}{\\partial \\beta_j} = 0,\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "624b1d2c", - "metadata": { - "editable": true - }, - "source": [ - "for all $j$. For $\\beta_0$ we have" - ] - }, - { - "cell_type": "markdown", - "id": "b872d2db", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\frac{\\partial C}{\\partial \\beta_0} = -\\frac{2}{n}\\sum_{i=0}^{n-1} \\left(y_i - \\beta_0 - \\sum_{j=1}^{p-1} X_{ij} \\beta_j\\right).\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "d6dd0d07", - "metadata": { - "editable": true - }, - "source": [ - "Multiplying away the constant $2/n$, we obtain" - ] - }, - { - "cell_type": "markdown", - "id": "2f7c34ed", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\sum_{i=0}^{n-1} \\beta_0 = \\sum_{i=0}^{n-1}y_i - \\sum_{i=0}^{n-1} \\sum_{j=1}^{p-1} X_{ij} \\beta_j.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "7e06d400", - "metadata": { - "editable": true - }, - "source": [ - "Let us specialize first to the case where we have only two parameters $\\beta_0$ and $\\beta_1$.\n", - "Our result for $\\beta_0$ simplifies then to" - ] - }, - { - "cell_type": "markdown", - "id": "bad7ab31", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "n\\beta_0 = \\sum_{i=0}^{n-1}y_i - \\sum_{i=0}^{n-1} X_{i1} \\beta_1.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "b11fd1d0", - "metadata": { - "editable": true - }, - "source": [ - "We obtain then" - ] - }, - { - "cell_type": "markdown", - "id": "e18f186d", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\beta_0 = \\frac{1}{n}\\sum_{i=0}^{n-1}y_i - \\beta_1\\frac{1}{n}\\sum_{i=0}^{n-1} X_{i1}.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "002f906f", - "metadata": { - "editable": true - }, - "source": [ - "If we define" - ] - }, - { - "cell_type": "markdown", - "id": "4b2ce40a", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\mu_{\\boldsymbol{x}_1}=\\frac{1}{n}\\sum_{i=0}^{n-1} X_{i1},\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "6f6da2aa", - "metadata": { - "editable": true - }, - "source": [ - "and the mean value of the outputs as" - ] - }, - { - "cell_type": "markdown", - "id": "f8705ff4", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\mu_y=\\frac{1}{n}\\sum_{i=0}^{n-1}y_i,\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "481c0458", - "metadata": { - "editable": true - }, - "source": [ - "we have" - ] - }, - { - "cell_type": "markdown", - "id": "de837aab", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\beta_0 = \\mu_y - \\beta_1\\mu_{\\boldsymbol{x}_1}.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "2c151900", - "metadata": { - "editable": true - }, - "source": [ - "In the general case with more parameters than $\\beta_0$ and $\\beta_1$, we have" - ] - }, - { - "cell_type": "markdown", - "id": "6df6dc61", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\beta_0 = \\frac{1}{n}\\sum_{i=0}^{n-1}y_i - \\frac{1}{n}\\sum_{i=0}^{n-1}\\sum_{j=1}^{p-1} X_{ij}\\beta_j.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "6d6150d9", - "metadata": { - "editable": true - }, - "source": [ - "We can rewrite the latter equation as" - ] - }, - { - "cell_type": "markdown", - "id": "904ad761", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\beta_0 = \\frac{1}{n}\\sum_{i=0}^{n-1}y_i - \\sum_{j=1}^{p-1} \\mu_{\\boldsymbol{x}_j}\\beta_j,\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "0e427a81", - "metadata": { - "editable": true - }, - "source": [ - "where we have defined" - ] - }, - { - "cell_type": "markdown", - "id": "d40dc5aa", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\mu_{\\boldsymbol{x}_j}=\\frac{1}{n}\\sum_{i=0}^{n-1} X_{ij},\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "259f8a07", - "metadata": { - "editable": true - }, - "source": [ - "the mean value for all elements of the column vector $\\boldsymbol{x}_j$.\n", - "\n", - "Replacing $y_i$ with $y_i - y_i - \\overline{\\boldsymbol{y}}$ and centering also our design matrix results in a cost function (in vector-matrix disguise)" - ] - }, - { - "cell_type": "markdown", - "id": "be7a32a4", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "C(\\boldsymbol{\\beta}) = (\\boldsymbol{\\tilde{y}} - \\tilde{X}\\boldsymbol{\\beta})^T(\\boldsymbol{\\tilde{y}} - \\tilde{X}\\boldsymbol{\\beta}).\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "e1723452", - "metadata": { - "editable": true - }, - "source": [ - "If we minimize with respect to $\\boldsymbol{\\beta}$ we have then" - ] - }, - { - "cell_type": "markdown", - "id": "a8979b1c", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\hat{\\boldsymbol{\\beta}} = (\\tilde{X}^T\\tilde{X})^{-1}\\tilde{X}^T\\boldsymbol{\\tilde{y}},\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "7c9b9a4d", - "metadata": { - "editable": true - }, - "source": [ - "where $\\boldsymbol{\\tilde{y}} = \\boldsymbol{y} - \\overline{\\boldsymbol{y}}$\n", - "and $\\tilde{X}_{ij} = X_{ij} - \\frac{1}{n}\\sum_{k=0}^{n-1}X_{kj}$.\n", - "\n", - "For Ridge regression we need to add $\\lambda \\boldsymbol{\\beta}^T\\boldsymbol{\\beta}$ to the cost function and get then" - ] - }, - { - "cell_type": "markdown", - "id": "6daf72ea", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\hat{\\boldsymbol{\\beta}} = (\\tilde{X}^T\\tilde{X} + \\lambda I)^{-1}\\tilde{X}^T\\boldsymbol{\\tilde{y}}.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "23161172", - "metadata": { - "editable": true - }, - "source": [ - "Now we try to implement this." - ] - }, - { - "cell_type": "code", - "execution_count": 10, - "id": "9b9f556f", - "metadata": { - "collapsed": false, - "editable": true - }, - "outputs": [], - "source": [ - "\n", - "np.random.seed(2018)\n", - "n = 100\n", - "# we do not include the intercept\n", - "d = 2\n", - "Lambda = 0.01\n", - "\n", - "# Make data set.\n", - "x = np.linspace(-3, 3, n)\n", - "y = 2.0 + 0.5*x + 5.0*(x**2)+ np.random.randn(n)\n", - "\n", - "#Design matrix X does not include the intercept. \n", - "X = np.zeros((len(x), d))\n", - "for p in range(d): \n", - " X[:, p] = x ** (p+1)\n", - "\n", - "\n", - "#Split data in train and test\n", - "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2)\n", - "\n", - "# Scale data by subtracting mean value,own implementation\n", - "#For our own implementation, we will need to deal with the intercept by centering the design matrix and the target variable\n", - "X_train_mean = np.mean(X_train,axis=0)\n", - "#Center by removing mean from each feature\n", - "X_train_scaled = X_train - X_train_mean\n", - "X_test_scaled = X_test - X_train_mean\n", - "#The model intercept (called y_scaler) is given by the mean of the target variable (IF X is centered, note)\n", - "y_scaler = np.mean(y_train)\n", - "y_train_scaled = y_train - y_scaler\n", - "\n", - "\n", - "#Calculate beta\n", - "beta_OLS = OLS_fit_beta(X_train_scaled, y_train_scaled)\n", - "beta_Ridge = Ridge_fit_beta(X_train_scaled, y_train_scaled,Lambda,d)\n", - "print(beta_OLS)\n", - "print(beta_Ridge)\n", - "# calculate intercepts and print them\n", - "interceptOLS = y_scaler - X_train_mean @ beta_OLS\n", - "interceptRidge = y_scaler - X_train_mean @ beta_Ridge\n", - "print(interceptOLS)\n", - "print(interceptRidge)\n", - "\n", - "#predict value with intercept\n", - "ytilde_test_OLS = X_test_scaled @ beta_OLS+y_scaler\n", - "ytilde_test_Ridge = X_test_scaled @ beta_Ridge+y_scaler\n", - "\n", - "\n", - "#Calculate MSE\n", - "\n", - "print(\" \")\n", - "print(\"test MSE of OLS:\")\n", - "print(MSE(y_test,ytilde_test_OLS))\n", - "print(\" \")\n", - "print(\"test MSE of Ridge\")\n", - "print(MSE(y_test,ytilde_test_Ridge))\n", - "\n", - "plt.scatter(x,y,label='Data')\n", - "plt.plot(x, X @ beta_OLS+interceptOLS,'*', label=\"OLS_Fit\")\n", - "plt.plot(x, X @ beta_Ridge+interceptRidge, label=\"Ridge_Fit\")\n", - "plt.grid()\n", - "plt.legend()\n", - "plt.show()" - ] - }, - { - "cell_type": "markdown", - "id": "b0a158df", - "metadata": { - "editable": true - }, - "source": [ - "Finally, instead of using our own function we repeat the same example\n", - "using the **standardscaler** functionality of the library\n", - "**Scikit-Learn**. Here we limit ourselves to Ridge regression only." - ] - }, - { - "cell_type": "code", - "execution_count": 11, - "id": "911c4d30", - "metadata": { - "collapsed": false, - "editable": true - }, - "outputs": [], - "source": [ - "from sklearn import linear_model\n", - "np.random.seed(2018)\n", - "n = 10\n", - "d = 2\n", - "Lambda = 0.01\n", - "\n", - "# Make data set.\n", - "x = np.linspace(-3, 3, n)\n", - "y = 2.0 + 0.5*x + 5.0*(x**2)+ np.random.randn(n)\n", - "\n", - "# Design matrix X does not include the intercept. \n", - "X = np.zeros((n, d))\n", - "for p in range(d): \n", - " X[:, p] = x ** (p+1)\n", - "\n", - "#Split data in train and test\n", - "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2)\n", - "# Scale data by subtracting mean value of the input using scikit-learn\n", - "scaler = StandardScaler(with_std=False)\n", - "scaler.fit(X_train)\n", - "X_train_mean = np.mean(X_train,axis=0)\n", - "X_train_scaled = scaler.transform(X_train)\n", - "X_test_scaled = scaler.transform(X_test)\n", - "# We scale also the output, here by our own code\n", - "y_scaler = np.mean(y_train)\n", - "y_train_scaled = y_train - y_scaler\n", - "y_test_scaled = y_test- y_scaler\n", - "\n", - "#Calculate beta\n", - "OLS = LinearRegression()\n", - "betaOLS=OLS.fit(X_train_scaled,y_train_scaled)\n", - "ypredictOLS = OLS.predict(X_test_scaled)\n", - "linear_model.Ridge(Lambda)\n", - "RegRidge.fit(X_train_scaled,y_train_scaled)\n", - "ypredictRidge = RegRidge.predict(X_test_scaled)\n", - "betaOLS = OLS.coef_\n", - "betaRidge = RegRidge.coef_\n", - "print(betaOLS)\n", - "print(betaRidge)\n", - "interceptOLS = np.mean(y_train) - X_train_mean @ betaOLS\n", - "interceptRidge = y_scaler - X_train_mean @ betaRidge\n", - "print(interceptOLS)\n", - "print(interceptRidge)\n", - "#predict value \n", - "ytilde_test_Ridge = X_test_scaled @ betaRidge+y_scaler\n", - "ytilde_test_OLS = X_test_scaled @ betaOLS+y_scaler\n", - "\n", - "#Calculate MSE\n", - "print(\" \")\n", - "print(\"test MSE of OLS\")\n", - "print(MSE(y_test,ytilde_test_OLS))\n", - "print(\" \")\n", - "print(\"test MSE of Ridge\")\n", - "print(MSE(y_test,ytilde_test_Ridge))\n", - "plt.scatter(x,y,label='Data')\n", - "plt.plot(x, X @ RegRidge.coef_ + RegRidge.intercept_ , label=\"Ridge_Fit\")\n", - "plt.grid()\n", - "plt.legend()\n", - "plt.show()" - ] - } - ], - "metadata": {}, - "nbformat": 4, - "nbformat_minor": 5 -} diff --git a/doc/LectureNotes/week38.ipynb b/doc/LectureNotes/week38.ipynb deleted file mode 100644 index a9e42c232..000000000 --- a/doc/LectureNotes/week38.ipynb +++ /dev/null @@ -1,3014 +0,0 @@ -{ - "cells": [ - { - "cell_type": "markdown", - "id": "92c39815", - "metadata": { - "editable": true - }, - "source": [ - "\n", - "" - ] - }, - { - "cell_type": "markdown", - "id": "c28ac15e", - "metadata": { - "editable": true - }, - "source": [ - "# Week 38: Logistic Regression and Optimization\n", - "**Morten Hjorth-Jensen**, Department of Physics and Center for Computing in Science Education, University of Oslo and Department of Physics and Astronomy and Facility for Rare Isotope Beams, Michigan State University\n", - "\n", - "Date: **September 18-22**" - ] - }, - { - "cell_type": "markdown", - "id": "04bf16b5", - "metadata": { - "editable": true - }, - "source": [ - "## Plans for week 38\n", - "\n", - "**Material for the active learning sessions on Tuesday and Wednesday.**\n", - "\n", - " * Lecture from last week on the bias-variance tradeoff\n", - "\n", - " * Resampling techniques, cross-validation examples included here, see also the lectures from last week on the bootstrap method\n", - "\n", - " * Exercise for week 38, see also the whiteboard notes from week 37 at \n", - "\n", - " * Work on project 1, in particular resampling methods like cross-validation and bootstrap.\n", - "\n", - " \n", - "**Material for the lecture on Thursday September 21.**\n", - "\n", - " * Logistic regression as our first encounter of classification methods. From binary cases to several categories.\n", - "\n", - " * Start gradient and optimization methods\n", - "\n", - " * Readings and Videos:\n", - "\n", - " * Hastie et al 4.1, 4.2 and 4.3 on logistic regression\n", - "\n", - " * For a good discussion on gradient methods, see Goodfellow et al section 4.3-4.5 and chapter 8. We will come back to the latter chapter in our discussion of Neural networks as well.\n", - "\n", - " * See also the whiteboard notes from week 37 at for a discussion and derivation of the bias-variance tradeoff. \n", - "\n", - " * [Video on Logistic regression](https://www.youtube.com/watch?v=C5268D9t9Ak)\n", - "\n", - " * [Yet another video on logistic regression](https://www.youtube.com/watch?v=yIYKR4sgzI8)\n", - "\n", - " * [Video on gradient descent](https://www.youtube.com/watch?v=sDv4f4s2SB8)" - ] - }, - { - "cell_type": "markdown", - "id": "e47b1a7c", - "metadata": { - "editable": true - }, - "source": [ - "## Material from last week and relevant for the first project" - ] - }, - { - "cell_type": "markdown", - "id": "1ad44c38", - "metadata": { - "editable": true - }, - "source": [ - "## Various steps in cross-validation\n", - "\n", - "When the repetitive splitting of the data set is done randomly,\n", - "samples may accidently end up in a fast majority of the splits in\n", - "either training or test set. Such samples may have an unbalanced\n", - "influence on either model building or prediction evaluation. To avoid\n", - "this $k$-fold cross-validation structures the data splitting. The\n", - "samples are divided into $k$ more or less equally sized exhaustive and\n", - "mutually exclusive subsets. In turn (at each split) one of these\n", - "subsets plays the role of the test set while the union of the\n", - "remaining subsets constitutes the training set. Such a splitting\n", - "warrants a balanced representation of each sample in both training and\n", - "test set over the splits. Still the division into the $k$ subsets\n", - "involves a degree of randomness. This may be fully excluded when\n", - "choosing $k=n$. This particular case is referred to as leave-one-out\n", - "cross-validation (LOOCV)." - ] - }, - { - "cell_type": "markdown", - "id": "48181efc", - "metadata": { - "editable": true - }, - "source": [ - "## How to set up the cross-validation for Ridge and/or Lasso\n", - "\n", - "* Define a range of interest for the penalty parameter.\n", - "\n", - "* Divide the data set into training and test set comprising samples $\\{1, \\ldots, n\\} \\setminus i$ and $\\{ i \\}$, respectively.\n", - "\n", - "* Fit the linear regression model by means of for example Ridge or Lasso regression for each $\\lambda$ in the grid using the training set, and the corresponding estimate of the error variance $\\boldsymbol{\\sigma}_{-i}^2(\\lambda)$, as" - ] - }, - { - "cell_type": "markdown", - "id": "62106e79", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\begin{align*}\n", - "\\boldsymbol{\\beta}_{-i}(\\lambda) & = ( \\boldsymbol{X}_{-i, \\ast}^{T}\n", - "\\boldsymbol{X}_{-i, \\ast} + \\lambda \\boldsymbol{I}_{pp})^{-1}\n", - "\\boldsymbol{X}_{-i, \\ast}^{T} \\boldsymbol{y}_{-i}\n", - "\\end{align*}\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "7d392fb4", - "metadata": { - "editable": true - }, - "source": [ - "* Evaluate the prediction performance of these models on the test set by $C[y_i, \\boldsymbol{X}_{i, \\ast}; \\boldsymbol{\\beta}_{-i}(\\lambda), \\boldsymbol{\\sigma}_{-i}^2(\\lambda)]$. Or, by the prediction error $|y_i - \\boldsymbol{X}_{i, \\ast} \\boldsymbol{\\beta}_{-i}(\\lambda)|$, the relative error, the error squared or the R2 score function.\n", - "\n", - "* Repeat the first three steps such that each sample plays the role of the test set once.\n", - "\n", - "* Average the prediction performances of the test sets at each grid point of the penalty bias/parameter. It is an estimate of the prediction performance of the model corresponding to this value of the penalty parameter on novel data." - ] - }, - { - "cell_type": "markdown", - "id": "883c8ba9", - "metadata": { - "editable": true - }, - "source": [ - "## Cross-validation in brief\n", - "\n", - "For the various values of $k$\n", - "\n", - "1. shuffle the dataset randomly.\n", - "\n", - "2. Split the dataset into $k$ groups.\n", - "\n", - "3. For each unique group:\n", - "\n", - "a. Decide which group to use as set for test data\n", - "\n", - "b. Take the remaining groups as a training data set\n", - "\n", - "c. Fit a model on the training set and evaluate it on the test set\n", - "\n", - "d. Retain the evaluation score and discard the model\n", - "\n", - "5. Summarize the model using the sample of model evaluation scores" - ] - }, - { - "cell_type": "markdown", - "id": "2db06c8a", - "metadata": { - "editable": true - }, - "source": [ - "## Code Example for Cross-validation and $k$-fold Cross-validation\n", - "\n", - "The code here uses Ridge regression with cross-validation (CV) resampling and $k$-fold CV in order to fit a specific polynomial." - ] - }, - { - "cell_type": "code", - "execution_count": 1, - "id": "7487b649", - "metadata": { - "collapsed": false, - "editable": true - }, - "outputs": [], - "source": [ - "%matplotlib inline\n", - "\n", - "import numpy as np\n", - "import matplotlib.pyplot as plt\n", - "from sklearn.model_selection import KFold\n", - "from sklearn.linear_model import Ridge\n", - "from sklearn.model_selection import cross_val_score\n", - "from sklearn.preprocessing import PolynomialFeatures\n", - "\n", - "# A seed just to ensure that the random numbers are the same for every run.\n", - "# Useful for eventual debugging.\n", - "np.random.seed(3155)\n", - "\n", - "# Generate the data.\n", - "nsamples = 100\n", - "x = np.random.randn(nsamples)\n", - "y = 3*x**2 + np.random.randn(nsamples)\n", - "\n", - "## Cross-validation on Ridge regression using KFold only\n", - "\n", - "# Decide degree on polynomial to fit\n", - "poly = PolynomialFeatures(degree = 6)\n", - "\n", - "# Decide which values of lambda to use\n", - "nlambdas = 500\n", - "lambdas = np.logspace(-3, 5, nlambdas)\n", - "\n", - "# Initialize a KFold instance\n", - "k = 5\n", - "kfold = KFold(n_splits = k)\n", - "\n", - "# Perform the cross-validation to estimate MSE\n", - "scores_KFold = np.zeros((nlambdas, k))\n", - "\n", - "i = 0\n", - "for lmb in lambdas:\n", - " ridge = Ridge(alpha = lmb)\n", - " j = 0\n", - " for train_inds, test_inds in kfold.split(x):\n", - " xtrain = x[train_inds]\n", - " ytrain = y[train_inds]\n", - "\n", - " xtest = x[test_inds]\n", - " ytest = y[test_inds]\n", - "\n", - " Xtrain = poly.fit_transform(xtrain[:, np.newaxis])\n", - " ridge.fit(Xtrain, ytrain[:, np.newaxis])\n", - "\n", - " Xtest = poly.fit_transform(xtest[:, np.newaxis])\n", - " ypred = ridge.predict(Xtest)\n", - "\n", - " scores_KFold[i,j] = np.sum((ypred - ytest[:, np.newaxis])**2)/np.size(ypred)\n", - "\n", - " j += 1\n", - " i += 1\n", - "\n", - "\n", - "estimated_mse_KFold = np.mean(scores_KFold, axis = 1)\n", - "\n", - "## Cross-validation using cross_val_score from sklearn along with KFold\n", - "\n", - "# kfold is an instance initialized above as:\n", - "# kfold = KFold(n_splits = k)\n", - "\n", - "estimated_mse_sklearn = np.zeros(nlambdas)\n", - "i = 0\n", - "for lmb in lambdas:\n", - " ridge = Ridge(alpha = lmb)\n", - "\n", - " X = poly.fit_transform(x[:, np.newaxis])\n", - " estimated_mse_folds = cross_val_score(ridge, X, y[:, np.newaxis], scoring='neg_mean_squared_error', cv=kfold)\n", - "\n", - " # cross_val_score return an array containing the estimated negative mse for every fold.\n", - " # we have to the the mean of every array in order to get an estimate of the mse of the model\n", - " estimated_mse_sklearn[i] = np.mean(-estimated_mse_folds)\n", - "\n", - " i += 1\n", - "\n", - "## Plot and compare the slightly different ways to perform cross-validation\n", - "\n", - "plt.figure()\n", - "\n", - "plt.plot(np.log10(lambdas), estimated_mse_sklearn, label = 'cross_val_score')\n", - "plt.plot(np.log10(lambdas), estimated_mse_KFold, 'r--', label = 'KFold')\n", - "\n", - "plt.xlabel('log10(lambda)')\n", - "plt.ylabel('mse')\n", - "\n", - "plt.legend()\n", - "\n", - "plt.show()" - ] - }, - { - "cell_type": "markdown", - "id": "3d38a274", - "metadata": { - "editable": true - }, - "source": [ - "## Material for lecture Thursday September 21" - ] - }, - { - "cell_type": "markdown", - "id": "53cb96b0", - "metadata": { - "editable": true - }, - "source": [ - "## Logistic Regression\n", - "\n", - "In linear regression our main interest was centered on learning the\n", - "coefficients of a functional fit (say a polynomial) in order to be\n", - "able to predict the response of a continuous variable on some unseen\n", - "data. The fit to the continuous variable $y_i$ is based on some\n", - "independent variables $\\boldsymbol{x}_i$. Linear regression resulted in\n", - "analytical expressions for standard ordinary Least Squares or Ridge\n", - "regression (in terms of matrices to invert) for several quantities,\n", - "ranging from the variance and thereby the confidence intervals of the\n", - "parameters $\\boldsymbol{\\beta}$ to the mean squared error. If we can invert\n", - "the product of the design matrices, linear regression gives then a\n", - "simple recipe for fitting our data." - ] - }, - { - "cell_type": "markdown", - "id": "6120b1c7", - "metadata": { - "editable": true - }, - "source": [ - "## Classification problems\n", - "\n", - "Classification problems, however, are concerned with outcomes taking\n", - "the form of discrete variables (i.e. categories). We may for example,\n", - "on the basis of DNA sequencing for a number of patients, like to find\n", - "out which mutations are important for a certain disease; or based on\n", - "scans of various patients' brains, figure out if there is a tumor or\n", - "not; or given a specific physical system, we'd like to identify its\n", - "state, say whether it is an ordered or disordered system (typical\n", - "situation in solid state physics); or classify the status of a\n", - "patient, whether she/he has a stroke or not and many other similar\n", - "situations.\n", - "\n", - "The most common situation we encounter when we apply logistic\n", - "regression is that of two possible outcomes, normally denoted as a\n", - "binary outcome, true or false, positive or negative, success or\n", - "failure etc." - ] - }, - { - "cell_type": "markdown", - "id": "936083c0", - "metadata": { - "editable": true - }, - "source": [ - "## Optimization and Deep learning\n", - "\n", - "Logistic regression will also serve as our stepping stone towards\n", - "neural network algorithms and supervised deep learning. For logistic\n", - "learning, the minimization of the cost function leads to a non-linear\n", - "equation in the parameters $\\boldsymbol{\\beta}$. The optimization of the\n", - "problem calls therefore for minimization algorithms. This forms the\n", - "bottle neck of all machine learning algorithms, namely how to find\n", - "reliable minima of a multi-variable function. This leads us to the\n", - "family of gradient descent methods. The latter are the working horses\n", - "of basically all modern machine learning algorithms.\n", - "\n", - "We note also that many of the topics discussed here on logistic \n", - "regression are also commonly used in modern supervised Deep Learning\n", - "models, as we will see later." - ] - }, - { - "cell_type": "markdown", - "id": "32780c62", - "metadata": { - "editable": true - }, - "source": [ - "## Basics\n", - "\n", - "We consider the case where the dependent variables, also called the\n", - "responses or the outcomes, $y_i$ are discrete and only take values\n", - "from $k=0,\\dots,K-1$ (i.e. $K$ classes).\n", - "\n", - "The goal is to predict the\n", - "output classes from the design matrix $\\boldsymbol{X}\\in\\mathbb{R}^{n\\times p}$\n", - "made of $n$ samples, each of which carries $p$ features or predictors. The\n", - "primary goal is to identify the classes to which new unseen samples\n", - "belong.\n", - "\n", - "Let us specialize to the case of two classes only, with outputs\n", - "$y_i=0$ and $y_i=1$. Our outcomes could represent the status of a\n", - "credit card user that could default or not on her/his credit card\n", - "debt. That is" - ] - }, - { - "cell_type": "markdown", - "id": "20d08abd", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "y_i = \\begin{bmatrix} 0 & \\mathrm{no}\\\\ 1 & \\mathrm{yes} \\end{bmatrix}.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "58b3452f", - "metadata": { - "editable": true - }, - "source": [ - "## Linear classifier\n", - "\n", - "Before moving to the logistic model, let us try to use our linear\n", - "regression model to classify these two outcomes. We could for example\n", - "fit a linear model to the default case if $y_i > 0.5$ and the no\n", - "default case $y_i \\leq 0.5$.\n", - "\n", - "We would then have our \n", - "weighted linear combination, namely" - ] - }, - { - "cell_type": "markdown", - "id": "7f605f89", - "metadata": { - "editable": true - }, - "source": [ - "\n", - "
\n", - "\n", - "$$\n", - "\\begin{equation}\n", - "\\boldsymbol{y} = \\boldsymbol{X}^T\\boldsymbol{\\beta} + \\boldsymbol{\\epsilon},\n", - "\\label{_auto1} \\tag{1}\n", - "\\end{equation}\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "40905342", - "metadata": { - "editable": true - }, - "source": [ - "where $\\boldsymbol{y}$ is a vector representing the possible outcomes, $\\boldsymbol{X}$ is our\n", - "$n\\times p$ design matrix and $\\boldsymbol{\\beta}$ represents our estimators/predictors." - ] - }, - { - "cell_type": "markdown", - "id": "77f09c4f", - "metadata": { - "editable": true - }, - "source": [ - "## Some selected properties\n", - "\n", - "The main problem with our function is that it takes values on the\n", - "entire real axis. In the case of logistic regression, however, the\n", - "labels $y_i$ are discrete variables. A typical example is the credit\n", - "card data discussed below here, where we can set the state of\n", - "defaulting the debt to $y_i=1$ and not to $y_i=0$ for one the persons\n", - "in the data set (see the full example below).\n", - "\n", - "One simple way to get a discrete output is to have sign\n", - "functions that map the output of a linear regressor to values $\\{0,1\\}$,\n", - "$f(s_i)=sign(s_i)=1$ if $s_i\\ge 0$ and 0 if otherwise. \n", - "We will encounter this model in our first demonstration of neural networks.\n", - "\n", - "Historically it is called the **perceptron** model in the machine learning\n", - "literature. This model is extremely simple. However, in many cases it is more\n", - "favorable to use a ``soft\" classifier that outputs\n", - "the probability of a given category. This leads us to the logistic function." - ] - }, - { - "cell_type": "markdown", - "id": "4eea9d16", - "metadata": { - "editable": true - }, - "source": [ - "## Simple example\n", - "\n", - "The following example on data for coronary heart disease (CHD) as function of age may serve as an illustration. In the code here we read and plot whether a person has had CHD (output = 1) or not (output = 0). This ouput is plotted the person's against age. Clearly, the figure shows that attempting to make a standard linear regression fit may not be very meaningful." - ] - }, - { - "cell_type": "code", - "execution_count": 2, - "id": "fdccf16e", - "metadata": { - "collapsed": false, - "editable": true - }, - "outputs": [], - "source": [ - "# Common imports\n", - "import os\n", - "import numpy as np\n", - "import pandas as pd\n", - "import matplotlib.pyplot as plt\n", - "from sklearn.linear_model import LinearRegression, Ridge, Lasso\n", - "from sklearn.model_selection import train_test_split\n", - "from sklearn.utils import resample\n", - "from sklearn.metrics import mean_squared_error\n", - "from IPython.display import display\n", - "from pylab import plt, mpl\n", - "plt.style.use('seaborn')\n", - "mpl.rcParams['font.family'] = 'serif'\n", - "\n", - "# Where to save the figures and data files\n", - "PROJECT_ROOT_DIR = \"Results\"\n", - "FIGURE_ID = \"Results/FigureFiles\"\n", - "DATA_ID = \"DataFiles/\"\n", - "\n", - "if not os.path.exists(PROJECT_ROOT_DIR):\n", - " os.mkdir(PROJECT_ROOT_DIR)\n", - "\n", - "if not os.path.exists(FIGURE_ID):\n", - " os.makedirs(FIGURE_ID)\n", - "\n", - "if not os.path.exists(DATA_ID):\n", - " os.makedirs(DATA_ID)\n", - "\n", - "def image_path(fig_id):\n", - " return os.path.join(FIGURE_ID, fig_id)\n", - "\n", - "def data_path(dat_id):\n", - " return os.path.join(DATA_ID, dat_id)\n", - "\n", - "def save_fig(fig_id):\n", - " plt.savefig(image_path(fig_id) + \".png\", format='png')\n", - "\n", - "infile = open(data_path(\"chddata.csv\"),'r')\n", - "\n", - "# Read the chd data as csv file and organize the data into arrays with age group, age, and chd\n", - "chd = pd.read_csv(infile, names=('ID', 'Age', 'Agegroup', 'CHD'))\n", - "chd.columns = ['ID', 'Age', 'Agegroup', 'CHD']\n", - "output = chd['CHD']\n", - "age = chd['Age']\n", - "agegroup = chd['Agegroup']\n", - "numberID = chd['ID'] \n", - "display(chd)\n", - "\n", - "plt.scatter(age, output, marker='o')\n", - "plt.axis([18,70.0,-0.1, 1.2])\n", - "plt.xlabel(r'Age')\n", - "plt.ylabel(r'CHD')\n", - "plt.title(r'Age distribution and Coronary heart disease')\n", - "plt.show()" - ] - }, - { - "cell_type": "markdown", - "id": "3db91831", - "metadata": { - "editable": true - }, - "source": [ - "## Plotting the mean value for each group\n", - "\n", - "What we could attempt however is to plot the mean value for each group." - ] - }, - { - "cell_type": "code", - "execution_count": 3, - "id": "b570a592", - "metadata": { - "collapsed": false, - "editable": true - }, - "outputs": [], - "source": [ - "agegroupmean = np.array([0.1, 0.133, 0.250, 0.333, 0.462, 0.625, 0.765, 0.800])\n", - "group = np.array([1, 2, 3, 4, 5, 6, 7, 8])\n", - "plt.plot(group, agegroupmean, \"r-\")\n", - "plt.axis([0,9,0, 1.0])\n", - "plt.xlabel(r'Age group')\n", - "plt.ylabel(r'CHD mean values')\n", - "plt.title(r'Mean values for each age group')\n", - "plt.show()" - ] - }, - { - "cell_type": "markdown", - "id": "45e5a12a", - "metadata": { - "editable": true - }, - "source": [ - "We are now trying to find a function $f(y\\vert x)$, that is a function which gives us an expected value for the output $y$ with a given input $x$.\n", - "In standard linear regression with a linear dependence on $x$, we would write this in terms of our model" - ] - }, - { - "cell_type": "markdown", - "id": "21d22b13", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "f(y_i\\vert x_i)=\\beta_0+\\beta_1 x_i.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "e6b2b13a", - "metadata": { - "editable": true - }, - "source": [ - "This expression implies however that $f(y_i\\vert x_i)$ could take any\n", - "value from minus infinity to plus infinity. If we however let\n", - "$f(y\\vert y)$ be represented by the mean value, the above example\n", - "shows us that we can constrain the function to take values between\n", - "zero and one, that is we have $0 \\le f(y_i\\vert x_i) \\le 1$. Looking\n", - "at our last curve we see also that it has an S-shaped form. This leads\n", - "us to a very popular model for the function $f$, namely the so-called\n", - "Sigmoid function or logistic model. We will consider this function as\n", - "representing the probability for finding a value of $y_i$ with a given\n", - "$x_i$." - ] - }, - { - "cell_type": "markdown", - "id": "038a694a", - "metadata": { - "editable": true - }, - "source": [ - "## The logistic function\n", - "\n", - "Another widely studied model, is the so-called \n", - "perceptron model, which is an example of a \"hard classification\" model. We\n", - "will encounter this model when we discuss neural networks as\n", - "well. Each datapoint is deterministically assigned to a category (i.e\n", - "$y_i=0$ or $y_i=1$). In many cases, and the coronary heart disease data forms one of many such examples, it is favorable to have a \"soft\"\n", - "classifier that outputs the probability of a given category rather\n", - "than a single value. For example, given $x_i$, the classifier\n", - "outputs the probability of being in a category $k$. Logistic regression\n", - "is the most common example of a so-called soft classifier. In logistic\n", - "regression, the probability that a data point $x_i$\n", - "belongs to a category $y_i=\\{0,1\\}$ is given by the so-called logit function (or Sigmoid) which is meant to represent the likelihood for a given event," - ] - }, - { - "cell_type": "markdown", - "id": "581a37c8", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "p(t) = \\frac{1}{1+\\mathrm \\exp{-t}}=\\frac{\\exp{t}}{1+\\mathrm \\exp{t}}.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "8e6ff605", - "metadata": { - "editable": true - }, - "source": [ - "Note that $1-p(t)= p(-t)$." - ] - }, - { - "cell_type": "markdown", - "id": "07e8c6c7", - "metadata": { - "editable": true - }, - "source": [ - "## Examples of likelihood functions used in logistic regression and nueral networks\n", - "\n", - "The following code plots the logistic function, the step function and other functions we will encounter from here and on." - ] - }, - { - "cell_type": "code", - "execution_count": 4, - "id": "82e381c1", - "metadata": { - "collapsed": false, - "editable": true - }, - "outputs": [], - "source": [ - "\"\"\"The sigmoid function (or the logistic curve) is a\n", - "function that takes any real number, z, and outputs a number (0,1).\n", - "It is useful in neural networks for assigning weights on a relative scale.\n", - "The value z is the weighted sum of parameters involved in the learning algorithm.\"\"\"\n", - "\n", - "import numpy\n", - "import matplotlib.pyplot as plt\n", - "import math as mt\n", - "\n", - "z = numpy.arange(-5, 5, .1)\n", - "sigma_fn = numpy.vectorize(lambda z: 1/(1+numpy.exp(-z)))\n", - "sigma = sigma_fn(z)\n", - "\n", - "fig = plt.figure()\n", - "ax = fig.add_subplot(111)\n", - "ax.plot(z, sigma)\n", - "ax.set_ylim([-0.1, 1.1])\n", - "ax.set_xlim([-5,5])\n", - "ax.grid(True)\n", - "ax.set_xlabel('z')\n", - "ax.set_title('sigmoid function')\n", - "\n", - "plt.show()\n", - "\n", - "\"\"\"Step Function\"\"\"\n", - "z = numpy.arange(-5, 5, .02)\n", - "step_fn = numpy.vectorize(lambda z: 1.0 if z >= 0.0 else 0.0)\n", - "step = step_fn(z)\n", - "\n", - "fig = plt.figure()\n", - "ax = fig.add_subplot(111)\n", - "ax.plot(z, step)\n", - "ax.set_ylim([-0.5, 1.5])\n", - "ax.set_xlim([-5,5])\n", - "ax.grid(True)\n", - "ax.set_xlabel('z')\n", - "ax.set_title('step function')\n", - "\n", - "plt.show()\n", - "\n", - "\"\"\"tanh Function\"\"\"\n", - "z = numpy.arange(-2*mt.pi, 2*mt.pi, 0.1)\n", - "t = numpy.tanh(z)\n", - "\n", - "fig = plt.figure()\n", - "ax = fig.add_subplot(111)\n", - "ax.plot(z, t)\n", - "ax.set_ylim([-1.0, 1.0])\n", - "ax.set_xlim([-2*mt.pi,2*mt.pi])\n", - "ax.grid(True)\n", - "ax.set_xlabel('z')\n", - "ax.set_title('tanh function')\n", - "\n", - "plt.show()" - ] - }, - { - "cell_type": "markdown", - "id": "cffc710d", - "metadata": { - "editable": true - }, - "source": [ - "## Two parameters\n", - "\n", - "We assume now that we have two classes with $y_i$ either $0$ or $1$. Furthermore we assume also that we have only two parameters $\\beta$ in our fitting of the Sigmoid function, that is we define probabilities" - ] - }, - { - "cell_type": "markdown", - "id": "077523d2", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\begin{align*}\n", - "p(y_i=1|x_i,\\boldsymbol{\\beta}) &= \\frac{\\exp{(\\beta_0+\\beta_1x_i)}}{1+\\exp{(\\beta_0+\\beta_1x_i)}},\\nonumber\\\\\n", - "p(y_i=0|x_i,\\boldsymbol{\\beta}) &= 1 - p(y_i=1|x_i,\\boldsymbol{\\beta}),\n", - "\\end{align*}\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "378c1ba1", - "metadata": { - "editable": true - }, - "source": [ - "where $\\boldsymbol{\\beta}$ are the weights we wish to extract from data, in our case $\\beta_0$ and $\\beta_1$. \n", - "\n", - "Note that we used" - ] - }, - { - "cell_type": "markdown", - "id": "12641f70", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "p(y_i=0\\vert x_i, \\boldsymbol{\\beta}) = 1-p(y_i=1\\vert x_i, \\boldsymbol{\\beta}).\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "72d4d322", - "metadata": { - "editable": true - }, - "source": [ - "## Maximum likelihood\n", - "\n", - "In order to define the total likelihood for all possible outcomes from a \n", - "dataset $\\mathcal{D}=\\{(y_i,x_i)\\}$, with the binary labels\n", - "$y_i\\in\\{0,1\\}$ and where the data points are drawn independently, we use the so-called [Maximum Likelihood Estimation](https://en.wikipedia.org/wiki/Maximum_likelihood_estimation) (MLE) principle. \n", - "We aim thus at maximizing \n", - "the probability of seeing the observed data. We can then approximate the \n", - "likelihood in terms of the product of the individual probabilities of a specific outcome $y_i$, that is" - ] - }, - { - "cell_type": "markdown", - "id": "218bad85", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\begin{align*}\n", - "P(\\mathcal{D}|\\boldsymbol{\\beta})& = \\prod_{i=1}^n \\left[p(y_i=1|x_i,\\boldsymbol{\\beta})\\right]^{y_i}\\left[1-p(y_i=1|x_i,\\boldsymbol{\\beta}))\\right]^{1-y_i}\\nonumber \\\\\n", - "\\end{align*}\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "7f1151b5", - "metadata": { - "editable": true - }, - "source": [ - "from which we obtain the log-likelihood and our **cost/loss** function" - ] - }, - { - "cell_type": "markdown", - "id": "c31ffe4e", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\mathcal{C}(\\boldsymbol{\\beta}) = \\sum_{i=1}^n \\left( y_i\\log{p(y_i=1|x_i,\\boldsymbol{\\beta})} + (1-y_i)\\log\\left[1-p(y_i=1|x_i,\\boldsymbol{\\beta}))\\right]\\right).\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "f653cea3", - "metadata": { - "editable": true - }, - "source": [ - "## The cost function rewritten\n", - "\n", - "Reordering the logarithms, we can rewrite the **cost/loss** function as" - ] - }, - { - "cell_type": "markdown", - "id": "d117384a", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\mathcal{C}(\\boldsymbol{\\beta}) = \\sum_{i=1}^n \\left(y_i(\\beta_0+\\beta_1x_i) -\\log{(1+\\exp{(\\beta_0+\\beta_1x_i)})}\\right).\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "3f7763f2", - "metadata": { - "editable": true - }, - "source": [ - "The maximum likelihood estimator is defined as the set of parameters that maximize the log-likelihood where we maximize with respect to $\\beta$.\n", - "Since the cost (error) function is just the negative log-likelihood, for logistic regression we have that" - ] - }, - { - "cell_type": "markdown", - "id": "0c5d4782", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\mathcal{C}(\\boldsymbol{\\beta})=-\\sum_{i=1}^n \\left(y_i(\\beta_0+\\beta_1x_i) -\\log{(1+\\exp{(\\beta_0+\\beta_1x_i)})}\\right).\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "e47ac025", - "metadata": { - "editable": true - }, - "source": [ - "This equation is known in statistics as the **cross entropy**. Finally, we note that just as in linear regression, \n", - "in practice we often supplement the cross-entropy with additional regularization terms, usually $L_1$ and $L_2$ regularization as we did for Ridge and Lasso regression." - ] - }, - { - "cell_type": "markdown", - "id": "0775be1d", - "metadata": { - "editable": true - }, - "source": [ - "## Minimizing the cross entropy\n", - "\n", - "The cross entropy is a convex function of the weights $\\boldsymbol{\\beta}$ and,\n", - "therefore, any local minimizer is a global minimizer. \n", - "\n", - "Minimizing this\n", - "cost function with respect to the two parameters $\\beta_0$ and $\\beta_1$ we obtain" - ] - }, - { - "cell_type": "markdown", - "id": "2c6d8021", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\frac{\\partial \\mathcal{C}(\\boldsymbol{\\beta})}{\\partial \\beta_0} = -\\sum_{i=1}^n \\left(y_i -\\frac{\\exp{(\\beta_0+\\beta_1x_i)}}{1+\\exp{(\\beta_0+\\beta_1x_i)}}\\right),\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "934b3029", - "metadata": { - "editable": true - }, - "source": [ - "and" - ] - }, - { - "cell_type": "markdown", - "id": "5736ce62", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\frac{\\partial \\mathcal{C}(\\boldsymbol{\\beta})}{\\partial \\beta_1} = -\\sum_{i=1}^n \\left(y_ix_i -x_i\\frac{\\exp{(\\beta_0+\\beta_1x_i)}}{1+\\exp{(\\beta_0+\\beta_1x_i)}}\\right).\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "24448336", - "metadata": { - "editable": true - }, - "source": [ - "## A more compact expression\n", - "\n", - "Let us now define a vector $\\boldsymbol{y}$ with $n$ elements $y_i$, an\n", - "$n\\times p$ matrix $\\boldsymbol{X}$ which contains the $x_i$ values and a\n", - "vector $\\boldsymbol{p}$ of fitted probabilities $p(y_i\\vert x_i,\\boldsymbol{\\beta})$. We can rewrite in a more compact form the first\n", - "derivative of cost function as" - ] - }, - { - "cell_type": "markdown", - "id": "62af3134", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\frac{\\partial \\mathcal{C}(\\boldsymbol{\\beta})}{\\partial \\boldsymbol{\\beta}} = -\\boldsymbol{X}^T\\left(\\boldsymbol{y}-\\boldsymbol{p}\\right).\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "e75f8b6b", - "metadata": { - "editable": true - }, - "source": [ - "If we in addition define a diagonal matrix $\\boldsymbol{W}$ with elements \n", - "$p(y_i\\vert x_i,\\boldsymbol{\\beta})(1-p(y_i\\vert x_i,\\boldsymbol{\\beta})$, we can obtain a compact expression of the second derivative as" - ] - }, - { - "cell_type": "markdown", - "id": "afbcdd5a", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\frac{\\partial^2 \\mathcal{C}(\\boldsymbol{\\beta})}{\\partial \\boldsymbol{\\beta}\\partial \\boldsymbol{\\beta}^T} = \\boldsymbol{X}^T\\boldsymbol{W}\\boldsymbol{X}.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "6a4b6b7f", - "metadata": { - "editable": true - }, - "source": [ - "## Extending to more predictors\n", - "\n", - "Within a binary classification problem, we can easily expand our model to include multiple predictors. Our ratio between likelihoods is then with $p$ predictors" - ] - }, - { - "cell_type": "markdown", - "id": "0487a05f", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\log{ \\frac{p(\\boldsymbol{\\beta}\\boldsymbol{x})}{1-p(\\boldsymbol{\\beta}\\boldsymbol{x})}} = \\beta_0+\\beta_1x_1+\\beta_2x_2+\\dots+\\beta_px_p.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "55d00e90", - "metadata": { - "editable": true - }, - "source": [ - "Here we defined $\\boldsymbol{x}=[1,x_1,x_2,\\dots,x_p]$ and $\\boldsymbol{\\beta}=[\\beta_0, \\beta_1, \\dots, \\beta_p]$ leading to" - ] - }, - { - "cell_type": "markdown", - "id": "13f16948", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "p(\\boldsymbol{\\beta}\\boldsymbol{x})=\\frac{ \\exp{(\\beta_0+\\beta_1x_1+\\beta_2x_2+\\dots+\\beta_px_p)}}{1+\\exp{(\\beta_0+\\beta_1x_1+\\beta_2x_2+\\dots+\\beta_px_p)}}.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "99af8c4d", - "metadata": { - "editable": true - }, - "source": [ - "## Including more classes\n", - "\n", - "Till now we have mainly focused on two classes, the so-called binary\n", - "system. Suppose we wish to extend to $K$ classes. Let us for the sake\n", - "of simplicity assume we have only two predictors. We have then following model" - ] - }, - { - "cell_type": "markdown", - "id": "8ba91bb6", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\log{\\frac{p(C=1\\vert x)}{p(K\\vert x)}} = \\beta_{10}+\\beta_{11}x_1,\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "f5833039", - "metadata": { - "editable": true - }, - "source": [ - "and" - ] - }, - { - "cell_type": "markdown", - "id": "451f2890", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\log{\\frac{p(C=2\\vert x)}{p(K\\vert x)}} = \\beta_{20}+\\beta_{21}x_1,\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "1ae365e3", - "metadata": { - "editable": true - }, - "source": [ - "and so on till the class $C=K-1$ class" - ] - }, - { - "cell_type": "markdown", - "id": "b3187ffb", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\log{\\frac{p(C=K-1\\vert x)}{p(K\\vert x)}} = \\beta_{(K-1)0}+\\beta_{(K-1)1}x_1,\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "edc72487", - "metadata": { - "editable": true - }, - "source": [ - "and the model is specified in term of $K-1$ so-called log-odds or\n", - "**logit** transformations." - ] - }, - { - "cell_type": "markdown", - "id": "1e550b7a", - "metadata": { - "editable": true - }, - "source": [ - "## More classes\n", - "\n", - "In our discussion of neural networks we will encounter the above again\n", - "in terms of a slightly modified function, the so-called **Softmax** function.\n", - "\n", - "The softmax function is used in various multiclass classification\n", - "methods, such as multinomial logistic regression (also known as\n", - "softmax regression), multiclass linear discriminant analysis, naive\n", - "Bayes classifiers, and artificial neural networks. Specifically, in\n", - "multinomial logistic regression and linear discriminant analysis, the\n", - "input to the function is the result of $K$ distinct linear functions,\n", - "and the predicted probability for the $k$-th class given a sample\n", - "vector $\\boldsymbol{x}$ and a weighting vector $\\boldsymbol{\\beta}$ is (with two\n", - "predictors):" - ] - }, - { - "cell_type": "markdown", - "id": "dc2781ed", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "p(C=k\\vert \\mathbf {x} )=\\frac{\\exp{(\\beta_{k0}+\\beta_{k1}x_1)}}{1+\\sum_{l=1}^{K-1}\\exp{(\\beta_{l0}+\\beta_{l1}x_1)}}.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "720ee440", - "metadata": { - "editable": true - }, - "source": [ - "It is easy to extend to more predictors. The final class is" - ] - }, - { - "cell_type": "markdown", - "id": "eaa0254a", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "p(C=K\\vert \\mathbf {x} )=\\frac{1}{1+\\sum_{l=1}^{K-1}\\exp{(\\beta_{l0}+\\beta_{l1}x_1)}},\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "f6bc3445", - "metadata": { - "editable": true - }, - "source": [ - "and they sum to one. Our earlier discussions were all specialized to\n", - "the case with two classes only. It is easy to see from the above that\n", - "what we derived earlier is compatible with these equations.\n", - "\n", - "To find the optimal parameters we would typically use a gradient\n", - "descent method. Newton's method and gradient descent methods are\n", - "discussed in the material on [optimization\n", - "methods](https://compphysics.github.io/MachineLearning/doc/pub/Splines/html/Splines-bs.html)." - ] - }, - { - "cell_type": "markdown", - "id": "b25b0241", - "metadata": { - "editable": true - }, - "source": [ - "## Friday September 23" - ] - }, - { - "cell_type": "markdown", - "id": "380d3c17", - "metadata": { - "editable": true - }, - "source": [ - "## Searching for Optimal Regularization Parameters $\\lambda$\n", - "\n", - "In project 1, when using Ridge and Lasso regression, we end up\n", - "searching for the optimal parameter $\\lambda$ which minimizes our\n", - "selected scores (MSE or $R2$ values for example). The brute force\n", - "approach, as discussed in the code here for Ridge regression, consists\n", - "in evaluating the MSE as function of different $\\lambda$ values.\n", - "Based on these calculations, one tries then to determine the value of the hyperparameter $\\lambda$\n", - "which results in optimal scores (for example the smallest MSE or an $R2=1$)." - ] - }, - { - "cell_type": "code", - "execution_count": 5, - "id": "b1e69471", - "metadata": { - "collapsed": false, - "editable": true - }, - "outputs": [], - "source": [ - "import numpy as np\n", - "import pandas as pd\n", - "import matplotlib.pyplot as plt\n", - "from sklearn.model_selection import train_test_split\n", - "from sklearn import linear_model\n", - "\n", - "def MSE(y_data,y_model):\n", - " n = np.size(y_model)\n", - " return np.sum((y_data-y_model)**2)/n\n", - "# A seed just to ensure that the random numbers are the same for every run.\n", - "# Useful for eventual debugging.\n", - "np.random.seed(2021)\n", - "\n", - "n = 100\n", - "x = np.random.rand(n)\n", - "y = np.exp(-x**2) + 1.5 * np.exp(-(x-2)**2)+ np.random.randn(n)\n", - "\n", - "Maxpolydegree = 5\n", - "X = np.zeros((n,Maxpolydegree-1))\n", - "\n", - "for degree in range(1,Maxpolydegree): #No intercept column\n", - " X[:,degree-1] = x**(degree)\n", - "\n", - "# We split the data in test and training data\n", - "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2)\n", - "\n", - "# Decide which values of lambda to use\n", - "nlambdas = 500\n", - "MSERidgePredict = np.zeros(nlambdas)\n", - "lambdas = np.logspace(-4, 2, nlambdas)\n", - "for i in range(nlambdas):\n", - " lmb = lambdas[i]\n", - " RegRidge = linear_model.Ridge(lmb)\n", - " RegRidge.fit(X_train,y_train)\n", - " ypredictRidge = RegRidge.predict(X_test)\n", - " MSERidgePredict[i] = MSE(y_test,ypredictRidge)\n", - "\n", - "# Now plot the results\n", - "plt.figure()\n", - "plt.plot(np.log10(lambdas), MSERidgePredict, 'g--', label = 'MSE SL Ridge Test')\n", - "plt.xlabel('log10(lambda)')\n", - "plt.ylabel('MSE')\n", - "plt.legend()\n", - "plt.show()" - ] - }, - { - "cell_type": "markdown", - "id": "e82def1d", - "metadata": { - "editable": true - }, - "source": [ - "Here we have performed a rather data greedy calculation as function of the regularization parameter $\\lambda$. There is no resampling here. The latter can easily be added by employing the function **RidgeCV** instead of just calling the **Ridge** function. For **RidgeCV** we need to pass the array of $\\lambda$ values.\n", - "By inspecting the figure we can in turn determine which is the optimal regularization parameter.\n", - "This becomes however less functional in the long run." - ] - }, - { - "cell_type": "markdown", - "id": "325e0956", - "metadata": { - "editable": true - }, - "source": [ - "## Grid Search\n", - "\n", - "An alternative is to use the so-called grid search functionality\n", - "included with the library **Scikit-Learn**, as demonstrated for the same\n", - "example here." - ] - }, - { - "cell_type": "code", - "execution_count": 6, - "id": "557868b5", - "metadata": { - "collapsed": false, - "editable": true - }, - "outputs": [], - "source": [ - "import numpy as np\n", - "from sklearn.model_selection import train_test_split\n", - "from sklearn.linear_model import Ridge\n", - "from sklearn.model_selection import GridSearchCV\n", - "\n", - "def R2(y_data, y_model):\n", - " return 1 - np.sum((y_data - y_model) ** 2) / np.sum((y_data - np.mean(y_data)) ** 2)\n", - "\n", - "def MSE(y_data,y_model):\n", - " n = np.size(y_model)\n", - " return np.sum((y_data-y_model)**2)/n\n", - "\n", - "# A seed just to ensure that the random numbers are the same for every run.\n", - "# Useful for eventual debugging.\n", - "np.random.seed(2021)\n", - "\n", - "n = 100\n", - "x = np.random.rand(n)\n", - "y = np.exp(-x**2) + 1.5 * np.exp(-(x-2)**2)+ np.random.randn(n)\n", - "\n", - "Maxpolydegree = 5\n", - "X = np.zeros((n,Maxpolydegree-1))\n", - "\n", - "for degree in range(1,Maxpolydegree): #No intercept column\n", - " X[:,degree-1] = x**(degree)\n", - "\n", - "# We split the data in test and training data\n", - "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2)\n", - "\n", - "# Decide which values of lambda to use\n", - "nlambdas = 10\n", - "lambdas = np.logspace(-4, 2, nlambdas)\n", - "# create and fit a ridge regression model, testing each alpha\n", - "model = Ridge()\n", - "gridsearch = GridSearchCV(estimator=model, param_grid=dict(alpha=lambdas))\n", - "gridsearch.fit(X_train, y_train)\n", - "print(gridsearch)\n", - "ypredictRidge = gridsearch.predict(X_test)\n", - "# summarize the results of the grid search\n", - "print(f\"Best estimated lambda-value: {gridsearch.best_estimator_.alpha}\")\n", - "print(f\"MSE score: {MSE(y_test,ypredictRidge)}\")\n", - "print(f\"R2 score: {R2(y_test,ypredictRidge)}\")" - ] - }, - { - "cell_type": "markdown", - "id": "72f0779e", - "metadata": { - "editable": true - }, - "source": [ - "By default the grid search function includes cross validation with\n", - "five folds. The [Scikit-Learn\n", - "documentation](https://scikit-learn.org/stable/modules/generated/sklearn.model_selection.GridSearchCV.html#sklearn.model_selection.GridSearchCV)\n", - "contains more information on how to set the different parameters.\n", - "\n", - "If we take out the random noise, running the above codes results in $\\lambda=0$ yielding the best fit." - ] - }, - { - "cell_type": "markdown", - "id": "e6f83d4a", - "metadata": { - "editable": true - }, - "source": [ - "## Randomized Grid Search\n", - "\n", - "An alternative to the above manual grid set up, is to use a random\n", - "search where the parameters are tuned from a random distribution\n", - "(uniform below) for a fixed number of iterations. A model is\n", - "constructed and evaluated for each combination of chosen parameters.\n", - "We repeat the previous example but now with a random search. Note\n", - "that values of $\\lambda$ are now limited to be within $x\\in\n", - "[0,1]$. This domain may not be the most relevant one for the specific\n", - "case under study." - ] - }, - { - "cell_type": "code", - "execution_count": 7, - "id": "fadead70", - "metadata": { - "collapsed": false, - "editable": true - }, - "outputs": [], - "source": [ - "import numpy as np\n", - "from sklearn.model_selection import train_test_split\n", - "from sklearn.linear_model import Ridge\n", - "from sklearn.model_selection import GridSearchCV\n", - "from scipy.stats import uniform as randuniform\n", - "from sklearn.model_selection import RandomizedSearchCV\n", - "\n", - "\n", - "def R2(y_data, y_model):\n", - " return 1 - np.sum((y_data - y_model) ** 2) / np.sum((y_data - np.mean(y_data)) ** 2)\n", - "\n", - "def MSE(y_data,y_model):\n", - " n = np.size(y_model)\n", - " return np.sum((y_data-y_model)**2)/n\n", - "\n", - "# A seed just to ensure that the random numbers are the same for every run.\n", - "# Useful for eventual debugging.\n", - "np.random.seed(2021)\n", - "\n", - "n = 100\n", - "x = np.random.rand(n)\n", - "y = np.exp(-x**2) + 1.5 * np.exp(-(x-2)**2)+ np.random.randn(n)\n", - "\n", - "Maxpolydegree = 5\n", - "X = np.zeros((n,Maxpolydegree-1))\n", - "\n", - "for degree in range(1,Maxpolydegree): #No intercept column\n", - " X[:,degree-1] = x**(degree)\n", - "\n", - "# We split the data in test and training data\n", - "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2)\n", - "\n", - "param_grid = {'alpha': randuniform()}\n", - "# create and fit a ridge regression model, testing each alpha\n", - "model = Ridge()\n", - "gridsearch = RandomizedSearchCV(estimator=model, param_distributions=param_grid, n_iter=100)\n", - "gridsearch.fit(X_train, y_train)\n", - "print(gridsearch)\n", - "ypredictRidge = gridsearch.predict(X_test)\n", - "# summarize the results of the grid search\n", - "print(f\"Best estimated lambda-value: {gridsearch.best_estimator_.alpha}\")\n", - "print(f\"MSE score: {MSE(y_test,ypredictRidge)}\")\n", - "print(f\"R2 score: {R2(y_test,ypredictRidge)}\")" - ] - }, - { - "cell_type": "markdown", - "id": "42658f49", - "metadata": { - "editable": true - }, - "source": [ - "## Wisconsin Cancer Data\n", - "\n", - "We show here how we can use a simple regression case on the breast\n", - "cancer data using Logistic regression as our algorithm for\n", - "classification." - ] - }, - { - "cell_type": "code", - "execution_count": 8, - "id": "01c1d986", - "metadata": { - "collapsed": false, - "editable": true - }, - "outputs": [], - "source": [ - "import matplotlib.pyplot as plt\n", - "import numpy as np\n", - "from sklearn.model_selection import train_test_split \n", - "from sklearn.datasets import load_breast_cancer\n", - "from sklearn.linear_model import LogisticRegression\n", - "\n", - "# Load the data\n", - "cancer = load_breast_cancer()\n", - "\n", - "X_train, X_test, y_train, y_test = train_test_split(cancer.data,cancer.target,random_state=0)\n", - "print(X_train.shape)\n", - "print(X_test.shape)\n", - "# Logistic Regression\n", - "logreg = LogisticRegression(solver='lbfgs')\n", - "logreg.fit(X_train, y_train)\n", - "print(\"Test set accuracy with Logistic Regression: {:.2f}\".format(logreg.score(X_test,y_test)))" - ] - }, - { - "cell_type": "markdown", - "id": "a86570ee", - "metadata": { - "editable": true - }, - "source": [ - "## Using the correlation matrix\n", - "\n", - "In addition to the above scores, we could also study the covariance (and the correlation matrix).\n", - "We use **Pandas** to compute the correlation matrix." - ] - }, - { - "cell_type": "code", - "execution_count": 9, - "id": "e241e87e", - "metadata": { - "collapsed": false, - "editable": true - }, - "outputs": [], - "source": [ - "import matplotlib.pyplot as plt\n", - "import numpy as np\n", - "from sklearn.model_selection import train_test_split \n", - "from sklearn.datasets import load_breast_cancer\n", - "from sklearn.linear_model import LogisticRegression\n", - "cancer = load_breast_cancer()\n", - "import pandas as pd\n", - "# Making a data frame\n", - "cancerpd = pd.DataFrame(cancer.data, columns=cancer.feature_names)\n", - "\n", - "fig, axes = plt.subplots(15,2,figsize=(10,20))\n", - "malignant = cancer.data[cancer.target == 0]\n", - "benign = cancer.data[cancer.target == 1]\n", - "ax = axes.ravel()\n", - "\n", - "for i in range(30):\n", - " _, bins = np.histogram(cancer.data[:,i], bins =50)\n", - " ax[i].hist(malignant[:,i], bins = bins, alpha = 0.5)\n", - " ax[i].hist(benign[:,i], bins = bins, alpha = 0.5)\n", - " ax[i].set_title(cancer.feature_names[i])\n", - " ax[i].set_yticks(())\n", - "ax[0].set_xlabel(\"Feature magnitude\")\n", - "ax[0].set_ylabel(\"Frequency\")\n", - "ax[0].legend([\"Malignant\", \"Benign\"], loc =\"best\")\n", - "fig.tight_layout()\n", - "plt.show()\n", - "\n", - "import seaborn as sns\n", - "correlation_matrix = cancerpd.corr().round(1)\n", - "# use the heatmap function from seaborn to plot the correlation matrix\n", - "# annot = True to print the values inside the square\n", - "plt.figure(figsize=(15,8))\n", - "sns.heatmap(data=correlation_matrix, annot=True)\n", - "plt.show()" - ] - }, - { - "cell_type": "markdown", - "id": "31db566e", - "metadata": { - "editable": true - }, - "source": [ - "## Discussing the correlation data\n", - "\n", - "In the above example we note two things. In the first plot we display\n", - "the overlap of benign and malignant tumors as functions of the various\n", - "features in the Wisconsing breast cancer data set. We see that for\n", - "some of the features we can distinguish clearly the benign and\n", - "malignant cases while for other features we cannot. This can point to\n", - "us which features may be of greater interest when we wish to classify\n", - "a benign or not benign tumour.\n", - "\n", - "In the second figure we have computed the so-called correlation\n", - "matrix, which in our case with thirty features becomes a $30\\times 30$\n", - "matrix.\n", - "\n", - "We constructed this matrix using **pandas** via the statements" - ] - }, - { - "cell_type": "code", - "execution_count": 10, - "id": "5ddb180b", - "metadata": { - "collapsed": false, - "editable": true - }, - "outputs": [], - "source": [ - "cancerpd = pd.DataFrame(cancer.data, columns=cancer.feature_names)" - ] - }, - { - "cell_type": "markdown", - "id": "95c6a55b", - "metadata": { - "editable": true - }, - "source": [ - "and then" - ] - }, - { - "cell_type": "code", - "execution_count": 11, - "id": "f3347712", - "metadata": { - "collapsed": false, - "editable": true - }, - "outputs": [], - "source": [ - "correlation_matrix = cancerpd.corr().round(1)" - ] - }, - { - "cell_type": "markdown", - "id": "f60362a3", - "metadata": { - "editable": true - }, - "source": [ - "Diagonalizing this matrix we can in turn say something about which\n", - "features are of relevance and which are not. This leads us to\n", - "the classical Principal Component Analysis (PCA) theorem with\n", - "applications. This will be discussed later this semester ([week 43](https://compphysics.github.io/MachineLearning/doc/pub/week43/html/week43-bs.html))." - ] - }, - { - "cell_type": "markdown", - "id": "232f7e0d", - "metadata": { - "editable": true - }, - "source": [ - "## Other measures in classification studies: Cancer Data again" - ] - }, - { - "cell_type": "code", - "execution_count": 12, - "id": "552632a5", - "metadata": { - "collapsed": false, - "editable": true - }, - "outputs": [], - "source": [ - "import matplotlib.pyplot as plt\n", - "import numpy as np\n", - "from sklearn.model_selection import train_test_split \n", - "from sklearn.datasets import load_breast_cancer\n", - "from sklearn.linear_model import LogisticRegression\n", - "\n", - "# Load the data\n", - "cancer = load_breast_cancer()\n", - "\n", - "X_train, X_test, y_train, y_test = train_test_split(cancer.data,cancer.target,random_state=0)\n", - "print(X_train.shape)\n", - "print(X_test.shape)\n", - "# Logistic Regression\n", - "logreg = LogisticRegression(solver='lbfgs')\n", - "logreg.fit(X_train, y_train)\n", - "\n", - "from sklearn.preprocessing import LabelEncoder\n", - "from sklearn.model_selection import cross_validate\n", - "#Cross validation\n", - "accuracy = cross_validate(logreg,X_test,y_test,cv=10)['test_score']\n", - "print(accuracy)\n", - "print(\"Test set accuracy with Logistic Regression: {:.2f}\".format(logreg.score(X_test,y_test)))\n", - "\n", - "import scikitplot as skplt\n", - "y_pred = logreg.predict(X_test)\n", - "skplt.metrics.plot_confusion_matrix(y_test, y_pred, normalize=True)\n", - "plt.show()\n", - "y_probas = logreg.predict_proba(X_test)\n", - "skplt.metrics.plot_roc(y_test, y_probas)\n", - "plt.show()\n", - "skplt.metrics.plot_cumulative_gain(y_test, y_probas)\n", - "plt.show()" - ] - }, - { - "cell_type": "markdown", - "id": "7752c5ea", - "metadata": { - "editable": true - }, - "source": [ - "## Optimization, the central part of any Machine Learning algortithm\n", - "\n", - "[Overview Video, why do we care about gradient methods?](https://www.uio.no/studier/emner/matnat/fys/FYS-STK3155/h20/forelesningsvideoer/OverarchingAimsWeek39.mp4?vrtx=view-as-webpage)\n", - "\n", - "Almost every problem in machine learning and data science starts with\n", - "a dataset $X$, a model $g(\\beta)$, which is a function of the\n", - "parameters $\\beta$ and a cost function $C(X, g(\\beta))$ that allows\n", - "us to judge how well the model $g(\\beta)$ explains the observations\n", - "$X$. The model is fit by finding the values of $\\beta$ that minimize\n", - "the cost function. Ideally we would be able to solve for $\\beta$\n", - "analytically, however this is not possible in general and we must use\n", - "some approximative/numerical method to compute the minimum." - ] - }, - { - "cell_type": "markdown", - "id": "f307c73e", - "metadata": { - "editable": true - }, - "source": [ - "## Revisiting our Logistic Regression case\n", - "\n", - "In our discussion on Logistic Regression we studied the \n", - "case of\n", - "two classes, with $y_i$ either\n", - "$0$ or $1$. Furthermore we assumed also that we have only two\n", - "parameters $\\beta$ in our fitting, that is we\n", - "defined probabilities" - ] - }, - { - "cell_type": "markdown", - "id": "921fcab7", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\begin{align*}\n", - "p(y_i=1|x_i,\\boldsymbol{\\beta}) &= \\frac{\\exp{(\\beta_0+\\beta_1x_i)}}{1+\\exp{(\\beta_0+\\beta_1x_i)}},\\nonumber\\\\\n", - "p(y_i=0|x_i,\\boldsymbol{\\beta}) &= 1 - p(y_i=1|x_i,\\boldsymbol{\\beta}),\n", - "\\end{align*}\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "9863a96d", - "metadata": { - "editable": true - }, - "source": [ - "where $\\boldsymbol{\\beta}$ are the weights we wish to extract from data, in our case $\\beta_0$ and $\\beta_1$." - ] - }, - { - "cell_type": "markdown", - "id": "69a4b9a3", - "metadata": { - "editable": true - }, - "source": [ - "## The equations to solve\n", - "\n", - "Our compact equations used a definition of a vector $\\boldsymbol{y}$ with $n$\n", - "elements $y_i$, an $n\\times p$ matrix $\\boldsymbol{X}$ which contains the\n", - "$x_i$ values and a vector $\\boldsymbol{p}$ of fitted probabilities\n", - "$p(y_i\\vert x_i,\\boldsymbol{\\beta})$. We rewrote in a more compact form\n", - "the first derivative of the cost function as" - ] - }, - { - "cell_type": "markdown", - "id": "f3f454ef", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\frac{\\partial \\mathcal{C}(\\boldsymbol{\\beta})}{\\partial \\boldsymbol{\\beta}} = -\\boldsymbol{X}^T\\left(\\boldsymbol{y}-\\boldsymbol{p}\\right).\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "8ba81e87", - "metadata": { - "editable": true - }, - "source": [ - "If we in addition define a diagonal matrix $\\boldsymbol{W}$ with elements \n", - "$p(y_i\\vert x_i,\\boldsymbol{\\beta})(1-p(y_i\\vert x_i,\\boldsymbol{\\beta})$, we can obtain a compact expression of the second derivative as" - ] - }, - { - "cell_type": "markdown", - "id": "0b87735e", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\frac{\\partial^2 \\mathcal{C}(\\boldsymbol{\\beta})}{\\partial \\boldsymbol{\\beta}\\partial \\boldsymbol{\\beta}^T} = \\boldsymbol{X}^T\\boldsymbol{W}\\boldsymbol{X}.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "3de8fc00", - "metadata": { - "editable": true - }, - "source": [ - "This defines what is called the Hessian matrix." - ] - }, - { - "cell_type": "markdown", - "id": "a582cfba", - "metadata": { - "editable": true - }, - "source": [ - "## Solving using Newton-Raphson's method\n", - "\n", - "If we can set up these equations, Newton-Raphson's iterative method is normally the method of choice. It requires however that we can compute in an efficient way the matrices that define the first and second derivatives. \n", - "\n", - "Our iterative scheme is then given by" - ] - }, - { - "cell_type": "markdown", - "id": "7cb1055f", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\boldsymbol{\\beta}^{\\mathrm{new}} = \\boldsymbol{\\beta}^{\\mathrm{old}}-\\left(\\frac{\\partial^2 \\mathcal{C}(\\boldsymbol{\\beta})}{\\partial \\boldsymbol{\\beta}\\partial \\boldsymbol{\\beta}^T}\\right)^{-1}_{\\boldsymbol{\\beta}^{\\mathrm{old}}}\\times \\left(\\frac{\\partial \\mathcal{C}(\\boldsymbol{\\beta})}{\\partial \\boldsymbol{\\beta}}\\right)_{\\boldsymbol{\\beta}^{\\mathrm{old}}},\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "ecea7f51", - "metadata": { - "editable": true - }, - "source": [ - "or in matrix form as" - ] - }, - { - "cell_type": "markdown", - "id": "f98861e3", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\boldsymbol{\\beta}^{\\mathrm{new}} = \\boldsymbol{\\beta}^{\\mathrm{old}}-\\left(\\boldsymbol{X}^T\\boldsymbol{W}\\boldsymbol{X} \\right)^{-1}\\times \\left(-\\boldsymbol{X}^T(\\boldsymbol{y}-\\boldsymbol{p}) \\right)_{\\boldsymbol{\\beta}^{\\mathrm{old}}}.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "4fd11bf8", - "metadata": { - "editable": true - }, - "source": [ - "The right-hand side is computed with the old values of $\\beta$. \n", - "\n", - "If we can compute these matrices, in particular the Hessian, the above is often the easiest method to implement." - ] - }, - { - "cell_type": "markdown", - "id": "9b7f27a4", - "metadata": { - "editable": true - }, - "source": [ - "## Brief reminder on Newton-Raphson's method\n", - "\n", - "Let us quickly remind ourselves how we derive the above method.\n", - "\n", - "Perhaps the most celebrated of all one-dimensional root-finding\n", - "routines is Newton's method, also called the Newton-Raphson\n", - "method. This method requires the evaluation of both the\n", - "function $f$ and its derivative $f'$ at arbitrary points. \n", - "If you can only calculate the derivative\n", - "numerically and/or your function is not of the smooth type, we\n", - "normally discourage the use of this method." - ] - }, - { - "cell_type": "markdown", - "id": "50e2e1f0", - "metadata": { - "editable": true - }, - "source": [ - "## The equations\n", - "\n", - "The Newton-Raphson formula consists geometrically of extending the\n", - "tangent line at a current point until it crosses zero, then setting\n", - "the next guess to the abscissa of that zero-crossing. The mathematics\n", - "behind this method is rather simple. Employing a Taylor expansion for\n", - "$x$ sufficiently close to the solution $s$, we have" - ] - }, - { - "cell_type": "markdown", - "id": "5605583d", - "metadata": { - "editable": true - }, - "source": [ - "\n", - "
\n", - "\n", - "$$\n", - "f(s)=0=f(x)+(s-x)f'(x)+\\frac{(s-x)^2}{2}f''(x) +\\dots.\n", - " \\label{eq:taylornr} \\tag{2}\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "d6ce1a0c", - "metadata": { - "editable": true - }, - "source": [ - "For small enough values of the function and for well-behaved\n", - "functions, the terms beyond linear are unimportant, hence we obtain" - ] - }, - { - "cell_type": "markdown", - "id": "7462cf59", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "f(x)+(s-x)f'(x)\\approx 0,\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "b3609230", - "metadata": { - "editable": true - }, - "source": [ - "yielding" - ] - }, - { - "cell_type": "markdown", - "id": "63c5804e", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "s\\approx x-\\frac{f(x)}{f'(x)}.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "2f6643d0", - "metadata": { - "editable": true - }, - "source": [ - "Having in mind an iterative procedure, it is natural to start iterating with" - ] - }, - { - "cell_type": "markdown", - "id": "58afbcf0", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "x_{n+1}=x_n-\\frac{f(x_n)}{f'(x_n)}.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "61a12296", - "metadata": { - "editable": true - }, - "source": [ - "## Simple geometric interpretation\n", - "\n", - "The above is Newton-Raphson's method. It has a simple geometric\n", - "interpretation, namely $x_{n+1}$ is the point where the tangent from\n", - "$(x_n,f(x_n))$ crosses the $x$-axis. Close to the solution,\n", - "Newton-Raphson converges fast to the desired result. However, if we\n", - "are far from a root, where the higher-order terms in the series are\n", - "important, the Newton-Raphson formula can give grossly inaccurate\n", - "results. For instance, the initial guess for the root might be so far\n", - "from the true root as to let the search interval include a local\n", - "maximum or minimum of the function. If an iteration places a trial\n", - "guess near such a local extremum, so that the first derivative nearly\n", - "vanishes, then Newton-Raphson may fail totally" - ] - }, - { - "cell_type": "markdown", - "id": "39144130", - "metadata": { - "editable": true - }, - "source": [ - "## Extending to more than one variable\n", - "\n", - "Newton's method can be generalized to systems of several non-linear equations\n", - "and variables. Consider the case with two equations" - ] - }, - { - "cell_type": "markdown", - "id": "b98db024", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\begin{array}{cc} f_1(x_1,x_2) &=0\\\\\n", - " f_2(x_1,x_2) &=0,\\end{array}\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "79154f84", - "metadata": { - "editable": true - }, - "source": [ - "which we Taylor expand to obtain" - ] - }, - { - "cell_type": "markdown", - "id": "2b225307", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\begin{array}{cc} 0=f_1(x_1+h_1,x_2+h_2)=&f_1(x_1,x_2)+h_1\n", - " \\partial f_1/\\partial x_1+h_2\n", - " \\partial f_1/\\partial x_2+\\dots\\\\\n", - " 0=f_2(x_1+h_1,x_2+h_2)=&f_2(x_1,x_2)+h_1\n", - " \\partial f_2/\\partial x_1+h_2\n", - " \\partial f_2/\\partial x_2+\\dots\n", - " \\end{array}.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "72363dfd", - "metadata": { - "editable": true - }, - "source": [ - "Defining the Jacobian matrix ${\\bf \\boldsymbol{J}}$ we have" - ] - }, - { - "cell_type": "markdown", - "id": "7608f604", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "{\\bf \\boldsymbol{J}}=\\left( \\begin{array}{cc}\n", - " \\partial f_1/\\partial x_1 & \\partial f_1/\\partial x_2 \\\\\n", - " \\partial f_2/\\partial x_1 &\\partial f_2/\\partial x_2\n", - " \\end{array} \\right),\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "d10f9e88", - "metadata": { - "editable": true - }, - "source": [ - "we can rephrase Newton's method as" - ] - }, - { - "cell_type": "markdown", - "id": "e8a79127", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\left(\\begin{array}{c} x_1^{n+1} \\\\ x_2^{n+1} \\end{array} \\right)=\n", - "\\left(\\begin{array}{c} x_1^{n} \\\\ x_2^{n} \\end{array} \\right)+\n", - "\\left(\\begin{array}{c} h_1^{n} \\\\ h_2^{n} \\end{array} \\right),\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "d8451a71", - "metadata": { - "editable": true - }, - "source": [ - "where we have defined" - ] - }, - { - "cell_type": "markdown", - "id": "8c2c4387", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\left(\\begin{array}{c} h_1^{n} \\\\ h_2^{n} \\end{array} \\right)=\n", - " -{\\bf \\boldsymbol{J}}^{-1}\n", - " \\left(\\begin{array}{c} f_1(x_1^{n},x_2^{n}) \\\\ f_2(x_1^{n},x_2^{n}) \\end{array} \\right).\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "3dc3a90d", - "metadata": { - "editable": true - }, - "source": [ - "We need thus to compute the inverse of the Jacobian matrix and it\n", - "is to understand that difficulties may\n", - "arise in case ${\\bf \\boldsymbol{J}}$ is nearly singular.\n", - "\n", - "It is rather straightforward to extend the above scheme to systems of\n", - "more than two non-linear equations. In our case, the Jacobian matrix is given by the Hessian that represents the second derivative of cost function." - ] - }, - { - "cell_type": "markdown", - "id": "fee016c8", - "metadata": { - "editable": true - }, - "source": [ - "## Steepest descent\n", - "\n", - "The basic idea of gradient descent is\n", - "that a function $F(\\mathbf{x})$, \n", - "$\\mathbf{x} \\equiv (x_1,\\cdots,x_n)$, decreases fastest if one goes from $\\bf {x}$ in the\n", - "direction of the negative gradient $-\\nabla F(\\mathbf{x})$.\n", - "\n", - "It can be shown that if" - ] - }, - { - "cell_type": "markdown", - "id": "e4340278", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\mathbf{x}_{k+1} = \\mathbf{x}_k - \\gamma_k \\nabla F(\\mathbf{x}_k),\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "d2af5812", - "metadata": { - "editable": true - }, - "source": [ - "with $\\gamma_k > 0$.\n", - "\n", - "For $\\gamma_k$ small enough, then $F(\\mathbf{x}_{k+1}) \\leq\n", - "F(\\mathbf{x}_k)$. This means that for a sufficiently small $\\gamma_k$\n", - "we are always moving towards smaller function values, i.e a minimum." - ] - }, - { - "cell_type": "markdown", - "id": "a8237bc8", - "metadata": { - "editable": true - }, - "source": [ - "## More on Steepest descent\n", - "\n", - "The previous observation is the basis of the method of steepest\n", - "descent, which is also referred to as just gradient descent (GD). One\n", - "starts with an initial guess $\\mathbf{x}_0$ for a minimum of $F$ and\n", - "computes new approximations according to" - ] - }, - { - "cell_type": "markdown", - "id": "079c64d8", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\mathbf{x}_{k+1} = \\mathbf{x}_k - \\gamma_k \\nabla F(\\mathbf{x}_k), \\ \\ k \\geq 0.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "08da6b25", - "metadata": { - "editable": true - }, - "source": [ - "The parameter $\\gamma_k$ is often referred to as the step length or\n", - "the learning rate within the context of Machine Learning." - ] - }, - { - "cell_type": "markdown", - "id": "7c1a4917", - "metadata": { - "editable": true - }, - "source": [ - "## The ideal\n", - "\n", - "Ideally the sequence $\\{\\mathbf{x}_k \\}_{k=0}$ converges to a global\n", - "minimum of the function $F$. In general we do not know if we are in a\n", - "global or local minimum. In the special case when $F$ is a convex\n", - "function, all local minima are also global minima, so in this case\n", - "gradient descent can converge to the global solution. The advantage of\n", - "this scheme is that it is conceptually simple and straightforward to\n", - "implement. However the method in this form has some severe\n", - "limitations:\n", - "\n", - "In machine learing we are often faced with non-convex high dimensional\n", - "cost functions with many local minima. Since GD is deterministic we\n", - "will get stuck in a local minimum, if the method converges, unless we\n", - "have a very good intial guess. This also implies that the scheme is\n", - "sensitive to the chosen initial condition.\n", - "\n", - "Note that the gradient is a function of $\\mathbf{x} =\n", - "(x_1,\\cdots,x_n)$ which makes it expensive to compute numerically." - ] - }, - { - "cell_type": "markdown", - "id": "4d2aabf0", - "metadata": { - "editable": true - }, - "source": [ - "## The sensitiveness of the gradient descent\n", - "\n", - "The gradient descent method \n", - "is sensitive to the choice of learning rate $\\gamma_k$. This is due\n", - "to the fact that we are only guaranteed that $F(\\mathbf{x}_{k+1}) \\leq\n", - "F(\\mathbf{x}_k)$ for sufficiently small $\\gamma_k$. The problem is to\n", - "determine an optimal learning rate. If the learning rate is chosen too\n", - "small the method will take a long time to converge and if it is too\n", - "large we can experience erratic behavior.\n", - "\n", - "Many of these shortcomings can be alleviated by introducing\n", - "randomness. One such method is that of Stochastic Gradient Descent\n", - "(SGD), to be discussed next week." - ] - }, - { - "cell_type": "markdown", - "id": "7377154c", - "metadata": { - "editable": true - }, - "source": [ - "## Convex functions\n", - "\n", - "Ideally we want our cost/loss function to be convex(concave).\n", - "\n", - "First we give the definition of a convex set: A set $C$ in\n", - "$\\mathbb{R}^n$ is said to be convex if, for all $x$ and $y$ in $C$ and\n", - "all $t \\in (0,1)$ , the point $(1 − t)x + ty$ also belongs to\n", - "C. Geometrically this means that every point on the line segment\n", - "connecting $x$ and $y$ is in $C$ as discussed below.\n", - "\n", - "The convex subsets of $\\mathbb{R}$ are the intervals of\n", - "$\\mathbb{R}$. Examples of convex sets of $\\mathbb{R}^2$ are the\n", - "regular polygons (triangles, rectangles, pentagons, etc...)." - ] - }, - { - "cell_type": "markdown", - "id": "697326eb", - "metadata": { - "editable": true - }, - "source": [ - "## Convex function\n", - "\n", - "**Convex function**: Let $X \\subset \\mathbb{R}^n$ be a convex set. Assume that the function $f: X \\rightarrow \\mathbb{R}$ is continuous, then $f$ is said to be convex if $$f(tx_1 + (1-t)x_2) \\leq tf(x_1) + (1-t)f(x_2) $$ for all $x_1, x_2 \\in X$ and for all $t \\in [0,1]$. If $\\leq$ is replaced with a strict inequaltiy in the definition, we demand $x_1 \\neq x_2$ and $t\\in(0,1)$ then $f$ is said to be strictly convex. For a single variable function, convexity means that if you draw a straight line connecting $f(x_1)$ and $f(x_2)$, the value of the function on the interval $[x_1,x_2]$ is always below the line as illustrated below." - ] - }, - { - "cell_type": "markdown", - "id": "a532b777", - "metadata": { - "editable": true - }, - "source": [ - "## Conditions on convex functions\n", - "\n", - "In the following we state first and second-order conditions which\n", - "ensures convexity of a function $f$. We write $D_f$ to denote the\n", - "domain of $f$, i.e the subset of $R^n$ where $f$ is defined. For more\n", - "details and proofs we refer to: [S. Boyd and L. Vandenberghe. Convex Optimization. Cambridge University Press](http://stanford.edu/boyd/cvxbook/, 2004).\n", - "\n", - "**First order condition.**\n", - "\n", - "Suppose $f$ is differentiable (i.e $\\nabla f(x)$ is well defined for\n", - "all $x$ in the domain of $f$). Then $f$ is convex if and only if $D_f$\n", - "is a convex set and $$f(y) \\geq f(x) + \\nabla f(x)^T (y-x) $$ holds\n", - "for all $x,y \\in D_f$. This condition means that for a convex function\n", - "the first order Taylor expansion (right hand side above) at any point\n", - "a global under estimator of the function. To convince yourself you can\n", - "make a drawing of $f(x) = x^2+1$ and draw the tangent line to $f(x)$ and\n", - "note that it is always below the graph.\n", - "\n", - "**Second order condition.**\n", - "\n", - "Assume that $f$ is twice\n", - "differentiable, i.e the Hessian matrix exists at each point in\n", - "$D_f$. Then $f$ is convex if and only if $D_f$ is a convex set and its\n", - "Hessian is positive semi-definite for all $x\\in D_f$. For a\n", - "single-variable function this reduces to $f''(x) \\geq 0$. Geometrically this means that $f$ has nonnegative curvature\n", - "everywhere.\n", - "\n", - "This condition is particularly useful since it gives us an procedure for determining if the function under consideration is convex, apart from using the definition." - ] - }, - { - "cell_type": "markdown", - "id": "ad4152f5", - "metadata": { - "editable": true - }, - "source": [ - "## More on convex functions\n", - "\n", - "The next result is of great importance to us and the reason why we are\n", - "going on about convex functions. In machine learning we frequently\n", - "have to minimize a loss/cost function in order to find the best\n", - "parameters for the model we are considering. \n", - "\n", - "Ideally we want the\n", - "global minimum (for high-dimensional models it is hard to know\n", - "if we have local or global minimum). However, if the cost/loss function\n", - "is convex the following result provides invaluable information:\n", - "\n", - "**Any minimum is global for convex functions.**\n", - "\n", - "Consider the problem of finding $x \\in \\mathbb{R}^n$ such that $f(x)$\n", - "is minimal, where $f$ is convex and differentiable. Then, any point\n", - "$x^*$ that satisfies $\\nabla f(x^*) = 0$ is a global minimum.\n", - "\n", - "This result means that if we know that the cost/loss function is convex and we are able to find a minimum, we are guaranteed that it is a global minimum." - ] - }, - { - "cell_type": "markdown", - "id": "e48d339b", - "metadata": { - "editable": true - }, - "source": [ - "## Some simple problems\n", - "\n", - "1. Show that $f(x)=x^2$ is convex for $x \\in \\mathbb{R}$ using the definition of convexity. Hint: If you re-write the definition, $f$ is convex if the following holds for all $x,y \\in D_f$ and any $\\lambda \\in [0,1]$ $\\lambda f(x)+(1-\\lambda)f(y)-f(\\lambda x + (1-\\lambda) y ) \\geq 0$.\n", - "\n", - "2. Using the second order condition show that the following functions are convex on the specified domain.\n", - "\n", - " * $f(x) = e^x$ is convex for $x \\in \\mathbb{R}$.\n", - "\n", - " * $g(x) = -\\ln(x)$ is convex for $x \\in (0,\\infty)$.\n", - "\n", - "3. Let $f(x) = x^2$ and $g(x) = e^x$. Show that $f(g(x))$ and $g(f(x))$ is convex for $x \\in \\mathbb{R}$. Also show that if $f(x)$ is any convex function than $h(x) = e^{f(x)}$ is convex.\n", - "\n", - "4. A norm is any function that satisfy the following properties\n", - "\n", - " * $f(\\alpha x) = |\\alpha| f(x)$ for all $\\alpha \\in \\mathbb{R}$.\n", - "\n", - " * $f(x+y) \\leq f(x) + f(y)$\n", - "\n", - " * $f(x) \\leq 0$ for all $x \\in \\mathbb{R}^n$ with equality if and only if $x = 0$\n", - "\n", - "Using the definition of convexity, try to show that a function satisfying the properties above is convex (the third condition is not needed to show this)." - ] - }, - { - "cell_type": "markdown", - "id": "9ae5c509", - "metadata": { - "editable": true - }, - "source": [ - "## Revisiting our first homework\n", - "\n", - "We will use linear regression as a case study for the gradient descent\n", - "methods. Linear regression is a great test case for the gradient\n", - "descent methods discussed in the lectures since it has several\n", - "desirable properties such as:\n", - "\n", - "1. An analytical solution (recall homework set 1).\n", - "\n", - "2. The gradient can be computed analytically.\n", - "\n", - "3. The cost function is convex which guarantees that gradient descent converges for small enough learning rates\n", - "\n", - "We revisit an example similar to what we had in the first homework set. We had a function of the type" - ] - }, - { - "cell_type": "code", - "execution_count": 13, - "id": "dd182f20", - "metadata": { - "collapsed": false, - "editable": true - }, - "outputs": [], - "source": [ - "x = 2*np.random.rand(m,1)\n", - "y = 4+3*x+np.random.randn(m,1)" - ] - }, - { - "cell_type": "markdown", - "id": "eef5bc40", - "metadata": { - "editable": true - }, - "source": [ - "with $x_i \\in [0,1] $ is chosen randomly using a uniform distribution. Additionally we have a stochastic noise chosen according to a normal distribution $\\cal {N}(0,1)$. \n", - "The linear regression model is given by" - ] - }, - { - "cell_type": "markdown", - "id": "2af1247d", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "h_\\beta(x) = \\boldsymbol{y} = \\beta_0 + \\beta_1 x,\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "20fcf8f2", - "metadata": { - "editable": true - }, - "source": [ - "such that" - ] - }, - { - "cell_type": "markdown", - "id": "2b6947aa", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\boldsymbol{y}_i = \\beta_0 + \\beta_1 x_i.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "c5838344", - "metadata": { - "editable": true - }, - "source": [ - "## Gradient descent example\n", - "\n", - "Let $\\mathbf{y} = (y_1,\\cdots,y_n)^T$, $\\mathbf{\\boldsymbol{y}} = (\\boldsymbol{y}_1,\\cdots,\\boldsymbol{y}_n)^T$ and $\\beta = (\\beta_0, \\beta_1)^T$\n", - "\n", - "It is convenient to write $\\mathbf{\\boldsymbol{y}} = X\\beta$ where $X \\in \\mathbb{R}^{100 \\times 2} $ is the design matrix given by (we keep the intercept here)" - ] - }, - { - "cell_type": "markdown", - "id": "c5af1dca", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "X \\equiv \\begin{bmatrix}\n", - "1 & x_1 \\\\\n", - "\\vdots & \\vdots \\\\\n", - "1 & x_{100} & \\\\\n", - "\\end{bmatrix}.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "f380504f", - "metadata": { - "editable": true - }, - "source": [ - "The cost/loss/risk function is given by (" - ] - }, - { - "cell_type": "markdown", - "id": "c4e7530e", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "C(\\beta) = \\frac{1}{n}||X\\beta-\\mathbf{y}||_{2}^{2} = \\frac{1}{n}\\sum_{i=1}^{100}\\left[ (\\beta_0 + \\beta_1 x_i)^2 - 2 y_i (\\beta_0 + \\beta_1 x_i) + y_i^2\\right]\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "babaeeee", - "metadata": { - "editable": true - }, - "source": [ - "and we want to find $\\beta$ such that $C(\\beta)$ is minimized." - ] - }, - { - "cell_type": "markdown", - "id": "1f25dc02", - "metadata": { - "editable": true - }, - "source": [ - "## The derivative of the cost/loss function\n", - "\n", - "Computing $\\partial C(\\beta) / \\partial \\beta_0$ and $\\partial C(\\beta) / \\partial \\beta_1$ we can show that the gradient can be written as" - ] - }, - { - "cell_type": "markdown", - "id": "58eb4735", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\nabla_{\\beta} C(\\beta) = \\frac{2}{n}\\begin{bmatrix} \\sum_{i=1}^{100} \\left(\\beta_0+\\beta_1x_i-y_i\\right) \\\\\n", - "\\sum_{i=1}^{100}\\left( x_i (\\beta_0+\\beta_1x_i)-y_ix_i\\right) \\\\\n", - "\\end{bmatrix} = \\frac{2}{n}X^T(X\\beta - \\mathbf{y}),\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "32f33b17", - "metadata": { - "editable": true - }, - "source": [ - "where $X$ is the design matrix defined above." - ] - }, - { - "cell_type": "markdown", - "id": "02ffa8c7", - "metadata": { - "editable": true - }, - "source": [ - "## The Hessian matrix\n", - "The Hessian matrix of $C(\\beta)$ is given by" - ] - }, - { - "cell_type": "markdown", - "id": "7009c819", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\boldsymbol{H} \\equiv \\begin{bmatrix}\n", - "\\frac{\\partial^2 C(\\beta)}{\\partial \\beta_0^2} & \\frac{\\partial^2 C(\\beta)}{\\partial \\beta_0 \\partial \\beta_1} \\\\\n", - "\\frac{\\partial^2 C(\\beta)}{\\partial \\beta_0 \\partial \\beta_1} & \\frac{\\partial^2 C(\\beta)}{\\partial \\beta_1^2} & \\\\\n", - "\\end{bmatrix} = \\frac{2}{n}X^T X.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "71cf8211", - "metadata": { - "editable": true - }, - "source": [ - "This result implies that $C(\\beta)$ is a convex function since the matrix $X^T X$ always is positive semi-definite." - ] - }, - { - "cell_type": "markdown", - "id": "b41b50aa", - "metadata": { - "editable": true - }, - "source": [ - "## Simple program\n", - "\n", - "We can now write a program that minimizes $C(\\beta)$ using the gradient descent method with a constant learning rate $\\gamma$ according to" - ] - }, - { - "cell_type": "markdown", - "id": "1b52d696", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\beta_{k+1} = \\beta_k - \\gamma \\nabla_\\beta C(\\beta_k), \\ k=0,1,\\cdots\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "ef629c8b", - "metadata": { - "editable": true - }, - "source": [ - "We can use the expression we computed for the gradient and let use a\n", - "$\\beta_0$ be chosen randomly and let $\\gamma = 0.001$. Stop iterating\n", - "when $||\\nabla_\\beta C(\\beta_k) || \\leq \\epsilon = 10^{-8}$. **Note that the code below does not include the latter stop criterion**.\n", - "\n", - "And finally we can compare our solution for $\\beta$ with the analytic result given by \n", - "$\\beta= (X^TX)^{-1} X^T \\mathbf{y}$." - ] - }, - { - "cell_type": "markdown", - "id": "0c30718a", - "metadata": { - "editable": true - }, - "source": [ - "## Gradient Descent Example\n", - "\n", - "Here our simple example" - ] - }, - { - "cell_type": "code", - "execution_count": 14, - "id": "84f33bde", - "metadata": { - "collapsed": false, - "editable": true - }, - "outputs": [], - "source": [ - "\n", - "# Importing various packages\n", - "from random import random, seed\n", - "import numpy as np\n", - "import matplotlib.pyplot as plt\n", - "from mpl_toolkits.mplot3d import Axes3D\n", - "from matplotlib import cm\n", - "from matplotlib.ticker import LinearLocator, FormatStrFormatter\n", - "import sys\n", - "\n", - "# the number of datapoints\n", - "n = 100\n", - "x = 2*np.random.rand(n,1)\n", - "y = 4+3*x+np.random.randn(n,1)\n", - "\n", - "X = np.c_[np.ones((n,1)), x]\n", - "# Hessian matrix\n", - "H = (2.0/n)* X.T @ X\n", - "# Get the eigenvalues\n", - "EigValues, EigVectors = np.linalg.eig(H)\n", - "print(f\"Eigenvalues of Hessian Matrix:{EigValues}\")\n", - "\n", - "beta_linreg = np.linalg.inv(X.T @ X) @ X.T @ y\n", - "print(beta_linreg)\n", - "beta = np.random.randn(2,1)\n", - "\n", - "eta = 1.0/np.max(EigValues)\n", - "Niterations = 1000\n", - "\n", - "for iter in range(Niterations):\n", - " gradient = (2.0/n)*X.T @ (X @ beta-y)\n", - " beta -= eta*gradient\n", - "\n", - "print(beta)\n", - "xnew = np.array([[0],[2]])\n", - "xbnew = np.c_[np.ones((2,1)), xnew]\n", - "ypredict = xbnew.dot(beta)\n", - "ypredict2 = xbnew.dot(beta_linreg)\n", - "plt.plot(xnew, ypredict, \"r-\")\n", - "plt.plot(xnew, ypredict2, \"b-\")\n", - "plt.plot(x, y ,'ro')\n", - "plt.axis([0,2.0,0, 15.0])\n", - "plt.xlabel(r'$x$')\n", - "plt.ylabel(r'$y$')\n", - "plt.title(r'Gradient descent example')\n", - "plt.show()" - ] - }, - { - "cell_type": "markdown", - "id": "d332552b", - "metadata": { - "editable": true - }, - "source": [ - "## And a corresponding example using **scikit-learn**" - ] - }, - { - "cell_type": "code", - "execution_count": 15, - "id": "c46612a1", - "metadata": { - "collapsed": false, - "editable": true - }, - "outputs": [], - "source": [ - "# Importing various packages\n", - "from random import random, seed\n", - "import numpy as np\n", - "import matplotlib.pyplot as plt\n", - "from sklearn.linear_model import SGDRegressor\n", - "\n", - "n = 100\n", - "x = 2*np.random.rand(n,1)\n", - "y = 4+3*x+np.random.randn(n,1)\n", - "\n", - "X = np.c_[np.ones((n,1)), x]\n", - "beta_linreg = np.linalg.inv(X.T @ X) @ (X.T @ y)\n", - "print(beta_linreg)\n", - "sgdreg = SGDRegressor(max_iter = 50, penalty=None, eta0=0.1)\n", - "sgdreg.fit(x,y.ravel())\n", - "print(sgdreg.intercept_, sgdreg.coef_)" - ] - }, - { - "cell_type": "markdown", - "id": "2aa00fc2", - "metadata": { - "editable": true - }, - "source": [ - "## Gradient descent and Ridge\n", - "\n", - "We have also discussed Ridge regression where the loss function contains a regularized term given by the $L_2$ norm of $\\beta$," - ] - }, - { - "cell_type": "markdown", - "id": "c2d248a4", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "C_{\\text{ridge}}(\\beta) = \\frac{1}{n}||X\\beta -\\mathbf{y}||^2 + \\lambda ||\\beta||^2, \\ \\lambda \\geq 0.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "fa969e77", - "metadata": { - "editable": true - }, - "source": [ - "In order to minimize $C_{\\text{ridge}}(\\beta)$ using GD we adjust the gradient as follows" - ] - }, - { - "cell_type": "markdown", - "id": "60d7d114", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\nabla_\\beta C_{\\text{ridge}}(\\beta) = \\frac{2}{n}\\begin{bmatrix} \\sum_{i=1}^{100} \\left(\\beta_0+\\beta_1x_i-y_i\\right) \\\\\n", - "\\sum_{i=1}^{100}\\left( x_i (\\beta_0+\\beta_1x_i)-y_ix_i\\right) \\\\\n", - "\\end{bmatrix} + 2\\lambda\\begin{bmatrix} \\beta_0 \\\\ \\beta_1\\end{bmatrix} = 2 (\\frac{1}{n}X^T(X\\beta - \\mathbf{y})+\\lambda \\beta).\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "a281f2c0", - "metadata": { - "editable": true - }, - "source": [ - "We can easily extend our program to minimize $C_{\\text{ridge}}(\\beta)$ using gradient descent and compare with the analytical solution given by" - ] - }, - { - "cell_type": "markdown", - "id": "5c40a890", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\beta_{\\text{ridge}} = \\left(X^T X + n\\lambda I_{2 \\times 2} \\right)^{-1} X^T \\mathbf{y}.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "5e848da6", - "metadata": { - "editable": true - }, - "source": [ - "## The Hessian matrix for Ridge Regression\n", - "The Hessian matrix of Ridge Regression for our simple example is given by" - ] - }, - { - "cell_type": "markdown", - "id": "54b17645", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\boldsymbol{H} \\equiv \\begin{bmatrix}\n", - "\\frac{\\partial^2 C(\\beta)}{\\partial \\beta_0^2} & \\frac{\\partial^2 C(\\beta)}{\\partial \\beta_0 \\partial \\beta_1} \\\\\n", - "\\frac{\\partial^2 C(\\beta)}{\\partial \\beta_0 \\partial \\beta_1} & \\frac{\\partial^2 C(\\beta)}{\\partial \\beta_1^2} & \\\\\n", - "\\end{bmatrix} = \\frac{2}{n}X^T X+2\\lambda\\boldsymbol{I}.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "a8bb3901", - "metadata": { - "editable": true - }, - "source": [ - "This implies that the Hessian matrix is positive definite, hence the stationary point is a\n", - "minimum.\n", - "Note that the Ridge cost function is convex being a sum of two convex\n", - "functions. Therefore, the stationary point is a global\n", - "minimum of this function." - ] - }, - { - "cell_type": "markdown", - "id": "61ab0a41", - "metadata": { - "editable": true - }, - "source": [ - "## Program example for gradient descent with Ridge Regression" - ] - }, - { - "cell_type": "code", - "execution_count": 16, - "id": "630a15e8", - "metadata": { - "collapsed": false, - "editable": true - }, - "outputs": [], - "source": [ - "from random import random, seed\n", - "import numpy as np\n", - "import matplotlib.pyplot as plt\n", - "from mpl_toolkits.mplot3d import Axes3D\n", - "from matplotlib import cm\n", - "from matplotlib.ticker import LinearLocator, FormatStrFormatter\n", - "import sys\n", - "\n", - "# the number of datapoints\n", - "n = 100\n", - "x = 2*np.random.rand(n,1)\n", - "y = 4+3*x+np.random.randn(n,1)\n", - "\n", - "X = np.c_[np.ones((n,1)), x]\n", - "XT_X = X.T @ X\n", - "\n", - "#Ridge parameter lambda\n", - "lmbda = 0.001\n", - "Id = n*lmbda* np.eye(XT_X.shape[0])\n", - "\n", - "# Hessian matrix\n", - "H = (2.0/n)* XT_X+2*lmbda* np.eye(XT_X.shape[0])\n", - "# Get the eigenvalues\n", - "EigValues, EigVectors = np.linalg.eig(H)\n", - "print(f\"Eigenvalues of Hessian Matrix:{EigValues}\")\n", - "\n", - "\n", - "beta_linreg = np.linalg.inv(XT_X+Id) @ X.T @ y\n", - "print(beta_linreg)\n", - "# Start plain gradient descent\n", - "beta = np.random.randn(2,1)\n", - "\n", - "eta = 1.0/np.max(EigValues)\n", - "Niterations = 100\n", - "\n", - "for iter in range(Niterations):\n", - " gradients = 2.0/n*X.T @ (X @ (beta)-y)+2*lmbda*beta\n", - " beta -= eta*gradients\n", - "\n", - "print(beta)\n", - "ypredict = X @ beta\n", - "ypredict2 = X @ beta_linreg\n", - "plt.plot(x, ypredict, \"r-\")\n", - "plt.plot(x, ypredict2, \"b-\")\n", - "plt.plot(x, y ,'ro')\n", - "plt.axis([0,2.0,0, 15.0])\n", - "plt.xlabel(r'$x$')\n", - "plt.ylabel(r'$y$')\n", - "plt.title(r'Gradient descent example for Ridge')\n", - "plt.show()" - ] - }, - { - "cell_type": "markdown", - "id": "21abaca5", - "metadata": { - "editable": true - }, - "source": [ - "## Using gradient descent methods, limitations\n", - "\n", - "* **Gradient descent (GD) finds local minima of our function**. Since the GD algorithm is deterministic, if it converges, it will converge to a local minimum of our cost/loss/risk function. Because in ML we are often dealing with extremely rugged landscapes with many local minima, this can lead to poor performance.\n", - "\n", - "* **GD is sensitive to initial conditions**. One consequence of the local nature of GD is that initial conditions matter. Depending on where one starts, one will end up at a different local minima. Therefore, it is very important to think about how one initializes the training process. This is true for GD as well as more complicated variants of GD.\n", - "\n", - "* **Gradients are computationally expensive to calculate for large datasets**. In many cases in statistics and ML, the cost/loss/risk function is a sum of terms, with one term for each data point. For example, in linear regression, $E \\propto \\sum_{i=1}^n (y_i - \\mathbf{w}^T\\cdot\\mathbf{x}_i)^2$; for logistic regression, the square error is replaced by the cross entropy. To calculate the gradient we have to sum over *all* $n$ data points. Doing this at every GD step becomes extremely computationally expensive. An ingenious solution to this, is to calculate the gradients using small subsets of the data called \"mini batches\". This has the added benefit of introducing stochasticity into our algorithm.\n", - "\n", - "* **GD is very sensitive to choices of learning rates**. GD is extremely sensitive to the choice of learning rates. If the learning rate is very small, the training process take an extremely long time. For larger learning rates, GD can diverge and give poor results. Furthermore, depending on what the local landscape looks like, we have to modify the learning rates to ensure convergence. Ideally, we would *adaptively* choose the learning rates to match the landscape.\n", - "\n", - "* **GD treats all directions in parameter space uniformly.** Another major drawback of GD is that unlike Newton's method, the learning rate for GD is the same in all directions in parameter space. For this reason, the maximum learning rate is set by the behavior of the steepest direction and this can significantly slow down training. Ideally, we would like to take large steps in flat directions and small steps in steep directions. Since we are exploring rugged landscapes where curvatures change, this requires us to keep track of not only the gradient but second derivatives. The ideal scenario would be to calculate the Hessian but this proves to be too computationally expensive. \n", - "\n", - "* GD can take exponential time to escape saddle points, even with random initialization. As we mentioned, GD is extremely sensitive to initial condition since it determines the particular local minimum GD would eventually reach. However, even with a good initialization scheme, through the introduction of randomness, GD can still take exponential time to escape saddle points." - ] - }, - { - "cell_type": "markdown", - "id": "5753b51d", - "metadata": { - "editable": true - }, - "source": [ - "## Challenge yourself the coming weekend\n", - "\n", - "Write a code which implements gradient descent for a logistic regression example." - ] - } - ], - "metadata": {}, - "nbformat": 4, - "nbformat_minor": 5 -} diff --git a/doc/LectureNotes/week39.ipynb b/doc/LectureNotes/week39.ipynb deleted file mode 100644 index ea2c34ebe..000000000 --- a/doc/LectureNotes/week39.ipynb +++ /dev/null @@ -1,4889 +0,0 @@ -{ - "cells": [ - { - "cell_type": "markdown", - "id": "428bf751", - "metadata": { - "editable": true - }, - "source": [ - "\n", - "" - ] - }, - { - "cell_type": "markdown", - "id": "1a0a75ed", - "metadata": { - "editable": true - }, - "source": [ - "# Week 39: Optimization and Gradient Methods\n", - "**Morten Hjorth-Jensen**, Department of Physics, University of Oslo and Department of Physics and Astronomy and Facility for Rare Isotope Beams, Michigan State University\n", - "\n", - "Date: **Week 39**" - ] - }, - { - "cell_type": "markdown", - "id": "333f3063", - "metadata": { - "editable": true - }, - "source": [ - "## Plan for week 39\n", - "\n", - "**Material for the active learning sessions on Tuesday and Wednesday.**\n", - "\n", - " * Discussions on how to structure your report for the first project\n", - "\n", - " * Exercise for week 39 on how to write the abstract and the introduction of the report and how to include references. \n", - "\n", - " * Work on project 1, in particular resampling methods like cross-validation and bootstrap. **For more discussions of project 1, chapter 5 of Goodfellow et al is a good read, in particular sections 5.1-5.5 and 5.7-5.11**.\n", - "\n", - " * [Video on how to write scientific reports recorded during one of the lab sessions](https://youtu.be/tVW1ZDmZnwM)\n", - "\n", - "These sections summarize neatly what we have done till now and point to what is coming with respect to deep learning. \n", - " * A general guideline can be found at .\n", - "\n", - " \n", - "\n", - "**Material for the lecture on Thursday September 28.**\n", - "\n", - " * Repetition of Logistic regression equations and classification problems and discussion of Gradient methods. Examples on how to implement Logistic Regression and discussion of stochastic gradient descent \n", - "\n", - " * Stochastic Gradient descent with examples and automatic differentiation\n", - "\n", - " * [Video of lecture](https://youtu.be/bFRVuIJroHs)\n", - "\n", - " * Whiteboard notes TBA at \n", - "\n", - " * Readings and Videos:\n", - "\n", - " * These lecture notes\n", - "\n", - " * For a good discussion on gradient methods, we would like to recommend Goodfellow et al section 4.3-4.5 and sections 8.3-8.6. We will come back to the latter chapter in our discussion of Neural networks as well. \n", - "\n", - " * [Video on gradient descent](https://www.youtube.com/watch?v=sDv4f4s2SB8)\n", - "\n", - " * [Video on stochastic gradient descent](https://www.youtube.com/watch?v=vMh0zPT0tLI)\n", - "\n", - "" - ] - }, - { - "cell_type": "markdown", - "id": "3ee03ecd", - "metadata": { - "editable": true - }, - "source": [ - "## Optimization, the central part of any Machine Learning algortithm\n", - "\n", - "The first few slides here are a repetition from last week. \n", - "\n", - "Almost every problem in machine learning and data science starts with\n", - "a dataset $X$, a model $g(\\beta)$, which is a function of the\n", - "parameters $\\beta$ and a cost function $C(X, g(\\beta))$ that allows\n", - "us to judge how well the model $g(\\beta)$ explains the observations\n", - "$X$. The model is fit by finding the values of $\\beta$ that minimize\n", - "the cost function. Ideally we would be able to solve for $\\beta$\n", - "analytically, however this is not possible in general and we must use\n", - "some approximative/numerical method to compute the minimum." - ] - }, - { - "cell_type": "markdown", - "id": "148ec577", - "metadata": { - "editable": true - }, - "source": [ - "## Revisiting our Logistic Regression case\n", - "\n", - "In our discussion on Logistic Regression we studied the \n", - "case of\n", - "two classes, with $y_i$ either\n", - "$0$ or $1$. Furthermore we assumed also that we have only two\n", - "parameters $\\beta$ in our fitting, that is we\n", - "defined probabilities" - ] - }, - { - "cell_type": "markdown", - "id": "e6e5e661", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\begin{align*}\n", - "p(y_i=1|x_i,\\boldsymbol{\\beta}) &= \\frac{\\exp{(\\beta_0+\\beta_1x_i)}}{1+\\exp{(\\beta_0+\\beta_1x_i)}},\\nonumber\\\\\n", - "p(y_i=0|x_i,\\boldsymbol{\\beta}) &= 1 - p(y_i=1|x_i,\\boldsymbol{\\beta}),\n", - "\\end{align*}\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "4a81fe9d", - "metadata": { - "editable": true - }, - "source": [ - "where $\\boldsymbol{\\beta}$ are the weights we wish to extract from data, in our case $\\beta_0$ and $\\beta_1$." - ] - }, - { - "cell_type": "markdown", - "id": "ac94af95", - "metadata": { - "editable": true - }, - "source": [ - "## The equations to solve\n", - "\n", - "Our compact equations used a definition of a vector $\\boldsymbol{y}$ with $n$\n", - "elements $y_i$, an $n\\times p$ matrix $\\boldsymbol{X}$ which contains the\n", - "$x_i$ values and a vector $\\boldsymbol{p}$ of fitted probabilities\n", - "$p(y_i\\vert x_i,\\boldsymbol{\\beta})$. We rewrote in a more compact form\n", - "the first derivative of the cost function as" - ] - }, - { - "cell_type": "markdown", - "id": "5bfc3f18", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\frac{\\partial \\mathcal{C}(\\boldsymbol{\\beta})}{\\partial \\boldsymbol{\\beta}} = -\\boldsymbol{X}^T\\left(\\boldsymbol{y}-\\boldsymbol{p}\\right).\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "2437c71a", - "metadata": { - "editable": true - }, - "source": [ - "If we in addition define a diagonal matrix $\\boldsymbol{W}$ with elements \n", - "$p(y_i\\vert x_i,\\boldsymbol{\\beta})(1-p(y_i\\vert x_i,\\boldsymbol{\\beta})$, we can obtain a compact expression of the second derivative as" - ] - }, - { - "cell_type": "markdown", - "id": "a5d4163c", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\frac{\\partial^2 \\mathcal{C}(\\boldsymbol{\\beta})}{\\partial \\boldsymbol{\\beta}\\partial \\boldsymbol{\\beta}^T} = \\boldsymbol{X}^T\\boldsymbol{W}\\boldsymbol{X}.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "cca433f5", - "metadata": { - "editable": true - }, - "source": [ - "This defines what is called the Hessian matrix." - ] - }, - { - "cell_type": "markdown", - "id": "c9ba0136", - "metadata": { - "editable": true - }, - "source": [ - "## Solving using Newton-Raphson's method\n", - "\n", - "If we can set up these equations, Newton-Raphson's iterative method is normally the method of choice. It requires however that we can compute in an efficient way the matrices that define the first and second derivatives. \n", - "\n", - "Our iterative scheme is then given by" - ] - }, - { - "cell_type": "markdown", - "id": "3a6a4c55", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\boldsymbol{\\beta}^{\\mathrm{new}} = \\boldsymbol{\\beta}^{\\mathrm{old}}-\\left(\\frac{\\partial^2 \\mathcal{C}(\\boldsymbol{\\beta})}{\\partial \\boldsymbol{\\beta}\\partial \\boldsymbol{\\beta}^T}\\right)^{-1}_{\\boldsymbol{\\beta}^{\\mathrm{old}}}\\times \\left(\\frac{\\partial \\mathcal{C}(\\boldsymbol{\\beta})}{\\partial \\boldsymbol{\\beta}}\\right)_{\\boldsymbol{\\beta}^{\\mathrm{old}}},\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "f71ca135", - "metadata": { - "editable": true - }, - "source": [ - "or in matrix form as" - ] - }, - { - "cell_type": "markdown", - "id": "942a71da", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\boldsymbol{\\beta}^{\\mathrm{new}} = \\boldsymbol{\\beta}^{\\mathrm{old}}-\\left(\\boldsymbol{X}^T\\boldsymbol{W}\\boldsymbol{X} \\right)^{-1}\\times \\left(-\\boldsymbol{X}^T(\\boldsymbol{y}-\\boldsymbol{p}) \\right)_{\\boldsymbol{\\beta}^{\\mathrm{old}}}.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "3d3ddaff", - "metadata": { - "editable": true - }, - "source": [ - "The right-hand side is computed with the old values of $\\beta$. \n", - "\n", - "If we can compute these matrices, in particular the Hessian, the above is often the easiest method to implement." - ] - }, - { - "cell_type": "markdown", - "id": "3dfb626a", - "metadata": { - "editable": true - }, - "source": [ - "## Brief reminder on Newton-Raphson's method\n", - "\n", - "Let us quickly remind ourselves how we derive the above method.\n", - "\n", - "Perhaps the most celebrated of all one-dimensional root-finding\n", - "routines is Newton's method, also called the Newton-Raphson\n", - "method. This method requires the evaluation of both the\n", - "function $f$ and its derivative $f'$ at arbitrary points. \n", - "If you can only calculate the derivative\n", - "numerically and/or your function is not of the smooth type, we\n", - "normally discourage the use of this method." - ] - }, - { - "cell_type": "markdown", - "id": "7a77c9ce", - "metadata": { - "editable": true - }, - "source": [ - "## The equations\n", - "\n", - "The Newton-Raphson formula consists geometrically of extending the\n", - "tangent line at a current point until it crosses zero, then setting\n", - "the next guess to the abscissa of that zero-crossing. The mathematics\n", - "behind this method is rather simple. Employing a Taylor expansion for\n", - "$x$ sufficiently close to the solution $s$, we have" - ] - }, - { - "cell_type": "markdown", - "id": "d094140b", - "metadata": { - "editable": true - }, - "source": [ - "\n", - "
\n", - "\n", - "$$\n", - "f(s)=0=f(x)+(s-x)f'(x)+\\frac{(s-x)^2}{2}f''(x) +\\dots.\n", - " \\label{eq:taylornr} \\tag{1}\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "9c04f928", - "metadata": { - "editable": true - }, - "source": [ - "For small enough values of the function and for well-behaved\n", - "functions, the terms beyond linear are unimportant, hence we obtain" - ] - }, - { - "cell_type": "markdown", - "id": "d29b9b63", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "f(x)+(s-x)f'(x)\\approx 0,\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "d3e508b5", - "metadata": { - "editable": true - }, - "source": [ - "yielding" - ] - }, - { - "cell_type": "markdown", - "id": "fd5bbc31", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "s\\approx x-\\frac{f(x)}{f'(x)}.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "7e255afd", - "metadata": { - "editable": true - }, - "source": [ - "Having in mind an iterative procedure, it is natural to start iterating with" - ] - }, - { - "cell_type": "markdown", - "id": "62d43c1c", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "x_{n+1}=x_n-\\frac{f(x_n)}{f'(x_n)}.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "0b23438c", - "metadata": { - "editable": true - }, - "source": [ - "## Simple geometric interpretation\n", - "\n", - "The above is Newton-Raphson's method. It has a simple geometric\n", - "interpretation, namely $x_{n+1}$ is the point where the tangent from\n", - "$(x_n,f(x_n))$ crosses the $x$-axis. Close to the solution,\n", - "Newton-Raphson converges fast to the desired result. However, if we\n", - "are far from a root, where the higher-order terms in the series are\n", - "important, the Newton-Raphson formula can give grossly inaccurate\n", - "results. For instance, the initial guess for the root might be so far\n", - "from the true root as to let the search interval include a local\n", - "maximum or minimum of the function. If an iteration places a trial\n", - "guess near such a local extremum, so that the first derivative nearly\n", - "vanishes, then Newton-Raphson may fail totally" - ] - }, - { - "cell_type": "markdown", - "id": "d7587ee4", - "metadata": { - "editable": true - }, - "source": [ - "## Extending to more than one variable\n", - "\n", - "Newton's method can be generalized to systems of several non-linear equations\n", - "and variables. Consider the case with two equations" - ] - }, - { - "cell_type": "markdown", - "id": "3736c3ae", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\begin{array}{cc} f_1(x_1,x_2) &=0\\\\\n", - " f_2(x_1,x_2) &=0,\\end{array}\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "e9cf6fb6", - "metadata": { - "editable": true - }, - "source": [ - "which we Taylor expand to obtain" - ] - }, - { - "cell_type": "markdown", - "id": "9c8e6fc9", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\begin{array}{cc} 0=f_1(x_1+h_1,x_2+h_2)=&f_1(x_1,x_2)+h_1\n", - " \\partial f_1/\\partial x_1+h_2\n", - " \\partial f_1/\\partial x_2+\\dots\\\\\n", - " 0=f_2(x_1+h_1,x_2+h_2)=&f_2(x_1,x_2)+h_1\n", - " \\partial f_2/\\partial x_1+h_2\n", - " \\partial f_2/\\partial x_2+\\dots\n", - " \\end{array}.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "2059ae9d", - "metadata": { - "editable": true - }, - "source": [ - "Defining the Jacobian matrix ${\\bf \\boldsymbol{J}}$ we have" - ] - }, - { - "cell_type": "markdown", - "id": "64c640e4", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "{\\bf \\boldsymbol{J}}=\\left( \\begin{array}{cc}\n", - " \\partial f_1/\\partial x_1 & \\partial f_1/\\partial x_2 \\\\\n", - " \\partial f_2/\\partial x_1 &\\partial f_2/\\partial x_2\n", - " \\end{array} \\right),\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "647d6bd2", - "metadata": { - "editable": true - }, - "source": [ - "we can rephrase Newton's method as" - ] - }, - { - "cell_type": "markdown", - "id": "24ff572b", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\left(\\begin{array}{c} x_1^{n+1} \\\\ x_2^{n+1} \\end{array} \\right)=\n", - "\\left(\\begin{array}{c} x_1^{n} \\\\ x_2^{n} \\end{array} \\right)+\n", - "\\left(\\begin{array}{c} h_1^{n} \\\\ h_2^{n} \\end{array} \\right),\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "521c56f5", - "metadata": { - "editable": true - }, - "source": [ - "where we have defined" - ] - }, - { - "cell_type": "markdown", - "id": "4508944b", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\left(\\begin{array}{c} h_1^{n} \\\\ h_2^{n} \\end{array} \\right)=\n", - " -{\\bf \\boldsymbol{J}}^{-1}\n", - " \\left(\\begin{array}{c} f_1(x_1^{n},x_2^{n}) \\\\ f_2(x_1^{n},x_2^{n}) \\end{array} \\right).\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "69b72003", - "metadata": { - "editable": true - }, - "source": [ - "We need thus to compute the inverse of the Jacobian matrix and it\n", - "is to understand that difficulties may\n", - "arise in case ${\\bf \\boldsymbol{J}}$ is nearly singular.\n", - "\n", - "It is rather straightforward to extend the above scheme to systems of\n", - "more than two non-linear equations. In our case, the Jacobian matrix is given by the Hessian that represents the second derivative of cost function." - ] - }, - { - "cell_type": "markdown", - "id": "dd11ba71", - "metadata": { - "editable": true - }, - "source": [ - "## Steepest descent\n", - "\n", - "The basic idea of gradient descent is\n", - "that a function $F(\\mathbf{x})$, \n", - "$\\mathbf{x} \\equiv (x_1,\\cdots,x_n)$, decreases fastest if one goes from $\\bf {x}$ in the\n", - "direction of the negative gradient $-\\nabla F(\\mathbf{x})$.\n", - "\n", - "It can be shown that if" - ] - }, - { - "cell_type": "markdown", - "id": "ccb5e1a6", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\mathbf{x}_{k+1} = \\mathbf{x}_k - \\gamma_k \\nabla F(\\mathbf{x}_k),\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "6952b928", - "metadata": { - "editable": true - }, - "source": [ - "with $\\gamma_k > 0$.\n", - "\n", - "For $\\gamma_k$ small enough, then $F(\\mathbf{x}_{k+1}) \\leq\n", - "F(\\mathbf{x}_k)$. This means that for a sufficiently small $\\gamma_k$\n", - "we are always moving towards smaller function values, i.e a minimum." - ] - }, - { - "cell_type": "markdown", - "id": "f0c5476d", - "metadata": { - "editable": true - }, - "source": [ - "## More on Steepest descent\n", - "\n", - "The previous observation is the basis of the method of steepest\n", - "descent, which is also referred to as just gradient descent (GD). One\n", - "starts with an initial guess $\\mathbf{x}_0$ for a minimum of $F$ and\n", - "computes new approximations according to" - ] - }, - { - "cell_type": "markdown", - "id": "4aeb7465", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\mathbf{x}_{k+1} = \\mathbf{x}_k - \\gamma_k \\nabla F(\\mathbf{x}_k), \\ \\ k \\geq 0.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "337ccfd3", - "metadata": { - "editable": true - }, - "source": [ - "The parameter $\\gamma_k$ is often referred to as the step length or\n", - "the learning rate within the context of Machine Learning." - ] - }, - { - "cell_type": "markdown", - "id": "7540286d", - "metadata": { - "editable": true - }, - "source": [ - "## The ideal\n", - "\n", - "Ideally the sequence $\\{\\mathbf{x}_k \\}_{k=0}$ converges to a global\n", - "minimum of the function $F$. In general we do not know if we are in a\n", - "global or local minimum. In the special case when $F$ is a convex\n", - "function, all local minima are also global minima, so in this case\n", - "gradient descent can converge to the global solution. The advantage of\n", - "this scheme is that it is conceptually simple and straightforward to\n", - "implement. However the method in this form has some severe\n", - "limitations:\n", - "\n", - "In machine learing we are often faced with non-convex high dimensional\n", - "cost functions with many local minima. Since GD is deterministic we\n", - "will get stuck in a local minimum, if the method converges, unless we\n", - "have a very good intial guess. This also implies that the scheme is\n", - "sensitive to the chosen initial condition.\n", - "\n", - "Note that the gradient is a function of $\\mathbf{x} =\n", - "(x_1,\\cdots,x_n)$ which makes it expensive to compute numerically." - ] - }, - { - "cell_type": "markdown", - "id": "b7ce5820", - "metadata": { - "editable": true - }, - "source": [ - "## The sensitiveness of the gradient descent\n", - "\n", - "The gradient descent method \n", - "is sensitive to the choice of learning rate $\\gamma_k$. This is due\n", - "to the fact that we are only guaranteed that $F(\\mathbf{x}_{k+1}) \\leq\n", - "F(\\mathbf{x}_k)$ for sufficiently small $\\gamma_k$. The problem is to\n", - "determine an optimal learning rate. If the learning rate is chosen too\n", - "small the method will take a long time to converge and if it is too\n", - "large we can experience erratic behavior.\n", - "\n", - "Many of these shortcomings can be alleviated by introducing\n", - "randomness. One such method is that of Stochastic Gradient Descent\n", - "(SGD), see below." - ] - }, - { - "cell_type": "markdown", - "id": "0a557da3", - "metadata": { - "editable": true - }, - "source": [ - "## Convex functions\n", - "\n", - "Ideally we want our cost/loss function to be convex(concave).\n", - "\n", - "First we give the definition of a convex set: A set $C$ in\n", - "$\\mathbb{R}^n$ is said to be convex if, for all $x$ and $y$ in $C$ and\n", - "all $t \\in (0,1)$ , the point $(1 − t)x + ty$ also belongs to\n", - "C. Geometrically this means that every point on the line segment\n", - "connecting $x$ and $y$ is in $C$ as discussed below.\n", - "\n", - "The convex subsets of $\\mathbb{R}$ are the intervals of\n", - "$\\mathbb{R}$. Examples of convex sets of $\\mathbb{R}^2$ are the\n", - "regular polygons (triangles, rectangles, pentagons, etc...)." - ] - }, - { - "cell_type": "markdown", - "id": "bdbf8a07", - "metadata": { - "editable": true - }, - "source": [ - "## Convex function\n", - "\n", - "**Convex function**: Let $X \\subset \\mathbb{R}^n$ be a convex\n", - "set. Assume that the function $f: X \\rightarrow \\mathbb{R}$ is\n", - "continuous, then $f$ is said to be convex if $f(tx_1 + (1-t)x_2) \\leq tf(x_1) + (1-t)f(x_2)$\n", - "for all $x_1, x_2 \\in X$ and for all $t \\in [0,1]$.\n", - "If $\\leq$ is replaced with a strict inequaltiy in the\n", - "definition, we demand $x_1 \\neq x_2$ and $t\\in(0,1)$ then $f$ is said\n", - "to be strictly convex. For a single variable function, convexity means\n", - "that if you draw a straight line connecting $f(x_1)$ and $f(x_2)$, the\n", - "value of the function on the interval $[x_1,x_2]$ is always below the\n", - "line as illustrated below." - ] - }, - { - "cell_type": "markdown", - "id": "e02d1dac", - "metadata": { - "editable": true - }, - "source": [ - "## Conditions on convex functions\n", - "\n", - "In the following we state first and second-order conditions which\n", - "ensures convexity of a function $f$. We write $D_f$ to denote the\n", - "domain of $f$, i.e the subset of $R^n$ where $f$ is defined. For more\n", - "details and proofs we refer to: [S. Boyd and L. Vandenberghe. Convex Optimization. Cambridge University Press](http://stanford.edu/boyd/cvxbook/).\n", - "\n", - "**First order condition.**\n", - "\n", - "Suppose $f$ is differentiable (i.e $\\nabla f(x)$ is well defined for\n", - "all $x$ in the domain of $f$). Then $f$ is convex if and only if $D_f$\n", - "is a convex set and $f(y) \\geq f(x) + \\nabla f(x)^T (y-x)$ holds\n", - "for all $x,y \\in D_f$.\n", - "\n", - "This condition means that for a convex function\n", - "the first order Taylor expansion (right hand side above) at any point\n", - "a global under estimator of the function. To convince yourself you can\n", - "make a drawing of $f(x) = x^2+1$ and draw the tangent line to $f(x)$ and\n", - "note that it is always below the graph.\n", - "\n", - "**Second order condition.**\n", - "\n", - "Assume that $f$ is twice\n", - "differentiable, i.e the Hessian matrix exists at each point in\n", - "$D_f$. Then $f$ is convex if and only if $D_f$ is a convex set and its\n", - "Hessian is positive semi-definite for all $x\\in D_f$. For a\n", - "single-variable function this reduces to $f''(x) \\geq 0$. Geometrically this means that $f$ has nonnegative curvature\n", - "everywhere.\n", - "\n", - "This condition is particularly useful since it gives us an procedure for determining if the function under consideration is convex, apart from using the definition." - ] - }, - { - "cell_type": "markdown", - "id": "d9a72971", - "metadata": { - "editable": true - }, - "source": [ - "## More on convex functions\n", - "\n", - "The next result is of great importance to us and the reason why we are\n", - "going on about convex functions. In machine learning we frequently\n", - "have to minimize a loss/cost function in order to find the best\n", - "parameters for the model we are considering. \n", - "\n", - "Ideally we want the\n", - "global minimum (for high-dimensional models it is hard to know\n", - "if we have local or global minimum). However, if the cost/loss function\n", - "is convex the following result provides invaluable information:\n", - "\n", - "**Any minimum is global for convex functions.**\n", - "\n", - "Consider the problem of finding $x \\in \\mathbb{R}^n$ such that $f(x)$\n", - "is minimal, where $f$ is convex and differentiable. Then, any point\n", - "$x^*$ that satisfies $\\nabla f(x^*) = 0$ is a global minimum.\n", - "\n", - "This result means that if we know that the cost/loss function is convex and we are able to find a minimum, we are guaranteed that it is a global minimum." - ] - }, - { - "cell_type": "markdown", - "id": "c3e744c2", - "metadata": { - "editable": true - }, - "source": [ - "## Some simple problems\n", - "\n", - "1. Show that $f(x)=x^2$ is convex for $x \\in \\mathbb{R}$ using the definition of convexity. Hint: If you re-write the definition, $f$ is convex if the following holds for all $x,y \\in D_f$ and any $\\lambda \\in [0,1]$ $\\lambda f(x)+(1-\\lambda)f(y)-f(\\lambda x + (1-\\lambda) y ) \\geq 0$.\n", - "\n", - "2. Using the second order condition show that the following functions are convex on the specified domain.\n", - "\n", - " * $f(x) = e^x$ is convex for $x \\in \\mathbb{R}$.\n", - "\n", - " * $g(x) = -\\ln(x)$ is convex for $x \\in (0,\\infty)$.\n", - "\n", - "3. Let $f(x) = x^2$ and $g(x) = e^x$. Show that $f(g(x))$ and $g(f(x))$ is convex for $x \\in \\mathbb{R}$. Also show that if $f(x)$ is any convex function than $h(x) = e^{f(x)}$ is convex.\n", - "\n", - "4. A norm is any function that satisfy the following properties\n", - "\n", - " * $f(\\alpha x) = |\\alpha| f(x)$ for all $\\alpha \\in \\mathbb{R}$.\n", - "\n", - " * $f(x+y) \\leq f(x) + f(y)$\n", - "\n", - " * $f(x) \\leq 0$ for all $x \\in \\mathbb{R}^n$ with equality if and only if $x = 0$\n", - "\n", - "Using the definition of convexity, try to show that a function satisfying the properties above is convex (the third condition is not needed to show this)." - ] - }, - { - "cell_type": "markdown", - "id": "2732cf8b", - "metadata": { - "editable": true - }, - "source": [ - "## Standard steepest descent\n", - "\n", - "Before we proceed, we would like to discuss the approach called the\n", - "**standard Steepest descent** (different from the above steepest descent discussion), which again leads to us having to be able\n", - "to compute a matrix. It belongs to the class of Conjugate Gradient methods (CG).\n", - "\n", - "[The success of the CG method](https://www.cs.cmu.edu/~quake-papers/painless-conjugate-gradient.pdf)\n", - "for finding solutions of non-linear problems is based on the theory\n", - "of conjugate gradients for linear systems of equations. It belongs to\n", - "the class of iterative methods for solving problems from linear\n", - "algebra of the type" - ] - }, - { - "cell_type": "markdown", - "id": "1b14ba6d", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\boldsymbol{A}\\boldsymbol{x} = \\boldsymbol{b}.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "5f271cd8", - "metadata": { - "editable": true - }, - "source": [ - "In the iterative process we end up with a problem like" - ] - }, - { - "cell_type": "markdown", - "id": "eb0ce7c8", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\boldsymbol{r}= \\boldsymbol{b}-\\boldsymbol{A}\\boldsymbol{x},\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "3482f635", - "metadata": { - "editable": true - }, - "source": [ - "where $\\boldsymbol{r}$ is the so-called residual or error in the iterative process.\n", - "\n", - "When we have found the exact solution, $\\boldsymbol{r}=0$." - ] - }, - { - "cell_type": "markdown", - "id": "0c88f8d2", - "metadata": { - "editable": true - }, - "source": [ - "## Gradient method\n", - "\n", - "The residual is zero when we reach the minimum of the quadratic equation" - ] - }, - { - "cell_type": "markdown", - "id": "fe152e73", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "P(\\boldsymbol{x})=\\frac{1}{2}\\boldsymbol{x}^T\\boldsymbol{A}\\boldsymbol{x} - \\boldsymbol{x}^T\\boldsymbol{b},\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "740c5860", - "metadata": { - "editable": true - }, - "source": [ - "with the constraint that the matrix $\\boldsymbol{A}$ is positive definite and\n", - "symmetric. This defines also the Hessian and we want it to be positive definite." - ] - }, - { - "cell_type": "markdown", - "id": "477da242", - "metadata": { - "editable": true - }, - "source": [ - "## Steepest descent method\n", - "\n", - "We denote the initial guess for $\\boldsymbol{x}$ as $\\boldsymbol{x}_0$. \n", - "We can assume without loss of generality that" - ] - }, - { - "cell_type": "markdown", - "id": "7e2169e6", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\boldsymbol{x}_0=0,\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "e513c1c5", - "metadata": { - "editable": true - }, - "source": [ - "or consider the system" - ] - }, - { - "cell_type": "markdown", - "id": "a4a4f67c", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\boldsymbol{A}\\boldsymbol{z} = \\boldsymbol{b}-\\boldsymbol{A}\\boldsymbol{x}_0,\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "96138e83", - "metadata": { - "editable": true - }, - "source": [ - "instead." - ] - }, - { - "cell_type": "markdown", - "id": "f843d9f8", - "metadata": { - "editable": true - }, - "source": [ - "## Steepest descent method\n", - "One can show that the solution $\\boldsymbol{x}$ is also the unique minimizer of the quadratic form" - ] - }, - { - "cell_type": "markdown", - "id": "5702234f", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "f(\\boldsymbol{x}) = \\frac{1}{2}\\boldsymbol{x}^T\\boldsymbol{A}\\boldsymbol{x} - \\boldsymbol{x}^T \\boldsymbol{x} , \\quad \\boldsymbol{x}\\in\\mathbf{R}^n.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "682a415f", - "metadata": { - "editable": true - }, - "source": [ - "This suggests taking the first basis vector $\\boldsymbol{r}_1$ (see below for definition) \n", - "to be the gradient of $f$ at $\\boldsymbol{x}=\\boldsymbol{x}_0$, \n", - "which equals" - ] - }, - { - "cell_type": "markdown", - "id": "302ac54a", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\boldsymbol{A}\\boldsymbol{x}_0-\\boldsymbol{b},\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "dd2cbeb1", - "metadata": { - "editable": true - }, - "source": [ - "and \n", - "$\\boldsymbol{x}_0=0$ it is equal $-\\boldsymbol{b}$." - ] - }, - { - "cell_type": "markdown", - "id": "f280370e", - "metadata": { - "editable": true - }, - "source": [ - "## Final expressions\n", - "We can compute the residual iteratively as" - ] - }, - { - "cell_type": "markdown", - "id": "9702a162", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\boldsymbol{r}_{k+1}=\\boldsymbol{b}-\\boldsymbol{A}\\boldsymbol{x}_{k+1},\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "3a1de3f0", - "metadata": { - "editable": true - }, - "source": [ - "which equals" - ] - }, - { - "cell_type": "markdown", - "id": "4fa494ea", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\boldsymbol{b}-\\boldsymbol{A}(\\boldsymbol{x}_k+\\alpha_k\\boldsymbol{r}_k),\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "a4f12308", - "metadata": { - "editable": true - }, - "source": [ - "or" - ] - }, - { - "cell_type": "markdown", - "id": "df770c35", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "(\\boldsymbol{b}-\\boldsymbol{A}\\boldsymbol{x}_k)-\\alpha_k\\boldsymbol{A}\\boldsymbol{r}_k,\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "b1a30174", - "metadata": { - "editable": true - }, - "source": [ - "which gives" - ] - }, - { - "cell_type": "markdown", - "id": "6f816a49", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\alpha_k = \\frac{\\boldsymbol{r}_k^T\\boldsymbol{r}_k}{\\boldsymbol{r}_k^T\\boldsymbol{A}\\boldsymbol{r}_k}\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "4e5cd41c", - "metadata": { - "editable": true - }, - "source": [ - "leading to the iterative scheme" - ] - }, - { - "cell_type": "markdown", - "id": "91f972cb", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\boldsymbol{x}_{k+1}=\\boldsymbol{x}_k+\\alpha_k\\boldsymbol{r}_{k},\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "97064af3", - "metadata": { - "editable": true - }, - "source": [ - "## Steepest descent example" - ] - }, - { - "cell_type": "code", - "execution_count": 1, - "id": "5af74f1d", - "metadata": { - "collapsed": false, - "editable": true - }, - "outputs": [], - "source": [ - "%matplotlib inline\n", - "\n", - "import numpy as np\n", - "import numpy.linalg as la\n", - "\n", - "import scipy.optimize as sopt\n", - "\n", - "import matplotlib.pyplot as pt\n", - "from mpl_toolkits.mplot3d import axes3d\n", - "\n", - "def f(x):\n", - " return x[0]**2 + 3.0*x[1]**2\n", - "\n", - "def df(x):\n", - " return np.array([2*x[0], 6*x[1]])\n", - "\n", - "fig = pt.figure()\n", - "ax = fig.gca(projection=\"3d\")\n", - "\n", - "xmesh, ymesh = np.mgrid[-3:3:50j,-3:3:50j]\n", - "fmesh = f(np.array([xmesh, ymesh]))\n", - "ax.plot_surface(xmesh, ymesh, fmesh)" - ] - }, - { - "cell_type": "markdown", - "id": "db2d4ba3", - "metadata": { - "editable": true - }, - "source": [ - "And then as countor plot" - ] - }, - { - "cell_type": "code", - "execution_count": 2, - "id": "dbba72eb", - "metadata": { - "collapsed": false, - "editable": true - }, - "outputs": [], - "source": [ - "pt.axis(\"equal\")\n", - "pt.contour(xmesh, ymesh, fmesh)\n", - "guesses = [np.array([2, 2./5])]" - ] - }, - { - "cell_type": "markdown", - "id": "8290c8f1", - "metadata": { - "editable": true - }, - "source": [ - "Find guesses" - ] - }, - { - "cell_type": "code", - "execution_count": 3, - "id": "ce55e78a", - "metadata": { - "collapsed": false, - "editable": true - }, - "outputs": [], - "source": [ - "x = guesses[-1]\n", - "s = -df(x)" - ] - }, - { - "cell_type": "markdown", - "id": "0fa3681b", - "metadata": { - "editable": true - }, - "source": [ - "Run it!" - ] - }, - { - "cell_type": "code", - "execution_count": 4, - "id": "a5aee074", - "metadata": { - "collapsed": false, - "editable": true - }, - "outputs": [], - "source": [ - "def f1d(alpha):\n", - " return f(x + alpha*s)\n", - "\n", - "alpha_opt = sopt.golden(f1d)\n", - "next_guess = x + alpha_opt * s\n", - "guesses.append(next_guess)\n", - "print(next_guess)" - ] - }, - { - "cell_type": "markdown", - "id": "8f8ed4d2", - "metadata": { - "editable": true - }, - "source": [ - "What happened?" - ] - }, - { - "cell_type": "code", - "execution_count": 5, - "id": "30855606", - "metadata": { - "collapsed": false, - "editable": true - }, - "outputs": [], - "source": [ - "pt.axis(\"equal\")\n", - "pt.contour(xmesh, ymesh, fmesh, 50)\n", - "it_array = np.array(guesses)\n", - "pt.plot(it_array.T[0], it_array.T[1], \"x-\")" - ] - }, - { - "cell_type": "markdown", - "id": "fcd5a0c8", - "metadata": { - "editable": true - }, - "source": [ - "Note that we did only one iteration here. We can easily add more using our previous guesses." - ] - }, - { - "cell_type": "markdown", - "id": "acdc3658", - "metadata": { - "editable": true - }, - "source": [ - "## Conjugate gradient method\n", - "In the CG method we define so-called conjugate directions and two vectors \n", - "$\\boldsymbol{s}$ and $\\boldsymbol{t}$\n", - "are said to be\n", - "conjugate if" - ] - }, - { - "cell_type": "markdown", - "id": "7e07632f", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\boldsymbol{s}^T\\boldsymbol{A}\\boldsymbol{t}= 0.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "356d5fe1", - "metadata": { - "editable": true - }, - "source": [ - "The philosophy of the CG method is to perform searches in various conjugate directions\n", - "of our vectors $\\boldsymbol{x}_i$ obeying the above criterion, namely" - ] - }, - { - "cell_type": "markdown", - "id": "2033af61", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\boldsymbol{x}_i^T\\boldsymbol{A}\\boldsymbol{x}_j= 0.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "0a85c783", - "metadata": { - "editable": true - }, - "source": [ - "Two vectors are conjugate if they are orthogonal with respect to \n", - "this inner product. Being conjugate is a symmetric relation: if $\\boldsymbol{s}$ is conjugate to $\\boldsymbol{t}$, then $\\boldsymbol{t}$ is conjugate to $\\boldsymbol{s}$." - ] - }, - { - "cell_type": "markdown", - "id": "6c19d77d", - "metadata": { - "editable": true - }, - "source": [ - "## Conjugate gradient method\n", - "An example is given by the eigenvectors of the matrix" - ] - }, - { - "cell_type": "markdown", - "id": "f42364fb", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\boldsymbol{v}_i^T\\boldsymbol{A}\\boldsymbol{v}_j= \\lambda\\boldsymbol{v}_i^T\\boldsymbol{v}_j,\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "c841e7d3", - "metadata": { - "editable": true - }, - "source": [ - "which is zero unless $i=j$." - ] - }, - { - "cell_type": "markdown", - "id": "297492ba", - "metadata": { - "editable": true - }, - "source": [ - "## Conjugate gradient method\n", - "Assume now that we have a symmetric positive-definite matrix $\\boldsymbol{A}$ of size\n", - "$n\\times n$. At each iteration $i+1$ we obtain the conjugate direction of a vector" - ] - }, - { - "cell_type": "markdown", - "id": "4963a2d8", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\boldsymbol{x}_{i+1}=\\boldsymbol{x}_{i}+\\alpha_i\\boldsymbol{p}_{i}.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "4a39d88b", - "metadata": { - "editable": true - }, - "source": [ - "We assume that $\\boldsymbol{p}_{i}$ is a sequence of $n$ mutually conjugate directions. \n", - "Then the $\\boldsymbol{p}_{i}$ form a basis of $R^n$ and we can expand the solution \n", - "$ \\boldsymbol{A}\\boldsymbol{x} = \\boldsymbol{b}$ in this basis, namely" - ] - }, - { - "cell_type": "markdown", - "id": "83a86148", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\boldsymbol{x} = \\sum^{n}_{i=1} \\alpha_i \\boldsymbol{p}_i.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "c691f06b", - "metadata": { - "editable": true - }, - "source": [ - "## Conjugate gradient method\n", - "The coefficients are given by" - ] - }, - { - "cell_type": "markdown", - "id": "d4df90e8", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\mathbf{A}\\mathbf{x} = \\sum^{n}_{i=1} \\alpha_i \\mathbf{A} \\mathbf{p}_i = \\mathbf{b}.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "bf3217ad", - "metadata": { - "editable": true - }, - "source": [ - "Multiplying with $\\boldsymbol{p}_k^T$ from the left gives" - ] - }, - { - "cell_type": "markdown", - "id": "b43b4b20", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\boldsymbol{p}_k^T \\boldsymbol{A}\\boldsymbol{x} = \\sum^{n}_{i=1} \\alpha_i\\boldsymbol{p}_k^T \\boldsymbol{A}\\boldsymbol{p}_i= \\boldsymbol{p}_k^T \\boldsymbol{b},\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "d82bb554", - "metadata": { - "editable": true - }, - "source": [ - "and we can define the coefficients $\\alpha_k$ as" - ] - }, - { - "cell_type": "markdown", - "id": "dde5ed03", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\alpha_k = \\frac{\\boldsymbol{p}_k^T \\boldsymbol{b}}{\\boldsymbol{p}_k^T \\boldsymbol{A} \\boldsymbol{p}_k}\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "65ecffe4", - "metadata": { - "editable": true - }, - "source": [ - "## Conjugate gradient method and iterations\n", - "\n", - "If we choose the conjugate vectors $\\boldsymbol{p}_k$ carefully, \n", - "then we may not need all of them to obtain a good approximation to the solution \n", - "$\\boldsymbol{x}$. \n", - "We want to regard the conjugate gradient method as an iterative method. \n", - "This will us to solve systems where $n$ is so large that the direct \n", - "method would take too much time.\n", - "\n", - "We denote the initial guess for $\\boldsymbol{x}$ as $\\boldsymbol{x}_0$. \n", - "We can assume without loss of generality that" - ] - }, - { - "cell_type": "markdown", - "id": "65a1b4c0", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\boldsymbol{x}_0=0,\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "41dec06b", - "metadata": { - "editable": true - }, - "source": [ - "or consider the system" - ] - }, - { - "cell_type": "markdown", - "id": "7d1da8a1", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\boldsymbol{A}\\boldsymbol{z} = \\boldsymbol{b}-\\boldsymbol{A}\\boldsymbol{x}_0,\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "c4850b28", - "metadata": { - "editable": true - }, - "source": [ - "instead." - ] - }, - { - "cell_type": "markdown", - "id": "ff91db7e", - "metadata": { - "editable": true - }, - "source": [ - "## Conjugate gradient method\n", - "One can show that the solution $\\boldsymbol{x}$ is also the unique minimizer of the quadratic form" - ] - }, - { - "cell_type": "markdown", - "id": "a8ab3c6e", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "f(\\boldsymbol{x}) = \\frac{1}{2}\\boldsymbol{x}^T\\boldsymbol{A}\\boldsymbol{x} - \\boldsymbol{x}^T \\boldsymbol{x} , \\quad \\boldsymbol{x}\\in\\mathbf{R}^n.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "e30ea38e", - "metadata": { - "editable": true - }, - "source": [ - "This suggests taking the first basis vector $\\boldsymbol{p}_1$ \n", - "to be the gradient of $f$ at $\\boldsymbol{x}=\\boldsymbol{x}_0$, \n", - "which equals" - ] - }, - { - "cell_type": "markdown", - "id": "ede52cdd", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\boldsymbol{A}\\boldsymbol{x}_0-\\boldsymbol{b},\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "3cdf6ffd", - "metadata": { - "editable": true - }, - "source": [ - "and \n", - "$\\boldsymbol{x}_0=0$ it is equal $-\\boldsymbol{b}$.\n", - "The other vectors in the basis will be conjugate to the gradient, \n", - "hence the name conjugate gradient method." - ] - }, - { - "cell_type": "markdown", - "id": "d66ac756", - "metadata": { - "editable": true - }, - "source": [ - "## Conjugate gradient method\n", - "Let $\\boldsymbol{r}_k$ be the residual at the $k$-th step:" - ] - }, - { - "cell_type": "markdown", - "id": "59b7a9f5", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\boldsymbol{r}_k=\\boldsymbol{b}-\\boldsymbol{A}\\boldsymbol{x}_k.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "769980be", - "metadata": { - "editable": true - }, - "source": [ - "Note that $\\boldsymbol{r}_k$ is the negative gradient of $f$ at \n", - "$\\boldsymbol{x}=\\boldsymbol{x}_k$, \n", - "so the gradient descent method would be to move in the direction $\\boldsymbol{r}_k$. \n", - "Here, we insist that the directions $\\boldsymbol{p}_k$ are conjugate to each other, \n", - "so we take the direction closest to the gradient $\\boldsymbol{r}_k$ \n", - "under the conjugacy constraint. \n", - "This gives the following expression" - ] - }, - { - "cell_type": "markdown", - "id": "3ae7691f", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\boldsymbol{p}_{k+1}=\\boldsymbol{r}_k-\\frac{\\boldsymbol{p}_k^T \\boldsymbol{A}\\boldsymbol{r}_k}{\\boldsymbol{p}_k^T\\boldsymbol{A}\\boldsymbol{p}_k} \\boldsymbol{p}_k.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "9cf530dc", - "metadata": { - "editable": true - }, - "source": [ - "## Conjugate gradient method\n", - "We can also compute the residual iteratively as" - ] - }, - { - "cell_type": "markdown", - "id": "6398a5d7", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\boldsymbol{r}_{k+1}=\\boldsymbol{b}-\\boldsymbol{A}\\boldsymbol{x}_{k+1},\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "b64c8282", - "metadata": { - "editable": true - }, - "source": [ - "which equals" - ] - }, - { - "cell_type": "markdown", - "id": "4b9bcf21", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\boldsymbol{b}-\\boldsymbol{A}(\\boldsymbol{x}_k+\\alpha_k\\boldsymbol{p}_k),\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "6d15e4b9", - "metadata": { - "editable": true - }, - "source": [ - "or" - ] - }, - { - "cell_type": "markdown", - "id": "592ac2b7", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "(\\boldsymbol{b}-\\boldsymbol{A}\\boldsymbol{x}_k)-\\alpha_k\\boldsymbol{A}\\boldsymbol{p}_k,\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "c54989ac", - "metadata": { - "editable": true - }, - "source": [ - "which gives" - ] - }, - { - "cell_type": "markdown", - "id": "87adadc2", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\boldsymbol{r}_{k+1}=\\boldsymbol{r}_k-\\boldsymbol{A}\\boldsymbol{p}_{k},\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "00250e67", - "metadata": { - "editable": true - }, - "source": [ - "## Revisiting our first homework\n", - "\n", - "We will use linear regression as a case study for the gradient descent\n", - "methods. Linear regression is a great test case for the gradient\n", - "descent methods discussed in the lectures since it has several\n", - "desirable properties such as:\n", - "\n", - "1. An analytical solution (recall homework set 1).\n", - "\n", - "2. The gradient can be computed analytically.\n", - "\n", - "3. The cost function is convex which guarantees that gradient descent converges for small enough learning rates\n", - "\n", - "We revisit an example similar to what we had in the first homework set. We had a function of the type" - ] - }, - { - "cell_type": "code", - "execution_count": 6, - "id": "47a98c7c", - "metadata": { - "collapsed": false, - "editable": true - }, - "outputs": [], - "source": [ - "x = 2*np.random.rand(m,1)\n", - "y = 4+3*x+np.random.randn(m,1)" - ] - }, - { - "cell_type": "markdown", - "id": "e3007f3b", - "metadata": { - "editable": true - }, - "source": [ - "with $x_i \\in [0,1] $ is chosen randomly using a uniform distribution. Additionally we have a stochastic noise chosen according to a normal distribution $\\cal {N}(0,1)$. \n", - "The linear regression model is given by" - ] - }, - { - "cell_type": "markdown", - "id": "c5b7179d", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "h_\\beta(x) = \\boldsymbol{y} = \\beta_0 + \\beta_1 x,\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "8a4d63b4", - "metadata": { - "editable": true - }, - "source": [ - "such that" - ] - }, - { - "cell_type": "markdown", - "id": "206c9402", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\boldsymbol{y}_i = \\beta_0 + \\beta_1 x_i.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "939b3b78", - "metadata": { - "editable": true - }, - "source": [ - "## Gradient descent example\n", - "\n", - "Let $\\mathbf{y} = (y_1,\\cdots,y_n)^T$, $\\mathbf{\\boldsymbol{y}} = (\\boldsymbol{y}_1,\\cdots,\\boldsymbol{y}_n)^T$ and $\\beta = (\\beta_0, \\beta_1)^T$\n", - "\n", - "It is convenient to write $\\mathbf{\\boldsymbol{y}} = X\\beta$ where $X \\in \\mathbb{R}^{100 \\times 2} $ is the design matrix given by (we keep the intercept here)" - ] - }, - { - "cell_type": "markdown", - "id": "b867af05", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "X \\equiv \\begin{bmatrix}\n", - "1 & x_1 \\\\\n", - "\\vdots & \\vdots \\\\\n", - "1 & x_{100} & \\\\\n", - "\\end{bmatrix}.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "76738c60", - "metadata": { - "editable": true - }, - "source": [ - "The cost/loss/risk function is given by (" - ] - }, - { - "cell_type": "markdown", - "id": "c01273f5", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "C(\\beta) = \\frac{1}{n}||X\\beta-\\mathbf{y}||_{2}^{2} = \\frac{1}{n}\\sum_{i=1}^{100}\\left[ (\\beta_0 + \\beta_1 x_i)^2 - 2 y_i (\\beta_0 + \\beta_1 x_i) + y_i^2\\right]\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "5d680787", - "metadata": { - "editable": true - }, - "source": [ - "and we want to find $\\beta$ such that $C(\\beta)$ is minimized." - ] - }, - { - "cell_type": "markdown", - "id": "2ef9ff3b", - "metadata": { - "editable": true - }, - "source": [ - "## The derivative of the cost/loss function\n", - "\n", - "Computing $\\partial C(\\beta) / \\partial \\beta_0$ and $\\partial C(\\beta) / \\partial \\beta_1$ we can show that the gradient can be written as" - ] - }, - { - "cell_type": "markdown", - "id": "e5a81fba", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\nabla_{\\beta} C(\\beta) = \\frac{2}{n}\\begin{bmatrix} \\sum_{i=1}^{100} \\left(\\beta_0+\\beta_1x_i-y_i\\right) \\\\\n", - "\\sum_{i=1}^{100}\\left( x_i (\\beta_0+\\beta_1x_i)-y_ix_i\\right) \\\\\n", - "\\end{bmatrix} = \\frac{2}{n}X^T(X\\beta - \\mathbf{y}),\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "b7298ace", - "metadata": { - "editable": true - }, - "source": [ - "where $X$ is the design matrix defined above." - ] - }, - { - "cell_type": "markdown", - "id": "64cfb75f", - "metadata": { - "editable": true - }, - "source": [ - "## The Hessian matrix\n", - "The Hessian matrix of $C(\\beta)$ is given by" - ] - }, - { - "cell_type": "markdown", - "id": "99503e16", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\boldsymbol{H} \\equiv \\begin{bmatrix}\n", - "\\frac{\\partial^2 C(\\beta)}{\\partial \\beta_0^2} & \\frac{\\partial^2 C(\\beta)}{\\partial \\beta_0 \\partial \\beta_1} \\\\\n", - "\\frac{\\partial^2 C(\\beta)}{\\partial \\beta_0 \\partial \\beta_1} & \\frac{\\partial^2 C(\\beta)}{\\partial \\beta_1^2} & \\\\\n", - "\\end{bmatrix} = \\frac{2}{n}X^T X.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "4a567780", - "metadata": { - "editable": true - }, - "source": [ - "This result implies that $C(\\beta)$ is a convex function since the matrix $X^T X$ always is positive semi-definite." - ] - }, - { - "cell_type": "markdown", - "id": "22c576da", - "metadata": { - "editable": true - }, - "source": [ - "## Simple program\n", - "\n", - "We can now write a program that minimizes $C(\\beta)$ using the gradient descent method with a constant learning rate $\\gamma$ according to" - ] - }, - { - "cell_type": "markdown", - "id": "44a99f62", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\beta_{k+1} = \\beta_k - \\gamma \\nabla_\\beta C(\\beta_k), \\ k=0,1,\\cdots\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "7021c749", - "metadata": { - "editable": true - }, - "source": [ - "We can use the expression we computed for the gradient and let use a\n", - "$\\beta_0$ be chosen randomly and let $\\gamma = 0.001$. Stop iterating\n", - "when $||\\nabla_\\beta C(\\beta_k) || \\leq \\epsilon = 10^{-8}$. **Note that the code below does not include the latter stop criterion**.\n", - "\n", - "And finally we can compare our solution for $\\beta$ with the analytic result given by \n", - "$\\beta= (X^TX)^{-1} X^T \\mathbf{y}$." - ] - }, - { - "cell_type": "markdown", - "id": "6044e7a8", - "metadata": { - "editable": true - }, - "source": [ - "## Gradient Descent Example\n", - "\n", - "Here our simple example" - ] - }, - { - "cell_type": "code", - "execution_count": 7, - "id": "72003ff9", - "metadata": { - "collapsed": false, - "editable": true - }, - "outputs": [], - "source": [ - "\n", - "# Importing various packages\n", - "from random import random, seed\n", - "import numpy as np\n", - "import matplotlib.pyplot as plt\n", - "from mpl_toolkits.mplot3d import Axes3D\n", - "from matplotlib import cm\n", - "from matplotlib.ticker import LinearLocator, FormatStrFormatter\n", - "import sys\n", - "\n", - "# the number of datapoints\n", - "n = 100\n", - "x = 2*np.random.rand(n,1)\n", - "y = 4+3*x+np.random.randn(n,1)\n", - "\n", - "X = np.c_[np.ones((n,1)), x]\n", - "# Hessian matrix\n", - "H = (2.0/n)* X.T @ X\n", - "# Get the eigenvalues\n", - "EigValues, EigVectors = np.linalg.eig(H)\n", - "print(f\"Eigenvalues of Hessian Matrix:{EigValues}\")\n", - "\n", - "beta_linreg = np.linalg.inv(X.T @ X) @ X.T @ y\n", - "print(beta_linreg)\n", - "beta = np.random.randn(2,1)\n", - "\n", - "eta = 1.0/np.max(EigValues)\n", - "Niterations = 1000\n", - "\n", - "for iter in range(Niterations):\n", - " gradient = (2.0/n)*X.T @ (X @ beta-y)\n", - " beta -= eta*gradient\n", - "\n", - "print(beta)\n", - "xnew = np.array([[0],[2]])\n", - "xbnew = np.c_[np.ones((2,1)), xnew]\n", - "ypredict = xbnew.dot(beta)\n", - "ypredict2 = xbnew.dot(beta_linreg)\n", - "plt.plot(xnew, ypredict, \"r-\")\n", - "plt.plot(xnew, ypredict2, \"b-\")\n", - "plt.plot(x, y ,'ro')\n", - "plt.axis([0,2.0,0, 15.0])\n", - "plt.xlabel(r'$x$')\n", - "plt.ylabel(r'$y$')\n", - "plt.title(r'Gradient descent example')\n", - "plt.show()" - ] - }, - { - "cell_type": "markdown", - "id": "01fdfcaf", - "metadata": { - "editable": true - }, - "source": [ - "## And a corresponding example using **scikit-learn**" - ] - }, - { - "cell_type": "code", - "execution_count": 8, - "id": "d16ddbdc", - "metadata": { - "collapsed": false, - "editable": true - }, - "outputs": [], - "source": [ - "# Importing various packages\n", - "from random import random, seed\n", - "import numpy as np\n", - "import matplotlib.pyplot as plt\n", - "from sklearn.linear_model import SGDRegressor\n", - "\n", - "n = 100\n", - "x = 2*np.random.rand(n,1)\n", - "y = 4+3*x+np.random.randn(n,1)\n", - "\n", - "X = np.c_[np.ones((n,1)), x]\n", - "beta_linreg = np.linalg.inv(X.T @ X) @ (X.T @ y)\n", - "print(beta_linreg)\n", - "sgdreg = SGDRegressor(max_iter = 50, penalty=None, eta0=0.1)\n", - "sgdreg.fit(x,y.ravel())\n", - "print(sgdreg.intercept_, sgdreg.coef_)" - ] - }, - { - "cell_type": "markdown", - "id": "08aaf479", - "metadata": { - "editable": true - }, - "source": [ - "## Gradient descent and Ridge\n", - "\n", - "We have also discussed Ridge regression where the loss function contains a regularized term given by the $L_2$ norm of $\\beta$," - ] - }, - { - "cell_type": "markdown", - "id": "0aa5045f", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "C_{\\text{ridge}}(\\beta) = \\frac{1}{n}||X\\beta -\\mathbf{y}||^2 + \\lambda ||\\beta||^2, \\ \\lambda \\geq 0.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "6474d14b", - "metadata": { - "editable": true - }, - "source": [ - "In order to minimize $C_{\\text{ridge}}(\\beta)$ using GD we adjust the gradient as follows" - ] - }, - { - "cell_type": "markdown", - "id": "9335b39d", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\nabla_\\beta C_{\\text{ridge}}(\\beta) = \\frac{2}{n}\\begin{bmatrix} \\sum_{i=1}^{100} \\left(\\beta_0+\\beta_1x_i-y_i\\right) \\\\\n", - "\\sum_{i=1}^{100}\\left( x_i (\\beta_0+\\beta_1x_i)-y_ix_i\\right) \\\\\n", - "\\end{bmatrix} + 2\\lambda\\begin{bmatrix} \\beta_0 \\\\ \\beta_1\\end{bmatrix} = 2 (\\frac{1}{n}X^T(X\\beta - \\mathbf{y})+\\lambda \\beta).\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "0680a59f", - "metadata": { - "editable": true - }, - "source": [ - "We can easily extend our program to minimize $C_{\\text{ridge}}(\\beta)$ using gradient descent and compare with the analytical solution given by" - ] - }, - { - "cell_type": "markdown", - "id": "de5afdeb", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\beta_{\\text{ridge}} = \\left(X^T X + n\\lambda I_{2 \\times 2} \\right)^{-1} X^T \\mathbf{y}.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "0042d7e6", - "metadata": { - "editable": true - }, - "source": [ - "## The Hessian matrix for Ridge Regression\n", - "The Hessian matrix of Ridge Regression for our simple example is given by" - ] - }, - { - "cell_type": "markdown", - "id": "02cf311f", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\boldsymbol{H} \\equiv \\begin{bmatrix}\n", - "\\frac{\\partial^2 C(\\beta)}{\\partial \\beta_0^2} & \\frac{\\partial^2 C(\\beta)}{\\partial \\beta_0 \\partial \\beta_1} \\\\\n", - "\\frac{\\partial^2 C(\\beta)}{\\partial \\beta_0 \\partial \\beta_1} & \\frac{\\partial^2 C(\\beta)}{\\partial \\beta_1^2} & \\\\\n", - "\\end{bmatrix} = \\frac{2}{n}X^T X+2\\lambda\\boldsymbol{I}.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "3dbc50e6", - "metadata": { - "editable": true - }, - "source": [ - "This implies that the Hessian matrix is positive definite, hence the stationary point is a\n", - "minimum.\n", - "Note that the Ridge cost function is convex being a sum of two convex\n", - "functions. Therefore, the stationary point is a global\n", - "minimum of this function." - ] - }, - { - "cell_type": "markdown", - "id": "437e17bc", - "metadata": { - "editable": true - }, - "source": [ - "## Program example for gradient descent with Ridge Regression" - ] - }, - { - "cell_type": "code", - "execution_count": 9, - "id": "f11ee927", - "metadata": { - "collapsed": false, - "editable": true - }, - "outputs": [], - "source": [ - "from random import random, seed\n", - "import numpy as np\n", - "import matplotlib.pyplot as plt\n", - "from mpl_toolkits.mplot3d import Axes3D\n", - "from matplotlib import cm\n", - "from matplotlib.ticker import LinearLocator, FormatStrFormatter\n", - "import sys\n", - "\n", - "# the number of datapoints\n", - "n = 100\n", - "x = 2*np.random.rand(n,1)\n", - "y = 4+3*x+np.random.randn(n,1)\n", - "\n", - "X = np.c_[np.ones((n,1)), x]\n", - "XT_X = X.T @ X\n", - "\n", - "#Ridge parameter lambda\n", - "lmbda = 0.001\n", - "Id = n*lmbda* np.eye(XT_X.shape[0])\n", - "\n", - "# Hessian matrix\n", - "H = (2.0/n)* XT_X+2*lmbda* np.eye(XT_X.shape[0])\n", - "# Get the eigenvalues\n", - "EigValues, EigVectors = np.linalg.eig(H)\n", - "print(f\"Eigenvalues of Hessian Matrix:{EigValues}\")\n", - "\n", - "\n", - "beta_linreg = np.linalg.inv(XT_X+Id) @ X.T @ y\n", - "print(beta_linreg)\n", - "# Start plain gradient descent\n", - "beta = np.random.randn(2,1)\n", - "\n", - "eta = 1.0/np.max(EigValues)\n", - "Niterations = 100\n", - "\n", - "for iter in range(Niterations):\n", - " gradients = 2.0/n*X.T @ (X @ (beta)-y)+2*lmbda*beta\n", - " beta -= eta*gradients\n", - "\n", - "print(beta)\n", - "ypredict = X @ beta\n", - "ypredict2 = X @ beta_linreg\n", - "plt.plot(x, ypredict, \"r-\")\n", - "plt.plot(x, ypredict2, \"b-\")\n", - "plt.plot(x, y ,'ro')\n", - "plt.axis([0,2.0,0, 15.0])\n", - "plt.xlabel(r'$x$')\n", - "plt.ylabel(r'$y$')\n", - "plt.title(r'Gradient descent example for Ridge')\n", - "plt.show()" - ] - }, - { - "cell_type": "markdown", - "id": "c06cf31f", - "metadata": { - "editable": true - }, - "source": [ - "## Using gradient descent methods, limitations\n", - "\n", - "* **Gradient descent (GD) finds local minima of our function**. Since the GD algorithm is deterministic, if it converges, it will converge to a local minimum of our cost/loss/risk function. Because in ML we are often dealing with extremely rugged landscapes with many local minima, this can lead to poor performance.\n", - "\n", - "* **GD is sensitive to initial conditions**. One consequence of the local nature of GD is that initial conditions matter. Depending on where one starts, one will end up at a different local minima. Therefore, it is very important to think about how one initializes the training process. This is true for GD as well as more complicated variants of GD.\n", - "\n", - "* **Gradients are computationally expensive to calculate for large datasets**. In many cases in statistics and ML, the cost/loss/risk function is a sum of terms, with one term for each data point. For example, in linear regression, $E \\propto \\sum_{i=1}^n (y_i - \\mathbf{w}^T\\cdot\\mathbf{x}_i)^2$; for logistic regression, the square error is replaced by the cross entropy. To calculate the gradient we have to sum over *all* $n$ data points. Doing this at every GD step becomes extremely computationally expensive. An ingenious solution to this, is to calculate the gradients using small subsets of the data called \"mini batches\". This has the added benefit of introducing stochasticity into our algorithm.\n", - "\n", - "* **GD is very sensitive to choices of learning rates**. GD is extremely sensitive to the choice of learning rates. If the learning rate is very small, the training process take an extremely long time. For larger learning rates, GD can diverge and give poor results. Furthermore, depending on what the local landscape looks like, we have to modify the learning rates to ensure convergence. Ideally, we would *adaptively* choose the learning rates to match the landscape.\n", - "\n", - "* **GD treats all directions in parameter space uniformly.** Another major drawback of GD is that unlike Newton's method, the learning rate for GD is the same in all directions in parameter space. For this reason, the maximum learning rate is set by the behavior of the steepest direction and this can significantly slow down training. Ideally, we would like to take large steps in flat directions and small steps in steep directions. Since we are exploring rugged landscapes where curvatures change, this requires us to keep track of not only the gradient but second derivatives. The ideal scenario would be to calculate the Hessian but this proves to be too computationally expensive. \n", - "\n", - "* GD can take exponential time to escape saddle points, even with random initialization. As we mentioned, GD is extremely sensitive to initial condition since it determines the particular local minimum GD would eventually reach. However, even with a good initialization scheme, through the introduction of randomness, GD can still take exponential time to escape saddle points." - ] - }, - { - "cell_type": "markdown", - "id": "870586cd", - "metadata": { - "editable": true - }, - "source": [ - "## Improving gradient descent with momentum\n", - "\n", - "We discuss here some simple examples where we introduce what is called 'memory'about previous steps, or what is normally called momentum gradient descent. The mathematics is explained below in connection with Stochastic gradient descent." - ] - }, - { - "cell_type": "code", - "execution_count": 10, - "id": "24517bb5", - "metadata": { - "collapsed": false, - "editable": true - }, - "outputs": [], - "source": [ - "from numpy import asarray\n", - "from numpy import arange\n", - "from numpy.random import rand\n", - "from numpy.random import seed\n", - "from matplotlib import pyplot\n", - " \n", - "# objective function\n", - "def objective(x):\n", - "\treturn x**2.0\n", - " \n", - "# derivative of objective function\n", - "def derivative(x):\n", - "\treturn x * 2.0\n", - " \n", - "# gradient descent algorithm\n", - "def gradient_descent(objective, derivative, bounds, n_iter, step_size):\n", - "\t# track all solutions\n", - "\tsolutions, scores = list(), list()\n", - "\t# generate an initial point\n", - "\tsolution = bounds[:, 0] + rand(len(bounds)) * (bounds[:, 1] - bounds[:, 0])\n", - "\t# run the gradient descent\n", - "\tfor i in range(n_iter):\n", - "\t\t# calculate gradient\n", - "\t\tgradient = derivative(solution)\n", - "\t\t# take a step\n", - "\t\tsolution = solution - step_size * gradient\n", - "\t\t# evaluate candidate point\n", - "\t\tsolution_eval = objective(solution)\n", - "\t\t# store solution\n", - "\t\tsolutions.append(solution)\n", - "\t\tscores.append(solution_eval)\n", - "\t\t# report progress\n", - "\t\tprint('>%d f(%s) = %.5f' % (i, solution, solution_eval))\n", - "\treturn [solutions, scores]\n", - " \n", - "# seed the pseudo random number generator\n", - "seed(4)\n", - "# define range for input\n", - "bounds = asarray([[-1.0, 1.0]])\n", - "# define the total iterations\n", - "n_iter = 30\n", - "# define the step size\n", - "step_size = 0.1\n", - "# perform the gradient descent search\n", - "solutions, scores = gradient_descent(objective, derivative, bounds, n_iter, step_size)\n", - "# sample input range uniformly at 0.1 increments\n", - "inputs = arange(bounds[0,0], bounds[0,1]+0.1, 0.1)\n", - "# compute targets\n", - "results = objective(inputs)\n", - "# create a line plot of input vs result\n", - "pyplot.plot(inputs, results)\n", - "# plot the solutions found\n", - "pyplot.plot(solutions, scores, '.-', color='red')\n", - "# show the plot\n", - "pyplot.show()" - ] - }, - { - "cell_type": "markdown", - "id": "57647429", - "metadata": { - "editable": true - }, - "source": [ - "## Same code but now with momentum gradient descent" - ] - }, - { - "cell_type": "code", - "execution_count": 11, - "id": "b8365c93", - "metadata": { - "collapsed": false, - "editable": true - }, - "outputs": [], - "source": [ - "from numpy import asarray\n", - "from numpy import arange\n", - "from numpy.random import rand\n", - "from numpy.random import seed\n", - "from matplotlib import pyplot\n", - " \n", - "# objective function\n", - "def objective(x):\n", - "\treturn x**2.0\n", - " \n", - "# derivative of objective function\n", - "def derivative(x):\n", - "\treturn x * 2.0\n", - " \n", - "# gradient descent algorithm\n", - "def gradient_descent(objective, derivative, bounds, n_iter, step_size, momentum):\n", - "\t# track all solutions\n", - "\tsolutions, scores = list(), list()\n", - "\t# generate an initial point\n", - "\tsolution = bounds[:, 0] + rand(len(bounds)) * (bounds[:, 1] - bounds[:, 0])\n", - "\t# keep track of the change\n", - "\tchange = 0.0\n", - "\t# run the gradient descent\n", - "\tfor i in range(n_iter):\n", - "\t\t# calculate gradient\n", - "\t\tgradient = derivative(solution)\n", - "\t\t# calculate update\n", - "\t\tnew_change = step_size * gradient + momentum * change\n", - "\t\t# take a step\n", - "\t\tsolution = solution - new_change\n", - "\t\t# save the change\n", - "\t\tchange = new_change\n", - "\t\t# evaluate candidate point\n", - "\t\tsolution_eval = objective(solution)\n", - "\t\t# store solution\n", - "\t\tsolutions.append(solution)\n", - "\t\tscores.append(solution_eval)\n", - "\t\t# report progress\n", - "\t\tprint('>%d f(%s) = %.5f' % (i, solution, solution_eval))\n", - "\treturn [solutions, scores]\n", - " \n", - "# seed the pseudo random number generator\n", - "seed(4)\n", - "# define range for input\n", - "bounds = asarray([[-1.0, 1.0]])\n", - "# define the total iterations\n", - "n_iter = 30\n", - "# define the step size\n", - "step_size = 0.1\n", - "# define momentum\n", - "momentum = 0.3\n", - "# perform the gradient descent search with momentum\n", - "solutions, scores = gradient_descent(objective, derivative, bounds, n_iter, step_size, momentum)\n", - "# sample input range uniformly at 0.1 increments\n", - "inputs = arange(bounds[0,0], bounds[0,1]+0.1, 0.1)\n", - "# compute targets\n", - "results = objective(inputs)\n", - "# create a line plot of input vs result\n", - "pyplot.plot(inputs, results)\n", - "# plot the solutions found\n", - "pyplot.plot(solutions, scores, '.-', color='red')\n", - "# show the plot\n", - "pyplot.show()" - ] - }, - { - "cell_type": "markdown", - "id": "3c5b105d", - "metadata": { - "editable": true - }, - "source": [ - "## Overview video on Stochastic Gradient Descent\n", - "\n", - "[What is Stochastic Gradient Descent](https://www.youtube.com/watch?v=vMh0zPT0tLI&ab_channel=StatQuestwithJoshStarmer)" - ] - }, - { - "cell_type": "markdown", - "id": "e78e4fcf", - "metadata": { - "editable": true - }, - "source": [ - "## Batches and mini-batches\n", - "\n", - "In gradient descent we compute the cost function and its gradient for all data points we have.\n", - "\n", - "In large-scale applications such as the [ILSVRC challenge](https://www.image-net.org/challenges/LSVRC/), the\n", - "training data can have on order of millions of examples. Hence, it\n", - "seems wasteful to compute the full cost function over the entire\n", - "training set in order to perform only a single parameter update. A\n", - "very common approach to addressing this challenge is to compute the\n", - "gradient over batches of the training data. For example, a typical batch could contain some thousand examples from\n", - "an entire training set of several millions. This batch is then used to\n", - "perform a parameter update." - ] - }, - { - "cell_type": "markdown", - "id": "9e856c0b", - "metadata": { - "editable": true - }, - "source": [ - "## Stochastic Gradient Descent (SGD)\n", - "\n", - "In stochastic gradient descent, the extreme case is the case where we\n", - "have only one batch, that is we include the whole data set.\n", - "\n", - "This process is called Stochastic Gradient\n", - "Descent (SGD) (or also sometimes on-line gradient descent). This is\n", - "relatively less common to see because in practice due to vectorized\n", - "code optimizations it can be computationally much more efficient to\n", - "evaluate the gradient for 100 examples, than the gradient for one\n", - "example 100 times. Even though SGD technically refers to using a\n", - "single example at a time to evaluate the gradient, you will hear\n", - "people use the term SGD even when referring to mini-batch gradient\n", - "descent (i.e. mentions of MGD for “Minibatch Gradient Descent”, or BGD\n", - "for “Batch gradient descent” are rare to see), where it is usually\n", - "assumed that mini-batches are used. The size of the mini-batch is a\n", - "hyperparameter but it is not very common to cross-validate or bootstrap it. It is\n", - "usually based on memory constraints (if any), or set to some value,\n", - "e.g. 32, 64 or 128. We use powers of 2 in practice because many\n", - "vectorized operation implementations work faster when their inputs are\n", - "sized in powers of 2.\n", - "\n", - "In our notes with SGD we mean stochastic gradient descent with mini-batches." - ] - }, - { - "cell_type": "markdown", - "id": "8400c2e5", - "metadata": { - "editable": true - }, - "source": [ - "## Stochastic Gradient Descent\n", - "\n", - "Stochastic gradient descent (SGD) and variants thereof address some of\n", - "the shortcomings of the Gradient descent method discussed above.\n", - "\n", - "The underlying idea of SGD comes from the observation that the cost\n", - "function, which we want to minimize, can almost always be written as a\n", - "sum over $n$ data points $\\{\\mathbf{x}_i\\}_{i=1}^n$," - ] - }, - { - "cell_type": "markdown", - "id": "d0ceff52", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "C(\\mathbf{\\beta}) = \\sum_{i=1}^n c_i(\\mathbf{x}_i,\n", - "\\mathbf{\\beta}).\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "562ca1d7", - "metadata": { - "editable": true - }, - "source": [ - "## Computation of gradients\n", - "\n", - "This in turn means that the gradient can be\n", - "computed as a sum over $i$-gradients" - ] - }, - { - "cell_type": "markdown", - "id": "ffea7df9", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\nabla_\\beta C(\\mathbf{\\beta}) = \\sum_i^n \\nabla_\\beta c_i(\\mathbf{x}_i,\n", - "\\mathbf{\\beta}).\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "20f1bd07", - "metadata": { - "editable": true - }, - "source": [ - "Stochasticity/randomness is introduced by only taking the\n", - "gradient on a subset of the data called minibatches. If there are $n$\n", - "data points and the size of each minibatch is $M$, there will be $n/M$\n", - "minibatches. We denote these minibatches by $B_k$ where\n", - "$k=1,\\cdots,n/M$." - ] - }, - { - "cell_type": "markdown", - "id": "4589bb1b", - "metadata": { - "editable": true - }, - "source": [ - "## SGD example\n", - "As an example, suppose we have $10$ data points $(\\mathbf{x}_1,\\cdots, \\mathbf{x}_{10})$ \n", - "and we choose to have $M=5$ minibathces,\n", - "then each minibatch contains two data points. In particular we have\n", - "$B_1 = (\\mathbf{x}_1,\\mathbf{x}_2), \\cdots, B_5 =\n", - "(\\mathbf{x}_9,\\mathbf{x}_{10})$. Note that if you choose $M=1$ you\n", - "have only a single batch with all data points and on the other extreme,\n", - "you may choose $M=n$ resulting in a minibatch for each datapoint, i.e\n", - "$B_k = \\mathbf{x}_k$.\n", - "\n", - "The idea is now to approximate the gradient by replacing the sum over\n", - "all data points with a sum over the data points in one the minibatches\n", - "picked at random in each gradient descent step" - ] - }, - { - "cell_type": "markdown", - "id": "0df2146b", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\nabla_{\\beta}\n", - "C(\\mathbf{\\beta}) = \\sum_{i=1}^n \\nabla_\\beta c_i(\\mathbf{x}_i,\n", - "\\mathbf{\\beta}) \\rightarrow \\sum_{i \\in B_k}^n \\nabla_\\beta\n", - "c_i(\\mathbf{x}_i, \\mathbf{\\beta}).\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "890e6746", - "metadata": { - "editable": true - }, - "source": [ - "## The gradient step\n", - "\n", - "Thus a gradient descent step now looks like" - ] - }, - { - "cell_type": "markdown", - "id": "b6e42059", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\beta_{j+1} = \\beta_j - \\gamma_j \\sum_{i \\in B_k}^n \\nabla_\\beta c_i(\\mathbf{x}_i,\n", - "\\mathbf{\\beta})\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "9dd3abbf", - "metadata": { - "editable": true - }, - "source": [ - "where $k$ is picked at random with equal\n", - "probability from $[1,n/M]$. An iteration over the number of\n", - "minibathces (n/M) is commonly referred to as an epoch. Thus it is\n", - "typical to choose a number of epochs and for each epoch iterate over\n", - "the number of minibatches, as exemplified in the code below." - ] - }, - { - "cell_type": "markdown", - "id": "97279f92", - "metadata": { - "editable": true - }, - "source": [ - "## Simple example code" - ] - }, - { - "cell_type": "code", - "execution_count": 12, - "id": "cb0c6322", - "metadata": { - "collapsed": false, - "editable": true - }, - "outputs": [], - "source": [ - "import numpy as np \n", - "\n", - "n = 100 #100 datapoints \n", - "M = 5 #size of each minibatch\n", - "m = int(n/M) #number of minibatches\n", - "n_epochs = 10 #number of epochs\n", - "\n", - "j = 0\n", - "for epoch in range(1,n_epochs+1):\n", - " for i in range(m):\n", - " k = np.random.randint(m) #Pick the k-th minibatch at random\n", - " #Compute the gradient using the data in minibatch Bk\n", - " #Compute new suggestion for \n", - " j += 1" - ] - }, - { - "cell_type": "markdown", - "id": "c0868aae", - "metadata": { - "editable": true - }, - "source": [ - "Taking the gradient only on a subset of the data has two important\n", - "benefits. First, it introduces randomness which decreases the chance\n", - "that our opmization scheme gets stuck in a local minima. Second, if\n", - "the size of the minibatches are small relative to the number of\n", - "datapoints ($M < n$), the computation of the gradient is much\n", - "cheaper since we sum over the datapoints in the $k-th$ minibatch and not\n", - "all $n$ datapoints." - ] - }, - { - "cell_type": "markdown", - "id": "1e17bb0f", - "metadata": { - "editable": true - }, - "source": [ - "## When do we stop?\n", - "\n", - "A natural question is when do we stop the search for a new minimum?\n", - "One possibility is to compute the full gradient after a given number\n", - "of epochs and check if the norm of the gradient is smaller than some\n", - "threshold and stop if true. However, the condition that the gradient\n", - "is zero is valid also for local minima, so this would only tell us\n", - "that we are close to a local/global minimum. However, we could also\n", - "evaluate the cost function at this point, store the result and\n", - "continue the search. If the test kicks in at a later stage we can\n", - "compare the values of the cost function and keep the $\\beta$ that\n", - "gave the lowest value." - ] - }, - { - "cell_type": "markdown", - "id": "f050ca70", - "metadata": { - "editable": true - }, - "source": [ - "## Slightly different approach\n", - "\n", - "Another approach is to let the step length $\\gamma_j$ depend on the\n", - "number of epochs in such a way that it becomes very small after a\n", - "reasonable time such that we do not move at all. Such approaches are\n", - "also called scaling. There are many such ways to [scale the learning\n", - "rate](https://towardsdatascience.com/gradient-descent-the-learning-rate-and-the-importance-of-feature-scaling-6c0b416596e1)\n", - "and [discussions here](https://www.jmlr.org/papers/volume23/20-1258/20-1258.pdf). See\n", - "also\n", - "\n", - "for a discussion of different scaling functions for the learning rate." - ] - }, - { - "cell_type": "markdown", - "id": "6a900f78", - "metadata": { - "editable": true - }, - "source": [ - "## Time decay rate\n", - "\n", - "As an example, let $e = 0,1,2,3,\\cdots$ denote the current epoch and let $t_0, t_1 > 0$ be two fixed numbers. Furthermore, let $t = e \\cdot m + i$ where $m$ is the number of minibatches and $i=0,\\cdots,m-1$. Then the function $$\\gamma_j(t; t_0, t_1) = \\frac{t_0}{t+t_1} $$ goes to zero as the number of epochs gets large. I.e. we start with a step length $\\gamma_j (0; t_0, t_1) = t_0/t_1$ which decays in *time* $t$.\n", - "\n", - "In this way we can fix the number of epochs, compute $\\beta$ and\n", - "evaluate the cost function at the end. Repeating the computation will\n", - "give a different result since the scheme is random by design. Then we\n", - "pick the final $\\beta$ that gives the lowest value of the cost\n", - "function." - ] - }, - { - "cell_type": "code", - "execution_count": 13, - "id": "1324db42", - "metadata": { - "collapsed": false, - "editable": true - }, - "outputs": [], - "source": [ - "import numpy as np \n", - "\n", - "def step_length(t,t0,t1):\n", - " return t0/(t+t1)\n", - "\n", - "n = 100 #100 datapoints \n", - "M = 5 #size of each minibatch\n", - "m = int(n/M) #number of minibatches\n", - "n_epochs = 500 #number of epochs\n", - "t0 = 1.0\n", - "t1 = 10\n", - "\n", - "gamma_j = t0/t1\n", - "j = 0\n", - "for epoch in range(1,n_epochs+1):\n", - " for i in range(m):\n", - " k = np.random.randint(m) #Pick the k-th minibatch at random\n", - " #Compute the gradient using the data in minibatch Bk\n", - " #Compute new suggestion for beta\n", - " t = epoch*m+i\n", - " gamma_j = step_length(t,t0,t1)\n", - " j += 1\n", - "\n", - "print(\"gamma_j after %d epochs: %g\" % (n_epochs,gamma_j))" - ] - }, - { - "cell_type": "markdown", - "id": "0c365408", - "metadata": { - "editable": true - }, - "source": [ - "## Code with a Number of Minibatches which varies\n", - "\n", - "In the code here we vary the number of mini-batches." - ] - }, - { - "cell_type": "code", - "execution_count": 14, - "id": "79417e81", - "metadata": { - "collapsed": false, - "editable": true - }, - "outputs": [], - "source": [ - "# Importing various packages\n", - "from math import exp, sqrt\n", - "from random import random, seed\n", - "import numpy as np\n", - "import matplotlib.pyplot as plt\n", - "\n", - "n = 100\n", - "x = 2*np.random.rand(n,1)\n", - "y = 4+3*x+np.random.randn(n,1)\n", - "\n", - "X = np.c_[np.ones((n,1)), x]\n", - "XT_X = X.T @ X\n", - "theta_linreg = np.linalg.inv(X.T @ X) @ (X.T @ y)\n", - "print(\"Own inversion\")\n", - "print(theta_linreg)\n", - "# Hessian matrix\n", - "H = (2.0/n)* XT_X\n", - "EigValues, EigVectors = np.linalg.eig(H)\n", - "print(f\"Eigenvalues of Hessian Matrix:{EigValues}\")\n", - "\n", - "theta = np.random.randn(2,1)\n", - "eta = 1.0/np.max(EigValues)\n", - "Niterations = 1000\n", - "\n", - "\n", - "for iter in range(Niterations):\n", - " gradients = 2.0/n*X.T @ ((X @ theta)-y)\n", - " theta -= eta*gradients\n", - "print(\"theta from own gd\")\n", - "print(theta)\n", - "\n", - "xnew = np.array([[0],[2]])\n", - "Xnew = np.c_[np.ones((2,1)), xnew]\n", - "ypredict = Xnew.dot(theta)\n", - "ypredict2 = Xnew.dot(theta_linreg)\n", - "\n", - "n_epochs = 50\n", - "M = 5 #size of each minibatch\n", - "m = int(n/M) #number of minibatches\n", - "t0, t1 = 5, 50\n", - "\n", - "def learning_schedule(t):\n", - " return t0/(t+t1)\n", - "\n", - "theta = np.random.randn(2,1)\n", - "\n", - "for epoch in range(n_epochs):\n", - "# Can you figure out a better way of setting up the contributions to each batch?\n", - " for i in range(m):\n", - " random_index = M*np.random.randint(m)\n", - " xi = X[random_index:random_index+M]\n", - " yi = y[random_index:random_index+M]\n", - " gradients = (2.0/M)* xi.T @ ((xi @ theta)-yi)\n", - " eta = learning_schedule(epoch*m+i)\n", - " theta = theta - eta*gradients\n", - "print(\"theta from own sdg\")\n", - "print(theta)\n", - "\n", - "plt.plot(xnew, ypredict, \"r-\")\n", - "plt.plot(xnew, ypredict2, \"b-\")\n", - "plt.plot(x, y ,'ro')\n", - "plt.axis([0,2.0,0, 15.0])\n", - "plt.xlabel(r'$x$')\n", - "plt.ylabel(r'$y$')\n", - "plt.title(r'Random numbers ')\n", - "plt.show()" - ] - }, - { - "cell_type": "markdown", - "id": "dd16fd67", - "metadata": { - "editable": true - }, - "source": [ - "## Replace or not\n", - "\n", - "In the above code, we have use replacement in setting up the\n", - "mini-batches. The discussion\n", - "[here](https://sebastianraschka.com/faq/docs/sgd-methods.html) may be\n", - "useful." - ] - }, - { - "cell_type": "markdown", - "id": "2bbf7fbd", - "metadata": { - "editable": true - }, - "source": [ - "## Momentum based GD\n", - "\n", - "The stochastic gradient descent (SGD) is almost always used with a\n", - "*momentum* or inertia term that serves as a memory of the direction we\n", - "are moving in parameter space. This is typically implemented as\n", - "follows" - ] - }, - { - "cell_type": "markdown", - "id": "d4aa4448", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\mathbf{v}_{t}=\\gamma \\mathbf{v}_{t-1}+\\eta_{t}\\nabla_\\theta E(\\boldsymbol{\\theta}_t) \\nonumber\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "fdcd258f", - "metadata": { - "editable": true - }, - "source": [ - "\n", - "
\n", - "\n", - "$$\n", - "\\begin{equation} \n", - "\\boldsymbol{\\theta}_{t+1}= \\boldsymbol{\\theta}_t -\\mathbf{v}_{t},\n", - "\\label{_auto1} \\tag{2}\n", - "\\end{equation}\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "52ec5bfb", - "metadata": { - "editable": true - }, - "source": [ - "where we have introduced a momentum parameter $\\gamma$, with\n", - "$0\\le\\gamma\\le 1$, and for brevity we dropped the explicit notation to\n", - "indicate the gradient is to be taken over a different mini-batch at\n", - "each step. We call this algorithm gradient descent with momentum\n", - "(GDM). From these equations, it is clear that $\\mathbf{v}_t$ is a\n", - "running average of recently encountered gradients and\n", - "$(1-\\gamma)^{-1}$ sets the characteristic time scale for the memory\n", - "used in the averaging procedure. Consistent with this, when\n", - "$\\gamma=0$, this just reduces down to ordinary SGD as discussed\n", - "earlier. An equivalent way of writing the updates is" - ] - }, - { - "cell_type": "markdown", - "id": "38004062", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\Delta \\boldsymbol{\\theta}_{t+1} = \\gamma \\Delta \\boldsymbol{\\theta}_t -\\ \\eta_{t}\\nabla_\\theta E(\\boldsymbol{\\theta}_t),\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "9d07c567", - "metadata": { - "editable": true - }, - "source": [ - "where we have defined $\\Delta \\boldsymbol{\\theta}_{t}= \\boldsymbol{\\theta}_t-\\boldsymbol{\\theta}_{t-1}$." - ] - }, - { - "cell_type": "markdown", - "id": "4dbba8bc", - "metadata": { - "editable": true - }, - "source": [ - "## More on momentum based approaches\n", - "\n", - "Let us try to get more intuition from these equations. It is helpful\n", - "to consider a simple physical analogy with a particle of mass $m$\n", - "moving in a viscous medium with drag coefficient $\\mu$ and potential\n", - "$E(\\mathbf{w})$. If we denote the particle's position by $\\mathbf{w}$,\n", - "then its motion is described by" - ] - }, - { - "cell_type": "markdown", - "id": "dab76529", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "m {d^2 \\mathbf{w} \\over dt^2} + \\mu {d \\mathbf{w} \\over dt }= -\\nabla_w E(\\mathbf{w}).\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "6e049d15", - "metadata": { - "editable": true - }, - "source": [ - "We can discretize this equation in the usual way to get" - ] - }, - { - "cell_type": "markdown", - "id": "5079f465", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "m { \\mathbf{w}_{t+\\Delta t}-2 \\mathbf{w}_{t} +\\mathbf{w}_{t-\\Delta t} \\over (\\Delta t)^2}+\\mu {\\mathbf{w}_{t+\\Delta t}- \\mathbf{w}_{t} \\over \\Delta t} = -\\nabla_w E(\\mathbf{w}).\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "51c2ed45", - "metadata": { - "editable": true - }, - "source": [ - "Rearranging this equation, we can rewrite this as" - ] - }, - { - "cell_type": "markdown", - "id": "7e8f7b16", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\Delta \\mathbf{w}_{t +\\Delta t}= - { (\\Delta t)^2 \\over m +\\mu \\Delta t} \\nabla_w E(\\mathbf{w})+ {m \\over m +\\mu \\Delta t} \\Delta \\mathbf{w}_t.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "ae0505aa", - "metadata": { - "editable": true - }, - "source": [ - "## Momentum parameter\n", - "\n", - "Notice that this equation is identical to previous one if we identify\n", - "the position of the particle, $\\mathbf{w}$, with the parameters\n", - "$\\boldsymbol{\\theta}$. This allows us to identify the momentum\n", - "parameter and learning rate with the mass of the particle and the\n", - "viscous drag as:" - ] - }, - { - "cell_type": "markdown", - "id": "9e7f520b", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\gamma= {m \\over m +\\mu \\Delta t }, \\qquad \\eta = {(\\Delta t)^2 \\over m +\\mu \\Delta t}.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "5c0aa1f6", - "metadata": { - "editable": true - }, - "source": [ - "Thus, as the name suggests, the momentum parameter is proportional to\n", - "the mass of the particle and effectively provides inertia.\n", - "Furthermore, in the large viscosity/small learning rate limit, our\n", - "memory time scales as $(1-\\gamma)^{-1} \\approx m/(\\mu \\Delta t)$.\n", - "\n", - "Why is momentum useful? SGD momentum helps the gradient descent\n", - "algorithm gain speed in directions with persistent but small gradients\n", - "even in the presence of stochasticity, while suppressing oscillations\n", - "in high-curvature directions. This becomes especially important in\n", - "situations where the landscape is shallow and flat in some directions\n", - "and narrow and steep in others. It has been argued that first-order\n", - "methods (with appropriate initial conditions) can perform comparable\n", - "to more expensive second order methods, especially in the context of\n", - "complex deep learning models.\n", - "\n", - "These beneficial properties of momentum can sometimes become even more\n", - "pronounced by using a slight modification of the classical momentum\n", - "algorithm called Nesterov Accelerated Gradient (NAG).\n", - "\n", - "In the NAG algorithm, rather than calculating the gradient at the\n", - "current parameters, $\\nabla_\\theta E(\\boldsymbol{\\theta}_t)$, one\n", - "calculates the gradient at the expected value of the parameters given\n", - "our current momentum, $\\nabla_\\theta E(\\boldsymbol{\\theta}_t +\\gamma\n", - "\\mathbf{v}_{t-1})$. This yields the NAG update rule" - ] - }, - { - "cell_type": "markdown", - "id": "991c2c15", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\mathbf{v}_{t}=\\gamma \\mathbf{v}_{t-1}+\\eta_{t}\\nabla_\\theta E(\\boldsymbol{\\theta}_t +\\gamma \\mathbf{v}_{t-1}) \\nonumber\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "c643afb5", - "metadata": { - "editable": true - }, - "source": [ - "\n", - "
\n", - "\n", - "$$\n", - "\\begin{equation} \n", - "\\boldsymbol{\\theta}_{t+1}= \\boldsymbol{\\theta}_t -\\mathbf{v}_{t}.\n", - "\\label{_auto2} \\tag{3}\n", - "\\end{equation}\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "ac4a060d", - "metadata": { - "editable": true - }, - "source": [ - "One of the major advantages of NAG is that it allows for the use of a larger learning rate than GDM for the same choice of $\\gamma$." - ] - }, - { - "cell_type": "markdown", - "id": "37584d4d", - "metadata": { - "editable": true - }, - "source": [ - "## Second moment of the gradient\n", - "\n", - "In stochastic gradient descent, with and without momentum, we still\n", - "have to specify a schedule for tuning the learning rates $\\eta_t$\n", - "as a function of time. As discussed in the context of Newton's\n", - "method, this presents a number of dilemmas. The learning rate is\n", - "limited by the steepest direction which can change depending on the\n", - "current position in the landscape. To circumvent this problem, ideally\n", - "our algorithm would keep track of curvature and take large steps in\n", - "shallow, flat directions and small steps in steep, narrow directions.\n", - "Second-order methods accomplish this by calculating or approximating\n", - "the Hessian and normalizing the learning rate by the\n", - "curvature. However, this is very computationally expensive for\n", - "extremely large models. Ideally, we would like to be able to\n", - "adaptively change the step size to match the landscape without paying\n", - "the steep computational price of calculating or approximating\n", - "Hessians.\n", - "\n", - "Recently, a number of methods have been introduced that accomplish\n", - "this by tracking not only the gradient, but also the second moment of\n", - "the gradient. These methods include AdaGrad, AdaDelta, Root Mean Squared Propagation (RMS-Prop), and\n", - "[ADAM](https://arxiv.org/abs/1412.6980)." - ] - }, - { - "cell_type": "markdown", - "id": "0e9c907f", - "metadata": { - "editable": true - }, - "source": [ - "## RMS prop\n", - "\n", - "In RMS prop, in addition to keeping a running average of the first\n", - "moment of the gradient, we also keep track of the second moment\n", - "denoted by $\\mathbf{s}_t=\\mathbb{E}[\\mathbf{g}_t^2]$. The update rule\n", - "for RMS prop is given by" - ] - }, - { - "cell_type": "markdown", - "id": "cb4567f1", - "metadata": { - "editable": true - }, - "source": [ - "\n", - "
\n", - "\n", - "$$\n", - "\\begin{equation}\n", - "\\mathbf{g}_t = \\nabla_\\theta E(\\boldsymbol{\\theta}) \n", - "\\label{_auto3} \\tag{4}\n", - "\\end{equation}\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "71805d3d", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\mathbf{s}_t =\\beta \\mathbf{s}_{t-1} +(1-\\beta)\\mathbf{g}_t^2 \\nonumber\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "09794996", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\boldsymbol{\\theta}_{t+1}=\\boldsymbol{\\theta}_t - \\eta_t { \\mathbf{g}_t \\over \\sqrt{\\mathbf{s}_t +\\epsilon}}, \\nonumber\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "aeb48f66", - "metadata": { - "editable": true - }, - "source": [ - "where $\\beta$ controls the averaging time of the second moment and is\n", - "typically taken to be about $\\beta=0.9$, $\\eta_t$ is a learning rate\n", - "typically chosen to be $10^{-3}$, and $\\epsilon\\sim 10^{-8} $ is a\n", - "small regularization constant to prevent divergences. Multiplication\n", - "and division by vectors is understood as an element-wise operation. It\n", - "is clear from this formula that the learning rate is reduced in\n", - "directions where the norm of the gradient is consistently large. This\n", - "greatly speeds up the convergence by allowing us to use a larger\n", - "learning rate for flat directions." - ] - }, - { - "cell_type": "markdown", - "id": "68e08134", - "metadata": { - "editable": true - }, - "source": [ - "## [ADAM optimizer](https://arxiv.org/abs/1412.6980)\n", - "\n", - "A related algorithm is the ADAM optimizer. In\n", - "[ADAM](https://arxiv.org/abs/1412.6980), we keep a running average of\n", - "both the first and second moment of the gradient and use this\n", - "information to adaptively change the learning rate for different\n", - "parameters. The method isefficient when working with large\n", - "problems involving lots data and/or parameters. It is a combination of the\n", - "gradient descent with momentum algorithm and the RMSprop algorithm\n", - "discussed above.\n", - "\n", - "In addition to keeping a running average of the first and\n", - "second moments of the gradient\n", - "(i.e. $\\mathbf{m}_t=\\mathbb{E}[\\mathbf{g}_t]$ and\n", - "$\\mathbf{s}_t=\\mathbb{E}[\\mathbf{g}^2_t]$, respectively), ADAM\n", - "performs an additional bias correction to account for the fact that we\n", - "are estimating the first two moments of the gradient using a running\n", - "average (denoted by the hats in the update rule below). The update\n", - "rule for ADAM is given by (where multiplication and division are once\n", - "again understood to be element-wise operations below)" - ] - }, - { - "cell_type": "markdown", - "id": "69308397", - "metadata": { - "editable": true - }, - "source": [ - "\n", - "
\n", - "\n", - "$$\n", - "\\begin{equation}\n", - "\\mathbf{g}_t = \\nabla_\\theta E(\\boldsymbol{\\theta}) \n", - "\\label{_auto4} \\tag{5}\n", - "\\end{equation}\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "d23ab794", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\mathbf{m}_t = \\beta_1 \\mathbf{m}_{t-1} + (1-\\beta_1) \\mathbf{g}_t \\nonumber\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "c4cef70b", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\mathbf{s}_t =\\beta_2 \\mathbf{s}_{t-1} +(1-\\beta_2)\\mathbf{g}_t^2 \\nonumber\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "6aebd1b5", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\boldsymbol{\\mathbf{m}}_t={\\mathbf{m}_t \\over 1-\\beta_1^t} \\nonumber\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "c43fe267", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\boldsymbol{\\mathbf{s}}_t ={\\mathbf{s}_t \\over1-\\beta_2^t} \\nonumber\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "9ae56692", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\boldsymbol{\\theta}_{t+1}=\\boldsymbol{\\theta}_t - \\eta_t { \\boldsymbol{\\mathbf{m}}_t \\over \\sqrt{\\boldsymbol{\\mathbf{s}}_t} +\\epsilon}, \\nonumber\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "784ba00e", - "metadata": { - "editable": true - }, - "source": [ - "\n", - "
\n", - "\n", - "$$\n", - "\\begin{equation} \n", - "\\label{_auto5} \\tag{6}\n", - "\\end{equation}\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "a187dfb2", - "metadata": { - "editable": true - }, - "source": [ - "where $\\beta_1$ and $\\beta_2$ set the memory lifetime of the first and\n", - "second moment and are typically taken to be $0.9$ and $0.99$\n", - "respectively, and $\\eta$ and $\\epsilon$ are identical to RMSprop.\n", - "\n", - "Like in RMSprop, the effective step size of a parameter depends on the\n", - "magnitude of its gradient squared. To understand this better, let us\n", - "rewrite this expression in terms of the variance\n", - "$\\boldsymbol{\\sigma}_t^2 = \\boldsymbol{\\mathbf{s}}_t -\n", - "(\\boldsymbol{\\mathbf{m}}_t)^2$. Consider a single parameter $\\theta_t$. The\n", - "update rule for this parameter is given by" - ] - }, - { - "cell_type": "markdown", - "id": "832cc99c", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\Delta \\theta_{t+1}= -\\eta_t { \\boldsymbol{m}_t \\over \\sqrt{\\sigma_t^2 + m_t^2 }+\\epsilon}.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "b1a24342", - "metadata": { - "editable": true - }, - "source": [ - "## Algorithms and codes for Adagrad, RMSprop and Adam\n", - "\n", - "The algorithms we have implemented are well described in the text by [Goodfellow, Bengio and Courville, chapter 8](https://www.deeplearningbook.org/contents/optimization.html).\n", - "\n", - "The codes which implement these algorithms are discussed after our presentation of automatic differentiation." - ] - }, - { - "cell_type": "markdown", - "id": "8a97509f", - "metadata": { - "editable": true - }, - "source": [ - "## Practical tips\n", - "\n", - "* **Randomize the data when making mini-batches**. It is always important to randomly shuffle the data when forming mini-batches. Otherwise, the gradient descent method can fit spurious correlations resulting from the order in which data is presented.\n", - "\n", - "* **Transform your inputs**. Learning becomes difficult when our landscape has a mixture of steep and flat directions. One simple trick for minimizing these situations is to standardize the data by subtracting the mean and normalizing the variance of input variables. Whenever possible, also decorrelate the inputs. To understand why this is helpful, consider the case of linear regression. It is easy to show that for the squared error cost function, the Hessian of the cost function is just the correlation matrix between the inputs. Thus, by standardizing the inputs, we are ensuring that the landscape looks homogeneous in all directions in parameter space. Since most deep networks can be viewed as linear transformations followed by a non-linearity at each layer, we expect this intuition to hold beyond the linear case.\n", - "\n", - "* **Monitor the out-of-sample performance.** Always monitor the performance of your model on a validation set (a small portion of the training data that is held out of the training process to serve as a proxy for the test set. If the validation error starts increasing, then the model is beginning to overfit. Terminate the learning process. This *early stopping* significantly improves performance in many settings.\n", - "\n", - "* **Adaptive optimization methods don't always have good generalization.** Recent studies have shown that adaptive methods such as ADAM, RMSPorp, and AdaGrad tend to have poor generalization compared to SGD or SGD with momentum, particularly in the high-dimensional limit (i.e. the number of parameters exceeds the number of data points). Although it is not clear at this stage why these methods perform so well in training deep neural networks, simpler procedures like properly-tuned SGD may work as well or better in these applications.\n", - "\n", - "Geron's text, see chapter 11, has several interesting discussions." - ] - }, - { - "cell_type": "markdown", - "id": "631a2aa8", - "metadata": { - "editable": true - }, - "source": [ - "## Automatic differentiation\n", - "\n", - "[Automatic differentiation (AD)](https://en.wikipedia.org/wiki/Automatic_differentiation), \n", - "also called algorithmic\n", - "differentiation or computational differentiation,is a set of\n", - "techniques to numerically evaluate the derivative of a function\n", - "specified by a computer program. AD exploits the fact that every\n", - "computer program, no matter how complicated, executes a sequence of\n", - "elementary arithmetic operations (addition, subtraction,\n", - "multiplication, division, etc.) and elementary functions (exp, log,\n", - "sin, cos, etc.). By applying the chain rule repeatedly to these\n", - "operations, derivatives of arbitrary order can be computed\n", - "automatically, accurately to working precision, and using at most a\n", - "small constant factor more arithmetic operations than the original\n", - "program.\n", - "\n", - "Automatic differentiation is neither:\n", - "\n", - "* Symbolic differentiation, nor\n", - "\n", - "* Numerical differentiation (the method of finite differences).\n", - "\n", - "Symbolic differentiation can lead to inefficient code and faces the\n", - "difficulty of converting a computer program into a single expression,\n", - "while numerical differentiation can introduce round-off errors in the\n", - "discretization process and cancellation\n", - "\n", - "Python has tools for so-called **automatic differentiation**.\n", - "Consider the following example" - ] - }, - { - "cell_type": "markdown", - "id": "472b23f2", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "f(x) = \\sin\\left(2\\pi x + x^2\\right)\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "1c91c90f", - "metadata": { - "editable": true - }, - "source": [ - "which has the following derivative" - ] - }, - { - "cell_type": "markdown", - "id": "a85c6aab", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "f'(x) = \\cos\\left(2\\pi x + x^2\\right)\\left(2\\pi + 2x\\right)\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "89a0bdbb", - "metadata": { - "editable": true - }, - "source": [ - "Using **autograd** we have" - ] - }, - { - "cell_type": "code", - "execution_count": 15, - "id": "6fe48a50", - "metadata": { - "collapsed": false, - "editable": true - }, - "outputs": [], - "source": [ - "import autograd.numpy as np\n", - "\n", - "# To do elementwise differentiation:\n", - "from autograd import elementwise_grad as egrad \n", - "\n", - "# To plot:\n", - "import matplotlib.pyplot as plt \n", - "\n", - "\n", - "def f(x):\n", - " return np.sin(2*np.pi*x + x**2)\n", - "\n", - "def f_grad_analytic(x):\n", - " return np.cos(2*np.pi*x + x**2)*(2*np.pi + 2*x)\n", - "\n", - "# Do the comparison:\n", - "x = np.linspace(0,1,1000)\n", - "\n", - "f_grad = egrad(f)\n", - "\n", - "computed = f_grad(x)\n", - "analytic = f_grad_analytic(x)\n", - "\n", - "plt.title('Derivative computed from Autograd compared with the analytical derivative')\n", - "plt.plot(x,computed,label='autograd')\n", - "plt.plot(x,analytic,label='analytic')\n", - "\n", - "plt.xlabel('x')\n", - "plt.ylabel('y')\n", - "plt.legend()\n", - "\n", - "plt.show()\n", - "\n", - "print(\"The max absolute difference is: %g\"%(np.max(np.abs(computed - analytic))))" - ] - }, - { - "cell_type": "markdown", - "id": "cab7d753", - "metadata": { - "editable": true - }, - "source": [ - "## Using autograd\n", - "\n", - "Here we\n", - "experiment with what kind of functions Autograd is capable\n", - "of finding the gradient of. The following Python functions are just\n", - "meant to illustrate what Autograd can do, but please feel free to\n", - "experiment with other, possibly more complicated, functions as well." - ] - }, - { - "cell_type": "code", - "execution_count": 16, - "id": "ca4d6b32", - "metadata": { - "collapsed": false, - "editable": true - }, - "outputs": [], - "source": [ - "import autograd.numpy as np\n", - "from autograd import grad\n", - "\n", - "def f1(x):\n", - " return x**3 + 1\n", - "\n", - "f1_grad = grad(f1)\n", - "\n", - "# Remember to send in float as argument to the computed gradient from Autograd!\n", - "a = 1.0\n", - "\n", - "# See the evaluated gradient at a using autograd:\n", - "print(\"The gradient of f1 evaluated at a = %g using autograd is: %g\"%(a,f1_grad(a)))\n", - "\n", - "# Compare with the analytical derivative, that is f1'(x) = 3*x**2 \n", - "grad_analytical = 3*a**2\n", - "print(\"The gradient of f1 evaluated at a = %g by finding the analytic expression is: %g\"%(a,grad_analytical))" - ] - }, - { - "cell_type": "markdown", - "id": "4a748513", - "metadata": { - "editable": true - }, - "source": [ - "## Autograd with more complicated functions\n", - "\n", - "To differentiate with respect to two (or more) arguments of a Python\n", - "function, Autograd need to know at which variable the function if\n", - "being differentiated with respect to." - ] - }, - { - "cell_type": "code", - "execution_count": 17, - "id": "f235cd43", - "metadata": { - "collapsed": false, - "editable": true - }, - "outputs": [], - "source": [ - "import autograd.numpy as np\n", - "from autograd import grad\n", - "def f2(x1,x2):\n", - " return 3*x1**3 + x2*(x1 - 5) + 1\n", - "\n", - "# By sending the argument 0, Autograd will compute the derivative w.r.t the first variable, in this case x1\n", - "f2_grad_x1 = grad(f2,0)\n", - "\n", - "# ... and differentiate w.r.t x2 by sending 1 as an additional arugment to grad\n", - "f2_grad_x2 = grad(f2,1)\n", - "\n", - "x1 = 1.0\n", - "x2 = 3.0 \n", - "\n", - "print(\"Evaluating at x1 = %g, x2 = %g\"%(x1,x2))\n", - "print(\"-\"*30)\n", - "\n", - "# Compare with the analytical derivatives:\n", - "\n", - "# Derivative of f2 w.r.t x1 is: 9*x1**2 + x2:\n", - "f2_grad_x1_analytical = 9*x1**2 + x2\n", - "\n", - "# Derivative of f2 w.r.t x2 is: x1 - 5:\n", - "f2_grad_x2_analytical = x1 - 5\n", - "\n", - "# See the evaluated derivations:\n", - "print(\"The derivative of f2 w.r.t x1: %g\"%( f2_grad_x1(x1,x2) ))\n", - "print(\"The analytical derivative of f2 w.r.t x1: %g\"%( f2_grad_x1(x1,x2) ))\n", - "\n", - "print()\n", - "\n", - "print(\"The derivative of f2 w.r.t x2: %g\"%( f2_grad_x2(x1,x2) ))\n", - "print(\"The analytical derivative of f2 w.r.t x2: %g\"%( f2_grad_x2(x1,x2) ))" - ] - }, - { - "cell_type": "markdown", - "id": "5d8df033", - "metadata": { - "editable": true - }, - "source": [ - "Note that the grad function will not produce the true gradient of the function. The true gradient of a function with two or more variables will produce a vector, where each element is the function differentiated w.r.t a variable." - ] - }, - { - "cell_type": "markdown", - "id": "2f7de144", - "metadata": { - "editable": true - }, - "source": [ - "## More complicated functions using the elements of their arguments directly" - ] - }, - { - "cell_type": "code", - "execution_count": 18, - "id": "a2ed8fd6", - "metadata": { - "collapsed": false, - "editable": true - }, - "outputs": [], - "source": [ - "import autograd.numpy as np\n", - "from autograd import grad\n", - "def f3(x): # Assumes x is an array of length 5 or higher\n", - " return 2*x[0] + 3*x[1] + 5*x[2] + 7*x[3] + 11*x[4]**2\n", - "\n", - "f3_grad = grad(f3)\n", - "\n", - "x = np.linspace(0,4,5)\n", - "\n", - "# Print the computed gradient:\n", - "print(\"The computed gradient of f3 is: \", f3_grad(x))\n", - "\n", - "# The analytical gradient is: (2, 3, 5, 7, 22*x[4])\n", - "f3_grad_analytical = np.array([2, 3, 5, 7, 22*x[4]])\n", - "\n", - "# Print the analytical gradient:\n", - "print(\"The analytical gradient of f3 is: \", f3_grad_analytical)" - ] - }, - { - "cell_type": "markdown", - "id": "1f633736", - "metadata": { - "editable": true - }, - "source": [ - "Note that in this case, when sending an array as input argument, the\n", - "output from Autograd is another array. This is the true gradient of\n", - "the function, as opposed to the function in the previous example. By\n", - "using arrays to represent the variables, the output from Autograd\n", - "might be easier to work with, as the output is closer to what one\n", - "could expect form a gradient-evaluting function." - ] - }, - { - "cell_type": "markdown", - "id": "a73225d4", - "metadata": { - "editable": true - }, - "source": [ - "## Functions using mathematical functions from Numpy" - ] - }, - { - "cell_type": "code", - "execution_count": 19, - "id": "39059d20", - "metadata": { - "collapsed": false, - "editable": true - }, - "outputs": [], - "source": [ - "import autograd.numpy as np\n", - "from autograd import grad\n", - "def f4(x):\n", - " return np.sqrt(1+x**2) + np.exp(x) + np.sin(2*np.pi*x)\n", - "\n", - "f4_grad = grad(f4)\n", - "\n", - "x = 2.7\n", - "\n", - "# Print the computed derivative:\n", - "print(\"The computed derivative of f4 at x = %g is: %g\"%(x,f4_grad(x)))\n", - "\n", - "# The analytical derivative is: x/sqrt(1 + x**2) + exp(x) + cos(2*pi*x)*2*pi\n", - "f4_grad_analytical = x/np.sqrt(1 + x**2) + np.exp(x) + np.cos(2*np.pi*x)*2*np.pi\n", - "\n", - "# Print the analytical gradient:\n", - "print(\"The analytical gradient of f4 at x = %g is: %g\"%(x,f4_grad_analytical))" - ] - }, - { - "cell_type": "markdown", - "id": "d147b69e", - "metadata": { - "editable": true - }, - "source": [ - "## More autograd" - ] - }, - { - "cell_type": "code", - "execution_count": 20, - "id": "90a2d143", - "metadata": { - "collapsed": false, - "editable": true - }, - "outputs": [], - "source": [ - "import autograd.numpy as np\n", - "from autograd import grad\n", - "def f5(x):\n", - " if x >= 0:\n", - " return x**2\n", - " else:\n", - " return -3*x + 1\n", - "\n", - "f5_grad = grad(f5)\n", - "\n", - "x = 2.7\n", - "\n", - "# Print the computed derivative:\n", - "print(\"The computed derivative of f5 at x = %g is: %g\"%(x,f5_grad(x)))" - ] - }, - { - "cell_type": "markdown", - "id": "6655faec", - "metadata": { - "editable": true - }, - "source": [ - "## And with loops" - ] - }, - { - "cell_type": "code", - "execution_count": 21, - "id": "639ea2a9", - "metadata": { - "collapsed": false, - "editable": true - }, - "outputs": [], - "source": [ - "import autograd.numpy as np\n", - "from autograd import grad\n", - "def f6_for(x):\n", - " val = 0\n", - " for i in range(10):\n", - " val = val + x**i\n", - " return val\n", - "\n", - "def f6_while(x):\n", - " val = 0\n", - " i = 0\n", - " while i < 10:\n", - " val = val + x**i\n", - " i = i + 1\n", - " return val\n", - "\n", - "f6_for_grad = grad(f6_for)\n", - "f6_while_grad = grad(f6_while)\n", - "\n", - "x = 0.5\n", - "\n", - "# Print the computed derivaties of f6_for and f6_while\n", - "print(\"The computed derivative of f6_for at x = %g is: %g\"%(x,f6_for_grad(x)))\n", - "print(\"The computed derivative of f6_while at x = %g is: %g\"%(x,f6_while_grad(x)))" - ] - }, - { - "cell_type": "code", - "execution_count": 22, - "id": "a53c5633", - "metadata": { - "collapsed": false, - "editable": true - }, - "outputs": [], - "source": [ - "import autograd.numpy as np\n", - "from autograd import grad\n", - "# Both of the functions are implementation of the sum: sum(x**i) for i = 0, ..., 9\n", - "# The analytical derivative is: sum(i*x**(i-1)) \n", - "f6_grad_analytical = 0\n", - "for i in range(10):\n", - " f6_grad_analytical += i*x**(i-1)\n", - "\n", - "print(\"The analytical derivative of f6 at x = %g is: %g\"%(x,f6_grad_analytical))" - ] - }, - { - "cell_type": "markdown", - "id": "be5e41d4", - "metadata": { - "editable": true - }, - "source": [ - "## Using recursion" - ] - }, - { - "cell_type": "code", - "execution_count": 23, - "id": "786e19d0", - "metadata": { - "collapsed": false, - "editable": true - }, - "outputs": [], - "source": [ - "import autograd.numpy as np\n", - "from autograd import grad\n", - "\n", - "def f7(n): # Assume that n is an integer\n", - " if n == 1 or n == 0:\n", - " return 1\n", - " else:\n", - " return n*f7(n-1)\n", - "\n", - "f7_grad = grad(f7)\n", - "\n", - "n = 2.0\n", - "\n", - "print(\"The computed derivative of f7 at n = %d is: %g\"%(n,f7_grad(n)))\n", - "\n", - "# The function f7 is an implementation of the factorial of n.\n", - "# By using the product rule, one can find that the derivative is:\n", - "\n", - "f7_grad_analytical = 0\n", - "for i in range(int(n)-1):\n", - " tmp = 1\n", - " for k in range(int(n)-1):\n", - " if k != i:\n", - " tmp *= (n - k)\n", - " f7_grad_analytical += tmp\n", - "\n", - "print(\"The analytical derivative of f7 at n = %d is: %g\"%(n,f7_grad_analytical))" - ] - }, - { - "cell_type": "markdown", - "id": "114e7e25", - "metadata": { - "editable": true - }, - "source": [ - "Note that if n is equal to zero or one, Autograd will give an error message. This message appears when the output is independent on input." - ] - }, - { - "cell_type": "markdown", - "id": "24c8ffa6", - "metadata": { - "editable": true - }, - "source": [ - "## Unsupported functions\n", - "Autograd supports many features. However, there are some functions that is not supported (yet) by Autograd.\n", - "\n", - "Assigning a value to the variable being differentiated with respect to" - ] - }, - { - "cell_type": "code", - "execution_count": 24, - "id": "59f521ac", - "metadata": { - "collapsed": false, - "editable": true - }, - "outputs": [], - "source": [ - "import autograd.numpy as np\n", - "from autograd import grad\n", - "def f8(x): # Assume x is an array\n", - " x[2] = 3\n", - " return x*2\n", - "\n", - "f8_grad = grad(f8)\n", - "\n", - "x = 8.4\n", - "\n", - "print(\"The derivative of f8 is:\",f8_grad(x))" - ] - }, - { - "cell_type": "markdown", - "id": "686c34bb", - "metadata": { - "editable": true - }, - "source": [ - "Here, Autograd tells us that an 'ArrayBox' does not support item assignment. The item assignment is done when the program tries to assign x[2] to the value 3. However, Autograd has implemented the computation of the derivative such that this assignment is not possible." - ] - }, - { - "cell_type": "markdown", - "id": "9b4cc4f3", - "metadata": { - "editable": true - }, - "source": [ - "## The syntax a.dot(b) when finding the dot product" - ] - }, - { - "cell_type": "code", - "execution_count": 25, - "id": "dea954af", - "metadata": { - "collapsed": false, - "editable": true - }, - "outputs": [], - "source": [ - "import autograd.numpy as np\n", - "from autograd import grad\n", - "def f9(a): # Assume a is an array with 2 elements\n", - " b = np.array([1.0,2.0])\n", - " return a.dot(b)\n", - "\n", - "f9_grad = grad(f9)\n", - "\n", - "x = np.array([1.0,0.0])\n", - "\n", - "print(\"The derivative of f9 is:\",f9_grad(x))" - ] - }, - { - "cell_type": "markdown", - "id": "9732d039", - "metadata": { - "editable": true - }, - "source": [ - "Here we are told that the 'dot' function does not belong to Autograd's\n", - "version of a Numpy array. To overcome this, an alternative syntax\n", - "which also computed the dot product can be used:" - ] - }, - { - "cell_type": "code", - "execution_count": 26, - "id": "f580c6a1", - "metadata": { - "collapsed": false, - "editable": true - }, - "outputs": [], - "source": [ - "import autograd.numpy as np\n", - "from autograd import grad\n", - "def f9_alternative(x): # Assume a is an array with 2 elements\n", - " b = np.array([1.0,2.0])\n", - " return np.dot(x,b) # The same as x_1*b_1 + x_2*b_2\n", - "\n", - "f9_alternative_grad = grad(f9_alternative)\n", - "\n", - "x = np.array([3.0,0.0])\n", - "\n", - "print(\"The gradient of f9 is:\",f9_alternative_grad(x))\n", - "\n", - "# The analytical gradient of the dot product of vectors x and b with two elements (x_1,x_2) and (b_1, b_2) respectively\n", - "# w.r.t x is (b_1, b_2)." - ] - }, - { - "cell_type": "markdown", - "id": "d8714004", - "metadata": { - "editable": true - }, - "source": [ - "## Recommended to avoid\n", - "The documentation recommends to avoid inplace operations such as" - ] - }, - { - "cell_type": "code", - "execution_count": 27, - "id": "e56cbb47", - "metadata": { - "collapsed": false, - "editable": true - }, - "outputs": [], - "source": [ - "a += b\n", - "a -= b\n", - "a*= b\n", - "a /=b" - ] - }, - { - "cell_type": "markdown", - "id": "fac1a7da", - "metadata": { - "editable": true - }, - "source": [ - "## Using Autograd with OLS\n", - "\n", - "We conclude the part on optmization by showing how we can make codes\n", - "for linear regression and logistic regression using **autograd**. The\n", - "first example shows results with ordinary leats squares." - ] - }, - { - "cell_type": "code", - "execution_count": 28, - "id": "c4c5b9c0", - "metadata": { - "collapsed": false, - "editable": true - }, - "outputs": [], - "source": [ - "# Using Autograd to calculate gradients for OLS\n", - "from random import random, seed\n", - "import numpy as np\n", - "import autograd.numpy as np\n", - "import matplotlib.pyplot as plt\n", - "from autograd import grad\n", - "\n", - "def CostOLS(beta):\n", - " return (1.0/n)*np.sum((y-X @ beta)**2)\n", - "\n", - "n = 100\n", - "x = 2*np.random.rand(n,1)\n", - "y = 4+3*x+np.random.randn(n,1)\n", - "\n", - "X = np.c_[np.ones((n,1)), x]\n", - "XT_X = X.T @ X\n", - "theta_linreg = np.linalg.pinv(XT_X) @ (X.T @ y)\n", - "print(\"Own inversion\")\n", - "print(theta_linreg)\n", - "# Hessian matrix\n", - "H = (2.0/n)* XT_X\n", - "EigValues, EigVectors = np.linalg.eig(H)\n", - "print(f\"Eigenvalues of Hessian Matrix:{EigValues}\")\n", - "\n", - "theta = np.random.randn(2,1)\n", - "eta = 1.0/np.max(EigValues)\n", - "Niterations = 1000\n", - "# define the gradient\n", - "training_gradient = grad(CostOLS)\n", - "\n", - "for iter in range(Niterations):\n", - " gradients = training_gradient(theta)\n", - " theta -= eta*gradients\n", - "print(\"theta from own gd\")\n", - "print(theta)\n", - "\n", - "xnew = np.array([[0],[2]])\n", - "Xnew = np.c_[np.ones((2,1)), xnew]\n", - "ypredict = Xnew.dot(theta)\n", - "ypredict2 = Xnew.dot(theta_linreg)\n", - "\n", - "plt.plot(xnew, ypredict, \"r-\")\n", - "plt.plot(xnew, ypredict2, \"b-\")\n", - "plt.plot(x, y ,'ro')\n", - "plt.axis([0,2.0,0, 15.0])\n", - "plt.xlabel(r'$x$')\n", - "plt.ylabel(r'$y$')\n", - "plt.title(r'Random numbers ')\n", - "plt.show()" - ] - }, - { - "cell_type": "markdown", - "id": "b16d7700", - "metadata": { - "editable": true - }, - "source": [ - "## Same code but now with momentum gradient descent" - ] - }, - { - "cell_type": "code", - "execution_count": 29, - "id": "7453efe5", - "metadata": { - "collapsed": false, - "editable": true - }, - "outputs": [], - "source": [ - "# Using Autograd to calculate gradients for OLS\n", - "from random import random, seed\n", - "import numpy as np\n", - "import autograd.numpy as np\n", - "import matplotlib.pyplot as plt\n", - "from autograd import grad\n", - "\n", - "def CostOLS(beta):\n", - " return (1.0/n)*np.sum((y-X @ beta)**2)\n", - "\n", - "n = 100\n", - "x = 2*np.random.rand(n,1)\n", - "y = 4+3*x#+np.random.randn(n,1)\n", - "\n", - "X = np.c_[np.ones((n,1)), x]\n", - "XT_X = X.T @ X\n", - "theta_linreg = np.linalg.pinv(XT_X) @ (X.T @ y)\n", - "print(\"Own inversion\")\n", - "print(theta_linreg)\n", - "# Hessian matrix\n", - "H = (2.0/n)* XT_X\n", - "EigValues, EigVectors = np.linalg.eig(H)\n", - "print(f\"Eigenvalues of Hessian Matrix:{EigValues}\")\n", - "\n", - "theta = np.random.randn(2,1)\n", - "eta = 1.0/np.max(EigValues)\n", - "Niterations = 30\n", - "\n", - "# define the gradient\n", - "training_gradient = grad(CostOLS)\n", - "\n", - "for iter in range(Niterations):\n", - " gradients = training_gradient(theta)\n", - " theta -= eta*gradients\n", - " print(iter,gradients[0],gradients[1])\n", - "print(\"theta from own gd\")\n", - "print(theta)\n", - "\n", - "# Now improve with momentum gradient descent\n", - "change = 0.0\n", - "delta_momentum = 0.3\n", - "for iter in range(Niterations):\n", - " # calculate gradient\n", - " gradients = training_gradient(theta)\n", - " # calculate update\n", - " new_change = eta*gradients+delta_momentum*change\n", - " # take a step\n", - " theta -= new_change\n", - " # save the change\n", - " change = new_change\n", - " print(iter,gradients[0],gradients[1])\n", - "print(\"theta from own gd wth momentum\")\n", - "print(theta)" - ] - }, - { - "cell_type": "markdown", - "id": "0a417277", - "metadata": { - "editable": true - }, - "source": [ - "## But noen of these can compete with Newton's method" - ] - }, - { - "cell_type": "code", - "execution_count": 30, - "id": "1a541fef", - "metadata": { - "collapsed": false, - "editable": true - }, - "outputs": [], - "source": [ - "# Using Newton's method\n", - "from random import random, seed\n", - "import numpy as np\n", - "import autograd.numpy as np\n", - "import matplotlib.pyplot as plt\n", - "from autograd import grad\n", - "\n", - "def CostOLS(beta):\n", - " return (1.0/n)*np.sum((y-X @ beta)**2)\n", - "\n", - "n = 100\n", - "x = 2*np.random.rand(n,1)\n", - "y = 4+3*x+np.random.randn(n,1)\n", - "\n", - "X = np.c_[np.ones((n,1)), x]\n", - "XT_X = X.T @ X\n", - "beta_linreg = np.linalg.pinv(XT_X) @ (X.T @ y)\n", - "print(\"Own inversion\")\n", - "print(beta_linreg)\n", - "# Hessian matrix\n", - "H = (2.0/n)* XT_X\n", - "# Note that here the Hessian does not depend on the parameters beta\n", - "invH = np.linalg.pinv(H)\n", - "EigValues, EigVectors = np.linalg.eig(H)\n", - "print(f\"Eigenvalues of Hessian Matrix:{EigValues}\")\n", - "\n", - "beta = np.random.randn(2,1)\n", - "Niterations = 5\n", - "\n", - "# define the gradient\n", - "training_gradient = grad(CostOLS)\n", - "\n", - "for iter in range(Niterations):\n", - " gradients = training_gradient(beta)\n", - " beta -= invH @ gradients\n", - " print(iter,gradients[0],gradients[1])\n", - "print(\"beta from own Newton code\")\n", - "print(beta)" - ] - }, - { - "cell_type": "markdown", - "id": "9e937e4f", - "metadata": { - "editable": true - }, - "source": [ - "## Including Stochastic Gradient Descent with Autograd\n", - "In this code we include the stochastic gradient descent approach discussed above. Note here that we specify which argument we are taking the derivative with respect to when using **autograd**." - ] - }, - { - "cell_type": "code", - "execution_count": 31, - "id": "9afef100", - "metadata": { - "collapsed": false, - "editable": true - }, - "outputs": [], - "source": [ - "# Using Autograd to calculate gradients using SGD\n", - "# OLS example\n", - "from random import random, seed\n", - "import numpy as np\n", - "import autograd.numpy as np\n", - "import matplotlib.pyplot as plt\n", - "from autograd import grad\n", - "\n", - "# Note change from previous example\n", - "def CostOLS(y,X,theta):\n", - " return np.sum((y-X @ theta)**2)\n", - "\n", - "n = 100\n", - "x = 2*np.random.rand(n,1)\n", - "y = 4+3*x+np.random.randn(n,1)\n", - "\n", - "X = np.c_[np.ones((n,1)), x]\n", - "XT_X = X.T @ X\n", - "theta_linreg = np.linalg.pinv(XT_X) @ (X.T @ y)\n", - "print(\"Own inversion\")\n", - "print(theta_linreg)\n", - "# Hessian matrix\n", - "H = (2.0/n)* XT_X\n", - "EigValues, EigVectors = np.linalg.eig(H)\n", - "print(f\"Eigenvalues of Hessian Matrix:{EigValues}\")\n", - "\n", - "theta = np.random.randn(2,1)\n", - "eta = 1.0/np.max(EigValues)\n", - "Niterations = 1000\n", - "\n", - "# Note that we request the derivative wrt third argument (theta, 2 here)\n", - "training_gradient = grad(CostOLS,2)\n", - "\n", - "for iter in range(Niterations):\n", - " gradients = (1.0/n)*training_gradient(y, X, theta)\n", - " theta -= eta*gradients\n", - "print(\"theta from own gd\")\n", - "print(theta)\n", - "\n", - "xnew = np.array([[0],[2]])\n", - "Xnew = np.c_[np.ones((2,1)), xnew]\n", - "ypredict = Xnew.dot(theta)\n", - "ypredict2 = Xnew.dot(theta_linreg)\n", - "\n", - "plt.plot(xnew, ypredict, \"r-\")\n", - "plt.plot(xnew, ypredict2, \"b-\")\n", - "plt.plot(x, y ,'ro')\n", - "plt.axis([0,2.0,0, 15.0])\n", - "plt.xlabel(r'$x$')\n", - "plt.ylabel(r'$y$')\n", - "plt.title(r'Random numbers ')\n", - "plt.show()\n", - "\n", - "n_epochs = 50\n", - "M = 5 #size of each minibatch\n", - "m = int(n/M) #number of minibatches\n", - "t0, t1 = 5, 50\n", - "def learning_schedule(t):\n", - " return t0/(t+t1)\n", - "\n", - "theta = np.random.randn(2,1)\n", - "\n", - "for epoch in range(n_epochs):\n", - "# Can you figure out a better way of setting up the contributions to each batch?\n", - " for i in range(m):\n", - " random_index = M*np.random.randint(m)\n", - " xi = X[random_index:random_index+M]\n", - " yi = y[random_index:random_index+M]\n", - " gradients = (1.0/M)*training_gradient(yi, xi, theta)\n", - " eta = learning_schedule(epoch*m+i)\n", - " theta = theta - eta*gradients\n", - "print(\"theta from own sdg\")\n", - "print(theta)" - ] - }, - { - "cell_type": "markdown", - "id": "2a7e982c", - "metadata": { - "editable": true - }, - "source": [ - "## Same code but now with momentum gradient descent" - ] - }, - { - "cell_type": "code", - "execution_count": 32, - "id": "91311a17", - "metadata": { - "collapsed": false, - "editable": true - }, - "outputs": [], - "source": [ - "# Using Autograd to calculate gradients using SGD\n", - "# OLS example\n", - "from random import random, seed\n", - "import numpy as np\n", - "import autograd.numpy as np\n", - "import matplotlib.pyplot as plt\n", - "from autograd import grad\n", - "\n", - "# Note change from previous example\n", - "def CostOLS(y,X,theta):\n", - " return np.sum((y-X @ theta)**2)\n", - "\n", - "n = 100\n", - "x = 2*np.random.rand(n,1)\n", - "y = 4+3*x+np.random.randn(n,1)\n", - "\n", - "X = np.c_[np.ones((n,1)), x]\n", - "XT_X = X.T @ X\n", - "theta_linreg = np.linalg.pinv(XT_X) @ (X.T @ y)\n", - "print(\"Own inversion\")\n", - "print(theta_linreg)\n", - "# Hessian matrix\n", - "H = (2.0/n)* XT_X\n", - "EigValues, EigVectors = np.linalg.eig(H)\n", - "print(f\"Eigenvalues of Hessian Matrix:{EigValues}\")\n", - "\n", - "theta = np.random.randn(2,1)\n", - "eta = 1.0/np.max(EigValues)\n", - "Niterations = 100\n", - "\n", - "# Note that we request the derivative wrt third argument (theta, 2 here)\n", - "training_gradient = grad(CostOLS,2)\n", - "\n", - "for iter in range(Niterations):\n", - " gradients = (1.0/n)*training_gradient(y, X, theta)\n", - " theta -= eta*gradients\n", - "print(\"theta from own gd\")\n", - "print(theta)\n", - "\n", - "\n", - "n_epochs = 50\n", - "M = 5 #size of each minibatch\n", - "m = int(n/M) #number of minibatches\n", - "t0, t1 = 5, 50\n", - "def learning_schedule(t):\n", - " return t0/(t+t1)\n", - "\n", - "theta = np.random.randn(2,1)\n", - "\n", - "change = 0.0\n", - "delta_momentum = 0.3\n", - "\n", - "for epoch in range(n_epochs):\n", - " for i in range(m):\n", - " random_index = M*np.random.randint(m)\n", - " xi = X[random_index:random_index+M]\n", - " yi = y[random_index:random_index+M]\n", - " gradients = (1.0/M)*training_gradient(yi, xi, theta)\n", - " eta = learning_schedule(epoch*m+i)\n", - " # calculate update\n", - " new_change = eta*gradients+delta_momentum*change\n", - " # take a step\n", - " theta -= new_change\n", - " # save the change\n", - " change = new_change\n", - "print(\"theta from own sdg with momentum\")\n", - "print(theta)" - ] - }, - { - "cell_type": "markdown", - "id": "516999d8", - "metadata": { - "editable": true - }, - "source": [ - "## Similar (second order function now) problem but now with AdaGrad" - ] - }, - { - "cell_type": "code", - "execution_count": 33, - "id": "e8292719", - "metadata": { - "collapsed": false, - "editable": true - }, - "outputs": [], - "source": [ - "# Using Autograd to calculate gradients using AdaGrad and Stochastic Gradient descent\n", - "# OLS example\n", - "from random import random, seed\n", - "import numpy as np\n", - "import autograd.numpy as np\n", - "import matplotlib.pyplot as plt\n", - "from autograd import grad\n", - "\n", - "# Note change from previous example\n", - "def CostOLS(y,X,theta):\n", - " return np.sum((y-X @ theta)**2)\n", - "\n", - "n = 1000\n", - "x = np.random.rand(n,1)\n", - "y = 2.0+3*x +4*x*x\n", - "\n", - "X = np.c_[np.ones((n,1)), x, x*x]\n", - "XT_X = X.T @ X\n", - "theta_linreg = np.linalg.pinv(XT_X) @ (X.T @ y)\n", - "print(\"Own inversion\")\n", - "print(theta_linreg)\n", - "\n", - "\n", - "# Note that we request the derivative wrt third argument (theta, 2 here)\n", - "training_gradient = grad(CostOLS,2)\n", - "# Define parameters for Stochastic Gradient Descent\n", - "n_epochs = 50\n", - "M = 5 #size of each minibatch\n", - "m = int(n/M) #number of minibatches\n", - "# Guess for unknown parameters theta\n", - "theta = np.random.randn(3,1)\n", - "\n", - "# Value for learning rate\n", - "eta = 0.01\n", - "# Including AdaGrad parameter to avoid possible division by zero\n", - "delta = 1e-8\n", - "for epoch in range(n_epochs):\n", - " Giter = 0.0\n", - " for i in range(m):\n", - " random_index = M*np.random.randint(m)\n", - " xi = X[random_index:random_index+M]\n", - " yi = y[random_index:random_index+M]\n", - " gradients = (1.0/M)*training_gradient(yi, xi, theta)\n", - " Giter += gradients*gradients\n", - " update = gradients*eta/(delta+np.sqrt(Giter))\n", - " theta -= update\n", - "print(\"theta from own AdaGrad\")\n", - "print(theta)" - ] - }, - { - "cell_type": "markdown", - "id": "bd67f5cb", - "metadata": { - "editable": true - }, - "source": [ - "Running this code we note an almost perfect agreement with the results from matrix inversion." - ] - }, - { - "cell_type": "markdown", - "id": "eb0d5fd0", - "metadata": { - "editable": true - }, - "source": [ - "## RMSprop for adaptive learning rate with Stochastic Gradient Descent" - ] - }, - { - "cell_type": "code", - "execution_count": 34, - "id": "d2eb93d1", - "metadata": { - "collapsed": false, - "editable": true - }, - "outputs": [], - "source": [ - "# Using Autograd to calculate gradients using RMSprop and Stochastic Gradient descent\n", - "# OLS example\n", - "from random import random, seed\n", - "import numpy as np\n", - "import autograd.numpy as np\n", - "import matplotlib.pyplot as plt\n", - "from autograd import grad\n", - "\n", - "# Note change from previous example\n", - "def CostOLS(y,X,theta):\n", - " return np.sum((y-X @ theta)**2)\n", - "\n", - "n = 1000\n", - "x = np.random.rand(n,1)\n", - "y = 2.0+3*x +4*x*x# +np.random.randn(n,1)\n", - "\n", - "X = np.c_[np.ones((n,1)), x, x*x]\n", - "XT_X = X.T @ X\n", - "theta_linreg = np.linalg.pinv(XT_X) @ (X.T @ y)\n", - "print(\"Own inversion\")\n", - "print(theta_linreg)\n", - "\n", - "\n", - "# Note that we request the derivative wrt third argument (theta, 2 here)\n", - "training_gradient = grad(CostOLS,2)\n", - "# Define parameters for Stochastic Gradient Descent\n", - "n_epochs = 50\n", - "M = 5 #size of each minibatch\n", - "m = int(n/M) #number of minibatches\n", - "# Guess for unknown parameters theta\n", - "theta = np.random.randn(3,1)\n", - "\n", - "# Value for learning rate\n", - "eta = 0.01\n", - "# Value for parameter rho\n", - "rho = 0.99\n", - "# Including AdaGrad parameter to avoid possible division by zero\n", - "delta = 1e-8\n", - "for epoch in range(n_epochs):\n", - " Giter = 0.0\n", - " for i in range(m):\n", - " random_index = M*np.random.randint(m)\n", - " xi = X[random_index:random_index+M]\n", - " yi = y[random_index:random_index+M]\n", - " gradients = (1.0/M)*training_gradient(yi, xi, theta)\n", - "\t# Accumulated gradient\n", - "\t# Scaling with rho the new and the previous results\n", - " Giter = (rho*Giter+(1-rho)*gradients*gradients)\n", - "\t# Taking the diagonal only and inverting\n", - " update = gradients*eta/(delta+np.sqrt(Giter))\n", - "\t# Hadamard product\n", - " theta -= update\n", - "print(\"theta from own RMSprop\")\n", - "print(theta)" - ] - }, - { - "cell_type": "markdown", - "id": "669b56c2", - "metadata": { - "editable": true - }, - "source": [ - "## And finally [ADAM](https://arxiv.org/pdf/1412.6980.pdf)" - ] - }, - { - "cell_type": "code", - "execution_count": 35, - "id": "bb3f553d", - "metadata": { - "collapsed": false, - "editable": true - }, - "outputs": [], - "source": [ - "# Using Autograd to calculate gradients using RMSprop and Stochastic Gradient descent\n", - "# OLS example\n", - "from random import random, seed\n", - "import numpy as np\n", - "import autograd.numpy as np\n", - "import matplotlib.pyplot as plt\n", - "from autograd import grad\n", - "\n", - "# Note change from previous example\n", - "def CostOLS(y,X,theta):\n", - " return np.sum((y-X @ theta)**2)\n", - "\n", - "n = 1000\n", - "x = np.random.rand(n,1)\n", - "y = 2.0+3*x +4*x*x# +np.random.randn(n,1)\n", - "\n", - "X = np.c_[np.ones((n,1)), x, x*x]\n", - "XT_X = X.T @ X\n", - "theta_linreg = np.linalg.pinv(XT_X) @ (X.T @ y)\n", - "print(\"Own inversion\")\n", - "print(theta_linreg)\n", - "\n", - "\n", - "# Note that we request the derivative wrt third argument (theta, 2 here)\n", - "training_gradient = grad(CostOLS,2)\n", - "# Define parameters for Stochastic Gradient Descent\n", - "n_epochs = 50\n", - "M = 5 #size of each minibatch\n", - "m = int(n/M) #number of minibatches\n", - "# Guess for unknown parameters theta\n", - "theta = np.random.randn(3,1)\n", - "\n", - "# Value for learning rate\n", - "eta = 0.01\n", - "# Value for parameters beta1 and beta2, see https://arxiv.org/abs/1412.6980\n", - "beta1 = 0.9\n", - "beta2 = 0.999\n", - "# Including AdaGrad parameter to avoid possible division by zero\n", - "delta = 1e-7\n", - "iter = 0\n", - "for epoch in range(n_epochs):\n", - " first_moment = 0.0\n", - " second_moment = 0.0\n", - " iter += 1\n", - " for i in range(m):\n", - " random_index = M*np.random.randint(m)\n", - " xi = X[random_index:random_index+M]\n", - " yi = y[random_index:random_index+M]\n", - " gradients = (1.0/M)*training_gradient(yi, xi, theta)\n", - " # Computing moments first\n", - " first_moment = beta1*first_moment + (1-beta1)*gradients\n", - " second_moment = beta2*second_moment+(1-beta2)*gradients*gradients\n", - " first_term = first_moment/(1.0-beta1**iter)\n", - " second_term = second_moment/(1.0-beta2**iter)\n", - "\t# Scaling with rho the new and the previous results\n", - " update = eta*first_term/(np.sqrt(second_term)+delta)\n", - " theta -= update\n", - "print(\"theta from own ADAM\")\n", - "print(theta)" - ] - }, - { - "cell_type": "markdown", - "id": "4e5c58ea", - "metadata": { - "editable": true - }, - "source": [ - "## And Logistic Regression" - ] - }, - { - "cell_type": "code", - "execution_count": 36, - "id": "1fec659e", - "metadata": { - "collapsed": false, - "editable": true - }, - "outputs": [], - "source": [ - "import autograd.numpy as np\n", - "from autograd import grad\n", - "\n", - "def sigmoid(x):\n", - " return 0.5 * (np.tanh(x / 2.) + 1)\n", - "\n", - "def logistic_predictions(weights, inputs):\n", - " # Outputs probability of a label being true according to logistic model.\n", - " return sigmoid(np.dot(inputs, weights))\n", - "\n", - "def training_loss(weights):\n", - " # Training loss is the negative log-likelihood of the training labels.\n", - " preds = logistic_predictions(weights, inputs)\n", - " label_probabilities = preds * targets + (1 - preds) * (1 - targets)\n", - " return -np.sum(np.log(label_probabilities))\n", - "\n", - "# Build a toy dataset.\n", - "inputs = np.array([[0.52, 1.12, 0.77],\n", - " [0.88, -1.08, 0.15],\n", - " [0.52, 0.06, -1.30],\n", - " [0.74, -2.49, 1.39]])\n", - "targets = np.array([True, True, False, True])\n", - "\n", - "# Define a function that returns gradients of training loss using Autograd.\n", - "training_gradient_fun = grad(training_loss)\n", - "\n", - "# Optimize weights using gradient descent.\n", - "weights = np.array([0.0, 0.0, 0.0])\n", - "print(\"Initial loss:\", training_loss(weights))\n", - "for i in range(100):\n", - " weights -= training_gradient_fun(weights) * 0.01\n", - "\n", - "print(\"Trained loss:\", training_loss(weights))" - ] - }, - { - "cell_type": "markdown", - "id": "ac14943c", - "metadata": { - "editable": true - }, - "source": [ - "## Introducing [JAX](https://jax.readthedocs.io/en/latest/)\n", - "\n", - "Presently, instead of using **autograd**, we recommend using [JAX](https://jax.readthedocs.io/en/latest/)\n", - "\n", - "**JAX** is Autograd and [XLA (Accelerated Linear Algebra))](https://www.tensorflow.org/xla),\n", - "brought together for high-performance numerical computing and machine learning research.\n", - "It provides composable transformations of Python+NumPy programs: differentiate, vectorize, parallelize, Just-In-Time compile to GPU/TPU, and more.\n", - "\n", - "Here's a simple example on how you can use **JAX** to compute the derivate of the logistic function." - ] - }, - { - "cell_type": "code", - "execution_count": 37, - "id": "57b4e540", - "metadata": { - "collapsed": false, - "editable": true - }, - "outputs": [], - "source": [ - "import jax.numpy as jnp\n", - "from jax import grad, jit, vmap\n", - "\n", - "def sum_logistic(x):\n", - " return jnp.sum(1.0 / (1.0 + jnp.exp(-x)))\n", - "\n", - "x_small = jnp.arange(3.)\n", - "derivative_fn = grad(sum_logistic)\n", - "print(derivative_fn(x_small))" - ] - } - ], - "metadata": {}, - "nbformat": 4, - "nbformat_minor": 5 -} diff --git a/doc/LectureNotes/week40.ipynb b/doc/LectureNotes/week40.ipynb deleted file mode 100644 index 70ab38246..000000000 --- a/doc/LectureNotes/week40.ipynb +++ /dev/null @@ -1,3545 +0,0 @@ -{ - "cells": [ - { - "cell_type": "markdown", - "id": "c410abdb", - "metadata": { - "editable": true - }, - "source": [ - "\n", - "" - ] - }, - { - "cell_type": "markdown", - "id": "ffdc5797", - "metadata": { - "editable": true - }, - "source": [ - "# Week 40: Gradient descent methods (continued) and start Neural networks\n", - "**Morten Hjorth-Jensen**, Department of Physics, University of Oslo, Norway and Department of Physics and Astronomy and Facility for Rare Ion Beams, Michigan State University, USA\n", - "\n", - "Date: **October 2-6, 2023**" - ] - }, - { - "cell_type": "markdown", - "id": "4bab315b", - "metadata": { - "editable": true - }, - "source": [ - "## Plans for week 40\n", - "\n", - "**Material for the active learning sessions on Tuesday and Wednesday.**\n", - "\n", - " * Work on project 1 and discussions on how to structure your report\n", - "\n", - " * No weekly exercises for week 40, project work only\n", - "\n", - " * [Video on how to write scientific reports recorded during one of the lab sessions](https://youtu.be/tVW1ZDmZnwM)\n", - "\n", - " * A general guideline can be found at .\n", - "\n", - " \n", - "\n", - "**Material for the lecture on Thursday October 5, 2023.**\n", - "\n", - " * Stochastic Gradient descent with examples and automatic differentiation\n", - "\n", - " * Neural Networks, setting up the basic steps, from the simple perceptron model to the multi-layer perceptron model. \n", - "\n", - " * Readings and Videos:\n", - "\n", - " * These lecture notes\n", - "\n", - " * For a good discussion on gradient methods, we would like to recommend Goodfellow et al section 4.3-4.5 and sections 8.3-8.6. We will come back to the latter chapter in our discussion of Neural networks as well.\n", - "\n", - " * [Aurelien Geron's chapter 4 on stochastic gradient descent](https://github.com/CompPhysics/MachineLearning/blob/master/doc/Textbooks/TensorflowML.pdf)\n", - "\n", - " * For neural networks we recommend Goodfellow et al chapter 6.\n", - "\n", - " * [Video on gradient descent](https://www.youtube.com/watch?v=sDv4f4s2SB8)\n", - "\n", - " * [Video on stochastic gradient descent](https://www.youtube.com/watch?v=vMh0zPT0tLI)\n", - "\n", - " * [Neural Networks demystified](https://www.youtube.com/watch?v=bxe2T-V8XRs&list=PLiaHhY2iBX9hdHaRr6b7XevZtgZRa1PoU&ab_channel=WelchLabs)\n", - "\n", - " * [Building Neural Networks from scratch](https://www.youtube.com/watch?v=Wo5dMEP_BbI&list=PLQVvvaa0QuDcjD5BAw2DxE6OF2tius3V3&ab_channel=sentdex)" - ] - }, - { - "cell_type": "markdown", - "id": "1ba76140", - "metadata": { - "editable": true - }, - "source": [ - "## Summary from last week, using gradient descent methods, limitations\n", - "\n", - "* **Gradient descent (GD) finds local minima of our function**. Since the GD algorithm is deterministic, if it converges, it will converge to a local minimum of our cost/loss/risk function. Because in ML we are often dealing with extremely rugged landscapes with many local minima, this can lead to poor performance.\n", - "\n", - "* **GD is sensitive to initial conditions**. One consequence of the local nature of GD is that initial conditions matter. Depending on where one starts, one will end up at a different local minima. Therefore, it is very important to think about how one initializes the training process. This is true for GD as well as more complicated variants of GD.\n", - "\n", - "* **Gradients are computationally expensive to calculate for large datasets**. In many cases in statistics and ML, the cost/loss/risk function is a sum of terms, with one term for each data point. For example, in linear regression, $E \\propto \\sum_{i=1}^n (y_i - \\mathbf{w}^T\\cdot\\mathbf{x}_i)^2$; for logistic regression, the square error is replaced by the cross entropy. To calculate the gradient we have to sum over *all* $n$ data points. Doing this at every GD step becomes extremely computationally expensive. An ingenious solution to this, is to calculate the gradients using small subsets of the data called \"mini batches\". This has the added benefit of introducing stochasticity into our algorithm.\n", - "\n", - "* **GD is very sensitive to choices of learning rates**. GD is extremely sensitive to the choice of learning rates. If the learning rate is very small, the training process take an extremely long time. For larger learning rates, GD can diverge and give poor results. Furthermore, depending on what the local landscape looks like, we have to modify the learning rates to ensure convergence. Ideally, we would *adaptively* choose the learning rates to match the landscape.\n", - "\n", - "* **GD treats all directions in parameter space uniformly.** Another major drawback of GD is that unlike Newton's method, the learning rate for GD is the same in all directions in parameter space. For this reason, the maximum learning rate is set by the behavior of the steepest direction and this can significantly slow down training. Ideally, we would like to take large steps in flat directions and small steps in steep directions. Since we are exploring rugged landscapes where curvatures change, this requires us to keep track of not only the gradient but second derivatives. The ideal scenario would be to calculate the Hessian but this proves to be too computationally expensive. \n", - "\n", - "* GD can take exponential time to escape saddle points, even with random initialization. As we mentioned, GD is extremely sensitive to initial condition since it determines the particular local minimum GD would eventually reach. However, even with a good initialization scheme, through the introduction of randomness, GD can still take exponential time to escape saddle points." - ] - }, - { - "cell_type": "markdown", - "id": "a8b56c00", - "metadata": { - "editable": true - }, - "source": [ - "## Overview video on Stochastic Gradient Descent\n", - "\n", - "[What is Stochastic Gradient Descent](https://www.youtube.com/watch?v=vMh0zPT0tLI&ab_channel=StatQuestwithJoshStarmer)" - ] - }, - { - "cell_type": "markdown", - "id": "eba32497", - "metadata": { - "editable": true - }, - "source": [ - "## Batches and mini-batches\n", - "\n", - "In gradient descent we compute the cost function and its gradient for all data points we have.\n", - "\n", - "In large-scale applications such as the [ILSVRC challenge](https://www.image-net.org/challenges/LSVRC/), the\n", - "training data can have on order of millions of examples. Hence, it\n", - "seems wasteful to compute the full cost function over the entire\n", - "training set in order to perform only a single parameter update. A\n", - "very common approach to addressing this challenge is to compute the\n", - "gradient over batches of the training data. For example, a typical batch could contain some thousand examples from\n", - "an entire training set of several millions. This batch is then used to\n", - "perform a parameter update." - ] - }, - { - "cell_type": "markdown", - "id": "55578599", - "metadata": { - "editable": true - }, - "source": [ - "## Stochastic Gradient Descent (SGD)\n", - "\n", - "In stochastic gradient descent, the extreme case is the case where we\n", - "have only one batch, that is we include the whole data set.\n", - "\n", - "This process is called Stochastic Gradient\n", - "Descent (SGD) (or also sometimes on-line gradient descent). This is\n", - "relatively less common to see because in practice due to vectorized\n", - "code optimizations it can be computationally much more efficient to\n", - "evaluate the gradient for 100 examples, than the gradient for one\n", - "example 100 times. Even though SGD technically refers to using a\n", - "single example at a time to evaluate the gradient, you will hear\n", - "people use the term SGD even when referring to mini-batch gradient\n", - "descent (i.e. mentions of MGD for “Minibatch Gradient Descent”, or BGD\n", - "for “Batch gradient descent” are rare to see), where it is usually\n", - "assumed that mini-batches are used. The size of the mini-batch is a\n", - "hyperparameter but it is not very common to cross-validate or bootstrap it. It is\n", - "usually based on memory constraints (if any), or set to some value,\n", - "e.g. 32, 64 or 128. We use powers of 2 in practice because many\n", - "vectorized operation implementations work faster when their inputs are\n", - "sized in powers of 2.\n", - "\n", - "In our notes with SGD we mean stochastic gradient descent with mini-batches." - ] - }, - { - "cell_type": "markdown", - "id": "140607b7", - "metadata": { - "editable": true - }, - "source": [ - "## Stochastic Gradient Descent\n", - "\n", - "Stochastic gradient descent (SGD) and variants thereof address some of\n", - "the shortcomings of the Gradient descent method discussed above.\n", - "\n", - "The underlying idea of SGD comes from the observation that the cost\n", - "function, which we want to minimize, can almost always be written as a\n", - "sum over $n$ data points $\\{\\mathbf{x}_i\\}_{i=1}^n$," - ] - }, - { - "cell_type": "markdown", - "id": "c1a00332", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "C(\\mathbf{\\beta}) = \\sum_{i=1}^n c_i(\\mathbf{x}_i,\n", - "\\mathbf{\\beta}).\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "2c04bdee", - "metadata": { - "editable": true - }, - "source": [ - "## Computation of gradients\n", - "\n", - "This in turn means that the gradient can be\n", - "computed as a sum over $i$-gradients" - ] - }, - { - "cell_type": "markdown", - "id": "087684a4", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\nabla_\\beta C(\\mathbf{\\beta}) = \\sum_i^n \\nabla_\\beta c_i(\\mathbf{x}_i,\n", - "\\mathbf{\\beta}).\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "e0362df4", - "metadata": { - "editable": true - }, - "source": [ - "Stochasticity/randomness is introduced by only taking the\n", - "gradient on a subset of the data called minibatches. If there are $n$\n", - "data points and the size of each minibatch is $M$, there will be $n/M$\n", - "minibatches. We denote these minibatches by $B_k$ where\n", - "$k=1,\\cdots,n/M$." - ] - }, - { - "cell_type": "markdown", - "id": "24051a4e", - "metadata": { - "editable": true - }, - "source": [ - "## SGD example\n", - "As an example, suppose we have $10$ data points $(\\mathbf{x}_1,\\cdots, \\mathbf{x}_{10})$ \n", - "and we choose to have $M=5$ minibathces,\n", - "then each minibatch contains two data points. In particular we have\n", - "$B_1 = (\\mathbf{x}_1,\\mathbf{x}_2), \\cdots, B_5 =\n", - "(\\mathbf{x}_9,\\mathbf{x}_{10})$. Note that if you choose $M=1$ you\n", - "have only a single batch with all data points and on the other extreme,\n", - "you may choose $M=n$ resulting in a minibatch for each datapoint, i.e\n", - "$B_k = \\mathbf{x}_k$.\n", - "\n", - "The idea is now to approximate the gradient by replacing the sum over\n", - "all data points with a sum over the data points in one the minibatches\n", - "picked at random in each gradient descent step" - ] - }, - { - "cell_type": "markdown", - "id": "7723f927", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\nabla_{\\beta}\n", - "C(\\mathbf{\\beta}) = \\sum_{i=1}^n \\nabla_\\beta c_i(\\mathbf{x}_i,\n", - "\\mathbf{\\beta}) \\rightarrow \\sum_{i \\in B_k}^n \\nabla_\\beta\n", - "c_i(\\mathbf{x}_i, \\mathbf{\\beta}).\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "59221981", - "metadata": { - "editable": true - }, - "source": [ - "## The gradient step\n", - "\n", - "Thus a gradient descent step now looks like" - ] - }, - { - "cell_type": "markdown", - "id": "a7d27b48", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\beta_{j+1} = \\beta_j - \\gamma_j \\sum_{i \\in B_k}^n \\nabla_\\beta c_i(\\mathbf{x}_i,\n", - "\\mathbf{\\beta})\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "c7595344", - "metadata": { - "editable": true - }, - "source": [ - "where $k$ is picked at random with equal\n", - "probability from $[1,n/M]$. An iteration over the number of\n", - "minibathces (n/M) is commonly referred to as an epoch. Thus it is\n", - "typical to choose a number of epochs and for each epoch iterate over\n", - "the number of minibatches, as exemplified in the code below." - ] - }, - { - "cell_type": "markdown", - "id": "0d7024b5", - "metadata": { - "editable": true - }, - "source": [ - "## Simple example code" - ] - }, - { - "cell_type": "code", - "execution_count": 1, - "id": "0f9dc38b", - "metadata": { - "collapsed": false, - "editable": true - }, - "outputs": [], - "source": [ - "import numpy as np \n", - "\n", - "n = 100 #100 datapoints \n", - "M = 5 #size of each minibatch\n", - "m = int(n/M) #number of minibatches\n", - "n_epochs = 10 #number of epochs\n", - "\n", - "j = 0\n", - "for epoch in range(1,n_epochs+1):\n", - " for i in range(m):\n", - " k = np.random.randint(m) #Pick the k-th minibatch at random\n", - " #Compute the gradient using the data in minibatch Bk\n", - " #Compute new suggestion for \n", - " j += 1" - ] - }, - { - "cell_type": "markdown", - "id": "df447303", - "metadata": { - "editable": true - }, - "source": [ - "Taking the gradient only on a subset of the data has two important\n", - "benefits. First, it introduces randomness which decreases the chance\n", - "that our opmization scheme gets stuck in a local minima. Second, if\n", - "the size of the minibatches are small relative to the number of\n", - "datapoints ($M < n$), the computation of the gradient is much\n", - "cheaper since we sum over the datapoints in the $k-th$ minibatch and not\n", - "all $n$ datapoints." - ] - }, - { - "cell_type": "markdown", - "id": "976aef35", - "metadata": { - "editable": true - }, - "source": [ - "## When do we stop?\n", - "\n", - "A natural question is when do we stop the search for a new minimum?\n", - "One possibility is to compute the full gradient after a given number\n", - "of epochs and check if the norm of the gradient is smaller than some\n", - "threshold and stop if true. However, the condition that the gradient\n", - "is zero is valid also for local minima, so this would only tell us\n", - "that we are close to a local/global minimum. However, we could also\n", - "evaluate the cost function at this point, store the result and\n", - "continue the search. If the test kicks in at a later stage we can\n", - "compare the values of the cost function and keep the $\\beta$ that\n", - "gave the lowest value." - ] - }, - { - "cell_type": "markdown", - "id": "0fab1ae1", - "metadata": { - "editable": true - }, - "source": [ - "## Slightly different approach\n", - "\n", - "Another approach is to let the step length $\\gamma_j$ depend on the\n", - "number of epochs in such a way that it becomes very small after a\n", - "reasonable time such that we do not move at all. Such approaches are\n", - "also called scaling. There are many such ways to [scale the learning\n", - "rate](https://towardsdatascience.com/gradient-descent-the-learning-rate-and-the-importance-of-feature-scaling-6c0b416596e1)\n", - "and [discussions here](https://www.jmlr.org/papers/volume23/20-1258/20-1258.pdf). See\n", - "also\n", - "\n", - "for a discussion of different scaling functions for the learning rate." - ] - }, - { - "cell_type": "markdown", - "id": "2db0116b", - "metadata": { - "editable": true - }, - "source": [ - "## Time decay rate\n", - "\n", - "As an example, let $e = 0,1,2,3,\\cdots$ denote the current epoch and let $t_0, t_1 > 0$ be two fixed numbers. Furthermore, let $t = e \\cdot m + i$ where $m$ is the number of minibatches and $i=0,\\cdots,m-1$. Then the function $$\\gamma_j(t; t_0, t_1) = \\frac{t_0}{t+t_1} $$ goes to zero as the number of epochs gets large. I.e. we start with a step length $\\gamma_j (0; t_0, t_1) = t_0/t_1$ which decays in *time* $t$.\n", - "\n", - "In this way we can fix the number of epochs, compute $\\beta$ and\n", - "evaluate the cost function at the end. Repeating the computation will\n", - "give a different result since the scheme is random by design. Then we\n", - "pick the final $\\beta$ that gives the lowest value of the cost\n", - "function." - ] - }, - { - "cell_type": "code", - "execution_count": 2, - "id": "a9ca6f9a", - "metadata": { - "collapsed": false, - "editable": true - }, - "outputs": [], - "source": [ - "import numpy as np \n", - "\n", - "def step_length(t,t0,t1):\n", - " return t0/(t+t1)\n", - "\n", - "n = 100 #100 datapoints \n", - "M = 5 #size of each minibatch\n", - "m = int(n/M) #number of minibatches\n", - "n_epochs = 500 #number of epochs\n", - "t0 = 1.0\n", - "t1 = 10\n", - "\n", - "gamma_j = t0/t1\n", - "j = 0\n", - "for epoch in range(1,n_epochs+1):\n", - " for i in range(m):\n", - " k = np.random.randint(m) #Pick the k-th minibatch at random\n", - " #Compute the gradient using the data in minibatch Bk\n", - " #Compute new suggestion for beta\n", - " t = epoch*m+i\n", - " gamma_j = step_length(t,t0,t1)\n", - " j += 1\n", - "\n", - "print(\"gamma_j after %d epochs: %g\" % (n_epochs,gamma_j))" - ] - }, - { - "cell_type": "markdown", - "id": "fcf9b69b", - "metadata": { - "editable": true - }, - "source": [ - "## Code with a Number of Minibatches which varies\n", - "\n", - "In the code here we vary the number of mini-batches." - ] - }, - { - "cell_type": "code", - "execution_count": 3, - "id": "861b050f", - "metadata": { - "collapsed": false, - "editable": true - }, - "outputs": [], - "source": [ - "%matplotlib inline\n", - "\n", - "# Importing various packages\n", - "from math import exp, sqrt\n", - "from random import random, seed\n", - "import numpy as np\n", - "import matplotlib.pyplot as plt\n", - "\n", - "n = 100\n", - "x = 2*np.random.rand(n,1)\n", - "y = 4+3*x+np.random.randn(n,1)\n", - "\n", - "X = np.c_[np.ones((n,1)), x]\n", - "XT_X = X.T @ X\n", - "theta_linreg = np.linalg.inv(X.T @ X) @ (X.T @ y)\n", - "print(\"Own inversion\")\n", - "print(theta_linreg)\n", - "# Hessian matrix\n", - "H = (2.0/n)* XT_X\n", - "EigValues, EigVectors = np.linalg.eig(H)\n", - "print(f\"Eigenvalues of Hessian Matrix:{EigValues}\")\n", - "\n", - "theta = np.random.randn(2,1)\n", - "eta = 1.0/np.max(EigValues)\n", - "Niterations = 1000\n", - "\n", - "\n", - "for iter in range(Niterations):\n", - " gradients = 2.0/n*X.T @ ((X @ theta)-y)\n", - " theta -= eta*gradients\n", - "print(\"theta from own gd\")\n", - "print(theta)\n", - "\n", - "xnew = np.array([[0],[2]])\n", - "Xnew = np.c_[np.ones((2,1)), xnew]\n", - "ypredict = Xnew.dot(theta)\n", - "ypredict2 = Xnew.dot(theta_linreg)\n", - "\n", - "n_epochs = 50\n", - "M = 5 #size of each minibatch\n", - "m = int(n/M) #number of minibatches\n", - "t0, t1 = 5, 50\n", - "\n", - "def learning_schedule(t):\n", - " return t0/(t+t1)\n", - "\n", - "theta = np.random.randn(2,1)\n", - "\n", - "for epoch in range(n_epochs):\n", - "# Can you figure out a better way of setting up the contributions to each batch?\n", - " for i in range(m):\n", - " random_index = M*np.random.randint(m)\n", - " xi = X[random_index:random_index+M]\n", - " yi = y[random_index:random_index+M]\n", - " gradients = (2.0/M)* xi.T @ ((xi @ theta)-yi)\n", - " eta = learning_schedule(epoch*m+i)\n", - " theta = theta - eta*gradients\n", - "print(\"theta from own sdg\")\n", - "print(theta)\n", - "\n", - "plt.plot(xnew, ypredict, \"r-\")\n", - "plt.plot(xnew, ypredict2, \"b-\")\n", - "plt.plot(x, y ,'ro')\n", - "plt.axis([0,2.0,0, 15.0])\n", - "plt.xlabel(r'$x$')\n", - "plt.ylabel(r'$y$')\n", - "plt.title(r'Random numbers ')\n", - "plt.show()" - ] - }, - { - "cell_type": "markdown", - "id": "97311aec", - "metadata": { - "editable": true - }, - "source": [ - "## Replace or not\n", - "\n", - "In the above code, we have use replacement in setting up the\n", - "mini-batches. The discussion\n", - "[here](https://sebastianraschka.com/faq/docs/sgd-methods.html) may be\n", - "useful." - ] - }, - { - "cell_type": "markdown", - "id": "423ddc16", - "metadata": { - "editable": true - }, - "source": [ - "## Momentum based GD\n", - "\n", - "The stochastic gradient descent (SGD) is almost always used with a\n", - "*momentum* or inertia term that serves as a memory of the direction we\n", - "are moving in parameter space. This is typically implemented as\n", - "follows" - ] - }, - { - "cell_type": "markdown", - "id": "a4f85670", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\mathbf{v}_{t}=\\gamma \\mathbf{v}_{t-1}+\\eta_{t}\\nabla_\\theta E(\\boldsymbol{\\theta}_t) \\nonumber\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "f15ea450", - "metadata": { - "editable": true - }, - "source": [ - "\n", - "
\n", - "\n", - "$$\n", - "\\begin{equation} \n", - "\\boldsymbol{\\theta}_{t+1}= \\boldsymbol{\\theta}_t -\\mathbf{v}_{t},\n", - "\\label{_auto1} \\tag{1}\n", - "\\end{equation}\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "233d7b7e", - "metadata": { - "editable": true - }, - "source": [ - "where we have introduced a momentum parameter $\\gamma$, with\n", - "$0\\le\\gamma\\le 1$, and for brevity we dropped the explicit notation to\n", - "indicate the gradient is to be taken over a different mini-batch at\n", - "each step. We call this algorithm gradient descent with momentum\n", - "(GDM). From these equations, it is clear that $\\mathbf{v}_t$ is a\n", - "running average of recently encountered gradients and\n", - "$(1-\\gamma)^{-1}$ sets the characteristic time scale for the memory\n", - "used in the averaging procedure. Consistent with this, when\n", - "$\\gamma=0$, this just reduces down to ordinary SGD as discussed\n", - "earlier. An equivalent way of writing the updates is" - ] - }, - { - "cell_type": "markdown", - "id": "b923e7d5", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\Delta \\boldsymbol{\\theta}_{t+1} = \\gamma \\Delta \\boldsymbol{\\theta}_t -\\ \\eta_{t}\\nabla_\\theta E(\\boldsymbol{\\theta}_t),\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "60980ded", - "metadata": { - "editable": true - }, - "source": [ - "where we have defined $\\Delta \\boldsymbol{\\theta}_{t}= \\boldsymbol{\\theta}_t-\\boldsymbol{\\theta}_{t-1}$." - ] - }, - { - "cell_type": "markdown", - "id": "cc771e70", - "metadata": { - "editable": true - }, - "source": [ - "## More on momentum based approaches\n", - "\n", - "Let us try to get more intuition from these equations. It is helpful\n", - "to consider a simple physical analogy with a particle of mass $m$\n", - "moving in a viscous medium with drag coefficient $\\mu$ and potential\n", - "$E(\\mathbf{w})$. If we denote the particle's position by $\\mathbf{w}$,\n", - "then its motion is described by" - ] - }, - { - "cell_type": "markdown", - "id": "859f6ffc", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "m {d^2 \\mathbf{w} \\over dt^2} + \\mu {d \\mathbf{w} \\over dt }= -\\nabla_w E(\\mathbf{w}).\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "064cc085", - "metadata": { - "editable": true - }, - "source": [ - "We can discretize this equation in the usual way to get" - ] - }, - { - "cell_type": "markdown", - "id": "47d13c3c", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "m { \\mathbf{w}_{t+\\Delta t}-2 \\mathbf{w}_{t} +\\mathbf{w}_{t-\\Delta t} \\over (\\Delta t)^2}+\\mu {\\mathbf{w}_{t+\\Delta t}- \\mathbf{w}_{t} \\over \\Delta t} = -\\nabla_w E(\\mathbf{w}).\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "0ca67954", - "metadata": { - "editable": true - }, - "source": [ - "Rearranging this equation, we can rewrite this as" - ] - }, - { - "cell_type": "markdown", - "id": "ea9f63a8", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\Delta \\mathbf{w}_{t +\\Delta t}= - { (\\Delta t)^2 \\over m +\\mu \\Delta t} \\nabla_w E(\\mathbf{w})+ {m \\over m +\\mu \\Delta t} \\Delta \\mathbf{w}_t.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "35146ea5", - "metadata": { - "editable": true - }, - "source": [ - "## Momentum parameter\n", - "\n", - "Notice that this equation is identical to previous one if we identify\n", - "the position of the particle, $\\mathbf{w}$, with the parameters\n", - "$\\boldsymbol{\\theta}$. This allows us to identify the momentum\n", - "parameter and learning rate with the mass of the particle and the\n", - "viscous drag as:" - ] - }, - { - "cell_type": "markdown", - "id": "82c87bb1", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\gamma= {m \\over m +\\mu \\Delta t }, \\qquad \\eta = {(\\Delta t)^2 \\over m +\\mu \\Delta t}.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "75415fca", - "metadata": { - "editable": true - }, - "source": [ - "Thus, as the name suggests, the momentum parameter is proportional to\n", - "the mass of the particle and effectively provides inertia.\n", - "Furthermore, in the large viscosity/small learning rate limit, our\n", - "memory time scales as $(1-\\gamma)^{-1} \\approx m/(\\mu \\Delta t)$.\n", - "\n", - "Why is momentum useful? SGD momentum helps the gradient descent\n", - "algorithm gain speed in directions with persistent but small gradients\n", - "even in the presence of stochasticity, while suppressing oscillations\n", - "in high-curvature directions. This becomes especially important in\n", - "situations where the landscape is shallow and flat in some directions\n", - "and narrow and steep in others. It has been argued that first-order\n", - "methods (with appropriate initial conditions) can perform comparable\n", - "to more expensive second order methods, especially in the context of\n", - "complex deep learning models.\n", - "\n", - "These beneficial properties of momentum can sometimes become even more\n", - "pronounced by using a slight modification of the classical momentum\n", - "algorithm called Nesterov Accelerated Gradient (NAG).\n", - "\n", - "In the NAG algorithm, rather than calculating the gradient at the\n", - "current parameters, $\\nabla_\\theta E(\\boldsymbol{\\theta}_t)$, one\n", - "calculates the gradient at the expected value of the parameters given\n", - "our current momentum, $\\nabla_\\theta E(\\boldsymbol{\\theta}_t +\\gamma\n", - "\\mathbf{v}_{t-1})$. This yields the NAG update rule" - ] - }, - { - "cell_type": "markdown", - "id": "59892cd6", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\mathbf{v}_{t}=\\gamma \\mathbf{v}_{t-1}+\\eta_{t}\\nabla_\\theta E(\\boldsymbol{\\theta}_t +\\gamma \\mathbf{v}_{t-1}) \\nonumber\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "a01225ea", - "metadata": { - "editable": true - }, - "source": [ - "\n", - "
\n", - "\n", - "$$\n", - "\\begin{equation} \n", - "\\boldsymbol{\\theta}_{t+1}= \\boldsymbol{\\theta}_t -\\mathbf{v}_{t}.\n", - "\\label{_auto2} \\tag{2}\n", - "\\end{equation}\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "e2c9f57b", - "metadata": { - "editable": true - }, - "source": [ - "One of the major advantages of NAG is that it allows for the use of a larger learning rate than GDM for the same choice of $\\gamma$." - ] - }, - { - "cell_type": "markdown", - "id": "1672a79e", - "metadata": { - "editable": true - }, - "source": [ - "## Second moment of the gradient\n", - "\n", - "In stochastic gradient descent, with and without momentum, we still\n", - "have to specify a schedule for tuning the learning rates $\\eta_t$\n", - "as a function of time. As discussed in the context of Newton's\n", - "method, this presents a number of dilemmas. The learning rate is\n", - "limited by the steepest direction which can change depending on the\n", - "current position in the landscape. To circumvent this problem, ideally\n", - "our algorithm would keep track of curvature and take large steps in\n", - "shallow, flat directions and small steps in steep, narrow directions.\n", - "Second-order methods accomplish this by calculating or approximating\n", - "the Hessian and normalizing the learning rate by the\n", - "curvature. However, this is very computationally expensive for\n", - "extremely large models. Ideally, we would like to be able to\n", - "adaptively change the step size to match the landscape without paying\n", - "the steep computational price of calculating or approximating\n", - "Hessians.\n", - "\n", - "Recently, a number of methods have been introduced that accomplish\n", - "this by tracking not only the gradient, but also the second moment of\n", - "the gradient. These methods include AdaGrad, AdaDelta, Root Mean Squared Propagation (RMS-Prop), and\n", - "[ADAM](https://arxiv.org/abs/1412.6980)." - ] - }, - { - "cell_type": "markdown", - "id": "6d4032f9", - "metadata": { - "editable": true - }, - "source": [ - "## RMS prop\n", - "\n", - "In RMS prop, in addition to keeping a running average of the first\n", - "moment of the gradient, we also keep track of the second moment\n", - "denoted by $\\mathbf{s}_t=\\mathbb{E}[\\mathbf{g}_t^2]$. The update rule\n", - "for RMS prop is given by" - ] - }, - { - "cell_type": "markdown", - "id": "63cde9f3", - "metadata": { - "editable": true - }, - "source": [ - "\n", - "
\n", - "\n", - "$$\n", - "\\begin{equation}\n", - "\\mathbf{g}_t = \\nabla_\\theta E(\\boldsymbol{\\theta}) \n", - "\\label{_auto3} \\tag{3}\n", - "\\end{equation}\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "6f8a52c2", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\mathbf{s}_t =\\beta \\mathbf{s}_{t-1} +(1-\\beta)\\mathbf{g}_t^2 \\nonumber\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "9edf087d", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\boldsymbol{\\theta}_{t+1}=\\boldsymbol{\\theta}_t - \\eta_t { \\mathbf{g}_t \\over \\sqrt{\\mathbf{s}_t +\\epsilon}}, \\nonumber\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "7eff676b", - "metadata": { - "editable": true - }, - "source": [ - "where $\\beta$ controls the averaging time of the second moment and is\n", - "typically taken to be about $\\beta=0.9$, $\\eta_t$ is a learning rate\n", - "typically chosen to be $10^{-3}$, and $\\epsilon\\sim 10^{-8} $ is a\n", - "small regularization constant to prevent divergences. Multiplication\n", - "and division by vectors is understood as an element-wise operation. It\n", - "is clear from this formula that the learning rate is reduced in\n", - "directions where the norm of the gradient is consistently large. This\n", - "greatly speeds up the convergence by allowing us to use a larger\n", - "learning rate for flat directions." - ] - }, - { - "cell_type": "markdown", - "id": "3fcb1068", - "metadata": { - "editable": true - }, - "source": [ - "## [ADAM optimizer](https://arxiv.org/abs/1412.6980)\n", - "\n", - "A related algorithm is the ADAM optimizer. In\n", - "[ADAM](https://arxiv.org/abs/1412.6980), we keep a running average of\n", - "both the first and second moment of the gradient and use this\n", - "information to adaptively change the learning rate for different\n", - "parameters. The method isefficient when working with large\n", - "problems involving lots data and/or parameters. It is a combination of the\n", - "gradient descent with momentum algorithm and the RMSprop algorithm\n", - "discussed above.\n", - "\n", - "In addition to keeping a running average of the first and\n", - "second moments of the gradient\n", - "(i.e. $\\mathbf{m}_t=\\mathbb{E}[\\mathbf{g}_t]$ and\n", - "$\\mathbf{s}_t=\\mathbb{E}[\\mathbf{g}^2_t]$, respectively), ADAM\n", - "performs an additional bias correction to account for the fact that we\n", - "are estimating the first two moments of the gradient using a running\n", - "average (denoted by the hats in the update rule below). The update\n", - "rule for ADAM is given by (where multiplication and division are once\n", - "again understood to be element-wise operations below)" - ] - }, - { - "cell_type": "markdown", - "id": "31b034e1", - "metadata": { - "editable": true - }, - "source": [ - "\n", - "
\n", - "\n", - "$$\n", - "\\begin{equation}\n", - "\\mathbf{g}_t = \\nabla_\\theta E(\\boldsymbol{\\theta}) \n", - "\\label{_auto4} \\tag{4}\n", - "\\end{equation}\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "571e9a91", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\mathbf{m}_t = \\beta_1 \\mathbf{m}_{t-1} + (1-\\beta_1) \\mathbf{g}_t \\nonumber\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "fb5883fa", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\mathbf{s}_t =\\beta_2 \\mathbf{s}_{t-1} +(1-\\beta_2)\\mathbf{g}_t^2 \\nonumber\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "ebffe7a1", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\boldsymbol{\\mathbf{m}}_t={\\mathbf{m}_t \\over 1-\\beta_1^t} \\nonumber\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "5a513bd7", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\boldsymbol{\\mathbf{s}}_t ={\\mathbf{s}_t \\over1-\\beta_2^t} \\nonumber\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "d49bc312", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\boldsymbol{\\theta}_{t+1}=\\boldsymbol{\\theta}_t - \\eta_t { \\boldsymbol{\\mathbf{m}}_t \\over \\sqrt{\\boldsymbol{\\mathbf{s}}_t} +\\epsilon}, \\nonumber\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "6f4e5040", - "metadata": { - "editable": true - }, - "source": [ - "\n", - "
\n", - "\n", - "$$\n", - "\\begin{equation} \n", - "\\label{_auto5} \\tag{5}\n", - "\\end{equation}\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "4771881e", - "metadata": { - "editable": true - }, - "source": [ - "where $\\beta_1$ and $\\beta_2$ set the memory lifetime of the first and\n", - "second moment and are typically taken to be $0.9$ and $0.99$\n", - "respectively, and $\\eta$ and $\\epsilon$ are identical to RMSprop.\n", - "\n", - "Like in RMSprop, the effective step size of a parameter depends on the\n", - "magnitude of its gradient squared. To understand this better, let us\n", - "rewrite this expression in terms of the variance\n", - "$\\boldsymbol{\\sigma}_t^2 = \\boldsymbol{\\mathbf{s}}_t -\n", - "(\\boldsymbol{\\mathbf{m}}_t)^2$. Consider a single parameter $\\theta_t$. The\n", - "update rule for this parameter is given by" - ] - }, - { - "cell_type": "markdown", - "id": "3a0d438e", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\Delta \\theta_{t+1}= -\\eta_t { \\boldsymbol{m}_t \\over \\sqrt{\\sigma_t^2 + m_t^2 }+\\epsilon}.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "6cbb721b", - "metadata": { - "editable": true - }, - "source": [ - "## Algorithms and codes for Adagrad, RMSprop and Adam\n", - "\n", - "The algorithms we have implemented are well described in the text by [Goodfellow, Bengio and Courville, chapter 8](https://www.deeplearningbook.org/contents/optimization.html).\n", - "\n", - "The codes which implement these algorithms are discussed after our presentation of automatic differentiation." - ] - }, - { - "cell_type": "markdown", - "id": "e7d8b851", - "metadata": { - "editable": true - }, - "source": [ - "## Practical tips\n", - "\n", - "* **Randomize the data when making mini-batches**. It is always important to randomly shuffle the data when forming mini-batches. Otherwise, the gradient descent method can fit spurious correlations resulting from the order in which data is presented.\n", - "\n", - "* **Transform your inputs**. Learning becomes difficult when our landscape has a mixture of steep and flat directions. One simple trick for minimizing these situations is to standardize the data by subtracting the mean and normalizing the variance of input variables. Whenever possible, also decorrelate the inputs. To understand why this is helpful, consider the case of linear regression. It is easy to show that for the squared error cost function, the Hessian of the cost function is just the correlation matrix between the inputs. Thus, by standardizing the inputs, we are ensuring that the landscape looks homogeneous in all directions in parameter space. Since most deep networks can be viewed as linear transformations followed by a non-linearity at each layer, we expect this intuition to hold beyond the linear case.\n", - "\n", - "* **Monitor the out-of-sample performance.** Always monitor the performance of your model on a validation set (a small portion of the training data that is held out of the training process to serve as a proxy for the test set. If the validation error starts increasing, then the model is beginning to overfit. Terminate the learning process. This *early stopping* significantly improves performance in many settings.\n", - "\n", - "* **Adaptive optimization methods don't always have good generalization.** Recent studies have shown that adaptive methods such as ADAM, RMSPorp, and AdaGrad tend to have poor generalization compared to SGD or SGD with momentum, particularly in the high-dimensional limit (i.e. the number of parameters exceeds the number of data points). Although it is not clear at this stage why these methods perform so well in training deep neural networks, simpler procedures like properly-tuned SGD may work as well or better in these applications.\n", - "\n", - "Geron's text, see chapter 11, has several interesting discussions." - ] - }, - { - "cell_type": "markdown", - "id": "75afab2b", - "metadata": { - "editable": true - }, - "source": [ - "## Automatic differentiation\n", - "\n", - "[Automatic differentiation (AD)](https://en.wikipedia.org/wiki/Automatic_differentiation), \n", - "also called algorithmic\n", - "differentiation or computational differentiation,is a set of\n", - "techniques to numerically evaluate the derivative of a function\n", - "specified by a computer program. AD exploits the fact that every\n", - "computer program, no matter how complicated, executes a sequence of\n", - "elementary arithmetic operations (addition, subtraction,\n", - "multiplication, division, etc.) and elementary functions (exp, log,\n", - "sin, cos, etc.). By applying the chain rule repeatedly to these\n", - "operations, derivatives of arbitrary order can be computed\n", - "automatically, accurately to working precision, and using at most a\n", - "small constant factor more arithmetic operations than the original\n", - "program.\n", - "\n", - "Automatic differentiation is neither:\n", - "\n", - "* Symbolic differentiation, nor\n", - "\n", - "* Numerical differentiation (the method of finite differences).\n", - "\n", - "Symbolic differentiation can lead to inefficient code and faces the\n", - "difficulty of converting a computer program into a single expression,\n", - "while numerical differentiation can introduce round-off errors in the\n", - "discretization process and cancellation\n", - "\n", - "Python has tools for so-called **automatic differentiation**.\n", - "Consider the following example" - ] - }, - { - "cell_type": "markdown", - "id": "c551bfeb", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "f(x) = \\sin\\left(2\\pi x + x^2\\right)\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "f2cbdd82", - "metadata": { - "editable": true - }, - "source": [ - "which has the following derivative" - ] - }, - { - "cell_type": "markdown", - "id": "22e5d8ce", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "f'(x) = \\cos\\left(2\\pi x + x^2\\right)\\left(2\\pi + 2x\\right)\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "d2d352b4", - "metadata": { - "editable": true - }, - "source": [ - "Using **autograd** we have" - ] - }, - { - "cell_type": "code", - "execution_count": 4, - "id": "19f1b95c", - "metadata": { - "collapsed": false, - "editable": true - }, - "outputs": [], - "source": [ - "import autograd.numpy as np\n", - "\n", - "# To do elementwise differentiation:\n", - "from autograd import elementwise_grad as egrad \n", - "\n", - "# To plot:\n", - "import matplotlib.pyplot as plt \n", - "\n", - "\n", - "def f(x):\n", - " return np.sin(2*np.pi*x + x**2)\n", - "\n", - "def f_grad_analytic(x):\n", - " return np.cos(2*np.pi*x + x**2)*(2*np.pi + 2*x)\n", - "\n", - "# Do the comparison:\n", - "x = np.linspace(0,1,1000)\n", - "\n", - "f_grad = egrad(f)\n", - "\n", - "computed = f_grad(x)\n", - "analytic = f_grad_analytic(x)\n", - "\n", - "plt.title('Derivative computed from Autograd compared with the analytical derivative')\n", - "plt.plot(x,computed,label='autograd')\n", - "plt.plot(x,analytic,label='analytic')\n", - "\n", - "plt.xlabel('x')\n", - "plt.ylabel('y')\n", - "plt.legend()\n", - "\n", - "plt.show()\n", - "\n", - "print(\"The max absolute difference is: %g\"%(np.max(np.abs(computed - analytic))))" - ] - }, - { - "cell_type": "markdown", - "id": "f3a495be", - "metadata": { - "editable": true - }, - "source": [ - "## Using autograd\n", - "\n", - "Here we\n", - "experiment with what kind of functions Autograd is capable\n", - "of finding the gradient of. The following Python functions are just\n", - "meant to illustrate what Autograd can do, but please feel free to\n", - "experiment with other, possibly more complicated, functions as well." - ] - }, - { - "cell_type": "code", - "execution_count": 5, - "id": "5c856602", - "metadata": { - "collapsed": false, - "editable": true - }, - "outputs": [], - "source": [ - "import autograd.numpy as np\n", - "from autograd import grad\n", - "\n", - "def f1(x):\n", - " return x**3 + 1\n", - "\n", - "f1_grad = grad(f1)\n", - "\n", - "# Remember to send in float as argument to the computed gradient from Autograd!\n", - "a = 1.0\n", - "\n", - "# See the evaluated gradient at a using autograd:\n", - "print(\"The gradient of f1 evaluated at a = %g using autograd is: %g\"%(a,f1_grad(a)))\n", - "\n", - "# Compare with the analytical derivative, that is f1'(x) = 3*x**2 \n", - "grad_analytical = 3*a**2\n", - "print(\"The gradient of f1 evaluated at a = %g by finding the analytic expression is: %g\"%(a,grad_analytical))" - ] - }, - { - "cell_type": "markdown", - "id": "b361074b", - "metadata": { - "editable": true - }, - "source": [ - "## Autograd with more complicated functions\n", - "\n", - "To differentiate with respect to two (or more) arguments of a Python\n", - "function, Autograd need to know at which variable the function if\n", - "being differentiated with respect to." - ] - }, - { - "cell_type": "code", - "execution_count": 6, - "id": "a458a151", - "metadata": { - "collapsed": false, - "editable": true - }, - "outputs": [], - "source": [ - "import autograd.numpy as np\n", - "from autograd import grad\n", - "def f2(x1,x2):\n", - " return 3*x1**3 + x2*(x1 - 5) + 1\n", - "\n", - "# By sending the argument 0, Autograd will compute the derivative w.r.t the first variable, in this case x1\n", - "f2_grad_x1 = grad(f2,0)\n", - "\n", - "# ... and differentiate w.r.t x2 by sending 1 as an additional arugment to grad\n", - "f2_grad_x2 = grad(f2,1)\n", - "\n", - "x1 = 1.0\n", - "x2 = 3.0 \n", - "\n", - "print(\"Evaluating at x1 = %g, x2 = %g\"%(x1,x2))\n", - "print(\"-\"*30)\n", - "\n", - "# Compare with the analytical derivatives:\n", - "\n", - "# Derivative of f2 w.r.t x1 is: 9*x1**2 + x2:\n", - "f2_grad_x1_analytical = 9*x1**2 + x2\n", - "\n", - "# Derivative of f2 w.r.t x2 is: x1 - 5:\n", - "f2_grad_x2_analytical = x1 - 5\n", - "\n", - "# See the evaluated derivations:\n", - "print(\"The derivative of f2 w.r.t x1: %g\"%( f2_grad_x1(x1,x2) ))\n", - "print(\"The analytical derivative of f2 w.r.t x1: %g\"%( f2_grad_x1(x1,x2) ))\n", - "\n", - "print()\n", - "\n", - "print(\"The derivative of f2 w.r.t x2: %g\"%( f2_grad_x2(x1,x2) ))\n", - "print(\"The analytical derivative of f2 w.r.t x2: %g\"%( f2_grad_x2(x1,x2) ))" - ] - }, - { - "cell_type": "markdown", - "id": "946c37f1", - "metadata": { - "editable": true - }, - "source": [ - "Note that the grad function will not produce the true gradient of the function. The true gradient of a function with two or more variables will produce a vector, where each element is the function differentiated w.r.t a variable." - ] - }, - { - "cell_type": "markdown", - "id": "a00d38e5", - "metadata": { - "editable": true - }, - "source": [ - "## More complicated functions using the elements of their arguments directly" - ] - }, - { - "cell_type": "code", - "execution_count": 7, - "id": "d8c2a448", - "metadata": { - "collapsed": false, - "editable": true - }, - "outputs": [], - "source": [ - "import autograd.numpy as np\n", - "from autograd import grad\n", - "def f3(x): # Assumes x is an array of length 5 or higher\n", - " return 2*x[0] + 3*x[1] + 5*x[2] + 7*x[3] + 11*x[4]**2\n", - "\n", - "f3_grad = grad(f3)\n", - "\n", - "x = np.linspace(0,4,5)\n", - "\n", - "# Print the computed gradient:\n", - "print(\"The computed gradient of f3 is: \", f3_grad(x))\n", - "\n", - "# The analytical gradient is: (2, 3, 5, 7, 22*x[4])\n", - "f3_grad_analytical = np.array([2, 3, 5, 7, 22*x[4]])\n", - "\n", - "# Print the analytical gradient:\n", - "print(\"The analytical gradient of f3 is: \", f3_grad_analytical)" - ] - }, - { - "cell_type": "markdown", - "id": "026d8733", - "metadata": { - "editable": true - }, - "source": [ - "Note that in this case, when sending an array as input argument, the\n", - "output from Autograd is another array. This is the true gradient of\n", - "the function, as opposed to the function in the previous example. By\n", - "using arrays to represent the variables, the output from Autograd\n", - "might be easier to work with, as the output is closer to what one\n", - "could expect form a gradient-evaluting function." - ] - }, - { - "cell_type": "markdown", - "id": "1a4dca11", - "metadata": { - "editable": true - }, - "source": [ - "## Functions using mathematical functions from Numpy" - ] - }, - { - "cell_type": "code", - "execution_count": 8, - "id": "c10b664f", - "metadata": { - "collapsed": false, - "editable": true - }, - "outputs": [], - "source": [ - "import autograd.numpy as np\n", - "from autograd import grad\n", - "def f4(x):\n", - " return np.sqrt(1+x**2) + np.exp(x) + np.sin(2*np.pi*x)\n", - "\n", - "f4_grad = grad(f4)\n", - "\n", - "x = 2.7\n", - "\n", - "# Print the computed derivative:\n", - "print(\"The computed derivative of f4 at x = %g is: %g\"%(x,f4_grad(x)))\n", - "\n", - "# The analytical derivative is: x/sqrt(1 + x**2) + exp(x) + cos(2*pi*x)*2*pi\n", - "f4_grad_analytical = x/np.sqrt(1 + x**2) + np.exp(x) + np.cos(2*np.pi*x)*2*np.pi\n", - "\n", - "# Print the analytical gradient:\n", - "print(\"The analytical gradient of f4 at x = %g is: %g\"%(x,f4_grad_analytical))" - ] - }, - { - "cell_type": "markdown", - "id": "07436a71", - "metadata": { - "editable": true - }, - "source": [ - "## More autograd" - ] - }, - { - "cell_type": "code", - "execution_count": 9, - "id": "1840a5d2", - "metadata": { - "collapsed": false, - "editable": true - }, - "outputs": [], - "source": [ - "import autograd.numpy as np\n", - "from autograd import grad\n", - "def f5(x):\n", - " if x >= 0:\n", - " return x**2\n", - " else:\n", - " return -3*x + 1\n", - "\n", - "f5_grad = grad(f5)\n", - "\n", - "x = 2.7\n", - "\n", - "# Print the computed derivative:\n", - "print(\"The computed derivative of f5 at x = %g is: %g\"%(x,f5_grad(x)))" - ] - }, - { - "cell_type": "markdown", - "id": "87ee8137", - "metadata": { - "editable": true - }, - "source": [ - "## And with loops" - ] - }, - { - "cell_type": "code", - "execution_count": 10, - "id": "f1b25f09", - "metadata": { - "collapsed": false, - "editable": true - }, - "outputs": [], - "source": [ - "import autograd.numpy as np\n", - "from autograd import grad\n", - "def f6_for(x):\n", - " val = 0\n", - " for i in range(10):\n", - " val = val + x**i\n", - " return val\n", - "\n", - "def f6_while(x):\n", - " val = 0\n", - " i = 0\n", - " while i < 10:\n", - " val = val + x**i\n", - " i = i + 1\n", - " return val\n", - "\n", - "f6_for_grad = grad(f6_for)\n", - "f6_while_grad = grad(f6_while)\n", - "\n", - "x = 0.5\n", - "\n", - "# Print the computed derivaties of f6_for and f6_while\n", - "print(\"The computed derivative of f6_for at x = %g is: %g\"%(x,f6_for_grad(x)))\n", - "print(\"The computed derivative of f6_while at x = %g is: %g\"%(x,f6_while_grad(x)))" - ] - }, - { - "cell_type": "code", - "execution_count": 11, - "id": "5fa2802b", - "metadata": { - "collapsed": false, - "editable": true - }, - "outputs": [], - "source": [ - "import autograd.numpy as np\n", - "from autograd import grad\n", - "# Both of the functions are implementation of the sum: sum(x**i) for i = 0, ..., 9\n", - "# The analytical derivative is: sum(i*x**(i-1)) \n", - "f6_grad_analytical = 0\n", - "for i in range(10):\n", - " f6_grad_analytical += i*x**(i-1)\n", - "\n", - "print(\"The analytical derivative of f6 at x = %g is: %g\"%(x,f6_grad_analytical))" - ] - }, - { - "cell_type": "markdown", - "id": "eb66fab4", - "metadata": { - "editable": true - }, - "source": [ - "## Using recursion" - ] - }, - { - "cell_type": "code", - "execution_count": 12, - "id": "965c8bbb", - "metadata": { - "collapsed": false, - "editable": true - }, - "outputs": [], - "source": [ - "import autograd.numpy as np\n", - "from autograd import grad\n", - "\n", - "def f7(n): # Assume that n is an integer\n", - " if n == 1 or n == 0:\n", - " return 1\n", - " else:\n", - " return n*f7(n-1)\n", - "\n", - "f7_grad = grad(f7)\n", - "\n", - "n = 2.0\n", - "\n", - "print(\"The computed derivative of f7 at n = %d is: %g\"%(n,f7_grad(n)))\n", - "\n", - "# The function f7 is an implementation of the factorial of n.\n", - "# By using the product rule, one can find that the derivative is:\n", - "\n", - "f7_grad_analytical = 0\n", - "for i in range(int(n)-1):\n", - " tmp = 1\n", - " for k in range(int(n)-1):\n", - " if k != i:\n", - " tmp *= (n - k)\n", - " f7_grad_analytical += tmp\n", - "\n", - "print(\"The analytical derivative of f7 at n = %d is: %g\"%(n,f7_grad_analytical))" - ] - }, - { - "cell_type": "markdown", - "id": "2e6e0c8a", - "metadata": { - "editable": true - }, - "source": [ - "Note that if n is equal to zero or one, Autograd will give an error message. This message appears when the output is independent on input." - ] - }, - { - "cell_type": "markdown", - "id": "42adbcc3", - "metadata": { - "editable": true - }, - "source": [ - "## Unsupported functions\n", - "Autograd supports many features. However, there are some functions that is not supported (yet) by Autograd.\n", - "\n", - "Assigning a value to the variable being differentiated with respect to" - ] - }, - { - "cell_type": "code", - "execution_count": 13, - "id": "6ca4a5dc", - "metadata": { - "collapsed": false, - "editable": true - }, - "outputs": [], - "source": [ - "import autograd.numpy as np\n", - "from autograd import grad\n", - "def f8(x): # Assume x is an array\n", - " x[2] = 3\n", - " return x*2\n", - "\n", - "f8_grad = grad(f8)\n", - "\n", - "x = 8.4\n", - "\n", - "print(\"The derivative of f8 is:\",f8_grad(x))" - ] - }, - { - "cell_type": "markdown", - "id": "5d816052", - "metadata": { - "editable": true - }, - "source": [ - "Here, Autograd tells us that an 'ArrayBox' does not support item assignment. The item assignment is done when the program tries to assign x[2] to the value 3. However, Autograd has implemented the computation of the derivative such that this assignment is not possible." - ] - }, - { - "cell_type": "markdown", - "id": "73f2e7e4", - "metadata": { - "editable": true - }, - "source": [ - "## The syntax a.dot(b) when finding the dot product" - ] - }, - { - "cell_type": "code", - "execution_count": 14, - "id": "2ead27d5", - "metadata": { - "collapsed": false, - "editable": true - }, - "outputs": [], - "source": [ - "import autograd.numpy as np\n", - "from autograd import grad\n", - "def f9(a): # Assume a is an array with 2 elements\n", - " b = np.array([1.0,2.0])\n", - " return a.dot(b)\n", - "\n", - "f9_grad = grad(f9)\n", - "\n", - "x = np.array([1.0,0.0])\n", - "\n", - "print(\"The derivative of f9 is:\",f9_grad(x))" - ] - }, - { - "cell_type": "markdown", - "id": "1edcb932", - "metadata": { - "editable": true - }, - "source": [ - "Here we are told that the 'dot' function does not belong to Autograd's\n", - "version of a Numpy array. To overcome this, an alternative syntax\n", - "which also computed the dot product can be used:" - ] - }, - { - "cell_type": "code", - "execution_count": 15, - "id": "05897777", - "metadata": { - "collapsed": false, - "editable": true - }, - "outputs": [], - "source": [ - "import autograd.numpy as np\n", - "from autograd import grad\n", - "def f9_alternative(x): # Assume a is an array with 2 elements\n", - " b = np.array([1.0,2.0])\n", - " return np.dot(x,b) # The same as x_1*b_1 + x_2*b_2\n", - "\n", - "f9_alternative_grad = grad(f9_alternative)\n", - "\n", - "x = np.array([3.0,0.0])\n", - "\n", - "print(\"The gradient of f9 is:\",f9_alternative_grad(x))\n", - "\n", - "# The analytical gradient of the dot product of vectors x and b with two elements (x_1,x_2) and (b_1, b_2) respectively\n", - "# w.r.t x is (b_1, b_2)." - ] - }, - { - "cell_type": "markdown", - "id": "2c899815", - "metadata": { - "editable": true - }, - "source": [ - "## Recommended to avoid\n", - "The documentation recommends to avoid inplace operations such as" - ] - }, - { - "cell_type": "code", - "execution_count": 16, - "id": "fd05063c", - "metadata": { - "collapsed": false, - "editable": true - }, - "outputs": [], - "source": [ - "a += b\n", - "a -= b\n", - "a*= b\n", - "a /=b" - ] - }, - { - "cell_type": "markdown", - "id": "94d6f0d9", - "metadata": { - "editable": true - }, - "source": [ - "## Using Autograd with OLS\n", - "\n", - "We conclude the part on optmization by showing how we can make codes\n", - "for linear regression and logistic regression using **autograd**. The\n", - "first example shows results with ordinary leats squares." - ] - }, - { - "cell_type": "code", - "execution_count": 17, - "id": "d002c672", - "metadata": { - "collapsed": false, - "editable": true - }, - "outputs": [], - "source": [ - "# Using Autograd to calculate gradients for OLS\n", - "from random import random, seed\n", - "import numpy as np\n", - "import autograd.numpy as np\n", - "import matplotlib.pyplot as plt\n", - "from autograd import grad\n", - "\n", - "def CostOLS(beta):\n", - " return (1.0/n)*np.sum((y-X @ beta)**2)\n", - "\n", - "n = 100\n", - "x = 2*np.random.rand(n,1)\n", - "y = 4+3*x+np.random.randn(n,1)\n", - "\n", - "X = np.c_[np.ones((n,1)), x]\n", - "XT_X = X.T @ X\n", - "theta_linreg = np.linalg.pinv(XT_X) @ (X.T @ y)\n", - "print(\"Own inversion\")\n", - "print(theta_linreg)\n", - "# Hessian matrix\n", - "H = (2.0/n)* XT_X\n", - "EigValues, EigVectors = np.linalg.eig(H)\n", - "print(f\"Eigenvalues of Hessian Matrix:{EigValues}\")\n", - "\n", - "theta = np.random.randn(2,1)\n", - "eta = 1.0/np.max(EigValues)\n", - "Niterations = 1000\n", - "# define the gradient\n", - "training_gradient = grad(CostOLS)\n", - "\n", - "for iter in range(Niterations):\n", - " gradients = training_gradient(theta)\n", - " theta -= eta*gradients\n", - "print(\"theta from own gd\")\n", - "print(theta)\n", - "\n", - "xnew = np.array([[0],[2]])\n", - "Xnew = np.c_[np.ones((2,1)), xnew]\n", - "ypredict = Xnew.dot(theta)\n", - "ypredict2 = Xnew.dot(theta_linreg)\n", - "\n", - "plt.plot(xnew, ypredict, \"r-\")\n", - "plt.plot(xnew, ypredict2, \"b-\")\n", - "plt.plot(x, y ,'ro')\n", - "plt.axis([0,2.0,0, 15.0])\n", - "plt.xlabel(r'$x$')\n", - "plt.ylabel(r'$y$')\n", - "plt.title(r'Random numbers ')\n", - "plt.show()" - ] - }, - { - "cell_type": "markdown", - "id": "e72279fe", - "metadata": { - "editable": true - }, - "source": [ - "## Same code but now with momentum gradient descent" - ] - }, - { - "cell_type": "code", - "execution_count": 18, - "id": "62aa2606", - "metadata": { - "collapsed": false, - "editable": true - }, - "outputs": [], - "source": [ - "# Using Autograd to calculate gradients for OLS\n", - "from random import random, seed\n", - "import numpy as np\n", - "import autograd.numpy as np\n", - "import matplotlib.pyplot as plt\n", - "from autograd import grad\n", - "\n", - "def CostOLS(beta):\n", - " return (1.0/n)*np.sum((y-X @ beta)**2)\n", - "\n", - "n = 100\n", - "x = 2*np.random.rand(n,1)\n", - "y = 4+3*x#+np.random.randn(n,1)\n", - "\n", - "X = np.c_[np.ones((n,1)), x]\n", - "XT_X = X.T @ X\n", - "theta_linreg = np.linalg.pinv(XT_X) @ (X.T @ y)\n", - "print(\"Own inversion\")\n", - "print(theta_linreg)\n", - "# Hessian matrix\n", - "H = (2.0/n)* XT_X\n", - "EigValues, EigVectors = np.linalg.eig(H)\n", - "print(f\"Eigenvalues of Hessian Matrix:{EigValues}\")\n", - "\n", - "theta = np.random.randn(2,1)\n", - "eta = 1.0/np.max(EigValues)\n", - "Niterations = 30\n", - "\n", - "# define the gradient\n", - "training_gradient = grad(CostOLS)\n", - "\n", - "for iter in range(Niterations):\n", - " gradients = training_gradient(theta)\n", - " theta -= eta*gradients\n", - " print(iter,gradients[0],gradients[1])\n", - "print(\"theta from own gd\")\n", - "print(theta)\n", - "\n", - "# Now improve with momentum gradient descent\n", - "change = 0.0\n", - "delta_momentum = 0.3\n", - "for iter in range(Niterations):\n", - " # calculate gradient\n", - " gradients = training_gradient(theta)\n", - " # calculate update\n", - " new_change = eta*gradients+delta_momentum*change\n", - " # take a step\n", - " theta -= new_change\n", - " # save the change\n", - " change = new_change\n", - " print(iter,gradients[0],gradients[1])\n", - "print(\"theta from own gd wth momentum\")\n", - "print(theta)" - ] - }, - { - "cell_type": "markdown", - "id": "bad8e42f", - "metadata": { - "editable": true - }, - "source": [ - "## But noen of these can compete with Newton's method" - ] - }, - { - "cell_type": "code", - "execution_count": 19, - "id": "13a572a8", - "metadata": { - "collapsed": false, - "editable": true - }, - "outputs": [], - "source": [ - "# Using Newton's method\n", - "from random import random, seed\n", - "import numpy as np\n", - "import autograd.numpy as np\n", - "import matplotlib.pyplot as plt\n", - "from autograd import grad\n", - "\n", - "def CostOLS(beta):\n", - " return (1.0/n)*np.sum((y-X @ beta)**2)\n", - "\n", - "n = 100\n", - "x = 2*np.random.rand(n,1)\n", - "y = 4+3*x+np.random.randn(n,1)\n", - "\n", - "X = np.c_[np.ones((n,1)), x]\n", - "XT_X = X.T @ X\n", - "beta_linreg = np.linalg.pinv(XT_X) @ (X.T @ y)\n", - "print(\"Own inversion\")\n", - "print(beta_linreg)\n", - "# Hessian matrix\n", - "H = (2.0/n)* XT_X\n", - "# Note that here the Hessian does not depend on the parameters beta\n", - "invH = np.linalg.pinv(H)\n", - "EigValues, EigVectors = np.linalg.eig(H)\n", - "print(f\"Eigenvalues of Hessian Matrix:{EigValues}\")\n", - "\n", - "beta = np.random.randn(2,1)\n", - "Niterations = 5\n", - "\n", - "# define the gradient\n", - "training_gradient = grad(CostOLS)\n", - "\n", - "for iter in range(Niterations):\n", - " gradients = training_gradient(beta)\n", - " beta -= invH @ gradients\n", - " print(iter,gradients[0],gradients[1])\n", - "print(\"beta from own Newton code\")\n", - "print(beta)" - ] - }, - { - "cell_type": "markdown", - "id": "5b2c9e3a", - "metadata": { - "editable": true - }, - "source": [ - "## Including Stochastic Gradient Descent with Autograd\n", - "In this code we include the stochastic gradient descent approach discussed above. Note here that we specify which argument we are taking the derivative with respect to when using **autograd**." - ] - }, - { - "cell_type": "code", - "execution_count": 20, - "id": "830370bf", - "metadata": { - "collapsed": false, - "editable": true - }, - "outputs": [], - "source": [ - "# Using Autograd to calculate gradients using SGD\n", - "# OLS example\n", - "from random import random, seed\n", - "import numpy as np\n", - "import autograd.numpy as np\n", - "import matplotlib.pyplot as plt\n", - "from autograd import grad\n", - "\n", - "# Note change from previous example\n", - "def CostOLS(y,X,theta):\n", - " return np.sum((y-X @ theta)**2)\n", - "\n", - "n = 100\n", - "x = 2*np.random.rand(n,1)\n", - "y = 4+3*x+np.random.randn(n,1)\n", - "\n", - "X = np.c_[np.ones((n,1)), x]\n", - "XT_X = X.T @ X\n", - "theta_linreg = np.linalg.pinv(XT_X) @ (X.T @ y)\n", - "print(\"Own inversion\")\n", - "print(theta_linreg)\n", - "# Hessian matrix\n", - "H = (2.0/n)* XT_X\n", - "EigValues, EigVectors = np.linalg.eig(H)\n", - "print(f\"Eigenvalues of Hessian Matrix:{EigValues}\")\n", - "\n", - "theta = np.random.randn(2,1)\n", - "eta = 1.0/np.max(EigValues)\n", - "Niterations = 1000\n", - "\n", - "# Note that we request the derivative wrt third argument (theta, 2 here)\n", - "training_gradient = grad(CostOLS,2)\n", - "\n", - "for iter in range(Niterations):\n", - " gradients = (1.0/n)*training_gradient(y, X, theta)\n", - " theta -= eta*gradients\n", - "print(\"theta from own gd\")\n", - "print(theta)\n", - "\n", - "xnew = np.array([[0],[2]])\n", - "Xnew = np.c_[np.ones((2,1)), xnew]\n", - "ypredict = Xnew.dot(theta)\n", - "ypredict2 = Xnew.dot(theta_linreg)\n", - "\n", - "plt.plot(xnew, ypredict, \"r-\")\n", - "plt.plot(xnew, ypredict2, \"b-\")\n", - "plt.plot(x, y ,'ro')\n", - "plt.axis([0,2.0,0, 15.0])\n", - "plt.xlabel(r'$x$')\n", - "plt.ylabel(r'$y$')\n", - "plt.title(r'Random numbers ')\n", - "plt.show()\n", - "\n", - "n_epochs = 50\n", - "M = 5 #size of each minibatch\n", - "m = int(n/M) #number of minibatches\n", - "t0, t1 = 5, 50\n", - "def learning_schedule(t):\n", - " return t0/(t+t1)\n", - "\n", - "theta = np.random.randn(2,1)\n", - "\n", - "for epoch in range(n_epochs):\n", - "# Can you figure out a better way of setting up the contributions to each batch?\n", - " for i in range(m):\n", - " random_index = M*np.random.randint(m)\n", - " xi = X[random_index:random_index+M]\n", - " yi = y[random_index:random_index+M]\n", - " gradients = (1.0/M)*training_gradient(yi, xi, theta)\n", - " eta = learning_schedule(epoch*m+i)\n", - " theta = theta - eta*gradients\n", - "print(\"theta from own sdg\")\n", - "print(theta)" - ] - }, - { - "cell_type": "markdown", - "id": "e580483f", - "metadata": { - "editable": true - }, - "source": [ - "## Same code but now with momentum gradient descent" - ] - }, - { - "cell_type": "code", - "execution_count": 21, - "id": "68895d3f", - "metadata": { - "collapsed": false, - "editable": true - }, - "outputs": [], - "source": [ - "# Using Autograd to calculate gradients using SGD\n", - "# OLS example\n", - "from random import random, seed\n", - "import numpy as np\n", - "import autograd.numpy as np\n", - "import matplotlib.pyplot as plt\n", - "from autograd import grad\n", - "\n", - "# Note change from previous example\n", - "def CostOLS(y,X,theta):\n", - " return np.sum((y-X @ theta)**2)\n", - "\n", - "n = 100\n", - "x = 2*np.random.rand(n,1)\n", - "y = 4+3*x+np.random.randn(n,1)\n", - "\n", - "X = np.c_[np.ones((n,1)), x]\n", - "XT_X = X.T @ X\n", - "theta_linreg = np.linalg.pinv(XT_X) @ (X.T @ y)\n", - "print(\"Own inversion\")\n", - "print(theta_linreg)\n", - "# Hessian matrix\n", - "H = (2.0/n)* XT_X\n", - "EigValues, EigVectors = np.linalg.eig(H)\n", - "print(f\"Eigenvalues of Hessian Matrix:{EigValues}\")\n", - "\n", - "theta = np.random.randn(2,1)\n", - "eta = 1.0/np.max(EigValues)\n", - "Niterations = 100\n", - "\n", - "# Note that we request the derivative wrt third argument (theta, 2 here)\n", - "training_gradient = grad(CostOLS,2)\n", - "\n", - "for iter in range(Niterations):\n", - " gradients = (1.0/n)*training_gradient(y, X, theta)\n", - " theta -= eta*gradients\n", - "print(\"theta from own gd\")\n", - "print(theta)\n", - "\n", - "\n", - "n_epochs = 50\n", - "M = 5 #size of each minibatch\n", - "m = int(n/M) #number of minibatches\n", - "t0, t1 = 5, 50\n", - "def learning_schedule(t):\n", - " return t0/(t+t1)\n", - "\n", - "theta = np.random.randn(2,1)\n", - "\n", - "change = 0.0\n", - "delta_momentum = 0.3\n", - "\n", - "for epoch in range(n_epochs):\n", - " for i in range(m):\n", - " random_index = M*np.random.randint(m)\n", - " xi = X[random_index:random_index+M]\n", - " yi = y[random_index:random_index+M]\n", - " gradients = (1.0/M)*training_gradient(yi, xi, theta)\n", - " eta = learning_schedule(epoch*m+i)\n", - " # calculate update\n", - " new_change = eta*gradients+delta_momentum*change\n", - " # take a step\n", - " theta -= new_change\n", - " # save the change\n", - " change = new_change\n", - "print(\"theta from own sdg with momentum\")\n", - "print(theta)" - ] - }, - { - "cell_type": "markdown", - "id": "01c29c9e", - "metadata": { - "editable": true - }, - "source": [ - "## Similar (second order function now) problem but now with AdaGrad" - ] - }, - { - "cell_type": "code", - "execution_count": 22, - "id": "36a00e5a", - "metadata": { - "collapsed": false, - "editable": true - }, - "outputs": [], - "source": [ - "# Using Autograd to calculate gradients using AdaGrad and Stochastic Gradient descent\n", - "# OLS example\n", - "from random import random, seed\n", - "import numpy as np\n", - "import autograd.numpy as np\n", - "import matplotlib.pyplot as plt\n", - "from autograd import grad\n", - "\n", - "# Note change from previous example\n", - "def CostOLS(y,X,theta):\n", - " return np.sum((y-X @ theta)**2)\n", - "\n", - "n = 1000\n", - "x = np.random.rand(n,1)\n", - "y = 2.0+3*x +4*x*x\n", - "\n", - "X = np.c_[np.ones((n,1)), x, x*x]\n", - "XT_X = X.T @ X\n", - "theta_linreg = np.linalg.pinv(XT_X) @ (X.T @ y)\n", - "print(\"Own inversion\")\n", - "print(theta_linreg)\n", - "\n", - "\n", - "# Note that we request the derivative wrt third argument (theta, 2 here)\n", - "training_gradient = grad(CostOLS,2)\n", - "# Define parameters for Stochastic Gradient Descent\n", - "n_epochs = 50\n", - "M = 5 #size of each minibatch\n", - "m = int(n/M) #number of minibatches\n", - "# Guess for unknown parameters theta\n", - "theta = np.random.randn(3,1)\n", - "\n", - "# Value for learning rate\n", - "eta = 0.01\n", - "# Including AdaGrad parameter to avoid possible division by zero\n", - "delta = 1e-8\n", - "for epoch in range(n_epochs):\n", - " Giter = 0.0\n", - " for i in range(m):\n", - " random_index = M*np.random.randint(m)\n", - " xi = X[random_index:random_index+M]\n", - " yi = y[random_index:random_index+M]\n", - " gradients = (1.0/M)*training_gradient(yi, xi, theta)\n", - " Giter += gradients*gradients\n", - " update = gradients*eta/(delta+np.sqrt(Giter))\n", - " theta -= update\n", - "print(\"theta from own AdaGrad\")\n", - "print(theta)" - ] - }, - { - "cell_type": "markdown", - "id": "18ccca46", - "metadata": { - "editable": true - }, - "source": [ - "Running this code we note an almost perfect agreement with the results from matrix inversion." - ] - }, - { - "cell_type": "markdown", - "id": "e076c773", - "metadata": { - "editable": true - }, - "source": [ - "## RMSprop for adaptive learning rate with Stochastic Gradient Descent" - ] - }, - { - "cell_type": "code", - "execution_count": 23, - "id": "cb4ad1d3", - "metadata": { - "collapsed": false, - "editable": true - }, - "outputs": [], - "source": [ - "# Using Autograd to calculate gradients using RMSprop and Stochastic Gradient descent\n", - "# OLS example\n", - "from random import random, seed\n", - "import numpy as np\n", - "import autograd.numpy as np\n", - "import matplotlib.pyplot as plt\n", - "from autograd import grad\n", - "\n", - "# Note change from previous example\n", - "def CostOLS(y,X,theta):\n", - " return np.sum((y-X @ theta)**2)\n", - "\n", - "n = 1000\n", - "x = np.random.rand(n,1)\n", - "y = 2.0+3*x +4*x*x# +np.random.randn(n,1)\n", - "\n", - "X = np.c_[np.ones((n,1)), x, x*x]\n", - "XT_X = X.T @ X\n", - "theta_linreg = np.linalg.pinv(XT_X) @ (X.T @ y)\n", - "print(\"Own inversion\")\n", - "print(theta_linreg)\n", - "\n", - "\n", - "# Note that we request the derivative wrt third argument (theta, 2 here)\n", - "training_gradient = grad(CostOLS,2)\n", - "# Define parameters for Stochastic Gradient Descent\n", - "n_epochs = 50\n", - "M = 5 #size of each minibatch\n", - "m = int(n/M) #number of minibatches\n", - "# Guess for unknown parameters theta\n", - "theta = np.random.randn(3,1)\n", - "\n", - "# Value for learning rate\n", - "eta = 0.01\n", - "# Value for parameter rho\n", - "rho = 0.99\n", - "# Including AdaGrad parameter to avoid possible division by zero\n", - "delta = 1e-8\n", - "for epoch in range(n_epochs):\n", - " Giter = 0.0\n", - " for i in range(m):\n", - " random_index = M*np.random.randint(m)\n", - " xi = X[random_index:random_index+M]\n", - " yi = y[random_index:random_index+M]\n", - " gradients = (1.0/M)*training_gradient(yi, xi, theta)\n", - "\t# Accumulated gradient\n", - "\t# Scaling with rho the new and the previous results\n", - " Giter = (rho*Giter+(1-rho)*gradients*gradients)\n", - "\t# Taking the diagonal only and inverting\n", - " update = gradients*eta/(delta+np.sqrt(Giter))\n", - "\t# Hadamard product\n", - " theta -= update\n", - "print(\"theta from own RMSprop\")\n", - "print(theta)" - ] - }, - { - "cell_type": "markdown", - "id": "2253fa34", - "metadata": { - "editable": true - }, - "source": [ - "## And finally [ADAM](https://arxiv.org/pdf/1412.6980.pdf)" - ] - }, - { - "cell_type": "code", - "execution_count": 24, - "id": "92b3454a", - "metadata": { - "collapsed": false, - "editable": true - }, - "outputs": [], - "source": [ - "# Using Autograd to calculate gradients using RMSprop and Stochastic Gradient descent\n", - "# OLS example\n", - "from random import random, seed\n", - "import numpy as np\n", - "import autograd.numpy as np\n", - "import matplotlib.pyplot as plt\n", - "from autograd import grad\n", - "\n", - "# Note change from previous example\n", - "def CostOLS(y,X,theta):\n", - " return np.sum((y-X @ theta)**2)\n", - "\n", - "n = 1000\n", - "x = np.random.rand(n,1)\n", - "y = 2.0+3*x +4*x*x# +np.random.randn(n,1)\n", - "\n", - "X = np.c_[np.ones((n,1)), x, x*x]\n", - "XT_X = X.T @ X\n", - "theta_linreg = np.linalg.pinv(XT_X) @ (X.T @ y)\n", - "print(\"Own inversion\")\n", - "print(theta_linreg)\n", - "\n", - "\n", - "# Note that we request the derivative wrt third argument (theta, 2 here)\n", - "training_gradient = grad(CostOLS,2)\n", - "# Define parameters for Stochastic Gradient Descent\n", - "n_epochs = 50\n", - "M = 5 #size of each minibatch\n", - "m = int(n/M) #number of minibatches\n", - "# Guess for unknown parameters theta\n", - "theta = np.random.randn(3,1)\n", - "\n", - "# Value for learning rate\n", - "eta = 0.01\n", - "# Value for parameters beta1 and beta2, see https://arxiv.org/abs/1412.6980\n", - "beta1 = 0.9\n", - "beta2 = 0.999\n", - "# Including AdaGrad parameter to avoid possible division by zero\n", - "delta = 1e-7\n", - "iter = 0\n", - "for epoch in range(n_epochs):\n", - " first_moment = 0.0\n", - " second_moment = 0.0\n", - " iter += 1\n", - " for i in range(m):\n", - " random_index = M*np.random.randint(m)\n", - " xi = X[random_index:random_index+M]\n", - " yi = y[random_index:random_index+M]\n", - " gradients = (1.0/M)*training_gradient(yi, xi, theta)\n", - " # Computing moments first\n", - " first_moment = beta1*first_moment + (1-beta1)*gradients\n", - " second_moment = beta2*second_moment+(1-beta2)*gradients*gradients\n", - " first_term = first_moment/(1.0-beta1**iter)\n", - " second_term = second_moment/(1.0-beta2**iter)\n", - "\t# Scaling with rho the new and the previous results\n", - " update = eta*first_term/(np.sqrt(second_term)+delta)\n", - " theta -= update\n", - "print(\"theta from own ADAM\")\n", - "print(theta)" - ] - }, - { - "cell_type": "markdown", - "id": "c2025d97", - "metadata": { - "editable": true - }, - "source": [ - "## And Logistic Regression" - ] - }, - { - "cell_type": "code", - "execution_count": 25, - "id": "3f6d8746", - "metadata": { - "collapsed": false, - "editable": true - }, - "outputs": [], - "source": [ - "import autograd.numpy as np\n", - "from autograd import grad\n", - "\n", - "def sigmoid(x):\n", - " return 0.5 * (np.tanh(x / 2.) + 1)\n", - "\n", - "def logistic_predictions(weights, inputs):\n", - " # Outputs probability of a label being true according to logistic model.\n", - " return sigmoid(np.dot(inputs, weights))\n", - "\n", - "def training_loss(weights):\n", - " # Training loss is the negative log-likelihood of the training labels.\n", - " preds = logistic_predictions(weights, inputs)\n", - " label_probabilities = preds * targets + (1 - preds) * (1 - targets)\n", - " return -np.sum(np.log(label_probabilities))\n", - "\n", - "# Build a toy dataset.\n", - "inputs = np.array([[0.52, 1.12, 0.77],\n", - " [0.88, -1.08, 0.15],\n", - " [0.52, 0.06, -1.30],\n", - " [0.74, -2.49, 1.39]])\n", - "targets = np.array([True, True, False, True])\n", - "\n", - "# Define a function that returns gradients of training loss using Autograd.\n", - "training_gradient_fun = grad(training_loss)\n", - "\n", - "# Optimize weights using gradient descent.\n", - "weights = np.array([0.0, 0.0, 0.0])\n", - "print(\"Initial loss:\", training_loss(weights))\n", - "for i in range(100):\n", - " weights -= training_gradient_fun(weights) * 0.01\n", - "\n", - "print(\"Trained loss:\", training_loss(weights))" - ] - }, - { - "cell_type": "markdown", - "id": "716627e3", - "metadata": { - "editable": true - }, - "source": [ - "## Introducing [JAX](https://jax.readthedocs.io/en/latest/)\n", - "\n", - "Presently, instead of using **autograd**, we recommend using [JAX](https://jax.readthedocs.io/en/latest/)\n", - "\n", - "**JAX** is Autograd and [XLA (Accelerated Linear Algebra))](https://www.tensorflow.org/xla),\n", - "brought together for high-performance numerical computing and machine learning research.\n", - "It provides composable transformations of Python+NumPy programs: differentiate, vectorize, parallelize, Just-In-Time compile to GPU/TPU, and more.\n", - "\n", - "Here's a simple example on how you can use **JAX** to compute the derivate of the logistic function." - ] - }, - { - "cell_type": "code", - "execution_count": 26, - "id": "5c938af4", - "metadata": { - "collapsed": false, - "editable": true - }, - "outputs": [], - "source": [ - "import jax.numpy as jnp\n", - "from jax import grad, jit, vmap\n", - "\n", - "def sum_logistic(x):\n", - " return jnp.sum(1.0 / (1.0 + jnp.exp(-x)))\n", - "\n", - "x_small = jnp.arange(3.)\n", - "derivative_fn = grad(sum_logistic)\n", - "print(derivative_fn(x_small))" - ] - }, - { - "cell_type": "markdown", - "id": "b087cc5f", - "metadata": { - "editable": true - }, - "source": [ - "## Introduction to Neural networks\n", - "\n", - "Artificial neural networks are computational systems that can learn to\n", - "perform tasks by considering examples, generally without being\n", - "programmed with any task-specific rules. It is supposed to mimic a\n", - "biological system, wherein neurons interact by sending signals in the\n", - "form of mathematical functions between layers. All layers can contain\n", - "an arbitrary number of neurons, and each connection is represented by\n", - "a weight variable." - ] - }, - { - "cell_type": "markdown", - "id": "c040b49e", - "metadata": { - "editable": true - }, - "source": [ - "## Artificial neurons\n", - "\n", - "The field of artificial neural networks has a long history of\n", - "development, and is closely connected with the advancement of computer\n", - "science and computers in general. A model of artificial neurons was\n", - "first developed by McCulloch and Pitts in 1943 to study signal\n", - "processing in the brain and has later been refined by others. The\n", - "general idea is to mimic neural networks in the human brain, which is\n", - "composed of billions of neurons that communicate with each other by\n", - "sending electrical signals. Each neuron accumulates its incoming\n", - "signals, which must exceed an activation threshold to yield an\n", - "output. If the threshold is not overcome, the neuron remains inactive,\n", - "i.e. has zero output.\n", - "\n", - "This behaviour has inspired a simple mathematical model for an artificial neuron." - ] - }, - { - "cell_type": "markdown", - "id": "663a7548", - "metadata": { - "editable": true - }, - "source": [ - "\n", - "
\n", - "\n", - "$$\n", - "\\begin{equation}\n", - " y = f\\left(\\sum_{i=1}^n w_ix_i\\right) = f(u)\n", - "\\label{artificialNeuron} \\tag{6}\n", - "\\end{equation}\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "7d41caae", - "metadata": { - "editable": true - }, - "source": [ - "Here, the output $y$ of the neuron is the value of its activation function, which have as input\n", - "a weighted sum of signals $x_i, \\dots ,x_n$ received by $n$ other neurons.\n", - "\n", - "Conceptually, it is helpful to divide neural networks into four\n", - "categories:\n", - "1. general purpose neural networks for supervised learning,\n", - "\n", - "2. neural networks designed specifically for image processing, the most prominent example of this class being Convolutional Neural Networks (CNNs),\n", - "\n", - "3. neural networks for sequential data such as Recurrent Neural Networks (RNNs), and\n", - "\n", - "4. neural networks for unsupervised learning such as Deep Boltzmann Machines.\n", - "\n", - "In natural science, DNNs and CNNs have already found numerous\n", - "applications. In statistical physics, they have been applied to detect\n", - "phase transitions in 2D Ising and Potts models, lattice gauge\n", - "theories, and different phases of polymers, or solving the\n", - "Navier-Stokes equation in weather forecasting. Deep learning has also\n", - "found interesting applications in quantum physics. Various quantum\n", - "phase transitions can be detected and studied using DNNs and CNNs,\n", - "topological phases, and even non-equilibrium many-body\n", - "localization. Representing quantum states as DNNs quantum state\n", - "tomography are among some of the impressive achievements to reveal the\n", - "potential of DNNs to facilitate the study of quantum systems.\n", - "\n", - "In quantum information theory, it has been shown that one can perform\n", - "gate decompositions with the help of neural. \n", - "\n", - "The applications are not limited to the natural sciences. There is a\n", - "plethora of applications in essentially all disciplines, from the\n", - "humanities to life science and medicine." - ] - }, - { - "cell_type": "markdown", - "id": "8cd5fa1c", - "metadata": { - "editable": true - }, - "source": [ - "## Neural network types\n", - "\n", - "An artificial neural network (ANN), is a computational model that\n", - "consists of layers of connected neurons, or nodes or units. We will\n", - "refer to these interchangeably as units or nodes, and sometimes as\n", - "neurons.\n", - "\n", - "It is supposed to mimic a biological nervous system by letting each\n", - "neuron interact with other neurons by sending signals in the form of\n", - "mathematical functions between layers. A wide variety of different\n", - "ANNs have been developed, but most of them consist of an input layer,\n", - "an output layer and eventual layers in-between, called *hidden\n", - "layers*. All layers can contain an arbitrary number of nodes, and each\n", - "connection between two nodes is associated with a weight variable.\n", - "\n", - "Neural networks (also called neural nets) are neural-inspired\n", - "nonlinear models for supervised learning. As we will see, neural nets\n", - "can be viewed as natural, more powerful extensions of supervised\n", - "learning methods such as linear and logistic regression and soft-max\n", - "methods we discussed earlier." - ] - }, - { - "cell_type": "markdown", - "id": "0b2c6e40", - "metadata": { - "editable": true - }, - "source": [ - "## Feed-forward neural networks\n", - "\n", - "The feed-forward neural network (FFNN) was the first and simplest type\n", - "of ANNs that were devised. In this network, the information moves in\n", - "only one direction: forward through the layers.\n", - "\n", - "Nodes are represented by circles, while the arrows display the\n", - "connections between the nodes, including the direction of information\n", - "flow. Additionally, each arrow corresponds to a weight variable\n", - "(figure to come). We observe that each node in a layer is connected\n", - "to *all* nodes in the subsequent layer, making this a so-called\n", - "*fully-connected* FFNN." - ] - }, - { - "cell_type": "markdown", - "id": "90e946b7", - "metadata": { - "editable": true - }, - "source": [ - "## Convolutional Neural Network\n", - "\n", - "A different variant of FFNNs are *convolutional neural networks*\n", - "(CNNs), which have a connectivity pattern inspired by the animal\n", - "visual cortex. Individual neurons in the visual cortex only respond to\n", - "stimuli from small sub-regions of the visual field, called a receptive\n", - "field. This makes the neurons well-suited to exploit the strong\n", - "spatially local correlation present in natural images. The response of\n", - "each neuron can be approximated mathematically as a convolution\n", - "operation. (figure to come)\n", - "\n", - "Convolutional neural networks emulate the behaviour of neurons in the\n", - "visual cortex by enforcing a *local* connectivity pattern between\n", - "nodes of adjacent layers: Each node in a convolutional layer is\n", - "connected only to a subset of the nodes in the previous layer, in\n", - "contrast to the fully-connected FFNN. Often, CNNs consist of several\n", - "convolutional layers that learn local features of the input, with a\n", - "fully-connected layer at the end, which gathers all the local data and\n", - "produces the outputs. They have wide applications in image and video\n", - "recognition." - ] - }, - { - "cell_type": "markdown", - "id": "1964f9e3", - "metadata": { - "editable": true - }, - "source": [ - "## Recurrent neural networks\n", - "\n", - "So far we have only mentioned ANNs where information flows in one\n", - "direction: forward. *Recurrent neural networks* on the other hand,\n", - "have connections between nodes that form directed *cycles*. This\n", - "creates a form of internal memory which are able to capture\n", - "information on what has been calculated before; the output is\n", - "dependent on the previous computations. Recurrent NNs make use of\n", - "sequential information by performing the same task for every element\n", - "in a sequence, where each element depends on previous elements. An\n", - "example of such information is sentences, making recurrent NNs\n", - "especially well-suited for handwriting and speech recognition." - ] - }, - { - "cell_type": "markdown", - "id": "faf981a1", - "metadata": { - "editable": true - }, - "source": [ - "## Other types of networks\n", - "\n", - "There are many other kinds of ANNs that have been developed. One type\n", - "that is specifically designed for interpolation in multidimensional\n", - "space is the radial basis function (RBF) network. RBFs are typically\n", - "made up of three layers: an input layer, a hidden layer with\n", - "non-linear radial symmetric activation functions and a linear output\n", - "layer (''linear'' here means that each node in the output layer has a\n", - "linear activation function). The layers are normally fully-connected\n", - "and there are no cycles, thus RBFs can be viewed as a type of\n", - "fully-connected FFNN. They are however usually treated as a separate\n", - "type of NN due the unusual activation functions." - ] - }, - { - "cell_type": "markdown", - "id": "3667182a", - "metadata": { - "editable": true - }, - "source": [ - "## Multilayer perceptrons\n", - "\n", - "One uses often so-called fully-connected feed-forward neural networks\n", - "with three or more layers (an input layer, one or more hidden layers\n", - "and an output layer) consisting of neurons that have non-linear\n", - "activation functions.\n", - "\n", - "Such networks are often called *multilayer perceptrons* (MLPs)." - ] - }, - { - "cell_type": "markdown", - "id": "5dd1a89f", - "metadata": { - "editable": true - }, - "source": [ - "## Why multilayer perceptrons?\n", - "\n", - "According to the *Universal approximation theorem*, a feed-forward\n", - "neural network with just a single hidden layer containing a finite\n", - "number of neurons can approximate a continuous multidimensional\n", - "function to arbitrary accuracy, assuming the activation function for\n", - "the hidden layer is a **non-constant, bounded and\n", - "monotonically-increasing continuous function**.\n", - "\n", - "Note that the requirements on the activation function only applies to\n", - "the hidden layer, the output nodes are always assumed to be linear, so\n", - "as to not restrict the range of output values." - ] - }, - { - "cell_type": "markdown", - "id": "da5b8927", - "metadata": { - "editable": true - }, - "source": [ - "## Illustration of a single perceptron model and a multi-perceptron model\n", - "\n", - "\n", - "\n", - "\n", - "

Figure 1: In a) we show a single perceptron model while in b) we dispay a network with two hidden layers, an input layer and an output layer.

\n", - "" - ] - }, - { - "cell_type": "markdown", - "id": "3bba849e", - "metadata": { - "editable": true - }, - "source": [ - "## Examples of XOR, OR and AND gates\n", - "\n", - "Let us first try to fit various gates using standard linear\n", - "regression. The gates we are thinking of are the classical XOR, OR and\n", - "AND gates, well-known elements in computer science. The tables here\n", - "show how we can set up the inputs $x_1$ and $x_2$ in order to yield a\n", - "specific target $y_i$." - ] - }, - { - "cell_type": "code", - "execution_count": 27, - "id": "de11d95e", - "metadata": { - "collapsed": false, - "editable": true - }, - "outputs": [], - "source": [ - "\"\"\"\n", - "Simple code that tests XOR, OR and AND gates with linear regression\n", - "\"\"\"\n", - "\n", - "import numpy as np\n", - "# Design matrix\n", - "X = np.array([ [1, 0, 0], [1, 0, 1], [1, 1, 0],[1, 1, 1]],dtype=np.float64)\n", - "print(f\"The X.TX matrix:{X.T @ X}\")\n", - "Xinv = np.linalg.pinv(X.T @ X)\n", - "print(f\"The invers of X.TX matrix:{Xinv}\")\n", - "\n", - "# The XOR gate \n", - "yXOR = np.array( [ 0, 1 ,1, 0])\n", - "ThetaXOR = Xinv @ X.T @ yXOR\n", - "print(f\"The values of theta for the XOR gate:{ThetaXOR}\")\n", - "print(f\"The linear regression prediction for the XOR gate:{X @ ThetaXOR}\")\n", - "\n", - "\n", - "# The OR gate \n", - "yOR = np.array( [ 0, 1 ,1, 1])\n", - "ThetaOR = Xinv @ X.T @ yOR\n", - "print(f\"The values of theta for the OR gate:{ThetaOR}\")\n", - "print(f\"The linear regression prediction for the OR gate:{X @ ThetaOR}\")\n", - "\n", - "\n", - "# The OR gate \n", - "yAND = np.array( [ 0, 0 ,0, 1])\n", - "ThetaAND = Xinv @ X.T @ yAND\n", - "print(f\"The values of theta for the AND gate:{ThetaAND}\")\n", - "print(f\"The linear regression prediction for the AND gate:{X @ ThetaAND}\")" - ] - }, - { - "cell_type": "markdown", - "id": "b0477050", - "metadata": { - "editable": true - }, - "source": [ - "What is happening here?" - ] - }, - { - "cell_type": "markdown", - "id": "1d72d90e", - "metadata": { - "editable": true - }, - "source": [ - "## Does Logistic Regression do a better Job?" - ] - }, - { - "cell_type": "code", - "execution_count": 28, - "id": "501aa7b5", - "metadata": { - "collapsed": false, - "editable": true - }, - "outputs": [], - "source": [ - "\"\"\"\n", - "Simple code that tests XOR and OR gates with linear regression\n", - "and logistic regression\n", - "\"\"\"\n", - "\n", - "import matplotlib.pyplot as plt\n", - "from sklearn.linear_model import LogisticRegression\n", - "import numpy as np\n", - "\n", - "# Design matrix\n", - "X = np.array([ [1, 0, 0], [1, 0, 1], [1, 1, 0],[1, 1, 1]],dtype=np.float64)\n", - "print(f\"The X.TX matrix:{X.T @ X}\")\n", - "Xinv = np.linalg.pinv(X.T @ X)\n", - "print(f\"The invers of X.TX matrix:{Xinv}\")\n", - "\n", - "# The XOR gate \n", - "yXOR = np.array( [ 0, 1 ,1, 0])\n", - "ThetaXOR = Xinv @ X.T @ yXOR\n", - "print(f\"The values of theta for the XOR gate:{ThetaXOR}\")\n", - "print(f\"The linear regression prediction for the XOR gate:{X @ ThetaXOR}\")\n", - "\n", - "\n", - "# The OR gate \n", - "yOR = np.array( [ 0, 1 ,1, 1])\n", - "ThetaOR = Xinv @ X.T @ yOR\n", - "print(f\"The values of theta for the OR gate:{ThetaOR}\")\n", - "print(f\"The linear regression prediction for the OR gate:{X @ ThetaOR}\")\n", - "\n", - "\n", - "# The OR gate \n", - "yAND = np.array( [ 0, 0 ,0, 1])\n", - "ThetaAND = Xinv @ X.T @ yAND\n", - "print(f\"The values of theta for the AND gate:{ThetaAND}\")\n", - "print(f\"The linear regression prediction for the AND gate:{X @ ThetaAND}\")\n", - "\n", - "# Now we change to logistic regression\n", - "\n", - "\n", - "# Logistic Regression\n", - "logreg = LogisticRegression()\n", - "logreg.fit(X, yOR)\n", - "print(\"Test set accuracy with Logistic Regression for OR gate: {:.2f}\".format(logreg.score(X,yOR)))\n", - "\n", - "logreg.fit(X, yXOR)\n", - "print(\"Test set accuracy with Logistic Regression for XOR gate: {:.2f}\".format(logreg.score(X,yXOR)))\n", - "\n", - "\n", - "logreg.fit(X, yAND)\n", - "print(\"Test set accuracy with Logistic Regression for AND gate: {:.2f}\".format(logreg.score(X,yAND)))" - ] - }, - { - "cell_type": "markdown", - "id": "03908b42", - "metadata": { - "editable": true - }, - "source": [ - "Not exactly impressive, but somewhat better." - ] - }, - { - "cell_type": "markdown", - "id": "91971469", - "metadata": { - "editable": true - }, - "source": [ - "## Adding Neural Networks" - ] - }, - { - "cell_type": "code", - "execution_count": 29, - "id": "f1717531", - "metadata": { - "collapsed": false, - "editable": true - }, - "outputs": [], - "source": [ - "\n", - "# and now neural networks with Scikit-Learn and the XOR\n", - "\n", - "from sklearn.neural_network import MLPClassifier\n", - "from sklearn.datasets import make_classification\n", - "X, yXOR = make_classification(n_samples=100, random_state=1)\n", - "FFNN = MLPClassifier(random_state=1, max_iter=300).fit(X, yXOR)\n", - "FFNN.predict_proba(X)\n", - "print(f\"Test set accuracy with Feed Forward Neural Network for XOR gate:{FFNN.score(X, yXOR)}\")" - ] - }, - { - "cell_type": "markdown", - "id": "05726714", - "metadata": { - "editable": true - }, - "source": [ - "## Mathematical model\n", - "\n", - "The output $y$ is produced via the activation function $f$" - ] - }, - { - "cell_type": "markdown", - "id": "1cf57e1c", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "y = f\\left(\\sum_{i=1}^n w_ix_i + b_i\\right) = f(z),\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "57743f5e", - "metadata": { - "editable": true - }, - "source": [ - "This function receives $x_i$ as inputs.\n", - "Here the activation $z=(\\sum_{i=1}^n w_ix_i+b_i)$. \n", - "In an FFNN of such neurons, the *inputs* $x_i$ are the *outputs* of\n", - "the neurons in the preceding layer. Furthermore, an MLP is\n", - "fully-connected, which means that each neuron receives a weighted sum\n", - "of the outputs of *all* neurons in the previous layer." - ] - }, - { - "cell_type": "markdown", - "id": "2d3f8338", - "metadata": { - "editable": true - }, - "source": [ - "## Mathematical model\n", - "\n", - "First, for each node $i$ in the first hidden layer, we calculate a weighted sum $z_i^1$ of the input coordinates $x_j$," - ] - }, - { - "cell_type": "markdown", - "id": "20be0ccb", - "metadata": { - "editable": true - }, - "source": [ - "\n", - "
\n", - "\n", - "$$\n", - "\\begin{equation} z_i^1 = \\sum_{j=1}^{M} w_{ij}^1 x_j + b_i^1\n", - "\\label{_auto6} \\tag{7}\n", - "\\end{equation}\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "d289b4c8", - "metadata": { - "editable": true - }, - "source": [ - "Here $b_i$ is the so-called bias which is normally needed in\n", - "case of zero activation weights or inputs. How to fix the biases and\n", - "the weights will be discussed below. The value of $z_i^1$ is the\n", - "argument to the activation function $f_i$ of each node $i$, The\n", - "variable $M$ stands for all possible inputs to a given node $i$ in the\n", - "first layer. We define the output $y_i^1$ of all neurons in layer 1 as" - ] - }, - { - "cell_type": "markdown", - "id": "498c2494", - "metadata": { - "editable": true - }, - "source": [ - "\n", - "
\n", - "\n", - "$$\n", - "\\begin{equation}\n", - " y_i^1 = f(z_i^1) = f\\left(\\sum_{j=1}^M w_{ij}^1 x_j + b_i^1\\right)\n", - "\\label{outputLayer1} \\tag{8}\n", - "\\end{equation}\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "77995e5d", - "metadata": { - "editable": true - }, - "source": [ - "where we assume that all nodes in the same layer have identical\n", - "activation functions, hence the notation $f$. In general, we could assume in the more general case that different layers have different activation functions.\n", - "In this case we would identify these functions with a superscript $l$ for the $l$-th layer," - ] - }, - { - "cell_type": "markdown", - "id": "ef353d76", - "metadata": { - "editable": true - }, - "source": [ - "\n", - "
\n", - "\n", - "$$\n", - "\\begin{equation}\n", - " y_i^l = f^l(u_i^l) = f^l\\left(\\sum_{j=1}^{N_{l-1}} w_{ij}^l y_j^{l-1} + b_i^l\\right)\n", - "\\label{generalLayer} \\tag{9}\n", - "\\end{equation}\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "0a25d2f4", - "metadata": { - "editable": true - }, - "source": [ - "where $N_l$ is the number of nodes in layer $l$. When the output of\n", - "all the nodes in the first hidden layer are computed, the values of\n", - "the subsequent layer can be calculated and so forth until the output\n", - "is obtained." - ] - }, - { - "cell_type": "markdown", - "id": "d7d29703", - "metadata": { - "editable": true - }, - "source": [ - "## Mathematical model\n", - "\n", - "The output of neuron $i$ in layer 2 is thus," - ] - }, - { - "cell_type": "markdown", - "id": "94eddeb9", - "metadata": { - "editable": true - }, - "source": [ - "\n", - "
\n", - "\n", - "$$\n", - "\\begin{equation}\n", - " y_i^2 = f^2\\left(\\sum_{j=1}^N w_{ij}^2 y_j^1 + b_i^2\\right) \n", - "\\label{_auto7} \\tag{10}\n", - "\\end{equation}\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "f047f4c6", - "metadata": { - "editable": true - }, - "source": [ - "\n", - "
\n", - "\n", - "$$\n", - "\\begin{equation} \n", - " = f^2\\left[\\sum_{j=1}^N w_{ij}^2f^1\\left(\\sum_{k=1}^M w_{jk}^1 x_k + b_j^1\\right) + b_i^2\\right]\n", - "\\label{outputLayer2} \\tag{11}\n", - "\\end{equation}\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "91d4806e", - "metadata": { - "editable": true - }, - "source": [ - "where we have substituted $y_k^1$ with the inputs $x_k$. Finally, the ANN output reads" - ] - }, - { - "cell_type": "markdown", - "id": "7342e125", - "metadata": { - "editable": true - }, - "source": [ - "\n", - "
\n", - "\n", - "$$\n", - "\\begin{equation}\n", - " y_i^3 = f^3\\left(\\sum_{j=1}^N w_{ij}^3 y_j^2 + b_i^3\\right) \n", - "\\label{_auto8} \\tag{12}\n", - "\\end{equation}\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "5068e976", - "metadata": { - "editable": true - }, - "source": [ - "\n", - "
\n", - "\n", - "$$\n", - "\\begin{equation} \n", - " = f_3\\left[\\sum_{j} w_{ij}^3 f^2\\left(\\sum_{k} w_{jk}^2 f^1\\left(\\sum_{m} w_{km}^1 x_m + b_k^1\\right) + b_j^2\\right)\n", - " + b_1^3\\right]\n", - "\\label{_auto9} \\tag{13}\n", - "\\end{equation}\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "b51a241d", - "metadata": { - "editable": true - }, - "source": [ - "## Mathematical model\n", - "\n", - "We can generalize this expression to an MLP with $l$ hidden\n", - "layers. The complete functional form is," - ] - }, - { - "cell_type": "markdown", - "id": "5a7b4915", - "metadata": { - "editable": true - }, - "source": [ - "\n", - "
\n", - "\n", - "$$\n", - "\\begin{equation}\n", - "y^{l+1}_i = f^{l+1}\\left[\\!\\sum_{j=1}^{N_l} w_{ij}^3 f^l\\left(\\sum_{k=1}^{N_{l-1}}w_{jk}^{l-1}\\left(\\dots f^1\\left(\\sum_{n=1}^{N_0} w_{mn}^1 x_n+ b_m^1\\right)\\dots\\right)+b_k^2\\right)+b_1^3\\right] \n", - "\\label{completeNN} \\tag{14}\n", - "\\end{equation}\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "c3215b7f", - "metadata": { - "editable": true - }, - "source": [ - "which illustrates a basic property of MLPs: The only independent\n", - "variables are the input values $x_n$." - ] - }, - { - "cell_type": "markdown", - "id": "f92eedb0", - "metadata": { - "editable": true - }, - "source": [ - "## Mathematical model\n", - "\n", - "This confirms that an MLP, despite its quite convoluted mathematical\n", - "form, is nothing more than an analytic function, specifically a\n", - "mapping of real-valued vectors $\\hat{x} \\in \\mathbb{R}^n \\rightarrow\n", - "\\hat{y} \\in \\mathbb{R}^m$.\n", - "\n", - "Furthermore, the flexibility and universality of an MLP can be\n", - "illustrated by realizing that the expression is essentially a nested\n", - "sum of scaled activation functions of the form" - ] - }, - { - "cell_type": "markdown", - "id": "b658fa6d", - "metadata": { - "editable": true - }, - "source": [ - "\n", - "
\n", - "\n", - "$$\n", - "\\begin{equation}\n", - " f(x) = c_1 f(c_2 x + c_3) + c_4\n", - "\\label{_auto10} \\tag{15}\n", - "\\end{equation}\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "8506281a", - "metadata": { - "editable": true - }, - "source": [ - "where the parameters $c_i$ are weights and biases. By adjusting these\n", - "parameters, the activation functions can be shifted up and down or\n", - "left and right, change slope or be rescaled which is the key to the\n", - "flexibility of a neural network." - ] - }, - { - "cell_type": "markdown", - "id": "0ad3f400", - "metadata": { - "editable": true - }, - "source": [ - "### Matrix-vector notation\n", - "\n", - "We can introduce a more convenient notation for the activations in an A NN. \n", - "\n", - "Additionally, we can represent the biases and activations\n", - "as layer-wise column vectors $\\hat{b}_l$ and $\\hat{y}_l$, so that the $i$-th element of each vector \n", - "is the bias $b_i^l$ and activation $y_i^l$ of node $i$ in layer $l$ respectively. \n", - "\n", - "We have that $\\mathrm{W}_l$ is an $N_{l-1} \\times N_l$ matrix, while $\\hat{b}_l$ and $\\hat{y}_l$ are $N_l \\times 1$ column vectors. \n", - "With this notation, the sum becomes a matrix-vector multiplication, and we can write\n", - "the equation for the activations of hidden layer 2 (assuming three nodes for simplicity) as" - ] - }, - { - "cell_type": "markdown", - "id": "7b431efc", - "metadata": { - "editable": true - }, - "source": [ - "\n", - "
\n", - "\n", - "$$\n", - "\\begin{equation}\n", - " \\hat{y}_2 = f_2(\\mathrm{W}_2 \\hat{y}_{1} + \\hat{b}_{2}) = \n", - " f_2\\left(\\left[\\begin{array}{ccc}\n", - " w^2_{11} &w^2_{12} &w^2_{13} \\\\\n", - " w^2_{21} &w^2_{22} &w^2_{23} \\\\\n", - " w^2_{31} &w^2_{32} &w^2_{33} \\\\\n", - " \\end{array} \\right] \\cdot\n", - " \\left[\\begin{array}{c}\n", - " y^1_1 \\\\\n", - " y^1_2 \\\\\n", - " y^1_3 \\\\\n", - " \\end{array}\\right] + \n", - " \\left[\\begin{array}{c}\n", - " b^2_1 \\\\\n", - " b^2_2 \\\\\n", - " b^2_3 \\\\\n", - " \\end{array}\\right]\\right).\n", - "\\label{_auto11} \\tag{16}\n", - "\\end{equation}\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "d129b057", - "metadata": { - "editable": true - }, - "source": [ - "### Matrix-vector notation and activation\n", - "\n", - "The activation of node $i$ in layer 2 is" - ] - }, - { - "cell_type": "markdown", - "id": "7af14562", - "metadata": { - "editable": true - }, - "source": [ - "\n", - "
\n", - "\n", - "$$\n", - "\\begin{equation}\n", - " y^2_i = f_2\\Bigr(w^2_{i1}y^1_1 + w^2_{i2}y^1_2 + w^2_{i3}y^1_3 + b^2_i\\Bigr) = \n", - " f_2\\left(\\sum_{j=1}^3 w^2_{ij} y_j^1 + b^2_i\\right).\n", - "\\label{_auto12} \\tag{17}\n", - "\\end{equation}\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "0b7e127c", - "metadata": { - "editable": true - }, - "source": [ - "This is not just a convenient and compact notation, but also a useful\n", - "and intuitive way to think about MLPs: The output is calculated by a\n", - "series of matrix-vector multiplications and vector additions that are\n", - "used as input to the activation functions. For each operation\n", - "$\\mathrm{W}_l \\hat{y}_{l-1}$ we move forward one layer." - ] - }, - { - "cell_type": "markdown", - "id": "91266ae3", - "metadata": { - "editable": true - }, - "source": [ - "### Activation functions\n", - "\n", - "A property that characterizes a neural network, other than its\n", - "connectivity, is the choice of activation function(s). As described\n", - "in, the following restrictions are imposed on an activation function\n", - "for a FFNN to fulfill the universal approximation theorem\n", - "\n", - " * Non-constant\n", - "\n", - " * Bounded\n", - "\n", - " * Monotonically-increasing\n", - "\n", - " * Continuous" - ] - }, - { - "cell_type": "markdown", - "id": "54728fbd", - "metadata": { - "editable": true - }, - "source": [ - "### Activation functions, Logistic and Hyperbolic ones\n", - "\n", - "The second requirement excludes all linear functions. Furthermore, in\n", - "a MLP with only linear activation functions, each layer simply\n", - "performs a linear transformation of its inputs.\n", - "\n", - "Regardless of the number of layers, the output of the NN will be\n", - "nothing but a linear function of the inputs. Thus we need to introduce\n", - "some kind of non-linearity to the NN to be able to fit non-linear\n", - "functions Typical examples are the logistic *Sigmoid*" - ] - }, - { - "cell_type": "markdown", - "id": "17b851fb", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "f(x) = \\frac{1}{1 + e^{-x}},\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "6e17f015", - "metadata": { - "editable": true - }, - "source": [ - "and the *hyperbolic tangent* function" - ] - }, - { - "cell_type": "markdown", - "id": "574fbcd0", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "f(x) = \\tanh(x)\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "daa971d1", - "metadata": { - "editable": true - }, - "source": [ - "### Relevance\n", - "\n", - "The *sigmoid* function are more biologically plausible because the\n", - "output of inactive neurons are zero. Such activation function are\n", - "called *one-sided*. However, it has been shown that the hyperbolic\n", - "tangent performs better than the sigmoid for training MLPs. has\n", - "become the most popular for *deep neural networks*" - ] - }, - { - "cell_type": "code", - "execution_count": 30, - "id": "c12bc7fe", - "metadata": { - "collapsed": false, - "editable": true - }, - "outputs": [], - "source": [ - "\"\"\"The sigmoid function (or the logistic curve) is a \n", - "function that takes any real number, z, and outputs a number (0,1).\n", - "It is useful in neural networks for assigning weights on a relative scale.\n", - "The value z is the weighted sum of parameters involved in the learning algorithm.\"\"\"\n", - "\n", - "import numpy\n", - "import matplotlib.pyplot as plt\n", - "import math as mt\n", - "\n", - "z = numpy.arange(-5, 5, .1)\n", - "sigma_fn = numpy.vectorize(lambda z: 1/(1+numpy.exp(-z)))\n", - "sigma = sigma_fn(z)\n", - "\n", - "fig = plt.figure()\n", - "ax = fig.add_subplot(111)\n", - "ax.plot(z, sigma)\n", - "ax.set_ylim([-0.1, 1.1])\n", - "ax.set_xlim([-5,5])\n", - "ax.grid(True)\n", - "ax.set_xlabel('z')\n", - "ax.set_title('sigmoid function')\n", - "\n", - "plt.show()\n", - "\n", - "\"\"\"Step Function\"\"\"\n", - "z = numpy.arange(-5, 5, .02)\n", - "step_fn = numpy.vectorize(lambda z: 1.0 if z >= 0.0 else 0.0)\n", - "step = step_fn(z)\n", - "\n", - "fig = plt.figure()\n", - "ax = fig.add_subplot(111)\n", - "ax.plot(z, step)\n", - "ax.set_ylim([-0.5, 1.5])\n", - "ax.set_xlim([-5,5])\n", - "ax.grid(True)\n", - "ax.set_xlabel('z')\n", - "ax.set_title('step function')\n", - "\n", - "plt.show()\n", - "\n", - "\"\"\"Sine Function\"\"\"\n", - "z = numpy.arange(-2*mt.pi, 2*mt.pi, 0.1)\n", - "t = numpy.sin(z)\n", - "\n", - "fig = plt.figure()\n", - "ax = fig.add_subplot(111)\n", - "ax.plot(z, t)\n", - "ax.set_ylim([-1.0, 1.0])\n", - "ax.set_xlim([-2*mt.pi,2*mt.pi])\n", - "ax.grid(True)\n", - "ax.set_xlabel('z')\n", - "ax.set_title('sine function')\n", - "\n", - "plt.show()\n", - "\n", - "\"\"\"Plots a graph of the squashing function used by a rectified linear\n", - "unit\"\"\"\n", - "z = numpy.arange(-2, 2, .1)\n", - "zero = numpy.zeros(len(z))\n", - "y = numpy.max([zero, z], axis=0)\n", - "\n", - "fig = plt.figure()\n", - "ax = fig.add_subplot(111)\n", - "ax.plot(z, y)\n", - "ax.set_ylim([-2.0, 2.0])\n", - "ax.set_xlim([-2.0, 2.0])\n", - "ax.grid(True)\n", - "ax.set_xlabel('z')\n", - "ax.set_title('Rectified linear unit')\n", - "\n", - "plt.show()" - ] - } - ], - "metadata": {}, - "nbformat": 4, - "nbformat_minor": 5 -} diff --git a/doc/LectureNotes/week41.ipynb b/doc/LectureNotes/week41.ipynb deleted file mode 100644 index 7c1e7c629..000000000 --- a/doc/LectureNotes/week41.ipynb +++ /dev/null @@ -1,3537 +0,0 @@ -{ - "cells": [ - { - "cell_type": "markdown", - "id": "9a4eccc2", - "metadata": {}, - "source": [ - "\n", - "" - ] - }, - { - "cell_type": "markdown", - "id": "243c5d47", - "metadata": {}, - "source": [ - "# Week 41 Neural networks and constructing a neural network code\n", - "**Morten Hjorth-Jensen**, Department of Physics, University of Oslo and Department of Physics and Astronomy and Facility for Rare Isotope Beams, Michigan State University\n", - "\n", - "Date: **Week 41**" - ] - }, - { - "cell_type": "markdown", - "id": "0cae636e", - "metadata": {}, - "source": [ - "## Plan for week 41\n", - "\n", - "**Material for the active learning sessions on Tuesday and Wednesday.**\n", - "\n", - " * Exercise on writing your own stochastic gradient and gradient descent codes. This exercise continues next week with studies of automatic differentiation\n", - "\n", - " * One lecture at the beginning of each session on the material from weeks 39 and 40 and how to write your own gradient descent code\n", - "\n", - " * Discussion of project 2\n", - "\n", - " * Your task before the sessions: revisit the material from weeks 39 and 40 and in particular the material from week 40 on stochastic gradient descent\n", - "\n", - " \n", - "\n", - "**Material for the lecture on Thursday October 12, 2023.**\n", - "\n", - " * Neural Networks, setting up the basic steps, from the simple perceptron model to the multi-layer perceptron model.\n", - "\n", - " * Building our own Feed-forward Neural Network\n", - "\n", - " * [Video of lecture notes](https://youtu.be/5-RRTO9uDvI)\n", - "\n", - " * [Whiteboard notes](https://github.com/CompPhysics/MachineLearning/blob/master/doc/HandWrittenNotes/2023/NotesOct12.pdf)\n", - "\n", - " * Readings and Videos:\n", - "\n", - " * These lecture notes\n", - "\n", - " * For neural networks we recommend Goodfellow et al chapter 6.\n", - "\n", - " * [Neural Networks demystified](https://www.youtube.com/watch?v=bxe2T-V8XRs&list=PLiaHhY2iBX9hdHaRr6b7XevZtgZRa1PoU&ab_channel=WelchLabs)\n", - "\n", - " * [Building Neural Networks from scratch](https://www.youtube.com/watch?v=Wo5dMEP_BbI&list=PLQVvvaa0QuDcjD5BAw2DxE6OF2tius3V3&ab_channel=sentdex)\n", - "\n", - " * [Video on Neural Networks](https://www.youtube.com/watch?v=CqOfi41LfDw)\n", - "\n", - " * [Video on the back propagation algorithm](https://www.youtube.com/watch?v=Ilg3gGewQ5U)\n", - "\n", - "I also recommend Michael Nielsen's intuitive approach to the neural networks and the universal approximation theorem, see the slides at ." - ] - }, - { - "cell_type": "markdown", - "id": "51ff64f7", - "metadata": {}, - "source": [ - "## Lecture Thursday October 12" - ] - }, - { - "cell_type": "markdown", - "id": "07ff4601", - "metadata": {}, - "source": [ - "## Introduction to Neural networks\n", - "\n", - "Artificial neural networks are computational systems that can learn to\n", - "perform tasks by considering examples, generally without being\n", - "programmed with any task-specific rules. It is supposed to mimic a\n", - "biological system, wherein neurons interact by sending signals in the\n", - "form of mathematical functions between layers. All layers can contain\n", - "an arbitrary number of neurons, and each connection is represented by\n", - "a weight variable." - ] - }, - { - "cell_type": "markdown", - "id": "4806cddf", - "metadata": {}, - "source": [ - "## Artificial neurons\n", - "\n", - "The field of artificial neural networks has a long history of\n", - "development, and is closely connected with the advancement of computer\n", - "science and computers in general. A model of artificial neurons was\n", - "first developed by McCulloch and Pitts in 1943 to study signal\n", - "processing in the brain and has later been refined by others. The\n", - "general idea is to mimic neural networks in the human brain, which is\n", - "composed of billions of neurons that communicate with each other by\n", - "sending electrical signals. Each neuron accumulates its incoming\n", - "signals, which must exceed an activation threshold to yield an\n", - "output. If the threshold is not overcome, the neuron remains inactive,\n", - "i.e. has zero output.\n", - "\n", - "This behaviour has inspired a simple mathematical model for an artificial neuron." - ] - }, - { - "cell_type": "markdown", - "id": "ccfdcf2b", - "metadata": {}, - "source": [ - "\n", - "
\n", - "\n", - "$$\n", - "\\begin{equation}\n", - " y = f\\left(\\sum_{i=1}^n w_ix_i\\right) = f(u)\n", - "\\label{artificialNeuron} \\tag{1}\n", - "\\end{equation}\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "900fd38b", - "metadata": {}, - "source": [ - "Here, the output $y$ of the neuron is the value of its activation function, which have as input\n", - "a weighted sum of signals $x_i, \\dots ,x_n$ received by $n$ other neurons.\n", - "\n", - "Conceptually, it is helpful to divide neural networks into four\n", - "categories:\n", - "1. general purpose neural networks for supervised learning,\n", - "\n", - "2. neural networks designed specifically for image processing, the most prominent example of this class being Convolutional Neural Networks (CNNs),\n", - "\n", - "3. neural networks for sequential data such as Recurrent Neural Networks (RNNs), and\n", - "\n", - "4. neural networks for unsupervised learning such as Deep Boltzmann Machines.\n", - "\n", - "In natural science, DNNs and CNNs have already found numerous\n", - "applications. In statistical physics, they have been applied to detect\n", - "phase transitions in 2D Ising and Potts models, lattice gauge\n", - "theories, and different phases of polymers, or solving the\n", - "Navier-Stokes equation in weather forecasting. Deep learning has also\n", - "found interesting applications in quantum physics. Various quantum\n", - "phase transitions can be detected and studied using DNNs and CNNs,\n", - "topological phases, and even non-equilibrium many-body\n", - "localization. Representing quantum states as DNNs quantum state\n", - "tomography are among some of the impressive achievements to reveal the\n", - "potential of DNNs to facilitate the study of quantum systems.\n", - "\n", - "In quantum information theory, it has been shown that one can perform\n", - "gate decompositions with the help of neural. \n", - "\n", - "The applications are not limited to the natural sciences. There is a\n", - "plethora of applications in essentially all disciplines, from the\n", - "humanities to life science and medicine." - ] - }, - { - "cell_type": "markdown", - "id": "15e0098f", - "metadata": {}, - "source": [ - "## Neural network types\n", - "\n", - "An artificial neural network (ANN), is a computational model that\n", - "consists of layers of connected neurons, or nodes or units. We will\n", - "refer to these interchangeably as units or nodes, and sometimes as\n", - "neurons.\n", - "\n", - "It is supposed to mimic a biological nervous system by letting each\n", - "neuron interact with other neurons by sending signals in the form of\n", - "mathematical functions between layers. A wide variety of different\n", - "ANNs have been developed, but most of them consist of an input layer,\n", - "an output layer and eventual layers in-between, called *hidden\n", - "layers*. All layers can contain an arbitrary number of nodes, and each\n", - "connection between two nodes is associated with a weight variable.\n", - "\n", - "Neural networks (also called neural nets) are neural-inspired\n", - "nonlinear models for supervised learning. As we will see, neural nets\n", - "can be viewed as natural, more powerful extensions of supervised\n", - "learning methods such as linear and logistic regression and soft-max\n", - "methods we discussed earlier." - ] - }, - { - "cell_type": "markdown", - "id": "70d3fe5d", - "metadata": {}, - "source": [ - "## Feed-forward neural networks\n", - "\n", - "The feed-forward neural network (FFNN) was the first and simplest type\n", - "of ANNs that were devised. In this network, the information moves in\n", - "only one direction: forward through the layers.\n", - "\n", - "Nodes are represented by circles, while the arrows display the\n", - "connections between the nodes, including the direction of information\n", - "flow. Additionally, each arrow corresponds to a weight variable\n", - "(figure to come). We observe that each node in a layer is connected\n", - "to *all* nodes in the subsequent layer, making this a so-called\n", - "*fully-connected* FFNN." - ] - }, - { - "cell_type": "markdown", - "id": "838210ba", - "metadata": {}, - "source": [ - "## Convolutional Neural Network\n", - "\n", - "A different variant of FFNNs are *convolutional neural networks*\n", - "(CNNs), which have a connectivity pattern inspired by the animal\n", - "visual cortex. Individual neurons in the visual cortex only respond to\n", - "stimuli from small sub-regions of the visual field, called a receptive\n", - "field. This makes the neurons well-suited to exploit the strong\n", - "spatially local correlation present in natural images. The response of\n", - "each neuron can be approximated mathematically as a convolution\n", - "operation. (figure to come)\n", - "\n", - "Convolutional neural networks emulate the behaviour of neurons in the\n", - "visual cortex by enforcing a *local* connectivity pattern between\n", - "nodes of adjacent layers: Each node in a convolutional layer is\n", - "connected only to a subset of the nodes in the previous layer, in\n", - "contrast to the fully-connected FFNN. Often, CNNs consist of several\n", - "convolutional layers that learn local features of the input, with a\n", - "fully-connected layer at the end, which gathers all the local data and\n", - "produces the outputs. They have wide applications in image and video\n", - "recognition." - ] - }, - { - "cell_type": "markdown", - "id": "8a78d22d", - "metadata": {}, - "source": [ - "## Recurrent neural networks\n", - "\n", - "So far we have only mentioned ANNs where information flows in one\n", - "direction: forward. *Recurrent neural networks* on the other hand,\n", - "have connections between nodes that form directed *cycles*. This\n", - "creates a form of internal memory which are able to capture\n", - "information on what has been calculated before; the output is\n", - "dependent on the previous computations. Recurrent NNs make use of\n", - "sequential information by performing the same task for every element\n", - "in a sequence, where each element depends on previous elements. An\n", - "example of such information is sentences, making recurrent NNs\n", - "especially well-suited for handwriting and speech recognition." - ] - }, - { - "cell_type": "markdown", - "id": "4ca0b479", - "metadata": {}, - "source": [ - "## Other types of networks\n", - "\n", - "There are many other kinds of ANNs that have been developed. One type\n", - "that is specifically designed for interpolation in multidimensional\n", - "space is the radial basis function (RBF) network. RBFs are typically\n", - "made up of three layers: an input layer, a hidden layer with\n", - "non-linear radial symmetric activation functions and a linear output\n", - "layer (''linear'' here means that each node in the output layer has a\n", - "linear activation function). The layers are normally fully-connected\n", - "and there are no cycles, thus RBFs can be viewed as a type of\n", - "fully-connected FFNN. They are however usually treated as a separate\n", - "type of NN due the unusual activation functions." - ] - }, - { - "cell_type": "markdown", - "id": "b80ebf1a", - "metadata": {}, - "source": [ - "## Multilayer perceptrons\n", - "\n", - "One uses often so-called fully-connected feed-forward neural networks\n", - "with three or more layers (an input layer, one or more hidden layers\n", - "and an output layer) consisting of neurons that have non-linear\n", - "activation functions.\n", - "\n", - "Such networks are often called *multilayer perceptrons* (MLPs)." - ] - }, - { - "cell_type": "markdown", - "id": "749545b4", - "metadata": {}, - "source": [ - "## Why multilayer perceptrons?\n", - "\n", - "According to the *Universal approximation theorem*, a feed-forward\n", - "neural network with just a single hidden layer containing a finite\n", - "number of neurons can approximate a continuous multidimensional\n", - "function to arbitrary accuracy, assuming the activation function for\n", - "the hidden layer is a **non-constant, bounded and\n", - "monotonically-increasing continuous function**.\n", - "\n", - "Note that the requirements on the activation function only applies to\n", - "the hidden layer, the output nodes are always assumed to be linear, so\n", - "as to not restrict the range of output values." - ] - }, - { - "cell_type": "markdown", - "id": "f524768e", - "metadata": {}, - "source": [ - "## Illustration of a single perceptron model and a multi-perceptron model\n", - "\n", - "\n", - "\n", - "\n", - "

Figure 1: In a) we show a single perceptron model while in b) we dispay a network with two hidden layers, an input layer and an output layer.

\n", - "" - ] - }, - { - "cell_type": "markdown", - "id": "6c2f8b44", - "metadata": {}, - "source": [ - "## Examples of XOR, OR and AND gates\n", - "\n", - "Let us first try to fit various gates using standard linear\n", - "regression. The gates we are thinking of are the classical XOR, OR and\n", - "AND gates, well-known elements in computer science. The tables here\n", - "show how we can set up the inputs $x_1$ and $x_2$ in order to yield a\n", - "specific target $y_i$." - ] - }, - { - "cell_type": "code", - "execution_count": 1, - "id": "8dfb9c06", - "metadata": {}, - "outputs": [], - "source": [ - "\"\"\"\n", - "Simple code that tests XOR, OR and AND gates with linear regression\n", - "\"\"\"\n", - "\n", - "import numpy as np\n", - "# Design matrix\n", - "X = np.array([ [1, 0, 0], [1, 0, 1], [1, 1, 0],[1, 1, 1]],dtype=np.float64)\n", - "print(f\"The X.TX matrix:{X.T @ X}\")\n", - "Xinv = np.linalg.pinv(X.T @ X)\n", - "print(f\"The invers of X.TX matrix:{Xinv}\")\n", - "\n", - "# The XOR gate \n", - "yXOR = np.array( [ 0, 1 ,1, 0])\n", - "ThetaXOR = Xinv @ X.T @ yXOR\n", - "print(f\"The values of theta for the XOR gate:{ThetaXOR}\")\n", - "print(f\"The linear regression prediction for the XOR gate:{X @ ThetaXOR}\")\n", - "\n", - "\n", - "# The OR gate \n", - "yOR = np.array( [ 0, 1 ,1, 1])\n", - "ThetaOR = Xinv @ X.T @ yOR\n", - "print(f\"The values of theta for the OR gate:{ThetaOR}\")\n", - "print(f\"The linear regression prediction for the OR gate:{X @ ThetaOR}\")\n", - "\n", - "\n", - "# The OR gate \n", - "yAND = np.array( [ 0, 0 ,0, 1])\n", - "ThetaAND = Xinv @ X.T @ yAND\n", - "print(f\"The values of theta for the AND gate:{ThetaAND}\")\n", - "print(f\"The linear regression prediction for the AND gate:{X @ ThetaAND}\")" - ] - }, - { - "cell_type": "markdown", - "id": "b0033599", - "metadata": {}, - "source": [ - "What is happening here?" - ] - }, - { - "cell_type": "markdown", - "id": "4663d22e", - "metadata": {}, - "source": [ - "## Does Logistic Regression do a better Job?" - ] - }, - { - "cell_type": "code", - "execution_count": 2, - "id": "846ae942", - "metadata": {}, - "outputs": [], - "source": [ - "%matplotlib inline\n", - "\n", - "\"\"\"\n", - "Simple code that tests XOR and OR gates with linear regression\n", - "and logistic regression\n", - "\"\"\"\n", - "\n", - "import matplotlib.pyplot as plt\n", - "from sklearn.linear_model import LogisticRegression\n", - "import numpy as np\n", - "\n", - "# Design matrix\n", - "X = np.array([ [1, 0, 0], [1, 0, 1], [1, 1, 0],[1, 1, 1]],dtype=np.float64)\n", - "print(f\"The X.TX matrix:{X.T @ X}\")\n", - "Xinv = np.linalg.pinv(X.T @ X)\n", - "print(f\"The invers of X.TX matrix:{Xinv}\")\n", - "\n", - "# The XOR gate \n", - "yXOR = np.array( [ 0, 1 ,1, 0])\n", - "ThetaXOR = Xinv @ X.T @ yXOR\n", - "print(f\"The values of theta for the XOR gate:{ThetaXOR}\")\n", - "print(f\"The linear regression prediction for the XOR gate:{X @ ThetaXOR}\")\n", - "\n", - "\n", - "# The OR gate \n", - "yOR = np.array( [ 0, 1 ,1, 1])\n", - "ThetaOR = Xinv @ X.T @ yOR\n", - "print(f\"The values of theta for the OR gate:{ThetaOR}\")\n", - "print(f\"The linear regression prediction for the OR gate:{X @ ThetaOR}\")\n", - "\n", - "\n", - "# The OR gate \n", - "yAND = np.array( [ 0, 0 ,0, 1])\n", - "ThetaAND = Xinv @ X.T @ yAND\n", - "print(f\"The values of theta for the AND gate:{ThetaAND}\")\n", - "print(f\"The linear regression prediction for the AND gate:{X @ ThetaAND}\")\n", - "\n", - "# Now we change to logistic regression\n", - "\n", - "\n", - "# Logistic Regression\n", - "logreg = LogisticRegression()\n", - "logreg.fit(X, yOR)\n", - "print(\"Test set accuracy with Logistic Regression for OR gate: {:.2f}\".format(logreg.score(X,yOR)))\n", - "\n", - "logreg.fit(X, yXOR)\n", - "print(\"Test set accuracy with Logistic Regression for XOR gate: {:.2f}\".format(logreg.score(X,yXOR)))\n", - "\n", - "\n", - "logreg.fit(X, yAND)\n", - "print(\"Test set accuracy with Logistic Regression for AND gate: {:.2f}\".format(logreg.score(X,yAND)))" - ] - }, - { - "cell_type": "markdown", - "id": "22786e56", - "metadata": {}, - "source": [ - "Not exactly impressive, but somewhat better." - ] - }, - { - "cell_type": "markdown", - "id": "b6bdebe1", - "metadata": {}, - "source": [ - "## Adding Neural Networks" - ] - }, - { - "cell_type": "code", - "execution_count": 3, - "id": "fdfb8244", - "metadata": {}, - "outputs": [], - "source": [ - "\n", - "# and now neural networks with Scikit-Learn and the XOR\n", - "\n", - "from sklearn.neural_network import MLPClassifier\n", - "from sklearn.datasets import make_classification\n", - "X, yXOR = make_classification(n_samples=100, random_state=1)\n", - "FFNN = MLPClassifier(random_state=1, max_iter=300).fit(X, yXOR)\n", - "FFNN.predict_proba(X)\n", - "print(f\"Test set accuracy with Feed Forward Neural Network for XOR gate:{FFNN.score(X, yXOR)}\")" - ] - }, - { - "cell_type": "markdown", - "id": "13c5155d", - "metadata": {}, - "source": [ - "## Mathematical model\n", - "\n", - "The output $y$ is produced via the activation function $f$" - ] - }, - { - "cell_type": "markdown", - "id": "47b4c719", - "metadata": {}, - "source": [ - "$$\n", - "y = f\\left(\\sum_{i=1}^n w_ix_i + b_i\\right) = f(z),\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "d65d78c7", - "metadata": {}, - "source": [ - "This function receives $x_i$ as inputs.\n", - "Here the activation $z=(\\sum_{i=1}^n w_ix_i+b_i)$. \n", - "In an FFNN of such neurons, the *inputs* $x_i$ are the *outputs* of\n", - "the neurons in the preceding layer. Furthermore, an MLP is\n", - "fully-connected, which means that each neuron receives a weighted sum\n", - "of the outputs of *all* neurons in the previous layer." - ] - }, - { - "cell_type": "markdown", - "id": "b8605d0d", - "metadata": {}, - "source": [ - "## Mathematical model\n", - "\n", - "First, for each node $i$ in the first hidden layer, we calculate a weighted sum $z_i^1$ of the input coordinates $x_j$," - ] - }, - { - "cell_type": "markdown", - "id": "be0a2d56", - "metadata": {}, - "source": [ - "\n", - "
\n", - "\n", - "$$\n", - "\\begin{equation} z_i^1 = \\sum_{j=1}^{M} w_{ij}^1 x_j + b_i^1\n", - "\\label{_auto1} \\tag{2}\n", - "\\end{equation}\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "8a8ec932", - "metadata": {}, - "source": [ - "Here $b_i$ is the so-called bias which is normally needed in\n", - "case of zero activation weights or inputs. How to fix the biases and\n", - "the weights will be discussed below. The value of $z_i^1$ is the\n", - "argument to the activation function $f_i$ of each node $i$, The\n", - "variable $M$ stands for all possible inputs to a given node $i$ in the\n", - "first layer. We define the output $y_i^1$ of all neurons in layer 1 as" - ] - }, - { - "cell_type": "markdown", - "id": "30b5df75", - "metadata": {}, - "source": [ - "\n", - "
\n", - "\n", - "$$\n", - "\\begin{equation}\n", - " y_i^1 = f(z_i^1) = f\\left(\\sum_{j=1}^M w_{ij}^1 x_j + b_i^1\\right)\n", - "\\label{outputLayer1} \\tag{3}\n", - "\\end{equation}\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "9906f339", - "metadata": {}, - "source": [ - "where we assume that all nodes in the same layer have identical\n", - "activation functions, hence the notation $f$. In general, we could assume in the more general case that different layers have different activation functions.\n", - "In this case we would identify these functions with a superscript $l$ for the $l$-th layer," - ] - }, - { - "cell_type": "markdown", - "id": "705c18d2", - "metadata": {}, - "source": [ - "\n", - "
\n", - "\n", - "$$\n", - "\\begin{equation}\n", - " y_i^l = f^l(u_i^l) = f^l\\left(\\sum_{j=1}^{N_{l-1}} w_{ij}^l y_j^{l-1} + b_i^l\\right)\n", - "\\label{generalLayer} \\tag{4}\n", - "\\end{equation}\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "c0779fc6", - "metadata": {}, - "source": [ - "where $N_l$ is the number of nodes in layer $l$. When the output of\n", - "all the nodes in the first hidden layer are computed, the values of\n", - "the subsequent layer can be calculated and so forth until the output\n", - "is obtained." - ] - }, - { - "cell_type": "markdown", - "id": "128a41e3", - "metadata": {}, - "source": [ - "## Mathematical model\n", - "\n", - "The output of neuron $i$ in layer 2 is thus," - ] - }, - { - "cell_type": "markdown", - "id": "e8efb8a6", - "metadata": {}, - "source": [ - "\n", - "
\n", - "\n", - "$$\n", - "\\begin{equation}\n", - " y_i^2 = f^2\\left(\\sum_{j=1}^N w_{ij}^2 y_j^1 + b_i^2\\right) \n", - "\\label{_auto2} \\tag{5}\n", - "\\end{equation}\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "f975dcc6", - "metadata": {}, - "source": [ - "\n", - "
\n", - "\n", - "$$\n", - "\\begin{equation} \n", - " = f^2\\left[\\sum_{j=1}^N w_{ij}^2f^1\\left(\\sum_{k=1}^M w_{jk}^1 x_k + b_j^1\\right) + b_i^2\\right]\n", - "\\label{outputLayer2} \\tag{6}\n", - "\\end{equation}\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "7c3843f7", - "metadata": {}, - "source": [ - "where we have substituted $y_k^1$ with the inputs $x_k$. Finally, the ANN output reads" - ] - }, - { - "cell_type": "markdown", - "id": "0008d41a", - "metadata": {}, - "source": [ - "\n", - "
\n", - "\n", - "$$\n", - "\\begin{equation}\n", - " y_i^3 = f^3\\left(\\sum_{j=1}^N w_{ij}^3 y_j^2 + b_i^3\\right) \n", - "\\label{_auto3} \\tag{7}\n", - "\\end{equation}\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "e8dc6d51", - "metadata": {}, - "source": [ - "\n", - "
\n", - "\n", - "$$\n", - "\\begin{equation} \n", - " = f_3\\left[\\sum_{j} w_{ij}^3 f^2\\left(\\sum_{k} w_{jk}^2 f^1\\left(\\sum_{m} w_{km}^1 x_m + b_k^1\\right) + b_j^2\\right)\n", - " + b_1^3\\right]\n", - "\\label{_auto4} \\tag{8}\n", - "\\end{equation}\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "1455a093", - "metadata": {}, - "source": [ - "## Mathematical model\n", - "\n", - "We can generalize this expression to an MLP with $l$ hidden\n", - "layers. The complete functional form is," - ] - }, - { - "cell_type": "markdown", - "id": "c2affab6", - "metadata": {}, - "source": [ - "\n", - "
\n", - "\n", - "$$\n", - "\\begin{equation}\n", - "y^{l+1}_i = f^{l+1}\\left[\\!\\sum_{j=1}^{N_l} w_{ij}^3 f^l\\left(\\sum_{k=1}^{N_{l-1}}w_{jk}^{l-1}\\left(\\dots f^1\\left(\\sum_{n=1}^{N_0} w_{mn}^1 x_n+ b_m^1\\right)\\dots\\right)+b_k^2\\right)+b_1^3\\right] \n", - "\\label{completeNN} \\tag{9}\n", - "\\end{equation}\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "c7910d23", - "metadata": {}, - "source": [ - "which illustrates a basic property of MLPs: The only independent\n", - "variables are the input values $x_n$." - ] - }, - { - "cell_type": "markdown", - "id": "ec9e660d", - "metadata": {}, - "source": [ - "## Mathematical model\n", - "\n", - "This confirms that an MLP, despite its quite convoluted mathematical\n", - "form, is nothing more than an analytic function, specifically a\n", - "mapping of real-valued vectors $\\hat{x} \\in \\mathbb{R}^n \\rightarrow\n", - "\\hat{y} \\in \\mathbb{R}^m$.\n", - "\n", - "Furthermore, the flexibility and universality of an MLP can be\n", - "illustrated by realizing that the expression is essentially a nested\n", - "sum of scaled activation functions of the form" - ] - }, - { - "cell_type": "markdown", - "id": "29c77377", - "metadata": {}, - "source": [ - "\n", - "
\n", - "\n", - "$$\n", - "\\begin{equation}\n", - " f(x) = c_1 f(c_2 x + c_3) + c_4\n", - "\\label{_auto5} \\tag{10}\n", - "\\end{equation}\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "f52146ef", - "metadata": {}, - "source": [ - "where the parameters $c_i$ are weights and biases. By adjusting these\n", - "parameters, the activation functions can be shifted up and down or\n", - "left and right, change slope or be rescaled which is the key to the\n", - "flexibility of a neural network." - ] - }, - { - "cell_type": "markdown", - "id": "7f9f65ce", - "metadata": {}, - "source": [ - "### Matrix-vector notation\n", - "\n", - "We can introduce a more convenient notation for the activations in an A NN. \n", - "\n", - "Additionally, we can represent the biases and activations\n", - "as layer-wise column vectors $\\hat{b}_l$ and $\\hat{y}_l$, so that the $i$-th element of each vector \n", - "is the bias $b_i^l$ and activation $y_i^l$ of node $i$ in layer $l$ respectively. \n", - "\n", - "We have that $\\mathrm{W}_l$ is an $N_{l-1} \\times N_l$ matrix, while $\\hat{b}_l$ and $\\hat{y}_l$ are $N_l \\times 1$ column vectors. \n", - "With this notation, the sum becomes a matrix-vector multiplication, and we can write\n", - "the equation for the activations of hidden layer 2 (assuming three nodes for simplicity) as" - ] - }, - { - "cell_type": "markdown", - "id": "7aec05b7", - "metadata": {}, - "source": [ - "\n", - "
\n", - "\n", - "$$\n", - "\\begin{equation}\n", - " \\hat{y}_2 = f_2(\\mathrm{W}_2 \\hat{y}_{1} + \\hat{b}_{2}) = \n", - " f_2\\left(\\left[\\begin{array}{ccc}\n", - " w^2_{11} &w^2_{12} &w^2_{13} \\\\\n", - " w^2_{21} &w^2_{22} &w^2_{23} \\\\\n", - " w^2_{31} &w^2_{32} &w^2_{33} \\\\\n", - " \\end{array} \\right] \\cdot\n", - " \\left[\\begin{array}{c}\n", - " y^1_1 \\\\\n", - " y^1_2 \\\\\n", - " y^1_3 \\\\\n", - " \\end{array}\\right] + \n", - " \\left[\\begin{array}{c}\n", - " b^2_1 \\\\\n", - " b^2_2 \\\\\n", - " b^2_3 \\\\\n", - " \\end{array}\\right]\\right).\n", - "\\label{_auto6} \\tag{11}\n", - "\\end{equation}\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "524f3145", - "metadata": {}, - "source": [ - "### Matrix-vector notation and activation\n", - "\n", - "The activation of node $i$ in layer 2 is" - ] - }, - { - "cell_type": "markdown", - "id": "67ea322c", - "metadata": {}, - "source": [ - "\n", - "
\n", - "\n", - "$$\n", - "\\begin{equation}\n", - " y^2_i = f_2\\Bigr(w^2_{i1}y^1_1 + w^2_{i2}y^1_2 + w^2_{i3}y^1_3 + b^2_i\\Bigr) = \n", - " f_2\\left(\\sum_{j=1}^3 w^2_{ij} y_j^1 + b^2_i\\right).\n", - "\\label{_auto7} \\tag{12}\n", - "\\end{equation}\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "fb2a1836", - "metadata": {}, - "source": [ - "This is not just a convenient and compact notation, but also a useful\n", - "and intuitive way to think about MLPs: The output is calculated by a\n", - "series of matrix-vector multiplications and vector additions that are\n", - "used as input to the activation functions. For each operation\n", - "$\\mathrm{W}_l \\hat{y}_{l-1}$ we move forward one layer." - ] - }, - { - "cell_type": "markdown", - "id": "c6e37074", - "metadata": {}, - "source": [ - "### Activation functions\n", - "\n", - "A property that characterizes a neural network, other than its\n", - "connectivity, is the choice of activation function(s). As described\n", - "in, the following restrictions are imposed on an activation function\n", - "for a FFNN to fulfill the universal approximation theorem\n", - "\n", - " * Non-constant\n", - "\n", - " * Bounded\n", - "\n", - " * Monotonically-increasing\n", - "\n", - " * Continuous" - ] - }, - { - "cell_type": "markdown", - "id": "516427eb", - "metadata": {}, - "source": [ - "### Activation functions, Logistic and Hyperbolic ones\n", - "\n", - "The second requirement excludes all linear functions. Furthermore, in\n", - "a MLP with only linear activation functions, each layer simply\n", - "performs a linear transformation of its inputs.\n", - "\n", - "Regardless of the number of layers, the output of the NN will be\n", - "nothing but a linear function of the inputs. Thus we need to introduce\n", - "some kind of non-linearity to the NN to be able to fit non-linear\n", - "functions Typical examples are the logistic *Sigmoid*" - ] - }, - { - "cell_type": "markdown", - "id": "607e0e1f", - "metadata": {}, - "source": [ - "$$\n", - "f(x) = \\frac{1}{1 + e^{-x}},\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "4147fa7c", - "metadata": {}, - "source": [ - "and the *hyperbolic tangent* function" - ] - }, - { - "cell_type": "markdown", - "id": "4c880e2a", - "metadata": {}, - "source": [ - "$$\n", - "f(x) = \\tanh(x)\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "56c9cd1b", - "metadata": {}, - "source": [ - "### Relevance\n", - "\n", - "The *sigmoid* function are more biologically plausible because the\n", - "output of inactive neurons are zero. Such activation function are\n", - "called *one-sided*. However, it has been shown that the hyperbolic\n", - "tangent performs better than the sigmoid for training MLPs. has\n", - "become the most popular for *deep neural networks*" - ] - }, - { - "cell_type": "code", - "execution_count": 4, - "id": "187aa1c5", - "metadata": {}, - "outputs": [], - "source": [ - "\"\"\"The sigmoid function (or the logistic curve) is a \n", - "function that takes any real number, z, and outputs a number (0,1).\n", - "It is useful in neural networks for assigning weights on a relative scale.\n", - "The value z is the weighted sum of parameters involved in the learning algorithm.\"\"\"\n", - "\n", - "import numpy\n", - "import matplotlib.pyplot as plt\n", - "import math as mt\n", - "\n", - "z = numpy.arange(-5, 5, .1)\n", - "sigma_fn = numpy.vectorize(lambda z: 1/(1+numpy.exp(-z)))\n", - "sigma = sigma_fn(z)\n", - "\n", - "fig = plt.figure()\n", - "ax = fig.add_subplot(111)\n", - "ax.plot(z, sigma)\n", - "ax.set_ylim([-0.1, 1.1])\n", - "ax.set_xlim([-5,5])\n", - "ax.grid(True)\n", - "ax.set_xlabel('z')\n", - "ax.set_title('sigmoid function')\n", - "\n", - "plt.show()\n", - "\n", - "\"\"\"Step Function\"\"\"\n", - "z = numpy.arange(-5, 5, .02)\n", - "step_fn = numpy.vectorize(lambda z: 1.0 if z >= 0.0 else 0.0)\n", - "step = step_fn(z)\n", - "\n", - "fig = plt.figure()\n", - "ax = fig.add_subplot(111)\n", - "ax.plot(z, step)\n", - "ax.set_ylim([-0.5, 1.5])\n", - "ax.set_xlim([-5,5])\n", - "ax.grid(True)\n", - "ax.set_xlabel('z')\n", - "ax.set_title('step function')\n", - "\n", - "plt.show()\n", - "\n", - "\"\"\"Sine Function\"\"\"\n", - "z = numpy.arange(-2*mt.pi, 2*mt.pi, 0.1)\n", - "t = numpy.sin(z)\n", - "\n", - "fig = plt.figure()\n", - "ax = fig.add_subplot(111)\n", - "ax.plot(z, t)\n", - "ax.set_ylim([-1.0, 1.0])\n", - "ax.set_xlim([-2*mt.pi,2*mt.pi])\n", - "ax.grid(True)\n", - "ax.set_xlabel('z')\n", - "ax.set_title('sine function')\n", - "\n", - "plt.show()\n", - "\n", - "\"\"\"Plots a graph of the squashing function used by a rectified linear\n", - "unit\"\"\"\n", - "z = numpy.arange(-2, 2, .1)\n", - "zero = numpy.zeros(len(z))\n", - "y = numpy.max([zero, z], axis=0)\n", - "\n", - "fig = plt.figure()\n", - "ax = fig.add_subplot(111)\n", - "ax.plot(z, y)\n", - "ax.set_ylim([-2.0, 2.0])\n", - "ax.set_xlim([-2.0, 2.0])\n", - "ax.grid(True)\n", - "ax.set_xlabel('z')\n", - "ax.set_title('Rectified linear unit')\n", - "\n", - "plt.show()" - ] - }, - { - "cell_type": "markdown", - "id": "e3195fd0", - "metadata": {}, - "source": [ - "## The multilayer perceptron (MLP)\n", - "\n", - "The multilayer perceptron is a very popular, and easy to implement approach, to deep learning. It consists of\n", - "1. A neural network with one or more layers of nodes between the input and the output nodes.\n", - "\n", - "2. The multilayer network structure, or architecture, or topology, consists of an input layer, one or more hidden layers, and one output layer.\n", - "\n", - "3. The input nodes pass values to the first hidden layer, its nodes pass the information on to the second and so on till we reach the output layer.\n", - "\n", - "As a convention it is normal to call a network with one layer of input units, one layer of hidden\n", - "units and one layer of output units as a two-layer network. A network with two layers of hidden units is called a three-layer network etc etc.\n", - "\n", - "For an MLP network there is no direct connection between the output nodes/neurons/units and the input nodes/neurons/units.\n", - "Hereafter we will call the various entities of a layer for nodes.\n", - "There are also no connections within a single layer.\n", - "\n", - "The number of input nodes does not need to equal the number of output\n", - "nodes. This applies also to the hidden layers. Each layer may have its\n", - "own number of nodes and activation functions.\n", - "\n", - "The hidden layers have their name from the fact that they are not\n", - "linked to observables and as we will see below when we define the\n", - "so-called activation $\\hat{z}$, we can think of this as a basis\n", - "expansion of the original inputs $\\hat{x}$. The difference however\n", - "between neural networks and say linear regression is that now these\n", - "basis functions (which will correspond to the weights in the network)\n", - "are learned from data. This results in an important difference between\n", - "neural networks and deep learning approaches on one side and methods\n", - "like logistic regression or linear regression and their modifications on the other side." - ] - }, - { - "cell_type": "markdown", - "id": "f15de9c4", - "metadata": {}, - "source": [ - "## From one to many layers, the universal approximation theorem\n", - "\n", - "A neural network with only one layer, what we called the simple\n", - "perceptron, is best suited if we have a standard binary model with\n", - "clear (linear) boundaries between the outcomes. As such it could\n", - "equally well be replaced by standard linear regression or logistic\n", - "regression. Networks with one or more hidden layers approximate\n", - "systems with more complex boundaries.\n", - "\n", - "As stated earlier, \n", - "an important theorem in studies of neural networks, restated without\n", - "proof here, is the [universal approximation\n", - "theorem](http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.441.7873&rep=rep1&type=pdf).\n", - "\n", - "It states that a feed-forward network with a single hidden layer\n", - "containing a finite number of neurons can approximate continuous\n", - "functions on compact subsets of real functions. The theorem thus\n", - "states that simple neural networks can represent a wide variety of\n", - "interesting functions when given appropriate parameters. It is the\n", - "multilayer feedforward architecture itself which gives neural networks\n", - "the potential of being universal approximators." - ] - }, - { - "cell_type": "markdown", - "id": "9d79d680", - "metadata": {}, - "source": [ - "## Deriving the back propagation code for a multilayer perceptron model\n", - "\n", - "As we have seen now in a feed forward network, we can express the final output of our network in terms of basic matrix-vector multiplications.\n", - "The unknowwn quantities are our weights $w_{ij}$ and we need to find an algorithm for changing them so that our errors are as small as possible.\n", - "This leads us to the famous [back propagation algorithm](https://www.nature.com/articles/323533a0).\n", - "\n", - "The questions we want to ask are how do changes in the biases and the\n", - "weights in our network change the cost function and how can we use the\n", - "final output to modify the weights?\n", - "\n", - "To derive these equations let us start with a plain regression problem\n", - "and define our cost function as" - ] - }, - { - "cell_type": "markdown", - "id": "31e1a9b1", - "metadata": {}, - "source": [ - "$$\n", - "{\\cal C}(\\hat{W}) = \\frac{1}{2}\\sum_{i=1}^n\\left(y_i - t_i\\right)^2,\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "890921b9", - "metadata": {}, - "source": [ - "where the $t_i$s are our $n$ targets (the values we want to\n", - "reproduce), while the outputs of the network after having propagated\n", - "all inputs $\\hat{x}$ are given by $y_i$. Below we will demonstrate\n", - "how the basic equations arising from the back propagation algorithm\n", - "can be modified in order to study classification problems with $K$\n", - "classes." - ] - }, - { - "cell_type": "markdown", - "id": "fe55dffb", - "metadata": {}, - "source": [ - "## Definitions\n", - "\n", - "With our definition of the targets $\\hat{t}$, the outputs of the\n", - "network $\\hat{y}$ and the inputs $\\hat{x}$ we\n", - "define now the activation $z_j^l$ of node/neuron/unit $j$ of the\n", - "$l$-th layer as a function of the bias, the weights which add up from\n", - "the previous layer $l-1$ and the forward passes/outputs\n", - "$\\hat{a}^{l-1}$ from the previous layer as" - ] - }, - { - "cell_type": "markdown", - "id": "61548fd5", - "metadata": {}, - "source": [ - "$$\n", - "z_j^l = \\sum_{i=1}^{M_{l-1}}w_{ij}^la_i^{l-1}+b_j^l,\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "7b437827", - "metadata": {}, - "source": [ - "where $b_k^l$ are the biases from layer $l$. Here $M_{l-1}$\n", - "represents the total number of nodes/neurons/units of layer $l-1$. The\n", - "figure here illustrates this equation. We can rewrite this in a more\n", - "compact form as the matrix-vector products we discussed earlier," - ] - }, - { - "cell_type": "markdown", - "id": "88aeaf0f", - "metadata": {}, - "source": [ - "$$\n", - "\\hat{z}^l = \\left(\\hat{W}^l\\right)^T\\hat{a}^{l-1}+\\hat{b}^l.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "d81878b1", - "metadata": {}, - "source": [ - "With the activation values $\\hat{z}^l$ we can in turn define the\n", - "output of layer $l$ as $\\hat{a}^l = f(\\hat{z}^l)$ where $f$ is our\n", - "activation function. In the examples here we will use the sigmoid\n", - "function discussed in our logistic regression lectures. We will also use the same activation function $f$ for all layers\n", - "and their nodes. It means we have" - ] - }, - { - "cell_type": "markdown", - "id": "aa3e6b55", - "metadata": {}, - "source": [ - "$$\n", - "a_j^l = f(z_j^l) = \\frac{1}{1+\\exp{-(z_j^l)}}.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "282fc0f1", - "metadata": {}, - "source": [ - "## Derivatives and the chain rule\n", - "\n", - "From the definition of the activation $z_j^l$ we have" - ] - }, - { - "cell_type": "markdown", - "id": "5007c640", - "metadata": {}, - "source": [ - "$$\n", - "\\frac{\\partial z_j^l}{\\partial w_{ij}^l} = a_i^{l-1},\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "ed8b0010", - "metadata": {}, - "source": [ - "and" - ] - }, - { - "cell_type": "markdown", - "id": "3174619f", - "metadata": {}, - "source": [ - "$$\n", - "\\frac{\\partial z_j^l}{\\partial a_i^{l-1}} = w_{ji}^l.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "448a714d", - "metadata": {}, - "source": [ - "With our definition of the activation function we have that (note that this function depends only on $z_j^l$)" - ] - }, - { - "cell_type": "markdown", - "id": "862da704", - "metadata": {}, - "source": [ - "$$\n", - "\\frac{\\partial a_j^l}{\\partial z_j^{l}} = a_j^l(1-a_j^l)=f(z_j^l)(1-f(z_j^l)).\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "9958b437", - "metadata": {}, - "source": [ - "## Derivative of the cost function\n", - "\n", - "With these definitions we can now compute the derivative of the cost function in terms of the weights.\n", - "\n", - "Let us specialize to the output layer $l=L$. Our cost function is" - ] - }, - { - "cell_type": "markdown", - "id": "be3a329b", - "metadata": {}, - "source": [ - "$$\n", - "{\\cal C}(\\hat{W^L}) = \\frac{1}{2}\\sum_{i=1}^n\\left(y_i - t_i\\right)^2=\\frac{1}{2}\\sum_{i=1}^n\\left(a_i^L - t_i\\right)^2,\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "2237bf2b", - "metadata": {}, - "source": [ - "The derivative of this function with respect to the weights is" - ] - }, - { - "cell_type": "markdown", - "id": "74e6185e", - "metadata": {}, - "source": [ - "$$\n", - "\\frac{\\partial{\\cal C}(\\hat{W^L})}{\\partial w_{jk}^L} = \\left(a_j^L - t_j\\right)\\frac{\\partial a_j^L}{\\partial w_{jk}^{L}},\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "462a7694", - "metadata": {}, - "source": [ - "The last partial derivative can easily be computed and reads (by applying the chain rule)" - ] - }, - { - "cell_type": "markdown", - "id": "cde99728", - "metadata": {}, - "source": [ - "$$\n", - "\\frac{\\partial a_j^L}{\\partial w_{jk}^{L}} = \\frac{\\partial a_j^L}{\\partial z_{j}^{L}}\\frac{\\partial z_j^L}{\\partial w_{jk}^{L}}=a_j^L(1-a_j^L)a_k^{L-1},\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "11c5d932", - "metadata": {}, - "source": [ - "## Bringing it together, first back propagation equation\n", - "\n", - "We have thus" - ] - }, - { - "cell_type": "markdown", - "id": "d46a1cc5", - "metadata": {}, - "source": [ - "$$\n", - "\\frac{\\partial{\\cal C}(\\hat{W^L})}{\\partial w_{jk}^L} = \\left(a_j^L - t_j\\right)a_j^L(1-a_j^L)a_k^{L-1},\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "7f634831", - "metadata": {}, - "source": [ - "Defining" - ] - }, - { - "cell_type": "markdown", - "id": "c2245dab", - "metadata": {}, - "source": [ - "$$\n", - "\\delta_j^L = a_j^L(1-a_j^L)\\left(a_j^L - t_j\\right) = f'(z_j^L)\\frac{\\partial {\\cal C}}{\\partial (a_j^L)},\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "fbda1939", - "metadata": {}, - "source": [ - "and using the Hadamard product of two vectors we can write this as" - ] - }, - { - "cell_type": "markdown", - "id": "54e8fb49", - "metadata": {}, - "source": [ - "$$\n", - "\\hat{\\delta}^L = f'(\\hat{z}^L)\\circ\\frac{\\partial {\\cal C}}{\\partial (\\hat{a}^L)}.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "0fa8b43d", - "metadata": {}, - "source": [ - "This is an important expression. The second term on the right handside\n", - "measures how fast the cost function is changing as a function of the $j$th\n", - "output activation. If, for example, the cost function doesn't depend\n", - "much on a particular output node $j$, then $\\delta_j^L$ will be small,\n", - "which is what we would expect. The first term on the right, measures\n", - "how fast the activation function $f$ is changing at a given activation\n", - "value $z_j^L$.\n", - "\n", - "Notice that everything in the above equations is easily computed. In\n", - "particular, we compute $z_j^L$ while computing the behaviour of the\n", - "network, and it is only a small additional overhead to compute\n", - "$f'(z^L_j)$. The exact form of the derivative with respect to the\n", - "output depends on the form of the cost function.\n", - "However, provided the cost function is known there should be little\n", - "trouble in calculating" - ] - }, - { - "cell_type": "markdown", - "id": "00455d1e", - "metadata": {}, - "source": [ - "$$\n", - "\\frac{\\partial {\\cal C}}{\\partial (a_j^L)}\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "8a503b44", - "metadata": {}, - "source": [ - "With the definition of $\\delta_j^L$ we have a more compact definition of the derivative of the cost function in terms of the weights, namely" - ] - }, - { - "cell_type": "markdown", - "id": "28aaa847", - "metadata": {}, - "source": [ - "$$\n", - "\\frac{\\partial{\\cal C}(\\hat{W^L})}{\\partial w_{jk}^L} = \\delta_j^La_k^{L-1}.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "ca7f309e", - "metadata": {}, - "source": [ - "## Derivatives in terms of $z_j^L$\n", - "\n", - "It is also easy to see that our previous equation can be written as" - ] - }, - { - "cell_type": "markdown", - "id": "79b5d957", - "metadata": {}, - "source": [ - "$$\n", - "\\delta_j^L =\\frac{\\partial {\\cal C}}{\\partial z_j^L}= \\frac{\\partial {\\cal C}}{\\partial a_j^L}\\frac{\\partial a_j^L}{\\partial z_j^L},\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "ba24b0ba", - "metadata": {}, - "source": [ - "which can also be interpreted as the partial derivative of the cost function with respect to the biases $b_j^L$, namely" - ] - }, - { - "cell_type": "markdown", - "id": "2f98d5ae", - "metadata": {}, - "source": [ - "$$\n", - "\\delta_j^L = \\frac{\\partial {\\cal C}}{\\partial b_j^L}\\frac{\\partial b_j^L}{\\partial z_j^L}=\\frac{\\partial {\\cal C}}{\\partial b_j^L},\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "596bd7eb", - "metadata": {}, - "source": [ - "That is, the error $\\delta_j^L$ is exactly equal to the rate of change of the cost function as a function of the bias." - ] - }, - { - "cell_type": "markdown", - "id": "9144dcb7", - "metadata": {}, - "source": [ - "## Bringing it together\n", - "\n", - "We have now three equations that are essential for the computations of the derivatives of the cost function at the output layer. These equations are needed to start the algorithm and they are\n", - "\n", - "**The starting equations.**" - ] - }, - { - "cell_type": "markdown", - "id": "4f2e52cb", - "metadata": {}, - "source": [ - "\n", - "
\n", - "\n", - "$$\n", - "\\begin{equation}\n", - "\\frac{\\partial{\\cal C}(\\hat{W^L})}{\\partial w_{jk}^L} = \\delta_j^La_k^{L-1},\n", - "\\label{_auto8} \\tag{13}\n", - "\\end{equation}\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "3b94d154", - "metadata": {}, - "source": [ - "and" - ] - }, - { - "cell_type": "markdown", - "id": "18f353fd", - "metadata": {}, - "source": [ - "\n", - "
\n", - "\n", - "$$\n", - "\\begin{equation}\n", - "\\delta_j^L = f'(z_j^L)\\frac{\\partial {\\cal C}}{\\partial (a_j^L)},\n", - "\\label{_auto9} \\tag{14}\n", - "\\end{equation}\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "631f4feb", - "metadata": {}, - "source": [ - "and" - ] - }, - { - "cell_type": "markdown", - "id": "1793bcd7", - "metadata": {}, - "source": [ - "\n", - "
\n", - "\n", - "$$\n", - "\\begin{equation}\n", - "\\delta_j^L = \\frac{\\partial {\\cal C}}{\\partial b_j^L},\n", - "\\label{_auto10} \\tag{15}\n", - "\\end{equation}\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "0cc3885e", - "metadata": {}, - "source": [ - "An interesting consequence of the above equations is that when the\n", - "activation $a_k^{L-1}$ is small, the gradient term, that is the\n", - "derivative of the cost function with respect to the weights, will also\n", - "tend to be small. We say then that the weight learns slowly, meaning\n", - "that it changes slowly when we minimize the weights via say gradient\n", - "descent. In this case we say the system learns slowly.\n", - "\n", - "Another interesting feature is that is when the activation function,\n", - "represented by the sigmoid function here, is rather flat when we move towards\n", - "its end values $0$ and $1$ (see the above Python codes). In these\n", - "cases, the derivatives of the activation function will also be close\n", - "to zero, meaning again that the gradients will be small and the\n", - "network learns slowly again.\n", - "\n", - "We need a fourth equation and we are set. We are going to propagate\n", - "backwards in order to the determine the weights and biases. In order\n", - "to do so we need to represent the error in the layer before the final\n", - "one $L-1$ in terms of the errors in the final output layer." - ] - }, - { - "cell_type": "markdown", - "id": "7f697fec", - "metadata": {}, - "source": [ - "## Final back propagating equation\n", - "\n", - "We have that (replacing $L$ with a general layer $l$)" - ] - }, - { - "cell_type": "markdown", - "id": "42a9acc8", - "metadata": {}, - "source": [ - "$$\n", - "\\delta_j^l =\\frac{\\partial {\\cal C}}{\\partial z_j^l}.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "ac01943b", - "metadata": {}, - "source": [ - "We want to express this in terms of the equations for layer $l+1$. Using the chain rule and summing over all $k$ entries we have" - ] - }, - { - "cell_type": "markdown", - "id": "a6ec5df0", - "metadata": {}, - "source": [ - "$$\n", - "\\delta_j^l =\\sum_k \\frac{\\partial {\\cal C}}{\\partial z_k^{l+1}}\\frac{\\partial z_k^{l+1}}{\\partial z_j^{l}}=\\sum_k \\delta_k^{l+1}\\frac{\\partial z_k^{l+1}}{\\partial z_j^{l}},\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "8b0f324a", - "metadata": {}, - "source": [ - "and recalling that" - ] - }, - { - "cell_type": "markdown", - "id": "4ae4c890", - "metadata": {}, - "source": [ - "$$\n", - "z_j^{l+1} = \\sum_{i=1}^{M_{l}}w_{ij}^{l+1}a_i^{l}+b_j^{l+1},\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "b8af6a3b", - "metadata": {}, - "source": [ - "with $M_l$ being the number of nodes in layer $l$, we obtain" - ] - }, - { - "cell_type": "markdown", - "id": "c5a36652", - "metadata": {}, - "source": [ - "$$\n", - "\\delta_j^l =\\sum_k \\delta_k^{l+1}w_{kj}^{l+1}f'(z_j^l),\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "eb9f0a42", - "metadata": {}, - "source": [ - "This is our final equation.\n", - "\n", - "We are now ready to set up the algorithm for back propagation and learning the weights and biases." - ] - }, - { - "cell_type": "markdown", - "id": "cd78653c", - "metadata": {}, - "source": [ - "## Setting up the Back propagation algorithm\n", - "\n", - "The four equations provide us with a way of computing the gradient of the cost function. Let us write this out in the form of an algorithm.\n", - "\n", - "First, we set up the input data $\\hat{x}$ and the activations\n", - "$\\hat{z}_1$ of the input layer and compute the activation function and\n", - "the pertinent outputs $\\hat{a}^1$.\n", - "\n", - "Secondly, we perform then the feed forward till we reach the output\n", - "layer and compute all $\\hat{z}_l$ of the input layer and compute the\n", - "activation function and the pertinent outputs $\\hat{a}^l$ for\n", - "$l=2,3,\\dots,L$.\n", - "\n", - "Thereafter we compute the ouput error $\\hat{\\delta}^L$ by computing all" - ] - }, - { - "cell_type": "markdown", - "id": "adab4f13", - "metadata": {}, - "source": [ - "$$\n", - "\\delta_j^L = f'(z_j^L)\\frac{\\partial {\\cal C}}{\\partial (a_j^L)}.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "9091074a", - "metadata": {}, - "source": [ - "Then we compute the back propagate error for each $l=L-1,L-2,\\dots,2$ as" - ] - }, - { - "cell_type": "markdown", - "id": "da04b8a8", - "metadata": {}, - "source": [ - "$$\n", - "\\delta_j^l = \\sum_k \\delta_k^{l+1}w_{kj}^{l+1}f'(z_j^l).\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "d707b6e0", - "metadata": {}, - "source": [ - "Finally, we update the weights and the biases using gradient descent for each $l=L-1,L-2,\\dots,2$ and update the weights and biases according to the rules" - ] - }, - { - "cell_type": "markdown", - "id": "f26ac396", - "metadata": {}, - "source": [ - "$$\n", - "w_{jk}^l\\leftarrow = w_{jk}^l- \\eta \\delta_j^la_k^{l-1},\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "1d5d1ed0", - "metadata": {}, - "source": [ - "$$\n", - "b_j^l \\leftarrow b_j^l-\\eta \\frac{\\partial {\\cal C}}{\\partial b_j^l}=b_j^l-\\eta \\delta_j^l,\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "d686cbb0", - "metadata": {}, - "source": [ - "The parameter $\\eta$ is the learning parameter discussed in connection with the gradient descent methods.\n", - "Here it is convenient to use stochastic gradient descent (see the examples below) with mini-batches with an outer loop that steps through multiple epochs of training." - ] - }, - { - "cell_type": "markdown", - "id": "31554688", - "metadata": {}, - "source": [ - "## Setting up the Back propagation algorithm\n", - "\n", - "The four equations above provide us with a way of computing the gradient of the cost function. Let us write this out in the form of an algorithm.\n", - "\n", - "First, we set up the input data $\\boldsymbol{x}$ and the activations\n", - "$\\boldsymbol{z}_1$ of the input layer and compute the activation function and\n", - "the pertinent outputs $\\boldsymbol{a}^1$.\n", - "\n", - "Secondly, we perform then the feed forward till we reach the output\n", - "layer and compute all $\\boldsymbol{z}_l$ of the input layer and compute the\n", - "activation function and the pertinent outputs $\\boldsymbol{a}^l$ for\n", - "$l=2,3,\\dots,L$.\n", - "\n", - "Thereafter we compute the ouput error $\\boldsymbol{\\delta}^L$ by computing all" - ] - }, - { - "cell_type": "markdown", - "id": "a34466dc", - "metadata": {}, - "source": [ - "$$\n", - "\\delta_j^L = f'(z_j^L)\\frac{\\partial {\\cal C}}{\\partial (a_j^L)}.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "742b0899", - "metadata": {}, - "source": [ - "Then we compute the back propagate error for each $l=L-1,L-2,\\dots,2$ as" - ] - }, - { - "cell_type": "markdown", - "id": "813c7f07", - "metadata": {}, - "source": [ - "$$\n", - "\\delta_j^l = \\sum_k \\delta_k^{l+1}w_{kj}^{l+1}f'(z_j^l).\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "88fccb02", - "metadata": {}, - "source": [ - "Finally, we update the weights and the biases using gradient descent for each $l=L-1,L-2,\\dots,2$ and update the weights and biases according to the rules" - ] - }, - { - "cell_type": "markdown", - "id": "a5d5593c", - "metadata": {}, - "source": [ - "$$\n", - "w_{jk}^l\\leftarrow = w_{jk}^l- \\eta \\delta_j^la_k^{l-1},\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "1b5aeaa8", - "metadata": {}, - "source": [ - "$$\n", - "b_j^l \\leftarrow b_j^l-\\eta \\frac{\\partial {\\cal C}}{\\partial b_j^l}=b_j^l-\\eta \\delta_j^l,\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "29156297", - "metadata": {}, - "source": [ - "The parameter $\\eta$ is the learning parameter discussed in connection with the gradient descent methods.\n", - "Here it is convenient to use stochastic gradient descent (see the examples below) with mini-batches with an outer loop that steps through multiple epochs of training." - ] - }, - { - "cell_type": "markdown", - "id": "752b2b7a", - "metadata": {}, - "source": [ - "## Setting up the Back propagation algorithm\n", - "\n", - "The four equations derived discussed above provide us with a way of computing the gradient of the cost function. Let us write this out in the form of an algorithm.\n", - "\n", - "First, we set up the input data $\\boldsymbol{x}$ and the activations\n", - "$\\boldsymbol{z}_1$ of the input layer and compute the activation function and\n", - "the pertinent outputs $\\boldsymbol{a}^1$.\n", - "\n", - "Secondly, we perform then the feed forward till we reach the output\n", - "layer and compute all $\\boldsymbol{z}_l$ of the input layer and compute the\n", - "activation function and the pertinent outputs $\\boldsymbol{a}^l$ for\n", - "$l=2,3,\\dots,L$.\n", - "\n", - "Thereafter we compute the ouput error $\\boldsymbol{\\delta}^L$ by computing all" - ] - }, - { - "cell_type": "markdown", - "id": "29bb348b", - "metadata": {}, - "source": [ - "$$\n", - "\\delta_j^L = f'(z_j^L)\\frac{\\partial {\\cal C}}{\\partial (a_j^L)}.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "2cbb4812", - "metadata": {}, - "source": [ - "Then we compute the back propagate error for each $l=L-1,L-2,\\dots,2$ as" - ] - }, - { - "cell_type": "markdown", - "id": "73fa8d95", - "metadata": {}, - "source": [ - "$$\n", - "\\delta_j^l = \\sum_k \\delta_k^{l+1}w_{kj}^{l+1}f'(z_j^l).\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "d815b24a", - "metadata": {}, - "source": [ - "Finally, we update the weights and the biases using gradient descent for each $l=L-1,L-2,\\dots,2$ and update the weights and biases according to the rules" - ] - }, - { - "cell_type": "markdown", - "id": "43d2f617", - "metadata": {}, - "source": [ - "$$\n", - "w_{jk}^l\\leftarrow = w_{jk}^l- \\eta \\delta_j^la_k^{l-1},\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "bf7af7f5", - "metadata": {}, - "source": [ - "$$\n", - "b_j^l \\leftarrow b_j^l-\\eta \\frac{\\partial {\\cal C}}{\\partial b_j^l}=b_j^l-\\eta \\delta_j^l,\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "9a5e5eaf", - "metadata": {}, - "source": [ - "The parameter $\\eta$ is the learning parameter discussed in connection with the gradient descent methods.\n", - "Here it is convenient to use stochastic gradient descent (see the examples below) with mini-batches with an outer loop that steps through multiple epochs of training." - ] - }, - { - "cell_type": "markdown", - "id": "e62f23f4", - "metadata": {}, - "source": [ - "## Setting up a Multi-layer perceptron model for classification\n", - "\n", - "We are now gong to develop an example based on the MNIST data\n", - "base. This is a classification problem and we need to use our\n", - "cross-entropy function we discussed in connection with logistic\n", - "regression. The cross-entropy defines our cost function for the\n", - "classificaton problems with neural networks.\n", - "\n", - "In binary classification with two classes $(0, 1)$ we define the\n", - "logistic/sigmoid function as the probability that a particular input\n", - "is in class $0$ or $1$. This is possible because the logistic\n", - "function takes any input from the real numbers and inputs a number\n", - "between 0 and 1, and can therefore be interpreted as a probability. It\n", - "also has other nice properties, such as a derivative that is simple to\n", - "calculate.\n", - "\n", - "For an input $\\boldsymbol{a}$ from the hidden layer, the probability that the input $\\boldsymbol{x}$\n", - "is in class 0 or 1 is just. We let $\\theta$ represent the unknown weights and biases to be adjusted by our equations). The variable $x$\n", - "represents our activation values $z$. We have" - ] - }, - { - "cell_type": "markdown", - "id": "42d7a94e", - "metadata": {}, - "source": [ - "$$\n", - "P(y = 0 \\mid \\boldsymbol{x}, \\boldsymbol{\\theta}) = \\frac{1}{1 + \\exp{(- \\boldsymbol{x}})} ,\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "5bfea505", - "metadata": {}, - "source": [ - "and" - ] - }, - { - "cell_type": "markdown", - "id": "9f6b8143", - "metadata": {}, - "source": [ - "$$\n", - "P(y = 1 \\mid \\boldsymbol{x}, \\boldsymbol{\\theta}) = 1 - P(y = 0 \\mid \\boldsymbol{x}, \\boldsymbol{\\theta}) ,\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "194f2cbe", - "metadata": {}, - "source": [ - "where $y \\in \\{0, 1\\}$ and $\\boldsymbol{\\theta}$ represents the weights and biases\n", - "of our network." - ] - }, - { - "cell_type": "markdown", - "id": "20cd18e6", - "metadata": {}, - "source": [ - "## Defining the cost function\n", - "\n", - "Our cost function is given as (see the Logistic regression lectures)" - ] - }, - { - "cell_type": "markdown", - "id": "b3e52796", - "metadata": {}, - "source": [ - "$$\n", - "\\mathcal{C}(\\boldsymbol{\\theta}) = - \\ln P(\\mathcal{D} \\mid \\boldsymbol{\\theta}) = - \\sum_{i=1}^n\n", - "y_i \\ln[P(y_i = 0)] + (1 - y_i) \\ln [1 - P(y_i = 0)] = \\sum_{i=1}^n \\mathcal{L}_i(\\boldsymbol{\\theta}) .\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "7cb68d89", - "metadata": {}, - "source": [ - "This last equality means that we can interpret our *cost* function as a sum over the *loss* function\n", - "for each point in the dataset $\\mathcal{L}_i(\\boldsymbol{\\theta})$. \n", - "The negative sign is just so that we can think about our algorithm as minimizing a positive number, rather\n", - "than maximizing a negative number. \n", - "\n", - "In *multiclass* classification it is common to treat each integer label as a so called *one-hot* vector: \n", - "\n", - "$y = 5 \\quad \\rightarrow \\quad \\boldsymbol{y} = (0, 0, 0, 0, 0, 1, 0, 0, 0, 0) ,$ and\n", - "\n", - "$y = 1 \\quad \\rightarrow \\quad \\boldsymbol{y} = (0, 1, 0, 0, 0, 0, 0, 0, 0, 0) ,$ \n", - "\n", - "i.e. a binary bit string of length $C$, where $C = 10$ is the number of classes in the MNIST dataset (numbers from $0$ to $9$).. \n", - "\n", - "If $\\boldsymbol{x}_i$ is the $i$-th input (image), $y_{ic}$ refers to the $c$-th component of the $i$-th\n", - "output vector $\\boldsymbol{y}_i$. \n", - "The probability of $\\boldsymbol{x}_i$ being in class $c$ will be given by the softmax function:" - ] - }, - { - "cell_type": "markdown", - "id": "0a98f80a", - "metadata": {}, - "source": [ - "$$\n", - "P(y_{ic} = 1 \\mid \\boldsymbol{x}_i, \\boldsymbol{\\theta}) = \\frac{\\exp{((\\boldsymbol{a}_i^{hidden})^T \\boldsymbol{w}_c)}}\n", - "{\\sum_{c'=0}^{C-1} \\exp{((\\boldsymbol{a}_i^{hidden})^T \\boldsymbol{w}_{c'})}} ,\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "b86447a6", - "metadata": {}, - "source": [ - "which reduces to the logistic function in the binary case. \n", - "The likelihood of this $C$-class classifier\n", - "is now given as:" - ] - }, - { - "cell_type": "markdown", - "id": "942e0060", - "metadata": {}, - "source": [ - "$$\n", - "P(\\mathcal{D} \\mid \\boldsymbol{\\theta}) = \\prod_{i=1}^n \\prod_{c=0}^{C-1} [P(y_{ic} = 1)]^{y_{ic}} .\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "99eae6f4", - "metadata": {}, - "source": [ - "Again we take the negative log-likelihood to define our cost function:" - ] - }, - { - "cell_type": "markdown", - "id": "872017e1", - "metadata": {}, - "source": [ - "$$\n", - "\\mathcal{C}(\\boldsymbol{\\theta}) = - \\log{P(\\mathcal{D} \\mid \\boldsymbol{\\theta})}.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "f55259c0", - "metadata": {}, - "source": [ - "See the logistic regression lectures for a full definition of the cost function.\n", - "\n", - "The back propagation equations need now only a small change, namely the definition of a new cost function. We are thus ready to use the same equations as before!" - ] - }, - { - "cell_type": "markdown", - "id": "db983bc4", - "metadata": {}, - "source": [ - "## Example: binary classification problem\n", - "\n", - "As an example of the above, relevant for project 2 as well, let us consider a binary class. As discussed in our logistic regression lectures, we defined a cost function in terms of the parameters $\\beta$ as" - ] - }, - { - "cell_type": "markdown", - "id": "165881cf", - "metadata": {}, - "source": [ - "$$\n", - "\\mathcal{C}(\\boldsymbol{\\beta}) = - \\sum_{i=1}^n \\left(y_i\\log{p(y_i \\vert x_i,\\boldsymbol{\\beta})}+(1-y_i)\\log{1-p(y_i \\vert x_i,\\boldsymbol{\\beta})}\\right),\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "50ecaa83", - "metadata": {}, - "source": [ - "where we had defined the logistic (sigmoid) function" - ] - }, - { - "cell_type": "markdown", - "id": "b16d30f7", - "metadata": {}, - "source": [ - "$$\n", - "p(y_i =1\\vert x_i,\\boldsymbol{\\beta})=\\frac{\\exp{(\\beta_0+\\beta_1 x_i)}}{1+\\exp{(\\beta_0+\\beta_1 x_i)}},\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "2d4c1829", - "metadata": {}, - "source": [ - "and" - ] - }, - { - "cell_type": "markdown", - "id": "4d7a8c79", - "metadata": {}, - "source": [ - "$$\n", - "p(y_i =0\\vert x_i,\\boldsymbol{\\beta})=1-p(y_i =1\\vert x_i,\\boldsymbol{\\beta}).\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "7c4a0d89", - "metadata": {}, - "source": [ - "The parameters $\\boldsymbol{\\beta}$ were defined using a minimization method like gradient descent or Newton-Raphson's method. \n", - "\n", - "Now we replace $x_i$ with the activation $z_i^l$ for a given layer $l$ and the outputs as $y_i=a_i^l=f(z_i^l)$, with $z_i^l$ now being a function of the weights $w_{ij}^l$ and biases $b_i^l$. \n", - "We have then" - ] - }, - { - "cell_type": "markdown", - "id": "96bccb9e", - "metadata": {}, - "source": [ - "$$\n", - "a_i^l = y_i = \\frac{\\exp{(z_i^l)}}{1+\\exp{(z_i^l)}},\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "01f9ae68", - "metadata": {}, - "source": [ - "with" - ] - }, - { - "cell_type": "markdown", - "id": "590fc8bd", - "metadata": {}, - "source": [ - "$$\n", - "z_i^l = \\sum_{j}w_{ij}^l a_j^{l-1}+b_i^l,\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "f3dc3a43", - "metadata": {}, - "source": [ - "where the superscript $l-1$ indicates that these are the outputs from layer $l-1$.\n", - "Our cost function at the final layer $l=L$ is now" - ] - }, - { - "cell_type": "markdown", - "id": "7dd1bbaa", - "metadata": {}, - "source": [ - "$$\n", - "\\mathcal{C}(\\boldsymbol{W}) = - \\sum_{i=1}^n \\left(t_i\\log{a_i^L}+(1-t_i)\\log{(1-a_i^L)}\\right),\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "dc472c94", - "metadata": {}, - "source": [ - "where we have defined the targets $t_i$. The derivatives of the cost function with respect to the output $a_i^L$ are then easily calculated and we get" - ] - }, - { - "cell_type": "markdown", - "id": "372c5019", - "metadata": {}, - "source": [ - "$$\n", - "\\frac{\\partial \\mathcal{C}(\\boldsymbol{W})}{\\partial a_i^L} = \\frac{a_i^L-t_i}{a_i^L(1-a_i^L)}.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "783cc2c1", - "metadata": {}, - "source": [ - "In case we use another activation function than the logistic one, we need to evaluate other derivatives." - ] - }, - { - "cell_type": "markdown", - "id": "d37a48b8", - "metadata": {}, - "source": [ - "## The Softmax function\n", - "In case we employ the more general case given by the Softmax equation, we need to evaluate the derivative of the activation function with respect to the activation $z_i^l$, that is we need" - ] - }, - { - "cell_type": "markdown", - "id": "e6790133", - "metadata": {}, - "source": [ - "$$\n", - "\\frac{\\partial f(z_i^l)}{\\partial w_{jk}^l} =\n", - "\\frac{\\partial f(z_i^l)}{\\partial z_j^l} \\frac{\\partial z_j^l}{\\partial w_{jk}^l}= \\frac{\\partial f(z_i^l)}{\\partial z_j^l}a_k^{l-1}.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "97578009", - "metadata": {}, - "source": [ - "For the Softmax function we have" - ] - }, - { - "cell_type": "markdown", - "id": "13822f62", - "metadata": {}, - "source": [ - "$$\n", - "f(z_i^l) = \\frac{\\exp{(z_i^l)}}{\\sum_{m=1}^K\\exp{(z_m^l)}}.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "10bf9fb7", - "metadata": {}, - "source": [ - "Its derivative with respect to $z_j^l$ gives" - ] - }, - { - "cell_type": "markdown", - "id": "cf59a594", - "metadata": {}, - "source": [ - "$$\n", - "\\frac{\\partial f(z_i^l)}{\\partial z_j^l}= f(z_i^l)\\left(\\delta_{ij}-f(z_j^l)\\right),\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "80a4d3d7", - "metadata": {}, - "source": [ - "which in case of the simply binary model reduces to having $i=j$." - ] - }, - { - "cell_type": "markdown", - "id": "91baac68", - "metadata": {}, - "source": [ - "## Developing a code for doing neural networks with back propagation\n", - "\n", - "One can identify a set of key steps when using neural networks to solve supervised learning problems: \n", - "\n", - "1. Collect and pre-process data \n", - "\n", - "2. Define model and architecture \n", - "\n", - "3. Choose cost function and optimizer \n", - "\n", - "4. Train the model \n", - "\n", - "5. Evaluate model performance on test data \n", - "\n", - "6. Adjust hyperparameters (if necessary, network architecture)" - ] - }, - { - "cell_type": "markdown", - "id": "b4d8a71e", - "metadata": {}, - "source": [ - "## Collect and pre-process data\n", - "\n", - "Here we will be using the MNIST dataset, which is readily available through the **scikit-learn**\n", - "package. You may also find it for example [here](http://yann.lecun.com/exdb/mnist/). \n", - "The *MNIST* (Modified National Institute of Standards and Technology) database is a large database\n", - "of handwritten digits that is commonly used for training various image processing systems. \n", - "The MNIST dataset consists of 70 000 images of size $28\\times 28$ pixels, each labeled from 0 to 9. \n", - "The scikit-learn dataset we will use consists of a selection of 1797 images of size $8\\times 8$ collected and processed from this database. \n", - "\n", - "To feed data into a feed-forward neural network we need to represent\n", - "the inputs as a design/feature matrix $X = (n_{inputs}, n_{features})$. Each\n", - "row represents an *input*, in this case a handwritten digit, and\n", - "each column represents a *feature*, in this case a pixel. The\n", - "correct answers, also known as *labels* or *targets* are\n", - "represented as a 1D array of integers \n", - "$Y = (n_{inputs}) = (5, 3, 1, 8,...)$.\n", - "\n", - "As an example, say we want to build a neural network using supervised learning to predict Body-Mass Index (BMI) from\n", - "measurements of height (in m) \n", - "and weight (in kg). If we have measurements of 5 people the design/feature matrix could be for example: \n", - "\n", - "$$ X = \\begin{bmatrix}\n", - "1.85 & 81\\\\\n", - "1.71 & 65\\\\\n", - "1.95 & 103\\\\\n", - "1.55 & 42\\\\\n", - "1.63 & 56\n", - "\\end{bmatrix} ,$$ \n", - "\n", - "and the targets would be: \n", - "\n", - "$$ Y = (23.7, 22.2, 27.1, 17.5, 21.1) $$ \n", - "\n", - "Since each input image is a 2D matrix, we need to flatten the image\n", - "(i.e. \"unravel\" the 2D matrix into a 1D array) to turn the data into a\n", - "design/feature matrix. This means we lose all spatial information in the\n", - "image, such as locality and translational invariance. More complicated\n", - "architectures such as Convolutional Neural Networks can take advantage\n", - "of such information, and are most commonly applied when analyzing\n", - "images." - ] - }, - { - "cell_type": "code", - "execution_count": 5, - "id": "ad941e6f", - "metadata": {}, - "outputs": [], - "source": [ - "# import necessary packages\n", - "import numpy as np\n", - "import matplotlib.pyplot as plt\n", - "from sklearn import datasets\n", - "\n", - "\n", - "# ensure the same random numbers appear every time\n", - "np.random.seed(0)\n", - "\n", - "# display images in notebook\n", - "%matplotlib inline\n", - "plt.rcParams['figure.figsize'] = (12,12)\n", - "\n", - "\n", - "# download MNIST dataset\n", - "digits = datasets.load_digits()\n", - "\n", - "# define inputs and labels\n", - "inputs = digits.images\n", - "labels = digits.target\n", - "\n", - "print(\"inputs = (n_inputs, pixel_width, pixel_height) = \" + str(inputs.shape))\n", - "print(\"labels = (n_inputs) = \" + str(labels.shape))\n", - "\n", - "\n", - "# flatten the image\n", - "# the value -1 means dimension is inferred from the remaining dimensions: 8x8 = 64\n", - "n_inputs = len(inputs)\n", - "inputs = inputs.reshape(n_inputs, -1)\n", - "print(\"X = (n_inputs, n_features) = \" + str(inputs.shape))\n", - "\n", - "\n", - "# choose some random images to display\n", - "indices = np.arange(n_inputs)\n", - "random_indices = np.random.choice(indices, size=5)\n", - "\n", - "for i, image in enumerate(digits.images[random_indices]):\n", - " plt.subplot(1, 5, i+1)\n", - " plt.axis('off')\n", - " plt.imshow(image, cmap=plt.cm.gray_r, interpolation='nearest')\n", - " plt.title(\"Label: %d\" % digits.target[random_indices[i]])\n", - "plt.show()" - ] - }, - { - "cell_type": "markdown", - "id": "c2f821dc", - "metadata": {}, - "source": [ - "## Train and test datasets\n", - "\n", - "Performing analysis before partitioning the dataset is a major error, that can lead to incorrect conclusions. \n", - "\n", - "We will reserve $80 \\%$ of our dataset for training and $20 \\%$ for testing. \n", - "\n", - "It is important that the train and test datasets are drawn randomly from our dataset, to ensure\n", - "no bias in the sampling. \n", - "Say you are taking measurements of weather data to predict the weather in the coming 5 days.\n", - "You don't want to train your model on measurements taken from the hours 00.00 to 12.00, and then test it on data\n", - "collected from 12.00 to 24.00." - ] - }, - { - "cell_type": "code", - "execution_count": 6, - "id": "d368bcd4", - "metadata": {}, - "outputs": [], - "source": [ - "from sklearn.model_selection import train_test_split\n", - "\n", - "# one-liner from scikit-learn library\n", - "train_size = 0.8\n", - "test_size = 1 - train_size\n", - "X_train, X_test, Y_train, Y_test = train_test_split(inputs, labels, train_size=train_size,\n", - " test_size=test_size)\n", - "\n", - "# equivalently in numpy\n", - "def train_test_split_numpy(inputs, labels, train_size, test_size):\n", - " n_inputs = len(inputs)\n", - " inputs_shuffled = inputs.copy()\n", - " labels_shuffled = labels.copy()\n", - " \n", - " np.random.shuffle(inputs_shuffled)\n", - " np.random.shuffle(labels_shuffled)\n", - " \n", - " train_end = int(n_inputs*train_size)\n", - " X_train, X_test = inputs_shuffled[:train_end], inputs_shuffled[train_end:]\n", - " Y_train, Y_test = labels_shuffled[:train_end], labels_shuffled[train_end:]\n", - " \n", - " return X_train, X_test, Y_train, Y_test\n", - "\n", - "#X_train, X_test, Y_train, Y_test = train_test_split_numpy(inputs, labels, train_size, test_size)\n", - "\n", - "print(\"Number of training images: \" + str(len(X_train)))\n", - "print(\"Number of test images: \" + str(len(X_test)))" - ] - }, - { - "cell_type": "markdown", - "id": "c0e21c2d", - "metadata": {}, - "source": [ - "## Define model and architecture\n", - "\n", - "Our simple feed-forward neural network will consist of an *input* layer, a single *hidden* layer and an *output* layer. The activation $y$ of each neuron is a weighted sum of inputs, passed through an activation function. In case of the simple perceptron model we have \n", - "\n", - "$$ z = \\sum_{i=1}^n w_i a_i ,$$\n", - "\n", - "$$ y = f(z) ,$$\n", - "\n", - "where $f$ is the activation function, $a_i$ represents input from neuron $i$ in the preceding layer\n", - "and $w_i$ is the weight to input $i$. \n", - "The activation of the neurons in the input layer is just the features (e.g. a pixel value). \n", - "\n", - "The simplest activation function for a neuron is the *Heaviside* function:\n", - "\n", - "$$ f(z) = \n", - "\\begin{cases}\n", - "1, & z > 0\\\\\n", - "0, & \\text{otherwise}\n", - "\\end{cases}\n", - "$$\n", - "\n", - "A feed-forward neural network with this activation is known as a *perceptron*. \n", - "For a binary classifier (i.e. two classes, 0 or 1, dog or not-dog) we can also use this in our output layer. \n", - "This activation can be generalized to $k$ classes (using e.g. the *one-against-all* strategy), \n", - "and we call these architectures *multiclass perceptrons*. \n", - "\n", - "However, it is now common to use the terms Single Layer Perceptron (SLP) (1 hidden layer) and \n", - "Multilayer Perceptron (MLP) (2 or more hidden layers) to refer to feed-forward neural networks with any activation function. \n", - "\n", - "Typical choices for activation functions include the sigmoid function, hyperbolic tangent, and Rectified Linear Unit (ReLU). \n", - "We will be using the sigmoid function $\\sigma(x)$: \n", - "\n", - "$$ f(x) = \\sigma(x) = \\frac{1}{1 + e^{-x}} ,$$\n", - "\n", - "which is inspired by probability theory (see logistic regression) and was most commonly used until about 2011. See the discussion below concerning other activation functions." - ] - }, - { - "cell_type": "markdown", - "id": "ba8404a4", - "metadata": {}, - "source": [ - "## Layers\n", - "\n", - "* Input \n", - "\n", - "Since each input image has 8x8 = 64 pixels or features, we have an input layer of 64 neurons. \n", - "\n", - "* Hidden layer\n", - "\n", - "We will use 50 neurons in the hidden layer receiving input from the neurons in the input layer. \n", - "Since each neuron in the hidden layer is connected to the 64 inputs we have 64x50 = 3200 weights to the hidden layer. \n", - "\n", - "* Output\n", - "\n", - "If we were building a binary classifier, it would be sufficient with a single neuron in the output layer,\n", - "which could output 0 or 1 according to the Heaviside function. This would be an example of a *hard* classifier, meaning it outputs the class of the input directly. However, if we are dealing with noisy data it is often beneficial to use a *soft* classifier, which outputs the probability of being in class 0 or 1. \n", - "\n", - "For a soft binary classifier, we could use a single neuron and interpret the output as either being the probability of being in class 0 or the probability of being in class 1. Alternatively we could use 2 neurons, and interpret each neuron as the probability of being in each class. \n", - "\n", - "Since we are doing multiclass classification, with 10 categories, it is natural to use 10 neurons in the output layer. We number the neurons $j = 0,1,...,9$. The activation of each output neuron $j$ will be according to the *softmax* function: \n", - "\n", - "$$ P(\\text{class $j$} \\mid \\text{input $\\boldsymbol{a}$}) = \\frac{\\exp{(\\boldsymbol{a}^T \\boldsymbol{w}_j)}}\n", - "{\\sum_{c=0}^{9} \\exp{(\\boldsymbol{a}^T \\boldsymbol{w}_c)}} ,$$ \n", - "\n", - "i.e. each neuron $j$ outputs the probability of being in class $j$ given an input from the hidden layer $\\boldsymbol{a}$, with $\\boldsymbol{w}_j$ the weights of neuron $j$ to the inputs. \n", - "The denominator is a normalization factor to ensure the outputs (probabilities) sum up to 1. \n", - "The exponent is just the weighted sum of inputs as before: \n", - "\n", - "$$ z_j = \\sum_{i=1}^n w_ {ij} a_i+b_j.$$ \n", - "\n", - "Since each neuron in the output layer is connected to the 50 inputs from the hidden layer we have 50x10 = 500\n", - "weights to the output layer." - ] - }, - { - "cell_type": "markdown", - "id": "5ea9e948", - "metadata": {}, - "source": [ - "## Weights and biases\n", - "\n", - "Typically weights are initialized with small values distributed around zero, drawn from a uniform\n", - "or normal distribution. Setting all weights to zero means all neurons give the same output, making the network useless. \n", - "\n", - "Adding a bias value to the weighted sum of inputs allows the neural network to represent a greater range\n", - "of values. Without it, any input with the value 0 will be mapped to zero (before being passed through the activation). The bias unit has an output of 1, and a weight to each neuron $j$, $b_j$: \n", - "\n", - "$$ z_j = \\sum_{i=1}^n w_ {ij} a_i + b_j.$$ \n", - "\n", - "The bias weights $\\boldsymbol{b}$ are often initialized to zero, but a small value like $0.01$ ensures all neurons have some output which can be backpropagated in the first training cycle." - ] - }, - { - "cell_type": "code", - "execution_count": 7, - "id": "890bc8b7", - "metadata": {}, - "outputs": [], - "source": [ - "# building our neural network\n", - "\n", - "n_inputs, n_features = X_train.shape\n", - "n_hidden_neurons = 50\n", - "n_categories = 10\n", - "\n", - "# we make the weights normally distributed using numpy.random.randn\n", - "\n", - "# weights and bias in the hidden layer\n", - "hidden_weights = np.random.randn(n_features, n_hidden_neurons)\n", - "hidden_bias = np.zeros(n_hidden_neurons) + 0.01\n", - "\n", - "# weights and bias in the output layer\n", - "output_weights = np.random.randn(n_hidden_neurons, n_categories)\n", - "output_bias = np.zeros(n_categories) + 0.01" - ] - }, - { - "cell_type": "markdown", - "id": "1acc9cfe", - "metadata": {}, - "source": [ - "## Feed-forward pass\n", - "\n", - "Denote $F$ the number of features, $H$ the number of hidden neurons and $C$ the number of categories. \n", - "For each input image we calculate a weighted sum of input features (pixel values) to each neuron $j$ in the hidden layer $l$: \n", - "\n", - "$$ z_{j}^{l} = \\sum_{i=1}^{F} w_{ij}^{l} x_i + b_{j}^{l},$$\n", - "\n", - "this is then passed through our activation function \n", - "\n", - "$$ a_{j}^{l} = f(z_{j}^{l}) .$$ \n", - "\n", - "We calculate a weighted sum of inputs (activations in the hidden layer) to each neuron $j$ in the output layer: \n", - "\n", - "$$ z_{j}^{L} = \\sum_{i=1}^{H} w_{ij}^{L} a_{i}^{l} + b_{j}^{L}.$$ \n", - "\n", - "Finally we calculate the output of neuron $j$ in the output layer using the softmax function: \n", - "\n", - "$$ a_{j}^{L} = \\frac{\\exp{(z_j^{L})}}\n", - "{\\sum_{c=0}^{C-1} \\exp{(z_c^{L})}} .$$" - ] - }, - { - "cell_type": "markdown", - "id": "e13f966a", - "metadata": {}, - "source": [ - "## Matrix multiplications\n", - "\n", - "Since our data has the dimensions $X = (n_{inputs}, n_{features})$ and our weights to the hidden\n", - "layer have the dimensions \n", - "$W_{hidden} = (n_{features}, n_{hidden})$,\n", - "we can easily feed the network all our training data in one go by taking the matrix product \n", - "\n", - "$$ X W^{h} = (n_{inputs}, n_{hidden}),$$ \n", - "\n", - "and obtain a matrix that holds the weighted sum of inputs to the hidden layer\n", - "for each input image and each hidden neuron. \n", - "We also add the bias to obtain a matrix of weighted sums to the hidden layer $Z^{h}$: \n", - "\n", - "$$ \\boldsymbol{z}^{l} = \\boldsymbol{X} \\boldsymbol{W}^{l} + \\boldsymbol{b}^{l} ,$$\n", - "\n", - "meaning the same bias (1D array with size equal number of hidden neurons) is added to each input image. \n", - "This is then passed through the activation: \n", - "\n", - "$$ \\boldsymbol{a}^{l} = f(\\boldsymbol{z}^l) .$$ \n", - "\n", - "This is fed to the output layer: \n", - "\n", - "$$ \\boldsymbol{z}^{L} = \\boldsymbol{a}^{L} \\boldsymbol{W}^{L} + \\boldsymbol{b}^{L} .$$\n", - "\n", - "Finally we receive our output values for each image and each category by passing it through the softmax function: \n", - "\n", - "$$ output = softmax (\\boldsymbol{z}^{L}) = (n_{inputs}, n_{categories}) .$$" - ] - }, - { - "cell_type": "code", - "execution_count": 8, - "id": "8df5db3a", - "metadata": {}, - "outputs": [], - "source": [ - "# setup the feed-forward pass, subscript h = hidden layer\n", - "\n", - "def sigmoid(x):\n", - " return 1/(1 + np.exp(-x))\n", - "\n", - "def feed_forward(X):\n", - " # weighted sum of inputs to the hidden layer\n", - " z_h = np.matmul(X, hidden_weights) + hidden_bias\n", - " # activation in the hidden layer\n", - " a_h = sigmoid(z_h)\n", - " \n", - " # weighted sum of inputs to the output layer\n", - " z_o = np.matmul(a_h, output_weights) + output_bias\n", - " # softmax output\n", - " # axis 0 holds each input and axis 1 the probabilities of each category\n", - " exp_term = np.exp(z_o)\n", - " probabilities = exp_term / np.sum(exp_term, axis=1, keepdims=True)\n", - " \n", - " return probabilities\n", - "\n", - "probabilities = feed_forward(X_train)\n", - "print(\"probabilities = (n_inputs, n_categories) = \" + str(probabilities.shape))\n", - "print(\"probability that image 0 is in category 0,1,2,...,9 = \\n\" + str(probabilities[0]))\n", - "print(\"probabilities sum up to: \" + str(probabilities[0].sum()))\n", - "print()\n", - "\n", - "# we obtain a prediction by taking the class with the highest likelihood\n", - "def predict(X):\n", - " probabilities = feed_forward(X)\n", - " return np.argmax(probabilities, axis=1)\n", - "\n", - "predictions = predict(X_train)\n", - "print(\"predictions = (n_inputs) = \" + str(predictions.shape))\n", - "print(\"prediction for image 0: \" + str(predictions[0]))\n", - "print(\"correct label for image 0: \" + str(Y_train[0]))" - ] - }, - { - "cell_type": "markdown", - "id": "aa73fc1e", - "metadata": {}, - "source": [ - "## Choose cost function and optimizer\n", - "\n", - "To measure how well our neural network is doing we need to introduce a cost function. \n", - "We will call the function that gives the error of a single sample output the *loss* function, and the function\n", - "that gives the total error of our network across all samples the *cost* function.\n", - "A typical choice for multiclass classification is the *cross-entropy* loss, also known as the negative log likelihood. \n", - "\n", - "In *multiclass* classification it is common to treat each integer label as a so called *one-hot* vector: \n", - "\n", - "$$ y = 5 \\quad \\rightarrow \\quad \\boldsymbol{y} = (0, 0, 0, 0, 0, 1, 0, 0, 0, 0) ,$$ \n", - "\n", - "$$ y = 1 \\quad \\rightarrow \\quad \\boldsymbol{y} = (0, 1, 0, 0, 0, 0, 0, 0, 0, 0) ,$$ \n", - "\n", - "i.e. a binary bit string of length $C$, where $C = 10$ is the number of classes in the MNIST dataset. \n", - "\n", - "Let $y_{ic}$ denote the $c$-th component of the $i$-th one-hot vector. \n", - "We define the cost function $\\mathcal{C}$ as a sum over the cross-entropy loss for each point $\\boldsymbol{x}_i$ in the dataset.\n", - "\n", - "In the one-hot representation only one of the terms in the loss function is non-zero, namely the\n", - "probability of the correct category $c'$ \n", - "(i.e. the category $c'$ such that $y_{ic'} = 1$). This means that the cross entropy loss only punishes you for how wrong\n", - "you got the correct label. The probability of category $c$ is given by the softmax function. The vector $\\boldsymbol{\\theta}$ represents the parameters of our network, i.e. all the weights and biases." - ] - }, - { - "cell_type": "markdown", - "id": "74081e44", - "metadata": {}, - "source": [ - "## Optimizing the cost function\n", - "\n", - "The network is trained by finding the weights and biases that minimize the cost function. One of the most widely used classes of methods is *gradient descent* and its generalizations. The idea behind gradient descent\n", - "is simply to adjust the weights in the direction where the gradient of the cost function is large and negative. This ensures we flow toward a *local* minimum of the cost function. \n", - "Each parameter $\\theta$ is iteratively adjusted according to the rule \n", - "\n", - "$$ \\theta_{i+1} = \\theta_i - \\eta \\nabla \\mathcal{C}(\\theta_i) ,$$\n", - "\n", - "where $\\eta$ is known as the *learning rate*, which controls how big a step we take towards the minimum. \n", - "This update can be repeated for any number of iterations, or until we are satisfied with the result. \n", - "\n", - "A simple and effective improvement is a variant called *Batch Gradient Descent*. \n", - "Instead of calculating the gradient on the whole dataset, we calculate an approximation of the gradient\n", - "on a subset of the data called a *minibatch*. \n", - "If there are $N$ data points and we have a minibatch size of $M$, the total number of batches\n", - "is $N/M$. \n", - "We denote each minibatch $B_k$, with $k = 1, 2,...,N/M$. The gradient then becomes: \n", - "\n", - "$$ \\nabla \\mathcal{C}(\\theta) = \\frac{1}{N} \\sum_{i=1}^N \\nabla \\mathcal{L}_i(\\theta) \\quad \\rightarrow \\quad\n", - "\\frac{1}{M} \\sum_{i \\in B_k} \\nabla \\mathcal{L}_i(\\theta) ,$$\n", - "\n", - "i.e. instead of averaging the loss over the entire dataset, we average over a minibatch. \n", - "\n", - "This has two important benefits: \n", - "1. Introducing stochasticity decreases the chance that the algorithm becomes stuck in a local minima. \n", - "\n", - "2. It significantly speeds up the calculation, since we do not have to use the entire dataset to calculate the gradient. \n", - "\n", - "The various optmization methods, with codes and algorithms, are discussed in our lectures on [Gradient descent approaches](https://compphysics.github.io/MachineLearning/doc/pub/Splines/html/Splines-bs.html)." - ] - }, - { - "cell_type": "markdown", - "id": "1e1c4fe3", - "metadata": {}, - "source": [ - "## Regularization\n", - "\n", - "It is common to add an extra term to the cost function, proportional\n", - "to the size of the weights. This is equivalent to constraining the\n", - "size of the weights, so that they do not grow out of control.\n", - "Constraining the size of the weights means that the weights cannot\n", - "grow arbitrarily large to fit the training data, and in this way\n", - "reduces *overfitting*.\n", - "\n", - "We will measure the size of the weights using the so called *L2-norm*, meaning our cost function becomes: \n", - "\n", - "$$ \\mathcal{C}(\\theta) = \\frac{1}{N} \\sum_{i=1}^N \\mathcal{L}_i(\\theta) \\quad \\rightarrow \\quad\n", - "\\frac{1}{N} \\sum_{i=1}^N \\mathcal{L}_i(\\theta) + \\lambda \\lvert \\lvert \\boldsymbol{w} \\rvert \\rvert_2^2 \n", - "= \\frac{1}{N} \\sum_{i=1}^N \\mathcal{L}(\\theta) + \\lambda \\sum_{ij} w_{ij}^2,$$ \n", - "\n", - "i.e. we sum up all the weights squared. The factor $\\lambda$ is known as a regularization parameter.\n", - "\n", - "In order to train the model, we need to calculate the derivative of\n", - "the cost function with respect to every bias and weight in the\n", - "network. In total our network has $(64 + 1)\\times 50=3250$ weights in\n", - "the hidden layer and $(50 + 1)\\times 10=510$ weights to the output\n", - "layer ($+1$ for the bias), and the gradient must be calculated for\n", - "every parameter. We use the *backpropagation* algorithm discussed\n", - "above. This is a clever use of the chain rule that allows us to\n", - "calculate the gradient efficently." - ] - }, - { - "cell_type": "markdown", - "id": "6f66a9ad", - "metadata": {}, - "source": [ - "## Matrix multiplication\n", - "\n", - "To more efficently train our network these equations are implemented using matrix operations. \n", - "The error in the output layer is calculated simply as, with $\\boldsymbol{t}$ being our targets, \n", - "\n", - "$$ \\delta_L = \\boldsymbol{t} - \\boldsymbol{y} = (n_{inputs}, n_{categories}) .$$ \n", - "\n", - "The gradient for the output weights is calculated as \n", - "\n", - "$$ \\nabla W_{L} = \\boldsymbol{a}^T \\delta_L = (n_{hidden}, n_{categories}) ,$$\n", - "\n", - "where $\\boldsymbol{a} = (n_{inputs}, n_{hidden})$. This simply means that we are summing up the gradients for each input. \n", - "Since we are going backwards we have to transpose the activation matrix. \n", - "\n", - "The gradient with respect to the output bias is then \n", - "\n", - "$$ \\nabla \\boldsymbol{b}_{L} = \\sum_{i=1}^{n_{inputs}} \\delta_L = (n_{categories}) .$$ \n", - "\n", - "The error in the hidden layer is \n", - "\n", - "$$ \\Delta_h = \\delta_L W_{L}^T \\circ f'(z_{h}) = \\delta_L W_{L}^T \\circ a_{h} \\circ (1 - a_{h}) = (n_{inputs}, n_{hidden}) ,$$ \n", - "\n", - "where $f'(a_{h})$ is the derivative of the activation in the hidden layer. The matrix products mean\n", - "that we are summing up the products for each neuron in the output layer. The symbol $\\circ$ denotes\n", - "the *Hadamard product*, meaning element-wise multiplication. \n", - "\n", - "This again gives us the gradients in the hidden layer: \n", - "\n", - "$$ \\nabla W_{h} = X^T \\delta_h = (n_{features}, n_{hidden}) ,$$ \n", - "\n", - "$$ \\nabla b_{h} = \\sum_{i=1}^{n_{inputs}} \\delta_h = (n_{hidden}) .$$" - ] - }, - { - "cell_type": "code", - "execution_count": 9, - "id": "b4ba72fe", - "metadata": {}, - "outputs": [], - "source": [ - "# to categorical turns our integer vector into a onehot representation\n", - "from sklearn.metrics import accuracy_score\n", - "\n", - "# one-hot in numpy\n", - "def to_categorical_numpy(integer_vector):\n", - " n_inputs = len(integer_vector)\n", - " n_categories = np.max(integer_vector) + 1\n", - " onehot_vector = np.zeros((n_inputs, n_categories))\n", - " onehot_vector[range(n_inputs), integer_vector] = 1\n", - " \n", - " return onehot_vector\n", - "\n", - "#Y_train_onehot, Y_test_onehot = to_categorical(Y_train), to_categorical(Y_test)\n", - "Y_train_onehot, Y_test_onehot = to_categorical_numpy(Y_train), to_categorical_numpy(Y_test)\n", - "\n", - "def feed_forward_train(X):\n", - " # weighted sum of inputs to the hidden layer\n", - " z_h = np.matmul(X, hidden_weights) + hidden_bias\n", - " # activation in the hidden layer\n", - " a_h = sigmoid(z_h)\n", - " \n", - " # weighted sum of inputs to the output layer\n", - " z_o = np.matmul(a_h, output_weights) + output_bias\n", - " # softmax output\n", - " # axis 0 holds each input and axis 1 the probabilities of each category\n", - " exp_term = np.exp(z_o)\n", - " probabilities = exp_term / np.sum(exp_term, axis=1, keepdims=True)\n", - " \n", - " # for backpropagation need activations in hidden and output layers\n", - " return a_h, probabilities\n", - "\n", - "def backpropagation(X, Y):\n", - " a_h, probabilities = feed_forward_train(X)\n", - " \n", - " # error in the output layer\n", - " error_output = probabilities - Y\n", - " # error in the hidden layer\n", - " error_hidden = np.matmul(error_output, output_weights.T) * a_h * (1 - a_h)\n", - " \n", - " # gradients for the output layer\n", - " output_weights_gradient = np.matmul(a_h.T, error_output)\n", - " output_bias_gradient = np.sum(error_output, axis=0)\n", - " \n", - " # gradient for the hidden layer\n", - " hidden_weights_gradient = np.matmul(X.T, error_hidden)\n", - " hidden_bias_gradient = np.sum(error_hidden, axis=0)\n", - "\n", - " return output_weights_gradient, output_bias_gradient, hidden_weights_gradient, hidden_bias_gradient\n", - "\n", - "print(\"Old accuracy on training data: \" + str(accuracy_score(predict(X_train), Y_train)))\n", - "\n", - "eta = 0.01\n", - "lmbd = 0.01\n", - "for i in range(1000):\n", - " # calculate gradients\n", - " dWo, dBo, dWh, dBh = backpropagation(X_train, Y_train_onehot)\n", - " \n", - " # regularization term gradients\n", - " dWo += lmbd * output_weights\n", - " dWh += lmbd * hidden_weights\n", - " \n", - " # update weights and biases\n", - " output_weights -= eta * dWo\n", - " output_bias -= eta * dBo\n", - " hidden_weights -= eta * dWh\n", - " hidden_bias -= eta * dBh\n", - "\n", - "print(\"New accuracy on training data: \" + str(accuracy_score(predict(X_train), Y_train)))" - ] - }, - { - "cell_type": "markdown", - "id": "1bf824b2", - "metadata": {}, - "source": [ - "## Improving performance\n", - "\n", - "As we can see the network does not seem to be learning at all. It seems to be just guessing the label for each image. \n", - "In order to obtain a network that does something useful, we will have to do a bit more work. \n", - "\n", - "The choice of *hyperparameters* such as learning rate and regularization parameter is hugely influential for the performance of the network. Typically a *grid-search* is performed, wherein we test different hyperparameters separated by orders of magnitude. For example we could test the learning rates $\\eta = 10^{-6}, 10^{-5},...,10^{-1}$ with different regularization parameters $\\lambda = 10^{-6},...,10^{-0}$. \n", - "\n", - "Next, we haven't implemented minibatching yet, which introduces stochasticity and is though to act as an important regularizer on the weights. We call a feed-forward + backward pass with a minibatch an *iteration*, and a full training period\n", - "going through the entire dataset ($n/M$ batches) an *epoch*.\n", - "\n", - "If this does not improve network performance, you may want to consider altering the network architecture, adding more neurons or hidden layers. \n", - "Andrew Ng goes through some of these considerations in this [video](https://youtu.be/F1ka6a13S9I). You can find a summary of the video [here](https://kevinzakka.github.io/2016/09/26/applying-deep-learning/)." - ] - }, - { - "cell_type": "markdown", - "id": "c98cec8d", - "metadata": {}, - "source": [ - "## Full object-oriented implementation\n", - "\n", - "It is very natural to think of the network as an object, with specific instances of the network\n", - "being realizations of this object with different hyperparameters. An implementation using Python classes provides a clean structure and interface, and the full implementation of our neural network is given below." - ] - }, - { - "cell_type": "code", - "execution_count": 10, - "id": "26d4691e", - "metadata": {}, - "outputs": [], - "source": [ - "class NeuralNetwork:\n", - " def __init__(\n", - " self,\n", - " X_data,\n", - " Y_data,\n", - " n_hidden_neurons=50,\n", - " n_categories=10,\n", - " epochs=10,\n", - " batch_size=100,\n", - " eta=0.1,\n", - " lmbd=0.0):\n", - "\n", - " self.X_data_full = X_data\n", - " self.Y_data_full = Y_data\n", - "\n", - " self.n_inputs = X_data.shape[0]\n", - " self.n_features = X_data.shape[1]\n", - " self.n_hidden_neurons = n_hidden_neurons\n", - " self.n_categories = n_categories\n", - "\n", - " self.epochs = epochs\n", - " self.batch_size = batch_size\n", - " self.iterations = self.n_inputs // self.batch_size\n", - " self.eta = eta\n", - " self.lmbd = lmbd\n", - "\n", - " self.create_biases_and_weights()\n", - "\n", - " def create_biases_and_weights(self):\n", - " self.hidden_weights = np.random.randn(self.n_features, self.n_hidden_neurons)\n", - " self.hidden_bias = np.zeros(self.n_hidden_neurons) + 0.01\n", - "\n", - " self.output_weights = np.random.randn(self.n_hidden_neurons, self.n_categories)\n", - " self.output_bias = np.zeros(self.n_categories) + 0.01\n", - "\n", - " def feed_forward(self):\n", - " # feed-forward for training\n", - " self.z_h = np.matmul(self.X_data, self.hidden_weights) + self.hidden_bias\n", - " self.a_h = sigmoid(self.z_h)\n", - "\n", - " self.z_o = np.matmul(self.a_h, self.output_weights) + self.output_bias\n", - "\n", - " exp_term = np.exp(self.z_o)\n", - " self.probabilities = exp_term / np.sum(exp_term, axis=1, keepdims=True)\n", - "\n", - " def feed_forward_out(self, X):\n", - " # feed-forward for output\n", - " z_h = np.matmul(X, self.hidden_weights) + self.hidden_bias\n", - " a_h = sigmoid(z_h)\n", - "\n", - " z_o = np.matmul(a_h, self.output_weights) + self.output_bias\n", - " \n", - " exp_term = np.exp(z_o)\n", - " probabilities = exp_term / np.sum(exp_term, axis=1, keepdims=True)\n", - " return probabilities\n", - "\n", - " def backpropagation(self):\n", - " error_output = self.probabilities - self.Y_data\n", - " error_hidden = np.matmul(error_output, self.output_weights.T) * self.a_h * (1 - self.a_h)\n", - "\n", - " self.output_weights_gradient = np.matmul(self.a_h.T, error_output)\n", - " self.output_bias_gradient = np.sum(error_output, axis=0)\n", - "\n", - " self.hidden_weights_gradient = np.matmul(self.X_data.T, error_hidden)\n", - " self.hidden_bias_gradient = np.sum(error_hidden, axis=0)\n", - "\n", - " if self.lmbd > 0.0:\n", - " self.output_weights_gradient += self.lmbd * self.output_weights\n", - " self.hidden_weights_gradient += self.lmbd * self.hidden_weights\n", - "\n", - " self.output_weights -= self.eta * self.output_weights_gradient\n", - " self.output_bias -= self.eta * self.output_bias_gradient\n", - " self.hidden_weights -= self.eta * self.hidden_weights_gradient\n", - " self.hidden_bias -= self.eta * self.hidden_bias_gradient\n", - "\n", - " def predict(self, X):\n", - " probabilities = self.feed_forward_out(X)\n", - " return np.argmax(probabilities, axis=1)\n", - "\n", - " def predict_probabilities(self, X):\n", - " probabilities = self.feed_forward_out(X)\n", - " return probabilities\n", - "\n", - " def train(self):\n", - " data_indices = np.arange(self.n_inputs)\n", - "\n", - " for i in range(self.epochs):\n", - " for j in range(self.iterations):\n", - " # pick datapoints with replacement\n", - " chosen_datapoints = np.random.choice(\n", - " data_indices, size=self.batch_size, replace=False\n", - " )\n", - "\n", - " # minibatch training data\n", - " self.X_data = self.X_data_full[chosen_datapoints]\n", - " self.Y_data = self.Y_data_full[chosen_datapoints]\n", - "\n", - " self.feed_forward()\n", - " self.backpropagation()" - ] - }, - { - "cell_type": "markdown", - "id": "24f75613", - "metadata": {}, - "source": [ - "## Evaluate model performance on test data\n", - "\n", - "To measure the performance of our network we evaluate how well it does it data it has never seen before, i.e. the test data. \n", - "We measure the performance of the network using the *accuracy* score. \n", - "The accuracy is as you would expect just the number of images correctly labeled divided by the total number of images. A perfect classifier will have an accuracy score of $1$. \n", - "\n", - "$$ \\text{Accuracy} = \\frac{\\sum_{i=1}^n I(\\tilde{y}_i = y_i)}{n} ,$$ \n", - "\n", - "where $I$ is the indicator function, $1$ if $\\tilde{y}_i = y_i$ and $0$ otherwise." - ] - }, - { - "cell_type": "code", - "execution_count": 11, - "id": "52a987ae", - "metadata": {}, - "outputs": [], - "source": [ - "epochs = 100\n", - "batch_size = 100\n", - "\n", - "dnn = NeuralNetwork(X_train, Y_train_onehot, eta=eta, lmbd=lmbd, epochs=epochs, batch_size=batch_size,\n", - " n_hidden_neurons=n_hidden_neurons, n_categories=n_categories)\n", - "dnn.train()\n", - "test_predict = dnn.predict(X_test)\n", - "\n", - "# accuracy score from scikit library\n", - "print(\"Accuracy score on test set: \", accuracy_score(Y_test, test_predict))\n", - "\n", - "# equivalent in numpy\n", - "def accuracy_score_numpy(Y_test, Y_pred):\n", - " return np.sum(Y_test == Y_pred) / len(Y_test)\n", - "\n", - "#print(\"Accuracy score on test set: \", accuracy_score_numpy(Y_test, test_predict))" - ] - }, - { - "cell_type": "markdown", - "id": "1605eb14", - "metadata": {}, - "source": [ - "## Adjust hyperparameters\n", - "\n", - "We now perform a grid search to find the optimal hyperparameters for the network. \n", - "Note that we are only using 1 layer with 50 neurons, and human performance is estimated to be around $98\\%$ ($2\\%$ error rate)." - ] - }, - { - "cell_type": "code", - "execution_count": 12, - "id": "952131d2", - "metadata": {}, - "outputs": [], - "source": [ - "eta_vals = np.logspace(-5, 1, 7)\n", - "lmbd_vals = np.logspace(-5, 1, 7)\n", - "# store the models for later use\n", - "DNN_numpy = np.zeros((len(eta_vals), len(lmbd_vals)), dtype=object)\n", - "\n", - "# grid search\n", - "for i, eta in enumerate(eta_vals):\n", - " for j, lmbd in enumerate(lmbd_vals):\n", - " dnn = NeuralNetwork(X_train, Y_train_onehot, eta=eta, lmbd=lmbd, epochs=epochs, batch_size=batch_size,\n", - " n_hidden_neurons=n_hidden_neurons, n_categories=n_categories)\n", - " dnn.train()\n", - " \n", - " DNN_numpy[i][j] = dnn\n", - " \n", - " test_predict = dnn.predict(X_test)\n", - " \n", - " print(\"Learning rate = \", eta)\n", - " print(\"Lambda = \", lmbd)\n", - " print(\"Accuracy score on test set: \", accuracy_score(Y_test, test_predict))\n", - " print()" - ] - }, - { - "cell_type": "markdown", - "id": "182a8a49", - "metadata": {}, - "source": [ - "## Visualization" - ] - }, - { - "cell_type": "code", - "execution_count": 13, - "id": "d3d1b7d5", - "metadata": {}, - "outputs": [], - "source": [ - "# visual representation of grid search\n", - "# uses seaborn heatmap, you can also do this with matplotlib imshow\n", - "import seaborn as sns\n", - "\n", - "sns.set()\n", - "\n", - "train_accuracy = np.zeros((len(eta_vals), len(lmbd_vals)))\n", - "test_accuracy = np.zeros((len(eta_vals), len(lmbd_vals)))\n", - "\n", - "for i in range(len(eta_vals)):\n", - " for j in range(len(lmbd_vals)):\n", - " dnn = DNN_numpy[i][j]\n", - " \n", - " train_pred = dnn.predict(X_train) \n", - " test_pred = dnn.predict(X_test)\n", - "\n", - " train_accuracy[i][j] = accuracy_score(Y_train, train_pred)\n", - " test_accuracy[i][j] = accuracy_score(Y_test, test_pred)\n", - "\n", - " \n", - "fig, ax = plt.subplots(figsize = (10, 10))\n", - "sns.heatmap(train_accuracy, annot=True, ax=ax, cmap=\"viridis\")\n", - "ax.set_title(\"Training Accuracy\")\n", - "ax.set_ylabel(\"$\\eta$\")\n", - "ax.set_xlabel(\"$\\lambda$\")\n", - "plt.show()\n", - "\n", - "fig, ax = plt.subplots(figsize = (10, 10))\n", - "sns.heatmap(test_accuracy, annot=True, ax=ax, cmap=\"viridis\")\n", - "ax.set_title(\"Test Accuracy\")\n", - "ax.set_ylabel(\"$\\eta$\")\n", - "ax.set_xlabel(\"$\\lambda$\")\n", - "plt.show()" - ] - }, - { - "cell_type": "markdown", - "id": "aa705900", - "metadata": {}, - "source": [ - "## scikit-learn implementation\n", - "\n", - "**scikit-learn** focuses more\n", - "on traditional machine learning methods, such as regression,\n", - "clustering, decision trees, etc. As such, it has only two types of\n", - "neural networks: Multi Layer Perceptron outputting continuous values,\n", - "*MPLRegressor*, and Multi Layer Perceptron outputting labels,\n", - "*MLPClassifier*. We will see how simple it is to use these classes.\n", - "\n", - "**scikit-learn** implements a few improvements from our neural network,\n", - "such as early stopping, a varying learning rate, different\n", - "optimization methods, etc. We would therefore expect a better\n", - "performance overall." - ] - }, - { - "cell_type": "code", - "execution_count": 14, - "id": "09c32314", - "metadata": {}, - "outputs": [], - "source": [ - "from sklearn.neural_network import MLPClassifier\n", - "# store models for later use\n", - "DNN_scikit = np.zeros((len(eta_vals), len(lmbd_vals)), dtype=object)\n", - "\n", - "for i, eta in enumerate(eta_vals):\n", - " for j, lmbd in enumerate(lmbd_vals):\n", - " dnn = MLPClassifier(hidden_layer_sizes=(n_hidden_neurons), activation='logistic',\n", - " alpha=lmbd, learning_rate_init=eta, max_iter=epochs)\n", - " dnn.fit(X_train, Y_train)\n", - " \n", - " DNN_scikit[i][j] = dnn\n", - " \n", - " print(\"Learning rate = \", eta)\n", - " print(\"Lambda = \", lmbd)\n", - " print(\"Accuracy score on test set: \", dnn.score(X_test, Y_test))\n", - " print()" - ] - }, - { - "cell_type": "markdown", - "id": "fde4721e", - "metadata": {}, - "source": [ - "## Visualization" - ] - }, - { - "cell_type": "code", - "execution_count": 15, - "id": "e855729e", - "metadata": {}, - "outputs": [], - "source": [ - "# optional\n", - "# visual representation of grid search\n", - "# uses seaborn heatmap, could probably do this in matplotlib\n", - "import seaborn as sns\n", - "\n", - "sns.set()\n", - "\n", - "train_accuracy = np.zeros((len(eta_vals), len(lmbd_vals)))\n", - "test_accuracy = np.zeros((len(eta_vals), len(lmbd_vals)))\n", - "\n", - "for i in range(len(eta_vals)):\n", - " for j in range(len(lmbd_vals)):\n", - " dnn = DNN_scikit[i][j]\n", - " \n", - " train_pred = dnn.predict(X_train) \n", - " test_pred = dnn.predict(X_test)\n", - "\n", - " train_accuracy[i][j] = accuracy_score(Y_train, train_pred)\n", - " test_accuracy[i][j] = accuracy_score(Y_test, test_pred)\n", - "\n", - " \n", - "fig, ax = plt.subplots(figsize = (10, 10))\n", - "sns.heatmap(train_accuracy, annot=True, ax=ax, cmap=\"viridis\")\n", - "ax.set_title(\"Training Accuracy\")\n", - "ax.set_ylabel(\"$\\eta$\")\n", - "ax.set_xlabel(\"$\\lambda$\")\n", - "plt.show()\n", - "\n", - "fig, ax = plt.subplots(figsize = (10, 10))\n", - "sns.heatmap(test_accuracy, annot=True, ax=ax, cmap=\"viridis\")\n", - "ax.set_title(\"Test Accuracy\")\n", - "ax.set_ylabel(\"$\\eta$\")\n", - "ax.set_xlabel(\"$\\lambda$\")\n", - "plt.show()" - ] - }, - { - "cell_type": "markdown", - "id": "765ac227", - "metadata": {}, - "source": [ - "## Testing our code for the XOR, OR and AND gates\n", - "\n", - "Last week we discussed three different types of gates, the so-called\n", - "XOR, the OR and the AND gates. Their inputs and outputs can be\n", - "summarized using the following tables, first for the OR gate with\n", - "inputs $x_1$ and $x_2$ and outputs $y$:\n", - "\n", - "\n", - "\n", - "\n", - "\n", - "\n", - "\n", - "\n", - "\n", - "\n", - "\n", - "
$x_1$ $x_2$ $y$
0 0 0
0 1 1
1 0 1
1 1 1
" - ] - }, - { - "cell_type": "markdown", - "id": "02d395cd", - "metadata": {}, - "source": [ - "## The AND and XOR Gates\n", - "\n", - "The AND gate is defined as\n", - "\n", - "\n", - "\n", - "\n", - "\n", - "\n", - "\n", - "\n", - "\n", - "\n", - "\n", - "
$x_1$ $x_2$ $y$
0 0 0
0 1 0
1 0 0
1 1 1
\n", - "\n", - "And finally we have the XOR gate\n", - "\n", - "\n", - "\n", - "\n", - "\n", - "\n", - "\n", - "\n", - "\n", - "\n", - "\n", - "
$x_1$ $x_2$ $y$
0 0 0
0 1 1
1 0 1
1 1 0
" - ] - }, - { - "cell_type": "markdown", - "id": "0fba1e7d", - "metadata": {}, - "source": [ - "## Representing the Data Sets\n", - "\n", - "Our design matrix is defined by the input values $x_1$ and $x_2$. Since we have four possible outputs, our design matrix reads" - ] - }, - { - "cell_type": "markdown", - "id": "9a3c4e68", - "metadata": {}, - "source": [ - "$$\n", - "\\boldsymbol{X}=\\begin{bmatrix} 0 & 0 \\\\\n", - " 0 & 1 \\\\\n", - "\t\t 1 & 0 \\\\\n", - "\t\t 1 & 1 \\end{bmatrix},\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "545fccde", - "metadata": {}, - "source": [ - "while the vector of outputs is $\\boldsymbol{y}^T=[0,1,1,0]$ for the XOR gate, $\\boldsymbol{y}^T=[0,0,0,1]$ for the AND gate and $\\boldsymbol{y}^T=[0,1,1,1]$ for the OR gate." - ] - }, - { - "cell_type": "markdown", - "id": "678395d0", - "metadata": {}, - "source": [ - "## Setting up the Neural Network\n", - "\n", - "We define first our design matrix and the various output vectors for the different gates." - ] - }, - { - "cell_type": "code", - "execution_count": 16, - "id": "7c64daef", - "metadata": {}, - "outputs": [], - "source": [ - "\"\"\"\n", - "Simple code that tests XOR, OR and AND gates with linear regression\n", - "\"\"\"\n", - "\n", - "# import necessary packages\n", - "import numpy as np\n", - "import matplotlib.pyplot as plt\n", - "from sklearn import datasets\n", - "\n", - "def sigmoid(x):\n", - " return 1/(1 + np.exp(-x))\n", - "\n", - "def feed_forward(X):\n", - " # weighted sum of inputs to the hidden layer\n", - " z_h = np.matmul(X, hidden_weights) + hidden_bias\n", - " # activation in the hidden layer\n", - " a_h = sigmoid(z_h)\n", - " \n", - " # weighted sum of inputs to the output layer\n", - " z_o = np.matmul(a_h, output_weights) + output_bias\n", - " # softmax output\n", - " # axis 0 holds each input and axis 1 the probabilities of each category\n", - " probabilities = sigmoid(z_o)\n", - " return probabilities\n", - "\n", - "# we obtain a prediction by taking the class with the highest likelihood\n", - "def predict(X):\n", - " probabilities = feed_forward(X)\n", - " return np.argmax(probabilities, axis=1)\n", - "\n", - "# ensure the same random numbers appear every time\n", - "np.random.seed(0)\n", - "\n", - "# Design matrix\n", - "X = np.array([ [0, 0], [0, 1], [1, 0],[1, 1]],dtype=np.float64)\n", - "\n", - "# The XOR gate\n", - "yXOR = np.array( [ 0, 1 ,1, 0])\n", - "# The OR gate\n", - "yOR = np.array( [ 0, 1 ,1, 1])\n", - "# The AND gate\n", - "yAND = np.array( [ 0, 0 ,0, 1])\n", - "\n", - "# Defining the neural network\n", - "n_inputs, n_features = X.shape\n", - "n_hidden_neurons = 2\n", - "n_categories = 2\n", - "n_features = 2\n", - "\n", - "# we make the weights normally distributed using numpy.random.randn\n", - "\n", - "# weights and bias in the hidden layer\n", - "hidden_weights = np.random.randn(n_features, n_hidden_neurons)\n", - "hidden_bias = np.zeros(n_hidden_neurons) + 0.01\n", - "\n", - "# weights and bias in the output layer\n", - "output_weights = np.random.randn(n_hidden_neurons, n_categories)\n", - "output_bias = np.zeros(n_categories) + 0.01\n", - "\n", - "probabilities = feed_forward(X)\n", - "print(probabilities)\n", - "\n", - "\n", - "predictions = predict(X)\n", - "print(predictions)" - ] - }, - { - "cell_type": "markdown", - "id": "c35ff8f2", - "metadata": {}, - "source": [ - "Not an impressive result, but this was our first forward pass with randomly assigned weights. Let us now add the full network with the back-propagation algorithm discussed above." - ] - }, - { - "cell_type": "markdown", - "id": "3b5396c0", - "metadata": {}, - "source": [ - "## The Code using Scikit-Learn" - ] - }, - { - "cell_type": "code", - "execution_count": 17, - "id": "3d4e508b", - "metadata": {}, - "outputs": [], - "source": [ - "# import necessary packages\n", - "import numpy as np\n", - "import matplotlib.pyplot as plt\n", - "from sklearn.neural_network import MLPClassifier\n", - "from sklearn.metrics import accuracy_score\n", - "import seaborn as sns\n", - "\n", - "# ensure the same random numbers appear every time\n", - "np.random.seed(0)\n", - "\n", - "# Design matrix\n", - "X = np.array([ [0, 0], [0, 1], [1, 0],[1, 1]],dtype=np.float64)\n", - "\n", - "# The XOR gate\n", - "yXOR = np.array( [ 0, 1 ,1, 0])\n", - "# The OR gate\n", - "yOR = np.array( [ 0, 1 ,1, 1])\n", - "# The AND gate\n", - "yAND = np.array( [ 0, 0 ,0, 1])\n", - "\n", - "# Defining the neural network\n", - "n_inputs, n_features = X.shape\n", - "n_hidden_neurons = 2\n", - "n_categories = 2\n", - "n_features = 2\n", - "\n", - "eta_vals = np.logspace(-5, 1, 7)\n", - "lmbd_vals = np.logspace(-5, 1, 7)\n", - "# store models for later use\n", - "DNN_scikit = np.zeros((len(eta_vals), len(lmbd_vals)), dtype=object)\n", - "epochs = 100\n", - "\n", - "for i, eta in enumerate(eta_vals):\n", - " for j, lmbd in enumerate(lmbd_vals):\n", - " dnn = MLPClassifier(hidden_layer_sizes=(n_hidden_neurons), activation='logistic',\n", - " alpha=lmbd, learning_rate_init=eta, max_iter=epochs)\n", - " dnn.fit(X, yXOR)\n", - " DNN_scikit[i][j] = dnn\n", - " print(\"Learning rate = \", eta)\n", - " print(\"Lambda = \", lmbd)\n", - " print(\"Accuracy score on data set: \", dnn.score(X, yXOR))\n", - " print()\n", - "\n", - "sns.set()\n", - "test_accuracy = np.zeros((len(eta_vals), len(lmbd_vals)))\n", - "for i in range(len(eta_vals)):\n", - " for j in range(len(lmbd_vals)):\n", - " dnn = DNN_scikit[i][j]\n", - " test_pred = dnn.predict(X)\n", - " test_accuracy[i][j] = accuracy_score(yXOR, test_pred)\n", - "\n", - "fig, ax = plt.subplots(figsize = (10, 10))\n", - "sns.heatmap(test_accuracy, annot=True, ax=ax, cmap=\"viridis\")\n", - "ax.set_title(\"Test Accuracy\")\n", - "ax.set_ylabel(\"$\\eta$\")\n", - "ax.set_xlabel(\"$\\lambda$\")\n", - "plt.show()" - ] - } - ], - "metadata": { - "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.9.10" - } - }, - "nbformat": 4, - "nbformat_minor": 5 -} diff --git a/doc/LectureNotes/week42.ipynb b/doc/LectureNotes/week42.ipynb deleted file mode 100644 index 8d7906a77..000000000 --- a/doc/LectureNotes/week42.ipynb +++ /dev/null @@ -1,2643 +0,0 @@ -{ - "cells": [ - { - "cell_type": "markdown", - "id": "bbaa1aec", - "metadata": {}, - "source": [ - "\n", - "" - ] - }, - { - "cell_type": "markdown", - "id": "d981139a", - "metadata": {}, - "source": [ - "# Week 42 Constructing a Neural Network code with introduction to Tensor flow\n", - "**Morten Hjorth-Jensen**, Department of Physics, University of Oslo and Department of Physics and Astronomy and Facility for Rare Isotope Beams, Michigan State University\n", - "\n", - "Date: **October 16-20, 2023**" - ] - }, - { - "cell_type": "markdown", - "id": "d3d2fdcb", - "metadata": {}, - "source": [ - "## Plan for week 42\n", - "\n", - "**Material for the active learning sessions on Tuesday and Wednesday.**\n", - "\n", - " * Exercise on writing your own stochastic gradient and gradient descent codes. This exercise continues from the previous week but now with inclusion of automatic differentiation\n", - "\n", - " * Discussion of project 2\n", - "\n", - " * [See video on automatic differentiation from last year](https://www.youtube.com/watch?v=cWCebuNKrA8). This video will be updated before Tuesday.\n", - "\n", - " \n", - "\n", - "**Material for the lecture on Thursday October 12, 2023.**\n", - "\n", - " * Building our own Feed-forward Neural Network and discussion of project 2\n", - "\n", - " * Readings and Videos:\n", - "\n", - " * These lecture notes\n", - "\n", - " * [Video of lecture](https://youtu.be/0q5-PhovchQ)\n", - "\n", - " * [Whiteboard notes](https://github.com/CompPhysics/MachineLearning/blob/master/doc/HandWrittenNotes/2023/NotesOct19.pdf)\n", - "\n", - " * [Aurelien Geron's chapters 10-11](https://github.com/CompPhysics/MachineLearning/blob/master/doc/Textbooks/TensorflowML.pdf)\n", - "\n", - " * For a more in depth discussion on neural networks we recommend Goodfellow et al chapters 6 and 7. \n", - "\n", - " * [Neural Networks demystified](https://www.youtube.com/watch?v=bxe2T-V8XRs&list=PLiaHhY2iBX9hdHaRr6b7XevZtgZRa1PoU&ab_channel=WelchLabs)\n", - "\n", - " * [Building Neural Networks from scratch](https://www.youtube.com/watch?v=Wo5dMEP_BbI&list=PLQVvvaa0QuDcjD5BAw2DxE6OF2tius3V3&ab_channel=sentdex)\n", - "\n", - " * [Video on Neural Networks](https://www.youtube.com/watch?v=CqOfi41LfDw)\n", - "\n", - " * [Video on the back propagation algorithm](https://www.youtube.com/watch?v=Ilg3gGewQ5U)\n", - "\n", - "I also recommend Michael Nielsen's intuitive approach to the neural networks and the universal approximation theorem, see the slides at ." - ] - }, - { - "cell_type": "markdown", - "id": "8e0c0ad3", - "metadata": {}, - "source": [ - "## Lecture Thursday October 19" - ] - }, - { - "cell_type": "markdown", - "id": "6d072b79", - "metadata": {}, - "source": [ - "## Review of the back propagation algorithm\n", - "\n", - "During the last lecture we discussed in detail the back propagation\n", - "algorithm. This algorithm is based on a repeated application of the\n", - "chain rule. Let us bring back the basic equation and at the same time\n", - "link this with the basic mathematics of automatic differentiation." - ] - }, - { - "cell_type": "markdown", - "id": "6a5894d2", - "metadata": {}, - "source": [ - "## Setting up the Back propagation algorithm\n", - "\n", - "The four equations derived last week provide us with a way of computing the gradient of the cost function. Let us write this out in the form of an algorithm.\n", - "\n", - "First, we set up the input data $\\boldsymbol{x}$ and the activations\n", - "$\\boldsymbol{z}_1$ of the input layer and compute the activation function and\n", - "the pertinent outputs $\\boldsymbol{a}^1$.\n", - "\n", - "Secondly, we perform then the feed forward till we reach the output\n", - "layer and compute all $\\boldsymbol{z}_l$ of the input layer and compute the\n", - "activation function and the pertinent outputs $\\boldsymbol{a}^l$ for\n", - "$l=2,3,\\dots,L$.\n", - "\n", - "Thereafter we compute the ouput error $\\boldsymbol{\\delta}^L$ by computing all" - ] - }, - { - "cell_type": "markdown", - "id": "47296efd", - "metadata": {}, - "source": [ - "$$\n", - "\\delta_j^L = f'(z_j^L)\\frac{\\partial {\\cal C}}{\\partial (a_j^L)}.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "598d3a19", - "metadata": {}, - "source": [ - "Then we compute the back propagate error for each $l=L-1,L-2,\\dots,2$ as" - ] - }, - { - "cell_type": "markdown", - "id": "7077d9c2", - "metadata": {}, - "source": [ - "$$\n", - "\\delta_j^l = \\sum_k \\delta_k^{l+1}w_{kj}^{l+1}f'(z_j^l).\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "c62043b3", - "metadata": {}, - "source": [ - "Finally, we update the weights and the biases using gradient descent for each $l=L-1,L-2,\\dots,2$ and update the weights and biases according to the rules" - ] - }, - { - "cell_type": "markdown", - "id": "3307a4bc", - "metadata": {}, - "source": [ - "$$\n", - "w_{jk}^l\\leftarrow = w_{jk}^l- \\eta \\delta_j^la_k^{l-1},\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "50db23f1", - "metadata": {}, - "source": [ - "$$\n", - "b_j^l \\leftarrow b_j^l-\\eta \\frac{\\partial {\\cal C}}{\\partial b_j^l}=b_j^l-\\eta \\delta_j^l,\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "0cf89ca4", - "metadata": {}, - "source": [ - "The parameter $\\eta$ is the learning parameter discussed in connection with the gradient descent methods.\n", - "Here it is convenient to use stochastic gradient descent (see the examples below) with mini-batches with an outer loop that steps through multiple epochs of training." - ] - }, - { - "cell_type": "markdown", - "id": "d5374d6f", - "metadata": {}, - "source": [ - "## Setting up a Multi-layer perceptron model for classification\n", - "\n", - "We are now gong to develop an example based on the MNIST data\n", - "base. This is a classification problem and we need to use our\n", - "cross-entropy function we discussed in connection with logistic\n", - "regression. The cross-entropy defines our cost function for the\n", - "classificaton problems with neural networks.\n", - "\n", - "In binary classification with two classes $(0, 1)$ we define the\n", - "logistic/sigmoid function as the probability that a particular input\n", - "is in class $0$ or $1$. This is possible because the logistic\n", - "function takes any input from the real numbers and inputs a number\n", - "between 0 and 1, and can therefore be interpreted as a probability. It\n", - "also has other nice properties, such as a derivative that is simple to\n", - "calculate.\n", - "\n", - "For an input $\\boldsymbol{a}$ from the hidden layer, the probability that the input $\\boldsymbol{x}$\n", - "is in class 0 or 1 is just. We let $\\theta$ represent the unknown weights and biases to be adjusted by our equations). The variable $x$\n", - "represents our activation values $z$. We have" - ] - }, - { - "cell_type": "markdown", - "id": "fc8ce130", - "metadata": {}, - "source": [ - "$$\n", - "P(y = 0 \\mid \\boldsymbol{x}, \\boldsymbol{\\theta}) = \\frac{1}{1 + \\exp{(- \\boldsymbol{x}})} ,\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "8eaf0c3c", - "metadata": {}, - "source": [ - "and" - ] - }, - { - "cell_type": "markdown", - "id": "3caeb6b3", - "metadata": {}, - "source": [ - "$$\n", - "P(y = 1 \\mid \\boldsymbol{x}, \\boldsymbol{\\theta}) = 1 - P(y = 0 \\mid \\boldsymbol{x}, \\boldsymbol{\\theta}) ,\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "cb5b4f3d", - "metadata": {}, - "source": [ - "where $y \\in \\{0, 1\\}$ and $\\boldsymbol{\\theta}$ represents the weights and biases\n", - "of our network." - ] - }, - { - "cell_type": "markdown", - "id": "6edbd945", - "metadata": {}, - "source": [ - "## Defining the cost function\n", - "\n", - "Our cost function is given as (see the Logistic regression lectures)" - ] - }, - { - "cell_type": "markdown", - "id": "3e039295", - "metadata": {}, - "source": [ - "$$\n", - "\\mathcal{C}(\\boldsymbol{\\theta}) = - \\ln P(\\mathcal{D} \\mid \\boldsymbol{\\theta}) = - \\sum_{i=1}^n\n", - "y_i \\ln[P(y_i = 0)] + (1 - y_i) \\ln [1 - P(y_i = 0)] = \\sum_{i=1}^n \\mathcal{L}_i(\\boldsymbol{\\theta}) .\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "60d3b57c", - "metadata": {}, - "source": [ - "This last equality means that we can interpret our *cost* function as a sum over the *loss* function\n", - "for each point in the dataset $\\mathcal{L}_i(\\boldsymbol{\\theta})$. \n", - "The negative sign is just so that we can think about our algorithm as minimizing a positive number, rather\n", - "than maximizing a negative number. \n", - "\n", - "In *multiclass* classification it is common to treat each integer label as a so called *one-hot* vector: \n", - "\n", - "$y = 5 \\quad \\rightarrow \\quad \\boldsymbol{y} = (0, 0, 0, 0, 0, 1, 0, 0, 0, 0) ,$ and\n", - "\n", - "$y = 1 \\quad \\rightarrow \\quad \\boldsymbol{y} = (0, 1, 0, 0, 0, 0, 0, 0, 0, 0) ,$ \n", - "\n", - "i.e. a binary bit string of length $C$, where $C = 10$ is the number of classes in the MNIST dataset (numbers from $0$ to $9$).. \n", - "\n", - "If $\\boldsymbol{x}_i$ is the $i$-th input (image), $y_{ic}$ refers to the $c$-th component of the $i$-th\n", - "output vector $\\boldsymbol{y}_i$. \n", - "The probability of $\\boldsymbol{x}_i$ being in class $c$ will be given by the softmax function:" - ] - }, - { - "cell_type": "markdown", - "id": "9045875f", - "metadata": {}, - "source": [ - "$$\n", - "P(y_{ic} = 1 \\mid \\boldsymbol{x}_i, \\boldsymbol{\\theta}) = \\frac{\\exp{((\\boldsymbol{a}_i^{hidden})^T \\boldsymbol{w}_c)}}\n", - "{\\sum_{c'=0}^{C-1} \\exp{((\\boldsymbol{a}_i^{hidden})^T \\boldsymbol{w}_{c'})}} ,\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "1d37a3a2", - "metadata": {}, - "source": [ - "which reduces to the logistic function in the binary case. \n", - "The likelihood of this $C$-class classifier\n", - "is now given as:" - ] - }, - { - "cell_type": "markdown", - "id": "429c3549", - "metadata": {}, - "source": [ - "$$\n", - "P(\\mathcal{D} \\mid \\boldsymbol{\\theta}) = \\prod_{i=1}^n \\prod_{c=0}^{C-1} [P(y_{ic} = 1)]^{y_{ic}} .\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "cde118d9", - "metadata": {}, - "source": [ - "Again we take the negative log-likelihood to define our cost function:" - ] - }, - { - "cell_type": "markdown", - "id": "16740280", - "metadata": {}, - "source": [ - "$$\n", - "\\mathcal{C}(\\boldsymbol{\\theta}) = - \\log{P(\\mathcal{D} \\mid \\boldsymbol{\\theta})}.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "a4b60c6f", - "metadata": {}, - "source": [ - "See the logistic regression lectures for a full definition of the cost function.\n", - "\n", - "The back propagation equations need now only a small change, namely the definition of a new cost function. We are thus ready to use the same equations as before!" - ] - }, - { - "cell_type": "markdown", - "id": "36cce044", - "metadata": {}, - "source": [ - "## Example: binary classification problem\n", - "\n", - "As an example of the above, relevant for project 2 as well, let us consider a binary class. As discussed in our logistic regression lectures, we defined a cost function in terms of the parameters $\\beta$ as" - ] - }, - { - "cell_type": "markdown", - "id": "d2cc5185", - "metadata": {}, - "source": [ - "$$\n", - "\\mathcal{C}(\\boldsymbol{\\beta}) = - \\sum_{i=1}^n \\left(y_i\\log{p(y_i \\vert x_i,\\boldsymbol{\\beta})}+(1-y_i)\\log{1-p(y_i \\vert x_i,\\boldsymbol{\\beta})}\\right),\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "6f62ac34", - "metadata": {}, - "source": [ - "where we had defined the logistic (sigmoid) function" - ] - }, - { - "cell_type": "markdown", - "id": "980d2595", - "metadata": {}, - "source": [ - "$$\n", - "p(y_i =1\\vert x_i,\\boldsymbol{\\beta})=\\frac{\\exp{(\\beta_0+\\beta_1 x_i)}}{1+\\exp{(\\beta_0+\\beta_1 x_i)}},\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "07f96bba", - "metadata": {}, - "source": [ - "and" - ] - }, - { - "cell_type": "markdown", - "id": "ab7ef463", - "metadata": {}, - "source": [ - "$$\n", - "p(y_i =0\\vert x_i,\\boldsymbol{\\beta})=1-p(y_i =1\\vert x_i,\\boldsymbol{\\beta}).\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "712f14c5", - "metadata": {}, - "source": [ - "The parameters $\\boldsymbol{\\beta}$ were defined using a minimization method like gradient descent or Newton-Raphson's method. \n", - "\n", - "Now we replace $x_i$ with the activation $z_i^l$ for a given layer $l$ and the outputs as $y_i=a_i^l=f(z_i^l)$, with $z_i^l$ now being a function of the weights $w_{ij}^l$ and biases $b_i^l$. \n", - "We have then" - ] - }, - { - "cell_type": "markdown", - "id": "efb3f21c", - "metadata": {}, - "source": [ - "$$\n", - "a_i^l = y_i = \\frac{\\exp{(z_i^l)}}{1+\\exp{(z_i^l)}},\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "661dd5e4", - "metadata": {}, - "source": [ - "with" - ] - }, - { - "cell_type": "markdown", - "id": "545879f3", - "metadata": {}, - "source": [ - "$$\n", - "z_i^l = \\sum_{j}w_{ij}^l a_j^{l-1}+b_i^l,\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "20187a39", - "metadata": {}, - "source": [ - "where the superscript $l-1$ indicates that these are the outputs from layer $l-1$.\n", - "Our cost function at the final layer $l=L$ is now" - ] - }, - { - "cell_type": "markdown", - "id": "ecd3c551", - "metadata": {}, - "source": [ - "$$\n", - "\\mathcal{C}(\\boldsymbol{W}) = - \\sum_{i=1}^n \\left(t_i\\log{a_i^L}+(1-t_i)\\log{(1-a_i^L)}\\right),\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "03d1bd2b", - "metadata": {}, - "source": [ - "where we have defined the targets $t_i$. The derivatives of the cost function with respect to the output $a_i^L$ are then easily calculated and we get" - ] - }, - { - "cell_type": "markdown", - "id": "1baaf3b0", - "metadata": {}, - "source": [ - "$$\n", - "\\frac{\\partial \\mathcal{C}(\\boldsymbol{W})}{\\partial a_i^L} = \\frac{a_i^L-t_i}{a_i^L(1-a_i^L)}.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "9114b454", - "metadata": {}, - "source": [ - "In case we use another activation function than the logistic one, we need to evaluate other derivatives." - ] - }, - { - "cell_type": "markdown", - "id": "19b41dd4", - "metadata": {}, - "source": [ - "## The Softmax function\n", - "In case we employ the more general case given by the Softmax equation, we need to evaluate the derivative of the activation function with respect to the activation $z_i^l$, that is we need" - ] - }, - { - "cell_type": "markdown", - "id": "bc1b97c5", - "metadata": {}, - "source": [ - "$$\n", - "\\frac{\\partial f(z_i^l)}{\\partial w_{jk}^l} =\n", - "\\frac{\\partial f(z_i^l)}{\\partial z_j^l} \\frac{\\partial z_j^l}{\\partial w_{jk}^l}= \\frac{\\partial f(z_i^l)}{\\partial z_j^l}a_k^{l-1}.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "52f2e768", - "metadata": {}, - "source": [ - "For the Softmax function we have" - ] - }, - { - "cell_type": "markdown", - "id": "1a60c363", - "metadata": {}, - "source": [ - "$$\n", - "f(z_i^l) = \\frac{\\exp{(z_i^l)}}{\\sum_{m=1}^K\\exp{(z_m^l)}}.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "93eb34b6", - "metadata": {}, - "source": [ - "Its derivative with respect to $z_j^l$ gives" - ] - }, - { - "cell_type": "markdown", - "id": "aa26229f", - "metadata": {}, - "source": [ - "$$\n", - "\\frac{\\partial f(z_i^l)}{\\partial z_j^l}= f(z_i^l)\\left(\\delta_{ij}-f(z_j^l)\\right),\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "1f075e8c", - "metadata": {}, - "source": [ - "which in case of the simply binary model reduces to having $i=j$." - ] - }, - { - "cell_type": "markdown", - "id": "b0cb8b0e", - "metadata": {}, - "source": [ - "## Developing a code for doing neural networks with back propagation\n", - "\n", - "One can identify a set of key steps when using neural networks to solve supervised learning problems: \n", - "\n", - "1. Collect and pre-process data \n", - "\n", - "2. Define model and architecture \n", - "\n", - "3. Choose cost function and optimizer \n", - "\n", - "4. Train the model \n", - "\n", - "5. Evaluate model performance on test data \n", - "\n", - "6. Adjust hyperparameters (if necessary, network architecture)" - ] - }, - { - "cell_type": "markdown", - "id": "c4cd71b6", - "metadata": {}, - "source": [ - "## Collect and pre-process data\n", - "\n", - "Here we will be using the MNIST dataset, which is readily available through the **scikit-learn**\n", - "package. You may also find it for example [here](http://yann.lecun.com/exdb/mnist/). \n", - "The *MNIST* (Modified National Institute of Standards and Technology) database is a large database\n", - "of handwritten digits that is commonly used for training various image processing systems. \n", - "The MNIST dataset consists of 70 000 images of size $28\\times 28$ pixels, each labeled from 0 to 9. \n", - "The scikit-learn dataset we will use consists of a selection of 1797 images of size $8\\times 8$ collected and processed from this database. \n", - "\n", - "To feed data into a feed-forward neural network we need to represent\n", - "the inputs as a design/feature matrix $X = (n_{inputs}, n_{features})$. Each\n", - "row represents an *input*, in this case a handwritten digit, and\n", - "each column represents a *feature*, in this case a pixel. The\n", - "correct answers, also known as *labels* or *targets* are\n", - "represented as a 1D array of integers \n", - "$Y = (n_{inputs}) = (5, 3, 1, 8,...)$.\n", - "\n", - "As an example, say we want to build a neural network using supervised learning to predict Body-Mass Index (BMI) from\n", - "measurements of height (in m) \n", - "and weight (in kg). If we have measurements of 5 people the design/feature matrix could be for example: \n", - "\n", - "$$ X = \\begin{bmatrix}\n", - "1.85 & 81\\\\\n", - "1.71 & 65\\\\\n", - "1.95 & 103\\\\\n", - "1.55 & 42\\\\\n", - "1.63 & 56\n", - "\\end{bmatrix} ,$$ \n", - "\n", - "and the targets would be: \n", - "\n", - "$$ Y = (23.7, 22.2, 27.1, 17.5, 21.1) $$ \n", - "\n", - "Since each input image is a 2D matrix, we need to flatten the image\n", - "(i.e. \"unravel\" the 2D matrix into a 1D array) to turn the data into a\n", - "design/feature matrix. This means we lose all spatial information in the\n", - "image, such as locality and translational invariance. More complicated\n", - "architectures such as Convolutional Neural Networks can take advantage\n", - "of such information, and are most commonly applied when analyzing\n", - "images." - ] - }, - { - "cell_type": "code", - "execution_count": 1, - "id": "ca43227b", - "metadata": {}, - "outputs": [], - "source": [ - "%matplotlib inline\n", - "\n", - "# import necessary packages\n", - "import numpy as np\n", - "import matplotlib.pyplot as plt\n", - "from sklearn import datasets\n", - "\n", - "\n", - "# ensure the same random numbers appear every time\n", - "np.random.seed(0)\n", - "\n", - "# display images in notebook\n", - "%matplotlib inline\n", - "plt.rcParams['figure.figsize'] = (12,12)\n", - "\n", - "\n", - "# download MNIST dataset\n", - "digits = datasets.load_digits()\n", - "\n", - "# define inputs and labels\n", - "inputs = digits.images\n", - "labels = digits.target\n", - "\n", - "print(\"inputs = (n_inputs, pixel_width, pixel_height) = \" + str(inputs.shape))\n", - "print(\"labels = (n_inputs) = \" + str(labels.shape))\n", - "\n", - "\n", - "# flatten the image\n", - "# the value -1 means dimension is inferred from the remaining dimensions: 8x8 = 64\n", - "n_inputs = len(inputs)\n", - "inputs = inputs.reshape(n_inputs, -1)\n", - "print(\"X = (n_inputs, n_features) = \" + str(inputs.shape))\n", - "\n", - "\n", - "# choose some random images to display\n", - "indices = np.arange(n_inputs)\n", - "random_indices = np.random.choice(indices, size=5)\n", - "\n", - "for i, image in enumerate(digits.images[random_indices]):\n", - " plt.subplot(1, 5, i+1)\n", - " plt.axis('off')\n", - " plt.imshow(image, cmap=plt.cm.gray_r, interpolation='nearest')\n", - " plt.title(\"Label: %d\" % digits.target[random_indices[i]])\n", - "plt.show()" - ] - }, - { - "cell_type": "markdown", - "id": "79f4798f", - "metadata": {}, - "source": [ - "## Train and test datasets\n", - "\n", - "Performing analysis before partitioning the dataset is a major error, that can lead to incorrect conclusions. \n", - "\n", - "We will reserve $80 \\%$ of our dataset for training and $20 \\%$ for testing. \n", - "\n", - "It is important that the train and test datasets are drawn randomly from our dataset, to ensure\n", - "no bias in the sampling. \n", - "Say you are taking measurements of weather data to predict the weather in the coming 5 days.\n", - "You don't want to train your model on measurements taken from the hours 00.00 to 12.00, and then test it on data\n", - "collected from 12.00 to 24.00." - ] - }, - { - "cell_type": "code", - "execution_count": 2, - "id": "38e01634", - "metadata": {}, - "outputs": [], - "source": [ - "from sklearn.model_selection import train_test_split\n", - "\n", - "# one-liner from scikit-learn library\n", - "train_size = 0.8\n", - "test_size = 1 - train_size\n", - "X_train, X_test, Y_train, Y_test = train_test_split(inputs, labels, train_size=train_size,\n", - " test_size=test_size)\n", - "\n", - "# equivalently in numpy\n", - "def train_test_split_numpy(inputs, labels, train_size, test_size):\n", - " n_inputs = len(inputs)\n", - " inputs_shuffled = inputs.copy()\n", - " labels_shuffled = labels.copy()\n", - " \n", - " np.random.shuffle(inputs_shuffled)\n", - " np.random.shuffle(labels_shuffled)\n", - " \n", - " train_end = int(n_inputs*train_size)\n", - " X_train, X_test = inputs_shuffled[:train_end], inputs_shuffled[train_end:]\n", - " Y_train, Y_test = labels_shuffled[:train_end], labels_shuffled[train_end:]\n", - " \n", - " return X_train, X_test, Y_train, Y_test\n", - "\n", - "#X_train, X_test, Y_train, Y_test = train_test_split_numpy(inputs, labels, train_size, test_size)\n", - "\n", - "print(\"Number of training images: \" + str(len(X_train)))\n", - "print(\"Number of test images: \" + str(len(X_test)))" - ] - }, - { - "cell_type": "markdown", - "id": "faca5ec2", - "metadata": {}, - "source": [ - "## Define model and architecture\n", - "\n", - "Our simple feed-forward neural network will consist of an *input* layer, a single *hidden* layer and an *output* layer. The activation $y$ of each neuron is a weighted sum of inputs, passed through an activation function. In case of the simple perceptron model we have \n", - "\n", - "$$ z = \\sum_{i=1}^n w_i a_i ,$$\n", - "\n", - "$$ y = f(z) ,$$\n", - "\n", - "where $f$ is the activation function, $a_i$ represents input from neuron $i$ in the preceding layer\n", - "and $w_i$ is the weight to input $i$. \n", - "The activation of the neurons in the input layer is just the features (e.g. a pixel value). \n", - "\n", - "The simplest activation function for a neuron is the *Heaviside* function:\n", - "\n", - "$$ f(z) = \n", - "\\begin{cases}\n", - "1, & z > 0\\\\\n", - "0, & \\text{otherwise}\n", - "\\end{cases}\n", - "$$\n", - "\n", - "A feed-forward neural network with this activation is known as a *perceptron*. \n", - "For a binary classifier (i.e. two classes, 0 or 1, dog or not-dog) we can also use this in our output layer. \n", - "This activation can be generalized to $k$ classes (using e.g. the *one-against-all* strategy), \n", - "and we call these architectures *multiclass perceptrons*. \n", - "\n", - "However, it is now common to use the terms Single Layer Perceptron (SLP) (1 hidden layer) and \n", - "Multilayer Perceptron (MLP) (2 or more hidden layers) to refer to feed-forward neural networks with any activation function. \n", - "\n", - "Typical choices for activation functions include the sigmoid function, hyperbolic tangent, and Rectified Linear Unit (ReLU). \n", - "We will be using the sigmoid function $\\sigma(x)$: \n", - "\n", - "$$ f(x) = \\sigma(x) = \\frac{1}{1 + e^{-x}} ,$$\n", - "\n", - "which is inspired by probability theory (see logistic regression) and was most commonly used until about 2011. See the discussion below concerning other activation functions." - ] - }, - { - "cell_type": "markdown", - "id": "e720f042", - "metadata": {}, - "source": [ - "## Layers\n", - "\n", - "* Input \n", - "\n", - "Since each input image has 8x8 = 64 pixels or features, we have an input layer of 64 neurons. \n", - "\n", - "* Hidden layer\n", - "\n", - "We will use 50 neurons in the hidden layer receiving input from the neurons in the input layer. \n", - "Since each neuron in the hidden layer is connected to the 64 inputs we have 64x50 = 3200 weights to the hidden layer. \n", - "\n", - "* Output\n", - "\n", - "If we were building a binary classifier, it would be sufficient with a single neuron in the output layer,\n", - "which could output 0 or 1 according to the Heaviside function. This would be an example of a *hard* classifier, meaning it outputs the class of the input directly. However, if we are dealing with noisy data it is often beneficial to use a *soft* classifier, which outputs the probability of being in class 0 or 1. \n", - "\n", - "For a soft binary classifier, we could use a single neuron and interpret the output as either being the probability of being in class 0 or the probability of being in class 1. Alternatively we could use 2 neurons, and interpret each neuron as the probability of being in each class. \n", - "\n", - "Since we are doing multiclass classification, with 10 categories, it is natural to use 10 neurons in the output layer. We number the neurons $j = 0,1,...,9$. The activation of each output neuron $j$ will be according to the *softmax* function: \n", - "\n", - "$$ P(\\text{class $j$} \\mid \\text{input $\\boldsymbol{a}$}) = \\frac{\\exp{(\\boldsymbol{a}^T \\boldsymbol{w}_j)}}\n", - "{\\sum_{c=0}^{9} \\exp{(\\boldsymbol{a}^T \\boldsymbol{w}_c)}} ,$$ \n", - "\n", - "i.e. each neuron $j$ outputs the probability of being in class $j$ given an input from the hidden layer $\\boldsymbol{a}$, with $\\boldsymbol{w}_j$ the weights of neuron $j$ to the inputs. \n", - "The denominator is a normalization factor to ensure the outputs (probabilities) sum up to 1. \n", - "The exponent is just the weighted sum of inputs as before: \n", - "\n", - "$$ z_j = \\sum_{i=1}^n w_ {ij} a_i+b_j.$$ \n", - "\n", - "Since each neuron in the output layer is connected to the 50 inputs from the hidden layer we have 50x10 = 500\n", - "weights to the output layer." - ] - }, - { - "cell_type": "markdown", - "id": "b4a3815d", - "metadata": {}, - "source": [ - "## Weights and biases\n", - "\n", - "Typically weights are initialized with small values distributed around zero, drawn from a uniform\n", - "or normal distribution. Setting all weights to zero means all neurons give the same output, making the network useless. \n", - "\n", - "Adding a bias value to the weighted sum of inputs allows the neural network to represent a greater range\n", - "of values. Without it, any input with the value 0 will be mapped to zero (before being passed through the activation). The bias unit has an output of 1, and a weight to each neuron $j$, $b_j$: \n", - "\n", - "$$ z_j = \\sum_{i=1}^n w_ {ij} a_i + b_j.$$ \n", - "\n", - "The bias weights $\\boldsymbol{b}$ are often initialized to zero, but a small value like $0.01$ ensures all neurons have some output which can be backpropagated in the first training cycle." - ] - }, - { - "cell_type": "code", - "execution_count": 3, - "id": "5c7ae6ce", - "metadata": {}, - "outputs": [], - "source": [ - "# building our neural network\n", - "\n", - "n_inputs, n_features = X_train.shape\n", - "n_hidden_neurons = 50\n", - "n_categories = 10\n", - "\n", - "# we make the weights normally distributed using numpy.random.randn\n", - "\n", - "# weights and bias in the hidden layer\n", - "hidden_weights = np.random.randn(n_features, n_hidden_neurons)\n", - "hidden_bias = np.zeros(n_hidden_neurons) + 0.01\n", - "\n", - "# weights and bias in the output layer\n", - "output_weights = np.random.randn(n_hidden_neurons, n_categories)\n", - "output_bias = np.zeros(n_categories) + 0.01" - ] - }, - { - "cell_type": "markdown", - "id": "bc289dbd", - "metadata": {}, - "source": [ - "## Feed-forward pass\n", - "\n", - "Denote $F$ the number of features, $H$ the number of hidden neurons and $C$ the number of categories. \n", - "For each input image we calculate a weighted sum of input features (pixel values) to each neuron $j$ in the hidden layer $l$: \n", - "\n", - "$$ z_{j}^{l} = \\sum_{i=1}^{F} w_{ij}^{l} x_i + b_{j}^{l},$$\n", - "\n", - "this is then passed through our activation function \n", - "\n", - "$$ a_{j}^{l} = f(z_{j}^{l}) .$$ \n", - "\n", - "We calculate a weighted sum of inputs (activations in the hidden layer) to each neuron $j$ in the output layer: \n", - "\n", - "$$ z_{j}^{L} = \\sum_{i=1}^{H} w_{ij}^{L} a_{i}^{l} + b_{j}^{L}.$$ \n", - "\n", - "Finally we calculate the output of neuron $j$ in the output layer using the softmax function: \n", - "\n", - "$$ a_{j}^{L} = \\frac{\\exp{(z_j^{L})}}\n", - "{\\sum_{c=0}^{C-1} \\exp{(z_c^{L})}} .$$" - ] - }, - { - "cell_type": "markdown", - "id": "3e93f012", - "metadata": {}, - "source": [ - "## Matrix multiplications\n", - "\n", - "Since our data has the dimensions $X = (n_{inputs}, n_{features})$ and our weights to the hidden\n", - "layer have the dimensions \n", - "$W_{hidden} = (n_{features}, n_{hidden})$,\n", - "we can easily feed the network all our training data in one go by taking the matrix product \n", - "\n", - "$$ X W^{h} = (n_{inputs}, n_{hidden}),$$ \n", - "\n", - "and obtain a matrix that holds the weighted sum of inputs to the hidden layer\n", - "for each input image and each hidden neuron. \n", - "We also add the bias to obtain a matrix of weighted sums to the hidden layer $Z^{h}$: \n", - "\n", - "$$ \\boldsymbol{z}^{l} = \\boldsymbol{X} \\boldsymbol{W}^{l} + \\boldsymbol{b}^{l} ,$$\n", - "\n", - "meaning the same bias (1D array with size equal number of hidden neurons) is added to each input image. \n", - "This is then passed through the activation: \n", - "\n", - "$$ \\boldsymbol{a}^{l} = f(\\boldsymbol{z}^l) .$$ \n", - "\n", - "This is fed to the output layer: \n", - "\n", - "$$ \\boldsymbol{z}^{L} = \\boldsymbol{a}^{L} \\boldsymbol{W}^{L} + \\boldsymbol{b}^{L} .$$\n", - "\n", - "Finally we receive our output values for each image and each category by passing it through the softmax function: \n", - "\n", - "$$ output = softmax (\\boldsymbol{z}^{L}) = (n_{inputs}, n_{categories}) .$$" - ] - }, - { - "cell_type": "code", - "execution_count": 4, - "id": "31084597", - "metadata": {}, - "outputs": [], - "source": [ - "# setup the feed-forward pass, subscript h = hidden layer\n", - "\n", - "def sigmoid(x):\n", - " return 1/(1 + np.exp(-x))\n", - "\n", - "def feed_forward(X):\n", - " # weighted sum of inputs to the hidden layer\n", - " z_h = np.matmul(X, hidden_weights) + hidden_bias\n", - " # activation in the hidden layer\n", - " a_h = sigmoid(z_h)\n", - " \n", - " # weighted sum of inputs to the output layer\n", - " z_o = np.matmul(a_h, output_weights) + output_bias\n", - " # softmax output\n", - " # axis 0 holds each input and axis 1 the probabilities of each category\n", - " exp_term = np.exp(z_o)\n", - " probabilities = exp_term / np.sum(exp_term, axis=1, keepdims=True)\n", - " \n", - " return probabilities\n", - "\n", - "probabilities = feed_forward(X_train)\n", - "print(\"probabilities = (n_inputs, n_categories) = \" + str(probabilities.shape))\n", - "print(\"probability that image 0 is in category 0,1,2,...,9 = \\n\" + str(probabilities[0]))\n", - "print(\"probabilities sum up to: \" + str(probabilities[0].sum()))\n", - "print()\n", - "\n", - "# we obtain a prediction by taking the class with the highest likelihood\n", - "def predict(X):\n", - " probabilities = feed_forward(X)\n", - " return np.argmax(probabilities, axis=1)\n", - "\n", - "predictions = predict(X_train)\n", - "print(\"predictions = (n_inputs) = \" + str(predictions.shape))\n", - "print(\"prediction for image 0: \" + str(predictions[0]))\n", - "print(\"correct label for image 0: \" + str(Y_train[0]))" - ] - }, - { - "cell_type": "markdown", - "id": "93ca9a82", - "metadata": {}, - "source": [ - "## Choose cost function and optimizer\n", - "\n", - "To measure how well our neural network is doing we need to introduce a cost function. \n", - "We will call the function that gives the error of a single sample output the *loss* function, and the function\n", - "that gives the total error of our network across all samples the *cost* function.\n", - "A typical choice for multiclass classification is the *cross-entropy* loss, also known as the negative log likelihood. \n", - "\n", - "In *multiclass* classification it is common to treat each integer label as a so called *one-hot* vector: \n", - "\n", - "$$ y = 5 \\quad \\rightarrow \\quad \\boldsymbol{y} = (0, 0, 0, 0, 0, 1, 0, 0, 0, 0) ,$$ \n", - "\n", - "$$ y = 1 \\quad \\rightarrow \\quad \\boldsymbol{y} = (0, 1, 0, 0, 0, 0, 0, 0, 0, 0) ,$$ \n", - "\n", - "i.e. a binary bit string of length $C$, where $C = 10$ is the number of classes in the MNIST dataset. \n", - "\n", - "Let $y_{ic}$ denote the $c$-th component of the $i$-th one-hot vector. \n", - "We define the cost function $\\mathcal{C}$ as a sum over the cross-entropy loss for each point $\\boldsymbol{x}_i$ in the dataset.\n", - "\n", - "In the one-hot representation only one of the terms in the loss function is non-zero, namely the\n", - "probability of the correct category $c'$ \n", - "(i.e. the category $c'$ such that $y_{ic'} = 1$). This means that the cross entropy loss only punishes you for how wrong\n", - "you got the correct label. The probability of category $c$ is given by the softmax function. The vector $\\boldsymbol{\\theta}$ represents the parameters of our network, i.e. all the weights and biases." - ] - }, - { - "cell_type": "markdown", - "id": "59ad4e01", - "metadata": {}, - "source": [ - "## Optimizing the cost function\n", - "\n", - "The network is trained by finding the weights and biases that minimize the cost function. One of the most widely used classes of methods is *gradient descent* and its generalizations. The idea behind gradient descent\n", - "is simply to adjust the weights in the direction where the gradient of the cost function is large and negative. This ensures we flow toward a *local* minimum of the cost function. \n", - "Each parameter $\\theta$ is iteratively adjusted according to the rule \n", - "\n", - "$$ \\theta_{i+1} = \\theta_i - \\eta \\nabla \\mathcal{C}(\\theta_i) ,$$\n", - "\n", - "where $\\eta$ is known as the *learning rate*, which controls how big a step we take towards the minimum. \n", - "This update can be repeated for any number of iterations, or until we are satisfied with the result. \n", - "\n", - "A simple and effective improvement is a variant called *Batch Gradient Descent*. \n", - "Instead of calculating the gradient on the whole dataset, we calculate an approximation of the gradient\n", - "on a subset of the data called a *minibatch*. \n", - "If there are $N$ data points and we have a minibatch size of $M$, the total number of batches\n", - "is $N/M$. \n", - "We denote each minibatch $B_k$, with $k = 1, 2,...,N/M$. The gradient then becomes: \n", - "\n", - "$$ \\nabla \\mathcal{C}(\\theta) = \\frac{1}{N} \\sum_{i=1}^N \\nabla \\mathcal{L}_i(\\theta) \\quad \\rightarrow \\quad\n", - "\\frac{1}{M} \\sum_{i \\in B_k} \\nabla \\mathcal{L}_i(\\theta) ,$$\n", - "\n", - "i.e. instead of averaging the loss over the entire dataset, we average over a minibatch. \n", - "\n", - "This has two important benefits: \n", - "1. Introducing stochasticity decreases the chance that the algorithm becomes stuck in a local minima. \n", - "\n", - "2. It significantly speeds up the calculation, since we do not have to use the entire dataset to calculate the gradient. \n", - "\n", - "The various optmization methods, with codes and algorithms, are discussed in our lectures on [Gradient descent approaches](https://compphysics.github.io/MachineLearning/doc/pub/Splines/html/Splines-bs.html)." - ] - }, - { - "cell_type": "markdown", - "id": "d017d149", - "metadata": {}, - "source": [ - "## Regularization\n", - "\n", - "It is common to add an extra term to the cost function, proportional\n", - "to the size of the weights. This is equivalent to constraining the\n", - "size of the weights, so that they do not grow out of control.\n", - "Constraining the size of the weights means that the weights cannot\n", - "grow arbitrarily large to fit the training data, and in this way\n", - "reduces *overfitting*.\n", - "\n", - "We will measure the size of the weights using the so called *L2-norm*, meaning our cost function becomes: \n", - "\n", - "$$ \\mathcal{C}(\\theta) = \\frac{1}{N} \\sum_{i=1}^N \\mathcal{L}_i(\\theta) \\quad \\rightarrow \\quad\n", - "\\frac{1}{N} \\sum_{i=1}^N \\mathcal{L}_i(\\theta) + \\lambda \\lvert \\lvert \\boldsymbol{w} \\rvert \\rvert_2^2 \n", - "= \\frac{1}{N} \\sum_{i=1}^N \\mathcal{L}(\\theta) + \\lambda \\sum_{ij} w_{ij}^2,$$ \n", - "\n", - "i.e. we sum up all the weights squared. The factor $\\lambda$ is known as a regularization parameter.\n", - "\n", - "In order to train the model, we need to calculate the derivative of\n", - "the cost function with respect to every bias and weight in the\n", - "network. In total our network has $(64 + 1)\\times 50=3250$ weights in\n", - "the hidden layer and $(50 + 1)\\times 10=510$ weights to the output\n", - "layer ($+1$ for the bias), and the gradient must be calculated for\n", - "every parameter. We use the *backpropagation* algorithm discussed\n", - "above. This is a clever use of the chain rule that allows us to\n", - "calculate the gradient efficently." - ] - }, - { - "cell_type": "markdown", - "id": "3b624b6e", - "metadata": {}, - "source": [ - "## Matrix multiplication\n", - "\n", - "To more efficently train our network these equations are implemented using matrix operations. \n", - "The error in the output layer is calculated simply as, with $\\boldsymbol{t}$ being our targets, \n", - "\n", - "$$ \\delta_L = \\boldsymbol{t} - \\boldsymbol{y} = (n_{inputs}, n_{categories}) .$$ \n", - "\n", - "The gradient for the output weights is calculated as \n", - "\n", - "$$ \\nabla W_{L} = \\boldsymbol{a}^T \\delta_L = (n_{hidden}, n_{categories}) ,$$\n", - "\n", - "where $\\boldsymbol{a} = (n_{inputs}, n_{hidden})$. This simply means that we are summing up the gradients for each input. \n", - "Since we are going backwards we have to transpose the activation matrix. \n", - "\n", - "The gradient with respect to the output bias is then \n", - "\n", - "$$ \\nabla \\boldsymbol{b}_{L} = \\sum_{i=1}^{n_{inputs}} \\delta_L = (n_{categories}) .$$ \n", - "\n", - "The error in the hidden layer is \n", - "\n", - "$$ \\Delta_h = \\delta_L W_{L}^T \\circ f'(z_{h}) = \\delta_L W_{L}^T \\circ a_{h} \\circ (1 - a_{h}) = (n_{inputs}, n_{hidden}) ,$$ \n", - "\n", - "where $f'(a_{h})$ is the derivative of the activation in the hidden layer. The matrix products mean\n", - "that we are summing up the products for each neuron in the output layer. The symbol $\\circ$ denotes\n", - "the *Hadamard product*, meaning element-wise multiplication. \n", - "\n", - "This again gives us the gradients in the hidden layer: \n", - "\n", - "$$ \\nabla W_{h} = X^T \\delta_h = (n_{features}, n_{hidden}) ,$$ \n", - "\n", - "$$ \\nabla b_{h} = \\sum_{i=1}^{n_{inputs}} \\delta_h = (n_{hidden}) .$$" - ] - }, - { - "cell_type": "code", - "execution_count": 5, - "id": "39eabb7a", - "metadata": {}, - "outputs": [], - "source": [ - "# to categorical turns our integer vector into a onehot representation\n", - "from sklearn.metrics import accuracy_score\n", - "\n", - "# one-hot in numpy\n", - "def to_categorical_numpy(integer_vector):\n", - " n_inputs = len(integer_vector)\n", - " n_categories = np.max(integer_vector) + 1\n", - " onehot_vector = np.zeros((n_inputs, n_categories))\n", - " onehot_vector[range(n_inputs), integer_vector] = 1\n", - " \n", - " return onehot_vector\n", - "\n", - "#Y_train_onehot, Y_test_onehot = to_categorical(Y_train), to_categorical(Y_test)\n", - "Y_train_onehot, Y_test_onehot = to_categorical_numpy(Y_train), to_categorical_numpy(Y_test)\n", - "\n", - "def feed_forward_train(X):\n", - " # weighted sum of inputs to the hidden layer\n", - " z_h = np.matmul(X, hidden_weights) + hidden_bias\n", - " # activation in the hidden layer\n", - " a_h = sigmoid(z_h)\n", - " \n", - " # weighted sum of inputs to the output layer\n", - " z_o = np.matmul(a_h, output_weights) + output_bias\n", - " # softmax output\n", - " # axis 0 holds each input and axis 1 the probabilities of each category\n", - " exp_term = np.exp(z_o)\n", - " probabilities = exp_term / np.sum(exp_term, axis=1, keepdims=True)\n", - " \n", - " # for backpropagation need activations in hidden and output layers\n", - " return a_h, probabilities\n", - "\n", - "def backpropagation(X, Y):\n", - " a_h, probabilities = feed_forward_train(X)\n", - " \n", - " # error in the output layer\n", - " error_output = probabilities - Y\n", - " # error in the hidden layer\n", - " error_hidden = np.matmul(error_output, output_weights.T) * a_h * (1 - a_h)\n", - " \n", - " # gradients for the output layer\n", - " output_weights_gradient = np.matmul(a_h.T, error_output)\n", - " output_bias_gradient = np.sum(error_output, axis=0)\n", - " \n", - " # gradient for the hidden layer\n", - " hidden_weights_gradient = np.matmul(X.T, error_hidden)\n", - " hidden_bias_gradient = np.sum(error_hidden, axis=0)\n", - "\n", - " return output_weights_gradient, output_bias_gradient, hidden_weights_gradient, hidden_bias_gradient\n", - "\n", - "print(\"Old accuracy on training data: \" + str(accuracy_score(predict(X_train), Y_train)))\n", - "\n", - "eta = 0.01\n", - "lmbd = 0.01\n", - "for i in range(1000):\n", - " # calculate gradients\n", - " dWo, dBo, dWh, dBh = backpropagation(X_train, Y_train_onehot)\n", - " \n", - " # regularization term gradients\n", - " dWo += lmbd * output_weights\n", - " dWh += lmbd * hidden_weights\n", - " \n", - " # update weights and biases\n", - " output_weights -= eta * dWo\n", - " output_bias -= eta * dBo\n", - " hidden_weights -= eta * dWh\n", - " hidden_bias -= eta * dBh\n", - "\n", - "print(\"New accuracy on training data: \" + str(accuracy_score(predict(X_train), Y_train)))" - ] - }, - { - "cell_type": "markdown", - "id": "22c14a38", - "metadata": {}, - "source": [ - "## Improving performance\n", - "\n", - "As we can see the network does not seem to be learning at all. It seems to be just guessing the label for each image. \n", - "In order to obtain a network that does something useful, we will have to do a bit more work. \n", - "\n", - "The choice of *hyperparameters* such as learning rate and regularization parameter is hugely influential for the performance of the network. Typically a *grid-search* is performed, wherein we test different hyperparameters separated by orders of magnitude. For example we could test the learning rates $\\eta = 10^{-6}, 10^{-5},...,10^{-1}$ with different regularization parameters $\\lambda = 10^{-6},...,10^{-0}$. \n", - "\n", - "Next, we haven't implemented minibatching yet, which introduces stochasticity and is though to act as an important regularizer on the weights. We call a feed-forward + backward pass with a minibatch an *iteration*, and a full training period\n", - "going through the entire dataset ($n/M$ batches) an *epoch*.\n", - "\n", - "If this does not improve network performance, you may want to consider altering the network architecture, adding more neurons or hidden layers. \n", - "Andrew Ng goes through some of these considerations in this [video](https://youtu.be/F1ka6a13S9I). You can find a summary of the video [here](https://kevinzakka.github.io/2016/09/26/applying-deep-learning/)." - ] - }, - { - "cell_type": "markdown", - "id": "33d33cf6", - "metadata": {}, - "source": [ - "## Full object-oriented implementation\n", - "\n", - "It is very natural to think of the network as an object, with specific instances of the network\n", - "being realizations of this object with different hyperparameters. An implementation using Python classes provides a clean structure and interface, and the full implementation of our neural network is given below." - ] - }, - { - "cell_type": "code", - "execution_count": 6, - "id": "a5009498", - "metadata": {}, - "outputs": [], - "source": [ - "class NeuralNetwork:\n", - " def __init__(\n", - " self,\n", - " X_data,\n", - " Y_data,\n", - " n_hidden_neurons=50,\n", - " n_categories=10,\n", - " epochs=10,\n", - " batch_size=100,\n", - " eta=0.1,\n", - " lmbd=0.0):\n", - "\n", - " self.X_data_full = X_data\n", - " self.Y_data_full = Y_data\n", - "\n", - " self.n_inputs = X_data.shape[0]\n", - " self.n_features = X_data.shape[1]\n", - " self.n_hidden_neurons = n_hidden_neurons\n", - " self.n_categories = n_categories\n", - "\n", - " self.epochs = epochs\n", - " self.batch_size = batch_size\n", - " self.iterations = self.n_inputs // self.batch_size\n", - " self.eta = eta\n", - " self.lmbd = lmbd\n", - "\n", - " self.create_biases_and_weights()\n", - "\n", - " def create_biases_and_weights(self):\n", - " self.hidden_weights = np.random.randn(self.n_features, self.n_hidden_neurons)\n", - " self.hidden_bias = np.zeros(self.n_hidden_neurons) + 0.01\n", - "\n", - " self.output_weights = np.random.randn(self.n_hidden_neurons, self.n_categories)\n", - " self.output_bias = np.zeros(self.n_categories) + 0.01\n", - "\n", - " def feed_forward(self):\n", - " # feed-forward for training\n", - " self.z_h = np.matmul(self.X_data, self.hidden_weights) + self.hidden_bias\n", - " self.a_h = sigmoid(self.z_h)\n", - "\n", - " self.z_o = np.matmul(self.a_h, self.output_weights) + self.output_bias\n", - "\n", - " exp_term = np.exp(self.z_o)\n", - " self.probabilities = exp_term / np.sum(exp_term, axis=1, keepdims=True)\n", - "\n", - " def feed_forward_out(self, X):\n", - " # feed-forward for output\n", - " z_h = np.matmul(X, self.hidden_weights) + self.hidden_bias\n", - " a_h = sigmoid(z_h)\n", - "\n", - " z_o = np.matmul(a_h, self.output_weights) + self.output_bias\n", - " \n", - " exp_term = np.exp(z_o)\n", - " probabilities = exp_term / np.sum(exp_term, axis=1, keepdims=True)\n", - " return probabilities\n", - "\n", - " def backpropagation(self):\n", - " error_output = self.probabilities - self.Y_data\n", - " error_hidden = np.matmul(error_output, self.output_weights.T) * self.a_h * (1 - self.a_h)\n", - "\n", - " self.output_weights_gradient = np.matmul(self.a_h.T, error_output)\n", - " self.output_bias_gradient = np.sum(error_output, axis=0)\n", - "\n", - " self.hidden_weights_gradient = np.matmul(self.X_data.T, error_hidden)\n", - " self.hidden_bias_gradient = np.sum(error_hidden, axis=0)\n", - "\n", - " if self.lmbd > 0.0:\n", - " self.output_weights_gradient += self.lmbd * self.output_weights\n", - " self.hidden_weights_gradient += self.lmbd * self.hidden_weights\n", - "\n", - " self.output_weights -= self.eta * self.output_weights_gradient\n", - " self.output_bias -= self.eta * self.output_bias_gradient\n", - " self.hidden_weights -= self.eta * self.hidden_weights_gradient\n", - " self.hidden_bias -= self.eta * self.hidden_bias_gradient\n", - "\n", - " def predict(self, X):\n", - " probabilities = self.feed_forward_out(X)\n", - " return np.argmax(probabilities, axis=1)\n", - "\n", - " def predict_probabilities(self, X):\n", - " probabilities = self.feed_forward_out(X)\n", - " return probabilities\n", - "\n", - " def train(self):\n", - " data_indices = np.arange(self.n_inputs)\n", - "\n", - " for i in range(self.epochs):\n", - " for j in range(self.iterations):\n", - " # pick datapoints with replacement\n", - " chosen_datapoints = np.random.choice(\n", - " data_indices, size=self.batch_size, replace=False\n", - " )\n", - "\n", - " # minibatch training data\n", - " self.X_data = self.X_data_full[chosen_datapoints]\n", - " self.Y_data = self.Y_data_full[chosen_datapoints]\n", - "\n", - " self.feed_forward()\n", - " self.backpropagation()" - ] - }, - { - "cell_type": "markdown", - "id": "68639daa", - "metadata": {}, - "source": [ - "## Evaluate model performance on test data\n", - "\n", - "To measure the performance of our network we evaluate how well it does it data it has never seen before, i.e. the test data. \n", - "We measure the performance of the network using the *accuracy* score. \n", - "The accuracy is as you would expect just the number of images correctly labeled divided by the total number of images. A perfect classifier will have an accuracy score of $1$. \n", - "\n", - "$$ \\text{Accuracy} = \\frac{\\sum_{i=1}^n I(\\tilde{y}_i = y_i)}{n} ,$$ \n", - "\n", - "where $I$ is the indicator function, $1$ if $\\tilde{y}_i = y_i$ and $0$ otherwise." - ] - }, - { - "cell_type": "code", - "execution_count": 7, - "id": "487c6612", - "metadata": {}, - "outputs": [], - "source": [ - "epochs = 100\n", - "batch_size = 100\n", - "\n", - "dnn = NeuralNetwork(X_train, Y_train_onehot, eta=eta, lmbd=lmbd, epochs=epochs, batch_size=batch_size,\n", - " n_hidden_neurons=n_hidden_neurons, n_categories=n_categories)\n", - "dnn.train()\n", - "test_predict = dnn.predict(X_test)\n", - "\n", - "# accuracy score from scikit library\n", - "print(\"Accuracy score on test set: \", accuracy_score(Y_test, test_predict))\n", - "\n", - "# equivalent in numpy\n", - "def accuracy_score_numpy(Y_test, Y_pred):\n", - " return np.sum(Y_test == Y_pred) / len(Y_test)\n", - "\n", - "#print(\"Accuracy score on test set: \", accuracy_score_numpy(Y_test, test_predict))" - ] - }, - { - "cell_type": "markdown", - "id": "c3b10024", - "metadata": {}, - "source": [ - "## Adjust hyperparameters\n", - "\n", - "We now perform a grid search to find the optimal hyperparameters for the network. \n", - "Note that we are only using 1 layer with 50 neurons, and human performance is estimated to be around $98\\%$ ($2\\%$ error rate)." - ] - }, - { - "cell_type": "code", - "execution_count": 8, - "id": "7ab55f7a", - "metadata": {}, - "outputs": [], - "source": [ - "eta_vals = np.logspace(-5, 1, 7)\n", - "lmbd_vals = np.logspace(-5, 1, 7)\n", - "# store the models for later use\n", - "DNN_numpy = np.zeros((len(eta_vals), len(lmbd_vals)), dtype=object)\n", - "\n", - "# grid search\n", - "for i, eta in enumerate(eta_vals):\n", - " for j, lmbd in enumerate(lmbd_vals):\n", - " dnn = NeuralNetwork(X_train, Y_train_onehot, eta=eta, lmbd=lmbd, epochs=epochs, batch_size=batch_size,\n", - " n_hidden_neurons=n_hidden_neurons, n_categories=n_categories)\n", - " dnn.train()\n", - " \n", - " DNN_numpy[i][j] = dnn\n", - " \n", - " test_predict = dnn.predict(X_test)\n", - " \n", - " print(\"Learning rate = \", eta)\n", - " print(\"Lambda = \", lmbd)\n", - " print(\"Accuracy score on test set: \", accuracy_score(Y_test, test_predict))\n", - " print()" - ] - }, - { - "cell_type": "markdown", - "id": "aa9d91e2", - "metadata": {}, - "source": [ - "## Visualization" - ] - }, - { - "cell_type": "code", - "execution_count": 9, - "id": "ce6b84ae", - "metadata": {}, - "outputs": [], - "source": [ - "# visual representation of grid search\n", - "# uses seaborn heatmap, you can also do this with matplotlib imshow\n", - "import seaborn as sns\n", - "\n", - "sns.set()\n", - "\n", - "train_accuracy = np.zeros((len(eta_vals), len(lmbd_vals)))\n", - "test_accuracy = np.zeros((len(eta_vals), len(lmbd_vals)))\n", - "\n", - "for i in range(len(eta_vals)):\n", - " for j in range(len(lmbd_vals)):\n", - " dnn = DNN_numpy[i][j]\n", - " \n", - " train_pred = dnn.predict(X_train) \n", - " test_pred = dnn.predict(X_test)\n", - "\n", - " train_accuracy[i][j] = accuracy_score(Y_train, train_pred)\n", - " test_accuracy[i][j] = accuracy_score(Y_test, test_pred)\n", - "\n", - " \n", - "fig, ax = plt.subplots(figsize = (10, 10))\n", - "sns.heatmap(train_accuracy, annot=True, ax=ax, cmap=\"viridis\")\n", - "ax.set_title(\"Training Accuracy\")\n", - "ax.set_ylabel(\"$\\eta$\")\n", - "ax.set_xlabel(\"$\\lambda$\")\n", - "plt.show()\n", - "\n", - "fig, ax = plt.subplots(figsize = (10, 10))\n", - "sns.heatmap(test_accuracy, annot=True, ax=ax, cmap=\"viridis\")\n", - "ax.set_title(\"Test Accuracy\")\n", - "ax.set_ylabel(\"$\\eta$\")\n", - "ax.set_xlabel(\"$\\lambda$\")\n", - "plt.show()" - ] - }, - { - "cell_type": "markdown", - "id": "1d50ccf4", - "metadata": {}, - "source": [ - "## scikit-learn implementation\n", - "\n", - "**scikit-learn** focuses more\n", - "on traditional machine learning methods, such as regression,\n", - "clustering, decision trees, etc. As such, it has only two types of\n", - "neural networks: Multi Layer Perceptron outputting continuous values,\n", - "*MPLRegressor*, and Multi Layer Perceptron outputting labels,\n", - "*MLPClassifier*. We will see how simple it is to use these classes.\n", - "\n", - "**scikit-learn** implements a few improvements from our neural network,\n", - "such as early stopping, a varying learning rate, different\n", - "optimization methods, etc. We would therefore expect a better\n", - "performance overall." - ] - }, - { - "cell_type": "code", - "execution_count": 10, - "id": "05cc9271", - "metadata": {}, - "outputs": [], - "source": [ - "from sklearn.neural_network import MLPClassifier\n", - "# store models for later use\n", - "DNN_scikit = np.zeros((len(eta_vals), len(lmbd_vals)), dtype=object)\n", - "\n", - "for i, eta in enumerate(eta_vals):\n", - " for j, lmbd in enumerate(lmbd_vals):\n", - " dnn = MLPClassifier(hidden_layer_sizes=(n_hidden_neurons), activation='logistic',\n", - " alpha=lmbd, learning_rate_init=eta, max_iter=epochs)\n", - " dnn.fit(X_train, Y_train)\n", - " \n", - " DNN_scikit[i][j] = dnn\n", - " \n", - " print(\"Learning rate = \", eta)\n", - " print(\"Lambda = \", lmbd)\n", - " print(\"Accuracy score on test set: \", dnn.score(X_test, Y_test))\n", - " print()" - ] - }, - { - "cell_type": "markdown", - "id": "9f51a74d", - "metadata": {}, - "source": [ - "## Visualization" - ] - }, - { - "cell_type": "code", - "execution_count": 11, - "id": "38a896b8", - "metadata": {}, - "outputs": [], - "source": [ - "# optional\n", - "# visual representation of grid search\n", - "# uses seaborn heatmap, could probably do this in matplotlib\n", - "import seaborn as sns\n", - "\n", - "sns.set()\n", - "\n", - "train_accuracy = np.zeros((len(eta_vals), len(lmbd_vals)))\n", - "test_accuracy = np.zeros((len(eta_vals), len(lmbd_vals)))\n", - "\n", - "for i in range(len(eta_vals)):\n", - " for j in range(len(lmbd_vals)):\n", - " dnn = DNN_scikit[i][j]\n", - " \n", - " train_pred = dnn.predict(X_train) \n", - " test_pred = dnn.predict(X_test)\n", - "\n", - " train_accuracy[i][j] = accuracy_score(Y_train, train_pred)\n", - " test_accuracy[i][j] = accuracy_score(Y_test, test_pred)\n", - "\n", - " \n", - "fig, ax = plt.subplots(figsize = (10, 10))\n", - "sns.heatmap(train_accuracy, annot=True, ax=ax, cmap=\"viridis\")\n", - "ax.set_title(\"Training Accuracy\")\n", - "ax.set_ylabel(\"$\\eta$\")\n", - "ax.set_xlabel(\"$\\lambda$\")\n", - "plt.show()\n", - "\n", - "fig, ax = plt.subplots(figsize = (10, 10))\n", - "sns.heatmap(test_accuracy, annot=True, ax=ax, cmap=\"viridis\")\n", - "ax.set_title(\"Test Accuracy\")\n", - "ax.set_ylabel(\"$\\eta$\")\n", - "ax.set_xlabel(\"$\\lambda$\")\n", - "plt.show()" - ] - }, - { - "cell_type": "markdown", - "id": "f8ee3eb3", - "metadata": {}, - "source": [ - "## Testing our code for the XOR, OR and AND gates\n", - "\n", - "Last week we discussed three different types of gates, the so-called\n", - "XOR, the OR and the AND gates. Their inputs and outputs can be\n", - "summarized using the following tables, first for the OR gate with\n", - "inputs $x_1$ and $x_2$ and outputs $y$:\n", - "\n", - "\n", - "\n", - "\n", - "\n", - "\n", - "\n", - "\n", - "\n", - "\n", - "\n", - "
$x_1$ $x_2$ $y$
0 0 0
0 1 1
1 0 1
1 1 1
" - ] - }, - { - "cell_type": "markdown", - "id": "5c0e406c", - "metadata": {}, - "source": [ - "## The AND and XOR Gates\n", - "\n", - "The AND gate is defined as\n", - "\n", - "\n", - "\n", - "\n", - "\n", - "\n", - "\n", - "\n", - "\n", - "\n", - "\n", - "
$x_1$ $x_2$ $y$
0 0 0
0 1 0
1 0 0
1 1 1
\n", - "\n", - "And finally we have the XOR gate\n", - "\n", - "\n", - "\n", - "\n", - "\n", - "\n", - "\n", - "\n", - "\n", - "\n", - "\n", - "
$x_1$ $x_2$ $y$
0 0 0
0 1 1
1 0 1
1 1 0
" - ] - }, - { - "cell_type": "markdown", - "id": "f52ee7dd", - "metadata": {}, - "source": [ - "## Representing the Data Sets\n", - "\n", - "Our design matrix is defined by the input values $x_1$ and $x_2$. Since we have four possible outputs, our design matrix reads" - ] - }, - { - "cell_type": "markdown", - "id": "f2634e6f", - "metadata": {}, - "source": [ - "$$\n", - "\\boldsymbol{X}=\\begin{bmatrix} 0 & 0 \\\\\n", - " 0 & 1 \\\\\n", - "\t\t 1 & 0 \\\\\n", - "\t\t 1 & 1 \\end{bmatrix},\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "a39715fe", - "metadata": {}, - "source": [ - "while the vector of outputs is $\\boldsymbol{y}^T=[0,1,1,0]$ for the XOR gate, $\\boldsymbol{y}^T=[0,0,0,1]$ for the AND gate and $\\boldsymbol{y}^T=[0,1,1,1]$ for the OR gate." - ] - }, - { - "cell_type": "markdown", - "id": "8bff01b2", - "metadata": {}, - "source": [ - "## Setting up the Neural Network\n", - "\n", - "We define first our design matrix and the various output vectors for the different gates." - ] - }, - { - "cell_type": "code", - "execution_count": 12, - "id": "9d94da1e", - "metadata": {}, - "outputs": [], - "source": [ - "\"\"\"\n", - "Simple code that tests XOR, OR and AND gates with linear regression\n", - "\"\"\"\n", - "\n", - "# import necessary packages\n", - "import numpy as np\n", - "import matplotlib.pyplot as plt\n", - "from sklearn import datasets\n", - "\n", - "def sigmoid(x):\n", - " return 1/(1 + np.exp(-x))\n", - "\n", - "def feed_forward(X):\n", - " # weighted sum of inputs to the hidden layer\n", - " z_h = np.matmul(X, hidden_weights) + hidden_bias\n", - " # activation in the hidden layer\n", - " a_h = sigmoid(z_h)\n", - " \n", - " # weighted sum of inputs to the output layer\n", - " z_o = np.matmul(a_h, output_weights) + output_bias\n", - " # softmax output\n", - " # axis 0 holds each input and axis 1 the probabilities of each category\n", - " probabilities = sigmoid(z_o)\n", - " return probabilities\n", - "\n", - "# we obtain a prediction by taking the class with the highest likelihood\n", - "def predict(X):\n", - " probabilities = feed_forward(X)\n", - " return np.argmax(probabilities, axis=1)\n", - "\n", - "# ensure the same random numbers appear every time\n", - "np.random.seed(0)\n", - "\n", - "# Design matrix\n", - "X = np.array([ [0, 0], [0, 1], [1, 0],[1, 1]],dtype=np.float64)\n", - "\n", - "# The XOR gate\n", - "yXOR = np.array( [ 0, 1 ,1, 0])\n", - "# The OR gate\n", - "yOR = np.array( [ 0, 1 ,1, 1])\n", - "# The AND gate\n", - "yAND = np.array( [ 0, 0 ,0, 1])\n", - "\n", - "# Defining the neural network\n", - "n_inputs, n_features = X.shape\n", - "n_hidden_neurons = 2\n", - "n_categories = 2\n", - "n_features = 2\n", - "\n", - "# we make the weights normally distributed using numpy.random.randn\n", - "\n", - "# weights and bias in the hidden layer\n", - "hidden_weights = np.random.randn(n_features, n_hidden_neurons)\n", - "hidden_bias = np.zeros(n_hidden_neurons) + 0.01\n", - "\n", - "# weights and bias in the output layer\n", - "output_weights = np.random.randn(n_hidden_neurons, n_categories)\n", - "output_bias = np.zeros(n_categories) + 0.01\n", - "\n", - "probabilities = feed_forward(X)\n", - "print(probabilities)\n", - "\n", - "\n", - "predictions = predict(X)\n", - "print(predictions)" - ] - }, - { - "cell_type": "markdown", - "id": "fdbce6ba", - "metadata": {}, - "source": [ - "Not an impressive result, but this was our first forward pass with randomly assigned weights. Let us now add the full network with the back-propagation algorithm discussed above." - ] - }, - { - "cell_type": "markdown", - "id": "f5cbb06d", - "metadata": {}, - "source": [ - "## The Code using Scikit-Learn" - ] - }, - { - "cell_type": "code", - "execution_count": 13, - "id": "edf69ad3", - "metadata": {}, - "outputs": [], - "source": [ - "# import necessary packages\n", - "import numpy as np\n", - "import matplotlib.pyplot as plt\n", - "from sklearn.neural_network import MLPClassifier\n", - "from sklearn.metrics import accuracy_score\n", - "import seaborn as sns\n", - "\n", - "# ensure the same random numbers appear every time\n", - "np.random.seed(0)\n", - "\n", - "# Design matrix\n", - "X = np.array([ [0, 0], [0, 1], [1, 0],[1, 1]],dtype=np.float64)\n", - "\n", - "# The XOR gate\n", - "yXOR = np.array( [ 0, 1 ,1, 0])\n", - "# The OR gate\n", - "yOR = np.array( [ 0, 1 ,1, 1])\n", - "# The AND gate\n", - "yAND = np.array( [ 0, 0 ,0, 1])\n", - "\n", - "# Defining the neural network\n", - "n_inputs, n_features = X.shape\n", - "n_hidden_neurons = 2\n", - "n_categories = 2\n", - "n_features = 2\n", - "\n", - "eta_vals = np.logspace(-5, 1, 7)\n", - "lmbd_vals = np.logspace(-5, 1, 7)\n", - "# store models for later use\n", - "DNN_scikit = np.zeros((len(eta_vals), len(lmbd_vals)), dtype=object)\n", - "epochs = 100\n", - "\n", - "for i, eta in enumerate(eta_vals):\n", - " for j, lmbd in enumerate(lmbd_vals):\n", - " dnn = MLPClassifier(hidden_layer_sizes=(n_hidden_neurons), activation='logistic',\n", - " alpha=lmbd, learning_rate_init=eta, max_iter=epochs)\n", - " dnn.fit(X, yXOR)\n", - " DNN_scikit[i][j] = dnn\n", - " print(\"Learning rate = \", eta)\n", - " print(\"Lambda = \", lmbd)\n", - " print(\"Accuracy score on data set: \", dnn.score(X, yXOR))\n", - " print()\n", - "\n", - "sns.set()\n", - "test_accuracy = np.zeros((len(eta_vals), len(lmbd_vals)))\n", - "for i in range(len(eta_vals)):\n", - " for j in range(len(lmbd_vals)):\n", - " dnn = DNN_scikit[i][j]\n", - " test_pred = dnn.predict(X)\n", - " test_accuracy[i][j] = accuracy_score(yXOR, test_pred)\n", - "\n", - "fig, ax = plt.subplots(figsize = (10, 10))\n", - "sns.heatmap(test_accuracy, annot=True, ax=ax, cmap=\"viridis\")\n", - "ax.set_title(\"Test Accuracy\")\n", - "ax.set_ylabel(\"$\\eta$\")\n", - "ax.set_xlabel(\"$\\lambda$\")\n", - "plt.show()" - ] - }, - { - "cell_type": "markdown", - "id": "d5e5d8a0", - "metadata": {}, - "source": [ - "## Building neural networks in Tensorflow and Keras\n", - "\n", - "Now we want to build on the experience gained from our neural network implementation in NumPy and scikit-learn\n", - "and use it to construct a neural network in Tensorflow. Once we have constructed a neural network in NumPy\n", - "and Tensorflow, building one in Keras is really quite trivial, though the performance may suffer. \n", - "\n", - "In our previous example we used only one hidden layer, and in this we will use two. From this it should be quite\n", - "clear how to build one using an arbitrary number of hidden layers, using data structures such as Python lists or\n", - "NumPy arrays." - ] - }, - { - "cell_type": "markdown", - "id": "8326a878", - "metadata": {}, - "source": [ - "## Tensorflow\n", - "\n", - "Tensorflow is an open source library machine learning library\n", - "developed by the Google Brain team for internal use. It was released\n", - "under the Apache 2.0 open source license in November 9, 2015.\n", - "\n", - "Tensorflow is a computational framework that allows you to construct\n", - "machine learning models at different levels of abstraction, from\n", - "high-level, object-oriented APIs like Keras, down to the C++ kernels\n", - "that Tensorflow is built upon. The higher levels of abstraction are\n", - "simpler to use, but less flexible, and our choice of implementation\n", - "should reflect the problems we are trying to solve.\n", - "\n", - "[Tensorflow uses](https://www.tensorflow.org/guide/graphs) so-called graphs to represent your computation\n", - "in terms of the dependencies between individual operations, such that you first build a Tensorflow *graph*\n", - "to represent your model, and then create a Tensorflow *session* to run the graph.\n", - "\n", - "In this guide we will analyze the same data as we did in our NumPy and\n", - "scikit-learn tutorial, gathered from the MNIST database of images. We\n", - "will give an introduction to the lower level Python Application\n", - "Program Interfaces (APIs), and see how we use them to build our graph.\n", - "Then we will build (effectively) the same graph in Keras, to see just\n", - "how simple solving a machine learning problem can be.\n", - "\n", - "To install tensorflow on Unix/Linux systems, use pip as" - ] - }, - { - "cell_type": "code", - "execution_count": 14, - "id": "dd988cfc", - "metadata": {}, - "outputs": [], - "source": [ - "pip3 install tensorflow" - ] - }, - { - "cell_type": "markdown", - "id": "d2f8d6f3", - "metadata": {}, - "source": [ - "and/or if you use **anaconda**, just write (or install from the graphical user interface)\n", - "(current release of CPU-only TensorFlow)" - ] - }, - { - "cell_type": "code", - "execution_count": 15, - "id": "fdaffccc", - "metadata": {}, - "outputs": [], - "source": [ - "conda create -n tf tensorflow\n", - "conda activate tf" - ] - }, - { - "cell_type": "markdown", - "id": "80db034a", - "metadata": {}, - "source": [ - "To install the current release of GPU TensorFlow" - ] - }, - { - "cell_type": "code", - "execution_count": 16, - "id": "e632c541", - "metadata": {}, - "outputs": [], - "source": [ - "conda create -n tf-gpu tensorflow-gpu\n", - "conda activate tf-gpu" - ] - }, - { - "cell_type": "markdown", - "id": "605ac1fd", - "metadata": {}, - "source": [ - "## Using Keras\n", - "\n", - "Keras is a high level [neural network](https://en.wikipedia.org/wiki/Application_programming_interface)\n", - "that supports Tensorflow, CTNK and Theano as backends. \n", - "If you have Anaconda installed you may run the following command" - ] - }, - { - "cell_type": "code", - "execution_count": 17, - "id": "11e69ce0", - "metadata": {}, - "outputs": [], - "source": [ - "conda install keras" - ] - }, - { - "cell_type": "markdown", - "id": "176bf3ac", - "metadata": {}, - "source": [ - "You can look up the [instructions here](https://keras.io/) for more information.\n", - "\n", - "We will to a large extent use **keras** in this course." - ] - }, - { - "cell_type": "markdown", - "id": "7a085449", - "metadata": {}, - "source": [ - "## Collect and pre-process data\n", - "\n", - "Let us look again at the MINST data set." - ] - }, - { - "cell_type": "code", - "execution_count": 18, - "id": "d8bae540", - "metadata": {}, - "outputs": [], - "source": [ - "# import necessary packages\n", - "import numpy as np\n", - "import matplotlib.pyplot as plt\n", - "import tensorflow as tf\n", - "from sklearn import datasets\n", - "\n", - "\n", - "# ensure the same random numbers appear every time\n", - "np.random.seed(0)\n", - "\n", - "# display images in notebook\n", - "%matplotlib inline\n", - "plt.rcParams['figure.figsize'] = (12,12)\n", - "\n", - "\n", - "# download MNIST dataset\n", - "digits = datasets.load_digits()\n", - "\n", - "# define inputs and labels\n", - "inputs = digits.images\n", - "labels = digits.target\n", - "\n", - "print(\"inputs = (n_inputs, pixel_width, pixel_height) = \" + str(inputs.shape))\n", - "print(\"labels = (n_inputs) = \" + str(labels.shape))\n", - "\n", - "\n", - "# flatten the image\n", - "# the value -1 means dimension is inferred from the remaining dimensions: 8x8 = 64\n", - "n_inputs = len(inputs)\n", - "inputs = inputs.reshape(n_inputs, -1)\n", - "print(\"X = (n_inputs, n_features) = \" + str(inputs.shape))\n", - "\n", - "\n", - "# choose some random images to display\n", - "indices = np.arange(n_inputs)\n", - "random_indices = np.random.choice(indices, size=5)\n", - "\n", - "for i, image in enumerate(digits.images[random_indices]):\n", - " plt.subplot(1, 5, i+1)\n", - " plt.axis('off')\n", - " plt.imshow(image, cmap=plt.cm.gray_r, interpolation='nearest')\n", - " plt.title(\"Label: %d\" % digits.target[random_indices[i]])\n", - "plt.show()" - ] - }, - { - "cell_type": "code", - "execution_count": 19, - "id": "5608d691", - "metadata": {}, - "outputs": [], - "source": [ - "from tensorflow.keras.layers import Input\n", - "from tensorflow.keras.models import Sequential #This allows appending layers to existing models\n", - "from tensorflow.keras.layers import Dense #This allows defining the characteristics of a particular layer\n", - "from tensorflow.keras import optimizers #This allows using whichever optimiser we want (sgd,adam,RMSprop)\n", - "from tensorflow.keras import regularizers #This allows using whichever regularizer we want (l1,l2,l1_l2)\n", - "from tensorflow.keras.utils import to_categorical #This allows using categorical cross entropy as the cost function\n", - "\n", - "from sklearn.model_selection import train_test_split\n", - "\n", - "# one-hot representation of labels\n", - "labels = to_categorical(labels)\n", - "\n", - "# split into train and test data\n", - "train_size = 0.8\n", - "test_size = 1 - train_size\n", - "X_train, X_test, Y_train, Y_test = train_test_split(inputs, labels, train_size=train_size,\n", - " test_size=test_size)" - ] - }, - { - "cell_type": "code", - "execution_count": 20, - "id": "7bce7422", - "metadata": {}, - "outputs": [], - "source": [ - "\n", - "epochs = 100\n", - "batch_size = 100\n", - "n_neurons_layer1 = 100\n", - "n_neurons_layer2 = 50\n", - "n_categories = 10\n", - "eta_vals = np.logspace(-5, 1, 7)\n", - "lmbd_vals = np.logspace(-5, 1, 7)\n", - "def create_neural_network_keras(n_neurons_layer1, n_neurons_layer2, n_categories, eta, lmbd):\n", - " model = Sequential()\n", - " model.add(Dense(n_neurons_layer1, activation='sigmoid', kernel_regularizer=regularizers.l2(lmbd)))\n", - " model.add(Dense(n_neurons_layer2, activation='sigmoid', kernel_regularizer=regularizers.l2(lmbd)))\n", - " model.add(Dense(n_categories, activation='softmax'))\n", - " \n", - " sgd = optimizers.SGD(lr=eta)\n", - " model.compile(loss='categorical_crossentropy', optimizer=sgd, metrics=['accuracy'])\n", - " \n", - " return model" - ] - }, - { - "cell_type": "code", - "execution_count": 21, - "id": "65a68468", - "metadata": {}, - "outputs": [], - "source": [ - "DNN_keras = np.zeros((len(eta_vals), len(lmbd_vals)), dtype=object)\n", - " \n", - "for i, eta in enumerate(eta_vals):\n", - " for j, lmbd in enumerate(lmbd_vals):\n", - " DNN = create_neural_network_keras(n_neurons_layer1, n_neurons_layer2, n_categories,\n", - " eta=eta, lmbd=lmbd)\n", - " DNN.fit(X_train, Y_train, epochs=epochs, batch_size=batch_size, verbose=0)\n", - " scores = DNN.evaluate(X_test, Y_test)\n", - " \n", - " DNN_keras[i][j] = DNN\n", - " \n", - " print(\"Learning rate = \", eta)\n", - " print(\"Lambda = \", lmbd)\n", - " print(\"Test accuracy: %.3f\" % scores[1])\n", - " print()" - ] - }, - { - "cell_type": "code", - "execution_count": 22, - "id": "45ae200f", - "metadata": {}, - "outputs": [], - "source": [ - "# optional\n", - "# visual representation of grid search\n", - "# uses seaborn heatmap, could probably do this in matplotlib\n", - "import seaborn as sns\n", - "\n", - "sns.set()\n", - "\n", - "train_accuracy = np.zeros((len(eta_vals), len(lmbd_vals)))\n", - "test_accuracy = np.zeros((len(eta_vals), len(lmbd_vals)))\n", - "\n", - "for i in range(len(eta_vals)):\n", - " for j in range(len(lmbd_vals)):\n", - " DNN = DNN_keras[i][j]\n", - "\n", - " train_accuracy[i][j] = DNN.evaluate(X_train, Y_train)[1]\n", - " test_accuracy[i][j] = DNN.evaluate(X_test, Y_test)[1]\n", - "\n", - " \n", - "fig, ax = plt.subplots(figsize = (10, 10))\n", - "sns.heatmap(train_accuracy, annot=True, ax=ax, cmap=\"viridis\")\n", - "ax.set_title(\"Training Accuracy\")\n", - "ax.set_ylabel(\"$\\eta$\")\n", - "ax.set_xlabel(\"$\\lambda$\")\n", - "plt.show()\n", - "\n", - "fig, ax = plt.subplots(figsize = (10, 10))\n", - "sns.heatmap(test_accuracy, annot=True, ax=ax, cmap=\"viridis\")\n", - "ax.set_title(\"Test Accuracy\")\n", - "ax.set_ylabel(\"$\\eta$\")\n", - "ax.set_xlabel(\"$\\lambda$\")\n", - "plt.show()" - ] - }, - { - "cell_type": "markdown", - "id": "b955ad39", - "metadata": {}, - "source": [ - "## The Breast Cancer Data, now with Keras" - ] - }, - { - "cell_type": "code", - "execution_count": 23, - "id": "8ed2e257", - "metadata": {}, - "outputs": [], - "source": [ - "\n", - "import tensorflow as tf\n", - "from tensorflow.keras.layers import Input\n", - "from tensorflow.keras.models import Sequential #This allows appending layers to existing models\n", - "from tensorflow.keras.layers import Dense #This allows defining the characteristics of a particular layer\n", - "from tensorflow.keras import optimizers #This allows using whichever optimiser we want (sgd,adam,RMSprop)\n", - "from tensorflow.keras import regularizers #This allows using whichever regularizer we want (l1,l2,l1_l2)\n", - "from tensorflow.keras.utils import to_categorical #This allows using categorical cross entropy as the cost function\n", - "import numpy as np\n", - "import matplotlib.pyplot as plt\n", - "import seaborn as sns\n", - "from sklearn.model_selection import train_test_split as splitter\n", - "from sklearn.datasets import load_breast_cancer\n", - "import pickle\n", - "import os \n", - "\n", - "\n", - "\"\"\"Load breast cancer dataset\"\"\"\n", - "\n", - "np.random.seed(0) #create same seed for random number every time\n", - "\n", - "cancer=load_breast_cancer() #Download breast cancer dataset\n", - "\n", - "inputs=cancer.data #Feature matrix of 569 rows (samples) and 30 columns (parameters)\n", - "outputs=cancer.target #Label array of 569 rows (0 for benign and 1 for malignant)\n", - "labels=cancer.feature_names[0:30]\n", - "\n", - "print('The content of the breast cancer dataset is:') #Print information about the datasets\n", - "print(labels)\n", - "print('-------------------------')\n", - "print(\"inputs = \" + str(inputs.shape))\n", - "print(\"outputs = \" + str(outputs.shape))\n", - "print(\"labels = \"+ str(labels.shape))\n", - "\n", - "x=inputs #Reassign the Feature and Label matrices to other variables\n", - "y=outputs\n", - "\n", - "#%% \n", - "\n", - "# Visualisation of dataset (for correlation analysis)\n", - "\n", - "plt.figure()\n", - "plt.scatter(x[:,0],x[:,2],s=40,c=y,cmap=plt.cm.Spectral)\n", - "plt.xlabel('Mean radius',fontweight='bold')\n", - "plt.ylabel('Mean perimeter',fontweight='bold')\n", - "plt.show()\n", - "\n", - "plt.figure()\n", - "plt.scatter(x[:,5],x[:,6],s=40,c=y, cmap=plt.cm.Spectral)\n", - "plt.xlabel('Mean compactness',fontweight='bold')\n", - "plt.ylabel('Mean concavity',fontweight='bold')\n", - "plt.show()\n", - "\n", - "\n", - "plt.figure()\n", - "plt.scatter(x[:,0],x[:,1],s=40,c=y,cmap=plt.cm.Spectral)\n", - "plt.xlabel('Mean radius',fontweight='bold')\n", - "plt.ylabel('Mean texture',fontweight='bold')\n", - "plt.show()\n", - "\n", - "plt.figure()\n", - "plt.scatter(x[:,2],x[:,1],s=40,c=y,cmap=plt.cm.Spectral)\n", - "plt.xlabel('Mean perimeter',fontweight='bold')\n", - "plt.ylabel('Mean compactness',fontweight='bold')\n", - "plt.show()\n", - "\n", - "\n", - "# Generate training and testing datasets\n", - "\n", - "#Select features relevant to classification (texture,perimeter,compactness and symmetery) \n", - "#and add to input matrix\n", - "\n", - "temp1=np.reshape(x[:,1],(len(x[:,1]),1))\n", - "temp2=np.reshape(x[:,2],(len(x[:,2]),1))\n", - "X=np.hstack((temp1,temp2)) \n", - "temp=np.reshape(x[:,5],(len(x[:,5]),1))\n", - "X=np.hstack((X,temp)) \n", - "temp=np.reshape(x[:,8],(len(x[:,8]),1))\n", - "X=np.hstack((X,temp)) \n", - "\n", - "X_train,X_test,y_train,y_test=splitter(X,y,test_size=0.1) #Split datasets into training and testing\n", - "\n", - "y_train=to_categorical(y_train) #Convert labels to categorical when using categorical cross entropy\n", - "y_test=to_categorical(y_test)\n", - "\n", - "del temp1,temp2,temp\n", - "\n", - "# %%\n", - "\n", - "# Define tunable parameters\"\n", - "\n", - "eta=np.logspace(-3,-1,3) #Define vector of learning rates (parameter to SGD optimiser)\n", - "lamda=0.01 #Define hyperparameter\n", - "n_layers=2 #Define number of hidden layers in the model\n", - "n_neuron=np.logspace(0,3,4,dtype=int) #Define number of neurons per layer\n", - "epochs=100 #Number of reiterations over the input data\n", - "batch_size=100 #Number of samples per gradient update\n", - "\n", - "# %%\n", - "\n", - "\"\"\"Define function to return Deep Neural Network model\"\"\"\n", - "\n", - "def NN_model(inputsize,n_layers,n_neuron,eta,lamda):\n", - " model=Sequential() \n", - " for i in range(n_layers): #Run loop to add hidden layers to the model\n", - " if (i==0): #First layer requires input dimensions\n", - " model.add(Dense(n_neuron,activation='relu',kernel_regularizer=regularizers.l2(lamda),input_dim=inputsize))\n", - " else: #Subsequent layers are capable of automatic shape inferencing\n", - " model.add(Dense(n_neuron,activation='relu',kernel_regularizer=regularizers.l2(lamda)))\n", - " model.add(Dense(2,activation='softmax')) #2 outputs - ordered and disordered (softmax for prob)\n", - " sgd=optimizers.SGD(lr=eta)\n", - " model.compile(loss='categorical_crossentropy',optimizer=sgd,metrics=['accuracy'])\n", - " return model\n", - "\n", - " \n", - "Train_accuracy=np.zeros((len(n_neuron),len(eta))) #Define matrices to store accuracy scores as a function\n", - "Test_accuracy=np.zeros((len(n_neuron),len(eta))) #of learning rate and number of hidden neurons for \n", - "\n", - "for i in range(len(n_neuron)): #run loops over hidden neurons and learning rates to calculate \n", - " for j in range(len(eta)): #accuracy scores \n", - " DNN_model=NN_model(X_train.shape[1],n_layers,n_neuron[i],eta[j],lamda)\n", - " DNN_model.fit(X_train,y_train,epochs=epochs,batch_size=batch_size,verbose=1)\n", - " Train_accuracy[i,j]=DNN_model.evaluate(X_train,y_train)[1]\n", - " Test_accuracy[i,j]=DNN_model.evaluate(X_test,y_test)[1]\n", - " \n", - "\n", - "def plot_data(x,y,data,title=None):\n", - "\n", - " # plot results\n", - " fontsize=16\n", - "\n", - "\n", - " fig = plt.figure()\n", - " ax = fig.add_subplot(111)\n", - " cax = ax.matshow(data, interpolation='nearest', vmin=0, vmax=1)\n", - " \n", - " cbar=fig.colorbar(cax)\n", - " cbar.ax.set_ylabel('accuracy (%)',rotation=90,fontsize=fontsize)\n", - " cbar.set_ticks([0,.2,.4,0.6,0.8,1.0])\n", - " cbar.set_ticklabels(['0%','20%','40%','60%','80%','100%'])\n", - "\n", - " # put text on matrix elements\n", - " for i, x_val in enumerate(np.arange(len(x))):\n", - " for j, y_val in enumerate(np.arange(len(y))):\n", - " c = \"${0:.1f}\\\\%$\".format( 100*data[j,i]) \n", - " ax.text(x_val, y_val, c, va='center', ha='center')\n", - "\n", - " # convert axis vaues to to string labels\n", - " x=[str(i) for i in x]\n", - " y=[str(i) for i in y]\n", - "\n", - "\n", - " ax.set_xticklabels(['']+x)\n", - " ax.set_yticklabels(['']+y)\n", - "\n", - " ax.set_xlabel('$\\\\mathrm{learning\\\\ rate}$',fontsize=fontsize)\n", - " ax.set_ylabel('$\\\\mathrm{hidden\\\\ neurons}$',fontsize=fontsize)\n", - " if title is not None:\n", - " ax.set_title(title)\n", - "\n", - " plt.tight_layout()\n", - "\n", - " plt.show()\n", - " \n", - "plot_data(eta,n_neuron,Train_accuracy, 'training')\n", - "plot_data(eta,n_neuron,Test_accuracy, 'testing')" - ] - }, - { - "cell_type": "markdown", - "id": "107bab25", - "metadata": {}, - "source": [ - "## Fine-tuning neural network hyperparameters\n", - "\n", - "The flexibility of neural networks is also one of their main\n", - "drawbacks: there are many hyperparameters to tweak. Not only can you\n", - "use any imaginable network topology (how neurons/nodes are interconnected),\n", - "but even in a simple FFNN you can change the number of layers, the\n", - "number of neurons per layer, the type of activation function to use in\n", - "each layer, the weight initialization logic, the stochastic gradient optmized and much more. How do you\n", - "know what combination of hyperparameters is the best for your task?\n", - "\n", - "* You can use grid search with cross-validation to find the right hyperparameters.\n", - "\n", - "However,since there are many hyperparameters to tune, and since\n", - "training a neural network on a large dataset takes a lot of time, you\n", - "will only be able to explore a tiny part of the hyperparameter space.\n", - "\n", - "* You can use randomized search.\n", - "\n", - "* Or use tools like [Oscar](http://oscar.calldesk.ai/), which implements more complex algorithms to help you find a good set of hyperparameters quickly." - ] - }, - { - "cell_type": "markdown", - "id": "53ad43ce", - "metadata": {}, - "source": [ - "## Hidden layers\n", - "\n", - "For many problems you can start with just one or two hidden layers and it will work just fine.\n", - "For the MNIST data set you ca easily get a high accuracy using just one hidden layer with a\n", - "few hundred neurons.\n", - "You can reach for this data set above 98% accuracy using two hidden layers with the same total amount of\n", - "neurons, in roughly the same amount of training time. \n", - "\n", - "For more complex problems, you can gradually\n", - "ramp up the number of hidden layers, until you start overfitting the training set. Very complex tasks, such\n", - "as large image classification or speech recognition, typically require networks with dozens of layers\n", - "and they need a huge amount\n", - "of training data. However, you will rarely have to train such networks from scratch: it is much more\n", - "common to reuse parts of a pretrained state-of-the-art network that performs a similar task." - ] - }, - { - "cell_type": "markdown", - "id": "6f613497", - "metadata": {}, - "source": [ - "## Which activation function should I use?\n", - "\n", - "The Back propagation algorithm we derived above works by going from\n", - "the output layer to the input layer, propagating the error gradient on\n", - "the way. Once the algorithm has computed the gradient of the cost\n", - "function with regards to each parameter in the network, it uses these\n", - "gradients to update each parameter with a Gradient Descent (GD) step.\n", - "\n", - "Unfortunately for us, the gradients often get smaller and smaller as the\n", - "algorithm progresses down to the first hidden layers. As a result, the\n", - "GD update leaves the lower layer connection weights\n", - "virtually unchanged, and training never converges to a good\n", - "solution. This is known in the literature as \n", - "**the vanishing gradients problem**. \n", - "\n", - "In other cases, the opposite can happen, namely the the gradients can grow bigger and\n", - "bigger. The result is that many of the layers get large updates of the \n", - "weights the\n", - "algorithm diverges. This is the **exploding gradients problem**, which is\n", - "mostly encountered in recurrent neural networks. More generally, deep\n", - "neural networks suffer from unstable gradients, different layers may\n", - "learn at widely different speeds" - ] - }, - { - "cell_type": "markdown", - "id": "91843fee", - "metadata": {}, - "source": [ - "## Is the Logistic activation function (Sigmoid) our choice?\n", - "\n", - "Although this unfortunate behavior has been empirically observed for\n", - "quite a while (it was one of the reasons why deep neural networks were\n", - "mostly abandoned for a long time), it is only around 2010 that\n", - "significant progress was made in understanding it.\n", - "\n", - "A paper titled [Understanding the Difficulty of Training Deep\n", - "Feedforward Neural Networks by Xavier Glorot and Yoshua Bengio](http://proceedings.mlr.press/v9/glorot10a.html) found that\n", - "the problems with the popular logistic\n", - "sigmoid activation function and the weight initialization technique\n", - "that was most popular at the time, namely random initialization using\n", - "a normal distribution with a mean of 0 and a standard deviation of\n", - "1. \n", - "\n", - "They showed that with this activation function and this\n", - "initialization scheme, the variance of the outputs of each layer is\n", - "much greater than the variance of its inputs. Going forward in the\n", - "network, the variance keeps increasing after each layer until the\n", - "activation function saturates at the top layers. This is actually made\n", - "worse by the fact that the logistic function has a mean of 0.5, not 0\n", - "(the hyperbolic tangent function has a mean of 0 and behaves slightly\n", - "better than the logistic function in deep networks)." - ] - }, - { - "cell_type": "markdown", - "id": "83535426", - "metadata": {}, - "source": [ - "## The derivative of the Logistic funtion\n", - "\n", - "Looking at the logistic activation function, when inputs become large\n", - "(negative or positive), the function saturates at 0 or 1, with a\n", - "derivative extremely close to 0. Thus when backpropagation kicks in,\n", - "it has virtually no gradient to propagate back through the network,\n", - "and what little gradient exists keeps getting diluted as\n", - "backpropagation progresses down through the top layers, so there is\n", - "really nothing left for the lower layers.\n", - "\n", - "In their paper, Glorot and Bengio propose a way to significantly\n", - "alleviate this problem. We need the signal to flow properly in both\n", - "directions: in the forward direction when making predictions, and in\n", - "the reverse direction when backpropagating gradients. We don’t want\n", - "the signal to die out, nor do we want it to explode and saturate. For\n", - "the signal to flow properly, the authors argue that we need the\n", - "variance of the outputs of each layer to be equal to the variance of\n", - "its inputs, and we also need the gradients to have equal variance\n", - "before and after flowing through a layer in the reverse direction.\n", - "\n", - "One of the insights in the 2010 paper by Glorot and Bengio was that\n", - "the vanishing/exploding gradients problems were in part due to a poor\n", - "choice of activation function. Until then most people had assumed that\n", - "if Nature had chosen to use roughly sigmoid activation functions in\n", - "biological neurons, they must be an excellent choice. But it turns out\n", - "that other activation functions behave much better in deep neural\n", - "networks, in particular the ReLU activation function, mostly because\n", - "it does not saturate for positive values (and also because it is quite\n", - "fast to compute)." - ] - }, - { - "cell_type": "markdown", - "id": "37bdca60", - "metadata": {}, - "source": [ - "## The RELU function family\n", - "\n", - "The ReLU activation function suffers from a problem known as the dying\n", - "ReLUs: during training, some neurons effectively die, meaning they\n", - "stop outputting anything other than 0.\n", - "\n", - "In some cases, you may find that half of your network’s neurons are\n", - "dead, especially if you used a large learning rate. During training,\n", - "if a neuron’s weights get updated such that the weighted sum of the\n", - "neuron’s inputs is negative, it will start outputting 0. When this\n", - "happen, the neuron is unlikely to come back to life since the gradient\n", - "of the ReLU function is 0 when its input is negative.\n", - "\n", - "To solve this problem, nowadays practitioners use a variant of the ReLU\n", - "function, such as the leaky ReLU discussed above or the so-called\n", - "exponential linear unit (ELU) function" - ] - }, - { - "cell_type": "markdown", - "id": "11ae19d2", - "metadata": {}, - "source": [ - "$$\n", - "ELU(z) = \\left\\{\\begin{array}{cc} \\alpha\\left( \\exp{(z)}-1\\right) & z < 0,\\\\ z & z \\ge 0.\\end{array}\\right.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "f3a54f08", - "metadata": {}, - "source": [ - "## Which activation function should we use?\n", - "\n", - "In general it seems that the ELU activation function is better than\n", - "the leaky ReLU function (and its variants), which is better than\n", - "ReLU. ReLU performs better than $\\tanh$ which in turn performs better\n", - "than the logistic function. \n", - "\n", - "If runtime\n", - "performance is an issue, then you may opt for the leaky ReLU function over the \n", - "ELU function If you don’t\n", - "want to tweak yet another hyperparameter, you may just use the default\n", - "$\\alpha$ of $0.01$ for the leaky ReLU, and $1$ for ELU. If you have\n", - "spare time and computing power, you can use cross-validation or\n", - "bootstrap to evaluate other activation functions." - ] - }, - { - "cell_type": "markdown", - "id": "4dd226db", - "metadata": {}, - "source": [ - "## More on activation functions, output layers\n", - "\n", - "In most cases you can use the ReLU activation function in the hidden layers (or one of its variants).\n", - "\n", - "It is a bit faster to compute than other activation functions, and the gradient descent optimization does in general not get stuck.\n", - "\n", - "**For the output layer:**\n", - "\n", - "* For classification the softmax activation function is generally a good choice for classification tasks (when the classes are mutually exclusive).\n", - "\n", - "* For regression tasks, you can simply use no activation function at all." - ] - }, - { - "cell_type": "markdown", - "id": "f9521d8f", - "metadata": {}, - "source": [ - "## Batch Normalization\n", - "\n", - "Batch Normalization\n", - "aims to address the vanishing/exploding gradients problems, and more generally the problem that the\n", - "distribution of each layer’s inputs changes during training, as the parameters of the previous layers change.\n", - "\n", - "The technique consists of adding an operation in the model just before the activation function of each\n", - "layer, simply zero-centering and normalizing the inputs, then scaling and shifting the result using two new\n", - "parameters per layer (one for scaling, the other for shifting). In other words, this operation lets the model\n", - "learn the optimal scale and mean of the inputs for each layer.\n", - "In order to zero-center and normalize the inputs, the algorithm needs to estimate the inputs’ mean and\n", - "standard deviation. It does so by evaluating the mean and standard deviation of the inputs over the current\n", - "mini-batch, from this the name batch normalization." - ] - }, - { - "cell_type": "markdown", - "id": "080c7f12", - "metadata": {}, - "source": [ - "## Dropout\n", - "\n", - "It is a fairly simple algorithm: at every training step, every neuron (including the input neurons but\n", - "excluding the output neurons) has a probability $p$ of being temporarily dropped out, meaning it will be\n", - "entirely ignored during this training step, but it may be active during the next step.\n", - "\n", - "The\n", - "hyperparameter $p$ is called the dropout rate, and it is typically set to 50%. After training, the neurons are not dropped anymore.\n", - " It is viewed as one of the most popular regularization techniques." - ] - }, - { - "cell_type": "markdown", - "id": "963e7d21", - "metadata": {}, - "source": [ - "## Gradient Clipping\n", - "\n", - "A popular technique to lessen the exploding gradients problem is to simply clip the gradients during\n", - "backpropagation so that they never exceed some threshold (this is mostly useful for recurrent neural\n", - "networks).\n", - "\n", - "This technique is called Gradient Clipping.\n", - "\n", - "In general however, Batch\n", - "Normalization is preferred." - ] - }, - { - "cell_type": "markdown", - "id": "0b69f45e", - "metadata": {}, - "source": [ - "## A very nice website on Neural Networks\n", - "\n", - "You may find this [website](https://playground.tensorflow.org/#activation=tanh&batchSize=10&dataset=circle®Dataset=reg-plane&learningRate=0.03®ularizationRate=0&noise=0&networkShape=4,2&seed=0.29243&showTestData=false&discretize=false&percTrainData=50&x=true&y=true&xTimesY=false&xSquared=false&ySquared=false&cosX=false&sinX=false&cosY=false&sinY=false&collectStats=false&problem=classification&initZero=false&hideText=false) very useful." - ] - }, - { - "cell_type": "markdown", - "id": "3585dfbf", - "metadata": {}, - "source": [ - "## A top-down perspective on Neural networks\n", - "\n", - "The first thing we would like to do is divide the data into two or three\n", - "parts. A training set, a validation or dev (development) set, and a\n", - "test set. The test set is the data on which we want to make\n", - "predictions. The dev set is a subset of the training data we use to\n", - "check how well we are doing out-of-sample, after training the model on\n", - "the training dataset. We use the validation error as a proxy for the\n", - "test error in order to make tweaks to our model. It is crucial that we\n", - "do not use any of the test data to train the algorithm. This is a\n", - "cardinal sin in ML. Then:\n", - "\n", - "* Estimate optimal error rate\n", - "\n", - "* Minimize underfitting (bias) on training data set.\n", - "\n", - "* Make sure you are not overfitting.\n", - "\n", - "If the validation and test sets are drawn from the same distributions,\n", - "then a good performance on the validation set should lead to similarly\n", - "good performance on the test set. \n", - "\n", - "However, sometimes\n", - "the training data and test data differ in subtle ways because, for\n", - "example, they are collected using slightly different methods, or\n", - "because it is cheaper to collect data in one way versus another. In\n", - "this case, there can be a mismatch between the training and test\n", - "data. This can lead to the neural network overfitting these small\n", - "differences between the test and training sets, and a poor performance\n", - "on the test set despite having a good performance on the validation\n", - "set. To rectify this, Andrew Ng suggests making two validation or dev\n", - "sets, one constructed from the training data and one constructed from\n", - "the test data. The difference between the performance of the algorithm\n", - "on these two validation sets quantifies the train-test mismatch. This\n", - "can serve as another important diagnostic when using DNNs for\n", - "supervised learning." - ] - }, - { - "cell_type": "markdown", - "id": "dd7c4575", - "metadata": {}, - "source": [ - "## Limitations of supervised learning with deep networks\n", - "\n", - "Like all statistical methods, supervised learning using neural\n", - "networks has important limitations. This is especially important when\n", - "one seeks to apply these methods, especially to physics problems. Like\n", - "all tools, DNNs are not a universal solution. Often, the same or\n", - "better performance on a task can be achieved by using a few\n", - "hand-engineered features (or even a collection of random\n", - "features). \n", - "\n", - "Here we list some of the important limitations of supervised neural network based models. \n", - "\n", - "* **Need labeled data**. All supervised learning methods, DNNs for supervised learning require labeled data. Often, labeled data is harder to acquire than unlabeled data (e.g. one must pay for human experts to label images).\n", - "\n", - "* **Supervised neural networks are extremely data intensive.** DNNs are data hungry. They perform best when data is plentiful. This is doubly so for supervised methods where the data must also be labeled. The utility of DNNs is extremely limited if data is hard to acquire or the datasets are small (hundreds to a few thousand samples). In this case, the performance of other methods that utilize hand-engineered features can exceed that of DNNs.\n", - "\n", - "* **Homogeneous data.** Almost all DNNs deal with homogeneous data of one type. It is very hard to design architectures that mix and match data types (i.e. some continuous variables, some discrete variables, some time series). In applications beyond images, video, and language, this is often what is required. In contrast, ensemble models like random forests or gradient-boosted trees have no difficulty handling mixed data types.\n", - "\n", - "* **Many problems are not about prediction.** In natural science we are often interested in learning something about the underlying distribution that generates the data. In this case, it is often difficult to cast these ideas in a supervised learning setting. While the problems are related, it is possible to make good predictions with a *wrong* model. The model might or might not be useful for understanding the underlying science.\n", - "\n", - "Some of these remarks are particular to DNNs, others are shared by all supervised learning methods. This motivates the use of unsupervised methods which in part circumvent these problems." - ] - } - ], - "metadata": { - "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.9.10" - } - }, - "nbformat": 4, - "nbformat_minor": 5 -} diff --git a/doc/LectureNotes/week43.ipynb b/doc/LectureNotes/week43.ipynb deleted file mode 100644 index 94b84df7a..000000000 --- a/doc/LectureNotes/week43.ipynb +++ /dev/null @@ -1,7528 +0,0 @@ -{ - "cells": [ - { - "cell_type": "markdown", - "id": "42ce64ba", - "metadata": { - "editable": true - }, - "source": [ - "\n", - "" - ] - }, - { - "cell_type": "markdown", - "id": "c987b86b", - "metadata": { - "editable": true - }, - "source": [ - "# Week 43: Deep Learning: Constructing a Neural Network code and solving differential equations\n", - "**Morten Hjorth-Jensen**, Department of Physics, University of Oslo and Department of Physics and Astronomy and Facility for Rare Isotope Beams, Michigan State University\n", - "\n", - "Date: **Oct 26, 2023**\n", - "\n", - "Copyright 1999-2023, Morten Hjorth-Jensen. Released under CC Attribution-NonCommercial 4.0 license" - ] - }, - { - "cell_type": "markdown", - "id": "0dc0d6ca", - "metadata": { - "editable": true - }, - "source": [ - "## Plans for week 43\n", - "\n", - "**Material for the active learning sessions on Tuesday and Wednesday.**\n", - "\n", - " * Exercise on writing your own neural network code, application to the OR and XOR gates\n", - "\n", - " * The exercises this week will be continued next week as well\n", - "\n", - " * Discussion of project 2\n", - "\n", - " * [Video of lab session](https://youtu.be/Ia6wwDLxqtM)\n", - "\n", - " \n", - "\n", - "**Material for the lecture on Thursday October 26, 2023.**\n", - "\n", - " * Building our own Feed-forward Neural Network and discussion of project 2, continuation from last week\n", - "\n", - " * Solving differential equations with Neural Networks and intro to **Tensorflow** with examples.\n", - "\n", - " * [Video of lecture](https://youtu.be/_-AwbBh4G-8)\n", - "\n", - " * Readings and Videos:\n", - "\n", - " * These lecture notes\n", - "\n", - " * [Aurelien Geron's chapters 10-11](https://github.com/CompPhysics/MachineLearning/blob/master/doc/Textbooks/TensorflowML.pdf)\n", - "\n", - " * For a more in depth discussion on neural networks we recommend Goodfellow et al chapters 6 and 7. \n", - "\n", - " * [Neural Networks demystified](https://www.youtube.com/watch?v=bxe2T-V8XRs&list=PLiaHhY2iBX9hdHaRr6b7XevZtgZRa1PoU&ab_channel=WelchLabs)\n", - "\n", - " * [Building Neural Networks from scratch](https://www.youtube.com/watch?v=Wo5dMEP_BbI&list=PLQVvvaa0QuDcjD5BAw2DxE6OF2tius3V3&ab_channel=sentdex)\n", - "\n", - " * [Video on Neural Networks](https://www.youtube.com/watch?v=CqOfi41LfDw)\n", - "\n", - " * [Video on the back propagation algorithm](https://www.youtube.com/watch?v=Ilg3gGewQ5U)\n", - "\n", - "I also recommend Michael Nielsen's intuitive approach to the neural networks and the universal approximation theorem, see the slides at ." - ] - }, - { - "cell_type": "markdown", - "id": "f4d3253b", - "metadata": { - "editable": true - }, - "source": [ - "## Using Automatic differentiation\n", - "a\n", - "In our discussions of ordinary differential equations \n", - "we will also study the usage of [Autograd](https://www.youtube.com/watch?v=fRf4l5qaX1M&ab_channel=AlexSmola) in computing gradients for deep learning. For the documentation of Autograd and examples see the lectures slides from [week 39](https://compphysics.github.io/MachineLearning/doc/pub/week39/html/week39.html) and the [Autograd documentation](https://github.com/HIPS/autograd).\n", - "t" - ] - }, - { - "cell_type": "markdown", - "id": "9744596b", - "metadata": { - "editable": true - }, - "source": [ - "## Back propagation and automatic differentiation\n", - "\n", - "For more details on the back propagation algorithm and automatic differentiation see\n", - "1. \n", - "\n", - "2. \n", - "\n", - "3. Slides 12-44 at URL\":http://cs231n.stanford.edu/slides/2017/cs231n_2017_lecture4.pdf\"" - ] - }, - { - "cell_type": "markdown", - "id": "bd189f93", - "metadata": { - "editable": true - }, - "source": [ - "## Material for exercises week 43 and week 44" - ] - }, - { - "cell_type": "markdown", - "id": "e901e3d4", - "metadata": { - "editable": true - }, - "source": [ - "## Writing our first neural network code, testing it for the OR and XOR gates\n", - "\n", - "During week 41 we discussed three different types of gates, the\n", - "so-called XOR, the OR and the AND gates. In order to develop a code\n", - "for neural networks, it can be useful to set up a simpler system with\n", - "only two inputs and one output. This can make it easier to debug and\n", - "study the feed forward pass and the back propagation part. In the\n", - "exercise this and next week, we propose to study this system with just\n", - "one hidden layer and two hidden nodes. There is only one output node\n", - "and we can choose to use either a simple regression case (fitting a\n", - "line) or just a binary classification case with the corss-entropy as\n", - "cost function.\n", - "\n", - "Their inputs and outputs can be\n", - "summarized using the following tables, first for the OR gate with\n", - "inputs $x_1$ and $x_2$ and outputs $y$:\n", - "\n", - "\n", - "\n", - "\n", - "\n", - "\n", - "\n", - "\n", - "\n", - "\n", - "\n", - "
$x_1$ $x_2$ $y$
0 0 0
0 1 1
1 0 1
1 1 1
" - ] - }, - { - "cell_type": "markdown", - "id": "fca381f9", - "metadata": { - "editable": true - }, - "source": [ - "## The AND and XOR Gates\n", - "\n", - "The AND gate is defined as\n", - "\n", - "\n", - "\n", - "\n", - "\n", - "\n", - "\n", - "\n", - "\n", - "\n", - "\n", - "
$x_1$ $x_2$ $y$
0 0 0
0 1 0
1 0 0
1 1 1
\n", - "\n", - "And finally we have the XOR gate\n", - "\n", - "\n", - "\n", - "\n", - "\n", - "\n", - "\n", - "\n", - "\n", - "\n", - "\n", - "
$x_1$ $x_2$ $y$
0 0 0
0 1 1
1 0 1
1 1 0
" - ] - }, - { - "cell_type": "markdown", - "id": "f0252121", - "metadata": { - "editable": true - }, - "source": [ - "## Representing the Data Sets\n", - "\n", - "Our design matrix is defined by the input values $x_1$ and $x_2$. Since we have four possible outputs, our design matrix reads" - ] - }, - { - "cell_type": "markdown", - "id": "f59fc5ee", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\boldsymbol{X}=\\begin{bmatrix} 0 & 0 \\\\\n", - " 0 & 1 \\\\\n", - "\t\t 1 & 0 \\\\\n", - "\t\t 1 & 1 \\end{bmatrix},\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "1d74ec2a", - "metadata": { - "editable": true - }, - "source": [ - "while the vector of outputs is $\\boldsymbol{y}^T=[0,1,1,0]$ for the XOR gate, $\\boldsymbol{y}^T=[0,0,0,1]$ for the AND gate and $\\boldsymbol{y}^T=[0,1,1,1]$ for the OR gate.\n", - "\n", - "Your tasks here are\n", - "\n", - "1. Set up the design matrix with the inputs as discussed above and a vector containing the output, the so-called targets. Note that the design matrix is the same for all gates. You need just to define different outputs.\n", - "\n", - "2. Construct a neural network with only one hidden layer and two hidden nodes using the Sigmoid function as activation function.\n", - "\n", - "3. Set up the output layer with only one output node and use again the Sigmoid function as activation function for the output.\n", - "\n", - "4. Initialize the weights and biases and perform a feed forward pass and compare the outputs with the targets.\n", - "\n", - "5. Set up the cost function (cross entropy for classification of binary cases).\n", - "\n", - "6. Calculate the gradients needed for the back propagation part.\n", - "\n", - "7. Use the gradients to train the network in the back propagation part. Think of using automatic differentiation.\n", - "\n", - "8. Train the network and study your results and compare with results obtained either with **scikit-learn** or **TensorFlow**.\n", - "\n", - "Everything you develop here can be used directly into the code for the project." - ] - }, - { - "cell_type": "markdown", - "id": "8e6565f3", - "metadata": { - "editable": true - }, - "source": [ - "## Setting up dimensionalities by hand\n", - "\n", - "It can be useful to test the dimensionalities for the network. Let us assume we have performed an optimization for XOR gate and found that the weights for the hidden layer are given by" - ] - }, - { - "cell_type": "markdown", - "id": "7f55beb5", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\boldsymbol{W_h}=\\begin{bmatrix} 1 & 1 \\\\\n", - " 1 & 1 \\end{bmatrix},\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "ba515e4f", - "metadata": { - "editable": true - }, - "source": [ - "Multiplying $\\boldsymbol{X}$ and $\\boldsymbol{W}$ gives" - ] - }, - { - "cell_type": "markdown", - "id": "1007d026", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\boldsymbol{X}{W}_h=\\begin{bmatrix} 0 & 0 \\\\\n", - " 1 & 1 \\\\\n", - "\t\t 1 & 1 \\\\\n", - "\t\t 2 & 2 \\end{bmatrix},\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "b1ee686a", - "metadata": { - "editable": true - }, - "source": [ - "Assume also that the bias vector for the hidden layer is" - ] - }, - { - "cell_type": "markdown", - "id": "2820cfdd", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\boldsymbol{b}_h=\\begin{bmatrix} 0 \\\\\n", - " -1\\end{bmatrix},\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "5b5f6d64", - "metadata": { - "editable": true - }, - "source": [ - "Adding it gives us the input to the activation function of the hidden layer" - ] - }, - { - "cell_type": "markdown", - "id": "0814e6d9", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\boldsymbol{z}_h=\\boldsymbol{X}\\boldsymbol{W}_h+\\boldsymbol{b}_h=\\begin{bmatrix} 0 & -1 \\\\\n", - " 1 & 0 \\\\\n", - "\t\t 1 & 0 \\\\\n", - "\t\t 2 & 1 \\end{bmatrix},\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "9da10b99", - "metadata": { - "editable": true - }, - "source": [ - "Let us then assume that our activation function is the RELU function, which simply means that we take the max of $0$ and the elements of the input argument $\\boldsymbol{z}_h$, that is we have" - ] - }, - { - "cell_type": "markdown", - "id": "c0f3ede6", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\boldsymbol{a}_h=\\mathrm{RELU}(\\boldsymbol{z}_h=\\boldsymbol{X}\\boldsymbol{W}_h+\\boldsymbol{b}_h)=\\begin{bmatrix} 0 & 0 \\\\\n", - " 1 & 0 \\\\\n", - "\t\t 1 & 0 \\\\\n", - "\t\t 2 & 1 \\end{bmatrix},\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "f00bc3ad", - "metadata": { - "editable": true - }, - "source": [ - "Assume also that the bias of the output layer is zero and that the weights of the output layer are" - ] - }, - { - "cell_type": "markdown", - "id": "da749419", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\boldsymbol{w}_o=\\begin{bmatrix} 1 \\\\\n", - " -2\\end{bmatrix},\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "2e9135f9", - "metadata": { - "editable": true - }, - "source": [ - "and multiplying with $\\boldsymbol{a}_h$ gives the output" - ] - }, - { - "cell_type": "markdown", - "id": "a0d879df", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\boldsymbol{a}_o=\\begin{bmatrix} 0 & 0 \\\\\n", - " 1 & 0 \\\\\n", - "\t\t 1 & 0 \\\\\n", - "\t\t 2 & 1 \\end{bmatrix}\\begin{bmatrix} 1 \\\\\n", - " -2\\end{bmatrix}=\\begin{bmatrix} 0 \\\\ 1 \\\\ 1 \\\\0\\end{bmatrix},\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "988a9a20", - "metadata": { - "editable": true - }, - "source": [ - "the wanted result. Pay attention to the dimensionalities as well." - ] - }, - { - "cell_type": "markdown", - "id": "354ad4af", - "metadata": { - "editable": true - }, - "source": [ - "## Setting up the Neural Network\n", - "\n", - "We define first our design matrix and the various output vectors for the different gates." - ] - }, - { - "cell_type": "code", - "execution_count": 1, - "id": "1f04aac4", - "metadata": { - "collapsed": false, - "editable": true - }, - "outputs": [], - "source": [ - "%matplotlib inline\n", - "\n", - "\"\"\"\n", - "Simple code that tests XOR, OR and AND gates with linear regression\n", - "\"\"\"\n", - "\n", - "# import necessary packages\n", - "import numpy as np\n", - "import matplotlib.pyplot as plt\n", - "from sklearn import datasets\n", - "\n", - "def sigmoid(x):\n", - " return 1/(1 + np.exp(-x))\n", - "\n", - "def feed_forward(X):\n", - " # weighted sum of inputs to the hidden layer\n", - " z_h = np.matmul(X, hidden_weights) + hidden_bias\n", - " # activation in the hidden layer\n", - " a_h = sigmoid(z_h)\n", - " \n", - " # weighted sum of inputs to the output layer\n", - " z_o = np.matmul(a_h, output_weights) + output_bias\n", - " # softmax output\n", - " # axis 0 holds each input and axis 1 the probabilities of each category\n", - " probabilities = sigmoid(z_o)\n", - " return probabilities\n", - "\n", - "\n", - "# ensure the same random numbers appear every time\n", - "np.random.seed(0)\n", - "\n", - "# Design matrix\n", - "X = np.array([ [0, 0], [0, 1], [1, 0],[1, 1]],dtype=np.float64)\n", - "\n", - "# The XOR gate\n", - "yXOR = np.array( [ 0, 1 ,1, 0])\n", - "# The OR gate\n", - "yOR = np.array( [ 0, 1 ,1, 1])\n", - "# The AND gate\n", - "yAND = np.array( [ 0, 0 ,0, 1])\n", - "\n", - "# Defining the neural network\n", - "n_inputs, n_features = X.shape\n", - "n_hidden_neurons = 2\n", - "n_categories = 1\n", - "n_features = 2\n", - "\n", - "# we make the weights normally distributed using numpy.random.randn\n", - "\n", - "# weights and bias in the hidden layer\n", - "hidden_weights = np.random.randn(n_features, n_hidden_neurons)\n", - "hidden_bias = np.zeros(n_hidden_neurons) + 0.01\n", - "\n", - "# weights and bias in the output layer\n", - "output_weights = np.random.randn(n_hidden_neurons, n_categories)\n", - "output_bias = np.zeros(n_categories) + 0.01\n", - "\n", - "probabilities = feed_forward(X)\n", - "print(probabilities)" - ] - }, - { - "cell_type": "markdown", - "id": "6e12253c", - "metadata": { - "editable": true - }, - "source": [ - "Not an impressive result, but this was our first forward pass with randomly assigned weights. Let us now add the full network with the back-propagation algorithm discussed above." - ] - }, - { - "cell_type": "markdown", - "id": "4ca80040", - "metadata": { - "editable": true - }, - "source": [ - "## The Code using Scikit-Learn" - ] - }, - { - "cell_type": "code", - "execution_count": 2, - "id": "1b657a96", - "metadata": { - "collapsed": false, - "editable": true - }, - "outputs": [], - "source": [ - "# import necessary packages\n", - "import numpy as np\n", - "import matplotlib.pyplot as plt\n", - "from sklearn.neural_network import MLPClassifier\n", - "from sklearn.metrics import accuracy_score\n", - "import seaborn as sns\n", - "\n", - "# ensure the same random numbers appear every time\n", - "np.random.seed(0)\n", - "\n", - "# Design matrix\n", - "X = np.array([ [0, 0], [0, 1], [1, 0],[1, 1]],dtype=np.float64)\n", - "\n", - "# The XOR gate\n", - "yXOR = np.array( [ 0, 1 ,1, 0])\n", - "# The OR gate\n", - "yOR = np.array( [ 0, 1 ,1, 1])\n", - "# The AND gate\n", - "yAND = np.array( [ 0, 0 ,0, 1])\n", - "\n", - "# Defining the neural network\n", - "n_hidden_neurons = 2\n", - "\n", - "eta_vals = np.logspace(-5, 1, 7)\n", - "lmbd_vals = np.logspace(-5, 1, 7)\n", - "# store models for later use\n", - "DNN_scikit = np.zeros((len(eta_vals), len(lmbd_vals)), dtype=object)\n", - "epochs = 100\n", - "\n", - "for i, eta in enumerate(eta_vals):\n", - " for j, lmbd in enumerate(lmbd_vals):\n", - " dnn = MLPClassifier(hidden_layer_sizes=(n_hidden_neurons), activation='logistic',\n", - " alpha=lmbd, learning_rate_init=eta, max_iter=epochs)\n", - " dnn.fit(X, yXOR)\n", - " DNN_scikit[i][j] = dnn\n", - " print(\"Learning rate = \", eta)\n", - " print(\"Lambda = \", lmbd)\n", - " print(\"Accuracy score on data set: \", dnn.score(X, yXOR))\n", - " print()\n", - "\n", - "sns.set()\n", - "test_accuracy = np.zeros((len(eta_vals), len(lmbd_vals)))\n", - "for i in range(len(eta_vals)):\n", - " for j in range(len(lmbd_vals)):\n", - " dnn = DNN_scikit[i][j]\n", - " test_pred = dnn.predict(X)\n", - " test_accuracy[i][j] = accuracy_score(yXOR, test_pred)\n", - "\n", - "fig, ax = plt.subplots(figsize = (10, 10))\n", - "sns.heatmap(test_accuracy, annot=True, ax=ax, cmap=\"viridis\")\n", - "ax.set_title(\"Test Accuracy\")\n", - "ax.set_ylabel(\"$\\eta$\")\n", - "ax.set_xlabel(\"$\\lambda$\")\n", - "plt.show()" - ] - }, - { - "cell_type": "markdown", - "id": "9f870fcf", - "metadata": { - "editable": true - }, - "source": [ - "## Building a neural network code\n", - "\n", - "Here we present a flexible object oriented codebase\n", - "for a feed forward neural network, along with a demonstration of how\n", - "to use it. Before we get into the details of the neural network, we\n", - "will first present some implementations of various schedulers, cost\n", - "functions and activation functions that can be used together with the\n", - "neural network.\n", - "\n", - "The codes here were developed by Eric Reber and Gregor Kajda during spring 2023." - ] - }, - { - "cell_type": "markdown", - "id": "75623483", - "metadata": { - "editable": true - }, - "source": [ - "### Learning rate methods\n", - "\n", - "The code below shows object oriented implementations of the Constant,\n", - "Momentum, Adagrad, AdagradMomentum, RMS prop and Adam schedulers. All\n", - "of the classes belong to the shared abstract Scheduler class, and\n", - "share the update_change() and reset() methods allowing for any of the\n", - "schedulers to be seamlessly used during the training stage, as will\n", - "later be shown in the fit() method of the neural\n", - "network. Update_change() only has one parameter, the gradient\n", - "($δ^l_ja^{l−1}_k$), and returns the change which will be subtracted\n", - "from the weights. The reset() function takes no parameters, and resets\n", - "the desired variables. For Constant and Momentum, reset does nothing." - ] - }, - { - "cell_type": "code", - "execution_count": 3, - "id": "7884cf44", - "metadata": { - "collapsed": false, - "editable": true - }, - "outputs": [], - "source": [ - "import autograd.numpy as np\n", - "\n", - "class Scheduler:\n", - " \"\"\"\n", - " Abstract class for Schedulers\n", - " \"\"\"\n", - "\n", - " def __init__(self, eta):\n", - " self.eta = eta\n", - "\n", - " # should be overwritten\n", - " def update_change(self, gradient):\n", - " raise NotImplementedError\n", - "\n", - " # overwritten if needed\n", - " def reset(self):\n", - " pass\n", - "\n", - "\n", - "class Constant(Scheduler):\n", - " def __init__(self, eta):\n", - " super().__init__(eta)\n", - "\n", - " def update_change(self, gradient):\n", - " return self.eta * gradient\n", - " \n", - " def reset(self):\n", - " pass\n", - "\n", - "\n", - "class Momentum(Scheduler):\n", - " def __init__(self, eta: float, momentum: float):\n", - " super().__init__(eta)\n", - " self.momentum = momentum\n", - " self.change = 0\n", - "\n", - " def update_change(self, gradient):\n", - " self.change = self.momentum * self.change + self.eta * gradient\n", - " return self.change\n", - "\n", - " def reset(self):\n", - " pass\n", - "\n", - "\n", - "class Adagrad(Scheduler):\n", - " def __init__(self, eta):\n", - " super().__init__(eta)\n", - " self.G_t = None\n", - "\n", - " def update_change(self, gradient):\n", - " delta = 1e-8 # avoid division ny zero\n", - "\n", - " if self.G_t is None:\n", - " self.G_t = np.zeros((gradient.shape[0], gradient.shape[0]))\n", - "\n", - " self.G_t += gradient @ gradient.T\n", - "\n", - " G_t_inverse = 1 / (\n", - " delta + np.sqrt(np.reshape(np.diagonal(self.G_t), (self.G_t.shape[0], 1)))\n", - " )\n", - " return self.eta * gradient * G_t_inverse\n", - "\n", - " def reset(self):\n", - " self.G_t = None\n", - "\n", - "\n", - "class AdagradMomentum(Scheduler):\n", - " def __init__(self, eta, momentum):\n", - " super().__init__(eta)\n", - " self.G_t = None\n", - " self.momentum = momentum\n", - " self.change = 0\n", - "\n", - " def update_change(self, gradient):\n", - " delta = 1e-8 # avoid division ny zero\n", - "\n", - " if self.G_t is None:\n", - " self.G_t = np.zeros((gradient.shape[0], gradient.shape[0]))\n", - "\n", - " self.G_t += gradient @ gradient.T\n", - "\n", - " G_t_inverse = 1 / (\n", - " delta + np.sqrt(np.reshape(np.diagonal(self.G_t), (self.G_t.shape[0], 1)))\n", - " )\n", - " self.change = self.change * self.momentum + self.eta * gradient * G_t_inverse\n", - " return self.change\n", - "\n", - " def reset(self):\n", - " self.G_t = None\n", - "\n", - "\n", - "class RMS_prop(Scheduler):\n", - " def __init__(self, eta, rho):\n", - " super().__init__(eta)\n", - " self.rho = rho\n", - " self.second = 0.0\n", - "\n", - " def update_change(self, gradient):\n", - " delta = 1e-8 # avoid division ny zero\n", - " self.second = self.rho * self.second + (1 - self.rho) * gradient * gradient\n", - " return self.eta * gradient / (np.sqrt(self.second + delta))\n", - "\n", - " def reset(self):\n", - " self.second = 0.0\n", - "\n", - "\n", - "class Adam(Scheduler):\n", - " def __init__(self, eta, rho, rho2):\n", - " super().__init__(eta)\n", - " self.rho = rho\n", - " self.rho2 = rho2\n", - " self.moment = 0\n", - " self.second = 0\n", - " self.n_epochs = 1\n", - "\n", - " def update_change(self, gradient):\n", - " delta = 1e-8 # avoid division ny zero\n", - "\n", - " self.moment = self.rho * self.moment + (1 - self.rho) * gradient\n", - " self.second = self.rho2 * self.second + (1 - self.rho2) * gradient * gradient\n", - "\n", - " moment_corrected = self.moment / (1 - self.rho**self.n_epochs)\n", - " second_corrected = self.second / (1 - self.rho2**self.n_epochs)\n", - "\n", - " return self.eta * moment_corrected / (np.sqrt(second_corrected + delta))\n", - "\n", - " def reset(self):\n", - " self.n_epochs += 1\n", - " self.moment = 0\n", - " self.second = 0" - ] - }, - { - "cell_type": "markdown", - "id": "a9747db3", - "metadata": { - "editable": true - }, - "source": [ - "### Usage of the above learning rate schedulers\n", - "\n", - "To initalize a scheduler, simply create the object and pass in the\n", - "necessary parameters such as the learning rate and the momentum as\n", - "shown below. As the Scheduler class is an abstract class it should not\n", - "called directly, and will raise an error upon usage." - ] - }, - { - "cell_type": "code", - "execution_count": 4, - "id": "b394ebc2", - "metadata": { - "collapsed": false, - "editable": true - }, - "outputs": [], - "source": [ - "momentum_scheduler = Momentum(eta=1e-3, momentum=0.9)\n", - "adam_scheduler = Adam(eta=1e-3, rho=0.9, rho2=0.999)" - ] - }, - { - "cell_type": "markdown", - "id": "734ce228", - "metadata": { - "editable": true - }, - "source": [ - "Here is a small example for how a segment of code using schedulers\n", - "could look. Switching out the schedulers is simple." - ] - }, - { - "cell_type": "code", - "execution_count": 5, - "id": "51396f90", - "metadata": { - "collapsed": false, - "editable": true - }, - "outputs": [], - "source": [ - "weights = np.ones((3,3))\n", - "print(f\"Before scheduler:\\n{weights=}\")\n", - "\n", - "epochs = 10\n", - "for e in range(epochs):\n", - " gradient = np.random.rand(3, 3)\n", - " change = adam_scheduler.update_change(gradient)\n", - " weights = weights - change\n", - " adam_scheduler.reset()\n", - "\n", - "print(f\"\\nAfter scheduler:\\n{weights=}\")" - ] - }, - { - "cell_type": "markdown", - "id": "44646fc6", - "metadata": { - "editable": true - }, - "source": [ - "### Cost functions\n", - "\n", - "Here we discuss cost functions that can be used when creating the\n", - "neural network. Every cost function takes the target vector as its\n", - "parameter, and returns a function valued only at $x$ such that it may\n", - "easily be differentiated." - ] - }, - { - "cell_type": "code", - "execution_count": 6, - "id": "912285f7", - "metadata": { - "collapsed": false, - "editable": true - }, - "outputs": [], - "source": [ - "import autograd.numpy as np\n", - "\n", - "def CostOLS(target):\n", - " \n", - " def func(X):\n", - " return (1.0 / target.shape[0]) * np.sum((target - X) ** 2)\n", - "\n", - " return func\n", - "\n", - "\n", - "def CostLogReg(target):\n", - "\n", - " def func(X):\n", - " \n", - " return -(1.0 / target.shape[0]) * np.sum(\n", - " (target * np.log(X + 10e-10)) + ((1 - target) * np.log(1 - X + 10e-10))\n", - " )\n", - "\n", - " return func\n", - "\n", - "\n", - "def CostCrossEntropy(target):\n", - " \n", - " def func(X):\n", - " return -(1.0 / target.size) * np.sum(target * np.log(X + 10e-10))\n", - "\n", - " return func" - ] - }, - { - "cell_type": "markdown", - "id": "9297b955", - "metadata": { - "editable": true - }, - "source": [ - "Below we give a short example of how these cost function may be used\n", - "to obtain results if you wish to test them out on your own using\n", - "AutoGrad's automatics differentiation." - ] - }, - { - "cell_type": "code", - "execution_count": 7, - "id": "39943643", - "metadata": { - "collapsed": false, - "editable": true - }, - "outputs": [], - "source": [ - "from autograd import grad\n", - "\n", - "target = np.array([[1, 2, 3]]).T\n", - "a = np.array([[4, 5, 6]]).T\n", - "\n", - "cost_func = CostCrossEntropy\n", - "cost_func_derivative = grad(cost_func(target))\n", - "\n", - "valued_at_a = cost_func_derivative(a)\n", - "print(f\"Derivative of cost function {cost_func.__name__} valued at a:\\n{valued_at_a}\")" - ] - }, - { - "cell_type": "markdown", - "id": "53f4d1d2", - "metadata": { - "editable": true - }, - "source": [ - "### Activation functions\n", - "\n", - "Finally, before we look at the neural network, we will look at the\n", - "activation functions which can be specified between the hidden layers\n", - "and as the output function. Each function can be valued for any given\n", - "vector or matrix X, and can be differentiated via derivate()." - ] - }, - { - "cell_type": "code", - "execution_count": 8, - "id": "90222b1a", - "metadata": { - "collapsed": false, - "editable": true - }, - "outputs": [], - "source": [ - "import autograd.numpy as np\n", - "from autograd import elementwise_grad\n", - "\n", - "def identity(X):\n", - " return X\n", - "\n", - "\n", - "def sigmoid(X):\n", - " try:\n", - " return 1.0 / (1 + np.exp(-X))\n", - " except FloatingPointError:\n", - " return np.where(X > np.zeros(X.shape), np.ones(X.shape), np.zeros(X.shape))\n", - "\n", - "\n", - "def softmax(X):\n", - " X = X - np.max(X, axis=-1, keepdims=True)\n", - " delta = 10e-10\n", - " return np.exp(X) / (np.sum(np.exp(X), axis=-1, keepdims=True) + delta)\n", - "\n", - "\n", - "def RELU(X):\n", - " return np.where(X > np.zeros(X.shape), X, np.zeros(X.shape))\n", - "\n", - "\n", - "def LRELU(X):\n", - " delta = 10e-4\n", - " return np.where(X > np.zeros(X.shape), X, delta * X)\n", - "\n", - "\n", - "def derivate(func):\n", - " if func.__name__ == \"RELU\":\n", - "\n", - " def func(X):\n", - " return np.where(X > 0, 1, 0)\n", - "\n", - " return func\n", - "\n", - " elif func.__name__ == \"LRELU\":\n", - "\n", - " def func(X):\n", - " delta = 10e-4\n", - " return np.where(X > 0, 1, delta)\n", - "\n", - " return func\n", - "\n", - " else:\n", - " return elementwise_grad(func)" - ] - }, - { - "cell_type": "markdown", - "id": "f3dd3611", - "metadata": { - "editable": true - }, - "source": [ - "Below follows a short demonstration of how to use an activation\n", - "function. The derivative of the activation function will be important\n", - "when calculating the output delta term during backpropagation. Note\n", - "that derivate() can also be used for cost functions for a more\n", - "generalized approach." - ] - }, - { - "cell_type": "code", - "execution_count": 9, - "id": "ded43dca", - "metadata": { - "collapsed": false, - "editable": true - }, - "outputs": [], - "source": [ - "z = np.array([[4, 5, 6]]).T\n", - "print(f\"Input to activation function:\\n{z}\")\n", - "\n", - "act_func = sigmoid\n", - "a = act_func(z)\n", - "print(f\"\\nOutput from {act_func.__name__} activation function:\\n{a}\")\n", - "\n", - "act_func_derivative = derivate(act_func)\n", - "valued_at_z = act_func_derivative(a)\n", - "print(f\"\\nDerivative of {act_func.__name__} activation function valued at z:\\n{valued_at_z}\")" - ] - }, - { - "cell_type": "markdown", - "id": "771c53a1", - "metadata": { - "editable": true - }, - "source": [ - "### The Neural Network\n", - "\n", - "Now that we have gotten a good understanding of the implementation of\n", - "some important components, we can take a look at an object oriented\n", - "implementation of a feed forward neural network. The feed forward\n", - "neural network has been implemented as a class named FFNN, which can\n", - "be initiated as a regressor or classifier dependant on the choice of\n", - "cost function. The FFNN can have any number of input nodes, hidden\n", - "layers with any amount of hidden nodes, and any amount of output nodes\n", - "meaning it can perform multiclass classification as well as binary\n", - "classification and regression problems. Although there is a lot of\n", - "code present, it makes for an easy to use and generalizeable interface\n", - "for creating many types of neural networks as will be demonstrated\n", - "below." - ] - }, - { - "cell_type": "code", - "execution_count": 10, - "id": "56ef870b", - "metadata": { - "collapsed": false, - "editable": true - }, - "outputs": [], - "source": [ - "import math\n", - "import autograd.numpy as np\n", - "import sys\n", - "import warnings\n", - "from autograd import grad, elementwise_grad\n", - "from random import random, seed\n", - "from copy import deepcopy, copy\n", - "from typing import Tuple, Callable\n", - "from sklearn.utils import resample\n", - "\n", - "warnings.simplefilter(\"error\")\n", - "\n", - "\n", - "class FFNN:\n", - " \"\"\"\n", - " Description:\n", - " ------------\n", - " Feed Forward Neural Network with interface enabling flexible design of a\n", - " nerual networks architecture and the specification of activation function\n", - " in the hidden layers and output layer respectively. This model can be used\n", - " for both regression and classification problems, depending on the output function.\n", - "\n", - " Attributes:\n", - " ------------\n", - " I dimensions (tuple[int]): A list of positive integers, which specifies the\n", - " number of nodes in each of the networks layers. The first integer in the array\n", - " defines the number of nodes in the input layer, the second integer defines number\n", - " of nodes in the first hidden layer and so on until the last number, which\n", - " specifies the number of nodes in the output layer.\n", - " II hidden_func (Callable): The activation function for the hidden layers\n", - " III output_func (Callable): The activation function for the output layer\n", - " IV cost_func (Callable): Our cost function\n", - " V seed (int): Sets random seed, makes results reproducible\n", - " \"\"\"\n", - "\n", - " def __init__(\n", - " self,\n", - " dimensions: tuple[int],\n", - " hidden_func: Callable = sigmoid,\n", - " output_func: Callable = lambda x: x,\n", - " cost_func: Callable = CostOLS,\n", - " seed: int = None,\n", - " ):\n", - " self.dimensions = dimensions\n", - " self.hidden_func = hidden_func\n", - " self.output_func = output_func\n", - " self.cost_func = cost_func\n", - " self.seed = seed\n", - " self.weights = list()\n", - " self.schedulers_weight = list()\n", - " self.schedulers_bias = list()\n", - " self.a_matrices = list()\n", - " self.z_matrices = list()\n", - " self.classification = None\n", - "\n", - " self.reset_weights()\n", - " self._set_classification()\n", - "\n", - " def fit(\n", - " self,\n", - " X: np.ndarray,\n", - " t: np.ndarray,\n", - " scheduler: Scheduler,\n", - " batches: int = 1,\n", - " epochs: int = 100,\n", - " lam: float = 0,\n", - " X_val: np.ndarray = None,\n", - " t_val: np.ndarray = None,\n", - " ):\n", - " \"\"\"\n", - " Description:\n", - " ------------\n", - " This function performs the training the neural network by performing the feedforward and backpropagation\n", - " algorithm to update the networks weights.\n", - "\n", - " Parameters:\n", - " ------------\n", - " I X (np.ndarray) : training data\n", - " II t (np.ndarray) : target data\n", - " III scheduler (Scheduler) : specified scheduler (algorithm for optimization of gradient descent)\n", - " IV scheduler_args (list[int]) : list of all arguments necessary for scheduler\n", - "\n", - " Optional Parameters:\n", - " ------------\n", - " V batches (int) : number of batches the datasets are split into, default equal to 1\n", - " VI epochs (int) : number of iterations used to train the network, default equal to 100\n", - " VII lam (float) : regularization hyperparameter lambda\n", - " VIII X_val (np.ndarray) : validation set\n", - " IX t_val (np.ndarray) : validation target set\n", - "\n", - " Returns:\n", - " ------------\n", - " I scores (dict) : A dictionary containing the performance metrics of the model.\n", - " The number of the metrics depends on the parameters passed to the fit-function.\n", - "\n", - " \"\"\"\n", - "\n", - " # setup \n", - " if self.seed is not None:\n", - " np.random.seed(self.seed)\n", - "\n", - " val_set = False\n", - " if X_val is not None and t_val is not None:\n", - " val_set = True\n", - "\n", - " # creating arrays for score metrics\n", - " train_errors = np.empty(epochs)\n", - " train_errors.fill(np.nan)\n", - " val_errors = np.empty(epochs)\n", - " val_errors.fill(np.nan)\n", - "\n", - " train_accs = np.empty(epochs)\n", - " train_accs.fill(np.nan)\n", - " val_accs = np.empty(epochs)\n", - " val_accs.fill(np.nan)\n", - "\n", - " self.schedulers_weight = list()\n", - " self.schedulers_bias = list()\n", - "\n", - " batch_size = X.shape[0] // batches\n", - "\n", - " X, t = resample(X, t)\n", - "\n", - " # this function returns a function valued only at X\n", - " cost_function_train = self.cost_func(t)\n", - " if val_set:\n", - " cost_function_val = self.cost_func(t_val)\n", - "\n", - " # create schedulers for each weight matrix\n", - " for i in range(len(self.weights)):\n", - " self.schedulers_weight.append(copy(scheduler))\n", - " self.schedulers_bias.append(copy(scheduler))\n", - "\n", - " print(f\"{scheduler.__class__.__name__}: Eta={scheduler.eta}, Lambda={lam}\")\n", - "\n", - " try:\n", - " for e in range(epochs):\n", - " for i in range(batches):\n", - " # allows for minibatch gradient descent\n", - " if i == batches - 1:\n", - " # If the for loop has reached the last batch, take all thats left\n", - " X_batch = X[i * batch_size :, :]\n", - " t_batch = t[i * batch_size :, :]\n", - " else:\n", - " X_batch = X[i * batch_size : (i + 1) * batch_size, :]\n", - " t_batch = t[i * batch_size : (i + 1) * batch_size, :]\n", - "\n", - " self._feedforward(X_batch)\n", - " self._backpropagate(X_batch, t_batch, lam)\n", - "\n", - " # reset schedulers for each epoch (some schedulers pass in this call)\n", - " for scheduler in self.schedulers_weight:\n", - " scheduler.reset()\n", - "\n", - " for scheduler in self.schedulers_bias:\n", - " scheduler.reset()\n", - "\n", - " # computing performance metrics\n", - " pred_train = self.predict(X)\n", - " train_error = cost_function_train(pred_train)\n", - "\n", - " train_errors[e] = train_error\n", - " if val_set:\n", - " \n", - " pred_val = self.predict(X_val)\n", - " val_error = cost_function_val(pred_val)\n", - " val_errors[e] = val_error\n", - "\n", - " if self.classification:\n", - " train_acc = self._accuracy(self.predict(X), t)\n", - " train_accs[e] = train_acc\n", - " if val_set:\n", - " val_acc = self._accuracy(pred_val, t_val)\n", - " val_accs[e] = val_acc\n", - "\n", - " # printing progress bar\n", - " progression = e / epochs\n", - " print_length = self._progress_bar(\n", - " progression,\n", - " train_error=train_errors[e],\n", - " train_acc=train_accs[e],\n", - " val_error=val_errors[e],\n", - " val_acc=val_accs[e],\n", - " )\n", - " except KeyboardInterrupt:\n", - " # allows for stopping training at any point and seeing the result\n", - " pass\n", - "\n", - " # visualization of training progression (similiar to tensorflow progression bar)\n", - " sys.stdout.write(\"\\r\" + \" \" * print_length)\n", - " sys.stdout.flush()\n", - " self._progress_bar(\n", - " 1,\n", - " train_error=train_errors[e],\n", - " train_acc=train_accs[e],\n", - " val_error=val_errors[e],\n", - " val_acc=val_accs[e],\n", - " )\n", - " sys.stdout.write(\"\")\n", - "\n", - " # return performance metrics for the entire run\n", - " scores = dict()\n", - "\n", - " scores[\"train_errors\"] = train_errors\n", - "\n", - " if val_set:\n", - " scores[\"val_errors\"] = val_errors\n", - "\n", - " if self.classification:\n", - " scores[\"train_accs\"] = train_accs\n", - "\n", - " if val_set:\n", - " scores[\"val_accs\"] = val_accs\n", - "\n", - " return scores\n", - "\n", - " def predict(self, X: np.ndarray, *, threshold=0.5):\n", - " \"\"\"\n", - " Description:\n", - " ------------\n", - " Performs prediction after training of the network has been finished.\n", - "\n", - " Parameters:\n", - " ------------\n", - " I X (np.ndarray): The design matrix, with n rows of p features each\n", - "\n", - " Optional Parameters:\n", - " ------------\n", - " II threshold (float) : sets minimal value for a prediction to be predicted as the positive class\n", - " in classification problems\n", - "\n", - " Returns:\n", - " ------------\n", - " I z (np.ndarray): A prediction vector (row) for each row in our design matrix\n", - " This vector is thresholded if regression=False, meaning that classification results\n", - " in a vector of 1s and 0s, while regressions in an array of decimal numbers\n", - "\n", - " \"\"\"\n", - "\n", - " predict = self._feedforward(X)\n", - "\n", - " if self.classification:\n", - " return np.where(predict > threshold, 1, 0)\n", - " else:\n", - " return predict\n", - "\n", - " def reset_weights(self):\n", - " \"\"\"\n", - " Description:\n", - " ------------\n", - " Resets/Reinitializes the weights in order to train the network for a new problem.\n", - "\n", - " \"\"\"\n", - " if self.seed is not None:\n", - " np.random.seed(self.seed)\n", - "\n", - " self.weights = list()\n", - " for i in range(len(self.dimensions) - 1):\n", - " weight_array = np.random.randn(\n", - " self.dimensions[i] + 1, self.dimensions[i + 1]\n", - " )\n", - " weight_array[0, :] = np.random.randn(self.dimensions[i + 1]) * 0.01\n", - "\n", - " self.weights.append(weight_array)\n", - "\n", - " def _feedforward(self, X: np.ndarray):\n", - " \"\"\"\n", - " Description:\n", - " ------------\n", - " Calculates the activation of each layer starting at the input and ending at the output.\n", - " Each following activation is calculated from a weighted sum of each of the preceeding\n", - " activations (except in the case of the input layer).\n", - "\n", - " Parameters:\n", - " ------------\n", - " I X (np.ndarray): The design matrix, with n rows of p features each\n", - "\n", - " Returns:\n", - " ------------\n", - " I z (np.ndarray): A prediction vector (row) for each row in our design matrix\n", - " \"\"\"\n", - "\n", - " # reset matrices\n", - " self.a_matrices = list()\n", - " self.z_matrices = list()\n", - "\n", - " # if X is just a vector, make it into a matrix\n", - " if len(X.shape) == 1:\n", - " X = X.reshape((1, X.shape[0]))\n", - "\n", - " # Add a coloumn of zeros as the first coloumn of the design matrix, in order\n", - " # to add bias to our data\n", - " bias = np.ones((X.shape[0], 1)) * 0.01\n", - " X = np.hstack([bias, X])\n", - "\n", - " # a^0, the nodes in the input layer (one a^0 for each row in X - where the\n", - " # exponent indicates layer number).\n", - " a = X\n", - " self.a_matrices.append(a)\n", - " self.z_matrices.append(a)\n", - "\n", - " # The feed forward algorithm\n", - " for i in range(len(self.weights)):\n", - " if i < len(self.weights) - 1:\n", - " z = a @ self.weights[i]\n", - " self.z_matrices.append(z)\n", - " a = self.hidden_func(z)\n", - " # bias column again added to the data here\n", - " bias = np.ones((a.shape[0], 1)) * 0.01\n", - " a = np.hstack([bias, a])\n", - " self.a_matrices.append(a)\n", - " else:\n", - " try:\n", - " # a^L, the nodes in our output layers\n", - " z = a @ self.weights[i]\n", - " a = self.output_func(z)\n", - " self.a_matrices.append(a)\n", - " self.z_matrices.append(z)\n", - " except Exception as OverflowError:\n", - " print(\n", - " \"OverflowError in fit() in FFNN\\nHOW TO DEBUG ERROR: Consider lowering your learning rate or scheduler specific parameters such as momentum, or check if your input values need scaling\"\n", - " )\n", - "\n", - " # this will be a^L\n", - " return a\n", - "\n", - " def _backpropagate(self, X, t, lam):\n", - " \"\"\"\n", - " Description:\n", - " ------------\n", - " Performs the backpropagation algorithm. In other words, this method\n", - " calculates the gradient of all the layers starting at the\n", - " output layer, and moving from right to left accumulates the gradient until\n", - " the input layer is reached. Each layers respective weights are updated while\n", - " the algorithm propagates backwards from the output layer (auto-differentation in reverse mode).\n", - "\n", - " Parameters:\n", - " ------------\n", - " I X (np.ndarray): The design matrix, with n rows of p features each.\n", - " II t (np.ndarray): The target vector, with n rows of p targets.\n", - " III lam (float32): regularization parameter used to punish the weights in case of overfitting\n", - "\n", - " Returns:\n", - " ------------\n", - " No return value.\n", - "\n", - " \"\"\"\n", - " out_derivative = derivate(self.output_func)\n", - " hidden_derivative = derivate(self.hidden_func)\n", - "\n", - " for i in range(len(self.weights) - 1, -1, -1):\n", - " # delta terms for output\n", - " if i == len(self.weights) - 1:\n", - " # for multi-class classification\n", - " if (\n", - " self.output_func.__name__ == \"softmax\"\n", - " ):\n", - " delta_matrix = self.a_matrices[i + 1] - t\n", - " # for single class classification\n", - " else:\n", - " cost_func_derivative = grad(self.cost_func(t))\n", - " delta_matrix = out_derivative(\n", - " self.z_matrices[i + 1]\n", - " ) * cost_func_derivative(self.a_matrices[i + 1])\n", - "\n", - " # delta terms for hidden layer\n", - " else:\n", - " delta_matrix = (\n", - " self.weights[i + 1][1:, :] @ delta_matrix.T\n", - " ).T * hidden_derivative(self.z_matrices[i + 1])\n", - "\n", - " # calculate gradient\n", - " gradient_weights = self.a_matrices[i][:, 1:].T @ delta_matrix\n", - " gradient_bias = np.sum(delta_matrix, axis=0).reshape(\n", - " 1, delta_matrix.shape[1]\n", - " )\n", - "\n", - " # regularization term\n", - " gradient_weights += self.weights[i][1:, :] * lam\n", - "\n", - " # use scheduler\n", - " update_matrix = np.vstack(\n", - " [\n", - " self.schedulers_bias[i].update_change(gradient_bias),\n", - " self.schedulers_weight[i].update_change(gradient_weights),\n", - " ]\n", - " )\n", - "\n", - " # update weights and bias\n", - " self.weights[i] -= update_matrix\n", - "\n", - " def _accuracy(self, prediction: np.ndarray, target: np.ndarray):\n", - " \"\"\"\n", - " Description:\n", - " ------------\n", - " Calculates accuracy of given prediction to target\n", - "\n", - " Parameters:\n", - " ------------\n", - " I prediction (np.ndarray): vector of predicitons output network\n", - " (1s and 0s in case of classification, and real numbers in case of regression)\n", - " II target (np.ndarray): vector of true values (What the network ideally should predict)\n", - "\n", - " Returns:\n", - " ------------\n", - " A floating point number representing the percentage of correctly classified instances.\n", - " \"\"\"\n", - " assert prediction.size == target.size\n", - " return np.average((target == prediction))\n", - " def _set_classification(self):\n", - " \"\"\"\n", - " Description:\n", - " ------------\n", - " Decides if FFNN acts as classifier (True) og regressor (False),\n", - " sets self.classification during init()\n", - " \"\"\"\n", - " self.classification = False\n", - " if (\n", - " self.cost_func.__name__ == \"CostLogReg\"\n", - " or self.cost_func.__name__ == \"CostCrossEntropy\"\n", - " ):\n", - " self.classification = True\n", - "\n", - " def _progress_bar(self, progression, **kwargs):\n", - " \"\"\"\n", - " Description:\n", - " ------------\n", - " Displays progress of training\n", - " \"\"\"\n", - " print_length = 40\n", - " num_equals = int(progression * print_length)\n", - " num_not = print_length - num_equals\n", - " arrow = \">\" if num_equals > 0 else \"\"\n", - " bar = \"[\" + \"=\" * (num_equals - 1) + arrow + \"-\" * num_not + \"]\"\n", - " perc_print = self._format(progression * 100, decimals=5)\n", - " line = f\" {bar} {perc_print}% \"\n", - "\n", - " for key in kwargs:\n", - " if not np.isnan(kwargs[key]):\n", - " value = self._format(kwargs[key], decimals=4)\n", - " line += f\"| {key}: {value} \"\n", - " sys.stdout.write(\"\\r\" + line)\n", - " sys.stdout.flush()\n", - " return len(line)\n", - "\n", - " def _format(self, value, decimals=4):\n", - " \"\"\"\n", - " Description:\n", - " ------------\n", - " Formats decimal numbers for progress bar\n", - " \"\"\"\n", - " if value > 0:\n", - " v = value\n", - " elif value < 0:\n", - " v = -10 * value\n", - " else:\n", - " v = 1\n", - " n = 1 + math.floor(math.log10(v))\n", - " if n >= decimals - 1:\n", - " return str(round(value))\n", - " return f\"{value:.{decimals-n-1}f}\"" - ] - }, - { - "cell_type": "markdown", - "id": "cefab2ac", - "metadata": { - "editable": true - }, - "source": [ - "Before we make a model, we will quickly generate a dataset we can use\n", - "for our linear regression problem as shown below" - ] - }, - { - "cell_type": "code", - "execution_count": 11, - "id": "6d5b49a1", - "metadata": { - "collapsed": false, - "editable": true - }, - "outputs": [], - "source": [ - "import autograd.numpy as np\n", - "from sklearn.model_selection import train_test_split\n", - "\n", - "def SkrankeFunction(x, y):\n", - " return np.ravel(0 + 1*x + 2*y + 3*x**2 + 4*x*y + 5*y**2)\n", - "\n", - "def create_X(x, y, n):\n", - " if len(x.shape) > 1:\n", - " x = np.ravel(x)\n", - " y = np.ravel(y)\n", - "\n", - " N = len(x)\n", - " l = int((n + 1) * (n + 2) / 2) # Number of elements in beta\n", - " X = np.ones((N, l))\n", - "\n", - " for i in range(1, n + 1):\n", - " q = int((i) * (i + 1) / 2)\n", - " for k in range(i + 1):\n", - " X[:, q + k] = (x ** (i - k)) * (y**k)\n", - "\n", - " return X\n", - "\n", - "step=0.5\n", - "x = np.arange(0, 1, step)\n", - "y = np.arange(0, 1, step)\n", - "x, y = np.meshgrid(x, y)\n", - "target = SkrankeFunction(x, y)\n", - "target = target.reshape(target.shape[0], 1)\n", - "\n", - "poly_degree=3\n", - "X = create_X(x, y, poly_degree)\n", - "\n", - "X_train, X_test, t_train, t_test = train_test_split(X, target)" - ] - }, - { - "cell_type": "markdown", - "id": "f857ae2b", - "metadata": { - "editable": true - }, - "source": [ - "Now that we have our dataset ready for the regression, we can create\n", - "our regressor. Note that with the seed parameter, we can make sure our\n", - "results stay the same every time we run the neural network. For\n", - "inititialization, we simply specify the dimensions (we wish the amount\n", - "of input nodes to be equal to the datapoints, and the output to\n", - "predict one value)." - ] - }, - { - "cell_type": "code", - "execution_count": 12, - "id": "2a92f970", - "metadata": { - "collapsed": false, - "editable": true - }, - "outputs": [], - "source": [ - "input_nodes = X_train.shape[1]\n", - "output_nodes = 1\n", - "\n", - "linear_regression = FFNN((input_nodes, output_nodes), output_func=identity, cost_func=CostOLS, seed=2023)" - ] - }, - { - "cell_type": "markdown", - "id": "28236066", - "metadata": { - "editable": true - }, - "source": [ - "We then fit our model with our training data using the scheduler of our choice." - ] - }, - { - "cell_type": "code", - "execution_count": 13, - "id": "b3c6c87e", - "metadata": { - "collapsed": false, - "editable": true - }, - "outputs": [], - "source": [ - "linear_regression.reset_weights() # reset weights such that previous runs or reruns don't affect the weights\n", - "\n", - "scheduler = Constant(eta=1e-3)\n", - "scores = linear_regression.fit(X_train, t_train, scheduler)" - ] - }, - { - "cell_type": "markdown", - "id": "f5b6209f", - "metadata": { - "editable": true - }, - "source": [ - "Due to the progress bar we can see the MSE (train_error) throughout\n", - "the FFNN's training. Note that the fit() function has some optional\n", - "parameters with defualt arguments. For example, the regularization\n", - "hyperparameter can be left ignored if not needed, and equally the FFNN\n", - "will by default run for 100 epochs. These can easily be changed, such\n", - "as for example:" - ] - }, - { - "cell_type": "code", - "execution_count": 14, - "id": "59d5742b", - "metadata": { - "collapsed": false, - "editable": true - }, - "outputs": [], - "source": [ - "linear_regression.reset_weights() # reset weights such that previous runs or reruns don't affect the weights\n", - "\n", - "scores = linear_regression.fit(X_train, t_train, scheduler, lam=1e-4, epochs=1000)" - ] - }, - { - "cell_type": "markdown", - "id": "13e834ae", - "metadata": { - "editable": true - }, - "source": [ - "We see that given more epochs to train on, the regressor reaches a lower MSE.\n", - "\n", - "Let us then switch to a binary classification. We use a binary\n", - "classification dataset, and follow a similar setup to the regression\n", - "case." - ] - }, - { - "cell_type": "code", - "execution_count": 15, - "id": "ab390311", - "metadata": { - "collapsed": false, - "editable": true - }, - "outputs": [], - "source": [ - "from sklearn.datasets import load_breast_cancer\n", - "from sklearn.preprocessing import MinMaxScaler\n", - "\n", - "wisconsin = load_breast_cancer()\n", - "X = wisconsin.data\n", - "target = wisconsin.target\n", - "target = target.reshape(target.shape[0], 1)\n", - "\n", - "X_train, X_val, t_train, t_val = train_test_split(X, target)\n", - "\n", - "scaler = MinMaxScaler()\n", - "scaler.fit(X_train)\n", - "X_train = scaler.transform(X_train)\n", - "X_val = scaler.transform(X_val)" - ] - }, - { - "cell_type": "code", - "execution_count": 16, - "id": "f2d67c2e", - "metadata": { - "collapsed": false, - "editable": true - }, - "outputs": [], - "source": [ - "input_nodes = X_train.shape[1]\n", - "output_nodes = 1\n", - "\n", - "logistic_regression = FFNN((input_nodes, output_nodes), output_func=sigmoid, cost_func=CostLogReg, seed=2023)" - ] - }, - { - "cell_type": "markdown", - "id": "e350f60e", - "metadata": { - "editable": true - }, - "source": [ - "We will now make use of our validation data by passing it into our fit function as a keyword argument" - ] - }, - { - "cell_type": "code", - "execution_count": 17, - "id": "211a328d", - "metadata": { - "collapsed": false, - "editable": true - }, - "outputs": [], - "source": [ - "logistic_regression.reset_weights() # reset weights such that previous runs or reruns don't affect the weights\n", - "\n", - "scheduler = Adam(eta=1e-3, rho=0.9, rho2=0.999)\n", - "scores = logistic_regression.fit(X_train, t_train, scheduler, epochs=1000, X_val=X_val, t_val=t_val)" - ] - }, - { - "cell_type": "markdown", - "id": "8425a8fb", - "metadata": { - "editable": true - }, - "source": [ - "Finally, we will create a neural network with 2 hidden layers with activation functions." - ] - }, - { - "cell_type": "code", - "execution_count": 18, - "id": "1070e9eb", - "metadata": { - "collapsed": false, - "editable": true - }, - "outputs": [], - "source": [ - "input_nodes = X_train.shape[1]\n", - "hidden_nodes1 = 100\n", - "hidden_nodes2 = 30\n", - "output_nodes = 1\n", - "\n", - "dims = (input_nodes, hidden_nodes1, hidden_nodes2, output_nodes)\n", - "\n", - "neural_network = FFNN(dims, hidden_func=RELU, output_func=sigmoid, cost_func=CostLogReg, seed=2023)" - ] - }, - { - "cell_type": "code", - "execution_count": 19, - "id": "c7171327", - "metadata": { - "collapsed": false, - "editable": true - }, - "outputs": [], - "source": [ - "neural_network.reset_weights() # reset weights such that previous runs or reruns don't affect the weights\n", - "\n", - "scheduler = Adam(eta=1e-4, rho=0.9, rho2=0.999)\n", - "scores = neural_network.fit(X_train, t_train, scheduler, epochs=1000, X_val=X_val, t_val=t_val)" - ] - }, - { - "cell_type": "markdown", - "id": "9c37cc8a", - "metadata": { - "editable": true - }, - "source": [ - "### Multiclass classification\n", - "\n", - "Finally, we will demonstrate the use case of multiclass classification\n", - "using our FFNN with the famous MNIST dataset, which contain images of\n", - "digits between the range of 0 to 9." - ] - }, - { - "cell_type": "code", - "execution_count": 20, - "id": "f33e3872", - "metadata": { - "collapsed": false, - "editable": true - }, - "outputs": [], - "source": [ - "from sklearn.datasets import load_digits\n", - "\n", - "def onehot(target: np.ndarray):\n", - " onehot = np.zeros((target.size, target.max() + 1))\n", - " onehot[np.arange(target.size), target] = 1\n", - " return onehot\n", - "\n", - "digits = load_digits()\n", - "\n", - "X = digits.data\n", - "target = digits.target\n", - "target = onehot(target)\n", - "\n", - "input_nodes = 64\n", - "hidden_nodes1 = 100\n", - "hidden_nodes2 = 30\n", - "output_nodes = 10\n", - "\n", - "dims = (input_nodes, hidden_nodes1, hidden_nodes2, output_nodes)\n", - "\n", - "multiclass = FFNN(dims, hidden_func=LRELU, output_func=softmax, cost_func=CostCrossEntropy)\n", - "\n", - "multiclass.reset_weights() # reset weights such that previous runs or reruns don't affect the weights\n", - "\n", - "scheduler = Adam(eta=1e-4, rho=0.9, rho2=0.999)\n", - "scores = multiclass.fit(X, target, scheduler, epochs=1000)" - ] - }, - { - "cell_type": "markdown", - "id": "98281e67", - "metadata": { - "editable": true - }, - "source": [ - "## Testing the XOR gate and other gates\n", - "\n", - "Let us now use our code to test the XOR gate." - ] - }, - { - "cell_type": "code", - "execution_count": 21, - "id": "24031566", - "metadata": { - "collapsed": false, - "editable": true - }, - "outputs": [], - "source": [ - "X = np.array([ [0, 0], [0, 1], [1, 0],[1, 1]],dtype=np.float64)\n", - "\n", - "# The XOR gate\n", - "yXOR = np.array( [[ 0], [1] ,[1], [0]])\n", - "\n", - "input_nodes = X.shape[1]\n", - "output_nodes = 1\n", - "\n", - "logistic_regression = FFNN((input_nodes, output_nodes), output_func=sigmoid, cost_func=CostLogReg, seed=2023)\n", - "logistic_regression.reset_weights() # reset weights such that previous runs or reruns don't affect the weights\n", - "scheduler = Adam(eta=1e-1, rho=0.9, rho2=0.999)\n", - "scores = logistic_regression.fit(X, yXOR, scheduler, epochs=1000)" - ] - }, - { - "cell_type": "markdown", - "id": "8302830f", - "metadata": { - "editable": true - }, - "source": [ - "Not bad, but the results depend strongly on the learning reate. Try different learning rates." - ] - }, - { - "cell_type": "markdown", - "id": "9003b71a", - "metadata": { - "editable": true - }, - "source": [ - "## Lecture Thursday October 26" - ] - }, - { - "cell_type": "markdown", - "id": "4446e61e", - "metadata": { - "editable": true - }, - "source": [ - "## Developing a code for doing neural networks with back propagation\n", - "\n", - "We repeat some of the elements discussed last week. The first part of\n", - "the material for Thursday was contained in the slides for last\n", - "week as well. We will repeat some of the topics here before we move into\n", - "applications to differential equations and other examples.\n", - "\n", - "One can identify a set of key steps when using neural networks to solve supervised learning problems: \n", - "\n", - "1. Collect and pre-process data \n", - "\n", - "2. Define model and architecture \n", - "\n", - "3. Choose cost function and optimizer \n", - "\n", - "4. Train the model \n", - "\n", - "5. Evaluate model performance on test data \n", - "\n", - "6. Adjust hyperparameters (if necessary, network architecture)" - ] - }, - { - "cell_type": "markdown", - "id": "de6e80a8", - "metadata": { - "editable": true - }, - "source": [ - "## Collect and pre-process data\n", - "\n", - "Here we will be using the MNIST dataset, which is readily available through the **scikit-learn**\n", - "package. You may also find it for example [here](http://yann.lecun.com/exdb/mnist/). \n", - "The *MNIST* (Modified National Institute of Standards and Technology) database is a large database\n", - "of handwritten digits that is commonly used for training various image processing systems. \n", - "The MNIST dataset consists of 70 000 images of size $28\\times 28$ pixels, each labeled from 0 to 9. \n", - "The scikit-learn dataset we will use consists of a selection of 1797 images of size $8\\times 8$ collected and processed from this database. \n", - "\n", - "To feed data into a feed-forward neural network we need to represent\n", - "the inputs as a design/feature matrix $X = (n_{inputs}, n_{features})$. Each\n", - "row represents an *input*, in this case a handwritten digit, and\n", - "each column represents a *feature*, in this case a pixel. The\n", - "correct answers, also known as *labels* or *targets* are\n", - "represented as a 1D array of integers \n", - "$Y = (n_{inputs}) = (5, 3, 1, 8,...)$.\n", - "\n", - "As an example, say we want to build a neural network using supervised learning to predict Body-Mass Index (BMI) from\n", - "measurements of height (in m) \n", - "and weight (in kg). If we have measurements of 5 people the design/feature matrix could be for example: \n", - "\n", - "$$ X = \\begin{bmatrix}\n", - "1.85 & 81\\\\\n", - "1.71 & 65\\\\\n", - "1.95 & 103\\\\\n", - "1.55 & 42\\\\\n", - "1.63 & 56\n", - "\\end{bmatrix} ,$$ \n", - "\n", - "and the targets would be: \n", - "\n", - "$$ Y = (23.7, 22.2, 27.1, 17.5, 21.1) $$ \n", - "\n", - "Since each input image is a 2D matrix, we need to flatten the image\n", - "(i.e. \"unravel\" the 2D matrix into a 1D array) to turn the data into a\n", - "design/feature matrix. This means we lose all spatial information in the\n", - "image, such as locality and translational invariance. More complicated\n", - "architectures such as Convolutional Neural Networks can take advantage\n", - "of such information, and are most commonly applied when analyzing\n", - "images." - ] - }, - { - "cell_type": "code", - "execution_count": 22, - "id": "011b021a", - "metadata": { - "collapsed": false, - "editable": true - }, - "outputs": [], - "source": [ - "# import necessary packages\n", - "import numpy as np\n", - "import matplotlib.pyplot as plt\n", - "from sklearn import datasets\n", - "\n", - "\n", - "# ensure the same random numbers appear every time\n", - "np.random.seed(0)\n", - "\n", - "# display images in notebook\n", - "%matplotlib inline\n", - "plt.rcParams['figure.figsize'] = (12,12)\n", - "\n", - "\n", - "# download MNIST dataset\n", - "digits = datasets.load_digits()\n", - "\n", - "# define inputs and labels\n", - "inputs = digits.images\n", - "labels = digits.target\n", - "\n", - "print(\"inputs = (n_inputs, pixel_width, pixel_height) = \" + str(inputs.shape))\n", - "print(\"labels = (n_inputs) = \" + str(labels.shape))\n", - "\n", - "\n", - "# flatten the image\n", - "# the value -1 means dimension is inferred from the remaining dimensions: 8x8 = 64\n", - "n_inputs = len(inputs)\n", - "inputs = inputs.reshape(n_inputs, -1)\n", - "print(\"X = (n_inputs, n_features) = \" + str(inputs.shape))\n", - "\n", - "\n", - "# choose some random images to display\n", - "indices = np.arange(n_inputs)\n", - "random_indices = np.random.choice(indices, size=5)\n", - "\n", - "for i, image in enumerate(digits.images[random_indices]):\n", - " plt.subplot(1, 5, i+1)\n", - " plt.axis('off')\n", - " plt.imshow(image, cmap=plt.cm.gray_r, interpolation='nearest')\n", - " plt.title(\"Label: %d\" % digits.target[random_indices[i]])\n", - "plt.show()" - ] - }, - { - "cell_type": "markdown", - "id": "4de43fe8", - "metadata": { - "editable": true - }, - "source": [ - "## Train and test datasets\n", - "\n", - "Performing analysis before partitioning the dataset is a major error, that can lead to incorrect conclusions. \n", - "\n", - "We will reserve $80 \\%$ of our dataset for training and $20 \\%$ for testing. \n", - "\n", - "It is important that the train and test datasets are drawn randomly from our dataset, to ensure\n", - "no bias in the sampling. \n", - "Say you are taking measurements of weather data to predict the weather in the coming 5 days.\n", - "You don't want to train your model on measurements taken from the hours 00.00 to 12.00, and then test it on data\n", - "collected from 12.00 to 24.00." - ] - }, - { - "cell_type": "code", - "execution_count": 23, - "id": "d9281e06", - "metadata": { - "collapsed": false, - "editable": true - }, - "outputs": [], - "source": [ - "from sklearn.model_selection import train_test_split\n", - "\n", - "# one-liner from scikit-learn library\n", - "train_size = 0.8\n", - "test_size = 1 - train_size\n", - "X_train, X_test, Y_train, Y_test = train_test_split(inputs, labels, train_size=train_size,\n", - " test_size=test_size)\n", - "\n", - "# equivalently in numpy\n", - "def train_test_split_numpy(inputs, labels, train_size, test_size):\n", - " n_inputs = len(inputs)\n", - " inputs_shuffled = inputs.copy()\n", - " labels_shuffled = labels.copy()\n", - " \n", - " np.random.shuffle(inputs_shuffled)\n", - " np.random.shuffle(labels_shuffled)\n", - " \n", - " train_end = int(n_inputs*train_size)\n", - " X_train, X_test = inputs_shuffled[:train_end], inputs_shuffled[train_end:]\n", - " Y_train, Y_test = labels_shuffled[:train_end], labels_shuffled[train_end:]\n", - " \n", - " return X_train, X_test, Y_train, Y_test\n", - "\n", - "#X_train, X_test, Y_train, Y_test = train_test_split_numpy(inputs, labels, train_size, test_size)\n", - "\n", - "print(\"Number of training images: \" + str(len(X_train)))\n", - "print(\"Number of test images: \" + str(len(X_test)))" - ] - }, - { - "cell_type": "markdown", - "id": "5d86b543", - "metadata": { - "editable": true - }, - "source": [ - "## Define model and architecture\n", - "\n", - "Our simple feed-forward neural network will consist of an *input* layer, a single *hidden* layer and an *output* layer. The activation $y$ of each neuron is a weighted sum of inputs, passed through an activation function. In case of the simple perceptron model we have \n", - "\n", - "$$ z = \\sum_{i=1}^n w_i a_i ,$$\n", - "\n", - "$$ y = f(z) ,$$\n", - "\n", - "where $f$ is the activation function, $a_i$ represents input from neuron $i$ in the preceding layer\n", - "and $w_i$ is the weight to input $i$. \n", - "The activation of the neurons in the input layer is just the features (e.g. a pixel value). \n", - "\n", - "The simplest activation function for a neuron is the *Heaviside* function:\n", - "\n", - "$$ f(z) = \n", - "\\begin{cases}\n", - "1, & z > 0\\\\\n", - "0, & \\text{otherwise}\n", - "\\end{cases}\n", - "$$\n", - "\n", - "A feed-forward neural network with this activation is known as a *perceptron*. \n", - "For a binary classifier (i.e. two classes, 0 or 1, dog or not-dog) we can also use this in our output layer. \n", - "This activation can be generalized to $k$ classes (using e.g. the *one-against-all* strategy), \n", - "and we call these architectures *multiclass perceptrons*. \n", - "\n", - "However, it is now common to use the terms Single Layer Perceptron (SLP) (1 hidden layer) and \n", - "Multilayer Perceptron (MLP) (2 or more hidden layers) to refer to feed-forward neural networks with any activation function. \n", - "\n", - "Typical choices for activation functions include the sigmoid function, hyperbolic tangent, and Rectified Linear Unit (ReLU). \n", - "We will be using the sigmoid function $\\sigma(x)$: \n", - "\n", - "$$ f(x) = \\sigma(x) = \\frac{1}{1 + e^{-x}} ,$$\n", - "\n", - "which is inspired by probability theory (see logistic regression) and was most commonly used until about 2011. See the discussion below concerning other activation functions." - ] - }, - { - "cell_type": "markdown", - "id": "02df2616", - "metadata": { - "editable": true - }, - "source": [ - "## Layers\n", - "\n", - "* Input \n", - "\n", - "Since each input image has 8x8 = 64 pixels or features, we have an input layer of 64 neurons. \n", - "\n", - "* Hidden layer\n", - "\n", - "We will use 50 neurons in the hidden layer receiving input from the neurons in the input layer. \n", - "Since each neuron in the hidden layer is connected to the 64 inputs we have 64x50 = 3200 weights to the hidden layer. \n", - "\n", - "* Output\n", - "\n", - "If we were building a binary classifier, it would be sufficient with a single neuron in the output layer,\n", - "which could output 0 or 1 according to the Heaviside function. This would be an example of a *hard* classifier, meaning it outputs the class of the input directly. However, if we are dealing with noisy data it is often beneficial to use a *soft* classifier, which outputs the probability of being in class 0 or 1. \n", - "\n", - "For a soft binary classifier, we could use a single neuron and interpret the output as either being the probability of being in class 0 or the probability of being in class 1. Alternatively we could use 2 neurons, and interpret each neuron as the probability of being in each class. \n", - "\n", - "Since we are doing multiclass classification, with 10 categories, it is natural to use 10 neurons in the output layer. We number the neurons $j = 0,1,...,9$. The activation of each output neuron $j$ will be according to the *softmax* function: \n", - "\n", - "$$ P(\\text{class $j$} \\mid \\text{input $\\boldsymbol{a}$}) = \\frac{\\exp{(\\boldsymbol{a}^T \\boldsymbol{w}_j)}}\n", - "{\\sum_{c=0}^{9} \\exp{(\\boldsymbol{a}^T \\boldsymbol{w}_c)}} ,$$ \n", - "\n", - "i.e. each neuron $j$ outputs the probability of being in class $j$ given an input from the hidden layer $\\boldsymbol{a}$, with $\\boldsymbol{w}_j$ the weights of neuron $j$ to the inputs. \n", - "The denominator is a normalization factor to ensure the outputs (probabilities) sum up to 1. \n", - "The exponent is just the weighted sum of inputs as before: \n", - "\n", - "$$ z_j = \\sum_{i=1}^n w_ {ij} a_i+b_j.$$ \n", - "\n", - "Since each neuron in the output layer is connected to the 50 inputs from the hidden layer we have 50x10 = 500\n", - "weights to the output layer." - ] - }, - { - "cell_type": "markdown", - "id": "0a17cfeb", - "metadata": { - "editable": true - }, - "source": [ - "## Weights and biases\n", - "\n", - "Typically weights are initialized with small values distributed around zero, drawn from a uniform\n", - "or normal distribution. Setting all weights to zero means all neurons give the same output, making the network useless. \n", - "\n", - "Adding a bias value to the weighted sum of inputs allows the neural network to represent a greater range\n", - "of values. Without it, any input with the value 0 will be mapped to zero (before being passed through the activation). The bias unit has an output of 1, and a weight to each neuron $j$, $b_j$: \n", - "\n", - "$$ z_j = \\sum_{i=1}^n w_ {ij} a_i + b_j.$$ \n", - "\n", - "The bias weights $\\boldsymbol{b}$ are often initialized to zero, but a small value like $0.01$ ensures all neurons have some output which can be backpropagated in the first training cycle." - ] - }, - { - "cell_type": "code", - "execution_count": 24, - "id": "94dd542a", - "metadata": { - "collapsed": false, - "editable": true - }, - "outputs": [], - "source": [ - "# building our neural network\n", - "\n", - "n_inputs, n_features = X_train.shape\n", - "n_hidden_neurons = 50\n", - "n_categories = 10\n", - "\n", - "# we make the weights normally distributed using numpy.random.randn\n", - "\n", - "# weights and bias in the hidden layer\n", - "hidden_weights = np.random.randn(n_features, n_hidden_neurons)\n", - "hidden_bias = np.zeros(n_hidden_neurons) + 0.01\n", - "\n", - "# weights and bias in the output layer\n", - "output_weights = np.random.randn(n_hidden_neurons, n_categories)\n", - "output_bias = np.zeros(n_categories) + 0.01" - ] - }, - { - "cell_type": "markdown", - "id": "7c13f0a8", - "metadata": { - "editable": true - }, - "source": [ - "## Feed-forward pass\n", - "\n", - "Denote $F$ the number of features, $H$ the number of hidden neurons and $C$ the number of categories. \n", - "For each input image we calculate a weighted sum of input features (pixel values) to each neuron $j$ in the hidden layer $l$: \n", - "\n", - "$$ z_{j}^{l} = \\sum_{i=1}^{F} w_{ij}^{l} x_i + b_{j}^{l},$$\n", - "\n", - "this is then passed through our activation function \n", - "\n", - "$$ a_{j}^{l} = f(z_{j}^{l}) .$$ \n", - "\n", - "We calculate a weighted sum of inputs (activations in the hidden layer) to each neuron $j$ in the output layer: \n", - "\n", - "$$ z_{j}^{L} = \\sum_{i=1}^{H} w_{ij}^{L} a_{i}^{l} + b_{j}^{L}.$$ \n", - "\n", - "Finally we calculate the output of neuron $j$ in the output layer using the softmax function: \n", - "\n", - "$$ a_{j}^{L} = \\frac{\\exp{(z_j^{L})}}\n", - "{\\sum_{c=0}^{C-1} \\exp{(z_c^{L})}} .$$" - ] - }, - { - "cell_type": "markdown", - "id": "d1bae3d4", - "metadata": { - "editable": true - }, - "source": [ - "## Matrix multiplications\n", - "\n", - "Since our data has the dimensions $X = (n_{inputs}, n_{features})$ and our weights to the hidden\n", - "layer have the dimensions \n", - "$W_{hidden} = (n_{features}, n_{hidden})$,\n", - "we can easily feed the network all our training data in one go by taking the matrix product \n", - "\n", - "$$ X W^{h} = (n_{inputs}, n_{hidden}),$$ \n", - "\n", - "and obtain a matrix that holds the weighted sum of inputs to the hidden layer\n", - "for each input image and each hidden neuron. \n", - "We also add the bias to obtain a matrix of weighted sums to the hidden layer $Z^{h}$: \n", - "\n", - "$$ \\boldsymbol{z}^{l} = \\boldsymbol{X} \\boldsymbol{W}^{l} + \\boldsymbol{b}^{l} ,$$\n", - "\n", - "meaning the same bias (1D array with size equal number of hidden neurons) is added to each input image. \n", - "This is then passed through the activation: \n", - "\n", - "$$ \\boldsymbol{a}^{l} = f(\\boldsymbol{z}^l) .$$ \n", - "\n", - "This is fed to the output layer: \n", - "\n", - "$$ \\boldsymbol{z}^{L} = \\boldsymbol{a}^{L} \\boldsymbol{W}^{L} + \\boldsymbol{b}^{L} .$$\n", - "\n", - "Finally we receive our output values for each image and each category by passing it through the softmax function: \n", - "\n", - "$$ output = softmax (\\boldsymbol{z}^{L}) = (n_{inputs}, n_{categories}) .$$" - ] - }, - { - "cell_type": "code", - "execution_count": 25, - "id": "20c03478", - "metadata": { - "collapsed": false, - "editable": true - }, - "outputs": [], - "source": [ - "# setup the feed-forward pass, subscript h = hidden layer\n", - "\n", - "def sigmoid(x):\n", - " return 1/(1 + np.exp(-x))\n", - "\n", - "def feed_forward(X):\n", - " # weighted sum of inputs to the hidden layer\n", - " z_h = np.matmul(X, hidden_weights) + hidden_bias\n", - " # activation in the hidden layer\n", - " a_h = sigmoid(z_h)\n", - " \n", - " # weighted sum of inputs to the output layer\n", - " z_o = np.matmul(a_h, output_weights) + output_bias\n", - " # softmax output\n", - " # axis 0 holds each input and axis 1 the probabilities of each category\n", - " exp_term = np.exp(z_o)\n", - " probabilities = exp_term / np.sum(exp_term, axis=1, keepdims=True)\n", - " \n", - " return probabilities\n", - "\n", - "probabilities = feed_forward(X_train)\n", - "print(\"probabilities = (n_inputs, n_categories) = \" + str(probabilities.shape))\n", - "print(\"probability that image 0 is in category 0,1,2,...,9 = \\n\" + str(probabilities[0]))\n", - "print(\"probabilities sum up to: \" + str(probabilities[0].sum()))\n", - "print()\n", - "\n", - "# we obtain a prediction by taking the class with the highest likelihood\n", - "def predict(X):\n", - " probabilities = feed_forward(X)\n", - " return np.argmax(probabilities, axis=1)\n", - "\n", - "predictions = predict(X_train)\n", - "print(\"predictions = (n_inputs) = \" + str(predictions.shape))\n", - "print(\"prediction for image 0: \" + str(predictions[0]))\n", - "print(\"correct label for image 0: \" + str(Y_train[0]))" - ] - }, - { - "cell_type": "markdown", - "id": "42c28741", - "metadata": { - "editable": true - }, - "source": [ - "## Choose cost function and optimizer\n", - "\n", - "To measure how well our neural network is doing we need to introduce a cost function. \n", - "We will call the function that gives the error of a single sample output the *loss* function, and the function\n", - "that gives the total error of our network across all samples the *cost* function.\n", - "A typical choice for multiclass classification is the *cross-entropy* loss, also known as the negative log likelihood. \n", - "\n", - "In *multiclass* classification it is common to treat each integer label as a so called *one-hot* vector: \n", - "\n", - "$$ y = 5 \\quad \\rightarrow \\quad \\boldsymbol{y} = (0, 0, 0, 0, 0, 1, 0, 0, 0, 0) ,$$ \n", - "\n", - "$$ y = 1 \\quad \\rightarrow \\quad \\boldsymbol{y} = (0, 1, 0, 0, 0, 0, 0, 0, 0, 0) ,$$ \n", - "\n", - "i.e. a binary bit string of length $C$, where $C = 10$ is the number of classes in the MNIST dataset. \n", - "\n", - "Let $y_{ic}$ denote the $c$-th component of the $i$-th one-hot vector. \n", - "We define the cost function $\\mathcal{C}$ as a sum over the cross-entropy loss for each point $\\boldsymbol{x}_i$ in the dataset.\n", - "\n", - "In the one-hot representation only one of the terms in the loss function is non-zero, namely the\n", - "probability of the correct category $c'$ \n", - "(i.e. the category $c'$ such that $y_{ic'} = 1$). This means that the cross entropy loss only punishes you for how wrong\n", - "you got the correct label. The probability of category $c$ is given by the softmax function. The vector $\\boldsymbol{\\theta}$ represents the parameters of our network, i.e. all the weights and biases." - ] - }, - { - "cell_type": "markdown", - "id": "62954b00", - "metadata": { - "editable": true - }, - "source": [ - "## Optimizing the cost function\n", - "\n", - "The network is trained by finding the weights and biases that minimize the cost function. One of the most widely used classes of methods is *gradient descent* and its generalizations. The idea behind gradient descent\n", - "is simply to adjust the weights in the direction where the gradient of the cost function is large and negative. This ensures we flow toward a *local* minimum of the cost function. \n", - "Each parameter $\\theta$ is iteratively adjusted according to the rule \n", - "\n", - "$$ \\theta_{i+1} = \\theta_i - \\eta \\nabla \\mathcal{C}(\\theta_i) ,$$\n", - "\n", - "where $\\eta$ is known as the *learning rate*, which controls how big a step we take towards the minimum. \n", - "This update can be repeated for any number of iterations, or until we are satisfied with the result. \n", - "\n", - "A simple and effective improvement is a variant called *Batch Gradient Descent*. \n", - "Instead of calculating the gradient on the whole dataset, we calculate an approximation of the gradient\n", - "on a subset of the data called a *minibatch*. \n", - "If there are $N$ data points and we have a minibatch size of $M$, the total number of batches\n", - "is $N/M$. \n", - "We denote each minibatch $B_k$, with $k = 1, 2,...,N/M$. The gradient then becomes: \n", - "\n", - "$$ \\nabla \\mathcal{C}(\\theta) = \\frac{1}{N} \\sum_{i=1}^N \\nabla \\mathcal{L}_i(\\theta) \\quad \\rightarrow \\quad\n", - "\\frac{1}{M} \\sum_{i \\in B_k} \\nabla \\mathcal{L}_i(\\theta) ,$$\n", - "\n", - "i.e. instead of averaging the loss over the entire dataset, we average over a minibatch. \n", - "\n", - "This has two important benefits: \n", - "1. Introducing stochasticity decreases the chance that the algorithm becomes stuck in a local minima. \n", - "\n", - "2. It significantly speeds up the calculation, since we do not have to use the entire dataset to calculate the gradient. \n", - "\n", - "The various optmization methods, with codes and algorithms, are discussed in our lectures on [Gradient descent approaches](https://compphysics.github.io/MachineLearning/doc/pub/Splines/html/Splines-bs.html)." - ] - }, - { - "cell_type": "markdown", - "id": "9f94aff8", - "metadata": { - "editable": true - }, - "source": [ - "## Regularization\n", - "\n", - "It is common to add an extra term to the cost function, proportional\n", - "to the size of the weights. This is equivalent to constraining the\n", - "size of the weights, so that they do not grow out of control.\n", - "Constraining the size of the weights means that the weights cannot\n", - "grow arbitrarily large to fit the training data, and in this way\n", - "reduces *overfitting*.\n", - "\n", - "We will measure the size of the weights using the so called *L2-norm*, meaning our cost function becomes: \n", - "\n", - "$$ \\mathcal{C}(\\theta) = \\frac{1}{N} \\sum_{i=1}^N \\mathcal{L}_i(\\theta) \\quad \\rightarrow \\quad\n", - "\\frac{1}{N} \\sum_{i=1}^N \\mathcal{L}_i(\\theta) + \\lambda \\lvert \\lvert \\boldsymbol{w} \\rvert \\rvert_2^2 \n", - "= \\frac{1}{N} \\sum_{i=1}^N \\mathcal{L}(\\theta) + \\lambda \\sum_{ij} w_{ij}^2,$$ \n", - "\n", - "i.e. we sum up all the weights squared. The factor $\\lambda$ is known as a regularization parameter.\n", - "\n", - "In order to train the model, we need to calculate the derivative of\n", - "the cost function with respect to every bias and weight in the\n", - "network. In total our network has $(64 + 1)\\times 50=3250$ weights in\n", - "the hidden layer and $(50 + 1)\\times 10=510$ weights to the output\n", - "layer ($+1$ for the bias), and the gradient must be calculated for\n", - "every parameter. We use the *backpropagation* algorithm discussed\n", - "above. This is a clever use of the chain rule that allows us to\n", - "calculate the gradient efficently." - ] - }, - { - "cell_type": "markdown", - "id": "bf73f8e5", - "metadata": { - "editable": true - }, - "source": [ - "## Matrix multiplication\n", - "\n", - "To more efficently train our network these equations are implemented using matrix operations. \n", - "The error in the output layer is calculated simply as, with $\\boldsymbol{t}$ being our targets, \n", - "\n", - "$$ \\delta_L = \\boldsymbol{t} - \\boldsymbol{y} = (n_{inputs}, n_{categories}) .$$ \n", - "\n", - "The gradient for the output weights is calculated as \n", - "\n", - "$$ \\nabla W_{L} = \\boldsymbol{a}^T \\delta_L = (n_{hidden}, n_{categories}) ,$$\n", - "\n", - "where $\\boldsymbol{a} = (n_{inputs}, n_{hidden})$. This simply means that we are summing up the gradients for each input. \n", - "Since we are going backwards we have to transpose the activation matrix. \n", - "\n", - "The gradient with respect to the output bias is then \n", - "\n", - "$$ \\nabla \\boldsymbol{b}_{L} = \\sum_{i=1}^{n_{inputs}} \\delta_L = (n_{categories}) .$$ \n", - "\n", - "The error in the hidden layer is \n", - "\n", - "$$ \\Delta_h = \\delta_L W_{L}^T \\circ f'(z_{h}) = \\delta_L W_{L}^T \\circ a_{h} \\circ (1 - a_{h}) = (n_{inputs}, n_{hidden}) ,$$ \n", - "\n", - "where $f'(a_{h})$ is the derivative of the activation in the hidden layer. The matrix products mean\n", - "that we are summing up the products for each neuron in the output layer. The symbol $\\circ$ denotes\n", - "the *Hadamard product*, meaning element-wise multiplication. \n", - "\n", - "This again gives us the gradients in the hidden layer: \n", - "\n", - "$$ \\nabla W_{h} = X^T \\delta_h = (n_{features}, n_{hidden}) ,$$ \n", - "\n", - "$$ \\nabla b_{h} = \\sum_{i=1}^{n_{inputs}} \\delta_h = (n_{hidden}) .$$" - ] - }, - { - "cell_type": "code", - "execution_count": 26, - "id": "9ffb0561", - "metadata": { - "collapsed": false, - "editable": true - }, - "outputs": [], - "source": [ - "# to categorical turns our integer vector into a onehot representation\n", - "from sklearn.metrics import accuracy_score\n", - "\n", - "# one-hot in numpy\n", - "def to_categorical_numpy(integer_vector):\n", - " n_inputs = len(integer_vector)\n", - " n_categories = np.max(integer_vector) + 1\n", - " onehot_vector = np.zeros((n_inputs, n_categories))\n", - " onehot_vector[range(n_inputs), integer_vector] = 1\n", - " \n", - " return onehot_vector\n", - "\n", - "#Y_train_onehot, Y_test_onehot = to_categorical(Y_train), to_categorical(Y_test)\n", - "Y_train_onehot, Y_test_onehot = to_categorical_numpy(Y_train), to_categorical_numpy(Y_test)\n", - "\n", - "def feed_forward_train(X):\n", - " # weighted sum of inputs to the hidden layer\n", - " z_h = np.matmul(X, hidden_weights) + hidden_bias\n", - " # activation in the hidden layer\n", - " a_h = sigmoid(z_h)\n", - " \n", - " # weighted sum of inputs to the output layer\n", - " z_o = np.matmul(a_h, output_weights) + output_bias\n", - " # softmax output\n", - " # axis 0 holds each input and axis 1 the probabilities of each category\n", - " exp_term = np.exp(z_o)\n", - " probabilities = exp_term / np.sum(exp_term, axis=1, keepdims=True)\n", - " \n", - " # for backpropagation need activations in hidden and output layers\n", - " return a_h, probabilities\n", - "\n", - "def backpropagation(X, Y):\n", - " a_h, probabilities = feed_forward_train(X)\n", - " \n", - " # error in the output layer\n", - " error_output = probabilities - Y\n", - " # error in the hidden layer\n", - " error_hidden = np.matmul(error_output, output_weights.T) * a_h * (1 - a_h)\n", - " \n", - " # gradients for the output layer\n", - " output_weights_gradient = np.matmul(a_h.T, error_output)\n", - " output_bias_gradient = np.sum(error_output, axis=0)\n", - " \n", - " # gradient for the hidden layer\n", - " hidden_weights_gradient = np.matmul(X.T, error_hidden)\n", - " hidden_bias_gradient = np.sum(error_hidden, axis=0)\n", - "\n", - " return output_weights_gradient, output_bias_gradient, hidden_weights_gradient, hidden_bias_gradient\n", - "\n", - "print(\"Old accuracy on training data: \" + str(accuracy_score(predict(X_train), Y_train)))\n", - "\n", - "eta = 0.01\n", - "lmbd = 0.01\n", - "for i in range(1000):\n", - " # calculate gradients\n", - " dWo, dBo, dWh, dBh = backpropagation(X_train, Y_train_onehot)\n", - " \n", - " # regularization term gradients\n", - " dWo += lmbd * output_weights\n", - " dWh += lmbd * hidden_weights\n", - " \n", - " # update weights and biases\n", - " output_weights -= eta * dWo\n", - " output_bias -= eta * dBo\n", - " hidden_weights -= eta * dWh\n", - " hidden_bias -= eta * dBh\n", - "\n", - "print(\"New accuracy on training data: \" + str(accuracy_score(predict(X_train), Y_train)))" - ] - }, - { - "cell_type": "markdown", - "id": "3b19f8e5", - "metadata": { - "editable": true - }, - "source": [ - "## Improving performance\n", - "\n", - "As we can see the network does not seem to be learning at all. It seems to be just guessing the label for each image. \n", - "In order to obtain a network that does something useful, we will have to do a bit more work. \n", - "\n", - "The choice of *hyperparameters* such as learning rate and regularization parameter is hugely influential for the performance of the network. Typically a *grid-search* is performed, wherein we test different hyperparameters separated by orders of magnitude. For example we could test the learning rates $\\eta = 10^{-6}, 10^{-5},...,10^{-1}$ with different regularization parameters $\\lambda = 10^{-6},...,10^{-0}$. \n", - "\n", - "Next, we haven't implemented minibatching yet, which introduces stochasticity and is though to act as an important regularizer on the weights. We call a feed-forward + backward pass with a minibatch an *iteration*, and a full training period\n", - "going through the entire dataset ($n/M$ batches) an *epoch*.\n", - "\n", - "If this does not improve network performance, you may want to consider altering the network architecture, adding more neurons or hidden layers. \n", - "Andrew Ng goes through some of these considerations in this [video](https://youtu.be/F1ka6a13S9I). You can find a summary of the video [here](https://kevinzakka.github.io/2016/09/26/applying-deep-learning/)." - ] - }, - { - "cell_type": "markdown", - "id": "443db3c1", - "metadata": { - "editable": true - }, - "source": [ - "## Full object-oriented implementation\n", - "\n", - "It is very natural to think of the network as an object, with specific instances of the network\n", - "being realizations of this object with different hyperparameters. An implementation using Python classes provides a clean structure and interface, and the full implementation of our neural network is given below." - ] - }, - { - "cell_type": "code", - "execution_count": 27, - "id": "5a7db6a1", - "metadata": { - "collapsed": false, - "editable": true - }, - "outputs": [], - "source": [ - "class NeuralNetwork:\n", - " def __init__(\n", - " self,\n", - " X_data,\n", - " Y_data,\n", - " n_hidden_neurons=50,\n", - " n_categories=10,\n", - " epochs=10,\n", - " batch_size=100,\n", - " eta=0.1,\n", - " lmbd=0.0):\n", - "\n", - " self.X_data_full = X_data\n", - " self.Y_data_full = Y_data\n", - "\n", - " self.n_inputs = X_data.shape[0]\n", - " self.n_features = X_data.shape[1]\n", - " self.n_hidden_neurons = n_hidden_neurons\n", - " self.n_categories = n_categories\n", - "\n", - " self.epochs = epochs\n", - " self.batch_size = batch_size\n", - " self.iterations = self.n_inputs // self.batch_size\n", - " self.eta = eta\n", - " self.lmbd = lmbd\n", - "\n", - " self.create_biases_and_weights()\n", - "\n", - " def create_biases_and_weights(self):\n", - " self.hidden_weights = np.random.randn(self.n_features, self.n_hidden_neurons)\n", - " self.hidden_bias = np.zeros(self.n_hidden_neurons) + 0.01\n", - "\n", - " self.output_weights = np.random.randn(self.n_hidden_neurons, self.n_categories)\n", - " self.output_bias = np.zeros(self.n_categories) + 0.01\n", - "\n", - " def feed_forward(self):\n", - " # feed-forward for training\n", - " self.z_h = np.matmul(self.X_data, self.hidden_weights) + self.hidden_bias\n", - " self.a_h = sigmoid(self.z_h)\n", - "\n", - " self.z_o = np.matmul(self.a_h, self.output_weights) + self.output_bias\n", - "\n", - " exp_term = np.exp(self.z_o)\n", - " self.probabilities = exp_term / np.sum(exp_term, axis=1, keepdims=True)\n", - "\n", - " def feed_forward_out(self, X):\n", - " # feed-forward for output\n", - " z_h = np.matmul(X, self.hidden_weights) + self.hidden_bias\n", - " a_h = sigmoid(z_h)\n", - "\n", - " z_o = np.matmul(a_h, self.output_weights) + self.output_bias\n", - " \n", - " exp_term = np.exp(z_o)\n", - " probabilities = exp_term / np.sum(exp_term, axis=1, keepdims=True)\n", - " return probabilities\n", - "\n", - " def backpropagation(self):\n", - " error_output = self.probabilities - self.Y_data\n", - " error_hidden = np.matmul(error_output, self.output_weights.T) * self.a_h * (1 - self.a_h)\n", - "\n", - " self.output_weights_gradient = np.matmul(self.a_h.T, error_output)\n", - " self.output_bias_gradient = np.sum(error_output, axis=0)\n", - "\n", - " self.hidden_weights_gradient = np.matmul(self.X_data.T, error_hidden)\n", - " self.hidden_bias_gradient = np.sum(error_hidden, axis=0)\n", - "\n", - " if self.lmbd > 0.0:\n", - " self.output_weights_gradient += self.lmbd * self.output_weights\n", - " self.hidden_weights_gradient += self.lmbd * self.hidden_weights\n", - "\n", - " self.output_weights -= self.eta * self.output_weights_gradient\n", - " self.output_bias -= self.eta * self.output_bias_gradient\n", - " self.hidden_weights -= self.eta * self.hidden_weights_gradient\n", - " self.hidden_bias -= self.eta * self.hidden_bias_gradient\n", - "\n", - " def predict(self, X):\n", - " probabilities = self.feed_forward_out(X)\n", - " return np.argmax(probabilities, axis=1)\n", - "\n", - " def predict_probabilities(self, X):\n", - " probabilities = self.feed_forward_out(X)\n", - " return probabilities\n", - "\n", - " def train(self):\n", - " data_indices = np.arange(self.n_inputs)\n", - "\n", - " for i in range(self.epochs):\n", - " for j in range(self.iterations):\n", - " # pick datapoints with replacement\n", - " chosen_datapoints = np.random.choice(\n", - " data_indices, size=self.batch_size, replace=False\n", - " )\n", - "\n", - " # minibatch training data\n", - " self.X_data = self.X_data_full[chosen_datapoints]\n", - " self.Y_data = self.Y_data_full[chosen_datapoints]\n", - "\n", - " self.feed_forward()\n", - " self.backpropagation()" - ] - }, - { - "cell_type": "markdown", - "id": "fe73ada1", - "metadata": { - "editable": true - }, - "source": [ - "## Evaluate model performance on test data\n", - "\n", - "To measure the performance of our network we evaluate how well it does it data it has never seen before, i.e. the test data. \n", - "We measure the performance of the network using the *accuracy* score. \n", - "The accuracy is as you would expect just the number of images correctly labeled divided by the total number of images. A perfect classifier will have an accuracy score of $1$. \n", - "\n", - "$$ \\text{Accuracy} = \\frac{\\sum_{i=1}^n I(\\tilde{y}_i = y_i)}{n} ,$$ \n", - "\n", - "where $I$ is the indicator function, $1$ if $\\tilde{y}_i = y_i$ and $0$ otherwise." - ] - }, - { - "cell_type": "code", - "execution_count": 28, - "id": "3c71da93", - "metadata": { - "collapsed": false, - "editable": true - }, - "outputs": [], - "source": [ - "epochs = 100\n", - "batch_size = 100\n", - "\n", - "dnn = NeuralNetwork(X_train, Y_train_onehot, eta=eta, lmbd=lmbd, epochs=epochs, batch_size=batch_size,\n", - " n_hidden_neurons=n_hidden_neurons, n_categories=n_categories)\n", - "dnn.train()\n", - "test_predict = dnn.predict(X_test)\n", - "\n", - "# accuracy score from scikit library\n", - "print(\"Accuracy score on test set: \", accuracy_score(Y_test, test_predict))\n", - "\n", - "# equivalent in numpy\n", - "def accuracy_score_numpy(Y_test, Y_pred):\n", - " return np.sum(Y_test == Y_pred) / len(Y_test)\n", - "\n", - "#print(\"Accuracy score on test set: \", accuracy_score_numpy(Y_test, test_predict))" - ] - }, - { - "cell_type": "markdown", - "id": "c6d594b6", - "metadata": { - "editable": true - }, - "source": [ - "## Adjust hyperparameters\n", - "\n", - "We now perform a grid search to find the optimal hyperparameters for the network. \n", - "Note that we are only using 1 layer with 50 neurons, and human performance is estimated to be around $98\\%$ ($2\\%$ error rate)." - ] - }, - { - "cell_type": "code", - "execution_count": 29, - "id": "bb8c3746", - "metadata": { - "collapsed": false, - "editable": true - }, - "outputs": [], - "source": [ - "eta_vals = np.logspace(-5, 1, 7)\n", - "lmbd_vals = np.logspace(-5, 1, 7)\n", - "# store the models for later use\n", - "DNN_numpy = np.zeros((len(eta_vals), len(lmbd_vals)), dtype=object)\n", - "\n", - "# grid search\n", - "for i, eta in enumerate(eta_vals):\n", - " for j, lmbd in enumerate(lmbd_vals):\n", - " dnn = NeuralNetwork(X_train, Y_train_onehot, eta=eta, lmbd=lmbd, epochs=epochs, batch_size=batch_size,\n", - " n_hidden_neurons=n_hidden_neurons, n_categories=n_categories)\n", - " dnn.train()\n", - " \n", - " DNN_numpy[i][j] = dnn\n", - " \n", - " test_predict = dnn.predict(X_test)\n", - " \n", - " print(\"Learning rate = \", eta)\n", - " print(\"Lambda = \", lmbd)\n", - " print(\"Accuracy score on test set: \", accuracy_score(Y_test, test_predict))\n", - " print()" - ] - }, - { - "cell_type": "markdown", - "id": "c460a08f", - "metadata": { - "editable": true - }, - "source": [ - "## Visualization" - ] - }, - { - "cell_type": "code", - "execution_count": 30, - "id": "ae408ce7", - "metadata": { - "collapsed": false, - "editable": true - }, - "outputs": [], - "source": [ - "# visual representation of grid search\n", - "# uses seaborn heatmap, you can also do this with matplotlib imshow\n", - "import seaborn as sns\n", - "\n", - "sns.set()\n", - "\n", - "train_accuracy = np.zeros((len(eta_vals), len(lmbd_vals)))\n", - "test_accuracy = np.zeros((len(eta_vals), len(lmbd_vals)))\n", - "\n", - "for i in range(len(eta_vals)):\n", - " for j in range(len(lmbd_vals)):\n", - " dnn = DNN_numpy[i][j]\n", - " \n", - " train_pred = dnn.predict(X_train) \n", - " test_pred = dnn.predict(X_test)\n", - "\n", - " train_accuracy[i][j] = accuracy_score(Y_train, train_pred)\n", - " test_accuracy[i][j] = accuracy_score(Y_test, test_pred)\n", - "\n", - " \n", - "fig, ax = plt.subplots(figsize = (10, 10))\n", - "sns.heatmap(train_accuracy, annot=True, ax=ax, cmap=\"viridis\")\n", - "ax.set_title(\"Training Accuracy\")\n", - "ax.set_ylabel(\"$\\eta$\")\n", - "ax.set_xlabel(\"$\\lambda$\")\n", - "plt.show()\n", - "\n", - "fig, ax = plt.subplots(figsize = (10, 10))\n", - "sns.heatmap(test_accuracy, annot=True, ax=ax, cmap=\"viridis\")\n", - "ax.set_title(\"Test Accuracy\")\n", - "ax.set_ylabel(\"$\\eta$\")\n", - "ax.set_xlabel(\"$\\lambda$\")\n", - "plt.show()" - ] - }, - { - "cell_type": "markdown", - "id": "255351d8", - "metadata": { - "editable": true - }, - "source": [ - "## scikit-learn implementation\n", - "\n", - "**scikit-learn** focuses more\n", - "on traditional machine learning methods, such as regression,\n", - "clustering, decision trees, etc. As such, it has only two types of\n", - "neural networks: Multi Layer Perceptron outputting continuous values,\n", - "*MPLRegressor*, and Multi Layer Perceptron outputting labels,\n", - "*MLPClassifier*. We will see how simple it is to use these classes.\n", - "\n", - "**scikit-learn** implements a few improvements from our neural network,\n", - "such as early stopping, a varying learning rate, different\n", - "optimization methods, etc. We would therefore expect a better\n", - "performance overall." - ] - }, - { - "cell_type": "code", - "execution_count": 31, - "id": "45102bf4", - "metadata": { - "collapsed": false, - "editable": true - }, - "outputs": [], - "source": [ - "from sklearn.neural_network import MLPClassifier\n", - "# store models for later use\n", - "DNN_scikit = np.zeros((len(eta_vals), len(lmbd_vals)), dtype=object)\n", - "\n", - "for i, eta in enumerate(eta_vals):\n", - " for j, lmbd in enumerate(lmbd_vals):\n", - " dnn = MLPClassifier(hidden_layer_sizes=(n_hidden_neurons), activation='logistic',\n", - " alpha=lmbd, learning_rate_init=eta, max_iter=epochs)\n", - " dnn.fit(X_train, Y_train)\n", - " \n", - " DNN_scikit[i][j] = dnn\n", - " \n", - " print(\"Learning rate = \", eta)\n", - " print(\"Lambda = \", lmbd)\n", - " print(\"Accuracy score on test set: \", dnn.score(X_test, Y_test))\n", - " print()" - ] - }, - { - "cell_type": "markdown", - "id": "9ed166d7", - "metadata": { - "editable": true - }, - "source": [ - "## Visualization" - ] - }, - { - "cell_type": "code", - "execution_count": 32, - "id": "e9fb271f", - "metadata": { - "collapsed": false, - "editable": true - }, - "outputs": [], - "source": [ - "# optional\n", - "# visual representation of grid search\n", - "# uses seaborn heatmap, could probably do this in matplotlib\n", - "import seaborn as sns\n", - "\n", - "sns.set()\n", - "\n", - "train_accuracy = np.zeros((len(eta_vals), len(lmbd_vals)))\n", - "test_accuracy = np.zeros((len(eta_vals), len(lmbd_vals)))\n", - "\n", - "for i in range(len(eta_vals)):\n", - " for j in range(len(lmbd_vals)):\n", - " dnn = DNN_scikit[i][j]\n", - " \n", - " train_pred = dnn.predict(X_train) \n", - " test_pred = dnn.predict(X_test)\n", - "\n", - " train_accuracy[i][j] = accuracy_score(Y_train, train_pred)\n", - " test_accuracy[i][j] = accuracy_score(Y_test, test_pred)\n", - "\n", - " \n", - "fig, ax = plt.subplots(figsize = (10, 10))\n", - "sns.heatmap(train_accuracy, annot=True, ax=ax, cmap=\"viridis\")\n", - "ax.set_title(\"Training Accuracy\")\n", - "ax.set_ylabel(\"$\\eta$\")\n", - "ax.set_xlabel(\"$\\lambda$\")\n", - "plt.show()\n", - "\n", - "fig, ax = plt.subplots(figsize = (10, 10))\n", - "sns.heatmap(test_accuracy, annot=True, ax=ax, cmap=\"viridis\")\n", - "ax.set_title(\"Test Accuracy\")\n", - "ax.set_ylabel(\"$\\eta$\")\n", - "ax.set_xlabel(\"$\\lambda$\")\n", - "plt.show()" - ] - }, - { - "cell_type": "markdown", - "id": "6cbb4072", - "metadata": { - "editable": true - }, - "source": [ - "## Building neural networks in Tensorflow and Keras\n", - "\n", - "Now we want to build on the experience gained from our neural network implementation in NumPy and scikit-learn\n", - "and use it to construct a neural network in Tensorflow. Once we have constructed a neural network in NumPy\n", - "and Tensorflow, building one in Keras is really quite trivial, though the performance may suffer. \n", - "\n", - "In our previous example we used only one hidden layer, and in this we will use two. From this it should be quite\n", - "clear how to build one using an arbitrary number of hidden layers, using data structures such as Python lists or\n", - "NumPy arrays." - ] - }, - { - "cell_type": "markdown", - "id": "2702932a", - "metadata": { - "editable": true - }, - "source": [ - "## Tensorflow\n", - "\n", - "Tensorflow is an open source library machine learning library\n", - "developed by the Google Brain team for internal use. It was released\n", - "under the Apache 2.0 open source license in November 9, 2015.\n", - "\n", - "Tensorflow is a computational framework that allows you to construct\n", - "machine learning models at different levels of abstraction, from\n", - "high-level, object-oriented APIs like Keras, down to the C++ kernels\n", - "that Tensorflow is built upon. The higher levels of abstraction are\n", - "simpler to use, but less flexible, and our choice of implementation\n", - "should reflect the problems we are trying to solve.\n", - "\n", - "[Tensorflow uses](https://www.tensorflow.org/guide/graphs) so-called graphs to represent your computation\n", - "in terms of the dependencies between individual operations, such that you first build a Tensorflow *graph*\n", - "to represent your model, and then create a Tensorflow *session* to run the graph.\n", - "\n", - "In this guide we will analyze the same data as we did in our NumPy and\n", - "scikit-learn tutorial, gathered from the MNIST database of images. We\n", - "will give an introduction to the lower level Python Application\n", - "Program Interfaces (APIs), and see how we use them to build our graph.\n", - "Then we will build (effectively) the same graph in Keras, to see just\n", - "how simple solving a machine learning problem can be.\n", - "\n", - "To install tensorflow on Unix/Linux systems, use pip as" - ] - }, - { - "cell_type": "code", - "execution_count": 33, - "id": "a66fc7b6", - "metadata": { - "collapsed": false, - "editable": true - }, - "outputs": [], - "source": [ - "pip3 install tensorflow" - ] - }, - { - "cell_type": "markdown", - "id": "3c99a292", - "metadata": { - "editable": true - }, - "source": [ - "and/or if you use **anaconda**, just write (or install from the graphical user interface)\n", - "(current release of CPU-only TensorFlow)" - ] - }, - { - "cell_type": "code", - "execution_count": 34, - "id": "71e9f24b", - "metadata": { - "collapsed": false, - "editable": true - }, - "outputs": [], - "source": [ - "conda create -n tf tensorflow\n", - "conda activate tf" - ] - }, - { - "cell_type": "markdown", - "id": "a623588f", - "metadata": { - "editable": true - }, - "source": [ - "To install the current release of GPU TensorFlow" - ] - }, - { - "cell_type": "code", - "execution_count": 35, - "id": "fa19ee75", - "metadata": { - "collapsed": false, - "editable": true - }, - "outputs": [], - "source": [ - "conda create -n tf-gpu tensorflow-gpu\n", - "conda activate tf-gpu" - ] - }, - { - "cell_type": "markdown", - "id": "de5fec4a", - "metadata": { - "editable": true - }, - "source": [ - "## Using Keras\n", - "\n", - "Keras is a high level [neural network](https://en.wikipedia.org/wiki/Application_programming_interface)\n", - "that supports Tensorflow, CTNK and Theano as backends. \n", - "If you have Anaconda installed you may run the following command" - ] - }, - { - "cell_type": "code", - "execution_count": 36, - "id": "edb61bdb", - "metadata": { - "collapsed": false, - "editable": true - }, - "outputs": [], - "source": [ - "conda install keras" - ] - }, - { - "cell_type": "markdown", - "id": "fd72dabb", - "metadata": { - "editable": true - }, - "source": [ - "You can look up the [instructions here](https://keras.io/) for more information.\n", - "\n", - "We will to a large extent use **keras** in our examples.." - ] - }, - { - "cell_type": "markdown", - "id": "b8262ab5", - "metadata": { - "editable": true - }, - "source": [ - "## Collect and pre-process data\n", - "\n", - "Let us look again at the MINST data set." - ] - }, - { - "cell_type": "code", - "execution_count": 37, - "id": "0b88258b", - "metadata": { - "collapsed": false, - "editable": true - }, - "outputs": [], - "source": [ - "# import necessary packages\n", - "import numpy as np\n", - "import matplotlib.pyplot as plt\n", - "import tensorflow as tf\n", - "from sklearn import datasets\n", - "\n", - "\n", - "# ensure the same random numbers appear every time\n", - "np.random.seed(0)\n", - "\n", - "# display images in notebook\n", - "%matplotlib inline\n", - "plt.rcParams['figure.figsize'] = (12,12)\n", - "\n", - "\n", - "# download MNIST dataset\n", - "digits = datasets.load_digits()\n", - "\n", - "# define inputs and labels\n", - "inputs = digits.images\n", - "labels = digits.target\n", - "\n", - "print(\"inputs = (n_inputs, pixel_width, pixel_height) = \" + str(inputs.shape))\n", - "print(\"labels = (n_inputs) = \" + str(labels.shape))\n", - "\n", - "\n", - "# flatten the image\n", - "# the value -1 means dimension is inferred from the remaining dimensions: 8x8 = 64\n", - "n_inputs = len(inputs)\n", - "inputs = inputs.reshape(n_inputs, -1)\n", - "print(\"X = (n_inputs, n_features) = \" + str(inputs.shape))\n", - "\n", - "\n", - "# choose some random images to display\n", - "indices = np.arange(n_inputs)\n", - "random_indices = np.random.choice(indices, size=5)\n", - "\n", - "for i, image in enumerate(digits.images[random_indices]):\n", - " plt.subplot(1, 5, i+1)\n", - " plt.axis('off')\n", - " plt.imshow(image, cmap=plt.cm.gray_r, interpolation='nearest')\n", - " plt.title(\"Label: %d\" % digits.target[random_indices[i]])\n", - "plt.show()" - ] - }, - { - "cell_type": "code", - "execution_count": 38, - "id": "5000582f", - "metadata": { - "collapsed": false, - "editable": true - }, - "outputs": [], - "source": [ - "from tensorflow.keras.layers import Input\n", - "from tensorflow.keras.models import Sequential #This allows appending layers to existing models\n", - "from tensorflow.keras.layers import Dense #This allows defining the characteristics of a particular layer\n", - "from tensorflow.keras import optimizers #This allows using whichever optimiser we want (sgd,adam,RMSprop)\n", - "from tensorflow.keras import regularizers #This allows using whichever regularizer we want (l1,l2,l1_l2)\n", - "from tensorflow.keras.utils import to_categorical #This allows using categorical cross entropy as the cost function\n", - "\n", - "from sklearn.model_selection import train_test_split\n", - "\n", - "# one-hot representation of labels\n", - "labels = to_categorical(labels)\n", - "\n", - "# split into train and test data\n", - "train_size = 0.8\n", - "test_size = 1 - train_size\n", - "X_train, X_test, Y_train, Y_test = train_test_split(inputs, labels, train_size=train_size,\n", - " test_size=test_size)" - ] - }, - { - "cell_type": "code", - "execution_count": 39, - "id": "a473cac3", - "metadata": { - "collapsed": false, - "editable": true - }, - "outputs": [], - "source": [ - "\n", - "epochs = 100\n", - "batch_size = 100\n", - "n_neurons_layer1 = 100\n", - "n_neurons_layer2 = 50\n", - "n_categories = 10\n", - "eta_vals = np.logspace(-5, 1, 7)\n", - "lmbd_vals = np.logspace(-5, 1, 7)\n", - "def create_neural_network_keras(n_neurons_layer1, n_neurons_layer2, n_categories, eta, lmbd):\n", - " model = Sequential()\n", - " model.add(Dense(n_neurons_layer1, activation='sigmoid', kernel_regularizer=regularizers.l2(lmbd)))\n", - " model.add(Dense(n_neurons_layer2, activation='sigmoid', kernel_regularizer=regularizers.l2(lmbd)))\n", - " model.add(Dense(n_categories, activation='softmax'))\n", - " \n", - " sgd = optimizers.SGD(lr=eta)\n", - " model.compile(loss='categorical_crossentropy', optimizer=sgd, metrics=['accuracy'])\n", - " \n", - " return model" - ] - }, - { - "cell_type": "code", - "execution_count": 40, - "id": "041ff977", - "metadata": { - "collapsed": false, - "editable": true - }, - "outputs": [], - "source": [ - "DNN_keras = np.zeros((len(eta_vals), len(lmbd_vals)), dtype=object)\n", - " \n", - "for i, eta in enumerate(eta_vals):\n", - " for j, lmbd in enumerate(lmbd_vals):\n", - " DNN = create_neural_network_keras(n_neurons_layer1, n_neurons_layer2, n_categories,\n", - " eta=eta, lmbd=lmbd)\n", - " DNN.fit(X_train, Y_train, epochs=epochs, batch_size=batch_size, verbose=0)\n", - " scores = DNN.evaluate(X_test, Y_test)\n", - " \n", - " DNN_keras[i][j] = DNN\n", - " \n", - " print(\"Learning rate = \", eta)\n", - " print(\"Lambda = \", lmbd)\n", - " print(\"Test accuracy: %.3f\" % scores[1])\n", - " print()" - ] - }, - { - "cell_type": "code", - "execution_count": 41, - "id": "1821d39d", - "metadata": { - "collapsed": false, - "editable": true - }, - "outputs": [], - "source": [ - "# optional\n", - "# visual representation of grid search\n", - "# uses seaborn heatmap, could probably do this in matplotlib\n", - "import seaborn as sns\n", - "\n", - "sns.set()\n", - "\n", - "train_accuracy = np.zeros((len(eta_vals), len(lmbd_vals)))\n", - "test_accuracy = np.zeros((len(eta_vals), len(lmbd_vals)))\n", - "\n", - "for i in range(len(eta_vals)):\n", - " for j in range(len(lmbd_vals)):\n", - " DNN = DNN_keras[i][j]\n", - "\n", - " train_accuracy[i][j] = DNN.evaluate(X_train, Y_train)[1]\n", - " test_accuracy[i][j] = DNN.evaluate(X_test, Y_test)[1]\n", - "\n", - " \n", - "fig, ax = plt.subplots(figsize = (10, 10))\n", - "sns.heatmap(train_accuracy, annot=True, ax=ax, cmap=\"viridis\")\n", - "ax.set_title(\"Training Accuracy\")\n", - "ax.set_ylabel(\"$\\eta$\")\n", - "ax.set_xlabel(\"$\\lambda$\")\n", - "plt.show()\n", - "\n", - "fig, ax = plt.subplots(figsize = (10, 10))\n", - "sns.heatmap(test_accuracy, annot=True, ax=ax, cmap=\"viridis\")\n", - "ax.set_title(\"Test Accuracy\")\n", - "ax.set_ylabel(\"$\\eta$\")\n", - "ax.set_xlabel(\"$\\lambda$\")\n", - "plt.show()" - ] - }, - { - "cell_type": "markdown", - "id": "c8b43dbc", - "metadata": { - "editable": true - }, - "source": [ - "## The Breast Cancer Data, now with Keras" - ] - }, - { - "cell_type": "code", - "execution_count": 42, - "id": "f902c476", - "metadata": { - "collapsed": false, - "editable": true - }, - "outputs": [], - "source": [ - "\n", - "import tensorflow as tf\n", - "from tensorflow.keras.layers import Input\n", - "from tensorflow.keras.models import Sequential #This allows appending layers to existing models\n", - "from tensorflow.keras.layers import Dense #This allows defining the characteristics of a particular layer\n", - "from tensorflow.keras import optimizers #This allows using whichever optimiser we want (sgd,adam,RMSprop)\n", - "from tensorflow.keras import regularizers #This allows using whichever regularizer we want (l1,l2,l1_l2)\n", - "from tensorflow.keras.utils import to_categorical #This allows using categorical cross entropy as the cost function\n", - "import numpy as np\n", - "import matplotlib.pyplot as plt\n", - "import seaborn as sns\n", - "from sklearn.model_selection import train_test_split as splitter\n", - "from sklearn.datasets import load_breast_cancer\n", - "import pickle\n", - "import os \n", - "\n", - "\n", - "\"\"\"Load breast cancer dataset\"\"\"\n", - "\n", - "np.random.seed(0) #create same seed for random number every time\n", - "\n", - "cancer=load_breast_cancer() #Download breast cancer dataset\n", - "\n", - "inputs=cancer.data #Feature matrix of 569 rows (samples) and 30 columns (parameters)\n", - "outputs=cancer.target #Label array of 569 rows (0 for benign and 1 for malignant)\n", - "labels=cancer.feature_names[0:30]\n", - "\n", - "print('The content of the breast cancer dataset is:') #Print information about the datasets\n", - "print(labels)\n", - "print('-------------------------')\n", - "print(\"inputs = \" + str(inputs.shape))\n", - "print(\"outputs = \" + str(outputs.shape))\n", - "print(\"labels = \"+ str(labels.shape))\n", - "\n", - "x=inputs #Reassign the Feature and Label matrices to other variables\n", - "y=outputs\n", - "\n", - "#%% \n", - "\n", - "# Visualisation of dataset (for correlation analysis)\n", - "\n", - "plt.figure()\n", - "plt.scatter(x[:,0],x[:,2],s=40,c=y,cmap=plt.cm.Spectral)\n", - "plt.xlabel('Mean radius',fontweight='bold')\n", - "plt.ylabel('Mean perimeter',fontweight='bold')\n", - "plt.show()\n", - "\n", - "plt.figure()\n", - "plt.scatter(x[:,5],x[:,6],s=40,c=y, cmap=plt.cm.Spectral)\n", - "plt.xlabel('Mean compactness',fontweight='bold')\n", - "plt.ylabel('Mean concavity',fontweight='bold')\n", - "plt.show()\n", - "\n", - "\n", - "plt.figure()\n", - "plt.scatter(x[:,0],x[:,1],s=40,c=y,cmap=plt.cm.Spectral)\n", - "plt.xlabel('Mean radius',fontweight='bold')\n", - "plt.ylabel('Mean texture',fontweight='bold')\n", - "plt.show()\n", - "\n", - "plt.figure()\n", - "plt.scatter(x[:,2],x[:,1],s=40,c=y,cmap=plt.cm.Spectral)\n", - "plt.xlabel('Mean perimeter',fontweight='bold')\n", - "plt.ylabel('Mean compactness',fontweight='bold')\n", - "plt.show()\n", - "\n", - "\n", - "# Generate training and testing datasets\n", - "\n", - "#Select features relevant to classification (texture,perimeter,compactness and symmetery) \n", - "#and add to input matrix\n", - "\n", - "temp1=np.reshape(x[:,1],(len(x[:,1]),1))\n", - "temp2=np.reshape(x[:,2],(len(x[:,2]),1))\n", - "X=np.hstack((temp1,temp2)) \n", - "temp=np.reshape(x[:,5],(len(x[:,5]),1))\n", - "X=np.hstack((X,temp)) \n", - "temp=np.reshape(x[:,8],(len(x[:,8]),1))\n", - "X=np.hstack((X,temp)) \n", - "\n", - "X_train,X_test,y_train,y_test=splitter(X,y,test_size=0.1) #Split datasets into training and testing\n", - "\n", - "y_train=to_categorical(y_train) #Convert labels to categorical when using categorical cross entropy\n", - "y_test=to_categorical(y_test)\n", - "\n", - "del temp1,temp2,temp\n", - "\n", - "# %%\n", - "\n", - "# Define tunable parameters\"\n", - "\n", - "eta=np.logspace(-3,-1,3) #Define vector of learning rates (parameter to SGD optimiser)\n", - "lamda=0.01 #Define hyperparameter\n", - "n_layers=2 #Define number of hidden layers in the model\n", - "n_neuron=np.logspace(0,3,4,dtype=int) #Define number of neurons per layer\n", - "epochs=100 #Number of reiterations over the input data\n", - "batch_size=100 #Number of samples per gradient update\n", - "\n", - "# %%\n", - "\n", - "\"\"\"Define function to return Deep Neural Network model\"\"\"\n", - "\n", - "def NN_model(inputsize,n_layers,n_neuron,eta,lamda):\n", - " model=Sequential() \n", - " for i in range(n_layers): #Run loop to add hidden layers to the model\n", - " if (i==0): #First layer requires input dimensions\n", - " model.add(Dense(n_neuron,activation='relu',kernel_regularizer=regularizers.l2(lamda),input_dim=inputsize))\n", - " else: #Subsequent layers are capable of automatic shape inferencing\n", - " model.add(Dense(n_neuron,activation='relu',kernel_regularizer=regularizers.l2(lamda)))\n", - " model.add(Dense(2,activation='softmax')) #2 outputs - ordered and disordered (softmax for prob)\n", - " sgd=optimizers.SGD(lr=eta)\n", - " model.compile(loss='categorical_crossentropy',optimizer=sgd,metrics=['accuracy'])\n", - " return model\n", - "\n", - " \n", - "Train_accuracy=np.zeros((len(n_neuron),len(eta))) #Define matrices to store accuracy scores as a function\n", - "Test_accuracy=np.zeros((len(n_neuron),len(eta))) #of learning rate and number of hidden neurons for \n", - "\n", - "for i in range(len(n_neuron)): #run loops over hidden neurons and learning rates to calculate \n", - " for j in range(len(eta)): #accuracy scores \n", - " DNN_model=NN_model(X_train.shape[1],n_layers,n_neuron[i],eta[j],lamda)\n", - " DNN_model.fit(X_train,y_train,epochs=epochs,batch_size=batch_size,verbose=1)\n", - " Train_accuracy[i,j]=DNN_model.evaluate(X_train,y_train)[1]\n", - " Test_accuracy[i,j]=DNN_model.evaluate(X_test,y_test)[1]\n", - " \n", - "\n", - "def plot_data(x,y,data,title=None):\n", - "\n", - " # plot results\n", - " fontsize=16\n", - "\n", - "\n", - " fig = plt.figure()\n", - " ax = fig.add_subplot(111)\n", - " cax = ax.matshow(data, interpolation='nearest', vmin=0, vmax=1)\n", - " \n", - " cbar=fig.colorbar(cax)\n", - " cbar.ax.set_ylabel('accuracy (%)',rotation=90,fontsize=fontsize)\n", - " cbar.set_ticks([0,.2,.4,0.6,0.8,1.0])\n", - " cbar.set_ticklabels(['0%','20%','40%','60%','80%','100%'])\n", - "\n", - " # put text on matrix elements\n", - " for i, x_val in enumerate(np.arange(len(x))):\n", - " for j, y_val in enumerate(np.arange(len(y))):\n", - " c = \"${0:.1f}\\\\%$\".format( 100*data[j,i]) \n", - " ax.text(x_val, y_val, c, va='center', ha='center')\n", - "\n", - " # convert axis vaues to to string labels\n", - " x=[str(i) for i in x]\n", - " y=[str(i) for i in y]\n", - "\n", - "\n", - " ax.set_xticklabels(['']+x)\n", - " ax.set_yticklabels(['']+y)\n", - "\n", - " ax.set_xlabel('$\\\\mathrm{learning\\\\ rate}$',fontsize=fontsize)\n", - " ax.set_ylabel('$\\\\mathrm{hidden\\\\ neurons}$',fontsize=fontsize)\n", - " if title is not None:\n", - " ax.set_title(title)\n", - "\n", - " plt.tight_layout()\n", - "\n", - " plt.show()\n", - " \n", - "plot_data(eta,n_neuron,Train_accuracy, 'training')\n", - "plot_data(eta,n_neuron,Test_accuracy, 'testing')" - ] - }, - { - "cell_type": "markdown", - "id": "fa673f3a", - "metadata": { - "editable": true - }, - "source": [ - "## Fine-tuning neural network hyperparameters\n", - "\n", - "The flexibility of neural networks is also one of their main\n", - "drawbacks: there are many hyperparameters to tweak. Not only can you\n", - "use any imaginable network topology (how neurons/nodes are interconnected),\n", - "but even in a simple FFNN you can change the number of layers, the\n", - "number of neurons per layer, the type of activation function to use in\n", - "each layer, the weight initialization logic, the stochastic gradient optmized and much more. How do you\n", - "know what combination of hyperparameters is the best for your task?\n", - "\n", - "* You can use grid search with cross-validation to find the right hyperparameters.\n", - "\n", - "However,since there are many hyperparameters to tune, and since\n", - "training a neural network on a large dataset takes a lot of time, you\n", - "will only be able to explore a tiny part of the hyperparameter space.\n", - "\n", - "* You can use randomized search.\n", - "\n", - "* Or use tools like [Oscar](http://oscar.calldesk.ai/), which implements more complex algorithms to help you find a good set of hyperparameters quickly." - ] - }, - { - "cell_type": "markdown", - "id": "6c4727a9", - "metadata": { - "editable": true - }, - "source": [ - "## Hidden layers\n", - "\n", - "For many problems you can start with just one or two hidden layers and it will work just fine.\n", - "For the MNIST data set you ca easily get a high accuracy using just one hidden layer with a\n", - "few hundred neurons.\n", - "You can reach for this data set above 98% accuracy using two hidden layers with the same total amount of\n", - "neurons, in roughly the same amount of training time. \n", - "\n", - "For more complex problems, you can gradually\n", - "ramp up the number of hidden layers, until you start overfitting the training set. Very complex tasks, such\n", - "as large image classification or speech recognition, typically require networks with dozens of layers\n", - "and they need a huge amount\n", - "of training data. However, you will rarely have to train such networks from scratch: it is much more\n", - "common to reuse parts of a pretrained state-of-the-art network that performs a similar task." - ] - }, - { - "cell_type": "markdown", - "id": "f24d5df1", - "metadata": { - "editable": true - }, - "source": [ - "## Which activation function should I use?\n", - "\n", - "The Back propagation algorithm we derived above works by going from\n", - "the output layer to the input layer, propagating the error gradient on\n", - "the way. Once the algorithm has computed the gradient of the cost\n", - "function with regards to each parameter in the network, it uses these\n", - "gradients to update each parameter with a Gradient Descent (GD) step.\n", - "\n", - "Unfortunately for us, the gradients often get smaller and smaller as the\n", - "algorithm progresses down to the first hidden layers. As a result, the\n", - "GD update leaves the lower layer connection weights\n", - "virtually unchanged, and training never converges to a good\n", - "solution. This is known in the literature as \n", - "**the vanishing gradients problem**. \n", - "\n", - "In other cases, the opposite can happen, namely the the gradients can grow bigger and\n", - "bigger. The result is that many of the layers get large updates of the \n", - "weights the\n", - "algorithm diverges. This is the **exploding gradients problem**, which is\n", - "mostly encountered in recurrent neural networks. More generally, deep\n", - "neural networks suffer from unstable gradients, different layers may\n", - "learn at widely different speeds" - ] - }, - { - "cell_type": "markdown", - "id": "80cd048d", - "metadata": { - "editable": true - }, - "source": [ - "## Is the Logistic activation function (Sigmoid) our choice?\n", - "\n", - "Although this unfortunate behavior has been empirically observed for\n", - "quite a while (it was one of the reasons why deep neural networks were\n", - "mostly abandoned for a long time), it is only around 2010 that\n", - "significant progress was made in understanding it.\n", - "\n", - "A paper titled [Understanding the Difficulty of Training Deep\n", - "Feedforward Neural Networks by Xavier Glorot and Yoshua Bengio](http://proceedings.mlr.press/v9/glorot10a.html) found that\n", - "the problems with the popular logistic\n", - "sigmoid activation function and the weight initialization technique\n", - "that was most popular at the time, namely random initialization using\n", - "a normal distribution with a mean of 0 and a standard deviation of\n", - "1. \n", - "\n", - "They showed that with this activation function and this\n", - "initialization scheme, the variance of the outputs of each layer is\n", - "much greater than the variance of its inputs. Going forward in the\n", - "network, the variance keeps increasing after each layer until the\n", - "activation function saturates at the top layers. This is actually made\n", - "worse by the fact that the logistic function has a mean of 0.5, not 0\n", - "(the hyperbolic tangent function has a mean of 0 and behaves slightly\n", - "better than the logistic function in deep networks)." - ] - }, - { - "cell_type": "markdown", - "id": "6863dde1", - "metadata": { - "editable": true - }, - "source": [ - "## The derivative of the Logistic funtion\n", - "\n", - "Looking at the logistic activation function, when inputs become large\n", - "(negative or positive), the function saturates at 0 or 1, with a\n", - "derivative extremely close to 0. Thus when backpropagation kicks in,\n", - "it has virtually no gradient to propagate back through the network,\n", - "and what little gradient exists keeps getting diluted as\n", - "backpropagation progresses down through the top layers, so there is\n", - "really nothing left for the lower layers.\n", - "\n", - "In their paper, Glorot and Bengio propose a way to significantly\n", - "alleviate this problem. We need the signal to flow properly in both\n", - "directions: in the forward direction when making predictions, and in\n", - "the reverse direction when backpropagating gradients. We don’t want\n", - "the signal to die out, nor do we want it to explode and saturate. For\n", - "the signal to flow properly, the authors argue that we need the\n", - "variance of the outputs of each layer to be equal to the variance of\n", - "its inputs, and we also need the gradients to have equal variance\n", - "before and after flowing through a layer in the reverse direction.\n", - "\n", - "One of the insights in the 2010 paper by Glorot and Bengio was that\n", - "the vanishing/exploding gradients problems were in part due to a poor\n", - "choice of activation function. Until then most people had assumed that\n", - "if Nature had chosen to use roughly sigmoid activation functions in\n", - "biological neurons, they must be an excellent choice. But it turns out\n", - "that other activation functions behave much better in deep neural\n", - "networks, in particular the ReLU activation function, mostly because\n", - "it does not saturate for positive values (and also because it is quite\n", - "fast to compute)." - ] - }, - { - "cell_type": "markdown", - "id": "95f03af7", - "metadata": { - "editable": true - }, - "source": [ - "## The RELU function family\n", - "\n", - "The ReLU activation function suffers from a problem known as the dying\n", - "ReLUs: during training, some neurons effectively die, meaning they\n", - "stop outputting anything other than 0.\n", - "\n", - "In some cases, you may find that half of your network’s neurons are\n", - "dead, especially if you used a large learning rate. During training,\n", - "if a neuron’s weights get updated such that the weighted sum of the\n", - "neuron’s inputs is negative, it will start outputting 0. When this\n", - "happen, the neuron is unlikely to come back to life since the gradient\n", - "of the ReLU function is 0 when its input is negative.\n", - "\n", - "To solve this problem, nowadays practitioners use a variant of the ReLU\n", - "function, such as the leaky ReLU discussed above or the so-called\n", - "exponential linear unit (ELU) function" - ] - }, - { - "cell_type": "markdown", - "id": "620cac32", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "ELU(z) = \\left\\{\\begin{array}{cc} \\alpha\\left( \\exp{(z)}-1\\right) & z < 0,\\\\ z & z \\ge 0.\\end{array}\\right.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "2dd91f71", - "metadata": { - "editable": true - }, - "source": [ - "## Which activation function should we use?\n", - "\n", - "In general it seems that the ELU activation function is better than\n", - "the leaky ReLU function (and its variants), which is better than\n", - "ReLU. ReLU performs better than $\\tanh$ which in turn performs better\n", - "than the logistic function. \n", - "\n", - "If runtime\n", - "performance is an issue, then you may opt for the leaky ReLU function over the \n", - "ELU function If you don’t\n", - "want to tweak yet another hyperparameter, you may just use the default\n", - "$\\alpha$ of $0.01$ for the leaky ReLU, and $1$ for ELU. If you have\n", - "spare time and computing power, you can use cross-validation or\n", - "bootstrap to evaluate other activation functions." - ] - }, - { - "cell_type": "markdown", - "id": "bfa3871c", - "metadata": { - "editable": true - }, - "source": [ - "## More on activation functions, output layers\n", - "\n", - "In most cases you can use the ReLU activation function in the hidden layers (or one of its variants).\n", - "\n", - "It is a bit faster to compute than other activation functions, and the gradient descent optimization does in general not get stuck.\n", - "\n", - "**For the output layer:**\n", - "\n", - "* For classification the softmax activation function is generally a good choice for classification tasks (when the classes are mutually exclusive).\n", - "\n", - "* For regression tasks, you can simply use no activation function at all." - ] - }, - { - "cell_type": "markdown", - "id": "9315a3fc", - "metadata": { - "editable": true - }, - "source": [ - "## Batch Normalization\n", - "\n", - "Batch Normalization\n", - "aims to address the vanishing/exploding gradients problems, and more generally the problem that the\n", - "distribution of each layer’s inputs changes during training, as the parameters of the previous layers change.\n", - "\n", - "The technique consists of adding an operation in the model just before the activation function of each\n", - "layer, simply zero-centering and normalizing the inputs, then scaling and shifting the result using two new\n", - "parameters per layer (one for scaling, the other for shifting). In other words, this operation lets the model\n", - "learn the optimal scale and mean of the inputs for each layer.\n", - "In order to zero-center and normalize the inputs, the algorithm needs to estimate the inputs’ mean and\n", - "standard deviation. It does so by evaluating the mean and standard deviation of the inputs over the current\n", - "mini-batch, from this the name batch normalization." - ] - }, - { - "cell_type": "markdown", - "id": "85eb5069", - "metadata": { - "editable": true - }, - "source": [ - "## Dropout\n", - "\n", - "It is a fairly simple algorithm: at every training step, every neuron (including the input neurons but\n", - "excluding the output neurons) has a probability $p$ of being temporarily dropped out, meaning it will be\n", - "entirely ignored during this training step, but it may be active during the next step.\n", - "\n", - "The\n", - "hyperparameter $p$ is called the dropout rate, and it is typically set to 50%. After training, the neurons are not dropped anymore.\n", - " It is viewed as one of the most popular regularization techniques." - ] - }, - { - "cell_type": "markdown", - "id": "d2d08622", - "metadata": { - "editable": true - }, - "source": [ - "## Gradient Clipping\n", - "\n", - "A popular technique to lessen the exploding gradients problem is to simply clip the gradients during\n", - "backpropagation so that they never exceed some threshold (this is mostly useful for recurrent neural\n", - "networks).\n", - "\n", - "This technique is called Gradient Clipping.\n", - "\n", - "In general however, Batch\n", - "Normalization is preferred." - ] - }, - { - "cell_type": "markdown", - "id": "566bcca7", - "metadata": { - "editable": true - }, - "source": [ - "## A very nice website on Neural Networks\n", - "\n", - "You may find this [website](https://playground.tensorflow.org/#activation=tanh&batchSize=10&dataset=circle®Dataset=reg-plane&learningRate=0.03®ularizationRate=0&noise=0&networkShape=4,2&seed=0.29243&showTestData=false&discretize=false&percTrainData=50&x=true&y=true&xTimesY=false&xSquared=false&ySquared=false&cosX=false&sinX=false&cosY=false&sinY=false&collectStats=false&problem=classification&initZero=false&hideText=false) very useful." - ] - }, - { - "cell_type": "markdown", - "id": "aedf225e", - "metadata": { - "editable": true - }, - "source": [ - "## A top-down perspective on Neural networks\n", - "\n", - "The first thing we would like to do is divide the data into two or three\n", - "parts. A training set, a validation or dev (development) set, and a\n", - "test set. The test set is the data on which we want to make\n", - "predictions. The dev set is a subset of the training data we use to\n", - "check how well we are doing out-of-sample, after training the model on\n", - "the training dataset. We use the validation error as a proxy for the\n", - "test error in order to make tweaks to our model. It is crucial that we\n", - "do not use any of the test data to train the algorithm. This is a\n", - "cardinal sin in ML. Then:\n", - "\n", - "* Estimate optimal error rate\n", - "\n", - "* Minimize underfitting (bias) on training data set.\n", - "\n", - "* Make sure you are not overfitting.\n", - "\n", - "If the validation and test sets are drawn from the same distributions,\n", - "then a good performance on the validation set should lead to similarly\n", - "good performance on the test set. \n", - "\n", - "However, sometimes\n", - "the training data and test data differ in subtle ways because, for\n", - "example, they are collected using slightly different methods, or\n", - "because it is cheaper to collect data in one way versus another. In\n", - "this case, there can be a mismatch between the training and test\n", - "data. This can lead to the neural network overfitting these small\n", - "differences between the test and training sets, and a poor performance\n", - "on the test set despite having a good performance on the validation\n", - "set. To rectify this, Andrew Ng suggests making two validation or dev\n", - "sets, one constructed from the training data and one constructed from\n", - "the test data. The difference between the performance of the algorithm\n", - "on these two validation sets quantifies the train-test mismatch. This\n", - "can serve as another important diagnostic when using DNNs for\n", - "supervised learning." - ] - }, - { - "cell_type": "markdown", - "id": "8723e9ba", - "metadata": { - "editable": true - }, - "source": [ - "## Limitations of supervised learning with deep networks\n", - "\n", - "Like all statistical methods, supervised learning using neural\n", - "networks has important limitations. This is especially important when\n", - "one seeks to apply these methods, especially to physics problems. Like\n", - "all tools, DNNs are not a universal solution. Often, the same or\n", - "better performance on a task can be achieved by using a few\n", - "hand-engineered features (or even a collection of random\n", - "features). \n", - "\n", - "Here we list some of the important limitations of supervised neural network based models. \n", - "\n", - "* **Need labeled data**. All supervised learning methods, DNNs for supervised learning require labeled data. Often, labeled data is harder to acquire than unlabeled data (e.g. one must pay for human experts to label images).\n", - "\n", - "* **Supervised neural networks are extremely data intensive.** DNNs are data hungry. They perform best when data is plentiful. This is doubly so for supervised methods where the data must also be labeled. The utility of DNNs is extremely limited if data is hard to acquire or the datasets are small (hundreds to a few thousand samples). In this case, the performance of other methods that utilize hand-engineered features can exceed that of DNNs.\n", - "\n", - "* **Homogeneous data.** Almost all DNNs deal with homogeneous data of one type. It is very hard to design architectures that mix and match data types (i.e. some continuous variables, some discrete variables, some time series). In applications beyond images, video, and language, this is often what is required. In contrast, ensemble models like random forests or gradient-boosted trees have no difficulty handling mixed data types.\n", - "\n", - "* **Many problems are not about prediction.** In natural science we are often interested in learning something about the underlying distribution that generates the data. In this case, it is often difficult to cast these ideas in a supervised learning setting. While the problems are related, it is possible to make good predictions with a *wrong* model. The model might or might not be useful for understanding the underlying science.\n", - "\n", - "Some of these remarks are particular to DNNs, others are shared by all supervised learning methods. This motivates the use of unsupervised methods which in part circumvent these problems." - ] - }, - { - "cell_type": "markdown", - "id": "b641b576", - "metadata": { - "editable": true - }, - "source": [ - "## Solving ODEs with Deep Learning\n", - "\n", - "The Universal Approximation Theorem states that a neural network can\n", - "approximate any function at a single hidden layer along with one input\n", - "and output layer to any given precision.\n", - "\n", - "**Book on solving differential equations with ML methods.**\n", - "\n", - "[An Introduction to Neural Network Methods for Differential Equations](https://www.springer.com/gp/book/9789401798150), by Yadav and Kumar.\n", - "\n", - "**Master thesis on applying deep learning to problems in mechanics.**\n", - "\n", - "[Using Deep Reinforcement Learning for Active Flow Control](https://www.duo.uio.no/handle/10852/79212), by Marius Holm\n", - "\n", - "**Thanks to Kristine Baluka Hein.**\n", - "\n", - "The lectures on differential equations were developed by Kristine Baluka Hein, now PhD student at IFI.\n", - "A great thanks to Kristine." - ] - }, - { - "cell_type": "markdown", - "id": "e919d2c8", - "metadata": { - "editable": true - }, - "source": [ - "## Ordinary Differential Equations\n", - "\n", - "An ordinary differential equation (ODE) is an equation involving functions having one variable.\n", - "\n", - "In general, an ordinary differential equation looks like" - ] - }, - { - "cell_type": "markdown", - "id": "12b84451", - "metadata": { - "editable": true - }, - "source": [ - "\n", - "
\n", - "\n", - "$$\n", - "\\begin{equation} \\label{ode} \\tag{1}\n", - "f\\left(x, \\, g(x), \\, g'(x), \\, g''(x), \\, \\dots \\, , \\, g^{(n)}(x)\\right) = 0\n", - "\\end{equation}\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "88407501", - "metadata": { - "editable": true - }, - "source": [ - "where $g(x)$ is the function to find, and $g^{(n)}(x)$ is the $n$-th derivative of $g(x)$.\n", - "\n", - "The $f\\left(x, g(x), g'(x), g''(x), \\, \\dots \\, , g^{(n)}(x)\\right)$ is just a way to write that there is an expression involving $x$ and $g(x), \\ g'(x), \\ g''(x), \\, \\dots \\, , \\text{ and } g^{(n)}(x)$ on the left side of the equality sign in ([1](#ode)).\n", - "The highest order of derivative, that is the value of $n$, determines to the order of the equation.\n", - "The equation is referred to as a $n$-th order ODE.\n", - "Along with ([1](#ode)), some additional conditions of the function $g(x)$ are typically given\n", - "for the solution to be unique." - ] - }, - { - "cell_type": "markdown", - "id": "034cef5e", - "metadata": { - "editable": true - }, - "source": [ - "## The trial solution\n", - "\n", - "Let the trial solution $g_t(x)$ be" - ] - }, - { - "cell_type": "markdown", - "id": "86693b23", - "metadata": { - "editable": true - }, - "source": [ - "\n", - "
\n", - "\n", - "$$\n", - "\\begin{equation}\n", - "\tg_t(x) = h_1(x) + h_2(x,N(x,P))\n", - "\\label{_auto1} \\tag{2}\n", - "\\end{equation}\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "5c8e1418", - "metadata": { - "editable": true - }, - "source": [ - "where $h_1(x)$ is a function that makes $g_t(x)$ satisfy a given set\n", - "of conditions, $N(x,P)$ a neural network with weights and biases\n", - "described by $P$ and $h_2(x, N(x,P))$ some expression involving the\n", - "neural network. The role of the function $h_2(x, N(x,P))$, is to\n", - "ensure that the output from $N(x,P)$ is zero when $g_t(x)$ is\n", - "evaluated at the values of $x$ where the given conditions must be\n", - "satisfied. The function $h_1(x)$ should alone make $g_t(x)$ satisfy\n", - "the conditions.\n", - "\n", - "But what about the network $N(x,P)$?\n", - "\n", - "As described previously, an optimization method could be used to minimize the parameters of a neural network, that being its weights and biases, through backward propagation." - ] - }, - { - "cell_type": "markdown", - "id": "4ca42ad5", - "metadata": { - "editable": true - }, - "source": [ - "## Minimization process\n", - "\n", - "For the minimization to be defined, we need to have a cost function at hand to minimize.\n", - "\n", - "It is given that $f\\left(x, \\, g(x), \\, g'(x), \\, g''(x), \\, \\dots \\, , \\, g^{(n)}(x)\\right)$ should be equal to zero in ([1](#ode)).\n", - "We can choose to consider the mean squared error as the cost function for an input $x$.\n", - "Since we are looking at one input, the cost function is just $f$ squared.\n", - "The cost function $c\\left(x, P \\right)$ can therefore be expressed as" - ] - }, - { - "cell_type": "markdown", - "id": "a0808029", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "C\\left(x, P\\right) = \\big(f\\left(x, \\, g(x), \\, g'(x), \\, g''(x), \\, \\dots \\, , \\, g^{(n)}(x)\\right)\\big)^2\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "8e242ee9", - "metadata": { - "editable": true - }, - "source": [ - "If $N$ inputs are given as a vector $\\boldsymbol{x}$ with elements $x_i$ for $i = 1,\\dots,N$,\n", - "the cost function becomes" - ] - }, - { - "cell_type": "markdown", - "id": "6cb613c0", - "metadata": { - "editable": true - }, - "source": [ - "\n", - "
\n", - "\n", - "$$\n", - "\\begin{equation} \\label{cost} \\tag{3}\n", - "\tC\\left(\\boldsymbol{x}, P\\right) = \\frac{1}{N} \\sum_{i=1}^N \\big(f\\left(x_i, \\, g(x_i), \\, g'(x_i), \\, g''(x_i), \\, \\dots \\, , \\, g^{(n)}(x_i)\\right)\\big)^2\n", - "\\end{equation}\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "ff0ace15", - "metadata": { - "editable": true - }, - "source": [ - "The neural net should then find the parameters $P$ that minimizes the cost function in\n", - "([3](#cost)) for a set of $N$ training samples $x_i$." - ] - }, - { - "cell_type": "markdown", - "id": "d77df59b", - "metadata": { - "editable": true - }, - "source": [ - "## Minimizing the cost function using gradient descent and automatic differentiation\n", - "\n", - "To perform the minimization using gradient descent, the gradient of $C\\left(\\boldsymbol{x}, P\\right)$ is needed.\n", - "It might happen so that finding an analytical expression of the gradient of $C(\\boldsymbol{x}, P)$ from ([3](#cost)) gets too messy, depending on which cost function one desires to use.\n", - "\n", - "Luckily, there exists libraries that makes the job for us through automatic differentiation.\n", - "Automatic differentiation is a method of finding the derivatives numerically with very high precision." - ] - }, - { - "cell_type": "markdown", - "id": "b34fce14", - "metadata": { - "editable": true - }, - "source": [ - "## Example: Exponential decay\n", - "\n", - "An exponential decay of a quantity $g(x)$ is described by the equation" - ] - }, - { - "cell_type": "markdown", - "id": "290ed299", - "metadata": { - "editable": true - }, - "source": [ - "\n", - "
\n", - "\n", - "$$\n", - "\\begin{equation} \\label{solve_expdec} \\tag{4}\n", - " g'(x) = -\\gamma g(x)\n", - "\\end{equation}\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "d386881a", - "metadata": { - "editable": true - }, - "source": [ - "with $g(0) = g_0$ for some chosen initial value $g_0$.\n", - "\n", - "The analytical solution of ([4](#solve_expdec)) is" - ] - }, - { - "cell_type": "markdown", - "id": "cf4aca15", - "metadata": { - "editable": true - }, - "source": [ - "\n", - "
\n", - "\n", - "$$\n", - "\\begin{equation}\n", - " g(x) = g_0 \\exp\\left(-\\gamma x\\right)\n", - "\\label{_auto2} \\tag{5}\n", - "\\end{equation}\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "ee5531c2", - "metadata": { - "editable": true - }, - "source": [ - "Having an analytical solution at hand, it is possible to use it to compare how well a neural network finds a solution of ([4](#solve_expdec))." - ] - }, - { - "cell_type": "markdown", - "id": "64a52bc0", - "metadata": { - "editable": true - }, - "source": [ - "## The function to solve for\n", - "\n", - "The program will use a neural network to solve" - ] - }, - { - "cell_type": "markdown", - "id": "e0154c0f", - "metadata": { - "editable": true - }, - "source": [ - "\n", - "
\n", - "\n", - "$$\n", - "\\begin{equation} \\label{solveode} \\tag{6}\n", - "g'(x) = -\\gamma g(x)\n", - "\\end{equation}\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "334e7f10", - "metadata": { - "editable": true - }, - "source": [ - "where $g(0) = g_0$ with $\\gamma$ and $g_0$ being some chosen values.\n", - "\n", - "In this example, $\\gamma = 2$ and $g_0 = 10$." - ] - }, - { - "cell_type": "markdown", - "id": "66c1d55c", - "metadata": { - "editable": true - }, - "source": [ - "## The trial solution\n", - "To begin with, a trial solution $g_t(t)$ must be chosen. A general trial solution for ordinary differential equations could be" - ] - }, - { - "cell_type": "markdown", - "id": "f03c7338", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "g_t(x, P) = h_1(x) + h_2(x, N(x, P))\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "ca114c87", - "metadata": { - "editable": true - }, - "source": [ - "with $h_1(x)$ ensuring that $g_t(x)$ satisfies some conditions and $h_2(x,N(x, P))$ an expression involving $x$ and the output from the neural network $N(x,P)$ with $P $ being the collection of the weights and biases for each layer. For now, it is assumed that the network consists of one input layer, one hidden layer, and one output layer." - ] - }, - { - "cell_type": "markdown", - "id": "801219a0", - "metadata": { - "editable": true - }, - "source": [ - "## Setup of Network\n", - "\n", - "In this network, there are no weights and bias at the input layer, so $P = \\{ P_{\\text{hidden}}, P_{\\text{output}} \\}$.\n", - "If there are $N_{\\text{hidden} }$ neurons in the hidden layer, then $P_{\\text{hidden}}$ is a $N_{\\text{hidden} } \\times (1 + N_{\\text{input}})$ matrix, given that there are $N_{\\text{input}}$ neurons in the input layer.\n", - "\n", - "The first column in $P_{\\text{hidden} }$ represents the bias for each neuron in the hidden layer and the second column represents the weights for each neuron in the hidden layer from the input layer.\n", - "If there are $N_{\\text{output} }$ neurons in the output layer, then $P_{\\text{output}} $ is a $N_{\\text{output} } \\times (1 + N_{\\text{hidden} })$ matrix.\n", - "\n", - "Its first column represents the bias of each neuron and the remaining columns represents the weights to each neuron.\n", - "\n", - "It is given that $g(0) = g_0$. The trial solution must fulfill this condition to be a proper solution of ([6](#solveode)). A possible way to ensure that $g_t(0, P) = g_0$, is to let $F(N(x,P)) = x \\cdot N(x,P)$ and $A(x) = g_0$. This gives the following trial solution:" - ] - }, - { - "cell_type": "markdown", - "id": "569486c4", - "metadata": { - "editable": true - }, - "source": [ - "\n", - "
\n", - "\n", - "$$\n", - "\\begin{equation} \\label{trial} \\tag{7}\n", - "g_t(x, P) = g_0 + x \\cdot N(x, P)\n", - "\\end{equation}\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "575831d8", - "metadata": { - "editable": true - }, - "source": [ - "## Reformulating the problem\n", - "\n", - "We wish that our neural network manages to minimize a given cost function.\n", - "\n", - "A reformulation of out equation, ([6](#solveode)), must therefore be done,\n", - "such that it describes the problem a neural network can solve for.\n", - "\n", - "The neural network must find the set of weights and biases $P$ such that the trial solution in ([7](#trial)) satisfies ([6](#solveode)).\n", - "\n", - "The trial solution" - ] - }, - { - "cell_type": "markdown", - "id": "f8682123", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "g_t(x, P) = g_0 + x \\cdot N(x, P)\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "e62b1005", - "metadata": { - "editable": true - }, - "source": [ - "has been chosen such that it already solves the condition $g(0) = g_0$. What remains, is to find $P$ such that" - ] - }, - { - "cell_type": "markdown", - "id": "4e33439d", - "metadata": { - "editable": true - }, - "source": [ - "\n", - "
\n", - "\n", - "$$\n", - "\\begin{equation} \\label{nnmin} \\tag{8}\n", - "g_t'(x, P) = - \\gamma g_t(x, P)\n", - "\\end{equation}\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "35159fc5", - "metadata": { - "editable": true - }, - "source": [ - "is fulfilled as *best as possible*." - ] - }, - { - "cell_type": "markdown", - "id": "03f74ead", - "metadata": { - "editable": true - }, - "source": [ - "## More technicalities\n", - "\n", - "The left hand side and right hand side of ([8](#nnmin)) must be computed separately, and then the neural network must choose weights and biases, contained in $P$, such that the sides are equal as best as possible.\n", - "This means that the absolute or squared difference between the sides must be as close to zero, ideally equal to zero.\n", - "In this case, the difference squared shows to be an appropriate measurement of how erroneous the trial solution is with respect to $P$ of the neural network.\n", - "\n", - "This gives the following cost function our neural network must solve for:" - ] - }, - { - "cell_type": "markdown", - "id": "3599c2de", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\min_{P}\\Big\\{ \\big(g_t'(x, P) - ( -\\gamma g_t(x, P) \\big)^2 \\Big\\}\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "5c50baf7", - "metadata": { - "editable": true - }, - "source": [ - "(the notation $\\min_{P}\\{ f(x, P) \\}$ means that we desire to find $P$ that yields the minimum of $f(x, P)$)\n", - "\n", - "or, in terms of weights and biases for the hidden and output layer in our network:" - ] - }, - { - "cell_type": "markdown", - "id": "636cb74c", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\min_{P_{\\text{hidden} }, \\ P_{\\text{output} }}\\Big\\{ \\big(g_t'(x, \\{ P_{\\text{hidden} }, P_{\\text{output} }\\}) - ( -\\gamma g_t(x, \\{ P_{\\text{hidden} }, P_{\\text{output} }\\}) \\big)^2 \\Big\\}\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "b4b301c2", - "metadata": { - "editable": true - }, - "source": [ - "for an input value $x$." - ] - }, - { - "cell_type": "markdown", - "id": "5d873576", - "metadata": { - "editable": true - }, - "source": [ - "## More details\n", - "\n", - "If the neural network evaluates $g_t(x, P)$ at more values for $x$, say $N$ values $x_i$ for $i = 1, \\dots, N$, then the *total* error to minimize becomes" - ] - }, - { - "cell_type": "markdown", - "id": "b744fd57", - "metadata": { - "editable": true - }, - "source": [ - "\n", - "
\n", - "\n", - "$$\n", - "\\begin{equation} \\label{min} \\tag{9}\n", - "\\min_{P}\\Big\\{\\frac{1}{N} \\sum_{i=1}^N \\big(g_t'(x_i, P) - ( -\\gamma g_t(x_i, P) \\big)^2 \\Big\\}\n", - "\\end{equation}\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "63290336", - "metadata": { - "editable": true - }, - "source": [ - "Letting $\\boldsymbol{x}$ be a vector with elements $x_i$ and $C(\\boldsymbol{x}, P) = \\frac{1}{N} \\sum_i \\big(g_t'(x_i, P) - ( -\\gamma g_t(x_i, P) \\big)^2$ denote the cost function, the minimization problem that our network must solve, becomes" - ] - }, - { - "cell_type": "markdown", - "id": "f8790d32", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\min_{P} C(\\boldsymbol{x}, P)\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "10ab609a", - "metadata": { - "editable": true - }, - "source": [ - "In terms of $P_{\\text{hidden} }$ and $P_{\\text{output} }$, this could also be expressed as\n", - "\n", - "$$\n", - "\\min_{P_{\\text{hidden} }, \\ P_{\\text{output} }} C(\\boldsymbol{x}, \\{P_{\\text{hidden} }, P_{\\text{output} }\\})\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "06e2efca", - "metadata": { - "editable": true - }, - "source": [ - "## A possible implementation of a neural network\n", - "\n", - "For simplicity, it is assumed that the input is an array $\\boldsymbol{x} = (x_1, \\dots, x_N)$ with $N$ elements. It is at these points the neural network should find $P$ such that it fulfills ([9](#min)).\n", - "\n", - "First, the neural network must feed forward the inputs.\n", - "This means that $\\boldsymbol{x}s$ must be passed through an input layer, a hidden layer and a output layer. The input layer in this case, does not need to process the data any further.\n", - "The input layer will consist of $N_{\\text{input} }$ neurons, passing its element to each neuron in the hidden layer. The number of neurons in the hidden layer will be $N_{\\text{hidden} }$." - ] - }, - { - "cell_type": "markdown", - "id": "bc8a8e04", - "metadata": { - "editable": true - }, - "source": [ - "## Technicalities\n", - "\n", - "For the $i$-th in the hidden layer with weight $w_i^{\\text{hidden} }$ and bias $b_i^{\\text{hidden} }$, the weighting from the $j$-th neuron at the input layer is:" - ] - }, - { - "cell_type": "markdown", - "id": "6564e278", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\begin{aligned}\n", - "z_{i,j}^{\\text{hidden}} &= b_i^{\\text{hidden}} + w_i^{\\text{hidden}}x_j \\\\\n", - "&=\n", - "\\begin{pmatrix}\n", - "b_i^{\\text{hidden}} & w_i^{\\text{hidden}}\n", - "\\end{pmatrix}\n", - "\\begin{pmatrix}\n", - "1 \\\\\n", - "x_j\n", - "\\end{pmatrix}\n", - "\\end{aligned}\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "f62120f5", - "metadata": { - "editable": true - }, - "source": [ - "## Final technicalities I\n", - "\n", - "The result after weighting the inputs at the $i$-th hidden neuron can be written as a vector:" - ] - }, - { - "cell_type": "markdown", - "id": "4f875005", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\begin{aligned}\n", - "\\boldsymbol{z}_{i}^{\\text{hidden}} &= \\Big( b_i^{\\text{hidden}} + w_i^{\\text{hidden}}x_1 , \\ b_i^{\\text{hidden}} + w_i^{\\text{hidden}} x_2, \\ \\dots \\, , \\ b_i^{\\text{hidden}} + w_i^{\\text{hidden}} x_N\\Big) \\\\\n", - "&=\n", - "\\begin{pmatrix}\n", - " b_i^{\\text{hidden}} & w_i^{\\text{hidden}}\n", - "\\end{pmatrix}\n", - "\\begin{pmatrix}\n", - "1 & 1 & \\dots & 1 \\\\\n", - "x_1 & x_2 & \\dots & x_N\n", - "\\end{pmatrix} \\\\\n", - "&= \\boldsymbol{p}_{i, \\text{hidden}}^T X\n", - "\\end{aligned}\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "8748bf88", - "metadata": { - "editable": true - }, - "source": [ - "## Final technicalities II\n", - "\n", - "The vector $\\boldsymbol{p}_{i, \\text{hidden}}^T$ constitutes each row in $P_{\\text{hidden} }$, which contains the weights for the neural network to minimize according to ([9](#min)).\n", - "\n", - "After having found $\\boldsymbol{z}_{i}^{\\text{hidden}} $ for every $i$-th neuron within the hidden layer, the vector will be sent to an activation function $a_i(\\boldsymbol{z})$.\n", - "\n", - "In this example, the sigmoid function has been chosen to be the activation function for each hidden neuron:" - ] - }, - { - "cell_type": "markdown", - "id": "ce8b1154", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "f(z) = \\frac{1}{1 + \\exp{(-z)}}\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "f6ae91fa", - "metadata": { - "editable": true - }, - "source": [ - "It is possible to use other activations functions for the hidden layer also.\n", - "\n", - "The output $\\boldsymbol{x}_i^{\\text{hidden}}$ from each $i$-th hidden neuron is:\n", - "\n", - "$$\n", - "\\boldsymbol{x}_i^{\\text{hidden} } = f\\big( \\boldsymbol{z}_{i}^{\\text{hidden}} \\big)\n", - "$$\n", - "\n", - "The outputs $\\boldsymbol{x}_i^{\\text{hidden} } $ are then sent to the output layer.\n", - "\n", - "The output layer consists of one neuron in this case, and combines the\n", - "output from each of the neurons in the hidden layers. The output layer\n", - "combines the results from the hidden layer using some weights $w_i^{\\text{output}}$\n", - "and biases $b_i^{\\text{output}}$. In this case,\n", - "it is assumes that the number of neurons in the output layer is one." - ] - }, - { - "cell_type": "markdown", - "id": "f33f3a2e", - "metadata": { - "editable": true - }, - "source": [ - "## Final technicalities III\n", - "\n", - "The procedure of weighting the output neuron $j$ in the hidden layer to the $i$-th neuron in the output layer is similar as for the hidden layer described previously." - ] - }, - { - "cell_type": "markdown", - "id": "d90fb703", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\begin{aligned}\n", - "z_{1,j}^{\\text{output}} & =\n", - "\\begin{pmatrix}\n", - "b_1^{\\text{output}} & \\boldsymbol{w}_1^{\\text{output}}\n", - "\\end{pmatrix}\n", - "\\begin{pmatrix}\n", - "1 \\\\\n", - "\\boldsymbol{x}_j^{\\text{hidden}}\n", - "\\end{pmatrix}\n", - "\\end{aligned}\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "0e4df2e9", - "metadata": { - "editable": true - }, - "source": [ - "## Final technicalities IV\n", - "\n", - "Expressing $z_{1,j}^{\\text{output}}$ as a vector gives the following way of weighting the inputs from the hidden layer:" - ] - }, - { - "cell_type": "markdown", - "id": "85cc6666", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\boldsymbol{z}_{1}^{\\text{output}} =\n", - "\\begin{pmatrix}\n", - "b_1^{\\text{output}} & \\boldsymbol{w}_1^{\\text{output}}\n", - "\\end{pmatrix}\n", - "\\begin{pmatrix}\n", - "1 & 1 & \\dots & 1 \\\\\n", - "\\boldsymbol{x}_1^{\\text{hidden}} & \\boldsymbol{x}_2^{\\text{hidden}} & \\dots & \\boldsymbol{x}_N^{\\text{hidden}}\n", - "\\end{pmatrix}\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "c4876b89", - "metadata": { - "editable": true - }, - "source": [ - "In this case we seek a continuous range of values since we are approximating a function. This means that after computing $\\boldsymbol{z}_{1}^{\\text{output}}$ the neural network has finished its feed forward step, and $\\boldsymbol{z}_{1}^{\\text{output}}$ is the final output of the network." - ] - }, - { - "cell_type": "markdown", - "id": "7e2cf00e", - "metadata": { - "editable": true - }, - "source": [ - "## Back propagation\n", - "\n", - "The next step is to decide how the parameters should be changed such that they minimize the cost function.\n", - "\n", - "The chosen cost function for this problem is" - ] - }, - { - "cell_type": "markdown", - "id": "a49b485d", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "C(\\boldsymbol{x}, P) = \\frac{1}{N} \\sum_i \\big(g_t'(x_i, P) - ( -\\gamma g_t(x_i, P) \\big)^2\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "7c5a4275", - "metadata": { - "editable": true - }, - "source": [ - "In order to minimize the cost function, an optimization method must be chosen.\n", - "\n", - "Here, gradient descent with a constant step size has been chosen." - ] - }, - { - "cell_type": "markdown", - "id": "ee92110b", - "metadata": { - "editable": true - }, - "source": [ - "## Gradient descent\n", - "\n", - "The idea of the gradient descent algorithm is to update parameters in\n", - "a direction where the cost function decreases goes to a minimum.\n", - "\n", - "In general, the update of some parameters $\\boldsymbol{\\omega}$ given a cost\n", - "function defined by some weights $\\boldsymbol{\\omega}$, $C(\\boldsymbol{x},\n", - "\\boldsymbol{\\omega})$, goes as follows:" - ] - }, - { - "cell_type": "markdown", - "id": "c76e461e", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\boldsymbol{\\omega}_{\\text{new} } = \\boldsymbol{\\omega} - \\lambda \\nabla_{\\boldsymbol{\\omega}} C(\\boldsymbol{x}, \\boldsymbol{\\omega})\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "df9bc42a", - "metadata": { - "editable": true - }, - "source": [ - "for a number of iterations or until $ \\big|\\big| \\boldsymbol{\\omega}_{\\text{new} } - \\boldsymbol{\\omega} \\big|\\big|$ becomes smaller than some given tolerance.\n", - "\n", - "The value of $\\lambda$ decides how large steps the algorithm must take\n", - "in the direction of $ \\nabla_{\\boldsymbol{\\omega}} C(\\boldsymbol{x}, \\boldsymbol{\\omega})$.\n", - "The notation $\\nabla_{\\boldsymbol{\\omega}}$ express the gradient with respect\n", - "to the elements in $\\boldsymbol{\\omega}$.\n", - "\n", - "In our case, we have to minimize the cost function $C(\\boldsymbol{x}, P)$ with\n", - "respect to the two sets of weights and biases, that is for the hidden\n", - "layer $P_{\\text{hidden} }$ and for the output layer $P_{\\text{output}\n", - "}$ .\n", - "\n", - "This means that $P_{\\text{hidden} }$ and $P_{\\text{output} }$ is updated by" - ] - }, - { - "cell_type": "markdown", - "id": "418dcc35", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\begin{aligned}\n", - "P_{\\text{hidden},\\text{new}} &= P_{\\text{hidden}} - \\lambda \\nabla_{P_{\\text{hidden}}} C(\\boldsymbol{x}, P) \\\\\n", - "P_{\\text{output},\\text{new}} &= P_{\\text{output}} - \\lambda \\nabla_{P_{\\text{output}}} C(\\boldsymbol{x}, P)\n", - "\\end{aligned}\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "145ede1b", - "metadata": { - "editable": true - }, - "source": [ - "## The code for solving the ODE" - ] - }, - { - "cell_type": "code", - "execution_count": 43, - "id": "98b44c55", - "metadata": { - "collapsed": false, - "editable": true - }, - "outputs": [], - "source": [ - "import autograd.numpy as np\n", - "from autograd import grad, elementwise_grad\n", - "import autograd.numpy.random as npr\n", - "from matplotlib import pyplot as plt\n", - "\n", - "def sigmoid(z):\n", - " return 1/(1 + np.exp(-z))\n", - "\n", - "# Assuming one input, hidden, and output layer\n", - "def neural_network(params, x):\n", - "\n", - " # Find the weights (including and biases) for the hidden and output layer.\n", - " # Assume that params is a list of parameters for each layer.\n", - " # The biases are the first element for each array in params,\n", - " # and the weights are the remaning elements in each array in params.\n", - "\n", - " w_hidden = params[0]\n", - " w_output = params[1]\n", - "\n", - " # Assumes input x being an one-dimensional array\n", - " num_values = np.size(x)\n", - " x = x.reshape(-1, num_values)\n", - "\n", - " # Assume that the input layer does nothing to the input x\n", - " x_input = x\n", - "\n", - " ## Hidden layer:\n", - "\n", - " # Add a row of ones to include bias\n", - " x_input = np.concatenate((np.ones((1,num_values)), x_input ), axis = 0)\n", - "\n", - " z_hidden = np.matmul(w_hidden, x_input)\n", - " x_hidden = sigmoid(z_hidden)\n", - "\n", - " ## Output layer:\n", - "\n", - " # Include bias:\n", - " x_hidden = np.concatenate((np.ones((1,num_values)), x_hidden ), axis = 0)\n", - "\n", - " z_output = np.matmul(w_output, x_hidden)\n", - " x_output = z_output\n", - "\n", - " return x_output\n", - "\n", - "# The trial solution using the deep neural network:\n", - "def g_trial(x,params, g0 = 10):\n", - " return g0 + x*neural_network(params,x)\n", - "\n", - "# The right side of the ODE:\n", - "def g(x, g_trial, gamma = 2):\n", - " return -gamma*g_trial\n", - "\n", - "# The cost function:\n", - "def cost_function(P, x):\n", - "\n", - " # Evaluate the trial function with the current parameters P\n", - " g_t = g_trial(x,P)\n", - "\n", - " # Find the derivative w.r.t x of the neural network\n", - " d_net_out = elementwise_grad(neural_network,1)(P,x)\n", - "\n", - " # Find the derivative w.r.t x of the trial function\n", - " d_g_t = elementwise_grad(g_trial,0)(x,P)\n", - "\n", - " # The right side of the ODE\n", - " func = g(x, g_t)\n", - "\n", - " err_sqr = (d_g_t - func)**2\n", - " cost_sum = np.sum(err_sqr)\n", - "\n", - " return cost_sum / np.size(err_sqr)\n", - "\n", - "# Solve the exponential decay ODE using neural network with one input, hidden, and output layer\n", - "def solve_ode_neural_network(x, num_neurons_hidden, num_iter, lmb):\n", - " ## Set up initial weights and biases\n", - "\n", - " # For the hidden layer\n", - " p0 = npr.randn(num_neurons_hidden, 2 )\n", - "\n", - " # For the output layer\n", - " p1 = npr.randn(1, num_neurons_hidden + 1 ) # +1 since bias is included\n", - "\n", - " P = [p0, p1]\n", - "\n", - " print('Initial cost: %g'%cost_function(P, x))\n", - "\n", - " ## Start finding the optimal weights using gradient descent\n", - "\n", - " # Find the Python function that represents the gradient of the cost function\n", - " # w.r.t the 0-th input argument -- that is the weights and biases in the hidden and output layer\n", - " cost_function_grad = grad(cost_function,0)\n", - "\n", - " # Let the update be done num_iter times\n", - " for i in range(num_iter):\n", - " # Evaluate the gradient at the current weights and biases in P.\n", - " # The cost_grad consist now of two arrays;\n", - " # one for the gradient w.r.t P_hidden and\n", - " # one for the gradient w.r.t P_output\n", - " cost_grad = cost_function_grad(P, x)\n", - "\n", - " P[0] = P[0] - lmb * cost_grad[0]\n", - " P[1] = P[1] - lmb * cost_grad[1]\n", - "\n", - " print('Final cost: %g'%cost_function(P, x))\n", - "\n", - " return P\n", - "\n", - "def g_analytic(x, gamma = 2, g0 = 10):\n", - " return g0*np.exp(-gamma*x)\n", - "\n", - "# Solve the given problem\n", - "if __name__ == '__main__':\n", - " # Set seed such that the weight are initialized\n", - " # with same weights and biases for every run.\n", - " npr.seed(15)\n", - "\n", - " ## Decide the vales of arguments to the function to solve\n", - " N = 10\n", - " x = np.linspace(0, 1, N)\n", - "\n", - " ## Set up the initial parameters\n", - " num_hidden_neurons = 10\n", - " num_iter = 10000\n", - " lmb = 0.001\n", - "\n", - " # Use the network\n", - " P = solve_ode_neural_network(x, num_hidden_neurons, num_iter, lmb)\n", - "\n", - " # Print the deviation from the trial solution and true solution\n", - " res = g_trial(x,P)\n", - " res_analytical = g_analytic(x)\n", - "\n", - " print('Max absolute difference: %g'%np.max(np.abs(res - res_analytical)))\n", - "\n", - " # Plot the results\n", - " plt.figure(figsize=(10,10))\n", - "\n", - " plt.title('Performance of neural network solving an ODE compared to the analytical solution')\n", - " plt.plot(x, res_analytical)\n", - " plt.plot(x, res[0,:])\n", - " plt.legend(['analytical','nn'])\n", - " plt.xlabel('x')\n", - " plt.ylabel('g(x)')\n", - " plt.show()" - ] - }, - { - "cell_type": "markdown", - "id": "47df9d6f", - "metadata": { - "editable": true - }, - "source": [ - "## The network with one input layer, specified number of hidden layers, and one output layer\n", - "\n", - "It is also possible to extend the construction of our network into a more general one, allowing the network to contain more than one hidden layers.\n", - "\n", - "The number of neurons within each hidden layer are given as a list of integers in the program below." - ] - }, - { - "cell_type": "code", - "execution_count": 44, - "id": "1415bdf5", - "metadata": { - "collapsed": false, - "editable": true - }, - "outputs": [], - "source": [ - "import autograd.numpy as np\n", - "from autograd import grad, elementwise_grad\n", - "import autograd.numpy.random as npr\n", - "from matplotlib import pyplot as plt\n", - "\n", - "def sigmoid(z):\n", - " return 1/(1 + np.exp(-z))\n", - "\n", - "# The neural network with one input layer and one output layer,\n", - "# but with number of hidden layers specified by the user.\n", - "def deep_neural_network(deep_params, x):\n", - " # N_hidden is the number of hidden layers\n", - "\n", - " N_hidden = np.size(deep_params) - 1 # -1 since params consists of\n", - " # parameters to all the hidden\n", - " # layers AND the output layer.\n", - "\n", - " # Assumes input x being an one-dimensional array\n", - " num_values = np.size(x)\n", - " x = x.reshape(-1, num_values)\n", - "\n", - " # Assume that the input layer does nothing to the input x\n", - " x_input = x\n", - "\n", - " # Due to multiple hidden layers, define a variable referencing to the\n", - " # output of the previous layer:\n", - " x_prev = x_input\n", - "\n", - " ## Hidden layers:\n", - "\n", - " for l in range(N_hidden):\n", - " # From the list of parameters P; find the correct weigths and bias for this layer\n", - " w_hidden = deep_params[l]\n", - "\n", - " # Add a row of ones to include bias\n", - " x_prev = np.concatenate((np.ones((1,num_values)), x_prev ), axis = 0)\n", - "\n", - " z_hidden = np.matmul(w_hidden, x_prev)\n", - " x_hidden = sigmoid(z_hidden)\n", - "\n", - " # Update x_prev such that next layer can use the output from this layer\n", - " x_prev = x_hidden\n", - "\n", - " ## Output layer:\n", - "\n", - " # Get the weights and bias for this layer\n", - " w_output = deep_params[-1]\n", - "\n", - " # Include bias:\n", - " x_prev = np.concatenate((np.ones((1,num_values)), x_prev), axis = 0)\n", - "\n", - " z_output = np.matmul(w_output, x_prev)\n", - " x_output = z_output\n", - "\n", - " return x_output\n", - "\n", - "# The trial solution using the deep neural network:\n", - "def g_trial_deep(x,params, g0 = 10):\n", - " return g0 + x*deep_neural_network(params, x)\n", - "\n", - "# The right side of the ODE:\n", - "def g(x, g_trial, gamma = 2):\n", - " return -gamma*g_trial\n", - "\n", - "# The same cost function as before, but calls deep_neural_network instead.\n", - "def cost_function_deep(P, x):\n", - "\n", - " # Evaluate the trial function with the current parameters P\n", - " g_t = g_trial_deep(x,P)\n", - "\n", - " # Find the derivative w.r.t x of the neural network\n", - " d_net_out = elementwise_grad(deep_neural_network,1)(P,x)\n", - "\n", - " # Find the derivative w.r.t x of the trial function\n", - " d_g_t = elementwise_grad(g_trial_deep,0)(x,P)\n", - "\n", - " # The right side of the ODE\n", - " func = g(x, g_t)\n", - "\n", - " err_sqr = (d_g_t - func)**2\n", - " cost_sum = np.sum(err_sqr)\n", - "\n", - " return cost_sum / np.size(err_sqr)\n", - "\n", - "# Solve the exponential decay ODE using neural network with one input and one output layer,\n", - "# but with specified number of hidden layers from the user.\n", - "def solve_ode_deep_neural_network(x, num_neurons, num_iter, lmb):\n", - " # num_hidden_neurons is now a list of number of neurons within each hidden layer\n", - "\n", - " # The number of elements in the list num_hidden_neurons thus represents\n", - " # the number of hidden layers.\n", - "\n", - " # Find the number of hidden layers:\n", - " N_hidden = np.size(num_neurons)\n", - "\n", - " ## Set up initial weights and biases\n", - "\n", - " # Initialize the list of parameters:\n", - " P = [None]*(N_hidden + 1) # + 1 to include the output layer\n", - "\n", - " P[0] = npr.randn(num_neurons[0], 2 )\n", - " for l in range(1,N_hidden):\n", - " P[l] = npr.randn(num_neurons[l], num_neurons[l-1] + 1) # +1 to include bias\n", - "\n", - " # For the output layer\n", - " P[-1] = npr.randn(1, num_neurons[-1] + 1 ) # +1 since bias is included\n", - "\n", - " print('Initial cost: %g'%cost_function_deep(P, x))\n", - "\n", - " ## Start finding the optimal weights using gradient descent\n", - "\n", - " # Find the Python function that represents the gradient of the cost function\n", - " # w.r.t the 0-th input argument -- that is the weights and biases in the hidden and output layer\n", - " cost_function_deep_grad = grad(cost_function_deep,0)\n", - "\n", - " # Let the update be done num_iter times\n", - " for i in range(num_iter):\n", - " # Evaluate the gradient at the current weights and biases in P.\n", - " # The cost_grad consist now of N_hidden + 1 arrays; the gradient w.r.t the weights and biases\n", - " # in the hidden layers and output layers evaluated at x.\n", - " cost_deep_grad = cost_function_deep_grad(P, x)\n", - "\n", - " for l in range(N_hidden+1):\n", - " P[l] = P[l] - lmb * cost_deep_grad[l]\n", - "\n", - " print('Final cost: %g'%cost_function_deep(P, x))\n", - "\n", - " return P\n", - "\n", - "def g_analytic(x, gamma = 2, g0 = 10):\n", - " return g0*np.exp(-gamma*x)\n", - "\n", - "# Solve the given problem\n", - "if __name__ == '__main__':\n", - " npr.seed(15)\n", - "\n", - " ## Decide the vales of arguments to the function to solve\n", - " N = 10\n", - " x = np.linspace(0, 1, N)\n", - "\n", - " ## Set up the initial parameters\n", - " num_hidden_neurons = np.array([10,10])\n", - " num_iter = 10000\n", - " lmb = 0.001\n", - "\n", - " P = solve_ode_deep_neural_network(x, num_hidden_neurons, num_iter, lmb)\n", - "\n", - " res = g_trial_deep(x,P)\n", - " res_analytical = g_analytic(x)\n", - "\n", - " plt.figure(figsize=(10,10))\n", - "\n", - " plt.title('Performance of a deep neural network solving an ODE compared to the analytical solution')\n", - " plt.plot(x, res_analytical)\n", - " plt.plot(x, res[0,:])\n", - " plt.legend(['analytical','dnn'])\n", - " plt.ylabel('g(x)')\n", - " plt.show()" - ] - }, - { - "cell_type": "markdown", - "id": "b480dee1", - "metadata": { - "editable": true - }, - "source": [ - "## Example: Population growth\n", - "\n", - "A logistic model of population growth assumes that a population converges toward an equilibrium.\n", - "The population growth can be modeled by" - ] - }, - { - "cell_type": "markdown", - "id": "3736290c", - "metadata": { - "editable": true - }, - "source": [ - "\n", - "
\n", - "\n", - "$$\n", - "\\begin{equation} \\label{log} \\tag{10}\n", - "\tg'(t) = \\alpha g(t)(A - g(t))\n", - "\\end{equation}\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "9fe04f20", - "metadata": { - "editable": true - }, - "source": [ - "where $g(t)$ is the population density at time $t$, $\\alpha > 0$ the growth rate and $A > 0$ is the maximum population number in the environment.\n", - "Also, at $t = 0$ the population has the size $g(0) = g_0$, where $g_0$ is some chosen constant.\n", - "\n", - "In this example, similar network as for the exponential decay using Autograd has been used to solve the equation. However, as the implementation might suffer from e.g numerical instability\n", - "and high execution time (this might be more apparent in the examples solving PDEs),\n", - "using a library like TensorFlow is recommended.\n", - "Here, we stay with a more simple approach and implement for comparison, the simple forward Euler method." - ] - }, - { - "cell_type": "markdown", - "id": "8090a04f", - "metadata": { - "editable": true - }, - "source": [ - "## Setting up the problem\n", - "\n", - "Here, we will model a population $g(t)$ in an environment having carrying capacity $A$.\n", - "The population follows the model" - ] - }, - { - "cell_type": "markdown", - "id": "22a5d518", - "metadata": { - "editable": true - }, - "source": [ - "\n", - "
\n", - "\n", - "$$\n", - "\\begin{equation} \\label{solveode_population} \\tag{11}\n", - "g'(t) = \\alpha g(t)(A - g(t))\n", - "\\end{equation}\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "24312795", - "metadata": { - "editable": true - }, - "source": [ - "where $g(0) = g_0$.\n", - "\n", - "In this example, we let $\\alpha = 2$, $A = 1$, and $g_0 = 1.2$." - ] - }, - { - "cell_type": "markdown", - "id": "c90e2f79", - "metadata": { - "editable": true - }, - "source": [ - "## The trial solution\n", - "\n", - "We will get a slightly different trial solution, as the boundary conditions are different\n", - "compared to the case for exponential decay.\n", - "\n", - "A possible trial solution satisfying the condition $g(0) = g_0$ could be\n", - "\n", - "$$\n", - "h_1(t) = g_0 + t \\cdot N(t,P)\n", - "$$\n", - "\n", - "with $N(t,P)$ being the output from the neural network with weights and biases for each layer collected in the set $P$.\n", - "\n", - "The analytical solution is\n", - "\n", - "$$\n", - "g(t) = \\frac{Ag_0}{g_0 + (A - g_0)\\exp(-\\alpha A t)}\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "112c3155", - "metadata": { - "editable": true - }, - "source": [ - "## The program using Autograd\n", - "\n", - "The network will be the similar as for the exponential decay example, but with some small modifications for our problem." - ] - }, - { - "cell_type": "code", - "execution_count": 45, - "id": "73371f5c", - "metadata": { - "collapsed": false, - "editable": true - }, - "outputs": [], - "source": [ - "import autograd.numpy as np\n", - "from autograd import grad, elementwise_grad\n", - "import autograd.numpy.random as npr\n", - "from matplotlib import pyplot as plt\n", - "\n", - "def sigmoid(z):\n", - " return 1/(1 + np.exp(-z))\n", - "\n", - "# Function to get the parameters.\n", - "# Done such that one can easily change the paramaters after one's liking.\n", - "def get_parameters():\n", - " alpha = 2\n", - " A = 1\n", - " g0 = 1.2\n", - " return alpha, A, g0\n", - "\n", - "def deep_neural_network(P, x):\n", - " # N_hidden is the number of hidden layers\n", - " N_hidden = np.size(P) - 1 # -1 since params consist of parameters to all the hidden layers AND the output layer\n", - "\n", - " # Assumes input x being an one-dimensional array\n", - " num_values = np.size(x)\n", - " x = x.reshape(-1, num_values)\n", - "\n", - " # Assume that the input layer does nothing to the input x\n", - " x_input = x\n", - "\n", - " # Due to multiple hidden layers, define a variable referencing to the\n", - " # output of the previous layer:\n", - " x_prev = x_input\n", - "\n", - " ## Hidden layers:\n", - "\n", - " for l in range(N_hidden):\n", - " # From the list of parameters P; find the correct weigths and bias for this layer\n", - " w_hidden = P[l]\n", - "\n", - " # Add a row of ones to include bias\n", - " x_prev = np.concatenate((np.ones((1,num_values)), x_prev ), axis = 0)\n", - "\n", - " z_hidden = np.matmul(w_hidden, x_prev)\n", - " x_hidden = sigmoid(z_hidden)\n", - "\n", - " # Update x_prev such that next layer can use the output from this layer\n", - " x_prev = x_hidden\n", - "\n", - " ## Output layer:\n", - "\n", - " # Get the weights and bias for this layer\n", - " w_output = P[-1]\n", - "\n", - " # Include bias:\n", - " x_prev = np.concatenate((np.ones((1,num_values)), x_prev), axis = 0)\n", - "\n", - " z_output = np.matmul(w_output, x_prev)\n", - " x_output = z_output\n", - "\n", - " return x_output\n", - "\n", - "\n", - "def cost_function_deep(P, x):\n", - "\n", - " # Evaluate the trial function with the current parameters P\n", - " g_t = g_trial_deep(x,P)\n", - "\n", - " # Find the derivative w.r.t x of the trial function\n", - " d_g_t = elementwise_grad(g_trial_deep,0)(x,P)\n", - "\n", - " # The right side of the ODE\n", - " func = f(x, g_t)\n", - "\n", - " err_sqr = (d_g_t - func)**2\n", - " cost_sum = np.sum(err_sqr)\n", - "\n", - " return cost_sum / np.size(err_sqr)\n", - "\n", - "# The right side of the ODE:\n", - "def f(x, g_trial):\n", - " alpha,A, g0 = get_parameters()\n", - " return alpha*g_trial*(A - g_trial)\n", - "\n", - "# The trial solution using the deep neural network:\n", - "def g_trial_deep(x, params):\n", - " alpha,A, g0 = get_parameters()\n", - " return g0 + x*deep_neural_network(params,x)\n", - "\n", - "# The analytical solution:\n", - "def g_analytic(t):\n", - " alpha,A, g0 = get_parameters()\n", - " return A*g0/(g0 + (A - g0)*np.exp(-alpha*A*t))\n", - "\n", - "def solve_ode_deep_neural_network(x, num_neurons, num_iter, lmb):\n", - " # num_hidden_neurons is now a list of number of neurons within each hidden layer\n", - "\n", - " # Find the number of hidden layers:\n", - " N_hidden = np.size(num_neurons)\n", - "\n", - " ## Set up initial weigths and biases\n", - "\n", - " # Initialize the list of parameters:\n", - " P = [None]*(N_hidden + 1) # + 1 to include the output layer\n", - "\n", - " P[0] = npr.randn(num_neurons[0], 2 )\n", - " for l in range(1,N_hidden):\n", - " P[l] = npr.randn(num_neurons[l], num_neurons[l-1] + 1) # +1 to include bias\n", - "\n", - " # For the output layer\n", - " P[-1] = npr.randn(1, num_neurons[-1] + 1 ) # +1 since bias is included\n", - "\n", - " print('Initial cost: %g'%cost_function_deep(P, x))\n", - "\n", - " ## Start finding the optimal weigths using gradient descent\n", - "\n", - " # Find the Python function that represents the gradient of the cost function\n", - " # w.r.t the 0-th input argument -- that is the weights and biases in the hidden and output layer\n", - " cost_function_deep_grad = grad(cost_function_deep,0)\n", - "\n", - " # Let the update be done num_iter times\n", - " for i in range(num_iter):\n", - " # Evaluate the gradient at the current weights and biases in P.\n", - " # The cost_grad consist now of N_hidden + 1 arrays; the gradient w.r.t the weights and biases\n", - " # in the hidden layers and output layers evaluated at x.\n", - " cost_deep_grad = cost_function_deep_grad(P, x)\n", - "\n", - " for l in range(N_hidden+1):\n", - " P[l] = P[l] - lmb * cost_deep_grad[l]\n", - "\n", - " print('Final cost: %g'%cost_function_deep(P, x))\n", - "\n", - " return P\n", - "\n", - "if __name__ == '__main__':\n", - " npr.seed(4155)\n", - "\n", - " ## Decide the vales of arguments to the function to solve\n", - " Nt = 10\n", - " T = 1\n", - " t = np.linspace(0,T, Nt)\n", - "\n", - " ## Set up the initial parameters\n", - " num_hidden_neurons = [100, 50, 25]\n", - " num_iter = 1000\n", - " lmb = 1e-3\n", - "\n", - " P = solve_ode_deep_neural_network(t, num_hidden_neurons, num_iter, lmb)\n", - "\n", - " g_dnn_ag = g_trial_deep(t,P)\n", - " g_analytical = g_analytic(t)\n", - "\n", - " # Find the maximum absolute difference between the solutons:\n", - " diff_ag = np.max(np.abs(g_dnn_ag - g_analytical))\n", - " print(\"The max absolute difference between the solutions is: %g\"%diff_ag)\n", - "\n", - " plt.figure(figsize=(10,10))\n", - "\n", - " plt.title('Performance of neural network solving an ODE compared to the analytical solution')\n", - " plt.plot(t, g_analytical)\n", - " plt.plot(t, g_dnn_ag[0,:])\n", - " plt.legend(['analytical','nn'])\n", - " plt.xlabel('t')\n", - " plt.ylabel('g(t)')\n", - "\n", - " plt.show()" - ] - }, - { - "cell_type": "markdown", - "id": "9ce89121", - "metadata": { - "editable": true - }, - "source": [ - "## Using forward Euler to solve the ODE\n", - "\n", - "A straightforward way of solving an ODE numerically, is to use Euler's method.\n", - "\n", - "Euler's method uses Taylor series to approximate the value at a function $f$ at a step $\\Delta x$ from $x$:\n", - "\n", - "$$\n", - "f(x + \\Delta x) \\approx f(x) + \\Delta x f'(x)\n", - "$$\n", - "\n", - "In our case, using Euler's method to approximate the value of $g$ at a step $\\Delta t$ from $t$ yields" - ] - }, - { - "cell_type": "markdown", - "id": "dfe02266", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\begin{aligned}\n", - " g(t + \\Delta t) &\\approx g(t) + \\Delta t g'(t) \\\\\n", - " &= g(t) + \\Delta t \\big(\\alpha g(t)(A - g(t))\\big)\n", - "\\end{aligned}\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "f2f12c48", - "metadata": { - "editable": true - }, - "source": [ - "along with the condition that $g(0) = g_0$.\n", - "\n", - "Let $t_i = i \\cdot \\Delta t$ where $\\Delta t = \\frac{T}{N_t-1}$ where $T$ is the final time our solver must solve for and $N_t$ the number of values for $t \\in [0, T]$ for $i = 0, \\dots, N_t-1$.\n", - "\n", - "For $i \\geq 1$, we have that" - ] - }, - { - "cell_type": "markdown", - "id": "ec46581e", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\begin{aligned}\n", - "t_i &= i\\Delta t \\\\\n", - "&= (i - 1)\\Delta t + \\Delta t \\\\\n", - "&= t_{i-1} + \\Delta t\n", - "\\end{aligned}\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "02c7198e", - "metadata": { - "editable": true - }, - "source": [ - "Now, if $g_i = g(t_i)$ then" - ] - }, - { - "cell_type": "markdown", - "id": "90c2533d", - "metadata": { - "editable": true - }, - "source": [ - "\n", - "
\n", - "\n", - "$$\n", - "\\begin{equation}\n", - " \\begin{aligned}\n", - " g_i &= g(t_i) \\\\\n", - " &= g(t_{i-1} + \\Delta t) \\\\\n", - " &\\approx g(t_{i-1}) + \\Delta t \\big(\\alpha g(t_{i-1})(A - g(t_{i-1}))\\big) \\\\\n", - " &= g_{i-1} + \\Delta t \\big(\\alpha g_{i-1}(A - g_{i-1})\\big)\n", - " \\end{aligned}\n", - "\\end{equation} \\label{odenum} \\tag{12}\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "f3dddcdf", - "metadata": { - "editable": true - }, - "source": [ - "for $i \\geq 1$ and $g_0 = g(t_0) = g(0) = g_0$.\n", - "\n", - "Equation ([12](#odenum)) could be implemented in the following way,\n", - "extending the program that uses the network using Autograd:" - ] - }, - { - "cell_type": "code", - "execution_count": 46, - "id": "52ee1308", - "metadata": { - "collapsed": false, - "editable": true - }, - "outputs": [], - "source": [ - "# Assume that all function definitions from the example program using Autograd\n", - "# are located here.\n", - "\n", - "if __name__ == '__main__':\n", - " npr.seed(4155)\n", - "\n", - " ## Decide the vales of arguments to the function to solve\n", - " Nt = 10\n", - " T = 1\n", - " t = np.linspace(0,T, Nt)\n", - "\n", - " ## Set up the initial parameters\n", - " num_hidden_neurons = [100,50,25]\n", - " num_iter = 1000\n", - " lmb = 1e-3\n", - "\n", - " P = solve_ode_deep_neural_network(t, num_hidden_neurons, num_iter, lmb)\n", - "\n", - " g_dnn_ag = g_trial_deep(t,P)\n", - " g_analytical = g_analytic(t)\n", - "\n", - " # Find the maximum absolute difference between the solutons:\n", - " diff_ag = np.max(np.abs(g_dnn_ag - g_analytical))\n", - " print(\"The max absolute difference between the solutions is: %g\"%diff_ag)\n", - "\n", - " plt.figure(figsize=(10,10))\n", - "\n", - " plt.title('Performance of neural network solving an ODE compared to the analytical solution')\n", - " plt.plot(t, g_analytical)\n", - " plt.plot(t, g_dnn_ag[0,:])\n", - " plt.legend(['analytical','nn'])\n", - " plt.xlabel('t')\n", - " plt.ylabel('g(t)')\n", - "\n", - " ## Find an approximation to the funtion using forward Euler\n", - "\n", - " alpha, A, g0 = get_parameters()\n", - " dt = T/(Nt - 1)\n", - "\n", - " # Perform forward Euler to solve the ODE\n", - " g_euler = np.zeros(Nt)\n", - " g_euler[0] = g0\n", - "\n", - " for i in range(1,Nt):\n", - " g_euler[i] = g_euler[i-1] + dt*(alpha*g_euler[i-1]*(A - g_euler[i-1]))\n", - "\n", - " # Print the errors done by each method\n", - " diff1 = np.max(np.abs(g_euler - g_analytical))\n", - " diff2 = np.max(np.abs(g_dnn_ag[0,:] - g_analytical))\n", - "\n", - " print('Max absolute difference between Euler method and analytical: %g'%diff1)\n", - " print('Max absolute difference between deep neural network and analytical: %g'%diff2)\n", - "\n", - " # Plot results\n", - " plt.figure(figsize=(10,10))\n", - "\n", - " plt.plot(t,g_euler)\n", - " plt.plot(t,g_analytical)\n", - " plt.plot(t,g_dnn_ag[0,:])\n", - "\n", - " plt.legend(['euler','analytical','dnn'])\n", - " plt.xlabel('Time t')\n", - " plt.ylabel('g(t)')\n", - "\n", - " plt.show()" - ] - }, - { - "cell_type": "markdown", - "id": "6537fc0c", - "metadata": { - "editable": true - }, - "source": [ - "## Example: Solving the one dimensional Poisson equation\n", - "\n", - "The Poisson equation for $g(x)$ in one dimension is" - ] - }, - { - "cell_type": "markdown", - "id": "bf0ace9e", - "metadata": { - "editable": true - }, - "source": [ - "\n", - "
\n", - "\n", - "$$\n", - "\\begin{equation} \\label{poisson} \\tag{13}\n", - " -g''(x) = f(x)\n", - "\\end{equation}\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "212fac99", - "metadata": { - "editable": true - }, - "source": [ - "where $f(x)$ is a given function for $x \\in (0,1)$.\n", - "\n", - "The conditions that $g(x)$ is chosen to fulfill, are" - ] - }, - { - "cell_type": "markdown", - "id": "fa2547d7", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\begin{align*}\n", - " g(0) &= 0 \\\\\n", - " g(1) &= 0\n", - "\\end{align*}\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "4d3aa4c3", - "metadata": { - "editable": true - }, - "source": [ - "This equation can be solved numerically using programs where e.g Autograd and TensorFlow are used.\n", - "The results from the networks can then be compared to the analytical solution.\n", - "In addition, it could be interesting to see how a typical method for numerically solving second order ODEs compares to the neural networks." - ] - }, - { - "cell_type": "markdown", - "id": "872d2747", - "metadata": { - "editable": true - }, - "source": [ - "## The specific equation to solve for\n", - "\n", - "Here, the function $g(x)$ to solve for follows the equation" - ] - }, - { - "cell_type": "markdown", - "id": "b51b983e", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "-g''(x) = f(x),\\qquad x \\in (0,1)\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "f208cc09", - "metadata": { - "editable": true - }, - "source": [ - "where $f(x)$ is a given function, along with the chosen conditions" - ] - }, - { - "cell_type": "markdown", - "id": "d584ffd3", - "metadata": { - "editable": true - }, - "source": [ - "\n", - "
\n", - "\n", - "$$\n", - "\\begin{aligned}\n", - "g(0) = g(1) = 0\n", - "\\end{aligned}\\label{cond} \\tag{14}\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "99794ce5", - "metadata": { - "editable": true - }, - "source": [ - "In this example, we consider the case when $f(x) = (3x + x^2)\\exp(x)$.\n", - "\n", - "For this case, a possible trial solution satisfying the conditions could be" - ] - }, - { - "cell_type": "markdown", - "id": "3f2f40d9", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "g_t(x) = x \\cdot (1-x) \\cdot N(P,x)\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "d5590dfb", - "metadata": { - "editable": true - }, - "source": [ - "The analytical solution for this problem is" - ] - }, - { - "cell_type": "markdown", - "id": "75ab0f4f", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "g(x) = x(1 - x)\\exp(x)\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "d83e4c37", - "metadata": { - "editable": true - }, - "source": [ - "## Solving the equation using Autograd" - ] - }, - { - "cell_type": "code", - "execution_count": 47, - "id": "95731560", - "metadata": { - "collapsed": false, - "editable": true - }, - "outputs": [], - "source": [ - "import autograd.numpy as np\n", - "from autograd import grad, elementwise_grad\n", - "import autograd.numpy.random as npr\n", - "from matplotlib import pyplot as plt\n", - "\n", - "def sigmoid(z):\n", - " return 1/(1 + np.exp(-z))\n", - "\n", - "def deep_neural_network(deep_params, x):\n", - " # N_hidden is the number of hidden layers\n", - " N_hidden = np.size(deep_params) - 1 # -1 since params consist of parameters to all the hidden layers AND the output layer\n", - "\n", - " # Assumes input x being an one-dimensional array\n", - " num_values = np.size(x)\n", - " x = x.reshape(-1, num_values)\n", - "\n", - " # Assume that the input layer does nothing to the input x\n", - " x_input = x\n", - "\n", - " # Due to multiple hidden layers, define a variable referencing to the\n", - " # output of the previous layer:\n", - " x_prev = x_input\n", - "\n", - " ## Hidden layers:\n", - "\n", - " for l in range(N_hidden):\n", - " # From the list of parameters P; find the correct weigths and bias for this layer\n", - " w_hidden = deep_params[l]\n", - "\n", - " # Add a row of ones to include bias\n", - " x_prev = np.concatenate((np.ones((1,num_values)), x_prev ), axis = 0)\n", - "\n", - " z_hidden = np.matmul(w_hidden, x_prev)\n", - " x_hidden = sigmoid(z_hidden)\n", - "\n", - " # Update x_prev such that next layer can use the output from this layer\n", - " x_prev = x_hidden\n", - "\n", - " ## Output layer:\n", - "\n", - " # Get the weights and bias for this layer\n", - " w_output = deep_params[-1]\n", - "\n", - " # Include bias:\n", - " x_prev = np.concatenate((np.ones((1,num_values)), x_prev), axis = 0)\n", - "\n", - " z_output = np.matmul(w_output, x_prev)\n", - " x_output = z_output\n", - "\n", - " return x_output\n", - "\n", - "def solve_ode_deep_neural_network(x, num_neurons, num_iter, lmb):\n", - " # num_hidden_neurons is now a list of number of neurons within each hidden layer\n", - "\n", - " # Find the number of hidden layers:\n", - " N_hidden = np.size(num_neurons)\n", - "\n", - " ## Set up initial weigths and biases\n", - "\n", - " # Initialize the list of parameters:\n", - " P = [None]*(N_hidden + 1) # + 1 to include the output layer\n", - "\n", - " P[0] = npr.randn(num_neurons[0], 2 )\n", - " for l in range(1,N_hidden):\n", - " P[l] = npr.randn(num_neurons[l], num_neurons[l-1] + 1) # +1 to include bias\n", - "\n", - " # For the output layer\n", - " P[-1] = npr.randn(1, num_neurons[-1] + 1 ) # +1 since bias is included\n", - "\n", - " print('Initial cost: %g'%cost_function_deep(P, x))\n", - "\n", - " ## Start finding the optimal weigths using gradient descent\n", - "\n", - " # Find the Python function that represents the gradient of the cost function\n", - " # w.r.t the 0-th input argument -- that is the weights and biases in the hidden and output layer\n", - " cost_function_deep_grad = grad(cost_function_deep,0)\n", - "\n", - " # Let the update be done num_iter times\n", - " for i in range(num_iter):\n", - " # Evaluate the gradient at the current weights and biases in P.\n", - " # The cost_grad consist now of N_hidden + 1 arrays; the gradient w.r.t the weights and biases\n", - " # in the hidden layers and output layers evaluated at x.\n", - " cost_deep_grad = cost_function_deep_grad(P, x)\n", - "\n", - " for l in range(N_hidden+1):\n", - " P[l] = P[l] - lmb * cost_deep_grad[l]\n", - "\n", - " print('Final cost: %g'%cost_function_deep(P, x))\n", - "\n", - " return P\n", - "\n", - "## Set up the cost function specified for this Poisson equation:\n", - "\n", - "# The right side of the ODE\n", - "def f(x):\n", - " return (3*x + x**2)*np.exp(x)\n", - "\n", - "def cost_function_deep(P, x):\n", - "\n", - " # Evaluate the trial function with the current parameters P\n", - " g_t = g_trial_deep(x,P)\n", - "\n", - " # Find the derivative w.r.t x of the trial function\n", - " d2_g_t = elementwise_grad(elementwise_grad(g_trial_deep,0))(x,P)\n", - "\n", - " right_side = f(x)\n", - "\n", - " err_sqr = (-d2_g_t - right_side)**2\n", - " cost_sum = np.sum(err_sqr)\n", - "\n", - " return cost_sum/np.size(err_sqr)\n", - "\n", - "# The trial solution:\n", - "def g_trial_deep(x,P):\n", - " return x*(1-x)*deep_neural_network(P,x)\n", - "\n", - "# The analytic solution;\n", - "def g_analytic(x):\n", - " return x*(1-x)*np.exp(x)\n", - "\n", - "if __name__ == '__main__':\n", - " npr.seed(4155)\n", - "\n", - " ## Decide the vales of arguments to the function to solve\n", - " Nx = 10\n", - " x = np.linspace(0,1, Nx)\n", - "\n", - " ## Set up the initial parameters\n", - " num_hidden_neurons = [200,100]\n", - " num_iter = 1000\n", - " lmb = 1e-3\n", - "\n", - " P = solve_ode_deep_neural_network(x, num_hidden_neurons, num_iter, lmb)\n", - "\n", - " g_dnn_ag = g_trial_deep(x,P)\n", - " g_analytical = g_analytic(x)\n", - "\n", - " # Find the maximum absolute difference between the solutons:\n", - " max_diff = np.max(np.abs(g_dnn_ag - g_analytical))\n", - " print(\"The max absolute difference between the solutions is: %g\"%max_diff)\n", - "\n", - " plt.figure(figsize=(10,10))\n", - "\n", - " plt.title('Performance of neural network solving an ODE compared to the analytical solution')\n", - " plt.plot(x, g_analytical)\n", - " plt.plot(x, g_dnn_ag[0,:])\n", - " plt.legend(['analytical','nn'])\n", - " plt.xlabel('x')\n", - " plt.ylabel('g(x)')\n", - " plt.show()" - ] - }, - { - "cell_type": "markdown", - "id": "559cb774", - "metadata": { - "editable": true - }, - "source": [ - "## Comparing with a numerical scheme\n", - "\n", - "The Poisson equation is possible to solve using Taylor series to approximate the second derivative.\n", - "\n", - "Using Taylor series, the second derivative can be expressed as\n", - "\n", - "$$\n", - "g''(x) = \\frac{g(x + \\Delta x) - 2g(x) + g(x-\\Delta x)}{\\Delta x^2} + E_{\\Delta x}(x)\n", - "$$\n", - "\n", - "where $\\Delta x$ is a small step size and $E_{\\Delta x}(x)$ being the error term.\n", - "\n", - "Looking away from the error terms gives an approximation to the second derivative:" - ] - }, - { - "cell_type": "markdown", - "id": "72b9c88d", - "metadata": { - "editable": true - }, - "source": [ - "\n", - "
\n", - "\n", - "$$\n", - "\\begin{equation} \\label{approx} \\tag{15}\n", - "g''(x) \\approx \\frac{g(x + \\Delta x) - 2g(x) + g(x-\\Delta x)}{\\Delta x^2}\n", - "\\end{equation}\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "1c7a99a5", - "metadata": { - "editable": true - }, - "source": [ - "If $x_i = i \\Delta x = x_{i-1} + \\Delta x$ and $g_i = g(x_i)$ for $i = 1,\\dots N_x - 2$ with $N_x$ being the number of values for $x$, ([15](#approx)) becomes" - ] - }, - { - "cell_type": "markdown", - "id": "b46248f9", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\begin{aligned}\n", - "g''(x_i) &\\approx \\frac{g(x_i + \\Delta x) - 2g(x_i) + g(x_i -\\Delta x)}{\\Delta x^2} \\\\\n", - "&= \\frac{g_{i+1} - 2g_i + g_{i-1}}{\\Delta x^2}\n", - "\\end{aligned}\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "fa1d6871", - "metadata": { - "editable": true - }, - "source": [ - "Since we know from our problem that" - ] - }, - { - "cell_type": "markdown", - "id": "caa3216a", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\begin{aligned}\n", - "-g''(x) &= f(x) \\\\\n", - "&= (3x + x^2)\\exp(x)\n", - "\\end{aligned}\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "936f3b89", - "metadata": { - "editable": true - }, - "source": [ - "along with the conditions $g(0) = g(1) = 0$,\n", - "the following scheme can be used to find an approximate solution for $g(x)$ numerically:" - ] - }, - { - "cell_type": "markdown", - "id": "1e7fa7e3", - "metadata": { - "editable": true - }, - "source": [ - "\n", - "
\n", - "\n", - "$$\n", - "\\begin{equation}\n", - " \\begin{aligned}\n", - " -\\Big( \\frac{g_{i+1} - 2g_i + g_{i-1}}{\\Delta x^2} \\Big) &= f(x_i) \\\\\n", - " -g_{i+1} + 2g_i - g_{i-1} &= \\Delta x^2 f(x_i)\n", - " \\end{aligned}\n", - "\\end{equation} \\label{odesys} \\tag{16}\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "9c46ad0b", - "metadata": { - "editable": true - }, - "source": [ - "for $i = 1, \\dots, N_x - 2$ where $g_0 = g_{N_x - 1} = 0$ and $f(x_i) = (3x_i + x_i^2)\\exp(x_i)$, which is given for our specific problem.\n", - "\n", - "The equation can be rewritten into a matrix equation:" - ] - }, - { - "cell_type": "markdown", - "id": "ccf16979", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\begin{aligned}\n", - "\\begin{pmatrix}\n", - "2 & -1 & 0 & \\dots & 0 \\\\\n", - "-1 & 2 & -1 & \\dots & 0 \\\\\n", - "\\vdots & & \\ddots & & \\vdots \\\\\n", - "0 & \\dots & -1 & 2 & -1 \\\\\n", - "0 & \\dots & 0 & -1 & 2\\\\\n", - "\\end{pmatrix}\n", - "\\begin{pmatrix}\n", - "g_1 \\\\\n", - "g_2 \\\\\n", - "\\vdots \\\\\n", - "g_{N_x - 3} \\\\\n", - "g_{N_x - 2}\n", - "\\end{pmatrix}\n", - "&=\n", - "\\Delta x^2\n", - "\\begin{pmatrix}\n", - "f(x_1) \\\\\n", - "f(x_2) \\\\\n", - "\\vdots \\\\\n", - "f(x_{N_x - 3}) \\\\\n", - "f(x_{N_x - 2})\n", - "\\end{pmatrix} \\\\\n", - "\\boldsymbol{A}\\boldsymbol{g} &= \\boldsymbol{f},\n", - "\\end{aligned}\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "e940bd60", - "metadata": { - "editable": true - }, - "source": [ - "which makes it possible to solve for the vector $\\boldsymbol{g}$." - ] - }, - { - "cell_type": "markdown", - "id": "ee51ae7f", - "metadata": { - "editable": true - }, - "source": [ - "## Setting up the code\n", - "\n", - "We can then compare the result from this numerical scheme with the output from our network using Autograd:" - ] - }, - { - "cell_type": "code", - "execution_count": 48, - "id": "c538fed6", - "metadata": { - "collapsed": false, - "editable": true - }, - "outputs": [], - "source": [ - "import autograd.numpy as np\n", - "from autograd import grad, elementwise_grad\n", - "import autograd.numpy.random as npr\n", - "from matplotlib import pyplot as plt\n", - "\n", - "def sigmoid(z):\n", - " return 1/(1 + np.exp(-z))\n", - "\n", - "def deep_neural_network(deep_params, x):\n", - " # N_hidden is the number of hidden layers\n", - " N_hidden = np.size(deep_params) - 1 # -1 since params consist of parameters to all the hidden layers AND the output layer\n", - "\n", - " # Assumes input x being an one-dimensional array\n", - " num_values = np.size(x)\n", - " x = x.reshape(-1, num_values)\n", - "\n", - " # Assume that the input layer does nothing to the input x\n", - " x_input = x\n", - "\n", - " # Due to multiple hidden layers, define a variable referencing to the\n", - " # output of the previous layer:\n", - " x_prev = x_input\n", - "\n", - " ## Hidden layers:\n", - "\n", - " for l in range(N_hidden):\n", - " # From the list of parameters P; find the correct weigths and bias for this layer\n", - " w_hidden = deep_params[l]\n", - "\n", - " # Add a row of ones to include bias\n", - " x_prev = np.concatenate((np.ones((1,num_values)), x_prev ), axis = 0)\n", - "\n", - " z_hidden = np.matmul(w_hidden, x_prev)\n", - " x_hidden = sigmoid(z_hidden)\n", - "\n", - " # Update x_prev such that next layer can use the output from this layer\n", - " x_prev = x_hidden\n", - "\n", - " ## Output layer:\n", - "\n", - " # Get the weights and bias for this layer\n", - " w_output = deep_params[-1]\n", - "\n", - " # Include bias:\n", - " x_prev = np.concatenate((np.ones((1,num_values)), x_prev), axis = 0)\n", - "\n", - " z_output = np.matmul(w_output, x_prev)\n", - " x_output = z_output\n", - "\n", - " return x_output\n", - "\n", - "def solve_ode_deep_neural_network(x, num_neurons, num_iter, lmb):\n", - " # num_hidden_neurons is now a list of number of neurons within each hidden layer\n", - "\n", - " # Find the number of hidden layers:\n", - " N_hidden = np.size(num_neurons)\n", - "\n", - " ## Set up initial weigths and biases\n", - "\n", - " # Initialize the list of parameters:\n", - " P = [None]*(N_hidden + 1) # + 1 to include the output layer\n", - "\n", - " P[0] = npr.randn(num_neurons[0], 2 )\n", - " for l in range(1,N_hidden):\n", - " P[l] = npr.randn(num_neurons[l], num_neurons[l-1] + 1) # +1 to include bias\n", - "\n", - " # For the output layer\n", - " P[-1] = npr.randn(1, num_neurons[-1] + 1 ) # +1 since bias is included\n", - "\n", - " print('Initial cost: %g'%cost_function_deep(P, x))\n", - "\n", - " ## Start finding the optimal weigths using gradient descent\n", - "\n", - " # Find the Python function that represents the gradient of the cost function\n", - " # w.r.t the 0-th input argument -- that is the weights and biases in the hidden and output layer\n", - " cost_function_deep_grad = grad(cost_function_deep,0)\n", - "\n", - " # Let the update be done num_iter times\n", - " for i in range(num_iter):\n", - " # Evaluate the gradient at the current weights and biases in P.\n", - " # The cost_grad consist now of N_hidden + 1 arrays; the gradient w.r.t the weights and biases\n", - " # in the hidden layers and output layers evaluated at x.\n", - " cost_deep_grad = cost_function_deep_grad(P, x)\n", - "\n", - " for l in range(N_hidden+1):\n", - " P[l] = P[l] - lmb * cost_deep_grad[l]\n", - "\n", - " print('Final cost: %g'%cost_function_deep(P, x))\n", - "\n", - " return P\n", - "\n", - "## Set up the cost function specified for this Poisson equation:\n", - "\n", - "# The right side of the ODE\n", - "def f(x):\n", - " return (3*x + x**2)*np.exp(x)\n", - "\n", - "def cost_function_deep(P, x):\n", - "\n", - " # Evaluate the trial function with the current parameters P\n", - " g_t = g_trial_deep(x,P)\n", - "\n", - " # Find the derivative w.r.t x of the trial function\n", - " d2_g_t = elementwise_grad(elementwise_grad(g_trial_deep,0))(x,P)\n", - "\n", - " right_side = f(x)\n", - "\n", - " err_sqr = (-d2_g_t - right_side)**2\n", - " cost_sum = np.sum(err_sqr)\n", - "\n", - " return cost_sum/np.size(err_sqr)\n", - "\n", - "# The trial solution:\n", - "def g_trial_deep(x,P):\n", - " return x*(1-x)*deep_neural_network(P,x)\n", - "\n", - "# The analytic solution;\n", - "def g_analytic(x):\n", - " return x*(1-x)*np.exp(x)\n", - "\n", - "if __name__ == '__main__':\n", - " npr.seed(4155)\n", - "\n", - " ## Decide the vales of arguments to the function to solve\n", - " Nx = 10\n", - " x = np.linspace(0,1, Nx)\n", - "\n", - " ## Set up the initial parameters\n", - " num_hidden_neurons = [200,100]\n", - " num_iter = 1000\n", - " lmb = 1e-3\n", - "\n", - " P = solve_ode_deep_neural_network(x, num_hidden_neurons, num_iter, lmb)\n", - "\n", - " g_dnn_ag = g_trial_deep(x,P)\n", - " g_analytical = g_analytic(x)\n", - "\n", - " # Find the maximum absolute difference between the solutons:\n", - "\n", - " plt.figure(figsize=(10,10))\n", - "\n", - " plt.title('Performance of neural network solving an ODE compared to the analytical solution')\n", - " plt.plot(x, g_analytical)\n", - " plt.plot(x, g_dnn_ag[0,:])\n", - " plt.legend(['analytical','nn'])\n", - " plt.xlabel('x')\n", - " plt.ylabel('g(x)')\n", - "\n", - " ## Perform the computation using the numerical scheme\n", - "\n", - " dx = 1/(Nx - 1)\n", - "\n", - " # Set up the matrix A\n", - " A = np.zeros((Nx-2,Nx-2))\n", - "\n", - " A[0,0] = 2\n", - " A[0,1] = -1\n", - "\n", - " for i in range(1,Nx-3):\n", - " A[i,i-1] = -1\n", - " A[i,i] = 2\n", - " A[i,i+1] = -1\n", - "\n", - " A[Nx - 3, Nx - 4] = -1\n", - " A[Nx - 3, Nx - 3] = 2\n", - "\n", - " # Set up the vector f\n", - " f_vec = dx**2 * f(x[1:-1])\n", - "\n", - " # Solve the equation\n", - " g_res = np.linalg.solve(A,f_vec)\n", - "\n", - " g_vec = np.zeros(Nx)\n", - " g_vec[1:-1] = g_res\n", - "\n", - " # Print the differences between each method\n", - " max_diff1 = np.max(np.abs(g_dnn_ag - g_analytical))\n", - " max_diff2 = np.max(np.abs(g_vec - g_analytical))\n", - " print(\"The max absolute difference between the analytical solution and DNN Autograd: %g\"%max_diff1)\n", - " print(\"The max absolute difference between the analytical solution and numerical scheme: %g\"%max_diff2)\n", - "\n", - " # Plot the results\n", - " plt.figure(figsize=(10,10))\n", - "\n", - " plt.plot(x,g_vec)\n", - " plt.plot(x,g_analytical)\n", - " plt.plot(x,g_dnn_ag[0,:])\n", - "\n", - " plt.legend(['numerical scheme','analytical','dnn'])\n", - " plt.show()" - ] - }, - { - "cell_type": "markdown", - "id": "9855543b", - "metadata": { - "editable": true - }, - "source": [ - "## Partial Differential Equations\n", - "\n", - "A partial differential equation (PDE) has a solution here the function\n", - "is defined by multiple variables. The equation may involve all kinds\n", - "of combinations of which variables the function is differentiated with\n", - "respect to.\n", - "\n", - "In general, a partial differential equation for a function $g(x_1,\\dots,x_N)$ with $N$ variables may be expressed as" - ] - }, - { - "cell_type": "markdown", - "id": "a1b8cd5d", - "metadata": { - "editable": true - }, - "source": [ - "\n", - "
\n", - "\n", - "$$\n", - "\\begin{equation} \\label{PDE} \\tag{17}\n", - " f\\left(x_1, \\, \\dots \\, , x_N, \\frac{\\partial g(x_1,\\dots,x_N) }{\\partial x_1}, \\dots , \\frac{\\partial g(x_1,\\dots,x_N) }{\\partial x_N}, \\frac{\\partial g(x_1,\\dots,x_N) }{\\partial x_1\\partial x_2}, \\, \\dots \\, , \\frac{\\partial^n g(x_1,\\dots,x_N) }{\\partial x_N^n} \\right) = 0\n", - "\\end{equation}\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "75d6ae90", - "metadata": { - "editable": true - }, - "source": [ - "where $f$ is an expression involving all kinds of possible mixed derivatives of $g(x_1,\\dots,x_N)$ up to an order $n$. In order for the solution to be unique, some additional conditions must also be given." - ] - }, - { - "cell_type": "markdown", - "id": "83d6d123", - "metadata": { - "editable": true - }, - "source": [ - "## Type of problem\n", - "\n", - "The problem our network must solve for, is similar to the ODE case.\n", - "We must have a trial solution $g_t$ at hand.\n", - "\n", - "For instance, the trial solution could be expressed as" - ] - }, - { - "cell_type": "markdown", - "id": "7d9f4892", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\begin{align*}\n", - " g_t(x_1,\\dots,x_N) = h_1(x_1,\\dots,x_N) + h_2(x_1,\\dots,x_N,N(x_1,\\dots,x_N,P))\n", - "\\end{align*}\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "bc1c8c1b", - "metadata": { - "editable": true - }, - "source": [ - "where $h_1(x_1,\\dots,x_N)$ is a function that ensures $g_t(x_1,\\dots,x_N)$ satisfies some given conditions.\n", - "The neural network $N(x_1,\\dots,x_N,P)$ has weights and biases described by $P$ and $h_2(x_1,\\dots,x_N,N(x_1,\\dots,x_N,P))$ is an expression using the output from the neural network in some way.\n", - "\n", - "The role of the function $h_2(x_1,\\dots,x_N,N(x_1,\\dots,x_N,P))$, is to ensure that the output of $N(x_1,\\dots,x_N,P)$ is zero when $g_t(x_1,\\dots,x_N)$ is evaluated at the values of $x_1,\\dots,x_N$ where the given conditions must be satisfied. The function $h_1(x_1,\\dots,x_N)$ should alone make $g_t(x_1,\\dots,x_N)$ satisfy the conditions." - ] - }, - { - "cell_type": "markdown", - "id": "6fdbc09b", - "metadata": { - "editable": true - }, - "source": [ - "## Network requirements\n", - "\n", - "The network tries then the minimize the cost function following the\n", - "same ideas as described for the ODE case, but now with more than one\n", - "variables to consider. The concept still remains the same; find a set\n", - "of parameters $P$ such that the expression $f$ in ([17](#PDE)) is as\n", - "close to zero as possible.\n", - "\n", - "As for the ODE case, the cost function is the mean squared error that\n", - "the network must try to minimize. The cost function for the network to\n", - "minimize is" - ] - }, - { - "cell_type": "markdown", - "id": "15f911ae", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "C\\left(x_1, \\dots, x_N, P\\right) = \\left( f\\left(x_1, \\, \\dots \\, , x_N, \\frac{\\partial g(x_1,\\dots,x_N) }{\\partial x_1}, \\dots , \\frac{\\partial g(x_1,\\dots,x_N) }{\\partial x_N}, \\frac{\\partial g(x_1,\\dots,x_N) }{\\partial x_1\\partial x_2}, \\, \\dots \\, , \\frac{\\partial^n g(x_1,\\dots,x_N) }{\\partial x_N^n} \\right) \\right)^2\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "73d815fc", - "metadata": { - "editable": true - }, - "source": [ - "## More details\n", - "\n", - "If we let $\\boldsymbol{x} = \\big( x_1, \\dots, x_N \\big)$ be an array containing the values for $x_1, \\dots, x_N$ respectively, the cost function can be reformulated into the following:" - ] - }, - { - "cell_type": "markdown", - "id": "a8b12b31", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "C\\left(\\boldsymbol{x}, P\\right) = f\\left( \\left( \\boldsymbol{x}, \\frac{\\partial g(\\boldsymbol{x}) }{\\partial x_1}, \\dots , \\frac{\\partial g(\\boldsymbol{x}) }{\\partial x_N}, \\frac{\\partial g(\\boldsymbol{x}) }{\\partial x_1\\partial x_2}, \\, \\dots \\, , \\frac{\\partial^n g(\\boldsymbol{x}) }{\\partial x_N^n} \\right) \\right)^2\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "0bca5395", - "metadata": { - "editable": true - }, - "source": [ - "If we also have $M$ different sets of values for $x_1, \\dots, x_N$, that is $\\boldsymbol{x}_i = \\big(x_1^{(i)}, \\dots, x_N^{(i)}\\big)$ for $i = 1,\\dots,M$ being the rows in matrix $X$, the cost function can be generalized into" - ] - }, - { - "cell_type": "markdown", - "id": "189bac4d", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "C\\left(X, P \\right) = \\sum_{i=1}^M f\\left( \\left( \\boldsymbol{x}_i, \\frac{\\partial g(\\boldsymbol{x}_i) }{\\partial x_1}, \\dots , \\frac{\\partial g(\\boldsymbol{x}_i) }{\\partial x_N}, \\frac{\\partial g(\\boldsymbol{x}_i) }{\\partial x_1\\partial x_2}, \\, \\dots \\, , \\frac{\\partial^n g(\\boldsymbol{x}_i) }{\\partial x_N^n} \\right) \\right)^2.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "9b596e36", - "metadata": { - "editable": true - }, - "source": [ - "## Example: The diffusion equation\n", - "\n", - "In one spatial dimension, the equation reads" - ] - }, - { - "cell_type": "markdown", - "id": "3dc31dd6", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\frac{\\partial g(x,t)}{\\partial t} = \\frac{\\partial^2 g(x,t)}{\\partial x^2}\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "263f026e", - "metadata": { - "editable": true - }, - "source": [ - "where a possible choice of conditions are" - ] - }, - { - "cell_type": "markdown", - "id": "717dae65", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\begin{align*}\n", - "g(0,t) &= 0 ,\\qquad t \\geq 0 \\\\\n", - "g(1,t) &= 0, \\qquad t \\geq 0 \\\\\n", - "g(x,0) &= u(x),\\qquad x\\in [0,1]\n", - "\\end{align*}\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "0f898a32", - "metadata": { - "editable": true - }, - "source": [ - "with $u(x)$ being some given function." - ] - }, - { - "cell_type": "markdown", - "id": "47634dd9", - "metadata": { - "editable": true - }, - "source": [ - "## Defining the problem\n", - "\n", - "For this case, we want to find $g(x,t)$ such that" - ] - }, - { - "cell_type": "markdown", - "id": "6af0489e", - "metadata": { - "editable": true - }, - "source": [ - "\n", - "
\n", - "\n", - "$$\n", - "\\begin{equation}\n", - " \\frac{\\partial g(x,t)}{\\partial t} = \\frac{\\partial^2 g(x,t)}{\\partial x^2}\n", - "\\end{equation} \\label{diffonedim} \\tag{18}\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "03dabab2", - "metadata": { - "editable": true - }, - "source": [ - "and" - ] - }, - { - "cell_type": "markdown", - "id": "796edf7a", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\begin{align*}\n", - "g(0,t) &= 0 ,\\qquad t \\geq 0 \\\\\n", - "g(1,t) &= 0, \\qquad t \\geq 0 \\\\\n", - "g(x,0) &= u(x),\\qquad x\\in [0,1]\n", - "\\end{align*}\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "78d4195f", - "metadata": { - "editable": true - }, - "source": [ - "with $u(x) = \\sin(\\pi x)$.\n", - "\n", - "First, let us set up the deep neural network.\n", - "The deep neural network will follow the same structure as discussed in the examples solving the ODEs.\n", - "First, we will look into how Autograd could be used in a network tailored to solve for bivariate functions." - ] - }, - { - "cell_type": "markdown", - "id": "13f63286", - "metadata": { - "editable": true - }, - "source": [ - "## Setting up the network using Autograd\n", - "\n", - "The only change to do here, is to extend our network such that\n", - "functions of multiple parameters are correctly handled. In this case\n", - "we have two variables in our function to solve for, that is time $t$\n", - "and position $x$. The variables will be represented by a\n", - "one-dimensional array in the program. The program will evaluate the\n", - "network at each possible pair $(x,t)$, given an array for the desired\n", - "$x$-values and $t$-values to approximate the solution at." - ] - }, - { - "cell_type": "code", - "execution_count": 49, - "id": "e05767f4", - "metadata": { - "collapsed": false, - "editable": true - }, - "outputs": [], - "source": [ - "def sigmoid(z):\n", - " return 1/(1 + np.exp(-z))\n", - "\n", - "def deep_neural_network(deep_params, x):\n", - " # x is now a point and a 1D numpy array; make it a column vector\n", - " num_coordinates = np.size(x,0)\n", - " x = x.reshape(num_coordinates,-1)\n", - "\n", - " num_points = np.size(x,1)\n", - "\n", - " # N_hidden is the number of hidden layers\n", - " N_hidden = np.size(deep_params) - 1 # -1 since params consist of parameters to all the hidden layers AND the output layer\n", - "\n", - " # Assume that the input layer does nothing to the input x\n", - " x_input = x\n", - " x_prev = x_input\n", - "\n", - " ## Hidden layers:\n", - "\n", - " for l in range(N_hidden):\n", - " # From the list of parameters P; find the correct weigths and bias for this layer\n", - " w_hidden = deep_params[l]\n", - "\n", - " # Add a row of ones to include bias\n", - " x_prev = np.concatenate((np.ones((1,num_points)), x_prev ), axis = 0)\n", - "\n", - " z_hidden = np.matmul(w_hidden, x_prev)\n", - " x_hidden = sigmoid(z_hidden)\n", - "\n", - " # Update x_prev such that next layer can use the output from this layer\n", - " x_prev = x_hidden\n", - "\n", - " ## Output layer:\n", - "\n", - " # Get the weights and bias for this layer\n", - " w_output = deep_params[-1]\n", - "\n", - " # Include bias:\n", - " x_prev = np.concatenate((np.ones((1,num_points)), x_prev), axis = 0)\n", - "\n", - " z_output = np.matmul(w_output, x_prev)\n", - " x_output = z_output\n", - "\n", - " return x_output[0][0]" - ] - }, - { - "cell_type": "markdown", - "id": "d4ebc584", - "metadata": { - "editable": true - }, - "source": [ - "## Setting up the network using Autograd; The trial solution\n", - "\n", - "The cost function must then iterate through the given arrays\n", - "containing values for $x$ and $t$, defines a point $(x,t)$ the deep\n", - "neural network and the trial solution is evaluated at, and then finds\n", - "the Jacobian of the trial solution.\n", - "\n", - "A possible trial solution for this PDE is\n", - "\n", - "$$\n", - "g_t(x,t) = h_1(x,t) + x(1-x)tN(x,t,P)\n", - "$$\n", - "\n", - "with $A(x,t)$ being a function ensuring that $g_t(x,t)$ satisfies our given conditions, and $N(x,t,P)$ being the output from the deep neural network using weights and biases for each layer from $P$.\n", - "\n", - "To fulfill the conditions, $A(x,t)$ could be:\n", - "\n", - "$$\n", - "h_1(x,t) = (1-t)\\Big(u(x) - \\big((1-x)u(0) + x u(1)\\big)\\Big) = (1-t)u(x) = (1-t)\\sin(\\pi x)\n", - "$$\n", - "since $(0) = u(1) = 0$ and $u(x) = \\sin(\\pi x)$." - ] - }, - { - "cell_type": "markdown", - "id": "124b550e", - "metadata": { - "editable": true - }, - "source": [ - "## Why the jacobian?\n", - "\n", - "The Jacobian is used because the program must find the derivative of\n", - "the trial solution with respect to $x$ and $t$.\n", - "\n", - "This gives the necessity of computing the Jacobian matrix, as we want\n", - "to evaluate the gradient with respect to $x$ and $t$ (note that the\n", - "Jacobian of a scalar-valued multivariate function is simply its\n", - "gradient).\n", - "\n", - "In Autograd, the differentiation is by default done with respect to\n", - "the first input argument of your Python function. Since the points is\n", - "an array representing $x$ and $t$, the Jacobian is calculated using\n", - "the values of $x$ and $t$.\n", - "\n", - "To find the second derivative with respect to $x$ and $t$, the\n", - "Jacobian can be found for the second time. The result is a Hessian\n", - "matrix, which is the matrix containing all the possible second order\n", - "mixed derivatives of $g(x,t)$." - ] - }, - { - "cell_type": "code", - "execution_count": 50, - "id": "53c4c879", - "metadata": { - "collapsed": false, - "editable": true - }, - "outputs": [], - "source": [ - "# Set up the trial function:\n", - "def u(x):\n", - " return np.sin(np.pi*x)\n", - "\n", - "def g_trial(point,P):\n", - " x,t = point\n", - " return (1-t)*u(x) + x*(1-x)*t*deep_neural_network(P,point)\n", - "\n", - "# The right side of the ODE:\n", - "def f(point):\n", - " return 0.\n", - "\n", - "# The cost function:\n", - "def cost_function(P, x, t):\n", - " cost_sum = 0\n", - "\n", - " g_t_jacobian_func = jacobian(g_trial)\n", - " g_t_hessian_func = hessian(g_trial)\n", - "\n", - " for x_ in x:\n", - " for t_ in t:\n", - " point = np.array([x_,t_])\n", - "\n", - " g_t = g_trial(point,P)\n", - " g_t_jacobian = g_t_jacobian_func(point,P)\n", - " g_t_hessian = g_t_hessian_func(point,P)\n", - "\n", - " g_t_dt = g_t_jacobian[1]\n", - " g_t_d2x = g_t_hessian[0][0]\n", - "\n", - " func = f(point)\n", - "\n", - " err_sqr = ( (g_t_dt - g_t_d2x) - func)**2\n", - " cost_sum += err_sqr\n", - "\n", - " return cost_sum" - ] - }, - { - "cell_type": "markdown", - "id": "b11a26b8", - "metadata": { - "editable": true - }, - "source": [ - "## Setting up the network using Autograd; The full program\n", - "\n", - "Having set up the network, along with the trial solution and cost function, we can now see how the deep neural network performs by comparing the results to the analytical solution.\n", - "\n", - "The analytical solution of our problem is\n", - "\n", - "$$\n", - "g(x,t) = \\exp(-\\pi^2 t)\\sin(\\pi x)\n", - "$$\n", - "\n", - "A possible way to implement a neural network solving the PDE, is given below.\n", - "Be aware, though, that it is fairly slow for the parameters used.\n", - "A better result is possible, but requires more iterations, and thus longer time to complete.\n", - "\n", - "Indeed, the program below is not optimal in its implementation, but rather serves as an example on how to implement and use a neural network to solve a PDE.\n", - "Using TensorFlow results in a much better execution time. Try it!" - ] - }, - { - "cell_type": "code", - "execution_count": 51, - "id": "fa2d8508", - "metadata": { - "collapsed": false, - "editable": true - }, - "outputs": [], - "source": [ - "import autograd.numpy as np\n", - "from autograd import jacobian,hessian,grad\n", - "import autograd.numpy.random as npr\n", - "from matplotlib import cm\n", - "from matplotlib import pyplot as plt\n", - "from mpl_toolkits.mplot3d import axes3d\n", - "\n", - "## Set up the network\n", - "\n", - "def sigmoid(z):\n", - " return 1/(1 + np.exp(-z))\n", - "\n", - "def deep_neural_network(deep_params, x):\n", - " # x is now a point and a 1D numpy array; make it a column vector\n", - " num_coordinates = np.size(x,0)\n", - " x = x.reshape(num_coordinates,-1)\n", - "\n", - " num_points = np.size(x,1)\n", - "\n", - " # N_hidden is the number of hidden layers\n", - " N_hidden = np.size(deep_params) - 1 # -1 since params consist of parameters to all the hidden layers AND the output layer\n", - "\n", - " # Assume that the input layer does nothing to the input x\n", - " x_input = x\n", - " x_prev = x_input\n", - "\n", - " ## Hidden layers:\n", - "\n", - " for l in range(N_hidden):\n", - " # From the list of parameters P; find the correct weigths and bias for this layer\n", - " w_hidden = deep_params[l]\n", - "\n", - " # Add a row of ones to include bias\n", - " x_prev = np.concatenate((np.ones((1,num_points)), x_prev ), axis = 0)\n", - "\n", - " z_hidden = np.matmul(w_hidden, x_prev)\n", - " x_hidden = sigmoid(z_hidden)\n", - "\n", - " # Update x_prev such that next layer can use the output from this layer\n", - " x_prev = x_hidden\n", - "\n", - " ## Output layer:\n", - "\n", - " # Get the weights and bias for this layer\n", - " w_output = deep_params[-1]\n", - "\n", - " # Include bias:\n", - " x_prev = np.concatenate((np.ones((1,num_points)), x_prev), axis = 0)\n", - "\n", - " z_output = np.matmul(w_output, x_prev)\n", - " x_output = z_output\n", - "\n", - " return x_output[0][0]\n", - "\n", - "## Define the trial solution and cost function\n", - "def u(x):\n", - " return np.sin(np.pi*x)\n", - "\n", - "def g_trial(point,P):\n", - " x,t = point\n", - " return (1-t)*u(x) + x*(1-x)*t*deep_neural_network(P,point)\n", - "\n", - "# The right side of the ODE:\n", - "def f(point):\n", - " return 0.\n", - "\n", - "# The cost function:\n", - "def cost_function(P, x, t):\n", - " cost_sum = 0\n", - "\n", - " g_t_jacobian_func = jacobian(g_trial)\n", - " g_t_hessian_func = hessian(g_trial)\n", - "\n", - " for x_ in x:\n", - " for t_ in t:\n", - " point = np.array([x_,t_])\n", - "\n", - " g_t = g_trial(point,P)\n", - " g_t_jacobian = g_t_jacobian_func(point,P)\n", - " g_t_hessian = g_t_hessian_func(point,P)\n", - "\n", - " g_t_dt = g_t_jacobian[1]\n", - " g_t_d2x = g_t_hessian[0][0]\n", - "\n", - " func = f(point)\n", - "\n", - " err_sqr = ( (g_t_dt - g_t_d2x) - func)**2\n", - " cost_sum += err_sqr\n", - "\n", - " return cost_sum /( np.size(x)*np.size(t) )\n", - "\n", - "## For comparison, define the analytical solution\n", - "def g_analytic(point):\n", - " x,t = point\n", - " return np.exp(-np.pi**2*t)*np.sin(np.pi*x)\n", - "\n", - "## Set up a function for training the network to solve for the equation\n", - "def solve_pde_deep_neural_network(x,t, num_neurons, num_iter, lmb):\n", - " ## Set up initial weigths and biases\n", - " N_hidden = np.size(num_neurons)\n", - "\n", - " ## Set up initial weigths and biases\n", - "\n", - " # Initialize the list of parameters:\n", - " P = [None]*(N_hidden + 1) # + 1 to include the output layer\n", - "\n", - " P[0] = npr.randn(num_neurons[0], 2 + 1 ) # 2 since we have two points, +1 to include bias\n", - " for l in range(1,N_hidden):\n", - " P[l] = npr.randn(num_neurons[l], num_neurons[l-1] + 1) # +1 to include bias\n", - "\n", - " # For the output layer\n", - " P[-1] = npr.randn(1, num_neurons[-1] + 1 ) # +1 since bias is included\n", - "\n", - " print('Initial cost: ',cost_function(P, x, t))\n", - "\n", - " cost_function_grad = grad(cost_function,0)\n", - "\n", - " # Let the update be done num_iter times\n", - " for i in range(num_iter):\n", - " cost_grad = cost_function_grad(P, x , t)\n", - "\n", - " for l in range(N_hidden+1):\n", - " P[l] = P[l] - lmb * cost_grad[l]\n", - "\n", - " print('Final cost: ',cost_function(P, x, t))\n", - "\n", - " return P\n", - "\n", - "if __name__ == '__main__':\n", - " ### Use the neural network:\n", - " npr.seed(15)\n", - "\n", - " ## Decide the vales of arguments to the function to solve\n", - " Nx = 10; Nt = 10\n", - " x = np.linspace(0, 1, Nx)\n", - " t = np.linspace(0,1,Nt)\n", - "\n", - " ## Set up the parameters for the network\n", - " num_hidden_neurons = [100, 25]\n", - " num_iter = 250\n", - " lmb = 0.01\n", - "\n", - " P = solve_pde_deep_neural_network(x,t, num_hidden_neurons, num_iter, lmb)\n", - "\n", - " ## Store the results\n", - " g_dnn_ag = np.zeros((Nx, Nt))\n", - " G_analytical = np.zeros((Nx, Nt))\n", - " for i,x_ in enumerate(x):\n", - " for j, t_ in enumerate(t):\n", - " point = np.array([x_, t_])\n", - " g_dnn_ag[i,j] = g_trial(point,P)\n", - "\n", - " G_analytical[i,j] = g_analytic(point)\n", - "\n", - " # Find the map difference between the analytical and the computed solution\n", - " diff_ag = np.abs(g_dnn_ag - G_analytical)\n", - " print('Max absolute difference between the analytical solution and the network: %g'%np.max(diff_ag))\n", - "\n", - " ## Plot the solutions in two dimensions, that being in position and time\n", - "\n", - " T,X = np.meshgrid(t,x)\n", - "\n", - " fig = plt.figure(figsize=(10,10))\n", - " ax = fig.gca(projection='3d')\n", - " ax.set_title('Solution from the deep neural network w/ %d layer'%len(num_hidden_neurons))\n", - " s = ax.plot_surface(T,X,g_dnn_ag,linewidth=0,antialiased=False,cmap=cm.viridis)\n", - " ax.set_xlabel('Time $t$')\n", - " ax.set_ylabel('Position $x$');\n", - "\n", - "\n", - " fig = plt.figure(figsize=(10,10))\n", - " ax = fig.gca(projection='3d')\n", - " ax.set_title('Analytical solution')\n", - " s = ax.plot_surface(T,X,G_analytical,linewidth=0,antialiased=False,cmap=cm.viridis)\n", - " ax.set_xlabel('Time $t$')\n", - " ax.set_ylabel('Position $x$');\n", - "\n", - " fig = plt.figure(figsize=(10,10))\n", - " ax = fig.gca(projection='3d')\n", - " ax.set_title('Difference')\n", - " s = ax.plot_surface(T,X,diff_ag,linewidth=0,antialiased=False,cmap=cm.viridis)\n", - " ax.set_xlabel('Time $t$')\n", - " ax.set_ylabel('Position $x$');\n", - "\n", - " ## Take some slices of the 3D plots just to see the solutions at particular times\n", - " indx1 = 0\n", - " indx2 = int(Nt/2)\n", - " indx3 = Nt-1\n", - "\n", - " t1 = t[indx1]\n", - " t2 = t[indx2]\n", - " t3 = t[indx3]\n", - "\n", - " # Slice the results from the DNN\n", - " res1 = g_dnn_ag[:,indx1]\n", - " res2 = g_dnn_ag[:,indx2]\n", - " res3 = g_dnn_ag[:,indx3]\n", - "\n", - " # Slice the analytical results\n", - " res_analytical1 = G_analytical[:,indx1]\n", - " res_analytical2 = G_analytical[:,indx2]\n", - " res_analytical3 = G_analytical[:,indx3]\n", - "\n", - " # Plot the slices\n", - " plt.figure(figsize=(10,10))\n", - " plt.title(\"Computed solutions at time = %g\"%t1)\n", - " plt.plot(x, res1)\n", - " plt.plot(x,res_analytical1)\n", - " plt.legend(['dnn','analytical'])\n", - "\n", - " plt.figure(figsize=(10,10))\n", - " plt.title(\"Computed solutions at time = %g\"%t2)\n", - " plt.plot(x, res2)\n", - " plt.plot(x,res_analytical2)\n", - " plt.legend(['dnn','analytical'])\n", - "\n", - " plt.figure(figsize=(10,10))\n", - " plt.title(\"Computed solutions at time = %g\"%t3)\n", - " plt.plot(x, res3)\n", - " plt.plot(x,res_analytical3)\n", - " plt.legend(['dnn','analytical'])\n", - "\n", - " plt.show()" - ] - }, - { - "cell_type": "markdown", - "id": "4dfabc5e", - "metadata": { - "editable": true - }, - "source": [ - "## Example: Solving the wave equation with Neural Networks\n", - "\n", - "The wave equation is" - ] - }, - { - "cell_type": "markdown", - "id": "8f6f58e6", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\frac{\\partial^2 g(x,t)}{\\partial t^2} = c^2\\frac{\\partial^2 g(x,t)}{\\partial x^2}\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "8a4abe82", - "metadata": { - "editable": true - }, - "source": [ - "with $c$ being the specified wave speed.\n", - "\n", - "Here, the chosen conditions are" - ] - }, - { - "cell_type": "markdown", - "id": "57c34190", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\begin{align*}\n", - "\tg(0,t) &= 0 \\\\\n", - "\tg(1,t) &= 0 \\\\\n", - "\tg(x,0) &= u(x) \\\\\n", - "\t\\frac{\\partial g(x,t)}{\\partial t} \\Big |_{t = 0} &= v(x)\n", - "\\end{align*}\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "8c5b8137", - "metadata": { - "editable": true - }, - "source": [ - "where $\\frac{\\partial g(x,t)}{\\partial t} \\Big |_{t = 0}$ means the derivative of $g(x,t)$ with respect to $t$ is evaluated at $t = 0$, and $u(x)$ and $v(x)$ being given functions." - ] - }, - { - "cell_type": "markdown", - "id": "08cb8e62", - "metadata": { - "editable": true - }, - "source": [ - "## The problem to solve for\n", - "\n", - "The wave equation to solve for, is" - ] - }, - { - "cell_type": "markdown", - "id": "f7b1bf8c", - "metadata": { - "editable": true - }, - "source": [ - "\n", - "
\n", - "\n", - "$$\n", - "\\begin{equation} \\label{wave} \\tag{19}\n", - "\\frac{\\partial^2 g(x,t)}{\\partial t^2} = c^2 \\frac{\\partial^2 g(x,t)}{\\partial x^2}\n", - "\\end{equation}\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "1127e6e8", - "metadata": { - "editable": true - }, - "source": [ - "where $c$ is the given wave speed.\n", - "The chosen conditions for this equation are" - ] - }, - { - "cell_type": "markdown", - "id": "7a099129", - "metadata": { - "editable": true - }, - "source": [ - "\n", - "
\n", - "\n", - "$$\n", - "\\begin{aligned}\n", - "g(0,t) &= 0, &t \\geq 0 \\\\\n", - "g(1,t) &= 0, &t \\geq 0 \\\\\n", - "g(x,0) &= u(x), &x\\in[0,1] \\\\\n", - "\\frac{\\partial g(x,t)}{\\partial t}\\Big |_{t = 0} &= v(x), &x \\in [0,1]\n", - "\\end{aligned} \\label{condwave} \\tag{20}\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "772c7eec", - "metadata": { - "editable": true - }, - "source": [ - "In this example, let $c = 1$ and $u(x) = \\sin(\\pi x)$ and $v(x) = -\\pi\\sin(\\pi x)$." - ] - }, - { - "cell_type": "markdown", - "id": "be8649c8", - "metadata": { - "editable": true - }, - "source": [ - "## The trial solution\n", - "Setting up the network is done in similar matter as for the example of solving the diffusion equation.\n", - "The only things we have to change, is the trial solution such that it satisfies the conditions from ([20](#condwave)) and the cost function.\n", - "\n", - "The trial solution becomes slightly different since we have other conditions than in the example of solving the diffusion equation. Here, a possible trial solution $g_t(x,t)$ is\n", - "\n", - "$$\n", - "g_t(x,t) = h_1(x,t) + x(1-x)t^2N(x,t,P)\n", - "$$\n", - "\n", - "where\n", - "\n", - "$$\n", - "h_1(x,t) = (1-t^2)u(x) + tv(x)\n", - "$$\n", - "\n", - "Note that this trial solution satisfies the conditions only if $u(0) = v(0) = u(1) = v(1) = 0$, which is the case in this example." - ] - }, - { - "cell_type": "markdown", - "id": "27484fe1", - "metadata": { - "editable": true - }, - "source": [ - "## The analytical solution\n", - "\n", - "The analytical solution for our specific problem, is\n", - "\n", - "$$\n", - "g(x,t) = \\sin(\\pi x)\\cos(\\pi t) - \\sin(\\pi x)\\sin(\\pi t)\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "16f8dd35", - "metadata": { - "editable": true - }, - "source": [ - "## Solving the wave equation - the full program using Autograd" - ] - }, - { - "cell_type": "code", - "execution_count": 52, - "id": "51011a0f", - "metadata": { - "collapsed": false, - "editable": true - }, - "outputs": [], - "source": [ - "import autograd.numpy as np\n", - "from autograd import hessian,grad\n", - "import autograd.numpy.random as npr\n", - "from matplotlib import cm\n", - "from matplotlib import pyplot as plt\n", - "from mpl_toolkits.mplot3d import axes3d\n", - "\n", - "## Set up the trial function:\n", - "def u(x):\n", - " return np.sin(np.pi*x)\n", - "\n", - "def v(x):\n", - " return -np.pi*np.sin(np.pi*x)\n", - "\n", - "def h1(point):\n", - " x,t = point\n", - " return (1 - t**2)*u(x) + t*v(x)\n", - "\n", - "def g_trial(point,P):\n", - " x,t = point\n", - " return h1(point) + x*(1-x)*t**2*deep_neural_network(P,point)\n", - "\n", - "## Define the cost function\n", - "def cost_function(P, x, t):\n", - " cost_sum = 0\n", - "\n", - " g_t_hessian_func = hessian(g_trial)\n", - "\n", - " for x_ in x:\n", - " for t_ in t:\n", - " point = np.array([x_,t_])\n", - "\n", - " g_t_hessian = g_t_hessian_func(point,P)\n", - "\n", - " g_t_d2x = g_t_hessian[0][0]\n", - " g_t_d2t = g_t_hessian[1][1]\n", - "\n", - " err_sqr = ( (g_t_d2t - g_t_d2x) )**2\n", - " cost_sum += err_sqr\n", - "\n", - " return cost_sum / (np.size(t) * np.size(x))\n", - "\n", - "## The neural network\n", - "def sigmoid(z):\n", - " return 1/(1 + np.exp(-z))\n", - "\n", - "def deep_neural_network(deep_params, x):\n", - " # x is now a point and a 1D numpy array; make it a column vector\n", - " num_coordinates = np.size(x,0)\n", - " x = x.reshape(num_coordinates,-1)\n", - "\n", - " num_points = np.size(x,1)\n", - "\n", - " # N_hidden is the number of hidden layers\n", - " N_hidden = np.size(deep_params) - 1 # -1 since params consist of parameters to all the hidden layers AND the output layer\n", - "\n", - " # Assume that the input layer does nothing to the input x\n", - " x_input = x\n", - " x_prev = x_input\n", - "\n", - " ## Hidden layers:\n", - "\n", - " for l in range(N_hidden):\n", - " # From the list of parameters P; find the correct weigths and bias for this layer\n", - " w_hidden = deep_params[l]\n", - "\n", - " # Add a row of ones to include bias\n", - " x_prev = np.concatenate((np.ones((1,num_points)), x_prev ), axis = 0)\n", - "\n", - " z_hidden = np.matmul(w_hidden, x_prev)\n", - " x_hidden = sigmoid(z_hidden)\n", - "\n", - " # Update x_prev such that next layer can use the output from this layer\n", - " x_prev = x_hidden\n", - "\n", - " ## Output layer:\n", - "\n", - " # Get the weights and bias for this layer\n", - " w_output = deep_params[-1]\n", - "\n", - " # Include bias:\n", - " x_prev = np.concatenate((np.ones((1,num_points)), x_prev), axis = 0)\n", - "\n", - " z_output = np.matmul(w_output, x_prev)\n", - " x_output = z_output\n", - "\n", - " return x_output[0][0]\n", - "\n", - "## The analytical solution\n", - "def g_analytic(point):\n", - " x,t = point\n", - " return np.sin(np.pi*x)*np.cos(np.pi*t) - np.sin(np.pi*x)*np.sin(np.pi*t)\n", - "\n", - "def solve_pde_deep_neural_network(x,t, num_neurons, num_iter, lmb):\n", - " ## Set up initial weigths and biases\n", - " N_hidden = np.size(num_neurons)\n", - "\n", - " ## Set up initial weigths and biases\n", - "\n", - " # Initialize the list of parameters:\n", - " P = [None]*(N_hidden + 1) # + 1 to include the output layer\n", - "\n", - " P[0] = npr.randn(num_neurons[0], 2 + 1 ) # 2 since we have two points, +1 to include bias\n", - " for l in range(1,N_hidden):\n", - " P[l] = npr.randn(num_neurons[l], num_neurons[l-1] + 1) # +1 to include bias\n", - "\n", - " # For the output layer\n", - " P[-1] = npr.randn(1, num_neurons[-1] + 1 ) # +1 since bias is included\n", - "\n", - " print('Initial cost: ',cost_function(P, x, t))\n", - "\n", - " cost_function_grad = grad(cost_function,0)\n", - "\n", - " # Let the update be done num_iter times\n", - " for i in range(num_iter):\n", - " cost_grad = cost_function_grad(P, x , t)\n", - "\n", - " for l in range(N_hidden+1):\n", - " P[l] = P[l] - lmb * cost_grad[l]\n", - "\n", - "\n", - " print('Final cost: ',cost_function(P, x, t))\n", - "\n", - " return P\n", - "\n", - "if __name__ == '__main__':\n", - " ### Use the neural network:\n", - " npr.seed(15)\n", - "\n", - " ## Decide the vales of arguments to the function to solve\n", - " Nx = 10; Nt = 10\n", - " x = np.linspace(0, 1, Nx)\n", - " t = np.linspace(0,1,Nt)\n", - "\n", - " ## Set up the parameters for the network\n", - " num_hidden_neurons = [50,20]\n", - " num_iter = 1000\n", - " lmb = 0.01\n", - "\n", - " P = solve_pde_deep_neural_network(x,t, num_hidden_neurons, num_iter, lmb)\n", - "\n", - " ## Store the results\n", - " res = np.zeros((Nx, Nt))\n", - " res_analytical = np.zeros((Nx, Nt))\n", - " for i,x_ in enumerate(x):\n", - " for j, t_ in enumerate(t):\n", - " point = np.array([x_, t_])\n", - " res[i,j] = g_trial(point,P)\n", - "\n", - " res_analytical[i,j] = g_analytic(point)\n", - "\n", - " diff = np.abs(res - res_analytical)\n", - " print(\"Max difference between analytical and solution from nn: %g\"%np.max(diff))\n", - "\n", - " ## Plot the solutions in two dimensions, that being in position and time\n", - "\n", - " T,X = np.meshgrid(t,x)\n", - "\n", - " fig = plt.figure(figsize=(10,10))\n", - " ax = fig.gca(projection='3d')\n", - " ax.set_title('Solution from the deep neural network w/ %d layer'%len(num_hidden_neurons))\n", - " s = ax.plot_surface(T,X,res,linewidth=0,antialiased=False,cmap=cm.viridis)\n", - " ax.set_xlabel('Time $t$')\n", - " ax.set_ylabel('Position $x$');\n", - "\n", - "\n", - " fig = plt.figure(figsize=(10,10))\n", - " ax = fig.gca(projection='3d')\n", - " ax.set_title('Analytical solution')\n", - " s = ax.plot_surface(T,X,res_analytical,linewidth=0,antialiased=False,cmap=cm.viridis)\n", - " ax.set_xlabel('Time $t$')\n", - " ax.set_ylabel('Position $x$');\n", - "\n", - "\n", - " fig = plt.figure(figsize=(10,10))\n", - " ax = fig.gca(projection='3d')\n", - " ax.set_title('Difference')\n", - " s = ax.plot_surface(T,X,diff,linewidth=0,antialiased=False,cmap=cm.viridis)\n", - " ax.set_xlabel('Time $t$')\n", - " ax.set_ylabel('Position $x$');\n", - "\n", - " ## Take some slices of the 3D plots just to see the solutions at particular times\n", - " indx1 = 0\n", - " indx2 = int(Nt/2)\n", - " indx3 = Nt-1\n", - "\n", - " t1 = t[indx1]\n", - " t2 = t[indx2]\n", - " t3 = t[indx3]\n", - "\n", - " # Slice the results from the DNN\n", - " res1 = res[:,indx1]\n", - " res2 = res[:,indx2]\n", - " res3 = res[:,indx3]\n", - "\n", - " # Slice the analytical results\n", - " res_analytical1 = res_analytical[:,indx1]\n", - " res_analytical2 = res_analytical[:,indx2]\n", - " res_analytical3 = res_analytical[:,indx3]\n", - "\n", - " # Plot the slices\n", - " plt.figure(figsize=(10,10))\n", - " plt.title(\"Computed solutions at time = %g\"%t1)\n", - " plt.plot(x, res1)\n", - " plt.plot(x,res_analytical1)\n", - " plt.legend(['dnn','analytical'])\n", - "\n", - " plt.figure(figsize=(10,10))\n", - " plt.title(\"Computed solutions at time = %g\"%t2)\n", - " plt.plot(x, res2)\n", - " plt.plot(x,res_analytical2)\n", - " plt.legend(['dnn','analytical'])\n", - "\n", - " plt.figure(figsize=(10,10))\n", - " plt.title(\"Computed solutions at time = %g\"%t3)\n", - " plt.plot(x, res3)\n", - " plt.plot(x,res_analytical3)\n", - " plt.legend(['dnn','analytical'])\n", - "\n", - " plt.show()" - ] - }, - { - "cell_type": "markdown", - "id": "fff9e254", - "metadata": { - "editable": true - }, - "source": [ - "## Resources on differential equations and deep learning\n", - "\n", - "1. [Artificial neural networks for solving ordinary and partial differential equations by I.E. Lagaris et al](https://pdfs.semanticscholar.org/d061/df393e0e8fbfd0ea24976458b7d42419040d.pdf)\n", - "\n", - "2. [Neural networks for solving differential equations by A. Honchar](https://becominghuman.ai/neural-networks-for-solving-differential-equations-fa230ac5e04c)\n", - "\n", - "3. [Solving differential equations using neural networks by M.M Chiaramonte and M. Kiener](http://cs229.stanford.edu/proj2013/ChiaramonteKiener-SolvingDifferentialEquationsUsingNeuralNetworks.pdf)\n", - "\n", - "4. [Introduction to Partial Differential Equations by A. Tveito, R. Winther](https://www.springer.com/us/book/9783540225515)" - ] - } - ], - "metadata": {}, - "nbformat": 4, - "nbformat_minor": 5 -} diff --git a/doc/LectureNotes/week44.ipynb b/doc/LectureNotes/week44.ipynb deleted file mode 100644 index a3733ab37..000000000 --- a/doc/LectureNotes/week44.ipynb +++ /dev/null @@ -1,5951 +0,0 @@ -{ - "cells": [ - { - "cell_type": "markdown", - "id": "e819719c", - "metadata": {}, - "source": [ - "\n", - "" - ] - }, - { - "cell_type": "markdown", - "id": "560c07a9", - "metadata": {}, - "source": [ - "# Week 44, Convolutional Neural Networks (CNN)\n", - "**Morten Hjorth-Jensen**, Department of Physics, University of Oslo and Department of Physics and Astronomy and National Superconducting Cyclotron Laboratory, Michigan State University\n", - "\n", - "Date: **October 30-November 3**" - ] - }, - { - "cell_type": "markdown", - "id": "6cfe69eb", - "metadata": {}, - "source": [ - "## Plan for week 44\n", - "\n", - "**Material for the active learning sessions on Tuesday and Wednesday.**\n", - "\n", - " * Exercise on writing your own neural network code, application to the OR and XOR gates, see notes from last week\n", - "\n", - " * The exercise this week is a continuation from last week\n", - "\n", - " * Discussion of project 2\n", - "\n", - " * [Video of lab session from week 43](https://youtu.be/Ia6wwDLxqtM)\n", - "\n", - " * [Video of lab session from week 44](https://youtu.be/EajWMW__k0I)\n", - "\n", - " * [See also whiteboard notes from lab session week 44](https://github.com/CompPhysics/MachineLearning/blob/master/doc/HandWrittenNotes/2023/Exercisesweek44.pdf)\n", - "\n", - " \n", - "\n", - "**Material for the lecture on Thursday November 2, 2023.**\n", - "\n", - " * Convolutional Neural Networks\n", - "\n", - " * Readings and Videos:\n", - "\n", - " * These lecture notes\n", - "\n", - " * For a more in depth discussion on neural networks we recommend Goodfellow et al chapter 9. See also chapter 11 and 12 on practicalities and applications \n", - "\n", - " * Reading suggestions for implementation of CNNs: [Aurelien Geron's chapter 13](https://github.com/CompPhysics/MachineLearning/blob/master/doc/Textbooks/TensorflowML.pdf). \n", - "\n", - " * [Video on Deep Learning](https://www.youtube.com/playlist?list=PLZHQObOWTQDNU6R1_67000Dx_ZCJB-3pi)\n", - "\n", - " * [Video on Convolutional Neural Networks from MIT](https://www.youtube.com/watch?v=iaSUYvmCekI&ab_channel=AlexanderAmini)\n", - "\n", - " * [Video on CNNs from Stanford](https://www.youtube.com/watch?v=bNb2fEVKeEo&list=PLC1qU-LWwrF64f4QKQT-Vg5Wr4qEE1Zxk&index=6&ab_channel=StanfordUniversitySchoolofEngineering)\n", - "\n", - "**And Lecture material on CNNs.**\n", - "\n", - "* [See Michael Nielsen's Lectures](http://neuralnetworksanddeeplearning.com/chap6.html)" - ] - }, - { - "cell_type": "markdown", - "id": "969e3bfb", - "metadata": {}, - "source": [ - "## Material for Lecture Thursday November 2" - ] - }, - { - "cell_type": "markdown", - "id": "4658c67a", - "metadata": {}, - "source": [ - "## Convolutional Neural Networks (recognizing images)\n", - "\n", - "Convolutional neural networks (CNNs) were developed during the last\n", - "decade of the previous century, with a focus on character recognition\n", - "tasks. Nowadays, CNNs are a central element in the spectacular success\n", - "of deep learning methods. The success in for example image\n", - "classifications have made them a central tool for most machine\n", - "learning practitioners.\n", - "\n", - "CNNs are very similar to ordinary Neural Networks.\n", - "They are made up of neurons that have learnable weights and\n", - "biases. Each neuron receives some inputs, performs a dot product and\n", - "optionally follows it with a non-linearity. The whole network still\n", - "expresses a single differentiable score function: from the raw image\n", - "pixels on one end to class scores at the other. And they still have a\n", - "loss function (for example Softmax) on the last (fully-connected) layer\n", - "and all the tips/tricks we developed for learning regular Neural\n", - "Networks still apply (back propagation, gradient descent etc etc)." - ] - }, - { - "cell_type": "markdown", - "id": "99ef8af3", - "metadata": {}, - "source": [ - "## What is the Difference\n", - "\n", - "**CNN architectures make the explicit assumption that\n", - "the inputs are images, which allows us to encode certain properties\n", - "into the architecture. These then make the forward function more\n", - "efficient to implement and vastly reduce the amount of parameters in\n", - "the network.**" - ] - }, - { - "cell_type": "markdown", - "id": "6c8fb76c", - "metadata": {}, - "source": [ - "## Neural Networks vs CNNs\n", - "\n", - "Neural networks are defined as **affine transformations**, that is \n", - "a vector is received as input and is multiplied with a matrix of so-called weights (our unknown paramters) to produce an\n", - "output (to which a bias vector is usually added before passing the result\n", - "through a nonlinear activation function). This is applicable to any type of input, be it an\n", - "image, a sound clip or an unordered collection of features: whatever their\n", - "dimensionality, their representation can always be flattened into a vector\n", - "before the transformation." - ] - }, - { - "cell_type": "markdown", - "id": "0dd2198c", - "metadata": {}, - "source": [ - "## Why CNNS for images, sound files, medical images from CT scans etc?\n", - "\n", - "However, when we consider images, sound clips and many other similar kinds of data, these data have an intrinsic\n", - "structure. More formally, they share these important properties:\n", - "* They are stored as multi-dimensional arrays (think of the pixels of a figure) .\n", - "\n", - "* They feature one or more axes for which ordering matters (e.g., width and height axes for an image, time axis for a sound clip).\n", - "\n", - "* One axis, called the channel axis, is used to access different views of the data (e.g., the red, green and blue channels of a color image, or the left and right channels of a stereo audio track).\n", - "\n", - "These properties are not exploited when an affine transformation is applied; in\n", - "fact, all the axes are treated in the same way and the topological information\n", - "is not taken into account. Still, taking advantage of the implicit structure of\n", - "the data may prove very handy in solving some tasks, like computer vision and\n", - "speech recognition, and in these cases it would be best to preserve it. This is\n", - "where discrete convolutions come into play.\n", - "\n", - "A discrete convolution is a linear transformation that preserves this notion of\n", - "ordering. It is sparse (only a few input units contribute to a given output\n", - "unit) and reuses parameters (the same weights are applied to multiple locations\n", - "in the input)." - ] - }, - { - "cell_type": "markdown", - "id": "70924749", - "metadata": {}, - "source": [ - "## Regular NNs don’t scale well to full images\n", - "\n", - "As an example, consider\n", - "an image of size $32\\times 32\\times 3$ (32 wide, 32 high, 3 color channels), so a\n", - "single fully-connected neuron in a first hidden layer of a regular\n", - "Neural Network would have $32\\times 32\\times 3 = 3072$ weights. This amount still\n", - "seems manageable, but clearly this fully-connected structure does not\n", - "scale to larger images. For example, an image of more respectable\n", - "size, say $200\\times 200\\times 3$, would lead to neurons that have \n", - "$200\\times 200\\times 3 = 120,000$ weights. \n", - "\n", - "We could have\n", - "several such neurons, and the parameters would add up quickly! Clearly,\n", - "this full connectivity is wasteful and the huge number of parameters\n", - "would quickly lead to possible overfitting.\n", - "\n", - "\n", - "\n", - "\n", - "

Figure 1: A regular 3-layer Neural Network.

\n", - "" - ] - }, - { - "cell_type": "markdown", - "id": "618b6e71", - "metadata": {}, - "source": [ - "## 3D volumes of neurons\n", - "\n", - "Convolutional Neural Networks take advantage of the fact that the\n", - "input consists of images and they constrain the architecture in a more\n", - "sensible way. \n", - "\n", - "In particular, unlike a regular Neural Network, the\n", - "layers of a CNN have neurons arranged in 3 dimensions: width,\n", - "height, depth. (Note that the word depth here refers to the third\n", - "dimension of an activation volume, not to the depth of a full Neural\n", - "Network, which can refer to the total number of layers in a network.)\n", - "\n", - "To understand it better, the above example of an image \n", - "with an input volume of\n", - "activations has dimensions $32\\times 32\\times 3$ (width, height,\n", - "depth respectively). \n", - "\n", - "The neurons in a layer will\n", - "only be connected to a small region of the layer before it, instead of\n", - "all of the neurons in a fully-connected manner. Moreover, the final\n", - "output layer could for this specific image have dimensions $1\\times 1 \\times 10$, \n", - "because by the\n", - "end of the CNN architecture we will reduce the full image into a\n", - "single vector of class scores, arranged along the depth\n", - "dimension. \n", - "\n", - "\n", - "\n", - "\n", - "

Figure 1: A CNN arranges its neurons in three dimensions (width, height, depth), as visualized in one of the layers. Every layer of a CNN transforms the 3D input volume to a 3D output volume of neuron activations. In this example, the red input layer holds the image, so its width and height would be the dimensions of the image, and the depth would be 3 (Red, Green, Blue channels).

\n", - "" - ] - }, - { - "cell_type": "markdown", - "id": "8f87c704", - "metadata": {}, - "source": [ - "## Layers used to build CNNs\n", - "\n", - "A simple CNN is a sequence of layers, and every layer of a CNN\n", - "transforms one volume of activations to another through a\n", - "differentiable function. We use three main types of layers to build\n", - "CNN architectures: Convolutional Layer, Pooling Layer, and\n", - "Fully-Connected Layer (exactly as seen in regular Neural Networks). We\n", - "will stack these layers to form a full CNN architecture.\n", - "\n", - "A simple CNN for image classification could have the architecture:\n", - "\n", - "* **INPUT** ($32\\times 32 \\times 3$) will hold the raw pixel values of the image, in this case an image of width 32, height 32, and with three color channels R,G,B.\n", - "\n", - "* **CONV** (convolutional )layer will compute the output of neurons that are connected to local regions in the input, each computing a dot product between their weights and a small region they are connected to in the input volume. This may result in volume such as $[32\\times 32\\times 12]$ if we decided to use 12 filters.\n", - "\n", - "* **RELU** layer will apply an elementwise activation function, such as the $max(0,x)$ thresholding at zero. This leaves the size of the volume unchanged ($[32\\times 32\\times 12]$).\n", - "\n", - "* **POOL** (pooling) layer will perform a downsampling operation along the spatial dimensions (width, height), resulting in volume such as $[16\\times 16\\times 12]$.\n", - "\n", - "* **FC** (i.e. fully-connected) layer will compute the class scores, resulting in volume of size $[1\\times 1\\times 10]$, where each of the 10 numbers correspond to a class score, such as among the 10 categories of the MNIST images we considered above . As with ordinary Neural Networks and as the name implies, each neuron in this layer will be connected to all the numbers in the previous volume." - ] - }, - { - "cell_type": "markdown", - "id": "15d8f220", - "metadata": {}, - "source": [ - "## Transforming images\n", - "\n", - "CNNs transform the original image layer by layer from the original\n", - "pixel values to the final class scores. \n", - "\n", - "Observe that some layers contain\n", - "parameters and other don’t. In particular, the CNN layers perform\n", - "transformations that are a function of not only the activations in the\n", - "input volume, but also of the parameters (the weights and biases of\n", - "the neurons). On the other hand, the RELU/POOL layers will implement a\n", - "fixed function. The parameters in the CONV/FC layers will be trained\n", - "with gradient descent so that the class scores that the CNN computes\n", - "are consistent with the labels in the training set for each image." - ] - }, - { - "cell_type": "markdown", - "id": "6b314939", - "metadata": {}, - "source": [ - "## CNNs in brief\n", - "\n", - "In summary:\n", - "\n", - "* A CNN architecture is in the simplest case a list of Layers that transform the image volume into an output volume (e.g. holding the class scores)\n", - "\n", - "* There are a few distinct types of Layers (e.g. CONV/FC/RELU/POOL are by far the most popular)\n", - "\n", - "* Each Layer accepts an input 3D volume and transforms it to an output 3D volume through a differentiable function\n", - "\n", - "* Each Layer may or may not have parameters (e.g. CONV/FC do, RELU/POOL don’t)\n", - "\n", - "* Each Layer may or may not have additional hyperparameters (e.g. CONV/FC/POOL do, RELU doesn’t)\n", - "\n", - "For more material on convolutional networks, we strongly recommend\n", - "the course\n", - "[CS231](http://cs231n.github.io/convolutional-networks/) which is taught at Stanford University (consistently ranked as one of the top computer science programs in the world). [Michael Nielsen's book is a must read, in particular chapter 6 which deals with CNNs](http://neuralnetworksanddeeplearning.com/chap6.html).\n", - "\n", - "The textbook by Goodfellow et al, see chapter 9 contains an in depth discussion as well." - ] - }, - { - "cell_type": "markdown", - "id": "08156a7a", - "metadata": {}, - "source": [ - "## Key Idea\n", - "\n", - "A dense neural network is representd by an affine operation (like matrix-matrix multiplication) where all parameters are included.\n", - "\n", - "The key idea in CNNs for say imaging is that in images neighbor pixels tend to be related! So we connect\n", - "only neighboring neurons in the input instead of connecting all with the first hidden layer.\n", - "\n", - "We say we perform a filtering (convolution is the mathematical operation)." - ] - }, - { - "cell_type": "markdown", - "id": "bb53a363", - "metadata": {}, - "source": [ - "## Mathematics of CNNs\n", - "\n", - "The mathematics of CNNs is based on the mathematical operation of\n", - "**convolution**. In mathematics (in particular in functional analysis),\n", - "convolution is represented by mathematical operation (integration,\n", - "summation etc) on two function in order to produce a third function\n", - "that expresses how the shape of one gets modified by the other.\n", - "Convolution has a plethora of applications in a variety of disciplines, spanning from statistics to signal processing, computer vision, solutions of differential equations,linear algebra, engineering, and yes, machine learning.\n", - "\n", - "Mathematically, convolution is defined as follows (one-dimensional example):\n", - "Let us define a continuous function $y(t)$ given by" - ] - }, - { - "cell_type": "markdown", - "id": "8835386d", - "metadata": {}, - "source": [ - "$$\n", - "y(t) = \\int x(a) w(t-a) da,\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "098e15c2", - "metadata": {}, - "source": [ - "where $x(a)$ represents a so-called input and $w(t-a)$ is normally called the weight function or kernel.\n", - "\n", - "The above integral is written in a more compact form as" - ] - }, - { - "cell_type": "markdown", - "id": "4dfb7ed3", - "metadata": {}, - "source": [ - "$$\n", - "y(t) = \\left(x * w\\right)(t).\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "99b69cad", - "metadata": {}, - "source": [ - "The discretized version reads" - ] - }, - { - "cell_type": "markdown", - "id": "ab342220", - "metadata": {}, - "source": [ - "$$\n", - "y(t) = \\sum_{a=-\\infty}^{a=\\infty}x(a)w(t-a).\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "44d11bbe", - "metadata": {}, - "source": [ - "Computing the inverse of the above convolution operations is known as deconvolution.\n", - "\n", - "How can we use this? And what does it mean? Let us study some familiar examples first." - ] - }, - { - "cell_type": "markdown", - "id": "1331f0c5", - "metadata": {}, - "source": [ - "## Convolution Examples: Polynomial multiplication\n", - "\n", - "We have already met such an example in project 1 when we tried to set\n", - "up the design matrix for a two-dimensional function. This was an\n", - "example of polynomial multiplication. Let us recast such a problem in terms of the convolution operation.\n", - "Let us look a the following polynomials to second and third order, respectively:" - ] - }, - { - "cell_type": "markdown", - "id": "55402188", - "metadata": {}, - "source": [ - "$$\n", - "p(t) = \\alpha_0+\\alpha_1 t+\\alpha_2 t^2,\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "e98603af", - "metadata": {}, - "source": [ - "and" - ] - }, - { - "cell_type": "markdown", - "id": "0bf4d76c", - "metadata": {}, - "source": [ - "$$\n", - "s(t) = \\beta_0+\\beta_1 t+\\beta_2 t^2+\\beta_3 t^3.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "7a909516", - "metadata": {}, - "source": [ - "The polynomial multiplication gives us a new polynomial of degree $5$" - ] - }, - { - "cell_type": "markdown", - "id": "40f9a726", - "metadata": {}, - "source": [ - "$$\n", - "z(t) = \\delta_0+\\delta_1 t+\\delta_2 t^2+\\delta_3 t^3+\\delta_4 t^4+\\delta_5 t^5.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "b6720a8f", - "metadata": {}, - "source": [ - "## Efficient Polynomial Multiplication\n", - "\n", - "Computing polynomial products can be implemented efficiently if we rewrite the more brute force multiplications using convolution.\n", - "We note first that the new coefficients are given as" - ] - }, - { - "cell_type": "markdown", - "id": "f515eff5", - "metadata": {}, - "source": [ - "$$\n", - "\\begin{split}\n", - "\\delta_0=&\\alpha_0\\beta_0\\\\\n", - "\\delta_1=&\\alpha_1\\beta_0+\\alpha_1\\beta_0\\\\\n", - "\\delta_2=&\\alpha_0\\beta_2+\\alpha_1\\beta_1+\\alpha_2\\beta_0\\\\\n", - "\\delta_3=&\\alpha_1\\beta_2+\\alpha_2\\beta_1+\\alpha_0\\beta_3\\\\\n", - "\\delta_4=&\\alpha_2\\beta_2+\\alpha_1\\beta_3\\\\\n", - "\\delta_5=&\\alpha_2\\beta_3.\\\\\n", - "\\end{split}\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "6dc0dfd7", - "metadata": {}, - "source": [ - "We note that $\\alpha_i=0$ except for $i\\in \\left\\{0,1,2\\right\\}$ and $\\beta_i=0$ except for $i\\in\\left\\{0,1,2,3\\right\\}$.\n", - "\n", - "We can then rewrite the coefficients $\\delta_j$ using a discrete convolution as" - ] - }, - { - "cell_type": "markdown", - "id": "619e31c1", - "metadata": {}, - "source": [ - "$$\n", - "\\delta_j = \\sum_{i=-\\infty}^{i=\\infty}\\alpha_i\\beta_{j-i}=(\\alpha * \\beta)_j,\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "bd052428", - "metadata": {}, - "source": [ - "or as a double sum with restriction $l=i+j$" - ] - }, - { - "cell_type": "markdown", - "id": "584f7ccb", - "metadata": {}, - "source": [ - "$$\n", - "\\delta_l = \\sum_{ij}\\alpha_i\\beta_{j}.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "a7a12d8f", - "metadata": {}, - "source": [ - "Do you see a potential drawback with these equations?" - ] - }, - { - "cell_type": "markdown", - "id": "dedb3be2", - "metadata": {}, - "source": [ - "## A more efficient way of coding the above Convolution\n", - "\n", - "Since we only have a finite number of $\\alpha$ and $\\beta$ values\n", - "which are non-zero, we can rewrite the above convolution expressions\n", - "as a matrix-vector multiplication" - ] - }, - { - "cell_type": "markdown", - "id": "524eab3c", - "metadata": {}, - "source": [ - "$$\n", - "\\boldsymbol{\\delta}=\\begin{bmatrix}\\alpha_0 & 0 & 0 & 0 \\\\\n", - " \\alpha_1 & \\alpha_0 & 0 & 0 \\\\\n", - "\t\t\t \\alpha_2 & \\alpha_1 & \\alpha_0 & 0 \\\\\n", - "\t\t\t 0 & \\alpha_2 & \\alpha_1 & \\alpha_0 \\\\\n", - "\t\t\t 0 & 0 & \\alpha_2 & \\alpha_1 \\\\\n", - "\t\t\t 0 & 0 & 0 & \\alpha_2\n", - "\t\t\t \\end{bmatrix}\\begin{bmatrix} \\beta_0 \\\\ \\beta_1 \\\\ \\beta_2 \\\\ \\beta_3\\end{bmatrix}.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "ad6d8e0e", - "metadata": {}, - "source": [ - "The process is commutative and we can easily see that we can rewrite the multiplication in terms of a matrix holding $\\beta$ and a vector holding $\\alpha$.\n", - "In this case we have" - ] - }, - { - "cell_type": "markdown", - "id": "fc3e73a5", - "metadata": {}, - "source": [ - "$$\n", - "\\boldsymbol{\\delta}=\\begin{bmatrix}\\beta_0 & 0 & 0 \\\\\n", - " \\beta_1 & \\beta_0 & 0 \\\\\n", - "\t\t\t \\beta_2 & \\beta_1 & \\beta_0 \\\\\n", - "\t\t\t \\beta_3 & \\beta_2 & \\beta_1 \\\\\n", - "\t\t\t 0 & \\beta_3 & \\beta_2 \\\\\n", - "\t\t\t 0 & 0 & \\beta_3\n", - "\t\t\t \\end{bmatrix}\\begin{bmatrix} \\alpha_0 \\\\ \\alpha_1 \\\\ \\alpha_2\\end{bmatrix}.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "1766bfc3", - "metadata": {}, - "source": [ - "Note that the use of these matrices is for mathematical purposes only and not implementation purposes.\n", - "When implementing the above equation we do not encode (and allocate memory) the matrices explicitely.\n", - "We rather code the convolutions in the minimal memory footprint that they require.\n", - "\n", - "Does the number of floating point operations change here when we use the commutative property?\n", - "\n", - "The above matrices are examples of so-called [Toeplitz\n", - "matrices](https://link.springer.com/book/10.1007/978-93-86279-04-0). A\n", - "Toeplitz matrix is a matrix in which each descending diagonal from\n", - "left to right is constant. For instance the last matrix, which we\n", - "rewrite as" - ] - }, - { - "cell_type": "markdown", - "id": "d79f9173", - "metadata": {}, - "source": [ - "$$\n", - "\\boldsymbol{A}=\\begin{bmatrix}a_0 & 0 & 0 \\\\\n", - " a_1 & a_0 & 0 \\\\\n", - "\t\t\t a_2 & a_1 & a_0 \\\\\n", - "\t\t\t a_3 & a_2 & a_1 \\\\\n", - "\t\t\t 0 & a_3 & a_2 \\\\\n", - "\t\t\t 0 & 0 & a_3\n", - "\t\t\t \\end{bmatrix},\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "ad6ed7a5", - "metadata": {}, - "source": [ - "with elements $a_{ii}=a_{i+1,j+1}=a_{i-j}$ is an example of a Toeplitz\n", - "matrix. Such a matrix does not need to be a square matrix. Toeplitz\n", - "matrices are also closely connected with Fourier series discussed\n", - "below, because the multiplication operator by a trigonometric\n", - "polynomial, compressed to a finite-dimensional space, can be\n", - "represented by such a matrix. The example above shows that we can\n", - "represent linear convolution as multiplication of a Toeplitz matrix by\n", - "a vector." - ] - }, - { - "cell_type": "markdown", - "id": "e792cb5f", - "metadata": {}, - "source": [ - "## Convolution Examples: Principle of Superposition and Periodic Forces (Fourier Transforms)\n", - "\n", - "For problems with so-called harmonic oscillations, given by for example the following differential equation" - ] - }, - { - "cell_type": "markdown", - "id": "d5aa44c1", - "metadata": {}, - "source": [ - "$$\n", - "m\\frac{d^2x}{dt^2}+\\eta\\frac{dx}{dt}+x(t)=F(t),\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "2d9e1071", - "metadata": {}, - "source": [ - "where $F(t)$ is an applied external force acting on the system (often\n", - "called a driving force), one can use the theory of Fourier\n", - "transformations to find the solutions of this type of equations.\n", - "\n", - "If one has several driving forces, $F(t)=\\sum_n F_n(t)$, one can find\n", - "the particular solution $x_{pn}(t)$ to the above differential equation for each $F_n$. The particular\n", - "solution for the entire driving force is then given by a series like" - ] - }, - { - "cell_type": "markdown", - "id": "74eb7fa4", - "metadata": {}, - "source": [ - "\n", - "
\n", - "\n", - "$$\n", - "\\begin{equation}\n", - "x_p(t)=\\sum_nx_{pn}(t).\n", - "\\label{_auto1} \\tag{1}\n", - "\\end{equation}\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "27373683", - "metadata": {}, - "source": [ - "This is known as the principle of superposition. It only applies when\n", - "the homogenous equation is linear. \n", - "Superposition is especially useful when $F(t)$ can be written\n", - "as a sum of sinusoidal terms, because the solutions for each\n", - "sinusoidal (sine or cosine) term is analytic. \n", - "\n", - "Driving forces are often periodic, even when they are not\n", - "sinusoidal. Periodicity implies that for some time $t$ our function repeats itself periodically after a period $\\tau$, that is" - ] - }, - { - "cell_type": "markdown", - "id": "fd5e9b0f", - "metadata": {}, - "source": [ - "$$\n", - "\\begin{eqnarray}\n", - "F(t+\\tau)=F(t). \n", - "\\end{eqnarray}\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "b0651b77", - "metadata": {}, - "source": [ - "One example of a non-sinusoidal periodic force is a square wave. Many\n", - "components in electric circuits are non-linear, for example diodes. This \n", - "makes many wave forms non-sinusoidal even when the circuits are being\n", - "driven by purely sinusoidal sources." - ] - }, - { - "cell_type": "markdown", - "id": "36246f87", - "metadata": {}, - "source": [ - "## Simple Code Example\n", - "\n", - "The code here shows a typical example of such a square wave generated\n", - "using the functionality included in the **scipy** Python package. We\n", - "have used a period of $\\tau=0.2$." - ] - }, - { - "cell_type": "code", - "execution_count": 1, - "id": "fa7c932a", - "metadata": {}, - "outputs": [], - "source": [ - "%matplotlib inline\n", - "\n", - "import numpy as np\n", - "import math\n", - "from scipy import signal\n", - "import matplotlib.pyplot as plt\n", - "\n", - "# number of points \n", - "n = 500\n", - "# start and final times \n", - "t0 = 0.0\n", - "tn = 1.0\n", - "# Period \n", - "t = np.linspace(t0, tn, n, endpoint=False)\n", - "SqrSignal = np.zeros(n)\n", - "SqrSignal = 1.0+signal.square(2*np.pi*5*t)\n", - "plt.plot(t, SqrSignal)\n", - "plt.ylim(-0.5, 2.5)\n", - "plt.show()" - ] - }, - { - "cell_type": "markdown", - "id": "aff076a3", - "metadata": {}, - "source": [ - "For the sinusoidal example the\n", - "period is $\\tau=2\\pi/\\omega$. However, higher harmonics can also\n", - "satisfy the periodicity requirement. In general, any force that\n", - "satisfies the periodicity requirement can be expressed as a sum over\n", - "harmonics," - ] - }, - { - "cell_type": "markdown", - "id": "8879200e", - "metadata": {}, - "source": [ - "\n", - "
\n", - "\n", - "$$\n", - "\\begin{equation}\n", - "F(t)=\\frac{f_0}{2}+\\sum_{n>0} f_n\\cos(2n\\pi t/\\tau)+g_n\\sin(2n\\pi t/\\tau).\n", - "\\label{_auto2} \\tag{2}\n", - "\\end{equation}\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "418c3a5e", - "metadata": {}, - "source": [ - "## Wrapping up Fourier transforms\n", - "\n", - "We can write down the answer for\n", - "$x_{pn}(t)$, by substituting $f_n/m$ or $g_n/m$ for $F_0/m$. By\n", - "writing each factor $2n\\pi t/\\tau$ as $n\\omega t$, with $\\omega\\equiv\n", - "2\\pi/\\tau$," - ] - }, - { - "cell_type": "markdown", - "id": "2ef255bf", - "metadata": {}, - "source": [ - "\n", - "
\n", - "\n", - "$$\n", - "\\begin{equation}\n", - "\\label{eq:fourierdef1} \\tag{3}\n", - "F(t)=\\frac{f_0}{2}+\\sum_{n>0}f_n\\cos(n\\omega t)+g_n\\sin(n\\omega t).\n", - "\\end{equation}\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "256eacba", - "metadata": {}, - "source": [ - "The solutions for $x(t)$ then come from replacing $\\omega$ with\n", - "$n\\omega$ for each term in the particular solution," - ] - }, - { - "cell_type": "markdown", - "id": "ae377df9", - "metadata": {}, - "source": [ - "$$\n", - "\\begin{eqnarray}\n", - "x_p(t)&=&\\frac{f_0}{2k}+\\sum_{n>0} \\alpha_n\\cos(n\\omega t-\\delta_n)+\\beta_n\\sin(n\\omega t-\\delta_n),\\\\\n", - "\\nonumber\n", - "\\alpha_n&=&\\frac{f_n/m}{\\sqrt{((n\\omega)^2-\\omega_0^2)+4\\beta^2n^2\\omega^2}},\\\\\n", - "\\nonumber\n", - "\\beta_n&=&\\frac{g_n/m}{\\sqrt{((n\\omega)^2-\\omega_0^2)+4\\beta^2n^2\\omega^2}},\\\\\n", - "\\nonumber\n", - "\\delta_n&=&\\tan^{-1}\\left(\\frac{2\\beta n\\omega}{\\omega_0^2-n^2\\omega^2}\\right).\n", - "\\end{eqnarray}\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "c18496b9", - "metadata": {}, - "source": [ - "## Finding the Coefficients\n", - "\n", - "Because the forces have been applied for a long time, any non-zero\n", - "damping eliminates the homogenous parts of the solution. We need then \n", - "only consider the particular solution for each $n$.\n", - "\n", - "The problem is considered solved if one can find expressions for the\n", - "coefficients $f_n$ and $g_n$, even though the solutions are expressed\n", - "as an infinite sum. The coefficients can be extracted from the\n", - "function $F(t)$ by" - ] - }, - { - "cell_type": "markdown", - "id": "98909a25", - "metadata": {}, - "source": [ - "\n", - "
\n", - "\n", - "$$\n", - "\\begin{eqnarray}\n", - "\\label{eq:fourierdef2} \\tag{4}\n", - "f_n&=&\\frac{2}{\\tau}\\int_{-\\tau/2}^{\\tau/2} dt~F(t)\\cos(2n\\pi t/\\tau),\\\\\n", - "\\nonumber\n", - "g_n&=&\\frac{2}{\\tau}\\int_{-\\tau/2}^{\\tau/2} dt~F(t)\\sin(2n\\pi t/\\tau).\n", - "\\end{eqnarray}\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "24ea20f8", - "metadata": {}, - "source": [ - "To check the consistency of these expressions and to verify\n", - "Eq. ([4](#eq:fourierdef2)), one can insert the expansion of $F(t)$ in\n", - "Eq. ([3](#eq:fourierdef1)) into the expression for the coefficients in\n", - "Eq. ([4](#eq:fourierdef2)) and see whether" - ] - }, - { - "cell_type": "markdown", - "id": "667eef29", - "metadata": {}, - "source": [ - "$$\n", - "f_n=\\frac{2}{\\tau}\\int_{-\\tau/2}^{\\tau/2} dt~\\left\\{\\frac{f_0}{2}+\\sum_{m>0}f_m\\cos(m\\omega t)+g_m\\sin(m\\omega t)\\right\\}\\cos(n\\omega t).\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "cc55e413", - "metadata": {}, - "source": [ - "Immediately, one can throw away all the terms with $g_m$ because they\n", - "convolute an even and an odd function. The term with $f_0/2$\n", - "disappears because $\\cos(n\\omega t)$ is equally positive and negative\n", - "over the interval and will integrate to zero. For all the terms\n", - "$f_m\\cos(m\\omega t)$ appearing in the sum, one can use angle addition\n", - "formulas to see that $\\cos(m\\omega t)\\cos(n\\omega\n", - "t)=(1/2)(\\cos[(m+n)\\omega t]+\\cos[(m-n)\\omega t]$. This will integrate\n", - "to zero unless $m=n$. In that case the $m=n$ term gives" - ] - }, - { - "cell_type": "markdown", - "id": "a6736340", - "metadata": {}, - "source": [ - "\n", - "
\n", - "\n", - "$$\n", - "\\begin{equation}\n", - "\\int_{-\\tau/2}^{\\tau/2}dt~\\cos^2(m\\omega t)=\\frac{\\tau}{2},\n", - "\\label{_auto3} \\tag{5}\n", - "\\end{equation}\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "f7fc5c92", - "metadata": {}, - "source": [ - "and" - ] - }, - { - "cell_type": "markdown", - "id": "145eb0ed", - "metadata": {}, - "source": [ - "$$\n", - "f_n=\\frac{2}{\\tau}\\int_{-\\tau/2}^{\\tau/2} dt~f_n/2=f_n.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "c55a6961", - "metadata": {}, - "source": [ - "The same method can be used to check for the consistency of $g_n$." - ] - }, - { - "cell_type": "markdown", - "id": "efe26d49", - "metadata": {}, - "source": [ - "## Final words on Fourier Transforms\n", - "\n", - "The code here uses the Fourier series applied to a \n", - "square wave signal. The code here\n", - "visualizes the various approximations given by Fourier series compared\n", - "with a square wave with period $T=0.2$ (dimensionless time), width $0.1$ and max value of the force $F=2$. We\n", - "see that when we increase the number of components in the Fourier\n", - "series, the Fourier series approximation gets closer and closer to the\n", - "square wave signal." - ] - }, - { - "cell_type": "code", - "execution_count": 2, - "id": "2d7c13f1", - "metadata": {}, - "outputs": [], - "source": [ - "import numpy as np\n", - "import math\n", - "from scipy import signal\n", - "import matplotlib.pyplot as plt\n", - "\n", - "# number of points \n", - "n = 500\n", - "# start and final times \n", - "t0 = 0.0\n", - "tn = 1.0\n", - "# Period \n", - "T =0.2\n", - "# Max value of square signal \n", - "Fmax= 2.0\n", - "# Width of signal \n", - "Width = 0.1\n", - "t = np.linspace(t0, tn, n, endpoint=False)\n", - "SqrSignal = np.zeros(n)\n", - "FourierSeriesSignal = np.zeros(n)\n", - "SqrSignal = 1.0+signal.square(2*np.pi*5*t+np.pi*Width/T)\n", - "a0 = Fmax*Width/T\n", - "FourierSeriesSignal = a0\n", - "Factor = 2.0*Fmax/np.pi\n", - "for i in range(1,500):\n", - " FourierSeriesSignal += Factor/(i)*np.sin(np.pi*i*Width/T)*np.cos(i*t*2*np.pi/T)\n", - "plt.plot(t, SqrSignal)\n", - "plt.plot(t, FourierSeriesSignal)\n", - "plt.ylim(-0.5, 2.5)\n", - "plt.show()" - ] - }, - { - "cell_type": "markdown", - "id": "7eb888fa", - "metadata": {}, - "source": [ - "### Fourier transforms and convolution\n", - "\n", - "We can use Fourier transforms in our studies of convolution as well. To see this, assume we have two functions $f$ and $g$ and their corresponding Fourier transforms $\\hat{f}$ and $\\hat{g}$. We remind the reader that the Fourier transform reads (say for the function $f$)" - ] - }, - { - "cell_type": "markdown", - "id": "ea8a36c0", - "metadata": {}, - "source": [ - "$$\n", - "\\hat{f}(y)=\\boldsymbol{F}[f(y)]=\\frac{1}{2\\pi}\\int_{-\\infty}^{\\infty} d\\omega \\exp{-i\\omega y} f(\\omega),\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "13ec89cc", - "metadata": {}, - "source": [ - "and similarly we have" - ] - }, - { - "cell_type": "markdown", - "id": "ec321c01", - "metadata": {}, - "source": [ - "$$\n", - "\\hat{g}(y)=\\boldsymbol{F}[g(y)]=\\frac{1}{2\\pi}\\int_{-\\infty}^{\\infty} d\\omega \\exp{-i\\omega y} g(\\omega).\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "fb441853", - "metadata": {}, - "source": [ - "The inverse Fourier transform is given by" - ] - }, - { - "cell_type": "markdown", - "id": "0e6c8c97", - "metadata": {}, - "source": [ - "$$\n", - "\\boldsymbol{F}^{-1}[g(y)]=\\frac{1}{2\\pi}\\int_{-\\infty}^{\\infty} d\\omega \\exp{i\\omega y} g(\\omega).\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "926ad151", - "metadata": {}, - "source": [ - "The inverse Fourier transform of the product of the two functions $\\hat{f}\\hat{g}$ can be written as" - ] - }, - { - "cell_type": "markdown", - "id": "6b94454c", - "metadata": {}, - "source": [ - "$$\n", - "\\boldsymbol{F}^{-1}[(\\hat{f}\\hat{g})(x)]=\\frac{1}{2\\pi}\\int_{-\\infty}^{\\infty} d\\omega \\exp{i\\omega x} \\hat{f}(\\omega)\\hat{g}(\\omega).\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "30482910", - "metadata": {}, - "source": [ - "We can rewrite the latter as" - ] - }, - { - "cell_type": "markdown", - "id": "de702fa7", - "metadata": {}, - "source": [ - "$$\n", - "\\boldsymbol{F}^{-1}[(\\hat{f}\\hat{g})(x)]=\\int_{-\\infty}^{\\infty} d\\omega \\exp{i\\omega x} \\hat{f}(\\omega)\\left[\\frac{1}{2\\pi}\\int_{-\\infty}^{\\infty}g(y)dy \\exp{-i\\omega y}\\right]=\\frac{1}{2\\pi}\\int_{-\\infty}^{\\infty}dy g(y)\\int_{-\\infty}^{\\infty} d\\omega \\hat{f}(\\omega) \\exp{i\\omega(x- y)},\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "8dc14e03", - "metadata": {}, - "source": [ - "which is simply" - ] - }, - { - "cell_type": "markdown", - "id": "58880666", - "metadata": {}, - "source": [ - "$$\n", - "\\boldsymbol{F}^{-1}[(\\hat{f}\\hat{g})(x)]=\\int_{-\\infty}^{\\infty}dy g(y)f(x-y)=(f*g)(x),\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "8d5d93c6", - "metadata": {}, - "source": [ - "the convolution of the functions $f$ and $g$." - ] - }, - { - "cell_type": "markdown", - "id": "b1b68406", - "metadata": {}, - "source": [ - "## Two-dimensional Objects\n", - "\n", - "We are now ready to start studying the discrete convolutions relevant for convolutional neural networks.\n", - "We often use convolutions over more than one dimension at a time. If\n", - "we have a two-dimensional image $I$ as input, we can have a **filter**\n", - "defined by a two-dimensional **kernel** $K$. This leads to an output $S$" - ] - }, - { - "cell_type": "markdown", - "id": "f095e15f", - "metadata": {}, - "source": [ - "$$\n", - "S_(i,j)=(I * K)(i,j) = \\sum_m\\sum_n I(m,n)K(i-m,j-n).\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "6d6c489a", - "metadata": {}, - "source": [ - "Convolution is a commutatitave process, which means we can rewrite this equation as" - ] - }, - { - "cell_type": "markdown", - "id": "76c943b7", - "metadata": {}, - "source": [ - "$$\n", - "S_(i,j)=(I * K)(i,j) = \\sum_m\\sum_n I(i-m,j-n)K(m,n).\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "8f38d5d5", - "metadata": {}, - "source": [ - "Normally the latter is more straightforward to implement in a machine larning library since there is less variation in the range of values of $m$ and $n$.\n", - "\n", - "Many deep learning libraries implement cross-correlation instead of convolution (although it is referred to s convolution)" - ] - }, - { - "cell_type": "markdown", - "id": "832c1e07", - "metadata": {}, - "source": [ - "$$\n", - "S_(i,j)=(I * K)(i,j) = \\sum_m\\sum_n I(i+m,j+n)K(m,n).\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "83a03b60", - "metadata": {}, - "source": [ - "## More on Dimensionalities\n", - "\n", - "In fields like signal processing (and imaging as well), one designs\n", - "so-called filters. These filters are defined by the convolutions and\n", - "are often hand-crafted. One may specify filters for smoothing, edge\n", - "detection, frequency reshaping, and similar operations. However with\n", - "neural networks the idea is to automatically learn the filters and use\n", - "many of them in conjunction with non-linear operations (activation\n", - "functions).\n", - "\n", - "As an example consider a neural network operating on sound sequence\n", - "data. Assume that we an input vector $\\boldsymbol{x}$ of length $d=10^6$. We\n", - "construct then a neural network with onle hidden layer only with\n", - "$10^4$ nodes. This means that we will have a weight matrix with\n", - "$10^4\\times 10^6=10^{10}$ weights to be determined, together with $10^4$ biases.\n", - "\n", - "Assume furthermore that we have an output layer which is meant to train whether the sound sequence represents a human voice (true) or something else (false).\n", - "It means that we have only one output node. But since this output node connects to $10^4$ nodes in the hidden layer, there are in total $10^4$ weights to be determined for the output layer, plus one bias. In total we have" - ] - }, - { - "cell_type": "markdown", - "id": "c495dae2", - "metadata": {}, - "source": [ - "$$\n", - "\\mathrm{NumberParameters}=10^{10}+10^4+10^4+1 \\approx 10^{10},\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "13f7e07c", - "metadata": {}, - "source": [ - "that is ten billion parameters to determine." - ] - }, - { - "cell_type": "markdown", - "id": "19ebaf8a", - "metadata": {}, - "source": [ - "## Further Dimensionality Remarks\n", - "\n", - "In today’s architecture one can train such neural networks, however\n", - "this is a huge number of parameters for the task at hand. In general,\n", - "it is a very wasteful and inefficient use of dense matrices as\n", - "parameters. Just as importantly, such trained network parameters are\n", - "very specific for the type of input data on which they were trained\n", - "and the network is not likely to generalize easily to variations in\n", - "the input.\n", - "\n", - "The main principles that justify convolutions is locality of\n", - "information and repetion of patterns within the signal. Sound samples\n", - "of the input in adjacent spots are much more likely to affect each\n", - "other than those that are very far away. Similarly, sounds are\n", - "repeated in multiple times in the signal. While slightly simplistic,\n", - "reasoning about such a sound example demonstrates this. The same\n", - "principles then apply to images and other similar data." - ] - }, - { - "cell_type": "markdown", - "id": "598b540b", - "metadata": {}, - "source": [ - "## CNNs in more detail\n", - "\n", - "Let assume we have an input matrix $I$ of dimensionality $3\\times 3$\n", - "and a $2\\times 2$ filter $W$ given by the following matrices" - ] - }, - { - "cell_type": "markdown", - "id": "511322b6", - "metadata": {}, - "source": [ - "$$\n", - "\\boldsymbol{I}=\\begin{bmatrix}i_{00} & i_{01} & i_{02} \\\\\n", - " i_{10} & i_{11} & i_{12} \\\\\n", - "\t i_{20} & i_{21} & i_{22} \\end{bmatrix},\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "1c45deca", - "metadata": {}, - "source": [ - "and" - ] - }, - { - "cell_type": "markdown", - "id": "9c41eaff", - "metadata": {}, - "source": [ - "$$\n", - "\\boldsymbol{W}=\\begin{bmatrix}w_{00} & w_{01} \\\\\n", - "\t w_{10} & w_{11}\\end{bmatrix}.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "64f84453", - "metadata": {}, - "source": [ - "We introduce now the hyperparameter $S$ **stride**. Stride represents how the filter $W$ moves the convolution process on the matrix $I$.\n", - "We strongly recommend the repository on [Arithmetic of deep learning by Dumoulin and Visin](https://github.com/vdumoulin/conv_arithmetic) \n", - "\n", - "Here we set the stride equal to $S=1$, which means that, starting with the element $i_{00}$, the filter will act on $2\\times 2$ submatrices each time, starting with the upper corner and moving according to the stride value column by column. \n", - "\n", - "Here we perform the operation" - ] - }, - { - "cell_type": "markdown", - "id": "e2cb4b08", - "metadata": {}, - "source": [ - "$$\n", - "S_(i,j)=(I * W)(i,j) = \\sum_m\\sum_n I(i-m,j-n)W(m,n),\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "37d20741", - "metadata": {}, - "source": [ - "and obtain" - ] - }, - { - "cell_type": "markdown", - "id": "e864de9c", - "metadata": {}, - "source": [ - "$$\n", - "\\boldsymbol{S}=\\begin{bmatrix}i_{00}w_{00}+i_{01}w_{01}+i_{10}w_{10}+i_{11}w_{11} & i_{01}w_{00}+i_{02}w_{01}+i_{11}w_{10}+i_{12}w_{11} \\\\\n", - "\t i_{10}w_{00}+i_{11}w_{01}+i_{20}w_{10}+i_{21}w_{11} & i_{11}w_{00}+i_{12}w_{01}+i_{21}w_{10}+i_{22}w_{11}\\end{bmatrix}.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "7b6c2fcd", - "metadata": {}, - "source": [ - "We can rewrite this operation in terms of a matrix-vector multiplication by defining a new vector where we flatten out the inputs as a vector $\\boldsymbol{I}'$ of length $9$ and\n", - "a matrix $\\boldsymbol{W}'$ with dimension $4\\times 9$ as" - ] - }, - { - "cell_type": "markdown", - "id": "2ad6a202", - "metadata": {}, - "source": [ - "$$\n", - "\\boldsymbol{I}'=\\begin{bmatrix}i_{00} \\\\ i_{01} \\\\ i_{02} \\\\ i_{10} \\\\ i_{11} \\\\ i_{12} \\\\ i_{20} \\\\ i_{21} \\\\ i_{22} \\end{bmatrix},\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "0d239cf4", - "metadata": {}, - "source": [ - "and the new matrix" - ] - }, - { - "cell_type": "markdown", - "id": "f653b7fe", - "metadata": {}, - "source": [ - "$$\n", - "\\boldsymbol{W}'=\\begin{bmatrix} w_{00} & w_{01} & 0 & w_{10} & w_{11} & 0 & 0 & 0 & 0 \\\\\n", - " 0 & w_{00} & w_{01} & 0 & w_{10} & w_{11} & 0 & 0 & 0 \\\\\n", - "\t\t\t0 & 0 & 0 & w_{00} & w_{01} & 0 & w_{10} & w_{11} & 0 \\\\\n", - " 0 & 0 & 0 & 0 & w_{00} & w_{01} & 0 & w_{10} & w_{11}\\end{bmatrix}.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "f06adedd", - "metadata": {}, - "source": [ - "We see easily that performing the matrix-vector multiplication $\\boldsymbol{W}'\\boldsymbol{I}'$ is the same as the above convolution with stride $S=1$, that is" - ] - }, - { - "cell_type": "markdown", - "id": "9313111f", - "metadata": {}, - "source": [ - "$$\n", - "S=(\\boldsymbol{W}*\\boldsymbol{I}),\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "36340b3c", - "metadata": {}, - "source": [ - "is now given by $\\boldsymbol{W}'\\boldsymbol{I}'$ which is a vector of length $4$ instead of the originally resulting $2\\times 2$ output matrix.\n", - "\n", - "The collection of kernels/filters $W$ defining a discrete convolution has a shape\n", - "corresponding to some permutation of $(n, m, k_1, \\ldots, k_N)$, where" - ] - }, - { - "cell_type": "markdown", - "id": "7720c270", - "metadata": {}, - "source": [ - "$$\n", - "\\begin{split}\n", - " n &\\equiv \\text{number of output feature maps},\\\\\n", - " m &\\equiv \\text{number of input feature maps},\\\\\n", - " k_j &\\equiv \\text{kernel size along axis $j$}.\n", - "\\end{split}\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "7b10925c", - "metadata": {}, - "source": [ - "The following properties affect the output size $o_j$ of a convolutional layer\n", - "along axis $j$:\n", - "\n", - "1. $i_j$: input size along axis $j$,\n", - "\n", - "2. $k_j$: kernel/filter size along axis $j$,\n", - "\n", - "3. stride (distance between two consecutive positions of the kernel/filter) along axis $j$,\n", - "\n", - "4. zero padding (number of zeros concatenated at the beginning and at the end of an axis) along axis $j$.\n", - "\n", - "For instance, the above examples shows a $2\\times 2$ kernel/filter $\\boldsymbol{W}$ applied to a $3 \\times 3$ input padded with a $0 \\times 0$\n", - "border of zeros using $1 \\times 1$ strides.\n", - "\n", - "Note that strides constitute a form of **subsampling**. As an alternative to\n", - "being interpreted as a measure of how much the kernel/filter is translated, strides\n", - "can also be viewed as how much of the output is retained. For instance, moving\n", - "the kernel by hops of two is equivalent to moving the kernel by hops of one but\n", - "retaining only odd output elements." - ] - }, - { - "cell_type": "markdown", - "id": "ec92fea8", - "metadata": {}, - "source": [ - "## Pooling\n", - "\n", - "In addition to discrete convolutions themselves, {\\em pooling\\/} operations\n", - "make up another important building block in CNNs. Pooling operations reduce\n", - "the size of feature maps by using some function to summarize subregions, such\n", - "as taking the average or the maximum value.\n", - "\n", - "Pooling works by sliding a window across the input and feeding the content of\n", - "the window to a {\\em pooling function}. In some sense, pooling works very much\n", - "like a discrete convolution, but replaces the linear combination described by\n", - "the kernel with some other function. Poolin\n", - "provides an example for average pooling, and \n", - "does the same for max pooling.\n", - "\n", - "The following properties affect the output size $o_j$ of a pooling layer\n", - "along axis $j$:\n", - "\n", - "1. $i_j$: input size along axis $j$,\n", - "\n", - "2. $k_j$: pooling window size along axis $j$,\n", - "\n", - "3. $s_j$: stride (distance between two consecutive positions of the pooling window) along axis $j$.\n", - "\n", - "The analysis of the relationship between convolutional layer properties is eased\n", - "by the fact that they don't interact across axes, i.e., the choice of kernel\n", - "size, stride and zero padding along axis $j$ only affects the output size of\n", - "axis $j$. Because of that, we will focus on the following simplified\n", - "setting:\n", - "\n", - "1. 2-D discrete convolutions ($N = 2$),\n", - "\n", - "2. square inputs ($i_1 = i_2 = i$),\n", - "\n", - "3. square kernel size ($k_1 = k_2 = k$),\n", - "\n", - "4. same strides along both axes ($s_1 = s_2 = s$),\n", - "\n", - "5. same zero padding along both axes ($p_1 = p_2 = p$).\n", - "\n", - "This facilitates the analysis and the visualization, but keep in mind that the\n", - "results outlined here also generalize to the N-D and non-square cases." - ] - }, - { - "cell_type": "markdown", - "id": "08aa5e12", - "metadata": {}, - "source": [ - "## No zero padding, unit strides\n", - "\n", - "The simplest case to analyze is when the kernel just slides across every\n", - "position of the input (i.e., $s = 1$ and $p = 0$).\n", - "\n", - "For any $i$ and $k$, and for $s = 1$ and $p = 0$," - ] - }, - { - "cell_type": "markdown", - "id": "18e6266b", - "metadata": {}, - "source": [ - "$$\n", - "o = (i - k) + 1.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "588b8363", - "metadata": {}, - "source": [ - "## Zero padding, unit strides\n", - "\n", - "To factor in zero padding (i.e., only restricting to $s = 1$), let's consider\n", - "its effect on the effective input size: padding with $p$ zeros changes the\n", - "effective input size from $i$ to $i + 2p$. In the general case, we can infer the following\n", - "relationship\n", - "\n", - "For any $i$, $k$ and $p$, and for $s = 1$," - ] - }, - { - "cell_type": "markdown", - "id": "8f0af9ec", - "metadata": {}, - "source": [ - "$$\n", - "o = (i - k) + 2p + 1.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "700387e0", - "metadata": {}, - "source": [ - "## Half (same) padding\n", - "\n", - "Having the output size be the same as the input size (i.e., $o = i$) can be a\n", - "desirable property:\n", - "\n", - "For any $i$ and for $k$ odd ($k = 2n + 1, \\quad n \\in \\mathbb{N}$), $s = 1$ and\n", - "$p = \\lfloor k / 2 \\rfloor = n$," - ] - }, - { - "cell_type": "markdown", - "id": "c81ee97e", - "metadata": {}, - "source": [ - "$$\n", - "\\begin{split}\n", - " o &= i + 2 \\lfloor k / 2 \\rfloor - (k - 1) \\\\\n", - " &= i + 2n - 2n \\\\\n", - " &= i.\n", - "\\end{split}\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "789a08f8", - "metadata": {}, - "source": [ - "## Full padding\n", - "\n", - "While convolving a kernel generally decreases the output size with\n", - "respect to the input size, sometimes the opposite is required. This can be\n", - "achieved with proper zero padding:\n", - "\n", - "For any $i$ and $k$, and for $p = k - 1$ and $s = 1$," - ] - }, - { - "cell_type": "markdown", - "id": "f6ed2c6b", - "metadata": {}, - "source": [ - "$$\n", - "\\begin{split}\n", - " o &= i + 2(k - 1) - (k - 1) \\\\\n", - " &= i + (k - 1).\n", - "\\end{split}\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "56b14905", - "metadata": {}, - "source": [ - "This is sometimes referred to as full padding, because in this\n", - "setting every possible partial or complete superimposition of the kernel on the\n", - "input feature map is taken into account." - ] - }, - { - "cell_type": "markdown", - "id": "e9efdbb2", - "metadata": {}, - "source": [ - "## Pooling arithmetic\n", - "\n", - "In a neural network, pooling layers provide invariance to small translations of\n", - "the input. The most common kind of pooling is **max pooling**, which\n", - "consists in splitting the input in (usually non-overlapping) patches and\n", - "outputting the maximum value of each patch. Other kinds of pooling exist, e.g.,\n", - "mean or average pooling, which all share the same idea of aggregating the input\n", - "locally by applying a non-linearity to the content of some patches.\n", - "\n", - "Since pooling does not involve\n", - "zero padding, the relationship describing the general case is as follows:\n", - "\n", - "For any $i$, $k$ and $s$," - ] - }, - { - "cell_type": "markdown", - "id": "26d22ac6", - "metadata": {}, - "source": [ - "$$\n", - "o = \\left\\lfloor \\frac{i - k}{s} \\right\\rfloor + 1.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "931da696", - "metadata": {}, - "source": [ - "## CNNs in more detail, building convolutional neural networks in Tensorflow and Keras\n", - "\n", - "As discussed above, CNNs are neural networks built from the assumption that the inputs\n", - "to the network are 2D images. This is important because the number of features or pixels in images\n", - "grows very fast with the image size, and an enormous number of weights and biases are needed in order to build an accurate network. \n", - "\n", - "As before, we still have our input, a hidden layer and an output. What's novel about convolutional networks\n", - "are the **convolutional** and **pooling** layers stacked in pairs between the input and the hidden layer.\n", - "In addition, the data is no longer represented as a 2D feature matrix, instead each input is a number of 2D\n", - "matrices, typically 1 for each color dimension (Red, Green, Blue)." - ] - }, - { - "cell_type": "markdown", - "id": "d217547f", - "metadata": {}, - "source": [ - "## Setting it up\n", - "\n", - "It means that to represent the entire\n", - "dataset of images, we require a 4D matrix or **tensor**. This tensor has the dimensions:" - ] - }, - { - "cell_type": "markdown", - "id": "27ecc7de", - "metadata": {}, - "source": [ - "$$\n", - "(n_{inputs},\\, n_{pixels, width},\\, n_{pixels, height},\\, depth) .\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "8b06f6ba", - "metadata": {}, - "source": [ - "## The MNIST dataset again\n", - "\n", - "The MNIST dataset consists of grayscale images with a pixel size of\n", - "$28\\times 28$, meaning we require $28 \\times 28 = 724$ weights to each\n", - "neuron in the first hidden layer.\n", - "\n", - "If we were to analyze images of size $128\\times 128$ we would require\n", - "$128 \\times 128 = 16384$ weights to each neuron. Even worse if we were\n", - "dealing with color images, as most images are, we have an image matrix\n", - "of size $128\\times 128$ for each color dimension (Red, Green, Blue),\n", - "meaning 3 times the number of weights $= 49152$ are required for every\n", - "single neuron in the first hidden layer." - ] - }, - { - "cell_type": "markdown", - "id": "ad0a0a50", - "metadata": {}, - "source": [ - "## Strong correlations\n", - "\n", - "Images typically have strong local correlations, meaning that a small\n", - "part of the image varies little from its neighboring regions. If for\n", - "example we have an image of a blue car, we can roughly assume that a\n", - "small blue part of the image is surrounded by other blue regions.\n", - "\n", - "Therefore, instead of connecting every single pixel to a neuron in the\n", - "first hidden layer, as we have previously done with deep neural\n", - "networks, we can instead connect each neuron to a small part of the\n", - "image (in all 3 RGB depth dimensions). The size of each small area is\n", - "fixed, and known as a [receptive](https://en.wikipedia.org/wiki/Receptive_field)." - ] - }, - { - "cell_type": "markdown", - "id": "8583f2c0", - "metadata": {}, - "source": [ - "## Layers of a CNN\n", - "The layers of a convolutional neural network arrange neurons in 3D: width, height and depth. \n", - "The input image is typically a square matrix of depth 3. \n", - "\n", - "A **convolution** is performed on the image which outputs\n", - "a 3D volume of neurons. The weights to the input are arranged in a number of 2D matrices, known as **filters**.\n", - "\n", - "Each filter slides along the input image, taking the dot product\n", - "between each small part of the image and the filter, in all depth\n", - "dimensions. This is then passed through a non-linear function,\n", - "typically the **Rectified Linear (ReLu)** function, which serves as the\n", - "activation of the neurons in the first convolutional layer. This is\n", - "further passed through a **pooling layer**, which reduces the size of the\n", - "convolutional layer, e.g. by taking the maximum or average across some\n", - "small regions, and this serves as input to the next convolutional\n", - "layer." - ] - }, - { - "cell_type": "markdown", - "id": "86e0bc8c", - "metadata": {}, - "source": [ - "## Systematic reduction\n", - "\n", - "By systematically reducing the size of the input volume, through\n", - "convolution and pooling, the network should create representations of\n", - "small parts of the input, and then from them assemble representations\n", - "of larger areas. The final pooling layer is flattened to serve as\n", - "input to a hidden layer, such that each neuron in the final pooling\n", - "layer is connected to every single neuron in the hidden layer. This\n", - "then serves as input to the output layer, e.g. a softmax output for\n", - "classification." - ] - }, - { - "cell_type": "markdown", - "id": "445a29e1", - "metadata": {}, - "source": [ - "## Prerequisites: Collect and pre-process data" - ] - }, - { - "cell_type": "code", - "execution_count": 1, - "id": "79884b14", - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "inputs = (n_inputs, pixel_width, pixel_height, depth) = (1797, 8, 8, 1)\n", - "labels = (n_inputs) = (1797,)\n" - ] - }, - { - "data": { - "image/png": "iVBORw0KGgoAAAANSUhEUgAAA7YAAADICAYAAADcOn20AAAAOXRFWHRTb2Z0d2FyZQBNYXRwbG90bGliIHZlcnNpb24zLjUuMSwgaHR0cHM6Ly9tYXRwbG90bGliLm9yZy/YYfK9AAAACXBIWXMAAA9hAAAPYQGoP6dpAAAQx0lEQVR4nO3dbWydZRkH8OuMjklYaEHMxla3ji46/KBdiItodB2oEUVXDNMYois6QgLCkKkhEGwHGDCaWIxODY510SUuJmSdZr4AdjUmxPBWEhaNjlBEzSYOOl+SbQwfPxhqN9Y68G7rdc7vl/QDZz3/c5+T6z7P899zOKtVVVUFAAAAJDVrphcAAAAA/wvFFgAAgNQUWwAAAFJTbAEAAEhNsQUAACA1xRYAAIDUFFsAAABSU2wBAABITbEFAAAgtYYptv39/VGr1eLhhx8ukler1eLTn/50kazxmb29va/6/nv37o2Pf/zjsWjRojjttNOivb09brjhhjhw4EC5RZJSvc9/b29v1Gq1CX++//3vF10r+dgD9kAjq/f5f+aZZ+LSSy+Nc889N04//fRobm6O5cuXx9e//vU4evRo0XWSj/lvHE0zvQDKePbZZ+Ntb3tbnHHGGXHbbbfFokWL4rHHHouenp4YHByMRx55JGbNapi/x6DBrFu3Lt73vve97PYrr7wynnzyyRP+GdQTe4BG9o9//CPOOOOMuOWWW2LRokVx5MiR2LVrV1x77bUxPDwc3/nOd2Z6iTBlzP9/KLZ1YmBgIA4cOBDbt2+Piy66KCIiVq1aFYcPH46bbropHn/88Vi+fPkMrxKmRmtra7S2th5z28jISOzZsycuv/zyaGlpmZmFwTSxB2hky5Yti61btx5z28UXXxx//vOfY+vWrfGNb3wj5syZM0Org6ll/v/DJbxxDh06FBs2bIiOjo5obm6Os846Ky644IIYGBiY8D7f/va34w1veEPMmTMn3vSmN53w41779u2Lq666KlpbW+PUU0+NJUuWxMaNG4t+PGD27NkREdHc3HzM7S+dzLzmNa8p9ljUp8zzfyL33HNPVFUV69atm9LHoX7YAzSyepv/iIjXve51MWvWrDjllFOm/LHIzfzXB1dsxzl8+HA899xz8dnPfjYWLlwYR44cifvvvz8+/OEPx5YtW+ITn/jEMb+/c+fOGBwcjFtvvTVOP/302LRpU3zsYx+LpqamuOyyyyLi3wO9YsWKmDVrVnzhC1+I9vb2ePDBB+P222+PkZGR2LJly6Rramtri4h//837ZLq6umLRokWxYcOG2LRpUyxevDgeffTRuPPOO+ODH/xgnHfeea/6daExZJ7/4/3zn/+M/v7+WLp0aaxcufIV3ZfGZQ/QyOph/quqihdffDH+9re/xc9+9rPo7++PDRs2RFOT010mZ/7rRNUgtmzZUkVE9dBDD530fY4ePVq98MIL1ac+9alq+fLlx/xZRFSnnXZatW/fvmN+f9myZdXSpUvHbrvqqququXPnVk8//fQx9//KV75SRUS1Z8+eYzJ7enqO+b329vaqvb39pNb7pz/9qbrggguqiBj7WbNmTXXo0KGTfcrUqUaY//F+/OMfVxFR3XHHHa/4vtQne4BG1ijzf8cdd4yd/9Rqtermm28+6ftSv8x/4/BR5OP84Ac/iHe84x0xd+7caGpqitmzZ8fmzZvj17/+9ct+96KLLop58+aN/fcpp5wSH/3oR2Pv3r3xhz/8ISIifvSjH8WqVatiwYIFcfTo0bGfiy++OCIihoaGJl3P3r17Y+/evf913c8//3ysXr06/vrXv8a2bdviF7/4RWzatCl++ctfxoc+9KGG+1Y0Xp2s83+8zZs3R1NTU3R3d7/i+9LY7AEaWfb57+7ujoceeih++tOfxuc///n48pe/HNdee+1J35/GZv7za6Br0//dvffeGx/5yEdizZo18bnPfS7mz58fTU1N8c1vfjPuueeel/3+/PnzJ7ztwIED0draGvv3748f/vCHY/8P7PH+8pe/FFn7l770pRgeHo6nn346zjnnnIiIeOc73xnLli2LCy+8MLZt2xZr164t8ljUp8zzf3zmzp074wMf+MAJ1wgTsQdoZPUw//Pnzx9bw3vf+94488wz48Ybb4xPfvKTvkCTSZn/+qDYjvO9730vlixZEtu3b49arTZ2++HDh0/4+/v27Zvwtte+9rUREXH22WfHm9/85vjiF794wowFCxb8r8uOiIjh4eFYuHDhWKl9yVvf+taIiHjiiSeKPA71K/P8j/fd7343jhw54gtzeMXsARpZvcz/eCtWrIiIiN/+9rcNc2LPq2P+64NiO06tVotTTz31mIHet2/fhN+I9sADD8T+/fvHPorw4osvxvbt26O9vX3sn1245JJLYteuXdHe3h5nnnnmlK19wYIF8cADD8Qf//jHWLhw4djtDz74YETEy/4ZCDhe5vkfb/PmzbFgwYKxj/rAybIHaGT1Mv/jDQ4ORkTE0qVLp/2xycX814eGK7Y///nPT/jtYu9///vjkksuiXvvvTeuvvrquOyyy+KZZ56J2267Lc4555z43e9+97L7nH322XHhhRfGLbfcMvaNaL/5zW+O+brvW2+9Ne677754+9vfHtddd1288Y1vjEOHDsXIyEjs2rUrvvWtb01aOl8axv/2Gftrrrkmtm3bFu95z3vixhtvjNe//vXxxBNPxO233x7z5s2Lyy+//CRfIepZvc7/S371q1/Fnj174qabbmqor7fn5NkDNLJ6nf+enp7Yv39/vOtd74qFCxfG6Oho/OQnP4m777471qxZE+eff/5JvkLUM/PfAGb626umy0vfiDbRz1NPPVVVVVXdeeedVVtbWzVnzpzqvPPOq+6+++6qp6enOv6liojqmmuuqTZt2lS1t7dXs2fPrpYtW1Zt27btZY/97LPPVtddd121ZMmSavbs2dVZZ51VnX/++dXNN99c/f3vfz8m8/hvRFu8eHG1ePHik3qOjz76aHXppZdWra2t1Zw5c6pzzz23WrduXfX73//+Fb1W1J9GmP+qqqorr7yyqtVq1ZNPPnnS96Ex2AM0snqf/507d1bvfve7q3nz5lVNTU3V3LlzqxUrVlRf+9rXqhdeeOEVv17UF/PfOGpVVVWlyzIAAABMF//cDwAAAKkptgAAAKSm2AIAAJCaYgsAAEBqii0AAACpKbYAAACkptgCAACQWtNML6CU/v7+onm9vb1F81paWormRUT09fUVzevs7Cyax/TZvXt30bzS+2nHjh1F8yIiDh48WDRvcHCwaJ79NL0GBgaK5q1fv75o3lQove/b2tqK5jG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lqK5jF9nn/++aJ5Bw8eLJrX3d1dNA+m2lve8paieaXfr2G8r371q0XzhoaGiuY1NzcXzYsof1xxnJpeK1euLJrX2dlZNK/0nhodHS2aFxGxfv36onn10ANcsQUAACA1xRYAAIDUFFsAAABSU2wBAABITbEFAAAgNcUWAACA1BRbAAAAUlNsAQAASE2xBQAAIDXFFgAAgNQUWwAAAFJTbAEAAEhNsQUAACA1xRYAAIDUFFsAAABSU2wBAABITbEFAAAgNcUWAACA1BRbAAAAUqtVVVXN9CIAAADg1XLFFgAAgNQUWwAAAFJTbAEAAEhNsQUAACA1xRYAAIDUFFsAAABSU2wBAABITbEFAAAgNcUWAACA1P4F8SqxxH5w1EMAAAAASUVORK5CYII=\n", - "text/plain": [ - "
" - ] - }, - "metadata": {}, - "output_type": "display_data" - } - ], - "source": [ - "# import necessary packages\n", - "import numpy as np\n", - "import matplotlib.pyplot as plt\n", - "from sklearn import datasets\n", - "\n", - "\n", - "# ensure the same random numbers appear every time\n", - "np.random.seed(0)\n", - "\n", - "# display images in notebook\n", - "%matplotlib inline\n", - "plt.rcParams['figure.figsize'] = (12,12)\n", - "\n", - "\n", - "# download MNIST dataset\n", - "digits = datasets.load_digits()\n", - "\n", - "# define inputs and labels\n", - "inputs = digits.images\n", - "labels = digits.target\n", - "\n", - "# RGB images have a depth of 3\n", - "# our images are grayscale so they should have a depth of 1\n", - "inputs = inputs[:,:,:,np.newaxis]\n", - "\n", - "print(\"inputs = (n_inputs, pixel_width, pixel_height, depth) = \" + str(inputs.shape))\n", - "print(\"labels = (n_inputs) = \" + str(labels.shape))\n", - "\n", - "\n", - "# choose some random images to display\n", - "n_inputs = len(inputs)\n", - "indices = np.arange(n_inputs)\n", - "random_indices = np.random.choice(indices, size=5)\n", - "\n", - "for i, image in enumerate(digits.images[random_indices]):\n", - " plt.subplot(1, 5, i+1)\n", - " plt.axis('off')\n", - " plt.imshow(image, cmap=plt.cm.gray_r, interpolation='nearest')\n", - " plt.title(\"Label: %d\" % digits.target[random_indices[i]])\n", - "plt.show()" - ] - }, - { - "cell_type": "markdown", - "id": "6fafadc0", - "metadata": {}, - "source": [ - "## Importing Keras and Tensorflow" - ] - }, - { - "cell_type": "code", - "execution_count": 2, - "id": "d10aa7b4", - "metadata": {}, - "outputs": [], - "source": [ - "from tensorflow.keras import datasets, layers, models\n", - "from tensorflow.keras.layers import Input\n", - "from tensorflow.keras.models import Sequential #This allows appending layers to existing models\n", - "from tensorflow.keras.layers import Dense #This allows defining the characteristics of a particular layer\n", - "from tensorflow.keras import optimizers #This allows using whichever optimiser we want (sgd,adam,RMSprop)\n", - "from tensorflow.keras import regularizers #This allows using whichever regularizer we want (l1,l2,l1_l2)\n", - "from tensorflow.keras.utils import to_categorical #This allows using categorical cross entropy as the cost function\n", - "#from tensorflow.keras import Conv2D\n", - "#from tensorflow.keras import MaxPooling2D\n", - "#from tensorflow.keras import Flatten\n", - "\n", - "from sklearn.model_selection import train_test_split\n", - "\n", - "# representation of labels\n", - "labels = to_categorical(labels)\n", - "\n", - "# split into train and test data\n", - "# one-liner from scikit-learn library\n", - "train_size = 0.8\n", - "test_size = 1 - train_size\n", - "X_train, X_test, Y_train, Y_test = train_test_split(inputs, labels, train_size=train_size,\n", - " test_size=test_size)" - ] - }, - { - "cell_type": "markdown", - "id": "4542534a", - "metadata": {}, - "source": [ - "## Running with Keras" - ] - }, - { - "cell_type": "code", - "execution_count": 3, - "id": "95dcc4fc", - "metadata": {}, - "outputs": [], - "source": [ - "def create_convolutional_neural_network_keras(input_shape, receptive_field,\n", - " n_filters, n_neurons_connected, n_categories,\n", - " eta, lmbd):\n", - " model = Sequential()\n", - " model.add(layers.Conv2D(n_filters, (receptive_field, receptive_field), input_shape=input_shape, padding='same',\n", - " activation='relu', kernel_regularizer=regularizers.l2(lmbd)))\n", - " model.add(layers.MaxPooling2D(pool_size=(2, 2)))\n", - " model.add(layers.Flatten())\n", - " model.add(layers.Dense(n_neurons_connected, activation='relu', kernel_regularizer=regularizers.l2(lmbd)))\n", - " model.add(layers.Dense(n_categories, activation='softmax', kernel_regularizer=regularizers.l2(lmbd)))\n", - " \n", - " sgd = optimizers.SGD(lr=eta)\n", - " model.compile(loss='categorical_crossentropy', optimizer=sgd, metrics=['accuracy'])\n", - " \n", - " return model\n", - "\n", - "epochs = 100\n", - "batch_size = 100\n", - "input_shape = X_train.shape[1:4]\n", - "receptive_field = 3\n", - "n_filters = 10\n", - "n_neurons_connected = 50\n", - "n_categories = 10\n", - "\n", - "eta_vals = np.logspace(-5, 1, 7)\n", - "lmbd_vals = np.logspace(-5, 1, 7)" - ] - }, - { - "cell_type": "markdown", - "id": "404c8750", - "metadata": {}, - "source": [ - "## Final part" - ] - }, - { - "cell_type": "code", - "execution_count": 4, - "id": "b26480e4", - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "Metal device set to: Apple M1\n" - ] - }, - { - "name": "stderr", - "output_type": "stream", - "text": [ - "/Users/mhjensen/miniforge3/envs/myenv/lib/python3.9/site-packages/keras/optimizer_v2/gradient_descent.py:102: UserWarning: The `lr` argument is deprecated, use `learning_rate` instead.\n", - " super(SGD, self).__init__(name, **kwargs)\n", - "2023-11-02 08:18:04.108752: W tensorflow/core/platform/profile_utils/cpu_utils.cc:128] Failed to get CPU frequency: 0 Hz\n" - ] - }, - { - "name": "stdout", - "output_type": "stream", - "text": [ - "12/12 [==============================] - 2s 83ms/step - loss: 3.4256 - accuracy: 0.0917\n", - "Learning rate = 1e-05\n", - "Lambda = 1e-05\n", - "Test accuracy: 0.092\n", - "\n", - "12/12 [==============================] - 2s 73ms/step - loss: 3.4338 - accuracy: 0.0944\n", - "Learning rate = 1e-05\n", - "Lambda = 0.0001\n", - "Test accuracy: 0.094\n", - "\n", - "12/12 [==============================] - 2s 73ms/step - loss: 3.5186 - accuracy: 0.0944\n", - "Learning rate = 1e-05\n", - "Lambda = 0.001\n", - "Test accuracy: 0.094\n", - "\n", - "12/12 [==============================] - 2s 74ms/step - loss: 4.3646 - accuracy: 0.0944\n", - "Learning rate = 1e-05\n", - "Lambda = 0.01\n", - "Test accuracy: 0.094\n", - "\n", - "12/12 [==============================] - 2s 79ms/step - loss: 12.7761 - accuracy: 0.0944\n", - "Learning rate = 1e-05\n", - "Lambda = 0.1\n", - "Test accuracy: 0.094\n", - "\n", - "12/12 [==============================] - 2s 76ms/step - loss: 92.0269 - accuracy: 0.0944\n", - "Learning rate = 1e-05\n", - "Lambda = 1.0\n", - "Test accuracy: 0.094\n", - "\n", - "12/12 [==============================] - 2s 77ms/step - loss: 519.9384 - accuracy: 0.0972\n", - "Learning rate = 1e-05\n", - "Lambda = 10.0\n", - "Test accuracy: 0.097\n", - "\n", - "12/12 [==============================] - 2s 81ms/step - loss: 1.5349 - accuracy: 0.4694\n", - "Learning rate = 0.0001\n", - "Lambda = 1e-05\n", - "Test accuracy: 0.469\n", - "\n", - "12/12 [==============================] - 2s 81ms/step - loss: 1.5442 - accuracy: 0.4667\n", - "Learning rate = 0.0001\n", - "Lambda = 0.0001\n", - "Test accuracy: 0.467\n", - "\n", - "12/12 [==============================] - 2s 81ms/step - loss: 1.6288 - accuracy: 0.4667\n", - "Learning rate = 0.0001\n", - "Lambda = 0.001\n", - "Test accuracy: 0.467\n", - "\n", - "12/12 [==============================] - 2s 77ms/step - loss: 2.4714 - accuracy: 0.4722\n", - "Learning rate = 0.0001\n", - "Lambda = 0.01\n", - "Test accuracy: 0.472\n", - "\n", - "12/12 [==============================] - 2s 80ms/step - loss: 10.4141 - accuracy: 0.4556\n", - "Learning rate = 0.0001\n", - "Lambda = 0.1\n", - "Test accuracy: 0.456\n", - "\n", - "12/12 [==============================] - 2s 79ms/step - loss: 53.5240 - accuracy: 0.4472\n", - "Learning rate = 0.0001\n", - "Lambda = 1.0\n", - "Test accuracy: 0.447\n", - "\n", - "12/12 [==============================] - 2s 82ms/step - loss: 4.6259 - accuracy: 0.0889\n", - "Learning rate = 0.0001\n", - "Lambda = 10.0\n", - "Test accuracy: 0.089\n", - "\n", - "12/12 [==============================] - 2s 79ms/step - loss: 0.2641 - accuracy: 0.9194\n", - "Learning rate = 0.001\n", - "Lambda = 1e-05\n", - "Test accuracy: 0.919\n", - "\n", - "12/12 [==============================] - 2s 79ms/step - loss: 0.2736 - accuracy: 0.9167\n", - "Learning rate = 0.001\n", - "Lambda = 0.0001\n", - "Test accuracy: 0.917\n", - "\n", - "12/12 [==============================] - 2s 82ms/step - loss: 0.3604 - accuracy: 0.9167\n", - "Learning rate = 0.001\n", - "Lambda = 0.001\n", - "Test accuracy: 0.917\n", - "\n", - "12/12 [==============================] - 2s 94ms/step - loss: 1.1848 - accuracy: 0.9167\n", - "Learning rate = 0.001\n", - "Lambda = 0.01\n", - "Test accuracy: 0.917\n", - "\n", - "12/12 [==============================] - 2s 94ms/step - loss: 5.7980 - accuracy: 0.9250\n", - "Learning rate = 0.001\n", - "Lambda = 0.1\n", - "Test accuracy: 0.925\n", - "\n", - "12/12 [==============================] - 2s 92ms/step - loss: 2.6003 - accuracy: 0.3472\n", - "Learning rate = 0.001\n", - "Lambda = 1.0\n", - "Test accuracy: 0.347\n", - "\n", - "12/12 [==============================] - 2s 95ms/step - loss: 2.3032 - accuracy: 0.0889\n", - "Learning rate = 0.001\n", - "Lambda = 10.0\n", - "Test accuracy: 0.089\n", - "\n", - "12/12 [==============================] - 2s 96ms/step - loss: 0.0958 - accuracy: 0.9694\n", - "Learning rate = 0.01\n", - "Lambda = 1e-05\n", - "Test accuracy: 0.969\n", - "\n", - "12/12 [==============================] - 2s 97ms/step - loss: 0.1060 - accuracy: 0.9750\n", - "Learning rate = 0.01\n", - "Lambda = 0.0001\n", - "Test accuracy: 0.975\n", - "\n", - "12/12 [==============================] - 2s 96ms/step - loss: 0.1862 - accuracy: 0.9778\n", - "Learning rate = 0.01\n", - "Lambda = 0.001\n", - "Test accuracy: 0.978\n", - "\n", - "12/12 [==============================] - 2s 96ms/step - loss: 0.6819 - accuracy: 0.9750\n", - "Learning rate = 0.01\n", - "Lambda = 0.01\n", - "Test accuracy: 0.975\n", - "\n", - "12/12 [==============================] - 2s 96ms/step - loss: 0.9978 - accuracy: 0.9028\n", - "Learning rate = 0.01\n", - "Lambda = 0.1\n", - "Test accuracy: 0.903\n", - "\n", - "12/12 [==============================] - 2s 98ms/step - loss: 2.3064 - accuracy: 0.0889\n", - "Learning rate = 0.01\n", - "Lambda = 1.0\n", - "Test accuracy: 0.089\n", - "\n", - "12/12 [==============================] - 2s 95ms/step - loss: 2.3065 - accuracy: 0.0889\n", - "Learning rate = 0.01\n", - "Lambda = 10.0\n", - "Test accuracy: 0.089\n", - "\n", - "12/12 [==============================] - 2s 93ms/step - loss: 0.2141 - accuracy: 0.9528\n", - "Learning rate = 0.1\n", - "Lambda = 1e-05\n", - "Test accuracy: 0.953\n", - "\n", - "12/12 [==============================] - 2s 95ms/step - loss: 0.2714 - accuracy: 0.9472\n", - "Learning rate = 0.1\n", - "Lambda = 0.0001\n", - "Test accuracy: 0.947\n", - "\n", - "12/12 [==============================] - 2s 89ms/step - loss: 0.2996 - accuracy: 0.9556\n", - "Learning rate = 0.1\n", - "Lambda = 0.001\n", - "Test accuracy: 0.956\n", - "\n", - "12/12 [==============================] - 2s 88ms/step - loss: 0.6088 - accuracy: 0.8611\n", - "Learning rate = 0.1\n", - "Lambda = 0.01\n", - "Test accuracy: 0.861\n", - "\n", - "12/12 [==============================] - 2s 93ms/step - loss: 1.7069 - accuracy: 0.6556\n", - "Learning rate = 0.1\n", - "Lambda = 0.1\n", - "Test accuracy: 0.656\n", - "\n", - "12/12 [==============================] - 2s 89ms/step - loss: 2.3077 - accuracy: 0.0778\n", - "Learning rate = 0.1\n", - "Lambda = 1.0\n", - "Test accuracy: 0.078\n", - "\n", - "12/12 [==============================] - 3s 117ms/step - loss: nan - accuracy: 0.0778\n", - "Learning rate = 0.1\n", - "Lambda = 10.0\n", - "Test accuracy: 0.078\n", - "\n", - "12/12 [==============================] - 2s 109ms/step - loss: 22.0022 - accuracy: 0.0778\n", - "Learning rate = 1.0\n", - "Lambda = 1e-05\n", - "Test accuracy: 0.078\n", - "\n", - "12/12 [==============================] - 3s 104ms/step - loss: 44.2070 - accuracy: 0.0778\n", - "Learning rate = 1.0\n", - "Lambda = 0.0001\n", - "Test accuracy: 0.078\n", - "\n", - "12/12 [==============================] - 3s 112ms/step - loss: 6.3536 - accuracy: 0.0778\n", - "Learning rate = 1.0\n", - "Lambda = 0.001\n", - "Test accuracy: 0.078\n", - "\n", - "12/12 [==============================] - 3s 125ms/step - loss: 2.3082 - accuracy: 0.0889\n", - "Learning rate = 1.0\n", - "Lambda = 0.01\n", - "Test accuracy: 0.089\n", - "\n", - "12/12 [==============================] - 3s 122ms/step - loss: 2.3126 - accuracy: 0.0778\n", - "Learning rate = 1.0\n", - "Lambda = 0.1\n", - "Test accuracy: 0.078\n", - "\n", - "12/12 [==============================] - 3s 123ms/step - loss: nan - accuracy: 0.0778\n", - "Learning rate = 1.0\n", - "Lambda = 1.0\n", - "Test accuracy: 0.078\n", - "\n", - "12/12 [==============================] - 3s 120ms/step - loss: nan - accuracy: 0.0778\n", - "Learning rate = 1.0\n", - "Lambda = 10.0\n", - "Test accuracy: 0.078\n", - "\n", - "12/12 [==============================] - 3s 116ms/step - loss: 6130353.0000 - accuracy: 0.1056\n", - "Learning rate = 10.0\n", - "Lambda = 1e-05\n", - "Test accuracy: 0.106\n", - "\n", - "12/12 [==============================] - 3s 120ms/step - loss: 388451.5000 - accuracy: 0.0917\n", - "Learning rate = 10.0\n", - "Lambda = 0.0001\n", - "Test accuracy: 0.092\n", - "\n", - "12/12 [==============================] - 3s 117ms/step - loss: 2.4314 - accuracy: 0.0889\n", - "Learning rate = 10.0\n", - "Lambda = 0.001\n", - "Test accuracy: 0.089\n", - "\n", - "12/12 [==============================] - 3s 120ms/step - loss: 2.5014 - accuracy: 0.0889\n", - "Learning rate = 10.0\n", - "Lambda = 0.01\n", - "Test accuracy: 0.089\n", - "\n", - "12/12 [==============================] - 3s 131ms/step - loss: nan - accuracy: 0.0778\n", - "Learning rate = 10.0\n", - "Lambda = 0.1\n", - "Test accuracy: 0.078\n", - "\n", - "12/12 [==============================] - 3s 124ms/step - loss: nan - accuracy: 0.0778\n", - "Learning rate = 10.0\n", - "Lambda = 1.0\n", - "Test accuracy: 0.078\n", - "\n", - "12/12 [==============================] - 3s 127ms/step - loss: nan - accuracy: 0.0778\n", - "Learning rate = 10.0\n", - "Lambda = 10.0\n", - "Test accuracy: 0.078\n", - "\n" - ] - } - ], - "source": [ - "CNN_keras = np.zeros((len(eta_vals), len(lmbd_vals)), dtype=object)\n", - " \n", - "for i, eta in enumerate(eta_vals):\n", - " for j, lmbd in enumerate(lmbd_vals):\n", - " CNN = create_convolutional_neural_network_keras(input_shape, receptive_field,\n", - " n_filters, n_neurons_connected, n_categories,\n", - " eta, lmbd)\n", - " CNN.fit(X_train, Y_train, epochs=epochs, batch_size=batch_size, verbose=0)\n", - " scores = CNN.evaluate(X_test, Y_test)\n", - " \n", - " CNN_keras[i][j] = CNN\n", - " \n", - " print(\"Learning rate = \", eta)\n", - " print(\"Lambda = \", lmbd)\n", - " print(\"Test accuracy: %.3f\" % scores[1])\n", - " print()" - ] - }, - { - "cell_type": "markdown", - "id": "67264745", - "metadata": {}, - "source": [ - "## Final visualization" - ] - }, - { - "cell_type": "code", - "execution_count": 7, - "id": "db92d957", - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "45/45 [==============================] - 4s 83ms/step - loss: 3.3532 - accuracy: 0.1134\n", - "12/12 [==============================] - 1s 66ms/step - loss: 3.4256 - accuracy: 0.0917\n", - "45/45 [==============================] - 4s 78ms/step - loss: 3.3619 - accuracy: 0.1141\n", - "12/12 [==============================] - 1s 64ms/step - loss: 3.4338 - accuracy: 0.0944\n", - "45/45 [==============================] - 3s 76ms/step - loss: 3.4466 - accuracy: 0.1141\n", - "12/12 [==============================] - 1s 62ms/step - loss: 3.5186 - accuracy: 0.0944\n", - "45/45 [==============================] - 4s 78ms/step - loss: 4.2927 - accuracy: 0.1141\n", - "12/12 [==============================] - 1s 66ms/step - loss: 4.3646 - accuracy: 0.0944\n", - "45/45 [==============================] - 3s 76ms/step - loss: 12.7049 - accuracy: 0.1141\n", - "12/12 [==============================] - 1s 63ms/step - loss: 12.7761 - accuracy: 0.0944\n", - "45/45 [==============================] - 3s 74ms/step - loss: 91.9603 - accuracy: 0.1134\n", - "12/12 [==============================] - 1s 59ms/step - loss: 92.0269 - accuracy: 0.0944\n", - "45/45 [==============================] - 3s 76ms/step - loss: 519.9026 - accuracy: 0.1148\n", - "12/12 [==============================] - 1s 62ms/step - loss: 519.9384 - accuracy: 0.0972\n", - "45/45 [==============================] - 4s 79ms/step - loss: 1.4512 - accuracy: 0.5449\n", - "12/12 [==============================] - 1s 62ms/step - loss: 1.5349 - accuracy: 0.4694\n", - "45/45 [==============================] - 3s 75ms/step - loss: 1.4605 - accuracy: 0.5470\n", - "12/12 [==============================] - 1s 62ms/step - loss: 1.5442 - accuracy: 0.4667\n", - "45/45 [==============================] - 4s 80ms/step - loss: 1.5454 - accuracy: 0.5477\n", - "12/12 [==============================] - 1s 64ms/step - loss: 1.6288 - accuracy: 0.4667\n", - "45/45 [==============================] - 3s 76ms/step - loss: 2.3881 - accuracy: 0.5435\n", - "12/12 [==============================] - 1s 68ms/step - loss: 2.4714 - accuracy: 0.4722\n", - "45/45 [==============================] - 4s 80ms/step - loss: 10.3364 - accuracy: 0.5393\n", - "12/12 [==============================] - 1s 63ms/step - loss: 10.4141 - accuracy: 0.4556\n", - "45/45 [==============================] - 4s 79ms/step - loss: 53.4810 - accuracy: 0.4983\n", - "12/12 [==============================] - 1s 65ms/step - loss: 53.5240 - accuracy: 0.4472\n", - "45/45 [==============================] - 3s 76ms/step - loss: 4.6258 - accuracy: 0.1044\n", - "12/12 [==============================] - 1s 66ms/step - loss: 4.6259 - accuracy: 0.0889\n", - "45/45 [==============================] - 4s 80ms/step - loss: 0.1946 - accuracy: 0.9534\n", - "12/12 [==============================] - 1s 67ms/step - loss: 0.2641 - accuracy: 0.9194\n", - "45/45 [==============================] - 3s 77ms/step - loss: 0.2027 - accuracy: 0.9541\n", - "12/12 [==============================] - 1s 64ms/step - loss: 0.2736 - accuracy: 0.9167\n", - "45/45 [==============================] - 4s 79ms/step - loss: 0.2901 - accuracy: 0.9541\n", - "12/12 [==============================] - 1s 65ms/step - loss: 0.3604 - accuracy: 0.9167\n", - "45/45 [==============================] - 3s 77ms/step - loss: 1.1123 - accuracy: 0.9520\n", - "12/12 [==============================] - 1s 58ms/step - loss: 1.1848 - accuracy: 0.9167\n", - "45/45 [==============================] - 4s 81ms/step - loss: 5.7392 - accuracy: 0.9415\n", - "12/12 [==============================] - 1s 61ms/step - loss: 5.7980 - accuracy: 0.9250\n", - "45/45 [==============================] - 3s 77ms/step - loss: 2.5993 - accuracy: 0.4085\n", - "12/12 [==============================] - 1s 65ms/step - loss: 2.6003 - accuracy: 0.3472\n", - "45/45 [==============================] - 3s 77ms/step - loss: 2.3024 - accuracy: 0.1044\n", - "12/12 [==============================] - 1s 66ms/step - loss: 2.3032 - accuracy: 0.0889\n", - "45/45 [==============================] - 4s 79ms/step - loss: 0.0180 - accuracy: 1.0000\n", - "12/12 [==============================] - 1s 66ms/step - loss: 0.0958 - accuracy: 0.9694\n", - "45/45 [==============================] - 4s 80ms/step - loss: 0.0280 - accuracy: 0.9986\n", - "12/12 [==============================] - 1s 68ms/step - loss: 0.1060 - accuracy: 0.9750\n", - "45/45 [==============================] - 3s 77ms/step - loss: 0.1148 - accuracy: 0.9986\n", - "12/12 [==============================] - 1s 67ms/step - loss: 0.1862 - accuracy: 0.9778\n", - "45/45 [==============================] - 3s 76ms/step - loss: 0.6357 - accuracy: 0.9958\n", - "12/12 [==============================] - 1s 67ms/step - loss: 0.6819 - accuracy: 0.9750\n", - "45/45 [==============================] - 3s 76ms/step - loss: 0.9286 - accuracy: 0.9499\n", - "12/12 [==============================] - 1s 65ms/step - loss: 0.9978 - accuracy: 0.9028\n", - "45/45 [==============================] - 3s 75ms/step - loss: 2.3020 - accuracy: 0.1044\n", - "12/12 [==============================] - 1s 64ms/step - loss: 2.3064 - accuracy: 0.0889\n", - "45/45 [==============================] - 4s 78ms/step - loss: 2.3020 - accuracy: 0.1044\n", - "12/12 [==============================] - 1s 66ms/step - loss: 2.3065 - accuracy: 0.0889\n", - "45/45 [==============================] - 4s 78ms/step - loss: 0.0060 - accuracy: 1.0000\n", - "12/12 [==============================] - 1s 62ms/step - loss: 0.2141 - accuracy: 0.9528\n", - "45/45 [==============================] - 3s 76ms/step - loss: 0.0368 - accuracy: 0.9930\n", - "12/12 [==============================] - 1s 65ms/step - loss: 0.2714 - accuracy: 0.9472\n", - "45/45 [==============================] - 4s 80ms/step - loss: 0.1343 - accuracy: 0.9910\n", - "12/12 [==============================] - 1s 68ms/step - loss: 0.2996 - accuracy: 0.9556\n", - "45/45 [==============================] - 4s 78ms/step - loss: 0.4220 - accuracy: 0.9207\n", - "12/12 [==============================] - 1s 66ms/step - loss: 0.6088 - accuracy: 0.8611\n", - "45/45 [==============================] - 4s 79ms/step - loss: 1.6795 - accuracy: 0.6764\n", - "12/12 [==============================] - 1s 61ms/step - loss: 1.7069 - accuracy: 0.6556\n", - "45/45 [==============================] - 4s 79ms/step - loss: 2.3020 - accuracy: 0.1044\n", - "12/12 [==============================] - 1s 67ms/step - loss: 2.3077 - accuracy: 0.0778\n", - "45/45 [==============================] - 4s 80ms/step - loss: nan - accuracy: 0.1044\n", - "12/12 [==============================] - 1s 68ms/step - loss: nan - accuracy: 0.0778\n", - "45/45 [==============================] - 4s 81ms/step - loss: 21.9981 - accuracy: 0.1044\n", - "12/12 [==============================] - 1s 67ms/step - loss: 22.0022 - accuracy: 0.0778\n", - "45/45 [==============================] - 4s 79ms/step - loss: 44.1977 - accuracy: 0.1044\n", - "12/12 [==============================] - 1s 67ms/step - loss: 44.2070 - accuracy: 0.0778\n", - "45/45 [==============================] - 3s 77ms/step - loss: 6.3493 - accuracy: 0.1044\n", - "12/12 [==============================] - 1s 68ms/step - loss: 6.3536 - accuracy: 0.0778\n", - "45/45 [==============================] - 4s 80ms/step - loss: 2.3030 - accuracy: 0.1044\n", - "12/12 [==============================] - 1s 66ms/step - loss: 2.3082 - accuracy: 0.0889\n", - "45/45 [==============================] - 4s 79ms/step - loss: 2.3029 - accuracy: 0.1044\n", - "12/12 [==============================] - 1s 66ms/step - loss: 2.3126 - accuracy: 0.0778\n", - "45/45 [==============================] - 4s 78ms/step - loss: nan - accuracy: 0.1044\n", - "12/12 [==============================] - 1s 64ms/step - loss: nan - accuracy: 0.0778\n", - "45/45 [==============================] - 4s 79ms/step - loss: nan - accuracy: 0.1044\n", - "12/12 [==============================] - 1s 66ms/step - loss: nan - accuracy: 0.0778\n", - "45/45 [==============================] - 4s 79ms/step - loss: 6130353.0000 - accuracy: 0.1009\n", - "12/12 [==============================] - 1s 66ms/step - loss: 6130353.0000 - accuracy: 0.1056\n", - "45/45 [==============================] - 3s 77ms/step - loss: 388451.4375 - accuracy: 0.1016\n", - "12/12 [==============================] - 1s 68ms/step - loss: 388451.5000 - accuracy: 0.0917\n", - "45/45 [==============================] - 4s 80ms/step - loss: 2.4241 - accuracy: 0.1044\n", - "12/12 [==============================] - 1s 66ms/step - loss: 2.4314 - accuracy: 0.0889\n", - "45/45 [==============================] - 4s 81ms/step - loss: 2.4394 - accuracy: 0.1037\n", - "12/12 [==============================] - 1s 62ms/step - loss: 2.5014 - accuracy: 0.0889\n" - ] - }, - { - "name": "stdout", - "output_type": "stream", - "text": [ - "45/45 [==============================] - 4s 79ms/step - loss: nan - accuracy: 0.1044\n", - "12/12 [==============================] - 1s 65ms/step - loss: nan - accuracy: 0.0778\n", - "45/45 [==============================] - 4s 81ms/step - loss: nan - accuracy: 0.1044\n", - "12/12 [==============================] - 1s 64ms/step - loss: nan - accuracy: 0.0778\n", - "45/45 [==============================] - 4s 78ms/step - loss: nan - accuracy: 0.1044\n", - "12/12 [==============================] - 1s 67ms/step - loss: nan - accuracy: 0.0778\n" - ] - }, - { - "data": { - "image/png": "iVBORw0KGgoAAAANSUhEUgAAAyAAAANbCAYAAAC6lftqAAAAOXRFWHRTb2Z0d2FyZQBNYXRwbG90bGliIHZlcnNpb24zLjUuMSwgaHR0cHM6Ly9tYXRwbG90bGliLm9yZy/YYfK9AAAACXBIWXMAAA9hAAAPYQGoP6dpAACCl0lEQVR4nOzdd3xT9f7H8XeSNi1dLIEWCsiuVaaIgAwREa84UEBAQYaiXv2BgrLcIIIIioLgBAeIIMuBICJ6VZS9t1CkrNIilJaWtmmT/P4IVENbCJicdLye95EH5OR8e75531r6yfdzzjE5nU6nAAAAAMAAZn9PAAAAAEDJQQECAAAAwDAUIAAAAAAMQwECAAAAwDAUIAAAAAAMQwECAAAAwDAUIAAAAAAMQwECAAAAwDAUIAAAAAAMQwECoEgaMWKE6tWrd8HHTTfd9K+OsXDhQtWrV0+HDx/26Zh/69ChQ4qJiVGzZs2UmZlp2HEBALgcJqfT6fT3JADgUh08eFAnT57MfT5t2jTt3LlTb7/9du42q9Wq2NjYyz7GyZMndfDgQcXGxspqtfpszL81adIkLVu2TIcPH9bLL7+su+++25DjAgBwOShAABQLI0aM0Nq1a/Xjjz/6eyqGcjgcuummm9S5c2ft3LlTKSkpmjt3rr+nBQBAgWjBAlCsrVmzRvXq1dOcOXPUrl07tWzZUitXrpQkzZs3T/fcc48aNWqkBg0a6K677tKSJUtyx57fTjVixAj17dtXCxYsUMeOHXXNNdfozjvv1M8///yvxkjSpk2bdP/996tRo0a68cYb9cknn6hv374aMWLEBd/fypUrlZCQoHbt2unOO+/U5s2btXv37jz7nThxQs8884xatmypxo0b6/7779eGDRtyX8/OztbUqVN18803q0GDBurUqZMWLFiQ+3rv3r3Vu3fvfLNds2ZN7nuPjY3VvHnz1KpVK7Vp00Z79+6V3W7X+++/r9tvv10NGjRQo0aN1KNHD61atcrt623fvl0PPfSQrr32WjVv3lyDBw9WQkKCcnJy1KpVKz311FN53td//vMfjRw58o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+fz589XZWWlxWnyk9vt1vLlyxUMBhUIBDRv3jzdunVLAwMDunPnjul4eaGwsFDNzc26fPmyysvLVVNTo3v37unZs2e6evWq6XgABSTXtLS0aGJiQsePH9f3799VV1en7u5u7iLDFh4+fKjx8XE9evRo2rNrGhsbdfbsWUPJ8ofD4VB7e7suXLggv9+vr1+/qra2VtevX9eCBQtMxwP+VUFBgTo6OhQOh+X3+5VIJOTxeNTT06MVK1aYjpc3fD6fioqKpp4n5nK5dOnSJa1du9Z0NECOdDqdNh0CAAAAwP8DZ0AAAAAAWIYCAgAAAMAyFBAAAAAAlqGAAAAAALAMBQQAAACAZSggAAAAACxDAQEAAABgGQoIAAAAAMtQQADAZlKplDwej7xer0KhkOk4AAD8JxQQALAZh8Oha9euqaamRpFIRMPDw6YjAQCQNQoIANiM0+lUXV2dmpubJUmDg4OGEwEAkD0KCADY1NKlSyVJ7969M5wEAIDsUUAAwKa6urokSUNDQ4aTAACQPQoIANjQ06dPdfPmTZWWlioajZqOAwBA1iggAGAziURCra2tqq+v186dO/XlyxeNjo6ajgUAQFYoIABgM8FgUBMTE2pra5PH45HENiwAgH1QQADARh48eKD+/n6dOnVKZWVlUwWEg+gAALuggACATXz+/FmBQEA7duzQli1bJEmLFi1SSUkJ50AAALZBAQEAmzhx4oRKS0t17NixjHl1dTVbsAAAtkEBAQAbuH37tp48eaJz586puLg445rH49HHjx+VTCYNpQMAIHuOdDqdNh0CAAAAwP8DKyAAAAAALEMBAQAAAGAZCggAAAAAy1BAAAAAAFiGAgIAAADAMhQQAAAAAJahgAAAAACwDAUEAAAAgGUoIAAAAAAsQwEBAAAAYBkKCAAAAADLUEAAAAAAWOYvnz5IEPg9NrYAAAAASUVORK5CYII=\n", - "text/plain": [ - "
" - ] - }, - "metadata": {}, - "output_type": "display_data" - }, - { - "data": { - "image/png": "iVBORw0KGgoAAAANSUhEUgAAAyAAAANbCAYAAAC6lftqAAAAOXRFWHRTb2Z0d2FyZQBNYXRwbG90bGliIHZlcnNpb24zLjUuMSwgaHR0cHM6Ly9tYXRwbG90bGliLm9yZy/YYfK9AAAACXBIWXMAAA9hAAAPYQGoP6dpAAC4mklEQVR4nOzdd3wT9R/H8VeSNm3pYENLmbIKIrNMQVRERRGUJfOHgiAOEBEQERQQZSoqQ0BZogyRKaIslSV7yB4im0LZhe4m+f2RtpCmlYBtWuj7+Xj0obncN3f3brje577fuzPYbDYbIiIiIiIibmDM7BUQEREREZHsQwWIiIiIiIi4jQoQERERERFxGxUgIiIiIiLiNipARERERETEbVSAiIiIiIiI26gAERERERERt1EBIiIiIiIibqMCREQkA+lZryIiIo48MnsFRETcqV+/fixcuPBf5wkODua33377z8uaN28eR48epV+/fred98cff+T999+nXr16fPPNN/952SIiIlmVwabTcyKSjZw8eZLLly8nv54wYQL79+9n3LhxydPMZjPly5f/z8t6/PHHqVGjBsOHD7/tvG3atOHGjRv8/fffrFixgiJFivzn5YuIiGRF6gERkWylaNGiFC1aNPl1njx5MJvNVK5cOdPW6dixY+zYsYPJkyfTp08ffvjhB955551MWx8REZGMpGtARERScfjwYV599VWqVq1K1apVeeONNzh16pTDPDNnzuTpp5/moYceol69egwaNIgbN24A9t6PM2fOsHDhQsqWLcvp06fTXNb8+fPx9/endu3aPP3008yfP5+4uDin+fbu3csrr7xCtWrVqFWrFm+//TZhYWHJ71+6dIn+/ftTp04dqlSpQrt27di+fXvy+2XLlmXs2LEOnzl27FjKli2b/Lpfv3507NiRDz/8kNDQUF544QUSEhK4fPkygwcP5rHHHqNChQrUqFGDN954w2m7fv75Z5o1a0alSpV49NFHGTVqFHFxcRw5coSyZcsyd+5ch/nPnz9PuXLlbjssTkRE7h8qQEREUjh27BitW7fm0qVLDB8+nI8//phTp07Rpk0bLl26BNgPtEeMGEG7du2YMmUKb7zxBosXL2bo0KEAjBs3jvz581O/fn3mzp1LgQIFUl2WxWJh8eLFPPPMM5jNZpo1a8alS5dYtWqVw3wHDx6kTZs2REdHM3z4cIYMGcL+/fvp1KkT8fHxREVF0bp1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YREBDg8N748eNZtGgRvXr1wtvbG39/f4fbBydZs2YNISEh+Pv7p3qh+86dO/Hz86N06dKA/ZqTW0VFRd12Pbdt28a7775L+/bt6dy5M4GBgQCMHDky+SL3pPVPuY5Xr15l3759VK5cGV9fX5o3b87ChQvZvXs3y5cvp0OHDrddvoiI3F80BEtEJIUaNWrw999/U65cOR566CEeeughKlSowPTp01m5ciUAPXv25M033wTsBUujRo14/fXXsVgshIeHA2A0/vsudsGCBVSuXJmGDRtSs2ZNh582bdpw7do1fvnlF8B+Pce6desc7o516NAhunbtyp49ewgNDeXUqVMcOnQo+f24uDi6d+/ODz/8ANh7IM6dO+ewDjt27LhtHjt37sRqtdKjR4/k4sNisSQPR7NarTzwwAPkzp2b1atXO7T96aef6NKlC7GxsQBUr16d4sWLM2rUKK5cucLzzz9/2+WLiMj9RQWIiEgKr7/+OidPnuTVV19l1apVrFu3ju7du/Pzzz8nX2NRq1YtVq5cyYgRI9i4cSPLly/niy++oHjx4snzBAQEsH//frZs2UJMTIzDMnbv3s3hw4fTHK7VoEEDcubMmXyR9+uvv86VK1fo0qULv/32G7/++is9e/bkwQcf5JFHHqFZs2YUKVKE1157jcWLF7Nu3Tp69OhBTExMci/Do48+ys8//8ysWbPYuHEjffv25cSJE7fNo2LFigAMGTKETZs2sWLFCl5++WUOHjwI2HtRTCYT3bt3Z/ny5QwaNIgNGzbw/fff8/nnn9OmTZvkoWsAzZs3Z8uWLdSuXZugoKA7+dWIiMh9QAWIiEgKISEhfP/99xgMBvr27UuPHj24cOEC48eP58knnwSgdevWDBgwgLVr19KtWzc++OADSpYsydSpU/H09ASgU6dOXLx4kc6dO7N3716HZcyfPx+TyeRwp6tbmc1mGjVqxK5duzhw4ADly5dn5syZWK1W3n77bYYMGULlypX5+uuvMZvN+Pn58d1331GlShU+/vhj3nrrLWJjY5k5c2byBeXvvfcejz/+OKNGjaJHjx74+Pi49MDDmjVr8sEHH7Bz5066dOnCsGHDKFSoUPLT45OGYbVr147hw4ezbds2Xn31VaZOnUqnTp3o16+fw+c9+uijALr4XEQkmzLYbDZbZq+EiIhkH19//TXffPMN69atw2w2Z/bqiIiIm+kidBERcYuFCxdy+PBhZs2aRdeuXVV8iIhkUypARETELQ4ePMicOXN44okn6NKlS2avjoiIZBINwRIREREREbfRRegiIiIiIuI2KkBERERERMRtVICIiIiIiIjbqAARERERERG3yVZ3wXrS3DazV+G+ZjAaMnsVREREMpZB524z2vLomZm9CmmyniuT2auQKmPg4cxehTuif0UiIiIiIuI2KkBERERERMRtstUQLBERERGRu2XFmtmrkKp7rUfhXltfERERERG5h6kAERERERERt9EQLBERERERF1hsWXMI1r12QK8eEBERERERcRsVICIiIiIi4jb3Wo+NiIiIiEimsGLL7FW4L6gHRERERERE3EYFiIiIiIiIuI2GYImIiIiIuCCrPojwXqMeEBERERERcRsVICIiIiIi4jYagiUiIiIi4gKLTXfBSg/qAREREREREbdRASIiIiIiIm6jIVgiIiIiIi7QgwjTh3pARERERETEbVSAiIiIiIiI22gIloiIiIiICywagpUu1AMiIiIiIiJuowJERERERETcRkOwRERERERcoLtgpQ/1gIiIiIiIiNuoABEREREREbfRECwRERERERdYbBqClR7UAyIiIiIiIm6jAkRERERERNxGQ7BERERERFxgzewVuE+oB0RERERERNxGBYiIiIiIiLiNhmCJiIiIiLjAogcRpgv1gIiIiIiIiNuoABEREREREbfRECwRERERERdYNAIrXagHRERERERE3EYFiIiIiIiIuI2GYImIiIiIuEAPIkwf6gERERERERG3UQEiIiIiIiJuoyFYIiIiIiIusGDI7FW4L6gHRERERERE3EYFiIiIiIiIuI2GYImIiIiIuMCqBxGmC/WAiIiIiIiI26gAERERERERt1EBkgFCn6zIuI1DWXJ1GjOPfEHrvk1u26ZB24eZvGskP12bzpS9o3n65Ued5mnY4REm7xzB0ojpfHvoczp80ByTh8lhngcqFWPo4r78cGYiP4ZNYtjP/ShVuXj6bFgWEtqwImM3fMTiy1P59vAXvNjn9hk/3uZhJu8YwZIr0/hm96g0M560fTg/XZ3GjINj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oUffv2pXXr1hQpUsTl5aoAERERERHJpnr06EFCQgIDBgwgJiaG6tWrM2XKFMxmM6dPn6ZBgwYMGzaMZs2akStXLiZPnsywYcN47rnnyJ07N61bt+a11167o2UabDabLYO2J8t50tw2s1fhvmYwZs07Q4iIiKQbg0avZ7Tl0TMzexXStOZ4mcxehVTVL344s1fhjuhfkYiIiIiIuI0KEBERERERcRtdAyIiIiIi4oKs+iDCe416QERERERExG1UgIiIiIiIiNtoCJaIiIiIiAv+y0P/5CalKCIiIiIibqMCRERERERE3EZDsEREREREXGDVXbDShXpARERERETEbVSAiIiIiIiI22gIloiIiIiICyw6d58ulKKIiIiIiLiNChAREREREXEbDcESEREREXGBHkSYPpSiiIiIiIi4jQoQERERERFxGw3BEhERERFxgVXn7tOFUhQREREREbdRASIiIiIiIm6jIVgiIiIiIi6w2AyZvQr3BfWAiIiIiIiI26gAERERERERt1EBIiIiIiIibqNrQEREREREXGDRuft0oRRFRERERMRtVICIiIiIiIjbaAiWiIiIiIgLrDadu08PSlFERERERNxGBYiIiIiIiLiNhmCJiIiIiLhAd8FKH0pRRERERETcRgWIiIiIiIi4jYZgiYiIiIi4wGIzZPYq3BfUAyIiIiIiIm6jAkRERERERNxGQ7BERERERFxg1bn7dJGtCpATA6pn9irc1wy2zF4Dkf9GD7jNeMb4zF6D+5/BmtlrcH8rPHJrZq+CyD1Pf25FRERERMRtslUPiIiIiIjI3bKoqzxdKEUREREREXEbFSAiIiIiIuI2GoIlIiIiIuICK3oQYXpQD4iIiIiIiLiNChAREREREXEbDcESEREREXGB7oKVPpSiiIiIiIi4jQoQERERERFxGw3BEhERERFxgUXn7tOFUhQREREREbdRASIiIiIiIm6jIVgiIiIiIi6w2vQgwvSgHhAREREREXEbFSAiIiIiIuI2GoIlIiIiIuIC3QUrfShFERERERFxGxUgIiIiIiLiNhqCJSIiIiLiAqtN5+7Tg1IUERERERG3UQEiIiIiIiJuoyFYIiIiIiIusKAHEaYH9YCIiIiIiIjbqAARERERERG30RAsEREREREX6C5Y6UMpioiIiIiI26gAERERERERt9EQLBERERERF+guWOlDPSAiIiIiIuI2KkBERERERMRtNARLRERERMQFugtW+lCKIiIiIiLiNipARERERETEbTQES0RERETEBRYNwUoXSlFERERERNxGBYiIiIiISDZltVr58ssvqVevHpUqVaJTp06cOHEizfkvXLhAr169qFmzJjVr1uStt97i3Llzd7RMFSAiIiIiIi6wYsiSP//FhAkTmDNnDkOHDmXu3LkYDAa6dOlCXFxcqvO//fbbhIWFMW3aNKZNm8a5c+d4/fXX72iZKkBERERERLKhuLg4pk6dSvfu3alfvz4hISGMGTOG8+fPs3LlSqf5IyIi2Lp1K126dKF8+fKUL1+erl27sm/fPq5cueLyclWAiIiIiIhkQwcPHiQyMpJatWolTwsICKB8+fJs3brVaX4vLy9y5MjBokWLuHHjBjdu3GDx4sUUL16cnDlzurxc3QVLRERERMQFWfUuWA0aNPjX91evXp3q9KRrN4KCghymFyhQgLCwMKf5vby8+PjjjxkyZAihoaEYDAby58/Pd999h9HoejZZM0UREREREclQ0dHRAJjNZofpXl5exMbGOs1vs9k4dOgQVapU4fvvv2fGjBkEBwfzxhtvcOPGDZeXqx4QEREREZF7WFo9HLfj7e0N2K8FSfp/gNjYWHx8fJzm//nnn5k1axa///47fn5+AEycOJHHHnuM+fPn07FjR5eWqwJERERERMQFVtt/u+NUVpM09Co8PJyiRYsmTw8PDyckJMRp/u3bt1OiRInk4gMgZ86clChRguPHj7u8XA3BEhERERHJhkJCQvDz82Pz5s3J0yIiIti/fz+hoaFO8wcFBXHixAmH4VnR0dGcPn2aYsWKubxcFSAiIiIiItmQ2Wymffv2jB49mtWrV3Pw4EHefvttAgMDadiwIRaLhQsXLhATEwPA888/D0DPnj05ePBg8vxms5lmzZq5vFwVICIiIiIiLrBgzJI//0WPHj1o0aIFAwYMoE2bNphMJqZMmYLZbCYsLIy6deuybNkywH53rFmzZmGz2ejYsSMvv/wynp6ezJ49m4CAAJeXabDZbLb/tNb3kLJDxmTasuuVLEbPxx6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pbdvfA/b9cd+PnrxcwqXCeLDH3vxeOuH+brfrOQekVJVivPl+iHUaHTzuRwrZ67li9e/oWqDhxj0Yy8q1i/HiJcnsPbHmz0iX/ebxdf9ZlH3+ep8vPRdOgxszo7Ve3mz9oDk60iunL/Ge88Mx8PswcC5PekwsDnLZ6zh/edGODw/JLuy2gxZ8udeY7CldZsFNzt//jz79+/nsccey7BllB0yJsM+W8CQJb5JInfPliVOydzfjM4PcJZ0Zsiel/q4TeGR2Xc4o7usiJuV2auQprd2tsnsVUjVF1VmZ/Yq3JFMH4KVpGDBghQsWDCzV0NERERERDJQlilARERERESyMqu6ytOFUhQREREREbdRASIiIiIiIm6jIVgiIiIiIi6wcO/dcSorUg+IiIiIiIi4jQoQERERERFxGw3BEhERERFxwb340L+sSD0gIiIiIiLiNipARERERETEbTQES0RERETEBXoQYfpQiiIiIiIi4jYqQERERERExG00BEtERERExAVWPYgwXagHRERERERE3EYFiIiIiIiIuI2GYImIiIiIuMCiBxGmC/WAiIiIiIiI26gAERERERERt9EQLBERERERF+hBhOlDKYqIiIiIiNuoABEREREREbfRECwRERERERdYdResdKEeEBERERERcRsVICIiIiIi4jYagiUiIiIi4gIrGoKVHtQDIiIiIiIibqMCRERERERE3EZDsEREREREXKC7YKUP9YCIiIiIiIjbqAARERERERG30RAsEREREREXWG06d58elKKIiIiIiLiNChAREREREXEbDcESEREREXGB7oKVPtQDIiIiIiIibqMCRERERERE3EZDsEREREREXGBFQ7DSg3pARERERETEbVSAiIiIiIiI22gIloiIiIiIC3QXrPShHhAREREREXEbFSAiIiIiIuI2GoIlIiIiIuICDcFKH+oBERERERERt1EBIiIiIiIibqMhWCIiIiIiLtAQrPShHhAREREREXEbFSAiIiIiIuI22WoI1sKXR2f2KtzXLKhbUkT+nRlrZq/Cfa/DwN6ZvQoi9y0NwUof6gERERERERG3UQEiIiIiIiJuk62GYImIiIiI3C2rhpunC/WAiIiIiIiI26gAERERERERt9EQLBERERERF+guWOlDPSAiIiIiIuI2KkBERERERMRtNARLRERERMQFGoKVPtQDIiIiIiIibqMCRERERERE3EZDsEREREREXKAhWOlDPSAiIiIiItmU1Wrlyy+/pF69elSqVIlOnTpx4sSJVOcdO3YsZcuWTfXnvffec3mZKkBERERERLKpCRMmMGfOHIYOHcrcuXMxGAx06dKFuLg4p3k7derE+vXrHX569uyJt7c3HTt2dHmZKkBERERERFxgtRmy5M/diouLY+rUqXTv3p369esTEhLCmDFjOH/+PCtXrnSa39fXl/z58yf/REdHM2nSJPr160dISIjLy1UBIiIiIiKSDR08eJDIyEhq1aqVPC0gIIDy5cuzdevW27YfPnw4pUuX5sUXX7yj5eoidBERERGRe1iDBg3+9f3Vq1enOv3cuXMABAUFOUwvUKAAYWFh//qZe/bsYfXq1cyYMQOj8c76NFSAiIiIiIi4wHaf3QUrOjoaALPZ7DDdy8uLa9eu/Wvb6dOnU6lSJYfeE1epABERERERuYel1cNxO97e3oD9WpCk/weIjY3Fx8cnzXZRUVGsXLmSDz/88K6Wq2tARERERESyoaShV+Hh4Q7Tw8PDCQwMTLPdunXrsFqtNGzY8K6WqwJERERERMQFVgxZ8uduhYSE4Ofnx+bNm5OnRUREsH//fkJDQ9Nst337dh588EECAgLuarkagiUiIiIikg2ZzWbat2/P6NGjyZMnD8HBwYwaNYrAwEAaNmyIxWLh8uXL+Pv7OwzROnjwIGXKlLnr5aoHREREREQkm+rRowctWrRgwIABtGnTBpPJxJQpUzCbzYSFhVG3bl2WLVvm0ObixYvkypXrrpepHhARERERERf8l4f+ZVUmk4k+ffrQp08fp/cKFy7MoUOHnKanLEjulHpARERERETEbVSAiIiIiIiI22gIloiIiIiIC+63BxFmFvWAiIiIiIiI26gAERERERERt9EQLBERERERF9yPd8HKDOoBERERERERt1EBIiIiIiIibqMhWCIiIiIiLtBdsNKHekBERERERMRtVICIiIiIiIjbaAiWiIiIiIgLdBes9KEeEBERERERcRsVICIiIiIi4jYagiUiIiIi4gKbLbPX4P6gHhAREREREXEbFSAiIiIiIuI2GoIlIiI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PlGP0qoGM6jyRlTPXJrd59pXHafF2Y/IXyUPYsXDmjFzC6u/XO3zuC92fpnHXJyhYPD+Xw66yY9Uepn0wN7mQAShdpQSvjmpPqSrFibwaxbqFW5gxaB7Rbnr6/Iq4WW5Zzt14aMmHmb0KqdrTZHBmr8IdydQCJMnJkyfJnTs3/v7+Tu8dO3aMFStW8Oqrr/7n5WRmAZIdZGYBIiL3hswsQLKLzCpAsgt3FSDZWVYuQB5cPCizVyFV+5oOyuxVuCNZ4obORYsWTfO9EiVKpEvxISIiIiIimS8b3QleREREREQyW5boARERERERyeoy/8KF+4N6QERERERExG1UgIiIiIiIiNtoCJaIiIiIiAvuxYf+ZUXqAREREREREbdRASIiIiIiIm6jIVgiIiIiIi7QEKz0oR4QERERERFxGxUgIiIiIiLiNhqCJSIiIiLiAj2HMH2oB0RERERERNxGBYiIiIiIiLiNhmCJiIiIiLhAd8FKH+oBERERERERt1EBIiIiIiIibqMhWCIiIiIirtBtsNKFekBERERERMRtVICIiIiIiIjbaAiWiIiIiIgLdBes9KEeEBERERERcRsVICIiIiIi4jYagiUiIiIi4gKb7oKVLtQDIiIiIiIibqMCRERERERE3EZDsEREREREXKC7YKUP9YCIiIiIiIjbqAARERERERG30RAsERERERFXaAhWulAPiIiIiIiIuI0KEBERERERcRsNwRIRERERcYEeRJg+1AMiIiIiIiJuowJERERERETcRkOwRERERERcoSFY6UI9ICIiIiIi4jYqQEREREREsimr1cqXX35JvXr1qFSpEp06deLEiRNpzh8fH8+nn35KvXr1qFy5Mu3bt+fAgQN3tEwVICIiIiIiLrDZDFny57+YMGECc+bMYejQocydOxeDwUCXLl2Ii4tLdf5Bgwbx448/8tFHHzF//nxy5cpFly5duH79usvLVAEiIiIiIpINxcXFMXXqVLp37079+vUJCQlhzJgxnD9/npUrVzrNf+rUKX788UeGDRvGo48+SsmSJfnkk08wm83s3bvX5eWqABERERERyYYOHjxIZGQktWrVSp4WEBBA+fLl2bp1q9P869evJyAggEceecRh/t9++43atWu7vF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4/d+4cAEFBQQ7TCxQoQFhYmNP8ly9f5uLFi2zdupWZM2dy9epVKlWqRO/evSlRooTL66seEBERERERV9iy6M9dio6OBnC61sPLy4vY2Fin+Q8fPgyAyWRixIgRjBkzhqioKNq2bcvFixddXq56QERERERE7mFp9XDcjre3N2C/FiTp/wFiY2Px8fFxmr9WrVps2bKFnDlzJk8bP348jz32GAsWLKBr164uLVc9ICIiIiIi2VDS0Kvw8HCH6eHh4QQGBqba5tbiAyBHjhwULlyY8+fPu7xcFSAiIiIiIi4w2LLmz90KCQnBz8+PzZs3J0+LiIhg//79hIaGOs0/a9YsatasSUxMTPK0GzducPz48Tu6MF0FiIiIiIhINmQ2m2nfvj2jR49m9erVHDx4kLfffpvAwEAaNmyIxWLhwoULyQXHY489hs1mo2/fvhw5coQ9e/bQvXt38uTJwwsvvODyclWAiIiIiIhkUz169KBFixYMGDCANm3aYDKZmDJlCmazmbCwMOrWrcuyZcsA+5CtGTNmEBkZSZs2bXjppZfw9/fn22+/dbiG5HYMNpvtP3Tc3Ftiwx7I7FW4r3kadE8DEfl3W2PjM3sV7nsDS9fO7FUQ+U9WxM3K7FVIU+lhYzJ7FVJ15L23M3sV7oh6QERERERExG1UgIiIiIiIiNtozIyIiIiIiAv+yx2n5Cb1gIiIiIiIiNuoABEREREREbfRECwREREREVdoCFa6UA+IiIiIiIi4jQoQERERERFxGw3BEhERERFxhYZgpQv1gIiIiIiIiNuoABEREREREbfRECwRERERERfoQYTpQz0gIiIiIiLiNipARERERETEbVSAiIiIiIiI26gAERERERERt1EBIiIiIiIibqO7YImIiIiIuEJ3wUoX6gERERERERG3UQEiIiIiIiJuoyFYIiIiIiIu0IMI04d6QERERERExG1UgIiIiIiIiNtoCJaIiIiIiCs0BCtdZKsC5IYtLrNX4b5mtcVm9irc9zzVaZmhlkcFZvYq3Pc+PtAos1fhvlcw4UBmr4KIyL/S0YyIiIiIiLhNtuoBERERERG5axqClS7UAyIiIiIiIm6jAkRERERERNxGQ7BERERERFygBxGmD/WAiIiIiIiI26gAERERERERt9EQLBERERERV2gIVrpQD4iIiIiIiLiNChAREREREXEbDcESEREREXGB7oKVPtQDIiIiIiIibqMCRERERERE3EZDsEREREREXKEhWOlCPSAiIiIiIuI2KkBERERERMRtNARLRERERMQVGoKVLtQDIiIiIiIibqMCRERERERE3EZDsEREREREXKAHEaYP9YCIiIiIiIjbqAARERERERG30RAsERERERFXaAhWulAPiIiIiIiIuI0KEBERERERcRsNwRIRERERcYWGYKUL9YCIiIiIiIjbqAARERERERG30RAsEREREREX6EGE6UM9ICIiIiIi4jYqQERERERExG00BEtERERExBUagpUu1AMiIiIiIiJuowJERERERETcRkOwRERERERcoLtgpQ/1gIiIiIiIiNuoABEREREREbfRECwREREREVdoCFa6UA+IiIiIiIi4jQoQERERERFxGw3BEhERERFxhYZgpQv1gIiIiIiIiNuoABEREREREbdRASIiIiIiIm6ja0BERERERFxgyOwVuE+oB0RERERERNxGBYiIiIiIiLiNhmC5yaYtJiZP8eTYCSO5ctl44bkEOrSNx5BGX15cHEyZ4cnylR5cvWagWFErbVvF81RDi8N8jZv5cPmKcx350/wo8ubJPveK27TFxNdTzBxPzPf55+Jpf5t8p84ws+KWfNu0iufJhgkO8zVpliPVfBfPj8xW+QJs3GJkYuJ3OHfid7hj24R/zfjrGZ78utLEtWsGihW10a5VPE+n+A4fP2lg3CRPtu8y4eEBVSpaeOu1eIILZa98j2xLYPXMGC6cspIjwED1Z8zUa2nGkEbAFouNDfPj2LEynuuXrOQtZKReKy8eesTTYb4LpyysmBrL8T0JGD0MFK9g4qnO3uQJyn7nnx7OX4o3QxrwgH9+rsRGMe/EVqb8ve5f29QrUIZuZR6ldEBBrsVFsSpsP18eXEW0JT55nuJ++ehV7klC8xYnwWZl+6XjjN6/nDNRVzJ6kzJV6FOVefmj1hQtX5hrFyJYOmkFc4Yv+tc2DdrVo3W/Fwh6oCDhJy8yb/RifpnyGwAFi+Xnu2MT0my7fNrvjO5sf794haJ0GdGekJqliY+NZ/uK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Xr77beVkJBgdij5zrFjx+Tm5qbt27drx44dWT/PPPOM2aHlG6tWrdLIkSPVpUsXrVmzRk8//bSGDBmin3/+2ezQAAqQ3CQ5OVlz5szRgAEDFBwcLH9/f3300UeKiYnRpk2bzA4v34iJiVHfvn31ySefqHLlymaHk6+cPn1aO3fu1NixYxUUFKQqVaro3XffVdmyZbVmzRqzw8sXrl69Kl9fX02YMEF16tRR1apV1b9/f128eFG//PKL2eHlK9OnT1exYsXMDiNfOn78uCpXriwvLy+VKVMm68fd3d3s0PIFi8WiTz75RD169FCPHj1UsWJFvf7662rSpIn27NljdngABUhuEhkZqZs3b6pRo0ZZY56engoICNDevXtNjCx/OXLkiEqUKKHVq1erXr16ZoeTr5QsWVKfffaZateunTXm5OQki8Wi69evmxhZ/lGyZElNnTpV1atXlyRdunRJ4eHh8vb2VrVq1UyOLv/Yu3evFi1apMmTJ5sdSr507Ngx3q8OdOLECZ07dy7bilJ4eLheeeUVk6ICflfY7ADwuwsXLkiSypUrZzXu5eWl6OhoM0LKl5544gk98cQTZoeRL3l6eio4ONhqbN26dTpz5oyaNWtmUlT51+jRo7V48WK5urpq5syZKlq0qNkh5QtxcXEaNmyYRo0ale3zGPZx/PhxlSlTRi+88IJOnTqlihUrqn///mrevLnZoeULp06dkiQlJCSoT58+ioiIkK+vr1577TX+/w+5AisguUhm/7arq6vVuJubm5KSkswICfhbfvrpJ40cOVItW7bk//QcoEePHlq2bJnatWun119/XUeOHDE7pHxh3Lhxevjhh7kewUGSk5N16tQp3bhxQ4MHD9Znn32mOnXqqF+/ftq1a5fZ4eULN27ckCS98847atu2rebMmaOmTZuqf//+5Bi5AisguUhm72tycrJVH2xSUpKKFCliVljAfdm8ebPefvtt1atXT1OnTjU7nHwps4VlwoQJOnDggObPn68PPvjA5KjytpUrV2rfvn36+uuvzQ4l33J1ddXevXtVuHDhrBNutWvXVlRUlMLDw9W4cWOTI8z7XFxcJEl9+vRRhw4dJEm1atVSRESE5s6dS45hOlZAcpHMpf7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BADymLi4OI0cOVItW7ZU165ddeXKFcXExJgdFgAANqEAAYA8Zvz48bp9+7YmTpyogIAASbRhAQDyDgoQAMhD1q9frzVr1ui9995TqVKlsgoQLkQHAOQVFCAAkEdcvHhRY8eOVZcuXdSiRQtJUoUKFeTp6cl1IACAPIMCBADyiNGjR6tEiRIaPny41XitWrVowQIA5BkUIACQByxZskTff/+9PvzwQxUtWtTqsYCAAJ05c0Y3btwwKToAAGznZLFYLGYHAQAAAKBgYAUEAAAAgGEoQAAAAAAYhgIEAAAAgGEoQAAAAAAYhgIEAAAAgGEoQAAAAAAYhgIEAAAAgGEoQAAAAAAYhgIEAAAAgGEoQAAAAAAYhgIEAAAAgGEoQAAAAAAY5v8BmmYJh1kX3KMAAAAASUVORK5CYII=\n", - "text/plain": [ - "
" - ] - }, - "metadata": {}, - "output_type": "display_data" - } - ], - "source": [ - "# visual representation of grid search\n", - "# uses seaborn heatmap, could probably do this in matplotlib\n", - "import seaborn as sns\n", - "\n", - "sns.set()\n", - "\n", - "train_accuracy = np.zeros((len(eta_vals), len(lmbd_vals)))\n", - "test_accuracy = np.zeros((len(eta_vals), len(lmbd_vals)))\n", - "\n", - "for i in range(len(eta_vals)):\n", - " for j in range(len(lmbd_vals)):\n", - " CNN = CNN_keras[i][j]\n", - "\n", - " train_accuracy[i][j] = CNN.evaluate(X_train, Y_train)[1]\n", - " test_accuracy[i][j] = CNN.evaluate(X_test, Y_test)[1]\n", - "\n", - " \n", - "fig, ax = plt.subplots(figsize = (10, 10))\n", - "sns.heatmap(train_accuracy, annot=True, ax=ax, cmap=\"viridis\")\n", - "ax.set_title(\"Training Accuracy\")\n", - "ax.set_ylabel(\"$\\eta$\")\n", - "ax.set_xlabel(\"$\\lambda$\")\n", - "plt.show()\n", - "\n", - "fig, ax = plt.subplots(figsize = (10, 10))\n", - "sns.heatmap(test_accuracy, annot=True, ax=ax, cmap=\"viridis\")\n", - "ax.set_title(\"Test Accuracy\")\n", - "ax.set_ylabel(\"$\\eta$\")\n", - "ax.set_xlabel(\"$\\lambda$\")\n", - "plt.show()" - ] - }, - { - "cell_type": "markdown", - "id": "8f104706", - "metadata": {}, - "source": [ - "## The CIFAR01 data set\n", - "\n", - "The CIFAR10 dataset contains 60,000 color images in 10 classes, with\n", - "6,000 images in each class. The dataset is divided into 50,000\n", - "training images and 10,000 testing images. The classes are mutually\n", - "exclusive and there is no overlap between them." - ] - }, - { - "cell_type": "code", - "execution_count": 8, - "id": "665b4103", - "metadata": {}, - "outputs": [], - "source": [ - "import tensorflow as tf\n", - "\n", - "from tensorflow.keras import datasets, layers, models\n", - "import matplotlib.pyplot as plt\n", - "\n", - "# We import the data set\n", - "(train_images, train_labels), (test_images, test_labels) = datasets.cifar10.load_data()\n", - "\n", - "# Normalize pixel values to be between 0 and 1 by dividing by 255. \n", - "train_images, test_images = train_images / 255.0, test_images / 255.0" - ] - }, - { - "cell_type": "markdown", - "id": "34035c79", - "metadata": {}, - "source": [ - "## Verifying the data set\n", - "\n", - "To verify that the dataset looks correct, let's plot the first 25 images from the training set and display the class name below each image." - ] - }, - { - "cell_type": "code", - "execution_count": 10, - "id": "966ea558", - "metadata": {}, - "outputs": [ - { - "data": { - "image/png": "iVBORw0KGgoAAAANSUhEUgAAAxoAAAMqCAYAAAAFOjf/AAAAOXRFWHRTb2Z0d2FyZQBNYXRwbG90bGliIHZlcnNpb24zLjUuMSwgaHR0cHM6Ly9tYXRwbG90bGliLm9yZy/YYfK9AAAACXBIWXMAAA9hAAAPYQGoP6dpAAEAAElEQVR4nOz9eZxcZ3nmjd9nqb2qq3pftEuWZMmWd2xsA15IICFkwsCEMMMQID8IEALzCZmwvcm8ybwfJpkxy4Q42wzJsGQjC1swJGwGjC1jvG+yJVlbS63eu7r2OnWW3x/CXXVdT1ndNqWWB+7vP9Jdy3me85xnOafrup7biqIoEkVRFEVRFEVRlB5in+8KKIqiKIqiKIry44c+aCiKoiiKoiiK0nP0QUNRFEVRFEVRlJ6jDxqKoiiKoiiKovQcfdBQ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RBw1FURRFURRFUXqOPmgoiqIoiqIoitJz9EFDURRFURRFUZSeow8airLO6P4LyvlE+5+iKD9J6Jx3fvmJftCYnp6W//gf/6Ps27dPrr32WqnX66t/SVF+BL75zW/K+973vnUpa/fu3fJHf/RH61KW8n8H2v+U5yuf+9znZPfu3XLy5MnzXRXlxwTP8+T3f//35Z//+Z/Pd1VWOHnypOzevVs+97nPnfVzN998s7z//e9/Vt95vrJ+mzA/D/nUpz4lDzzwgNxyyy0yOjoqqVTqfFdJ+THnk5/85PmugvITjPY/RVF+UpidnZVPfvKT8vu///vnuyrPmltvvVWy2ez5rkZP+Il+0CgWizIyMiKveMUrzndVFEVRFEVRFEX27t17vqvQM35ipVM333yzfO5zn5OpqSnZvXu3vOENb5Ddu3fL3/3d38lNN90k1113nXzve98TEZE777xT/sN/+A9y5ZVXyjXXXCO/+Zu/KadPn4bjPfDAA/L6179eLrvsMrnxxhvlU5/6lLzpTW9a+elLUd7whjfIPffcI/fcc4/s3r1bvv/973ftc+9///vl5ptvhu92++l0YWFBPvjBD8p1110nl19+ubz+9a+X++677xnL/8M//EO58MIL5R//8R/P2Tkqz1+0/ynPF8IwlD/5kz+RG2+8US699FL5tV/7NVleXobPHDx4UN72trfJFVdcIVdccYW8853vlMnJSfhMsViU//Jf/otcd911sm/fPnnta18r+/fvh8/s3r1bbr31VnnNa14jV155pfzJn/zJOT8/5Uen0WjIRz7yEXnZy14mF198sVxxxRXy5je/WQ4cOCAisuo8dfLkSXnpS18qIiIf+MAH4LOr3dN97nOfk3379sl9990nr3nNa2Tfvn3y8pe/XL71rW/JkSNH5I1vfKNceuml8tM//dNy2223QR2OHTsm7373u+X666+Xyy67TN7whjd0nRdnZmbkbW97m1xyySVyww03yMc//nEJgnZ2+U7pVDempqbkPe95j1x99dVy6aWXyhvf+EZ5/PHHn0ULrx8/sQ8at956q9xwww0yPDwsn/3sZ+Xf/bt/JyIiH/vYx+R973ufvO9975PLLrtMvvjFL8qv/MqvyOjoqHz0ox+VD3zgA/LAAw/IL/3SL8nCwoKIiDz11FPypje9SUREPvrRj8q73vUu+V//63+dddFVfvL4f//f/1f27t0re/fulc9+9rNSqVRExOxza6FWq8nrXvc6ueuuu+Q3f/M35dZbb5VMJiNvectb5KmnnjI+/xd/8Rfyp3/6p/Jf/+t/Xenryk8W2v+U5wu33HKL/PEf/7G85jWvkVtvvVX6+/vlIx/5yMr7R48elde97nWysLAgf/AHfyAf+tCHZHJyUv79v//3K+tus9mUN77xjfLNb35TfuM3fkNuvfVWGRsbk7e85S3Gw8af/umfystf/nL56Ec/unLzqTy/ee973yv/+I//KL/6q78qf/mXfynvf//75eDBg/Ibv/EbazJ3j4yMyK233ioiIu94xztW/r+WezoREd/35T3veY+87nWvkz/5kz+RRCIh//k//2d5+9vfLjfeeKP84R/+oQwPD8v73vc+mZ6eFhGRw4cPy6tf/WqZnJyU3/7t35YPf/jDYlmWvPGNb5R77rkH6vdHf/RHMjAwsDIO/uzP/kw+/vGPr6ltFhcX5XWve5089thj8ju/8zvykY98RMIwlNe//vVd59/zzU+sdGrv3r0yMDAg8XhcLrvsMmk2myIi8rrXvU5+5md+RkTO/NXllltukeuuu04+9rGPrXz3iiuukFe84hXyl3/5l/Jbv/Vb8ud//ueSzWblE5/4xIrPY/v27fK6171u/U9Med5ywQUXrGguL7vsMvn+978vItjn1srnP/95mZyclC984Qty4YUXiojIVVddJa961avkBz/4gezYsWPls3/3d38nt9xyi/ze7/2evPa1r+3R2Sj/t6H9T3k+UCqV5DOf+Yz88i//srzrXe8SEZEXv/jFMjMzI3fccYeInPlDYDKZlE9+8pMrffbaa6+Vn/qpn5JPfOIT8r73vU+++MUvyhNPPCF///d/L5deeqmIiLzkJS+RN7zhDfLhD39Y/umf/mmlzEsuuUR+9Vd/dZ3PVHmueJ4n1WpVfud3fmdF2n711VdLtVqVP/iDP5C5ublVjxGPx2XPnj0iIrJ582bZu3fvmu/pRM7c/7397W+XX/zFXxSRM/32Pe95j7zxjW+UN7/5zSIiMjQ0J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AA3vGOd5hsuYnD8kHjyiuvxNe//nX8xV/8BT772c/i6quvxlNPPYXLL798ViabgYGBSbnJu971rsn/f+tb38LFF1+MefPm4YYbbsD73/9+PPjgg3jzm9+MvXv3Tn6/0WjgiiuuwPnnn49PfepTyGaz+N//+3/jL//yL/Hyl78c//iP/4j+/n5cddVV2LFjBwBg7dq1OO+887B582b8zd/8Df7hH/4BnufhwgsvxH333Ufb90//9E/o6enBJz/5SbzhDW/Apz/9aXziE5+YVdsMDg7i/PPPx6OPPooPfvCD+PjHP44oivC2t70NzzzzzKyWYRxefPe738UjjzyCj370o7jyyivx05/+dFrp3K233opVq1bhn/7pn/D6178epVIJb3/72/HEE0/gQx/6EK655hp87Wtfw4MPPjiHe2Ecztx+++14+umn8dGPfhTXXHMNHn74YVx++eUAZj8uhmGIT3/60/jwhz+Mv/7rv8aKFStwySWXoFQq4WMf+xg+9alPoaurC5deeunkQ8z69etx/vnnY+/evfjoRz+K6667Dps3b8Zb3vIWWrbxwmN8fBx//ud/ju7ubnziE5/AjTfeiHK5jP/xP/4HxsbGAADbt2/Hv/zLv+B//a//hU984hOI4xjvec97pu07jz/+OG688Ua8+93vxvXXX4/h4WFccMEF2Llz51ztmvE7yg033IDrrrsO55xzDm6++Wb82Z/9GW688UZ86lOfwq233oprrrkGr3zlK/HP//zPuP7665FOp/G+970P27Ztw+rVqyf/8HfNNdfgb//2bw/x3hw+HHbSqVqthomJCXzwgx/EH//xHwMATj/9dExMTOCjH/0odu/ePeMyMpkMjj32WAD7pCfHHXccoijC9ddfj7POOgs33njj5GdPOeUU/PEf/zE++9nP4n3vex8AIIoi/OVf/iX+7M/+DMA+g88VV1yBCy+8EBdddBEAoK+vD294wxvwyCOPYP78+bjpppuQTqfx+c9/Hu3t7QD26Udf+9rX4vrrr8fXvva1yXWeeeaZ+Pu//3sAwEtf+lKMj4/j85//PC6++GJ0dnZOu2+33HILhoeH8aUvfQmLFi0CALzsZS/DH//xH+Mf//EfZ/3AYhw+dHR04DOf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+eeey6+8IUv4AMf+AD+7M/+DE8//TQ++9nP0kF+zitx991348gjj8RJJ52EK664Au9///tx+eWX47/9t/+GoaEh3HTTTejs7Ez8i9uB8O53vxs///nP8Y53vAN/8Rd/gUwmgy9+8YvYvHkzPvOZz9Bnv//972PevHk466yzcOedd+IrX/kK/tf/+l+Jci3lne98J771rW/hne98Jy6++GJ0d3fj9ttvx1e/+lXSRhu/O+zZswfvec97cMEFF2DDhg244YYbcPbZZ+PMM8+c1V9LXv/61+Pzn/883v3ud+Pyyy9HW1sbbr75ZgsNMmbE87znPS4ed9xxyOVyuPLKK/Ge97wHfX19uOuuu/D4449PTvN46aWX4vzzz8cll1yCt7zlLchms/jKV76CH/7whzZxxQucU045BVEU4bLLLsNf/MVfoFgs4rvf/S7Gxsbw6le/Gt/85jef13LjOMall16Kv/7rv0YQBLjpppvQ0dFh040a09LT04N3vOMduOWWW5DJZPDiF78YDz/8ML74xS/iyiuvxBe/+EXceuutmD9/Pjo6OnDnnXfilltuAbBPsg5M3Xf+9Kc/RWdnJ4455phDtj+HE4fdg8YRRxyBj3/847jpppvwrne9C52dnTj55JPxhS98ARdccAHuv/9+vO1tb8NVV12FL3zhC/j+97+P1atX46abbsL5558/uZy2tjZcdNFF+MpXvoKf/vSn+MUvfoHzzjsPxWIR//zP/4zLLrsMbW1teOlLX4orrrgC/f39v9V2H3300fj3f/933HDDDfjABz4Az/Nw4okn4vOf/zxe9KIX0WevvvpqfO9738PnPvc59Pf34/3vfz8uvPDCWa1n3rx5+PKXv4yPf/zjuPbaa1GtVrFs2TJcd911eOMb3/hb7YNxaHjTm96ESqWCyy67DJlMBn/6p3+K973vfZN65JnIZDK45ZZb8JGPfATXXXcdPM/Dm970JixZssSmEDVm5PmOi9lsFp/97Gfx8Y9/HNdddx1GR0exbNkyfOhDH8J5550HADjmmGNw66234sYbb8SVV16JOI6xcuVKfPKTn9zvrEHGC4OBgQF85jOfwT/+4z/i//yf/4NyuYyjjz4a//RP/4QXv/jFz/tBY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euFj/Mw4H7rrrLpIg/9d//RcajQbOOOOMWX3/xS9+MbZs2YKHH3548rXBwUE89NBDrd5U43ecZsnd/igWixgaGkK1Wp187Ve/+hV95kUvehE2b96MJ598cvK1Wq2G97znPfjqV786+Vp/fz88z8O1116LwcFBXH/99S3Yi98tXnAPGsViEZdeein+/d//Hf/wD/+AO++8E9dddx09aFx66aXYtGkTLrnkEvzwhz/EHXfcgfe85z34zne+M6nHO++887Bw4UJcdNFF+MY3voF77rkHN9xwA2688UYMDAyQHtow9ofnebjiiitw11134fLLL8fPfvYzfPOb38RFF12Ezs7OxL8EP8dxxx2HXC6HK6+8Et/5zndw77334sYbb8Tjjz+O17zmNQBm15eNFy7W/4zDgT179uA973kP7rrrLvz7v/87rrnmGpx99tk488wzZ/X917/+9Vi5ciXe/e5345vf/CZ++MMf4n/+z/+JKIoO8pYbv2t0dHRg/fr1uPvuu/crzTv33HNRrVbxgQ98APfccw++8IUv4J//+Z/pD8jnnXcelixZgne961341re+hTvuuAN/9Vd/hUqlkphGv3LlSlx44YX4yle+gl/+8pcHbf8OR16Qv11fcsklKBQKuOWWW3DLLbdgzZo1uOqqq3DttdcCAI455hjceuutuPHGG3HllVcijmOsXLkSn/zkJydN5IVCAbfeeis+/vGP4/rrr8fY2BgWLVqE9773vbj44osP4d4Zv2ucd955KBaL+Od//mdcdtllaGtrw0tf+lJcccUV5B1SstksPvvZz+LjH/84rrvuOoyOjmLZsmX40Ic+hPPOOw/A7Pqy8cLG+p9xqHnTm96ESqWCyy67DJlMBn/6p3+K973vffA8b1bfz2QyuOWWW/CRj3wE1113HTzPw5ve9CYsWbLEplE2iLe97W145JFH8D//5//E3//93yd+5uyzz8ZVV12FL3zhC/j+97+P1atX46abbsL5558/+Zm2tjZ88YtfxMc+9jFcd911aDQaOOmkk/CFL3xhvyGT7373u/Hd734Xf/M3f4Nvf/vbyGazB2UfDze8OI7jQ70RhmEYhmEYhmH8fvGCk04ZhmEYhmEYhnHwsQcNwzAMwzAMwzB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27cMDDzww/7epqSncf//9na6qcYKxfv16DA0N4e///u/p73v37sX999+Ps88+GwCwfft2/PSnP6V1++GHH8a+ffuWtL4vRE64B42enh489dRT2LFjx7P+LPuqV70KtVoNH/rQh/Dzn/8cX/3qV/G5z32OFtHLL78cq1evxn/5L/8Ft956K26//Xb8wR/8AarVauS2jps2bcLv/d7v4W/+5m9w1113HbPzM17YWP8zXqj09/fjrW99K77yla/gU5/6FHbs2IH/83/+D772ta/hmmuuwcqVK3HLLbfgBz/4AXbs2IEbbrgBn/zkJwFg3k23u7sbAPDjH/8YjzzyyHE7F+PFxcTEBN773vfijjvuwF/91V/h+uuvx0UXXYQLLrhgUZ9/3eteh02bNuHqq6/Gd77zHfzwhz/EO97xjvkHYMN4vvi+j/e///2444478L73vQ8/+clP8J3vfAdvf/vb0dvbi7e//e0AgHe/+92YnZ3F7//+7+NHP/oRbr31Vlx11VXwPA+e5x3nszi+nHAPGm9+85uRSCTwjne8A9VqNfI9F110Ea699lrce++9eMc73oH/+3//L2688Ua60evq6sLXvvY1bNu2DR/96Efxh3/4h6jVavjqV7/6rAZDV199NVasWIH//t//Oz31GicO1v+MFzIf/OAH8YEPfADf//738c53vhPf/va38aEPfQhXXnkl/uIv/gLLli3Dddddhz/6oz/C/fffj5tuugkbNmzA3XffDQA4+eSTcdlll+GWW27Bf/2v//U4n43xYuGNb3wjBgcHcdVVV+Ezn/kMfvM3fxM33njjom/Qkskkbr75Zmzfvh0f/ehH8aEPfQgXXHABXvWqVx3jmhsnApdffjk++9nPYvfu3bjqqqvwp3/6p9i2bRu++c1vzmsw1q5diy9+8Yuo1Wr4gz/4A3zqU5/CO97xDgwNDSGXyx3nMzi+eKGp+AzDMAzDMAzjebFjxw4kEgmce+6583+bmZnBRRddhGuuuWbezPRExLa3NQzDMAzDMIznyYMPPojPfvazeP/734/TTz8d09PT+NKXvoTu7m5cdtllx7t6xxV70DAMwzAMwzCM58mVV16Jer2Ov/7rv8bo6Ciy2Sxe9rKX4eMf//izb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GgIf//3f09/37t3L+6//36cffbZAIDt27fjpz/96XyePXDY18UMUI1/C9b/jKXgjjvuoBT4H/zgB2g2mzjvvPMW9fnzzz8f+/btwwMPPDD/t6mpKdx///2druqLkhPuF41cLof3vOc9+PSnP41MJoPzzz8fP/nJT+hB4z3veQ/e9KY34V3vehd+53d+B6lUCn/zN3+DH/7wh/jsZz8LALj88svxta99DW9/+9vx7ne/G8uXL8cdd9yBz3/+83jLW96CRCJxvE7ReBHS39+Pt771rbj55puRTCZx/vnn44EHHsDXvvY1XHPNNfja176GW265BSMjI+jp6cHPfvYz3HzzzQAw76bb3d0NAPjxj3+M3t5enHLKKcftfIyXBr7v4/3vfz/+23/7b3jf+943v+vPjTfeiN7e3vlffd/97nfj+9//Pn7/938fV155JYrFIj7zmc/A8zx4nnecz8J4sWL9z1gKJiYm8N73vhdXXHEFdu3ahU9+8pO46KKLcMEFFywqa+B1r3sdvvKVr+Dqq6/G+973PnR1deGmm26a/xLwROeEe9AAgHe9613IZrO4+eabcfPNN2Pbtm249tpr8cd//McAgFNOOQW33HILPvWpT+Gaa65BGIbYtGkT/vf//t/zIvJsNotbbrkFf/7nf44bbrgBs7OzWLlyJT7wgQ/gyiuvPI5nZ7xY+eAHP4jBwUH89V//Nb70pS9h1apV+NCHPoTf/d3fxYUXXoiPfvSjuO6665BMJnHSSSfhpptuwsc+9jHcfffduOKKK3DyySfjsssuwy233ILbb78d3/ve9473KRkvAS6//HLkcjl87nOfw1VXXYWuri68/OUvx/vf//75HPi1a9fii1/8Iv7sz/4Mf/AHf4CBgQG8613vwk033YRcLnecz8B4MWP9zzjWvPGNb0S1WsVVV12FZDKJ3/zN38QHP/jBRT+kJpNJ3HzzzfjYxz6Gj370o/A8D2984xuxevXqyJS+E40T0kfDMAzD6Bw7duxAIpHAueeeO/+3mZkZXHTRRbjmmmvmzSQN41hg/c8wXrickL9oGIZhGJ3jwQcfxGc/+1m8//3vx+mnn47p6Wl86UtfQnd3Ny677LLjXT3jJY71P8N44WIPGoZhGMa/iSuvvBL1eh1//dd/jdHRUWSzWbzsZS/Dxz/+8WfdstkwOoX1P8N44WKpU4ZhGIZhGIZhdJwTbntbwzAMwzAMwzCOPfagYRiGYRiGYRhGx7EHDcMwDMMwDMMwOo49aBiGYRiGYRiG0XHsQcMwDMMwDMMwjI5jDxqGYRiGYRiGYXQce9AwDMMwDMMwDKPj2IOGYRiGYRiGYRgd5/8PMCuQ0w15/v4AAAAASUVORK5CYII=\n", - "text/plain": [ - "
" - ] - }, - "metadata": {}, - "output_type": "display_data" - } - ], - "source": [ - "class_names = ['airplane', 'automobile', 'bird', 'cat', 'deer',\n", - " 'dog', 'frog', 'horse', 'ship', 'truck']\n", - "\n", - "plt.figure(figsize=(10,10))\n", - "for i in range(25):\n", - " plt.subplot(5,5,i+1)\n", - " plt.xticks([])\n", - " plt.yticks([])\n", - " plt.grid(False)\n", - " plt.imshow(train_images[i], cmap=plt.cm.binary)\n", - " # The CIFAR labels happen to be arrays, \n", - " # which is why you need the extra index\n", - " plt.xlabel(class_names[train_labels[i][0]])\n", - "plt.show()" - ] - }, - { - "cell_type": "markdown", - "id": "8685c2f8", - "metadata": {}, - "source": [ - "## Set up the model\n", - "\n", - "The 6 lines of code below define the convolutional base using a common pattern: a stack of Conv2D and MaxPooling2D layers.\n", - "\n", - "As input, a CNN takes tensors of shape (image_height, image_width, color_channels), ignoring the batch size. If you are new to these dimensions, color_channels refers to (R,G,B). In this example, you will configure our CNN to process inputs of shape (32, 32, 3), which is the format of CIFAR images. You can do this by passing the argument input_shape to our first layer." - ] - }, - { - "cell_type": "code", - "execution_count": 11, - "id": "30f87291", - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "Model: \"sequential_49\"\n", - "_________________________________________________________________\n", - " Layer (type) Output Shape Param # \n", - "=================================================================\n", - " conv2d_49 (Conv2D) (None, 30, 30, 32) 896 \n", - " \n", - " max_pooling2d_49 (MaxPoolin (None, 15, 15, 32) 0 \n", - " g2D) \n", - " \n", - " conv2d_50 (Conv2D) (None, 13, 13, 64) 18496 \n", - " \n", - " max_pooling2d_50 (MaxPoolin (None, 6, 6, 64) 0 \n", - " g2D) \n", - " \n", - " conv2d_51 (Conv2D) (None, 4, 4, 64) 36928 \n", - " \n", - "=================================================================\n", - "Total params: 56,320\n", - "Trainable params: 56,320\n", - "Non-trainable params: 0\n", - "_________________________________________________________________\n" - ] - } - ], - "source": [ - "model = models.Sequential()\n", - "model.add(layers.Conv2D(32, (3, 3), activation='relu', input_shape=(32, 32, 3)))\n", - "model.add(layers.MaxPooling2D((2, 2)))\n", - "model.add(layers.Conv2D(64, (3, 3), activation='relu'))\n", - "model.add(layers.MaxPooling2D((2, 2)))\n", - "model.add(layers.Conv2D(64, (3, 3), activation='relu'))\n", - "\n", - "# Let's display the architecture of our model so far.\n", - "\n", - "model.summary()" - ] - }, - { - "cell_type": "markdown", - "id": "b7c68c02", - "metadata": {}, - "source": [ - "You can see that the output of every Conv2D and MaxPooling2D layer is a 3D tensor of shape (height, width, channels). The width and height dimensions tend to shrink as you go deeper in the network. The number of output channels for each Conv2D layer is controlled by the first argument (e.g., 32 or 64). Typically, as the width and height shrink, you can afford (computationally) to add more output channels in each Conv2D layer." - ] - }, - { - "cell_type": "markdown", - "id": "a3eefda1", - "metadata": {}, - "source": [ - "## Add Dense layers on top\n", - "\n", - "To complete our model, you will feed the last output tensor from the\n", - "convolutional base (of shape (4, 4, 64)) into one or more Dense layers\n", - "to perform classification. Dense layers take vectors as input (which\n", - "are 1D), while the current output is a 3D tensor. First, you will\n", - "flatten (or unroll) the 3D output to 1D, then add one or more Dense\n", - "layers on top. CIFAR has 10 output classes, so you use a final Dense\n", - "layer with 10 outputs and a softmax activation." - ] - }, - { - "cell_type": "code", - "execution_count": 13, - "id": "725ce3a1", - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "Model: \"sequential_49\"\n", - "_________________________________________________________________\n", - " Layer (type) Output Shape Param # \n", - "=================================================================\n", - " conv2d_49 (Conv2D) (None, 30, 30, 32) 896 \n", - " \n", - " max_pooling2d_49 (MaxPoolin (None, 15, 15, 32) 0 \n", - " g2D) \n", - " \n", - " conv2d_50 (Conv2D) (None, 13, 13, 64) 18496 \n", - " \n", - " max_pooling2d_50 (MaxPoolin (None, 6, 6, 64) 0 \n", - " g2D) \n", - " \n", - " conv2d_51 (Conv2D) (None, 4, 4, 64) 36928 \n", - " \n", - " flatten_49 (Flatten) (None, 1024) 0 \n", - " \n", - " dense_98 (Dense) (None, 64) 65600 \n", - " \n", - " dense_99 (Dense) (None, 10) 650 \n", - " \n", - "=================================================================\n", - "Total params: 122,570\n", - "Trainable params: 122,570\n", - "Non-trainable params: 0\n", - "_________________________________________________________________\n" - ] - } - ], - "source": [ - "model.add(layers.Flatten())\n", - "model.add(layers.Dense(64, activation='relu'))\n", - "model.add(layers.Dense(10))\n", - "#Here's the complete architecture of our model.\n", - "\n", - "model.summary()" - ] - }, - { - "cell_type": "markdown", - "id": "2f0e86ba", - "metadata": {}, - "source": [ - "As you can see, our (4, 4, 64) outputs were flattened into vectors of shape (1024) before going through two Dense layers." - ] - }, - { - "cell_type": "markdown", - "id": "9fe3e5a8", - "metadata": {}, - "source": [ - "## Compile and train the model" - ] - }, - { - "cell_type": "code", - "execution_count": 14, - "id": "904da8d6", - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "Epoch 1/10\n", - "1563/1563 [==============================] - 28s 15ms/step - loss: 1.5353 - accuracy: 0.4394 - val_loss: 1.2184 - val_accuracy: 0.5616\n", - "Epoch 2/10\n", - "1563/1563 [==============================] - 18s 12ms/step - loss: 1.1560 - accuracy: 0.5909 - val_loss: 1.0712 - val_accuracy: 0.6214\n", - "Epoch 3/10\n", - "1563/1563 [==============================] - 20s 13ms/step - loss: 1.0176 - accuracy: 0.6411 - val_loss: 1.0012 - val_accuracy: 0.6527\n", - "Epoch 4/10\n", - "1563/1563 [==============================] - 18s 12ms/step - loss: 0.9234 - accuracy: 0.6788 - val_loss: 0.9674 - val_accuracy: 0.6599\n", - "Epoch 5/10\n", - "1563/1563 [==============================] - 18s 12ms/step - loss: 0.8524 - accuracy: 0.7033 - val_loss: 0.8982 - val_accuracy: 0.6890\n", - "Epoch 6/10\n", - "1563/1563 [==============================] - 18s 11ms/step - loss: 0.7966 - accuracy: 0.7203 - val_loss: 0.9145 - val_accuracy: 0.6835\n", - "Epoch 7/10\n", - "1563/1563 [==============================] - 18s 11ms/step - loss: 0.7483 - accuracy: 0.7407 - val_loss: 0.9275 - val_accuracy: 0.6849\n", - "Epoch 8/10\n", - "1563/1563 [==============================] - 17s 11ms/step - loss: 0.7049 - accuracy: 0.7532 - val_loss: 0.9460 - val_accuracy: 0.6781\n", - "Epoch 9/10\n", - "1563/1563 [==============================] - 21s 13ms/step - loss: 0.6663 - accuracy: 0.7696 - val_loss: 0.8528 - val_accuracy: 0.7078\n", - "Epoch 10/10\n", - "1563/1563 [==============================] - 19s 12ms/step - loss: 0.6297 - accuracy: 0.7788 - val_loss: 0.8747 - val_accuracy: 0.7032\n" - ] - } - ], - "source": [ - "model.compile(optimizer='adam',\n", - " loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True),\n", - " metrics=['accuracy'])\n", - "\n", - "history = model.fit(train_images, train_labels, epochs=10, \n", - " validation_data=(test_images, test_labels))" - ] - }, - { - "cell_type": "markdown", - "id": "98cf0684", - "metadata": {}, - "source": [ - "## Finally, evaluate the model" - ] - }, - { - "cell_type": "code", - "execution_count": 15, - "id": "b040f2e9", - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "313/313 - 2s - loss: 0.8747 - accuracy: 0.7032 - 2s/epoch - 5ms/step\n", - "0.7031999826431274\n" - ] - }, - { - "data": { - "image/png": "iVBORw0KGgoAAAANSUhEUgAAA+0AAAPlCAYAAAAXFAx+AAAAOXRFWHRTb2Z0d2FyZQBNYXRwbG90bGliIHZlcnNpb24zLjUuMSw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tKDG7D58fja9gVYOESkbHAQAAAK6ax+ORx1Fg3C+Pp1h5X3jhGQ0bNrjIsZMn03XTTe20efOP+uyzT/TQQwN0yy036tZbO2jkyOFKTU254vfn5Ml0Pfvs/6h3727q1Ok63X13L7311hy53W7vOSkpe/TnP49Q164d1bt3N7366guy2Wzexz/88H3173+3brnlRg0ceI/WrPlcknTixM/q0CFJW7ZsLvKcHTok6fPPP5UkLVjwlh57bIimTp2kbt066fXXX5GkS75Op9OpBQveUr9+vdWly40aMmSgfvjhe0nSQw8N0Isv/rXIc/7ww/e6+eb2ysrKuuL36nIFlfgzoNxKTkmXJCU1rCyz2WRwGgAAAODqeDwe5X3ygtzp+w3LYIm/VmF3TJLJdHn/vr7ttts1evSjSks7pho1EiRJa9euUlxcZeXknNO0aS9pwoTJatWqjTIyMjRz5mt6+eVntWjR0ivKN2HCWEVHR2v69NkKD6+gjRu/08yZ09S4cRN17HizTpz4WaNGDVeHDp301luLlJubqxde+Ktee+1FPf30c1q6dIkWLPibxowZrzZt2mrTpo168cW/KiYmRjVq1LysDDt2bNc99zTRokXvye126+uvv7zk65w163V98cU6jR37pBITG2nVqpWaOHGcFi58Tz173qH58+dp3LgnFRISKklavfoz3XhjR1WqVOmK3qfiYKUdJaJw1/jTkhiNBwAAQNlhUmAtRrVq1UbXXFNda9eu8h5bu3aVevTopUqVovXkk1N02223q2rVamrSpKl6975LBw5c2Q8lCgry1b17Tz355BRde21DVa9eQ/363a+4uMre7/nJJ8tVsWKkJk9+RnXr1lezZi301FNTVLNmLUnSBx8s1T339Ncdd/RR9eo1dPfd9+iRR0bK5XL/0VNf5OGHH1H16jWUkFBTUVFRf/g68/Jy9emnKzR06GPq0qWrqlevoaFDH9X99w9UXl6eune/TU6nQ99885UkKTc3R99++5V69rzjit6n4mKlHSVi16FM2Qqcioqw6toalYyOAwAAAFw1k8mksDsmSU77ZZ0fFGSW01m8snnpb2q97FV2qTBzjx69tHbtag0ZMlz79qXq4MEDev75V1WzZi0dPnxI77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BLliwxOAkAAJC4px0AAAAAAL9FaQcAAAAAwE8xHg8AAAAAgJ9ipR0AAAAAAD9FaQcAAAAAwE9R2gEAAAAA8FOUdgAAAAAA/BSlHQAAAAAAP0VpBwAAAADAT1HaAQAAAADwU5R2AAAAAAD8FKUdAAAAAAA/9X9QQ3a3Ryf0BQAAAABJRU5ErkJggg==\n", - "text/plain": [ - "
" - ] - }, - "metadata": {}, - "output_type": "display_data" - } - ], - "source": [ - "plt.plot(history.history['accuracy'], label='accuracy')\n", - "plt.plot(history.history['val_accuracy'], label = 'val_accuracy')\n", - "plt.xlabel('Epoch')\n", - "plt.ylabel('Accuracy')\n", - "plt.ylim([0.5, 1])\n", - "plt.legend(loc='lower right')\n", - "\n", - "test_loss, test_acc = model.evaluate(test_images, test_labels, verbose=2)\n", - "\n", - "print(test_acc)" - ] - }, - { - "cell_type": "markdown", - "id": "837aed5a", - "metadata": {}, - "source": [ - "## Building our own CNN code\n", - "\n", - "Here we present a flexible and readable python code for a CNN\n", - "implemented with NumPy. We will present the code, showcase how to use\n", - "the codebase and fit a CNN that yields a 99% accuracy on the 28x28\n", - "MNIST dataset within reasonable time.\n", - "\n", - "The CNN is compatible with all schedulers, cost functions and\n", - "activation functions discussed in constructing our neural network\n", - "codes.\n", - "\n", - " The CNN code consists of different types of Layer classes, including\n", - "Convolution2DLayer, Pooling2DLayer, FlattenLayer, FullyConnectedLayer\n", - "and OutputLayer, which can be added to the CNN object using the\n", - "interface of the CNN class. This allows you to easily construct your\n", - "own CNN, as well as allowing you to get used to an interface similar\n", - "to that of TensorFlow which is used for real world applications. \n", - "\n", - "Another important feature of this code is that it throws errors if\n", - "unreasonable decisions are made (for example using a kernel that is\n", - "larger than the image, not using a FlattenLayer, etc), and provides\n", - "the user with an informative error message." - ] - }, - { - "cell_type": "markdown", - "id": "af874397", - "metadata": {}, - "source": [ - "### List of contents:\n", - "\n", - "1. Schedulers\n", - "\n", - "2. Activation Functions\n", - "\n", - "3. Cost Functions \n", - "\n", - "4. Convolution\n", - "\n", - "5. Layers\n", - "\n", - "6. CNN \n", - "\n", - "7. Some final remarks" - ] - }, - { - "cell_type": "markdown", - "id": "32d09325", - "metadata": {}, - "source": [ - "### Schedulers\n", - "\n", - "The code below shows object oriented implementations of the Constant,\n", - "Momentum, Adagrad, AdagradMomentum, RMS prop and Adam schedulers. All\n", - "of the classes belong to the shared abstract Scheduler class, and\n", - "share the update_change() and reset() methods allowing for any of the\n", - "schedulers to be seamlessly used during the training stage, as will\n", - "later be shown in the fit() method of the neural\n", - "network. Update_change() only has one parameter, the gradient\n", - "($\\delta^{l}_{j}a^{l-1}_k$), and returns the change which will be\n", - "subtracted from the weights. The reset() function takes no parameters,\n", - "and resets the desired variables. For Constant and Momentum, reset\n", - "does nothing." - ] - }, - { - "cell_type": "code", - "execution_count": 14, - "id": "8b746f30", - "metadata": {}, - "outputs": [], - "source": [ - "import autograd.numpy as np\n", - "\n", - "class Scheduler:\n", - " \"\"\"\n", - " Abstract class for Schedulers\n", - " \"\"\"\n", - "\n", - " def __init__(self, eta):\n", - " self.eta = eta\n", - "\n", - " # should be overwritten\n", - " def update_change(self, gradient):\n", - " raise NotImplementedError\n", - "\n", - " # overwritten if needed\n", - " def reset(self):\n", - " pass\n", - "\n", - "\n", - "class Constant(Scheduler):\n", - " def __init__(self, eta):\n", - " super().__init__(eta)\n", - "\n", - " def update_change(self, gradient):\n", - " return self.eta * gradient\n", - " \n", - " def reset(self):\n", - " pass\n", - "\n", - "\n", - "class Momentum(Scheduler):\n", - " def __init__(self, eta: float, momentum: float):\n", - " super().__init__(eta)\n", - " self.momentum = momentum\n", - " self.change = 0\n", - "\n", - " def update_change(self, gradient):\n", - " self.change = self.momentum * self.change + self.eta * gradient\n", - " return self.change\n", - "\n", - " def reset(self):\n", - " pass\n", - "\n", - "\n", - "class Adagrad(Scheduler):\n", - " def __init__(self, eta):\n", - " super().__init__(eta)\n", - " self.G_t = None\n", - "\n", - " def update_change(self, gradient):\n", - " delta = 1e-8 # avoid division ny zero\n", - "\n", - " if self.G_t is None:\n", - " self.G_t = np.zeros((gradient.shape[0], gradient.shape[0]))\n", - "\n", - " self.G_t += gradient @ gradient.T\n", - "\n", - " G_t_inverse = 1 / (\n", - " delta + np.sqrt(np.reshape(np.diagonal(self.G_t), (self.G_t.shape[0], 1)))\n", - " )\n", - " return self.eta * gradient * G_t_inverse\n", - "\n", - " def reset(self):\n", - " self.G_t = None\n", - "\n", - "\n", - "class AdagradMomentum(Scheduler):\n", - " def __init__(self, eta, momentum):\n", - " super().__init__(eta)\n", - " self.G_t = None\n", - " self.momentum = momentum\n", - " self.change = 0\n", - "\n", - " def update_change(self, gradient):\n", - " delta = 1e-8 # avoid division ny zero\n", - "\n", - " if self.G_t is None:\n", - " self.G_t = np.zeros((gradient.shape[0], gradient.shape[0]))\n", - "\n", - " self.G_t += gradient @ gradient.T\n", - "\n", - " G_t_inverse = 1 / (\n", - " delta + np.sqrt(np.reshape(np.diagonal(self.G_t), (self.G_t.shape[0], 1)))\n", - " )\n", - " self.change = self.change * self.momentum + self.eta * gradient * G_t_inverse\n", - " return self.change\n", - "\n", - " def reset(self):\n", - " self.G_t = None\n", - "\n", - "\n", - "class RMS_prop(Scheduler):\n", - " def __init__(self, eta, rho):\n", - " super().__init__(eta)\n", - " self.rho = rho\n", - " self.second = 0.0\n", - "\n", - " def update_change(self, gradient):\n", - " delta = 1e-8 # avoid division ny zero\n", - " self.second = self.rho * self.second + (1 - self.rho) * gradient * gradient\n", - " return self.eta * gradient / (np.sqrt(self.second + delta))\n", - "\n", - " def reset(self):\n", - " self.second = 0.0\n", - "\n", - "\n", - "class Adam(Scheduler):\n", - " def __init__(self, eta, rho, rho2):\n", - " super().__init__(eta)\n", - " self.rho = rho\n", - " self.rho2 = rho2\n", - " self.moment = 0\n", - " self.second = 0\n", - " self.n_epochs = 1\n", - "\n", - " def update_change(self, gradient):\n", - " delta = 1e-8 # avoid division ny zero\n", - "\n", - " self.moment = self.rho * self.moment + (1 - self.rho) * gradient\n", - " self.second = self.rho2 * self.second + (1 - self.rho2) * gradient * gradient\n", - "\n", - " moment_corrected = self.moment / (1 - self.rho**self.n_epochs)\n", - " second_corrected = self.second / (1 - self.rho2**self.n_epochs)\n", - "\n", - " return self.eta * moment_corrected / (np.sqrt(second_corrected + delta))\n", - "\n", - " def reset(self):\n", - " self.n_epochs += 1\n", - " self.moment = 0\n", - " self.second = 0" - ] - }, - { - "cell_type": "markdown", - "id": "d8f99677", - "metadata": {}, - "source": [ - "### Usage of schedulers\n", - "\n", - "To initalize a scheduler, simply create the object and pass in the necessary parameters such as the learning rate and the momentum as shown below. As the Scheduler class is an abstract class it should not called directly, and will raise an error upon usage." - ] - }, - { - "cell_type": "code", - "execution_count": 15, - "id": "4bd66798", - "metadata": {}, - "outputs": [], - "source": [ - "momentum_scheduler = Momentum(eta=1e-3, momentum=0.9)\n", - "adam_scheduler = Adam(eta=1e-3, rho=0.9, rho2=0.999)" - ] - }, - { - "cell_type": "markdown", - "id": "8fdac498", - "metadata": {}, - "source": [ - "Here is a small example for how a segment of code using schedulers could look. Switching out the schedulers is simple." - ] - }, - { - "cell_type": "code", - "execution_count": 16, - "id": "ffe6bf79", - "metadata": {}, - "outputs": [], - "source": [ - "weights = np.ones((3,3))\n", - "print(f\"Before scheduler:\\n{weights=}\")\n", - "\n", - "epochs = 10\n", - "for e in range(epochs):\n", - " gradient = np.random.rand(3, 3)\n", - " change = adam_scheduler.update_change(gradient)\n", - " weights = weights - change\n", - " adam_scheduler.reset()\n", - "\n", - "print(f\"\\nAfter scheduler:\\n{weights=}\")" - ] - }, - { - "cell_type": "markdown", - "id": "da6184be", - "metadata": {}, - "source": [ - "### Cost functions\n", - "\n", - "In this section we will quickly look at cost functions that can be\n", - "used when creating the neural network. Every cost function takes the\n", - "target vector as its parameter, and returns a function valued only at\n", - "X such that it may easily be differentiated." - ] - }, - { - "cell_type": "code", - "execution_count": 17, - "id": "d6f94f7a", - "metadata": {}, - "outputs": [], - "source": [ - "def CostOLS(target):\n", - " \"\"\"\n", - " Return OLS function valued only at X, so\n", - " that it may be easily differentiated\n", - " \"\"\"\n", - "\n", - " def func(X):\n", - " return (1.0 / target.shape[0]) * np.sum((target - X) ** 2)\n", - "\n", - " return func\n", - "\n", - "\n", - "def CostLogReg(target):\n", - " \"\"\"\n", - " Return Logistic Regression cost function\n", - " valued only at X, so that it may be easily differentiated\n", - " \"\"\"\n", - "\n", - " def func(X):\n", - " return -(1.0 / target.shape[0]) * np.sum(\n", - " (target * np.log(X + 10e-10)) + ((1 - target) * np.log(1 - X + 10e-10))\n", - " )\n", - "\n", - " return func\n", - "\n", - "\n", - "def CostCrossEntropy(target):\n", - " \"\"\"\n", - " Return cross entropy cost function valued only at X, so\n", - " that it may be easily differentiated\n", - " \"\"\"\n", - " \n", - " def func(X):\n", - " return -(1.0 / target.size) * np.sum(target * np.log(X + 10e-10))\n", - "\n", - " return func" - ] - }, - { - "cell_type": "markdown", - "id": "2e31a305", - "metadata": {}, - "source": [ - "### Usage of cost functions\n", - "\n", - "Below we will provide a short example of how these cost function may\n", - "be used to obtain results if you wish to test them out on your own\n", - "using AutoGrad's automatic differentiation." - ] - }, - { - "cell_type": "code", - "execution_count": 18, - "id": "86787efe", - "metadata": {}, - "outputs": [], - "source": [ - "from autograd import grad\n", - "\n", - "target = np.array([[1, 2, 3]]).T\n", - "a = np.array([[4, 5, 6]]).T\n", - "\n", - "cost_func = CostCrossEntropy\n", - "cost_func_derivative = grad(cost_func(target))\n", - "\n", - "valued_at_a = cost_func_derivative(a)\n", - "print(f\"Derivative of cost function {cost_func.__name__} valued at a:\\n{valued_at_a}\")" - ] - }, - { - "cell_type": "markdown", - "id": "4dce940e", - "metadata": {}, - "source": [ - "### Activation functions\n", - "\n", - "Finally, before we look at the layers that make up the neural network,\n", - "we will look at the activation functions which can be specified\n", - "between the hidden layers and as the output function. Each function\n", - "can be valued for any given vector or matrix X, and can be\n", - "differentiated via derivate()." - ] - }, - { - "cell_type": "code", - "execution_count": 19, - "id": "9d2c299f", - "metadata": {}, - "outputs": [], - "source": [ - "\n", - "import autograd.numpy as np\n", - "from autograd import elementwise_grad\n", - "\n", - "def identity(X):\n", - " return X\n", - "\n", - "\n", - "def sigmoid(X):\n", - " try:\n", - " return 1.0 / (1 + np.exp(-X))\n", - " except FloatingPointError:\n", - " return np.where(X > np.zeros(X.shape), np.ones(X.shape), np.zeros(X.shape))\n", - "\n", - "\n", - "def softmax(X):\n", - " X = X - np.max(X, axis=-1, keepdims=True)\n", - " delta = 10e-10\n", - " return np.exp(X) / (np.sum(np.exp(X), axis=-1, keepdims=True) + delta)\n", - "\n", - "\n", - "def RELU(X):\n", - " return np.where(X > np.zeros(X.shape), X, np.zeros(X.shape))\n", - "\n", - "\n", - "def LRELU(X):\n", - " delta = 10e-4\n", - " return np.where(X > np.zeros(X.shape), X, delta * X)\n", - "\n", - "\n", - "def derivate(func):\n", - " if func.__name__ == \"RELU\":\n", - "\n", - " def func(X):\n", - " return np.where(X > 0, 1, 0)\n", - "\n", - " return func\n", - "\n", - " elif func.__name__ == \"LRELU\":\n", - "\n", - " def func(X):\n", - " delta = 10e-4\n", - " return np.where(X > 0, 1, delta)\n", - "\n", - " return func\n", - "\n", - " else:\n", - " return elementwise_grad(func)" - ] - }, - { - "cell_type": "markdown", - "id": "83b08081", - "metadata": {}, - "source": [ - "### Usage of activation functions\n", - "\n", - "Below we present a short demonstration of how to use an activation\n", - "function. The derivative of the activation function will be important\n", - "when calculating the output delta term during backpropagation. Note\n", - "that derivate() can also be used for cost functions for a more\n", - "generalized approach." - ] - }, - { - "cell_type": "code", - "execution_count": 20, - "id": "25d64b84", - "metadata": {}, - "outputs": [], - "source": [ - "z = np.array([[4, 5, 6]]).T\n", - "print(f\"Input to activation function:\\n{z}\")\n", - "\n", - "act_func = sigmoid\n", - "a = act_func(z)\n", - "print(f\"\\nOutput from {act_func.__name__} activation function:\\n{a}\")\n", - "\n", - "act_func_derivative = derivate(act_func)\n", - "valued_at_z = act_func_derivative(a)\n", - "print(f\"\\nDerivative of {act_func.__name__} activation function valued at z:\\n{valued_at_z}\")" - ] - }, - { - "cell_type": "markdown", - "id": "2ac7f432", - "metadata": {}, - "source": [ - "### Convolution\n", - "\n", - "In order to construct a convolutional neural network (CNN), it is\n", - "crucial to comprehend the fundamental principles of convolution and\n", - "how it aids in extracting information from images. Convolution, at its\n", - "core, is merely a mathematical operation between two functions that\n", - "yields another function. It is represented by an integral between two\n", - "functions, which is typically expressed as:" - ] - }, - { - "cell_type": "markdown", - "id": "9e40a4b8", - "metadata": {}, - "source": [ - "$$\n", - "(f \\ast g)(t):=\\int_{-\\infty}^{\\infty} f(\\tau) g(t-\\tau) d \\tau.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "c6f8f49d", - "metadata": {}, - "source": [ - "Here, f and g are the two functions on which we want to perform an\n", - "operation. The outcome of the convolution operation is represented by\n", - "$(f \\ast g)$, and it is derived by sliding the function g over f and\n", - "computing the integral of their product at each position. If both\n", - "functions are continuous, convolution takes the form shown\n", - "above. However, if we discretize both f and g, the convolution\n", - "operation will take the form of a sum between the elements of f and g:" - ] - }, - { - "cell_type": "markdown", - "id": "990d7b4c", - "metadata": {}, - "source": [ - "$$\n", - "(f \\ast g)[n]=\\sum_{m=0}^{n-1} f[m] g[n-m].\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "cdcb5e34", - "metadata": {}, - "source": [ - "The key idea we utilize to extract the information contained in an\n", - "image is to slide an $m \\times n$ matrix *g* over an $m \\times n$\n", - "matrix *f*. In our case, *f* represents the image, while *g*\n", - "represents the kernel, oftentimes called a filter. However, since our\n", - "convolution will be a two-dimensional variant, we need to extend our\n", - "mathematical formula with an additional summation:" - ] - }, - { - "cell_type": "markdown", - "id": "1a31b881", - "metadata": {}, - "source": [ - "$$\n", - "(f \\ast g)[i, j]\\sum_{m=0}^{M-1}\\sum_{n=0}^{N-1} f[m,n] g[i-m, j-n].\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "bc501ada", - "metadata": {}, - "source": [ - "It is imperative to note that the size of the kernel g is\n", - "significantly smaller than the size of the input image f, thereby\n", - "reducing the amount of computation necessary for feature\n", - "extraction. Furthermore, the kernel is usually a trainable parameter\n", - "in a convolutional neural network, allowing the network to learn\n", - "appropriate kernels for specific tasks.\n", - "\n", - "To give you an example of how 2D convolution works in practice,\n", - "suppose we have an image *f* of dimension $6 \\times 6$" - ] - }, - { - "cell_type": "markdown", - "id": "826b08dc", - "metadata": {}, - "source": [ - "$$\n", - "f = \\begin{bmatrix}\n", - "4 & 1 & 2 & 9 & 8 & 6 \\\\\n", - "9 & 5 & 9 & 5 & 8 & 5 \\\\\n", - "1 & 5 & 9 & 7 & 6 & 4 \\\\\n", - "2 & 9 & 8 & 3 & 7 & 1 \\\\\n", - "8 & 1 & 6 & 4 & 2 & 2 \\\\\n", - "1 & 0 & 5 & 7 & 8 & 2 \\\\\n", - "\\end{bmatrix}\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "005de3fb", - "metadata": {}, - "source": [ - "and a $3 \\times 3$ kernel *g* called a low-pass filter. Note that the\n", - "kernel is usually rotated by 180 degrees during convolution, however\n", - "this has no effect on this kernel." - ] - }, - { - "cell_type": "markdown", - "id": "05a330e4", - "metadata": {}, - "source": [ - "$$\n", - "g = \\frac{1}{9}\n", - "\\begin{bmatrix}\n", - "1 & 1 & 1 \\\\\n", - "1 & 1 & 1 \\\\\n", - "1 & 1 & 1 \\\\\n", - "\\end{bmatrix}\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "2b2f22cd", - "metadata": {}, - "source": [ - "In order to filter the image, we have to extract a $3 \\times 3$\n", - "element from the upper left corner of *f*, and perform element-wise\n", - "multiplication of the extracted image pixels with the elements of the\n", - "kernel *g*:" - ] - }, - { - "cell_type": "markdown", - "id": "96f92012", - "metadata": {}, - "source": [ - "$$\n", - "\\begin{bmatrix}\n", - "4 & 1 & 2 \\\\\n", - "9 & 5 & 9 \\\\\n", - "1 & 5 & 9 \\\\\n", - "\\end{bmatrix}\n", - "\\cdot\n", - "\\begin{bmatrix}\n", - "\\frac{1}{9} & \\frac{1}{9} & \\frac{1}{9} \\\\\n", - "\\frac{1}{9} & \\frac{1}{9} & \\frac{1}{9} \\\\\n", - "\\frac{1}{9} & \\frac{1}{9} & \\frac{1}{9} \\\\\n", - "\\end{bmatrix}\n", - "=\n", - "\\begin{bmatrix}\n", - "\\frac{4}{9} & \\frac{1}{9} & \\frac{2}{9} \\\\\n", - "\\frac{9}{9} & \\frac{5}{9} & \\frac{9}{9} \\\\\n", - "\\frac{1}{9} & \\frac{5}{9} & \\frac{9}{9} \\\\\n", - "\\end {bmatrix}\n", - "= \\textbf{A}\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "9da8697b", - "metadata": {}, - "source": [ - "Then, following the multiplication, we summarize all the elements of the resulting matrix A:" - ] - }, - { - "cell_type": "markdown", - "id": "ca826ccb", - "metadata": {}, - "source": [ - "$$\n", - "(f \\ast g)[0, 0]= \\sum_{i=0}^{2} \\sum_{j=0}^{2} a_{i,j} = 5\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "bee3496b", - "metadata": {}, - "source": [ - "Which corresponds to the first element of the filtered image $(f \\ast g)$.\n", - "\n", - "Here we use a stride of 1, a parameter denoted *s* which describes how\n", - "many indexes we move the kernel *g* to the right before repeating the\n", - "calculations above for the next $3 \\times 3$ element of the image\n", - "*f*. It is usually presumed that *s*=1, however, larger values for *s*\n", - "can be used to reduce the dimentionality of the filtered image such\n", - "that the convolution operation is more computationally efficient. In\n", - "the context of a convolutional neural network, this will become very\n", - "useful.\n", - "\n", - "The full result of the convolution is:" - ] - }, - { - "cell_type": "markdown", - "id": "56669311", - "metadata": {}, - "source": [ - "$$\n", - "(f \\ast g) =\n", - "\\begin{bmatrix}\n", - "5 & 5.78 & 7 & 6.44 \\\\\n", - "6.33 & 6.67 & 6.89 & 5.11 \\\\\n", - "5.44 & 5.78 & 5.78 & 4 \\\\\n", - "4.44 & 4.78 & 5.56 & 4 \\\\\n", - "\\end{bmatrix}\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "b012e0eb", - "metadata": {}, - "source": [ - "The result is markedly smaller in shape than the original image. This occurs when using convolution without first padding the image with additional columns and rows, allowing us to keep the original image shape after sliding the kernel over the image.\n", - "How many rows and columns we wish to pad the image with depends strictly on the shape of the kernel, as we wish to pad the image with *r* additional rows and *c* additional columns." - ] - }, - { - "cell_type": "markdown", - "id": "638c9e09", - "metadata": {}, - "source": [ - "$$\n", - "r =\\lfloor \\frac{kernel\\ height}{2} \\rfloor \\cdot 2 \\\\\n", - "c =\\lfloor \\frac{kernel\\ width}{2} \\rfloor \\cdot 2\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "7774dd55", - "metadata": {}, - "source": [ - "Note the notation $\\lfloor \\frac{kernel width}{2} \\rfloor$ means that\n", - "we floor the result of the division, meaning we round down to a whole\n", - "number in case $\\frac{kernel width}{2}$ results in a floating point\n", - "number.\n", - "\n", - "Using those simple equations, we find out by how much we have to\n", - "extend the dimensions of the original image. Before proceeding,\n", - "however, we might ask what we shall fill the additional rows and\n", - "columns with? One of the most common approaches to padding is\n", - "zero-padding, which as the name suggest, involves filling the rows and\n", - "columns with zeros. This is the approach that we will be using for\n", - "this demonstration. If we apply this padding to out original $6 \\times 6$\n", - "image, the result will be an $8 \\times 8$ image as the kernel has a width and\n", - "height of 3. Note that the original image is encapsuled by the\n", - "zero-padded rows and columns:" - ] - }, - { - "cell_type": "markdown", - "id": "eaecffed", - "metadata": {}, - "source": [ - "$$\n", - "\\begin{bmatrix}\n", - "0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 \\\\\n", - "0 & 4 & 1 & 2 & 9 & 8 & 6 & 0 \\\\\n", - "0 & 9 & 5 & 9 & 5 & 8 & 5 & 0 \\\\\n", - "0 & 1 & 5 & 9 & 7 & 6 & 4 & 0 \\\\\n", - "0 & 2 & 9 & 8 & 3 & 7 & 1 & 0 \\\\\n", - "0 & 8 & 1 & 6 & 4 & 2 & 2 & 0 \\\\\n", - "0 & 1 & 0 & 5 & 7 & 8 & 2 & 0 \\\\\n", - "0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 \\\\\n", - "\n", - "\\end{bmatrix}\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "9492033c", - "metadata": {}, - "source": [ - "Below we have provided code that demonstrates padding and convolution. As you will see when we run the code, the size of the image will remain unchanged when using padding.~" - ] - }, - { - "cell_type": "code", - "execution_count": 21, - "id": "0554e3ab", - "metadata": {}, - "outputs": [], - "source": [ - "import numpy as np\n", - "\n", - "def padding(image, kernel):\n", - " # calculate r and c\n", - " r = (kernel.shape[0] // 2) * 2\n", - " c = (kernel.shape[1] // 2) * 2\n", - " \n", - " # padded image dimensions\n", - " padded_height = image.shape[0] + r\n", - " padded_width = image.shape[1] + c\n", - " \n", - " # for more readable code\n", - " k_half_height = kernel.shape[0] // 2\n", - " k_half_width = kernel.shape[1] // 2\n", - "\n", - " # zero matrix with padded dimensions\n", - " padded_img = np.zeros((padded_height, padded_width))\n", - "\n", - " # place image into zero matrix\n", - " padded_img[k_half_height : padded_height - k_half_height,\n", - " k_half_width : padded_width - k_half_width] = image[:, :]\n", - "\n", - " return padded_img\n", - "\n", - "def convolve(original_image, padded_image, kernel, stride=1):\n", - " # rotate kernel by 180 degrees\n", - " kernel = np.rot90(np.rot90(kernel))\n", - "\n", - " # note that kernel height // 2 is written as 'm'\n", - " # and kernel width // 2 as 'n' in the mathematical notation\n", - " m = kernel.shape[0] // 2\n", - " n = kernel.shape[1] // 2\n", - " \n", - " r = (kernel.shape[0] // 2) * 2\n", - " c = (kernel.shape[1] // 2) * 2\n", - " \n", - " # initialize output array\n", - " convolved_image = np.zeros(original_image.shape)\n", - " image_height = original_image.shape[0]\n", - " image_width = original_image.shape[1]\n", - "\n", - " # the convolution\n", - " for i in range(m, image_height + m, stride):\n", - " for j in range(n, image_width + n, stride):\n", - " convolved_image[i-m, j-n] = np.sum(\n", - " padded_image[i : i + m, j : j + n]\n", - " * kernel\n", - " )\n", - " \n", - " return convolved_image\n", - "\n", - "def convolve(image, kernel, stride=1):\n", - " for i in range(2):\n", - " kernel = np.rot90(kernel)\n", - "\n", - " k_half_height = kernel.shape[0] // 2\n", - " k_half_width = kernel.shape[0] // 2\n", - "\n", - " conv_image = np.zeros(image.shape)\n", - " pad_image = padding(image, kernel)\n", - "\n", - " for i in range(k_half_height, conv_image.shape[0] + k_half_height, stride):\n", - " for j in range(k_half_width, conv_image.shape[1] + k_half_width, stride):\n", - " conv_image[i - k_half_height, j - k_half_width] = np.sum(\n", - " pad_image[\n", - " i - k_half_height : i + k_half_height + 1, j - k_half_width : j + k_half_width + 1\n", - " ]\n", - " * kernel\n", - " )\n", - "\n", - " return conv_image" - ] - }, - { - "cell_type": "markdown", - "id": "0eeb696e", - "metadata": {}, - "source": [ - "Fun fact: When filtering images, you will see that convolution involves rotating the kernel by 180 degrees. \n", - "However, this is not the case when applying convolution in a CNN, where the same operation not rotated by 180 degrees is called \n", - "cross-correlation." - ] - }, - { - "cell_type": "code", - "execution_count": 22, - "id": "85bbe906", - "metadata": {}, - "outputs": [], - "source": [ - "\n", - "original_image = np.array([[4, 1, 2, 9, 8, 6],\n", - " [9, 5, 9, 5, 8, 5],\n", - " [1, 5, 9, 7, 6, 4],\n", - " [2, 9, 8, 3, 7, 1],\n", - " [8, 1, 6, 4, 2, 2],\n", - " [1, 0, 5, 7, 8, 2]])\n", - "\n", - "kernel = (1/9)*np.ones((3,3))\n", - "\n", - "print(f\"{original_image.shape=}\")\n", - "\n", - "# note that convolve() performs padding\n", - "convolved_image = convolve(original_image, kernel, stride=1)\n", - "\n", - "print(f\"{convolved_image.shape=}\")" - ] - }, - { - "cell_type": "markdown", - "id": "c5a5e0db", - "metadata": {}, - "source": [ - "As you can see, the resulting image is of the same size as the\n", - "original image. To round of our demonstration of convolution, we will\n", - "present the results of convolution using commonly used kernels. In a\n", - "CNN, the values of the kernels are randomly initialized, and then\n", - "learned during training. These kernels will extract information\n", - "regarding the picture, such as for example the edge detection filter\n", - "demonstrated below extracts the edges present in the picture. Of\n", - "course, there is no guarantee that the CNN will learn an edge\n", - "detection filter, but this should provide some intuiton as to how the\n", - "CNN is able to use kernels to make better predictions than a regular\n", - "feed forward neural network." - ] - }, - { - "cell_type": "code", - "execution_count": 23, - "id": "eaa84aaa", - "metadata": {}, - "outputs": [], - "source": [ - "# Now an example using a real image and first a gaussian low-pass filter and then a sobel filter\n", - "import numpy as np\n", - "import imageio.v3 as imageio\n", - "import matplotlib.pyplot as plt\n", - "import time\n", - "\n", - "def generate_gauss_mask(sigma, K=1):\n", - " side = np.ceil(1 + 8 * sigma)\n", - " y, x = np.mgrid[-side // 2 + 1 : (side // 2) + 1, -side // 2 + 1 : (side // 2) + 1]\n", - " ker_coef = K / (2 * np.pi * sigma**2)\n", - " g = np.exp(-((x**2 + y**2) / (2.0 * sigma**2)))\n", - "\n", - " return g, ker_coef\n", - "\n", - "\n", - "img_path = \"data/IMG-2167.JPG\"\n", - "image_of_cute_dog = imageio.imread(img_path, mode='L')\n", - "\n", - "plt.imshow(image_of_cute_dog, cmap=\"gray\", vmin=0, vmax=255, aspect=\"auto\")\n", - "plt.title(\"Original image\")\n", - "plt.show()\n", - "\n", - "gauss, kernel = generate_gauss_mask(sigma=6)\n", - "gauss_kernel = gauss*kernel\n", - "\n", - "filtered_image = convolve(image_of_cute_dog, gauss_kernel)\n", - "plt.imshow(filtered_image, cmap=\"gray\", vmin=0, vmax=255, aspect=\"auto\")\n", - "plt.title(\"Result of convolution with gauss kernel (blurring filter)\")\n", - "plt.show()\n", - "\n", - "sobel_kernel = np.array([[1, 2, 1],\n", - " [0, 0, 0], \n", - " [-1, -2, -1]])\n", - "\n", - "filtered_image = convolve(image_of_cute_dog, sobel_kernel)\n", - "\n", - "plt.imshow(filtered_image, cmap=\"gray\", vmin=0, vmax=255, aspect=\"auto\")\n", - "plt.title(\"Result of convolution with sobel kernel (edge detection filter)\")\n", - "plt.show()" - ] - }, - { - "cell_type": "markdown", - "id": "96fa5861", - "metadata": {}, - "source": [ - "### Layers\n", - "\n", - "The code below initialises global variables for readability and\n", - "describes the abstract class Layers. This is not important in order to\n", - "understand the CNN, but is benefitial for organizing the code neatly." - ] - }, - { - "cell_type": "code", - "execution_count": 24, - "id": "d8afa149", - "metadata": {}, - "outputs": [], - "source": [ - "import math\n", - "import autograd.numpy as np\n", - "from copy import deepcopy, copy\n", - "from autograd import grad\n", - "from typing import Callable\n", - "\n", - "# global variables for index readability\n", - "input_index = 0\n", - "node_index = 1\n", - "bias_index = 1\n", - "input_channel_index = 1\n", - "feature_maps_index = 1\n", - "height_index = 2\n", - "width_index = 3\n", - "kernel_feature_maps_index = 1\n", - "kernel_input_channels_index = 0\n", - "\n", - "\n", - "class Layer:\n", - " def __init__(self, seed):\n", - " self.seed = seed\n", - "\n", - " def _feedforward(self):\n", - " raise NotImplementedError\n", - "\n", - " def _backpropagate(self):\n", - " raise NotImplementedError\n", - "\n", - " def _reset_weights(self, previous_nodes):\n", - " raise NotImplementedError" - ] - }, - { - "cell_type": "markdown", - "id": "72355a22", - "metadata": {}, - "source": [ - "### Convolution2DLayer: convolution in a hidden layer\n", - "\n", - "After establishing the foundational understanding of applying\n", - "convolution to spatial data, let us delve into the intricate workings\n", - "of a convolutional layer in a Convolutional Neural Network (CNN). The\n", - "primary function of convolution, as previously discussed, is to\n", - "extract pertinent information from images while simultaneously\n", - "decreasing the scale of our data. To initiate the image processing, we\n", - "shall begin by partitioning the images into color channels (unless the\n", - "image is grayscale), comprising three primary colors: red, green, and\n", - "blue. We will subsequently utilize trainable kernels to construct a\n", - "higher-dimensional encoding of each channel called feature\n", - "maps. Successive layers will receive these feature maps as inputs,\n", - "generating further encodings, albeit with reduced dimensions. The term\n", - "trainable kernels denotes the initialization of pre-defined\n", - "kernel-shaped weights, which we will then train via backpropagation,\n", - "similar to how weights are trained in a Feedforward Neural Network.\n", - "\n", - "To ensure seamless integration between our implementation of the\n", - "convolutional layer and popular machine learning frameworks like\n", - "Tensorflow (Keras) and PyTorch, we have adopted a design pattern that\n", - "mirrors the construction of models using these APIs. This involves\n", - "implementing our convolutional layer as a Python class or object,\n", - "which allows for a more modular and flexible approach to building\n", - "neural networks. By structuring our code in this way, users can easily\n", - "incorporate our implementation into their existing machine learning\n", - "pipelines without having to make significant changes to their\n", - "codebase. Additionally, this design pattern promotes code reusability\n", - "and makes it easier to maintain and update our convolutional layer\n", - "implementation over time.\n", - "\n", - "Note that the Convolution2DLayer takes in an activation function as a parameter, as it also performs non-linearity." - ] - }, - { - "cell_type": "code", - "execution_count": 25, - "id": "32559517", - "metadata": {}, - "outputs": [], - "source": [ - "class Convolution2DLayer(Layer):\n", - " def __init__(\n", - " self,\n", - " input_channels,\n", - " feature_maps,\n", - " kernel_height,\n", - " kernel_width,\n", - " v_stride,\n", - " h_stride,\n", - " pad,\n", - " act_func: Callable,\n", - " seed=None,\n", - " reset_weights_independently=True,\n", - " ):\n", - " super().__init__(seed)\n", - " self.input_channels = input_channels\n", - " self.feature_maps = feature_maps\n", - " self.kernel_height = kernel_height\n", - " self.kernel_width = kernel_width\n", - " self.v_stride = v_stride\n", - " self.h_stride = h_stride\n", - " self.pad = pad\n", - " self.act_func = act_func\n", - "\n", - " # such that the layer can be used on its own\n", - " # outside of the CNN module\n", - " if reset_weights_independently == True:\n", - " self._reset_weights_independently()\n", - "\n", - " def _feedforward(self, X_batch):\n", - " # note that the shape of X_batch = [inputs, input_maps, img_height, img_width]\n", - "\n", - " # pad the input batch\n", - " X_batch_padded = self._padding(X_batch)\n", - "\n", - " # calculate height_index and width_index after stride\n", - " strided_height = int(np.ceil(X_batch.shape[height_index] / self.v_stride))\n", - " strided_width = int(np.ceil(X_batch.shape[width_index] / self.h_stride))\n", - "\n", - " # create output array\n", - " output = np.ndarray(\n", - " (\n", - " X_batch.shape[input_index],\n", - " self.feature_maps,\n", - " strided_height,\n", - " strided_width,\n", - " )\n", - " )\n", - "\n", - " # save input and output for backpropagation\n", - " self.X_batch_feedforward = X_batch\n", - " self.output_shape = output.shape\n", - "\n", - " # checking for errors, no need to look here :)\n", - " self._check_for_errors()\n", - "\n", - " # convolve input with kernel\n", - " for img in range(X_batch.shape[input_index]):\n", - " for chin in range(self.input_channels):\n", - " for fmap in range(self.feature_maps):\n", - " out_h = 0\n", - " for h in range(0, X_batch.shape[height_index], self.v_stride):\n", - " out_w = 0\n", - " for w in range(0, X_batch.shape[width_index], self.h_stride):\n", - " output[img, fmap, out_h, out_w] = np.sum(\n", - " X_batch_padded[\n", - " img,\n", - " chin,\n", - " h : h + self.kernel_height,\n", - " w : w + self.kernel_width,\n", - " ]\n", - " * self.kernel[chin, fmap, :, :]\n", - " )\n", - " out_w += 1\n", - " out_h += 1\n", - "\n", - " # Pay attention to the fact that we're not rotating the kernel by 180 degrees when filtering the image in\n", - " # the convolutional layer, as convolution in terms of Machine Learning is a procedure known as cross-correlation\n", - " # in image processing and signal processing\n", - "\n", - " # return a\n", - " return self.act_func(output / (self.kernel_height))\n", - "\n", - " def _backpropagate(self, delta_term_next):\n", - " # intiate matrices\n", - " delta_term = np.zeros((self.X_batch_feedforward.shape))\n", - " gradient_kernel = np.zeros((self.kernel.shape))\n", - "\n", - " # pad input for convolution\n", - " X_batch_padded = self._padding(self.X_batch_feedforward)\n", - "\n", - " # Since an activation function is used at the output of the convolution layer, its derivative\n", - " # has to be accounted for in the backpropagation -> as if ReLU was a layer on its own.\n", - " act_derivative = derivate(self.act_func)\n", - " delta_term_next = act_derivative(delta_term_next)\n", - "\n", - " # fill in 0's for values removed by vertical stride in feedforward\n", - " if self.v_stride > 1:\n", - " v_ind = 1\n", - " for i in range(delta_term_next.shape[height_index]):\n", - " for j in range(self.v_stride - 1):\n", - " delta_term_next = np.insert(\n", - " delta_term_next, v_ind, 0, axis=height_index\n", - " )\n", - " v_ind += self.v_stride\n", - "\n", - " # fill in 0's for values removed by horizontal stride in feedforward\n", - " if self.h_stride > 1:\n", - " h_ind = 1\n", - " for i in range(delta_term_next.shape[width_index]):\n", - " for k in range(self.h_stride - 1):\n", - " delta_term_next = np.insert(\n", - " delta_term_next, h_ind, 0, axis=width_index\n", - " )\n", - " h_ind += self.h_stride\n", - "\n", - " # crops out 0-rows and 0-columns\n", - " delta_term_next = delta_term_next[\n", - " :,\n", - " :,\n", - " : self.X_batch_feedforward.shape[height_index],\n", - " : self.X_batch_feedforward.shape[width_index],\n", - " ]\n", - "\n", - " # the gradient received from the next layer also needs to be padded\n", - " delta_term_next = self._padding(delta_term_next)\n", - "\n", - " # calculate delta term by convolving next delta term with kernel\n", - " for img in range(self.X_batch_feedforward.shape[input_index]):\n", - " for chin in range(self.input_channels):\n", - " for fmap in range(self.feature_maps):\n", - " for h in range(self.X_batch_feedforward.shape[height_index]):\n", - " for w in range(self.X_batch_feedforward.shape[width_index]):\n", - " delta_term[img, chin, h, w] = np.sum(\n", - " delta_term_next[\n", - " img,\n", - " fmap,\n", - " h : h + self.kernel_height,\n", - " w : w + self.kernel_width,\n", - " ]\n", - " * np.rot90(np.rot90(self.kernel[chin, fmap, :, :]))\n", - " )\n", - "\n", - " # calculate gradient for kernel for weight update\n", - " # also via convolution\n", - " for chin in range(self.input_channels):\n", - " for fmap in range(self.feature_maps):\n", - " for k_x in range(self.kernel_height):\n", - " for k_y in range(self.kernel_width):\n", - " gradient_kernel[chin, fmap, k_x, k_y] = np.sum(\n", - " X_batch_padded[\n", - " img,\n", - " chin,\n", - " h : h + self.kernel_height,\n", - " w : w + self.kernel_width,\n", - " ]\n", - " * delta_term_next[\n", - " img,\n", - " fmap,\n", - " h : h + self.kernel_height,\n", - " w : w + self.kernel_width,\n", - " ]\n", - " )\n", - " # all kernels are updated with weight gradient of kernel\n", - " self.kernel -= gradient_kernel\n", - "\n", - " # return delta term\n", - " return delta_term\n", - "\n", - " def _padding(self, X_batch, batch_type=\"image\"):\n", - "\n", - " # same padding for images\n", - " if self.pad == \"same\" and batch_type == \"image\":\n", - " padded_height = X_batch.shape[height_index] + (self.kernel_height // 2) * 2\n", - " padded_width = X_batch.shape[width_index] + (self.kernel_width // 2) * 2\n", - " half_kernel_height = self.kernel_height // 2\n", - " half_kernel_width = self.kernel_width // 2\n", - "\n", - " # initialize padded array\n", - " X_batch_padded = np.ndarray(\n", - " (\n", - " X_batch.shape[input_index],\n", - " X_batch.shape[feature_maps_index],\n", - " padded_height,\n", - " padded_width,\n", - " )\n", - " )\n", - "\n", - " # zero pad all images in X_batch\n", - " for img in range(X_batch.shape[input_index]):\n", - " padded_img = np.zeros(\n", - " (X_batch.shape[feature_maps_index], padded_height, padded_width)\n", - " )\n", - " padded_img[\n", - " :,\n", - " half_kernel_height : padded_height - half_kernel_height,\n", - " half_kernel_width : padded_width - half_kernel_width,\n", - " ] = X_batch[img, :, :, :]\n", - " X_batch_padded[img, :, :, :] = padded_img[:, :, :]\n", - "\n", - " return X_batch_padded\n", - "\n", - " # same padding for gradients\n", - " elif self.pad == \"same\" and batch_type == \"grad\":\n", - " padded_height = X_batch.shape[height_index] + (self.kernel_height // 2) * 2\n", - " padded_width = X_batch.shape[width_index] + (self.kernel_width // 2) * 2\n", - " half_kernel_height = self.kernel_height // 2\n", - " half_kernel_width = self.kernel_width // 2\n", - "\n", - " # initialize padded array\n", - " delta_term_padded = np.zeros(\n", - " (\n", - " X_batch.shape[input_index],\n", - " X_batch.shape[feature_maps_index],\n", - " padded_height,\n", - " padded_width,\n", - " )\n", - " )\n", - "\n", - " # zero pad delta term\n", - " delta_term_padded[\n", - " :, :, : X_batch.shape[height_index], : X_batch.shape[width_index]\n", - " ] = X_batch[:, :, :, :]\n", - "\n", - " return delta_term_padded\n", - "\n", - " else:\n", - " return X_batch\n", - "\n", - " def _reset_weights_independently(self):\n", - " # sets seed to remove randomness inbetween runs\n", - " if self.seed is not None:\n", - " np.random.seed(self.seed)\n", - "\n", - " # initializes kernel matrix\n", - " self.kernel = np.ndarray(\n", - " (\n", - " self.input_channels,\n", - " self.feature_maps,\n", - " self.kernel_height,\n", - " self.kernel_width,\n", - " )\n", - " )\n", - "\n", - " # randomly initializes weights\n", - " for chin in range(self.kernel.shape[kernel_input_channels_index]):\n", - " for fmap in range(self.kernel.shape[kernel_feature_maps_index]):\n", - " self.kernel[chin, fmap, :, :] = np.random.rand(\n", - " self.kernel_height, self.kernel_width\n", - " )\n", - "\n", - " def _reset_weights(self, previous_nodes):\n", - " # sets weights\n", - " self._reset_weights_independently()\n", - "\n", - " # returns shape of output used for subsequent layer's weight initiation\n", - " strided_height = int(\n", - " np.ceil(previous_nodes.shape[height_index] / self.v_stride)\n", - " )\n", - " strided_width = int(np.ceil(previous_nodes.shape[width_index] / self.h_stride))\n", - " next_nodes = np.ones(\n", - " (\n", - " previous_nodes.shape[input_index],\n", - " self.feature_maps,\n", - " strided_height,\n", - " strided_width,\n", - " )\n", - " )\n", - " return next_nodes / self.kernel_height\n", - "\n", - " def _check_for_errors(self):\n", - " if self.X_batch_feedforward.shape[input_channel_index] != self.input_channels:\n", - " raise AssertionError(\n", - " f\"ERROR: Number of input channels in data ({self.X_batch_feedforward.shape[input_channel_index]}) is not equal to input channels in Convolution2DLayerOPT ({self.input_channels})! Please change the number of input channels of the Convolution2DLayer such that they are equal\"\n", - " )" - ] - }, - { - "cell_type": "markdown", - "id": "fc174600", - "metadata": {}, - "source": [ - "### Backpropagation in the convolutional layer\n", - "\n", - "As you may have noticed, we have not yet explained how the\n", - "backpropagation algorithm works in a convolutional layer. However,\n", - "having covered all other major details about convolutional layers, we\n", - "are now prepared to do so. It should come as no surprise that the\n", - "calculation of delta terms at each convolutional layer takes the form\n", - "of convolution. After the gradient has been propagated backwards\n", - "through the flattening layer, where it was reshaped into an\n", - "appropriate form, calculating the update value for the kernel is\n", - "simply a matter of convolving the output gradient with the input of\n", - "the layer for which we are updating the weights. For more detail, this\n", - "article serves as an excellent resource, see\n", - "" - ] - }, - { - "cell_type": "markdown", - "id": "8eacacfe", - "metadata": {}, - "source": [ - "### Demonstration\n", - "\n", - "We can use the convolutional layer above to perform a simple convolution on an image of the now familiar cute dog." - ] - }, - { - "cell_type": "code", - "execution_count": 26, - "id": "46196b67", - "metadata": {}, - "outputs": [], - "source": [ - "import numpy as np\n", - "import imageio.v3 as imageio\n", - "import matplotlib.pyplot as plt\n", - "\n", - "def plot_convolution_result(X, layer):\n", - " plt.imshow(X[0, 0, :, :], vmin=0, vmax=255, cmap=\"gray\")\n", - " plt.title(\"Original image\")\n", - " plt.colorbar()\n", - " plt.show()\n", - " conv_result = layer._feedforward(X)\n", - " plt.title(\"Result of convolutional layer\")\n", - " plt.imshow(conv_result[0, 0, :, :], vmin=0, vmax=255, cmap=\"gray\")\n", - " plt.colorbar()\n", - " plt.show()\n", - "\n", - "# create layer\n", - "layer = Convolution2DLayer(\n", - " input_channels=3,\n", - " feature_maps=1,\n", - " kernel_height=4,\n", - " kernel_width=4,\n", - " v_stride=2,\n", - " h_stride=2,\n", - " pad=\"same\",\n", - " act_func=identity,\n", - " seed=2023,\n", - " )\n", - "\n", - "# read in image path, make data correct format\n", - "img_path = img_path = \"data/IMG-2167.JPG\"\n", - "image_of_cute_dog = imageio.imread(img_path)\n", - "image_shape = image_of_cute_dog.shape\n", - "image_of_cute_dog = image_of_cute_dog.reshape(1, image_shape[0], image_shape[1], image_shape[2])\n", - "image_of_cute_dog = image_of_cute_dog.transpose(0, 3, 1, 2)\n", - "\n", - "# plot the result of the convolution\n", - "plot_convolution_result(image_of_cute_dog, layer)" - ] - }, - { - "cell_type": "markdown", - "id": "dc29eda8", - "metadata": {}, - "source": [ - "We cobserve that the result has half the pixels on each axis due to\n", - "the fact that we've used a horizontal and vertical stride of 2. The\n", - "result of this convolution is not very insightfull, as the kernel has\n", - "completely random values for the first feedforward pass. However, as\n", - "we perform multiple forward and backward passes, the results of the\n", - "convolution should provide identifying features of the image it uses\n", - "for classification.\n", - "\n", - "Note that image data usually comes in many different shapes and sizes,\n", - "but for our CNN we require the input data be formatted as \\[Number of\n", - "inputs, input channels, input height, input width\\]. Occasionally, the\n", - "data you come accross use will be formatted like this, but on many\n", - "occasions reshaping and transposing the dimensions is sadly necessary." - ] - }, - { - "cell_type": "markdown", - "id": "f77ea3fb", - "metadata": {}, - "source": [ - "### Pooling Layer\n", - "\n", - "The pooling layer is another widely used type of layer in\n", - "convolutional neural networks that enables data downsampling to a more\n", - "manageable size. Despite recent technological advancements that allow\n", - "for convolution without excessive size reduction of the data, the\n", - "pooling layer still remains a fundamental component of convolutional\n", - "neural networks. It can be used before, after, or in between\n", - "convolutional layers, although finding the optimal placement of layers\n", - "and network depth requires experimentation to achieve the best\n", - "performance for a given problem. The code we provide allows you to\n", - "perform two types of pooling known as max pooling and average pooling." - ] - }, - { - "cell_type": "code", - "execution_count": 27, - "id": "8738e00a", - "metadata": {}, - "outputs": [], - "source": [ - "class Pooling2DLayer(Layer):\n", - " def __init__(\n", - " self,\n", - " kernel_height,\n", - " kernel_width,\n", - " v_stride,\n", - " h_stride,\n", - " pooling=\"max\",\n", - " seed=None,\n", - " ):\n", - " super().__init__(seed)\n", - " self.kernel_height = kernel_height\n", - " self.kernel_width = kernel_width\n", - " self.v_stride = v_stride\n", - " self.h_stride = h_stride\n", - " self.pooling = pooling\n", - "\n", - " def _feedforward(self, X_batch):\n", - " # Saving the input for use in the backwardpass\n", - " self.X_batch_feedforward = X_batch\n", - "\n", - " # check if user is silly\n", - " self._check_for_errors()\n", - "\n", - " # Computing the size of the feature maps based on kernel size and the stride parameter\n", - " strided_height = (\n", - " X_batch.shape[height_index] - self.kernel_height\n", - " ) // self.v_stride + 1\n", - " if X_batch.shape[height_index] == X_batch.shape[width_index]:\n", - " strided_width = strided_height\n", - " else:\n", - " strided_width = (\n", - " X_batch.shape[width_index] - self.kernel_width\n", - " ) // self.h_stride + 1\n", - "\n", - " # initialize output array\n", - " output = np.ndarray(\n", - " (\n", - " X_batch.shape[input_index],\n", - " X_batch.shape[feature_maps_index],\n", - " strided_height,\n", - " strided_width,\n", - " )\n", - " )\n", - "\n", - " # select pooling action, either max or average pooling\n", - " if self.pooling == \"max\":\n", - " self.pooling_action = np.max\n", - " elif self.pooling == \"average\":\n", - " self.pooling_action = np.mean\n", - "\n", - " # pool based on kernel size and stride\n", - " for img in range(output.shape[input_index]):\n", - " for fmap in range(output.shape[feature_maps_index]):\n", - " for h in range(strided_height):\n", - " for w in range(strided_width):\n", - " output[img, fmap, h, w] = self.pooling_action(\n", - " X_batch[\n", - " img,\n", - " fmap,\n", - " (h * self.v_stride) : (h * self.v_stride)\n", - " + self.kernel_height,\n", - " (w * self.h_stride) : (w * self.h_stride)\n", - " + self.kernel_width,\n", - " ]\n", - " )\n", - "\n", - " # output for feedforward in next layer\n", - " return output\n", - "\n", - " def _backpropagate(self, delta_term_next):\n", - " # initiate delta term array\n", - " delta_term = np.zeros((self.X_batch_feedforward.shape))\n", - "\n", - " for img in range(delta_term_next.shape[input_index]):\n", - " for fmap in range(delta_term_next.shape[feature_maps_index]):\n", - " for h in range(0, delta_term_next.shape[height_index], self.v_stride):\n", - " for w in range(\n", - " 0, delta_term_next.shape[width_index], self.h_stride\n", - " ):\n", - " # max pooling\n", - " if self.pooling == \"max\":\n", - " # get window\n", - " window = self.X_batch_feedforward[\n", - " img,\n", - " fmap,\n", - " h : h + self.kernel_height,\n", - " w : w + self.kernel_width,\n", - " ]\n", - "\n", - " # find max values indices in window\n", - " max_h, max_w = np.unravel_index(\n", - " window.argmax(), window.shape\n", - " )\n", - "\n", - " # set values in new, upsampled delta term\n", - " delta_term[\n", - " img,\n", - " fmap,\n", - " (h + max_h),\n", - " (w + max_w),\n", - " ] += delta_term_next[img, fmap, h, w]\n", - "\n", - " # average pooling\n", - " if self.pooling == \"average\":\n", - " delta_term[\n", - " img,\n", - " fmap,\n", - " h : h + self.kernel_height,\n", - " w : w + self.kernel_width,\n", - " ] = (\n", - " delta_term_next[img, fmap, h, w]\n", - " / self.kernel_height\n", - " / self.kernel_width\n", - " )\n", - " # returns input to backpropagation in previous layer\n", - " return delta_term\n", - "\n", - " def _reset_weights(self, previous_nodes):\n", - " # calculate strided height, strided width\n", - " strided_height = (\n", - " previous_nodes.shape[height_index] - self.kernel_height\n", - " ) // self.v_stride + 1\n", - " if previous_nodes.shape[height_index] == previous_nodes.shape[width_index]:\n", - " strided_width = strided_height\n", - " else:\n", - " strided_width = (\n", - " previous_nodes.shape[width_index] - self.kernel_width\n", - " ) // self.h_stride + 1\n", - "\n", - " # initiate output array\n", - " output = np.ones(\n", - " (\n", - " previous_nodes.shape[input_index],\n", - " previous_nodes.shape[feature_maps_index],\n", - " strided_height,\n", - " strided_width,\n", - " )\n", - " )\n", - "\n", - " # returns output with shape used for reset weights in next layer\n", - " return output\n", - "\n", - " def _check_for_errors(self):\n", - " # check if input is smaller than kernel size -> error\n", - " assert (\n", - " self.X_batch_feedforward.shape[width_index] >= self.kernel_width\n", - " ), f\"ERROR: Pooling kernel width_index ({self.kernel_width}) larger than data width_index ({self.X_batch_feedforward.input.shape[2]}), please lower the kernel width_index of the Pooling2DLayer\"\n", - " assert (\n", - " self.X_batch_feedforward.shape[height_index] >= self.kernel_height\n", - " ), f\"ERROR: Pooling kernel height_index ({self.kernel_height}) larger than data height_index ({self.X_batch_feedforward.input.shape[3]}), please lower the kernel height_index of the Pooling2DLayer\"" - ] - }, - { - "cell_type": "markdown", - "id": "eee176d8", - "metadata": {}, - "source": [ - "### Flattening Layer\n", - "\n", - "Before we can begin building our first CNN model, we need to introduce\n", - "the flattening layer. As its name suggests, the flattening layer\n", - "transforms the data into a one-dimensional vector that can be fed into\n", - "the feedforward layers of our network. This layer plays a crucial role\n", - "in preparing the data for further processing in the\n", - "network. Additionally, the flattening layer is responsible for\n", - "reshaping the gradient to the proper shape during\n", - "backpropagation. This ensures that the kernels are correctly updated,\n", - "allowing for effective learning in the network." - ] - }, - { - "cell_type": "code", - "execution_count": 28, - "id": "8b9d8469", - "metadata": {}, - "outputs": [], - "source": [ - "class FlattenLayer(Layer):\n", - " def __init__(self, act_func=LRELU, seed=None):\n", - " super().__init__(seed)\n", - " self.act_func = act_func\n", - "\n", - " def _feedforward(self, X_batch):\n", - " # save input for backpropagation\n", - " self.X_batch_feedforward_shape = X_batch.shape\n", - " # Remember, the data has the following shape: (I, FM, H, W, ) in the convolutional layers\n", - " # whilst the data has the shape (I, FM * H * W) in the fully connected layers\n", - " # I = Inputs, FM = Feature Maps, H = Height and W = Width.\n", - " X_batch = X_batch.reshape(\n", - " X_batch.shape[input_index],\n", - " X_batch.shape[feature_maps_index]\n", - " * X_batch.shape[height_index]\n", - " * X_batch.shape[width_index],\n", - " )\n", - "\n", - " # add bias to a\n", - " self.z_matrix = X_batch\n", - " bias = np.ones((X_batch.shape[input_index], 1)) * 0.01\n", - " self.a_matrix = np.hstack([bias, X_batch])\n", - "\n", - " # return a, the input to feedforward in next layer\n", - " return self.a_matrix\n", - "\n", - " def _backpropagate(self, weights_next, delta_term_next):\n", - " activation_derivative = derivate(self.act_func)\n", - "\n", - " # calculate delta term\n", - " delta_term = (\n", - " weights_next[bias_index:, :] @ delta_term_next.T\n", - " ).T * activation_derivative(self.z_matrix)\n", - "\n", - " # FlattenLayer does not update weights\n", - " # reshapes delta layer to convolutional layer data format [Input, Feature_Maps, Height, Width]\n", - " return delta_term.reshape(self.X_batch_feedforward_shape)\n", - "\n", - " def _reset_weights(self, previous_nodes):\n", - " # note that the previous nodes to the FlattenLayer are from the convolutional layers\n", - " previous_nodes = previous_nodes.reshape(\n", - " previous_nodes.shape[input_index],\n", - " previous_nodes.shape[feature_maps_index]\n", - " * previous_nodes.shape[height_index]\n", - " * previous_nodes.shape[width_index],\n", - " )\n", - "\n", - " # return shape used in reset_weights in next layer\n", - " return previous_nodes.shape[node_index]\n", - "\n", - " def get_prev_a(self):\n", - " return self.a_matrix" - ] - }, - { - "cell_type": "markdown", - "id": "65bb0e6d", - "metadata": {}, - "source": [ - "### Fully Connected Layers\n", - "\n", - "Finally, the result from the flatten layer will pass to a series of\n", - "fully connected layers, which function as a normal feed forward neural\n", - "network. The fully connected layers are split into two classes;\n", - "FullyConnectedLayer which acts as a hidden layer, and OutputLayer,\n", - "which acts as the single output layer at the end of the CNN. If one\n", - "wishes to use this codebase to construct a normal feed forward neural\n", - "network, it must start with a FlattenLayer due to techincal details\n", - "regarding weight intitialization. However many FullyConnectedLayers\n", - "can be added to the CNN, and in each layer the amount of nodes, which\n", - "activation function and scheduler to use can be specified. In\n", - "practice, the scheduler will be specified in the CNN object\n", - "initialization, and inherited if no other scheduler is specified." - ] - }, - { - "cell_type": "code", - "execution_count": 29, - "id": "20a4a7d1", - "metadata": {}, - "outputs": [], - "source": [ - "class FullyConnectedLayer(Layer):\n", - " # FullyConnectedLayer per default uses LRELU and Adam scheduler\n", - " # with an eta of 0.0001, rho of 0.9 and rho2 of 0.999\n", - " def __init__(\n", - " self,\n", - " nodes: int,\n", - " act_func: Callable = LRELU,\n", - " scheduler: Scheduler = Adam(eta=1e-4, rho=0.9, rho2=0.999),\n", - " seed: int = None,\n", - " ):\n", - " super().__init__(seed)\n", - " self.nodes = nodes\n", - " self.act_func = act_func\n", - " self.scheduler_weight = copy(scheduler)\n", - " self.scheduler_bias = copy(scheduler)\n", - "\n", - " # initiate matrices for later\n", - " self.weights = None\n", - " self.a_matrix = None\n", - " self.z_matrix = None\n", - "\n", - " def _feedforward(self, X_batch):\n", - " # calculate z\n", - " self.z_matrix = X_batch @ self.weights\n", - "\n", - " # calculate a, add bias\n", - " bias = np.ones((X_batch.shape[input_index], 1)) * 0.01\n", - " self.a_matrix = self.act_func(self.z_matrix)\n", - " self.a_matrix = np.hstack([bias, self.a_matrix])\n", - "\n", - " # return a, the input for feedforward in next layer\n", - " return self.a_matrix\n", - "\n", - " def _backpropagate(self, weights_next, delta_term_next, a_previous, lam):\n", - " # take the derivative of the activation function\n", - " activation_derivative = derivate(self.act_func)\n", - "\n", - " # calculate the delta term\n", - " delta_term = (\n", - " weights_next[bias_index:, :] @ delta_term_next.T\n", - " ).T * activation_derivative(self.z_matrix)\n", - "\n", - " # intitiate matrix to store gradient\n", - " # note that we exclude the bias term, which we will calculate later\n", - " gradient_weights = np.zeros(\n", - " (\n", - " a_previous.shape[input_index],\n", - " a_previous.shape[node_index] - bias_index,\n", - " delta_term.shape[node_index],\n", - " )\n", - " )\n", - "\n", - " # calculate gradient = delta term * previous a\n", - " for i in range(len(delta_term)):\n", - " gradient_weights[i, :, :] = np.outer(\n", - " a_previous[i, bias_index:], delta_term[i, :]\n", - " )\n", - "\n", - " # sum the gradient, divide by input_index\n", - " gradient_weights = np.mean(gradient_weights, axis=input_index)\n", - " # for the bias gradient we do not multiply by previous a\n", - " gradient_bias = np.mean(delta_term, axis=input_index).reshape(\n", - " 1, delta_term.shape[node_index]\n", - " )\n", - "\n", - " # regularization term\n", - " gradient_weights += self.weights[bias_index:, :] * lam\n", - "\n", - " # send gradients into scheduler\n", - " # returns update matrix which will be used to update the weights and bias\n", - " update_matrix = np.vstack(\n", - " [\n", - " self.scheduler_bias.update_change(gradient_bias),\n", - " self.scheduler_weight.update_change(gradient_weights),\n", - " ]\n", - " )\n", - "\n", - " # update weights\n", - " self.weights -= update_matrix\n", - "\n", - " # return weights and delta term, input for backpropagation in previous layer\n", - " return self.weights, delta_term\n", - "\n", - " def _reset_weights(self, previous_nodes):\n", - " # sets seed to remove randomness inbetween runs\n", - " if self.seed is not None:\n", - " np.random.seed(self.seed)\n", - "\n", - " # add bias, initiate random weights\n", - " bias = 1\n", - " self.weights = np.random.randn(previous_nodes + bias, self.nodes)\n", - "\n", - " # returns number of nodes, used for reset_weights in next layer\n", - " return self.nodes\n", - "\n", - " def _reset_scheduler(self):\n", - " # resets scheduler per epoch\n", - " self.scheduler_weight.reset()\n", - " self.scheduler_bias.reset()\n", - "\n", - " def get_prev_a(self):\n", - " # returns a matrix, used in backpropagation\n", - " return self.a_matrix\n", - "\n", - "\n", - "class OutputLayer(FullyConnectedLayer):\n", - " def __init__(\n", - " self,\n", - " nodes: int,\n", - " output_func: Callable = LRELU,\n", - " cost_func: Callable = CostCrossEntropy,\n", - " scheduler: Scheduler = Adam(eta=1e-4, rho=0.9, rho2=0.999),\n", - " seed: int = None,\n", - " ):\n", - " super().__init__(nodes, output_func, copy(scheduler), seed)\n", - " self.cost_func = cost_func\n", - "\n", - " # initiate matrices for later\n", - " self.weights = None\n", - " self.a_matrix = None\n", - " self.z_matrix = None\n", - "\n", - " # decides if the output layer performs binary or multi-class classification\n", - " self._set_pred_format()\n", - "\n", - " def _feedforward(self, X_batch: np.ndarray):\n", - " # calculate a, z\n", - " # note that bias is not added as this would create an extra output class\n", - " self.z_matrix = X_batch @ self.weights\n", - " self.a_matrix = self.act_func(self.z_matrix)\n", - "\n", - " # returns prediction\n", - " return self.a_matrix\n", - "\n", - " def _backpropagate(self, target, a_previous, lam):\n", - " # note that in the OutputLayer the activation function is the output function\n", - " activation_derivative = derivate(self.act_func)\n", - "\n", - " # calculate output delta terms\n", - " # for multi-class or binary classification\n", - " if self.pred_format == \"Multi-class\":\n", - " delta_term = self.a_matrix - target\n", - " else:\n", - " cost_func_derivative = grad(self.cost_func(target))\n", - " delta_term = activation_derivative(self.z_matrix) * cost_func_derivative(\n", - " self.a_matrix\n", - " )\n", - "\n", - " # intiate matrix that stores gradient\n", - " gradient_weights = np.zeros(\n", - " (\n", - " a_previous.shape[input_index],\n", - " a_previous.shape[node_index] - bias_index,\n", - " delta_term.shape[node_index],\n", - " )\n", - " )\n", - "\n", - " # calculate gradient = delta term * previous a\n", - " for i in range(len(delta_term)):\n", - " gradient_weights[i, :, :] = np.outer(\n", - " a_previous[i, bias_index:], delta_term[i, :]\n", - " )\n", - "\n", - " # sum the gradient, divide by input_index\n", - " gradient_weights = np.mean(gradient_weights, axis=input_index)\n", - " # for the bias gradient we do not multiply by previous a\n", - " gradient_bias = np.mean(delta_term, axis=input_index).reshape(\n", - " 1, delta_term.shape[node_index]\n", - " )\n", - "\n", - " # regularization term\n", - " gradient_weights += self.weights[bias_index:, :] * lam\n", - "\n", - " # send gradients into scheduler\n", - " # returns update matrix which will be used to update the weights and bias\n", - " update_matrix = np.vstack(\n", - " [\n", - " self.scheduler_bias.update_change(gradient_bias),\n", - " self.scheduler_weight.update_change(gradient_weights),\n", - " ]\n", - " )\n", - "\n", - " # update weights\n", - " self.weights -= update_matrix\n", - "\n", - " # return weights and delta term, input for backpropagation in previous layer\n", - " return self.weights, delta_term\n", - "\n", - " def _reset_weights(self, previous_nodes):\n", - " # sets seed to remove randomness inbetween runs\n", - " if self.seed is not None:\n", - " np.random.seed(self.seed)\n", - "\n", - " # add bias, initiate random weights\n", - " bias = 1\n", - " self.weights = np.random.rand(previous_nodes + bias, self.nodes)\n", - "\n", - " # returns number of nodes, used for reset_weights in next layer\n", - " return self.nodes\n", - "\n", - " def _reset_scheduler(self):\n", - " # resets scheduler per epoch\n", - " self.scheduler_weight.reset()\n", - " self.scheduler_bias.reset()\n", - "\n", - " def _set_pred_format(self):\n", - " # sets prediction format to either regression, binary or multi-class classification\n", - " if self.act_func.__name__ is None or self.act_func.__name__ == \"identity\":\n", - " self.pred_format = \"Regression\"\n", - " elif self.act_func.__name__ == \"sigmoid\" or self.act_func.__name__ == \"tanh\":\n", - " self.pred_format = \"Binary\"\n", - " else:\n", - " self.pred_format = \"Multi-class\"\n", - "\n", - " def get_pred_format(self):\n", - " # returns format of prediction\n", - " return self.pred_format" - ] - }, - { - "cell_type": "markdown", - "id": "f02f8704", - "metadata": {}, - "source": [ - "### Optimized Convolution2DLayer\n", - "\n", - "For our CNN, we have also implemented an optimized version of the\n", - "Convolution2DLayer, Convolution2DLayerOPT, which runs much faster. See\n", - "VII. Remarks for discussion. This layer will per default be used by\n", - "the CNN due to its computational advantages, but is much less\n", - "readable. We've documented it such that specially interested students\n", - "can understand the principles behind it, but it is not recommended to\n", - "read. In short, we reshape and transpose parts of the image such that\n", - "the convolutional operation can be swapped out for a simple matrix\n", - "multiplication." - ] - }, - { - "cell_type": "code", - "execution_count": 30, - "id": "abe01496", - "metadata": {}, - "outputs": [], - "source": [ - "class Convolution2DLayerOPT(Convolution2DLayer):\n", - " \"\"\"\n", - " Am optimized version of the convolution layer above which\n", - " utilizes an approach of extracting windows of size equivalent\n", - " in size to the filter. The convoution is then performed on those\n", - " windows instead of a full feature map.\n", - " \"\"\"\n", - "\n", - " def __init__(\n", - " self,\n", - " input_channels,\n", - " feature_maps,\n", - " kernel_height,\n", - " kernel_width,\n", - " v_stride,\n", - " h_stride,\n", - " pad,\n", - " act_func: Callable,\n", - " seed=None,\n", - " reset_weights_independently=True,\n", - " ):\n", - " super().__init__(\n", - " input_channels,\n", - " feature_maps,\n", - " kernel_height,\n", - " kernel_width,\n", - " v_stride,\n", - " h_stride,\n", - " pad,\n", - " act_func,\n", - " seed,\n", - " )\n", - " # true if layer is used outside of CNN\n", - " if reset_weights_independently == True:\n", - " self._reset_weights_independently()\n", - "\n", - " def _feedforward(self, X_batch):\n", - " # The optimized _feedforward method is difficult to understand but computationally more efficient\n", - " # for a more \"by the book\" approach, please look at the _feedforward method of Convolution2DLayer\n", - "\n", - " # save the input for backpropagation\n", - " self.X_batch_feedforward = X_batch\n", - "\n", - " # check that there are the correct amount of input channels\n", - " self._check_for_errors()\n", - "\n", - " # calculate new shape after stride\n", - " strided_height = int(np.ceil(X_batch.shape[height_index] / self.v_stride))\n", - " strided_width = int(np.ceil(X_batch.shape[width_index] / self.h_stride))\n", - "\n", - " # get windows of the image for more computationally efficient convolution\n", - " # the idea is that we want to align the dimensions that we wish to matrix\n", - " # multiply, then use a simple matrix multiplication instead of convolution.\n", - " # then, we reshape the size back to its intended shape\n", - " windows = self._extract_windows(X_batch)\n", - " windows = windows.transpose(1, 0, 2, 3, 4).reshape(\n", - " X_batch.shape[input_index],\n", - " strided_height * strided_width,\n", - " -1,\n", - " )\n", - "\n", - " # reshape the kernel for more computationally efficient convolution\n", - " kernel = self.kernel\n", - " kernel = kernel.transpose(0, 2, 3, 1).reshape(\n", - " kernel.shape[kernel_input_channels_index]\n", - " * kernel.shape[height_index]\n", - " * kernel.shape[width_index],\n", - " -1,\n", - " )\n", - "\n", - " # use simple matrix calculation to obtain output\n", - " output = (\n", - " (windows @ kernel)\n", - " .reshape(\n", - " X_batch.shape[input_index],\n", - " strided_height,\n", - " strided_width,\n", - " -1,\n", - " )\n", - " .transpose(0, 3, 1, 2)\n", - " )\n", - "\n", - " # The output is reshaped and rearranged to appropriate shape\n", - " return self.act_func(\n", - " output / (self.kernel_height * X_batch.shape[feature_maps_index])\n", - " )\n", - "\n", - " def _backpropagate(self, delta_term_next):\n", - " # The optimized _backpropagate method is difficult to understand but computationally more efficient\n", - " # for a more \"by the book\" approach, please look at the _backpropagate method of Convolution2DLayer\n", - " act_derivative = derivate(self.act_func)\n", - " delta_term_next = act_derivative(delta_term_next)\n", - "\n", - " # calculate strided dimensions\n", - " strided_height = int(\n", - " np.ceil(self.X_batch_feedforward.shape[height_index] / self.v_stride)\n", - " )\n", - " strided_width = int(\n", - " np.ceil(self.X_batch_feedforward.shape[width_index] / self.h_stride)\n", - " )\n", - "\n", - " # copy kernel\n", - " kernel = self.kernel\n", - "\n", - " # get windows, reshape for matrix multiplication\n", - " windows = self._extract_windows(self.X_batch_feedforward, \"image\").reshape(\n", - " self.X_batch_feedforward.shape[input_index]\n", - " * strided_height\n", - " * strided_width,\n", - " -1,\n", - " )\n", - "\n", - " # initialize output gradient, reshape and transpose into correct shape\n", - " # for matrix multiplication\n", - " output_grad_tr = delta_term_next.transpose(0, 2, 3, 1).reshape(\n", - " self.X_batch_feedforward.shape[input_index]\n", - " * strided_height\n", - " * strided_width,\n", - " -1,\n", - " )\n", - "\n", - " # calculate gradient kernel via simple matrix multiplication and reshaping\n", - " gradient_kernel = (\n", - " (windows.T @ output_grad_tr)\n", - " .reshape(\n", - " kernel.shape[kernel_input_channels_index],\n", - " kernel.shape[height_index],\n", - " kernel.shape[width_index],\n", - " kernel.shape[kernel_feature_maps_index],\n", - " )\n", - " .transpose(0, 3, 1, 2)\n", - " )\n", - "\n", - " # for computing the input gradient\n", - " windows_out, upsampled_height, upsampled_width = self._extract_windows(\n", - " delta_term_next, \"grad\"\n", - " )\n", - "\n", - " # calculate new window dimensions\n", - " new_windows_first_dim = (\n", - " self.X_batch_feedforward.shape[input_index]\n", - " * upsampled_height\n", - " * upsampled_width\n", - " )\n", - " # ceil allows for various asymmetric kernels\n", - " new_windows_sec_dim = int(np.ceil(windows_out.size / new_windows_first_dim))\n", - "\n", - " # reshape for matrix multiplication\n", - " windows_out = windows_out.transpose(1, 0, 2, 3, 4).reshape(\n", - " new_windows_first_dim, new_windows_sec_dim\n", - " )\n", - "\n", - " # reshape for matrix multiplication\n", - " kernel_reshaped = kernel.reshape(self.input_channels, -1)\n", - "\n", - " # calculating input gradient for next convolutional layer\n", - " input_grad = (windows_out @ kernel_reshaped.T).reshape(\n", - " self.X_batch_feedforward.shape[input_index],\n", - " upsampled_height,\n", - " upsampled_width,\n", - " kernel.shape[kernel_input_channels_index],\n", - " )\n", - " input_grad = input_grad.transpose(0, 3, 1, 2)\n", - "\n", - " # Update the weights in the kernel\n", - " self.kernel -= gradient_kernel\n", - "\n", - " # Output the gradient to propagate backwards\n", - " return input_grad\n", - "\n", - " def _extract_windows(self, X_batch, batch_type=\"image\"):\n", - " \"\"\"\n", - " Receives as input the X_batch with shape (inputs, feature_maps, image_height, image_width)\n", - " and extract windows of size kernel_height * kernel_width for every image and every feature_map.\n", - " It then returns an np.ndarray of shape (image_height * image_width, inputs, feature_maps, kernel_height, kernel_width)\n", - " which will be used either to filter the images in feedforward or to calculate the gradient.\n", - " \"\"\"\n", - "\n", - " # initialize list of windows\n", - " windows = []\n", - "\n", - " if batch_type == \"image\":\n", - " # pad the images\n", - " X_batch_padded = self._padding(X_batch, batch_type=\"image\")\n", - " img_height, img_width = X_batch_padded.shape[2:]\n", - " # For each location in the image...\n", - " for h in range(\n", - " 0,\n", - " X_batch.shape[height_index],\n", - " self.v_stride,\n", - " ):\n", - " for w in range(\n", - " 0,\n", - " X_batch.shape[width_index],\n", - " self.h_stride,\n", - " ):\n", - " # ...obtain an image patch of the original size (strided)\n", - "\n", - " # get window\n", - " window = X_batch_padded[\n", - " :,\n", - " :,\n", - " h : h + self.kernel_height,\n", - " w : w + self.kernel_width,\n", - " ]\n", - "\n", - " # append to list of windows\n", - " windows.append(window)\n", - "\n", - " # return numpy array instead of list\n", - " return np.stack(windows)\n", - "\n", - " # In order to be able to perform backprogagation by the method of window extraction,\n", - " # here is a modified approach to extracting the windows which allow for the necessary\n", - " # upsampling of the gradient in case the on of the stride parameters is larger than one.\n", - "\n", - " if batch_type == \"grad\":\n", - "\n", - " # In the case of one of the stride parameters being odd, we have to take some\n", - " # extra care in calculating the upsampled size of X_batch. We solve this\n", - " # by simply flooring the result of dividing stride by 2.\n", - " if self.v_stride < 2 or self.v_stride % 2 == 0:\n", - " v_stride = 0\n", - " else:\n", - " v_stride = int(np.floor(self.v_stride / 2))\n", - "\n", - " if self.h_stride < 2 or self.h_stride % 2 == 0:\n", - " h_stride = 0\n", - " else:\n", - " h_stride = int(np.floor(self.h_stride / 2))\n", - "\n", - " upsampled_height = (X_batch.shape[height_index] * self.v_stride) - v_stride\n", - " upsampled_width = (X_batch.shape[width_index] * self.h_stride) - h_stride\n", - "\n", - " # When upsampling, we need to insert rows and columns filled with zeros\n", - " # into each feature map. How many of those we have to insert is purely\n", - " # dependant on the value of stride parameter in the vertical and horizontal\n", - " # direction.\n", - " if self.v_stride > 1:\n", - " v_ind = 1\n", - " for i in range(X_batch.shape[height_index]):\n", - " for j in range(self.v_stride - 1):\n", - " X_batch = np.insert(X_batch, v_ind, 0, axis=height_index)\n", - " v_ind += self.v_stride\n", - "\n", - " if self.h_stride > 1:\n", - " h_ind = 1\n", - " for i in range(X_batch.shape[width_index]):\n", - " for k in range(self.h_stride - 1):\n", - " X_batch = np.insert(X_batch, h_ind, 0, axis=width_index)\n", - " h_ind += self.h_stride\n", - "\n", - " # Since the insertion of zero-filled rows and columns isn't perfect, we have\n", - " # to assure that the resulting feature maps will have the expected upsampled height\n", - " # and width by cutting them og at desired dimensions.\n", - "\n", - " X_batch = X_batch[:, :, :upsampled_height, :upsampled_width]\n", - "\n", - " X_batch_padded = self._padding(X_batch, batch_type=\"grad\")\n", - "\n", - " # initialize list of windows\n", - " windows = []\n", - "\n", - " # For each location in the image...\n", - " for h in range(\n", - " 0,\n", - " X_batch.shape[height_index],\n", - " self.v_stride,\n", - " ):\n", - " for w in range(\n", - " 0,\n", - " X_batch.shape[width_index],\n", - " self.h_stride,\n", - " ):\n", - " # ...obtain an image patch of the original size (strided)\n", - "\n", - " # get window\n", - " window = X_batch_padded[\n", - " :, :, h : h + self.kernel_height, w : w + self.kernel_width\n", - " ]\n", - "\n", - " # append window to list\n", - " windows.append(window)\n", - "\n", - " # return numpy array, unsampled dimensions\n", - " return np.stack(windows), upsampled_height, upsampled_width\n", - "\n", - " def _check_for_errors(self):\n", - " # compares input channels of data to input channels of Convolution2DLayer\n", - " if self.X_batch_feedforward.shape[input_channel_index] != self.input_channels:\n", - " raise AssertionError(\n", - " f\"ERROR: Number of input channels in data ({self.X_batch_feedforward.shape[input_channel_index]}) is not equal to input channels in Convolution2DLayerOPT ({self.input_channels})! Please change the number of input channels of the Convolution2DLayer such that they are equal\"\n", - " )" - ] - }, - { - "cell_type": "markdown", - "id": "d9317467", - "metadata": {}, - "source": [ - "### The Convolutional Neural Network (CNN)\n", - "\n", - "Finally, we present the code for the CNN. The CNN class organizes all the layers, and allows for training on image data." - ] - }, - { - "cell_type": "code", - "execution_count": 31, - "id": "dea10f08", - "metadata": {}, - "outputs": [], - "source": [ - "import math\n", - "import autograd.numpy as np\n", - "import sys\n", - "import warnings\n", - "from autograd import grad, elementwise_grad\n", - "from random import random, seed\n", - "from copy import deepcopy\n", - "from typing import Tuple, Callable\n", - "from sklearn.utils import resample\n", - "\n", - "warnings.simplefilter(\"error\")\n", - "\n", - "\n", - "class CNN:\n", - " def __init__(\n", - " self,\n", - " cost_func: Callable = CostCrossEntropy,\n", - " scheduler: Scheduler = Adam(eta=1e-4, rho=0.9, rho2=0.999),\n", - " seed: int = None,\n", - " ):\n", - " \"\"\"\n", - " Description:\n", - " ------------\n", - " Instantiates CNN object\n", - "\n", - " Parameters:\n", - " ------------\n", - " I output_func (costFunctions) cost function for feed forward neural network part of CNN,\n", - " such as \"CostLogReg\", \"CostOLS\" or \"CostCrossEntropy\"\n", - "\n", - " II scheduler (Scheduler) optional parameter, default set to Adam. Can also be set to other\n", - " schedulers such as AdaGrad, Momentum, RMS_prop and Constant. Note that schedulers have\n", - " to be instantiated first with proper parameters (for example eta, rho and rho2 for Adam)\n", - "\n", - " III seed (int) used for seeding all random operations\n", - " \"\"\"\n", - " self.layers = list()\n", - " self.cost_func = cost_func\n", - " self.scheduler = scheduler\n", - " self.schedulers_weight = list()\n", - " self.schedulers_bias = list()\n", - " self.seed = seed\n", - " self.pred_format = None\n", - "\n", - " def add_FullyConnectedLayer(\n", - " self, nodes: int, act_func=LRELU, scheduler=None\n", - " ) -> None:\n", - " \"\"\"\n", - " Description:\n", - " ------------\n", - " Add a FullyConnectedLayer to the CNN, i.e. a hidden layer in the feed forward neural\n", - " network part of the CNN. Often called a Dense layer in literature\n", - "\n", - " Parameters:\n", - " ------------\n", - " I nodes (int) number of nodes in FullyConnectedLayer\n", - " II act_func (activationFunctions) activation function of FullyConnectedLayer,\n", - " such as \"sigmoid\", \"RELU\", \"LRELU\", \"softmax\" or \"identity\"\n", - " III scheduler (Scheduler) optional parameter, default set to Adam. Can also be set to other\n", - " schedulers such as AdaGrad, Momentum, RMS_prop and Constant\n", - " \"\"\"\n", - " assert self.layers, \"FullyConnectedLayer should follow FlattenLayer in CNN\"\n", - "\n", - " if scheduler is None:\n", - " scheduler = self.scheduler\n", - "\n", - " layer = FullyConnectedLayer(nodes, act_func, scheduler, self.seed)\n", - " self.layers.append(layer)\n", - "\n", - " def add_OutputLayer(self, nodes: int, output_func=sigmoid, scheduler=None) -> None:\n", - " \"\"\"\n", - " Description:\n", - " ------------\n", - " Add an OutputLayer to the CNN, i.e. a the final layer in the feed forward neural\n", - " network part of the CNN\n", - "\n", - " Parameters:\n", - " ------------\n", - " I nodes (int) number of nodes in OutputLayer. Set nodes=1 for binary classification and\n", - " nodes = number of classes for multi-class classification\n", - " II output_func (activationFunctions) activation function for the output layer, such as\n", - " \"identity\" for regression, \"sigmoid\" for binary classification and \"softmax\" for multi-class\n", - " classification\n", - " III scheduler (Scheduler) optional parameter, default set to Adam. Can also be set to other\n", - " schedulers such as AdaGrad, Momentum, RMS_prop and Constant\n", - " \"\"\"\n", - " assert self.layers, \"OutputLayer should follow FullyConnectedLayer in CNN\"\n", - "\n", - " if scheduler is None:\n", - " scheduler = self.scheduler\n", - "\n", - " output_layer = OutputLayer(\n", - " nodes, output_func, self.cost_func, scheduler, self.seed\n", - " )\n", - " self.layers.append(output_layer)\n", - " self.pred_format = output_layer.get_pred_format()\n", - "\n", - " def add_FlattenLayer(self, act_func=LRELU) -> None:\n", - " \"\"\"\n", - " Description:\n", - " ------------\n", - " Add a FlattenLayer to the CNN, which flattens the image data such that it is formatted to\n", - " be used in the feed forward neural network part of the CNN\n", - " \"\"\"\n", - " self.layers.append(FlattenLayer(act_func=act_func, seed=self.seed))\n", - "\n", - " def add_Convolution2DLayer(\n", - " self,\n", - " input_channels=1,\n", - " feature_maps=1,\n", - " kernel_height=3,\n", - " kernel_width=3,\n", - " v_stride=1,\n", - " h_stride=1,\n", - " pad=\"same\",\n", - " act_func=LRELU,\n", - " optimized=True,\n", - " ) -> None:\n", - " \"\"\"\n", - " Description:\n", - " ------------\n", - " Add a Convolution2DLayer to the CNN, i.e. a convolutional layer with a 2 dimensional kernel. Should be\n", - " the first layer added to the CNN\n", - "\n", - " Parameters:\n", - " ------------\n", - " I input_channels (int) specifies amount of input channels. For monochrome images, use input_channels\n", - " = 1, and input_channels = 3 for colored images, where each channel represents one of R, G and B\n", - " II feature_maps (int) amount of feature maps in CNN\n", - " III kernel_height (int) height of the kernel, also called 'convolutional filter' in literature\n", - " IV kernel_width (int) width of the kernel, also called 'convolutional filter' in literature\n", - " V v_stride (int) value of vertical stride for dimentionality reduction\n", - " VI h_stride (int) value of horizontal stride for dimentionality reduction\n", - " VII pad (str) default = \"same\" ensures output size is the same as input size (given stride=1)\n", - " VIII act_func (activationFunctions) default = \"LRELU\", nonlinear activation function\n", - " IX optimized (bool) default = True, uses Convolution2DLayerOPT if True which is much faster when\n", - " compared to Convolution2DLayer, which is a more straightforward, understandable implementation\n", - " \"\"\"\n", - " if optimized:\n", - " conv_layer = Convolution2DLayerOPT(\n", - " input_channels,\n", - " feature_maps,\n", - " kernel_height,\n", - " kernel_width,\n", - " v_stride,\n", - " h_stride,\n", - " pad,\n", - " act_func,\n", - " self.seed,\n", - " reset_weights_independently=False,\n", - " )\n", - " else:\n", - " conv_layer = Convolution2DLayer(\n", - " input_channels,\n", - " feature_maps,\n", - " kernel_height,\n", - " kernel_width,\n", - " v_stride,\n", - " h_stride,\n", - " pad,\n", - " act_func,\n", - " self.seed,\n", - " reset_weights_independently=False,\n", - " )\n", - " self.layers.append(conv_layer)\n", - "\n", - " def add_PoolingLayer(\n", - " self, kernel_height=2, kernel_width=2, v_stride=1, h_stride=1, pooling=\"max\"\n", - " ) -> None:\n", - " \"\"\"\n", - " Description:\n", - " ------------\n", - " Add a Pooling2DLayer to the CNN, i.e. a pooling layer that reduces the dimentionality of\n", - " the image data. It is not necessary to use a Pooling2DLayer when creating a CNN, but it\n", - " can be used to speed up the training\n", - "\n", - " Parameters:\n", - " ------------\n", - " I kernel_height (int) height of the kernel used for pooling\n", - " II kernel_width (int) width of the kernel used for pooling\n", - " III v_stride (int) value of vertical stride for dimentionality reduction\n", - " IV h_stride (int) value of horizontal stride for dimentionality reduction\n", - " V pooling (str) either \"max\" or \"average\", describes type of pooling performed\n", - " \"\"\"\n", - " pooling_layer = Pooling2DLayer(\n", - " kernel_height, kernel_width, v_stride, h_stride, pooling, self.seed\n", - " )\n", - " self.layers.append(pooling_layer)\n", - "\n", - " def fit(\n", - " self,\n", - " X: np.ndarray,\n", - " t: np.ndarray,\n", - " epochs: int = 100,\n", - " lam: float = 0,\n", - " batches: int = 1,\n", - " X_val: np.ndarray = None,\n", - " t_val: np.ndarray = None,\n", - " ) -> dict:\n", - " \"\"\"\n", - " Description:\n", - " ------------\n", - " Fits the CNN to input X for a given amount of epochs. Performs feedforward and backpropagation passes,\n", - " can utilize batches, regulariziation and validation if desired.\n", - "\n", - " Parameters:\n", - " ------------\n", - " X (numpy array) with input data in format [images, input channels,\n", - " image height, image_width]\n", - " t (numpy array) target labels for input data\n", - " epochs (int) amount of epochs\n", - " lam (float) regulariziation term lambda\n", - " batches (int) amount of batches input data splits into\n", - " X_val (numpy array) validation data\n", - " t_val (numpy array) target labels for validation data\n", - "\n", - " Returns:\n", - " ------------\n", - " scores (dict) a dictionary with \"train_error\", \"train_acc\", \"val_error\", val_acc\" keys\n", - " that contain numpy arrays with float values of all accuracies/errors over all epochs.\n", - " Can be used to create plots. Also used to update the progress bar during training\n", - " \"\"\"\n", - "\n", - " # setup\n", - " if self.seed is not None:\n", - " np.random.seed(self.seed)\n", - "\n", - " # initialize weights\n", - " self._initialize_weights(X)\n", - "\n", - " # create arrays for score metrics\n", - " scores = self._initialize_scores(epochs)\n", - "\n", - " assert batches <= t.shape[0]\n", - " batch_size = X.shape[0] // batches\n", - "\n", - " try:\n", - " for epoch in range(epochs):\n", - " for batch in range(batches):\n", - " # minibatch gradient descent\n", - " # If the for loop has reached the last batch, take all thats left\n", - " if batch == batches - 1:\n", - " X_batch = X[batch * batch_size :, :, :, :]\n", - " t_batch = t[batch * batch_size :, :]\n", - " else:\n", - " X_batch = X[\n", - " batch * batch_size : (batch + 1) * batch_size, :, :, :\n", - " ]\n", - " t_batch = t[batch * batch_size : (batch + 1) * batch_size, :]\n", - "\n", - " self._feedforward(X_batch)\n", - " self._backpropagate(t_batch, lam)\n", - "\n", - " # reset schedulers for each epoch (some schedulers pass in this call)\n", - " for layer in self.layers:\n", - " if isinstance(layer, FullyConnectedLayer):\n", - " layer._reset_scheduler()\n", - "\n", - " # computing performance metrics\n", - " scores = self._compute_scores(scores, epoch, X, t, X_val, t_val)\n", - "\n", - " # printing progress bar\n", - " print_length = self._progress_bar(\n", - " epoch,\n", - " epochs,\n", - " scores,\n", - " )\n", - " # allows for stopping training at any point and seeing the result\n", - " except KeyboardInterrupt:\n", - " pass\n", - "\n", - " # visualization of training progression (similiar to tensorflow progression bar)\n", - " sys.stdout.write(\"\\r\" + \" \" * print_length)\n", - " sys.stdout.flush()\n", - " self._progress_bar(\n", - " epochs,\n", - " epochs,\n", - " scores,\n", - " )\n", - " sys.stdout.write(\"\")\n", - "\n", - " return scores\n", - "\n", - " def _feedforward(self, X_batch) -> np.ndarray:\n", - " \"\"\"\n", - " Description:\n", - " ------------\n", - " Performs the feedforward pass for all layers in the CNN. Called from fit()\n", - " \"\"\"\n", - " a = X_batch\n", - " for layer in self.layers:\n", - " a = layer._feedforward(a)\n", - "\n", - " return a\n", - "\n", - " def _backpropagate(self, t_batch, lam) -> None:\n", - " \"\"\"\n", - " Description:\n", - " ------------\n", - " Performs backpropagation for all layers in the CNN. Called from fit()\n", - " \"\"\"\n", - " assert len(self.layers) >= 2\n", - " reversed_layers = self.layers[::-1]\n", - "\n", - " # for every layer, backwards\n", - " for i in range(len(reversed_layers) - 1):\n", - " layer = reversed_layers[i]\n", - " prev_layer = reversed_layers[i + 1]\n", - "\n", - " # OutputLayer\n", - " if isinstance(layer, OutputLayer):\n", - " prev_a = prev_layer.get_prev_a()\n", - " weights_next, delta_next = layer._backpropagate(t_batch, prev_a, lam)\n", - "\n", - " # FullyConnectedLayer\n", - " elif isinstance(layer, FullyConnectedLayer):\n", - " assert (\n", - " delta_next is not None\n", - " ), \"No OutputLayer to follow FullyConnectedLayer\"\n", - " assert (\n", - " weights_next is not None\n", - " ), \"No OutputLayer to follow FullyConnectedLayer\"\n", - " prev_a = prev_layer.get_prev_a()\n", - " weights_next, delta_next = layer._backpropagate(\n", - " weights_next, delta_next, prev_a, lam\n", - " )\n", - "\n", - " # FlattenLayer\n", - " elif isinstance(layer, FlattenLayer):\n", - " assert (\n", - " delta_next is not None\n", - " ), \"No FullyConnectedLayer to follow FlattenLayer\"\n", - " assert (\n", - " weights_next is not None\n", - " ), \"No FullyConnectedLayer to follow FlattenLayer\"\n", - " delta_next = layer._backpropagate(weights_next, delta_next)\n", - "\n", - " # Convolution2DLayer and Convolution2DLayerOPT\n", - " elif isinstance(layer, Convolution2DLayer):\n", - " assert (\n", - " delta_next is not None\n", - " ), \"No FlattenLayer to follow Convolution2DLayer\"\n", - " delta_next = layer._backpropagate(delta_next)\n", - "\n", - " # Pooling2DLayer\n", - " elif isinstance(layer, Pooling2DLayer):\n", - " assert delta_next is not None, \"No Layer to follow Pooling2DLayer\"\n", - " delta_next = layer._backpropagate(delta_next)\n", - "\n", - " # Catch error\n", - " else:\n", - " raise NotImplementedError\n", - "\n", - " def _compute_scores(\n", - " self,\n", - " scores: dict,\n", - " epoch: int,\n", - " X: np.ndarray,\n", - " t: np.ndarray,\n", - " X_val: np.ndarray,\n", - " t_val: np.ndarray,\n", - " ) -> dict:\n", - " \"\"\"\n", - " Description:\n", - " ------------\n", - " Computes scores such as training error, training accuracy, validation error\n", - " and validation accuracy for the CNN depending on if a validation set is used\n", - " and if the CNN performs classification or regression\n", - "\n", - " Returns:\n", - " ------------\n", - " scores (dict) a dictionary with \"train_error\", \"train_acc\", \"val_error\", val_acc\" keys\n", - " that contain numpy arrays with float values of all accuracies/errors over all epochs.\n", - " Can be used to create plots. Also used to update the progress bar during training\n", - " \"\"\"\n", - "\n", - " pred_train = self.predict(X)\n", - " cost_function_train = self.cost_func(t)\n", - " train_error = cost_function_train(pred_train)\n", - " scores[\"train_error\"][epoch] = train_error\n", - "\n", - " if X_val is not None and t_val is not None:\n", - " cost_function_val = self.cost_func(t_val)\n", - " pred_val = self.predict(X_val)\n", - " val_error = cost_function_val(pred_val)\n", - " scores[\"val_error\"][epoch] = val_error\n", - "\n", - " if self.pred_format != \"Regression\":\n", - " train_acc = self._accuracy(pred_train, t)\n", - " scores[\"train_acc\"][epoch] = train_acc\n", - " if X_val is not None and t_val is not None:\n", - " val_acc = self._accuracy(pred_val, t_val)\n", - " scores[\"val_acc\"][epoch] = val_acc\n", - "\n", - " return scores\n", - "\n", - " def _initialize_scores(self, epochs) -> dict:\n", - " \"\"\"\n", - " Description:\n", - " ------------\n", - " Initializes scores such as training error, training accuracy, validation error\n", - " and validation accuracy for the CNN\n", - "\n", - " Returns:\n", - " ------------\n", - " A dictionary with \"train_error\", \"train_acc\", \"val_error\", val_acc\" keys that\n", - " will contain numpy arrays with float values of all accuracies/errors over all epochs\n", - " when passed through the _compute_scores() function during fit()\n", - " \"\"\"\n", - " scores = dict()\n", - "\n", - " train_errors = np.empty(epochs)\n", - " train_errors.fill(np.nan)\n", - " val_errors = np.empty(epochs)\n", - " val_errors.fill(np.nan)\n", - "\n", - " train_accs = np.empty(epochs)\n", - " train_accs.fill(np.nan)\n", - " val_accs = np.empty(epochs)\n", - " val_accs.fill(np.nan)\n", - "\n", - " scores[\"train_error\"] = train_errors\n", - " scores[\"val_error\"] = val_errors\n", - " scores[\"train_acc\"] = train_accs\n", - " scores[\"val_acc\"] = val_accs\n", - "\n", - " return scores\n", - "\n", - " def _initialize_weights(self, X: np.ndarray) -> None:\n", - " \"\"\"\n", - " Description:\n", - " ------------\n", - " Initializes weights for all layers in CNN\n", - "\n", - " Parameters:\n", - " ------------\n", - " I X (np.ndarray) input of format [img, feature_maps, height, width]\n", - " \"\"\"\n", - " prev_nodes = X\n", - " for layer in self.layers:\n", - " prev_nodes = layer._reset_weights(prev_nodes)\n", - "\n", - " def predict(self, X: np.ndarray, *, threshold=0.5) -> np.ndarray:\n", - " \"\"\"\n", - " Description:\n", - " ------------\n", - " Predicts output of input X\n", - "\n", - " Parameters:\n", - " ------------\n", - " I X (np.ndarray) input [img, feature_maps, height, width]\n", - " \"\"\"\n", - "\n", - " prediction = self._feedforward(X)\n", - "\n", - " if self.pred_format == \"Binary\":\n", - " return np.where(prediction > threshold, 1, 0)\n", - " elif self.pred_format == \"Multi-class\":\n", - " class_prediction = np.zeros(prediction.shape)\n", - " for i in range(prediction.shape[0]):\n", - " class_prediction[i, np.argmax(prediction[i, :])] = 1\n", - " return class_prediction\n", - " else:\n", - " return prediction\n", - "\n", - " def _accuracy(self, prediction: np.ndarray, target: np.ndarray) -> float:\n", - " \"\"\"\n", - " Description:\n", - " ------------\n", - " Calculates accuracy of given prediction to target\n", - "\n", - " Parameters:\n", - " ------------\n", - " I prediction (np.ndarray): output of predict() fuction\n", - " (1s and 0s in case of classification, and real numbers in case of regression)\n", - " II target (np.ndarray): vector of true values (What the network should predict)\n", - "\n", - " Returns:\n", - " ------------\n", - " A floating point number representing the percentage of correctly classified instances.\n", - " \"\"\"\n", - " assert prediction.size == target.size\n", - " return np.average((target == prediction))\n", - "\n", - " def _progress_bar(self, epoch: int, epochs: int, scores: dict) -> int:\n", - " \"\"\"\n", - " Description:\n", - " ------------\n", - " Displays progress of training\n", - " \"\"\"\n", - " progression = epoch / epochs\n", - " epoch -= 1\n", - " print_length = 40\n", - " num_equals = int(progression * print_length)\n", - " num_not = print_length - num_equals\n", - " arrow = \">\" if num_equals > 0 else \"\"\n", - " bar = \"[\" + \"=\" * (num_equals - 1) + arrow + \"-\" * num_not + \"]\"\n", - " perc_print = self._fmt(progression * 100, N=5)\n", - " line = f\" {bar} {perc_print}% \"\n", - "\n", - " for key, score in scores.items():\n", - " if np.isnan(score[epoch]) == False:\n", - " value = self._fmt(score[epoch], N=4)\n", - " line += f\"| {key}: {value} \"\n", - " print(line, end=\"\\r\")\n", - " return len(line)\n", - "\n", - " def _fmt(self, value: int, N=4) -> str:\n", - " \"\"\"\n", - " Description:\n", - " ------------\n", - " Formats decimal numbers for progress bar\n", - " \"\"\"\n", - " if value > 0:\n", - " v = value\n", - " elif value < 0:\n", - " v = -10 * value\n", - " else:\n", - " v = 1\n", - " n = 1 + math.floor(math.log10(v))\n", - " if n >= N - 1:\n", - " return str(round(value))\n", - " # or overflow\n", - " return f\"{value:.{N-n-1}f}\"" - ] - }, - { - "cell_type": "markdown", - "id": "e7315a76", - "metadata": {}, - "source": [ - "### Usage of CNN code\n", - "\n", - "Using the CNN codebase is very simple. We begin by initiating a CNN\n", - "object, which takes a cost function, a scheduler and a seed as its\n", - "arguments. If a scheduler is not provided, it will per default\n", - "initiate an Adam scheduler with eta=1e-4, and if a seed is not\n", - "provided, the CNN will not be seeded, meaning it will run with a\n", - "different random seed every run. Below we demonstrate an initiation of\n", - "our CNN." - ] - }, - { - "cell_type": "code", - "execution_count": 32, - "id": "8fcf6203", - "metadata": {}, - "outputs": [], - "source": [ - "adam_scheduler = Adam(eta=1e-3, rho=0.9, rho2=0.999)\n", - "cnn = CNN(cost_func=CostCrossEntropy, scheduler=adam_scheduler, seed=2023)" - ] - }, - { - "cell_type": "markdown", - "id": "4a2a562a", - "metadata": {}, - "source": [ - "Now that we have our CNN object, we can begin to add layers to it!\n", - "Many of the add_layer functions have default values, for example\n", - "add_Convolution2DLayer() has a default v_stride and h_stride of\n", - "1. However, these can of course be set to any value you please. Note\n", - "that the input channels of a subsequent convolutional layer must equal\n", - "the previous convolutional layer's feature maps." - ] - }, - { - "cell_type": "code", - "execution_count": 33, - "id": "db3f1eb5", - "metadata": {}, - "outputs": [], - "source": [ - "cnn.add_Convolution2DLayer(\n", - " input_channels=1,\n", - " feature_maps=1,\n", - " kernel_height=3,\n", - " kernel_width=3,\n", - " act_func=LRELU,\n", - ")\n", - "\n", - "cnn.add_FlattenLayer()\n", - "\n", - "cnn.add_FullyConnectedLayer(30, LRELU)\n", - "\n", - "cnn.add_FullyConnectedLayer(20, LRELU)\n", - "\n", - "cnn.add_OutputLayer(10, softmax)" - ] - }, - { - "cell_type": "markdown", - "id": "b7303b63", - "metadata": {}, - "source": [ - "Here we have created a CNN with the following architecture:\n", - "\n", - "1. A convolutional layer with 1 input channel, with a kernel height of 2 and a width of 2, which uses LRELU as its non-linearity function. This layer outputs 1 feature map, which feed into the subsequent layer.\n", - "\n", - "2. A flatten layer\n", - "\n", - "3. A hidden layer with 30 nodes, with LRELU as its activation function\n", - "\n", - "4. Another hidden layer but with 20 nodes\n", - "\n", - "5. The output layer, with softmax as its activation function and 10 nodes. We use 10 nodes because we will be using a dataset with 10 classes.\n", - "\n", - "Now, before we can train the model, we need to load in our data. We\n", - "will use the MNIST dataset and use 10000 $28 \\times 28 images$." - ] - }, - { - "cell_type": "code", - "execution_count": 34, - "id": "f1403d34", - "metadata": {}, - "outputs": [], - "source": [ - "from sklearn.datasets import fetch_openml\n", - "from sklearn.model_selection import train_test_split\n", - "\n", - "def onehot(target: np.ndarray):\n", - " onehot = np.zeros((target.size, target.max() + 1))\n", - " onehot[np.arange(target.size), target] = 1\n", - " return onehot\n", - "\n", - "# get dataset\n", - "dataset = fetch_openml(\"mnist_784\", parser=\"auto\")\n", - "mnist = dataset.data.to_numpy(dtype=\"float\")[:10000, :]\n", - "\n", - "# scale data\n", - "for i in range(mnist.shape[1]):\n", - " mnist[:, i] /= 255\n", - " \n", - "# reshape to add single input channel to data shape [inputs, input_channels, height, width]\n", - "mnist = mnist.reshape(mnist.shape[0], 1, 28, 28)\n", - "\n", - "# one hot encode target as we are doing multi-class classification\n", - "target = onehot(np.array([int(i) for i in dataset.target.to_numpy()[:10000]]))\n", - "\n", - "# split into training and validation data\n", - "x_train, x_val, y_train, y_val = train_test_split(mnist, target)" - ] - }, - { - "cell_type": "markdown", - "id": "0d565479", - "metadata": {}, - "source": [ - "Now we may train our model. Note that we can utilize regularization in\n", - "the CNN by using the lam (lambda) parameter in fit(), and utilize\n", - "different types of gradient descent by specifying the amount of\n", - "batches via the batches parameter as shown below.\n", - "\n", - "The functionfit() returns a score dictionary of the training error and\n", - "accuracy (and validation error and accuracy if a validation set is\n", - "provided) which can be used to plot the error and accuracy of the\n", - "model over epochs." - ] - }, - { - "cell_type": "code", - "execution_count": 35, - "id": "7a4f925e", - "metadata": {}, - "outputs": [], - "source": [ - "scores = cnn.fit(\n", - " x_train,\n", - " y_train,\n", - " lam=1e-5,\n", - " batches=10,\n", - " epochs=100,\n", - " X_val=x_val,\n", - " t_val=y_val,\n", - ")\n", - "\n", - "plt.plot(scores[\"train_acc\"], label=\"Training\")\n", - "plt.plot(scores[\"val_acc\"], label=\"Validation\")\n", - "plt.ylim([0.8,1])\n", - "plt.xlabel(\"Epochs\")\n", - "plt.ylabel(\"Accuracy\")\n", - "plt.legend()\n", - "plt.show()" - ] - }, - { - "cell_type": "markdown", - "id": "f896c2cf", - "metadata": {}, - "source": [ - "Considering we only trained the model for 100 epochs without any tuning of the hyperparameters, this result is pretty good.\n", - "\n", - "The codebase allows for great flexibility in CNN\n", - "architectures. Pooling layers can be added before, inbetween or after\n", - "convolutional layers, but due to the great optimizations made within\n", - "Convolution2DLayerOPT, we recommend using the v_stride and h_stride\n", - "parameters in add_Convolution2DLayer() to reduce the dimentionality of\n", - "the problem as the pooling layer is slow in comparison. To use the\n", - "unoptimized version of Convolution2DLayer, simply pass optimized=False\n", - "as an argument in add_Convolution2DLayer().\n", - "\n", - "If one wishes to perform binary classification using the CNN, simply\n", - "use the cost function 'CostLogReg' when initializing the CNN and use 1\n", - "node at the OutputLayer.\n", - "\n", - "Below we have created another, more untraditional architecture using\n", - "our code to demonstrate its flexibility and different attributes such\n", - "as asymmetric stride that might become useful when constructing your\n", - "own CNN." - ] - }, - { - "cell_type": "code", - "execution_count": 36, - "id": "1f785537", - "metadata": {}, - "outputs": [], - "source": [ - "adam_scheduler = Adam(eta=1e-3, rho=0.9, rho2=0.999)\n", - "cnn = CNN(cost_func=CostCrossEntropy, scheduler=adam_scheduler, seed=2023)\n", - "\n", - "cnn.add_Convolution2DLayer(\n", - " input_channels=1,\n", - " feature_maps=7,\n", - " kernel_height=7,\n", - " kernel_width=1,\n", - " act_func=LRELU,\n", - ")\n", - "\n", - "cnn.add_PoolingLayer(\n", - " kernel_height=2,\n", - " kernel_width=2,\n", - " pooling=\"average\",\n", - ")\n", - "\n", - "cnn.add_PoolingLayer(\n", - " kernel_height=2,\n", - " kernel_width=2,\n", - " pooling=\"max\",\n", - ")\n", - "\n", - "cnn.add_Convolution2DLayer(\n", - " input_channels=7,\n", - " feature_maps=1,\n", - " kernel_height=4,\n", - " kernel_width=4,\n", - " v_stride=2,\n", - " h_stride=3,\n", - " act_func=LRELU,\n", - " optimized=False,\n", - ")\n", - "\n", - "cnn.add_Convolution2DLayer(\n", - " input_channels=1,\n", - " feature_maps=1,\n", - " kernel_height=2,\n", - " kernel_width=2,\n", - " act_func=sigmoid,\n", - " optimized=True,\n", - ")\n", - "\n", - "cnn.add_PoolingLayer(\n", - " kernel_height=2,\n", - " kernel_width=2,\n", - " pooling=\"max\"\n", - ")\n", - "\n", - "cnn.add_FlattenLayer()\n", - "\n", - "cnn.add_FullyConnectedLayer(100, LRELU)\n", - "\n", - "cnn.add_FullyConnectedLayer(10, sigmoid)\n", - "\n", - "cnn.add_FullyConnectedLayer(101, identity)\n", - "\n", - "cnn.add_OutputLayer(10, softmax)" - ] - }, - { - "cell_type": "markdown", - "id": "b301a921", - "metadata": {}, - "source": [ - "Here we see the use of asymmetrical 1D kernels such as the $7 \\times\n", - "1$ kernel in the first convolutional layer, both max and average\n", - "pooling, asymmetric stride in the unoptimized convolutional layer,\n", - "more pooling, a flatten layer, a hidden layer with 100 nodes using\n", - "LRELU, another hidden layer with 10 hidden nodes that uses the sigmoid\n", - "activation function, and another hidden layer with 101 nodes which\n", - "utilizes no activation function (identity). Finally, we arrive at the\n", - "output layer with 10 nodes, which uses softmax as its activation\n", - "function." - ] - }, - { - "cell_type": "markdown", - "id": "2820a187", - "metadata": {}, - "source": [ - "### Additional Remarks\n", - "\n", - "The stride parameter controls the distance between each convolution\n", - "and the kernel/filter. If our image is padded, stride is the only\n", - "parameter that determines the size of the output from a convolutional\n", - "layer. However, if we decide not to perform any padding, the size of\n", - "the output feature map depends on both the stride and kernel size. It\n", - "is important to note that neither the stride nor the kernel has to be\n", - "symmetrical. This means that we can use a rectangular filter if we\n", - "choose, and the stride in the vertical direction (axis=0 in Python)\n", - "does not need to be the same as the stride in the horizontal direction\n", - "(axis=1 in Python). It may even be the case that asymmetric\n", - "combinations of stride or kernel dimensions, or both, yield better\n", - "results than symmetric values for these parameters." - ] - }, - { - "cell_type": "code", - "execution_count": 37, - "id": "03397138", - "metadata": {}, - "outputs": [], - "source": [ - "def convolve(image, kernel, stride=1):\n", - " for i in range(2):\n", - " kernel = np.rot90(kernel)\n", - "\n", - " k_half_height = kernel.shape[0] // 2\n", - " k_half_width = kernel.shape[0] // 2\n", - "\n", - " conv_image = np.zeros(image.shape)\n", - " pad_image = padding(image, kernel)\n", - "\n", - " for i in range(k_half_height, conv_image.shape[0] + k_half_height, stride):\n", - " for j in range(k_half_width, conv_image.shape[1] + k_half_width, stride):\n", - " conv_image[i - k_half_height, j - k_half_width] = np.sum(\n", - " pad_image[\n", - " i - k_half_height : i + k_half_height + 1, j - k_half_width : j + k_half_width + 1\n", - " ]\n", - " * kernel\n", - " )\n", - "\n", - " return conv_image" - ] - }, - { - "cell_type": "markdown", - "id": "d880c6e5", - "metadata": {}, - "source": [ - "### Remarks on the speed\n", - "\n", - "Despite the naive convolution algorithm shown above working finely, it\n", - "is extremely slow, requiring approximately 20-30 seconds to process a\n", - "single image. The time complexity of 2D convolution, which is O(NMnm),\n", - "rapidly becomes a constraint and may, at worst, make computations\n", - "infeasible. Consequently, optimizing the naive 2D convolution\n", - "algorithm is a necessity, as the execution time of the algorithm\n", - "significantly increases as the input data size expands. This can pose\n", - "a bottleneck in applications that necessitate real-time processing of\n", - "large data volumes, such as image and video processing, deep learning,\n", - "and scientific simulations.\n", - "\n", - "To address this issue, we shall present two widely used optimization\n", - "techniques: the separable kernel approach and Fast Fourier Transform\n", - "(FFT). Both of these methods can drastically reduce the computational\n", - "complexity of convolution and enhance the overall efficiency of\n", - "processing substantial data quantities. While we shall refrain from\n", - "delving into the intricacies of these algorithms, we strongly\n", - "encourage you to examine at least the application of FFT to optimize\n", - "computations." - ] - }, - { - "cell_type": "markdown", - "id": "508b0369", - "metadata": {}, - "source": [ - "### Convolution using separable kernels" - ] - }, - { - "cell_type": "code", - "execution_count": 38, - "id": "50089042", - "metadata": {}, - "outputs": [], - "source": [ - "def conv2DSep(image, kernel, coef, stride=1, pad=\"zero\"):\n", - " for i in range(2):\n", - " kernel = np.rot90(kernel)\n", - "\n", - " # The kernel is quadratic, thus we only need one of its dimensions\n", - " half_dim = kernel.shape[0] // 2\n", - "\n", - " ker1 = np.array(kernel[0, :])\n", - " ker2 = np.array(kernel[:, 0])\n", - "\n", - " if pad == \"zero\":\n", - " conv_image = np.zeros(image.shape)\n", - " pad_image = padding(image, kernel)\n", - " else:\n", - " conv_image = np.zeros(\n", - " (image.shape[0] - kernel.shape[0], image.shape[1] - kernel.shape[1])\n", - " )\n", - " pad_image = image[:, :]\n", - "\n", - " for i in range(half_dim, conv_image.shape[0] + half_dim, stride):\n", - " for j in range(half_dim, conv_image.shape[1] + half_dim, stride):\n", - " conv_image[i - half_dim, j - half_dim] = (\n", - " pad_image[\n", - " i - half_dim : i + half_dim + 1, j - half_dim : j + half_dim + 1\n", - " ]\n", - " @ ker1\n", - " @ ker2.T\n", - " * coef\n", - " )\n", - "\n", - " return conv_image\n", - "\n", - "img_path = img_path = \"data/IMG-2167.JPG\"\n", - "image_of_cute_dog = imageio.imread(img_path, mode=\"L\")\n", - "start_time = time.time()\n", - "filtered_image = conv2DSep(image_of_cute_dog, kernel=sobel_kernel, coef=1)\n", - "print(f'Time taken for convolution with seperated kernel on 128x128 image {time.time() - start_time}')\n", - "plt.imshow(filtered_image, cmap=\"gray\", vmin=0, vmax=255, aspect=\"auto\")\n", - "plt.show()" - ] - }, - { - "cell_type": "markdown", - "id": "a17d2eea", - "metadata": {}, - "source": [ - "By taking advantage of the capabilities of separable kernels, we can\n", - "effectively cut the computational expense of filtering an image in\n", - "half. Yet, if we seek even more rapid processing, we can turn to the\n", - "Fast Fourier Transform (FFT) algorithm provided by the numpy\n", - "library. By utilizing FFT to transform the input image and filter into\n", - "the frequency domain, we can perform convolution in this domain. This\n", - "approach significantly reduces the number of operations needed and\n", - "results in a marked speedup relative to other convolution\n", - "techniques. In addition, it is worth noting that the FFT is widely\n", - "regarded as one of the most critical algorithms developed to date,\n", - "with applications ranging from digital signal processing to scientific\n", - "computing." - ] - }, - { - "cell_type": "markdown", - "id": "46da3baa", - "metadata": {}, - "source": [ - "### Convolution in the Fourier domain" - ] - }, - { - "cell_type": "code", - "execution_count": 39, - "id": "5e72abeb", - "metadata": {}, - "outputs": [], - "source": [ - "start_time = time.time()\n", - "img_fft = np.fft.fft2(image_of_cute_dog)\n", - "kernel_fft = np.fft.fft2(sobel_kernel, s=image_of_cute_dog.shape)\n", - "\n", - "conv_image = img_fft * kernel_fft\n", - "\n", - "filtered_image = np.fft.ifft2(conv_image)\n", - "print(f'Time take for convolution in the fourier domain: {time.time() - start_time}')\n", - "plt.imshow(filtered_image.real, cmap=\"gray\", vmin=0, vmax=255, aspect=\"auto\")\n", - "plt.show()" - ] - }, - { - "cell_type": "markdown", - "id": "eefbce6f", - "metadata": {}, - "source": [ - "It is evident that executing convolution in the Fourier domain yields\n", - "the quickest computation time. Nonetheless, one should exercise\n", - "caution, particularly when dealing with images of relatively small\n", - "dimensions, as one of the other methods may prove to be more\n", - "expeditious than FFT-enhanced convolution. The overhead involved in\n", - "transferring both the image and filter into the Fourier domain,\n", - "followed by their subsequent transformation back into the spatial\n", - "domain, results in a minor inconvenience. Therefore, it is imperative\n", - "to remain cognizant of this fact when utilizing FFT as the primary\n", - "optimization technique." - ] - } - ], - "metadata": { - "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.9.10" - } - }, - "nbformat": 4, - "nbformat_minor": 5 -} diff --git a/doc/LectureNotes/week45.ipynb b/doc/LectureNotes/week45.ipynb deleted file mode 100644 index d80fa50f3..000000000 --- a/doc/LectureNotes/week45.ipynb +++ /dev/null @@ -1,1997 +0,0 @@ -{ - "cells": [ - { - "cell_type": "markdown", - "id": "967cdaca", - "metadata": { - "editable": true - }, - "source": [ - "\n", - "" - ] - }, - { - "cell_type": "markdown", - "id": "7f44e4d0", - "metadata": { - "editable": true - }, - "source": [ - "# Week 45, Recurrent Neural Networks\n", - "**Morten Hjorth-Jensen**, Department of Physics, University of Oslo and Department of Physics and Astronomy and National Superconducting Cyclotron Laboratory, Michigan State University\n", - "\n", - "Date: **November 6-10**" - ] - }, - { - "cell_type": "markdown", - "id": "3094316d", - "metadata": { - "editable": true - }, - "source": [ - "## Plan for week 45\n", - "\n", - "**Material for the active learning sessions on Tuesday and Wednesday.**\n", - "\n", - " * Discussion of project 2\n", - "\n", - " * [Video of lab session from week 43](https://youtu.be/Ia6wwDLxqtM)\n", - "\n", - " * [Video of lab session from week 44](https://youtu.be/EajWMW__k0I)\n", - "\n", - " * [Video of lab session from week 45](https://youtu.be/tgkj0KAEtZo)\n", - "\n", - " * [See also whiteboard notes from lab session week 44](https://github.com/CompPhysics/MachineLearning/blob/master/doc/HandWrittenNotes/2023/Exercisesweek44.pdf)\n", - "\n", - " \n", - "\n", - "**Material for the lecture on Thursday November 9, 2023.**\n", - "\n", - " * Short repetition on Convolutional Neural Networks\n", - "\n", - " * Recurrent Neural Networks (RNNs)\n", - "\n", - " * Readings and Videos:\n", - "\n", - " * These lecture notes\n", - "\n", - " * [Video of lecture](https://youtu.be/z0x-vgyAZUk)\n", - "\n", - " * [Whiteboard notes](https://github.com/CompPhysics/MachineLearning/blob/master/doc/HandWrittenNotes/2023/NotesNov9.pdf)\n", - "\n", - " * For a more in depth discussion on neural networks we recommend Goodfellow et al chapter 10. See also chapter 11 and 12 on practicalities and applications \n", - "\n", - " * Reading suggestions for implementation of RNNs: [Aurelien Geron's chapter 14](https://github.com/CompPhysics/MachineLearning/blob/master/doc/Textbooks/TensorflowML.pdf).\n", - "\n", - " * [Video on Recurrent Neural Networks from MIT](https://www.youtube.com/watch?v=SEnXr6v2ifU&ab_channel=AlexanderAmini)\n", - "\n", - " * [Video on Deep Learning](https://www.youtube.com/playlist?list=PLZHQObOWTQDNU6R1_67000Dx_ZCJB-3pi)" - ] - }, - { - "cell_type": "markdown", - "id": "46b1e9db", - "metadata": { - "editable": true - }, - "source": [ - "## Material for the lab sessions, additional ways to present classification results and other practicalities" - ] - }, - { - "cell_type": "markdown", - "id": "19315bd5", - "metadata": { - "editable": true - }, - "source": [ - "## Searching for Optimal Regularization Parameters $\\lambda$\n", - "\n", - "In project 1, when using Ridge and Lasso regression, we end up\n", - "searching for the optimal parameter $\\lambda$ which minimizes our\n", - "selected scores (MSE or $R2$ values for example). The brute force\n", - "approach, as discussed in the code here for Ridge regression, consists\n", - "in evaluating the MSE as function of different $\\lambda$ values.\n", - "Based on these calculations, one tries then to determine the value of the hyperparameter $\\lambda$\n", - "which results in optimal scores (for example the smallest MSE or an $R2=1$)." - ] - }, - { - "cell_type": "code", - "execution_count": 1, - "id": "d03a6f44", - "metadata": { - "collapsed": false, - "editable": true - }, - "outputs": [], - "source": [ - "%matplotlib inline\n", - "\n", - "import numpy as np\n", - "import pandas as pd\n", - "import matplotlib.pyplot as plt\n", - "from sklearn.model_selection import train_test_split\n", - "from sklearn import linear_model\n", - "\n", - "def MSE(y_data,y_model):\n", - " n = np.size(y_model)\n", - " return np.sum((y_data-y_model)**2)/n\n", - "# A seed just to ensure that the random numbers are the same for every run.\n", - "# Useful for eventual debugging.\n", - "np.random.seed(2021)\n", - "\n", - "n = 100\n", - "x = np.random.rand(n)\n", - "y = np.exp(-x**2) + 1.5 * np.exp(-(x-2)**2)+ np.random.randn(n)\n", - "\n", - "Maxpolydegree = 5\n", - "X = np.zeros((n,Maxpolydegree-1))\n", - "\n", - "for degree in range(1,Maxpolydegree): #No intercept column\n", - " X[:,degree-1] = x**(degree)\n", - "\n", - "# We split the data in test and training data\n", - "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2)\n", - "\n", - "# Decide which values of lambda to use\n", - "nlambdas = 500\n", - "MSERidgePredict = np.zeros(nlambdas)\n", - "lambdas = np.logspace(-4, 2, nlambdas)\n", - "for i in range(nlambdas):\n", - " lmb = lambdas[i]\n", - " RegRidge = linear_model.Ridge(lmb)\n", - " RegRidge.fit(X_train,y_train)\n", - " ypredictRidge = RegRidge.predict(X_test)\n", - " MSERidgePredict[i] = MSE(y_test,ypredictRidge)\n", - "\n", - "# Now plot the results\n", - "plt.figure()\n", - "plt.plot(np.log10(lambdas), MSERidgePredict, 'g--', label = 'MSE SL Ridge Test')\n", - "plt.xlabel('log10(lambda)')\n", - "plt.ylabel('MSE')\n", - "plt.legend()\n", - "plt.show()" - ] - }, - { - "cell_type": "markdown", - "id": "e6cbd4ca", - "metadata": { - "editable": true - }, - "source": [ - "Here we have performed a rather data greedy calculation as function of the regularization parameter $\\lambda$. There is no resampling here. The latter can easily be added by employing the function **RidgeCV** instead of just calling the **Ridge** function. For **RidgeCV** we need to pass the array of $\\lambda$ values.\n", - "By inspecting the figure we can in turn determine which is the optimal regularization parameter.\n", - "This becomes however less functional in the long run." - ] - }, - { - "cell_type": "markdown", - "id": "1ea723fc", - "metadata": { - "editable": true - }, - "source": [ - "## Grid Search\n", - "\n", - "An alternative is to use the so-called grid search functionality\n", - "included with the library **Scikit-Learn**, as demonstrated for the same\n", - "example here." - ] - }, - { - "cell_type": "code", - "execution_count": 2, - "id": "0ebb62df", - "metadata": { - "collapsed": false, - "editable": true - }, - "outputs": [], - "source": [ - "import numpy as np\n", - "from sklearn.model_selection import train_test_split\n", - "from sklearn.linear_model import Ridge\n", - "from sklearn.model_selection import GridSearchCV\n", - "\n", - "def R2(y_data, y_model):\n", - " return 1 - np.sum((y_data - y_model) ** 2) / np.sum((y_data - np.mean(y_data)) ** 2)\n", - "\n", - "def MSE(y_data,y_model):\n", - " n = np.size(y_model)\n", - " return np.sum((y_data-y_model)**2)/n\n", - "\n", - "# A seed just to ensure that the random numbers are the same for every run.\n", - "# Useful for eventual debugging.\n", - "np.random.seed(2021)\n", - "\n", - "n = 100\n", - "x = np.random.rand(n)\n", - "y = np.exp(-x**2) + 1.5 * np.exp(-(x-2)**2)+ np.random.randn(n)\n", - "\n", - "Maxpolydegree = 5\n", - "X = np.zeros((n,Maxpolydegree-1))\n", - "\n", - "for degree in range(1,Maxpolydegree): #No intercept column\n", - " X[:,degree-1] = x**(degree)\n", - "\n", - "# We split the data in test and training data\n", - "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2)\n", - "\n", - "# Decide which values of lambda to use\n", - "nlambdas = 10\n", - "lambdas = np.logspace(-4, 2, nlambdas)\n", - "# create and fit a ridge regression model, testing each alpha\n", - "model = Ridge()\n", - "gridsearch = GridSearchCV(estimator=model, param_grid=dict(alpha=lambdas))\n", - "gridsearch.fit(X_train, y_train)\n", - "print(gridsearch)\n", - "ypredictRidge = gridsearch.predict(X_test)\n", - "# summarize the results of the grid search\n", - "print(f\"Best estimated lambda-value: {gridsearch.best_estimator_.alpha}\")\n", - "print(f\"MSE score: {MSE(y_test,ypredictRidge)}\")\n", - "print(f\"R2 score: {R2(y_test,ypredictRidge)}\")" - ] - }, - { - "cell_type": "markdown", - "id": "0fb161e1", - "metadata": { - "editable": true - }, - "source": [ - "By default the grid search function includes cross validation with\n", - "five folds. The [Scikit-Learn\n", - "documentation](https://scikit-learn.org/stable/modules/generated/sklearn.model_selection.GridSearchCV.html#sklearn.model_selection.GridSearchCV)\n", - "contains more information on how to set the different parameters.\n", - "\n", - "If we take out the random noise, running the above codes results in $\\lambda=0$ yielding the best fit." - ] - }, - { - "cell_type": "markdown", - "id": "8bdb137e", - "metadata": { - "editable": true - }, - "source": [ - "## Randomized Grid Search\n", - "\n", - "An alternative to the above manual grid set up, is to use a random\n", - "search where the parameters are tuned from a random distribution\n", - "(uniform below) for a fixed number of iterations. A model is\n", - "constructed and evaluated for each combination of chosen parameters.\n", - "We repeat the previous example but now with a random search. Note\n", - "that values of $\\lambda$ are now limited to be within $x\\in\n", - "[0,1]$. This domain may not be the most relevant one for the specific\n", - "case under study." - ] - }, - { - "cell_type": "code", - "execution_count": 3, - "id": "af61779f", - "metadata": { - "collapsed": false, - "editable": true - }, - "outputs": [], - "source": [ - "import numpy as np\n", - "from sklearn.model_selection import train_test_split\n", - "from sklearn.linear_model import Ridge\n", - "from sklearn.model_selection import GridSearchCV\n", - "from scipy.stats import uniform as randuniform\n", - "from sklearn.model_selection import RandomizedSearchCV\n", - "\n", - "\n", - "def R2(y_data, y_model):\n", - " return 1 - np.sum((y_data - y_model) ** 2) / np.sum((y_data - np.mean(y_data)) ** 2)\n", - "\n", - "def MSE(y_data,y_model):\n", - " n = np.size(y_model)\n", - " return np.sum((y_data-y_model)**2)/n\n", - "\n", - "# A seed just to ensure that the random numbers are the same for every run.\n", - "# Useful for eventual debugging.\n", - "np.random.seed(2021)\n", - "\n", - "n = 100\n", - "x = np.random.rand(n)\n", - "y = np.exp(-x**2) + 1.5 * np.exp(-(x-2)**2)+ np.random.randn(n)\n", - "\n", - "Maxpolydegree = 5\n", - "X = np.zeros((n,Maxpolydegree-1))\n", - "\n", - "for degree in range(1,Maxpolydegree): #No intercept column\n", - " X[:,degree-1] = x**(degree)\n", - "\n", - "# We split the data in test and training data\n", - "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2)\n", - "\n", - "param_grid = {'alpha': randuniform()}\n", - "# create and fit a ridge regression model, testing each alpha\n", - "model = Ridge()\n", - "gridsearch = RandomizedSearchCV(estimator=model, param_distributions=param_grid, n_iter=100)\n", - "gridsearch.fit(X_train, y_train)\n", - "print(gridsearch)\n", - "ypredictRidge = gridsearch.predict(X_test)\n", - "# summarize the results of the grid search\n", - "print(f\"Best estimated lambda-value: {gridsearch.best_estimator_.alpha}\")\n", - "print(f\"MSE score: {MSE(y_test,ypredictRidge)}\")\n", - "print(f\"R2 score: {R2(y_test,ypredictRidge)}\")" - ] - }, - { - "cell_type": "markdown", - "id": "89f07674", - "metadata": { - "editable": true - }, - "source": [ - "## Wisconsin Cancer Data\n", - "\n", - "We show here how we can use a simple regression case on the breast\n", - "cancer data using Logistic regression as our algorithm for\n", - "classification." - ] - }, - { - "cell_type": "code", - "execution_count": 4, - "id": "37c8ca05", - "metadata": { - "collapsed": false, - "editable": true - }, - "outputs": [], - "source": [ - "import matplotlib.pyplot as plt\n", - "import numpy as np\n", - "from sklearn.model_selection import train_test_split \n", - "from sklearn.datasets import load_breast_cancer\n", - "from sklearn.linear_model import LogisticRegression\n", - "\n", - "# Load the data\n", - "cancer = load_breast_cancer()\n", - "\n", - "X_train, X_test, y_train, y_test = train_test_split(cancer.data,cancer.target,random_state=0)\n", - "print(X_train.shape)\n", - "print(X_test.shape)\n", - "# Logistic Regression\n", - "logreg = LogisticRegression(solver='lbfgs')\n", - "logreg.fit(X_train, y_train)\n", - "print(\"Test set accuracy with Logistic Regression: {:.2f}\".format(logreg.score(X_test,y_test)))" - ] - }, - { - "cell_type": "markdown", - "id": "509bf7a9", - "metadata": { - "editable": true - }, - "source": [ - "## Using the correlation matrix\n", - "\n", - "In addition to the above scores, we could also study the covariance (and the correlation matrix).\n", - "We use **Pandas** to compute the correlation matrix." - ] - }, - { - "cell_type": "code", - "execution_count": 5, - "id": "e9d06a0c", - "metadata": { - "collapsed": false, - "editable": true - }, - "outputs": [], - "source": [ - "import matplotlib.pyplot as plt\n", - "import numpy as np\n", - "from sklearn.model_selection import train_test_split \n", - "from sklearn.datasets import load_breast_cancer\n", - "from sklearn.linear_model import LogisticRegression\n", - "cancer = load_breast_cancer()\n", - "import pandas as pd\n", - "# Making a data frame\n", - "cancerpd = pd.DataFrame(cancer.data, columns=cancer.feature_names)\n", - "\n", - "fig, axes = plt.subplots(15,2,figsize=(10,20))\n", - "malignant = cancer.data[cancer.target == 0]\n", - "benign = cancer.data[cancer.target == 1]\n", - "ax = axes.ravel()\n", - "\n", - "for i in range(30):\n", - " _, bins = np.histogram(cancer.data[:,i], bins =50)\n", - " ax[i].hist(malignant[:,i], bins = bins, alpha = 0.5)\n", - " ax[i].hist(benign[:,i], bins = bins, alpha = 0.5)\n", - " ax[i].set_title(cancer.feature_names[i])\n", - " ax[i].set_yticks(())\n", - "ax[0].set_xlabel(\"Feature magnitude\")\n", - "ax[0].set_ylabel(\"Frequency\")\n", - "ax[0].legend([\"Malignant\", \"Benign\"], loc =\"best\")\n", - "fig.tight_layout()\n", - "plt.show()\n", - "\n", - "import seaborn as sns\n", - "correlation_matrix = cancerpd.corr().round(1)\n", - "# use the heatmap function from seaborn to plot the correlation matrix\n", - "# annot = True to print the values inside the square\n", - "plt.figure(figsize=(15,8))\n", - "sns.heatmap(data=correlation_matrix, annot=True)\n", - "plt.show()" - ] - }, - { - "cell_type": "markdown", - "id": "ab1f9810", - "metadata": { - "editable": true - }, - "source": [ - "## Discussing the correlation data\n", - "\n", - "In the above example we note two things. In the first plot we display\n", - "the overlap of benign and malignant tumors as functions of the various\n", - "features in the Wisconsing breast cancer data set. We see that for\n", - "some of the features we can distinguish clearly the benign and\n", - "malignant cases while for other features we cannot. This can point to\n", - "us which features may be of greater interest when we wish to classify\n", - "a benign or not benign tumour.\n", - "\n", - "In the second figure we have computed the so-called correlation\n", - "matrix, which in our case with thirty features becomes a $30\\times 30$\n", - "matrix.\n", - "\n", - "We constructed this matrix using **pandas** via the statements" - ] - }, - { - "cell_type": "code", - "execution_count": 6, - "id": "d8a5dabe", - "metadata": { - "collapsed": false, - "editable": true - }, - "outputs": [], - "source": [ - "cancerpd = pd.DataFrame(cancer.data, columns=cancer.feature_names)" - ] - }, - { - "cell_type": "markdown", - "id": "69fd6511", - "metadata": { - "editable": true - }, - "source": [ - "and then" - ] - }, - { - "cell_type": "code", - "execution_count": 7, - "id": "b74de9e5", - "metadata": { - "collapsed": false, - "editable": true - }, - "outputs": [], - "source": [ - "correlation_matrix = cancerpd.corr().round(1)" - ] - }, - { - "cell_type": "markdown", - "id": "24e267e4", - "metadata": { - "editable": true - }, - "source": [ - "Diagonalizing this matrix we can in turn say something about which\n", - "features are of relevance and which are not. This leads us to\n", - "the classical Principal Component Analysis (PCA) theorem with\n", - "applications. This will be discussed later this semester ([week 43](https://compphysics.github.io/MachineLearning/doc/pub/week43/html/week43-bs.html))." - ] - }, - { - "cell_type": "markdown", - "id": "77a9c527", - "metadata": { - "editable": true - }, - "source": [ - "## Other ways of presenting a classification problem\n", - "\n", - "For a binary classifcation matrix, the so-called **confusion matrix**, is often used. It can also be extended to more catgeories/classes as well.\n", - "The following quantities are then used\n", - "1. positive condition number $P$, which represents the number of real positive cases in the data (output one/true etc)\n", - "\n", - "2. The condition negative number $N$ which is the number of negative cases (ouput zero/false etc)\n", - "\n", - "3. The true positive number $TP$ which represents whether a positive test result has been correctly classified (the application of our trained model on a test data set)\n", - "\n", - "4. The true negative $TN$ number which represents whether a negative test has been correctly classified\n", - "\n", - "5. The false positive $FP$ number, a so-called type I error which tells us about the fraction of positive test result which are wrongly classified\n", - "\n", - "6. A false negative $FN$ number, a so-called type II error which, should be pretty obvious, indicates if a negative test has been wrongly classified.\n", - "\n", - "It is is easy to think in terms of illness. You could think of the above as\n", - "1. True positive: Sick people correctly identified as sick\n", - "\n", - "2. False positive: Healthy people incorrectly identified as sick\n", - "\n", - "3. True negative: Healthy people correctly identified as healthy\n", - "\n", - "4. False negative: Sick people incorrectly identified as healthy" - ] - }, - { - "cell_type": "markdown", - "id": "5f6ea3f0", - "metadata": { - "editable": true - }, - "source": [ - "## Combinations of classification results\n", - "\n", - "It is common in the literature to define various combinations the above numbers. The most commonly used are\n", - "\n", - "**Sensitivity, recall, hit rate, or true positive rate $TPR$. It is the probability of a positive test result, conditioned on the individual truly being positive.**" - ] - }, - { - "cell_type": "markdown", - "id": "b0d324b8", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "{\\displaystyle \\mathrm {TPR} ={\\frac {\\mathrm {TP} }{\\mathrm {P} }}={\\frac {\\mathrm {TP} }{\\mathrm {TP} +\\mathrm {FN} }}=1-\\mathrm {FNR} }\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "d5593af9", - "metadata": { - "editable": true - }, - "source": [ - "The $TPR$ defines how many correct positive results occur among all positive samples available during the test\n", - "\n", - "**Miss rate or false negative rate $FNR$.**" - ] - }, - { - "cell_type": "markdown", - "id": "e857f89e", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "{\\displaystyle \\mathrm {FNR} ={\\frac {\\mathrm {FN} }{\\mathrm {P} }}={\\frac {\\mathrm {FN} }{\\mathrm {FN} +\\mathrm {TP} }} }\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "13dc6da3", - "metadata": { - "editable": true - }, - "source": [ - "**Specificity, selectivity or true negative rate $TNR$. It is the probability of a negative test result, conditioned on the individual truly being negative.**" - ] - }, - { - "cell_type": "markdown", - "id": "0f77aa9a", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "{\\displaystyle \\mathrm {TNR} ={\\frac {\\mathrm {TN} }{\\mathrm {N} }}={\\frac {\\mathrm {TN} }{\\mathrm {TN} +\\mathrm {FP} }}=1-\\mathrm {FPR} }\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "3c560ddf", - "metadata": { - "editable": true - }, - "source": [ - "with the fall-out false positive rate" - ] - }, - { - "cell_type": "markdown", - "id": "b46686df", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "{\\displaystyle \\mathrm {FPR} ={\\frac {\\mathrm {FP} }{\\mathrm {N} }}={\\frac {\\mathrm {FP} }{\\mathrm {FP} +\\mathrm {TN} }}=1-\\mathrm {TNR} }\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "24aec375", - "metadata": { - "editable": true - }, - "source": [ - "The $FPR$ defines how many incorrect positive results occur among\n", - "all negative samples available during the test." - ] - }, - { - "cell_type": "markdown", - "id": "8d288b9d", - "metadata": { - "editable": true - }, - "source": [ - "## Positive and negative prediction values\n", - "\n", - "The positive and negative predictive values \n", - "are the proportions of positive and negative results in statistics and\n", - "diagnostic tests that are true positive and true negative results,\n", - "respectively.[1] The PPV and NPV describe the performance of a\n", - "diagnostic test or other statistical measure. A high result can be\n", - "interpreted as indicating the accuracy of such a statistic.\n", - "\n", - "**Precision or positive predictive value $PPV$.**" - ] - }, - { - "cell_type": "markdown", - "id": "e1663205", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "{\\displaystyle \\mathrm {PPV} ={\\frac {\\mathrm {TP} }{\\mathrm {TP} +\\mathrm {FP} }}=1-\\mathrm {FDR} }\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "b34d890c", - "metadata": { - "editable": true - }, - "source": [ - "**Negative predictive value $NPV$.**" - ] - }, - { - "cell_type": "markdown", - "id": "14e7f314", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "{\\displaystyle \\mathrm {NPV} ={\\frac {\\mathrm {TN} }{\\mathrm {TN} +\\mathrm {FN} }}=1-\\mathrm {FOR} }\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "879bac6b", - "metadata": { - "editable": true - }, - "source": [ - "## Other quantities\n", - "\n", - "**False discovery rate $FDR$.**" - ] - }, - { - "cell_type": "markdown", - "id": "31d2b3b7", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "{\\displaystyle \\mathrm {FDR} ={\\frac {\\mathrm {FP} }{\\mathrm {FP} +\\mathrm {TP} }}=1-\\mathrm {PPV} }\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "34fd7537", - "metadata": { - "editable": true - }, - "source": [ - "**False omission rate $FOR$.**" - ] - }, - { - "cell_type": "markdown", - "id": "4bebbe84", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "{\\displaystyle \\mathrm {FOR} ={\\frac {\\mathrm {FN} }{\\mathrm {FN} +\\mathrm {TN} }}=1-\\mathrm {NPV} }\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "690c8d76", - "metadata": { - "editable": true - }, - "source": [ - "## $F_1$ score\n", - "\n", - "In statistical analysis of binary classification, the F-score or\n", - "F-measure is a measure of a test's accuracy. It is calculated from the\n", - "precision and recall of the test, where the precision is the number of\n", - "true positive results divided by the number of all positive results,\n", - "including those not identified correctly, and the recall is the number\n", - "of true positive results divided by the number of all samples that\n", - "should have been identified as positive. Precision is also known as\n", - "positive predictive value, and recall is also known as sensitivity in\n", - "diagnostic binary classification.\n", - "\n", - "The F1 score is the harmonic mean of the precision and recall. It thus\n", - "symmetrically represents both precision and recall in one metric. The\n", - "highest possible value of an F-score is 1.0, indicating perfect\n", - "precision and recall, and the lowest possible value is 0, if either\n", - "precision or recall are zero.\n", - "\n", - "It is defined as" - ] - }, - { - "cell_type": "markdown", - "id": "12d8a75e", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "{\\displaystyle \\mathrm {F} _{1}=2\\times {\\frac {\\mathrm {PPV} \\times \\mathrm {TPR} }{\\mathrm {PPV} +\\mathrm {TPR} }}={\\frac {2\\mathrm {TP} }{2\\mathrm {TP} +\\mathrm {FP} +\\mathrm {FN} }}}\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "1df29154", - "metadata": { - "editable": true - }, - "source": [ - "## ROC curve\n", - "\n", - "A receiver operating characteristic curve, or ROC curve, is a\n", - "graphical plot that illustrates the performance of a binary classifier\n", - "model at varying threshold values.\n", - "\n", - "The ROC curve is the plot of the true positive rate (TPR) against the false positive rate (FPR) at each threshold setting.\n", - "\n", - "To draw a ROC curve, only the true positive rate (TPR) and false\n", - "positive rate (FPR) are needed (as functions of some classifier\n", - "parameter). The TPR defines how many correct positive results occur\n", - "among all positive samples available during the test. FPR, on the\n", - "other hand, defines how many incorrect positive results occur among\n", - "all negative samples available during the test.\n", - "\n", - "See for more discussions." - ] - }, - { - "cell_type": "markdown", - "id": "9083178e", - "metadata": { - "editable": true - }, - "source": [ - "## Cumulative gain curve\n", - "\n", - "The cumulative gain curve is a performance evaluation used typically for binary classification problems.\n", - "It plots the $TPR$ True Positive Rate or Sensitivity (which represents the \n", - "fraction of examples correctly classified\n", - "against Predictive Positive Rate, which represents \n", - "the fraction of positively predicted examples.\n", - "\n", - "The examples below show the confusion matrix, the ROC curve and the cumulative gain for the Wisconsin cancer data." - ] - }, - { - "cell_type": "markdown", - "id": "e7719466", - "metadata": { - "editable": true - }, - "source": [ - "## Other measures in classification studies: Cancer Data again" - ] - }, - { - "cell_type": "code", - "execution_count": 8, - "id": "bcddf060", - "metadata": { - "collapsed": false, - "editable": true - }, - "outputs": [], - "source": [ - "import matplotlib.pyplot as plt\n", - "import numpy as np\n", - "from sklearn.model_selection import train_test_split \n", - "from sklearn.datasets import load_breast_cancer\n", - "from sklearn.linear_model import LogisticRegression\n", - "\n", - "# Load the data\n", - "cancer = load_breast_cancer()\n", - "\n", - "X_train, X_test, y_train, y_test = train_test_split(cancer.data,cancer.target,random_state=0)\n", - "print(X_train.shape)\n", - "print(X_test.shape)\n", - "# Logistic Regression\n", - "logreg = LogisticRegression(solver='lbfgs')\n", - "logreg.fit(X_train, y_train)\n", - "\n", - "from sklearn.preprocessing import LabelEncoder\n", - "from sklearn.model_selection import cross_validate\n", - "#Cross validation\n", - "accuracy = cross_validate(logreg,X_test,y_test,cv=10)['test_score']\n", - "print(accuracy)\n", - "print(\"Test set accuracy with Logistic Regression: {:.2f}\".format(logreg.score(X_test,y_test)))\n", - "\n", - "import scikitplot as skplt\n", - "y_pred = logreg.predict(X_test)\n", - "skplt.metrics.plot_confusion_matrix(y_test, y_pred, normalize=True)\n", - "plt.show()\n", - "y_probas = logreg.predict_proba(X_test)\n", - "skplt.metrics.plot_roc(y_test, y_probas)\n", - "plt.show()\n", - "skplt.metrics.plot_cumulative_gain(y_test, y_probas)\n", - "plt.show()" - ] - }, - { - "cell_type": "markdown", - "id": "6ec55e94", - "metadata": { - "editable": true - }, - "source": [ - "## Material for Lecture Thursday November 9" - ] - }, - { - "cell_type": "markdown", - "id": "690b1a08", - "metadata": { - "editable": true - }, - "source": [ - "## Recurrent neural networks (RNNs): Overarching view\n", - "\n", - "Till now our focus has been, including convolutional neural networks\n", - "as well, on feedforward neural networks. The output or the activations\n", - "flow only in one direction, from the input layer to the output layer.\n", - "\n", - "A recurrent neural network (RNN) looks very much like a feedforward\n", - "neural network, except that it also has connections pointing\n", - "backward. \n", - "\n", - "RNNs are used to analyze time series data such as stock prices, and\n", - "tell you when to buy or sell. In autonomous driving systems, they can\n", - "anticipate car trajectories and help avoid accidents. More generally,\n", - "they can work on sequences of arbitrary lengths, rather than on\n", - "fixed-sized inputs like all the nets we have discussed so far. For\n", - "example, they can take sentences, documents, or audio samples as\n", - "input, making them extremely useful for natural language processing\n", - "systems such as automatic translation and speech-to-text." - ] - }, - { - "cell_type": "markdown", - "id": "825bc136", - "metadata": { - "editable": true - }, - "source": [ - "## A simple example" - ] - }, - { - "cell_type": "code", - "execution_count": 9, - "id": "ce956b33", - "metadata": { - "collapsed": false, - "editable": true - }, - "outputs": [], - "source": [ - "# Start importing packages\n", - "import pandas as pd\n", - "import numpy as np\n", - "import matplotlib.pyplot as plt\n", - "import tensorflow as tf\n", - "from tensorflow.keras import datasets, layers, models\n", - "from tensorflow.keras.layers import Input\n", - "from tensorflow.keras.models import Model, Sequential \n", - "from tensorflow.keras.layers import Dense, SimpleRNN, LSTM, GRU\n", - "from tensorflow.keras import optimizers \n", - "from tensorflow.keras import regularizers \n", - "from tensorflow.keras.utils import to_categorical \n", - "\n", - "\n", - "\n", - "# convert into dataset matrix\n", - "def convertToMatrix(data, step):\n", - " X, Y =[], []\n", - " for i in range(len(data)-step):\n", - " d=i+step \n", - " X.append(data[i:d,])\n", - " Y.append(data[d,])\n", - " return np.array(X), np.array(Y)\n", - "\n", - "step = 4\n", - "N = 1000 \n", - "Tp = 800 \n", - "\n", - "t=np.arange(0,N)\n", - "x=np.sin(0.02*t)+2*np.random.rand(N)\n", - "df = pd.DataFrame(x)\n", - "df.head()\n", - "\n", - "values=df.values\n", - "train,test = values[0:Tp,:], values[Tp:N,:]\n", - "\n", - "# add step elements into train and test\n", - "test = np.append(test,np.repeat(test[-1,],step))\n", - "train = np.append(train,np.repeat(train[-1,],step))\n", - " \n", - "trainX,trainY =convertToMatrix(train,step)\n", - "testX,testY =convertToMatrix(test,step)\n", - "trainX = np.reshape(trainX, (trainX.shape[0], 1, trainX.shape[1]))\n", - "testX = np.reshape(testX, (testX.shape[0], 1, testX.shape[1]))\n", - "\n", - "model = Sequential()\n", - "model.add(SimpleRNN(units=32, input_shape=(1,step), activation=\"relu\"))\n", - "model.add(Dense(8, activation=\"relu\")) \n", - "model.add(Dense(1))\n", - "model.compile(loss='mean_squared_error', optimizer='rmsprop')\n", - "model.summary()\n", - "\n", - "model.fit(trainX,trainY, epochs=100, batch_size=16, verbose=2)\n", - "trainPredict = model.predict(trainX)\n", - "testPredict= model.predict(testX)\n", - "predicted=np.concatenate((trainPredict,testPredict),axis=0)\n", - "\n", - "trainScore = model.evaluate(trainX, trainY, verbose=0)\n", - "print(trainScore)\n", - "plt.plot(df)\n", - "plt.plot(predicted)\n", - "plt.show()" - ] - }, - { - "cell_type": "markdown", - "id": "002c4d99", - "metadata": { - "editable": true - }, - "source": [ - "### RNNs\n", - "\n", - "RNNs are very powerful, because they\n", - "combine two properties:\n", - "1. Distributed hidden state that allows them to store a lot of information about the past efficiently.\n", - "\n", - "2. Non-linear dynamics that allows them to update their hidden state in complicated ways.\n", - "\n", - "With enough neurons and time, RNNs\n", - "can compute anything that can be\n", - "computed by your computer!" - ] - }, - { - "cell_type": "markdown", - "id": "6572c07f", - "metadata": { - "editable": true - }, - "source": [ - "## Basic layout\n", - "\n", - "\n", - "\n", - "\n", - "

Figure 1:

\n", - "" - ] - }, - { - "cell_type": "markdown", - "id": "fbd8e269", - "metadata": { - "editable": true - }, - "source": [ - "### We need to specify the initial activity state of all the hidden and output units\n", - "\n", - "1. We could just fix these initial states to have some default value like 0.5.\n", - "\n", - "2. But it is better to treat the initial states as learned parameters.\n", - "\n", - "3. We learn them in the same way as we learn the weights.\n", - "\n", - "* Start off with an initial random guess for the initial states.\n", - "\n", - "a. At the end of each training sequence, backpropagate through time all the way to the initial states to get the gradient of the error function with respect to each initial state.\n", - "\n", - "b. Adjust the initial states by following the negative gradient." - ] - }, - { - "cell_type": "markdown", - "id": "919bb09e", - "metadata": { - "editable": true - }, - "source": [ - "### We can specify inputs in several ways\n", - "\n", - "1. Specify the initial states of all the units.\n", - "\n", - "2. Specify the initial states of a subset of the units.\n", - "\n", - "3. Specify the states of the same subset of the units at every time step.\n", - "\n", - "This is the natural way to model most sequential data." - ] - }, - { - "cell_type": "markdown", - "id": "6e3360db", - "metadata": { - "editable": true - }, - "source": [ - "### We can specify targets in several ways\n", - "\n", - "1. Specify desired final activities of all the units\n", - "\n", - "2. Specify desired activities of all units for the last few steps\n", - "\n", - "* Good for learning attractors\n", - "\n", - "* It is easy to add in extra error derivatives as we backpropagate.\n", - "\n", - " * Specify the desired activity of a subset of the units.\n", - "\n", - "* The other units are input or hidden units. \n", - "\n", - "\n", - "\n", - "\n", - "

Figure 1:

\n", - "\n", - "\n", - "\n", - "\n", - "\n", - "

Figure 1:

\n", - "\n", - "\n", - "\n", - "\n", - "\n", - "

Figure 1:

\n", - "\n", - "\n", - "\n", - "\n", - "\n", - "

Figure 1:

\n", - "" - ] - }, - { - "cell_type": "markdown", - "id": "0f284cbd", - "metadata": { - "editable": true - }, - "source": [ - "### Backpropagation through time\n", - "\n", - "We can think of the recurrent net as a layered, feed-forward\n", - "net with shared weights and then train the feed-forward net\n", - "with weight constraints.\n", - "\n", - "We can also think of this training algorithm in the time domain:\n", - "1. The forward pass builds up a stack of the activities of all the units at each time step.\n", - "\n", - "2. The backward pass peels activities off the stack to compute the error derivatives at each time step.\n", - "\n", - "3. After the backward pass we add together the derivatives at all the different times for each weight." - ] - }, - { - "cell_type": "markdown", - "id": "b5e9785e", - "metadata": { - "editable": true - }, - "source": [ - "### The backward pass is linear\n", - "\n", - "1. There is a big difference between the forward and backward passes.\n", - "\n", - "2. In the forward pass we use squashing functions (like the logistic) to prevent the activity vectors from exploding.\n", - "\n", - "3. The backward pass, is completely linear. If you double the error derivatives at the final layer, all the error derivatives will double.\n", - "\n", - "The forward pass determines the slope of the linear function used for\n", - "backpropagating through each neuron\n", - "\n", - "\n", - "\n", - "\n", - "

Figure 1:

\n", - "\n", - "\n", - "\n", - "\n", - "\n", - "

Figure 1:

\n", - "\n", - "\n", - "\n", - "\n", - "\n", - "

Figure 1:

\n", - "\n", - "\n", - "\n", - "\n", - "\n", - "

Figure 1:

\n", - "\n", - "\n", - "\n", - "\n", - "\n", - "

Figure 1:

\n", - "\n", - "\n", - "\n", - "\n", - "\n", - "

Figure 1:

\n", - "\n", - "\n", - "\n", - "\n", - "\n", - "

Figure 1:

\n", - "" - ] - }, - { - "cell_type": "markdown", - "id": "50a43c30", - "metadata": { - "editable": true - }, - "source": [ - "## The problem of exploding or vanishing gradients\n", - "* What happens to the magnitude of the gradients as we backpropagate through many layers?\n", - "\n", - "a. If the weights are small, the gradients shrink exponentially.\n", - "\n", - "b. If the weights are big the gradients grow exponentially.\n", - "\n", - "* Typical feed-forward neural nets can cope with these exponential effects because they only have a few hidden layers.\n", - "\n", - "* In an RNN trained on long sequences (e.g. 100 time steps) the gradients can easily explode or vanish.\n", - "\n", - "a. We can avoid this by initializing the weights very carefully.\n", - "\n", - "* Even with good initial weights, its very hard to detect that the current target output depends on an input from many time-steps ago.\n", - "\n", - "RNNs have difficulty dealing with long-range dependencies." - ] - }, - { - "cell_type": "markdown", - "id": "f3e0d31b", - "metadata": { - "editable": true - }, - "source": [ - "## Four effective ways to learn an RNN\n", - "1. Long Short Term Memory Make the RNN out of little modules that are designed to remember values for a long time.\n", - "\n", - "2. Hessian Free Optimization: Deal with the vanishing gradients problem by using a fancy optimizer that can detect directions with a tiny gradient but even smaller curvature.\n", - "\n", - "3. Echo State Networks: Initialize the input a hidden and hidden-hidden and output-hidden connections very carefully so that the hidden state has a huge reservoir of weakly coupled oscillators which can be selectively driven by the input.\n", - "\n", - " * ESNs only need to learn the hidden-output connections.\n", - "\n", - "4. Good initialization with momentum Initialize like in Echo State Networks, but then learn all of the connections using momentum" - ] - }, - { - "cell_type": "markdown", - "id": "b1571231", - "metadata": { - "editable": true - }, - "source": [ - "### Long Short Term Memory (LSTM)\n", - "\n", - "LSTM uses a memory cell for \n", - " modeling long-range dependencies and avoid vanishing gradient\n", - " problems.\n", - "\n", - "1. Introduced by Hochreiter and Schmidhuber (1997) who solved the problem of getting an RNN to remember things for a long time (like hundreds of time steps).\n", - "\n", - "2. They designed a memory cell using logistic and linear units with multiplicative interactions.\n", - "\n", - "3. Information gets into the cell whenever its “write” gate is on.\n", - "\n", - "4. The information stays in the cell so long as its **keep** gate is on.\n", - "\n", - "5. Information can be read from the cell by turning on its **read** gate." - ] - }, - { - "cell_type": "markdown", - "id": "e7886dd3", - "metadata": { - "editable": true - }, - "source": [ - "### Implementing a memory cell in a neural network\n", - "\n", - "To preserve information for a long time in\n", - "the activities of an RNN, we use a circuit\n", - "that implements an analog memory cell.\n", - "\n", - "1. A linear unit that has a self-link with a weight of 1 will maintain its state.\n", - "\n", - "2. Information is stored in the cell by activating its write gate.\n", - "\n", - "3. Information is retrieved by activating the read gate.\n", - "\n", - "4. We can backpropagate through this circuit because logistics are have nice derivatives. \n", - "\n", - "\n", - "\n", - "\n", - "

Figure 1:

\n", - "\n", - "\n", - "\n", - "\n", - "\n", - "

Figure 1:

\n", - "\n", - "\n", - "\n", - "\n", - "\n", - "

Figure 1:

\n", - "\n", - "\n", - "\n", - "\n", - "\n", - "

Figure 1:

\n", - "\n", - "\n", - "\n", - "\n", - "\n", - "

Figure 1:

\n", - "\n", - "\n", - "\n", - "\n", - "\n", - "

Figure 1:

\n", - "\n", - "\n", - "\n", - "\n", - "\n", - "

Figure 1:

\n", - "\n", - "\n", - "\n", - "\n", - "\n", - "

Figure 1:

\n", - "\n", - "\n", - "\n", - "\n", - "\n", - "

Figure 1:

\n", - "\n", - "\n", - "\n", - "\n", - "\n", - "

Figure 1:

\n", - "" - ] - }, - { - "cell_type": "markdown", - "id": "f878b195", - "metadata": { - "editable": true - }, - "source": [ - "## An extrapolation example\n", - "\n", - "The following code provides an example of how recurrent neural\n", - "networks can be used to extrapolate to unknown values of physics data\n", - "sets. Specifically, the data sets used in this program come from\n", - "a quantum mechanical many-body calculation of energies as functions of the number of particles." - ] - }, - { - "cell_type": "code", - "execution_count": 10, - "id": "1889da48", - "metadata": { - "collapsed": false, - "editable": true - }, - "outputs": [], - "source": [ - "\n", - "# For matrices and calculations\n", - "import numpy as np\n", - "# For machine learning (backend for keras)\n", - "import tensorflow as tf\n", - "# User-friendly machine learning library\n", - "# Front end for TensorFlow\n", - "import tensorflow.keras\n", - "# Different methods from Keras needed to create an RNN\n", - "# This is not necessary but it shortened function calls \n", - "# that need to be used in the code.\n", - "from tensorflow.keras import datasets, layers, models\n", - "from tensorflow.keras.layers import Input\n", - "from tensorflow.keras import regularizers\n", - "from tensorflow.keras.models import Model, Sequential\n", - "from tensorflow.keras.layers import Dense, SimpleRNN, LSTM, GRU\n", - "# For timing the code\n", - "from timeit import default_timer as timer\n", - "# For plotting\n", - "import matplotlib.pyplot as plt\n", - "\n", - "\n", - "# The data set\n", - "datatype='VaryDimension'\n", - "X_tot = np.arange(2, 42, 2)\n", - "y_tot = np.array([-0.03077640549, -0.08336233266, -0.1446729567, -0.2116753732, -0.2830637392, -0.3581341341, -0.436462435, -0.5177783846,\n", - "\t-0.6019067271, -0.6887363571, -0.7782028952, -0.8702784034, -0.9649652536, -1.062292565, -1.16231451, \n", - "\t-1.265109911, -1.370782966, -1.479465113, -1.591317992, -1.70653767])" - ] - }, - { - "cell_type": "markdown", - "id": "5bf3bea4", - "metadata": { - "editable": true - }, - "source": [ - "## Formatting the Data\n", - "\n", - "The way the recurrent neural networks are trained in this program\n", - "differs from how machine learning algorithms are usually trained.\n", - "Typically a machine learning algorithm is trained by learning the\n", - "relationship between the x data and the y data. In this program, the\n", - "recurrent neural network will be trained to recognize the relationship\n", - "in a sequence of y values. This is type of data formatting is\n", - "typically used time series forcasting, but it can also be used in any\n", - "extrapolation (time series forecasting is just a specific type of\n", - "extrapolation along the time axis). This method of data formatting\n", - "does not use the x data and assumes that the y data are evenly spaced.\n", - "\n", - "For a standard machine learning algorithm, the training data has the\n", - "form of (x,y) so the machine learning algorithm learns to assiciate a\n", - "y value with a given x value. This is useful when the test data has x\n", - "values within the same range as the training data. However, for this\n", - "application, the x values of the test data are outside of the x values\n", - "of the training data and the traditional method of training a machine\n", - "learning algorithm does not work as well. For this reason, the\n", - "recurrent neural network is trained on sequences of y values of the\n", - "form ((y1, y2), y3), so that the network is concerned with learning\n", - "the pattern of the y data and not the relation between the x and y\n", - "data. As long as the pattern of y data outside of the training region\n", - "stays relatively stable compared to what was inside the training\n", - "region, this method of training can produce accurate extrapolations to\n", - "y values far removed from the training data set.\n", - "\n", - "\n", - "\n", - "\n", - "\n", - "\n", - "" - ] - }, - { - "cell_type": "code", - "execution_count": 11, - "id": "6fc9b3dd", - "metadata": { - "collapsed": false, - "editable": true - }, - "outputs": [], - "source": [ - "# FORMAT_DATA\n", - "def format_data(data, length_of_sequence = 2): \n", - " \"\"\"\n", - " Inputs:\n", - " data(a numpy array): the data that will be the inputs to the recurrent neural\n", - " network\n", - " length_of_sequence (an int): the number of elements in one iteration of the\n", - " sequence patter. For a function approximator use length_of_sequence = 2.\n", - " Returns:\n", - " rnn_input (a 3D numpy array): the input data for the recurrent neural network. Its\n", - " dimensions are length of data - length of sequence, length of sequence, \n", - " dimnsion of data\n", - " rnn_output (a numpy array): the training data for the neural network\n", - " Formats data to be used in a recurrent neural network.\n", - " \"\"\"\n", - "\n", - " X, Y = [], []\n", - " for i in range(len(data)-length_of_sequence):\n", - " # Get the next length_of_sequence elements\n", - " a = data[i:i+length_of_sequence]\n", - " # Get the element that immediately follows that\n", - " b = data[i+length_of_sequence]\n", - " # Reshape so that each data point is contained in its own array\n", - " a = np.reshape (a, (len(a), 1))\n", - " X.append(a)\n", - " Y.append(b)\n", - " rnn_input = np.array(X)\n", - " rnn_output = np.array(Y)\n", - "\n", - " return rnn_input, rnn_output\n", - "\n", - "\n", - "# ## Defining the Recurrent Neural Network Using Keras\n", - "# \n", - "# The following method defines a simple recurrent neural network in keras consisting of one input layer, one hidden layer, and one output layer.\n", - "\n", - "def rnn(length_of_sequences, batch_size = None, stateful = False):\n", - " \"\"\"\n", - " Inputs:\n", - " length_of_sequences (an int): the number of y values in \"x data\". This is determined\n", - " when the data is formatted\n", - " batch_size (an int): Default value is None. See Keras documentation of SimpleRNN.\n", - " stateful (a boolean): Default value is False. See Keras documentation of SimpleRNN.\n", - " Returns:\n", - " model (a Keras model): The recurrent neural network that is built and compiled by this\n", - " method\n", - " Builds and compiles a recurrent neural network with one hidden layer and returns the model.\n", - " \"\"\"\n", - " # Number of neurons in the input and output layers\n", - " in_out_neurons = 1\n", - " # Number of neurons in the hidden layer\n", - " hidden_neurons = 200\n", - " # Define the input layer\n", - " inp = Input(batch_shape=(batch_size, \n", - " length_of_sequences, \n", - " in_out_neurons)) \n", - " # Define the hidden layer as a simple RNN layer with a set number of neurons and add it to \n", - " # the network immediately after the input layer\n", - " rnn = SimpleRNN(hidden_neurons, \n", - " return_sequences=False,\n", - " stateful = stateful,\n", - " name=\"RNN\")(inp)\n", - " # Define the output layer as a dense neural network layer (standard neural network layer)\n", - " #and add it to the network immediately after the hidden layer.\n", - " dens = Dense(in_out_neurons,name=\"dense\")(rnn)\n", - " # Create the machine learning model starting with the input layer and ending with the \n", - " # output layer\n", - " model = Model(inputs=[inp],outputs=[dens])\n", - " # Compile the machine learning model using the mean squared error function as the loss \n", - " # function and an Adams optimizer.\n", - " model.compile(loss=\"mean_squared_error\", optimizer=\"adam\") \n", - " return model" - ] - }, - { - "cell_type": "markdown", - "id": "6b02bff4", - "metadata": { - "editable": true - }, - "source": [ - "## Predicting New Points With A Trained Recurrent Neural Network" - ] - }, - { - "cell_type": "code", - "execution_count": 12, - "id": "7030f585", - "metadata": { - "collapsed": false, - "editable": true - }, - "outputs": [], - "source": [ - "def test_rnn (x1, y_test, plot_min, plot_max):\n", - " \"\"\"\n", - " Inputs:\n", - " x1 (a list or numpy array): The complete x component of the data set\n", - " y_test (a list or numpy array): The complete y component of the data set\n", - " plot_min (an int or float): the smallest x value used in the training data\n", - " plot_max (an int or float): the largest x valye used in the training data\n", - " Returns:\n", - " None.\n", - " Uses a trained recurrent neural network model to predict future points in the \n", - " series. Computes the MSE of the predicted data set from the true data set, saves\n", - " the predicted data set to a csv file, and plots the predicted and true data sets w\n", - " while also displaying the data range used for training.\n", - " \"\"\"\n", - " # Add the training data as the first dim points in the predicted data array as these\n", - " # are known values.\n", - " y_pred = y_test[:dim].tolist()\n", - " # Generate the first input to the trained recurrent neural network using the last two \n", - " # points of the training data. Based on how the network was trained this means that it\n", - " # will predict the first point in the data set after the training data. All of the \n", - " # brackets are necessary for Tensorflow.\n", - " next_input = np.array([[[y_test[dim-2]], [y_test[dim-1]]]])\n", - " # Save the very last point in the training data set. This will be used later.\n", - " last = [y_test[dim-1]]\n", - "\n", - " # Iterate until the complete data set is created.\n", - " for i in range (dim, len(y_test)):\n", - " # Predict the next point in the data set using the previous two points.\n", - " next = model.predict(next_input)\n", - " # Append just the number of the predicted data set\n", - " y_pred.append(next[0][0])\n", - " # Create the input that will be used to predict the next data point in the data set.\n", - " next_input = np.array([[last, next[0]]], dtype=np.float64)\n", - " last = next\n", - "\n", - " # Print the mean squared error between the known data set and the predicted data set.\n", - " print('MSE: ', np.square(np.subtract(y_test, y_pred)).mean())\n", - " # Save the predicted data set as a csv file for later use\n", - " name = datatype + 'Predicted'+str(dim)+'.csv'\n", - " np.savetxt(name, y_pred, delimiter=',')\n", - " # Plot the known data set and the predicted data set. The red box represents the region that was used\n", - " # for the training data.\n", - " fig, ax = plt.subplots()\n", - " ax.plot(x1, y_test, label=\"true\", linewidth=3)\n", - " ax.plot(x1, y_pred, 'g-.',label=\"predicted\", linewidth=4)\n", - " ax.legend()\n", - " # Created a red region to represent the points used in the training data.\n", - " ax.axvspan(plot_min, plot_max, alpha=0.25, color='red')\n", - " plt.show()\n", - "\n", - "# Check to make sure the data set is complete\n", - "assert len(X_tot) == len(y_tot)\n", - "\n", - "# This is the number of points that will be used in as the training data\n", - "dim=12\n", - "\n", - "# Separate the training data from the whole data set\n", - "X_train = X_tot[:dim]\n", - "y_train = y_tot[:dim]\n", - "\n", - "\n", - "# Generate the training data for the RNN, using a sequence of 2\n", - "rnn_input, rnn_training = format_data(y_train, 2)\n", - "\n", - "\n", - "# Create a recurrent neural network in Keras and produce a summary of the \n", - "# machine learning model\n", - "model = rnn(length_of_sequences = rnn_input.shape[1])\n", - "model.summary()\n", - "\n", - "# Start the timer. Want to time training+testing\n", - "start = timer()\n", - "# Fit the model using the training data genenerated above using 150 training iterations and a 5%\n", - "# validation split. Setting verbose to True prints information about each training iteration.\n", - "hist = model.fit(rnn_input, rnn_training, batch_size=None, epochs=150, \n", - " verbose=True,validation_split=0.05)\n", - "\n", - "for label in [\"loss\",\"val_loss\"]:\n", - " plt.plot(hist.history[label],label=label)\n", - "\n", - "plt.ylabel(\"loss\")\n", - "plt.xlabel(\"epoch\")\n", - "plt.title(\"The final validation loss: {}\".format(hist.history[\"val_loss\"][-1]))\n", - "plt.legend()\n", - "plt.show()\n", - "\n", - "# Use the trained neural network to predict more points of the data set\n", - "test_rnn(X_tot, y_tot, X_tot[0], X_tot[dim-1])\n", - "# Stop the timer and calculate the total time needed.\n", - "end = timer()\n", - "print('Time: ', end-start)" - ] - }, - { - "cell_type": "markdown", - "id": "53dc1510", - "metadata": { - "editable": true - }, - "source": [ - "## Other Things to Try\n", - "\n", - "Changing the size of the recurrent neural network and its parameters\n", - "can drastically change the results you get from the model. The below\n", - "code takes the simple recurrent neural network from above and adds a\n", - "second hidden layer, changes the number of neurons in the hidden\n", - "layer, and explicitly declares the activation function of the hidden\n", - "layers to be a sigmoid function. The loss function and optimizer can\n", - "also be changed but are kept the same as the above network. These\n", - "parameters can be tuned to provide the optimal result from the\n", - "network. For some ideas on how to improve the performance of a\n", - "[recurrent neural network](https://danijar.com/tips-for-training-recurrent-neural-networks)." - ] - }, - { - "cell_type": "code", - "execution_count": 13, - "id": "62aa2c1c", - "metadata": { - "collapsed": false, - "editable": true - }, - "outputs": [], - "source": [ - "def rnn_2layers(length_of_sequences, batch_size = None, stateful = False):\n", - " \"\"\"\n", - " Inputs:\n", - " length_of_sequences (an int): the number of y values in \"x data\". This is determined\n", - " when the data is formatted\n", - " batch_size (an int): Default value is None. See Keras documentation of SimpleRNN.\n", - " stateful (a boolean): Default value is False. See Keras documentation of SimpleRNN.\n", - " Returns:\n", - " model (a Keras model): The recurrent neural network that is built and compiled by this\n", - " method\n", - " Builds and compiles a recurrent neural network with two hidden layers and returns the model.\n", - " \"\"\"\n", - " # Number of neurons in the input and output layers\n", - " in_out_neurons = 1\n", - " # Number of neurons in the hidden layer, increased from the first network\n", - " hidden_neurons = 500\n", - " # Define the input layer\n", - " inp = Input(batch_shape=(batch_size, \n", - " length_of_sequences, \n", - " in_out_neurons)) \n", - " # Create two hidden layers instead of one hidden layer. Explicitly set the activation\n", - " # function to be the sigmoid function (the default value is hyperbolic tangent)\n", - " rnn1 = SimpleRNN(hidden_neurons, \n", - " return_sequences=True, # This needs to be True if another hidden layer is to follow\n", - " stateful = stateful, activation = 'sigmoid',\n", - " name=\"RNN1\")(inp)\n", - " rnn2 = SimpleRNN(hidden_neurons, \n", - " return_sequences=False, activation = 'sigmoid',\n", - " stateful = stateful,\n", - " name=\"RNN2\")(rnn1)\n", - " # Define the output layer as a dense neural network layer (standard neural network layer)\n", - " #and add it to the network immediately after the hidden layer.\n", - " dens = Dense(in_out_neurons,name=\"dense\")(rnn2)\n", - " # Create the machine learning model starting with the input layer and ending with the \n", - " # output layer\n", - " model = Model(inputs=[inp],outputs=[dens])\n", - " # Compile the machine learning model using the mean squared error function as the loss \n", - " # function and an Adams optimizer.\n", - " model.compile(loss=\"mean_squared_error\", optimizer=\"adam\") \n", - " return model\n", - "\n", - "# Check to make sure the data set is complete\n", - "assert len(X_tot) == len(y_tot)\n", - "\n", - "# This is the number of points that will be used in as the training data\n", - "dim=12\n", - "\n", - "# Separate the training data from the whole data set\n", - "X_train = X_tot[:dim]\n", - "y_train = y_tot[:dim]\n", - "\n", - "\n", - "# Generate the training data for the RNN, using a sequence of 2\n", - "rnn_input, rnn_training = format_data(y_train, 2)\n", - "\n", - "\n", - "# Create a recurrent neural network in Keras and produce a summary of the \n", - "# machine learning model\n", - "model = rnn_2layers(length_of_sequences = 2)\n", - "model.summary()\n", - "\n", - "# Start the timer. Want to time training+testing\n", - "start = timer()\n", - "# Fit the model using the training data genenerated above using 150 training iterations and a 5%\n", - "# validation split. Setting verbose to True prints information about each training iteration.\n", - "hist = model.fit(rnn_input, rnn_training, batch_size=None, epochs=150, \n", - " verbose=True,validation_split=0.05)\n", - "\n", - "\n", - "# This section plots the training loss and the validation loss as a function of training iteration.\n", - "# This is not required for analyzing the couple cluster data but can help determine if the network is\n", - "# being overtrained.\n", - "for label in [\"loss\",\"val_loss\"]:\n", - " plt.plot(hist.history[label],label=label)\n", - "\n", - "plt.ylabel(\"loss\")\n", - "plt.xlabel(\"epoch\")\n", - "plt.title(\"The final validation loss: {}\".format(hist.history[\"val_loss\"][-1]))\n", - "plt.legend()\n", - "plt.show()\n", - "\n", - "# Use the trained neural network to predict more points of the data set\n", - "test_rnn(X_tot, y_tot, X_tot[0], X_tot[dim-1])\n", - "# Stop the timer and calculate the total time needed.\n", - "end = timer()\n", - "print('Time: ', end-start)" - ] - }, - { - "cell_type": "markdown", - "id": "56fb2d92", - "metadata": { - "editable": true - }, - "source": [ - "## Other Types of Recurrent Neural Networks\n", - "\n", - "Besides a simple recurrent neural network layer, there are two other\n", - "commonly used types of recurrent neural network layers: Long Short\n", - "Term Memory (LSTM) and Gated Recurrent Unit (GRU). For a short\n", - "introduction to these layers see \n", - "and .\n", - "\n", - "The first network created below is similar to the previous network,\n", - "but it replaces the SimpleRNN layers with LSTM layers. The second\n", - "network below has two hidden layers made up of GRUs, which are\n", - "preceeded by two dense (feeddorward) neural network layers. These\n", - "dense layers \"preprocess\" the data before it reaches the recurrent\n", - "layers. This architecture has been shown to improve the performance\n", - "of recurrent neural networks (see the link above and also\n", - "." - ] - }, - { - "cell_type": "code", - "execution_count": 14, - "id": "145ed525", - "metadata": { - "collapsed": false, - "editable": true - }, - "outputs": [], - "source": [ - "def lstm_2layers(length_of_sequences, batch_size = None, stateful = False):\n", - " \"\"\"\n", - " Inputs:\n", - " length_of_sequences (an int): the number of y values in \"x data\". This is determined\n", - " when the data is formatted\n", - " batch_size (an int): Default value is None. See Keras documentation of SimpleRNN.\n", - " stateful (a boolean): Default value is False. See Keras documentation of SimpleRNN.\n", - " Returns:\n", - " model (a Keras model): The recurrent neural network that is built and compiled by this\n", - " method\n", - " Builds and compiles a recurrent neural network with two LSTM hidden layers and returns the model.\n", - " \"\"\"\n", - " # Number of neurons on the input/output layer and the number of neurons in the hidden layer\n", - " in_out_neurons = 1\n", - " hidden_neurons = 250\n", - " # Input Layer\n", - " inp = Input(batch_shape=(batch_size, \n", - " length_of_sequences, \n", - " in_out_neurons)) \n", - " # Hidden layers (in this case they are LSTM layers instead if SimpleRNN layers)\n", - " rnn= LSTM(hidden_neurons, \n", - " return_sequences=True,\n", - " stateful = stateful,\n", - " name=\"RNN\", use_bias=True, activation='tanh')(inp)\n", - " rnn1 = LSTM(hidden_neurons, \n", - " return_sequences=False,\n", - " stateful = stateful,\n", - " name=\"RNN1\", use_bias=True, activation='tanh')(rnn)\n", - " # Output layer\n", - " dens = Dense(in_out_neurons,name=\"dense\")(rnn1)\n", - " # Define the midel\n", - " model = Model(inputs=[inp],outputs=[dens])\n", - " # Compile the model\n", - " model.compile(loss='mean_squared_error', optimizer='adam') \n", - " # Return the model\n", - " return model\n", - "\n", - "def dnn2_gru2(length_of_sequences, batch_size = None, stateful = False):\n", - " \"\"\"\n", - " Inputs:\n", - " length_of_sequences (an int): the number of y values in \"x data\". This is determined\n", - " when the data is formatted\n", - " batch_size (an int): Default value is None. See Keras documentation of SimpleRNN.\n", - " stateful (a boolean): Default value is False. See Keras documentation of SimpleRNN.\n", - " Returns:\n", - " model (a Keras model): The recurrent neural network that is built and compiled by this\n", - " method\n", - " Builds and compiles a recurrent neural network with four hidden layers (two dense followed by\n", - " two GRU layers) and returns the model.\n", - " \"\"\" \n", - " # Number of neurons on the input/output layers and hidden layers\n", - " in_out_neurons = 1\n", - " hidden_neurons = 250\n", - " # Input layer\n", - " inp = Input(batch_shape=(batch_size, \n", - " length_of_sequences, \n", - " in_out_neurons)) \n", - " # Hidden Dense (feedforward) layers\n", - " dnn = Dense(hidden_neurons/2, activation='relu', name='dnn')(inp)\n", - " dnn1 = Dense(hidden_neurons/2, activation='relu', name='dnn1')(dnn)\n", - " # Hidden GRU layers\n", - " rnn1 = GRU(hidden_neurons, \n", - " return_sequences=True,\n", - " stateful = stateful,\n", - " name=\"RNN1\", use_bias=True)(dnn1)\n", - " rnn = GRU(hidden_neurons, \n", - " return_sequences=False,\n", - " stateful = stateful,\n", - " name=\"RNN\", use_bias=True)(rnn1)\n", - " # Output layer\n", - " dens = Dense(in_out_neurons,name=\"dense\")(rnn)\n", - " # Define the model\n", - " model = Model(inputs=[inp],outputs=[dens])\n", - " # Compile the mdoel\n", - " model.compile(loss='mean_squared_error', optimizer='adam') \n", - " # Return the model\n", - " return model\n", - "\n", - "# Check to make sure the data set is complete\n", - "assert len(X_tot) == len(y_tot)\n", - "\n", - "# This is the number of points that will be used in as the training data\n", - "dim=12\n", - "\n", - "# Separate the training data from the whole data set\n", - "X_train = X_tot[:dim]\n", - "y_train = y_tot[:dim]\n", - "\n", - "\n", - "# Generate the training data for the RNN, using a sequence of 2\n", - "rnn_input, rnn_training = format_data(y_train, 2)\n", - "\n", - "\n", - "# Create a recurrent neural network in Keras and produce a summary of the \n", - "# machine learning model\n", - "# Change the method name to reflect which network you want to use\n", - "model = dnn2_gru2(length_of_sequences = 2)\n", - "model.summary()\n", - "\n", - "# Start the timer. Want to time training+testing\n", - "start = timer()\n", - "# Fit the model using the training data genenerated above using 150 training iterations and a 5%\n", - "# validation split. Setting verbose to True prints information about each training iteration.\n", - "hist = model.fit(rnn_input, rnn_training, batch_size=None, epochs=150, \n", - " verbose=True,validation_split=0.05)\n", - "\n", - "\n", - "# This section plots the training loss and the validation loss as a function of training iteration.\n", - "# This is not required for analyzing the couple cluster data but can help determine if the network is\n", - "# being overtrained.\n", - "for label in [\"loss\",\"val_loss\"]:\n", - " plt.plot(hist.history[label],label=label)\n", - "\n", - "plt.ylabel(\"loss\")\n", - "plt.xlabel(\"epoch\")\n", - "plt.title(\"The final validation loss: {}\".format(hist.history[\"val_loss\"][-1]))\n", - "plt.legend()\n", - "plt.show()\n", - "\n", - "# Use the trained neural network to predict more points of the data set\n", - "test_rnn(X_tot, y_tot, X_tot[0], X_tot[dim-1])\n", - "# Stop the timer and calculate the total time needed.\n", - "end = timer()\n", - "print('Time: ', end-start)\n", - "\n", - "\n", - "# ### Training Recurrent Neural Networks in the Standard Way (i.e. learning the relationship between the X and Y data)\n", - "# \n", - "# Finally, comparing the performace of a recurrent neural network using the standard data formatting to the performance of the network with time sequence data formatting shows the benefit of this type of data formatting with extrapolation.\n", - "\n", - "# Check to make sure the data set is complete\n", - "assert len(X_tot) == len(y_tot)\n", - "\n", - "# This is the number of points that will be used in as the training data\n", - "dim=12\n", - "\n", - "# Separate the training data from the whole data set\n", - "X_train = X_tot[:dim]\n", - "y_train = y_tot[:dim]\n", - "\n", - "# Reshape the data for Keras specifications\n", - "X_train = X_train.reshape((dim, 1))\n", - "y_train = y_train.reshape((dim, 1))\n", - "\n", - "\n", - "# Create a recurrent neural network in Keras and produce a summary of the \n", - "# machine learning model\n", - "# Set the sequence length to 1 for regular data formatting \n", - "model = rnn(length_of_sequences = 1)\n", - "model.summary()\n", - "\n", - "# Start the timer. Want to time training+testing\n", - "start = timer()\n", - "# Fit the model using the training data genenerated above using 150 training iterations and a 5%\n", - "# validation split. Setting verbose to True prints information about each training iteration.\n", - "hist = model.fit(X_train, y_train, batch_size=None, epochs=150, \n", - " verbose=True,validation_split=0.05)\n", - "\n", - "\n", - "# This section plots the training loss and the validation loss as a function of training iteration.\n", - "# This is not required for analyzing the couple cluster data but can help determine if the network is\n", - "# being overtrained.\n", - "for label in [\"loss\",\"val_loss\"]:\n", - " plt.plot(hist.history[label],label=label)\n", - "\n", - "plt.ylabel(\"loss\")\n", - "plt.xlabel(\"epoch\")\n", - "plt.title(\"The final validation loss: {}\".format(hist.history[\"val_loss\"][-1]))\n", - "plt.legend()\n", - "plt.show()\n", - "\n", - "# Use the trained neural network to predict the remaining data points\n", - "X_pred = X_tot[dim:]\n", - "X_pred = X_pred.reshape((len(X_pred), 1))\n", - "y_model = model.predict(X_pred)\n", - "y_pred = np.concatenate((y_tot[:dim], y_model.flatten()))\n", - "\n", - "# Plot the known data set and the predicted data set. The red box represents the region that was used\n", - "# for the training data.\n", - "fig, ax = plt.subplots()\n", - "ax.plot(X_tot, y_tot, label=\"true\", linewidth=3)\n", - "ax.plot(X_tot, y_pred, 'g-.',label=\"predicted\", linewidth=4)\n", - "ax.legend()\n", - "# Created a red region to represent the points used in the training data.\n", - "ax.axvspan(X_tot[0], X_tot[dim], alpha=0.25, color='red')\n", - "plt.show()\n", - "\n", - "# Stop the timer and calculate the total time needed.\n", - "end = timer()\n", - "print('Time: ', end-start)" - ] - } - ], - "metadata": {}, - "nbformat": 4, - "nbformat_minor": 5 -} diff --git a/doc/LectureNotes/week46.ipynb b/doc/LectureNotes/week46.ipynb deleted file mode 100644 index 87bc2f83d..000000000 --- a/doc/LectureNotes/week46.ipynb +++ /dev/null @@ -1,3131 +0,0 @@ -{ - "cells": [ - { - "cell_type": "markdown", - "id": "f9935da5", - "metadata": { - "editable": true - }, - "source": [ - "\n", - "" - ] - }, - { - "cell_type": "markdown", - "id": "0b990b1c", - "metadata": { - "editable": true - }, - "source": [ - "# Week 46: Decision Trees, Ensemble methods and Random Forests\n", - "**Morten Hjorth-Jensen**, Department of Physics, University of Oslo and Department of Physics and Astronomy and National Superconducting Cyclotron Laboratory, Michigan State University\n", - "\n", - "Date: **Week 46, November 13-17**" - ] - }, - { - "cell_type": "markdown", - "id": "71e9f143", - "metadata": { - "editable": true - }, - "source": [ - "## Plan for week 46\n", - "\n", - "**Active learning sessions on Tuesday and Wednesday.**\n", - "\n", - " * Work and Discussion of project 2\n", - "\n", - " * Discussion of project 3 as well\n", - "\n", - " \n", - "\n", - "**Material for the lecture on Thursday November 16, 2023.**\n", - "\n", - " * Thursday: Basics of decision trees, classification and regression algorithms and ensemble models \n", - "\n", - " * Readings and Videos:\n", - "\n", - " * These lecture notes\n", - "\n", - " * [Video of lecture](https://youtu.be/PMswUwhYa7k)\n", - "\n", - " * [Whiteboard notes](https://github.com/CompPhysics/MachineLearning/blob/master/doc/HandWrittenNotes/2023/NotesNov16.pdf) \n", - "\n", - " * [Video on Decision trees](https://www.youtube.com/watch?v=RmajweUFKvM&ab_channel=Simplilearn)\n", - "\n", - " * Decision Trees: Geron's chapter 6 covers decision trees while ensemble models, voting and bagging are discussed in chapter 7. See also lecture from [STK-IN4300, lecture 7](https://www.uio.no/studier/emner/matnat/math/STK-IN4300/h20/slides/lecture_7.pdf). Chapter 9.2 of Hastie et al contains also a good discussion." - ] - }, - { - "cell_type": "markdown", - "id": "00b82c38", - "metadata": { - "editable": true - }, - "source": [ - "## Decision trees, overarching aims\n", - "\n", - "We start here with the most basic algorithm, the so-called decision\n", - "tree. With this basic algorithm we can in turn build more complex\n", - "networks, spanning from homogeneous and heterogenous forests (bagging,\n", - "random forests and more) to one of the most popular supervised\n", - "algorithms nowadays, the extreme gradient boosting, or just\n", - "XGBoost. But let us start with the simplest possible ingredient.\n", - "\n", - "Decision trees are supervised learning algorithms used for both,\n", - "classification and regression tasks.\n", - "\n", - "The main idea of decision trees\n", - "is to find those descriptive features which contain the most\n", - "**information** regarding the target feature and then split the dataset\n", - "along the values of these features such that the target feature values\n", - "for the resulting underlying datasets are as pure as possible.\n", - "\n", - "The descriptive features which reproduce best the target/output features are normally said\n", - "to be the most informative ones. The process of finding the **most\n", - "informative** feature is done until we accomplish a stopping criteria\n", - "where we then finally end up in so called **leaf nodes**." - ] - }, - { - "cell_type": "markdown", - "id": "c733808f", - "metadata": { - "editable": true - }, - "source": [ - "## Basics of a tree\n", - "\n", - "A decision tree is typically divided into a **root node**, the **interior nodes**,\n", - "and the final **leaf nodes** or just **leaves**. These entities are then connected by so-called **branches**.\n", - "\n", - "The leaf nodes\n", - "contain the predictions we will make for new query instances presented\n", - "to our trained model. This is possible since the model has \n", - "learned the underlying structure of the training data and hence can,\n", - "given some assumptions, make predictions about the target feature value\n", - "(class) of unseen query instances." - ] - }, - { - "cell_type": "markdown", - "id": "2b60a24e", - "metadata": { - "editable": true - }, - "source": [ - "## A typical Decision Tree with its pertinent Jargon, Classification Problem\n", - "\n", - "\n", - "\n", - "\n", - "

Figure 1:

\n", - "\n", - "\n", - "This tree was produced using the Wisconsin cancer data (discussed here as well, see code examples below) using **Scikit-Learn**'s decision tree classifier. Here we have used the so-called **gini** index (see below) to split the various branches." - ] - }, - { - "cell_type": "markdown", - "id": "1a8dc5f7", - "metadata": { - "editable": true - }, - "source": [ - "## General Features\n", - "\n", - "The overarching approach to decision trees is a top-down approach.\n", - "\n", - "* A leaf provides the classification of a given instance.\n", - "\n", - "* A node specifies a test of some attribute of the instance.\n", - "\n", - "* A branch corresponds to a possible values of an attribute.\n", - "\n", - "* An instance is classified by starting at the root node of the tree, testing the attribute specified by this node, then moving down the tree branch corresponding to the value of the attribute in the given example.\n", - "\n", - "This process is then repeated for the subtree rooted at the new\n", - "node." - ] - }, - { - "cell_type": "markdown", - "id": "188465ed", - "metadata": { - "editable": true - }, - "source": [ - "## How do we set it up?\n", - "\n", - "In simplified terms, the process of training a decision tree and\n", - "predicting the target features of query instances is as follows:\n", - "\n", - "1. Present a dataset containing of a number of training instances characterized by a number of descriptive features and a target feature\n", - "\n", - "2. Train the decision tree model by continuously splitting the target feature along the values of the descriptive features using a measure of information gain during the training process\n", - "\n", - "3. Grow the tree until we accomplish a stopping criteria create leaf nodes which represent the *predictions* we want to make for new query instances\n", - "\n", - "4. Show query instances to the tree and run down the tree until we arrive at leaf nodes\n", - "\n", - "Then we are essentially done!" - ] - }, - { - "cell_type": "markdown", - "id": "7f927d1c", - "metadata": { - "editable": true - }, - "source": [ - "## Decision trees and Regression" - ] - }, - { - "cell_type": "code", - "execution_count": 1, - "id": "92377283", - "metadata": { - "collapsed": false, - "editable": true - }, - "outputs": [], - "source": [ - "%matplotlib inline\n", - "\n", - "import numpy as np\n", - "import matplotlib.pyplot as plt\n", - "from sklearn.preprocessing import PolynomialFeatures\n", - "from sklearn.linear_model import LinearRegression\n", - "\n", - "steps=250\n", - "\n", - "distance=0\n", - "x=0\n", - "distance_list=[]\n", - "steps_list=[]\n", - "while x\n", - "\n", - "Grade Trend Hours slept Hours Studied Grade \n", - "\n", - "\n", - " Above Low High Above \n", - " Below High Low Below \n", - " Above Low High Above \n", - " Above High High Above \n", - " Below Low High Below \n", - " Above Low Low Below \n", - " Below High High Below \n", - " Below Low High Below \n", - " Above Low Low Below \n", - " Above High High Above \n", - "\n", - "" - ] - }, - { - "cell_type": "markdown", - "id": "df7b209e", - "metadata": { - "editable": true - }, - "source": [ - "## Computing the various Gini Indices\n", - "\n", - "In computations we will translate all classes into numbers. Being\n", - "these binary classes, they can easily be split into ones and zeros.\n", - "\n", - "**Gini index for Average trend.**\n", - "\n", - "[See handwritten notes November 3](https://github.com/CompPhysics/MachineLearning/blob/master/doc/HandWrittenNotes/2022/NotesNov32022.pdf)" - ] - }, - { - "cell_type": "markdown", - "id": "0f77f79d", - "metadata": { - "editable": true - }, - "source": [ - "## Computing the various Gini Indices, Hours slept\n", - "\n", - "**Gini index for hour slept.**\n", - "\n", - "[See handwritten notes November 3](https://github.com/CompPhysics/MachineLearning/blob/master/doc/HandWrittenNotes/2022/NotesNov32022.pdf)" - ] - }, - { - "cell_type": "markdown", - "id": "737f4e14", - "metadata": { - "editable": true - }, - "source": [ - "## Computing the various Gini Indices, Hours studied\n", - "\n", - "**Gini index for hour studied.**\n", - "\n", - "[See handwritten notes November 3](https://github.com/CompPhysics/MachineLearning/blob/master/doc/HandWrittenNotes/2022/NotesNov32022.pdf)\n", - "\n", - "For final tree, see the above handwritten notes" - ] - }, - { - "cell_type": "markdown", - "id": "e2c139d1", - "metadata": { - "editable": true - }, - "source": [ - "## A possible code using Scikit-Learn" - ] - }, - { - "cell_type": "code", - "execution_count": 6, - "id": "d0089709", - "metadata": { - "collapsed": false, - "editable": true - }, - "outputs": [], - "source": [ - "# Common imports\n", - "import numpy as np\n", - "import pandas as pd\n", - "import matplotlib.pyplot as plt\n", - "from sklearn.tree import DecisionTreeClassifier\n", - "from sklearn.model_selection import train_test_split\n", - "from sklearn.tree import export_graphviz\n", - "from sklearn.preprocessing import StandardScaler, OneHotEncoder\n", - "from sklearn.compose import ColumnTransformer\n", - "from IPython.display import Image \n", - "from pydot import graph_from_dot_data\n", - "import os\n", - "\n", - "# Where to save the figures and data files\n", - "PROJECT_ROOT_DIR = \"Results\"\n", - "FIGURE_ID = \"Results/FigureFiles\"\n", - "DATA_ID = \"DataFiles/\"\n", - "\n", - "if not os.path.exists(PROJECT_ROOT_DIR):\n", - " os.mkdir(PROJECT_ROOT_DIR)\n", - "\n", - "if not os.path.exists(FIGURE_ID):\n", - " os.makedirs(FIGURE_ID)\n", - "\n", - "if not os.path.exists(DATA_ID):\n", - " os.makedirs(DATA_ID)\n", - "\n", - "def image_path(fig_id):\n", - " return os.path.join(FIGURE_ID, fig_id)\n", - "\n", - "def data_path(dat_id):\n", - " return os.path.join(DATA_ID, dat_id)\n", - "\n", - "def save_fig(fig_id):\n", - " plt.savefig(image_path(fig_id) + \".png\", format='png')\n", - "\n", - "infile = open(data_path(\"grades.csv\"),'r')\n", - "\n", - "# Read the experimental data with Pandas\n", - "from IPython.display import display\n", - "grades = pd.read_csv(infile)\n", - "grades = pd.DataFrame(grades)\n", - "display(grades)\n", - "# Features and targets\n", - "X = grades.loc[:, grades.columns != 'Grade'].values\n", - "y = grades.loc[:, grades.columns == 'Grade'].values\n", - "print(X)\n", - "# Then do a Classification tree\n", - "tree_clf = DecisionTreeClassifier(max_depth=2)\n", - "tree_clf.fit(X, y)\n", - "print(\"Train set accuracy with Decision Tree: {:.2f}\".format(tree_clf.score(X,y)))\n", - "#transfer to a decision tree graph\n", - "export_graphviz(\n", - " tree_clf,\n", - " out_file=\"DataFiles/grade.dot\",\n", - " rounded=True,\n", - " filled=True\n", - ")\n", - "cmd = 'dot -Tpng DataFiles/grade.dot -o DataFiles/grades.png'\n", - "os.system(cmd)" - ] - }, - { - "cell_type": "markdown", - "id": "5f185aef", - "metadata": { - "editable": true - }, - "source": [ - "## Further example: Computing the Gini index\n", - "\n", - "The next example we will look at is a classical one in many Machine\n", - "Learning applications. Based on various meteorological features, we\n", - "have several so-called attributes which decide whether we at the end\n", - "will do some outdoor activity like skiing, going for a bike ride etc\n", - "etc. The table here contains the feautures **outlook**, **temperature**,\n", - "**humidity** and **wind**. The target or output is whether we ride\n", - "(True=1) or whether we do something else that day (False=0). The\n", - "attributes for each feature are then sunny, overcast and rain for the\n", - "outlook, hot, cold and mild for temperature, high and normal for\n", - "humidity and weak and strong for wind.\n", - "\n", - "The table here summarizes the various attributes and\n", - "\n", - "\n", - "\n", - "\n", - "\n", - "\n", - "\n", - "\n", - "\n", - "\n", - "\n", - "\n", - "\n", - "\n", - "\n", - "\n", - "\n", - "\n", - "\n", - "\n", - "
Day Outlook Temperature Humidity Wind Ride
1 Sunny Hot High Weak 0
2 Sunny Hot High Strong 1
3 Overcast Hot High Weak 1
4 Rain Mild High Weak 1
5 Rain Cool Normal Weak 1
6 Rain Cool Normal Strong 0
7 Overcast Cool Normal Strong 1
8 Sunny Mild High Weak 0
9 Sunny Cool Normal Weak 1
10 Rain Mild Normal Weak 1
11 Sunny Mild Normal Strong 1
12 Overcast Mild High Strong 1
13 Overcast Hot Normal Weak 1
14 Rain Mild High Strong 0
" - ] - }, - { - "cell_type": "markdown", - "id": "fe73a991", - "metadata": { - "editable": true - }, - "source": [ - "## Simple Python Code to read in Data and perform Classification" - ] - }, - { - "cell_type": "code", - "execution_count": 7, - "id": "9b082c47", - "metadata": { - "collapsed": false, - "editable": true - }, - "outputs": [], - "source": [ - "# Common imports\n", - "import numpy as np\n", - "import pandas as pd\n", - "import matplotlib.pyplot as plt\n", - "from sklearn.tree import DecisionTreeClassifier\n", - "from sklearn.model_selection import train_test_split\n", - "from sklearn.tree import export_graphviz\n", - "from sklearn.preprocessing import StandardScaler, OneHotEncoder\n", - "from sklearn.compose import ColumnTransformer\n", - "from IPython.display import Image \n", - "from pydot import graph_from_dot_data\n", - "import os\n", - "\n", - "# Where to save the figures and data files\n", - "PROJECT_ROOT_DIR = \"Results\"\n", - "FIGURE_ID = \"Results/FigureFiles\"\n", - "DATA_ID = \"DataFiles/\"\n", - "\n", - "if not os.path.exists(PROJECT_ROOT_DIR):\n", - " os.mkdir(PROJECT_ROOT_DIR)\n", - "\n", - "if not os.path.exists(FIGURE_ID):\n", - " os.makedirs(FIGURE_ID)\n", - "\n", - "if not os.path.exists(DATA_ID):\n", - " os.makedirs(DATA_ID)\n", - "\n", - "def image_path(fig_id):\n", - " return os.path.join(FIGURE_ID, fig_id)\n", - "\n", - "def data_path(dat_id):\n", - " return os.path.join(DATA_ID, dat_id)\n", - "\n", - "def save_fig(fig_id):\n", - " plt.savefig(image_path(fig_id) + \".png\", format='png')\n", - "\n", - "infile = open(data_path(\"rideclass.csv\"),'r')\n", - "\n", - "# Read the experimental data with Pandas\n", - "from IPython.display import display\n", - "ridedata = pd.read_csv(infile,names = ('Outlook','Temperature','Humidity','Wind','Ride'))\n", - "ridedata = pd.DataFrame(ridedata)\n", - "\n", - "# Features and targets\n", - "X = ridedata.loc[:, ridedata.columns != 'Ride'].values\n", - "y = ridedata.loc[:, ridedata.columns == 'Ride'].values\n", - "\n", - "# Create the encoder.\n", - "encoder = OneHotEncoder(handle_unknown=\"ignore\")\n", - "# Assume for simplicity all features are categorical.\n", - "encoder.fit(X) \n", - "# Apply the encoder.\n", - "X = encoder.transform(X)\n", - "print(X)\n", - "# Then do a Classification tree\n", - "tree_clf = DecisionTreeClassifier(max_depth=2)\n", - "tree_clf.fit(X, y)\n", - "print(\"Train set accuracy with Decision Tree: {:.2f}\".format(tree_clf.score(X,y)))\n", - "#transfer to a decision tree graph\n", - "export_graphviz(\n", - " tree_clf,\n", - " out_file=\"DataFiles/ride.dot\",\n", - " rounded=True,\n", - " filled=True\n", - ")\n", - "cmd = 'dot -Tpng DataFiles/cancer.dot -o DataFiles/cancer.png'\n", - "os.system(cmd)" - ] - }, - { - "cell_type": "markdown", - "id": "df9287bb", - "metadata": { - "editable": true - }, - "source": [ - "## Computing the Gini Factor\n", - "\n", - "The above functions (gini, entropy and misclassification error) are\n", - "important components of the so-called CART algorithm. We will discuss\n", - "this algorithm below after we have discussed the information gain\n", - "algorithm ID3.\n", - "\n", - "In the example here we have converted all our attributes into numerical values $0,1,2$ etc." - ] - }, - { - "cell_type": "code", - "execution_count": 8, - "id": "00d95a16", - "metadata": { - "collapsed": false, - "editable": true - }, - "outputs": [], - "source": [ - "# Split a dataset based on an attribute and an attribute value\n", - "def test_split(index, value, dataset):\n", - "\tleft, right = list(), list()\n", - "\tfor row in dataset:\n", - "\t\tif row[index] < value:\n", - "\t\t\tleft.append(row)\n", - "\t\telse:\n", - "\t\t\tright.append(row)\n", - "\treturn left, right\n", - " \n", - "# Calculate the Gini index for a split dataset\n", - "def gini_index(groups, classes):\n", - "\t# count all samples at split point\n", - "\tn_instances = float(sum([len(group) for group in groups]))\n", - "\t# sum weighted Gini index for each group\n", - "\tgini = 0.0\n", - "\tfor group in groups:\n", - "\t\tsize = float(len(group))\n", - "\t\t# avoid divide by zero\n", - "\t\tif size == 0:\n", - "\t\t\tcontinue\n", - "\t\tscore = 0.0\n", - "\t\t# score the group based on the score for each class\n", - "\t\tfor class_val in classes:\n", - "\t\t\tp = [row[-1] for row in group].count(class_val) / size\n", - "\t\t\tscore += p * p\n", - "\t\t# weight the group score by its relative size\n", - "\t\tgini += (1.0 - score) * (size / n_instances)\n", - "\treturn gini\n", - "\n", - "# Select the best split point for a dataset\n", - "def get_split(dataset):\n", - "\tclass_values = list(set(row[-1] for row in dataset))\n", - "\tb_index, b_value, b_score, b_groups = 999, 999, 999, None\n", - "\tfor index in range(len(dataset[0])-1):\n", - "\t\tfor row in dataset:\n", - "\t\t\tgroups = test_split(index, row[index], dataset)\n", - "\t\t\tgini = gini_index(groups, class_values)\n", - "\t\t\tprint('X%d < %.3f Gini=%.3f' % ((index+1), row[index], gini))\n", - "\t\t\tif gini < b_score:\n", - "\t\t\t\tb_index, b_value, b_score, b_groups = index, row[index], gini, groups\n", - "\treturn {'index':b_index, 'value':b_value, 'groups':b_groups}\n", - " \n", - "dataset = [[0,0,0,0,0],\n", - " [0,0,0,1,1],\n", - " [1,0,0,0,1],\n", - " [2,1,0,0,1],\n", - " [2,2,1,0,1],\n", - " [2,2,1,1,0],\n", - " [1,2,1,1,1],\n", - " [0,1,0,0,0],\n", - " [0,2,1,0,1],\n", - " [2,1,1,0,1],\n", - " [0,1,1,1,1],\n", - " [1,1,0,1,1],\n", - " [1,0,1,0,1],\n", - " [2,1,0,1,0]]\n", - "\n", - "split = get_split(dataset)\n", - "print('Split: [X%d < %.3f]' % ((split['index']+1), split['value']))" - ] - }, - { - "cell_type": "markdown", - "id": "b6452b51", - "metadata": { - "editable": true - }, - "source": [ - "## Regression trees" - ] - }, - { - "cell_type": "code", - "execution_count": 9, - "id": "3a98b310", - "metadata": { - "collapsed": false, - "editable": true - }, - "outputs": [], - "source": [ - "# Quadratic training set + noise\n", - "np.random.seed(42)\n", - "m = 200\n", - "X = np.random.rand(m, 1)\n", - "y = 4 * (X - 0.5) ** 2\n", - "y = y + np.random.randn(m, 1) / 10" - ] - }, - { - "cell_type": "code", - "execution_count": 10, - "id": "1f8e183f", - "metadata": { - "collapsed": false, - "editable": true - }, - "outputs": [], - "source": [ - "from sklearn.tree import DecisionTreeRegressor\n", - "\n", - "tree_reg = DecisionTreeRegressor(max_depth=2, random_state=42)\n", - "tree_reg.fit(X, y)" - ] - }, - { - "cell_type": "markdown", - "id": "6c91981e", - "metadata": { - "editable": true - }, - "source": [ - "## Final regressor code" - ] - }, - { - "cell_type": "code", - "execution_count": 11, - "id": "c9b69f54", - "metadata": { - "collapsed": false, - "editable": true - }, - "outputs": [], - "source": [ - "from sklearn.tree import DecisionTreeRegressor\n", - "\n", - "tree_reg1 = DecisionTreeRegressor(random_state=42, max_depth=2)\n", - "tree_reg2 = DecisionTreeRegressor(random_state=42, max_depth=3)\n", - "tree_reg1.fit(X, y)\n", - "tree_reg2.fit(X, y)\n", - "\n", - "def plot_regression_predictions(tree_reg, X, y, axes=[0, 1, -0.2, 1], ylabel=\"$y$\"):\n", - " x1 = np.linspace(axes[0], axes[1], 500).reshape(-1, 1)\n", - " y_pred = tree_reg.predict(x1)\n", - " plt.axis(axes)\n", - " plt.xlabel(\"$x_1$\", fontsize=18)\n", - " if ylabel:\n", - " plt.ylabel(ylabel, fontsize=18, rotation=0)\n", - " plt.plot(X, y, \"b.\")\n", - " plt.plot(x1, y_pred, \"r.-\", linewidth=2, label=r\"$\\hat{y}$\")\n", - "\n", - "plt.figure(figsize=(11, 4))\n", - "plt.subplot(121)\n", - "plot_regression_predictions(tree_reg1, X, y)\n", - "for split, style in ((0.1973, \"k-\"), (0.0917, \"k--\"), (0.7718, \"k--\")):\n", - " plt.plot([split, split], [-0.2, 1], style, linewidth=2)\n", - "plt.text(0.21, 0.65, \"Depth=0\", fontsize=15)\n", - "plt.text(0.01, 0.2, \"Depth=1\", fontsize=13)\n", - "plt.text(0.65, 0.8, \"Depth=1\", fontsize=13)\n", - "plt.legend(loc=\"upper center\", fontsize=18)\n", - "plt.title(\"max_depth=2\", fontsize=14)\n", - "\n", - "plt.subplot(122)\n", - "plot_regression_predictions(tree_reg2, X, y, ylabel=None)\n", - "for split, style in ((0.1973, \"k-\"), (0.0917, \"k--\"), (0.7718, \"k--\")):\n", - " plt.plot([split, split], [-0.2, 1], style, linewidth=2)\n", - "for split in (0.0458, 0.1298, 0.2873, 0.9040):\n", - " plt.plot([split, split], [-0.2, 1], \"k:\", linewidth=1)\n", - "plt.text(0.3, 0.5, \"Depth=2\", fontsize=13)\n", - "plt.title(\"max_depth=3\", fontsize=14)\n", - "\n", - "plt.show()" - ] - }, - { - "cell_type": "code", - "execution_count": 12, - "id": "53db8f73", - "metadata": { - "collapsed": false, - "editable": true - }, - "outputs": [], - "source": [ - "tree_reg1 = DecisionTreeRegressor(random_state=42)\n", - "tree_reg2 = DecisionTreeRegressor(random_state=42, min_samples_leaf=10)\n", - "tree_reg1.fit(X, y)\n", - "tree_reg2.fit(X, y)\n", - "\n", - "x1 = np.linspace(0, 1, 500).reshape(-1, 1)\n", - "y_pred1 = tree_reg1.predict(x1)\n", - "y_pred2 = tree_reg2.predict(x1)\n", - "\n", - "plt.figure(figsize=(11, 4))\n", - "\n", - "plt.subplot(121)\n", - "plt.plot(X, y, \"b.\")\n", - "plt.plot(x1, y_pred1, \"r.-\", linewidth=2, label=r\"$\\hat{y}$\")\n", - "plt.axis([0, 1, -0.2, 1.1])\n", - "plt.xlabel(\"$x_1$\", fontsize=18)\n", - "plt.ylabel(\"$y$\", fontsize=18, rotation=0)\n", - "plt.legend(loc=\"upper center\", fontsize=18)\n", - "plt.title(\"No restrictions\", fontsize=14)\n", - "\n", - "plt.subplot(122)\n", - "plt.plot(X, y, \"b.\")\n", - "plt.plot(x1, y_pred2, \"r.-\", linewidth=2, label=r\"$\\hat{y}$\")\n", - "plt.axis([0, 1, -0.2, 1.1])\n", - "plt.xlabel(\"$x_1$\", fontsize=18)\n", - "plt.title(\"min_samples_leaf={}\".format(tree_reg2.min_samples_leaf), fontsize=14)\n", - "\n", - "plt.show()" - ] - }, - { - "cell_type": "markdown", - "id": "3be38ddf", - "metadata": { - "editable": true - }, - "source": [ - "## Pros and cons of trees, pros\n", - "\n", - "* White box, easy to interpret model. Some people believe that decision trees more closely mirror human decision-making than do the regression and classification approaches discussed earlier (think of support vector machines)\n", - "\n", - "* Trees are very easy to explain to people. In fact, they are even easier to explain than linear regression!\n", - "\n", - "* No feature normalization needed\n", - "\n", - "* Tree models can handle both continuous and categorical data (Classification and Regression Trees)\n", - "\n", - "* Can model nonlinear relationships\n", - "\n", - "* Can model interactions between the different descriptive features\n", - "\n", - "* Trees can be displayed graphically, and are easily interpreted even by a non-expert (especially if they are small)" - ] - }, - { - "cell_type": "markdown", - "id": "e4aaab5f", - "metadata": { - "editable": true - }, - "source": [ - "## Disadvantages\n", - "\n", - "* Unfortunately, trees generally do not have the same level of predictive accuracy as some of the other regression and classification approaches\n", - "\n", - "* If continuous features are used the tree may become quite large and hence less interpretable\n", - "\n", - "* Decision trees are prone to overfit the training data and hence do not well generalize the data if no stopping criteria or improvements like pruning, boosting or bagging are implemented\n", - "\n", - "* Small changes in the data may lead to a completely different tree. This issue can be addressed by using ensemble methods like bagging, boosting or random forests\n", - "\n", - "* Unbalanced datasets where some target feature values occur much more frequently than others may lead to biased trees since the frequently occurring feature values are preferred over the less frequently occurring ones. \n", - "\n", - "* If the number of features is relatively large (high dimensional) and the number of instances is relatively low, the tree might overfit the data\n", - "\n", - "* Features with many levels may be preferred over features with less levels since for them it is *more easy* to split the dataset such that the sub datasets only contain pure target feature values. This issue can be addressed by preferring for instance the information gain ratio as splitting criteria over information gain\n", - "\n", - "However, by aggregating many decision trees, using methods like\n", - "bagging, random forests, and boosting, the predictive performance of\n", - "trees can be substantially improved." - ] - }, - { - "cell_type": "markdown", - "id": "0010cb58", - "metadata": { - "editable": true - }, - "source": [ - "## Ensemble Methods: From a Single Tree to Many Trees and Extreme Boosting, Meet the Jungle of Methods\n", - "\n", - "As stated above and seen in many of the examples discussed here about\n", - "a single decision tree, we often end up overfitting our training\n", - "data. This normally means that we have a high variance. Can we reduce\n", - "the variance of a statistical learning method?\n", - "\n", - "This leads us to a set of different methods that can combine different\n", - "machine learning algorithms or just use one of them to construct\n", - "forests and jungles of trees, homogeneous ones or heterogenous\n", - "ones. These methods are recognized by different names which we will\n", - "try to explain here. These are\n", - "\n", - "1. Voting classifiers\n", - "\n", - "2. Bagging and Pasting\n", - "\n", - "3. Random forests\n", - "\n", - "4. Boosting methods, from adaptive to Extreme Gradient Boosting (XGBoost)\n", - "\n", - "We discuss these methods here." - ] - }, - { - "cell_type": "markdown", - "id": "f3a71c11", - "metadata": { - "editable": true - }, - "source": [ - "## An Overview of Ensemble Methods\n", - "\n", - "\n", - "\n", - "\n", - "

Figure 1:

\n", - "" - ] - }, - { - "cell_type": "markdown", - "id": "aef5e772", - "metadata": { - "editable": true - }, - "source": [ - "## Why Voting?\n", - "\n", - "The idea behind boosting, and voting as well can be phrased as follows:\n", - "**Can a group of people somehow arrive at highly\n", - "reasoned decisions, despite the weak judgement of the individual\n", - "members?**\n", - "\n", - "The aim is to create a good classifier by combining several weak classifiers.\n", - "**A weak classifier is a classifier which is able to produce results that are only slightly better than guessing at random.**\n", - "\n", - "The basic approach is to apply repeatedly (in boosting this is done in an iterative way) a weak classifier to modifications of the data.\n", - "In voting we simply apply the law of large numbers while in boosting we give more weight to misclassified data in\n", - "each iteration. \n", - "\n", - "Decision trees play an important role as our weak classifier. They serve as the basic method." - ] - }, - { - "cell_type": "markdown", - "id": "a30b02f8", - "metadata": { - "editable": true - }, - "source": [ - "## Tossing coins\n", - "\n", - "The simplest case is a so-called voting ensemble. To illustrate this,\n", - "think of yourself tossing coins with a biased outcome of 51 per cent\n", - "for heads and 49% for tails. With only few tosses,\n", - "you may not clearly see this distribution for heads and tails. However, after some\n", - "thousands of tosses, there will be a clear majority of heads. With 2000 tosses\n", - "you should see approximately 1020 heads and 980 tails.\n", - "\n", - "We can then state that the outcome is a clear majority of heads. If\n", - "you do this ten thousand times, it is easy to see that there is a 97%\n", - "likelihood of a majority of heads.\n", - "\n", - "Another example would be to collect all polls before an\n", - "election. Different polls may show different likelihoods for a\n", - "candidate winning with say a majority of the popular vote. The majority vote\n", - "would then consist in many polls indicating that this candidate will\n", - "actually win.\n", - "\n", - "The example here shows how we can implement the coin tossing case,\n", - "clealry demostrating that after some tosses we see the [law of large](https://en.wikipedia.org/wiki/Law_of_large_numbers)\n", - "numbers kicking in." - ] - }, - { - "cell_type": "markdown", - "id": "3afd02ed", - "metadata": { - "editable": true - }, - "source": [ - "## Standard imports first" - ] - }, - { - "cell_type": "code", - "execution_count": 13, - "id": "4a1b7a89", - "metadata": { - "collapsed": false, - "editable": true - }, - "outputs": [], - "source": [ - "# Common imports\n", - "from IPython.display import Image \n", - "from pydot import graph_from_dot_data\n", - "import pandas as pd\n", - "import numpy as np\n", - "import matplotlib.pyplot as plt\n", - "from sklearn.tree import DecisionTreeClassifier\n", - "from sklearn.model_selection import train_test_split\n", - "from sklearn.tree import export_graphviz\n", - "from sklearn.preprocessing import StandardScaler, OneHotEncoder\n", - "from sklearn.compose import ColumnTransformer\n", - "from IPython.display import Image \n", - "from pydot import graph_from_dot_data\n", - "import os\n", - "\n", - "# Where to save the figures and data files\n", - "PROJECT_ROOT_DIR = \"Results\"\n", - "FIGURE_ID = \"Results/FigureFiles\"\n", - "DATA_ID = \"DataFiles/\"\n", - "\n", - "if not os.path.exists(PROJECT_ROOT_DIR):\n", - " os.mkdir(PROJECT_ROOT_DIR)\n", - "\n", - "if not os.path.exists(FIGURE_ID):\n", - " os.makedirs(FIGURE_ID)\n", - "\n", - "if not os.path.exists(DATA_ID):\n", - " os.makedirs(DATA_ID)\n", - "\n", - "def image_path(fig_id):\n", - " return os.path.join(FIGURE_ID, fig_id)\n", - "\n", - "def data_path(dat_id):\n", - " return os.path.join(DATA_ID, dat_id)\n", - "\n", - "def save_fig(fig_id):\n", - " plt.savefig(image_path(fig_id) + \".png\", format='png')" - ] - }, - { - "cell_type": "markdown", - "id": "0c32e96d", - "metadata": { - "editable": true - }, - "source": [ - "## Simple Voting Example, head or tail" - ] - }, - { - "cell_type": "code", - "execution_count": 14, - "id": "4d1c99f7", - "metadata": { - "collapsed": false, - "editable": true - }, - "outputs": [], - "source": [ - "\n", - "# Common imports\n", - "import numpy as np\n", - "import matplotlib\n", - "import matplotlib.pyplot as plt\n", - "from matplotlib.colors import ListedColormap\n", - "plt.rcParams['axes.labelsize'] = 14\n", - "plt.rcParams['xtick.labelsize'] = 12\n", - "plt.rcParams['ytick.labelsize'] = 12\n", - "\n", - "heads_proba = 0.51\n", - "coin_tosses = (np.random.rand(10000, 10) < heads_proba).astype(np.int32)\n", - "cumulative_heads_ratio = np.cumsum(coin_tosses, axis=0) / np.arange(1, 10001).reshape(-1, 1)\n", - "plt.figure(figsize=(8,3.5))\n", - "plt.plot(cumulative_heads_ratio)\n", - "plt.plot([0, 10000], [0.51, 0.51], \"k--\", linewidth=2, label=\"51%\")\n", - "plt.plot([0, 10000], [0.5, 0.5], \"k-\", label=\"50%\")\n", - "plt.xlabel(\"Number of coin tosses\")\n", - "plt.ylabel(\"Heads ratio\")\n", - "plt.legend(loc=\"lower right\")\n", - "plt.axis([0, 10000, 0.42, 0.58])\n", - "save_fig(\"votingsimple\")\n", - "plt.show()" - ] - }, - { - "cell_type": "markdown", - "id": "e0e3f1dc", - "metadata": { - "editable": true - }, - "source": [ - "## Using the Voting Classifier\n", - "\n", - "We can use the voting classifier on other data sets, here the exciting binary case of two distinct objects using the make moons functionality of **Scikit-Learn**." - ] - }, - { - "cell_type": "code", - "execution_count": 15, - "id": "c3d00f7d", - "metadata": { - "collapsed": false, - "editable": true - }, - "outputs": [], - "source": [ - "from sklearn.model_selection import train_test_split\n", - "from sklearn.datasets import make_moons\n", - "\n", - "X, y = make_moons(n_samples=500, noise=0.30, random_state=42)\n", - "X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=42)\n", - "\n", - "from sklearn.ensemble import RandomForestClassifier\n", - "from sklearn.ensemble import VotingClassifier\n", - "from sklearn.linear_model import LogisticRegression\n", - "from sklearn.svm import SVC\n", - "\n", - "log_clf = LogisticRegression(solver=\"liblinear\", random_state=42)\n", - "rnd_clf = RandomForestClassifier(n_estimators=10, random_state=42)\n", - "svm_clf = SVC(gamma=\"auto\", random_state=42)\n", - "\n", - "voting_clf = VotingClassifier(\n", - " estimators=[('lr', log_clf), ('rf', rnd_clf), ('svc', svm_clf)],\n", - " voting='hard')\n", - "\n", - "voting_clf.fit(X_train, y_train)\n", - "\n", - "from sklearn.metrics import accuracy_score\n", - "\n", - "for clf in (log_clf, rnd_clf, svm_clf, voting_clf):\n", - " clf.fit(X_train, y_train)\n", - " y_pred = clf.predict(X_test)\n", - " print(clf.__class__.__name__, accuracy_score(y_test, y_pred))\n", - "\n", - "log_clf = LogisticRegression(solver=\"liblinear\", random_state=42)\n", - "rnd_clf = RandomForestClassifier(n_estimators=10, random_state=42)\n", - "svm_clf = SVC(gamma=\"auto\", probability=True, random_state=42)\n", - "voting_clf = VotingClassifier(\n", - " estimators=[('lr', log_clf), ('rf', rnd_clf), ('svc', svm_clf)],\n", - " voting='soft')\n", - "voting_clf.fit(X_train, y_train)\n", - "\n", - "from sklearn.metrics import accuracy_score\n", - "\n", - "for clf in (log_clf, rnd_clf, svm_clf, voting_clf):\n", - " clf.fit(X_train, y_train)\n", - " y_pred = clf.predict(X_test)\n", - " print(clf.__class__.__name__, accuracy_score(y_test, y_pred))" - ] - }, - { - "cell_type": "markdown", - "id": "f0d12f2c", - "metadata": { - "editable": true - }, - "source": [ - "## Voting and Bagging" - ] - }, - { - "cell_type": "code", - "execution_count": 16, - "id": "1bbde2a9", - "metadata": { - "collapsed": false, - "editable": true - }, - "outputs": [], - "source": [ - "from sklearn.model_selection import train_test_split\n", - "from sklearn.datasets import make_moons\n", - "\n", - "X, y = make_moons(n_samples=500, noise=0.30, random_state=42)\n", - "X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=42)\n", - "from sklearn.ensemble import RandomForestClassifier\n", - "from sklearn.ensemble import VotingClassifier\n", - "from sklearn.linear_model import LogisticRegression\n", - "from sklearn.svm import SVC\n", - "\n", - "log_clf = LogisticRegression(random_state=42)\n", - "rnd_clf = RandomForestClassifier(random_state=42)\n", - "svm_clf = SVC(random_state=42)\n", - "\n", - "voting_clf = VotingClassifier(\n", - " estimators=[('lr', log_clf), ('rf', rnd_clf), ('svc', svm_clf)],\n", - " voting='hard')\n", - "voting_clf.fit(X_train, y_train)" - ] - }, - { - "cell_type": "code", - "execution_count": 17, - "id": "80a82744", - "metadata": { - "collapsed": false, - "editable": true - }, - "outputs": [], - "source": [ - "from sklearn.metrics import accuracy_score\n", - "\n", - "for clf in (log_clf, rnd_clf, svm_clf, voting_clf):\n", - " clf.fit(X_train, y_train)\n", - " y_pred = clf.predict(X_test)\n", - " print(clf.__class__.__name__, accuracy_score(y_test, y_pred))" - ] - }, - { - "cell_type": "code", - "execution_count": 18, - "id": "65c732b4", - "metadata": { - "collapsed": false, - "editable": true - }, - "outputs": [], - "source": [ - "log_clf = LogisticRegression(random_state=42)\n", - "rnd_clf = RandomForestClassifier(random_state=42)\n", - "svm_clf = SVC(probability=True, random_state=42)\n", - "\n", - "voting_clf = VotingClassifier(\n", - " estimators=[('lr', log_clf), ('rf', rnd_clf), ('svc', svm_clf)],\n", - " voting='soft')\n", - "voting_clf.fit(X_train, y_train)" - ] - }, - { - "cell_type": "code", - "execution_count": 19, - "id": "956f7ec5", - "metadata": { - "collapsed": false, - "editable": true - }, - "outputs": [], - "source": [ - "from sklearn.metrics import accuracy_score\n", - "\n", - "for clf in (log_clf, rnd_clf, svm_clf, voting_clf):\n", - " clf.fit(X_train, y_train)\n", - " y_pred = clf.predict(X_test)\n", - " print(clf.__class__.__name__, accuracy_score(y_test, y_pred))" - ] - }, - { - "cell_type": "markdown", - "id": "ee527167", - "metadata": { - "editable": true - }, - "source": [ - "## Bagging\n", - "\n", - "The **plain** decision trees suffer from high\n", - "variance. This means that if we split the training data into two parts\n", - "at random, and fit a decision tree to both halves, the results that we\n", - "get could be quite different. In contrast, a procedure with low\n", - "variance will yield similar results if applied repeatedly to distinct\n", - "data sets; linear regression tends to have low variance, if the ratio\n", - "of $n$ to $p$ is moderately large. \n", - "\n", - "**Bootstrap aggregation**, or just **bagging**, is a\n", - "general-purpose procedure for reducing the variance of a statistical\n", - "learning method." - ] - }, - { - "cell_type": "markdown", - "id": "354baed9", - "metadata": { - "editable": true - }, - "source": [ - "## More bagging\n", - "\n", - "Bagging typically results in improved accuracy\n", - "over prediction using a single tree. Unfortunately, however, it can be\n", - "difficult to interpret the resulting model. Recall that one of the\n", - "advantages of decision trees is the attractive and easily interpreted\n", - "diagram that results.\n", - "\n", - "However, when we bag a large number of trees, it is no longer\n", - "possible to represent the resulting statistical learning procedure\n", - "using a single tree, and it is no longer clear which variables are\n", - "most important to the procedure. Thus, bagging improves prediction\n", - "accuracy at the expense of interpretability. Although the collection\n", - "of bagged trees is much more difficult to interpret than a single\n", - "tree, one can obtain an overall summary of the importance of each\n", - "predictor using the MSE (for bagging regression trees) or the Gini\n", - "index (for bagging classification trees). In the case of bagging\n", - "regression trees, we can record the total amount that the MSE is\n", - "decreased due to splits over a given predictor, averaged over all $B$ possible\n", - "trees. A large value indicates an important predictor. Similarly, in\n", - "the context of bagging classification trees, we can add up the total\n", - "amount that the Gini index is decreased by splits over a given\n", - "predictor, averaged over all $B$ trees." - ] - }, - { - "cell_type": "markdown", - "id": "fc1a2451", - "metadata": { - "editable": true - }, - "source": [ - "## Making your own Bootstrap: Changing the Level of the Decision Tree\n", - "\n", - "Let us bring up our good old boostrap example from the linear regression lectures. We change the linerar regression algorithm with\n", - "a decision tree wth different depths and perform a bootstrap aggregate (in this case we perform as many bootstraps as data points $n$)." - ] - }, - { - "cell_type": "code", - "execution_count": 20, - "id": "129bb9fb", - "metadata": { - "collapsed": false, - "editable": true - }, - "outputs": [], - "source": [ - "\n", - "import matplotlib.pyplot as plt\n", - "import numpy as np\n", - "from sklearn.model_selection import train_test_split\n", - "from sklearn.pipeline import make_pipeline\n", - "from sklearn.utils import resample\n", - "from sklearn.tree import DecisionTreeRegressor\n", - "\n", - "n = 100\n", - "n_boostraps = 100\n", - "maxdepth = 8\n", - "\n", - "# Make data set.\n", - "x = np.linspace(-3, 3, n).reshape(-1, 1)\n", - "y = np.exp(-x**2) + 1.5 * np.exp(-(x-2)**2)+ np.random.normal(0, 0.1, x.shape)\n", - "error = np.zeros(maxdepth)\n", - "bias = np.zeros(maxdepth)\n", - "variance = np.zeros(maxdepth)\n", - "polydegree = np.zeros(maxdepth)\n", - "X_train, X_test, y_train, y_test = train_test_split(x, y, test_size=0.2)\n", - "\n", - "from sklearn.preprocessing import StandardScaler\n", - "scaler = StandardScaler()\n", - "scaler.fit(X_train)\n", - "X_train_scaled = scaler.transform(X_train)\n", - "X_test_scaled = scaler.transform(X_test)\n", - "\n", - "# we produce a simple tree first as benchmark\n", - "simpletree = DecisionTreeRegressor(max_depth=3) \n", - "simpletree.fit(X_train_scaled, y_train)\n", - "simpleprediction = simpletree.predict(X_test_scaled)\n", - "for degree in range(1,maxdepth):\n", - " model = DecisionTreeRegressor(max_depth=degree) \n", - " y_pred = np.empty((y_test.shape[0], n_boostraps))\n", - " for i in range(n_boostraps):\n", - " x_, y_ = resample(X_train_scaled, y_train)\n", - " model.fit(x_, y_)\n", - " y_pred[:, i] = model.predict(X_test_scaled)#.ravel()\n", - "\n", - " polydegree[degree] = degree\n", - " error[degree] = np.mean( np.mean((y_test - y_pred)**2, axis=1, keepdims=True) )\n", - " bias[degree] = np.mean( (y_test - np.mean(y_pred, axis=1, keepdims=True))**2 )\n", - " variance[degree] = np.mean( np.var(y_pred, axis=1, keepdims=True) )\n", - " print('Polynomial degree:', degree)\n", - " print('Error:', error[degree])\n", - " print('Bias^2:', bias[degree])\n", - " print('Var:', variance[degree])\n", - " print('{} >= {} + {} = {}'.format(error[degree], bias[degree], variance[degree], bias[degree]+variance[degree]))\n", - " \n", - "mse_simpletree= np.mean( np.mean((y_test - simpleprediction)**2))\n", - "print(\"Simple tree:\",mse_simpletree)\n", - "plt.xlim(1,maxdepth)\n", - "plt.plot(polydegree, error, label='MSE')\n", - "plt.plot(polydegree, bias, label='bias')\n", - "plt.plot(polydegree, variance, label='Variance')\n", - "plt.legend()\n", - "save_fig(\"baggingboot\")\n", - "plt.show()" - ] - }, - { - "cell_type": "markdown", - "id": "170b00ab", - "metadata": { - "editable": true - }, - "source": [ - "## Random forests\n", - "\n", - "Random forests provide an improvement over bagged trees by way of a\n", - "small tweak that decorrelates the trees. \n", - "\n", - "As in bagging, we build a\n", - "number of decision trees on bootstrapped training samples. But when\n", - "building these decision trees, each time a split in a tree is\n", - "considered, a random sample of $m$ predictors is chosen as split\n", - "candidates from the full set of $p$ predictors. The split is allowed to\n", - "use only one of those $m$ predictors. \n", - "\n", - "A fresh sample of $m$ predictors is\n", - "taken at each split, and typically we choose" - ] - }, - { - "cell_type": "markdown", - "id": "58a4aa65", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "m\\approx \\sqrt{p}.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "a5ed07c1", - "metadata": { - "editable": true - }, - "source": [ - "In building a random forest, at\n", - "each split in the tree, the algorithm is not even allowed to consider\n", - "a majority of the available predictors. \n", - "\n", - "The reason for this is rather clever. Suppose that there is one very\n", - "strong predictor in the data set, along with a number of other\n", - "moderately strong predictors. Then in the collection of bagged\n", - "variable importance random forest trees, most or all of the trees will\n", - "use this strong predictor in the top split. Consequently, all of the\n", - "bagged trees will look quite similar to each other. Hence the\n", - "predictions from the bagged trees will be highly correlated.\n", - "Unfortunately, averaging many highly correlated quantities does not\n", - "lead to as large of a reduction in variance as averaging many\n", - "uncorrelated quantities. In particular, this means that bagging will\n", - "not lead to a substantial reduction in variance over a single tree in\n", - "this setting." - ] - }, - { - "cell_type": "markdown", - "id": "c5369edb", - "metadata": { - "editable": true - }, - "source": [ - "## Random Forest Algorithm\n", - "The algorithm described here can be applied to both classification and regression problems.\n", - "\n", - "We will grow of forest of say $B$ trees.\n", - "1. For $b=1:B$\n", - "\n", - " * Draw a bootstrap sample from the training data organized in our $\\boldsymbol{X}$ matrix.\n", - "\n", - " * We grow then a random forest tree $T_b$ based on the bootstrapped data by repeating the steps outlined till we reach the maximum node size is reached\n", - "\n", - "1. we select $m \\le p$ variables at random from the $p$ predictors/features\n", - "\n", - "2. pick the best split point among the $m$ features using for example the CART algorithm and create a new node\n", - "\n", - "3. split the node into daughter nodes\n", - "\n", - "4. Output then the ensemble of trees $\\{T_b\\}_1^{B}$ and make predictions for either a regression type of problem or a classification type of problem." - ] - }, - { - "cell_type": "markdown", - "id": "4355c5ad", - "metadata": { - "editable": true - }, - "source": [ - "## Random Forests Compared with other Methods on the Cancer Data" - ] - }, - { - "cell_type": "code", - "execution_count": 21, - "id": "0fbcd18f", - "metadata": { - "collapsed": false, - "editable": true - }, - "outputs": [], - "source": [ - "import matplotlib.pyplot as plt\n", - "import numpy as np\n", - "from sklearn.model_selection import train_test_split \n", - "from sklearn.datasets import load_breast_cancer\n", - "from sklearn.svm import SVC\n", - "from sklearn.linear_model import LogisticRegression\n", - "from sklearn.tree import DecisionTreeClassifier\n", - "from sklearn.ensemble import BaggingClassifier\n", - "\n", - "# Load the data\n", - "cancer = load_breast_cancer()\n", - "\n", - "X_train, X_test, y_train, y_test = train_test_split(cancer.data,cancer.target,random_state=0)\n", - "print(X_train.shape)\n", - "print(X_test.shape)\n", - "#define methods\n", - "# Logistic Regression\n", - "logreg = LogisticRegression(solver='lbfgs')\n", - "# Support vector machine\n", - "svm = SVC(gamma='auto', C=100)\n", - "# Decision Trees\n", - "deep_tree_clf = DecisionTreeClassifier(max_depth=None)\n", - "#Scale the data\n", - "from sklearn.preprocessing import StandardScaler\n", - "scaler = StandardScaler()\n", - "scaler.fit(X_train)\n", - "X_train_scaled = scaler.transform(X_train)\n", - "X_test_scaled = scaler.transform(X_test)\n", - "# Logistic Regression\n", - "logreg.fit(X_train_scaled, y_train)\n", - "print(\"Test set accuracy Logistic Regression with scaled data: {:.2f}\".format(logreg.score(X_test_scaled,y_test)))\n", - "# Support Vector Machine\n", - "svm.fit(X_train_scaled, y_train)\n", - "print(\"Test set accuracy SVM with scaled data: {:.2f}\".format(logreg.score(X_test_scaled,y_test)))\n", - "# Decision Trees\n", - "deep_tree_clf.fit(X_train_scaled, y_train)\n", - "print(\"Test set accuracy with Decision Trees and scaled data: {:.2f}\".format(deep_tree_clf.score(X_test_scaled,y_test)))\n", - "\n", - "\n", - "from sklearn.ensemble import RandomForestClassifier\n", - "from sklearn.preprocessing import LabelEncoder\n", - "from sklearn.model_selection import cross_validate\n", - "# Data set not specificied\n", - "#Instantiate the model with 500 trees and entropy as splitting criteria\n", - "Random_Forest_model = RandomForestClassifier(n_estimators=500,criterion=\"entropy\")\n", - "Random_Forest_model.fit(X_train_scaled, y_train)\n", - "#Cross validation\n", - "accuracy = cross_validate(Random_Forest_model,X_test_scaled,y_test,cv=10)['test_score']\n", - "print(accuracy)\n", - "print(\"Test set accuracy with Random Forests and scaled data: {:.2f}\".format(Random_Forest_model.score(X_test_scaled,y_test)))\n", - "\n", - "\n", - "import scikitplot as skplt\n", - "y_pred = Random_Forest_model.predict(X_test_scaled)\n", - "skplt.metrics.plot_confusion_matrix(y_test, y_pred, normalize=True)\n", - "plt.show()\n", - "y_probas = Random_Forest_model.predict_proba(X_test_scaled)\n", - "skplt.metrics.plot_roc(y_test, y_probas)\n", - "plt.show()\n", - "skplt.metrics.plot_cumulative_gain(y_test, y_probas)\n", - "plt.show()" - ] - }, - { - "cell_type": "markdown", - "id": "4072de62", - "metadata": { - "editable": true - }, - "source": [ - "Recall that the cumulative gains curve shows the percentage of the\n", - "overall number of cases in a given category *gained* by targeting a\n", - "percentage of the total number of cases.\n", - "\n", - "Similarly, the receiver operating characteristic curve, or ROC curve,\n", - "displays the diagnostic ability of a binary classifier system as its\n", - "discrimination threshold is varied. It plots the true positive rate against the false positive rate." - ] - }, - { - "cell_type": "markdown", - "id": "481673fb", - "metadata": { - "editable": true - }, - "source": [ - "## Compare Bagging on Trees with Random Forests" - ] - }, - { - "cell_type": "code", - "execution_count": 22, - "id": "d5fe5939", - "metadata": { - "collapsed": false, - "editable": true - }, - "outputs": [], - "source": [ - "bag_clf = BaggingClassifier(\n", - " DecisionTreeClassifier(splitter=\"random\", max_leaf_nodes=16, random_state=42),\n", - " n_estimators=500, max_samples=1.0, bootstrap=True, n_jobs=-1, random_state=42)" - ] - }, - { - "cell_type": "code", - "execution_count": 23, - "id": "7ee6160d", - "metadata": { - "collapsed": false, - "editable": true - }, - "outputs": [], - "source": [ - "bag_clf.fit(X_train, y_train)\n", - "y_pred = bag_clf.predict(X_test)\n", - "from sklearn.ensemble import RandomForestClassifier\n", - "rnd_clf = RandomForestClassifier(n_estimators=500, max_leaf_nodes=16, n_jobs=-1, random_state=42)\n", - "rnd_clf.fit(X_train, y_train)\n", - "y_pred_rf = rnd_clf.predict(X_test)\n", - "np.sum(y_pred == y_pred_rf) / len(y_pred)" - ] - }, - { - "cell_type": "markdown", - "id": "3a6e484c", - "metadata": { - "editable": true - }, - "source": [ - "## Boosting, a Bird's Eye View\n", - "\n", - "The basic idea is to combine weak classifiers in order to create a good\n", - "classifier. With a weak classifier we often intend a classifier which\n", - "produces results which are only slightly better than we would get by\n", - "random guesses.\n", - "\n", - "This is done by applying in an iterative way a weak (or a standard\n", - "classifier like decision trees) to modify the data. In each iteration\n", - "we emphasize those observations which are misclassified by weighting\n", - "them with a factor." - ] - }, - { - "cell_type": "markdown", - "id": "ed91ea28", - "metadata": { - "editable": true - }, - "source": [ - "## What is boosting? Additive Modelling/Iterative Fitting\n", - "\n", - "Boosting is a way of fitting an additive expansion in a set of\n", - "elementary basis functions like for example some simple polynomials.\n", - "Assume for example that we have a function" - ] - }, - { - "cell_type": "markdown", - "id": "9ab6f212", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "f_M(x) = \\sum_{i=1}^M \\beta_m b(x;\\gamma_m),\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "288a57f1", - "metadata": { - "editable": true - }, - "source": [ - "where $\\beta_m$ are the expansion parameters to be determined in a\n", - "minimization process and $b(x;\\gamma_m)$ are some simple functions of\n", - "the multivariable parameter $x$ which is characterized by the\n", - "parameters $\\gamma_m$.\n", - "\n", - "As an example, consider the Sigmoid function we used in logistic\n", - "regression. In that case, we can translate the function\n", - "$b(x;\\gamma_m)$ into the Sigmoid function" - ] - }, - { - "cell_type": "markdown", - "id": "d0ea7a14", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\sigma(t) = \\frac{1}{1+\\exp{(-t)}},\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "faa1b446", - "metadata": { - "editable": true - }, - "source": [ - "where $t=\\gamma_0+\\gamma_1 x$ and the parameters $\\gamma_0$ and\n", - "$\\gamma_1$ were determined by the Logistic Regression fitting\n", - "algorithm.\n", - "\n", - "As another example, consider the cost function we defined for linear regression" - ] - }, - { - "cell_type": "markdown", - "id": "a20c6de5", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "C(\\boldsymbol{y},\\boldsymbol{f}) = \\frac{1}{n} \\sum_{i=0}^{n-1}(y_i-f(x_i))^2.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "17800601", - "metadata": { - "editable": true - }, - "source": [ - "In this case the function $f(x)$ was replaced by the design matrix\n", - "$\\boldsymbol{X}$ and the unknown linear regression parameters $\\boldsymbol{\\beta}$,\n", - "that is $\\boldsymbol{f}=\\boldsymbol{X}\\boldsymbol{\\beta}$. In linear regression we can \n", - "simply invert a matrix and obtain the parameters $\\beta$ by" - ] - }, - { - "cell_type": "markdown", - "id": "7b59e224", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\boldsymbol{\\beta}=\\left(\\boldsymbol{X}^T\\boldsymbol{X}\\right)^{-1}\\boldsymbol{X}^T\\boldsymbol{y}.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "f5917a9a", - "metadata": { - "editable": true - }, - "source": [ - "In iterative fitting or additive modeling, we minimize the cost function with respect to the parameters $\\beta_m$ and $\\gamma_m$." - ] - }, - { - "cell_type": "markdown", - "id": "8d2101f2", - "metadata": { - "editable": true - }, - "source": [ - "## Iterative Fitting, Regression and Squared-error Cost Function\n", - "\n", - "The way we proceed is as follows (here we specialize to the squared-error cost function)\n", - "\n", - "1. Establish a cost function, here $C(\\boldsymbol{y},\\boldsymbol{f}) = \\frac{1}{n} \\sum_{i=0}^{n-1}(y_i-f_M(x_i))^2$ with $f_M(x) = \\sum_{i=1}^M \\beta_m b(x;\\gamma_m)$.\n", - "\n", - "2. Initialize with a guess $f_0(x)$. It could be one or even zero or some random numbers.\n", - "\n", - "3. For $m=1:M$\n", - "\n", - "a. minimize $\\sum_{i=0}^{n-1}(y_i-f_{m-1}(x_i)-\\beta b(x;\\gamma))^2$ wrt $\\gamma$ and $\\beta$\n", - "\n", - "b. This gives the optimal values $\\beta_m$ and $\\gamma_m$\n", - "\n", - "c. Determine then the new values $f_m(x)=f_{m-1}(x) +\\beta_m b(x;\\gamma_m)$\n", - "\n", - "We could use any of the algorithms we have discussed till now. If we\n", - "use trees, $\\gamma$ parameterizes the split variables and split points\n", - "at the internal nodes, and the predictions at the terminal nodes." - ] - }, - { - "cell_type": "markdown", - "id": "65f77895", - "metadata": { - "editable": true - }, - "source": [ - "## Squared-Error Example and Iterative Fitting\n", - "\n", - "To better understand what happens, let us develop the steps for the iterative fitting using the above squared error function.\n", - "\n", - "For simplicity we assume also that our functions $b(x;\\gamma)=1+\\gamma x$. \n", - "\n", - "This means that for every iteration $m$, we need to optimize" - ] - }, - { - "cell_type": "markdown", - "id": "28b76851", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "(\\beta_m,\\gamma_m) = \\mathrm{argmin}_{\\beta,\\lambda}\\hspace{0.1cm} \\sum_{i=0}^{n-1}(y_i-f_{m-1}(x_i)-\\beta b(x;\\gamma))^2=\\sum_{i=0}^{n-1}(y_i-f_{m-1}(x_i)-\\beta(1+\\gamma x_i))^2.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "985ccfb2", - "metadata": { - "editable": true - }, - "source": [ - "We start our iteration by simply setting $f_0(x)=0$. \n", - "Taking the derivatives with respect to $\\beta$ and $\\gamma$ we obtain" - ] - }, - { - "cell_type": "markdown", - "id": "05d75812", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\frac{\\partial {\\cal C}}{\\partial \\beta} = -2\\sum_{i}(1+\\gamma x_i)(y_i-\\beta(1+\\gamma x_i))=0,\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "9cfc5c74", - "metadata": { - "editable": true - }, - "source": [ - "and" - ] - }, - { - "cell_type": "markdown", - "id": "3833eb7b", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\frac{\\partial {\\cal C}}{\\partial \\gamma} =-2\\sum_{i}\\beta x_i(y_i-\\beta(1+\\gamma x_i))=0.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "3fca374c", - "metadata": { - "editable": true - }, - "source": [ - "We can then rewrite these equations as (defining $\\boldsymbol{w}=\\boldsymbol{e}+\\gamma \\boldsymbol{x})$ with $\\boldsymbol{e}$ being the unit vector)" - ] - }, - { - "cell_type": "markdown", - "id": "aeb623d7", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\gamma \\boldsymbol{w}^T(\\boldsymbol{y}-\\beta\\gamma \\boldsymbol{w})=0,\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "f8e542a2", - "metadata": { - "editable": true - }, - "source": [ - "which gives us $\\beta = \\boldsymbol{w}^T\\boldsymbol{y}/(\\boldsymbol{w}^T\\boldsymbol{w})$. Similarly we have" - ] - }, - { - "cell_type": "markdown", - "id": "d92e3136", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\beta\\gamma \\boldsymbol{x}^T(\\boldsymbol{y}-\\beta(1+\\gamma \\boldsymbol{x}))=0,\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "bca4d27a", - "metadata": { - "editable": true - }, - "source": [ - "which leads to $\\gamma =(\\boldsymbol{x}^T\\boldsymbol{y}-\\beta\\boldsymbol{x}^T\\boldsymbol{e})/(\\beta\\boldsymbol{x}^T\\boldsymbol{x})$. Inserting\n", - "for $\\beta$ gives us an equation for $\\gamma$. This is a non-linear equation in the unknown $\\gamma$ and has to be solved numerically. \n", - "\n", - "The solution to these two equations gives us in turn $\\beta_1$ and $\\gamma_1$ leading to the new expression for $f_1(x)$ as\n", - "$f_1(x) = \\beta_1(1+\\gamma_1x)$. Doing this $M$ times results in our final estimate for the function $f$." - ] - }, - { - "cell_type": "markdown", - "id": "d2fa1316", - "metadata": { - "editable": true - }, - "source": [ - "## Iterative Fitting, Classification and AdaBoost\n", - "\n", - "Let us consider a binary classification problem with two outcomes $y_i \\in \\{-1,1\\}$ and $i=0,1,2,\\dots,n-1$ as our set of\n", - "observations. We define a classification function $G(x)$ which produces a prediction taking one or the other of the two values \n", - "$\\{-1,1\\}$.\n", - "\n", - "The error rate of the training sample is then" - ] - }, - { - "cell_type": "markdown", - "id": "5401b686", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\mathrm{\\overline{err}}=\\frac{1}{n} \\sum_{i=0}^{n-1} I(y_i\\ne G(x_i)).\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "082464c4", - "metadata": { - "editable": true - }, - "source": [ - "The iterative procedure starts with defining a weak classifier whose\n", - "error rate is barely better than random guessing. The iterative\n", - "procedure in boosting is to sequentially apply a weak\n", - "classification algorithm to repeatedly modified versions of the data\n", - "producing a sequence of weak classifiers $G_m(x)$.\n", - "\n", - "Here we will express our function $f(x)$ in terms of $G(x)$. That is" - ] - }, - { - "cell_type": "markdown", - "id": "4f2a4a17", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "f_M(x) = \\sum_{i=1}^M \\beta_m b(x;\\gamma_m),\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "4aad349a", - "metadata": { - "editable": true - }, - "source": [ - "will be a function of" - ] - }, - { - "cell_type": "markdown", - "id": "d2050bb1", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "G_M(x) = \\mathrm{sign} \\sum_{i=1}^M \\alpha_m G_m(x).\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "359b0eb3", - "metadata": { - "editable": true - }, - "source": [ - "## Adaptive Boosting, AdaBoost\n", - "\n", - "In our iterative procedure we define thus" - ] - }, - { - "cell_type": "markdown", - "id": "eab77ff9", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "f_m(x) = f_{m-1}(x)+\\beta_mG_m(x).\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "d7c87ec5", - "metadata": { - "editable": true - }, - "source": [ - "The simplest possible cost function which leads (also simple from a computational point of view) to the AdaBoost algorithm is the\n", - "exponential cost/loss function defined as" - ] - }, - { - "cell_type": "markdown", - "id": "3cf53a5f", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "C(\\boldsymbol{y},\\boldsymbol{f}) = \\sum_{i=0}^{n-1}\\exp{(-y_i(f_{m-1}(x_i)+\\beta G(x_i))}.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "67bbb3ac", - "metadata": { - "editable": true - }, - "source": [ - "We optimize $\\beta$ and $G$ for each value of $m=1:M$ as we did in the regression case.\n", - "This is normally done in two steps. Let us however first rewrite the cost function as" - ] - }, - { - "cell_type": "markdown", - "id": "d9a2448e", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "C(\\boldsymbol{y},\\boldsymbol{f}) = \\sum_{i=0}^{n-1}w_i^{m}\\exp{(-y_i\\beta G(x_i))},\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "392f16f2", - "metadata": { - "editable": true - }, - "source": [ - "where we have defined $w_i^m= \\exp{(-y_if_{m-1}(x_i))}$." - ] - }, - { - "cell_type": "markdown", - "id": "a645e83c", - "metadata": { - "editable": true - }, - "source": [ - "## Building up AdaBoost\n", - "\n", - "First, for any $\\beta > 0$, we optimize $G$ by setting" - ] - }, - { - "cell_type": "markdown", - "id": "89e1d11e", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "G_m(x) = \\mathrm{sign} \\sum_{i=0}^{n-1} w_i^m I(y_i \\ne G_(x_i)),\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "f884f217", - "metadata": { - "editable": true - }, - "source": [ - "which is the classifier that minimizes the weighted error rate in predicting $y$.\n", - "\n", - "We can do this by rewriting" - ] - }, - { - "cell_type": "markdown", - "id": "664acf19", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\exp{-(\\beta)}\\sum_{y_i=G(x_i)}w_i^m+\\exp{(\\beta)}\\sum_{y_i\\ne G(x_i)}w_i^m,\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "d83ebe5e", - "metadata": { - "editable": true - }, - "source": [ - "which can be rewritten as" - ] - }, - { - "cell_type": "markdown", - "id": "96134017", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "(\\exp{(\\beta)}-\\exp{-(\\beta)})\\sum_{i=0}^{n-1}w_i^mI(y_i\\ne G(x_i))+\\exp{(-\\beta)}\\sum_{i=0}^{n-1}w_i^m=0,\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "97fc79c8", - "metadata": { - "editable": true - }, - "source": [ - "which leads to" - ] - }, - { - "cell_type": "markdown", - "id": "0d1e4f3e", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\beta_m = \\frac{1}{2}\\log{\\frac{1-\\mathrm{\\overline{err}}}{\\mathrm{\\overline{err}}}},\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "7d571a24", - "metadata": { - "editable": true - }, - "source": [ - "where we have redefined the error as" - ] - }, - { - "cell_type": "markdown", - "id": "8f31a3a7", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\mathrm{\\overline{err}}_m=\\frac{1}{n}\\frac{\\sum_{i=0}^{n-1}w_i^mI(y_i\\ne G(x_i)}{\\sum_{i=0}^{n-1}w_i^m},\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "e0e3db77", - "metadata": { - "editable": true - }, - "source": [ - "which leads to an update of" - ] - }, - { - "cell_type": "markdown", - "id": "fc1ce185", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "f_m(x) = f_{m-1}(x) +\\beta_m G_m(x).\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "d7360d72", - "metadata": { - "editable": true - }, - "source": [ - "This leads to the new weights" - ] - }, - { - "cell_type": "markdown", - "id": "cf486320", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "w_i^{m+1} = w_i^m \\exp{(-y_i\\beta_m G_m(x_i))}\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "8ebdf8ce", - "metadata": { - "editable": true - }, - "source": [ - "## Adaptive boosting: AdaBoost, Basic Algorithm\n", - "\n", - "The algorithm here is rather straightforward. Assume that our weak\n", - "classifier is a decision tree and we consider a binary set of outputs\n", - "with $y_i \\in \\{-1,1\\}$ and $i=0,1,2,\\dots,n-1$ as our set of\n", - "observations. Our design matrix is given in terms of the\n", - "feature/predictor vectors\n", - "$\\boldsymbol{X}=[\\boldsymbol{x}_0\\boldsymbol{x}_1\\dots\\boldsymbol{x}_{p-1}]$. Finally, we define also a\n", - "classifier determined by our data via a function $G(x)$. This function tells us how well we are able to classify our outputs/targets $\\boldsymbol{y}$. \n", - "\n", - "We have already defined the misclassification error $\\mathrm{err}$ as" - ] - }, - { - "cell_type": "markdown", - "id": "853a1218", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\mathrm{err}=\\frac{1}{n}\\sum_{i=0}^{n-1}I(y_i\\ne G(x_i)),\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "d287b19d", - "metadata": { - "editable": true - }, - "source": [ - "where the function $I()$ is one if we misclassify and zero if we classify correctly." - ] - }, - { - "cell_type": "markdown", - "id": "637ef064", - "metadata": { - "editable": true - }, - "source": [ - "## Basic Steps of AdaBoost\n", - "\n", - "With the above definitions we are now ready to set up the algorithm for AdaBoost.\n", - "The basic idea is to set up weights which will be used to scale the correctly classified and the misclassified cases.\n", - "1. We start by initializing all weights to $w_i = 1/n$, with $i=0,1,2,\\dots n-1$. It is easy to see that we must have $\\sum_{i=0}^{n-1}w_i = 1$.\n", - "\n", - "2. We rewrite the misclassification error as" - ] - }, - { - "cell_type": "markdown", - "id": "f1698dc3", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\mathrm{\\overline{err}}_m=\\frac{\\sum_{i=0}^{n-1}w_i^m I(y_i\\ne G(x_i))}{\\sum_{i=0}^{n-1}w_i},\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "c6d08c01", - "metadata": { - "editable": true - }, - "source": [ - "1. Then we start looping over all attempts at classifying, namely we start an iterative process for $m=1:M$, where $M$ is the final number of classifications. Our given classifier could for example be a plain decision tree.\n", - "\n", - "a. Fit then a given classifier to the training set using the weights $w_i$.\n", - "\n", - "b. Compute then $\\mathrm{err}$ and figure out which events are classified properly and which are classified wrongly.\n", - "\n", - "c. Define a quantity $\\alpha_{m} = \\log{(1-\\mathrm{\\overline{err}}_m)/\\mathrm{\\overline{err}}_m}$\n", - "\n", - "d. Set the new weights to $w_i = w_i\\times \\exp{(\\alpha_m I(y_i\\ne G(x_i)}$.\n", - "\n", - "5. Compute the new classifier $G(x)= \\sum_{i=0}^{n-1}\\alpha_m I(y_i\\ne G(x_i)$.\n", - "\n", - "For the iterations with $m \\le 2$ the weights are modified\n", - "individually at each steps. The observations which were misclassified\n", - "at iteration $m-1$ have a weight which is larger than those which were\n", - "classified properly. As this proceeds, the observations which were\n", - "difficult to classifiy correctly are given a larger influence. Each\n", - "new classification step $m$ is then forced to concentrate on those\n", - "observations that are missed in the previous iterations." - ] - }, - { - "cell_type": "markdown", - "id": "c58db919", - "metadata": { - "editable": true - }, - "source": [ - "## AdaBoost Examples\n", - "\n", - "Using **Scikit-Learn** it is easy to apply the adaptive boosting algorithm, as done here." - ] - }, - { - "cell_type": "code", - "execution_count": 24, - "id": "104e1c7c", - "metadata": { - "collapsed": false, - "editable": true - }, - "outputs": [], - "source": [ - "from sklearn.ensemble import AdaBoostClassifier\n", - "\n", - "ada_clf = AdaBoostClassifier(\n", - " DecisionTreeClassifier(max_depth=1), n_estimators=200,\n", - " algorithm=\"SAMME.R\", learning_rate=0.5, random_state=42)\n", - "ada_clf.fit(X_train, y_train)\n", - "\n", - "from sklearn.ensemble import AdaBoostClassifier\n", - "\n", - "ada_clf = AdaBoostClassifier(\n", - " DecisionTreeClassifier(max_depth=1), n_estimators=200,\n", - " algorithm=\"SAMME.R\", learning_rate=0.5, random_state=42)\n", - "ada_clf.fit(X_train_scaled, y_train)\n", - "y_pred = ada_clf.predict(X_test_scaled)\n", - "skplt.metrics.plot_confusion_matrix(y_test, y_pred, normalize=True)\n", - "plt.show()\n", - "y_probas = ada_clf.predict_proba(X_test_scaled)\n", - "skplt.metrics.plot_roc(y_test, y_probas)\n", - "plt.show()\n", - "skplt.metrics.plot_cumulative_gain(y_test, y_probas)\n", - "plt.show()" - ] - } - ], - "metadata": {}, - "nbformat": 4, - "nbformat_minor": 5 -} diff --git a/doc/LectureNotes/week47.ipynb b/doc/LectureNotes/week47.ipynb deleted file mode 100644 index 06576e777..000000000 --- a/doc/LectureNotes/week47.ipynb +++ /dev/null @@ -1,3018 +0,0 @@ -{ - "cells": [ - { - "cell_type": "markdown", - "id": "6314bf67", - "metadata": { - "editable": true - }, - "source": [ - "\n", - "" - ] - }, - { - "cell_type": "markdown", - "id": "c46d28d1", - "metadata": { - "editable": true - }, - "source": [ - "# Week 47: From Decision Trees to Ensemble Methods, Random Forests and Boosting Methods and Summary of Course\n", - "**Morten Hjorth-Jensen**, Department of Physics, University of Oslo and Department of Physics and Astronomy and Facility for Rare Ion Beams, Michigan State University\n", - "\n", - "Date: **November 20-24, 2023**" - ] - }, - { - "cell_type": "markdown", - "id": "091c41a2", - "metadata": { - "editable": true - }, - "source": [ - "## Plan for week 47\n", - "\n", - "**Active learning sessions on Tuesday and Wednesday.**\n", - "\n", - " * Work and Discussion of project 3\n", - "\n", - " * Last weekly exercise, course feedback, to be completed by Sunday November 26\n", - "\n", - " \n", - "\n", - "**Material for the lecture on Thursday November 23, 2023.**\n", - "\n", - " * Thursday: Basics of decision trees, classification and regression algorithms and ensemble models \n", - "\n", - " * Readings and Videos:\n", - "\n", - " * These lecture notes\n", - "\n", - " * [Video of Lecture](https://youtu.be/SpWXsvn5I9E)\n", - "\n", - " * [Whiteboard notes](https://github.com/CompPhysics/MachineLearning/blob/master/doc/HandWrittenNotes/2023/NotesNov23.pdf)\n", - "\n", - " * [Video on Decision trees](https://www.youtube.com/watch?v=RmajweUFKvM&ab_channel=Simplilearn)\n", - "\n", - " * [Video on boosting methods by Hastie](https://www.youtube.com/watch?v=wPqtzj5VZus&ab_channel=H2O.ai)\n", - "\n", - " * [Video on AdaBoost](https://www.youtube.com/watch?v=LsK-xG1cLYA)\n", - "\n", - " * [Video on Gradient boost, part 1, parts 2-4 follow thereafter](https://www.youtube.com/watch?v=3CC4N4z3GJc)\n", - "\n", - " * Decision Trees: Geron's chapter 6 covers decision trees while ensemble models, voting and bagging are discussed in chapter 7. See also lecture from [STK-IN4300, lecture 7](https://www.uio.no/studier/emner/matnat/math/STK-IN4300/h20/slides/lecture_7.pdf). Chapter 9.2 of Hastie et al contains also a good discussion." - ] - }, - { - "cell_type": "markdown", - "id": "3f081cea", - "metadata": { - "editable": true - }, - "source": [ - "## Bagging\n", - "\n", - "The **plain** decision trees suffer from high\n", - "variance. This means that if we split the training data into two parts\n", - "at random, and fit a decision tree to both halves, the results that we\n", - "get could be quite different. In contrast, a procedure with low\n", - "variance will yield similar results if applied repeatedly to distinct\n", - "data sets; linear regression tends to have low variance, if the ratio\n", - "of $n$ to $p$ is moderately large. \n", - "\n", - "**Bootstrap aggregation**, or just **bagging**, is a\n", - "general-purpose procedure for reducing the variance of a statistical\n", - "learning method." - ] - }, - { - "cell_type": "markdown", - "id": "3789d0ad", - "metadata": { - "editable": true - }, - "source": [ - "## More bagging\n", - "\n", - "Bagging typically results in improved accuracy\n", - "over prediction using a single tree. Unfortunately, however, it can be\n", - "difficult to interpret the resulting model. Recall that one of the\n", - "advantages of decision trees is the attractive and easily interpreted\n", - "diagram that results.\n", - "\n", - "However, when we bag a large number of trees, it is no longer\n", - "possible to represent the resulting statistical learning procedure\n", - "using a single tree, and it is no longer clear which variables are\n", - "most important to the procedure. Thus, bagging improves prediction\n", - "accuracy at the expense of interpretability. Although the collection\n", - "of bagged trees is much more difficult to interpret than a single\n", - "tree, one can obtain an overall summary of the importance of each\n", - "predictor using the MSE (for bagging regression trees) or the Gini\n", - "index (for bagging classification trees). In the case of bagging\n", - "regression trees, we can record the total amount that the MSE is\n", - "decreased due to splits over a given predictor, averaged over all $B$ possible\n", - "trees. A large value indicates an important predictor. Similarly, in\n", - "the context of bagging classification trees, we can add up the total\n", - "amount that the Gini index is decreased by splits over a given\n", - "predictor, averaged over all $B$ trees." - ] - }, - { - "cell_type": "markdown", - "id": "b6bfb9a8", - "metadata": { - "editable": true - }, - "source": [ - "## Making your own Bootstrap: Changing the Level of the Decision Tree\n", - "\n", - "Let us bring up our good old boostrap example from the linear regression lectures. We change the linerar regression algorithm with\n", - "a decision tree wth different depths and perform a bootstrap aggregate (in this case we perform as many bootstraps as data points $n$)." - ] - }, - { - "cell_type": "code", - "execution_count": 1, - "id": "bd257c56", - "metadata": { - "collapsed": false, - "editable": true - }, - "outputs": [], - "source": [ - "%matplotlib inline\n", - "\n", - "# Common imports\n", - "import matplotlib.pyplot as plt\n", - "import numpy as np\n", - "from sklearn.model_selection import train_test_split\n", - "from sklearn.pipeline import make_pipeline\n", - "from sklearn.utils import resample\n", - "from sklearn.tree import DecisionTreeRegressor\n", - "import pandas as pd\n", - "from sklearn.tree import DecisionTreeClassifier\n", - "from sklearn.model_selection import train_test_split\n", - "from sklearn.preprocessing import StandardScaler, OneHotEncoder\n", - "from sklearn.compose import ColumnTransformer\n", - "from IPython.display import Image \n", - "import os\n", - "\n", - "# Where to save the figures and data files\n", - "PROJECT_ROOT_DIR = \"Results\"\n", - "FIGURE_ID = \"Results/FigureFiles\"\n", - "DATA_ID = \"DataFiles/\"\n", - "\n", - "if not os.path.exists(PROJECT_ROOT_DIR):\n", - " os.mkdir(PROJECT_ROOT_DIR)\n", - "\n", - "if not os.path.exists(FIGURE_ID):\n", - " os.makedirs(FIGURE_ID)\n", - "\n", - "if not os.path.exists(DATA_ID):\n", - " os.makedirs(DATA_ID)\n", - "\n", - "def image_path(fig_id):\n", - " return os.path.join(FIGURE_ID, fig_id)\n", - "\n", - "def data_path(dat_id):\n", - " return os.path.join(DATA_ID, dat_id)\n", - "\n", - "def save_fig(fig_id):\n", - " plt.savefig(image_path(fig_id) + \".png\", format='png')\n", - "\n", - "\n", - "n = 100\n", - "n_boostraps = 100\n", - "maxdepth = 8\n", - "\n", - "# Make data set.\n", - "x = np.linspace(-3, 3, n).reshape(-1, 1)\n", - "y = np.exp(-x**2) + 1.5 * np.exp(-(x-2)**2)+ np.random.normal(0, 0.1, x.shape)\n", - "error = np.zeros(maxdepth)\n", - "bias = np.zeros(maxdepth)\n", - "variance = np.zeros(maxdepth)\n", - "polydegree = np.zeros(maxdepth)\n", - "X_train, X_test, y_train, y_test = train_test_split(x, y, test_size=0.2)\n", - "\n", - "from sklearn.preprocessing import StandardScaler\n", - "scaler = StandardScaler()\n", - "scaler.fit(X_train)\n", - "X_train_scaled = scaler.transform(X_train)\n", - "X_test_scaled = scaler.transform(X_test)\n", - "\n", - "# we produce a simple tree first as benchmark\n", - "simpletree = DecisionTreeRegressor(max_depth=3) \n", - "simpletree.fit(X_train_scaled, y_train)\n", - "simpleprediction = simpletree.predict(X_test_scaled)\n", - "for degree in range(1,maxdepth):\n", - " model = DecisionTreeRegressor(max_depth=degree) \n", - " y_pred = np.empty((y_test.shape[0], n_boostraps))\n", - " for i in range(n_boostraps):\n", - " x_, y_ = resample(X_train_scaled, y_train)\n", - " model.fit(x_, y_)\n", - " y_pred[:, i] = model.predict(X_test_scaled)#.ravel()\n", - "\n", - " polydegree[degree] = degree\n", - " error[degree] = np.mean( np.mean((y_test - y_pred)**2, axis=1, keepdims=True) )\n", - " bias[degree] = np.mean( (y_test - np.mean(y_pred, axis=1, keepdims=True))**2 )\n", - " variance[degree] = np.mean( np.var(y_pred, axis=1, keepdims=True) )\n", - " print('Polynomial degree:', degree)\n", - " print('Error:', error[degree])\n", - " print('Bias^2:', bias[degree])\n", - " print('Var:', variance[degree])\n", - " print('{} >= {} + {} = {}'.format(error[degree], bias[degree], variance[degree], bias[degree]+variance[degree]))\n", - " \n", - "mse_simpletree= np.mean( np.mean((y_test - simpleprediction)**2))\n", - "print(\"Simple tree:\",mse_simpletree)\n", - "plt.xlim(1,maxdepth)\n", - "plt.plot(polydegree, error, label='MSE')\n", - "plt.plot(polydegree, bias, label='bias')\n", - "plt.plot(polydegree, variance, label='Variance')\n", - "plt.legend()\n", - "save_fig(\"baggingboot\")\n", - "plt.show()" - ] - }, - { - "cell_type": "markdown", - "id": "ec697394", - "metadata": { - "editable": true - }, - "source": [ - "## Random forests\n", - "\n", - "Random forests provide an improvement over bagged trees by way of a\n", - "small tweak that decorrelates the trees. \n", - "\n", - "As in bagging, we build a\n", - "number of decision trees on bootstrapped training samples. But when\n", - "building these decision trees, each time a split in a tree is\n", - "considered, a random sample of $m$ predictors is chosen as split\n", - "candidates from the full set of $p$ predictors. The split is allowed to\n", - "use only one of those $m$ predictors. \n", - "\n", - "A fresh sample of $m$ predictors is\n", - "taken at each split, and typically we choose" - ] - }, - { - "cell_type": "markdown", - "id": "2f8e4054", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "m\\approx \\sqrt{p}.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "5476fc65", - "metadata": { - "editable": true - }, - "source": [ - "In building a random forest, at\n", - "each split in the tree, the algorithm is not even allowed to consider\n", - "a majority of the available predictors. \n", - "\n", - "The reason for this is rather clever. Suppose that there is one very\n", - "strong predictor in the data set, along with a number of other\n", - "moderately strong predictors. Then in the collection of bagged\n", - "variable importance random forest trees, most or all of the trees will\n", - "use this strong predictor in the top split. Consequently, all of the\n", - "bagged trees will look quite similar to each other. Hence the\n", - "predictions from the bagged trees will be highly correlated.\n", - "Unfortunately, averaging many highly correlated quantities does not\n", - "lead to as large of a reduction in variance as averaging many\n", - "uncorrelated quantities. In particular, this means that bagging will\n", - "not lead to a substantial reduction in variance over a single tree in\n", - "this setting." - ] - }, - { - "cell_type": "markdown", - "id": "024d17cc", - "metadata": { - "editable": true - }, - "source": [ - "## Random Forest Algorithm\n", - "The algorithm described here can be applied to both classification and regression problems.\n", - "\n", - "We will grow of forest of say $B$ trees.\n", - "1. For $b=1:B$\n", - "\n", - " * Draw a bootstrap sample from the training data organized in our $\\boldsymbol{X}$ matrix.\n", - "\n", - " * We grow then a random forest tree $T_b$ based on the bootstrapped data by repeating the steps outlined till we reach the maximum node size is reached\n", - "\n", - "1. we select $m \\le p$ variables at random from the $p$ predictors/features\n", - "\n", - "2. pick the best split point among the $m$ features using for example the CART algorithm and create a new node\n", - "\n", - "3. split the node into daughter nodes\n", - "\n", - "4. Output then the ensemble of trees $\\{T_b\\}_1^{B}$ and make predictions for either a regression type of problem or a classification type of problem." - ] - }, - { - "cell_type": "markdown", - "id": "adbab589", - "metadata": { - "editable": true - }, - "source": [ - "## Random Forests Compared with other Methods on the Cancer Data" - ] - }, - { - "cell_type": "code", - "execution_count": 2, - "id": "44d47f87", - "metadata": { - "collapsed": false, - "editable": true - }, - "outputs": [], - "source": [ - "import matplotlib.pyplot as plt\n", - "import numpy as np\n", - "from sklearn.model_selection import train_test_split \n", - "from sklearn.datasets import load_breast_cancer\n", - "from sklearn.svm import SVC\n", - "from sklearn.linear_model import LogisticRegression\n", - "from sklearn.tree import DecisionTreeClassifier\n", - "from sklearn.ensemble import BaggingClassifier\n", - "\n", - "# Load the data\n", - "cancer = load_breast_cancer()\n", - "\n", - "X_train, X_test, y_train, y_test = train_test_split(cancer.data,cancer.target,random_state=0)\n", - "print(X_train.shape)\n", - "print(X_test.shape)\n", - "#define methods\n", - "# Logistic Regression\n", - "logreg = LogisticRegression(solver='lbfgs')\n", - "# Support vector machine\n", - "svm = SVC(gamma='auto', C=100)\n", - "# Decision Trees\n", - "deep_tree_clf = DecisionTreeClassifier(max_depth=None)\n", - "#Scale the data\n", - "from sklearn.preprocessing import StandardScaler\n", - "scaler = StandardScaler()\n", - "scaler.fit(X_train)\n", - "X_train_scaled = scaler.transform(X_train)\n", - "X_test_scaled = scaler.transform(X_test)\n", - "# Logistic Regression\n", - "logreg.fit(X_train_scaled, y_train)\n", - "print(\"Test set accuracy Logistic Regression with scaled data: {:.2f}\".format(logreg.score(X_test_scaled,y_test)))\n", - "# Support Vector Machine\n", - "svm.fit(X_train_scaled, y_train)\n", - "print(\"Test set accuracy SVM with scaled data: {:.2f}\".format(logreg.score(X_test_scaled,y_test)))\n", - "# Decision Trees\n", - "deep_tree_clf.fit(X_train_scaled, y_train)\n", - "print(\"Test set accuracy with Decision Trees and scaled data: {:.2f}\".format(deep_tree_clf.score(X_test_scaled,y_test)))\n", - "\n", - "\n", - "from sklearn.ensemble import RandomForestClassifier\n", - "from sklearn.preprocessing import LabelEncoder\n", - "from sklearn.model_selection import cross_validate\n", - "# Data set not specificied\n", - "#Instantiate the model with 500 trees and entropy as splitting criteria\n", - "Random_Forest_model = RandomForestClassifier(n_estimators=500,criterion=\"entropy\")\n", - "Random_Forest_model.fit(X_train_scaled, y_train)\n", - "#Cross validation\n", - "accuracy = cross_validate(Random_Forest_model,X_test_scaled,y_test,cv=10)['test_score']\n", - "print(accuracy)\n", - "print(\"Test set accuracy with Random Forests and scaled data: {:.2f}\".format(Random_Forest_model.score(X_test_scaled,y_test)))\n", - "\n", - "\n", - "import scikitplot as skplt\n", - "y_pred = Random_Forest_model.predict(X_test_scaled)\n", - "skplt.metrics.plot_confusion_matrix(y_test, y_pred, normalize=True)\n", - "plt.show()\n", - "y_probas = Random_Forest_model.predict_proba(X_test_scaled)\n", - "skplt.metrics.plot_roc(y_test, y_probas)\n", - "plt.show()\n", - "skplt.metrics.plot_cumulative_gain(y_test, y_probas)\n", - "plt.show()" - ] - }, - { - "cell_type": "markdown", - "id": "2670f5de", - "metadata": { - "editable": true - }, - "source": [ - "Recall that the cumulative gains curve shows the percentage of the\n", - "overall number of cases in a given category *gained* by targeting a\n", - "percentage of the total number of cases.\n", - "\n", - "Similarly, the receiver operating characteristic curve, or ROC curve,\n", - "displays the diagnostic ability of a binary classifier system as its\n", - "discrimination threshold is varied. It plots the true positive rate against the false positive rate." - ] - }, - { - "cell_type": "markdown", - "id": "622c79ae", - "metadata": { - "editable": true - }, - "source": [ - "## Compare Bagging on Trees with Random Forests" - ] - }, - { - "cell_type": "code", - "execution_count": 3, - "id": "eceba36c", - "metadata": { - "collapsed": false, - "editable": true - }, - "outputs": [], - "source": [ - "bag_clf = BaggingClassifier(\n", - " DecisionTreeClassifier(splitter=\"random\", max_leaf_nodes=16, random_state=42),\n", - " n_estimators=500, max_samples=1.0, bootstrap=True, n_jobs=-1, random_state=42)" - ] - }, - { - "cell_type": "code", - "execution_count": 4, - "id": "40d42e1a", - "metadata": { - "collapsed": false, - "editable": true - }, - "outputs": [], - "source": [ - "bag_clf.fit(X_train, y_train)\n", - "y_pred = bag_clf.predict(X_test)\n", - "from sklearn.ensemble import RandomForestClassifier\n", - "rnd_clf = RandomForestClassifier(n_estimators=500, max_leaf_nodes=16, n_jobs=-1, random_state=42)\n", - "rnd_clf.fit(X_train, y_train)\n", - "y_pred_rf = rnd_clf.predict(X_test)\n", - "np.sum(y_pred == y_pred_rf) / len(y_pred)" - ] - }, - { - "cell_type": "markdown", - "id": "bee77377", - "metadata": { - "editable": true - }, - "source": [ - "## Boosting, a Bird's Eye View\n", - "\n", - "The basic idea is to combine weak classifiers in order to create a good\n", - "classifier. With a weak classifier we often intend a classifier which\n", - "produces results which are only slightly better than we would get by\n", - "random guesses.\n", - "\n", - "This is done by applying in an iterative way a weak (or a standard\n", - "classifier like decision trees) to modify the data. In each iteration\n", - "we emphasize those observations which are misclassified by weighting\n", - "them with a factor." - ] - }, - { - "cell_type": "markdown", - "id": "4ea2d5e4", - "metadata": { - "editable": true - }, - "source": [ - "## What is boosting? Additive Modelling/Iterative Fitting\n", - "\n", - "Boosting is a way of fitting an additive expansion in a set of\n", - "elementary basis functions like for example some simple polynomials.\n", - "Assume for example that we have a function" - ] - }, - { - "cell_type": "markdown", - "id": "c69bf1b6", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "f_M(x) = \\sum_{i=1}^M \\beta_m b(x;\\gamma_m),\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "d53b6cb2", - "metadata": { - "editable": true - }, - "source": [ - "where $\\beta_m$ are the expansion parameters to be determined in a\n", - "minimization process and $b(x;\\gamma_m)$ are some simple functions of\n", - "the multivariable parameter $x$ which is characterized by the\n", - "parameters $\\gamma_m$.\n", - "\n", - "As an example, consider the Sigmoid function we used in logistic\n", - "regression. In that case, we can translate the function\n", - "$b(x;\\gamma_m)$ into the Sigmoid function" - ] - }, - { - "cell_type": "markdown", - "id": "57ee288e", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\sigma(t) = \\frac{1}{1+\\exp{(-t)}},\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "d03b9aa0", - "metadata": { - "editable": true - }, - "source": [ - "where $t=\\gamma_0+\\gamma_1 x$ and the parameters $\\gamma_0$ and\n", - "$\\gamma_1$ were determined by the Logistic Regression fitting\n", - "algorithm.\n", - "\n", - "As another example, consider the cost function we defined for linear regression" - ] - }, - { - "cell_type": "markdown", - "id": "3caace0f", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "C(\\boldsymbol{y},\\boldsymbol{f}) = \\frac{1}{n} \\sum_{i=0}^{n-1}(y_i-f(x_i))^2.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "99c4d861", - "metadata": { - "editable": true - }, - "source": [ - "In this case the function $f(x)$ was replaced by the design matrix\n", - "$\\boldsymbol{X}$ and the unknown linear regression parameters $\\boldsymbol{\\beta}$,\n", - "that is $\\boldsymbol{f}=\\boldsymbol{X}\\boldsymbol{\\beta}$. In linear regression we can \n", - "simply invert a matrix and obtain the parameters $\\beta$ by" - ] - }, - { - "cell_type": "markdown", - "id": "15e7309c", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\boldsymbol{\\beta}=\\left(\\boldsymbol{X}^T\\boldsymbol{X}\\right)^{-1}\\boldsymbol{X}^T\\boldsymbol{y}.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "78f883b0", - "metadata": { - "editable": true - }, - "source": [ - "In iterative fitting or additive modeling, we minimize the cost function with respect to the parameters $\\beta_m$ and $\\gamma_m$." - ] - }, - { - "cell_type": "markdown", - "id": "95d67f7e", - "metadata": { - "editable": true - }, - "source": [ - "## Iterative Fitting, Regression and Squared-error Cost Function\n", - "\n", - "The way we proceed is as follows (here we specialize to the squared-error cost function)\n", - "\n", - "1. Establish a cost function, here ${\\cal C}(\\boldsymbol{y},\\boldsymbol{f}) = \\frac{1}{n} \\sum_{i=0}^{n-1}(y_i-f_M(x_i))^2$ with $f_M(x) = \\sum_{i=1}^M \\beta_m b(x;\\gamma_m)$.\n", - "\n", - "2. Initialize with a guess $f_0(x)$. It could be one or even zero or some random numbers.\n", - "\n", - "3. For $m=1:M$\n", - "\n", - "a. minimize $\\sum_{i=0}^{n-1}(y_i-f_{m-1}(x_i)-\\beta b(x;\\gamma))^2$ wrt $\\gamma$ and $\\beta$\n", - "\n", - "b. This gives the optimal values $\\beta_m$ and $\\gamma_m$\n", - "\n", - "c. Determine then the new values $f_m(x)=f_{m-1}(x) +\\beta_m b(x;\\gamma_m)$\n", - "\n", - "We could use any of the algorithms we have discussed till now. If we\n", - "use trees, $\\gamma$ parameterizes the split variables and split points\n", - "at the internal nodes, and the predictions at the terminal nodes." - ] - }, - { - "cell_type": "markdown", - "id": "571085d4", - "metadata": { - "editable": true - }, - "source": [ - "## Squared-Error Example and Iterative Fitting\n", - "\n", - "To better understand what happens, let us develop the steps for the iterative fitting using the above squared error function.\n", - "\n", - "For simplicity we assume also that our functions $b(x;\\gamma)=1+\\gamma x$. \n", - "\n", - "This means that for every iteration $m$, we need to optimize" - ] - }, - { - "cell_type": "markdown", - "id": "6c23e842", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "(\\beta_m,\\gamma_m) = \\mathrm{argmin}_{\\beta,\\lambda}\\hspace{0.1cm} \\sum_{i=0}^{n-1}(y_i-f_{m-1}(x_i)-\\beta b(x;\\gamma))^2=\\sum_{i=0}^{n-1}(y_i-f_{m-1}(x_i)-\\beta(1+\\gamma x_i))^2.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "6a3315ef", - "metadata": { - "editable": true - }, - "source": [ - "We start our iteration by simply setting $f_0(x)=0$. \n", - "Taking the derivatives with respect to $\\beta$ and $\\gamma$ we obtain" - ] - }, - { - "cell_type": "markdown", - "id": "c377e717", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\frac{\\partial {\\cal C}}{\\partial \\beta} = -2\\sum_{i}(1+\\gamma x_i)(y_i-\\beta(1+\\gamma x_i))=0,\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "0effec3c", - "metadata": { - "editable": true - }, - "source": [ - "and" - ] - }, - { - "cell_type": "markdown", - "id": "5104bdd4", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\frac{\\partial {\\cal C}}{\\partial \\gamma} =-2\\sum_{i}\\beta x_i(y_i-\\beta(1+\\gamma x_i))=0.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "07255d2b", - "metadata": { - "editable": true - }, - "source": [ - "We can then rewrite these equations as (defining $\\boldsymbol{w}=\\boldsymbol{e}+\\gamma \\boldsymbol{x})$ with $\\boldsymbol{e}$ being the unit vector)" - ] - }, - { - "cell_type": "markdown", - "id": "e597dcd5", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\gamma \\boldsymbol{w}^T(\\boldsymbol{y}-\\beta\\gamma \\boldsymbol{w})=0,\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "5044ba81", - "metadata": { - "editable": true - }, - "source": [ - "which gives us $\\beta = \\boldsymbol{w}^T\\boldsymbol{y}/(\\boldsymbol{w}^T\\boldsymbol{w})$. Similarly we have" - ] - }, - { - "cell_type": "markdown", - "id": "6ec9b996", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\beta\\gamma \\boldsymbol{x}^T(\\boldsymbol{y}-\\beta(1+\\gamma \\boldsymbol{x}))=0,\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "f6835c6d", - "metadata": { - "editable": true - }, - "source": [ - "which leads to $\\gamma =(\\boldsymbol{x}^T\\boldsymbol{y}-\\beta\\boldsymbol{x}^T\\boldsymbol{e})/(\\beta\\boldsymbol{x}^T\\boldsymbol{x})$. Inserting\n", - "for $\\beta$ gives us an equation for $\\gamma$. This is a non-linear equation in the unknown $\\gamma$ and has to be solved numerically. \n", - "\n", - "The solution to these two equations gives us in turn $\\beta_1$ and $\\gamma_1$ leading to the new expression for $f_1(x)$ as\n", - "$f_1(x) = \\beta_1(1+\\gamma_1x)$. Doing this $M$ times results in our final estimate for the function $f$." - ] - }, - { - "cell_type": "markdown", - "id": "ec4ec69c", - "metadata": { - "editable": true - }, - "source": [ - "## Iterative Fitting, Classification and AdaBoost\n", - "\n", - "Let us consider a binary classification problem with two outcomes $y_i \\in \\{-1,1\\}$ and $i=0,1,2,\\dots,n-1$ as our set of\n", - "observations. We define a classification function $G(x)$ which produces a prediction taking one or the other of the two values \n", - "$\\{-1,1\\}$.\n", - "\n", - "The error rate of the training sample is then" - ] - }, - { - "cell_type": "markdown", - "id": "ee339678", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\mathrm{\\overline{err}}=\\frac{1}{n} \\sum_{i=0}^{n-1} I(y_i\\ne G(x_i)).\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "e8eaad5d", - "metadata": { - "editable": true - }, - "source": [ - "The iterative procedure starts with defining a weak classifier whose\n", - "error rate is barely better than random guessing. The iterative\n", - "procedure in boosting is to sequentially apply a weak\n", - "classification algorithm to repeatedly modified versions of the data\n", - "producing a sequence of weak classifiers $G_m(x)$.\n", - "\n", - "Here we will express our function $f(x)$ in terms of $G(x)$. That is" - ] - }, - { - "cell_type": "markdown", - "id": "b401d599", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "f_M(x) = \\sum_{i=1}^M \\beta_m b(x;\\gamma_m),\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "a9e7822e", - "metadata": { - "editable": true - }, - "source": [ - "will be a function of" - ] - }, - { - "cell_type": "markdown", - "id": "715194ce", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "G_M(x) = \\mathrm{sign} \\sum_{i=1}^M \\alpha_m G_m(x).\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "195fc1da", - "metadata": { - "editable": true - }, - "source": [ - "## Adaptive Boosting, AdaBoost\n", - "\n", - "In our iterative procedure we define thus" - ] - }, - { - "cell_type": "markdown", - "id": "9436883a", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "f_m(x) = f_{m-1}(x)+\\beta_mG_m(x).\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "4ebf9f1e", - "metadata": { - "editable": true - }, - "source": [ - "The simplest possible cost function which leads (also simple from a computational point of view) to the AdaBoost algorithm is the\n", - "exponential cost/loss function defined as" - ] - }, - { - "cell_type": "markdown", - "id": "603422c9", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "C(\\boldsymbol{y},\\boldsymbol{f}) = \\sum_{i=0}^{n-1}\\exp{(-y_i(f_{m-1}(x_i)+\\beta G(x_i))}.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "da3e2e12", - "metadata": { - "editable": true - }, - "source": [ - "We optimize $\\beta$ and $G$ for each value of $m=1:M$ as we did in the regression case.\n", - "This is normally done in two steps. Let us however first rewrite the cost function as" - ] - }, - { - "cell_type": "markdown", - "id": "851833f0", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "C(\\boldsymbol{y},\\boldsymbol{f}) = \\sum_{i=0}^{n-1}w_i^{m}\\exp{(-y_i\\beta G(x_i))},\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "4bbf5443", - "metadata": { - "editable": true - }, - "source": [ - "where we have defined $w_i^m= \\exp{(-y_if_{m-1}(x_i))}$." - ] - }, - { - "cell_type": "markdown", - "id": "b63b18c5", - "metadata": { - "editable": true - }, - "source": [ - "## Building up AdaBoost\n", - "\n", - "First, for any $\\beta > 0$, we optimize $G$ by setting" - ] - }, - { - "cell_type": "markdown", - "id": "f3f75de8", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "G_m(x) = \\mathrm{sign} \\sum_{i=0}^{n-1} w_i^m I(y_i \\ne G_(x_i)),\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "998b02e8", - "metadata": { - "editable": true - }, - "source": [ - "which is the classifier that minimizes the weighted error rate in predicting $y$.\n", - "\n", - "We can do this by rewriting" - ] - }, - { - "cell_type": "markdown", - "id": "98b1751b", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\exp{-(\\beta)}\\sum_{y_i=G(x_i)}w_i^m+\\exp{(\\beta)}\\sum_{y_i\\ne G(x_i)}w_i^m,\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "4b030d99", - "metadata": { - "editable": true - }, - "source": [ - "which can be rewritten as" - ] - }, - { - "cell_type": "markdown", - "id": "e286c8e8", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "(\\exp{(\\beta)}-\\exp{-(\\beta)})\\sum_{i=0}^{n-1}w_i^mI(y_i\\ne G(x_i))+\\exp{(-\\beta)}\\sum_{i=0}^{n-1}w_i^m=0,\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "7328b345", - "metadata": { - "editable": true - }, - "source": [ - "which leads to" - ] - }, - { - "cell_type": "markdown", - "id": "b10d1b97", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\beta_m = \\frac{1}{2}\\log{\\frac{1-\\mathrm{\\overline{err}}}{\\mathrm{\\overline{err}}}},\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "6601235f", - "metadata": { - "editable": true - }, - "source": [ - "where we have redefined the error as" - ] - }, - { - "cell_type": "markdown", - "id": "2d7d9eb9", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\mathrm{\\overline{err}}_m=\\frac{1}{n}\\frac{\\sum_{i=0}^{n-1}w_i^mI(y_i\\ne G(x_i)}{\\sum_{i=0}^{n-1}w_i^m},\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "41a404a6", - "metadata": { - "editable": true - }, - "source": [ - "which leads to an update of" - ] - }, - { - "cell_type": "markdown", - "id": "65f30690", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "f_m(x) = f_{m-1}(x) +\\beta_m G_m(x).\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "aea33aa2", - "metadata": { - "editable": true - }, - "source": [ - "This leads to the new weights" - ] - }, - { - "cell_type": "markdown", - "id": "225e3f3e", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "w_i^{m+1} = w_i^m \\exp{(-y_i\\beta_m G_m(x_i))}\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "eb9cd9ea", - "metadata": { - "editable": true - }, - "source": [ - "## Adaptive boosting: AdaBoost, Basic Algorithm\n", - "\n", - "The algorithm here is rather straightforward. Assume that our weak\n", - "classifier is a decision tree and we consider a binary set of outputs\n", - "with $y_i \\in \\{-1,1\\}$ and $i=0,1,2,\\dots,n-1$ as our set of\n", - "observations. Our design matrix is given in terms of the\n", - "feature/predictor vectors\n", - "$\\boldsymbol{X}=[\\boldsymbol{x}_0\\boldsymbol{x}_1\\dots\\boldsymbol{x}_{p-1}]$. Finally, we define also a\n", - "classifier determined by our data via a function $G(x)$. This function tells us how well we are able to classify our outputs/targets $\\boldsymbol{y}$. \n", - "\n", - "We have already defined the misclassification error $\\mathrm{err}$ as" - ] - }, - { - "cell_type": "markdown", - "id": "09491585", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\mathrm{err}=\\frac{1}{n}\\sum_{i=0}^{n-1}I(y_i\\ne G(x_i)),\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "60b25717", - "metadata": { - "editable": true - }, - "source": [ - "where the function $I()$ is one if we misclassify and zero if we classify correctly." - ] - }, - { - "cell_type": "markdown", - "id": "af1b7fce", - "metadata": { - "editable": true - }, - "source": [ - "## Basic Steps of AdaBoost\n", - "\n", - "With the above definitions we are now ready to set up the algorithm for AdaBoost.\n", - "The basic idea is to set up weights which will be used to scale the correctly classified and the misclassified cases.\n", - "1. We start by initializing all weights to $w_i = 1/n$, with $i=0,1,2,\\dots n-1$. It is easy to see that we must have $\\sum_{i=0}^{n-1}w_i = 1$.\n", - "\n", - "2. We rewrite the misclassification error as" - ] - }, - { - "cell_type": "markdown", - "id": "e207bb04", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\mathrm{\\overline{err}}_m=\\frac{\\sum_{i=0}^{n-1}w_i^m I(y_i\\ne G(x_i))}{\\sum_{i=0}^{n-1}w_i},\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "50ea5302", - "metadata": { - "editable": true - }, - "source": [ - "1. Then we start looping over all attempts at classifying, namely we start an iterative process for $m=1:M$, where $M$ is the final number of classifications. Our given classifier could for example be a plain decision tree.\n", - "\n", - "a. Fit then a given classifier to the training set using the weights $w_i$.\n", - "\n", - "b. Compute then $\\mathrm{err}$ and figure out which events are classified properly and which are classified wrongly.\n", - "\n", - "c. Define a quantity $\\alpha_{m} = \\log{(1-\\mathrm{\\overline{err}}_m)/\\mathrm{\\overline{err}}_m}$\n", - "\n", - "d. Set the new weights to $w_i = w_i\\times \\exp{(\\alpha_m I(y_i\\ne G(x_i)}$.\n", - "\n", - "5. Compute the new classifier $G(x)= \\sum_{i=0}^{n-1}\\alpha_m I(y_i\\ne G(x_i)$.\n", - "\n", - "For the iterations with $m \\le 2$ the weights are modified\n", - "individually at each steps. The observations which were misclassified\n", - "at iteration $m-1$ have a weight which is larger than those which were\n", - "classified properly. As this proceeds, the observations which were\n", - "difficult to classifiy correctly are given a larger influence. Each\n", - "new classification step $m$ is then forced to concentrate on those\n", - "observations that are missed in the previous iterations." - ] - }, - { - "cell_type": "markdown", - "id": "e6b2e841", - "metadata": { - "editable": true - }, - "source": [ - "## AdaBoost Examples\n", - "\n", - "Using **Scikit-Learn** it is easy to apply the adaptive boosting algorithm, as done here." - ] - }, - { - "cell_type": "code", - "execution_count": 5, - "id": "f3473567", - "metadata": { - "collapsed": false, - "editable": true - }, - "outputs": [], - "source": [ - "from sklearn.ensemble import AdaBoostClassifier\n", - "\n", - "ada_clf = AdaBoostClassifier(\n", - " DecisionTreeClassifier(max_depth=2), n_estimators=200,\n", - " algorithm=\"SAMME.R\", learning_rate=0.01, random_state=42)\n", - "ada_clf.fit(X_train, y_train)\n", - "y_pred = ada_clf.predict(X_test)\n", - "skplt.metrics.plot_confusion_matrix(y_test, y_pred, normalize=True)\n", - "plt.show()\n", - "y_probas = ada_clf.predict_proba(X_test)\n", - "skplt.metrics.plot_roc(y_test, y_probas)\n", - "plt.show()\n", - "skplt.metrics.plot_cumulative_gain(y_test, y_probas)\n", - "plt.show()" - ] - }, - { - "cell_type": "markdown", - "id": "4bf435d0", - "metadata": { - "editable": true - }, - "source": [ - "## Gradient boosting: Basics with Steepest Descent/Functional Gradient Descent\n", - "\n", - "Gradient boosting is again a similar technique to Adaptive boosting,\n", - "it combines so-called weak classifiers or regressors into a strong\n", - "method via a series of iterations.\n", - "\n", - "In order to understand the method, let us illustrate its basics by\n", - "bringing back the essential steps in linear regression, where our cost\n", - "function was the least squares function." - ] - }, - { - "cell_type": "markdown", - "id": "6f9bf84b", - "metadata": { - "editable": true - }, - "source": [ - "## The Squared-Error again! Steepest Descent\n", - "\n", - "We start again with our cost function ${\\cal C}(\\boldsymbol{y}m\\boldsymbol{f})=\\sum_{i=0}^{n-1}{\\cal L}(y_i, f(x_i))$ where we want to minimize\n", - "This means that for every iteration, we need to optimize" - ] - }, - { - "cell_type": "markdown", - "id": "bceb5dce", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "(\\hat{\\boldsymbol{f}}) = \\mathrm{argmin}_{\\boldsymbol{f}}\\hspace{0.1cm} \\sum_{i=0}^{n-1}(y_i-f(x_i))^2.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "b334a5df", - "metadata": { - "editable": true - }, - "source": [ - "We define a real function $h_m(x)$ that defines our final function $f_M(x)$ as" - ] - }, - { - "cell_type": "markdown", - "id": "df096d69", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "f_M(x) = \\sum_{m=0}^M h_m(x).\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "f0367c24", - "metadata": { - "editable": true - }, - "source": [ - "In the steepest decent approach we approximate $h_m(x) = -\\rho_m g_m(x)$, where $\\rho_m$ is a scalar and $g_m(x)$ the gradient defined as" - ] - }, - { - "cell_type": "markdown", - "id": "7e83582e", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "g_m(x_i) = \\left[ \\frac{\\partial {\\cal L}(y_i, f(x_i))}{\\partial f(x_i)}\\right]_{f(x_i)=f_{m-1}(x_i)}.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "6b43e044", - "metadata": { - "editable": true - }, - "source": [ - "With the new gradient we can update $f_m(x) = f_{m-1}(x) -\\rho_m g_m(x)$. Using the above squared-error function we see that\n", - "the gradient is $g_m(x_i) = -2(y_i-f(x_i))$.\n", - "\n", - "Choosing $f_0(x)=0$ we obtain $g_m(x) = -2y_i$ and inserting this into the minimization problem for the cost function we have" - ] - }, - { - "cell_type": "markdown", - "id": "5e5567eb", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "(\\rho_1) = \\mathrm{argmin}_{\\rho}\\hspace{0.1cm} \\sum_{i=0}^{n-1}(y_i+2\\rho y_i)^2.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "bc4464a3", - "metadata": { - "editable": true - }, - "source": [ - "## Steepest Descent Example\n", - "\n", - "Optimizing with respect to $\\rho$ we obtain (taking the derivative) that $\\rho_1 = -1/2$. We have then that" - ] - }, - { - "cell_type": "markdown", - "id": "74a990d2", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "f_1(x) = f_{0}(x) -\\rho_1 g_1(x)=-y_i.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "11ac33af", - "metadata": { - "editable": true - }, - "source": [ - "We can then proceed and compute" - ] - }, - { - "cell_type": "markdown", - "id": "31fad8d3", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "g_2(x_i) = \\left[ \\frac{\\partial {\\cal L}(y_i, f(x_i))}{\\partial f(x_i)}\\right]_{f(x_i)=f_{1}(x_i)=y_i}=-4y_i,\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "664e354f", - "metadata": { - "editable": true - }, - "source": [ - "and find a new value for $\\rho_2=-1/2$ and continue till we have reached $m=M$. We can modify the steepest descent method, or steepest boosting, by introducing what is called **gradient boosting**." - ] - }, - { - "cell_type": "markdown", - "id": "bdcc9bb0", - "metadata": { - "editable": true - }, - "source": [ - "## Gradient Boosting, algorithm\n", - "\n", - "Steepest descent is however not much used, since it only optimizes $f$ at a fixed set of $n$ points,\n", - "so we do not learn a function that can generalize. However, we can modify the algorithm by\n", - "fitting a weak learner to approximate the negative gradient signal. \n", - "\n", - "Suppose we have a cost function $C(f)=\\sum_{i=0}^{n-1}L(y_i, f(x_i))$ where $y_i$ is our target and $f(x_i)$ the function which is meant to model $y_i$. The above cost function could be our standard squared-error function" - ] - }, - { - "cell_type": "markdown", - "id": "91ea379e", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "C(\\boldsymbol{y},\\boldsymbol{f})=\\sum_{i=0}^{n-1}(y_i-f(x_i))^2.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "191fcbc6", - "metadata": { - "editable": true - }, - "source": [ - "The way we proceed in an iterative fashion is to\n", - "1. Initialize our estimate $f_0(x)$.\n", - "\n", - "2. For $m=1:M$, we\n", - "\n", - "a. compute the negative gradient vector $\\boldsymbol{u}_m = -\\partial C(\\boldsymbol{y},\\boldsymbol{f})/\\partial \\boldsymbol{f}(x)$ at $f(x) = f_{m-1}(x)$;\n", - "\n", - "b. fit the so-called base-learner to the negative gradient $h_m(u_m,x)$;\n", - "\n", - "c. update the estimate $f_m(x) = f_{m-1}(x)+h_m(u_m,x)$;\n", - "\n", - "4. The final estimate is then $f_M(x) = \\sum_{m=1}^M h_m(u_m,x)$." - ] - }, - { - "cell_type": "markdown", - "id": "8257c200", - "metadata": { - "editable": true - }, - "source": [ - "## Gradient Boosting, Examples of Regression" - ] - }, - { - "cell_type": "code", - "execution_count": 6, - "id": "97cc442d", - "metadata": { - "collapsed": false, - "editable": true - }, - "outputs": [], - "source": [ - "import matplotlib.pyplot as plt\n", - "import numpy as np\n", - "from sklearn.model_selection import train_test_split\n", - "from sklearn.ensemble import GradientBoostingRegressor\n", - "import scikitplot as skplt\n", - "from sklearn.metrics import mean_squared_error\n", - "\n", - "n = 100\n", - "maxdegree = 6\n", - "\n", - "# Make data set.\n", - "x = np.linspace(-3, 3, n).reshape(-1, 1)\n", - "y = np.exp(-x**2) + 1.5 * np.exp(-(x-2)**2)+ np.random.normal(0, 0.1, x.shape)\n", - "\n", - "error = np.zeros(maxdegree)\n", - "bias = np.zeros(maxdegree)\n", - "variance = np.zeros(maxdegree)\n", - "polydegree = np.zeros(maxdegree)\n", - "X_train, X_test, y_train, y_test = train_test_split(x, y, test_size=0.2)\n", - "\n", - "for degree in range(1,maxdegree):\n", - " model = GradientBoostingRegressor(max_depth=degree, n_estimators=100, learning_rate=1.0) \n", - " model.fit(X_train,y_train)\n", - " y_pred = model.predict(X_test)\n", - " polydegree[degree] = degree\n", - " error[degree] = np.mean( np.mean((y_test - y_pred)**2) )\n", - " bias[degree] = np.mean( (y_test - np.mean(y_pred))**2 )\n", - " variance[degree] = np.mean( np.var(y_pred) )\n", - " print('Max depth:', degree)\n", - " print('Error:', error[degree])\n", - " print('Bias^2:', bias[degree])\n", - " print('Var:', variance[degree])\n", - " print('{} >= {} + {} = {}'.format(error[degree], bias[degree], variance[degree], bias[degree]+variance[degree]))\n", - "\n", - "plt.xlim(1,maxdegree-1)\n", - "plt.plot(polydegree, error, label='Error')\n", - "plt.plot(polydegree, bias, label='bias')\n", - "plt.plot(polydegree, variance, label='Variance')\n", - "plt.legend()\n", - "save_fig(\"gdregression\")\n", - "plt.show()" - ] - }, - { - "cell_type": "markdown", - "id": "e29cb10a", - "metadata": { - "editable": true - }, - "source": [ - "## Gradient Boosting, Classification Example" - ] - }, - { - "cell_type": "code", - "execution_count": 7, - "id": "5e71ebb0", - "metadata": { - "collapsed": false, - "editable": true - }, - "outputs": [], - "source": [ - "import matplotlib.pyplot as plt\n", - "import numpy as np\n", - "from sklearn.model_selection import train_test_split \n", - "from sklearn.datasets import load_breast_cancer\n", - "import scikitplot as skplt\n", - "from sklearn.ensemble import GradientBoostingClassifier\n", - "from sklearn.model_selection import cross_validate\n", - "\n", - "# Load the data\n", - "cancer = load_breast_cancer()\n", - "\n", - "X_train, X_test, y_train, y_test = train_test_split(cancer.data,cancer.target,random_state=0)\n", - "print(X_train.shape)\n", - "print(X_test.shape)\n", - "#now scale the data\n", - "from sklearn.preprocessing import StandardScaler\n", - "scaler = StandardScaler()\n", - "scaler.fit(X_train)\n", - "X_train_scaled = scaler.transform(X_train)\n", - "X_test_scaled = scaler.transform(X_test)\n", - "\n", - "gd_clf = GradientBoostingClassifier(max_depth=3, n_estimators=100, learning_rate=1.0) \n", - "gd_clf.fit(X_train_scaled, y_train)\n", - "#Cross validation\n", - "accuracy = cross_validate(gd_clf,X_test_scaled,y_test,cv=10)['test_score']\n", - "print(accuracy)\n", - "print(\"Test set accuracy with Gradient boosting and scaled data: {:.2f}\".format(gd_clf.score(X_test_scaled,y_test)))\n", - "\n", - "import scikitplot as skplt\n", - "y_pred = gd_clf.predict(X_test_scaled)\n", - "skplt.metrics.plot_confusion_matrix(y_test, y_pred, normalize=True)\n", - "save_fig(\"gdclassiffierconfusion\")\n", - "plt.show()\n", - "y_probas = gd_clf.predict_proba(X_test_scaled)\n", - "skplt.metrics.plot_roc(y_test, y_probas)\n", - "save_fig(\"gdclassiffierroc\")\n", - "plt.show()\n", - "skplt.metrics.plot_cumulative_gain(y_test, y_probas)\n", - "save_fig(\"gdclassiffiercgain\")\n", - "plt.show()" - ] - }, - { - "cell_type": "markdown", - "id": "7704ba08", - "metadata": { - "editable": true - }, - "source": [ - "## XGBoost: Extreme Gradient Boosting\n", - "\n", - "[XGBoost](https://github.com/dmlc/xgboost) or Extreme Gradient\n", - "Boosting, is an optimized distributed gradient boosting library\n", - "designed to be highly efficient, flexible and portable. It implements\n", - "machine learning algorithms under the Gradient Boosting\n", - "framework. XGBoost provides a parallel tree boosting that solve many\n", - "data science problems in a fast and accurate way. See the [article by Chen and Guestrin](https://arxiv.org/abs/1603.02754).\n", - "\n", - "The authors design and build a highly scalable end-to-end tree\n", - "boosting system. It has a theoretically justified weighted quantile\n", - "sketch for efficient proposal calculation. It introduces a novel sparsity-aware algorithm for parallel tree learning and an effective cache-aware block structure for out-of-core tree learning.\n", - "\n", - "It is now the algorithm which wins essentially all ML competitions!!!" - ] - }, - { - "cell_type": "markdown", - "id": "8f314f34", - "metadata": { - "editable": true - }, - "source": [ - "## Regression Case" - ] - }, - { - "cell_type": "code", - "execution_count": 8, - "id": "c6b184a5", - "metadata": { - "collapsed": false, - "editable": true - }, - "outputs": [], - "source": [ - "import matplotlib.pyplot as plt\n", - "import numpy as np\n", - "from sklearn.model_selection import train_test_split\n", - "import xgboost as xgb\n", - "import scikitplot as skplt\n", - "from sklearn.metrics import mean_squared_error\n", - "\n", - "n = 100\n", - "maxdegree = 6\n", - "\n", - "# Make data set.\n", - "x = np.linspace(-3, 3, n).reshape(-1, 1)\n", - "y = np.exp(-x**2) + 1.5 * np.exp(-(x-2)**2)+ np.random.normal(0, 0.1, x.shape)\n", - "\n", - "error = np.zeros(maxdegree)\n", - "bias = np.zeros(maxdegree)\n", - "variance = np.zeros(maxdegree)\n", - "polydegree = np.zeros(maxdegree)\n", - "X_train, X_test, y_train, y_test = train_test_split(x, y, test_size=0.2)\n", - "\n", - "for degree in range(maxdegree):\n", - " model = xgb.XGBRegressor(objective ='reg:squarederror', colsaobjective ='reg:squarederror', colsample_bytree = 0.3, learning_rate = 0.1,max_depth = degree, alpha = 10, n_estimators = 200)\n", - "\n", - " model.fit(X_train,y_train)\n", - " y_pred = model.predict(X_test)\n", - " polydegree[degree] = degree\n", - " error[degree] = np.mean( np.mean((y_test - y_pred)**2) )\n", - " bias[degree] = np.mean( (y_test - np.mean(y_pred))**2 )\n", - " variance[degree] = np.mean( np.var(y_pred) )\n", - " print('Max depth:', degree)\n", - " print('Error:', error[degree])\n", - " print('Bias^2:', bias[degree])\n", - " print('Var:', variance[degree])\n", - " print('{} >= {} + {} = {}'.format(error[degree], bias[degree], variance[degree], bias[degree]+variance[degree]))\n", - "\n", - "plt.xlim(1,maxdegree-1)\n", - "plt.plot(polydegree, error, label='Error')\n", - "plt.plot(polydegree, bias, label='bias')\n", - "plt.plot(polydegree, variance, label='Variance')\n", - "plt.legend()\n", - "plt.show()" - ] - }, - { - "cell_type": "markdown", - "id": "59a68c8d", - "metadata": { - "editable": true - }, - "source": [ - "## Xgboost on the Cancer Data\n", - "\n", - "As you will see from the confusion matrix below, XGBoots does an excellent job on the Wisconsin cancer data and outperforms essentially all agorithms we have discussed till now." - ] - }, - { - "cell_type": "code", - "execution_count": 9, - "id": "6a3f228b", - "metadata": { - "collapsed": false, - "editable": true - }, - "outputs": [], - "source": [ - "\n", - "import matplotlib.pyplot as plt\n", - "import numpy as np\n", - "from sklearn.model_selection import train_test_split \n", - "from sklearn.datasets import load_breast_cancer\n", - "from sklearn.preprocessing import LabelEncoder\n", - "from sklearn.model_selection import cross_validate\n", - "import scikitplot as skplt\n", - "import xgboost as xgb\n", - "# Load the data\n", - "cancer = load_breast_cancer()\n", - "\n", - "X_train, X_test, y_train, y_test = train_test_split(cancer.data,cancer.target,random_state=0)\n", - "print(X_train.shape)\n", - "print(X_test.shape)\n", - "#now scale the data\n", - "from sklearn.preprocessing import StandardScaler\n", - "scaler = StandardScaler()\n", - "scaler.fit(X_train)\n", - "X_train_scaled = scaler.transform(X_train)\n", - "X_test_scaled = scaler.transform(X_test)\n", - "\n", - "xg_clf = xgb.XGBClassifier()\n", - "xg_clf.fit(X_train_scaled,y_train)\n", - "\n", - "y_test = xg_clf.predict(X_test_scaled)\n", - "\n", - "print(\"Test set accuracy with Gradient Boosting and scaled data: {:.2f}\".format(xg_clf.score(X_test_scaled,y_test)))\n", - "\n", - "import scikitplot as skplt\n", - "y_pred = xg_clf.predict(X_test_scaled)\n", - "skplt.metrics.plot_confusion_matrix(y_test, y_pred, normalize=True)\n", - "save_fig(\"xdclassiffierconfusion\")\n", - "plt.show()\n", - "y_probas = xg_clf.predict_proba(X_test_scaled)\n", - "skplt.metrics.plot_roc(y_test, y_probas)\n", - "save_fig(\"xdclassiffierroc\")\n", - "plt.show()\n", - "skplt.metrics.plot_cumulative_gain(y_test, y_probas)\n", - "save_fig(\"gdclassiffiercgain\")\n", - "plt.show()\n", - "\n", - "\n", - "xgb.plot_tree(xg_clf,num_trees=0)\n", - "plt.rcParams['figure.figsize'] = [50, 10]\n", - "save_fig(\"xgtree\")\n", - "plt.show()\n", - "\n", - "xgb.plot_importance(xg_clf)\n", - "plt.rcParams['figure.figsize'] = [5, 5]\n", - "save_fig(\"xgparams\")\n", - "plt.show()" - ] - }, - { - "cell_type": "markdown", - "id": "4756e98c", - "metadata": { - "editable": true - }, - "source": [ - "## Summary of course" - ] - }, - { - "cell_type": "markdown", - "id": "0d2f09bc", - "metadata": { - "editable": true - }, - "source": [ - "## What? Me worry? No final exam in this course!\n", - "\n", - "\n", - "\n", - "

Figure 1:

\n", - "" - ] - }, - { - "cell_type": "markdown", - "id": "bedc75f8", - "metadata": { - "editable": true - }, - "source": [ - "## What is the link between Artificial Intelligence and Machine Learning and some general Remarks\n", - "\n", - "Artificial intelligence is built upon integrated machine learning\n", - "algorithms as discussed in this course, which in turn are fundamentally rooted in optimization and\n", - "statistical learning.\n", - "\n", - "Can we have Artificial Intelligence without Machine Learning? See [this post for inspiration](https://www.linkedin.com/pulse/what-artificial-intelligence-without-machine-learning-claudia-pohlink)." - ] - }, - { - "cell_type": "markdown", - "id": "25385cd0", - "metadata": { - "editable": true - }, - "source": [ - "## Going back to the beginning of the semester\n", - "\n", - "Traditionally the field of machine learning has had its main focus on\n", - "predictions and correlations. These concepts outline in some sense\n", - "the difference between machine learning and what is normally called\n", - "Bayesian statistics or Bayesian inference.\n", - "\n", - "In machine learning and prediction based tasks, we are often\n", - "interested in developing algorithms that are capable of learning\n", - "patterns from given data in an automated fashion, and then using these\n", - "learned patterns to make predictions or assessments of newly given\n", - "data. In many cases, our primary concern is the quality of the\n", - "predictions or assessments, and we are less concerned with the\n", - "underlying patterns that were learned in order to make these\n", - "predictions. This leads to what normally has been labeled as a\n", - "frequentist approach." - ] - }, - { - "cell_type": "markdown", - "id": "97a4cbd9", - "metadata": { - "editable": true - }, - "source": [ - "## Not so sharp distinctions\n", - "\n", - "You should keep in mind that the division between a traditional\n", - "frequentist approach with focus on predictions and correlations only\n", - "and a Bayesian approach with an emphasis on estimations and\n", - "causations, is not that sharp. Machine learning can be frequentist\n", - "with ensemble methods (EMB) as examples and Bayesian with Gaussian\n", - "Processes as examples.\n", - "\n", - "If one views ML from a statistical learning\n", - "perspective, one is then equally interested in estimating errors as\n", - "one is in finding correlations and making predictions. It is important\n", - "to keep in mind that the frequentist and Bayesian approaches differ\n", - "mainly in their interpretations of probability. In the frequentist\n", - "world, we can only assign probabilities to repeated random\n", - "phenomena. From the observations of these phenomena, we can infer the\n", - "probability of occurrence of a specific event. In Bayesian\n", - "statistics, we assign probabilities to specific events and the\n", - "probability represents the measure of belief/confidence for that\n", - "event. The belief can be updated in the light of new evidence." - ] - }, - { - "cell_type": "markdown", - "id": "77dada73", - "metadata": { - "editable": true - }, - "source": [ - "## Topics we have covered this year\n", - "\n", - "The course has two central parts\n", - "\n", - "1. Statistical analysis and optimization of data\n", - "\n", - "2. Machine learning" - ] - }, - { - "cell_type": "markdown", - "id": "4f784898", - "metadata": { - "editable": true - }, - "source": [ - "## Statistical analysis and optimization of data\n", - "\n", - "The following topics have been discussed:\n", - "1. Basic concepts, expectation values, variance, covariance, correlation functions and errors;\n", - "\n", - "2. Simpler models, binomial distribution, the Poisson distribution, simple and multivariate normal distributions;\n", - "\n", - "3. Central elements from linear algebra, matrix inversion and SVD\n", - "\n", - "4. Gradient methods for data optimization\n", - "\n", - "5. Estimation of errors using cross-validation, bootstrapping and jackknife methods;\n", - "\n", - "6. Practical optimization using Singular-value decomposition and least squares for parameterizing data.\n", - "\n", - "7. Principal Component Analysis to reduce the number of features." - ] - }, - { - "cell_type": "markdown", - "id": "35722378", - "metadata": { - "editable": true - }, - "source": [ - "## Machine learning\n", - "\n", - "The following topics will be covered\n", - "1. Linear methods for regression and classification:\n", - "\n", - "a. Ordinary Least Squares\n", - "\n", - "b. Ridge regression\n", - "\n", - "c. Lasso regression\n", - "\n", - "d. Logistic regression\n", - "\n", - "5. Neural networks and deep learning:\n", - "\n", - "a. Feed Forward Neural Networks\n", - "\n", - "b. Convolutional Neural Networks\n", - "\n", - "c. Recurrent Neural Networks\n", - "\n", - "4. Decisions trees and ensemble methods:\n", - "\n", - "a. Decision trees\n", - "\n", - "b. Bagging and voting\n", - "\n", - "c. Random forests\n", - "\n", - "d. Boosting and gradient boosting\n", - "\n", - "5. Support vector machines, not covered this year but included in notes\n", - "\n", - "a. Binary classification and multiclass classification\n", - "\n", - "b. Kernel methods\n", - "\n", - "c. Regression" - ] - }, - { - "cell_type": "markdown", - "id": "c5de1725", - "metadata": { - "editable": true - }, - "source": [ - "## Learning outcomes and overarching aims of this course\n", - "\n", - "The course introduces a variety of central algorithms and methods\n", - "essential for studies of data analysis and machine learning. The\n", - "course is project based and through the various projects, normally\n", - "three, you will be exposed to fundamental research problems\n", - "in these fields, with the aim to reproduce state of the art scientific\n", - "results. The students will learn to develop and structure large codes\n", - "for studying these systems, get acquainted with computing facilities\n", - "and learn to handle large scientific projects. A good scientific and\n", - "ethical conduct is emphasized throughout the course. \n", - "\n", - "* Understand linear methods for regression and classification;\n", - "\n", - "* Learn about neural network;\n", - "\n", - "* Learn about bagging, boosting and trees\n", - "\n", - "* Support vector machines, not covered\n", - "\n", - "* Learn about basic data analysis;\n", - "\n", - "* Be capable of extending the acquired knowledge to other systems and cases;\n", - "\n", - "* Have an understanding of central algorithms used in data analysis and machine learning;\n", - "\n", - "* Work on numerical projects to illustrate the theory. The projects play a central role and you are expected to know modern programming languages like Python or C++." - ] - }, - { - "cell_type": "markdown", - "id": "77f0effd", - "metadata": { - "editable": true - }, - "source": [ - "## Perspective on Machine Learning\n", - "\n", - "1. Rapidly emerging application area\n", - "\n", - "2. Experiment AND theory are evolving in many many fields. Still many low-hanging fruits.\n", - "\n", - "3. Requires education/retraining for more widespread adoption\n", - "\n", - "4. A lot of “word-of-mouth” development methods\n", - "\n", - "Huge amounts of data sets require automation, classical analysis tools often inadequate. \n", - "High energy physics hit this wall in the 90’s.\n", - "In 2009 single top quark production was determined via [Boosted decision trees, Bayesian\n", - "Neural Networks, etc.](https://arxiv.org/pdf/0903.0850.pdf). Similarly, the search for Higgs was a statistical learning tour de force. See this link on [Kaggle.com](https://www.kaggle.com/c/higgs-boson)." - ] - }, - { - "cell_type": "markdown", - "id": "1da4f54b", - "metadata": { - "editable": true - }, - "source": [ - "## Machine Learning Research\n", - "\n", - "Where to find recent results:\n", - "1. Conference proceedings, arXiv and blog posts!\n", - "\n", - "2. **NIPS**: [Neural Information Processing Systems](https://papers.nips.cc)\n", - "\n", - "3. **ICLR**: [International Conference on Learning Representations](https://openreview.net/group?id=ICLR.cc/2018/Conference#accepted-oral-papers)\n", - "\n", - "4. **ICML**: International Conference on Machine Learning\n", - "\n", - "5. [Journal of Machine Learning Research](http://www.jmlr.org/papers/v19/) \n", - "\n", - "6. [Follow ML on ArXiv](https://arxiv.org/list/cs.LG/recent)" - ] - }, - { - "cell_type": "markdown", - "id": "960798e1", - "metadata": { - "editable": true - }, - "source": [ - "## Starting your Machine Learning Project\n", - "\n", - "1. Identify problem type: classification, regression\n", - "\n", - "2. Consider your data carefully\n", - "\n", - "3. Choose a simple model that fits 1. and 2.\n", - "\n", - "4. Consider your data carefully again! Think of data representation more carefully.\n", - "\n", - "5. Based on your results, feedback loop to earliest possible point" - ] - }, - { - "cell_type": "markdown", - "id": "3bb0c58d", - "metadata": { - "editable": true - }, - "source": [ - "## Choose a Model and Algorithm\n", - "\n", - "1. Supervised?\n", - "\n", - "2. Start with the simplest model that fits your problem\n", - "\n", - "3. Start with minimal processing of data" - ] - }, - { - "cell_type": "markdown", - "id": "06e070b4", - "metadata": { - "editable": true - }, - "source": [ - "## Preparing Your Data\n", - "\n", - "1. Shuffle your data\n", - "\n", - "2. Mean center your data\n", - "\n", - " * Why?\n", - "\n", - "3. Normalize the variance\n", - "\n", - " * Why?\n", - "\n", - "4. [Whitening](https://multivariatestatsjl.readthedocs.io/en/latest/whiten.html)\n", - "\n", - " * Decorrelates data\n", - "\n", - " * Can be hit or miss\n", - "\n", - "5. When to do train/test split?\n", - "\n", - "Whitening is a decorrelation transformation that transforms a set of\n", - "random variables into a set of new random variables with identity\n", - "covariance (uncorrelated with unit variances)." - ] - }, - { - "cell_type": "markdown", - "id": "8fc31057", - "metadata": { - "editable": true - }, - "source": [ - "## Which Activation and Weights to Choose in Neural Networks\n", - "\n", - "1. RELU? ELU?\n", - "\n", - "2. Sigmoid or Tanh?\n", - "\n", - "3. Set all weights to 0?\n", - "\n", - " * Terrible idea\n", - "\n", - "4. Set all weights to random values?\n", - "\n", - " * Small random values" - ] - }, - { - "cell_type": "markdown", - "id": "be1f2461", - "metadata": { - "editable": true - }, - "source": [ - "## Optimization Methods and Hyperparameters\n", - "1. Stochastic gradient descent\n", - "\n", - "a. Stochastic gradient descent + momentum\n", - "\n", - "2. State-of-the-art approaches:\n", - "\n", - " * RMSProp\n", - "\n", - " * Adam\n", - "\n", - " * and more\n", - "\n", - "Which regularization and hyperparameters? $L_1$ or $L_2$, soft\n", - "classifiers, depths of trees and many other. Need to explore a large\n", - "set of hyperparameters and regularization methods." - ] - }, - { - "cell_type": "markdown", - "id": "2bf97adf", - "metadata": { - "editable": true - }, - "source": [ - "## Resampling\n", - "\n", - "When do we resample?\n", - "\n", - "1. [Bootstrap](https://www.cambridge.org/core/books/bootstrap-methods-and-their-application/ED2FD043579F27952363566DC09CBD6A)\n", - "\n", - "2. [Cross-validation](https://www.youtube.com/watch?v=fSytzGwwBVw&ab_channel=StatQuestwithJoshStarmer)\n", - "\n", - "3. Jackknife and many other" - ] - }, - { - "cell_type": "markdown", - "id": "af4d612c", - "metadata": { - "editable": true - }, - "source": [ - "## Other courses on Data science and Machine Learning at UiO\n", - "\n", - "1. [FYS5429 Advanced Machine Learning and Data Analysis for the Physical Sciences](https://www.uio.no/studier/emner/matnat/fys/FYS5429/index-eng.html). Discussed deep learning and generative deep learning.\n", - "\n", - "2. [FYS5419 Quantum Computing and Quantum Machine Learning](https://www.uio.no/studier/emner/matnat/fys/FYS5419/index-eng.html)\n", - "\n", - "3. [STK2100 Machine learning and statistical methods for prediction and classification](http://www.uio.no/studier/emner/matnat/math/STK2100/index-eng.html). \n", - "\n", - "4. [IN3050/IN4050 Introduction to Artificial Intelligence and Machine Learning](https://www.uio.no/studier/emner/matnat/ifi/IN3050/index-eng.html). Introductory course in machine learning and AI with an algorithmic approach. \n", - "\n", - "5. [STK-INF3000/4000 Selected Topics in Data Science](http://www.uio.no/studier/emner/matnat/math/STK-INF3000/index-eng.html). The course provides insight into selected contemporary relevant topics within Data Science. \n", - "\n", - "6. [IN4080 Natural Language Processing](https://www.uio.no/studier/emner/matnat/ifi/IN4080/index.html). Probabilistic and machine learning techniques applied to natural language processing. o [STK-IN4300 – Statistical learning methods in Data Science](https://www.uio.no/studier/emner/matnat/math/STK-IN4300/index-eng.html). An advanced introduction to statistical and machine learning. For students with a good mathematics and statistics background.\n", - "\n", - "7. [IN-STK5000 Adaptive Methods for Data-Based Decision Making](https://www.uio.no/studier/emner/matnat/ifi/IN-STK5000/index-eng.html). Methods for adaptive collection and processing of data based on machine learning techniques. \n", - "\n", - "8. [IN5400/INF5860 – Machine Learning for Image Analysis](https://www.uio.no/studier/emner/matnat/ifi/IN5400/). An introduction to deep learning with particular emphasis on applications within Image analysis, but useful for other application areas too.\n", - "\n", - "9. [TEK5040 – Dyp læring for autonome systemer](https://www.uio.no/studier/emner/matnat/its/TEK5040/). The course addresses advanced algorithms and architectures for deep learning with neural networks. The course provides an introduction to how deep-learning techniques can be used in the construction of key parts of advanced autonomous systems that exist in physical environments and cyber environments." - ] - }, - { - "cell_type": "markdown", - "id": "02ca1e2c", - "metadata": { - "editable": true - }, - "source": [ - "## Additional courses of interest\n", - "\n", - "1. [STK4051 Computational Statistics](https://www.uio.no/studier/emner/matnat/math/STK4051/index-eng.html)\n", - "\n", - "2. [STK4021 Applied Bayesian Analysis and Numerical Methods](https://www.uio.no/studier/emner/matnat/math/STK4021/index-eng.html)" - ] - }, - { - "cell_type": "markdown", - "id": "1bd70651", - "metadata": { - "editable": true - }, - "source": [ - "## What's the future like?\n", - "\n", - "Based on multi-layer nonlinear neural networks, deep learning can\n", - "learn directly from raw data, automatically extract and abstract\n", - "features from layer to layer, and then achieve the goal of regression,\n", - "classification, or ranking. Deep learning has made breakthroughs in\n", - "computer vision, speech processing and natural language, and reached\n", - "or even surpassed human level. The success of deep learning is mainly\n", - "due to the three factors: big data, big model, and big computing.\n", - "\n", - "In the past few decades, many different architectures of deep neural\n", - "networks have been proposed, such as\n", - "1. Convolutional neural networks, which are mostly used in image and video data processing, and have also been applied to sequential data such as text processing;\n", - "\n", - "2. Recurrent neural networks, which can process sequential data of variable length and have been widely used in natural language understanding and speech processing;\n", - "\n", - "3. Encoder-decoder framework, which is mostly used for image or sequence generation, such as machine translation, text summarization, and image captioning.\n", - "\n", - "4. **Generative deep learning**! Recent textbook by David Foster (and obviously many other ones) at \"" - ] - }, - { - "cell_type": "markdown", - "id": "ec41c770", - "metadata": { - "editable": true - }, - "source": [ - "## Types of Machine Learning, a repetition\n", - "\n", - "The approaches to machine learning are many, but are often split into two main categories. \n", - "In *supervised learning* we know the answer to a problem,\n", - "and let the computer deduce the logic behind it. On the other hand, *unsupervised learning*\n", - "is a method for finding patterns and relationship in data sets without any prior knowledge of the system.\n", - "Some authours also operate with a third category, namely *reinforcement learning*. This is a paradigm \n", - "of learning inspired by behavioural psychology, where learning is achieved by trial-and-error, \n", - "solely from rewards and punishment.\n", - "\n", - "Another way to categorize machine learning tasks is to consider the desired output of a system.\n", - "Some of the most common tasks are:\n", - "\n", - " * Classification: Outputs are divided into two or more classes. The goal is to produce a model that assigns inputs into one of these classes. An example is to identify digits based on pictures of hand-written ones. Classification is typically supervised learning.\n", - "\n", - " * Regression: Finding a functional relationship between an input data set and a reference data set. The goal is to construct a function that maps input data to continuous output values.\n", - "\n", - " * Clustering: Data are divided into groups with certain common traits, without knowing the different groups beforehand. It is thus a form of unsupervised learning.\n", - "\n", - " * Other unsupervised learning algortihms like **Boltzmann machines**" - ] - }, - { - "cell_type": "markdown", - "id": "eb4b2fd3", - "metadata": { - "editable": true - }, - "source": [ - "## Why Boltzmann machines?\n", - "\n", - "What is known as restricted Boltzmann Machines (RMB) have received a lot of attention lately. \n", - "One of the major reasons is that they can be stacked layer-wise to build deep neural networks that capture complicated statistics.\n", - "\n", - "The original RBMs had just one visible layer and a hidden layer, but recently so-called Gaussian-binary RBMs have gained quite some popularity in imaging since they are capable of modeling continuous data that are common to natural images. \n", - "\n", - "Furthermore, they have been used to solve complicated [quantum mechanical many-particle problems or classical statistical physics problems like the Ising and Potts classes of models](https://journals.aps.org/rmp/abstract/10.1103/RevModPhys.91.045002)." - ] - }, - { - "cell_type": "markdown", - "id": "666fb9a8", - "metadata": { - "editable": true - }, - "source": [ - "## Boltzmann Machines\n", - "\n", - "Why use a generative model rather than the more well known discriminative deep neural networks (DNN)? **Simplest approach to generative deep learning**.\n", - "\n", - "* Discriminitave methods have several limitations: They are mainly supervised learning methods, thus requiring labeled data. And there are tasks they cannot accomplish, like drawing new examples from an unknown probability distribution.\n", - "\n", - "* A generative model can learn to represent and sample from a probability distribution. The core idea is to learn a parametric model of the probability distribution from which the training data was drawn. As an example\n", - "\n", - "a. A model for images could learn to draw new examples of cats and dogs, given a training dataset of images of cats and dogs.\n", - "\n", - "b. Generate a sample of an ordered or disordered phase, having been given samples of such phases.\n", - "\n", - "c. Model the trial function for [Monte Carlo calculations](https://journals.aps.org/rmp/abstract/10.1103/RevModPhys.91.045002)." - ] - }, - { - "cell_type": "markdown", - "id": "59961309", - "metadata": { - "editable": true - }, - "source": [ - "## Some similarities and differences from DNNs\n", - "\n", - "1. Both use gradient-descent based learning procedures for minimizing cost functions\n", - "\n", - "2. Energy based models don't use backpropagation and automatic differentiation for computing gradients, instead turning to Markov Chain Monte Carlo methods.\n", - "\n", - "3. DNNs often have several hidden layers. A restricted Boltzmann machine has only one hidden layer, however several RBMs can be stacked to make up Deep Belief Networks, of which they constitute the building blocks.\n", - "\n", - "History: The RBM was developed by amongst others [Geoffrey Hinton](https://en.wikipedia.org/wiki/Geoffrey_Hinton), called by some the \"Godfather of Deep Learning\", working with the University of Toronto and Google." - ] - }, - { - "cell_type": "markdown", - "id": "95115be7", - "metadata": { - "editable": true - }, - "source": [ - "## Boltzmann machines (BM)\n", - "\n", - "A BM is what we would call an undirected probabilistic graphical model\n", - "with stochastic continuous or discrete units.\n", - "\n", - "It is interpreted as a stochastic recurrent neural network where the\n", - "state of each unit(neurons/nodes) depends on the units it is connected\n", - "to. The weights in the network represent thus the strength of the\n", - "interaction between various units/nodes.\n", - "\n", - "It turns into a Hopfield network if we choose deterministic rather\n", - "than stochastic units. In contrast to a Hopfield network, a BM is a\n", - "so-called generative model. It allows us to generate new samples from\n", - "the learned distribution." - ] - }, - { - "cell_type": "markdown", - "id": "67240cfb", - "metadata": { - "editable": true - }, - "source": [ - "## A standard BM setup\n", - "\n", - "A standard BM network is divided into a set of observable and visible units $\\hat{x}$ and a set of unknown hidden units/nodes $\\hat{h}$.\n", - "\n", - "Additionally there can be bias nodes for the hidden and visible layers. These biases are normally set to $1$.\n", - "\n", - "BMs are stackable, meaning they cwe can train a BM which serves as input to another BM. We can construct deep networks for learning complex PDFs. The layers can be trained one after another, a feature which makes them popular in deep learning\n", - "\n", - "However, they are often hard to train. This leads to the introduction of so-called restricted BMs, or RBMS.\n", - "Here we take away all lateral connections between nodes in the visible layer as well as connections between nodes in the hidden layer. The network is illustrated in the figure below." - ] - }, - { - "cell_type": "markdown", - "id": "34238f91", - "metadata": { - "editable": true - }, - "source": [ - "## The structure of the RBM network\n", - "\n", - "\n", - "\n", - "\n", - "

Figure 1:

\n", - "" - ] - }, - { - "cell_type": "markdown", - "id": "b5a2f4e8", - "metadata": { - "editable": true - }, - "source": [ - "## The network\n", - "\n", - "**The network layers**:\n", - "1. A function $\\mathbf{x}$ that represents the visible layer, a vector of $M$ elements (nodes). This layer represents both what the RBM might be given as training input, and what we want it to be able to reconstruct. This might for example be given by the pixels of an image or coefficients representing speech, or the coordinates of a quantum mechanical state function.\n", - "\n", - "2. The function $\\mathbf{h}$ represents the hidden, or latent, layer. A vector of $N$ elements (nodes). Also called \"feature detectors\"." - ] - }, - { - "cell_type": "markdown", - "id": "8814bf46", - "metadata": { - "editable": true - }, - "source": [ - "## Goals\n", - "\n", - "The goal of the hidden layer is to increase the model's expressive\n", - "power. We encode complex interactions between visible variables by\n", - "introducing additional, hidden variables that interact with visible\n", - "degrees of freedom in a simple manner, yet still reproduce the complex\n", - "correlations between visible degrees in the data once marginalized\n", - "over (integrated out).\n", - "\n", - "**The network parameters, to be optimized/learned**:\n", - "1. $\\mathbf{a}$ represents the visible bias, a vector of same length as $\\mathbf{x}$.\n", - "\n", - "2. $\\mathbf{b}$ represents the hidden bias, a vector of same lenght as $\\mathbf{h}$.\n", - "\n", - "3. $W$ represents the interaction weights, a matrix of size $M\\times N$." - ] - }, - { - "cell_type": "markdown", - "id": "7fc70e53", - "metadata": { - "editable": true - }, - "source": [ - "## Joint distribution\n", - "\n", - "The restricted Boltzmann machine is described by a Boltzmann distribution" - ] - }, - { - "cell_type": "markdown", - "id": "db48a9df", - "metadata": { - "editable": true - }, - "source": [ - "\n", - "
\n", - "\n", - "$$\n", - "\\begin{equation}\n", - "\tP_{rbm}(\\mathbf{x},\\mathbf{h}) = \\frac{1}{Z} e^{-\\frac{1}{T_0}E(\\mathbf{x},\\mathbf{h})},\n", - "\\label{_auto1} \\tag{1}\n", - "\\end{equation}\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "62a31f83", - "metadata": { - "editable": true - }, - "source": [ - "where $Z$ is the normalization constant or partition function, defined as" - ] - }, - { - "cell_type": "markdown", - "id": "cb335a56", - "metadata": { - "editable": true - }, - "source": [ - "\n", - "
\n", - "\n", - "$$\n", - "\\begin{equation}\n", - "\tZ = \\int \\int e^{-\\frac{1}{T_0}E(\\mathbf{x},\\mathbf{h})} d\\mathbf{x} d\\mathbf{h}.\n", - "\\label{_auto2} \\tag{2}\n", - "\\end{equation}\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "599fa487", - "metadata": { - "editable": true - }, - "source": [ - "It is common to ignore $T_0$ by setting it to one." - ] - }, - { - "cell_type": "markdown", - "id": "114dd535", - "metadata": { - "editable": true - }, - "source": [ - "## Network Elements, the energy function\n", - "\n", - "The function $E(\\mathbf{x},\\mathbf{h})$ gives the **energy** of a\n", - "configuration (pair of vectors) $(\\mathbf{x}, \\mathbf{h})$. The lower\n", - "the energy of a configuration, the higher the probability of it. This\n", - "function also depends on the parameters $\\mathbf{a}$, $\\mathbf{b}$ and\n", - "$W$. Thus, when we adjust them during the learning procedure, we are\n", - "adjusting the energy function to best fit our problem.\n", - "\n", - "An expression for the energy function is" - ] - }, - { - "cell_type": "markdown", - "id": "211cb42a", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "E(\\hat{x},\\hat{h}) = -\\sum_{ia}^{NA}b_i^a \\alpha_i^a(x_i)-\\sum_{jd}^{MD}c_j^d \\beta_j^d(h_j)-\\sum_{ijad}^{NAMD}b_i^a \\alpha_i^a(x_i)c_j^d \\beta_j^d(h_j)w_{ij}^{ad}.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "e70c1aa0", - "metadata": { - "editable": true - }, - "source": [ - "Here $\\beta_j^d(h_j)$ and $\\alpha_i^a(x_j)$ are so-called transfer functions that map a given input value to a desired feature value. The labels $a$ and $d$ denote that there can be multiple transfer functions per variable. The first sum depends only on the visible units. The second on the hidden ones. **Note** that there is no connection between nodes in a layer.\n", - "\n", - "The quantities $b$ and $c$ can be interpreted as the visible and hidden biases, respectively.\n", - "\n", - "The connection between the nodes in the two layers is given by the weights $w_{ij}$." - ] - }, - { - "cell_type": "markdown", - "id": "8176921d", - "metadata": { - "editable": true - }, - "source": [ - "## Defining different types of RBMs\n", - "There are different variants of RBMs, and the differences lie in the types of visible and hidden units we choose as well as in the implementation of the energy function $E(\\mathbf{x},\\mathbf{h})$. \n", - "\n", - "**Binary-Binary RBM:**\n", - "\n", - "RBMs were first developed using binary units in both the visible and hidden layer. The corresponding energy function is defined as follows:" - ] - }, - { - "cell_type": "markdown", - "id": "d4559704", - "metadata": { - "editable": true - }, - "source": [ - "\n", - "
\n", - "\n", - "$$\n", - "\\begin{equation}\n", - "\tE(\\mathbf{x}, \\mathbf{h}) = - \\sum_i^M x_i a_i- \\sum_j^N b_j h_j - \\sum_{i,j}^{M,N} x_i w_{ij} h_j,\n", - "\\label{_auto3} \\tag{3}\n", - "\\end{equation}\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "6087f3b1", - "metadata": { - "editable": true - }, - "source": [ - "where the binary values taken on by the nodes are most commonly 0 and 1.\n", - "\n", - "**Gaussian-Binary RBM:**\n", - "\n", - "Another varient is the RBM where the visible units are Gaussian while the hidden units remain binary:" - ] - }, - { - "cell_type": "markdown", - "id": "090cbae9", - "metadata": { - "editable": true - }, - "source": [ - "\n", - "
\n", - "\n", - "$$\n", - "\\begin{equation}\n", - "\tE(\\mathbf{x}, \\mathbf{h}) = \\sum_i^M \\frac{(x_i - a_i)^2}{2\\sigma_i^2} - \\sum_j^N b_j h_j - \\sum_{i,j}^{M,N} \\frac{x_i w_{ij} h_j}{\\sigma_i^2}. \n", - "\\label{_auto4} \\tag{4}\n", - "\\end{equation}\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "19c78c3f", - "metadata": { - "editable": true - }, - "source": [ - "## More about RBMs\n", - "1. Useful when we model continuous data (i.e., we wish $\\mathbf{x}$ to be continuous)\n", - "\n", - "2. Requires a smaller learning rate, since there's no upper bound to the value a component might take in the reconstruction\n", - "\n", - "Other types of units include:\n", - "1. Softmax and multinomial units\n", - "\n", - "2. Gaussian visible and hidden units\n", - "\n", - "3. Binomial units\n", - "\n", - "4. Rectified linear units\n", - "\n", - "To read more, see [Lectures on Boltzmann machines in Physics](https://github.com/CompPhysics/ComputationalPhysics2/blob/gh-pages/doc/pub/notebook2/ipynb/notebook2.ipynb)." - ] - }, - { - "cell_type": "markdown", - "id": "2c32807b", - "metadata": { - "editable": true - }, - "source": [ - "## Autoencoders: Overarching view\n", - "\n", - "Autoencoders are artificial neural networks capable of learning\n", - "efficient representations of the input data (these representations are called codings) without\n", - "any supervision (i.e., the training set is unlabeled). These codings\n", - "typically have a much lower dimensionality than the input data, making\n", - "autoencoders useful for dimensionality reduction. \n", - "\n", - "More importantly, autoencoders act as powerful feature detectors, and\n", - "they can be used for unsupervised pretraining of deep neural networks.\n", - "\n", - "Lastly, they are capable of randomly generating new data that looks\n", - "very similar to the training data; this is called a generative\n", - "model. For example, you could train an autoencoder on pictures of\n", - "faces, and it would then be able to generate new faces. Surprisingly,\n", - "autoencoders work by simply learning to copy their inputs to their\n", - "outputs. This may sound like a trivial task, but we will see that\n", - "constraining the network in various ways can make it rather\n", - "difficult. For example, you can limit the size of the internal\n", - "representation, or you can add noise to the inputs and train the\n", - "network to recover the original inputs. These constraints prevent the\n", - "autoencoder from trivially copying the inputs directly to the outputs,\n", - "which forces it to learn efficient ways of representing the data. In\n", - "short, the codings are byproducts of the autoencoder’s attempt to\n", - "learn the identity function under some constraints.\n", - "\n", - "[Video on autoencoders](https://www.coursera.org/lecture/building-deep-learning-models-with-tensorflow/autoencoders-1U4L3)\n", - "\n", - "See also A. Geron's textbook, chapter 15." - ] - }, - { - "cell_type": "markdown", - "id": "f988bcd6", - "metadata": { - "editable": true - }, - "source": [ - "## Bayesian Machine Learning\n", - "\n", - "This is an important topic if we aim at extracting a probability\n", - "distribution. This gives us also a confidence interval and error\n", - "estimates.\n", - "\n", - "Bayesian machine learning allows us to encode our prior beliefs about\n", - "what those models should look like, independent of what the data tells\n", - "us. This is especially useful when we don’t have a ton of data to\n", - "confidently learn our model.\n", - "\n", - "[Video on Bayesian deep learning](https://www.youtube.com/watch?v=E1qhGw8QxqY&ab_channel=AndrewGordonWilson)\n", - "\n", - "See also the [slides here](https://github.com/CompPhysics/MachineLearning/blob/master/doc/Articles/lec03.pdf)." - ] - }, - { - "cell_type": "markdown", - "id": "c75013bd", - "metadata": { - "editable": true - }, - "source": [ - "## Reinforcement Learning\n", - "\n", - "Reinforcement Learning (RL) is one of the most exciting fields of\n", - "Machine Learning today, and also one of the oldest. It has been around\n", - "since the 1950s, producing many interesting applications over the\n", - "years.\n", - "\n", - "It studies\n", - "how agents take actions based on trial and error, so as to maximize\n", - "some notion of cumulative reward in a dynamic system or\n", - "environment. Due to its generality, the problem has also been studied\n", - "in many other disciplines, such as game theory, control theory,\n", - "operations research, information theory, multi-agent systems, swarm\n", - "intelligence, statistics, and genetic algorithms.\n", - "\n", - "In March 2016, AlphaGo, a computer program that plays the board game\n", - "Go, beat Lee Sedol in a five-game match. This was the first time a\n", - "computer Go program had beaten a 9-dan (highest rank) professional\n", - "without handicaps. AlphaGo is based on deep convolutional neural\n", - "networks and reinforcement learning. AlphaGo’s victory was a major\n", - "milestone in artificial intelligence and it has also made\n", - "reinforcement learning a hot research area in the field of machine\n", - "learning.\n", - "\n", - "[Lecture on Reinforcement Learning](https://www.youtube.com/watch?v=FgzM3zpZ55o&ab_channel=stanfordonline).\n", - "\n", - "See also A. Geron's textbook, chapter 16." - ] - }, - { - "cell_type": "markdown", - "id": "f0ba11de", - "metadata": { - "editable": true - }, - "source": [ - "## Transfer learning\n", - "\n", - "The goal of transfer learning is to transfer the model or knowledge\n", - "obtained from a source task to the target task, in order to resolve\n", - "the issues of insufficient training data in the target task. The\n", - "rationality of doing so lies in that usually the source and target\n", - "tasks have inter-correlations, and therefore either the features,\n", - "samples, or models in the source task might provide useful information\n", - "for us to better solve the target task. Transfer learning is a hot\n", - "research topic in recent years, with many problems still waiting to be studied.\n", - "\n", - "[Lecture on transfer learning](https://www.ias.edu/video/machinelearning/2020/0331-SamoryKpotufe)." - ] - }, - { - "cell_type": "markdown", - "id": "7c3f7c5b", - "metadata": { - "editable": true - }, - "source": [ - "## Adversarial learning\n", - "\n", - "The conventional deep generative model has a potential problem: the\n", - "model tends to generate extreme instances to maximize the\n", - "probabilistic likelihood, which will hurt its performance. Adversarial\n", - "learning utilizes the adversarial behaviors (e.g., generating\n", - "adversarial instances or training an adversarial model) to enhance the\n", - "robustness of the model and improve the quality of the generated\n", - "data. In recent years, one of the most promising unsupervised learning\n", - "technologies, generative adversarial networks (GAN), has already been\n", - "successfully applied to image, speech, and text.\n", - "\n", - "[Lecture on adversial learning](https://www.youtube.com/watch?v=CIfsB_EYsVI&ab_channel=StanfordUniversitySchoolofEngineering)." - ] - }, - { - "cell_type": "markdown", - "id": "964dd5f1", - "metadata": { - "editable": true - }, - "source": [ - "## Dual learning\n", - "\n", - "Dual learning is a new learning paradigm, the basic idea of which is\n", - "to use the primal-dual structure between machine learning tasks to\n", - "obtain effective feedback/regularization, and guide and strengthen the\n", - "learning process, thus reducing the requirement of large-scale labeled\n", - "data for deep learning. The idea of dual learning has been applied to\n", - "many problems in machine learning, including machine translation,\n", - "image style conversion, question answering and generation, image\n", - "classification and generation, text classification and generation,\n", - "image-to-text, and text-to-image." - ] - }, - { - "cell_type": "markdown", - "id": "53d27ff9", - "metadata": { - "editable": true - }, - "source": [ - "## Distributed machine learning\n", - "\n", - "Distributed computation will speed up machine learning algorithms,\n", - "significantly improve their efficiency, and thus enlarge their\n", - "application. When distributed meets machine learning, more than just\n", - "implementing the machine learning algorithms in parallel is required." - ] - }, - { - "cell_type": "markdown", - "id": "263d674f", - "metadata": { - "editable": true - }, - "source": [ - "## Meta learning\n", - "\n", - "Meta learning is an emerging research direction in machine\n", - "learning. Roughly speaking, meta learning concerns learning how to\n", - "learn, and focuses on the understanding and adaptation of the learning\n", - "itself, instead of just completing a specific learning task. That is,\n", - "a meta learner needs to be able to evaluate its own learning methods\n", - "and adjust its own learning methods according to specific learning\n", - "tasks." - ] - }, - { - "cell_type": "markdown", - "id": "df2807f3", - "metadata": { - "editable": true - }, - "source": [ - "## The Challenges Facing Machine Learning\n", - "\n", - "While there has been much progress in machine learning, there are also challenges.\n", - "\n", - "For example, the mainstream machine learning technologies are\n", - "black-box approaches, making us concerned about their potential\n", - "risks. To tackle this challenge, we may want to make machine learning\n", - "more explainable and controllable. As another example, the\n", - "computational complexity of machine learning algorithms is usually\n", - "very high and we may want to invent lightweight algorithms or\n", - "implementations. Furthermore, in many domains such as physics,\n", - "chemistry, biology, and social sciences, people usually seek elegantly\n", - "simple equations (e.g., the Schrödinger equation) to uncover the\n", - "underlying laws behind various phenomena. In the field of machine\n", - "learning, can we reveal simple laws instead of designing more complex\n", - "models for data fitting? Although there are many challenges, we are\n", - "still very optimistic about the future of machine learning. As we look\n", - "forward to the future, here are what we think the research hotspots in\n", - "the next ten years will be.\n", - "\n", - "See the article on [Discovery of Physics From Data: Universal Laws and Discrepancies](https://www.frontiersin.org/articles/10.3389/frai.2020.00025/full)" - ] - }, - { - "cell_type": "markdown", - "id": "97618d26", - "metadata": { - "editable": true - }, - "source": [ - "## Explainable machine learning\n", - "\n", - "Machine learning, especially deep learning, evolves rapidly. The\n", - "ability gap between machine and human on many complex cognitive tasks\n", - "becomes narrower and narrower. However, we are still in the very early\n", - "stage in terms of explaining why those effective models work and how\n", - "they work.\n", - "\n", - "**What is missing: the gap between correlation and causation**. Standard Machine Learning is based on what e have called a frequentist approach. \n", - "\n", - "Most\n", - "machine learning techniques, especially the statistical ones, depend\n", - "highly on correlations in data sets to make predictions and analyses. In\n", - "contrast, rational humans tend to reply on clear and trustworthy\n", - "causality relations obtained via logical reasoning on real and clear\n", - "facts. It is one of the core goals of explainable machine learning to\n", - "transition from solving problems by data correlation to solving\n", - "problems by logical reasoning.\n", - "\n", - "**Bayesian Machine Learning is one of the exciting research directions in this field**." - ] - }, - { - "cell_type": "markdown", - "id": "e661ff12", - "metadata": { - "editable": true - }, - "source": [ - "## Scientific Machine Learning\n", - "\n", - "An important and emerging field is what has been dubbed as scientific ML, see the article by Deiana et al [Applications and Techniques for Fast Machine Learning in Science, arXiv:2110.13041](https://arxiv.org/abs/2110.13041)\n", - "\n", - "The authors discuss applications and techniques for fast machine\n", - "learning (ML) in science - the concept of integrating power ML\n", - "methods into the real-time experimental data processing loop to\n", - "accelerate scientific discovery. The report covers three main areas\n", - "\n", - "1. applications for fast ML across a number of scientific domains;\n", - "\n", - "2. techniques for training and implementing performant and resource-efficient ML algorithms;\n", - "\n", - "3. and computing architectures, platforms, and technologies for deploying these algorithms." - ] - }, - { - "cell_type": "markdown", - "id": "45e0405a", - "metadata": { - "editable": true - }, - "source": [ - "## Quantum machine learning\n", - "\n", - "Quantum machine learning is an emerging interdisciplinary research\n", - "area at the intersection of quantum computing and machine learning.\n", - "\n", - "Quantum computers use effects such as quantum coherence and quantum\n", - "entanglement to process information, which is fundamentally different\n", - "from classical computers. Quantum algorithms have surpassed the best\n", - "classical algorithms in several problems (e.g., searching for an\n", - "unsorted database, inverting a sparse matrix), which we call quantum\n", - "acceleration.\n", - "\n", - "When quantum computing meets machine learning, it can be a mutually\n", - "beneficial and reinforcing process, as it allows us to take advantage\n", - "of quantum computing to improve the performance of classical machine\n", - "learning algorithms. In addition, we can also use the machine learning\n", - "algorithms (on classic computers) to analyze and improve quantum\n", - "computing systems.\n", - "\n", - "[Lecture on Quantum ML](https://www.youtube.com/watch?v=Xh9pUu3-WxM&ab_channel=InstituteforPure%26AppliedMathematics%28IPAM%29).\n", - "\n", - "[Read interview with Maria Schuld on her work on Quantum Machine Learning](https://physics.aps.org/articles/v13/179?utm_campaign=weekly&utm_medium=email&utm_source=emailalert). See also [her recent textbook](https://www.springer.com/gp/book/9783319964232)." - ] - }, - { - "cell_type": "markdown", - "id": "04188bac", - "metadata": { - "editable": true - }, - "source": [ - "## Quantum machine learning algorithms based on linear algebra\n", - "\n", - "Many quantum machine learning algorithms are based on variants of\n", - "quantum algorithms for solving linear equations, which can efficiently\n", - "solve N-variable linear equations with complexity of O(log2 N) under\n", - "certain conditions. The quantum matrix inversion algorithm can\n", - "accelerate many machine learning methods, such as least square linear\n", - "regression, least square version of support vector machine, Gaussian\n", - "process, and more. The training of these algorithms can be simplified\n", - "to solve linear equations. The key bottleneck of this type of quantum\n", - "machine learning algorithms is data input—that is, how to initialize\n", - "the quantum system with the entire data set. Although efficient\n", - "data-input algorithms exist for certain situations, how to efficiently\n", - "input data into a quantum system is as yet unknown for most cases." - ] - }, - { - "cell_type": "markdown", - "id": "6ab01276", - "metadata": { - "editable": true - }, - "source": [ - "## Quantum reinforcement learning\n", - "\n", - "In quantum reinforcement learning, a quantum agent interacts with the\n", - "classical environment to obtain rewards from the environment, so as to\n", - "adjust and improve its behavioral strategies. In some cases, it\n", - "achieves quantum acceleration by the quantum processing capabilities\n", - "of the agent or the possibility of exploring the environment through\n", - "quantum superposition. Such algorithms have been proposed in\n", - "superconducting circuits and systems of trapped ions." - ] - }, - { - "cell_type": "markdown", - "id": "132951d0", - "metadata": { - "editable": true - }, - "source": [ - "## Quantum deep learning\n", - "\n", - "Dedicated quantum information processors, such as quantum annealers\n", - "and programmable photonic circuits, are well suited for building deep\n", - "quantum networks. The simplest deep quantum network is the Boltzmann\n", - "machine. The classical Boltzmann machine consists of bits with tunable\n", - "interactions and is trained by adjusting the interaction of these bits\n", - "so that the distribution of its expression conforms to the statistics\n", - "of the data. To quantize the Boltzmann machine, the neural network can\n", - "simply be represented as a set of interacting quantum spins that\n", - "correspond to an adjustable Ising model. Then, by initializing the\n", - "input neurons in the Boltzmann machine to a fixed state and allowing\n", - "the system to heat up, we can read out the output qubits to get the\n", - "result." - ] - }, - { - "cell_type": "markdown", - "id": "06d34a06", - "metadata": { - "editable": true - }, - "source": [ - "## Social machine learning\n", - "\n", - "Machine learning aims to imitate how humans\n", - "learn. While we have developed successful machine learning algorithms,\n", - "until now we have ignored one important fact: humans are social. Each\n", - "of us is one part of the total society and it is difficult for us to\n", - "live, learn, and improve ourselves, alone and isolated. Therefore, we\n", - "should design machines with social properties. Can we let machines\n", - "evolve by imitating human society so as to achieve more effective,\n", - "intelligent, interpretable “social machine learning”?\n", - "\n", - "And much more." - ] - }, - { - "cell_type": "markdown", - "id": "8e7e63e1", - "metadata": { - "editable": true - }, - "source": [ - "## The last words?\n", - "\n", - "Early computer scientist Alan Kay said, **The best way to predict the\n", - "future is to create it**. Therefore, all machine learning\n", - "practitioners, whether scholars or engineers, professors or students,\n", - "need to work together to advance these important research\n", - "topics. Together, we will not just predict the future, but create it." - ] - }, - { - "cell_type": "markdown", - "id": "8d87fad6", - "metadata": { - "editable": true - }, - "source": [ - "## AI/ML and some statements you may have heard (and what do they mean?)\n", - "\n", - "1. Fei-Fei Li on ImageNet: **map out the entire world of objects** ([The data that transformed AI research](https://cacm.acm.org/news/219702-the-data-that-transformed-ai-research-and-possibly-the-world/fulltext))\n", - "\n", - "2. Russell and Norvig in their popular textbook: **relevant to any intellectual task; it is truly a universal field** ([Artificial Intelligence, A modern approach](http://aima.cs.berkeley.edu/))\n", - "\n", - "3. Woody Bledsoe puts it more bluntly: **in the long run, AI is the only science** (quoted in Pamilla McCorduck, [Machines who think](https://www.pamelamccorduck.com/machines-who-think))\n", - "\n", - "If you wish to have a critical read on AI/ML from a societal point of view, see [Kate Crawford's recent text Atlas of AI](https://www.katecrawford.net/)\n", - "\n", - "**Here: with AI/ML we intend a collection of machine learning methods with an emphasis on statistical learning and data analysis**" - ] - }, - { - "cell_type": "markdown", - "id": "52dd089f", - "metadata": { - "editable": true - }, - "source": [ - "## Best wishes to you all and thanks so much for your heroic efforts this semester\n", - "\n", - "\n", - "\n", - "\n", - "

Figure 1:

\n", - "" - ] - } - ], - "metadata": {}, - "nbformat": 4, - "nbformat_minor": 5 -} diff --git a/doc/src/week35/exercisesweek35.do.txt b/doc/src/week35/exercisesweek35.do.txt index 50fffd070..141784618 100644 --- a/doc/src/week35/exercisesweek35.do.txt +++ b/doc/src/week35/exercisesweek35.do.txt @@ -1,6 +1,6 @@ TITLE: Exercises week 35 -AUTHOR: August 28-September 1, 2023 -DATE: Deadline is Friday September 1 at midnight +AUTHOR: August 26-30, 2024 +DATE: Deadline is Friday August 30 at midnight ===== Exercise: Analytical exercises ===== diff --git a/doc/LectureNotes/exercisesweek35.ipynb b/doc/src/week35/exercisesweek35.ipynb similarity index 93% rename from doc/LectureNotes/exercisesweek35.ipynb rename to doc/src/week35/exercisesweek35.ipynb index 3612d41ab..2d0645240 100644 --- a/doc/LectureNotes/exercisesweek35.ipynb +++ b/doc/src/week35/exercisesweek35.ipynb @@ -2,7 +2,7 @@ "cells": [ { "cell_type": "markdown", - "id": "053b96d5", + "id": "a15180da", "metadata": { "editable": true }, @@ -14,20 +14,20 @@ }, { "cell_type": "markdown", - "id": "a09cb811", + "id": "ac77b923", "metadata": { "editable": true }, "source": [ "# Exercises week 35\n", - "**August 28-September 1, 2023**\n", + "**August 26-30, 2024**\n", "\n", - "Date: **Deadline is Friday September 1 at midnight**" + "Date: **Deadline is Friday August 30 at midnight**" ] }, { "cell_type": "markdown", - "id": "8e83839e", + "id": "e8b90270", "metadata": { "editable": true }, @@ -49,7 +49,7 @@ }, { "cell_type": "markdown", - "id": "fe2b1c49", + "id": "2e2e8f1a", "metadata": { "editable": true }, @@ -61,7 +61,7 @@ }, { "cell_type": "markdown", - "id": "259f2ad1", + "id": "1cdc68da", "metadata": { "editable": true }, @@ -71,7 +71,7 @@ }, { "cell_type": "markdown", - "id": "5ac63202", + "id": "b87f9fdd", "metadata": { "editable": true }, @@ -83,7 +83,7 @@ }, { "cell_type": "markdown", - "id": "a52c6353", + "id": "6ab53932", "metadata": { "editable": true }, @@ -93,7 +93,7 @@ }, { "cell_type": "markdown", - "id": "910282dd", + "id": "1a7a8ec2", "metadata": { "editable": true }, @@ -105,7 +105,7 @@ }, { "cell_type": "markdown", - "id": "f3d0f2f5", + "id": "3bdb1514", "metadata": { "editable": true }, @@ -120,7 +120,7 @@ }, { "cell_type": "markdown", - "id": "5fe4bc49", + "id": "3e54eca9", "metadata": { "editable": true }, @@ -132,7 +132,7 @@ }, { "cell_type": "markdown", - "id": "55fee214", + "id": "3db49a1c", "metadata": { "editable": true }, @@ -142,7 +142,7 @@ }, { "cell_type": "markdown", - "id": "92b0b614", + "id": "5d4d3a0e", "metadata": { "editable": true }, @@ -154,7 +154,7 @@ }, { "cell_type": "markdown", - "id": "6b68973e", + "id": "90eecd1c", "metadata": { "editable": true }, @@ -164,7 +164,7 @@ }, { "cell_type": "markdown", - "id": "89e679e8", + "id": "7eb7605f", "metadata": { "editable": true }, @@ -176,7 +176,7 @@ }, { "cell_type": "markdown", - "id": "a35b6ab2", + "id": "b30dd90f", "metadata": { "editable": true }, @@ -186,7 +186,7 @@ }, { "cell_type": "markdown", - "id": "747d2724", + "id": "1167ec1f", "metadata": { "editable": true }, @@ -198,7 +198,7 @@ }, { "cell_type": "markdown", - "id": "911dc89a", + "id": "8f309e9e", "metadata": { "editable": true }, @@ -216,7 +216,7 @@ { "cell_type": "code", "execution_count": 1, - "id": "09971906", + "id": "2df1063f", "metadata": { "collapsed": false, "editable": true @@ -230,7 +230,7 @@ }, { "cell_type": "markdown", - "id": "de82ebe8", + "id": "0cb75ec5", "metadata": { "editable": true }, @@ -244,7 +244,7 @@ }, { "cell_type": "markdown", - "id": "21b2c91f", + "id": "f0c36bdb", "metadata": { "editable": true }, @@ -257,7 +257,7 @@ }, { "cell_type": "markdown", - "id": "3b542aa1", + "id": "8c3ce778", "metadata": { "editable": true }, @@ -268,7 +268,7 @@ }, { "cell_type": "markdown", - "id": "5393a93f", + "id": "f861d243", "metadata": { "editable": true }, @@ -280,7 +280,7 @@ }, { "cell_type": "markdown", - "id": "df1b8e23", + "id": "51500e4b", "metadata": { "editable": true }, @@ -290,7 +290,7 @@ }, { "cell_type": "markdown", - "id": "30ad9bb6", + "id": "fda9dadd", "metadata": { "editable": true }, @@ -302,7 +302,7 @@ }, { "cell_type": "markdown", - "id": "0e2c0d15", + "id": "6b691499", "metadata": { "editable": true }, @@ -313,7 +313,7 @@ }, { "cell_type": "markdown", - "id": "80eab896", + "id": "b6f10ab9", "metadata": { "editable": true }, @@ -333,7 +333,7 @@ { "cell_type": "code", "execution_count": 2, - "id": "887378fa", + "id": "285159ae", "metadata": { "collapsed": false, "editable": true @@ -349,7 +349,7 @@ }, { "cell_type": "markdown", - "id": "a059a330", + "id": "c2840fc9", "metadata": { "editable": true }, @@ -359,7 +359,7 @@ }, { "cell_type": "markdown", - "id": "e2614fe9", + "id": "9dbda275", "metadata": { "editable": true }, @@ -370,7 +370,7 @@ }, { "cell_type": "markdown", - "id": "8522c8f4", + "id": "824dba6f", "metadata": { "editable": true }, @@ -382,7 +382,7 @@ }, { "cell_type": "markdown", - "id": "c4e99901", + "id": "a3f059cf", "metadata": { "editable": true },