{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "\n", "# Data Analysis and Machine Learning\n", "\n", " \n", "**Morten Hjorth-Jensen**, Department of Physics, University of Oslo and Department of Physics and Astronomy and National Superconducting Cyclotron Laboratory, Michigan State University\n", "\n", "Date: **Oct 16, 2018**\n", "\n", "Copyright 1999-2018, Morten Hjorth-Jensen. Released under CC Attribution-NonCommercial 4.0 license\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "# Introduction\n", "\n", "Statistics, data science and machine learning form important fields of\n", "research in modern science. They describe how to learn and make\n", "predictions from data, as well as allowing us to extract important\n", "correlations about physical process and the underlying laws of motion\n", "in large data sets. The latter, big data sets, appear frequently in\n", "essentially all disciplines, from the traditional Science, Technology,\n", "Mathematics and Engineering fields to Life Science, Law, education\n", "research, the Humanities and the Social Sciences. \n", "\n", "It has become more\n", "and more common to see research projects on big data in for example\n", "the Social Sciences where extracting patterns from complicated survey\n", "data is one of many research directions. Having a solid grasp of data\n", "analysis and machine learning is thus becoming central to scientific\n", "computing in many fields, and competences and skills within the fields\n", "of machine learning and scientific computing are nowadays strongly\n", "requested by many potential employers. The latter cannot be\n", "overstated, familiarity with machine learning has almost become a\n", "prerequisite for many of the most exciting employment opportunities,\n", "whether they are in bioinformatics, life science, physics or finance,\n", "in the private or the public sector. This author has had several\n", "students or met students who have been hired recently based on their\n", "skills and competences in scientific computing and data science, often\n", "with marginal knowledge of machine learning.\n", "\n", "Machine learning is a subfield of computer science, and is closely\n", "related to computational statistics. It evolved from the study of\n", "pattern recognition in artificial intelligence (AI) research, and has\n", "made contributions to AI tasks like computer vision, natural language\n", "processing and speech recognition. Many of the methods we will study are also \n", "strongly rooted in basic mathematics and physics research. \n", "\n", "Ideally, machine learning represents the science of giving computers\n", "the ability to learn without being explicitly programmed. The idea is\n", "that there exist generic algorithms which can be used to find patterns\n", "in a broad class of data sets without having to write code\n", "specifically for each problem. The algorithm will build its own logic\n", "based on the data. You should however always keep in mind that\n", "machines and algorithms are to a large extent developed by humans. The\n", "insights and knowledge we have about a specific system, play a central\n", "role when we develop a specific machine learning algorithm. \n", "\n", "Machine learning is an extremely rich field, in spite of its young\n", "age. The increases we have seen during the last three decades in\n", "computational capabilities have been followed by developments of\n", "methods and techniques for analyzing and handling large date sets,\n", "relying heavily on statistics, computer science and mathematics. The\n", "field is rather new and developing rapidly. Popular software packages\n", "written in Python for machine learning like\n", "[Scikit-learn](http://scikit-learn.org/stable/),\n", "[Tensorflow](https://www.tensorflow.org/),\n", "[PyTorch](http://pytorch.org/) and [Keras](https://keras.io/), all\n", "freely available at their respective GitHub sites, encompass\n", "communities of developers in the thousands or more. And the number of\n", "code developers and contributors keeps increasing. Not all the\n", "algorithms and methods can be given a rigorous mathematical\n", "justification, opening up thereby large rooms for experimenting and\n", "trial and error and thereby exciting new developments. However, a\n", "solid command of linear algebra, multivariate theory, probability\n", "theory, statistical data analysis, understanding errors and Monte\n", "Carlo methods are central elements in a proper understanding of many\n", "of algorithms and methods we will discuss.\n", "\n", "\n", "\n", "## Learning outcomes\n", "\n", "These setsof lectures aim at giving you an overview of central aspects of\n", "statistical data analysis as well as some of the central algorithms\n", "used in machine learning. We will introduce a variety of central\n", "algorithms and methods essential for studies of data analysis and\n", "machine learning. \n", "\n", "Hands-on projects and experimenting with data and algorithms plays a central role in\n", "these lectures, and our hope is, through the various\n", "projects and exercies, to expose you to fundamental\n", "research problems in these fields, with the aim to reproduce state of\n", "the art scientific results. You will learn to develop and\n", "structure large codes for studying these systems, get acquainted with\n", "computing facilities and learn to handle large scientific projects. A\n", "good scientific and ethical conduct is emphasized throughout the\n", "course. More specifically, you will\n", "\n", "1. learn about basic data analysis, Bayesian statistics, Monte Carlo methods, data optimization and machine learning;\n", "\n", "2. be capable of extending the acquired knowledge to other systems and cases;\n", "\n", "3. Have an understanding of central algorithms used in data analysis and machine learning;\n", "\n", "4. Gain knowledge of central aspects of Monte Carlo methods, Markov chains, Gibbs samplers and their possible applications, from numerical integration to simulation of stock markets;\n", "\n", "5. Understand methods for regression and classification;\n", "\n", "6. Learn about neural network, genetic algorithms and Boltzmann machines;\n", "\n", "7. Work on numerical projects to illustrate the theory. The projects play a central role and you are expected to know modern programming languages like Python or C++, in addition to a basic knowledge of linear algebra (typically taught during the first one or two years of undergraduate studies).\n", "\n", "There are several topics we will cover here, spanning from a\n", "statistical data analysis and its basic concepts such expectation\n", "values, variance, covariance, correlation functions and errors, via\n", "well-known probability distribution functions like uniform\n", "distribution, the binomial distribution, the Poisson distribution and\n", "simple and multivariate normal distributions to central elements of\n", "Bayesian statistics and modeling. We will also remind the reader about\n", "central elements from linear algebra and standard methods based on\n", "linear algebra used to fit functions such Cubic splines and gradient\n", "methods for data optimization and the Singular-value decomposition and\n", "least square methods for parameterizing data.\n", "\n", "We will also cover Monte Carlo methods, Markov chains, well-known\n", "algorithms for sampling stochastic events like the Metropolis-Hastings\n", "and Gibbs sampling methods. An important aspect of all our\n", "calculations is a proper estimation of errors. Here we will also\n", "discuss famous resampling techniques like the blocking, bootstrapping\n", "and jackknife methods.\n", "\n", "The second part of the material covers several algorithms used in\n", "machine learning.\n", "\n", "\n", "\n", "\n", "\n", "\n", "## Types of Machine Learning\n", "\n", "\n", "The approaches to machine learning are many, but are often split into\n", "two main categories. In *supervised learning* we know the answer to a\n", "problem, and let the computer deduce the logic behind it. On the other\n", "hand, *unsupervised learning* is a method for finding patterns and\n", "relationship in data sets without any prior knowledge of the system.\n", "Some authours also operate with a third category, namely\n", "*reinforcement learning*. This is a paradigm of learning inspired by\n", "behavioral psychology, where learning is achieved by trial-and-error,\n", "solely from rewards and punishment.\n", "\n", "Another way to categorize machine learning tasks is to consider the\n", "desired output of a system. Some of the most common tasks are:\n", "\n", " * Classification: Outputs are divided into two or more classes. The goal is to produce a model that assigns inputs into one of these classes. An example is to identify digits based on pictures of hand-written ones. Classification is typically supervised learning.\n", "\n", " * Regression: Finding a functional relationship between an input data set and a reference data set. The goal is to construct a function that maps input data to continuous output values.\n", "\n", " * Clustering: Data are divided into groups with certain common traits, without knowing the different groups beforehand. It is thus a form of unsupervised learning.\n", "\n", "The methods we cover have three main topics in common, irrespective of\n", "whether we deal with supervised or unsupervised learning. The first\n", "ingredient is normally our data set (which can be subdivided into\n", "training and test data), the second item is a model which is normally a\n", "function of some parameters. The model reflects our knowledge of the system (or lack thereof). As an example, if we know that our data show a behavior similar to what would be predicted by a polynomial, fitting our data to a polynomial of some degree would then determin our model. \n", "\n", "The last ingredient is a so-called **cost**\n", "function which allows us to present an estimate on how good our model\n", "is in reproducing the data it is supposed to train. \n", "\n", "Here we will build our machine learning approach on elements of the\n", "statistical foundation discussed above, with elements from data\n", "analysis, stochastic processes etc. We will discuss the following\n", "machine learning algorithms\n", "\n", "1. Linear regression and its variants, in essence polynomial regression\n", "\n", "2. Decision tree algorithms, from simpler to more complex ones\n", "\n", "3. Nearest neighbors models\n", "\n", "4. Bayesian statistics and regression\n", "\n", "5. Support vector machines and finally various variants of\n", "\n", "6. Artifical neural networks and deep learning\n", "\n", "7. Networks for unsupervised learning using for example reduced Boltzmann machines.\n", "\n", "## Choice of programming language\n", "\n", "Python plays nowadays a central role in the development of machine\n", "learning techniques and tools for data analysis. In particular, seen\n", "the wealth of machine learning and data analysis packages written in\n", "Python, easy to use libraries with immediate visualization(and not the\n", "least impressive galleries of existing example), the popularity of the\n", "Jupyter notebook framework with the possibility to run **R** codes or\n", "compiled programs written in C++, and much more made our choice of\n", "programming language for this series of lectures of easy. However,\n", "since the focus here is not only on using existing Python tools such\n", "as **scikit-learn** or **tensorflow**, but also on developing your own\n", "algorithms and codes, we will as far as possible present many of these\n", "algorithms eithers a Python codes or C++ codes. Finally, we will, as\n", "far as possible keep parallel versions of the data analysis and\n", "machine larning programming aspects in **R** as\n", "well. [R](https://www.r-project.org/) is a language and environment\n", "for statistical computing and graphics which is widely used in\n", "statistics and mathematics applications.\n", "\n", "The reason we also focus on compiled languages like C++ (or\n", "Fortran), is that Python is still notoriously slow when we do not\n", "utilize highly streamlined computational libraries like\n", "[Lapack](http://www.netlib.org/lapack/) or other numerical libraries\n", "written in compiled languages (many of these libraries are written in\n", "Fortran). Although a project like [Numba](https://numba.pydata.org/)\n", "holds great promise for speeding up the unrolling of lengthy loops, C+\n", "and Fortran are presently still the performance winners. Numba gives\n", "you potentially the power to speed up your applications with high\n", "performance functions written directly in Python. In particular,\n", "array-oriented and math-heavy Python code can achieve similar\n", "performance to C, C++ and Fortran. However, even with these speed-ups,\n", "for codes involving heavy Markov Chain Monte Carlo analyses and\n", "optimizations of cost functions, C++/C or Fortran codes tend to\n", "outperform Python codes. \n", "\n", "Presently thus, the community tends to let\n", "code written in C++/C or Fortran do the heavy duty numerical\n", "number crunching and leave the post-analysis of the data to the above\n", "mentioned Python modules or software packages. However, with the developments taking place in for example the Python community, and seen\n", "the changes during the last decade, the above situation may change swiftly in the not too distant future. \n", "\n", "Many of the examples we discuss in this series of lectures come with\n", "existing data files or provide code examples which produce the data to\n", "be analyzed. Most of the applications we will discuss deal with\n", "small data sets (less than a terabyte of information) and can easily\n", "be analyzed and tested on standard off the shelf laptops you find in general \n", "grocery stores.\n", "\n", "## Data handling, machine learning and ethical aspects\n", "\n", "In most of the cases we will study, we will either generate the data\n", "to analyze ourselves (both for supervised learning and unsupervised\n", "learning) or we will recur again and again to data present in say\n", "**scikit-learn** or **tensorflow**. Many of the examples we end up\n", "dealing with are from a privacy and data protection point of view,\n", "rather inoccuous and boring results of numerical\n", "calculations. However, this does not hinder us from developing a sound\n", "ethical attitude to the data we use, how we analyze the data and how\n", "we handle the data.\n", "\n", "The most immediate and simplest possible ethical aspects deal with our\n", "approach to the scientific process. Nowadays, with version control\n", "software like [Git](https://git-scm.com/) and various online\n", "repositories like [Github](https://github.com/),\n", "[Gitlab](https://about.gitlab.com/) etc, we can easily make our codes\n", "and data sets we have used, freely and easily accessible to a wider\n", "community. This helps us almost automagically in making our science\n", "reproducible. The large open-source development communities involved\n", "in say [Scikit-learn](http://scikit-learn.org/stable/),\n", "[Tensorflow](https://www.tensorflow.org/),\n", "[PyTorch](http://pytorch.org/) and [Keras](https://keras.io/), are\n", "all excellent examples of this. The codes can be tested and improved\n", "upon continuosly, helping thereby our scientific community at large in\n", "developing data analysis and machine learning tools. It is much\n", "easier today to gain traction and acceptance for making your science\n", "reproducible. From a societal stand, this is an important element\n", "since many of the developers are employees of large public institutions like\n", "universities and research labs. Our taxpayer do deserve to get\n", "something back for their bucks.\n", "\n", "However, this more mechanical aspect of the ethics of science (in\n", "particular the reproducibility of scientific results) is something\n", "which is obvious and everybody should do as part of the dialectics of\n", "science. The fact that many scientists are not willing to share their codes or \n", "data is detrimental to the scientific discourse.\n", "\n", "Before we proceed, we should add a disclaimer. Even though\n", "we may dream of computers developing some kind of higher learning\n", "capabilities, at the end (even if the artificial intelligence\n", "community keeps touting our ears full of fancy futuristic avenues), it is we\n", "who end up constructing and instructing, via various algorithms, the\n", "computers. Self-driving cars for example, rely on sofisticated\n", "programs which take into account all possible situations a car can\n", "encounter. In addition, extensive usage of training datas from GPS\n", "information, maps etc, are typically fed into the software for\n", "self-driving cars. Adding to this various sensors and cameras that\n", "feed information to the programs, there are zillions of ethical issues\n", "which arise from this.\n", "\n", "For self-driving cars, where basically many of the standard machine\n", "learning algorithms discussed here enter into the codes, at a certain\n", "stage we have to make choices. Yes, we , the lads and lasses who wrote\n", "a program for a specific brand of a self-driving car. As an example,\n", "a most carmakers have as their utmost priority the security of the\n", "driver and the accompanying passengers. A famous carmaker, which is\n", "one of the leaders in the market of self-driving cars, had **if**\n", "statements of the following type: suppose there are two obstacles in\n", "front of you and you cannot avoid to collide with one of them. One of\n", "the obstacles is a monstertruck while the other one is a kindergarten\n", "class trying to cross the road. The self-driving car algo would then\n", "opt for the hitting the small folks instead of the monstertruck, since\n", "the likelihood of surving a collision with our future citizens, is\n", "much higher.\n", "\n", "This brings us leads then to serious ethical aspects. Why should we\n", "opt for such an option? Who decides and who is entitled to make such\n", "choices? Keep in mind that many of the algorithms you will about in\n", "this series of lectures or hear about later, are indeed based on\n", "simple programming instructions. And you are very likely to be one of\n", "the people who may end up writing such a code. Thus, developing a\n", "sound ethical attitude to what we do, an approach well beyond the\n", "simple mechanistic one of making our science available and\n", "reproducible, is much needed. The example of the self-driving cars is\n", "just one of infinitely many cases where we have to make choices. When\n", "you analyze data on economic inequalities, who guarantees that you are\n", "not weighting some data in a particular way, perhaps because you dearly want a\n", "specific conclusion which may support your political views?\n", "\n", "We do not have the answers here, but we want you think over these\n", "topics in a more overarching way. A statistical data analysis with\n", "its dry numbers and graphs meant to guide the eye, do not necessarily\n", "reflect the truth, whatever that is. As a scientist, and after a\n", "university education, you are supposedly a better citizen, with an\n", "improved critical view and understanding of the scientific method, and\n", "perhaps some deeper understandings of the ethics of science at\n", "large. Use these insights. Be a critical citizen. You owe it to our\n", "societies.\n", "\n", "\n", "\n", "\n", "\n", "## Software\n", "\n", "Our emphasis throughout this series of lectures \n", "is on understanding the mathematical aspects of\n", "different algorithms used in the fields of data analysis and machine learning. \n", "\n", "However, where possible we will emphasize the\n", "importance of using available software. We start thus with a hands-on\n", "and top-down approach to machine learning. The aim is thus to start with\n", "relevant data or data we have produced \n", "and use these to introduce statistical data analysis\n", "concepts and machine learning algorithms before we delve into the\n", "algorithms themselves. The examples we will use in the beginning, start with simple\n", "polynomials with random noise added. We will use the Python\n", "software package [Scikit-learn](http://scikit-learn.org/stable/) and\n", "introduce various machine learning algorithms to make fits of\n", "the data and predictions. We move thereafter to more interesting\n", "cases such as the simulation of financial transactions or disease\n", "models. These are examples where we can easily set up the data and\n", "then use machine learning algorithms included in for example\n", "**scikit-learn**. \n", "\n", "These examples will serve us the purpose of getting\n", "started. Furthermore, they allow us to catch more than two birds with\n", "a stone. They will allow us to bring in some programming specific\n", "topics and tools as well as showing the power of various Python (and\n", "R) packages for machine learning and statistical data analysis. In the\n", "lectures on linear algebra we cover in more detail various programming\n", "features of languages like Python and C++ (and other), we will also\n", "look into more specific linear functions which are relevant for the\n", "various algorithms we will discuss. Here, we will mainly focus on two\n", "specific Python packages for Machine Learning, scikit-learn and\n", "tensorflow (see below for links etc). Moreover, the examples we\n", "introduce will serve as inputs to many of our discussions later, as\n", "well as allowing you to set up models and produce your own data and\n", "get started with programming.\n", "\n", "\n", "\n", "\n", "\n", "## Software and needed installations\n", "\n", "We will make extensive use of Python as programming language and its\n", "myriad of available libraries. You will find\n", "IPython/Jupyter notebooks invaluable in your work. You can run **R**\n", "codes in the Jupyter/IPython notebooks, with the immediate benefit of\n", "visualizing your data. You can also use compiled languages like C++,\n", "Rust, Fortran etc if you prefer. The focus in these lectures will be\n", "on Python, but we will provide many code examples for those of you who\n", "prefer R or compiled languages. You can integrate C++ codes and R in for example\n", "a Jupyter notebook. \n", "\n", "\n", "If you have Python installed (we recommend Python3) and you feel\n", "pretty familiar with installing different packages, we recommend that\n", "you install the following Python packages via **pip** as \n", "\n", "1. pip install numpy scipy matplotlib ipython scikit-learn mglearn sympy pandas pillow \n", "\n", "For Python3, replace **pip** with **pip3**.\n", "\n", "For OSX users we recommend, after having installed Xcode, to\n", "install **brew**. Brew allows for a seamless installation of additional\n", "software via for example \n", "\n", "1. brew install python3\n", "\n", "For Linux users, with its variety of distributions like for example the widely popular Ubuntu distribution,\n", "you can use **pip** as well and simply install Python as \n", "\n", "1. sudo apt-get install python3 (or python for pyhton2.7)\n", "\n", "etc etc. \n", "\n", "\n", "## Python installers\n", "\n", "If you don't want to perform these operations separately and venture\n", "into the hassle of exploring how to set up dependencies and paths, we\n", "recommend two widely used distrubutions which set up all relevant\n", "dependencies for Python, namely \n", "\n", "* [Anaconda](https://docs.anaconda.com/), \n", "\n", "which is an open source\n", "distribution of the Python and R programming languages for large-scale\n", "data processing, predictive analytics, and scientific computing, that\n", "aims to simplify package management and deployment. Package versions\n", "are managed by the package management system **conda**. \n", "\n", "* [Enthought canopy](https://www.enthought.com/product/canopy/) \n", "\n", "is a Python\n", "distribution for scientific and analytic computing distribution and\n", "analysis environment, available for free and under a commercial\n", "license.\n", "\n", "\n", "\n", "## Installing R, C++, cython or Julia\n", "\n", "You will also find it convenient to utilize R. Although we will mainly\n", "use Python during lectures and in various projects and exercises, we\n", "provide a full R set of codes for the same examples. Those of you\n", "already familiar with R should feel free to continue using R, keeping\n", "however an eye on the parallel Python set ups. Similarly, if you are a\n", "Python afecionado, feel free to explore R as well. Jupyter/Ipython\n", "notebook allows you to run **R** codes interactively in your\n", "browser. The software library **R** is tuned to statistically analysis\n", "and allows for an easy usage of the tools we will discuss in these\n", "texts.\n", "\n", "To install **R** with Jupyter notebook \n", "[follow the link here](https://mpacer.org/maths/r-kernel-for-ipython-notebook)\n", "\n", "\n", "\n", "\n", "## Installing R, C++, cython, Numba etc\n", "\n", "\n", "For the C++ aficionados, Jupyter/IPython notebook allows you also to\n", "install C++ and run codes written in this language interactively in\n", "the browser. Since we will emphasize writing many of the algorithms\n", "yourself, you can thus opt for either Python or C++ (or Fortran or other compiled languages) as programming\n", "languages.\n", "\n", "To add more entropy, **cython** can also be used when running your\n", "notebooks. It means that Python with the Jupyter/IPython notebook\n", "setup allows you to integrate widely popular softwares and tools for\n", "scientific computing. Similarly, the \n", "[Numba Python package](https://numba.pydata.org/) delivers increased performance\n", "capabilities with minimal rewrites of your codes. With its\n", "versatility, including symbolic operations, Python offers a unique\n", "computational environment. Your Jupyter/IPython notebook can easily be\n", "converted into a nicely rendered **PDF** file or a Latex file for\n", "further processing. For example, convert to latex as" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ " pycod jupyter nbconvert filename.ipynb --to latex \n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "And to add more versatility, the Python package [SymPy](http://www.sympy.org/en/index.html) is a Python library for symbolic mathematics. It aims to become a full-featured computer algebra system (CAS) and is entirely written in Python. \n", "\n", "Finally, if you wish to use the light mark-up language \n", "[doconce](https://github.com/hplgit/doconce) you can convert a standard ascii text file into various HTML \n", "formats, ipython notebooks, latex files, pdf files etc with minimal edits.\n", "\n", "\n", "## Simple linear regression model using **scikit-learn**\n", "\n", "We start with perhaps our simplest possible example, using **scikit-learn** to perform linear regression analysis on a data set produced by us. \n", "What follows is a simple Python code where we have defined function $y$ in terms of the variable $x$. Both are defined as vectors of dimension $1\\times 100$. The entries to the vector $\\hat{x}$ are given by random numbers generated with a uniform distribution with entries $x_i \\in [0,1]$ (more about probability distribution functions later). These values are then used to define a function $y(x)$ (tabulated again as a vector) with a linear dependence on $x$ plus a random noise added via the normal distribution.\n", "\n", "\n", "The Numpy functions are imported used the **import numpy as np**\n", "statement and the random number generator for the uniform distribution\n", "is called using the function **np.random.rand()**, where we specificy\n", "that we want $100$ random variables. Using Numpy we define\n", "automatically an array with the specified number of elements, $100$ in\n", "our case. With the Numpy function **randn()** we can compute random\n", "numbers with the normal distribution (mean value $\\mu$ equal to zero and\n", "variance $\\sigma^2$ set to one) and produce the values of $y$ assuming a linear\n", "dependence as function of $x$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "$$\n", "y = 2x+N(0,1),\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "where $N(0,1)$ represents random numbers generated by the normal\n", "distribution. From **scikit-learn** we import then the\n", "**LinearRegression** functionality and make a prediction $\\tilde{y} =\n", "\\alpha + \\beta x$ using the function **fit(x,y)**. We call the set of\n", "data $(\\hat{x},\\hat{y})$ for our training data. The Python package\n", "**scikit-learn** has also a functionality which extracts the above\n", "fitting parameters $\\alpha$ and $\\beta$ (see below). Later we will\n", "distinguish between training data and test data.\n", "\n", "For plotting we use the Python package\n", "[matplotlib](https://matplotlib.org/) which produces publication\n", "quality figures. Feel free to explore the extensive\n", "[gallery](https://matplotlib.org/gallery/index.html) of examples. In\n", "this example we plot our original values of $x$ and $y$ as well as the\n", "prediction **ypredict** ($\\tilde{y}$), which attempts at fitting our\n", "data with a straight line.\n", "\n", "The Python code follows here." ] }, { "cell_type": "code", "execution_count": 1, "metadata": { "collapsed": false }, "outputs": [], "source": [ "%matplotlib inline\n", "\n", "# Importing various packages\n", "import numpy as np\n", "import matplotlib.pyplot as plt\n", "from sklearn.linear_model import LinearRegression\n", "\n", "x = np.random.rand(100,1)\n", "y = 2*x+np.random.randn(100,1)\n", "linreg = LinearRegression()\n", "linreg.fit(x,y)\n", "xnew = np.array([[0],[1]])\n", "ypredict = linreg.predict(xnew)\n", "\n", "plt.plot(xnew, ypredict, \"r-\")\n", "plt.plot(x, y ,'ro')\n", "plt.axis([0,1.0,0, 5.0])\n", "plt.xlabel(r'$x$')\n", "plt.ylabel(r'$y$')\n", "plt.title(r'Simple Linear Regression')\n", "plt.show()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "This example serves several aims. It allows us to demonstrate several\n", "aspects of data analysis and later machine learning algorithms. The\n", "immediate visualization shows that our linear fit is not\n", "impressive. It goes through the data points, but there are many\n", "outliers which are not reproduced by our linear regression. We could\n", "now play around with this small program and change for example the\n", "factor in front of $x$ and the normal distribution. Try to change the\n", "function $y$ to" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "$$\n", "y = 10x+0.01 \\times N(0,1),\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "where $x$ is defined as before. Does the fit look better? Indeed, by\n", "reducing the role of the normal distribution we see immediately that\n", "our linear prediction seemingly reproduces better the training\n", "set. However, this testing 'by the eye' is obviouly not satisfactory in the\n", "long run. Here we have only defined the training data and our model, and \n", "have not discussed a more rigorous approach to the **cost** function.\n", "\n", "We need more rigorous criteria in defining whether we have succeeded or\n", "not in modeling our training data. You will be surprised to see that\n", "many scientists seldomly venture beyond this 'by the eye' approach. A\n", "standard approach for the *cost* function is the so-called $\\chi^2$\n", "function" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "$$\n", "\\chi^2 = \\frac{1}{n}\n", "\\sum_{i=0}^{n-1}\\frac{(y_i-\\tilde{y}_i)^2}{\\sigma_i^2},\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "where $\\sigma_i^2$ is the variance (to be defined later) of the entry\n", "$y_i$. We may not know the explicit value of $\\sigma_i^2$, it serves\n", "however the aim of scaling the equations and make the cost function\n", "dimensionless. \n", "\n", "Minimizing the cost function is a central aspect of\n", "our discussions to come. Finding its minima as function of the model\n", "parameters ($\\alpha$ and $\\beta$ in our case) will be a recurring\n", "theme in these series of lectures. Essentially all machine learning\n", "algorithms we will discuss center around the minimization of the\n", "chosen cost function. This depends in turn on our specific\n", "model for describing the data, a typical situation in supervised\n", "learning. Automatizing the search for the minima of the cost function is a\n", "central ingredient in all algorithms. Typical methods which are\n", "employed are various variants of **gradient** methods. These will be\n", "discussed in more detail later. Again, you'll be surprised to hear that\n", "many practitioners minimize the above function ''by the eye', popularly dubbed as \n", "'chi by the eye'. That is, change a parameter and see (visually and numerically) that \n", "the $\\chi^2$ function becomes smaller. \n", "\n", "There are many ways to define the cost function. A simpler approach is to look at the relative difference between the training data and the predicted data, that is we define \n", "the relative error as" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "$$\n", "\\epsilon_{\\mathrm{relative}}= \\frac{\\vert \\hat{y} -\\hat{\\tilde{y}}\\vert}{\\vert \\hat{y}\\vert}.\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "We can modify easily the above Python code and plot the relative instead" ] }, { "cell_type": "code", "execution_count": 2, "metadata": { "collapsed": false }, "outputs": [], "source": [ "import numpy as np\n", "import matplotlib.pyplot as plt\n", "from sklearn.linear_model import LinearRegression\n", "\n", "x = np.random.rand(100,1)\n", "y = 5*x+0.01*np.random.randn(100,1)\n", "linreg = LinearRegression()\n", "linreg.fit(x,y)\n", "ypredict = linreg.predict(x)\n", "\n", "plt.plot(x, np.abs(ypredict-y)/abs(y), \"ro\")\n", "plt.axis([0,1.0,0.0, 0.5])\n", "plt.xlabel(r'$x$')\n", "plt.ylabel(r'$\\epsilon_{\\mathrm{relative}}$')\n", "plt.title(r'Relative error')\n", "plt.show()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Depending on the parameter in front of the normal distribution, we may\n", "have a small or larger relative error. Try to play around with\n", "different training data sets and study (graphically) the value of the\n", "relative error.\n", "\n", "As mentioned above, **scikit-learn** has an impressive functionality.\n", "We can for example extract the values of $\\alpha$ and $\\beta$ and\n", "their error estimates, or the variance and standard deviation and many\n", "other properties from the statistical data analysis. \n", "\n", "Here we show an\n", "example of the functionality of scikit-learn." ] }, { "cell_type": "code", "execution_count": 3, "metadata": { "collapsed": false }, "outputs": [], "source": [ "import numpy as np \n", "import matplotlib.pyplot as plt \n", "from sklearn.linear_model import LinearRegression \n", "from sklearn.metrics import mean_squared_error, r2_score, mean_squared_log_error, mean_absolute_error\n", "\n", "x = np.random.rand(100,1)\n", "y = 2.0+ 5*x+0.5*np.random.randn(100,1)\n", "linreg = LinearRegression()\n", "linreg.fit(x,y)\n", "ypredict = linreg.predict(x)\n", "print('The intercept alpha: \\n', linreg.intercept_)\n", "print('Coefficient beta : \\n', linreg.coef_)\n", "# The mean squared error \n", "print(\"Mean squared error: %.2f\" % mean_squared_error(y, ypredict))\n", "# Explained variance score: 1 is perfect prediction \n", "print('Variance score: %.2f' % r2_score(y, ypredict))\n", "# Mean squared log error \n", "print('Mean squared log error: %.2f' % mean_squared_log_error(y, ypredict) )\n", "# Mean absolute error \n", "print('Mean absolute error: %.2f' % mean_absolute_error(y, ypredict))\n", "plt.plot(x, ypredict, \"r-\")\n", "plt.plot(x, y ,'ro')\n", "plt.axis([0.0,1.0,1.5, 7.0])\n", "plt.xlabel(r'$x$')\n", "plt.ylabel(r'$y$')\n", "plt.title(r'Linear Regression fit ')\n", "plt.show()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "The function **coef** gives us the parameter $\\beta$ of our fit while **intercept** yields \n", "$\\alpha$. Depending on the constant in front of the normal distribution, we get values near or far from $alpha =2$ and $\\beta =5$. Try to play around with different parameters in front of the normal distribution. The function **meansquarederror** gives us the mean square error, a risk metric corresponding to the expected value of the squared (quadratic) error or loss defined as" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "$$\n", "MSE(\\hat{y},\\hat{\\tilde{y}}) = \\frac{1}{n}\n", "\\sum_{i=0}^{n-1}(y_i-\\tilde{y}_i)^2,\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "The smaller the value, the better the fit. Ideally we would like to\n", "have an MSE equal zero. The attentive reader has probably recognized\n", "this function as being similar to the $\\chi^2$ function defined above.\n", "\n", "The **r2score** function computes $R^2$, the coefficient of\n", "determination. It provides a measure of how well future samples are\n", "likely to be predicted by the model. Best possible score is 1.0 and it\n", "can be negative (because the model can be arbitrarily worse). A\n", "constant model that always predicts the expected value of $\\hat{y}$,\n", "disregarding the input features, would get a $R^2$ score of $0.0$.\n", "\n", "If $\\tilde{\\hat{y}}_i$ is the predicted value of the $i-th$ sample and $y_i$ is the corresponding true value, then the score $R^2$ is defined as" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "$$\n", "R^2(\\hat{y}, \\tilde{\\hat{y}}) = 1 - \\frac{\\sum_{i=0}^{n - 1} (y_i - \\tilde{y}_i)^2}{\\sum_{i=0}^{n - 1} (y_i - \\bar{y})^2},\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "where we have defined the mean value of $\\hat{y}$ as" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "$$\n", "\\bar{y} = \\frac{1}{n} \\sum_{i=0}^{n - 1} y_i.\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Another quantity will meet again in our discussions of regression analysis is \n", " mean absolute error (MAE), a risk metric corresponding to the expected value of the absolute error loss or what we call the $l1$-norm loss. In our discussion above we presented the relative error.\n", "The MAE is defined as follows" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "$$\n", "\\text{MAE}(\\hat{y}, \\hat{\\tilde{y}}) = \\frac{1}{n} \\sum_{i=0}^{n-1} \\left| y_i - \\tilde{y}_i \\right|.\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Finally we present the \n", "squared logarithmic (quadratic) error" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "$$\n", "\\text{MSLE}(\\hat{y}, \\hat{\\tilde{y}}) = \\frac{1}{n} \\sum_{i=0}^{n - 1} (\\log_e (1 + y_i) - \\log_e (1 + \\tilde{y}_i) )^2,\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "where $\\log_e (x)$ stands for the natural logarithm of $x$. This error\n", "estimate is best to use when targets having exponential growth, such\n", "as population counts, average sales of a commodity over a span of\n", "years etc. \n", "\n", "We will discuss in more\n", "detail these and other functions in the various lectures. We conclude this part with another example. Instead of \n", "a linear $x$-dependence we study now a cubic polynomial and use the polynomial regression analysis tools of scikit-learn." ] }, { "cell_type": "code", "execution_count": 4, "metadata": { "collapsed": false }, "outputs": [], "source": [ "import matplotlib.pyplot as plt\n", "import numpy as np\n", "import random\n", "from sklearn.linear_model import Ridge\n", "from sklearn.preprocessing import PolynomialFeatures\n", "from sklearn.pipeline import make_pipeline\n", "from sklearn.linear_model import LinearRegression\n", "\n", "x=np.linspace(0.02,0.98,200)\n", "noise = np.asarray(random.sample((range(200)),200))\n", "y=x**3*noise\n", "yn=x**3*100\n", "poly3 = PolynomialFeatures(degree=3)\n", "X = poly3.fit_transform(x[:,np.newaxis])\n", "clf3 = LinearRegression()\n", "clf3.fit(X,y)\n", "\n", "Xplot=poly3.fit_transform(x[:,np.newaxis])\n", "poly3_plot=plt.plot(x, clf3.predict(Xplot), label='Cubic Fit')\n", "plt.plot(x,yn, color='red', label=\"True Cubic\")\n", "plt.scatter(x, y, label='Data', color='orange', s=15)\n", "plt.legend()\n", "plt.show()\n", "\n", "def error(a):\n", " for i in y:\n", " err=(y-yn)/yn\n", " return abs(np.sum(err))/len(err)\n", "\n", "print (error(y))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Similarly, using **R**, we can perform similar studies. The following **R** code illustrates this.\n", "(more details on **R** will be inserted later).\n", "\n", "## Non-Linear Least squares in R" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ " set.seed(1485)\n", " len = 24\n", " x = runif(len)\n", " y = x^3+rnorm(len, 0,0.06)\n", " ds = data.frame(x = x, y = y)\n", " str(ds)\n", " plot( y ~ x, main =\"Known cubic with noise\")\n", " s = seq(0,1,length =100)\n", " lines(s, s^3, lty =2, col =\"green\")\n", " m = nls(y ~ I(x^power), data = ds, start = list(power=1), trace = T)\n", " class(m)\n", " summary(m)\n", " power = round(summary(m)$coefficients[1], 3)\n", " power.se = round(summary(m)$coefficients[2], 3)\n", " plot(y ~ x, main = \"Fitted power model\", sub = \"Blue: fit; green: known\")\n", " s = seq(0, 1, length = 100)\n", " lines(s, s^3, lty = 2, col = \"green\")\n", " lines(s, predict(m, list(x = s)), lty = 1, col = \"blue\")\n", " text(0, 0.5, paste(\"y =x^ (\", power, \" +/- \", power.se, \")\", sep = \"\"), pos = 4)\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "In our lectures on regression analysis (and other ones as well), we will discuss in more details various **R** functionalities. \n", "\n", "\n", "Another useful Python package is\n", "[pandas](https://pandas.pydata.org/), which is an open source library\n", "providing high-performance, easy-to-use data structures and data\n", "analysis tools for Python. The following simple example shows how we can, in an easy way make tables of our data. Here we define a data set which includes names, city of residence and age, and displays the data in an easy to read way. We will see repeated use of **pandas**, in particular in connection with classification of data." ] }, { "cell_type": "code", "execution_count": 5, "metadata": { "collapsed": false }, "outputs": [], "source": [ "import pandas as pd\n", "from IPython.display import display\n", "data = {'Name': [\"John\", \"Anna\", \"Peter\", \"Linda\"], 'Location': [\"Nairobi\", \"Napoli\", \"London\", \"Buenos Aires\"], 'Age':[51, 21, 34, 45]}\n", "data_pandas = pd.DataFrame(data)\n", "display(data_pandas)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Examples\n", "\n", "We present here several examples, with pertinent Python codes that we\n", "will use to illustrate various machine learning methods and ways to\n", "analyze, from simple to complex, various data sets. Many of these\n", "examples allow us to generate the data we want to analyze, following\n", "much of the same philosophy we discussed above when\n", "fitting various polynomials.\n", "\n", "We start with a simple exponential growth model that is meant to mimick an ecoli lab experiment.\n", "We can easily model this system and then produce the data used to train various machine learning algorithms.\n", "Another model from the life sciences is the so-called predator-prey model from ecology. Thereafter we present \n", "a simple model for financial transactions before moving to a random walk model and ending with \n", "the simulation of velocities of a non-interacting atom or molecule confined to move in a one-dimensional region.\n", "\n", "\n", "### Ecoli lab experiment\n", "\n", "A typical pattern seen in population models is that the population grows faster and faster. [Why? Is there an underlying (general) mechanism](http://www.zo.utexas.edu/courses/Thoc/PopGrowth.html)?\n", "Here we will construct a model for cell growth based on a simple difference equation for the growth. We make the following assumptions\n", "\n", "1. Cells divide after $T$ seconds on average (one generation)\n", "\n", "2. $2N$ celles divide into twice as many new cells $\\Delta N$ in a time\n", " interval $\\Delta t$ as $N$ cells would: $\\Delta N \\propto N$\n", "\n", "3. $N$ cells result in twice as many new individuals $\\Delta N$ in\n", " time $2\\Delta t$ as in time $\\Delta t$: $\\Delta N \\propto\\Delta t$\n", "\n", "4. Same proportionality with respect to death \n", "\n", "5. Proposed model: $\\Delta N = b\\Delta t N - d\\Delta tN$ for some unknown\n", " constants $b$ (births) and $d$ (deaths)\n", "\n", "6. Describe evolution in discrete time: $t_n=n\\Delta t$\n", "\n", "7. Program-friendly notation: $N$ at $t_n$ is $N^n$\n", "\n", "8. Math model: $N^{n+1} = N^n + r\\Delta t\\, N$ (with $\\ r=b-d$)\n", "\n", "9. Program model: `N[n+1] = N[n] + r*dt*N[n]`\n", "\n", "The difference equation can be programmed in a simple way, and in order to get started we\n", "set $r=1.5$, $N^0=1$, $\\Delta t=0.5$. The program reads" ] }, { "cell_type": "code", "execution_count": 6, "metadata": { "collapsed": false }, "outputs": [], "source": [ "import numpy as np\n", "\n", "t = np.linspace(0, 10, 21) # 20 intervals in [0, 10]\n", "dt = t[1] - t[0]\n", "N = np.zeros(t.size)\n", "N[0] = 1\n", "r = 0.5\n", "\n", "for n in range(0, N.size-1, 1):\n", " N[n+1] = N[n] + r*dt*N[n]\n", " print('N[%d]=%.1f' % (n+1, N[n+1]))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "and it generates the following output" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ " N[1]=1.2\n", " N[2]=1.6\n", " N[3]=2.0\n", " N[4]=2.4\n", " N[5]=3.1\n", " N[6]=3.8\n", " N[7]=4.8\n", " N[8]=6.0\n", " N[9]=7.5\n", " N[10]=9.3\n", " N[11]=11.6\n", " N[12]=14.6\n", " N[13]=18.2\n", " N[14]=22.7\n", " N[15]=28.4\n", " N[16]=35.5\n", " N[17]=44.4\n", " N[18]=55.5\n", " N[19]=69.4\n", " N[20]=86.7\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "This forms our data which later will define our training set. \n", "In this case we defined the value of the parameter $r$. We could alternatively assume that we just received the \n", "above data file and where asked to find $r$. How can we estimate $r$ from data? This will be one of our tasks later.\n", "\n", "We can use the difference equation with the experimental data" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "$$\n", "N^{n+1} = N^n + r\\Delta t N^n\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Suppose now that $N^{n+1}$ and $N^n$ are known from data. Then we could solve with respect to $r$ as follows" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "$$\n", "r = \\frac{N^{n+1}-N^n}{N^n\\Delta t}\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Suppose we set $t_1=600$, $t_2=1200$,\n", "$N^1=140$ and $N^2=250$. \n", "The following code plots the data" ] }, { "cell_type": "code", "execution_count": 7, "metadata": { "collapsed": false }, "outputs": [], "source": [ "import numpy as np\n", "import matplotlib.pyplot as plt\n", "\n", "# Estimate r\n", "data = np.loadtxt('ecoli.csv', delimiter=',')\n", "t_e = data[:,0]\n", "N_e = data[:,1]\n", "i = 2 # Data point (i,i+1) used to estimate r\n", "r = (N_e[i+1] - N_e[i])/(N_e[i]*(t_e[i+1] - t_e[i]))\n", "print('Estimated r=%.5f' % r)\n", "# Can experiment with r values and see if the model can\n", "# match the data better\n", "T = 1200 # cell can divide after T sec\n", "t_max = 5*T # 5 generations in experiment\n", "t = np.linspace(0, t_max, 1000)\n", "dt = t[1] - t[0]\n", "N = np.zeros(t.size)\n", "\n", "N[0] = 100\n", "for n in range(0, len(t)-1, 1):\n", " N[n+1] = N[n] + r*dt*N[n]\n", "\n", "plt.plot(t, N, 'r-', t_e, N_e, 'bo')\n", "plt.xlabel('time [s]'); plt.ylabel('N')\n", "plt.legend(['model', 'experiment'], loc='upper left')\n", "plt.show()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "We can then change the parameter $r$ in the program and play around to make a better fit. By now we know that this\n", "'search bythe eye' approach is not the most optimal one. \n", "\n", "\n", "### Predator-Prey model from ecology\n", "\n", "The population dynamics of a simple predator-prey system is a\n", "classical example shown in many biology textbooks when ecological\n", "systems are discussed. The system contains all elements of the\n", "scientific method:\n", "\n", " * The set up of a specific hypothesis combined with\n", "\n", " * the experimental methods needed (one can study existing data or perform experiments)\n", "\n", " * analyzing and interpreting the data and performing further experiments if needed\n", "\n", " * trying to extract general behaviors and extract eventual laws or patterns\n", "\n", " * develop mathematical relations for the uncovered regularities/laws and test these by per forming new experiments\n", "\n", "Lots of data about populations of hares and lynx collected from furs in Hudson Bay, Canada, are available. It is known that the populations oscillate. Why?\n", "Here we start by\n", "\n", "1. plotting the data\n", "\n", "2. derive a simple model for the population dynamics\n", "\n", "3. (fitting parameters in the model to the data)\n", "\n", "4. using the model predict the evolution other predator-pray systems\n", "\n", "Most mammalian predators rely on a variety of prey, which complicates mathematical modeling; however, a few predators have become highly specialized and seek almost exclusively a single prey species. An example of this simplified predator-prey interaction is seen in Canadian northern forests, where the populations of the lynx and the snowshoe hare are intertwined in a life and death struggle.\n", "\n", "One reason that this particular system has been so extensively studied is that the Hudson Bay company kept careful records of all furs from the early 1800s into the 1900s. The records for the furs collected by the Hudson Bay company showed distinct oscillations (approximately 12 year periods), suggesting that these species caused almost periodic fluctuations of each other's populations. The table here shows data from 1900 to 1920.\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "
Year Hares (x1000) Lynx (x1000)
1900 30.0 4.0
1901 47.2 6.1
1902 70.2 9.8
1903 77.4 35.2
1904 36.3 59.4
1905 20.6 41.7
1906 18.1 19.0
1907 21.4 13.0
1908 22.0 8.3
1909 25.4 9.1
1910 27.1 7.4
1911 40.3 8.0
1912 57 12.3
1913 76.6 19.5
1914 52.3 45.7
1915 19.5 51.1
1916 11.2 29.7
1917 7.6 15.8
1918 14.6 9.7
1919 16.2 10.1
1920 24.7 8.6
" ] }, { "cell_type": "code", "execution_count": 8, "metadata": { "collapsed": false }, "outputs": [], "source": [ "import numpy as np\n", "from matplotlib import pyplot as plt\n", "\n", "# Load in data file\n", "data = np.loadtxt('src/Hudson_Bay.csv', delimiter=',', skiprows=1)\n", "# Make arrays containing x-axis and hares and lynx populations\n", "year = data[:,0]\n", "hares = data[:,1]\n", "lynx = data[:,2]\n", "\n", "plt.plot(year, hares ,'b-+', year, lynx, 'r-o')\n", "plt.axis([1900,1920,0, 100.0])\n", "plt.xlabel(r'Year')\n", "plt.ylabel(r'Numbers of hares and lynx ')\n", "plt.legend(('Hares','Lynx'), loc='upper right')\n", "plt.title(r'Population of hares and lynx from 1900-1920 (x1000)}')\n", "plt.savefig('Hudson_Bay_data.pdf')\n", "plt.savefig('Hudson_Bay_data.png')\n", "plt.show()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "\n", "\n", "\n", "

\n", "\n", "\n", "\n", "\n", "\n", "\n", "We see from the plot that there are indeed fluctuations.\n", "We would like to create a mathematical model that explains these\n", "population fluctuations. Ecologists have predicted that in a simple\n", "predator-prey system that a rise in prey population is followed (with\n", "a lag) by a rise in the predator population. When the predator\n", "population is sufficiently high, then the prey population begins\n", "dropping. After the prey population falls, then the predator\n", "population falls, which allows the prey population to recover and\n", "complete one cycle of this interaction. Thus, we see that\n", "qualitatively oscillations occur. Can a mathematical model predict\n", "this? What causes cycles to slow or speed up? What affects the\n", "amplitude of the oscillation or do you expect to see the oscillations\n", "damp to a stable equilibrium? The models tend to ignore factors like\n", "climate and other complicating factors. How significant are these?\n", "\n", " * We see oscillations in the data\n", "\n", " * What causes cycles to slow or speed up?\n", "\n", " * What affects the amplitude of the oscillation or do you expect to see the oscillations damp to a stable equilibrium?\n", "\n", " * With a model we can better *understand the data*\n", "\n", " * More important: Can we understand the ecology dynamics of predator-pray populations?\n", "\n", "The classical way (in all books) is to present the Lotka-Volterra equations:" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "$$\n", "\\begin{align*}\n", "\\frac{dH}{dt} &= H(a - b L)\\\\\n", "\\frac{dL}{dt} &= - L(d - c H)\n", "\\end{align*}\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Here,\n", "\n", " * $H$ is the number of preys\n", "\n", " * $L$ the number of predators\n", "\n", " * $a$, $b$, $d$, $c$ are parameters\n", "\n", "The population of hares evolves due to births and deaths exactly as a bacteria population:" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "$$\n", "\\Delta H = a \\Delta t H^n\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "However, hares have an additional loss in the population because\n", "they are eaten by lynx.\n", "All the hares and lynx can form\n", "$H\\cdot L$ pairs in total. When such pairs meet during a time\n", "interval $\\Delta t$, there is some\n", "small probablity that the lynx will eat the hare.\n", "So in fraction $b\\Delta t HL$, the lynx eat hares. This\n", "loss of hares must be accounted for. Subtracted in the equation for hares:" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "$$\n", "\\Delta H = a\\Delta t H^n - b \\Delta t H^nL^n\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "We assume that the primary growth for the lynx population depends on sufficient food for raising lynx kittens, which implies an adequate source of nutrients from predation on hares. Thus, the growth of the lynx population does not only depend of how many lynx there are, but on how many hares they can eat.\n", "In a time interval $\\Delta t HL$ hares and lynx can meet, and in a\n", "fraction $b\\Delta t HL$ the lynx eats the hare. All of this does not\n", "contribute to the growth of lynx, again just a fraction of\n", "$b\\Delta t HL$ that we write as\n", "$d\\Delta t HL$. In addition, lynx die just as in the population\n", "dynamics with one isolated animal population, leading to a loss\n", "$-c\\Delta t L$.\n", "The accounting of lynx then looks like" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "$$\n", "\\Delta L = d\\Delta t H^nL^n - c\\Delta t L^n\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "By writing up the definition of $\\Delta H$ and $\\Delta L$, and putting\n", "all assumed known terms $H^n$ and $L^n$ on the right-hand side, we have" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "$$\n", "H^{n+1} = H^n + a\\Delta t H^n - b\\Delta t H^n L^n\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "$$\n", "L^{n+1} = L^n + d\\Delta t H^nL^n - c\\Delta t L^n\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Note:\n", "\n", " * These equations are ready to be implemented!\n", "\n", " * But to start, we need $H^0$ and $L^0$ (which we can get from the data)\n", "\n", " * We also need values for $a$, $b$, $d$, $c$\n", "\n", " * As always, models tend to be general - as here, applicable\n", " to \"all\" predator-pray systems\n", "\n", " * The critical issue is whether the *interaction* between hares and lynx\n", " is sufficiently well modeled by $\\hbox{const}HL$\n", "\n", " * The parameters $a$, $b$, $d$, and $c$ must be\n", " estimated from data" ] }, { "cell_type": "code", "execution_count": 9, "metadata": { "collapsed": false }, "outputs": [], "source": [ "import numpy as np\n", "import matplotlib.pyplot as plt\n", "\n", "def solver(m, H0, L0, dt, a, b, c, d, t0):\n", " \"\"\"Solve the difference equations for H and L over m years\n", " with time step dt (measured in years.\"\"\"\n", "\n", " num_intervals = int(m/float(dt))\n", " t = np.linspace(t0, t0 + m, num_intervals+1)\n", " H = np.zeros(t.size)\n", " L = np.zeros(t.size)\n", "\n", " print('Init:', H0, L0, dt)\n", " H[0] = H0\n", " L[0] = L0\n", "\n", " for n in range(0, len(t)-1):\n", " H[n+1] = H[n] + a*dt*H[n] - b*dt*H[n]*L[n]\n", " L[n+1] = L[n] + d*dt*H[n]*L[n] - c*dt*L[n]\n", " return H, L, t\n", "\n", "# Load in data file\n", "data = np.loadtxt('src/Hudson_Bay.csv', delimiter=',', skiprows=1)\n", "# Make arrays containing x-axis and hares and lynx populations\n", "t_e = data[:,0]\n", "H_e = data[:,1]\n", "L_e = data[:,2]\n", "\n", "# Simulate using the model\n", "H, L, t = solver(m=20, H0=34.91, L0=3.857, dt=0.1,\n", " a=0.4807, b=0.02482, c=0.9272, d=0.02756,\n", " t0=1900)\n", "\n", "# Visualize simulations and data\n", "plt.plot(t_e, H_e, 'b-+', t_e, L_e, 'r-o', t, H, 'm--', t, L, 'k--')\n", "plt.xlabel('Year')\n", "plt.ylabel('Numbers of hares and lynx')\n", "plt.axis([1900, 1920, 0, 140])\n", "plt.title(r'Population of hares and lynx 1900-1920 (x1000)')\n", "plt.legend(('H_e', 'L_e', 'H', 'L'), loc='upper left')\n", "plt.savefig('Hudson_Bay_sim.pdf')\n", "plt.savefig('Hudson_Bay_sim.png')\n", "plt.show()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "\n", "\n", "\n", "

\n", "\n", "\n", "\n", "\n", "\n", "We will later perform a least-square fitting. Then we can find optimal\n", "values for the parameters $a$, $b$, $d$, $c$. In our calculations here\n", "we set $a=0.4807$, $b=0.02482$, $d=0.9272$ and $c=0.02756$. These\n", "parameters result in a slightly modified initial conditions, namely\n", "$H(0) = 34.91$ and $L(0)=3.857$. \n", "\n", "\n", "The following Python code demonstrates how we can use linear regression to fit for example the population of lynx.\n", "Similarly, we have also used a decision tree algorithm to fit the lynx population data. As expected, the linear regression is not exactly impressive" ] }, { "cell_type": "code", "execution_count": 10, "metadata": { "collapsed": false }, "outputs": [], "source": [ "import numpy as np\n", "import matplotlib.pyplot as plt\n", "from IPython.display import display\n", "import sklearn\n", "from sklearn.linear_model import LinearRegression\n", "from sklearn.tree import DecisionTreeRegressor\n", "\n", "\n", "data = np.loadtxt('src/Hudson_Bay.csv', delimiter=',', skiprows=1)\n", "x = data[:,0]\n", "y = data[:,1]\n", "line = np.linspace(1900,1920,1000,endpoint=False).reshape(-1,1)\n", "reg = DecisionTreeRegressor(min_samples_split=3).fit(x.reshape(-1,1),y.reshape(-1,1))\n", "plt.plot(line, reg.predict(line), label=\"decision tree\")\n", "regline = LinearRegression().fit(x.reshape(-1,1),y.reshape(-1,1))\n", "plt.plot(line, regline.predict(line), label= \"Linear Regression\")\n", "plt.plot(x, y, label= \"Linear Regression\")\n", "plt.show()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "The similar code for linear regression in **R** reads (more details to come)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ " HudsonBay = read.csv(\"src/Hudson_Bay.csv\",header=T)\n", " fix(HudsonBay)\n", " dim(HudsonBay)\n", " names(HudsonBay)\n", " plot(HudsonBay$Year, HudsonBay$Hares..x1000.)\n", " attach(HudsonBay)\n", " plot(Year, Hares..x1000.)\n", " plot(Year, Hares..x1000., col=\"red\", varwidth=T, xlab=\"Years\", ylab=\"Haresx 1000\")\n", " summary(HudsonBay)\n", " summary(Hares..x1000.)\n", " library(MASS)\n", " library(ISLR)\n", " scatter.smooth(x=Year, y = Hares..x1000.)\n", " linearMod = lm(Hares..x1000. ~ Year)\n", " print(linearMod)\n", " summary(linearMod)\n", " plot(linearMod)\n", " confint(linearMod)\n", " predict(linearMod,data.frame(Year=c(1910,1914,1920)),interval=\"confidence\")\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Simulating financial transactions\n", "\n", "The aim here is to simulate financial transactions among financial agents\n", "using Monte Carlo methods. The final goal is to extract a distribution of income as function\n", "of the income $m$. From Pareto's work ([V. Pareto, 1897](http://www.institutcoppet.org/2012/05/08/cours-deconomie-politique-1896-de-vilfredo-pareto)) it is known from empirical studies\n", "that the higher end of the distribution of money follows a distribution" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "$$\n", "w_m\\propto m^{-1-\\alpha},\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "with $\\alpha\\in [1,2]$. We will here follow the analysis made by [Patriarca and collaborators](http://www.sciencedirect.com/science/article/pii/S0378437104004327). \n", "\n", "Here we will study numerically the relation between the micro-dynamic relations among financial \n", "agents and the resulting macroscopic money distribution.\n", "\n", "We assume we have $N$ agents that exchange money in pairs $(i,j)$. We assume also that all agents\n", "start with the same amount of money $m_0 > 0$. At a given 'time step', we choose randomly a pair\n", "of agents $(i,j)$ and let a transaction take place. This means that agent $i$'s money $m_i$ changes\n", "to $m_i'$ and similarly we have $m_j\\rightarrow m_j'$. \n", "Money is conserved during a transaction, meaning that" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "\n", "
\n", "\n", "$$\n", "\\begin{equation}\n", " m_i+m_j=m_i'+m_j'.\n", "\\label{eq:conserve} \\tag{1}\n", "\\end{equation}\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "The change is done via a random reassignement (a random number) $\\epsilon$, meaning that" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "$$\n", "m_i' = \\epsilon(m_i+m_j),\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "leading to" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "$$\n", "m_j'= (1-\\epsilon)(m_i+m_j).\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "The number $\\epsilon$ is extracted from a uniform distribution.\n", "In this simple model, no agents are left with a debt, that is $m\\ge 0$.\n", "Due to the conservation law above, one can show that the system relaxes toward an equilibrium\n", "state given by a Gibbs distribution" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "$$\n", "w_m=\\beta \\exp{(-\\beta m)},\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "with" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "$$\n", "\\beta = \\frac{1}{\\langle m\\rangle},\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "and $\\langle m\\rangle=\\sum_i m_i/N=m_0$, the average money.\n", "It means that after equilibrium has been reached that the majority of agents is left with a small\n", "number of money, while the number of richest agents, those with $m$ larger than a specific value $m'$,\n", "exponentially decreases with $m'$.\n", "\n", "We assume that we have $N=500$ agents. In each simulation, we need a sufficiently large number of transactions, say $10^7$. Our aim is find the final equilibrium distribution $w_m$. In order to do that we would need\n", "several runs of the above simulations, at least $10^3-10^4$ runs (experiments).\n", "\n", "Our task is to first set up an algorithm which simulates the above transactions with an initial\n", " amount $m_0$.\n", " The challenge here is to figure out a Monte Carlo simulation based on the\n", " above equations.\n", " You will in particular need to make an algorithm which sets up a histogram as function of $m$.\n", " This histogram contains the number of times a value $m$ is registered and represents\n", " $w_m\\Delta m$. You will need to set up a value for the interval $\\Delta m$ (typically $0.01-0.05$).\n", " That means you need to account for the number of times you register an income in the interval\n", " $m,m+\\Delta m$. The number of times you register this income, represents the value that enters the histogram." ] }, { "cell_type": "code", "execution_count": 11, "metadata": { "collapsed": false }, "outputs": [], "source": [ "#!/usr/bin/env python\n", "import numpy as np\n", "import matplotlib.mlab as mlab\n", "import matplotlib.pyplot as plt\n", "import random\n", "\n", "# initialize the rng with a seed\n", "random.seed()\n", "# Hard coding of input parameters\n", "Agents = 500\n", "MCcounts = 1000\n", "Transactions = 100000\n", "startMoney = 1.0\n", "Lambda = 0.0\n", "FinancialAgents = startMoney*np.ones(Agents)\n", "for i in range (1, MCcounts, 1):\n", " for j in range (1, Transactions, 1):\n", " agent_i = int(Agents*random.random())\n", " agent_j = int(Agents*random.random())\n", " epsilon = random.random()\n", " if agent_i != agent_j:\n", " m1 = Lambda*FinancialAgents[agent_i] + (1-Lambda)*epsilon*(FinancialAgents[agent_i] + FinancialAgents[agent_j])\n", " m2 = Lambda*FinancialAgents[agent_j] + (1-Lambda)*(1-epsilon)*(FinancialAgents[agent_i] + FinancialAgents[agent_j])\n", " FinancialAgents[agent_i] = m1\n", " FinancialAgents[agent_j] = m2\n", "\n", "# the histogram of the data\n", "n, bins, patches = plt.hist(FinancialAgents, 50, facecolor='green')\n", "\n", "plt.xlabel('$x$')\n", "plt.ylabel('Distribution of wealth')\n", "plt.title(r'Money')\n", "plt.axis([0, 10, 0, 500])\n", "plt.grid(True)\n", "plt.show()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "We can then change our model to allow for a saving criterion, meaning that the agents save\n", " a fraction $\\lambda$ of the money they have before the transaction is made. The final distribution will then no longer be given by Gibbs distribution. It could also include a taxation on financial transactions.\n", "\n", " The conservation law of Eq. ([eq:conserve](#eq:conserve)) holds, but the money to be shared in a transaction between\n", " agent $i$ and agent $j$ is now $(1-\\lambda)(m_i+m_j)$. This means that we have" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "$$\n", "m_i' = \\lambda m_i+\\epsilon(1-\\lambda)(m_i+m_j),\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "and" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "$$\n", "m_j' = \\lambda m_j+(1-\\epsilon)(1-\\lambda)(m_i+m_j),\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "which can be written as" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "$$\n", "m_i'=m_i+\\delta m\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "and" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "$$\n", "m_j'=m_j-\\delta m,\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "with" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "$$\n", "\\delta m=(1-\\lambda)(\\epsilon m_j-(1-\\epsilon)m_i),\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "showing how money is conserved during a transaction.\n", " Select values of $\\lambda =0.25,0.5$ and $\\lambda=0.9$ and try to extract the corresponding\n", " equilibrium distributions and compare these with the Gibbs distribution. We will use this model to \n", "extract a parametrization of the above curves, see for example [Patriarca and collaborators](http://www.sciencedirect.com/science/article/pii/S0378437104004327).\n", "\n", "\n", "### Particle in one dimension and velocity distribution" ] }, { "cell_type": "code", "execution_count": 12, "metadata": { "collapsed": false }, "outputs": [], "source": [ "# Program to test the Metropolis algorithm with one particle at given temp in one dimension\n", "import numpy as np\n", "import matplotlib.mlab as mlab\n", "import matplotlib.pyplot as plt\n", "import random\n", "from math import sqrt, exp, log\n", "# initialize the rng with a seed\n", "random.seed()\n", "# Hard coding of input parameters\n", "MCcycles = 100000\n", "Temperature = 2.0\n", "beta = 1./Temperature\n", "InitialVelocity = -2.0\n", "CurrentVelocity = InitialVelocity\n", "Energy = 0.5*InitialVelocity*InitialVelocity\n", "VelocityRange = 10*sqrt(Temperature)\n", "VelocityStep = 2*VelocityRange/10.\n", "AverageEnergy = Energy\n", "AverageEnergy2 = Energy*Energy\n", "VelocityValues = np.zeros(MCcycles)\n", "# The Monte Carlo sampling with Metropolis starts here\n", "for i in range (1, MCcycles, 1):\n", " TrialVelocity = CurrentVelocity + (2.0*random.random() - 1.0)*VelocityStep\n", " EnergyChange = 0.5*(TrialVelocity*TrialVelocity -CurrentVelocity*CurrentVelocity);\n", " if random.random() <= exp(-beta*EnergyChange):\n", " CurrentVelocity = TrialVelocity\n", " Energy += EnergyChange\n", " VelocityValues[i] = CurrentVelocity\n", " AverageEnergy += Energy\n", " AverageEnergy2 += Energy*Energy\n", "#Final averages\n", "AverageEnergy = AverageEnergy/MCcycles\n", "AverageEnergy2 = AverageEnergy2/MCcycles\n", "Variance = AverageEnergy2 - AverageEnergy*AverageEnergy\n", "print(AverageEnergy, Variance)\n", "n, bins, patches = plt.hist(VelocityValues, 400, facecolor='green')\n", "\n", "plt.xlabel('$v$')\n", "plt.ylabel('Velocity distribution P(v)')\n", "plt.title(r'Velocity histogram at $k_BT=2$')\n", "plt.axis([-5, 5, 0, 600])\n", "plt.grid(True)\n", "plt.show()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Random walk model" ] }, { "cell_type": "code", "execution_count": 13, "metadata": { "collapsed": false }, "outputs": [], "source": [ "import numpy as np\n", "import matplotlib.pyplot as plt\n", "from sklearn.preprocessing import PolynomialFeatures\n", "from sklearn.linear_model import LinearRegression\n", "\n", "steps=250\n", "\n", "distance=0\n", "x=0\n", "distance_list=[]\n", "steps_list=[]\n", "while x\n", "## Important Matrix and vector handling packages\n", "\n", "There are several central software packages for linear algebra and eigenvalue problems. Several of the more\n", "popular ones have been wrapped into ofter software packages like those from the widely used text **Numerical Recipes**. The original source codes in many of the available packages are often taken from the widely used\n", "software package LAPACK, which follows two other popular packages\n", "developed in the 1970s, namely EISPACK and LINPACK. We describe them shortly here.\n", "\n", " * LINPACK: package for linear equations and least square problems.\n", "\n", " * LAPACK:package for solving symmetric, unsymmetric and generalized eigenvalue problems. From LAPACK's website it is possible to download for free all source codes from this library. Both C/C++ and Fortran versions are available.\n", "\n", " * BLAS (I, II and III): (Basic Linear Algebra Subprograms) are routines that provide standard building blocks for performing basic vector and matrix operations. Blas I is vector operations, II vector-matrix operations and III matrix-matrix operations. Highly parallelized and efficient codes, all available for download from .\n", "\n", "When dealing with matrices and vectors a central issue is memory\n", "handling and allocation. If our code is written in Python the way we\n", "declare these objects and the way they are handled, interpreted and\n", "used by say a linear algebra library, requires codes that interface\n", "our Python program with such libraries. For Python programmers,\n", "**Numpy** is by now the standard Python package for numerical arrays in\n", "Python as well as the source of functions which act on these\n", "arrays. These functions span from eigenvalue solvers to functions that\n", "compute the mean value, variance or the covariance matrix. If you are\n", "not familiar with how arrays are handled in say Python or compiled\n", "languages like C++ and Fortran, the sections in this chapter may be\n", "useful. For C++ programmer, **Armadillo** is widely used library for\n", "linear algebra and eigenvalue problems. In addition it offers a\n", "convenient way to handle and organize arrays. We discuss this library\n", "as well. Before we proceed we believe it may be convenient to repeat some basic features of \n", " matrices and vectors.\n", "\n", "\n", "## Basic Matrix Features\n", "\n", " Matrix properties reminder" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "$$\n", "\\mathbf{A} =\n", " \\begin{bmatrix} a_{11} & a_{12} & a_{13} & a_{14} \\\\\n", " a_{21} & a_{22} & a_{23} & a_{24} \\\\\n", " a_{31} & a_{32} & a_{33} & a_{34} \\\\\n", " a_{41} & a_{42} & a_{43} & a_{44}\n", " \\end{bmatrix}\\qquad\n", "\\mathbf{I} =\n", " \\begin{bmatrix} 1 & 0 & 0 & 0 \\\\\n", " 0 & 1 & 0 & 0 \\\\\n", " 0 & 0 & 1 & 0 \\\\\n", " 0 & 0 & 0 & 1\n", " \\end{bmatrix}\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Basic Matrix Features\n", "\n", "\n", "The inverse of a matrix is defined by" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "$$\n", "\\mathbf{A}^{-1} \\cdot \\mathbf{A} = I\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Basic Matrix Features\n", "\n", " Matrix Properties Reminder\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "
Relations Name matrix elements
$A = A^{T}$ symmetric $a_{ij} = a_{ji}$
$A = \\left (A^{T} \\right )^{-1}$ real orthogonal $\\sum_k a_{ik} a_{jk} = \\sum_k a_{ki} a_{kj} = \\delta_{ij}$
$A = A^{ * }$ real matrix $a_{ij} = a_{ij}^{ * }$
$A = A^{\\dagger}$ hermitian $a_{ij} = a_{ji}^{ * }$
$A = \\left (A^{\\dagger} \\right )^{-1}$ unitary $\\sum_k a_{ik} a_{jk}^{ * } = \\sum_k a_{ki}^{ * } a_{kj} = \\delta_{ij}$
\n", "\n", "\n", "## Some famous Matrices\n", "\n", " * Diagonal if $a_{ij}=0$ for $i\\ne j$\n", "\n", " * Upper triangular if $a_{ij}=0$ for $i > j$\n", "\n", " * Lower triangular if $a_{ij}=0$ for $i < j$\n", "\n", " * Upper Hessenberg if $a_{ij}=0$ for $i > j+1$\n", "\n", " * Lower Hessenberg if $a_{ij}=0$ for $i < j+1$\n", "\n", " * Tridiagonal if $a_{ij}=0$ for $|i -j| > 1$\n", "\n", " * Lower banded with bandwidth $p$: $a_{ij}=0$ for $i > j+p$\n", "\n", " * Upper banded with bandwidth $p$: $a_{ij}=0$ for $i < j+p$\n", "\n", " * Banded, block upper triangular, block lower triangular....\n", "\n", "## Basic Matrix Features\n", "\n", " Some Equivalent Statements\n", "For an $N\\times N$ matrix $\\mathbf{A}$ the following properties are all equivalent\n", "\n", " * If the inverse of $\\mathbf{A}$ exists, $\\mathbf{A}$ is nonsingular.\n", "\n", " * The equation $\\mathbf{Ax}=0$ implies $\\mathbf{x}=0$.\n", "\n", " * The rows of $\\mathbf{A}$ form a basis of $R^N$.\n", "\n", " * The columns of $\\mathbf{A}$ form a basis of $R^N$.\n", "\n", " * $\\mathbf{A}$ is a product of elementary matrices.\n", "\n", " * $0$ is not eigenvalue of $\\mathbf{A}$.\n", "\n", "## Numpy and arrays\n", "[Numpy](http://www.numpy.org/) provides an easy way to handle arrays in Python. The standard way to import this library is as" ] }, { "cell_type": "code", "execution_count": 14, "metadata": { "collapsed": false }, "outputs": [], "source": [ "import numpy as np\n", "n = 10\n", "x = np.random.normal(size=n)\n", "print(x)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Here we have defined a vector $x$ with $n=10$ elements with its values given by the Normal distribution $N(0,1)$.\n", "Another alternative is to declare a vector as follows" ] }, { "cell_type": "code", "execution_count": 15, "metadata": { "collapsed": false }, "outputs": [], "source": [ "import numpy as np\n", "x = np.array([1, 2, 3])\n", "print(x)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Here we have defined a vector with three elements, with $x_0=1$, $x_1=2$ and $x_2=3$. Note that both Python and C++\n", "start numbering array elements from $0$ and on. This means that a vector with $n$ elements has a sequence of entities $x_0, x_1, x_2, \\dots, x_{n-1}$. We could also let (recommended) Numpy to compute the logarithms of a specific array as" ] }, { "cell_type": "code", "execution_count": 16, "metadata": { "collapsed": false }, "outputs": [], "source": [ "import numpy as np\n", "x = np.log(np.array([4, 7, 8]))\n", "print(x)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Here we have used Numpy's unary function $np.log$. This function is\n", "highly tuned to compute array elements since the code is vectorized\n", "and does not require looping. We normaly recommend that you use the\n", "Numpy intrinsic functions instead of the corresponding **log** function\n", "from Python's **math** module. The looping is done explicitely by the\n", "**np.log** function. The alternative, and slower way to compute the\n", "logarithms of a vector would be to write" ] }, { "cell_type": "code", "execution_count": 17, "metadata": { "collapsed": false }, "outputs": [], "source": [ "import numpy as np\n", "from math import log\n", "x = np.array([4, 7, 8])\n", "for i in range(0, len(x)):\n", " x[i] = log(x[i])\n", "print(x)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "We note that our code is much longer already and we need to import the **log** function from the **math** module. \n", "The attentive reader will also notice that the output is $[1, 1, 2]$. Python interprets automacally our numbers as integers (like the **automatic** keyword in C++). To change this we could define our array elements to be double precision numbers as" ] }, { "cell_type": "code", "execution_count": 18, "metadata": { "collapsed": false }, "outputs": [], "source": [ "import numpy as np\n", "x = np.log(np.array([4, 7, 8], dtype = np.float64))\n", "print(x)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "or simply write them as double precision numbers (Python uses 64 bits as default for floating point type variables), that is" ] }, { "cell_type": "code", "execution_count": 19, "metadata": { "collapsed": false }, "outputs": [], "source": [ "import numpy as np\n", "x = np.log(np.array([4.0, 7.0, 8.0])\n", "print(x)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "To check the number of bytes (remember that one byte contains eight bits for double precision variables), you can use simple use the **itemsize** functionality (the array $x$ is actually an object which inherits the functionalities defined in Numpy) as" ] }, { "cell_type": "code", "execution_count": 20, "metadata": { "collapsed": false }, "outputs": [], "source": [ "import numpy as np\n", "x = np.log(np.array([4.0, 7.0, 8.0])\n", "print(x.itemsize)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Matrices in Python\n", "Having defined vectors, we are now ready to try out matrices. We can define a $3 \\times 3 $ real matrix $\\hat{A}$\n", "as (recall that we user lowercase letters for vectors and uppercase letters for matrices)" ] }, { "cell_type": "code", "execution_count": 21, "metadata": { "collapsed": false }, "outputs": [], "source": [ "import numpy as np\n", "A = np.log(np.array([ [4.0, 7.0, 8.0], [3.0, 10.0, 11.0], [4.0, 5.0, 7.0] ]))\n", "print(A)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "If we use the **shape** function we would get $(3, 3)$ as output, that is verifying that our matrix is a $3\\times 3$ matrix. We can slice the matrix and print for example the first column (Python organized matrix elements in a row-major order, see below) as" ] }, { "cell_type": "code", "execution_count": 22, "metadata": { "collapsed": false }, "outputs": [], "source": [ "import numpy as np\n", "A = np.log(np.array([ [4.0, 7.0, 8.0], [3.0, 10.0, 11.0], [4.0, 5.0, 7.0] ]))\n", "# print the first column, row-major order and elements start with 0\n", "print(A[:,0])" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "We can continue this was by printing out other columns or rows. The example here prints out the second column" ] }, { "cell_type": "code", "execution_count": 23, "metadata": { "collapsed": false }, "outputs": [], "source": [ "import numpy as np\n", "A = np.log(np.array([ [4.0, 7.0, 8.0], [3.0, 10.0, 11.0], [4.0, 5.0, 7.0] ]))\n", "# print the first column, row-major order and elements start with 0\n", "print(A[1,:])" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Numpy contains many other functionalities that allow us to slice, subdivide etc etc arrays. We strongly recommend that you look up the [Numpy website for more details](http://www.numpy.org/). Useful functions when defining a matrix are the **np.zeros** function which declares a matrix of a given dimension and sets all elements to zero" ] }, { "cell_type": "code", "execution_count": 24, "metadata": { "collapsed": false }, "outputs": [], "source": [ "import numpy as np\n", "n = 10\n", "# define a matrix of dimension 10 x 10 and set all elements to zero\n", "A = np.zeros( (n, n) )\n", "print(A)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "or initializing all elements to" ] }, { "cell_type": "code", "execution_count": 25, "metadata": { "collapsed": false }, "outputs": [], "source": [ "import numpy as np\n", "n = 10\n", "# define a matrix of dimension 10 x 10 and set all elements to one\n", "A = np.ones( (n, n) )\n", "print(A)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "or as unitarily distributed random numbers (see the material on random number generators in the statistics part)" ] }, { "cell_type": "code", "execution_count": 26, "metadata": { "collapsed": false }, "outputs": [], "source": [ "import numpy as np\n", "n = 10\n", "# define a matrix of dimension 10 x 10 and set all elements to random numbers with x \\in [0, 1]\n", "A = np.random.rand(n, n)\n", "print(A)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "As we will see throughout these lectures, there are several extremely useful functionalities in Numpy.\n", "As an example, consider the discussion of the covariance matrix. Suppose we have defined three vectors\n", "$\\hat{x}, \\hat{y}, \\hat{z}$ with $n$ elements each. The covariance matrix is defined as" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "$$\n", "\\hat{\\Sigma} = \\begin{bmatrix} \\sigma_{xx} & \\sigma_{xy} & \\sigma_{xz} \\\\\n", " \\sigma_{yx} & \\sigma_{yy} & \\sigma_{yz} \\\\\n", " \\sigma_{zx} & \\sigma_{zy} & \\sigma_{zz} \n", " \\end{bmatrix},\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "where for example" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "$$\n", "\\sigma_{xy} =\\frac{1}{n} \\sum_{i=0}^{n-1}(x_i- \\overline{x})(y_i- \\overline{y}).\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "The Numpy function **np.cov** calculates the covariance elements using the factor $1/(n-1)$ instead of $1/n$ since it assumes we do not have the exact mean values. For a more in-depth discussion of the covariance and covariance matrix and its meaning, we refer you to the lectures on statistics. \n", "The following simple function uses the **np.vstack** function which takes each vector of dimension $1\\times n$ and produces a $ 3\\times n$ matrix $\\hat{W}$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "$$\n", "\\hat{W} = \\begin{bmatrix} x_0 & y_0 & z_0 \\\\\n", " x_1 & y_1 & z_1 \\\\\n", " x_2 & y_2 & z_2 \\\\\n", " \\dots & \\dots & \\dots \\\\\n", " x_{n-2} & y_{n-2} & z_{n-2} \\\\\n", " x_{n-1} & y_{n-1} & z_{n-1}\n", " \\end{bmatrix},\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "which in turn is converted into into the $3 times 3$ covariance matrix\n", "$\\hat{\\Sigma}$ via the Numpy function **np.cov()**. In our review of\n", "statistical functions and quantities we will discuss more about the\n", "meaning of the covariance matrix. Here we note that we can calculate\n", "the mean value of each set of samples $\\hat{x}$ etc using the Numpy\n", "function **np.mean(x)**. We can also extract the eigenvalues of the\n", "covariance matrix through the **np.linalg.eig()** function." ] }, { "cell_type": "code", "execution_count": 27, "metadata": { "collapsed": false }, "outputs": [], "source": [ "# Importing various packages\n", "import numpy as np\n", "\n", "n = 100\n", "x = np.random.normal(size=n)\n", "print(np.mean(x))\n", "y = 4+3*x+np.random.normal(size=n)\n", "print(np.mean(y))\n", "z = x**3+np.random.normal(size=n)\n", "print(np.mean(z))\n", "W = np.vstack((x, y, z))\n", "Sigma = np.cov(W)\n", "print(Sigma)\n", "Eigvals, Eigvecs = np.linalg.eig(Sigma)\n", "print(Eigvals)" ] }, { "cell_type": "code", "execution_count": 28, "metadata": { "collapsed": false }, "outputs": [], "source": [ "import numpy as np\n", "import matplotlib.pyplot as plt\n", "from scipy import sparse\n", "eye = np.eye(4)\n", "print(eye)\n", "sparse_mtx = sparse.csr_matrix(eye)\n", "print(sparse_mtx)\n", "x = np.linspace(-10,10,100)\n", "y = np.sin(x)\n", "plt.plot(x,y,marker='x')\n", "plt.show()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Matrix Handling in C/C++, Static and Dynamical allocation\n", "\n", " Static\n", "We have an $N\\times N$ matrix A with $N=100$\n", "In C/C++ this would be defined as" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ " int N = 100;\n", " double A[100][100];\n", " // initialize all elements to zero\n", " for(i=0 ; i < N ; i++) {\n", " for(j=0 ; j < N ; j++) {\n", " A[i][j] = 0.0;\n", " \n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Note the way the matrix is organized, row-major order.\n", "\n", "\n", "## Matrix Handling in C/C++\n", "\n", " Row Major Order, Addition\n", "We have $N\\times N$ matrices A, B and C and we wish to\n", "evaluate $A=B+C$." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "$$\n", "\\mathbf{A}= \\mathbf{B}\\pm\\mathbf{C} \\Longrightarrow a_{ij} = b_{ij}\\pm c_{ij},\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "In C/C++ this would be coded like" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ " for(i=0 ; i < N ; i++) {\n", " for(j=0 ; j < N ; j++) {\n", " a[i][j] = b[i][j]+c[i][j]\n", " \n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Matrix Handling in C/C++\n", "\n", " Row Major Order, Multiplication\n", "We have $N\\times N$ matrices A, B and C and we wish to\n", "evaluate $A=BC$." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "$$\n", "\\mathbf{A}=\\mathbf{BC} \\Longrightarrow a_{ij} = \\sum_{k=1}^{n} b_{ik}c_{kj},\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "In C/C++ this would be coded like" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ " for(i=0 ; i < N ; i++) {\n", " for(j=0 ; j < N ; j++) {\n", " for(k=0 ; k < N ; k++) {\n", " a[i][j]+=b[i][k]*c[k][j];\n", " \n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Dynamic memory allocation in C/C++\n", "\n", "At least three possibilities in this course\n", "\n", " * Do it yourself\n", "\n", " * Use the functions provided in the library package lib.cpp\n", "\n", " * Use Armadillo (a C++ linear algebra library, discussion both here and at lab). \n", "\n", "## Matrix Handling in C/C++, Dynamic Allocation\n", "\n", " Do it yourself" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ " int N;\n", " double ** A;\n", " A = new double*[N]\n", " for ( i = 0; i < N; i++)\n", " A[i] = new double[N];\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Always free space when you don't need an array anymore." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ " for ( i = 0; i < N; i++)\n", " delete[] A[i];\n", " delete[] A;\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Armadillo, recommended!!\n", "\n", " * Armadillo is a C++ linear algebra library (matrix maths) aiming towards a good balance between speed and ease of use. The syntax is deliberately similar to Matlab.\n", "\n", " * Integer, floating point and complex numbers are supported, as well as a subset of trigonometric and statistics functions. Various matrix decompositions are provided through optional integration with LAPACK, or one of its high performance drop-in replacements (such as the multi-threaded MKL or ACML libraries).\n", "\n", " * A delayed evaluation approach is employed (at compile-time) to combine several operations into one and reduce (or eliminate) the need for temporaries. This is accomplished through recursive templates and template meta-programming.\n", "\n", " * Useful for conversion of research code into production environments, or if C++ has been decided as the language of choice, due to speed and/or integration capabilities.\n", "\n", " * The library is open-source software, and is distributed under a license that is useful in both open-source and commercial/proprietary contexts.\n", "\n", "## Armadillo, simple examples" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ " #include \n", " #include \n", " \n", " using namespace std;\n", " using namespace arma;\n", " \n", " int main(int argc, char** argv)\n", " {\n", " mat A = randu(5,5);\n", " mat B = randu(5,5);\n", " \n", " cout << A*B << endl;\n", " \n", " return 0;\n", " \n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Armadillo, how to compile and install\n", "\n", "For people using Ubuntu, Debian, Linux Mint, simply go to the synaptic package manager and install\n", "armadillo from there.\n", "You may have to install Lapack as well.\n", "For Mac and Windows users, follow the instructions from the webpage\n", ".\n", "To compile, use for example (linux/ubuntu)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ " c++ -O2 -o program.x program.cpp -larmadillo -llapack -lblas\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "where the `-l` option indicates the library you wish to link to.\n", "\n", "For OS X users you may have to declare the paths to the include files and the libraries as" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ " c++ -O2 -o program.x program.cpp -L/usr/local/lib -I/usr/local/include -larmadillo -llapack -lblas\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Armadillo, simple examples" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ " #include \n", " #include \"armadillo\"\n", " using namespace arma;\n", " using namespace std;\n", " \n", " int main(int argc, char** argv)\n", " {\n", " // directly specify the matrix size (elements are uninitialised)\n", " mat A(2,3);\n", " // .n_rows = number of rows (read only)\n", " // .n_cols = number of columns (read only)\n", " cout << \"A.n_rows = \" << A.n_rows << endl;\n", " cout << \"A.n_cols = \" << A.n_cols << endl;\n", " // directly access an element (indexing starts at 0)\n", " A(1,2) = 456.0;\n", " A.print(\"A:\");\n", " // scalars are treated as a 1x1 matrix,\n", " // hence the code below will set A to have a size of 1x1\n", " A = 5.0;\n", " A.print(\"A:\");\n", " // if you want a matrix with all elements set to a particular value\n", " // the .fill() member function can be used\n", " A.set_size(3,3);\n", " A.fill(5.0); A.print(\"A:\");\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Armadillo, simple examples" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ " mat B;\n", " \n", " // endr indicates \"end of row\"\n", " B << 0.555950 << 0.274690 << 0.540605 << 0.798938 << endr\n", " << 0.108929 << 0.830123 << 0.891726 << 0.895283 << endr\n", " << 0.948014 << 0.973234 << 0.216504 << 0.883152 << endr\n", " << 0.023787 << 0.675382 << 0.231751 << 0.450332 << endr;\n", " \n", " // print to the cout stream\n", " // with an optional string before the contents of the matrix\n", " B.print(\"B:\");\n", " \n", " // the << operator can also be used to print the matrix\n", " // to an arbitrary stream (cout in this case)\n", " cout << \"B:\" << endl << B << endl;\n", " // save to disk\n", " B.save(\"B.txt\", raw_ascii);\n", " // load from disk\n", " mat C;\n", " C.load(\"B.txt\");\n", " C += 2.0 * B;\n", " C.print(\"C:\");\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Armadillo, simple examples" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ " // submatrix types:\n", " //\n", " // .submat(first_row, first_column, last_row, last_column)\n", " // .row(row_number)\n", " // .col(column_number)\n", " // .cols(first_column, last_column)\n", " // .rows(first_row, last_row)\n", " \n", " cout << \"C.submat(0,0,3,1) =\" << endl;\n", " cout << C.submat(0,0,3,1) << endl;\n", " \n", " // generate the identity matrix\n", " mat D = eye(4,4);\n", " \n", " D.submat(0,0,3,1) = C.cols(1,2);\n", " D.print(\"D:\");\n", " \n", " // transpose\n", " cout << \"trans(B) =\" << endl;\n", " cout << trans(B) << endl;\n", " \n", " // maximum from each column (traverse along rows)\n", " cout << \"max(B) =\" << endl;\n", " cout << max(B) << endl;\n", " \n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Armadillo, simple examples" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ " // maximum from each row (traverse along columns)\n", " cout << \"max(B,1) =\" << endl;\n", " cout << max(B,1) << endl;\n", " // maximum value in B\n", " cout << \"max(max(B)) = \" << max(max(B)) << endl;\n", " // sum of each column (traverse along rows)\n", " cout << \"sum(B) =\" << endl;\n", " cout << sum(B) << endl;\n", " // sum of each row (traverse along columns)\n", " cout << \"sum(B,1) =\" << endl;\n", " cout << sum(B,1) << endl;\n", " // sum of all elements\n", " cout << \"sum(sum(B)) = \" << sum(sum(B)) << endl;\n", " cout << \"accu(B) = \" << accu(B) << endl;\n", " // trace = sum along diagonal\n", " cout << \"trace(B) = \" << trace(B) << endl;\n", " // random matrix -- values are uniformly distributed in the [0,1] interval\n", " mat E = randu(4,4);\n", " E.print(\"E:\");\n", " \n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Armadillo, simple examples" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ " // row vectors are treated like a matrix with one row\n", " rowvec r;\n", " r << 0.59499 << 0.88807 << 0.88532 << 0.19968;\n", " r.print(\"r:\");\n", " \n", " // column vectors are treated like a matrix with one column\n", " colvec q;\n", " q << 0.81114 << 0.06256 << 0.95989 << 0.73628;\n", " q.print(\"q:\");\n", " \n", " // dot or inner product\n", " cout << \"as_scalar(r*q) = \" << as_scalar(r*q) << endl;\n", " \n", " // outer product\n", " cout << \"q*r =\" << endl;\n", " cout << q*r << endl;\n", " \n", " \n", " // sum of three matrices (no temporary matrices are created)\n", " mat F = B + C + D;\n", " F.print(\"F:\");\n", " \n", " return 0;\n", " \n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Armadillo, simple examples" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ " #include \n", " #include \"armadillo\"\n", " using namespace arma;\n", " using namespace std;\n", " \n", " int main(int argc, char** argv)\n", " {\n", " cout << \"Armadillo version: \" << arma_version::as_string() << endl;\n", " \n", " mat A;\n", " \n", " A << 0.165300 << 0.454037 << 0.995795 << 0.124098 << 0.047084 << endr\n", " << 0.688782 << 0.036549 << 0.552848 << 0.937664 << 0.866401 << endr\n", " << 0.348740 << 0.479388 << 0.506228 << 0.145673 << 0.491547 << endr\n", " << 0.148678 << 0.682258 << 0.571154 << 0.874724 << 0.444632 << endr\n", " << 0.245726 << 0.595218 << 0.409327 << 0.367827 << 0.385736 << endr;\n", " \n", " A.print(\"A =\");\n", " \n", " // determinant\n", " cout << \"det(A) = \" << det(A) << endl;\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Armadillo, simple examples" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ " // inverse\n", " cout << \"inv(A) = \" << endl << inv(A) << endl;\n", " double k = 1.23;\n", " \n", " mat B = randu(5,5);\n", " mat C = randu(5,5);\n", " \n", " rowvec r = randu(5);\n", " colvec q = randu(5);\n", " \n", " \n", " // examples of some expressions\n", " // for which optimised implementations exist\n", " // optimised implementation of a trinary expression\n", " // that results in a scalar\n", " cout << \"as_scalar( r*inv(diagmat(B))*q ) = \";\n", " cout << as_scalar( r*inv(diagmat(B))*q ) << endl;\n", " \n", " // example of an expression which is optimised\n", " // as a call to the dgemm() function in BLAS:\n", " cout << \"k*trans(B)*C = \" << endl << k*trans(B)*C;\n", " \n", " return 0;\n", " \n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Gaussian Elimination\n", "\n", "We start with the linear set of equations" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "$$\n", "\\mathbf{A}\\mathbf{x} = \\mathbf{w}.\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "We assume also that the matrix $\\mathbf{A}$ is non-singular and that the\n", "matrix elements along the diagonal satisfy $a_{ii} \\ne 0$. Simple $4\\times 4 $ example" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "$$\n", "\\begin{bmatrix}\n", " a_{11}& a_{12} &a_{13}& a_{14}\\\\\n", " a_{21}& a_{22} &a_{23}& a_{24}\\\\\n", " a_{31}& a_{32} &a_{33}& a_{34}\\\\\n", " a_{41}& a_{42} &a_{43}& a_{44}\\\\\n", " \\end{bmatrix} \\begin{bmatrix}\n", " x_1\\\\\n", " x_2\\\\\n", " x_3 \\\\\n", " x_4 \\\\\n", " \\end{bmatrix}\n", " =\\begin{bmatrix}\n", " w_1\\\\\n", " w_2\\\\\n", " w_3 \\\\\n", " w_4\\\\\n", " \\end{bmatrix}.\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Gaussian Elimination\n", "or" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "$$\n", "a_{11}x_1 +a_{12}x_2 +a_{13}x_3 + a_{14}x_4=w_1 \\nonumber\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "$$\n", "a_{21}x_1 + a_{22}x_2 + a_{23}x_3 + a_{24}x_4=w_2 \\nonumber\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "$$\n", "a_{31}x_1 + a_{32}x_2 + a_{33}x_3 + a_{34}x_4=w_3 \\nonumber\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "$$\n", "a_{41}x_1 + a_{42}x_2 + a_{43}x_3 + a_{44}x_4=w_4. \\nonumber\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Gaussian Elimination\n", "\n", "The basic idea of Gaussian elimination is to use the first equation to eliminate the first unknown $x_1$\n", "from the remaining $n-1$ equations. Then we use the new second equation to eliminate the second unknown\n", "$x_2$ from the remaining $n-2$ equations. With $n-1$ such eliminations\n", "we obtain a so-called upper triangular set of equations of the form" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "$$\n", "b_{11}x_1 +b_{12}x_2 +b_{13}x_3 + b_{14}x_4=y_1 \\nonumber\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "$$\n", "b_{22}x_2 + b_{23}x_3 + b_{24}x_4=y_2 \\nonumber\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "$$\n", "b_{33}x_3 + b_{34}x_4=y_3 \\nonumber\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "\n", "
\n", "\n", "$$\n", "b_{44}x_4=y_4. \\nonumber\n", "\\label{eq:gaussbacksub} \\tag{2}\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "We can solve this system of equations recursively starting from $x_n$ (in our case $x_4$) and proceed with\n", "what is called a backward substitution. \n", "\n", "## Gaussian Elimination\n", "This process can be expressed mathematically as" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "\n", "
\n", "\n", "$$\n", "\\begin{equation}\n", " x_m = \\frac{1}{b_{mm}}\\left(y_m-\\sum_{k=m+1}^nb_{mk}x_k\\right)\\quad m=n-1,n-2,\\dots,1.\n", "\\label{_auto1} \\tag{3}\n", "\\end{equation}\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "To arrive at such an upper triangular system of equations, we start by eliminating\n", "the unknown $x_1$ for $j=2,n$. We achieve this by multiplying the first equation by $a_{j1}/a_{11}$ and then subtract\n", "the result from the $j$th equation. We assume obviously that $a_{11}\\ne 0$ and that\n", "$\\mathbf{A}$ is not singular.\n", "\n", "## Gaussian Elimination\n", "\n", "Our actual $4\\times 4$ example reads after the first operation" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "$$\n", "\\begin{bmatrix}\n", " a_{11}& a_{12} &a_{13}& a_{14}\\\\\n", " 0& (a_{22}-\\frac{a_{21}a_{12}}{a_{11}}) &(a_{23}-\\frac{a_{21}a_{13}}{a_{11}}) & (a_{24}-\\frac{a_{21}a_{14}}{a_{11}})\\\\\n", "0& (a_{32}-\\frac{a_{31}a_{12}}{a_{11}})& (a_{33}-\\frac{a_{31}a_{13}}{a_{11}})& (a_{34}-\\frac{a_{31}a_{14}}{a_{11}})\\\\\n", "0&(a_{42}-\\frac{a_{41}a_{12}}{a_{11}}) &(a_{43}-\\frac{a_{41}a_{13}}{a_{11}}) & (a_{44}-\\frac{a_{41}a_{14}}{a_{11}}) \\\\\n", " \\end{bmatrix} \\begin{bmatrix}\n", " x_1\\\\\n", " x_2\\\\\n", " x_3 \\\\\n", " x_4 \\\\\n", " \\end{bmatrix} \n", " =\\begin{bmatrix}\n", " y_1\\\\\n", " w_2^{(2)}\\\\\n", " w_3^{(2)} \\\\\n", " w_4^{(2)}\\\\\n", " \\end{bmatrix},\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "or" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "$$\n", "b_{11}x_1 +b_{12}x_2 +b_{13}x_3 + b_{14}x_4=y_1 \\nonumber\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "$$\n", "a^{(2)}_{22}x_2 + a^{(2)}_{23}x_3 + a^{(2)}_{24}x_4=w^{(2)}_2 \\nonumber\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "$$\n", "a^{(2)}_{32}x_2 + a^{(2)}_{33}x_3 + a^{(2)}_{34}x_4=w^{(2)}_3 \\nonumber\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "$$\n", "a^{(2)}_{42}x_2 + a^{(2)}_{43}x_3 + a^{(2)}_{44}x_4=w^{(2)}_4, \\nonumber\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "\n", "
\n", "\n", "$$\n", "\\begin{equation} \n", "\\label{_auto2} \\tag{4}\n", "\\end{equation}\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Gaussian Elimination\n", "\n", "The new coefficients are" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "\n", "
\n", "\n", "$$\n", "\\begin{equation}\n", " b_{1k} = a_{1k}^{(1)} \\quad k=1,\\dots,n,\n", "\\label{_auto3} \\tag{5}\n", "\\end{equation}\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "where each $a_{1k}^{(1)}$ is equal to the original $a_{1k}$ element. The other coefficients are" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "\n", "
\n", "\n", "$$\n", "\\begin{equation}\n", "a_{jk}^{(2)} = a_{jk}^{(1)}-\\frac{a_{j1}^{(1)}a_{1k}^{(1)}}{a_{11}^{(1)}} \\quad j,k=2,\\dots,n,\n", "\\label{_auto4} \\tag{6}\n", "\\end{equation}\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "with a new right-hand side given by" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "\n", "
\n", "\n", "$$\n", "\\begin{equation}\n", "y_{1}=w_1^{(1)}, \\quad w_j^{(2)} =w_j^{(1)}-\\frac{a_{j1}^{(1)}w_1^{(1)}}{a_{11}^{(1)}} \\quad j=2,\\dots,n.\n", "\\label{_auto5} \\tag{7}\n", "\\end{equation}\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "We have also set $w_1^{(1)}=w_1$, the original vector element.\n", "We see that the system of unknowns $x_1,\\dots,x_n$ is transformed into an $(n-1)\\times (n-1)$ problem.\n", "\n", "## Gaussian Elimination\n", "\n", "This step is called forward substitution.\n", "Proceeding with these substitutions, we obtain the\n", "general expressions for the new coefficients" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "\n", "
\n", "\n", "$$\n", "\\begin{equation}\n", " a_{jk}^{(m+1)} = a_{jk}^{(m)}-\\frac{a_{jm}^{(m)}a_{mk}^{(m)}}{a_{mm}^{(m)}} \\quad j,k=m+1,\\dots,n,\n", "\\label{_auto6} \\tag{8}\n", "\\end{equation}\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "with $m=1,\\dots,n-1$ and a\n", "right-hand side given by" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "\n", "
\n", "\n", "$$\n", "\\begin{equation}\n", " w_j^{(m+1)} =w_j^{(m)}-\\frac{a_{jm}^{(m)}w_m^{(m)}}{a_{mm}^{(m)}}\\quad j=m+1,\\dots,n.\n", "\\label{_auto7} \\tag{9}\n", "\\end{equation}\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "This set of $n-1$ elimations leads us to an equations which is solved by back substitution.\n", "If the arithmetics is exact and the matrix $\\mathbf{A}$ is not singular, then the computed answer will be exact.\n", "\n", "Even though the matrix elements along the diagonal are not zero,\n", "numerically small numbers may appear and subsequent divisions may lead to large numbers, which, if added\n", "to a small number may yield losses of precision. Suppose for example that our first division in $(a_{22}-a_{21}a_{12}/a_{11})$\n", "results in $-10^{-7}$ and that $a_{22}$ is one.\n", "one. We are then\n", "adding $10^7+1$. With single precision this results in $10^7$.\n", "\n", "\n", "\n", "## Linear Algebra Methods\n", "\n", " * Gaussian elimination, $O(2/3n^3)$ flops, general matrix\n", "\n", " * LU decomposition, upper triangular and lower tridiagonal matrices, $O(2/3n^3)$ flops, general matrix. Get easily the inverse, determinant and can solve linear equations with back-substitution only, $O(n^2)$ flops\n", "\n", " * Cholesky decomposition. Real symmetric or hermitian positive definite matrix, $O(1/3n^3)$ flops.\n", "\n", " * Tridiagonal linear systems, important for differential equations. Normally positive definite and non-singular. $O(8n)$ flops for symmetric. Special case of banded matrices.\n", "\n", " * Singular value decomposition\n", "\n", " * the QR method will be discussed in chapter 7 in connection with eigenvalue systems. $O(4/3n^3)$ flops.\n", "\n", "## LU Decomposition\n", "\n", "The LU decomposition method means that we can rewrite\n", "this matrix as the product of two matrices $\\mathbf{L}$ and $\\mathbf{U}$\n", "where" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "$$\n", "\\begin{bmatrix}\n", " a_{11} & a_{12} & a_{13} & a_{14} \\\\\n", " a_{21} & a_{22} & a_{23} & a_{24} \\\\\n", " a_{31} & a_{32} & a_{33} & a_{34} \\\\\n", " a_{41} & a_{42} & a_{43} & a_{44}\n", " \\end{bmatrix}\n", " = \\begin{bmatrix}\n", " 1 & 0 & 0 & 0 \\\\\n", " l_{21} & 1 & 0 & 0 \\\\\n", " l_{31} & l_{32} & 1 & 0 \\\\\n", " l_{41} & l_{42} & l_{43} & 1\n", " \\end{bmatrix}\n", " \\begin{bmatrix}\n", " u_{11} & u_{12} & u_{13} & u_{14} \\\\\n", " 0 & u_{22} & u_{23} & u_{24} \\\\\n", " 0 & 0 & u_{33} & u_{34} \\\\\n", " 0 & 0 & 0 & u_{44}\n", " \\end{bmatrix}.\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## LU Decomposition\n", "\n", "LU decomposition forms the backbone of other algorithms in linear algebra, such as the\n", "solution of linear equations given by" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "$$\n", "a_{11}x_1 +a_{12}x_2 +a_{13}x_3 + a_{14}x_4=w_1 \\nonumber\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "$$\n", "a_{21}x_1 + a_{22}x_2 + a_{23}x_3 + a_{24}x_4=w_2 \\nonumber\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "$$\n", "a_{31}x_1 + a_{32}x_2 + a_{33}x_3 + a_{34}x_4=w_3 \\nonumber\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "$$\n", "a_{41}x_1 + a_{42}x_2 + a_{43}x_3 + a_{44}x_4=w_4. \\nonumber\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "The above set of equations is conveniently solved by using LU decomposition as an intermediate step.\n", "\n", "The matrix $\\mathbf{A}\\in \\mathbb{R}^{n\\times n}$ has an LU factorization if the determinant\n", "is different from zero. If the LU factorization exists and $\\mathbf{A}$ is non-singular, then the LU factorization\n", "is unique and the determinant is given by" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "$$\n", "det\\{\\mathbf{A}\\}=det\\{\\mathbf{LU}\\}= det\\{\\mathbf{L}\\}det\\{\\mathbf{U}\\}=u_{11}u_{22}\\dots u_{nn}.\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## LU Decomposition, why?\n", "\n", "There are at least three main advantages with LU decomposition compared with standard Gaussian elimination:\n", "\n", " * It is straightforward to compute the determinant of a matrix\n", "\n", " * If we have to solve sets of linear equations with the same matrix but with different vectors $\\mathbf{y}$, the number of FLOPS is of the order $n^3$.\n", "\n", " * The inverse is such an operation \n", "\n", "## LU Decomposition, linear equations\n", "\n", "With the LU decomposition it is rather\n", "simple to solve a system of linear equations" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "$$\n", "a_{11}x_1 +a_{12}x_2 +a_{13}x_3 + a_{14}x_4=w_1 \\nonumber\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "$$\n", "a_{21}x_1 + a_{22}x_2 + a_{23}x_3 + a_{24}x_4=w_2 \\nonumber\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "$$\n", "a_{31}x_1 + a_{32}x_2 + a_{33}x_3 + a_{34}x_4=w_3 \\nonumber\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "$$\n", "a_{41}x_1 + a_{42}x_2 + a_{43}x_3 + a_{44}x_4=w_4. \\nonumber\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "This can be written in matrix form as" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "$$\n", "\\mathbf{Ax}=\\mathbf{w}.\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "where $\\mathbf{A}$ and $\\mathbf{w}$ are known and we have to solve for\n", "$\\mathbf{x}$. Using the LU dcomposition we write" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "$$\n", "\\mathbf{A} \\mathbf{x} \\equiv \\mathbf{L} \\mathbf{U} \\mathbf{x} =\\mathbf{w}.\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## LU Decomposition, linear equations\n", "\n", "The previous equation can be calculated in two steps" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "$$\n", "\\mathbf{L} \\mathbf{y} = \\mathbf{w};\\qquad \\mathbf{Ux}=\\mathbf{y}.\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "To show that this is correct we use to the LU decomposition\n", "to rewrite our system of linear equations as" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "$$\n", "\\mathbf{LUx}=\\mathbf{w},\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "and since the determinant of $\\mathbf{L}$ is equal to 1 (by construction\n", "since the diagonals of $\\mathbf{L}$ equal 1) we can use the inverse of\n", "$\\mathbf{L}$ to obtain" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "$$\n", "\\mathbf{Ux}=\\mathbf{L^{-1}w}=\\mathbf{y},\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "which yields the intermediate step" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "$$\n", "\\mathbf{L^{-1}w}=\\mathbf{y}\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "and as soon as we have $\\mathbf{y}$ we can obtain $\\mathbf{x}$\n", "through $\\mathbf{Ux}=\\mathbf{y}$.\n", "\n", "## LU Decomposition, why?\n", "\n", "For our four-dimentional example this takes the form" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "$$\n", "y_1=w_1 \\nonumber\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "$$\n", "l_{21}y_1 + y_2=w_2\\nonumber\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "$$\n", "l_{31}y_1 + l_{32}y_2 + y_3 =w_3\\nonumber\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "$$\n", "l_{41}y_1 + l_{42}y_2 + l_{43}y_3 + y_4=w_4. \\nonumber\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "and" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "$$\n", "u_{11}x_1 +u_{12}x_2 +u_{13}x_3 + u_{14}x_4=y_1 \\nonumber\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "$$\n", "u_{22}x_2 + u_{23}x_3 + u_{24}x_4=y_2\\nonumber\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "$$\n", "u_{33}x_3 + u_{34}x_4=y_3\\nonumber\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "$$\n", "u_{44}x_4=y_4 \\nonumber\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "This example shows the basis for the algorithm\n", "needed to solve the set of $n$ linear equations.\n", "\n", "## LU Decomposition, linear equations\n", "\n", "The algorithm goes as follows\n", "\n", " * Set up the matrix $\\bf A$ and the vector $\\bf w$ with their correct dimensions. This determines the dimensionality of the unknown vector $\\bf x$.\n", "\n", " * Then LU decompose the matrix $\\bf A$ through a call to the function `ludcmp(double a, int n, int indx, double &d)`. This functions returns the LU decomposed matrix $\\bf A$, its determinant and the vector indx which keeps track of the number of interchanges of rows. If the determinant is zero, the solution is malconditioned.\n", "\n", " * Thereafter you call the function `lubksb(double a, int n, int indx, double w)` which uses the LU decomposed matrix $\\bf A$ and the vector $\\bf w$ and returns $\\bf x$ in the same place as $\\bf w$. Upon exit the original content in $\\bf w$ is destroyed. If you wish to keep this information, you should make a backup of it in your calling function.\n", "\n", "## LU Decomposition, the inverse of a matrix\n", "\n", "If the inverse exists then" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "$$\n", "\\mathbf{A}^{-1}\\mathbf{A}=\\mathbf{I},\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "the identity matrix. With an LU decomposed matrix we can rewrite the last equation as" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "$$\n", "\\mathbf{LU}\\mathbf{A}^{-1}=\\mathbf{I}.\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## LU Decomposition, the inverse of a matrix\n", "\n", "If we assume that the first column (that is column 1) of the inverse matrix\n", "can be written as a vector with unknown entries" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "$$\n", "\\mathbf{A}_1^{-1}= \\begin{bmatrix}\n", " a_{11}^{-1} \\\\\n", " a_{21}^{-1} \\\\\n", " \\dots \\\\\n", " a_{n1}^{-1} \\\\\n", " \\end{bmatrix},\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "then we have a linear set of equations" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "$$\n", "\\mathbf{LU}\\begin{bmatrix}\n", " a_{11}^{-1} \\\\\n", " a_{21}^{-1} \\\\\n", " \\dots \\\\\n", " a_{n1}^{-1} \\\\\n", " \\end{bmatrix} =\\begin{bmatrix}\n", " 1 \\\\\n", " 0 \\\\\n", " \\dots \\\\\n", " 0 \\\\\n", " \\end{bmatrix}.\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## LU Decomposition, the inverse\n", "\n", "In a similar way we can compute the unknow entries of the second column," ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "$$\n", "\\mathbf{LU}\\begin{bmatrix}\n", " a_{12}^{-1} \\\\\n", " a_{22}^{-1} \\\\\n", " \\dots \\\\\n", " a_{n2}^{-1} \\\\\n", " \\end{bmatrix}=\\begin{bmatrix}\n", " 0 \\\\\n", " 1 \\\\\n", " \\dots \\\\\n", " 0 \\\\\n", " \\end{bmatrix},\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "and continue till we have solved all $n$ sets of linear equations.\n", "\n", "\n", "## [Using Armadillo to perform an LU decomposition](https://github.com/CompPhysics/ComputationalPhysicsMSU/blob/master/doc/Programs/CppQtCodesLectures/MatrixTest/main.cpp)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ " #include \n", " #include \"armadillo\"\n", " using namespace arma;\n", " using namespace std;\n", " \n", " int main()\n", " {\n", " mat A = randu(5,5);\n", " vec b = randu(5);\n", " \n", " A.print(\"A =\");\n", " b.print(\"b=\");\n", " // solve Ax = b\n", " vec x = solve(A,b);\n", " // print x\n", " x.print(\"x=\");\n", " // find LU decomp of A, if needed, P is the permutation matrix\n", " mat L, U;\n", " lu(L,U,A);\n", " // print l\n", " L.print(\" L= \");\n", " // print U\n", " U.print(\" U= \");\n", " //Check that A = LU\n", " (A-L*U).print(\"Test of LU decomposition\");\n", " return 0;\n", " }\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# Review of Statistics\n", "\n", "\n", "## Domains and probabilities\n", "\n", "Consider the following simple example, namely the tossing of two dice, resulting in the following possible values" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "$$\n", "\\{2,3,4,5,6,7,8,9,10,11,12\\}.\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "These values are called the *domain*. \n", "To this domain we have the corresponding *probabilities*" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "$$\n", "\\{1/36,2/36/,3/36,4/36,5/36,6/36,5/36,4/36,3/36,2/36,1/36\\}.\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Tossing the dice\n", "\n", "The numbers in the domain are the outcomes of the physical process of tossing say two dice.\n", "We cannot tell beforehand whether the outcome is 3 or 5 or any other number in this domain.\n", "This defines the randomness of the outcome, or unexpectedness or any other synonimous word which\n", "encompasses the uncertitude of the final outcome. \n", "\n", "The only thing we can tell beforehand\n", "is that say the outcome 2 has a certain probability. \n", "If our favorite hobby is to spend an hour every evening throwing dice and \n", "registering the sequence of outcomes, we will note that the numbers in the above domain" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "$$\n", "\\{2,3,4,5,6,7,8,9,10,11,12\\},\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "appear in a random order. After 11 throws the results may look like" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "$$\n", "\\{10,8,6,3,6,9,11,8,12,4,5\\}.\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Stochastic variables\n", "\n", "\n", "**Random variables are characterized by a domain which contains all possible values that the random value may take. This domain has a corresponding probability distribution function(PDF)**.\n", "\n", "\n", "\n", "## Stochastic variables and the main concepts, the discrete case\n", "\n", "There are two main concepts associated with a stochastic variable. The\n", "*domain* is the set $\\mathbb D = \\{x\\}$ of all accessible values\n", "the variable can assume, so that $X \\in \\mathbb D$. An example of a\n", "discrete domain is the set of six different numbers that we may get by\n", "throwing of a dice, $x\\in\\{1,\\,2,\\,3,\\,4,\\,5,\\,6\\}$.\n", "\n", "The *probability distribution function (PDF)* is a function\n", "$p(x)$ on the domain which, in the discrete case, gives us the\n", "probability or relative frequency with which these values of $X$\n", "occur" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "$$\n", "p(x) = \\mathrm{Prob}(X=x).\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Stochastic variables and the main concepts, the continuous case\n", "\n", "In the continuous case, the PDF does not directly depict the\n", "actual probability. Instead we define the probability for the\n", "stochastic variable to assume any value on an infinitesimal interval\n", "around $x$ to be $p(x)dx$. The continuous function $p(x)$ then gives us\n", "the *density* of the probability rather than the probability\n", "itself. The probability for a stochastic variable to assume any value\n", "on a non-infinitesimal interval $[a,\\,b]$ is then just the integral" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "$$\n", "\\mathrm{Prob}(a\\leq X\\leq b) = \\int_a^b p(x)dx.\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Qualitatively speaking, a stochastic variable represents the values of\n", "numbers chosen as if by chance from some specified PDF so that the\n", "selection of a large set of these numbers reproduces this PDF.\n", "\n", "\n", "\n", "## The cumulative probability\n", "\n", "Of interest to us is the *cumulative probability\n", "distribution function* (**CDF**), $P(x)$, which is just the probability\n", "for a stochastic variable $X$ to assume any value less than $x$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "$$\n", "P(x)=\\mathrm{Prob(}X\\leq x\\mathrm{)} =\n", "\\int_{-\\infty}^x p(x^{\\prime})dx^{\\prime}.\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "The relation between a CDF and its corresponding PDF is then" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "$$\n", "p(x) = \\frac{d}{dx}P(x).\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Properties of PDFs\n", "\n", "\n", "There are two properties that all PDFs must satisfy. The first one is\n", "positivity (assuming that the PDF is normalized)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "$$\n", "0 \\leq p(x) \\leq 1.\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Naturally, it would be nonsensical for any of the values of the domain\n", "to occur with a probability greater than $1$ or less than $0$. Also,\n", "the PDF must be normalized. That is, all the probabilities must add up\n", "to unity. The probability of \"anything\" to happen is always unity. For\n", "both discrete and continuous PDFs, this condition is" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "$$\n", "\\begin{align*}\n", "\\sum_{x_i\\in\\mathbb D} p(x_i) & = 1,\\\\\n", "\\int_{x\\in\\mathbb D} p(x)\\,dx & = 1.\n", "\\end{align*}\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Important distributions, the uniform distribution\n", "\n", "The first one\n", "is the most basic PDF; namely the uniform distribution" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "\n", "
\n", "\n", "$$\n", "\\begin{equation}\n", "p(x) = \\frac{1}{b-a}\\theta(x-a)\\theta(b-x).\n", "\\label{eq:unifromPDF} \\tag{10}\n", "\\end{equation}\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "For $a=0$ and $b=1$ we have" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "$$\n", "\\begin{array}{ll}\n", "p(x)dx = dx & \\in [0,1].\n", "\\end{array}\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "The latter distribution is used to generate random numbers. For other PDFs, one needs normally a mapping from this distribution to say for example the exponential distribution. \n", "\n", "\n", "\n", "## Gaussian distribution\n", "\n", "The second one is the Gaussian Distribution" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "$$\n", "p(x) = \\frac{1}{\\sigma\\sqrt{2\\pi}} \\exp{(-\\frac{(x-\\mu)^2}{2\\sigma^2})},\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "with mean value $\\mu$ and standard deviation $\\sigma$. If $\\mu=0$ and $\\sigma=1$, it is normally called the **standard normal distribution**" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "$$\n", "p(x) = \\frac{1}{\\sqrt{2\\pi}} \\exp{(-\\frac{x^2}{2})},\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "The following simple Python code plots the above distribution for different values of $\\mu$ and $\\sigma$." ] }, { "cell_type": "code", "execution_count": 29, "metadata": { "collapsed": false }, "outputs": [], "source": [ "import numpy as np\n", "from math import acos, exp, sqrt\n", "from matplotlib import pyplot as plt\n", "from matplotlib import rc, rcParams\n", "import matplotlib.units as units\n", "import matplotlib.ticker as ticker\n", "rc('text',usetex=True)\n", "rc('font',**{'family':'serif','serif':['Gaussian distribution']})\n", "font = {'family' : 'serif',\n", " 'color' : 'darkred',\n", " 'weight' : 'normal',\n", " 'size' : 16,\n", " }\n", "pi = acos(-1.0)\n", "mu0 = 0.0\n", "sigma0 = 1.0\n", "mu1= 1.0\n", "sigma1 = 2.0\n", "mu2 = 2.0\n", "sigma2 = 4.0\n", "\n", "x = np.linspace(-20.0, 20.0)\n", "v0 = np.exp(-(x*x-2*x*mu0+mu0*mu0)/(2*sigma0*sigma0))/sqrt(2*pi*sigma0*sigma0)\n", "v1 = np.exp(-(x*x-2*x*mu1+mu1*mu1)/(2*sigma1*sigma1))/sqrt(2*pi*sigma1*sigma1)\n", "v2 = np.exp(-(x*x-2*x*mu2+mu2*mu2)/(2*sigma2*sigma2))/sqrt(2*pi*sigma2*sigma2)\n", "plt.plot(x, v0, 'b-', x, v1, 'r-', x, v2, 'g-')\n", "plt.title(r'{\\bf Gaussian distributions}', fontsize=20)\n", "plt.text(-19, 0.3, r'Parameters: $\\mu = 0$, $\\sigma = 1$', fontdict=font)\n", "plt.text(-19, 0.18, r'Parameters: $\\mu = 1$, $\\sigma = 2$', fontdict=font)\n", "plt.text(-19, 0.08, r'Parameters: $\\mu = 2$, $\\sigma = 4$', fontdict=font)\n", "plt.xlabel(r'$x$',fontsize=20)\n", "plt.ylabel(r'$p(x)$ [MeV]',fontsize=20)\n", "\n", "# Tweak spacing to prevent clipping of ylabel \n", "plt.subplots_adjust(left=0.15)\n", "plt.savefig('gaussian.pdf', format='pdf')\n", "plt.show()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Exponential distribution\n", "\n", "Another important distribution in science is the exponential distribution" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "$$\n", "p(x) = \\alpha\\exp{-(\\alpha x)}.\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Expectation values\n", "\n", "Let $h(x)$ be an arbitrary continuous function on the domain of the stochastic\n", "variable $X$ whose PDF is $p(x)$. We define the *expectation value*\n", "of $h$ with respect to $p$ as follows" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "\n", "
\n", "\n", "$$\n", "\\begin{equation}\n", "\\langle h \\rangle_X \\equiv \\int\\! h(x)p(x)\\,dx\n", "\\label{eq:expectation_value_of_h_wrt_p} \\tag{11}\n", "\\end{equation}\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Whenever the PDF is known implicitly, like in this case, we will drop\n", "the index $X$ for clarity. \n", "A particularly useful class of special expectation values are the\n", "*moments*. The $n$-th moment of the PDF $p$ is defined as\n", "follows" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "$$\n", "\\langle x^n \\rangle \\equiv \\int\\! x^n p(x)\\,dx\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Stochastic variables and the main concepts, mean values\n", "\n", "The zero-th moment $\\langle 1\\rangle$ is just the normalization condition of\n", "$p$. The first moment, $\\langle x\\rangle$, is called the *mean* of $p$\n", "and often denoted by the letter $\\mu$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "$$\n", "\\langle x\\rangle = \\mu \\equiv \\int x p(x)dx,\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "for a continuous distribution and" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "$$\n", "\\langle x\\rangle = \\mu \\equiv \\sum_{i=1}^N x_i p(x_i),\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "for a discrete distribution. \n", "Qualitatively it represents the centroid or the average value of the\n", "PDF and is therefore simply called the expectation value of $p(x)$.\n", "\n", "\n", "\n", "## Stochastic variables and the main concepts, central moments, the variance\n", "\n", "\n", "A special version of the moments is the set of *central moments*, the n-th central moment defined as" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "$$\n", "\\langle (x-\\langle x\\rangle )^n\\rangle \\equiv \\int\\! (x-\\langle x\\rangle)^n p(x)\\,dx\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "The zero-th and first central moments are both trivial, equal $1$ and\n", "$0$, respectively. But the second central moment, known as the\n", "*variance* of $p$, is of particular interest. For the stochastic\n", "variable $X$, the variance is denoted as $\\sigma^2_X$ or $\\mathrm{Var}(X)$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "$$\n", "\\begin{align*}\n", "\\sigma^2_X &=\\mathrm{Var}(X) = \\langle (x-\\langle x\\rangle)^2\\rangle =\n", "\\int (x-\\langle x\\rangle)^2 p(x)dx\\\\\n", "& = \\int\\left(x^2 - 2 x \\langle x\\rangle^{2} +\\langle x\\rangle^2\\right)p(x)dx\\\\\n", "& = \\langle x^2\\rangle - 2 \\langle x\\rangle\\langle x\\rangle + \\langle x\\rangle^2\\\\\n", "& = \\langle x^2 \\rangle - \\langle x\\rangle^2\n", "\\end{align*}\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "The square root of the variance, $\\sigma =\\sqrt{\\langle (x-\\langle x\\rangle)^2\\rangle}$ is called the \n", "**standard deviation** of $p$. It is the RMS (root-mean-square)\n", "value of the deviation of the PDF from its mean value, interpreted\n", "qualitatively as the \"spread\" of $p$ around its mean.\n", "\n", "\n", "\n", "\n", "\n", "## Probability Distribution Functions\n", "\n", "\n", "The following table collects properties of probability distribution functions.\n", "In our notation we reserve the label $p(x)$ for the probability of a certain event,\n", "while $P(x)$ is the cumulative probability. \n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "
Discrete PDF Continuous PDF
Domain $\\left\\{x_1, x_2, x_3, \\dots, x_N\\right\\}$ $[a,b]$
Probability $p(x_i)$ $p(x)dx$
Cumulative $P_i=\\sum_{l=1}^ip(x_l)$ $P(x)=\\int_a^xp(t)dt$
Positivity $0 \\le p(x_i) \\le 1$ $p(x) \\ge 0$
Positivity $0 \\le P_i \\le 1$ $0 \\le P(x) \\le 1$
Monotonic $P_i \\ge P_j$ if $x_i \\ge x_j$ $P(x_i) \\ge P(x_j)$ if $x_i \\ge x_j$
Normalization $P_N=1$ $P(b)=1$
\n", "\n", "\n", "\n", "\n", "## Probability Distribution Functions\n", "\n", "With a PDF we can compute expectation values of selected quantities such as" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "$$\n", "\\langle x^k\\rangle=\\sum_{i=1}^{N}x_i^kp(x_i),\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "if we have a discrete PDF or" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "$$\n", "\\langle x^k\\rangle=\\int_a^b x^kp(x)dx,\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "in the case of a continuous PDF. We have already defined the mean value $\\mu$\n", "and the variance $\\sigma^2$. \n", "\n", "\n", "\n", "## The three famous Probability Distribution Functions\n", "\n", "\n", "There are at least three PDFs which one may encounter. These are the\n", "\n", "**Uniform distribution**" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "$$\n", "p(x)=\\frac{1}{b-a}\\Theta(x-a)\\Theta(b-x),\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "yielding probabilities different from zero in the interval $[a,b]$.\n", "\n", "**The exponential distribution**" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "$$\n", "p(x)=\\alpha \\exp{(-\\alpha x)},\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "yielding probabilities different from zero in the interval $[0,\\infty)$ and with mean value" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "$$\n", "\\mu = \\int_0^{\\infty}xp(x)dx=\\int_0^{\\infty}x\\alpha \\exp{(-\\alpha x)}dx=\\frac{1}{\\alpha},\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "with variance" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "$$\n", "\\sigma^2=\\int_0^{\\infty}x^2p(x)dx-\\mu^2 = \\frac{1}{\\alpha^2}.\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Probability Distribution Functions, the normal distribution\n", "\n", "Finally, we have the so-called univariate normal distribution, or just the **normal distribution**" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "$$\n", "p(x)=\\frac{1}{b\\sqrt{2\\pi}}\\exp{\\left(-\\frac{(x-a)^2}{2b^2}\\right)}\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "with probabilities different from zero in the interval $(-\\infty,\\infty)$.\n", "The integral $\\int_{-\\infty}^{\\infty}\\exp{\\left(-(x^2\\right)}dx$ appears in many calculations, its value\n", "is $\\sqrt{\\pi}$, a result we will need when we compute the mean value and the variance.\n", "The mean value is" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "$$\n", "\\mu = \\int_0^{\\infty}xp(x)dx=\\frac{1}{b\\sqrt{2\\pi}}\\int_{-\\infty}^{\\infty}x \\exp{\\left(-\\frac{(x-a)^2}{2b^2}\\right)}dx,\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "which becomes with a suitable change of variables" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "$$\n", "\\mu =\\frac{1}{b\\sqrt{2\\pi}}\\int_{-\\infty}^{\\infty}b\\sqrt{2}(a+b\\sqrt{2}y)\\exp{-y^2}dy=a.\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Probability Distribution Functions, the normal distribution\n", "\n", "Similarly, the variance becomes" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "$$\n", "\\sigma^2 = \\frac{1}{b\\sqrt{2\\pi}}\\int_{-\\infty}^{\\infty}(x-\\mu)^2 \\exp{\\left(-\\frac{(x-a)^2}{2b^2}\\right)}dx,\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "and inserting the mean value and performing a variable change we obtain" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "$$\n", "\\sigma^2 = \\frac{1}{b\\sqrt{2\\pi}}\\int_{-\\infty}^{\\infty}b\\sqrt{2}(b\\sqrt{2}y)^2\\exp{\\left(-y^2\\right)}dy=\n", "\\frac{2b^2}{\\sqrt{\\pi}}\\int_{-\\infty}^{\\infty}y^2\\exp{\\left(-y^2\\right)}dy,\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "and performing a final integration by parts we obtain the well-known result $\\sigma^2=b^2$.\n", "It is useful to introduce the standard normal distribution as well, defined by $\\mu=a=0$, viz. a distribution\n", "centered around zero and with a variance $\\sigma^2=1$, leading to" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "\n", "
\n", "\n", "$$\n", "\\begin{equation}\n", " p(x)=\\frac{1}{\\sqrt{2\\pi}}\\exp{\\left(-\\frac{x^2}{2}\\right)}.\n", "\\label{_auto8} \\tag{12}\n", "\\end{equation}\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Probability Distribution Functions, the cumulative distribution\n", "\n", "\n", "The exponential and uniform distributions have simple cumulative functions,\n", "whereas the normal distribution does not, being proportional to the so-called\n", "error function $erf(x)$, given by" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "$$\n", "P(x) = \\frac{1}{\\sqrt{2\\pi}}\\int_{-\\infty}^x\\exp{\\left(-\\frac{t^2}{2}\\right)}dt,\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "which is difficult to evaluate in a quick way. \n", "\n", "\n", "\n", "\n", "## Probability Distribution Functions, other important distribution\n", "\n", "\n", "Some other PDFs which one encounters often in the natural sciences are the binomial distribution" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "$$\n", "p(x) = \\left(\\begin{array}{c} n \\\\ x\\end{array}\\right)y^x(1-y)^{n-x} \\hspace{0.5cm}x=0,1,\\dots,n,\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "where $y$ is the probability for a specific event, such as the tossing of a coin or moving left or right\n", "in case of a random walker. Note that $x$ is a discrete stochastic variable. \n", "\n", "The sequence of binomial trials is characterized by the following definitions\n", "\n", " * Every experiment is thought to consist of $N$ independent trials.\n", "\n", " * In every independent trial one registers if a specific situation happens or not, such as the jump to the left or right of a random walker.\n", "\n", " * The probability for every outcome in a single trial has the same value, for example the outcome of tossing (either heads or tails) a coin is always $1/2$.\n", "\n", "## Probability Distribution Functions, the binomial distribution\n", "\n", "\n", "In order to compute the mean and variance we need to recall Newton's binomial\n", "formula" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "$$\n", "(a+b)^m=\\sum_{n=0}^m \\left(\\begin{array}{c} m \\\\ n\\end{array}\\right)a^nb^{m-n},\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "which can be used to show that" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "$$\n", "\\sum_{x=0}^n\\left(\\begin{array}{c} n \\\\ x\\end{array}\\right)y^x(1-y)^{n-x} = (y+1-y)^n = 1,\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "the PDF is normalized to one. \n", "The mean value is" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "$$\n", "\\mu = \\sum_{x=0}^n x\\left(\\begin{array}{c} n \\\\ x\\end{array}\\right)y^x(1-y)^{n-x} =\n", "\\sum_{x=0}^n x\\frac{n!}{x!(n-x)!}y^x(1-y)^{n-x},\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "resulting in" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "$$\n", "\\mu = \n", "\\sum_{x=0}^n x\\frac{(n-1)!}{(x-1)!(n-1-(x-1))!}y^{x-1}(1-y)^{n-1-(x-1)},\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "which we rewrite as" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "$$\n", "\\mu=ny\\sum_{\\nu=0}^n\\left(\\begin{array}{c} n-1 \\\\ \\nu\\end{array}\\right)y^{\\nu}(1-y)^{n-1-\\nu} =ny(y+1-y)^{n-1}=ny.\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "The variance is slightly trickier to get. It reads $\\sigma^2=ny(1-y)$. \n", "\n", "\n", "## Probability Distribution Functions, Poisson's distribution\n", "\n", "\n", "Another important distribution with discrete stochastic variables $x$ is \n", "the Poisson model, which resembles the exponential distribution and reads" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "$$\n", "p(x) = \\frac{\\lambda^x}{x!} e^{-\\lambda} \\hspace{0.5cm}x=0,1,\\dots,;\\lambda > 0.\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "In this case both the mean value and the variance are easier to calculate," ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "$$\n", "\\mu = \\sum_{x=0}^{\\infty} x \\frac{\\lambda^x}{x!} e^{-\\lambda} = \\lambda e^{-\\lambda}\\sum_{x=1}^{\\infty}\n", "\\frac{\\lambda^{x-1}}{(x-1)!}=\\lambda,\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "and the variance is $\\sigma^2=\\lambda$. \n", "\n", "\n", "\n", "\n", "\n", "## Probability Distribution Functions, Poisson's distribution\n", "\n", "An example of applications of the Poisson distribution could be the counting\n", "of the number of $\\alpha$-particles emitted from a radioactive source in a given time interval.\n", "In the limit of $n\\rightarrow \\infty$ and for small probabilities $y$, the binomial distribution\n", "approaches the Poisson distribution. Setting $\\lambda = ny$, with $y$ the probability for an event in\n", "the binomial distribution we can show that" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "$$\n", "\\lim_{n\\rightarrow \\infty}\\left(\\begin{array}{c} n \\\\ x\\end{array}\\right)y^x(1-y)^{n-x} e^{-\\lambda}=\\sum_{x=1}^{\\infty}\\frac{\\lambda^x}{x!} e^{-\\lambda}.\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Meet the covariance!\n", "\n", "An important quantity in a statistical analysis is the so-called covariance. \n", "\n", "Consider the set $\\{X_i\\}$ of $n$\n", "stochastic variables (not necessarily uncorrelated) with the\n", "multivariate PDF $P(x_1,\\dots,x_n)$. The *covariance* of two\n", "of the stochastic variables, $X_i$ and $X_j$, is defined as follows" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "\n", "
\n", "\n", "$$\n", "\\begin{equation}\n", "\\mathrm{Cov}(X_i,\\,X_j) = \\langle (x_i-\\langle x_i\\rangle)(x_j-\\langle x_j\\rangle)\\rangle \n", "\\label{_auto9} \\tag{13}\n", "\\end{equation}\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "\n", "
\n", "\n", "$$\n", "\\begin{equation} \n", "=\\int\\cdots\\int (x_i-\\langle x_i\\rangle)(x_j-\\langle x_j\\rangle)P(x_1,\\dots,x_n)\\,dx_1\\dots dx_n,\n", "\\label{eq:def_covariance} \\tag{14}\n", "\\end{equation}\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "with" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "$$\n", "\\langle x_i\\rangle =\n", "\\int\\cdots\\int x_i P(x_1,\\dots,x_n)\\,dx_1\\dots dx_n.\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Meet the covariance in matrix disguise\n", "\n", "If we consider the above covariance as a matrix" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "$$\n", "C_{ij} =\\mathrm{Cov}(X_i,\\,X_j),\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "then the diagonal elements are just the familiar\n", "variances, $C_{ii} = \\mathrm{Cov}(X_i,\\,X_i) = \\mathrm{Var}(X_i)$. It turns out that\n", "all the off-diagonal elements are zero if the stochastic variables are\n", "uncorrelated. \n", "\n", "\n", "\n", "## Covariance" ] }, { "cell_type": "code", "execution_count": 30, "metadata": { "collapsed": false }, "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", "def covariance(x, y, n):\n", " sum = 0.0\n", " mean_x = np.mean(x)\n", " mean_y = np.mean(y)\n", " for i in range(0, n):\n", " sum += (x[(i)]-mean_x)*(y[i]-mean_y)\n", " return sum/n\n", "\n", "n = 10\n", "\n", "x=np.random.normal(size=n)\n", "y = 4+3*x+np.random.normal(size=n)\n", "covxy = covariance(x,y,n)\n", "print(covxy)\n", "z = np.vstack((x, y))\n", "c = np.cov(z.T)\n", "\n", "print(c)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Meet the covariance, uncorrelated events\n", "\n", "\n", "Consider the stochastic variables $X_i$ and $X_j$, ($i\\neq j$). We have" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "$$\n", "\\begin{align*}\n", "Cov(X_i,\\,X_j) &= \\langle (x_i-\\langle x_i\\rangle)(x_j-\\langle x_j\\rangle)\\rangle\\\\\n", "&=\\langle x_i x_j - x_i\\langle x_j\\rangle - \\langle x_i\\rangle x_j + \\langle x_i\\rangle\\langle x_j\\rangle\\rangle\\\\\n", "&=\\langle x_i x_j\\rangle - \\langle x_i\\langle x_j\\rangle\\rangle - \\langle \\langle x_i\\rangle x_j \\rangle +\n", "\\langle \\langle x_i\\rangle\\langle x_j\\rangle\\rangle \\\\\n", "&=\\langle x_i x_j\\rangle - \\langle x_i\\rangle\\langle x_j\\rangle - \\langle x_i\\rangle\\langle x_j\\rangle +\n", "\\langle x_i\\rangle\\langle x_j\\rangle \\\\\n", "&=\\langle x_i x_j\\rangle - \\langle x_i\\rangle\\langle x_j\\rangle\n", "\\end{align*}\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "If $X_i$ and $X_j$ are independent (assuming $i \\neq j$), we have that" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "$$\n", "\\langle x_i x_j\\rangle = \\langle x_i\\rangle\\langle x_j\\rangle,\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "leading to" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "$$\n", "Cov(X_i, X_j) = 0 \\hspace{0.1cm} (i\\neq j).\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Numerical experiments and the covariance\n", "\n", "\n", "Now that we have constructed an idealized mathematical framework, let\n", "us try to apply it to empirical observations. Examples of relevant\n", "physical phenomena may be spontaneous decays of nuclei, or a purely\n", "mathematical set of numbers produced by some deterministic\n", "mechanism. It is the latter we will deal with, using so-called pseudo-random\n", "number generators. In general our observations will contain only a limited set of\n", "observables. We remind the reader that\n", "a *stochastic process* is a process that produces sequentially a\n", "chain of values" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "$$\n", "\\{x_1, x_2,\\dots\\,x_k,\\dots\\}.\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Numerical experiments and the covariance\n", "\n", "We will call these\n", "values our *measurements* and the entire set as our measured\n", "*sample*. The action of measuring all the elements of a sample\n", "we will call a stochastic *experiment* (since, operationally,\n", "they are often associated with results of empirical observation of\n", "some physical or mathematical phenomena; precisely an experiment). We\n", "assume that these values are distributed according to some \n", "PDF $p_X^{\\phantom X}(x)$, where $X$ is just the formal symbol for the\n", "stochastic variable whose PDF is $p_X^{\\phantom X}(x)$. Instead of\n", "trying to determine the full distribution $p$ we are often only\n", "interested in finding the few lowest moments, like the mean\n", "$\\mu_X^{\\phantom X}$ and the variance $\\sigma_X^{\\phantom X}$.\n", "\n", "\n", "\n", "\n", "## Numerical experiments and the covariance, actual situations\n", "\n", "In practical situations however, a sample is always of finite size. Let that\n", "size be $n$. The expectation value of a sample $\\alpha$, the **sample mean**, is then defined as follows" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "$$\n", "\\langle x_{\\alpha} \\rangle \\equiv \\frac{1}{n}\\sum_{k=1}^n x_{\\alpha,k}.\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "The *sample variance* is:" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "$$\n", "\\mathrm{Var}(x) \\equiv \\frac{1}{n}\\sum_{k=1}^n (x_{\\alpha,k} - \\langle x_{\\alpha} \\rangle)^2,\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "with its square root being the *standard deviation of the sample*. \n", "\n", "\n", "\n", "\n", "## Numerical experiments and the covariance, our observables\n", "\n", "You can think of the above observables as a set of quantities which define\n", "a given experiment. This experiment is then repeated several times, say $m$ times.\n", "The total average is then" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "\n", "
\n", "\n", "$$\n", "\\begin{equation}\n", "\\langle X_m \\rangle= \\frac{1}{m}\\sum_{\\alpha=1}^mx_{\\alpha}=\\frac{1}{mn}\\sum_{\\alpha, k} x_{\\alpha,k},\n", "\\label{eq:exptmean} \\tag{15}\n", "\\end{equation}\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "where the last sums end at $m$ and $n$.\n", "The total variance is" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "$$\n", "\\sigma^2_m= \\frac{1}{mn^2}\\sum_{\\alpha=1}^m(\\langle x_{\\alpha} \\rangle-\\langle X_m \\rangle)^2,\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "which we rewrite as" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "\n", "
\n", "\n", "$$\n", "\\begin{equation}\n", "\\sigma^2_m=\\frac{1}{m}\\sum_{\\alpha=1}^m\\sum_{kl=1}^n (x_{\\alpha,k}-\\langle X_m \\rangle)(x_{\\alpha,l}-\\langle X_m \\rangle).\n", "\\label{eq:exptvariance} \\tag{16}\n", "\\end{equation}\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Numerical experiments and the covariance, the sample variance\n", "\n", "\n", "We define also the sample variance $\\sigma^2$ of all $mn$ individual experiments as" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "\n", "
\n", "\n", "$$\n", "\\begin{equation}\n", "\\sigma^2=\\frac{1}{mn}\\sum_{\\alpha=1}^m\\sum_{k=1}^n (x_{\\alpha,k}-\\langle X_m \\rangle)^2.\n", "\\label{eq:sampleexptvariance} \\tag{17}\n", "\\end{equation}\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "These quantities, being known experimental values or the results from our calculations, \n", "may differ, in some cases\n", "significantly, from the similarly named\n", "exact values for the mean value $\\mu_X$, the variance $\\mathrm{Var}(X)$\n", "and the covariance $\\mathrm{Cov}(X,Y)$. \n", "\n", "\n", "\n", "## Numerical experiments and the covariance, central limit theorem\n", "\n", "\n", "The central limit theorem states that the PDF $\\tilde{p}(z)$ of\n", "the average of $m$ random values corresponding to a PDF $p(x)$ \n", "is a normal distribution whose mean is the \n", "mean value of the PDF $p(x)$ and whose variance is the variance\n", "of the PDF $p(x)$ divided by $m$, the number of values used to compute $z$.\n", "\n", "The central limit theorem leads then to the well-known expression for the\n", "standard deviation, given by" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "$$\n", "\\sigma_m=\n", "\\frac{\\sigma}{\\sqrt{m}}.\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "In many cases the above estimate for the standard deviation, in particular if correlations are strong, may be too simplistic. We need therefore a more precise defintion of the error and the variance in our results.\n", "\n", "\n", "\n", "## Definition of Correlation Functions and Standard Deviation\n", "\n", "Our estimate of the true average $\\mu_{X}$ is the sample mean $\\langle X_m \\rangle$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "$$\n", "\\mu_{X}^{\\phantom X} \\approx X_m=\\frac{1}{mn}\\sum_{\\alpha=1}^m\\sum_{k=1}^n x_{\\alpha,k}.\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "We can then use Eq. ([eq:exptvariance](#eq:exptvariance))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "$$\n", "\\sigma^2_m=\\frac{1}{mn^2}\\sum_{\\alpha=1}^m\\sum_{kl=1}^n (x_{\\alpha,k}-\\langle X_m \\rangle)(x_{\\alpha,l}-\\langle X_m \\rangle),\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "and rewrite it as" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "$$\n", "\\sigma^2_m=\\frac{\\sigma^2}{n}+\\frac{2}{mn^2}\\sum_{\\alpha=1}^m\\sum_{k\n", "
\n", "\n", "$$\n", "\\begin{equation}\n", "\\kappa_d = \\frac{f_d}{\\sigma^2}\n", "\\label{eq:autocorrelformal} \\tag{18}\n", "\\end{equation}\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "which gives us a useful measure of the correlation pair correlation\n", "starting always at $1$ for $d=0$.\n", "\n", "\n", "\n", "## Definition of Correlation Functions and Standard Deviation, sample variance\n", "\n", "\n", "The sample variance of the $mn$ experiments can now be\n", "written in terms of the autocorrelation function" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "\n", "
\n", "\n", "$$\n", "\\begin{equation}\n", "\\sigma_m^2=\\frac{\\sigma^2}{n}+\\frac{2}{n}\\cdot\\sigma^2\\sum_{d=1}^{n-1}\n", "\\frac{f_d}{\\sigma^2}=\\left(1+2\\sum_{d=1}^{n-1}\\kappa_d\\right)\\frac{1}{n}\\sigma^2=\\frac{\\tau}{n}\\cdot\\sigma^2\n", "\\label{eq:error_estimate_corr_time} \\tag{19}\n", "\\end{equation}\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "and we see that $\\sigma_m$ can be expressed in terms of the\n", "uncorrelated sample variance times a correction factor $\\tau$ which\n", "accounts for the correlation between measurements. We call this\n", "correction factor the *autocorrelation time*" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "\n", "
\n", "\n", "$$\n", "\\begin{equation}\n", "\\tau = 1+2\\sum_{d=1}^{n-1}\\kappa_d\n", "\\label{eq:autocorrelation_time} \\tag{20}\n", "\\end{equation}\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "\n", "\n", "For a correlation free experiment, $\\tau$\n", "equals 1. \n", "\n", "\n", "\n", "\n", "\n", "## Definition of Correlation Functions and Standard Deviation\n", "\n", "From the point of view of\n", "Eq. ([eq:error_estimate_corr_time](#eq:error_estimate_corr_time)) we can interpret a sequential\n", "correlation as an effective reduction of the number of measurements by\n", "a factor $\\tau$. The effective number of measurements becomes" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "$$\n", "n_\\mathrm{eff} = \\frac{n}{\\tau}\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "To neglect the autocorrelation time $\\tau$ will always cause our\n", "simple uncorrelated estimate of $\\sigma_m^2\\approx \\sigma^2/n$ to\n", "be less than the true sample error. The estimate of the error will be\n", "too \"good\". On the other hand, the calculation of the full\n", "autocorrelation time poses an efficiency problem if the set of\n", "measurements is very large. The solution to this problem is given by \n", "more practically oriented methods like the blocking technique.\n", "\n", "\n", "\n", "\n", "\n", "## Code to compute the Covariance matrix and the Covariance" ] }, { "cell_type": "code", "execution_count": 31, "metadata": { "collapsed": false }, "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", "# Sample covariance, note the factor 1/(n-1)\n", "def covariance(x, y, n):\n", " sum = 0.0\n", " mean_x = np.mean(x)\n", " mean_y = np.mean(y)\n", " for i in range(0, n):\n", " sum += (x[(i)]-mean_x)*(y[i]-mean_y)\n", " return sum/(n-1.)\n", "\n", "n = 100\n", "x = np.random.normal(size=n)\n", "print(np.mean(x))\n", "y = 4+3*x+np.random.normal(size=n)\n", "print(np.mean(y))\n", "z = x**3+np.random.normal(size=n)\n", "print(np.mean(z))\n", "covxx = covariance(x,x,n)\n", "covyy = covariance(y,y,n)\n", "covzz = covariance(z,z,n)\n", "covxy = covariance(x,y,n)\n", "covxz = covariance(x,z,n)\n", "covyz = covariance(y,z,n)\n", "print(covxx,covyy, covzz)\n", "print(covxy,covxz, covyz)\n", "w = np.vstack((x, y, z))\n", "#print(w)\n", "c = np.cov(w)\n", "print(c)\n", "#eigen = np.zeros(n)\n", "Eigvals, Eigvecs = np.linalg.eig(c)\n", "print(Eigvals)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# Random Numbers\n", "\n", "\n", "Uniform deviates are just random numbers that lie within a specified range\n", "(typically 0 to 1), with any one number in the range just as likely as any other. They\n", "are, in other words, what you probably think random numbers are. However,\n", "we want to distinguish uniform deviates from other sorts of random numbers, for\n", "example numbers drawn from a normal (Gaussian) distribution of specified mean\n", "and standard deviation. These other sorts of deviates are almost always generated by\n", "performing appropriate operations on one or more uniform deviates, as we will see\n", "in subsequent sections. So, a reliable source of random uniform deviates, the subject\n", "of this section, is an essential building block for any sort of stochastic modeling\n", "or Monte Carlo computer work.\n", "\n", "\n", "\n", "\n", "# Random Numbers, better name: pseudo random numbers\n", "\n", "\n", "A disclaimer is however appropriate. It should be fairly obvious that \n", "something as deterministic as a computer cannot generate purely random numbers.\n", "\n", "Numbers generated by any of the standard algorithms are in reality pseudo random\n", "numbers, hopefully abiding to the following criteria:\n", "\n", " * they produce a uniform distribution in the interval [0,1].\n", "\n", " * correlations between random numbers are negligible\n", "\n", " * the period before the same sequence of random numbers is repeated is as large as possible and finally\n", "\n", " * the algorithm should be fast.\n", "\n", "# Random number generator RNG\n", "\n", " The most common random number generators are based on so-called\n", "Linear congruential relations of the type" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "$$\n", "N_i=(aN_{i-1}+c) \\mathrm{MOD} (M),\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "which yield a number in the interval [0,1] through" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "$$\n", "x_i=N_i/M\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "The number \n", "$M$ is called the period and it should be as large as possible \n", " and \n", "$N_0$ is the starting value, or seed. The function $\\mathrm{MOD}$ means the remainder,\n", "that is if we were to evaluate $(13)\\mathrm{MOD}(9)$, the outcome is the remainder\n", "of the division $13/9$, namely $4$.\n", "\n", "\n", "\n", "# Random number generator RNG and periodic outputs\n", "\n", "\n", "The problem with such generators is that their outputs are periodic;\n", "they \n", "will start to repeat themselves with a period that is at most $M$. If however\n", "the parameters $a$ and $c$ are badly chosen, the period may be even shorter.\n", "\n", "Consider the following example" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "$$\n", "N_i=(6N_{i-1}+7) \\mathrm{MOD} (5),\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "with a seed $N_0=2$. This generator produces the sequence\n", "$4,1,3,0,2,4,1,3,0,2,...\\dots$, i.e., a sequence with period $5$.\n", "However, increasing $M$ may not guarantee a larger period as the following\n", "example shows" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "$$\n", "N_i=(27N_{i-1}+11) \\mathrm{MOD} (54),\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "which still, with $N_0=2$, results in $11,38,11,38,11,38,\\dots$, a period of\n", "just $2$.\n", "\n", "\n", "\n", "# Random number generator RNG and its period\n", "\n", "Typical periods for the random generators provided in the program library \n", "are of the order of $\\sim 10^9$ or larger. Other random number generators which have\n", "become increasingly popular are so-called shift-register generators.\n", "In these generators each successive number depends on many preceding\n", "values (rather than the last values as in the linear congruential\n", "generator).\n", "For example, you could make a shift register generator whose $l$th \n", "number is the sum of the $l-i$th and $l-j$th values with modulo $M$," ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "$$\n", "N_l=(aN_{l-i}+cN_{l-j})\\mathrm{MOD}(M).\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# Random number generator RNG, other examples\n", "\n", "Such a generator again produces a sequence of pseudorandom numbers\n", "but this time with a period much larger than $M$.\n", "It is also possible to construct more elaborate algorithms by including\n", "more than two past terms in the sum of each iteration.\n", "One example is the generator of [Marsaglia and Zaman](http://dl.acm.org/citation.cfm?id=187154)\n", "which consists of two congruential relations" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "\n", "
\n", "\n", "$$\n", "\\begin{equation}\n", " N_l=(N_{l-3}-N_{l-1})\\mathrm{MOD}(2^{31}-69),\n", "\\label{eq:mz1} \\tag{21}\n", "\\end{equation}\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "followed by" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "\n", "
\n", "\n", "$$\n", "\\begin{equation}\n", " N_l=(69069N_{l-1}+1013904243)\\mathrm{MOD}(2^{32}),\n", "\\label{eq:mz2} \\tag{22}\n", "\\end{equation}\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "which according to the authors has a period larger than $2^{94}$.\n", "\n", "\n", "\n", "# Random number generator RNG, other examples\n", "\n", "Instead of using modular addition, we could use the bitwise\n", "exclusive-OR ($\\oplus$) operation so that" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "$$\n", "N_l=(N_{l-i})\\oplus (N_{l-j})\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "where the bitwise action of $\\oplus$ means that if $N_{l-i}=N_{l-j}$ the result is\n", "$0$ whereas if $N_{l-i}\\ne N_{l-j}$ the result is\n", "$1$. As an example, consider the case where $N_{l-i}=6$ and $N_{l-j}=11$. The first\n", "one has a bit representation (using 4 bits only) which reads $0110$ whereas the \n", "second number is $1011$. Employing the $\\oplus$ operator yields \n", "$1101$, or $2^3+2^2+2^0=13$.\n", "\n", "In Fortran90, the bitwise $\\oplus$ operation is coded through the intrinsic\n", "function $\\mathrm{IEOR}(m,n)$ where $m$ and $n$ are the input numbers, while in $C$\n", "it is given by $m\\wedge n$. \n", "\n", "\n", "\n", "\n", "# Random number generator RNG, RAN0\n", "\n", "\n", "We show here how the linear congruential algorithm can be implemented, namely" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "$$\n", "N_i=(aN_{i-1}) \\mathrm{MOD} (M).\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "However, since $a$ and $N_{i-1}$ are integers and their multiplication \n", "could become greater than the standard 32 bit integer, there is a trick via \n", "Schrage's algorithm which approximates the multiplication\n", "of large integers through the factorization" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "$$\n", "M=aq+r,\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "where we have defined" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "$$\n", "q=[M/a],\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "and" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "$$\n", "r = M\\hspace{0.1cm}\\mathrm{MOD} \\hspace{0.1cm}a.\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "where the brackets denote integer division. In the code below the numbers \n", "$q$ and $r$ are chosen so that $r < q$.\n", "\n", "\n", "\n", "\n", "\n", "# Random number generator RNG, RAN0\n", "\n", "\n", "To see how this works we note first that" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "\n", "
\n", "\n", "$$\n", "\\begin{equation}\n", "(aN_{i-1}) \\mathrm{MOD} (M)= (aN_{i-1}-[N_{i-1}/q]M)\\mathrm{MOD} (M),\n", "\\label{eq:rntrick1} \\tag{23}\n", "\\end{equation}\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "since we can add or subtract any integer multiple of $M$ from $aN_{i-1}$.\n", "The last term $[N_{i-1}/q]M\\mathrm{MOD}(M)$ is zero since the integer division \n", "$[N_{i-1}/q]$ just yields a constant which is multiplied with $M$. \n", "\n", "\n", "\n", "\n", "# Random number generator RNG, RAN0\n", "\n", "We can now rewrite Eq. ([eq:rntrick1](#eq:rntrick1)) as" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "\n", "
\n", "\n", "$$\n", "\\begin{equation}\n", "(aN_{i-1}) \\mathrm{MOD} (M)= (aN_{i-1}-[N_{i-1}/q](aq+r))\\mathrm{MOD} (M),\n", "\\label{eq:rntrick2} \\tag{24}\n", "\\end{equation}\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "which results\n", "in" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "\n", "
\n", "\n", "$$\n", "\\begin{equation}\n", "(aN_{i-1}) \\mathrm{MOD} (M)= \\left(a(N_{i-1}-[N_{i-1}/q]q)-[N_{i-1}/q]r)\\right)\\mathrm{MOD} (M),\n", "\\label{eq:rntrick3} \\tag{25}\n", "\\end{equation}\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "yielding" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "\n", "
\n", "\n", "$$\n", "\\begin{equation}\n", "(aN_{i-1}) \\mathrm{MOD} (M)= \\left(a(N_{i-1}\\mathrm{MOD} (q)) -[N_{i-1}/q]r)\\right)\\mathrm{MOD} (M).\n", "\\label{eq:rntrick4} \\tag{26}\n", "\\end{equation}\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# Random number generator RNG, RAN0\n", "\n", "The term $[N_{i-1}/q]r$ is always smaller or equal $N_{i-1}(r/q)$ and with $r < q$ we obtain always a \n", "number smaller than $N_{i-1}$, which is smaller than $M$. \n", "And since the number $N_{i-1}\\mathrm{MOD} (q)$ is between zero and $q-1$ then\n", "$a(N_{i-1}\\mathrm{MOD} (q))< aq$. Combined with our definition of $q=[M/a]$ ensures that \n", "this term is also smaller than $M$ meaning that both terms fit into a\n", "32-bit signed integer. None of these two terms can be negative, but their difference could.\n", "The algorithm below adds $M$ if their difference is negative.\n", "Note that the program uses the bitwise $\\oplus$ operator to generate\n", "the starting point for each generation of a random number. The period\n", "of $ran0$ is $\\sim 2.1\\times 10^{9}$. A special feature of this\n", "algorithm is that is should never be called with the initial seed \n", "set to $0$. \n", "\n", "\n", "\n", "\n", "# Random number generator RNG, RAN0 code" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ " /*\n", " ** The function\n", " ** ran0()\n", " ** is an \"Minimal\" random number generator of Park and Miller\n", " ** Set or reset the input value\n", " ** idum to any integer value (except the unlikely value MASK)\n", " ** to initialize the sequence; idum must not be altered between\n", " ** calls for sucessive deviates in a sequence.\n", " ** The function returns a uniform deviate between 0.0 and 1.0.\n", " */\n", " double ran0(long &idum)\n", " {\n", " const int a = 16807, m = 2147483647, q = 127773;\n", " const int r = 2836, MASK = 123459876;\n", " const double am = 1./m;\n", " long k;\n", " double ans;\n", " idum ^= MASK;\n", " k = (*idum)/q;\n", " idum = a*(idum - k*q) - r*k;\n", " // add m if negative difference\n", " if(idum < 0) idum += m;\n", " ans=am*(idum);\n", " idum ^= MASK;\n", " return ans;\n", " } // End: function ran0() \n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Properties of Selected Random Number Generators\n", "\n", "\n", "As mentioned previously, the underlying PDF for the generation of\n", "random numbers is the uniform distribution, meaning that the \n", "probability for finding a number $x$ in the interval [0,1] is $p(x)=1$.\n", "\n", "A random number generator should produce numbers which are uniformly distributed\n", "in this interval. The table shows the distribution of $N=10000$ random\n", "numbers generated by the functions in the program library.\n", "We note in this table that the number of points in the various\n", "intervals $0.0-0.1$, $0.1-0.2$ etc are fairly close to $1000$, with some minor\n", "deviations. \n", "\n", "Two additional measures are the standard deviation $\\sigma$ and the mean\n", "$\\mu=\\langle x\\rangle$.\n", "\n", "\n", "\n", "## Properties of Selected Random Number Generators\n", "\n", "For the uniform distribution, the mean value $\\mu$ is then" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "$$\n", "\\mu=\\langle x\\rangle=\\frac{1}{2}\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "while the standard deviation is" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "$$\n", "\\sigma=\\sqrt{\\langle x^2\\rangle-\\mu^2}=\\frac{1}{\\sqrt{12}}=0.2886.\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Properties of Selected Random Number Generators\n", "\n", "The various random number generators produce results which agree rather well with\n", "these limiting values. \n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "
$x$-bin ran0 ran1 ran2 ran3
0.0-0.1 1013 991 938 1047
0.1-0.2 1002 1009 1040 1030
0.2-0.3 989 999 1030 993
0.3-0.4 939 960 1023 937
0.4-0.5 1038 1001 1002 992
0.5-0.6 1037 1047 1009 1009
0.6-0.7 1005 989 1003 989
0.7-0.8 986 962 985 954
0.8-0.9 1000 1027 1009 1023
0.9-1.0 991 1015 961 1026
$\\mu$ 0.4997 0.5018 0.4992 0.4990
$\\sigma$ 0.2882 0.2892 0.2861 0.2915
\n", "\n", "\n", "\n", "## Simple demonstration of RNGs using python\n", "\n", "The following simple Python code plots the distribution of the produced random numbers using the linear congruential RNG employed by Python. The trend displayed in the previous table is seen rather clearly." ] }, { "cell_type": "code", "execution_count": 32, "metadata": { "collapsed": false }, "outputs": [], "source": [ "#!/usr/bin/env python\n", "import numpy as np\n", "import matplotlib.mlab as mlab\n", "import matplotlib.pyplot as plt\n", "import random\n", "\n", "# initialize the rng with a seed\n", "random.seed() \n", "counts = 10000\n", "values = np.zeros(counts) \n", "for i in range (1, counts, 1):\n", " values[i] = random.random()\n", "\n", "# the histogram of the data\n", "n, bins, patches = plt.hist(values, 10, facecolor='green')\n", "\n", "plt.xlabel('$x$')\n", "plt.ylabel('Number of counts')\n", "plt.title(r'Test of uniform distribution')\n", "plt.axis([0, 1, 0, 1100])\n", "plt.grid(True)\n", "plt.show()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Properties of Selected Random Number Generators\n", "\n", "Since our random numbers, which are typically generated via a linear congruential algorithm,\n", "are never fully independent, we can then define \n", "an important test which measures the degree of correlation, namely the so-called \n", "auto-correlation function defined previously, see again Eq. ([eq:autocorrelformal](#eq:autocorrelformal)).\n", "We rewrite it here as" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "$$\n", "C_k=\\frac{f_d}\n", " {\\sigma^2},\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "with $C_0=1$. Recall that \n", "$\\sigma^2=\\langle x_i^2\\rangle-\\langle x_i\\rangle^2$ and that" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "$$\n", "f_d = \\frac{1}{nm}\\sum_{\\alpha=1}^m\\sum_{k=1}^{n-d}(x_{\\alpha,k}-\\langle X_m \\rangle)(x_{\\alpha,k+d}-\\langle X_m \\rangle),\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "The non-vanishing of $C_k$ for $k\\ne 0$ means that the random\n", "numbers are not independent. The independence of the random numbers is crucial \n", "in the evaluation of other expectation values. If they are not independent, our\n", "assumption for approximating $\\sigma_N$ is no longer valid.\n", "\n", "\n", "\n", "\n", "\n", "## Autocorrelation function\n", "This program computes the autocorrelation function as discussed in the equation on the previous slide for random numbers generated with the normal distribution $N(0,1)$." ] }, { "cell_type": "code", "execution_count": 33, "metadata": { "collapsed": false }, "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", "def autocovariance(x, n, k, mean_x):\n", " sum = 0.0\n", " for i in range(0, n-k):\n", " sum += (x[(i+k)]-mean_x)*(x[i]-mean_x)\n", " return sum/n\n", "\n", "n = 1000\n", "x=np.random.normal(size=n)\n", "autocor = np.zeros(n)\n", "figaxis = np.zeros(n)\n", "mean_x=np.mean(x)\n", "var_x = np.var(x)\n", "print(mean_x, var_x)\n", "for i in range (0, n):\n", " figaxis[i] = i\n", " autocor[i]=(autocovariance(x, n, i, mean_x))/var_x \n", "\n", "plt.plot(figaxis, autocor, \"r-\")\n", "plt.axis([0,n,-0.1, 1.0])\n", "plt.xlabel(r'$i$')\n", "plt.ylabel(r'$\\gamma_i$')\n", "plt.title(r'Autocorrelation function')\n", "plt.show()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "As can be seen from the plot, the first point gives back the variance and a value of one. \n", "For the remaining values we notice that there are still non-zero values for the auto-correlation function.\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "## Correlation function and which random number generators should I use\n", "\n", "The program here computes the correlation function for one of the standard functions included with the c++ compiler." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ " // This function computes the autocorrelation function for \n", " // the standard c++ random number generator\n", " \n", " #include \n", " #include \n", " #include \n", " #include \n", " using namespace std;\n", " // output file as global variable\n", " ofstream ofile; \n", " \n", " // Main function begins here \n", " int main(int argc, char* argv[])\n", " {\n", " int n;\n", " char *outfilename;\n", " \n", " cin >> n;\n", " double MCint = 0.; double MCintsqr2=0.;\n", " double invers_period = 1./RAND_MAX; // initialise the random number generator\n", " srand(time(NULL)); // This produces the so-called seed in MC jargon\n", " // Compute the variance and the mean value of the uniform distribution\n", " // Compute also the specific values x for each cycle in order to be able to\n", " // the covariance and the correlation function \n", " // Read in output file, abort if there are too few command-line arguments\n", " if( argc <= 2 ){\n", " cout << \"Bad Usage: \" << argv[0] << \n", " \t \" read also output file and number of cycles on same line\" << endl;\n", " exit(1);\n", " }\n", " else{\n", " outfilename=argv[1];\n", " }\n", " ofile.open(outfilename); \n", " // Get the number of Monte-Carlo samples\n", " n = atoi(argv[2]);\n", " double *X; \n", " X = new double[n];\n", " for (int i = 0; i < n; i++){\n", " double x = double(rand())*invers_period; \n", " X[i] = x;\n", " MCint += x;\n", " MCintsqr2 += x*x;\n", " }\n", " double Mean = MCint/((double) n );\n", " MCintsqr2 = MCintsqr2/((double) n );\n", " double STDev = sqrt(MCintsqr2-Mean*Mean);\n", " double Variance = MCintsqr2-Mean*Mean;\n", " // Write mean value and standard deviation \n", " cout << \" Standard deviation= \" << STDev << \" Integral = \" << Mean << endl;\n", " \n", " // Now we compute the autocorrelation function\n", " double *autocor; autocor = new double[n];\n", " for (int j = 0; j < n; j++){\n", " double sum = 0.0;\n", " for (int k = 0; k < (n-j); k++){\n", " \t sum += (X[k]-Mean)*(X[k+j]-Mean); \n", " }\n", " autocor[j] = sum/Variance/((double) n );\n", " ofile << setiosflags(ios::showpoint | ios::uppercase);\n", " ofile << setw(15) << setprecision(8) << j;\n", " ofile << setw(15) << setprecision(8) << autocor[j] << endl;\n", " }\n", " ofile.close(); // close output file\n", " return 0;\n", " } // end of main program \n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# Which RNG should I use?\n", "\n", "* C++ has a class called **random**. The [random class](http://www.cplusplus.com/reference/random/) contains a large selection of RNGs and is highly recommended. Some of these RNGs have very large periods making it thereby very safe to use these RNGs in case one is performing large calculations. In particular, the [Mersenne twister random number engine](http://www.cplusplus.com/reference/random/mersenne_twister_engine/) has a period of $2^{19937}$. \n", "\n", "* Add RNGs in Python\n", "\n", "## How to use the Mersenne generator\n", "\n", "The following part of a c++ code (from project 4) sets up the uniform distribution for $x\\in [0,1]$." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ " /*\n", " \n", " // You need this \n", " #include \n", " \n", " // Initialize the seed and call the Mersienne algo\n", " std::random_device rd;\n", " std::mt19937_64 gen(rd());\n", " // Set up the uniform distribution for x \\in [[0, 1]\n", " std::uniform_real_distribution RandomNumberGenerator(0.0,1.0);\n", " \n", " // Now use the RNG\n", " int ix = (int) (RandomNumberGenerator(gen)*NSpins);\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Why blocking?\n", " Statistical analysis\n", " * Monte Carlo simulations can be treated as *computer experiments*\n", "\n", " * The results can be analysed with the same statistical tools as we would use analysing experimental data.\n", "\n", " * As in all experiments, we are looking for expectation values and an estimate of how accurate they are, i.e., possible sources for errors.\n", "\n", "A very good article which explains blocking is H. Flyvbjerg and H. G. Petersen, *Error estimates on averages of correlated data*, [Journal of Chemical Physics 91, 461-466 (1989)](http://scitation.aip.org/content/aip/journal/jcp/91/1/10.1063/1.457480).\n", "\n", "\n", "\n", "\n", "\n", "\n", "## Why blocking?\n", " Statistical analysis\n", " * As in other experiments, Monte Carlo experiments have two classes of errors:\n", "\n", " * Statistical errors\n", "\n", " * Systematical errors\n", "\n", "\n", " * Statistical errors can be estimated using standard tools from statistics\n", "\n", " * Systematical errors are method specific and must be treated differently from case to case. (In VMC a common source is the step length or time step in importance sampling)\n", "\n", "## Code to demonstrate the calculation of the autocorrelation function\n", "The following code computes the autocorrelation function, the covariance and the standard deviation\n", "for standard RNG. \n", "The [following file](https://github.com/CompPhysics/ComputationalPhysics2/tree/gh-pages/doc/Programs/LecturePrograms/programs/Blocking/autocorrelation.cpp) gives the code." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ " // This function computes the autocorrelation function for \n", " // the Mersenne random number generator with a uniform distribution\n", " #include \n", " #include \n", " #include \n", " #include \n", " #include \n", " #include \n", " #include \n", " #include \n", " using namespace std;\n", " using namespace arma;\n", " // output file\n", " ofstream ofile;\n", " \n", " // Main function begins here \n", " int main(int argc, char* argv[])\n", " {\n", " int MonteCarloCycles;\n", " string filename;\n", " if (argc > 1) {\n", " filename=argv[1];\n", " MonteCarloCycles = atoi(argv[2]);\n", " string fileout = filename;\n", " string argument = to_string(MonteCarloCycles);\n", " fileout.append(argument);\n", " ofile.open(fileout);\n", " }\n", " \n", " // Compute the variance and the mean value of the uniform distribution\n", " // Compute also the specific values x for each cycle in order to be able to\n", " // compute the covariance and the correlation function \n", " \n", " vec X = zeros(MonteCarloCycles);\n", " double MCint = 0.; double MCintsqr2=0.;\n", " std::random_device rd;\n", " std::mt19937_64 gen(rd());\n", " // Set up the uniform distribution for x \\in [[0, 1]\n", " std::uniform_real_distribution RandomNumberGenerator(0.0,1.0);\n", " for (int i = 0; i < MonteCarloCycles; i++){\n", " double x = RandomNumberGenerator(gen); \n", " X(i) = x;\n", " MCint += x;\n", " MCintsqr2 += x*x;\n", " }\n", " double Mean = MCint/((double) MonteCarloCycles );\n", " MCintsqr2 = MCintsqr2/((double) MonteCarloCycles );\n", " double STDev = sqrt(MCintsqr2-Mean*Mean);\n", " double Variance = MCintsqr2-Mean*Mean;\n", " // Write mean value and variance\n", " cout << \" Sample variance= \" << Variance << \" Mean value = \" << Mean << endl;\n", " // Now we compute the autocorrelation function\n", " vec autocorrelation = zeros(MonteCarloCycles);\n", " for (int j = 0; j < MonteCarloCycles; j++){\n", " double sum = 0.0;\n", " for (int k = 0; k < (MonteCarloCycles-j); k++){\n", " sum += (X(k)-Mean)*(X(k+j)-Mean); \n", " }\n", " autocorrelation(j) = sum/Variance/((double) MonteCarloCycles );\n", " ofile << setiosflags(ios::showpoint | ios::uppercase);\n", " ofile << setw(15) << setprecision(8) << j;\n", " ofile << setw(15) << setprecision(8) << autocorrelation(j) << endl;\n", " }\n", " // Now compute the exact covariance using the autocorrelation function\n", " double Covariance = 0.0;\n", " for (int j = 0; j < MonteCarloCycles; j++){\n", " Covariance += autocorrelation(j);\n", " }\n", " Covariance *= 2.0/((double) MonteCarloCycles);\n", " // Compute now the total variance, including the covariance, and obtain the standard deviation\n", " double TotalVariance = (Variance/((double) MonteCarloCycles ))+Covariance;\n", " cout << \"Covariance =\" << Covariance << \"Totalvariance= \" << TotalVariance << \"Sample Variance/n= \" << (Variance/((double) MonteCarloCycles )) << endl;\n", " cout << \" STD from sample variance= \" << sqrt(Variance/((double) MonteCarloCycles )) << \" STD with covariance = \" << sqrt(TotalVariance) << endl;\n", " \n", " ofile.close(); // close output file\n", " return 0;\n", " } // end of main program \n", " \n", " \n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## What is blocking?\n", " Blocking\n", " * Say that we have a set of samples from a Monte Carlo experiment\n", "\n", " * Assuming (wrongly) that our samples are uncorrelated our best estimate of the standard deviation of the mean $\\langle \\mathbf{M}\\rangle$ is given by" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "$$\n", "\\sigma=\\sqrt{\\frac{1}{n}\\left(\\langle \\mathbf{M}^2\\rangle-\\langle \\mathbf{M}\\rangle^2\\right)}\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "* If the samples are correlated we can rewrite our results to show that" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "$$\n", "\\sigma=\\sqrt{\\frac{1+2\\tau/\\Delta t}{n}\\left(\\langle \\mathbf{M}^2\\rangle-\\langle \\mathbf{M}\\rangle^2\\right)}\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "where $\\tau$ is the correlation time (the time between a sample and the next uncorrelated sample) and $\\Delta t$ is time between each sample\n", "\n", "\n", "\n", "## What is blocking?\n", " Blocking \n", " * If $\\Delta t\\gg\\tau$ our first estimate of $\\sigma$ still holds\n", "\n", " * Much more common that $\\Delta t<\\tau$\n", "\n", " * In the method of data blocking we divide the sequence of samples into blocks\n", "\n", " * We then take the mean $\\langle \\mathbf{M}_i\\rangle$ of block $i=1\\ldots n_{blocks}$ to calculate the total mean and variance\n", "\n", " * The size of each block must be so large that sample $j$ of block $i$ is not correlated with sample $j$ of block $i+1$\n", "\n", " * The correlation time $\\tau$ would be a good choice\n", "\n", "## What is blocking?\n", " Blocking\n", " * Problem: We don't know $\\tau$ or it is too expensive to compute\n", "\n", " * Solution: Make a plot of std. dev. as a function of blocksize\n", "\n", " * The estimate of std. dev. of correlated data is too low $\\to$ the error will increase with increasing block size until the blocks are uncorrelated, where we reach a plateau\n", "\n", " * When the std. dev. stops increasing the blocks are uncorrelated\n", "\n", "## Implementation\n", "\n", " * Do a Monte Carlo simulation, storing all samples to file\n", "\n", " * Do the statistical analysis on this file, independently of your Monte Carlo program\n", "\n", " * Read the file into an array\n", "\n", " * Loop over various block sizes\n", "\n", " * For each block size $n_b$, loop over the array in steps of $n_b$ taking the mean of elements $i n_b,\\ldots,(i+1) n_b$\n", "\n", " * Take the mean and variance of the resulting array\n", "\n", " * Write the results for each block size to file for later\n", " analysis\n", "\n", "## Actual implementation with code, main function\n", "When the file gets large, it can be useful to write your data in binary mode instead of ascii characters.\n", "The [following python file](https://github.com/CompPhysics/MachineLearning/blob/master/doc/Programs/Sampling/analysis.py) reads data from file with the output from every Monte Carlo cycle." ] }, { "cell_type": "code", "execution_count": 34, "metadata": { "collapsed": false }, "outputs": [], "source": [ "# Blocking\n", " @timeFunction\n", " def blocking(self, blockSizeMax = 500):\n", " blockSizeMin = 1\n", "\n", " self.blockSizes = []\n", " self.meanVec = []\n", " self.varVec = []\n", "\n", " for i in range(blockSizeMin, blockSizeMax):\n", " if(len(self.data) % i != 0):\n", " pass#continue\n", " blockSize = i\n", " meanTempVec = []\n", " varTempVec = []\n", " startPoint = 0\n", " endPoint = blockSize\n", "\n", " while endPoint <= len(self.data):\n", " meanTempVec.append(np.average(self.data[startPoint:endPoint]))\n", " startPoint = endPoint\n", " endPoint += blockSize\n", " mean, var = np.average(meanTempVec), np.var(meanTempVec)/len(meanTempVec)\n", " self.meanVec.append(mean)\n", " self.varVec.append(var)\n", " self.blockSizes.append(blockSize)\n", "\n", " self.blockingAvg = np.average(self.meanVec[-200:])\n", " self.blockingVar = (np.average(self.varVec[-200:]))\n", " self.blockingStd = np.sqrt(self.blockingVar)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## The Bootstrap method\n", "\n", "The Bootstrap resampling method is also very popular. It is very simple:\n", "\n", "1. Start with your sample of measurements and compute the sample variance and the mean values\n", "\n", "2. Then start again but pick in a random way the numbers in the sample and recalculate the mean and the sample variance.\n", "\n", "3. Repeat this $K$ times.\n", "\n", "It can be shown, see the article by [Efron](https://projecteuclid.org/download/pdf_1/euclid.aos/1176344552)\n", "that it produces the correct standard deviation.\n", "\n", "This method is very useful for small ensembles of data points. \n", "\n", "\n", "## Bootstrapping\n", "Given a set of $N$ data, assume that we are interested in some \n", "observable $\\theta$ which may be estimated from that set. This observable can also be for example the result of a fit based on all $N$ raw data. \n", "Let us call the value of the observable obtained from the original \n", "data set $\\hat{\\theta}$. One recreates from the sample repeatedly \n", "other samples by choosing randomly $N$ data out of the original set. \n", "This costs essentially nothing, since we just recycle the original data set for the building of new sets. \n", "\n", "\n", "## Bootstrapping, recipe\n", "Let us assume we have done this $K$ times and thus have $K$ sets of $N$ \n", "data values each. \n", "Of course some values will enter more than once in the new sets. For each of these sets one computes the observable $\\theta$ resulting in values $\\theta_k$ with $k = 1,...,K$. Then one determines" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "$$\n", "\\tilde{\\theta} = \\frac{1}{K} \\sum_{k=1}^K \\theta_k,\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "and" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "$$\n", "sigma^2_{\\tilde{\\theta}} = \\frac{1}{K} \\sum_{k=1}^K \\left(\\theta_k-\\tilde{\\theta}\\right)^2.\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "These are estimators for $\\angle\\theta\\rangle$ and its variance. They are not unbiased and therefore \n", "$\\tilde{\\theta}\\neq\\hat{\\theta}$ for finite K. \n", "\n", "The difference is called bias and gives an idea on how far away the result may be from \n", "the true $\\angle\\theta\\rangle$. As final result for the observable one quotes $\\angle\\theta\\rangle = \\tilde{\\theta} \\pm \\sigma_{\\tilde{\\theta}}$ .\n", "\n", "\n", "\n", "## Bootstrapping, [code](https://github.com/CompPhysics/MachineLearning/blob/master/doc/Programs/Sampling/analysis.py)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ " # Bootstrap\n", " @timeFunction\n", " def bootstrap(self, nBoots = 1000):\n", " bootVec = np.zeros(nBoots)\n", " for k in range(0,nBoots):\n", " bootVec[k] = np.average(np.random.choice(self.data, len(self.data)))\n", " self.bootAvg = np.average(bootVec)\n", " self.bootVar = np.var(bootVec)\n", " self.bootStd = np.std(bootVec)\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Jackknife, [code](https://github.com/CompPhysics/MachineLearning/blob/master/doc/Programs/Sampling/analysis.py)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ " # Jackknife\n", " @timeFunction\n", " def jackknife(self):\n", " jackknVec = np.zeros(len(self.data))\n", " for k in range(0,len(self.data)):\n", " jackknVec[k] = np.average(np.delete(self.data, k))\n", " self.jackknAvg = self.avg - (len(self.data) - 1) * (np.average(jackknVec) - self.avg)\n", " self.jackknVar = float(len(self.data) - 1) * np.var(jackknVec)\n", " self.jackknStd = np.sqrt(self.jackknVar)\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# Regression analysis, overarching aims\n", "\n", "\n", "Regression modeling deals with the description of the sampling distribution of a given random variable $y$ varies as function of another variable or a set of such variables $\\hat{x} =[x_0, x_1,\\dots, x_p]^T$. \n", "The first variable is called the **dependent**, the **outcome** or the **response** variable while the set of variables $\\hat{x}$ is called the independent variable, or the predictor variable or the explanatory variable. \n", "\n", "A regression model aims at finding a likelihood function $p(y\\vert \\hat{x})$, that is the conditional distribution for $y$ with a given $\\hat{x}$. The estimation of $p(y\\vert \\hat{x})$ is made using a data set with \n", "* $n$ cases $i = 0, 1, 2, \\dots, n-1$ \n", "\n", "* Response (dependent or outcome) variable $y_i$ with $i = 0, 1, 2, \\dots, n-1$ \n", "\n", "* $p$ Explanatory (independent or predictor) variables $\\hat{x}_i=[x_{i0}, x_{i1}, \\dots, x_{ip}]$ with $i = 0, 1, 2, \\dots, n-1$ \n", "\n", " The goal of the regression analysis is to extract/exploit relationship between $y_i$ and $\\hat{x}_i$ in or to infer causal dependencies, approximations to the likelihood functions, functional relationships and to make predictions .\n", "\n", "\n", "\n", "## Regression analysis, overarching aims II\n", "\n", "\n", "\n", "Consider an experiment in which $p$ characteristics of $n$ samples are\n", "measured. The data from this experiment are denoted $\\mathbf{X}$, with\n", "$\\mathbf{X}$ as above. The matrix $\\mathbf{X}$ is called the *design\n", "matrix*. Additional information of the samples is available in the\n", "form of $\\mathbf{Y}$ (also as above). The variable $\\mathbf{Y}$ is\n", "generally referred to as the *response variable*. The aim of\n", "regression analysis is to explain $\\mathbf{Y}$ in terms of\n", "$\\mathbf{X}$ through a functional relationship like $Y_i =\n", "f(\\mathbf{X}_{i,\\ast})$. When no prior knowledge on the form of\n", "$f(\\cdot)$ is available, it is common to assume a linear relationship\n", "between $\\mathbf{X}$ and $\\mathbf{Y}$. This assumption gives rise to\n", "the *linear regression model* where $\\beta = (\\beta_1, \\ldots,\n", "\\beta_p)^{\\top}$ is the *regression parameter*. The parameter\n", "$\\beta_j$, $j=1, \\ldots, p$, represents the effect size of covariate\n", "$j$ on the response. That is, for each unit change in covariate $j$\n", "(while keeping the other covariates fixed) the observed change in the\n", "response is equal to $\\beta_j$. \n", "\n", "\n", "\n", "\n", "## General linear models\n", "\n", "Before we proceed let us study a case from linear algebra where we aim at fitting a set of data $\\hat{y}=[y_0,y_1,\\dots,y_{n-1}]$. We could think of these data as a result of an experiment or a complicated numerical experiment. These data are functions of a series of variables $\\hat{x}=[x_0,x_1,\\dots,x_{n-1}]$, that is $y_i = y(x_i)$ with $i=0,1,2,\\dots,n-1$. The variables $x_i$ could represent physical quantities like time, temperature, position etc. We assume that $y(x)$ is a smooth function. \n", "\n", "Since obtaining these data points may not be trivial, we want to use these data to fit a function which can allow us to make predictions for values of $y$ which are not in the present set. The perhaps simplest approach is to assume we can parametrize our function in terms of a polynomial of degree $n-1$ with $n$ points, that is" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "$$\n", "y=y(x) \\rightarrow y(x_i)=\\tilde{y}_i+\\epsilon_i=\\sum_{j=0}^{n-1} \\beta_i x_i^j+\\epsilon_i,\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "where $\\epsilon_i$ is the error in our approximation. \n", "\n", "\n", "\n", "\n", "\n", "## Rewriting the fitting procedure as a linear algebra problem\n", "\n", "For every set of values $y_i,x_i$ we have thus the corresponding set of equations" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "$$\n", "\\begin{align*}\n", "y_0&=\\beta_0+\\beta_1x_0^1+\\beta_2x_0^2+\\dots+\\beta_{n-1}x_0^{n-1}+\\epsilon_0\\\\\n", "y_1&=\\beta_0+\\beta_1x_1^1+\\beta_2x_1^2+\\dots+\\beta_{n-1}x_1^{n-1}+\\epsilon_1\\\\\n", "y_2&=\\beta_0+\\beta_1x_2^1+\\beta_2x_2^2+\\dots+\\beta_{n-1}x_2^{n-1}+\\epsilon_2\\\\\n", "\\dots & \\dots \\\\\n", "y_{n-1}&=\\beta_0+\\beta_1x_{n-1}^1+\\beta_2x_{n-1}^2+\\dots+\\beta_1x_{n-1}^{n-1}+\\epsilon_{n-1}.\\\\\n", "\\end{align*}\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Rewriting the fitting procedure as a linear algebra problem, follows\n", "\n", "Defining the vectors" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "$$\n", "\\hat{y} = [y_0,y_1, y_2,\\dots, y_{n-1}]^T,\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "and" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "$$\n", "\\hat{\\beta} = [\\beta_0,\\beta_1, \\beta_2,\\dots, \\beta_{n-1}]^T,\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "and" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "$$\n", "\\hat{\\epsilon} = [\\epsilon_0,\\epsilon_1, \\epsilon_2,\\dots, \\epsilon_{n-1}]^T,\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "and the matrix" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "$$\n", "\\hat{X}=\n", "\\begin{bmatrix} \n", "1& x_{0}^1 &x_{0}^2& \\dots & \\dots &x_{0}^{n-1}\\\\\n", "1& x_{1}^1 &x_{1}^2& \\dots & \\dots &x_{1}^{n-1}\\\\\n", "1& x_{2}^1 &x_{2}^2& \\dots & \\dots &x_{2}^{n-1}\\\\ \n", "\\dots& \\dots &\\dots& \\dots & \\dots &\\dots\\\\\n", "1& x_{n-1}^1 &x_{n-1}^2& \\dots & \\dots &x_{n-1}^{n-1}\\\\\n", "\\end{bmatrix}\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "we can rewrite our equations as" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "$$\n", "\\hat{y} = \\hat{X}\\hat{\\beta}+\\hat{\\epsilon}.\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Generalizing the fitting procedure as a linear algebra problem\n", "\n", "We are obviously not limited to the above polynomial. We could replace the various powers of $x$ with elements of Fourier series, that is, instead of $x_i^j$ we could have $\\cos{(j x_i)}$ or $\\sin{(j x_i)}$, or time series or other orthogonal functions.\n", "For every set of values $y_i,x_i$ we can then generalize the equations to" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "$$\n", "\\begin{align*}\n", "y_0&=\\beta_0x_{00}+\\beta_1x_{01}+\\beta_2x_{02}+\\dots+\\beta_{n-1}x_{0n-1}+\\epsilon_0\\\\\n", "y_1&=\\beta_0x_{10}+\\beta_1x_{11}+\\beta_2x_{12}+\\dots+\\beta_{n-1}x_{1n-1}+\\epsilon_1\\\\\n", "y_2&=\\beta_0x_{20}+\\beta_1x_{21}+\\beta_2x_{22}+\\dots+\\beta_{n-1}x_{2n-1}+\\epsilon_2\\\\\n", "\\dots & \\dots \\\\\n", "y_{i}&=\\beta_0x_{i0}+\\beta_1x_{i1}+\\beta_2x_{i2}+\\dots+\\beta_{n-1}x_{in-1}+\\epsilon_i\\\\\n", "\\dots & \\dots \\\\\n", "y_{n-1}&=\\beta_0x_{n-1,0}+\\beta_1x_{n-1,2}+\\beta_2x_{n-1,2}+\\dots+\\beta_1x_{n-1,n-1}+\\epsilon_{n-1}.\\\\\n", "\\end{align*}\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Generalizing the fitting procedure as a linear algebra problem\n", "\n", "We redefine in turn the matrix $\\hat{X}$ as" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "$$\n", "\\hat{X}=\n", "\\begin{bmatrix} \n", "x_{00}& x_{01} &x_{02}& \\dots & \\dots &x_{0,n-1}\\\\\n", "x_{10}& x_{11} &x_{12}& \\dots & \\dots &x_{1,n-1}\\\\\n", "x_{20}& x_{21} &x_{22}& \\dots & \\dots &x_{2,n-1}\\\\ \n", "\\dots& \\dots &\\dots& \\dots & \\dots &\\dots\\\\\n", "x_{n-1,0}& x_{n-1,1} &x_{n-1,2}& \\dots & \\dots &x_{n-1,n-1}\\\\\n", "\\end{bmatrix}\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "and without loss of generality we rewrite again our equations as" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "$$\n", "\\hat{y} = \\hat{X}\\hat{\\beta}+\\hat{\\epsilon}.\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "The left-hand side of this equation forms know. Our error vector $\\hat{\\epsilon}$ and the parameter vector $\\hat{\\beta}$ are our unknow quantities. How can we obtain the optimal set of $\\beta_i$ values? \n", "\n", "\n", "\n", "\n", "## Optimizing our parameters\n", "\n", "We have defined the matrix $\\hat{X}$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "$$\n", "\\begin{align*}\n", "y_0&=\\beta_0x_{00}+\\beta_1x_{01}+\\beta_2x_{02}+\\dots+\\beta_{n-1}x_{0n-1}+\\epsilon_0\\\\\n", "y_1&=\\beta_0x_{10}+\\beta_1x_{11}+\\beta_2x_{12}+\\dots+\\beta_{n-1}x_{1n-1}+\\epsilon_1\\\\\n", "y_2&=\\beta_0x_{20}+\\beta_1x_{21}+\\beta_2x_{22}+\\dots+\\beta_{n-1}x_{2n-1}+\\epsilon_1\\\\\n", "\\dots & \\dots \\\\\n", "y_{i}&=\\beta_0x_{i0}+\\beta_1x_{i1}+\\beta_2x_{i2}+\\dots+\\beta_{n-1}x_{in-1}+\\epsilon_1\\\\\n", "\\dots & \\dots \\\\\n", "y_{n-1}&=\\beta_0x_{n-1,0}+\\beta_1x_{n-1,2}+\\beta_2x_{n-1,2}+\\dots+\\beta_1x_{n-1,n-1}+\\epsilon_{n-1}.\\\\\n", "\\end{align*}\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Optimizing our parameters, more details\n", "\n", "We well use this matrix to define the approximation $\\hat{\\tilde{y}}$ via the unknown quantity $\\hat{\\beta}$ as" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "$$\n", "\\hat{\\tilde{y}}= \\hat{X}\\hat{\\beta},\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "and in order to find the optimal parameters $\\beta_i$ instead of solving the above linear algebra problem, we define a function which gives a measure of the spread between the values $y_i$ (which represent hopefully the exact values) and the parametrized values $\\tilde{y}_i$, namely" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "$$\n", "Q(\\hat{\\beta})=\\sum_{i=0}^{n-1}\\left(y_i-\\tilde{y}_i\\right)^2=\\left(\\hat{y}-\\hat{\\tilde{y}}\\right)^T\\left(\\hat{y}-\\hat{\\tilde{y}}\\right),\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "or using the matrix $\\hat{X}$ as" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "$$\n", "Q(\\hat{\\beta})=\\left(\\hat{y}-\\hat{X}\\hat{\\beta}\\right)^T\\left(\\hat{y}-\\hat{X}\\hat{\\beta}\\right).\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Interpretations and optimizing our parameters\n", "\n", "The function" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "$$\n", "Q(\\hat{\\beta})=\\left(\\hat{y}-\\hat{X}\\hat{\\beta}\\right)^T\\left(\\hat{y}-\\hat{X}\\hat{\\beta}\\right),\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "can be linked to the variance of the quantity $y_i$ if we interpret the latter as the mean value of for example a numerical experiment. When linking below with the maximum likelihood approach below, we will indeed interpret $y_i$ as a mean value" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "$$\n", "y_{i}=\\langle y_i \\rangle = \\beta_0x_{i,0}+\\beta_1x_{i,1}+\\beta_2x_{i,2}+\\dots+\\beta_{n-1}x_{i,n-1}+\\epsilon_i,\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "where $\\langle y_i \\rangle$ is the mean value. Keep in mind also that till now we have treated $y_i$ as the exact value. Normally, the response (dependent or outcome) variable $y_i$ the outcome of a numerical experiment or another type of experiment and is thus only an approximation to the true value. It is then always accompanied by an error estimate, often limited to a statistical error estimate given by the standard deviation discussed earlier. In the discussion here we will treat $y_i$ as our exact value for the response variable.\n", "\n", "In order to find the parameters $\\beta_i$ we will then minimize the spread of $Q(\\hat{\\beta})$ by requiring" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "$$\n", "\\frac{\\partial Q(\\hat{\\beta})}{\\partial \\beta_j} = \\frac{\\partial }{\\partial \\beta_j}\\left[ \\sum_{i=0}^{n-1}\\left(y_i-\\beta_0x_{i,0}-\\beta_1x_{i,1}-\\beta_2x_{i,2}-\\dots-\\beta_{n-1}x_{i,n-1}\\right)^2\\right]=0,\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "which results in" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "$$\n", "\\frac{\\partial Q(\\hat{\\beta})}{\\partial \\beta_j} = -2\\left[ \\sum_{i=0}^{n-1}x_{ij}\\left(y_i-\\beta_0x_{i,0}-\\beta_1x_{i,1}-\\beta_2x_{i,2}-\\dots-\\beta_{n-1}x_{i,n-1}\\right)\\right]=0,\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "or in a matrix-vector form as" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "$$\n", "\\frac{\\partial Q(\\hat{\\beta})}{\\partial \\hat{\\beta}} = 0 = \\hat{X}^T\\left( \\hat{y}-\\hat{X}\\hat{\\beta}\\right).\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Interpretations and optimizing our parameters\n", "\n", "We can rewrite" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "$$\n", "\\frac{\\partial Q(\\hat{\\beta})}{\\partial \\hat{\\beta}} = 0 = \\hat{X}^T\\left( \\hat{y}-\\hat{X}\\hat{\\beta}\\right),\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "as" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "$$\n", "\\hat{X}^T\\hat{y} = \\hat{X}^T\\hat{X}\\hat{\\beta},\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "and if the matrix $\\hat{X}^T\\hat{X}$ is invertible we have the solution" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "$$\n", "\\hat{\\beta} =\\left(\\hat{X}^T\\hat{X}\\right)^{-1}\\hat{X}^T\\hat{y}.\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Interpretations and optimizing our parameters\n", "\n", "The residuals $\\hat{\\epsilon}$ are in turn given by" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "$$\n", "\\hat{\\epsilon} = \\hat{y}-\\hat{\\tilde{y}} = \\hat{y}-\\hat{X}\\hat{\\beta},\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "and with" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "$$\n", "\\hat{X}^T\\left( \\hat{y}-\\hat{X}\\hat{\\beta}\\right)= 0,\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "we have" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "$$\n", "\\hat{X}^T\\hat{\\epsilon}=\\hat{X}^T\\left( \\hat{y}-\\hat{X}\\hat{\\beta}\\right)= 0,\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "meaning that the solution for $\\hat{\\beta}$ is the one which minimizes the residuals. Later we will link this with the maximum likelihood approach.\n", "\n", "\n", "\n", "\n", "\n", "## The $\\chi^2$ function\n", "\n", "\n", "Normally, the response (dependent or outcome) variable $y_i$ the outcome of a numerical experiment or another type of experiment and is thus only an approximation to the true value. It is then always accompanied by an error estimate, often limited to a statistical error estimate given by the standard deviation discussed earlier. In the discussion here we will treat $y_i$ as our exact value for the response variable.\n", "\n", "Introducing the standard deviation $\\sigma_i$ for each measurement $y_i$, we define now the $\\chi^2$ function as" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "$$\n", "\\chi^2(\\hat{\\beta})=\\sum_{i=0}^{n-1}\\frac{\\left(y_i-\\tilde{y}_i\\right)^2}{\\sigma_i^2}=\\left(\\hat{y}-\\hat{\\tilde{y}}\\right)^T\\frac{1}{\\hat{\\Sigma^2}}\\left(\\hat{y}-\\hat{\\tilde{y}}\\right),\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "where the matrix $\\hat{\\Sigma}$ is a diagonal matrix with $\\sigma_i$ as matrix elements. \n", "\n", "\n", "\n", "\n", "## The $\\chi^2$ function\n", "\n", "\n", "In order to find the parameters $\\beta_i$ we will then minimize the spread of $\\chi^2(\\hat{\\beta})$ by requiring" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "$$\n", "\\frac{\\partial \\chi^2(\\hat{\\beta})}{\\partial \\beta_j} = \\frac{\\partial }{\\partial \\beta_j}\\left[ \\sum_{i=0}^{n-1}\\left(\\frac{y_i-\\beta_0x_{i,0}-\\beta_1x_{i,1}-\\beta_2x_{i,2}-\\dots-\\beta_{n-1}x_{i,n-1}}{\\sigma_i}\\right)^2\\right]=0,\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "which results in" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "$$\n", "\\frac{\\partial \\chi^2(\\hat{\\beta})}{\\partial \\beta_j} = -2\\left[ \\sum_{i=0}^{n-1}\\frac{x_{ij}}{\\sigma_i}\\left(\\frac{y_i-\\beta_0x_{i,0}-\\beta_1x_{i,1}-\\beta_2x_{i,2}-\\dots-\\beta_{n-1}x_{i,n-1}}{\\sigma_i}\\right)\\right]=0,\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "or in a matrix-vector form as" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "$$\n", "\\frac{\\partial \\chi^2(\\hat{\\beta})}{\\partial \\hat{\\beta}} = 0 = \\hat{A}^T\\left( \\hat{b}-\\hat{A}\\hat{\\beta}\\right).\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "where we have defined the matrix $\\hat{A} =\\hat{X}/\\hat{\\Sigma}$ with matrix elements $a_{ij} = x_{ij}/\\sigma_i$ and the vector $\\hat{b}$ with elements $b_i = y_i/\\sigma_i$. \n", "\n", "\n", "\n", "## The $\\chi^2$ function\n", "\n", "\n", "We can rewrite" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "$$\n", "\\frac{\\partial \\chi^2(\\hat{\\beta})}{\\partial \\hat{\\beta}} = 0 = \\hat{A}^T\\left( \\hat{b}-\\hat{A}\\hat{\\beta}\\right),\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "as" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "$$\n", "\\hat{A}^T\\hat{b} = \\hat{A}^T\\hat{A}\\hat{\\beta},\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "and if the matrix $\\hat{A}^T\\hat{A}$ is invertible we have the solution" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "$$\n", "\\hat{\\beta} =\\left(\\hat{A}^T\\hat{A}\\right)^{-1}\\hat{A}^T\\hat{b}.\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## The $\\chi^2$ function\n", "\n", "\n", "If we then introduce the matrix" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "$$\n", "\\hat{H} = \\left(\\hat{A}^T\\hat{A}\\right)^{-1},\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "we have then the following expression for the parameters $\\beta_j$ (the matrix elements of $\\hat{H}$ are $h_{ij}$)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "$$\n", "\\beta_j = \\sum_{k=0}^{p-1}h_{jk}\\sum_{i=0}^{n-1}\\frac{y_i}{\\sigma_i}\\frac{x_{ik}}{\\sigma_i} = \\sum_{k=0}^{p-1}h_{jk}\\sum_{i=0}^{n-1}b_ia_{ik}\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "We state without proof the expression for the uncertainty in the parameters $\\beta_j$ as (we leave this as an exercise)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "$$\n", "\\sigma^2(\\beta_j) = \\sum_{i=0}^{n-1}\\sigma_i^2\\left( \\frac{\\partial \\beta_j}{\\partial y_i}\\right)^2,\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "resulting in" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "$$\n", "\\sigma^2(\\beta_j) = \\left(\\sum_{k=0}^{p-1}h_{jk}\\sum_{i=0}^{n-1}a_{ik}\\right)\\left(\\sum_{l=0}^{p-1}h_{jl}\\sum_{m=0}^{n-1}a_{ml}\\right) = h_{jj}!\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## The $\\chi^2$ function\n", "\n", "The first step here is to approximate the function $y$ with a first-order polynomial, that is we write" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "$$\n", "y=y(x) \\rightarrow y(x_i) \\approx \\beta_0+\\beta_1 x_i.\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "By computing the derivatives of $\\chi^2$ with respect to $\\beta_0$ and $\\beta_1$ show that these are given by" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "$$\n", "\\frac{\\partial \\chi^2(\\hat{\\beta})}{\\partial \\beta_0} = -2\\left[ \\sum_{i=0}^{n-1}\\left(\\frac{y_i-\\beta_0-\\beta_1x_{i}}{\\sigma_i^2}\\right)\\right]=0,\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "and" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "$$\n", "\\frac{\\partial \\chi^2(\\hat{\\beta})}{\\partial \\beta_0} = -2\\left[ \\sum_{i=0}^{n-1}x_i\\left(\\frac{y_i-\\beta_0-\\beta_1x_{i}}{\\sigma_i^2}\\right)\\right]=0.\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## The $\\chi^2$ function\n", "\n", "\n", "For a linear fit we don't need to invert a matrix!! \n", "Defining" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "$$\n", "\\gamma = \\sum_{i=0}^{n-1}\\frac{1}{\\sigma_i^2},\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "2\n", "1\n", "7\n", " \n", "<\n", "<\n", "<\n", "!\n", "!\n", "M\n", "A\n", "T\n", "H\n", "_\n", "B\n", "L\n", "O\n", "C\n", "K" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "2\n", "1\n", "8\n", " \n", "<\n", "<\n", "<\n", "!\n", "!\n", "M\n", "A\n", "T\n", "H\n", "_\n", "B\n", "L\n", "O\n", "C\n", "K" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "2\n", "1\n", "9\n", " \n", "<\n", "<\n", "<\n", "!\n", "!\n", "M\n", "A\n", "T\n", "H\n", "_\n", "B\n", "L\n", "O\n", "C\n", "K" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "$$\n", "\\gamma_{xy} = \\sum_{i=0}^{n-1}\\frac{y_ix_{i}}{\\sigma_i^2},\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "we obtain" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "2\n", "2\n", "1\n", " \n", "<\n", "<\n", "<\n", "!\n", "!\n", "M\n", "A\n", "T\n", "H\n", "_\n", "B\n", "L\n", "O\n", "C\n", "K" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "$$\n", "\\beta_1 = \\frac{\\gamma_{xy}\\gamma-\\gamma_x\\gamma_y}{\\gamma\\gamma_{xx}-\\gamma_x^2}.\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "This approach (different linear and non-linear regression) suffers often from both being underdetermined and overdetermined in the unknown coefficients $\\beta_i$. A better approach is to use the Singular Value Decomposition (SVD) method discussed below. Or using Lasso and Ridge regression. See below.\n", "\n", "\n", "\n", "\n", "\n", "\n", "## Simple regression model\n", "We are now ready to write our first program which aims at solving the above linear regression equations. We start with data we have produced ourselves, in this case normally distributed random numbers along the $x$-axis. These numbers define then the value of a function $y(x)=4+3x+N(0,1)$. Thereafter we order the $x$ values and employ our linear regression algorithm to set up the best fit. Here we find it useful to use the numpy function $c\\_$ arrays where arrays are stacked along their last axis after being upgraded to at least two dimensions with ones post-pended to the shape. The following examples help in understanding what happens" ] }, { "cell_type": "code", "execution_count": 35, "metadata": { "collapsed": false }, "outputs": [], "source": [ "import numpy as np\n", "print(np.c_[np.array([1,2,3]), np.array([4,5,6])])\n", "print(np.c_[np.array([[1,2,3]]), 0, 0, np.array([[4,5,6]])])" ] }, { "cell_type": "code", "execution_count": 36, "metadata": { "collapsed": false }, "outputs": [], "source": [ "# Importing various packages\n", "from random import random, seed\n", "import numpy as np\n", "import matplotlib.pyplot as plt\n", "\n", "x = 2*np.random.rand(100,1)\n", "y = 4+3*x+np.random.randn(100,1)\n", "\n", "xb = np.c_[np.ones((100,1)), x]\n", "beta = np.linalg.inv(xb.T.dot(xb)).dot(xb.T).dot(y)\n", "xnew = np.array([[0],[2]])\n", "xbnew = np.c_[np.ones((2,1)), xnew]\n", "ypredict = xbnew.dot(beta)\n", "\n", "plt.plot(xnew, ypredict, \"r-\")\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'Linear Regression')\n", "plt.show()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "We see that, as expected, a linear fit gives a seemingly (from the graph) good representation of the data.\n", "\n", "\n", "\n", "\n", "\n", "## Simple regression model, now using **scikit-learn**\n", "\n", "\n", "We can repeat the above algorithm using **scikit-learn** as follows" ] }, { "cell_type": "code", "execution_count": 37, "metadata": { "collapsed": false }, "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 LinearRegression\n", "\n", "x = 2*np.random.rand(100,1)\n", "y = 4+3*x+np.random.randn(100,1)\n", "linreg = LinearRegression()\n", "linreg.fit(x,y)\n", "xnew = np.array([[0],[2]])\n", "ypredict = linreg.predict(xnew)\n", "\n", "plt.plot(xnew, ypredict, \"r-\")\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", "metadata": {}, "source": [ "## Simple linear regression model using **scikit-learn**\n", "\n", "We start with perhaps our simplest possible example, using **scikit-learn** to perform linear regression analysis on a data set produced by us. \n", "What follows is a simple Python code where we have defined function $y$ in terms of the variable $x$. Both are defined as vectors of dimension $1\\times 100$. The entries to the vector $\\hat{x}$ are given by random numbers generated with a uniform distribution with entries $x_i \\in [0,1]$ (more about probability distribution functions later). These values are then used to define a function $y(x)$ (tabulated again as a vector) with a linear dependence on $x$ plus a random noise added via the normal distribution.\n", "\n", "\n", "The Numpy functions are imported used the **import numpy as np**\n", "statement and the random number generator for the uniform distribution\n", "is called using the function **np.random.rand()**, where we specificy\n", "that we want $100$ random variables. Using Numpy we define\n", "automatically an array with the specified number of elements, $100$ in\n", "our case. With the Numpy function **randn()** we can compute random\n", "numbers with the normal distribution (mean value $\\mu$ equal to zero and\n", "variance $\\sigma^2$ set to one) and produce the values of $y$ assuming a linear\n", "dependence as function of $x$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "$$\n", "y = 2x+N(0,1),\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "where $N(0,1)$ represents random numbers generated by the normal\n", "distribution. From **scikit-learn** we import then the\n", "**LinearRegression** functionality and make a prediction $\\tilde{y} =\n", "\\alpha + \\beta x$ using the function **fit(x,y)**. We call the set of\n", "data $(\\hat{x},\\hat{y})$ for our training data. The Python package\n", "**scikit-learn** has also a functionality which extracts the above\n", "fitting parameters $\\alpha$ and $\\beta$ (see below). Later we will\n", "distinguish between training data and test data.\n", "\n", "For plotting we use the Python package\n", "[matplotlib](https://matplotlib.org/) which produces publication\n", "quality figures. Feel free to explore the extensive\n", "[gallery](https://matplotlib.org/gallery/index.html) of examples. In\n", "this example we plot our original values of $x$ and $y$ as well as the\n", "prediction **ypredict** ($\\tilde{y}$), which attempts at fitting our\n", "data with a straight line.\n", "\n", "The Python code follows here." ] }, { "cell_type": "code", "execution_count": 38, "metadata": { "collapsed": false }, "outputs": [], "source": [ "# Importing various packages\n", "import numpy as np\n", "import matplotlib.pyplot as plt\n", "from sklearn.linear_model import LinearRegression\n", "\n", "x = np.random.rand(100,1)\n", "y = 2*x+np.random.randn(100,1)\n", "linreg = LinearRegression()\n", "linreg.fit(x,y)\n", "xnew = np.array([[0],[1]])\n", "ypredict = linreg.predict(xnew)\n", "\n", "plt.plot(xnew, ypredict, \"r-\")\n", "plt.plot(x, y ,'ro')\n", "plt.axis([0,1.0,0, 5.0])\n", "plt.xlabel(r'$x$')\n", "plt.ylabel(r'$y$')\n", "plt.title(r'Simple Linear Regression')\n", "plt.show()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Simple linear regression model\n", "\n", "This example serves several aims. It allows us to demonstrate several\n", "aspects of data analysis and later machine learning algorithms. The\n", "immediate visualization shows that our linear fit is not\n", "impressive. It goes through the data points, but there are many\n", "outliers which are not reproduced by our linear regression. We could\n", "now play around with this small program and change for example the\n", "factor in front of $x$ and the normal distribution. Try to change the\n", "function $y$ to" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "$$\n", "y = 10x+0.01 \\times N(0,1),\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "where $x$ is defined as before. \n", "\n", "\n", "\n", "## Less noise\n", "\n", "Does the fit look better? Indeed, by\n", "reducing the role of the normal distribution we see immediately that\n", "our linear prediction seemingly reproduces better the training\n", "set. However, this testing 'by the eye' is obviouly not satisfactory in the\n", "long run. Here we have only defined the training data and our model, and \n", "have not discussed a more rigorous approach to the **cost** function.\n", "\n", "\n", "\n", "## How to study our fits\n", "\n", "We need more rigorous criteria in defining whether we have succeeded or\n", "not in modeling our training data. You will be surprised to see that\n", "many scientists seldomly venture beyond this 'by the eye' approach. A\n", "standard approach for the *cost* function is the so-called $\\chi^2$\n", "function" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "$$\n", "\\chi^2 = \\frac{1}{n}\n", "\\sum_{i=0}^{n-1}\\frac{(y_i-\\tilde{y}_i)^2}{\\sigma_i^2},\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "where $\\sigma_i^2$ is the variance (to be defined later) of the entry\n", "$y_i$. We may not know the explicit value of $\\sigma_i^2$, it serves\n", "however the aim of scaling the equations and make the cost function\n", "dimensionless. \n", "\n", "\n", "\n", "## Minimizing the cost function\n", "\n", "Minimizing the cost function is a central aspect of\n", "our discussions to come. Finding its minima as function of the model\n", "parameters ($\\alpha$ and $\\beta$ in our case) will be a recurring\n", "theme in these series of lectures. Essentially all machine learning\n", "algorithms we will discuss center around the minimization of the\n", "chosen cost function. This depends in turn on our specific\n", "model for describing the data, a typical situation in supervised\n", "learning. Automatizing the search for the minima of the cost function is a\n", "central ingredient in all algorithms. Typical methods which are\n", "employed are various variants of **gradient** methods. These will be\n", "discussed in more detail later. Again, you'll be surprised to hear that\n", "many practitioners minimize the above function ''by the eye', popularly dubbed as \n", "'chi by the eye'. That is, change a parameter and see (visually and numerically) that \n", "the $\\chi^2$ function becomes smaller. \n", "\n", "\n", "## Relative error\n", "\n", "There are many ways to define the cost function. A simpler approach is to look at the relative difference between the training data and the predicted data, that is we define \n", "the relative error as" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "$$\n", "\\epsilon_{\\mathrm{relative}}= \\frac{\\vert \\hat{y} -\\hat{\\tilde{y}}\\vert}{\\vert \\hat{y}\\vert}.\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "We can modify easily the above Python code and plot the relative error instead" ] }, { "cell_type": "code", "execution_count": 39, "metadata": { "collapsed": false }, "outputs": [], "source": [ "import numpy as np\n", "import matplotlib.pyplot as plt\n", "from sklearn.linear_model import LinearRegression\n", "\n", "x = np.random.rand(100,1)\n", "y = 5*x+0.01*np.random.randn(100,1)\n", "linreg = LinearRegression()\n", "linreg.fit(x,y)\n", "ypredict = linreg.predict(x)\n", "\n", "plt.plot(x, np.abs(ypredict-y)/abs(y), \"ro\")\n", "plt.axis([0,1.0,0.0, 0.5])\n", "plt.xlabel(r'$x$')\n", "plt.ylabel(r'$\\epsilon_{\\mathrm{relative}}$')\n", "plt.title(r'Relative error')\n", "plt.show()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Depending on the parameter in front of the normal distribution, we may\n", "have a small or larger relative error. Try to play around with\n", "different training data sets and study (graphically) the value of the\n", "relative error.\n", "\n", "\n", "\n", "## The richness of **scikit-learn**\n", "\n", "As mentioned above, **scikit-learn** has an impressive functionality.\n", "We can for example extract the values of $\\alpha$ and $\\beta$ and\n", "their error estimates, or the variance and standard deviation and many\n", "other properties from the statistical data analysis. \n", "\n", "Here we show an\n", "example of the functionality of scikit-learn." ] }, { "cell_type": "code", "execution_count": 40, "metadata": { "collapsed": false }, "outputs": [], "source": [ "import numpy as np \n", "import matplotlib.pyplot as plt \n", "from sklearn.linear_model import LinearRegression \n", "from sklearn.metrics import mean_squared_error, r2_score, mean_squared_log_error, mean_absolute_error\n", "\n", "x = np.random.rand(100,1)\n", "y = 2.0+ 5*x+0.5*np.random.randn(100,1)\n", "linreg = LinearRegression()\n", "linreg.fit(x,y)\n", "ypredict = linreg.predict(x)\n", "print('The intercept alpha: \\n', linreg.intercept_)\n", "print('Coefficient beta : \\n', linreg.coef_)\n", "# The mean squared error \n", "print(\"Mean squared error: %.2f\" % mean_squared_error(y, ypredict))\n", "# Explained variance score: 1 is perfect prediction \n", "print('Variance score: %.2f' % r2_score(y, ypredict))\n", "# Mean squared log error \n", "print('Mean squared log error: %.2f' % mean_squared_log_error(y, ypredict) )\n", "# Mean absolute error \n", "print('Mean absolute error: %.2f' % mean_absolute_error(y, ypredict))\n", "plt.plot(x, ypredict, \"r-\")\n", "plt.plot(x, y ,'ro')\n", "plt.axis([0.0,1.0,1.5, 7.0])\n", "plt.xlabel(r'$x$')\n", "plt.ylabel(r'$y$')\n", "plt.title(r'Linear Regression fit ')\n", "plt.show()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Functions in **scikit-learn**\n", "\n", "The function **coef** gives us the parameter $\\beta$ of our fit while **intercept** yields \n", "$\\alpha$. Depending on the constant in front of the normal distribution, we get values near or far from $alpha =2$ and $\\beta =5$. Try to play around with different parameters in front of the normal distribution. The function **meansquarederror** gives us the mean square error, a risk metric corresponding to the expected value of the squared (quadratic) error or loss defined as" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "$$\n", "MSE(\\hat{y},\\hat{\\tilde{y}}) = \\frac{1}{n}\n", "\\sum_{i=0}^{n-1}(y_i-\\tilde{y}_i)^2,\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "The smaller the value, the better the fit. Ideally we would like to\n", "have an MSE equal zero. The attentive reader has probably recognized\n", "this function as being similar to the $\\chi^2$ function defined above.\n", "\n", "\n", "## Other functions in **scikit-learn**\n", "\n", "The **r2score** function computes $R^2$, the coefficient of\n", "determination. It provides a measure of how well future samples are\n", "likely to be predicted by the model. Best possible score is 1.0 and it\n", "can be negative (because the model can be arbitrarily worse). A\n", "constant model that always predicts the expected value of $\\hat{y}$,\n", "disregarding the input features, would get a $R^2$ score of $0.0$.\n", "\n", "If $\\tilde{\\hat{y}}_i$ is the predicted value of the $i-th$ sample and $y_i$ is the corresponding true value, then the score $R^2$ is defined as" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "$$\n", "R^2(\\hat{y}, \\tilde{\\hat{y}}) = 1 - \\frac{\\sum_{i=0}^{n - 1} (y_i - \\tilde{y}_i)^2}{\\sum_{i=0}^{n - 1} (y_i - \\bar{y})^2},\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "where we have defined the mean value of $\\hat{y}$ as" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "$$\n", "\\bar{y} = \\frac{1}{n} \\sum_{i=0}^{n - 1} y_i.\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## The mean absolute error and other functions in **scikit-learn**\n", "\n", "Another quantity will meet again in our discussions of regression analysis is \n", " mean absolute error (MAE), a risk metric corresponding to the expected value of the absolute error loss or what we call the $l1$-norm loss. In our discussion above we presented the relative error.\n", "The MAE is defined as follows" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "$$\n", "\\text{MAE}(\\hat{y}, \\hat{\\tilde{y}}) = \\frac{1}{n} \\sum_{i=0}^{n-1} \\left| y_i - \\tilde{y}_i \\right|.\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Finally we present the \n", "squared logarithmic (quadratic) error" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "$$\n", "\\text{MSLE}(\\hat{y}, \\hat{\\tilde{y}}) = \\frac{1}{n} \\sum_{i=0}^{n - 1} (\\log_e (1 + y_i) - \\log_e (1 + \\tilde{y}_i) )^2,\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "where $\\log_e (x)$ stands for the natural logarithm of $x$. This error\n", "estimate is best to use when targets having exponential growth, such\n", "as population counts, average sales of a commodity over a span of\n", "years etc. \n", "\n", "\n", "\n", "## Cubic polynomial in **scikit-learn**\n", "\n", "We will discuss in more\n", "detail these and other functions in the various lectures. We conclude this part with another example. Instead of \n", "a linear $x$-dependence we study now a cubic polynomial and use the polynomial regression analysis tools of scikit-learn. \n", "Add description of the various python commands." ] }, { "cell_type": "code", "execution_count": 41, "metadata": { "collapsed": false }, "outputs": [], "source": [ "import matplotlib.pyplot as plt\n", "import numpy as np\n", "import random\n", "from sklearn.linear_model import Ridge\n", "from sklearn.preprocessing import PolynomialFeatures\n", "from sklearn.pipeline import make_pipeline\n", "from sklearn.linear_model import LinearRegression\n", "\n", "x=np.linspace(0.02,0.98,200)\n", "noise = np.asarray(random.sample((range(200)),200))\n", "y=x**3*noise\n", "yn=x**3*100\n", "poly3 = PolynomialFeatures(degree=3)\n", "X = poly3.fit_transform(x[:,np.newaxis])\n", "clf3 = LinearRegression()\n", "clf3.fit(X,y)\n", "\n", "Xplot=poly3.fit_transform(x[:,np.newaxis])\n", "poly3_plot=plt.plot(x, clf3.predict(Xplot), label='Cubic Fit')\n", "plt.plot(x,yn, color='red', label=\"True Cubic\")\n", "plt.scatter(x, y, label='Data', color='orange', s=15)\n", "plt.legend()\n", "plt.show()\n", "\n", "def error(a):\n", " for i in y:\n", " err=(y-yn)/yn\n", " return abs(np.sum(err))/len(err)\n", "\n", "print (error(y))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Using **R**, we can perform similar studies. \n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "## Polynomial Regression" ] }, { "cell_type": "code", "execution_count": 42, "metadata": { "collapsed": false }, "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", "m = 100\n", "x = 2*np.random.rand(m,1)+4.\n", "y = 4+3*x*x+ +x-np.random.randn(m,1)\n", "\n", "xb = np.c_[np.ones((m,1)), x]\n", "theta = np.linalg.inv(xb.T.dot(xb)).dot(xb.T).dot(y)\n", "xnew = np.array([[0],[2]])\n", "xbnew = np.c_[np.ones((2,1)), xnew]\n", "ypredict = xbnew.dot(theta)\n", "\n", "plt.plot(xnew, ypredict, \"r-\")\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", "metadata": {}, "source": [ "## Linking the regression analysis with a statistical interpretation\n", "\n", "Before we proceed, and to link with our discussions of Bayesian statistics to come, it is useful the derive the standard regression analysis equations using a statistical interpretation. This allows us also to derive quantities like the variance and other expectation values in a rather straightforward way. \n", "\n", "It is assumed that $\\varepsilon_i\n", "\\sim \\mathcal{N}(0, \\sigma^2)$ and the $\\varepsilon_{i}$ are\n", "independent, i.e.:" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "$$\n", "\\begin{align*} \n", "\\mbox{Cov}(\\varepsilon_{i_1},\n", "\\varepsilon_{i_2}) & = \\left\\{ \\begin{array}{lcc} \\sigma^2 & \\mbox{if}\n", "& i_1 = i_2, \\\\ 0 & \\mbox{if} & i_1 \\not= i_2. \\end{array} \\right.\n", "\\end{align*}\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "The randomness of $\\varepsilon_i$ implies that\n", "$\\mathbf{Y}_i$ is also a random variable. In particular,\n", "$\\mathbf{Y}_i$ is normally distributed, because $\\varepsilon_i \\sim\n", "\\mathcal{N}(0, \\sigma^2)$ and $\\mathbf{X}_{i,\\ast} \\, \\beta$ is a\n", "non-random scalar. To specify the parameters of the distribution of\n", "$\\mathbf{Y}_i$ we need to calculate its first two moments. \n", "\n", "\n", "## Expectation value and variance\n", "\n", "Its expectation equals:" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "$$\n", "\\begin{align*} \n", "\\mathbb{E}(Y_i) & =\n", "\\mathbb{E}(\\mathbf{X}_{i, \\ast} \\, \\beta) + \\mathbb{E}(\\varepsilon_i)\n", "\\, \\, \\, = \\, \\, \\, \\mathbf{X}_{i, \\ast} \\, \\beta, \n", "\\end{align*}\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "while\n", "its variance is" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "$$\n", "\\begin{align*} \\mbox{Var}(Y_i) & = \\mathbb{E} \\{ [Y_i\n", "- \\mathbb{E}(Y_i)]^2 \\} \\, \\, \\, = \\, \\, \\, \\mathbb{E} ( Y_i^2 ) -\n", "[\\mathbb{E}(Y_i)]^2 \\\\ & = \\mathbb{E} [ ( \\mathbf{X}_{i, \\ast} \\,\n", "\\beta + \\varepsilon_i )^2] - ( \\mathbf{X}_{i, \\ast} \\, \\beta)^2 \\\\ &\n", "= \\mathbb{E} [ ( \\mathbf{X}_{i, \\ast} \\, \\beta)^2 + 2 \\varepsilon_i\n", "\\mathbf{X}_{i, \\ast} \\, \\beta + \\varepsilon_i^2 ] - ( \\mathbf{X}_{i,\n", "\\ast} \\, \\beta)^2 \\\\ & = ( \\mathbf{X}_{i, \\ast} \\, \\beta)^2 + 2\n", "\\mathbb{E}(\\varepsilon_i) \\mathbf{X}_{i, \\ast} \\, \\beta +\n", "\\mathbb{E}(\\varepsilon_i^2 ) - ( \\mathbf{X}_{i, \\ast} \\, \\beta)^2 \n", "\\\\ & = \\mathbb{E}(\\varepsilon_i^2 ) \\, \\, \\, = \\, \\, \\,\n", "\\mbox{Var}(\\varepsilon_i) \\, \\, \\, = \\, \\, \\, \\sigma^2. \n", "\\end{align*}\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Hence, $Y_i \\sim \\mathcal{N}( \\mathbf{X}_{i, \\ast} \\, \\beta, \\sigma^2)$. \n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "## The singular value decompostion\n", "\n", "\n", "\n", "A general\n", "$m\\times n$ matrix $\\hat{A}$ can be written in terms of a diagonal\n", "matrix $\\hat{D}$ of dimensionality $n\\times n$ and two orthognal\n", "matrices $\\hat{U}$ and $\\hat{V}$, where the first has dimensionality\n", "$m \\times m$ and the last dimensionality $n\\times n$. \n", "We have then" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "$$\n", "\\hat{A} = \\hat{U}\\hat{D}\\hat{V}^T\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## From standard regression to Ridge regressions\n", "\n", "One of the typical problems we encounter with linear regression, in particular \n", "when the matrix $\\hat{X}$ (our so-called design matrix) is high-dimensional, \n", "are problems with near singular or singular matrices. The column vectors of $\\hat{X}$ \n", "may be linearly dependent, normally referred to as super-collinearity. \n", "This means that the matrix may be rank deficient and it is basically impossible to \n", "to model the data using linear regression. As an example, consider the matrix" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "$$\n", "\\begin{align*}\n", "\\mathbf{X} & = \\left[\n", "\\begin{array}{rrr}\n", "1 & -1 & 2\n", "\\\\\n", "1 & 0 & 1\n", "\\\\\n", "1 & 2 & -1\n", "\\\\\n", "1 & 1 & 0\n", "\\end{array} \\right]\n", "\\end{align*}\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "The columns of $\\hat{X}$ are linearly dependent. We se this easily since the \n", "the first column is the row-wise sum of the other two columns. The rank (more correct,\n", "the column rank) of a matrix is the dimension of the space spanned by the\n", "column vectors. Hence, the rank of $\\mathbf{X}$ is equal to the number\n", "of linearly independent columns. In this particular case the matrix has rank 2.\n", "\n", "Super-collinearity of an $(n \\times p)$-dimensional design matrix $\\mathbf{X}$ implies\n", "that the inverse of the matrix $\\hat{X}^T\\hat{x}$ (the matrix we needto invert to solve the linear regression equations) is non-invertible. If we have a square matrix that does not have an inverse, we say this matrix singular. The example here demonstrates this" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "$$\n", "\\begin{align*}\n", "\\hat{X} & = \\left[\n", "\\begin{array}{rr}\n", "1 & -1\n", "\\\\\n", "1 & -1\n", "\\end{array} \\right].\n", "\\end{align*}\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "We see easily that $\\mbox{det}(\\hat{X}) = x_{11} x_{22} - x_{12} x_{21} = 1 \\times (-1) - 1 \\times (-1) = 0$. Hence, $\\mathbf{X}$ is singular and its inverse is undefined.\n", "This is equivalent to saying that the matrix $\\hat{X}$ has at least an eigenvalue which is zero.\n", "\n", "\n", "## Fixing the singularity\n", "\n", "If our design matrix $\\hat{X}$ which enters the linear regression problem" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "\n", "
\n", "\n", "$$\n", "\\begin{equation}\n", "\\hat{\\beta} = (\\hat{X}^{T} \\hat{X})^{-1} \\hat{X}^{T} \\hat{y},\n", "\\label{_auto10} \\tag{27}\n", "\\end{equation}\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "has linearly dependent column vectors, we will not be able to compute the inverse\n", "of $\\hat{X}^T\\hat{X}$ and we cannot find the parameters (estimators) $\\beta_i$. \n", "The estimators are only well-defined if $(\\hat{X}^{T}\\hat{X})^{-1}$ exits. \n", "This is more likely to happen when the matrix $\\hat{X}$ is high-dimensional. In this case it is likely to encounter a situation where \n", "the regression parameters $\\beta_i$ cannot be estimated.\n", "\n", "The *ad hoc* approach which was introduced in the 70s was simply to add a diagonal component to the matrix to invert, that is we change" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "$$\n", "\\hat{X}^{T} \\hat{X} \\rightarrow \\hat{X}^{T} \\hat{X}+\\lambda \\hat{I},\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "where $\\hat{I}$ is the identity matrix.\n", "\n", "\n", "\n", "\n", "\n", "\n", "## Fitting vs. predicting when data is in the model class\n", "\n", "We start by considering the case\n", "$f(x)=2x$.\n", "\n", "Then the data is clearly generated by a model that is contained within\n", "all three model classes we are using to make predictions (linear\n", "models, third order polynomials, and tenth order polynomials).\n", "\n", "Run the code for the following cases:\n", "\n", "1. For $f(x)=2x$ , $Ntrain=10$ and $\\sigma =0$ (noiseless case), train the three classes of models (linear, third-order polynomial, and tenth order polynomial) for a training set when $x \\in [0,1]$ . Make graphs comparing fits for different order of polynomials. Which model fits the data the best?\n", "\n", "2. Do you think that the data that has the least error on the training set will also make the best predictions? Why or why not? Can you try to discuss and formalize your intuition? What can go right and what can go wrong?\n", "\n", "3. Check your answer by seeing how well your fits predict newly generated test data (including on data outside the range you fit on, for example $x \\in [0,1.2]$ ) using the code below. How well do you do on points in the range of x where you trained the model? How about points outside the original training data set?\n", "\n", "4. Repeat the above for $f(x)=2x$ , $Ntrain=10$ , and $\\sigma=1$ . What changes?\n", "\n", "Repeat the exercises above for $f(x)=2x$ , $Ntrain=100$ , and $\\sigma=1$ . What changes?\n", "Summarize what you have learned about the relationship between model complexity (number of parameters), goodness of fit on training data, and the ability to predict well.\n", "\n", "\n", "\n", "## Fitting versus predicting when data is not in the model class\n", "\n", "Thus far, we have considered the case where the data is generated using a model contained in the model class. Now consider $f(x)=2x-10x^5+15x^{10}$ . Notice that the for linear and third-order polynomial the true model $f(x)$ is not contained in model class.\n", "\n", "1. Do better fits lead to better predictions?\n", "\n", "2. What is the relationship between the true model for generating the data and the model class that has the most predictive power? How is this related to the model complexity? How does this depend on the number of data points $Ntrain$ and $\\sigma$?\n", "\n", "Summarize what you think you learned about the relationship of knowing the true model class and predictive power.\n", "\n", "\n", "## An example code without the model assessment part" ] }, { "cell_type": "code", "execution_count": 43, "metadata": { "collapsed": false }, "outputs": [], "source": [ "import numpy as np\n", "import sklearn as sk\n", "from sklearn import datasets, linear_model\n", "from sklearn.preprocessing import PolynomialFeatures\n", "\n", "import matplotlib as mpl\n", "from matplotlib import pyplot as plt\n", "\n", "%matplotlib notebook\n", "\n", "# The Training Data\n", "\n", "N_train=100\n", "\n", "sigma_train=1;\n", "\n", "# Train on integers\n", "x=np.linspace(0.05,0.95,N_train)\n", "# Draw random noise\n", "s = sigma_train*np.random.randn(N_train)\n", "\n", "#linear\n", "y=2*x+s\n", "\n", "#Tenth Order\n", "#y=2*x-10*x**5+15*x**10+s\n", "\n", "p1=plt.plot(x,y, \"o\",ms=15, label='Training')\n", "\n", "#Linear Regression\n", "# Create linear regression object\n", "clf = linear_model.LinearRegression()\n", "\n", "# Train the model using the training sets\n", "clf.fit(x[:, np.newaxis], y)\n", "# The coefficients\n", "\n", "xplot=np.linspace(0.02,0.98,200)\n", "linear_plot=plt.plot(xplot, clf.predict(xplot[:, np.newaxis]),label='Linear')\n", "\n", "#Polynomial Regression\n", "\n", "\n", "poly3 = PolynomialFeatures(degree=3)\n", "X = poly3.fit_transform(x[:,np.newaxis])\n", "clf3 = linear_model.LinearRegression()\n", "clf3.fit(X,y)\n", "\n", "\n", "Xplot=poly3.fit_transform(xplot[:,np.newaxis])\n", "poly3_plot=plt.plot(xplot, clf3.predict(Xplot), label='Poly 3')\n", "\n", "\n", "\n", "#poly5 = PolynomialFeatures(degree=5)\n", "#X = poly5.fit_transform(x[:,np.newaxis])\n", "#clf5 = linear_model.LinearRegression()\n", "#clf5.fit(X,y)\n", "\n", "#Xplot=poly5.fit_transform(xplot[:,np.newaxis])\n", "#plt.plot(xplot, clf5.predict(Xplot), 'r--',linewidth=1)\n", "\n", "poly10 = PolynomialFeatures(degree=10)\n", "X = poly10.fit_transform(x[:,np.newaxis])\n", "clf10 = linear_model.LinearRegression()\n", "clf10.fit(X,y)\n", "\n", "Xplot=poly10.fit_transform(xplot[:,np.newaxis])\n", "poly10_plot=plt.plot(xplot, clf10.predict(Xplot), label='Poly 10')\n", "\n", "axes = plt.gca()\n", "axes.set_ylim([-7,7])\n", "\n", "handles, labels=axes.get_legend_handles_labels()\n", "plt.legend(handles,labels, loc='lower center')\n", "plt.xlabel(\"$x$\")\n", "plt.ylabel(\"$y$\")\n", "Title=\"$N=$\"+str(N_train)+\", $\\sigma=$\"+str(sigma_train)\n", "plt.title(Title+\" (train)\")\n", "plt.tight_layout()\n", "plt.show()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Generating test data" ] }, { "cell_type": "code", "execution_count": 44, "metadata": { "collapsed": false }, "outputs": [], "source": [ "# Generate Test Data\n", "\n", "#Number of test data\n", "N_test=20\n", "\n", "sigma_test=sigma_train\n", "\n", "max_x=1.2\n", "x_test=max_x*np.random.random(N_test)\n", "# Draw random noise\n", "s_test = sigma_test*np.random.randn(N_test)\n", "\n", "#Linear\n", "y_test=2*x_test+s_test\n", "#Tenth order\n", "#y_test=2*x_test-10*x_test**5+15*x_test**10+s_test\n", "\n", "#Make design matrices for prediction\n", "x_plot=np.linspace(0,max_x, 200)\n", "X3 = poly3.fit_transform(x_plot[:,np.newaxis])\n", "X10 = poly10.fit_transform(x_plot[:,np.newaxis])\n", "\n", "%matplotlib notebook\n", "\n", "fig = plt.figure() \n", "p1=plt.plot(x_test,y_test.transpose(), 'o', ms=12, label='data')\n", "p2=plt.plot(x_plot,clf.predict(x_plot[:,np.newaxis]), label='linear')\n", "p3=plt.plot(x_plot,clf3.predict(X3), label='3rd order')\n", "p10=plt.plot(x_plot,clf10.predict(X10), label='10th order')\n", "\n", "\n", "plt.legend(loc=2)\n", "plt.xlabel('$x$')\n", "plt.ylabel('$y$')\n", "plt.legend(loc='best')\n", "plt.title(Title+\" (pred.)\")\n", "plt.tight_layout()\n", "plt.show()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## How can we effectively evaluate the various models?\n", "\n", "In Ridge regression and the subsequent discussion of its properties\n", "the bias or penalty parameter is considered known or `given'. In\n", "practice, it is unknown and the user needs to make an informed\n", "decision on its value. How do we do that? Much of the same considerations apply to the Lasso method. \n", "\n", "\n", "## Code examples for Ridge and Lasso Regression" ] }, { "cell_type": "code", "execution_count": 45, "metadata": { "collapsed": false }, "outputs": [], "source": [ "import matplotlib.pyplot as plt\n", "import numpy as np\n", "from sklearn import linear_model\n", "from sklearn.linear_model import LinearRegression\n", "from sklearn.metrics import mean_squared_error, r2_score\n", "\n", "#creating data with random noise\n", "x=np.arange(50)\n", "\n", "delta=np.random.uniform(-2.5,2.5, size=(50))\n", "np.random.shuffle(delta)\n", "y =0.5*x+5+delta\n", "\n", "#arranging data into 2x50 matrix\n", "a=np.array(x) #inputs\n", "b=np.array(y) #outputs\n", "\n", "#Split into training and test\n", "X_train=a[:37, np.newaxis]\n", "X_test=a[37:, np.newaxis]\n", "y_train=b[:37]\n", "y_test=b[37:]\n", "\n", "print (\"X_train: \", X_train.shape)\n", "print (\"y_train: \", y_train.shape)\n", "print (\"X_test: \", X_test.shape)\n", "print (\"y_test: \", y_test.shape)\n", "\n", "print (\"------------------------------------\")\n", "\n", "print (\"Ordinary Least Squares\")\n", "#Add Ordinary Least Squares fit\n", "reg=LinearRegression()\n", "reg.fit(X_train, y_train)\n", "pred=reg.predict(X_test)\n", "print (\"Prediction Shape: \", pred.shape)\n", "\n", "print('Coefficients: \\n', reg.coef_)\n", "# The mean squared error\n", "print(\"Mean squared error: %.2f\"\n", " % mean_squared_error(y_test, pred))\n", "# Explained variance score: 1 is perfect prediction\n", "print('Variance score: %.2f' % r2_score(y_test, pred))\n", "\n", "#plot\n", "plt.scatter(X_test,y_test,color='green', label=\"Training Data\")\n", "plt.plot(X_test, pred, color='black', label=\"Fit Line\")\n", "plt.legend()\n", "plt.show()\n", "\n", "print (\"------------------------------------\")\n", "\n", "print (\"Ridge Regression\")\n", "\n", "ridge=linear_model.RidgeCV(alphas=[0.1,1.0,10.0])\n", "ridge.fit(X_train,y_train)\n", "print (\"Ridge Coefficient: \",ridge.coef_)\n", "print (\"Ridge Intercept: \", ridge.intercept_)\n", "#Look into graphing with Ridge fit\n", "\n", "print (\"------------------------------------\")\n", "\n", "print (\"Lasso\")\n", "lasso=linear_model.Lasso(alpha=0.1)\n", "lasso.fit(X_train,y_train)\n", "predl=lasso.predict(X_test)\n", "print(\"Lasso Coefficient: \", lasso.coef_)\n", "print(\"Lasso Intercept: \", lasso.intercept_)\n", "plt.scatter(X_test,y_test,color='green', label=\"Training Data\")\n", "plt.plot(X_test, predl, color='blue', label=\"Lasso\")\n", "plt.legend()\n", "plt.show()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## A second-order polynomial with Ridge and Lasso" ] }, { "cell_type": "code", "execution_count": 46, "metadata": { "collapsed": false }, "outputs": [], "source": [ "import numpy as np\n", "import matplotlib.pyplot as plt\n", "from sklearn.linear_model import Ridge\n", "from sklearn.metrics import r2_score\n", "\n", "np.random.seed(4155)\n", "\n", "n_samples = 100\n", "\n", "x = np.random.rand(n_samples,1)\n", "y = 5*x*x + 0.1*np.random.rand(n_samples,1)\n", "\n", "# Centering x and y.\n", "x_ = x - np.mean(x)\n", "y_ = y - np.mean(y) # beta_0 = mean(y)\n", "\n", "X = np.c_[np.ones((n_samples,1)), x, x**2]\n", "X_ = np.c_[x_, x_**2]\n", "\n", "\n", "### 1.\n", "lmb_values = [1e-4, 1e-3, 1e-2, 10, 1e2, 1e4]\n", "num_values = len(lmb_values)\n", "\n", "## Ridge-regression of centered and not centered data\n", "beta_ridge = np.zeros((3,num_values))\n", "beta_ridge_centered = np.zeros((3,num_values))\n", "\n", "I3 = np.eye(3)\n", "I2 = np.eye(2)\n", "\n", "for i,lmb in enumerate(lmb_values):\n", " beta_ridge[:,i] = (np.linalg.inv( X.T @ X + lmb*I3) @ X.T @ y).flatten()\n", " beta_ridge_centered[1:,i] = (np.linalg.inv( X_.T @ X_ + lmb*I2) @ X_.T @ y_).flatten()\n", "\n", "# sett beta_0 = np.mean(y)\n", "beta_ridge_centered[0,:] = np.mean(y)\n", "\n", "## OLS (ordinary least squares) solution \n", "beta_ls = np.linalg.inv( X.T @ X ) @ X.T @ y\n", "\n", "## Evaluate the models\n", "pred_ls = X @ beta_ls\n", "pred_ridge = X @ beta_ridge\n", "pred_ridge_centered = X_ @ beta_ridge_centered[1:] + beta_ridge_centered[0,:]\n", "\n", "## Plot the results\n", "\n", "# Sorting\n", "sort_ind = np.argsort(x[:,0])\n", "\n", "x_plot = x[sort_ind,0]\n", "x_centered_plot = x_[sort_ind,0]\n", "\n", "pred_ls_plot = pred_ls[sort_ind,0]\n", "pred_ridge_plot = pred_ridge[sort_ind,:]\n", "pred_ridge_centered_plot = pred_ridge_centered[sort_ind,:]\n", "\n", "# Plott not centered\n", "plt.plot(x_plot,pred_ls_plot,label='ls')\n", "\n", "for i in range(num_values):\n", " plt.plot(x_plot,pred_ridge_plot[:,i],label='ridge, lmb=%g'%lmb_values[i])\n", "\n", "plt.plot(x,y,'ro')\n", "\n", "plt.title('linear regression on un-centered data')\n", "plt.legend()\n", "\n", "# Plott centered\n", "plt.figure()\n", "\n", "for i in range(num_values):\n", " plt.plot(x_centered_plot,pred_ridge_centered_plot[:,i],label='ridge, lmb=%g'%lmb_values[i])\n", "\n", "plt.plot(x_,y,'ro')\n", "\n", "plt.title('linear regression on centered data')\n", "plt.legend()\n", "\n", "\n", "# 2.\n", "\n", "pred_ridge_scikit = np.zeros((n_samples,num_values))\n", "for i,lmb in enumerate(lmb_values):\n", " pred_ridge_scikit[:,i] = (Ridge(alpha=lmb,fit_intercept=False).fit(X,y).predict(X)).flatten() # fit_intercept=False fordi bias er allerede i X\n", "\n", "plt.figure()\n", "\n", "plt.plot(x_plot,pred_ls_plot,label='ls')\n", "\n", "for i in range(num_values):\n", " plt.plot(x_plot,pred_ridge_scikit[sort_ind,i],label='scikit-ridge, lmb=%g'%lmb_values[i])\n", "\n", "plt.plot(x,y,'ro')\n", "plt.legend()\n", "plt.title('linear regression using scikit')\n", "\n", "plt.show()\n", "\n", "### R2-score of the results\n", "for i in range(num_values):\n", " print('lambda = %g'%lmb_values[i])\n", " print('r2 for scikit: %g'%r2_score(y,pred_ridge_scikit[:,i]))\n", " print('r2 for own code, not centered: %g'%r2_score(y,pred_ridge[:,i]))\n", " print('r2 for own, centered: %g\\n'%r2_score(y,pred_ridge_centered[:,i]))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Resampling methods\n", "\n", "Resampling methods are an indispensable tool in modern\n", "statistics. They involve repeatedly drawing samples from a training\n", "set and refitting a model of interest on each sample in order to\n", "obtain additional information about the fitted model. For example, in\n", "order to estimate the variability of a linear regression fit, we can\n", "repeatedly draw different samples from the training data, fit a linear\n", "regression to each new sample, and then examine the extent to which\n", "the resulting fits differ. Such an approach may allow us to obtain\n", "information that would not be available from fitting the model only\n", "once using the original training sample.\n", "\n", "\n", "\n", "## Resampling approaches can be computationally expensive\n", "\n", "Resampling approaches can be computationally expensive, because they\n", "involve fitting the same statistical method multiple times using\n", "different subsets of the training data. However, due to recent\n", "advances in computing power, the computational requirements of\n", "resampling methods generally are not prohibitive. In this chapter, we\n", "discuss two of the most commonly used resampling methods,\n", "cross-validation and the bootstrap. Both methods are important tools\n", "in the practical application of many statistical learning\n", "procedures. For example, cross-validation can be used to estimate the\n", "test error associated with a given statistical learning method in\n", "order to evaluate its performance, or to select the appropriate level\n", "of flexibility. The process of evaluating a model’s performance is\n", "known as model assessment, whereas the process of selecting the proper\n", "level of flexibility for a model is known as model selection. The\n", "bootstrap is widely used.\n", "\n", "\n", "\n", "## Why resampling methods ?\n", " Statistical analysis\n", " * Our simulations can be treated as *computer experiments*. This is particularly the case for Monte Carlo methods\n", "\n", " * The results can be analysed with the same statistical tools as we would use analysing experimental data.\n", "\n", " * As in all experiments, we are looking for expectation values and an estimate of how accurate they are, i.e., possible sources for errors.\n", "\n", "## Statistical analysis\n", "\n", " * As in other experiments, many numerical experiments have two classes of errors:\n", "\n", " * Statistical errors\n", "\n", " * Systematical errors\n", "\n", "\n", " * Statistical errors can be estimated using standard tools from statistics\n", "\n", " * Systematical errors are method specific and must be treated differently from case to case. \n", "\n", "## Statistics\n", "\n", "The *probability distribution function (PDF)* is a function\n", "$p(x)$ on the domain which, in the discrete case, gives us the\n", "probability or relative frequency with which these values of $X$ occur:" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "$$\n", "p(x) = \\mathrm{prob}(X=x)\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "In the continuous case, the PDF does not directly depict the\n", "actual probability. Instead we define the probability for the\n", "stochastic variable to assume any value on an infinitesimal interval\n", "around $x$ to be $p(x)dx$. The continuous function $p(x)$ then gives us\n", "the *density* of the probability rather than the probability\n", "itself. The probability for a stochastic variable to assume any value\n", "on a non-infinitesimal interval $[a,\\,b]$ is then just the integral:" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "$$\n", "\\mathrm{prob}(a\\leq X\\leq b) = \\int_a^b p(x)dx\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Qualitatively speaking, a stochastic variable represents the values of\n", "numbers chosen as if by chance from some specified PDF so that the\n", "selection of a large set of these numbers reproduces this PDF.\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "## Log-likelihood\n", "\n", "A popular strategy is to choose a penalty parameter that yields a good\n", "but parsimonious model. Information criteria measure the balance\n", "between model fit and model complexity. One possibility is Aikaike's\n", "information criterion (AIC).\n", "The AIC measures model fit by the log-likelihood\n", "and model complexity is measured by the number of parameters used by\n", "the model. The number of model parameters in regular regression simply\n", "corresponds to the number of covariates in the model. Or, by the\n", "degrees of freedom consumed by the model, which is equivalent to the\n", "trace of the hat matrix. For ridge regression it thus seems natural to\n", "define model complexity analogously by the trace of the ridge hat\n", "matrix. This yields the AIC for the linear regression model with ridge\n", "estimates:" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "$$\n", "\\begin{align*}\n", "\\mbox{AIC}(\\lambda) & = 2 \\, p - 2 \\log(\\hat{L})\n", "\\\\\n", "& = 2 \\, \\mbox{tr} [\\mathbf{H}(\\lambda)] - 2 \\log\\{L[\\hat{\\beta}(\\lambda), \\hat{\\sigma}^2(\\lambda)]\\}\n", "\\\\\n", "& = 2 \\, \\sum_{j=1}^p \\frac{d_{jj}^2}{d_{jj}^2 + \\lambda}\n", "+ 2 n \\, \\log[\\sqrt{2 \\, \\pi} \\, \\hat{\\sigma}(\\lambda)] + \\frac{1}{\\hat{\\sigma}^2(\\lambda)} \\sum_{i=1}^n [y_i - \\mathbf{X}_{i, \\ast} \\, \\hat{\\beta}(\\lambda)]^2.\n", "\\end{align*}\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "The value of $\\lambda$ which minimizes $\\mbox{AIC}(\\lambda)$ corresponds to the `optimal' balance of model complexity and overfitting.\n", "\n", "\n", "\n", "## Cross-validation\n", "\n", "Instead of choosing the penalty parameter to balance model fit with\n", "model complexity, cross-validation requires it (i.e. the penalty\n", "parameter) to yield a model with good prediction\n", "performance. Commonly, this performance is evaluated on novel\n", "data. Novel data need not be easy to come by and one has to make do\n", "with the data at hand. The setting of `original' and novel data is\n", "then mimicked by sample splitting: the data set is divided into two\n", "(groups of samples). One of these two data sets, called the *training\n", "set*, plays the role of `original' data on which the model is\n", "built. The second of these data sets, called the *test set*, plays the\n", "role of the `novel' data and is used to evaluate the prediction\n", "performance (often operationalized as the log-likelihood or the\n", "prediction error or its square or the R2 score) of the model built on the training data set. This\n", "procedure (model building and prediction evaluation on training and\n", "test set, respectively) is done for a collection of possible penalty\n", "parameter choices. The penalty parameter that yields the model with\n", "the best prediction performance is to be preferred. The thus obtained\n", "performance evaluation depends on the actual split of the data set. To\n", "remove this dependence the data set is split many times into a\n", "training and test set. For each split the model parameters are\n", "estimated for all choices of $\\lambda$ using the training data and\n", "estimated parameters are evaluated on the corresponding test set. The\n", "penalty parameter that on average over the test sets performs best (in\n", "some sense) is then selected.\n", "\n", "\n", "\n", "## Computationally expensive\n", "\n", "The validation set approach is conceptually simple and is easy to implement. But it has two potential drawbacks:\n", "\n", "* The validation estimate of the test error rate can be highly variable, depending on precisely which observations are included in the training set and which observations are included in the validation set.\n", "\n", "* In the validation approach, only a subset of the observations, those that are included in the training set rather than in the validation set are used to fit the model. Since statistical methods tend to perform worse when trained on fewer observations, this suggests that the validation set error rate may tend to overestimate the test error rate for the model fit on the entire data set.\n", "\n", "## Various steps in cross-validation\n", "\n", "When the repetitive splitting of the data set is done randomly,\n", "samples may accidently end up in a fast majority of the splits in\n", "either training or test set. Such samples may have an unbalanced\n", "influence on either model building or prediction evaluation. To avoid\n", "this $k$-fold cross-validation structures the data splitting. The\n", "samples are divided into $k$ more or less equally sized exhaustive and\n", "mutually exclusive subsets. In turn (at each split) one of these\n", "subsets plays the role of the test set while the union of the\n", "remaining subsets constitutes the training set. Such a splitting\n", "warrants a balanced representation of each sample in both training and\n", "test set over the splits. Still the division into the $k$ subsets\n", "involves a degree of randomness. This may be fully excluded when\n", "choosing $k=n$. This particular case is referred to as leave-one-out\n", "cross-validation (LOOCV). \n", "\n", "\n", "## How to set up the cross-validation for Ridge and/or Lasso\n", "\n", "* Define a range of interest for the penalty parameter.\n", "\n", "* Divide the data set into training and test set comprising samples $\\{1, \\ldots, n\\} \\setminus i$ and $\\{ i \\}$, respectively.\n", "\n", "* Fit the linear regression model by means of ridge estimation for each $\\lambda$ in the grid using the training set, and the corresponding estimate of the error variance $\\hat{\\sigma}_{-i}^2(\\lambda)$, as" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "$$\n", "\\begin{align*}\n", "\\hat{\\beta}_{-i}(\\lambda) & = ( \\hat{X}_{-i, \\ast}^{\\top}\n", "\\hat{X}_{-i, \\ast} + \\lambda \\hat{I}_{pp})^{-1}\n", "\\hat{X}_{-i, \\ast}^{\\top} \\hat{y}_{-i}\n", "\\end{align*}\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "* Evaluate the prediction performance of these models on the test set by $\\log\\{L[y_i, \\hat{X}_{i, \\ast}; \\hat{\\beta}_{-i}(\\lambda), \\hat{\\sigma}_{-i}^2(\\lambda)]\\}$. Or, by the prediction error $|y_i - \\hat{X}_{i, \\ast} \\hat{\\beta}_{-i}(\\lambda)|$, the relative error, the error squared or the R2 score function.\n", "\n", "* Repeat the first three steps such that each sample plays the role of the test set once.\n", "\n", "* Average the prediction performances of the test sets at each grid point of the penalty bias/parameter by computing the *cross-validated log-likelihood*. It is an estimate of the prediction performance of the model corresponding to this value of the penalty parameter on novel data. It is defined as" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "$$\n", "\\begin{align*}\n", "\\frac{1}{n} \\sum_{i = 1}^n \\log\\{L[y_i, \\mathbf{X}_{i, \\ast}; \\hat{\\beta}_{-i}(\\lambda), \\hat{\\sigma}_{-i}^2(\\lambda)]\\}.\n", "\\end{align*}\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "* The value of the penalty parameter that maximizes the cross-validated log-likelihood is the value of choice. Or we can use the MSE or the R2 score functions.\n", "\n", "## Predicted Residual Error Sum of Squares\n", "\n", "Another approach in the LOOCV scheme is to the use the so-called Predicted Residual Error Sum of Squares (PRESS). \n", "\n", "We can define the optimal penalty parameter to minimize" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "$$\n", "\\begin{align*}\n", "\\lambda_{\\mbox{{\\tiny opt}}} = \\arg \\min_{\\lambda} \\frac{1}{n} \\sum_{i=1}^n [y_i - \\hat{X}_{i, \\ast} \\hat{\\beta}_{-i}(\\lambda)]^2.\n", "\\end{align*}\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "The LOOCV prediction performance can be\n", "expressed analytically in terms of the known quantities derived from\n", "the design matrix and the parameters $\\beta$.\n", "\n", "\n", "\n", "\n", "## Resampling methods: Jackknife and Bootstrap\n", "\n", "Two famous\n", "resampling methods are the **independent bootstrap** and **the jackknife**. \n", "\n", "The jackknife is a special case of the independent bootstrap. Still, the jackknife was made\n", "popular prior to the independent bootstrap. And as the popularity of\n", "the independent bootstrap soared, new variants, such as **the dependent bootstrap**.\n", "\n", "The Jackknife and independent bootstrap work for\n", "independent, identically distributed random variables.\n", "If these conditions are not\n", "satisfied, the methods will fail. Yet, it should be said that if the data are\n", "independent, identically distributed, and we only want to estimate the\n", "variance of $\\overline{X}$ (which often is the case), then there is no\n", "need for bootstrapping. \n", "\n", "\n", "## Resampling methods: Jackknife\n", "\n", "The Jackknife works by making many replicas of the estimator $\\widehat{\\theta}$. \n", "The jackknife is a resampling method, we explained that this happens by scrambling the data in some way. When using the jackknife, this is done by systematically leaving out one observation from the vector of observed values $\\hat{x} = (x_1,x_2,\\cdots,X_n)$. \n", "Let $\\hat{x}_i$ denote the vector" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "$$\n", "\\hat{x}_i = (x_1,x_2,\\cdots,x_{i-1},x_{i+1},\\cdots,x_n),\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "which equals the vector $\\hat{x}$ with the exception that observation\n", "number $i$ is left out. Using this notation, define\n", "$\\widehat{\\theta}_i$ to be the estimator\n", "$\\widehat{\\theta}$ computed using $\\vec{X}_i$. \n", "\n", "\n", "## Resampling methods: Jackknife estimator\n", "\n", "To get an estimate for the bias and\n", "standard error of $\\widehat{\\theta}$, use the following\n", "estimators for each component of $\\widehat{\\theta}$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "$$\n", "\\widehat{\\mathrm{Bias}}(\\widehat \\theta,\\theta) = (n-1)\\left( - \\widehat{\\theta} + \\frac{1}{n}\\sum_{i=1}^{n} \\widehat \\theta_i \\right) \\qquad \\text{and} \\qquad \\widehat{\\sigma}^2_{\\widehat{\\theta} } = \\frac{n-1}{n}\\sum_{i=1}^{n}( \\widehat{\\theta}_i - \\frac{1}{n}\\sum_{j=1}^{n}\\widehat \\theta_j )^2.\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Jackknife code example" ] }, { "cell_type": "code", "execution_count": 47, "metadata": { "collapsed": false }, "outputs": [], "source": [ "from numpy import *\n", "from numpy.random import randint, randn\n", "from time import time\n", "\n", "def jackknife(data, stat):\n", " n = len(data);t = zeros(n); inds = arange(n); t0 = time()\n", " ## 'jackknifing' by leaving out an observation for each i \n", " for i in range(n):\n", " t[i] = stat(delete(data,i) )\n", "\n", " # analysis \n", " print(\"Runtime: %g sec\" % (time()-t0)); print(\"Jackknife Statistics :\")\n", " print(\"original bias std. error\")\n", " print(\"%8g %14g %15g\" % (stat(data),(n-1)*mean(t)/n, (n*var(t))**.5))\n", "\n", " return t\n", "\n", "\n", "# Returns mean of data samples \n", "def stat(data):\n", " return mean(data)\n", "\n", "\n", "mu, sigma = 100, 15\n", "datapoints = 10000\n", "x = mu + sigma*random.randn(datapoints)\n", "# jackknife returns the data sample \n", "t = jackknife(x, stat)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Resampling methods: Bootstrap\n", "\n", "Bootstrapping is a nonparametric approach to statistical inference\n", "that substitutes computation for more traditional distributional\n", "assumptions and asymptotic results. Bootstrapping offers a number of\n", "advantages: \n", "1. The bootstrap is quite general, although there are some cases in which it fails. \n", "\n", "2. Because it does not require distributional assumptions (such as normally distributed errors), the bootstrap can provide more accurate inferences when the data are not well behaved or when the sample size is small. \n", "\n", "3. It is possible to apply the bootstrap to statistics with sampling distributions that are difficult to derive, even asymptotically. \n", "\n", "4. It is relatively simple to apply the bootstrap to complex data-collection plans (such as stratified and clustered samples).\n", "\n", "## Resampling methods: Bootstrap background\n", "\n", "Since $\\widehat{\\theta} = \\widehat{\\theta}(\\hat{X})$ is a function of random variables,\n", "$\\widehat{\\theta}$ itself must be a random variable. Thus it has\n", "a pdf, call this function $p(\\hat{t})$. The aim of the bootstrap is to\n", "estimate $p(\\hat{t})$ by the relative frequency of\n", "$\\widehat{\\theta}$. You can think of this as using a histogram\n", "in the place of $p(\\hat{t})$. If the relative frequency closely\n", "resembles $p(\\vec{t})$, then using numerics, it is straight forward to\n", "estimate all the interesting parameters of $p(\\hat{t})$ using point\n", "estimators. \n", "\n", "\n", "\n", "## Resampling methods: More Bootstrap background\n", "\n", "In the case that $\\widehat{\\theta}$ has\n", "more than one component, and the components are independent, we use the\n", "same estimator on each component separately. If the probability\n", "density function of $X_i$, $p(x)$, had been known, then it would have\n", "been straight forward to do this by: \n", "1. Drawing lots of numbers from $p(x)$, suppose we call one such set of numbers $(X_1^*, X_2^*, \\cdots, X_n^*)$. \n", "\n", "2. Then using these numbers, we could compute a replica of $\\widehat{\\theta}$ called $\\widehat{\\theta}^*$. \n", "\n", "By repeated use of (1) and (2), many\n", "estimates of $\\widehat{\\theta}$ could have been obtained. The\n", "idea is to use the relative frequency of $\\widehat{\\theta}^*$\n", "(think of a histogram) as an estimate of $p(\\hat{t})$.\n", "\n", "\n", "## Resampling methods: Bootstrap approach\n", "\n", "But\n", "unless there is enough information available about the process that\n", "generated $X_1,X_2,\\cdots,X_n$, $p(x)$ is in general\n", "unknown. Therefore, [Efron in 1979](https://projecteuclid.org/euclid.aos/1176344552) asked the\n", "question: What if we replace $p(x)$ by the relative frequency\n", "of the observation $X_i$; if we draw observations in accordance with\n", "the relative frequency of the observations, will we obtain the same\n", "result in some asymptotic sense? The answer is yes.\n", "\n", "\n", "Instead of generating the histogram for the relative\n", "frequency of the observation $X_i$, just draw the values\n", "$(X_1^*,X_2^*,\\cdots,X_n^*)$ with replacement from the vector\n", "$\\hat{X}$. \n", "\n", "\n", "## Resampling methods: Bootstrap steps\n", "\n", "The independent bootstrap works like this: \n", "\n", "1. Draw with replacement $n$ numbers for the observed variables $\\hat{x} = (x_1,x_2,\\cdots,x_n)$. \n", "\n", "2. Define a vector $\\hat{x}^*$ containing the values which were drawn from $\\hat{x}$. \n", "\n", "3. Using the vector $\\hat{x}^*$ compute $\\widehat{\\theta}^*$ by evaluating $\\widehat \\theta$ under the observations $\\hat{x}^*$. \n", "\n", "4. Repeat this process $k$ times. \n", "\n", "When you are done, you can draw a histogram of the relative frequency of $\\widehat \\theta^*$. This is your estimate of the probability distribution $p(t)$. Using this probability distribution you can estimate any statistics thereof. In principle you never draw the histogram of the relative frequency of $\\widehat{\\theta}^*$. Instead you use the estimators corresponding to the statistic of interest. For example, if you are interested in estimating the variance of $\\widehat \\theta$, apply the etsimator $\\widehat \\sigma^2$ to the values $\\widehat \\theta ^*$.\n", "\n", "\n", "\n", "## Code example for the Bootstrap method\n", "The following code starts with a Gaussian distribution with mean value $\\mu =100$ and variance $\\sigma=15$. We use this to generate the data used in the bootstrap analysis. The bootstrap analysis returns a data set after a given number of bootstrap operations (as many as we have data points). This data set consists of estimated mean values for each bootstrap operation. The histogram generated by the bootstrap method shows that the distribution for these mean values is also a Gaussian, centered around the mean value $\\mu=100$ but with standard deviation $\\sigma/\\sqrt{n}$, where $n$ is the number of bootstrap samples (in this case the same as the number of original data points). The value of the standard deviation is what we expect from the central limit theorem." ] }, { "cell_type": "code", "execution_count": 48, "metadata": { "collapsed": false }, "outputs": [], "source": [ "from numpy import *\n", "from numpy.random import randint, randn\n", "from time import time\n", "import matplotlib.mlab as mlab\n", "import matplotlib.pyplot as plt\n", "\n", "# Returns mean of bootstrap samples \n", "def stat(data):\n", " return mean(data)\n", "\n", "# Bootstrap algorithm \n", "def bootstrap(data, statistic, R):\n", " t = zeros(R); n = len(data); inds = arange(n); t0 = time()\n", "\n", " # non-parametric bootstrap \n", " for i in range(R):\n", " t[i] = statistic(data[randint(0,n,n)])\n", "\n", " # analysis \n", " print(\"Runtime: %g sec\" % (time()-t0)); print(\"Bootstrap Statistics :\")\n", " print(\"original bias std. error\")\n", " print(\"%8g %8g %14g %15g\" % (statistic(data), std(data),\\\n", " mean(t), \\\n", " std(t)))\n", " return t\n", "\n", "\n", "mu, sigma = 100, 15\n", "datapoints = 10000\n", "x = mu + sigma*random.randn(datapoints)\n", "# bootstrap returns the data sample t = bootstrap(x, stat, datapoints)\n", "# the histogram of the bootstrapped data n, binsboot, patches = plt.hist(t, 50, normed=1, facecolor='red', alpha=0.75)\n", "\n", "# add a 'best fit' line \n", "y = mlab.normpdf( binsboot, mean(t), std(t))\n", "lt = plt.plot(binsboot, y, 'r--', linewidth=1)\n", "plt.xlabel('Smarts')\n", "plt.ylabel('Probability')\n", "plt.axis([99.5, 100.6, 0, 3.0])\n", "plt.grid(True)\n", "\n", "plt.show()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Resampling methods: Blocking\n", "\n", "The blocking method was made popular by [Flyvbjerg and Pedersen (1989)](https://aip.scitation.org/doi/10.1063/1.457480)\n", "and has become one of the standard ways to estimate\n", "$V(\\widehat{\\theta})$ for exactly one $\\widehat{\\theta}$, namely\n", "$\\widehat{\\theta} = \\overline{X}$. \n", "\n", "Assume $n = 2^d$ for some integer $d>1$ and $X_1,X_2,\\cdots, X_n$ is a stationary time series to begin with. \n", "Moreover, assume that the time series is asymptotically uncorrelated. We switch to vector notation by arranging $X_1,X_2,\\cdots,X_n$ in an $n$-tuple. Define:" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "$$\n", "\\begin{align*}\n", "\\hat{X} = (X_1,X_2,\\cdots,X_n).\n", "\\end{align*}\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "The strength of the blocking method is when the number of\n", "observations, $n$ is large. For large $n$, the complexity of dependent\n", "bootstrapping scales poorly, but the blocking method does not,\n", "moreover, it becomes more accurate the larger $n$ is.\n", "\n", "\n", "## Blocking Transformations\n", " We now define\n", "blocking transformations. The idea is to take the mean of subsequent\n", "pair of elements from $\\vec{X}$ and form a new vector\n", "$\\vec{X}_1$. Continuing in the same way by taking the mean of\n", "subsequent pairs of elements of $\\vec{X}_1$ we obtain $\\vec{X}_2$, and\n", "so on. \n", "Define $\\vec{X}_i$ recursively by:" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "$$\n", "(\\vec{X}_0)_k \\equiv (\\vec{X})_k \\nonumber\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "\n", "
\n", "\n", "$$\n", "\\begin{equation} \n", "(\\vec{X}_{i+1})_k \\equiv \\frac{1}{2}\\Big( (\\vec{X}_i)_{2k-1} +\n", "(\\vec{X}_i)_{2k} \\Big) \\qquad \\text{for all} \\qquad 1 \\leq i \\leq d-1\n", "\\label{_auto11} \\tag{28}\n", "\\end{equation}\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "The quantity $\\vec{X}_k$ is\n", "subject to $k$ **blocking transformations**. We now have $d$ vectors\n", "$\\vec{X}_0, \\vec{X}_1,\\cdots,\\vec X_{d-1}$ containing the subsequent\n", "averages of observations. It turns out that if the components of\n", "$\\vec{X}$ is a stationary time series, then the components of\n", "$\\vec{X}_i$ is a stationary time series for all $0 \\leq i \\leq d-1$\n", "\n", "We can then compute the autocovariance, the variance, sample mean, and\n", "number of observations for each $i$. \n", "Let $\\gamma_i, \\sigma_i^2,\n", "\\overline{X}_i$ denote the autocovariance, variance and average of the\n", "elements of $\\vec{X}_i$ and let $n_i$ be the number of elements of\n", "$\\vec{X}_i$. It follows by induction that $n_i = n/2^i$. \n", "\n", "\n", "## Blocking Transformations\n", "\n", "Using the\n", "definition of the blocking transformation and the distributive\n", "property of the covariance, it is clear that since $h =|i-j|$\n", "we can define" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "$$\n", "\\gamma_{k+1}(h) = cov\\left( ({X}_{k+1})_{i}, ({X}_{k+1})_{j} \\right) \\nonumber\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "$$\n", "= \\frac{1}{4}cov\\left( ({X}_{k})_{2i-1} + ({X}_{k})_{2i}, ({X}_{k})_{2j-1} + ({X}_{k})_{2j} \\right) \\nonumber\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "\n", "
\n", "\n", "$$\n", "\\begin{equation} \n", "= \\frac{1}{2}\\gamma_{k}(2h) + \\frac{1}{2}\\gamma_k(2h+1) \\hspace{0.1cm} \\mathrm{h = 0} \n", "\\label{_auto12} \\tag{29}\n", "\\end{equation}\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "\n", "
\n", "\n", "$$\n", "\\begin{equation} \n", "=\\frac{1}{4}\\gamma_k(2h-1) + \\frac{1}{2}\\gamma_k(2h) + \\frac{1}{4}\\gamma_k(2h+1) \\quad \\mathrm{else}\n", "\\label{_auto13} \\tag{30}\n", "\\end{equation}\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "The quantity $\\hat{X}$ is asymptotic uncorrelated by assumption, $\\hat{X}_k$ is also asymptotic uncorrelated. Let's turn our attention to the variance of the sample mean $V(\\overline{X})$. \n", "\n", "\n", "## Blocking Transformations, getting there\n", "We have" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "\n", "
\n", "\n", "$$\n", "\\begin{equation}\n", "V(\\overline{X}_k) = \\frac{\\sigma_k^2}{n_k} + \\underbrace{\\frac{2}{n_k} \\sum_{h=1}^{n_k-1}\\left( 1 - \\frac{h}{n_k} \\right)\\gamma_k(h)}_{\\equiv e_k} = \\frac{\\sigma^2_k}{n_k} + e_k \\quad \\text{if} \\quad \\gamma_k(0) = \\sigma_k^2. \n", "\\label{_auto14} \\tag{31}\n", "\\end{equation}\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "The term $e_k$ is called the **truncation error**:" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "\n", "
\n", "\n", "$$\n", "\\begin{equation}\n", "e_k = \\frac{2}{n_k} \\sum_{h=1}^{n_k-1}\\left( 1 - \\frac{h}{n_k} \\right)\\gamma_k(h). \n", "\\label{_auto15} \\tag{32}\n", "\\end{equation}\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "We can show that $V(\\overline{X}_i) = V(\\overline{X}_j)$ for all $0 \\leq i \\leq d-1$ and $0 \\leq j \\leq d-1$. \n", "\n", "\n", "## Blocking Transformations, final expressions\n", "\n", "We can then wrap up" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "$$\n", "n_{j+1} \\overline{X}_{j+1} = \\sum_{i=1}^{n_{j+1}} (\\hat{X}_{j+1})_i = \\frac{1}{2}\\sum_{i=1}^{n_{j}/2} (\\hat{X}_{j})_{2i-1} + (\\hat{X}_{j})_{2i} \\nonumber\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "\n", "
\n", "\n", "$$\n", "\\begin{equation} \n", "= \\frac{1}{2}\\left[ (\\hat{X}_j)_1 + (\\hat{X}_j)_2 + \\cdots + (\\hat{X}_j)_{n_j} \\right] = \\underbrace{\\frac{n_j}{2}}_{=n_{j+1}} \\overline{X}_j = n_{j+1}\\overline{X}_j. \n", "\\label{_auto16} \\tag{33}\n", "\\end{equation}\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "By repeated use of this equation we get $V(\\overline{X}_i) = V(\\overline{X}_0) = V(\\overline{X})$ for all $0 \\leq i \\leq d-1$. This has the consequence that" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "\n", "
\n", "\n", "$$\n", "\\begin{equation}\n", "V(\\overline{X}) = \\frac{\\sigma_k^2}{n_k} + e_k \\qquad \\text{for all} \\qquad 0 \\leq k \\leq d-1. \\label{eq:convergence} \\tag{34}\n", "\\end{equation}\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Fyvbjerg and Petersen demonstrated that the sequence\n", "$\\{e_k\\}_{k=0}^{d-1}$ is decreasing, and conjecture that the term\n", "$e_k$ can be made as small as we would like by making $k$ (and hence\n", "$d$) sufficiently large. The sequence is decreasing (Master of Science thesis by Marius Jonsson, UiO 2018).\n", "It means we can apply blocking transformations until\n", "$e_k$ is sufficiently small, and then estimate $V(\\overline{X})$ by\n", "$\\widehat{\\sigma}^2_k/n_k$. \n", "\n", "\n", "\n", "## [Code examples for Blocking, Jackknife and bootstrap](https://github.com/CompPhysics/MachineLearning/tree/master/doc/Programs/ResamplingAnalysisScripts)" ] }, { "cell_type": "code", "execution_count": 49, "metadata": { "collapsed": false }, "outputs": [], "source": [ "from sys import argv\n", "from os import mkdir, path\n", "import time\n", "import numpy as np\n", "import matplotlib.pyplot as plt\n", "from matplotlib.ticker import FormatStrFormatter\n", "from matplotlib.font_manager import FontProperties\n", "\n", "# Timing Decorator\n", "def timeFunction(f):\n", " def wrap(*args):\n", " time1 = time.time()\n", " ret = f(*args)\n", " time2 = time.time()\n", " print '%s Function Took: \\t %0.3f s' % (f.func_name.title(), (time2-time1))\n", " return ret\n", " return wrap\n", "\n", "class dataAnalysisClass:\n", " # General Init functions\n", " def __init__(self, fileName, size=0):\n", " self.inputFileName = fileName\n", " self.loadData(size)\n", " self.createOutputFolder()\n", " self.avg = np.average(self.data)\n", " self.var = np.var(self.data)\n", " self.std = np.std(self.data)\n", "\n", " def loadData(self, size=0):\n", " if size != 0:\n", " with open(self.inputFileName) as inputFile:\n", " self.data = np.zeros(size)\n", " for x in xrange(size):\n", " self.data[x] = float(next(inputFile))\n", " else:\n", " self.data = np.loadtxt(self.inputFileName)\n", "\n", " # Statistical Analysis with Multiple Methods\n", " def runAllAnalyses(self):\n", " if len(self.data) <= 100000:\n", " print \"Autocorrelation...\"\n", " self.autocorrelation()\n", " print \"Bootstrap...\"\n", " self.bootstrap()\n", " print \"Jackknife...\"\n", " self.jackknife()\n", " print \"Blocking...\"\n", " self.blocking()\n", "\n", " # Standard Autocorrelation\n", " @timeFunction\n", " def autocorrelation(self):\n", " self.acf = np.zeros(len(self.data)/2)\n", " for k in range(0, len(self.data)/2):\n", " self.acf[k] = np.corrcoef(np.array([self.data[0:len(self.data)-k], \\\n", " self.data[k:len(self.data)]]))[0,1]\n", "\n", " # Bootstrap\n", " @timeFunction\n", " def bootstrap(self, nBoots = 1000):\n", " bootVec = np.zeros(nBoots)\n", " for k in range(0,nBoots):\n", " bootVec[k] = np.average(np.random.choice(self.data, len(self.data)))\n", " self.bootAvg = np.average(bootVec)\n", " self.bootVar = np.var(bootVec)\n", " self.bootStd = np.std(bootVec)\n", "\n", " # Jackknife\n", " @timeFunction\n", " def jackknife(self):\n", " jackknVec = np.zeros(len(self.data))\n", " for k in range(0,len(self.data)):\n", " jackknVec[k] = np.average(np.delete(self.data, k))\n", " self.jackknAvg = self.avg - (len(self.data) - 1) * (np.average(jackknVec) - self.avg)\n", " self.jackknVar = float(len(self.data) - 1) * np.var(jackknVec)\n", " self.jackknStd = np.sqrt(self.jackknVar)\n", "\n", " # Blocking\n", " @timeFunction\n", " def blocking(self, blockSizeMax = 500):\n", " blockSizeMin = 1\n", "\n", " self.blockSizes = []\n", " self.meanVec = []\n", " self.varVec = []\n", "\n", " for i in range(blockSizeMin, blockSizeMax):\n", " if(len(self.data) % i != 0):\n", " pass#continue\n", " blockSize = i\n", " meanTempVec = []\n", " varTempVec = []\n", " startPoint = 0\n", " endPoint = blockSize\n", "\n", " while endPoint <= len(self.data):\n", " meanTempVec.append(np.average(self.data[startPoint:endPoint]))\n", " startPoint = endPoint\n", " endPoint += blockSize\n", " mean, var = np.average(meanTempVec), np.var(meanTempVec)/len(meanTempVec)\n", " self.meanVec.append(mean)\n", " self.varVec.append(var)\n", " self.blockSizes.append(blockSize)\n", "\n", " self.blockingAvg = np.average(self.meanVec[-200:])\n", " self.blockingVar = (np.average(self.varVec[-200:]))\n", " self.blockingStd = np.sqrt(self.blockingVar)\n", "\n", "\n", "\n", " # Plot of Data, Autocorrelation Function and Histogram\n", " def plotAll(self):\n", " self.createOutputFolder()\n", " if len(self.data) <= 100000:\n", " self.plotAutocorrelation()\n", " self.plotData()\n", " self.plotHistogram()\n", " self.plotBlocking()\n", "\n", " # Create Output Plots Folder\n", " def createOutputFolder(self):\n", " self.outName = self.inputFileName[:-4]\n", " if not path.exists(self.outName):\n", " mkdir(self.outName)\n", "\n", " # Plot the Dataset, Mean and Std\n", " def plotData(self):\n", " # Far away plot\n", " font = {'fontname':'serif'}\n", " plt.plot(range(0, len(self.data)), self.data, 'r-', linewidth=1)\n", " plt.plot([0, len(self.data)], [self.avg, self.avg], 'b-', linewidth=1)\n", " plt.plot([0, len(self.data)], [self.avg + self.std, self.avg + self.std], 'g--', linewidth=1)\n", " plt.plot([0, len(self.data)], [self.avg - self.std, self.avg - self.std], 'g--', linewidth=1)\n", " plt.ylim(self.avg - 5*self.std, self.avg + 5*self.std)\n", " plt.gca().yaxis.set_major_formatter(FormatStrFormatter('%.4f'))\n", " plt.xlim(0, len(self.data))\n", " plt.ylabel(self.outName.title() + ' Monte Carlo Evolution', **font)\n", " plt.xlabel('MonteCarlo History', **font)\n", " plt.title(self.outName.title(), **font)\n", " plt.savefig(self.outName + \"/data.eps\")\n", " plt.savefig(self.outName + \"/data.png\")\n", " plt.clf()\n", "\n", " # Plot Histogram of Dataset and Gaussian around it\n", " def plotHistogram(self):\n", " binNumber = 50\n", " font = {'fontname':'serif'}\n", " count, bins, ignore = plt.hist(self.data, bins=np.linspace(self.avg - 5*self.std, self.avg + 5*self.std, binNumber))\n", " plt.plot([self.avg, self.avg], [0,np.max(count)+10], 'b-', linewidth=1)\n", " plt.ylim(0,np.max(count)+10)\n", " plt.ylabel(self.outName.title() + ' Histogram', **font)\n", " plt.xlabel(self.outName.title() , **font)\n", " plt.title('Counts', **font)\n", "\n", " #gaussian\n", " norm = 0\n", " for i in range(0,len(bins)-1):\n", " norm += (bins[i+1]-bins[i])*count[i]\n", " plt.plot(bins, norm/(self.std * np.sqrt(2 * np.pi)) * np.exp( - (bins - self.avg)**2 / (2 * self.std**2) ), linewidth=1, color='r')\n", " plt.savefig(self.outName + \"/hist.eps\")\n", " plt.savefig(self.outName + \"/hist.png\")\n", " plt.clf()\n", "\n", " # Plot the Autocorrelation Function\n", " def plotAutocorrelation(self):\n", " font = {'fontname':'serif'}\n", " plt.plot(range(1, len(self.data)/2), self.acf[1:], 'r-')\n", " plt.ylim(-1, 1)\n", " plt.xlim(0, len(self.data)/2)\n", " plt.ylabel('Autocorrelation Function', **font)\n", " plt.xlabel('Lag', **font)\n", " plt.title('Autocorrelation', **font)\n", " plt.savefig(self.outName + \"/autocorrelation.eps\")\n", " plt.savefig(self.outName + \"/autocorrelation.png\")\n", " plt.clf()\n", "\n", " def plotBlocking(self):\n", " font = {'fontname':'serif'}\n", " plt.plot(self.blockSizes, self.varVec, 'r-')\n", " plt.ylabel('Variance', **font)\n", " plt.xlabel('Block Size', **font)\n", " plt.title('Blocking', **font)\n", " plt.savefig(self.outName + \"/blocking.eps\")\n", " plt.savefig(self.outName + \"/blocking.png\")\n", " plt.clf()\n", "\n", " # Print Stuff to the Terminal\n", " def printOutput(self):\n", " print \"\\nSample Size: \\t\", len(self.data)\n", " print \"\\n=========================================\\n\"\n", " print \"Sample Average: \\t\", self.avg\n", " print \"Sample Variance:\\t\", self.var\n", " print \"Sample Std: \\t\", self.std\n", " print \"\\n=========================================\\n\"\n", " print \"Bootstrap Average: \\t\", self.bootAvg\n", " print \"Bootstrap Variance:\\t\", self.bootVar\n", " print \"Bootstrap Error: \\t\", self.bootStd\n", " print \"\\n=========================================\\n\"\n", " print \"Jackknife Average: \\t\", self.jackknAvg\n", " print \"Jackknife Variance:\\t\", self.jackknVar\n", " print \"Jackknife Error: \\t\", self.jackknStd\n", " print \"\\n=========================================\\n\"\n", " print \"Blocking Average: \\t\", self.blockingAvg\n", " print \"Blocking Variance:\\t\", self.blockingVar\n", " print \"Blocking Error: \\t\", self.blockingStd, \"\\n\"\n", "\n", "# Initialize the class\n", "if len(argv) > 2:\n", " dataAnalysis = dataAnalysisClass(argv[1], int(argv[2]))\n", "else:\n", " dataAnalysis = dataAnalysisClass(argv[1])\n", "\n", "# Run Analyses\n", "dataAnalysis.runAllAnalyses()\n", "\n", "# Plot the data\n", "dataAnalysis.plotAll()\n", "\n", "# Print Some Output\n", "dataAnalysis.printOutput()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## The bias-variance tradeoff\n", "\n", "We begin with an unknown function $y=f(x)$ and fix a \\emph{hypothesis set}\n", " $\\mathcal{H}$ consisting of all functions we are willing to consider,\n", " defined also on the domain of $f$. This set may be uncountably\n", " infinite (e.g. if there are real-valued parameters to fit). \n", "The\n", " choice of which functions to include in $\\mathcal{H}$ usually depends\n", " on our intuition about the problem of interest. The function $f(x)$\n", " produces a set of pairs $(x_i,y_i)$, $i=1\\dots N$, which serve as the\n", " observable data. Our goal is to select a function from the hypothesis\n", " set $h\\in\\mathcal{H}$ which approximates $f(x)$ as best as possible,\n", " namely, we would like to find $h\\in\\mathcal{H}$ such that $h\\approx\n", " f$ in some strict mathematical sense which we specify below. If this\n", " is possible, we say that we \\emph{learned} $f(x)$. But if the\n", " function $f(x)$ can, in principle, take any value on\n", " \\emph{unobserved} inputs, how is it possible to learn in any\n", " meaningful sense?\n", "\n", "\n", "## Training and testing data\n", "\n", "We will discuss the bias-variance tradeoff in the context of continuous predictions such as regression. However, many of the intuitions and ideas discussed here also carry over to classification tasks. Consider a dataset $\\mathcal{L}$ consisting of the data $\\mathbf{X}_\\mathcal{L}=\\{(y_j, \\boldsymbol{x}_j), j=1\\ldots N\\}$. Let us assume that the true data is generated from a noisy model" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "$$\n", "y=f(\\boldsymbol{x}) + \\epsilon\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "where $\\epsilon$ is normally distributed with mean zero and standard deviation $\\sigma_\\epsilon$.\n", "\n", "\n", "## Procedure to find a predictor\n", "\n", "We have a statistical procedure (e.g. least-squares regression) for\n", "forming a predictor $\\hat{g}_{\\mathcal{L}}(\\boldsymbol{x})$ that gives the\n", "prediction of our model for a new data point $\\boldsymbol{x}$. This estimator\n", "is chosen by minimizing a cost function which we take to be the\n", "squared error" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "$$\n", "\\mathcal{C}( \\boldsymbol{X}, \\hat{g}(\\boldsymbol{x})) = \\sum_i (y_i - \\hat{g}_\\mathcal{L}(\\boldsymbol{x}_i))^2.\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## What we want\n", "\n", "We are interested in the generalization error on all data drawn from\n", "the true model, not just the error on the particular training dataset\n", "$\\mathcal{L}$ that we have in hand. This is just the expectation of\n", "the cost function over many different data sets\n", "$\\{\\mathcal{L}_j\\}$. Denote this expectation value by\n", "$E_{\\mathcal{L}}$. In other words, we can view $\\hat{g}_{\\mathcal{L}}$\n", "as a stochastic functional that depends on the dataset $\\mathcal{L}$\n", "and we can think of $E_{\\mathcal{L}}$ as the expected value of the\n", "functional if we drew an infinite number of datasets $\\{\\mathcal{L}_1,\n", "\\mathcal{L}_2, \\ldots \\}$.\n", "\n", "\n", "\n", "## The expected generalization error\n", "\n", "We would also like to average over different instances of the\n", "\"noise\" $\\epsilon$ and we denote the expectation value over the\n", "noise by $E_\\epsilon$. Thus, we can decompose the expected\n", "generalization error as" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "$$\n", "E_\\mathcal{L, \\epsilon}[\\mathcal{C}( \\boldsymbol{X}, \\hat{g}(\\boldsymbol{x})) ]= E_\\mathcal{L,\\epsilon}\\left[ \\sum_i ({y}_i - \\hat{g}_\\mathcal{L}(\\boldsymbol{x}_i))^2 \\right] \\nonumber\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "$$\n", "= E_\\mathcal{L, \\epsilon}\\left[ \\sum_{i}({y}_i -f(\\boldsymbol{x}_i) +f(\\boldsymbol{x}_i)- \\hat{g}_\\mathcal{L}(\\boldsymbol{x}_i))^2\\right] \\nonumber\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "$$\n", "= \\sum_i E_\\epsilon[ ({y}_i -f(\\boldsymbol{x}_i))^2 ]+ E_\\mathcal{L, \\epsilon}[(f(\\boldsymbol{x}_i)- \\hat{g}_\\mathcal{L}(\\boldsymbol{x}_i))^2] + 2E_\\epsilon[{y}_i -f(\\boldsymbol{x}_i)]E_\\mathcal{L}[f(\\boldsymbol{x}_i)- \\hat{g}_\\mathcal{L}(\\boldsymbol{x}_i)] \\nonumber\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "\n", "
\n", "\n", "$$\n", "\\begin{equation} \n", " =\\sum_i \\sigma_\\epsilon^2 + E_\\mathcal{L}[(f(\\boldsymbol{x}_i)- \\hat{g}_\\mathcal{L}(\\boldsymbol{x}_i))^2],\n", "\\label{_auto17} \\tag{35}\n", "\\end{equation}\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "where in the last line we used the fact that our noise has zero mean\n", "and variance $\\sigma_\\epsilon^2$ and the sum over $i$ applies to all\n", "terms. \n", "\n", "\n", "## Elaborating a little bit more\n", "\n", "It is also helpful to further decompose the second term as\n", "follows:" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "$$\n", "E_\\mathcal{L}[(f(\\boldsymbol{x}_i)- \\hat{g}_\\mathcal{L}(\\boldsymbol{x}_i))^2] =E_\\mathcal{L}[(f(\\mathbf{x}_i)-E_\\mathcal{L}[\\hat{g}_\\mathcal{L}(\\boldsymbol{x}_i)]+ E_\\mathcal{L}[\\hat{g}_\\mathcal{L}(\\boldsymbol{x}_i)]- \\hat{g}_\\mathcal{L}(\\boldsymbol{x}_i))^2] \\nonumber\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "$$\n", "=E_\\mathcal{L}[(f(\\boldsymbol{x}_i)-E_\\mathcal{L}[\\hat{g}_\\mathcal{L}(\\boldsymbol{x}_i)])^2] + E_\\mathcal{L}[( \\hat{g}_\\mathcal{L}(\\boldsymbol{x}_i)-E_\\mathcal{L}[\\hat{g}_\\mathcal{L}(\\boldsymbol{x}_i)])^2] \\nonumber\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "$$\n", "+2E_\\mathcal{L}[(f(\\boldsymbol{x}_i)-E_\\mathcal{L}[\\hat{g}_\\mathcal{L}(\\boldsymbol{x}_i)])( \\hat{g}_\\mathcal{L}(\\boldsymbol{x}_i)-E_\\mathcal{L}[\\hat{g}_\\mathcal{L}(\\boldsymbol{x}_i)])] \\nonumber\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "\n", "
\n", "\n", "$$\n", "\\begin{equation} \n", "=(f(\\boldsymbol{x}_i)-E_\\mathcal{L}[\\hat{g}_\\mathcal{L}(\\boldsymbol{x}_i)])^2+E_\\mathcal{L}[( \\hat{g}_\\mathcal{L}(\\boldsymbol{x}_i)-E_\\mathcal{L}[\\hat{g}_\\mathcal{L}(\\boldsymbol{x}_i)])^2].\n", "\\label{_auto18} \\tag{36}\n", "\\end{equation}\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## The bias\n", "\n", "The first term is called the bias" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "$$\n", "Bias^2= \\sum_i (f(\\boldsymbol{x}_i)-E_\\mathcal{L}[\\hat{g}_\\mathcal{L}(\\boldsymbol{x}_i)])^2\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "and measures the deviation of the expectation value of our estimator (i.e. the asymptotic value of our estimator in the infinite data limit) from the true value. \n", "\n", "\n", "## The variance\n", "The second term is called the variance" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "$$\n", "Var=\\sum_i E_\\mathcal{L}[( \\hat{g}_\\mathcal{L}(\\boldsymbol{x}_i)-E_\\mathcal{L}[\\hat{g}_\\mathcal{L}(\\boldsymbol{x}_i)])^2],\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "and measures how much our estimator fluctuates due to finite-sample effects. Combining these expressions, we see that the expected out-of-sample error of our model can be decomposed as" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "$$\n", "E_\\mathrm{out}=E_\\mathcal{L, \\epsilon}[\\mathcal{C}( \\boldsymbol{X}, \\hat{g}(\\boldsymbol{x})) ] = Bias^2 + Var + Noise.\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "The bias-variance tradeoff summarizes the fundamental tension in\n", "machine learning, particularly supervised learning, between the\n", "complexity of a model and the amount of training data needed to train\n", "it. Since data is often limited, in practice it is often useful to\n", "use a less-complex model with higher bias - a model whose asymptotic\n", "performance is worse than another model - because it is easier to\n", "train and less sensitive to sampling noise arising from having a\n", "finite-sized training dataset (smaller variance). \n", "\n", "\n", "## Summing up\n", "\n", "The above equations tell us that in\n", "order to minimize the expected test error, we need to select a\n", "statistical learning method that simultaneously achieves low variance\n", "and low bias. Note that variance is inherently a nonnegative quantity,\n", "and squared bias is also nonnegative. Hence, we see that the expected\n", "test MSE can never lie below $Var(\\epsilon)$, the irreducible error.\n", "\n", "\n", "What do we mean by the variance and bias of a statistical learning\n", "method? The variance refers to the amount by which our model would change if we\n", "estimated it using a different training data set. Since the training\n", "data are used to fit the statistical learning method, different\n", "training data sets will result in a different estimate. But ideally the\n", "estimate for our model should not vary too much between training\n", "sets. However, if a method has high variance then small changes in\n", "the training data can result in large changes in the model. In general, more\n", "flexible statistical methods have higher variance.\n", "\n", "\n", "\n", "## The one-dimensional Ising model, project 2\n", "\n", "The one-dimensional Ising model with nearest neighbor interaction, no external field and a constant coupling constant $J$ is given by" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "\n", "
\n", "\n", "$$\n", "\\begin{equation}\n", " H = -J \\sum_{k}^L s_k s_{k + 1},\n", "\\label{_auto19} \\tag{37}\n", "\\end{equation}\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "where $s_i \\in \\{-1, 1\\}$ and $s_{N + 1} = s_1$. The number of spins in the system is determined by $L$. For the one-dimensional system there is no phase transition.\n", "\n", "We will look at a system of $L = 40$ spins with a coupling constant of $J = 1$. To get enough training data we will generate 10000 states with their respective energies." ] }, { "cell_type": "code", "execution_count": 50, "metadata": { "collapsed": false }, "outputs": [], "source": [ "import numpy as np\n", "import matplotlib.pyplot as plt\n", "from mpl_toolkits.axes_grid1 import make_axes_locatable\n", "import seaborn as sns\n", "import scipy.linalg as scl\n", "from sklearn.model_selection import train_test_split\n", "import sklearn.linear_model as skl\n", "import tqdm\n", "sns.set(color_codes=True)\n", "cmap_args=dict(vmin=-1., vmax=1., cmap='seismic')\n", "\n", "L = 40\n", "n = int(1e4)\n", "\n", "spins = np.random.choice([-1, 1], size=(n, L))\n", "J = 1.0\n", "\n", "energies = np.zeros(n)\n", "\n", "for i in range(n):\n", " energies[i] = - J * np.dot(spins[i], np.roll(spins[i], 1))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Here we use linear (ordinary least squares), ridge and LASSO\n", "regression to predict the energy in the nearest neighbor\n", "one-dimensional Ising model on a ring, i.e., the endpoints wrap\n", "around. We will use the linear regression models to fit a value for\n", "the coupling constant to achieve this.\n", "\n", "\n", "## Reformulating the problem to suit regression\n", "\n", "A more general form for the one-dimensional Ising model is" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "\n", "
\n", "\n", "$$\n", "\\begin{equation}\n", " H = - \\sum_j^L \\sum_k^L s_j s_k J_{jk}.\n", "\\label{_auto20} \\tag{38}\n", "\\end{equation}\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Here we allow for interactions beyond the nearest neighbors and a more\n", "adaptive coupling matrix. This latter expression can be formulated as\n", "a matrix-product on the form" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "\n", "
\n", "\n", "$$\n", "\\begin{equation}\n", " H = X J,\n", "\\label{_auto21} \\tag{39}\n", "\\end{equation}\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "where $X_{jk} = s_j s_k$ and $J$ is the matrix consisting of the\n", "elements $-J_{jk}$. This form of writing the energy fits perfectly\n", "with the form utilized in linear regression, viz." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "\n", "
\n", "\n", "$$\n", "\\begin{equation}\n", " y = X\\omega + \\epsilon,\n", "\\label{_auto22} \\tag{40}\n", "\\end{equation}\n", "$$" ] }, { "cell_type": "code", "execution_count": 51, "metadata": { "collapsed": false }, "outputs": [], "source": [ "X = np.zeros((n, L ** 2))\n", "for i in range(n):\n", " X[i] = np.outer(spins[i], spins[i]).ravel()\n", "y = energies\n", "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.96)\n", "\n", "X_train_own = np.concatenate(\n", " (np.ones(len(X_train))[:, np.newaxis], X_train),\n", " axis=1\n", ")\n", "\n", "X_test_own = np.concatenate(\n", " (np.ones(len(X_test))[:, np.newaxis], X_test),\n", " axis=1\n", ")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Linear regression\n", "\n", "The problem at hand is to try to fit the equation" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "\n", "
\n", "\n", "$$\n", "\\begin{equation}\n", " y = f(x) + \\epsilon,\n", "\\label{_auto23} \\tag{41}\n", "\\end{equation}\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "where $f(x)$ is some unknown function of the data $x$ and $\\epsilon$\n", "is normally distributed with mean zero noise with standard deviation\n", "$\\sigma_{\\epsilon}$. Our job is to try to find a predictor which\n", "estimates the function $f(x)$. In linear regression we assume that we\n", "can formulate the problem as" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "\n", "
\n", "\n", "$$\n", "\\begin{equation}\n", " y = X\\omega + \\epsilon,\n", "\\label{_auto24} \\tag{42}\n", "\\end{equation}\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "where $X$ and $\\omega$ are now matrices. Our job at hand is now to\n", "find a **cost function** $C$, which we wish to minimize in order to find\n", "the best estimate of $\\omega$.\n", "\n", "\n", "## Ordinary least squares\n", "\n", "In the ordinary least squares method we choose the cost function" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "\n", "
\n", "\n", "$$\n", "\\begin{equation}\n", " C(X, \\omega) = ||X\\omega - y||^2\n", " = (X\\omega - y)^T(X\\omega - y)\n", "\\label{_auto25} \\tag{43}\n", "\\end{equation}\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "We then find the extremal point of $C$ by taking the derivative with respect to $\\omega$ and setting it to zero, i.e.," ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "\n", "
\n", "\n", "$$\n", "\\begin{equation}\n", " \\dfrac{\\mathrm{d}C}{\\mathrm{d}\\omega}\n", " = 0.\n", "\\label{_auto26} \\tag{44}\n", "\\end{equation}\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "This yields the expression for $\\omega$ to be" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "\n", "
\n", "\n", "$$\n", "\\begin{equation}\n", " \\omega = \\frac{X^T y}{X^T X},\n", "\\label{_auto27} \\tag{45}\n", "\\end{equation}\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "which immediately imposes some requirements on $X$ as there must exist\n", "an inverse of $X^T X$. If the expression we are modelling contains an\n", "intercept, i.e., a constant expression we must make sure that the\n", "first column of $X$ consists of $1$." ] }, { "cell_type": "code", "execution_count": 52, "metadata": { "collapsed": false }, "outputs": [], "source": [ "def get_ols_weights_naive(x: np.ndarray, y: np.ndarray) -> np.ndarray:\n", " return scl.inv(x.T @ x) @ (x.T @ y)\n", "omega = get_ols_weights_naive(X_train_own, y_train)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Singular Value decomposition\n", "Doing the inversion directly turns out to be a bad idea as the matrix\n", "$X^TX$ is singular. An alternative approach is to use the **singular\n", "value decomposition**. Using the definition of the Moore-Penrose\n", "pseudoinverse we can write the equation for $\\omega$ as" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "\n", "
\n", "\n", "$$\n", "\\begin{equation}\n", " \\omega = X^{+}y,\n", "\\label{_auto28} \\tag{46}\n", "\\end{equation}\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "where the pseudoinverse of $X$ is given by" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "\n", "
\n", "\n", "$$\n", "\\begin{equation}\n", " X^{+} = \\frac{X^T}{X^T X}.\n", "\\label{_auto29} \\tag{47}\n", "\\end{equation}\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Using singular value decomposition we have that $X = U\\Sigma V^T$,\n", "where $X^{+} = V\\Sigma^{+} U^T$. This reduces the equation for\n", "$\\omega$ to" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "\n", "
\n", "\n", "$$\n", "\\begin{equation}\n", " \\omega = V\\Sigma^{+} U^T y.\n", "\\label{_auto30} \\tag{48}\n", "\\end{equation}\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Note that solving this equation by actually doing the pseudoinverse\n", "(which is what we will do) is not a good idea as this operation scales\n", "as $\\mathcal{O}(n^3)$, where $n$ is the number of elements in a\n", "general matrix. Instead, doing $QR$-factorization and solving the\n", "linear system as an equation would reduce this down to\n", "$\\mathcal{O}(n^2)$ operations." ] }, { "cell_type": "code", "execution_count": 53, "metadata": { "collapsed": false }, "outputs": [], "source": [ "def get_ols_weights(x: np.ndarray, y: np.ndarray) -> np.ndarray:\n", " u, s, v = scl.svd(x)\n", " return v.T @ scl.pinv(scl.diagsvd(s, u.shape[0], v.shape[0])) @ u.T @ y" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Before passing in the data to the function we append a column with ones to the training data." ] }, { "cell_type": "code", "execution_count": 54, "metadata": { "collapsed": false }, "outputs": [], "source": [ "omega = get_ols_weights(X_train_own,y_train)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Fitting with scikit-learn\n", "\n", "Next we fit a `LinearRegression`-model from Scikit-learn for comparison." ] }, { "cell_type": "code", "execution_count": 55, "metadata": { "collapsed": false }, "outputs": [], "source": [ "clf = skl.LinearRegression().fit(X_train, y_train)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Extracting the $J$-matrix from both our own method and the Scikit-learn model where we make sure to remove the intercept." ] }, { "cell_type": "code", "execution_count": 56, "metadata": { "collapsed": false }, "outputs": [], "source": [ "J_own = omega[1:].reshape(L, L)\n", "J_sk = clf.coef_.reshape(L, L)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "A way of looking at the coefficients in $J$ is to plot the matrices as images." ] }, { "cell_type": "code", "execution_count": 57, "metadata": { "collapsed": false }, "outputs": [], "source": [ "fig = plt.figure(figsize=(20, 14))\n", "im = plt.imshow(J_own, **cmap_args)\n", "plt.title(\"Home-made OLS\", fontsize=18)\n", "plt.xticks(fontsize=18)\n", "plt.yticks(fontsize=18)\n", "cb = fig.colorbar(im)\n", "cb.ax.set_yticklabels(cb.ax.get_yticklabels(), fontsize=18)\n", "\n", "fig = plt.figure(figsize=(20, 14))\n", "im = plt.imshow(J_sk, **cmap_args)\n", "plt.title(\"LinearRegression from Scikit-learn\", fontsize=18)\n", "plt.xticks(fontsize=18)\n", "plt.yticks(fontsize=18)\n", "cb = fig.colorbar(im)\n", "cb.ax.set_yticklabels(cb.ax.get_yticklabels(), fontsize=18)\n", "plt.show()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "We can see that our model for the least squares method performes close\n", "to the benchmark from Scikit-learn. It is interesting to note that OLS\n", "considers both $J_{j, j + 1} = -0.5$ and $J_{j, j - 1} = -0.5$ as\n", "valid matrix elements for $J$.\n", "\n", "\n", "## Ridge regression\n", "\n", "Having explored the ordinary least squares we move on to ridge\n", "regression. In ridge regression we include a **regularizer**. This\n", "involves a new cost function which leads to a new estimate for the\n", "weights $\\omega$. This results in a penalized regression problem. The\n", "cost function is given by" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "\n", "
\n", "\n", "$$\n", "\\begin{equation}\n", " C(X, \\omega; \\lambda) = ||X\\omega - y||^2 + \\lambda ||\\omega||^2\n", " = (X\\omega - y)^T(X\\omega - y) + \\lambda \\omega^T\\omega.\n", "\\label{_auto31} \\tag{49}\n", "\\end{equation}\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Finding the extremum of this function yields the weights" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "\n", "
\n", "\n", "$$\n", "\\begin{equation}\n", " \\omega(\\lambda) = \\frac{X^Ty}{X^TX + \\lambda} \\to \\frac{\\omega_{\\text{LS}}}{1 + \\lambda},\n", "\\label{_auto32} \\tag{50}\n", "\\end{equation}\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "where $\\omega_{\\text{LS}}$ is the weights from ordinary least\n", "squares. The last assumption assumes that $X$ is orthogonal, which it\n", "is not. We will therefore resort to solving the equation as it stands\n", "on the left hand side." ] }, { "cell_type": "code", "execution_count": 58, "metadata": { "collapsed": false }, "outputs": [], "source": [ "def get_ridge_weights(x: np.ndarray, y: np.ndarray, _lambda: float) -> np.ndarray:\n", " return x.T @ y @ scl.inv(\n", " x.T @ x + np.eye(x.shape[1], x.shape[1]) * _lambda\n", " )\n", "lambda = 0.1\n", "omega_ridge = get_ridge_weights(X_train_own, y_train, np.array([_lambda]))\n", "clf_ridge = skl.Ridge(alpha=_lambda).fit(X_train, y_train)\n", "J_ridge_own = omega_ridge[1:].reshape(L, L)\n", "J_ridge_sk = clf_ridge.coef_.reshape(L, L)\n", "fig = plt.figure(figsize=(20, 14))\n", "im = plt.imshow(J_ridge_own, **cmap_args)\n", "plt.title(\"Home-made ridge regression\", fontsize=18)\n", "plt.xticks(fontsize=18)\n", "plt.yticks(fontsize=18)\n", "cb = fig.colorbar(im)\n", "cb.ax.set_yticklabels(cb.ax.get_yticklabels(), fontsize=18)\n", "\n", "fig = plt.figure(figsize=(20, 14))\n", "im = plt.imshow(J_ridge_sk, **cmap_args)\n", "plt.title(\"Ridge from Scikit-learn\", fontsize=18)\n", "plt.xticks(fontsize=18)\n", "plt.yticks(fontsize=18)\n", "cb = fig.colorbar(im)\n", "cb.ax.set_yticklabels(cb.ax.get_yticklabels(), fontsize=18)\n", "\n", "plt.show()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## LASSO regression\n", "\n", "In the **Least Absolute Shrinkage and Selection Operator** (LASSO)-method we get a third cost function." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "\n", "
\n", "\n", "$$\n", "\\begin{equation}\n", " C(X, \\omega; \\lambda) =\n", " ||X\\omega - y||^2 + \\lambda ||\\omega||\n", " = (X\\omega - y)^T(X\\omega - y) + \\lambda \\sqrt{\\omega^T\\omega}.\n", "\\label{_auto33} \\tag{51}\n", "\\end{equation}\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Finding the extremal point of this cost function is not so straight-forward as in least squares and ridge. We will therefore rely solely on the function ``Lasso`` from Scikit-learn." ] }, { "cell_type": "code", "execution_count": 59, "metadata": { "collapsed": false }, "outputs": [], "source": [ "clf_lasso = skl.Lasso(alpha=_lambda).fit(X_train, y_train)\n", "J_lasso_sk = clf_lasso.coef_.reshape(L, L)\n", "fig = plt.figure(figsize=(20, 14))\n", "im = plt.imshow(J_lasso_sk, **cmap_args)\n", "plt.title(\"Lasso from Scikit-learn\", fontsize=18)\n", "plt.xticks(fontsize=18)\n", "plt.yticks(fontsize=18)\n", "cb = fig.colorbar(im)\n", "cb.ax.set_yticklabels(cb.ax.get_yticklabels(), fontsize=18)\n", "\n", "plt.show()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "It is quite striking how LASSO breaks the symmetry of the coupling\n", "constant as opposed to ridge and OLS. We get a sparse solution with\n", "$J_{j, j + 1} = -1$.\n", "\n", "\n", "\n", "## Performance of the different models\n", "\n", "In order to judge which model performs best at varying values of $\\lambda$ (for ridge and LASSO) we compute $R^2$ which is given by" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "\n", "
\n", "\n", "$$\n", "\\begin{equation}\n", " R^2 = 1 - \\frac{(y - \\hat{y})^2}{(y - \\bar{y})^2},\n", "\\label{_auto34} \\tag{52}\n", "\\end{equation}\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "where $y$ is a vector with the true values of the energy, $\\hat{y}$ is the predicted values of $y$ from the models and $\\bar{y}$ is the mean of $\\hat{y}$." ] }, { "cell_type": "code", "execution_count": 60, "metadata": { "collapsed": false }, "outputs": [], "source": [ "def r_squared(y, y_hat):\n", " return 1 - np.sum((y - y_hat) ** 2) / np.sum((y - np.mean(y_hat)) ** 2)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "This is the same metric used by Scikit-learn for their regression models when scoring." ] }, { "cell_type": "code", "execution_count": 61, "metadata": { "collapsed": false }, "outputs": [], "source": [ "y_hat = clf.predict(X_test)\n", "r_test = r_squared(y_test, y_hat)\n", "sk_r_test = clf.score(X_test, y_test)\n", "\n", "assert abs(r_test - sk_r_test) < 1e-2" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Performance as function of the regularization parameter\n", "\n", "We see how the different models perform for a different set of values for $\\lambda$." ] }, { "cell_type": "code", "execution_count": 62, "metadata": { "collapsed": false }, "outputs": [], "source": [ "lambdas = np.logspace(-4, 5, 10)\n", "\n", "train_errors = {\n", " \"ols_own\": np.zeros(lambdas.size),\n", " \"ols_sk\": np.zeros(lambdas.size),\n", " \"ridge_own\": np.zeros(lambdas.size),\n", " \"ridge_sk\": np.zeros(lambdas.size),\n", " \"lasso_sk\": np.zeros(lambdas.size)\n", "}\n", "\n", "test_errors = {\n", " \"ols_own\": np.zeros(lambdas.size),\n", " \"ols_sk\": np.zeros(lambdas.size),\n", " \"ridge_own\": np.zeros(lambdas.size),\n", " \"ridge_sk\": np.zeros(lambdas.size),\n", " \"lasso_sk\": np.zeros(lambdas.size)\n", "}\n", "\n", "plot_counter = 1\n", "\n", "fig = plt.figure(figsize=(32, 54))\n", "\n", "for i, _lambda in enumerate(tqdm.tqdm(lambdas)):\n", " omega = get_ols_weights(X_train_own, y_train)\n", " y_hat_train = X_train_own @ omega\n", " y_hat_test = X_test_own @ omega\n", "\n", " train_errors[\"ols_own\"][i] = r_squared(y_train, y_hat_train)\n", " test_errors[\"ols_own\"][i] = r_squared(y_test, y_hat_test)\n", "\n", " plt.subplot(10, 5, plot_counter)\n", " plt.imshow(omega[1:].reshape(L, L), **cmap_args)\n", " plt.title(\"Home made OLS\")\n", " plot_counter += 1\n", "\n", " omega = get_ridge_weights(X_train_own, y_train, _lambda)\n", " y_hat_train = X_train_own @ omega\n", " y_hat_test = X_test_own @ omega\n", "\n", " train_errors[\"ridge_own\"][i] = r_squared(y_train, y_hat_train)\n", " test_errors[\"ridge_own\"][i] = r_squared(y_test, y_hat_test)\n", "\n", " plt.subplot(10, 5, plot_counter)\n", " plt.imshow(omega[1:].reshape(L, L), **cmap_args)\n", " plt.title(r\"Home made ridge, $\\lambda = %.4f$\" % _lambda)\n", " plot_counter += 1\n", "\n", " for key, method in zip(\n", " [\"ols_sk\", \"ridge_sk\", \"lasso_sk\"],\n", " [skl.LinearRegression(), skl.Ridge(alpha=_lambda), skl.Lasso(alpha=_lambda)]\n", " ):\n", " method = method.fit(X_train, y_train)\n", "\n", " train_errors[key][i] = method.score(X_train, y_train)\n", " test_errors[key][i] = method.score(X_test, y_test)\n", "\n", " omega = method.coef_.reshape(L, L)\n", "\n", " plt.subplot(10, 5, plot_counter)\n", " plt.imshow(omega, **cmap_args)\n", " plt.title(r\"%s, $\\lambda = %.4f$\" % (key, _lambda))\n", " plot_counter += 1\n", "\n", "plt.show()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "We can see that LASSO quite fast reaches a good solution for low\n", "values of $\\lambda$, but will \"wither\" when we increase $\\lambda$ too\n", "much. Ridge is more stable over a larger range of values for\n", "$\\lambda$, but eventually also fades away.\n", "\n", "\n", "## Finding the optimal value of $\\lambda$\n", "\n", "To determine which value of $\\lambda$ is best we plot the accuracy of\n", "the models when predicting the training and the testing set. We expect\n", "the accuracy of the training set to be quite good, but if the accuracy\n", "of the testing set is much lower this tells us that we might be\n", "subject to an overfit model. The ideal scenario is an accuracy on the\n", "testing set that is close to the accuracy of the training set." ] }, { "cell_type": "code", "execution_count": 63, "metadata": { "collapsed": false }, "outputs": [], "source": [ "fig = plt.figure(figsize=(20, 14))\n", "\n", "colors = {\n", " \"ols_own\": \"b\",\n", " \"ridge_own\": \"g\",\n", " \"ols_sk\": \"r\",\n", " \"ridge_sk\": \"y\",\n", " \"lasso_sk\": \"c\"\n", "}\n", "\n", "for key in train_errors:\n", " plt.semilogx(\n", " lambdas,\n", " train_errors[key],\n", " colors[key],\n", " label=\"Train {0}\".format(key),\n", " linewidth=4.0\n", " )\n", "\n", "for key in test_errors:\n", " plt.semilogx(\n", " lambdas,\n", " test_errors[key],\n", " colors[key] + \"--\",\n", " label=\"Test {0}\".format(key),\n", " linewidth=4.0\n", " )\n", "#plt.semilogx(lambdas, train_errors[\"ols_own\"], label=\"Train (OLS own)\")\n", "#plt.semilogx(lambdas, test_errors[\"ols_own\"], label=\"Test (OLS own)\")\n", "\n", "plt.legend(loc=\"best\", fontsize=18)\n", "plt.xlabel(r\"$\\lambda$\", fontsize=18)\n", "plt.ylabel(r\"$R^2$\", fontsize=18)\n", "plt.tick_params(labelsize=18)\n", "plt.show()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "From the above figure we can see that LASSO with $\\lambda = 10^{-2}$\n", "achieve a very good accuracy on the test set. This by far surpases the\n", "other models for all values of $\\lambda$.\n", "\n", "\n", "\n", "# Optimization and Gradient Methods\n", "\n", "\n", "\n", "## Optimization, the central part of any Machine Learning algortithm\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.\n", "\n", "\n", "\n", "## 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", "metadata": {}, "source": [ "$$\n", "\\begin{align*}\n", "p(y_i=1|x_i,\\hat{\\beta}) &= \\frac{\\exp{(\\beta_0+\\beta_1x_i)}}{1+\\exp{(\\beta_0+\\beta_1x_i)}},\\nonumber\\\\\n", "p(y_i=0|x_i,\\hat{\\beta}) &= 1 - p(y_i=1|x_i,\\hat{\\beta}),\n", "\\end{align*}\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "where $\\hat{\\beta}$ are the weights we wish to extract from data, in our case $\\beta_0$ and $\\beta_1$. \n", "\n", "\n", "## The equations to solve\n", "\n", "Our compact equations used a definition of a vector $\\hat{y}$ with $n$\n", "elements $y_i$, an $n\\times p$ matrix $\\hat{X}$ which contains the\n", "$x_i$ values and a vector $\\hat{p}$ of fitted probabilities\n", "$p(y_i\\vert x_i,\\hat{\\beta})$. We rewrote in a more compact form\n", "the first derivative of the cost function as" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "$$\n", "\\frac{\\partial \\mathcal{C}(\\hat{\\beta})}{\\partial \\hat{\\beta}} = -\\hat{X}^T\\left(\\hat{y}-\\hat{p}\\right).\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "If we in addition define a diagonal matrix $\\hat{W}$ with elements \n", "$p(y_i\\vert x_i,\\hat{\\beta})(1-p(y_i\\vert x_i,\\hat{\\beta})$, we can obtain a compact expression of the second derivative as" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "$$\n", "\\frac{\\partial^2 \\mathcal{C}(\\hat{\\beta})}{\\partial \\hat{\\beta}\\partial \\hat{\\beta}^T} = \\hat{X}^T\\hat{W}\\hat{X}.\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "This defines what is called the Hessian matrix.\n", "\n", "\n", "## 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", "metadata": {}, "source": [ "$$\n", "\\hat{\\beta}^{\\mathrm{new}} = \\hat{\\beta}^{\\mathrm{old}}-\\left(\\frac{\\partial^2 \\mathcal{C}(\\hat{\\beta})}{\\partial \\hat{\\beta}\\partial \\hat{\\beta}^T}\\right)^{-1}_{\\hat{\\beta}^{\\mathrm{old}}}\\times \\left(\\frac{\\partial \\mathcal{C}(\\hat{\\beta})}{\\partial \\hat{\\beta}}\\right)_{\\hat{\\beta}^{\\mathrm{old}}},\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "or in matrix form as" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "$$\n", "\\hat{\\beta}^{\\mathrm{new}} = \\hat{\\beta}^{\\mathrm{old}}-\\left(\\hat{X}^T\\hat{W}\\hat{X} \\right)^{-1}\\times \\left(-\\hat{X}^T(\\hat{y}-\\hat{p}) \\right)_{\\hat{\\beta}^{\\mathrm{old}}}.\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "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. \n", "\n", "\n", "\n", "## 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.\n", "\n", "\n", "## 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", "metadata": {}, "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{53}\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "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", "metadata": {}, "source": [ "$$\n", "f(x)+(s-x)f'(x)\\approx 0,\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "yielding" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "$$\n", "s\\approx x-\\frac{f(x)}{f'(x)}.\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Having in mind an iterative procedure, it is natural to start iterating with" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "$$\n", "x_{n+1}=x_n-\\frac{f(x_n)}{f'(x_n)}.\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "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\n", "\n", "\n", "\n", "## 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", "metadata": {}, "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", "metadata": {}, "source": [ "which we Taylor expand to obtain" ] }, { "cell_type": "markdown", "metadata": {}, "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", "metadata": {}, "source": [ "Defining the Jacobian matrix $\\hat{J}$ we have" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "$$\n", "\\hat{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", "metadata": {}, "source": [ "we can rephrase Newton's method as" ] }, { "cell_type": "markdown", "metadata": {}, "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", "metadata": {}, "source": [ "where we have defined" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "$$\n", "\\left(\\begin{array}{c} h_1^{n} \\\\ h_2^{n} \\end{array} \\right)=\n", " -\\hat{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", "metadata": {}, "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 $\\hat{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. \n", "\n", "\n", "\n", "\n", "## 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", "metadata": {}, "source": [ "$$\n", "\\mathbf{x}_{k+1} = \\mathbf{x}_k - \\gamma_k \\nabla F(\\mathbf{x}_k),\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "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.\n", "\n", "\n", "## 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", "metadata": {}, "source": [ "$$\n", "\\mathbf{x}_{k+1} = \\mathbf{x}_k - \\gamma_k \\nabla F(\\mathbf{x}_k), \\ \\ k \\geq 0.\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "The parameter $\\gamma_k$ is often referred to as the step length or\n", "the learning rate within the context of Machine Learning.\n", "\n", "\n", "## 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.\n", "\n", "\n", "\n", "## 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.\n", "\n", "\n", "\n", "## 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...).\n", "\n", "\n", "## 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.\n", "\n", "\n", "## 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", "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", "\n", " Second order condition \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", "\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.\n", "\n", "\n", "## 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", "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", "\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.\n", "\n", "\n", "## 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", "\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", "\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).\n", "\n", "\n", "\n", "## Standard steepest descent\n", "\n", "\n", "Before we proceed, we would like to discuss the approach called the\n", "**standard Steepest descent**, 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", "metadata": {}, "source": [ "$$\n", "\\hat{A}\\hat{x} = \\hat{b}.\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "In the iterative process we end up with a problem like" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "$$\n", "\\hat{r}= \\hat{b}-\\hat{A}\\hat{x},\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "where $\\hat{r}$ is the so-called residual or error in the iterative process.\n", "\n", "When we have found the exact solution, $\\hat{r}=0$.\n", "\n", "\n", "## Gradient method\n", "\n", "The residual is zero when we reach the minimum of the quadratic equation" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "$$\n", "P(\\hat{x})=\\frac{1}{2}\\hat{x}^T\\hat{A}\\hat{x} - \\hat{x}^T\\hat{b},\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "with the constraint that the matrix $\\hat{A}$ is positive definite and\n", "symmetric. This defines also the Hessian and we want it to be positive definite. \n", "\n", "\n", "\n", "## Steepest descent method\n", "\n", "We denote the initial guess for $\\hat{x}$ as $\\hat{x}_0$. \n", "We can assume without loss of generality that" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "$$\n", "\\hat{x}_0=0,\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "or consider the system" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "$$\n", "\\hat{A}\\hat{z} = \\hat{b}-\\hat{A}\\hat{x}_0,\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "instead.\n", "\n", "\n", "\n", "## Steepest descent method\n", "\n", "One can show that the solution $\\hat{x}$ is also the unique minimizer of the quadratic form" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "$$\n", "f(\\hat{x}) = \\frac{1}{2}\\hat{x}^T\\hat{A}\\hat{x} - \\hat{x}^T \\hat{x} , \\quad \\hat{x}\\in\\mathbf{R}^n.\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "This suggests taking the first basis vector $\\hat{r}_1$ (see below for definition) \n", "to be the gradient of $f$ at $\\hat{x}=\\hat{x}_0$, \n", "which equals" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "$$\n", "\\hat{A}\\hat{x}_0-\\hat{b},\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "and \n", "$\\hat{x}_0=0$ it is equal $-\\hat{b}$.\n", "\n", "\n", "\n", "\n", "## Final expressions\n", "\n", "We can compute the residual iteratively as" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "$$\n", "\\hat{r}_{k+1}=\\hat{b}-\\hat{A}\\hat{x}_{k+1},\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "which equals" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "$$\n", "\\hat{b}-\\hat{A}(\\hat{x}_k+\\alpha_k\\hat{r}_k),\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "or" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "$$\n", "(\\hat{b}-\\hat{A}\\hat{x}_k)-\\alpha_k\\hat{A}\\hat{r}_k,\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "which gives" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "$$\n", "\\alpha_k = \\frac{\\hat{r}_k^T\\hat{r}_k}{\\hat{r}_k^T\\hat{A}\\hat{r}_k}\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "leading to the iterative scheme" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "$$\n", "\\hat{x}_{k+1}=\\hat{x}_k-\\alpha_k\\hat{r}_{k},\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Code examples for steepest descent\n", "\n", "\n", "## Simple codes for steepest descent and conjugate gradient using a $2\\times 2$ matrix, in c++, Python code to come" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ " #include \n", " #include \n", " #include \n", " #include \n", " #include \"vectormatrixclass.h\"\n", " using namespace std;\n", " // Main function begins here\n", " int main(int argc, char * argv[]){\n", " int dim = 2;\n", " Vector x(dim),xsd(dim), b(dim),x0(dim);\n", " Matrix A(dim,dim);\n", " \n", " // Set our initial guess\n", " x0(0) = x0(1) = 0;\n", " // Set the matrix\n", " A(0,0) = 3; A(1,0) = 2; A(0,1) = 2; A(1,1) = 6;\n", " b(0) = 2; b(1) = -8;\n", " cout << \"The Matrix A that we are using: \" << endl;\n", " A.Print();\n", " cout << endl;\n", " xsd = SteepestDescent(A,b,x0);\n", " cout << \"The approximate solution using Steepest Descent is: \" << endl;\n", " xsd.Print();\n", " cout << endl;\n", " }\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## The routine for the steepest descent method" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ " Vector SteepestDescent(Matrix A, Vector b, Vector x0){\n", " int IterMax, i;\n", " int dim = x0.Dimension();\n", " const double tolerance = 1.0e-14;\n", " Vector x(dim),f(dim),z(dim);\n", " double c,alpha,d;\n", " IterMax = 30;\n", " x = x0;\n", " r = A*x-b;\n", " i = 0;\n", " while (i <= IterMax){\n", " z = A*r;\n", " c = dot(r,r);\n", " alpha = c/dot(r,z);\n", " x = x - alpha*r;\n", " r = A*x-b;\n", " if(sqrt(dot(r,r)) < tolerance) break;\n", " i++;\n", " }\n", " return x;\n", " }\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Steepest descent example" ] }, { "cell_type": "code", "execution_count": 64, "metadata": { "collapsed": false }, "outputs": [], "source": [ "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 0.5*x[0]**2 + 2.5*x[1]**2\n", "\n", "def df(x):\n", " return np.array([x[0], 5*x[1]])\n", "\n", "fig = pt.figure()\n", "ax = fig.gca(projection=\"3d\")\n", "\n", "xmesh, ymesh = np.mgrid[-2:2:50j,-2:2:50j]\n", "fmesh = f(np.array([xmesh, ymesh]))\n", "ax.plot_surface(xmesh, ymesh, fmesh)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "And then as countor plot" ] }, { "cell_type": "code", "execution_count": 65, "metadata": { "collapsed": false }, "outputs": [], "source": [ "pt.axis(\"equal\")\n", "pt.contour(xmesh, ymesh, fmesh)\n", "guesses = [np.array([2, 2./5])]" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Find guesses" ] }, { "cell_type": "code", "execution_count": 66, "metadata": { "collapsed": false }, "outputs": [], "source": [ "x = guesses[-1]\n", "s = -df(x)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Run it!" ] }, { "cell_type": "code", "execution_count": 67, "metadata": { "collapsed": false }, "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", "metadata": {}, "source": [ "What happened?" ] }, { "cell_type": "code", "execution_count": 68, "metadata": { "collapsed": false }, "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", "metadata": {}, "source": [ "## Conjugate gradient method\n", "\n", "In the CG method we define so-called conjugate directions and two vectors \n", "$\\hat{s}$ and $\\hat{t}$\n", "are said to be\n", "conjugate if" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "$$\n", "\\hat{s}^T\\hat{A}\\hat{t}= 0.\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "The philosophy of the CG method is to perform searches in various conjugate directions\n", "of our vectors $\\hat{x}_i$ obeying the above criterion, namely" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "$$\n", "\\hat{x}_i^T\\hat{A}\\hat{x}_j= 0.\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Two vectors are conjugate if they are orthogonal with respect to \n", "this inner product. Being conjugate is a symmetric relation: if $\\hat{s}$ is conjugate to $\\hat{t}$, then $\\hat{t}$ is conjugate to $\\hat{s}$.\n", "\n", "\n", "\n", "## Conjugate gradient method\n", "\n", "An example is given by the eigenvectors of the matrix" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "$$\n", "\\hat{v}_i^T\\hat{A}\\hat{v}_j= \\lambda\\hat{v}_i^T\\hat{v}_j,\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "which is zero unless $i=j$. \n", "\n", "\n", "\n", "\n", "## Conjugate gradient method\n", "\n", "Assume now that we have a symmetric positive-definite matrix $\\hat{A}$ of size\n", "$n\\times n$. At each iteration $i+1$ we obtain the conjugate direction of a vector" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "$$\n", "\\hat{x}_{i+1}=\\hat{x}_{i}+\\alpha_i\\hat{p}_{i}.\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "We assume that $\\hat{p}_{i}$ is a sequence of $n$ mutually conjugate directions. \n", "Then the $\\hat{p}_{i}$ form a basis of $R^n$ and we can expand the solution \n", "$ \\hat{A}\\hat{x} = \\hat{b}$ in this basis, namely" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "$$\n", "\\hat{x} = \\sum^{n}_{i=1} \\alpha_i \\hat{p}_i.\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Conjugate gradient method\n", "\n", "The coefficients are given by" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "$$\n", "\\mathbf{A}\\mathbf{x} = \\sum^{n}_{i=1} \\alpha_i \\mathbf{A} \\mathbf{p}_i = \\mathbf{b}.\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Multiplying with $\\hat{p}_k^T$ from the left gives" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "$$\n", "\\hat{p}_k^T \\hat{A}\\hat{x} = \\sum^{n}_{i=1} \\alpha_i\\hat{p}_k^T \\hat{A}\\hat{p}_i= \\hat{p}_k^T \\hat{b},\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "and we can define the coefficients $\\alpha_k$ as" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "$$\n", "\\alpha_k = \\frac{\\hat{p}_k^T \\hat{b}}{\\hat{p}_k^T \\hat{A} \\hat{p}_k}\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Conjugate gradient method and iterations\n", "\n", "\n", "If we choose the conjugate vectors $\\hat{p}_k$ carefully, \n", "then we may not need all of them to obtain a good approximation to the solution \n", "$\\hat{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 $\\hat{x}$ as $\\hat{x}_0$. \n", "We can assume without loss of generality that" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "$$\n", "\\hat{x}_0=0,\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "or consider the system" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "$$\n", "\\hat{A}\\hat{z} = \\hat{b}-\\hat{A}\\hat{x}_0,\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "instead.\n", "\n", "\n", "\n", "\n", "## Conjugate gradient method\n", "\n", "One can show that the solution $\\hat{x}$ is also the unique minimizer of the quadratic form" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "$$\n", "f(\\hat{x}) = \\frac{1}{2}\\hat{x}^T\\hat{A}\\hat{x} - \\hat{x}^T \\hat{x} , \\quad \\hat{x}\\in\\mathbf{R}^n.\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "This suggests taking the first basis vector $\\hat{p}_1$ \n", "to be the gradient of $f$ at $\\hat{x}=\\hat{x}_0$, \n", "which equals" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "$$\n", "\\hat{A}\\hat{x}_0-\\hat{b},\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "and \n", "$\\hat{x}_0=0$ it is equal $-\\hat{b}$.\n", "The other vectors in the basis will be conjugate to the gradient, \n", "hence the name conjugate gradient method.\n", "\n", "\n", "\n", "\n", "## Conjugate gradient method\n", "\n", "Let $\\hat{r}_k$ be the residual at the $k$-th step:" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "$$\n", "\\hat{r}_k=\\hat{b}-\\hat{A}\\hat{x}_k.\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Note that $\\hat{r}_k$ is the negative gradient of $f$ at \n", "$\\hat{x}=\\hat{x}_k$, \n", "so the gradient descent method would be to move in the direction $\\hat{r}_k$. \n", "Here, we insist that the directions $\\hat{p}_k$ are conjugate to each other, \n", "so we take the direction closest to the gradient $\\hat{r}_k$ \n", "under the conjugacy constraint. \n", "This gives the following expression" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "$$\n", "\\hat{p}_{k+1}=\\hat{r}_k-\\frac{\\hat{p}_k^T \\hat{A}\\hat{r}_k}{\\hat{p}_k^T\\hat{A}\\hat{p}_k} \\hat{p}_k.\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Conjugate gradient method\n", "\n", "We can also compute the residual iteratively as" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "$$\n", "\\hat{r}_{k+1}=\\hat{b}-\\hat{A}\\hat{x}_{k+1},\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "which equals" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "$$\n", "\\hat{b}-\\hat{A}(\\hat{x}_k+\\alpha_k\\hat{p}_k),\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "or" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "$$\n", "(\\hat{b}-\\hat{A}\\hat{x}_k)-\\alpha_k\\hat{A}\\hat{p}_k,\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "which gives" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "$$\n", "\\hat{r}_{k+1}=\\hat{r}_k-\\hat{A}\\hat{p}_{k},\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Simple implementation of the Conjugate gradient algorithm" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ " Vector ConjugateGradient(Matrix A, Vector b, Vector x0){\n", " int dim = x0.Dimension();\n", " const double tolerance = 1.0e-14;\n", " Vector x(dim),r(dim),v(dim),z(dim);\n", " double c,t,d;\n", " \n", " x = x0;\n", " r = b - A*x;\n", " v = r;\n", " c = dot(r,r);\n", " int i = 0; IterMax = dim;\n", " while(i <= IterMax){\n", " z = A*v;\n", " t = c/dot(v,z);\n", " x = x + t*v;\n", " r = r - t*z;\n", " d = dot(r,r);\n", " if(sqrt(d) < tolerance)\n", " break;\n", " v = r + (d/c)*v;\n", " c = d; i++;\n", " }\n", " return x;\n", " } \n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Broyden–Fletcher–Goldfarb–Shanno algorithm\n", "\n", "The optimization problem is to minimize $f(\\mathbf {x} )$ where $\\mathbf {x}$ is a vector in $R^{n}$, and $f$ is a differentiable scalar function. There are no constraints on the values that $\\mathbf {x}$ can take.\n", "\n", "The algorithm begins at an initial estimate for the optimal value $\\mathbf {x}_{0}$ and proceeds iteratively to get a better estimate at each stage.\n", "\n", "The search direction $p_k$ at stage $k$ is given by the solution of the analogue of the Newton equation" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "$$\n", "B_{k}\\mathbf {p} _{k}=-\\nabla f(\\mathbf {x}_{k}),\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "where $B_{k}$ is an approximation to the Hessian matrix, which is\n", "updated iteratively at each stage, and $\\nabla f(\\mathbf {x} _{k})$\n", "is the gradient of the function\n", "evaluated at $x_k$. \n", "A line search in the direction $p_k$ is then used to\n", "find the next point $x_{k+1}$ by minimising" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "$$\n", "f(\\mathbf {x}_{k}+\\alpha \\mathbf {p}_{k}),\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "over the scalar $\\alpha > 0$.\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "## 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 the example from homework set 1 where we had" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "$$\n", "y_i = 5x_i^2 + 0.1\\xi_i, \\ i=1,\\cdots,100\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "with $x_i \\in [0,1] $ chosen randomly with a uniform distribution. Additionally $\\xi_i$ represents stochastic noise chosen according to a normal distribution $\\cal {N}(0,1)$. \n", "The linear regression model is given by" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "$$\n", "h_\\beta(x) = \\hat{y} = \\beta_0 + \\beta_1 x,\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "such that" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "$$\n", "\\hat{y}_i = \\beta_0 + \\beta_1 x_i.\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Gradient descent example\n", "\n", "Let $\\mathbf{y} = (y_1,\\cdots,y_n)^T$, $\\mathbf{\\hat{y}} = (\\hat{y}_1,\\cdots,\\hat{y}_n)^T$ and $\\beta = (\\beta_0, \\beta_1)^T$\n", "\n", "It is convenient to write $\\mathbf{\\hat{y}} = X\\beta$ where $X \\in \\mathbb{R}^{100 \\times 2} $ is the design matrix given by" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "$$\n", "X \\equiv \\begin{bmatrix}\n", "1 & x_1 \\\\\n", "\\vdots & \\vdots \\\\\n", "1 & x_{100} & \\\\\n", "\\end{bmatrix}.\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "The loss function is given by" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "$$\n", "C(\\beta) = ||X\\beta-\\mathbf{y}||^2 = ||X\\beta||^2 - 2 \\mathbf{y}^T X\\beta + ||\\mathbf{y}||^2 = \\sum_{i=1}^{100} (\\beta_0 + \\beta_1 x_i)^2 - 2 y_i (\\beta_0 + \\beta_1 x_i) + y_i^2\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "and we want to find $\\beta$ such that $C(\\beta)$ is minimized.\n", "\n", "\n", "## 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", "metadata": {}, "source": [ "$$\n", "\\nabla_{\\beta} C(\\beta) = (\\partial C(\\beta) / \\partial \\beta_0, \\partial C(\\beta) / \\partial \\beta_1)^T = 2\\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} = 2X^T(X\\beta - \\mathbf{y}),\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "where $X$ is the design matrix defined above.\n", "\n", "\n", "## The Hessian matrix\n", "The Hessian matrix of $C(\\beta)$ is given by" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "$$\n", "\\hat{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} = 2X^T X.\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "This result implies that $C(\\beta)$ is a convex function since the matrix $X^T X$ always is positive semi-definite.\n", "\n", "\n", "\n", "\n", "\n", "## 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", "metadata": {}, "source": [ "$$\n", "\\beta_{k+1} = \\beta_k - \\gamma \\nabla_\\beta C(\\beta_k), \\ k=0,1,\\cdots\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "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}$. \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": "code", "execution_count": 69, "metadata": { "collapsed": false }, "outputs": [], "source": [ "import numpy as np\n", "\n", "\"\"\"\n", "The following setup is just a suggestion, feel free to write it the way you like.\n", "\"\"\"\n", "\n", "#Setup problem described in the exercise\n", "N = 100 #Nr of datapoints\n", "M = 2 #Nr of features\n", "x = np.random.rand(N) #Uniformly generated x-values in [0,1]\n", "y = 5*x**2 + 0.1*np.random.randn(N)\n", "X = np.c_[np.ones(N),x] #Construct design matrix\n", "\n", "#Compute beta according to normal equations to compare with GD solution\n", "Xt_X_inv = np.linalg.inv(np.dot(X.T,X))\n", "Xt_y = np.dot(X.transpose(),y)\n", "beta_NE = np.dot(Xt_X_inv,Xt_y)\n", "print(beta_NE)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Gradient Descent Example\n", "\n", "Another simple example is here" ] }, { "cell_type": "code", "execution_count": 70, "metadata": { "collapsed": false }, "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", "x = 2*np.random.rand(100,1)\n", "y = 4+3*x+np.random.randn(100,1)\n", "\n", "xb = np.c_[np.ones((100,1)), x]\n", "beta_linreg = np.linalg.inv(xb.T.dot(xb)).dot(xb.T).dot(y)\n", "print(beta_linreg)\n", "beta = np.random.randn(2,1)\n", "\n", "eta = 0.1\n", "Niterations = 1000\n", "m = 100\n", "\n", "for iter in range(Niterations):\n", " gradients = 2.0/m*xb.T.dot(xb.dot(beta)-y)\n", " beta -= eta*gradients\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", "metadata": {}, "source": [ "## And a corresponding example using **scikit-learn**" ] }, { "cell_type": "code", "execution_count": 71, "metadata": { "collapsed": false }, "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", "x = 2*np.random.rand(100,1)\n", "y = 4+3*x+np.random.randn(100,1)\n", "\n", "xb = np.c_[np.ones((100,1)), x]\n", "beta_linreg = np.linalg.inv(xb.T.dot(xb)).dot(xb.T).dot(y)\n", "print(beta_linreg)\n", "sgdreg = SGDRegressor(n_iter = 50, penalty=None, eta0=0.1)\n", "sgdreg.fit(x,y.ravel())\n", "print(sgdreg.intercept_, sgdreg.coef_)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Gradient descent and Ridge\n", "\n", "We have also discussed Ridge regression where the loss function contains a regularized given by the $L_2$ norm of $\\beta$," ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "$$\n", "C_{\\text{ridge}}(\\beta) = ||X\\beta -\\mathbf{y}||^2 + \\lambda ||\\beta||^2, \\ \\lambda \\geq 0.\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "In order to minimize $C_{\\text{ridge}}(\\beta)$ using GD we only have adjust the gradient as follows" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "$$\n", "\\nabla_\\beta C_{\\text{ridge}}(\\beta) = 2\\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 (X^T(X\\beta - \\mathbf{y})+\\lambda \\beta).\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "We can now extend our program to minimize $C_{\\text{ridge}}(\\beta)$ using gradient descent and compare with the analytical solution given by" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "$$\n", "\\beta_{\\text{ridge}} = \\left(X^T X + \\lambda I_{2 \\times 2} \\right)^{-1} X^T \\mathbf{y},\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "for $\\lambda = {0,1,10,50,100}$ ($\\lambda = 0$ corresponds to ordinary least squares). \n", "We can then compute $||\\beta_{\\text{ridge}}||$ for each $\\lambda$." ] }, { "cell_type": "code", "execution_count": 72, "metadata": { "collapsed": false }, "outputs": [], "source": [ "import numpy as np\n", "\n", "\"\"\"\n", "The following setup is just a suggestion, feel free to write it the way you like.\n", "\"\"\"\n", "\n", "#Setup problem described in the exercise\n", "N = 100 #Nr of datapoints\n", "M = 2 #Nr of features\n", "x = np.random.rand(N)\n", "y = 5*x**2 + 0.1*np.random.randn(N)\n", "\n", "\n", "#Compute analytic beta for Ridge regression \n", "X = np.c_[np.ones(N),x]\n", "XT_X = np.dot(X.T,X)\n", "\n", "l = 0.1 #Ridge parameter lambda\n", "Id = np.eye(XT_X.shape[0])\n", "\n", "Z = np.linalg.inv(XT_X+l*Id)\n", "beta_ridge = np.dot(Z,np.dot(X.T,y))\n", "\n", "print(beta_ridge)\n", "print(np.linalg.norm(beta_ridge)) #||beta||" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Automatic differentiation\n", "Python has tools for so-called **automatic differentiation**.\n", "Consider the following example" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "$$\n", "f(x) = \\sin\\left(2\\pi x + x^2\\right)\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "which has the following derivative" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "$$\n", "f'(x) = \\cos\\left(2\\pi x + x^2\\right)\\left(2\\pi + 2x\\right)\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Using **autograd** we have" ] }, { "cell_type": "code", "execution_count": 73, "metadata": { "collapsed": false }, "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", "metadata": {}, "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": 74, "metadata": { "collapsed": false }, "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", "metadata": {}, "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": 75, "metadata": { "collapsed": false }, "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", "metadata": {}, "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.\n", "\n", "\n", "\n", "## More complicated functions using the elements of their arguments directly" ] }, { "cell_type": "code", "execution_count": 76, "metadata": { "collapsed": false }, "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", "metadata": {}, "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.\n", "\n", "\n", "## Functions using mathematical functions from Numpy" ] }, { "cell_type": "code", "execution_count": 77, "metadata": { "collapsed": false }, "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", "metadata": {}, "source": [ "## More autograd" ] }, { "cell_type": "code", "execution_count": 78, "metadata": { "collapsed": false }, "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", "metadata": {}, "source": [ "## And with loops" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "1\n", "0\n", "7\n", " \n", "<\n", "<\n", "<\n", "!\n", "!\n", "C\n", "O\n", "D\n", "E\n", "_\n", "B\n", "L\n", "O\n", "C\n", "K\n", " \n", " \n", "p\n", "y\n", "c\n", "o\n", "d" ] }, { "cell_type": "code", "execution_count": 79, "metadata": { "collapsed": false }, "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", "metadata": {}, "source": [ "## Using recursion" ] }, { "cell_type": "code", "execution_count": 80, "metadata": { "collapsed": false }, "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", "metadata": {}, "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.\n", "\n", "\n", "## 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": 81, "metadata": { "collapsed": false }, "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", "metadata": {}, "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.\n", "\n", "\n", "## The syntax a.dot(b) when finding the dot product" ] }, { "cell_type": "code", "execution_count": 82, "metadata": { "collapsed": false }, "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", "metadata": {}, "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": 83, "metadata": { "collapsed": false }, "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", "metadata": {}, "source": [ "## Recommended to avoid\n", "The documentation recommends to avoid inplace operations such as" ] }, { "cell_type": "code", "execution_count": 84, "metadata": { "collapsed": false }, "outputs": [], "source": [ "a += b\n", "a -= b\n", "a*= b\n", "a /=b" ] }, { "cell_type": "markdown", "metadata": {}, "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", "metadata": {}, "source": [ "$$\n", "C(\\mathbf{\\beta}) = \\sum_{i=1}^n c_i(\\mathbf{x}_i,\n", "\\mathbf{\\beta}).\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "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", "metadata": {}, "source": [ "$$\n", "\\nabla_\\beta C(\\mathbf{\\beta}) = \\sum_i^n \\nabla_\\beta c_i(\\mathbf{x}_i,\n", "\\mathbf{\\beta}).\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "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$.\n", "\n", "\n", "## 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", "metadata": {}, "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", "metadata": {}, "source": [ "## The gradient step\n", "\n", "Thus a gradient descent step now looks like" ] }, { "cell_type": "markdown", "metadata": {}, "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", "metadata": {}, "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.\n", "\n", "\n", "## Simple example code" ] }, { "cell_type": "code", "execution_count": 85, "metadata": { "collapsed": false }, "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", "metadata": {}, "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.\n", "\n", "\n", "## 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.\n", "\n", "\n", "## 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.\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": 86, "metadata": { "collapsed": false }, "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", "metadata": {}, "source": [ "## Program for stochastic gradient" ] }, { "cell_type": "code", "execution_count": 87, "metadata": { "collapsed": false }, "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", "from sklearn.linear_model import SGDRegressor\n", "\n", "x = 2*np.random.rand(100,1)\n", "y = 4+3*x+np.random.randn(100,1)\n", "\n", "xb = np.c_[np.ones((100,1)), x]\n", "theta_linreg = np.linalg.inv(xb.T.dot(xb)).dot(xb.T).dot(y)\n", "print(\"Own inversion\")\n", "print(theta_linreg)\n", "sgdreg = SGDRegressor(n_iter = 50, penalty=None, eta0=0.1)\n", "sgdreg.fit(x,y.ravel())\n", "print(\"sgdreg from scikit\")\n", "print(sgdreg.intercept_, sgdreg.coef_)\n", "\n", "\n", "theta = np.random.randn(2,1)\n", "\n", "eta = 0.1\n", "Niterations = 1000\n", "m = 100\n", "\n", "for iter in range(Niterations):\n", " gradients = 2.0/m*xb.T.dot(xb.dot(theta)-y)\n", " theta -= eta*gradients\n", "print(\"theta frm own gd\")\n", "print(theta)\n", "\n", "xnew = np.array([[0],[2]])\n", "xbnew = np.c_[np.ones((2,1)), xnew]\n", "ypredict = xbnew.dot(theta)\n", "ypredict2 = xbnew.dot(theta_linreg)\n", "\n", "\n", "n_epochs = 50\n", "t0, t1 = 5, 50\n", "m = 100\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", " for i in range(m):\n", " random_index = np.random.randint(m)\n", " xi = xb[random_index:random_index+1]\n", " yi = y[random_index:random_index+1]\n", " gradients = 2 * xi.T.dot(xi.dot(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", "\n", "\n", "\n", "\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", "metadata": {}, "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 energy 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 energy 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.\n", "\n", "## Momentum based GD\n", "\n", "The stochastic gradient descent (SGD) is almost always used with a *momentum* or inertia term that serves as a memory of the direction we are moving in parameter space. This is typically \n", "implemented as follows" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "$$\n", "\\mathbf{v}_{t}=\\gamma \\mathbf{v}_{t-1}+\\eta_{t}\\nabla_\\theta E(\\boldsymbol{\\theta}_t) \\nonumber\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "\n", "
\n", "\n", "$$\n", "\\begin{equation} \n", "\\boldsymbol{\\theta}_{t+1}= \\boldsymbol{\\theta}_t -\\mathbf{v}_{t},\n", "\\label{_auto35} \\tag{54}\n", "\\end{equation}\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "where we have introduced a momentum parameter $\\gamma$, with $0\\le\\gamma\\le 1$, and for brevity we dropped the explicit notation to indicate the gradient is to be taken over a different mini-batch at each step. We call this algorithm gradient descent with momentum (GDM). From these equations, it is clear that $\\mathbf{v}_t$ is a running average of recently encountered gradients and $(1-\\gamma)^{-1}$ sets the characteristic time scale for the memory used in the averaging procedure. Consistent with this, when $\\gamma=0$, this just reduces down to ordinary SGD as discussed earlier. An equivalent way of writing the updates is" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "$$\n", "\\Delta \\boldsymbol{\\theta}_{t+1} = \\gamma \\Delta \\boldsymbol{\\theta}_t -\\ \\eta_{t}\\nabla_\\theta E(\\boldsymbol{\\theta}_t),\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "where we have defined $\\Delta \\boldsymbol{\\theta}_{t}= \\boldsymbol{\\theta}_t-\\boldsymbol{\\theta}_{t-1}$.\n", "\n", "\n", "## More on momentum based approaches\n", "\n", "Let us try to get more intuition from these equations. It is helpful to consider a simple physical analogy with a particle of mass $m$ 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}$, then its motion is described by" ] }, { "cell_type": "markdown", "metadata": {}, "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", "metadata": {}, "source": [ "We can discretize this equation in the usual way to get" ] }, { "cell_type": "markdown", "metadata": {}, "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", "metadata": {}, "source": [ "Rearranging this equation, we can rewrite this as" ] }, { "cell_type": "markdown", "metadata": {}, "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", "metadata": {}, "source": [ "## Momentum parameter\n", "Notice that this equation is identical to previous one if we identify the position of the particle, $\\mathbf{w}$, with the parameters $\\boldsymbol{\\theta}$. This allows\n", "us to identify the momentum parameter and learning rate with the mass of the particle and the viscous drag as:" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "$$\n", "\\gamma= {m \\over m +\\mu \\Delta t }, \\qquad \\eta = {(\\Delta t)^2 \\over m +\\mu \\Delta t}.\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Thus, as the name suggests, the momentum parameter is proportional to the mass of the particle and effectively provides inertia. Furthermore, in the large viscosity/small learning rate limit, our memory time scales as $(1-\\gamma)^{-1} \\approx m/(\\mu \\Delta t)$.\n", "\n", "Why is momentum useful? SGD momentum helps the gradient descent algorithm gain speed in directions with persistent but small gradients even in the presence of stochasticity, while suppressing oscillations in high-curvature directions. This becomes especially important in situations where the landscape is shallow and flat in some directions and narrow and steep in others. It has been argued that first-order methods (with appropriate initial conditions) can perform comparable to more expensive second order methods, especially in the context of complex deep learning models. \n", "\n", "These beneficial properties of momentum can sometimes become even more pronounced by using a slight modification of the classical momentum algorithm called Nesterov Accelerated Gradient (NAG). \n", "\n", "In the NAG algorithm, rather than calculating the gradient at the current parameters, $\\nabla_\\theta E(\\boldsymbol{\\theta}_t)$, one calculates the gradient at the expected value of the parameters given our current momentum, $\\nabla_\\theta E(\\boldsymbol{\\theta}_t +\\gamma \\mathbf{v}_{t-1})$. This yields the NAG update rule" ] }, { "cell_type": "markdown", "metadata": {}, "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", "metadata": {}, "source": [ "\n", "
\n", "\n", "$$\n", "\\begin{equation} \n", "\\boldsymbol{\\theta}_{t+1}= \\boldsymbol{\\theta}_t -\\mathbf{v}_{t}.\n", "\\label{_auto36} \\tag{55}\n", "\\end{equation}\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "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$.\n", "\n", "\n", "\n", "## Second moment of the gradient\n", "\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 this by tracking not only the gradient, but also the second moment of the gradient. These methods include AdaGrad, AdaDelta, RMS-Prop, and ADAM.\n", "\n", "\n", "## RMS prop\n", "\n", "In RMS prop, in addition to keeping a running average of the first moment of the gradient, we also keep track of the second moment denoted by $\\mathbf{s}_t=\\mathbb{E}[\\mathbf{g}_t^2]$. The update rule for RMS prop is given by" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "\n", "
\n", "\n", "$$\n", "\\begin{equation}\n", "\\mathbf{g}_t = \\nabla_\\theta E(\\boldsymbol{\\theta}) \n", "\\label{_auto37} \\tag{56}\n", "\\end{equation}\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "$$\n", "\\mathbf{s}_t =\\beta \\mathbf{s}_{t-1} +(1-\\beta)\\mathbf{g}_t^2 \\nonumber\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "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", "metadata": {}, "source": [ "where $\\beta$ controls the averaging time of the second moment and is typically taken to be about $\\beta=0.9$, $\\eta_t$ is a learning rate typically chosen to be $10^{-3}$, and $\\epsilon\\sim 10^{-8} $ is a small regularization constant to prevent divergences. Multiplication and division by vectors is understood as an element-wise operation. It is clear from this formula that the learning rate is reduced in directions where the norm of the gradient is consistently large. This greatly speeds up the convergence by allowing us to use a larger learning rate for flat directions.\n", "\n", "\n", "\n", "## ADAM optimizer\n", "\n", "A related algorithm is the ADAM optimizer. In ADAM, we keep a running average of both the first and second moment of the gradient and use this information to adaptively change the learning rate for different parameters. In addition to keeping a running average of the first and second moments of the gradient (i.e. $\\mathbf{m}_t=\\mathbb{E}[\\mathbf{g}_t]$ and $\\mathbf{s}_t=\\mathbb{E}[\\mathbf{g}^2_t]$, respectively), ADAM performs an additional bias correction to account for the fact that we are estimating the first two moments of the gradient using a running average (denoted by the hats in the update rule below). The update rule for ADAM is given by (where multiplication and division are once again understood to be element-wise operations below)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "\n", "
\n", "\n", "$$\n", "\\begin{equation}\n", "\\mathbf{g}_t = \\nabla_\\theta E(\\boldsymbol{\\theta}) \n", "\\label{_auto38} \\tag{57}\n", "\\end{equation}\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "$$\n", "\\mathbf{m}_t = \\beta_1 \\mathbf{m}_{t-1} + (1-\\beta_1) \\mathbf{g}_t \\nonumber\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "$$\n", "\\mathbf{s}_t =\\beta_2 \\mathbf{s}_{t-1} +(1-\\beta_2)\\mathbf{g}_t^2 \\nonumber\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "$$\n", "\\hat{\\mathbf{m}}_t={\\mathbf{m}_t \\over 1-\\beta_1^t} \\nonumber\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "$$\n", "\\hat{\\mathbf{s}}_t ={\\mathbf{s}_t \\over1-\\beta_2^t} \\nonumber\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "$$\n", "\\boldsymbol{\\theta}_{t+1}=\\boldsymbol{\\theta}_t - \\eta_t { \\hat{\\mathbf{m}}_t \\over \\sqrt{\\hat{\\mathbf{s}}_t} +\\epsilon}, \\nonumber\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "\n", "
\n", "\n", "$$\n", "\\begin{equation} \n", "\\label{_auto39} \\tag{58}\n", "\\end{equation}\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "where $\\beta_1$ and $\\beta_2$ set the memory lifetime of the first and second moment and are typically taken to be $0.9$ and $0.99$ respectively, and $\\eta$ and $\\epsilon$ are identical to RMSprop.\n", "\n", "Like in RMSprop, the effective step size of a parameter depends on the magnitude of its gradient squared. To understand this better, let us rewrite this expression in terms of the variance $\\boldsymbol{\\sigma}_t^2 = \\hat{\\mathbf{s}}_t - (\\hat{\\mathbf{m}}_t)^2$. Consider a single parameter $\\theta_t$. The update rule for this parameter is given by" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "$$\n", "\\Delta \\theta_{t+1}= -\\eta_t { \\hat{m}_t \\over \\sqrt{\\sigma_t^2 + m_t^2 }+\\epsilon}.\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "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 energy matrix 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", "# Logistic Regression\n", "\n", "In linear regression our main interest was centered on learning the\n", "coefficients of a functional fit (say a polynomial) in order to be\n", "able to predict the response of a continuous variable on some unseen\n", "data. The fit to the continuous variable $y_i$ is based on some\n", "independent variables $\\hat{x}_i$. Linear regression resulted in\n", "analytical expressions (in terms of matrices to invert) for several\n", "quantities, ranging from the variance and thereby the confidence\n", "intervals of the parameters $\\hat{\\beta}$ to the mean squared\n", "error. If we can invert the product of the design matrices, linear\n", "regression gives then a simple recipe for fitting our data.\n", "\n", "\n", "Classification problems, however, are concerned with outcomes taking\n", "the form of discrete variables (i.e. categories). We may for example,\n", "on the basis of DNA sequencing for a number of patients, like to find\n", "out which mutations are important for a certain disease; or based on\n", "scans of various patients' brains, figure out if there is a tumor or\n", "not; or given a specific physical system, we'd like to identify its\n", "state, say whether it is an ordered or disordered system (typical\n", "situation in solid state physics); or classify the status of a\n", "patient, whether she/he has a stroke or not and many other similar\n", "situations.\n", "\n", "The most common situation we encounter when we apply logistic\n", "regression is that of two possible outcomes, normally denoted as a\n", "binary outcome, true or false, positive or negative, success or\n", "failure etc.\n", "\n", "\n", "## Optimization and Deep learning\n", "\n", "Logistic regression will also serve as our stepping stone towards neural\n", "network algorithms and supervised deep learning. For logistic\n", "learning, the minimization of the cost function leads to a non-linear\n", "equation in the parameters $\\hat{\\beta}$. The optmization of the problem calls therefore for minimization algorithms. This forms the bottle neck of all machine learning algorithms, namely how to find reliable minima of a multi-variable function. This leads us to the family of gradient descent methods. The latter are the working horses of basically all modern machine learning algorithms. \n", "\n", "We note also that many of the topics discussed here \n", "regression are also commonly used in modern supervised Deep Learning\n", "models, as we will see later.\n", "\n", "\n", "\n", "## Basics\n", "\n", "We consider the case where the dependent variables, also called the\n", "responses or the outcomes, $y_i$ are discrete and only take values\n", "from $k=0,\\dots,K-1$ (i.e. $K$ classes).\n", "\n", "The goal is to predict the\n", "output classes from the design matrix $\\hat{X}\\in\\mathbb{R}^{n\\times p}$\n", "made of $n$ samples, each of which carries $p$ features or predictors. The\n", "primary goal is to identify the classes to which new unseen samples\n", "belong.\n", "\n", "Let us specialize to the case of two classes only, with outputs $y_i=0$ and $y_i=1$. Our outcomes could represent the status of a credit card user who could default or not on her/his credit card debt. That is" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "$$\n", "y_i = \\begin{bmatrix} 0 & \\mathrm{no}\\\\ 1 & \\mathrm{yes} \\end{bmatrix}.\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Linear classifier\n", "\n", "Before moving to the logistic model, let us try to use our linear regression model to classify these two outcomes. We could for example fit a linear model to the default case if $y_i > 0.5$ and the no default case $y_i \\leq 0.5$. \n", "\n", "We would then have our \n", "weighted linear combination, namely" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "\n", "
\n", "\n", "$$\n", "\\begin{equation}\n", "\\hat{y} = \\hat{X}^T\\hat{\\beta} + \\hat{\\epsilon},\n", "\\label{_auto40} \\tag{59}\n", "\\end{equation}\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "where $\\hat{y}$ is a vector representing the possible outcomes, $\\hat{X}$ is our\n", "$n\\times p$ design matrix and $\\hat{\\beta}$ represents our estimators/predictors.\n", "\n", "\n", "## Some selected properties\n", "\n", "The main problem with our function is that it \n", "takes values on the entire real axis. In the case of\n", "logistic regression, however, the labels $y_i$ are discrete\n", "variables. \n", "\n", "One simple way to get a discrete output is to have sign\n", "functions that map the output of a linear regressor to values $\\{0,1\\}$,\n", "$f(s_i)=sign(s_i)=1$ if $s_i\\ge 0$ and 0 if otherwise. \n", "We will encounter this model in our first demonstration of neural networks. Historically it is called the \"perceptron\" model in the machine learning\n", "literature. This model is extremely simple. However, in many cases it is more\n", "favorable to use a ``soft\" classifier that outputs\n", "the probability of a given category. This leads us to the logistic function.\n", "\n", "The code for plotting the perceptron can be seen here. This si nothing but the standard [Heaviside step function](https://en.wikipedia.org/wiki/Heaviside_step_function)." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## The logistic function\n", "\n", "The perceptron is an example of a ``hard classification\" model. We\n", "will encounter this model when we discuss neural networks as\n", "well. Each datapoint is deterministically assigned to a category (i.e\n", "$y_i=0$ or $y_i=1$). In many cases, it is favorable to have a \"soft\"\n", "classifier that outputs the probability of a given category rather\n", "than a single value. For example, given $x_i$, the classifier\n", "outputs the probability of being in a category $k$. Logistic regression\n", "is the most common example of a so-called soft classifier. In logistic\n", "regression, the probability that a data point $x_i$\n", "belongs to a category $y_i=\\{0,1\\}$ is given by the so-called logit function (or Sigmoid) which is meant to represent the likelihood for a given event," ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "$$\n", "p(t) = \\frac{1}{1+\\mathrm \\exp{-t}}=\\frac{\\exp{t}}{1+\\mathrm \\exp{t}}.\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Note that $1-p(t)= p(-t)$.\n", "The following code plots the logistic function." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Two parameters\n", "\n", "We assume now that we have two classes with $y_i$ either $0$ or $1$. Furthermore we assume also that we have only two parameters $\\beta$ in our fitting of the Sigmoid function, that is we define probabilities" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "$$\n", "\\begin{align*}\n", "p(y_i=1|x_i,\\hat{\\beta}) &= \\frac{\\exp{(\\beta_0+\\beta_1x_i)}}{1+\\exp{(\\beta_0+\\beta_1x_i)}},\\nonumber\\\\\n", "p(y_i=0|x_i,\\hat{\\beta}) &= 1 - p(y_i=1|x_i,\\hat{\\beta}),\n", "\\end{align*}\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "where $\\hat{\\beta}$ are the weights we wish to extract from data, in our case $\\beta_0$ and $\\beta_1$. \n", "\n", "Note that we used" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "$$\n", "p(y_i=0\\vert x_i, \\hat{\\beta}) = 1-p(y_i=1\\vert x_i, \\hat{\\beta}).\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Maximum likelihood\n", "\n", "In order to define the total likelihood for all possible outcomes from a \n", "dataset $\\mathcal{D}=\\{(y_i,x_i)\\}$, with the binary labels\n", "$y_i\\in\\{0,1\\}$ and where the data points are drawn independently, we use the so-called [Maximum Likelihood Estimation](https://en.wikipedia.org/wiki/Maximum_likelihood_estimation) (MLE) principle. \n", "We aim thus at maximizing \n", "the probability of seeing the observed data. We can then approximate the \n", "likelihood in terms of the product of the individual probabilities of a specific outcome $y_i$, that is" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "$$\n", "\\begin{align*}\n", "P(\\mathcal{D}|\\hat{\\beta})& = \\prod_{i=1}^n \\left[p(y_i=1|x_i,\\hat{\\beta})\\right]^{y_i}\\left[1-p(y_i=1|x_i,\\hat{\\beta}))\\right]^{1-y_i}\\nonumber \\\\\n", "\\end{align*}\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "from which we obtain the log-likelihood and our **cost/loss** function" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "$$\n", "\\mathcal{C}(\\hat{\\beta}) = \\sum_{i=1}^n \\left( y_i\\log{p(y_i=1|x_i,\\hat{\\beta})} + (1-y_i)\\log\\left[1-p(y_i=1|x_i,\\hat{\\beta}))\\right]\\right).\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## The cost function rewritten\n", "\n", "Reordering the logarithms, we can rewrite the **cost/loss** function as" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "$$\n", "\\mathcal{C}(\\hat{\\beta}) = \\sum_{i=1}^n \\left(y_i(\\beta_0+\\beta_1x_i) -\\log{(1+\\exp{(\\beta_0+\\beta_1x_i)})}\\right).\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "The maximum likelihood estimator is defined as the set of parameters that maximize the log-likelihood where we maximize with respect to $\\beta$.\n", "Since the cost (error) function is just the negative log-likelihood, for logistic regression we have that" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "$$\n", "\\mathcal{C}(\\hat{\\beta})=-\\sum_{i=1}^n \\left(y_i(\\beta_0+\\beta_1x_i) -\\log{(1+\\exp{(\\beta_0+\\beta_1x_i)})}\\right).\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "This equation is known in statistics as the **cross entropy**. Finally, we note that just as in linear regression, \n", "in practice we often supplement the cross-entropy with additional regularization terms, usually $L_1$ and $L_2$ regularization as we did for Ridge and Lasso regression.\n", "\n", "\n", "## Minimizing the cross entropy\n", "\n", "The cross entropy is a convex function of the weights $\\hat{\\beta}$ and,\n", "therefore, any local minimizer is a global minimizer. \n", "\n", "\n", "Minimizing this\n", "cost function with respect to the two parameters $\\beta_0$ and $\\beta_1$ we obtain" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "$$\n", "\\frac{\\partial \\mathcal{C}(\\hat{\\beta})}{\\partial \\beta_0} = -\\sum_{i=1}^n \\left(y_i -\\frac{\\exp{(\\beta_0+\\beta_1x_i)}}{1+\\exp{(\\beta_0+\\beta_1x_i)}}\\right),\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "and" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "$$\n", "\\frac{\\partial \\mathcal{C}(\\hat{\\beta})}{\\partial \\beta_1} = -\\sum_{i=1}^n \\left(y_ix_i -x_i\\frac{\\exp{(\\beta_0+\\beta_1x_i)}}{1+\\exp{(\\beta_0+\\beta_1x_i)}}\\right).\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## A more compact expression\n", "\n", "Let us now define a vector $\\hat{y}$ with $n$ elements $y_i$, an\n", "$n\\times p$ matrix $\\hat{X}$ which contains the $x_i$ values and a\n", "vector $\\hat{p}$ of fitted probabilities $p(y_i\\vert x_i,\\hat{\\beta})$. We can rewrite in a more compact form the first\n", "derivative of cost function as" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "$$\n", "\\frac{\\partial \\mathcal{C}(\\hat{\\beta})}{\\partial \\hat{\\beta}} = -\\hat{X}^T\\left(\\hat{y}-\\hat{p}\\right).\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "If we in addition define a diagonal matrix $\\hat{W}$ with elements \n", "$p(y_i\\vert x_i,\\hat{\\beta})(1-p(y_i\\vert x_i,\\hat{\\beta})$, we can obtain a compact expression of the second derivative as" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "$$\n", "\\frac{\\partial^2 \\mathcal{C}(\\hat{\\beta})}{\\partial \\hat{\\beta}\\partial \\hat{\\beta}^T} = \\hat{X}^T\\hat{W}\\hat{X}.\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Extending to more predictors\n", "\n", "Within a binary classification problem, we can easily expand our model to include multiple predictors. Our ratio between likelihoods is then with $p$ predictors" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "$$\n", "\\log{ \\frac{p(\\hat{\\beta}\\hat{x})}{1-p(\\hat{\\beta}\\hat{x})}} = \\beta_0+\\beta_1x_1+\\beta_2x_2+\\dots+\\beta_px_p.\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Here we defined $\\hat{x}=[1,x_1,x_2,\\dots,x_p]$ and $\\hat{\\beta}=[\\beta_0, \\beta_1, \\dots, \\beta_p]$ leading to" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "$$\n", "p(\\hat{\\beta}\\hat{x})=\\frac{ \\exp{(\\beta_0+\\beta_1x_1+\\beta_2x_2+\\dots+\\beta_px_p)}}{1+\\exp{(\\beta_0+\\beta_1x_1+\\beta_2x_2+\\dots+\\beta_px_p)}}.\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Including more classes\n", "\n", "Till now we have mainly focused on two classes, the so-called binary system. Suppose we wish to extend to $K$ classes.\n", "Let us for the sake of simplicity assume we have only two predictors. We have then following model" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "3\n", "8\n", "9\n", " \n", "<\n", "<\n", "<\n", "!\n", "!\n", "M\n", "A\n", "T\n", "H\n", "_\n", "B\n", "L\n", "O\n", "C\n", "K" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "$$\n", "\\log{\\frac{p(C=2\\vert x)}{p(K\\vert x)}} = \\beta_{20}+\\beta_{21}x_1,\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "and so on till the class $C=K-1$ class" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "$$\n", "\\log{\\frac{p(C=K-1\\vert x)}{p(K\\vert x)}} = \\beta_{(K-1)0}+\\beta_{(K-1)1}x_1,\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "and the model is specified in term of $K-1$ so-called log-odds or **logit** transformations.\n", "\n", "\n", "\n", "## The Softmax function\n", "\n", "In our discussion of neural networks we will encounter the above again in terms of the so-called **Softmax** function.\n", "\n", "The softmax function is used in various multiclass classification\n", "methods, such as multinomial logistic regression (also known as\n", "softmax regression), multiclass linear discriminant\n", "analysis, naive Bayes classifiers, and artificial neural networks.\n", "Specifically, in multinomial logistic regression and linear\n", "discriminant analysis, the input to the function is the result of $K$\n", "distinct linear functions, and the predicted probability for the $k$-th\n", "class given a sample vector $\\hat{x}$ and a weighting vector $\\hat{\\beta}$ is (with two predictors):" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "$$\n", "p(C=k\\vert \\mathbf {x} )=\\frac{\\exp{(\\beta_{k0}+\\beta_{k1}x_1)}}{1+\\sum_{l=1}^{K-1}\\exp{(\\beta_{l0}+\\beta_{l1}x_1)}}.\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "It is easy to extend to more predictors. The final class is" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "$$\n", "p(C=K\\vert \\mathbf {x} )=\\frac{1}{1+\\sum_{l=1}^{K-1}\\exp{(\\beta_{l0}+\\beta_{l1}x_1)}},\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "and they sum to one. Our earlier discussions were all specialized to the case with two classes only. It is easy to see from the above that what we derived earlier is compatible with these equations. \n", "\n", "To find the optimal parameters we would typically use a gradient descent method.\n", "Newton's method and gradient descent methods are discussed in the material on [optimization methods](https://compphysics.github.io/MachineLearning/doc/pub/Splines/html/Splines-bs.html). \n", "\n", "\n", "\n", "\n", "## A **scikit-learn** example" ] }, { "cell_type": "code", "execution_count": 88, "metadata": { "collapsed": false }, "outputs": [], "source": [ "import numpy as np\n", "import matplotlib.pyplot as plt\n", "from sklearn import datasets\n", "iris = datasets.load_iris()\n", "list(iris.keys())\n", "['data', 'target_names', 'feature_names', 'target', 'DESCR']\n", "X = iris[\"data\"][:, 3:] # petal width\n", "y = (iris[\"target\"] == 2).astype(np.int) # 1 if Iris-Virginica, else 0\n", "\n", "from sklearn.linear_model import LogisticRegression\n", "log_reg = LogisticRegression()\n", "log_reg.fit(X, y)\n", "\n", "X_new = np.linspace(0, 3, 1000).reshape(-1, 1)\n", "y_proba = log_reg.predict_proba(X_new)\n", "plt.plot(X_new, y_proba[:, 1], \"g-\", label=\"Iris-Virginica\")\n", "plt.plot(X_new, y_proba[:, 0], \"b--\", label=\"Not Iris-Virginica\")\n", "plt.show()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## A simple classification problem" ] }, { "cell_type": "code", "execution_count": 89, "metadata": { "collapsed": false }, "outputs": [], "source": [ "import numpy as np\n", "from sklearn import datasets, linear_model\n", "import matplotlib.pyplot as plt\n", "\n", "\n", "def generate_data():\n", " np.random.seed(0)\n", " X, y = datasets.make_moons(200, noise=0.20)\n", " return X, y\n", "\n", "\n", "def visualize(X, y, clf):\n", " # plt.scatter(X[:, 0], X[:, 1], s=40, c=y, cmap=plt.cm.Spectral)\n", " # plt.show()\n", " plot_decision_boundary(lambda x: clf.predict(x), X, y)\n", " plt.title(\"Logistic Regression\")\n", "\n", "\n", "def plot_decision_boundary(pred_func, X, y):\n", " # Set min and max values and give it some padding\n", " x_min, x_max = X[:, 0].min() - .5, X[:, 0].max() + .5\n", " y_min, y_max = X[:, 1].min() - .5, X[:, 1].max() + .5\n", " h = 0.01\n", " # Generate a grid of points with distance h between them\n", " xx, yy = np.meshgrid(np.arange(x_min, x_max, h), np.arange(y_min, y_max, h))\n", " # Predict the function value for the whole gid\n", " Z = pred_func(np.c_[xx.ravel(), yy.ravel()])\n", " Z = Z.reshape(xx.shape)\n", " # Plot the contour and training examples\n", " plt.contourf(xx, yy, Z, cmap=plt.cm.Spectral)\n", " plt.scatter(X[:, 0], X[:, 1], c=y, cmap=plt.cm.Spectral)\n", " plt.show()\n", "\n", "\n", "def classify(X, y):\n", " clf = linear_model.LogisticRegressionCV()\n", " clf.fit(X, y)\n", " return clf\n", "\n", "\n", "def main():\n", " X, y = generate_data()\n", " # visualize(X, y)\n", " clf = classify(X, y)\n", " visualize(X, y, clf)\n", "\n", "\n", "if __name__ == \"__main__\":\n", " main()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## The two-dimensional Ising model, Predicting phase transition of the two-dimensional Ising model\n", "\n", "The Hamiltonian of the two-dimensional Ising model without an external field for a constant coupling constant $J$ is given by" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "\n", "
\n", "\n", "$$\n", "\\begin{equation}\n", " H = -J \\sum_{\\langle ij\\rangle} S_i S_j,\n", "\\label{_auto41} \\tag{60}\n", "\\end{equation}\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "where $S_i \\in \\{-1, 1\\}$ and $\\langle ij \\rangle$ signifies that we only iterate over the nearest neighbors in the lattice. We will be looking at a system of $L = 40$ spins in each dimension, i.e., $L^2 = 1600$ spins in total. Opposed to the one-dimensional Ising model we will get a phase transition from an **ordered** phase to a **disordered** phase at the critical temperature" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "\n", "
\n", "\n", "$$\n", "\\begin{equation}\n", " \\frac{T_c}{J} = \\frac{2}{\\log\\left(1 + \\sqrt{2}\\right)} \\approx 2.26,\n", "\\label{_auto42} \\tag{61}\n", "\\end{equation}\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "as shown by Lars Onsager.\n", "\n", "\n", "Here we use **logistic regression** to predict when a phase transition\n", "occurs. The data we will look at is a set of spin configurations,\n", "i.e., individual lattices with spins, labeled **ordered** `1` or\n", "**disordered** `0`. Our job is to build a model which will take in a\n", "spin configuration and predict whether or not the spin configuration\n", "constitutes an ordered or a disordered phase. To achieve this we will\n", "represent the lattices as flattened arrays with $1600$ elements\n", "instead of a matrix of $40 \\times 40$ elements. As an extra test of\n", "the performance of the algorithms we will divide the dataset into\n", "three pieces. We will do a conventional train-test-split on a\n", "combination of totally ordered and totally disordered phases. The\n", "remaining \"critical-like\" states will be used as test data which we\n", "hope the model will be able to make good extrapolated predictions on." ] }, { "cell_type": "code", "execution_count": 90, "metadata": { "collapsed": false }, "outputs": [], "source": [ "import pickle\n", "import os\n", "import glob\n", "import numpy as np\n", "import pandas as pd\n", "import matplotlib.pyplot as plt\n", "import seaborn as sns\n", "import sklearn.model_selection as skms\n", "import sklearn.linear_model as skl\n", "import sklearn.metrics as skm\n", "import tqdm\n", "import copy\n", "import time\n", "from IPython.display import display\n", "\n", "%matplotlib inline\n", "\n", "sns.set(color_codes=True)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Reading in the data\n", "\n", "Using the data from [Mehta et al.](https://physics.bu.edu/~pankajm/ML-Review-Datasets/isingMC/) (specifically the two datasets named `Ising2DFM_reSample_L40_T=All.pkl` and `Ising2DFM_reSample_L40_T=All_labels.pkl`) we have to unpack the data into numpy arrays." ] }, { "cell_type": "code", "execution_count": 91, "metadata": { "collapsed": false }, "outputs": [], "source": [ "filenames = glob.glob(os.path.join(\"..\", \"dat\", \"*\"))\n", "label_filename = list(filter(lambda x: \"label\" in x, filenames))[0]\n", "dat_filename = list(filter(lambda x: \"label\" not in x, filenames))[0]\n", "\n", "# Read in the labels\n", "with open(label_filename, \"rb\") as f:\n", " labels = pickle.load(f)\n", "\n", "# Read in the corresponding configurations\n", "with open(dat_filename, \"rb\") as f:\n", " data = np.unpackbits(pickle.load(f)).reshape(-1, 1600).astype(\"int\")\n", "\n", "# Set spin-down to -1\n", "data[data == 0] = -1" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "This dataset consists of $10000$ samples, i.e., $10000$ spin\n", "configurations with $40 \\times 40$ spins each, for $16$ temperatures\n", "between $0.25$ to $4.0$. Next we create a train/test-split and keep\n", "the data in the critical phase as a separate dataset for\n", "extrapolation-testing." ] }, { "cell_type": "code", "execution_count": 92, "metadata": { "collapsed": false }, "outputs": [], "source": [ "# Set up slices of the dataset\n", "ordered = slice(0, 70000)\n", "critical = slice(70000, 100000)\n", "disordered = slice(100000, 160000)\n", "\n", "X_train, X_test, y_train, y_test = skms.train_test_split(\n", " np.concatenate((data[ordered], data[disordered])),\n", " np.concatenate((labels[ordered], labels[disordered])),\n", " test_size=0.95\n", ")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Using a small training set yields a better accuracy. This will be discussed in the end.\n", "\n", "\n", "## Logistic regression\n", "\n", "Logistic regression is a linear model for classification. Recalling\n", "the cost function for ordinary least squares with both L2 (ridge) and\n", "L1 (LASSO) penalties we will see that the logistic cost function is\n", "very similar. In OLS we wish to predict a continuous variable\n", "$\\hat{y}$ using" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "\n", "
\n", "\n", "$$\n", "\\begin{equation}\n", " \\hat{y} = X\\omega,\n", "\\label{_auto43} \\tag{62}\n", "\\end{equation}\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "where $X \\in \\mathbb{R}^{n \\times p}$ is the input data and $\\omega^{p\n", "\\times d}$ are the weights of the regression. In a classification\n", "setting (binary classification in our situation) we are interested in\n", "a positive or negative answer. We can thus define either answer to be\n", "above or below some threshold. But, in order to limit the size of the\n", "answer and also to get a probability interpretation on how sure we are\n", "for either answer we can compute the sigmoid function of OLS. That is," ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "\n", "
\n", "\n", "$$\n", "\\begin{equation}\n", " f(X\\omega) = \\frac{1}{1 + \\exp(-X\\omega)}.\n", "\\label{_auto44} \\tag{63}\n", "\\end{equation}\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "We are thus interested in minizming the following cost function" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "\n", "
\n", "\n", "$$\n", "\\begin{equation}\n", " C(X, \\omega) = \\sum_{i = 1}^n \\left\\{\n", " - y_i\\log\\left( f(x_i^T\\omega) \\right)\n", " - (1 - y_i)\\log\\left[1 - f(x_i^T\\omega)\\right]\n", " \\right\\},\n", "\\label{_auto45} \\tag{64}\n", "\\end{equation}\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "where we will restrict ourselves to a value for $f(z)$ as the sigmoid\n", "described above. We can also tack on a L2 (Ridge) or L1 (LASSO)\n", "penalization to this cost function in the same manner we did for\n", "linear regression.\n", "\n", "\n", "## Exploring the logistic regression\n", "\n", "The penalization factor $\\lambda$ is inverted in the case of the\n", "logistic regression model we use. We will explore several values of\n", "$\\lambda$ using both L1 and L2 penalization. We do this using a grid\n", "search over different parameters and run a 3-fold cross validation for\n", "each configuration. In other words, we fit a model 3 times for each\n", "configuration of the hyper parameters." ] }, { "cell_type": "code", "execution_count": 93, "metadata": { "collapsed": false }, "outputs": [], "source": [ "lambdas = np.logspace(-7, -1, 7)\n", "\n", "param_grid = {\n", " \"C\": list(1.0/lambdas),\n", " \"penalty\": [\"l1\", \"l2\"]\n", "}\n", "clf = skms.GridSearchCV(\n", " skl.LogisticRegression(),\n", " param_grid=param_grid,\n", " n_jobs=-1,\n", " return_train_score=True\n", ")\n", "t0 = time.time()\n", "clf.fit(X_train, y_train)\n", "t1 = time.time()\n", "\n", "print (\n", " \"Time spent fitting GridSearchCV(LogisticRegression): {0:.3f} sec\".format(\n", " t1 - t0\n", " )\n", ")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "We can see that logistic regression is quite slow and using the grid\n", "search and cross validation results in quite a heavy\n", "computation. Below we show the results of the different\n", "configurations." ] }, { "cell_type": "code", "execution_count": 94, "metadata": { "collapsed": false }, "outputs": [], "source": [ "logreg_df = pd.DataFrame(clf.cv_results_)\n", "\n", "display(logreg_df)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Accuracy of a classification model\n", "\n", "To determine how well a classification model is performing we count\n", "the number of correctly labeled classes and divide by the number of\n", "classes in total. The accuracy is thus given by" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "\n", "
\n", "\n", "$$\n", "\\begin{equation}\n", " a(y, \\hat{y}) = \\frac{1}{n}\\sum_{i = 1}^{n} I(y_i = \\hat{y}_i),\n", "\\label{_auto46} \\tag{65}\n", "\\end{equation}\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "where $I(y_i = \\hat{y}_i)$ is the indicator function given by" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "\n", "
\n", "\n", "$$\n", "\\begin{equation}\n", " I(x = y) = \\begin{array}{cc}\n", " 1 & x = y, \\\\\n", " 0 & x \\neq y.\n", " \\end{array}\n", "\\label{_auto47} \\tag{66}\n", "\\end{equation}\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "This is the accuracy provided by Scikit-learn when using **sklearn.metrics.accuracyscore**.\n", "\n", "Below we compute the accuracy of the best fit model on the training data (which should give a good accuracy), the test data (which has not been shown to the model) and the critical data (completely new data that needs to be extrapolated)." ] }, { "cell_type": "code", "execution_count": 95, "metadata": { "collapsed": false }, "outputs": [], "source": [ "train_accuracy = skm.accuracy_score(y_train, clf.predict(X_train))\n", "test_accuracy = skm.accuracy_score(y_test, clf.predict(X_test))\n", "critical_accuracy = skm.accuracy_score(labels[critical], clf.predict(data[critical]))\n", "\n", "print (\"Accuracy on train data: {0}\".format(train_accuracy))\n", "print (\"Accuracy on test data: {0}\".format(test_accuracy))\n", "print (\"Accuracy on critical data: {0}\".format(critical_accuracy))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "We can see that we get quite good accuracy on the training data, but gradually worsening accuracy on the test and critical data.\n", "\n", "\n", "## Analyzing the results\n", "\n", "Below we show a different metric for determining the quality of our\n", "model, namely the **reciever operating characteristic** (ROC). The ROC\n", "curve tells us how well the model correctly classifies the different\n", "labels. We plot the **true positive rate** (the rate of predicted\n", "positive classes that are positive) versus the **false positive rate**\n", "(the rate of predicted positive classes that are negative). The ROC\n", "curve is built by computing the true positive rate and the false\n", "positive rate for varying **thresholds**, i.e, which probability we\n", "should acredit a certain class.\n", "\n", "By computing the **area under the curve** (AUC) of the ROC curve we get an estimate of how well our model is performing. Pure guessing will get an AUC of $0.5$. A perfect score will get an AUC of $1.0$." ] }, { "cell_type": "code", "execution_count": 96, "metadata": { "collapsed": false }, "outputs": [], "source": [ "fig = plt.figure(figsize=(20, 14))\n", "\n", "for (_X, _y), label in zip(\n", " [\n", " (X_train, y_train),\n", " (X_test, y_test),\n", " (data[critical], labels[critical])\n", " ],\n", " [\"Train\", \"Test\", \"Critical\"]\n", "):\n", " proba = clf.predict_proba(_X)\n", " fpr, tpr, _ = skm.roc_curve(_y, proba[:, 1])\n", " roc_auc = skm.auc(fpr, tpr)\n", "\n", " print (\"LogisticRegression AUC ({0}): {1}\".format(label, roc_auc))\n", "\n", " plt.plot(fpr, tpr, label=\"{0} (AUC = {1})\".format(label, roc_auc), linewidth=4.0)\n", "\n", "plt.plot([0, 1], [0, 1], \"--\", label=\"Guessing (AUC = 0.5)\", linewidth=4.0)\n", "\n", "plt.title(r\"The ROC curve for LogisticRegression\", fontsize=18)\n", "plt.xlabel(r\"False positive rate\", fontsize=18)\n", "plt.ylabel(r\"True positive rate\", fontsize=18)\n", "plt.axis([-0.01, 1.01, -0.01, 1.01])\n", "plt.xticks(fontsize=18)\n", "plt.yticks(fontsize=18)\n", "plt.legend(loc=\"best\", fontsize=18)\n", "plt.show()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "We can see that this plot of the ROC looks very strange. This tells us\n", "that logistic regression is quite inept at predicting the Ising model\n", "transition and is therefore highly non-linear. The ROC curve for the\n", "training data looks quite good, but as the testing data is so far off\n", "we see that we are dealing with an overfit model.\n", "\n", "A previous run with $50\\%$ of the data used for training yielded a\n", "worse performance than using a smaller training set. This again gives\n", "confidence to the fact that logistic regression is not able to\n", "correctly fit the Ising model as it is not a linear model.\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "# Neural networks\n", "\n", "Artificial neural networks are computational systems that can learn to\n", "perform tasks by considering examples, generally without being\n", "programmed with any task-specific rules. It is supposed to mimic a\n", "biological system, wherein neurons interact by sending signals in the\n", "form of mathematical functions between layers. All layers can contain\n", "an arbitrary number of neurons, and each connection is represented by\n", "a weight variable.\n", "\n", "\n", "\n", "## Artificial neurons\n", "\n", "The field of artificial neural networks has a long history of\n", "development, and is closely connected with the advancement of computer\n", "science and computers in general. A model of artificial neurons was\n", "first developed by McCulloch and Pitts in 1943 to study signal\n", "processing in the brain and has later been refined by others. The\n", "general idea is to mimic neural networks in the human brain, which is\n", "composed of billions of neurons that communicate with each other by\n", "sending electrical signals. Each neuron accumulates its incoming\n", "signals, which must exceed an activation threshold to yield an\n", "output. If the threshold is not overcome, the neuron remains inactive,\n", "i.e. has zero output.\n", "\n", "This behaviour has inspired a simple mathematical model for an artificial neuron." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "\n", "
\n", "\n", "$$\n", "\\begin{equation}\n", " y = f\\left(\\sum_{i=1}^n w_ix_i\\right) = f(u)\n", "\\label{artificialNeuron} \\tag{67}\n", "\\end{equation}\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Here, the output $y$ of the neuron is the value of its activation function, which have as input\n", "a weighted sum of signals $x_i, \\dots ,x_n$ received by $n$ other neurons.\n", "\n", "Conceptually, it is helpful to divide neural networks into four\n", "categories:\n", "1. general purpose neural networks for supervised learning,\n", "\n", "2. neural networks designed specifically for image processing, the most prominent example of this class being Convolutional Neural Networks (CNNs),\n", "\n", "3. neural networks for sequential data such as Recurrent Neural Networks (RNNs), and\n", "\n", "4. neural networks for unsupervised learning such as Deep Boltzmann Machines.\n", "\n", "In natural science, DNNs and CNNs have already found numerous\n", "applications. In statistical physics, they have been applied to detect\n", "phase transitions in 2D Ising and Potts models, lattice gauge\n", "theories, and different phases of polymers, or solving the\n", "Navier-Stokes equation in weather forecasting. Deep learning has also\n", "found interesting applications in quantum physics. Various quantum\n", "phase transitions can be detected and studied using DNNs and CNNs,\n", "topological phases, and even non-equilibrium many-body\n", "localization. Representing quantum states as DNNs quantum state\n", "tomography are among some of the impressive achievements to reveal the\n", "potential of DNNs to facilitate the study of quantum systems.\n", "\n", "In quantum information theory, it has been shown that one can perform\n", "gate decompositions with the help of neural. \n", "\n", "The applications are not limited to the natural sciences. There is a\n", "plethora of applications in essentially all disciplines, from the\n", "humanities to life science and medicine.\n", "\n", "\n", "## Neural network types\n", "\n", "An artificial neural network (ANN), is a computational model that\n", "consists of layers of connected neurons, or nodes or units. We will\n", "refer to these interchangeably as units or nodes, and sometimes as\n", "neurons.\n", "\n", "It is supposed to mimic a biological nervous system by letting each\n", "neuron interact with other neurons by sending signals in the form of\n", "mathematical functions between layers. A wide variety of different\n", "ANNs have been developed, but most of them consist of an input layer,\n", "an output layer and eventual layers in-between, called *hidden\n", "layers*. All layers can contain an arbitrary number of nodes, and each\n", "connection between two nodes is associated with a weight variable.\n", "\n", "Neural networks (also called neural nets) are neural-inspired\n", "nonlinear models for supervised learning. As we will see, neural nets\n", "can be viewed as natural, more powerful extensions of supervised\n", "learning methods such as linear and logistic regression and soft-max\n", "methods we discussed earlier.\n", "\n", "\n", "\n", "## Feed-forward neural networks\n", "\n", "The feed-forward neural network (FFNN) was the first and simplest type\n", "of ANNs that were devised. In this network, the information moves in\n", "only one direction: forward through the layers.\n", "\n", "Nodes are represented by circles, while the arrows display the\n", "connections between the nodes, including the direction of information\n", "flow. Additionally, each arrow corresponds to a weight variable\n", "(figure to come). We observe that each node in a layer is connected\n", "to *all* nodes in the subsequent layer, making this a so-called\n", "*fully-connected* FFNN.\n", "\n", "\n", "\n", "\n", "## Convolutional Neural Network\n", "\n", "A different variant of FFNNs are *convolutional neural networks*\n", "(CNNs), which have a connectivity pattern inspired by the animal\n", "visual cortex. Individual neurons in the visual cortex only respond to\n", "stimuli from small sub-regions of the visual field, called a receptive\n", "field. This makes the neurons well-suited to exploit the strong\n", "spatially local correlation present in natural images. The response of\n", "each neuron can be approximated mathematically as a convolution\n", "operation. (figure to come)\n", "\n", "Convolutional neural networks emulate the behaviour of neurons in the\n", "visual cortex by enforcing a *local* connectivity pattern between\n", "nodes of adjacent layers: Each node in a convolutional layer is\n", "connected only to a subset of the nodes in the previous layer, in\n", "contrast to the fully-connected FFNN. Often, CNNs consist of several\n", "convolutional layers that learn local features of the input, with a\n", "fully-connected layer at the end, which gathers all the local data and\n", "produces the outputs. They have wide applications in image and video\n", "recognition.\n", "\n", "\n", "## Recurrent neural networks\n", "\n", "So far we have only mentioned ANNs where information flows in one\n", "direction: forward. *Recurrent neural networks* on the other hand,\n", "have connections between nodes that form directed *cycles*. This\n", "creates a form of internal memory which are able to capture\n", "information on what has been calculated before; the output is\n", "dependent on the previous computations. Recurrent NNs make use of\n", "sequential information by performing the same task for every element\n", "in a sequence, where each element depends on previous elements. An\n", "example of such information is sentences, making recurrent NNs\n", "especially well-suited for handwriting and speech recognition.\n", "\n", "\n", "## Other types of networks\n", "\n", "There are many other kinds of ANNs that have been developed. One type\n", "that is specifically designed for interpolation in multidimensional\n", "space is the radial basis function (RBF) network. RBFs are typically\n", "made up of three layers: an input layer, a hidden layer with\n", "non-linear radial symmetric activation functions and a linear output\n", "layer (''linear'' here means that each node in the output layer has a\n", "linear activation function). The layers are normally fully-connected\n", "and there are no cycles, thus RBFs can be viewed as a type of\n", "fully-connected FFNN. They are however usually treated as a separate\n", "type of NN due the unusual activation functions.\n", "\n", "\n", "## Multilayer perceptrons\n", "\n", "One uses often so-called fully-connected feed-forward neural networks\n", "with three or more layers (an input layer, one or more hidden layers\n", "and an output layer) consisting of neurons that have non-linear\n", "activation functions.\n", "\n", "Such networks are often called *multilayer perceptrons* (MLPs).\n", "\n", "\n", "## Why multilayer perceptrons?\n", "\n", "According to the *Universal approximation theorem*, a feed-forward\n", "neural network with just a single hidden layer containing a finite\n", "number of neurons can approximate a continuous multidimensional\n", "function to arbitrary accuracy, assuming the activation function for\n", "the hidden layer is a **non-constant, bounded and\n", "monotonically-increasing continuous function**.\n", "\n", "Note that the requirements on the activation function only applies to\n", "the hidden layer, the output nodes are always assumed to be linear, so\n", "as to not restrict the range of output values.\n", "\n", "\n", "\n", "## Mathematical model\n", "\n", "The output $y$ is produced via the activation function $f$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "$$\n", "y = f\\left(\\sum_{i=1}^n w_ix_i + b_i\\right) = f(z),\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "This function receives $x_i$ as inputs.\n", "Here the activation $z=(\\sum_{i=1}^n w_ix_i+b_i)$. \n", "In an FFNN of such neurons, the *inputs* $x_i$ are the *outputs* of\n", "the neurons in the preceding layer. Furthermore, an MLP is\n", "fully-connected, which means that each neuron receives a weighted sum\n", "of the outputs of *all* neurons in the previous layer.\n", "\n", "\n", "## Mathematical model\n", "\n", "First, for each node $i$ in the first hidden layer, we calculate a weighted sum $z_i^1$ of the input coordinates $x_j$," ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "\n", "
\n", "\n", "$$\n", "\\begin{equation} z_i^1 = \\sum_{j=1}^{M} w_{ij}^1 x_j + b_i^1\n", "\\label{_auto48} \\tag{68}\n", "\\end{equation}\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Here $b_i$ is the so-called bias which is normally needed in\n", "case of zero activation weights or inputs. How to fix the biases and\n", "the weights will be discussed below. The value of $z_i^1$ is the\n", "argument to the activation function $f_i$ of each node $i$, The\n", "variable $M$ stands for all possible inputs to a given node $i$ in the\n", "first layer. We define the output $y_i^1$ of all neurons in layer 1 as" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "\n", "
\n", "\n", "$$\n", "\\begin{equation}\n", " y_i^1 = f(z_i^1) = f\\left(\\sum_{j=1}^M w_{ij}^1 x_j + b_i^1\\right)\n", "\\label{outputLayer1} \\tag{69}\n", "\\end{equation}\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "where we assume that all nodes in the same layer have identical\n", "activation functions, hence the notation $f$. In general, we could assume in the more general case that different layers have different activation functions.\n", "In this case we would identify these functions with a superscript $l$ for the $l$-th layer," ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "\n", "
\n", "\n", "$$\n", "\\begin{equation}\n", " y_i^l = f^l(u_i^l) = f^l\\left(\\sum_{j=1}^{N_{l-1}} w_{ij}^l y_j^{l-1} + b_i^l\\right)\n", "\\label{generalLayer} \\tag{70}\n", "\\end{equation}\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "where $N_l$ is the number of nodes in layer $l$. When the output of\n", "all the nodes in the first hidden layer are computed, the values of\n", "the subsequent layer can be calculated and so forth until the output\n", "is obtained.\n", "\n", "\n", "\n", "\n", "## Mathematical model\n", "\n", "The output of neuron $i$ in layer 2 is thus," ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "\n", "
\n", "\n", "$$\n", "\\begin{equation}\n", " y_i^2 = f^2\\left(\\sum_{j=1}^N w_{ij}^2 y_j^1 + b_i^2\\right) \n", "\\label{_auto49} \\tag{71}\n", "\\end{equation}\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "\n", "
\n", "\n", "$$\n", "\\begin{equation} \n", " = f^2\\left[\\sum_{j=1}^N w_{ij}^2f^1\\left(\\sum_{k=1}^M w_{jk}^1 x_k + b_j^1\\right) + b_i^2\\right]\n", "\\label{outputLayer2} \\tag{72}\n", "\\end{equation}\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "where we have substituted $y_k^1$ with the inputs $x_k$. Finally, the ANN output reads" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "\n", "
\n", "\n", "$$\n", "\\begin{equation}\n", " y_i^3 = f^3\\left(\\sum_{j=1}^N w_{ij}^3 y_j^2 + b_i^3\\right) \n", "\\label{_auto50} \\tag{73}\n", "\\end{equation}\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "\n", "
\n", "\n", "$$\n", "\\begin{equation} \n", " = f_3\\left[\\sum_{j} w_{ij}^3 f^2\\left(\\sum_{k} w_{jk}^2 f^1\\left(\\sum_{m} w_{km}^1 x_m + b_k^1\\right) + b_j^2\\right)\n", " + b_1^3\\right]\n", "\\label{_auto51} \\tag{74}\n", "\\end{equation}\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Mathematical model\n", "\n", "We can generalize this expression to an MLP with $l$ hidden\n", "layers. The complete functional form is," ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "\n", "
\n", "\n", "$$\n", "\\begin{equation}\n", "y^{l+1}_i = f^{l+1}\\left[\\!\\sum_{j=1}^{N_l} w_{ij}^3 f^l\\left(\\sum_{k=1}^{N_{l-1}}w_{jk}^{l-1}\\left(\\dots f^1\\left(\\sum_{n=1}^{N_0} w_{mn}^1 x_n+ b_m^1\\right)\\dots\\right)+b_k^2\\right)+b_1^3\\right] \n", "\\label{completeNN} \\tag{75}\n", "\\end{equation}\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "which illustrates a basic property of MLPs: The only independent\n", "variables are the input values $x_n$.\n", "\n", "\n", "## Mathematical model\n", "\n", "This confirms that an MLP, despite its quite convoluted mathematical\n", "form, is nothing more than an analytic function, specifically a\n", "mapping of real-valued vectors $\\hat{x} \\in \\mathbb{R}^n \\rightarrow\n", "\\hat{y} \\in \\mathbb{R}^m$.\n", "\n", "Furthermore, the flexibility and universality of an MLP can be\n", "illustrated by realizing that the expression is essentially a nested\n", "sum of scaled activation functions of the form" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "\n", "
\n", "\n", "$$\n", "\\begin{equation}\n", " f(x) = c_1 f(c_2 x + c_3) + c_4\n", "\\label{_auto52} \\tag{76}\n", "\\end{equation}\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "where the parameters $c_i$ are weights and biases. By adjusting these\n", "parameters, the activation functions can be shifted up and down or\n", "left and right, change slope or be rescaled which is the key to the\n", "flexibility of a neural network.\n", "\n", "\n", "### Matrix-vector notation\n", "\n", "We can introduce a more convenient notation for the activations in an A NN. \n", "\n", "Additionally, we can represent the biases and activations\n", "as layer-wise column vectors $\\hat{b}_l$ and $\\hat{y}_l$, so that the $i$-th element of each vector \n", "is the bias $b_i^l$ and activation $y_i^l$ of node $i$ in layer $l$ respectively. \n", "\n", "We have that $\\mathrm{W}_l$ is an $N_{l-1} \\times N_l$ matrix, while $\\hat{b}_l$ and $\\hat{y}_l$ are $N_l \\times 1$ column vectors. \n", "With this notation, the sum becomes a matrix-vector multiplication, and we can write\n", "the equation for the activations of hidden layer 2 (assuming three nodes for simplicity) as" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "\n", "
\n", "\n", "$$\n", "\\begin{equation}\n", " \\hat{y}_2 = f_2(\\mathrm{W}_2 \\hat{y}_{1} + \\hat{b}_{2}) = \n", " f_2\\left(\\left[\\begin{array}{ccc}\n", " w^2_{11} &w^2_{12} &w^2_{13} \\\\\n", " w^2_{21} &w^2_{22} &w^2_{23} \\\\\n", " w^2_{31} &w^2_{32} &w^2_{33} \\\\\n", " \\end{array} \\right] \\cdot\n", " \\left[\\begin{array}{c}\n", " y^1_1 \\\\\n", " y^1_2 \\\\\n", " y^1_3 \\\\\n", " \\end{array}\\right] + \n", " \\left[\\begin{array}{c}\n", " b^2_1 \\\\\n", " b^2_2 \\\\\n", " b^2_3 \\\\\n", " \\end{array}\\right]\\right).\n", "\\label{_auto53} \\tag{77}\n", "\\end{equation}\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Matrix-vector notation and activation\n", "\n", "The activation of node $i$ in layer 2 is" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "\n", "
\n", "\n", "$$\n", "\\begin{equation}\n", " y^2_i = f_2\\Bigr(w^2_{i1}y^1_1 + w^2_{i2}y^1_2 + w^2_{i3}y^1_3 + b^2_i\\Bigr) = \n", " f_2\\left(\\sum_{j=1}^3 w^2_{ij} y_j^1 + b^2_i\\right).\n", "\\label{_auto54} \\tag{78}\n", "\\end{equation}\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "This is not just a convenient and compact notation, but also a useful\n", "and intuitive way to think about MLPs: The output is calculated by a\n", "series of matrix-vector multiplications and vector additions that are\n", "used as input to the activation functions. For each operation\n", "$\\mathrm{W}_l \\hat{y}_{l-1}$ we move forward one layer.\n", "\n", "\n", "\n", "### Activation functions\n", "\n", "A property that characterizes a neural network, other than its\n", "connectivity, is the choice of activation function(s). As described\n", "in, the following restrictions are imposed on an activation function\n", "for a FFNN to fulfill the universal approximation theorem\n", "\n", " * Non-constant\n", "\n", " * Bounded\n", "\n", " * Monotonically-increasing\n", "\n", " * Continuous\n", "\n", "### Activation functions, Logistic and Hyperbolic ones\n", "\n", "The second requirement excludes all linear functions. Furthermore, in\n", "a MLP with only linear activation functions, each layer simply\n", "performs a linear transformation of its inputs.\n", "\n", "Regardless of the number of layers, the output of the NN will be\n", "nothing but a linear function of the inputs. Thus we need to introduce\n", "some kind of non-linearity to the NN to be able to fit non-linear\n", "functions Typical examples are the logistic *Sigmoid*" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "$$\n", "f(x) = \\frac{1}{1 + e^{-x}},\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "and the *hyperbolic tangent* function" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "$$\n", "f(x) = \\tanh(x)\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Relevance\n", "\n", "The *sigmoid* function are more biologically plausible because the\n", "output of inactive neurons are zero. Such activation function are\n", "called *one-sided*. However, it has been shown that the hyperbolic\n", "tangent performs better than the sigmoid for training MLPs. has\n", "become the most popular for *deep neural networks*" ] }, { "cell_type": "code", "execution_count": 97, "metadata": { "collapsed": false }, "outputs": [], "source": [ "\"\"\"The sigmoid function (or the logistic curve) is a \n", "function that takes any real number, z, and outputs a number (0,1).\n", "It is useful in neural networks for assigning weights on a relative scale.\n", "The value z is the weighted sum of parameters involved in the learning algorithm.\"\"\"\n", "\n", "import numpy\n", "import matplotlib.pyplot as plt\n", "import math as mt\n", "\n", "z = numpy.arange(-5, 5, .1)\n", "sigma_fn = numpy.vectorize(lambda z: 1/(1+numpy.exp(-z)))\n", "sigma = sigma_fn(z)\n", "\n", "fig = plt.figure()\n", "ax = fig.add_subplot(111)\n", "ax.plot(z, sigma)\n", "ax.set_ylim([-0.1, 1.1])\n", "ax.set_xlim([-5,5])\n", "ax.grid(True)\n", "ax.set_xlabel('z')\n", "ax.set_title('sigmoid function')\n", "\n", "plt.show()\n", "\n", "\"\"\"Step Function\"\"\"\n", "z = numpy.arange(-5, 5, .02)\n", "step_fn = numpy.vectorize(lambda z: 1.0 if z >= 0.0 else 0.0)\n", "step = step_fn(z)\n", "\n", "fig = plt.figure()\n", "ax = fig.add_subplot(111)\n", "ax.plot(z, step)\n", "ax.set_ylim([-0.5, 1.5])\n", "ax.set_xlim([-5,5])\n", "ax.grid(True)\n", "ax.set_xlabel('z')\n", "ax.set_title('step function')\n", "\n", "plt.show()\n", "\n", "\"\"\"Sine Function\"\"\"\n", "z = numpy.arange(-2*mt.pi, 2*mt.pi, 0.1)\n", "t = numpy.sin(z)\n", "\n", "fig = plt.figure()\n", "ax = fig.add_subplot(111)\n", "ax.plot(z, t)\n", "ax.set_ylim([-1.0, 1.0])\n", "ax.set_xlim([-2*mt.pi,2*mt.pi])\n", "ax.grid(True)\n", "ax.set_xlabel('z')\n", "ax.set_title('sine function')\n", "\n", "plt.show()\n", "\n", "\"\"\"Plots a graph of the squashing function used by a rectified linear\n", "unit\"\"\"\n", "z = numpy.arange(-2, 2, .1)\n", "zero = numpy.zeros(len(z))\n", "y = numpy.max([zero, z], axis=0)\n", "\n", "fig = plt.figure()\n", "ax = fig.add_subplot(111)\n", "ax.plot(z, y)\n", "ax.set_ylim([-2.0, 2.0])\n", "ax.set_xlim([-2.0, 2.0])\n", "ax.grid(True)\n", "ax.set_xlabel('z')\n", "ax.set_title('Rectified linear unit')\n", "\n", "plt.show()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## The multilayer perceptron (MLP)\n", "\n", "The multilayer perceptron is a very popular, and easy to implement approach, to deep learning. It consists of\n", "1. A neural network with one or more layers of nodes between the input and the output nodes.\n", "\n", "2. The multilayer network structure, or architecture, or topology, consists of an input layer, one or more hidden layers, and one output layer.\n", "\n", "3. The input nodes pass values to the first hidden layer, its nodes pass the information on to the second and so on till we reach the output layer.\n", "\n", "As a convention it is normal to call a network with one layer of input units, one layer of hidden\n", "units and one layer of output units as a two-layer network. A network with two layers of hidden units is called a three-layer network etc etc.\n", "\n", "For an MLP network there is no direct connection between the output nodes/neurons/units and the input nodes/neurons/units.\n", "Hereafter we will call the various entities of a layer for nodes.\n", "There are also no connections within a single layer.\n", "\n", "The number of input nodes does not need to equal the number of output\n", "nodes. This applies also to the hidden layers. Each layer may have its\n", "own number of nodes and activation functions.\n", "\n", "The hidden layers have their name from the fact that they are not\n", "linked to observables and as we will see below when we define the\n", "so-called activation $\\hat{z}$, we can think of this as a basis\n", "expansion of the original inputs $\\hat{x}$. The difference however\n", "between neural networks and say linear regression is that now these\n", "basis functions (which will correspond to the weights in the network)\n", "are learned from data. This results in an important difference between\n", "neural networks and deep learning approaches on one side and methods\n", "like logistic regression or linear regression and their modifications on the other side.\n", "\n", "\n", "\n", "## From one to many layers, the universal approximation theorem\n", "\n", "\n", "A neural network with only one layer, what we called the simple\n", "perceptron, is best suited if we have a standard binary model with\n", "clear (linear) boundaries between the outcomes. As such it could\n", "equally well be replaced by standard linear regression or logistic\n", "regression. Networks with one or more hidden layers approximate\n", "systems with more complex boundaries.\n", "\n", "As stated earlier, \n", "an important theorem in studies of neural networks, restated without\n", "proof here, is the [universal approximation\n", "theorem](http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.441.7873&rep=rep1&type=pdf).\n", "\n", "It states that a feed-forward network with a single hidden layer\n", "containing a finite number of neurons can approximate continuous\n", "functions on compact subsets of real functions. The theorem thus\n", "states that simple neural networks can represent a wide variety of\n", "interesting functions when given appropriate parameters. It is the\n", "multilayer feedforward architecture itself which gives neural networks\n", "the potential of being universal approximators.\n", "\n", "\n", "\n", "## Deriving the back propagation code for a multilayer perceptron model\n", "\n", "\n", "**Note: figures will be inserted later!**\n", "\n", "As we have seen now in a feed forward network, we can express the final output of our network in terms of basic matrix-vector multiplications.\n", "The unknowwn quantities are our weights $w_{ij}$ and we need to find an algorithm for changing them so that our errors are as small as possible.\n", "This leads us to the famous [back propagation algorithm](https://www.nature.com/articles/323533a0).\n", "\n", "The questions we want to ask are how do changes in the biases and the\n", "weights in our network change the cost function and how can we use the\n", "final output to modify the weights?\n", "\n", "To derive these equations let us start with a plain regression problem\n", "and define our cost function as" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "$$\n", "{\\cal C}(\\hat{W}) = \\frac{1}{2}\\sum_{i=1}^n\\left(y_i - t_i\\right)^2,\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "where the $t_i$s are our $n$ targets (the values we want to\n", "reproduce), while the outputs of the network after having propagated\n", "all inputs $\\hat{x}$ are given by $y_i$. Below we will demonstrate\n", "how the basic equations arising from the back propagation algorithm\n", "can be modified in order to study classification problems with $K$\n", "classes.\n", "\n", "\n", "## Definitions\n", "\n", "With our definition of the targets $\\hat{t}$, the outputs of the\n", "network $\\hat{y}$ and the inputs $\\hat{x}$ we\n", "define now the activation $z_j^l$ of node/neuron/unit $j$ of the\n", "$l$-th layer as a function of the bias, the weights which add up from\n", "the previous layer $l-1$ and the forward passes/outputs\n", "$\\hat{a}^{l-1}$ from the previous layer as" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "$$\n", "z_j^l = \\sum_{i=1}^{M_{l-1}}w_{ij}^la_i^{l-1}+b_j^l,\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "where $b_k^l$ are the biases from layer $l$. Here $M_{l-1}$\n", "represents the total number of nodes/neurons/units of layer $l-1$. The\n", "figure here illustrates this equation. We can rewrite this in a more\n", "compact form as the matrix-vector products we discussed earlier," ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "$$\n", "\\hat{z}^l = \\left(\\hat{W}^l\\right)^T\\hat{a}^{l-1}+\\hat{b}^l.\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "With the activation values $\\hat{z}^l$ we can in turn define the\n", "output of layer $l$ as $\\hat{a}^l = f(\\hat{z}^l)$ where $f$ is our\n", "activation function. In the examples here we will use the sigmoid\n", "function discussed in our logistic regression lectures. We will also use the same activation function $f$ for all layers\n", "and their nodes. It means we have" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "$$\n", "a_j^l = f(z_j^l) = \\frac{1}{1+\\exp{-(z_j^l)}}.\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Derivatives and the chain rule\n", "\n", "From the definition of the activation $z_j^l$ we have" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "$$\n", "\\frac{\\partial z_j^l}{\\partial w_{ij}^l} = a_i^{l-1},\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "and" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "$$\n", "\\frac{\\partial z_j^l}{\\partial a_i^{l-1}} = w_{ji}^l.\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "With our definition of the activation function we have that (note that this function depends only on $z_j^l$)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "$$\n", "\\frac{\\partial a_j^l}{\\partial z_j^{l}} = a_j^l(1-a_j^l)=f(z_j^l)(1-f(z_j^l)).\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Derivative of the cost function\n", "\n", "With these definitions we can now compute the derivative of the cost function in terms of the weights.\n", "\n", "Let us specialize to the output layer $l=L$. Our cost function is" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "$$\n", "{\\cal C}(\\hat{W^L}) = \\frac{1}{2}\\sum_{i=1}^n\\left(y_i - t_i\\right)^2=\\frac{1}{2}\\sum_{i=1}^n\\left(a_i^L - t_i\\right)^2,\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "The derivative of this function with respect to the weights is" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "$$\n", "\\frac{\\partial{\\cal C}(\\hat{W^L})}{\\partial w_{jk}^L} = \\left(a_j^L - t_j\\right)\\frac{\\partial a_j^L}{\\partial w_{jk}^{L}},\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "The last partial derivative can easily be computed and reads (by applying the chain rule)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "$$\n", "\\frac{\\partial a_j^L}{\\partial w_{jk}^{L}} = \\frac{\\partial a_j^L}{\\partial z_{j}^{L}}\\frac{\\partial z_j^L}{\\partial w_{jk}^{L}}=a_j^L(1-a_j^L)a_k^{L-1},\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Bringing it together, first back propagation equation\n", "\n", "We have thus" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "$$\n", "\\frac{\\partial{\\cal C}(\\hat{W^L})}{\\partial w_{jk}^L} = \\left(a_j^L - t_j\\right)a_j^L(1-a_j^L)a_k^{L-1},\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Defining" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "$$\n", "\\delta_j^L = a_j^L(1-a_j^L)\\left(a_j^L - t_j\\right) = f'(z_j^L)\\frac{\\partial {\\cal C}}{\\partial (a_j^L)},\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "and using the Hadamard product of two vectors we can write this as" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "$$\n", "\\hat{\\delta}^L = f'(\\hat{z}^L)\\circ\\frac{\\partial {\\cal C}}{\\partial (\\hat{a}L)}.\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "This is an important expression. The second term on the right handside\n", "measures how fast the cost function is changing as a function of the $j$th\n", "output activation. If, for example, the cost function doesn't depend\n", "much on a particular output node $j$, then $\\delta_j^L$ will be small,\n", "which is what we would expect. The first term on the right, measures\n", "how fast the activation function $f$ is changing at a given activation\n", "value $z_j^L$.\n", "\n", "Notice that everything in the above equations is easily computed. In\n", "particular, we compute $z_j^L$ while computing the behaviour of the\n", "network, and it is only a small additional overhead to compute\n", "$f'(z^L_j)$. The exact form of the derivative with respect to the\n", "output depends on the form of the cost function.\n", "However, provided the cost function is known there should be little\n", "trouble in calculating" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "$$\n", "\\frac{\\partial {\\cal C}}{\\partial (a_j^L)}\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "With the definition of $\\delta_j^L$ we have a more compact definition of the derivative of the cost function in terms of the weights, namely" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "$$\n", "\\frac{\\partial{\\cal C}(\\hat{W^L})}{\\partial w_{jk}^L} = \\delta_j^La_k^{L-1}.\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Derivatives in terms of $z_j^L$\n", "\n", "It is also easy to see that our previous equation can be written as" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "$$\n", "\\delta_j^L =\\frac{\\partial {\\cal C}}{\\partial z_j^L}= \\frac{\\partial {\\cal C}}{\\partial a_j^L}\\frac{\\partial a_j^L}{\\partial z_j^L},\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "which can also be interpreted as the partial derivative of the cost function with respect to the biases $b_j^L$, namely" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "$$\n", "\\delta_j^L = \\frac{\\partial {\\cal C}}{\\partial b_j^L}\\frac{\\partial b_j^L}{\\partial z_j^L}=\\frac{\\partial {\\cal C}}{\\partial b_j^L},\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "That is, the error $\\delta_j^L$ is exactly equal to the rate of change of the cost function as a function of the bias. \n", "\n", "## Bringing it together\n", "\n", "We have now three equations that are essential for the computations of the derivatives of the cost function at the output layer. These equations are needed to start the algorithm and they are\n", "\n", " The starting equations" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "\n", "
\n", "\n", "$$\n", "\\begin{equation}\n", "\\frac{\\partial{\\cal C}(\\hat{W^L})}{\\partial w_{jk}^L} = \\delta_j^La_k^{L-1},\n", "\\label{_auto55} \\tag{79}\n", "\\end{equation}\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "and" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "\n", "
\n", "\n", "$$\n", "\\begin{equation}\n", "\\delta_j^L = f'(z_j^L)\\frac{\\partial {\\cal C}}{\\partial (a_j^L)},\n", "\\label{_auto56} \\tag{80}\n", "\\end{equation}\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "and" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "\n", "
\n", "\n", "$$\n", "\\begin{equation}\n", "\\delta_j^L = \\frac{\\partial {\\cal C}}{\\partial b_j^L},\n", "\\label{_auto57} \\tag{81}\n", "\\end{equation}\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "An interesting consequence of the above equations is that when the\n", "activation $a_k^{L-1}$ is small, the gradient term, that is the\n", "derivative of the cost function with respect to the weights, will also\n", "tend to be small. We say then that the weight learns slowly, meaning\n", "that it changes slowly when we minimize the weights via say gradient\n", "descent. In this case we say the system learns slowly.\n", "\n", "Another interesting feature is that is when the activation function,\n", "represented by the sigmoid function here, is rather flat when we move towards\n", "its end values $0$ and $1$ (see the above Python codes). In these\n", "cases, the derivatives of the activation function will also be close\n", "to zero, meaning again that the gradients will be small and the\n", "network learns slowly again.\n", "\n", "\n", "\n", "We need a fourth equation and we are set. We are going to propagate\n", "backwards in order to the determine the weights and biases. In order\n", "to do so we need to represent the error in the layer before the final\n", "one $L-1$ in terms of the errors in the final output layer.\n", "\n", "\n", "## Final back propagating equation\n", "\n", "We have that (replacing $L$ with a general layer $l$)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "$$\n", "\\delta_j^l =\\frac{\\partial {\\cal C}}{\\partial z_j^l}.\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "We want to express this in terms of the equations for layer $l+1$. Using the chain rule and summing over all $k$ entries we have" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "$$\n", "\\delta_j^l =\\sum_k \\frac{\\partial {\\cal C}}{\\partial z_k^{l+1}}\\frac{\\partial z_k^{l+1}}{\\partial z_j^{l}}=\\sum_k \\delta_k^{l+1}\\frac{\\partial z_k^{l+1}}{\\partial z_j^{l}},\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "and recalling that" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "$$\n", "z_j^{l+1} = \\sum_{i=1}^{M_{l}}w_{ij}^{l+1}a_j^{l}+b_j^{l+1},\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "with $M_l$ being the number of nodes in layer $l$, we obtain" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "$$\n", "\\delta_j^l =\\sum_k \\delta_k^{l+1}w_{kj}^{l+1}f'(z_j^l),\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "This is our final equation.\n", "\n", "We are now ready to set up the algorithm for back propagation and learning the weights and biases.\n", "\n", "\n", "## Setting up the Back propagation algorithm\n", "\n", "\n", "\n", "The four equations provide us with a way of computing the gradient of the cost function. Let us write this out in the form of an algorithm.\n", "\n", "\n", "First, we set up the input data $\\hat{x}$ and the activations\n", "$\\hat{z}_1$ of the input layer and compute the activation function and\n", "the pertinent outputs $\\hat{a}^1$.\n", "\n", "\n", "\n", "Secondly, we perform then the feed forward till we reach the output\n", "layer and compute all $\\hat{z}_l$ of the input layer and compute the\n", "activation function and the pertinent outputs $\\hat{a}^l$ for\n", "$l=2,3,\\dots,L$.\n", "\n", "\n", "\n", "Thereafter we compute the ouput error $\\hat{\\delta}^L$ by computing all" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "$$\n", "\\delta_j^L = f'(z_j^L)\\frac{\\partial {\\cal C}}{\\partial (a_j^L)}.\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Then we compute the back propagate error for each $l=L-1,L-2,\\dots,2$ as" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "$$\n", "\\delta_j^l = \\sum_k \\delta_k^{l+1}w_{kj}^{l+1}f'(z_j^l).\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Finally, we update the weights and the biases using gradient descent for each $l=L-1,L-2,\\dots,2$ and update the weights and biases according to the rules" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "$$\n", "w_{jk}^l\\leftarrow = w_{jk}^l- \\eta \\delta_j^la_k^{l-1},\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "$$\n", "b_j^l \\leftarrow b_j^l-\\eta \\frac{\\partial {\\cal C}}{\\partial b_j^l}=b_j^l-\\eta \\delta_j^l,\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "The parameter $\\eta$ is the learning parameter discussed in connection with the gradient descent methods.\n", "Here it is convenient to use stochastic gradient descent (see the examples below) with mini-batches with an outer loop that steps through multiple epochs of training.\n", "\n", "\n", "\n", "## Setting up a Multi-layer perceptron model for classification\n", "\n", "We are now gong to develop an example based on the MNIST data\n", "base. This is a classification problem and we need to use our\n", "cross-entropy function we discussed in connection with logistic\n", "regression. The cross-entropy defines our cost function for the\n", "classificaton problems with neural networks.\n", "\n", "In binary classification with two classes $(0, 1)$ we define the\n", "logistic/sigmoid function as the probability that a particular input\n", "is in class $0$ or $1$. This is possible because the logistic\n", "function takes any input from the real numbers and inputs a number\n", "between 0 and 1, and can therefore be interpreted as a probability. It\n", "also has other nice properties, such as a derivative that is simple to\n", "calculate.\n", "\n", "For an input $\\boldsymbol{a}$ from the hidden layer, the probability that the input $\\boldsymbol{x}$\n", "is in class 0 or 1 is just. We let $\\theta$ represent the unknown weights and biases to be adjusted by our equations). The variable $x$\n", "represents our activation values $z$. We have" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "$$\n", "P(y = 0 \\mid \\hat{x}, \\hat{\\theta}) = \\frac{1}{1 + \\exp{(- \\hat{x}})} ,\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "and" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "$$\n", "P(y = 1 \\mid \\hat{x}, \\hat{\\theta}) = 1 - P(y = 0 \\mid \\hat{x}, \\hat{\\theta}) ,\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "where $y \\in \\{0, 1\\}$ and $\\hat{\\theta}$ represents the weights and biases\n", "of our network.\n", "\n", "\n", "\n", "## Defining the cost function\n", "\n", "Our cost function is given as (see the Logistic regression lectures)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "$$\n", "\\mathcal{C}(\\hat{\\theta}) = - \\ln P(\\mathcal{D} \\mid \\hat{\\theta}) = - \\sum_{i=1}^n\n", "y_i \\ln[P(y_i = 0)] + (1 - y_i) \\ln [1 - P(y_i = 0)] = \\sum_{i=1}^n \\mathcal{L}_i(\\hat{\\theta}) .\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "This last equality means that we can interpret our *cost* function as a sum over the *loss* function\n", "for each point in the dataset $\\mathcal{L}_i(\\hat{\\theta})$. \n", "The negative sign is just so that we can think about our algorithm as minimizing a positive number, rather\n", "than maximizing a negative number. \n", "\n", "In *multiclass* classification it is common to treat each integer label as a so called *one-hot* vector: \n", "\n", "$y = 5 \\quad \\rightarrow \\quad \\hat{y} = (0, 0, 0, 0, 0, 1, 0, 0, 0, 0) ,$ and\n", "\n", "\n", "$y = 1 \\quad \\rightarrow \\quad \\hat{y} = (0, 1, 0, 0, 0, 0, 0, 0, 0, 0) ,$ \n", "\n", "\n", "i.e. a binary bit string of length $C$, where $C = 10$ is the number of classes in the MNIST dataset (numbers from $0$ to $9$).. \n", "\n", "If $\\hat{x}_i$ is the $i$-th input (image), $y_{ic}$ refers to the $c$-th component of the $i$-th\n", "output vector $\\hat{y}_i$. \n", "The probability of $\\hat{x}_i$ being in class $c$ will be given by the softmax function:" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "$$\n", "P(y_{ic} = 1 \\mid \\hat{x}_i, \\hat{\\theta}) = \\frac{\\exp{((\\hat{a}_i^{hidden})^T \\hat{w}_c)}}\n", "{\\sum_{c'=0}^{C-1} \\exp{((\\hat{a}_i^{hidden})^T \\hat{w}_{c'})}} ,\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "which reduces to the logistic function in the binary case. \n", "The likelihood of this $C$-class classifier\n", "is now given as:" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "$$\n", "P(\\mathcal{D} \\mid \\hat{\\theta}) = \\prod_{i=1}^n \\prod_{c=0}^{C-1} [P(y_{ic} = 1)]^{y_{ic}} .\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Again we take the negative log-likelihood to define our cost function:" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "$$\n", "\\mathcal{C}(\\hat{\\theta}) = - \\log{P(\\mathcal{D} \\mid \\hat{\\theta})}.\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "See the logistic regression lectures for a full definition of the cost function.\n", "\n", "The back propagation equations need now only a small change, namely the definition of a new cost function. We are thus ready to use the same equations as before!\n", "\n", "\n", "## Example: binary classification problem\n", "\n", "As an example of the above, relevant for project 2 as well, let us consider a binary class. As discussed in our logistic regression lectures, we defined a cost function in terms of the parameters $\\beta$ as" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "$$\n", "\\mathcal{C}(\\hat{\\beta}) = - \\sum_{i=1}^n \\left(y_i\\log{p(y_i \\vert x_i,\\hat{\\beta})}+(i-y_i)\\log{1-p(y_i \\vert x_i,\\hat{\\beta})}\\right),\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "where we had defined the logistic (sigmoid) function" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "$$\n", "p(y_i =1\\vert x_i,\\hat{\\beta})=\\frac{\\exp{(\\beta_0+\\beta_1 x_i)}}{1+\\exp{(\\beta_0+\\beta_1 x_i)}},\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "and" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "$$\n", "p(y_i =0\\vert x_i,\\hat{\\beta})=1-p(y_i =1\\vert x_i,\\hat{\\beta}).\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "The parameters $\\hat{\\beta}$ were defined using a minimization method like gradient descent or Newton-Raphson's method. \n", "\n", "Now we replace $x_i$ with the activation $z_i^l$ for a given layer $l$ and the outputs as $y_i=a_i^l=f(z_i^l)$, with $z_i^l$ now being a function of the weights $w_{ij}^l$ and biases $b_i^l$. \n", "We have then" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "$$\n", "a_i^l = y_i = \\frac{\\exp{(z_i^l)}}{1+\\exp{(z_i^l)}},\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "with" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "$$\n", "z_i^l = \\sum_{j}w_{ij}^l a_j^{l-1}+b_i^l,\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "where the superscript $l-1$ indicates that these are the outputs from layer $l-1$.\n", "Our cost function at the final layer $l=L$ is now" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "$$\n", "\\mathcal{C}(\\hat{W}) = - \\sum_{i=1}^n \\left(t_i\\log{a_i^L}+(i-t_i)\\log{(1-a_i^L)}\\right),\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "where we have defined the targets $t_i$. The derivatives of the cost function with respect to the output $a_i^L$ are then easily calculated and we get" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "$$\n", "\\frac{\\partial \\mathcal{C}(\\hat{W})}{\\partial a_i^L} = \\frac{a_i^L-t_i}{a_i^L(1-a_i^L)}.\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "In case we use another activation function than the logistic one, we need to evaluate other derivatives. \n", "\n", "\n", "\n", "## The Softmax function\n", "In case we employ the more general case given by the Softmax equation, we need to evaluate the derivative of the activation function with respect to the activation $z_i^l$, that is we need" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "$$\n", "\\frac{\\partial f(z_i^l)}{\\partial w_{jk}^l} =\n", "\\frac{\\partial f(z_i^l)}{\\partial z_j^l} \\frac{\\partial z_j^l}{\\partial w_{jk}^l}= \\frac{\\partial f(z_i^l)}{\\partial z_j^l}a_k^{l-1}.\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "For the Softmax function we have" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "$$\n", "f(z_i^l) = \\frac{\\exp{(z_i^l)}}{\\sum_{m=1}^K\\exp{(z_m^l)}}.\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Its derivative with respect to $z_j^l$ gives" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "$$\n", "\\frac{\\partial f(z_i^l)}{\\partial z_j^l}= f(z_i^l)\\left(\\delta_{ij}-f(z_j^l)\\right),\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "which in case of the simply binary model reduces to having $i=j$. \n", "\n", "\n", "## Developing a code for doing neural networks with back propagation\n", "\n", "\n", "One can identify a set of key steps when using neural networks to solve supervised learning problems: \n", "\n", "1. Collect and pre-process data \n", "\n", "2. Define model and architecture \n", "\n", "3. Choose cost function and optimizer \n", "\n", "4. Train the model \n", "\n", "5. Evaluate model performance on test data \n", "\n", "6. Adjust hyperparameters (if necessary, network architecture)\n", "\n", "## Collect and pre-process data\n", "\n", "Here we will be using the MNIST dataset, which is readily available through the **scikit-learn**\n", "package. You may also find it for example [here](http://yann.lecun.com/exdb/mnist/). \n", "The *MNIST* (Modified National Institute of Standards and Technology) database is a large database\n", "of handwritten digits that is commonly used for training various image processing systems. \n", "The MNIST dataset consists of 70 000 images of size 28x28 pixels, each labeled from 0 to 9. \n", "The scikit-learn dataset we will use consists of a selection of 1797 images of size $8\\times 8$ collected and processed from this database. \n", "\n", "To feed data into a feed-forward neural network we need to represent\n", "the inputs as a feature matrix $X = (n_{inputs}, n_{features})$. Each\n", "row represents an *input*, in this case a handwritten digit, and\n", "each column represents a *feature*, in this case a pixel. The\n", "correct answers, also known as *labels* or *targets* are\n", "represented as a 1D array of integers \n", "$Y = (n_{inputs}) = (5, 3, 1, 8,...)$.\n", "\n", "As an example, say we want to build a neural network using supervised learning to predict Body-Mass Index (BMI) from\n", "measurements of height (in m) \n", "and weight (in kg). If we have measurements of 5 people the feature matrix could be for example: \n", "\n", "$$ X = \\begin{bmatrix}\n", "1.85 & 81\\\\\n", "1.71 & 65\\\\\n", "1.95 & 103\\\\\n", "1.55 & 42\\\\\n", "1.63 & 56\n", "\\end{bmatrix} ,$$ \n", "\n", "and the targets would be: \n", "\n", "$$ Y = (23.7, 22.2, 27.1, 17.5, 21.1) $$ \n", "\n", "Since each input image is a 2D matrix, we need to flatten the image\n", "(i.e. \"unravel\" the 2D matrix into a 1D array) to turn the data into a\n", "feature matrix. This means we lose all spatial information in the\n", "image, such as locality and translational invariance. More complicated\n", "architectures such as Convolutional Neural Networks can take advantage\n", "of such information, and are most commonly applied when analyzing\n", "images." ] }, { "cell_type": "code", "execution_count": 98, "metadata": { "collapsed": false }, "outputs": [], "source": [ "# import necessary packages\n", "import numpy as np\n", "import matplotlib.pyplot as plt\n", "from sklearn import datasets\n", "\n", "\n", "# ensure the same random numbers appear every time\n", "np.random.seed(0)\n", "\n", "# display images in notebook\n", "%matplotlib inline\n", "plt.rcParams['figure.figsize'] = (12,12)\n", "\n", "\n", "# download MNIST dataset\n", "digits = datasets.load_digits()\n", "\n", "# define inputs and labels\n", "inputs = digits.images\n", "labels = digits.target\n", "\n", "print(\"inputs = (n_inputs, pixel_width, pixel_height) = \" + str(inputs.shape))\n", "print(\"labels = (n_inputs) = \" + str(labels.shape))\n", "\n", "\n", "# flatten the image\n", "# the value -1 means dimension is inferred from the remaining dimensions: 8x8 = 64\n", "n_inputs = len(inputs)\n", "inputs = inputs.reshape(n_inputs, -1)\n", "print(\"X = (n_inputs, n_features) = \" + str(inputs.shape))\n", "\n", "\n", "# choose some random images to display\n", "indices = np.arange(n_inputs)\n", "random_indices = np.random.choice(indices, size=5)\n", "\n", "for i, image in enumerate(digits.images[random_indices]):\n", " plt.subplot(1, 5, i+1)\n", " plt.axis('off')\n", " plt.imshow(image, cmap=plt.cm.gray_r, interpolation='nearest')\n", " plt.title(\"Label: %d\" % digits.target[random_indices[i]])\n", "plt.show()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Train and test datasets\n", "\n", "Performing analysis before partitioning the dataset is a major error, that can lead to incorrect conclusions. \n", "\n", "We will reserve $80 \\%$ of our dataset for training and $20 \\%$ for testing. \n", "\n", "It is important that the train and test datasets are drawn randomly from our dataset, to ensure\n", "no bias in the sampling. \n", "Say you are taking measurements of weather data to predict the weather in the coming 5 days.\n", "You don't want to train your model on measurements taken from the hours 00.00 to 12.00, and then test it on data\n", "collected from 12.00 to 24.00." ] }, { "cell_type": "code", "execution_count": 99, "metadata": { "collapsed": false }, "outputs": [], "source": [ "from sklearn.model_selection import train_test_split\n", "\n", "# one-liner from scikit-learn library\n", "train_size = 0.8\n", "test_size = 1 - train_size\n", "X_train, X_test, Y_train, Y_test = train_test_split(inputs, labels, train_size=train_size,\n", " test_size=test_size)\n", "\n", "# equivalently in numpy\n", "def train_test_split_numpy(inputs, labels, train_size, test_size):\n", " n_inputs = len(inputs)\n", " inputs_shuffled = inputs.copy()\n", " labels_shuffled = labels.copy()\n", " \n", " np.random.shuffle(inputs_shuffled)\n", " np.random.shuffle(labels_shuffled)\n", " \n", " train_end = int(n_inputs*train_size)\n", " X_train, X_test = inputs_shuffled[:train_end], inputs_shuffled[train_end:]\n", " Y_train, Y_test = labels_shuffled[:train_end], labels_shuffled[train_end:]\n", " \n", " return X_train, X_test, Y_train, Y_test\n", "\n", "#X_train, X_test, Y_train, Y_test = train_test_split_numpy(inputs, labels, train_size, test_size)\n", "\n", "print(\"Number of training images: \" + str(len(X_train)))\n", "print(\"Number of test images: \" + str(len(X_test)))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Define model and architecture\n", "\n", "Our simple feed-forward neural network will consist of an *input* layer, a single *hidden* layer and an *output* layer. The activation $y$ of each neuron is a weighted sum of inputs, passed through an activation function. In case of the simple perceptron model we have \n", "\n", "$$ z = \\sum_{i=1}^n w_i a_i ,$$\n", "\n", "$$ y = f(z) ,$$\n", "\n", "where $f$ is the activation function, $a_i$ represents input from neuron $i$ in the preceding layer\n", "and $w_i$ is the weight to input $i$. \n", "The activation of the neurons in the input layer is just the features (e.g. a pixel value). \n", "\n", "The simplest activation function for a neuron is the *Heaviside* function:\n", "\n", "$$ f(z) = \n", "\\begin{cases}\n", "1, & z > 0\\\\\n", "0, & \\text{otherwise}\n", "\\end{cases}\n", "$$\n", "\n", "A feed-forward neural network with this activation is known as a *perceptron*. \n", "For a binary classifier (i.e. two classes, 0 or 1, dog or not-dog) we can also use this in our output layer. \n", "This activation can be generalized to $k$ classes (using e.g. the *one-against-all* strategy), \n", "and we call these architectures *multiclass perceptrons*. \n", "\n", "However, it is now common to use the terms Single Layer Perceptron (SLP) (1 hidden layer) and \n", "Multilayer Perceptron (MLP) (2 or more hidden layers) to refer to feed-forward neural networks with any activation function. \n", "\n", "Typical choices for activation functions include the sigmoid function, hyperbolic tangent, and Rectified Linear Unit (ReLU). \n", "We will be using the sigmoid function $\\sigma(x)$: \n", "\n", "$$ f(x) = \\sigma(x) = \\frac{1}{1 + e^{-x}} ,$$\n", "\n", "which is inspired by probability theory (see logistic regression) and was most commonly used until about 2011. See the discussion below concerning other activation functions.\n", "\n", "\n", "## Layers\n", "\n", "* Input \n", "\n", "Since each input image has 8x8 = 64 pixels or features, we have an input layer of 64 neurons. \n", "\n", "* Hidden layer\n", "\n", "We will use 50 neurons in the hidden layer receiving input from the neurons in the input layer. \n", "Since each neuron in the hidden layer is connected to the 64 inputs we have 64x50 = 3200 weights to the hidden layer. \n", "\n", "* Output\n", "\n", "If we were building a binary classifier, it would be sufficient with a single neuron in the output layer,\n", "which could output 0 or 1 according to the Heaviside function. This would be an example of a *hard* classifier, meaning it outputs the class of the input directly. However, if we are dealing with noisy data it is often beneficial to use a *soft* classifier, which outputs the probability of being in class 0 or 1. \n", "\n", "For a soft binary classifier, we could use a single neuron and interpret the output as either being the probability of being in class 0 or the probability of being in class 1. Alternatively we could use 2 neurons, and interpret each neuron as the probability of being in each class. \n", "\n", "Since we are doing multiclass classification, with 10 categories, it is natural to use 10 neurons in the output layer. We number the neurons $j = 0,1,...,9$. The activation of each output neuron $j$ will be according to the *softmax* function: \n", "\n", "$$ P(\\text{class $j$} \\mid \\text{input $\\hat{a}$}) = \\frac{\\exp{(\\hat{a}^T \\hat{w}_j)}}\n", "{\\sum_{c=0}^{9} \\exp{(\\hat{a}^T \\hat{w}_c)}} ,$$ \n", "\n", "i.e. each neuron $j$ outputs the probability of being in class $j$ given an input from the hidden layer $\\hat{a}$, with $\\hat{w}_j$ the weights of neuron $j$ to the inputs. \n", "The denominator is a normalization factor to ensure the outputs (probabilities) sum up to 1. \n", "The exponent is just the weighted sum of inputs as before: \n", "\n", "$$ z_j = \\sum_{i=1}^n w_ {ij} a_i+b_j.$$ \n", "\n", "Since each neuron in the output layer is connected to the 50 inputs from the hidden layer we have 50x10 = 500\n", "weights to the output layer.\n", "\n", "\n", "## Weights and biases\n", "\n", "Typically weights are initialized with small values distributed around zero, drawn from a uniform\n", "or normal distribution. Setting all weights to zero means all neurons give the same output, making the network useless. \n", "\n", "Adding a bias value to the weighted sum of inputs allows the neural network to represent a greater range\n", "of values. Without it, any input with the value 0 will be mapped to zero (before being passed through the activation). The bias unit has an output of 1, and a weight to each neuron $j$, $b_j$: \n", "\n", "$$ z_j = \\sum_{i=1}^n w_ {ij} a_i + b_j.$$ \n", "\n", "The bias weights $\\hat{b}$ are often initialized to zero, but a small value like $0.01$ ensures all neurons have some output which can be backpropagated in the first training cycle." ] }, { "cell_type": "code", "execution_count": 100, "metadata": { "collapsed": false }, "outputs": [], "source": [ "# building our neural network\n", "\n", "n_inputs, n_features = X_train.shape\n", "n_hidden_neurons = 50\n", "n_categories = 10\n", "\n", "# we make the weights normally distributed using numpy.random.randn\n", "\n", "# weights and bias in the hidden layer\n", "hidden_weights = np.random.randn(n_features, n_hidden_neurons)\n", "hidden_bias = np.zeros(n_hidden_neurons) + 0.01\n", "\n", "# weights and bias in the output layer\n", "output_weights = np.random.randn(n_hidden_neurons, n_categories)\n", "output_bias = np.zeros(n_categories) + 0.01" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Feed-forward pass\n", "\n", "Denote $F$ the number of features, $H$ the number of hidden neurons and $C$ the number of categories. \n", "For each input image we calculate a weighted sum of input features (pixel values) to each neuron $j$ in the hidden layer $l$: \n", "\n", "$$ z_{j}^{l} = \\sum_{i=1}^{F} w_{ij}^{l} x_i + b_{j}^{l},$$\n", "\n", "this is then passed through our activation function \n", "\n", "$$ a_{j}^{l} = f(z_{j}^{l}) .$$ \n", "\n", "We calculate a weighted sum of inputs (activations in the hidden layer) to each neuron $j$ in the output layer: \n", "\n", "$$ z_{j}^{L} = \\sum_{i=1}^{H} w_{ij}^{L} a_{i}^{l} + b_{j}^{L}.$$ \n", "\n", "Finally we calculate the output of neuron $j$ in the output layer using the softmax function: \n", "\n", "$$ a_{j}^{L} = \\frac{\\exp{(z_j^{L})}}\n", "{\\sum_{c=0}^{C-1} \\exp{(z_c^{L})}} .$$ \n", "\n", "\n", "## Matrix multiplications\n", "\n", "Since our data has the dimensions $X = (n_{inputs}, n_{features})$ and our weights to the hidden\n", "layer have the dimensions \n", "$W_{hidden} = (n_{features}, n_{hidden})$,\n", "we can easily feed the network all our training data in one go by taking the matrix product \n", "\n", "$$ X W^{h} = (n_{inputs}, n_{hidden}),$$ \n", "\n", "and obtain a matrix that holds the weighted sum of inputs to the hidden layer\n", "for each input image and each hidden neuron. \n", "We also add the bias to obtain a matrix of weighted sums to the hidden layer $Z^{h}$: \n", "\n", "$$ \\hat{z}^{l} = \\hat{X} \\hat{W}^{l} + \\hat{b}^{l} ,$$\n", "\n", "meaning the same bias (1D array with size equal number of hidden neurons) is added to each input image. \n", "This is then passed through the activation: \n", "\n", "$$ \\hat{a}^{l} = f(\\hat{z}^l) .$$ \n", "\n", "This is fed to the output layer: \n", "\n", "$$ \\hat{z}^{L} = \\hat{a}^{L} \\hat{W}^{L} + \\hat{b}^{L} .$$\n", "\n", "Finally we receive our output values for each image and each category by passing it through the softmax function: \n", "\n", "$$ output = softmax (\\hat{z}^{L}) = (n_{inputs}, n_{categories}) .$$" ] }, { "cell_type": "code", "execution_count": 101, "metadata": { "collapsed": false }, "outputs": [], "source": [ "# setup the feed-forward pass, subscript h = hidden layer\n", "\n", "def sigmoid(x):\n", " return 1/(1 + np.exp(-x))\n", "\n", "def feed_forward(X):\n", " # weighted sum of inputs to the hidden layer\n", " z_h = np.matmul(X, hidden_weights) + hidden_bias\n", " # activation in the hidden layer\n", " a_h = sigmoid(z_h)\n", " \n", " # weighted sum of inputs to the output layer\n", " z_o = np.matmul(a_h, output_weights) + output_bias\n", " # softmax output\n", " # axis 0 holds each input and axis 1 the probabilities of each category\n", " exp_term = np.exp(z_o)\n", " probabilities = exp_term / np.sum(exp_term, axis=1, keepdims=True)\n", " \n", " return probabilities\n", "\n", "probabilities = feed_forward(X_train)\n", "print(\"probabilities = (n_inputs, n_categories) = \" + str(probabilities.shape))\n", "print(\"probability that image 0 is in category 0,1,2,...,9 = \\n\" + str(probabilities[0]))\n", "print(\"probabilities sum up to: \" + str(probabilities[0].sum()))\n", "print()\n", "\n", "# we obtain a prediction by taking the class with the highest likelihood\n", "def predict(X):\n", " probabilities = feed_forward(X)\n", " return np.argmax(probabilities, axis=1)\n", "\n", "predictions = predict(X_train)\n", "print(\"predictions = (n_inputs) = \" + str(predictions.shape))\n", "print(\"prediction for image 0: \" + str(predictions[0]))\n", "print(\"correct label for image 0: \" + str(Y_train[0]))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Choose cost function and optimizer\n", "\n", "To measure how well our neural network is doing we need to introduce a cost function. \n", "We will call the function that gives the error of a single sample output the *loss* function, and the function\n", "that gives the total error of our network across all samples the *cost* function.\n", "A typical choice for multiclass classification is the *cross-entropy* loss, also known as the negative log likelihood. \n", "\n", "In *multiclass* classification it is common to treat each integer label as a so called *one-hot* vector: \n", "\n", "$$ y = 5 \\quad \\rightarrow \\quad \\hat{y} = (0, 0, 0, 0, 0, 1, 0, 0, 0, 0) ,$$ \n", "\n", "\n", "$$ y = 1 \\quad \\rightarrow \\quad \\hat{y} = (0, 1, 0, 0, 0, 0, 0, 0, 0, 0) ,$$ \n", "\n", "\n", "i.e. a binary bit string of length $C$, where $C = 10$ is the number of classes in the MNIST dataset. \n", "\n", "Let $y_{ic}$ denote the $c$-th component of the $i$-th one-hot vector. \n", "We define the cost function $\\mathcal{C}$ as a sum over the cross-entropy loss for each point $\\hat{x}_i$ in the dataset.\n", "\n", "In the one-hot representation only one of the terms in the loss function is non-zero, namely the\n", "probability of the correct category $c'$ \n", "(i.e. the category $c'$ such that $y_{ic'} = 1$). This means that the cross entropy loss only punishes you for how wrong\n", "you got the correct label. The probability of category $c$ is given by the softmax function. The vector $\\hat{\\theta}$ represents the parameters of our network, i.e. all the weights and biases. \n", "\n", "\n", "\n", "## Optimizing the cost function\n", "\n", "The network is trained by finding the weights and biases that minimize the cost function. One of the most widely used classes of methods is *gradient descent* and its generalizations. The idea behind gradient descent\n", "is simply to adjust the weights in the direction where the gradient of the cost function is large and negative. This ensures we flow toward a *local* minimum of the cost function. \n", "Each parameter $\\theta$ is iteratively adjusted according to the rule \n", "\n", "$$ \\theta_{i+1} = \\theta_i - \\eta \\nabla \\mathcal{C}(\\theta_i) ,$$\n", "\n", "where $\\eta$ is known as the *learning rate*, which controls how big a step we take towards the minimum. \n", "This update can be repeated for any number of iterations, or until we are satisfied with the result. \n", "\n", "A simple and effective improvement is a variant called *Batch Gradient Descent*. \n", "Instead of calculating the gradient on the whole dataset, we calculate an approximation of the gradient\n", "on a subset of the data called a *minibatch*. \n", "If there are $N$ data points and we have a minibatch size of $M$, the total number of batches\n", "is $N/M$. \n", "We denote each minibatch $B_k$, with $k = 1, 2,...,N/M$. The gradient then becomes: \n", "\n", "$$ \\nabla \\mathcal{C}(\\theta) = \\frac{1}{N} \\sum_{i=1}^N \\nabla \\mathcal{L}_i(\\theta) \\quad \\rightarrow \\quad\n", "\\frac{1}{M} \\sum_{i \\in B_k} \\nabla \\mathcal{L}_i(\\theta) ,$$\n", "\n", "i.e. instead of averaging the loss over the entire dataset, we average over a minibatch. \n", "\n", "This has two important benefits: \n", "1. Introducing stochasticity decreases the chance that the algorithm becomes stuck in a local minima. \n", "\n", "2. It significantly speeds up the calculation, since we do not have to use the entire dataset to calculate the gradient. \n", "\n", "The various optmization methods, with codes and algorithms, are discussed in our lectures on [Gradient descent approaches](https://compphysics.github.io/MachineLearning/doc/pub/Splines/html/Splines-bs.html).\n", "\n", "\n", "## Regularization\n", "\n", "It is common to add an extra term to the cost function, proportional\n", "to the size of the weights. This is equivalent to constraining the\n", "size of the weights, so that they do not grow out of control.\n", "Constraining the size of the weights means that the weights cannot\n", "grow arbitrarily large to fit the training data, and in this way\n", "reduces *overfitting*.\n", "\n", "We will measure the size of the weights using the so called *L2-norm*, meaning our cost function becomes: \n", "\n", "$$ \\nabla \\mathcal{C}(\\theta) = \\frac{1}{N} \\sum_{i=1}^N \\nabla \\mathcal{L}_i(\\theta) \\quad \\rightarrow \\quad\n", "\\frac{1}{N} \\sum_{i=1}^N \\nabla \\mathcal{L}_i(\\theta) + \\lambda \\lvert \\lvert \\hat{w} \\rvert \\rvert_2^2 \n", "= \\frac{1}{N} \\sum_{i=1}^N \\nabla \\mathcal{L}(\\theta) + \\lambda \\sum_{ij} w_{ij}^2,$$ \n", "\n", "i.e. we sum up all the weights squared. The factor $\\lambda$ is known as a regularization parameter.\n", "\n", "\n", "In order to train the model, we need to calculate the derivative of\n", "the cost function with respect to every bias and weight in the\n", "network. In total our network has $(64 + 1)\\times 50=3250$ weights in\n", "the hidden layer and $(50 + 1)\\times 10=510$ weights to the output\n", "layer ($+1$ for the bias), and the gradient must be calculated for\n", "every parameter. We use the *backpropagation* algorithm discussed\n", "above. This is a clever use of the chain rule that allows us to\n", "calculate the gradient efficently. \n", "\n", "\n", "\n", "## Matrix multiplication\n", "\n", "To more efficently train our network these equations are implemented using matrix operations. \n", "The error in the output layer is calculated simply as, with $\\hat{t}$ being our targets, \n", "\n", "$$ \\delta_L = \\hat{t} - \\hat{y} = (n_{inputs}, n_{categories}) .$$ \n", "\n", "The gradient for the output weights is calculated as \n", "\n", "$$ \\nabla W_{L} = \\hat{a}^T \\delta_L = (n_{hidden}, n_{categories}) ,$$\n", "\n", "where $\\hat{a} = (n_{inputs}, n_{hidden})$. This simply means that we are summing up the gradients for each input. \n", "Since we are going backwards we have to transpose the activation matrix. \n", "\n", "The gradient with respect to the output bias is then \n", "\n", "$$ \\nabla \\hat{b}_{L} = \\sum_{i=1}^{n_{inputs}} \\delta_L = (n_{categories}) .$$ \n", "\n", "The error in the hidden layer is \n", "\n", "$$ \\Delta_h = \\delta_L W_{L}^T \\circ f'(z_{h}) = \\delta_L W_{L}^T \\circ a_{h} \\circ (1 - a_{h}) = (n_{inputs}, n_{hidden}) ,$$ \n", "\n", "where $f'(a_{h})$ is the derivative of the activation in the hidden layer. The matrix products mean\n", "that we are summing up the products for each neuron in the output layer. The symbol $\\circ$ denotes\n", "the *Hadamard product*, meaning element-wise multiplication. \n", "\n", "This again gives us the gradients in the hidden layer: \n", "\n", "$$ \\nabla W_{h} = X^T \\delta_h = (n_{features}, n_{hidden}) ,$$ \n", "\n", "$$ \\nabla b_{h} = \\sum_{i=1}^{n_{inputs}} \\delta_h = (n_{hidden}) .$$" ] }, { "cell_type": "code", "execution_count": 102, "metadata": { "collapsed": false }, "outputs": [], "source": [ "# to categorical turns our integer vector into a onehot representation\n", "from sklearn.metrics import accuracy_score\n", "\n", "# one-hot in numpy\n", "def to_categorical_numpy(integer_vector):\n", " n_inputs = len(integer_vector)\n", " n_categories = np.max(integer_vector) + 1\n", " onehot_vector = np.zeros((n_inputs, n_categories))\n", " onehot_vector[range(n_inputs), integer_vector] = 1\n", " \n", " return onehot_vector\n", "\n", "#Y_train_onehot, Y_test_onehot = to_categorical(Y_train), to_categorical(Y_test)\n", "Y_train_onehot, Y_test_onehot = to_categorical_numpy(Y_train), to_categorical_numpy(Y_test)\n", "\n", "def feed_forward_train(X):\n", " # weighted sum of inputs to the hidden layer\n", " z_h = np.matmul(X, hidden_weights) + hidden_bias\n", " # activation in the hidden layer\n", " a_h = sigmoid(z_h)\n", " \n", " # weighted sum of inputs to the output layer\n", " z_o = np.matmul(a_h, output_weights) + output_bias\n", " # softmax output\n", " # axis 0 holds each input and axis 1 the probabilities of each category\n", " exp_term = np.exp(z_o)\n", " probabilities = exp_term / np.sum(exp_term, axis=1, keepdims=True)\n", " \n", " # for backpropagation need activations in hidden and output layers\n", " return a_h, probabilities\n", "\n", "def backpropagation(X, Y):\n", " a_h, probabilities = feed_forward_train(X)\n", " \n", " # error in the output layer\n", " error_output = probabilities - Y\n", " # error in the hidden layer\n", " error_hidden = np.matmul(error_output, output_weights.T) * a_h * (1 - a_h)\n", " \n", " # gradients for the output layer\n", " output_weights_gradient = np.matmul(a_h.T, error_output)\n", " output_bias_gradient = np.sum(error_output, axis=0)\n", " \n", " # gradient for the hidden layer\n", " hidden_weights_gradient = np.matmul(X.T, error_hidden)\n", " hidden_bias_gradient = np.sum(error_hidden, axis=0)\n", "\n", " return output_weights_gradient, output_bias_gradient, hidden_weights_gradient, hidden_bias_gradient\n", "\n", "print(\"Old accuracy on training data: \" + str(accuracy_score(predict(X_train), Y_train)))\n", "\n", "eta = 0.01\n", "lmbd = 0.01\n", "for i in range(1000):\n", " # calculate gradients\n", " dWo, dBo, dWh, dBh = backpropagation(X_train, Y_train_onehot)\n", " \n", " # regularization term gradients\n", " dWo += lmbd * output_weights\n", " dWh += lmbd * hidden_weights\n", " \n", " # update weights and biases\n", " output_weights -= eta * dWo\n", " output_bias -= eta * dBo\n", " hidden_weights -= eta * dWh\n", " hidden_bias -= eta * dBh\n", "\n", "print(\"New accuracy on training data: \" + str(accuracy_score(predict(X_train), Y_train)))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Improving performance\n", "\n", "As we can see the network does not seem to be learning at all. It seems to be just guessing the label for each image. \n", "In order to obtain a network that does something useful, we will have to do a bit more work. \n", "\n", "The choice of *hyperparameters* such as learning rate and regularization parameter is hugely influential for the performance of the network. Typically a *grid-search* is performed, wherein we test different hyperparameters separated by orders of magnitude. For example we could test the learning rates $\\eta = 10^{-6}, 10^{-5},...,10^{-1}$ with different regularization parameters $\\lambda = 10^{-6},...,10^{-0}$. \n", "\n", "Next, we haven't implemented minibatching yet, which introduces stochasticity and is though to act as an important regularizer on the weights. We call a feed-forward + backward pass with a minibatch an *iteration*, and a full training period\n", "going through the entire dataset ($n/M$ batches) an *epoch*.\n", "\n", "If this does not improve network performance, you may want to consider altering the network architecture, adding more neurons or hidden layers. \n", "Andrew Ng goes through some of these considerations in this [video](https://youtu.be/F1ka6a13S9I). You can find a summary of the video [here](https://kevinzakka.github.io/2016/09/26/applying-deep-learning/). \n", "\n", "\n", "## Full object-oriented implementation\n", "\n", "It is very natural to think of the network as an object, with specific instances of the network\n", "being realizations of this object with different hyperparameters. An implementation using Python classes provides a clean structure and interface, and the full implementation of our neural network is given below." ] }, { "cell_type": "code", "execution_count": 103, "metadata": { "collapsed": false }, "outputs": [], "source": [ "class NeuralNetwork:\n", " def __init__(\n", " self,\n", " X_data,\n", " Y_data,\n", " n_hidden_neurons=50,\n", " n_categories=10,\n", " epochs=10,\n", " batch_size=100,\n", " eta=0.1,\n", " lmbd=0.0,\n", "\n", " ):\n", " self.X_data_full = X_data\n", " self.Y_data_full = Y_data\n", "\n", " self.n_inputs = X_data.shape[0]\n", " self.n_features = X_data.shape[1]\n", " self.n_hidden_neurons = n_hidden_neurons\n", " self.n_categories = n_categories\n", "\n", " self.epochs = epochs\n", " self.batch_size = batch_size\n", " self.iterations = self.n_inputs // self.batch_size\n", " self.eta = eta\n", " self.lmbd = lmbd\n", "\n", " self.create_biases_and_weights()\n", "\n", " def create_biases_and_weights(self):\n", " self.hidden_weights = np.random.randn(self.n_features, self.n_hidden_neurons)\n", " self.hidden_bias = np.zeros(self.n_hidden_neurons) + 0.01\n", "\n", " self.output_weights = np.random.randn(self.n_hidden_neurons, self.n_categories)\n", " self.output_bias = np.zeros(self.n_categories) + 0.01\n", "\n", " def feed_forward(self):\n", " # feed-forward for training\n", " self.z_h = np.matmul(self.X_data, self.hidden_weights) + self.hidden_bias\n", " self.a_h = sigmoid(self.z_h)\n", "\n", " self.z_o = np.matmul(self.a_h, self.output_weights) + self.output_bias\n", "\n", " exp_term = np.exp(self.z_o)\n", " self.probabilities = exp_term / np.sum(exp_term, axis=1, keepdims=True)\n", "\n", " def feed_forward_out(self, X):\n", " # feed-forward for output\n", " z_h = np.matmul(X, self.hidden_weights) + self.hidden_bias\n", " a_h = sigmoid(z_h)\n", "\n", " z_o = np.matmul(a_h, self.output_weights) + self.output_bias\n", " \n", " exp_term = np.exp(z_o)\n", " probabilities = exp_term / np.sum(exp_term, axis=1, keepdims=True)\n", " return probabilities\n", "\n", " def backpropagation(self):\n", " error_output = self.probabilities - self.Y_data\n", " error_hidden = np.matmul(error_output, self.output_weights.T) * self.a_h * (1 - self.a_h)\n", "\n", " self.output_weights_gradient = np.matmul(self.a_h.T, error_output)\n", " self.output_bias_gradient = np.sum(error_output, axis=0)\n", "\n", " self.hidden_weights_gradient = np.matmul(self.X_data.T, error_hidden)\n", " self.hidden_bias_gradient = np.sum(error_hidden, axis=0)\n", "\n", " if self.lmbd > 0.0:\n", " self.output_weights_gradient += self.lmbd * self.output_weights\n", " self.hidden_weights_gradient += self.lmbd * self.hidden_weights\n", "\n", " self.output_weights -= self.eta * self.output_weights_gradient\n", " self.output_bias -= self.eta * self.output_bias_gradient\n", " self.hidden_weights -= self.eta * self.hidden_weights_gradient\n", " self.hidden_bias -= self.eta * self.hidden_bias_gradient\n", "\n", " def predict(self, X):\n", " probabilities = self.feed_forward_out(X)\n", " return np.argmax(probabilities, axis=1)\n", "\n", " def predict_probabilities(self, X):\n", " probabilities = self.feed_forward_out(X)\n", " return probabilities\n", "\n", " def train(self):\n", " data_indices = np.arange(self.n_inputs)\n", "\n", " for i in range(self.epochs):\n", " for j in range(self.iterations):\n", " # pick datapoints with replacement\n", " chosen_datapoints = np.random.choice(\n", " data_indices, size=self.batch_size, replace=False\n", " )\n", "\n", " # minibatch training data\n", " self.X_data = self.X_data_full[chosen_datapoints]\n", " self.Y_data = self.Y_data_full[chosen_datapoints]\n", "\n", " self.feed_forward()\n", " self.backpropagation()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Evaluate model performance on test data\n", "\n", "To measure the performance of our network we evaluate how well it does it data it has never seen before, i.e. the test data. \n", "We measure the performance of the network using the *accuracy* score. \n", "The accuracy is as you would expect just the number of images correctly labeled divided by the total number of images. A perfect classifier will have an accuracy score of $1$. \n", "\n", "$$ \\text{Accuracy} = \\frac{\\sum_{i=1}^n I(\\hat{y}_i = y_i)}{n} ,$$ \n", "\n", "where $I$ is the indicator function, $1$ if $\\hat{y}_i = y_i$ and $0$ otherwise." ] }, { "cell_type": "code", "execution_count": 104, "metadata": { "collapsed": false }, "outputs": [], "source": [ "epochs = 100\n", "batch_size = 100\n", "\n", "dnn = NeuralNetwork(X_train, Y_train_onehot, eta=eta, lmbd=lmbd, epochs=epochs, batch_size=batch_size,\n", " n_hidden_neurons=n_hidden_neurons, n_categories=n_categories)\n", "dnn.train()\n", "test_predict = dnn.predict(X_test)\n", "\n", "# accuracy score from scikit library\n", "print(\"Accuracy score on test set: \", accuracy_score(Y_test, test_predict))\n", "\n", "# equivalent in numpy\n", "def accuracy_score_numpy(Y_test, Y_pred):\n", " return np.sum(Y_test == Y_pred) / len(Y_test)\n", "\n", "#print(\"Accuracy score on test set: \", accuracy_score_numpy(Y_test, test_predict))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Adjust hyperparameters\n", "\n", "We now perform a grid search to find the optimal hyperparameters for the network. \n", "Note that we are only using 1 layer with 50 neurons, and human performance is estimated to be around $98\\%$ ($2\\%$ error rate)." ] }, { "cell_type": "code", "execution_count": 105, "metadata": { "collapsed": false }, "outputs": [], "source": [ "eta_vals = np.logspace(-5, 1, 7)\n", "lmbd_vals = np.logspace(-5, 1, 7)\n", "# store the models for later use\n", "DNN_numpy = np.zeros((len(eta_vals), len(lmbd_vals)), dtype=object)\n", "\n", "# grid search\n", "for i, eta in enumerate(eta_vals):\n", " for j, lmbd in enumerate(lmbd_vals):\n", " dnn = NeuralNetwork(X_train, Y_train_onehot, eta=eta, lmbd=lmbd, epochs=epochs, batch_size=batch_size,\n", " n_hidden_neurons=n_hidden_neurons, n_categories=n_categories)\n", " dnn.train()\n", " \n", " DNN_numpy[i][j] = dnn\n", " \n", " test_predict = dnn.predict(X_test)\n", " \n", " print(\"Learning rate = \", eta)\n", " print(\"Lambda = \", lmbd)\n", " print(\"Accuracy score on test set: \", accuracy_score(Y_test, test_predict))\n", " print()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Visualization" ] }, { "cell_type": "code", "execution_count": 106, "metadata": { "collapsed": false }, "outputs": [], "source": [ "# visual representation of grid search\n", "# uses seaborn heatmap, you can also do this with matplotlib imshow\n", "import seaborn as sns\n", "\n", "sns.set()\n", "\n", "train_accuracy = np.zeros((len(eta_vals), len(lmbd_vals)))\n", "test_accuracy = np.zeros((len(eta_vals), len(lmbd_vals)))\n", "\n", "for i in range(len(eta_vals)):\n", " for j in range(len(lmbd_vals)):\n", " dnn = DNN_numpy[i][j]\n", " \n", " train_pred = dnn.predict(X_train) \n", " test_pred = dnn.predict(X_test)\n", "\n", " train_accuracy[i][j] = accuracy_score(Y_train, train_pred)\n", " test_accuracy[i][j] = accuracy_score(Y_test, test_pred)\n", "\n", " \n", "fig, ax = plt.subplots(figsize = (10, 10))\n", "sns.heatmap(train_accuracy, annot=True, ax=ax, cmap=\"viridis\")\n", "ax.set_title(\"Training Accuracy\")\n", "ax.set_ylabel(\"$\\eta$\")\n", "ax.set_xlabel(\"$\\lambda$\")\n", "plt.show()\n", "\n", "fig, ax = plt.subplots(figsize = (10, 10))\n", "sns.heatmap(test_accuracy, annot=True, ax=ax, cmap=\"viridis\")\n", "ax.set_title(\"Test Accuracy\")\n", "ax.set_ylabel(\"$\\eta$\")\n", "ax.set_xlabel(\"$\\lambda$\")\n", "plt.show()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## scikit-learn implementation\n", "\n", "**scikit-learn** focuses more\n", "on traditional machine learning methods, such as regression,\n", "clustering, decision trees, etc. As such, it has only two types of\n", "neural networks: Multi Layer Perceptron outputting continuous values,\n", "*MPLRegressor*, and Multi Layer Perceptron outputting labels,\n", "*MLPClassifier*. We will see how simple it is to use these classes.\n", "\n", "**scikit-learn** implements a few improvements from our neural network,\n", "such as early stopping, a varying learning rate, different\n", "optimization methods, etc. We would therefore expect a better\n", "performance overall." ] }, { "cell_type": "code", "execution_count": 107, "metadata": { "collapsed": false }, "outputs": [], "source": [ "from sklearn.neural_network import MLPClassifier\n", "# store models for later use\n", "DNN_scikit = np.zeros((len(eta_vals), len(lmbd_vals)), dtype=object)\n", "\n", "for i, eta in enumerate(eta_vals):\n", " for j, lmbd in enumerate(lmbd_vals):\n", " dnn = MLPClassifier(hidden_layer_sizes=(n_hidden_neurons), activation='logistic',\n", " alpha=lmbd, learning_rate_init=eta, max_iter=epochs)\n", " dnn.fit(X_train, Y_train)\n", " \n", " DNN_scikit[i][j] = dnn\n", " \n", " print(\"Learning rate = \", eta)\n", " print(\"Lambda = \", lmbd)\n", " print(\"Accuracy score on test set: \", dnn.score(X_test, Y_test))\n", " print()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Visualization" ] }, { "cell_type": "code", "execution_count": 108, "metadata": { "collapsed": false }, "outputs": [], "source": [ "# optional\n", "# visual representation of grid search\n", "# uses seaborn heatmap, could probably do this in matplotlib\n", "import seaborn as sns\n", "\n", "sns.set()\n", "\n", "train_accuracy = np.zeros((len(eta_vals), len(lmbd_vals)))\n", "test_accuracy = np.zeros((len(eta_vals), len(lmbd_vals)))\n", "\n", "for i in range(len(eta_vals)):\n", " for j in range(len(lmbd_vals)):\n", " dnn = DNN_scikit[i][j]\n", " \n", " train_pred = dnn.predict(X_train) \n", " test_pred = dnn.predict(X_test)\n", "\n", " train_accuracy[i][j] = accuracy_score(Y_train, train_pred)\n", " test_accuracy[i][j] = accuracy_score(Y_test, test_pred)\n", "\n", " \n", "fig, ax = plt.subplots(figsize = (10, 10))\n", "sns.heatmap(train_accuracy, annot=True, ax=ax, cmap=\"viridis\")\n", "ax.set_title(\"Training Accuracy\")\n", "ax.set_ylabel(\"$\\eta$\")\n", "ax.set_xlabel(\"$\\lambda$\")\n", "plt.show()\n", "\n", "fig, ax = plt.subplots(figsize = (10, 10))\n", "sns.heatmap(test_accuracy, annot=True, ax=ax, cmap=\"viridis\")\n", "ax.set_title(\"Test Accuracy\")\n", "ax.set_ylabel(\"$\\eta$\")\n", "ax.set_xlabel(\"$\\lambda$\")\n", "plt.show()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Building neural networks in Tensorflow and Keras\n", "\n", "Now we want to build on the experience gained from our neural network implementation in NumPy and scikit-learn\n", "and use it to construct a neural network in Tensorflow. Once we have constructed a neural network in NumPy\n", "and Tensorflow, building one in Keras is really quite trivial, though the performance may suffer. \n", "\n", "In our previous example we used only one hidden layer, and in this we will use two. From this it should be quite\n", "clear how to build one using an arbitrary number of hidden layers, using data structures such as Python lists or\n", "NumPy arrays.\n", "\n", "\n", "## Tensorflow\n", "\n", "Tensorflow is an open source library machine learning library\n", "developed by the Google Brain team for internal use. It was released\n", "under the Apache 2.0 open source license in November 9, 2015.\n", "\n", "Tensorflow is a computational framework that allows you to construct\n", "machine learning models at different levels of abstraction, from\n", "high-level, object-oriented APIs like Keras, down to the C++ kernels\n", "that Tensorflow is built upon. The higher levels of abstraction are\n", "simpler to use, but less flexible, and our choice of implementation\n", "should reflect the problems we are trying to solve.\n", "\n", "[Tensorflow uses](https://www.tensorflow.org/guide/graphs) so-called graphs to represent your computation\n", "in terms of the dependencies between individual operations, such that you first build a Tensorflow *graph*\n", "to represent your model, and then create a Tensorflow *session* to run the graph.\n", "\n", "In this guide we will analyze the same data as we did in our NumPy and\n", "scikit-learn tutorial, gathered from the MNIST database of images. We\n", "will give an introduction to the lower level Python Application\n", "Program Interfaces (APIs), and see how we use them to build our graph.\n", "Then we will build (effectively) the same graph in Keras, to see just\n", "how simple solving a machine learning problem can be.\n", "\n", "To install tensorflow on Unix/Linux systems, use pip as" ] }, { "cell_type": "code", "execution_count": 109, "metadata": { "collapsed": false }, "outputs": [], "source": [ "pip3 install tensorflow" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "and/or if you use **anaconda**, just write (or install from the graphical user interface)" ] }, { "cell_type": "code", "execution_count": 110, "metadata": { "collapsed": false }, "outputs": [], "source": [ "conda install tensorflow" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Collect and pre-process data" ] }, { "cell_type": "code", "execution_count": 111, "metadata": { "collapsed": false }, "outputs": [], "source": [ "# import necessary packages\n", "import numpy as np\n", "import matplotlib.pyplot as plt\n", "from sklearn import datasets\n", "\n", "\n", "# ensure the same random numbers appear every time\n", "np.random.seed(0)\n", "\n", "# display images in notebook\n", "%matplotlib inline\n", "plt.rcParams['figure.figsize'] = (12,12)\n", "\n", "\n", "# download MNIST dataset\n", "digits = datasets.load_digits()\n", "\n", "# define inputs and labels\n", "inputs = digits.images\n", "labels = digits.target\n", "\n", "print(\"inputs = (n_inputs, pixel_width, pixel_height) = \" + str(inputs.shape))\n", "print(\"labels = (n_inputs) = \" + str(labels.shape))\n", "\n", "\n", "# flatten the image\n", "# the value -1 means dimension is inferred from the remaining dimensions: 8x8 = 64\n", "n_inputs = len(inputs)\n", "inputs = inputs.reshape(n_inputs, -1)\n", "print(\"X = (n_inputs, n_features) = \" + str(inputs.shape))\n", "\n", "\n", "# choose some random images to display\n", "indices = np.arange(n_inputs)\n", "random_indices = np.random.choice(indices, size=5)\n", "\n", "for i, image in enumerate(digits.images[random_indices]):\n", " plt.subplot(1, 5, i+1)\n", " plt.axis('off')\n", " plt.imshow(image, cmap=plt.cm.gray_r, interpolation='nearest')\n", " plt.title(\"Label: %d\" % digits.target[random_indices[i]])\n", "plt.show()" ] }, { "cell_type": "code", "execution_count": 112, "metadata": { "collapsed": false }, "outputs": [], "source": [ "from keras.utils import to_categorical\n", "from sklearn.model_selection import train_test_split\n", "\n", "# one-hot representation of labels\n", "labels = to_categorical(labels)\n", "\n", "# split into train and test data\n", "train_size = 0.8\n", "test_size = 1 - train_size\n", "X_train, X_test, Y_train, Y_test = train_test_split(inputs, labels, train_size=train_size,\n", " test_size=test_size)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Using TensorFlow backend\n", "\n", "1. Define model and architecture\n", "\n", "2. Choose cost function and optimizer" ] }, { "cell_type": "code", "execution_count": 113, "metadata": { "collapsed": false }, "outputs": [], "source": [ "import tensorflow as tf\n", "\n", "class NeuralNetworkTensorflow:\n", " def __init__(\n", " self,\n", " X_train,\n", " Y_train,\n", " X_test,\n", " Y_test,\n", " n_neurons_layer1=100,\n", " n_neurons_layer2=50,\n", " n_categories=2,\n", " epochs=10,\n", " batch_size=100,\n", " eta=0.1,\n", " lmbd=0.0,\n", " ):\n", " \n", " # keep track of number of steps\n", " self.global_step = tf.Variable(0, dtype=tf.int32, trainable=False, name='global_step')\n", " \n", " self.X_train = X_train\n", " self.Y_train = Y_train\n", " self.X_test = X_test\n", " self.Y_test = Y_test\n", " \n", " self.n_inputs = X_train.shape[0]\n", " self.n_features = X_train.shape[1]\n", " self.n_neurons_layer1 = n_neurons_layer1\n", " self.n_neurons_layer2 = n_neurons_layer2\n", " self.n_categories = n_categories\n", " \n", " self.epochs = epochs\n", " self.batch_size = batch_size\n", " self.iterations = self.n_inputs // self.batch_size\n", " self.eta = eta\n", " self.lmbd = lmbd\n", " \n", " # build network piece by piece\n", " # name scopes (with) are used to enforce creation of new variables\n", " # https://www.tensorflow.org/guide/variables\n", " self.create_placeholders()\n", " self.create_DNN()\n", " self.create_loss()\n", " self.create_optimiser()\n", " self.create_accuracy()\n", " \n", " def create_placeholders(self):\n", " # placeholders are fine here, but \"Datasets\" are the preferred method\n", " # of streaming data into a model\n", " with tf.name_scope('data'):\n", " self.X = tf.placeholder(tf.float32, shape=(None, self.n_features), name='X_data')\n", " self.Y = tf.placeholder(tf.float32, shape=(None, self.n_categories), name='Y_data')\n", " \n", " def create_DNN(self):\n", " with tf.name_scope('DNN'):\n", " # the weights are stored to calculate regularization loss later\n", " \n", " # Fully connected layer 1\n", " self.W_fc1 = self.weight_variable([self.n_features, self.n_neurons_layer1], name='fc1', dtype=tf.float32)\n", " b_fc1 = self.bias_variable([self.n_neurons_layer1], name='fc1', dtype=tf.float32)\n", " a_fc1 = tf.nn.sigmoid(tf.matmul(self.X, self.W_fc1) + b_fc1)\n", " \n", " # Fully connected layer 2\n", " self.W_fc2 = self.weight_variable([self.n_neurons_layer1, self.n_neurons_layer2], name='fc2', dtype=tf.float32)\n", " b_fc2 = self.bias_variable([self.n_neurons_layer2], name='fc2', dtype=tf.float32)\n", " a_fc2 = tf.nn.sigmoid(tf.matmul(a_fc1, self.W_fc2) + b_fc2)\n", " \n", " # Output layer\n", " self.W_out = self.weight_variable([self.n_neurons_layer2, self.n_categories], name='out', dtype=tf.float32)\n", " b_out = self.bias_variable([self.n_categories], name='out', dtype=tf.float32)\n", " self.z_out = tf.matmul(a_fc2, self.W_out) + b_out\n", " \n", " def create_loss(self):\n", " with tf.name_scope('loss'):\n", " softmax_loss = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits_v2(labels=self.Y, logits=self.z_out))\n", " \n", " regularizer_loss_fc1 = tf.nn.l2_loss(self.W_fc1)\n", " regularizer_loss_fc2 = tf.nn.l2_loss(self.W_fc2)\n", " regularizer_loss_out = tf.nn.l2_loss(self.W_out)\n", " regularizer_loss = self.lmbd*(regularizer_loss_fc1 + regularizer_loss_fc2 + regularizer_loss_out)\n", " \n", " self.loss = softmax_loss + regularizer_loss\n", "\n", " def create_accuracy(self):\n", " with tf.name_scope('accuracy'):\n", " probabilities = tf.nn.softmax(self.z_out)\n", " predictions = tf.argmax(probabilities, axis=1)\n", " labels = tf.argmax(self.Y, axis=1)\n", " \n", " correct_predictions = tf.equal(predictions, labels)\n", " correct_predictions = tf.cast(correct_predictions, tf.float32)\n", " self.accuracy = tf.reduce_mean(correct_predictions)\n", " \n", " def create_optimiser(self):\n", " with tf.name_scope('optimizer'):\n", " self.optimizer = tf.train.GradientDescentOptimizer(learning_rate=self.eta).minimize(self.loss, global_step=self.global_step)\n", " \n", " def weight_variable(self, shape, name='', dtype=tf.float32):\n", " initial = tf.truncated_normal(shape, stddev=0.1)\n", " return tf.Variable(initial, name=name, dtype=dtype)\n", " \n", " def bias_variable(self, shape, name='', dtype=tf.float32):\n", " initial = tf.constant(0.1, shape=shape)\n", " return tf.Variable(initial, name=name, dtype=dtype)\n", " \n", " def fit(self):\n", " data_indices = np.arange(self.n_inputs)\n", "\n", " with tf.Session() as sess:\n", " sess.run(tf.global_variables_initializer())\n", " for i in range(self.epochs):\n", " for j in range(self.iterations):\n", " chosen_datapoints = np.random.choice(data_indices, size=self.batch_size, replace=False)\n", " batch_X, batch_Y = self.X_train[chosen_datapoints], self.Y_train[chosen_datapoints]\n", " \n", " sess.run([DNN.loss, DNN.optimizer],\n", " feed_dict={DNN.X: batch_X,\n", " DNN.Y: batch_Y})\n", " accuracy = sess.run(DNN.accuracy,\n", " feed_dict={DNN.X: batch_X,\n", " DNN.Y: batch_Y})\n", " step = sess.run(DNN.global_step)\n", " \n", " self.train_loss, self.train_accuracy = sess.run([DNN.loss, DNN.accuracy],\n", " feed_dict={DNN.X: self.X_train,\n", " DNN.Y: self.Y_train})\n", " \n", " self.test_loss, self.test_accuracy = sess.run([DNN.loss, DNN.accuracy],\n", " feed_dict={DNN.X: self.X_test,\n", " DNN.Y: self.Y_test})" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Optimizing and using gradient descent" ] }, { "cell_type": "code", "execution_count": 114, "metadata": { "collapsed": false }, "outputs": [], "source": [ "epochs = 100\n", "batch_size = 100\n", "n_neurons_layer1 = 100\n", "n_neurons_layer2 = 50\n", "n_categories = 10\n", "eta_vals = np.logspace(-5, 1, 7)\n", "lmbd_vals = np.logspace(-5, 1, 7)" ] }, { "cell_type": "code", "execution_count": 115, "metadata": { "collapsed": false }, "outputs": [], "source": [ "DNN_tf = np.zeros((len(eta_vals), len(lmbd_vals)), dtype=object)\n", " \n", "for i, eta in enumerate(eta_vals):\n", " for j, lmbd in enumerate(lmbd_vals):\n", " DNN = NeuralNetworkTensorflow(X_train, Y_train, X_test, Y_test,\n", " n_neurons_layer1, n_neurons_layer2, n_categories,\n", " epochs=epochs, batch_size=batch_size, eta=eta, lmbd=lmbd)\n", " DNN.fit()\n", " \n", " DNN_tf[i][j] = DNN\n", " \n", " print(\"Learning rate = \", eta)\n", " print(\"Lambda = \", lmbd)\n", " print(\"Test accuracy: %.3f\" % DNN.test_accuracy)\n", " print()" ] }, { "cell_type": "code", "execution_count": 116, "metadata": { "collapsed": false }, "outputs": [], "source": [ "# optional\n", "# visual representation of grid search\n", "# uses seaborn heatmap, could probably do this in matplotlib\n", "import seaborn as sns\n", "\n", "sns.set()\n", "\n", "train_accuracy = np.zeros((len(eta_vals), len(lmbd_vals)))\n", "test_accuracy = np.zeros((len(eta_vals), len(lmbd_vals)))\n", "\n", "for i in range(len(eta_vals)):\n", " for j in range(len(lmbd_vals)):\n", " DNN = DNN_tf[i][j]\n", "\n", " train_accuracy[i][j] = DNN.train_accuracy\n", " test_accuracy[i][j] = DNN.test_accuracy\n", "\n", " \n", "fig, ax = plt.subplots(figsize = (10, 10))\n", "sns.heatmap(train_accuracy, annot=True, ax=ax, cmap=\"viridis\")\n", "ax.set_title(\"Training Accuracy\")\n", "ax.set_ylabel(\"$\\eta$\")\n", "ax.set_xlabel(\"$\\lambda$\")\n", "plt.show()\n", "\n", "fig, ax = plt.subplots(figsize = (10, 10))\n", "sns.heatmap(test_accuracy, annot=True, ax=ax, cmap=\"viridis\")\n", "ax.set_title(\"Test Accuracy\")\n", "ax.set_ylabel(\"$\\eta$\")\n", "ax.set_xlabel(\"$\\lambda$\")\n", "plt.show()" ] }, { "cell_type": "code", "execution_count": 117, "metadata": { "collapsed": false }, "outputs": [], "source": [ "# optional\n", "# we can use log files to visualize our graph in Tensorboard\n", "writer = tf.summary.FileWriter('logs/')\n", "writer.add_graph(tf.get_default_graph())" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Using Keras\n", "\n", "Keras is a high level [neural network](https://en.wikipedia.org/wiki/Application_programming_interface)\n", "that supports Tensorflow, CTNK and Theano as backends. \n", "If you have Tensorflow installed Keras is available through the *tf.keras* module. \n", "If you have Anaconda installed you may run the following command" ] }, { "cell_type": "code", "execution_count": 118, "metadata": { "collapsed": false }, "outputs": [], "source": [ "conda install keras" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Alternatively, if you have Tensorflow or one of the other supported backends install you may use the pip package manager:" ] }, { "cell_type": "code", "execution_count": 119, "metadata": { "collapsed": false }, "outputs": [], "source": [ "pip3 install keras" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "or look up the [instructions here](https://keras.io/)." ] }, { "cell_type": "code", "execution_count": 120, "metadata": { "collapsed": false }, "outputs": [], "source": [ "from keras.models import Sequential\n", "from keras.layers import Dense\n", "from keras.regularizers import l2\n", "from keras.optimizers import SGD\n", "\n", "def create_neural_network_keras(n_neurons_layer1, n_neurons_layer2, n_categories, eta, lmbd):\n", " model = Sequential()\n", " model.add(Dense(n_neurons_layer1, activation='sigmoid', kernel_regularizer=l2(lmbd)))\n", " model.add(Dense(n_neurons_layer2, activation='sigmoid', kernel_regularizer=l2(lmbd)))\n", " model.add(Dense(n_categories, activation='softmax'))\n", " \n", " sgd = SGD(lr=eta)\n", " model.compile(loss='categorical_crossentropy', optimizer=sgd, metrics=['accuracy'])\n", " \n", " return model" ] }, { "cell_type": "code", "execution_count": 121, "metadata": { "collapsed": false }, "outputs": [], "source": [ "DNN_keras = np.zeros((len(eta_vals), len(lmbd_vals)), dtype=object)\n", " \n", "for i, eta in enumerate(eta_vals):\n", " for j, lmbd in enumerate(lmbd_vals):\n", " DNN = create_neural_network_keras(n_neurons_layer1, n_neurons_layer2, n_categories,\n", " eta=eta, lmbd=lmbd)\n", " DNN.fit(X_train, Y_train, epochs=epochs, batch_size=batch_size, verbose=0)\n", " scores = DNN.evaluate(X_test, Y_test)\n", " \n", " DNN_keras[i][j] = DNN\n", " \n", " print(\"Learning rate = \", eta)\n", " print(\"Lambda = \", lmbd)\n", " print(\"Test accuracy: %.3f\" % scores[1])\n", " print()" ] }, { "cell_type": "code", "execution_count": 122, "metadata": { "collapsed": false }, "outputs": [], "source": [ "# optional\n", "# visual representation of grid search\n", "# uses seaborn heatmap, could probably do this in matplotlib\n", "import seaborn as sns\n", "\n", "sns.set()\n", "\n", "train_accuracy = np.zeros((len(eta_vals), len(lmbd_vals)))\n", "test_accuracy = np.zeros((len(eta_vals), len(lmbd_vals)))\n", "\n", "for i in range(len(eta_vals)):\n", " for j in range(len(lmbd_vals)):\n", " DNN = DNN_keras[i][j]\n", "\n", " train_accuracy[i][j] = DNN.evaluate(X_train, Y_train)[1]\n", " test_accuracy[i][j] = DNN.evaluate(X_test, Y_test)[1]\n", "\n", " \n", "fig, ax = plt.subplots(figsize = (10, 10))\n", "sns.heatmap(train_accuracy, annot=True, ax=ax, cmap=\"viridis\")\n", "ax.set_title(\"Training Accuracy\")\n", "ax.set_ylabel(\"$\\eta$\")\n", "ax.set_xlabel(\"$\\lambda$\")\n", "plt.show()\n", "\n", "fig, ax = plt.subplots(figsize = (10, 10))\n", "sns.heatmap(test_accuracy, annot=True, ax=ax, cmap=\"viridis\")\n", "ax.set_title(\"Test Accuracy\")\n", "ax.set_ylabel(\"$\\eta$\")\n", "ax.set_xlabel(\"$\\lambda$\")\n", "plt.show()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Which activation function should I use?\n", "\n", "The Back propagation algorithm we derived above works by going from\n", "the output layer to the input layer, propagating the error gradient on\n", "the way. Once the algorithm has computed the gradient of the cost\n", "function with regards to each parameter in the network, it uses these\n", "gradients to update each parameter with a Gradient Descent (GD) step.\n", "\n", "\n", "Unfortunately for us, the gradients often get smaller and smaller as the\n", "algorithm progresses down to the first hidden layers. As a result, the\n", "GD update leaves the lower layer connection weights\n", "virtually unchanged, and training never converges to a good\n", "solution. This is known in the literature as \n", "**the vanishing gradients problem**. \n", "\n", "In other cases, the opposite can happen, namely the the gradients can grow bigger and\n", "bigger. The result is that many of the layers get large updates of the \n", "weights the\n", "algorithm diverges. This is the **exploding gradients problem**, which is\n", "mostly encountered in recurrent neural networks. More generally, deep\n", "neural networks suffer from unstable gradients, different layers may\n", "learn at widely different speeds\n", "\n", "\n", "## Is the Logistic activation function (Sigmoid) our choice?\n", "\n", "Although this unfortunate behavior has been empirically observed for\n", "quite a while (it was one of the reasons why deep neural networks were\n", "mostly abandoned for a long time), it is only around 2010 that\n", "significant progress was made in understanding it.\n", "\n", "A paper titled [Understanding the Difficulty of Training Deep\n", "Feedforward Neural Networks by Xavier Glorot and Yoshua Bengio](http://proceedings.mlr.press/v9/glorot10a.html) found that\n", "the problems with the popular logistic\n", "sigmoid activation function and the weight initialization technique\n", "that was most popular at the time, namely random initialization using\n", "a normal distribution with a mean of 0 and a standard deviation of\n", "1. \n", "\n", "They showed that with this activation function and this\n", "initialization scheme, the variance of the outputs of each layer is\n", "much greater than the variance of its inputs. Going forward in the\n", "network, the variance keeps increasing after each layer until the\n", "activation function saturates at the top layers. This is actually made\n", "worse by the fact that the logistic function has a mean of 0.5, not 0\n", "(the hyperbolic tangent function has a mean of 0 and behaves slightly\n", "better than the logistic function in deep networks).\n", "\n", "\n", "\n", "## The derivative of the Logistic funtion\n", "\n", "Looking at the logistic activation function, when inputs become large\n", "(negative or positive), the function saturates at 0 or 1, with a\n", "derivative extremely close to 0. Thus when backpropagation kicks in,\n", "it has virtually no gradient to propagate back through the network,\n", "and what little gradient exists keeps getting diluted as\n", "backpropagation progresses down through the top layers, so there is\n", "really nothing left for the lower layers.\n", "\n", "In their paper, Glorot and Bengio propose a way to significantly\n", "alleviate this problem. We need the signal to flow properly in both\n", "directions: in the forward direction when making predictions, and in\n", "the reverse direction when backpropagating gradients. We don’t want\n", "the signal to die out, nor do we want it to explode and saturate. For\n", "the signal to flow properly, the authors argue that we need the\n", "variance of the outputs of each layer to be equal to the variance of\n", "its inputs, and we also need the gradients to have equal variance\n", "before and after flowing through a layer in the reverse direction.\n", "\n", "\n", "\n", "One of the insights in the 2010 paper by Glorot and Bengio was that\n", "the vanishing/exploding gradients problems were in part due to a poor\n", "choice of activation function. Until then most people had assumed that\n", "if Nature had chosen to use roughly sigmoid activation functions in\n", "biological neurons, they must be an excellent choice. But it turns out\n", "that other activation functions behave much better in deep neural\n", "networks, in particular the ReLU activation function, mostly because\n", "it does not saturate for positive values (and also because it is quite\n", "fast to compute).\n", "\n", "\n", "\n", "## The RELU function family\n", "\n", "The ReLU activation function suffers from a problem known as the dying\n", "ReLUs: during training, some neurons effectively die, meaning they\n", "stop outputting anything other than 0.\n", "\n", "In some cases, you may find that half of your network’s neurons are\n", "dead, especially if you used a large learning rate. During training,\n", "if a neuron’s weights get updated such that the weighted sum of the\n", "neuron’s inputs is negative, it will start outputting 0. When this\n", "happen, the neuron is unlikely to come back to life since the gradient\n", "of the ReLU function is 0 when its input is negative.\n", "\n", "To solve this problem, nowadays practitioners use a variant of the ReLU\n", "function, such as the leaky ReLU discussed above or the so-called\n", "exponential linear unit (ELU) function" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "$$\n", "ELU(z) = \\left\\{\\begin{array}{cc} \\alpha\\left( \\exp{(z)}-1\\right) & z < 0,\\\\ z & z \\ge 0.\\end{array}\\right.\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Which activation function should we use?\n", "\n", "In general it seems that the ELU activation function is better than\n", "the leaky ReLU function (and its variants), which is better than\n", "ReLU. ReLU performs better than $\\tanh$ which in turn performs better\n", "than the logistic function. \n", "\n", "If runtime\n", "performance is an issue, then you may opt for the leaky ReLU function over the \n", "ELU function If you don’t\n", "want to tweak yet another hyperparameter, you may just use the default\n", "$\\alpha$ of $0.01$ for the leaky ReLU, and $1$ for ELU. If you have\n", "spare time and computing power, you can use cross-validation or\n", "bootstrap to evaluate other activation functions.\n", "\n", "\n", "\n", "## A top-down perspective on Neural networks\n", "\n", "\n", "The first thing we would like to do is divide the data into two or three\n", "parts. A training set, a validation or dev (development) set, and a\n", "test set. The test set is the data on which we want to make\n", "predictions. The dev set is a subset of the training data we use to\n", "check how well we are doing out-of-sample, after training the model on\n", "the training dataset. We use the validation error as a proxy for the\n", "test error in order to make tweaks to our model. It is crucial that we\n", "do not use any of the test data to train the algorithm. This is a\n", "cardinal sin in ML. Then:\n", "\n", "\n", "* Estimate optimal error rate\n", "\n", "* Minimize underfitting (bias) on training data set.\n", "\n", "* Make sure you are not overfitting.\n", "\n", "If the validation and test sets are drawn from the same distributions,\n", "then a good performance on the validation set should lead to similarly\n", "good performance on the test set. \n", "\n", "However, sometimes\n", "the training data and test data differ in subtle ways because, for\n", "example, they are collected using slightly different methods, or\n", "because it is cheaper to collect data in one way versus another. In\n", "this case, there can be a mismatch between the training and test\n", "data. This can lead to the neural network overfitting these small\n", "differences between the test and training sets, and a poor performance\n", "on the test set despite having a good performance on the validation\n", "set. To rectify this, Andrew Ng suggests making two validation or dev\n", "sets, one constructed from the training data and one constructed from\n", "the test data. The difference between the performance of the algorithm\n", "on these two validation sets quantifies the train-test mismatch. This\n", "can serve as another important diagnostic when using DNNs for\n", "supervised learning.\n", "\n", "\n", "## Limitations of supervised learning with deep networks\n", "\n", "Like all statistical methods, supervised learning using neural\n", "networks has important limitations. This is especially important when\n", "one seeks to apply these methods, especially to physics problems. Like\n", "all tools, DNNs are not a universal solution. Often, the same or\n", "better performance on a task can be achieved by using a few\n", "hand-engineered features (or even a collection of random\n", "features). \n", "\n", "Here we list some of the important limitations of supervised neural network based models. \n", "\n", "\n", "\n", "* **Need labeled data**. All supervised learning methods, DNNs for supervised learning require labeled data. Often, labeled data is harder to acquire than unlabeled data (e.g. one must pay for human experts to label images).\n", "\n", "* **Supervised neural networks are extremely data intensive.** DNNs are data hungry. They perform best when data is plentiful. This is doubly so for supervised methods where the data must also be labeled. The utility of DNNs is extremely limited if data is hard to acquire or the datasets are small (hundreds to a few thousand samples). In this case, the performance of other methods that utilize hand-engineered features can exceed that of DNNs.\n", "\n", "* **Homogeneous data.** Almost all DNNs deal with homogeneous data of one type. It is very hard to design architectures that mix and match data types (i.e. some continuous variables, some discrete variables, some time series). In applications beyond images, video, and language, this is often what is required. In contrast, ensemble models like random forests or gradient-boosted trees have no difficulty handling mixed data types.\n", "\n", "* **Many problems are not about prediction.** In natural science we are often interested in learning something about the underlying distribution that generates the data. In this case, it is often difficult to cast these ideas in a supervised learning setting. While the problems are related, it is possible to make good predictions with a *wrong* model. The model might or might not be useful for understanding the underlying science.\n", "\n", "Some of these remarks are particular to DNNs, others are shared by all supervised learning methods. This motivates the use of unsupervised methods which in part circumnavigate these problems.\n", "\n", "\n", "# Nearest Neighbors and Decision Trees\n", "\n", "## Decision trees, overarching aims\n", "\n", "Add text about decision trees and include about random forests (use Ising model classification)\n", "\n", "\n", "\n", "## Nearest Neighbors" ] }, { "cell_type": "code", "execution_count": 123, "metadata": { "collapsed": false }, "outputs": [], "source": [ "import mglearn\n", "import numpy as np\n", "from sklearn import linear_model\n", "from sklearn.linear_model import LinearRegression\n", "import matplotlib.pyplot as plt\n", "from sklearn.preprocessing import PolynomialFeatures\n", "from sklearn.pipeline import Pipeline\n", "from sklearn.neighbors import KNeighborsClassifier\n", "\n", "# Generate sample data\n", "X = np.sort(5*np.random.rand(40,1), axis=0)\n", "y = X**3\n", "y=y.ravel()\n", "\n", "# Add noise to targets\n", "X[::4] +=(0.5 - np.random.rand(1))\n", "y[::5] +=(0.5 - np.random.rand(8))\n", "\n", "a=np.array(X)\n", "b=np.array(y)\n", "\n", "X_train=a[:19]\n", "X_test=a[19:]\n", "y_train=b[:19]\n", "y_test=b[19:]\n", "\n", "model=Pipeline([('poly', PolynomialFeatures(degree=3)),('linear', LinearRegression(fit_intercept=False))])\n", "model=model.fit(X_train, y_train)\n", "pred=model.predict(X_test)\n", "\n", "\n", "poly=PolynomialFeatures(degree=3)\n", "poly.fit_transform(X_train, y_train)\n", "plt.scatter(X_test, y_test)\n", "plt.plot(X_test, pred, color='green')\n", "plt.show()\n", "\n", "print (model.score(X_test,y_test))\n", "\n", "print (\"---------K-Nearest Neighbors-------\")\n", "\"\"\"neighbors_settings=range(1,11)\n", "for n_neighbors in neighbors_settings:\n", " clf=KNeighborsClassifier(n_neighbors=n_neighbors)\n", " clf.fit(X_train, y_train)\n", " training_accuracy.append(clf.score(X_train, y_train))\n", " test_accuracy.append(clf.score(X_test, y_test))\n", "\n", "\n", "print (mglearn.plots.plot_knn_regression(n_neighbors=3))\"\"\"\n", "\n", "from sklearn.neighbors import KNeighborsRegressor\n", "\n", "X, y=mglearn.datasets.make_wave(n_samples=40)\n", "reg = KNeighborsRegressor(n_neighbors=3)\n", "reg.fit(X_train, y_train)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Decision trees and Regression" ] }, { "cell_type": "code", "execution_count": 124, "metadata": { "collapsed": false }, "outputs": [], "source": [ "import numpy as np\n", "import matplotlib.pyplot as plt\n", "from sklearn.preprocessing import PolynomialFeatures\n", "from sklearn.linear_model import LinearRegression\n", "\n", "steps=250\n", "\n", "distance=0\n", "x=0\n", "distance_list=[]\n", "steps_list=[]\n", "while x