Files
FYS-STK4155/doc/LectureNotes/chapter1.ipynb
T
Morten Hjorth-Jensen 365bc221d3 added dot files
2021-08-26 10:14:24 +02:00

3559 lines
126 KiB
Plaintext
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
{
"cells": [
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# Linear Regression\n",
"\n",
"[Video of Lecture](https://www.uio.no/studier/emner/matnat/fys/FYS-STK3155/h20/forelesningsvideoer/LectureAug21.mp4?vrtx=view-as-webpage)\n",
"\n",
"\n",
"## Introduction\n",
"\n",
"\n",
"\n",
"\n",
"\n",
"Our emphasis throughout this series of lectures (small change) \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",
"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.\n",
"* The first ingredient is normally our data set (which can be subdivided into training, validation and test data). Many find the most difficult part of using Machine Learning to be the set up of your data in a meaningful way. \n",
"\n",
"* The second item is a model which is normally a function of some parameters. The model reflects our knowledge of the system (or lack thereof). As an example, if we know that our data show a behavior similar to what would be predicted by a polynomial, fitting our data to a polynomial of some degree would then determin our model. \n",
"\n",
"* The last ingredient is a so-called **cost/loss** function (or error or risk function) which allows us to present an estimate on how good our model is in reproducing the data it is supposed to train. \n",
"\n",
"\n",
"\n",
"At the heart of basically all Machine Learning algorithms we will encounter so-called minimization or optimization algorithms. A large family of such methods are so-called **gradient methods**.\n",
"\n",
"\n",
"### A Frequentist approach to data analysis\n",
"\n",
"When you hear phrases like **predictions and estimations** and\n",
"**correlations and causations**, what do you think of? May be you think\n",
"of the difference between classifying new data points and generating\n",
"new data points.\n",
"Or perhaps you consider that correlations represent some kind of symmetric statements like\n",
"if $A$ is correlated with $B$, then $B$ is correlated with\n",
"$A$. Causation on the other hand is directional, that is if $A$ causes $B$, $B$ does not\n",
"necessarily cause $A$.\n",
"\n",
"These concepts are in some sense the difference between machine\n",
"learning and statistics. In machine learning and prediction based\n",
"tasks, we are often interested in developing algorithms that are\n",
"capable of learning patterns from given data in an automated fashion,\n",
"and then using these learned patterns to make predictions or\n",
"assessments of newly given data. In many cases, our primary concern\n",
"is the quality of the predictions or assessments, and we are less\n",
"concerned about the underlying patterns that were learned in order\n",
"to make these predictions.\n",
"\n",
"In machine learning we normally use [a so-called frequentist approach](https://en.wikipedia.org/wiki/Frequentist_inference),\n",
"where the aim is to make predictions and find correlations. We focus\n",
"less on for example extracting a probability distribution function (PDF). The PDF can be\n",
"used in turn to make estimations and find causations such as given $A$\n",
"what is the likelihood of finding $B$.\n",
"\n",
"\n",
"### What is a good model?\n",
"\n",
"In science and engineering we often end up in situations where we want to infer (or learn) a\n",
"quantitative model $M$ for a given set of sample points $\\boldsymbol{X} \\in [x_1, x_2,\\dots x_N]$.\n",
"\n",
"As we will see repeatedely in these lectures, we could try to fit these data points to a model given by a\n",
"straight line, or if we wish to be more sophisticated to a more complex\n",
"function.\n",
"\n",
"The reason for inferring such a model is that it\n",
"serves many useful purposes. On the one hand, the model can reveal information\n",
"encoded in the data or underlying mechanisms from which the data were generated. For instance, we could discover important\n",
"corelations that relate interesting physics interpretations.\n",
"\n",
"In addition, it can simplify the representation of the given data set and help\n",
"us in making predictions about future data samples.\n",
"\n",
"A first important consideration to keep in mind is that inferring the *correct* model\n",
"for a given data set is an elusive, if not impossible, task. The fundamental difficulty\n",
"is that if we are not specific about what we mean by a *correct* model, there\n",
"could easily be many different models that fit the given data set *equally well*.\n",
"\n",
"\n",
"\n",
"\n",
"The central question is this: what leads us to say that a model is correct or\n",
"optimal for a given data set? To make the model inference problem well posed, i.e.,\n",
"to guarantee that there is a unique optimal model for the given data, we need to\n",
"impose additional assumptions or restrictions on the class of models considered. To\n",
"this end, we should not be looking for just any model that can describe the data.\n",
"Instead, we should look for a **model** $M$ that is the best among a restricted class\n",
"of models. In addition, to make the model inference problem computationally\n",
"tractable, we need to specify how restricted the class of models needs to be. A\n",
"common strategy is to start \n",
"with the simplest possible class of models that is just necessary to describe the data\n",
"or solve the problem at hand. More precisely, the model class should be rich enough\n",
"to contain at least one model that can fit the data to a desired accuracy and yet be\n",
"restricted enough that it is relatively simple to find the best model for the given data.\n",
"\n",
"Thus, the most popular strategy is to start from the\n",
"simplest class of models and increase the complexity of the models only when the\n",
"simpler models become inadequate. For instance, if we work with a regression problem to fit a set of sample points, one\n",
"may first try the simplest class of models, namely linear models, followed obviously by more complex models.\n",
"\n",
"How to evaluate which model fits best the data is something we will come back to over and over again in these sets of lectures.\n",
"\n",
"\n",
"\n",
"\n",
"\n",
"\n",
"\n",
"\n",
"\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": null,
"metadata": {
"collapsed": false,
"editable": true
},
"outputs": [],
"source": [
"%matplotlib inline\n",
"\n",
"# Importing various packages\n",
"import numpy as np\n",
"import matplotlib.pyplot as plt\n",
"from sklearn.linear_model import LinearRegression\n",
"\n",
"x = np.random.rand(100,1)\n",
"y = 2*x+np.random.randn(100,1)\n",
"linreg = LinearRegression()\n",
"linreg.fit(x,y)\n",
"xnew = np.array([[0],[1]])\n",
"ypredict = linreg.predict(xnew)\n",
"\n",
"plt.plot(xnew, ypredict, \"r-\")\n",
"plt.plot(x, y ,'ro')\n",
"plt.axis([0,1.0,0, 5.0])\n",
"plt.xlabel(r'$x$')\n",
"plt.ylabel(r'$y$')\n",
"plt.title(r'Simple Linear Regression')\n",
"plt.show()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"This example serves several aims. It allows us to demonstrate several\n",
"aspects of data analysis and later machine learning algorithms. The\n",
"immediate visualization shows that our linear fit is not\n",
"impressive. It goes through the data points, but there are many\n",
"outliers which are not reproduced by our linear regression. We could\n",
"now play around with this small program and change for example the\n",
"factor in front of $x$ and the normal distribution. Try to change the\n",
"function $y$ to"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"$$\n",
"y = 10x+0.01 \\times N(0,1),\n",
"$$"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"where $x$ is defined as before. Does the fit look better? Indeed, by\n",
"reducing the role of the 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": [
"The squared cost function results in an arithmetic mean-unbiased\n",
"estimator, and the absolute-value cost function results in a\n",
"median-unbiased estimator (in the one-dimensional case, and a\n",
"geometric median-unbiased estimator for the multi-dimensional\n",
"case). The squared cost function has the disadvantage that it has the tendency\n",
"to be dominated by outliers.\n",
"\n",
"We can modify easily the above Python code and plot the relative error instead"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false,
"editable": true
},
"outputs": [],
"source": [
"import numpy as np\n",
"import matplotlib.pyplot as plt\n",
"from sklearn.linear_model import LinearRegression\n",
"\n",
"x = np.random.rand(100,1)\n",
"y = 5*x+0.01*np.random.randn(100,1)\n",
"linreg = LinearRegression()\n",
"linreg.fit(x,y)\n",
"ypredict = linreg.predict(x)\n",
"\n",
"plt.plot(x, np.abs(ypredict-y)/abs(y), \"ro\")\n",
"plt.axis([0,1.0,0.0, 0.5])\n",
"plt.xlabel(r'$x$')\n",
"plt.ylabel(r'$\\epsilon_{\\mathrm{relative}}$')\n",
"plt.title(r'Relative error')\n",
"plt.show()"
]
},
{
"cell_type": "markdown",
"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": null,
"metadata": {
"collapsed": false,
"editable": true
},
"outputs": [],
"source": [
"import numpy as np \n",
"import matplotlib.pyplot as plt \n",
"from sklearn.linear_model import LinearRegression \n",
"from sklearn.metrics import mean_squared_error, r2_score, mean_squared_log_error, mean_absolute_error\n",
"\n",
"x = np.random.rand(100,1)\n",
"y = 2.0+ 5*x+0.5*np.random.randn(100,1)\n",
"linreg = LinearRegression()\n",
"linreg.fit(x,y)\n",
"ypredict = linreg.predict(x)\n",
"print('The intercept alpha: \\n', linreg.intercept_)\n",
"print('Coefficient beta : \\n', linreg.coef_)\n",
"# The mean squared error \n",
"print(\"Mean squared error: %.2f\" % mean_squared_error(y, ypredict))\n",
"# Explained variance score: 1 is perfect prediction \n",
"print('Variance score: %.2f' % r2_score(y, ypredict))\n",
"# Mean squared log error \n",
"print('Mean squared log error: %.2f' % mean_squared_log_error(y, ypredict) )\n",
"# Mean absolute error \n",
"print('Mean absolute error: %.2f' % mean_absolute_error(y, ypredict))\n",
"plt.plot(x, ypredict, \"r-\")\n",
"plt.plot(x, y ,'ro')\n",
"plt.axis([0.0,1.0,1.5, 7.0])\n",
"plt.xlabel(r'$x$')\n",
"plt.ylabel(r'$y$')\n",
"plt.title(r'Linear Regression fit ')\n",
"plt.show()"
]
},
{
"cell_type": "markdown",
"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": [
"We present the \n",
"squared logarithmic (quadratic) error"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"$$\n",
"\\text{MSLE}(\\hat{y}, \\hat{\\tilde{y}}) = \\frac{1}{n} \\sum_{i=0}^{n - 1} (\\log_e (1 + y_i) - \\log_e (1 + \\tilde{y}_i) )^2,\n",
"$$"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"where $\\log_e (x)$ stands for the natural logarithm of $x$. This error\n",
"estimate is best to use when targets having exponential growth, such\n",
"as population counts, average sales of a commodity over a span of\n",
"years etc. \n",
"\n",
"\n",
"Finally, another cost function is the Huber cost function used in robust regression.\n",
"\n",
"The rationale behind this possible cost function is its reduced\n",
"sensitivity to outliers in the data set. In our discussions on\n",
"dimensionality reduction and normalization of data we will meet other\n",
"ways of dealing with outliers.\n",
"\n",
"The Huber cost function is defined as"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"$$\n",
"H_{\\delta}(a)=\\left\\{\\begin{array}\\frac{1}{2}a^{2}&{\\text{for }}|a|\\leq \\delta ,\\\\ \\delta (|a|-\\frac {1}{2}\\del\\\n",
"ta ),&{\\text{otherwise.}\\end{array}\\right.\n",
"$$"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Here $a=\\boldsymbol{y} - \\boldsymbol{\\tilde{y}}$.\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": null,
"metadata": {
"collapsed": false,
"editable": true
},
"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": [
"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": null,
"metadata": {
"collapsed": false,
"editable": true
},
"outputs": [],
"source": [
"# Common imports\n",
"import numpy as np\n",
"import pandas as pd\n",
"import matplotlib.pyplot as plt\n",
"import sklearn.linear_model as skl\n",
"from sklearn.model_selection import train_test_split\n",
"from sklearn.metrics import mean_squared_error, r2_score, mean_absolute_error\n",
"import os\n",
"\n",
"# Where to save the figures and data files\n",
"PROJECT_ROOT_DIR = \"Results\"\n",
"FIGURE_ID = \"Results/FigureFiles\"\n",
"DATA_ID = \"DataFiles/\"\n",
"\n",
"if not os.path.exists(PROJECT_ROOT_DIR):\n",
" os.mkdir(PROJECT_ROOT_DIR)\n",
"\n",
"if not os.path.exists(FIGURE_ID):\n",
" os.makedirs(FIGURE_ID)\n",
"\n",
"if not os.path.exists(DATA_ID):\n",
" os.makedirs(DATA_ID)\n",
"\n",
"def image_path(fig_id):\n",
" return os.path.join(FIGURE_ID, fig_id)\n",
"\n",
"def data_path(dat_id):\n",
" return os.path.join(DATA_ID, dat_id)\n",
"\n",
"def save_fig(fig_id):\n",
" plt.savefig(image_path(fig_id) + \".png\", format='png')\n",
"\n",
"infile = open(data_path(\"MassEval2016.dat\"),'r')"
]
},
{
"cell_type": "markdown",
"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": null,
"metadata": {
"collapsed": false,
"editable": true
},
"outputs": [],
"source": [
"from pylab import plt, mpl\n",
"plt.style.use('seaborn')\n",
"mpl.rcParams['font.family'] = 'serif'\n",
"\n",
"def MakePlot(x,y, styles, labels, axlabels):\n",
" plt.figure(figsize=(10,6))\n",
" for i in range(len(x)):\n",
" plt.plot(x[i], y[i], styles[i], label = labels[i])\n",
" plt.xlabel(axlabels[0])\n",
" plt.ylabel(axlabels[1])\n",
" plt.legend(loc=0)"
]
},
{
"cell_type": "markdown",
"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": null,
"metadata": {
"collapsed": false,
"editable": true
},
"outputs": [],
"source": [
"\"\"\" \n",
"This is taken from the data file of the mass 2016 evaluation. \n",
"All files are 3436 lines long with 124 character per line. \n",
" Headers are 39 lines long. \n",
" col 1 : Fortran character control: 1 = page feed 0 = line feed \n",
" format : a1,i3,i5,i5,i5,1x,a3,a4,1x,f13.5,f11.5,f11.3,f9.3,1x,a2,f11.3,f9.3,1x,i3,1x,f12.5,f11.5 \n",
" These formats are reflected in the pandas widths variable below, see the statement \n",
" widths=(1,3,5,5,5,1,3,4,1,13,11,11,9,1,2,11,9,1,3,1,12,11,1), \n",
" Pandas has also a variable header, with length 39 in this case. \n",
"\"\"\""
]
},
{
"cell_type": "markdown",
"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": null,
"metadata": {
"collapsed": false,
"editable": true
},
"outputs": [],
"source": [
"# Read the experimental data with Pandas\n",
"Masses = pd.read_fwf(infile, usecols=(2,3,4,6,11),\n",
" names=('N', 'Z', 'A', 'Element', 'Ebinding'),\n",
" widths=(1,3,5,5,5,1,3,4,1,13,11,11,9,1,2,11,9,1,3,1,12,11,1),\n",
" header=39,\n",
" index_col=False)\n",
"\n",
"# Extrapolated values are indicated by '#' in place of the decimal place, so\n",
"# the Ebinding column won't be numeric. Coerce to float and drop these entries.\n",
"Masses['Ebinding'] = pd.to_numeric(Masses['Ebinding'], errors='coerce')\n",
"Masses = Masses.dropna()\n",
"# Convert from keV to MeV.\n",
"Masses['Ebinding'] /= 1000\n",
"\n",
"# Group the DataFrame by nucleon number, A.\n",
"Masses = Masses.groupby('A')\n",
"# Find the rows of the grouped DataFrame with the maximum binding energy.\n",
"Masses = Masses.apply(lambda t: t[t.Ebinding==t.Ebinding.max()])"
]
},
{
"cell_type": "markdown",
"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": null,
"metadata": {
"collapsed": false,
"editable": true
},
"outputs": [],
"source": [
"A = Masses['A']\n",
"Z = Masses['Z']\n",
"N = Masses['N']\n",
"Element = Masses['Element']\n",
"Energies = Masses['Ebinding']\n",
"print(Masses)"
]
},
{
"cell_type": "markdown",
"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": null,
"metadata": {
"collapsed": false,
"editable": true
},
"outputs": [],
"source": [
"# Now we set up the design matrix X\n",
"X = np.zeros((len(A),5))\n",
"X[:,0] = 1\n",
"X[:,1] = A\n",
"X[:,2] = A**(2.0/3.0)\n",
"X[:,3] = A**(-1.0/3.0)\n",
"X[:,4] = A**(-1.0)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"With **scikitlearn** we are now ready to use linear regression and fit our data."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false,
"editable": true
},
"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": null,
"metadata": {
"collapsed": false,
"editable": true
},
"outputs": [],
"source": [
"# The mean squared error \n",
"print(\"Mean squared error: %.2f\" % mean_squared_error(Energies, fity))\n",
"# Explained variance score: 1 is perfect prediction \n",
"print('Variance score: %.2f' % r2_score(Energies, fity))\n",
"# Mean absolute error \n",
"print('Mean absolute error: %.2f' % mean_absolute_error(Energies, fity))\n",
"print(clf.coef_, clf.intercept_)\n",
"\n",
"Masses['Eapprox'] = fity\n",
"# Generate a plot comparing the experimental with the fitted values values.\n",
"fig, ax = plt.subplots()\n",
"ax.set_xlabel(r'$A = N + Z$')\n",
"ax.set_ylabel(r'$E_\\mathrm{bind}\\,/\\mathrm{MeV}$')\n",
"ax.plot(Masses['A'], Masses['Ebinding'], alpha=0.7, lw=2,\n",
" label='Ame2016')\n",
"ax.plot(Masses['A'], Masses['Eapprox'], alpha=0.7, lw=2, c='m',\n",
" label='Fit')\n",
"ax.legend()\n",
"save_fig(\"Masses2016\")\n",
"plt.show()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"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": null,
"metadata": {
"collapsed": false,
"editable": true
},
"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": [
"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": null,
"metadata": {
"collapsed": false,
"editable": true
},
"outputs": [],
"source": [
"from sklearn.neural_network import MLPRegressor\n",
"from sklearn.metrics import accuracy_score\n",
"import seaborn as sns\n",
"\n",
"X_train = X\n",
"Y_train = Energies\n",
"n_hidden_neurons = 100\n",
"epochs = 100\n",
"# store models for later use\n",
"eta_vals = np.logspace(-5, 1, 7)\n",
"lmbd_vals = np.logspace(-5, 1, 7)\n",
"# store the models for later use\n",
"DNN_scikit = np.zeros((len(eta_vals), len(lmbd_vals)), dtype=object)\n",
"train_accuracy = np.zeros((len(eta_vals), len(lmbd_vals)))\n",
"sns.set()\n",
"for i, eta in enumerate(eta_vals):\n",
" for j, lmbd in enumerate(lmbd_vals):\n",
" dnn = MLPRegressor(hidden_layer_sizes=(n_hidden_neurons), activation='logistic',\n",
" alpha=lmbd, learning_rate_init=eta, max_iter=epochs)\n",
" dnn.fit(X_train, Y_train)\n",
" DNN_scikit[i][j] = dnn\n",
" train_accuracy[i][j] = dnn.score(X_train, Y_train)\n",
"\n",
"fig, ax = plt.subplots(figsize = (10, 10))\n",
"sns.heatmap(train_accuracy, annot=True, ax=ax, cmap=\"viridis\")\n",
"ax.set_title(\"Training Accuracy\")\n",
"ax.set_ylabel(\"$\\eta$\")\n",
"ax.set_xlabel(\"$\\lambda$\")\n",
"plt.show()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Linear Regression, basic elements\n",
"\n",
"\n",
"[Video of Lecture](https://www.uio.no/studier/emner/matnat/fys/FYS-STK4155/h20/forelesningsvideoer/LectureAug27.mp4?vrtx=view-as-webpage).\n",
"\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",
"\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",
"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$. This is however a classification problem and we will come back to it when we discuss Logistic Regression. \n",
"\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",
"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",
"In our [introductory notes](https://compphysics.github.io/MachineLearning/doc/pub/How2ReadData/html/How2ReadData.html) we looked at the so-called [liquid drop model](https://en.wikipedia.org/wiki/Semi-empirical_mass_formula). Let us remind ourselves about what we did by looking at the code.\n",
"\n",
"We restate the parts of the code we are most interested in."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false,
"editable": true
},
"outputs": [],
"source": [
"# Common imports\n",
"import numpy as np\n",
"import pandas as pd\n",
"import matplotlib.pyplot as plt\n",
"from IPython.display import display\n",
"import os\n",
"\n",
"# Where to save the figures and data files\n",
"PROJECT_ROOT_DIR = \"Results\"\n",
"FIGURE_ID = \"Results/FigureFiles\"\n",
"DATA_ID = \"DataFiles/\"\n",
"\n",
"if not os.path.exists(PROJECT_ROOT_DIR):\n",
" os.mkdir(PROJECT_ROOT_DIR)\n",
"\n",
"if not os.path.exists(FIGURE_ID):\n",
" os.makedirs(FIGURE_ID)\n",
"\n",
"if not os.path.exists(DATA_ID):\n",
" os.makedirs(DATA_ID)\n",
"\n",
"def image_path(fig_id):\n",
" return os.path.join(FIGURE_ID, fig_id)\n",
"\n",
"def data_path(dat_id):\n",
" return os.path.join(DATA_ID, dat_id)\n",
"\n",
"def save_fig(fig_id):\n",
" plt.savefig(image_path(fig_id) + \".png\", format='png')\n",
"\n",
"infile = open(data_path(\"MassEval2016.dat\"),'r')\n",
"\n",
"\n",
"# Read the experimental data with Pandas\n",
"Masses = pd.read_fwf(infile, usecols=(2,3,4,6,11),\n",
" names=('N', 'Z', 'A', 'Element', 'Ebinding'),\n",
" widths=(1,3,5,5,5,1,3,4,1,13,11,11,9,1,2,11,9,1,3,1,12,11,1),\n",
" header=39,\n",
" index_col=False)\n",
"\n",
"# Extrapolated values are indicated by '#' in place of the decimal place, so\n",
"# the Ebinding column won't be numeric. Coerce to float and drop these entries.\n",
"Masses['Ebinding'] = pd.to_numeric(Masses['Ebinding'], errors='coerce')\n",
"Masses = Masses.dropna()\n",
"# Convert from keV to MeV.\n",
"Masses['Ebinding'] /= 1000\n",
"\n",
"# Group the DataFrame by nucleon number, A.\n",
"Masses = Masses.groupby('A')\n",
"# Find the rows of the grouped DataFrame with the maximum binding energy.\n",
"Masses = Masses.apply(lambda t: t[t.Ebinding==t.Ebinding.max()])\n",
"A = Masses['A']\n",
"Z = Masses['Z']\n",
"N = Masses['N']\n",
"Element = Masses['Element']\n",
"Energies = Masses['Ebinding']\n",
"\n",
"# Now we set up the design matrix X\n",
"X = np.zeros((len(A),5))\n",
"X[:,0] = 1\n",
"X[:,1] = A\n",
"X[:,2] = A**(2.0/3.0)\n",
"X[:,3] = A**(-1.0/3.0)\n",
"X[:,4] = A**(-1.0)\n",
"# Then nice printout using pandas\n",
"DesignMatrix = pd.DataFrame(X)\n",
"DesignMatrix.index = A\n",
"DesignMatrix.columns = ['1', 'A', 'A^(2/3)', 'A^(-1/3)', '1/A']\n",
"display(DesignMatrix)"
]
},
{
"cell_type": "markdown",
"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",
"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}\\boldsymbol{\\beta}\\right)^T\\left(\\boldsymbol{y}-\\boldsymbol{X}\\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 $C$ 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",
"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 (see the discussion below) with the maximum likelihood approach below, we will indeed interpret $y_i$ as a mean value"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"$$\n",
"y_{i}=\\langle y_i \\rangle = \\beta_0x_{i,0}+\\beta_1x_{i,1}+\\beta_2x_{i,2}+\\dots+\\beta_{n-1}x_{i,n-1}+\\epsilon_i,\n",
"$$"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"where $\\langle y_i \\rangle$ is the mean value. Keep in mind also that\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",
"**Small question**: Do you think the example we have at hand here (the nuclear binding energies) can lead to problems in inverting the matrix $\\boldsymbol{X}^T\\boldsymbol{X}$? What kind of problems can we expect? \n",
"\n",
"\n",
"The following matrix and vector relation will be useful here and for the rest of the course. Vectors are always written as boldfaced lower case letters and \n",
"matrices as upper case boldfaced letters."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"4\n",
"3\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": [
"4\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": [
"4\n",
"5\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",
"\\frac{\\partial \\log{\\vert\\boldsymbol{A}\\vert}}{\\partial \\boldsymbol{A}} = (\\boldsymbol{A}^{-1})^T.\n",
"$$"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"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",
"\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": null,
"metadata": {
"collapsed": false,
"editable": true
},
"outputs": [],
"source": [
"# matrix inversion to find beta\n",
"beta = np.linalg.inv(X.T.dot(X)).dot(X.T).dot(Energies)\n",
"# and then make the prediction\n",
"ytilde = X @ beta"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Alternatively, you can use the least squares functionality in **Numpy** as"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false,
"editable": true
},
"outputs": [],
"source": [
"fit = np.linalg.lstsq(X, Energies, rcond =None)[0]\n",
"ytildenp = np.dot(fit,X.T)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"And finally we plot our fit with and compare with data"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false,
"editable": true
},
"outputs": [],
"source": [
"Masses['Eapprox'] = ytilde\n",
"# Generate a plot comparing the experimental with the fitted values values.\n",
"fig, ax = plt.subplots()\n",
"ax.set_xlabel(r'$A = N + Z$')\n",
"ax.set_ylabel(r'$E_\\mathrm{bind}\\,/\\mathrm{MeV}$')\n",
"ax.plot(Masses['A'], Masses['Ebinding'], alpha=0.7, lw=2,\n",
" label='Ame2016')\n",
"ax.plot(Masses['A'], Masses['Eapprox'], alpha=0.7, lw=2, c='m',\n",
" label='Fit')\n",
"ax.legend()\n",
"save_fig(\"Masses2016OLS\")\n",
"plt.show()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"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": null,
"metadata": {
"collapsed": false,
"editable": true
},
"outputs": [],
"source": [
"def R2(y_data, y_model):\n",
" return 1 - np.sum((y_data - y_model) ** 2) / np.sum((y_data - np.mean(y_data)) ** 2)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"and we would be using it as"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false,
"editable": true
},
"outputs": [],
"source": [
"print(R2(Energies,ytilde))"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"We can easily add our **MSE** score as"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false,
"editable": true
},
"outputs": [],
"source": [
"def MSE(y_data,y_model):\n",
" n = np.size(y_model)\n",
" return np.sum((y_data-y_model)**2)/n\n",
"\n",
"print(MSE(Energies,ytilde))"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"and finally the relative error as"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false,
"editable": true
},
"outputs": [],
"source": [
"def RelativeError(y_data,y_model):\n",
" return abs((y_data-y_model)/y_data)\n",
"print(RelativeError(Energies, ytilde))"
]
},
{
"cell_type": "markdown",
"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\n",
"before, with the same initializations and declarations. We use also\n",
"**pandas** again, rather extensively in order to organize our data.\n",
"\n",
"The difference now is that we use **Scikit-Learn's** regression tools\n",
"instead of our own matrix inversion implementation. Furthermore, we\n",
"sneak in **Ridge** regression (to be discussed below) which includes a\n",
"hyperparameter $\\lambda$, also to be explained below."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false,
"editable": true
},
"outputs": [],
"source": [
"# Common imports\n",
"import os\n",
"import numpy as np\n",
"import pandas as pd\n",
"import matplotlib.pyplot as plt\n",
"import matplotlib.pyplot as plt\n",
"import sklearn.linear_model as skl\n",
"from sklearn.metrics import mean_squared_error, r2_score, mean_absolute_error\n",
"\n",
"# Where to save the figures and data files\n",
"PROJECT_ROOT_DIR = \"Results\"\n",
"FIGURE_ID = \"Results/FigureFiles\"\n",
"DATA_ID = \"DataFiles/\"\n",
"\n",
"if not os.path.exists(PROJECT_ROOT_DIR):\n",
" os.mkdir(PROJECT_ROOT_DIR)\n",
"\n",
"if not os.path.exists(FIGURE_ID):\n",
" os.makedirs(FIGURE_ID)\n",
"\n",
"if not os.path.exists(DATA_ID):\n",
" os.makedirs(DATA_ID)\n",
"\n",
"def image_path(fig_id):\n",
" return os.path.join(FIGURE_ID, fig_id)\n",
"\n",
"def data_path(dat_id):\n",
" return os.path.join(DATA_ID, dat_id)\n",
"\n",
"def save_fig(fig_id):\n",
" plt.savefig(image_path(fig_id) + \".png\", format='png')\n",
"\n",
"infile = open(data_path(\"EoS.csv\"),'r')\n",
"\n",
"# Read the EoS data as csv file and organize the data into two arrays with density and energies\n",
"EoS = pd.read_csv(infile, names=('Density', 'Energy'))\n",
"EoS['Energy'] = pd.to_numeric(EoS['Energy'], errors='coerce')\n",
"EoS = EoS.dropna()\n",
"Energies = EoS['Energy']\n",
"Density = EoS['Density']\n",
"# The design matrix now as function of various polytrops\n",
"X = np.zeros((len(Density),4))\n",
"X[:,3] = Density**(4.0/3.0)\n",
"X[:,2] = Density\n",
"X[:,1] = Density**(2.0/3.0)\n",
"X[:,0] = 1\n",
"\n",
"# We use now Scikit-Learn's linear regressor and ridge regressor\n",
"# OLS part\n",
"clf = skl.LinearRegression().fit(X, Energies)\n",
"ytilde = clf.predict(X)\n",
"EoS['Eols'] = ytilde\n",
"# The mean squared error \n",
"print(\"Mean squared error: %.2f\" % mean_squared_error(Energies, ytilde))\n",
"# Explained variance score: 1 is perfect prediction \n",
"print('Variance score: %.2f' % r2_score(Energies, ytilde))\n",
"# Mean absolute error \n",
"print('Mean absolute error: %.2f' % mean_absolute_error(Energies, ytilde))\n",
"print(clf.coef_, clf.intercept_)\n",
"\n",
"# The Ridge regression with a hyperparameter lambda = 0.1\n",
"_lambda = 0.1\n",
"clf_ridge = skl.Ridge(alpha=_lambda).fit(X, Energies)\n",
"yridge = clf_ridge.predict(X)\n",
"EoS['Eridge'] = yridge\n",
"# The mean squared error \n",
"print(\"Mean squared error: %.2f\" % mean_squared_error(Energies, yridge))\n",
"# Explained variance score: 1 is perfect prediction \n",
"print('Variance score: %.2f' % r2_score(Energies, yridge))\n",
"# Mean absolute error \n",
"print('Mean absolute error: %.2f' % mean_absolute_error(Energies, yridge))\n",
"print(clf_ridge.coef_, clf_ridge.intercept_)\n",
"\n",
"fig, ax = plt.subplots()\n",
"ax.set_xlabel(r'$\\rho[\\mathrm{fm}^{-3}]$')\n",
"ax.set_ylabel(r'Energy per particle')\n",
"ax.plot(EoS['Density'], EoS['Energy'], alpha=0.7, lw=2,\n",
" label='Theoretical data')\n",
"ax.plot(EoS['Density'], EoS['Eols'], alpha=0.7, lw=2, c='m',\n",
" label='OLS')\n",
"ax.plot(EoS['Density'], EoS['Eridge'], alpha=0.7, lw=2, c='g',\n",
" label='Ridge $\\lambda = 0.1$')\n",
"ax.legend()\n",
"save_fig(\"EoSfitting\")\n",
"plt.show()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"The above simple polynomial in density $\\rho$ gives an excellent fit\n",
"to the data. \n",
"\n",
"We note also that there is a small deviation between the\n",
"standard OLS and the Ridge regression at higher densities. We discuss this in more detail\n",
"below.\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": null,
"metadata": {
"collapsed": false,
"editable": true
},
"outputs": [],
"source": [
"import os\n",
"import numpy as np\n",
"import pandas as pd\n",
"import matplotlib.pyplot as plt\n",
"from sklearn.model_selection import train_test_split\n",
"# Where to save the figures and data files\n",
"PROJECT_ROOT_DIR = \"Results\"\n",
"FIGURE_ID = \"Results/FigureFiles\"\n",
"DATA_ID = \"DataFiles/\"\n",
"\n",
"if not os.path.exists(PROJECT_ROOT_DIR):\n",
" os.mkdir(PROJECT_ROOT_DIR)\n",
"\n",
"if not os.path.exists(FIGURE_ID):\n",
" os.makedirs(FIGURE_ID)\n",
"\n",
"if not os.path.exists(DATA_ID):\n",
" os.makedirs(DATA_ID)\n",
"\n",
"def image_path(fig_id):\n",
" return os.path.join(FIGURE_ID, fig_id)\n",
"\n",
"def data_path(dat_id):\n",
" return os.path.join(DATA_ID, dat_id)\n",
"\n",
"def save_fig(fig_id):\n",
" plt.savefig(image_path(fig_id) + \".png\", format='png')\n",
"\n",
"def R2(y_data, y_model):\n",
" return 1 - np.sum((y_data - y_model) ** 2) / np.sum((y_data - np.mean(y_data)) ** 2)\n",
"def MSE(y_data,y_model):\n",
" n = np.size(y_model)\n",
" return np.sum((y_data-y_model)**2)/n\n",
"\n",
"infile = open(data_path(\"EoS.csv\"),'r')\n",
"\n",
"# Read the EoS data as csv file and organized into two arrays with density and energies\n",
"EoS = pd.read_csv(infile, names=('Density', 'Energy'))\n",
"EoS['Energy'] = pd.to_numeric(EoS['Energy'], errors='coerce')\n",
"EoS = EoS.dropna()\n",
"Energies = EoS['Energy']\n",
"Density = EoS['Density']\n",
"# The design matrix now as function of various polytrops\n",
"X = np.zeros((len(Density),5))\n",
"X[:,0] = 1\n",
"X[:,1] = Density**(2.0/3.0)\n",
"X[:,2] = Density\n",
"X[:,3] = Density**(4.0/3.0)\n",
"X[:,4] = Density**(5.0/3.0)\n",
"# We split the data in test and training data\n",
"X_train, X_test, y_train, y_test = train_test_split(X, Energies, test_size=0.2)\n",
"# matrix inversion to find beta\n",
"beta = np.linalg.inv(X_train.T.dot(X_train)).dot(X_train.T).dot(y_train)\n",
"# and then make the prediction\n",
"ytilde = X_train @ beta\n",
"print(\"Training R2\")\n",
"print(R2(y_train,ytilde))\n",
"print(\"Training MSE\")\n",
"print(MSE(y_train,ytilde))\n",
"ypredict = X_test @ beta\n",
"print(\"Test R2\")\n",
"print(R2(y_test,ypredict))\n",
"print(\"Test MSE\")\n",
"print(MSE(y_test,ypredict))"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## The Boston housing data example\n",
"\n",
"The Boston housing \n",
"data set was originally a part of UCI Machine Learning Repository\n",
"and has been removed now. The data set is now included in **Scikit-Learn**'s \n",
"library. There are 506 samples and 13 feature (predictor) variables\n",
"in this data set. The objective is to predict the value of prices of\n",
"the house using the features (predictors) listed here.\n",
"\n",
"The features/predictors are\n",
"1. CRIM: Per capita crime rate by town\n",
"\n",
"2. ZN: Proportion of residential land zoned for lots over 25000 square feet\n",
"\n",
"3. INDUS: Proportion of non-retail business acres per town\n",
"\n",
"4. CHAS: Charles River dummy variable (= 1 if tract bounds river; 0 otherwise)\n",
"\n",
"5. NOX: Nitric oxide concentration (parts per 10 million)\n",
"\n",
"6. RM: Average number of rooms per dwelling\n",
"\n",
"7. AGE: Proportion of owner-occupied units built prior to 1940\n",
"\n",
"8. DIS: Weighted distances to five Boston employment centers\n",
"\n",
"9. RAD: Index of accessibility to radial highways\n",
"\n",
"10. TAX: Full-value property tax rate per USD10000\n",
"\n",
"11. B: $1000(Bk - 0.63)^2$, where $Bk$ is the proportion of [people of African American descent] by town\n",
"\n",
"12. LSTAT: Percentage of lower status of the population\n",
"\n",
"13. MEDV: Median value of owner-occupied homes in USD 1000s\n",
"\n",
"## Housing data, the code\n",
"We start by importing the libraries"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false,
"editable": true
},
"outputs": [],
"source": [
"import numpy as np\n",
"import matplotlib.pyplot as plt \n",
"\n",
"import pandas as pd \n",
"import seaborn as sns"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"and load the Boston Housing DataSet from **Scikit-Learn**"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false,
"editable": true
},
"outputs": [],
"source": [
"from sklearn.datasets import load_boston\n",
"\n",
"boston_dataset = load_boston()\n",
"\n",
"# boston_dataset is a dictionary\n",
"# let's check what it contains\n",
"boston_dataset.keys()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Then we invoke Pandas"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false,
"editable": true
},
"outputs": [],
"source": [
"boston = pd.DataFrame(boston_dataset.data, columns=boston_dataset.feature_names)\n",
"boston.head()\n",
"boston['MEDV'] = boston_dataset.target"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"and preprocess the data"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false,
"editable": true
},
"outputs": [],
"source": [
"# check for missing values in all the columns\n",
"boston.isnull().sum()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"We can then visualize the data"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false,
"editable": true
},
"outputs": [],
"source": [
"# set the size of the figure\n",
"sns.set(rc={'figure.figsize':(11.7,8.27)})\n",
"\n",
"# plot a histogram showing the distribution of the target values\n",
"sns.distplot(boston['MEDV'], bins=30)\n",
"plt.show()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"It is now useful to look at the correlation matrix"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false,
"editable": true
},
"outputs": [],
"source": [
"# compute the pair wise correlation for all columns \n",
"correlation_matrix = boston.corr().round(2)\n",
"# use the heatmap function from seaborn to plot the correlation matrix\n",
"# annot = True to print the values inside the square\n",
"sns.heatmap(data=correlation_matrix, annot=True)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"From the above coorelation plot we can see that **MEDV** is strongly correlated to **LSTAT** and **RM**. We see also that **RAD** and **TAX** are stronly correlated, but we don't include this in our features together to avoid multi-colinearity"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false,
"editable": true
},
"outputs": [],
"source": [
"plt.figure(figsize=(20, 5))\n",
"\n",
"features = ['LSTAT', 'RM']\n",
"target = boston['MEDV']\n",
"\n",
"for i, col in enumerate(features):\n",
" plt.subplot(1, len(features) , i+1)\n",
" x = boston[col]\n",
" y = target\n",
" plt.scatter(x, y, marker='o')\n",
" plt.title(col)\n",
" plt.xlabel(col)\n",
" plt.ylabel('MEDV')"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Now we start training our model"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false,
"editable": true
},
"outputs": [],
"source": [
"X = pd.DataFrame(np.c_[boston['LSTAT'], boston['RM']], columns = ['LSTAT','RM'])\n",
"Y = boston['MEDV']"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"We split the data into training and test sets"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false,
"editable": true
},
"outputs": [],
"source": [
"from sklearn.model_selection import train_test_split\n",
"\n",
"# splits the training and test data set in 80% : 20%\n",
"# assign random_state to any value.This ensures consistency.\n",
"X_train, X_test, Y_train, Y_test = train_test_split(X, Y, test_size = 0.2, random_state=5)\n",
"print(X_train.shape)\n",
"print(X_test.shape)\n",
"print(Y_train.shape)\n",
"print(Y_test.shape)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Then we use the linear regression functionality from **Scikit-Learn**"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false,
"editable": true
},
"outputs": [],
"source": [
"from sklearn.linear_model import LinearRegression\n",
"from sklearn.metrics import mean_squared_error, r2_score\n",
"\n",
"lin_model = LinearRegression()\n",
"lin_model.fit(X_train, Y_train)\n",
"\n",
"# model evaluation for training set\n",
"\n",
"y_train_predict = lin_model.predict(X_train)\n",
"rmse = (np.sqrt(mean_squared_error(Y_train, y_train_predict)))\n",
"r2 = r2_score(Y_train, y_train_predict)\n",
"\n",
"print(\"The model performance for training set\")\n",
"print(\"--------------------------------------\")\n",
"print('RMSE is {}'.format(rmse))\n",
"print('R2 score is {}'.format(r2))\n",
"print(\"\\n\")\n",
"\n",
"# model evaluation for testing set\n",
"\n",
"y_test_predict = lin_model.predict(X_test)\n",
"# root mean square error of the model\n",
"rmse = (np.sqrt(mean_squared_error(Y_test, y_test_predict)))\n",
"\n",
"# r-squared score of the model\n",
"r2 = r2_score(Y_test, y_test_predict)\n",
"\n",
"print(\"The model performance for testing set\")\n",
"print(\"--------------------------------------\")\n",
"print('RMSE is {}'.format(rmse))\n",
"print('R2 score is {}'.format(r2))"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false,
"editable": true
},
"outputs": [],
"source": [
"# plotting the y_test vs y_pred\n",
"# ideally should have been a straight line\n",
"plt.scatter(Y_test, y_test_predict)\n",
"plt.show()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Reducing the number of degrees of freedom, overarching view\n",
"\n",
"Many Machine Learning problems involve thousands or even millions of\n",
"features for each training instance. Not only does this make training\n",
"extremely slow, it can also make it much harder to find a good\n",
"solution, as we will see. This problem is often referred to as the\n",
"curse of dimensionality. Fortunately, in real-world problems, it is\n",
"often possible to reduce the number of features considerably, turning\n",
"an intractable problem into a tractable one.\n",
"\n",
"Later we will discuss some of the most popular dimensionality reduction\n",
"techniques: the principal component analysis (PCA), Kernel PCA, and\n",
"Locally Linear Embedding (LLE). \n",
"\n",
"\n",
"Principal component analysis and its various variants deal with the\n",
"problem of fitting a low-dimensional [affine\n",
"subspace](https://en.wikipedia.org/wiki/Affine_space) to a set of of\n",
"data points in a high-dimensional space. With its family of methods it\n",
"is one of the most used tools in data modeling, compression and\n",
"visualization.\n",
"\n",
"\n",
"Before we proceed however, we will discuss how to preprocess our\n",
"data. Till now and in connection with our previous examples we have\n",
"not met so many cases where we are too sensitive to the scaling of our\n",
"data. Normally the data may need a rescaling and/or may be sensitive\n",
"to extreme values. Scaling the data renders our inputs much more\n",
"suitable for the algorithms we want to employ.\n",
"\n",
"**Scikit-Learn** has several functions which allow us to rescale the\n",
"data, normally resulting in much better results in terms of various\n",
"accuracy scores. The **StandardScaler** function in **Scikit-Learn**\n",
"ensures that for each feature/predictor we study the mean value is\n",
"zero and the variance is one (every column in the design/feature\n",
"matrix). This scaling has the drawback that it does not ensure that\n",
"we have a particular maximum or minimum in our data set. Another\n",
"function included in **Scikit-Learn** is the **MinMaxScaler** which\n",
"ensures that all features are exactly between $0$ and $1$. The\n",
"\n",
"\n",
"The **Normalizer** scales each data\n",
"point such that the feature vector has a euclidean length of one. In other words, it\n",
"projects a data point on the circle (or sphere in the case of higher dimensions) with a\n",
"radius of 1. This means every data point is scaled by a different number (by the\n",
"inverse of its length).\n",
"This normalization is often used when only the direction (or angle) of the data matters,\n",
"not the length of the feature vector.\n",
"\n",
"The **RobustScaler** works similarly to the StandardScaler in that it\n",
"ensures statistical properties for each feature that guarantee that\n",
"they are on the same scale. However, the RobustScaler uses the median\n",
"and quartiles, instead of mean and variance. This makes the\n",
"RobustScaler ignore data points that are very different from the rest\n",
"(like measurement errors). These odd data points are also called\n",
"outliers, and might often lead to trouble for other scaling\n",
"techniques.\n",
"\n",
"\n",
"### Simple preprocessing examples, Franke function and regression"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false,
"editable": true
},
"outputs": [],
"source": [
"# Common imports\n",
"import os\n",
"import numpy as np\n",
"import pandas as pd\n",
"import matplotlib.pyplot as plt\n",
"import sklearn.linear_model as skl\n",
"from sklearn.metrics import mean_squared_error\n",
"from sklearn.model_selection import train_test_split\n",
"from sklearn.preprocessing import MinMaxScaler, StandardScaler, Normalizer\n",
"\n",
"# Where to save the figures and data files\n",
"PROJECT_ROOT_DIR = \"Results\"\n",
"FIGURE_ID = \"Results/FigureFiles\"\n",
"DATA_ID = \"DataFiles/\"\n",
"\n",
"if not os.path.exists(PROJECT_ROOT_DIR):\n",
" os.mkdir(PROJECT_ROOT_DIR)\n",
"\n",
"if not os.path.exists(FIGURE_ID):\n",
" os.makedirs(FIGURE_ID)\n",
"\n",
"if not os.path.exists(DATA_ID):\n",
" os.makedirs(DATA_ID)\n",
"\n",
"def image_path(fig_id):\n",
" return os.path.join(FIGURE_ID, fig_id)\n",
"\n",
"def data_path(dat_id):\n",
" return os.path.join(DATA_ID, dat_id)\n",
"\n",
"def save_fig(fig_id):\n",
" plt.savefig(image_path(fig_id) + \".png\", format='png')\n",
"\n",
"\n",
"def FrankeFunction(x,y):\n",
"\tterm1 = 0.75*np.exp(-(0.25*(9*x-2)**2) - 0.25*((9*y-2)**2))\n",
"\tterm2 = 0.75*np.exp(-((9*x+1)**2)/49.0 - 0.1*(9*y+1))\n",
"\tterm3 = 0.5*np.exp(-(9*x-7)**2/4.0 - 0.25*((9*y-3)**2))\n",
"\tterm4 = -0.2*np.exp(-(9*x-4)**2 - (9*y-7)**2)\n",
"\treturn term1 + term2 + term3 + term4\n",
"\n",
"\n",
"def create_X(x, y, n ):\n",
"\tif len(x.shape) > 1:\n",
"\t\tx = np.ravel(x)\n",
"\t\ty = np.ravel(y)\n",
"\n",
"\tN = len(x)\n",
"\tl = int((n+1)*(n+2)/2)\t\t# Number of elements in beta\n",
"\tX = np.ones((N,l))\n",
"\n",
"\tfor i in range(1,n+1):\n",
"\t\tq = int((i)*(i+1)/2)\n",
"\t\tfor k in range(i+1):\n",
"\t\t\tX[:,q+k] = (x**(i-k))*(y**k)\n",
"\n",
"\treturn X\n",
"\n",
"\n",
"# Making meshgrid of datapoints and compute Franke's function\n",
"n = 5\n",
"N = 1000\n",
"x = np.sort(np.random.uniform(0, 1, N))\n",
"y = np.sort(np.random.uniform(0, 1, N))\n",
"z = FrankeFunction(x, y)\n",
"X = create_X(x, y, n=n) \n",
"# split in training and test data\n",
"X_train, X_test, y_train, y_test = train_test_split(X,z,test_size=0.2)\n",
"\n",
"\n",
"clf = skl.LinearRegression().fit(X_train, y_train)\n",
"\n",
"# The mean squared error and R2 score\n",
"print(\"MSE before scaling: {:.2f}\".format(mean_squared_error(clf.predict(X_test), y_test)))\n",
"print(\"R2 score before scaling {:.2f}\".format(clf.score(X_test,y_test)))\n",
"\n",
"scaler = StandardScaler()\n",
"scaler.fit(X_train)\n",
"X_train_scaled = scaler.transform(X_train)\n",
"X_test_scaled = scaler.transform(X_test)\n",
"\n",
"print(\"Feature min values before scaling:\\n {}\".format(X_train.min(axis=0)))\n",
"print(\"Feature max values before scaling:\\n {}\".format(X_train.max(axis=0)))\n",
"\n",
"print(\"Feature min values after scaling:\\n {}\".format(X_train_scaled.min(axis=0)))\n",
"print(\"Feature max values after scaling:\\n {}\".format(X_train_scaled.max(axis=0)))\n",
"\n",
"clf = skl.LinearRegression().fit(X_train_scaled, y_train)\n",
"\n",
"\n",
"print(\"MSE after scaling: {:.2f}\".format(mean_squared_error(clf.predict(X_test_scaled), y_test)))\n",
"print(\"R2 score for scaled data: {:.2f}\".format(clf.score(X_test_scaled,y_test)))"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Exercises\n",
"\n",
"### Exercise: Setting up various Python environments\n",
"\n",
"The first exercise here is of a mere technical art. We want you to have \n",
"* git as a version control software and to establish a user account on a provider like GitHub. Other providers like GitLab etc are equally fine. You can also use the University of Oslo [GitHub facilities](https://www.uio.no/tjenester/it/maskin/filer/versjonskontroll/github.html). \n",
"\n",
"* Install various Python packages\n",
"\n",
"We will make extensive use of Python as programming language and its\n",
"myriad of available libraries. You will find\n",
"IPython/Jupyter notebooks invaluable in your work. You can run **R**\n",
"codes in the Jupyter/IPython notebooks, with the immediate benefit of\n",
"visualizing your data. You can also use compiled languages like C++,\n",
"Rust, Fortran etc if you prefer. The focus in these lectures will be\n",
"on Python.\n",
"\n",
"If you have Python installed (we recommend Python3) and you feel\n",
"pretty familiar with installing different packages, we recommend that\n",
"you install the following Python packages via **pip** as \n",
"\n",
"1. pip install numpy scipy matplotlib ipython scikit-learn sympy pandas pillow \n",
"\n",
"For **Tensorflow**, we recommend following the instructions in the text of \n",
"[Aurelien Geron, HandsOn Machine Learning with ScikitLearn and TensorFlow, O'Reilly](http://shop.oreilly.com/product/0636920052289.do)\n",
"\n",
"We will come back to **tensorflow** later. \n",
"\n",
"For Python3, replace **pip** with **pip3**.\n",
"\n",
"For OSX users we recommend, after having installed Xcode, to\n",
"install **brew**. Brew allows for a seamless installation of additional\n",
"software via for example \n",
"\n",
"1. brew install python3\n",
"\n",
"For Linux users, with its variety of distributions like for example the widely popular Ubuntu distribution,\n",
"you can use **pip** as well and simply install Python as \n",
"\n",
"1. sudo apt-get install python3 (or python for Python2.7)\n",
"\n",
"If you don't want to perform these operations separately and venture\n",
"into the hassle of exploring how to set up dependencies and paths, we\n",
"recommend two widely used distrubutions which set up all relevant\n",
"dependencies for Python, namely \n",
"\n",
"* [Anaconda](https://docs.anaconda.com/), \n",
"\n",
"which is an open source\n",
"distribution of the Python and R programming languages for large-scale\n",
"data processing, predictive analytics, and scientific computing, that\n",
"aims to simplify package management and deployment. Package versions\n",
"are managed by the package management system **conda**. \n",
"\n",
"* [Enthought canopy](https://www.enthought.com/product/canopy/) \n",
"\n",
"is a Python\n",
"distribution for scientific and analytic computing distribution and\n",
"analysis environment, available for free and under a commercial\n",
"license.\n",
"\n",
"We recommend using **Anaconda** if you are not too familiar with setting paths in a terminal environment.\n",
"\n",
"\n",
"\n",
"\n",
"### Exercise: making your own data and exploring scikit-learn\n",
"\n",
"We will generate our own dataset for a function $y(x)$ where $x \\in [0,1]$ and defined by random numbers computed with the uniform distribution. The function $y$ is a quadratic polynomial in $x$ with added stochastic noise according to the normal distribution $\\cal {N}(0,1)$.\n",
"The following simple Python instructions define our $x$ and $y$ values (with 100 data points)."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false,
"editable": true
},
"outputs": [],
"source": [
"x = np.random.rand(100,1)\n",
"y = 2.0+5*x*x+0.1*np.random.randn(100,1)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"1. Write your own code (following the examples under the [regression notes](https://compphysics.github.io/MachineLearning/doc/LectureNotes/_build/html/chapter1.html)) for computing the parametrization of the data set fitting a second-order polynomial. \n",
"\n",
"2. Use thereafter **scikit-learn** (see again the examples in the regression slides) and compare with your own code. \n",
"\n",
"3. Using scikit-learn, compute also the mean square error, a risk metric corresponding to the expected value of the squared (quadratic) error defined as"
]
},
{
"cell_type": "markdown",
"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 for it, you can use your own program and define functions which compute the above two functions. \n",
"Discuss the meaning of these results. Try also to vary the coefficient in front of the added stochastic noise term and discuss the quality of the fits.\n",
"\n",
"!bsol\n",
"The code here is an example of where we define our own design matrix and fit parameters $\\beta$."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false,
"editable": true
},
"outputs": [],
"source": [
"import os\n",
"import numpy as np\n",
"import pandas as pd\n",
"import matplotlib.pyplot as plt\n",
"from sklearn.model_selection import train_test_split\n",
"\n",
"def save_fig(fig_id):\n",
" plt.savefig(image_path(fig_id) + \".png\", format='png')\n",
"\n",
"def R2(y_data, y_model):\n",
" return 1 - np.sum((y_data - y_model) ** 2) / np.sum((y_data - np.mean(y_data)) ** 2)\n",
"def MSE(y_data,y_model):\n",
" n = np.size(y_model)\n",
" return np.sum((y_data-y_model)**2)/n\n",
"\n",
"x = np.random.rand(100)\n",
"y = 2.0+5*x*x+0.1*np.random.randn(100)\n",
"\n",
"\n",
"# The design matrix now as function of a given polynomial\n",
"X = np.zeros((len(x),3))\n",
"X[:,0] = 1.0\n",
"X[:,1] = x\n",
"X[:,2] = x**2\n",
"# We split the data in test and training data\n",
"X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2)\n",
"# matrix inversion to find beta\n",
"beta = np.linalg.inv(X_train.T @ X_train) @ X_train.T @ y_train\n",
"print(beta)\n",
"# and then make the prediction\n",
"ytilde = X_train @ beta\n",
"print(\"Training R2\")\n",
"print(R2(y_train,ytilde))\n",
"print(\"Training MSE\")\n",
"print(MSE(y_train,ytilde))\n",
"ypredict = X_test @ beta\n",
"print(\"Test R2\")\n",
"print(R2(y_test,ypredict))\n",
"print(\"Test MSE\")\n",
"print(MSE(y_test,ypredict))"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"!esol\n",
"\n",
"\n",
"\n",
"### Exercise: Normalizing our data\n",
"\n",
"A much used approach before starting to train the data is to preprocess our\n",
"data. Normally the data may need a rescaling and/or may be sensitive\n",
"to extreme values. Scaling the data renders our inputs much more\n",
"suitable for the algorithms we want to employ.\n",
"\n",
"**Scikit-Learn** has several functions which allow us to rescale the\n",
"data, normally resulting in much better results in terms of various\n",
"accuracy scores. The **StandardScaler** function in **Scikit-Learn**\n",
"ensures that for each feature/predictor we study the mean value is\n",
"zero and the variance is one (every column in the design/feature\n",
"matrix). This scaling has the drawback that it does not ensure that\n",
"we have a particular maximum or minimum in our data set. Another\n",
"function included in **Scikit-Learn** is the **MinMaxScaler** which\n",
"ensures that all features are exactly between $0$ and $1$. The\n",
"\n",
"\n",
"The **Normalizer** scales each data\n",
"point such that the feature vector has a euclidean length of one. In other words, it\n",
"projects a data point on the circle (or sphere in the case of higher dimensions) with a\n",
"radius of 1. This means every data point is scaled by a different number (by the\n",
"inverse of its length).\n",
"This normalization is often used when only the direction (or angle) of the data matters,\n",
"not the length of the feature vector.\n",
"\n",
"The **RobustScaler** works similarly to the StandardScaler in that it\n",
"ensures statistical properties for each feature that guarantee that\n",
"they are on the same scale. However, the RobustScaler uses the median\n",
"and quartiles, instead of mean and variance. This makes the\n",
"RobustScaler ignore data points that are very different from the rest\n",
"(like measurement errors). These odd data points are also called\n",
"outliers, and might often lead to trouble for other scaling\n",
"techniques.\n",
"\n",
"\n",
"It also common to split the data in a **training** set and a **testing** set. A typical split is to use $80\\%$ of the data for training and the rest\n",
"for testing. This can be done as follows with our design matrix $\\boldsymbol{X}$ and data $\\boldsymbol{y}$ (remember to import **scikit-learn**)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false,
"editable": true
},
"outputs": [],
"source": [
"# split in training and test data\n",
"X_train, X_test, y_train, y_test = train_test_split(X,y,test_size=0.2)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Then we can use the standard scaler to scale our data as"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false,
"editable": true
},
"outputs": [],
"source": [
"scaler = StandardScaler()\n",
"scaler.fit(X_train)\n",
"X_train_scaled = scaler.transform(X_train)\n",
"X_test_scaled = scaler.transform(X_test)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"In this exercise we want you to to compute the MSE for the training\n",
"data and the test data as function of the complexity of a polynomial,\n",
"that is the degree of a given polynomial. We want you also to compute the $R2$ score as function of the complexity of the model for both training data and test data. You should also run the calculation with and without scaling. \n",
"\n",
"One of \n",
"the aims is to reproduce Figure 2.11 of [Hastie et al](https://github.com/CompPhysics/MLErasmus/blob/master/doc/Textbooks/elementsstat.pdf).\n",
"\n",
"\n",
"\n",
"Our data is defined by $x\\in [-3,3]$ with a total of for example $100$ data points."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false,
"editable": true
},
"outputs": [],
"source": [
"np.random.seed()\n",
"n = 100\n",
"maxdegree = 14\n",
"# Make data set.\n",
"x = np.linspace(-3, 3, n).reshape(-1, 1)\n",
"y = np.exp(-x**2) + 1.5 * np.exp(-(x-2)**2)+ np.random.normal(0, 0.1, x.shape)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"where $y$ is the function we want to fit with a given polynomial.\n",
"!bsubex\n",
"Write a first code which sets up a design matrix $X$ defined by a fifth-order polynomial. Scale your data and split it in training and test data. \n",
"!esubex\n",
"\n",
"!bsubex\n",
"Perform an ordinary least squares and compute the means squared error and the $R2$ factor for the training data and the test data, with and without scaling.\n",
"!esubex\n",
"\n",
"!bsubex\n",
"Add now a model which allows you to make polynomials up to degree $15$. Perform a standard OLS fitting of the training data and compute the MSE and $R2$ for the training and test data and plot both test and training data MSE and $R2$ as functions of the polynomial degree. Compare what you see with Figure 2.11 of Hastie et al. Comment your results. For which polynomial degree do you find an optimal MSE (smallest value)?\n",
"!bsol\n",
"Here you simply need to change the degree of the polynomial in the above code to $n=15$.\n",
"!esol\n",
"!esubex"
]
}
],
"metadata": {},
"nbformat": 4,
"nbformat_minor": 4
}