From bff99c3750598cf248ce99c41fafa8cbe9f10c8c Mon Sep 17 00:00:00 2001 From: Morten Hjorth-Jensen Date: Sun, 24 Sep 2023 22:04:27 +0200 Subject: [PATCH] update --- doc/LectureNotes/week39.ipynb | 4874 +++++++++++++++++++++++++++++++++ doc/src/week39/jax.py | 5 +- 2 files changed, 4877 insertions(+), 2 deletions(-) create mode 100644 doc/LectureNotes/week39.ipynb diff --git a/doc/LectureNotes/week39.ipynb b/doc/LectureNotes/week39.ipynb new file mode 100644 index 000000000..f8ed9613e --- /dev/null +++ b/doc/LectureNotes/week39.ipynb @@ -0,0 +1,4874 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "id": "97c9bb6c", + "metadata": { + "editable": true + }, + "source": [ + "\n", + "" + ] + }, + { + "cell_type": "markdown", + "id": "ade8d870", + "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": "87cd74c3", + "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", + "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/)\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)" + ] + }, + { + "cell_type": "markdown", + "id": "529184e5", + "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": "1a65465a", + "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": "b67231b3", + "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": "3f5e03db", + "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": "e83141ae", + "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": "cef5864b", + "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": "2f59bbb1", + "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": "3869b3c6", + "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": "e4656e92", + "metadata": { + "editable": true + }, + "source": [ + "This defines what is called the Hessian matrix." + ] + }, + { + "cell_type": "markdown", + "id": "b73ae554", + "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": "70a2df05", + "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": "2e36f976", + "metadata": { + "editable": true + }, + "source": [ + "or in matrix form as" + ] + }, + { + "cell_type": "markdown", + "id": "7c4959c9", + "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": "c553379e", + "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": "145f9699", + "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": "9a68f686", + "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": "d523ab61", + "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": "8205fd3a", + "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": "98d52e46", + "metadata": { + "editable": true + }, + "source": [ + "$$\n", + "f(x)+(s-x)f'(x)\\approx 0,\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "203f65e8", + "metadata": { + "editable": true + }, + "source": [ + "yielding" + ] + }, + { + "cell_type": "markdown", + "id": "dd40195b", + "metadata": { + "editable": true + }, + "source": [ + "$$\n", + "s\\approx x-\\frac{f(x)}{f'(x)}.\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "e13a7340", + "metadata": { + "editable": true + }, + "source": [ + "Having in mind an iterative procedure, it is natural to start iterating with" + ] + }, + { + "cell_type": "markdown", + "id": "30c258c9", + "metadata": { + "editable": true + }, + "source": [ + "$$\n", + "x_{n+1}=x_n-\\frac{f(x_n)}{f'(x_n)}.\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "84f880c9", + "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": "b237f214", + "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": "b4ea1db2", + "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": "8b2b6606", + "metadata": { + "editable": true + }, + "source": [ + "which we Taylor expand to obtain" + ] + }, + { + "cell_type": "markdown", + "id": "e9d217a4", + "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": "54f87f7c", + "metadata": { + "editable": true + }, + "source": [ + "Defining the Jacobian matrix ${\\bf \\boldsymbol{J}}$ we have" + ] + }, + { + "cell_type": "markdown", + "id": "c2711fc8", + "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": "e0409f1c", + "metadata": { + "editable": true + }, + "source": [ + "we can rephrase Newton's method as" + ] + }, + { + "cell_type": "markdown", + "id": "53651890", + "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": "4e70e7ac", + "metadata": { + "editable": true + }, + "source": [ + "where we have defined" + ] + }, + { + "cell_type": "markdown", + "id": "9336db1d", + "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": "2c2ae028", + "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": "cdf99885", + "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": "11bb1b41", + "metadata": { + "editable": true + }, + "source": [ + "$$\n", + "\\mathbf{x}_{k+1} = \\mathbf{x}_k - \\gamma_k \\nabla F(\\mathbf{x}_k),\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "5d957768", + "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": "455b420a", + "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": "aacb8b05", + "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": "2bb3385b", + "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": "21326ef0", + "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": "a41b3cc6", + "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": "a01f11a5", + "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": "076a32fa", + "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": "73adde3c", + "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": "9f9ab5ff", + "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": "0b2a482b", + "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": "6566ee55", + "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": "c2e30cc1", + "metadata": { + "editable": true + }, + "source": [ + "$$\n", + "\\boldsymbol{A}\\boldsymbol{x} = \\boldsymbol{b}.\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "5012b398", + "metadata": { + "editable": true + }, + "source": [ + "In the iterative process we end up with a problem like" + ] + }, + { + "cell_type": "markdown", + "id": "ca65d9a9", + "metadata": { + "editable": true + }, + "source": [ + "$$\n", + "\\boldsymbol{r}= \\boldsymbol{b}-\\boldsymbol{A}\\boldsymbol{x},\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "ec9323dd", + "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": "5caf0f7f", + "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": "07734ce6", + "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": "468dcb52", + "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": "b63a89ae", + "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": "56a122a3", + "metadata": { + "editable": true + }, + "source": [ + "$$\n", + "\\boldsymbol{x}_0=0,\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "3256eb29", + "metadata": { + "editable": true + }, + "source": [ + "or consider the system" + ] + }, + { + "cell_type": "markdown", + "id": "b6bab858", + "metadata": { + "editable": true + }, + "source": [ + "$$\n", + "\\boldsymbol{A}\\boldsymbol{z} = \\boldsymbol{b}-\\boldsymbol{A}\\boldsymbol{x}_0,\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "7ff39e96", + "metadata": { + "editable": true + }, + "source": [ + "instead." + ] + }, + { + "cell_type": "markdown", + "id": "6678fce9", + "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": "853eb11f", + "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": "7c229917", + "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": "5c8f310a", + "metadata": { + "editable": true + }, + "source": [ + "$$\n", + "\\boldsymbol{A}\\boldsymbol{x}_0-\\boldsymbol{b},\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "f8a8c317", + "metadata": { + "editable": true + }, + "source": [ + "and \n", + "$\\boldsymbol{x}_0=0$ it is equal $-\\boldsymbol{b}$." + ] + }, + { + "cell_type": "markdown", + "id": "49b64ed0", + "metadata": { + "editable": true + }, + "source": [ + "## Final expressions\n", + "We can compute the residual iteratively as" + ] + }, + { + "cell_type": "markdown", + "id": "857ee939", + "metadata": { + "editable": true + }, + "source": [ + "$$\n", + "\\boldsymbol{r}_{k+1}=\\boldsymbol{b}-\\boldsymbol{A}\\boldsymbol{x}_{k+1},\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "7e5611fa", + "metadata": { + "editable": true + }, + "source": [ + "which equals" + ] + }, + { + "cell_type": "markdown", + "id": "384d5aa2", + "metadata": { + "editable": true + }, + "source": [ + "$$\n", + "\\boldsymbol{b}-\\boldsymbol{A}(\\boldsymbol{x}_k+\\alpha_k\\boldsymbol{r}_k),\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "0ce677be", + "metadata": { + "editable": true + }, + "source": [ + "or" + ] + }, + { + "cell_type": "markdown", + "id": "e97f9044", + "metadata": { + "editable": true + }, + "source": [ + "$$\n", + "(\\boldsymbol{b}-\\boldsymbol{A}\\boldsymbol{x}_k)-\\alpha_k\\boldsymbol{A}\\boldsymbol{r}_k,\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "d7fbeb68", + "metadata": { + "editable": true + }, + "source": [ + "which gives" + ] + }, + { + "cell_type": "markdown", + "id": "293c09b1", + "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": "af88e065", + "metadata": { + "editable": true + }, + "source": [ + "leading to the iterative scheme" + ] + }, + { + "cell_type": "markdown", + "id": "2757e302", + "metadata": { + "editable": true + }, + "source": [ + "$$\n", + "\\boldsymbol{x}_{k+1}=\\boldsymbol{x}_k+\\alpha_k\\boldsymbol{r}_{k},\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "87aab66b", + "metadata": { + "editable": true + }, + "source": [ + "## Steepest descent example" + ] + }, + { + "cell_type": "code", + "execution_count": 1, + "id": "a0e20ff7", + "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": "c01b471a", + "metadata": { + "editable": true + }, + "source": [ + "And then as countor plot" + ] + }, + { + "cell_type": "code", + "execution_count": 2, + "id": "5b835c85", + "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": "d6a3c121", + "metadata": { + "editable": true + }, + "source": [ + "Find guesses" + ] + }, + { + "cell_type": "code", + "execution_count": 3, + "id": "19e1d73c", + "metadata": { + "collapsed": false, + "editable": true + }, + "outputs": [], + "source": [ + "x = guesses[-1]\n", + "s = -df(x)" + ] + }, + { + "cell_type": "markdown", + "id": "9f7b2dfc", + "metadata": { + "editable": true + }, + "source": [ + "Run it!" + ] + }, + { + "cell_type": "code", + "execution_count": 4, + "id": "7d8247e6", + "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": "c44006da", + "metadata": { + "editable": true + }, + "source": [ + "What happened?" + ] + }, + { + "cell_type": "code", + "execution_count": 5, + "id": "bb8a0fd8", + "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": "3d3c98f0", + "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": "29e5e792", + "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": "2b0e0db3", + "metadata": { + "editable": true + }, + "source": [ + "$$\n", + "\\boldsymbol{s}^T\\boldsymbol{A}\\boldsymbol{t}= 0.\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "401dd643", + "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": "bc29d596", + "metadata": { + "editable": true + }, + "source": [ + "$$\n", + "\\boldsymbol{x}_i^T\\boldsymbol{A}\\boldsymbol{x}_j= 0.\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "c1b7adb4", + "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": "18924232", + "metadata": { + "editable": true + }, + "source": [ + "## Conjugate gradient method\n", + "An example is given by the eigenvectors of the matrix" + ] + }, + { + "cell_type": "markdown", + "id": "1764ac31", + "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": "379d5862", + "metadata": { + "editable": true + }, + "source": [ + "which is zero unless $i=j$." + ] + }, + { + "cell_type": "markdown", + "id": "9587d8bf", + "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": "4c3d0bfb", + "metadata": { + "editable": true + }, + "source": [ + "$$\n", + "\\boldsymbol{x}_{i+1}=\\boldsymbol{x}_{i}+\\alpha_i\\boldsymbol{p}_{i}.\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "4079ca1a", + "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": "e5b487a5", + "metadata": { + "editable": true + }, + "source": [ + "$$\n", + "\\boldsymbol{x} = \\sum^{n}_{i=1} \\alpha_i \\boldsymbol{p}_i.\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "b623d7f7", + "metadata": { + "editable": true + }, + "source": [ + "## Conjugate gradient method\n", + "The coefficients are given by" + ] + }, + { + "cell_type": "markdown", + "id": "8520c560", + "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": "52575016", + "metadata": { + "editable": true + }, + "source": [ + "Multiplying with $\\boldsymbol{p}_k^T$ from the left gives" + ] + }, + { + "cell_type": "markdown", + "id": "1b8a85bd", + "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": "e53b0f45", + "metadata": { + "editable": true + }, + "source": [ + "and we can define the coefficients $\\alpha_k$ as" + ] + }, + { + "cell_type": "markdown", + "id": "2238e15f", + "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": "f00e8864", + "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": "7a17895d", + "metadata": { + "editable": true + }, + "source": [ + "$$\n", + "\\boldsymbol{x}_0=0,\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "d4bafcb3", + "metadata": { + "editable": true + }, + "source": [ + "or consider the system" + ] + }, + { + "cell_type": "markdown", + "id": "78a7d2c3", + "metadata": { + "editable": true + }, + "source": [ + "$$\n", + "\\boldsymbol{A}\\boldsymbol{z} = \\boldsymbol{b}-\\boldsymbol{A}\\boldsymbol{x}_0,\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "e3192cbf", + "metadata": { + "editable": true + }, + "source": [ + "instead." + ] + }, + { + "cell_type": "markdown", + "id": "0d99ed55", + "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": "b9653ede", + "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": "78441105", + "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": "317355d2", + "metadata": { + "editable": true + }, + "source": [ + "$$\n", + "\\boldsymbol{A}\\boldsymbol{x}_0-\\boldsymbol{b},\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "9bb15157", + "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": "ac584971", + "metadata": { + "editable": true + }, + "source": [ + "## Conjugate gradient method\n", + "Let $\\boldsymbol{r}_k$ be the residual at the $k$-th step:" + ] + }, + { + "cell_type": "markdown", + "id": "911f1dfa", + "metadata": { + "editable": true + }, + "source": [ + "$$\n", + "\\boldsymbol{r}_k=\\boldsymbol{b}-\\boldsymbol{A}\\boldsymbol{x}_k.\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "d1472568", + "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": "c79708e8", + "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": "535d3e73", + "metadata": { + "editable": true + }, + "source": [ + "## Conjugate gradient method\n", + "We can also compute the residual iteratively as" + ] + }, + { + "cell_type": "markdown", + "id": "ad718f62", + "metadata": { + "editable": true + }, + "source": [ + "$$\n", + "\\boldsymbol{r}_{k+1}=\\boldsymbol{b}-\\boldsymbol{A}\\boldsymbol{x}_{k+1},\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "d0a90fa5", + "metadata": { + "editable": true + }, + "source": [ + "which equals" + ] + }, + { + "cell_type": "markdown", + "id": "860e9217", + "metadata": { + "editable": true + }, + "source": [ + "$$\n", + "\\boldsymbol{b}-\\boldsymbol{A}(\\boldsymbol{x}_k+\\alpha_k\\boldsymbol{p}_k),\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "6d8a72c8", + "metadata": { + "editable": true + }, + "source": [ + "or" + ] + }, + { + "cell_type": "markdown", + "id": "746e6fc0", + "metadata": { + "editable": true + }, + "source": [ + "$$\n", + "(\\boldsymbol{b}-\\boldsymbol{A}\\boldsymbol{x}_k)-\\alpha_k\\boldsymbol{A}\\boldsymbol{p}_k,\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "f76c0e69", + "metadata": { + "editable": true + }, + "source": [ + "which gives" + ] + }, + { + "cell_type": "markdown", + "id": "9aee35ca", + "metadata": { + "editable": true + }, + "source": [ + "$$\n", + "\\boldsymbol{r}_{k+1}=\\boldsymbol{r}_k-\\boldsymbol{A}\\boldsymbol{p}_{k},\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "ce9ce258", + "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": "f902a0f2", + "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": "36d883b2", + "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": "cde21ef1", + "metadata": { + "editable": true + }, + "source": [ + "$$\n", + "h_\\beta(x) = \\boldsymbol{y} = \\beta_0 + \\beta_1 x,\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "f2a021d3", + "metadata": { + "editable": true + }, + "source": [ + "such that" + ] + }, + { + "cell_type": "markdown", + "id": "ea0a91e4", + "metadata": { + "editable": true + }, + "source": [ + "$$\n", + "\\boldsymbol{y}_i = \\beta_0 + \\beta_1 x_i.\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "854f3ebb", + "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": "dd282d2d", + "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": "fd562029", + "metadata": { + "editable": true + }, + "source": [ + "The cost/loss/risk function is given by (" + ] + }, + { + "cell_type": "markdown", + "id": "25369bc3", + "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": "a222f3ea", + "metadata": { + "editable": true + }, + "source": [ + "and we want to find $\\beta$ such that $C(\\beta)$ is minimized." + ] + }, + { + "cell_type": "markdown", + "id": "1d5fb6f1", + "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": "eab2df73", + "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": "daee1165", + "metadata": { + "editable": true + }, + "source": [ + "where $X$ is the design matrix defined above." + ] + }, + { + "cell_type": "markdown", + "id": "f2c6f5cc", + "metadata": { + "editable": true + }, + "source": [ + "## The Hessian matrix\n", + "The Hessian matrix of $C(\\beta)$ is given by" + ] + }, + { + "cell_type": "markdown", + "id": "ecce0d08", + "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": "c4308e5f", + "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": "4ee64b17", + "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": "57e8db33", + "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": "c42e4032", + "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": "4c430cd3", + "metadata": { + "editable": true + }, + "source": [ + "## Gradient Descent Example\n", + "\n", + "Here our simple example" + ] + }, + { + "cell_type": "code", + "execution_count": 7, + "id": "9ac6096f", + "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": "df783e1d", + "metadata": { + "editable": true + }, + "source": [ + "## And a corresponding example using **scikit-learn**" + ] + }, + { + "cell_type": "code", + "execution_count": 8, + "id": "98f08f24", + "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": "50a5ab0d", + "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": "b35293d4", + "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": "fed491ee", + "metadata": { + "editable": true + }, + "source": [ + "In order to minimize $C_{\\text{ridge}}(\\beta)$ using GD we adjust the gradient as follows" + ] + }, + { + "cell_type": "markdown", + "id": "a0b4c94e", + "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": "e4f02dce", + "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": "b9f297ff", + "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": "4e1caf44", + "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": "a046daea", + "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": "02f05574", + "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": "45484749", + "metadata": { + "editable": true + }, + "source": [ + "## Program example for gradient descent with Ridge Regression" + ] + }, + { + "cell_type": "code", + "execution_count": 9, + "id": "9973cd20", + "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": "1836d4ef", + "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": "88975d3d", + "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": "56f415e0", + "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": "d3343584", + "metadata": { + "editable": true + }, + "source": [ + "## Same code but now with momentum gradient descent" + ] + }, + { + "cell_type": "code", + "execution_count": 11, + "id": "ff1e3778", + "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": "c1d70995", + "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": "930a5be8", + "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": "0a7fb7ef", + "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": "dbff87b0", + "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": "cd292df5", + "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": "1b2ffa4e", + "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": "d0abe4b0", + "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": "65c15c60", + "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": "460354c0", + "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": "c2a5dfcd", + "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": "eeeb0fe8", + "metadata": { + "editable": true + }, + "source": [ + "## The gradient step\n", + "\n", + "Thus a gradient descent step now looks like" + ] + }, + { + "cell_type": "markdown", + "id": "2b49c741", + "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": "8ba7b9be", + "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": "50da33c0", + "metadata": { + "editable": true + }, + "source": [ + "## Simple example code" + ] + }, + { + "cell_type": "code", + "execution_count": 12, + "id": "31bd6a24", + "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": "0deb8111", + "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": "16d54f02", + "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": "b300d06b", + "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": "6bc7778d", + "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": "a60fe5bd", + "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": "2192721f", + "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": "e404f2c5", + "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": "fffdbb91", + "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": "8cce7a0e", + "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": "3154c365", + "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": "a2a9ceca", + "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": "3374c700", + "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": "893d86fe", + "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": "ca2449e8", + "metadata": { + "editable": true + }, + "source": [ + "where we have defined $\\Delta \\boldsymbol{\\theta}_{t}= \\boldsymbol{\\theta}_t-\\boldsymbol{\\theta}_{t-1}$." + ] + }, + { + "cell_type": "markdown", + "id": "3cbd4adb", + "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": "e3f07cbc", + "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": "99f2ac0f", + "metadata": { + "editable": true + }, + "source": [ + "We can discretize this equation in the usual way to get" + ] + }, + { + "cell_type": "markdown", + "id": "83336244", + "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": "efd3e708", + "metadata": { + "editable": true + }, + "source": [ + "Rearranging this equation, we can rewrite this as" + ] + }, + { + "cell_type": "markdown", + "id": "6c24d65c", + "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": "853d885b", + "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": "5ab54645", + "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": "90f1503b", + "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": "d496d988", + "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": "258ca1e6", + "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": "84278058", + "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": "feaee2f4", + "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": "218edcf1", + "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": "18dbc91c", + "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": "0bfcf74a", + "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": "5fedd6f0", + "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": "b210b2a4", + "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": "34ffacbb", + "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": "cd03375d", + "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": "0db5d6e0", + "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": "84c709d9", + "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": "e4e47496", + "metadata": { + "editable": true + }, + "source": [ + "$$\n", + "\\boldsymbol{\\mathbf{m}}_t={\\mathbf{m}_t \\over 1-\\beta_1^t} \\nonumber\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "164f27df", + "metadata": { + "editable": true + }, + "source": [ + "$$\n", + "\\boldsymbol{\\mathbf{s}}_t ={\\mathbf{s}_t \\over1-\\beta_2^t} \\nonumber\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "591f4833", + "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": "e2127e8a", + "metadata": { + "editable": true + }, + "source": [ + "\n", + "
\n", + "\n", + "$$\n", + "\\begin{equation} \n", + "\\label{_auto5} \\tag{6}\n", + "\\end{equation}\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "5cef8b84", + "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": "505c8905", + "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": "ca96ddec", + "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": "fa011176", + "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": "b91c4543", + "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": "f13065e5", + "metadata": { + "editable": true + }, + "source": [ + "$$\n", + "f(x) = \\sin\\left(2\\pi x + x^2\\right)\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "22937f5e", + "metadata": { + "editable": true + }, + "source": [ + "which has the following derivative" + ] + }, + { + "cell_type": "markdown", + "id": "e1459fe1", + "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": "441a109a", + "metadata": { + "editable": true + }, + "source": [ + "Using **autograd** we have" + ] + }, + { + "cell_type": "code", + "execution_count": 15, + "id": "9043abae", + "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": "787d5d78", + "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": "6a677479", + "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": "f94a1d32", + "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": "c0eb89fd", + "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": "05d7497d", + "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": "24e3ca02", + "metadata": { + "editable": true + }, + "source": [ + "## More complicated functions using the elements of their arguments directly" + ] + }, + { + "cell_type": "code", + "execution_count": 18, + "id": "a616e696", + "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": "f695da56", + "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": "5ac073ee", + "metadata": { + "editable": true + }, + "source": [ + "## Functions using mathematical functions from Numpy" + ] + }, + { + "cell_type": "code", + "execution_count": 19, + "id": "efc8906e", + "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": "7c587e8f", + "metadata": { + "editable": true + }, + "source": [ + "## More autograd" + ] + }, + { + "cell_type": "code", + "execution_count": 20, + "id": "6428be1f", + "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": "8e1de777", + "metadata": { + "editable": true + }, + "source": [ + "## And with loops" + ] + }, + { + "cell_type": "code", + "execution_count": 21, + "id": "770ff6aa", + "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": "b924cc5d", + "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": "f0b0e1e9", + "metadata": { + "editable": true + }, + "source": [ + "## Using recursion" + ] + }, + { + "cell_type": "code", + "execution_count": 23, + "id": "1585ab28", + "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": "2718df1a", + "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": "d8fa5235", + "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": "196a52d6", + "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": "9127a2c5", + "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": "2b12ed61", + "metadata": { + "editable": true + }, + "source": [ + "## The syntax a.dot(b) when finding the dot product" + ] + }, + { + "cell_type": "code", + "execution_count": 25, + "id": "8ced55c8", + "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": "92ebdc2b", + "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": "276f763e", + "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": "7841ad0b", + "metadata": { + "editable": true + }, + "source": [ + "## Recommended to avoid\n", + "The documentation recommends to avoid inplace operations such as" + ] + }, + { + "cell_type": "code", + "execution_count": 27, + "id": "10107989", + "metadata": { + "collapsed": false, + "editable": true + }, + "outputs": [], + "source": [ + "a += b\n", + "a -= b\n", + "a*= b\n", + "a /=b" + ] + }, + { + "cell_type": "markdown", + "id": "4c1139c0", + "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": "3022af88", + "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": "04d09021", + "metadata": { + "editable": true + }, + "source": [ + "## Same code but now with momentum gradient descent" + ] + }, + { + "cell_type": "code", + "execution_count": 29, + "id": "71bf4b6d", + "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": "ad417bba", + "metadata": { + "editable": true + }, + "source": [ + "## But noen of these can compete with Newton's method" + ] + }, + { + "cell_type": "code", + "execution_count": 30, + "id": "c394bcef", + "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": "2e4cf4b5", + "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": "47411bcf", + "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": "f8e30af2", + "metadata": { + "editable": true + }, + "source": [ + "## Same code but now with momentum gradient descent" + ] + }, + { + "cell_type": "code", + "execution_count": 32, + "id": "dd594924", + "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": "75c4c29d", + "metadata": { + "editable": true + }, + "source": [ + "## Similar (second order function now) problem but now with AdaGrad" + ] + }, + { + "cell_type": "code", + "execution_count": 33, + "id": "4dd14fc5", + "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": "be4ce0cd", + "metadata": { + "editable": true + }, + "source": [ + "Running this code we note an almost perfect agreement with the results from matrix inversion." + ] + }, + { + "cell_type": "markdown", + "id": "0b739495", + "metadata": { + "editable": true + }, + "source": [ + "## RMSprop for adaptive learning rate with Stochastic Gradient Descent" + ] + }, + { + "cell_type": "code", + "execution_count": 34, + "id": "ae87789c", + "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": "76c8872b", + "metadata": { + "editable": true + }, + "source": [ + "## And finally [ADAM](https://arxiv.org/pdf/1412.6980.pdf)" + ] + }, + { + "cell_type": "code", + "execution_count": 35, + "id": "e99dbaa4", + "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": "596df570", + "metadata": { + "editable": true + }, + "source": [ + "## And Logistic Regression" + ] + }, + { + "cell_type": "code", + "execution_count": 36, + "id": "6693f042", + "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": "a40ed853", + "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": "02f88360", + "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/src/week39/jax.py b/doc/src/week39/jax.py index a5d76a774..6a4f5a48e 100644 --- a/doc/src/week39/jax.py +++ b/doc/src/week39/jax.py @@ -1,9 +1,10 @@ -import jax.numpy as jnp +import jax.nuympy as jnp from jax import grad, jit, vmap +from jax import random def sum_logistic(x): return jnp.sum(1.0 / (1.0 + jnp.exp(-x))) -x_small = jnp.arange(3.) +x_small = arange(3.) derivative_fn = grad(sum_logistic) print(derivative_fn(x_small))