{ "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: **Aug 15, 2019**\n", "\n", "Copyright 1999-2019, Morten Hjorth-Jensen. Released under CC Attribution-NonCommercial 4.0 license\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "# Introduction\n", "\n", "During the last two decades there has been a swift and amazing\n", "development of Machine Learning techniques and algorithms that impact\n", "many areas in not only Science and Technology but also the Humanities,\n", "Social Sciences, Medicine, Law, indeed, almost all possible\n", "disciplines. The applications are incredibly many, from self-driving\n", "cars to solving high-dimensional differential equations or complicated\n", "quantum mechanical many-body problems. Machine Learning is perceived\n", "by many as one of the main disruptive techniques nowadays. \n", "\n", "Statistics, Data science and Machine Learning form important\n", "fields of research in modern science. They describe how to learn and\n", "make predictions from data, as well as allowing us to extract\n", "important correlations about physical process and the underlying laws\n", "of motion in large data sets. The latter, big data sets, appear\n", "frequently in essentially all disciplines, from the traditional\n", "Science, Technology, Mathematics and Engineering fields to Life\n", "Science, Law, education research, the Humanities and the Social\n", "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 sets of 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 exercises, 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 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 \n", "statistical data analysis and its basic concepts such as expectation\n", "values, variance, covariance, correlation functions and errors, via\n", "well-known probability distribution functions like the 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 optimize (minimize) functions (the family of gradient descent methods)\n", "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, the bootstrapping\n", "and the jackknife methods and the infamous bias-variance tradeoff. \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\n", "a function of some parameters. The model reflects our knowledge of\n", "the system (or lack thereof). As an example, if we know that our data\n", "show a behavior similar to what would be predicted by a polynomial,\n", "fitting our data to a polynomial of some degree would then determin\n", "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\n", "\n", "2. Decision tree algorithms, from single trees to random forests\n", "\n", "3. Bayesian statistics and regression\n", "\n", "4. Support vector machines and finally various variants of\n", "\n", "5. Artifical neural networks and deep learning, including convolutional neural networks and Bayesian neural networks\n", "\n", "6. 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 libraries written in\n", "Python, easy to use libraries with immediate visualization(and not the\n", "least impressive galleries of existing examples), 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 easy. However,\n", "since the focus here is not only on using existing Python libraries 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 either as a Python codes or C++ or Fortran (or other languages) codes. \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", "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 fellow taxpayers 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 so 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, yes you reading these lines,\n", "who end up constructing and instructing, via various algorithms, the\n", "machine learning approaches. 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 data 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", "all carmakers have as their utmost priority the security of the\n", "driver and the accompanying passengers. A famous European 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 leads 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 encounter 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, nor will we venture into a deeper\n", "discussions of these aspects, but we want you think over these topics\n", "in a more overarching way. A statistical data analysis with its dry\n", "numbers and graphs meant to guide the eye, does 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 understanding of the ethics of science at\n", "large. Use these insights. Be a critical citizen. You owe it to our\n", "society.\n", "\n", "\n", "\n", "\n", "# Getting started with Machine Learning\n", "\n", "Our emphasis throughout this series of lectures \n", "is on understanding the mathematical aspects of\n", "different algorithms used in the fields of data analysis and machine learning. \n", "\n", "However, where possible we will emphasize the\n", "importance of using available software. We start thus with a hands-on\n", "and top-down approach to machine learning. The aim is thus to start with\n", "relevant data or data we have produced \n", "and use these to introduce statistical data analysis\n", "concepts and machine learning algorithms before we delve into the\n", "algorithms themselves. The examples we will use in the beginning, start with simple\n", "polynomials with random noise added. We will use the Python\n", "software package [Scikit-Learn](http://scikit-learn.org/stable/) and\n", "introduce various machine learning algorithms to make fits of\n", "the data and predictions. We move thereafter to more interesting\n", "cases such as data from say experiments (below we will look at experimental nuclear binding energies as an example).\n", "These are examples where we can easily set up the data and\n", "then use machine learning algorithms included in for example\n", "**Scikit-Learn**. \n", "\n", "These examples will serve us the purpose of getting\n", "started. Furthermore, they allow us to catch more than two birds with\n", "a stone. They will allow us to bring in some programming specific\n", "topics and tools as well as showing the power of various Python \n", "libraries for machine learning and statistical data analysis. \n", "\n", "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", "## What is Machine Learning?\n", "\n", "Statistics, data science and machine learning form important fields of\n", "research in modern science. They describe how to learn and make\n", "predictions from data, as well as allowing us to extract important\n", "correlations about physical process and the underlying laws of motion\n", "in large data sets. The latter, big data sets, appear frequently in\n", "essentially all disciplines, from the traditional Science, Technology,\n", "Mathematics and Engineering fields to Life Science, Law, education\n", "research, the Humanities and the Social Sciences. \n", "\n", "It has become more\n", "and more common to see research projects on big data in for example\n", "the Social Sciences where extracting patterns from complicated survey\n", "data is one of many research directions. Having a solid grasp of data\n", "analysis and machine learning is thus becoming central to scientific\n", "computing in many fields, and competences and skills within the fields\n", "of machine learning and scientific computing are nowadays strongly\n", "requested by many potential employers. The latter cannot be\n", "overstated, familiarity with machine learning has almost become a\n", "prerequisite for many of the most exciting employment opportunities,\n", "whether they are in bioinformatics, life science, physics or finance,\n", "in the private or the public sector. This author has had several\n", "students or met students who have been hired recently based on their\n", "skills and competences in scientific computing and data science, often\n", "with marginal knowledge of machine learning.\n", "\n", "Machine learning is a subfield of computer science, and is closely\n", "related to computational statistics. It evolved from the study of\n", "pattern recognition in artificial intelligence (AI) research, and has\n", "made contributions to AI tasks like computer vision, natural language\n", "processing and speech recognition. Many of the methods we will study are also \n", "strongly rooted in basic mathematics and physics research. \n", "\n", "Ideally, machine learning represents the science of giving computers\n", "the ability to learn without being explicitly programmed. The idea is\n", "that there exist generic algorithms which can be used to find patterns\n", "in a broad class of data sets without having to write code\n", "specifically for each problem. The algorithm will build its own logic\n", "based on the data. You should however always keep in mind that\n", "machines and algorithms are to a large extent developed by humans. The\n", "insights and knowledge we have about a specific system, play a central\n", "role when we develop a specific machine learning algorithm. \n", "\n", "Machine learning is an extremely rich field, in spite of its young\n", "age. The increases we have seen during the last three decades in\n", "computational capabilities have been followed by developments of\n", "methods and techniques for analyzing and handling large date sets,\n", "relying heavily on statistics, computer science and mathematics. The\n", "field is rather new and developing rapidly. Popular software packages\n", "written in Python for machine learning like\n", "[Scikit-learn](http://scikit-learn.org/stable/),\n", "[Tensorflow](https://www.tensorflow.org/),\n", "[PyTorch](http://pytorch.org/) and [Keras](https://keras.io/), all\n", "freely available at their respective GitHub sites, encompass\n", "communities of developers in the thousands or more. And the number of\n", "code developers and contributors keeps increasing. Not all the\n", "algorithms and methods can be given a rigorous mathematical\n", "justification, opening up thereby large rooms for experimenting and\n", "trial and error and thereby exciting new developments. However, a\n", "solid command of linear algebra, multivariate theory, probability\n", "theory, statistical data analysis, understanding errors and Monte\n", "Carlo methods are central elements in a proper understanding of many\n", "of algorithms and methods we will discuss.\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", "At the heart of basically all ML algorithms there are so-called minimization algorithms, often we end up with various variants of **gradient** methods.\n", "\n", "\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", "Jupyter notebooks invaluable in your work. You can run **R**\n", "codes in the Jupyter/IPython notebooks, with the immediate benefit of\n", "visualizing your data. You can also use compiled languages like C++,\n", "Rust, Julia, Fortran etc if you prefer. The focus in these lectures will be\n", "on Python.\n", "\n", "\n", "If you have Python installed (we strongly recommend Python3) and you feel\n", "pretty familiar with installing different packages, we recommend that\n", "you install the following Python packages via **pip** as \n", "\n", "1. pip install numpy scipy matplotlib ipython scikit-learn mglearn sympy pandas pillow \n", "\n", "For Python3, replace **pip** with **pip3**.\n", "\n", "For OSX users we recommend, after having installed Xcode, to\n", "install **brew**. Brew allows for a seamless installation of additional\n", "software via for example \n", "\n", "1. brew install python3\n", "\n", "For Linux users, with its variety of distributions like for example the widely popular Ubuntu distribution,\n", "you can use **pip** as well and simply install Python as \n", "\n", "1. sudo apt-get install python3 (or python for pyhton2.7)\n", "\n", "etc etc. \n", "\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", "Furthermore, [Google's Colab](https://colab.research.google.com/notebooks/welcome.ipynb) is a free Jupyter notebook environment that requires \n", "no setup and runs entirely in the cloud. Try it out!\n", "\n", "## Useful Python libraries\n", "Here we list several useful Python libraries we strongly recommend (if you use anaconda many of these are already there)\n", "\n", "* [NumPy](https://www.numpy.org/) is a highly popular library for large, multi-dimensional arrays and matrices, along with a large collection of high-level mathematical functions to operate on these arrays\n", "\n", "* [The pandas](https://pandas.pydata.org/) library provides high-performance, easy-to-use data structures and data analysis tools \n", "\n", "* [Xarray](http://xarray.pydata.org/en/stable/) is a Python package that makes working with labelled multi-dimensional arrays simple, efficient, and fun!\n", "\n", "* [Scipy](https://www.scipy.org/) (pronounced “Sigh Pie”) is a Python-based ecosystem of open-source software for mathematics, science, and engineering. \n", "\n", "* [Matplotlib](https://matplotlib.org/) is a Python 2D plotting library which produces publication quality figures in a variety of hardcopy formats and interactive environments across platforms.\n", "\n", "* [Autograd](https://github.com/HIPS/autograd) can automatically differentiate native Python and Numpy code. It can handle a large subset of Python's features, including loops, ifs, recursion and closures, and it can even take derivatives of derivatives of derivatives\n", "\n", "* [SymPy](https://www.sympy.org/en/index.html) is a Python library for symbolic mathematics. \n", "\n", "* [scikit-learn](https://scikit-learn.org/stable/) has simple and efficient tools for machine learning, data mining and data analysis\n", "\n", "* [TensorFlow](https://www.tensorflow.org/) is a Python library for fast numerical computing created and released by Google\n", "\n", "* [Keras](https://keras.io/) is a high-level neural networks API, written in Python and capable of running on top of TensorFlow, CNTK, or Theano\n", "\n", "* And many more such as [pytorch](https://pytorch.org/), [Theano](https://pypi.org/project/Theano/) etc \n", "\n", "## Installing R, C++, cython or Julia\n", "\n", "You will also find it convenient to utilize **R**. We will mainly\n", "use Python during our lectures and in various projects and exercises.\n", "Those of you\n", "already familiar with **R** should feel free to continue using **R**, keeping\n", "however an eye on the parallel Python set ups. Similarly, if you are a\n", "Python afecionado, feel free to explore **R** as well. Jupyter/Ipython\n", "notebook allows you to run **R** codes interactively in your\n", "browser. The software library **R** is really tailored for statistical data analysis\n", "and allows for an easy usage of the tools and algorithms we will discuss in these\n", "lectures.\n", "\n", "To install **R** with Jupyter notebook \n", "[follow the link here](https://mpacer.org/maths/r-kernel-for-ipython-notebook)\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 notebook\n", "setup allows you to integrate widely popular softwares and tools for\n", "scientific computing. Similarly, the \n", "[Numba Python package](https://numba.pydata.org/) delivers increased performance\n", "capabilities with minimal rewrites of your codes. With its\n", "versatility, including symbolic operations, Python offers a unique\n", "computational environment. Your jupyter notebook can easily be\n", "converted into a nicely rendered **PDF** file or a Latex file for\n", "further processing. For example, convert to latex as" ] }, { "cell_type": "markdown", "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. These lectures were generated using **doconce**.\n", "\n", "\n", "\n", "## Numpy examples and Important Matrix and vector handling packages\n", "\n", "There are several central software libraries for linear algebra and eigenvalue problems. Several of the more\n", "popular ones have been wrapped into ofter software packages like those from the widely used text **Numerical Recipes**. The original source codes in many of the available packages are often taken from the widely used\n", "software package LAPACK, which follows two other popular packages\n", "developed in the 1970s, namely EISPACK and LINPACK. We describe them shortly here.\n", "\n", " * LINPACK: package for linear equations and least square problems.\n", "\n", " * LAPACK:package for solving symmetric, unsymmetric and generalized eigenvalue problems. From LAPACK's website it is possible to download for free all source codes from this library. Both C/C++ and Fortran versions are available.\n", "\n", " * BLAS (I, II and III): (Basic Linear Algebra Subprograms) are routines that provide standard building blocks for performing basic vector and matrix operations. Blas I is vector operations, II vector-matrix operations and III matrix-matrix operations. Highly parallelized and efficient codes, all available for download from .\n", "\n", "## Basic Matrix Features" ] }, { "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": [ "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": [ "\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", "\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", "### More 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": 1, "metadata": {}, "outputs": [], "source": [ "import numpy as np" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Here follows a simple example where we set up an array of ten elements, all determined by random numbers drawn according to the normal distribution," ] }, { "cell_type": "code", "execution_count": 2, "metadata": {}, "outputs": [], "source": [ "n = 10\n", "x = np.random.normal(size=n)\n", "print(x)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "We defined a vector $x$ with $n=10$ elements with its values given by the Normal distribution $N(0,1)$.\n", "Another alternative is to declare a vector as follows" ] }, { "cell_type": "code", "execution_count": 3, "metadata": {}, "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": 4, "metadata": {}, "outputs": [], "source": [ "import numpy as np\n", "x = np.log(np.array([4, 7, 8]))\n", "print(x)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "In the last example we used Numpy's unary function $np.log$. This function is\n", "highly tuned to compute array elements since the code is vectorized\n", "and does not require looping. We normaly recommend that you use the\n", "Numpy intrinsic functions instead of the corresponding **log** function\n", "from Python's **math** module. The looping is done explicitely by the\n", "**np.log** function. The alternative, and slower way to compute the\n", "logarithms of a vector would be to write" ] }, { "cell_type": "code", "execution_count": 5, "metadata": {}, "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 automagically our numbers as integers (like the **automatic** keyword in C++). To change this we could define our array elements to be double precision numbers as" ] }, { "cell_type": "code", "execution_count": 6, "metadata": {}, "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": 7, "metadata": {}, "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": 8, "metadata": {}, "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", "\n", "Having defined vectors, we are now ready to try out matrices. We can\n", "define a $3 \\times 3 $ real matrix $\\hat{A}$ as (recall that we user\n", "lowercase letters for vectors and uppercase letters for matrices)" ] }, { "cell_type": "code", "execution_count": 9, "metadata": {}, "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": 10, "metadata": {}, "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": 11, "metadata": {}, "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": 12, "metadata": {}, "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": 13, "metadata": {}, "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": 14, "metadata": {}, "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. \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()**. We note that we can also 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": 15, "metadata": {}, "outputs": [], "source": [ "# Importing various packages\n", "import numpy as np\n", "\n", "n = 100\n", "x = np.random.normal(size=n)\n", "print(np.mean(x))\n", "y = 4+3*x+np.random.normal(size=n)\n", "print(np.mean(y))\n", "z = x**3+np.random.normal(size=n)\n", "print(np.mean(z))\n", "W = np.vstack((x, y, z))\n", "Sigma = np.cov(W)\n", "print(Sigma)\n", "Eigvals, Eigvecs = np.linalg.eig(Sigma)\n", "print(Eigvals)" ] }, { "cell_type": "code", "execution_count": 16, "metadata": {}, "outputs": [], "source": [ "%matplotlib inline\n", "\n", "import numpy as np\n", "import matplotlib.pyplot as plt\n", "from scipy import sparse\n", "eye = np.eye(4)\n", "print(eye)\n", "sparse_mtx = sparse.csr_matrix(eye)\n", "print(sparse_mtx)\n", "x = np.linspace(-10,10,100)\n", "y = np.sin(x)\n", "plt.plot(x,y,marker='x')\n", "plt.show()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Meet the Pandas\n", "\n", "\n", "\n", "\n", "\n", "

\n", "\n", "\n", "\n", "\n", "\n", "Another useful Python package is\n", "[pandas](https://pandas.pydata.org/), which is an open source library\n", "providing high-performance, easy-to-use data structures and data\n", "analysis tools for Python. **pandas** stands for panel data, a term borrowed from econometrics and is an efficient library for data analysis with an emphasis on tabular data.\n", "**pandas** has two major classes, the **DataFrame** class with two-dimensional data objects and tabular data organized in columns and the class **Series** with a focus on one-dimensional data objects. Both classes allow you to index data easily as we will see in the examples below. \n", "**pandas** allows you also to perform mathematical operations on the data, spanning from simple reshapings of vectors and matrices to statistical operations. \n", "\n", "The following simple example shows how we can, in an easy way make tables of our data. Here we define a data set which includes names, place of birth and date of birth, and displays the data in an easy to read way. We will see repeated use of **pandas**, in particular in connection with classification of data." ] }, { "cell_type": "code", "execution_count": 17, "metadata": {}, "outputs": [], "source": [ "import pandas as pd\n", "from IPython.display import display\n", "data = {'First Name': [\"Frodo\", \"Bilbo\", \"Aragorn II\", \"Samwise\"],\n", " 'Last Name': [\"Baggins\", \"Baggins\",\"Elessar\",\"Gamgee\"],\n", " 'Place of birth': [\"Shire\", \"Shire\", \"Eriador\", \"Shire\"],\n", " 'Date of Birth T.A.': [2968, 2890, 2931, 2980]\n", " }\n", "data_pandas = pd.DataFrame(data)\n", "display(data_pandas)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "In the above we have imported **pandas** with the shorthand **pd**, the latter has become the standard way we import **pandas**. We make then a list of various variables\n", "and reorganize the aboves lists into a **DataFrame** and then print out a neat table with specific column labels as *Name*, *place of birth* and *date of birth*.\n", "Displaying these results, we see that the indices are given by the default numbers from zero to three.\n", "**pandas** is extremely flexible and we can easily change the above indices by defining a new type of indexing as" ] }, { "cell_type": "code", "execution_count": 18, "metadata": {}, "outputs": [], "source": [ "data_pandas = pd.DataFrame(data,index=['Frodo','Bilbo','Aragorn','Sam'])\n", "display(data_pandas)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Thereafter we display the content of the row which begins with the index **Aragorn**" ] }, { "cell_type": "code", "execution_count": 19, "metadata": {}, "outputs": [], "source": [ "display(data_pandas.loc['Aragorn'])" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "We can easily append data to this, for example" ] }, { "cell_type": "code", "execution_count": 20, "metadata": {}, "outputs": [], "source": [ "new_hobbit = {'First Name': [\"Peregrin\"],\n", " 'Last Name': [\"Took\"],\n", " 'Place of birth': [\"Shire\"],\n", " 'Date of Birth T.A.': [2990]\n", " }\n", "data_pandas=data_pandas.append(pd.DataFrame(new_hobbit, index=['Pippin']))\n", "display(data_pandas)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Here are other examples where we use the **DataFrame** functionality to handle arrays, now with more interesting features for us, namely numbers. We set up a matrix \n", "of dimensionality $10\\times 5$ and compute the mean value and standard deviation of each column. Similarly, we can perform mathematial operations like squaring the matrix elements and many other operations." ] }, { "cell_type": "code", "execution_count": 21, "metadata": {}, "outputs": [], "source": [ "import numpy as np\n", "import pandas as pd\n", "from IPython.display import display\n", "np.random.seed(100)\n", "# setting up a 10 x 5 matrix\n", "rows = 10\n", "cols = 5\n", "a = np.random.randn(rows,cols)\n", "df = pd.DataFrame(a)\n", "display(df)\n", "print(df.mean())\n", "print(df.std())\n", "display(df**2)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Thereafter we can select specific columns only and plot final results" ] }, { "cell_type": "code", "execution_count": 22, "metadata": {}, "outputs": [], "source": [ "df.columns = ['First', 'Second', 'Third', 'Fourth', 'Fifth']\n", "df.index = np.arange(10)\n", "\n", "display(df)\n", "print(df['Second'].mean() )\n", "print(df.info())\n", "print(df.describe())\n", "\n", "from pylab import plt, mpl\n", "plt.style.use('seaborn')\n", "mpl.rcParams['font.family'] = 'serif'\n", "\n", "df.cumsum().plot(lw=2.0, figsize=(10,6))\n", "plt.show()\n", "\n", "\n", "df.plot.bar(figsize=(10,6), rot=15)\n", "plt.show()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "We can produce a $4\\times 4$ matrix" ] }, { "cell_type": "code", "execution_count": 23, "metadata": {}, "outputs": [], "source": [ "b = np.arange(16).reshape((4,4))\n", "print(b)\n", "df1 = pd.DataFrame(b)\n", "print(df1)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "and many other operations. \n", "\n", "The **Series** class is another important class included in\n", "**pandas**. You can view it as a specialization of **DataFrame** but where\n", "we have just a single column of data. It shares many of the same features as _DataFrame. As with **DataFrame**,\n", "most operations are vectorized, achieving thereby a high performance when dealing with computations of arrays, in particular labeled arrays.\n", "As we will see below it leads also to a very concice code close to the mathematical operations we may be interested in.\n", "For multidimensional arrays, we recommend strongly [xarray](http://xarray.pydata.org/en/stable/). **xarray** has much of the same flexibility as **pandas**, but allows for the extension to higher dimensions than two. We will see examples later of the usage of both **pandas** and **xarray**. \n", "\n", "\n", "\n", "## Reading Data and fitting\n", "\n", "In order to study various Machine Learning algorithms, we need to\n", "access data. Acccessing data is an essential step in all machine\n", "learning algorithms. In particular, setting up the so-called **design\n", "matrix** (to be defined below) is often the first element we need in\n", "order to perform our calculations. To set up the design matrix means\n", "reading (and later, when the calculations are done, writing) data\n", "in various formats, The formats span from reading files from disk,\n", "loading data from databases and interacting with online sources\n", "like web application programming interfaces (APIs).\n", "\n", "In handling various input formats, as discussed above, we will mainly stay with **pandas**,\n", "a Python package which allows us, in a seamless and painless way, to\n", "deal with a multitude of formats, from standard **csv** (comma separated\n", "values) files, via **excel**, **html** to **hdf5** formats. With **pandas**\n", "and the **DataFrame** and **Series** functionalities we are able to convert text data\n", "into the calculational formats we need for a specific algorithm. And our code is going to be \n", "pretty close the basic mathematical expressions.\n", "\n", "Our first data set is going to be a classic from nuclear physics, namely all\n", "available data on binding energies. Don't be intimidated if you are not familiar with nuclear physics. It serves simply as an example here of a data set. \n", "\n", "We will show some of the\n", "strengths of packages like **Scikit-Learn** in fitting nuclear binding energies to\n", "specific functions using linear regression first. Then, as a teaser, we will show you how \n", "you can easily implement other algorithms like decision trees and random forests and neural networks.\n", "\n", "But before we really start with nuclear physics data, let's just look at some simpler polynomial fitting cases, such as,\n", "(don't be offended) fitting straight lines!\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", "\n", "What follows is a simple Python code where we have defined a function\n", "$y$ in terms of the variable $x$. Both are defined as vectors with $100$ entries. \n", "The numbers in the vector $\\hat{x}$ are given\n", "by random numbers generated with a uniform distribution with entries\n", "$x_i \\in [0,1]$ (more about probability distribution functions\n", "later). These values are then used to define a function $y(x)$\n", "(tabulated again as a vector) with a linear dependence on $x$ plus a\n", "random noise added via the normal distribution.\n", "\n", "\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": 24, "metadata": {}, "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": [ "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 noise given by the normal distribution we see immediately that\n", "our linear prediction seemingly reproduces better the training\n", "set. However, this testing 'by the eye' is obviouly not satisfactory in the\n", "long run. Here we have only defined the training data and our model, and \n", "have not discussed a more rigorous approach to the **cost** function.\n", "\n", "We need more rigorous criteria in defining whether we have succeeded or\n", "not in modeling our training data. You will be surprised to see that\n", "many scientists seldomly venture beyond this 'by the eye' approach. A\n", "standard approach for the *cost* function is the so-called $\\chi^2$\n", "function (a variant of the mean-squared error (MSE))" ] }, { "cell_type": "markdown", "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 (why would we prefer the MSE instead of 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": 25, "metadata": {}, "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": 26, "metadata": {}, "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 taht we will meet again in our discussions of regression analysis is \n", " the mean absolute error (MAE), a risk metric corresponding to the expected value of the absolute error loss or what we call the $l1$-norm loss. In our discussion above we presented the relative error.\n", "The MAE is defined as follows" ] }, { "cell_type": "markdown", "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": 27, "metadata": {}, "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": [ "### To our real data: nuclear binding energies. Brief reminder on masses and binding energies\n", "\n", "Let us now dive into nuclear physics and remind ourselves briefly about some basic features about binding\n", "energies. A basic quantity which can be measured for the ground\n", "states of nuclei is the atomic mass $M(N, Z)$ of the neutral atom with\n", "atomic mass number $A$ and charge $Z$. The number of neutrons is $N$. There are indeed several sophisticated experiments worldwide which allow us to measure this quantity to high precision (parts per million even). \n", "\n", "Atomic masses are usually tabulated in terms of the mass excess defined by" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "$$\n", "\\Delta M(N, Z) = M(N, Z) - uA,\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "where $u$ is the Atomic Mass Unit" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "$$\n", "u = M(^{12}\\mathrm{C})/12 = 931.4940954(57) \\hspace{0.1cm} \\mathrm{MeV}/c^2.\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "The nucleon masses are" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "$$\n", "m_p = 1.00727646693(9)u,\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "and" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "$$\n", "m_n = 939.56536(8)\\hspace{0.1cm} \\mathrm{MeV}/c^2 = 1.0086649156(6)u.\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "In the [2016 mass evaluation of by W.J.Huang, G.Audi, M.Wang, F.G.Kondev, S.Naimi and X.Xu](http://nuclearmasses.org/resources_folder/Wang_2017_Chinese_Phys_C_41_030003.pdf)\n", "there are data on masses and decays of 3437 nuclei.\n", "\n", "The nuclear binding energy is defined as the energy required to break\n", "up a given nucleus into its constituent parts of $N$ neutrons and $Z$\n", "protons. In terms of the atomic masses $M(N, Z)$ the binding energy is\n", "defined by" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "$$\n", "BE(N, Z) = ZM_H c^2 + Nm_n c^2 - M(N, Z)c^2 ,\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "where $M_H$ is the mass of the hydrogen atom and $m_n$ is the mass of the neutron.\n", "In terms of the mass excess the binding energy is given by" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "$$\n", "BE(N, Z) = Z\\Delta_H c^2 + N\\Delta_n c^2 -\\Delta(N, Z)c^2 ,\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "where $\\Delta_H c^2 = 7.2890$ MeV and $\\Delta_n c^2 = 8.0713$ MeV.\n", "\n", "\n", "A popular and physically intuitive model which can be used to parametrize \n", "the experimental binding energies as function of $A$, is the so-called \n", "**liquid drop model**. The ansatz is based on the following expression" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "$$\n", "BE(N,Z) = a_1A-a_2A^{2/3}-a_3\\frac{Z^2}{A^{1/3}}-a_4\\frac{(N-Z)^2}{A},\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "where $A$ stands for the number of nucleons and the $a_i$s are parameters which are determined by a fit \n", "to the experimental data. \n", "\n", "\n", "\n", "\n", "To arrive at the above expression we have assumed that we can make the following assumptions:\n", "\n", " * There is a volume term $a_1A$ proportional with the number of nucleons (the energy is also an extensive quantity). When an assembly of nucleons of the same size is packed together into the smallest volume, each interior nucleon has a certain number of other nucleons in contact with it. This contribution is proportional to the volume.\n", "\n", " * There is a surface energy term $a_2A^{2/3}$. The assumption here is that a nucleon at the surface of a nucleus interacts with fewer other nucleons than one in the interior of the nucleus and hence its binding energy is less. This surface energy term takes that into account and is therefore negative and is proportional to the surface area.\n", "\n", " * There is a Coulomb energy term $a_3\\frac{Z^2}{A^{1/3}}$. The electric repulsion between each pair of protons in a nucleus yields less binding. \n", "\n", " * There is an asymmetry term $a_4\\frac{(N-Z)^2}{A}$. This term is associated with the Pauli exclusion principle and reflects the fact that the proton-neutron interaction is more attractive on the average than the neutron-neutron and proton-proton interactions.\n", "\n", "We could also add a so-called pairing term, which is a correction term that\n", "arises from the tendency of proton pairs and neutron pairs to\n", "occur. An even number of particles is more stable than an odd number. \n", "\n", "\n", "### Organizing our data\n", "\n", "Let us start with reading and organizing our data. \n", "We start with the compilation of masses and binding energies from 2016.\n", "After having downloaded this file to our own computer, we are now ready to read the file and start structuring our data.\n", "\n", "\n", "We start with preparing folders for storing our calculations and the data file over masses and binding energies. We import also various modules that we will find useful in order to present various Machine Learning methods. Here we focus mainly on the functionality of **scikit-learn**." ] }, { "cell_type": "code", "execution_count": 28, "metadata": {}, "outputs": [], "source": [ "# Common imports\n", "import numpy as np\n", "import pandas as pd\n", "import matplotlib.pyplot as plt\n", "import sklearn.linear_model as skl\n", "from sklearn.model_selection import train_test_split\n", "from sklearn.metrics import mean_squared_error, r2_score, mean_absolute_error\n", "import os\n", "\n", "# Where to save the figures and data files\n", "PROJECT_ROOT_DIR = \"Results\"\n", "FIGURE_ID = \"Results/FigureFiles\"\n", "DATA_ID = \"DataFiles/\"\n", "\n", "if not os.path.exists(PROJECT_ROOT_DIR):\n", " os.mkdir(PROJECT_ROOT_DIR)\n", "\n", "if not os.path.exists(FIGURE_ID):\n", " os.makedirs(FIGURE_ID)\n", "\n", "if not os.path.exists(DATA_ID):\n", " os.makedirs(DATA_ID)\n", "\n", "def image_path(fig_id):\n", " return os.path.join(FIGURE_ID, fig_id)\n", "\n", "def data_path(dat_id):\n", " return os.path.join(DATA_ID, dat_id)\n", "\n", "def save_fig(fig_id):\n", " plt.savefig(image_path(fig_id) + \".png\", format='png')\n", "\n", "infile = open(data_path(\"MassEval2016.dat\"),'r')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Before we proceed, we define also a function for making our plots. You can obviously avoid this and simply set up various **matplotlib** commands every time you need them. You may however find it convenient to collect all such commands in one function and simply call this function." ] }, { "cell_type": "code", "execution_count": 29, "metadata": {}, "outputs": [], "source": [ "from pylab import plt, mpl\n", "plt.style.use('seaborn')\n", "mpl.rcParams['font.family'] = 'serif'\n", "\n", "def MakePlot(x,y, styles, labels, axlabels):\n", " plt.figure(figsize=(10,6))\n", " for i in range(len(x)):\n", " plt.plot(x[i], y[i], styles[i], label = labels[i])\n", " plt.xlabel(axlabels[0])\n", " plt.ylabel(axlabels[1])\n", " plt.legend(loc=0)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Our next step is to read the data on experimental binding energies and\n", "reorganize them as functions of the mass number $A$, the number of\n", "protons $Z$ and neutrons $N$ using **pandas**. Before we do this it is\n", "always useful (unless you have a binary file or other types of compressed\n", "data) to actually open the file and simply take a look at it!\n", "\n", "\n", "In particular, the program that outputs the final nuclear masses is written in Fortran with a specific format. It means that we need to figure out the format and which columns contain the data we are interested in. Pandas comes with a function that reads formatted output. After having admired the file, we are now ready to start massaging it with **pandas**. The file begins with some basic format information." ] }, { "cell_type": "code", "execution_count": 30, "metadata": {}, "outputs": [], "source": [ "\"\"\" \n", "This is taken from the data file of the mass 2016 evaluation. \n", "All files are 3436 lines long with 124 character per line. \n", " Headers are 39 lines long. \n", " col 1 : Fortran character control: 1 = page feed 0 = line feed \n", " format : a1,i3,i5,i5,i5,1x,a3,a4,1x,f13.5,f11.5,f11.3,f9.3,1x,a2,f11.3,f9.3,1x,i3,1x,f12.5,f11.5 \n", " These formats are reflected in the pandas widths variable below, see the statement \n", " widths=(1,3,5,5,5,1,3,4,1,13,11,11,9,1,2,11,9,1,3,1,12,11,1), \n", " Pandas has also a variable header, with length 39 in this case. \n", "\"\"\"" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "The data we are interested in are in columns 2, 3, 4 and 11, giving us\n", "the number of neutrons, protons, mass numbers and binding energies,\n", "respectively. We add also for the sake of completeness the element name. The data are in fixed-width formatted lines and we will\n", "covert them into the **pandas** DataFrame structure." ] }, { "cell_type": "code", "execution_count": 31, "metadata": {}, "outputs": [], "source": [ "# Read the experimental data with Pandas\n", "Masses = pd.read_fwf(infile, usecols=(2,3,4,6,11),\n", " names=('N', 'Z', 'A', 'Element', 'Ebinding'),\n", " widths=(1,3,5,5,5,1,3,4,1,13,11,11,9,1,2,11,9,1,3,1,12,11,1),\n", " header=39,\n", " index_col=False)\n", "\n", "# Extrapolated values are indicated by '#' in place of the decimal place, so\n", "# the Ebinding column won't be numeric. Coerce to float and drop these entries.\n", "Masses['Ebinding'] = pd.to_numeric(Masses['Ebinding'], errors='coerce')\n", "Masses = Masses.dropna()\n", "# Convert from keV to MeV.\n", "Masses['Ebinding'] /= 1000\n", "\n", "# Group the DataFrame by nucleon number, A.\n", "Masses = Masses.groupby('A')\n", "# Find the rows of the grouped DataFrame with the maximum binding energy.\n", "Masses = Masses.apply(lambda t: t[t.Ebinding==t.Ebinding.max()])" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "We have now read in the data, grouped them according to the variables we are interested in. \n", "We see how easy it is to reorganize the data using **pandas**. If we\n", "were to do these operations in C/C++ or Fortran, we would have had to\n", "write various functions/subroutines which perform the above\n", "reorganizations for us. Having reorganized the data, we can now start\n", "to make some simple fits using both the functionalities in **numpy** and\n", "**Scikit-Learn** afterwards. \n", "\n", "Now we define five variables which contain\n", "the number of nucleons $A$, the number of protons $Z$ and the number of neutrons $N$, the element name and finally the energies themselves." ] }, { "cell_type": "code", "execution_count": 32, "metadata": {}, "outputs": [], "source": [ "A = Masses['A']\n", "Z = Masses['Z']\n", "N = Masses['N']\n", "Element = Masses['Element']\n", "Energies = Masses['Ebinding']\n", "print(Masses)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "The next step, and we will define this mathematically later, is to set up the so-called **design matrix**. We will throughout call this matrix $\\boldsymbol{X}$.\n", "It has dimensionality $p\\times n$, where $n$ is the number of data points and $p$ are the so-called predictors. In our case here they are given by the number of polynomials in $A$ we wish to include in the fit." ] }, { "cell_type": "code", "execution_count": 33, "metadata": {}, "outputs": [], "source": [ "# Now we set up the design matrix X\n", "X = np.zeros((len(A),5))\n", "X[:,0] = 1\n", "X[:,1] = A\n", "X[:,2] = A**(2.0/3.0)\n", "X[:,3] = A**(-1.0/3.0)\n", "X[:,4] = A**(-1.0)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "With **scikitlearn** we are now ready to use linear regression and fit our data." ] }, { "cell_type": "code", "execution_count": 34, "metadata": {}, "outputs": [], "source": [ "clf = skl.LinearRegression().fit(X, Energies)\n", "fity = clf.predict(X)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Pretty simple! \n", "Now we can print measures of how our fit is doing, the coefficients from the fits and plot the final fit together with our data." ] }, { "cell_type": "code", "execution_count": 35, "metadata": {}, "outputs": [], "source": [ "# The mean squared error \n", "print(\"Mean squared error: %.2f\" % mean_squared_error(Energies, fity))\n", "# Explained variance score: 1 is perfect prediction \n", "print('Variance score: %.2f' % r2_score(Energies, fity))\n", "# Mean absolute error \n", "print('Mean absolute error: %.2f' % mean_absolute_error(Energies, fity))\n", "print(clf.coef_, clf.intercept_)\n", "\n", "Masses['Eapprox'] = fity\n", "# Generate a plot comparing the experimental with the fitted values values.\n", "fig, ax = plt.subplots()\n", "ax.set_xlabel(r'$A = N + Z$')\n", "ax.set_ylabel(r'$E_\\mathrm{bind}\\,/\\mathrm{MeV}$')\n", "ax.plot(Masses['A'], Masses['Ebinding'], alpha=0.7, lw=2,\n", " label='Ame2016')\n", "ax.plot(Masses['A'], Masses['Eapprox'], alpha=0.7, lw=2, c='m',\n", " label='Fit')\n", "ax.legend()\n", "save_fig(\"Masses2016\")\n", "plt.show()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Seeing the wood for the trees\n", "\n", "As a teaser, let us now see how we can do this with decision trees using **scikit-learn**. Later we will switch to so-called **random forests**!" ] }, { "cell_type": "code", "execution_count": 36, "metadata": {}, "outputs": [], "source": [ "\n", "#Decision Tree Regression\n", "from sklearn.tree import DecisionTreeRegressor\n", "regr_1=DecisionTreeRegressor(max_depth=5)\n", "regr_2=DecisionTreeRegressor(max_depth=7)\n", "regr_3=DecisionTreeRegressor(max_depth=9)\n", "regr_1.fit(X, Energies)\n", "regr_2.fit(X, Energies)\n", "regr_3.fit(X, Energies)\n", "\n", "\n", "y_1 = regr_1.predict(X)\n", "y_2 = regr_2.predict(X)\n", "y_3=regr_3.predict(X)\n", "Masses['Eapprox'] = y_3\n", "# Plot the results\n", "plt.figure()\n", "plt.plot(A, Energies, color=\"blue\", label=\"Data\", linewidth=2)\n", "plt.plot(A, y_1, color=\"red\", label=\"max_depth=5\", linewidth=2)\n", "plt.plot(A, y_2, color=\"green\", label=\"max_depth=7\", linewidth=2)\n", "plt.plot(A, y_3, color=\"m\", label=\"max_depth=9\", linewidth=2)\n", "\n", "plt.xlabel(\"$A$\")\n", "plt.ylabel(\"$E$[MeV]\")\n", "plt.title(\"Decision Tree Regression\")\n", "plt.legend()\n", "save_fig(\"Masses2016Trees\")\n", "plt.show()\n", "print(Masses)\n", "print(np.mean( (Energies-y_1)**2))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### And what about using neural networks?\n", "\n", "The **seaborn** package allows us to visualize data in an efficient way. Note that we use **scikit-learn**'s multi-layer perceptron (or feed forward neural network) \n", "functionality." ] }, { "cell_type": "code", "execution_count": 37, "metadata": {}, "outputs": [], "source": [ "from sklearn.neural_network import MLPRegressor\n", "from sklearn.metrics import accuracy_score\n", "import seaborn as sns\n", "\n", "X_train = X\n", "Y_train = Energies\n", "n_hidden_neurons = 100\n", "epochs = 100\n", "# store models for later use\n", "eta_vals = np.logspace(-5, 1, 7)\n", "lmbd_vals = np.logspace(-5, 1, 7)\n", "# store the models for later use\n", "DNN_scikit = np.zeros((len(eta_vals), len(lmbd_vals)), dtype=object)\n", "train_accuracy = np.zeros((len(eta_vals), len(lmbd_vals)))\n", "sns.set()\n", "for i, eta in enumerate(eta_vals):\n", " for j, lmbd in enumerate(lmbd_vals):\n", " dnn = MLPRegressor(hidden_layer_sizes=(n_hidden_neurons), activation='logistic',\n", " alpha=lmbd, learning_rate_init=eta, max_iter=epochs)\n", " dnn.fit(X_train, Y_train)\n", " DNN_scikit[i][j] = dnn\n", " train_accuracy[i][j] = dnn.score(X_train, Y_train)\n", "\n", "fig, ax = plt.subplots(figsize = (10, 10))\n", "sns.heatmap(train_accuracy, annot=True, ax=ax, cmap=\"viridis\")\n", "ax.set_title(\"Training Accuracy\")\n", "ax.set_ylabel(\"$\\eta$\")\n", "ax.set_xlabel(\"$\\lambda$\")\n", "plt.show()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## A first summary\n", "\n", "The aim behind these introductory words was to present to you various\n", "Python libraries and their functionalities, in particular libraries like\n", "**numpy**, **pandas**, **xarray** and **matplotlib** and other that make our life much easier\n", "in handling various data sets and visualizing data. \n", "\n", "Furthermore,\n", "**Scikit-Learn** allows us with few lines of code to implement popular\n", "Machine Learning algorithms for supervised learning. Later we will meet **Tensorflow**, a powerful library for deep learning. \n", "Now it is time to dive more into the details of various methods. We will start with linear regression and try to take a deeper look at what it entails.\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "# Why Linear Regression (aka Ordinary Least Squares and family)\n", "\n", "Fitting a continuous function with linear parameterization in terms of the parameters $\\boldsymbol{\\beta}$.\n", "* Method of choice for fitting a continuous function!\n", "\n", "* Gives an excellent introduction to central Machine Learning features with **understandable pedagogical** links to other methods like **Neural Networks**, **Support Vector Machines** etc\n", "\n", "* Analytical expression for the fitting parameters $\\boldsymbol{\\beta}$\n", "\n", "* Analytical expressions for statistical propertiers like mean values, variances, confidence intervals and more\n", "\n", "* Analytical relation with probabilistic interpretations \n", "\n", "* Easy to introduce basic concepts like bias-variance tradeoff, cross-validation, resampling and regularization techniques and many other ML topics\n", "\n", "* Easy to code! And links well with classification problems and logistic regression and neural networks\n", "\n", "* Allows for **easy** hands-on understanding of gradient descent methods\n", "\n", "* and many more features\n", "\n", "For more discussions of Ridge and Lasso regression, [Wessel van Wieringen's](https://arxiv.org/abs/1509.09169) article is highly recommended.\n", "Similarly, [Mehta et al's article](https://arxiv.org/abs/1803.08823) is also recommended.\n", "\n", "\n", "### Regression analysis, overarching aims\n", "\n", "Regression modeling deals with the description of the sampling distribution of a given random variable $y$ and how it varies as function of another variable or a set of such variables $\\boldsymbol{x} =[x_0, x_1,\\dots, x_{n-1}]^T$. \n", "The first variable is called the **dependent**, the **outcome** or the **response** variable while the set of variables $\\boldsymbol{x}$ is called the independent variable, or the predictor variable or the explanatory variable. \n", "\n", "A regression model aims at finding a likelihood function $p(\\boldsymbol{y}\\vert \\boldsymbol{x})$, that is the conditional distribution for $\\boldsymbol{y}$ with a given $\\boldsymbol{x}$. The estimation of $p(\\boldsymbol{y}\\vert \\boldsymbol{x})$ is made using a data set with \n", "* $n$ cases $i = 0, 1, 2, \\dots, n-1$ \n", "\n", "* Response (target, dependent or outcome) variable $y_i$ with $i = 0, 1, 2, \\dots, n-1$ \n", "\n", "* $p$ so-called explanatory (independent or predictor) variables $\\boldsymbol{x}_i=[x_{i0}, x_{i1}, \\dots, x_{ip-1}]$ with $i = 0, 1, 2, \\dots, n-1$ and explanatory variables running from $0$ to $p-1$. See below for more explicit examples. \n", "\n", " The goal of the regression analysis is to extract/exploit relationship between $\\boldsymbol{y}$ and $\\boldsymbol{X}$ in or to infer causal dependencies, approximations to the likelihood functions, functional relationships and to make predictions, making fits and many other things.\n", "\n", "\n", "Consider an experiment in which $p$ characteristics of $n$ samples are\n", "measured. The data from this experiment, for various explanatory variables $p$ are normally represented by a matrix \n", "$\\mathbf{X}$.\n", "\n", "The matrix $\\mathbf{X}$ is called the *design\n", "matrix*. Additional information of the samples is available in the\n", "form of $\\boldsymbol{y}$ (also as above). The variable $\\boldsymbol{y}$ is\n", "generally referred to as the *response variable*. The aim of\n", "regression analysis is to explain $\\boldsymbol{y}$ in terms of\n", "$\\boldsymbol{X}$ through a functional relationship like $y_i =\n", "f(\\mathbf{X}_{i,\\ast})$. When no prior knowledge on the form of\n", "$f(\\cdot)$ is available, it is common to assume a linear relationship\n", "between $\\boldsymbol{X}$ and $\\boldsymbol{y}$. This assumption gives rise to\n", "the *linear regression model* where $\\boldsymbol{\\beta} = [\\beta_0, \\ldots,\n", "\\beta_{p-1}]^{T}$ are the *regression parameters*. \n", "\n", "Linear regression gives us a set of analytical equations for the parameters $\\beta_j$.\n", "\n", "\n", "### Examples\n", "\n", "In order to understand the relation among the predictors $p$, the set of data $n$ and the target (outcome, output etc) $\\boldsymbol{y}$,\n", "consider the model we discussed for describing nuclear binding energies. \n", "\n", "There we assumed that we could parametrize the data using a polynomial approximation based on the liquid drop model.\n", "Assuming" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "$$\n", "BE(A) = a_0+a_1A+a_2A^{2/3}+a_3A^{-1/3}+a_4A^{-1},\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "we have five predictors, that is the intercept, the $A$ dependent term, the $A^{2/3}$ term and the $A^{-1/3}$ and $A^{-1}$ terms.\n", "This gives $p=0,1,2,3,4$. Furthermore we have $n$ entries for each predictor. It means that our design matrix is a \n", "$p\\times n$ matrix $\\boldsymbol{X}$.\n", "\n", "Here the predictors are based on a model we have made. A popular data set which is widely encountered in ML applications is the\n", "so-called [credit card default data from Taiwan](https://www.sciencedirect.com/science/article/pii/S0957417407006719?via%3Dihub). The data set contains data on $n=30000$ credit card holders with predictors like gender, marital status, age, profession, education, etc. In total there are $24$ such predictors or attributes leading to a design matrix of dimensionality $24 \\times 30000$\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 $\\boldsymbol{y}=[y_0,y_1,\\dots,y_{n-1}]$. We could think of these data as a result of an experiment or a complicated numerical experiment. These data are functions of a series of variables $\\boldsymbol{x}=[x_0,x_1,\\dots,x_{n-1}]$, that is $y_i = y(x_i)$ with $i=0,1,2,\\dots,n-1$. The variables $x_i$ could represent physical quantities like time, temperature, position etc. We assume that $y(x)$ is a smooth function. \n", "\n", "Since obtaining these data points may not be trivial, we want to use these data to fit a function which can allow us to make predictions for values of $y$ which are not in the present set. The perhaps simplest approach is to assume we can parametrize our function in terms of a polynomial of degree $n-1$ with $n$ points, that is" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "$$\n", "y=y(x) \\rightarrow y(x_i)=\\tilde{y}_i+\\epsilon_i=\\sum_{j=0}^{n-1} \\beta_j x_i^j+\\epsilon_i,\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "where $\\epsilon_i$ is the error in our approximation. \n", "\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_{n-1}x_{n-1}^{n-1}+\\epsilon_{n-1}.\\\\\n", "\\end{align*}\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Defining the vectors" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "$$\n", "\\boldsymbol{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", "\\boldsymbol{\\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", "\\boldsymbol{\\epsilon} = [\\epsilon_0,\\epsilon_1, \\epsilon_2,\\dots, \\epsilon_{n-1}]^T,\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "and the design matrix" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "$$\n", "\\boldsymbol{X}=\n", "\\begin{bmatrix} \n", "1& x_{0}^1 &x_{0}^2& \\dots & \\dots &x_{0}^{n-1}\\\\\n", "1& x_{1}^1 &x_{1}^2& \\dots & \\dots &x_{1}^{n-1}\\\\\n", "1& x_{2}^1 &x_{2}^2& \\dots & \\dots &x_{2}^{n-1}\\\\ \n", "\\dots& \\dots &\\dots& \\dots & \\dots &\\dots\\\\\n", "1& x_{n-1}^1 &x_{n-1}^2& \\dots & \\dots &x_{n-1}^{n-1}\\\\\n", "\\end{bmatrix}\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "we can rewrite our equations as" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "$$\n", "\\boldsymbol{y} = \\boldsymbol{X}\\boldsymbol{\\beta}+\\boldsymbol{\\epsilon}.\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "The above design matrix is called a [Vandermonde matrix](https://en.wikipedia.org/wiki/Vandermonde_matrix).\n", "\n", "\n", "\n", "\n", "## Generalizing the fitting procedure as a linear algebra problem\n", "\n", "We are obviously not limited to the above polynomial expansions. We\n", "could replace the various powers of $x$ with elements of Fourier\n", "series or instead of $x_i^j$ we could have $\\cos{(j x_i)}$ or $\\sin{(j\n", "x_i)}$, or time series or other orthogonal functions. For every set\n", "of values $y_i,x_i$ we can then generalize the equations to" ] }, { "cell_type": "markdown", "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_{n-1}x_{n-1,n-1}+\\epsilon_{n-1}.\\\\\n", "\\end{align*}\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "**Note that we have $p=n$ here. The matrix is symmetric. This is generally not the case!**\n", "\n", "We redefine in turn the matrix $\\boldsymbol{X}$ as" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "$$\n", "\\boldsymbol{X}=\n", "\\begin{bmatrix} \n", "x_{00}& x_{01} &x_{02}& \\dots & \\dots &x_{0,n-1}\\\\\n", "x_{10}& x_{11} &x_{12}& \\dots & \\dots &x_{1,n-1}\\\\\n", "x_{20}& x_{21} &x_{22}& \\dots & \\dots &x_{2,n-1}\\\\ \n", "\\dots& \\dots &\\dots& \\dots & \\dots &\\dots\\\\\n", "x_{n-1,0}& x_{n-1,1} &x_{n-1,2}& \\dots & \\dots &x_{n-1,n-1}\\\\\n", "\\end{bmatrix}\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "and without loss of generality we rewrite again our equations as" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "$$\n", "\\boldsymbol{y} = \\boldsymbol{X}\\boldsymbol{\\beta}+\\boldsymbol{\\epsilon}.\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "The left-hand side of this equation is kwown. Our error vector $\\boldsymbol{\\epsilon}$ and the parameter vector $\\boldsymbol{\\beta}$ are our unknow quantities. How can we obtain the optimal set of $\\beta_i$ values? \n", "\n", "We have defined the matrix $\\boldsymbol{X}$ via the equations" ] }, { "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_{n-1}x_{n-1,n-1}+\\epsilon_{n-1}.\\\\\n", "\\end{align*}\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "As we noted above, we stayed with a system with the design matrix \n", " $\\boldsymbol{X}\\in {\\mathbb{R}}^{n\\times n}$, that is we have $p=n$. For reasons to come later (algorithmic arguments) we will hereafter define \n", "our matrix as $\\boldsymbol{X}\\in {\\mathbb{R}}^{n\\times p}$, with the predictors refering to the column numbers and the entries $n$ being the row elements.\n", "\n", "\n", "## Our model for the nuclear binding energies\n", "\n", "In our introductory notes we looked at the so-called [liguid drop model](https://en.wikipedia.org/wiki/Semi-empirical_mass_formula). Let us remind ourselves about what we did by looking at the code.\n", "\n", "We restate the parts of the code we are most interested in." ] }, { "cell_type": "code", "execution_count": 38, "metadata": {}, "outputs": [], "source": [ "# Common imports\n", "import numpy as np\n", "import pandas as pd\n", "import matplotlib.pyplot as plt\n", "from IPython.display import display\n", "import os\n", "\n", "# Where to save the figures and data files\n", "PROJECT_ROOT_DIR = \"Results\"\n", "FIGURE_ID = \"Results/FigureFiles\"\n", "DATA_ID = \"DataFiles/\"\n", "\n", "if not os.path.exists(PROJECT_ROOT_DIR):\n", " os.mkdir(PROJECT_ROOT_DIR)\n", "\n", "if not os.path.exists(FIGURE_ID):\n", " os.makedirs(FIGURE_ID)\n", "\n", "if not os.path.exists(DATA_ID):\n", " os.makedirs(DATA_ID)\n", "\n", "def image_path(fig_id):\n", " return os.path.join(FIGURE_ID, fig_id)\n", "\n", "def data_path(dat_id):\n", " return os.path.join(DATA_ID, dat_id)\n", "\n", "def save_fig(fig_id):\n", " plt.savefig(image_path(fig_id) + \".png\", format='png')\n", "\n", "infile = open(data_path(\"MassEval2016.dat\"),'r')\n", "\n", "\n", "# Read the experimental data with Pandas\n", "Masses = pd.read_fwf(infile, usecols=(2,3,4,6,11),\n", " names=('N', 'Z', 'A', 'Element', 'Ebinding'),\n", " widths=(1,3,5,5,5,1,3,4,1,13,11,11,9,1,2,11,9,1,3,1,12,11,1),\n", " header=39,\n", " index_col=False)\n", "\n", "# Extrapolated values are indicated by '#' in place of the decimal place, so\n", "# the Ebinding column won't be numeric. Coerce to float and drop these entries.\n", "Masses['Ebinding'] = pd.to_numeric(Masses['Ebinding'], errors='coerce')\n", "Masses = Masses.dropna()\n", "# Convert from keV to MeV.\n", "Masses['Ebinding'] /= 1000\n", "\n", "# Group the DataFrame by nucleon number, A.\n", "Masses = Masses.groupby('A')\n", "# Find the rows of the grouped DataFrame with the maximum binding energy.\n", "Masses = Masses.apply(lambda t: t[t.Ebinding==t.Ebinding.max()])\n", "A = Masses['A']\n", "Z = Masses['Z']\n", "N = Masses['N']\n", "Element = Masses['Element']\n", "Energies = Masses['Ebinding']\n", "\n", "# Now we set up the design matrix X\n", "X = np.zeros((len(A),5))\n", "X[:,0] = 1\n", "X[:,1] = A\n", "X[:,2] = A**(2.0/3.0)\n", "X[:,3] = A**(-1.0/3.0)\n", "X[:,4] = A**(-1.0)\n", "# Then nice printout using pandas\n", "DesignMatrix = pd.DataFrame(X)\n", "DesignMatrix.index = A\n", "DesignMatrix.columns = ['1', 'A', 'A^(2/3)', 'A^(-1/3)', '1/A']\n", "display(DesignMatrix)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "With $\\boldsymbol{\\beta}\\in {\\mathbb{R}}^{p\\times 1}$, it means that we will hereafter write our equations for the approximation as" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "$$\n", "\\boldsymbol{\\tilde{y}}= \\boldsymbol{X}\\boldsymbol{\\beta},\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "throughout these lectures. \n", "\n", "\n", "\n", "With the above we use the design matrix to define the approximation $\\boldsymbol{\\tilde{y}}$ via the unknown quantity $\\boldsymbol{\\beta}$ as" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "$$\n", "\\boldsymbol{\\tilde{y}}= \\boldsymbol{X}\\boldsymbol{\\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 parameterized values $\\tilde{y}_i$, namely" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "$$\n", "C(\\boldsymbol{\\beta})=\\frac{1}{n}\\sum_{i=0}^{n-1}\\left(y_i-\\tilde{y}_i\\right)^2=\\frac{1}{n}\\left\\{\\left(\\boldsymbol{y}-\\boldsymbol{\\tilde{y}}\\right)^T\\left(\\boldsymbol{y}-\\boldsymbol{\\tilde{y}}\\right)\\right\\},\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "or using the matrix $\\boldsymbol{X}$ and in a more compact matrix-vector notation as" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "$$\n", "C(\\boldsymbol{\\beta})=\\frac{1}{n}\\left\\{\\left(\\boldsymbol{y}-\\boldsymbol{X}^T\\boldsymbol{\\beta}\\right)^T\\left(\\boldsymbol{y}-\\boldsymbol{X}^T\\boldsymbol{\\beta}\\right)\\right\\}.\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "This function is one possible way to define the so-called cost function.\n", "\n", "\n", "\n", "It is also common to define\n", "the function $Q$ as" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "$$\n", "C(\\boldsymbol{\\beta})=\\frac{1}{2n}\\sum_{i=0}^{n-1}\\left(y_i-\\tilde{y}_i\\right)^2,\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "since when taking the first derivative with respect to the unknown parameters $\\beta$, the factor of $2$ cancels out. \n", "\n", "\n", "\n", "\n", "## Interpretations and optimizing our parameters\n", "\n", "\n", "The function" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "$$\n", "C(\\boldsymbol{\\beta})=\\frac{1}{n}\\left\\{\\left(\\boldsymbol{y}-\\boldsymbol{X}\\boldsymbol{\\beta}\\right)^T\\left(\\boldsymbol{y}-\\boldsymbol{X}\\boldsymbol{\\beta}\\right)\\right\\},\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "can be linked to the variance of the quantity $y_i$ if we interpret the latter as the mean value. \n", "When linking below with the maximum likelihood approach below, we will indeed interpret $y_i$ as a mean value (see exercises)" ] }, { "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\n", "till now we have treated $y_i$ as the exact value. Normally, the\n", "response (dependent or outcome) variable $y_i$ the outcome of a\n", "numerical experiment or another type of experiment and is thus only an\n", "approximation to the true value. It is then always accompanied by an\n", "error estimate, often limited to a statistical error estimate given by\n", "the standard deviation discussed earlier. In the discussion here we\n", "will treat $y_i$ as our exact value for the response variable.\n", "\n", "In order to find the parameters $\\beta_i$ we will then minimize the spread of $C(\\boldsymbol{\\beta})$, that is we are going to solve the problem" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "$$\n", "{\\displaystyle \\min_{\\boldsymbol{\\beta}\\in\n", "{\\mathbb{R}}^{p}}}\\frac{1}{n}\\left\\{\\left(\\boldsymbol{y}-\\boldsymbol{X}\\boldsymbol{\\beta}\\right)^T\\left(\\boldsymbol{y}-\\boldsymbol{X}\\boldsymbol{\\beta}\\right)\\right\\}.\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "In practical terms it means we will require" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "$$\n", "\\frac{\\partial C(\\boldsymbol{\\beta})}{\\partial \\beta_j} = \\frac{\\partial }{\\partial \\beta_j}\\left[ \\frac{1}{n}\\sum_{i=0}^{n-1}\\left(y_i-\\beta_0x_{i,0}-\\beta_1x_{i,1}-\\beta_2x_{i,2}-\\dots-\\beta_{n-1}x_{i,n-1}\\right)^2\\right]=0,\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "which results in" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "$$\n", "\\frac{\\partial C(\\boldsymbol{\\beta})}{\\partial \\beta_j} = -\\frac{2}{n}\\left[ \\sum_{i=0}^{n-1}x_{ij}\\left(y_i-\\beta_0x_{i,0}-\\beta_1x_{i,1}-\\beta_2x_{i,2}-\\dots-\\beta_{n-1}x_{i,n-1}\\right)\\right]=0,\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "or in a matrix-vector form as" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "$$\n", "\\frac{\\partial C(\\boldsymbol{\\beta})}{\\partial \\boldsymbol{\\beta}} = 0 = \\boldsymbol{X}^T\\left( \\boldsymbol{y}-\\boldsymbol{X}\\boldsymbol{\\beta}\\right).\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "We can rewrite" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "$$\n", "\\frac{\\partial C(\\boldsymbol{\\beta})}{\\partial \\boldsymbol{\\beta}} = 0 = \\boldsymbol{X}^T\\left( \\boldsymbol{y}-\\boldsymbol{X}\\boldsymbol{\\beta}\\right),\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "as" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "$$\n", "\\boldsymbol{X}^T\\boldsymbol{y} = \\boldsymbol{X}^T\\boldsymbol{X}\\boldsymbol{\\beta},\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "and if the matrix $\\boldsymbol{X}^T\\boldsymbol{X}$ is invertible we have the solution" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "$$\n", "\\boldsymbol{\\beta} =\\left(\\boldsymbol{X}^T\\boldsymbol{X}\\right)^{-1}\\boldsymbol{X}^T\\boldsymbol{y}.\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "We note also that since our design matrix is defined as $\\boldsymbol{X}\\in\n", "{\\mathbb{R}}^{n\\times p}$, the product $\\boldsymbol{X}^T\\boldsymbol{X} \\in\n", "{\\mathbb{R}}^{p\\times p}$. In the above case we have that $p \\ll n$,\n", "in our case $p=5$ meaning that we end up with inverting a small\n", "$5\\times 5$ matrix. This is a rather common situation, in many cases we end up with low-dimensional\n", "matrices to invert. The methods discussed here and for many other\n", "supervised learning algorithms like classification with logistic\n", "regression or support vector machines, exhibit dimensionalities which\n", "allow for the usage of direct linear algebra methods such as **LU** decomposition or **Singular Value Decomposition** (SVD) for finding the inverse of the matrix\n", "$\\boldsymbol{X}^T\\boldsymbol{X}$. \n", "\n", "\n", "\n", "The residuals $\\boldsymbol{\\epsilon}$ are in turn given by" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "$$\n", "\\boldsymbol{\\epsilon} = \\boldsymbol{y}-\\boldsymbol{\\tilde{y}} = \\boldsymbol{y}-\\boldsymbol{X}\\boldsymbol{\\beta},\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "and with" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "$$\n", "\\boldsymbol{X}^T\\left( \\boldsymbol{y}-\\boldsymbol{X}\\boldsymbol{\\beta}\\right)= 0,\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "we have" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "$$\n", "\\boldsymbol{X}^T\\boldsymbol{\\epsilon}=\\boldsymbol{X}^T\\left( \\boldsymbol{y}-\\boldsymbol{X}\\boldsymbol{\\beta}\\right)= 0,\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "meaning that the solution for $\\boldsymbol{\\beta}$ is the one which minimizes the residuals. Later we will link this with the maximum likelihood approach.\n", "\n", "\n", "Let us now return to our nuclear binding energies and simply code the above equations. \n", "\n", "It is rather straightforward to implement the matrix inversion and obtain the parameters $\\boldsymbol{\\beta}$. After having defined the matrix $\\boldsymbol{X}$ we simply need to \n", "write" ] }, { "cell_type": "code", "execution_count": 39, "metadata": {}, "outputs": [], "source": [ "# matrix inversion to find beta\n", "beta = np.linalg.inv(X.T.dot(X)).dot(X.T).dot(Energies)\n", "# and then make the prediction\n", "ytilde = X @ beta" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Alternatively, you can use the least squares functionality in **Numpy** as" ] }, { "cell_type": "code", "execution_count": 40, "metadata": {}, "outputs": [], "source": [ "fit = np.linalg.lstsq(X, Energies, rcond =None)[0]\n", "ytildenp = np.dot(fit,X.T)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "And finally we plot our fit with and compare with data" ] }, { "cell_type": "code", "execution_count": 41, "metadata": {}, "outputs": [], "source": [ "Masses['Eapprox'] = ytilde\n", "# Generate a plot comparing the experimental with the fitted values values.\n", "fig, ax = plt.subplots()\n", "ax.set_xlabel(r'$A = N + Z$')\n", "ax.set_ylabel(r'$E_\\mathrm{bind}\\,/\\mathrm{MeV}$')\n", "ax.plot(Masses['A'], Masses['Ebinding'], alpha=0.7, lw=2,\n", " label='Ame2016')\n", "ax.plot(Masses['A'], Masses['Eapprox'], alpha=0.7, lw=2, c='m',\n", " label='Fit')\n", "ax.legend()\n", "save_fig(\"Masses2016OLS\")\n", "plt.show()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Adding error analysis and training set up\n", "\n", "We can easily test our fit by computing the $R2$ score that we discussed in connection with the functionality of _Scikit_Learn_ in the introductory slides.\n", "Since we are not using _Scikit-Learn here we can define our own $R2$ function as" ] }, { "cell_type": "code", "execution_count": 42, "metadata": {}, "outputs": [], "source": [ "def R2(y_data, y_model):\n", " return 1 - np.sum((y_data - y_model) ** 2) / np.sum((y_data - np.mean(y_model)) ** 2)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "and we would be using it as" ] }, { "cell_type": "code", "execution_count": 43, "metadata": {}, "outputs": [], "source": [ "print(R2(Energies,ytilde))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "We can easily add our **MSE** score as" ] }, { "cell_type": "code", "execution_count": 44, "metadata": {}, "outputs": [], "source": [ "def MSE(y_data,y_model):\n", " n = np.size(y_model)\n", " return np.sum((y_data-y_model)**2)/n\n", "\n", "print(MSE(Energies,ytilde))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "and finally the relative error as" ] }, { "cell_type": "code", "execution_count": 45, "metadata": {}, "outputs": [], "source": [ "def RelativeError(y_data,y_model):\n", " return abs((y_data-y_model)/y_data)\n", "print(RelativeError(Energies, ytilde))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## The $\\chi^2$ function\n", "\n", "Normally, the response (dependent or outcome) variable $y_i$ is the\n", "outcome of a numerical experiment or another type of experiment and is\n", "thus only an approximation to the true value. It is then always\n", "accompanied by an error estimate, often limited to a statistical error\n", "estimate given by the standard deviation discussed earlier. In the\n", "discussion here we will treat $y_i$ as our exact value for the\n", "response variable.\n", "\n", "Introducing the standard deviation $\\sigma_i$ for each measurement\n", "$y_i$, we define now the $\\chi^2$ function (omitting the $1/n$ term)\n", "as" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "$$\n", "\\chi^2(\\boldsymbol{\\beta})=\\frac{1}{n}\\sum_{i=0}^{n-1}\\frac{\\left(y_i-\\tilde{y}_i\\right)^2}{\\sigma_i^2}=\\frac{1}{n}\\left\\{\\left(\\boldsymbol{y}-\\boldsymbol{\\tilde{y}}\\right)^T\\frac{1}{\\boldsymbol{\\Sigma^2}}\\left(\\boldsymbol{y}-\\boldsymbol{\\tilde{y}}\\right)\\right\\},\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "where the matrix $\\boldsymbol{\\Sigma}$ is a diagonal matrix with $\\sigma_i$ as matrix elements. \n", "\n", "\n", "In order to find the parameters $\\beta_i$ we will then minimize the spread of $\\chi^2(\\boldsymbol{\\beta})$ by requiring" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "$$\n", "\\frac{\\partial \\chi^2(\\boldsymbol{\\beta})}{\\partial \\beta_j} = \\frac{\\partial }{\\partial \\beta_j}\\left[ \\frac{1}{n}\\sum_{i=0}^{n-1}\\left(\\frac{y_i-\\beta_0x_{i,0}-\\beta_1x_{i,1}-\\beta_2x_{i,2}-\\dots-\\beta_{n-1}x_{i,n-1}}{\\sigma_i}\\right)^2\\right]=0,\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "which results in" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "$$\n", "\\frac{\\partial \\chi^2(\\boldsymbol{\\beta})}{\\partial \\beta_j} = -\\frac{2}{n}\\left[ \\sum_{i=0}^{n-1}\\frac{x_{ij}}{\\sigma_i}\\left(\\frac{y_i-\\beta_0x_{i,0}-\\beta_1x_{i,1}-\\beta_2x_{i,2}-\\dots-\\beta_{n-1}x_{i,n-1}}{\\sigma_i}\\right)\\right]=0,\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "or in a matrix-vector form as" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "$$\n", "\\frac{\\partial \\chi^2(\\boldsymbol{\\beta})}{\\partial \\boldsymbol{\\beta}} = 0 = \\boldsymbol{A}^T\\left( \\boldsymbol{b}-\\boldsymbol{A}\\boldsymbol{\\beta}\\right).\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "where we have defined the matrix $\\boldsymbol{A} =\\boldsymbol{X}/\\boldsymbol{\\Sigma}$ with matrix elements $a_{ij} = x_{ij}/\\sigma_i$ and the vector $\\boldsymbol{b}$ with elements $b_i = y_i/\\sigma_i$. \n", "\n", "We can rewrite" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "$$\n", "\\frac{\\partial \\chi^2(\\boldsymbol{\\beta})}{\\partial \\boldsymbol{\\beta}} = 0 = \\boldsymbol{A}^T\\left( \\boldsymbol{b}-\\boldsymbol{A}\\boldsymbol{\\beta}\\right),\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "as" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "$$\n", "\\boldsymbol{A}^T\\boldsymbol{b} = \\boldsymbol{A}^T\\boldsymbol{A}\\boldsymbol{\\beta},\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "and if the matrix $\\boldsymbol{A}^T\\boldsymbol{A}$ is invertible we have the solution" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "$$\n", "\\boldsymbol{\\beta} =\\left(\\boldsymbol{A}^T\\boldsymbol{A}\\right)^{-1}\\boldsymbol{A}^T\\boldsymbol{b}.\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "If we then introduce the matrix" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "$$\n", "\\boldsymbol{H} = \\left(\\boldsymbol{A}^T\\boldsymbol{A}\\right)^{-1},\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "we have then the following expression for the parameters $\\beta_j$ (the matrix elements of $\\boldsymbol{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 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(\\boldsymbol{\\beta})}{\\partial \\beta_0} = -2\\left[ \\frac{1}{n}\\sum_{i=0}^{n-1}\\left(\\frac{y_i-\\beta_0-\\beta_1x_{i}}{\\sigma_i^2}\\right)\\right]=0,\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "and" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "$$\n", "\\frac{\\partial \\chi^2(\\boldsymbol{\\beta})}{\\partial \\beta_1} = -\\frac{2}{n}\\left[ \\sum_{i=0}^{n-1}x_i\\left(\\frac{y_i-\\beta_0-\\beta_1x_{i}}{\\sigma_i^2}\\right)\\right]=0.\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "For a linear fit (a first-order polynomial) 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": [ "$$\n", "\\gamma_x = \\sum_{i=0}^{n-1}\\frac{x_{i}}{\\sigma_i^2},\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "$$\n", "\\gamma_y = \\sum_{i=0}^{n-1}\\left(\\frac{y_i}{\\sigma_i^2}\\right),\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "$$\n", "\\gamma_{xx} = \\sum_{i=0}^{n-1}\\frac{x_ix_{i}}{\\sigma_i^2},\n", "$$" ] }, { "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": [ "$$\n", "\\beta_0 = \\frac{\\gamma_{xx}\\gamma_y-\\gamma_x\\gamma_y}{\\gamma\\gamma_{xx}-\\gamma_x^2},\n", "$$" ] }, { "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\n", "often from both being underdetermined and overdetermined in the\n", "unknown coefficients $\\beta_i$. A better approach is to use the\n", "Singular Value Decomposition (SVD) method discussed below. Or using\n", "Lasso and Ridge regression. See below.\n", "\n", "\n", "## Fitting an Equation of State for Dense Nuclear Matter\n", "\n", "Before we continue, let us introduce yet another example. We are going to fit the\n", "nuclear equation of state using results from many-body calculations.\n", "The equation of state we have made available here, as function of\n", "density, has been derived using modern nucleon-nucleon potentials with\n", "[the addition of three-body\n", "forces](https://www.sciencedirect.com/science/article/pii/S0370157399001106). This\n", "time the file is presented as a standard **csv** file.\n", "\n", "The beginning of the Python code here is similar to what you have seen before,\n", "with the same initializations and declarations. We use also **pandas**\n", "again, rather extensively in order to organize our data.\n", "\n", "The difference now is that we use **Scikit-Learn's** regression tools\n", "instead of our own matrix inversion implementation. Furthermore, we\n", "sneak in **Ridge** regression (to be discussed below) which includes a\n", "hyperparameter $\\lambda$, also to be explained below.\n", "\n", "## The code" ] }, { "cell_type": "code", "execution_count": 46, "metadata": {}, "outputs": [], "source": [ "# Common imports\n", "import os\n", "import numpy as np\n", "import pandas as pd\n", "import matplotlib.pyplot as plt\n", "import matplotlib.pyplot as plt\n", "import sklearn.linear_model as skl\n", "from sklearn.metrics import mean_squared_error, r2_score, mean_absolute_error\n", "\n", "# Where to save the figures and data files\n", "PROJECT_ROOT_DIR = \"Results\"\n", "FIGURE_ID = \"Results/FigureFiles\"\n", "DATA_ID = \"DataFiles/\"\n", "\n", "if not os.path.exists(PROJECT_ROOT_DIR):\n", " os.mkdir(PROJECT_ROOT_DIR)\n", "\n", "if not os.path.exists(FIGURE_ID):\n", " os.makedirs(FIGURE_ID)\n", "\n", "if not os.path.exists(DATA_ID):\n", " os.makedirs(DATA_ID)\n", "\n", "def image_path(fig_id):\n", " return os.path.join(FIGURE_ID, fig_id)\n", "\n", "def data_path(dat_id):\n", " return os.path.join(DATA_ID, dat_id)\n", "\n", "def save_fig(fig_id):\n", " plt.savefig(image_path(fig_id) + \".png\", format='png')\n", "\n", "infile = open(data_path(\"EoS.csv\"),'r')\n", "\n", "# Read the EoS data as csv file and organize the data into two arrays with density and energies\n", "EoS = pd.read_csv(infile, names=('Density', 'Energy'))\n", "EoS['Energy'] = pd.to_numeric(EoS['Energy'], errors='coerce')\n", "EoS = EoS.dropna()\n", "Energies = EoS['Energy']\n", "Density = EoS['Density']\n", "# The design matrix now as function of various polytrops\n", "X = np.zeros((len(Density),4))\n", "X[:,3] = Density**(4.0/3.0)\n", "X[:,2] = Density\n", "X[:,1] = Density**(2.0/3.0)\n", "X[:,0] = 1\n", "\n", "# We use now Scikit-Learn's linear regressor and ridge regressor\n", "# OLS part\n", "clf = skl.LinearRegression().fit(X, Energies)\n", "ytilde = clf.predict(X)\n", "EoS['Eols'] = ytilde\n", "# The mean squared error \n", "print(\"Mean squared error: %.2f\" % mean_squared_error(Energies, ytilde))\n", "# Explained variance score: 1 is perfect prediction \n", "print('Variance score: %.2f' % r2_score(Energies, ytilde))\n", "# Mean absolute error \n", "print('Mean absolute error: %.2f' % mean_absolute_error(Energies, ytilde))\n", "print(clf.coef_, clf.intercept_)\n", "\n", "# The Ridge regression with a hyperparameter lambda = 0.1\n", "_lambda = 0.1\n", "clf_ridge = skl.Ridge(alpha=_lambda).fit(X, Energies)\n", "yridge = clf_ridge.predict(X)\n", "EoS['Eridge'] = yridge\n", "# The mean squared error \n", "print(\"Mean squared error: %.2f\" % mean_squared_error(Energies, yridge))\n", "# Explained variance score: 1 is perfect prediction \n", "print('Variance score: %.2f' % r2_score(Energies, yridge))\n", "# Mean absolute error \n", "print('Mean absolute error: %.2f' % mean_absolute_error(Energies, yridge))\n", "print(clf_ridge.coef_, clf_ridge.intercept_)\n", "\n", "fig, ax = plt.subplots()\n", "ax.set_xlabel(r'$\\rho[\\mathrm{fm}^{-3}]$')\n", "ax.set_ylabel(r'Energy per particle')\n", "ax.plot(EoS['Density'], EoS['Energy'], alpha=0.7, lw=2,\n", " label='Theoretical data')\n", "ax.plot(EoS['Density'], EoS['Eols'], alpha=0.7, lw=2, c='m',\n", " label='OLS')\n", "ax.plot(EoS['Density'], EoS['Eridge'], alpha=0.7, lw=2, c='g',\n", " label='Ridge $\\lambda = 0.1$')\n", "ax.legend()\n", "save_fig(\"EoSfitting\")\n", "plt.show()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "The above simple polynomial in density $\\rho$ gives an excellent fit\n", "to the data. \n", "We note also that there is a small deviation between the\n", "standard OLS and the Ridge regression at higher densities. We discuss this in more detail\n", "below.\n", "\n", "\n", "## Splitting our Data in Training and Test data\n", "\n", "It is normal in essentially all Machine Learning studies to split the\n", "data in a training set and a test set (sometimes also an additional\n", "validation set). **Scikit-Learn** has an own function for this. There\n", "is no explicit recipe for how much data should be included as training\n", "data and say test data. An accepted rule of thumb is to use\n", "approximately $2/3$ to $4/5$ of the data as training data. We will\n", "postpone a discussion of this splitting to the end of these notes and\n", "our discussion of the so-called **bias-variance** tradeoff. Here we\n", "limit ourselves to repeat the above equation of state fitting example\n", "but now splitting the data into a training set and a test set." ] }, { "cell_type": "code", "execution_count": 47, "metadata": {}, "outputs": [], "source": [ "import os\n", "import numpy as np\n", "import pandas as pd\n", "import matplotlib.pyplot as plt\n", "from sklearn.model_selection import train_test_split\n", "# Where to save the figures and data files\n", "PROJECT_ROOT_DIR = \"Results\"\n", "FIGURE_ID = \"Results/FigureFiles\"\n", "DATA_ID = \"DataFiles/\"\n", "\n", "if not os.path.exists(PROJECT_ROOT_DIR):\n", " os.mkdir(PROJECT_ROOT_DIR)\n", "\n", "if not os.path.exists(FIGURE_ID):\n", " os.makedirs(FIGURE_ID)\n", "\n", "if not os.path.exists(DATA_ID):\n", " os.makedirs(DATA_ID)\n", "\n", "def image_path(fig_id):\n", " return os.path.join(FIGURE_ID, fig_id)\n", "\n", "def data_path(dat_id):\n", " return os.path.join(DATA_ID, dat_id)\n", "\n", "def save_fig(fig_id):\n", " plt.savefig(image_path(fig_id) + \".png\", format='png')\n", "\n", "def R2(y_data, y_model):\n", " return 1 - np.sum((y_data - y_model) ** 2) / np.sum((y_data - np.mean(y_model)) ** 2)\n", "def MSE(y_data,y_model):\n", " n = np.size(y_model)\n", " return np.sum((y_data-y_model)**2)/n\n", "\n", "infile = open(data_path(\"EoS.csv\"),'r')\n", "\n", "# Read the EoS data as csv file and organized into two arrays with density and energies\n", "EoS = pd.read_csv(infile, names=('Density', 'Energy'))\n", "EoS['Energy'] = pd.to_numeric(EoS['Energy'], errors='coerce')\n", "EoS = EoS.dropna()\n", "Energies = EoS['Energy']\n", "Density = EoS['Density']\n", "# The design matrix now as function of various polytrops\n", "X = np.zeros((len(Density),5))\n", "X[:,0] = 1\n", "X[:,1] = Density**(2.0/3.0)\n", "X[:,2] = Density\n", "X[:,3] = Density**(4.0/3.0)\n", "X[:,4] = Density**(5.0/3.0)\n", "# We split the data in test and training data\n", "X_train, X_test, y_train, y_test = train_test_split(X, Energies, test_size=0.2)\n", "# matrix inversion to find beta\n", "beta = np.linalg.inv(X_train.T.dot(X_train)).dot(X_train.T).dot(y_train)\n", "# and then make the prediction\n", "ytilde = X_train @ beta\n", "print(\"Training R2\")\n", "print(R2(y_train,ytilde))\n", "print(\"Training MSE\")\n", "print(MSE(y_train,ytilde))\n", "ypredict = X_test @ beta\n", "print(\"Test R2\")\n", "print(R2(y_test,ypredict))\n", "print(\"Test MSE\")\n", "print(MSE(y_test,ypredict))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## The singular value decomposition\n", "\n", "The examples we have looked at so far are cases where we normally can\n", "invert the matrix $\\boldsymbol{X}^T\\boldsymbol{X}$. Using a polynomial expansion as we\n", "did both for the masses and the fitting of the equation of state,\n", "leads to row vectors of the design matrix which are essentially\n", "orthogonal due to the polynomial character of our model. This may\n", "however not the be case in general and a standard matrix inversion\n", "algorithm based on say LU decomposition may lead to singularities. We will see an example of this below when we try to fit\n", "the coupling constant of the widely used Ising model. \n", "There is however a way to partially circumvent this problem and also gain some insight about the ordinary least squares approach. \n", "\n", "This is given by the **Singular Value Decomposition** algorithm, perhaps\n", "the most powerful linear algebra algorithm. Let us look at a\n", "different example where we may have problems with the standard matrix\n", "inversion algorithm. Thereafter we dive into the math of the SVD.\n", "\n", "\n", "## The Ising model\n", "\n", "The one-dimensional Ising model with nearest neighbor interaction, no\n", "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{_auto1} \\tag{1}\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\n", "in the system is determined by $L$. For the one-dimensional system\n", "there is no phase transition.\n", "\n", "We will look at a system of $L = 40$ spins with a coupling constant of\n", "$J = 1$. To get enough training data we will generate 10000 states\n", "with their respective energies." ] }, { "cell_type": "code", "execution_count": 48, "metadata": {}, "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 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 ordinary least squares\n", "regression to predict the energy for the nearest neighbor\n", "one-dimensional Ising model on a ring, i.e., the endpoints wrap\n", "around. We will use linear regression to fit a value for\n", "the coupling constant to achieve this.\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{_auto2} \\tag{2}\n", "\\end{equation}\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Here we allow for interactions beyond the nearest neighbors and a state dependent\n", "coupling constant. This latter expression can be formulated as\n", "a matrix-product" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "\n", "
\n", "\n", "$$\n", "\\begin{equation}\n", " \\boldsymbol{H} = \\boldsymbol{X} J,\n", "\\label{_auto3} \\tag{3}\n", "\\end{equation}\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "where $X_{jk} = s_j s_k$ and $J$ is a matrix which consists of the\n", "elements $-J_{jk}$. This form of writing the energy fits perfectly\n", "with the form utilized in linear regression, that is" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "\n", "
\n", "\n", "$$\n", "\\begin{equation}\n", " \\boldsymbol{y} = \\boldsymbol{X}\\boldsymbol{\\beta} + \\boldsymbol{\\epsilon},\n", "\\label{_auto4} \\tag{4}\n", "\\end{equation}\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "We split the data in training and test data as discussed in the previous example" ] }, { "cell_type": "code", "execution_count": 49, "metadata": {}, "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.2)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "In the ordinary least squares method we choose the cost function" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "\n", "
\n", "\n", "$$\n", "\\begin{equation}\n", " C(\\boldsymbol{X}, \\boldsymbol{\\beta})= \\frac{1}{n}\\left\\{(\\boldsymbol{X}\\boldsymbol{\\beta} - \\boldsymbol{y})^T(\\boldsymbol{X}\\boldsymbol{\\beta} - \\boldsymbol{y})\\right\\}.\n", "\\label{_auto5} \\tag{5}\n", "\\end{equation}\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "We then find the extremal point of $C$ by taking the derivative with respect to $\\boldsymbol{\\beta}$ as discussed above.\n", "This yields the expression for $\\boldsymbol{\\beta}$ to be" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "$$\n", "\\boldsymbol{\\beta} = \\frac{\\boldsymbol{X}^T \\boldsymbol{y}}{\\boldsymbol{X}^T \\boldsymbol{X}},\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "which immediately imposes some requirements on $\\boldsymbol{X}$ as there must exist\n", "an inverse of $\\boldsymbol{X}^T \\boldsymbol{X}$. If the expression we are modeling contains an\n", "intercept, i.e., a constant term, we must make sure that the\n", "first column of $\\boldsymbol{X}$ consists of $1$. We do this here" ] }, { "cell_type": "code", "execution_count": 50, "metadata": {}, "outputs": [], "source": [ "X_train_own = np.concatenate(\n", " (np.ones(len(X_train))[:, np.newaxis], X_train),\n", " axis=1\n", ")\n", "X_test_own = np.concatenate(\n", " (np.ones(len(X_test))[:, np.newaxis], X_test),\n", " axis=1\n", ")" ] }, { "cell_type": "code", "execution_count": 51, "metadata": {}, "outputs": [], "source": [ "def ols_inv(x: np.ndarray, y: np.ndarray) -> np.ndarray:\n", " return scl.inv(x.T @ x) @ (x.T @ y)\n", "beta = ols_inv(X_train_own, y_train)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Singular Value decomposition\n", "\n", "Doing the inversion directly turns out to be a bad idea since the matrix\n", "$\\boldsymbol{X}^T\\boldsymbol{X}$ 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 $\\boldsymbol{\\beta}$ as" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "$$\n", "\\boldsymbol{\\beta} = \\boldsymbol{X}^{+}\\boldsymbol{y},\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "where the pseudoinverse of $\\boldsymbol{X}$ is given by" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "$$\n", "\\boldsymbol{X}^{+} = \\frac{\\boldsymbol{X}^T}{\\boldsymbol{X}^T\\boldsymbol{X}}.\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Using singular value decomposition we can decompose the matrix $\\boldsymbol{X} = \\boldsymbol{U}\\boldsymbol{\\Sigma} \\boldsymbol{V}^T$,\n", "where $\\boldsymbol{U}$ and $\\boldsymbol{V}$ are orthogonal(unitary) matrices and $\\boldsymbol{\\Sigma}$ contains the singular values (more details below).\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", " \\boldsymbol{\\beta} = \\boldsymbol{V}\\boldsymbol{\\Sigma}^{+} \\boldsymbol{U}^T \\boldsymbol{y}.\n", "\\label{_auto6} \\tag{6}\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": 52, "metadata": {}, "outputs": [], "source": [ "def ols_svd(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": "code", "execution_count": 53, "metadata": {}, "outputs": [], "source": [ "beta = ols_svd(X_train_own,y_train)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "When extracting the $J$-matrix we need to make sure that we remove the intercept, as is done here" ] }, { "cell_type": "code", "execution_count": 54, "metadata": {}, "outputs": [], "source": [ "J = beta[1:].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": 55, "metadata": {}, "outputs": [], "source": [ "fig = plt.figure(figsize=(20, 14))\n", "im = plt.imshow(J, **cmap_args)\n", "plt.title(\"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", "plt.show()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "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", "In our discussion below on hyperparameters and Ridge and Lasso regression we will see that\n", "this problem can be removed, partly and only with Lasso regression. \n", "\n", "In this case our matrix inversion was actually possible. The obvious question now is what is the mathematics behind the SVD?\n", "\n", "\n", "\n", "## Linear Regression Problems\n", "\n", "One of the typical problems we encounter with linear regression, in particular \n", "when the matrix $\\boldsymbol{X}$ (our so-called design matrix) is high-dimensional, \n", "are problems with near singular or singular matrices. The column vectors of $\\boldsymbol{X}$ \n", "may be linearly dependent, normally referred to as super-collinearity. \n", "This means that the matrix may be rank deficient and it is basically impossible to \n", "to model the data using linear regression. As an example, consider the matrix" ] }, { "cell_type": "markdown", "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 $\\boldsymbol{X}$ are linearly dependent. We see this easily since the \n", "the first column is the row-wise sum of the other two columns. The rank (more correct,\n", "the column rank) of a matrix is the dimension of the space spanned by the\n", "column vectors. Hence, the rank of $\\mathbf{X}$ is equal to the number\n", "of linearly independent columns. In this particular case the matrix has rank 2.\n", "\n", "Super-collinearity of an $(n \\times p)$-dimensional design matrix $\\mathbf{X}$ implies\n", "that the inverse of the matrix $\\boldsymbol{X}^T\\boldsymbol{x}$ (the matrix we need to invert to solve the linear regression equations) is non-invertible. If we have a square matrix that does not have an inverse, we say this matrix singular. The example here demonstrates this" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "$$\n", "\\begin{align*}\n", "\\boldsymbol{X} & = \\left[\n", "\\begin{array}{rr}\n", "1 & -1\n", "\\\\\n", "1 & -1\n", "\\end{array} \\right].\n", "\\end{align*}\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "We see easily that $\\mbox{det}(\\boldsymbol{X}) = x_{11} x_{22} - x_{12} x_{21} = 1 \\times (-1) - 1 \\times (-1) = 0$. Hence, $\\mathbf{X}$ is singular and its inverse is undefined.\n", "This is equivalent to saying that the matrix $\\boldsymbol{X}$ has at least an eigenvalue which is zero.\n", "\n", "\n", "\n", "## Fixing the singularity\n", "\n", "If our design matrix $\\boldsymbol{X}$ which enters the linear regression problem" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "\n", "
\n", "\n", "$$\n", "\\begin{equation}\n", "\\boldsymbol{\\beta} = (\\boldsymbol{X}^{T} \\boldsymbol{X})^{-1} \\boldsymbol{X}^{T} \\boldsymbol{y},\n", "\\label{_auto7} \\tag{7}\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 $\\boldsymbol{X}^T\\boldsymbol{X}$ and we cannot find the parameters (estimators) $\\beta_i$. \n", "The estimators are only well-defined if $(\\boldsymbol{X}^{T}\\boldsymbol{X})^{-1}$ exits. \n", "This is more likely to happen when the matrix $\\boldsymbol{X}$ is high-dimensional. In this case it is likely to encounter a situation where \n", "the regression parameters $\\beta_i$ cannot be estimated.\n", "\n", "A cheap *ad hoc* approach is simply to add a small diagonal component to the matrix to invert, that is we change" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "$$\n", "\\boldsymbol{X}^{T} \\boldsymbol{X} \\rightarrow \\boldsymbol{X}^{T} \\boldsymbol{X}+\\lambda \\boldsymbol{I},\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "where $\\boldsymbol{I}$ is the identity matrix. When we discuss **Ridge** regression this is actually what we end up evaluating. The parameter $\\lambda$ is called a hyperparameter. More about this later. \n", "\n", "\n", "\n", "\n", "## Basic math of the SVD\n", "\n", "\n", "From standard linear algebra we know that a square matrix $\\boldsymbol{X}$ can be diagonalized if and only it is \n", "a so-called [normal matrix](https://en.wikipedia.org/wiki/Normal_matrix), that is if $\\boldsymbol{X}\\in {\\mathbb{R}}^{n\\times n}$\n", "we have $\\boldsymbol{X}\\boldsymbol{X}^T=\\boldsymbol{X}^T\\boldsymbol{X}$ or if $\\boldsymbol{X}\\in {\\mathbb{C}}^{n\\times n}$ we have $\\boldsymbol{X}\\boldsymbol{X}^{\\dagger}=\\boldsymbol{X}^{\\dagger}\\boldsymbol{X}$.\n", "The matrix has then a set of eigenpairs" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "$$\n", "(\\lambda_1,\\boldsymbol{u}_1),\\dots, (\\lambda_n,\\boldsymbol{u}_n),\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "and the eigenvalues are given by the diagonal matrix" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "$$\n", "\\boldsymbol{\\Sigma}=\\mathrm{Diag}(\\lambda_1, \\dots,\\lambda_n).\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "The matrix $\\boldsymbol{X}$ can be written in terms of an orthogonal/unitary transformation $\\boldsymbol{U}$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "$$\n", "\\boldsymbol{X} = \\boldsymbol{U}\\boldsymbol{\\Sigma}\\boldsymbol{V}^T,\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "with $\\boldsymbol{U}\\boldsymbol{U}^T=\\boldsymbol{I}$ or $\\boldsymbol{U}\\boldsymbol{U}^{\\dagger}=\\boldsymbol{I}$.\n", "\n", "Not all square matrices are diagonalizable. A matrix like the one discussed above" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "$$\n", "\\boldsymbol{X} = \\begin{bmatrix} \n", "1& -1 \\\\\n", "1& -1\\\\\n", "\\end{bmatrix}\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "is not diagonalizable, it is a so-called [defective matrix](https://en.wikipedia.org/wiki/Defective_matrix). It is easy to see that the condition\n", "$\\boldsymbol{X}\\boldsymbol{X}^T=\\boldsymbol{X}^T\\boldsymbol{X}$ is not fulfilled. \n", "\n", "\n", "\n", "## The SVD, a Fantastic Algorithm\n", "\n", "\n", "However, and this is the strength of the SVD algorithm, any general\n", "matrix $\\boldsymbol{X}$ can be decomposed in terms of a diagonal matrix and\n", "two orthogonal/unitary matrices. The [Singular Value Decompostion\n", "(SVD) theorem](https://en.wikipedia.org/wiki/Singular_value_decomposition)\n", "states that a general $m\\times n$ matrix $\\boldsymbol{X}$ can be written in\n", "terms of a diagonal matrix $\\boldsymbol{\\Sigma}$ of dimensionality $n\\times n$\n", "and two orthognal matrices $\\boldsymbol{U}$ and $\\boldsymbol{V}$, where the first has\n", "dimensionality $m \\times m$ and the last dimensionality $n\\times n$.\n", "We have then" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "$$\n", "\\boldsymbol{X} = \\boldsymbol{U}\\boldsymbol{\\Sigma}\\boldsymbol{V}^T\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "As an example, the above defective matrix can be decomposed as" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "$$\n", "\\boldsymbol{X} = \\frac{1}{\\sqrt{2}}\\begin{bmatrix} 1& 1 \\\\ 1& -1\\\\ \\end{bmatrix} \\begin{bmatrix} 2& 0 \\\\ 0& 0\\\\ \\end{bmatrix} \\frac{1}{\\sqrt{2}}\\begin{bmatrix} 1& -1 \\\\ 1& 1\\\\ \\end{bmatrix}=\\boldsymbol{U}\\boldsymbol{\\Sigma}\\boldsymbol{V}^T,\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "with eigenvalues $\\sigma_1=2$ and $\\sigma_2=0$. \n", "The SVD exits always! \n", "\n", "\n", "\n", "## Another Example\n", "\n", "Consider the following matrix which can be SVD decomposed as" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "$$\n", "\\boldsymbol{X} = \\frac{1}{15}\\begin{bmatrix} 14 & 2\\\\ 4 & 22\\\\ 16 & 13\\end{matrix}=\\frac{1}{3}\\begin{bmatrix} 1& 2 & 2 \\\\ 2& -1 & 1\\\\ 2 & 1& -2\\end{bmatrix} \\begin{bmatrix} 2& 0 \\\\ 0& 1\\\\ 0 & 0\\end{bmatrix}\\frac{1}{5}\\begin{bmatrix} 3& 4 \\\\ 4& -3\\end{bmatrix}=\\boldsymbol{U}\\boldsymbol{\\Sigma}\\boldsymbol{V}^T.\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "This is a $3\\times 2$ matrix which is decomposed in terms of a\n", "$3\\times 3$ matrix $\\boldsymbol{U}$, and a $2\\times 2$ matrix $\\boldsymbol{V}$. It is easy to see\n", "that $\\boldsymbol{U}$ and $\\boldsymbol{V}$ are orthogonal (how?). \n", "\n", "And the SVD\n", "decomposition (singular values) gives eigenvalues \n", "$\\sigma_i\\geq\\sigma_{i+1}$ for all $i$ and for dimensions larger than $i=2$, the\n", "eigenvalues (singular values) are zero.\n", "\n", "In the general case, where our design matrix $\\boldsymbol{X}$ has dimension\n", "$n\\times p$, the matrix is thus decomposed into an $n\\times n$\n", "orthogonal matrix $\\boldsymbol{U}$, a $p\\times p$ orthogonal matrix $\\boldsymbol{V}$\n", "and a diagonal matrix $\\boldsymbol{\\Sigma}$ with $r=\\mathrm{min}(n,p)$\n", "singular values $\\sigma_i\\lg 0$ on the main diagonal and zeros filling\n", "the rest of the matrix. There are at most $p$ singular values\n", "assuming that $n > p$. In our regression examples for the nuclear\n", "masses and the equation of state this is indeed the case, while for\n", "the Ising model we have $p > n$. These are often cases that lead to\n", "near singular or singular matrices.\n", "\n", "The columns of $\\boldsymbol{U}$ are called the left singular vectors while the columns of $\\boldsymbol{V}$ are the right singular vectors.\n", "\n", "\n", "## Economy-size SVD\n", "\n", "If we assume that $n > p$, then our matrix $\\boldsymbol{U}$ has dimension $n\n", "\\times n$. The last $n-p$ columns of $\\boldsymbol{U}$ become however\n", "irrelevant in our calculations since they are multiplied with the\n", "zeros in $\\boldsymbol{\\Sigma}$.\n", "\n", "The economy-size decomposition removes extra rows or columns of zeros\n", "from the diagonal matrix of singular values, $\\boldsymbol{\\Sigma}$, along with the columns\n", "in either $\\boldsymbol{U}$ or $\\boldsymbol{V}$ that multiply those zeros in the expression. \n", "Removing these zeros and columns can improve execution time\n", "and reduce storage requirements without compromising the accuracy of\n", "the decomposition.\n", "\n", "If $n > p$, we keep only the first $p$ columns of $\\boldsymbol{U}$ and $\\boldsymbol{\\Sigma}$ has dimension $p\\times p$. \n", "If $p > n$, then only the first $n$ columns of $\\boldsymbol{V}$ are computed and $\\boldsymbol{\\Sigma}$ has dimension $n\\times n$.\n", "The $n=p$ case is obvious, we retain the full SVD. \n", "In general the economy-size SVD leads to less FLOPS and still conserving the desired accuracy.\n", "\n", "\n", "## Mathematical Properties\n", "\n", "There are several interesting mathematical properties which will be\n", "relevant when we are going to discuss the differences between say\n", "ordinary least squares (OLS) and **Ridge** regression.\n", "\n", "We have from OLS that the parameters of the linear approximation are given by" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "$$\n", "\\boldsymbol{\\tilde{y}} = \\boldsymbol{X}\\boldsymbol{\\beta} = \\boldsymbol{X}\\left(\\boldsymbol{X}^T\\boldsymbol{X}\\right)^{-1}\\boldsymbol{X}^T\\boldsymbol{y}.\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "The matrix to invert can be rewritten in terms of our SVD decomposition as" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "$$\n", "\\boldsymbol{X}^T\\boldsymbol{X} = \\boldsymbol{V}\\boldsymbol{\\Sigma}^T\\boldsymbol{U}^T\\boldsymbol{U}\\boldsymbol{\\Sigma}\\boldsymbol{V}^T.\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Using the orthogonality properties of $\\boldsymbol{U}$ we have" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "$$\n", "\\boldsymbol{X}^T\\boldsymbol{X} = \\boldsymbol{V}\\boldsymbol{\\Sigma}^T\\boldsymbol{\\Sigma}\\boldsymbol{V}^T = \\boldsymbol{V}\\boldsymbol{D}\\boldsymbol{V}^T,\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "with $\\boldsymbol{D}$ being a diagonal matrix with values along the diagonal given by the singular values squared. \n", "\n", "This means that" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "$$\n", "(\\boldsymbol{X}^T\\boldsymbol{X})\\boldsymbol{V} = \\boldsymbol{V}\\boldsymbol{D},\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "that is the eigenvectors of $(\\boldsymbol{X}^T\\boldsymbol{X})$ are given by the columns of the right singular matrix of $\\boldsymbol{X}$ and the eigenvalues are the squared singular values. It is easy to show (show this) that" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "$$\n", "(\\boldsymbol{X}\\boldsymbol{X}^T)\\boldsymbol{U} = \\boldsymbol{U}\\boldsymbol{D},\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "that is, the eigenvectors of $(\\boldsymbol{X}\\boldsymbol{X})^T$ are the columns of the left singular matrix and the eigenvalues are the same. \n", "\n", "Going back to our OLS equation we have" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "$$\n", "\\boldsymbol{X}\\boldsymbol{\\beta} = \\boldsymbol{X}\\left(\\boldsymbol{V}\\boldsymbol{D}\\boldsymbol{V}^T \\right)^{-1}\\boldsymbol{X}^T\\boldsymbol{y}=\\boldsymbol{U\\Sigma V^T}\\left(\\boldsymbol{V}\\boldsymbol{D}\\boldsymbol{V}^T \\right)^{-1}(\\boldsymbol{U\\Sigma V^T})^T\\boldsymbol{y}=\\boldsymbol{U}\\boldsymbol{U}^T\\boldsymbol{y}.\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "We will come back to this expression when we discuss Ridge regression. \n", "\n", "\n", "\n", "## Ridge and LASSO Regression\n", "\n", "Let us remind ourselves about the expression for the standard Mean Squared Error (MSE) which we used to define our cost function and the equations for the ordinary least squares (OLS) method, that is \n", "our optimization problem is" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "$$\n", "{\\displaystyle \\min_{\\boldsymbol{\\beta}\\in {\\mathbb{R}}^{p}}}\\frac{1}{n}\\left\\{\\left(\\boldsymbol{y}-\\boldsymbol{X}\\boldsymbol{\\beta}\\right)^T\\left(\\boldsymbol{y}-\\boldsymbol{X}\\boldsymbol{\\beta}\\right)\\right\\}.\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "or we can state it as" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "$$\n", "{\\displaystyle \\min_{\\boldsymbol{\\beta}\\in\n", "{\\mathbb{R}}^{p}}}\\frac{1}{n}\\sum_{i=0}^{n-1}\\left(y_i-\\tilde{y}_i\\right)^2=\\frac{1}{n}\\vert\\vert \\boldsymbol{y}-\\boldsymbol{X}\\boldsymbol{\\beta}\\vert\\vert_2^2,\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "where we have used the definition of a norm-2 vector, that is" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "$$\n", "\\vert\\vert \\boldsymbol{x}\\vert\\vert_2 = \\sqrt{\\sum_i x_i^2}.\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "By minimizing the above equation with respect to the parameters\n", "$\\boldsymbol{\\beta}$ we could then obtain an analytical expression for the\n", "parameters $\\boldsymbol{\\beta}$. We can add a regularization parameter $\\lambda$ by\n", "defining a new cost function to be optimized, that is" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "$$\n", "{\\displaystyle \\min_{\\boldsymbol{\\beta}\\in\n", "{\\mathbb{R}}^{p}}}\\frac{1}{n}\\vert\\vert \\boldsymbol{y}-\\boldsymbol{X}\\boldsymbol{\\beta}\\vert\\vert_2^2+\\lambda\\vert\\vert \\boldsymbol{\\beta}\\vert\\vert_2^2\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "which leads to the Ridge regression minimization problem where we\n", "require that $\\vert\\vert \\boldsymbol{\\beta}\\vert\\vert_2^2\\le t$, where $t$ is\n", "a finite number larger than zero. By defining" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "$$\n", "C(\\boldsymbol{X},\\boldsymbol{\\beta})=\\frac{1}{n}\\vert\\vert \\boldsymbol{y}-\\boldsymbol{X}\\boldsymbol{\\beta}\\vert\\vert_2^2+\\lambda\\vert\\vert \\boldsymbol{\\beta}\\vert\\vert_1,\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "we have a new optimization equation" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "$$\n", "{\\displaystyle \\min_{\\boldsymbol{\\beta}\\in\n", "{\\mathbb{R}}^{p}}}\\frac{1}{n}\\vert\\vert \\boldsymbol{y}-\\boldsymbol{X}\\boldsymbol{\\beta}\\vert\\vert_2^2+\\lambda\\vert\\vert \\boldsymbol{\\beta}\\vert\\vert_1\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "which leads to Lasso regression. Lasso stands for least absolute shrinkage and selection operator. \n", "\n", "Here we have defined the norm-1 as" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "$$\n", "\\vert\\vert \\boldsymbol{x}\\vert\\vert_1 = \\sum_i \\vert x_i\\vert.\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Using the matrix-vector expression for Ridge regression," ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "$$\n", "C(\\boldsymbol{X},\\boldsymbol{\\beta})=\\frac{1}{n}\\left\\{(\\boldsymbol{y}-\\boldsymbol{X}\\boldsymbol{\\beta})^T(\\boldsymbol{y}-\\boldsymbol{X}\\boldsymbol{\\beta})\\right\\}+\\lambda\\boldsymbol{\\beta}^T\\boldsymbol{\\beta},\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "by taking the derivatives with respect to $\\boldsymbol{\\beta}$ we obtain then\n", "a slightly modified matrix inversion problem which for finite values\n", "of $\\lambda$ does not suffer from singularity problems. We obtain" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "$$\n", "\\boldsymbol{\\beta}^{\\mathrm{Ridge}} = \\left(\\boldsymbol{X}^T\\boldsymbol{X}+\\lambda\\boldsymbol{I}\\right)^{-1}\\boldsymbol{X}^T\\boldsymbol{y},\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "with $\\boldsymbol{I}$ being a $p\\times p$ identity matrix with the constraint that" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "$$\n", "\\sum_{i=0}^{p-1} \\beta_i^2 \\leq t,\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "with $t$ a finite positive number. \n", "\n", "We see that Ridge regression is nothing but the standard\n", "OLS with a modified diagonal term added to $\\boldsymbol{X}^T\\boldsymbol{X}$. The\n", "consequences, in particular for our discussion of the bias-variance\n", "are rather interesting.\n", "\n", "Furthermore, if we use the result above in terms of the SVD decomposition (our analysis was done for the OLS method), we had" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "$$\n", "(\\boldsymbol{X}\\boldsymbol{X}^T)\\boldsymbol{U} = \\boldsymbol{U}\\boldsymbol{D}.\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "We can analyse the OLS solutions in terms of the eigenvectors (the columns) of the right singular value matrix $\\boldsymbol{U}$ as" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "$$\n", "\\boldsymbol{X}\\boldsymbol{\\beta} = \\boldsymbol{X}\\left(\\boldsymbol{V}\\boldsymbol{D}\\boldsymbol{V}^T \\right)^{-1}\\boldsymbol{X}^T\\boldsymbol{y}=\\boldsymbol{U\\Sigma V^T}\\left(\\boldsymbol{V}\\boldsymbol{D}\\boldsymbol{V}^T \\right)^{-1}(\\boldsymbol{U\\Sigma V^T})^T\\boldsymbol{y}=\\boldsymbol{U}\\boldsymbol{U}^T\\boldsymbol{y}\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "For Ridge regression this becomes" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "$$\n", "\\boldsymbol{X}\\boldsymbol{\\beta}^{\\mathrm{Ridge}} = \\boldsymbol{U\\Sigma V^T}\\left(\\boldsymbol{V}\\boldsymbol{D}\\boldsymbol{V}^T+\\lambda\\boldsymbol{I} \\right)^{-1}(\\boldsymbol{U\\Sigma V^T})^T\\boldsymbol{y}=\\sum_{j=0}^{p-1}\\boldsymbol{u}_j\\boldsymbol{u}_j^T\\frac{\\sigma_j^2}{\\sigma_j^2+\\lambda}\\boldsymbol{y},\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "with the vectors $\\boldsymbol{u}_j$ being the columns of $\\boldsymbol{U}$. \n", "\n", "## Interpreting the Ridge results\n", "\n", "Since $\\lambda \\geq 0$, it means that compared to OLS, we have" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "$$\n", "\\frac{\\sigma_j^2}{\\sigma_j^2+\\lambda} \\leq 1.\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Ridge regression finds the coordinates of $\\boldsymbol{y}$ with respect to the\n", "orthonormal basis $\\boldsymbol{U}$, it then shrinks the coordinates by\n", "$\\frac{\\sigma_j^2}{\\sigma_j^2+\\lambda}$. Recall that the SVD has\n", "eigenvalues ordered in a descending way, that is $\\sigma_i \\geq\n", "\\sigma_{i+1}$.\n", "\n", "For small eigenvalues $\\sigma_i$ it means that their contributions become less important, a fact which can be used to reduce the number of degrees of freedom.\n", "Actually, calculating the variance of $\\boldsymbol{X}\\boldsymbol{v}_j$ shows that this quantity is equal to $\\sigma_j^2/n$.\n", "With a parameter $\\lambda$ we can thus shrink the role of specific parameters. \n", "\n", "\n", "For the sake of simplicity, let us assume that the design matrix is orthonormal, that is" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "$$\n", "\\boldsymbol{X}^T\\boldsymbol{X}=(\\boldsymbol{X}^T\\boldsymbol{X})^{-1} =\\boldsymbol{I}.\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "In this case the standard OLS results in" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "$$\n", "\\boldsymbol{\\beta}^{\\mathrm{OLS}} = \\boldsymbol{X}^T\\boldsymbol{y}=\\sum_{i=0}^{p-1}\\boldsymbol{u}_j\\boldsymbol{u}_j^T\\boldsymbol{y},\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "and" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "$$\n", "\\boldsymbol{\\beta}^{\\mathrm{Ridge}} = \\left(\\boldsymbol{I}+\\lambda\\boldsymbol{I}\\right)^{-1}\\boldsymbol{X}^T\\boldsymbol{y}=\\left(1+\\lambda\\right)^{-1}\\boldsymbol{\\beta}^{\\mathrm{OLS}},\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "that is the Ridge estimator scales the OLS estimator by the inverse of a factor $1+\\lambda$, and\n", "the Ridge estimator converges to zero when the hyperparameter goes to\n", "infinity.\n", "\n", "We will come back to more interpreations after we have gone through some of the statistical analysis part. \n", "\n", "For more discussions of Ridge and Lasso regression, [Wessel van Wieringen's](https://arxiv.org/abs/1509.09169) article is highly recommended.\n", "Similarly, [Mehta et al's article](https://arxiv.org/abs/1803.08823) is also recommended.\n", "\n", "## Where are we going?\n", "\n", "Before we proceed, we need to rethink what we have been doing. In our\n", "eager to fit the data, we have omitted several important elements in\n", "our regression analysis. In what follows we will\n", "1. look at statistical properties, including a discussion of mean values, variance and the so-called bias-variance tradeoff\n", "\n", "2. introduce resampling techniques like cross-validation, bootstrapping and jackknife and more\n", "\n", "This will allow us to link the standard linear algebra methods we have discussed above to a statistical interpretation of the methods. \n", "\n", "\n", "\n", "## 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", "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", "## Why resampling methods ?\n", "\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", "* 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", "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": [ "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": [ "A special version of the moments is the set of *central moments*,\n", "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", "
\n", "\n", "$$\n", "\\begin{equation}\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", "\\label{_auto8} \\tag{8}\n", "\\end{equation}\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "\n", "
\n", "\n", "$$\n", "\\begin{equation} \n", " = \\int\\! \\left(x^2 - 2 x \\langle x\\rangle^{2} +\n", " \\langle x\\rangle^2\\right)p(x)\\,dx\n", "\\label{_auto9} \\tag{9}\n", "\\end{equation}\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "\n", "
\n", "\n", "$$\n", "\\begin{equation} \n", " = \\langle x^2\\rangle - 2 \\langle x\\rangle\\langle x\\rangle + \\langle x\\rangle^2\n", "\\label{_auto10} \\tag{10}\n", "\\end{equation}\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "\n", "
\n", "\n", "$$\n", "\\begin{equation} \n", " = \\langle x^2\\rangle - \\langle x\\rangle^2\n", "\\label{_auto11} \\tag{11}\n", "\\end{equation}\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "The square root of the variance, $\\sigma =\\sqrt{\\langle (x-\\langle x\\rangle)^2\\rangle}$ is called the *standard deviation* of $p$. It is clearly just 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", "## Statistics, covariance\n", "\n", "Another important quantity is the so called covariance, a variant of\n", "the above defined variance. Consider again 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", "\\mathrm{cov}(X_i,\\,X_j) \\equiv \\langle (x_i-\\langle x_i\\rangle)(x_j-\\langle x_j\\rangle)\\rangle\n", "\\nonumber\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "\n", "
\n", "\n", "$$\n", "\\begin{equation} \n", "=\n", "\\int\\!\\cdots\\!\\int\\!(x_i-\\langle x_i \\rangle)(x_j-\\langle x_j \\rangle)\\,\n", "P(x_1,\\dots,x_n)\\,dx_1\\dots dx_n\n", "\\label{eq:def_covariance} \\tag{12}\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": [ "If we consider the above covariance as a matrix $C_{ij}=\\mathrm{cov}(X_i,\\,X_j)$, 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. This is easy to show, keeping in mind the linearity of\n", "the expectation value. Consider the stochastic variables $X_i$ and\n", "$X_j$, ($i\\neq j$):" ] }, { "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{_auto12} \\tag{13}\n", "\\end{equation}\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "\n", "
\n", "\n", "$$\n", "\\begin{equation} \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", "\\label{_auto13} \\tag{14}\n", "\\end{equation}\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "\n", "
\n", "\n", "$$\n", "\\begin{equation} \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", "\\label{_auto14} \\tag{15}\n", "\\end{equation}\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "\n", "
\n", "\n", "$$\n", "\\begin{equation} \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", "\\label{_auto15} \\tag{16}\n", "\\end{equation}\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "\n", "
\n", "\n", "$$\n", "\\begin{equation} \n", "=\\langle x_i x_j\\rangle - \\langle x_i\\rangle\\langle x_j\\rangle\n", "\\label{_auto16} \\tag{17}\n", "\\end{equation}\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Statistics, independent variables\n", "\n", "If $X_i$ and $X_j$ are independent, we get \n", "$\\langle x_i x_j\\rangle =\\langle x_i\\rangle\\langle x_j\\rangle$, resulting in $\\mathrm{cov}(X_i, X_j) = 0\\ \\ (i\\neq j)$.\n", "\n", "Also useful for us is the covariance of linear combinations of\n", "stochastic variables. Let $\\{X_i\\}$ and $\\{Y_i\\}$ be two sets of\n", "stochastic variables. Let also $\\{a_i\\}$ and $\\{b_i\\}$ be two sets of\n", "scalars. Consider the linear combination:" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "$$\n", "U = \\sum_i a_i X_i \\qquad V = \\sum_j b_j Y_j\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "By the linearity of the expectation value" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "$$\n", "\\mathrm{cov}(U, V) = \\sum_{i,j}a_i b_j \\mathrm{cov}(X_i, Y_j)\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Now, since the variance is just $\\mathrm{var}(X_i) = \\mathrm{cov}(X_i, X_i)$, we get\n", "the variance of the linear combination $U = \\sum_i a_i X_i$:" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "\n", "
\n", "\n", "$$\n", "\\begin{equation}\n", "\\mathrm{var}(U) = \\sum_{i,j}a_i a_j \\mathrm{cov}(X_i, X_j)\n", "\\label{eq:variance_linear_combination} \\tag{18}\n", "\\end{equation}\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "And in the special case when the stochastic variables are\n", "uncorrelated, the off-diagonal elements of the covariance are as we\n", "know zero, resulting in:" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "1\n", "3\n", "4\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", "\\mathrm{var}(\\sum_i a_i X_i) = \\sum_i a_i^2 \\mathrm{var}(X_i)\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "which will become very useful in our study of the error in the mean\n", "value of a set of measurements.\n", "\n", "## Statistics and stochastic processes\n", "\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": [ "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", "In practical situations a sample is always of finite size. Let that\n", "size be $n$. The expectation value of a sample, the *sample mean*, is then defined as follows:" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "$$\n", "\\bar{x}_n \\equiv \\frac{1}{n}\\sum_{k=1}^n x_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_k - \\bar{x}_n)^2\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "its square root being the *standard deviation of the sample*. The\n", "*sample covariance* is:" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "$$\n", "\\mathrm{cov}(x)\\equiv\\frac{1}{n}\\sum_{kl}(x_k - \\bar{x}_n)(x_l - \\bar{x}_n)\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Note that the sample variance is the sample covariance without the\n", "cross terms. In a similar manner as the covariance in Eq. ([12](#eq:def_covariance)) is a measure of the correlation between\n", "two stochastic variables, the above defined sample covariance is a\n", "measure of the sequential correlation between succeeding measurements\n", "of a sample.\n", "\n", "These quantities, being known experimental values, differ\n", "significantly from and must not be confused with the similarly named\n", "quantities for stochastic variables, mean $\\mu_X$, variance $\\mathrm{var}(X)$\n", "and covariance $\\mathrm{cov}(X,Y)$.\n", "\n", "The law of large numbers\n", "states that as the size of our sample grows to infinity, the sample\n", "mean approaches the true mean $\\mu_X^{\\phantom X}$ of the chosen PDF:" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "$$\n", "\\lim_{n\\to\\infty}\\bar{x}_n = \\mu_X^{\\phantom X}\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "The sample mean $\\bar{x}_n$ works therefore as an estimate of the true\n", "mean $\\mu_X^{\\phantom X}$.\n", "\n", "What we need to find out is how good an approximation $\\bar{x}_n$ is to\n", "$\\mu_X^{\\phantom X}$. In any stochastic measurement, an estimated\n", "mean is of no use to us without a measure of its error. A quantity\n", "that tells us how well we can reproduce it in another experiment. We\n", "are therefore interested in the PDF of the sample mean itself. Its\n", "standard deviation will be a measure of the spread of sample means,\n", "and we will simply call it the *error* of the sample mean, or\n", "just sample error, and denote it by $\\mathrm{err}_X^{\\phantom X}$. In\n", "practice, we will only be able to produce an *estimate* of the\n", "sample error since the exact value would require the knowledge of the\n", "true PDFs behind, which we usually do not have.\n", "\n", "## Statistics, more on sample error\n", "\n", "Let us first take a look at what happens to the sample error as the\n", "size of the sample grows. In a sample, each of the measurements $x_i$\n", "can be associated with its own stochastic variable $X_i$. The\n", "stochastic variable $\\overline X_n$ for the sample mean $\\bar{x}_n$ is\n", "then just a linear combination, already familiar to us:" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "$$\n", "\\overline X_n = \\frac{1}{n}\\sum_{i=1}^n X_i\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "All the coefficients are just equal $1/n$. The PDF of $\\overline X_n$,\n", "denoted by $p_{\\overline X_n}(x)$ is the desired PDF of the sample\n", "means. \n", "\n", "The probability density of obtaining a sample mean $\\bar x_n$\n", "is the product of probabilities of obtaining arbitrary values $x_1,\n", "x_2,\\dots,x_n$ with the constraint that the mean of the set $\\{x_i\\}$\n", "is $\\bar x_n$:" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "$$\n", "p_{\\overline X_n}(x) = \\int p_X^{\\phantom X}(x_1)\\cdots\n", "\\int p_X^{\\phantom X}(x_n)\\ \n", "\\delta\\!\\left(x - \\frac{x_1+x_2+\\dots+x_n}{n}\\right)dx_n \\cdots dx_1\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "And in particular we are interested in its variance $\\mathrm{var}(\\overline X_n)$.\n", "\n", "## Statistics, central limit theorem\n", "\n", "It is generally not possible to express $p_{\\overline X_n}(x)$ in a\n", "closed form given an arbitrary PDF $p_X^{\\phantom X}$ and a number\n", "$n$. But for the limit $n\\to\\infty$ it is possible to make an\n", "approximation. The very important result is called *the central limit theorem*. It tells us that as $n$ goes to infinity,\n", "$p_{\\overline X_n}(x)$ approaches a Gaussian distribution whose mean\n", "and variance equal the true mean and variance, $\\mu_{X}^{\\phantom X}$\n", "and $\\sigma_{X}^{2}$, respectively:" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "\n", "
\n", "\n", "$$\n", "\\begin{equation}\n", "\\lim_{n\\to\\infty} p_{\\overline X_n}(x) =\n", "\\left(\\frac{n}{2\\pi\\mathrm{var}(X)}\\right)^{1/2}\n", "e^{-\\frac{n(x-\\bar x_n)^2}{2\\mathrm{var}(X)}}\n", "\\label{eq:central_limit_gaussian} \\tag{19}\n", "\\end{equation}\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "The desired variance\n", "$\\mathrm{var}(\\overline X_n)$, i.e. the sample error squared\n", "$\\mathrm{err}_X^2$, is given by:" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "\n", "
\n", "\n", "$$\n", "\\begin{equation}\n", "\\mathrm{err}_X^2 = \\mathrm{var}(\\overline X_n) = \\frac{1}{n^2}\n", "\\sum_{ij} \\mathrm{cov}(X_i, X_j)\n", "\\label{eq:error_exact} \\tag{20}\n", "\\end{equation}\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "We see now that in order to calculate the exact error of the sample\n", "with the above expression, we would need the true means\n", "$\\mu_{X_i}^{\\phantom X}$ of the stochastic variables $X_i$. To\n", "calculate these requires that we know the true multivariate PDF of all\n", "the $X_i$. But this PDF is unknown to us, we have only got the measurements of\n", "one sample. The best we can do is to let the sample itself be an\n", "estimate of the PDF of each of the $X_i$, estimating all properties of\n", "$X_i$ through the measurements of the sample.\n", "\n", "Our estimate of $\\mu_{X_i}^{\\phantom X}$ is then the sample mean $\\bar x$\n", "itself, in accordance with the the central limit theorem:" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "$$\n", "\\mu_{X_i}^{\\phantom X} = \\langle x_i\\rangle \\approx \\frac{1}{n}\\sum_{k=1}^n x_k = \\bar x\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Using $\\bar x$ in place of $\\mu_{X_i}^{\\phantom X}$ we can give an\n", "*estimate* of the covariance in Eq. ([20](#eq:error_exact))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "$$\n", "\\mathrm{cov}(X_i, X_j) = \\langle (x_i-\\langle x_i\\rangle)(x_j-\\langle x_j\\rangle)\\rangle\n", "\\approx\\langle (x_i - \\bar x)(x_j - \\bar{x})\\rangle,\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "resulting in" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "$$\n", "\\frac{1}{n} \\sum_{l}^n \\left(\\frac{1}{n}\\sum_{k}^n (x_k -\\bar x_n)(x_l - \\bar x_n)\\right)=\\frac{1}{n}\\frac{1}{n} \\sum_{kl} (x_k -\\bar x_n)(x_l - \\bar x_n)=\\frac{1}{n}\\mathrm{cov}(x)\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "By the same procedure we can use the sample variance as an\n", "estimate of the variance of any of the stochastic variables $X_i$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "$$\n", "\\mathrm{var}(X_i)=\\langle x_i - \\langle x_i\\rangle\\rangle \\approx \\langle x_i - \\bar x_n\\rangle\\nonumber,\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "which is approximated as" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "\n", "
\n", "\n", "$$\n", "\\begin{equation}\n", "\\mathrm{var}(X_i)\\approx \\frac{1}{n}\\sum_{k=1}^n (x_k - \\bar x_n)=\\mathrm{var}(x)\n", "\\label{eq:var_estimate_i_think} \\tag{21}\n", "\\end{equation}\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Now we can calculate an estimate of the error\n", "$\\mathrm{err}_X^{\\phantom X}$ of the sample mean $\\bar x_n$:" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "$$\n", "\\mathrm{err}_X^2\n", "=\\frac{1}{n^2}\\sum_{ij} \\mathrm{cov}(X_i, X_j) \\nonumber\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "$$\n", "\\approx\\frac{1}{n^2}\\sum_{ij}\\frac{1}{n}\\mathrm{cov}(x) =\\frac{1}{n^2}n^2\\frac{1}{n}\\mathrm{cov}(x)\\nonumber\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "\n", "
\n", "\n", "$$\n", "\\begin{equation} \n", "=\\frac{1}{n}\\mathrm{cov}(x)\n", "\\label{eq:error_estimate} \\tag{22}\n", "\\end{equation}\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "which is nothing but the sample covariance divided by the number of\n", "measurements in the sample.\n", "\n", "In the special case that the measurements of the sample are\n", "uncorrelated (equivalently the stochastic variables $X_i$ are\n", "uncorrelated) we have that the off-diagonal elements of the covariance\n", "are zero. This gives the following estimate of the sample error:" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "$$\n", "\\mathrm{err}_X^2=\\frac{1}{n^2}\\sum_{ij} \\mathrm{cov}(X_i, X_j) =\n", "\\frac{1}{n^2} \\sum_i \\mathrm{var}(X_i),\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "resulting in" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "\n", "
\n", "\n", "$$\n", "\\begin{equation}\n", "\\mathrm{err}_X^2\\approx \\frac{1}{n^2} \\sum_i \\mathrm{var}(x)= \\frac{1}{n}\\mathrm{var}(x)\n", "\\label{eq:error_estimate_uncorrel} \\tag{23}\n", "\\end{equation}\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "where in the second step we have used Eq. ([21](#eq:var_estimate_i_think)).\n", "The error of the sample is then just its standard deviation divided by\n", "the square root of the number of measurements the sample contains.\n", "This is a very useful formula which is easy to compute. It acts as a\n", "first approximation to the error, but in numerical experiments, we\n", "cannot overlook the always present correlations.\n", "\n", "For computational purposes one usually splits up the estimate of\n", "$\\mathrm{err}_X^2$, given by Eq. ([22](#eq:error_estimate)), into two\n", "parts" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "$$\n", "\\mathrm{err}_X^2 = \\frac{1}{n}\\mathrm{var}(x) + \\frac{1}{n}(\\mathrm{cov}(x)-\\mathrm{var}(x)),\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "which equals" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "\n", "
\n", "\n", "$$\n", "\\begin{equation}\n", "\\frac{1}{n^2}\\sum_{k=1}^n (x_k - \\bar x_n)^2 +\\frac{2}{n^2}\\sum_{k\n", "
\n", "\n", "$$\n", "\\begin{equation} \n", "=\\frac{\\tau}{n}\\cdot\\mathrm{var}(x)\n", "\\label{eq:error_estimate_corr_time} \\tag{25}\n", "\\end{equation}\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "and we see that $\\mathrm{err}_X$ can be expressed in terms 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{26}\n", "\\end{equation}\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "For a correlation free experiment, $\\tau$\n", "equals 1. From the point of view of\n", "eq. ([25](#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 $\\mathrm{err}_X^2\\approx \\mathrm{var}(x)/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.\n", "\n", "## Linking the regression analysis with a statistical interpretation\n", "\n", "Finally, we are going to discuss several statistical properties which can be obtained in terms of analytical expressions. \n", "The\n", "advantage of doing linear regression is that we actually end up with\n", "analytical expressions for several statistical quantities. \n", "Standard least squares and Ridge regression allow us to\n", "derive quantities like the variance and other expectation values in a\n", "rather straightforward way.\n", "\n", "\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} \\, \\boldsymbol{\\beta}$ is a\n", "non-random scalar. To specify the parameters of the distribution of\n", "$\\mathbf{y}_i$ we need to calculate its first two moments. \n", "\n", "Recall that $\\boldsymbol{X}$ is a matrix of dimensionality $n\\times p$. The\n", "notation above $\\mathbf{X}_{i,\\ast}$ means that we are looking at the\n", "row number $i$ and perform a sum over all values $p$.\n", "\n", "\n", "## Assumptions made\n", "\n", "The assumption we have made here can be summarized as (and this is going to useful when we discuss the bias-variance trade off)\n", "that there exists a function $f(\\boldsymbol{x})$ and a normal distributed error $\\boldsymbol{\\varepsilon}\\sim \\mathcal{N}(0, \\sigma^2)$\n", "which describes our data" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "$$\n", "\\boldsymbol{y} = f(\\boldsymbol{x})+\\boldsymbol{\\varepsilon}\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "We approximate this function with our model from the solution of the linear regression equations, that is our\n", "function $f$ is approximated by $\\boldsymbol{\\tilde{y}}$ where we want to minimize $(\\boldsymbol{y}-\\boldsymbol{\\tilde{y}})^2$, our MSE, with" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "$$\n", "\\boldsymbol{\\tilde{y}} = \\boldsymbol{X}\\boldsymbol{\\beta}.\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "We can calculate the expectation value of $\\boldsymbol{y}$ for a given element $i$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "$$\n", "\\begin{align*} \n", "\\mathbb{E}(y_i) & =\n", "\\mathbb{E}(\\mathbf{X}_{i, \\ast} \\, \\boldsymbol{\\beta}) + \\mathbb{E}(\\varepsilon_i)\n", "\\, \\, \\, = \\, \\, \\, \\mathbf{X}_{i, \\ast} \\, \\beta, \n", "\\end{align*}\n", "$$" ] }, { "cell_type": "markdown", "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} \\, \\boldsymbol{\\beta})^2 \\\\ &\n", "= \\mathbb{E} [ ( \\mathbf{X}_{i, \\ast} \\, \\boldsymbol{\\beta})^2 + 2 \\varepsilon_i\n", "\\mathbf{X}_{i, \\ast} \\, \\boldsymbol{\\beta} + \\varepsilon_i^2 ] - ( \\mathbf{X}_{i,\n", "\\ast} \\, \\beta)^2 \\\\ & = ( \\mathbf{X}_{i, \\ast} \\, \\boldsymbol{\\beta})^2 + 2\n", "\\mathbb{E}(\\varepsilon_i) \\mathbf{X}_{i, \\ast} \\, \\boldsymbol{\\beta} +\n", "\\mathbb{E}(\\varepsilon_i^2 ) - ( \\mathbf{X}_{i, \\ast} \\, \\boldsymbol{\\beta})^2 \n", "\\\\ & = \\mathbb{E}(\\varepsilon_i^2 ) \\, \\, \\, = \\, \\, \\,\n", "\\mbox{Var}(\\varepsilon_i) \\, \\, \\, = \\, \\, \\, \\sigma^2. \n", "\\end{align*}\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Hence, $y_i \\sim \\mathcal{N}( \\mathbf{X}_{i, \\ast} \\, \\boldsymbol{\\beta}, \\sigma^2)$, that is $\\boldsymbol{y}$ follows a normal distribution with \n", "mean value $\\boldsymbol{X}\\boldsymbol{\\beta}$ and variance $\\sigma^2$ (not be confused with the singular values of the SVD). \n", "\n", "\n", "## Expectation value and variance for $\\boldsymbol{\\beta}$\n", "\n", "With the OLS expressions for the parameters $\\boldsymbol{\\beta}$ we can evaluate the expectation value" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "$$\n", "\\mathbb{E}(\\boldsymbol{\\beta}) = \\mathbb{E}[ (\\mathbf{X}^{\\top} \\mathbf{X})^{-1}\\mathbf{X}^{T} \\mathbf{Y}]=(\\mathbf{X}^{T} \\mathbf{X})^{-1}\\mathbf{X}^{T} \\mathbb{E}[ \\mathbf{Y}]=(\\mathbf{X}^{T} \\mathbf{X})^{-1} \\mathbf{X}^{T}\\mathbf{X}\\boldsymbol{\\beta}=\\boldsymbol{\\beta}.\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "This means that the estimator of the regression parameters is unbiased.\n", "\n", "We can also calculate the variance\n", "\n", "The variance of $\\boldsymbol{\\beta}$ is" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "$$\n", "\\begin{eqnarray*}\n", "\\mbox{Var}(\\boldsymbol{\\beta}) & = & \\mathbb{E} \\{ [\\boldsymbol{\\beta} - \\mathbb{E}(\\boldsymbol{\\beta})] [\\boldsymbol{\\beta} - \\mathbb{E}(\\boldsymbol{\\beta})]^{T} \\}\n", "\\\\\n", "& = & \\mathbb{E} \\{ [(\\mathbf{X}^{T} \\mathbf{X})^{-1} \\, \\mathbf{X}^{T} \\mathbf{Y} - \\boldsymbol{\\beta}] \\, [(\\mathbf{X}^{T} \\mathbf{X})^{-1} \\, \\mathbf{X}^{T} \\mathbf{Y} - \\boldsymbol{\\beta}]^{T} \\}\n", "\\\\\n", "% & = & \\mathbb{E} \\{ [(\\mathbf{X}^{T} \\mathbf{X})^{-1} \\, \\mathbf{X}^{T} \\mathbf{Y}] \\, [(\\mathbf{X}^{T} \\mathbf{X})^{-1} \\, \\mathbf{X}^{T} \\mathbf{Y}]^{T} \\} - \\boldsymbol{\\beta} \\, \\boldsymbol{\\beta}^{T}\n", "% \\\\\n", "% & = & \\mathbb{E} \\{ (\\mathbf{X}^{T} \\mathbf{X})^{-1} \\, \\mathbf{X}^{T} \\mathbf{Y} \\, \\mathbf{Y}^{T} \\, \\mathbf{X} \\, (\\mathbf{X}^{T} \\mathbf{X})^{-1} \\} - \\boldsymbol{\\beta} \\, \\boldsymbol{\\beta}^{T}\n", "% \\\\\n", "& = & (\\mathbf{X}^{T} \\mathbf{X})^{-1} \\, \\mathbf{X}^{T} \\, \\mathbb{E} \\{ \\mathbf{Y} \\, \\mathbf{Y}^{T} \\} \\, \\mathbf{X} \\, (\\mathbf{X}^{T} \\mathbf{X})^{-1} - \\boldsymbol{\\beta} \\, \\boldsymbol{\\beta}^{T}\n", "\\\\\n", "& = & (\\mathbf{X}^{T} \\mathbf{X})^{-1} \\, \\mathbf{X}^{T} \\, \\{ \\mathbf{X} \\, \\boldsymbol{\\beta} \\, \\boldsymbol{\\beta}^{T} \\, \\mathbf{X}^{T} + \\sigma^2 \\} \\, \\mathbf{X} \\, (\\mathbf{X}^{T} \\mathbf{X})^{-1} - \\boldsymbol{\\beta} \\, \\boldsymbol{\\beta}^{T}\n", "% \\\\\n", "% & = & (\\mathbf{X}^T \\mathbf{X})^{-1} \\, \\mathbf{X}^T \\, \\mathbf{X} \\, \\boldsymbol{\\beta} \\, \\boldsymbol{\\beta}^T \\, \\mathbf{X}^T \\, \\mathbf{X} \\, (\\mathbf{X}^T % \\mathbf{X})^{-1}\n", "% \\\\\n", "% & & + \\, \\, \\sigma^2 \\, (\\mathbf{X}^T \\mathbf{X})^{-1} \\, \\mathbf{X}^T \\, \\mathbf{X} \\, (\\mathbf{X}^T \\mathbf{X})^{-1} - \\boldsymbol{\\beta} \\boldsymbol{\\beta}^T\n", "\\\\\n", "& = & \\boldsymbol{\\beta} \\, \\boldsymbol{\\beta}^{T} + \\sigma^2 \\, (\\mathbf{X}^{T} \\mathbf{X})^{-1} - \\boldsymbol{\\beta} \\, \\boldsymbol{\\beta}^{T}\n", "\\, \\, \\, = \\, \\, \\, \\sigma^2 \\, (\\mathbf{X}^{T} \\mathbf{X})^{-1},\n", "\\end{eqnarray*}\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "where we have used that $\\mathbb{E} (\\mathbf{Y} \\mathbf{Y}^{T}) =\n", "\\mathbf{X} \\, \\boldsymbol{\\beta} \\, \\boldsymbol{\\beta}^{T} \\, \\mathbf{X}^{T} +\n", "\\sigma^2 \\, \\mathbf{I}_{nn}$. From $\\mbox{Var}(\\boldsymbol{\\beta}) = \\sigma^2\n", "\\, (\\mathbf{X}^{T} \\mathbf{X})^{-1}$, one obtains an estimate of the\n", "variance of the estimate of the $j$-th regression coefficient:\n", "$\\hat{\\sigma}^2 (\\hat{\\beta}_j ) = \\hat{\\sigma}^2 \\sqrt{\n", "[(\\mathbf{X}^{T} \\mathbf{X})^{-1}]_{jj} }$. This may be used to\n", "construct a confidence interval for the estimates.\n", "\n", "\n", "In a similar way, we cna obtain analytical expressions for say the\n", "expectation values of the parameters $\\boldsymbol{\\beta}$ and their variance\n", "when we employ Ridge regression, and thereby a confidence interval. \n", "\n", "It is rather straightforward to show that" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "$$\n", "\\mathbb{E} \\big[ \\boldsymbol{\\beta}^{\\mathrm{Ridge}} \\big]=(\\mathbf{X}^{T} \\mathbf{X} + \\lambda \\mathbf{I}_{pp})^{-1} (\\mathbf{X}^{\\top} \\mathbf{X})\\boldsymbol{\\beta}^{\\mathrm{OLS}}.\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "We see clearly that \n", "$\\mathbb{E} \\big[ \\boldsymbol{\\beta}^{\\mathrm{Ridge}} \\big] \\not= \\boldsymbol{\\beta}^{\\mathrm{OLS}}$ for any $\\lambda > 0$. We say then that the ridge estimator is biased.\n", "\n", "We can also compute the variance as" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "$$\n", "\\mbox{Var}[\\boldsymbol{\\beta}^{\\mathrm{Ridge}}]=\\sigma^2[ \\mathbf{X}^{T} \\mathbf{X} + \\lambda \\mathbf{I} ]^{-1} \\mathbf{X}^{T} \\mathbf{X} \\{ [ \\mathbf{X}^{\\top} \\mathbf{X} + \\lambda \\mathbf{I} ]^{-1}\\}^{T},\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "and it is easy to see that if the parameter $\\lambda$ goes to infinity then the variance of Ridge parameters $\\boldsymbol{\\beta}$ goes to zero. \n", "\n", "With this, we can compute the difference" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "$$\n", "\\mbox{Var}[\\boldsymbol{\\beta}^{\\mathrm{OLS}}]-\\mbox{Var}(\\boldsymbol{\\beta}^{\\mathrm{Ridge}})=\\sigma^2 [ \\mathbf{X}^{T} \\mathbf{X} + \\lambda \\mathbf{I} ]^{-1}[ 2\\lambda\\mathbf{I} + \\lambda^2 (\\mathbf{X}^{T} \\mathbf{X})^{-1} ] \\{ [ \\mathbf{X}^{T} \\mathbf{X} + \\lambda \\mathbf{I} ]^{-1}\\}^{T}.\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "The difference is non-negative definite since each component of the\n", "matrix product is non-negative definite. \n", "This means the variance we obtain with the standard OLS will always for $\\lambda > 0$ be larger than the variance of $\\boldsymbol{\\beta}$ obtained with the Ridge estimator. This has interesting consequences when we discuss the so-called bias-variance trade-off below. \n", "\n", "\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.\n", "\n", "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 \n", "*training 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 $\\boldsymbol{\\sigma}_{-i}^2(\\lambda)$, as" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "$$\n", "\\begin{align*}\n", "\\boldsymbol{\\beta}_{-i}(\\lambda) & = ( \\boldsymbol{X}_{-i, \\ast}^{T}\n", "\\boldsymbol{X}_{-i, \\ast} + \\lambda \\boldsymbol{I}_{pp})^{-1}\n", "\\boldsymbol{X}_{-i, \\ast}^{T} \\boldsymbol{y}_{-i}\n", "\\end{align*}\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "* Evaluate the prediction performance of these models on the test set by $\\log\\{L[y_i, \\boldsymbol{X}_{i, \\ast}; \\boldsymbol{\\beta}_{-i}(\\lambda), \\boldsymbol{\\sigma}_{-i}^2(\\lambda)]\\}$. Or, by the prediction error $|y_i - \\boldsymbol{X}_{i, \\ast} \\boldsymbol{\\beta}_{-i}(\\lambda)|$, the relative error, the error squared or the R2 score function.\n", "\n", "* Repeat the first three steps such that each sample plays the role of the test set once.\n", "\n", "* Average the prediction performances of the test sets at each grid point of the penalty bias/parameter 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}; \\boldsymbol{\\beta}_{-i}(\\lambda), \\boldsymbol{\\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", "## 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 where we systematically leave out one observation from the vector of observed values $\\boldsymbol{x} = (x_1,x_2,\\cdots,X_n)$. \n", "Let $\\boldsymbol{x}_i$ denote the vector" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "$$\n", "\\boldsymbol{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 $\\boldsymbol{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", "\n", "## Jackknife code example" ] }, { "cell_type": "code", "execution_count": 56, "metadata": {}, "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}(\\boldsymbol{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(\\boldsymbol{t})$. The aim of the bootstrap is to\n", "estimate $p(\\boldsymbol{t})$ by the relative frequency of\n", "$\\widehat{\\theta}$. You can think of this as using a histogram\n", "in the place of $p(\\boldsymbol{t})$. If the relative frequency closely\n", "resembles $p(\\vec{t})$, then using numerics, it is straight forward to\n", "estimate all the interesting parameters of $p(\\boldsymbol{t})$ using point\n", "estimators. \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(\\boldsymbol{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", "$\\boldsymbol{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 $\\boldsymbol{x} = (x_1,x_2,\\cdots,x_n)$. \n", "\n", "2. Define a vector $\\boldsymbol{x}^*$ containing the values which were drawn from $\\boldsymbol{x}$. \n", "\n", "3. Using the vector $\\boldsymbol{x}^*$ compute $\\widehat{\\theta}^*$ by evaluating $\\widehat \\theta$ under the observations $\\boldsymbol{x}^*$. \n", "\n", "4. Repeat this process $k$ times. \n", "\n", "When you are done, you can draw a histogram of the relative frequency\n", "of $\\widehat \\theta^*$. This is your estimate of the probability\n", "distribution $p(t)$. Using this probability distribution you can\n", "estimate any statistics thereof. In principle you never draw the\n", "histogram of the relative frequency of $\\widehat{\\theta}^*$. Instead\n", "you use the estimators corresponding to the statistic of interest. For\n", "example, if you are interested in estimating the variance of $\\widehat\n", "\\theta$, apply the etsimator $\\widehat \\sigma^2$ to the values\n", "$\\widehat \\theta ^*$.\n", "\n", "\n", "\n", "## Code example for the Bootstrap method\n", "\n", "The following code starts with a Gaussian distribution with mean value\n", "$\\mu =100$ and variance $\\sigma=15$. We use this to generate the data\n", "used in the bootstrap analysis. The bootstrap analysis returns a data\n", "set after a given number of bootstrap operations (as many as we have\n", "data points). This data set consists of estimated mean values for each\n", "bootstrap operation. The histogram generated by the bootstrap method\n", "shows that the distribution for these mean values is also a Gaussian,\n", "centered around the mean value $\\mu=100$ but with standard deviation\n", "$\\sigma/\\sqrt{n}$, where $n$ is the number of bootstrap samples (in\n", "this case the same as the number of original data points). The value\n", "of the standard deviation is what we expect from the central limit\n", "theorem." ] }, { "cell_type": "code", "execution_count": 57, "metadata": {}, "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", " # 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),mean(t),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 \n", "t = bootstrap(x, stat, datapoints)\n", "# the histogram of the bootstrapped data \n", "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": [ "## Code Example for Cross-validation and $k$-fold Cross-validation\n", "\n", "The code here uses Ridge regression with cross-validation (CV) resampling and $k$-fold CV in order to fit a specific polynomial." ] }, { "cell_type": "code", "execution_count": 58, "metadata": {}, "outputs": [], "source": [ "import numpy as np\n", "import matplotlib.pyplot as plt\n", "from sklearn.model_selection import KFold\n", "from sklearn.linear_model import Ridge\n", "from sklearn.model_selection import cross_val_score\n", "from sklearn.preprocessing import PolynomialFeatures\n", "\n", "# A seed just to ensure that the random numbers are the same for every run.\n", "# Useful for eventual debugging.\n", "np.random.seed(3155)\n", "\n", "# Generate the data.\n", "nsamples = 100\n", "x = np.random.randn(nsamples)\n", "y = 3*x**2 + np.random.randn(nsamples)\n", "\n", "## Cross-validation on Ridge regression using KFold only\n", "\n", "# Decide degree on polynomial to fit\n", "poly = PolynomialFeatures(degree = 6)\n", "\n", "# Decide which values of lambda to use\n", "nlambdas = 500\n", "lambdas = np.logspace(-3, 5, nlambdas)\n", "\n", "# Initialize a KFold instance\n", "k = 5\n", "kfold = KFold(n_splits = k)\n", "\n", "# Perform the cross-validation to estimate MSE\n", "scores_KFold = np.zeros((nlambdas, k))\n", "\n", "i = 0\n", "for lmb in lambdas:\n", " ridge = Ridge(alpha = lmb)\n", " j = 0\n", " for train_inds, test_inds in kfold.split(x):\n", " xtrain = x[train_inds]\n", " ytrain = y[train_inds]\n", "\n", " xtest = x[test_inds]\n", " ytest = y[test_inds]\n", "\n", " Xtrain = poly.fit_transform(xtrain[:, np.newaxis])\n", " ridge.fit(Xtrain, ytrain[:, np.newaxis])\n", "\n", " Xtest = poly.fit_transform(xtest[:, np.newaxis])\n", " ypred = ridge.predict(Xtest)\n", "\n", " scores_KFold[i,j] = np.sum((ypred - ytest[:, np.newaxis])**2)/np.size(ypred)\n", "\n", " j += 1\n", " i += 1\n", "\n", "\n", "estimated_mse_KFold = np.mean(scores_KFold, axis = 1)\n", "\n", "## Cross-validation using cross_val_score from sklearn along with KFold\n", "\n", "# kfold is an instance initialized above as:\n", "# kfold = KFold(n_splits = k)\n", "\n", "estimated_mse_sklearn = np.zeros(nlambdas)\n", "i = 0\n", "for lmb in lambdas:\n", " ridge = Ridge(alpha = lmb)\n", "\n", " X = poly.fit_transform(x[:, np.newaxis])\n", " estimated_mse_folds = cross_val_score(ridge, X, y[:, np.newaxis], scoring='neg_mean_squared_error', cv=kfold)\n", "\n", " # cross_val_score return an array containing the estimated negative mse for every fold.\n", " # we have to the the mean of every array in order to get an estimate of the mse of the model\n", " estimated_mse_sklearn[i] = np.mean(-estimated_mse_folds)\n", "\n", " i += 1\n", "\n", "## Plot and compare the slightly different ways to perform cross-validation\n", "\n", "plt.figure()\n", "\n", "plt.plot(np.log10(lambdas), estimated_mse_sklearn, label = 'cross_val_score')\n", "plt.plot(np.log10(lambdas), estimated_mse_KFold, 'r--', label = 'KFold')\n", "\n", "plt.xlabel('log10(lambda)')\n", "plt.ylabel('mse')\n", "\n", "plt.legend()\n", "\n", "plt.show()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## The bias-variance tradeoff\n", "\n", "\n", "We will discuss the bias-variance tradeoff in the context of\n", "continuous predictions such as regression. However, many of the\n", "intuitions and ideas discussed here also carry over to classification\n", "tasks. Consider a dataset $\\mathcal{L}$ consisting of the data\n", "$\\mathbf{X}_\\mathcal{L}=\\{(y_j, \\boldsymbol{x}_j), j=0\\ldots n-1\\}$. \n", "\n", "Let us assume that the true data is generated from a noisy model" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "$$\n", "\\boldsymbol{y}=f(\\boldsymbol{x}) + \\boldsymbol{\\epsilon}\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "where $\\epsilon$ is normally distributed with mean zero and standard deviation $\\sigma^2$.\n", "\n", "In our derivation of the ordinary least squares method we defined then\n", "an approximation to the function $f$ in terms of the parameters\n", "$\\boldsymbol{\\beta}$ and the design matrix $\\boldsymbol{X}$ which embody our model,\n", "that is $\\boldsymbol{\\tilde{y}}=\\boldsymbol{X}\\boldsymbol{\\beta}$. \n", "\n", "Thereafter we found the parameters $\\boldsymbol{\\beta}$ by optimizing the means squared error via the so-called cost function" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "$$\n", "C(\\boldsymbol{X},\\boldsymbol{\\beta}) =\\frac{1}{n}\\sum_{i=0}^{n-1}(y_i-\\tilde{y}_i)^2=\\mathbb{E}\\left[(\\boldsymbol{y}-\\boldsymbol{\\tilde{y}})^2\\right].\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "We can rewrite this as" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "$$\n", "\\mathbb{E}\\left[(\\boldsymbol{y}-\\boldsymbol{\\tilde{y}})^2\\right]=\\frac{1}{n}\\sum_i(f_i-\\mathbb{E}\\left[\\boldsymbol{\\tilde{y}}\\right])^2+\\frac{1}{n}\\sum_i(\\tilde{y}_i-\\mathbb{E}\\left[\\boldsymbol{\\tilde{y}}\\right])^2+\\sigma^2.\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "The three terms represent the square of the bias of the learning\n", "method, which can be thought of as the error caused by the simplifying\n", "assumptions built into the method. The second term represents the\n", "variance of the chosen model and finally the last terms is variance of\n", "the error $\\boldsymbol{\\epsilon}$.\n", "\n", "To derive this equation, we need to recall that the variance of $\\boldsymbol{y}$ and $\\boldsymbol{\\epsilon}$ are both equal to $\\sigma^2$. The mean value of $\\boldsymbol{\\epsilon}$ is by definition equal to zero. Furthermore, the function $f$ is not a stochastics variable, idem for $\\boldsymbol{\\tilde{y}}$.\n", "We use a more compact notation in terms of the expectation value" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "$$\n", "\\mathbb{E}\\left[(\\boldsymbol{y}-\\boldsymbol{\\tilde{y}})^2\\right]=\\mathbb{E}\\left[(\\boldsymbol{f}+\\boldsymbol{\\epsilon}-\\boldsymbol{\\tilde{y}})^2\\right],\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "and adding and subtracting $\\mathbb{E}\\left[\\boldsymbol{\\tilde{y}}\\right]$ we get" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "$$\n", "\\mathbb{E}\\left[(\\boldsymbol{y}-\\boldsymbol{\\tilde{y}})^2\\right]=\\mathbb{E}\\left[(\\boldsymbol{f}+\\boldsymbol{\\epsilon}-\\boldsymbol{\\tilde{y}}+\\mathbb{E}\\left[\\boldsymbol{\\tilde{y}}\\right]-\\mathbb{E}\\left[\\boldsymbol{\\tilde{y}}\\right])^2\\right],\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "which, using the abovementioned expectation values can be rewritten as" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "$$\n", "\\mathbb{E}\\left[(\\boldsymbol{y}-\\boldsymbol{\\tilde{y}})^2\\right]=\\mathbb{E}\\left[(\\boldsymbol{y}-\\mathbb{E}\\left[\\boldsymbol{\\tilde{y}}\\right])^2\\right]+\\mathrm{Var}\\left[\\boldsymbol{\\tilde{y}}\\right]+\\sigma^2,\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "that is the rewriting in terms of the so-called bias, the variance of the model $\\boldsymbol{\\tilde{y}}$ and the variance of $\\boldsymbol{\\epsilon}$.\n", "\n", "\n", "\n", "\n", "\n", "## Example code for Bias-Variance tradeoff" ] }, { "cell_type": "code", "execution_count": 59, "metadata": {}, "outputs": [], "source": [ "import matplotlib.pyplot as plt\n", "import numpy as np\n", "from sklearn.linear_model import LinearRegression, Ridge, Lasso\n", "from sklearn.preprocessing import PolynomialFeatures\n", "from sklearn.model_selection import train_test_split\n", "from sklearn.pipeline import make_pipeline\n", "from sklearn.utils import resample\n", "\n", "np.random.seed(2018)\n", "\n", "n = 500\n", "n_boostraps = 100\n", "degree = 18 # A quite high value, just to show.\n", "noise = 0.1\n", "\n", "# Make data set.\n", "x = np.linspace(-1, 3, n).reshape(-1, 1)\n", "y = np.exp(-x**2) + 1.5 * np.exp(-(x-2)**2) + np.random.normal(0, 0.1, x.shape)\n", "\n", "# Hold out some test data that is never used in training.\n", "x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.2)\n", "\n", "# Combine x transformation and model into one operation.\n", "# Not neccesary, but convenient.\n", "model = make_pipeline(PolynomialFeatures(degree=degree), LinearRegression(fit_intercept=False))\n", "\n", "# The following (m x n_bootstraps) matrix holds the column vectors y_pred\n", "# for each bootstrap iteration.\n", "y_pred = np.empty((y_test.shape[0], n_boostraps))\n", "for i in range(n_boostraps):\n", " x_, y_ = resample(x_train, y_train)\n", "\n", " # Evaluate the new model on the same test data each time.\n", " y_pred[:, i] = model.fit(x_, y_).predict(x_test).ravel()\n", "\n", "# Note: Expectations and variances taken w.r.t. different training\n", "# data sets, hence the axis=1. Subsequent means are taken across the test data\n", "# set in order to obtain a total value, but before this we have error/bias/variance\n", "# calculated per data point in the test set.\n", "# Note 2: The use of keepdims=True is important in the calculation of bias as this \n", "# maintains the column vector form. Dropping this yields very unexpected results.\n", "error = np.mean( np.mean((y_test - y_pred)**2, axis=1, keepdims=True) )\n", "bias = np.mean( (y_test - np.mean(y_pred, axis=1, keepdims=True))**2 )\n", "variance = np.mean( np.var(y_pred, axis=1, keepdims=True) )\n", "print('Error:', error)\n", "print('Bias^2:', bias)\n", "print('Var:', variance)\n", "print('{} >= {} + {} = {}'.format(error, bias, variance, bias+variance))\n", "\n", "plt.plot(x[::5, :], y[::5, :], label='f(x)')\n", "plt.scatter(x_test, y_test, label='Data points')\n", "plt.scatter(x_test, np.mean(y_pred, axis=1), label='Pred')\n", "plt.legend()\n", "plt.show()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Understanding what happens" ] }, { "cell_type": "code", "execution_count": 60, "metadata": {}, "outputs": [], "source": [ "import matplotlib.pyplot as plt\n", "import numpy as np\n", "from sklearn.linear_model import LinearRegression, Ridge, Lasso\n", "from sklearn.preprocessing import PolynomialFeatures\n", "from sklearn.model_selection import train_test_split\n", "from sklearn.pipeline import make_pipeline\n", "from sklearn.utils import resample\n", "\n", "np.random.seed(2018)\n", "\n", "n = 40\n", "n_boostraps = 100\n", "maxdegree = 14\n", "\n", "\n", "# Make data set.\n", "x = np.linspace(-3, 3, n).reshape(-1, 1)\n", "y = np.exp(-x**2) + 1.5 * np.exp(-(x-2)**2)+ np.random.normal(0, 0.1, x.shape)\n", "error = np.zeros(maxdegree)\n", "bias = np.zeros(maxdegree)\n", "variance = np.zeros(maxdegree)\n", "polydegree = np.zeros(maxdegree)\n", "x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.2)\n", "\n", "for degree in range(maxdegree):\n", " model = make_pipeline(PolynomialFeatures(degree=degree), LinearRegression(fit_intercept=False))\n", " y_pred = np.empty((y_test.shape[0], n_boostraps))\n", " for i in range(n_boostraps):\n", " x_, y_ = resample(x_train, y_train)\n", " y_pred[:, i] = model.fit(x_, y_).predict(x_test).ravel()\n", "\n", " polydegree[degree] = degree\n", " error[degree] = np.mean( np.mean((y_test - y_pred)**2, axis=1, keepdims=True) )\n", " bias[degree] = np.mean( (y_test - np.mean(y_pred, axis=1, keepdims=True))**2 )\n", " variance[degree] = np.mean( np.var(y_pred, axis=1, keepdims=True) )\n", " print('Polynomial degree:', degree)\n", " print('Error:', error[degree])\n", " print('Bias^2:', bias[degree])\n", " print('Var:', variance[degree])\n", " print('{} >= {} + {} = {}'.format(error[degree], bias[degree], variance[degree], bias[degree]+variance[degree]))\n", "\n", "plt.plot(polydegree, np.log10(error), label='Error')\n", "plt.plot(polydegree, bias, label='bias')\n", "plt.plot(polydegree, variance, label='Variance')\n", "plt.legend()\n", "plt.show()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Summing up\n", "\n", "\n", "\n", "\n", "The bias-variance tradeoff summarizes the fundamental tension in\n", "machine learning, particularly supervised learning, between the\n", "complexity of a model and the amount of training data needed to train\n", "it. Since data is often limited, in practice it is often useful to\n", "use a less-complex model with higher bias, that is a model whose asymptotic\n", "performance is worse than another model because it is easier to\n", "train and less sensitive to sampling noise arising from having a\n", "finite-sized training dataset (smaller variance). \n", "\n", "\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", "## Another Example rom Scikit-Learn's Repository" ] }, { "cell_type": "code", "execution_count": 61, "metadata": {}, "outputs": [], "source": [ "\"\"\"\n", "============================\n", "Underfitting vs. Overfitting\n", "============================\n", "\n", "This example demonstrates the problems of underfitting and overfitting and\n", "how we can use linear regression with polynomial features to approximate\n", "nonlinear functions. The plot shows the function that we want to approximate,\n", "which is a part of the cosine function. In addition, the samples from the\n", "real function and the approximations of different models are displayed. The\n", "models have polynomial features of different degrees. We can see that a\n", "linear function (polynomial with degree 1) is not sufficient to fit the\n", "training samples. This is called **underfitting**. A polynomial of degree 4\n", "approximates the true function almost perfectly. However, for higher degrees\n", "the model will **overfit** the training data, i.e. it learns the noise of the\n", "training data.\n", "We evaluate quantitatively **overfitting** / **underfitting** by using\n", "cross-validation. We calculate the mean squared error (MSE) on the validation\n", "set, the higher, the less likely the model generalizes correctly from the\n", "training data.\n", "\"\"\"\n", "\n", "print(__doc__)\n", "\n", "import numpy as np\n", "import matplotlib.pyplot as plt\n", "from sklearn.pipeline import Pipeline\n", "from sklearn.preprocessing import PolynomialFeatures\n", "from sklearn.linear_model import LinearRegression\n", "from sklearn.model_selection import cross_val_score\n", "\n", "\n", "def true_fun(X):\n", " return np.cos(1.5 * np.pi * X)\n", "\n", "np.random.seed(0)\n", "\n", "n_samples = 30\n", "degrees = [1, 4, 15]\n", "\n", "X = np.sort(np.random.rand(n_samples))\n", "y = true_fun(X) + np.random.randn(n_samples) * 0.1\n", "\n", "plt.figure(figsize=(14, 5))\n", "for i in range(len(degrees)):\n", " ax = plt.subplot(1, len(degrees), i + 1)\n", " plt.setp(ax, xticks=(), yticks=())\n", "\n", " polynomial_features = PolynomialFeatures(degree=degrees[i],\n", " include_bias=False)\n", " linear_regression = LinearRegression()\n", " pipeline = Pipeline([(\"polynomial_features\", polynomial_features),\n", " (\"linear_regression\", linear_regression)])\n", " pipeline.fit(X[:, np.newaxis], y)\n", "\n", " # Evaluate the models using crossvalidation\n", " scores = cross_val_score(pipeline, X[:, np.newaxis], y,\n", " scoring=\"neg_mean_squared_error\", cv=10)\n", "\n", " X_test = np.linspace(0, 1, 100)\n", " plt.plot(X_test, pipeline.predict(X_test[:, np.newaxis]), label=\"Model\")\n", " plt.plot(X_test, true_fun(X_test), label=\"True function\")\n", " plt.scatter(X, y, edgecolor='b', s=20, label=\"Samples\")\n", " plt.xlabel(\"x\")\n", " plt.ylabel(\"y\")\n", " plt.xlim((0, 1))\n", " plt.ylim((-2, 2))\n", " plt.legend(loc=\"best\")\n", " plt.title(\"Degree {}\\nMSE = {:.2e}(+/- {:.2e})\".format(\n", " degrees[i], -scores.mean(), scores.std()))\n", "plt.show()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## The one-dimensional Ising model\n", "\n", "Let us bring back the Ising model again, but now with an additional\n", "focus on Ridge and Lasso regression as well. We repeat some of the\n", "basic parts of the Ising model and the setup of the training and test\n", "data. The one-dimensional Ising model with nearest neighbor\n", "interaction, no external field and a constant coupling constant $J$ is\n", "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{_auto17} \\tag{27}\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": 62, "metadata": {}, "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": [ "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{_auto18} \\tag{28}\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{_auto19} \\tag{29}\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", " \\boldsymbol{y} = \\boldsymbol{X}\\boldsymbol{\\beta} + \\boldsymbol{\\epsilon}.\n", "\\label{_auto20} \\tag{30}\n", "\\end{equation}\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "We organize the data as we did above" ] }, { "cell_type": "code", "execution_count": 63, "metadata": {}, "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": [ "We will do all fitting with **Scikit-Learn**," ] }, { "cell_type": "code", "execution_count": 64, "metadata": {}, "outputs": [], "source": [ "clf = skl.LinearRegression().fit(X_train, y_train)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "When extracting the $J$-matrix we make sure to remove the intercept" ] }, { "cell_type": "code", "execution_count": 65, "metadata": {}, "outputs": [], "source": [ "J_sk = clf.coef_.reshape(L, L)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "And then we plot the results" ] }, { "cell_type": "code", "execution_count": 66, "metadata": {}, "outputs": [], "source": [ "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": [ "The results perfectly with our previous discussion where we used our own code.\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 $\\boldsymbol{\\beta}$. This results in a penalized regression problem. The\n", "cost function is given by" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "1\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": "code", "execution_count": 67, "metadata": {}, "outputs": [], "source": [ "_lambda = 0.1\n", "clf_ridge = skl.Ridge(alpha=_lambda).fit(X_train, y_train)\n", "J_ridge_sk = clf_ridge.coef_.reshape(L, L)\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(\\boldsymbol{X}, \\boldsymbol{\\beta}; \\lambda) = (\\boldsymbol{X}\\boldsymbol{\\beta} - \\boldsymbol{y})^T(\\boldsymbol{X}\\boldsymbol{\\beta} - \\boldsymbol{y}) + \\lambda \\sqrt{\\boldsymbol{\\beta}^T\\boldsymbol{\\beta}}.\n", "\\label{_auto22} \\tag{32}\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": 68, "metadata": {}, "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", "\n", "## 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": 69, "metadata": {}, "outputs": [], "source": [ "lambdas = np.logspace(-4, 5, 10)\n", "\n", "train_errors = {\n", " \"ols_sk\": 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_sk\": 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", " 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 see that LASSO 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": 70, "metadata": {}, "outputs": [], "source": [ "fig = plt.figure(figsize=(20, 14))\n", "\n", "colors = {\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.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", "achieves a very good accuracy on the test set. This by far surpasses the\n", "other models for all values of $\\lambda$.\n", "\n", "\n", "\n", "\n", "## Further Exercises\n", "\n", "### Exercise 1\n", "\n", "We will generate our own dataset for a function $y(x)$ where $x \\in [0,1]$ and defined by random numbers computed with the uniform distribution. The function $y$ is a quadratic polynomial in $x$ with added stochastic noise according to the normal distribution $\\cal {N}(0,1)$.\n", "The following simple Python instructions define our $x$ and $y$ values (with 100 data points)." ] }, { "cell_type": "code", "execution_count": 71, "metadata": {}, "outputs": [], "source": [ "x = np.random.rand(100,1)\n", "y = 5*x*x+0.1*np.random.randn(100,1)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "1. Write your own code (following the examples above) for computing the parametrization of the data set fitting a second-order polynomial. \n", "\n", "2. Use thereafter **scikit-learn** (see again the examples in the regression slides) and compare with your own code. \n", "\n", "3. Using scikit-learn, compute also the mean square error, a risk metric corresponding to the expected value of the squared (quadratic) error defined as" ] }, { "cell_type": "markdown", "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": [ "and the $R^2$ score function.\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": [ "You can use the functionality included in scikit-learn. If you feel\n", "for it, you can use your own program and define functions which\n", "compute the above two functions. Discuss the meaning of these\n", "results. Try also to vary the coefficient in front of the added\n", "stochastic noise term and discuss the quality of the fits.\n", "\n", "\n", "\n", "\n", "### Exercise 2, variance of the parameters $\\beta$ in linear regression\n", "\n", "Show that the variance of the parameters $\\beta$ in the linear regression method (chapter 3, equation (3.8) of [Trevor Hastie, Robert Tibshirani, Jerome H. Friedman, The Elements of Statistical Learning, Springer](https://www.springer.com/gp/book/9780387848570)) is given as" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "$$\n", "\\mathrm{Var}(\\hat{\\beta}) = \\left(\\hat{X}^T\\hat{X}\\right)^{-1}\\sigma^2,\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "with" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "$$\n", "\\sigma^2 = \\frac{1}{N-p-1}\\sum_{i=1}^{N} (y_i-\\tilde{y}_i)^2,\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "where we have assumed that we fit a function of degree $p-1$ (for example a polynomial in $x$). \n", "\n", "\n", "\n", "### Exercise 3\n", "\n", "This exercise is a continuation of exercise 1. We will\n", "use the same function to generate our data set, still staying with a\n", "simple function $y(x)$ which we want to fit using linear regression,\n", "but now extending the analysis to include the Ridge and the Lasso\n", "regression methods. You can use the code under the Regression as an example on how to use the Ridge and the Lasso methods.\n", "\n", "We will thus again generate our own dataset for a function $y(x)$ where \n", "$x \\in [0,1]$ and defined by random numbers computed with the uniform\n", "distribution. The function $y$ is a quadratic polynomial in $x$ with\n", "added stochastic noise according to the normal distribution $\\cal{N}(0,1)$.\n", "\n", "The following simple Python instructions define our $x$ and $y$ values (with 100 data points)." ] }, { "cell_type": "code", "execution_count": 72, "metadata": {}, "outputs": [], "source": [ "x = np.random.rand(100,1)\n", "y = 5*x*x+0.1*np.random.randn(100,1)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "1. Write your own code for the Ridge method and compute the parametrization for different values of $\\lambda$. Compare and analyze your results with those from exercise 1. Study the dependence on $\\lambda$ while also varying the strength of the noise in your expression for $y(x)$. \n", "\n", "2. Repeat the above but using the functionality of **scikit-learn**. Compare your code with the results from **scikit-learn**. Remember to run with the same random numbers for generating $x$ and $y$. \n", "\n", "3. Our next step is to study the variance of the parameters $\\beta_1$ and $\\beta_2$ (assuming that we are parametrizing our function with a second-order polynomial. We will use standard linear regression and the Ridge regression. You can now opt for either writing your own function that calculates the variance of these paramaters (recall that this is equal to the diagonal elements of the matrix $(\\hat{X}^T\\hat{X})+\\lambda\\hat{I})^{-1}$) or use the functionality of **scikit-learn** and compute their variances. Discuss the results of these variances as functions \n", "\n", "4. Repeat the previous step but add now the Lasso method. Discuss your results and compare with standard regression and the Ridge regression results.\n", "\n", "5. Try to implement the cross-validation as well. \n", "\n", "6. Finally, using **scikit-learn** or your own code, compute also the mean square error, a risk metric corresponding to the expected value of the squared (quadratic) error 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": [ "and the $R^2$ score function.\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": [ "Discuss these quantities as functions of the variable $\\lambda$ in the Ridge and Lasso regression methods. \n", "\n", "### Exercise 4\n", "\n", "We will study how\n", "to fit polynomials to a specific two-dimensional function called\n", "[Franke's\n", "function](http://www.dtic.mil/dtic/tr/fulltext/u2/a081688.pdf). This\n", "is a function which has been widely used when testing various interpolation and fitting\n", "algorithms. Furthermore, after having established the model and the\n", "method, we will employ resamling techniques such as the cross-validation and/or\n", "the bootstrap methods, in order to perform a proper assessment of our models.\n", "\n", "\n", "The Franke function, which is a weighted sum of four exponentials reads as follows" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "$$\n", "\\begin{align*}\n", "f(x,y) &= \\frac{3}{4}\\exp{\\left(-\\frac{(9x-2)^2}{4} - \\frac{(9y-2)^2}{4}\\right)}+\\frac{3}{4}\\exp{\\left(-\\frac{(9x+1)^2}{49}- \\frac{(9y+1)}{10}\\right)} \\\\\n", "&+\\frac{1}{2}\\exp{\\left(-\\frac{(9x-7)^2}{4} - \\frac{(9y-3)^2}{4}\\right)} -\\frac{1}{5}\\exp{\\left(-(9x-4)^2 - (9y-7)^2\\right) }.\n", "\\end{align*}\n", "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "The function will be defined for $x,y\\in [0,1]$. Our first step will\n", "be to perform an OLS regression analysis of this function, trying out\n", "a polynomial fit with an $x$ and $y$ dependence of the form $[x, y,\n", "x^2, y^2, xy, \\dots]$. We will also include cross-validation and\n", "bootstrap as resampling techniques. As in homeworks 1 and 2, we\n", "can use a uniform distribution to set up the arrays of values for $x$\n", "and $y$, or as in the example below just a fix values for $x$ and $y$ with a given step size.\n", "In this case we will have two predictors and need to fit a\n", "function (for example a polynomial) of $x$ and $y$. Thereafter we will\n", "repeat much of the same procedure using the the Ridge and\n", "Lasso regression methods, introducing thus a dependence on the bias\n", "(penalty) $\\lambda$.\n", "\n", "\n", "The Python function for the Franke function is included here (it performs also a three-dimensional plot of it)" ] }, { "cell_type": "code", "execution_count": 73, "metadata": {}, "outputs": [], "source": [ "from mpl_toolkits.mplot3d import Axes3D\n", "import matplotlib.pyplot as plt\n", "from matplotlib import cm\n", "from matplotlib.ticker import LinearLocator, FormatStrFormatter\n", "import numpy as np\n", "from random import random, seed\n", "\n", "fig = plt.figure()\n", "ax = fig.gca(projection='3d')\n", "\n", "# Make data.\n", "x = np.arange(0, 1, 0.05)\n", "y = np.arange(0, 1, 0.05)\n", "x, y = np.meshgrid(x,y)\n", "\n", "\n", "def FrankeFunction(x,y):\n", " term1 = 0.75*np.exp(-(0.25*(9*x-2)**2) - 0.25*((9*y-2)**2))\n", " term2 = 0.75*np.exp(-((9*x+1)**2)/49.0 - 0.1*(9*y+1))\n", " term3 = 0.5*np.exp(-(9*x-7)**2/4.0 - 0.25*((9*y-3)**2))\n", " term4 = -0.2*np.exp(-(9*x-4)**2 - (9*y-7)**2)\n", " return term1 + term2 + term3 + term4\n", "\n", "\n", "z = FrankeFunction(x, y)\n", "\n", "# Plot the surface.\n", "surf = ax.plot_surface(x, y, z, cmap=cm.coolwarm,\n", " linewidth=0, antialiased=False)\n", "\n", "# Customize the z axis.\n", "ax.set_zlim(-0.10, 1.40)\n", "ax.zaxis.set_major_locator(LinearLocator(10))\n", "ax.zaxis.set_major_formatter(FormatStrFormatter('%.02f'))\n", "\n", "# Add a color bar which maps values to colors.\n", "fig.colorbar(surf, shrink=0.5, aspect=5)\n", "\n", "plt.show()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "We will thus again generate our own dataset for a function $\\mathrm{FrankeFunction}(x,y)$ where \n", "$x,y \\in [0,1]$ could be defined by random numbers computed with the uniform\n", "distribution. The function $f(x,y)$ is the Franke function. You should explore also the addition\n", "an added stochastic noise to this function using the normal distribution $\\cal{N}(0,1)$.\n", "\n", "Write your own code (using either a matrix inversion or a singular value decomposition from e.g., **numpy** ) or use your code from exercises 1 and 3\n", "and perform a standard least square regression analysis using polynomials in $x$ and $y$ up to fifth order. Find the confidence intervals of the parameters $\\beta$ by computing their variances, evaluate the Mean Squared error (MSE)" ] }, { "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": [ "and the $R^2$ score function.\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": [ "Perform a resampling of the data where you split the data in training data and test data. Implement the $k$-fold cross-validation algorithm and/or the bootstrap algorithm\n", "and evaluate again the MSE and the $R^2$ functions resulting from the test data. Evaluate also the bias and variance of the final models.\n", "\n", "\n", "Write then your own code for the Ridge method, either using matrix\n", "inversion or the singular value decomposition as done for standard OLS. Perform the same analysis as in the\n", "previous exercise (for the same polynomials and include resampling\n", "techniques) but now for different values of $\\lambda$. Compare and\n", "analyze your results with those obtained with standard OLS. Study the\n", "dependence on $\\lambda$ while also varying eventually the strength of\n", "the noise in your expression for $\\mathrm{FrankeFunction}(x,y)$.\n", "\n", "Then perform the same studies but now with Lasso regression. Use the functionalities of\n", "**scikit-learn**. Give a critical discussion of the three methods and a\n", "judgement of which model fits the data best.\n", "\n", "\n", "\n", "\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": [ "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{_auto23} \\tag{33}\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", "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 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": [ "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", "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": [ "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": [ "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": [ "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": [ "$$\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": 74, "metadata": {}, "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": 75, "metadata": {}, "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{_auto24} \\tag{34}\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{_auto25} \\tag{35}\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": 76, "metadata": {}, "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": [ "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": 77, "metadata": {}, "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": 78, "metadata": {}, "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": [ "## 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{_auto26} \\tag{36}\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{_auto27} \\tag{37}\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{_auto28} \\tag{38}\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", "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": 79, "metadata": {}, "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": 80, "metadata": {}, "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{_auto29} \\tag{39}\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{_auto30} \\tag{40}\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": 81, "metadata": {}, "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": 82, "metadata": {}, "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", "\n", "\n", "\n", "\n", "# Optimization and Gradient Methods\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", "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", "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", "\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{41}\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": [ "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", "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 $\\boldsymbol{J}$ we have" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "$$\n", "\\boldsymbol{J}=\\left( \\begin{array}{cc}\n", " \\partial f_1/\\partial x_1 & \\partial f_1/\\partial x_2 \\\\\n", " \\partial f_2/\\partial x_1 &\\partial f_2/\\partial x_2\n", " \\end{array} \\right),\n", "$$" ] }, { "cell_type": "markdown", "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", " -{\\boldsymbol{J}}^{-1}\n", " \\left(\\begin{array}{c} f_1(x_1^{n},x_2^{n}) \\\\ f_2(x_1^{n},x_2^{n}) \\end{array} \\right).\n", "$$" ] }, { "cell_type": "markdown", "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 $\\boldsymbol{J}$ is nearly singular.\n", "\n", "It is rather straightforward to extend the above scheme to systems of\n", "more than two non-linear equations. In our case, the Jacobian matrix is given by the Hessian that represents the second derivative of cost function. \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", "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", "\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 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", "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", "In the following we state first and second-order conditions which\n", "ensures convexity of a function $f$. We write $D_f$ to denote the\n", "domain of $f$, i.e the subset of $R^n$ where $f$ is defined. For more\n", "details and proofs we refer to: [S. Boyd and L. Vandenberghe. Convex Optimization. Cambridge University Press](http://stanford.edu/boyd/cvxbook/, 2004).\n", "\n", "**First order condition.**\n", "\n", "Suppose $f$ is differentiable (i.e $\\nabla f(x)$ is well defined for\n", "all $x$ in the domain of $f$). Then $f$ is convex if and only if $D_f$\n", "is a convex set and $$f(y) \\geq f(x) + \\nabla f(x)^T (y-x) $$ holds\n", "for all $x,y \\in D_f$. This condition means that for a convex function\n", "the first order Taylor expansion (right hand side above) at any point\n", "a global under estimator of the function. To convince yourself you can\n", "make a drawing of $f(x) = x^2+1$ and draw the tangent line to $f(x)$ and\n", "note that it is always below the graph.\n", "\n", "\n", "\n", "**Second order condition.**\n", "\n", "Assume that $f$ is twice\n", "differentiable, i.e the Hessian matrix exists at each point in\n", "$D_f$. Then $f$ is convex if and only if $D_f$ is a convex set and its\n", "Hessian is positive semi-definite for all $x\\in D_f$. For a\n", "single-variable function this reduces to $f''(x) \\geq 0$. Geometrically this means that $f$ has nonnegative curvature\n", "everywhere.\n", "\n", "\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", "The next result is of great importance to us and the reason why we are\n", "going on about convex functions. In machine learning we frequently\n", "have to minimize a loss/cost function in order to find the best\n", "parameters for the model we are considering. \n", "\n", "Ideally we want the\n", "global minimum (for high-dimensional models it is hard to know\n", "if we have local or global minimum). However, if the cost/loss function\n", "is convex the following result provides invaluable information:\n", "\n", "**Any minimum is global for convex functions.**\n", "\n", "Consider the problem of finding $x \\in \\mathbb{R}^n$ such that $f(x)$\n", "is minimal, where $f$ is convex and differentiable. Then, any point\n", "$x^*$ that satisfies $\\nabla f(x^*) = 0$ is a global minimum.\n", "\n", "\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", "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", "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", "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", "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": [ "## 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": [ " 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": 83, "metadata": {}, "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": 84, "metadata": {}, "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": 85, "metadata": {}, "outputs": [], "source": [ "x = guesses[-1]\n", "s = -df(x)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Run it!" ] }, { "cell_type": "code", "execution_count": 86, "metadata": {}, "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": 87, "metadata": {}, "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", "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", "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": [ "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": [ "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", "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", "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": [ "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", "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.\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", "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 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", "## 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": 88, "metadata": {}, "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": [ "Another simple example is here" ] }, { "cell_type": "code", "execution_count": 89, "metadata": {}, "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": 90, "metadata": {}, "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": 91, "metadata": {}, "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": 92, "metadata": {}, "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": 93, "metadata": {}, "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": 94, "metadata": {}, "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": 95, "metadata": {}, "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": 96, "metadata": {}, "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": "code", "execution_count": 97, "metadata": {}, "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": [ "1\n", "0\n", "3\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": 98, "metadata": {}, "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": 99, "metadata": {}, "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": 100, "metadata": {}, "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": 101, "metadata": {}, "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": 102, "metadata": {}, "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": 103, "metadata": {}, "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": [ "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", "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": [ "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." ] }, { "cell_type": "code", "execution_count": 104, "metadata": {}, "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", "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", "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": 105, "metadata": {}, "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": "code", "execution_count": 106, "metadata": {}, "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{_auto31} \\tag{42}\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{_auto32} \\tag{43}\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", "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{_auto33} \\tag{44}\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{_auto34} \\tag{45}\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{_auto35} \\tag{46}\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." ] } ], "metadata": { "kernelspec": { "display_name": "Python 3", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.7.3" } }, "nbformat": 4, "nbformat_minor": 2 }