diff --git a/doc/LectureNotes/.book.copyright b/doc/LectureNotes/.book.copyright index 4a0005b5d..0507b6521 100644 --- a/doc/LectureNotes/.book.copyright +++ b/doc/LectureNotes/.book.copyright @@ -1 +1 @@ -{'holder': ['Morten Hjorth-Jensen'], 'year': '1999-2018', 'license': 'Released under CC Attribution-NonCommercial 4.0 license', 'cite doconce': False} \ No newline at end of file +{'holder': ['Morten Hjorth-Jensen'], 'year': '1999-2019', 'license': 'Released under CC Attribution-NonCommercial 4.0 license', 'cite doconce': False} \ No newline at end of file diff --git a/doc/LectureNotes/book.dlog b/doc/LectureNotes/book.dlog index 07cf15422..cfdaa7fef 100644 --- a/doc/LectureNotes/book.dlog +++ b/doc/LectureNotes/book.dlog @@ -229,3 +229,2758 @@ collected all required additional files in ipynb-book-src.tar.gz which must be d environments in math environments. output in book.ipynb +translating doconce text in book.do.txt to ipynb +ERROR: 2 !bblock do not match 4 !eblock directives + + +Two !eblock after each other! + +!eblock + + +===== Numpy and arrays ===== +"Numpy":"http://www.numpy.org/" provides an easy way to handle arrays in Python. The standard way to import this library is as + +!bc pycod +import numpy as np +!ec +Here follows a simple example where we set up an array of ten elements, all determined by random numbers drawn according to the normal distribution, +!bc pycod +n = 10 +x = np.random.normal(size=n) +print(x) +!ec +We defined a vector $x$ with $n=10$ elements with its values given by the Normal distribution $N(0,1)$. +Another alternative is to declare a vector as follows +!bc pycod +import numpy as np +x = np.array([1, 2, 3]) +print(x) +!ec +Here we have defined a vector with three elements, with $x_0=1$, $x_1=2$ and $x_2=3$. Note that both Python and C++ +start numbering array elements from $0$ and on. This means that a vector with $n$ elements has a sequence of entities $x_0, x_1, x_2, \dots, x_{n-1}$. We could also let (recommended) Numpy to compute the logarithms of a specific array as +!bc pycod +import numpy as np +x = np.log(np.array([4, 7, 8])) +print(x) +!ec + +In the last example we used Numpy's unary function $np.log$. This function is +highly tuned to compute array elements since the code is vectorized +and does not require looping. We normaly recommend that you use the +Numpy intrinsic functions instead of the corresponding _log_ function +from Python's _math_ module. The looping is done explicitely by the +_np.log_ function. The alternative, and slower way to compute the +logarithms of a vector would be to write + +!bc pycod +import numpy as np +from math import log +x = np.array([4, 7, 8]) +for i in range(0, len(x)): + x[i] = log(x[i]) +print(x) +!ec +We note that our code is much longer already and we need to import the _log_ function from the _math_ module. +The attentive reader will also notice that the output is $[1, 1, 2]$. Python interprets automagically our numbers as integers (like the _automatic_ keyword in C++). To change this we could define our array elements to be double precision numbers as +!bc pycod +import numpy as np +x = np.log(np.array([4, 7, 8], dtype = np.float64)) +print(x) +!ec +or simply write them as double precision numbers (Python uses 64 bits as default for floating point type variables), that is +!bc pycod +import numpy as np +x = np.log(np.array([4.0, 7.0, 8.0]) +print(x) +!ec +To check the number of bytes (remember that one byte contains eight bits for double precision variables), you can use simple use the _itemsize_ functionality (the array $x$ is actually an object which inherits the functionalities defined in Numpy) as +!bc pycod +import numpy as np +x = np.log(np.array([4.0, 7.0, 8.0]) +print(x.itemsize) +!ec + + +===== Matrices in Python ===== + +Having defined vectors, we are now ready to try out matrices. We can +define a $3 \times 3 $ real matrix $\hat{A}$ as (recall that we user +lowercase letters for vectors and uppercase letters for matrices) + +!bc pycod +import numpy as np +A = np.log(np.array([ [4.0, 7.0, 8.0], [3.0, 10.0, 11.0], [4.0, 5.0, 7.0] ])) +print(A) +!ec +If we use the _shape_ function we would get $(3, 3)$ as output, that is verifying that our matrix is a $3\times 3$ matrix. We can slice the matrix and print for example the first column (Python organized matrix elements in a row-major order, see below) as +!bc pycod +import numpy as np +A = np.log(np.array([ [4.0, 7.0, 8.0], [3.0, 10.0, 11.0], [4.0, 5.0, 7.0] ])) +# print the first column, row-major order and elements start with 0 +print(A[:,0]) +!ec +We can continue this was by printing out other columns or rows. The example here prints out the second column +!bc pycod +import numpy as np +A = np.log(np.array([ [4.0, 7.0, 8.0], [3.0, 10.0, 11.0], [4.0, 5.0, 7.0] ])) +# print the first column, row-major order and elements start with 0 +print(A[1,:]) +!ec +Numpy contains many other functionalities that allow us to slice, subdivide etc etc arrays. We strongly recommend that you look up the "Numpy website for more details":"http://www.numpy.org/". Useful functions when defining a matrix are the _np.zeros_ function which declares a matrix of a given dimension and sets all elements to zero +!bc pycod +import numpy as np +n = 10 +# define a matrix of dimension 10 x 10 and set all elements to zero +A = np.zeros( (n, n) ) +print(A) +!ec +or initializing all elements to +!bc pycod +import numpy as np +n = 10 +# define a matrix of dimension 10 x 10 and set all elements to one +A = np.ones( (n, n) ) +print(A) +!ec +or as unitarily distributed random numbers (see the material on random number generators in the statistics part) +!bc pycod +import numpy as np +n = 10 +# define a matrix of dimension 10 x 10 and set all elements to random numbers with x \in [0, 1] +A = np.random.rand(n, n) +print(A) +!ec + +As we will see throughout these lectures, there are several extremely useful functionalities in Numpy. +As an example, consider the discussion of the covariance matrix. Suppose we have defined three vectors +$\hat{x}, \hat{y}, \hat{z}$ with $n$ elements each. The covariance matrix is defined as +!bt +\[ +\hat{\Sigma} = \begin{bmatrix} \sigma_{xx} & \sigma_{xy} & \sigma_{xz} \\ + \sigma_{yx} & \sigma_{yy} & \sigma_{yz} \\ + \sigma_{zx} & \sigma_{zy} & \sigma_{zz} + \end{bmatrix}, +\] +!et +where for example +!bt +\[ +\sigma_{xy} =\frac{1}{n} \sum_{i=0}^{n-1}(x_i- \overline{x})(y_i- \overline{y}). +\] +!et +The Numpy function _np.cov_ calculates the covariance elements using the factor $1/(n-1)$ instead of $1/n$ since it assumes we do not have the exact mean values. +The following simple function uses the _np.vstack_ function which takes each vector of dimension $1\times n$ and produces a $3\times n$ matrix $\hat{W}$ +!bt +\[ +\hat{W} = \begin{bmatrix} x_0 & y_0 & z_0 \\ + x_1 & y_1 & z_1 \\ + x_2 & y_2 & z_2 \\ + \dots & \dots & \dots \\ + x_{n-2} & y_{n-2} & z_{n-2} \\ + x_{n-1} & y_{n-1} & z_{n-1} + \end{bmatrix}, +\] +!et + +which in turn is converted into into the $3\times 3$ covariance matrix +$\hat{\Sigma}$ via the Numpy function _np.cov()_. We note that we can also calculate +the mean value of each set of samples $\hat{x}$ etc using the Numpy +function _np.mean(x)_. We can also extract the eigenvalues of the +covariance matrix through the _np.linalg.eig()_ function. + +!bc pycod +# Importing various packages +import numpy as np + +n = 100 +x = np.random.normal(size=n) +print(np.mean(x)) +y = 4+3*x+np.random.normal(size=n) +print(np.mean(y)) +z = x**3+np.random.normal(size=n) +print(np.mean(z)) +W = np.vstack((x, y, z)) +Sigma = np.cov(W) +print(Sigma) +Eigvals, Eigvecs = np.linalg.eig(Sigma) +print(Eigvals) +!ec + + +!bc pycod +import numpy as np +import matplotlib.pyplot as plt +from scipy import sparse +eye = np.eye(4) +print(eye) +sparse_mtx = sparse.csr_matrix(eye) +print(sparse_mtx) +x = np.linspace(-10,10,100) +y = np.sin(x) +plt.plot(x,y,marker='x') +plt.show() +!ec + + +===== Meet the Pandas ===== + + +FIGURE: [fig/pandas.jpg, width=600 frac=0.8] + +Another useful Python package is +"pandas":"https://pandas.pydata.org/", which is an open source library +providing high-performance, easy-to-use data structures and data +analysis tools for Python. _pandas_ stands for panel data, a term borrowed from econometrics and is an efficient library for data analysis with an emphasis on tabular data. +_pandas_ has two major classes, the _DataFrame_ class with two-dimensional data objects and tabular data organized in columns and the class _Series_ with a focus on one-dimensional data objects. Both classes allow you to index data easily as we will see in the examples below. +_pandas_ allows you also to perform mathematical operations on the data, spanning from simple reshapings of vectors and matrices to statistical operations. + +The following simple example shows how we can, in an easy way make tables of our data. Here we define a data set which includes names, place of birth and date of birth, and displays the data in an easy to read way. We will see repeated use of _pandas_, in particular in connection with classification of data. + +!bc pycod +import pandas as pd +from IPython.display import display +data = {'First Name': ["Frodo", "Bilbo", "Aragorn II", "Samwise"], + 'Last Name': ["Baggins", "Baggins","Elessar","Gamgee"], + 'Place of birth': ["Shire", "Shire", "Eriador", "Shire"], + 'Date of Birth T.A.': [2968, 2890, 2931, 2980] + } +data_pandas = pd.DataFrame(data) +display(data_pandas) +!ec + +In the above we have imported _pandas_ with the shorthand _pd_, the latter has become the standard way we import _pandas_. We make then a list of various variables +and reorganize the aboves lists into a _DataFrame_ and then print out a neat table with specific column labels as *Name*, *place of birth* and *date of birth*. +Displaying these results, we see that the indices are given by the default numbers from zero to three. +_pandas_ is extremely flexible and we can easily change the above indices by defining a new type of indexing as +!bc pycod +data_pandas = pd.DataFrame(data,index=['Frodo','Bilbo','Aragorn','Sam']) +display(data_pandas) +!ec +Thereafter we display the content of the row which begins with the index _Aragorn_ +!bc pycod +display(data_pandas.loc['Aragorn']) +!ec + +We can easily append data to this, for example +!bc pycod +new_hobbit = {'First Name': ["Peregrin"], + 'Last Name': ["Took"], + 'Place of birth': ["Shire"], + 'Date of Birth T.A.': [2990] + } +data_pandas=data_pandas.append(pd.DataFrame(new_hobbit, index=['Pippin'])) +display(data_pandas) +!ec + + +Here are other examples where we use the _DataFrame_ functionality to handle arrays, now with more interesting features for us, namely numbers. We set up a matrix +of dimensionality $10\times 5$ and compute the mean value and standard deviation of each column. Similarly, we can perform mathematial operations like squaring the matrix elements and many other operations. +!bc pycod +import numpy as np +import pandas as pd +from IPython.display import display +np.random.seed(100) +# setting up a 10 x 5 matrix +rows = 10 +cols = 5 +a = np.random.randn(rows,cols) +df = pd.DataFrame(a) +display(df) +print(df.mean()) +print(df.std()) +display(df**2) +!ec + +Thereafter we can select specific columns only and plot final results +!bc pycod +df.columns = ['First', 'Second', 'Third', 'Fourth', 'Fifth'] +df.index = np.arange(10) + +display(df) +print(df['Second'].mean() ) +print(df.info()) +print(df.describe()) + +from pylab import plt, mpl +plt.style.use('seaborn') +mpl.rcParams['font.family'] = 'serif' + +df.cumsum().plot(lw=2.0, figsize=(10,6)) +plt.show() + + +df.plot.bar(figsize=(10,6), rot=15) +plt.show() +!ec +We can produce a $4\times 4$ matrix +!bc pycod +b = np.arange(16).reshape((4,4)) +print(b) +df1 = pd.DataFrame(b) +print(df1) +!ec +and many other operations. + +The _Series_ class is another important class included in +_pandas_. You can view it as a specialization of _DataFrame_ but where +we have just a single column of data. It shares many of the same features as _DataFrame. As with _DataFrame_, +most operations are vectorized, achieving thereby a high performance when dealing with computations of arrays, in particular labeled arrays. +As we will see below it leads also to a very concice code close to the mathematical operations we may be interested in. +For multidimensional arrays, we recommend strongly "xarray":"http://xarray.pydata.org/en/stable/". _xarray_ has much of the same flexibility as _pandas_, but allows for the extension to higher dimensions than two. We will see examples later of the usage of both _pandas_ and _xarray_. + + + +===== Reading Data and fitting ===== + +In order to study various Machine Learning algorithms, we need to +access data. Acccessing data is an essential step in all machine +learning algorithms. In particular, setting up the so-called _design +matrix_ (to be defined below) is often the first element we need in +order to perform our calculations. To set up the design matrix means +reading (and later, when the calculations are done, writing) data +in various formats, The formats span from reading files from disk, +loading data from databases and interacting with online sources +like web application programming interfaces (APIs). + +In handling various input formats, as discussed above, we will mainly stay with _pandas_, +a Python package which allows us, in a seamless and painless way, to +deal with a multitude of formats, from standard _csv_ (comma separated +values) files, via _excel_, _html_ to _hdf5_ formats. With _pandas_ +and the _DataFrame_ and _Series_ functionalities we are able to convert text data +into the calculational formats we need for a specific algorithm. And our code is going to be +pretty close the basic mathematical expressions. + +Our first data set is going to be a classic from nuclear physics, namely all +available data on binding energies. Don't be intimidated if you are not familiar with nuclear physics. It serves simply as an example here of a data set. + +We will show some of the +strengths of packages like _Scikit-Learn_ in fitting nuclear binding energies to +specific functions using linear regression first. Then, as a teaser, we will show you how +you can easily implement other algorithms like decision trees and random forests and neural networks. + +But before we really start with nuclear physics data, let's just look at some simpler polynomial fitting cases, such as, +(don't be offended) fitting straight lines! + + +=== Simple linear regression model using _scikit-learn_ === + +We start with perhaps our simplest possible example, using _Scikit-Learn_ to perform linear regression analysis on a data set produced by us. + +What follows is a simple Python code where we have defined a function +$y$ in terms of the variable $x$. Both are defined as vectors with $100$ entries. +The numbers in the vector $\hat{x}$ are given +by random numbers generated with a uniform distribution with entries +$x_i \in [0,1]$ (more about probability distribution functions +later). These values are then used to define a function $y(x)$ +(tabulated again as a vector) with a linear dependence on $x$ plus a +random noise added via the normal distribution. + + +The Numpy functions are imported used the _import numpy as np_ +statement and the random number generator for the uniform distribution +is called using the function _np.random.rand()_, where we specificy +that we want $100$ random variables. Using Numpy we define +automatically an array with the specified number of elements, $100$ in +our case. With the Numpy function _randn()_ we can compute random +numbers with the normal distribution (mean value $\mu$ equal to zero and +variance $\sigma^2$ set to one) and produce the values of $y$ assuming a linear +dependence as function of $x$ + +!bt +\[ +y = 2x+N(0,1), +\] +!et + +where $N(0,1)$ represents random numbers generated by the normal +distribution. From _Scikit-Learn_ we import then the +_LinearRegression_ functionality and make a prediction $\tilde{y} = +\alpha + \beta x$ using the function _fit(x,y)_. We call the set of +data $(\hat{x},\hat{y})$ for our training data. The Python package +_scikit-learn_ has also a functionality which extracts the above +fitting parameters $\alpha$ and $\beta$ (see below). Later we will +distinguish between training data and test data. + +For plotting we use the Python package +"matplotlib":"https://matplotlib.org/" which produces publication +quality figures. Feel free to explore the extensive +"gallery":"https://matplotlib.org/gallery/index.html" of examples. In +this example we plot our original values of $x$ and $y$ as well as the +prediction _ypredict_ ($\tilde{y}$), which attempts at fitting our +data with a straight line. + +The Python code follows here. +!bc pycod +# Importing various packages +import numpy as np +import matplotlib.pyplot as plt +from sklearn.linear_model import LinearRegression + +x = np.random.rand(100,1) +y = 2*x+np.random.randn(100,1) +linreg = LinearRegression() +linreg.fit(x,y) +xnew = np.array([[0],[1]]) +ypredict = linreg.predict(xnew) + +plt.plot(xnew, ypredict, "r-") +plt.plot(x, y ,'ro') +plt.axis([0,1.0,0, 5.0]) +plt.xlabel(r'$x$') +plt.ylabel(r'$y$') +plt.title(r'Simple Linear Regression') +plt.show() +!ec + +This example serves several aims. It allows us to demonstrate several +aspects of data analysis and later machine learning algorithms. The +immediate visualization shows that our linear fit is not +impressive. It goes through the data points, but there are many +outliers which are not reproduced by our linear regression. We could +now play around with this small program and change for example the +factor in front of $x$ and the normal distribution. Try to change the +function $y$ to + +!bt +\[ +y = 10x+0.01 \times N(0,1), +\] +!et + +where $x$ is defined as before. Does the fit look better? Indeed, by +reducing the role of the noise given by the normal distribution we see immediately that +our linear prediction seemingly reproduces better the training +set. However, this testing 'by the eye' is obviouly not satisfactory in the +long run. Here we have only defined the training data and our model, and +have not discussed a more rigorous approach to the _cost_ function. + +We need more rigorous criteria in defining whether we have succeeded or +not in modeling our training data. You will be surprised to see that +many scientists seldomly venture beyond this 'by the eye' approach. A +standard approach for the *cost* function is the so-called $\chi^2$ +function (a variant of the mean-squared error (MSE)) + +!bt +\[ \chi^2 = \frac{1}{n} +\sum_{i=0}^{n-1}\frac{(y_i-\tilde{y}_i)^2}{\sigma_i^2}, +\] +!et + +where $\sigma_i^2$ is the variance (to be defined later) of the entry +$y_i$. We may not know the explicit value of $\sigma_i^2$, it serves +however the aim of scaling the equations and make the cost function +dimensionless. + +Minimizing the cost function is a central aspect of +our discussions to come. Finding its minima as function of the model +parameters ($\alpha$ and $\beta$ in our case) will be a recurring +theme in these series of lectures. Essentially all machine learning +algorithms we will discuss center around the minimization of the +chosen cost function. This depends in turn on our specific +model for describing the data, a typical situation in supervised +learning. Automatizing the search for the minima of the cost function is a +central ingredient in all algorithms. Typical methods which are +employed are various variants of _gradient_ methods. These will be +discussed in more detail later. Again, you'll be surprised to hear that +many practitioners minimize the above function ''by the eye', popularly dubbed as +'chi by the eye'. That is, change a parameter and see (visually and numerically) that +the $\chi^2$ function becomes smaller. + +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 +the relative error (why would we prefer the MSE instead of the relative error?) as + +!bt +\[ +\epsilon_{\mathrm{relative}}= \frac{\vert \hat{y} -\hat{\tilde{y}}\vert}{\vert \hat{y}\vert}. +\] +!et +We can modify easily the above Python code and plot the relative error instead +!bc pycod +import numpy as np +import matplotlib.pyplot as plt +from sklearn.linear_model import LinearRegression + +x = np.random.rand(100,1) +y = 5*x+0.01*np.random.randn(100,1) +linreg = LinearRegression() +linreg.fit(x,y) +ypredict = linreg.predict(x) + +plt.plot(x, np.abs(ypredict-y)/abs(y), "ro") +plt.axis([0,1.0,0.0, 0.5]) +plt.xlabel(r'$x$') +plt.ylabel(r'$\epsilon_{\mathrm{relative}}$') +plt.title(r'Relative error') +plt.show() +!ec + +Depending on the parameter in front of the normal distribution, we may +have a small or larger relative error. Try to play around with +different training data sets and study (graphically) the value of the +relative error. + +As mentioned above, _Scikit-Learn_ has an impressive functionality. +We can for example extract the values of $\alpha$ and $\beta$ and +their error estimates, or the variance and standard deviation and many +other properties from the statistical data analysis. + +Here we show an +example of the functionality of _Scikit-Learn_. +!bc pycod +import numpy as np +import matplotlib.pyplot as plt +from sklearn.linear_model import LinearRegression +from sklearn.metrics import mean_squared_error, r2_score, mean_squared_log_error, mean_absolute_error + +x = np.random.rand(100,1) +y = 2.0+ 5*x+0.5*np.random.randn(100,1) +linreg = LinearRegression() +linreg.fit(x,y) +ypredict = linreg.predict(x) +print('The intercept alpha: \n', linreg.intercept_) +print('Coefficient beta : \n', linreg.coef_) +# The mean squared error +print("Mean squared error: %.2f" % mean_squared_error(y, ypredict)) +# Explained variance score: 1 is perfect prediction +print('Variance score: %.2f' % r2_score(y, ypredict)) +# Mean squared log error +print('Mean squared log error: %.2f' % mean_squared_log_error(y, ypredict) ) +# Mean absolute error +print('Mean absolute error: %.2f' % mean_absolute_error(y, ypredict)) +plt.plot(x, ypredict, "r-") +plt.plot(x, y ,'ro') +plt.axis([0.0,1.0,1.5, 7.0]) +plt.xlabel(r'$x$') +plt.ylabel(r'$y$') +plt.title(r'Linear Regression fit ') +plt.show() + +!ec +The function _coef_ gives us the parameter $\beta$ of our fit while _intercept_ yields +$\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 +!bt +\[ MSE(\hat{y},\hat{\tilde{y}}) = \frac{1}{n} +\sum_{i=0}^{n-1}(y_i-\tilde{y}_i)^2, +\] +!et + +The smaller the value, the better the fit. Ideally we would like to +have an MSE equal zero. The attentive reader has probably recognized +this function as being similar to the $\chi^2$ function defined above. + +The _r2score_ function computes $R^2$, the coefficient of +determination. It provides a measure of how well future samples are +likely to be predicted by the model. Best possible score is 1.0 and it +can be negative (because the model can be arbitrarily worse). A +constant model that always predicts the expected value of $\hat{y}$, +disregarding the input features, would get a $R^2$ score of $0.0$. + +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 +!bt +\[ +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}, +\] +!et +where we have defined the mean value of $\hat{y}$ as +!bt +\[ +\bar{y} = \frac{1}{n} \sum_{i=0}^{n - 1} y_i. +\] +!et +Another quantity taht we will meet again in our discussions of regression analysis is + 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. +The MAE is defined as follows +!bt +\[ +\text{MAE}(\hat{y}, \hat{\tilde{y}}) = \frac{1}{n} \sum_{i=0}^{n-1} \left| y_i - \tilde{y}_i \right|. +\] +!et +Finally we present the +squared logarithmic (quadratic) error +!bt +\[ +\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, +\] +!et + +where $\log_e (x)$ stands for the natural logarithm of $x$. This error +estimate is best to use when targets having exponential growth, such +as population counts, average sales of a commodity over a span of +years etc. + +We will discuss in more +detail these and other functions in the various lectures. We conclude this part with another example. Instead of +a linear $x$-dependence we study now a cubic polynomial and use the polynomial regression analysis tools of scikit-learn. + +!bc pycod +import matplotlib.pyplot as plt +import numpy as np +import random +from sklearn.linear_model import Ridge +from sklearn.preprocessing import PolynomialFeatures +from sklearn.pipeline import make_pipeline +from sklearn.linear_model import LinearRegression + +x=np.linspace(0.02,0.98,200) +noise = np.asarray(random.sample((range(200)),200)) +y=x**3*noise +yn=x**3*100 +poly3 = PolynomialFeatures(degree=3) +X = poly3.fit_transform(x[:,np.newaxis]) +clf3 = LinearRegression() +clf3.fit(X,y) + +Xplot=poly3.fit_transform(x[:,np.newaxis]) +poly3_plot=plt.plot(x, clf3.predict(Xplot), label='Cubic Fit') +plt.plot(x,yn, color='red', label="True Cubic") +plt.scatter(x, y, label='Data', color='orange', s=15) +plt.legend() +plt.show() + +def error(a): + for i in y: + err=(y-yn)/yn + return abs(np.sum(err))/len(err) + +print (error(y)) +!ec + + + + +=== To our real data: nuclear binding energies. Brief reminder on masses and binding energies === + +Let us now dive into nuclear physics and remind ourselves briefly about some basic features about binding +energies. A basic quantity which can be measured for the ground +states of nuclei is the atomic mass $M(N, Z)$ of the neutral atom with +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). + +Atomic masses are usually tabulated in terms of the mass excess defined by +!bt +\[ +\Delta M(N, Z) = M(N, Z) - uA, +\] +!et +where $u$ is the Atomic Mass Unit +!bt +\[ +u = M(^{12}\mathrm{C})/12 = 931.4940954(57) \hspace{0.1cm} \mathrm{MeV}/c^2. +\] +!et +The nucleon masses are +!bt +\[ +m_p = 1.00727646693(9)u, +\] +!et +and +!bt +\[ +m_n = 939.56536(8)\hspace{0.1cm} \mathrm{MeV}/c^2 = 1.0086649156(6)u. +\] +!et + +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" +there are data on masses and decays of 3437 nuclei. + +The nuclear binding energy is defined as the energy required to break +up a given nucleus into its constituent parts of $N$ neutrons and $Z$ +protons. In terms of the atomic masses $M(N, Z)$ the binding energy is +defined by + + +!bt +\[ +BE(N, Z) = ZM_H c^2 + Nm_n c^2 - M(N, Z)c^2 , +\] +!et +where $M_H$ is the mass of the hydrogen atom and $m_n$ is the mass of the neutron. +In terms of the mass excess the binding energy is given by +!bt +\[ +BE(N, Z) = Z\Delta_H c^2 + N\Delta_n c^2 -\Delta(N, Z)c^2 , +\] +!et +where $\Delta_H c^2 = 7.2890$ MeV and $\Delta_n c^2 = 8.0713$ MeV. + + +A popular and physically intuitive model which can be used to parametrize +the experimental binding energies as function of $A$, is the so-called +_liquid drop model_. The ansatz is based on the following expression + +!bt +\[ +BE(N,Z) = a_1A-a_2A^{2/3}-a_3\frac{Z^2}{A^{1/3}}-a_4\frac{(N-Z)^2}{A}, +\] +!et + +where $A$ stands for the number of nucleons and the $a_i$s are parameters which are determined by a fit +to the experimental data. + + + + +To arrive at the above expression we have assumed that we can make the following assumptions: + + * 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. + + * 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. + + + * 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. + + * 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. + +We could also add a so-called pairing term, which is a correction term that +arises from the tendency of proton pairs and neutron pairs to +occur. An even number of particles is more stable than an odd number. + + +=== Organizing our data === + +Let us start with reading and organizing our data. +We start with the compilation of masses and binding energies from 2016. +After having downloaded this file to our own computer, we are now ready to read the file and start structuring our data. + + +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_. +!bc pycod +# Common imports +import numpy as np +import pandas as pd +import matplotlib.pyplot as plt +import sklearn.linear_model as skl +from sklearn.model_selection import train_test_split +from sklearn.metrics import mean_squared_error, r2_score, mean_absolute_error +import os + +# Where to save the figures and data files +PROJECT_ROOT_DIR = "Results" +FIGURE_ID = "Results/FigureFiles" +DATA_ID = "DataFiles/" + +if not os.path.exists(PROJECT_ROOT_DIR): + os.mkdir(PROJECT_ROOT_DIR) + +if not os.path.exists(FIGURE_ID): + os.makedirs(FIGURE_ID) + +if not os.path.exists(DATA_ID): + os.makedirs(DATA_ID) + +def image_path(fig_id): + return os.path.join(FIGURE_ID, fig_id) + +def data_path(dat_id): + return os.path.join(DATA_ID, dat_id) + +def save_fig(fig_id): + plt.savefig(image_path(fig_id) + ".png", format='png') + +infile = open(data_path("MassEval2016.dat"),'r') +!ec + + +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. +!bc pycod +from pylab import plt, mpl +plt.style.use('seaborn') +mpl.rcParams['font.family'] = 'serif' + +def MakePlot(x,y, styles, labels, axlabels): + plt.figure(figsize=(10,6)) + for i in range(len(x)): + plt.plot(x[i], y[i], styles[i], label = labels[i]) + plt.xlabel(axlabels[0]) + plt.ylabel(axlabels[1]) + plt.legend(loc=0) +!ec + +Our next step is to read the data on experimental binding energies and +reorganize them as functions of the mass number $A$, the number of +protons $Z$ and neutrons $N$ using _pandas_. Before we do this it is +always useful (unless you have a binary file or other types of compressed +data) to actually open the file and simply take a look at it! + + +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. +!bc pycod +""" +This is taken from the data file of the mass 2016 evaluation. +All files are 3436 lines long with 124 character per line. + Headers are 39 lines long. + col 1 : Fortran character control: 1 = page feed 0 = line feed + 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 + These formats are reflected in the pandas widths variable below, see the statement + widths=(1,3,5,5,5,1,3,4,1,13,11,11,9,1,2,11,9,1,3,1,12,11,1), + Pandas has also a variable header, with length 39 in this case. +""" +!ec + +The data we are interested in are in columns 2, 3, 4 and 11, giving us +the number of neutrons, protons, mass numbers and binding energies, +respectively. We add also for the sake of completeness the element name. The data are in fixed-width formatted lines and we will +covert them into the _pandas_ DataFrame structure. + +!bc pycod +# Read the experimental data with Pandas +Masses = pd.read_fwf(infile, usecols=(2,3,4,6,11), + names=('N', 'Z', 'A', 'Element', 'Ebinding'), + widths=(1,3,5,5,5,1,3,4,1,13,11,11,9,1,2,11,9,1,3,1,12,11,1), + header=39, + index_col=False) + +# Extrapolated values are indicated by '#' in place of the decimal place, so +# the Ebinding column won't be numeric. Coerce to float and drop these entries. +Masses['Ebinding'] = pd.to_numeric(Masses['Ebinding'], errors='coerce') +Masses = Masses.dropna() +# Convert from keV to MeV. +Masses['Ebinding'] /= 1000 + +# Group the DataFrame by nucleon number, A. +Masses = Masses.groupby('A') +# Find the rows of the grouped DataFrame with the maximum binding energy. +Masses = Masses.apply(lambda t: t[t.Ebinding==t.Ebinding.max()]) +!ec + +We have now read in the data, grouped them according to the variables we are interested in. +We see how easy it is to reorganize the data using _pandas_. If we +were to do these operations in C/C++ or Fortran, we would have had to +write various functions/subroutines which perform the above +reorganizations for us. Having reorganized the data, we can now start +to make some simple fits using both the functionalities in _numpy_ and +_Scikit-Learn_ afterwards. + +Now we define five variables which contain +the number of nucleons $A$, the number of protons $Z$ and the number of neutrons $N$, the element name and finally the energies themselves. +!bc pycod +A = Masses['A'] +Z = Masses['Z'] +N = Masses['N'] +Element = Masses['Element'] +Energies = Masses['Ebinding'] +print(Masses) +!ec +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 $\bm{X}$. +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. +!bc pycod +# Now we set up the design matrix X +X = np.zeros((len(A),5)) +X[:,0] = 1 +X[:,1] = A +X[:,2] = A**(2.0/3.0) +X[:,3] = A**(-1.0/3.0) +X[:,4] = A**(-1.0) +!ec +With _scikitlearn_ we are now ready to use linear regression and fit our data. +!bc pycod +clf = skl.LinearRegression().fit(X, Energies) +fity = clf.predict(X) +!ec +Pretty simple! +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. +!bc pycod +# The mean squared error +print("Mean squared error: %.2f" % mean_squared_error(Energies, fity)) +# Explained variance score: 1 is perfect prediction +print('Variance score: %.2f' % r2_score(Energies, fity)) +# Mean absolute error +print('Mean absolute error: %.2f' % mean_absolute_error(Energies, fity)) +print(clf.coef_, clf.intercept_) + +Masses['Eapprox'] = fity +# Generate a plot comparing the experimental with the fitted values values. +fig, ax = plt.subplots() +ax.set_xlabel(r'$A = N + Z$') +ax.set_ylabel(r'$E_\mathrm{bind}\,/\mathrm{MeV}$') +ax.plot(Masses['A'], Masses['Ebinding'], alpha=0.7, lw=2, + label='Ame2016') +ax.plot(Masses['A'], Masses['Eapprox'], alpha=0.7, lw=2, c='m', + label='Fit') +ax.legend() +save_fig("Masses2016") +plt.show() +!ec + + +=== Seeing the wood for the trees === + +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_! + + +!bc pycod + +#Decision Tree Regression +from sklearn.tree import DecisionTreeRegressor +regr_1=DecisionTreeRegressor(max_depth=5) +regr_2=DecisionTreeRegressor(max_depth=7) +regr_3=DecisionTreeRegressor(max_depth=9) +regr_1.fit(X, Energies) +regr_2.fit(X, Energies) +regr_3.fit(X, Energies) + + +y_1 = regr_1.predict(X) +y_2 = regr_2.predict(X) +y_3=regr_3.predict(X) +Masses['Eapprox'] = y_3 +# Plot the results +plt.figure() +plt.plot(A, Energies, color="blue", label="Data", linewidth=2) +plt.plot(A, y_1, color="red", label="max_depth=5", linewidth=2) +plt.plot(A, y_2, color="green", label="max_depth=7", linewidth=2) +plt.plot(A, y_3, color="m", label="max_depth=9", linewidth=2) + +plt.xlabel("$A$") +plt.ylabel("$E$[MeV]") +plt.title("Decision Tree Regression") +plt.legend() +save_fig("Masses2016Trees") +plt.show() +print(Masses) +print(np.mean( (Energies-y_1)**2)) +!ec + + +=== And what about using neural networks? === +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) +functionality. +!bc pycod +from sklearn.neural_network import MLPRegressor +from sklearn.metrics import accuracy_score +import seaborn as sns + +X_train = X +Y_train = Energies +n_hidden_neurons = 100 +epochs = 100 +# store models for later use +eta_vals = np.logspace(-5, 1, 7) +lmbd_vals = np.logspace(-5, 1, 7) +# store the models for later use +DNN_scikit = np.zeros((len(eta_vals), len(lmbd_vals)), dtype=object) +train_accuracy = np.zeros((len(eta_vals), len(lmbd_vals))) +sns.set() +for i, eta in enumerate(eta_vals): + for j, lmbd in enumerate(lmbd_vals): + dnn = MLPRegressor(hidden_layer_sizes=(n_hidden_neurons), activation='logistic', + alpha=lmbd, learning_rate_init=eta, max_iter=epochs) + dnn.fit(X_train, Y_train) + DNN_scikit[i][j] = dnn + train_accuracy[i][j] = dnn.score(X_train, Y_train) + +fig, ax = plt.subplots(figsize = (10, 10)) +sns.heatmap(train_accuracy, annot=True, ax=ax, cmap="viridis") +ax.set_title("Training Accuracy") +ax.set_ylabel("$\eta$") +ax.set_xlabel("$\lambda$") +plt.show() + + + +!ec + + + + + + +===== A first summary ===== + +The aim behind these introductory words was to present to you various +Python libraries and their functionalities, in particular libraries like +_numpy_, _pandas_, _xarray_ and _matplotlib_ and other that make our life much easier +in handling various data sets and visualizing data. + +Furthermore, +_Scikit-Learn_ allows us with few lines of code to implement popular +Machine Learning algorithms for supervised learning. Later we will meet _Tensorflow_, a powerful library for deep learning. +Now it is time to dive more into the details of various methods. We will start with linear regression and try to take a deeper look at what it entails. + + + + + + + + +======= Why Linear Regression (aka Ordinary Least Squares and family) ======= + +Fitting a continuous function with linear parameterization in terms of the parameters $\bm{\beta}$. +* Method of choice for fitting a continuous function! +* Gives an excellent introduction to central Machine Learning features with _understandable pedagogical_ links to other methods like _Neural Networks_, _Support Vector Machines_ etc +* Analytical expression for the fitting parameters $\bm{\beta}$ +* Analytical expressions for statistical propertiers like mean values, variances, confidence intervals and more +* Analytical relation with probabilistic interpretations +* Easy to introduce basic concepts like bias-variance tradeoff, cross-validation, resampling and regularization techniques and many other ML topics +* Easy to code! And links well with classification problems and logistic regression and neural networks +* Allows for _easy_ hands-on understanding of gradient descent methods +* and many more features + +For more discussions of Ridge and Lasso regression, "Wessel van Wieringen's":"https://arxiv.org/abs/1509.09169" article is highly recommended. +Similarly, "Mehta et al's article":"https://arxiv.org/abs/1803.08823" is also recommended. + + +=== Regression analysis, overarching aims === + +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 $\bm{x} =[x_0, x_1,\dots, x_{n-1}]^T$. +The first variable is called the _dependent_, the _outcome_ or the _response_ variable while the set of variables $\bm{x}$ is called the independent variable, or the predictor variable or the explanatory variable. + +A regression model aims at finding a likelihood function $p(\bm{y}\vert \bm{x})$, that is the conditional distribution for $\bm{y}$ with a given $\bm{x}$. The estimation of $p(\bm{y}\vert \bm{x})$ is made using a data set with +* $n$ cases $i = 0, 1, 2, \dots, n-1$ +* Response (target, dependent or outcome) variable $y_i$ with $i = 0, 1, 2, \dots, n-1$ +* $p$ so-called explanatory (independent or predictor) variables $\bm{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. + The goal of the regression analysis is to extract/exploit relationship between $\bm{y}$ and $\bm{X}$ in or to infer causal dependencies, approximations to the likelihood functions, functional relationships and to make predictions, making fits and many other things. + + +Consider an experiment in which $p$ characteristics of $n$ samples are +measured. The data from this experiment, for various explanatory variables $p$ are normally represented by a matrix +$\mathbf{X}$. + +The matrix $\mathbf{X}$ is called the *design +matrix*. Additional information of the samples is available in the +form of $\bm{y}$ (also as above). The variable $\bm{y}$ is +generally referred to as the *response variable*. The aim of +regression analysis is to explain $\bm{y}$ in terms of +$\bm{X}$ through a functional relationship like $y_i = +f(\mathbf{X}_{i,\ast})$. When no prior knowledge on the form of +$f(\cdot)$ is available, it is common to assume a linear relationship +between $\bm{X}$ and $\bm{y}$. This assumption gives rise to +the *linear regression model* where $\bm{\beta} = [\beta_0, \ldots, +\beta_{p-1}]^{T}$ are the *regression parameters*. + +Linear regression gives us a set of analytical equations for the parameters $\beta_j$. + + +=== Examples === + +In order to understand the relation among the predictors $p$, the set of data $n$ and the target (outcome, output etc) $\bm{y}$, +consider the model we discussed for describing nuclear binding energies. + +There we assumed that we could parametrize the data using a polynomial approximation based on the liquid drop model. +Assuming +!bt +\[ +BE(A) = a_0+a_1A+a_2A^{2/3}+a_3A^{-1/3}+a_4A^{-1}, +\] +!et +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. +This gives $p=0,1,2,3,4$. Furthermore we have $n$ entries for each predictor. It means that our design matrix is a +$p\times n$ matrix $\bm{X}$. + +Here the predictors are based on a model we have made. A popular data set which is widely encountered in ML applications is the +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$ + + +===== General linear models ===== + +Before we proceed let us study a case from linear algebra where we aim at fitting a set of data $\bm{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 $\bm{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. + +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 +!bt +\[ +y=y(x) \rightarrow y(x_i)=\tilde{y}_i+\epsilon_i=\sum_{j=0}^{n-1} \beta_j x_i^j+\epsilon_i, +\] +!et +where $\epsilon_i$ is the error in our approximation. + + +For every set of values $y_i,x_i$ we have thus the corresponding set of equations +!bt +\begin{align*} +y_0&=\beta_0+\beta_1x_0^1+\beta_2x_0^2+\dots+\beta_{n-1}x_0^{n-1}+\epsilon_0\\ +y_1&=\beta_0+\beta_1x_1^1+\beta_2x_1^2+\dots+\beta_{n-1}x_1^{n-1}+\epsilon_1\\ +y_2&=\beta_0+\beta_1x_2^1+\beta_2x_2^2+\dots+\beta_{n-1}x_2^{n-1}+\epsilon_2\\ +\dots & \dots \\ +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}.\\ +\end{align*} +!et + + +Defining the vectors +!bt +\[ +\bm{y} = [y_0,y_1, y_2,\dots, y_{n-1}]^T, +\] +!et +and +!bt +\[ +\bm{\beta} = [\beta_0,\beta_1, \beta_2,\dots, \beta_{n-1}]^T, +\] +!et +and +!bt +\[ +\bm{\epsilon} = [\epsilon_0,\epsilon_1, \epsilon_2,\dots, \epsilon_{n-1}]^T, +\] +!et +and the design matrix +!bt +\[ +\bm{X}= +\begin{bmatrix} +1& x_{0}^1 &x_{0}^2& \dots & \dots &x_{0}^{n-1}\\ +1& x_{1}^1 &x_{1}^2& \dots & \dots &x_{1}^{n-1}\\ +1& x_{2}^1 &x_{2}^2& \dots & \dots &x_{2}^{n-1}\\ +\dots& \dots &\dots& \dots & \dots &\dots\\ +1& x_{n-1}^1 &x_{n-1}^2& \dots & \dots &x_{n-1}^{n-1}\\ +\end{bmatrix} +\] +!et +we can rewrite our equations as +!bt +\[ +\bm{y} = \bm{X}\bm{\beta}+\bm{\epsilon}. +\] +!et +The above design matrix is called a "Vandermonde matrix":"https://en.wikipedia.org/wiki/Vandermonde_matrix". + + + + +===== Generalizing the fitting procedure as a linear algebra problem ===== + +We are obviously not limited to the above polynomial expansions. We +could replace the various powers of $x$ with elements of Fourier +series or instead of $x_i^j$ we could have $\cos{(j x_i)}$ or $\sin{(j +x_i)}$, or time series or other orthogonal functions. For every set +of values $y_i,x_i$ we can then generalize the equations to + +!bt +\begin{align*} +y_0&=\beta_0x_{00}+\beta_1x_{01}+\beta_2x_{02}+\dots+\beta_{n-1}x_{0n-1}+\epsilon_0\\ +y_1&=\beta_0x_{10}+\beta_1x_{11}+\beta_2x_{12}+\dots+\beta_{n-1}x_{1n-1}+\epsilon_1\\ +y_2&=\beta_0x_{20}+\beta_1x_{21}+\beta_2x_{22}+\dots+\beta_{n-1}x_{2n-1}+\epsilon_2\\ +\dots & \dots \\ +y_{i}&=\beta_0x_{i0}+\beta_1x_{i1}+\beta_2x_{i2}+\dots+\beta_{n-1}x_{in-1}+\epsilon_i\\ +\dots & \dots \\ +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}.\\ +\end{align*} +!et + +_Note that we have $p=n$ here. The matrix is symmetric. This is generally not the case!_ + +We redefine in turn the matrix $\bm{X}$ as +!bt +\[ +\bm{X}= +\begin{bmatrix} +x_{00}& x_{01} &x_{02}& \dots & \dots &x_{0,n-1}\\ +x_{10}& x_{11} &x_{12}& \dots & \dots &x_{1,n-1}\\ +x_{20}& x_{21} &x_{22}& \dots & \dots &x_{2,n-1}\\ +\dots& \dots &\dots& \dots & \dots &\dots\\ +x_{n-1,0}& x_{n-1,1} &x_{n-1,2}& \dots & \dots &x_{n-1,n-1}\\ +\end{bmatrix} +\] +!et +and without loss of generality we rewrite again our equations as +!bt +\[ +\bm{y} = \bm{X}\bm{\beta}+\bm{\epsilon}. +\] +!et +The left-hand side of this equation is kwown. Our error vector $\bm{\epsilon}$ and the parameter vector $\bm{\beta}$ are our unknow quantities. How can we obtain the optimal set of $\beta_i$ values? + +We have defined the matrix $\bm{X}$ via the equations +!bt +\begin{align*} +y_0&=\beta_0x_{00}+\beta_1x_{01}+\beta_2x_{02}+\dots+\beta_{n-1}x_{0n-1}+\epsilon_0\\ +y_1&=\beta_0x_{10}+\beta_1x_{11}+\beta_2x_{12}+\dots+\beta_{n-1}x_{1n-1}+\epsilon_1\\ +y_2&=\beta_0x_{20}+\beta_1x_{21}+\beta_2x_{22}+\dots+\beta_{n-1}x_{2n-1}+\epsilon_1\\ +\dots & \dots \\ +y_{i}&=\beta_0x_{i0}+\beta_1x_{i1}+\beta_2x_{i2}+\dots+\beta_{n-1}x_{in-1}+\epsilon_1\\ +\dots & \dots \\ +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}.\\ +\end{align*} +!et + +As we noted above, we stayed with a system with the design matrix + $\bm{X}\in {\mathbb{R}}^{n\times n}$, that is we have $p=n$. For reasons to come later (algorithmic arguments) we will hereafter define +our matrix as $\bm{X}\in {\mathbb{R}}^{n\times p}$, with the predictors refering to the column numbers and the entries $n$ being the row elements. + + +===== Our model for the nuclear binding energies ===== + +In our introductory notes we looked at the so-called "liguid drop model":"https://en.wikipedia.org/wiki/Semi-empirical_mass_formula". Let us remind ourselves about what we did by looking at the code. + +We restate the parts of the code we are most interested in. +!bc pycod +# Common imports +import numpy as np +import pandas as pd +import matplotlib.pyplot as plt +from IPython.display import display +import os + +# Where to save the figures and data files +PROJECT_ROOT_DIR = "Results" +FIGURE_ID = "Results/FigureFiles" +DATA_ID = "DataFiles/" + +if not os.path.exists(PROJECT_ROOT_DIR): + os.mkdir(PROJECT_ROOT_DIR) + +if not os.path.exists(FIGURE_ID): + os.makedirs(FIGURE_ID) + +if not os.path.exists(DATA_ID): + os.makedirs(DATA_ID) + +def image_path(fig_id): + return os.path.join(FIGURE_ID, fig_id) + +def data_path(dat_id): + return os.path.join(DATA_ID, dat_id) + +def save_fig(fig_id): + plt.savefig(image_path(fig_id) + ".png", format='png') + +infile = open(data_path("MassEval2016.dat"),'r') + + +# Read the experimental data with Pandas +Masses = pd.read_fwf(infile, usecols=(2,3,4,6,11), + names=('N', 'Z', 'A', 'Element', 'Ebinding'), + widths=(1,3,5,5,5,1,3,4,1,13,11,11,9,1,2,11,9,1,3,1,12,11,1), + header=39, + index_col=False) + +# Extrapolated values are indicated by '#' in place of the decimal place, so +# the Ebinding column won't be numeric. Coerce to float and drop these entries. +Masses['Ebinding'] = pd.to_numeric(Masses['Ebinding'], errors='coerce') +Masses = Masses.dropna() +# Convert from keV to MeV. +Masses['Ebinding'] /= 1000 + +# Group the DataFrame by nucleon number, A. +Masses = Masses.groupby('A') +# Find the rows of the grouped DataFrame with the maximum binding energy. +Masses = Masses.apply(lambda t: t[t.Ebinding==t.Ebinding.max()]) +A = Masses['A'] +Z = Masses['Z'] +N = Masses['N'] +Element = Masses['Element'] +Energies = Masses['Ebinding'] + +# Now we set up the design matrix X +X = np.zeros((len(A),5)) +X[:,0] = 1 +X[:,1] = A +X[:,2] = A**(2.0/3.0) +X[:,3] = A**(-1.0/3.0) +X[:,4] = A**(-1.0) +# Then nice printout using pandas +DesignMatrix = pd.DataFrame(X) +DesignMatrix.index = A +DesignMatrix.columns = ['1', 'A', 'A^(2/3)', 'A^(-1/3)', '1/A'] +display(DesignMatrix) +!ec + +With $\bm{\beta}\in {\mathbb{R}}^{p\times 1}$, it means that we will hereafter write our equations for the approximation as +!bt +\[ +\bm{\tilde{y}}= \bm{X}\bm{\beta}, +\] +!et +throughout these lectures. + + + +With the above we use the design matrix to define the approximation $\bm{\tilde{y}}$ via the unknown quantity $\bm{\beta}$ as +!bt +\[ +\bm{\tilde{y}}= \bm{X}\bm{\beta}, +\] +!et +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 +!bt +\[ +C(\bm{\beta})=\frac{1}{n}\sum_{i=0}^{n-1}\left(y_i-\tilde{y}_i\right)^2=\frac{1}{n}\left\{\left(\bm{y}-\bm{\tilde{y}}\right)^T\left(\bm{y}-\bm{\tilde{y}}\right)\right\}, +\] +!et +or using the matrix $\bm{X}$ and in a more compact matrix-vector notation as +!bt +\[ +C(\bm{\beta})=\frac{1}{n}\left\{\left(\bm{y}-\bm{X}^T\bm{\beta}\right)^T\left(\bm{y}-\bm{X}^T\bm{\beta}\right)\right\}. +\] +!et +This function is one possible way to define the so-called cost function. + + + +It is also common to define +the function $Q$ as + +!bt +\[ +C(\bm{\beta})=\frac{1}{2n}\sum_{i=0}^{n-1}\left(y_i-\tilde{y}_i\right)^2, +\] +!et +since when taking the first derivative with respect to the unknown parameters $\beta$, the factor of $2$ cancels out. +!eblock +translating doconce text in book.do.txt to ipynb +ERROR: 2 !bblock do not match 4 !eblock directives + + +Two !eblock after each other! + +!eblock + + +===== Numpy and arrays ===== +"Numpy":"http://www.numpy.org/" provides an easy way to handle arrays in Python. The standard way to import this library is as + +!bc pycod +import numpy as np +!ec +Here follows a simple example where we set up an array of ten elements, all determined by random numbers drawn according to the normal distribution, +!bc pycod +n = 10 +x = np.random.normal(size=n) +print(x) +!ec +We defined a vector $x$ with $n=10$ elements with its values given by the Normal distribution $N(0,1)$. +Another alternative is to declare a vector as follows +!bc pycod +import numpy as np +x = np.array([1, 2, 3]) +print(x) +!ec +Here we have defined a vector with three elements, with $x_0=1$, $x_1=2$ and $x_2=3$. Note that both Python and C++ +start numbering array elements from $0$ and on. This means that a vector with $n$ elements has a sequence of entities $x_0, x_1, x_2, \dots, x_{n-1}$. We could also let (recommended) Numpy to compute the logarithms of a specific array as +!bc pycod +import numpy as np +x = np.log(np.array([4, 7, 8])) +print(x) +!ec + +In the last example we used Numpy's unary function $np.log$. This function is +highly tuned to compute array elements since the code is vectorized +and does not require looping. We normaly recommend that you use the +Numpy intrinsic functions instead of the corresponding _log_ function +from Python's _math_ module. The looping is done explicitely by the +_np.log_ function. The alternative, and slower way to compute the +logarithms of a vector would be to write + +!bc pycod +import numpy as np +from math import log +x = np.array([4, 7, 8]) +for i in range(0, len(x)): + x[i] = log(x[i]) +print(x) +!ec +We note that our code is much longer already and we need to import the _log_ function from the _math_ module. +The attentive reader will also notice that the output is $[1, 1, 2]$. Python interprets automagically our numbers as integers (like the _automatic_ keyword in C++). To change this we could define our array elements to be double precision numbers as +!bc pycod +import numpy as np +x = np.log(np.array([4, 7, 8], dtype = np.float64)) +print(x) +!ec +or simply write them as double precision numbers (Python uses 64 bits as default for floating point type variables), that is +!bc pycod +import numpy as np +x = np.log(np.array([4.0, 7.0, 8.0]) +print(x) +!ec +To check the number of bytes (remember that one byte contains eight bits for double precision variables), you can use simple use the _itemsize_ functionality (the array $x$ is actually an object which inherits the functionalities defined in Numpy) as +!bc pycod +import numpy as np +x = np.log(np.array([4.0, 7.0, 8.0]) +print(x.itemsize) +!ec + + +===== Matrices in Python ===== + +Having defined vectors, we are now ready to try out matrices. We can +define a $3 \times 3 $ real matrix $\hat{A}$ as (recall that we user +lowercase letters for vectors and uppercase letters for matrices) + +!bc pycod +import numpy as np +A = np.log(np.array([ [4.0, 7.0, 8.0], [3.0, 10.0, 11.0], [4.0, 5.0, 7.0] ])) +print(A) +!ec +If we use the _shape_ function we would get $(3, 3)$ as output, that is verifying that our matrix is a $3\times 3$ matrix. We can slice the matrix and print for example the first column (Python organized matrix elements in a row-major order, see below) as +!bc pycod +import numpy as np +A = np.log(np.array([ [4.0, 7.0, 8.0], [3.0, 10.0, 11.0], [4.0, 5.0, 7.0] ])) +# print the first column, row-major order and elements start with 0 +print(A[:,0]) +!ec +We can continue this was by printing out other columns or rows. The example here prints out the second column +!bc pycod +import numpy as np +A = np.log(np.array([ [4.0, 7.0, 8.0], [3.0, 10.0, 11.0], [4.0, 5.0, 7.0] ])) +# print the first column, row-major order and elements start with 0 +print(A[1,:]) +!ec +Numpy contains many other functionalities that allow us to slice, subdivide etc etc arrays. We strongly recommend that you look up the "Numpy website for more details":"http://www.numpy.org/". Useful functions when defining a matrix are the _np.zeros_ function which declares a matrix of a given dimension and sets all elements to zero +!bc pycod +import numpy as np +n = 10 +# define a matrix of dimension 10 x 10 and set all elements to zero +A = np.zeros( (n, n) ) +print(A) +!ec +or initializing all elements to +!bc pycod +import numpy as np +n = 10 +# define a matrix of dimension 10 x 10 and set all elements to one +A = np.ones( (n, n) ) +print(A) +!ec +or as unitarily distributed random numbers (see the material on random number generators in the statistics part) +!bc pycod +import numpy as np +n = 10 +# define a matrix of dimension 10 x 10 and set all elements to random numbers with x \in [0, 1] +A = np.random.rand(n, n) +print(A) +!ec + +As we will see throughout these lectures, there are several extremely useful functionalities in Numpy. +As an example, consider the discussion of the covariance matrix. Suppose we have defined three vectors +$\hat{x}, \hat{y}, \hat{z}$ with $n$ elements each. The covariance matrix is defined as +!bt +\[ +\hat{\Sigma} = \begin{bmatrix} \sigma_{xx} & \sigma_{xy} & \sigma_{xz} \\ + \sigma_{yx} & \sigma_{yy} & \sigma_{yz} \\ + \sigma_{zx} & \sigma_{zy} & \sigma_{zz} + \end{bmatrix}, +\] +!et +where for example +!bt +\[ +\sigma_{xy} =\frac{1}{n} \sum_{i=0}^{n-1}(x_i- \overline{x})(y_i- \overline{y}). +\] +!et +The Numpy function _np.cov_ calculates the covariance elements using the factor $1/(n-1)$ instead of $1/n$ since it assumes we do not have the exact mean values. +The following simple function uses the _np.vstack_ function which takes each vector of dimension $1\times n$ and produces a $3\times n$ matrix $\hat{W}$ +!bt +\[ +\hat{W} = \begin{bmatrix} x_0 & y_0 & z_0 \\ + x_1 & y_1 & z_1 \\ + x_2 & y_2 & z_2 \\ + \dots & \dots & \dots \\ + x_{n-2} & y_{n-2} & z_{n-2} \\ + x_{n-1} & y_{n-1} & z_{n-1} + \end{bmatrix}, +\] +!et + +which in turn is converted into into the $3\times 3$ covariance matrix +$\hat{\Sigma}$ via the Numpy function _np.cov()_. We note that we can also calculate +the mean value of each set of samples $\hat{x}$ etc using the Numpy +function _np.mean(x)_. We can also extract the eigenvalues of the +covariance matrix through the _np.linalg.eig()_ function. + +!bc pycod +# Importing various packages +import numpy as np + +n = 100 +x = np.random.normal(size=n) +print(np.mean(x)) +y = 4+3*x+np.random.normal(size=n) +print(np.mean(y)) +z = x**3+np.random.normal(size=n) +print(np.mean(z)) +W = np.vstack((x, y, z)) +Sigma = np.cov(W) +print(Sigma) +Eigvals, Eigvecs = np.linalg.eig(Sigma) +print(Eigvals) +!ec + + +!bc pycod +import numpy as np +import matplotlib.pyplot as plt +from scipy import sparse +eye = np.eye(4) +print(eye) +sparse_mtx = sparse.csr_matrix(eye) +print(sparse_mtx) +x = np.linspace(-10,10,100) +y = np.sin(x) +plt.plot(x,y,marker='x') +plt.show() +!ec + + +===== Meet the Pandas ===== + + +FIGURE: [fig/pandas.jpg, width=600 frac=0.8] + +Another useful Python package is +"pandas":"https://pandas.pydata.org/", which is an open source library +providing high-performance, easy-to-use data structures and data +analysis tools for Python. _pandas_ stands for panel data, a term borrowed from econometrics and is an efficient library for data analysis with an emphasis on tabular data. +_pandas_ has two major classes, the _DataFrame_ class with two-dimensional data objects and tabular data organized in columns and the class _Series_ with a focus on one-dimensional data objects. Both classes allow you to index data easily as we will see in the examples below. +_pandas_ allows you also to perform mathematical operations on the data, spanning from simple reshapings of vectors and matrices to statistical operations. + +The following simple example shows how we can, in an easy way make tables of our data. Here we define a data set which includes names, place of birth and date of birth, and displays the data in an easy to read way. We will see repeated use of _pandas_, in particular in connection with classification of data. + +!bc pycod +import pandas as pd +from IPython.display import display +data = {'First Name': ["Frodo", "Bilbo", "Aragorn II", "Samwise"], + 'Last Name': ["Baggins", "Baggins","Elessar","Gamgee"], + 'Place of birth': ["Shire", "Shire", "Eriador", "Shire"], + 'Date of Birth T.A.': [2968, 2890, 2931, 2980] + } +data_pandas = pd.DataFrame(data) +display(data_pandas) +!ec + +In the above we have imported _pandas_ with the shorthand _pd_, the latter has become the standard way we import _pandas_. We make then a list of various variables +and reorganize the aboves lists into a _DataFrame_ and then print out a neat table with specific column labels as *Name*, *place of birth* and *date of birth*. +Displaying these results, we see that the indices are given by the default numbers from zero to three. +_pandas_ is extremely flexible and we can easily change the above indices by defining a new type of indexing as +!bc pycod +data_pandas = pd.DataFrame(data,index=['Frodo','Bilbo','Aragorn','Sam']) +display(data_pandas) +!ec +Thereafter we display the content of the row which begins with the index _Aragorn_ +!bc pycod +display(data_pandas.loc['Aragorn']) +!ec + +We can easily append data to this, for example +!bc pycod +new_hobbit = {'First Name': ["Peregrin"], + 'Last Name': ["Took"], + 'Place of birth': ["Shire"], + 'Date of Birth T.A.': [2990] + } +data_pandas=data_pandas.append(pd.DataFrame(new_hobbit, index=['Pippin'])) +display(data_pandas) +!ec + + +Here are other examples where we use the _DataFrame_ functionality to handle arrays, now with more interesting features for us, namely numbers. We set up a matrix +of dimensionality $10\times 5$ and compute the mean value and standard deviation of each column. Similarly, we can perform mathematial operations like squaring the matrix elements and many other operations. +!bc pycod +import numpy as np +import pandas as pd +from IPython.display import display +np.random.seed(100) +# setting up a 10 x 5 matrix +rows = 10 +cols = 5 +a = np.random.randn(rows,cols) +df = pd.DataFrame(a) +display(df) +print(df.mean()) +print(df.std()) +display(df**2) +!ec + +Thereafter we can select specific columns only and plot final results +!bc pycod +df.columns = ['First', 'Second', 'Third', 'Fourth', 'Fifth'] +df.index = np.arange(10) + +display(df) +print(df['Second'].mean() ) +print(df.info()) +print(df.describe()) + +from pylab import plt, mpl +plt.style.use('seaborn') +mpl.rcParams['font.family'] = 'serif' + +df.cumsum().plot(lw=2.0, figsize=(10,6)) +plt.show() + + +df.plot.bar(figsize=(10,6), rot=15) +plt.show() +!ec +We can produce a $4\times 4$ matrix +!bc pycod +b = np.arange(16).reshape((4,4)) +print(b) +df1 = pd.DataFrame(b) +print(df1) +!ec +and many other operations. + +The _Series_ class is another important class included in +_pandas_. You can view it as a specialization of _DataFrame_ but where +we have just a single column of data. It shares many of the same features as _DataFrame. As with _DataFrame_, +most operations are vectorized, achieving thereby a high performance when dealing with computations of arrays, in particular labeled arrays. +As we will see below it leads also to a very concice code close to the mathematical operations we may be interested in. +For multidimensional arrays, we recommend strongly "xarray":"http://xarray.pydata.org/en/stable/". _xarray_ has much of the same flexibility as _pandas_, but allows for the extension to higher dimensions than two. We will see examples later of the usage of both _pandas_ and _xarray_. + + + +===== Reading Data and fitting ===== + +In order to study various Machine Learning algorithms, we need to +access data. Acccessing data is an essential step in all machine +learning algorithms. In particular, setting up the so-called _design +matrix_ (to be defined below) is often the first element we need in +order to perform our calculations. To set up the design matrix means +reading (and later, when the calculations are done, writing) data +in various formats, The formats span from reading files from disk, +loading data from databases and interacting with online sources +like web application programming interfaces (APIs). + +In handling various input formats, as discussed above, we will mainly stay with _pandas_, +a Python package which allows us, in a seamless and painless way, to +deal with a multitude of formats, from standard _csv_ (comma separated +values) files, via _excel_, _html_ to _hdf5_ formats. With _pandas_ +and the _DataFrame_ and _Series_ functionalities we are able to convert text data +into the calculational formats we need for a specific algorithm. And our code is going to be +pretty close the basic mathematical expressions. + +Our first data set is going to be a classic from nuclear physics, namely all +available data on binding energies. Don't be intimidated if you are not familiar with nuclear physics. It serves simply as an example here of a data set. + +We will show some of the +strengths of packages like _Scikit-Learn_ in fitting nuclear binding energies to +specific functions using linear regression first. Then, as a teaser, we will show you how +you can easily implement other algorithms like decision trees and random forests and neural networks. + +But before we really start with nuclear physics data, let's just look at some simpler polynomial fitting cases, such as, +(don't be offended) fitting straight lines! + + +=== Simple linear regression model using _scikit-learn_ === + +We start with perhaps our simplest possible example, using _Scikit-Learn_ to perform linear regression analysis on a data set produced by us. + +What follows is a simple Python code where we have defined a function +$y$ in terms of the variable $x$. Both are defined as vectors with $100$ entries. +The numbers in the vector $\hat{x}$ are given +by random numbers generated with a uniform distribution with entries +$x_i \in [0,1]$ (more about probability distribution functions +later). These values are then used to define a function $y(x)$ +(tabulated again as a vector) with a linear dependence on $x$ plus a +random noise added via the normal distribution. + + +The Numpy functions are imported used the _import numpy as np_ +statement and the random number generator for the uniform distribution +is called using the function _np.random.rand()_, where we specificy +that we want $100$ random variables. Using Numpy we define +automatically an array with the specified number of elements, $100$ in +our case. With the Numpy function _randn()_ we can compute random +numbers with the normal distribution (mean value $\mu$ equal to zero and +variance $\sigma^2$ set to one) and produce the values of $y$ assuming a linear +dependence as function of $x$ + +!bt +\[ +y = 2x+N(0,1), +\] +!et + +where $N(0,1)$ represents random numbers generated by the normal +distribution. From _Scikit-Learn_ we import then the +_LinearRegression_ functionality and make a prediction $\tilde{y} = +\alpha + \beta x$ using the function _fit(x,y)_. We call the set of +data $(\hat{x},\hat{y})$ for our training data. The Python package +_scikit-learn_ has also a functionality which extracts the above +fitting parameters $\alpha$ and $\beta$ (see below). Later we will +distinguish between training data and test data. + +For plotting we use the Python package +"matplotlib":"https://matplotlib.org/" which produces publication +quality figures. Feel free to explore the extensive +"gallery":"https://matplotlib.org/gallery/index.html" of examples. In +this example we plot our original values of $x$ and $y$ as well as the +prediction _ypredict_ ($\tilde{y}$), which attempts at fitting our +data with a straight line. + +The Python code follows here. +!bc pycod +# Importing various packages +import numpy as np +import matplotlib.pyplot as plt +from sklearn.linear_model import LinearRegression + +x = np.random.rand(100,1) +y = 2*x+np.random.randn(100,1) +linreg = LinearRegression() +linreg.fit(x,y) +xnew = np.array([[0],[1]]) +ypredict = linreg.predict(xnew) + +plt.plot(xnew, ypredict, "r-") +plt.plot(x, y ,'ro') +plt.axis([0,1.0,0, 5.0]) +plt.xlabel(r'$x$') +plt.ylabel(r'$y$') +plt.title(r'Simple Linear Regression') +plt.show() +!ec + +This example serves several aims. It allows us to demonstrate several +aspects of data analysis and later machine learning algorithms. The +immediate visualization shows that our linear fit is not +impressive. It goes through the data points, but there are many +outliers which are not reproduced by our linear regression. We could +now play around with this small program and change for example the +factor in front of $x$ and the normal distribution. Try to change the +function $y$ to + +!bt +\[ +y = 10x+0.01 \times N(0,1), +\] +!et + +where $x$ is defined as before. Does the fit look better? Indeed, by +reducing the role of the noise given by the normal distribution we see immediately that +our linear prediction seemingly reproduces better the training +set. However, this testing 'by the eye' is obviouly not satisfactory in the +long run. Here we have only defined the training data and our model, and +have not discussed a more rigorous approach to the _cost_ function. + +We need more rigorous criteria in defining whether we have succeeded or +not in modeling our training data. You will be surprised to see that +many scientists seldomly venture beyond this 'by the eye' approach. A +standard approach for the *cost* function is the so-called $\chi^2$ +function (a variant of the mean-squared error (MSE)) + +!bt +\[ \chi^2 = \frac{1}{n} +\sum_{i=0}^{n-1}\frac{(y_i-\tilde{y}_i)^2}{\sigma_i^2}, +\] +!et + +where $\sigma_i^2$ is the variance (to be defined later) of the entry +$y_i$. We may not know the explicit value of $\sigma_i^2$, it serves +however the aim of scaling the equations and make the cost function +dimensionless. + +Minimizing the cost function is a central aspect of +our discussions to come. Finding its minima as function of the model +parameters ($\alpha$ and $\beta$ in our case) will be a recurring +theme in these series of lectures. Essentially all machine learning +algorithms we will discuss center around the minimization of the +chosen cost function. This depends in turn on our specific +model for describing the data, a typical situation in supervised +learning. Automatizing the search for the minima of the cost function is a +central ingredient in all algorithms. Typical methods which are +employed are various variants of _gradient_ methods. These will be +discussed in more detail later. Again, you'll be surprised to hear that +many practitioners minimize the above function ''by the eye', popularly dubbed as +'chi by the eye'. That is, change a parameter and see (visually and numerically) that +the $\chi^2$ function becomes smaller. + +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 +the relative error (why would we prefer the MSE instead of the relative error?) as + +!bt +\[ +\epsilon_{\mathrm{relative}}= \frac{\vert \hat{y} -\hat{\tilde{y}}\vert}{\vert \hat{y}\vert}. +\] +!et +We can modify easily the above Python code and plot the relative error instead +!bc pycod +import numpy as np +import matplotlib.pyplot as plt +from sklearn.linear_model import LinearRegression + +x = np.random.rand(100,1) +y = 5*x+0.01*np.random.randn(100,1) +linreg = LinearRegression() +linreg.fit(x,y) +ypredict = linreg.predict(x) + +plt.plot(x, np.abs(ypredict-y)/abs(y), "ro") +plt.axis([0,1.0,0.0, 0.5]) +plt.xlabel(r'$x$') +plt.ylabel(r'$\epsilon_{\mathrm{relative}}$') +plt.title(r'Relative error') +plt.show() +!ec + +Depending on the parameter in front of the normal distribution, we may +have a small or larger relative error. Try to play around with +different training data sets and study (graphically) the value of the +relative error. + +As mentioned above, _Scikit-Learn_ has an impressive functionality. +We can for example extract the values of $\alpha$ and $\beta$ and +their error estimates, or the variance and standard deviation and many +other properties from the statistical data analysis. + +Here we show an +example of the functionality of _Scikit-Learn_. +!bc pycod +import numpy as np +import matplotlib.pyplot as plt +from sklearn.linear_model import LinearRegression +from sklearn.metrics import mean_squared_error, r2_score, mean_squared_log_error, mean_absolute_error + +x = np.random.rand(100,1) +y = 2.0+ 5*x+0.5*np.random.randn(100,1) +linreg = LinearRegression() +linreg.fit(x,y) +ypredict = linreg.predict(x) +print('The intercept alpha: \n', linreg.intercept_) +print('Coefficient beta : \n', linreg.coef_) +# The mean squared error +print("Mean squared error: %.2f" % mean_squared_error(y, ypredict)) +# Explained variance score: 1 is perfect prediction +print('Variance score: %.2f' % r2_score(y, ypredict)) +# Mean squared log error +print('Mean squared log error: %.2f' % mean_squared_log_error(y, ypredict) ) +# Mean absolute error +print('Mean absolute error: %.2f' % mean_absolute_error(y, ypredict)) +plt.plot(x, ypredict, "r-") +plt.plot(x, y ,'ro') +plt.axis([0.0,1.0,1.5, 7.0]) +plt.xlabel(r'$x$') +plt.ylabel(r'$y$') +plt.title(r'Linear Regression fit ') +plt.show() + +!ec +The function _coef_ gives us the parameter $\beta$ of our fit while _intercept_ yields +$\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 +!bt +\[ MSE(\hat{y},\hat{\tilde{y}}) = \frac{1}{n} +\sum_{i=0}^{n-1}(y_i-\tilde{y}_i)^2, +\] +!et + +The smaller the value, the better the fit. Ideally we would like to +have an MSE equal zero. The attentive reader has probably recognized +this function as being similar to the $\chi^2$ function defined above. + +The _r2score_ function computes $R^2$, the coefficient of +determination. It provides a measure of how well future samples are +likely to be predicted by the model. Best possible score is 1.0 and it +can be negative (because the model can be arbitrarily worse). A +constant model that always predicts the expected value of $\hat{y}$, +disregarding the input features, would get a $R^2$ score of $0.0$. + +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 +!bt +\[ +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}, +\] +!et +where we have defined the mean value of $\hat{y}$ as +!bt +\[ +\bar{y} = \frac{1}{n} \sum_{i=0}^{n - 1} y_i. +\] +!et +Another quantity taht we will meet again in our discussions of regression analysis is + 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. +The MAE is defined as follows +!bt +\[ +\text{MAE}(\hat{y}, \hat{\tilde{y}}) = \frac{1}{n} \sum_{i=0}^{n-1} \left| y_i - \tilde{y}_i \right|. +\] +!et +Finally we present the +squared logarithmic (quadratic) error +!bt +\[ +\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, +\] +!et + +where $\log_e (x)$ stands for the natural logarithm of $x$. This error +estimate is best to use when targets having exponential growth, such +as population counts, average sales of a commodity over a span of +years etc. + +We will discuss in more +detail these and other functions in the various lectures. We conclude this part with another example. Instead of +a linear $x$-dependence we study now a cubic polynomial and use the polynomial regression analysis tools of scikit-learn. + +!bc pycod +import matplotlib.pyplot as plt +import numpy as np +import random +from sklearn.linear_model import Ridge +from sklearn.preprocessing import PolynomialFeatures +from sklearn.pipeline import make_pipeline +from sklearn.linear_model import LinearRegression + +x=np.linspace(0.02,0.98,200) +noise = np.asarray(random.sample((range(200)),200)) +y=x**3*noise +yn=x**3*100 +poly3 = PolynomialFeatures(degree=3) +X = poly3.fit_transform(x[:,np.newaxis]) +clf3 = LinearRegression() +clf3.fit(X,y) + +Xplot=poly3.fit_transform(x[:,np.newaxis]) +poly3_plot=plt.plot(x, clf3.predict(Xplot), label='Cubic Fit') +plt.plot(x,yn, color='red', label="True Cubic") +plt.scatter(x, y, label='Data', color='orange', s=15) +plt.legend() +plt.show() + +def error(a): + for i in y: + err=(y-yn)/yn + return abs(np.sum(err))/len(err) + +print (error(y)) +!ec + + + + +=== To our real data: nuclear binding energies. Brief reminder on masses and binding energies === + +Let us now dive into nuclear physics and remind ourselves briefly about some basic features about binding +energies. A basic quantity which can be measured for the ground +states of nuclei is the atomic mass $M(N, Z)$ of the neutral atom with +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). + +Atomic masses are usually tabulated in terms of the mass excess defined by +!bt +\[ +\Delta M(N, Z) = M(N, Z) - uA, +\] +!et +where $u$ is the Atomic Mass Unit +!bt +\[ +u = M(^{12}\mathrm{C})/12 = 931.4940954(57) \hspace{0.1cm} \mathrm{MeV}/c^2. +\] +!et +The nucleon masses are +!bt +\[ +m_p = 1.00727646693(9)u, +\] +!et +and +!bt +\[ +m_n = 939.56536(8)\hspace{0.1cm} \mathrm{MeV}/c^2 = 1.0086649156(6)u. +\] +!et + +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" +there are data on masses and decays of 3437 nuclei. + +The nuclear binding energy is defined as the energy required to break +up a given nucleus into its constituent parts of $N$ neutrons and $Z$ +protons. In terms of the atomic masses $M(N, Z)$ the binding energy is +defined by + + +!bt +\[ +BE(N, Z) = ZM_H c^2 + Nm_n c^2 - M(N, Z)c^2 , +\] +!et +where $M_H$ is the mass of the hydrogen atom and $m_n$ is the mass of the neutron. +In terms of the mass excess the binding energy is given by +!bt +\[ +BE(N, Z) = Z\Delta_H c^2 + N\Delta_n c^2 -\Delta(N, Z)c^2 , +\] +!et +where $\Delta_H c^2 = 7.2890$ MeV and $\Delta_n c^2 = 8.0713$ MeV. + + +A popular and physically intuitive model which can be used to parametrize +the experimental binding energies as function of $A$, is the so-called +_liquid drop model_. The ansatz is based on the following expression + +!bt +\[ +BE(N,Z) = a_1A-a_2A^{2/3}-a_3\frac{Z^2}{A^{1/3}}-a_4\frac{(N-Z)^2}{A}, +\] +!et + +where $A$ stands for the number of nucleons and the $a_i$s are parameters which are determined by a fit +to the experimental data. + + + + +To arrive at the above expression we have assumed that we can make the following assumptions: + + * 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. + + * 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. + + + * 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. + + * 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. + +We could also add a so-called pairing term, which is a correction term that +arises from the tendency of proton pairs and neutron pairs to +occur. An even number of particles is more stable than an odd number. + + +=== Organizing our data === + +Let us start with reading and organizing our data. +We start with the compilation of masses and binding energies from 2016. +After having downloaded this file to our own computer, we are now ready to read the file and start structuring our data. + + +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_. +!bc pycod +# Common imports +import numpy as np +import pandas as pd +import matplotlib.pyplot as plt +import sklearn.linear_model as skl +from sklearn.model_selection import train_test_split +from sklearn.metrics import mean_squared_error, r2_score, mean_absolute_error +import os + +# Where to save the figures and data files +PROJECT_ROOT_DIR = "Results" +FIGURE_ID = "Results/FigureFiles" +DATA_ID = "DataFiles/" + +if not os.path.exists(PROJECT_ROOT_DIR): + os.mkdir(PROJECT_ROOT_DIR) + +if not os.path.exists(FIGURE_ID): + os.makedirs(FIGURE_ID) + +if not os.path.exists(DATA_ID): + os.makedirs(DATA_ID) + +def image_path(fig_id): + return os.path.join(FIGURE_ID, fig_id) + +def data_path(dat_id): + return os.path.join(DATA_ID, dat_id) + +def save_fig(fig_id): + plt.savefig(image_path(fig_id) + ".png", format='png') + +infile = open(data_path("MassEval2016.dat"),'r') +!ec + + +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. +!bc pycod +from pylab import plt, mpl +plt.style.use('seaborn') +mpl.rcParams['font.family'] = 'serif' + +def MakePlot(x,y, styles, labels, axlabels): + plt.figure(figsize=(10,6)) + for i in range(len(x)): + plt.plot(x[i], y[i], styles[i], label = labels[i]) + plt.xlabel(axlabels[0]) + plt.ylabel(axlabels[1]) + plt.legend(loc=0) +!ec + +Our next step is to read the data on experimental binding energies and +reorganize them as functions of the mass number $A$, the number of +protons $Z$ and neutrons $N$ using _pandas_. Before we do this it is +always useful (unless you have a binary file or other types of compressed +data) to actually open the file and simply take a look at it! + + +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. +!bc pycod +""" +This is taken from the data file of the mass 2016 evaluation. +All files are 3436 lines long with 124 character per line. + Headers are 39 lines long. + col 1 : Fortran character control: 1 = page feed 0 = line feed + 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 + These formats are reflected in the pandas widths variable below, see the statement + widths=(1,3,5,5,5,1,3,4,1,13,11,11,9,1,2,11,9,1,3,1,12,11,1), + Pandas has also a variable header, with length 39 in this case. +""" +!ec + +The data we are interested in are in columns 2, 3, 4 and 11, giving us +the number of neutrons, protons, mass numbers and binding energies, +respectively. We add also for the sake of completeness the element name. The data are in fixed-width formatted lines and we will +covert them into the _pandas_ DataFrame structure. + +!bc pycod +# Read the experimental data with Pandas +Masses = pd.read_fwf(infile, usecols=(2,3,4,6,11), + names=('N', 'Z', 'A', 'Element', 'Ebinding'), + widths=(1,3,5,5,5,1,3,4,1,13,11,11,9,1,2,11,9,1,3,1,12,11,1), + header=39, + index_col=False) + +# Extrapolated values are indicated by '#' in place of the decimal place, so +# the Ebinding column won't be numeric. Coerce to float and drop these entries. +Masses['Ebinding'] = pd.to_numeric(Masses['Ebinding'], errors='coerce') +Masses = Masses.dropna() +# Convert from keV to MeV. +Masses['Ebinding'] /= 1000 + +# Group the DataFrame by nucleon number, A. +Masses = Masses.groupby('A') +# Find the rows of the grouped DataFrame with the maximum binding energy. +Masses = Masses.apply(lambda t: t[t.Ebinding==t.Ebinding.max()]) +!ec + +We have now read in the data, grouped them according to the variables we are interested in. +We see how easy it is to reorganize the data using _pandas_. If we +were to do these operations in C/C++ or Fortran, we would have had to +write various functions/subroutines which perform the above +reorganizations for us. Having reorganized the data, we can now start +to make some simple fits using both the functionalities in _numpy_ and +_Scikit-Learn_ afterwards. + +Now we define five variables which contain +the number of nucleons $A$, the number of protons $Z$ and the number of neutrons $N$, the element name and finally the energies themselves. +!bc pycod +A = Masses['A'] +Z = Masses['Z'] +N = Masses['N'] +Element = Masses['Element'] +Energies = Masses['Ebinding'] +print(Masses) +!ec +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 $\bm{X}$. +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. +!bc pycod +# Now we set up the design matrix X +X = np.zeros((len(A),5)) +X[:,0] = 1 +X[:,1] = A +X[:,2] = A**(2.0/3.0) +X[:,3] = A**(-1.0/3.0) +X[:,4] = A**(-1.0) +!ec +With _scikitlearn_ we are now ready to use linear regression and fit our data. +!bc pycod +clf = skl.LinearRegression().fit(X, Energies) +fity = clf.predict(X) +!ec +Pretty simple! +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. +!bc pycod +# The mean squared error +print("Mean squared error: %.2f" % mean_squared_error(Energies, fity)) +# Explained variance score: 1 is perfect prediction +print('Variance score: %.2f' % r2_score(Energies, fity)) +# Mean absolute error +print('Mean absolute error: %.2f' % mean_absolute_error(Energies, fity)) +print(clf.coef_, clf.intercept_) + +Masses['Eapprox'] = fity +# Generate a plot comparing the experimental with the fitted values values. +fig, ax = plt.subplots() +ax.set_xlabel(r'$A = N + Z$') +ax.set_ylabel(r'$E_\mathrm{bind}\,/\mathrm{MeV}$') +ax.plot(Masses['A'], Masses['Ebinding'], alpha=0.7, lw=2, + label='Ame2016') +ax.plot(Masses['A'], Masses['Eapprox'], alpha=0.7, lw=2, c='m', + label='Fit') +ax.legend() +save_fig("Masses2016") +plt.show() +!ec + + +=== Seeing the wood for the trees === + +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_! + + +!bc pycod + +#Decision Tree Regression +from sklearn.tree import DecisionTreeRegressor +regr_1=DecisionTreeRegressor(max_depth=5) +regr_2=DecisionTreeRegressor(max_depth=7) +regr_3=DecisionTreeRegressor(max_depth=9) +regr_1.fit(X, Energies) +regr_2.fit(X, Energies) +regr_3.fit(X, Energies) + + +y_1 = regr_1.predict(X) +y_2 = regr_2.predict(X) +y_3=regr_3.predict(X) +Masses['Eapprox'] = y_3 +# Plot the results +plt.figure() +plt.plot(A, Energies, color="blue", label="Data", linewidth=2) +plt.plot(A, y_1, color="red", label="max_depth=5", linewidth=2) +plt.plot(A, y_2, color="green", label="max_depth=7", linewidth=2) +plt.plot(A, y_3, color="m", label="max_depth=9", linewidth=2) + +plt.xlabel("$A$") +plt.ylabel("$E$[MeV]") +plt.title("Decision Tree Regression") +plt.legend() +save_fig("Masses2016Trees") +plt.show() +print(Masses) +print(np.mean( (Energies-y_1)**2)) +!ec + + +=== And what about using neural networks? === +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) +functionality. +!bc pycod +from sklearn.neural_network import MLPRegressor +from sklearn.metrics import accuracy_score +import seaborn as sns + +X_train = X +Y_train = Energies +n_hidden_neurons = 100 +epochs = 100 +# store models for later use +eta_vals = np.logspace(-5, 1, 7) +lmbd_vals = np.logspace(-5, 1, 7) +# store the models for later use +DNN_scikit = np.zeros((len(eta_vals), len(lmbd_vals)), dtype=object) +train_accuracy = np.zeros((len(eta_vals), len(lmbd_vals))) +sns.set() +for i, eta in enumerate(eta_vals): + for j, lmbd in enumerate(lmbd_vals): + dnn = MLPRegressor(hidden_layer_sizes=(n_hidden_neurons), activation='logistic', + alpha=lmbd, learning_rate_init=eta, max_iter=epochs) + dnn.fit(X_train, Y_train) + DNN_scikit[i][j] = dnn + train_accuracy[i][j] = dnn.score(X_train, Y_train) + +fig, ax = plt.subplots(figsize = (10, 10)) +sns.heatmap(train_accuracy, annot=True, ax=ax, cmap="viridis") +ax.set_title("Training Accuracy") +ax.set_ylabel("$\eta$") +ax.set_xlabel("$\lambda$") +plt.show() + + + +!ec + + + + + + +===== A first summary ===== + +The aim behind these introductory words was to present to you various +Python libraries and their functionalities, in particular libraries like +_numpy_, _pandas_, _xarray_ and _matplotlib_ and other that make our life much easier +in handling various data sets and visualizing data. + +Furthermore, +_Scikit-Learn_ allows us with few lines of code to implement popular +Machine Learning algorithms for supervised learning. Later we will meet _Tensorflow_, a powerful library for deep learning. +Now it is time to dive more into the details of various methods. We will start with linear regression and try to take a deeper look at what it entails. + + + + + + + + +======= Why Linear Regression (aka Ordinary Least Squares and family) ======= + +Fitting a continuous function with linear parameterization in terms of the parameters $\bm{\beta}$. +* Method of choice for fitting a continuous function! +* Gives an excellent introduction to central Machine Learning features with _understandable pedagogical_ links to other methods like _Neural Networks_, _Support Vector Machines_ etc +* Analytical expression for the fitting parameters $\bm{\beta}$ +* Analytical expressions for statistical propertiers like mean values, variances, confidence intervals and more +* Analytical relation with probabilistic interpretations +* Easy to introduce basic concepts like bias-variance tradeoff, cross-validation, resampling and regularization techniques and many other ML topics +* Easy to code! And links well with classification problems and logistic regression and neural networks +* Allows for _easy_ hands-on understanding of gradient descent methods +* and many more features + +For more discussions of Ridge and Lasso regression, "Wessel van Wieringen's":"https://arxiv.org/abs/1509.09169" article is highly recommended. +Similarly, "Mehta et al's article":"https://arxiv.org/abs/1803.08823" is also recommended. + + +=== Regression analysis, overarching aims === + +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 $\bm{x} =[x_0, x_1,\dots, x_{n-1}]^T$. +The first variable is called the _dependent_, the _outcome_ or the _response_ variable while the set of variables $\bm{x}$ is called the independent variable, or the predictor variable or the explanatory variable. + +A regression model aims at finding a likelihood function $p(\bm{y}\vert \bm{x})$, that is the conditional distribution for $\bm{y}$ with a given $\bm{x}$. The estimation of $p(\bm{y}\vert \bm{x})$ is made using a data set with +* $n$ cases $i = 0, 1, 2, \dots, n-1$ +* Response (target, dependent or outcome) variable $y_i$ with $i = 0, 1, 2, \dots, n-1$ +* $p$ so-called explanatory (independent or predictor) variables $\bm{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. + The goal of the regression analysis is to extract/exploit relationship between $\bm{y}$ and $\bm{X}$ in or to infer causal dependencies, approximations to the likelihood functions, functional relationships and to make predictions, making fits and many other things. + + +Consider an experiment in which $p$ characteristics of $n$ samples are +measured. The data from this experiment, for various explanatory variables $p$ are normally represented by a matrix +$\mathbf{X}$. + +The matrix $\mathbf{X}$ is called the *design +matrix*. Additional information of the samples is available in the +form of $\bm{y}$ (also as above). The variable $\bm{y}$ is +generally referred to as the *response variable*. The aim of +regression analysis is to explain $\bm{y}$ in terms of +$\bm{X}$ through a functional relationship like $y_i = +f(\mathbf{X}_{i,\ast})$. When no prior knowledge on the form of +$f(\cdot)$ is available, it is common to assume a linear relationship +between $\bm{X}$ and $\bm{y}$. This assumption gives rise to +the *linear regression model* where $\bm{\beta} = [\beta_0, \ldots, +\beta_{p-1}]^{T}$ are the *regression parameters*. + +Linear regression gives us a set of analytical equations for the parameters $\beta_j$. + + +=== Examples === + +In order to understand the relation among the predictors $p$, the set of data $n$ and the target (outcome, output etc) $\bm{y}$, +consider the model we discussed for describing nuclear binding energies. + +There we assumed that we could parametrize the data using a polynomial approximation based on the liquid drop model. +Assuming +!bt +\[ +BE(A) = a_0+a_1A+a_2A^{2/3}+a_3A^{-1/3}+a_4A^{-1}, +\] +!et +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. +This gives $p=0,1,2,3,4$. Furthermore we have $n$ entries for each predictor. It means that our design matrix is a +$p\times n$ matrix $\bm{X}$. + +Here the predictors are based on a model we have made. A popular data set which is widely encountered in ML applications is the +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$ + + +===== General linear models ===== + +Before we proceed let us study a case from linear algebra where we aim at fitting a set of data $\bm{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 $\bm{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. + +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 +!bt +\[ +y=y(x) \rightarrow y(x_i)=\tilde{y}_i+\epsilon_i=\sum_{j=0}^{n-1} \beta_j x_i^j+\epsilon_i, +\] +!et +where $\epsilon_i$ is the error in our approximation. + + +For every set of values $y_i,x_i$ we have thus the corresponding set of equations +!bt +\begin{align*} +y_0&=\beta_0+\beta_1x_0^1+\beta_2x_0^2+\dots+\beta_{n-1}x_0^{n-1}+\epsilon_0\\ +y_1&=\beta_0+\beta_1x_1^1+\beta_2x_1^2+\dots+\beta_{n-1}x_1^{n-1}+\epsilon_1\\ +y_2&=\beta_0+\beta_1x_2^1+\beta_2x_2^2+\dots+\beta_{n-1}x_2^{n-1}+\epsilon_2\\ +\dots & \dots \\ +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}.\\ +\end{align*} +!et + + +Defining the vectors +!bt +\[ +\bm{y} = [y_0,y_1, y_2,\dots, y_{n-1}]^T, +\] +!et +and +!bt +\[ +\bm{\beta} = [\beta_0,\beta_1, \beta_2,\dots, \beta_{n-1}]^T, +\] +!et +and +!bt +\[ +\bm{\epsilon} = [\epsilon_0,\epsilon_1, \epsilon_2,\dots, \epsilon_{n-1}]^T, +\] +!et +and the design matrix +!bt +\[ +\bm{X}= +\begin{bmatrix} +1& x_{0}^1 &x_{0}^2& \dots & \dots &x_{0}^{n-1}\\ +1& x_{1}^1 &x_{1}^2& \dots & \dots &x_{1}^{n-1}\\ +1& x_{2}^1 &x_{2}^2& \dots & \dots &x_{2}^{n-1}\\ +\dots& \dots &\dots& \dots & \dots &\dots\\ +1& x_{n-1}^1 &x_{n-1}^2& \dots & \dots &x_{n-1}^{n-1}\\ +\end{bmatrix} +\] +!et +we can rewrite our equations as +!bt +\[ +\bm{y} = \bm{X}\bm{\beta}+\bm{\epsilon}. +\] +!et +The above design matrix is called a "Vandermonde matrix":"https://en.wikipedia.org/wiki/Vandermonde_matrix". + + + + +===== Generalizing the fitting procedure as a linear algebra problem ===== + +We are obviously not limited to the above polynomial expansions. We +could replace the various powers of $x$ with elements of Fourier +series or instead of $x_i^j$ we could have $\cos{(j x_i)}$ or $\sin{(j +x_i)}$, or time series or other orthogonal functions. For every set +of values $y_i,x_i$ we can then generalize the equations to + +!bt +\begin{align*} +y_0&=\beta_0x_{00}+\beta_1x_{01}+\beta_2x_{02}+\dots+\beta_{n-1}x_{0n-1}+\epsilon_0\\ +y_1&=\beta_0x_{10}+\beta_1x_{11}+\beta_2x_{12}+\dots+\beta_{n-1}x_{1n-1}+\epsilon_1\\ +y_2&=\beta_0x_{20}+\beta_1x_{21}+\beta_2x_{22}+\dots+\beta_{n-1}x_{2n-1}+\epsilon_2\\ +\dots & \dots \\ +y_{i}&=\beta_0x_{i0}+\beta_1x_{i1}+\beta_2x_{i2}+\dots+\beta_{n-1}x_{in-1}+\epsilon_i\\ +\dots & \dots \\ +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}.\\ +\end{align*} +!et + +_Note that we have $p=n$ here. The matrix is symmetric. This is generally not the case!_ + +We redefine in turn the matrix $\bm{X}$ as +!bt +\[ +\bm{X}= +\begin{bmatrix} +x_{00}& x_{01} &x_{02}& \dots & \dots &x_{0,n-1}\\ +x_{10}& x_{11} &x_{12}& \dots & \dots &x_{1,n-1}\\ +x_{20}& x_{21} &x_{22}& \dots & \dots &x_{2,n-1}\\ +\dots& \dots &\dots& \dots & \dots &\dots\\ +x_{n-1,0}& x_{n-1,1} &x_{n-1,2}& \dots & \dots &x_{n-1,n-1}\\ +\end{bmatrix} +\] +!et +and without loss of generality we rewrite again our equations as +!bt +\[ +\bm{y} = \bm{X}\bm{\beta}+\bm{\epsilon}. +\] +!et +The left-hand side of this equation is kwown. Our error vector $\bm{\epsilon}$ and the parameter vector $\bm{\beta}$ are our unknow quantities. How can we obtain the optimal set of $\beta_i$ values? + +We have defined the matrix $\bm{X}$ via the equations +!bt +\begin{align*} +y_0&=\beta_0x_{00}+\beta_1x_{01}+\beta_2x_{02}+\dots+\beta_{n-1}x_{0n-1}+\epsilon_0\\ +y_1&=\beta_0x_{10}+\beta_1x_{11}+\beta_2x_{12}+\dots+\beta_{n-1}x_{1n-1}+\epsilon_1\\ +y_2&=\beta_0x_{20}+\beta_1x_{21}+\beta_2x_{22}+\dots+\beta_{n-1}x_{2n-1}+\epsilon_1\\ +\dots & \dots \\ +y_{i}&=\beta_0x_{i0}+\beta_1x_{i1}+\beta_2x_{i2}+\dots+\beta_{n-1}x_{in-1}+\epsilon_1\\ +\dots & \dots \\ +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}.\\ +\end{align*} +!et + +As we noted above, we stayed with a system with the design matrix + $\bm{X}\in {\mathbb{R}}^{n\times n}$, that is we have $p=n$. For reasons to come later (algorithmic arguments) we will hereafter define +our matrix as $\bm{X}\in {\mathbb{R}}^{n\times p}$, with the predictors refering to the column numbers and the entries $n$ being the row elements. + + +===== Our model for the nuclear binding energies ===== + +In our introductory notes we looked at the so-called "liguid drop model":"https://en.wikipedia.org/wiki/Semi-empirical_mass_formula". Let us remind ourselves about what we did by looking at the code. + +We restate the parts of the code we are most interested in. +!bc pycod +# Common imports +import numpy as np +import pandas as pd +import matplotlib.pyplot as plt +from IPython.display import display +import os + +# Where to save the figures and data files +PROJECT_ROOT_DIR = "Results" +FIGURE_ID = "Results/FigureFiles" +DATA_ID = "DataFiles/" + +if not os.path.exists(PROJECT_ROOT_DIR): + os.mkdir(PROJECT_ROOT_DIR) + +if not os.path.exists(FIGURE_ID): + os.makedirs(FIGURE_ID) + +if not os.path.exists(DATA_ID): + os.makedirs(DATA_ID) + +def image_path(fig_id): + return os.path.join(FIGURE_ID, fig_id) + +def data_path(dat_id): + return os.path.join(DATA_ID, dat_id) + +def save_fig(fig_id): + plt.savefig(image_path(fig_id) + ".png", format='png') + +infile = open(data_path("MassEval2016.dat"),'r') + + +# Read the experimental data with Pandas +Masses = pd.read_fwf(infile, usecols=(2,3,4,6,11), + names=('N', 'Z', 'A', 'Element', 'Ebinding'), + widths=(1,3,5,5,5,1,3,4,1,13,11,11,9,1,2,11,9,1,3,1,12,11,1), + header=39, + index_col=False) + +# Extrapolated values are indicated by '#' in place of the decimal place, so +# the Ebinding column won't be numeric. Coerce to float and drop these entries. +Masses['Ebinding'] = pd.to_numeric(Masses['Ebinding'], errors='coerce') +Masses = Masses.dropna() +# Convert from keV to MeV. +Masses['Ebinding'] /= 1000 + +# Group the DataFrame by nucleon number, A. +Masses = Masses.groupby('A') +# Find the rows of the grouped DataFrame with the maximum binding energy. +Masses = Masses.apply(lambda t: t[t.Ebinding==t.Ebinding.max()]) +A = Masses['A'] +Z = Masses['Z'] +N = Masses['N'] +Element = Masses['Element'] +Energies = Masses['Ebinding'] + +# Now we set up the design matrix X +X = np.zeros((len(A),5)) +X[:,0] = 1 +X[:,1] = A +X[:,2] = A**(2.0/3.0) +X[:,3] = A**(-1.0/3.0) +X[:,4] = A**(-1.0) +# Then nice printout using pandas +DesignMatrix = pd.DataFrame(X) +DesignMatrix.index = A +DesignMatrix.columns = ['1', 'A', 'A^(2/3)', 'A^(-1/3)', '1/A'] +display(DesignMatrix) +!ec + +With $\bm{\beta}\in {\mathbb{R}}^{p\times 1}$, it means that we will hereafter write our equations for the approximation as +!bt +\[ +\bm{\tilde{y}}= \bm{X}\bm{\beta}, +\] +!et +throughout these lectures. + + + +With the above we use the design matrix to define the approximation $\bm{\tilde{y}}$ via the unknown quantity $\bm{\beta}$ as +!bt +\[ +\bm{\tilde{y}}= \bm{X}\bm{\beta}, +\] +!et +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 +!bt +\[ +C(\bm{\beta})=\frac{1}{n}\sum_{i=0}^{n-1}\left(y_i-\tilde{y}_i\right)^2=\frac{1}{n}\left\{\left(\bm{y}-\bm{\tilde{y}}\right)^T\left(\bm{y}-\bm{\tilde{y}}\right)\right\}, +\] +!et +or using the matrix $\bm{X}$ and in a more compact matrix-vector notation as +!bt +\[ +C(\bm{\beta})=\frac{1}{n}\left\{\left(\bm{y}-\bm{X}^T\bm{\beta}\right)^T\left(\bm{y}-\bm{X}^T\bm{\beta}\right)\right\}. +\] +!et +This function is one possible way to define the so-called cost function. + + + +It is also common to define +the function $Q$ as + +!bt +\[ +C(\bm{\beta})=\frac{1}{2n}\sum_{i=0}^{n-1}\left(y_i-\tilde{y}_i\right)^2, +\] +!et +since when taking the first derivative with respect to the unknown parameters $\beta$, the factor of $2$ cancels out. +!eblock +translating doconce text in book.do.txt to ipynb +*** replacing \bm{...} by \boldsymbol{...} (\bm is not supported by MathJax) +*** error: figure file "fig/pandas.jpg" does not exist! +translating doconce text in book.do.txt to ipynb +*** replacing \bm{...} by \boldsymbol{...} (\bm is not supported by MathJax) +collected all required additional files in ipynb-book-src.tar.gz which must be distributed with the notebook +*** warning: latex envir \begin{bmatrix} does not work well in Markdown. + Stick to \[ ... \], equation, equation*, align, or align* + environments in math environments. + +*** warning: latex envir \begin{bmatrix} does not work well in Markdown. + Stick to \[ ... \], equation, equation*, align, or align* + environments in math environments. + +*** warning: latex envir \begin{bmatrix} does not work well in Markdown. + Stick to \[ ... \], equation, equation*, align, or align* + environments in math environments. + +*** warning: latex envir \begin{bmatrix} does not work well in Markdown. + Stick to \[ ... \], equation, equation*, align, or align* + environments in math environments. + +*** warning: latex envir \begin{bmatrix} does not work well in Markdown. + Stick to \[ ... \], equation, equation*, align, or align* + environments in math environments. + +*** warning: latex envir \begin{bmatrix} does not work well in Markdown. + Stick to \[ ... \], equation, equation*, align, or align* + environments in math environments. + +*** warning: latex envir \begin{bmatrix} does not work well in Markdown. + Stick to \[ ... \], equation, equation*, align, or align* + environments in math environments. + +*** warning: latex envir \begin{bmatrix} does not work well in Markdown. + Stick to \[ ... \], equation, equation*, align, or align* + environments in math environments. + +*** warning: latex envir \begin{eqnarray*} does not work well in Markdown. + Stick to \[ ... \], equation, equation*, align, or align* + environments in math environments. + +output in book.ipynb +*** error: file has a mako construction ${\bf \hat{J}' + but seemingly no definition in <%...%>' + (it is not a command-line given mako variable either). + However, if this is a variable in a Makefile or Bash script + run with --no_mako - and you cannot use mako and Makefile or Bash variables + in the same document! + +*** error: file has a mako construction ${\bm{J}' + but seemingly no definition in <%...%>' + (it is not a command-line given mako variable either). + However, if this is a variable in a Makefile or Bash script + run with --no_mako - and you cannot use mako and Makefile or Bash variables + in the same document! + +translating doconce text in book.do.txt to ipynb +*** replacing \bm{...} by \boldsymbol{...} (\bm is not supported by MathJax) +collected all required additional files in ipynb-book-src.tar.gz which must be distributed with the notebook +*** warning: latex envir \begin{bmatrix} does not work well in Markdown. + Stick to \[ ... \], equation, equation*, align, or align* + environments in math environments. + +*** warning: latex envir \begin{bmatrix} does not work well in Markdown. + Stick to \[ ... \], equation, equation*, align, or align* + environments in math environments. + +*** warning: latex envir \begin{bmatrix} does not work well in Markdown. + Stick to \[ ... \], equation, equation*, align, or align* + environments in math environments. + +*** warning: latex envir \begin{bmatrix} does not work well in Markdown. + Stick to \[ ... \], equation, equation*, align, or align* + environments in math environments. + +*** warning: latex envir \begin{bmatrix} does not work well in Markdown. + Stick to \[ ... \], equation, equation*, align, or align* + environments in math environments. + +*** warning: latex envir \begin{bmatrix} does not work well in Markdown. + Stick to \[ ... \], equation, equation*, align, or align* + environments in math environments. + +*** warning: latex envir \begin{bmatrix} does not work well in Markdown. + Stick to \[ ... \], equation, equation*, align, or align* + environments in math environments. + +*** warning: latex envir \begin{bmatrix} does not work well in Markdown. + Stick to \[ ... \], equation, equation*, align, or align* + environments in math environments. + +*** warning: latex envir \begin{eqnarray*} does not work well in Markdown. + Stick to \[ ... \], equation, equation*, align, or align* + environments in math environments. + +*** warning: latex envir \begin{bmatrix} does not work well in Markdown. + Stick to \[ ... \], equation, equation*, align, or align* + environments in math environments. + +*** warning: latex envir \begin{bmatrix} does not work well in Markdown. + Stick to \[ ... \], equation, equation*, align, or align* + environments in math environments. + +*** warning: latex envir \begin{bmatrix} does not work well in Markdown. + Stick to \[ ... \], equation, equation*, align, or align* + environments in math environments. + +*** warning: latex envir \begin{bmatrix} does not work well in Markdown. + Stick to \[ ... \], equation, equation*, align, or align* + environments in math environments. + +output in book.ipynb +translating doconce text in book.do.txt to ipynb +*** replacing \bm{...} by \boldsymbol{...} (\bm is not supported by MathJax) +collected all required additional files in ipynb-book-src.tar.gz which must be distributed with the notebook +*** warning: latex envir \begin{bmatrix} does not work well in Markdown. + Stick to \[ ... \], equation, equation*, align, or align* + environments in math environments. + +*** warning: latex envir \begin{bmatrix} does not work well in Markdown. + Stick to \[ ... \], equation, equation*, align, or align* + environments in math environments. + +*** warning: latex envir \begin{bmatrix} does not work well in Markdown. + Stick to \[ ... \], equation, equation*, align, or align* + environments in math environments. + +*** warning: latex envir \begin{bmatrix} does not work well in Markdown. + Stick to \[ ... \], equation, equation*, align, or align* + environments in math environments. + +*** warning: latex envir \begin{bmatrix} does not work well in Markdown. + Stick to \[ ... \], equation, equation*, align, or align* + environments in math environments. + +*** warning: latex envir \begin{bmatrix} does not work well in Markdown. + Stick to \[ ... \], equation, equation*, align, or align* + environments in math environments. + +*** warning: latex envir \begin{bmatrix} does not work well in Markdown. + Stick to \[ ... \], equation, equation*, align, or align* + environments in math environments. + +*** warning: latex envir \begin{bmatrix} does not work well in Markdown. + Stick to \[ ... \], equation, equation*, align, or align* + environments in math environments. + +*** warning: latex envir \begin{eqnarray*} does not work well in Markdown. + Stick to \[ ... \], equation, equation*, align, or align* + environments in math environments. + +*** warning: latex envir \begin{bmatrix} does not work well in Markdown. + Stick to \[ ... \], equation, equation*, align, or align* + environments in math environments. + +*** warning: latex envir \begin{bmatrix} does not work well in Markdown. + Stick to \[ ... \], equation, equation*, align, or align* + environments in math environments. + +*** warning: latex envir \begin{bmatrix} does not work well in Markdown. + Stick to \[ ... \], equation, equation*, align, or align* + environments in math environments. + +*** warning: latex envir \begin{bmatrix} does not work well in Markdown. + Stick to \[ ... \], equation, equation*, align, or align* + environments in math environments. + +*** warning: latex envir \begin{bmatrix} does not work well in Markdown. + Stick to \[ ... \], equation, equation*, align, or align* + environments in math environments. + +output in book.ipynb diff --git a/doc/LectureNotes/book.do.txt b/doc/LectureNotes/book.do.txt index b932f82fa..1b8928d45 100644 --- a/doc/LectureNotes/book.do.txt +++ b/doc/LectureNotes/book.do.txt @@ -5,9 +5,364 @@ DATE: today TOC: on - ======= Introduction ======= +During the last two decades there has been a swift and amazing +development of Machine Learning techniques and algorithms that impact +many areas in not only Science and Technology but also the Humanities, +Social Sciences, Medicine, Law, indeed, almost all possible +disciplines. The applications are incredibly many, from self-driving +cars to solving high-dimensional differential equations or complicated +quantum mechanical many-body problems. Machine Learning is perceived +by many as one of the main disruptive techniques nowadays. + +Statistics, Data science and Machine Learning form important +fields of research in modern science. They describe how to learn and +make predictions from data, as well as allowing us to extract +important correlations about physical process and the underlying laws +of motion in large data sets. The latter, big data sets, appear +frequently in essentially all disciplines, from the traditional +Science, Technology, Mathematics and Engineering fields to Life +Science, Law, education research, the Humanities and the Social +Sciences. + +It has become more +and more common to see research projects on big data in for example +the Social Sciences where extracting patterns from complicated survey +data is one of many research directions. Having a solid grasp of data +analysis and machine learning is thus becoming central to scientific +computing in many fields, and competences and skills within the fields +of machine learning and scientific computing are nowadays strongly +requested by many potential employers. The latter cannot be +overstated, familiarity with machine learning has almost become a +prerequisite for many of the most exciting employment opportunities, +whether they are in bioinformatics, life science, physics or finance, +in the private or the public sector. This author has had several +students or met students who have been hired recently based on their +skills and competences in scientific computing and data science, often +with marginal knowledge of machine learning. + +Machine learning is a subfield of computer science, and is closely +related to computational statistics. It evolved from the study of +pattern recognition in artificial intelligence (AI) research, and has +made contributions to AI tasks like computer vision, natural language +processing and speech recognition. Many of the methods we will study are also +strongly rooted in basic mathematics and physics research. + +Ideally, machine learning represents the science of giving computers +the ability to learn without being explicitly programmed. The idea is +that there exist generic algorithms which can be used to find patterns +in a broad class of data sets without having to write code +specifically for each problem. The algorithm will build its own logic +based on the data. You should however always keep in mind that +machines and algorithms are to a large extent developed by humans. The +insights and knowledge we have about a specific system, play a central +role when we develop a specific machine learning algorithm. + +Machine learning is an extremely rich field, in spite of its young +age. The increases we have seen during the last three decades in +computational capabilities have been followed by developments of +methods and techniques for analyzing and handling large date sets, +relying heavily on statistics, computer science and mathematics. The +field is rather new and developing rapidly. Popular software packages +written in Python for machine learning like +"Scikit-learn":"http://scikit-learn.org/stable/", +"Tensorflow":"https://www.tensorflow.org/", +"PyTorch":"http://pytorch.org/" and "Keras":"https://keras.io/", all +freely available at their respective GitHub sites, encompass +communities of developers in the thousands or more. And the number of +code developers and contributors keeps increasing. Not all the +algorithms and methods can be given a rigorous mathematical +justification, opening up thereby large rooms for experimenting and +trial and error and thereby exciting new developments. However, a +solid command of linear algebra, multivariate theory, probability +theory, statistical data analysis, understanding errors and Monte +Carlo methods are central elements in a proper understanding of many +of algorithms and methods we will discuss. + + + +===== Learning outcomes ===== + +These sets of lectures aim at giving you an overview of central aspects of +statistical data analysis as well as some of the central algorithms +used in machine learning. We will introduce a variety of central +algorithms and methods essential for studies of data analysis and +machine learning. + +Hands-on projects and experimenting with data and algorithms plays a central role in +these lectures, and our hope is, through the various +projects and exercises, to expose you to fundamental +research problems in these fields, with the aim to reproduce state of +the art scientific results. You will learn to develop and +structure codes for studying these systems, get acquainted with +computing facilities and learn to handle large scientific projects. A +good scientific and ethical conduct is emphasized throughout the +course. More specifically, you will + +o Learn about basic data analysis, Bayesian statistics, Monte Carlo methods, data optimization and machine learning; +o Be capable of extending the acquired knowledge to other systems and cases; +o Have an understanding of central algorithms used in data analysis and machine learning; +o Gain knowledge of central aspects of Monte Carlo methods, Markov chains, Gibbs samplers and their possible applications, from numerical integration to simulation of stock markets; +o Understand methods for regression and classification; +o Learn about neural network, genetic algorithms and Boltzmann machines; +o Work on numerical projects to illustrate the theory. The projects play a central role and you are expected to know modern programming languages like Python or C++, in addition to a basic knowledge of linear algebra (typically taught during the first one or two years of undergraduate studies). + +There are several topics we will cover here, spanning from +statistical data analysis and its basic concepts such as expectation +values, variance, covariance, correlation functions and errors, via +well-known probability distribution functions like the uniform +distribution, the binomial distribution, the Poisson distribution and +simple and multivariate normal distributions to central elements of +Bayesian statistics and modeling. We will also remind the reader about +central elements from linear algebra and standard methods based on +linear algebra used to optimize (minimize) functions (the family of gradient descent methods) +and the Singular-value decomposition and +least square methods for parameterizing data. + +We will also cover Monte Carlo methods, Markov chains, well-known +algorithms for sampling stochastic events like the Metropolis-Hastings +and Gibbs sampling methods. An important aspect of all our +calculations is a proper estimation of errors. Here we will also +discuss famous resampling techniques like the blocking, the bootstrapping +and the jackknife methods and the infamous bias-variance tradeoff. + +The second part of the material covers several algorithms used in +machine learning. + + + + + + +===== Types of Machine Learning ===== + + +The approaches to machine learning are many, but are often split into +two main categories. In *supervised learning* we know the answer to a +problem, and let the computer deduce the logic behind it. On the other +hand, *unsupervised learning* is a method for finding patterns and +relationship in data sets without any prior knowledge of the system. +Some authours also operate with a third category, namely +*reinforcement learning*. This is a paradigm of learning inspired by +behavioral psychology, where learning is achieved by trial-and-error, +solely from rewards and punishment. + +Another way to categorize machine learning tasks is to consider the +desired output of a system. Some of the most common tasks are: + + * 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. + + * 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. + + * Clustering: Data are divided into groups with certain common traits, without knowing the different groups beforehand. It is thus a form of unsupervised learning. + + +The methods we cover have three main topics in common, irrespective of +whether we deal with supervised or unsupervised learning. The first +ingredient is normally our data set (which can be subdivided into +training and test data), 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. + +The last ingredient is a so-called _cost_ +function which allows us to present an estimate on how good our model +is in reproducing the data it is supposed to train. + +Here we will build our machine learning approach on elements of the +statistical foundation discussed above, with elements from data +analysis, stochastic processes etc. We will discuss the following +machine learning algorithms + +o Linear regression and its variants +o Decision tree algorithms, from single trees to random forests +o Bayesian statistics and regression +o Support vector machines and finally various variants of +o Artifical neural networks and deep learning, including convolutional neural networks and Bayesian neural networks +o Networks for unsupervised learning using for example reduced Boltzmann machines. + + + +===== Choice of programming language ===== + +Python plays nowadays a central role in the development of machine +learning techniques and tools for data analysis. In particular, seen +the wealth of machine learning and data analysis libraries written in +Python, easy to use libraries with immediate visualization(and not the +least impressive galleries of existing examples), the popularity of the +Jupyter notebook framework with the possibility to run _R_ codes or +compiled programs written in C++, and much more made our choice of +programming language for this series of lectures easy. However, +since the focus here is not only on using existing Python libraries such +as _Scikit-Learn_ or _Tensorflow_, but also on developing your own +algorithms and codes, we will as far as possible present many of these +algorithms either as a Python codes or C++ or Fortran (or other languages) codes. + +The reason we also focus on compiled languages like C++ (or +Fortran), is that Python is still notoriously slow when we do not +utilize highly streamlined computational libraries like +"Lapack":"http://www.netlib.org/lapack/" or other numerical libraries +written in compiled languages (many of these libraries are written in +Fortran). Although a project like "Numba":"https://numba.pydata.org/" +holds great promise for speeding up the unrolling of lengthy loops, C++ +and Fortran are presently still the performance winners. Numba gives +you potentially the power to speed up your applications with high +performance functions written directly in Python. In particular, +array-oriented and math-heavy Python code can achieve similar +performance to C, C++ and Fortran. However, even with these speed-ups, +for codes involving heavy Markov Chain Monte Carlo analyses and +optimizations of cost functions, C++/C or Fortran codes tend to +outperform Python codes. + +Presently thus, the community tends to let +code written in C++/C or Fortran do the heavy duty numerical +number crunching and leave the post-analysis of the data to the above +mentioned Python modules or software packages. However, with the developments taking place in for example the Python community, and seen +the changes during the last decade, the above situation may change swiftly in the not too distant future. + +Many of the examples we discuss in this series of lectures come with +existing data files or provide code examples which produce the data to +be analyzed. Most of the applications we will discuss deal with +small data sets (less than a terabyte of information) and can easily +be analyzed and tested on standard off the shelf laptops you find in general +stores. + +===== Data handling, machine learning and ethical aspects ===== + +In most of the cases we will study, we will either generate the data +to analyze ourselves (both for supervised learning and unsupervised +learning) or we will recur again and again to data present in say +_Scikit-Learn_ or _Tensorflow_. Many of the examples we end up +dealing with are from a privacy and data protection point of view, +rather inoccuous and boring results of numerical +calculations. However, this does not hinder us from developing a sound +ethical attitude to the data we use, how we analyze the data and how +we handle the data. + +The most immediate and simplest possible ethical aspects deal with our +approach to the scientific process. Nowadays, with version control +software like "Git":"https://git-scm.com/" and various online +repositories like "Github":"https://github.com/", +"Gitlab":"https://about.gitlab.com/" etc, we can easily make our codes +and data sets we have used, freely and easily accessible to a wider +community. This helps us almost automagically in making our science +reproducible. The large open-source development communities involved +in say "Scikit-Learn":"http://scikit-learn.org/stable/", +"Tensorflow":"https://www.tensorflow.org/", +"PyTorch":"http://pytorch.org/" and "Keras":"https://keras.io/", are +all excellent examples of this. The codes can be tested and improved +upon continuosly, helping thereby our scientific community at large in +developing data analysis and machine learning tools. It is much +easier today to gain traction and acceptance for making your science +reproducible. From a societal stand, this is an important element +since many of the developers are employees of large public institutions like +universities and research labs. Our fellow taxpayers do deserve to get +something back for their bucks. + +However, this more mechanical aspect of the ethics of science (in +particular the reproducibility of scientific results) is something +which is obvious and everybody should do so as part of the dialectics of +science. The fact that many scientists are not willing to share their codes or +data is detrimental to the scientific discourse. + +Before we proceed, we should add a disclaimer. Even though +we may dream of computers developing some kind of higher learning +capabilities, at the end (even if the artificial intelligence +community keeps touting our ears full of fancy futuristic avenues), it is we, yes you reading these lines, +who end up constructing and instructing, via various algorithms, the +machine learning approaches. Self-driving cars for example, rely on sofisticated +programs which take into account all possible situations a car can +encounter. In addition, extensive usage of training data from GPS +information, maps etc, are typically fed into the software for +self-driving cars. Adding to this various sensors and cameras that +feed information to the programs, there are zillions of ethical issues +which arise from this. + +For self-driving cars, where basically many of the standard machine +learning algorithms discussed here enter into the codes, at a certain +stage we have to make choices. Yes, we , the lads and lasses who wrote +a program for a specific brand of a self-driving car. As an example, +all carmakers have as their utmost priority the security of the +driver and the accompanying passengers. A famous European carmaker, which is +one of the leaders in the market of self-driving cars, had _if_ +statements of the following type: suppose there are two obstacles in +front of you and you cannot avoid to collide with one of them. One of +the obstacles is a monstertruck while the other one is a kindergarten +class trying to cross the road. The self-driving car algo would then +opt for the hitting the small folks instead of the monstertruck, since +the likelihood of surving a collision with our future citizens, is +much higher. + +This leads to serious ethical aspects. Why should we +opt for such an option? Who decides and who is entitled to make such +choices? Keep in mind that many of the algorithms you will encounter in +this series of lectures or hear about later, are indeed based on +simple programming instructions. And you are very likely to be one of +the people who may end up writing such a code. Thus, developing a +sound ethical attitude to what we do, an approach well beyond the +simple mechanistic one of making our science available and +reproducible, is much needed. The example of the self-driving cars is +just one of infinitely many cases where we have to make choices. When +you analyze data on economic inequalities, who guarantees that you are +not weighting some data in a particular way, perhaps because you dearly want a +specific conclusion which may support your political views? + +We do not have the answers here, nor will we venture into a deeper +discussions of these aspects, but we want you think over these topics +in a more overarching way. A statistical data analysis with its dry +numbers and graphs meant to guide the eye, does not necessarily +reflect the truth, whatever that is. As a scientist, and after a +university education, you are supposedly a better citizen, with an +improved critical view and understanding of the scientific method, and +perhaps some deeper understanding of the ethics of science at +large. Use these insights. Be a critical citizen. You owe it to our +society. + + + + +======= Getting started with Machine Learning ======= + +Our emphasis throughout this series of lectures +is on understanding the mathematical aspects of +different algorithms used in the fields of data analysis and machine learning. + +However, where possible we will emphasize the +importance of using available software. We start thus with a hands-on +and top-down approach to machine learning. The aim is thus to start with +relevant data or data we have produced +and use these to introduce statistical data analysis +concepts and machine learning algorithms before we delve into the +algorithms themselves. The examples we will use in the beginning, start with simple +polynomials with random noise added. We will use the Python +software package "Scikit-Learn":"http://scikit-learn.org/stable/" and +introduce various machine learning algorithms to make fits of +the data and predictions. We move thereafter to more interesting +cases such as data from say experiments (below we will look at experimental nuclear binding energies as an example). +These are examples where we can easily set up the data and +then use machine learning algorithms included in for example +_Scikit-Learn_. + +These examples will serve us the purpose of getting +started. Furthermore, they allow us to catch more than two birds with +a stone. They will allow us to bring in some programming specific +topics and tools as well as showing the power of various Python +libraries for machine learning and statistical data analysis. + +Here, we will mainly focus on two +specific Python packages for Machine Learning, Scikit-Learn and +Tensorflow (see below for links etc). Moreover, the examples we +introduce will serve as inputs to many of our discussions later, as +well as allowing you to set up models and produce your own data and +get started with programming. + + + +===== What is Machine Learning? ===== + Statistics, data science and machine learning form important fields of research in modern science. They describe how to learn and make predictions from data, as well as allowing us to extract important @@ -73,59 +428,6 @@ of algorithms and methods we will discuss. -===== Learning outcomes ===== - -These setsof lectures aim at giving you an overview of central aspects of -statistical data analysis as well as some of the central algorithms -used in machine learning. We will introduce a variety of central -algorithms and methods essential for studies of data analysis and -machine learning. - -Hands-on projects and experimenting with data and algorithms plays a central role in -these lectures, and our hope is, through the various -projects and exercies, to expose you to fundamental -research problems in these fields, with the aim to reproduce state of -the art scientific results. You will learn to develop and -structure large codes for studying these systems, get acquainted with -computing facilities and learn to handle large scientific projects. A -good scientific and ethical conduct is emphasized throughout the -course. More specifically, you will - -o learn about basic data analysis, Bayesian statistics, Monte Carlo methods, data optimization and machine learning; -o be capable of extending the acquired knowledge to other systems and cases; -o Have an understanding of central algorithms used in data analysis and machine learning; -o Gain knowledge of central aspects of Monte Carlo methods, Markov chains, Gibbs samplers and their possible applications, from numerical integration to simulation of stock markets; -o Understand methods for regression and classification; -o Learn about neural network, genetic algorithms and Boltzmann machines; -o Work on numerical projects to illustrate the theory. The projects play a central role and you are expected to know modern programming languages like Python or C++, in addition to a basic knowledge of linear algebra (typically taught during the first one or two years of undergraduate studies). - -There are several topics we will cover here, spanning from a -statistical data analysis and its basic concepts such expectation -values, variance, covariance, correlation functions and errors, via -well-known probability distribution functions like uniform -distribution, the binomial distribution, the Poisson distribution and -simple and multivariate normal distributions to central elements of -Bayesian statistics and modeling. We will also remind the reader about -central elements from linear algebra and standard methods based on -linear algebra used to fit functions such Cubic splines and gradient -methods for data optimization and the Singular-value decomposition and -least square methods for parameterizing data. - -We will also cover Monte Carlo methods, Markov chains, well-known -algorithms for sampling stochastic events like the Metropolis-Hastings -and Gibbs sampling methods. An important aspect of all our -calculations is a proper estimation of errors. Here we will also -discuss famous resampling techniques like the blocking, bootstrapping -and jackknife methods. - -The second part of the material covers several algorithms used in -machine learning. - - - - - - ===== Types of Machine Learning ===== @@ -158,202 +460,10 @@ function of some parameters. The model reflects our knowledge of the system (or The last ingredient is a so-called _cost_ function which allows us to present an estimate on how good our model is in reproducing the data it is supposed to train. - -Here we will build our machine learning approach on elements of the -statistical foundation discussed above, with elements from data -analysis, stochastic processes etc. We will discuss the following -machine learning algorithms - -o Linear regression and its variants, in essence polynomial regression -o Decision tree algorithms, from simpler to more complex ones -o Nearest neighbors models -o Bayesian statistics and regression -o Support vector machines and finally various variants of -o Artifical neural networks and deep learning -o Networks for unsupervised learning using for example reduced Boltzmann machines. +At the heart of basically all ML algorithms there are so-called minimization algorithms, often we end up with various variants of _gradient_ methods. -===== Choice of programming language ===== - -Python plays nowadays a central role in the development of machine -learning techniques and tools for data analysis. In particular, seen -the wealth of machine learning and data analysis packages written in -Python, easy to use libraries with immediate visualization(and not the -least impressive galleries of existing example), the popularity of the -Jupyter notebook framework with the possibility to run _R_ codes or -compiled programs written in C++, and much more made our choice of -programming language for this series of lectures of easy. However, -since the focus here is not only on using existing Python tools such -as _scikit-learn_ or _tensorflow_, but also on developing your own -algorithms and codes, we will as far as possible present many of these -algorithms eithers a Python codes or C++ codes. Finally, we will, as -far as possible keep parallel versions of the data analysis and -machine larning programming aspects in _R_ as -well. "R":"https://www.r-project.org/" is a language and environment -for statistical computing and graphics which is widely used in -statistics and mathematics applications. - -The reason we also focus on compiled languages like C++ (or -Fortran), is that Python is still notoriously slow when we do not -utilize highly streamlined computational libraries like -"Lapack":"http://www.netlib.org/lapack/" or other numerical libraries -written in compiled languages (many of these libraries are written in -Fortran). Although a project like "Numba":"https://numba.pydata.org/" -holds great promise for speeding up the unrolling of lengthy loops, C+ -and Fortran are presently still the performance winners. Numba gives -you potentially the power to speed up your applications with high -performance functions written directly in Python. In particular, -array-oriented and math-heavy Python code can achieve similar -performance to C, C++ and Fortran. However, even with these speed-ups, -for codes involving heavy Markov Chain Monte Carlo analyses and -optimizations of cost functions, C++/C or Fortran codes tend to -outperform Python codes. - -Presently thus, the community tends to let -code written in C++/C or Fortran do the heavy duty numerical -number crunching and leave the post-analysis of the data to the above -mentioned Python modules or software packages. However, with the developments taking place in for example the Python community, and seen -the changes during the last decade, the above situation may change swiftly in the not too distant future. - -Many of the examples we discuss in this series of lectures come with -existing data files or provide code examples which produce the data to -be analyzed. Most of the applications we will discuss deal with -small data sets (less than a terabyte of information) and can easily -be analyzed and tested on standard off the shelf laptops you find in general -grocery stores. - -===== Data handling, machine learning and ethical aspects ===== - -In most of the cases we will study, we will either generate the data -to analyze ourselves (both for supervised learning and unsupervised -learning) or we will recur again and again to data present in say -_scikit-learn_ or _tensorflow_. Many of the examples we end up -dealing with are from a privacy and data protection point of view, -rather inoccuous and boring results of numerical -calculations. However, this does not hinder us from developing a sound -ethical attitude to the data we use, how we analyze the data and how -we handle the data. - -The most immediate and simplest possible ethical aspects deal with our -approach to the scientific process. Nowadays, with version control -software like "Git":"https://git-scm.com/" and various online -repositories like "Github":"https://github.com/", -"Gitlab":"https://about.gitlab.com/" etc, we can easily make our codes -and data sets we have used, freely and easily accessible to a wider -community. This helps us almost automagically in making our science -reproducible. The large open-source development communities involved -in say "Scikit-learn":"http://scikit-learn.org/stable/", -"Tensorflow":"https://www.tensorflow.org/", -"PyTorch":"http://pytorch.org/" and "Keras":"https://keras.io/", are -all excellent examples of this. The codes can be tested and improved -upon continuosly, helping thereby our scientific community at large in -developing data analysis and machine learning tools. It is much -easier today to gain traction and acceptance for making your science -reproducible. From a societal stand, this is an important element -since many of the developers are employees of large public institutions like -universities and research labs. Our taxpayer do deserve to get -something back for their bucks. - -However, this more mechanical aspect of the ethics of science (in -particular the reproducibility of scientific results) is something -which is obvious and everybody should do as part of the dialectics of -science. The fact that many scientists are not willing to share their codes or -data is detrimental to the scientific discourse. - -Before we proceed, we should add a disclaimer. Even though -we may dream of computers developing some kind of higher learning -capabilities, at the end (even if the artificial intelligence -community keeps touting our ears full of fancy futuristic avenues), it is we -who end up constructing and instructing, via various algorithms, the -computers. Self-driving cars for example, rely on sofisticated -programs which take into account all possible situations a car can -encounter. In addition, extensive usage of training datas from GPS -information, maps etc, are typically fed into the software for -self-driving cars. Adding to this various sensors and cameras that -feed information to the programs, there are zillions of ethical issues -which arise from this. - -For self-driving cars, where basically many of the standard machine -learning algorithms discussed here enter into the codes, at a certain -stage we have to make choices. Yes, we , the lads and lasses who wrote -a program for a specific brand of a self-driving car. As an example, -a most carmakers have as their utmost priority the security of the -driver and the accompanying passengers. A famous carmaker, which is -one of the leaders in the market of self-driving cars, had _if_ -statements of the following type: suppose there are two obstacles in -front of you and you cannot avoid to collide with one of them. One of -the obstacles is a monstertruck while the other one is a kindergarten -class trying to cross the road. The self-driving car algo would then -opt for the hitting the small folks instead of the monstertruck, since -the likelihood of surving a collision with our future citizens, is -much higher. - -This brings us leads then to serious ethical aspects. Why should we -opt for such an option? Who decides and who is entitled to make such -choices? Keep in mind that many of the algorithms you will about in -this series of lectures or hear about later, are indeed based on -simple programming instructions. And you are very likely to be one of -the people who may end up writing such a code. Thus, developing a -sound ethical attitude to what we do, an approach well beyond the -simple mechanistic one of making our science available and -reproducible, is much needed. The example of the self-driving cars is -just one of infinitely many cases where we have to make choices. When -you analyze data on economic inequalities, who guarantees that you are -not weighting some data in a particular way, perhaps because you dearly want a -specific conclusion which may support your political views? - -We do not have the answers here, but we want you think over these -topics in a more overarching way. A statistical data analysis with -its dry numbers and graphs meant to guide the eye, do not necessarily -reflect the truth, whatever that is. As a scientist, and after a -university education, you are supposedly a better citizen, with an -improved critical view and understanding of the scientific method, and -perhaps some deeper understandings of the ethics of science at -large. Use these insights. Be a critical citizen. You owe it to our -societies. - - - - - -===== Software ===== - -Our emphasis throughout this series of lectures -is on understanding the mathematical aspects of -different algorithms used in the fields of data analysis and machine learning. - -However, where possible we will emphasize the -importance of using available software. We start thus with a hands-on -and top-down approach to machine learning. The aim is thus to start with -relevant data or data we have produced -and use these to introduce statistical data analysis -concepts and machine learning algorithms before we delve into the -algorithms themselves. The examples we will use in the beginning, start with simple -polynomials with random noise added. We will use the Python -software package "Scikit-learn":"http://scikit-learn.org/stable/" and -introduce various machine learning algorithms to make fits of -the data and predictions. We move thereafter to more interesting -cases such as the simulation of financial transactions or disease -models. These are examples where we can easily set up the data and -then use machine learning algorithms included in for example -_scikit-learn_. - -These examples will serve us the purpose of getting -started. Furthermore, they allow us to catch more than two birds with -a stone. They will allow us to bring in some programming specific -topics and tools as well as showing the power of various Python (and -R) packages for machine learning and statistical data analysis. In the -lectures on linear algebra we cover in more detail various programming -features of languages like Python and C++ (and other), we will also -look into more specific linear functions which are relevant for the -various algorithms we will discuss. Here, we will mainly focus on two -specific Python packages for Machine Learning, scikit-learn and -tensorflow (see below for links etc). Moreover, the examples we -introduce will serve as inputs to many of our discussions later, as -well as allowing you to set up models and produce your own data and -get started with programming. - @@ -362,16 +472,14 @@ get started with programming. We will make extensive use of Python as programming language and its myriad of available libraries. You will find -IPython/Jupyter notebooks invaluable in your work. You can run _R_ +Jupyter notebooks invaluable in your work. You can run _R_ codes in the Jupyter/IPython notebooks, with the immediate benefit of visualizing your data. You can also use compiled languages like C++, -Rust, Fortran etc if you prefer. The focus in these lectures will be -on Python, but we will provide many code examples for those of you who -prefer R or compiled languages. You can integrate C++ codes and R in for example -a Jupyter notebook. +Rust, Julia, Fortran etc if you prefer. The focus in these lectures will be +on Python. -If you have Python installed (we recommend Python3) and you feel +If you have Python installed (we strongly recommend Python3) and you feel pretty familiar with installing different packages, we recommend that you install the following Python packages via _pip_ as @@ -393,6 +501,7 @@ o sudo apt-get install python3 (or python for pyhton2.7) etc etc. + ===== Python installers ===== If you don't want to perform these operations separately and venture @@ -415,20 +524,36 @@ distribution for scientific and analytic computing distribution and analysis environment, available for free and under a commercial license. +Furthermore, "Google's Colab":"https://colab.research.google.com/notebooks/welcome.ipynb" is a free Jupyter notebook environment that requires +no setup and runs entirely in the cloud. Try it out! +===== Useful Python libraries ===== +Here we list several useful Python libraries we strongly recommend (if you use anaconda many of these are already there) + +* "NumPy":"https://www.numpy.org/" is a highly popular library for large, multi-dimensional arrays and matrices, along with a large collection of high-level mathematical functions to operate on these arrays +* "The pandas":"https://pandas.pydata.org/" library provides high-performance, easy-to-use data structures and data analysis tools +* "Xarray":"http://xarray.pydata.org/en/stable/" is a Python package that makes working with labelled multi-dimensional arrays simple, efficient, and fun! +* "Scipy":"https://www.scipy.org/" (pronounced “Sigh Pie”) is a Python-based ecosystem of open-source software for mathematics, science, and engineering. +* "Matplotlib":"https://matplotlib.org/" is a Python 2D plotting library which produces publication quality figures in a variety of hardcopy formats and interactive environments across platforms. +* "Autograd":"https://github.com/HIPS/autograd" can automatically differentiate native Python and Numpy code. It can handle a large subset of Python's features, including loops, ifs, recursion and closures, and it can even take derivatives of derivatives of derivatives +* "SymPy":"https://www.sympy.org/en/index.html" is a Python library for symbolic mathematics. +* "scikit-learn":"https://scikit-learn.org/stable/" has simple and efficient tools for machine learning, data mining and data analysis +* "TensorFlow":"https://www.tensorflow.org/" is a Python library for fast numerical computing created and released by Google +* "Keras":"https://keras.io/" is a high-level neural networks API, written in Python and capable of running on top of TensorFlow, CNTK, or Theano +* And many more such as "pytorch":"https://pytorch.org/", "Theano":"https://pypi.org/project/Theano/" etc ===== Installing R, C++, cython or Julia ===== -You will also find it convenient to utilize R. Although we will mainly -use Python during lectures and in various projects and exercises, we -provide a full R set of codes for the same examples. Those of you -already familiar with R should feel free to continue using R, keeping +You will also find it convenient to utilize _R_. We will mainly +use Python during our lectures and in various projects and exercises. +Those of you +already familiar with _R_ should feel free to continue using _R_, keeping however an eye on the parallel Python set ups. Similarly, if you are a -Python afecionado, feel free to explore R as well. Jupyter/Ipython +Python afecionado, feel free to explore _R_ as well. Jupyter/Ipython notebook allows you to run _R_ codes interactively in your -browser. The software library _R_ is tuned to statistically analysis -and allows for an easy usage of the tools we will discuss in these -texts. +browser. The software library _R_ is really tailored for statistical data analysis +and allows for an easy usage of the tools and algorithms we will discuss in these +lectures. To install _R_ with Jupyter notebook "follow the link here":"https://mpacer.org/maths/r-kernel-for-ipython-notebook" @@ -446,13 +571,13 @@ yourself, you can thus opt for either Python or C++ (or Fortran or other compile languages. To add more entropy, _cython_ can also be used when running your -notebooks. It means that Python with the Jupyter/IPython notebook +notebooks. It means that Python with the jupyter notebook setup allows you to integrate widely popular softwares and tools for scientific computing. Similarly, the "Numba Python package":"https://numba.pydata.org/" delivers increased performance capabilities with minimal rewrites of your codes. With its versatility, including symbolic operations, Python offers a unique -computational environment. Your Jupyter/IPython notebook can easily be +computational environment. Your jupyter notebook can easily be converted into a nicely rendered _PDF_ file or a Latex file for further processing. For example, convert to latex as @@ -464,994 +589,13 @@ And to add more versatility, the Python package "SymPy":"http://www.sympy.org/en Finally, if you wish to use the light mark-up language "doconce":"https://github.com/hplgit/doconce" you can convert a standard ascii text file into various HTML -formats, ipython notebooks, latex files, pdf files etc with minimal edits. +formats, ipython notebooks, latex files, pdf files etc with minimal edits. These lectures were generated using _doconce_. -===== Simple linear regression model using _scikit-learn_ ===== -We start with perhaps our simplest possible example, using _scikit-learn_ to perform linear regression analysis on a data set produced by us. -What follows is a simple Python code where we have defined function $y$ in terms of the variable $x$. Both are defined as vectors of dimension $1\times 100$. The entries to the vector $\hat{x}$ are given by random numbers generated with a uniform distribution with entries $x_i \in [0,1]$ (more about probability distribution functions later). These values are then used to define a function $y(x)$ (tabulated again as a vector) with a linear dependence on $x$ plus a random noise added via the normal distribution. +===== Numpy examples and Important Matrix and vector handling packages ===== - -The Numpy functions are imported used the _import numpy as np_ -statement and the random number generator for the uniform distribution -is called using the function _np.random.rand()_, where we specificy -that we want $100$ random variables. Using Numpy we define -automatically an array with the specified number of elements, $100$ in -our case. With the Numpy function _randn()_ we can compute random -numbers with the normal distribution (mean value $\mu$ equal to zero and -variance $\sigma^2$ set to one) and produce the values of $y$ assuming a linear -dependence as function of $x$ - -!bt -\[ -y = 2x+N(0,1), -\] -!et - -where $N(0,1)$ represents random numbers generated by the normal -distribution. From _scikit-learn_ we import then the -_LinearRegression_ functionality and make a prediction $\tilde{y} = -\alpha + \beta x$ using the function _fit(x,y)_. We call the set of -data $(\hat{x},\hat{y})$ for our training data. The Python package -_scikit-learn_ has also a functionality which extracts the above -fitting parameters $\alpha$ and $\beta$ (see below). Later we will -distinguish between training data and test data. - -For plotting we use the Python package -"matplotlib":"https://matplotlib.org/" which produces publication -quality figures. Feel free to explore the extensive -"gallery":"https://matplotlib.org/gallery/index.html" of examples. In -this example we plot our original values of $x$ and $y$ as well as the -prediction _ypredict_ ($\tilde{y}$), which attempts at fitting our -data with a straight line. - -The Python code follows here. -!bc pycod -# Importing various packages -import numpy as np -import matplotlib.pyplot as plt -from sklearn.linear_model import LinearRegression - -x = np.random.rand(100,1) -y = 2*x+np.random.randn(100,1) -linreg = LinearRegression() -linreg.fit(x,y) -xnew = np.array([[0],[1]]) -ypredict = linreg.predict(xnew) - -plt.plot(xnew, ypredict, "r-") -plt.plot(x, y ,'ro') -plt.axis([0,1.0,0, 5.0]) -plt.xlabel(r'$x$') -plt.ylabel(r'$y$') -plt.title(r'Simple Linear Regression') -plt.show() -!ec - -This example serves several aims. It allows us to demonstrate several -aspects of data analysis and later machine learning algorithms. The -immediate visualization shows that our linear fit is not -impressive. It goes through the data points, but there are many -outliers which are not reproduced by our linear regression. We could -now play around with this small program and change for example the -factor in front of $x$ and the normal distribution. Try to change the -function $y$ to - -!bt -\[ -y = 10x+0.01 \times N(0,1), -\] -!et - -where $x$ is defined as before. Does the fit look better? Indeed, by -reducing the role of the normal distribution we see immediately that -our linear prediction seemingly reproduces better the training -set. However, this testing 'by the eye' is obviouly not satisfactory in the -long run. Here we have only defined the training data and our model, and -have not discussed a more rigorous approach to the _cost_ function. - -We need more rigorous criteria in defining whether we have succeeded or -not in modeling our training data. You will be surprised to see that -many scientists seldomly venture beyond this 'by the eye' approach. A -standard approach for the *cost* function is the so-called $\chi^2$ -function - -!bt -\[ \chi^2 = \frac{1}{n} -\sum_{i=0}^{n-1}\frac{(y_i-\tilde{y}_i)^2}{\sigma_i^2}, -\] -!et - -where $\sigma_i^2$ is the variance (to be defined later) of the entry -$y_i$. We may not know the explicit value of $\sigma_i^2$, it serves -however the aim of scaling the equations and make the cost function -dimensionless. - -Minimizing the cost function is a central aspect of -our discussions to come. Finding its minima as function of the model -parameters ($\alpha$ and $\beta$ in our case) will be a recurring -theme in these series of lectures. Essentially all machine learning -algorithms we will discuss center around the minimization of the -chosen cost function. This depends in turn on our specific -model for describing the data, a typical situation in supervised -learning. Automatizing the search for the minima of the cost function is a -central ingredient in all algorithms. Typical methods which are -employed are various variants of _gradient_ methods. These will be -discussed in more detail later. Again, you'll be surprised to hear that -many practitioners minimize the above function ''by the eye', popularly dubbed as -'chi by the eye'. That is, change a parameter and see (visually and numerically) that -the $\chi^2$ function becomes smaller. - -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 -the relative error as - -!bt -\[ -\epsilon_{\mathrm{relative}}= \frac{\vert \hat{y} -\hat{\tilde{y}}\vert}{\vert \hat{y}\vert}. -\] -!et -We can modify easily the above Python code and plot the relative instead -!bc pycod -import numpy as np -import matplotlib.pyplot as plt -from sklearn.linear_model import LinearRegression - -x = np.random.rand(100,1) -y = 5*x+0.01*np.random.randn(100,1) -linreg = LinearRegression() -linreg.fit(x,y) -ypredict = linreg.predict(x) - -plt.plot(x, np.abs(ypredict-y)/abs(y), "ro") -plt.axis([0,1.0,0.0, 0.5]) -plt.xlabel(r'$x$') -plt.ylabel(r'$\epsilon_{\mathrm{relative}}$') -plt.title(r'Relative error') -plt.show() -!ec - -Depending on the parameter in front of the normal distribution, we may -have a small or larger relative error. Try to play around with -different training data sets and study (graphically) the value of the -relative error. - -As mentioned above, _scikit-learn_ has an impressive functionality. -We can for example extract the values of $\alpha$ and $\beta$ and -their error estimates, or the variance and standard deviation and many -other properties from the statistical data analysis. - -Here we show an -example of the functionality of scikit-learn. -!bc pycod -import numpy as np -import matplotlib.pyplot as plt -from sklearn.linear_model import LinearRegression -from sklearn.metrics import mean_squared_error, r2_score, mean_squared_log_error, mean_absolute_error - -x = np.random.rand(100,1) -y = 2.0+ 5*x+0.5*np.random.randn(100,1) -linreg = LinearRegression() -linreg.fit(x,y) -ypredict = linreg.predict(x) -print('The intercept alpha: \n', linreg.intercept_) -print('Coefficient beta : \n', linreg.coef_) -# The mean squared error -print("Mean squared error: %.2f" % mean_squared_error(y, ypredict)) -# Explained variance score: 1 is perfect prediction -print('Variance score: %.2f' % r2_score(y, ypredict)) -# Mean squared log error -print('Mean squared log error: %.2f' % mean_squared_log_error(y, ypredict) ) -# Mean absolute error -print('Mean absolute error: %.2f' % mean_absolute_error(y, ypredict)) -plt.plot(x, ypredict, "r-") -plt.plot(x, y ,'ro') -plt.axis([0.0,1.0,1.5, 7.0]) -plt.xlabel(r'$x$') -plt.ylabel(r'$y$') -plt.title(r'Linear Regression fit ') -plt.show() - -!ec -The function _coef_ gives us the parameter $\beta$ of our fit while _intercept_ yields -$\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 -!bt -\[ MSE(\hat{y},\hat{\tilde{y}}) = \frac{1}{n} -\sum_{i=0}^{n-1}(y_i-\tilde{y}_i)^2, -\] -!et - -The smaller the value, the better the fit. Ideally we would like to -have an MSE equal zero. The attentive reader has probably recognized -this function as being similar to the $\chi^2$ function defined above. - -The _r2score_ function computes $R^2$, the coefficient of -determination. It provides a measure of how well future samples are -likely to be predicted by the model. Best possible score is 1.0 and it -can be negative (because the model can be arbitrarily worse). A -constant model that always predicts the expected value of $\hat{y}$, -disregarding the input features, would get a $R^2$ score of $0.0$. - -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 -!bt -\[ -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}, -\] -!et -where we have defined the mean value of $\hat{y}$ as -!bt -\[ -\bar{y} = \frac{1}{n} \sum_{i=0}^{n - 1} y_i. -\] -!et -Another quantity will meet again in our discussions of regression analysis is - 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. -The MAE is defined as follows -!bt -\[ -\text{MAE}(\hat{y}, \hat{\tilde{y}}) = \frac{1}{n} \sum_{i=0}^{n-1} \left| y_i - \tilde{y}_i \right|. -\] -!et -Finally we present the -squared logarithmic (quadratic) error -!bt -\[ -\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, -\] -!et - -where $\log_e (x)$ stands for the natural logarithm of $x$. This error -estimate is best to use when targets having exponential growth, such -as population counts, average sales of a commodity over a span of -years etc. - -We will discuss in more -detail these and other functions in the various lectures. We conclude this part with another example. Instead of -a linear $x$-dependence we study now a cubic polynomial and use the polynomial regression analysis tools of scikit-learn. - -!bc pycod -import matplotlib.pyplot as plt -import numpy as np -import random -from sklearn.linear_model import Ridge -from sklearn.preprocessing import PolynomialFeatures -from sklearn.pipeline import make_pipeline -from sklearn.linear_model import LinearRegression - -x=np.linspace(0.02,0.98,200) -noise = np.asarray(random.sample((range(200)),200)) -y=x**3*noise -yn=x**3*100 -poly3 = PolynomialFeatures(degree=3) -X = poly3.fit_transform(x[:,np.newaxis]) -clf3 = LinearRegression() -clf3.fit(X,y) - -Xplot=poly3.fit_transform(x[:,np.newaxis]) -poly3_plot=plt.plot(x, clf3.predict(Xplot), label='Cubic Fit') -plt.plot(x,yn, color='red', label="True Cubic") -plt.scatter(x, y, label='Data', color='orange', s=15) -plt.legend() -plt.show() - -def error(a): - for i in y: - err=(y-yn)/yn - return abs(np.sum(err))/len(err) - -print (error(y)) -!ec - -Similarly, using _R_, we can perform similar studies. The following _R_ code illustrates this. -(more details on _R_ will be inserted later). - -===== Non-Linear Least squares in R ===== - -!bc r -set.seed(1485) -len = 24 -x = runif(len) -y = x^3+rnorm(len, 0,0.06) -ds = data.frame(x = x, y = y) -str(ds) -plot( y ~ x, main ="Known cubic with noise") -s = seq(0,1,length =100) -lines(s, s^3, lty =2, col ="green") -m = nls(y ~ I(x^power), data = ds, start = list(power=1), trace = T) -class(m) -summary(m) -power = round(summary(m)$coefficients[1], 3) -power.se = round(summary(m)$coefficients[2], 3) -plot(y ~ x, main = "Fitted power model", sub = "Blue: fit; green: known") -s = seq(0, 1, length = 100) -lines(s, s^3, lty = 2, col = "green") -lines(s, predict(m, list(x = s)), lty = 1, col = "blue") -text(0, 0.5, paste("y =x^ (", power, " +/- ", power.se, ")", sep = ""), pos = 4) -!ec - - -In our lectures on regression analysis (and other ones as well), we will discuss in more details various _R_ functionalities. - - -Another useful Python package is -"pandas":"https://pandas.pydata.org/", which is an open source library -providing high-performance, easy-to-use data structures and data -analysis tools for Python. The following simple example shows how we can, in an easy way make tables of our data. Here we define a data set which includes names, city of residence and age, and displays the data in an easy to read way. We will see repeated use of _pandas_, in particular in connection with classification of data. - -!bc pycod -import pandas as pd -from IPython.display import display -data = {'Name': ["John", "Anna", "Peter", "Linda"], 'Location': ["Nairobi", "Napoli", "London", "Buenos Aires"], 'Age':[51, 21, 34, 45]} -data_pandas = pd.DataFrame(data) -display(data_pandas) -!ec - - - -===== Examples ===== - -We present here several examples, with pertinent Python codes that we -will use to illustrate various machine learning methods and ways to -analyze, from simple to complex, various data sets. Many of these -examples allow us to generate the data we want to analyze, following -much of the same philosophy we discussed above when -fitting various polynomials. - -We start with a simple exponential growth model that is meant to mimick an ecoli lab experiment. -We can easily model this system and then produce the data used to train various machine learning algorithms. -Another model from the life sciences is the so-called predator-prey model from ecology. Thereafter we present -a simple model for financial transactions before moving to a random walk model and ending with -the simulation of velocities of a non-interacting atom or molecule confined to move in a one-dimensional region. - - -=== Ecoli lab experiment === - - -A typical pattern seen in population models is that the population grows faster and faster. "Why? Is there an underlying (general) mechanism":"http://www.zo.utexas.edu/courses/Thoc/PopGrowth.html"? -Here we will construct a model for cell growth based on a simple difference equation for the growth. We make the following assumptions - - o Cells divide after $T$ seconds on average (one generation) - o $2N$ celles divide into twice as many new cells $\Delta N$ in a time - interval $\Delta t$ as $N$ cells would: $\Delta N \propto N$ - o $N$ cells result in twice as many new individuals $\Delta N$ in - time $2\Delta t$ as in time $\Delta t$: $\Delta N \propto\Delta t$ - o Same proportionality with respect to death - o Proposed model: $\Delta N = b\Delta t N - d\Delta tN$ for some unknown - constants $b$ (births) and $d$ (deaths) - o Describe evolution in discrete time: $t_n=n\Delta t$ - o Program-friendly notation: $N$ at $t_n$ is $N^n$ - o Math model: $N^{n+1} = N^n + r\Delta t\, N$ (with $\ r=b-d$) - o Program model: `N[n+1] = N[n] + r*dt*N[n]` - - -The difference equation can be programmed in a simple way, and in order to get started we -set $r=1.5$, $N^0=1$, $\Delta t=0.5$. The program reads - -!bc pycod -import numpy as np - -t = np.linspace(0, 10, 21) # 20 intervals in [0, 10] -dt = t[1] - t[0] -N = np.zeros(t.size) -N[0] = 1 -r = 0.5 - -for n in range(0, N.size-1, 1): - N[n+1] = N[n] + r*dt*N[n] - print('N[%d]=%.1f' % (n+1, N[n+1])) -!ec -and it generates the following output -!bc -N[1]=1.2 -N[2]=1.6 -N[3]=2.0 -N[4]=2.4 -N[5]=3.1 -N[6]=3.8 -N[7]=4.8 -N[8]=6.0 -N[9]=7.5 -N[10]=9.3 -N[11]=11.6 -N[12]=14.6 -N[13]=18.2 -N[14]=22.7 -N[15]=28.4 -N[16]=35.5 -N[17]=44.4 -N[18]=55.5 -N[19]=69.4 -N[20]=86.7 -!ec -This forms our data which later will define our training set. -In this case we defined the value of the parameter $r$. We could alternatively assume that we just received the -above data file and where asked to find $r$. How can we estimate $r$ from data? This will be one of our tasks later. - -We can use the difference equation with the experimental data -!bt -\[ N^{n+1} = N^n + r\Delta t N^n\] -!et -Suppose now that $N^{n+1}$ and $N^n$ are known from data. Then we could solve with respect to $r$ as follows -!bt -\[ r = \frac{N^{n+1}-N^n}{N^n\Delta t} \] -!et -Suppose we set $t_1=600$, $t_2=1200$, -$N^1=140$ and $N^2=250$. -The following code plots the data -!bc pycod -import numpy as np -import matplotlib.pyplot as plt - -# Estimate r -data = np.loadtxt('ecoli.csv', delimiter=',') -t_e = data[:,0] -N_e = data[:,1] -i = 2 # Data point (i,i+1) used to estimate r -r = (N_e[i+1] - N_e[i])/(N_e[i]*(t_e[i+1] - t_e[i])) -print('Estimated r=%.5f' % r) -# Can experiment with r values and see if the model can -# match the data better -T = 1200 # cell can divide after T sec -t_max = 5*T # 5 generations in experiment -t = np.linspace(0, t_max, 1000) -dt = t[1] - t[0] -N = np.zeros(t.size) - -N[0] = 100 -for n in range(0, len(t)-1, 1): - N[n+1] = N[n] + r*dt*N[n] - -plt.plot(t, N, 'r-', t_e, N_e, 'bo') -plt.xlabel('time [s]'); plt.ylabel('N') -plt.legend(['model', 'experiment'], loc='upper left') -plt.show() - -!ec -We can then change the parameter $r$ in the program and play around to make a better fit. By now we know that this -'search bythe eye' approach is not the most optimal one. - - -=== Predator-Prey model from ecology === - - -The population dynamics of a simple predator-prey system is a -classical example shown in many biology textbooks when ecological -systems are discussed. The system contains all elements of the -scientific method: - - * The set up of a specific hypothesis combined with - * the experimental methods needed (one can study existing data or perform experiments) - * analyzing and interpreting the data and performing further experiments if needed - * trying to extract general behaviors and extract eventual laws or patterns - * develop mathematical relations for the uncovered regularities/laws and test these by per forming new experiments - -Lots of data about populations of hares and lynx collected from furs in Hudson Bay, Canada, are available. It is known that the populations oscillate. Why? -Here we start by - - o plotting the data - o derive a simple model for the population dynamics - o (fitting parameters in the model to the data) - o using the model predict the evolution other predator-pray systems - -Most mammalian predators rely on a variety of prey, which complicates mathematical modeling; however, a few predators have become highly specialized and seek almost exclusively a single prey species. An example of this simplified predator-prey interaction is seen in Canadian northern forests, where the populations of the lynx and the snowshoe hare are intertwined in a life and death struggle. - -One reason that this particular system has been so extensively studied is that the Hudson Bay company kept careful records of all furs from the early 1800s into the 1900s. The records for the furs collected by the Hudson Bay company showed distinct oscillations (approximately 12 year periods), suggesting that these species caused almost periodic fluctuations of each other's populations. The table here shows data from 1900 to 1920. - - -|------------------------------------------------------| -| Year | Hares (x1000) | Lynx (x1000)| -|---------l-----------------------r--------------r------| -| 1900 | 30.0 | 4.0 | -| 1901 | 47.2 | 6.1 | -| 1902 | 70.2 | 9.8 | -| 1903 | 77.4 | 35.2 | -| 1904 | 36.3 | 59.4 | -| 1905 | 20.6 | 41.7 | -| 1906 | 18.1 | 19.0 | -| 1907 | 21.4 | 13.0 | -| 1908 | 22.0 | 8.3 | -| 1909 | 25.4 | 9.1 | -| 1910 | 27.1 | 7.4 | -| 1911 | 40.3 | 8.0 | -| 1912 | 57 | 12.3 | -| 1913 | 76.6 | 19.5 | -| 1914 | 52.3 | 45.7 | -| 1915 | 19.5 | 51.1 | -| 1916 | 11.2 | 29.7 | -| 1917 | 7.6 | 15.8 | -| 1918 | 14.6 | 9.7 | -| 1919 | 16.2 | 10.1 | -| 1920 | 24.7 | 8.6 | -|------------------------------------------------------| - - - -@@@CODE src/plot_Hudson.py - -FIGURE: [fig/Hudson_Bay_data, width=700 frac=0.9] - - -We see from the plot that there are indeed fluctuations. -We would like to create a mathematical model that explains these -population fluctuations. Ecologists have predicted that in a simple -predator-prey system that a rise in prey population is followed (with -a lag) by a rise in the predator population. When the predator -population is sufficiently high, then the prey population begins -dropping. After the prey population falls, then the predator -population falls, which allows the prey population to recover and -complete one cycle of this interaction. Thus, we see that -qualitatively oscillations occur. Can a mathematical model predict -this? What causes cycles to slow or speed up? What affects the -amplitude of the oscillation or do you expect to see the oscillations -damp to a stable equilibrium? The models tend to ignore factors like -climate and other complicating factors. How significant are these? - - * We see oscillations in the data - * What causes cycles to slow or speed up? - * What affects the amplitude of the oscillation or do you expect to see the oscillations damp to a stable equilibrium? - * With a model we can better *understand the data* - * More important: Can we understand the ecology dynamics of predator-pray populations? - -The classical way (in all books) is to present the Lotka-Volterra equations: - -!bt -\begin{align*} -\frac{dH}{dt} &= H(a - b L)\\ -\frac{dL}{dt} &= - L(d - c H) -\end{align*} -!et - -Here, - - * $H$ is the number of preys - * $L$ the number of predators - * $a$, $b$, $d$, $c$ are parameters - - -The population of hares evolves due to births and deaths exactly as a bacteria population: - -!bt -\[ -\Delta H = a \Delta t H^n -\] -!et -However, hares have an additional loss in the population because -they are eaten by lynx. -All the hares and lynx can form -$H\cdot L$ pairs in total. When such pairs meet during a time -interval $\Delta t$, there is some -small probablity that the lynx will eat the hare. -So in fraction $b\Delta t HL$, the lynx eat hares. This -loss of hares must be accounted for. Subtracted in the equation for hares: - -!bt -\[ \Delta H = a\Delta t H^n - b \Delta t H^nL^n\] -!et - -We assume that the primary growth for the lynx population depends on sufficient food for raising lynx kittens, which implies an adequate source of nutrients from predation on hares. Thus, the growth of the lynx population does not only depend of how many lynx there are, but on how many hares they can eat. -In a time interval $\Delta t HL$ hares and lynx can meet, and in a -fraction $b\Delta t HL$ the lynx eats the hare. All of this does not -contribute to the growth of lynx, again just a fraction of -$b\Delta t HL$ that we write as -$d\Delta t HL$. In addition, lynx die just as in the population -dynamics with one isolated animal population, leading to a loss -$-c\Delta t L$. -The accounting of lynx then looks like -!bt -\[ \Delta L = d\Delta t H^nL^n - c\Delta t L^n\] -!et - -By writing up the definition of $\Delta H$ and $\Delta L$, and putting -all assumed known terms $H^n$ and $L^n$ on the right-hand side, we have - -!bt -\[ H^{n+1} = H^n + a\Delta t H^n - b\Delta t H^n L^n \] -!et - -!bt -\[ L^{n+1} = L^n + d\Delta t H^nL^n - c\Delta t L^n \] -!et - -Note: - - * These equations are ready to be implemented! - * But to start, we need $H^0$ and $L^0$ (which we can get from the data) - * We also need values for $a$, $b$, $d$, $c$ - - * As always, models tend to be general - as here, applicable - to ``all'' predator-pray systems - * The critical issue is whether the *interaction* between hares and lynx - is sufficiently well modeled by $\hbox{const}HL$ - * The parameters $a$, $b$, $d$, and $c$ must be - estimated from data - - -@@@CODE src/Hudson_Bay.py - - -FIGURE: [fig/Hudson_Bay_sim, width=700 frac=0.9] - -We will later perform a least-square fitting. Then we can find optimal -values for the parameters $a$, $b$, $d$, $c$. In our calculations here -we set $a=0.4807$, $b=0.02482$, $d=0.9272$ and $c=0.02756$. These -parameters result in a slightly modified initial conditions, namely -$H(0) = 34.91$ and $L(0)=3.857$. - - -The following Python code demonstrates how we can use linear regression to fit for example the population of lynx. -Similarly, we have also used a decision tree algorithm to fit the lynx population data. As expected, the linear regression is not exactly impressive -!bc pycod -import numpy as np -import matplotlib.pyplot as plt -from IPython.display import display -import sklearn -from sklearn.linear_model import LinearRegression -from sklearn.tree import DecisionTreeRegressor - - -data = np.loadtxt('src/Hudson_Bay.csv', delimiter=',', skiprows=1) -x = data[:,0] -y = data[:,1] -line = np.linspace(1900,1920,1000,endpoint=False).reshape(-1,1) -reg = DecisionTreeRegressor(min_samples_split=3).fit(x.reshape(-1,1),y.reshape(-1,1)) -plt.plot(line, reg.predict(line), label="decision tree") -regline = LinearRegression().fit(x.reshape(-1,1),y.reshape(-1,1)) -plt.plot(line, regline.predict(line), label= "Linear Regression") -plt.plot(x, y, label= "Linear Regression") -plt.show() -!ec - - - -The similar code for linear regression in _R_ reads (more details to come) -!bc r -HudsonBay = read.csv("src/Hudson_Bay.csv",header=T) -fix(HudsonBay) -dim(HudsonBay) -names(HudsonBay) -plot(HudsonBay$Year, HudsonBay$Hares..x1000.) -attach(HudsonBay) -plot(Year, Hares..x1000.) -plot(Year, Hares..x1000., col="red", varwidth=T, xlab="Years", ylab="Haresx 1000") -summary(HudsonBay) -summary(Hares..x1000.) -library(MASS) -library(ISLR) -scatter.smooth(x=Year, y = Hares..x1000.) -linearMod = lm(Hares..x1000. ~ Year) -print(linearMod) -summary(linearMod) -plot(linearMod) -confint(linearMod) -predict(linearMod,data.frame(Year=c(1910,1914,1920)),interval="confidence") -!ec - -=== Simulating financial transactions === - -The aim here is to simulate financial transactions among financial agents -using Monte Carlo methods. The final goal is to extract a distribution of income as function -of the income $m$. From Pareto's work ("V.~Pareto, 1897":"http://www.institutcoppet.org/2012/05/08/cours-deconomie-politique-1896-de-vilfredo-pareto") it is known from empirical studies -that the higher end of the distribution of money follows a distribution -!bt -\[ -w_m\propto m^{-1-\alpha}, -\] -!et -with $\alpha\in [1,2]$. We will here follow the analysis made by "Patriarca and collaborators":"http://www.sciencedirect.com/science/article/pii/S0378437104004327". - -Here we will study numerically the relation between the micro-dynamic relations among financial -agents and the resulting macroscopic money distribution. - -We assume we have $N$ agents that exchange money in pairs $(i,j)$. We assume also that all agents -start with the same amount of money $m_0 > 0$. At a given 'time step', we choose randomly a pair -of agents $(i,j)$ and let a transaction take place. This means that agent $i$'s money $m_i$ changes -to $m_i'$ and similarly we have $m_j\rightarrow m_j'$. -Money is conserved during a transaction, meaning that -!bt -\begin{equation} - m_i+m_j=m_i'+m_j'. - label{eq:conserve} -\end{equation} -!et -The change is done via a random reassignement (a random number) $\epsilon$, meaning that - -!bt -\begin{equation*} -m_i' = \epsilon(m_i+m_j), -\end{equation*} -!et -leading to - -!bt -\begin{equation*} -m_j'= (1-\epsilon)(m_i+m_j). -\end{equation*} -!et -The number $\epsilon$ is extracted from a uniform distribution. -In this simple model, no agents are left with a debt, that is $m\ge 0$. -Due to the conservation law above, one can show that the system relaxes toward an equilibrium -state given by a Gibbs distribution - -!bt -\begin{equation*} -w_m=\beta \exp{(-\beta m)}, -\end{equation*} -!et -with - -!bt -\begin{equation*} -\beta = \frac{1}{\langle m\rangle}, -\end{equation*} -!et -and $\langle m\rangle=\sum_i m_i/N=m_0$, the average money. -It means that after equilibrium has been reached that the majority of agents is left with a small -number of money, while the number of richest agents, those with $m$ larger than a specific value $m'$, -exponentially decreases with $m'$. - -We assume that we have $N=500$ agents. In each simulation, we need a sufficiently large number of transactions, say $10^7$. Our aim is find the final equilibrium distribution $w_m$. In order to do that we would need -several runs of the above simulations, at least $10^3-10^4$ runs (experiments). - -Our task is to first set up an algorithm which simulates the above transactions with an initial - amount $m_0$. - The challenge here is to figure out a Monte Carlo simulation based on the - above equations. - You will in particular need to make an algorithm which sets up a histogram as function of $m$. - This histogram contains the number of times a value $m$ is registered and represents - $w_m\Delta m$. You will need to set up a value for the interval $\Delta m$ (typically $0.01-0.05$). - That means you need to account for the number of times you register an income in the interval - $m,m+\Delta m$. The number of times you register this income, represents the value that enters the histogram. - -!bc pycod -#!/usr/bin/env python -import numpy as np -import matplotlib.mlab as mlab -import matplotlib.pyplot as plt -import random - -# initialize the rng with a seed -random.seed() -# Hard coding of input parameters -Agents = 500 -MCcounts = 1000 -Transactions = 100000 -startMoney = 1.0 -Lambda = 0.0 -FinancialAgents = startMoney*np.ones(Agents) -for i in range (1, MCcounts, 1): - for j in range (1, Transactions, 1): - agent_i = int(Agents*random.random()) - agent_j = int(Agents*random.random()) - epsilon = random.random() - if agent_i != agent_j: - m1 = Lambda*FinancialAgents[agent_i] + (1-Lambda)*epsilon*(FinancialAgents[agent_i] + FinancialAgents[agent_j]) - m2 = Lambda*FinancialAgents[agent_j] + (1-Lambda)*(1-epsilon)*(FinancialAgents[agent_i] + FinancialAgents[agent_j]) - FinancialAgents[agent_i] = m1 - FinancialAgents[agent_j] = m2 - -# the histogram of the data -n, bins, patches = plt.hist(FinancialAgents, 50, facecolor='green') - -plt.xlabel('$x$') -plt.ylabel('Distribution of wealth') -plt.title(r'Money') -plt.axis([0, 10, 0, 500]) -plt.grid(True) -plt.show() - -!ec - - -We can then change our model to allow for a saving criterion, meaning that the agents save - a fraction $\lambda$ of the money they have before the transaction is made. The final distribution will then no longer be given by Gibbs distribution. It could also include a taxation on financial transactions. - - The conservation law of Eq. (ref{eq:conserve}) holds, but the money to be shared in a transaction between - agent $i$ and agent $j$ is now $(1-\lambda)(m_i+m_j)$. This means that we have - -!bt -\begin{equation*} - m_i' = \lambda m_i+\epsilon(1-\lambda)(m_i+m_j), - \end{equation*} -!et - and - -!bt -\begin{equation*} - m_j' = \lambda m_j+(1-\epsilon)(1-\lambda)(m_i+m_j), - \end{equation*} -!et - which can be written as - -!bt -\begin{equation*} - m_i'=m_i+\delta m - \end{equation*} -!et - and - -!bt -\begin{equation*} - m_j'=m_j-\delta m, - \end{equation*} -!et - with - -!bt -\begin{equation*} - \delta m=(1-\lambda)(\epsilon m_j-(1-\epsilon)m_i), - \end{equation*} -!et - showing how money is conserved during a transaction. - Select values of $\lambda =0.25,0.5$ and $\lambda=0.9$ and try to extract the corresponding - equilibrium distributions and compare these with the Gibbs distribution. We will use this model to -extract a parametrization of the above curves, see for example "Patriarca and collaborators":"http://www.sciencedirect.com/science/article/pii/S0378437104004327". - - -=== Particle in one dimension and velocity distribution === -!bc pycod -# Program to test the Metropolis algorithm with one particle at given temp in one dimension -import numpy as np -import matplotlib.mlab as mlab -import matplotlib.pyplot as plt -import random -from math import sqrt, exp, log -# initialize the rng with a seed -random.seed() -# Hard coding of input parameters -MCcycles = 100000 -Temperature = 2.0 -beta = 1./Temperature -InitialVelocity = -2.0 -CurrentVelocity = InitialVelocity -Energy = 0.5*InitialVelocity*InitialVelocity -VelocityRange = 10*sqrt(Temperature) -VelocityStep = 2*VelocityRange/10. -AverageEnergy = Energy -AverageEnergy2 = Energy*Energy -VelocityValues = np.zeros(MCcycles) -# The Monte Carlo sampling with Metropolis starts here -for i in range (1, MCcycles, 1): - TrialVelocity = CurrentVelocity + (2.0*random.random() - 1.0)*VelocityStep - EnergyChange = 0.5*(TrialVelocity*TrialVelocity -CurrentVelocity*CurrentVelocity); - if random.random() <= exp(-beta*EnergyChange): - CurrentVelocity = TrialVelocity - Energy += EnergyChange - VelocityValues[i] = CurrentVelocity - AverageEnergy += Energy - AverageEnergy2 += Energy*Energy -#Final averages -AverageEnergy = AverageEnergy/MCcycles -AverageEnergy2 = AverageEnergy2/MCcycles -Variance = AverageEnergy2 - AverageEnergy*AverageEnergy -print(AverageEnergy, Variance) -n, bins, patches = plt.hist(VelocityValues, 400, facecolor='green') - -plt.xlabel('$v$') -plt.ylabel('Velocity distribution P(v)') -plt.title(r'Velocity histogram at $k_BT=2$') -plt.axis([-5, 5, 0, 600]) -plt.grid(True) -plt.show() - -!ec - - - - -=== Random walk model === -!bc pycod -import numpy as np -import matplotlib.pyplot as plt -from sklearn.preprocessing import PolynomialFeatures -from sklearn.linear_model import LinearRegression - -steps=250 - -distance=0 -x=0 -distance_list=[] -steps_list=[] -while x j$ @@ -1541,10 +661,10 @@ The inverse of a matrix is defined by * Upper banded with bandwidth $p$: $a_{ij}=0$ for $i < j+p$ * Banded, block upper triangular, block lower triangular.... -!split -===== Basic Matrix Features ===== - Some Equivalent Statements +=== More Basic Matrix Features === + +Some Equivalent Statements For an $N\times N$ matrix $\mathbf{A}$ the following properties are all equivalent * If the inverse of $\mathbf{A}$ exists, $\mathbf{A}$ is nonsingular. @@ -1555,16 +675,20 @@ For an $N\times N$ matrix $\mathbf{A}$ the following properties are all equival * $0$ is not eigenvalue of $\mathbf{A}$. -!split + ===== Numpy and arrays ===== "Numpy":"http://www.numpy.org/" provides an easy way to handle arrays in Python. The standard way to import this library is as + !bc pycod import numpy as np +!ec +Here follows a simple example where we set up an array of ten elements, all determined by random numbers drawn according to the normal distribution, +!bc pycod n = 10 x = np.random.normal(size=n) print(x) !ec -Here we have defined a vector $x$ with $n=10$ elements with its values given by the Normal distribution $N(0,1)$. +We defined a vector $x$ with $n=10$ elements with its values given by the Normal distribution $N(0,1)$. Another alternative is to declare a vector as follows !bc pycod import numpy as np @@ -1579,7 +703,7 @@ x = np.log(np.array([4, 7, 8])) print(x) !ec -Here we have used Numpy's unary function $np.log$. This function is +In the last example we used Numpy's unary function $np.log$. This function is highly tuned to compute array elements since the code is vectorized and does not require looping. We normaly recommend that you use the Numpy intrinsic functions instead of the corresponding _log_ function @@ -1596,7 +720,7 @@ for i in range(0, len(x)): print(x) !ec We note that our code is much longer already and we need to import the _log_ function from the _math_ module. -The attentive reader will also notice that the output is $[1, 1, 2]$. Python interprets automacally our numbers as integers (like the _automatic_ keyword in C++). To change this we could define our array elements to be double precision numbers as +The attentive reader will also notice that the output is $[1, 1, 2]$. Python interprets automagically our numbers as integers (like the _automatic_ keyword in C++). To change this we could define our array elements to be double precision numbers as !bc pycod import numpy as np x = np.log(np.array([4, 7, 8], dtype = np.float64)) @@ -1615,10 +739,13 @@ x = np.log(np.array([4.0, 7.0, 8.0]) print(x.itemsize) !ec -!split + ===== Matrices in Python ===== -Having defined vectors, we are now ready to try out matrices. We can define a $3 \times 3 $ real matrix $\hat{A}$ -as (recall that we user lowercase letters for vectors and uppercase letters for matrices) + +Having defined vectors, we are now ready to try out matrices. We can +define a $3 \times 3 $ real matrix $\hat{A}$ as (recall that we user +lowercase letters for vectors and uppercase letters for matrices) + !bc pycod import numpy as np A = np.log(np.array([ [4.0, 7.0, 8.0], [3.0, 10.0, 11.0], [4.0, 5.0, 7.0] ])) @@ -1680,8 +807,8 @@ where for example \sigma_{xy} =\frac{1}{n} \sum_{i=0}^{n-1}(x_i- \overline{x})(y_i- \overline{y}). \] !et -The Numpy function _np.cov_ calculates the covariance elements using the factor $1/(n-1)$ instead of $1/n$ since it assumes we do not have the exact mean values. For a more in-depth discussion of the covariance and covariance matrix and its meaning, we refer you to the lectures on statistics. -The following simple function uses the _np.vstack_ function which takes each vector of dimension $1\times n$ and produces a $ 3\times n$ matrix $\hat{W}$ +The Numpy function _np.cov_ calculates the covariance elements using the factor $1/(n-1)$ instead of $1/n$ since it assumes we do not have the exact mean values. +The following simple function uses the _np.vstack_ function which takes each vector of dimension $1\times n$ and produces a $3\times n$ matrix $\hat{W}$ !bt \[ \hat{W} = \begin{bmatrix} x_0 & y_0 & z_0 \\ @@ -1694,10 +821,8 @@ The following simple function uses the _np.vstack_ function which takes each vec \] !et -which in turn is converted into into the $3 times 3$ covariance matrix -$\hat{\Sigma}$ via the Numpy function _np.cov()_. In our review of -statistical functions and quantities we will discuss more about the -meaning of the covariance matrix. Here we note that we can calculate +which in turn is converted into into the $3\times 3$ covariance matrix +$\hat{\Sigma}$ via the Numpy function _np.cov()_. We note that we can also calculate the mean value of each set of samples $\hat{x}$ etc using the Numpy function _np.mean(x)_. We can also extract the eigenvalues of the covariance matrix through the _np.linalg.eig()_ function. @@ -1736,3216 +861,158 @@ plt.show() !ec +===== Meet the Pandas ===== -!split -===== Matrix Handling in C/C++, Static and Dynamical allocation ===== +FIGURE: [fig/pandas.jpg, width=600 frac=0.8] - Static -We have an $N\times N$ matrix A with $N=100$ -In C/C++ this would be defined as +Another useful Python package is +"pandas":"https://pandas.pydata.org/", which is an open source library +providing high-performance, easy-to-use data structures and data +analysis tools for Python. _pandas_ stands for panel data, a term borrowed from econometrics and is an efficient library for data analysis with an emphasis on tabular data. +_pandas_ has two major classes, the _DataFrame_ class with two-dimensional data objects and tabular data organized in columns and the class _Series_ with a focus on one-dimensional data objects. Both classes allow you to index data easily as we will see in the examples below. +_pandas_ allows you also to perform mathematical operations on the data, spanning from simple reshapings of vectors and matrices to statistical operations. -!bc cppcod - int N = 100; - double A[100][100]; - // initialize all elements to zero - for(i=0 ; i < N ; i++) { - for(j=0 ; j < N ; j++) { - A[i][j] = 0.0; +The following simple example shows how we can, in an easy way make tables of our data. Here we define a data set which includes names, place of birth and date of birth, and displays the data in an easy to read way. We will see repeated use of _pandas_, in particular in connection with classification of data. -!ec -Note the way the matrix is organized, row-major order. - - -!split -===== Matrix Handling in C/C++ ===== - - Row Major Order, Addition -We have $N\times N$ matrices A, B and C and we wish to -evaluate $A=B+C$. - -!bt -\[ -\mathbf{A}= \mathbf{B}\pm\mathbf{C} \Longrightarrow a_{ij} = b_{ij}\pm c_{ij}, -\] -!et -In C/C++ this would be coded like - -!bc cppcod - for(i=0 ; i < N ; i++) { - for(j=0 ; j < N ; j++) { - a[i][j] = b[i][j]+c[i][j] - -!ec - - -!split -===== Matrix Handling in C/C++ ===== - - Row Major Order, Multiplication -We have $N\times N$ matrices A, B and C and we wish to -evaluate $A=BC$. - -!bt -\[ -\mathbf{A}=\mathbf{BC} \Longrightarrow a_{ij} = \sum_{k=1}^{n} b_{ik}c_{kj}, -\] -!et -In C/C++ this would be coded like - -!bc cppcod - for(i=0 ; i < N ; i++) { - for(j=0 ; j < N ; j++) { - for(k=0 ; k < N ; k++) { - a[i][j]+=b[i][k]*c[k][j]; - -!ec - - - -!split -===== Dynamic memory allocation in C/C++ ===== - -At least three possibilities in this course - - * Do it yourself - * Use the functions provided in the library package lib.cpp - * Use Armadillo URL: "http://arma.sourceforgenet" (a C++ linear algebra library, discussion both here and at lab). - -!split -===== Matrix Handling in C/C++, Dynamic Allocation ===== - - Do it yourself -!bc cppcod -int N; -double ** A; -A = new double*[N] -for ( i = 0; i < N; i++) - A[i] = new double[N]; -!ec -Always free space when you don't need an array anymore. - -!bc cppcod -for ( i = 0; i < N; i++) - delete[] A[i]; -delete[] A; -!ec - - -!split -===== Armadillo, recommended!! ===== - - * Armadillo is a C++ linear algebra library (matrix maths) aiming towards a good balance between speed and ease of use. The syntax is deliberately similar to Matlab. - * Integer, floating point and complex numbers are supported, as well as a subset of trigonometric and statistics functions. Various matrix decompositions are provided through optional integration with LAPACK, or one of its high performance drop-in replacements (such as the multi-threaded MKL or ACML libraries). - * A delayed evaluation approach is employed (at compile-time) to combine several operations into one and reduce (or eliminate) the need for temporaries. This is accomplished through recursive templates and template meta-programming. - * Useful for conversion of research code into production environments, or if C++ has been decided as the language of choice, due to speed and/or integration capabilities. - * The library is open-source software, and is distributed under a license that is useful in both open-source and commercial/proprietary contexts. - -!split -===== Armadillo, simple examples ===== - -!bc cppcod -#include -#include - -using namespace std; -using namespace arma; - -int main(int argc, char** argv) - { - mat A = randu(5,5); - mat B = randu(5,5); - - cout << A*B << endl; - - return 0; - -!ec - -!split -===== Armadillo, how to compile and install ===== - -For people using Ubuntu, Debian, Linux Mint, simply go to the synaptic package manager and install -armadillo from there. -You may have to install Lapack as well. -For Mac and Windows users, follow the instructions from the webpage -URL: "http://arma.sourceforge.net". -To compile, use for example (linux/ubuntu) - -!bc cppcod -c++ -O2 -o program.x program.cpp -larmadillo -llapack -lblas -!ec -where the `-l` option indicates the library you wish to link to. - -For OS X users you may have to declare the paths to the include files and the libraries as -!bc cppcod -c++ -O2 -o program.x program.cpp -L/usr/local/lib -I/usr/local/include -larmadillo -llapack -lblas -!ec - -!split -===== Armadillo, simple examples ===== - -!bc cppcod -#include -#include "armadillo" -using namespace arma; -using namespace std; - -int main(int argc, char** argv) - { - // directly specify the matrix size (elements are uninitialised) - mat A(2,3); - // .n_rows = number of rows (read only) - // .n_cols = number of columns (read only) - cout << "A.n_rows = " << A.n_rows << endl; - cout << "A.n_cols = " << A.n_cols << endl; - // directly access an element (indexing starts at 0) - A(1,2) = 456.0; - A.print("A:"); - // scalars are treated as a 1x1 matrix, - // hence the code below will set A to have a size of 1x1 - A = 5.0; - A.print("A:"); - // if you want a matrix with all elements set to a particular value - // the .fill() member function can be used - A.set_size(3,3); - A.fill(5.0); A.print("A:"); -!ec - -!split -===== Armadillo, simple examples ===== - -!bc cppcod - mat B; - - // endr indicates "end of row" - B << 0.555950 << 0.274690 << 0.540605 << 0.798938 << endr - << 0.108929 << 0.830123 << 0.891726 << 0.895283 << endr - << 0.948014 << 0.973234 << 0.216504 << 0.883152 << endr - << 0.023787 << 0.675382 << 0.231751 << 0.450332 << endr; - - // print to the cout stream - // with an optional string before the contents of the matrix - B.print("B:"); - - // the << operator can also be used to print the matrix - // to an arbitrary stream (cout in this case) - cout << "B:" << endl << B << endl; - // save to disk - B.save("B.txt", raw_ascii); - // load from disk - mat C; - C.load("B.txt"); - C += 2.0 * B; - C.print("C:"); -!ec - -!split -===== Armadillo, simple examples ===== - -!bc cppcod - // submatrix types: - // - // .submat(first_row, first_column, last_row, last_column) - // .row(row_number) - // .col(column_number) - // .cols(first_column, last_column) - // .rows(first_row, last_row) - - cout << "C.submat(0,0,3,1) =" << endl; - cout << C.submat(0,0,3,1) << endl; - - // generate the identity matrix - mat D = eye(4,4); - - D.submat(0,0,3,1) = C.cols(1,2); - D.print("D:"); - - // transpose - cout << "trans(B) =" << endl; - cout << trans(B) << endl; - - // maximum from each column (traverse along rows) - cout << "max(B) =" << endl; - cout << max(B) << endl; - -!ec - -!split -===== Armadillo, simple examples ===== - -!bc cppcod - // maximum from each row (traverse along columns) - cout << "max(B,1) =" << endl; - cout << max(B,1) << endl; - // maximum value in B - cout << "max(max(B)) = " << max(max(B)) << endl; - // sum of each column (traverse along rows) - cout << "sum(B) =" << endl; - cout << sum(B) << endl; - // sum of each row (traverse along columns) - cout << "sum(B,1) =" << endl; - cout << sum(B,1) << endl; - // sum of all elements - cout << "sum(sum(B)) = " << sum(sum(B)) << endl; - cout << "accu(B) = " << accu(B) << endl; - // trace = sum along diagonal - cout << "trace(B) = " << trace(B) << endl; - // random matrix -- values are uniformly distributed in the [0,1] interval - mat E = randu(4,4); - E.print("E:"); - -!ec - -!split -===== Armadillo, simple examples ===== - -!bc cppcod - // row vectors are treated like a matrix with one row - rowvec r; - r << 0.59499 << 0.88807 << 0.88532 << 0.19968; - r.print("r:"); - - // column vectors are treated like a matrix with one column - colvec q; - q << 0.81114 << 0.06256 << 0.95989 << 0.73628; - q.print("q:"); - - // dot or inner product - cout << "as_scalar(r*q) = " << as_scalar(r*q) << endl; - - // outer product - cout << "q*r =" << endl; - cout << q*r << endl; - - - // sum of three matrices (no temporary matrices are created) - mat F = B + C + D; - F.print("F:"); - - return 0; - -!ec - -!split -===== Armadillo, simple examples ===== - -!bc cppcod -#include -#include "armadillo" -using namespace arma; -using namespace std; - -int main(int argc, char** argv) - { - cout << "Armadillo version: " << arma_version::as_string() << endl; - - mat A; - - A << 0.165300 << 0.454037 << 0.995795 << 0.124098 << 0.047084 << endr - << 0.688782 << 0.036549 << 0.552848 << 0.937664 << 0.866401 << endr - << 0.348740 << 0.479388 << 0.506228 << 0.145673 << 0.491547 << endr - << 0.148678 << 0.682258 << 0.571154 << 0.874724 << 0.444632 << endr - << 0.245726 << 0.595218 << 0.409327 << 0.367827 << 0.385736 << endr; - - A.print("A ="); - - // determinant - cout << "det(A) = " << det(A) << endl; -!ec - -!split -===== Armadillo, simple examples ===== - -!bc cppcod - // inverse - cout << "inv(A) = " << endl << inv(A) << endl; - double k = 1.23; - - mat B = randu(5,5); - mat C = randu(5,5); - - rowvec r = randu(5); - colvec q = randu(5); - - - // examples of some expressions - // for which optimised implementations exist - // optimised implementation of a trinary expression - // that results in a scalar - cout << "as_scalar( r*inv(diagmat(B))*q ) = "; - cout << as_scalar( r*inv(diagmat(B))*q ) << endl; - - // example of an expression which is optimised - // as a call to the dgemm() function in BLAS: - cout << "k*trans(B)*C = " << endl << k*trans(B)*C; - - return 0; - -!ec - -!split -===== Gaussian Elimination ===== - -We start with the linear set of equations - -!bt -\[ - \mathbf{A}\mathbf{x} = \mathbf{w}. -\] -!et -We assume also that the matrix $\mathbf{A}$ is non-singular and that the -matrix elements along the diagonal satisfy $a_{ii} \ne 0$. Simple $4\times 4 $ example - -!bt -\[ -\begin{bmatrix} - a_{11}& a_{12} &a_{13}& a_{14}\\ - a_{21}& a_{22} &a_{23}& a_{24}\\ - a_{31}& a_{32} &a_{33}& a_{34}\\ - a_{41}& a_{42} &a_{43}& a_{44}\\ - \end{bmatrix} \begin{bmatrix} - x_1\\ - x_2\\ - x_3 \\ - x_4 \\ - \end{bmatrix} - =\begin{bmatrix} - w_1\\ - w_2\\ - w_3 \\ - w_4\\ - \end{bmatrix}. -\] -!et - -!split -===== Gaussian Elimination ===== -or - -!bt -\begin{align} - a_{11}x_1 +a_{12}x_2 +a_{13}x_3 + a_{14}x_4=&w_1 \nonumber \\ -a_{21}x_1 + a_{22}x_2 + a_{23}x_3 + a_{24}x_4=&w_2 \nonumber \\ -a_{31}x_1 + a_{32}x_2 + a_{33}x_3 + a_{34}x_4=&w_3 \nonumber \\ -a_{41}x_1 + a_{42}x_2 + a_{43}x_3 + a_{44}x_4=&w_4. \nonumber -\end{align} -!et - -!split -===== Gaussian Elimination ===== - -The basic idea of Gaussian elimination is to use the first equation to eliminate the first unknown $x_1$ -from the remaining $n-1$ equations. Then we use the new second equation to eliminate the second unknown -$x_2$ from the remaining $n-2$ equations. With $n-1$ such eliminations -we obtain a so-called upper triangular set of equations of the form - -!bt -\begin{align} - b_{11}x_1 +b_{12}x_2 +b_{13}x_3 + b_{14}x_4=&y_1 \nonumber \\ - b_{22}x_2 + b_{23}x_3 + b_{24}x_4=&y_2 \nonumber \\ -b_{33}x_3 + b_{34}x_4=&y_3 \nonumber \\ -b_{44}x_4=&y_4. \nonumber -label{eq:gaussbacksub} -\end{align} -!et -We can solve this system of equations recursively starting from $x_n$ (in our case $x_4$) and proceed with -what is called a backward substitution. - -!split -===== Gaussian Elimination ===== -This process can be expressed mathematically as - -!bt -\begin{equation} - x_m = \frac{1}{b_{mm}}\left(y_m-\sum_{k=m+1}^nb_{mk}x_k\right)\quad m=n-1,n-2,\dots,1. -\end{equation} -!et -To arrive at such an upper triangular system of equations, we start by eliminating -the unknown $x_1$ for $j=2,n$. We achieve this by multiplying the first equation by $a_{j1}/a_{11}$ and then subtract -the result from the $j$th equation. We assume obviously that $a_{11}\ne 0$ and that -$\mathbf{A}$ is not singular. - -!split -===== Gaussian Elimination ===== - -Our actual $4\times 4$ example reads after the first operation - -!bt -\[ -\begin{bmatrix} - a_{11}& a_{12} &a_{13}& a_{14}\\ - 0& (a_{22}-\frac{a_{21}a_{12}}{a_{11}}) &(a_{23}-\frac{a_{21}a_{13}}{a_{11}}) & (a_{24}-\frac{a_{21}a_{14}}{a_{11}})\\ -0& (a_{32}-\frac{a_{31}a_{12}}{a_{11}})& (a_{33}-\frac{a_{31}a_{13}}{a_{11}})& (a_{34}-\frac{a_{31}a_{14}}{a_{11}})\\ -0&(a_{42}-\frac{a_{41}a_{12}}{a_{11}}) &(a_{43}-\frac{a_{41}a_{13}}{a_{11}}) & (a_{44}-\frac{a_{41}a_{14}}{a_{11}}) \\ - \end{bmatrix} \begin{bmatrix} - x_1\\ - x_2\\ - x_3 \\ - x_4 \\ - \end{bmatrix} - =\begin{bmatrix} - y_1\\ - w_2^{(2)}\\ - w_3^{(2)} \\ - w_4^{(2)}\\ - \end{bmatrix}, -\] -!et -or - -!bt -\begin{align} - b_{11}x_1 +b_{12}x_2 +b_{13}x_3 + b_{14}x_4=&y_1 \nonumber \\ - a^{(2)}_{22}x_2 + a^{(2)}_{23}x_3 + a^{(2)}_{24}x_4=&w^{(2)}_2 \nonumber \\ - a^{(2)}_{32}x_2 + a^{(2)}_{33}x_3 + a^{(2)}_{34}x_4=&w^{(2)}_3 \nonumber \\ - a^{(2)}_{42}x_2 + a^{(2)}_{43}x_3 + a^{(2)}_{44}x_4=&w^{(2)}_4, \nonumber \\ -\end{align} -!et - -!split -===== Gaussian Elimination ===== - -The new coefficients are - -!bt -\begin{equation} - b_{1k} = a_{1k}^{(1)} \quad k=1,\dots,n, -\end{equation} -!et -where each $a_{1k}^{(1)}$ is equal to the original $a_{1k}$ element. The other coefficients are - -!bt -\begin{equation} -a_{jk}^{(2)} = a_{jk}^{(1)}-\frac{a_{j1}^{(1)}a_{1k}^{(1)}}{a_{11}^{(1)}} \quad j,k=2,\dots,n, -\end{equation} -!et -with a new right-hand side given by - -!bt -\begin{equation} -y_{1}=w_1^{(1)}, \quad w_j^{(2)} =w_j^{(1)}-\frac{a_{j1}^{(1)}w_1^{(1)}}{a_{11}^{(1)}} \quad j=2,\dots,n. -\end{equation} -!et -We have also set $w_1^{(1)}=w_1$, the original vector element. -We see that the system of unknowns $x_1,\dots,x_n$ is transformed into an $(n-1)\times (n-1)$ problem. - -!split -===== Gaussian Elimination ===== - -This step is called forward substitution. -Proceeding with these substitutions, we obtain the -general expressions for the new coefficients - -!bt -\begin{equation} - a_{jk}^{(m+1)} = a_{jk}^{(m)}-\frac{a_{jm}^{(m)}a_{mk}^{(m)}}{a_{mm}^{(m)}} \quad j,k=m+1,\dots,n, -\end{equation} -!et -with $m=1,\dots,n-1$ and a -right-hand side given by - -!bt -\begin{equation} - w_j^{(m+1)} =w_j^{(m)}-\frac{a_{jm}^{(m)}w_m^{(m)}}{a_{mm}^{(m)}}\quad j=m+1,\dots,n. -\end{equation} -!et -This set of $n-1$ elimations leads us to an equations which is solved by back substitution. -If the arithmetics is exact and the matrix $\mathbf{A}$ is not singular, then the computed answer will be exact. - -Even though the matrix elements along the diagonal are not zero, -numerically small numbers may appear and subsequent divisions may lead to large numbers, which, if added -to a small number may yield losses of precision. Suppose for example that our first division in $(a_{22}-a_{21}a_{12}/a_{11})$ -results in $-10^{-7}$ and that $a_{22}$ is one. -one. We are then -adding $10^7+1$. With single precision this results in $10^7$. - - - -!split -===== Linear Algebra Methods ===== - - * Gaussian elimination, $O(2/3n^3)$ flops, general matrix - * LU decomposition, upper triangular and lower tridiagonal matrices, $O(2/3n^3)$ flops, general matrix. Get easily the inverse, determinant and can solve linear equations with back-substitution only, $O(n^2)$ flops - * Cholesky decomposition. Real symmetric or hermitian positive definite matrix, $O(1/3n^3)$ flops. - * Tridiagonal linear systems, important for differential equations. Normally positive definite and non-singular. $O(8n)$ flops for symmetric. Special case of banded matrices. - * Singular value decomposition - * the QR method will be discussed in chapter 7 in connection with eigenvalue systems. $O(4/3n^3)$ flops. - -!split -===== LU Decomposition ===== - -The LU decomposition method means that we can rewrite -this matrix as the product of two matrices $\mathbf{L}$ and $\mathbf{U}$ -where - -!bt -\[ - \begin{bmatrix} - a_{11} & a_{12} & a_{13} & a_{14} \\ - a_{21} & a_{22} & a_{23} & a_{24} \\ - a_{31} & a_{32} & a_{33} & a_{34} \\ - a_{41} & a_{42} & a_{43} & a_{44} - \end{bmatrix} - = \begin{bmatrix} - 1 & 0 & 0 & 0 \\ - l_{21} & 1 & 0 & 0 \\ - l_{31} & l_{32} & 1 & 0 \\ - l_{41} & l_{42} & l_{43} & 1 - \end{bmatrix} - \begin{bmatrix} - u_{11} & u_{12} & u_{13} & u_{14} \\ - 0 & u_{22} & u_{23} & u_{24} \\ - 0 & 0 & u_{33} & u_{34} \\ - 0 & 0 & 0 & u_{44} - \end{bmatrix}. -\] -!et - -!split -===== LU Decomposition ===== - -LU decomposition forms the backbone of other algorithms in linear algebra, such as the -solution of linear equations given by - -!bt -\begin{align} - a_{11}x_1 +a_{12}x_2 +a_{13}x_3 + a_{14}x_4=&w_1 \nonumber \\ -a_{21}x_1 + a_{22}x_2 + a_{23}x_3 + a_{24}x_4=&w_2 \nonumber \\ -a_{31}x_1 + a_{32}x_2 + a_{33}x_3 + a_{34}x_4=&w_3 \nonumber \\ -a_{41}x_1 + a_{42}x_2 + a_{43}x_3 + a_{44}x_4=&w_4. \nonumber -\end{align} -!et -The above set of equations is conveniently solved by using LU decomposition as an intermediate step. - -The matrix $\mathbf{A}\in \mathbb{R}^{n\times n}$ has an LU factorization if the determinant -is different from zero. If the LU factorization exists and $\mathbf{A}$ is non-singular, then the LU factorization -is unique and the determinant is given by - -!bt -\[ -det\{\mathbf{A}\}=det\{\mathbf{LU}\}= det\{\mathbf{L}\}det\{\mathbf{U}\}=u_{11}u_{22}\dots u_{nn}. -\] -!et - -!split -===== LU Decomposition, why? ===== - -There are at least three main advantages with LU decomposition compared with standard Gaussian elimination: - - * It is straightforward to compute the determinant of a matrix - * If we have to solve sets of linear equations with the same matrix but with different vectors $\mathbf{y}$, the number of FLOPS is of the order $n^3$. - * The inverse is such an operation - -!split -===== LU Decomposition, linear equations ===== - -With the LU decomposition it is rather -simple to solve a system of linear equations - -!bt -\begin{align} - a_{11}x_1 +a_{12}x_2 +a_{13}x_3 + a_{14}x_4=&w_1 \nonumber \\ -a_{21}x_1 + a_{22}x_2 + a_{23}x_3 + a_{24}x_4=&w_2 \nonumber \\ -a_{31}x_1 + a_{32}x_2 + a_{33}x_3 + a_{34}x_4=&w_3 \nonumber \\ -a_{41}x_1 + a_{42}x_2 + a_{43}x_3 + a_{44}x_4=&w_4. \nonumber -\end{align} -!et - -This can be written in matrix form as - -!bt -\[ \mathbf{Ax}=\mathbf{w}. \] -!et - -where $\mathbf{A}$ and $\mathbf{w}$ are known and we have to solve for -$\mathbf{x}$. Using the LU dcomposition we write - -!bt -\[ \mathbf{A} \mathbf{x} \equiv \mathbf{L} \mathbf{U} \mathbf{x} =\mathbf{w}. \] -!et - -!split -===== LU Decomposition, linear equations ===== - -The previous equation can be calculated in two steps - -!bt -\[ \mathbf{L} \mathbf{y} = \mathbf{w};\qquad \mathbf{Ux}=\mathbf{y}. \] -!et - -To show that this is correct we use to the LU decomposition -to rewrite our system of linear equations as - -!bt -\[ \mathbf{LUx}=\mathbf{w}, \] -!et -and since the determinant of $\mathbf{L}$ is equal to 1 (by construction -since the diagonals of $\mathbf{L}$ equal 1) we can use the inverse of -$\mathbf{L}$ to obtain - -!bt -\[ - \mathbf{Ux}=\mathbf{L^{-1}w}=\mathbf{y}, -\] -!et -which yields the intermediate step - -!bt -\[ - \mathbf{L^{-1}w}=\mathbf{y} -\] -!et -and as soon as we have $\mathbf{y}$ we can obtain $\mathbf{x}$ -through $\mathbf{Ux}=\mathbf{y}$. - -!split -===== LU Decomposition, why? ===== - -For our four-dimentional example this takes the form - -!bt -\begin{align} - y_1=&w_1 \nonumber\\ -l_{21}y_1 + y_2=&w_2\nonumber \\ -l_{31}y_1 + l_{32}y_2 + y_3 =&w_3\nonumber \\ -l_{41}y_1 + l_{42}y_2 + l_{43}y_3 + y_4=&w_4. \nonumber -\end{align} -!et - -and - -!bt -\begin{align} - u_{11}x_1 +u_{12}x_2 +u_{13}x_3 + u_{14}x_4=&y_1 \nonumber\\ -u_{22}x_2 + u_{23}x_3 + u_{24}x_4=&y_2\nonumber \\ -u_{33}x_3 + u_{34}x_4=&y_3\nonumber \\ -u_{44}x_4=&y_4 \nonumber -\end{align} -!et - -This example shows the basis for the algorithm -needed to solve the set of $n$ linear equations. - -!split -===== LU Decomposition, linear equations ===== - -The algorithm goes as follows - - * Set up the matrix $\bf A$ and the vector $\bf w$ with their correct dimensions. This determines the dimensionality of the unknown vector $\bf x$. - * Then LU decompose the matrix $\bf A$ through a call to the function `ludcmp(double a, int n, int indx, double &d)`. This functions returns the LU decomposed matrix $\bf A$, its determinant and the vector indx which keeps track of the number of interchanges of rows. If the determinant is zero, the solution is malconditioned. - * Thereafter you call the function `lubksb(double a, int n, int indx, double w)` which uses the LU decomposed matrix $\bf A$ and the vector $\bf w$ and returns $\bf x$ in the same place as $\bf w$. Upon exit the original content in $\bf w$ is destroyed. If you wish to keep this information, you should make a backup of it in your calling function. - -!split -===== LU Decomposition, the inverse of a matrix ===== - -If the inverse exists then - -!bt -\[ - \mathbf{A}^{-1}\mathbf{A}=\mathbf{I}, -\] -!et -the identity matrix. With an LU decomposed matrix we can rewrite the last equation as - -!bt -\[ - \mathbf{LU}\mathbf{A}^{-1}=\mathbf{I}. -\] -!et - -!split -===== LU Decomposition, the inverse of a matrix ===== - -If we assume that the first column (that is column 1) of the inverse matrix -can be written as a vector with unknown entries - -!bt -\[ - \mathbf{A}_1^{-1}= \begin{bmatrix} - - a_{11}^{-1} \\ - a_{21}^{-1} \\ - \dots \\ - a_{n1}^{-1} \\ - \end{bmatrix}, -\] -!et -then we have a linear set of equations - -!bt -\[ - \mathbf{LU}\begin{bmatrix} - - a_{11}^{-1} \\ - a_{21}^{-1} \\ - \dots \\ - a_{n1}^{-1} \\ - \end{bmatrix} =\begin{bmatrix} - 1 \\ - 0 \\ - \dots \\ - 0 \\ - \end{bmatrix}. -\] -!et - -!split -===== LU Decomposition, the inverse ===== - -In a similar way we can compute the unknow entries of the second column, - -!bt -\[ - \mathbf{LU}\begin{bmatrix} - - a_{12}^{-1} \\ - a_{22}^{-1} \\ - \dots \\ - a_{n2}^{-1} \\ - \end{bmatrix}=\begin{bmatrix} - 0 \\ - 1 \\ - \dots \\ - 0 \\ - \end{bmatrix}, -\] -!et -and continue till we have solved all $n$ sets of linear equations. - - -!split -===== "Using Armadillo to perform an LU decomposition":"https://github.com/CompPhysics/ComputationalPhysicsMSU/blob/master/doc/Programs/CppQtCodesLectures/MatrixTest/main.cpp" ===== -!bc cppcod -#include -#include "armadillo" -using namespace arma; -using namespace std; - -int main() - { - mat A = randu(5,5); - vec b = randu(5); - - A.print("A ="); - b.print("b="); - // solve Ax = b - vec x = solve(A,b); - // print x - x.print("x="); - // find LU decomp of A, if needed, P is the permutation matrix - mat L, U; - lu(L,U,A); - // print l - L.print(" L= "); - // print U - U.print(" U= "); - //Check that A = LU - (A-L*U).print("Test of LU decomposition"); - return 0; - } -!ec - - -======= Review of Statistics ======= - - -===== Domains and probabilities ===== - -Consider the following simple example, namely the tossing of two dice, resulting in the following possible values -!bt -\begin{equation*} -\{2,3,4,5,6,7,8,9,10,11,12\}. -\end{equation*} -!et -These values are called the *domain*. -To this domain we have the corresponding *probabilities* -!bt -\begin{equation*} -\{1/36,2/36/,3/36,4/36,5/36,6/36,5/36,4/36,3/36,2/36,1/36\}. -\end{equation*} -!et - - - -===== Tossing the dice ===== - -The numbers in the domain are the outcomes of the physical process of tossing say two dice. -We cannot tell beforehand whether the outcome is 3 or 5 or any other number in this domain. -This defines the randomness of the outcome, or unexpectedness or any other synonimous word which -encompasses the uncertitude of the final outcome. - -The only thing we can tell beforehand -is that say the outcome 2 has a certain probability. -If our favorite hobby is to spend an hour every evening throwing dice and -registering the sequence of outcomes, we will note that the numbers in the above domain -!bt -\begin{equation*} -\{2,3,4,5,6,7,8,9,10,11,12\}, -\end{equation*} -!et -appear in a random order. After 11 throws the results may look like - -!bt -\begin{equation*} -\{10,8,6,3,6,9,11,8,12,4,5\}. -\end{equation*} -!et - - - -===== Stochastic variables ===== - - -_Random variables are characterized by a domain which contains all possible values that the random value may take. This domain has a corresponding probability distribution function(PDF)_. - - - -===== Stochastic variables and the main concepts, the discrete case ===== - -There are two main concepts associated with a stochastic variable. The -*domain* is the set $\mathbb D = \{x\}$ of all accessible values -the variable can assume, so that $X \in \mathbb D$. An example of a -discrete domain is the set of six different numbers that we may get by -throwing of a dice, $x\in\{1,\,2,\,3,\,4,\,5,\,6\}$. - -The *probability distribution function (PDF)* is a function -$p(x)$ on the domain which, in the discrete case, gives us the -probability or relative frequency with which these values of $X$ -occur -!bt -\begin{equation*} -p(x) = \mathrm{Prob}(X=x). -\end{equation*} -!et - - - - -===== Stochastic variables and the main concepts, the continuous case ===== - -In the continuous case, the PDF does not directly depict the -actual probability. Instead we define the probability for the -stochastic variable to assume any value on an infinitesimal interval -around $x$ to be $p(x)dx$. The continuous function $p(x)$ then gives us -the *density* of the probability rather than the probability -itself. The probability for a stochastic variable to assume any value -on a non-infinitesimal interval $[a,\,b]$ is then just the integral - -!bt -\begin{equation*} -\mathrm{Prob}(a\leq X\leq b) = \int_a^b p(x)dx. -\end{equation*} -!et -Qualitatively speaking, a stochastic variable represents the values of -numbers chosen as if by chance from some specified PDF so that the -selection of a large set of these numbers reproduces this PDF. - - - -===== The cumulative probability ===== - -Of interest to us is the *cumulative probability -distribution function* (_CDF_), $P(x)$, which is just the probability -for a stochastic variable $X$ to assume any value less than $x$ -!bt -\begin{equation*} -P(x)=\mathrm{Prob(}X\leq x\mathrm{)} = -\int_{-\infty}^x p(x^{\prime})dx^{\prime}. -\end{equation*} -!et -The relation between a CDF and its corresponding PDF is then - -!bt -\begin{equation*} -p(x) = \frac{d}{dx}P(x). -\end{equation*} -!et - - - -===== Properties of PDFs ===== - - -There are two properties that all PDFs must satisfy. The first one is -positivity (assuming that the PDF is normalized) - -!bt -\begin{equation*} -0 \leq p(x) \leq 1. -\end{equation*} -!et -Naturally, it would be nonsensical for any of the values of the domain -to occur with a probability greater than $1$ or less than $0$. Also, -the PDF must be normalized. That is, all the probabilities must add up -to unity. The probability of ``anything'' to happen is always unity. For -both discrete and continuous PDFs, this condition is -!bt -\begin{align*} -\sum_{x_i\in\mathbb D} p(x_i) & = 1,\\ -\int_{x\in\mathbb D} p(x)\,dx & = 1. -\end{align*} -!et - - - -===== Important distributions, the uniform distribution ===== - -The first one -is the most basic PDF; namely the uniform distribution -!bt -\begin{equation} -p(x) = \frac{1}{b-a}\theta(x-a)\theta(b-x). -label{eq:unifromPDF} -\end{equation} -!et -For $a=0$ and $b=1$ we have -!bt -\[ -\begin{array}{ll} -p(x)dx = dx & \in [0,1]. -\end{array} -\] -!et -The latter distribution is used to generate random numbers. For other PDFs, one needs normally a mapping from this distribution to say for example the exponential distribution. - - - -===== Gaussian distribution ===== - -The second one is the Gaussian Distribution -!bt -\begin{equation*} -p(x) = \frac{1}{\sigma\sqrt{2\pi}} \exp{(-\frac{(x-\mu)^2}{2\sigma^2})}, -\end{equation*} -!et -with mean value $\mu$ and standard deviation $\sigma$. If $\mu=0$ and $\sigma=1$, it is normally called the _standard normal distribution_ -!bt -\begin{equation*} -p(x) = \frac{1}{\sqrt{2\pi}} \exp{(-\frac{x^2}{2})}, -\end{equation*} -!et - -The following simple Python code plots the above distribution for different values of $\mu$ and $\sigma$. -!bc pyscpro -import numpy as np -from math import acos, exp, sqrt -from matplotlib import pyplot as plt -from matplotlib import rc, rcParams -import matplotlib.units as units -import matplotlib.ticker as ticker -rc('text',usetex=True) -rc('font',**{'family':'serif','serif':['Gaussian distribution']}) -font = {'family' : 'serif', - 'color' : 'darkred', - 'weight' : 'normal', - 'size' : 16, - } -pi = acos(-1.0) -mu0 = 0.0 -sigma0 = 1.0 -mu1= 1.0 -sigma1 = 2.0 -mu2 = 2.0 -sigma2 = 4.0 - -x = np.linspace(-20.0, 20.0) -v0 = np.exp(-(x*x-2*x*mu0+mu0*mu0)/(2*sigma0*sigma0))/sqrt(2*pi*sigma0*sigma0) -v1 = np.exp(-(x*x-2*x*mu1+mu1*mu1)/(2*sigma1*sigma1))/sqrt(2*pi*sigma1*sigma1) -v2 = np.exp(-(x*x-2*x*mu2+mu2*mu2)/(2*sigma2*sigma2))/sqrt(2*pi*sigma2*sigma2) -plt.plot(x, v0, 'b-', x, v1, 'r-', x, v2, 'g-') -plt.title(r'{\bf Gaussian distributions}', fontsize=20) -plt.text(-19, 0.3, r'Parameters: $\mu = 0$, $\sigma = 1$', fontdict=font) -plt.text(-19, 0.18, r'Parameters: $\mu = 1$, $\sigma = 2$', fontdict=font) -plt.text(-19, 0.08, r'Parameters: $\mu = 2$, $\sigma = 4$', fontdict=font) -plt.xlabel(r'$x$',fontsize=20) -plt.ylabel(r'$p(x)$ [MeV]',fontsize=20) - -# Tweak spacing to prevent clipping of ylabel -plt.subplots_adjust(left=0.15) -plt.savefig('gaussian.pdf', format='pdf') -plt.show() -!ec - - - - -===== Exponential distribution ===== - -Another important distribution in science is the exponential distribution -!bt -\begin{equation*} -p(x) = \alpha\exp{-(\alpha x)}. -\end{equation*} -!et - - - -===== Expectation values ===== - -Let $h(x)$ be an arbitrary continuous function on the domain of the stochastic -variable $X$ whose PDF is $p(x)$. We define the *expectation value* -of $h$ with respect to $p$ as follows - -!bt -\begin{equation} -\langle h \rangle_X \equiv \int\! h(x)p(x)\,dx -label{eq:expectation_value_of_h_wrt_p} -\end{equation} -!et -Whenever the PDF is known implicitly, like in this case, we will drop -the index $X$ for clarity. -A particularly useful class of special expectation values are the -*moments*. The $n$-th moment of the PDF $p$ is defined as -follows -!bt -\begin{equation*} -\langle x^n \rangle \equiv \int\! x^n p(x)\,dx -\end{equation*} -!et - - - -===== Stochastic variables and the main concepts, mean values ===== - -The zero-th moment $\langle 1\rangle$ is just the normalization condition of -$p$. The first moment, $\langle x\rangle$, is called the *mean* of $p$ -and often denoted by the letter $\mu$ -!bt -\begin{equation*} -\langle x\rangle = \mu \equiv \int x p(x)dx, -\end{equation*} -!et -for a continuous distribution and -!bt -\begin{equation*} -\langle x\rangle = \mu \equiv \sum_{i=1}^N x_i p(x_i), -\end{equation*} -!et -for a discrete distribution. -Qualitatively it represents the centroid or the average value of the -PDF and is therefore simply called the expectation value of $p(x)$. - - - -===== Stochastic variables and the main concepts, central moments, the variance ===== - - -A special version of the moments is the set of *central moments*, the n-th central moment defined as -!bt -\begin{equation*} -\langle (x-\langle x\rangle )^n\rangle \equiv \int\! (x-\langle x\rangle)^n p(x)\,dx -\end{equation*} -!et -The zero-th and first central moments are both trivial, equal $1$ and -$0$, respectively. But the second central moment, known as the -*variance* of $p$, is of particular interest. For the stochastic -variable $X$, the variance is denoted as $\sigma^2_X$ or $\mathrm{Var}(X)$ -!bt -\begin{align*} -\sigma^2_X &=\mathrm{Var}(X) = \langle (x-\langle x\rangle)^2\rangle = -\int (x-\langle x\rangle)^2 p(x)dx\\ -& = \int\left(x^2 - 2 x \langle x\rangle^{2} +\langle x\rangle^2\right)p(x)dx\\ -& = \langle x^2\rangle - 2 \langle x\rangle\langle x\rangle + \langle x\rangle^2\\ -& = \langle x^2 \rangle - \langle x\rangle^2 -\end{align*} -!et -The square root of the variance, $\sigma =\sqrt{\langle (x-\langle x\rangle)^2\rangle}$ is called the -_standard deviation_ of $p$. It is the RMS (root-mean-square) -value of the deviation of the PDF from its mean value, interpreted -qualitatively as the ``spread'' of $p$ around its mean. - - - - - -===== Probability Distribution Functions ===== - - -The following table collects properties of probability distribution functions. -In our notation we reserve the label $p(x)$ for the probability of a certain event, -while $P(x)$ is the cumulative probability. - - -|--------------------------------------------------------------------------------------------------------------------------------------| -| | Discrete PDF | Continuous PDF | -|---------------------l-------------------------------------------c-------------------------------------------c------------------------| -| Domain | $\left\{x_1, x_2, x_3, \dots, x_N\right\}$ | $[a,b]$ | -| Probability | $p(x_i)$ | $p(x)dx$ | -| Cumulative | $P_i=\sum_{l=1}^ip(x_l)$ | $P(x)=\int_a^xp(t)dt$ | -| Positivity | $0 \le p(x_i) \le 1$ | $p(x) \ge 0$ | -| Positivity | $0 \le P_i \le 1$ | $0 \le P(x) \le 1$ | -| Monotonic | $P_i \ge P_j$ if $x_i \ge x_j$ | $P(x_i) \ge P(x_j)$ if $x_i \ge x_j$ | -| Normalization | $P_N=1$ | $P(b)=1$ | -|--------------------------------------------------------------------------------------------------------------------------------------| - - - - - -===== Probability Distribution Functions ===== - -With a PDF we can compute expectation values of selected quantities such as - -!bt -\begin{equation*} - \langle x^k\rangle=\sum_{i=1}^{N}x_i^kp(x_i), -\end{equation*} -!et -if we have a discrete PDF or - -!bt -\begin{equation*} - \langle x^k\rangle=\int_a^b x^kp(x)dx, -\end{equation*} -!et -in the case of a continuous PDF. We have already defined the mean value $\mu$ -and the variance $\sigma^2$. - - - -===== The three famous Probability Distribution Functions ===== - - -There are at least three PDFs which one may encounter. These are the - -_Uniform distribution_ -!bt -\begin{equation*} -p(x)=\frac{1}{b-a}\Theta(x-a)\Theta(b-x), -\end{equation*} -!et -yielding probabilities different from zero in the interval $[a,b]$. - -_The exponential distribution_ -!bt -\begin{equation*} -p(x)=\alpha \exp{(-\alpha x)}, -\end{equation*} -!et -yielding probabilities different from zero in the interval $[0,\infty)$ and with mean value -!bt -\begin{equation*} -\mu = \int_0^{\infty}xp(x)dx=\int_0^{\infty}x\alpha \exp{(-\alpha x)}dx=\frac{1}{\alpha}, -\end{equation*} -!et - -with variance -!bt -\begin{equation*} -\sigma^2=\int_0^{\infty}x^2p(x)dx-\mu^2 = \frac{1}{\alpha^2}. -\end{equation*} -!et - - -===== Probability Distribution Functions, the normal distribution ===== - -Finally, we have the so-called univariate normal distribution, or just the _normal distribution_ -!bt -\begin{equation*} -p(x)=\frac{1}{b\sqrt{2\pi}}\exp{\left(-\frac{(x-a)^2}{2b^2}\right)} -\end{equation*} -!et -with probabilities different from zero in the interval $(-\infty,\infty)$. -The integral $\int_{-\infty}^{\infty}\exp{\left(-(x^2\right)}dx$ appears in many calculations, its value -is $\sqrt{\pi}$, a result we will need when we compute the mean value and the variance. -The mean value is -!bt -\begin{equation*} - \mu = \int_0^{\infty}xp(x)dx=\frac{1}{b\sqrt{2\pi}}\int_{-\infty}^{\infty}x \exp{\left(-\frac{(x-a)^2}{2b^2}\right)}dx, -\end{equation*} -!et -which becomes with a suitable change of variables -!bt -\begin{equation*} - \mu =\frac{1}{b\sqrt{2\pi}}\int_{-\infty}^{\infty}b\sqrt{2}(a+b\sqrt{2}y)\exp{-y^2}dy=a. -\end{equation*} -!et - - - -===== Probability Distribution Functions, the normal distribution ===== - -Similarly, the variance becomes -!bt -\begin{equation*} - \sigma^2 = \frac{1}{b\sqrt{2\pi}}\int_{-\infty}^{\infty}(x-\mu)^2 \exp{\left(-\frac{(x-a)^2}{2b^2}\right)}dx, -\end{equation*} -!et -and inserting the mean value and performing a variable change we obtain - -!bt -\begin{equation*} - \sigma^2 = \frac{1}{b\sqrt{2\pi}}\int_{-\infty}^{\infty}b\sqrt{2}(b\sqrt{2}y)^2\exp{\left(-y^2\right)}dy= -\frac{2b^2}{\sqrt{\pi}}\int_{-\infty}^{\infty}y^2\exp{\left(-y^2\right)}dy, -\end{equation*} -!et -and performing a final integration by parts we obtain the well-known result $\sigma^2=b^2$. -It is useful to introduce the standard normal distribution as well, defined by $\mu=a=0$, viz. a distribution -centered around zero and with a variance $\sigma^2=1$, leading to - -!bt -\begin{equation} - p(x)=\frac{1}{\sqrt{2\pi}}\exp{\left(-\frac{x^2}{2}\right)}. -\end{equation} -!et - - - -===== Probability Distribution Functions, the cumulative distribution ===== - - -The exponential and uniform distributions have simple cumulative functions, -whereas the normal distribution does not, being proportional to the so-called -error function $erf(x)$, given by - -!bt -\begin{equation*} -P(x) = \frac{1}{\sqrt{2\pi}}\int_{-\infty}^x\exp{\left(-\frac{t^2}{2}\right)}dt, -\end{equation*} -!et -which is difficult to evaluate in a quick way. - - - - -===== Probability Distribution Functions, other important distribution ===== - - -Some other PDFs which one encounters often in the natural sciences are the binomial distribution -!bt -\begin{equation*} - p(x) = \left(\begin{array}{c} n \\ x\end{array}\right)y^x(1-y)^{n-x} \hspace{0.5cm}x=0,1,\dots,n, -\end{equation*} -!et -where $y$ is the probability for a specific event, such as the tossing of a coin or moving left or right -in case of a random walker. Note that $x$ is a discrete stochastic variable. - -The sequence of binomial trials is characterized by the following definitions - - * Every experiment is thought to consist of $N$ independent trials. - - * In every independent trial one registers if a specific situation happens or not, such as the jump to the left or right of a random walker. - - * The probability for every outcome in a single trial has the same value, for example the outcome of tossing (either heads or tails) a coin is always $1/2$. - - - -===== Probability Distribution Functions, the binomial distribution ===== - - -In order to compute the mean and variance we need to recall Newton's binomial -formula -!bt -\begin{equation*} - (a+b)^m=\sum_{n=0}^m \left(\begin{array}{c} m \\ n\end{array}\right)a^nb^{m-n}, -\end{equation*} -!et -which can be used to show that - -!bt -\begin{equation*} -\sum_{x=0}^n\left(\begin{array}{c} n \\ x\end{array}\right)y^x(1-y)^{n-x} = (y+1-y)^n = 1, -\end{equation*} -!et -the PDF is normalized to one. -The mean value is -!bt -\begin{equation*} -\mu = \sum_{x=0}^n x\left(\begin{array}{c} n \\ x\end{array}\right)y^x(1-y)^{n-x} = -\sum_{x=0}^n x\frac{n!}{x!(n-x)!}y^x(1-y)^{n-x}, -\end{equation*} -!et -resulting in -!bt -\begin{equation*} -\mu = -\sum_{x=0}^n x\frac{(n-1)!}{(x-1)!(n-1-(x-1))!}y^{x-1}(1-y)^{n-1-(x-1)}, -\end{equation*} -!et -which we rewrite as - -!bt -\begin{equation*} -\mu=ny\sum_{\nu=0}^n\left(\begin{array}{c} n-1 \\ \nu\end{array}\right)y^{\nu}(1-y)^{n-1-\nu} =ny(y+1-y)^{n-1}=ny. -\end{equation*} -!et - -The variance is slightly trickier to get. It reads $\sigma^2=ny(1-y)$. - - -===== Probability Distribution Functions, Poisson's distribution ===== - - -Another important distribution with discrete stochastic variables $x$ is -the Poisson model, which resembles the exponential distribution and reads -!bt -\begin{equation*} - p(x) = \frac{\lambda^x}{x!} e^{-\lambda} \hspace{0.5cm}x=0,1,\dots,;\lambda > 0. -\end{equation*} -!et -In this case both the mean value and the variance are easier to calculate, - -!bt -\begin{equation*} -\mu = \sum_{x=0}^{\infty} x \frac{\lambda^x}{x!} e^{-\lambda} = \lambda e^{-\lambda}\sum_{x=1}^{\infty} -\frac{\lambda^{x-1}}{(x-1)!}=\lambda, -\end{equation*} -!et -and the variance is $\sigma^2=\lambda$. - - - - - -===== Probability Distribution Functions, Poisson's distribution ===== - -An example of applications of the Poisson distribution could be the counting -of the number of $\alpha$-particles emitted from a radioactive source in a given time interval. -In the limit of $n\rightarrow \infty$ and for small probabilities $y$, the binomial distribution -approaches the Poisson distribution. Setting $\lambda = ny$, with $y$ the probability for an event in -the binomial distribution we can show that - -!bt -\begin{equation*} -\lim_{n\rightarrow \infty}\left(\begin{array}{c} n \\ x\end{array}\right)y^x(1-y)^{n-x} e^{-\lambda}=\sum_{x=1}^{\infty}\frac{\lambda^x}{x!} e^{-\lambda}. -\end{equation*} -!et - - - - -===== Meet the covariance! ===== - -An important quantity in a statistical analysis is the so-called covariance. - -Consider the set $\{X_i\}$ of $n$ -stochastic variables (not necessarily uncorrelated) with the -multivariate PDF $P(x_1,\dots,x_n)$. The *covariance* of two -of the stochastic variables, $X_i$ and $X_j$, is defined as follows - -!bt -\begin{align} -\mathrm{Cov}(X_i,\,X_j) & = \langle (x_i-\langle x_i\rangle)(x_j-\langle x_j\rangle)\rangle \\ -&=\int\cdots\int (x_i-\langle x_i\rangle)(x_j-\langle x_j\rangle)P(x_1,\dots,x_n)\,dx_1\dots dx_n, -label{eq:def_covariance} -\end{align} -!et -with -!bt -\begin{equation*} -\langle x_i\rangle = -\int\cdots\int x_i P(x_1,\dots,x_n)\,dx_1\dots dx_n. -\end{equation*} -!et - - - - - -===== Meet the covariance in matrix disguise ===== - -If we consider the above covariance as a matrix -!bt -\[ -C_{ij} =\mathrm{Cov}(X_i,\,X_j), -\] -!et -then the diagonal elements are just the familiar -variances, $C_{ii} = \mathrm{Cov}(X_i,\,X_i) = \mathrm{Var}(X_i)$. It turns out that -all the off-diagonal elements are zero if the stochastic variables are -uncorrelated. - - - -===== Covariance ===== -!bc pycod -# Importing various packages -from math import exp, sqrt -from random import random, seed -import numpy as np -import matplotlib.pyplot as plt - -def covariance(x, y, n): - sum = 0.0 - mean_x = np.mean(x) - mean_y = np.mean(y) - for i in range(0, n): - sum += (x[(i)]-mean_x)*(y[i]-mean_y) - return sum/n - -n = 10 - -x=np.random.normal(size=n) -y = 4+3*x+np.random.normal(size=n) -covxy = covariance(x,y,n) -print(covxy) -z = np.vstack((x, y)) -c = np.cov(z.T) - -print(c) - -!ec - - - - -===== Meet the covariance, uncorrelated events ===== - - -Consider the stochastic variables $X_i$ and $X_j$, ($i\neq j$). We have -!bt -\begin{align*} -Cov(X_i,\,X_j) &= \langle (x_i-\langle x_i\rangle)(x_j-\langle x_j\rangle)\rangle\\ -&=\langle x_i x_j - x_i\langle x_j\rangle - \langle x_i\rangle x_j + \langle x_i\rangle\langle x_j\rangle\rangle\\ -&=\langle x_i x_j\rangle - \langle x_i\langle x_j\rangle\rangle - \langle \langle x_i\rangle x_j \rangle + -\langle \langle x_i\rangle\langle x_j\rangle\rangle \\ -&=\langle x_i x_j\rangle - \langle x_i\rangle\langle x_j\rangle - \langle x_i\rangle\langle x_j\rangle + -\langle x_i\rangle\langle x_j\rangle \\ -&=\langle x_i x_j\rangle - \langle x_i\rangle\langle x_j\rangle -\end{align*} -!et -If $X_i$ and $X_j$ are independent (assuming $i \neq j$), we have that -!bt -\[ -\langle x_i x_j\rangle = \langle x_i\rangle\langle x_j\rangle, -\] -!et -leading to -!bt -\[ -Cov(X_i, X_j) = 0 \hspace{0.1cm} (i\neq j). -\] -!et - - - - - -===== Numerical experiments and the covariance ===== - - -Now that we have constructed an idealized mathematical framework, let -us try to apply it to empirical observations. Examples of relevant -physical phenomena may be spontaneous decays of nuclei, or a purely -mathematical set of numbers produced by some deterministic -mechanism. It is the latter we will deal with, using so-called pseudo-random -number generators. In general our observations will contain only a limited set of -observables. We remind the reader that -a *stochastic process* is a process that produces sequentially a -chain of values -!bt -\begin{equation*} -\{x_1, x_2,\dots\,x_k,\dots\}. -\end{equation*} -!et - - - - -===== Numerical experiments and the covariance ===== - -We will call these -values our *measurements* and the entire set as our measured -*sample*. The action of measuring all the elements of a sample -we will call a stochastic *experiment* (since, operationally, -they are often associated with results of empirical observation of -some physical or mathematical phenomena; precisely an experiment). We -assume that these values are distributed according to some -PDF $p_X^{\phantom X}(x)$, where $X$ is just the formal symbol for the -stochastic variable whose PDF is $p_X^{\phantom X}(x)$. Instead of -trying to determine the full distribution $p$ we are often only -interested in finding the few lowest moments, like the mean -$\mu_X^{\phantom X}$ and the variance $\sigma_X^{\phantom X}$. - - - - -===== Numerical experiments and the covariance, actual situations ===== - -In practical situations however, a sample is always of finite size. Let that -size be $n$. The expectation value of a sample $\alpha$, the _sample mean_, is then defined as follows -!bt -\begin{equation*} -\langle x_{\alpha} \rangle \equiv \frac{1}{n}\sum_{k=1}^n x_{\alpha,k}. -\end{equation*} -!et -The *sample variance* is: -!bt -\begin{equation*} -\mathrm{Var}(x) \equiv \frac{1}{n}\sum_{k=1}^n (x_{\alpha,k} - \langle x_{\alpha} \rangle)^2, -\end{equation*} -!et -with its square root being the *standard deviation of the sample*. - - - - -===== Numerical experiments and the covariance, our observables ===== - -You can think of the above observables as a set of quantities which define -a given experiment. This experiment is then repeated several times, say $m$ times. -The total average is then -!bt -\begin{equation} -\langle X_m \rangle= \frac{1}{m}\sum_{\alpha=1}^mx_{\alpha}=\frac{1}{mn}\sum_{\alpha, k} x_{\alpha,k}, -label{eq:exptmean} -\end{equation} -!et -where the last sums end at $m$ and $n$. -The total variance is -!bt -\begin{equation*} -\sigma^2_m= \frac{1}{mn^2}\sum_{\alpha=1}^m(\langle x_{\alpha} \rangle-\langle X_m \rangle)^2, -\end{equation*} -!et -which we rewrite as -!bt -\begin{equation} -\sigma^2_m=\frac{1}{m}\sum_{\alpha=1}^m\sum_{kl=1}^n (x_{\alpha,k}-\langle X_m \rangle)(x_{\alpha,l}-\langle X_m \rangle). -label{eq:exptvariance} -\end{equation} -!et - - - -===== Numerical experiments and the covariance, the sample variance ===== - - -We define also the sample variance $\sigma^2$ of all $mn$ individual experiments as -!bt -\begin{equation} -\sigma^2=\frac{1}{mn}\sum_{\alpha=1}^m\sum_{k=1}^n (x_{\alpha,k}-\langle X_m \rangle)^2. -label{eq:sampleexptvariance} -\end{equation} -!et - - - -These quantities, being known experimental values or the results from our calculations, -may differ, in some cases -significantly, from the similarly named -exact values for the mean value $\mu_X$, the variance $\mathrm{Var}(X)$ -and the covariance $\mathrm{Cov}(X,Y)$. - - - -===== Numerical experiments and the covariance, central limit theorem ===== - - -The central limit theorem states that the PDF $\tilde{p}(z)$ of -the average of $m$ random values corresponding to a PDF $p(x)$ -is a normal distribution whose mean is the -mean value of the PDF $p(x)$ and whose variance is the variance -of the PDF $p(x)$ divided by $m$, the number of values used to compute $z$. - -The central limit theorem leads then to the well-known expression for the -standard deviation, given by -!bt -\begin{equation*} - \sigma_m= -\frac{\sigma}{\sqrt{m}}. -\end{equation*} -!et - -In many cases the above estimate for the standard deviation, in particular if correlations are strong, may be too simplistic. We need therefore a more precise defintion of the error and the variance in our results. - - - -===== Definition of Correlation Functions and Standard Deviation ===== - -Our estimate of the true average $\mu_{X}$ is the sample mean $\langle X_m \rangle$ - -!bt -\begin{equation*} -\mu_{X}^{\phantom X} \approx X_m=\frac{1}{mn}\sum_{\alpha=1}^m\sum_{k=1}^n x_{\alpha,k}. -\end{equation*} -!et - - -We can then use Eq. (ref{eq:exptvariance}) -!bt -\begin{equation*} -\sigma^2_m=\frac{1}{mn^2}\sum_{\alpha=1}^m\sum_{kl=1}^n (x_{\alpha,k}-\langle X_m \rangle)(x_{\alpha,l}-\langle X_m \rangle), -\end{equation*} -!et -and rewrite it as -!bt -\begin{equation*} -\sigma^2_m=\frac{\sigma^2}{n}+\frac{2}{mn^2}\sum_{\alpha=1}^m\sum_{k -#include -#include -#include -using namespace std; -// output file as global variable -ofstream ofile; - -// Main function begins here -int main(int argc, char* argv[]) -{ - int n; - char *outfilename; - - cin >> n; - double MCint = 0.; double MCintsqr2=0.; - double invers_period = 1./RAND_MAX; // initialise the random number generator - srand(time(NULL)); // This produces the so-called seed in MC jargon - // Compute the variance and the mean value of the uniform distribution - // Compute also the specific values x for each cycle in order to be able to - // the covariance and the correlation function - // Read in output file, abort if there are too few command-line arguments - if( argc <= 2 ){ - cout << "Bad Usage: " << argv[0] << - " read also output file and number of cycles on same line" << endl; - exit(1); - } - else{ - outfilename=argv[1]; - } - ofile.open(outfilename); - // Get the number of Monte-Carlo samples - n = atoi(argv[2]); - double *X; - X = new double[n]; - for (int i = 0; i < n; i++){ - double x = double(rand())*invers_period; - X[i] = x; - MCint += x; - MCintsqr2 += x*x; - } - double Mean = MCint/((double) n ); - MCintsqr2 = MCintsqr2/((double) n ); - double STDev = sqrt(MCintsqr2-Mean*Mean); - double Variance = MCintsqr2-Mean*Mean; -// Write mean value and standard deviation - cout << " Standard deviation= " << STDev << " Integral = " << Mean << endl; - - // Now we compute the autocorrelation function - double *autocor; autocor = new double[n]; - for (int j = 0; j < n; j++){ - double sum = 0.0; - for (int k = 0; k < (n-j); k++){ - sum += (X[k]-Mean)*(X[k+j]-Mean); - } - autocor[j] = sum/Variance/((double) n ); - ofile << setiosflags(ios::showpoint | ios::uppercase); - ofile << setw(15) << setprecision(8) << j; - ofile << setw(15) << setprecision(8) << autocor[j] << endl; - } - ofile.close(); // close output file - return 0; -} // end of main program -!ec - - - - - -======= Which RNG should I use? ======= - -* C++ has a class called _random_. The "random class":"http://www.cplusplus.com/reference/random/" contains a large selection of RNGs and is highly recommended. Some of these RNGs have very large periods making it thereby very safe to use these RNGs in case one is performing large calculations. In particular, the "Mersenne twister random number engine":"http://www.cplusplus.com/reference/random/mersenne_twister_engine/" has a period of $2^{19937}$. -* Add RNGs in Python - - - - - -===== How to use the Mersenne generator ===== - -The following part of a c++ code (from project 4) sets up the uniform distribution for $x\in [0,1]$. -!bc cppcod -/* - -// You need this -#include - -// Initialize the seed and call the Mersienne algo -std::random_device rd; -std::mt19937_64 gen(rd()); -// Set up the uniform distribution for x \in [[0, 1] -std::uniform_real_distribution RandomNumberGenerator(0.0,1.0); - -// Now use the RNG -int ix = (int) (RandomNumberGenerator(gen)*NSpins); -!ec - - - - - - -===== Why blocking? ===== - Statistical analysis - * Monte Carlo simulations can be treated as *computer experiments* - * The results can be analysed with the same statistical tools as we would use analysing experimental data. - * As in all experiments, we are looking for expectation values and an estimate of how accurate they are, i.e., possible sources for errors. - -A very good article which explains blocking is H. Flyvbjerg and H. G. Petersen, *Error estimates on averages of correlated data*, "Journal of Chemical Physics 91, 461-466 (1989)":"http://scitation.aip.org/content/aip/journal/jcp/91/1/10.1063/1.457480". - - - - - - -===== Why blocking? ===== - Statistical analysis - * As in other experiments, Monte Carlo experiments have two classes of errors: - * Statistical errors - * Systematical errors - * Statistical errors can be estimated using standard tools from statistics - * Systematical errors are method specific and must be treated differently from case to case. (In VMC a common source is the step length or time step in importance sampling) - - - - -===== Code to demonstrate the calculation of the autocorrelation function ===== -The following code computes the autocorrelation function, the covariance and the standard deviation -for standard RNG. -The "following file":"https://github.com/CompPhysics/ComputationalPhysics2/tree/gh-pages/doc/Programs/LecturePrograms/programs/Blocking/autocorrelation.cpp" gives the code. -!bc cppcod -// This function computes the autocorrelation function for -// the Mersenne random number generator with a uniform distribution -#include -#include -#include -#include -#include -#include -#include -#include -using namespace std; -using namespace arma; -// output file -ofstream ofile; - -// Main function begins here -int main(int argc, char* argv[]) -{ - int MonteCarloCycles; - string filename; - if (argc > 1) { - filename=argv[1]; - MonteCarloCycles = atoi(argv[2]); - string fileout = filename; - string argument = to_string(MonteCarloCycles); - fileout.append(argument); - ofile.open(fileout); - } - - // Compute the variance and the mean value of the uniform distribution - // Compute also the specific values x for each cycle in order to be able to - // compute the covariance and the correlation function - - vec X = zeros(MonteCarloCycles); - double MCint = 0.; double MCintsqr2=0.; - std::random_device rd; - std::mt19937_64 gen(rd()); - // Set up the uniform distribution for x \in [[0, 1] - std::uniform_real_distribution RandomNumberGenerator(0.0,1.0); - for (int i = 0; i < MonteCarloCycles; i++){ - double x = RandomNumberGenerator(gen); - X(i) = x; - MCint += x; - MCintsqr2 += x*x; - } - double Mean = MCint/((double) MonteCarloCycles ); - MCintsqr2 = MCintsqr2/((double) MonteCarloCycles ); - double STDev = sqrt(MCintsqr2-Mean*Mean); - double Variance = MCintsqr2-Mean*Mean; - // Write mean value and variance - cout << " Sample variance= " << Variance << " Mean value = " << Mean << endl; - // Now we compute the autocorrelation function - vec autocorrelation = zeros(MonteCarloCycles); - for (int j = 0; j < MonteCarloCycles; j++){ - double sum = 0.0; - for (int k = 0; k < (MonteCarloCycles-j); k++){ - sum += (X(k)-Mean)*(X(k+j)-Mean); - } - autocorrelation(j) = sum/Variance/((double) MonteCarloCycles ); - ofile << setiosflags(ios::showpoint | ios::uppercase); - ofile << setw(15) << setprecision(8) << j; - ofile << setw(15) << setprecision(8) << autocorrelation(j) << endl; - } - // Now compute the exact covariance using the autocorrelation function - double Covariance = 0.0; - for (int j = 0; j < MonteCarloCycles; j++){ - Covariance += autocorrelation(j); - } - Covariance *= 2.0/((double) MonteCarloCycles); - // Compute now the total variance, including the covariance, and obtain the standard deviation - double TotalVariance = (Variance/((double) MonteCarloCycles ))+Covariance; - cout << "Covariance =" << Covariance << "Totalvariance= " << TotalVariance << "Sample Variance/n= " << (Variance/((double) MonteCarloCycles )) << endl; - cout << " STD from sample variance= " << sqrt(Variance/((double) MonteCarloCycles )) << " STD with covariance = " << sqrt(TotalVariance) << endl; - - ofile.close(); // close output file - return 0; -} // end of main program - - -!ec - - - -===== What is blocking? ===== - Blocking - * Say that we have a set of samples from a Monte Carlo experiment - * Assuming (wrongly) that our samples are uncorrelated our best estimate of the standard deviation of the mean $\langle \mathbf{M}\rangle$ is given by -!bt -\[ -\sigma=\sqrt{\frac{1}{n}\left(\langle \mathbf{M}^2\rangle-\langle \mathbf{M}\rangle^2\right)} -\] -!et - * If the samples are correlated we can rewrite our results to show that -!bt -\[ -\sigma=\sqrt{\frac{1+2\tau/\Delta t}{n}\left(\langle \mathbf{M}^2\rangle-\langle \mathbf{M}\rangle^2\right)} -\] -!et - where $\tau$ is the correlation time (the time between a sample and the next uncorrelated sample) and $\Delta t$ is time between each sample - - - -===== What is blocking? ===== - Blocking - * If $\Delta t\gg\tau$ our first estimate of $\sigma$ still holds - * Much more common that $\Delta t<\tau$ - * In the method of data blocking we divide the sequence of samples into blocks - * We then take the mean $\langle \mathbf{M}_i\rangle$ of block $i=1\ldots n_{blocks}$ to calculate the total mean and variance - * The size of each block must be so large that sample $j$ of block $i$ is not correlated with sample $j$ of block $i+1$ - * The correlation time $\tau$ would be a good choice - - - -===== What is blocking? ===== - Blocking - * Problem: We don't know $\tau$ or it is too expensive to compute - * Solution: Make a plot of std. dev. as a function of blocksize - * The estimate of std. dev. of correlated data is too low $\to$ the error will increase with increasing block size until the blocks are uncorrelated, where we reach a plateau - * When the std. dev. stops increasing the blocks are uncorrelated - - - -===== Implementation ===== - - * Do a Monte Carlo simulation, storing all samples to file - * Do the statistical analysis on this file, independently of your Monte Carlo program - * Read the file into an array - * Loop over various block sizes - * For each block size $n_b$, loop over the array in steps of $n_b$ taking the mean of elements $i n_b,\ldots,(i+1) n_b$ - * Take the mean and variance of the resulting array - * Write the results for each block size to file for later - analysis - - - - - - - -===== Actual implementation with code, main function ===== -When the file gets large, it can be useful to write your data in binary mode instead of ascii characters. -The "following python file":"https://github.com/CompPhysics/MachineLearning/blob/master/doc/Programs/Sampling/analysis.py" reads data from file with the output from every Monte Carlo cycle. -!bc pycod -# Blocking - @timeFunction - def blocking(self, blockSizeMax = 500): - blockSizeMin = 1 - - self.blockSizes = [] - self.meanVec = [] - self.varVec = [] - - for i in range(blockSizeMin, blockSizeMax): - if(len(self.data) % i != 0): - pass#continue - blockSize = i - meanTempVec = [] - varTempVec = [] - startPoint = 0 - endPoint = blockSize - - while endPoint <= len(self.data): - meanTempVec.append(np.average(self.data[startPoint:endPoint])) - startPoint = endPoint - endPoint += blockSize - mean, var = np.average(meanTempVec), np.var(meanTempVec)/len(meanTempVec) - self.meanVec.append(mean) - self.varVec.append(var) - self.blockSizes.append(blockSize) - - self.blockingAvg = np.average(self.meanVec[-200:]) - self.blockingVar = (np.average(self.varVec[-200:])) - self.blockingStd = np.sqrt(self.blockingVar) - -!ec - - - - - -===== The Bootstrap method ===== - -The Bootstrap resampling method is also very popular. It is very simple: - -o Start with your sample of measurements and compute the sample variance and the mean values -o Then start again but pick in a random way the numbers in the sample and recalculate the mean and the sample variance. -o Repeat this $K$ times. - -It can be shown, see the article by "Efron":"https://projecteuclid.org/download/pdf_1/euclid.aos/1176344552" -that it produces the correct standard deviation. - -This method is very useful for small ensembles of data points. - - -===== Bootstrapping ===== -Given a set of $N$ data, assume that we are interested in some -observable $\theta$ which may be estimated from that set. This observable can also be for example the result of a fit based on all $N$ raw data. -Let us call the value of the observable obtained from the original -data set $\hat{\theta}$. One recreates from the sample repeatedly -other samples by choosing randomly $N$ data out of the original set. -This costs essentially nothing, since we just recycle the original data set for the building of new sets. - - -===== Bootstrapping, recipe ===== -Let us assume we have done this $K$ times and thus have $K$ sets of $N$ -data values each. -Of course some values will enter more than once in the new sets. For each of these sets one computes the observable $\theta$ resulting in values $\theta_k$ with $k = 1,...,K$. Then one determines -!bt -\[ -\tilde{\theta} = \frac{1}{K} \sum_{k=1}^K \theta_k, -\] -!et -and -!bt -\[ -sigma^2_{\tilde{\theta}} = \frac{1}{K} \sum_{k=1}^K \left(\theta_k-\tilde{\theta}\right)^2. -\] -!et - -These are estimators for $\angle\theta\rangle$ and its variance. They are not unbiased and therefore -$\tilde{\theta}\neq\hat{\theta}$ for finite K. - -The difference is called bias and gives an idea on how far away the result may be from -the true $\angle\theta\rangle$. As final result for the observable one quotes $\angle\theta\rangle = \tilde{\theta} \pm \sigma_{\tilde{\theta}}$ . - - - -===== Bootstrapping, "code":"https://github.com/CompPhysics/MachineLearning/blob/master/doc/Programs/Sampling/analysis.py" ===== -!bc -# Bootstrap - @timeFunction - def bootstrap(self, nBoots = 1000): - bootVec = np.zeros(nBoots) - for k in range(0,nBoots): - bootVec[k] = np.average(np.random.choice(self.data, len(self.data))) - self.bootAvg = np.average(bootVec) - self.bootVar = np.var(bootVec) - self.bootStd = np.std(bootVec) -!ec - - -===== Jackknife, "code":"https://github.com/CompPhysics/MachineLearning/blob/master/doc/Programs/Sampling/analysis.py" ===== -!bc -# Jackknife - @timeFunction - def jackknife(self): - jackknVec = np.zeros(len(self.data)) - for k in range(0,len(self.data)): - jackknVec[k] = np.average(np.delete(self.data, k)) - self.jackknAvg = self.avg - (len(self.data) - 1) * (np.average(jackknVec) - self.avg) - self.jackknVar = float(len(self.data) - 1) * np.var(jackknVec) - self.jackknStd = np.sqrt(self.jackknVar) -!ec - - - - - - -======= Regression analysis, overarching aims ======= - - -Regression modeling deals with the description of the sampling distribution of a given random variable $y$ varies as function of another variable or a set of such variables $\hat{x} =[x_0, x_1,\dots, x_p]^T$. -The first variable is called the _dependent_, the _outcome_ or the _response_ variable while the set of variables $\hat{x}$ is called the independent variable, or the predictor variable or the explanatory variable. - -A regression model aims at finding a likelihood function $p(y\vert \hat{x})$, that is the conditional distribution for $y$ with a given $\hat{x}$. The estimation of $p(y\vert \hat{x})$ is made using a data set with -* $n$ cases $i = 0, 1, 2, \dots, n-1$ -* Response (dependent or outcome) variable $y_i$ with $i = 0, 1, 2, \dots, n-1$ -* $p$ Explanatory (independent or predictor) variables $\hat{x}_i=[x_{i0}, x_{i1}, \dots, x_{ip}]$ with $i = 0, 1, 2, \dots, n-1$ - The goal of the regression analysis is to extract/exploit relationship between $y_i$ and $\hat{x}_i$ in or to infer causal dependencies, approximations to the likelihood functions, functional relationships and to make predictions . - - - -===== Regression analysis, overarching aims II ===== - - - -Consider an experiment in which $p$ characteristics of $n$ samples are -measured. The data from this experiment are denoted $\mathbf{X}$, with -$\mathbf{X}$ as above. The matrix $\mathbf{X}$ is called the *design -matrix*. Additional information of the samples is available in the -form of $\mathbf{Y}$ (also as above). The variable $\mathbf{Y}$ is -generally referred to as the *response variable*. The aim of -regression analysis is to explain $\mathbf{Y}$ in terms of -$\mathbf{X}$ through a functional relationship like $Y_i = -f(\mathbf{X}_{i,\ast})$. When no prior knowledge on the form of -$f(\cdot)$ is available, it is common to assume a linear relationship -between $\mathbf{X}$ and $\mathbf{Y}$. This assumption gives rise to -the *linear regression model* where $\beta = (\beta_1, \ldots, -\beta_p)^{\top}$ is the *regression parameter*. The parameter -$\beta_j$, $j=1, \ldots, p$, represents the effect size of covariate -$j$ on the response. That is, for each unit change in covariate $j$ -(while keeping the other covariates fixed) the observed change in the -response is equal to $\beta_j$. - - - - -===== General linear models ===== - -Before we proceed let us study a case from linear algebra where we aim at fitting a set of data $\hat{y}=[y_0,y_1,\dots,y_{n-1}]$. We could think of these data as a result of an experiment or a complicated numerical experiment. These data are functions of a series of variables $\hat{x}=[x_0,x_1,\dots,x_{n-1}]$, that is $y_i = y(x_i)$ with $i=0,1,2,\dots,n-1$. The variables $x_i$ could represent physical quantities like time, temperature, position etc. We assume that $y(x)$ is a smooth function. - -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 -!bt -\[ -y=y(x) \rightarrow y(x_i)=\tilde{y}_i+\epsilon_i=\sum_{j=0}^{n-1} \beta_i x_i^j+\epsilon_i, -\] -!et -where $\epsilon_i$ is the error in our approximation. - - - - - -===== Rewriting the fitting procedure as a linear algebra problem ===== - -For every set of values $y_i,x_i$ we have thus the corresponding set of equations -!bt -\begin{align*} -y_0&=\beta_0+\beta_1x_0^1+\beta_2x_0^2+\dots+\beta_{n-1}x_0^{n-1}+\epsilon_0\\ -y_1&=\beta_0+\beta_1x_1^1+\beta_2x_1^2+\dots+\beta_{n-1}x_1^{n-1}+\epsilon_1\\ -y_2&=\beta_0+\beta_1x_2^1+\beta_2x_2^2+\dots+\beta_{n-1}x_2^{n-1}+\epsilon_2\\ -\dots & \dots \\ -y_{n-1}&=\beta_0+\beta_1x_{n-1}^1+\beta_2x_{n-1}^2+\dots+\beta_1x_{n-1}^{n-1}+\epsilon_{n-1}.\\ -\end{align*} -!et - - - - -===== Rewriting the fitting procedure as a linear algebra problem, follows ===== - -Defining the vectors -!bt -\[ -\hat{y} = [y_0,y_1, y_2,\dots, y_{n-1}]^T, -\] -!et -and -!bt -\[ -\hat{\beta} = [\beta_0,\beta_1, \beta_2,\dots, \beta_{n-1}]^T, -\] -!et -and -!bt -\[ -\hat{\epsilon} = [\epsilon_0,\epsilon_1, \epsilon_2,\dots, \epsilon_{n-1}]^T, -\] -!et -and the matrix -!bt -\[ -\hat{X}= -\begin{bmatrix} -1& x_{0}^1 &x_{0}^2& \dots & \dots &x_{0}^{n-1}\\ -1& x_{1}^1 &x_{1}^2& \dots & \dots &x_{1}^{n-1}\\ -1& x_{2}^1 &x_{2}^2& \dots & \dots &x_{2}^{n-1}\\ -\dots& \dots &\dots& \dots & \dots &\dots\\ -1& x_{n-1}^1 &x_{n-1}^2& \dots & \dots &x_{n-1}^{n-1}\\ -\end{bmatrix} -\] -!et -we can rewrite our equations as -!bt -\[ -\hat{y} = \hat{X}\hat{\beta}+\hat{\epsilon}. -\] -!et - - - - -===== Generalizing the fitting procedure as a linear algebra problem ===== - -We are obviously not limited to the above polynomial. We could replace the various powers of $x$ with elements of Fourier series, that is, instead of $x_i^j$ we could have $\cos{(j x_i)}$ or $\sin{(j x_i)}$, or time series or other orthogonal functions. -For every set of values $y_i,x_i$ we can then generalize the equations to -!bt -\begin{align*} -y_0&=\beta_0x_{00}+\beta_1x_{01}+\beta_2x_{02}+\dots+\beta_{n-1}x_{0n-1}+\epsilon_0\\ -y_1&=\beta_0x_{10}+\beta_1x_{11}+\beta_2x_{12}+\dots+\beta_{n-1}x_{1n-1}+\epsilon_1\\ -y_2&=\beta_0x_{20}+\beta_1x_{21}+\beta_2x_{22}+\dots+\beta_{n-1}x_{2n-1}+\epsilon_2\\ -\dots & \dots \\ -y_{i}&=\beta_0x_{i0}+\beta_1x_{i1}+\beta_2x_{i2}+\dots+\beta_{n-1}x_{in-1}+\epsilon_i\\ -\dots & \dots \\ -y_{n-1}&=\beta_0x_{n-1,0}+\beta_1x_{n-1,2}+\beta_2x_{n-1,2}+\dots+\beta_1x_{n-1,n-1}+\epsilon_{n-1}.\\ -\end{align*} -!et - - - - -===== Generalizing the fitting procedure as a linear algebra problem ===== - -We redefine in turn the matrix $\hat{X}$ as -!bt -\[ -\hat{X}= -\begin{bmatrix} -x_{00}& x_{01} &x_{02}& \dots & \dots &x_{0,n-1}\\ -x_{10}& x_{11} &x_{12}& \dots & \dots &x_{1,n-1}\\ -x_{20}& x_{21} &x_{22}& \dots & \dots &x_{2,n-1}\\ -\dots& \dots &\dots& \dots & \dots &\dots\\ -x_{n-1,0}& x_{n-1,1} &x_{n-1,2}& \dots & \dots &x_{n-1,n-1}\\ -\end{bmatrix} -\] -!et -and without loss of generality we rewrite again our equations as -!bt -\[ -\hat{y} = \hat{X}\hat{\beta}+\hat{\epsilon}. -\] -!et -The left-hand side of this equation forms know. Our error vector $\hat{\epsilon}$ and the parameter vector $\hat{\beta}$ are our unknow quantities. How can we obtain the optimal set of $\beta_i$ values? - - - - -===== Optimizing our parameters ===== - -We have defined the matrix $\hat{X}$ -!bt -\begin{align*} -y_0&=\beta_0x_{00}+\beta_1x_{01}+\beta_2x_{02}+\dots+\beta_{n-1}x_{0n-1}+\epsilon_0\\ -y_1&=\beta_0x_{10}+\beta_1x_{11}+\beta_2x_{12}+\dots+\beta_{n-1}x_{1n-1}+\epsilon_1\\ -y_2&=\beta_0x_{20}+\beta_1x_{21}+\beta_2x_{22}+\dots+\beta_{n-1}x_{2n-1}+\epsilon_1\\ -\dots & \dots \\ -y_{i}&=\beta_0x_{i0}+\beta_1x_{i1}+\beta_2x_{i2}+\dots+\beta_{n-1}x_{in-1}+\epsilon_1\\ -\dots & \dots \\ -y_{n-1}&=\beta_0x_{n-1,0}+\beta_1x_{n-1,2}+\beta_2x_{n-1,2}+\dots+\beta_1x_{n-1,n-1}+\epsilon_{n-1}.\\ -\end{align*} -!et - - - - -===== Optimizing our parameters, more details ===== - -We well use this matrix to define the approximation $\hat{\tilde{y}}$ via the unknown quantity $\hat{\beta}$ as -!bt -\[ -\hat{\tilde{y}}= \hat{X}\hat{\beta}, -\] -!et -and in order to find the optimal parameters $\beta_i$ instead of solving the above linear algebra problem, we define a function which gives a measure of the spread between the values $y_i$ (which represent hopefully the exact values) and the parametrized values $\tilde{y}_i$, namely -!bt -\[ -Q(\hat{\beta})=\sum_{i=0}^{n-1}\left(y_i-\tilde{y}_i\right)^2=\left(\hat{y}-\hat{\tilde{y}}\right)^T\left(\hat{y}-\hat{\tilde{y}}\right), -\] -!et -or using the matrix $\hat{X}$ as -!bt -\[ -Q(\hat{\beta})=\left(\hat{y}-\hat{X}\hat{\beta}\right)^T\left(\hat{y}-\hat{X}\hat{\beta}\right). -\] -!et - - - - -===== Interpretations and optimizing our parameters ===== - -The function -!bt -\[ -Q(\hat{\beta})=\left(\hat{y}-\hat{X}\hat{\beta}\right)^T\left(\hat{y}-\hat{X}\hat{\beta}\right), -\] -!et -can be linked to the variance of the quantity $y_i$ if we interpret the latter as the mean value of for example a numerical experiment. When linking below with the maximum likelihood approach below, we will indeed interpret $y_i$ as a mean value -!bt -\[ -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, -\] -!et -where $\langle y_i \rangle$ is the mean value. Keep in mind also that till now we have treated $y_i$ as the exact value. Normally, the response (dependent or outcome) variable $y_i$ the outcome of a numerical experiment or another type of experiment and is thus only an approximation to the true value. It is then always accompanied by an error estimate, often limited to a statistical error estimate given by the standard deviation discussed earlier. In the discussion here we will treat $y_i$ as our exact value for the response variable. - -In order to find the parameters $\beta_i$ we will then minimize the spread of $Q(\hat{\beta})$ by requiring -!bt -\[ -\frac{\partial Q(\hat{\beta})}{\partial \beta_j} = \frac{\partial }{\partial \beta_j}\left[ \sum_{i=0}^{n-1}\left(y_i-\beta_0x_{i,0}-\beta_1x_{i,1}-\beta_2x_{i,2}-\dots-\beta_{n-1}x_{i,n-1}\right)^2\right]=0, -\] -!et -which results in -!bt -\[ -\frac{\partial Q(\hat{\beta})}{\partial \beta_j} = -2\left[ \sum_{i=0}^{n-1}x_{ij}\left(y_i-\beta_0x_{i,0}-\beta_1x_{i,1}-\beta_2x_{i,2}-\dots-\beta_{n-1}x_{i,n-1}\right)\right]=0, -\] -!et -or in a matrix-vector form as -!bt -\[ -\frac{\partial Q(\hat{\beta})}{\partial \hat{\beta}} = 0 = \hat{X}^T\left( \hat{y}-\hat{X}\hat{\beta}\right). -\] -!et - - - - - - -===== Interpretations and optimizing our parameters ===== - -We can rewrite -!bt -\[ -\frac{\partial Q(\hat{\beta})}{\partial \hat{\beta}} = 0 = \hat{X}^T\left( \hat{y}-\hat{X}\hat{\beta}\right), -\] -!et -as -!bt -\[ -\hat{X}^T\hat{y} = \hat{X}^T\hat{X}\hat{\beta}, -\] -!et -and if the matrix $\hat{X}^T\hat{X}$ is invertible we have the solution -!bt -\[ -\hat{\beta} =\left(\hat{X}^T\hat{X}\right)^{-1}\hat{X}^T\hat{y}. -\] -!et - - - - -===== Interpretations and optimizing our parameters ===== - -The residuals $\hat{\epsilon}$ are in turn given by -!bt -\[ -\hat{\epsilon} = \hat{y}-\hat{\tilde{y}} = \hat{y}-\hat{X}\hat{\beta}, -\] -!et -and with -!bt -\[ -\hat{X}^T\left( \hat{y}-\hat{X}\hat{\beta}\right)= 0, -\] -!et -we have -!bt -\[ -\hat{X}^T\hat{\epsilon}=\hat{X}^T\left( \hat{y}-\hat{X}\hat{\beta}\right)= 0, -\] -!et -meaning that the solution for $\hat{\beta}$ is the one which minimizes the residuals. Later we will link this with the maximum likelihood approach. - - - - - -===== The $\chi^2$ function ===== - - -Normally, the response (dependent or outcome) variable $y_i$ the outcome of a numerical experiment or another type of experiment and is thus only an approximation to the true value. It is then always accompanied by an error estimate, often limited to a statistical error estimate given by the standard deviation discussed earlier. In the discussion here we will treat $y_i$ as our exact value for the response variable. - -Introducing the standard deviation $\sigma_i$ for each measurement $y_i$, we define now the $\chi^2$ function as -!bt -\[ -\chi^2(\hat{\beta})=\sum_{i=0}^{n-1}\frac{\left(y_i-\tilde{y}_i\right)^2}{\sigma_i^2}=\left(\hat{y}-\hat{\tilde{y}}\right)^T\frac{1}{\hat{\Sigma^2}}\left(\hat{y}-\hat{\tilde{y}}\right), -\] -!et -where the matrix $\hat{\Sigma}$ is a diagonal matrix with $\sigma_i$ as matrix elements. - - - - -===== The $\chi^2$ function ===== - - -In order to find the parameters $\beta_i$ we will then minimize the spread of $\chi^2(\hat{\beta})$ by requiring -!bt -\[ -\frac{\partial \chi^2(\hat{\beta})}{\partial \beta_j} = \frac{\partial }{\partial \beta_j}\left[ \sum_{i=0}^{n-1}\left(\frac{y_i-\beta_0x_{i,0}-\beta_1x_{i,1}-\beta_2x_{i,2}-\dots-\beta_{n-1}x_{i,n-1}}{\sigma_i}\right)^2\right]=0, -\] -!et -which results in -!bt -\[ -\frac{\partial \chi^2(\hat{\beta})}{\partial \beta_j} = -2\left[ \sum_{i=0}^{n-1}\frac{x_{ij}}{\sigma_i}\left(\frac{y_i-\beta_0x_{i,0}-\beta_1x_{i,1}-\beta_2x_{i,2}-\dots-\beta_{n-1}x_{i,n-1}}{\sigma_i}\right)\right]=0, -\] -!et -or in a matrix-vector form as -!bt -\[ -\frac{\partial \chi^2(\hat{\beta})}{\partial \hat{\beta}} = 0 = \hat{A}^T\left( \hat{b}-\hat{A}\hat{\beta}\right). -\] -!et -where we have defined the matrix $\hat{A} =\hat{X}/\hat{\Sigma}$ with matrix elements $a_{ij} = x_{ij}/\sigma_i$ and the vector $\hat{b}$ with elements $b_i = y_i/\sigma_i$. - - - -===== The $\chi^2$ function ===== - - -We can rewrite -!bt -\[ -\frac{\partial \chi^2(\hat{\beta})}{\partial \hat{\beta}} = 0 = \hat{A}^T\left( \hat{b}-\hat{A}\hat{\beta}\right), -\] -!et -as -!bt -\[ -\hat{A}^T\hat{b} = \hat{A}^T\hat{A}\hat{\beta}, -\] -!et -and if the matrix $\hat{A}^T\hat{A}$ is invertible we have the solution -!bt -\[ -\hat{\beta} =\left(\hat{A}^T\hat{A}\right)^{-1}\hat{A}^T\hat{b}. -\] -!et - - - -===== The $\chi^2$ function ===== - - -If we then introduce the matrix -!bt -\[ -\hat{H} = \left(\hat{A}^T\hat{A}\right)^{-1}, -\] -!et -we have then the following expression for the parameters $\beta_j$ (the matrix elements of $\hat{H}$ are $h_{ij}$) -!bt -\[ -\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} -\] -!et -We state without proof the expression for the uncertainty in the parameters $\beta_j$ as (we leave this as an exercise) -!bt -\[ -\sigma^2(\beta_j) = \sum_{i=0}^{n-1}\sigma_i^2\left( \frac{\partial \beta_j}{\partial y_i}\right)^2, -\] -!et -resulting in -!bt -\[ -\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}! -\] -!et - - - -===== The $\chi^2$ function ===== - -The first step here is to approximate the function $y$ with a first-order polynomial, that is we write -!bt -\[ -y=y(x) \rightarrow y(x_i) \approx \beta_0+\beta_1 x_i. -\] -!et -By computing the derivatives of $\chi^2$ with respect to $\beta_0$ and $\beta_1$ show that these are given by -!bt -\[ -\frac{\partial \chi^2(\hat{\beta})}{\partial \beta_0} = -2\left[ \sum_{i=0}^{n-1}\left(\frac{y_i-\beta_0-\beta_1x_{i}}{\sigma_i^2}\right)\right]=0, -\] -!et -and -!bt -\[ -\frac{\partial \chi^2(\hat{\beta})}{\partial \beta_0} = -2\left[ \sum_{i=0}^{n-1}x_i\left(\frac{y_i-\beta_0-\beta_1x_{i}}{\sigma_i^2}\right)\right]=0. -\] -!et - - - -===== The $\chi^2$ function ===== - - -For a linear fit we don't need to invert a matrix!! -Defining -!bt -\[ -\gamma = \sum_{i=0}^{n-1}\frac{1}{\sigma_i^2}, -\] -!et - -!bt -\[ -\gamma_x = \sum_{i=0}^{n-1}\frac{x_{i}}{\sigma_i^2}, -\] -!et -!bt -\[ -\gamma_y = \sum_{i=0}^{n-1}\left(\frac{y_i}{\sigma_i^2}\right), -\] -!et -!bt -\[ -\gamma_{xx} = \sum_{i=0}^{n-1}\frac{x_ix_{i}}{\sigma_i^2}, -\] -!et -!bt -\[ -\gamma_{xy} = \sum_{i=0}^{n-1}\frac{y_ix_{i}}{\sigma_i^2}, -\] -!et -we obtain -!bt -\[ -\beta_0 = \frac{\gamma_{xx}\gamma_y-\gamma_x\gamma_y}{\gamma\gamma_{xx}-\gamma_x^2}, -\] -!et -!bt -\[ -\beta_1 = \frac{\gamma_{xy}\gamma-\gamma_x\gamma_y}{\gamma\gamma_{xx}-\gamma_x^2}. -\] -!et - -This approach (different linear and non-linear regression) suffers often from both being underdetermined and overdetermined in the unknown coefficients $\beta_i$. A better approach is to use the Singular Value Decomposition (SVD) method discussed below. Or using Lasso and Ridge regression. See below. - - - - - - -===== Simple regression model ===== -We are now ready to write our first program which aims at solving the above linear regression equations. We start with data we have produced ourselves, in this case normally distributed random numbers along the $x$-axis. These numbers define then the value of a function $y(x)=4+3x+N(0,1)$. Thereafter we order the $x$ values and employ our linear regression algorithm to set up the best fit. Here we find it useful to use the numpy function $c\_$ arrays where arrays are stacked along their last axis after being upgraded to at least two dimensions with ones post-pended to the shape. The following examples help in understanding what happens !bc pycod -import numpy as np -print(np.c_[np.array([1,2,3]), np.array([4,5,6])]) -print(np.c_[np.array([[1,2,3]]), 0, 0, np.array([[4,5,6]])]) +import pandas as pd +from IPython.display import display +data = {'First Name': ["Frodo", "Bilbo", "Aragorn II", "Samwise"], + 'Last Name': ["Baggins", "Baggins","Elessar","Gamgee"], + 'Place of birth': ["Shire", "Shire", "Eriador", "Shire"], + 'Date of Birth T.A.': [2968, 2890, 2931, 2980] + } +data_pandas = pd.DataFrame(data) +display(data_pandas) !ec +In the above we have imported _pandas_ with the shorthand _pd_, the latter has become the standard way we import _pandas_. We make then a list of various variables +and reorganize the aboves lists into a _DataFrame_ and then print out a neat table with specific column labels as *Name*, *place of birth* and *date of birth*. +Displaying these results, we see that the indices are given by the default numbers from zero to three. +_pandas_ is extremely flexible and we can easily change the above indices by defining a new type of indexing as +!bc pycod +data_pandas = pd.DataFrame(data,index=['Frodo','Bilbo','Aragorn','Sam']) +display(data_pandas) +!ec +Thereafter we display the content of the row which begins with the index _Aragorn_ +!bc pycod +display(data_pandas.loc['Aragorn']) +!ec + +We can easily append data to this, for example +!bc pycod +new_hobbit = {'First Name': ["Peregrin"], + 'Last Name': ["Took"], + 'Place of birth': ["Shire"], + 'Date of Birth T.A.': [2990] + } +data_pandas=data_pandas.append(pd.DataFrame(new_hobbit, index=['Pippin'])) +display(data_pandas) +!ec + + +Here are other examples where we use the _DataFrame_ functionality to handle arrays, now with more interesting features for us, namely numbers. We set up a matrix +of dimensionality $10\times 5$ and compute the mean value and standard deviation of each column. Similarly, we can perform mathematial operations like squaring the matrix elements and many other operations. !bc pycod -# Importing various packages -from random import random, seed import numpy as np -import matplotlib.pyplot as plt +import pandas as pd +from IPython.display import display +np.random.seed(100) +# setting up a 10 x 5 matrix +rows = 10 +cols = 5 +a = np.random.randn(rows,cols) +df = pd.DataFrame(a) +display(df) +print(df.mean()) +print(df.std()) +display(df**2) +!ec -x = 2*np.random.rand(100,1) -y = 4+3*x+np.random.randn(100,1) +Thereafter we can select specific columns only and plot final results +!bc pycod +df.columns = ['First', 'Second', 'Third', 'Fourth', 'Fifth'] +df.index = np.arange(10) -xb = np.c_[np.ones((100,1)), x] -beta = np.linalg.inv(xb.T.dot(xb)).dot(xb.T).dot(y) -xnew = np.array([[0],[2]]) -xbnew = np.c_[np.ones((2,1)), xnew] -ypredict = xbnew.dot(beta) +display(df) +print(df['Second'].mean() ) +print(df.info()) +print(df.describe()) -plt.plot(xnew, ypredict, "r-") -plt.plot(x, y ,'ro') -plt.axis([0,2.0,0, 15.0]) -plt.xlabel(r'$x$') -plt.ylabel(r'$y$') -plt.title(r'Linear Regression') +from pylab import plt, mpl +plt.style.use('seaborn') +mpl.rcParams['font.family'] = 'serif' + +df.cumsum().plot(lw=2.0, figsize=(10,6)) plt.show() -!ec -We see that, as expected, a linear fit gives a seemingly (from the graph) good representation of the data. - - - - - -===== Simple regression model, now using _scikit-learn_ ===== - - -We can repeat the above algorithm using _scikit-learn_ as follows -!bc pycod -# Importing various packages -from random import random, seed -import numpy as np -import matplotlib.pyplot as plt -from sklearn.linear_model import LinearRegression - -x = 2*np.random.rand(100,1) -y = 4+3*x+np.random.randn(100,1) -linreg = LinearRegression() -linreg.fit(x,y) -xnew = np.array([[0],[2]]) -ypredict = linreg.predict(xnew) - -plt.plot(xnew, ypredict, "r-") -plt.plot(x, y ,'ro') -plt.axis([0,2.0,0, 15.0]) -plt.xlabel(r'$x$') -plt.ylabel(r'$y$') -plt.title(r'Random numbers ') +df.plot.bar(figsize=(10,6), rot=15) plt.show() !ec +We can produce a $4\times 4$ matrix +!bc pycod +b = np.arange(16).reshape((4,4)) +print(b) +df1 = pd.DataFrame(b) +print(df1) +!ec +and many other operations. + +The _Series_ class is another important class included in +_pandas_. You can view it as a specialization of _DataFrame_ but where +we have just a single column of data. It shares many of the same features as _DataFrame. As with _DataFrame_, +most operations are vectorized, achieving thereby a high performance when dealing with computations of arrays, in particular labeled arrays. +As we will see below it leads also to a very concice code close to the mathematical operations we may be interested in. +For multidimensional arrays, we recommend strongly "xarray":"http://xarray.pydata.org/en/stable/". _xarray_ has much of the same flexibility as _pandas_, but allows for the extension to higher dimensions than two. We will see examples later of the usage of both _pandas_ and _xarray_. -===== Simple linear regression model using _scikit-learn_ ===== +===== Reading Data and fitting ===== -We start with perhaps our simplest possible example, using _scikit-learn_ to perform linear regression analysis on a data set produced by us. -What follows is a simple Python code where we have defined function $y$ in terms of the variable $x$. Both are defined as vectors of dimension $1\times 100$. The entries to the vector $\hat{x}$ are given by random numbers generated with a uniform distribution with entries $x_i \in [0,1]$ (more about probability distribution functions later). These values are then used to define a function $y(x)$ (tabulated again as a vector) with a linear dependence on $x$ plus a random noise added via the normal distribution. +In order to study various Machine Learning algorithms, we need to +access data. Acccessing data is an essential step in all machine +learning algorithms. In particular, setting up the so-called _design +matrix_ (to be defined below) is often the first element we need in +order to perform our calculations. To set up the design matrix means +reading (and later, when the calculations are done, writing) data +in various formats, The formats span from reading files from disk, +loading data from databases and interacting with online sources +like web application programming interfaces (APIs). + +In handling various input formats, as discussed above, we will mainly stay with _pandas_, +a Python package which allows us, in a seamless and painless way, to +deal with a multitude of formats, from standard _csv_ (comma separated +values) files, via _excel_, _html_ to _hdf5_ formats. With _pandas_ +and the _DataFrame_ and _Series_ functionalities we are able to convert text data +into the calculational formats we need for a specific algorithm. And our code is going to be +pretty close the basic mathematical expressions. + +Our first data set is going to be a classic from nuclear physics, namely all +available data on binding energies. Don't be intimidated if you are not familiar with nuclear physics. It serves simply as an example here of a data set. + +We will show some of the +strengths of packages like _Scikit-Learn_ in fitting nuclear binding energies to +specific functions using linear regression first. Then, as a teaser, we will show you how +you can easily implement other algorithms like decision trees and random forests and neural networks. + +But before we really start with nuclear physics data, let's just look at some simpler polynomial fitting cases, such as, +(don't be offended) fitting straight lines! + + +=== Simple linear regression model using _scikit-learn_ === + +We start with perhaps our simplest possible example, using _Scikit-Learn_ to perform linear regression analysis on a data set produced by us. + +What follows is a simple Python code where we have defined a function +$y$ in terms of the variable $x$. Both are defined as vectors with $100$ entries. +The numbers in the vector $\hat{x}$ are given +by random numbers generated with a uniform distribution with entries +$x_i \in [0,1]$ (more about probability distribution functions +later). These values are then used to define a function $y(x)$ +(tabulated again as a vector) with a linear dependence on $x$ plus a +random noise added via the normal distribution. The Numpy functions are imported used the _import numpy as np_ @@ -4965,7 +1032,7 @@ y = 2x+N(0,1), !et where $N(0,1)$ represents random numbers generated by the normal -distribution. From _scikit-learn_ we import then the +distribution. From _Scikit-Learn_ we import then the _LinearRegression_ functionality and make a prediction $\tilde{y} = \alpha + \beta x$ using the function _fit(x,y)_. We call the set of data $(\hat{x},\hat{y})$ for our training data. The Python package @@ -5004,10 +1071,6 @@ plt.title(r'Simple Linear Regression') plt.show() !ec - - -===== Simple linear regression model ===== - This example serves several aims. It allows us to demonstrate several aspects of data analysis and later machine learning algorithms. The immediate visualization shows that our linear fit is not @@ -5023,28 +1086,18 @@ y = 10x+0.01 \times N(0,1), \] !et -where $x$ is defined as before. - - - -===== Less noise ===== - -Does the fit look better? Indeed, by -reducing the role of the normal distribution we see immediately that +where $x$ is defined as before. Does the fit look better? Indeed, by +reducing the role of the noise given by the normal distribution we see immediately that our linear prediction seemingly reproduces better the training set. However, this testing 'by the eye' is obviouly not satisfactory in the long run. Here we have only defined the training data and our model, and have not discussed a more rigorous approach to the _cost_ function. - - -===== How to study our fits ===== - We need more rigorous criteria in defining whether we have succeeded or not in modeling our training data. You will be surprised to see that many scientists seldomly venture beyond this 'by the eye' approach. A standard approach for the *cost* function is the so-called $\chi^2$ -function +function (a variant of the mean-squared error (MSE)) !bt \[ \chi^2 = \frac{1}{n} @@ -5057,10 +1110,6 @@ $y_i$. We may not know the explicit value of $\sigma_i^2$, it serves however the aim of scaling the equations and make the cost function dimensionless. - - -===== Minimizing the cost function ===== - Minimizing the cost function is a central aspect of our discussions to come. Finding its minima as function of the model parameters ($\alpha$ and $\beta$ in our case) will be a recurring @@ -5076,11 +1125,8 @@ many practitioners minimize the above function ''by the eye', popularly dubbed a 'chi by the eye'. That is, change a parameter and see (visually and numerically) that the $\chi^2$ function becomes smaller. - -===== Relative error ===== - 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 -the relative error as +the relative error (why would we prefer the MSE instead of the relative error?) as !bt \[ @@ -5112,17 +1158,13 @@ have a small or larger relative error. Try to play around with different training data sets and study (graphically) the value of the relative error. - - -===== The richness of _scikit-learn_ ===== - -As mentioned above, _scikit-learn_ has an impressive functionality. +As mentioned above, _Scikit-Learn_ has an impressive functionality. We can for example extract the values of $\alpha$ and $\beta$ and their error estimates, or the variance and standard deviation and many other properties from the statistical data analysis. Here we show an -example of the functionality of scikit-learn. +example of the functionality of _Scikit-Learn_. !bc pycod import numpy as np import matplotlib.pyplot as plt @@ -5153,11 +1195,6 @@ plt.title(r'Linear Regression fit ') plt.show() !ec - - - -===== Functions in _scikit-learn_ ===== - The function _coef_ gives us the parameter $\beta$ of our fit while _intercept_ yields $\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 !bt @@ -5170,9 +1207,6 @@ The smaller the value, the better the fit. Ideally we would like to have an MSE equal zero. The attentive reader has probably recognized this function as being similar to the $\chi^2$ function defined above. - -===== Other functions in _scikit-learn_ ===== - The _r2score_ function computes $R^2$, the coefficient of determination. It provides a measure of how well future samples are likely to be predicted by the model. Best possible score is 1.0 and it @@ -5192,12 +1226,8 @@ where we have defined the mean value of $\hat{y}$ as \bar{y} = \frac{1}{n} \sum_{i=0}^{n - 1} y_i. \] !et - - -===== The mean absolute error and other functions in _scikit-learn_ ===== - -Another quantity will meet again in our discussions of regression analysis is - 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. +Another quantity taht we will meet again in our discussions of regression analysis is + 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. The MAE is defined as follows !bt \[ @@ -5217,14 +1247,9 @@ estimate is best to use when targets having exponential growth, such as population counts, average sales of a commodity over a span of years etc. - - -===== Cubic polynomial in _scikit-learn_ ===== - We will discuss in more detail these and other functions in the various lectures. We conclude this part with another example. Instead of a linear $x$-dependence we study now a cubic polynomial and use the polynomial regression analysis tools of scikit-learn. -Add description of the various python commands. !bc pycod import matplotlib.pyplot as plt @@ -5259,136 +1284,1440 @@ def error(a): print (error(y)) !ec -Using _R_, we can perform similar studies. + + + +=== To our real data: nuclear binding energies. Brief reminder on masses and binding energies === + +Let us now dive into nuclear physics and remind ourselves briefly about some basic features about binding +energies. A basic quantity which can be measured for the ground +states of nuclei is the atomic mass $M(N, Z)$ of the neutral atom with +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). + +Atomic masses are usually tabulated in terms of the mass excess defined by +!bt +\[ +\Delta M(N, Z) = M(N, Z) - uA, +\] +!et +where $u$ is the Atomic Mass Unit +!bt +\[ +u = M(^{12}\mathrm{C})/12 = 931.4940954(57) \hspace{0.1cm} \mathrm{MeV}/c^2. +\] +!et +The nucleon masses are +!bt +\[ +m_p = 1.00727646693(9)u, +\] +!et +and +!bt +\[ +m_n = 939.56536(8)\hspace{0.1cm} \mathrm{MeV}/c^2 = 1.0086649156(6)u. +\] +!et + +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" +there are data on masses and decays of 3437 nuclei. + +The nuclear binding energy is defined as the energy required to break +up a given nucleus into its constituent parts of $N$ neutrons and $Z$ +protons. In terms of the atomic masses $M(N, Z)$ the binding energy is +defined by + + +!bt +\[ +BE(N, Z) = ZM_H c^2 + Nm_n c^2 - M(N, Z)c^2 , +\] +!et +where $M_H$ is the mass of the hydrogen atom and $m_n$ is the mass of the neutron. +In terms of the mass excess the binding energy is given by +!bt +\[ +BE(N, Z) = Z\Delta_H c^2 + N\Delta_n c^2 -\Delta(N, Z)c^2 , +\] +!et +where $\Delta_H c^2 = 7.2890$ MeV and $\Delta_n c^2 = 8.0713$ MeV. + + +A popular and physically intuitive model which can be used to parametrize +the experimental binding energies as function of $A$, is the so-called +_liquid drop model_. The ansatz is based on the following expression + +!bt +\[ +BE(N,Z) = a_1A-a_2A^{2/3}-a_3\frac{Z^2}{A^{1/3}}-a_4\frac{(N-Z)^2}{A}, +\] +!et + +where $A$ stands for the number of nucleons and the $a_i$s are parameters which are determined by a fit +to the experimental data. +To arrive at the above expression we have assumed that we can make the following assumptions: + + * 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. + + * 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. + * 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. -===== Polynomial Regression ===== + * 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. + +We could also add a so-called pairing term, which is a correction term that +arises from the tendency of proton pairs and neutron pairs to +occur. An even number of particles is more stable than an odd number. + + +=== Organizing our data === + +Let us start with reading and organizing our data. +We start with the compilation of masses and binding energies from 2016. +After having downloaded this file to our own computer, we are now ready to read the file and start structuring our data. + + +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_. !bc pycod -# Importing various packages -from math import exp, sqrt -from random import random, seed +# Common imports import numpy as np +import pandas as pd import matplotlib.pyplot as plt +import sklearn.linear_model as skl +from sklearn.model_selection import train_test_split +from sklearn.metrics import mean_squared_error, r2_score, mean_absolute_error +import os -m = 100 -x = 2*np.random.rand(m,1)+4. -y = 4+3*x*x+ +x-np.random.randn(m,1) +# Where to save the figures and data files +PROJECT_ROOT_DIR = "Results" +FIGURE_ID = "Results/FigureFiles" +DATA_ID = "DataFiles/" -xb = np.c_[np.ones((m,1)), x] -theta = np.linalg.inv(xb.T.dot(xb)).dot(xb.T).dot(y) -xnew = np.array([[0],[2]]) -xbnew = np.c_[np.ones((2,1)), xnew] -ypredict = xbnew.dot(theta) +if not os.path.exists(PROJECT_ROOT_DIR): + os.mkdir(PROJECT_ROOT_DIR) -plt.plot(xnew, ypredict, "r-") -plt.plot(x, y ,'ro') -plt.axis([0,2.0,0, 15.0]) -plt.xlabel(r'$x$') -plt.ylabel(r'$y$') -plt.title(r'Random numbers ') +if not os.path.exists(FIGURE_ID): + os.makedirs(FIGURE_ID) + +if not os.path.exists(DATA_ID): + os.makedirs(DATA_ID) + +def image_path(fig_id): + return os.path.join(FIGURE_ID, fig_id) + +def data_path(dat_id): + return os.path.join(DATA_ID, dat_id) + +def save_fig(fig_id): + plt.savefig(image_path(fig_id) + ".png", format='png') + +infile = open(data_path("MassEval2016.dat"),'r') +!ec + + +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. +!bc pycod +from pylab import plt, mpl +plt.style.use('seaborn') +mpl.rcParams['font.family'] = 'serif' + +def MakePlot(x,y, styles, labels, axlabels): + plt.figure(figsize=(10,6)) + for i in range(len(x)): + plt.plot(x[i], y[i], styles[i], label = labels[i]) + plt.xlabel(axlabels[0]) + plt.ylabel(axlabels[1]) + plt.legend(loc=0) +!ec + +Our next step is to read the data on experimental binding energies and +reorganize them as functions of the mass number $A$, the number of +protons $Z$ and neutrons $N$ using _pandas_. Before we do this it is +always useful (unless you have a binary file or other types of compressed +data) to actually open the file and simply take a look at it! + + +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. +!bc pycod +""" +This is taken from the data file of the mass 2016 evaluation. +All files are 3436 lines long with 124 character per line. + Headers are 39 lines long. + col 1 : Fortran character control: 1 = page feed 0 = line feed + 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 + These formats are reflected in the pandas widths variable below, see the statement + widths=(1,3,5,5,5,1,3,4,1,13,11,11,9,1,2,11,9,1,3,1,12,11,1), + Pandas has also a variable header, with length 39 in this case. +""" +!ec + +The data we are interested in are in columns 2, 3, 4 and 11, giving us +the number of neutrons, protons, mass numbers and binding energies, +respectively. We add also for the sake of completeness the element name. The data are in fixed-width formatted lines and we will +covert them into the _pandas_ DataFrame structure. + +!bc pycod +# Read the experimental data with Pandas +Masses = pd.read_fwf(infile, usecols=(2,3,4,6,11), + names=('N', 'Z', 'A', 'Element', 'Ebinding'), + widths=(1,3,5,5,5,1,3,4,1,13,11,11,9,1,2,11,9,1,3,1,12,11,1), + header=39, + index_col=False) + +# Extrapolated values are indicated by '#' in place of the decimal place, so +# the Ebinding column won't be numeric. Coerce to float and drop these entries. +Masses['Ebinding'] = pd.to_numeric(Masses['Ebinding'], errors='coerce') +Masses = Masses.dropna() +# Convert from keV to MeV. +Masses['Ebinding'] /= 1000 + +# Group the DataFrame by nucleon number, A. +Masses = Masses.groupby('A') +# Find the rows of the grouped DataFrame with the maximum binding energy. +Masses = Masses.apply(lambda t: t[t.Ebinding==t.Ebinding.max()]) +!ec + +We have now read in the data, grouped them according to the variables we are interested in. +We see how easy it is to reorganize the data using _pandas_. If we +were to do these operations in C/C++ or Fortran, we would have had to +write various functions/subroutines which perform the above +reorganizations for us. Having reorganized the data, we can now start +to make some simple fits using both the functionalities in _numpy_ and +_Scikit-Learn_ afterwards. + +Now we define five variables which contain +the number of nucleons $A$, the number of protons $Z$ and the number of neutrons $N$, the element name and finally the energies themselves. +!bc pycod +A = Masses['A'] +Z = Masses['Z'] +N = Masses['N'] +Element = Masses['Element'] +Energies = Masses['Ebinding'] +print(Masses) +!ec +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 $\bm{X}$. +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. +!bc pycod +# Now we set up the design matrix X +X = np.zeros((len(A),5)) +X[:,0] = 1 +X[:,1] = A +X[:,2] = A**(2.0/3.0) +X[:,3] = A**(-1.0/3.0) +X[:,4] = A**(-1.0) +!ec +With _scikitlearn_ we are now ready to use linear regression and fit our data. +!bc pycod +clf = skl.LinearRegression().fit(X, Energies) +fity = clf.predict(X) +!ec +Pretty simple! +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. +!bc pycod +# The mean squared error +print("Mean squared error: %.2f" % mean_squared_error(Energies, fity)) +# Explained variance score: 1 is perfect prediction +print('Variance score: %.2f' % r2_score(Energies, fity)) +# Mean absolute error +print('Mean absolute error: %.2f' % mean_absolute_error(Energies, fity)) +print(clf.coef_, clf.intercept_) + +Masses['Eapprox'] = fity +# Generate a plot comparing the experimental with the fitted values values. +fig, ax = plt.subplots() +ax.set_xlabel(r'$A = N + Z$') +ax.set_ylabel(r'$E_\mathrm{bind}\,/\mathrm{MeV}$') +ax.plot(Masses['A'], Masses['Ebinding'], alpha=0.7, lw=2, + label='Ame2016') +ax.plot(Masses['A'], Masses['Eapprox'], alpha=0.7, lw=2, c='m', + label='Fit') +ax.legend() +save_fig("Masses2016") plt.show() +!ec + + +=== Seeing the wood for the trees === + +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_! + + +!bc pycod + +#Decision Tree Regression +from sklearn.tree import DecisionTreeRegressor +regr_1=DecisionTreeRegressor(max_depth=5) +regr_2=DecisionTreeRegressor(max_depth=7) +regr_3=DecisionTreeRegressor(max_depth=9) +regr_1.fit(X, Energies) +regr_2.fit(X, Energies) +regr_3.fit(X, Energies) + + +y_1 = regr_1.predict(X) +y_2 = regr_2.predict(X) +y_3=regr_3.predict(X) +Masses['Eapprox'] = y_3 +# Plot the results +plt.figure() +plt.plot(A, Energies, color="blue", label="Data", linewidth=2) +plt.plot(A, y_1, color="red", label="max_depth=5", linewidth=2) +plt.plot(A, y_2, color="green", label="max_depth=7", linewidth=2) +plt.plot(A, y_3, color="m", label="max_depth=9", linewidth=2) + +plt.xlabel("$A$") +plt.ylabel("$E$[MeV]") +plt.title("Decision Tree Regression") +plt.legend() +save_fig("Masses2016Trees") +plt.show() +print(Masses) +print(np.mean( (Energies-y_1)**2)) +!ec + + +=== And what about using neural networks? === +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) +functionality. +!bc pycod +from sklearn.neural_network import MLPRegressor +from sklearn.metrics import accuracy_score +import seaborn as sns + +X_train = X +Y_train = Energies +n_hidden_neurons = 100 +epochs = 100 +# store models for later use +eta_vals = np.logspace(-5, 1, 7) +lmbd_vals = np.logspace(-5, 1, 7) +# store the models for later use +DNN_scikit = np.zeros((len(eta_vals), len(lmbd_vals)), dtype=object) +train_accuracy = np.zeros((len(eta_vals), len(lmbd_vals))) +sns.set() +for i, eta in enumerate(eta_vals): + for j, lmbd in enumerate(lmbd_vals): + dnn = MLPRegressor(hidden_layer_sizes=(n_hidden_neurons), activation='logistic', + alpha=lmbd, learning_rate_init=eta, max_iter=epochs) + dnn.fit(X_train, Y_train) + DNN_scikit[i][j] = dnn + train_accuracy[i][j] = dnn.score(X_train, Y_train) + +fig, ax = plt.subplots(figsize = (10, 10)) +sns.heatmap(train_accuracy, annot=True, ax=ax, cmap="viridis") +ax.set_title("Training Accuracy") +ax.set_ylabel("$\eta$") +ax.set_xlabel("$\lambda$") +plt.show() + + !ec + + + + + +===== A first summary ===== + +The aim behind these introductory words was to present to you various +Python libraries and their functionalities, in particular libraries like +_numpy_, _pandas_, _xarray_ and _matplotlib_ and other that make our life much easier +in handling various data sets and visualizing data. + +Furthermore, +_Scikit-Learn_ allows us with few lines of code to implement popular +Machine Learning algorithms for supervised learning. Later we will meet _Tensorflow_, a powerful library for deep learning. +Now it is time to dive more into the details of various methods. We will start with linear regression and try to take a deeper look at what it entails. + + + + -===== Linking the regression analysis with a statistical interpretation ===== -Before we proceed, and to link with our discussions of Bayesian statistics to come, it is useful the derive the standard regression analysis equations using a statistical interpretation. This allows us also to derive quantities like the variance and other expectation values in a rather straightforward way. -It is assumed that $\varepsilon_i -\sim \mathcal{N}(0, \sigma^2)$ and the $\varepsilon_{i}$ are -independent, i.e.: + +======= Why Linear Regression (aka Ordinary Least Squares and family) ======= + +Fitting a continuous function with linear parameterization in terms of the parameters $\bm{\beta}$. +* Method of choice for fitting a continuous function! +* Gives an excellent introduction to central Machine Learning features with _understandable pedagogical_ links to other methods like _Neural Networks_, _Support Vector Machines_ etc +* Analytical expression for the fitting parameters $\bm{\beta}$ +* Analytical expressions for statistical propertiers like mean values, variances, confidence intervals and more +* Analytical relation with probabilistic interpretations +* Easy to introduce basic concepts like bias-variance tradeoff, cross-validation, resampling and regularization techniques and many other ML topics +* Easy to code! And links well with classification problems and logistic regression and neural networks +* Allows for _easy_ hands-on understanding of gradient descent methods +* and many more features + +For more discussions of Ridge and Lasso regression, "Wessel van Wieringen's":"https://arxiv.org/abs/1509.09169" article is highly recommended. +Similarly, "Mehta et al's article":"https://arxiv.org/abs/1803.08823" is also recommended. + + +=== Regression analysis, overarching aims === + +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 $\bm{x} =[x_0, x_1,\dots, x_{n-1}]^T$. +The first variable is called the _dependent_, the _outcome_ or the _response_ variable while the set of variables $\bm{x}$ is called the independent variable, or the predictor variable or the explanatory variable. + +A regression model aims at finding a likelihood function $p(\bm{y}\vert \bm{x})$, that is the conditional distribution for $\bm{y}$ with a given $\bm{x}$. The estimation of $p(\bm{y}\vert \bm{x})$ is made using a data set with +* $n$ cases $i = 0, 1, 2, \dots, n-1$ +* Response (target, dependent or outcome) variable $y_i$ with $i = 0, 1, 2, \dots, n-1$ +* $p$ so-called explanatory (independent or predictor) variables $\bm{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. + The goal of the regression analysis is to extract/exploit relationship between $\bm{y}$ and $\bm{X}$ in or to infer causal dependencies, approximations to the likelihood functions, functional relationships and to make predictions, making fits and many other things. + + +Consider an experiment in which $p$ characteristics of $n$ samples are +measured. The data from this experiment, for various explanatory variables $p$ are normally represented by a matrix +$\mathbf{X}$. + +The matrix $\mathbf{X}$ is called the *design +matrix*. Additional information of the samples is available in the +form of $\bm{y}$ (also as above). The variable $\bm{y}$ is +generally referred to as the *response variable*. The aim of +regression analysis is to explain $\bm{y}$ in terms of +$\bm{X}$ through a functional relationship like $y_i = +f(\mathbf{X}_{i,\ast})$. When no prior knowledge on the form of +$f(\cdot)$ is available, it is common to assume a linear relationship +between $\bm{X}$ and $\bm{y}$. This assumption gives rise to +the *linear regression model* where $\bm{\beta} = [\beta_0, \ldots, +\beta_{p-1}]^{T}$ are the *regression parameters*. + +Linear regression gives us a set of analytical equations for the parameters $\beta_j$. + + +=== Examples === + +In order to understand the relation among the predictors $p$, the set of data $n$ and the target (outcome, output etc) $\bm{y}$, +consider the model we discussed for describing nuclear binding energies. + +There we assumed that we could parametrize the data using a polynomial approximation based on the liquid drop model. +Assuming !bt -\begin{align*} -\mbox{Cov}(\varepsilon_{i_1}, -\varepsilon_{i_2}) & = \left\{ \begin{array}{lcc} \sigma^2 & \mbox{if} -& i_1 = i_2, \\ 0 & \mbox{if} & i_1 \not= i_2. \end{array} \right. -\end{align*} +\[ +BE(A) = a_0+a_1A+a_2A^{2/3}+a_3A^{-1/3}+a_4A^{-1}, +\] !et -The randomness of $\varepsilon_i$ implies that -$\mathbf{Y}_i$ is also a random variable. In particular, -$\mathbf{Y}_i$ is normally distributed, because $\varepsilon_i \sim -\mathcal{N}(0, \sigma^2)$ and $\mathbf{X}_{i,\ast} \, \beta$ is a -non-random scalar. To specify the parameters of the distribution of -$\mathbf{Y}_i$ we need to calculate its first two moments. +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. +This gives $p=0,1,2,3,4$. Furthermore we have $n$ entries for each predictor. It means that our design matrix is a +$p\times n$ matrix $\bm{X}$. + +Here the predictors are based on a model we have made. A popular data set which is widely encountered in ML applications is the +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$ -===== Expectation value and variance ===== +===== General linear models ===== -Its expectation equals: +Before we proceed let us study a case from linear algebra where we aim at fitting a set of data $\bm{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 $\bm{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. + +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 !bt -\begin{align*} -\mathbb{E}(Y_i) & = -\mathbb{E}(\mathbf{X}_{i, \ast} \, \beta) + \mathbb{E}(\varepsilon_i) -\, \, \, = \, \, \, \mathbf{X}_{i, \ast} \, \beta, -\end{align*} +\[ +y=y(x) \rightarrow y(x_i)=\tilde{y}_i+\epsilon_i=\sum_{j=0}^{n-1} \beta_j x_i^j+\epsilon_i, +\] !et -while -its variance is +where $\epsilon_i$ is the error in our approximation. + + +For every set of values $y_i,x_i$ we have thus the corresponding set of equations !bt -\begin{align*} \mbox{Var}(Y_i) & = \mathbb{E} \{ [Y_i -- \mathbb{E}(Y_i)]^2 \} \, \, \, = \, \, \, \mathbb{E} ( Y_i^2 ) - -[\mathbb{E}(Y_i)]^2 \\ & = \mathbb{E} [ ( \mathbf{X}_{i, \ast} \, -\beta + \varepsilon_i )^2] - ( \mathbf{X}_{i, \ast} \, \beta)^2 \\ & -= \mathbb{E} [ ( \mathbf{X}_{i, \ast} \, \beta)^2 + 2 \varepsilon_i -\mathbf{X}_{i, \ast} \, \beta + \varepsilon_i^2 ] - ( \mathbf{X}_{i, -\ast} \, \beta)^2 \\ & = ( \mathbf{X}_{i, \ast} \, \beta)^2 + 2 -\mathbb{E}(\varepsilon_i) \mathbf{X}_{i, \ast} \, \beta + -\mathbb{E}(\varepsilon_i^2 ) - ( \mathbf{X}_{i, \ast} \, \beta)^2 -\\ & = \mathbb{E}(\varepsilon_i^2 ) \, \, \, = \, \, \, -\mbox{Var}(\varepsilon_i) \, \, \, = \, \, \, \sigma^2. +\begin{align*} +y_0&=\beta_0+\beta_1x_0^1+\beta_2x_0^2+\dots+\beta_{n-1}x_0^{n-1}+\epsilon_0\\ +y_1&=\beta_0+\beta_1x_1^1+\beta_2x_1^2+\dots+\beta_{n-1}x_1^{n-1}+\epsilon_1\\ +y_2&=\beta_0+\beta_1x_2^1+\beta_2x_2^2+\dots+\beta_{n-1}x_2^{n-1}+\epsilon_2\\ +\dots & \dots \\ +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}.\\ \end{align*} !et -Hence, $Y_i \sim \mathcal{N}( \mathbf{X}_{i, \ast} \, \beta, \sigma^2)$. - - - - - -===== The singular value decompostion ===== - - - -A general -$m\times n$ matrix $\hat{A}$ can be written in terms of a diagonal -matrix $\hat{D}$ of dimensionality $n\times n$ and two orthognal -matrices $\hat{U}$ and $\hat{V}$, where the first has dimensionality -$m \times m$ and the last dimensionality $n\times n$. -We have then +Defining the vectors !bt -\[ -\hat{A} = \hat{U}\hat{D}\hat{V}^T -\] -!et +\[ +\bm{y} = [y_0,y_1, y_2,\dots, y_{n-1}]^T, +\] +!et +and +!bt +\[ +\bm{\beta} = [\beta_0,\beta_1, \beta_2,\dots, \beta_{n-1}]^T, +\] +!et +and +!bt +\[ +\bm{\epsilon} = [\epsilon_0,\epsilon_1, \epsilon_2,\dots, \epsilon_{n-1}]^T, +\] +!et +and the design matrix +!bt +\[ +\bm{X}= +\begin{bmatrix} +1& x_{0}^1 &x_{0}^2& \dots & \dots &x_{0}^{n-1}\\ +1& x_{1}^1 &x_{1}^2& \dots & \dots &x_{1}^{n-1}\\ +1& x_{2}^1 &x_{2}^2& \dots & \dots &x_{2}^{n-1}\\ +\dots& \dots &\dots& \dots & \dots &\dots\\ +1& x_{n-1}^1 &x_{n-1}^2& \dots & \dots &x_{n-1}^{n-1}\\ +\end{bmatrix} +\] +!et +we can rewrite our equations as +!bt +\[ +\bm{y} = \bm{X}\bm{\beta}+\bm{\epsilon}. +\] +!et +The above design matrix is called a "Vandermonde matrix":"https://en.wikipedia.org/wiki/Vandermonde_matrix". +===== Generalizing the fitting procedure as a linear algebra problem ===== + +We are obviously not limited to the above polynomial expansions. We +could replace the various powers of $x$ with elements of Fourier +series or instead of $x_i^j$ we could have $\cos{(j x_i)}$ or $\sin{(j +x_i)}$, or time series or other orthogonal functions. For every set +of values $y_i,x_i$ we can then generalize the equations to + +!bt +\begin{align*} +y_0&=\beta_0x_{00}+\beta_1x_{01}+\beta_2x_{02}+\dots+\beta_{n-1}x_{0n-1}+\epsilon_0\\ +y_1&=\beta_0x_{10}+\beta_1x_{11}+\beta_2x_{12}+\dots+\beta_{n-1}x_{1n-1}+\epsilon_1\\ +y_2&=\beta_0x_{20}+\beta_1x_{21}+\beta_2x_{22}+\dots+\beta_{n-1}x_{2n-1}+\epsilon_2\\ +\dots & \dots \\ +y_{i}&=\beta_0x_{i0}+\beta_1x_{i1}+\beta_2x_{i2}+\dots+\beta_{n-1}x_{in-1}+\epsilon_i\\ +\dots & \dots \\ +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}.\\ +\end{align*} +!et + +_Note that we have $p=n$ here. The matrix is symmetric. This is generally not the case!_ + +We redefine in turn the matrix $\bm{X}$ as +!bt +\[ +\bm{X}= +\begin{bmatrix} +x_{00}& x_{01} &x_{02}& \dots & \dots &x_{0,n-1}\\ +x_{10}& x_{11} &x_{12}& \dots & \dots &x_{1,n-1}\\ +x_{20}& x_{21} &x_{22}& \dots & \dots &x_{2,n-1}\\ +\dots& \dots &\dots& \dots & \dots &\dots\\ +x_{n-1,0}& x_{n-1,1} &x_{n-1,2}& \dots & \dots &x_{n-1,n-1}\\ +\end{bmatrix} +\] +!et +and without loss of generality we rewrite again our equations as +!bt +\[ +\bm{y} = \bm{X}\bm{\beta}+\bm{\epsilon}. +\] +!et +The left-hand side of this equation is kwown. Our error vector $\bm{\epsilon}$ and the parameter vector $\bm{\beta}$ are our unknow quantities. How can we obtain the optimal set of $\beta_i$ values? + +We have defined the matrix $\bm{X}$ via the equations +!bt +\begin{align*} +y_0&=\beta_0x_{00}+\beta_1x_{01}+\beta_2x_{02}+\dots+\beta_{n-1}x_{0n-1}+\epsilon_0\\ +y_1&=\beta_0x_{10}+\beta_1x_{11}+\beta_2x_{12}+\dots+\beta_{n-1}x_{1n-1}+\epsilon_1\\ +y_2&=\beta_0x_{20}+\beta_1x_{21}+\beta_2x_{22}+\dots+\beta_{n-1}x_{2n-1}+\epsilon_1\\ +\dots & \dots \\ +y_{i}&=\beta_0x_{i0}+\beta_1x_{i1}+\beta_2x_{i2}+\dots+\beta_{n-1}x_{in-1}+\epsilon_1\\ +\dots & \dots \\ +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}.\\ +\end{align*} +!et + +As we noted above, we stayed with a system with the design matrix + $\bm{X}\in {\mathbb{R}}^{n\times n}$, that is we have $p=n$. For reasons to come later (algorithmic arguments) we will hereafter define +our matrix as $\bm{X}\in {\mathbb{R}}^{n\times p}$, with the predictors refering to the column numbers and the entries $n$ being the row elements. + + +===== Our model for the nuclear binding energies ===== + +In our introductory notes we looked at the so-called "liguid drop model":"https://en.wikipedia.org/wiki/Semi-empirical_mass_formula". Let us remind ourselves about what we did by looking at the code. + +We restate the parts of the code we are most interested in. +!bc pycod +# Common imports +import numpy as np +import pandas as pd +import matplotlib.pyplot as plt +from IPython.display import display +import os + +# Where to save the figures and data files +PROJECT_ROOT_DIR = "Results" +FIGURE_ID = "Results/FigureFiles" +DATA_ID = "DataFiles/" + +if not os.path.exists(PROJECT_ROOT_DIR): + os.mkdir(PROJECT_ROOT_DIR) + +if not os.path.exists(FIGURE_ID): + os.makedirs(FIGURE_ID) + +if not os.path.exists(DATA_ID): + os.makedirs(DATA_ID) + +def image_path(fig_id): + return os.path.join(FIGURE_ID, fig_id) + +def data_path(dat_id): + return os.path.join(DATA_ID, dat_id) + +def save_fig(fig_id): + plt.savefig(image_path(fig_id) + ".png", format='png') + +infile = open(data_path("MassEval2016.dat"),'r') + + +# Read the experimental data with Pandas +Masses = pd.read_fwf(infile, usecols=(2,3,4,6,11), + names=('N', 'Z', 'A', 'Element', 'Ebinding'), + widths=(1,3,5,5,5,1,3,4,1,13,11,11,9,1,2,11,9,1,3,1,12,11,1), + header=39, + index_col=False) + +# Extrapolated values are indicated by '#' in place of the decimal place, so +# the Ebinding column won't be numeric. Coerce to float and drop these entries. +Masses['Ebinding'] = pd.to_numeric(Masses['Ebinding'], errors='coerce') +Masses = Masses.dropna() +# Convert from keV to MeV. +Masses['Ebinding'] /= 1000 + +# Group the DataFrame by nucleon number, A. +Masses = Masses.groupby('A') +# Find the rows of the grouped DataFrame with the maximum binding energy. +Masses = Masses.apply(lambda t: t[t.Ebinding==t.Ebinding.max()]) +A = Masses['A'] +Z = Masses['Z'] +N = Masses['N'] +Element = Masses['Element'] +Energies = Masses['Ebinding'] + +# Now we set up the design matrix X +X = np.zeros((len(A),5)) +X[:,0] = 1 +X[:,1] = A +X[:,2] = A**(2.0/3.0) +X[:,3] = A**(-1.0/3.0) +X[:,4] = A**(-1.0) +# Then nice printout using pandas +DesignMatrix = pd.DataFrame(X) +DesignMatrix.index = A +DesignMatrix.columns = ['1', 'A', 'A^(2/3)', 'A^(-1/3)', '1/A'] +display(DesignMatrix) +!ec + +With $\bm{\beta}\in {\mathbb{R}}^{p\times 1}$, it means that we will hereafter write our equations for the approximation as +!bt +\[ +\bm{\tilde{y}}= \bm{X}\bm{\beta}, +\] +!et +throughout these lectures. + + + +With the above we use the design matrix to define the approximation $\bm{\tilde{y}}$ via the unknown quantity $\bm{\beta}$ as +!bt +\[ +\bm{\tilde{y}}= \bm{X}\bm{\beta}, +\] +!et +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 +!bt +\[ +C(\bm{\beta})=\frac{1}{n}\sum_{i=0}^{n-1}\left(y_i-\tilde{y}_i\right)^2=\frac{1}{n}\left\{\left(\bm{y}-\bm{\tilde{y}}\right)^T\left(\bm{y}-\bm{\tilde{y}}\right)\right\}, +\] +!et +or using the matrix $\bm{X}$ and in a more compact matrix-vector notation as +!bt +\[ +C(\bm{\beta})=\frac{1}{n}\left\{\left(\bm{y}-\bm{X}^T\bm{\beta}\right)^T\left(\bm{y}-\bm{X}^T\bm{\beta}\right)\right\}. +\] +!et +This function is one possible way to define the so-called cost function. + + + +It is also common to define +the function $Q$ as + +!bt +\[ +C(\bm{\beta})=\frac{1}{2n}\sum_{i=0}^{n-1}\left(y_i-\tilde{y}_i\right)^2, +\] +!et +since when taking the first derivative with respect to the unknown parameters $\beta$, the factor of $2$ cancels out. +===== Interpretations and optimizing our parameters ===== + + +The function +!bt +\[ +C(\bm{\beta})=\frac{1}{n}\left\{\left(\bm{y}-\bm{X}\bm{\beta}\right)^T\left(\bm{y}-\bm{X}\bm{\beta}\right)\right\}, +\] +!et +can be linked to the variance of the quantity $y_i$ if we interpret the latter as the mean value. +When linking below with the maximum likelihood approach below, we will indeed interpret $y_i$ as a mean value (see exercises) +!bt +\[ +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, +\] +!et + +where $\langle y_i \rangle$ is the mean value. Keep in mind also that +till now we have treated $y_i$ as the exact value. Normally, the +response (dependent or outcome) variable $y_i$ the outcome of a +numerical experiment or another type of experiment and is thus only an +approximation to the true value. It is then always accompanied by an +error estimate, often limited to a statistical error estimate given by +the standard deviation discussed earlier. In the discussion here we +will treat $y_i$ as our exact value for the response variable. + +In order to find the parameters $\beta_i$ we will then minimize the spread of $C(\bm{\beta})$, that is we are going to solve the problem +!bt +\[ +{\displaystyle \min_{\bm{\beta}\in +{\mathbb{R}}^{p}}}\frac{1}{n}\left\{\left(\bm{y}-\bm{X}\bm{\beta}\right)^T\left(\bm{y}-\bm{X}\bm{\beta}\right)\right\}. +\] +!et +In practical terms it means we will require +!bt +\[ +\frac{\partial C(\bm{\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, +\] +!et +which results in +!bt +\[ +\frac{\partial C(\bm{\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, +\] +!et +or in a matrix-vector form as +!bt +\[ +\frac{\partial C(\bm{\beta})}{\partial \bm{\beta}} = 0 = \bm{X}^T\left( \bm{y}-\bm{X}\bm{\beta}\right). +\] +!et +We can rewrite +!bt +\[ +\frac{\partial C(\bm{\beta})}{\partial \bm{\beta}} = 0 = \bm{X}^T\left( \bm{y}-\bm{X}\bm{\beta}\right), +\] +!et +as +!bt +\[ +\bm{X}^T\bm{y} = \bm{X}^T\bm{X}\bm{\beta}, +\] +!et +and if the matrix $\bm{X}^T\bm{X}$ is invertible we have the solution +!bt +\[ +\bm{\beta} =\left(\bm{X}^T\bm{X}\right)^{-1}\bm{X}^T\bm{y}. +\] +!et + +We note also that since our design matrix is defined as $\bm{X}\in +{\mathbb{R}}^{n\times p}$, the product $\bm{X}^T\bm{X} \in +{\mathbb{R}}^{p\times p}$. In the above case we have that $p \ll n$, +in our case $p=5$ meaning that we end up with inverting a small +$5\times 5$ matrix. This is a rather common situation, in many cases we end up with low-dimensional +matrices to invert. The methods discussed here and for many other +supervised learning algorithms like classification with logistic +regression or support vector machines, exhibit dimensionalities which +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 +$\bm{X}^T\bm{X}$. +The residuals $\bm{\epsilon}$ are in turn given by +!bt +\[ +\bm{\epsilon} = \bm{y}-\bm{\tilde{y}} = \bm{y}-\bm{X}\bm{\beta}, +\] +!et +and with +!bt +\[ +\bm{X}^T\left( \bm{y}-\bm{X}\bm{\beta}\right)= 0, +\] +!et +we have +!bt +\[ +\bm{X}^T\bm{\epsilon}=\bm{X}^T\left( \bm{y}-\bm{X}\bm{\beta}\right)= 0, +\] +!et +meaning that the solution for $\bm{\beta}$ is the one which minimizes the residuals. Later we will link this with the maximum likelihood approach. + + +Let us now return to our nuclear binding energies and simply code the above equations. + +It is rather straightforward to implement the matrix inversion and obtain the parameters $\bm{\beta}$. After having defined the matrix $\bm{X}$ we simply need to +write +!bc pycod +# matrix inversion to find beta +beta = np.linalg.inv(X.T.dot(X)).dot(X.T).dot(Energies) +# and then make the prediction +ytilde = X @ beta +!ec +Alternatively, you can use the least squares functionality in _Numpy_ as +!bc pycod +fit = np.linalg.lstsq(X, Energies, rcond =None)[0] +ytildenp = np.dot(fit,X.T) +!ec + +And finally we plot our fit with and compare with data +!bc pycod +Masses['Eapprox'] = ytilde +# Generate a plot comparing the experimental with the fitted values values. +fig, ax = plt.subplots() +ax.set_xlabel(r'$A = N + Z$') +ax.set_ylabel(r'$E_\mathrm{bind}\,/\mathrm{MeV}$') +ax.plot(Masses['A'], Masses['Ebinding'], alpha=0.7, lw=2, + label='Ame2016') +ax.plot(Masses['A'], Masses['Eapprox'], alpha=0.7, lw=2, c='m', + label='Fit') +ax.legend() +save_fig("Masses2016OLS") +plt.show() +!ec + +===== Adding error analysis and training set up ===== + +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. +Since we are not using _Scikit-Learn here we can define our own $R2$ function as +!bc pycod +def R2(y_data, y_model): + return 1 - np.sum((y_data - y_model) ** 2) / np.sum((y_data - np.mean(y_model)) ** 2) +!ec +and we would be using it as +!bc pycod +print(R2(Energies,ytilde)) +!ec + +We can easily add our _MSE_ score as +!bc pycod +def MSE(y_data,y_model): + n = np.size(y_model) + return np.sum((y_data-y_model)**2)/n + +print(MSE(Energies,ytilde)) +!ec +and finally the relative error as +!bc pycod +def RelativeError(y_data,y_model): + return abs((y_data-y_model)/y_data) +print(RelativeError(Energies, ytilde)) +!ec -===== From standard regression to Ridge regressions ===== +===== The $\chi^2$ function ===== + +Normally, the response (dependent or outcome) variable $y_i$ is the +outcome of a numerical experiment or another type of experiment and is +thus only an approximation to the true value. It is then always +accompanied by an error estimate, often limited to a statistical error +estimate given by the standard deviation discussed earlier. In the +discussion here we will treat $y_i$ as our exact value for the +response variable. + +Introducing the standard deviation $\sigma_i$ for each measurement +$y_i$, we define now the $\chi^2$ function (omitting the $1/n$ term) +as + +!bt +\[ +\chi^2(\bm{\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(\bm{y}-\bm{\tilde{y}}\right)^T\frac{1}{\bm{\Sigma^2}}\left(\bm{y}-\bm{\tilde{y}}\right)\right\}, +\] +!et +where the matrix $\bm{\Sigma}$ is a diagonal matrix with $\sigma_i$ as matrix elements. + + +In order to find the parameters $\beta_i$ we will then minimize the spread of $\chi^2(\bm{\beta})$ by requiring +!bt +\[ +\frac{\partial \chi^2(\bm{\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, +\] +!et +which results in +!bt +\[ +\frac{\partial \chi^2(\bm{\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, +\] +!et +or in a matrix-vector form as +!bt +\[ +\frac{\partial \chi^2(\bm{\beta})}{\partial \bm{\beta}} = 0 = \bm{A}^T\left( \bm{b}-\bm{A}\bm{\beta}\right). +\] +!et +where we have defined the matrix $\bm{A} =\bm{X}/\bm{\Sigma}$ with matrix elements $a_{ij} = x_{ij}/\sigma_i$ and the vector $\bm{b}$ with elements $b_i = y_i/\sigma_i$. + +We can rewrite +!bt +\[ +\frac{\partial \chi^2(\bm{\beta})}{\partial \bm{\beta}} = 0 = \bm{A}^T\left( \bm{b}-\bm{A}\bm{\beta}\right), +\] +!et +as +!bt +\[ +\bm{A}^T\bm{b} = \bm{A}^T\bm{A}\bm{\beta}, +\] +!et +and if the matrix $\bm{A}^T\bm{A}$ is invertible we have the solution +!bt +\[ +\bm{\beta} =\left(\bm{A}^T\bm{A}\right)^{-1}\bm{A}^T\bm{b}. +\] +!et + +If we then introduce the matrix +!bt +\[ +\bm{H} = \left(\bm{A}^T\bm{A}\right)^{-1}, +\] +!et +we have then the following expression for the parameters $\beta_j$ (the matrix elements of $\bm{H}$ are $h_{ij}$) +!bt +\[ +\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} +\] +!et +We state without proof the expression for the uncertainty in the parameters $\beta_j$ as (we leave this as an exercise) +!bt +\[ +\sigma^2(\beta_j) = \sum_{i=0}^{n-1}\sigma_i^2\left( \frac{\partial \beta_j}{\partial y_i}\right)^2, +\] +!et +resulting in +!bt +\[ +\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}! +\] +!et + +The first step here is to approximate the function $y$ with a first-order polynomial, that is we write +!bt +\[ +y=y(x) \rightarrow y(x_i) \approx \beta_0+\beta_1 x_i. +\] +!et +By computing the derivatives of $\chi^2$ with respect to $\beta_0$ and $\beta_1$ show that these are given by +!bt +\[ +\frac{\partial \chi^2(\bm{\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, +\] +!et +and +!bt +\[ +\frac{\partial \chi^2(\bm{\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. +\] +!et + +For a linear fit (a first-order polynomial) we don't need to invert a matrix!! +Defining +!bt +\[ +\gamma = \sum_{i=0}^{n-1}\frac{1}{\sigma_i^2}, +\] +!et + +!bt +\[ +\gamma_x = \sum_{i=0}^{n-1}\frac{x_{i}}{\sigma_i^2}, +\] +!et + +!bt +\[ +\gamma_y = \sum_{i=0}^{n-1}\left(\frac{y_i}{\sigma_i^2}\right), +\] +!et + +!bt +\[ +\gamma_{xx} = \sum_{i=0}^{n-1}\frac{x_ix_{i}}{\sigma_i^2}, +\] +!et + +!bt +\[ +\gamma_{xy} = \sum_{i=0}^{n-1}\frac{y_ix_{i}}{\sigma_i^2}, +\] +!et + +we obtain + +!bt +\[ +\beta_0 = \frac{\gamma_{xx}\gamma_y-\gamma_x\gamma_y}{\gamma\gamma_{xx}-\gamma_x^2}, +\] +!et + +!bt +\[ +\beta_1 = \frac{\gamma_{xy}\gamma-\gamma_x\gamma_y}{\gamma\gamma_{xx}-\gamma_x^2}. +\] +!et + +This approach (different linear and non-linear regression) suffers +often from both being underdetermined and overdetermined in the +unknown coefficients $\beta_i$. A better approach is to use the +Singular Value Decomposition (SVD) method discussed below. Or using +Lasso and Ridge regression. See below. + + +===== Fitting an Equation of State for Dense Nuclear Matter ===== + +Before we continue, let us introduce yet another example. We are going to fit the +nuclear equation of state using results from many-body calculations. +The equation of state we have made available here, as function of +density, has been derived using modern nucleon-nucleon potentials with +"the addition of three-body +forces":"https://www.sciencedirect.com/science/article/pii/S0370157399001106". This +time the file is presented as a standard _csv_ file. + +The beginning of the Python code here is similar to what you have seen before, +with the same initializations and declarations. We use also _pandas_ +again, rather extensively in order to organize our data. + +The difference now is that we use _Scikit-Learn's_ regression tools +instead of our own matrix inversion implementation. Furthermore, we +sneak in _Ridge_ regression (to be discussed below) which includes a +hyperparameter $\lambda$, also to be explained below. + +!split +===== The code ===== + +!bc pycod +# Common imports +import os +import numpy as np +import pandas as pd +import matplotlib.pyplot as plt +import matplotlib.pyplot as plt +import sklearn.linear_model as skl +from sklearn.metrics import mean_squared_error, r2_score, mean_absolute_error + +# Where to save the figures and data files +PROJECT_ROOT_DIR = "Results" +FIGURE_ID = "Results/FigureFiles" +DATA_ID = "DataFiles/" + +if not os.path.exists(PROJECT_ROOT_DIR): + os.mkdir(PROJECT_ROOT_DIR) + +if not os.path.exists(FIGURE_ID): + os.makedirs(FIGURE_ID) + +if not os.path.exists(DATA_ID): + os.makedirs(DATA_ID) + +def image_path(fig_id): + return os.path.join(FIGURE_ID, fig_id) + +def data_path(dat_id): + return os.path.join(DATA_ID, dat_id) + +def save_fig(fig_id): + plt.savefig(image_path(fig_id) + ".png", format='png') + +infile = open(data_path("EoS.csv"),'r') + +# Read the EoS data as csv file and organize the data into two arrays with density and energies +EoS = pd.read_csv(infile, names=('Density', 'Energy')) +EoS['Energy'] = pd.to_numeric(EoS['Energy'], errors='coerce') +EoS = EoS.dropna() +Energies = EoS['Energy'] +Density = EoS['Density'] +# The design matrix now as function of various polytrops +X = np.zeros((len(Density),4)) +X[:,3] = Density**(4.0/3.0) +X[:,2] = Density +X[:,1] = Density**(2.0/3.0) +X[:,0] = 1 + +# We use now Scikit-Learn's linear regressor and ridge regressor +# OLS part +clf = skl.LinearRegression().fit(X, Energies) +ytilde = clf.predict(X) +EoS['Eols'] = ytilde +# The mean squared error +print("Mean squared error: %.2f" % mean_squared_error(Energies, ytilde)) +# Explained variance score: 1 is perfect prediction +print('Variance score: %.2f' % r2_score(Energies, ytilde)) +# Mean absolute error +print('Mean absolute error: %.2f' % mean_absolute_error(Energies, ytilde)) +print(clf.coef_, clf.intercept_) + +# The Ridge regression with a hyperparameter lambda = 0.1 +_lambda = 0.1 +clf_ridge = skl.Ridge(alpha=_lambda).fit(X, Energies) +yridge = clf_ridge.predict(X) +EoS['Eridge'] = yridge +# The mean squared error +print("Mean squared error: %.2f" % mean_squared_error(Energies, yridge)) +# Explained variance score: 1 is perfect prediction +print('Variance score: %.2f' % r2_score(Energies, yridge)) +# Mean absolute error +print('Mean absolute error: %.2f' % mean_absolute_error(Energies, yridge)) +print(clf_ridge.coef_, clf_ridge.intercept_) + +fig, ax = plt.subplots() +ax.set_xlabel(r'$\rho[\mathrm{fm}^{-3}]$') +ax.set_ylabel(r'Energy per particle') +ax.plot(EoS['Density'], EoS['Energy'], alpha=0.7, lw=2, + label='Theoretical data') +ax.plot(EoS['Density'], EoS['Eols'], alpha=0.7, lw=2, c='m', + label='OLS') +ax.plot(EoS['Density'], EoS['Eridge'], alpha=0.7, lw=2, c='g', + label='Ridge $\lambda = 0.1$') +ax.legend() +save_fig("EoSfitting") +plt.show() +!ec + +The above simple polynomial in density $\rho$ gives an excellent fit +to the data. +We note also that there is a small deviation between the +standard OLS and the Ridge regression at higher densities. We discuss this in more detail +below. + + +===== Splitting our Data in Training and Test data ===== + +It is normal in essentially all Machine Learning studies to split the +data in a training set and a test set (sometimes also an additional +validation set). _Scikit-Learn_ has an own function for this. There +is no explicit recipe for how much data should be included as training +data and say test data. An accepted rule of thumb is to use +approximately $2/3$ to $4/5$ of the data as training data. We will +postpone a discussion of this splitting to the end of these notes and +our discussion of the so-called _bias-variance_ tradeoff. Here we +limit ourselves to repeat the above equation of state fitting example +but now splitting the data into a training set and a test set. + +!bc pycod +import os +import numpy as np +import pandas as pd +import matplotlib.pyplot as plt +from sklearn.model_selection import train_test_split +# Where to save the figures and data files +PROJECT_ROOT_DIR = "Results" +FIGURE_ID = "Results/FigureFiles" +DATA_ID = "DataFiles/" + +if not os.path.exists(PROJECT_ROOT_DIR): + os.mkdir(PROJECT_ROOT_DIR) + +if not os.path.exists(FIGURE_ID): + os.makedirs(FIGURE_ID) + +if not os.path.exists(DATA_ID): + os.makedirs(DATA_ID) + +def image_path(fig_id): + return os.path.join(FIGURE_ID, fig_id) + +def data_path(dat_id): + return os.path.join(DATA_ID, dat_id) + +def save_fig(fig_id): + plt.savefig(image_path(fig_id) + ".png", format='png') + +def R2(y_data, y_model): + return 1 - np.sum((y_data - y_model) ** 2) / np.sum((y_data - np.mean(y_model)) ** 2) +def MSE(y_data,y_model): + n = np.size(y_model) + return np.sum((y_data-y_model)**2)/n + +infile = open(data_path("EoS.csv"),'r') + +# Read the EoS data as csv file and organized into two arrays with density and energies +EoS = pd.read_csv(infile, names=('Density', 'Energy')) +EoS['Energy'] = pd.to_numeric(EoS['Energy'], errors='coerce') +EoS = EoS.dropna() +Energies = EoS['Energy'] +Density = EoS['Density'] +# The design matrix now as function of various polytrops +X = np.zeros((len(Density),5)) +X[:,0] = 1 +X[:,1] = Density**(2.0/3.0) +X[:,2] = Density +X[:,3] = Density**(4.0/3.0) +X[:,4] = Density**(5.0/3.0) +# We split the data in test and training data +X_train, X_test, y_train, y_test = train_test_split(X, Energies, test_size=0.2) +# matrix inversion to find beta +beta = np.linalg.inv(X_train.T.dot(X_train)).dot(X_train.T).dot(y_train) +# and then make the prediction +ytilde = X_train @ beta +print("Training R2") +print(R2(y_train,ytilde)) +print("Training MSE") +print(MSE(y_train,ytilde)) +ypredict = X_test @ beta +print("Test R2") +print(R2(y_test,ypredict)) +print("Test MSE") +print(MSE(y_test,ypredict)) +!ec + + + +===== The singular value decomposition ===== + +The examples we have looked at so far are cases where we normally can +invert the matrix $\bm{X}^T\bm{X}$. Using a polynomial expansion as we +did both for the masses and the fitting of the equation of state, +leads to row vectors of the design matrix which are essentially +orthogonal due to the polynomial character of our model. This may +however not the be case in general and a standard matrix inversion +algorithm based on say LU decomposition may lead to singularities. We will see an example of this below when we try to fit +the coupling constant of the widely used Ising model. +There is however a way to partially circumvent this problem and also gain some insight about the ordinary least squares approach. + +This is given by the _Singular Value Decomposition_ algorithm, perhaps +the most powerful linear algebra algorithm. Let us look at a +different example where we may have problems with the standard matrix +inversion algorithm. Thereafter we dive into the math of the SVD. + + +===== The Ising model ===== + +The one-dimensional Ising model with nearest neighbor interaction, no +external field and a constant coupling constant $J$ is given by + +!bt +\begin{align} + H = -J \sum_{k}^L s_k s_{k + 1}, +\end{align} +!et + +where $s_i \in \{-1, 1\}$ and $s_{N + 1} = s_1$. The number of spins +in the system is determined by $L$. For the one-dimensional system +there is no phase transition. + +We will look at a system of $L = 40$ spins with a coupling constant of +$J = 1$. To get enough training data we will generate 10000 states +with their respective energies. + + +!bc pycod +import numpy as np +import matplotlib.pyplot as plt +from mpl_toolkits.axes_grid1 import make_axes_locatable +import seaborn as sns +import scipy.linalg as scl +from sklearn.model_selection import train_test_split +import tqdm +sns.set(color_codes=True) +cmap_args=dict(vmin=-1., vmax=1., cmap='seismic') + +L = 40 +n = int(1e4) + +spins = np.random.choice([-1, 1], size=(n, L)) +J = 1.0 + +energies = np.zeros(n) + +for i in range(n): + energies[i] = - J * np.dot(spins[i], np.roll(spins[i], 1)) +!ec + +Here we use ordinary least squares +regression to predict the energy for the nearest neighbor +one-dimensional Ising model on a ring, i.e., the endpoints wrap +around. We will use linear regression to fit a value for +the coupling constant to achieve this. + +===== Reformulating the problem to suit regression ===== + +A more general form for the one-dimensional Ising model is + +!bt +\begin{align} + H = - \sum_j^L \sum_k^L s_j s_k J_{jk}. +\end{align} +!et + +Here we allow for interactions beyond the nearest neighbors and a state dependent +coupling constant. This latter expression can be formulated as +a matrix-product +!bt +\begin{align} + \bm{H} = \bm{X} J, +\end{align} +!et + +where $X_{jk} = s_j s_k$ and $J$ is a matrix which consists of the +elements $-J_{jk}$. This form of writing the energy fits perfectly +with the form utilized in linear regression, that is + +!bt +\begin{align} + \bm{y} = \bm{X}\bm{\beta} + \bm{\epsilon}, +\end{align} +!et + +We split the data in training and test data as discussed in the previous example + +!bc pycod +X = np.zeros((n, L ** 2)) +for i in range(n): + X[i] = np.outer(spins[i], spins[i]).ravel() +y = energies +X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2) +!ec + + +In the ordinary least squares method we choose the cost function + +!bt +\begin{align} + C(\bm{X}, \bm{\beta})= \frac{1}{n}\left\{(\bm{X}\bm{\beta} - \bm{y})^T(\bm{X}\bm{\beta} - \bm{y})\right\}. +\end{align} +!et + +We then find the extremal point of $C$ by taking the derivative with respect to $\bm{\beta}$ as discussed above. +This yields the expression for $\bm{\beta}$ to be + +!bt +\[ + \bm{\beta} = \frac{\bm{X}^T \bm{y}}{\bm{X}^T \bm{X}}, +\] +!et + +which immediately imposes some requirements on $\bm{X}$ as there must exist +an inverse of $\bm{X}^T \bm{X}$. If the expression we are modeling contains an +intercept, i.e., a constant term, we must make sure that the +first column of $\bm{X}$ consists of $1$. We do this here + +!bc pycod +X_train_own = np.concatenate( + (np.ones(len(X_train))[:, np.newaxis], X_train), + axis=1 +) +X_test_own = np.concatenate( + (np.ones(len(X_test))[:, np.newaxis], X_test), + axis=1 +) +!ec + +!bc pycod +def ols_inv(x: np.ndarray, y: np.ndarray) -> np.ndarray: + return scl.inv(x.T @ x) @ (x.T @ y) +beta = ols_inv(X_train_own, y_train) +!ec + + + +===== Singular Value decomposition ===== + +Doing the inversion directly turns out to be a bad idea since the matrix +$\bm{X}^T\bm{X}$ is singular. An alternative approach is to use the _singular +value decomposition_. Using the definition of the Moore-Penrose +pseudoinverse we can write the equation for $\bm{\beta}$ as + +!bt +\[ + \bm{\beta} = \bm{X}^{+}\bm{y}, +\] +!et + +where the pseudoinverse of $\bm{X}$ is given by + +!bt +\[ + \bm{X}^{+} = \frac{\bm{X}^T}{\bm{X}^T\bm{X}}. +\] +!et + +Using singular value decomposition we can decompose the matrix $\bm{X} = \bm{U}\bm{\Sigma} \bm{V}^T$, +where $\bm{U}$ and $\bm{V}$ are orthogonal(unitary) matrices and $\bm{\Sigma}$ contains the singular values (more details below). +where $X^{+} = V\Sigma^{+} U^T$. This reduces the equation for +$\omega$ to +!bt +\begin{align} + \bm{\beta} = \bm{V}\bm{\Sigma}^{+} \bm{U}^T \bm{y}. +\end{align} +!et + +Note that solving this equation by actually doing the pseudoinverse +(which is what we will do) is not a good idea as this operation scales +as $\mathcal{O}(n^3)$, where $n$ is the number of elements in a +general matrix. Instead, doing $QR$-factorization and solving the +linear system as an equation would reduce this down to +$\mathcal{O}(n^2)$ operations. + + +!bc pycod +def ols_svd(x: np.ndarray, y: np.ndarray) -> np.ndarray: + u, s, v = scl.svd(x) + return v.T @ scl.pinv(scl.diagsvd(s, u.shape[0], v.shape[0])) @ u.T @ y +!ec + +!bc pycod +beta = ols_svd(X_train_own,y_train) +!ec + +When extracting the $J$-matrix we need to make sure that we remove the intercept, as is done here + +!bc pycod +J = beta[1:].reshape(L, L) +!ec + +A way of looking at the coefficients in $J$ is to plot the matrices as images. + + +!bc pycod +fig = plt.figure(figsize=(20, 14)) +im = plt.imshow(J, **cmap_args) +plt.title("OLS", fontsize=18) +plt.xticks(fontsize=18) +plt.yticks(fontsize=18) +cb = fig.colorbar(im) +cb.ax.set_yticklabels(cb.ax.get_yticklabels(), fontsize=18) +plt.show() +!ec +It is interesting to note that OLS +considers both $J_{j, j + 1} = -0.5$ and $J_{j, j - 1} = -0.5$ as +valid matrix elements for $J$. +In our discussion below on hyperparameters and Ridge and Lasso regression we will see that +this problem can be removed, partly and only with Lasso regression. + +In this case our matrix inversion was actually possible. The obvious question now is what is the mathematics behind the SVD? + + + +===== Linear Regression Problems ===== One of the typical problems we encounter with linear regression, in particular -when the matrix $\hat{X}$ (our so-called design matrix) is high-dimensional, -are problems with near singular or singular matrices. The column vectors of $\hat{X}$ +when the matrix $\bm{X}$ (our so-called design matrix) is high-dimensional, +are problems with near singular or singular matrices. The column vectors of $\bm{X}$ may be linearly dependent, normally referred to as super-collinearity. This means that the matrix may be rank deficient and it is basically impossible to to model the data using linear regression. As an example, consider the matrix @@ -5407,17 +2736,17 @@ to model the data using linear regression. As an example, consider the matrix \end{align*} !et -The columns of $\hat{X}$ are linearly dependent. We se this easily since the +The columns of $\bm{X}$ are linearly dependent. We see this easily since the the first column is the row-wise sum of the other two columns. The rank (more correct, the column rank) of a matrix is the dimension of the space spanned by the column vectors. Hence, the rank of $\mathbf{X}$ is equal to the number of linearly independent columns. In this particular case the matrix has rank 2. Super-collinearity of an $(n \times p)$-dimensional design matrix $\mathbf{X}$ implies -that the inverse of the matrix $\hat{X}^T\hat{x}$ (the matrix we needto invert to solve the linear regression equations) is non-invertible. If we have a square matrix that does not have an inverse, we say this matrix singular. The example here demonstrates this +that the inverse of the matrix $\bm{X}^T\bm{x}$ (the matrix we need to invert to solve the linear regression equations) is non-invertible. If we have a square matrix that does not have an inverse, we say this matrix singular. The example here demonstrates this !bt \begin{align*} -\hat{X} & = \left[ +\bm{X} & = \left[ \begin{array}{rr} 1 & -1 \\ @@ -5425,401 +2754,395 @@ that the inverse of the matrix $\hat{X}^T\hat{x}$ (the matrix we needto invert t \end{array} \right]. \end{align*} !et -We see easily that $\mbox{det}(\hat{X}) = x_{11} x_{22} - x_{12} x_{21} = 1 \times (-1) - 1 \times (-1) = 0$. Hence, $\mathbf{X}$ is singular and its inverse is undefined. -This is equivalent to saying that the matrix $\hat{X}$ has at least an eigenvalue which is zero. +We see easily that $\mbox{det}(\bm{X}) = x_{11} x_{22} - x_{12} x_{21} = 1 \times (-1) - 1 \times (-1) = 0$. Hence, $\mathbf{X}$ is singular and its inverse is undefined. +This is equivalent to saying that the matrix $\bm{X}$ has at least an eigenvalue which is zero. + ===== Fixing the singularity ===== -If our design matrix $\hat{X}$ which enters the linear regression problem +If our design matrix $\bm{X}$ which enters the linear regression problem !bt \begin{align} -\hat{\beta} & = (\hat{X}^{T} \hat{X})^{-1} \hat{X}^{T} \hat{y}, +\bm{\beta} & = (\bm{X}^{T} \bm{X})^{-1} \bm{X}^{T} \bm{y}, \end{align} !et has linearly dependent column vectors, we will not be able to compute the inverse -of $\hat{X}^T\hat{X}$ and we cannot find the parameters (estimators) $\beta_i$. -The estimators are only well-defined if $(\hat{X}^{T}\hat{X})^{-1}$ exits. -This is more likely to happen when the matrix $\hat{X}$ is high-dimensional. In this case it is likely to encounter a situation where +of $\bm{X}^T\bm{X}$ and we cannot find the parameters (estimators) $\beta_i$. +The estimators are only well-defined if $(\bm{X}^{T}\bm{X})^{-1}$ exits. +This is more likely to happen when the matrix $\bm{X}$ is high-dimensional. In this case it is likely to encounter a situation where the regression parameters $\beta_i$ cannot be estimated. -The *ad hoc* approach which was introduced in the 70s was simply to add a diagonal component to the matrix to invert, that is we change +A cheap *ad hoc* approach is simply to add a small diagonal component to the matrix to invert, that is we change !bt \[ -\hat{X}^{T} \hat{X} \rightarrow \hat{X}^{T} \hat{X}+\lambda \hat{I}, +\bm{X}^{T} \bm{X} \rightarrow \bm{X}^{T} \bm{X}+\lambda \bm{I}, \] !et -where $\hat{I}$ is the identity matrix. +where $\bm{I}$ is the identity matrix. When we discuss _Ridge_ regression this is actually what we end up evaluating. The parameter $\lambda$ is called a hyperparameter. More about this later. +===== Basic math of the SVD ===== + + +From standard linear algebra we know that a square matrix $\bm{X}$ can be diagonalized if and only it is +a so-called "normal matrix":"https://en.wikipedia.org/wiki/Normal_matrix", that is if $\bm{X}\in {\mathbb{R}}^{n\times n}$ +we have $\bm{X}\bm{X}^T=\bm{X}^T\bm{X}$ or if $\bm{X}\in {\mathbb{C}}^{n\times n}$ we have $\bm{X}\bm{X}^{\dagger}=\bm{X}^{\dagger}\bm{X}$. +The matrix has then a set of eigenpairs + +!bt +\[ +(\lambda_1,\bm{u}_1),\dots, (\lambda_n,\bm{u}_n), +!et +and the eigenvalues are given by the diagonal matrix +!bt +\[ +\bm{\Sigma}=\mathrm{Diag}(\lambda_1, \dots,\lambda_n). +\] +!et +The matrix $\bm{X}$ can be written in terms of an orthogonal/unitary transformation $\bm{U}$ +!bt +\[ +\bm{X} = \bm{U}\bm{\Sigma}\bm{V}^T, +\] +!et +with $\bm{U}\bm{U}^T=\bm{I}$ or $\bm{U}\bm{U}^{\dagger}=\bm{I}$. +Not all square matrices are diagonalizable. A matrix like the one discussed above +!bt +\[ +\bm{X} = \begin{bmatrix} +1& -1 \\ +1& -1\\ +\end{bmatrix} +\] +!et +is not diagonalizable, it is a so-called "defective matrix":"https://en.wikipedia.org/wiki/Defective_matrix". It is easy to see that the condition +$\bm{X}\bm{X}^T=\bm{X}^T\bm{X}$ is not fulfilled. -===== Fitting vs. predicting when data is in the model class ===== -We start by considering the case -$f(x)=2x$. - -Then the data is clearly generated by a model that is contained within -all three model classes we are using to make predictions (linear -models, third order polynomials, and tenth order polynomials). -Run the code for the following cases: +===== The SVD, a Fantastic Algorithm ===== -o For $f(x)=2x$ , $Ntrain=10$ and $\sigma =0$ (noiseless case), train the three classes of models (linear, third-order polynomial, and tenth order polynomial) for a training set when $x \in [0,1]$ . Make graphs comparing fits for different order of polynomials. Which model fits the data the best? -o Do you think that the data that has the least error on the training set will also make the best predictions? Why or why not? Can you try to discuss and formalize your intuition? What can go right and what can go wrong? -o Check your answer by seeing how well your fits predict newly generated test data (including on data outside the range you fit on, for example $x \in [0,1.2]$ ) using the code below. How well do you do on points in the range of x where you trained the model? How about points outside the original training data set? -o Repeat the above for $f(x)=2x$ , $Ntrain=10$ , and $\sigma=1$ . What changes? -Repeat the exercises above for $f(x)=2x$ , $Ntrain=100$ , and $\sigma=1$ . What changes? -Summarize what you have learned about the relationship between model complexity (number of parameters), goodness of fit on training data, and the ability to predict well. +However, and this is the strength of the SVD algorithm, any general +matrix $\bm{X}$ can be decomposed in terms of a diagonal matrix and +two orthogonal/unitary matrices. The "Singular Value Decompostion +(SVD) theorem":"https://en.wikipedia.org/wiki/Singular_value_decomposition" +states that a general $m\times n$ matrix $\bm{X}$ can be written in +terms of a diagonal matrix $\bm{\Sigma}$ of dimensionality $n\times n$ +and two orthognal matrices $\bm{U}$ and $\bm{V}$, where the first has +dimensionality $m \times m$ and the last dimensionality $n\times n$. +We have then + +!bt +\[ +\bm{X} = \bm{U}\bm{\Sigma}\bm{V}^T +\] +!et + +As an example, the above defective matrix can be decomposed as + +!bt +\[ +\bm{X} = \frac{1}{\sqrt{2}}\begin{bmatrix} 1& 1 \\ 1& -1\\ \end{bmatrix} \begin{bmatrix} 2& 0 \\ 0& 0\\ \end{bmatrix} \frac{1}{\sqrt{2}}\begin{bmatrix} 1& -1 \\ 1& 1\\ \end{bmatrix}=\bm{U}\bm{\Sigma}\bm{V}^T, +\] +!et + +with eigenvalues $\sigma_1=2$ and $\sigma_2=0$. +The SVD exits always! + + + +===== Another Example ===== + +Consider the following matrix which can be SVD decomposed as + +!bt +\[ +\bm{X} = \frac{1}{15}\begin{bmatrix} 14 & 2\\ 4 & 22\\ 16 & 13\end{matrix}=\frac{1}{3}\begin{bmatrix} 1& 2 & 2 \\ 2& -1 & 1\\ 2 & 1& -2\end{bmatrix} \begin{bmatrix} 2& 0 \\ 0& 1\\ 0 & 0\end{bmatrix}\frac{1}{5}\begin{bmatrix} 3& 4 \\ 4& -3\end{bmatrix}=\bm{U}\bm{\Sigma}\bm{V}^T. +\] +!et + +This is a $3\times 2$ matrix which is decomposed in terms of a +$3\times 3$ matrix $\bm{U}$, and a $2\times 2$ matrix $\bm{V}$. It is easy to see +that $\bm{U}$ and $\bm{V}$ are orthogonal (how?). + +And the SVD +decomposition (singular values) gives eigenvalues +$\sigma_i\geq\sigma_{i+1}$ for all $i$ and for dimensions larger than $i=2$, the +eigenvalues (singular values) are zero. + +In the general case, where our design matrix $\bm{X}$ has dimension +$n\times p$, the matrix is thus decomposed into an $n\times n$ +orthogonal matrix $\bm{U}$, a $p\times p$ orthogonal matrix $\bm{V}$ +and a diagonal matrix $\bm{\Sigma}$ with $r=\mathrm{min}(n,p)$ +singular values $\sigma_i\lg 0$ on the main diagonal and zeros filling +the rest of the matrix. There are at most $p$ singular values +assuming that $n > p$. In our regression examples for the nuclear +masses and the equation of state this is indeed the case, while for +the Ising model we have $p > n$. These are often cases that lead to +near singular or singular matrices. + +The columns of $\bm{U}$ are called the left singular vectors while the columns of $\bm{V}$ are the right singular vectors. + + +===== Economy-size SVD ===== + +If we assume that $n > p$, then our matrix $\bm{U}$ has dimension $n +\times n$. The last $n-p$ columns of $\bm{U}$ become however +irrelevant in our calculations since they are multiplied with the +zeros in $\bm{\Sigma}$. + +The economy-size decomposition removes extra rows or columns of zeros +from the diagonal matrix of singular values, $\bm{\Sigma}$, along with the columns +in either $\bm{U}$ or $\bm{V}$ that multiply those zeros in the expression. +Removing these zeros and columns can improve execution time +and reduce storage requirements without compromising the accuracy of +the decomposition. + +If $n > p$, we keep only the first $p$ columns of $\bm{U}$ and $\bm{\Sigma}$ has dimension $p\times p$. +If $p > n$, then only the first $n$ columns of $\bm{V}$ are computed and $\bm{\Sigma}$ has dimension $n\times n$. +The $n=p$ case is obvious, we retain the full SVD. +In general the economy-size SVD leads to less FLOPS and still conserving the desired accuracy. + + +===== Mathematical Properties ===== + +There are several interesting mathematical properties which will be +relevant when we are going to discuss the differences between say +ordinary least squares (OLS) and _Ridge_ regression. + +We have from OLS that the parameters of the linear approximation are given by +!bt +\[ +\bm{\tilde{y}} = \bm{X}\bm{\beta} = \bm{X}\left(\bm{X}^T\bm{X}\right)^{-1}\bm{X}^T\bm{y}. +\] +!et + +The matrix to invert can be rewritten in terms of our SVD decomposition as + +!bt +\[ +\bm{X}^T\bm{X} = \bm{V}\bm{\Sigma}^T\bm{U}^T\bm{U}\bm{\Sigma}\bm{V}^T. +\] +!et +Using the orthogonality properties of $\bm{U}$ we have + +!bt +\[ +\bm{X}^T\bm{X} = \bm{V}\bm{\Sigma}^T\bm{\Sigma}\bm{V}^T = \bm{V}\bm{D}\bm{V}^T, +\] +!et +with $\bm{D}$ being a diagonal matrix with values along the diagonal given by the singular values squared. + +This means that +!bt +\[ +(\bm{X}^T\bm{X})\bm{V} = \bm{V}\bm{D}, +\] +!et +that is the eigenvectors of $(\bm{X}^T\bm{X})$ are given by the columns of the right singular matrix of $\bm{X}$ and the eigenvalues are the squared singular values. It is easy to show (show this) that +!bt +\[ +(\bm{X}\bm{X}^T)\bm{U} = \bm{U}\bm{D}, +\] +!et +that is, the eigenvectors of $(\bm{X}\bm{X})^T$ are the columns of the left singular matrix and the eigenvalues are the same. + +Going back to our OLS equation we have +!bt +\[ +\bm{X}\bm{\beta} = \bm{X}\left(\bm{V}\bm{D}\bm{V}^T \right)^{-1}\bm{X}^T\bm{y}=\bm{U\Sigma V^T}\left(\bm{V}\bm{D}\bm{V}^T \right)^{-1}(\bm{U\Sigma V^T})^T\bm{y}=\bm{U}\bm{U}^T\bm{y}. +\] +!et +We will come back to this expression when we discuss Ridge regression. + + + +===== Ridge and LASSO Regression ===== + +Let us remind ourselves about the expression for the standard Mean Squared Error (MSE) which we used to define our cost function and the equations for the ordinary least squares (OLS) method, that is +our optimization problem is +!bt +\[ +{\displaystyle \min_{\bm{\beta}\in {\mathbb{R}}^{p}}}\frac{1}{n}\left\{\left(\bm{y}-\bm{X}\bm{\beta}\right)^T\left(\bm{y}-\bm{X}\bm{\beta}\right)\right\}. +\] +!et +or we can state it as +!bt +\[ +{\displaystyle \min_{\bm{\beta}\in +{\mathbb{R}}^{p}}}\frac{1}{n}\sum_{i=0}^{n-1}\left(y_i-\tilde{y}_i\right)^2=\frac{1}{n}\vert\vert \bm{y}-\bm{X}\bm{\beta}\vert\vert_2^2, +\] +!et +where we have used the definition of a norm-2 vector, that is +!bt +\[ +\vert\vert \bm{x}\vert\vert_2 = \sqrt{\sum_i x_i^2}. +\] +!et + +By minimizing the above equation with respect to the parameters +$\bm{\beta}$ we could then obtain an analytical expression for the +parameters $\bm{\beta}$. We can add a regularization parameter $\lambda$ by +defining a new cost function to be optimized, that is + +!bt +\[ +{\displaystyle \min_{\bm{\beta}\in +{\mathbb{R}}^{p}}}\frac{1}{n}\vert\vert \bm{y}-\bm{X}\bm{\beta}\vert\vert_2^2+\lambda\vert\vert \bm{\beta}\vert\vert_2^2 +\] +!et + +which leads to the Ridge regression minimization problem where we +require that $\vert\vert \bm{\beta}\vert\vert_2^2\le t$, where $t$ is +a finite number larger than zero. By defining + +!bt +\[ +C(\bm{X},\bm{\beta})=\frac{1}{n}\vert\vert \bm{y}-\bm{X}\bm{\beta}\vert\vert_2^2+\lambda\vert\vert \bm{\beta}\vert\vert_1, +\] +!et + +we have a new optimization equation +!bt +\[ +{\displaystyle \min_{\bm{\beta}\in +{\mathbb{R}}^{p}}}\frac{1}{n}\vert\vert \bm{y}-\bm{X}\bm{\beta}\vert\vert_2^2+\lambda\vert\vert \bm{\beta}\vert\vert_1 +\] +!et +which leads to Lasso regression. Lasso stands for least absolute shrinkage and selection operator. + +Here we have defined the norm-1 as +!bt +\[ +\vert\vert \bm{x}\vert\vert_1 = \sum_i \vert x_i\vert. +\] +!et + +Using the matrix-vector expression for Ridge regression, + +!bt +\[ +C(\bm{X},\bm{\beta})=\frac{1}{n}\left\{(\bm{y}-\bm{X}\bm{\beta})^T(\bm{y}-\bm{X}\bm{\beta})\right\}+\lambda\bm{\beta}^T\bm{\beta}, +\] +!et + +by taking the derivatives with respect to $\bm{\beta}$ we obtain then +a slightly modified matrix inversion problem which for finite values +of $\lambda$ does not suffer from singularity problems. We obtain + +!bt +\[ +\bm{\beta}^{\mathrm{Ridge}} = \left(\bm{X}^T\bm{X}+\lambda\bm{I}\right)^{-1}\bm{X}^T\bm{y}, +\] +!et + +with $\bm{I}$ being a $p\times p$ identity matrix with the constraint that + +!bt +\[ +\sum_{i=0}^{p-1} \beta_i^2 \leq t, +\] +!et + +with $t$ a finite positive number. + +We see that Ridge regression is nothing but the standard +OLS with a modified diagonal term added to $\bm{X}^T\bm{X}$. The +consequences, in particular for our discussion of the bias-variance +are rather interesting. + +Furthermore, if we use the result above in terms of the SVD decomposition (our analysis was done for the OLS method), we had +!bt +\[ +(\bm{X}\bm{X}^T)\bm{U} = \bm{U}\bm{D}. +\] +!et + +We can analyse the OLS solutions in terms of the eigenvectors (the columns) of the right singular value matrix $\bm{U}$ as +!bt +\[ +\bm{X}\bm{\beta} = \bm{X}\left(\bm{V}\bm{D}\bm{V}^T \right)^{-1}\bm{X}^T\bm{y}=\bm{U\Sigma V^T}\left(\bm{V}\bm{D}\bm{V}^T \right)^{-1}(\bm{U\Sigma V^T})^T\bm{y}=\bm{U}\bm{U}^T\bm{y} +\] +!et + + +For Ridge regression this becomes + +!bt +\[ +\bm{X}\bm{\beta}^{\mathrm{Ridge}} = \bm{U\Sigma V^T}\left(\bm{V}\bm{D}\bm{V}^T+\lambda\bm{I} \right)^{-1}(\bm{U\Sigma V^T})^T\bm{y}=\sum_{j=0}^{p-1}\bm{u}_j\bm{u}_j^T\frac{\sigma_j^2}{\sigma_j^2+\lambda}\bm{y}, +\] +!et + +with the vectors $\bm{u}_j$ being the columns of $\bm{U}$. + +===== Interpreting the Ridge results ===== + +Since $\lambda \geq 0$, it means that compared to OLS, we have + +!bt +\[ +\frac{\sigma_j^2}{\sigma_j^2+\lambda} \leq 1. +\] +!et + +Ridge regression finds the coordinates of $\bm{y}$ with respect to the +orthonormal basis $\bm{U}$, it then shrinks the coordinates by +$\frac{\sigma_j^2}{\sigma_j^2+\lambda}$. Recall that the SVD has +eigenvalues ordered in a descending way, that is $\sigma_i \geq +\sigma_{i+1}$. + +For small eigenvalues $\sigma_i$ it means that their contributions become less important, a fact which can be used to reduce the number of degrees of freedom. +Actually, calculating the variance of $\bm{X}\bm{v}_j$ shows that this quantity is equal to $\sigma_j^2/n$. +With a parameter $\lambda$ we can thus shrink the role of specific parameters. + + +For the sake of simplicity, let us assume that the design matrix is orthonormal, that is + +!bt +\[ +\bm{X}^T\bm{X}=(\bm{X}^T\bm{X})^{-1} =\bm{I}. +\] +!et + +In this case the standard OLS results in +!bt +\[ +\bm{\beta}^{\mathrm{OLS}} = \bm{X}^T\bm{y}=\sum_{i=0}^{p-1}\bm{u}_j\bm{u}_j^T\bm{y}, +\] +!et +and -===== Fitting versus predicting when data is not in the model class ===== +!bt +\[ +\bm{\beta}^{\mathrm{Ridge}} = \left(\bm{I}+\lambda\bm{I}\right)^{-1}\bm{X}^T\bm{y}=\left(1+\lambda\right)^{-1}\bm{\beta}^{\mathrm{OLS}}, +\] +!et -Thus far, we have considered the case where the data is generated using a model contained in the model class. Now consider $f(x)=2x-10x^5+15x^{10}$ . Notice that the for linear and third-order polynomial the true model $f(x)$ is not contained in model class. +that is the Ridge estimator scales the OLS estimator by the inverse of a factor $1+\lambda$, and +the Ridge estimator converges to zero when the hyperparameter goes to +infinity. -o Do better fits lead to better predictions? -o What is the relationship between the true model for generating the data and the model class that has the most predictive power? How is this related to the model complexity? How does this depend on the number of data points $Ntrain$ and $\sigma$? -Summarize what you think you learned about the relationship of knowing the true model class and predictive power. +We will come back to more interpreations after we have gone through some of the statistical analysis part. +For more discussions of Ridge and Lasso regression, "Wessel van Wieringen's":"https://arxiv.org/abs/1509.09169" article is highly recommended. +Similarly, "Mehta et al's article":"https://arxiv.org/abs/1803.08823" is also recommended. -===== An example code without the model assessment part ===== +===== Where are we going? ===== -!bc pycod -import numpy as np -import sklearn as sk -from sklearn import datasets, linear_model -from sklearn.preprocessing import PolynomialFeatures - -import matplotlib as mpl -from matplotlib import pyplot as plt - -%matplotlib notebook - -# The Training Data - -N_train=100 - -sigma_train=1; - -# Train on integers -x=np.linspace(0.05,0.95,N_train) -# Draw random noise -s = sigma_train*np.random.randn(N_train) - -#linear -y=2*x+s - -#Tenth Order -#y=2*x-10*x**5+15*x**10+s - -p1=plt.plot(x,y, "o",ms=15, label='Training') - -#Linear Regression -# Create linear regression object -clf = linear_model.LinearRegression() - -# Train the model using the training sets -clf.fit(x[:, np.newaxis], y) -# The coefficients - -xplot=np.linspace(0.02,0.98,200) -linear_plot=plt.plot(xplot, clf.predict(xplot[:, np.newaxis]),label='Linear') - -#Polynomial Regression - - -poly3 = PolynomialFeatures(degree=3) -X = poly3.fit_transform(x[:,np.newaxis]) -clf3 = linear_model.LinearRegression() -clf3.fit(X,y) - - -Xplot=poly3.fit_transform(xplot[:,np.newaxis]) -poly3_plot=plt.plot(xplot, clf3.predict(Xplot), label='Poly 3') - - - -#poly5 = PolynomialFeatures(degree=5) -#X = poly5.fit_transform(x[:,np.newaxis]) -#clf5 = linear_model.LinearRegression() -#clf5.fit(X,y) - -#Xplot=poly5.fit_transform(xplot[:,np.newaxis]) -#plt.plot(xplot, clf5.predict(Xplot), 'r--',linewidth=1) - -poly10 = PolynomialFeatures(degree=10) -X = poly10.fit_transform(x[:,np.newaxis]) -clf10 = linear_model.LinearRegression() -clf10.fit(X,y) - -Xplot=poly10.fit_transform(xplot[:,np.newaxis]) -poly10_plot=plt.plot(xplot, clf10.predict(Xplot), label='Poly 10') - -axes = plt.gca() -axes.set_ylim([-7,7]) - -handles, labels=axes.get_legend_handles_labels() -plt.legend(handles,labels, loc='lower center') -plt.xlabel("$x$") -plt.ylabel("$y$") -Title="$N=$"+str(N_train)+", $\sigma=$"+str(sigma_train) -plt.title(Title+" (train)") -plt.tight_layout() -plt.show() - -!ec - - -===== Generating test data ===== -!bc pycod -# Generate Test Data - -#Number of test data -N_test=20 - -sigma_test=sigma_train - -max_x=1.2 -x_test=max_x*np.random.random(N_test) -# Draw random noise -s_test = sigma_test*np.random.randn(N_test) - -#Linear -y_test=2*x_test+s_test -#Tenth order -#y_test=2*x_test-10*x_test**5+15*x_test**10+s_test - -#Make design matrices for prediction -x_plot=np.linspace(0,max_x, 200) -X3 = poly3.fit_transform(x_plot[:,np.newaxis]) -X10 = poly10.fit_transform(x_plot[:,np.newaxis]) - -%matplotlib notebook - -fig = plt.figure() -p1=plt.plot(x_test,y_test.transpose(), 'o', ms=12, label='data') -p2=plt.plot(x_plot,clf.predict(x_plot[:,np.newaxis]), label='linear') -p3=plt.plot(x_plot,clf3.predict(X3), label='3rd order') -p10=plt.plot(x_plot,clf10.predict(X10), label='10th order') - - -plt.legend(loc=2) -plt.xlabel('$x$') -plt.ylabel('$y$') -plt.legend(loc='best') -plt.title(Title+" (pred.)") -plt.tight_layout() -plt.show() - - -!ec - - -===== How can we effectively evaluate the various models? ===== - -In Ridge regression and the subsequent discussion of its properties -the bias or penalty parameter is considered known or `given'. In -practice, it is unknown and the user needs to make an informed -decision on its value. How do we do that? Much of the same considerations apply to the Lasso method. - - -===== Code examples for Ridge and Lasso Regression ===== - -!bc pycod -import matplotlib.pyplot as plt -import numpy as np -from sklearn import linear_model -from sklearn.linear_model import LinearRegression -from sklearn.metrics import mean_squared_error, r2_score - -#creating data with random noise -x=np.arange(50) - -delta=np.random.uniform(-2.5,2.5, size=(50)) -np.random.shuffle(delta) -y =0.5*x+5+delta - -#arranging data into 2x50 matrix -a=np.array(x) #inputs -b=np.array(y) #outputs - -#Split into training and test -X_train=a[:37, np.newaxis] -X_test=a[37:, np.newaxis] -y_train=b[:37] -y_test=b[37:] - -print ("X_train: ", X_train.shape) -print ("y_train: ", y_train.shape) -print ("X_test: ", X_test.shape) -print ("y_test: ", y_test.shape) - -print ("------------------------------------") - -print ("Ordinary Least Squares") -#Add Ordinary Least Squares fit -reg=LinearRegression() -reg.fit(X_train, y_train) -pred=reg.predict(X_test) -print ("Prediction Shape: ", pred.shape) - -print('Coefficients: \n', reg.coef_) -# The mean squared error -print("Mean squared error: %.2f" - % mean_squared_error(y_test, pred)) -# Explained variance score: 1 is perfect prediction -print('Variance score: %.2f' % r2_score(y_test, pred)) - -#plot -plt.scatter(X_test,y_test,color='green', label="Training Data") -plt.plot(X_test, pred, color='black', label="Fit Line") -plt.legend() -plt.show() - -print ("------------------------------------") - -print ("Ridge Regression") - -ridge=linear_model.RidgeCV(alphas=[0.1,1.0,10.0]) -ridge.fit(X_train,y_train) -print ("Ridge Coefficient: ",ridge.coef_) -print ("Ridge Intercept: ", ridge.intercept_) -#Look into graphing with Ridge fit - -print ("------------------------------------") - -print ("Lasso") -lasso=linear_model.Lasso(alpha=0.1) -lasso.fit(X_train,y_train) -predl=lasso.predict(X_test) -print("Lasso Coefficient: ", lasso.coef_) -print("Lasso Intercept: ", lasso.intercept_) -plt.scatter(X_test,y_test,color='green', label="Training Data") -plt.plot(X_test, predl, color='blue', label="Lasso") -plt.legend() -plt.show() -!ec - - - - - - -===== A second-order polynomial with Ridge and Lasso ===== -!bc pycod -import numpy as np -import matplotlib.pyplot as plt -from sklearn.linear_model import Ridge -from sklearn.metrics import r2_score - -np.random.seed(4155) - -n_samples = 100 - -x = np.random.rand(n_samples,1) -y = 5*x*x + 0.1*np.random.rand(n_samples,1) - -# Centering x and y. -x_ = x - np.mean(x) -y_ = y - np.mean(y) # beta_0 = mean(y) - -X = np.c_[np.ones((n_samples,1)), x, x**2] -X_ = np.c_[x_, x_**2] - - -### 1. -lmb_values = [1e-4, 1e-3, 1e-2, 10, 1e2, 1e4] -num_values = len(lmb_values) - -## Ridge-regression of centered and not centered data -beta_ridge = np.zeros((3,num_values)) -beta_ridge_centered = np.zeros((3,num_values)) - -I3 = np.eye(3) -I2 = np.eye(2) - -for i,lmb in enumerate(lmb_values): - beta_ridge[:,i] = (np.linalg.inv( X.T @ X + lmb*I3) @ X.T @ y).flatten() - beta_ridge_centered[1:,i] = (np.linalg.inv( X_.T @ X_ + lmb*I2) @ X_.T @ y_).flatten() - -# sett beta_0 = np.mean(y) -beta_ridge_centered[0,:] = np.mean(y) - -## OLS (ordinary least squares) solution -beta_ls = np.linalg.inv( X.T @ X ) @ X.T @ y - -## Evaluate the models -pred_ls = X @ beta_ls -pred_ridge = X @ beta_ridge -pred_ridge_centered = X_ @ beta_ridge_centered[1:] + beta_ridge_centered[0,:] - -## Plot the results - -# Sorting -sort_ind = np.argsort(x[:,0]) - -x_plot = x[sort_ind,0] -x_centered_plot = x_[sort_ind,0] - -pred_ls_plot = pred_ls[sort_ind,0] -pred_ridge_plot = pred_ridge[sort_ind,:] -pred_ridge_centered_plot = pred_ridge_centered[sort_ind,:] - -# Plott not centered -plt.plot(x_plot,pred_ls_plot,label='ls') - -for i in range(num_values): - plt.plot(x_plot,pred_ridge_plot[:,i],label='ridge, lmb=%g'%lmb_values[i]) - -plt.plot(x,y,'ro') - -plt.title('linear regression on un-centered data') -plt.legend() - -# Plott centered -plt.figure() - -for i in range(num_values): - plt.plot(x_centered_plot,pred_ridge_centered_plot[:,i],label='ridge, lmb=%g'%lmb_values[i]) - -plt.plot(x_,y,'ro') - -plt.title('linear regression on centered data') -plt.legend() - - -# 2. - -pred_ridge_scikit = np.zeros((n_samples,num_values)) -for i,lmb in enumerate(lmb_values): - pred_ridge_scikit[:,i] = (Ridge(alpha=lmb,fit_intercept=False).fit(X,y).predict(X)).flatten() # fit_intercept=False fordi bias er allerede i X - -plt.figure() - -plt.plot(x_plot,pred_ls_plot,label='ls') - -for i in range(num_values): - plt.plot(x_plot,pred_ridge_scikit[sort_ind,i],label='scikit-ridge, lmb=%g'%lmb_values[i]) - -plt.plot(x,y,'ro') -plt.legend() -plt.title('linear regression using scikit') - -plt.show() - -### R2-score of the results -for i in range(num_values): - print('lambda = %g'%lmb_values[i]) - print('r2 for scikit: %g'%r2_score(y,pred_ridge_scikit[:,i])) - print('r2 for own code, not centered: %g'%r2_score(y,pred_ridge[:,i])) - print('r2 for own, centered: %g\n'%r2_score(y,pred_ridge_centered[:,i])) - - -!ec +Before we proceed, we need to rethink what we have been doing. In our +eager to fit the data, we have omitted several important elements in +our regression analysis. In what follows we will +o look at statistical properties, including a discussion of mean values, variance and the so-called bias-variance tradeoff +o introduce resampling techniques like cross-validation, bootstrapping and jackknife and more +This will allow us to link the standard linear algebra methods we have discussed above to a statistical interpretation of the methods. @@ -5837,9 +3160,6 @@ information that would not be available from fitting the model only once using the original training sample. - -===== Resampling approaches can be computationally expensive ===== - Resampling approaches can be computationally expensive, because they involve fitting the same statistical method multiple times using different subsets of the training data. However, due to recent @@ -5856,27 +3176,18 @@ known as model assessment, whereas the process of selecting the proper level of flexibility for a model is known as model selection. The bootstrap is widely used. - - ===== Why resampling methods ? ===== - Statistical analysis - * Our simulations can be treated as *computer experiments*. This is particularly the case for Monte Carlo methods - * The results can be analysed with the same statistical tools as we would use analysing experimental data. - * As in all experiments, we are looking for expectation values and an estimate of how accurate they are, i.e., possible sources for errors. + +* Our simulations can be treated as *computer experiments*. This is particularly the case for Monte Carlo methods +* The results can be analysed with the same statistical tools as we would use analysing experimental data. +* As in all experiments, we are looking for expectation values and an estimate of how accurate they are, i.e., possible sources for errors. - - - -===== Statistical analysis ===== - - * As in other experiments, many numerical experiments have two classes of errors: - * Statistical errors - * Systematical errors - * Statistical errors can be estimated using standard tools from statistics - * Systematical errors are method specific and must be treated differently from case to case. - - +* As in other experiments, many numerical experiments have two classes of errors: + * Statistical errors + * Systematical errors +* Statistical errors can be estimated using standard tools from statistics +* Systematical errors are method specific and must be treated differently from case to case. ===== Statistics ===== @@ -5904,43 +3215,621 @@ Qualitatively speaking, a stochastic variable represents the values of numbers chosen as if by chance from some specified PDF so that the selection of a large set of these numbers reproduces this PDF. - - - - - - -===== Log-likelihood ===== - -A popular strategy is to choose a penalty parameter that yields a good -but parsimonious model. Information criteria measure the balance -between model fit and model complexity. One possibility is Aikaike's -information criterion (AIC). -The AIC measures model fit by the log-likelihood -and model complexity is measured by the number of parameters used by -the model. The number of model parameters in regular regression simply -corresponds to the number of covariates in the model. Or, by the -degrees of freedom consumed by the model, which is equivalent to the -trace of the hat matrix. For ridge regression it thus seems natural to -define model complexity analogously by the trace of the ridge hat -matrix. This yields the AIC for the linear regression model with ridge -estimates: - - +A particularly useful class of special expectation values are the +*moments*. The $n$-th moment of the PDF $p$ is defined as +follows: !bt -\begin{align*} -\mbox{AIC}(\lambda) & = 2 \, p - 2 \log(\hat{L}) -\\ -& = 2 \, \mbox{tr} [\mathbf{H}(\lambda)] - 2 \log\{L[\hat{\beta}(\lambda), \hat{\sigma}^2(\lambda)]\} -\\ -& = 2 \, \sum_{j=1}^p \frac{d_{jj}^2}{d_{jj}^2 + \lambda} -+ 2 n \, \log[\sqrt{2 \, \pi} \, \hat{\sigma}(\lambda)] + \frac{1}{\hat{\sigma}^2(\lambda)} \sum_{i=1}^n [y_i - \mathbf{X}_{i, \ast} \, \hat{\beta}(\lambda)]^2. +\[ +\langle x^n\rangle \equiv \int\! x^n p(x)\,dx +\] +!et +The zero-th moment $\langle 1\rangle$ is just the normalization condition of +$p$. The first moment, $\langle x\rangle$, is called the *mean* of $p$ +and often denoted by the letter $\mu$: +!bt +\[ +\langle x\rangle = \mu \equiv \int\! x p(x)\,dx +\] +!et + +A special version of the moments is the set of *central moments*, +the n-th central moment defined as: +!bt +\[ +\langle (x-\langle x \rangle )^n\rangle \equiv \int\! (x-\langle x\rangle)^n p(x)\,dx +\] +!et +The zero-th and first central moments are both trivial, equal $1$ and +$0$, respectively. But the second central moment, known as the +*variance* of $p$, is of particular interest. For the stochastic +variable $X$, the variance is denoted as $\sigma^2_X$ or $\mathrm{var}(X)$: +!bt +\begin{align} +\sigma^2_X\ \ =\ \ \mathrm{var}(X) & = \langle (x-\langle x\rangle)^2\rangle = +\int\! (x-\langle x\rangle)^2 p(x)\,dx\\ +& = \int\! \left(x^2 - 2 x \langle x\rangle^{2} + + \langle x\rangle^2\right)p(x)\,dx\\ +& = \langle x^2\rangle - 2 \langle x\rangle\langle x\rangle + \langle x\rangle^2\\ +& = \langle x^2\rangle - \langle x\rangle^2 +\end{align} +!et +The square root of the variance, $\sigma =\sqrt{\langle (x-\langle x\rangle)^2\rangle}$ is called the *standard deviation* of $p$. It is clearly just the RMS (root-mean-square) +value of the deviation of the PDF from its mean value, interpreted +qualitatively as the *spread* of $p$ around its mean. + + + +===== Statistics, covariance ===== + +Another important quantity is the so called covariance, a variant of +the above defined variance. Consider again the set $\{X_i\}$ of $n$ +stochastic variables (not necessarily uncorrelated) with the +multivariate PDF $P(x_1,\dots,x_n)$. The *covariance* of two +of the stochastic variables, $X_i$ and $X_j$, is defined as follows: +!bt +\begin{align} +\mathrm{cov}(X_i,\,X_j) &\equiv \langle (x_i-\langle x_i\rangle)(x_j-\langle x_j\rangle)\rangle +\nonumber\\ +&= +\int\!\cdots\!\int\!(x_i-\langle x_i \rangle)(x_j-\langle x_j \rangle)\, +P(x_1,\dots,x_n)\,dx_1\dots dx_n +label{eq:def_covariance} +\end{align} +!et +with +!bt +\[ +\langle x_i\rangle = +\int\!\cdots\!\int\!x_i\,P(x_1,\dots,x_n)\,dx_1\dots dx_n +\] +!et + +If we consider the above covariance as a matrix $C_{ij}=\mathrm{cov}(X_i,\,X_j)$, then the diagonal elements are just the familiar +variances, $C_{ii} = \mathrm{cov}(X_i,\,X_i) = \mathrm{var}(X_i)$. It turns out that +all the off-diagonal elements are zero if the stochastic variables are +uncorrelated. This is easy to show, keeping in mind the linearity of +the expectation value. Consider the stochastic variables $X_i$ and +$X_j$, ($i\neq j$): +!bt +\begin{align} +\mathrm{cov}(X_i,\,X_j) &= \langle(x_i-\langle x_i\rangle)(x_j-\langle x_j\rangle)\rangle\\ +&=\langle x_i x_j - x_i\langle x_j\rangle - \langle x_i\rangle x_j + \langle x_i\rangle\langle x_j\rangle\rangle \\ +&=\langle x_i x_j\rangle - \langle x_i\langle x_j\rangle\rangle - \langle \langle x_i\rangle x_j\rangle + +\langle \langle x_i\rangle\langle x_j\rangle\rangle\\ +&=\langle x_i x_j\rangle - \langle x_i\rangle\langle x_j\rangle - \langle x_i\rangle\langle x_j\rangle + +\langle x_i\rangle\langle x_j\rangle\\ +&=\langle x_i x_j\rangle - \langle x_i\rangle\langle x_j\rangle +\end{align} +!et + +===== Statistics, independent variables ===== + +If $X_i$ and $X_j$ are independent, we get +$\langle x_i x_j\rangle =\langle x_i\rangle\langle x_j\rangle$, resulting in $\mathrm{cov}(X_i, X_j) = 0\ \ (i\neq j)$. + +Also useful for us is the covariance of linear combinations of +stochastic variables. Let $\{X_i\}$ and $\{Y_i\}$ be two sets of +stochastic variables. Let also $\{a_i\}$ and $\{b_i\}$ be two sets of +scalars. Consider the linear combination: +!bt +\[ +U = \sum_i a_i X_i \qquad V = \sum_j b_j Y_j +\] +!et +By the linearity of the expectation value +!bt +\[ +\mathrm{cov}(U, V) = \sum_{i,j}a_i b_j \mathrm{cov}(X_i, Y_j) +\] +!et + +Now, since the variance is just $\mathrm{var}(X_i) = \mathrm{cov}(X_i, X_i)$, we get +the variance of the linear combination $U = \sum_i a_i X_i$: +!bt +\begin{equation} +\mathrm{var}(U) = \sum_{i,j}a_i a_j \mathrm{cov}(X_i, X_j) +label{eq:variance_linear_combination} +\end{equation} +!et +And in the special case when the stochastic variables are +uncorrelated, the off-diagonal elements of the covariance are as we +know zero, resulting in: +!bt +\[ +\mathrm{var}(U) = \sum_i a_i^2 \mathrm{cov}(X_i, X_i) = \sum_i a_i^2 \mathrm{var}(X_i) +\] +!et +!bt +\[ +\mathrm{var}(\sum_i a_i X_i) = \sum_i a_i^2 \mathrm{var}(X_i) +\] +!et +which will become very useful in our study of the error in the mean +value of a set of measurements. + +===== Statistics and stochastic processes ===== + +A *stochastic process* is a process that produces sequentially a +chain of values: +!bt +\[ +\{x_1, x_2,\dots\,x_k,\dots\}. +\] +!et +We will call these +values our *measurements* and the entire set as our measured +*sample*. The action of measuring all the elements of a sample +we will call a stochastic *experiment* since, operationally, +they are often associated with results of empirical observation of +some physical or mathematical phenomena; precisely an experiment. We +assume that these values are distributed according to some +PDF $p_X^{\phantom X}(x)$, where $X$ is just the formal symbol for the +stochastic variable whose PDF is $p_X^{\phantom X}(x)$. Instead of +trying to determine the full distribution $p$ we are often only +interested in finding the few lowest moments, like the mean +$\mu_X^{\phantom X}$ and the variance $\sigma_X^{\phantom X}$. + +In practical situations a sample is always of finite size. Let that +size be $n$. The expectation value of a sample, the *sample mean*, is then defined as follows: +!bt +\[ +\bar{x}_n \equiv \frac{1}{n}\sum_{k=1}^n x_k +\] +!et +The *sample variance* is: +!bt +\[ +\mathrm{var}(x) \equiv \frac{1}{n}\sum_{k=1}^n (x_k - \bar{x}_n)^2 +\] +!et +its square root being the *standard deviation of the sample*. The +*sample covariance* is: +!bt +\[ +\mathrm{cov}(x)\equiv\frac{1}{n}\sum_{kl}(x_k - \bar{x}_n)(x_l - \bar{x}_n) +\] +!et + +Note that the sample variance is the sample covariance without the +cross terms. In a similar manner as the covariance in Eq.~(ref{eq:def_covariance}) is a measure of the correlation between +two stochastic variables, the above defined sample covariance is a +measure of the sequential correlation between succeeding measurements +of a sample. + +These quantities, being known experimental values, differ +significantly from and must not be confused with the similarly named +quantities for stochastic variables, mean $\mu_X$, variance $\mathrm{var}(X)$ +and covariance $\mathrm{cov}(X,Y)$. + +The law of large numbers +states that as the size of our sample grows to infinity, the sample +mean approaches the true mean $\mu_X^{\phantom X}$ of the chosen PDF: +!bt +\[ +\lim_{n\to\infty}\bar{x}_n = \mu_X^{\phantom X} +\] +!et +The sample mean $\bar{x}_n$ works therefore as an estimate of the true +mean $\mu_X^{\phantom X}$. + +What we need to find out is how good an approximation $\bar{x}_n$ is to +$\mu_X^{\phantom X}$. In any stochastic measurement, an estimated +mean is of no use to us without a measure of its error. A quantity +that tells us how well we can reproduce it in another experiment. We +are therefore interested in the PDF of the sample mean itself. Its +standard deviation will be a measure of the spread of sample means, +and we will simply call it the *error* of the sample mean, or +just sample error, and denote it by $\mathrm{err}_X^{\phantom X}$. In +practice, we will only be able to produce an *estimate* of the +sample error since the exact value would require the knowledge of the +true PDFs behind, which we usually do not have. + +===== Statistics, more on sample error ===== + +Let us first take a look at what happens to the sample error as the +size of the sample grows. In a sample, each of the measurements $x_i$ +can be associated with its own stochastic variable $X_i$. The +stochastic variable $\overline X_n$ for the sample mean $\bar{x}_n$ is +then just a linear combination, already familiar to us: +!bt +\[ +\overline X_n = \frac{1}{n}\sum_{i=1}^n X_i +\] +!et +All the coefficients are just equal $1/n$. The PDF of $\overline X_n$, +denoted by $p_{\overline X_n}(x)$ is the desired PDF of the sample +means. + +The probability density of obtaining a sample mean $\bar x_n$ +is the product of probabilities of obtaining arbitrary values $x_1, +x_2,\dots,x_n$ with the constraint that the mean of the set $\{x_i\}$ +is $\bar x_n$: +!bt +\[ +p_{\overline X_n}(x) = \int p_X^{\phantom X}(x_1)\cdots +\int p_X^{\phantom X}(x_n)\ +\delta\!\left(x - \frac{x_1+x_2+\dots+x_n}{n}\right)dx_n \cdots dx_1 +\] +!et +And in particular we are interested in its variance $\mathrm{var}(\overline X_n)$. + +===== Statistics, central limit theorem ===== + +It is generally not possible to express $p_{\overline X_n}(x)$ in a +closed form given an arbitrary PDF $p_X^{\phantom X}$ and a number +$n$. But for the limit $n\to\infty$ it is possible to make an +approximation. The very important result is called *the central limit theorem*. It tells us that as $n$ goes to infinity, +$p_{\overline X_n}(x)$ approaches a Gaussian distribution whose mean +and variance equal the true mean and variance, $\mu_{X}^{\phantom X}$ +and $\sigma_{X}^{2}$, respectively: +!bt +\begin{equation} +\lim_{n\to\infty} p_{\overline X_n}(x) = +\left(\frac{n}{2\pi\mathrm{var}(X)}\right)^{1/2} +e^{-\frac{n(x-\bar x_n)^2}{2\mathrm{var}(X)}} +label{eq:central_limit_gaussian} +\end{equation} +!et + + +The desired variance +$\mathrm{var}(\overline X_n)$, i.e. the sample error squared +$\mathrm{err}_X^2$, is given by: +!bt +\begin{equation} +\mathrm{err}_X^2 = \mathrm{var}(\overline X_n) = \frac{1}{n^2} +\sum_{ij} \mathrm{cov}(X_i, X_j) +label{eq:error_exact} +\end{equation} +!et +We see now that in order to calculate the exact error of the sample +with the above expression, we would need the true means +$\mu_{X_i}^{\phantom X}$ of the stochastic variables $X_i$. To +calculate these requires that we know the true multivariate PDF of all +the $X_i$. But this PDF is unknown to us, we have only got the measurements of +one sample. The best we can do is to let the sample itself be an +estimate of the PDF of each of the $X_i$, estimating all properties of +$X_i$ through the measurements of the sample. + +Our estimate of $\mu_{X_i}^{\phantom X}$ is then the sample mean $\bar x$ +itself, in accordance with the the central limit theorem: +!bt +\[ +\mu_{X_i}^{\phantom X} = \langle x_i\rangle \approx \frac{1}{n}\sum_{k=1}^n x_k = \bar x +\] +!et +Using $\bar x$ in place of $\mu_{X_i}^{\phantom X}$ we can give an +*estimate* of the covariance in Eq.~(ref{eq:error_exact}) +!bt +\[ +\mathrm{cov}(X_i, X_j) = \langle (x_i-\langle x_i\rangle)(x_j-\langle x_j\rangle)\rangle +\approx\langle (x_i - \bar x)(x_j - \bar{x})\rangle, +\] +!et +resulting in +!bt +\[ +\frac{1}{n} \sum_{l}^n \left(\frac{1}{n}\sum_{k}^n (x_k -\bar x_n)(x_l - \bar x_n)\right)=\frac{1}{n}\frac{1}{n} \sum_{kl} (x_k -\bar x_n)(x_l - \bar x_n)=\frac{1}{n}\mathrm{cov}(x) +\] +!et + +By the same procedure we can use the sample variance as an +estimate of the variance of any of the stochastic variables $X_i$ +!bt +\[ +\mathrm{var}(X_i)=\langle x_i - \langle x_i\rangle\rangle \approx \langle x_i - \bar x_n\rangle\nonumber, +\] +!et +which is approximated as +!bt +\begin{equation} +\mathrm{var}(X_i)\approx \frac{1}{n}\sum_{k=1}^n (x_k - \bar x_n)=\mathrm{var}(x) +label{eq:var_estimate_i_think} +\end{equation} +!et + +Now we can calculate an estimate of the error +$\mathrm{err}_X^{\phantom X}$ of the sample mean $\bar x_n$: +!bt +\begin{align} +\mathrm{err}_X^2 +&=\frac{1}{n^2}\sum_{ij} \mathrm{cov}(X_i, X_j) \nonumber \\ +&\approx&\frac{1}{n^2}\sum_{ij}\frac{1}{n}\mathrm{cov}(x) =\frac{1}{n^2}n^2\frac{1}{n}\mathrm{cov}(x)\nonumber\\ +&=\frac{1}{n}\mathrm{cov}(x) +label{eq:error_estimate} +\end{align} +!et +which is nothing but the sample covariance divided by the number of +measurements in the sample. + +In the special case that the measurements of the sample are +uncorrelated (equivalently the stochastic variables $X_i$ are +uncorrelated) we have that the off-diagonal elements of the covariance +are zero. This gives the following estimate of the sample error: +!bt +\[ +\mathrm{err}_X^2=\frac{1}{n^2}\sum_{ij} \mathrm{cov}(X_i, X_j) = +\frac{1}{n^2} \sum_i \mathrm{var}(X_i), +\] +!et +resulting in +!bt +\begin{equation} +\mathrm{err}_X^2\approx \frac{1}{n^2} \sum_i \mathrm{var}(x)= \frac{1}{n}\mathrm{var}(x) +label{eq:error_estimate_uncorrel} +\end{equation} +!et +where in the second step we have used Eq.~(ref{eq:var_estimate_i_think}). +The error of the sample is then just its standard deviation divided by +the square root of the number of measurements the sample contains. +This is a very useful formula which is easy to compute. It acts as a +first approximation to the error, but in numerical experiments, we +cannot overlook the always present correlations. + +For computational purposes one usually splits up the estimate of +$\mathrm{err}_X^2$, given by Eq.~(ref{eq:error_estimate}), into two +parts +!bt +\[ +\mathrm{err}_X^2 = \frac{1}{n}\mathrm{var}(x) + \frac{1}{n}(\mathrm{cov}(x)-\mathrm{var}(x)), +\] +!et +which equals +!bt +\begin{equation} +\frac{1}{n^2}\sum_{k=1}^n (x_k - \bar x_n)^2 +\frac{2}{n^2}\sum_{k 0$. We say then that the ridge estimator is biased. + +We can also compute the variance as + +!bt +\[ +\mbox{Var}[\bm{\beta}^{\mathrm{Ridge}}]=\sigma^2[ \mathbf{X}^{T} \mathbf{X} + \lambda \mathbf{I} ]^{-1} \mathbf{X}^{T} \mathbf{X} \{ [ \mathbf{X}^{\top} \mathbf{X} + \lambda \mathbf{I} ]^{-1}\}^{T}, +\] +!et +and it is easy to see that if the parameter $\lambda$ goes to infinity then the variance of Ridge parameters $\bm{\beta}$ goes to zero. + +With this, we can compute the difference + +!bt +\[ +\mbox{Var}[\bm{\beta}^{\mathrm{OLS}}]-\mbox{Var}(\bm{\beta}^{\mathrm{Ridge}})=\sigma^2 [ \mathbf{X}^{T} \mathbf{X} + \lambda \mathbf{I} ]^{-1}[ 2\lambda\mathbf{I} + \lambda^2 (\mathbf{X}^{T} \mathbf{X})^{-1} ] \{ [ \mathbf{X}^{T} \mathbf{X} + \lambda \mathbf{I} ]^{-1}\}^{T}. +\] +!et +The difference is non-negative definite since each component of the +matrix product is non-negative definite. +This means the variance we obtain with the standard OLS will always for $\lambda > 0$ be larger than the variance of $\bm{\beta}$ obtained with the Ridge estimator. This has interesting consequences when we discuss the so-called bias-variance trade-off below. - ===== Cross-validation ===== Instead of choosing the penalty parameter to balance model fit with @@ -5948,12 +3837,14 @@ model complexity, cross-validation requires it (i.e. the penalty parameter) to yield a model with good prediction performance. Commonly, this performance is evaluated on novel data. Novel data need not be easy to come by and one has to make do -with the data at hand. The setting of `original' and novel data is +with the data at hand. + +The setting of _original_ and novel data is then mimicked by sample splitting: the data set is divided into two -(groups of samples). One of these two data sets, called the *training -set*, plays the role of `original' data on which the model is +(groups of samples). One of these two data sets, called the +*training set*, plays the role of _original_ data on which the model is built. The second of these data sets, called the *test set*, plays the -role of the `novel' data and is used to evaluate the prediction +role of the _novel_ data and is used to evaluate the prediction performance (often operationalized as the log-likelihood or the prediction error or its square or the R2 score) of the model built on the training data set. This procedure (model building and prediction evaluation on training and @@ -5980,7 +3871,7 @@ The validation set approach is conceptually simple and is easy to implement. But - + ===== Various steps in cross-validation ===== When the repetitive splitting of the data set is done randomly, @@ -5998,52 +3889,36 @@ involves a degree of randomness. This may be fully excluded when choosing $k=n$. This particular case is referred to as leave-one-out cross-validation (LOOCV). - + ===== How to set up the cross-validation for Ridge and/or Lasso ===== * Define a range of interest for the penalty parameter. * Divide the data set into training and test set comprising samples $\{1, \ldots, n\} \setminus i$ and $\{ i \}$, respectively. -* Fit the linear regression model by means of ridge estimation for each $\lambda$ in the grid using the training set, and the corresponding estimate of the error variance $\hat{\sigma}_{-i}^2(\lambda)$, as +* Fit the linear regression model by means of ridge estimation for each $\lambda$ in the grid using the training set, and the corresponding estimate of the error variance $\bm{\sigma}_{-i}^2(\lambda)$, as !bt \begin{align*} -\hat{\beta}_{-i}(\lambda) & = ( \hat{X}_{-i, \ast}^{\top} -\hat{X}_{-i, \ast} + \lambda \hat{I}_{pp})^{-1} -\hat{X}_{-i, \ast}^{\top} \hat{y}_{-i} +\bm{\beta}_{-i}(\lambda) & = ( \bm{X}_{-i, \ast}^{T} +\bm{X}_{-i, \ast} + \lambda \bm{I}_{pp})^{-1} +\bm{X}_{-i, \ast}^{T} \bm{y}_{-i} \end{align*} !et -* Evaluate the prediction performance of these models on the test set by $\log\{L[y_i, \hat{X}_{i, \ast}; \hat{\beta}_{-i}(\lambda), \hat{\sigma}_{-i}^2(\lambda)]\}$. Or, by the prediction error $|y_i - \hat{X}_{i, \ast} \hat{\beta}_{-i}(\lambda)|$, the relative error, the error squared or the R2 score function. +* Evaluate the prediction performance of these models on the test set by $\log\{L[y_i, \bm{X}_{i, \ast}; \bm{\beta}_{-i}(\lambda), \bm{\sigma}_{-i}^2(\lambda)]\}$. Or, by the prediction error $|y_i - \bm{X}_{i, \ast} \bm{\beta}_{-i}(\lambda)|$, the relative error, the error squared or the R2 score function. * Repeat the first three steps such that each sample plays the role of the test set once. * Average the prediction performances of the test sets at each grid point of the penalty bias/parameter by computing the *cross-validated log-likelihood*. It is an estimate of the prediction performance of the model corresponding to this value of the penalty parameter on novel data. It is defined as !bt \begin{align*} -\frac{1}{n} \sum_{i = 1}^n \log\{L[y_i, \mathbf{X}_{i, \ast}; \hat{\beta}_{-i}(\lambda), \hat{\sigma}_{-i}^2(\lambda)]\}. +\frac{1}{n} \sum_{i = 1}^n \log\{L[y_i, \mathbf{X}_{i, \ast}; \bm{\beta}_{-i}(\lambda), \bm{\sigma}_{-i}^2(\lambda)]\}. \end{align*} !et * The value of the penalty parameter that maximizes the cross-validated log-likelihood is the value of choice. Or we can use the MSE or the R2 score functions. -===== Predicted Residual Error Sum of Squares ===== - -Another approach in the LOOCV scheme is to the use the so-called Predicted Residual Error Sum of Squares (PRESS). - -We can define the optimal penalty parameter to minimize -!bt -\begin{align*} -\lambda_{\mbox{{\tiny opt}}} = \arg \min_{\lambda} \frac{1}{n} \sum_{i=1}^n [y_i - \hat{X}_{i, \ast} \hat{\beta}_{-i}(\lambda)]^2. -\end{align*} -!et - -The LOOCV prediction performance can be -expressed analytically in terms of the known quantities derived from -the design matrix and the parameters $\beta$. - - ===== Resampling methods: Jackknife and Bootstrap ===== @@ -6067,33 +3942,20 @@ need for bootstrapping. ===== Resampling methods: Jackknife ===== The Jackknife works by making many replicas of the estimator $\widehat{\theta}$. -The jackknife is a resampling method, we explained that this happens by scrambling the data in some way. When using the jackknife, this is done by systematically leaving out one observation from the vector of observed values $\hat{x} = (x_1,x_2,\cdots,X_n)$. -Let $\hat{x}_i$ denote the vector +The jackknife is a resampling method where we systematically leave out one observation from the vector of observed values $\bm{x} = (x_1,x_2,\cdots,X_n)$. +Let $\bm{x}_i$ denote the vector !bt \[ -\hat{x}_i = (x_1,x_2,\cdots,x_{i-1},x_{i+1},\cdots,x_n), +\bm{x}_i = (x_1,x_2,\cdots,x_{i-1},x_{i+1},\cdots,x_n), \] !et -which equals the vector $\hat{x}$ with the exception that observation +which equals the vector $\bm{x}$ with the exception that observation number $i$ is left out. Using this notation, define $\widehat{\theta}_i$ to be the estimator $\widehat{\theta}$ computed using $\vec{X}_i$. -===== Resampling methods: Jackknife estimator ===== - -To get an estimate for the bias and -standard error of $\widehat{\theta}$, use the following -estimators for each component of $\widehat{\theta}$ - -!bt -\[ -\widehat{\mathrm{Bias}}(\widehat \theta,\theta) = (n-1)\left( - \widehat{\theta} + \frac{1}{n}\sum_{i=1}^{n} \widehat \theta_i \right) \qquad \text{and} \qquad \widehat{\sigma}^2_{\widehat{\theta} } = \frac{n-1}{n}\sum_{i=1}^{n}( \widehat{\theta}_i - \frac{1}{n}\sum_{j=1}^{n}\widehat \theta_j )^2. -\] -!et - - ===== Jackknife code example ===== !bc pycod @@ -6146,14 +4008,14 @@ o It is relatively simple to apply the bootstrap to complex data-collection plan ===== Resampling methods: Bootstrap background ===== -Since $\widehat{\theta} = \widehat{\theta}(\hat{X})$ is a function of random variables, +Since $\widehat{\theta} = \widehat{\theta}(\bm{X})$ is a function of random variables, $\widehat{\theta}$ itself must be a random variable. Thus it has -a pdf, call this function $p(\hat{t})$. The aim of the bootstrap is to -estimate $p(\hat{t})$ by the relative frequency of +a pdf, call this function $p(\bm{t})$. The aim of the bootstrap is to +estimate $p(\bm{t})$ by the relative frequency of $\widehat{\theta}$. You can think of this as using a histogram -in the place of $p(\hat{t})$. If the relative frequency closely +in the place of $p(\bm{t})$. If the relative frequency closely resembles $p(\vec{t})$, then using numerics, it is straight forward to -estimate all the interesting parameters of $p(\hat{t})$ using point +estimate all the interesting parameters of $p(\bm{t})$ using point estimators. @@ -6171,7 +4033,7 @@ o Then using these numbers, we could compute a replica of $\widehat{\theta}$ cal By repeated use of (1) and (2), many estimates of $\widehat{\theta}$ could have been obtained. The idea is to use the relative frequency of $\widehat{\theta}^*$ -(think of a histogram) as an estimate of $p(\hat{t})$. +(think of a histogram) as an estimate of $p(\bm{t})$. ===== Resampling methods: Bootstrap approach ===== @@ -6189,24 +4051,46 @@ result in some asymptotic sense? The answer is yes. Instead of generating the histogram for the relative frequency of the observation $X_i$, just draw the values $(X_1^*,X_2^*,\cdots,X_n^*)$ with replacement from the vector -$\hat{X}$. +$\bm{X}$. ===== Resampling methods: Bootstrap steps ===== The independent bootstrap works like this: -o Draw with replacement $n$ numbers for the observed variables $\hat{x} = (x_1,x_2,\cdots,x_n)$. -o Define a vector $\hat{x}^*$ containing the values which were drawn from $\hat{x}$. -o Using the vector $\hat{x}^*$ compute $\widehat{\theta}^*$ by evaluating $\widehat \theta$ under the observations $\hat{x}^*$. +o Draw with replacement $n$ numbers for the observed variables $\bm{x} = (x_1,x_2,\cdots,x_n)$. +o Define a vector $\bm{x}^*$ containing the values which were drawn from $\bm{x}$. +o Using the vector $\bm{x}^*$ compute $\widehat{\theta}^*$ by evaluating $\widehat \theta$ under the observations $\bm{x}^*$. o Repeat this process $k$ times. -When you are done, you can draw a histogram of the relative frequency of $\widehat \theta^*$. This is your estimate of the probability distribution $p(t)$. Using this probability distribution you can estimate any statistics thereof. In principle you never draw the histogram of the relative frequency of $\widehat{\theta}^*$. Instead you use the estimators corresponding to the statistic of interest. For example, if you are interested in estimating the variance of $\widehat \theta$, apply the etsimator $\widehat \sigma^2$ to the values $\widehat \theta ^*$. +When you are done, you can draw a histogram of the relative frequency +of $\widehat \theta^*$. This is your estimate of the probability +distribution $p(t)$. Using this probability distribution you can +estimate any statistics thereof. In principle you never draw the +histogram of the relative frequency of $\widehat{\theta}^*$. Instead +you use the estimators corresponding to the statistic of interest. For +example, if you are interested in estimating the variance of $\widehat +\theta$, apply the etsimator $\widehat \sigma^2$ to the values +$\widehat \theta ^*$. ===== Code example for the Bootstrap method ===== -The following code starts with a Gaussian distribution with mean value $\mu =100$ and variance $\sigma=15$. We use this to generate the data used in the bootstrap analysis. The bootstrap analysis returns a data set after a given number of bootstrap operations (as many as we have data points). This data set consists of estimated mean values for each bootstrap operation. The histogram generated by the bootstrap method shows that the distribution for these mean values is also a Gaussian, centered around the mean value $\mu=100$ but with standard deviation $\sigma/\sqrt{n}$, where $n$ is the number of bootstrap samples (in this case the same as the number of original data points). The value of the standard deviation is what we expect from the central limit theorem. + +The following code starts with a Gaussian distribution with mean value +$\mu =100$ and variance $\sigma=15$. We use this to generate the data +used in the bootstrap analysis. The bootstrap analysis returns a data +set after a given number of bootstrap operations (as many as we have +data points). This data set consists of estimated mean values for each +bootstrap operation. The histogram generated by the bootstrap method +shows that the distribution for these mean values is also a Gaussian, +centered around the mean value $\mu=100$ but with standard deviation +$\sigma/\sqrt{n}$, where $n$ is the number of bootstrap samples (in +this case the same as the number of original data points). The value +of the standard deviation is what we expect from the central limit +theorem. + + !bc pycod from numpy import * from numpy.random import randint, randn @@ -6218,30 +4102,29 @@ import matplotlib.pyplot as plt def stat(data): return mean(data) -# Bootstrap algorithm +# Bootstrap algorithm def bootstrap(data, statistic, R): t = zeros(R); n = len(data); inds = arange(n); t0 = time() - - # non-parametric bootstrap + # non-parametric bootstrap for i in range(R): t[i] = statistic(data[randint(0,n,n)]) - # analysis + # analysis print("Runtime: %g sec" % (time()-t0)); print("Bootstrap Statistics :") print("original bias std. error") - print("%8g %8g %14g %15g" % (statistic(data), std(data),\ - mean(t), \ - std(t))) + print("%8g %8g %14g %15g" % (statistic(data), std(data),mean(t),std(t))) return t mu, sigma = 100, 15 datapoints = 10000 x = mu + sigma*random.randn(datapoints) -# bootstrap returns the data sample t = bootstrap(x, stat, datapoints) -# the histogram of the bootstrapped data n, binsboot, patches = plt.hist(t, 50, normed=1, facecolor='red', alpha=0.75) +# bootstrap returns the data sample +t = bootstrap(x, stat, datapoints) +# the histogram of the bootstrapped data +n, binsboot, patches = plt.hist(t, 50, normed=1, facecolor='red', alpha=0.75) -# add a 'best fit' line +# add a 'best fit' line y = mlab.normpdf( binsboot, mean(t), std(t)) lt = plt.plot(binsboot, y, 'r--', linewidth=1) plt.xlabel('Smarts') @@ -6255,342 +4138,99 @@ plt.show() -===== Resampling methods: Blocking ===== - -The blocking method was made popular by "Flyvbjerg and Pedersen (1989)":"https://aip.scitation.org/doi/10.1063/1.457480" -and has become one of the standard ways to estimate -$V(\widehat{\theta})$ for exactly one $\widehat{\theta}$, namely -$\widehat{\theta} = \overline{X}$. - -Assume $n = 2^d$ for some integer $d>1$ and $X_1,X_2,\cdots, X_n$ is a stationary time series to begin with. -Moreover, assume that the time series is asymptotically uncorrelated. We switch to vector notation by arranging $X_1,X_2,\cdots,X_n$ in an $n$-tuple. Define: -!bt -\begin{align*} -\hat{X} = (X_1,X_2,\cdots,X_n). -\end{align*} -!et - -The strength of the blocking method is when the number of -observations, $n$ is large. For large $n$, the complexity of dependent -bootstrapping scales poorly, but the blocking method does not, -moreover, it becomes more accurate the larger $n$ is. - - -===== Blocking Transformations ===== - We now define -blocking transformations. The idea is to take the mean of subsequent -pair of elements from $\vec{X}$ and form a new vector -$\vec{X}_1$. Continuing in the same way by taking the mean of -subsequent pairs of elements of $\vec{X}_1$ we obtain $\vec{X}_2$, and -so on. -Define $\vec{X}_i$ recursively by: - -!bt -\begin{align} -(\vec{X}_0)_k &\equiv (\vec{X})_k \nonumber \\ -(\vec{X}_{i+1})_k &\equiv \frac{1}{2}\Big( (\vec{X}_i)_{2k-1} + -(\vec{X}_i)_{2k} \Big) \qquad \text{for all} \qquad 1 \leq i \leq d-1 -\end{align} -!et - -The quantity $\vec{X}_k$ is -subject to $k$ _blocking transformations_. We now have $d$ vectors -$\vec{X}_0, \vec{X}_1,\cdots,\vec X_{d-1}$ containing the subsequent -averages of observations. It turns out that if the components of -$\vec{X}$ is a stationary time series, then the components of -$\vec{X}_i$ is a stationary time series for all $0 \leq i \leq d-1$ - -We can then compute the autocovariance, the variance, sample mean, and -number of observations for each $i$. -Let $\gamma_i, \sigma_i^2, -\overline{X}_i$ denote the autocovariance, variance and average of the -elements of $\vec{X}_i$ and let $n_i$ be the number of elements of -$\vec{X}_i$. It follows by induction that $n_i = n/2^i$. - - -===== Blocking Transformations ===== - -Using the -definition of the blocking transformation and the distributive -property of the covariance, it is clear that since $h =|i-j|$ -we can define -!bt -\begin{align} -\gamma_{k+1}(h) &= cov\left( ({X}_{k+1})_{i}, ({X}_{k+1})_{j} \right) \nonumber \\ -&= \frac{1}{4}cov\left( ({X}_{k})_{2i-1} + ({X}_{k})_{2i}, ({X}_{k})_{2j-1} + ({X}_{k})_{2j} \right) \nonumber \\ -&= \frac{1}{2}\gamma_{k}(2h) + \frac{1}{2}\gamma_k(2h+1) \hspace{0.1cm} \mathrm{h = 0} \\ -&=\frac{1}{4}\gamma_k(2h-1) + \frac{1}{2}\gamma_k(2h) + \frac{1}{4}\gamma_k(2h+1) \quad \mathrm{else} -\end{align} -!et - -The quantity $\hat{X}$ is asymptotic uncorrelated by assumption, $\hat{X}_k$ is also asymptotic uncorrelated. Let's turn our attention to the variance of the sample mean $V(\overline{X})$. - - -===== Blocking Transformations, getting there ===== -We have -!bt -\begin{align} -V(\overline{X}_k) = \frac{\sigma_k^2}{n_k} + \underbrace{\frac{2}{n_k} \sum_{h=1}^{n_k-1}\left( 1 - \frac{h}{n_k} \right)\gamma_k(h)}_{\equiv e_k} = \frac{\sigma^2_k}{n_k} + e_k \quad \text{if} \quad \gamma_k(0) = \sigma_k^2. -\end{align} -!et -The term $e_k$ is called the _truncation error_: -!bt -\begin{equation} -e_k = \frac{2}{n_k} \sum_{h=1}^{n_k-1}\left( 1 - \frac{h}{n_k} \right)\gamma_k(h). -\end{equation} -!et -We can show that $V(\overline{X}_i) = V(\overline{X}_j)$ for all $0 \leq i \leq d-1$ and $0 \leq j \leq d-1$. - - -===== Blocking Transformations, final expressions ===== - -We can then wrap up -!bt -\begin{align} -n_{j+1} \overline{X}_{j+1} &= \sum_{i=1}^{n_{j+1}} (\hat{X}_{j+1})_i = \frac{1}{2}\sum_{i=1}^{n_{j}/2} (\hat{X}_{j})_{2i-1} + (\hat{X}_{j})_{2i} \nonumber \\ -&= \frac{1}{2}\left[ (\hat{X}_j)_1 + (\hat{X}_j)_2 + \cdots + (\hat{X}_j)_{n_j} \right] = \underbrace{\frac{n_j}{2}}_{=n_{j+1}} \overline{X}_j = n_{j+1}\overline{X}_j. -\end{align} -!et -By repeated use of this equation we get $V(\overline{X}_i) = V(\overline{X}_0) = V(\overline{X})$ for all $0 \leq i \leq d-1$. This has the consequence that -!bt -\begin{align} -V(\overline{X}) = \frac{\sigma_k^2}{n_k} + e_k \qquad \text{for all} \qquad 0 \leq k \leq d-1. \label{eq:convergence} -\end{align} -!et - -Fyvbjerg and Petersen demonstrated that the sequence -$\{e_k\}_{k=0}^{d-1}$ is decreasing, and conjecture that the term -$e_k$ can be made as small as we would like by making $k$ (and hence -$d$) sufficiently large. The sequence is decreasing (Master of Science thesis by Marius Jonsson, UiO 2018). -It means we can apply blocking transformations until -$e_k$ is sufficiently small, and then estimate $V(\overline{X})$ by -$\widehat{\sigma}^2_k/n_k$. - - - -===== "Code examples for Blocking, Jackknife and bootstrap":"https://github.com/CompPhysics/MachineLearning/tree/master/doc/Programs/ResamplingAnalysisScripts" ===== +===== Code Example for Cross-validation and $k$-fold Cross-validation ===== +The code here uses Ridge regression with cross-validation (CV) resampling and $k$-fold CV in order to fit a specific polynomial. !bc pycod -from sys import argv -from os import mkdir, path -import time import numpy as np import matplotlib.pyplot as plt -from matplotlib.ticker import FormatStrFormatter -from matplotlib.font_manager import FontProperties +from sklearn.model_selection import KFold +from sklearn.linear_model import Ridge +from sklearn.model_selection import cross_val_score +from sklearn.preprocessing import PolynomialFeatures -# Timing Decorator -def timeFunction(f): - def wrap(*args): - time1 = time.time() - ret = f(*args) - time2 = time.time() - print '%s Function Took: \t %0.3f s' % (f.func_name.title(), (time2-time1)) - return ret - return wrap +# A seed just to ensure that the random numbers are the same for every run. +# Useful for eventual debugging. +np.random.seed(3155) -class dataAnalysisClass: - # General Init functions - def __init__(self, fileName, size=0): - self.inputFileName = fileName - self.loadData(size) - self.createOutputFolder() - self.avg = np.average(self.data) - self.var = np.var(self.data) - self.std = np.std(self.data) +# Generate the data. +nsamples = 100 +x = np.random.randn(nsamples) +y = 3*x**2 + np.random.randn(nsamples) - def loadData(self, size=0): - if size != 0: - with open(self.inputFileName) as inputFile: - self.data = np.zeros(size) - for x in xrange(size): - self.data[x] = float(next(inputFile)) - else: - self.data = np.loadtxt(self.inputFileName) +## Cross-validation on Ridge regression using KFold only - # Statistical Analysis with Multiple Methods - def runAllAnalyses(self): - if len(self.data) <= 100000: - print "Autocorrelation..." - self.autocorrelation() - print "Bootstrap..." - self.bootstrap() - print "Jackknife..." - self.jackknife() - print "Blocking..." - self.blocking() +# Decide degree on polynomial to fit +poly = PolynomialFeatures(degree = 6) - # Standard Autocorrelation - @timeFunction - def autocorrelation(self): - self.acf = np.zeros(len(self.data)/2) - for k in range(0, len(self.data)/2): - self.acf[k] = np.corrcoef(np.array([self.data[0:len(self.data)-k], \ - self.data[k:len(self.data)]]))[0,1] +# Decide which values of lambda to use +nlambdas = 500 +lambdas = np.logspace(-3, 5, nlambdas) - # Bootstrap - @timeFunction - def bootstrap(self, nBoots = 1000): - bootVec = np.zeros(nBoots) - for k in range(0,nBoots): - bootVec[k] = np.average(np.random.choice(self.data, len(self.data))) - self.bootAvg = np.average(bootVec) - self.bootVar = np.var(bootVec) - self.bootStd = np.std(bootVec) +# Initialize a KFold instance +k = 5 +kfold = KFold(n_splits = k) - # Jackknife - @timeFunction - def jackknife(self): - jackknVec = np.zeros(len(self.data)) - for k in range(0,len(self.data)): - jackknVec[k] = np.average(np.delete(self.data, k)) - self.jackknAvg = self.avg - (len(self.data) - 1) * (np.average(jackknVec) - self.avg) - self.jackknVar = float(len(self.data) - 1) * np.var(jackknVec) - self.jackknStd = np.sqrt(self.jackknVar) +# Perform the cross-validation to estimate MSE +scores_KFold = np.zeros((nlambdas, k)) - # Blocking - @timeFunction - def blocking(self, blockSizeMax = 500): - blockSizeMin = 1 +i = 0 +for lmb in lambdas: + ridge = Ridge(alpha = lmb) + j = 0 + for train_inds, test_inds in kfold.split(x): + xtrain = x[train_inds] + ytrain = y[train_inds] - self.blockSizes = [] - self.meanVec = [] - self.varVec = [] + xtest = x[test_inds] + ytest = y[test_inds] - for i in range(blockSizeMin, blockSizeMax): - if(len(self.data) % i != 0): - pass#continue - blockSize = i - meanTempVec = [] - varTempVec = [] - startPoint = 0 - endPoint = blockSize + Xtrain = poly.fit_transform(xtrain[:, np.newaxis]) + ridge.fit(Xtrain, ytrain[:, np.newaxis]) - while endPoint <= len(self.data): - meanTempVec.append(np.average(self.data[startPoint:endPoint])) - startPoint = endPoint - endPoint += blockSize - mean, var = np.average(meanTempVec), np.var(meanTempVec)/len(meanTempVec) - self.meanVec.append(mean) - self.varVec.append(var) - self.blockSizes.append(blockSize) + Xtest = poly.fit_transform(xtest[:, np.newaxis]) + ypred = ridge.predict(Xtest) - self.blockingAvg = np.average(self.meanVec[-200:]) - self.blockingVar = (np.average(self.varVec[-200:])) - self.blockingStd = np.sqrt(self.blockingVar) + scores_KFold[i,j] = np.sum((ypred - ytest[:, np.newaxis])**2)/np.size(ypred) + + j += 1 + i += 1 +estimated_mse_KFold = np.mean(scores_KFold, axis = 1) - # Plot of Data, Autocorrelation Function and Histogram - def plotAll(self): - self.createOutputFolder() - if len(self.data) <= 100000: - self.plotAutocorrelation() - self.plotData() - self.plotHistogram() - self.plotBlocking() +## Cross-validation using cross_val_score from sklearn along with KFold - # Create Output Plots Folder - def createOutputFolder(self): - self.outName = self.inputFileName[:-4] - if not path.exists(self.outName): - mkdir(self.outName) +# kfold is an instance initialized above as: +# kfold = KFold(n_splits = k) - # Plot the Dataset, Mean and Std - def plotData(self): - # Far away plot - font = {'fontname':'serif'} - plt.plot(range(0, len(self.data)), self.data, 'r-', linewidth=1) - plt.plot([0, len(self.data)], [self.avg, self.avg], 'b-', linewidth=1) - plt.plot([0, len(self.data)], [self.avg + self.std, self.avg + self.std], 'g--', linewidth=1) - plt.plot([0, len(self.data)], [self.avg - self.std, self.avg - self.std], 'g--', linewidth=1) - plt.ylim(self.avg - 5*self.std, self.avg + 5*self.std) - plt.gca().yaxis.set_major_formatter(FormatStrFormatter('%.4f')) - plt.xlim(0, len(self.data)) - plt.ylabel(self.outName.title() + ' Monte Carlo Evolution', **font) - plt.xlabel('MonteCarlo History', **font) - plt.title(self.outName.title(), **font) - plt.savefig(self.outName + "/data.eps") - plt.savefig(self.outName + "/data.png") - plt.clf() +estimated_mse_sklearn = np.zeros(nlambdas) +i = 0 +for lmb in lambdas: + ridge = Ridge(alpha = lmb) - # Plot Histogram of Dataset and Gaussian around it - def plotHistogram(self): - binNumber = 50 - font = {'fontname':'serif'} - count, bins, ignore = plt.hist(self.data, bins=np.linspace(self.avg - 5*self.std, self.avg + 5*self.std, binNumber)) - plt.plot([self.avg, self.avg], [0,np.max(count)+10], 'b-', linewidth=1) - plt.ylim(0,np.max(count)+10) - plt.ylabel(self.outName.title() + ' Histogram', **font) - plt.xlabel(self.outName.title() , **font) - plt.title('Counts', **font) + X = poly.fit_transform(x[:, np.newaxis]) + estimated_mse_folds = cross_val_score(ridge, X, y[:, np.newaxis], scoring='neg_mean_squared_error', cv=kfold) - #gaussian - norm = 0 - for i in range(0,len(bins)-1): - norm += (bins[i+1]-bins[i])*count[i] - plt.plot(bins, norm/(self.std * np.sqrt(2 * np.pi)) * np.exp( - (bins - self.avg)**2 / (2 * self.std**2) ), linewidth=1, color='r') - plt.savefig(self.outName + "/hist.eps") - plt.savefig(self.outName + "/hist.png") - plt.clf() + # cross_val_score return an array containing the estimated negative mse for every fold. + # we have to the the mean of every array in order to get an estimate of the mse of the model + estimated_mse_sklearn[i] = np.mean(-estimated_mse_folds) - # Plot the Autocorrelation Function - def plotAutocorrelation(self): - font = {'fontname':'serif'} - plt.plot(range(1, len(self.data)/2), self.acf[1:], 'r-') - plt.ylim(-1, 1) - plt.xlim(0, len(self.data)/2) - plt.ylabel('Autocorrelation Function', **font) - plt.xlabel('Lag', **font) - plt.title('Autocorrelation', **font) - plt.savefig(self.outName + "/autocorrelation.eps") - plt.savefig(self.outName + "/autocorrelation.png") - plt.clf() + i += 1 - def plotBlocking(self): - font = {'fontname':'serif'} - plt.plot(self.blockSizes, self.varVec, 'r-') - plt.ylabel('Variance', **font) - plt.xlabel('Block Size', **font) - plt.title('Blocking', **font) - plt.savefig(self.outName + "/blocking.eps") - plt.savefig(self.outName + "/blocking.png") - plt.clf() +## Plot and compare the slightly different ways to perform cross-validation - # Print Stuff to the Terminal - def printOutput(self): - print "\nSample Size: \t", len(self.data) - print "\n=========================================\n" - print "Sample Average: \t", self.avg - print "Sample Variance:\t", self.var - print "Sample Std: \t", self.std - print "\n=========================================\n" - print "Bootstrap Average: \t", self.bootAvg - print "Bootstrap Variance:\t", self.bootVar - print "Bootstrap Error: \t", self.bootStd - print "\n=========================================\n" - print "Jackknife Average: \t", self.jackknAvg - print "Jackknife Variance:\t", self.jackknVar - print "Jackknife Error: \t", self.jackknStd - print "\n=========================================\n" - print "Blocking Average: \t", self.blockingAvg - print "Blocking Variance:\t", self.blockingVar - print "Blocking Error: \t", self.blockingStd, "\n" +plt.figure() -# Initialize the class -if len(argv) > 2: - dataAnalysis = dataAnalysisClass(argv[1], int(argv[2])) -else: - dataAnalysis = dataAnalysisClass(argv[1]) +plt.plot(np.log10(lambdas), estimated_mse_sklearn, label = 'cross_val_score') +plt.plot(np.log10(lambdas), estimated_mse_KFold, 'r--', label = 'KFold') -# Run Analyses -dataAnalysis.runAllAnalyses() +plt.xlabel('log10(lambda)') +plt.ylabel('mse') -# Plot the data -dataAnalysis.plotAll() +plt.legend() -# Print Some Output -dataAnalysis.printOutput() +plt.show() !ec @@ -6598,139 +4238,204 @@ dataAnalysis.printOutput() ===== The bias-variance tradeoff ===== -We begin with an unknown function $y=f(x)$ and fix a \emph{hypothesis set} - $\mathcal{H}$ consisting of all functions we are willing to consider, - defined also on the domain of $f$. This set may be uncountably - infinite (e.g.~if there are real-valued parameters to fit). -The - choice of which functions to include in $\mathcal{H}$ usually depends - on our intuition about the problem of interest. The function $f(x)$ - produces a set of pairs $(x_i,y_i)$, $i=1\dots N$, which serve as the - observable data. Our goal is to select a function from the hypothesis - set $h\in\mathcal{H}$ which approximates $f(x)$ as best as possible, - namely, we would like to find $h\in\mathcal{H}$ such that $h\approx - f$ in some strict mathematical sense which we specify below. If this - is possible, we say that we \emph{learned} $f(x)$. But if the - function $f(x)$ can, in principle, take any value on - \emph{unobserved} inputs, how is it possible to learn in any - meaningful sense? - -===== Training and testing data ===== +We will discuss the bias-variance tradeoff in the context of +continuous predictions such as regression. However, many of the +intuitions and ideas discussed here also carry over to classification +tasks. Consider a dataset $\mathcal{L}$ consisting of the data +$\mathbf{X}_\mathcal{L}=\{(y_j, \boldsymbol{x}_j), j=0\ldots n-1\}$. -We will discuss the bias-variance tradeoff in the context of continuous predictions such as regression. However, many of the intuitions and ideas discussed here also carry over to classification tasks. Consider a dataset $\mathcal{L}$ consisting of the data $\mathbf{X}_\mathcal{L}=\{(y_j, \boldsymbol{x}_j), j=1\ldots N\}$. Let us assume that the true data is generated from a noisy model -!bt -\[ -y=f(\boldsymbol{x}) + \epsilon -\] -!et -where $\epsilon$ is normally distributed with mean zero and standard deviation $\sigma_\epsilon$. - - -===== Procedure to find a predictor ===== - -We have a statistical procedure (e.g. least-squares regression) for -forming a predictor $\hat{g}_{\mathcal{L}}(\boldsymbol{x})$ that gives the -prediction of our model for a new data point $\boldsymbol{x}$. This estimator -is chosen by minimizing a cost function which we take to be the -squared error +Let us assume that the true data is generated from a noisy model !bt \[ - \mathcal{C}( \boldsymbol{X}, \hat{g}(\boldsymbol{x})) = \sum_i (y_i - \hat{g}_\mathcal{L}(\boldsymbol{x}_i))^2. +\bm{y}=f(\boldsymbol{x}) + \bm{\epsilon} \] !et +where $\epsilon$ is normally distributed with mean zero and standard deviation $\sigma^2$. -===== What we want ===== +In our derivation of the ordinary least squares method we defined then +an approximation to the function $f$ in terms of the parameters +$\bm{\beta}$ and the design matrix $\bm{X}$ which embody our model, +that is $\bm{\tilde{y}}=\bm{X}\bm{\beta}$. -We are interested in the generalization error on all data drawn from -the true model, not just the error on the particular training dataset -$\mathcal{L}$ that we have in hand. This is just the expectation of -the cost function over many different data sets -$\{\mathcal{L}_j\}$. Denote this expectation value by -$E_{\mathcal{L}}$. In other words, we can view $\hat{g}_{\mathcal{L}}$ -as a stochastic functional that depends on the dataset $\mathcal{L}$ -and we can think of $E_{\mathcal{L}}$ as the expected value of the -functional if we drew an infinite number of datasets $\{\mathcal{L}_1, -\mathcal{L}_2, \ldots \}$. - - - -===== The expected generalization error ===== - -We would also like to average over different instances of the -``noise'' $\epsilon$ and we denote the expectation value over the -noise by $E_\epsilon$. Thus, we can decompose the expected -generalization error as - - -!bt -\begin{align} -E_\mathcal{L, \epsilon}[\mathcal{C}( \boldsymbol{X}, \hat{g}(\boldsymbol{x})) ]&= E_\mathcal{L,\epsilon}\left[ \sum_i ({y}_i - \hat{g}_\mathcal{L}(\boldsymbol{x}_i))^2 \right] \nonumber \\ - &= E_\mathcal{L, \epsilon}\left[ \sum_{i}({y}_i -f(\boldsymbol{x}_i) +f(\boldsymbol{x}_i)- \hat{g}_\mathcal{L}(\boldsymbol{x}_i))^2\right] \nonumber \\ - &= \sum_i E_\epsilon[ ({y}_i -f(\boldsymbol{x}_i))^2 ]+ E_\mathcal{L, \epsilon}[(f(\boldsymbol{x}_i)- \hat{g}_\mathcal{L}(\boldsymbol{x}_i))^2] + 2E_\epsilon[{y}_i -f(\boldsymbol{x}_i)]E_\mathcal{L}[f(\boldsymbol{x}_i)- \hat{g}_\mathcal{L}(\boldsymbol{x}_i)] \nonumber \\ - &=\sum_i \sigma_\epsilon^2 + E_\mathcal{L}[(f(\boldsymbol{x}_i)- \hat{g}_\mathcal{L}(\boldsymbol{x}_i))^2], -\end{align} -!et - -where in the last line we used the fact that our noise has zero mean -and variance $\sigma_\epsilon^2$ and the sum over $i$ applies to all -terms. - - -===== Elaborating a little bit more ===== - -It is also helpful to further decompose the second term as -follows: - -!bt -\begin{align} -E_\mathcal{L}[(f(\boldsymbol{x}_i)- \hat{g}_\mathcal{L}(\boldsymbol{x}_i))^2] &=E_\mathcal{L}[(f(\mathbf{x}_i)-E_\mathcal{L}[\hat{g}_\mathcal{L}(\boldsymbol{x}_i)]+ E_\mathcal{L}[\hat{g}_\mathcal{L}(\boldsymbol{x}_i)]- \hat{g}_\mathcal{L}(\boldsymbol{x}_i))^2] \nonumber \\ -&=E_\mathcal{L}[(f(\boldsymbol{x}_i)-E_\mathcal{L}[\hat{g}_\mathcal{L}(\boldsymbol{x}_i)])^2] + E_\mathcal{L}[( \hat{g}_\mathcal{L}(\boldsymbol{x}_i)-E_\mathcal{L}[\hat{g}_\mathcal{L}(\boldsymbol{x}_i)])^2] \nonumber \\ -&+2E_\mathcal{L}[(f(\boldsymbol{x}_i)-E_\mathcal{L}[\hat{g}_\mathcal{L}(\boldsymbol{x}_i)])( \hat{g}_\mathcal{L}(\boldsymbol{x}_i)-E_\mathcal{L}[\hat{g}_\mathcal{L}(\boldsymbol{x}_i)])] \nonumber \\ -&=(f(\boldsymbol{x}_i)-E_\mathcal{L}[\hat{g}_\mathcal{L}(\boldsymbol{x}_i)])^2+E_\mathcal{L}[( \hat{g}_\mathcal{L}(\boldsymbol{x}_i)-E_\mathcal{L}[\hat{g}_\mathcal{L}(\boldsymbol{x}_i)])^2]. -\end{align} -!et - - -===== The bias ===== - -The first term is called the bias +Thereafter we found the parameters $\bm{\beta}$ by optimizing the means squared error via the so-called cost function !bt \[ -Bias^2= \sum_i (f(\boldsymbol{x}_i)-E_\mathcal{L}[\hat{g}_\mathcal{L}(\boldsymbol{x}_i)])^2 +C(\bm{X},\bm{\beta}) =\frac{1}{n}\sum_{i=0}^{n-1}(y_i-\tilde{y}_i)^2=\mathbb{E}\left[(\bm{y}-\bm{\tilde{y}})^2\right]. \] !et -and measures the deviation of the expectation value of our estimator (i.e. the asymptotic value of our estimator in the infinite data limit) from the true value. - -===== The variance ===== -The second term is called the variance +We can rewrite this as !bt \[ -Var=\sum_i E_\mathcal{L}[( \hat{g}_\mathcal{L}(\boldsymbol{x}_i)-E_\mathcal{L}[\hat{g}_\mathcal{L}(\boldsymbol{x}_i)])^2], +\mathbb{E}\left[(\bm{y}-\bm{\tilde{y}})^2\right]=\frac{1}{n}\sum_i(f_i-\mathbb{E}\left[\bm{\tilde{y}}\right])^2+\frac{1}{n}\sum_i(\tilde{y}_i-\mathbb{E}\left[\bm{\tilde{y}}\right])^2+\sigma^2. \] !et -and measures how much our estimator fluctuates due to finite-sample effects. Combining these expressions, we see that the expected out-of-sample error of our model can be decomposed as +The three terms represent the square of the bias of the learning +method, which can be thought of as the error caused by the simplifying +assumptions built into the method. The second term represents the +variance of the chosen model and finally the last terms is variance of +the error $\bm{\epsilon}$. + +To derive this equation, we need to recall that the variance of $\bm{y}$ and $\bm{\epsilon}$ are both equal to $\sigma^2$. The mean value of $\bm{\epsilon}$ is by definition equal to zero. Furthermore, the function $f$ is not a stochastics variable, idem for $\bm{\tilde{y}}$. +We use a more compact notation in terms of the expectation value !bt \[ -E_\mathrm{out}=E_\mathcal{L, \epsilon}[\mathcal{C}( \boldsymbol{X}, \hat{g}(\boldsymbol{x})) ] = Bias^2 + Var + Noise. +\mathbb{E}\left[(\bm{y}-\bm{\tilde{y}})^2\right]=\mathbb{E}\left[(\bm{f}+\bm{\epsilon}-\bm{\tilde{y}})^2\right], \] !et +and adding and subtracting $\mathbb{E}\left[\bm{\tilde{y}}\right]$ we get +!bt +\[ +\mathbb{E}\left[(\bm{y}-\bm{\tilde{y}})^2\right]=\mathbb{E}\left[(\bm{f}+\bm{\epsilon}-\bm{\tilde{y}}+\mathbb{E}\left[\bm{\tilde{y}}\right]-\mathbb{E}\left[\bm{\tilde{y}}\right])^2\right], +\] +!et +which, using the abovementioned expectation values can be rewritten as +!bt +\[ +\mathbb{E}\left[(\bm{y}-\bm{\tilde{y}})^2\right]=\mathbb{E}\left[(\bm{y}-\mathbb{E}\left[\bm{\tilde{y}}\right])^2\right]+\mathrm{Var}\left[\bm{\tilde{y}}\right]+\sigma^2, +\] +!et +that is the rewriting in terms of the so-called bias, the variance of the model $\bm{\tilde{y}}$ and the variance of $\bm{\epsilon}$. + + + + + +===== Example code for Bias-Variance tradeoff ===== +!bc pycod +import matplotlib.pyplot as plt +import numpy as np +from sklearn.linear_model import LinearRegression, Ridge, Lasso +from sklearn.preprocessing import PolynomialFeatures +from sklearn.model_selection import train_test_split +from sklearn.pipeline import make_pipeline +from sklearn.utils import resample + +np.random.seed(2018) + +n = 500 +n_boostraps = 100 +degree = 18 # A quite high value, just to show. +noise = 0.1 + +# Make data set. +x = np.linspace(-1, 3, n).reshape(-1, 1) +y = np.exp(-x**2) + 1.5 * np.exp(-(x-2)**2) + np.random.normal(0, 0.1, x.shape) + +# Hold out some test data that is never used in training. +x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.2) + +# Combine x transformation and model into one operation. +# Not neccesary, but convenient. +model = make_pipeline(PolynomialFeatures(degree=degree), LinearRegression(fit_intercept=False)) + +# The following (m x n_bootstraps) matrix holds the column vectors y_pred +# for each bootstrap iteration. +y_pred = np.empty((y_test.shape[0], n_boostraps)) +for i in range(n_boostraps): + x_, y_ = resample(x_train, y_train) + + # Evaluate the new model on the same test data each time. + y_pred[:, i] = model.fit(x_, y_).predict(x_test).ravel() + +# Note: Expectations and variances taken w.r.t. different training +# data sets, hence the axis=1. Subsequent means are taken across the test data +# set in order to obtain a total value, but before this we have error/bias/variance +# calculated per data point in the test set. +# Note 2: The use of keepdims=True is important in the calculation of bias as this +# maintains the column vector form. Dropping this yields very unexpected results. +error = np.mean( np.mean((y_test - y_pred)**2, axis=1, keepdims=True) ) +bias = np.mean( (y_test - np.mean(y_pred, axis=1, keepdims=True))**2 ) +variance = np.mean( np.var(y_pred, axis=1, keepdims=True) ) +print('Error:', error) +print('Bias^2:', bias) +print('Var:', variance) +print('{} >= {} + {} = {}'.format(error, bias, variance, bias+variance)) + +plt.plot(x[::5, :], y[::5, :], label='f(x)') +plt.scatter(x_test, y_test, label='Data points') +plt.scatter(x_test, np.mean(y_pred, axis=1), label='Pred') +plt.legend() +plt.show() + +!ec + + + +===== Understanding what happens ===== +!bc pycod +import matplotlib.pyplot as plt +import numpy as np +from sklearn.linear_model import LinearRegression, Ridge, Lasso +from sklearn.preprocessing import PolynomialFeatures +from sklearn.model_selection import train_test_split +from sklearn.pipeline import make_pipeline +from sklearn.utils import resample + +np.random.seed(2018) + +n = 40 +n_boostraps = 100 +maxdegree = 14 + + +# Make data set. +x = np.linspace(-3, 3, n).reshape(-1, 1) +y = np.exp(-x**2) + 1.5 * np.exp(-(x-2)**2)+ np.random.normal(0, 0.1, x.shape) +error = np.zeros(maxdegree) +bias = np.zeros(maxdegree) +variance = np.zeros(maxdegree) +polydegree = np.zeros(maxdegree) +x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.2) + +for degree in range(maxdegree): + model = make_pipeline(PolynomialFeatures(degree=degree), LinearRegression(fit_intercept=False)) + y_pred = np.empty((y_test.shape[0], n_boostraps)) + for i in range(n_boostraps): + x_, y_ = resample(x_train, y_train) + y_pred[:, i] = model.fit(x_, y_).predict(x_test).ravel() + + polydegree[degree] = degree + error[degree] = np.mean( np.mean((y_test - y_pred)**2, axis=1, keepdims=True) ) + bias[degree] = np.mean( (y_test - np.mean(y_pred, axis=1, keepdims=True))**2 ) + variance[degree] = np.mean( np.var(y_pred, axis=1, keepdims=True) ) + print('Polynomial degree:', degree) + print('Error:', error[degree]) + print('Bias^2:', bias[degree]) + print('Var:', variance[degree]) + print('{} >= {} + {} = {}'.format(error[degree], bias[degree], variance[degree], bias[degree]+variance[degree])) + +plt.plot(polydegree, np.log10(error), label='Error') +plt.plot(polydegree, bias, label='bias') +plt.plot(polydegree, variance, label='Variance') +plt.legend() +plt.show() + + + + +!ec + + +===== Summing up ===== + + + The bias-variance tradeoff summarizes the fundamental tension in machine learning, particularly supervised learning, between the complexity of a model and the amount of training data needed to train it. Since data is often limited, in practice it is often useful to -use a less-complex model with higher bias -- a model whose asymptotic -performance is worse than another model -- because it is easier to +use a less-complex model with higher bias, that is a model whose asymptotic +performance is worse than another model because it is easier to train and less sensitive to sampling noise arising from having a finite-sized training dataset (smaller variance). - -===== Summing up ===== + The above equations tell us that in order to minimize the expected test error, we need to select a @@ -6752,9 +4457,92 @@ flexible statistical methods have higher variance. -===== The one-dimensional Ising model, project 2 ===== +===== Another Example rom Scikit-Learn's Repository ===== +!bc pycod +""" +============================ +Underfitting vs. Overfitting +============================ -The one-dimensional Ising model with nearest neighbor interaction, no external field and a constant coupling constant $J$ is given by +This example demonstrates the problems of underfitting and overfitting and +how we can use linear regression with polynomial features to approximate +nonlinear functions. The plot shows the function that we want to approximate, +which is a part of the cosine function. In addition, the samples from the +real function and the approximations of different models are displayed. The +models have polynomial features of different degrees. We can see that a +linear function (polynomial with degree 1) is not sufficient to fit the +training samples. This is called **underfitting**. A polynomial of degree 4 +approximates the true function almost perfectly. However, for higher degrees +the model will **overfit** the training data, i.e. it learns the noise of the +training data. +We evaluate quantitatively **overfitting** / **underfitting** by using +cross-validation. We calculate the mean squared error (MSE) on the validation +set, the higher, the less likely the model generalizes correctly from the +training data. +""" + +print(__doc__) + +import numpy as np +import matplotlib.pyplot as plt +from sklearn.pipeline import Pipeline +from sklearn.preprocessing import PolynomialFeatures +from sklearn.linear_model import LinearRegression +from sklearn.model_selection import cross_val_score + + +def true_fun(X): + return np.cos(1.5 * np.pi * X) + +np.random.seed(0) + +n_samples = 30 +degrees = [1, 4, 15] + +X = np.sort(np.random.rand(n_samples)) +y = true_fun(X) + np.random.randn(n_samples) * 0.1 + +plt.figure(figsize=(14, 5)) +for i in range(len(degrees)): + ax = plt.subplot(1, len(degrees), i + 1) + plt.setp(ax, xticks=(), yticks=()) + + polynomial_features = PolynomialFeatures(degree=degrees[i], + include_bias=False) + linear_regression = LinearRegression() + pipeline = Pipeline([("polynomial_features", polynomial_features), + ("linear_regression", linear_regression)]) + pipeline.fit(X[:, np.newaxis], y) + + # Evaluate the models using crossvalidation + scores = cross_val_score(pipeline, X[:, np.newaxis], y, + scoring="neg_mean_squared_error", cv=10) + + X_test = np.linspace(0, 1, 100) + plt.plot(X_test, pipeline.predict(X_test[:, np.newaxis]), label="Model") + plt.plot(X_test, true_fun(X_test), label="True function") + plt.scatter(X, y, edgecolor='b', s=20, label="Samples") + plt.xlabel("x") + plt.ylabel("y") + plt.xlim((0, 1)) + plt.ylim((-2, 2)) + plt.legend(loc="best") + plt.title("Degree {}\nMSE = {:.2e}(+/- {:.2e})".format( + degrees[i], -scores.mean(), scores.std())) +plt.show() +!ec + + + + +===== The one-dimensional Ising model ===== + +Let us bring back the Ising model again, but now with an additional +focus on Ridge and Lasso regression as well. We repeat some of the +basic parts of the Ising model and the setup of the training and test +data. The one-dimensional Ising model with nearest neighbor +interaction, no external field and a constant coupling constant $J$ is +given by !bt \begin{align} @@ -6790,15 +4578,6 @@ for i in range(n): energies[i] = - J * np.dot(spins[i], np.roll(spins[i], 1)) !ec -Here we use linear (ordinary least squares), ridge and LASSO -regression to predict the energy in the nearest neighbor -one-dimensional Ising model on a ring, i.e., the endpoints wrap -around. We will use the linear regression models to fit a value for -the coupling constant to achieve this. - - -===== Reformulating the problem to suit regression ===== - A more general form for the one-dimensional Ising model is !bt @@ -6821,12 +4600,10 @@ elements $-J_{jk}$. This form of writing the energy fits perfectly with the form utilized in linear regression, viz. !bt \begin{align} - y = X\omega + \epsilon, + \bm{y} = \bm{X}\bm{\beta} + \bm{\epsilon}. \end{align} !et - - - +We organize the data as we did above !bc pycod X = np.zeros((n, L ** 2)) for i in range(n): @@ -6845,147 +4622,17 @@ X_test_own = np.concatenate( ) !ec - -===== Linear regression ===== - -The problem at hand is to try to fit the equation -!bt -\begin{align} - y = f(x) + \epsilon, -\end{align} -!et - -where $f(x)$ is some unknown function of the data $x$ and $\epsilon$ -is normally distributed with mean zero noise with standard deviation -$\sigma_{\epsilon}$. Our job is to try to find a predictor which -estimates the function $f(x)$. In linear regression we assume that we -can formulate the problem as - -!bt -\begin{align} - y = X\omega + \epsilon, -\end{align} -!et - -where $X$ and $\omega$ are now matrices. Our job at hand is now to -find a _cost function_ $C$, which we wish to minimize in order to find -the best estimate of $\omega$. - - -===== Ordinary least squares ===== - -In the ordinary least squares method we choose the cost function -!bt -\begin{align} - C(X, \omega) = ||X\omega - y||^2 - = (X\omega - y)^T(X\omega - y) -\end{align} -!et -We then find the extremal point of $C$ by taking the derivative with respect to $\omega$ and setting it to zero, i.e., - -!bt -\begin{align} - \dfrac{\mathrm{d}C}{\mathrm{d}\omega} - = 0. -\end{align} -!et -This yields the expression for $\omega$ to be -!bt -\begin{align} - \omega = \frac{X^T y}{X^T X}, -\end{align} -!et - -which immediately imposes some requirements on $X$ as there must exist -an inverse of $X^T X$. If the expression we are modelling contains an -intercept, i.e., a constant expression we must make sure that the -first column of $X$ consists of $1$. - - -!bc pycod -def get_ols_weights_naive(x: np.ndarray, y: np.ndarray) -> np.ndarray: - return scl.inv(x.T @ x) @ (x.T @ y) -omega = get_ols_weights_naive(X_train_own, y_train) -!ec - - - -===== Singular Value decomposition ===== -Doing the inversion directly turns out to be a bad idea as the matrix -$X^TX$ is singular. An alternative approach is to use the _singular -value decomposition_. Using the definition of the Moore-Penrose -pseudoinverse we can write the equation for $\omega$ as - -!bt -\begin{align} - \omega = X^{+}y, -\end{align} -!et -where the pseudoinverse of $X$ is given by -!bt -\begin{align} - X^{+} = \frac{X^T}{X^T X}. -\end{align} -!et - -Using singular value decomposition we have that $X = U\Sigma V^T$, -where $X^{+} = V\Sigma^{+} U^T$. This reduces the equation for -$\omega$ to -!bt -\begin{align} - \omega = V\Sigma^{+} U^T y. -\end{align} -!et - -Note that solving this equation by actually doing the pseudoinverse -(which is what we will do) is not a good idea as this operation scales -as $\mathcal{O}(n^3)$, where $n$ is the number of elements in a -general matrix. Instead, doing $QR$-factorization and solving the -linear system as an equation would reduce this down to -$\mathcal{O}(n^2)$ operations. - - -!bc pycod -def get_ols_weights(x: np.ndarray, y: np.ndarray) -> np.ndarray: - u, s, v = scl.svd(x) - return v.T @ scl.pinv(scl.diagsvd(s, u.shape[0], v.shape[0])) @ u.T @ y -!ec -Before passing in the data to the function we append a column with ones to the training data. - - -!bc pycod -omega = get_ols_weights(X_train_own,y_train) -!ec - - -===== Fitting with scikit-learn ===== - -Next we fit a `LinearRegression`-model from Scikit-learn for comparison. +We will do all fitting with _Scikit-Learn_, !bc pycod clf = skl.LinearRegression().fit(X_train, y_train) !ec - -Extracting the $J$-matrix from both our own method and the Scikit-learn model where we make sure to remove the intercept. - - +When extracting the $J$-matrix we make sure to remove the intercept !bc pycod -J_own = omega[1:].reshape(L, L) J_sk = clf.coef_.reshape(L, L) !ec - -A way of looking at the coefficients in $J$ is to plot the matrices as images. - - +And then we plot the results !bc pycod -fig = plt.figure(figsize=(20, 14)) -im = plt.imshow(J_own, **cmap_args) -plt.title("Home-made OLS", fontsize=18) -plt.xticks(fontsize=18) -plt.yticks(fontsize=18) -cb = fig.colorbar(im) -cb.ax.set_yticklabels(cb.ax.get_yticklabels(), fontsize=18) - fig = plt.figure(figsize=(20, 14)) im = plt.imshow(J_sk, **cmap_args) plt.title("LinearRegression from Scikit-learn", fontsize=18) @@ -6995,11 +4642,7 @@ cb = fig.colorbar(im) cb.ax.set_yticklabels(cb.ax.get_yticklabels(), fontsize=18) plt.show() !ec - -We can see that our model for the least squares method performes close -to the benchmark from Scikit-learn. It is interesting to note that OLS -considers both $J_{j, j + 1} = -0.5$ and $J_{j, j - 1} = -0.5$ as -valid matrix elements for $J$. +The results perfectly with our previous discussion where we used our own code. ===== Ridge regression ===== @@ -7007,47 +4650,18 @@ valid matrix elements for $J$. Having explored the ordinary least squares we move on to ridge regression. In ridge regression we include a _regularizer_. This involves a new cost function which leads to a new estimate for the -weights $\omega$. This results in a penalized regression problem. The +weights $\bm{\beta}$. This results in a penalized regression problem. The cost function is given by !bt \begin{align} - C(X, \omega; \lambda) = ||X\omega - y||^2 + \lambda ||\omega||^2 - = (X\omega - y)^T(X\omega - y) + \lambda \omega^T\omega. + C(\bm{X}, \bm{\beta}; \lambda) = (\bm{X}\bm{\beta} - \bm{y})^T(\bm{X}\bm{\beta} - \bm{y}) + \lambda \bm{\beta}^T\bm{\beta}. \end{align} !et -Finding the extremum of this function yields the weights - -!bt -\begin{align} - \omega(\lambda) = \frac{X^Ty}{X^TX + \lambda} \to \frac{\omega_{\text{LS}}}{1 + \lambda}, -\end{align} -!et - -where $\omega_{\text{LS}}$ is the weights from ordinary least -squares. The last assumption assumes that $X$ is orthogonal, which it -is not. We will therefore resort to solving the equation as it stands -on the left hand side. - - !bc pycod -def get_ridge_weights(x: np.ndarray, y: np.ndarray, _lambda: float) -> np.ndarray: - return x.T @ y @ scl.inv( - x.T @ x + np.eye(x.shape[1], x.shape[1]) * _lambda - ) -lambda = 0.1 -omega_ridge = get_ridge_weights(X_train_own, y_train, np.array([_lambda])) +_lambda = 0.1 clf_ridge = skl.Ridge(alpha=_lambda).fit(X_train, y_train) -J_ridge_own = omega_ridge[1:].reshape(L, L) J_ridge_sk = clf_ridge.coef_.reshape(L, L) -fig = plt.figure(figsize=(20, 14)) -im = plt.imshow(J_ridge_own, **cmap_args) -plt.title("Home-made ridge regression", fontsize=18) -plt.xticks(fontsize=18) -plt.yticks(fontsize=18) -cb = fig.colorbar(im) -cb.ax.set_yticklabels(cb.ax.get_yticklabels(), fontsize=18) - fig = plt.figure(figsize=(20, 14)) im = plt.imshow(J_ridge_sk, **cmap_args) plt.title("Ridge from Scikit-learn", fontsize=18) @@ -7063,14 +4677,14 @@ plt.show() ===== LASSO regression ===== In the _Least Absolute Shrinkage and Selection Operator_ (LASSO)-method we get a third cost function. + !bt \begin{align} - C(X, \omega; \lambda) = - ||X\omega - y||^2 + \lambda ||\omega|| - = (X\omega - y)^T(X\omega - y) + \lambda \sqrt{\omega^T\omega}. + C(\bm{X}, \bm{\beta}; \lambda) = (\bm{X}\bm{\beta} - \bm{y})^T(\bm{X}\bm{\beta} - \bm{y}) + \lambda \sqrt{\bm{\beta}^T\bm{\beta}}. \end{align} !et -Finding the extremal point of this cost function is not so straight-forward as in least squares and ridge. We will therefore rely solely on the function ``Lasso`` from Scikit-learn. + +Finding the extremal point of this cost function is not so straight-forward as in least squares and ridge. We will therefore rely solely on the function ``Lasso`` from _Scikit-Learn_. !bc pycod clf_lasso = skl.Lasso(alpha=_lambda).fit(X_train, y_train) @@ -7092,33 +4706,6 @@ $J_{j, j + 1} = -1$. -===== Performance of the different models ===== - -In order to judge which model performs best at varying values of $\lambda$ (for ridge and LASSO) we compute $R^2$ which is given by - -!bt -\begin{align} - R^2 = 1 - \frac{(y - \hat{y})^2}{(y - \bar{y})^2}, -\end{align} -!et -where $y$ is a vector with the true values of the energy, $\hat{y}$ is the predicted values of $y$ from the models and $\bar{y}$ is the mean of $\hat{y}$. - - -!bc pycod -def r_squared(y, y_hat): - return 1 - np.sum((y - y_hat) ** 2) / np.sum((y - np.mean(y_hat)) ** 2) -!ec - -This is the same metric used by Scikit-learn for their regression models when scoring. -!bc pycod -y_hat = clf.predict(X_test) -r_test = r_squared(y_test, y_hat) -sk_r_test = clf.score(X_test, y_test) - -assert abs(r_test - sk_r_test) < 1e-2 -!ec - - ===== Performance as function of the regularization parameter ===== @@ -7129,17 +4716,13 @@ We see how the different models perform for a different set of values for $\lamb lambdas = np.logspace(-4, 5, 10) train_errors = { - "ols_own": np.zeros(lambdas.size), "ols_sk": np.zeros(lambdas.size), - "ridge_own": np.zeros(lambdas.size), "ridge_sk": np.zeros(lambdas.size), "lasso_sk": np.zeros(lambdas.size) } test_errors = { - "ols_own": np.zeros(lambdas.size), "ols_sk": np.zeros(lambdas.size), - "ridge_own": np.zeros(lambdas.size), "ridge_sk": np.zeros(lambdas.size), "lasso_sk": np.zeros(lambdas.size) } @@ -7149,30 +4732,6 @@ plot_counter = 1 fig = plt.figure(figsize=(32, 54)) for i, _lambda in enumerate(tqdm.tqdm(lambdas)): - omega = get_ols_weights(X_train_own, y_train) - y_hat_train = X_train_own @ omega - y_hat_test = X_test_own @ omega - - train_errors["ols_own"][i] = r_squared(y_train, y_hat_train) - test_errors["ols_own"][i] = r_squared(y_test, y_hat_test) - - plt.subplot(10, 5, plot_counter) - plt.imshow(omega[1:].reshape(L, L), **cmap_args) - plt.title("Home made OLS") - plot_counter += 1 - - omega = get_ridge_weights(X_train_own, y_train, _lambda) - y_hat_train = X_train_own @ omega - y_hat_test = X_test_own @ omega - - train_errors["ridge_own"][i] = r_squared(y_train, y_hat_train) - test_errors["ridge_own"][i] = r_squared(y_test, y_hat_test) - - plt.subplot(10, 5, plot_counter) - plt.imshow(omega[1:].reshape(L, L), **cmap_args) - plt.title(r"Home made ridge, $\lambda = %.4f$" % _lambda) - plot_counter += 1 - for key, method in zip( ["ols_sk", "ridge_sk", "lasso_sk"], [skl.LinearRegression(), skl.Ridge(alpha=_lambda), skl.Lasso(alpha=_lambda)] @@ -7192,7 +4751,7 @@ for i, _lambda in enumerate(tqdm.tqdm(lambdas)): plt.show() !ec -We can see that LASSO quite fast reaches a good solution for low +We see that LASSO reaches a good solution for low values of $\lambda$, but will "wither" when we increase $\lambda$ too much. Ridge is more stable over a larger range of values for $\lambda$, but eventually also fades away. @@ -7212,8 +4771,6 @@ testing set that is close to the accuracy of the training set. fig = plt.figure(figsize=(20, 14)) colors = { - "ols_own": "b", - "ridge_own": "g", "ols_sk": "r", "ridge_sk": "y", "lasso_sk": "c" @@ -7236,9 +4793,6 @@ for key in test_errors: label="Test {0}".format(key), linewidth=4.0 ) -#plt.semilogx(lambdas, train_errors["ols_own"], label="Train (OLS own)") -#plt.semilogx(lambdas, test_errors["ols_own"], label="Test (OLS own)") - plt.legend(loc="best", fontsize=18) plt.xlabel(r"$\lambda$", fontsize=18) plt.ylabel(r"$R^2$", fontsize=18) @@ -7247,13 +4801,900 @@ plt.show() !ec From the above figure we can see that LASSO with $\lambda = 10^{-2}$ -achieve a very good accuracy on the test set. This by far surpases the +achieves a very good accuracy on the test set. This by far surpasses the other models for all values of $\lambda$. -======= Optimization and Gradient Methods ======= +===== Further Exercises ===== + +=== Exercise 1 === + +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)$. +The following simple Python instructions define our $x$ and $y$ values (with 100 data points). +!bc pycod +x = np.random.rand(100,1) +y = 5*x*x+0.1*np.random.randn(100,1) +!ec + +o Write your own code (following the examples above) for computing the parametrization of the data set fitting a second-order polynomial. +o Use thereafter _scikit-learn_ (see again the examples in the regression slides) and compare with your own code. +o Using scikit-learn, compute also the mean square error, a risk metric corresponding to the expected value of the squared (quadratic) error defined as +!bt +\[ MSE(\hat{y},\hat{\tilde{y}}) = \frac{1}{n} +\sum_{i=0}^{n-1}(y_i-\tilde{y}_i)^2, +\] +!et +and the $R^2$ score function. +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 +!bt +\[ +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}, +\] +!et +where we have defined the mean value of $\hat{y}$ as +!bt +\[ +\bar{y} = \frac{1}{n} \sum_{i=0}^{n - 1} y_i. +\] +!et + +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. 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. + + + + +=== Exercise 2, variance of the parameters $\beta$ in linear regression === + +Show that the variance of the parameters $\beta$ in the linear regression method (chapter 3, equation (3.8) of "Trevor Hastie, Robert Tibshirani, Jerome H. Friedman, The Elements of Statistical Learning, Springer":"https://www.springer.com/gp/book/9780387848570") is given as + +!bt +\[ +\mathrm{Var}(\hat{\beta}) = \left(\hat{X}^T\hat{X}\right)^{-1}\sigma^2, +\] +!et +with +!bt +\[ +\sigma^2 = \frac{1}{N-p-1}\sum_{i=1}^{N} (y_i-\tilde{y}_i)^2, +\] +!et +where we have assumed that we fit a function of degree $p-1$ (for example a polynomial in $x$). + + + +=== Exercise 3 === + +This exercise is a continuation of exercise 1. We will +use the same function to generate our data set, still staying with a +simple function $y(x)$ which we want to fit using linear regression, +but now extending the analysis to include the Ridge and the Lasso +regression methods. You can use the code under the Regression as an example on how to use the Ridge and the Lasso methods. + +We will thus again 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)$. + +The following simple Python instructions define our $x$ and $y$ values (with 100 data points). +!bc pycod +x = np.random.rand(100,1) +y = 5*x*x+0.1*np.random.randn(100,1) +!ec + +o Write your own code for the Ridge method and compute the parametrization for different values of $\lambda$. Compare and analyze your results with those from exercise 1. Study the dependence on $\lambda$ while also varying the strength of the noise in your expression for $y(x)$. + +o Repeat the above but using the functionality of _scikit-learn_. Compare your code with the results from _scikit-learn_. Remember to run with the same random numbers for generating $x$ and $y$. + +o Our next step is to study the variance of the parameters $\beta_1$ and $\beta_2$ (assuming that we are parametrizing our function with a second-order polynomial. We will use standard linear regression and the Ridge regression. You can now opt for either writing your own function that calculates the variance of these paramaters (recall that this is equal to the diagonal elements of the matrix $(\hat{X}^T\hat{X})+\lambda\hat{I})^{-1}$) or use the functionality of _scikit-learn_ and compute their variances. Discuss the results of these variances as functions + +o Repeat the previous step but add now the Lasso method. Discuss your results and compare with standard regression and the Ridge regression results. + +o Try to implement the cross-validation as well. + +o Finally, using _scikit-learn_ or your own code, compute also the mean square error, a risk metric corresponding to the expected value of the squared (quadratic) error defined as +!bt +\[ MSE(\hat{y},\hat{\tilde{y}}) = \frac{1}{n} +\sum_{i=0}^{n-1}(y_i-\tilde{y}_i)^2, +\] +!et +and the $R^2$ score function. +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 +!bt +\[ +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}, +\] +!et +where we have defined the mean value of $\hat{y}$ as +!bt +\[ +\bar{y} = \frac{1}{n} \sum_{i=0}^{n - 1} y_i. +\] +!et +Discuss these quantities as functions of the variable $\lambda$ in the Ridge and Lasso regression methods. + +=== Exercise 4 === + +We will study how +to fit polynomials to a specific two-dimensional function called +"Franke's +function":"http://www.dtic.mil/dtic/tr/fulltext/u2/a081688.pdf". This +is a function which has been widely used when testing various interpolation and fitting +algorithms. Furthermore, after having established the model and the +method, we will employ resamling techniques such as the cross-validation and/or +the bootstrap methods, in order to perform a proper assessment of our models. + + +The Franke function, which is a weighted sum of four exponentials reads as follows +!bt +\begin{align*} +f(x,y) &= \frac{3}{4}\exp{\left(-\frac{(9x-2)^2}{4} - \frac{(9y-2)^2}{4}\right)}+\frac{3}{4}\exp{\left(-\frac{(9x+1)^2}{49}- \frac{(9y+1)}{10}\right)} \\ +&+\frac{1}{2}\exp{\left(-\frac{(9x-7)^2}{4} - \frac{(9y-3)^2}{4}\right)} -\frac{1}{5}\exp{\left(-(9x-4)^2 - (9y-7)^2\right) }. +\end{align*} +!et + +The function will be defined for $x,y\in [0,1]$. Our first step will +be to perform an OLS regression analysis of this function, trying out +a polynomial fit with an $x$ and $y$ dependence of the form $[x, y, +x^2, y^2, xy, \dots]$. We will also include cross-validation and +bootstrap as resampling techniques. As in homeworks 1 and 2, we +can use a uniform distribution to set up the arrays of values for $x$ +and $y$, or as in the example below just a fix values for $x$ and $y$ with a given step size. +In this case we will have two predictors and need to fit a +function (for example a polynomial) of $x$ and $y$. Thereafter we will +repeat much of the same procedure using the the Ridge and +Lasso regression methods, introducing thus a dependence on the bias +(penalty) $\lambda$. + + +The Python function for the Franke function is included here (it performs also a three-dimensional plot of it) +!bc pycod +from mpl_toolkits.mplot3d import Axes3D +import matplotlib.pyplot as plt +from matplotlib import cm +from matplotlib.ticker import LinearLocator, FormatStrFormatter +import numpy as np +from random import random, seed + +fig = plt.figure() +ax = fig.gca(projection='3d') + +# Make data. +x = np.arange(0, 1, 0.05) +y = np.arange(0, 1, 0.05) +x, y = np.meshgrid(x,y) + + +def FrankeFunction(x,y): + term1 = 0.75*np.exp(-(0.25*(9*x-2)**2) - 0.25*((9*y-2)**2)) + term2 = 0.75*np.exp(-((9*x+1)**2)/49.0 - 0.1*(9*y+1)) + term3 = 0.5*np.exp(-(9*x-7)**2/4.0 - 0.25*((9*y-3)**2)) + term4 = -0.2*np.exp(-(9*x-4)**2 - (9*y-7)**2) + return term1 + term2 + term3 + term4 + + +z = FrankeFunction(x, y) + +# Plot the surface. +surf = ax.plot_surface(x, y, z, cmap=cm.coolwarm, + linewidth=0, antialiased=False) + +# Customize the z axis. +ax.set_zlim(-0.10, 1.40) +ax.zaxis.set_major_locator(LinearLocator(10)) +ax.zaxis.set_major_formatter(FormatStrFormatter('%.02f')) + +# Add a color bar which maps values to colors. +fig.colorbar(surf, shrink=0.5, aspect=5) + +plt.show() + +!ec + + +We will thus again generate our own dataset for a function $\mathrm{FrankeFunction}(x,y)$ where +$x,y \in [0,1]$ could be defined by random numbers computed with the uniform +distribution. The function $f(x,y)$ is the Franke function. You should explore also the addition +an added stochastic noise to this function using the normal distribution $\cal{N}(0,1)$. + +Write your own code (using either a matrix inversion or a singular value decomposition from e.g., _numpy_ ) or use your code from exercises 1 and 3 +and perform a standard least square regression analysis using polynomials in $x$ and $y$ up to fifth order. Find the confidence intervals of the parameters $\beta$ by computing their variances, evaluate the Mean Squared error (MSE) +!bt +\[ MSE(\hat{y},\hat{\tilde{y}}) = \frac{1}{n} +\sum_{i=0}^{n-1}(y_i-\tilde{y}_i)^2, +\] +!et +and the $R^2$ score function. +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 +!bt +\[ +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}, +\] +!et +where we have defined the mean value of $\hat{y}$ as +!bt +\[ +\bar{y} = \frac{1}{n} \sum_{i=0}^{n - 1} y_i. +\] +!et + +Perform a resampling of the data where you split the data in training data and test data. Implement the $k$-fold cross-validation algorithm and/or the bootstrap algorithm +and evaluate again the MSE and the $R^2$ functions resulting from the test data. Evaluate also the bias and variance of the final models. + + +Write then your own code for the Ridge method, either using matrix +inversion or the singular value decomposition as done for standard OLS. Perform the same analysis as in the +previous exercise (for the same polynomials and include resampling +techniques) but now for different values of $\lambda$. Compare and +analyze your results with those obtained with standard OLS. Study the +dependence on $\lambda$ while also varying eventually the strength of +the noise in your expression for $\mathrm{FrankeFunction}(x,y)$. + +Then perform the same studies but now with Lasso regression. Use the functionalities of +_scikit-learn_. Give a critical discussion of the three methods and a +judgement of which model fits the data best. + + + + + +======= Logistic Regression ======= + +In linear regression our main interest was centered on learning the +coefficients of a functional fit (say a polynomial) in order to be +able to predict the response of a continuous variable on some unseen +data. The fit to the continuous variable $y_i$ is based on some +independent variables $\hat{x}_i$. Linear regression resulted in +analytical expressions (in terms of matrices to invert) for several +quantities, ranging from the variance and thereby the confidence +intervals of the parameters $\hat{\beta}$ to the mean squared +error. If we can invert the product of the design matrices, linear +regression gives then a simple recipe for fitting our data. + + +Classification problems, however, are concerned with outcomes taking +the form of discrete variables (i.e. categories). We may for example, +on the basis of DNA sequencing for a number of patients, like to find +out which mutations are important for a certain disease; or based on +scans of various patients' brains, figure out if there is a tumor or +not; or given a specific physical system, we'd like to identify its +state, say whether it is an ordered or disordered system (typical +situation in solid state physics); or classify the status of a +patient, whether she/he has a stroke or not and many other similar +situations. + +The most common situation we encounter when we apply logistic +regression is that of two possible outcomes, normally denoted as a +binary outcome, true or false, positive or negative, success or +failure etc. + + +===== Optimization and Deep learning ===== + +Logistic regression will also serve as our stepping stone towards neural +network algorithms and supervised deep learning. For logistic +learning, the minimization of the cost function leads to a non-linear +equation in the parameters $\hat{\beta}$. The optmization of the problem calls therefore for minimization algorithms. This forms the bottle neck of all machine learning algorithms, namely how to find reliable minima of a multi-variable function. This leads us to the family of gradient descent methods. The latter are the working horses of basically all modern machine learning algorithms. + +We note also that many of the topics discussed here +regression are also commonly used in modern supervised Deep Learning +models, as we will see later. + + + +===== Basics ===== + +We consider the case where the dependent variables, also called the +responses or the outcomes, $y_i$ are discrete and only take values +from $k=0,\dots,K-1$ (i.e. $K$ classes). + +The goal is to predict the +output classes from the design matrix $\hat{X}\in\mathbb{R}^{n\times p}$ +made of $n$ samples, each of which carries $p$ features or predictors. The +primary goal is to identify the classes to which new unseen samples +belong. + +Let us specialize to the case of two classes only, with outputs $y_i=0$ and $y_i=1$. Our outcomes could represent the status of a credit card user who could default or not on her/his credit card debt. That is +!bt +\[ +y_i = \begin{bmatrix} 0 & \mathrm{no}\\ 1 & \mathrm{yes} \end{bmatrix}. +\] +!et + + + +Before moving to the logistic model, let us try to use our linear regression model to classify these two outcomes. We could for example fit a linear model to the default case if $y_i > 0.5$ and the no default case $y_i \leq 0.5$. + +We would then have our +weighted linear combination, namely +!bt +\begin{equation} +\hat{y} = \hat{X}^T\hat{\beta} + \hat{\epsilon}, +\end{equation} +!et +where $\hat{y}$ is a vector representing the possible outcomes, $\hat{X}$ is our +$n\times p$ design matrix and $\hat{\beta}$ represents our estimators/predictors. + + +The main problem with our function is that it +takes values on the entire real axis. In the case of +logistic regression, however, the labels $y_i$ are discrete +variables. + +One simple way to get a discrete output is to have sign +functions that map the output of a linear regressor to values $\{0,1\}$, +$f(s_i)=sign(s_i)=1$ if $s_i\ge 0$ and 0 if otherwise. +We will encounter this model in our first demonstration of neural networks. Historically it is called the ``perceptron" model in the machine learning +literature. This model is extremely simple. However, in many cases it is more +favorable to use a ``soft" classifier that outputs +the probability of a given category. This leads us to the logistic function. + +The code for plotting the perceptron can be seen here. This si nothing but the standard "Heaviside step function":"https://en.wikipedia.org/wiki/Heaviside_step_function". +!bc pycod + +!ec + + + +The perceptron is an example of a ``hard classification'' model. We +will encounter this model when we discuss neural networks as +well. Each datapoint is deterministically assigned to a category (i.e +$y_i=0$ or $y_i=1$). In many cases, it is favorable to have a ``soft'' +classifier that outputs the probability of a given category rather +than a single value. For example, given $x_i$, the classifier +outputs the probability of being in a category $k$. Logistic regression +is the most common example of a so-called soft classifier. In logistic +regression, the probability that a data point $x_i$ +belongs to a category $y_i=\{0,1\}$ is given by the so-called logit function (or Sigmoid) which is meant to represent the likelihood for a given event, +!bt +\[ +p(t) = \frac{1}{1+\mathrm \exp{-t}}=\frac{\exp{t}}{1+\mathrm \exp{t}}. +\] +!et +Note that $1-p(t)= p(-t)$. +The following code plots the logistic function. +!bc pycod + +!ec + + + + +We assume now that we have two classes with $y_i$ either $0$ or $1$. Furthermore we assume also that we have only two parameters $\beta$ in our fitting of the Sigmoid function, that is we define probabilities +!bt +\begin{align*} +p(y_i=1|x_i,\hat{\beta}) &= \frac{\exp{(\beta_0+\beta_1x_i)}}{1+\exp{(\beta_0+\beta_1x_i)}},\nonumber\\ +p(y_i=0|x_i,\hat{\beta}) &= 1 - p(y_i=1|x_i,\hat{\beta}), +\end{align*} +!et +where $\hat{\beta}$ are the weights we wish to extract from data, in our case $\beta_0$ and $\beta_1$. + +Note that we used +!bt +\[ +p(y_i=0\vert x_i, \hat{\beta}) = 1-p(y_i=1\vert x_i, \hat{\beta}). +\] +!et + + +===== Maximum likelihood ===== + +In order to define the total likelihood for all possible outcomes from a +dataset $\mathcal{D}=\{(y_i,x_i)\}$, with the binary labels +$y_i\in\{0,1\}$ and where the data points are drawn independently, we use the so-called "Maximum Likelihood Estimation":"https://en.wikipedia.org/wiki/Maximum_likelihood_estimation" (MLE) principle. +We aim thus at maximizing +the probability of seeing the observed data. We can then approximate the +likelihood in terms of the product of the individual probabilities of a specific outcome $y_i$, that is +!bt +\begin{align*} +P(\mathcal{D}|\hat{\beta})& = \prod_{i=1}^n \left[p(y_i=1|x_i,\hat{\beta})\right]^{y_i}\left[1-p(y_i=1|x_i,\hat{\beta}))\right]^{1-y_i}\nonumber \\ +\end{align*} +!et +from which we obtain the log-likelihood and our _cost/loss_ function +!bt +\[ +\mathcal{C}(\hat{\beta}) = \sum_{i=1}^n \left( y_i\log{p(y_i=1|x_i,\hat{\beta})} + (1-y_i)\log\left[1-p(y_i=1|x_i,\hat{\beta}))\right]\right). +\] +!et + + +===== The cost function rewritten ===== + +Reordering the logarithms, we can rewrite the _cost/loss_ function as +!bt +\[ +\mathcal{C}(\hat{\beta}) = \sum_{i=1}^n \left(y_i(\beta_0+\beta_1x_i) -\log{(1+\exp{(\beta_0+\beta_1x_i)})}\right). +\] +!et + +The maximum likelihood estimator is defined as the set of parameters that maximize the log-likelihood where we maximize with respect to $\beta$. +Since the cost (error) function is just the negative log-likelihood, for logistic regression we have that +!bt +\[ +\mathcal{C}(\hat{\beta})=-\sum_{i=1}^n \left(y_i(\beta_0+\beta_1x_i) -\log{(1+\exp{(\beta_0+\beta_1x_i)})}\right). +\] +!et +This equation is known in statistics as the _cross entropy_. Finally, we note that just as in linear regression, +in practice we often supplement the cross-entropy with additional regularization terms, usually $L_1$ and $L_2$ regularization as we did for Ridge and Lasso regression. + + +The cross entropy is a convex function of the weights $\hat{\beta}$ and, +therefore, any local minimizer is a global minimizer. + + +Minimizing this +cost function with respect to the two parameters $\beta_0$ and $\beta_1$ we obtain + +!bt +\[ +\frac{\partial \mathcal{C}(\hat{\beta})}{\partial \beta_0} = -\sum_{i=1}^n \left(y_i -\frac{\exp{(\beta_0+\beta_1x_i)}}{1+\exp{(\beta_0+\beta_1x_i)}}\right), +\] +!et +and +!bt +\[ +\frac{\partial \mathcal{C}(\hat{\beta})}{\partial \beta_1} = -\sum_{i=1}^n \left(y_ix_i -x_i\frac{\exp{(\beta_0+\beta_1x_i)}}{1+\exp{(\beta_0+\beta_1x_i)}}\right). +\] +!et + + +Let us now define a vector $\hat{y}$ with $n$ elements $y_i$, an +$n\times p$ matrix $\hat{X}$ which contains the $x_i$ values and a +vector $\hat{p}$ of fitted probabilities $p(y_i\vert x_i,\hat{\beta})$. We can rewrite in a more compact form the first +derivative of cost function as + +!bt +\[ +\frac{\partial \mathcal{C}(\hat{\beta})}{\partial \hat{\beta}} = -\hat{X}^T\left(\hat{y}-\hat{p}\right). +\] +!et + +If we in addition define a diagonal matrix $\hat{W}$ with elements +$p(y_i\vert x_i,\hat{\beta})(1-p(y_i\vert x_i,\hat{\beta})$, we can obtain a compact expression of the second derivative as + +!bt +\[ +\frac{\partial^2 \mathcal{C}(\hat{\beta})}{\partial \hat{\beta}\partial \hat{\beta}^T} = \hat{X}^T\hat{W}\hat{X}. +\] +!et + +===== Extending to more predictors ===== + +Within a binary classification problem, we can easily expand our model to include multiple predictors. Our ratio between likelihoods is then with $p$ predictors +!bt +\[ +\log{ \frac{p(\hat{\beta}\hat{x})}{1-p(\hat{\beta}\hat{x})}} = \beta_0+\beta_1x_1+\beta_2x_2+\dots+\beta_px_p. +\] +!et +Here we defined $\hat{x}=[1,x_1,x_2,\dots,x_p]$ and $\hat{\beta}=[\beta_0, \beta_1, \dots, \beta_p]$ leading to +!bt +\[ +p(\hat{\beta}\hat{x})=\frac{ \exp{(\beta_0+\beta_1x_1+\beta_2x_2+\dots+\beta_px_p)}}{1+\exp{(\beta_0+\beta_1x_1+\beta_2x_2+\dots+\beta_px_p)}}. +\] +!et + + +Till now we have mainly focused on two classes, the so-called binary system. Suppose we wish to extend to $K$ classes. +Let us for the sake of simplicity assume we have only two predictors. We have then following model +!bt +\[ +\log{\frac{p(C=1\vert x)}{p(K\vert x)}} = \beta_{10}+\beta_{11}x_1, +\] +!et +!bt +\[ +\log{\frac{p(C=2\vert x)}{p(K\vert x)}} = \beta_{20}+\beta_{21}x_1, +\] +!et +and so on till the class $C=K-1$ class +!bt +\[ +\log{\frac{p(C=K-1\vert x)}{p(K\vert x)}} = \beta_{(K-1)0}+\beta_{(K-1)1}x_1, +\] +!et +and the model is specified in term of $K-1$ so-called log-odds or _logit_ transformations. + + + +===== The Softmax function ===== + +In our discussion of neural networks we will encounter the above again in terms of the so-called _Softmax_ function. + +The softmax function is used in various multiclass classification +methods, such as multinomial logistic regression (also known as +softmax regression), multiclass linear discriminant +analysis, naive Bayes classifiers, and artificial neural networks. +Specifically, in multinomial logistic regression and linear +discriminant analysis, the input to the function is the result of $K$ +distinct linear functions, and the predicted probability for the $k$-th +class given a sample vector $\hat{x}$ and a weighting vector $\hat{\beta}$ is (with two predictors): + +!bt +\[ +p(C=k\vert \mathbf {x} )=\frac{\exp{(\beta_{k0}+\beta_{k1}x_1)}}{1+\sum_{l=1}^{K-1}\exp{(\beta_{l0}+\beta_{l1}x_1)}}. +\] +!et +It is easy to extend to more predictors. The final class is +!bt +\[ +p(C=K\vert \mathbf {x} )=\frac{1}{1+\sum_{l=1}^{K-1}\exp{(\beta_{l0}+\beta_{l1}x_1)}}, +\] +!et +and they sum to one. Our earlier discussions were all specialized to the case with two classes only. It is easy to see from the above that what we derived earlier is compatible with these equations. + +To find the optimal parameters we would typically use a gradient descent method. +Newton's method and gradient descent methods are discussed in the material on "optimization methods":"https://compphysics.github.io/MachineLearning/doc/pub/Splines/html/Splines-bs.html". + + + + +===== A _scikit-learn_ example ===== + +!bc pycod +import numpy as np +import matplotlib.pyplot as plt +from sklearn import datasets +iris = datasets.load_iris() +list(iris.keys()) +['data', 'target_names', 'feature_names', 'target', 'DESCR'] +X = iris["data"][:, 3:] # petal width +y = (iris["target"] == 2).astype(np.int) # 1 if Iris-Virginica, else 0 + +from sklearn.linear_model import LogisticRegression +log_reg = LogisticRegression() +log_reg.fit(X, y) + +X_new = np.linspace(0, 3, 1000).reshape(-1, 1) +y_proba = log_reg.predict_proba(X_new) +plt.plot(X_new, y_proba[:, 1], "g-", label="Iris-Virginica") +plt.plot(X_new, y_proba[:, 0], "b--", label="Not Iris-Virginica") +plt.show() + +!ec + + + +===== A simple classification problem ===== +!bc pycod +import numpy as np +from sklearn import datasets, linear_model +import matplotlib.pyplot as plt + + +def generate_data(): + np.random.seed(0) + X, y = datasets.make_moons(200, noise=0.20) + return X, y + + +def visualize(X, y, clf): + # plt.scatter(X[:, 0], X[:, 1], s=40, c=y, cmap=plt.cm.Spectral) + # plt.show() + plot_decision_boundary(lambda x: clf.predict(x), X, y) + plt.title("Logistic Regression") + + +def plot_decision_boundary(pred_func, X, y): + # Set min and max values and give it some padding + x_min, x_max = X[:, 0].min() - .5, X[:, 0].max() + .5 + y_min, y_max = X[:, 1].min() - .5, X[:, 1].max() + .5 + h = 0.01 + # Generate a grid of points with distance h between them + xx, yy = np.meshgrid(np.arange(x_min, x_max, h), np.arange(y_min, y_max, h)) + # Predict the function value for the whole gid + Z = pred_func(np.c_[xx.ravel(), yy.ravel()]) + Z = Z.reshape(xx.shape) + # Plot the contour and training examples + plt.contourf(xx, yy, Z, cmap=plt.cm.Spectral) + plt.scatter(X[:, 0], X[:, 1], c=y, cmap=plt.cm.Spectral) + plt.show() + + +def classify(X, y): + clf = linear_model.LogisticRegressionCV() + clf.fit(X, y) + return clf + + +def main(): + X, y = generate_data() + # visualize(X, y) + clf = classify(X, y) + visualize(X, y, clf) + + +if __name__ == "__main__": + main() +!ec + + +===== The two-dimensional Ising model, Predicting phase transition of the two-dimensional Ising model ===== + +The Hamiltonian of the two-dimensional Ising model without an external field for a constant coupling constant $J$ is given by +!bt +\begin{align} + H = -J \sum_{\langle ij\rangle} S_i S_j, +\end{align} +!et +where $S_i \in \{-1, 1\}$ and $\langle ij \rangle$ signifies that we only iterate over the nearest neighbors in the lattice. We will be looking at a system of $L = 40$ spins in each dimension, i.e., $L^2 = 1600$ spins in total. Opposed to the one-dimensional Ising model we will get a phase transition from an _ordered_ phase to a _disordered_ phase at the critical temperature + +!bt +\begin{align} + \frac{T_c}{J} = \frac{2}{\log\left(1 + \sqrt{2}\right)} \approx 2.26, +\end{align} +!et +as shown by Lars Onsager. + + +Here we use _logistic regression_ to predict when a phase transition +occurs. The data we will look at is a set of spin configurations, +i.e., individual lattices with spins, labeled _ordered_ `1` or +_disordered_ `0`. Our job is to build a model which will take in a +spin configuration and predict whether or not the spin configuration +constitutes an ordered or a disordered phase. To achieve this we will +represent the lattices as flattened arrays with $1600$ elements +instead of a matrix of $40 \times 40$ elements. As an extra test of +the performance of the algorithms we will divide the dataset into +three pieces. We will do a conventional train-test-split on a +combination of totally ordered and totally disordered phases. The +remaining "critical-like" states will be used as test data which we +hope the model will be able to make good extrapolated predictions on. + + +!bc pycod +import pickle +import os +import glob +import numpy as np +import pandas as pd +import matplotlib.pyplot as plt +import seaborn as sns +import sklearn.model_selection as skms +import sklearn.linear_model as skl +import sklearn.metrics as skm +import tqdm +import copy +import time +from IPython.display import display + +%matplotlib inline + +sns.set(color_codes=True) +!ec + + +Using the data from "Mehta et al.":"https://physics.bu.edu/~pankajm/ML-Review-Datasets/isingMC/" (specifically the two datasets named `Ising2DFM_reSample_L40_T=All.pkl` and `Ising2DFM_reSample_L40_T=All_labels.pkl`) we have to unpack the data into numpy arrays. + + +!bc pycod +filenames = glob.glob(os.path.join("..", "dat", "*")) +label_filename = list(filter(lambda x: "label" in x, filenames))[0] +dat_filename = list(filter(lambda x: "label" not in x, filenames))[0] + +# Read in the labels +with open(label_filename, "rb") as f: + labels = pickle.load(f) + +# Read in the corresponding configurations +with open(dat_filename, "rb") as f: + data = np.unpackbits(pickle.load(f)).reshape(-1, 1600).astype("int") + +# Set spin-down to -1 +data[data == 0] = -1 +!ec + +This dataset consists of $10000$ samples, i.e., $10000$ spin +configurations with $40 \times 40$ spins each, for $16$ temperatures +between $0.25$ to $4.0$. Next we create a train/test-split and keep +the data in the critical phase as a separate dataset for +extrapolation-testing. + + +!bc pycod +# Set up slices of the dataset +ordered = slice(0, 70000) +critical = slice(70000, 100000) +disordered = slice(100000, 160000) + +X_train, X_test, y_train, y_test = skms.train_test_split( + np.concatenate((data[ordered], data[disordered])), + np.concatenate((labels[ordered], labels[disordered])), + test_size=0.95 +) +!ec + + + +===== Logistic regression ===== + +Logistic regression is a linear model for classification. Recalling +the cost function for ordinary least squares with both L2 (ridge) and +L1 (LASSO) penalties we will see that the logistic cost function is +very similar. In OLS we wish to predict a continuous variable +$\hat{y}$ using +!bt +\begin{align} + \hat{y} = X\omega, +\end{align} +!et + +where $X \in \mathbb{R}^{n \times p}$ is the input data and $\omega^{p +\times d}$ are the weights of the regression. In a classification +setting (binary classification in our situation) we are interested in +a positive or negative answer. We can thus define either answer to be +above or below some threshold. But, in order to limit the size of the +answer and also to get a probability interpretation on how sure we are +for either answer we can compute the sigmoid function of OLS. That is, + +!bt +\begin{align} + f(X\omega) = \frac{1}{1 + \exp(-X\omega)}. +\end{align} +!et +We are thus interested in minizming the following cost function +!bt +\begin{align} + C(X, \omega) = \sum_{i = 1}^n \left\{ + - y_i\log\left( f(x_i^T\omega) \right) + - (1 - y_i)\log\left[1 - f(x_i^T\omega)\right] + \right\}, +\end{align} +!et + +where we will restrict ourselves to a value for $f(z)$ as the sigmoid +described above. We can also tack on a L2 (Ridge) or L1 (LASSO) +penalization to this cost function in the same manner we did for +linear regression. + + +The penalization factor $\lambda$ is inverted in the case of the +logistic regression model we use. We will explore several values of +$\lambda$ using both L1 and L2 penalization. We do this using a grid +search over different parameters and run a 3-fold cross validation for +each configuration. In other words, we fit a model 3 times for each +configuration of the hyper parameters. + + +!bc pycod +lambdas = np.logspace(-7, -1, 7) + +param_grid = { + "C": list(1.0/lambdas), + "penalty": ["l1", "l2"] +} +clf = skms.GridSearchCV( + skl.LogisticRegression(), + param_grid=param_grid, + n_jobs=-1, + return_train_score=True +) +t0 = time.time() +clf.fit(X_train, y_train) +t1 = time.time() + +print ( + "Time spent fitting GridSearchCV(LogisticRegression): {0:.3f} sec".format( + t1 - t0 + ) +) +!ec + +We can see that logistic regression is quite slow and using the grid +search and cross validation results in quite a heavy +computation. Below we show the results of the different +configurations. + + +!bc pycod +logreg_df = pd.DataFrame(clf.cv_results_) + +display(logreg_df) +!ec + + +===== Accuracy of a classification model ===== + +To determine how well a classification model is performing we count +the number of correctly labeled classes and divide by the number of +classes in total. The accuracy is thus given by + +!bt +\begin{align} + a(y, \hat{y}) = \frac{1}{n}\sum_{i = 1}^{n} I(y_i = \hat{y}_i), +\end{align} +!et + +where $I(y_i = \hat{y}_i)$ is the indicator function given by + +!bt +\begin{align} + I(x = y) = \begin{array}{cc} + 1 & x = y, \\ + 0 & x \neq y. + \end{array} +\end{align} +!et + +This is the accuracy provided by Scikit-learn when using _sklearn.metrics.accuracyscore_. + +Below we compute the accuracy of the best fit model on the training data (which should give a good accuracy), the test data (which has not been shown to the model) and the critical data (completely new data that needs to be extrapolated). + + +!bc pycod +train_accuracy = skm.accuracy_score(y_train, clf.predict(X_train)) +test_accuracy = skm.accuracy_score(y_test, clf.predict(X_test)) +critical_accuracy = skm.accuracy_score(labels[critical], clf.predict(data[critical])) + +print ("Accuracy on train data: {0}".format(train_accuracy)) +print ("Accuracy on test data: {0}".format(test_accuracy)) +print ("Accuracy on critical data: {0}".format(critical_accuracy)) +!ec + +We can see that we get quite good accuracy on the training data, but gradually worsening accuracy on the test and critical data. + + +===== Analyzing the results ===== + +Below we show a different metric for determining the quality of our +model, namely the _reciever operating characteristic_ (ROC). The ROC +curve tells us how well the model correctly classifies the different +labels. We plot the _true positive rate_ (the rate of predicted +positive classes that are positive) versus the _false positive rate_ +(the rate of predicted positive classes that are negative). The ROC +curve is built by computing the true positive rate and the false +positive rate for varying _thresholds_, i.e, which probability we +should acredit a certain class. + +By computing the _area under the curve_ (AUC) of the ROC curve we get an estimate of how well our model is performing. Pure guessing will get an AUC of $0.5$. A perfect score will get an AUC of $1.0$. + + +!bc pycod +fig = plt.figure(figsize=(20, 14)) + +for (_X, _y), label in zip( + [ + (X_train, y_train), + (X_test, y_test), + (data[critical], labels[critical]) + ], + ["Train", "Test", "Critical"] +): + proba = clf.predict_proba(_X) + fpr, tpr, _ = skm.roc_curve(_y, proba[:, 1]) + roc_auc = skm.auc(fpr, tpr) + + print ("LogisticRegression AUC ({0}): {1}".format(label, roc_auc)) + + plt.plot(fpr, tpr, label="{0} (AUC = {1})".format(label, roc_auc), linewidth=4.0) + +plt.plot([0, 1], [0, 1], "--", label="Guessing (AUC = 0.5)", linewidth=4.0) + +plt.title(r"The ROC curve for LogisticRegression", fontsize=18) +plt.xlabel(r"False positive rate", fontsize=18) +plt.ylabel(r"True positive rate", fontsize=18) +plt.axis([-0.01, 1.01, -0.01, 1.01]) +plt.xticks(fontsize=18) +plt.yticks(fontsize=18) +plt.legend(loc="best", fontsize=18) +plt.show() +!ec + +We can see that this plot of the ROC looks very strange. This tells us +that logistic regression is quite inept at predicting the Ising model +transition and is therefore highly non-linear. The ROC curve for the +training data looks quite good, but as the testing data is so far off +we see that we are dealing with an overfit model. + + + + + +======= Optimization and Gradient Methods ======= ===== Optimization, the central part of any Machine Learning algortithm ===== @@ -7287,8 +5728,6 @@ p(y_i=0|x_i,\hat{\beta}) &= 1 - p(y_i=1|x_i,\hat{\beta}), where $\hat{\beta}$ are the weights we wish to extract from data, in our case $\beta_0$ and $\beta_1$. -===== The equations to solve ===== - Our compact equations used a definition of a vector $\hat{y}$ with $n$ elements $y_i$, an $n\times p$ matrix $\hat{X}$ which contains the $x_i$ values and a vector $\hat{p}$ of fitted probabilities @@ -7336,8 +5775,6 @@ If we can compute these matrices, in particular the Hessian, the above is often -===== Brief reminder on Newton-Raphson's method ===== - Let us quickly remind ourselves how we derive the above method. Perhaps the most celebrated of all one-dimensional root-finding @@ -7349,7 +5786,6 @@ numerically and/or your function is not of the smooth type, we normally discourage the use of this method. -===== The equations ===== The Newton-Raphson formula consists geometrically of extending the tangent line at a current point until it crosses zero, then setting @@ -7389,8 +5825,6 @@ Having in mind an iterative procedure, it is natural to start iterating with !et -===== Simple geometric interpretation ===== - The above is Newton-Raphson's method. It has a simple geometric interpretation, namely $x_{n+1}$ is the point where the tangent from $(x_n,f(x_n))$ crosses the $x$-axis. Close to the solution, @@ -7405,8 +5839,6 @@ vanishes, then Newton-Raphson may fail totally -===== Extending to more than one variable ===== - Newton's method can be generalized to systems of several non-linear equations and variables. Consider the case with two equations !bt @@ -7428,10 +5860,10 @@ which we Taylor expand to obtain \end{array}. \] !et -Defining the Jacobian matrix $\hat{J}$ we have +Defining the Jacobian matrix $\bm{J}$ we have !bt \[ - \hat{J}=\left( \begin{array}{cc} + \bm{J}=\left( \begin{array}{cc} \partial f_1/\partial x_1 & \partial f_1/\partial x_2 \\ \partial f_2/\partial x_1 &\partial f_2/\partial x_2 \end{array} \right), @@ -7449,13 +5881,13 @@ where we have defined !bt \[ \left(\begin{array}{c} h_1^{n} \\ h_2^{n} \end{array} \right)= - -\hat{J}^{-1} + -{\bm{J}}^{-1} \left(\begin{array}{c} f_1(x_1^{n},x_2^{n}) \\ f_2(x_1^{n},x_2^{n}) \end{array} \right). \] !et We need thus to compute the inverse of the Jacobian matrix and it is to understand that difficulties may -arise in case $\hat{J}$ is nearly singular. +arise in case $\bm{J}$ is nearly singular. It is rather straightforward to extend the above scheme to systems of more than two non-linear equations. In our case, the Jacobian matrix is given by the Hessian that represents the second derivative of cost function. @@ -7482,8 +5914,6 @@ For $\gamma_k$ small enough, then $F(\mathbf{x}_{k+1}) \leq F(\mathbf{x}_k)$. This means that for a sufficiently small $\gamma_k$ we are always moving towards smaller function values, i.e a minimum. - -===== More on Steepest descent ===== The previous observation is the basis of the method of steepest descent, which is also referred to as just gradient descent (GD). One @@ -7499,8 +5929,7 @@ computes new approximations according to The parameter $\gamma_k$ is often referred to as the step length or the learning rate within the context of Machine Learning. - -===== The ideal ===== + Ideally the sequence $\{\mathbf{x}_k \}_{k=0}$ converges to a global minimum of the function $F$. In general we do not know if we are in a @@ -7521,8 +5950,6 @@ Note that the gradient is a function of $\mathbf{x} = (x_1,\cdots,x_n)$ which makes it expensive to compute numerically. - -===== The sensitiveness of the gradient descent ===== The gradient descent method is sensitive to the choice of learning rate $\gamma_k$. This is due @@ -7537,8 +5964,6 @@ randomness. One such method is that of Stochastic Gradient Descent (SGD), see below. - -===== Convex functions ===== Ideally we want our cost/loss function to be convex(concave). @@ -7558,14 +5983,12 @@ regular polygons (triangles, rectangles, pentagons, etc...). _Convex function_: Let $X \subset \mathbb{R}^n$ be a convex set. Assume that the function $f: X \rightarrow \mathbb{R}$ is continuous, then $f$ is said to be convex if $$f(tx_1 + (1-t)x_2) \leq tf(x_1) + (1-t)f(x_2) $$ for all $x_1, x_2 \in X$ and for all $t \in [0,1]$. If $\leq$ is replaced with a strict inequaltiy in the definition, we demand $x_1 \neq x_2$ and $t\in(0,1)$ then $f$ is said to be strictly convex. For a single variable function, convexity means that if you draw a straight line connecting $f(x_1)$ and $f(x_2)$, the value of the function on the interval $[x_1,x_2]$ is always below the line as illustrated below. -===== Conditions on convex functions ===== - In the following we state first and second-order conditions which ensures convexity of a function $f$. We write $D_f$ to denote the domain of $f$, i.e the subset of $R^n$ where $f$ is defined. For more details and proofs we refer to: "S. Boyd and L. Vandenberghe. Convex Optimization. Cambridge University Press":"http://stanford.edu/boyd/cvxbook/, 2004". - First order condition +!bblock First order condition Suppose $f$ is differentiable (i.e $\nabla f(x)$ is well defined for all $x$ in the domain of $f$). Then $f$ is convex if and only if $D_f$ is a convex set and $$f(y) \geq f(x) + \nabla f(x)^T (y-x) $$ holds @@ -7574,22 +5997,20 @@ the first order Taylor expansion (right hand side above) at any point a global under estimator of the function. To convince yourself you can make a drawing of $f(x) = x^2+1$ and draw the tangent line to $f(x)$ and note that it is always below the graph. +!eblock - - Second order condition +!bblock Second order condition Assume that $f$ is twice differentiable, i.e the Hessian matrix exists at each point in $D_f$. Then $f$ is convex if and only if $D_f$ is a convex set and its Hessian is positive semi-definite for all $x\in D_f$. For a single-variable function this reduces to $f''(x) \geq 0$. Geometrically this means that $f$ has nonnegative curvature everywhere. - +!eblock This condition is particularly useful since it gives us an procedure for determining if the function under consideration is convex, apart from using the definition. -===== More on convex functions ===== - The next result is of great importance to us and the reason why we are going on about convex functions. In machine learning we frequently have to minimize a loss/cost function in order to find the best @@ -7600,11 +6021,11 @@ global minimum (for high-dimensional models it is hard to know if we have local or global minimum). However, if the cost/loss function is convex the following result provides invaluable information: - Any minimum is global for convex functions +!bblock Any minimum is global for convex functions Consider the problem of finding $x \in \mathbb{R}^n$ such that $f(x)$ is minimal, where $f$ is convex and differentiable. Then, any point $x^*$ that satisfies $\nabla f(x^*) = 0$ is a global minimum. - +!eblock This result means that if we know that the cost/loss function is convex and we are able to find a minimum, we are guaranteed that it is a global minimum. @@ -7657,8 +6078,6 @@ where $\hat{r}$ is the so-called residual or error in the iterative process. When we have found the exact solution, $\hat{r}=0$. -===== Gradient method ===== - The residual is zero when we reach the minimum of the quadratic equation !bt \begin{equation*} @@ -7671,8 +6090,6 @@ symmetric. This defines also the Hessian and we want it to be positive definit -===== Steepest descent method ===== - We denote the initial guess for $\hat{x}$ as $\hat{x}_0$. We can assume without loss of generality that !bt @@ -7690,8 +6107,6 @@ instead. -===== Steepest descent method ===== - One can show that the solution $\hat{x}$ is also the unique minimizer of the quadratic form !bt \begin{equation*} @@ -7709,11 +6124,6 @@ which equals and $\hat{x}_0=0$ it is equal $-\hat{b}$. - - - -===== Final expressions ===== - We can compute the residual iteratively as !bt \begin{equation*} @@ -7746,12 +6156,6 @@ leading to the iterative scheme \end{equation*} !et - - - -===== Code examples for steepest descent ===== - - ===== Simple codes for steepest descent and conjugate gradient using a $2\times 2$ matrix, in c++, Python code to come ===== !bc cppcod @@ -7784,8 +6188,6 @@ int main(int argc, char * argv[]){ -===== The routine for the steepest descent method ===== - !bc cppcod Vector SteepestDescent(Matrix A, Vector b, Vector x0){ int IterMax, i; @@ -7810,9 +6212,6 @@ Vector SteepestDescent(Matrix A, Vector b, Vector x0){ } !ec - - - ===== Steepest descent example ===== !bc pycod @@ -7888,10 +6287,6 @@ of our vectors $\hat{x}_i$ obeying the above criterion, namely Two vectors are conjugate if they are orthogonal with respect to this inner product. Being conjugate is a symmetric relation: if $\hat{s}$ is conjugate to $\hat{t}$, then $\hat{t}$ is conjugate to $\hat{s}$. - - -===== Conjugate gradient method ===== - An example is given by the eigenvectors of the matrix !bt \begin{equation*} @@ -7900,11 +6295,6 @@ An example is given by the eigenvectors of the matrix !et which is zero unless $i=j$. - - - -===== Conjugate gradient method ===== - Assume now that we have a symmetric positive-definite matrix $\hat{A}$ of size $n\times n$. At each iteration $i+1$ we obtain the conjugate direction of a vector !bt @@ -7922,10 +6312,6 @@ $ \hat{A}\hat{x} = \hat{b}$ in this basis, namely \end{equation*} !et - - -===== Conjugate gradient method ===== - The coefficients are given by !bt \begin{equation*} @@ -7947,11 +6333,6 @@ and we can define the coefficients $\alpha_k$ as \end{equation*} !et - - -===== Conjugate gradient method and iterations ===== - - If we choose the conjugate vectors $\hat{p}_k$ carefully, then we may not need all of them to obtain a good approximation to the solution $\hat{x}$. @@ -7974,11 +6355,6 @@ or consider the system !et instead. - - - -===== Conjugate gradient method ===== - One can show that the solution $\hat{x}$ is also the unique minimizer of the quadratic form !bt \begin{equation*} @@ -7998,11 +6374,6 @@ $\hat{x}_0=0$ it is equal $-\hat{b}$. The other vectors in the basis will be conjugate to the gradient, hence the name conjugate gradient method. - - - -===== Conjugate gradient method ===== - Let $\hat{r}_k$ be the residual at the $k$-th step: !bt \begin{equation*} @@ -8022,10 +6393,6 @@ This gives the following expression \end{equation*} !et - - -===== Conjugate gradient method ===== - We can also compute the residual iteratively as !bt \begin{equation*} @@ -8052,10 +6419,6 @@ which gives \end{equation*} !et - - - - ===== Simple implementation of the Conjugate gradient algorithm ===== !bc cppcod @@ -8085,9 +6448,6 @@ which gives } !ec - - - ===== Broyden–Fletcher–Goldfarb–Shanno algorithm ===== The optimization problem is to minimize $f(\mathbf {x} )$ where $\mathbf {x}$ is a vector in $R^{n}$, and $f$ is a differentiable scalar function. There are no constraints on the values that $\mathbf {x}$ can take. @@ -8115,20 +6475,12 @@ f(\mathbf {x}_{k}+\alpha \mathbf {p}_{k}), over the scalar $\alpha > 0$. - - - - - - -===== Revisiting our first homework ===== - We will use linear regression as a case study for the gradient descent methods. Linear regression is a great test case for the gradient descent methods discussed in the lectures since it has several desirable properties such as: -o An analytical solution (recall homework set 1). +o An analytical solution. o The gradient can be computed analytically. o The cost function is convex which guarantees that gradient descent converges for small enough learning rates @@ -8152,7 +6504,7 @@ such that \] !et - + ===== Gradient descent example ===== Let $\mathbf{y} = (y_1,\cdots,y_n)^T$, $\mathbf{\hat{y}} = (\hat{y}_1,\cdots,\hat{y}_n)^T$ and $\beta = (\beta_0, \beta_1)^T$ @@ -8176,8 +6528,6 @@ C(\beta) = ||X\beta-\mathbf{y}||^2 = ||X\beta||^2 - 2 \mathbf{y}^T X\beta + ||\m and we want to find $\beta$ such that $C(\beta)$ is minimized. -===== The derivative of the cost/loss function ===== - Computing $\partial C(\beta) / \partial \beta_0$ and $\partial C(\beta) / \partial \beta_1$ we can show that the gradient can be written as !bt \[ @@ -8189,7 +6539,6 @@ Computing $\partial C(\beta) / \partial \beta_0$ and $\partial C(\beta) / \parti where $X$ is the design matrix defined above. -===== The Hessian matrix ===== The Hessian matrix of $C(\beta)$ is given by !bt \[ @@ -8203,8 +6552,6 @@ This result implies that $C(\beta)$ is a convex function since the matrix $X^T X - - ===== Simple program ===== We can now write a program that minimizes $C(\beta)$ using the gradient descent method with a constant learning rate $\gamma$ according to @@ -8242,8 +6589,6 @@ print(beta_NE) !ec -===== Gradient Descent Example ===== - Another simple example is here !bc pycod @@ -8312,7 +6657,7 @@ print(sgdreg.intercept_, sgdreg.coef_) - + ===== Gradient descent and Ridge ===== We have also discussed Ridge regression where the loss function contains a regularized given by the $L_2$ norm of $\beta$, @@ -8422,7 +6767,7 @@ plt.show() print("The max absolute difference is: %g"%(np.max(np.abs(computed - analytic)))) !ec - + ===== Using autograd ===== Here we @@ -8528,7 +6873,7 @@ using arrays to represent the variables, the output from Autograd might be easier to work with, as the output is closer to what one could expect form a gradient-evaluting function. - + ===== Functions using mathematical functions from Numpy ===== !bc pycod @@ -8553,8 +6898,6 @@ print("The analytical gradient of f4 at x = %g is: %g"%(x,f4_grad_analytical)) -===== More autograd ===== - !bc pycod import autograd.numpy as np from autograd import grad @@ -8573,9 +6916,6 @@ print("The computed derivative of f5 at x = %g is: %g"%(x,f5_grad(x))) !ec - -===== And with loops ===== - !bc pycod import autograd.numpy as np from autograd import grad @@ -8732,8 +7072,6 @@ C(\mathbf{\beta}) = \sum_{i=1}^n c_i(\mathbf{x}_i, !et -===== Computation of gradients ===== - This in turn means that the gradient can be computed as a sum over $i$-gradients !bt @@ -8750,7 +7088,6 @@ minibatches. We denote these minibatches by $B_k$ where $k=1,\cdots,n/M$. -===== SGD example ===== As an example, suppose we have $10$ data points $(\mathbf{x}_1,\cdots, \mathbf{x}_{10})$ and we choose to have $M=5$ minibathces, then each minibatch contains two data points. In particular we have @@ -8773,7 +7110,6 @@ c_i(\mathbf{x}_i, \mathbf{\beta}). !et -===== The gradient step ===== Thus a gradient descent step now looks like !bt @@ -8790,8 +7126,6 @@ typical to choose a number of epochs and for each epoch iterate over the number of minibatches, as exemplified in the code below. -===== Simple example code ===== - !bc pycod import numpy as np @@ -8818,8 +7152,6 @@ cheaper since we sum over the datapoints in the $k-th$ minibatch and not all $n$ datapoints. -===== When do we stop? ===== - A natural question is when do we stop the search for a new minimum? One possibility is to compute the full gradient after a given number of epochs and check if the norm of the gradient is smaller than some @@ -8832,8 +7164,6 @@ compare the values of the cost function and keep the $\beta$ that gave the lowest value. -===== Slightly different approach ===== - Another approach is to let the step length $\gamma_j$ depend on the number of epochs in such a way that it becomes very small after a reasonable time such that we do not move at all. @@ -8875,11 +7205,6 @@ print("gamma_j after %d epochs: %g" % (n_epochs,gamma_j)) - - - -===== Program for stochastic gradient ===== - !bc pycod # Importing various packages from math import exp, sqrt @@ -8955,10 +7280,6 @@ plt.show() !ec - - - - ===== Using gradient descent methods, limitations ===== * _Gradient descent (GD) finds local minima of our function_. Since the GD algorithm is deterministic, if it converges, it will converge to a local minimum of our energy function. Because in ML we are often dealing with extremely rugged landscapes with many local minima, this can lead to poor performance. @@ -9042,9 +7363,6 @@ One of the major advantages of NAG is that it allows for the use of a larger lea -===== Second moment of the gradient ===== - - In stochastic gradient descent, with and without momentum, we still have to specify a schedule for tuning the learning rates $\eta_t$ as a function of time. As discussed in the context of Newton's @@ -9115,3433 +7433,3 @@ Like in RMSprop, the effective step size of a parameter depends on the magnitude * _Adaptive optimization methods don't always have good generalization._ Recent studies have shown that adaptive methods such as ADAM, RMSPorp, and AdaGrad tend to have poor generalization compared to SGD or SGD with momentum, particularly in the high-dimensional limit (i.e. the number of parameters exceeds the number of data points). Although it is not clear at this stage why these methods perform so well in training deep neural networks, simpler procedures like properly-tuned SGD may work as well or better in these applications. -======= Logistic Regression ======= - -In linear regression our main interest was centered on learning the -coefficients of a functional fit (say a polynomial) in order to be -able to predict the response of a continuous variable on some unseen -data. The fit to the continuous variable $y_i$ is based on some -independent variables $\hat{x}_i$. Linear regression resulted in -analytical expressions (in terms of matrices to invert) for several -quantities, ranging from the variance and thereby the confidence -intervals of the parameters $\hat{\beta}$ to the mean squared -error. If we can invert the product of the design matrices, linear -regression gives then a simple recipe for fitting our data. - - -Classification problems, however, are concerned with outcomes taking -the form of discrete variables (i.e. categories). We may for example, -on the basis of DNA sequencing for a number of patients, like to find -out which mutations are important for a certain disease; or based on -scans of various patients' brains, figure out if there is a tumor or -not; or given a specific physical system, we'd like to identify its -state, say whether it is an ordered or disordered system (typical -situation in solid state physics); or classify the status of a -patient, whether she/he has a stroke or not and many other similar -situations. - -The most common situation we encounter when we apply logistic -regression is that of two possible outcomes, normally denoted as a -binary outcome, true or false, positive or negative, success or -failure etc. - - -===== Optimization and Deep learning ===== - -Logistic regression will also serve as our stepping stone towards neural -network algorithms and supervised deep learning. For logistic -learning, the minimization of the cost function leads to a non-linear -equation in the parameters $\hat{\beta}$. The optmization of the problem calls therefore for minimization algorithms. This forms the bottle neck of all machine learning algorithms, namely how to find reliable minima of a multi-variable function. This leads us to the family of gradient descent methods. The latter are the working horses of basically all modern machine learning algorithms. - -We note also that many of the topics discussed here -regression are also commonly used in modern supervised Deep Learning -models, as we will see later. - - - -===== Basics ===== - -We consider the case where the dependent variables, also called the -responses or the outcomes, $y_i$ are discrete and only take values -from $k=0,\dots,K-1$ (i.e. $K$ classes). - -The goal is to predict the -output classes from the design matrix $\hat{X}\in\mathbb{R}^{n\times p}$ -made of $n$ samples, each of which carries $p$ features or predictors. The -primary goal is to identify the classes to which new unseen samples -belong. - -Let us specialize to the case of two classes only, with outputs $y_i=0$ and $y_i=1$. Our outcomes could represent the status of a credit card user who could default or not on her/his credit card debt. That is -!bt -\[ -y_i = \begin{bmatrix} 0 & \mathrm{no}\\ 1 & \mathrm{yes} \end{bmatrix}. -\] -!et - - - - -===== Linear classifier ===== - -Before moving to the logistic model, let us try to use our linear regression model to classify these two outcomes. We could for example fit a linear model to the default case if $y_i > 0.5$ and the no default case $y_i \leq 0.5$. - -We would then have our -weighted linear combination, namely -!bt -\begin{equation} -\hat{y} = \hat{X}^T\hat{\beta} + \hat{\epsilon}, -\end{equation} -!et -where $\hat{y}$ is a vector representing the possible outcomes, $\hat{X}$ is our -$n\times p$ design matrix and $\hat{\beta}$ represents our estimators/predictors. - - -===== Some selected properties ===== - -The main problem with our function is that it -takes values on the entire real axis. In the case of -logistic regression, however, the labels $y_i$ are discrete -variables. - -One simple way to get a discrete output is to have sign -functions that map the output of a linear regressor to values $\{0,1\}$, -$f(s_i)=sign(s_i)=1$ if $s_i\ge 0$ and 0 if otherwise. -We will encounter this model in our first demonstration of neural networks. Historically it is called the ``perceptron" model in the machine learning -literature. This model is extremely simple. However, in many cases it is more -favorable to use a ``soft" classifier that outputs -the probability of a given category. This leads us to the logistic function. - -The code for plotting the perceptron can be seen here. This si nothing but the standard "Heaviside step function":"https://en.wikipedia.org/wiki/Heaviside_step_function". -!bc pycod - -!ec - - - -===== The logistic function ===== - -The perceptron is an example of a ``hard classification'' model. We -will encounter this model when we discuss neural networks as -well. Each datapoint is deterministically assigned to a category (i.e -$y_i=0$ or $y_i=1$). In many cases, it is favorable to have a ``soft'' -classifier that outputs the probability of a given category rather -than a single value. For example, given $x_i$, the classifier -outputs the probability of being in a category $k$. Logistic regression -is the most common example of a so-called soft classifier. In logistic -regression, the probability that a data point $x_i$ -belongs to a category $y_i=\{0,1\}$ is given by the so-called logit function (or Sigmoid) which is meant to represent the likelihood for a given event, -!bt -\[ -p(t) = \frac{1}{1+\mathrm \exp{-t}}=\frac{\exp{t}}{1+\mathrm \exp{t}}. -\] -!et -Note that $1-p(t)= p(-t)$. -The following code plots the logistic function. -!bc pycod - -!ec - - - - -===== Two parameters ===== - -We assume now that we have two classes with $y_i$ either $0$ or $1$. Furthermore we assume also that we have only two parameters $\beta$ in our fitting of the Sigmoid function, that is we define probabilities -!bt -\begin{align*} -p(y_i=1|x_i,\hat{\beta}) &= \frac{\exp{(\beta_0+\beta_1x_i)}}{1+\exp{(\beta_0+\beta_1x_i)}},\nonumber\\ -p(y_i=0|x_i,\hat{\beta}) &= 1 - p(y_i=1|x_i,\hat{\beta}), -\end{align*} -!et -where $\hat{\beta}$ are the weights we wish to extract from data, in our case $\beta_0$ and $\beta_1$. - -Note that we used -!bt -\[ -p(y_i=0\vert x_i, \hat{\beta}) = 1-p(y_i=1\vert x_i, \hat{\beta}). -\] -!et - - -===== Maximum likelihood ===== - -In order to define the total likelihood for all possible outcomes from a -dataset $\mathcal{D}=\{(y_i,x_i)\}$, with the binary labels -$y_i\in\{0,1\}$ and where the data points are drawn independently, we use the so-called "Maximum Likelihood Estimation":"https://en.wikipedia.org/wiki/Maximum_likelihood_estimation" (MLE) principle. -We aim thus at maximizing -the probability of seeing the observed data. We can then approximate the -likelihood in terms of the product of the individual probabilities of a specific outcome $y_i$, that is -!bt -\begin{align*} -P(\mathcal{D}|\hat{\beta})& = \prod_{i=1}^n \left[p(y_i=1|x_i,\hat{\beta})\right]^{y_i}\left[1-p(y_i=1|x_i,\hat{\beta}))\right]^{1-y_i}\nonumber \\ -\end{align*} -!et -from which we obtain the log-likelihood and our _cost/loss_ function -!bt -\[ -\mathcal{C}(\hat{\beta}) = \sum_{i=1}^n \left( y_i\log{p(y_i=1|x_i,\hat{\beta})} + (1-y_i)\log\left[1-p(y_i=1|x_i,\hat{\beta}))\right]\right). -\] -!et - - -===== The cost function rewritten ===== - -Reordering the logarithms, we can rewrite the _cost/loss_ function as -!bt -\[ -\mathcal{C}(\hat{\beta}) = \sum_{i=1}^n \left(y_i(\beta_0+\beta_1x_i) -\log{(1+\exp{(\beta_0+\beta_1x_i)})}\right). -\] -!et - -The maximum likelihood estimator is defined as the set of parameters that maximize the log-likelihood where we maximize with respect to $\beta$. -Since the cost (error) function is just the negative log-likelihood, for logistic regression we have that -!bt -\[ -\mathcal{C}(\hat{\beta})=-\sum_{i=1}^n \left(y_i(\beta_0+\beta_1x_i) -\log{(1+\exp{(\beta_0+\beta_1x_i)})}\right). -\] -!et -This equation is known in statistics as the _cross entropy_. Finally, we note that just as in linear regression, -in practice we often supplement the cross-entropy with additional regularization terms, usually $L_1$ and $L_2$ regularization as we did for Ridge and Lasso regression. - - -===== Minimizing the cross entropy ===== - -The cross entropy is a convex function of the weights $\hat{\beta}$ and, -therefore, any local minimizer is a global minimizer. - - -Minimizing this -cost function with respect to the two parameters $\beta_0$ and $\beta_1$ we obtain - -!bt -\[ -\frac{\partial \mathcal{C}(\hat{\beta})}{\partial \beta_0} = -\sum_{i=1}^n \left(y_i -\frac{\exp{(\beta_0+\beta_1x_i)}}{1+\exp{(\beta_0+\beta_1x_i)}}\right), -\] -!et -and -!bt -\[ -\frac{\partial \mathcal{C}(\hat{\beta})}{\partial \beta_1} = -\sum_{i=1}^n \left(y_ix_i -x_i\frac{\exp{(\beta_0+\beta_1x_i)}}{1+\exp{(\beta_0+\beta_1x_i)}}\right). -\] -!et - - -===== A more compact expression ===== - -Let us now define a vector $\hat{y}$ with $n$ elements $y_i$, an -$n\times p$ matrix $\hat{X}$ which contains the $x_i$ values and a -vector $\hat{p}$ of fitted probabilities $p(y_i\vert x_i,\hat{\beta})$. We can rewrite in a more compact form the first -derivative of cost function as - -!bt -\[ -\frac{\partial \mathcal{C}(\hat{\beta})}{\partial \hat{\beta}} = -\hat{X}^T\left(\hat{y}-\hat{p}\right). -\] -!et - -If we in addition define a diagonal matrix $\hat{W}$ with elements -$p(y_i\vert x_i,\hat{\beta})(1-p(y_i\vert x_i,\hat{\beta})$, we can obtain a compact expression of the second derivative as - -!bt -\[ -\frac{\partial^2 \mathcal{C}(\hat{\beta})}{\partial \hat{\beta}\partial \hat{\beta}^T} = \hat{X}^T\hat{W}\hat{X}. -\] -!et - - -===== Extending to more predictors ===== - -Within a binary classification problem, we can easily expand our model to include multiple predictors. Our ratio between likelihoods is then with $p$ predictors -!bt -\[ -\log{ \frac{p(\hat{\beta}\hat{x})}{1-p(\hat{\beta}\hat{x})}} = \beta_0+\beta_1x_1+\beta_2x_2+\dots+\beta_px_p. -\] -!et -Here we defined $\hat{x}=[1,x_1,x_2,\dots,x_p]$ and $\hat{\beta}=[\beta_0, \beta_1, \dots, \beta_p]$ leading to -!bt -\[ -p(\hat{\beta}\hat{x})=\frac{ \exp{(\beta_0+\beta_1x_1+\beta_2x_2+\dots+\beta_px_p)}}{1+\exp{(\beta_0+\beta_1x_1+\beta_2x_2+\dots+\beta_px_p)}}. -\] -!et - - -===== Including more classes ===== - -Till now we have mainly focused on two classes, the so-called binary system. Suppose we wish to extend to $K$ classes. -Let us for the sake of simplicity assume we have only two predictors. We have then following model -!bt -\[ -\log{\frac{p(C=1\vert x)}{p(K\vert x)}} = \beta_{10}+\beta_{11}x_1, -\] -!et -!bt -\[ -\log{\frac{p(C=2\vert x)}{p(K\vert x)}} = \beta_{20}+\beta_{21}x_1, -\] -!et -and so on till the class $C=K-1$ class -!bt -\[ -\log{\frac{p(C=K-1\vert x)}{p(K\vert x)}} = \beta_{(K-1)0}+\beta_{(K-1)1}x_1, -\] -!et -and the model is specified in term of $K-1$ so-called log-odds or _logit_ transformations. - - - -===== The Softmax function ===== - -In our discussion of neural networks we will encounter the above again in terms of the so-called _Softmax_ function. - -The softmax function is used in various multiclass classification -methods, such as multinomial logistic regression (also known as -softmax regression), multiclass linear discriminant -analysis, naive Bayes classifiers, and artificial neural networks. -Specifically, in multinomial logistic regression and linear -discriminant analysis, the input to the function is the result of $K$ -distinct linear functions, and the predicted probability for the $k$-th -class given a sample vector $\hat{x}$ and a weighting vector $\hat{\beta}$ is (with two predictors): - -!bt -\[ -p(C=k\vert \mathbf {x} )=\frac{\exp{(\beta_{k0}+\beta_{k1}x_1)}}{1+\sum_{l=1}^{K-1}\exp{(\beta_{l0}+\beta_{l1}x_1)}}. -\] -!et -It is easy to extend to more predictors. The final class is -!bt -\[ -p(C=K\vert \mathbf {x} )=\frac{1}{1+\sum_{l=1}^{K-1}\exp{(\beta_{l0}+\beta_{l1}x_1)}}, -\] -!et -and they sum to one. Our earlier discussions were all specialized to the case with two classes only. It is easy to see from the above that what we derived earlier is compatible with these equations. - -To find the optimal parameters we would typically use a gradient descent method. -Newton's method and gradient descent methods are discussed in the material on "optimization methods":"https://compphysics.github.io/MachineLearning/doc/pub/Splines/html/Splines-bs.html". - - - - -===== A _scikit-learn_ example ===== - -!bc pycod -import numpy as np -import matplotlib.pyplot as plt -from sklearn import datasets -iris = datasets.load_iris() -list(iris.keys()) -['data', 'target_names', 'feature_names', 'target', 'DESCR'] -X = iris["data"][:, 3:] # petal width -y = (iris["target"] == 2).astype(np.int) # 1 if Iris-Virginica, else 0 - -from sklearn.linear_model import LogisticRegression -log_reg = LogisticRegression() -log_reg.fit(X, y) - -X_new = np.linspace(0, 3, 1000).reshape(-1, 1) -y_proba = log_reg.predict_proba(X_new) -plt.plot(X_new, y_proba[:, 1], "g-", label="Iris-Virginica") -plt.plot(X_new, y_proba[:, 0], "b--", label="Not Iris-Virginica") -plt.show() - -!ec - - - -===== A simple classification problem ===== -!bc pycod -import numpy as np -from sklearn import datasets, linear_model -import matplotlib.pyplot as plt - - -def generate_data(): - np.random.seed(0) - X, y = datasets.make_moons(200, noise=0.20) - return X, y - - -def visualize(X, y, clf): - # plt.scatter(X[:, 0], X[:, 1], s=40, c=y, cmap=plt.cm.Spectral) - # plt.show() - plot_decision_boundary(lambda x: clf.predict(x), X, y) - plt.title("Logistic Regression") - - -def plot_decision_boundary(pred_func, X, y): - # Set min and max values and give it some padding - x_min, x_max = X[:, 0].min() - .5, X[:, 0].max() + .5 - y_min, y_max = X[:, 1].min() - .5, X[:, 1].max() + .5 - h = 0.01 - # Generate a grid of points with distance h between them - xx, yy = np.meshgrid(np.arange(x_min, x_max, h), np.arange(y_min, y_max, h)) - # Predict the function value for the whole gid - Z = pred_func(np.c_[xx.ravel(), yy.ravel()]) - Z = Z.reshape(xx.shape) - # Plot the contour and training examples - plt.contourf(xx, yy, Z, cmap=plt.cm.Spectral) - plt.scatter(X[:, 0], X[:, 1], c=y, cmap=plt.cm.Spectral) - plt.show() - - -def classify(X, y): - clf = linear_model.LogisticRegressionCV() - clf.fit(X, y) - return clf - - -def main(): - X, y = generate_data() - # visualize(X, y) - clf = classify(X, y) - visualize(X, y, clf) - - -if __name__ == "__main__": - main() -!ec - - -===== The two-dimensional Ising model, Predicting phase transition of the two-dimensional Ising model ===== - -The Hamiltonian of the two-dimensional Ising model without an external field for a constant coupling constant $J$ is given by -!bt -\begin{align} - H = -J \sum_{\langle ij\rangle} S_i S_j, -\end{align} -!et -where $S_i \in \{-1, 1\}$ and $\langle ij \rangle$ signifies that we only iterate over the nearest neighbors in the lattice. We will be looking at a system of $L = 40$ spins in each dimension, i.e., $L^2 = 1600$ spins in total. Opposed to the one-dimensional Ising model we will get a phase transition from an _ordered_ phase to a _disordered_ phase at the critical temperature - -!bt -\begin{align} - \frac{T_c}{J} = \frac{2}{\log\left(1 + \sqrt{2}\right)} \approx 2.26, -\end{align} -!et -as shown by Lars Onsager. - - -Here we use _logistic regression_ to predict when a phase transition -occurs. The data we will look at is a set of spin configurations, -i.e., individual lattices with spins, labeled _ordered_ `1` or -_disordered_ `0`. Our job is to build a model which will take in a -spin configuration and predict whether or not the spin configuration -constitutes an ordered or a disordered phase. To achieve this we will -represent the lattices as flattened arrays with $1600$ elements -instead of a matrix of $40 \times 40$ elements. As an extra test of -the performance of the algorithms we will divide the dataset into -three pieces. We will do a conventional train-test-split on a -combination of totally ordered and totally disordered phases. The -remaining "critical-like" states will be used as test data which we -hope the model will be able to make good extrapolated predictions on. - - -!bc pycod -import pickle -import os -import glob -import numpy as np -import pandas as pd -import matplotlib.pyplot as plt -import seaborn as sns -import sklearn.model_selection as skms -import sklearn.linear_model as skl -import sklearn.metrics as skm -import tqdm -import copy -import time -from IPython.display import display - -%matplotlib inline - -sns.set(color_codes=True) -!ec - - -===== Reading in the data ===== - -Using the data from "Mehta et al.":"https://physics.bu.edu/~pankajm/ML-Review-Datasets/isingMC/" (specifically the two datasets named `Ising2DFM_reSample_L40_T=All.pkl` and `Ising2DFM_reSample_L40_T=All_labels.pkl`) we have to unpack the data into numpy arrays. - - -!bc pycod -filenames = glob.glob(os.path.join("..", "dat", "*")) -label_filename = list(filter(lambda x: "label" in x, filenames))[0] -dat_filename = list(filter(lambda x: "label" not in x, filenames))[0] - -# Read in the labels -with open(label_filename, "rb") as f: - labels = pickle.load(f) - -# Read in the corresponding configurations -with open(dat_filename, "rb") as f: - data = np.unpackbits(pickle.load(f)).reshape(-1, 1600).astype("int") - -# Set spin-down to -1 -data[data == 0] = -1 -!ec - -This dataset consists of $10000$ samples, i.e., $10000$ spin -configurations with $40 \times 40$ spins each, for $16$ temperatures -between $0.25$ to $4.0$. Next we create a train/test-split and keep -the data in the critical phase as a separate dataset for -extrapolation-testing. - - -!bc pycod -# Set up slices of the dataset -ordered = slice(0, 70000) -critical = slice(70000, 100000) -disordered = slice(100000, 160000) - -X_train, X_test, y_train, y_test = skms.train_test_split( - np.concatenate((data[ordered], data[disordered])), - np.concatenate((labels[ordered], labels[disordered])), - test_size=0.95 -) -!ec - -Using a small training set yields a better accuracy. This will be discussed in the end. - - -===== Logistic regression ===== - -Logistic regression is a linear model for classification. Recalling -the cost function for ordinary least squares with both L2 (ridge) and -L1 (LASSO) penalties we will see that the logistic cost function is -very similar. In OLS we wish to predict a continuous variable -$\hat{y}$ using -!bt -\begin{align} - \hat{y} = X\omega, -\end{align} -!et - -where $X \in \mathbb{R}^{n \times p}$ is the input data and $\omega^{p -\times d}$ are the weights of the regression. In a classification -setting (binary classification in our situation) we are interested in -a positive or negative answer. We can thus define either answer to be -above or below some threshold. But, in order to limit the size of the -answer and also to get a probability interpretation on how sure we are -for either answer we can compute the sigmoid function of OLS. That is, - -!bt -\begin{align} - f(X\omega) = \frac{1}{1 + \exp(-X\omega)}. -\end{align} -!et -We are thus interested in minizming the following cost function -!bt -\begin{align} - C(X, \omega) = \sum_{i = 1}^n \left\{ - - y_i\log\left( f(x_i^T\omega) \right) - - (1 - y_i)\log\left[1 - f(x_i^T\omega)\right] - \right\}, -\end{align} -!et - -where we will restrict ourselves to a value for $f(z)$ as the sigmoid -described above. We can also tack on a L2 (Ridge) or L1 (LASSO) -penalization to this cost function in the same manner we did for -linear regression. - - -===== Exploring the logistic regression ===== - -The penalization factor $\lambda$ is inverted in the case of the -logistic regression model we use. We will explore several values of -$\lambda$ using both L1 and L2 penalization. We do this using a grid -search over different parameters and run a 3-fold cross validation for -each configuration. In other words, we fit a model 3 times for each -configuration of the hyper parameters. - - -!bc pycod -lambdas = np.logspace(-7, -1, 7) - -param_grid = { - "C": list(1.0/lambdas), - "penalty": ["l1", "l2"] -} -clf = skms.GridSearchCV( - skl.LogisticRegression(), - param_grid=param_grid, - n_jobs=-1, - return_train_score=True -) -t0 = time.time() -clf.fit(X_train, y_train) -t1 = time.time() - -print ( - "Time spent fitting GridSearchCV(LogisticRegression): {0:.3f} sec".format( - t1 - t0 - ) -) -!ec - -We can see that logistic regression is quite slow and using the grid -search and cross validation results in quite a heavy -computation. Below we show the results of the different -configurations. - - -!bc pycod -logreg_df = pd.DataFrame(clf.cv_results_) - -display(logreg_df) -!ec - - -===== Accuracy of a classification model ===== - -To determine how well a classification model is performing we count -the number of correctly labeled classes and divide by the number of -classes in total. The accuracy is thus given by - -!bt -\begin{align} - a(y, \hat{y}) = \frac{1}{n}\sum_{i = 1}^{n} I(y_i = \hat{y}_i), -\end{align} -!et - -where $I(y_i = \hat{y}_i)$ is the indicator function given by - -!bt -\begin{align} - I(x = y) = \begin{array}{cc} - 1 & x = y, \\ - 0 & x \neq y. - \end{array} -\end{align} -!et - -This is the accuracy provided by Scikit-learn when using _sklearn.metrics.accuracyscore_. - -Below we compute the accuracy of the best fit model on the training data (which should give a good accuracy), the test data (which has not been shown to the model) and the critical data (completely new data that needs to be extrapolated). - - -!bc pycod -train_accuracy = skm.accuracy_score(y_train, clf.predict(X_train)) -test_accuracy = skm.accuracy_score(y_test, clf.predict(X_test)) -critical_accuracy = skm.accuracy_score(labels[critical], clf.predict(data[critical])) - -print ("Accuracy on train data: {0}".format(train_accuracy)) -print ("Accuracy on test data: {0}".format(test_accuracy)) -print ("Accuracy on critical data: {0}".format(critical_accuracy)) -!ec - -We can see that we get quite good accuracy on the training data, but gradually worsening accuracy on the test and critical data. - - -===== Analyzing the results ===== - -Below we show a different metric for determining the quality of our -model, namely the _reciever operating characteristic_ (ROC). The ROC -curve tells us how well the model correctly classifies the different -labels. We plot the _true positive rate_ (the rate of predicted -positive classes that are positive) versus the _false positive rate_ -(the rate of predicted positive classes that are negative). The ROC -curve is built by computing the true positive rate and the false -positive rate for varying _thresholds_, i.e, which probability we -should acredit a certain class. - -By computing the _area under the curve_ (AUC) of the ROC curve we get an estimate of how well our model is performing. Pure guessing will get an AUC of $0.5$. A perfect score will get an AUC of $1.0$. - - -!bc pycod -fig = plt.figure(figsize=(20, 14)) - -for (_X, _y), label in zip( - [ - (X_train, y_train), - (X_test, y_test), - (data[critical], labels[critical]) - ], - ["Train", "Test", "Critical"] -): - proba = clf.predict_proba(_X) - fpr, tpr, _ = skm.roc_curve(_y, proba[:, 1]) - roc_auc = skm.auc(fpr, tpr) - - print ("LogisticRegression AUC ({0}): {1}".format(label, roc_auc)) - - plt.plot(fpr, tpr, label="{0} (AUC = {1})".format(label, roc_auc), linewidth=4.0) - -plt.plot([0, 1], [0, 1], "--", label="Guessing (AUC = 0.5)", linewidth=4.0) - -plt.title(r"The ROC curve for LogisticRegression", fontsize=18) -plt.xlabel(r"False positive rate", fontsize=18) -plt.ylabel(r"True positive rate", fontsize=18) -plt.axis([-0.01, 1.01, -0.01, 1.01]) -plt.xticks(fontsize=18) -plt.yticks(fontsize=18) -plt.legend(loc="best", fontsize=18) -plt.show() -!ec - -We can see that this plot of the ROC looks very strange. This tells us -that logistic regression is quite inept at predicting the Ising model -transition and is therefore highly non-linear. The ROC curve for the -training data looks quite good, but as the testing data is so far off -we see that we are dealing with an overfit model. - -A previous run with $50\%$ of the data used for training yielded a -worse performance than using a smaller training set. This again gives -confidence to the fact that logistic regression is not able to -correctly fit the Ising model as it is not a linear model. - - - - - - - -======= Neural networks ======= - -Artificial neural networks are computational systems that can learn to -perform tasks by considering examples, generally without being -programmed with any task-specific rules. It is supposed to mimic a -biological system, wherein neurons interact by sending signals in the -form of mathematical functions between layers. All layers can contain -an arbitrary number of neurons, and each connection is represented by -a weight variable. - - - -===== Artificial neurons ===== - -The field of artificial neural networks has a long history of -development, and is closely connected with the advancement of computer -science and computers in general. A model of artificial neurons was -first developed by McCulloch and Pitts in 1943 to study signal -processing in the brain and has later been refined by others. The -general idea is to mimic neural networks in the human brain, which is -composed of billions of neurons that communicate with each other by -sending electrical signals. Each neuron accumulates its incoming -signals, which must exceed an activation threshold to yield an -output. If the threshold is not overcome, the neuron remains inactive, -i.e. has zero output. - -This behaviour has inspired a simple mathematical model for an artificial neuron. - -!bt -\begin{equation} - y = f\left(\sum_{i=1}^n w_ix_i\right) = f(u) - label{artificialNeuron} -\end{equation} -!et -Here, the output $y$ of the neuron is the value of its activation function, which have as input -a weighted sum of signals $x_i, \dots ,x_n$ received by $n$ other neurons. - -Conceptually, it is helpful to divide neural networks into four -categories: -o general purpose neural networks for supervised learning, -o neural networks designed specifically for image processing, the most prominent example of this class being Convolutional Neural Networks (CNNs), -o neural networks for sequential data such as Recurrent Neural Networks (RNNs), and -o neural networks for unsupervised learning such as Deep Boltzmann Machines. - - -In natural science, DNNs and CNNs have already found numerous -applications. In statistical physics, they have been applied to detect -phase transitions in 2D Ising and Potts models, lattice gauge -theories, and different phases of polymers, or solving the -Navier-Stokes equation in weather forecasting. Deep learning has also -found interesting applications in quantum physics. Various quantum -phase transitions can be detected and studied using DNNs and CNNs, -topological phases, and even non-equilibrium many-body -localization. Representing quantum states as DNNs quantum state -tomography are among some of the impressive achievements to reveal the -potential of DNNs to facilitate the study of quantum systems. - -In quantum information theory, it has been shown that one can perform -gate decompositions with the help of neural. - -The applications are not limited to the natural sciences. There is a -plethora of applications in essentially all disciplines, from the -humanities to life science and medicine. - - -===== Neural network types ===== - -An artificial neural network (ANN), is a computational model that -consists of layers of connected neurons, or nodes or units. We will -refer to these interchangeably as units or nodes, and sometimes as -neurons. - -It is supposed to mimic a biological nervous system by letting each -neuron interact with other neurons by sending signals in the form of -mathematical functions between layers. A wide variety of different -ANNs have been developed, but most of them consist of an input layer, -an output layer and eventual layers in-between, called *hidden -layers*. All layers can contain an arbitrary number of nodes, and each -connection between two nodes is associated with a weight variable. - -Neural networks (also called neural nets) are neural-inspired -nonlinear models for supervised learning. As we will see, neural nets -can be viewed as natural, more powerful extensions of supervised -learning methods such as linear and logistic regression and soft-max -methods we discussed earlier. - - - -===== Feed-forward neural networks ===== - -The feed-forward neural network (FFNN) was the first and simplest type -of ANNs that were devised. In this network, the information moves in -only one direction: forward through the layers. - -Nodes are represented by circles, while the arrows display the -connections between the nodes, including the direction of information -flow. Additionally, each arrow corresponds to a weight variable -(figure to come). We observe that each node in a layer is connected -to *all* nodes in the subsequent layer, making this a so-called -*fully-connected* FFNN. - - - - -===== Convolutional Neural Network ===== - -A different variant of FFNNs are *convolutional neural networks* -(CNNs), which have a connectivity pattern inspired by the animal -visual cortex. Individual neurons in the visual cortex only respond to -stimuli from small sub-regions of the visual field, called a receptive -field. This makes the neurons well-suited to exploit the strong -spatially local correlation present in natural images. The response of -each neuron can be approximated mathematically as a convolution -operation. (figure to come) - -Convolutional neural networks emulate the behaviour of neurons in the -visual cortex by enforcing a *local* connectivity pattern between -nodes of adjacent layers: Each node in a convolutional layer is -connected only to a subset of the nodes in the previous layer, in -contrast to the fully-connected FFNN. Often, CNNs consist of several -convolutional layers that learn local features of the input, with a -fully-connected layer at the end, which gathers all the local data and -produces the outputs. They have wide applications in image and video -recognition. - - -===== Recurrent neural networks ===== - -So far we have only mentioned ANNs where information flows in one -direction: forward. *Recurrent neural networks* on the other hand, -have connections between nodes that form directed *cycles*. This -creates a form of internal memory which are able to capture -information on what has been calculated before; the output is -dependent on the previous computations. Recurrent NNs make use of -sequential information by performing the same task for every element -in a sequence, where each element depends on previous elements. An -example of such information is sentences, making recurrent NNs -especially well-suited for handwriting and speech recognition. - - -===== Other types of networks ===== - -There are many other kinds of ANNs that have been developed. One type -that is specifically designed for interpolation in multidimensional -space is the radial basis function (RBF) network. RBFs are typically -made up of three layers: an input layer, a hidden layer with -non-linear radial symmetric activation functions and a linear output -layer (''linear'' here means that each node in the output layer has a -linear activation function). The layers are normally fully-connected -and there are no cycles, thus RBFs can be viewed as a type of -fully-connected FFNN. They are however usually treated as a separate -type of NN due the unusual activation functions. - - -===== Multilayer perceptrons ===== - -One uses often so-called fully-connected feed-forward neural networks -with three or more layers (an input layer, one or more hidden layers -and an output layer) consisting of neurons that have non-linear -activation functions. - -Such networks are often called *multilayer perceptrons* (MLPs). - - -===== Why multilayer perceptrons? ===== - -According to the *Universal approximation theorem*, a feed-forward -neural network with just a single hidden layer containing a finite -number of neurons can approximate a continuous multidimensional -function to arbitrary accuracy, assuming the activation function for -the hidden layer is a _non-constant, bounded and -monotonically-increasing continuous function_. - -Note that the requirements on the activation function only applies to -the hidden layer, the output nodes are always assumed to be linear, so -as to not restrict the range of output values. - - - -===== Mathematical model ===== - -The output $y$ is produced via the activation function $f$ -!bt -\[ - y = f\left(\sum_{i=1}^n w_ix_i + b_i\right) = f(z), -\] -!et -This function receives $x_i$ as inputs. -Here the activation $z=(\sum_{i=1}^n w_ix_i+b_i)$. -In an FFNN of such neurons, the *inputs* $x_i$ are the *outputs* of -the neurons in the preceding layer. Furthermore, an MLP is -fully-connected, which means that each neuron receives a weighted sum -of the outputs of *all* neurons in the previous layer. - - -===== Mathematical model ===== - -First, for each node $i$ in the first hidden layer, we calculate a weighted sum $z_i^1$ of the input coordinates $x_j$, - -!bt -\begin{equation} z_i^1 = \sum_{j=1}^{M} w_{ij}^1 x_j + b_i^1 -\end{equation} -!et - -Here $b_i$ is the so-called bias which is normally needed in -case of zero activation weights or inputs. How to fix the biases and -the weights will be discussed below. The value of $z_i^1$ is the -argument to the activation function $f_i$ of each node $i$, The -variable $M$ stands for all possible inputs to a given node $i$ in the -first layer. We define the output $y_i^1$ of all neurons in layer 1 as - -!bt -\begin{equation} - y_i^1 = f(z_i^1) = f\left(\sum_{j=1}^M w_{ij}^1 x_j + b_i^1\right) - label{outputLayer1} -\end{equation} -!et - -where we assume that all nodes in the same layer have identical -activation functions, hence the notation $f$. In general, we could assume in the more general case that different layers have different activation functions. -In this case we would identify these functions with a superscript $l$ for the $l$-th layer, - -!bt -\begin{equation} - y_i^l = f^l(u_i^l) = f^l\left(\sum_{j=1}^{N_{l-1}} w_{ij}^l y_j^{l-1} + b_i^l\right) - label{generalLayer} -\end{equation} -!et - -where $N_l$ is the number of nodes in layer $l$. When the output of -all the nodes in the first hidden layer are computed, the values of -the subsequent layer can be calculated and so forth until the output -is obtained. - - - - -===== Mathematical model ===== - -The output of neuron $i$ in layer 2 is thus, - -!bt -\begin{align} - y_i^2 &= f^2\left(\sum_{j=1}^N w_{ij}^2 y_j^1 + b_i^2\right) \\ - &= f^2\left[\sum_{j=1}^N w_{ij}^2f^1\left(\sum_{k=1}^M w_{jk}^1 x_k + b_j^1\right) + b_i^2\right] - label{outputLayer2} -\end{align} -!et -where we have substituted $y_k^1$ with the inputs $x_k$. Finally, the ANN output reads - -!bt -\begin{align} - y_i^3 &= f^3\left(\sum_{j=1}^N w_{ij}^3 y_j^2 + b_i^3\right) \\ - &= f_3\left[\sum_{j} w_{ij}^3 f^2\left(\sum_{k} w_{jk}^2 f^1\left(\sum_{m} w_{km}^1 x_m + b_k^1\right) + b_j^2\right) - + b_1^3\right] -\end{align} -!et - - -===== Mathematical model ===== - -We can generalize this expression to an MLP with $l$ hidden -layers. The complete functional form is, - -!bt -\begin{align} -&y^{l+1}_i = f^{l+1}\left[\!\sum_{j=1}^{N_l} w_{ij}^3 f^l\left(\sum_{k=1}^{N_{l-1}}w_{jk}^{l-1}\left(\dots f^1\left(\sum_{n=1}^{N_0} w_{mn}^1 x_n+ b_m^1\right)\dots\right)+b_k^2\right)+b_1^3\right] && - label{completeNN} -\end{align} -!et - -which illustrates a basic property of MLPs: The only independent -variables are the input values $x_n$. - - -===== Mathematical model ===== - -This confirms that an MLP, despite its quite convoluted mathematical -form, is nothing more than an analytic function, specifically a -mapping of real-valued vectors $\hat{x} \in \mathbb{R}^n \rightarrow -\hat{y} \in \mathbb{R}^m$. - -Furthermore, the flexibility and universality of an MLP can be -illustrated by realizing that the expression is essentially a nested -sum of scaled activation functions of the form - -!bt -\begin{equation} - f(x) = c_1 f(c_2 x + c_3) + c_4 -\end{equation} -!et - -where the parameters $c_i$ are weights and biases. By adjusting these -parameters, the activation functions can be shifted up and down or -left and right, change slope or be rescaled which is the key to the -flexibility of a neural network. - - -=== Matrix-vector notation === - -We can introduce a more convenient notation for the activations in an A NN. - -Additionally, we can represent the biases and activations -as layer-wise column vectors $\hat{b}_l$ and $\hat{y}_l$, so that the $i$-th element of each vector -is the bias $b_i^l$ and activation $y_i^l$ of node $i$ in layer $l$ respectively. - -We have that $\mathrm{W}_l$ is an $N_{l-1} \times N_l$ matrix, while $\hat{b}_l$ and $\hat{y}_l$ are $N_l \times 1$ column vectors. -With this notation, the sum becomes a matrix-vector multiplication, and we can write -the equation for the activations of hidden layer 2 (assuming three nodes for simplicity) as -!bt -\begin{equation} - \hat{y}_2 = f_2(\mathrm{W}_2 \hat{y}_{1} + \hat{b}_{2}) = - f_2\left(\left[\begin{array}{ccc} - w^2_{11} &w^2_{12} &w^2_{13} \\ - w^2_{21} &w^2_{22} &w^2_{23} \\ - w^2_{31} &w^2_{32} &w^2_{33} \\ - \end{array} \right] \cdot - \left[\begin{array}{c} - y^1_1 \\ - y^1_2 \\ - y^1_3 \\ - \end{array}\right] + - \left[\begin{array}{c} - b^2_1 \\ - b^2_2 \\ - b^2_3 \\ - \end{array}\right]\right). -\end{equation} -!et - - -=== Matrix-vector notation and activation === - -The activation of node $i$ in layer 2 is - -!bt -\begin{equation} - y^2_i = f_2\Bigr(w^2_{i1}y^1_1 + w^2_{i2}y^1_2 + w^2_{i3}y^1_3 + b^2_i\Bigr) = - f_2\left(\sum_{j=1}^3 w^2_{ij} y_j^1 + b^2_i\right). -\end{equation} -!et - -This is not just a convenient and compact notation, but also a useful -and intuitive way to think about MLPs: The output is calculated by a -series of matrix-vector multiplications and vector additions that are -used as input to the activation functions. For each operation -$\mathrm{W}_l \hat{y}_{l-1}$ we move forward one layer. - - - -=== Activation functions === - - -A property that characterizes a neural network, other than its -connectivity, is the choice of activation function(s). As described -in, the following restrictions are imposed on an activation function -for a FFNN to fulfill the universal approximation theorem - - * Non-constant - - * Bounded - - * Monotonically-increasing - - * Continuous - - -=== Activation functions, Logistic and Hyperbolic ones === - -The second requirement excludes all linear functions. Furthermore, in -a MLP with only linear activation functions, each layer simply -performs a linear transformation of its inputs. - -Regardless of the number of layers, the output of the NN will be -nothing but a linear function of the inputs. Thus we need to introduce -some kind of non-linearity to the NN to be able to fit non-linear -functions Typical examples are the logistic *Sigmoid* - -!bt -\[ - f(x) = \frac{1}{1 + e^{-x}}, -\] -!et -and the *hyperbolic tangent* function -!bt -\[ - f(x) = \tanh(x) -\] -!et - - -=== Relevance === - -The *sigmoid* function are more biologically plausible because the -output of inactive neurons are zero. Such activation function are -called *one-sided*. However, it has been shown that the hyperbolic -tangent performs better than the sigmoid for training MLPs. has -become the most popular for *deep neural networks* - -!bc pycod -"""The sigmoid function (or the logistic curve) is a -function that takes any real number, z, and outputs a number (0,1). -It is useful in neural networks for assigning weights on a relative scale. -The value z is the weighted sum of parameters involved in the learning algorithm.""" - -import numpy -import matplotlib.pyplot as plt -import math as mt - -z = numpy.arange(-5, 5, .1) -sigma_fn = numpy.vectorize(lambda z: 1/(1+numpy.exp(-z))) -sigma = sigma_fn(z) - -fig = plt.figure() -ax = fig.add_subplot(111) -ax.plot(z, sigma) -ax.set_ylim([-0.1, 1.1]) -ax.set_xlim([-5,5]) -ax.grid(True) -ax.set_xlabel('z') -ax.set_title('sigmoid function') - -plt.show() - -"""Step Function""" -z = numpy.arange(-5, 5, .02) -step_fn = numpy.vectorize(lambda z: 1.0 if z >= 0.0 else 0.0) -step = step_fn(z) - -fig = plt.figure() -ax = fig.add_subplot(111) -ax.plot(z, step) -ax.set_ylim([-0.5, 1.5]) -ax.set_xlim([-5,5]) -ax.grid(True) -ax.set_xlabel('z') -ax.set_title('step function') - -plt.show() - -"""Sine Function""" -z = numpy.arange(-2*mt.pi, 2*mt.pi, 0.1) -t = numpy.sin(z) - -fig = plt.figure() -ax = fig.add_subplot(111) -ax.plot(z, t) -ax.set_ylim([-1.0, 1.0]) -ax.set_xlim([-2*mt.pi,2*mt.pi]) -ax.grid(True) -ax.set_xlabel('z') -ax.set_title('sine function') - -plt.show() - -"""Plots a graph of the squashing function used by a rectified linear -unit""" -z = numpy.arange(-2, 2, .1) -zero = numpy.zeros(len(z)) -y = numpy.max([zero, z], axis=0) - -fig = plt.figure() -ax = fig.add_subplot(111) -ax.plot(z, y) -ax.set_ylim([-2.0, 2.0]) -ax.set_xlim([-2.0, 2.0]) -ax.grid(True) -ax.set_xlabel('z') -ax.set_title('Rectified linear unit') - -plt.show() -!ec - - - -===== The multilayer perceptron (MLP) ===== - -The multilayer perceptron is a very popular, and easy to implement approach, to deep learning. It consists of -o A neural network with one or more layers of nodes between the input and the output nodes. -o The multilayer network structure, or architecture, or topology, consists of an input layer, one or more hidden layers, and one output layer. -o The input nodes pass values to the first hidden layer, its nodes pass the information on to the second and so on till we reach the output layer. - -As a convention it is normal to call a network with one layer of input units, one layer of hidden -units and one layer of output units as a two-layer network. A network with two layers of hidden units is called a three-layer network etc etc. - -For an MLP network there is no direct connection between the output nodes/neurons/units and the input nodes/neurons/units. -Hereafter we will call the various entities of a layer for nodes. -There are also no connections within a single layer. - -The number of input nodes does not need to equal the number of output -nodes. This applies also to the hidden layers. Each layer may have its -own number of nodes and activation functions. - -The hidden layers have their name from the fact that they are not -linked to observables and as we will see below when we define the -so-called activation $\hat{z}$, we can think of this as a basis -expansion of the original inputs $\hat{x}$. The difference however -between neural networks and say linear regression is that now these -basis functions (which will correspond to the weights in the network) -are learned from data. This results in an important difference between -neural networks and deep learning approaches on one side and methods -like logistic regression or linear regression and their modifications on the other side. - - - -===== From one to many layers, the universal approximation theorem ===== - - -A neural network with only one layer, what we called the simple -perceptron, is best suited if we have a standard binary model with -clear (linear) boundaries between the outcomes. As such it could -equally well be replaced by standard linear regression or logistic -regression. Networks with one or more hidden layers approximate -systems with more complex boundaries. - -As stated earlier, -an important theorem in studies of neural networks, restated without -proof here, is the "universal approximation -theorem":"http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.441.7873&rep=rep1&type=pdf". - -It states that a feed-forward network with a single hidden layer -containing a finite number of neurons can approximate continuous -functions on compact subsets of real functions. The theorem thus -states that simple neural networks can represent a wide variety of -interesting functions when given appropriate parameters. It is the -multilayer feedforward architecture itself which gives neural networks -the potential of being universal approximators. - - - -===== Deriving the back propagation code for a multilayer perceptron model ===== - - -_Note: figures will be inserted later!_ - -As we have seen now in a feed forward network, we can express the final output of our network in terms of basic matrix-vector multiplications. -The unknowwn quantities are our weights $w_{ij}$ and we need to find an algorithm for changing them so that our errors are as small as possible. -This leads us to the famous "back propagation algorithm":"https://www.nature.com/articles/323533a0". - -The questions we want to ask are how do changes in the biases and the -weights in our network change the cost function and how can we use the -final output to modify the weights? - -To derive these equations let us start with a plain regression problem -and define our cost function as - -!bt -\[ -{\cal C}(\hat{W}) = \frac{1}{2}\sum_{i=1}^n\left(y_i - t_i\right)^2, -\] -!et - -where the $t_i$s are our $n$ targets (the values we want to -reproduce), while the outputs of the network after having propagated -all inputs $\hat{x}$ are given by $y_i$. Below we will demonstrate -how the basic equations arising from the back propagation algorithm -can be modified in order to study classification problems with $K$ -classes. - - -===== Definitions ===== - -With our definition of the targets $\hat{t}$, the outputs of the -network $\hat{y}$ and the inputs $\hat{x}$ we -define now the activation $z_j^l$ of node/neuron/unit $j$ of the -$l$-th layer as a function of the bias, the weights which add up from -the previous layer $l-1$ and the forward passes/outputs -$\hat{a}^{l-1}$ from the previous layer as - - -!bt -\[ -z_j^l = \sum_{i=1}^{M_{l-1}}w_{ij}^la_i^{l-1}+b_j^l, -\] -!et - -where $b_k^l$ are the biases from layer $l$. Here $M_{l-1}$ -represents the total number of nodes/neurons/units of layer $l-1$. The -figure here illustrates this equation. We can rewrite this in a more -compact form as the matrix-vector products we discussed earlier, - -!bt -\[ -\hat{z}^l = \left(\hat{W}^l\right)^T\hat{a}^{l-1}+\hat{b}^l. -\] -!et - -With the activation values $\hat{z}^l$ we can in turn define the -output of layer $l$ as $\hat{a}^l = f(\hat{z}^l)$ where $f$ is our -activation function. In the examples here we will use the sigmoid -function discussed in our logistic regression lectures. We will also use the same activation function $f$ for all layers -and their nodes. It means we have - -!bt -\[ -a_j^l = f(z_j^l) = \frac{1}{1+\exp{-(z_j^l)}}. -\] -!et - - - -===== Derivatives and the chain rule ===== - -From the definition of the activation $z_j^l$ we have -!bt -\[ -\frac{\partial z_j^l}{\partial w_{ij}^l} = a_i^{l-1}, -\] -!et -and -!bt -\[ -\frac{\partial z_j^l}{\partial a_i^{l-1}} = w_{ji}^l. -\] -!et - -With our definition of the activation function we have that (note that this function depends only on $z_j^l$) -!bt -\[ -\frac{\partial a_j^l}{\partial z_j^{l}} = a_j^l(1-a_j^l)=f(z_j^l)(1-f(z_j^l)). -\] -!et - - - -===== Derivative of the cost function ===== - -With these definitions we can now compute the derivative of the cost function in terms of the weights. - -Let us specialize to the output layer $l=L$. Our cost function is -!bt -\[ -{\cal C}(\hat{W^L}) = \frac{1}{2}\sum_{i=1}^n\left(y_i - t_i\right)^2=\frac{1}{2}\sum_{i=1}^n\left(a_i^L - t_i\right)^2, -\] -!et -The derivative of this function with respect to the weights is - -!bt -\[ -\frac{\partial{\cal C}(\hat{W^L})}{\partial w_{jk}^L} = \left(a_j^L - t_j\right)\frac{\partial a_j^L}{\partial w_{jk}^{L}}, -\] -!et -The last partial derivative can easily be computed and reads (by applying the chain rule) -!bt -\[ -\frac{\partial a_j^L}{\partial w_{jk}^{L}} = \frac{\partial a_j^L}{\partial z_{j}^{L}}\frac{\partial z_j^L}{\partial w_{jk}^{L}}=a_j^L(1-a_j^L)a_k^{L-1}, -\] -!et - - - - -===== Bringing it together, first back propagation equation ===== - -We have thus -!bt -\[ -\frac{\partial{\cal C}(\hat{W^L})}{\partial w_{jk}^L} = \left(a_j^L - t_j\right)a_j^L(1-a_j^L)a_k^{L-1}, -\] -!et - -Defining -!bt -\[ -\delta_j^L = a_j^L(1-a_j^L)\left(a_j^L - t_j\right) = f'(z_j^L)\frac{\partial {\cal C}}{\partial (a_j^L)}, -\] -!et -and using the Hadamard product of two vectors we can write this as -!bt -\[ -\hat{\delta}^L = f'(\hat{z}^L)\circ\frac{\partial {\cal C}}{\partial (\hat{a}L)}. -\] -!et - -This is an important expression. The second term on the right handside -measures how fast the cost function is changing as a function of the $j$th -output activation. If, for example, the cost function doesn't depend -much on a particular output node $j$, then $\delta_j^L$ will be small, -which is what we would expect. The first term on the right, measures -how fast the activation function $f$ is changing at a given activation -value $z_j^L$. - -Notice that everything in the above equations is easily computed. In -particular, we compute $z_j^L$ while computing the behaviour of the -network, and it is only a small additional overhead to compute -$f'(z^L_j)$. The exact form of the derivative with respect to the -output depends on the form of the cost function. -However, provided the cost function is known there should be little -trouble in calculating - -!bt -\[ -\frac{\partial {\cal C}}{\partial (a_j^L)} -\] -!et - -With the definition of $\delta_j^L$ we have a more compact definition of the derivative of the cost function in terms of the weights, namely -!bt -\[ -\frac{\partial{\cal C}(\hat{W^L})}{\partial w_{jk}^L} = \delta_j^La_k^{L-1}. -\] -!et - - -===== Derivatives in terms of $z_j^L$ ===== - -It is also easy to see that our previous equation can be written as - -!bt -\[ -\delta_j^L =\frac{\partial {\cal C}}{\partial z_j^L}= \frac{\partial {\cal C}}{\partial a_j^L}\frac{\partial a_j^L}{\partial z_j^L}, -\] -!et -which can also be interpreted as the partial derivative of the cost function with respect to the biases $b_j^L$, namely -!bt -\[ -\delta_j^L = \frac{\partial {\cal C}}{\partial b_j^L}\frac{\partial b_j^L}{\partial z_j^L}=\frac{\partial {\cal C}}{\partial b_j^L}, -\] -!et -That is, the error $\delta_j^L$ is exactly equal to the rate of change of the cost function as a function of the bias. - -===== Bringing it together ===== - -We have now three equations that are essential for the computations of the derivatives of the cost function at the output layer. These equations are needed to start the algorithm and they are - - The starting equations - -!bt -\begin{equation} -\frac{\partial{\cal C}(\hat{W^L})}{\partial w_{jk}^L} = \delta_j^La_k^{L-1}, -\end{equation} -!et -and -!bt -\begin{equation} -\delta_j^L = f'(z_j^L)\frac{\partial {\cal C}}{\partial (a_j^L)}, -\end{equation} -!et -and - -!bt -\begin{equation} -\delta_j^L = \frac{\partial {\cal C}}{\partial b_j^L}, -\end{equation} -!et - - - -An interesting consequence of the above equations is that when the -activation $a_k^{L-1}$ is small, the gradient term, that is the -derivative of the cost function with respect to the weights, will also -tend to be small. We say then that the weight learns slowly, meaning -that it changes slowly when we minimize the weights via say gradient -descent. In this case we say the system learns slowly. - -Another interesting feature is that is when the activation function, -represented by the sigmoid function here, is rather flat when we move towards -its end values $0$ and $1$ (see the above Python codes). In these -cases, the derivatives of the activation function will also be close -to zero, meaning again that the gradients will be small and the -network learns slowly again. - - - -We need a fourth equation and we are set. We are going to propagate -backwards in order to the determine the weights and biases. In order -to do so we need to represent the error in the layer before the final -one $L-1$ in terms of the errors in the final output layer. - - -===== Final back propagating equation ===== - -We have that (replacing $L$ with a general layer $l$) -!bt -\[ -\delta_j^l =\frac{\partial {\cal C}}{\partial z_j^l}. -\] -!et -We want to express this in terms of the equations for layer $l+1$. Using the chain rule and summing over all $k$ entries we have - -!bt -\[ -\delta_j^l =\sum_k \frac{\partial {\cal C}}{\partial z_k^{l+1}}\frac{\partial z_k^{l+1}}{\partial z_j^{l}}=\sum_k \delta_k^{l+1}\frac{\partial z_k^{l+1}}{\partial z_j^{l}}, -\] -!et -and recalling that -!bt -\[ -z_j^{l+1} = \sum_{i=1}^{M_{l}}w_{ij}^{l+1}a_j^{l}+b_j^{l+1}, -\] -!et -with $M_l$ being the number of nodes in layer $l$, we obtain -!bt -\[ -\delta_j^l =\sum_k \delta_k^{l+1}w_{kj}^{l+1}f'(z_j^l), -\] -!et -This is our final equation. - -We are now ready to set up the algorithm for back propagation and learning the weights and biases. - - -===== Setting up the Back propagation algorithm ===== - - - -The four equations provide us with a way of computing the gradient of the cost function. Let us write this out in the form of an algorithm. - - -First, we set up the input data $\hat{x}$ and the activations -$\hat{z}_1$ of the input layer and compute the activation function and -the pertinent outputs $\hat{a}^1$. - - - -Secondly, we perform then the feed forward till we reach the output -layer and compute all $\hat{z}_l$ of the input layer and compute the -activation function and the pertinent outputs $\hat{a}^l$ for -$l=2,3,\dots,L$. - - - -Thereafter we compute the ouput error $\hat{\delta}^L$ by computing all -!bt -\[ -\delta_j^L = f'(z_j^L)\frac{\partial {\cal C}}{\partial (a_j^L)}. -\] -!et - - - -Then we compute the back propagate error for each $l=L-1,L-2,\dots,2$ as -!bt -\[ -\delta_j^l = \sum_k \delta_k^{l+1}w_{kj}^{l+1}f'(z_j^l). -\] -!et - - - -Finally, we update the weights and the biases using gradient descent for each $l=L-1,L-2,\dots,2$ and update the weights and biases according to the rules -!bt -\[ -w_{jk}^l\leftarrow = w_{jk}^l- \eta \delta_j^la_k^{l-1}, -\] -!et - -!bt -\[ -b_j^l \leftarrow b_j^l-\eta \frac{\partial {\cal C}}{\partial b_j^l}=b_j^l-\eta \delta_j^l, -\] -!et - - -The parameter $\eta$ is the learning parameter discussed in connection with the gradient descent methods. -Here it is convenient to use stochastic gradient descent (see the examples below) with mini-batches with an outer loop that steps through multiple epochs of training. - - - -===== Setting up a Multi-layer perceptron model for classification ===== - -We are now gong to develop an example based on the MNIST data -base. This is a classification problem and we need to use our -cross-entropy function we discussed in connection with logistic -regression. The cross-entropy defines our cost function for the -classificaton problems with neural networks. - -In binary classification with two classes $(0, 1)$ we define the -logistic/sigmoid function as the probability that a particular input -is in class $0$ or $1$. This is possible because the logistic -function takes any input from the real numbers and inputs a number -between 0 and 1, and can therefore be interpreted as a probability. It -also has other nice properties, such as a derivative that is simple to -calculate. - -For an input $\boldsymbol{a}$ from the hidden layer, the probability that the input $\boldsymbol{x}$ -is in class 0 or 1 is just. We let $\theta$ represent the unknown weights and biases to be adjusted by our equations). The variable $x$ -represents our activation values $z$. We have -!bt -\[ -P(y = 0 \mid \hat{x}, \hat{\theta}) = \frac{1}{1 + \exp{(- \hat{x}})} , -\] -!et -and -!bt -\[ -P(y = 1 \mid \hat{x}, \hat{\theta}) = 1 - P(y = 0 \mid \hat{x}, \hat{\theta}) , -\] -!et - -where $y \in \{0, 1\}$ and $\hat{\theta}$ represents the weights and biases -of our network. - - - -===== Defining the cost function ===== - -Our cost function is given as (see the Logistic regression lectures) -!bt -\[ -\mathcal{C}(\hat{\theta}) = - \ln P(\mathcal{D} \mid \hat{\theta}) = - \sum_{i=1}^n -y_i \ln[P(y_i = 0)] + (1 - y_i) \ln [1 - P(y_i = 0)] = \sum_{i=1}^n \mathcal{L}_i(\hat{\theta}) . -\] -!et - -This last equality means that we can interpret our *cost* function as a sum over the *loss* function -for each point in the dataset $\mathcal{L}_i(\hat{\theta})$. -The negative sign is just so that we can think about our algorithm as minimizing a positive number, rather -than maximizing a negative number. - -In *multiclass* classification it is common to treat each integer label as a so called *one-hot* vector: - -$y = 5 \quad \rightarrow \quad \hat{y} = (0, 0, 0, 0, 0, 1, 0, 0, 0, 0) ,$ and - - -$y = 1 \quad \rightarrow \quad \hat{y} = (0, 1, 0, 0, 0, 0, 0, 0, 0, 0) ,$ - - -i.e. a binary bit string of length $C$, where $C = 10$ is the number of classes in the MNIST dataset (numbers from $0$ to $9$).. - -If $\hat{x}_i$ is the $i$-th input (image), $y_{ic}$ refers to the $c$-th component of the $i$-th -output vector $\hat{y}_i$. -The probability of $\hat{x}_i$ being in class $c$ will be given by the softmax function: - -!bt -\[ -P(y_{ic} = 1 \mid \hat{x}_i, \hat{\theta}) = \frac{\exp{((\hat{a}_i^{hidden})^T \hat{w}_c)}} -{\sum_{c'=0}^{C-1} \exp{((\hat{a}_i^{hidden})^T \hat{w}_{c'})}} , -\] -!et - -which reduces to the logistic function in the binary case. -The likelihood of this $C$-class classifier -is now given as: - -!bt -\[ -P(\mathcal{D} \mid \hat{\theta}) = \prod_{i=1}^n \prod_{c=0}^{C-1} [P(y_{ic} = 1)]^{y_{ic}} . -\] -!et -Again we take the negative log-likelihood to define our cost function: - -!bt -\[ -\mathcal{C}(\hat{\theta}) = - \log{P(\mathcal{D} \mid \hat{\theta})}. -\] -!et -See the logistic regression lectures for a full definition of the cost function. - -The back propagation equations need now only a small change, namely the definition of a new cost function. We are thus ready to use the same equations as before! - - -===== Example: binary classification problem ===== - -As an example of the above, relevant for project 2 as well, let us consider a binary class. As discussed in our logistic regression lectures, we defined a cost function in terms of the parameters $\beta$ as -!bt -\[ -\mathcal{C}(\hat{\beta}) = - \sum_{i=1}^n \left(y_i\log{p(y_i \vert x_i,\hat{\beta})}+(i-y_i)\log{1-p(y_i \vert x_i,\hat{\beta})}\right), -\] -!et -where we had defined the logistic (sigmoid) function -!bt -\[ -p(y_i =1\vert x_i,\hat{\beta})=\frac{\exp{(\beta_0+\beta_1 x_i)}}{1+\exp{(\beta_0+\beta_1 x_i)}}, -\] -!et -and -!bt -\[ -p(y_i =0\vert x_i,\hat{\beta})=1-p(y_i =1\vert x_i,\hat{\beta}). -\] -!et -The parameters $\hat{\beta}$ were defined using a minimization method like gradient descent or Newton-Raphson's method. - -Now we replace $x_i$ with the activation $z_i^l$ for a given layer $l$ and the outputs as $y_i=a_i^l=f(z_i^l)$, with $z_i^l$ now being a function of the weights $w_{ij}^l$ and biases $b_i^l$. -We have then -!bt -\[ -a_i^l = y_i = \frac{\exp{(z_i^l)}}{1+\exp{(z_i^l)}}, -\] -!et -with -!bt -\[ -z_i^l = \sum_{j}w_{ij}^l a_j^{l-1}+b_i^l, -\] -!et -where the superscript $l-1$ indicates that these are the outputs from layer $l-1$. -Our cost function at the final layer $l=L$ is now -!bt -\[ -\mathcal{C}(\hat{W}) = - \sum_{i=1}^n \left(t_i\log{a_i^L}+(i-t_i)\log{(1-a_i^L)}\right), -\] -!et -where we have defined the targets $t_i$. The derivatives of the cost function with respect to the output $a_i^L$ are then easily calculated and we get -!bt -\[ -\frac{\partial \mathcal{C}(\hat{W})}{\partial a_i^L} = \frac{a_i^L-t_i}{a_i^L(1-a_i^L)}. -\] -!et -In case we use another activation function than the logistic one, we need to evaluate other derivatives. - - - -===== The Softmax function ===== -In case we employ the more general case given by the Softmax equation, we need to evaluate the derivative of the activation function with respect to the activation $z_i^l$, that is we need -!bt -\[ -\frac{\partial f(z_i^l)}{\partial w_{jk}^l} = -\frac{\partial f(z_i^l)}{\partial z_j^l} \frac{\partial z_j^l}{\partial w_{jk}^l}= \frac{\partial f(z_i^l)}{\partial z_j^l}a_k^{l-1}. -\] -!et -For the Softmax function we have -!bt -\[ -f(z_i^l) = \frac{\exp{(z_i^l)}}{\sum_{m=1}^K\exp{(z_m^l)}}. -\] -!et -Its derivative with respect to $z_j^l$ gives -!bt -\[ -\frac{\partial f(z_i^l)}{\partial z_j^l}= f(z_i^l)\left(\delta_{ij}-f(z_j^l)\right), -\] -!et -which in case of the simply binary model reduces to having $i=j$. - - -===== Developing a code for doing neural networks with back propagation ===== - - -One can identify a set of key steps when using neural networks to solve supervised learning problems: - -o Collect and pre-process data -o Define model and architecture -o Choose cost function and optimizer -o Train the model -o Evaluate model performance on test data -o Adjust hyperparameters (if necessary, network architecture) - - -===== Collect and pre-process data ===== - -Here we will be using the MNIST dataset, which is readily available through the _scikit-learn_ -package. You may also find it for example "here":"http://yann.lecun.com/exdb/mnist/". -The *MNIST* (Modified National Institute of Standards and Technology) database is a large database -of handwritten digits that is commonly used for training various image processing systems. -The MNIST dataset consists of 70 000 images of size 28x28 pixels, each labeled from 0 to 9. -The scikit-learn dataset we will use consists of a selection of 1797 images of size $8\times 8$ collected and processed from this database. - -To feed data into a feed-forward neural network we need to represent -the inputs as a feature matrix $X = (n_{inputs}, n_{features})$. Each -row represents an *input*, in this case a handwritten digit, and -each column represents a *feature*, in this case a pixel. The -correct answers, also known as *labels* or *targets* are -represented as a 1D array of integers -$Y = (n_{inputs}) = (5, 3, 1, 8,...)$. - -As an example, say we want to build a neural network using supervised learning to predict Body-Mass Index (BMI) from -measurements of height (in m) -and weight (in kg). If we have measurements of 5 people the feature matrix could be for example: - -$$ X = \begin{bmatrix} -1.85 & 81\\ -1.71 & 65\\ -1.95 & 103\\ -1.55 & 42\\ -1.63 & 56 -\end{bmatrix} ,$$ - -and the targets would be: - -$$ Y = (23.7, 22.2, 27.1, 17.5, 21.1) $$ - -Since each input image is a 2D matrix, we need to flatten the image -(i.e. "unravel" the 2D matrix into a 1D array) to turn the data into a -feature matrix. This means we lose all spatial information in the -image, such as locality and translational invariance. More complicated -architectures such as Convolutional Neural Networks can take advantage -of such information, and are most commonly applied when analyzing -images. - - -!bc pycod -# import necessary packages -import numpy as np -import matplotlib.pyplot as plt -from sklearn import datasets - - -# ensure the same random numbers appear every time -np.random.seed(0) - -# display images in notebook -%matplotlib inline -plt.rcParams['figure.figsize'] = (12,12) - - -# download MNIST dataset -digits = datasets.load_digits() - -# define inputs and labels -inputs = digits.images -labels = digits.target - -print("inputs = (n_inputs, pixel_width, pixel_height) = " + str(inputs.shape)) -print("labels = (n_inputs) = " + str(labels.shape)) - - -# flatten the image -# the value -1 means dimension is inferred from the remaining dimensions: 8x8 = 64 -n_inputs = len(inputs) -inputs = inputs.reshape(n_inputs, -1) -print("X = (n_inputs, n_features) = " + str(inputs.shape)) - - -# choose some random images to display -indices = np.arange(n_inputs) -random_indices = np.random.choice(indices, size=5) - -for i, image in enumerate(digits.images[random_indices]): - plt.subplot(1, 5, i+1) - plt.axis('off') - plt.imshow(image, cmap=plt.cm.gray_r, interpolation='nearest') - plt.title("Label: %d" % digits.target[random_indices[i]]) -plt.show() -!ec - - -===== Train and test datasets ===== - -Performing analysis before partitioning the dataset is a major error, that can lead to incorrect conclusions. - -We will reserve $80 \%$ of our dataset for training and $20 \%$ for testing. - -It is important that the train and test datasets are drawn randomly from our dataset, to ensure -no bias in the sampling. -Say you are taking measurements of weather data to predict the weather in the coming 5 days. -You don't want to train your model on measurements taken from the hours 00.00 to 12.00, and then test it on data -collected from 12.00 to 24.00. - - -!bc pycod -from sklearn.model_selection import train_test_split - -# one-liner from scikit-learn library -train_size = 0.8 -test_size = 1 - train_size -X_train, X_test, Y_train, Y_test = train_test_split(inputs, labels, train_size=train_size, - test_size=test_size) - -# equivalently in numpy -def train_test_split_numpy(inputs, labels, train_size, test_size): - n_inputs = len(inputs) - inputs_shuffled = inputs.copy() - labels_shuffled = labels.copy() - - np.random.shuffle(inputs_shuffled) - np.random.shuffle(labels_shuffled) - - train_end = int(n_inputs*train_size) - X_train, X_test = inputs_shuffled[:train_end], inputs_shuffled[train_end:] - Y_train, Y_test = labels_shuffled[:train_end], labels_shuffled[train_end:] - - return X_train, X_test, Y_train, Y_test - -#X_train, X_test, Y_train, Y_test = train_test_split_numpy(inputs, labels, train_size, test_size) - -print("Number of training images: " + str(len(X_train))) -print("Number of test images: " + str(len(X_test))) -!ec - - -===== Define model and architecture ===== - -Our simple feed-forward neural network will consist of an *input* layer, a single *hidden* layer and an *output* layer. The activation $y$ of each neuron is a weighted sum of inputs, passed through an activation function. In case of the simple perceptron model we have - -$$ z = \sum_{i=1}^n w_i a_i ,$$ - -$$ y = f(z) ,$$ - -where $f$ is the activation function, $a_i$ represents input from neuron $i$ in the preceding layer -and $w_i$ is the weight to input $i$. -The activation of the neurons in the input layer is just the features (e.g. a pixel value). - -The simplest activation function for a neuron is the *Heaviside* function: - -$$ f(z) = -\begin{cases} -1, & z > 0\\ -0, & \text{otherwise} -\end{cases} -$$ - -A feed-forward neural network with this activation is known as a *perceptron*. -For a binary classifier (i.e. two classes, 0 or 1, dog or not-dog) we can also use this in our output layer. -This activation can be generalized to $k$ classes (using e.g. the *one-against-all* strategy), -and we call these architectures *multiclass perceptrons*. - -However, it is now common to use the terms Single Layer Perceptron (SLP) (1 hidden layer) and -Multilayer Perceptron (MLP) (2 or more hidden layers) to refer to feed-forward neural networks with any activation function. - -Typical choices for activation functions include the sigmoid function, hyperbolic tangent, and Rectified Linear Unit (ReLU). -We will be using the sigmoid function $\sigma(x)$: - -$$ f(x) = \sigma(x) = \frac{1}{1 + e^{-x}} ,$$ - -which is inspired by probability theory (see logistic regression) and was most commonly used until about 2011. See the discussion below concerning other activation functions. - - -===== Layers ===== - -* Input -Since each input image has 8x8 = 64 pixels or features, we have an input layer of 64 neurons. - -* Hidden layer -We will use 50 neurons in the hidden layer receiving input from the neurons in the input layer. -Since each neuron in the hidden layer is connected to the 64 inputs we have 64x50 = 3200 weights to the hidden layer. - -* Output -If we were building a binary classifier, it would be sufficient with a single neuron in the output layer, -which could output 0 or 1 according to the Heaviside function. This would be an example of a *hard* classifier, meaning it outputs the class of the input directly. However, if we are dealing with noisy data it is often beneficial to use a *soft* classifier, which outputs the probability of being in class 0 or 1. - -For a soft binary classifier, we could use a single neuron and interpret the output as either being the probability of being in class 0 or the probability of being in class 1. Alternatively we could use 2 neurons, and interpret each neuron as the probability of being in each class. - -Since we are doing multiclass classification, with 10 categories, it is natural to use 10 neurons in the output layer. We number the neurons $j = 0,1,...,9$. The activation of each output neuron $j$ will be according to the *softmax* function: - -$$ P(\text{class $j$} \mid \text{input $\hat{a}$}) = \frac{\exp{(\hat{a}^T \hat{w}_j)}} -{\sum_{c=0}^{9} \exp{(\hat{a}^T \hat{w}_c)}} ,$$ - -i.e. each neuron $j$ outputs the probability of being in class $j$ given an input from the hidden layer $\hat{a}$, with $\hat{w}_j$ the weights of neuron $j$ to the inputs. -The denominator is a normalization factor to ensure the outputs (probabilities) sum up to 1. -The exponent is just the weighted sum of inputs as before: - -$$ z_j = \sum_{i=1}^n w_ {ij} a_i+b_j.$$ - -Since each neuron in the output layer is connected to the 50 inputs from the hidden layer we have 50x10 = 500 -weights to the output layer. - - -===== Weights and biases ===== - -Typically weights are initialized with small values distributed around zero, drawn from a uniform -or normal distribution. Setting all weights to zero means all neurons give the same output, making the network useless. - -Adding a bias value to the weighted sum of inputs allows the neural network to represent a greater range -of values. Without it, any input with the value 0 will be mapped to zero (before being passed through the activation). The bias unit has an output of 1, and a weight to each neuron $j$, $b_j$: - -$$ z_j = \sum_{i=1}^n w_ {ij} a_i + b_j.$$ - -The bias weights $\hat{b}$ are often initialized to zero, but a small value like $0.01$ ensures all neurons have some output which can be backpropagated in the first training cycle. -!bc pycod -# building our neural network - -n_inputs, n_features = X_train.shape -n_hidden_neurons = 50 -n_categories = 10 - -# we make the weights normally distributed using numpy.random.randn - -# weights and bias in the hidden layer -hidden_weights = np.random.randn(n_features, n_hidden_neurons) -hidden_bias = np.zeros(n_hidden_neurons) + 0.01 - -# weights and bias in the output layer -output_weights = np.random.randn(n_hidden_neurons, n_categories) -output_bias = np.zeros(n_categories) + 0.01 -!ec - - -===== Feed-forward pass ===== - -Denote $F$ the number of features, $H$ the number of hidden neurons and $C$ the number of categories. -For each input image we calculate a weighted sum of input features (pixel values) to each neuron $j$ in the hidden layer $l$: - -$$ z_{j}^{l} = \sum_{i=1}^{F} w_{ij}^{l} x_i + b_{j}^{l},$$ - -this is then passed through our activation function - -$$ a_{j}^{l} = f(z_{j}^{l}) .$$ - -We calculate a weighted sum of inputs (activations in the hidden layer) to each neuron $j$ in the output layer: - -$$ z_{j}^{L} = \sum_{i=1}^{H} w_{ij}^{L} a_{i}^{l} + b_{j}^{L}.$$ - -Finally we calculate the output of neuron $j$ in the output layer using the softmax function: - -$$ a_{j}^{L} = \frac{\exp{(z_j^{L})}} -{\sum_{c=0}^{C-1} \exp{(z_c^{L})}} .$$ - - -===== Matrix multiplications ===== - -Since our data has the dimensions $X = (n_{inputs}, n_{features})$ and our weights to the hidden -layer have the dimensions -$W_{hidden} = (n_{features}, n_{hidden})$, -we can easily feed the network all our training data in one go by taking the matrix product - -$$ X W^{h} = (n_{inputs}, n_{hidden}),$$ - -and obtain a matrix that holds the weighted sum of inputs to the hidden layer -for each input image and each hidden neuron. -We also add the bias to obtain a matrix of weighted sums to the hidden layer $Z^{h}$: - -$$ \hat{z}^{l} = \hat{X} \hat{W}^{l} + \hat{b}^{l} ,$$ - -meaning the same bias (1D array with size equal number of hidden neurons) is added to each input image. -This is then passed through the activation: - -$$ \hat{a}^{l} = f(\hat{z}^l) .$$ - -This is fed to the output layer: - -$$ \hat{z}^{L} = \hat{a}^{L} \hat{W}^{L} + \hat{b}^{L} .$$ - -Finally we receive our output values for each image and each category by passing it through the softmax function: - -$$ output = softmax (\hat{z}^{L}) = (n_{inputs}, n_{categories}) .$$ - - -!bc pycod -# setup the feed-forward pass, subscript h = hidden layer - -def sigmoid(x): - return 1/(1 + np.exp(-x)) - -def feed_forward(X): - # weighted sum of inputs to the hidden layer - z_h = np.matmul(X, hidden_weights) + hidden_bias - # activation in the hidden layer - a_h = sigmoid(z_h) - - # weighted sum of inputs to the output layer - z_o = np.matmul(a_h, output_weights) + output_bias - # softmax output - # axis 0 holds each input and axis 1 the probabilities of each category - exp_term = np.exp(z_o) - probabilities = exp_term / np.sum(exp_term, axis=1, keepdims=True) - - return probabilities - -probabilities = feed_forward(X_train) -print("probabilities = (n_inputs, n_categories) = " + str(probabilities.shape)) -print("probability that image 0 is in category 0,1,2,...,9 = \n" + str(probabilities[0])) -print("probabilities sum up to: " + str(probabilities[0].sum())) -print() - -# we obtain a prediction by taking the class with the highest likelihood -def predict(X): - probabilities = feed_forward(X) - return np.argmax(probabilities, axis=1) - -predictions = predict(X_train) -print("predictions = (n_inputs) = " + str(predictions.shape)) -print("prediction for image 0: " + str(predictions[0])) -print("correct label for image 0: " + str(Y_train[0])) -!ec - - -===== Choose cost function and optimizer ===== - -To measure how well our neural network is doing we need to introduce a cost function. -We will call the function that gives the error of a single sample output the *loss* function, and the function -that gives the total error of our network across all samples the *cost* function. -A typical choice for multiclass classification is the *cross-entropy* loss, also known as the negative log likelihood. - -In *multiclass* classification it is common to treat each integer label as a so called *one-hot* vector: - -$$ y = 5 \quad \rightarrow \quad \hat{y} = (0, 0, 0, 0, 0, 1, 0, 0, 0, 0) ,$$ - - -$$ y = 1 \quad \rightarrow \quad \hat{y} = (0, 1, 0, 0, 0, 0, 0, 0, 0, 0) ,$$ - - -i.e. a binary bit string of length $C$, where $C = 10$ is the number of classes in the MNIST dataset. - -Let $y_{ic}$ denote the $c$-th component of the $i$-th one-hot vector. -We define the cost function $\mathcal{C}$ as a sum over the cross-entropy loss for each point $\hat{x}_i$ in the dataset. - -In the one-hot representation only one of the terms in the loss function is non-zero, namely the -probability of the correct category $c'$ -(i.e. the category $c'$ such that $y_{ic'} = 1$). This means that the cross entropy loss only punishes you for how wrong -you got the correct label. The probability of category $c$ is given by the softmax function. The vector $\hat{\theta}$ represents the parameters of our network, i.e. all the weights and biases. - - - -===== Optimizing the cost function ===== - -The network is trained by finding the weights and biases that minimize the cost function. One of the most widely used classes of methods is *gradient descent* and its generalizations. The idea behind gradient descent -is simply to adjust the weights in the direction where the gradient of the cost function is large and negative. This ensures we flow toward a *local* minimum of the cost function. -Each parameter $\theta$ is iteratively adjusted according to the rule - -$$ \theta_{i+1} = \theta_i - \eta \nabla \mathcal{C}(\theta_i) ,$$ - -where $\eta$ is known as the *learning rate*, which controls how big a step we take towards the minimum. -This update can be repeated for any number of iterations, or until we are satisfied with the result. - -A simple and effective improvement is a variant called *Batch Gradient Descent*. -Instead of calculating the gradient on the whole dataset, we calculate an approximation of the gradient -on a subset of the data called a *minibatch*. -If there are $N$ data points and we have a minibatch size of $M$, the total number of batches -is $N/M$. -We denote each minibatch $B_k$, with $k = 1, 2,...,N/M$. The gradient then becomes: - -$$ \nabla \mathcal{C}(\theta) = \frac{1}{N} \sum_{i=1}^N \nabla \mathcal{L}_i(\theta) \quad \rightarrow \quad -\frac{1}{M} \sum_{i \in B_k} \nabla \mathcal{L}_i(\theta) ,$$ - -i.e. instead of averaging the loss over the entire dataset, we average over a minibatch. - -This has two important benefits: -o Introducing stochasticity decreases the chance that the algorithm becomes stuck in a local minima. -o It significantly speeds up the calculation, since we do not have to use the entire dataset to calculate the gradient. - -The various optmization methods, with codes and algorithms, are discussed in our lectures on "Gradient descent approaches":"https://compphysics.github.io/MachineLearning/doc/pub/Splines/html/Splines-bs.html". - - -===== Regularization ===== - -It is common to add an extra term to the cost function, proportional -to the size of the weights. This is equivalent to constraining the -size of the weights, so that they do not grow out of control. -Constraining the size of the weights means that the weights cannot -grow arbitrarily large to fit the training data, and in this way -reduces *overfitting*. - -We will measure the size of the weights using the so called *L2-norm*, meaning our cost function becomes: - -$$ \nabla \mathcal{C}(\theta) = \frac{1}{N} \sum_{i=1}^N \nabla \mathcal{L}_i(\theta) \quad \rightarrow \quad -\frac{1}{N} \sum_{i=1}^N \nabla \mathcal{L}_i(\theta) + \lambda \lvert \lvert \hat{w} \rvert \rvert_2^2 -= \frac{1}{N} \sum_{i=1}^N \nabla \mathcal{L}(\theta) + \lambda \sum_{ij} w_{ij}^2,$$ - -i.e. we sum up all the weights squared. The factor $\lambda$ is known as a regularization parameter. - - -In order to train the model, we need to calculate the derivative of -the cost function with respect to every bias and weight in the -network. In total our network has $(64 + 1)\times 50=3250$ weights in -the hidden layer and $(50 + 1)\times 10=510$ weights to the output -layer ($+1$ for the bias), and the gradient must be calculated for -every parameter. We use the *backpropagation* algorithm discussed -above. This is a clever use of the chain rule that allows us to -calculate the gradient efficently. - - - -===== Matrix multiplication ===== - -To more efficently train our network these equations are implemented using matrix operations. -The error in the output layer is calculated simply as, with $\hat{t}$ being our targets, - -$$ \delta_L = \hat{t} - \hat{y} = (n_{inputs}, n_{categories}) .$$ - -The gradient for the output weights is calculated as - -$$ \nabla W_{L} = \hat{a}^T \delta_L = (n_{hidden}, n_{categories}) ,$$ - -where $\hat{a} = (n_{inputs}, n_{hidden})$. This simply means that we are summing up the gradients for each input. -Since we are going backwards we have to transpose the activation matrix. - -The gradient with respect to the output bias is then - -$$ \nabla \hat{b}_{L} = \sum_{i=1}^{n_{inputs}} \delta_L = (n_{categories}) .$$ - -The error in the hidden layer is - -$$ \Delta_h = \delta_L W_{L}^T \circ f'(z_{h}) = \delta_L W_{L}^T \circ a_{h} \circ (1 - a_{h}) = (n_{inputs}, n_{hidden}) ,$$ - -where $f'(a_{h})$ is the derivative of the activation in the hidden layer. The matrix products mean -that we are summing up the products for each neuron in the output layer. The symbol $\circ$ denotes -the *Hadamard product*, meaning element-wise multiplication. - -This again gives us the gradients in the hidden layer: - -$$ \nabla W_{h} = X^T \delta_h = (n_{features}, n_{hidden}) ,$$ - -$$ \nabla b_{h} = \sum_{i=1}^{n_{inputs}} \delta_h = (n_{hidden}) .$$ - - -!bc pycod -# to categorical turns our integer vector into a onehot representation -from sklearn.metrics import accuracy_score - -# one-hot in numpy -def to_categorical_numpy(integer_vector): - n_inputs = len(integer_vector) - n_categories = np.max(integer_vector) + 1 - onehot_vector = np.zeros((n_inputs, n_categories)) - onehot_vector[range(n_inputs), integer_vector] = 1 - - return onehot_vector - -#Y_train_onehot, Y_test_onehot = to_categorical(Y_train), to_categorical(Y_test) -Y_train_onehot, Y_test_onehot = to_categorical_numpy(Y_train), to_categorical_numpy(Y_test) - -def feed_forward_train(X): - # weighted sum of inputs to the hidden layer - z_h = np.matmul(X, hidden_weights) + hidden_bias - # activation in the hidden layer - a_h = sigmoid(z_h) - - # weighted sum of inputs to the output layer - z_o = np.matmul(a_h, output_weights) + output_bias - # softmax output - # axis 0 holds each input and axis 1 the probabilities of each category - exp_term = np.exp(z_o) - probabilities = exp_term / np.sum(exp_term, axis=1, keepdims=True) - - # for backpropagation need activations in hidden and output layers - return a_h, probabilities - -def backpropagation(X, Y): - a_h, probabilities = feed_forward_train(X) - - # error in the output layer - error_output = probabilities - Y - # error in the hidden layer - error_hidden = np.matmul(error_output, output_weights.T) * a_h * (1 - a_h) - - # gradients for the output layer - output_weights_gradient = np.matmul(a_h.T, error_output) - output_bias_gradient = np.sum(error_output, axis=0) - - # gradient for the hidden layer - hidden_weights_gradient = np.matmul(X.T, error_hidden) - hidden_bias_gradient = np.sum(error_hidden, axis=0) - - return output_weights_gradient, output_bias_gradient, hidden_weights_gradient, hidden_bias_gradient - -print("Old accuracy on training data: " + str(accuracy_score(predict(X_train), Y_train))) - -eta = 0.01 -lmbd = 0.01 -for i in range(1000): - # calculate gradients - dWo, dBo, dWh, dBh = backpropagation(X_train, Y_train_onehot) - - # regularization term gradients - dWo += lmbd * output_weights - dWh += lmbd * hidden_weights - - # update weights and biases - output_weights -= eta * dWo - output_bias -= eta * dBo - hidden_weights -= eta * dWh - hidden_bias -= eta * dBh - -print("New accuracy on training data: " + str(accuracy_score(predict(X_train), Y_train))) -!ec - - -===== Improving performance ===== - -As we can see the network does not seem to be learning at all. It seems to be just guessing the label for each image. -In order to obtain a network that does something useful, we will have to do a bit more work. - -The choice of *hyperparameters* such as learning rate and regularization parameter is hugely influential for the performance of the network. Typically a *grid-search* is performed, wherein we test different hyperparameters separated by orders of magnitude. For example we could test the learning rates $\eta = 10^{-6}, 10^{-5},...,10^{-1}$ with different regularization parameters $\lambda = 10^{-6},...,10^{-0}$. - -Next, we haven't implemented minibatching yet, which introduces stochasticity and is though to act as an important regularizer on the weights. We call a feed-forward + backward pass with a minibatch an *iteration*, and a full training period -going through the entire dataset ($n/M$ batches) an *epoch*. - -If this does not improve network performance, you may want to consider altering the network architecture, adding more neurons or hidden layers. -Andrew Ng goes through some of these considerations in this "video":"https://youtu.be/F1ka6a13S9I". You can find a summary of the video "here":"https://kevinzakka.github.io/2016/09/26/applying-deep-learning/". - - -===== Full object-oriented implementation ===== - -It is very natural to think of the network as an object, with specific instances of the network -being realizations of this object with different hyperparameters. An implementation using Python classes provides a clean structure and interface, and the full implementation of our neural network is given below. - - -!bc pycod -class NeuralNetwork: - def __init__( - self, - X_data, - Y_data, - n_hidden_neurons=50, - n_categories=10, - epochs=10, - batch_size=100, - eta=0.1, - lmbd=0.0, - - ): - self.X_data_full = X_data - self.Y_data_full = Y_data - - self.n_inputs = X_data.shape[0] - self.n_features = X_data.shape[1] - self.n_hidden_neurons = n_hidden_neurons - self.n_categories = n_categories - - self.epochs = epochs - self.batch_size = batch_size - self.iterations = self.n_inputs // self.batch_size - self.eta = eta - self.lmbd = lmbd - - self.create_biases_and_weights() - - def create_biases_and_weights(self): - self.hidden_weights = np.random.randn(self.n_features, self.n_hidden_neurons) - self.hidden_bias = np.zeros(self.n_hidden_neurons) + 0.01 - - self.output_weights = np.random.randn(self.n_hidden_neurons, self.n_categories) - self.output_bias = np.zeros(self.n_categories) + 0.01 - - def feed_forward(self): - # feed-forward for training - self.z_h = np.matmul(self.X_data, self.hidden_weights) + self.hidden_bias - self.a_h = sigmoid(self.z_h) - - self.z_o = np.matmul(self.a_h, self.output_weights) + self.output_bias - - exp_term = np.exp(self.z_o) - self.probabilities = exp_term / np.sum(exp_term, axis=1, keepdims=True) - - def feed_forward_out(self, X): - # feed-forward for output - z_h = np.matmul(X, self.hidden_weights) + self.hidden_bias - a_h = sigmoid(z_h) - - z_o = np.matmul(a_h, self.output_weights) + self.output_bias - - exp_term = np.exp(z_o) - probabilities = exp_term / np.sum(exp_term, axis=1, keepdims=True) - return probabilities - - def backpropagation(self): - error_output = self.probabilities - self.Y_data - error_hidden = np.matmul(error_output, self.output_weights.T) * self.a_h * (1 - self.a_h) - - self.output_weights_gradient = np.matmul(self.a_h.T, error_output) - self.output_bias_gradient = np.sum(error_output, axis=0) - - self.hidden_weights_gradient = np.matmul(self.X_data.T, error_hidden) - self.hidden_bias_gradient = np.sum(error_hidden, axis=0) - - if self.lmbd > 0.0: - self.output_weights_gradient += self.lmbd * self.output_weights - self.hidden_weights_gradient += self.lmbd * self.hidden_weights - - self.output_weights -= self.eta * self.output_weights_gradient - self.output_bias -= self.eta * self.output_bias_gradient - self.hidden_weights -= self.eta * self.hidden_weights_gradient - self.hidden_bias -= self.eta * self.hidden_bias_gradient - - def predict(self, X): - probabilities = self.feed_forward_out(X) - return np.argmax(probabilities, axis=1) - - def predict_probabilities(self, X): - probabilities = self.feed_forward_out(X) - return probabilities - - def train(self): - data_indices = np.arange(self.n_inputs) - - for i in range(self.epochs): - for j in range(self.iterations): - # pick datapoints with replacement - chosen_datapoints = np.random.choice( - data_indices, size=self.batch_size, replace=False - ) - - # minibatch training data - self.X_data = self.X_data_full[chosen_datapoints] - self.Y_data = self.Y_data_full[chosen_datapoints] - - self.feed_forward() - self.backpropagation() -!ec - - -===== Evaluate model performance on test data ===== - -To measure the performance of our network we evaluate how well it does it data it has never seen before, i.e. the test data. -We measure the performance of the network using the *accuracy* score. -The accuracy is as you would expect just the number of images correctly labeled divided by the total number of images. A perfect classifier will have an accuracy score of $1$. - -$$ \text{Accuracy} = \frac{\sum_{i=1}^n I(\hat{y}_i = y_i)}{n} ,$$ - -where $I$ is the indicator function, $1$ if $\hat{y}_i = y_i$ and $0$ otherwise. - - -!bc pycod -epochs = 100 -batch_size = 100 - -dnn = NeuralNetwork(X_train, Y_train_onehot, eta=eta, lmbd=lmbd, epochs=epochs, batch_size=batch_size, - n_hidden_neurons=n_hidden_neurons, n_categories=n_categories) -dnn.train() -test_predict = dnn.predict(X_test) - -# accuracy score from scikit library -print("Accuracy score on test set: ", accuracy_score(Y_test, test_predict)) - -# equivalent in numpy -def accuracy_score_numpy(Y_test, Y_pred): - return np.sum(Y_test == Y_pred) / len(Y_test) - -#print("Accuracy score on test set: ", accuracy_score_numpy(Y_test, test_predict)) -!ec - - -===== Adjust hyperparameters ===== - -We now perform a grid search to find the optimal hyperparameters for the network. -Note that we are only using 1 layer with 50 neurons, and human performance is estimated to be around $98\%$ ($2\%$ error rate). - -!bc pycod -eta_vals = np.logspace(-5, 1, 7) -lmbd_vals = np.logspace(-5, 1, 7) -# store the models for later use -DNN_numpy = np.zeros((len(eta_vals), len(lmbd_vals)), dtype=object) - -# grid search -for i, eta in enumerate(eta_vals): - for j, lmbd in enumerate(lmbd_vals): - dnn = NeuralNetwork(X_train, Y_train_onehot, eta=eta, lmbd=lmbd, epochs=epochs, batch_size=batch_size, - n_hidden_neurons=n_hidden_neurons, n_categories=n_categories) - dnn.train() - - DNN_numpy[i][j] = dnn - - test_predict = dnn.predict(X_test) - - print("Learning rate = ", eta) - print("Lambda = ", lmbd) - print("Accuracy score on test set: ", accuracy_score(Y_test, test_predict)) - print() -!ec - - -===== Visualization ===== - -!bc pycod -# visual representation of grid search -# uses seaborn heatmap, you can also do this with matplotlib imshow -import seaborn as sns - -sns.set() - -train_accuracy = np.zeros((len(eta_vals), len(lmbd_vals))) -test_accuracy = np.zeros((len(eta_vals), len(lmbd_vals))) - -for i in range(len(eta_vals)): - for j in range(len(lmbd_vals)): - dnn = DNN_numpy[i][j] - - train_pred = dnn.predict(X_train) - test_pred = dnn.predict(X_test) - - train_accuracy[i][j] = accuracy_score(Y_train, train_pred) - test_accuracy[i][j] = accuracy_score(Y_test, test_pred) - - -fig, ax = plt.subplots(figsize = (10, 10)) -sns.heatmap(train_accuracy, annot=True, ax=ax, cmap="viridis") -ax.set_title("Training Accuracy") -ax.set_ylabel("$\eta$") -ax.set_xlabel("$\lambda$") -plt.show() - -fig, ax = plt.subplots(figsize = (10, 10)) -sns.heatmap(test_accuracy, annot=True, ax=ax, cmap="viridis") -ax.set_title("Test Accuracy") -ax.set_ylabel("$\eta$") -ax.set_xlabel("$\lambda$") -plt.show() -!ec - - -===== scikit-learn implementation ===== - -_scikit-learn_ focuses more -on traditional machine learning methods, such as regression, -clustering, decision trees, etc. As such, it has only two types of -neural networks: Multi Layer Perceptron outputting continuous values, -*MPLRegressor*, and Multi Layer Perceptron outputting labels, -*MLPClassifier*. We will see how simple it is to use these classes. - -_scikit-learn_ implements a few improvements from our neural network, -such as early stopping, a varying learning rate, different -optimization methods, etc. We would therefore expect a better -performance overall. - -!bc pycod -from sklearn.neural_network import MLPClassifier -# store models for later use -DNN_scikit = np.zeros((len(eta_vals), len(lmbd_vals)), dtype=object) - -for i, eta in enumerate(eta_vals): - for j, lmbd in enumerate(lmbd_vals): - dnn = MLPClassifier(hidden_layer_sizes=(n_hidden_neurons), activation='logistic', - alpha=lmbd, learning_rate_init=eta, max_iter=epochs) - dnn.fit(X_train, Y_train) - - DNN_scikit[i][j] = dnn - - print("Learning rate = ", eta) - print("Lambda = ", lmbd) - print("Accuracy score on test set: ", dnn.score(X_test, Y_test)) - print() -!ec - - - -===== Visualization ===== -!bc pycod -# optional -# visual representation of grid search -# uses seaborn heatmap, could probably do this in matplotlib -import seaborn as sns - -sns.set() - -train_accuracy = np.zeros((len(eta_vals), len(lmbd_vals))) -test_accuracy = np.zeros((len(eta_vals), len(lmbd_vals))) - -for i in range(len(eta_vals)): - for j in range(len(lmbd_vals)): - dnn = DNN_scikit[i][j] - - train_pred = dnn.predict(X_train) - test_pred = dnn.predict(X_test) - - train_accuracy[i][j] = accuracy_score(Y_train, train_pred) - test_accuracy[i][j] = accuracy_score(Y_test, test_pred) - - -fig, ax = plt.subplots(figsize = (10, 10)) -sns.heatmap(train_accuracy, annot=True, ax=ax, cmap="viridis") -ax.set_title("Training Accuracy") -ax.set_ylabel("$\eta$") -ax.set_xlabel("$\lambda$") -plt.show() - -fig, ax = plt.subplots(figsize = (10, 10)) -sns.heatmap(test_accuracy, annot=True, ax=ax, cmap="viridis") -ax.set_title("Test Accuracy") -ax.set_ylabel("$\eta$") -ax.set_xlabel("$\lambda$") -plt.show() -!ec - - - -===== Building neural networks in Tensorflow and Keras ===== - -Now we want to build on the experience gained from our neural network implementation in NumPy and scikit-learn -and use it to construct a neural network in Tensorflow. Once we have constructed a neural network in NumPy -and Tensorflow, building one in Keras is really quite trivial, though the performance may suffer. - -In our previous example we used only one hidden layer, and in this we will use two. From this it should be quite -clear how to build one using an arbitrary number of hidden layers, using data structures such as Python lists or -NumPy arrays. - - -===== Tensorflow ===== - -Tensorflow is an open source library machine learning library -developed by the Google Brain team for internal use. It was released -under the Apache 2.0 open source license in November 9, 2015. - -Tensorflow is a computational framework that allows you to construct -machine learning models at different levels of abstraction, from -high-level, object-oriented APIs like Keras, down to the C++ kernels -that Tensorflow is built upon. The higher levels of abstraction are -simpler to use, but less flexible, and our choice of implementation -should reflect the problems we are trying to solve. - -"Tensorflow uses":"https://www.tensorflow.org/guide/graphs" so-called graphs to represent your computation -in terms of the dependencies between individual operations, such that you first build a Tensorflow *graph* -to represent your model, and then create a Tensorflow *session* to run the graph. - -In this guide we will analyze the same data as we did in our NumPy and -scikit-learn tutorial, gathered from the MNIST database of images. We -will give an introduction to the lower level Python Application -Program Interfaces (APIs), and see how we use them to build our graph. -Then we will build (effectively) the same graph in Keras, to see just -how simple solving a machine learning problem can be. - -To install tensorflow on Unix/Linux systems, use pip as -!bc pycod -pip3 install tensorflow -!ec -and/or if you use _anaconda_, just write (or install from the graphical user interface) -!bc pycod -conda install tensorflow -!ec - - -===== Collect and pre-process data ===== - -!bc pycod -# import necessary packages -import numpy as np -import matplotlib.pyplot as plt -from sklearn import datasets - - -# ensure the same random numbers appear every time -np.random.seed(0) - -# display images in notebook -%matplotlib inline -plt.rcParams['figure.figsize'] = (12,12) - - -# download MNIST dataset -digits = datasets.load_digits() - -# define inputs and labels -inputs = digits.images -labels = digits.target - -print("inputs = (n_inputs, pixel_width, pixel_height) = " + str(inputs.shape)) -print("labels = (n_inputs) = " + str(labels.shape)) - - -# flatten the image -# the value -1 means dimension is inferred from the remaining dimensions: 8x8 = 64 -n_inputs = len(inputs) -inputs = inputs.reshape(n_inputs, -1) -print("X = (n_inputs, n_features) = " + str(inputs.shape)) - - -# choose some random images to display -indices = np.arange(n_inputs) -random_indices = np.random.choice(indices, size=5) - -for i, image in enumerate(digits.images[random_indices]): - plt.subplot(1, 5, i+1) - plt.axis('off') - plt.imshow(image, cmap=plt.cm.gray_r, interpolation='nearest') - plt.title("Label: %d" % digits.target[random_indices[i]]) -plt.show() -!ec - -!bc pycod -from keras.utils import to_categorical -from sklearn.model_selection import train_test_split - -# one-hot representation of labels -labels = to_categorical(labels) - -# split into train and test data -train_size = 0.8 -test_size = 1 - train_size -X_train, X_test, Y_train, Y_test = train_test_split(inputs, labels, train_size=train_size, - test_size=test_size) -!ec - - -===== Using TensorFlow backend ===== - -o Define model and architecture -o Choose cost function and optimizer - -!bc pycod -import tensorflow as tf - -class NeuralNetworkTensorflow: - def __init__( - self, - X_train, - Y_train, - X_test, - Y_test, - n_neurons_layer1=100, - n_neurons_layer2=50, - n_categories=2, - epochs=10, - batch_size=100, - eta=0.1, - lmbd=0.0, - ): - - # keep track of number of steps - self.global_step = tf.Variable(0, dtype=tf.int32, trainable=False, name='global_step') - - self.X_train = X_train - self.Y_train = Y_train - self.X_test = X_test - self.Y_test = Y_test - - self.n_inputs = X_train.shape[0] - self.n_features = X_train.shape[1] - self.n_neurons_layer1 = n_neurons_layer1 - self.n_neurons_layer2 = n_neurons_layer2 - self.n_categories = n_categories - - self.epochs = epochs - self.batch_size = batch_size - self.iterations = self.n_inputs // self.batch_size - self.eta = eta - self.lmbd = lmbd - - # build network piece by piece - # name scopes (with) are used to enforce creation of new variables - # https://www.tensorflow.org/guide/variables - self.create_placeholders() - self.create_DNN() - self.create_loss() - self.create_optimiser() - self.create_accuracy() - - def create_placeholders(self): - # placeholders are fine here, but "Datasets" are the preferred method - # of streaming data into a model - with tf.name_scope('data'): - self.X = tf.placeholder(tf.float32, shape=(None, self.n_features), name='X_data') - self.Y = tf.placeholder(tf.float32, shape=(None, self.n_categories), name='Y_data') - - def create_DNN(self): - with tf.name_scope('DNN'): - # the weights are stored to calculate regularization loss later - - # Fully connected layer 1 - self.W_fc1 = self.weight_variable([self.n_features, self.n_neurons_layer1], name='fc1', dtype=tf.float32) - b_fc1 = self.bias_variable([self.n_neurons_layer1], name='fc1', dtype=tf.float32) - a_fc1 = tf.nn.sigmoid(tf.matmul(self.X, self.W_fc1) + b_fc1) - - # Fully connected layer 2 - self.W_fc2 = self.weight_variable([self.n_neurons_layer1, self.n_neurons_layer2], name='fc2', dtype=tf.float32) - b_fc2 = self.bias_variable([self.n_neurons_layer2], name='fc2', dtype=tf.float32) - a_fc2 = tf.nn.sigmoid(tf.matmul(a_fc1, self.W_fc2) + b_fc2) - - # Output layer - self.W_out = self.weight_variable([self.n_neurons_layer2, self.n_categories], name='out', dtype=tf.float32) - b_out = self.bias_variable([self.n_categories], name='out', dtype=tf.float32) - self.z_out = tf.matmul(a_fc2, self.W_out) + b_out - - def create_loss(self): - with tf.name_scope('loss'): - softmax_loss = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits_v2(labels=self.Y, logits=self.z_out)) - - regularizer_loss_fc1 = tf.nn.l2_loss(self.W_fc1) - regularizer_loss_fc2 = tf.nn.l2_loss(self.W_fc2) - regularizer_loss_out = tf.nn.l2_loss(self.W_out) - regularizer_loss = self.lmbd*(regularizer_loss_fc1 + regularizer_loss_fc2 + regularizer_loss_out) - - self.loss = softmax_loss + regularizer_loss - - def create_accuracy(self): - with tf.name_scope('accuracy'): - probabilities = tf.nn.softmax(self.z_out) - predictions = tf.argmax(probabilities, axis=1) - labels = tf.argmax(self.Y, axis=1) - - correct_predictions = tf.equal(predictions, labels) - correct_predictions = tf.cast(correct_predictions, tf.float32) - self.accuracy = tf.reduce_mean(correct_predictions) - - def create_optimiser(self): - with tf.name_scope('optimizer'): - self.optimizer = tf.train.GradientDescentOptimizer(learning_rate=self.eta).minimize(self.loss, global_step=self.global_step) - - def weight_variable(self, shape, name='', dtype=tf.float32): - initial = tf.truncated_normal(shape, stddev=0.1) - return tf.Variable(initial, name=name, dtype=dtype) - - def bias_variable(self, shape, name='', dtype=tf.float32): - initial = tf.constant(0.1, shape=shape) - return tf.Variable(initial, name=name, dtype=dtype) - - def fit(self): - data_indices = np.arange(self.n_inputs) - - with tf.Session() as sess: - sess.run(tf.global_variables_initializer()) - for i in range(self.epochs): - for j in range(self.iterations): - chosen_datapoints = np.random.choice(data_indices, size=self.batch_size, replace=False) - batch_X, batch_Y = self.X_train[chosen_datapoints], self.Y_train[chosen_datapoints] - - sess.run([DNN.loss, DNN.optimizer], - feed_dict={DNN.X: batch_X, - DNN.Y: batch_Y}) - accuracy = sess.run(DNN.accuracy, - feed_dict={DNN.X: batch_X, - DNN.Y: batch_Y}) - step = sess.run(DNN.global_step) - - self.train_loss, self.train_accuracy = sess.run([DNN.loss, DNN.accuracy], - feed_dict={DNN.X: self.X_train, - DNN.Y: self.Y_train}) - - self.test_loss, self.test_accuracy = sess.run([DNN.loss, DNN.accuracy], - feed_dict={DNN.X: self.X_test, - DNN.Y: self.Y_test}) -!ec - - - -===== Optimizing and using gradient descent ===== - -!bc pycod -epochs = 100 -batch_size = 100 -n_neurons_layer1 = 100 -n_neurons_layer2 = 50 -n_categories = 10 -eta_vals = np.logspace(-5, 1, 7) -lmbd_vals = np.logspace(-5, 1, 7) -!ec - - -!bc pycod -DNN_tf = np.zeros((len(eta_vals), len(lmbd_vals)), dtype=object) - -for i, eta in enumerate(eta_vals): - for j, lmbd in enumerate(lmbd_vals): - DNN = NeuralNetworkTensorflow(X_train, Y_train, X_test, Y_test, - n_neurons_layer1, n_neurons_layer2, n_categories, - epochs=epochs, batch_size=batch_size, eta=eta, lmbd=lmbd) - DNN.fit() - - DNN_tf[i][j] = DNN - - print("Learning rate = ", eta) - print("Lambda = ", lmbd) - print("Test accuracy: %.3f" % DNN.test_accuracy) - print() -!ec - -!bc pycod -# optional -# visual representation of grid search -# uses seaborn heatmap, could probably do this in matplotlib -import seaborn as sns - -sns.set() - -train_accuracy = np.zeros((len(eta_vals), len(lmbd_vals))) -test_accuracy = np.zeros((len(eta_vals), len(lmbd_vals))) - -for i in range(len(eta_vals)): - for j in range(len(lmbd_vals)): - DNN = DNN_tf[i][j] - - train_accuracy[i][j] = DNN.train_accuracy - test_accuracy[i][j] = DNN.test_accuracy - - -fig, ax = plt.subplots(figsize = (10, 10)) -sns.heatmap(train_accuracy, annot=True, ax=ax, cmap="viridis") -ax.set_title("Training Accuracy") -ax.set_ylabel("$\eta$") -ax.set_xlabel("$\lambda$") -plt.show() - -fig, ax = plt.subplots(figsize = (10, 10)) -sns.heatmap(test_accuracy, annot=True, ax=ax, cmap="viridis") -ax.set_title("Test Accuracy") -ax.set_ylabel("$\eta$") -ax.set_xlabel("$\lambda$") -plt.show() -!ec - -!bc pycod -# optional -# we can use log files to visualize our graph in Tensorboard -writer = tf.summary.FileWriter('logs/') -writer.add_graph(tf.get_default_graph()) -!ec - - - -===== Using Keras ===== - -Keras is a high level "neural network":"https://en.wikipedia.org/wiki/Application_programming_interface" -that supports Tensorflow, CTNK and Theano as backends. -If you have Tensorflow installed Keras is available through the *tf.keras* module. -If you have Anaconda installed you may run the following command -!bc pycod -conda install keras -!ec - -Alternatively, if you have Tensorflow or one of the other supported backends install you may use the pip package manager: - -!bc pycod -pip3 install keras -!ec -or look up the "instructions here":"https://keras.io/". - -!bc pycod -from keras.models import Sequential -from keras.layers import Dense -from keras.regularizers import l2 -from keras.optimizers import SGD - -def create_neural_network_keras(n_neurons_layer1, n_neurons_layer2, n_categories, eta, lmbd): - model = Sequential() - model.add(Dense(n_neurons_layer1, activation='sigmoid', kernel_regularizer=l2(lmbd))) - model.add(Dense(n_neurons_layer2, activation='sigmoid', kernel_regularizer=l2(lmbd))) - model.add(Dense(n_categories, activation='softmax')) - - sgd = SGD(lr=eta) - model.compile(loss='categorical_crossentropy', optimizer=sgd, metrics=['accuracy']) - - return model -!ec - -!bc pycod -DNN_keras = np.zeros((len(eta_vals), len(lmbd_vals)), dtype=object) - -for i, eta in enumerate(eta_vals): - for j, lmbd in enumerate(lmbd_vals): - DNN = create_neural_network_keras(n_neurons_layer1, n_neurons_layer2, n_categories, - eta=eta, lmbd=lmbd) - DNN.fit(X_train, Y_train, epochs=epochs, batch_size=batch_size, verbose=0) - scores = DNN.evaluate(X_test, Y_test) - - DNN_keras[i][j] = DNN - - print("Learning rate = ", eta) - print("Lambda = ", lmbd) - print("Test accuracy: %.3f" % scores[1]) - print() -!ec - -!bc pycod -# optional -# visual representation of grid search -# uses seaborn heatmap, could probably do this in matplotlib -import seaborn as sns - -sns.set() - -train_accuracy = np.zeros((len(eta_vals), len(lmbd_vals))) -test_accuracy = np.zeros((len(eta_vals), len(lmbd_vals))) - -for i in range(len(eta_vals)): - for j in range(len(lmbd_vals)): - DNN = DNN_keras[i][j] - - train_accuracy[i][j] = DNN.evaluate(X_train, Y_train)[1] - test_accuracy[i][j] = DNN.evaluate(X_test, Y_test)[1] - - -fig, ax = plt.subplots(figsize = (10, 10)) -sns.heatmap(train_accuracy, annot=True, ax=ax, cmap="viridis") -ax.set_title("Training Accuracy") -ax.set_ylabel("$\eta$") -ax.set_xlabel("$\lambda$") -plt.show() - -fig, ax = plt.subplots(figsize = (10, 10)) -sns.heatmap(test_accuracy, annot=True, ax=ax, cmap="viridis") -ax.set_title("Test Accuracy") -ax.set_ylabel("$\eta$") -ax.set_xlabel("$\lambda$") -plt.show() -!ec - - - - - -===== Which activation function should I use? ===== - -The Back propagation algorithm we derived above works by going from -the output layer to the input layer, propagating the error gradient on -the way. Once the algorithm has computed the gradient of the cost -function with regards to each parameter in the network, it uses these -gradients to update each parameter with a Gradient Descent (GD) step. - - -Unfortunately for us, the gradients often get smaller and smaller as the -algorithm progresses down to the first hidden layers. As a result, the -GD update leaves the lower layer connection weights -virtually unchanged, and training never converges to a good -solution. This is known in the literature as -_the vanishing gradients problem_. - -In other cases, the opposite can happen, namely the the gradients can grow bigger and -bigger. The result is that many of the layers get large updates of the -weights the -algorithm diverges. This is the _exploding gradients problem_, which is -mostly encountered in recurrent neural networks. More generally, deep -neural networks suffer from unstable gradients, different layers may -learn at widely different speeds - - -===== Is the Logistic activation function (Sigmoid) our choice? ===== - -Although this unfortunate behavior has been empirically observed for -quite a while (it was one of the reasons why deep neural networks were -mostly abandoned for a long time), it is only around 2010 that -significant progress was made in understanding it. - -A paper titled "Understanding the Difficulty of Training Deep -Feedforward Neural Networks by Xavier Glorot and Yoshua Bengio":"http://proceedings.mlr.press/v9/glorot10a.html" found that -the problems with the popular logistic -sigmoid activation function and the weight initialization technique -that was most popular at the time, namely random initialization using -a normal distribution with a mean of 0 and a standard deviation of -1. - -They showed that with this activation function and this -initialization scheme, the variance of the outputs of each layer is -much greater than the variance of its inputs. Going forward in the -network, the variance keeps increasing after each layer until the -activation function saturates at the top layers. This is actually made -worse by the fact that the logistic function has a mean of 0.5, not 0 -(the hyperbolic tangent function has a mean of 0 and behaves slightly -better than the logistic function in deep networks). - - - -===== The derivative of the Logistic funtion ===== - -Looking at the logistic activation function, when inputs become large -(negative or positive), the function saturates at 0 or 1, with a -derivative extremely close to 0. Thus when backpropagation kicks in, -it has virtually no gradient to propagate back through the network, -and what little gradient exists keeps getting diluted as -backpropagation progresses down through the top layers, so there is -really nothing left for the lower layers. - -In their paper, Glorot and Bengio propose a way to significantly -alleviate this problem. We need the signal to flow properly in both -directions: in the forward direction when making predictions, and in -the reverse direction when backpropagating gradients. We don’t want -the signal to die out, nor do we want it to explode and saturate. For -the signal to flow properly, the authors argue that we need the -variance of the outputs of each layer to be equal to the variance of -its inputs, and we also need the gradients to have equal variance -before and after flowing through a layer in the reverse direction. - - - -One of the insights in the 2010 paper by Glorot and Bengio was that -the vanishing/exploding gradients problems were in part due to a poor -choice of activation function. Until then most people had assumed that -if Nature had chosen to use roughly sigmoid activation functions in -biological neurons, they must be an excellent choice. But it turns out -that other activation functions behave much better in deep neural -networks, in particular the ReLU activation function, mostly because -it does not saturate for positive values (and also because it is quite -fast to compute). - - - -===== The RELU function family ===== - -The ReLU activation function suffers from a problem known as the dying -ReLUs: during training, some neurons effectively die, meaning they -stop outputting anything other than 0. - -In some cases, you may find that half of your network’s neurons are -dead, especially if you used a large learning rate. During training, -if a neuron’s weights get updated such that the weighted sum of the -neuron’s inputs is negative, it will start outputting 0. When this -happen, the neuron is unlikely to come back to life since the gradient -of the ReLU function is 0 when its input is negative. - -To solve this problem, nowadays practitioners use a variant of the ReLU -function, such as the leaky ReLU discussed above or the so-called -exponential linear unit (ELU) function - - -!bt -\[ -ELU(z) = \left\{\begin{array}{cc} \alpha\left( \exp{(z)}-1\right) & z < 0,\\ z & z \ge 0.\end{array}\right. -\] -!et - - -===== Which activation function should we use? ===== - -In general it seems that the ELU activation function is better than -the leaky ReLU function (and its variants), which is better than -ReLU. ReLU performs better than $\tanh$ which in turn performs better -than the logistic function. - -If runtime -performance is an issue, then you may opt for the leaky ReLU function over the -ELU function If you don’t -want to tweak yet another hyperparameter, you may just use the default -$\alpha$ of $0.01$ for the leaky ReLU, and $1$ for ELU. If you have -spare time and computing power, you can use cross-validation or -bootstrap to evaluate other activation functions. - - - -===== A top-down perspective on Neural networks ===== - - -The first thing we would like to do is divide the data into two or three -parts. A training set, a validation or dev (development) set, and a -test set. The test set is the data on which we want to make -predictions. The dev set is a subset of the training data we use to -check how well we are doing out-of-sample, after training the model on -the training dataset. We use the validation error as a proxy for the -test error in order to make tweaks to our model. It is crucial that we -do not use any of the test data to train the algorithm. This is a -cardinal sin in ML. Then: - - -* Estimate optimal error rate - -* Minimize underfitting (bias) on training data set. - -* Make sure you are not overfitting. - -If the validation and test sets are drawn from the same distributions, -then a good performance on the validation set should lead to similarly -good performance on the test set. - -However, sometimes -the training data and test data differ in subtle ways because, for -example, they are collected using slightly different methods, or -because it is cheaper to collect data in one way versus another. In -this case, there can be a mismatch between the training and test -data. This can lead to the neural network overfitting these small -differences between the test and training sets, and a poor performance -on the test set despite having a good performance on the validation -set. To rectify this, Andrew Ng suggests making two validation or dev -sets, one constructed from the training data and one constructed from -the test data. The difference between the performance of the algorithm -on these two validation sets quantifies the train-test mismatch. This -can serve as another important diagnostic when using DNNs for -supervised learning. - - -===== Limitations of supervised learning with deep networks ===== - -Like all statistical methods, supervised learning using neural -networks has important limitations. This is especially important when -one seeks to apply these methods, especially to physics problems. Like -all tools, DNNs are not a universal solution. Often, the same or -better performance on a task can be achieved by using a few -hand-engineered features (or even a collection of random -features). - -Here we list some of the important limitations of supervised neural network based models. - - - -* _Need labeled data_. All supervised learning methods, DNNs for supervised learning require labeled data. Often, labeled data is harder to acquire than unlabeled data (e.g. one must pay for human experts to label images). -* _Supervised neural networks are extremely data intensive._ DNNs are data hungry. They perform best when data is plentiful. This is doubly so for supervised methods where the data must also be labeled. The utility of DNNs is extremely limited if data is hard to acquire or the datasets are small (hundreds to a few thousand samples). In this case, the performance of other methods that utilize hand-engineered features can exceed that of DNNs. -* _Homogeneous data._ Almost all DNNs deal with homogeneous data of one type. It is very hard to design architectures that mix and match data types (i.e.~some continuous variables, some discrete variables, some time series). In applications beyond images, video, and language, this is often what is required. In contrast, ensemble models like random forests or gradient-boosted trees have no difficulty handling mixed data types. -* _Many problems are not about prediction._ In natural science we are often interested in learning something about the underlying distribution that generates the data. In this case, it is often difficult to cast these ideas in a supervised learning setting. While the problems are related, it is possible to make good predictions with a *wrong* model. The model might or might not be useful for understanding the underlying science. - -Some of these remarks are particular to DNNs, others are shared by all supervised learning methods. This motivates the use of unsupervised methods which in part circumnavigate these problems. - - -======= Nearest Neighbors and Decision Trees ======= - -===== Decision trees, overarching aims ===== - -Add text about decision trees and include about random forests (use Ising model classification) - - - -===== Nearest Neighbors ===== -!bc pycod -import mglearn -import numpy as np -from sklearn import linear_model -from sklearn.linear_model import LinearRegression -import matplotlib.pyplot as plt -from sklearn.preprocessing import PolynomialFeatures -from sklearn.pipeline import Pipeline -from sklearn.neighbors import KNeighborsClassifier - -# Generate sample data -X = np.sort(5*np.random.rand(40,1), axis=0) -y = X**3 -y=y.ravel() - -# Add noise to targets -X[::4] +=(0.5 - np.random.rand(1)) -y[::5] +=(0.5 - np.random.rand(8)) - -a=np.array(X) -b=np.array(y) - -X_train=a[:19] -X_test=a[19:] -y_train=b[:19] -y_test=b[19:] - -model=Pipeline([('poly', PolynomialFeatures(degree=3)),('linear', LinearRegression(fit_intercept=False))]) -model=model.fit(X_train, y_train) -pred=model.predict(X_test) - - -poly=PolynomialFeatures(degree=3) -poly.fit_transform(X_train, y_train) -plt.scatter(X_test, y_test) -plt.plot(X_test, pred, color='green') -plt.show() - -print (model.score(X_test,y_test)) - -print ("---------K-Nearest Neighbors-------") -"""neighbors_settings=range(1,11) -for n_neighbors in neighbors_settings: - clf=KNeighborsClassifier(n_neighbors=n_neighbors) - clf.fit(X_train, y_train) - training_accuracy.append(clf.score(X_train, y_train)) - test_accuracy.append(clf.score(X_test, y_test)) - - -print (mglearn.plots.plot_knn_regression(n_neighbors=3))""" - -from sklearn.neighbors import KNeighborsRegressor - -X, y=mglearn.datasets.make_wave(n_samples=40) -reg = KNeighborsRegressor(n_neighbors=3) -reg.fit(X_train, y_train) -!ec - - -===== Decision trees and Regression ===== -!bc pycod -import numpy as np -import matplotlib.pyplot as plt -from sklearn.preprocessing import PolynomialFeatures -from sklearn.linear_model import LinearRegression - -steps=250 - -distance=0 -x=0 -distance_list=[] -steps_list=[] -while x 0$. At a given 'time step', we choose randomly a pair -of agents $(i,j)$ and let a transaction take place. This means that agent $i$'s money $m_i$ changes -to $m_i'$ and similarly we have $m_j\rightarrow m_j'$. -Money is conserved during a transaction, meaning that -!bt -\begin{equation} - m_i+m_j=m_i'+m_j'. - label{eq:conserve} -\end{equation} -!et -The change is done via a random reassignement (a random number) $\epsilon$, meaning that - -!bt -\begin{equation*} -m_i' = \epsilon(m_i+m_j), -\end{equation*} -!et -leading to - -!bt -\begin{equation*} -m_j'= (1-\epsilon)(m_i+m_j). -\end{equation*} -!et -The number $\epsilon$ is extracted from a uniform distribution. -In this simple model, no agents are left with a debt, that is $m\ge 0$. -Due to the conservation law above, one can show that the system relaxes toward an equilibrium -state given by a Gibbs distribution - -!bt -\begin{equation*} -w_m=\beta \exp{(-\beta m)}, -\end{equation*} -!et -with - -!bt -\begin{equation*} -\beta = \frac{1}{\langle m\rangle}, -\end{equation*} -!et -and $\langle m\rangle=\sum_i m_i/N=m_0$, the average money. -It means that after equilibrium has been reached that the majority of agents is left with a small -number of money, while the number of richest agents, those with $m$ larger than a specific value $m'$, -exponentially decreases with $m'$. - -We assume that we have $N=500$ agents. In each simulation, we need a sufficiently large number of transactions, say $10^7$. Our aim is find the final equilibrium distribution $w_m$. In order to do that we would need -several runs of the above simulations, at least $10^3-10^4$ runs (experiments). - -Our task is to first set up an algorithm which simulates the above transactions with an initial - amount $m_0$. - The challenge here is to figure out a Monte Carlo simulation based on the - above equations. - You will in particular need to make an algorithm which sets up a histogram as function of $m$. - This histogram contains the number of times a value $m$ is registered and represents - $w_m\Delta m$. You will need to set up a value for the interval $\Delta m$ (typically $0.01-0.05$). - That means you need to account for the number of times you register an income in the interval - $m,m+\Delta m$. The number of times you register this income, represents the value that enters the histogram. - -!bc pycod -#!/usr/bin/env python -import numpy as np -import matplotlib.mlab as mlab -import matplotlib.pyplot as plt -import random - -# initialize the rng with a seed -random.seed() -# Hard coding of input parameters -Agents = 500 -MCcounts = 1000 -Transactions = 100000 -startMoney = 1.0 -Lambda = 0.0 -FinancialAgents = startMoney*np.ones(Agents) -for i in range (1, MCcounts, 1): - for j in range (1, Transactions, 1): - agent_i = int(Agents*random.random()) - agent_j = int(Agents*random.random()) - epsilon = random.random() - if agent_i != agent_j: - m1 = Lambda*FinancialAgents[agent_i] + (1-Lambda)*epsilon*(FinancialAgents[agent_i] + FinancialAgents[agent_j]) - m2 = Lambda*FinancialAgents[agent_j] + (1-Lambda)*(1-epsilon)*(FinancialAgents[agent_i] + FinancialAgents[agent_j]) - FinancialAgents[agent_i] = m1 - FinancialAgents[agent_j] = m2 - -# the histogram of the data -n, bins, patches = plt.hist(FinancialAgents, 50, facecolor='green') - -plt.xlabel('$x$') -plt.ylabel('Distribution of wealth') -plt.title(r'Money') -plt.axis([0, 10, 0, 500]) -plt.grid(True) -plt.show() - -!ec - - -We can then change our model to allow for a saving criterion, meaning that the agents save - a fraction $\lambda$ of the money they have before the transaction is made. The final distribution will then no longer be given by Gibbs distribution. It could also include a taxation on financial transactions. - - The conservation law of Eq. (ref{eq:conserve}) holds, but the money to be shared in a transaction between - agent $i$ and agent $j$ is now $(1-\lambda)(m_i+m_j)$. This means that we have - -!bt -\begin{equation*} - m_i' = \lambda m_i+\epsilon(1-\lambda)(m_i+m_j), - \end{equation*} -!et - and - -!bt -\begin{equation*} - m_j' = \lambda m_j+(1-\epsilon)(1-\lambda)(m_i+m_j), - \end{equation*} -!et - which can be written as - -!bt -\begin{equation*} - m_i'=m_i+\delta m - \end{equation*} -!et - and - -!bt -\begin{equation*} - m_j'=m_j-\delta m, - \end{equation*} -!et - with - -!bt -\begin{equation*} - \delta m=(1-\lambda)(\epsilon m_j-(1-\epsilon)m_i), - \end{equation*} -!et - showing how money is conserved during a transaction. - Select values of $\lambda =0.25,0.5$ and $\lambda=0.9$ and try to extract the corresponding - equilibrium distributions and compare these with the Gibbs distribution. We will use this model to -extract a parametrization of the above curves, see for example "Patriarca and collaborators":"http://www.sciencedirect.com/science/article/pii/S0378437104004327". - - -=== Particle in one dimension and velocity distribution === -!bc pycod -# Program to test the Metropolis algorithm with one particle at given temp in one dimension -import numpy as np -import matplotlib.mlab as mlab -import matplotlib.pyplot as plt -import random -from math import sqrt, exp, log -# initialize the rng with a seed -random.seed() -# Hard coding of input parameters -MCcycles = 100000 -Temperature = 2.0 -beta = 1./Temperature -InitialVelocity = -2.0 -CurrentVelocity = InitialVelocity -Energy = 0.5*InitialVelocity*InitialVelocity -VelocityRange = 10*sqrt(Temperature) -VelocityStep = 2*VelocityRange/10. -AverageEnergy = Energy -AverageEnergy2 = Energy*Energy -VelocityValues = np.zeros(MCcycles) -# The Monte Carlo sampling with Metropolis starts here -for i in range (1, MCcycles, 1): - TrialVelocity = CurrentVelocity + (2.0*random.random() - 1.0)*VelocityStep - EnergyChange = 0.5*(TrialVelocity*TrialVelocity -CurrentVelocity*CurrentVelocity); - if random.random() <= exp(-beta*EnergyChange): - CurrentVelocity = TrialVelocity - Energy += EnergyChange - VelocityValues[i] = CurrentVelocity - AverageEnergy += Energy - AverageEnergy2 += Energy*Energy -#Final averages -AverageEnergy = AverageEnergy/MCcycles -AverageEnergy2 = AverageEnergy2/MCcycles -Variance = AverageEnergy2 - AverageEnergy*AverageEnergy -print(AverageEnergy, Variance) -n, bins, patches = plt.hist(VelocityValues, 400, facecolor='green') - -plt.xlabel('$v$') -plt.ylabel('Velocity distribution P(v)') -plt.title(r'Velocity histogram at $k_BT=2$') -plt.axis([-5, 5, 0, 600]) -plt.grid(True) -plt.show() - -!ec - - - - -=== Random walk model === -!bc pycod -import numpy as np -import matplotlib.pyplot as plt -from sklearn.preprocessing import PolynomialFeatures -from sklearn.linear_model import LinearRegression - -steps=250 - -distance=0 -x=0 -distance_list=[] -steps_list=[] -while x j$ @@ -1541,10 +661,10 @@ The inverse of a matrix is defined by * Upper banded with bandwidth $p$: $a_{ij}=0$ for $i < j+p$ * Banded, block upper triangular, block lower triangular.... -!split -===== Basic Matrix Features ===== -!bblock Some Equivalent Statements +=== More Basic Matrix Features === + +Some Equivalent Statements For an $N\times N$ matrix $\mathbf{A}$ the following properties are all equivalent * If the inverse of $\mathbf{A}$ exists, $\mathbf{A}$ is nonsingular. @@ -1553,18 +673,22 @@ For an $N\times N$ matrix $\mathbf{A}$ the following properties are all equival * The columns of $\mathbf{A}$ form a basis of $R^N$. * $\mathbf{A}$ is a product of elementary matrices. * $0$ is not eigenvalue of $\mathbf{A}$. -!eblock -!split + + ===== Numpy and arrays ===== "Numpy":"http://www.numpy.org/" provides an easy way to handle arrays in Python. The standard way to import this library is as + !bc pycod import numpy as np +!ec +Here follows a simple example where we set up an array of ten elements, all determined by random numbers drawn according to the normal distribution, +!bc pycod n = 10 x = np.random.normal(size=n) print(x) !ec -Here we have defined a vector $x$ with $n=10$ elements with its values given by the Normal distribution $N(0,1)$. +We defined a vector $x$ with $n=10$ elements with its values given by the Normal distribution $N(0,1)$. Another alternative is to declare a vector as follows !bc pycod import numpy as np @@ -1579,7 +703,7 @@ x = np.log(np.array([4, 7, 8])) print(x) !ec -Here we have used Numpy's unary function $np.log$. This function is +In the last example we used Numpy's unary function $np.log$. This function is highly tuned to compute array elements since the code is vectorized and does not require looping. We normaly recommend that you use the Numpy intrinsic functions instead of the corresponding _log_ function @@ -1596,7 +720,7 @@ for i in range(0, len(x)): print(x) !ec We note that our code is much longer already and we need to import the _log_ function from the _math_ module. -The attentive reader will also notice that the output is $[1, 1, 2]$. Python interprets automacally our numbers as integers (like the _automatic_ keyword in C++). To change this we could define our array elements to be double precision numbers as +The attentive reader will also notice that the output is $[1, 1, 2]$. Python interprets automagically our numbers as integers (like the _automatic_ keyword in C++). To change this we could define our array elements to be double precision numbers as !bc pycod import numpy as np x = np.log(np.array([4, 7, 8], dtype = np.float64)) @@ -1615,10 +739,13 @@ x = np.log(np.array([4.0, 7.0, 8.0]) print(x.itemsize) !ec -!split + ===== Matrices in Python ===== -Having defined vectors, we are now ready to try out matrices. We can define a $3 \times 3 $ real matrix $\hat{A}$ -as (recall that we user lowercase letters for vectors and uppercase letters for matrices) + +Having defined vectors, we are now ready to try out matrices. We can +define a $3 \times 3 $ real matrix $\hat{A}$ as (recall that we user +lowercase letters for vectors and uppercase letters for matrices) + !bc pycod import numpy as np A = np.log(np.array([ [4.0, 7.0, 8.0], [3.0, 10.0, 11.0], [4.0, 5.0, 7.0] ])) @@ -1680,8 +807,8 @@ where for example \sigma_{xy} =\frac{1}{n} \sum_{i=0}^{n-1}(x_i- \overline{x})(y_i- \overline{y}). \] !et -The Numpy function _np.cov_ calculates the covariance elements using the factor $1/(n-1)$ instead of $1/n$ since it assumes we do not have the exact mean values. For a more in-depth discussion of the covariance and covariance matrix and its meaning, we refer you to the lectures on statistics. -The following simple function uses the _np.vstack_ function which takes each vector of dimension $1\times n$ and produces a $ 3\times n$ matrix $\hat{W}$ +The Numpy function _np.cov_ calculates the covariance elements using the factor $1/(n-1)$ instead of $1/n$ since it assumes we do not have the exact mean values. +The following simple function uses the _np.vstack_ function which takes each vector of dimension $1\times n$ and produces a $3\times n$ matrix $\hat{W}$ !bt \[ \hat{W} = \begin{bmatrix} x_0 & y_0 & z_0 \\ @@ -1694,10 +821,8 @@ The following simple function uses the _np.vstack_ function which takes each vec \] !et -which in turn is converted into into the $3 times 3$ covariance matrix -$\hat{\Sigma}$ via the Numpy function _np.cov()_. In our review of -statistical functions and quantities we will discuss more about the -meaning of the covariance matrix. Here we note that we can calculate +which in turn is converted into into the $3\times 3$ covariance matrix +$\hat{\Sigma}$ via the Numpy function _np.cov()_. We note that we can also calculate the mean value of each set of samples $\hat{x}$ etc using the Numpy function _np.mean(x)_. We can also extract the eigenvalues of the covariance matrix through the _np.linalg.eig()_ function. @@ -1736,3216 +861,158 @@ plt.show() !ec +===== Meet the Pandas ===== -!split -===== Matrix Handling in C/C++, Static and Dynamical allocation ===== +FIGURE: [fig/pandas.jpg, width=600 frac=0.8] -!bblock Static -We have an $N\times N$ matrix A with $N=100$ -In C/C++ this would be defined as +Another useful Python package is +"pandas":"https://pandas.pydata.org/", which is an open source library +providing high-performance, easy-to-use data structures and data +analysis tools for Python. _pandas_ stands for panel data, a term borrowed from econometrics and is an efficient library for data analysis with an emphasis on tabular data. +_pandas_ has two major classes, the _DataFrame_ class with two-dimensional data objects and tabular data organized in columns and the class _Series_ with a focus on one-dimensional data objects. Both classes allow you to index data easily as we will see in the examples below. +_pandas_ allows you also to perform mathematical operations on the data, spanning from simple reshapings of vectors and matrices to statistical operations. -!bc cppcod - int N = 100; - double A[100][100]; - // initialize all elements to zero - for(i=0 ; i < N ; i++) { - for(j=0 ; j < N ; j++) { - A[i][j] = 0.0; +The following simple example shows how we can, in an easy way make tables of our data. Here we define a data set which includes names, place of birth and date of birth, and displays the data in an easy to read way. We will see repeated use of _pandas_, in particular in connection with classification of data. -!ec -Note the way the matrix is organized, row-major order. -!eblock - -!split -===== Matrix Handling in C/C++ ===== - -!bblock Row Major Order, Addition -We have $N\times N$ matrices A, B and C and we wish to -evaluate $A=B+C$. - -!bt -\[ -\mathbf{A}= \mathbf{B}\pm\mathbf{C} \Longrightarrow a_{ij} = b_{ij}\pm c_{ij}, -\] -!et -In C/C++ this would be coded like - -!bc cppcod - for(i=0 ; i < N ; i++) { - for(j=0 ; j < N ; j++) { - a[i][j] = b[i][j]+c[i][j] - -!ec -!eblock - -!split -===== Matrix Handling in C/C++ ===== - -!bblock Row Major Order, Multiplication -We have $N\times N$ matrices A, B and C and we wish to -evaluate $A=BC$. - -!bt -\[ -\mathbf{A}=\mathbf{BC} \Longrightarrow a_{ij} = \sum_{k=1}^{n} b_{ik}c_{kj}, -\] -!et -In C/C++ this would be coded like - -!bc cppcod - for(i=0 ; i < N ; i++) { - for(j=0 ; j < N ; j++) { - for(k=0 ; k < N ; k++) { - a[i][j]+=b[i][k]*c[k][j]; - -!ec -!eblock - - -!split -===== Dynamic memory allocation in C/C++ ===== - -At least three possibilities in this course - - * Do it yourself - * Use the functions provided in the library package lib.cpp - * Use Armadillo URL: "http://arma.sourceforgenet" (a C++ linear algebra library, discussion both here and at lab). - -!split -===== Matrix Handling in C/C++, Dynamic Allocation ===== - -!bblock Do it yourself -!bc cppcod -int N; -double ** A; -A = new double*[N] -for ( i = 0; i < N; i++) - A[i] = new double[N]; -!ec -Always free space when you don't need an array anymore. - -!bc cppcod -for ( i = 0; i < N; i++) - delete[] A[i]; -delete[] A; -!ec -!eblock - -!split -===== Armadillo, recommended!! ===== - - * Armadillo is a C++ linear algebra library (matrix maths) aiming towards a good balance between speed and ease of use. The syntax is deliberately similar to Matlab. - * Integer, floating point and complex numbers are supported, as well as a subset of trigonometric and statistics functions. Various matrix decompositions are provided through optional integration with LAPACK, or one of its high performance drop-in replacements (such as the multi-threaded MKL or ACML libraries). - * A delayed evaluation approach is employed (at compile-time) to combine several operations into one and reduce (or eliminate) the need for temporaries. This is accomplished through recursive templates and template meta-programming. - * Useful for conversion of research code into production environments, or if C++ has been decided as the language of choice, due to speed and/or integration capabilities. - * The library is open-source software, and is distributed under a license that is useful in both open-source and commercial/proprietary contexts. - -!split -===== Armadillo, simple examples ===== - -!bc cppcod -#include -#include - -using namespace std; -using namespace arma; - -int main(int argc, char** argv) - { - mat A = randu(5,5); - mat B = randu(5,5); - - cout << A*B << endl; - - return 0; - -!ec - -!split -===== Armadillo, how to compile and install ===== - -For people using Ubuntu, Debian, Linux Mint, simply go to the synaptic package manager and install -armadillo from there. -You may have to install Lapack as well. -For Mac and Windows users, follow the instructions from the webpage -URL: "http://arma.sourceforge.net". -To compile, use for example (linux/ubuntu) - -!bc cppcod -c++ -O2 -o program.x program.cpp -larmadillo -llapack -lblas -!ec -where the `-l` option indicates the library you wish to link to. - -For OS X users you may have to declare the paths to the include files and the libraries as -!bc cppcod -c++ -O2 -o program.x program.cpp -L/usr/local/lib -I/usr/local/include -larmadillo -llapack -lblas -!ec - -!split -===== Armadillo, simple examples ===== - -!bc cppcod -#include -#include "armadillo" -using namespace arma; -using namespace std; - -int main(int argc, char** argv) - { - // directly specify the matrix size (elements are uninitialised) - mat A(2,3); - // .n_rows = number of rows (read only) - // .n_cols = number of columns (read only) - cout << "A.n_rows = " << A.n_rows << endl; - cout << "A.n_cols = " << A.n_cols << endl; - // directly access an element (indexing starts at 0) - A(1,2) = 456.0; - A.print("A:"); - // scalars are treated as a 1x1 matrix, - // hence the code below will set A to have a size of 1x1 - A = 5.0; - A.print("A:"); - // if you want a matrix with all elements set to a particular value - // the .fill() member function can be used - A.set_size(3,3); - A.fill(5.0); A.print("A:"); -!ec - -!split -===== Armadillo, simple examples ===== - -!bc cppcod - mat B; - - // endr indicates "end of row" - B << 0.555950 << 0.274690 << 0.540605 << 0.798938 << endr - << 0.108929 << 0.830123 << 0.891726 << 0.895283 << endr - << 0.948014 << 0.973234 << 0.216504 << 0.883152 << endr - << 0.023787 << 0.675382 << 0.231751 << 0.450332 << endr; - - // print to the cout stream - // with an optional string before the contents of the matrix - B.print("B:"); - - // the << operator can also be used to print the matrix - // to an arbitrary stream (cout in this case) - cout << "B:" << endl << B << endl; - // save to disk - B.save("B.txt", raw_ascii); - // load from disk - mat C; - C.load("B.txt"); - C += 2.0 * B; - C.print("C:"); -!ec - -!split -===== Armadillo, simple examples ===== - -!bc cppcod - // submatrix types: - // - // .submat(first_row, first_column, last_row, last_column) - // .row(row_number) - // .col(column_number) - // .cols(first_column, last_column) - // .rows(first_row, last_row) - - cout << "C.submat(0,0,3,1) =" << endl; - cout << C.submat(0,0,3,1) << endl; - - // generate the identity matrix - mat D = eye(4,4); - - D.submat(0,0,3,1) = C.cols(1,2); - D.print("D:"); - - // transpose - cout << "trans(B) =" << endl; - cout << trans(B) << endl; - - // maximum from each column (traverse along rows) - cout << "max(B) =" << endl; - cout << max(B) << endl; - -!ec - -!split -===== Armadillo, simple examples ===== - -!bc cppcod - // maximum from each row (traverse along columns) - cout << "max(B,1) =" << endl; - cout << max(B,1) << endl; - // maximum value in B - cout << "max(max(B)) = " << max(max(B)) << endl; - // sum of each column (traverse along rows) - cout << "sum(B) =" << endl; - cout << sum(B) << endl; - // sum of each row (traverse along columns) - cout << "sum(B,1) =" << endl; - cout << sum(B,1) << endl; - // sum of all elements - cout << "sum(sum(B)) = " << sum(sum(B)) << endl; - cout << "accu(B) = " << accu(B) << endl; - // trace = sum along diagonal - cout << "trace(B) = " << trace(B) << endl; - // random matrix -- values are uniformly distributed in the [0,1] interval - mat E = randu(4,4); - E.print("E:"); - -!ec - -!split -===== Armadillo, simple examples ===== - -!bc cppcod - // row vectors are treated like a matrix with one row - rowvec r; - r << 0.59499 << 0.88807 << 0.88532 << 0.19968; - r.print("r:"); - - // column vectors are treated like a matrix with one column - colvec q; - q << 0.81114 << 0.06256 << 0.95989 << 0.73628; - q.print("q:"); - - // dot or inner product - cout << "as_scalar(r*q) = " << as_scalar(r*q) << endl; - - // outer product - cout << "q*r =" << endl; - cout << q*r << endl; - - - // sum of three matrices (no temporary matrices are created) - mat F = B + C + D; - F.print("F:"); - - return 0; - -!ec - -!split -===== Armadillo, simple examples ===== - -!bc cppcod -#include -#include "armadillo" -using namespace arma; -using namespace std; - -int main(int argc, char** argv) - { - cout << "Armadillo version: " << arma_version::as_string() << endl; - - mat A; - - A << 0.165300 << 0.454037 << 0.995795 << 0.124098 << 0.047084 << endr - << 0.688782 << 0.036549 << 0.552848 << 0.937664 << 0.866401 << endr - << 0.348740 << 0.479388 << 0.506228 << 0.145673 << 0.491547 << endr - << 0.148678 << 0.682258 << 0.571154 << 0.874724 << 0.444632 << endr - << 0.245726 << 0.595218 << 0.409327 << 0.367827 << 0.385736 << endr; - - A.print("A ="); - - // determinant - cout << "det(A) = " << det(A) << endl; -!ec - -!split -===== Armadillo, simple examples ===== - -!bc cppcod - // inverse - cout << "inv(A) = " << endl << inv(A) << endl; - double k = 1.23; - - mat B = randu(5,5); - mat C = randu(5,5); - - rowvec r = randu(5); - colvec q = randu(5); - - - // examples of some expressions - // for which optimised implementations exist - // optimised implementation of a trinary expression - // that results in a scalar - cout << "as_scalar( r*inv(diagmat(B))*q ) = "; - cout << as_scalar( r*inv(diagmat(B))*q ) << endl; - - // example of an expression which is optimised - // as a call to the dgemm() function in BLAS: - cout << "k*trans(B)*C = " << endl << k*trans(B)*C; - - return 0; - -!ec - -!split -===== Gaussian Elimination ===== - -We start with the linear set of equations - -!bt -\[ - \mathbf{A}\mathbf{x} = \mathbf{w}. -\] -!et -We assume also that the matrix $\mathbf{A}$ is non-singular and that the -matrix elements along the diagonal satisfy $a_{ii} \ne 0$. Simple $4\times 4 $ example - -!bt -\[ -\begin{bmatrix} - a_{11}& a_{12} &a_{13}& a_{14}\\ - a_{21}& a_{22} &a_{23}& a_{24}\\ - a_{31}& a_{32} &a_{33}& a_{34}\\ - a_{41}& a_{42} &a_{43}& a_{44}\\ - \end{bmatrix} \begin{bmatrix} - x_1\\ - x_2\\ - x_3 \\ - x_4 \\ - \end{bmatrix} - =\begin{bmatrix} - w_1\\ - w_2\\ - w_3 \\ - w_4\\ - \end{bmatrix}. -\] -!et - -!split -===== Gaussian Elimination ===== -or - -!bt -\begin{align} - a_{11}x_1 +a_{12}x_2 +a_{13}x_3 + a_{14}x_4=&w_1 \nonumber \\ -a_{21}x_1 + a_{22}x_2 + a_{23}x_3 + a_{24}x_4=&w_2 \nonumber \\ -a_{31}x_1 + a_{32}x_2 + a_{33}x_3 + a_{34}x_4=&w_3 \nonumber \\ -a_{41}x_1 + a_{42}x_2 + a_{43}x_3 + a_{44}x_4=&w_4. \nonumber -\end{align} -!et - -!split -===== Gaussian Elimination ===== - -The basic idea of Gaussian elimination is to use the first equation to eliminate the first unknown $x_1$ -from the remaining $n-1$ equations. Then we use the new second equation to eliminate the second unknown -$x_2$ from the remaining $n-2$ equations. With $n-1$ such eliminations -we obtain a so-called upper triangular set of equations of the form - -!bt -\begin{align} - b_{11}x_1 +b_{12}x_2 +b_{13}x_3 + b_{14}x_4=&y_1 \nonumber \\ - b_{22}x_2 + b_{23}x_3 + b_{24}x_4=&y_2 \nonumber \\ -b_{33}x_3 + b_{34}x_4=&y_3 \nonumber \\ -b_{44}x_4=&y_4. \nonumber -label{eq:gaussbacksub} -\end{align} -!et -We can solve this system of equations recursively starting from $x_n$ (in our case $x_4$) and proceed with -what is called a backward substitution. - -!split -===== Gaussian Elimination ===== -This process can be expressed mathematically as - -!bt -\begin{equation} - x_m = \frac{1}{b_{mm}}\left(y_m-\sum_{k=m+1}^nb_{mk}x_k\right)\quad m=n-1,n-2,\dots,1. -\end{equation} -!et -To arrive at such an upper triangular system of equations, we start by eliminating -the unknown $x_1$ for $j=2,n$. We achieve this by multiplying the first equation by $a_{j1}/a_{11}$ and then subtract -the result from the $j$th equation. We assume obviously that $a_{11}\ne 0$ and that -$\mathbf{A}$ is not singular. - -!split -===== Gaussian Elimination ===== - -Our actual $4\times 4$ example reads after the first operation - -!bt -\[ -\begin{bmatrix} - a_{11}& a_{12} &a_{13}& a_{14}\\ - 0& (a_{22}-\frac{a_{21}a_{12}}{a_{11}}) &(a_{23}-\frac{a_{21}a_{13}}{a_{11}}) & (a_{24}-\frac{a_{21}a_{14}}{a_{11}})\\ -0& (a_{32}-\frac{a_{31}a_{12}}{a_{11}})& (a_{33}-\frac{a_{31}a_{13}}{a_{11}})& (a_{34}-\frac{a_{31}a_{14}}{a_{11}})\\ -0&(a_{42}-\frac{a_{41}a_{12}}{a_{11}}) &(a_{43}-\frac{a_{41}a_{13}}{a_{11}}) & (a_{44}-\frac{a_{41}a_{14}}{a_{11}}) \\ - \end{bmatrix} \begin{bmatrix} - x_1\\ - x_2\\ - x_3 \\ - x_4 \\ - \end{bmatrix} - =\begin{bmatrix} - y_1\\ - w_2^{(2)}\\ - w_3^{(2)} \\ - w_4^{(2)}\\ - \end{bmatrix}, -\] -!et -or - -!bt -\begin{align} - b_{11}x_1 +b_{12}x_2 +b_{13}x_3 + b_{14}x_4=&y_1 \nonumber \\ - a^{(2)}_{22}x_2 + a^{(2)}_{23}x_3 + a^{(2)}_{24}x_4=&w^{(2)}_2 \nonumber \\ - a^{(2)}_{32}x_2 + a^{(2)}_{33}x_3 + a^{(2)}_{34}x_4=&w^{(2)}_3 \nonumber \\ - a^{(2)}_{42}x_2 + a^{(2)}_{43}x_3 + a^{(2)}_{44}x_4=&w^{(2)}_4, \nonumber \\ -\end{align} -!et - -!split -===== Gaussian Elimination ===== - -The new coefficients are - -!bt -\begin{equation} - b_{1k} = a_{1k}^{(1)} \quad k=1,\dots,n, -\end{equation} -!et -where each $a_{1k}^{(1)}$ is equal to the original $a_{1k}$ element. The other coefficients are - -!bt -\begin{equation} -a_{jk}^{(2)} = a_{jk}^{(1)}-\frac{a_{j1}^{(1)}a_{1k}^{(1)}}{a_{11}^{(1)}} \quad j,k=2,\dots,n, -\end{equation} -!et -with a new right-hand side given by - -!bt -\begin{equation} -y_{1}=w_1^{(1)}, \quad w_j^{(2)} =w_j^{(1)}-\frac{a_{j1}^{(1)}w_1^{(1)}}{a_{11}^{(1)}} \quad j=2,\dots,n. -\end{equation} -!et -We have also set $w_1^{(1)}=w_1$, the original vector element. -We see that the system of unknowns $x_1,\dots,x_n$ is transformed into an $(n-1)\times (n-1)$ problem. - -!split -===== Gaussian Elimination ===== - -This step is called forward substitution. -Proceeding with these substitutions, we obtain the -general expressions for the new coefficients - -!bt -\begin{equation} - a_{jk}^{(m+1)} = a_{jk}^{(m)}-\frac{a_{jm}^{(m)}a_{mk}^{(m)}}{a_{mm}^{(m)}} \quad j,k=m+1,\dots,n, -\end{equation} -!et -with $m=1,\dots,n-1$ and a -right-hand side given by - -!bt -\begin{equation} - w_j^{(m+1)} =w_j^{(m)}-\frac{a_{jm}^{(m)}w_m^{(m)}}{a_{mm}^{(m)}}\quad j=m+1,\dots,n. -\end{equation} -!et -This set of $n-1$ elimations leads us to an equations which is solved by back substitution. -If the arithmetics is exact and the matrix $\mathbf{A}$ is not singular, then the computed answer will be exact. - -Even though the matrix elements along the diagonal are not zero, -numerically small numbers may appear and subsequent divisions may lead to large numbers, which, if added -to a small number may yield losses of precision. Suppose for example that our first division in $(a_{22}-a_{21}a_{12}/a_{11})$ -results in $-10^{-7}$ and that $a_{22}$ is one. -one. We are then -adding $10^7+1$. With single precision this results in $10^7$. - - - -!split -===== Linear Algebra Methods ===== - - * Gaussian elimination, $O(2/3n^3)$ flops, general matrix - * LU decomposition, upper triangular and lower tridiagonal matrices, $O(2/3n^3)$ flops, general matrix. Get easily the inverse, determinant and can solve linear equations with back-substitution only, $O(n^2)$ flops - * Cholesky decomposition. Real symmetric or hermitian positive definite matrix, $O(1/3n^3)$ flops. - * Tridiagonal linear systems, important for differential equations. Normally positive definite and non-singular. $O(8n)$ flops for symmetric. Special case of banded matrices. - * Singular value decomposition - * the QR method will be discussed in chapter 7 in connection with eigenvalue systems. $O(4/3n^3)$ flops. - -!split -===== LU Decomposition ===== - -The LU decomposition method means that we can rewrite -this matrix as the product of two matrices $\mathbf{L}$ and $\mathbf{U}$ -where - -!bt -\[ - \begin{bmatrix} - a_{11} & a_{12} & a_{13} & a_{14} \\ - a_{21} & a_{22} & a_{23} & a_{24} \\ - a_{31} & a_{32} & a_{33} & a_{34} \\ - a_{41} & a_{42} & a_{43} & a_{44} - \end{bmatrix} - = \begin{bmatrix} - 1 & 0 & 0 & 0 \\ - l_{21} & 1 & 0 & 0 \\ - l_{31} & l_{32} & 1 & 0 \\ - l_{41} & l_{42} & l_{43} & 1 - \end{bmatrix} - \begin{bmatrix} - u_{11} & u_{12} & u_{13} & u_{14} \\ - 0 & u_{22} & u_{23} & u_{24} \\ - 0 & 0 & u_{33} & u_{34} \\ - 0 & 0 & 0 & u_{44} - \end{bmatrix}. -\] -!et - -!split -===== LU Decomposition ===== - -LU decomposition forms the backbone of other algorithms in linear algebra, such as the -solution of linear equations given by - -!bt -\begin{align} - a_{11}x_1 +a_{12}x_2 +a_{13}x_3 + a_{14}x_4=&w_1 \nonumber \\ -a_{21}x_1 + a_{22}x_2 + a_{23}x_3 + a_{24}x_4=&w_2 \nonumber \\ -a_{31}x_1 + a_{32}x_2 + a_{33}x_3 + a_{34}x_4=&w_3 \nonumber \\ -a_{41}x_1 + a_{42}x_2 + a_{43}x_3 + a_{44}x_4=&w_4. \nonumber -\end{align} -!et -The above set of equations is conveniently solved by using LU decomposition as an intermediate step. - -The matrix $\mathbf{A}\in \mathbb{R}^{n\times n}$ has an LU factorization if the determinant -is different from zero. If the LU factorization exists and $\mathbf{A}$ is non-singular, then the LU factorization -is unique and the determinant is given by - -!bt -\[ -det\{\mathbf{A}\}=det\{\mathbf{LU}\}= det\{\mathbf{L}\}det\{\mathbf{U}\}=u_{11}u_{22}\dots u_{nn}. -\] -!et - -!split -===== LU Decomposition, why? ===== - -There are at least three main advantages with LU decomposition compared with standard Gaussian elimination: - - * It is straightforward to compute the determinant of a matrix - * If we have to solve sets of linear equations with the same matrix but with different vectors $\mathbf{y}$, the number of FLOPS is of the order $n^3$. - * The inverse is such an operation - -!split -===== LU Decomposition, linear equations ===== - -With the LU decomposition it is rather -simple to solve a system of linear equations - -!bt -\begin{align} - a_{11}x_1 +a_{12}x_2 +a_{13}x_3 + a_{14}x_4=&w_1 \nonumber \\ -a_{21}x_1 + a_{22}x_2 + a_{23}x_3 + a_{24}x_4=&w_2 \nonumber \\ -a_{31}x_1 + a_{32}x_2 + a_{33}x_3 + a_{34}x_4=&w_3 \nonumber \\ -a_{41}x_1 + a_{42}x_2 + a_{43}x_3 + a_{44}x_4=&w_4. \nonumber -\end{align} -!et - -This can be written in matrix form as - -!bt -\[ \mathbf{Ax}=\mathbf{w}. \] -!et - -where $\mathbf{A}$ and $\mathbf{w}$ are known and we have to solve for -$\mathbf{x}$. Using the LU dcomposition we write - -!bt -\[ \mathbf{A} \mathbf{x} \equiv \mathbf{L} \mathbf{U} \mathbf{x} =\mathbf{w}. \] -!et - -!split -===== LU Decomposition, linear equations ===== - -The previous equation can be calculated in two steps - -!bt -\[ \mathbf{L} \mathbf{y} = \mathbf{w};\qquad \mathbf{Ux}=\mathbf{y}. \] -!et - -To show that this is correct we use to the LU decomposition -to rewrite our system of linear equations as - -!bt -\[ \mathbf{LUx}=\mathbf{w}, \] -!et -and since the determinant of $\mathbf{L}$ is equal to 1 (by construction -since the diagonals of $\mathbf{L}$ equal 1) we can use the inverse of -$\mathbf{L}$ to obtain - -!bt -\[ - \mathbf{Ux}=\mathbf{L^{-1}w}=\mathbf{y}, -\] -!et -which yields the intermediate step - -!bt -\[ - \mathbf{L^{-1}w}=\mathbf{y} -\] -!et -and as soon as we have $\mathbf{y}$ we can obtain $\mathbf{x}$ -through $\mathbf{Ux}=\mathbf{y}$. - -!split -===== LU Decomposition, why? ===== - -For our four-dimentional example this takes the form - -!bt -\begin{align} - y_1=&w_1 \nonumber\\ -l_{21}y_1 + y_2=&w_2\nonumber \\ -l_{31}y_1 + l_{32}y_2 + y_3 =&w_3\nonumber \\ -l_{41}y_1 + l_{42}y_2 + l_{43}y_3 + y_4=&w_4. \nonumber -\end{align} -!et - -and - -!bt -\begin{align} - u_{11}x_1 +u_{12}x_2 +u_{13}x_3 + u_{14}x_4=&y_1 \nonumber\\ -u_{22}x_2 + u_{23}x_3 + u_{24}x_4=&y_2\nonumber \\ -u_{33}x_3 + u_{34}x_4=&y_3\nonumber \\ -u_{44}x_4=&y_4 \nonumber -\end{align} -!et - -This example shows the basis for the algorithm -needed to solve the set of $n$ linear equations. - -!split -===== LU Decomposition, linear equations ===== - -The algorithm goes as follows - - * Set up the matrix $\bf A$ and the vector $\bf w$ with their correct dimensions. This determines the dimensionality of the unknown vector $\bf x$. - * Then LU decompose the matrix $\bf A$ through a call to the function `ludcmp(double a, int n, int indx, double &d)`. This functions returns the LU decomposed matrix $\bf A$, its determinant and the vector indx which keeps track of the number of interchanges of rows. If the determinant is zero, the solution is malconditioned. - * Thereafter you call the function `lubksb(double a, int n, int indx, double w)` which uses the LU decomposed matrix $\bf A$ and the vector $\bf w$ and returns $\bf x$ in the same place as $\bf w$. Upon exit the original content in $\bf w$ is destroyed. If you wish to keep this information, you should make a backup of it in your calling function. - -!split -===== LU Decomposition, the inverse of a matrix ===== - -If the inverse exists then - -!bt -\[ - \mathbf{A}^{-1}\mathbf{A}=\mathbf{I}, -\] -!et -the identity matrix. With an LU decomposed matrix we can rewrite the last equation as - -!bt -\[ - \mathbf{LU}\mathbf{A}^{-1}=\mathbf{I}. -\] -!et - -!split -===== LU Decomposition, the inverse of a matrix ===== - -If we assume that the first column (that is column 1) of the inverse matrix -can be written as a vector with unknown entries - -!bt -\[ - \mathbf{A}_1^{-1}= \begin{bmatrix} - - a_{11}^{-1} \\ - a_{21}^{-1} \\ - \dots \\ - a_{n1}^{-1} \\ - \end{bmatrix}, -\] -!et -then we have a linear set of equations - -!bt -\[ - \mathbf{LU}\begin{bmatrix} - - a_{11}^{-1} \\ - a_{21}^{-1} \\ - \dots \\ - a_{n1}^{-1} \\ - \end{bmatrix} =\begin{bmatrix} - 1 \\ - 0 \\ - \dots \\ - 0 \\ - \end{bmatrix}. -\] -!et - -!split -===== LU Decomposition, the inverse ===== - -In a similar way we can compute the unknow entries of the second column, - -!bt -\[ - \mathbf{LU}\begin{bmatrix} - - a_{12}^{-1} \\ - a_{22}^{-1} \\ - \dots \\ - a_{n2}^{-1} \\ - \end{bmatrix}=\begin{bmatrix} - 0 \\ - 1 \\ - \dots \\ - 0 \\ - \end{bmatrix}, -\] -!et -and continue till we have solved all $n$ sets of linear equations. - - -!split -===== "Using Armadillo to perform an LU decomposition":"https://github.com/CompPhysics/ComputationalPhysicsMSU/blob/master/doc/Programs/CppQtCodesLectures/MatrixTest/main.cpp" ===== -!bc cppcod -#include -#include "armadillo" -using namespace arma; -using namespace std; - -int main() - { - mat A = randu(5,5); - vec b = randu(5); - - A.print("A ="); - b.print("b="); - // solve Ax = b - vec x = solve(A,b); - // print x - x.print("x="); - // find LU decomp of A, if needed, P is the permutation matrix - mat L, U; - lu(L,U,A); - // print l - L.print(" L= "); - // print U - U.print(" U= "); - //Check that A = LU - (A-L*U).print("Test of LU decomposition"); - return 0; - } -!ec - - -======= Review of Statistics ======= - - -===== Domains and probabilities ===== -!bblock -Consider the following simple example, namely the tossing of two dice, resulting in the following possible values -!bt -\begin{equation*} -\{2,3,4,5,6,7,8,9,10,11,12\}. -\end{equation*} -!et -These values are called the *domain*. -To this domain we have the corresponding *probabilities* -!bt -\begin{equation*} -\{1/36,2/36/,3/36,4/36,5/36,6/36,5/36,4/36,3/36,2/36,1/36\}. -\end{equation*} -!et -!eblock - - -===== Tossing the dice ===== -!bblock -The numbers in the domain are the outcomes of the physical process of tossing say two dice. -We cannot tell beforehand whether the outcome is 3 or 5 or any other number in this domain. -This defines the randomness of the outcome, or unexpectedness or any other synonimous word which -encompasses the uncertitude of the final outcome. - -The only thing we can tell beforehand -is that say the outcome 2 has a certain probability. -If our favorite hobby is to spend an hour every evening throwing dice and -registering the sequence of outcomes, we will note that the numbers in the above domain -!bt -\begin{equation*} -\{2,3,4,5,6,7,8,9,10,11,12\}, -\end{equation*} -!et -appear in a random order. After 11 throws the results may look like - -!bt -\begin{equation*} -\{10,8,6,3,6,9,11,8,12,4,5\}. -\end{equation*} -!et -!eblock - - -===== Stochastic variables ===== -!bblock - -_Random variables are characterized by a domain which contains all possible values that the random value may take. This domain has a corresponding probability distribution function(PDF)_. -!eblock - - -===== Stochastic variables and the main concepts, the discrete case ===== -!bblock -There are two main concepts associated with a stochastic variable. The -*domain* is the set $\mathbb D = \{x\}$ of all accessible values -the variable can assume, so that $X \in \mathbb D$. An example of a -discrete domain is the set of six different numbers that we may get by -throwing of a dice, $x\in\{1,\,2,\,3,\,4,\,5,\,6\}$. - -The *probability distribution function (PDF)* is a function -$p(x)$ on the domain which, in the discrete case, gives us the -probability or relative frequency with which these values of $X$ -occur -!bt -\begin{equation*} -p(x) = \mathrm{Prob}(X=x). -\end{equation*} -!et -!eblock - - - -===== Stochastic variables and the main concepts, the continuous case ===== -!bblock -In the continuous case, the PDF does not directly depict the -actual probability. Instead we define the probability for the -stochastic variable to assume any value on an infinitesimal interval -around $x$ to be $p(x)dx$. The continuous function $p(x)$ then gives us -the *density* of the probability rather than the probability -itself. The probability for a stochastic variable to assume any value -on a non-infinitesimal interval $[a,\,b]$ is then just the integral - -!bt -\begin{equation*} -\mathrm{Prob}(a\leq X\leq b) = \int_a^b p(x)dx. -\end{equation*} -!et -Qualitatively speaking, a stochastic variable represents the values of -numbers chosen as if by chance from some specified PDF so that the -selection of a large set of these numbers reproduces this PDF. -!eblock - - -===== The cumulative probability ===== -!bblock -Of interest to us is the *cumulative probability -distribution function* (_CDF_), $P(x)$, which is just the probability -for a stochastic variable $X$ to assume any value less than $x$ -!bt -\begin{equation*} -P(x)=\mathrm{Prob(}X\leq x\mathrm{)} = -\int_{-\infty}^x p(x^{\prime})dx^{\prime}. -\end{equation*} -!et -The relation between a CDF and its corresponding PDF is then - -!bt -\begin{equation*} -p(x) = \frac{d}{dx}P(x). -\end{equation*} -!et -!eblock - - -===== Properties of PDFs ===== -!bblock - -There are two properties that all PDFs must satisfy. The first one is -positivity (assuming that the PDF is normalized) - -!bt -\begin{equation*} -0 \leq p(x) \leq 1. -\end{equation*} -!et -Naturally, it would be nonsensical for any of the values of the domain -to occur with a probability greater than $1$ or less than $0$. Also, -the PDF must be normalized. That is, all the probabilities must add up -to unity. The probability of ``anything'' to happen is always unity. For -both discrete and continuous PDFs, this condition is -!bt -\begin{align*} -\sum_{x_i\in\mathbb D} p(x_i) & = 1,\\ -\int_{x\in\mathbb D} p(x)\,dx & = 1. -\end{align*} -!et -!eblock - - -===== Important distributions, the uniform distribution ===== -!bblock -The first one -is the most basic PDF; namely the uniform distribution -!bt -\begin{equation} -p(x) = \frac{1}{b-a}\theta(x-a)\theta(b-x). -label{eq:unifromPDF} -\end{equation} -!et -For $a=0$ and $b=1$ we have -!bt -\[ -\begin{array}{ll} -p(x)dx = dx & \in [0,1]. -\end{array} -\] -!et -The latter distribution is used to generate random numbers. For other PDFs, one needs normally a mapping from this distribution to say for example the exponential distribution. -!eblock - - -===== Gaussian distribution ===== -!bblock -The second one is the Gaussian Distribution -!bt -\begin{equation*} -p(x) = \frac{1}{\sigma\sqrt{2\pi}} \exp{(-\frac{(x-\mu)^2}{2\sigma^2})}, -\end{equation*} -!et -with mean value $\mu$ and standard deviation $\sigma$. If $\mu=0$ and $\sigma=1$, it is normally called the _standard normal distribution_ -!bt -\begin{equation*} -p(x) = \frac{1}{\sqrt{2\pi}} \exp{(-\frac{x^2}{2})}, -\end{equation*} -!et - -The following simple Python code plots the above distribution for different values of $\mu$ and $\sigma$. -!bc pyscpro -import numpy as np -from math import acos, exp, sqrt -from matplotlib import pyplot as plt -from matplotlib import rc, rcParams -import matplotlib.units as units -import matplotlib.ticker as ticker -rc('text',usetex=True) -rc('font',**{'family':'serif','serif':['Gaussian distribution']}) -font = {'family' : 'serif', - 'color' : 'darkred', - 'weight' : 'normal', - 'size' : 16, - } -pi = acos(-1.0) -mu0 = 0.0 -sigma0 = 1.0 -mu1= 1.0 -sigma1 = 2.0 -mu2 = 2.0 -sigma2 = 4.0 - -x = np.linspace(-20.0, 20.0) -v0 = np.exp(-(x*x-2*x*mu0+mu0*mu0)/(2*sigma0*sigma0))/sqrt(2*pi*sigma0*sigma0) -v1 = np.exp(-(x*x-2*x*mu1+mu1*mu1)/(2*sigma1*sigma1))/sqrt(2*pi*sigma1*sigma1) -v2 = np.exp(-(x*x-2*x*mu2+mu2*mu2)/(2*sigma2*sigma2))/sqrt(2*pi*sigma2*sigma2) -plt.plot(x, v0, 'b-', x, v1, 'r-', x, v2, 'g-') -plt.title(r'{\bf Gaussian distributions}', fontsize=20) -plt.text(-19, 0.3, r'Parameters: $\mu = 0$, $\sigma = 1$', fontdict=font) -plt.text(-19, 0.18, r'Parameters: $\mu = 1$, $\sigma = 2$', fontdict=font) -plt.text(-19, 0.08, r'Parameters: $\mu = 2$, $\sigma = 4$', fontdict=font) -plt.xlabel(r'$x$',fontsize=20) -plt.ylabel(r'$p(x)$ [MeV]',fontsize=20) - -# Tweak spacing to prevent clipping of ylabel -plt.subplots_adjust(left=0.15) -plt.savefig('gaussian.pdf', format='pdf') -plt.show() -!ec -!eblock - - - -===== Exponential distribution ===== -!bblock -Another important distribution in science is the exponential distribution -!bt -\begin{equation*} -p(x) = \alpha\exp{-(\alpha x)}. -\end{equation*} -!et -!eblock - - -===== Expectation values ===== -!bblock -Let $h(x)$ be an arbitrary continuous function on the domain of the stochastic -variable $X$ whose PDF is $p(x)$. We define the *expectation value* -of $h$ with respect to $p$ as follows - -!bt -\begin{equation} -\langle h \rangle_X \equiv \int\! h(x)p(x)\,dx -label{eq:expectation_value_of_h_wrt_p} -\end{equation} -!et -Whenever the PDF is known implicitly, like in this case, we will drop -the index $X$ for clarity. -A particularly useful class of special expectation values are the -*moments*. The $n$-th moment of the PDF $p$ is defined as -follows -!bt -\begin{equation*} -\langle x^n \rangle \equiv \int\! x^n p(x)\,dx -\end{equation*} -!et -!eblock - - -===== Stochastic variables and the main concepts, mean values ===== -!bblock -The zero-th moment $\langle 1\rangle$ is just the normalization condition of -$p$. The first moment, $\langle x\rangle$, is called the *mean* of $p$ -and often denoted by the letter $\mu$ -!bt -\begin{equation*} -\langle x\rangle = \mu \equiv \int x p(x)dx, -\end{equation*} -!et -for a continuous distribution and -!bt -\begin{equation*} -\langle x\rangle = \mu \equiv \sum_{i=1}^N x_i p(x_i), -\end{equation*} -!et -for a discrete distribution. -Qualitatively it represents the centroid or the average value of the -PDF and is therefore simply called the expectation value of $p(x)$. -!eblock - - -===== Stochastic variables and the main concepts, central moments, the variance ===== -!bblock - -A special version of the moments is the set of *central moments*, the n-th central moment defined as -!bt -\begin{equation*} -\langle (x-\langle x\rangle )^n\rangle \equiv \int\! (x-\langle x\rangle)^n p(x)\,dx -\end{equation*} -!et -The zero-th and first central moments are both trivial, equal $1$ and -$0$, respectively. But the second central moment, known as the -*variance* of $p$, is of particular interest. For the stochastic -variable $X$, the variance is denoted as $\sigma^2_X$ or $\mathrm{Var}(X)$ -!bt -\begin{align*} -\sigma^2_X &=\mathrm{Var}(X) = \langle (x-\langle x\rangle)^2\rangle = -\int (x-\langle x\rangle)^2 p(x)dx\\ -& = \int\left(x^2 - 2 x \langle x\rangle^{2} +\langle x\rangle^2\right)p(x)dx\\ -& = \langle x^2\rangle - 2 \langle x\rangle\langle x\rangle + \langle x\rangle^2\\ -& = \langle x^2 \rangle - \langle x\rangle^2 -\end{align*} -!et -The square root of the variance, $\sigma =\sqrt{\langle (x-\langle x\rangle)^2\rangle}$ is called the -_standard deviation_ of $p$. It is the RMS (root-mean-square) -value of the deviation of the PDF from its mean value, interpreted -qualitatively as the ``spread'' of $p$ around its mean. -!eblock - - - - -===== Probability Distribution Functions ===== -!bblock - -The following table collects properties of probability distribution functions. -In our notation we reserve the label $p(x)$ for the probability of a certain event, -while $P(x)$ is the cumulative probability. - - -|--------------------------------------------------------------------------------------------------------------------------------------| -| | Discrete PDF | Continuous PDF | -|---------------------l-------------------------------------------c-------------------------------------------c------------------------| -| Domain | $\left\{x_1, x_2, x_3, \dots, x_N\right\}$ | $[a,b]$ | -| Probability | $p(x_i)$ | $p(x)dx$ | -| Cumulative | $P_i=\sum_{l=1}^ip(x_l)$ | $P(x)=\int_a^xp(t)dt$ | -| Positivity | $0 \le p(x_i) \le 1$ | $p(x) \ge 0$ | -| Positivity | $0 \le P_i \le 1$ | $0 \le P(x) \le 1$ | -| Monotonic | $P_i \ge P_j$ if $x_i \ge x_j$ | $P(x_i) \ge P(x_j)$ if $x_i \ge x_j$ | -| Normalization | $P_N=1$ | $P(b)=1$ | -|--------------------------------------------------------------------------------------------------------------------------------------| - -!eblock - - - -===== Probability Distribution Functions ===== -!bblock -With a PDF we can compute expectation values of selected quantities such as - -!bt -\begin{equation*} - \langle x^k\rangle=\sum_{i=1}^{N}x_i^kp(x_i), -\end{equation*} -!et -if we have a discrete PDF or - -!bt -\begin{equation*} - \langle x^k\rangle=\int_a^b x^kp(x)dx, -\end{equation*} -!et -in the case of a continuous PDF. We have already defined the mean value $\mu$ -and the variance $\sigma^2$. -!eblock - - -===== The three famous Probability Distribution Functions ===== -!bblock - -There are at least three PDFs which one may encounter. These are the - -_Uniform distribution_ -!bt -\begin{equation*} -p(x)=\frac{1}{b-a}\Theta(x-a)\Theta(b-x), -\end{equation*} -!et -yielding probabilities different from zero in the interval $[a,b]$. - -_The exponential distribution_ -!bt -\begin{equation*} -p(x)=\alpha \exp{(-\alpha x)}, -\end{equation*} -!et -yielding probabilities different from zero in the interval $[0,\infty)$ and with mean value -!bt -\begin{equation*} -\mu = \int_0^{\infty}xp(x)dx=\int_0^{\infty}x\alpha \exp{(-\alpha x)}dx=\frac{1}{\alpha}, -\end{equation*} -!et -!eblock -with variance -!bt -\begin{equation*} -\sigma^2=\int_0^{\infty}x^2p(x)dx-\mu^2 = \frac{1}{\alpha^2}. -\end{equation*} -!et - - -===== Probability Distribution Functions, the normal distribution ===== -!bblock -Finally, we have the so-called univariate normal distribution, or just the _normal distribution_ -!bt -\begin{equation*} -p(x)=\frac{1}{b\sqrt{2\pi}}\exp{\left(-\frac{(x-a)^2}{2b^2}\right)} -\end{equation*} -!et -with probabilities different from zero in the interval $(-\infty,\infty)$. -The integral $\int_{-\infty}^{\infty}\exp{\left(-(x^2\right)}dx$ appears in many calculations, its value -is $\sqrt{\pi}$, a result we will need when we compute the mean value and the variance. -The mean value is -!bt -\begin{equation*} - \mu = \int_0^{\infty}xp(x)dx=\frac{1}{b\sqrt{2\pi}}\int_{-\infty}^{\infty}x \exp{\left(-\frac{(x-a)^2}{2b^2}\right)}dx, -\end{equation*} -!et -which becomes with a suitable change of variables -!bt -\begin{equation*} - \mu =\frac{1}{b\sqrt{2\pi}}\int_{-\infty}^{\infty}b\sqrt{2}(a+b\sqrt{2}y)\exp{-y^2}dy=a. -\end{equation*} -!et -!eblock - - -===== Probability Distribution Functions, the normal distribution ===== -!bblock -Similarly, the variance becomes -!bt -\begin{equation*} - \sigma^2 = \frac{1}{b\sqrt{2\pi}}\int_{-\infty}^{\infty}(x-\mu)^2 \exp{\left(-\frac{(x-a)^2}{2b^2}\right)}dx, -\end{equation*} -!et -and inserting the mean value and performing a variable change we obtain - -!bt -\begin{equation*} - \sigma^2 = \frac{1}{b\sqrt{2\pi}}\int_{-\infty}^{\infty}b\sqrt{2}(b\sqrt{2}y)^2\exp{\left(-y^2\right)}dy= -\frac{2b^2}{\sqrt{\pi}}\int_{-\infty}^{\infty}y^2\exp{\left(-y^2\right)}dy, -\end{equation*} -!et -and performing a final integration by parts we obtain the well-known result $\sigma^2=b^2$. -It is useful to introduce the standard normal distribution as well, defined by $\mu=a=0$, viz. a distribution -centered around zero and with a variance $\sigma^2=1$, leading to - -!bt -\begin{equation} - p(x)=\frac{1}{\sqrt{2\pi}}\exp{\left(-\frac{x^2}{2}\right)}. -\end{equation} -!et -!eblock - - -===== Probability Distribution Functions, the cumulative distribution ===== -!bblock - -The exponential and uniform distributions have simple cumulative functions, -whereas the normal distribution does not, being proportional to the so-called -error function $erf(x)$, given by - -!bt -\begin{equation*} -P(x) = \frac{1}{\sqrt{2\pi}}\int_{-\infty}^x\exp{\left(-\frac{t^2}{2}\right)}dt, -\end{equation*} -!et -which is difficult to evaluate in a quick way. -!eblock - - - -===== Probability Distribution Functions, other important distribution ===== -!bblock - -Some other PDFs which one encounters often in the natural sciences are the binomial distribution -!bt -\begin{equation*} - p(x) = \left(\begin{array}{c} n \\ x\end{array}\right)y^x(1-y)^{n-x} \hspace{0.5cm}x=0,1,\dots,n, -\end{equation*} -!et -where $y$ is the probability for a specific event, such as the tossing of a coin or moving left or right -in case of a random walker. Note that $x$ is a discrete stochastic variable. - -The sequence of binomial trials is characterized by the following definitions - - * Every experiment is thought to consist of $N$ independent trials. - - * In every independent trial one registers if a specific situation happens or not, such as the jump to the left or right of a random walker. - - * The probability for every outcome in a single trial has the same value, for example the outcome of tossing (either heads or tails) a coin is always $1/2$. -!eblock - - -===== Probability Distribution Functions, the binomial distribution ===== -!bblock - -In order to compute the mean and variance we need to recall Newton's binomial -formula -!bt -\begin{equation*} - (a+b)^m=\sum_{n=0}^m \left(\begin{array}{c} m \\ n\end{array}\right)a^nb^{m-n}, -\end{equation*} -!et -which can be used to show that - -!bt -\begin{equation*} -\sum_{x=0}^n\left(\begin{array}{c} n \\ x\end{array}\right)y^x(1-y)^{n-x} = (y+1-y)^n = 1, -\end{equation*} -!et -the PDF is normalized to one. -The mean value is -!bt -\begin{equation*} -\mu = \sum_{x=0}^n x\left(\begin{array}{c} n \\ x\end{array}\right)y^x(1-y)^{n-x} = -\sum_{x=0}^n x\frac{n!}{x!(n-x)!}y^x(1-y)^{n-x}, -\end{equation*} -!et -resulting in -!bt -\begin{equation*} -\mu = -\sum_{x=0}^n x\frac{(n-1)!}{(x-1)!(n-1-(x-1))!}y^{x-1}(1-y)^{n-1-(x-1)}, -\end{equation*} -!et -which we rewrite as - -!bt -\begin{equation*} -\mu=ny\sum_{\nu=0}^n\left(\begin{array}{c} n-1 \\ \nu\end{array}\right)y^{\nu}(1-y)^{n-1-\nu} =ny(y+1-y)^{n-1}=ny. -\end{equation*} -!et -!eblock -The variance is slightly trickier to get. It reads $\sigma^2=ny(1-y)$. - - -===== Probability Distribution Functions, Poisson's distribution ===== -!bblock - -Another important distribution with discrete stochastic variables $x$ is -the Poisson model, which resembles the exponential distribution and reads -!bt -\begin{equation*} - p(x) = \frac{\lambda^x}{x!} e^{-\lambda} \hspace{0.5cm}x=0,1,\dots,;\lambda > 0. -\end{equation*} -!et -In this case both the mean value and the variance are easier to calculate, - -!bt -\begin{equation*} -\mu = \sum_{x=0}^{\infty} x \frac{\lambda^x}{x!} e^{-\lambda} = \lambda e^{-\lambda}\sum_{x=1}^{\infty} -\frac{\lambda^{x-1}}{(x-1)!}=\lambda, -\end{equation*} -!et -and the variance is $\sigma^2=\lambda$. -!eblock - - - - -===== Probability Distribution Functions, Poisson's distribution ===== -!bblock -An example of applications of the Poisson distribution could be the counting -of the number of $\alpha$-particles emitted from a radioactive source in a given time interval. -In the limit of $n\rightarrow \infty$ and for small probabilities $y$, the binomial distribution -approaches the Poisson distribution. Setting $\lambda = ny$, with $y$ the probability for an event in -the binomial distribution we can show that - -!bt -\begin{equation*} -\lim_{n\rightarrow \infty}\left(\begin{array}{c} n \\ x\end{array}\right)y^x(1-y)^{n-x} e^{-\lambda}=\sum_{x=1}^{\infty}\frac{\lambda^x}{x!} e^{-\lambda}. -\end{equation*} -!et -!eblock - - - -===== Meet the covariance! ===== -!bblock -An important quantity in a statistical analysis is the so-called covariance. - -Consider the set $\{X_i\}$ of $n$ -stochastic variables (not necessarily uncorrelated) with the -multivariate PDF $P(x_1,\dots,x_n)$. The *covariance* of two -of the stochastic variables, $X_i$ and $X_j$, is defined as follows - -!bt -\begin{align} -\mathrm{Cov}(X_i,\,X_j) & = \langle (x_i-\langle x_i\rangle)(x_j-\langle x_j\rangle)\rangle \\ -&=\int\cdots\int (x_i-\langle x_i\rangle)(x_j-\langle x_j\rangle)P(x_1,\dots,x_n)\,dx_1\dots dx_n, -label{eq:def_covariance} -\end{align} -!et -with -!bt -\begin{equation*} -\langle x_i\rangle = -\int\cdots\int x_i P(x_1,\dots,x_n)\,dx_1\dots dx_n. -\end{equation*} -!et -!eblock - - - - -===== Meet the covariance in matrix disguise ===== -!bblock -If we consider the above covariance as a matrix -!bt -\[ -C_{ij} =\mathrm{Cov}(X_i,\,X_j), -\] -!et -then the diagonal elements are just the familiar -variances, $C_{ii} = \mathrm{Cov}(X_i,\,X_i) = \mathrm{Var}(X_i)$. It turns out that -all the off-diagonal elements are zero if the stochastic variables are -uncorrelated. -!eblock - - -===== Covariance ===== -!bc pycod -# Importing various packages -from math import exp, sqrt -from random import random, seed -import numpy as np -import matplotlib.pyplot as plt - -def covariance(x, y, n): - sum = 0.0 - mean_x = np.mean(x) - mean_y = np.mean(y) - for i in range(0, n): - sum += (x[(i)]-mean_x)*(y[i]-mean_y) - return sum/n - -n = 10 - -x=np.random.normal(size=n) -y = 4+3*x+np.random.normal(size=n) -covxy = covariance(x,y,n) -print(covxy) -z = np.vstack((x, y)) -c = np.cov(z.T) - -print(c) - -!ec - - - - -===== Meet the covariance, uncorrelated events ===== -!bblock - -Consider the stochastic variables $X_i$ and $X_j$, ($i\neq j$). We have -!bt -\begin{align*} -Cov(X_i,\,X_j) &= \langle (x_i-\langle x_i\rangle)(x_j-\langle x_j\rangle)\rangle\\ -&=\langle x_i x_j - x_i\langle x_j\rangle - \langle x_i\rangle x_j + \langle x_i\rangle\langle x_j\rangle\rangle\\ -&=\langle x_i x_j\rangle - \langle x_i\langle x_j\rangle\rangle - \langle \langle x_i\rangle x_j \rangle + -\langle \langle x_i\rangle\langle x_j\rangle\rangle \\ -&=\langle x_i x_j\rangle - \langle x_i\rangle\langle x_j\rangle - \langle x_i\rangle\langle x_j\rangle + -\langle x_i\rangle\langle x_j\rangle \\ -&=\langle x_i x_j\rangle - \langle x_i\rangle\langle x_j\rangle -\end{align*} -!et -If $X_i$ and $X_j$ are independent (assuming $i \neq j$), we have that -!bt -\[ -\langle x_i x_j\rangle = \langle x_i\rangle\langle x_j\rangle, -\] -!et -leading to -!bt -\[ -Cov(X_i, X_j) = 0 \hspace{0.1cm} (i\neq j). -\] -!et -!eblock - - - - -===== Numerical experiments and the covariance ===== -!bblock - -Now that we have constructed an idealized mathematical framework, let -us try to apply it to empirical observations. Examples of relevant -physical phenomena may be spontaneous decays of nuclei, or a purely -mathematical set of numbers produced by some deterministic -mechanism. It is the latter we will deal with, using so-called pseudo-random -number generators. In general our observations will contain only a limited set of -observables. We remind the reader that -a *stochastic process* is a process that produces sequentially a -chain of values -!bt -\begin{equation*} -\{x_1, x_2,\dots\,x_k,\dots\}. -\end{equation*} -!et -!eblock - - - -===== Numerical experiments and the covariance ===== -!bblock -We will call these -values our *measurements* and the entire set as our measured -*sample*. The action of measuring all the elements of a sample -we will call a stochastic *experiment* (since, operationally, -they are often associated with results of empirical observation of -some physical or mathematical phenomena; precisely an experiment). We -assume that these values are distributed according to some -PDF $p_X^{\phantom X}(x)$, where $X$ is just the formal symbol for the -stochastic variable whose PDF is $p_X^{\phantom X}(x)$. Instead of -trying to determine the full distribution $p$ we are often only -interested in finding the few lowest moments, like the mean -$\mu_X^{\phantom X}$ and the variance $\sigma_X^{\phantom X}$. -!eblock - - - -===== Numerical experiments and the covariance, actual situations ===== -!bblock -In practical situations however, a sample is always of finite size. Let that -size be $n$. The expectation value of a sample $\alpha$, the _sample mean_, is then defined as follows -!bt -\begin{equation*} -\langle x_{\alpha} \rangle \equiv \frac{1}{n}\sum_{k=1}^n x_{\alpha,k}. -\end{equation*} -!et -The *sample variance* is: -!bt -\begin{equation*} -\mathrm{Var}(x) \equiv \frac{1}{n}\sum_{k=1}^n (x_{\alpha,k} - \langle x_{\alpha} \rangle)^2, -\end{equation*} -!et -with its square root being the *standard deviation of the sample*. -!eblock - - - -===== Numerical experiments and the covariance, our observables ===== -!bblock -You can think of the above observables as a set of quantities which define -a given experiment. This experiment is then repeated several times, say $m$ times. -The total average is then -!bt -\begin{equation} -\langle X_m \rangle= \frac{1}{m}\sum_{\alpha=1}^mx_{\alpha}=\frac{1}{mn}\sum_{\alpha, k} x_{\alpha,k}, -label{eq:exptmean} -\end{equation} -!et -where the last sums end at $m$ and $n$. -The total variance is -!bt -\begin{equation*} -\sigma^2_m= \frac{1}{mn^2}\sum_{\alpha=1}^m(\langle x_{\alpha} \rangle-\langle X_m \rangle)^2, -\end{equation*} -!et -which we rewrite as -!bt -\begin{equation} -\sigma^2_m=\frac{1}{m}\sum_{\alpha=1}^m\sum_{kl=1}^n (x_{\alpha,k}-\langle X_m \rangle)(x_{\alpha,l}-\langle X_m \rangle). -label{eq:exptvariance} -\end{equation} -!et -!eblock - - -===== Numerical experiments and the covariance, the sample variance ===== -!bblock - -We define also the sample variance $\sigma^2$ of all $mn$ individual experiments as -!bt -\begin{equation} -\sigma^2=\frac{1}{mn}\sum_{\alpha=1}^m\sum_{k=1}^n (x_{\alpha,k}-\langle X_m \rangle)^2. -label{eq:sampleexptvariance} -\end{equation} -!et - - - -These quantities, being known experimental values or the results from our calculations, -may differ, in some cases -significantly, from the similarly named -exact values for the mean value $\mu_X$, the variance $\mathrm{Var}(X)$ -and the covariance $\mathrm{Cov}(X,Y)$. -!eblock - - -===== Numerical experiments and the covariance, central limit theorem ===== -!bblock - -The central limit theorem states that the PDF $\tilde{p}(z)$ of -the average of $m$ random values corresponding to a PDF $p(x)$ -is a normal distribution whose mean is the -mean value of the PDF $p(x)$ and whose variance is the variance -of the PDF $p(x)$ divided by $m$, the number of values used to compute $z$. - -The central limit theorem leads then to the well-known expression for the -standard deviation, given by -!bt -\begin{equation*} - \sigma_m= -\frac{\sigma}{\sqrt{m}}. -\end{equation*} -!et - -In many cases the above estimate for the standard deviation, in particular if correlations are strong, may be too simplistic. We need therefore a more precise defintion of the error and the variance in our results. -!eblock - - -===== Definition of Correlation Functions and Standard Deviation ===== -!bblock -Our estimate of the true average $\mu_{X}$ is the sample mean $\langle X_m \rangle$ - -!bt -\begin{equation*} -\mu_{X}^{\phantom X} \approx X_m=\frac{1}{mn}\sum_{\alpha=1}^m\sum_{k=1}^n x_{\alpha,k}. -\end{equation*} -!et - - -We can then use Eq. (ref{eq:exptvariance}) -!bt -\begin{equation*} -\sigma^2_m=\frac{1}{mn^2}\sum_{\alpha=1}^m\sum_{kl=1}^n (x_{\alpha,k}-\langle X_m \rangle)(x_{\alpha,l}-\langle X_m \rangle), -\end{equation*} -!et -and rewrite it as -!bt -\begin{equation*} -\sigma^2_m=\frac{\sigma^2}{n}+\frac{2}{mn^2}\sum_{\alpha=1}^m\sum_{k -#include -#include -#include -using namespace std; -// output file as global variable -ofstream ofile; - -// Main function begins here -int main(int argc, char* argv[]) -{ - int n; - char *outfilename; - - cin >> n; - double MCint = 0.; double MCintsqr2=0.; - double invers_period = 1./RAND_MAX; // initialise the random number generator - srand(time(NULL)); // This produces the so-called seed in MC jargon - // Compute the variance and the mean value of the uniform distribution - // Compute also the specific values x for each cycle in order to be able to - // the covariance and the correlation function - // Read in output file, abort if there are too few command-line arguments - if( argc <= 2 ){ - cout << "Bad Usage: " << argv[0] << - " read also output file and number of cycles on same line" << endl; - exit(1); - } - else{ - outfilename=argv[1]; - } - ofile.open(outfilename); - // Get the number of Monte-Carlo samples - n = atoi(argv[2]); - double *X; - X = new double[n]; - for (int i = 0; i < n; i++){ - double x = double(rand())*invers_period; - X[i] = x; - MCint += x; - MCintsqr2 += x*x; - } - double Mean = MCint/((double) n ); - MCintsqr2 = MCintsqr2/((double) n ); - double STDev = sqrt(MCintsqr2-Mean*Mean); - double Variance = MCintsqr2-Mean*Mean; -// Write mean value and standard deviation - cout << " Standard deviation= " << STDev << " Integral = " << Mean << endl; - - // Now we compute the autocorrelation function - double *autocor; autocor = new double[n]; - for (int j = 0; j < n; j++){ - double sum = 0.0; - for (int k = 0; k < (n-j); k++){ - sum += (X[k]-Mean)*(X[k+j]-Mean); - } - autocor[j] = sum/Variance/((double) n ); - ofile << setiosflags(ios::showpoint | ios::uppercase); - ofile << setw(15) << setprecision(8) << j; - ofile << setw(15) << setprecision(8) << autocor[j] << endl; - } - ofile.close(); // close output file - return 0; -} // end of main program -!ec -!eblock - - - - -======= Which RNG should I use? ======= -!bblock -* C++ has a class called _random_. The "random class":"http://www.cplusplus.com/reference/random/" contains a large selection of RNGs and is highly recommended. Some of these RNGs have very large periods making it thereby very safe to use these RNGs in case one is performing large calculations. In particular, the "Mersenne twister random number engine":"http://www.cplusplus.com/reference/random/mersenne_twister_engine/" has a period of $2^{19937}$. -* Add RNGs in Python - -!eblock - - - -===== How to use the Mersenne generator ===== -!bblock -The following part of a c++ code (from project 4) sets up the uniform distribution for $x\in [0,1]$. -!bc cppcod -/* - -// You need this -#include - -// Initialize the seed and call the Mersienne algo -std::random_device rd; -std::mt19937_64 gen(rd()); -// Set up the uniform distribution for x \in [[0, 1] -std::uniform_real_distribution RandomNumberGenerator(0.0,1.0); - -// Now use the RNG -int ix = (int) (RandomNumberGenerator(gen)*NSpins); -!ec -!eblock - - - - - -===== Why blocking? ===== -!bblock Statistical analysis - * Monte Carlo simulations can be treated as *computer experiments* - * The results can be analysed with the same statistical tools as we would use analysing experimental data. - * As in all experiments, we are looking for expectation values and an estimate of how accurate they are, i.e., possible sources for errors. - -A very good article which explains blocking is H. Flyvbjerg and H. G. Petersen, *Error estimates on averages of correlated data*, "Journal of Chemical Physics 91, 461-466 (1989)":"http://scitation.aip.org/content/aip/journal/jcp/91/1/10.1063/1.457480". - -!eblock - - - - -===== Why blocking? ===== -!bblock Statistical analysis - * As in other experiments, Monte Carlo experiments have two classes of errors: - * Statistical errors - * Systematical errors - * Statistical errors can be estimated using standard tools from statistics - * Systematical errors are method specific and must be treated differently from case to case. (In VMC a common source is the step length or time step in importance sampling) -!eblock - - - -===== Code to demonstrate the calculation of the autocorrelation function ===== -The following code computes the autocorrelation function, the covariance and the standard deviation -for standard RNG. -The "following file":"https://github.com/CompPhysics/ComputationalPhysics2/tree/gh-pages/doc/Programs/LecturePrograms/programs/Blocking/autocorrelation.cpp" gives the code. -!bc cppcod -// This function computes the autocorrelation function for -// the Mersenne random number generator with a uniform distribution -#include -#include -#include -#include -#include -#include -#include -#include -using namespace std; -using namespace arma; -// output file -ofstream ofile; - -// Main function begins here -int main(int argc, char* argv[]) -{ - int MonteCarloCycles; - string filename; - if (argc > 1) { - filename=argv[1]; - MonteCarloCycles = atoi(argv[2]); - string fileout = filename; - string argument = to_string(MonteCarloCycles); - fileout.append(argument); - ofile.open(fileout); - } - - // Compute the variance and the mean value of the uniform distribution - // Compute also the specific values x for each cycle in order to be able to - // compute the covariance and the correlation function - - vec X = zeros(MonteCarloCycles); - double MCint = 0.; double MCintsqr2=0.; - std::random_device rd; - std::mt19937_64 gen(rd()); - // Set up the uniform distribution for x \in [[0, 1] - std::uniform_real_distribution RandomNumberGenerator(0.0,1.0); - for (int i = 0; i < MonteCarloCycles; i++){ - double x = RandomNumberGenerator(gen); - X(i) = x; - MCint += x; - MCintsqr2 += x*x; - } - double Mean = MCint/((double) MonteCarloCycles ); - MCintsqr2 = MCintsqr2/((double) MonteCarloCycles ); - double STDev = sqrt(MCintsqr2-Mean*Mean); - double Variance = MCintsqr2-Mean*Mean; - // Write mean value and variance - cout << " Sample variance= " << Variance << " Mean value = " << Mean << endl; - // Now we compute the autocorrelation function - vec autocorrelation = zeros(MonteCarloCycles); - for (int j = 0; j < MonteCarloCycles; j++){ - double sum = 0.0; - for (int k = 0; k < (MonteCarloCycles-j); k++){ - sum += (X(k)-Mean)*(X(k+j)-Mean); - } - autocorrelation(j) = sum/Variance/((double) MonteCarloCycles ); - ofile << setiosflags(ios::showpoint | ios::uppercase); - ofile << setw(15) << setprecision(8) << j; - ofile << setw(15) << setprecision(8) << autocorrelation(j) << endl; - } - // Now compute the exact covariance using the autocorrelation function - double Covariance = 0.0; - for (int j = 0; j < MonteCarloCycles; j++){ - Covariance += autocorrelation(j); - } - Covariance *= 2.0/((double) MonteCarloCycles); - // Compute now the total variance, including the covariance, and obtain the standard deviation - double TotalVariance = (Variance/((double) MonteCarloCycles ))+Covariance; - cout << "Covariance =" << Covariance << "Totalvariance= " << TotalVariance << "Sample Variance/n= " << (Variance/((double) MonteCarloCycles )) << endl; - cout << " STD from sample variance= " << sqrt(Variance/((double) MonteCarloCycles )) << " STD with covariance = " << sqrt(TotalVariance) << endl; - - ofile.close(); // close output file - return 0; -} // end of main program - - -!ec - - - -===== What is blocking? ===== -!bblock Blocking - * Say that we have a set of samples from a Monte Carlo experiment - * Assuming (wrongly) that our samples are uncorrelated our best estimate of the standard deviation of the mean $\langle \mathbf{M}\rangle$ is given by -!bt -\[ -\sigma=\sqrt{\frac{1}{n}\left(\langle \mathbf{M}^2\rangle-\langle \mathbf{M}\rangle^2\right)} -\] -!et - * If the samples are correlated we can rewrite our results to show that -!bt -\[ -\sigma=\sqrt{\frac{1+2\tau/\Delta t}{n}\left(\langle \mathbf{M}^2\rangle-\langle \mathbf{M}\rangle^2\right)} -\] -!et - where $\tau$ is the correlation time (the time between a sample and the next uncorrelated sample) and $\Delta t$ is time between each sample -!eblock - - -===== What is blocking? ===== -!bblock Blocking - * If $\Delta t\gg\tau$ our first estimate of $\sigma$ still holds - * Much more common that $\Delta t<\tau$ - * In the method of data blocking we divide the sequence of samples into blocks - * We then take the mean $\langle \mathbf{M}_i\rangle$ of block $i=1\ldots n_{blocks}$ to calculate the total mean and variance - * The size of each block must be so large that sample $j$ of block $i$ is not correlated with sample $j$ of block $i+1$ - * The correlation time $\tau$ would be a good choice -!eblock - - -===== What is blocking? ===== -!bblock Blocking - * Problem: We don't know $\tau$ or it is too expensive to compute - * Solution: Make a plot of std. dev. as a function of blocksize - * The estimate of std. dev. of correlated data is too low $\to$ the error will increase with increasing block size until the blocks are uncorrelated, where we reach a plateau - * When the std. dev. stops increasing the blocks are uncorrelated -!eblock - - -===== Implementation ===== -!bblock - * Do a Monte Carlo simulation, storing all samples to file - * Do the statistical analysis on this file, independently of your Monte Carlo program - * Read the file into an array - * Loop over various block sizes - * For each block size $n_b$, loop over the array in steps of $n_b$ taking the mean of elements $i n_b,\ldots,(i+1) n_b$ - * Take the mean and variance of the resulting array - * Write the results for each block size to file for later - analysis -!eblock - - - - - - -===== Actual implementation with code, main function ===== -When the file gets large, it can be useful to write your data in binary mode instead of ascii characters. -The "following python file":"https://github.com/CompPhysics/MachineLearning/blob/master/doc/Programs/Sampling/analysis.py" reads data from file with the output from every Monte Carlo cycle. -!bc pycod -# Blocking - @timeFunction - def blocking(self, blockSizeMax = 500): - blockSizeMin = 1 - - self.blockSizes = [] - self.meanVec = [] - self.varVec = [] - - for i in range(blockSizeMin, blockSizeMax): - if(len(self.data) % i != 0): - pass#continue - blockSize = i - meanTempVec = [] - varTempVec = [] - startPoint = 0 - endPoint = blockSize - - while endPoint <= len(self.data): - meanTempVec.append(np.average(self.data[startPoint:endPoint])) - startPoint = endPoint - endPoint += blockSize - mean, var = np.average(meanTempVec), np.var(meanTempVec)/len(meanTempVec) - self.meanVec.append(mean) - self.varVec.append(var) - self.blockSizes.append(blockSize) - - self.blockingAvg = np.average(self.meanVec[-200:]) - self.blockingVar = (np.average(self.varVec[-200:])) - self.blockingStd = np.sqrt(self.blockingVar) - -!ec - - - - - -===== The Bootstrap method ===== - -The Bootstrap resampling method is also very popular. It is very simple: - -o Start with your sample of measurements and compute the sample variance and the mean values -o Then start again but pick in a random way the numbers in the sample and recalculate the mean and the sample variance. -o Repeat this $K$ times. - -It can be shown, see the article by "Efron":"https://projecteuclid.org/download/pdf_1/euclid.aos/1176344552" -that it produces the correct standard deviation. - -This method is very useful for small ensembles of data points. - - -===== Bootstrapping ===== -Given a set of $N$ data, assume that we are interested in some -observable $\theta$ which may be estimated from that set. This observable can also be for example the result of a fit based on all $N$ raw data. -Let us call the value of the observable obtained from the original -data set $\hat{\theta}$. One recreates from the sample repeatedly -other samples by choosing randomly $N$ data out of the original set. -This costs essentially nothing, since we just recycle the original data set for the building of new sets. - - -===== Bootstrapping, recipe ===== -Let us assume we have done this $K$ times and thus have $K$ sets of $N$ -data values each. -Of course some values will enter more than once in the new sets. For each of these sets one computes the observable $\theta$ resulting in values $\theta_k$ with $k = 1,...,K$. Then one determines -!bt -\[ -\tilde{\theta} = \frac{1}{K} \sum_{k=1}^K \theta_k, -\] -!et -and -!bt -\[ -sigma^2_{\tilde{\theta}} = \frac{1}{K} \sum_{k=1}^K \left(\theta_k-\tilde{\theta}\right)^2. -\] -!et - -These are estimators for $\angle\theta\rangle$ and its variance. They are not unbiased and therefore -$\tilde{\theta}\neq\hat{\theta}$ for finite K. - -The difference is called bias and gives an idea on how far away the result may be from -the true $\angle\theta\rangle$. As final result for the observable one quotes $\angle\theta\rangle = \tilde{\theta} \pm \sigma_{\tilde{\theta}}$ . - - - -===== Bootstrapping, "code":"https://github.com/CompPhysics/MachineLearning/blob/master/doc/Programs/Sampling/analysis.py" ===== -!bc -# Bootstrap - @timeFunction - def bootstrap(self, nBoots = 1000): - bootVec = np.zeros(nBoots) - for k in range(0,nBoots): - bootVec[k] = np.average(np.random.choice(self.data, len(self.data))) - self.bootAvg = np.average(bootVec) - self.bootVar = np.var(bootVec) - self.bootStd = np.std(bootVec) -!ec - - -===== Jackknife, "code":"https://github.com/CompPhysics/MachineLearning/blob/master/doc/Programs/Sampling/analysis.py" ===== -!bc -# Jackknife - @timeFunction - def jackknife(self): - jackknVec = np.zeros(len(self.data)) - for k in range(0,len(self.data)): - jackknVec[k] = np.average(np.delete(self.data, k)) - self.jackknAvg = self.avg - (len(self.data) - 1) * (np.average(jackknVec) - self.avg) - self.jackknVar = float(len(self.data) - 1) * np.var(jackknVec) - self.jackknStd = np.sqrt(self.jackknVar) -!ec - - - - - - -======= Regression analysis, overarching aims ======= -!bblock - -Regression modeling deals with the description of the sampling distribution of a given random variable $y$ varies as function of another variable or a set of such variables $\hat{x} =[x_0, x_1,\dots, x_p]^T$. -The first variable is called the _dependent_, the _outcome_ or the _response_ variable while the set of variables $\hat{x}$ is called the independent variable, or the predictor variable or the explanatory variable. - -A regression model aims at finding a likelihood function $p(y\vert \hat{x})$, that is the conditional distribution for $y$ with a given $\hat{x}$. The estimation of $p(y\vert \hat{x})$ is made using a data set with -* $n$ cases $i = 0, 1, 2, \dots, n-1$ -* Response (dependent or outcome) variable $y_i$ with $i = 0, 1, 2, \dots, n-1$ -* $p$ Explanatory (independent or predictor) variables $\hat{x}_i=[x_{i0}, x_{i1}, \dots, x_{ip}]$ with $i = 0, 1, 2, \dots, n-1$ - The goal of the regression analysis is to extract/exploit relationship between $y_i$ and $\hat{x}_i$ in or to infer causal dependencies, approximations to the likelihood functions, functional relationships and to make predictions . -!eblock - - -===== Regression analysis, overarching aims II ===== -!bblock - - -Consider an experiment in which $p$ characteristics of $n$ samples are -measured. The data from this experiment are denoted $\mathbf{X}$, with -$\mathbf{X}$ as above. The matrix $\mathbf{X}$ is called the *design -matrix*. Additional information of the samples is available in the -form of $\mathbf{Y}$ (also as above). The variable $\mathbf{Y}$ is -generally referred to as the *response variable*. The aim of -regression analysis is to explain $\mathbf{Y}$ in terms of -$\mathbf{X}$ through a functional relationship like $Y_i = -f(\mathbf{X}_{i,\ast})$. When no prior knowledge on the form of -$f(\cdot)$ is available, it is common to assume a linear relationship -between $\mathbf{X}$ and $\mathbf{Y}$. This assumption gives rise to -the *linear regression model* where $\beta = (\beta_1, \ldots, -\beta_p)^{\top}$ is the *regression parameter*. The parameter -$\beta_j$, $j=1, \ldots, p$, represents the effect size of covariate -$j$ on the response. That is, for each unit change in covariate $j$ -(while keeping the other covariates fixed) the observed change in the -response is equal to $\beta_j$. - -!eblock - - -===== General linear models ===== -!bblock -Before we proceed let us study a case from linear algebra where we aim at fitting a set of data $\hat{y}=[y_0,y_1,\dots,y_{n-1}]$. We could think of these data as a result of an experiment or a complicated numerical experiment. These data are functions of a series of variables $\hat{x}=[x_0,x_1,\dots,x_{n-1}]$, that is $y_i = y(x_i)$ with $i=0,1,2,\dots,n-1$. The variables $x_i$ could represent physical quantities like time, temperature, position etc. We assume that $y(x)$ is a smooth function. - -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 -!bt -\[ -y=y(x) \rightarrow y(x_i)=\tilde{y}_i+\epsilon_i=\sum_{j=0}^{n-1} \beta_i x_i^j+\epsilon_i, -\] -!et -where $\epsilon_i$ is the error in our approximation. - -!eblock - - - -===== Rewriting the fitting procedure as a linear algebra problem ===== -!bblock -For every set of values $y_i,x_i$ we have thus the corresponding set of equations -!bt -\begin{align*} -y_0&=\beta_0+\beta_1x_0^1+\beta_2x_0^2+\dots+\beta_{n-1}x_0^{n-1}+\epsilon_0\\ -y_1&=\beta_0+\beta_1x_1^1+\beta_2x_1^2+\dots+\beta_{n-1}x_1^{n-1}+\epsilon_1\\ -y_2&=\beta_0+\beta_1x_2^1+\beta_2x_2^2+\dots+\beta_{n-1}x_2^{n-1}+\epsilon_2\\ -\dots & \dots \\ -y_{n-1}&=\beta_0+\beta_1x_{n-1}^1+\beta_2x_{n-1}^2+\dots+\beta_1x_{n-1}^{n-1}+\epsilon_{n-1}.\\ -\end{align*} -!et -!eblock - - - -===== Rewriting the fitting procedure as a linear algebra problem, follows ===== -!bblock -Defining the vectors -!bt -\[ -\hat{y} = [y_0,y_1, y_2,\dots, y_{n-1}]^T, -\] -!et -and -!bt -\[ -\hat{\beta} = [\beta_0,\beta_1, \beta_2,\dots, \beta_{n-1}]^T, -\] -!et -and -!bt -\[ -\hat{\epsilon} = [\epsilon_0,\epsilon_1, \epsilon_2,\dots, \epsilon_{n-1}]^T, -\] -!et -and the matrix -!bt -\[ -\hat{X}= -\begin{bmatrix} -1& x_{0}^1 &x_{0}^2& \dots & \dots &x_{0}^{n-1}\\ -1& x_{1}^1 &x_{1}^2& \dots & \dots &x_{1}^{n-1}\\ -1& x_{2}^1 &x_{2}^2& \dots & \dots &x_{2}^{n-1}\\ -\dots& \dots &\dots& \dots & \dots &\dots\\ -1& x_{n-1}^1 &x_{n-1}^2& \dots & \dots &x_{n-1}^{n-1}\\ -\end{bmatrix} -\] -!et -we can rewrite our equations as -!bt -\[ -\hat{y} = \hat{X}\hat{\beta}+\hat{\epsilon}. -\] -!et -!eblock - - - -===== Generalizing the fitting procedure as a linear algebra problem ===== -!bblock -We are obviously not limited to the above polynomial. We could replace the various powers of $x$ with elements of Fourier series, that is, instead of $x_i^j$ we could have $\cos{(j x_i)}$ or $\sin{(j x_i)}$, or time series or other orthogonal functions. -For every set of values $y_i,x_i$ we can then generalize the equations to -!bt -\begin{align*} -y_0&=\beta_0x_{00}+\beta_1x_{01}+\beta_2x_{02}+\dots+\beta_{n-1}x_{0n-1}+\epsilon_0\\ -y_1&=\beta_0x_{10}+\beta_1x_{11}+\beta_2x_{12}+\dots+\beta_{n-1}x_{1n-1}+\epsilon_1\\ -y_2&=\beta_0x_{20}+\beta_1x_{21}+\beta_2x_{22}+\dots+\beta_{n-1}x_{2n-1}+\epsilon_2\\ -\dots & \dots \\ -y_{i}&=\beta_0x_{i0}+\beta_1x_{i1}+\beta_2x_{i2}+\dots+\beta_{n-1}x_{in-1}+\epsilon_i\\ -\dots & \dots \\ -y_{n-1}&=\beta_0x_{n-1,0}+\beta_1x_{n-1,2}+\beta_2x_{n-1,2}+\dots+\beta_1x_{n-1,n-1}+\epsilon_{n-1}.\\ -\end{align*} -!et -!eblock - - - -===== Generalizing the fitting procedure as a linear algebra problem ===== -!bblock -We redefine in turn the matrix $\hat{X}$ as -!bt -\[ -\hat{X}= -\begin{bmatrix} -x_{00}& x_{01} &x_{02}& \dots & \dots &x_{0,n-1}\\ -x_{10}& x_{11} &x_{12}& \dots & \dots &x_{1,n-1}\\ -x_{20}& x_{21} &x_{22}& \dots & \dots &x_{2,n-1}\\ -\dots& \dots &\dots& \dots & \dots &\dots\\ -x_{n-1,0}& x_{n-1,1} &x_{n-1,2}& \dots & \dots &x_{n-1,n-1}\\ -\end{bmatrix} -\] -!et -and without loss of generality we rewrite again our equations as -!bt -\[ -\hat{y} = \hat{X}\hat{\beta}+\hat{\epsilon}. -\] -!et -The left-hand side of this equation forms know. Our error vector $\hat{\epsilon}$ and the parameter vector $\hat{\beta}$ are our unknow quantities. How can we obtain the optimal set of $\beta_i$ values? -!eblock - - - -===== Optimizing our parameters ===== -!bblock -We have defined the matrix $\hat{X}$ -!bt -\begin{align*} -y_0&=\beta_0x_{00}+\beta_1x_{01}+\beta_2x_{02}+\dots+\beta_{n-1}x_{0n-1}+\epsilon_0\\ -y_1&=\beta_0x_{10}+\beta_1x_{11}+\beta_2x_{12}+\dots+\beta_{n-1}x_{1n-1}+\epsilon_1\\ -y_2&=\beta_0x_{20}+\beta_1x_{21}+\beta_2x_{22}+\dots+\beta_{n-1}x_{2n-1}+\epsilon_1\\ -\dots & \dots \\ -y_{i}&=\beta_0x_{i0}+\beta_1x_{i1}+\beta_2x_{i2}+\dots+\beta_{n-1}x_{in-1}+\epsilon_1\\ -\dots & \dots \\ -y_{n-1}&=\beta_0x_{n-1,0}+\beta_1x_{n-1,2}+\beta_2x_{n-1,2}+\dots+\beta_1x_{n-1,n-1}+\epsilon_{n-1}.\\ -\end{align*} -!et -!eblock - - - -===== Optimizing our parameters, more details ===== -!bblock -We well use this matrix to define the approximation $\hat{\tilde{y}}$ via the unknown quantity $\hat{\beta}$ as -!bt -\[ -\hat{\tilde{y}}= \hat{X}\hat{\beta}, -\] -!et -and in order to find the optimal parameters $\beta_i$ instead of solving the above linear algebra problem, we define a function which gives a measure of the spread between the values $y_i$ (which represent hopefully the exact values) and the parametrized values $\tilde{y}_i$, namely -!bt -\[ -Q(\hat{\beta})=\sum_{i=0}^{n-1}\left(y_i-\tilde{y}_i\right)^2=\left(\hat{y}-\hat{\tilde{y}}\right)^T\left(\hat{y}-\hat{\tilde{y}}\right), -\] -!et -or using the matrix $\hat{X}$ as -!bt -\[ -Q(\hat{\beta})=\left(\hat{y}-\hat{X}\hat{\beta}\right)^T\left(\hat{y}-\hat{X}\hat{\beta}\right). -\] -!et -!eblock - - - -===== Interpretations and optimizing our parameters ===== -!bblock -The function -!bt -\[ -Q(\hat{\beta})=\left(\hat{y}-\hat{X}\hat{\beta}\right)^T\left(\hat{y}-\hat{X}\hat{\beta}\right), -\] -!et -can be linked to the variance of the quantity $y_i$ if we interpret the latter as the mean value of for example a numerical experiment. When linking below with the maximum likelihood approach below, we will indeed interpret $y_i$ as a mean value -!bt -\[ -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, -\] -!et -where $\langle y_i \rangle$ is the mean value. Keep in mind also that till now we have treated $y_i$ as the exact value. Normally, the response (dependent or outcome) variable $y_i$ the outcome of a numerical experiment or another type of experiment and is thus only an approximation to the true value. It is then always accompanied by an error estimate, often limited to a statistical error estimate given by the standard deviation discussed earlier. In the discussion here we will treat $y_i$ as our exact value for the response variable. - -In order to find the parameters $\beta_i$ we will then minimize the spread of $Q(\hat{\beta})$ by requiring -!bt -\[ -\frac{\partial Q(\hat{\beta})}{\partial \beta_j} = \frac{\partial }{\partial \beta_j}\left[ \sum_{i=0}^{n-1}\left(y_i-\beta_0x_{i,0}-\beta_1x_{i,1}-\beta_2x_{i,2}-\dots-\beta_{n-1}x_{i,n-1}\right)^2\right]=0, -\] -!et -which results in -!bt -\[ -\frac{\partial Q(\hat{\beta})}{\partial \beta_j} = -2\left[ \sum_{i=0}^{n-1}x_{ij}\left(y_i-\beta_0x_{i,0}-\beta_1x_{i,1}-\beta_2x_{i,2}-\dots-\beta_{n-1}x_{i,n-1}\right)\right]=0, -\] -!et -or in a matrix-vector form as -!bt -\[ -\frac{\partial Q(\hat{\beta})}{\partial \hat{\beta}} = 0 = \hat{X}^T\left( \hat{y}-\hat{X}\hat{\beta}\right). -\] -!et - - -!eblock - - - -===== Interpretations and optimizing our parameters ===== -!bblock -We can rewrite -!bt -\[ -\frac{\partial Q(\hat{\beta})}{\partial \hat{\beta}} = 0 = \hat{X}^T\left( \hat{y}-\hat{X}\hat{\beta}\right), -\] -!et -as -!bt -\[ -\hat{X}^T\hat{y} = \hat{X}^T\hat{X}\hat{\beta}, -\] -!et -and if the matrix $\hat{X}^T\hat{X}$ is invertible we have the solution -!bt -\[ -\hat{\beta} =\left(\hat{X}^T\hat{X}\right)^{-1}\hat{X}^T\hat{y}. -\] -!et - -!eblock - - -===== Interpretations and optimizing our parameters ===== -!bblock -The residuals $\hat{\epsilon}$ are in turn given by -!bt -\[ -\hat{\epsilon} = \hat{y}-\hat{\tilde{y}} = \hat{y}-\hat{X}\hat{\beta}, -\] -!et -and with -!bt -\[ -\hat{X}^T\left( \hat{y}-\hat{X}\hat{\beta}\right)= 0, -\] -!et -we have -!bt -\[ -\hat{X}^T\hat{\epsilon}=\hat{X}^T\left( \hat{y}-\hat{X}\hat{\beta}\right)= 0, -\] -!et -meaning that the solution for $\hat{\beta}$ is the one which minimizes the residuals. Later we will link this with the maximum likelihood approach. - -!eblock - - - -===== The $\chi^2$ function ===== -!bblock - -Normally, the response (dependent or outcome) variable $y_i$ the outcome of a numerical experiment or another type of experiment and is thus only an approximation to the true value. It is then always accompanied by an error estimate, often limited to a statistical error estimate given by the standard deviation discussed earlier. In the discussion here we will treat $y_i$ as our exact value for the response variable. - -Introducing the standard deviation $\sigma_i$ for each measurement $y_i$, we define now the $\chi^2$ function as -!bt -\[ -\chi^2(\hat{\beta})=\sum_{i=0}^{n-1}\frac{\left(y_i-\tilde{y}_i\right)^2}{\sigma_i^2}=\left(\hat{y}-\hat{\tilde{y}}\right)^T\frac{1}{\hat{\Sigma^2}}\left(\hat{y}-\hat{\tilde{y}}\right), -\] -!et -where the matrix $\hat{\Sigma}$ is a diagonal matrix with $\sigma_i$ as matrix elements. - -!eblock - - -===== The $\chi^2$ function ===== -!bblock - -In order to find the parameters $\beta_i$ we will then minimize the spread of $\chi^2(\hat{\beta})$ by requiring -!bt -\[ -\frac{\partial \chi^2(\hat{\beta})}{\partial \beta_j} = \frac{\partial }{\partial \beta_j}\left[ \sum_{i=0}^{n-1}\left(\frac{y_i-\beta_0x_{i,0}-\beta_1x_{i,1}-\beta_2x_{i,2}-\dots-\beta_{n-1}x_{i,n-1}}{\sigma_i}\right)^2\right]=0, -\] -!et -which results in -!bt -\[ -\frac{\partial \chi^2(\hat{\beta})}{\partial \beta_j} = -2\left[ \sum_{i=0}^{n-1}\frac{x_{ij}}{\sigma_i}\left(\frac{y_i-\beta_0x_{i,0}-\beta_1x_{i,1}-\beta_2x_{i,2}-\dots-\beta_{n-1}x_{i,n-1}}{\sigma_i}\right)\right]=0, -\] -!et -or in a matrix-vector form as -!bt -\[ -\frac{\partial \chi^2(\hat{\beta})}{\partial \hat{\beta}} = 0 = \hat{A}^T\left( \hat{b}-\hat{A}\hat{\beta}\right). -\] -!et -where we have defined the matrix $\hat{A} =\hat{X}/\hat{\Sigma}$ with matrix elements $a_{ij} = x_{ij}/\sigma_i$ and the vector $\hat{b}$ with elements $b_i = y_i/\sigma_i$. -!eblock - - -===== The $\chi^2$ function ===== -!bblock - -We can rewrite -!bt -\[ -\frac{\partial \chi^2(\hat{\beta})}{\partial \hat{\beta}} = 0 = \hat{A}^T\left( \hat{b}-\hat{A}\hat{\beta}\right), -\] -!et -as -!bt -\[ -\hat{A}^T\hat{b} = \hat{A}^T\hat{A}\hat{\beta}, -\] -!et -and if the matrix $\hat{A}^T\hat{A}$ is invertible we have the solution -!bt -\[ -\hat{\beta} =\left(\hat{A}^T\hat{A}\right)^{-1}\hat{A}^T\hat{b}. -\] -!et -!eblock - - -===== The $\chi^2$ function ===== -!bblock - -If we then introduce the matrix -!bt -\[ -\hat{H} = \left(\hat{A}^T\hat{A}\right)^{-1}, -\] -!et -we have then the following expression for the parameters $\beta_j$ (the matrix elements of $\hat{H}$ are $h_{ij}$) -!bt -\[ -\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} -\] -!et -We state without proof the expression for the uncertainty in the parameters $\beta_j$ as (we leave this as an exercise) -!bt -\[ -\sigma^2(\beta_j) = \sum_{i=0}^{n-1}\sigma_i^2\left( \frac{\partial \beta_j}{\partial y_i}\right)^2, -\] -!et -resulting in -!bt -\[ -\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}! -\] -!et -!eblock - - -===== The $\chi^2$ function ===== -!bblock -The first step here is to approximate the function $y$ with a first-order polynomial, that is we write -!bt -\[ -y=y(x) \rightarrow y(x_i) \approx \beta_0+\beta_1 x_i. -\] -!et -By computing the derivatives of $\chi^2$ with respect to $\beta_0$ and $\beta_1$ show that these are given by -!bt -\[ -\frac{\partial \chi^2(\hat{\beta})}{\partial \beta_0} = -2\left[ \sum_{i=0}^{n-1}\left(\frac{y_i-\beta_0-\beta_1x_{i}}{\sigma_i^2}\right)\right]=0, -\] -!et -and -!bt -\[ -\frac{\partial \chi^2(\hat{\beta})}{\partial \beta_0} = -2\left[ \sum_{i=0}^{n-1}x_i\left(\frac{y_i-\beta_0-\beta_1x_{i}}{\sigma_i^2}\right)\right]=0. -\] -!et -!eblock - - -===== The $\chi^2$ function ===== -!bblock - -For a linear fit we don't need to invert a matrix!! -Defining -!bt -\[ -\gamma = \sum_{i=0}^{n-1}\frac{1}{\sigma_i^2}, -\] -!et - -!bt -\[ -\gamma_x = \sum_{i=0}^{n-1}\frac{x_{i}}{\sigma_i^2}, -\] -!et -!bt -\[ -\gamma_y = \sum_{i=0}^{n-1}\left(\frac{y_i}{\sigma_i^2}\right), -\] -!et -!bt -\[ -\gamma_{xx} = \sum_{i=0}^{n-1}\frac{x_ix_{i}}{\sigma_i^2}, -\] -!et -!bt -\[ -\gamma_{xy} = \sum_{i=0}^{n-1}\frac{y_ix_{i}}{\sigma_i^2}, -\] -!et -we obtain -!bt -\[ -\beta_0 = \frac{\gamma_{xx}\gamma_y-\gamma_x\gamma_y}{\gamma\gamma_{xx}-\gamma_x^2}, -\] -!et -!bt -\[ -\beta_1 = \frac{\gamma_{xy}\gamma-\gamma_x\gamma_y}{\gamma\gamma_{xx}-\gamma_x^2}. -\] -!et - -This approach (different linear and non-linear regression) suffers often from both being underdetermined and overdetermined in the unknown coefficients $\beta_i$. A better approach is to use the Singular Value Decomposition (SVD) method discussed below. Or using Lasso and Ridge regression. See below. -!eblock - - - - - -===== Simple regression model ===== -We are now ready to write our first program which aims at solving the above linear regression equations. We start with data we have produced ourselves, in this case normally distributed random numbers along the $x$-axis. These numbers define then the value of a function $y(x)=4+3x+N(0,1)$. Thereafter we order the $x$ values and employ our linear regression algorithm to set up the best fit. Here we find it useful to use the numpy function $c\_$ arrays where arrays are stacked along their last axis after being upgraded to at least two dimensions with ones post-pended to the shape. The following examples help in understanding what happens !bc pycod -import numpy as np -print(np.c_[np.array([1,2,3]), np.array([4,5,6])]) -print(np.c_[np.array([[1,2,3]]), 0, 0, np.array([[4,5,6]])]) +import pandas as pd +from IPython.display import display +data = {'First Name': ["Frodo", "Bilbo", "Aragorn II", "Samwise"], + 'Last Name': ["Baggins", "Baggins","Elessar","Gamgee"], + 'Place of birth': ["Shire", "Shire", "Eriador", "Shire"], + 'Date of Birth T.A.': [2968, 2890, 2931, 2980] + } +data_pandas = pd.DataFrame(data) +display(data_pandas) !ec +In the above we have imported _pandas_ with the shorthand _pd_, the latter has become the standard way we import _pandas_. We make then a list of various variables +and reorganize the aboves lists into a _DataFrame_ and then print out a neat table with specific column labels as *Name*, *place of birth* and *date of birth*. +Displaying these results, we see that the indices are given by the default numbers from zero to three. +_pandas_ is extremely flexible and we can easily change the above indices by defining a new type of indexing as +!bc pycod +data_pandas = pd.DataFrame(data,index=['Frodo','Bilbo','Aragorn','Sam']) +display(data_pandas) +!ec +Thereafter we display the content of the row which begins with the index _Aragorn_ +!bc pycod +display(data_pandas.loc['Aragorn']) +!ec + +We can easily append data to this, for example +!bc pycod +new_hobbit = {'First Name': ["Peregrin"], + 'Last Name': ["Took"], + 'Place of birth': ["Shire"], + 'Date of Birth T.A.': [2990] + } +data_pandas=data_pandas.append(pd.DataFrame(new_hobbit, index=['Pippin'])) +display(data_pandas) +!ec + + +Here are other examples where we use the _DataFrame_ functionality to handle arrays, now with more interesting features for us, namely numbers. We set up a matrix +of dimensionality $10\times 5$ and compute the mean value and standard deviation of each column. Similarly, we can perform mathematial operations like squaring the matrix elements and many other operations. !bc pycod -# Importing various packages -from random import random, seed import numpy as np -import matplotlib.pyplot as plt +import pandas as pd +from IPython.display import display +np.random.seed(100) +# setting up a 10 x 5 matrix +rows = 10 +cols = 5 +a = np.random.randn(rows,cols) +df = pd.DataFrame(a) +display(df) +print(df.mean()) +print(df.std()) +display(df**2) +!ec -x = 2*np.random.rand(100,1) -y = 4+3*x+np.random.randn(100,1) +Thereafter we can select specific columns only and plot final results +!bc pycod +df.columns = ['First', 'Second', 'Third', 'Fourth', 'Fifth'] +df.index = np.arange(10) -xb = np.c_[np.ones((100,1)), x] -beta = np.linalg.inv(xb.T.dot(xb)).dot(xb.T).dot(y) -xnew = np.array([[0],[2]]) -xbnew = np.c_[np.ones((2,1)), xnew] -ypredict = xbnew.dot(beta) +display(df) +print(df['Second'].mean() ) +print(df.info()) +print(df.describe()) -plt.plot(xnew, ypredict, "r-") -plt.plot(x, y ,'ro') -plt.axis([0,2.0,0, 15.0]) -plt.xlabel(r'$x$') -plt.ylabel(r'$y$') -plt.title(r'Linear Regression') +from pylab import plt, mpl +plt.style.use('seaborn') +mpl.rcParams['font.family'] = 'serif' + +df.cumsum().plot(lw=2.0, figsize=(10,6)) plt.show() -!ec -We see that, as expected, a linear fit gives a seemingly (from the graph) good representation of the data. - - - - - -===== Simple regression model, now using _scikit-learn_ ===== - - -We can repeat the above algorithm using _scikit-learn_ as follows -!bc pycod -# Importing various packages -from random import random, seed -import numpy as np -import matplotlib.pyplot as plt -from sklearn.linear_model import LinearRegression - -x = 2*np.random.rand(100,1) -y = 4+3*x+np.random.randn(100,1) -linreg = LinearRegression() -linreg.fit(x,y) -xnew = np.array([[0],[2]]) -ypredict = linreg.predict(xnew) - -plt.plot(xnew, ypredict, "r-") -plt.plot(x, y ,'ro') -plt.axis([0,2.0,0, 15.0]) -plt.xlabel(r'$x$') -plt.ylabel(r'$y$') -plt.title(r'Random numbers ') +df.plot.bar(figsize=(10,6), rot=15) plt.show() !ec +We can produce a $4\times 4$ matrix +!bc pycod +b = np.arange(16).reshape((4,4)) +print(b) +df1 = pd.DataFrame(b) +print(df1) +!ec +and many other operations. + +The _Series_ class is another important class included in +_pandas_. You can view it as a specialization of _DataFrame_ but where +we have just a single column of data. It shares many of the same features as _DataFrame. As with _DataFrame_, +most operations are vectorized, achieving thereby a high performance when dealing with computations of arrays, in particular labeled arrays. +As we will see below it leads also to a very concice code close to the mathematical operations we may be interested in. +For multidimensional arrays, we recommend strongly "xarray":"http://xarray.pydata.org/en/stable/". _xarray_ has much of the same flexibility as _pandas_, but allows for the extension to higher dimensions than two. We will see examples later of the usage of both _pandas_ and _xarray_. -===== Simple linear regression model using _scikit-learn_ ===== +===== Reading Data and fitting ===== -We start with perhaps our simplest possible example, using _scikit-learn_ to perform linear regression analysis on a data set produced by us. -What follows is a simple Python code where we have defined function $y$ in terms of the variable $x$. Both are defined as vectors of dimension $1\times 100$. The entries to the vector $\hat{x}$ are given by random numbers generated with a uniform distribution with entries $x_i \in [0,1]$ (more about probability distribution functions later). These values are then used to define a function $y(x)$ (tabulated again as a vector) with a linear dependence on $x$ plus a random noise added via the normal distribution. +In order to study various Machine Learning algorithms, we need to +access data. Acccessing data is an essential step in all machine +learning algorithms. In particular, setting up the so-called _design +matrix_ (to be defined below) is often the first element we need in +order to perform our calculations. To set up the design matrix means +reading (and later, when the calculations are done, writing) data +in various formats, The formats span from reading files from disk, +loading data from databases and interacting with online sources +like web application programming interfaces (APIs). + +In handling various input formats, as discussed above, we will mainly stay with _pandas_, +a Python package which allows us, in a seamless and painless way, to +deal with a multitude of formats, from standard _csv_ (comma separated +values) files, via _excel_, _html_ to _hdf5_ formats. With _pandas_ +and the _DataFrame_ and _Series_ functionalities we are able to convert text data +into the calculational formats we need for a specific algorithm. And our code is going to be +pretty close the basic mathematical expressions. + +Our first data set is going to be a classic from nuclear physics, namely all +available data on binding energies. Don't be intimidated if you are not familiar with nuclear physics. It serves simply as an example here of a data set. + +We will show some of the +strengths of packages like _Scikit-Learn_ in fitting nuclear binding energies to +specific functions using linear regression first. Then, as a teaser, we will show you how +you can easily implement other algorithms like decision trees and random forests and neural networks. + +But before we really start with nuclear physics data, let's just look at some simpler polynomial fitting cases, such as, +(don't be offended) fitting straight lines! + + +=== Simple linear regression model using _scikit-learn_ === + +We start with perhaps our simplest possible example, using _Scikit-Learn_ to perform linear regression analysis on a data set produced by us. + +What follows is a simple Python code where we have defined a function +$y$ in terms of the variable $x$. Both are defined as vectors with $100$ entries. +The numbers in the vector $\hat{x}$ are given +by random numbers generated with a uniform distribution with entries +$x_i \in [0,1]$ (more about probability distribution functions +later). These values are then used to define a function $y(x)$ +(tabulated again as a vector) with a linear dependence on $x$ plus a +random noise added via the normal distribution. The Numpy functions are imported used the _import numpy as np_ @@ -4965,7 +1032,7 @@ y = 2x+N(0,1), !et where $N(0,1)$ represents random numbers generated by the normal -distribution. From _scikit-learn_ we import then the +distribution. From _Scikit-Learn_ we import then the _LinearRegression_ functionality and make a prediction $\tilde{y} = \alpha + \beta x$ using the function _fit(x,y)_. We call the set of data $(\hat{x},\hat{y})$ for our training data. The Python package @@ -5004,10 +1071,6 @@ plt.title(r'Simple Linear Regression') plt.show() !ec - - -===== Simple linear regression model ===== - This example serves several aims. It allows us to demonstrate several aspects of data analysis and later machine learning algorithms. The immediate visualization shows that our linear fit is not @@ -5023,28 +1086,18 @@ y = 10x+0.01 \times N(0,1), \] !et -where $x$ is defined as before. - - - -===== Less noise ===== - -Does the fit look better? Indeed, by -reducing the role of the normal distribution we see immediately that +where $x$ is defined as before. Does the fit look better? Indeed, by +reducing the role of the noise given by the normal distribution we see immediately that our linear prediction seemingly reproduces better the training set. However, this testing 'by the eye' is obviouly not satisfactory in the long run. Here we have only defined the training data and our model, and have not discussed a more rigorous approach to the _cost_ function. - - -===== How to study our fits ===== - We need more rigorous criteria in defining whether we have succeeded or not in modeling our training data. You will be surprised to see that many scientists seldomly venture beyond this 'by the eye' approach. A standard approach for the *cost* function is the so-called $\chi^2$ -function +function (a variant of the mean-squared error (MSE)) !bt \[ \chi^2 = \frac{1}{n} @@ -5057,10 +1110,6 @@ $y_i$. We may not know the explicit value of $\sigma_i^2$, it serves however the aim of scaling the equations and make the cost function dimensionless. - - -===== Minimizing the cost function ===== - Minimizing the cost function is a central aspect of our discussions to come. Finding its minima as function of the model parameters ($\alpha$ and $\beta$ in our case) will be a recurring @@ -5076,11 +1125,8 @@ many practitioners minimize the above function ''by the eye', popularly dubbed a 'chi by the eye'. That is, change a parameter and see (visually and numerically) that the $\chi^2$ function becomes smaller. - -===== Relative error ===== - 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 -the relative error as +the relative error (why would we prefer the MSE instead of the relative error?) as !bt \[ @@ -5112,17 +1158,13 @@ have a small or larger relative error. Try to play around with different training data sets and study (graphically) the value of the relative error. - - -===== The richness of _scikit-learn_ ===== - -As mentioned above, _scikit-learn_ has an impressive functionality. +As mentioned above, _Scikit-Learn_ has an impressive functionality. We can for example extract the values of $\alpha$ and $\beta$ and their error estimates, or the variance and standard deviation and many other properties from the statistical data analysis. Here we show an -example of the functionality of scikit-learn. +example of the functionality of _Scikit-Learn_. !bc pycod import numpy as np import matplotlib.pyplot as plt @@ -5153,11 +1195,6 @@ plt.title(r'Linear Regression fit ') plt.show() !ec - - - -===== Functions in _scikit-learn_ ===== - The function _coef_ gives us the parameter $\beta$ of our fit while _intercept_ yields $\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 !bt @@ -5170,9 +1207,6 @@ The smaller the value, the better the fit. Ideally we would like to have an MSE equal zero. The attentive reader has probably recognized this function as being similar to the $\chi^2$ function defined above. - -===== Other functions in _scikit-learn_ ===== - The _r2score_ function computes $R^2$, the coefficient of determination. It provides a measure of how well future samples are likely to be predicted by the model. Best possible score is 1.0 and it @@ -5192,12 +1226,8 @@ where we have defined the mean value of $\hat{y}$ as \bar{y} = \frac{1}{n} \sum_{i=0}^{n - 1} y_i. \] !et - - -===== The mean absolute error and other functions in _scikit-learn_ ===== - -Another quantity will meet again in our discussions of regression analysis is - 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. +Another quantity taht we will meet again in our discussions of regression analysis is + 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. The MAE is defined as follows !bt \[ @@ -5217,14 +1247,9 @@ estimate is best to use when targets having exponential growth, such as population counts, average sales of a commodity over a span of years etc. - - -===== Cubic polynomial in _scikit-learn_ ===== - We will discuss in more detail these and other functions in the various lectures. We conclude this part with another example. Instead of a linear $x$-dependence we study now a cubic polynomial and use the polynomial regression analysis tools of scikit-learn. -Add description of the various python commands. !bc pycod import matplotlib.pyplot as plt @@ -5259,136 +1284,1440 @@ def error(a): print (error(y)) !ec -Using _R_, we can perform similar studies. + + + +=== To our real data: nuclear binding energies. Brief reminder on masses and binding energies === + +Let us now dive into nuclear physics and remind ourselves briefly about some basic features about binding +energies. A basic quantity which can be measured for the ground +states of nuclei is the atomic mass $M(N, Z)$ of the neutral atom with +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). + +Atomic masses are usually tabulated in terms of the mass excess defined by +!bt +\[ +\Delta M(N, Z) = M(N, Z) - uA, +\] +!et +where $u$ is the Atomic Mass Unit +!bt +\[ +u = M(^{12}\mathrm{C})/12 = 931.4940954(57) \hspace{0.1cm} \mathrm{MeV}/c^2. +\] +!et +The nucleon masses are +!bt +\[ +m_p = 1.00727646693(9)u, +\] +!et +and +!bt +\[ +m_n = 939.56536(8)\hspace{0.1cm} \mathrm{MeV}/c^2 = 1.0086649156(6)u. +\] +!et + +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" +there are data on masses and decays of 3437 nuclei. + +The nuclear binding energy is defined as the energy required to break +up a given nucleus into its constituent parts of $N$ neutrons and $Z$ +protons. In terms of the atomic masses $M(N, Z)$ the binding energy is +defined by + + +!bt +\[ +BE(N, Z) = ZM_H c^2 + Nm_n c^2 - M(N, Z)c^2 , +\] +!et +where $M_H$ is the mass of the hydrogen atom and $m_n$ is the mass of the neutron. +In terms of the mass excess the binding energy is given by +!bt +\[ +BE(N, Z) = Z\Delta_H c^2 + N\Delta_n c^2 -\Delta(N, Z)c^2 , +\] +!et +where $\Delta_H c^2 = 7.2890$ MeV and $\Delta_n c^2 = 8.0713$ MeV. + + +A popular and physically intuitive model which can be used to parametrize +the experimental binding energies as function of $A$, is the so-called +_liquid drop model_. The ansatz is based on the following expression + +!bt +\[ +BE(N,Z) = a_1A-a_2A^{2/3}-a_3\frac{Z^2}{A^{1/3}}-a_4\frac{(N-Z)^2}{A}, +\] +!et + +where $A$ stands for the number of nucleons and the $a_i$s are parameters which are determined by a fit +to the experimental data. +To arrive at the above expression we have assumed that we can make the following assumptions: + + * 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. + + * 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. + * 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. -===== Polynomial Regression ===== + * 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. + +We could also add a so-called pairing term, which is a correction term that +arises from the tendency of proton pairs and neutron pairs to +occur. An even number of particles is more stable than an odd number. + + +=== Organizing our data === + +Let us start with reading and organizing our data. +We start with the compilation of masses and binding energies from 2016. +After having downloaded this file to our own computer, we are now ready to read the file and start structuring our data. + + +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_. !bc pycod -# Importing various packages -from math import exp, sqrt -from random import random, seed +# Common imports import numpy as np +import pandas as pd import matplotlib.pyplot as plt +import sklearn.linear_model as skl +from sklearn.model_selection import train_test_split +from sklearn.metrics import mean_squared_error, r2_score, mean_absolute_error +import os -m = 100 -x = 2*np.random.rand(m,1)+4. -y = 4+3*x*x+ +x-np.random.randn(m,1) +# Where to save the figures and data files +PROJECT_ROOT_DIR = "Results" +FIGURE_ID = "Results/FigureFiles" +DATA_ID = "DataFiles/" -xb = np.c_[np.ones((m,1)), x] -theta = np.linalg.inv(xb.T.dot(xb)).dot(xb.T).dot(y) -xnew = np.array([[0],[2]]) -xbnew = np.c_[np.ones((2,1)), xnew] -ypredict = xbnew.dot(theta) +if not os.path.exists(PROJECT_ROOT_DIR): + os.mkdir(PROJECT_ROOT_DIR) -plt.plot(xnew, ypredict, "r-") -plt.plot(x, y ,'ro') -plt.axis([0,2.0,0, 15.0]) -plt.xlabel(r'$x$') -plt.ylabel(r'$y$') -plt.title(r'Random numbers ') +if not os.path.exists(FIGURE_ID): + os.makedirs(FIGURE_ID) + +if not os.path.exists(DATA_ID): + os.makedirs(DATA_ID) + +def image_path(fig_id): + return os.path.join(FIGURE_ID, fig_id) + +def data_path(dat_id): + return os.path.join(DATA_ID, dat_id) + +def save_fig(fig_id): + plt.savefig(image_path(fig_id) + ".png", format='png') + +infile = open(data_path("MassEval2016.dat"),'r') +!ec + + +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. +!bc pycod +from pylab import plt, mpl +plt.style.use('seaborn') +mpl.rcParams['font.family'] = 'serif' + +def MakePlot(x,y, styles, labels, axlabels): + plt.figure(figsize=(10,6)) + for i in range(len(x)): + plt.plot(x[i], y[i], styles[i], label = labels[i]) + plt.xlabel(axlabels[0]) + plt.ylabel(axlabels[1]) + plt.legend(loc=0) +!ec + +Our next step is to read the data on experimental binding energies and +reorganize them as functions of the mass number $A$, the number of +protons $Z$ and neutrons $N$ using _pandas_. Before we do this it is +always useful (unless you have a binary file or other types of compressed +data) to actually open the file and simply take a look at it! + + +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. +!bc pycod +""" +This is taken from the data file of the mass 2016 evaluation. +All files are 3436 lines long with 124 character per line. + Headers are 39 lines long. + col 1 : Fortran character control: 1 = page feed 0 = line feed + 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 + These formats are reflected in the pandas widths variable below, see the statement + widths=(1,3,5,5,5,1,3,4,1,13,11,11,9,1,2,11,9,1,3,1,12,11,1), + Pandas has also a variable header, with length 39 in this case. +""" +!ec + +The data we are interested in are in columns 2, 3, 4 and 11, giving us +the number of neutrons, protons, mass numbers and binding energies, +respectively. We add also for the sake of completeness the element name. The data are in fixed-width formatted lines and we will +covert them into the _pandas_ DataFrame structure. + +!bc pycod +# Read the experimental data with Pandas +Masses = pd.read_fwf(infile, usecols=(2,3,4,6,11), + names=('N', 'Z', 'A', 'Element', 'Ebinding'), + widths=(1,3,5,5,5,1,3,4,1,13,11,11,9,1,2,11,9,1,3,1,12,11,1), + header=39, + index_col=False) + +# Extrapolated values are indicated by '#' in place of the decimal place, so +# the Ebinding column won't be numeric. Coerce to float and drop these entries. +Masses['Ebinding'] = pd.to_numeric(Masses['Ebinding'], errors='coerce') +Masses = Masses.dropna() +# Convert from keV to MeV. +Masses['Ebinding'] /= 1000 + +# Group the DataFrame by nucleon number, A. +Masses = Masses.groupby('A') +# Find the rows of the grouped DataFrame with the maximum binding energy. +Masses = Masses.apply(lambda t: t[t.Ebinding==t.Ebinding.max()]) +!ec + +We have now read in the data, grouped them according to the variables we are interested in. +We see how easy it is to reorganize the data using _pandas_. If we +were to do these operations in C/C++ or Fortran, we would have had to +write various functions/subroutines which perform the above +reorganizations for us. Having reorganized the data, we can now start +to make some simple fits using both the functionalities in _numpy_ and +_Scikit-Learn_ afterwards. + +Now we define five variables which contain +the number of nucleons $A$, the number of protons $Z$ and the number of neutrons $N$, the element name and finally the energies themselves. +!bc pycod +A = Masses['A'] +Z = Masses['Z'] +N = Masses['N'] +Element = Masses['Element'] +Energies = Masses['Ebinding'] +print(Masses) +!ec +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 $\bm{X}$. +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. +!bc pycod +# Now we set up the design matrix X +X = np.zeros((len(A),5)) +X[:,0] = 1 +X[:,1] = A +X[:,2] = A**(2.0/3.0) +X[:,3] = A**(-1.0/3.0) +X[:,4] = A**(-1.0) +!ec +With _scikitlearn_ we are now ready to use linear regression and fit our data. +!bc pycod +clf = skl.LinearRegression().fit(X, Energies) +fity = clf.predict(X) +!ec +Pretty simple! +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. +!bc pycod +# The mean squared error +print("Mean squared error: %.2f" % mean_squared_error(Energies, fity)) +# Explained variance score: 1 is perfect prediction +print('Variance score: %.2f' % r2_score(Energies, fity)) +# Mean absolute error +print('Mean absolute error: %.2f' % mean_absolute_error(Energies, fity)) +print(clf.coef_, clf.intercept_) + +Masses['Eapprox'] = fity +# Generate a plot comparing the experimental with the fitted values values. +fig, ax = plt.subplots() +ax.set_xlabel(r'$A = N + Z$') +ax.set_ylabel(r'$E_\mathrm{bind}\,/\mathrm{MeV}$') +ax.plot(Masses['A'], Masses['Ebinding'], alpha=0.7, lw=2, + label='Ame2016') +ax.plot(Masses['A'], Masses['Eapprox'], alpha=0.7, lw=2, c='m', + label='Fit') +ax.legend() +save_fig("Masses2016") plt.show() +!ec + + +=== Seeing the wood for the trees === + +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_! + + +!bc pycod + +#Decision Tree Regression +from sklearn.tree import DecisionTreeRegressor +regr_1=DecisionTreeRegressor(max_depth=5) +regr_2=DecisionTreeRegressor(max_depth=7) +regr_3=DecisionTreeRegressor(max_depth=9) +regr_1.fit(X, Energies) +regr_2.fit(X, Energies) +regr_3.fit(X, Energies) + + +y_1 = regr_1.predict(X) +y_2 = regr_2.predict(X) +y_3=regr_3.predict(X) +Masses['Eapprox'] = y_3 +# Plot the results +plt.figure() +plt.plot(A, Energies, color="blue", label="Data", linewidth=2) +plt.plot(A, y_1, color="red", label="max_depth=5", linewidth=2) +plt.plot(A, y_2, color="green", label="max_depth=7", linewidth=2) +plt.plot(A, y_3, color="m", label="max_depth=9", linewidth=2) + +plt.xlabel("$A$") +plt.ylabel("$E$[MeV]") +plt.title("Decision Tree Regression") +plt.legend() +save_fig("Masses2016Trees") +plt.show() +print(Masses) +print(np.mean( (Energies-y_1)**2)) +!ec + + +=== And what about using neural networks? === +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) +functionality. +!bc pycod +from sklearn.neural_network import MLPRegressor +from sklearn.metrics import accuracy_score +import seaborn as sns + +X_train = X +Y_train = Energies +n_hidden_neurons = 100 +epochs = 100 +# store models for later use +eta_vals = np.logspace(-5, 1, 7) +lmbd_vals = np.logspace(-5, 1, 7) +# store the models for later use +DNN_scikit = np.zeros((len(eta_vals), len(lmbd_vals)), dtype=object) +train_accuracy = np.zeros((len(eta_vals), len(lmbd_vals))) +sns.set() +for i, eta in enumerate(eta_vals): + for j, lmbd in enumerate(lmbd_vals): + dnn = MLPRegressor(hidden_layer_sizes=(n_hidden_neurons), activation='logistic', + alpha=lmbd, learning_rate_init=eta, max_iter=epochs) + dnn.fit(X_train, Y_train) + DNN_scikit[i][j] = dnn + train_accuracy[i][j] = dnn.score(X_train, Y_train) + +fig, ax = plt.subplots(figsize = (10, 10)) +sns.heatmap(train_accuracy, annot=True, ax=ax, cmap="viridis") +ax.set_title("Training Accuracy") +ax.set_ylabel("$\eta$") +ax.set_xlabel("$\lambda$") +plt.show() + + !ec + + + + + +===== A first summary ===== + +The aim behind these introductory words was to present to you various +Python libraries and their functionalities, in particular libraries like +_numpy_, _pandas_, _xarray_ and _matplotlib_ and other that make our life much easier +in handling various data sets and visualizing data. + +Furthermore, +_Scikit-Learn_ allows us with few lines of code to implement popular +Machine Learning algorithms for supervised learning. Later we will meet _Tensorflow_, a powerful library for deep learning. +Now it is time to dive more into the details of various methods. We will start with linear regression and try to take a deeper look at what it entails. + + + + -===== Linking the regression analysis with a statistical interpretation ===== -Before we proceed, and to link with our discussions of Bayesian statistics to come, it is useful the derive the standard regression analysis equations using a statistical interpretation. This allows us also to derive quantities like the variance and other expectation values in a rather straightforward way. -It is assumed that $\varepsilon_i -\sim \mathcal{N}(0, \sigma^2)$ and the $\varepsilon_{i}$ are -independent, i.e.: + +======= Why Linear Regression (aka Ordinary Least Squares and family) ======= + +Fitting a continuous function with linear parameterization in terms of the parameters $\bm{\beta}$. +* Method of choice for fitting a continuous function! +* Gives an excellent introduction to central Machine Learning features with _understandable pedagogical_ links to other methods like _Neural Networks_, _Support Vector Machines_ etc +* Analytical expression for the fitting parameters $\bm{\beta}$ +* Analytical expressions for statistical propertiers like mean values, variances, confidence intervals and more +* Analytical relation with probabilistic interpretations +* Easy to introduce basic concepts like bias-variance tradeoff, cross-validation, resampling and regularization techniques and many other ML topics +* Easy to code! And links well with classification problems and logistic regression and neural networks +* Allows for _easy_ hands-on understanding of gradient descent methods +* and many more features + +For more discussions of Ridge and Lasso regression, "Wessel van Wieringen's":"https://arxiv.org/abs/1509.09169" article is highly recommended. +Similarly, "Mehta et al's article":"https://arxiv.org/abs/1803.08823" is also recommended. + + +=== Regression analysis, overarching aims === + +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 $\bm{x} =[x_0, x_1,\dots, x_{n-1}]^T$. +The first variable is called the _dependent_, the _outcome_ or the _response_ variable while the set of variables $\bm{x}$ is called the independent variable, or the predictor variable or the explanatory variable. + +A regression model aims at finding a likelihood function $p(\bm{y}\vert \bm{x})$, that is the conditional distribution for $\bm{y}$ with a given $\bm{x}$. The estimation of $p(\bm{y}\vert \bm{x})$ is made using a data set with +* $n$ cases $i = 0, 1, 2, \dots, n-1$ +* Response (target, dependent or outcome) variable $y_i$ with $i = 0, 1, 2, \dots, n-1$ +* $p$ so-called explanatory (independent or predictor) variables $\bm{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. + The goal of the regression analysis is to extract/exploit relationship between $\bm{y}$ and $\bm{X}$ in or to infer causal dependencies, approximations to the likelihood functions, functional relationships and to make predictions, making fits and many other things. + + +Consider an experiment in which $p$ characteristics of $n$ samples are +measured. The data from this experiment, for various explanatory variables $p$ are normally represented by a matrix +$\mathbf{X}$. + +The matrix $\mathbf{X}$ is called the *design +matrix*. Additional information of the samples is available in the +form of $\bm{y}$ (also as above). The variable $\bm{y}$ is +generally referred to as the *response variable*. The aim of +regression analysis is to explain $\bm{y}$ in terms of +$\bm{X}$ through a functional relationship like $y_i = +f(\mathbf{X}_{i,\ast})$. When no prior knowledge on the form of +$f(\cdot)$ is available, it is common to assume a linear relationship +between $\bm{X}$ and $\bm{y}$. This assumption gives rise to +the *linear regression model* where $\bm{\beta} = [\beta_0, \ldots, +\beta_{p-1}]^{T}$ are the *regression parameters*. + +Linear regression gives us a set of analytical equations for the parameters $\beta_j$. + + +=== Examples === + +In order to understand the relation among the predictors $p$, the set of data $n$ and the target (outcome, output etc) $\bm{y}$, +consider the model we discussed for describing nuclear binding energies. + +There we assumed that we could parametrize the data using a polynomial approximation based on the liquid drop model. +Assuming !bt -\begin{align*} -\mbox{Cov}(\varepsilon_{i_1}, -\varepsilon_{i_2}) & = \left\{ \begin{array}{lcc} \sigma^2 & \mbox{if} -& i_1 = i_2, \\ 0 & \mbox{if} & i_1 \not= i_2. \end{array} \right. -\end{align*} +\[ +BE(A) = a_0+a_1A+a_2A^{2/3}+a_3A^{-1/3}+a_4A^{-1}, +\] !et -The randomness of $\varepsilon_i$ implies that -$\mathbf{Y}_i$ is also a random variable. In particular, -$\mathbf{Y}_i$ is normally distributed, because $\varepsilon_i \sim -\mathcal{N}(0, \sigma^2)$ and $\mathbf{X}_{i,\ast} \, \beta$ is a -non-random scalar. To specify the parameters of the distribution of -$\mathbf{Y}_i$ we need to calculate its first two moments. +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. +This gives $p=0,1,2,3,4$. Furthermore we have $n$ entries for each predictor. It means that our design matrix is a +$p\times n$ matrix $\bm{X}$. + +Here the predictors are based on a model we have made. A popular data set which is widely encountered in ML applications is the +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$ -===== Expectation value and variance ===== +===== General linear models ===== -Its expectation equals: +Before we proceed let us study a case from linear algebra where we aim at fitting a set of data $\bm{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 $\bm{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. + +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 !bt -\begin{align*} -\mathbb{E}(Y_i) & = -\mathbb{E}(\mathbf{X}_{i, \ast} \, \beta) + \mathbb{E}(\varepsilon_i) -\, \, \, = \, \, \, \mathbf{X}_{i, \ast} \, \beta, -\end{align*} +\[ +y=y(x) \rightarrow y(x_i)=\tilde{y}_i+\epsilon_i=\sum_{j=0}^{n-1} \beta_j x_i^j+\epsilon_i, +\] !et -while -its variance is +where $\epsilon_i$ is the error in our approximation. + + +For every set of values $y_i,x_i$ we have thus the corresponding set of equations !bt -\begin{align*} \mbox{Var}(Y_i) & = \mathbb{E} \{ [Y_i -- \mathbb{E}(Y_i)]^2 \} \, \, \, = \, \, \, \mathbb{E} ( Y_i^2 ) - -[\mathbb{E}(Y_i)]^2 \\ & = \mathbb{E} [ ( \mathbf{X}_{i, \ast} \, -\beta + \varepsilon_i )^2] - ( \mathbf{X}_{i, \ast} \, \beta)^2 \\ & -= \mathbb{E} [ ( \mathbf{X}_{i, \ast} \, \beta)^2 + 2 \varepsilon_i -\mathbf{X}_{i, \ast} \, \beta + \varepsilon_i^2 ] - ( \mathbf{X}_{i, -\ast} \, \beta)^2 \\ & = ( \mathbf{X}_{i, \ast} \, \beta)^2 + 2 -\mathbb{E}(\varepsilon_i) \mathbf{X}_{i, \ast} \, \beta + -\mathbb{E}(\varepsilon_i^2 ) - ( \mathbf{X}_{i, \ast} \, \beta)^2 -\\ & = \mathbb{E}(\varepsilon_i^2 ) \, \, \, = \, \, \, -\mbox{Var}(\varepsilon_i) \, \, \, = \, \, \, \sigma^2. +\begin{align*} +y_0&=\beta_0+\beta_1x_0^1+\beta_2x_0^2+\dots+\beta_{n-1}x_0^{n-1}+\epsilon_0\\ +y_1&=\beta_0+\beta_1x_1^1+\beta_2x_1^2+\dots+\beta_{n-1}x_1^{n-1}+\epsilon_1\\ +y_2&=\beta_0+\beta_1x_2^1+\beta_2x_2^2+\dots+\beta_{n-1}x_2^{n-1}+\epsilon_2\\ +\dots & \dots \\ +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}.\\ \end{align*} !et -Hence, $Y_i \sim \mathcal{N}( \mathbf{X}_{i, \ast} \, \beta, \sigma^2)$. - - - - - -===== The singular value decompostion ===== -!bblock - - -A general -$m\times n$ matrix $\hat{A}$ can be written in terms of a diagonal -matrix $\hat{D}$ of dimensionality $n\times n$ and two orthognal -matrices $\hat{U}$ and $\hat{V}$, where the first has dimensionality -$m \times m$ and the last dimensionality $n\times n$. -We have then +Defining the vectors !bt -\[ -\hat{A} = \hat{U}\hat{D}\hat{V}^T -\] -!et -!eblock +\[ +\bm{y} = [y_0,y_1, y_2,\dots, y_{n-1}]^T, +\] +!et +and +!bt +\[ +\bm{\beta} = [\beta_0,\beta_1, \beta_2,\dots, \beta_{n-1}]^T, +\] +!et +and +!bt +\[ +\bm{\epsilon} = [\epsilon_0,\epsilon_1, \epsilon_2,\dots, \epsilon_{n-1}]^T, +\] +!et +and the design matrix +!bt +\[ +\bm{X}= +\begin{bmatrix} +1& x_{0}^1 &x_{0}^2& \dots & \dots &x_{0}^{n-1}\\ +1& x_{1}^1 &x_{1}^2& \dots & \dots &x_{1}^{n-1}\\ +1& x_{2}^1 &x_{2}^2& \dots & \dots &x_{2}^{n-1}\\ +\dots& \dots &\dots& \dots & \dots &\dots\\ +1& x_{n-1}^1 &x_{n-1}^2& \dots & \dots &x_{n-1}^{n-1}\\ +\end{bmatrix} +\] +!et +we can rewrite our equations as +!bt +\[ +\bm{y} = \bm{X}\bm{\beta}+\bm{\epsilon}. +\] +!et +The above design matrix is called a "Vandermonde matrix":"https://en.wikipedia.org/wiki/Vandermonde_matrix". +===== Generalizing the fitting procedure as a linear algebra problem ===== + +We are obviously not limited to the above polynomial expansions. We +could replace the various powers of $x$ with elements of Fourier +series or instead of $x_i^j$ we could have $\cos{(j x_i)}$ or $\sin{(j +x_i)}$, or time series or other orthogonal functions. For every set +of values $y_i,x_i$ we can then generalize the equations to + +!bt +\begin{align*} +y_0&=\beta_0x_{00}+\beta_1x_{01}+\beta_2x_{02}+\dots+\beta_{n-1}x_{0n-1}+\epsilon_0\\ +y_1&=\beta_0x_{10}+\beta_1x_{11}+\beta_2x_{12}+\dots+\beta_{n-1}x_{1n-1}+\epsilon_1\\ +y_2&=\beta_0x_{20}+\beta_1x_{21}+\beta_2x_{22}+\dots+\beta_{n-1}x_{2n-1}+\epsilon_2\\ +\dots & \dots \\ +y_{i}&=\beta_0x_{i0}+\beta_1x_{i1}+\beta_2x_{i2}+\dots+\beta_{n-1}x_{in-1}+\epsilon_i\\ +\dots & \dots \\ +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}.\\ +\end{align*} +!et + +_Note that we have $p=n$ here. The matrix is symmetric. This is generally not the case!_ + +We redefine in turn the matrix $\bm{X}$ as +!bt +\[ +\bm{X}= +\begin{bmatrix} +x_{00}& x_{01} &x_{02}& \dots & \dots &x_{0,n-1}\\ +x_{10}& x_{11} &x_{12}& \dots & \dots &x_{1,n-1}\\ +x_{20}& x_{21} &x_{22}& \dots & \dots &x_{2,n-1}\\ +\dots& \dots &\dots& \dots & \dots &\dots\\ +x_{n-1,0}& x_{n-1,1} &x_{n-1,2}& \dots & \dots &x_{n-1,n-1}\\ +\end{bmatrix} +\] +!et +and without loss of generality we rewrite again our equations as +!bt +\[ +\bm{y} = \bm{X}\bm{\beta}+\bm{\epsilon}. +\] +!et +The left-hand side of this equation is kwown. Our error vector $\bm{\epsilon}$ and the parameter vector $\bm{\beta}$ are our unknow quantities. How can we obtain the optimal set of $\beta_i$ values? + +We have defined the matrix $\bm{X}$ via the equations +!bt +\begin{align*} +y_0&=\beta_0x_{00}+\beta_1x_{01}+\beta_2x_{02}+\dots+\beta_{n-1}x_{0n-1}+\epsilon_0\\ +y_1&=\beta_0x_{10}+\beta_1x_{11}+\beta_2x_{12}+\dots+\beta_{n-1}x_{1n-1}+\epsilon_1\\ +y_2&=\beta_0x_{20}+\beta_1x_{21}+\beta_2x_{22}+\dots+\beta_{n-1}x_{2n-1}+\epsilon_1\\ +\dots & \dots \\ +y_{i}&=\beta_0x_{i0}+\beta_1x_{i1}+\beta_2x_{i2}+\dots+\beta_{n-1}x_{in-1}+\epsilon_1\\ +\dots & \dots \\ +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}.\\ +\end{align*} +!et + +As we noted above, we stayed with a system with the design matrix + $\bm{X}\in {\mathbb{R}}^{n\times n}$, that is we have $p=n$. For reasons to come later (algorithmic arguments) we will hereafter define +our matrix as $\bm{X}\in {\mathbb{R}}^{n\times p}$, with the predictors refering to the column numbers and the entries $n$ being the row elements. + + +===== Our model for the nuclear binding energies ===== + +In our introductory notes we looked at the so-called "liguid drop model":"https://en.wikipedia.org/wiki/Semi-empirical_mass_formula". Let us remind ourselves about what we did by looking at the code. + +We restate the parts of the code we are most interested in. +!bc pycod +# Common imports +import numpy as np +import pandas as pd +import matplotlib.pyplot as plt +from IPython.display import display +import os + +# Where to save the figures and data files +PROJECT_ROOT_DIR = "Results" +FIGURE_ID = "Results/FigureFiles" +DATA_ID = "DataFiles/" + +if not os.path.exists(PROJECT_ROOT_DIR): + os.mkdir(PROJECT_ROOT_DIR) + +if not os.path.exists(FIGURE_ID): + os.makedirs(FIGURE_ID) + +if not os.path.exists(DATA_ID): + os.makedirs(DATA_ID) + +def image_path(fig_id): + return os.path.join(FIGURE_ID, fig_id) + +def data_path(dat_id): + return os.path.join(DATA_ID, dat_id) + +def save_fig(fig_id): + plt.savefig(image_path(fig_id) + ".png", format='png') + +infile = open(data_path("MassEval2016.dat"),'r') + + +# Read the experimental data with Pandas +Masses = pd.read_fwf(infile, usecols=(2,3,4,6,11), + names=('N', 'Z', 'A', 'Element', 'Ebinding'), + widths=(1,3,5,5,5,1,3,4,1,13,11,11,9,1,2,11,9,1,3,1,12,11,1), + header=39, + index_col=False) + +# Extrapolated values are indicated by '#' in place of the decimal place, so +# the Ebinding column won't be numeric. Coerce to float and drop these entries. +Masses['Ebinding'] = pd.to_numeric(Masses['Ebinding'], errors='coerce') +Masses = Masses.dropna() +# Convert from keV to MeV. +Masses['Ebinding'] /= 1000 + +# Group the DataFrame by nucleon number, A. +Masses = Masses.groupby('A') +# Find the rows of the grouped DataFrame with the maximum binding energy. +Masses = Masses.apply(lambda t: t[t.Ebinding==t.Ebinding.max()]) +A = Masses['A'] +Z = Masses['Z'] +N = Masses['N'] +Element = Masses['Element'] +Energies = Masses['Ebinding'] + +# Now we set up the design matrix X +X = np.zeros((len(A),5)) +X[:,0] = 1 +X[:,1] = A +X[:,2] = A**(2.0/3.0) +X[:,3] = A**(-1.0/3.0) +X[:,4] = A**(-1.0) +# Then nice printout using pandas +DesignMatrix = pd.DataFrame(X) +DesignMatrix.index = A +DesignMatrix.columns = ['1', 'A', 'A^(2/3)', 'A^(-1/3)', '1/A'] +display(DesignMatrix) +!ec + +With $\bm{\beta}\in {\mathbb{R}}^{p\times 1}$, it means that we will hereafter write our equations for the approximation as +!bt +\[ +\bm{\tilde{y}}= \bm{X}\bm{\beta}, +\] +!et +throughout these lectures. + + + +With the above we use the design matrix to define the approximation $\bm{\tilde{y}}$ via the unknown quantity $\bm{\beta}$ as +!bt +\[ +\bm{\tilde{y}}= \bm{X}\bm{\beta}, +\] +!et +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 +!bt +\[ +C(\bm{\beta})=\frac{1}{n}\sum_{i=0}^{n-1}\left(y_i-\tilde{y}_i\right)^2=\frac{1}{n}\left\{\left(\bm{y}-\bm{\tilde{y}}\right)^T\left(\bm{y}-\bm{\tilde{y}}\right)\right\}, +\] +!et +or using the matrix $\bm{X}$ and in a more compact matrix-vector notation as +!bt +\[ +C(\bm{\beta})=\frac{1}{n}\left\{\left(\bm{y}-\bm{X}^T\bm{\beta}\right)^T\left(\bm{y}-\bm{X}^T\bm{\beta}\right)\right\}. +\] +!et +This function is one possible way to define the so-called cost function. + + + +It is also common to define +the function $Q$ as + +!bt +\[ +C(\bm{\beta})=\frac{1}{2n}\sum_{i=0}^{n-1}\left(y_i-\tilde{y}_i\right)^2, +\] +!et +since when taking the first derivative with respect to the unknown parameters $\beta$, the factor of $2$ cancels out. +===== Interpretations and optimizing our parameters ===== + + +The function +!bt +\[ +C(\bm{\beta})=\frac{1}{n}\left\{\left(\bm{y}-\bm{X}\bm{\beta}\right)^T\left(\bm{y}-\bm{X}\bm{\beta}\right)\right\}, +\] +!et +can be linked to the variance of the quantity $y_i$ if we interpret the latter as the mean value. +When linking below with the maximum likelihood approach below, we will indeed interpret $y_i$ as a mean value (see exercises) +!bt +\[ +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, +\] +!et + +where $\langle y_i \rangle$ is the mean value. Keep in mind also that +till now we have treated $y_i$ as the exact value. Normally, the +response (dependent or outcome) variable $y_i$ the outcome of a +numerical experiment or another type of experiment and is thus only an +approximation to the true value. It is then always accompanied by an +error estimate, often limited to a statistical error estimate given by +the standard deviation discussed earlier. In the discussion here we +will treat $y_i$ as our exact value for the response variable. + +In order to find the parameters $\beta_i$ we will then minimize the spread of $C(\bm{\beta})$, that is we are going to solve the problem +!bt +\[ +{\displaystyle \min_{\bm{\beta}\in +{\mathbb{R}}^{p}}}\frac{1}{n}\left\{\left(\bm{y}-\bm{X}\bm{\beta}\right)^T\left(\bm{y}-\bm{X}\bm{\beta}\right)\right\}. +\] +!et +In practical terms it means we will require +!bt +\[ +\frac{\partial C(\bm{\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, +\] +!et +which results in +!bt +\[ +\frac{\partial C(\bm{\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, +\] +!et +or in a matrix-vector form as +!bt +\[ +\frac{\partial C(\bm{\beta})}{\partial \bm{\beta}} = 0 = \bm{X}^T\left( \bm{y}-\bm{X}\bm{\beta}\right). +\] +!et +We can rewrite +!bt +\[ +\frac{\partial C(\bm{\beta})}{\partial \bm{\beta}} = 0 = \bm{X}^T\left( \bm{y}-\bm{X}\bm{\beta}\right), +\] +!et +as +!bt +\[ +\bm{X}^T\bm{y} = \bm{X}^T\bm{X}\bm{\beta}, +\] +!et +and if the matrix $\bm{X}^T\bm{X}$ is invertible we have the solution +!bt +\[ +\bm{\beta} =\left(\bm{X}^T\bm{X}\right)^{-1}\bm{X}^T\bm{y}. +\] +!et + +We note also that since our design matrix is defined as $\bm{X}\in +{\mathbb{R}}^{n\times p}$, the product $\bm{X}^T\bm{X} \in +{\mathbb{R}}^{p\times p}$. In the above case we have that $p \ll n$, +in our case $p=5$ meaning that we end up with inverting a small +$5\times 5$ matrix. This is a rather common situation, in many cases we end up with low-dimensional +matrices to invert. The methods discussed here and for many other +supervised learning algorithms like classification with logistic +regression or support vector machines, exhibit dimensionalities which +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 +$\bm{X}^T\bm{X}$. +The residuals $\bm{\epsilon}$ are in turn given by +!bt +\[ +\bm{\epsilon} = \bm{y}-\bm{\tilde{y}} = \bm{y}-\bm{X}\bm{\beta}, +\] +!et +and with +!bt +\[ +\bm{X}^T\left( \bm{y}-\bm{X}\bm{\beta}\right)= 0, +\] +!et +we have +!bt +\[ +\bm{X}^T\bm{\epsilon}=\bm{X}^T\left( \bm{y}-\bm{X}\bm{\beta}\right)= 0, +\] +!et +meaning that the solution for $\bm{\beta}$ is the one which minimizes the residuals. Later we will link this with the maximum likelihood approach. -===== From standard regression to Ridge regressions ===== +Let us now return to our nuclear binding energies and simply code the above equations. + +It is rather straightforward to implement the matrix inversion and obtain the parameters $\bm{\beta}$. After having defined the matrix $\bm{X}$ we simply need to +write +!bc pycod +# matrix inversion to find beta +beta = np.linalg.inv(X.T.dot(X)).dot(X.T).dot(Energies) +# and then make the prediction +ytilde = X @ beta +!ec +Alternatively, you can use the least squares functionality in _Numpy_ as +!bc pycod +fit = np.linalg.lstsq(X, Energies, rcond =None)[0] +ytildenp = np.dot(fit,X.T) +!ec + +And finally we plot our fit with and compare with data +!bc pycod +Masses['Eapprox'] = ytilde +# Generate a plot comparing the experimental with the fitted values values. +fig, ax = plt.subplots() +ax.set_xlabel(r'$A = N + Z$') +ax.set_ylabel(r'$E_\mathrm{bind}\,/\mathrm{MeV}$') +ax.plot(Masses['A'], Masses['Ebinding'], alpha=0.7, lw=2, + label='Ame2016') +ax.plot(Masses['A'], Masses['Eapprox'], alpha=0.7, lw=2, c='m', + label='Fit') +ax.legend() +save_fig("Masses2016OLS") +plt.show() +!ec + +===== Adding error analysis and training set up ===== + +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. +Since we are not using _Scikit-Learn here we can define our own $R2$ function as +!bc pycod +def R2(y_data, y_model): + return 1 - np.sum((y_data - y_model) ** 2) / np.sum((y_data - np.mean(y_model)) ** 2) +!ec +and we would be using it as +!bc pycod +print(R2(Energies,ytilde)) +!ec + +We can easily add our _MSE_ score as +!bc pycod +def MSE(y_data,y_model): + n = np.size(y_model) + return np.sum((y_data-y_model)**2)/n + +print(MSE(Energies,ytilde)) +!ec +and finally the relative error as +!bc pycod +def RelativeError(y_data,y_model): + return abs((y_data-y_model)/y_data) +print(RelativeError(Energies, ytilde)) +!ec + + + +===== The $\chi^2$ function ===== + +Normally, the response (dependent or outcome) variable $y_i$ is the +outcome of a numerical experiment or another type of experiment and is +thus only an approximation to the true value. It is then always +accompanied by an error estimate, often limited to a statistical error +estimate given by the standard deviation discussed earlier. In the +discussion here we will treat $y_i$ as our exact value for the +response variable. + +Introducing the standard deviation $\sigma_i$ for each measurement +$y_i$, we define now the $\chi^2$ function (omitting the $1/n$ term) +as + +!bt +\[ +\chi^2(\bm{\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(\bm{y}-\bm{\tilde{y}}\right)^T\frac{1}{\bm{\Sigma^2}}\left(\bm{y}-\bm{\tilde{y}}\right)\right\}, +\] +!et +where the matrix $\bm{\Sigma}$ is a diagonal matrix with $\sigma_i$ as matrix elements. + + +In order to find the parameters $\beta_i$ we will then minimize the spread of $\chi^2(\bm{\beta})$ by requiring +!bt +\[ +\frac{\partial \chi^2(\bm{\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, +\] +!et +which results in +!bt +\[ +\frac{\partial \chi^2(\bm{\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, +\] +!et +or in a matrix-vector form as +!bt +\[ +\frac{\partial \chi^2(\bm{\beta})}{\partial \bm{\beta}} = 0 = \bm{A}^T\left( \bm{b}-\bm{A}\bm{\beta}\right). +\] +!et +where we have defined the matrix $\bm{A} =\bm{X}/\bm{\Sigma}$ with matrix elements $a_{ij} = x_{ij}/\sigma_i$ and the vector $\bm{b}$ with elements $b_i = y_i/\sigma_i$. + +We can rewrite +!bt +\[ +\frac{\partial \chi^2(\bm{\beta})}{\partial \bm{\beta}} = 0 = \bm{A}^T\left( \bm{b}-\bm{A}\bm{\beta}\right), +\] +!et +as +!bt +\[ +\bm{A}^T\bm{b} = \bm{A}^T\bm{A}\bm{\beta}, +\] +!et +and if the matrix $\bm{A}^T\bm{A}$ is invertible we have the solution +!bt +\[ +\bm{\beta} =\left(\bm{A}^T\bm{A}\right)^{-1}\bm{A}^T\bm{b}. +\] +!et + +If we then introduce the matrix +!bt +\[ +\bm{H} = \left(\bm{A}^T\bm{A}\right)^{-1}, +\] +!et +we have then the following expression for the parameters $\beta_j$ (the matrix elements of $\bm{H}$ are $h_{ij}$) +!bt +\[ +\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} +\] +!et +We state without proof the expression for the uncertainty in the parameters $\beta_j$ as (we leave this as an exercise) +!bt +\[ +\sigma^2(\beta_j) = \sum_{i=0}^{n-1}\sigma_i^2\left( \frac{\partial \beta_j}{\partial y_i}\right)^2, +\] +!et +resulting in +!bt +\[ +\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}! +\] +!et + +The first step here is to approximate the function $y$ with a first-order polynomial, that is we write +!bt +\[ +y=y(x) \rightarrow y(x_i) \approx \beta_0+\beta_1 x_i. +\] +!et +By computing the derivatives of $\chi^2$ with respect to $\beta_0$ and $\beta_1$ show that these are given by +!bt +\[ +\frac{\partial \chi^2(\bm{\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, +\] +!et +and +!bt +\[ +\frac{\partial \chi^2(\bm{\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. +\] +!et + +For a linear fit (a first-order polynomial) we don't need to invert a matrix!! +Defining +!bt +\[ +\gamma = \sum_{i=0}^{n-1}\frac{1}{\sigma_i^2}, +\] +!et + +!bt +\[ +\gamma_x = \sum_{i=0}^{n-1}\frac{x_{i}}{\sigma_i^2}, +\] +!et + +!bt +\[ +\gamma_y = \sum_{i=0}^{n-1}\left(\frac{y_i}{\sigma_i^2}\right), +\] +!et + +!bt +\[ +\gamma_{xx} = \sum_{i=0}^{n-1}\frac{x_ix_{i}}{\sigma_i^2}, +\] +!et + +!bt +\[ +\gamma_{xy} = \sum_{i=0}^{n-1}\frac{y_ix_{i}}{\sigma_i^2}, +\] +!et + +we obtain + +!bt +\[ +\beta_0 = \frac{\gamma_{xx}\gamma_y-\gamma_x\gamma_y}{\gamma\gamma_{xx}-\gamma_x^2}, +\] +!et + +!bt +\[ +\beta_1 = \frac{\gamma_{xy}\gamma-\gamma_x\gamma_y}{\gamma\gamma_{xx}-\gamma_x^2}. +\] +!et + +This approach (different linear and non-linear regression) suffers +often from both being underdetermined and overdetermined in the +unknown coefficients $\beta_i$. A better approach is to use the +Singular Value Decomposition (SVD) method discussed below. Or using +Lasso and Ridge regression. See below. + + +===== Fitting an Equation of State for Dense Nuclear Matter ===== + +Before we continue, let us introduce yet another example. We are going to fit the +nuclear equation of state using results from many-body calculations. +The equation of state we have made available here, as function of +density, has been derived using modern nucleon-nucleon potentials with +"the addition of three-body +forces":"https://www.sciencedirect.com/science/article/pii/S0370157399001106". This +time the file is presented as a standard _csv_ file. + +The beginning of the Python code here is similar to what you have seen before, +with the same initializations and declarations. We use also _pandas_ +again, rather extensively in order to organize our data. + +The difference now is that we use _Scikit-Learn's_ regression tools +instead of our own matrix inversion implementation. Furthermore, we +sneak in _Ridge_ regression (to be discussed below) which includes a +hyperparameter $\lambda$, also to be explained below. + +!split +===== The code ===== + +!bc pycod +# Common imports +import os +import numpy as np +import pandas as pd +import matplotlib.pyplot as plt +import matplotlib.pyplot as plt +import sklearn.linear_model as skl +from sklearn.metrics import mean_squared_error, r2_score, mean_absolute_error + +# Where to save the figures and data files +PROJECT_ROOT_DIR = "Results" +FIGURE_ID = "Results/FigureFiles" +DATA_ID = "DataFiles/" + +if not os.path.exists(PROJECT_ROOT_DIR): + os.mkdir(PROJECT_ROOT_DIR) + +if not os.path.exists(FIGURE_ID): + os.makedirs(FIGURE_ID) + +if not os.path.exists(DATA_ID): + os.makedirs(DATA_ID) + +def image_path(fig_id): + return os.path.join(FIGURE_ID, fig_id) + +def data_path(dat_id): + return os.path.join(DATA_ID, dat_id) + +def save_fig(fig_id): + plt.savefig(image_path(fig_id) + ".png", format='png') + +infile = open(data_path("EoS.csv"),'r') + +# Read the EoS data as csv file and organize the data into two arrays with density and energies +EoS = pd.read_csv(infile, names=('Density', 'Energy')) +EoS['Energy'] = pd.to_numeric(EoS['Energy'], errors='coerce') +EoS = EoS.dropna() +Energies = EoS['Energy'] +Density = EoS['Density'] +# The design matrix now as function of various polytrops +X = np.zeros((len(Density),4)) +X[:,3] = Density**(4.0/3.0) +X[:,2] = Density +X[:,1] = Density**(2.0/3.0) +X[:,0] = 1 + +# We use now Scikit-Learn's linear regressor and ridge regressor +# OLS part +clf = skl.LinearRegression().fit(X, Energies) +ytilde = clf.predict(X) +EoS['Eols'] = ytilde +# The mean squared error +print("Mean squared error: %.2f" % mean_squared_error(Energies, ytilde)) +# Explained variance score: 1 is perfect prediction +print('Variance score: %.2f' % r2_score(Energies, ytilde)) +# Mean absolute error +print('Mean absolute error: %.2f' % mean_absolute_error(Energies, ytilde)) +print(clf.coef_, clf.intercept_) + +# The Ridge regression with a hyperparameter lambda = 0.1 +_lambda = 0.1 +clf_ridge = skl.Ridge(alpha=_lambda).fit(X, Energies) +yridge = clf_ridge.predict(X) +EoS['Eridge'] = yridge +# The mean squared error +print("Mean squared error: %.2f" % mean_squared_error(Energies, yridge)) +# Explained variance score: 1 is perfect prediction +print('Variance score: %.2f' % r2_score(Energies, yridge)) +# Mean absolute error +print('Mean absolute error: %.2f' % mean_absolute_error(Energies, yridge)) +print(clf_ridge.coef_, clf_ridge.intercept_) + +fig, ax = plt.subplots() +ax.set_xlabel(r'$\rho[\mathrm{fm}^{-3}]$') +ax.set_ylabel(r'Energy per particle') +ax.plot(EoS['Density'], EoS['Energy'], alpha=0.7, lw=2, + label='Theoretical data') +ax.plot(EoS['Density'], EoS['Eols'], alpha=0.7, lw=2, c='m', + label='OLS') +ax.plot(EoS['Density'], EoS['Eridge'], alpha=0.7, lw=2, c='g', + label='Ridge $\lambda = 0.1$') +ax.legend() +save_fig("EoSfitting") +plt.show() +!ec + +The above simple polynomial in density $\rho$ gives an excellent fit +to the data. +We note also that there is a small deviation between the +standard OLS and the Ridge regression at higher densities. We discuss this in more detail +below. + + +===== Splitting our Data in Training and Test data ===== + +It is normal in essentially all Machine Learning studies to split the +data in a training set and a test set (sometimes also an additional +validation set). _Scikit-Learn_ has an own function for this. There +is no explicit recipe for how much data should be included as training +data and say test data. An accepted rule of thumb is to use +approximately $2/3$ to $4/5$ of the data as training data. We will +postpone a discussion of this splitting to the end of these notes and +our discussion of the so-called _bias-variance_ tradeoff. Here we +limit ourselves to repeat the above equation of state fitting example +but now splitting the data into a training set and a test set. + +!bc pycod +import os +import numpy as np +import pandas as pd +import matplotlib.pyplot as plt +from sklearn.model_selection import train_test_split +# Where to save the figures and data files +PROJECT_ROOT_DIR = "Results" +FIGURE_ID = "Results/FigureFiles" +DATA_ID = "DataFiles/" + +if not os.path.exists(PROJECT_ROOT_DIR): + os.mkdir(PROJECT_ROOT_DIR) + +if not os.path.exists(FIGURE_ID): + os.makedirs(FIGURE_ID) + +if not os.path.exists(DATA_ID): + os.makedirs(DATA_ID) + +def image_path(fig_id): + return os.path.join(FIGURE_ID, fig_id) + +def data_path(dat_id): + return os.path.join(DATA_ID, dat_id) + +def save_fig(fig_id): + plt.savefig(image_path(fig_id) + ".png", format='png') + +def R2(y_data, y_model): + return 1 - np.sum((y_data - y_model) ** 2) / np.sum((y_data - np.mean(y_model)) ** 2) +def MSE(y_data,y_model): + n = np.size(y_model) + return np.sum((y_data-y_model)**2)/n + +infile = open(data_path("EoS.csv"),'r') + +# Read the EoS data as csv file and organized into two arrays with density and energies +EoS = pd.read_csv(infile, names=('Density', 'Energy')) +EoS['Energy'] = pd.to_numeric(EoS['Energy'], errors='coerce') +EoS = EoS.dropna() +Energies = EoS['Energy'] +Density = EoS['Density'] +# The design matrix now as function of various polytrops +X = np.zeros((len(Density),5)) +X[:,0] = 1 +X[:,1] = Density**(2.0/3.0) +X[:,2] = Density +X[:,3] = Density**(4.0/3.0) +X[:,4] = Density**(5.0/3.0) +# We split the data in test and training data +X_train, X_test, y_train, y_test = train_test_split(X, Energies, test_size=0.2) +# matrix inversion to find beta +beta = np.linalg.inv(X_train.T.dot(X_train)).dot(X_train.T).dot(y_train) +# and then make the prediction +ytilde = X_train @ beta +print("Training R2") +print(R2(y_train,ytilde)) +print("Training MSE") +print(MSE(y_train,ytilde)) +ypredict = X_test @ beta +print("Test R2") +print(R2(y_test,ypredict)) +print("Test MSE") +print(MSE(y_test,ypredict)) +!ec + + + +===== The singular value decomposition ===== + +The examples we have looked at so far are cases where we normally can +invert the matrix $\bm{X}^T\bm{X}$. Using a polynomial expansion as we +did both for the masses and the fitting of the equation of state, +leads to row vectors of the design matrix which are essentially +orthogonal due to the polynomial character of our model. This may +however not the be case in general and a standard matrix inversion +algorithm based on say LU decomposition may lead to singularities. We will see an example of this below when we try to fit +the coupling constant of the widely used Ising model. +There is however a way to partially circumvent this problem and also gain some insight about the ordinary least squares approach. + +This is given by the _Singular Value Decomposition_ algorithm, perhaps +the most powerful linear algebra algorithm. Let us look at a +different example where we may have problems with the standard matrix +inversion algorithm. Thereafter we dive into the math of the SVD. + + +===== The Ising model ===== + +The one-dimensional Ising model with nearest neighbor interaction, no +external field and a constant coupling constant $J$ is given by + +!bt +\begin{align} + H = -J \sum_{k}^L s_k s_{k + 1}, +\end{align} +!et + +where $s_i \in \{-1, 1\}$ and $s_{N + 1} = s_1$. The number of spins +in the system is determined by $L$. For the one-dimensional system +there is no phase transition. + +We will look at a system of $L = 40$ spins with a coupling constant of +$J = 1$. To get enough training data we will generate 10000 states +with their respective energies. + + +!bc pycod +import numpy as np +import matplotlib.pyplot as plt +from mpl_toolkits.axes_grid1 import make_axes_locatable +import seaborn as sns +import scipy.linalg as scl +from sklearn.model_selection import train_test_split +import tqdm +sns.set(color_codes=True) +cmap_args=dict(vmin=-1., vmax=1., cmap='seismic') + +L = 40 +n = int(1e4) + +spins = np.random.choice([-1, 1], size=(n, L)) +J = 1.0 + +energies = np.zeros(n) + +for i in range(n): + energies[i] = - J * np.dot(spins[i], np.roll(spins[i], 1)) +!ec + +Here we use ordinary least squares +regression to predict the energy for the nearest neighbor +one-dimensional Ising model on a ring, i.e., the endpoints wrap +around. We will use linear regression to fit a value for +the coupling constant to achieve this. + +===== Reformulating the problem to suit regression ===== + +A more general form for the one-dimensional Ising model is + +!bt +\begin{align} + H = - \sum_j^L \sum_k^L s_j s_k J_{jk}. +\end{align} +!et + +Here we allow for interactions beyond the nearest neighbors and a state dependent +coupling constant. This latter expression can be formulated as +a matrix-product +!bt +\begin{align} + \bm{H} = \bm{X} J, +\end{align} +!et + +where $X_{jk} = s_j s_k$ and $J$ is a matrix which consists of the +elements $-J_{jk}$. This form of writing the energy fits perfectly +with the form utilized in linear regression, that is + +!bt +\begin{align} + \bm{y} = \bm{X}\bm{\beta} + \bm{\epsilon}, +\end{align} +!et + +We split the data in training and test data as discussed in the previous example + +!bc pycod +X = np.zeros((n, L ** 2)) +for i in range(n): + X[i] = np.outer(spins[i], spins[i]).ravel() +y = energies +X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2) +!ec + + +In the ordinary least squares method we choose the cost function + +!bt +\begin{align} + C(\bm{X}, \bm{\beta})= \frac{1}{n}\left\{(\bm{X}\bm{\beta} - \bm{y})^T(\bm{X}\bm{\beta} - \bm{y})\right\}. +\end{align} +!et + +We then find the extremal point of $C$ by taking the derivative with respect to $\bm{\beta}$ as discussed above. +This yields the expression for $\bm{\beta}$ to be + +!bt +\[ + \bm{\beta} = \frac{\bm{X}^T \bm{y}}{\bm{X}^T \bm{X}}, +\] +!et + +which immediately imposes some requirements on $\bm{X}$ as there must exist +an inverse of $\bm{X}^T \bm{X}$. If the expression we are modeling contains an +intercept, i.e., a constant term, we must make sure that the +first column of $\bm{X}$ consists of $1$. We do this here + +!bc pycod +X_train_own = np.concatenate( + (np.ones(len(X_train))[:, np.newaxis], X_train), + axis=1 +) +X_test_own = np.concatenate( + (np.ones(len(X_test))[:, np.newaxis], X_test), + axis=1 +) +!ec + +!bc pycod +def ols_inv(x: np.ndarray, y: np.ndarray) -> np.ndarray: + return scl.inv(x.T @ x) @ (x.T @ y) +beta = ols_inv(X_train_own, y_train) +!ec + + + +===== Singular Value decomposition ===== + +Doing the inversion directly turns out to be a bad idea since the matrix +$\bm{X}^T\bm{X}$ is singular. An alternative approach is to use the _singular +value decomposition_. Using the definition of the Moore-Penrose +pseudoinverse we can write the equation for $\bm{\beta}$ as + +!bt +\[ + \bm{\beta} = \bm{X}^{+}\bm{y}, +\] +!et + +where the pseudoinverse of $\bm{X}$ is given by + +!bt +\[ + \bm{X}^{+} = \frac{\bm{X}^T}{\bm{X}^T\bm{X}}. +\] +!et + +Using singular value decomposition we can decompose the matrix $\bm{X} = \bm{U}\bm{\Sigma} \bm{V}^T$, +where $\bm{U}$ and $\bm{V}$ are orthogonal(unitary) matrices and $\bm{\Sigma}$ contains the singular values (more details below). +where $X^{+} = V\Sigma^{+} U^T$. This reduces the equation for +$\omega$ to +!bt +\begin{align} + \bm{\beta} = \bm{V}\bm{\Sigma}^{+} \bm{U}^T \bm{y}. +\end{align} +!et + +Note that solving this equation by actually doing the pseudoinverse +(which is what we will do) is not a good idea as this operation scales +as $\mathcal{O}(n^3)$, where $n$ is the number of elements in a +general matrix. Instead, doing $QR$-factorization and solving the +linear system as an equation would reduce this down to +$\mathcal{O}(n^2)$ operations. + + +!bc pycod +def ols_svd(x: np.ndarray, y: np.ndarray) -> np.ndarray: + u, s, v = scl.svd(x) + return v.T @ scl.pinv(scl.diagsvd(s, u.shape[0], v.shape[0])) @ u.T @ y +!ec + +!bc pycod +beta = ols_svd(X_train_own,y_train) +!ec + +When extracting the $J$-matrix we need to make sure that we remove the intercept, as is done here + +!bc pycod +J = beta[1:].reshape(L, L) +!ec + +A way of looking at the coefficients in $J$ is to plot the matrices as images. + + +!bc pycod +fig = plt.figure(figsize=(20, 14)) +im = plt.imshow(J, **cmap_args) +plt.title("OLS", fontsize=18) +plt.xticks(fontsize=18) +plt.yticks(fontsize=18) +cb = fig.colorbar(im) +cb.ax.set_yticklabels(cb.ax.get_yticklabels(), fontsize=18) +plt.show() +!ec +It is interesting to note that OLS +considers both $J_{j, j + 1} = -0.5$ and $J_{j, j - 1} = -0.5$ as +valid matrix elements for $J$. +In our discussion below on hyperparameters and Ridge and Lasso regression we will see that +this problem can be removed, partly and only with Lasso regression. + +In this case our matrix inversion was actually possible. The obvious question now is what is the mathematics behind the SVD? + + + +===== Linear Regression Problems ===== One of the typical problems we encounter with linear regression, in particular -when the matrix $\hat{X}$ (our so-called design matrix) is high-dimensional, -are problems with near singular or singular matrices. The column vectors of $\hat{X}$ +when the matrix $\bm{X}$ (our so-called design matrix) is high-dimensional, +are problems with near singular or singular matrices. The column vectors of $\bm{X}$ may be linearly dependent, normally referred to as super-collinearity. This means that the matrix may be rank deficient and it is basically impossible to to model the data using linear regression. As an example, consider the matrix @@ -5407,17 +2736,17 @@ to model the data using linear regression. As an example, consider the matrix \end{align*} !et -The columns of $\hat{X}$ are linearly dependent. We se this easily since the +The columns of $\bm{X}$ are linearly dependent. We see this easily since the the first column is the row-wise sum of the other two columns. The rank (more correct, the column rank) of a matrix is the dimension of the space spanned by the column vectors. Hence, the rank of $\mathbf{X}$ is equal to the number of linearly independent columns. In this particular case the matrix has rank 2. Super-collinearity of an $(n \times p)$-dimensional design matrix $\mathbf{X}$ implies -that the inverse of the matrix $\hat{X}^T\hat{x}$ (the matrix we needto invert to solve the linear regression equations) is non-invertible. If we have a square matrix that does not have an inverse, we say this matrix singular. The example here demonstrates this +that the inverse of the matrix $\bm{X}^T\bm{x}$ (the matrix we need to invert to solve the linear regression equations) is non-invertible. If we have a square matrix that does not have an inverse, we say this matrix singular. The example here demonstrates this !bt \begin{align*} -\hat{X} & = \left[ +\bm{X} & = \left[ \begin{array}{rr} 1 & -1 \\ @@ -5425,406 +2754,400 @@ that the inverse of the matrix $\hat{X}^T\hat{x}$ (the matrix we needto invert t \end{array} \right]. \end{align*} !et -We see easily that $\mbox{det}(\hat{X}) = x_{11} x_{22} - x_{12} x_{21} = 1 \times (-1) - 1 \times (-1) = 0$. Hence, $\mathbf{X}$ is singular and its inverse is undefined. -This is equivalent to saying that the matrix $\hat{X}$ has at least an eigenvalue which is zero. +We see easily that $\mbox{det}(\bm{X}) = x_{11} x_{22} - x_{12} x_{21} = 1 \times (-1) - 1 \times (-1) = 0$. Hence, $\mathbf{X}$ is singular and its inverse is undefined. +This is equivalent to saying that the matrix $\bm{X}$ has at least an eigenvalue which is zero. + ===== Fixing the singularity ===== -If our design matrix $\hat{X}$ which enters the linear regression problem +If our design matrix $\bm{X}$ which enters the linear regression problem !bt \begin{align} -\hat{\beta} & = (\hat{X}^{T} \hat{X})^{-1} \hat{X}^{T} \hat{y}, +\bm{\beta} & = (\bm{X}^{T} \bm{X})^{-1} \bm{X}^{T} \bm{y}, \end{align} !et has linearly dependent column vectors, we will not be able to compute the inverse -of $\hat{X}^T\hat{X}$ and we cannot find the parameters (estimators) $\beta_i$. -The estimators are only well-defined if $(\hat{X}^{T}\hat{X})^{-1}$ exits. -This is more likely to happen when the matrix $\hat{X}$ is high-dimensional. In this case it is likely to encounter a situation where +of $\bm{X}^T\bm{X}$ and we cannot find the parameters (estimators) $\beta_i$. +The estimators are only well-defined if $(\bm{X}^{T}\bm{X})^{-1}$ exits. +This is more likely to happen when the matrix $\bm{X}$ is high-dimensional. In this case it is likely to encounter a situation where the regression parameters $\beta_i$ cannot be estimated. -The *ad hoc* approach which was introduced in the 70s was simply to add a diagonal component to the matrix to invert, that is we change +A cheap *ad hoc* approach is simply to add a small diagonal component to the matrix to invert, that is we change !bt \[ -\hat{X}^{T} \hat{X} \rightarrow \hat{X}^{T} \hat{X}+\lambda \hat{I}, +\bm{X}^{T} \bm{X} \rightarrow \bm{X}^{T} \bm{X}+\lambda \bm{I}, \] !et -where $\hat{I}$ is the identity matrix. +where $\bm{I}$ is the identity matrix. When we discuss _Ridge_ regression this is actually what we end up evaluating. The parameter $\lambda$ is called a hyperparameter. More about this later. +===== Basic math of the SVD ===== + + +From standard linear algebra we know that a square matrix $\bm{X}$ can be diagonalized if and only it is +a so-called "normal matrix":"https://en.wikipedia.org/wiki/Normal_matrix", that is if $\bm{X}\in {\mathbb{R}}^{n\times n}$ +we have $\bm{X}\bm{X}^T=\bm{X}^T\bm{X}$ or if $\bm{X}\in {\mathbb{C}}^{n\times n}$ we have $\bm{X}\bm{X}^{\dagger}=\bm{X}^{\dagger}\bm{X}$. +The matrix has then a set of eigenpairs + +!bt +\[ +(\lambda_1,\bm{u}_1),\dots, (\lambda_n,\bm{u}_n), +!et +and the eigenvalues are given by the diagonal matrix +!bt +\[ +\bm{\Sigma}=\mathrm{Diag}(\lambda_1, \dots,\lambda_n). +\] +!et +The matrix $\bm{X}$ can be written in terms of an orthogonal/unitary transformation $\bm{U}$ +!bt +\[ +\bm{X} = \bm{U}\bm{\Sigma}\bm{V}^T, +\] +!et +with $\bm{U}\bm{U}^T=\bm{I}$ or $\bm{U}\bm{U}^{\dagger}=\bm{I}$. +Not all square matrices are diagonalizable. A matrix like the one discussed above +!bt +\[ +\bm{X} = \begin{bmatrix} +1& -1 \\ +1& -1\\ +\end{bmatrix} +\] +!et +is not diagonalizable, it is a so-called "defective matrix":"https://en.wikipedia.org/wiki/Defective_matrix". It is easy to see that the condition +$\bm{X}\bm{X}^T=\bm{X}^T\bm{X}$ is not fulfilled. -===== Fitting vs. predicting when data is in the model class ===== -We start by considering the case -$f(x)=2x$. - -Then the data is clearly generated by a model that is contained within -all three model classes we are using to make predictions (linear -models, third order polynomials, and tenth order polynomials). -Run the code for the following cases: +===== The SVD, a Fantastic Algorithm ===== -o For $f(x)=2x$ , $Ntrain=10$ and $\sigma =0$ (noiseless case), train the three classes of models (linear, third-order polynomial, and tenth order polynomial) for a training set when $x \in [0,1]$ . Make graphs comparing fits for different order of polynomials. Which model fits the data the best? -o Do you think that the data that has the least error on the training set will also make the best predictions? Why or why not? Can you try to discuss and formalize your intuition? What can go right and what can go wrong? -o Check your answer by seeing how well your fits predict newly generated test data (including on data outside the range you fit on, for example $x \in [0,1.2]$ ) using the code below. How well do you do on points in the range of x where you trained the model? How about points outside the original training data set? -o Repeat the above for $f(x)=2x$ , $Ntrain=10$ , and $\sigma=1$ . What changes? -Repeat the exercises above for $f(x)=2x$ , $Ntrain=100$ , and $\sigma=1$ . What changes? -Summarize what you have learned about the relationship between model complexity (number of parameters), goodness of fit on training data, and the ability to predict well. +However, and this is the strength of the SVD algorithm, any general +matrix $\bm{X}$ can be decomposed in terms of a diagonal matrix and +two orthogonal/unitary matrices. The "Singular Value Decompostion +(SVD) theorem":"https://en.wikipedia.org/wiki/Singular_value_decomposition" +states that a general $m\times n$ matrix $\bm{X}$ can be written in +terms of a diagonal matrix $\bm{\Sigma}$ of dimensionality $n\times n$ +and two orthognal matrices $\bm{U}$ and $\bm{V}$, where the first has +dimensionality $m \times m$ and the last dimensionality $n\times n$. +We have then + +!bt +\[ +\bm{X} = \bm{U}\bm{\Sigma}\bm{V}^T +\] +!et + +As an example, the above defective matrix can be decomposed as + +!bt +\[ +\bm{X} = \frac{1}{\sqrt{2}}\begin{bmatrix} 1& 1 \\ 1& -1\\ \end{bmatrix} \begin{bmatrix} 2& 0 \\ 0& 0\\ \end{bmatrix} \frac{1}{\sqrt{2}}\begin{bmatrix} 1& -1 \\ 1& 1\\ \end{bmatrix}=\bm{U}\bm{\Sigma}\bm{V}^T, +\] +!et + +with eigenvalues $\sigma_1=2$ and $\sigma_2=0$. +The SVD exits always! + + + +===== Another Example ===== + +Consider the following matrix which can be SVD decomposed as + +!bt +\[ +\bm{X} = \frac{1}{15}\begin{bmatrix} 14 & 2\\ 4 & 22\\ 16 & 13\end{matrix}=\frac{1}{3}\begin{bmatrix} 1& 2 & 2 \\ 2& -1 & 1\\ 2 & 1& -2\end{bmatrix} \begin{bmatrix} 2& 0 \\ 0& 1\\ 0 & 0\end{bmatrix}\frac{1}{5}\begin{bmatrix} 3& 4 \\ 4& -3\end{bmatrix}=\bm{U}\bm{\Sigma}\bm{V}^T. +\] +!et + +This is a $3\times 2$ matrix which is decomposed in terms of a +$3\times 3$ matrix $\bm{U}$, and a $2\times 2$ matrix $\bm{V}$. It is easy to see +that $\bm{U}$ and $\bm{V}$ are orthogonal (how?). + +And the SVD +decomposition (singular values) gives eigenvalues +$\sigma_i\geq\sigma_{i+1}$ for all $i$ and for dimensions larger than $i=2$, the +eigenvalues (singular values) are zero. + +In the general case, where our design matrix $\bm{X}$ has dimension +$n\times p$, the matrix is thus decomposed into an $n\times n$ +orthogonal matrix $\bm{U}$, a $p\times p$ orthogonal matrix $\bm{V}$ +and a diagonal matrix $\bm{\Sigma}$ with $r=\mathrm{min}(n,p)$ +singular values $\sigma_i\lg 0$ on the main diagonal and zeros filling +the rest of the matrix. There are at most $p$ singular values +assuming that $n > p$. In our regression examples for the nuclear +masses and the equation of state this is indeed the case, while for +the Ising model we have $p > n$. These are often cases that lead to +near singular or singular matrices. + +The columns of $\bm{U}$ are called the left singular vectors while the columns of $\bm{V}$ are the right singular vectors. + + +===== Economy-size SVD ===== + +If we assume that $n > p$, then our matrix $\bm{U}$ has dimension $n +\times n$. The last $n-p$ columns of $\bm{U}$ become however +irrelevant in our calculations since they are multiplied with the +zeros in $\bm{\Sigma}$. + +The economy-size decomposition removes extra rows or columns of zeros +from the diagonal matrix of singular values, $\bm{\Sigma}$, along with the columns +in either $\bm{U}$ or $\bm{V}$ that multiply those zeros in the expression. +Removing these zeros and columns can improve execution time +and reduce storage requirements without compromising the accuracy of +the decomposition. + +If $n > p$, we keep only the first $p$ columns of $\bm{U}$ and $\bm{\Sigma}$ has dimension $p\times p$. +If $p > n$, then only the first $n$ columns of $\bm{V}$ are computed and $\bm{\Sigma}$ has dimension $n\times n$. +The $n=p$ case is obvious, we retain the full SVD. +In general the economy-size SVD leads to less FLOPS and still conserving the desired accuracy. + + +===== Mathematical Properties ===== + +There are several interesting mathematical properties which will be +relevant when we are going to discuss the differences between say +ordinary least squares (OLS) and _Ridge_ regression. + +We have from OLS that the parameters of the linear approximation are given by +!bt +\[ +\bm{\tilde{y}} = \bm{X}\bm{\beta} = \bm{X}\left(\bm{X}^T\bm{X}\right)^{-1}\bm{X}^T\bm{y}. +\] +!et + +The matrix to invert can be rewritten in terms of our SVD decomposition as + +!bt +\[ +\bm{X}^T\bm{X} = \bm{V}\bm{\Sigma}^T\bm{U}^T\bm{U}\bm{\Sigma}\bm{V}^T. +\] +!et +Using the orthogonality properties of $\bm{U}$ we have + +!bt +\[ +\bm{X}^T\bm{X} = \bm{V}\bm{\Sigma}^T\bm{\Sigma}\bm{V}^T = \bm{V}\bm{D}\bm{V}^T, +\] +!et +with $\bm{D}$ being a diagonal matrix with values along the diagonal given by the singular values squared. + +This means that +!bt +\[ +(\bm{X}^T\bm{X})\bm{V} = \bm{V}\bm{D}, +\] +!et +that is the eigenvectors of $(\bm{X}^T\bm{X})$ are given by the columns of the right singular matrix of $\bm{X}$ and the eigenvalues are the squared singular values. It is easy to show (show this) that +!bt +\[ +(\bm{X}\bm{X}^T)\bm{U} = \bm{U}\bm{D}, +\] +!et +that is, the eigenvectors of $(\bm{X}\bm{X})^T$ are the columns of the left singular matrix and the eigenvalues are the same. + +Going back to our OLS equation we have +!bt +\[ +\bm{X}\bm{\beta} = \bm{X}\left(\bm{V}\bm{D}\bm{V}^T \right)^{-1}\bm{X}^T\bm{y}=\bm{U\Sigma V^T}\left(\bm{V}\bm{D}\bm{V}^T \right)^{-1}(\bm{U\Sigma V^T})^T\bm{y}=\bm{U}\bm{U}^T\bm{y}. +\] +!et +We will come back to this expression when we discuss Ridge regression. + + + +===== Ridge and LASSO Regression ===== + +Let us remind ourselves about the expression for the standard Mean Squared Error (MSE) which we used to define our cost function and the equations for the ordinary least squares (OLS) method, that is +our optimization problem is +!bt +\[ +{\displaystyle \min_{\bm{\beta}\in {\mathbb{R}}^{p}}}\frac{1}{n}\left\{\left(\bm{y}-\bm{X}\bm{\beta}\right)^T\left(\bm{y}-\bm{X}\bm{\beta}\right)\right\}. +\] +!et +or we can state it as +!bt +\[ +{\displaystyle \min_{\bm{\beta}\in +{\mathbb{R}}^{p}}}\frac{1}{n}\sum_{i=0}^{n-1}\left(y_i-\tilde{y}_i\right)^2=\frac{1}{n}\vert\vert \bm{y}-\bm{X}\bm{\beta}\vert\vert_2^2, +\] +!et +where we have used the definition of a norm-2 vector, that is +!bt +\[ +\vert\vert \bm{x}\vert\vert_2 = \sqrt{\sum_i x_i^2}. +\] +!et + +By minimizing the above equation with respect to the parameters +$\bm{\beta}$ we could then obtain an analytical expression for the +parameters $\bm{\beta}$. We can add a regularization parameter $\lambda$ by +defining a new cost function to be optimized, that is + +!bt +\[ +{\displaystyle \min_{\bm{\beta}\in +{\mathbb{R}}^{p}}}\frac{1}{n}\vert\vert \bm{y}-\bm{X}\bm{\beta}\vert\vert_2^2+\lambda\vert\vert \bm{\beta}\vert\vert_2^2 +\] +!et + +which leads to the Ridge regression minimization problem where we +require that $\vert\vert \bm{\beta}\vert\vert_2^2\le t$, where $t$ is +a finite number larger than zero. By defining + +!bt +\[ +C(\bm{X},\bm{\beta})=\frac{1}{n}\vert\vert \bm{y}-\bm{X}\bm{\beta}\vert\vert_2^2+\lambda\vert\vert \bm{\beta}\vert\vert_1, +\] +!et + +we have a new optimization equation +!bt +\[ +{\displaystyle \min_{\bm{\beta}\in +{\mathbb{R}}^{p}}}\frac{1}{n}\vert\vert \bm{y}-\bm{X}\bm{\beta}\vert\vert_2^2+\lambda\vert\vert \bm{\beta}\vert\vert_1 +\] +!et +which leads to Lasso regression. Lasso stands for least absolute shrinkage and selection operator. + +Here we have defined the norm-1 as +!bt +\[ +\vert\vert \bm{x}\vert\vert_1 = \sum_i \vert x_i\vert. +\] +!et + +Using the matrix-vector expression for Ridge regression, + +!bt +\[ +C(\bm{X},\bm{\beta})=\frac{1}{n}\left\{(\bm{y}-\bm{X}\bm{\beta})^T(\bm{y}-\bm{X}\bm{\beta})\right\}+\lambda\bm{\beta}^T\bm{\beta}, +\] +!et + +by taking the derivatives with respect to $\bm{\beta}$ we obtain then +a slightly modified matrix inversion problem which for finite values +of $\lambda$ does not suffer from singularity problems. We obtain + +!bt +\[ +\bm{\beta}^{\mathrm{Ridge}} = \left(\bm{X}^T\bm{X}+\lambda\bm{I}\right)^{-1}\bm{X}^T\bm{y}, +\] +!et + +with $\bm{I}$ being a $p\times p$ identity matrix with the constraint that + +!bt +\[ +\sum_{i=0}^{p-1} \beta_i^2 \leq t, +\] +!et + +with $t$ a finite positive number. + +We see that Ridge regression is nothing but the standard +OLS with a modified diagonal term added to $\bm{X}^T\bm{X}$. The +consequences, in particular for our discussion of the bias-variance +are rather interesting. + +Furthermore, if we use the result above in terms of the SVD decomposition (our analysis was done for the OLS method), we had +!bt +\[ +(\bm{X}\bm{X}^T)\bm{U} = \bm{U}\bm{D}. +\] +!et + +We can analyse the OLS solutions in terms of the eigenvectors (the columns) of the right singular value matrix $\bm{U}$ as +!bt +\[ +\bm{X}\bm{\beta} = \bm{X}\left(\bm{V}\bm{D}\bm{V}^T \right)^{-1}\bm{X}^T\bm{y}=\bm{U\Sigma V^T}\left(\bm{V}\bm{D}\bm{V}^T \right)^{-1}(\bm{U\Sigma V^T})^T\bm{y}=\bm{U}\bm{U}^T\bm{y} +\] +!et + + +For Ridge regression this becomes + +!bt +\[ +\bm{X}\bm{\beta}^{\mathrm{Ridge}} = \bm{U\Sigma V^T}\left(\bm{V}\bm{D}\bm{V}^T+\lambda\bm{I} \right)^{-1}(\bm{U\Sigma V^T})^T\bm{y}=\sum_{j=0}^{p-1}\bm{u}_j\bm{u}_j^T\frac{\sigma_j^2}{\sigma_j^2+\lambda}\bm{y}, +\] +!et + +with the vectors $\bm{u}_j$ being the columns of $\bm{U}$. + +===== Interpreting the Ridge results ===== + +Since $\lambda \geq 0$, it means that compared to OLS, we have + +!bt +\[ +\frac{\sigma_j^2}{\sigma_j^2+\lambda} \leq 1. +\] +!et + +Ridge regression finds the coordinates of $\bm{y}$ with respect to the +orthonormal basis $\bm{U}$, it then shrinks the coordinates by +$\frac{\sigma_j^2}{\sigma_j^2+\lambda}$. Recall that the SVD has +eigenvalues ordered in a descending way, that is $\sigma_i \geq +\sigma_{i+1}$. + +For small eigenvalues $\sigma_i$ it means that their contributions become less important, a fact which can be used to reduce the number of degrees of freedom. +Actually, calculating the variance of $\bm{X}\bm{v}_j$ shows that this quantity is equal to $\sigma_j^2/n$. +With a parameter $\lambda$ we can thus shrink the role of specific parameters. + + +For the sake of simplicity, let us assume that the design matrix is orthonormal, that is + +!bt +\[ +\bm{X}^T\bm{X}=(\bm{X}^T\bm{X})^{-1} =\bm{I}. +\] +!et + +In this case the standard OLS results in +!bt +\[ +\bm{\beta}^{\mathrm{OLS}} = \bm{X}^T\bm{y}=\sum_{i=0}^{p-1}\bm{u}_j\bm{u}_j^T\bm{y}, +\] +!et +and -===== Fitting versus predicting when data is not in the model class ===== +!bt +\[ +\bm{\beta}^{\mathrm{Ridge}} = \left(\bm{I}+\lambda\bm{I}\right)^{-1}\bm{X}^T\bm{y}=\left(1+\lambda\right)^{-1}\bm{\beta}^{\mathrm{OLS}}, +\] +!et -Thus far, we have considered the case where the data is generated using a model contained in the model class. Now consider $f(x)=2x-10x^5+15x^{10}$ . Notice that the for linear and third-order polynomial the true model $f(x)$ is not contained in model class. +that is the Ridge estimator scales the OLS estimator by the inverse of a factor $1+\lambda$, and +the Ridge estimator converges to zero when the hyperparameter goes to +infinity. -o Do better fits lead to better predictions? -o What is the relationship between the true model for generating the data and the model class that has the most predictive power? How is this related to the model complexity? How does this depend on the number of data points $Ntrain$ and $\sigma$? -Summarize what you think you learned about the relationship of knowing the true model class and predictive power. +We will come back to more interpreations after we have gone through some of the statistical analysis part. +For more discussions of Ridge and Lasso regression, "Wessel van Wieringen's":"https://arxiv.org/abs/1509.09169" article is highly recommended. +Similarly, "Mehta et al's article":"https://arxiv.org/abs/1803.08823" is also recommended. -===== An example code without the model assessment part ===== +===== Where are we going? ===== -!bc pycod -import numpy as np -import sklearn as sk -from sklearn import datasets, linear_model -from sklearn.preprocessing import PolynomialFeatures - -import matplotlib as mpl -from matplotlib import pyplot as plt - -%matplotlib notebook - -# The Training Data - -N_train=100 - -sigma_train=1; - -# Train on integers -x=np.linspace(0.05,0.95,N_train) -# Draw random noise -s = sigma_train*np.random.randn(N_train) - -#linear -y=2*x+s - -#Tenth Order -#y=2*x-10*x**5+15*x**10+s - -p1=plt.plot(x,y, "o",ms=15, label='Training') - -#Linear Regression -# Create linear regression object -clf = linear_model.LinearRegression() - -# Train the model using the training sets -clf.fit(x[:, np.newaxis], y) -# The coefficients - -xplot=np.linspace(0.02,0.98,200) -linear_plot=plt.plot(xplot, clf.predict(xplot[:, np.newaxis]),label='Linear') - -#Polynomial Regression - - -poly3 = PolynomialFeatures(degree=3) -X = poly3.fit_transform(x[:,np.newaxis]) -clf3 = linear_model.LinearRegression() -clf3.fit(X,y) - - -Xplot=poly3.fit_transform(xplot[:,np.newaxis]) -poly3_plot=plt.plot(xplot, clf3.predict(Xplot), label='Poly 3') - - - -#poly5 = PolynomialFeatures(degree=5) -#X = poly5.fit_transform(x[:,np.newaxis]) -#clf5 = linear_model.LinearRegression() -#clf5.fit(X,y) - -#Xplot=poly5.fit_transform(xplot[:,np.newaxis]) -#plt.plot(xplot, clf5.predict(Xplot), 'r--',linewidth=1) - -poly10 = PolynomialFeatures(degree=10) -X = poly10.fit_transform(x[:,np.newaxis]) -clf10 = linear_model.LinearRegression() -clf10.fit(X,y) - -Xplot=poly10.fit_transform(xplot[:,np.newaxis]) -poly10_plot=plt.plot(xplot, clf10.predict(Xplot), label='Poly 10') - -axes = plt.gca() -axes.set_ylim([-7,7]) - -handles, labels=axes.get_legend_handles_labels() -plt.legend(handles,labels, loc='lower center') -plt.xlabel("$x$") -plt.ylabel("$y$") -Title="$N=$"+str(N_train)+", $\sigma=$"+str(sigma_train) -plt.title(Title+" (train)") -plt.tight_layout() -plt.show() - -!ec - - -===== Generating test data ===== -!bc pycod -# Generate Test Data - -#Number of test data -N_test=20 - -sigma_test=sigma_train - -max_x=1.2 -x_test=max_x*np.random.random(N_test) -# Draw random noise -s_test = sigma_test*np.random.randn(N_test) - -#Linear -y_test=2*x_test+s_test -#Tenth order -#y_test=2*x_test-10*x_test**5+15*x_test**10+s_test - -#Make design matrices for prediction -x_plot=np.linspace(0,max_x, 200) -X3 = poly3.fit_transform(x_plot[:,np.newaxis]) -X10 = poly10.fit_transform(x_plot[:,np.newaxis]) - -%matplotlib notebook - -fig = plt.figure() -p1=plt.plot(x_test,y_test.transpose(), 'o', ms=12, label='data') -p2=plt.plot(x_plot,clf.predict(x_plot[:,np.newaxis]), label='linear') -p3=plt.plot(x_plot,clf3.predict(X3), label='3rd order') -p10=plt.plot(x_plot,clf10.predict(X10), label='10th order') - - -plt.legend(loc=2) -plt.xlabel('$x$') -plt.ylabel('$y$') -plt.legend(loc='best') -plt.title(Title+" (pred.)") -plt.tight_layout() -plt.show() - - -!ec - - -===== How can we effectively evaluate the various models? ===== - -In Ridge regression and the subsequent discussion of its properties -the bias or penalty parameter is considered known or `given'. In -practice, it is unknown and the user needs to make an informed -decision on its value. How do we do that? Much of the same considerations apply to the Lasso method. - - -===== Code examples for Ridge and Lasso Regression ===== - -!bc pycod -import matplotlib.pyplot as plt -import numpy as np -from sklearn import linear_model -from sklearn.linear_model import LinearRegression -from sklearn.metrics import mean_squared_error, r2_score - -#creating data with random noise -x=np.arange(50) - -delta=np.random.uniform(-2.5,2.5, size=(50)) -np.random.shuffle(delta) -y =0.5*x+5+delta - -#arranging data into 2x50 matrix -a=np.array(x) #inputs -b=np.array(y) #outputs - -#Split into training and test -X_train=a[:37, np.newaxis] -X_test=a[37:, np.newaxis] -y_train=b[:37] -y_test=b[37:] - -print ("X_train: ", X_train.shape) -print ("y_train: ", y_train.shape) -print ("X_test: ", X_test.shape) -print ("y_test: ", y_test.shape) - -print ("------------------------------------") - -print ("Ordinary Least Squares") -#Add Ordinary Least Squares fit -reg=LinearRegression() -reg.fit(X_train, y_train) -pred=reg.predict(X_test) -print ("Prediction Shape: ", pred.shape) - -print('Coefficients: \n', reg.coef_) -# The mean squared error -print("Mean squared error: %.2f" - % mean_squared_error(y_test, pred)) -# Explained variance score: 1 is perfect prediction -print('Variance score: %.2f' % r2_score(y_test, pred)) - -#plot -plt.scatter(X_test,y_test,color='green', label="Training Data") -plt.plot(X_test, pred, color='black', label="Fit Line") -plt.legend() -plt.show() - -print ("------------------------------------") - -print ("Ridge Regression") - -ridge=linear_model.RidgeCV(alphas=[0.1,1.0,10.0]) -ridge.fit(X_train,y_train) -print ("Ridge Coefficient: ",ridge.coef_) -print ("Ridge Intercept: ", ridge.intercept_) -#Look into graphing with Ridge fit - -print ("------------------------------------") - -print ("Lasso") -lasso=linear_model.Lasso(alpha=0.1) -lasso.fit(X_train,y_train) -predl=lasso.predict(X_test) -print("Lasso Coefficient: ", lasso.coef_) -print("Lasso Intercept: ", lasso.intercept_) -plt.scatter(X_test,y_test,color='green', label="Training Data") -plt.plot(X_test, predl, color='blue', label="Lasso") -plt.legend() -plt.show() -!ec - - - - - - -===== A second-order polynomial with Ridge and Lasso ===== -!bc pycod -import numpy as np -import matplotlib.pyplot as plt -from sklearn.linear_model import Ridge -from sklearn.metrics import r2_score - -np.random.seed(4155) - -n_samples = 100 - -x = np.random.rand(n_samples,1) -y = 5*x*x + 0.1*np.random.rand(n_samples,1) - -# Centering x and y. -x_ = x - np.mean(x) -y_ = y - np.mean(y) # beta_0 = mean(y) - -X = np.c_[np.ones((n_samples,1)), x, x**2] -X_ = np.c_[x_, x_**2] - - -### 1. -lmb_values = [1e-4, 1e-3, 1e-2, 10, 1e2, 1e4] -num_values = len(lmb_values) - -## Ridge-regression of centered and not centered data -beta_ridge = np.zeros((3,num_values)) -beta_ridge_centered = np.zeros((3,num_values)) - -I3 = np.eye(3) -I2 = np.eye(2) - -for i,lmb in enumerate(lmb_values): - beta_ridge[:,i] = (np.linalg.inv( X.T @ X + lmb*I3) @ X.T @ y).flatten() - beta_ridge_centered[1:,i] = (np.linalg.inv( X_.T @ X_ + lmb*I2) @ X_.T @ y_).flatten() - -# sett beta_0 = np.mean(y) -beta_ridge_centered[0,:] = np.mean(y) - -## OLS (ordinary least squares) solution -beta_ls = np.linalg.inv( X.T @ X ) @ X.T @ y - -## Evaluate the models -pred_ls = X @ beta_ls -pred_ridge = X @ beta_ridge -pred_ridge_centered = X_ @ beta_ridge_centered[1:] + beta_ridge_centered[0,:] - -## Plot the results - -# Sorting -sort_ind = np.argsort(x[:,0]) - -x_plot = x[sort_ind,0] -x_centered_plot = x_[sort_ind,0] - -pred_ls_plot = pred_ls[sort_ind,0] -pred_ridge_plot = pred_ridge[sort_ind,:] -pred_ridge_centered_plot = pred_ridge_centered[sort_ind,:] - -# Plott not centered -plt.plot(x_plot,pred_ls_plot,label='ls') - -for i in range(num_values): - plt.plot(x_plot,pred_ridge_plot[:,i],label='ridge, lmb=%g'%lmb_values[i]) - -plt.plot(x,y,'ro') - -plt.title('linear regression on un-centered data') -plt.legend() - -# Plott centered -plt.figure() - -for i in range(num_values): - plt.plot(x_centered_plot,pred_ridge_centered_plot[:,i],label='ridge, lmb=%g'%lmb_values[i]) - -plt.plot(x_,y,'ro') - -plt.title('linear regression on centered data') -plt.legend() - - -# 2. - -pred_ridge_scikit = np.zeros((n_samples,num_values)) -for i,lmb in enumerate(lmb_values): - pred_ridge_scikit[:,i] = (Ridge(alpha=lmb,fit_intercept=False).fit(X,y).predict(X)).flatten() # fit_intercept=False fordi bias er allerede i X - -plt.figure() - -plt.plot(x_plot,pred_ls_plot,label='ls') - -for i in range(num_values): - plt.plot(x_plot,pred_ridge_scikit[sort_ind,i],label='scikit-ridge, lmb=%g'%lmb_values[i]) - -plt.plot(x,y,'ro') -plt.legend() -plt.title('linear regression using scikit') - -plt.show() - -### R2-score of the results -for i in range(num_values): - print('lambda = %g'%lmb_values[i]) - print('r2 for scikit: %g'%r2_score(y,pred_ridge_scikit[:,i])) - print('r2 for own code, not centered: %g'%r2_score(y,pred_ridge[:,i])) - print('r2 for own, centered: %g\n'%r2_score(y,pred_ridge_centered[:,i])) - - -!ec +Before we proceed, we need to rethink what we have been doing. In our +eager to fit the data, we have omitted several important elements in +our regression analysis. In what follows we will +o look at statistical properties, including a discussion of mean values, variance and the so-called bias-variance tradeoff +o introduce resampling techniques like cross-validation, bootstrapping and jackknife and more +This will allow us to link the standard linear algebra methods we have discussed above to a statistical interpretation of the methods. ===== Resampling methods ===== -!bblock + Resampling methods are an indispensable tool in modern statistics. They involve repeatedly drawing samples from a training set and refitting a model of interest on each sample in order to @@ -5835,11 +3158,8 @@ regression to each new sample, and then examine the extent to which the resulting fits differ. Such an approach may allow us to obtain information that would not be available from fitting the model only once using the original training sample. -!eblock -===== Resampling approaches can be computationally expensive ===== -!bblock Resampling approaches can be computationally expensive, because they involve fitting the same statistical method multiple times using different subsets of the training data. However, due to recent @@ -5855,31 +3175,22 @@ of flexibility. The process of evaluating a model’s performance is known as model assessment, whereas the process of selecting the proper level of flexibility for a model is known as model selection. The bootstrap is widely used. -!eblock - ===== Why resampling methods ? ===== -!bblock Statistical analysis - * Our simulations can be treated as *computer experiments*. This is particularly the case for Monte Carlo methods - * The results can be analysed with the same statistical tools as we would use analysing experimental data. - * As in all experiments, we are looking for expectation values and an estimate of how accurate they are, i.e., possible sources for errors. + +* Our simulations can be treated as *computer experiments*. This is particularly the case for Monte Carlo methods +* The results can be analysed with the same statistical tools as we would use analysing experimental data. +* As in all experiments, we are looking for expectation values and an estimate of how accurate they are, i.e., possible sources for errors. -!eblock - - -===== Statistical analysis ===== -!bblock - * As in other experiments, many numerical experiments have two classes of errors: - * Statistical errors - * Systematical errors - * Statistical errors can be estimated using standard tools from statistics - * Systematical errors are method specific and must be treated differently from case to case. -!eblock - +* As in other experiments, many numerical experiments have two classes of errors: + * Statistical errors + * Systematical errors +* Statistical errors can be estimated using standard tools from statistics +* Systematical errors are method specific and must be treated differently from case to case. ===== Statistics ===== -!bblock + The *probability distribution function (PDF)* is a function $p(x)$ on the domain which, in the discrete case, gives us the probability or relative frequency with which these values of $X$ occur: @@ -5903,44 +3214,622 @@ on a non-infinitesimal interval $[a,\,b]$ is then just the integral: Qualitatively speaking, a stochastic variable represents the values of numbers chosen as if by chance from some specified PDF so that the selection of a large set of these numbers reproduces this PDF. -!eblock - - - - - - -===== Log-likelihood ===== - -A popular strategy is to choose a penalty parameter that yields a good -but parsimonious model. Information criteria measure the balance -between model fit and model complexity. One possibility is Aikaike's -information criterion (AIC). -The AIC measures model fit by the log-likelihood -and model complexity is measured by the number of parameters used by -the model. The number of model parameters in regular regression simply -corresponds to the number of covariates in the model. Or, by the -degrees of freedom consumed by the model, which is equivalent to the -trace of the hat matrix. For ridge regression it thus seems natural to -define model complexity analogously by the trace of the ridge hat -matrix. This yields the AIC for the linear regression model with ridge -estimates: - +A particularly useful class of special expectation values are the +*moments*. The $n$-th moment of the PDF $p$ is defined as +follows: !bt -\begin{align*} -\mbox{AIC}(\lambda) & = 2 \, p - 2 \log(\hat{L}) -\\ -& = 2 \, \mbox{tr} [\mathbf{H}(\lambda)] - 2 \log\{L[\hat{\beta}(\lambda), \hat{\sigma}^2(\lambda)]\} -\\ -& = 2 \, \sum_{j=1}^p \frac{d_{jj}^2}{d_{jj}^2 + \lambda} -+ 2 n \, \log[\sqrt{2 \, \pi} \, \hat{\sigma}(\lambda)] + \frac{1}{\hat{\sigma}^2(\lambda)} \sum_{i=1}^n [y_i - \mathbf{X}_{i, \ast} \, \hat{\beta}(\lambda)]^2. +\[ +\langle x^n\rangle \equiv \int\! x^n p(x)\,dx +\] +!et +The zero-th moment $\langle 1\rangle$ is just the normalization condition of +$p$. The first moment, $\langle x\rangle$, is called the *mean* of $p$ +and often denoted by the letter $\mu$: +!bt +\[ +\langle x\rangle = \mu \equiv \int\! x p(x)\,dx +\] +!et + +A special version of the moments is the set of *central moments*, +the n-th central moment defined as: +!bt +\[ +\langle (x-\langle x \rangle )^n\rangle \equiv \int\! (x-\langle x\rangle)^n p(x)\,dx +\] +!et +The zero-th and first central moments are both trivial, equal $1$ and +$0$, respectively. But the second central moment, known as the +*variance* of $p$, is of particular interest. For the stochastic +variable $X$, the variance is denoted as $\sigma^2_X$ or $\mathrm{var}(X)$: +!bt +\begin{align} +\sigma^2_X\ \ =\ \ \mathrm{var}(X) & = \langle (x-\langle x\rangle)^2\rangle = +\int\! (x-\langle x\rangle)^2 p(x)\,dx\\ +& = \int\! \left(x^2 - 2 x \langle x\rangle^{2} + + \langle x\rangle^2\right)p(x)\,dx\\ +& = \langle x^2\rangle - 2 \langle x\rangle\langle x\rangle + \langle x\rangle^2\\ +& = \langle x^2\rangle - \langle x\rangle^2 +\end{align} +!et +The square root of the variance, $\sigma =\sqrt{\langle (x-\langle x\rangle)^2\rangle}$ is called the *standard deviation* of $p$. It is clearly just the RMS (root-mean-square) +value of the deviation of the PDF from its mean value, interpreted +qualitatively as the *spread* of $p$ around its mean. + + + +===== Statistics, covariance ===== + +Another important quantity is the so called covariance, a variant of +the above defined variance. Consider again the set $\{X_i\}$ of $n$ +stochastic variables (not necessarily uncorrelated) with the +multivariate PDF $P(x_1,\dots,x_n)$. The *covariance* of two +of the stochastic variables, $X_i$ and $X_j$, is defined as follows: +!bt +\begin{align} +\mathrm{cov}(X_i,\,X_j) &\equiv \langle (x_i-\langle x_i\rangle)(x_j-\langle x_j\rangle)\rangle +\nonumber\\ +&= +\int\!\cdots\!\int\!(x_i-\langle x_i \rangle)(x_j-\langle x_j \rangle)\, +P(x_1,\dots,x_n)\,dx_1\dots dx_n +label{eq:def_covariance} +\end{align} +!et +with +!bt +\[ +\langle x_i\rangle = +\int\!\cdots\!\int\!x_i\,P(x_1,\dots,x_n)\,dx_1\dots dx_n +\] +!et + +If we consider the above covariance as a matrix $C_{ij}=\mathrm{cov}(X_i,\,X_j)$, then the diagonal elements are just the familiar +variances, $C_{ii} = \mathrm{cov}(X_i,\,X_i) = \mathrm{var}(X_i)$. It turns out that +all the off-diagonal elements are zero if the stochastic variables are +uncorrelated. This is easy to show, keeping in mind the linearity of +the expectation value. Consider the stochastic variables $X_i$ and +$X_j$, ($i\neq j$): +!bt +\begin{align} +\mathrm{cov}(X_i,\,X_j) &= \langle(x_i-\langle x_i\rangle)(x_j-\langle x_j\rangle)\rangle\\ +&=\langle x_i x_j - x_i\langle x_j\rangle - \langle x_i\rangle x_j + \langle x_i\rangle\langle x_j\rangle\rangle \\ +&=\langle x_i x_j\rangle - \langle x_i\langle x_j\rangle\rangle - \langle \langle x_i\rangle x_j\rangle + +\langle \langle x_i\rangle\langle x_j\rangle\rangle\\ +&=\langle x_i x_j\rangle - \langle x_i\rangle\langle x_j\rangle - \langle x_i\rangle\langle x_j\rangle + +\langle x_i\rangle\langle x_j\rangle\\ +&=\langle x_i x_j\rangle - \langle x_i\rangle\langle x_j\rangle +\end{align} +!et + +===== Statistics, independent variables ===== + +If $X_i$ and $X_j$ are independent, we get +$\langle x_i x_j\rangle =\langle x_i\rangle\langle x_j\rangle$, resulting in $\mathrm{cov}(X_i, X_j) = 0\ \ (i\neq j)$. + +Also useful for us is the covariance of linear combinations of +stochastic variables. Let $\{X_i\}$ and $\{Y_i\}$ be two sets of +stochastic variables. Let also $\{a_i\}$ and $\{b_i\}$ be two sets of +scalars. Consider the linear combination: +!bt +\[ +U = \sum_i a_i X_i \qquad V = \sum_j b_j Y_j +\] +!et +By the linearity of the expectation value +!bt +\[ +\mathrm{cov}(U, V) = \sum_{i,j}a_i b_j \mathrm{cov}(X_i, Y_j) +\] +!et + +Now, since the variance is just $\mathrm{var}(X_i) = \mathrm{cov}(X_i, X_i)$, we get +the variance of the linear combination $U = \sum_i a_i X_i$: +!bt +\begin{equation} +\mathrm{var}(U) = \sum_{i,j}a_i a_j \mathrm{cov}(X_i, X_j) +label{eq:variance_linear_combination} +\end{equation} +!et +And in the special case when the stochastic variables are +uncorrelated, the off-diagonal elements of the covariance are as we +know zero, resulting in: +!bt +\[ +\mathrm{var}(U) = \sum_i a_i^2 \mathrm{cov}(X_i, X_i) = \sum_i a_i^2 \mathrm{var}(X_i) +\] +!et +!bt +\[ +\mathrm{var}(\sum_i a_i X_i) = \sum_i a_i^2 \mathrm{var}(X_i) +\] +!et +which will become very useful in our study of the error in the mean +value of a set of measurements. + +===== Statistics and stochastic processes ===== + +A *stochastic process* is a process that produces sequentially a +chain of values: +!bt +\[ +\{x_1, x_2,\dots\,x_k,\dots\}. +\] +!et +We will call these +values our *measurements* and the entire set as our measured +*sample*. The action of measuring all the elements of a sample +we will call a stochastic *experiment* since, operationally, +they are often associated with results of empirical observation of +some physical or mathematical phenomena; precisely an experiment. We +assume that these values are distributed according to some +PDF $p_X^{\phantom X}(x)$, where $X$ is just the formal symbol for the +stochastic variable whose PDF is $p_X^{\phantom X}(x)$. Instead of +trying to determine the full distribution $p$ we are often only +interested in finding the few lowest moments, like the mean +$\mu_X^{\phantom X}$ and the variance $\sigma_X^{\phantom X}$. + +In practical situations a sample is always of finite size. Let that +size be $n$. The expectation value of a sample, the *sample mean*, is then defined as follows: +!bt +\[ +\bar{x}_n \equiv \frac{1}{n}\sum_{k=1}^n x_k +\] +!et +The *sample variance* is: +!bt +\[ +\mathrm{var}(x) \equiv \frac{1}{n}\sum_{k=1}^n (x_k - \bar{x}_n)^2 +\] +!et +its square root being the *standard deviation of the sample*. The +*sample covariance* is: +!bt +\[ +\mathrm{cov}(x)\equiv\frac{1}{n}\sum_{kl}(x_k - \bar{x}_n)(x_l - \bar{x}_n) +\] +!et + +Note that the sample variance is the sample covariance without the +cross terms. In a similar manner as the covariance in Eq.~(ref{eq:def_covariance}) is a measure of the correlation between +two stochastic variables, the above defined sample covariance is a +measure of the sequential correlation between succeeding measurements +of a sample. + +These quantities, being known experimental values, differ +significantly from and must not be confused with the similarly named +quantities for stochastic variables, mean $\mu_X$, variance $\mathrm{var}(X)$ +and covariance $\mathrm{cov}(X,Y)$. + +The law of large numbers +states that as the size of our sample grows to infinity, the sample +mean approaches the true mean $\mu_X^{\phantom X}$ of the chosen PDF: +!bt +\[ +\lim_{n\to\infty}\bar{x}_n = \mu_X^{\phantom X} +\] +!et +The sample mean $\bar{x}_n$ works therefore as an estimate of the true +mean $\mu_X^{\phantom X}$. + +What we need to find out is how good an approximation $\bar{x}_n$ is to +$\mu_X^{\phantom X}$. In any stochastic measurement, an estimated +mean is of no use to us without a measure of its error. A quantity +that tells us how well we can reproduce it in another experiment. We +are therefore interested in the PDF of the sample mean itself. Its +standard deviation will be a measure of the spread of sample means, +and we will simply call it the *error* of the sample mean, or +just sample error, and denote it by $\mathrm{err}_X^{\phantom X}$. In +practice, we will only be able to produce an *estimate* of the +sample error since the exact value would require the knowledge of the +true PDFs behind, which we usually do not have. + +===== Statistics, more on sample error ===== + +Let us first take a look at what happens to the sample error as the +size of the sample grows. In a sample, each of the measurements $x_i$ +can be associated with its own stochastic variable $X_i$. The +stochastic variable $\overline X_n$ for the sample mean $\bar{x}_n$ is +then just a linear combination, already familiar to us: +!bt +\[ +\overline X_n = \frac{1}{n}\sum_{i=1}^n X_i +\] +!et +All the coefficients are just equal $1/n$. The PDF of $\overline X_n$, +denoted by $p_{\overline X_n}(x)$ is the desired PDF of the sample +means. + +The probability density of obtaining a sample mean $\bar x_n$ +is the product of probabilities of obtaining arbitrary values $x_1, +x_2,\dots,x_n$ with the constraint that the mean of the set $\{x_i\}$ +is $\bar x_n$: +!bt +\[ +p_{\overline X_n}(x) = \int p_X^{\phantom X}(x_1)\cdots +\int p_X^{\phantom X}(x_n)\ +\delta\!\left(x - \frac{x_1+x_2+\dots+x_n}{n}\right)dx_n \cdots dx_1 +\] +!et +And in particular we are interested in its variance $\mathrm{var}(\overline X_n)$. + +===== Statistics, central limit theorem ===== + +It is generally not possible to express $p_{\overline X_n}(x)$ in a +closed form given an arbitrary PDF $p_X^{\phantom X}$ and a number +$n$. But for the limit $n\to\infty$ it is possible to make an +approximation. The very important result is called *the central limit theorem*. It tells us that as $n$ goes to infinity, +$p_{\overline X_n}(x)$ approaches a Gaussian distribution whose mean +and variance equal the true mean and variance, $\mu_{X}^{\phantom X}$ +and $\sigma_{X}^{2}$, respectively: +!bt +\begin{equation} +\lim_{n\to\infty} p_{\overline X_n}(x) = +\left(\frac{n}{2\pi\mathrm{var}(X)}\right)^{1/2} +e^{-\frac{n(x-\bar x_n)^2}{2\mathrm{var}(X)}} +label{eq:central_limit_gaussian} +\end{equation} +!et + + +The desired variance +$\mathrm{var}(\overline X_n)$, i.e. the sample error squared +$\mathrm{err}_X^2$, is given by: +!bt +\begin{equation} +\mathrm{err}_X^2 = \mathrm{var}(\overline X_n) = \frac{1}{n^2} +\sum_{ij} \mathrm{cov}(X_i, X_j) +label{eq:error_exact} +\end{equation} +!et +We see now that in order to calculate the exact error of the sample +with the above expression, we would need the true means +$\mu_{X_i}^{\phantom X}$ of the stochastic variables $X_i$. To +calculate these requires that we know the true multivariate PDF of all +the $X_i$. But this PDF is unknown to us, we have only got the measurements of +one sample. The best we can do is to let the sample itself be an +estimate of the PDF of each of the $X_i$, estimating all properties of +$X_i$ through the measurements of the sample. + +Our estimate of $\mu_{X_i}^{\phantom X}$ is then the sample mean $\bar x$ +itself, in accordance with the the central limit theorem: +!bt +\[ +\mu_{X_i}^{\phantom X} = \langle x_i\rangle \approx \frac{1}{n}\sum_{k=1}^n x_k = \bar x +\] +!et +Using $\bar x$ in place of $\mu_{X_i}^{\phantom X}$ we can give an +*estimate* of the covariance in Eq.~(ref{eq:error_exact}) +!bt +\[ +\mathrm{cov}(X_i, X_j) = \langle (x_i-\langle x_i\rangle)(x_j-\langle x_j\rangle)\rangle +\approx\langle (x_i - \bar x)(x_j - \bar{x})\rangle, +\] +!et +resulting in +!bt +\[ +\frac{1}{n} \sum_{l}^n \left(\frac{1}{n}\sum_{k}^n (x_k -\bar x_n)(x_l - \bar x_n)\right)=\frac{1}{n}\frac{1}{n} \sum_{kl} (x_k -\bar x_n)(x_l - \bar x_n)=\frac{1}{n}\mathrm{cov}(x) +\] +!et + +By the same procedure we can use the sample variance as an +estimate of the variance of any of the stochastic variables $X_i$ +!bt +\[ +\mathrm{var}(X_i)=\langle x_i - \langle x_i\rangle\rangle \approx \langle x_i - \bar x_n\rangle\nonumber, +\] +!et +which is approximated as +!bt +\begin{equation} +\mathrm{var}(X_i)\approx \frac{1}{n}\sum_{k=1}^n (x_k - \bar x_n)=\mathrm{var}(x) +label{eq:var_estimate_i_think} +\end{equation} +!et + +Now we can calculate an estimate of the error +$\mathrm{err}_X^{\phantom X}$ of the sample mean $\bar x_n$: +!bt +\begin{align} +\mathrm{err}_X^2 +&=\frac{1}{n^2}\sum_{ij} \mathrm{cov}(X_i, X_j) \nonumber \\ +&\approx&\frac{1}{n^2}\sum_{ij}\frac{1}{n}\mathrm{cov}(x) =\frac{1}{n^2}n^2\frac{1}{n}\mathrm{cov}(x)\nonumber\\ +&=\frac{1}{n}\mathrm{cov}(x) +label{eq:error_estimate} +\end{align} +!et +which is nothing but the sample covariance divided by the number of +measurements in the sample. + +In the special case that the measurements of the sample are +uncorrelated (equivalently the stochastic variables $X_i$ are +uncorrelated) we have that the off-diagonal elements of the covariance +are zero. This gives the following estimate of the sample error: +!bt +\[ +\mathrm{err}_X^2=\frac{1}{n^2}\sum_{ij} \mathrm{cov}(X_i, X_j) = +\frac{1}{n^2} \sum_i \mathrm{var}(X_i), +\] +!et +resulting in +!bt +\begin{equation} +\mathrm{err}_X^2\approx \frac{1}{n^2} \sum_i \mathrm{var}(x)= \frac{1}{n}\mathrm{var}(x) +label{eq:error_estimate_uncorrel} +\end{equation} +!et +where in the second step we have used Eq.~(ref{eq:var_estimate_i_think}). +The error of the sample is then just its standard deviation divided by +the square root of the number of measurements the sample contains. +This is a very useful formula which is easy to compute. It acts as a +first approximation to the error, but in numerical experiments, we +cannot overlook the always present correlations. + +For computational purposes one usually splits up the estimate of +$\mathrm{err}_X^2$, given by Eq.~(ref{eq:error_estimate}), into two +parts +!bt +\[ +\mathrm{err}_X^2 = \frac{1}{n}\mathrm{var}(x) + \frac{1}{n}(\mathrm{cov}(x)-\mathrm{var}(x)), +\] +!et +which equals +!bt +\begin{equation} +\frac{1}{n^2}\sum_{k=1}^n (x_k - \bar x_n)^2 +\frac{2}{n^2}\sum_{k 0$. We say then that the ridge estimator is biased. + +We can also compute the variance as + +!bt +\[ +\mbox{Var}[\bm{\beta}^{\mathrm{Ridge}}]=\sigma^2[ \mathbf{X}^{T} \mathbf{X} + \lambda \mathbf{I} ]^{-1} \mathbf{X}^{T} \mathbf{X} \{ [ \mathbf{X}^{\top} \mathbf{X} + \lambda \mathbf{I} ]^{-1}\}^{T}, +\] +!et +and it is easy to see that if the parameter $\lambda$ goes to infinity then the variance of Ridge parameters $\bm{\beta}$ goes to zero. + +With this, we can compute the difference + +!bt +\[ +\mbox{Var}[\bm{\beta}^{\mathrm{OLS}}]-\mbox{Var}(\bm{\beta}^{\mathrm{Ridge}})=\sigma^2 [ \mathbf{X}^{T} \mathbf{X} + \lambda \mathbf{I} ]^{-1}[ 2\lambda\mathbf{I} + \lambda^2 (\mathbf{X}^{T} \mathbf{X})^{-1} ] \{ [ \mathbf{X}^{T} \mathbf{X} + \lambda \mathbf{I} ]^{-1}\}^{T}. +\] +!et +The difference is non-negative definite since each component of the +matrix product is non-negative definite. +This means the variance we obtain with the standard OLS will always for $\lambda > 0$ be larger than the variance of $\bm{\beta}$ obtained with the Ridge estimator. This has interesting consequences when we discuss the so-called bias-variance trade-off below. - ===== Cross-validation ===== Instead of choosing the penalty parameter to balance model fit with @@ -5948,12 +3837,14 @@ model complexity, cross-validation requires it (i.e. the penalty parameter) to yield a model with good prediction performance. Commonly, this performance is evaluated on novel data. Novel data need not be easy to come by and one has to make do -with the data at hand. The setting of `original' and novel data is +with the data at hand. + +The setting of _original_ and novel data is then mimicked by sample splitting: the data set is divided into two -(groups of samples). One of these two data sets, called the *training -set*, plays the role of `original' data on which the model is +(groups of samples). One of these two data sets, called the +*training set*, plays the role of _original_ data on which the model is built. The second of these data sets, called the *test set*, plays the -role of the `novel' data and is used to evaluate the prediction +role of the _novel_ data and is used to evaluate the prediction performance (often operationalized as the log-likelihood or the prediction error or its square or the R2 score) of the model built on the training data set. This procedure (model building and prediction evaluation on training and @@ -5980,7 +3871,7 @@ The validation set approach is conceptually simple and is easy to implement. But - + ===== Various steps in cross-validation ===== When the repetitive splitting of the data set is done randomly, @@ -5998,52 +3889,36 @@ involves a degree of randomness. This may be fully excluded when choosing $k=n$. This particular case is referred to as leave-one-out cross-validation (LOOCV). - + ===== How to set up the cross-validation for Ridge and/or Lasso ===== * Define a range of interest for the penalty parameter. * Divide the data set into training and test set comprising samples $\{1, \ldots, n\} \setminus i$ and $\{ i \}$, respectively. -* Fit the linear regression model by means of ridge estimation for each $\lambda$ in the grid using the training set, and the corresponding estimate of the error variance $\hat{\sigma}_{-i}^2(\lambda)$, as +* Fit the linear regression model by means of ridge estimation for each $\lambda$ in the grid using the training set, and the corresponding estimate of the error variance $\bm{\sigma}_{-i}^2(\lambda)$, as !bt \begin{align*} -\hat{\beta}_{-i}(\lambda) & = ( \hat{X}_{-i, \ast}^{\top} -\hat{X}_{-i, \ast} + \lambda \hat{I}_{pp})^{-1} -\hat{X}_{-i, \ast}^{\top} \hat{y}_{-i} +\bm{\beta}_{-i}(\lambda) & = ( \bm{X}_{-i, \ast}^{T} +\bm{X}_{-i, \ast} + \lambda \bm{I}_{pp})^{-1} +\bm{X}_{-i, \ast}^{T} \bm{y}_{-i} \end{align*} !et -* Evaluate the prediction performance of these models on the test set by $\log\{L[y_i, \hat{X}_{i, \ast}; \hat{\beta}_{-i}(\lambda), \hat{\sigma}_{-i}^2(\lambda)]\}$. Or, by the prediction error $|y_i - \hat{X}_{i, \ast} \hat{\beta}_{-i}(\lambda)|$, the relative error, the error squared or the R2 score function. +* Evaluate the prediction performance of these models on the test set by $\log\{L[y_i, \bm{X}_{i, \ast}; \bm{\beta}_{-i}(\lambda), \bm{\sigma}_{-i}^2(\lambda)]\}$. Or, by the prediction error $|y_i - \bm{X}_{i, \ast} \bm{\beta}_{-i}(\lambda)|$, the relative error, the error squared or the R2 score function. * Repeat the first three steps such that each sample plays the role of the test set once. * Average the prediction performances of the test sets at each grid point of the penalty bias/parameter by computing the *cross-validated log-likelihood*. It is an estimate of the prediction performance of the model corresponding to this value of the penalty parameter on novel data. It is defined as !bt \begin{align*} -\frac{1}{n} \sum_{i = 1}^n \log\{L[y_i, \mathbf{X}_{i, \ast}; \hat{\beta}_{-i}(\lambda), \hat{\sigma}_{-i}^2(\lambda)]\}. +\frac{1}{n} \sum_{i = 1}^n \log\{L[y_i, \mathbf{X}_{i, \ast}; \bm{\beta}_{-i}(\lambda), \bm{\sigma}_{-i}^2(\lambda)]\}. \end{align*} !et * The value of the penalty parameter that maximizes the cross-validated log-likelihood is the value of choice. Or we can use the MSE or the R2 score functions. -===== Predicted Residual Error Sum of Squares ===== -!bblock -Another approach in the LOOCV scheme is to the use the so-called Predicted Residual Error Sum of Squares (PRESS). - -We can define the optimal penalty parameter to minimize -!bt -\begin{align*} -\lambda_{\mbox{{\tiny opt}}} = \arg \min_{\lambda} \frac{1}{n} \sum_{i=1}^n [y_i - \hat{X}_{i, \ast} \hat{\beta}_{-i}(\lambda)]^2. -\end{align*} -!et - -The LOOCV prediction performance can be -expressed analytically in terms of the known quantities derived from -the design matrix and the parameters $\beta$. -!eblock - ===== Resampling methods: Jackknife and Bootstrap ===== @@ -6067,33 +3942,20 @@ need for bootstrapping. ===== Resampling methods: Jackknife ===== The Jackknife works by making many replicas of the estimator $\widehat{\theta}$. -The jackknife is a resampling method, we explained that this happens by scrambling the data in some way. When using the jackknife, this is done by systematically leaving out one observation from the vector of observed values $\hat{x} = (x_1,x_2,\cdots,X_n)$. -Let $\hat{x}_i$ denote the vector +The jackknife is a resampling method where we systematically leave out one observation from the vector of observed values $\bm{x} = (x_1,x_2,\cdots,X_n)$. +Let $\bm{x}_i$ denote the vector !bt \[ -\hat{x}_i = (x_1,x_2,\cdots,x_{i-1},x_{i+1},\cdots,x_n), +\bm{x}_i = (x_1,x_2,\cdots,x_{i-1},x_{i+1},\cdots,x_n), \] !et -which equals the vector $\hat{x}$ with the exception that observation +which equals the vector $\bm{x}$ with the exception that observation number $i$ is left out. Using this notation, define $\widehat{\theta}_i$ to be the estimator $\widehat{\theta}$ computed using $\vec{X}_i$. -===== Resampling methods: Jackknife estimator ===== - -To get an estimate for the bias and -standard error of $\widehat{\theta}$, use the following -estimators for each component of $\widehat{\theta}$ - -!bt -\[ -\widehat{\mathrm{Bias}}(\widehat \theta,\theta) = (n-1)\left( - \widehat{\theta} + \frac{1}{n}\sum_{i=1}^{n} \widehat \theta_i \right) \qquad \text{and} \qquad \widehat{\sigma}^2_{\widehat{\theta} } = \frac{n-1}{n}\sum_{i=1}^{n}( \widehat{\theta}_i - \frac{1}{n}\sum_{j=1}^{n}\widehat \theta_j )^2. -\] -!et - - ===== Jackknife code example ===== !bc pycod @@ -6131,7 +3993,7 @@ t = jackknife(x, stat) ===== Resampling methods: Bootstrap ===== -!bblock + Bootstrapping is a nonparametric approach to statistical inference that substitutes computation for more traditional distributional assumptions and asymptotic results. Bootstrapping offers a number of @@ -6140,20 +4002,20 @@ o The bootstrap is quite general, although there are some cases in which it fail o Because it does not require distributional assumptions (such as normally distributed errors), the bootstrap can provide more accurate inferences when the data are not well behaved or when the sample size is small. o It is possible to apply the bootstrap to statistics with sampling distributions that are difficult to derive, even asymptotically. o It is relatively simple to apply the bootstrap to complex data-collection plans (such as stratified and clustered samples). -!eblock + ===== Resampling methods: Bootstrap background ===== -Since $\widehat{\theta} = \widehat{\theta}(\hat{X})$ is a function of random variables, +Since $\widehat{\theta} = \widehat{\theta}(\bm{X})$ is a function of random variables, $\widehat{\theta}$ itself must be a random variable. Thus it has -a pdf, call this function $p(\hat{t})$. The aim of the bootstrap is to -estimate $p(\hat{t})$ by the relative frequency of +a pdf, call this function $p(\bm{t})$. The aim of the bootstrap is to +estimate $p(\bm{t})$ by the relative frequency of $\widehat{\theta}$. You can think of this as using a histogram -in the place of $p(\hat{t})$. If the relative frequency closely +in the place of $p(\bm{t})$. If the relative frequency closely resembles $p(\vec{t})$, then using numerics, it is straight forward to -estimate all the interesting parameters of $p(\hat{t})$ using point +estimate all the interesting parameters of $p(\bm{t})$ using point estimators. @@ -6171,7 +4033,7 @@ o Then using these numbers, we could compute a replica of $\widehat{\theta}$ cal By repeated use of (1) and (2), many estimates of $\widehat{\theta}$ could have been obtained. The idea is to use the relative frequency of $\widehat{\theta}^*$ -(think of a histogram) as an estimate of $p(\hat{t})$. +(think of a histogram) as an estimate of $p(\bm{t})$. ===== Resampling methods: Bootstrap approach ===== @@ -6189,24 +4051,46 @@ result in some asymptotic sense? The answer is yes. Instead of generating the histogram for the relative frequency of the observation $X_i$, just draw the values $(X_1^*,X_2^*,\cdots,X_n^*)$ with replacement from the vector -$\hat{X}$. +$\bm{X}$. ===== Resampling methods: Bootstrap steps ===== The independent bootstrap works like this: -o Draw with replacement $n$ numbers for the observed variables $\hat{x} = (x_1,x_2,\cdots,x_n)$. -o Define a vector $\hat{x}^*$ containing the values which were drawn from $\hat{x}$. -o Using the vector $\hat{x}^*$ compute $\widehat{\theta}^*$ by evaluating $\widehat \theta$ under the observations $\hat{x}^*$. +o Draw with replacement $n$ numbers for the observed variables $\bm{x} = (x_1,x_2,\cdots,x_n)$. +o Define a vector $\bm{x}^*$ containing the values which were drawn from $\bm{x}$. +o Using the vector $\bm{x}^*$ compute $\widehat{\theta}^*$ by evaluating $\widehat \theta$ under the observations $\bm{x}^*$. o Repeat this process $k$ times. -When you are done, you can draw a histogram of the relative frequency of $\widehat \theta^*$. This is your estimate of the probability distribution $p(t)$. Using this probability distribution you can estimate any statistics thereof. In principle you never draw the histogram of the relative frequency of $\widehat{\theta}^*$. Instead you use the estimators corresponding to the statistic of interest. For example, if you are interested in estimating the variance of $\widehat \theta$, apply the etsimator $\widehat \sigma^2$ to the values $\widehat \theta ^*$. +When you are done, you can draw a histogram of the relative frequency +of $\widehat \theta^*$. This is your estimate of the probability +distribution $p(t)$. Using this probability distribution you can +estimate any statistics thereof. In principle you never draw the +histogram of the relative frequency of $\widehat{\theta}^*$. Instead +you use the estimators corresponding to the statistic of interest. For +example, if you are interested in estimating the variance of $\widehat +\theta$, apply the etsimator $\widehat \sigma^2$ to the values +$\widehat \theta ^*$. ===== Code example for the Bootstrap method ===== -The following code starts with a Gaussian distribution with mean value $\mu =100$ and variance $\sigma=15$. We use this to generate the data used in the bootstrap analysis. The bootstrap analysis returns a data set after a given number of bootstrap operations (as many as we have data points). This data set consists of estimated mean values for each bootstrap operation. The histogram generated by the bootstrap method shows that the distribution for these mean values is also a Gaussian, centered around the mean value $\mu=100$ but with standard deviation $\sigma/\sqrt{n}$, where $n$ is the number of bootstrap samples (in this case the same as the number of original data points). The value of the standard deviation is what we expect from the central limit theorem. + +The following code starts with a Gaussian distribution with mean value +$\mu =100$ and variance $\sigma=15$. We use this to generate the data +used in the bootstrap analysis. The bootstrap analysis returns a data +set after a given number of bootstrap operations (as many as we have +data points). This data set consists of estimated mean values for each +bootstrap operation. The histogram generated by the bootstrap method +shows that the distribution for these mean values is also a Gaussian, +centered around the mean value $\mu=100$ but with standard deviation +$\sigma/\sqrt{n}$, where $n$ is the number of bootstrap samples (in +this case the same as the number of original data points). The value +of the standard deviation is what we expect from the central limit +theorem. + + !bc pycod from numpy import * from numpy.random import randint, randn @@ -6218,30 +4102,29 @@ import matplotlib.pyplot as plt def stat(data): return mean(data) -# Bootstrap algorithm +# Bootstrap algorithm def bootstrap(data, statistic, R): t = zeros(R); n = len(data); inds = arange(n); t0 = time() - - # non-parametric bootstrap + # non-parametric bootstrap for i in range(R): t[i] = statistic(data[randint(0,n,n)]) - # analysis + # analysis print("Runtime: %g sec" % (time()-t0)); print("Bootstrap Statistics :") print("original bias std. error") - print("%8g %8g %14g %15g" % (statistic(data), std(data),\ - mean(t), \ - std(t))) + print("%8g %8g %14g %15g" % (statistic(data), std(data),mean(t),std(t))) return t mu, sigma = 100, 15 datapoints = 10000 x = mu + sigma*random.randn(datapoints) -# bootstrap returns the data sample t = bootstrap(x, stat, datapoints) -# the histogram of the bootstrapped data n, binsboot, patches = plt.hist(t, 50, normed=1, facecolor='red', alpha=0.75) +# bootstrap returns the data sample +t = bootstrap(x, stat, datapoints) +# the histogram of the bootstrapped data +n, binsboot, patches = plt.hist(t, 50, normed=1, facecolor='red', alpha=0.75) -# add a 'best fit' line +# add a 'best fit' line y = mlab.normpdf( binsboot, mean(t), std(t)) lt = plt.plot(binsboot, y, 'r--', linewidth=1) plt.xlabel('Smarts') @@ -6255,342 +4138,99 @@ plt.show() -===== Resampling methods: Blocking ===== - -The blocking method was made popular by "Flyvbjerg and Pedersen (1989)":"https://aip.scitation.org/doi/10.1063/1.457480" -and has become one of the standard ways to estimate -$V(\widehat{\theta})$ for exactly one $\widehat{\theta}$, namely -$\widehat{\theta} = \overline{X}$. - -Assume $n = 2^d$ for some integer $d>1$ and $X_1,X_2,\cdots, X_n$ is a stationary time series to begin with. -Moreover, assume that the time series is asymptotically uncorrelated. We switch to vector notation by arranging $X_1,X_2,\cdots,X_n$ in an $n$-tuple. Define: -!bt -\begin{align*} -\hat{X} = (X_1,X_2,\cdots,X_n). -\end{align*} -!et - -The strength of the blocking method is when the number of -observations, $n$ is large. For large $n$, the complexity of dependent -bootstrapping scales poorly, but the blocking method does not, -moreover, it becomes more accurate the larger $n$ is. - - -===== Blocking Transformations ===== - We now define -blocking transformations. The idea is to take the mean of subsequent -pair of elements from $\vec{X}$ and form a new vector -$\vec{X}_1$. Continuing in the same way by taking the mean of -subsequent pairs of elements of $\vec{X}_1$ we obtain $\vec{X}_2$, and -so on. -Define $\vec{X}_i$ recursively by: - -!bt -\begin{align} -(\vec{X}_0)_k &\equiv (\vec{X})_k \nonumber \\ -(\vec{X}_{i+1})_k &\equiv \frac{1}{2}\Big( (\vec{X}_i)_{2k-1} + -(\vec{X}_i)_{2k} \Big) \qquad \text{for all} \qquad 1 \leq i \leq d-1 -\end{align} -!et - -The quantity $\vec{X}_k$ is -subject to $k$ _blocking transformations_. We now have $d$ vectors -$\vec{X}_0, \vec{X}_1,\cdots,\vec X_{d-1}$ containing the subsequent -averages of observations. It turns out that if the components of -$\vec{X}$ is a stationary time series, then the components of -$\vec{X}_i$ is a stationary time series for all $0 \leq i \leq d-1$ - -We can then compute the autocovariance, the variance, sample mean, and -number of observations for each $i$. -Let $\gamma_i, \sigma_i^2, -\overline{X}_i$ denote the autocovariance, variance and average of the -elements of $\vec{X}_i$ and let $n_i$ be the number of elements of -$\vec{X}_i$. It follows by induction that $n_i = n/2^i$. - - -===== Blocking Transformations ===== - -Using the -definition of the blocking transformation and the distributive -property of the covariance, it is clear that since $h =|i-j|$ -we can define -!bt -\begin{align} -\gamma_{k+1}(h) &= cov\left( ({X}_{k+1})_{i}, ({X}_{k+1})_{j} \right) \nonumber \\ -&= \frac{1}{4}cov\left( ({X}_{k})_{2i-1} + ({X}_{k})_{2i}, ({X}_{k})_{2j-1} + ({X}_{k})_{2j} \right) \nonumber \\ -&= \frac{1}{2}\gamma_{k}(2h) + \frac{1}{2}\gamma_k(2h+1) \hspace{0.1cm} \mathrm{h = 0} \\ -&=\frac{1}{4}\gamma_k(2h-1) + \frac{1}{2}\gamma_k(2h) + \frac{1}{4}\gamma_k(2h+1) \quad \mathrm{else} -\end{align} -!et - -The quantity $\hat{X}$ is asymptotic uncorrelated by assumption, $\hat{X}_k$ is also asymptotic uncorrelated. Let's turn our attention to the variance of the sample mean $V(\overline{X})$. - - -===== Blocking Transformations, getting there ===== -We have -!bt -\begin{align} -V(\overline{X}_k) = \frac{\sigma_k^2}{n_k} + \underbrace{\frac{2}{n_k} \sum_{h=1}^{n_k-1}\left( 1 - \frac{h}{n_k} \right)\gamma_k(h)}_{\equiv e_k} = \frac{\sigma^2_k}{n_k} + e_k \quad \text{if} \quad \gamma_k(0) = \sigma_k^2. -\end{align} -!et -The term $e_k$ is called the _truncation error_: -!bt -\begin{equation} -e_k = \frac{2}{n_k} \sum_{h=1}^{n_k-1}\left( 1 - \frac{h}{n_k} \right)\gamma_k(h). -\end{equation} -!et -We can show that $V(\overline{X}_i) = V(\overline{X}_j)$ for all $0 \leq i \leq d-1$ and $0 \leq j \leq d-1$. - - -===== Blocking Transformations, final expressions ===== - -We can then wrap up -!bt -\begin{align} -n_{j+1} \overline{X}_{j+1} &= \sum_{i=1}^{n_{j+1}} (\hat{X}_{j+1})_i = \frac{1}{2}\sum_{i=1}^{n_{j}/2} (\hat{X}_{j})_{2i-1} + (\hat{X}_{j})_{2i} \nonumber \\ -&= \frac{1}{2}\left[ (\hat{X}_j)_1 + (\hat{X}_j)_2 + \cdots + (\hat{X}_j)_{n_j} \right] = \underbrace{\frac{n_j}{2}}_{=n_{j+1}} \overline{X}_j = n_{j+1}\overline{X}_j. -\end{align} -!et -By repeated use of this equation we get $V(\overline{X}_i) = V(\overline{X}_0) = V(\overline{X})$ for all $0 \leq i \leq d-1$. This has the consequence that -!bt -\begin{align} -V(\overline{X}) = \frac{\sigma_k^2}{n_k} + e_k \qquad \text{for all} \qquad 0 \leq k \leq d-1. \label{eq:convergence} -\end{align} -!et - -Fyvbjerg and Petersen demonstrated that the sequence -$\{e_k\}_{k=0}^{d-1}$ is decreasing, and conjecture that the term -$e_k$ can be made as small as we would like by making $k$ (and hence -$d$) sufficiently large. The sequence is decreasing (Master of Science thesis by Marius Jonsson, UiO 2018). -It means we can apply blocking transformations until -$e_k$ is sufficiently small, and then estimate $V(\overline{X})$ by -$\widehat{\sigma}^2_k/n_k$. - - - -===== "Code examples for Blocking, Jackknife and bootstrap":"https://github.com/CompPhysics/MachineLearning/tree/master/doc/Programs/ResamplingAnalysisScripts" ===== +===== Code Example for Cross-validation and $k$-fold Cross-validation ===== +The code here uses Ridge regression with cross-validation (CV) resampling and $k$-fold CV in order to fit a specific polynomial. !bc pycod -from sys import argv -from os import mkdir, path -import time import numpy as np import matplotlib.pyplot as plt -from matplotlib.ticker import FormatStrFormatter -from matplotlib.font_manager import FontProperties +from sklearn.model_selection import KFold +from sklearn.linear_model import Ridge +from sklearn.model_selection import cross_val_score +from sklearn.preprocessing import PolynomialFeatures -# Timing Decorator -def timeFunction(f): - def wrap(*args): - time1 = time.time() - ret = f(*args) - time2 = time.time() - print '%s Function Took: \t %0.3f s' % (f.func_name.title(), (time2-time1)) - return ret - return wrap +# A seed just to ensure that the random numbers are the same for every run. +# Useful for eventual debugging. +np.random.seed(3155) -class dataAnalysisClass: - # General Init functions - def __init__(self, fileName, size=0): - self.inputFileName = fileName - self.loadData(size) - self.createOutputFolder() - self.avg = np.average(self.data) - self.var = np.var(self.data) - self.std = np.std(self.data) +# Generate the data. +nsamples = 100 +x = np.random.randn(nsamples) +y = 3*x**2 + np.random.randn(nsamples) - def loadData(self, size=0): - if size != 0: - with open(self.inputFileName) as inputFile: - self.data = np.zeros(size) - for x in xrange(size): - self.data[x] = float(next(inputFile)) - else: - self.data = np.loadtxt(self.inputFileName) +## Cross-validation on Ridge regression using KFold only - # Statistical Analysis with Multiple Methods - def runAllAnalyses(self): - if len(self.data) <= 100000: - print "Autocorrelation..." - self.autocorrelation() - print "Bootstrap..." - self.bootstrap() - print "Jackknife..." - self.jackknife() - print "Blocking..." - self.blocking() +# Decide degree on polynomial to fit +poly = PolynomialFeatures(degree = 6) - # Standard Autocorrelation - @timeFunction - def autocorrelation(self): - self.acf = np.zeros(len(self.data)/2) - for k in range(0, len(self.data)/2): - self.acf[k] = np.corrcoef(np.array([self.data[0:len(self.data)-k], \ - self.data[k:len(self.data)]]))[0,1] +# Decide which values of lambda to use +nlambdas = 500 +lambdas = np.logspace(-3, 5, nlambdas) - # Bootstrap - @timeFunction - def bootstrap(self, nBoots = 1000): - bootVec = np.zeros(nBoots) - for k in range(0,nBoots): - bootVec[k] = np.average(np.random.choice(self.data, len(self.data))) - self.bootAvg = np.average(bootVec) - self.bootVar = np.var(bootVec) - self.bootStd = np.std(bootVec) +# Initialize a KFold instance +k = 5 +kfold = KFold(n_splits = k) - # Jackknife - @timeFunction - def jackknife(self): - jackknVec = np.zeros(len(self.data)) - for k in range(0,len(self.data)): - jackknVec[k] = np.average(np.delete(self.data, k)) - self.jackknAvg = self.avg - (len(self.data) - 1) * (np.average(jackknVec) - self.avg) - self.jackknVar = float(len(self.data) - 1) * np.var(jackknVec) - self.jackknStd = np.sqrt(self.jackknVar) +# Perform the cross-validation to estimate MSE +scores_KFold = np.zeros((nlambdas, k)) - # Blocking - @timeFunction - def blocking(self, blockSizeMax = 500): - blockSizeMin = 1 +i = 0 +for lmb in lambdas: + ridge = Ridge(alpha = lmb) + j = 0 + for train_inds, test_inds in kfold.split(x): + xtrain = x[train_inds] + ytrain = y[train_inds] - self.blockSizes = [] - self.meanVec = [] - self.varVec = [] + xtest = x[test_inds] + ytest = y[test_inds] - for i in range(blockSizeMin, blockSizeMax): - if(len(self.data) % i != 0): - pass#continue - blockSize = i - meanTempVec = [] - varTempVec = [] - startPoint = 0 - endPoint = blockSize + Xtrain = poly.fit_transform(xtrain[:, np.newaxis]) + ridge.fit(Xtrain, ytrain[:, np.newaxis]) - while endPoint <= len(self.data): - meanTempVec.append(np.average(self.data[startPoint:endPoint])) - startPoint = endPoint - endPoint += blockSize - mean, var = np.average(meanTempVec), np.var(meanTempVec)/len(meanTempVec) - self.meanVec.append(mean) - self.varVec.append(var) - self.blockSizes.append(blockSize) + Xtest = poly.fit_transform(xtest[:, np.newaxis]) + ypred = ridge.predict(Xtest) - self.blockingAvg = np.average(self.meanVec[-200:]) - self.blockingVar = (np.average(self.varVec[-200:])) - self.blockingStd = np.sqrt(self.blockingVar) + scores_KFold[i,j] = np.sum((ypred - ytest[:, np.newaxis])**2)/np.size(ypred) + + j += 1 + i += 1 +estimated_mse_KFold = np.mean(scores_KFold, axis = 1) - # Plot of Data, Autocorrelation Function and Histogram - def plotAll(self): - self.createOutputFolder() - if len(self.data) <= 100000: - self.plotAutocorrelation() - self.plotData() - self.plotHistogram() - self.plotBlocking() +## Cross-validation using cross_val_score from sklearn along with KFold - # Create Output Plots Folder - def createOutputFolder(self): - self.outName = self.inputFileName[:-4] - if not path.exists(self.outName): - mkdir(self.outName) +# kfold is an instance initialized above as: +# kfold = KFold(n_splits = k) - # Plot the Dataset, Mean and Std - def plotData(self): - # Far away plot - font = {'fontname':'serif'} - plt.plot(range(0, len(self.data)), self.data, 'r-', linewidth=1) - plt.plot([0, len(self.data)], [self.avg, self.avg], 'b-', linewidth=1) - plt.plot([0, len(self.data)], [self.avg + self.std, self.avg + self.std], 'g--', linewidth=1) - plt.plot([0, len(self.data)], [self.avg - self.std, self.avg - self.std], 'g--', linewidth=1) - plt.ylim(self.avg - 5*self.std, self.avg + 5*self.std) - plt.gca().yaxis.set_major_formatter(FormatStrFormatter('%.4f')) - plt.xlim(0, len(self.data)) - plt.ylabel(self.outName.title() + ' Monte Carlo Evolution', **font) - plt.xlabel('MonteCarlo History', **font) - plt.title(self.outName.title(), **font) - plt.savefig(self.outName + "/data.eps") - plt.savefig(self.outName + "/data.png") - plt.clf() +estimated_mse_sklearn = np.zeros(nlambdas) +i = 0 +for lmb in lambdas: + ridge = Ridge(alpha = lmb) - # Plot Histogram of Dataset and Gaussian around it - def plotHistogram(self): - binNumber = 50 - font = {'fontname':'serif'} - count, bins, ignore = plt.hist(self.data, bins=np.linspace(self.avg - 5*self.std, self.avg + 5*self.std, binNumber)) - plt.plot([self.avg, self.avg], [0,np.max(count)+10], 'b-', linewidth=1) - plt.ylim(0,np.max(count)+10) - plt.ylabel(self.outName.title() + ' Histogram', **font) - plt.xlabel(self.outName.title() , **font) - plt.title('Counts', **font) + X = poly.fit_transform(x[:, np.newaxis]) + estimated_mse_folds = cross_val_score(ridge, X, y[:, np.newaxis], scoring='neg_mean_squared_error', cv=kfold) - #gaussian - norm = 0 - for i in range(0,len(bins)-1): - norm += (bins[i+1]-bins[i])*count[i] - plt.plot(bins, norm/(self.std * np.sqrt(2 * np.pi)) * np.exp( - (bins - self.avg)**2 / (2 * self.std**2) ), linewidth=1, color='r') - plt.savefig(self.outName + "/hist.eps") - plt.savefig(self.outName + "/hist.png") - plt.clf() + # cross_val_score return an array containing the estimated negative mse for every fold. + # we have to the the mean of every array in order to get an estimate of the mse of the model + estimated_mse_sklearn[i] = np.mean(-estimated_mse_folds) - # Plot the Autocorrelation Function - def plotAutocorrelation(self): - font = {'fontname':'serif'} - plt.plot(range(1, len(self.data)/2), self.acf[1:], 'r-') - plt.ylim(-1, 1) - plt.xlim(0, len(self.data)/2) - plt.ylabel('Autocorrelation Function', **font) - plt.xlabel('Lag', **font) - plt.title('Autocorrelation', **font) - plt.savefig(self.outName + "/autocorrelation.eps") - plt.savefig(self.outName + "/autocorrelation.png") - plt.clf() + i += 1 - def plotBlocking(self): - font = {'fontname':'serif'} - plt.plot(self.blockSizes, self.varVec, 'r-') - plt.ylabel('Variance', **font) - plt.xlabel('Block Size', **font) - plt.title('Blocking', **font) - plt.savefig(self.outName + "/blocking.eps") - plt.savefig(self.outName + "/blocking.png") - plt.clf() +## Plot and compare the slightly different ways to perform cross-validation - # Print Stuff to the Terminal - def printOutput(self): - print "\nSample Size: \t", len(self.data) - print "\n=========================================\n" - print "Sample Average: \t", self.avg - print "Sample Variance:\t", self.var - print "Sample Std: \t", self.std - print "\n=========================================\n" - print "Bootstrap Average: \t", self.bootAvg - print "Bootstrap Variance:\t", self.bootVar - print "Bootstrap Error: \t", self.bootStd - print "\n=========================================\n" - print "Jackknife Average: \t", self.jackknAvg - print "Jackknife Variance:\t", self.jackknVar - print "Jackknife Error: \t", self.jackknStd - print "\n=========================================\n" - print "Blocking Average: \t", self.blockingAvg - print "Blocking Variance:\t", self.blockingVar - print "Blocking Error: \t", self.blockingStd, "\n" +plt.figure() -# Initialize the class -if len(argv) > 2: - dataAnalysis = dataAnalysisClass(argv[1], int(argv[2])) -else: - dataAnalysis = dataAnalysisClass(argv[1]) +plt.plot(np.log10(lambdas), estimated_mse_sklearn, label = 'cross_val_score') +plt.plot(np.log10(lambdas), estimated_mse_KFold, 'r--', label = 'KFold') -# Run Analyses -dataAnalysis.runAllAnalyses() +plt.xlabel('log10(lambda)') +plt.ylabel('mse') -# Plot the data -dataAnalysis.plotAll() +plt.legend() -# Print Some Output -dataAnalysis.printOutput() +plt.show() !ec @@ -6598,139 +4238,204 @@ dataAnalysis.printOutput() ===== The bias-variance tradeoff ===== -We begin with an unknown function $y=f(x)$ and fix a \emph{hypothesis set} - $\mathcal{H}$ consisting of all functions we are willing to consider, - defined also on the domain of $f$. This set may be uncountably - infinite (e.g.~if there are real-valued parameters to fit). -The - choice of which functions to include in $\mathcal{H}$ usually depends - on our intuition about the problem of interest. The function $f(x)$ - produces a set of pairs $(x_i,y_i)$, $i=1\dots N$, which serve as the - observable data. Our goal is to select a function from the hypothesis - set $h\in\mathcal{H}$ which approximates $f(x)$ as best as possible, - namely, we would like to find $h\in\mathcal{H}$ such that $h\approx - f$ in some strict mathematical sense which we specify below. If this - is possible, we say that we \emph{learned} $f(x)$. But if the - function $f(x)$ can, in principle, take any value on - \emph{unobserved} inputs, how is it possible to learn in any - meaningful sense? - -===== Training and testing data ===== +We will discuss the bias-variance tradeoff in the context of +continuous predictions such as regression. However, many of the +intuitions and ideas discussed here also carry over to classification +tasks. Consider a dataset $\mathcal{L}$ consisting of the data +$\mathbf{X}_\mathcal{L}=\{(y_j, \boldsymbol{x}_j), j=0\ldots n-1\}$. -We will discuss the bias-variance tradeoff in the context of continuous predictions such as regression. However, many of the intuitions and ideas discussed here also carry over to classification tasks. Consider a dataset $\mathcal{L}$ consisting of the data $\mathbf{X}_\mathcal{L}=\{(y_j, \boldsymbol{x}_j), j=1\ldots N\}$. Let us assume that the true data is generated from a noisy model -!bt -\[ -y=f(\boldsymbol{x}) + \epsilon -\] -!et -where $\epsilon$ is normally distributed with mean zero and standard deviation $\sigma_\epsilon$. - - -===== Procedure to find a predictor ===== - -We have a statistical procedure (e.g. least-squares regression) for -forming a predictor $\hat{g}_{\mathcal{L}}(\boldsymbol{x})$ that gives the -prediction of our model for a new data point $\boldsymbol{x}$. This estimator -is chosen by minimizing a cost function which we take to be the -squared error +Let us assume that the true data is generated from a noisy model !bt \[ - \mathcal{C}( \boldsymbol{X}, \hat{g}(\boldsymbol{x})) = \sum_i (y_i - \hat{g}_\mathcal{L}(\boldsymbol{x}_i))^2. +\bm{y}=f(\boldsymbol{x}) + \bm{\epsilon} \] !et +where $\epsilon$ is normally distributed with mean zero and standard deviation $\sigma^2$. -===== What we want ===== +In our derivation of the ordinary least squares method we defined then +an approximation to the function $f$ in terms of the parameters +$\bm{\beta}$ and the design matrix $\bm{X}$ which embody our model, +that is $\bm{\tilde{y}}=\bm{X}\bm{\beta}$. -We are interested in the generalization error on all data drawn from -the true model, not just the error on the particular training dataset -$\mathcal{L}$ that we have in hand. This is just the expectation of -the cost function over many different data sets -$\{\mathcal{L}_j\}$. Denote this expectation value by -$E_{\mathcal{L}}$. In other words, we can view $\hat{g}_{\mathcal{L}}$ -as a stochastic functional that depends on the dataset $\mathcal{L}$ -and we can think of $E_{\mathcal{L}}$ as the expected value of the -functional if we drew an infinite number of datasets $\{\mathcal{L}_1, -\mathcal{L}_2, \ldots \}$. - - - -===== The expected generalization error ===== - -We would also like to average over different instances of the -``noise'' $\epsilon$ and we denote the expectation value over the -noise by $E_\epsilon$. Thus, we can decompose the expected -generalization error as - - -!bt -\begin{align} -E_\mathcal{L, \epsilon}[\mathcal{C}( \boldsymbol{X}, \hat{g}(\boldsymbol{x})) ]&= E_\mathcal{L,\epsilon}\left[ \sum_i ({y}_i - \hat{g}_\mathcal{L}(\boldsymbol{x}_i))^2 \right] \nonumber \\ - &= E_\mathcal{L, \epsilon}\left[ \sum_{i}({y}_i -f(\boldsymbol{x}_i) +f(\boldsymbol{x}_i)- \hat{g}_\mathcal{L}(\boldsymbol{x}_i))^2\right] \nonumber \\ - &= \sum_i E_\epsilon[ ({y}_i -f(\boldsymbol{x}_i))^2 ]+ E_\mathcal{L, \epsilon}[(f(\boldsymbol{x}_i)- \hat{g}_\mathcal{L}(\boldsymbol{x}_i))^2] + 2E_\epsilon[{y}_i -f(\boldsymbol{x}_i)]E_\mathcal{L}[f(\boldsymbol{x}_i)- \hat{g}_\mathcal{L}(\boldsymbol{x}_i)] \nonumber \\ - &=\sum_i \sigma_\epsilon^2 + E_\mathcal{L}[(f(\boldsymbol{x}_i)- \hat{g}_\mathcal{L}(\boldsymbol{x}_i))^2], -\end{align} -!et - -where in the last line we used the fact that our noise has zero mean -and variance $\sigma_\epsilon^2$ and the sum over $i$ applies to all -terms. - - -===== Elaborating a little bit more ===== - -It is also helpful to further decompose the second term as -follows: - -!bt -\begin{align} -E_\mathcal{L}[(f(\boldsymbol{x}_i)- \hat{g}_\mathcal{L}(\boldsymbol{x}_i))^2] &=E_\mathcal{L}[(f(\mathbf{x}_i)-E_\mathcal{L}[\hat{g}_\mathcal{L}(\boldsymbol{x}_i)]+ E_\mathcal{L}[\hat{g}_\mathcal{L}(\boldsymbol{x}_i)]- \hat{g}_\mathcal{L}(\boldsymbol{x}_i))^2] \nonumber \\ -&=E_\mathcal{L}[(f(\boldsymbol{x}_i)-E_\mathcal{L}[\hat{g}_\mathcal{L}(\boldsymbol{x}_i)])^2] + E_\mathcal{L}[( \hat{g}_\mathcal{L}(\boldsymbol{x}_i)-E_\mathcal{L}[\hat{g}_\mathcal{L}(\boldsymbol{x}_i)])^2] \nonumber \\ -&+2E_\mathcal{L}[(f(\boldsymbol{x}_i)-E_\mathcal{L}[\hat{g}_\mathcal{L}(\boldsymbol{x}_i)])( \hat{g}_\mathcal{L}(\boldsymbol{x}_i)-E_\mathcal{L}[\hat{g}_\mathcal{L}(\boldsymbol{x}_i)])] \nonumber \\ -&=(f(\boldsymbol{x}_i)-E_\mathcal{L}[\hat{g}_\mathcal{L}(\boldsymbol{x}_i)])^2+E_\mathcal{L}[( \hat{g}_\mathcal{L}(\boldsymbol{x}_i)-E_\mathcal{L}[\hat{g}_\mathcal{L}(\boldsymbol{x}_i)])^2]. -\end{align} -!et - - -===== The bias ===== - -The first term is called the bias +Thereafter we found the parameters $\bm{\beta}$ by optimizing the means squared error via the so-called cost function !bt \[ -Bias^2= \sum_i (f(\boldsymbol{x}_i)-E_\mathcal{L}[\hat{g}_\mathcal{L}(\boldsymbol{x}_i)])^2 +C(\bm{X},\bm{\beta}) =\frac{1}{n}\sum_{i=0}^{n-1}(y_i-\tilde{y}_i)^2=\mathbb{E}\left[(\bm{y}-\bm{\tilde{y}})^2\right]. \] !et -and measures the deviation of the expectation value of our estimator (i.e. the asymptotic value of our estimator in the infinite data limit) from the true value. - -===== The variance ===== -The second term is called the variance +We can rewrite this as !bt \[ -Var=\sum_i E_\mathcal{L}[( \hat{g}_\mathcal{L}(\boldsymbol{x}_i)-E_\mathcal{L}[\hat{g}_\mathcal{L}(\boldsymbol{x}_i)])^2], +\mathbb{E}\left[(\bm{y}-\bm{\tilde{y}})^2\right]=\frac{1}{n}\sum_i(f_i-\mathbb{E}\left[\bm{\tilde{y}}\right])^2+\frac{1}{n}\sum_i(\tilde{y}_i-\mathbb{E}\left[\bm{\tilde{y}}\right])^2+\sigma^2. \] !et -and measures how much our estimator fluctuates due to finite-sample effects. Combining these expressions, we see that the expected out-of-sample error of our model can be decomposed as +The three terms represent the square of the bias of the learning +method, which can be thought of as the error caused by the simplifying +assumptions built into the method. The second term represents the +variance of the chosen model and finally the last terms is variance of +the error $\bm{\epsilon}$. + +To derive this equation, we need to recall that the variance of $\bm{y}$ and $\bm{\epsilon}$ are both equal to $\sigma^2$. The mean value of $\bm{\epsilon}$ is by definition equal to zero. Furthermore, the function $f$ is not a stochastics variable, idem for $\bm{\tilde{y}}$. +We use a more compact notation in terms of the expectation value !bt \[ -E_\mathrm{out}=E_\mathcal{L, \epsilon}[\mathcal{C}( \boldsymbol{X}, \hat{g}(\boldsymbol{x})) ] = Bias^2 + Var + Noise. +\mathbb{E}\left[(\bm{y}-\bm{\tilde{y}})^2\right]=\mathbb{E}\left[(\bm{f}+\bm{\epsilon}-\bm{\tilde{y}})^2\right], \] !et +and adding and subtracting $\mathbb{E}\left[\bm{\tilde{y}}\right]$ we get +!bt +\[ +\mathbb{E}\left[(\bm{y}-\bm{\tilde{y}})^2\right]=\mathbb{E}\left[(\bm{f}+\bm{\epsilon}-\bm{\tilde{y}}+\mathbb{E}\left[\bm{\tilde{y}}\right]-\mathbb{E}\left[\bm{\tilde{y}}\right])^2\right], +\] +!et +which, using the abovementioned expectation values can be rewritten as +!bt +\[ +\mathbb{E}\left[(\bm{y}-\bm{\tilde{y}})^2\right]=\mathbb{E}\left[(\bm{y}-\mathbb{E}\left[\bm{\tilde{y}}\right])^2\right]+\mathrm{Var}\left[\bm{\tilde{y}}\right]+\sigma^2, +\] +!et +that is the rewriting in terms of the so-called bias, the variance of the model $\bm{\tilde{y}}$ and the variance of $\bm{\epsilon}$. + + + + + +===== Example code for Bias-Variance tradeoff ===== +!bc pycod +import matplotlib.pyplot as plt +import numpy as np +from sklearn.linear_model import LinearRegression, Ridge, Lasso +from sklearn.preprocessing import PolynomialFeatures +from sklearn.model_selection import train_test_split +from sklearn.pipeline import make_pipeline +from sklearn.utils import resample + +np.random.seed(2018) + +n = 500 +n_boostraps = 100 +degree = 18 # A quite high value, just to show. +noise = 0.1 + +# Make data set. +x = np.linspace(-1, 3, n).reshape(-1, 1) +y = np.exp(-x**2) + 1.5 * np.exp(-(x-2)**2) + np.random.normal(0, 0.1, x.shape) + +# Hold out some test data that is never used in training. +x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.2) + +# Combine x transformation and model into one operation. +# Not neccesary, but convenient. +model = make_pipeline(PolynomialFeatures(degree=degree), LinearRegression(fit_intercept=False)) + +# The following (m x n_bootstraps) matrix holds the column vectors y_pred +# for each bootstrap iteration. +y_pred = np.empty((y_test.shape[0], n_boostraps)) +for i in range(n_boostraps): + x_, y_ = resample(x_train, y_train) + + # Evaluate the new model on the same test data each time. + y_pred[:, i] = model.fit(x_, y_).predict(x_test).ravel() + +# Note: Expectations and variances taken w.r.t. different training +# data sets, hence the axis=1. Subsequent means are taken across the test data +# set in order to obtain a total value, but before this we have error/bias/variance +# calculated per data point in the test set. +# Note 2: The use of keepdims=True is important in the calculation of bias as this +# maintains the column vector form. Dropping this yields very unexpected results. +error = np.mean( np.mean((y_test - y_pred)**2, axis=1, keepdims=True) ) +bias = np.mean( (y_test - np.mean(y_pred, axis=1, keepdims=True))**2 ) +variance = np.mean( np.var(y_pred, axis=1, keepdims=True) ) +print('Error:', error) +print('Bias^2:', bias) +print('Var:', variance) +print('{} >= {} + {} = {}'.format(error, bias, variance, bias+variance)) + +plt.plot(x[::5, :], y[::5, :], label='f(x)') +plt.scatter(x_test, y_test, label='Data points') +plt.scatter(x_test, np.mean(y_pred, axis=1), label='Pred') +plt.legend() +plt.show() + +!ec + + + +===== Understanding what happens ===== +!bc pycod +import matplotlib.pyplot as plt +import numpy as np +from sklearn.linear_model import LinearRegression, Ridge, Lasso +from sklearn.preprocessing import PolynomialFeatures +from sklearn.model_selection import train_test_split +from sklearn.pipeline import make_pipeline +from sklearn.utils import resample + +np.random.seed(2018) + +n = 40 +n_boostraps = 100 +maxdegree = 14 + + +# Make data set. +x = np.linspace(-3, 3, n).reshape(-1, 1) +y = np.exp(-x**2) + 1.5 * np.exp(-(x-2)**2)+ np.random.normal(0, 0.1, x.shape) +error = np.zeros(maxdegree) +bias = np.zeros(maxdegree) +variance = np.zeros(maxdegree) +polydegree = np.zeros(maxdegree) +x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.2) + +for degree in range(maxdegree): + model = make_pipeline(PolynomialFeatures(degree=degree), LinearRegression(fit_intercept=False)) + y_pred = np.empty((y_test.shape[0], n_boostraps)) + for i in range(n_boostraps): + x_, y_ = resample(x_train, y_train) + y_pred[:, i] = model.fit(x_, y_).predict(x_test).ravel() + + polydegree[degree] = degree + error[degree] = np.mean( np.mean((y_test - y_pred)**2, axis=1, keepdims=True) ) + bias[degree] = np.mean( (y_test - np.mean(y_pred, axis=1, keepdims=True))**2 ) + variance[degree] = np.mean( np.var(y_pred, axis=1, keepdims=True) ) + print('Polynomial degree:', degree) + print('Error:', error[degree]) + print('Bias^2:', bias[degree]) + print('Var:', variance[degree]) + print('{} >= {} + {} = {}'.format(error[degree], bias[degree], variance[degree], bias[degree]+variance[degree])) + +plt.plot(polydegree, np.log10(error), label='Error') +plt.plot(polydegree, bias, label='bias') +plt.plot(polydegree, variance, label='Variance') +plt.legend() +plt.show() + + + + +!ec + + +===== Summing up ===== + + + The bias-variance tradeoff summarizes the fundamental tension in machine learning, particularly supervised learning, between the complexity of a model and the amount of training data needed to train it. Since data is often limited, in practice it is often useful to -use a less-complex model with higher bias -- a model whose asymptotic -performance is worse than another model -- because it is easier to +use a less-complex model with higher bias, that is a model whose asymptotic +performance is worse than another model because it is easier to train and less sensitive to sampling noise arising from having a finite-sized training dataset (smaller variance). - -===== Summing up ===== + The above equations tell us that in order to minimize the expected test error, we need to select a @@ -6752,9 +4457,92 @@ flexible statistical methods have higher variance. -===== The one-dimensional Ising model, project 2 ===== +===== Another Example rom Scikit-Learn's Repository ===== +!bc pycod +""" +============================ +Underfitting vs. Overfitting +============================ -The one-dimensional Ising model with nearest neighbor interaction, no external field and a constant coupling constant $J$ is given by +This example demonstrates the problems of underfitting and overfitting and +how we can use linear regression with polynomial features to approximate +nonlinear functions. The plot shows the function that we want to approximate, +which is a part of the cosine function. In addition, the samples from the +real function and the approximations of different models are displayed. The +models have polynomial features of different degrees. We can see that a +linear function (polynomial with degree 1) is not sufficient to fit the +training samples. This is called **underfitting**. A polynomial of degree 4 +approximates the true function almost perfectly. However, for higher degrees +the model will **overfit** the training data, i.e. it learns the noise of the +training data. +We evaluate quantitatively **overfitting** / **underfitting** by using +cross-validation. We calculate the mean squared error (MSE) on the validation +set, the higher, the less likely the model generalizes correctly from the +training data. +""" + +print(__doc__) + +import numpy as np +import matplotlib.pyplot as plt +from sklearn.pipeline import Pipeline +from sklearn.preprocessing import PolynomialFeatures +from sklearn.linear_model import LinearRegression +from sklearn.model_selection import cross_val_score + + +def true_fun(X): + return np.cos(1.5 * np.pi * X) + +np.random.seed(0) + +n_samples = 30 +degrees = [1, 4, 15] + +X = np.sort(np.random.rand(n_samples)) +y = true_fun(X) + np.random.randn(n_samples) * 0.1 + +plt.figure(figsize=(14, 5)) +for i in range(len(degrees)): + ax = plt.subplot(1, len(degrees), i + 1) + plt.setp(ax, xticks=(), yticks=()) + + polynomial_features = PolynomialFeatures(degree=degrees[i], + include_bias=False) + linear_regression = LinearRegression() + pipeline = Pipeline([("polynomial_features", polynomial_features), + ("linear_regression", linear_regression)]) + pipeline.fit(X[:, np.newaxis], y) + + # Evaluate the models using crossvalidation + scores = cross_val_score(pipeline, X[:, np.newaxis], y, + scoring="neg_mean_squared_error", cv=10) + + X_test = np.linspace(0, 1, 100) + plt.plot(X_test, pipeline.predict(X_test[:, np.newaxis]), label="Model") + plt.plot(X_test, true_fun(X_test), label="True function") + plt.scatter(X, y, edgecolor='b', s=20, label="Samples") + plt.xlabel("x") + plt.ylabel("y") + plt.xlim((0, 1)) + plt.ylim((-2, 2)) + plt.legend(loc="best") + plt.title("Degree {}\nMSE = {:.2e}(+/- {:.2e})".format( + degrees[i], -scores.mean(), scores.std())) +plt.show() +!ec + + + + +===== The one-dimensional Ising model ===== + +Let us bring back the Ising model again, but now with an additional +focus on Ridge and Lasso regression as well. We repeat some of the +basic parts of the Ising model and the setup of the training and test +data. The one-dimensional Ising model with nearest neighbor +interaction, no external field and a constant coupling constant $J$ is +given by !bt \begin{align} @@ -6790,15 +4578,6 @@ for i in range(n): energies[i] = - J * np.dot(spins[i], np.roll(spins[i], 1)) !ec -Here we use linear (ordinary least squares), ridge and LASSO -regression to predict the energy in the nearest neighbor -one-dimensional Ising model on a ring, i.e., the endpoints wrap -around. We will use the linear regression models to fit a value for -the coupling constant to achieve this. - - -===== Reformulating the problem to suit regression ===== - A more general form for the one-dimensional Ising model is !bt @@ -6821,12 +4600,10 @@ elements $-J_{jk}$. This form of writing the energy fits perfectly with the form utilized in linear regression, viz. !bt \begin{align} - y = X\omega + \epsilon, + \bm{y} = \bm{X}\bm{\beta} + \bm{\epsilon}. \end{align} !et - - - +We organize the data as we did above !bc pycod X = np.zeros((n, L ** 2)) for i in range(n): @@ -6845,147 +4622,17 @@ X_test_own = np.concatenate( ) !ec - -===== Linear regression ===== - -The problem at hand is to try to fit the equation -!bt -\begin{align} - y = f(x) + \epsilon, -\end{align} -!et - -where $f(x)$ is some unknown function of the data $x$ and $\epsilon$ -is normally distributed with mean zero noise with standard deviation -$\sigma_{\epsilon}$. Our job is to try to find a predictor which -estimates the function $f(x)$. In linear regression we assume that we -can formulate the problem as - -!bt -\begin{align} - y = X\omega + \epsilon, -\end{align} -!et - -where $X$ and $\omega$ are now matrices. Our job at hand is now to -find a _cost function_ $C$, which we wish to minimize in order to find -the best estimate of $\omega$. - - -===== Ordinary least squares ===== - -In the ordinary least squares method we choose the cost function -!bt -\begin{align} - C(X, \omega) = ||X\omega - y||^2 - = (X\omega - y)^T(X\omega - y) -\end{align} -!et -We then find the extremal point of $C$ by taking the derivative with respect to $\omega$ and setting it to zero, i.e., - -!bt -\begin{align} - \dfrac{\mathrm{d}C}{\mathrm{d}\omega} - = 0. -\end{align} -!et -This yields the expression for $\omega$ to be -!bt -\begin{align} - \omega = \frac{X^T y}{X^T X}, -\end{align} -!et - -which immediately imposes some requirements on $X$ as there must exist -an inverse of $X^T X$. If the expression we are modelling contains an -intercept, i.e., a constant expression we must make sure that the -first column of $X$ consists of $1$. - - -!bc pycod -def get_ols_weights_naive(x: np.ndarray, y: np.ndarray) -> np.ndarray: - return scl.inv(x.T @ x) @ (x.T @ y) -omega = get_ols_weights_naive(X_train_own, y_train) -!ec - - - -===== Singular Value decomposition ===== -Doing the inversion directly turns out to be a bad idea as the matrix -$X^TX$ is singular. An alternative approach is to use the _singular -value decomposition_. Using the definition of the Moore-Penrose -pseudoinverse we can write the equation for $\omega$ as - -!bt -\begin{align} - \omega = X^{+}y, -\end{align} -!et -where the pseudoinverse of $X$ is given by -!bt -\begin{align} - X^{+} = \frac{X^T}{X^T X}. -\end{align} -!et - -Using singular value decomposition we have that $X = U\Sigma V^T$, -where $X^{+} = V\Sigma^{+} U^T$. This reduces the equation for -$\omega$ to -!bt -\begin{align} - \omega = V\Sigma^{+} U^T y. -\end{align} -!et - -Note that solving this equation by actually doing the pseudoinverse -(which is what we will do) is not a good idea as this operation scales -as $\mathcal{O}(n^3)$, where $n$ is the number of elements in a -general matrix. Instead, doing $QR$-factorization and solving the -linear system as an equation would reduce this down to -$\mathcal{O}(n^2)$ operations. - - -!bc pycod -def get_ols_weights(x: np.ndarray, y: np.ndarray) -> np.ndarray: - u, s, v = scl.svd(x) - return v.T @ scl.pinv(scl.diagsvd(s, u.shape[0], v.shape[0])) @ u.T @ y -!ec -Before passing in the data to the function we append a column with ones to the training data. - - -!bc pycod -omega = get_ols_weights(X_train_own,y_train) -!ec - - -===== Fitting with scikit-learn ===== - -Next we fit a `LinearRegression`-model from Scikit-learn for comparison. +We will do all fitting with _Scikit-Learn_, !bc pycod clf = skl.LinearRegression().fit(X_train, y_train) !ec - -Extracting the $J$-matrix from both our own method and the Scikit-learn model where we make sure to remove the intercept. - - +When extracting the $J$-matrix we make sure to remove the intercept !bc pycod -J_own = omega[1:].reshape(L, L) J_sk = clf.coef_.reshape(L, L) !ec - -A way of looking at the coefficients in $J$ is to plot the matrices as images. - - +And then we plot the results !bc pycod -fig = plt.figure(figsize=(20, 14)) -im = plt.imshow(J_own, **cmap_args) -plt.title("Home-made OLS", fontsize=18) -plt.xticks(fontsize=18) -plt.yticks(fontsize=18) -cb = fig.colorbar(im) -cb.ax.set_yticklabels(cb.ax.get_yticklabels(), fontsize=18) - fig = plt.figure(figsize=(20, 14)) im = plt.imshow(J_sk, **cmap_args) plt.title("LinearRegression from Scikit-learn", fontsize=18) @@ -6995,11 +4642,7 @@ cb = fig.colorbar(im) cb.ax.set_yticklabels(cb.ax.get_yticklabels(), fontsize=18) plt.show() !ec - -We can see that our model for the least squares method performes close -to the benchmark from Scikit-learn. It is interesting to note that OLS -considers both $J_{j, j + 1} = -0.5$ and $J_{j, j - 1} = -0.5$ as -valid matrix elements for $J$. +The results perfectly with our previous discussion where we used our own code. ===== Ridge regression ===== @@ -7007,47 +4650,18 @@ valid matrix elements for $J$. Having explored the ordinary least squares we move on to ridge regression. In ridge regression we include a _regularizer_. This involves a new cost function which leads to a new estimate for the -weights $\omega$. This results in a penalized regression problem. The +weights $\bm{\beta}$. This results in a penalized regression problem. The cost function is given by !bt \begin{align} - C(X, \omega; \lambda) = ||X\omega - y||^2 + \lambda ||\omega||^2 - = (X\omega - y)^T(X\omega - y) + \lambda \omega^T\omega. + C(\bm{X}, \bm{\beta}; \lambda) = (\bm{X}\bm{\beta} - \bm{y})^T(\bm{X}\bm{\beta} - \bm{y}) + \lambda \bm{\beta}^T\bm{\beta}. \end{align} !et -Finding the extremum of this function yields the weights - -!bt -\begin{align} - \omega(\lambda) = \frac{X^Ty}{X^TX + \lambda} \to \frac{\omega_{\text{LS}}}{1 + \lambda}, -\end{align} -!et - -where $\omega_{\text{LS}}$ is the weights from ordinary least -squares. The last assumption assumes that $X$ is orthogonal, which it -is not. We will therefore resort to solving the equation as it stands -on the left hand side. - - !bc pycod -def get_ridge_weights(x: np.ndarray, y: np.ndarray, _lambda: float) -> np.ndarray: - return x.T @ y @ scl.inv( - x.T @ x + np.eye(x.shape[1], x.shape[1]) * _lambda - ) -lambda = 0.1 -omega_ridge = get_ridge_weights(X_train_own, y_train, np.array([_lambda])) +_lambda = 0.1 clf_ridge = skl.Ridge(alpha=_lambda).fit(X_train, y_train) -J_ridge_own = omega_ridge[1:].reshape(L, L) J_ridge_sk = clf_ridge.coef_.reshape(L, L) -fig = plt.figure(figsize=(20, 14)) -im = plt.imshow(J_ridge_own, **cmap_args) -plt.title("Home-made ridge regression", fontsize=18) -plt.xticks(fontsize=18) -plt.yticks(fontsize=18) -cb = fig.colorbar(im) -cb.ax.set_yticklabels(cb.ax.get_yticklabels(), fontsize=18) - fig = plt.figure(figsize=(20, 14)) im = plt.imshow(J_ridge_sk, **cmap_args) plt.title("Ridge from Scikit-learn", fontsize=18) @@ -7063,14 +4677,14 @@ plt.show() ===== LASSO regression ===== In the _Least Absolute Shrinkage and Selection Operator_ (LASSO)-method we get a third cost function. + !bt \begin{align} - C(X, \omega; \lambda) = - ||X\omega - y||^2 + \lambda ||\omega|| - = (X\omega - y)^T(X\omega - y) + \lambda \sqrt{\omega^T\omega}. + C(\bm{X}, \bm{\beta}; \lambda) = (\bm{X}\bm{\beta} - \bm{y})^T(\bm{X}\bm{\beta} - \bm{y}) + \lambda \sqrt{\bm{\beta}^T\bm{\beta}}. \end{align} !et -Finding the extremal point of this cost function is not so straight-forward as in least squares and ridge. We will therefore rely solely on the function ``Lasso`` from Scikit-learn. + +Finding the extremal point of this cost function is not so straight-forward as in least squares and ridge. We will therefore rely solely on the function ``Lasso`` from _Scikit-Learn_. !bc pycod clf_lasso = skl.Lasso(alpha=_lambda).fit(X_train, y_train) @@ -7092,33 +4706,6 @@ $J_{j, j + 1} = -1$. -===== Performance of the different models ===== - -In order to judge which model performs best at varying values of $\lambda$ (for ridge and LASSO) we compute $R^2$ which is given by - -!bt -\begin{align} - R^2 = 1 - \frac{(y - \hat{y})^2}{(y - \bar{y})^2}, -\end{align} -!et -where $y$ is a vector with the true values of the energy, $\hat{y}$ is the predicted values of $y$ from the models and $\bar{y}$ is the mean of $\hat{y}$. - - -!bc pycod -def r_squared(y, y_hat): - return 1 - np.sum((y - y_hat) ** 2) / np.sum((y - np.mean(y_hat)) ** 2) -!ec - -This is the same metric used by Scikit-learn for their regression models when scoring. -!bc pycod -y_hat = clf.predict(X_test) -r_test = r_squared(y_test, y_hat) -sk_r_test = clf.score(X_test, y_test) - -assert abs(r_test - sk_r_test) < 1e-2 -!ec - - ===== Performance as function of the regularization parameter ===== @@ -7129,17 +4716,13 @@ We see how the different models perform for a different set of values for $\lamb lambdas = np.logspace(-4, 5, 10) train_errors = { - "ols_own": np.zeros(lambdas.size), "ols_sk": np.zeros(lambdas.size), - "ridge_own": np.zeros(lambdas.size), "ridge_sk": np.zeros(lambdas.size), "lasso_sk": np.zeros(lambdas.size) } test_errors = { - "ols_own": np.zeros(lambdas.size), "ols_sk": np.zeros(lambdas.size), - "ridge_own": np.zeros(lambdas.size), "ridge_sk": np.zeros(lambdas.size), "lasso_sk": np.zeros(lambdas.size) } @@ -7149,30 +4732,6 @@ plot_counter = 1 fig = plt.figure(figsize=(32, 54)) for i, _lambda in enumerate(tqdm.tqdm(lambdas)): - omega = get_ols_weights(X_train_own, y_train) - y_hat_train = X_train_own @ omega - y_hat_test = X_test_own @ omega - - train_errors["ols_own"][i] = r_squared(y_train, y_hat_train) - test_errors["ols_own"][i] = r_squared(y_test, y_hat_test) - - plt.subplot(10, 5, plot_counter) - plt.imshow(omega[1:].reshape(L, L), **cmap_args) - plt.title("Home made OLS") - plot_counter += 1 - - omega = get_ridge_weights(X_train_own, y_train, _lambda) - y_hat_train = X_train_own @ omega - y_hat_test = X_test_own @ omega - - train_errors["ridge_own"][i] = r_squared(y_train, y_hat_train) - test_errors["ridge_own"][i] = r_squared(y_test, y_hat_test) - - plt.subplot(10, 5, plot_counter) - plt.imshow(omega[1:].reshape(L, L), **cmap_args) - plt.title(r"Home made ridge, $\lambda = %.4f$" % _lambda) - plot_counter += 1 - for key, method in zip( ["ols_sk", "ridge_sk", "lasso_sk"], [skl.LinearRegression(), skl.Ridge(alpha=_lambda), skl.Lasso(alpha=_lambda)] @@ -7192,7 +4751,7 @@ for i, _lambda in enumerate(tqdm.tqdm(lambdas)): plt.show() !ec -We can see that LASSO quite fast reaches a good solution for low +We see that LASSO reaches a good solution for low values of $\lambda$, but will "wither" when we increase $\lambda$ too much. Ridge is more stable over a larger range of values for $\lambda$, but eventually also fades away. @@ -7212,8 +4771,6 @@ testing set that is close to the accuracy of the training set. fig = plt.figure(figsize=(20, 14)) colors = { - "ols_own": "b", - "ridge_own": "g", "ols_sk": "r", "ridge_sk": "y", "lasso_sk": "c" @@ -7236,9 +4793,6 @@ for key in test_errors: label="Test {0}".format(key), linewidth=4.0 ) -#plt.semilogx(lambdas, train_errors["ols_own"], label="Train (OLS own)") -#plt.semilogx(lambdas, test_errors["ols_own"], label="Test (OLS own)") - plt.legend(loc="best", fontsize=18) plt.xlabel(r"$\lambda$", fontsize=18) plt.ylabel(r"$R^2$", fontsize=18) @@ -7247,13 +4801,251 @@ plt.show() !ec From the above figure we can see that LASSO with $\lambda = 10^{-2}$ -achieve a very good accuracy on the test set. This by far surpases the +achieves a very good accuracy on the test set. This by far surpasses the other models for all values of $\lambda$. -======= Optimization and Gradient Methods ======= +===== Further Exercises ===== + +=== Exercise 1 === + +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)$. +The following simple Python instructions define our $x$ and $y$ values (with 100 data points). +!bc pycod +x = np.random.rand(100,1) +y = 5*x*x+0.1*np.random.randn(100,1) +!ec + +o Write your own code (following the examples above) for computing the parametrization of the data set fitting a second-order polynomial. +o Use thereafter _scikit-learn_ (see again the examples in the regression slides) and compare with your own code. +o Using scikit-learn, compute also the mean square error, a risk metric corresponding to the expected value of the squared (quadratic) error defined as +!bt +\[ MSE(\hat{y},\hat{\tilde{y}}) = \frac{1}{n} +\sum_{i=0}^{n-1}(y_i-\tilde{y}_i)^2, +\] +!et +and the $R^2$ score function. +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 +!bt +\[ +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}, +\] +!et +where we have defined the mean value of $\hat{y}$ as +!bt +\[ +\bar{y} = \frac{1}{n} \sum_{i=0}^{n - 1} y_i. +\] +!et + +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. 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. + + + + +=== Exercise 2, variance of the parameters $\beta$ in linear regression === + +Show that the variance of the parameters $\beta$ in the linear regression method (chapter 3, equation (3.8) of "Trevor Hastie, Robert Tibshirani, Jerome H. Friedman, The Elements of Statistical Learning, Springer":"https://www.springer.com/gp/book/9780387848570") is given as + +!bt +\[ +\mathrm{Var}(\hat{\beta}) = \left(\hat{X}^T\hat{X}\right)^{-1}\sigma^2, +\] +!et +with +!bt +\[ +\sigma^2 = \frac{1}{N-p-1}\sum_{i=1}^{N} (y_i-\tilde{y}_i)^2, +\] +!et +where we have assumed that we fit a function of degree $p-1$ (for example a polynomial in $x$). + + + +=== Exercise 3 === + +This exercise is a continuation of exercise 1. We will +use the same function to generate our data set, still staying with a +simple function $y(x)$ which we want to fit using linear regression, +but now extending the analysis to include the Ridge and the Lasso +regression methods. You can use the code under the Regression as an example on how to use the Ridge and the Lasso methods. + +We will thus again 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)$. + +The following simple Python instructions define our $x$ and $y$ values (with 100 data points). +!bc pycod +x = np.random.rand(100,1) +y = 5*x*x+0.1*np.random.randn(100,1) +!ec + +o Write your own code for the Ridge method and compute the parametrization for different values of $\lambda$. Compare and analyze your results with those from exercise 1. Study the dependence on $\lambda$ while also varying the strength of the noise in your expression for $y(x)$. + +o Repeat the above but using the functionality of _scikit-learn_. Compare your code with the results from _scikit-learn_. Remember to run with the same random numbers for generating $x$ and $y$. + +o Our next step is to study the variance of the parameters $\beta_1$ and $\beta_2$ (assuming that we are parametrizing our function with a second-order polynomial. We will use standard linear regression and the Ridge regression. You can now opt for either writing your own function that calculates the variance of these paramaters (recall that this is equal to the diagonal elements of the matrix $(\hat{X}^T\hat{X})+\lambda\hat{I})^{-1}$) or use the functionality of _scikit-learn_ and compute their variances. Discuss the results of these variances as functions + +o Repeat the previous step but add now the Lasso method. Discuss your results and compare with standard regression and the Ridge regression results. + +o Try to implement the cross-validation as well. + +o Finally, using _scikit-learn_ or your own code, compute also the mean square error, a risk metric corresponding to the expected value of the squared (quadratic) error defined as +!bt +\[ MSE(\hat{y},\hat{\tilde{y}}) = \frac{1}{n} +\sum_{i=0}^{n-1}(y_i-\tilde{y}_i)^2, +\] +!et +and the $R^2$ score function. +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 +!bt +\[ +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}, +\] +!et +where we have defined the mean value of $\hat{y}$ as +!bt +\[ +\bar{y} = \frac{1}{n} \sum_{i=0}^{n - 1} y_i. +\] +!et +Discuss these quantities as functions of the variable $\lambda$ in the Ridge and Lasso regression methods. + +=== Exercise 4 === + +We will study how +to fit polynomials to a specific two-dimensional function called +"Franke's +function":"http://www.dtic.mil/dtic/tr/fulltext/u2/a081688.pdf". This +is a function which has been widely used when testing various interpolation and fitting +algorithms. Furthermore, after having established the model and the +method, we will employ resamling techniques such as the cross-validation and/or +the bootstrap methods, in order to perform a proper assessment of our models. + + +The Franke function, which is a weighted sum of four exponentials reads as follows +!bt +\begin{align*} +f(x,y) &= \frac{3}{4}\exp{\left(-\frac{(9x-2)^2}{4} - \frac{(9y-2)^2}{4}\right)}+\frac{3}{4}\exp{\left(-\frac{(9x+1)^2}{49}- \frac{(9y+1)}{10}\right)} \\ +&+\frac{1}{2}\exp{\left(-\frac{(9x-7)^2}{4} - \frac{(9y-3)^2}{4}\right)} -\frac{1}{5}\exp{\left(-(9x-4)^2 - (9y-7)^2\right) }. +\end{align*} +!et + +The function will be defined for $x,y\in [0,1]$. Our first step will +be to perform an OLS regression analysis of this function, trying out +a polynomial fit with an $x$ and $y$ dependence of the form $[x, y, +x^2, y^2, xy, \dots]$. We will also include cross-validation and +bootstrap as resampling techniques. As in homeworks 1 and 2, we +can use a uniform distribution to set up the arrays of values for $x$ +and $y$, or as in the example below just a fix values for $x$ and $y$ with a given step size. +In this case we will have two predictors and need to fit a +function (for example a polynomial) of $x$ and $y$. Thereafter we will +repeat much of the same procedure using the the Ridge and +Lasso regression methods, introducing thus a dependence on the bias +(penalty) $\lambda$. + + +The Python function for the Franke function is included here (it performs also a three-dimensional plot of it) +!bc pycod +from mpl_toolkits.mplot3d import Axes3D +import matplotlib.pyplot as plt +from matplotlib import cm +from matplotlib.ticker import LinearLocator, FormatStrFormatter +import numpy as np +from random import random, seed + +fig = plt.figure() +ax = fig.gca(projection='3d') + +# Make data. +x = np.arange(0, 1, 0.05) +y = np.arange(0, 1, 0.05) +x, y = np.meshgrid(x,y) + + +def FrankeFunction(x,y): + term1 = 0.75*np.exp(-(0.25*(9*x-2)**2) - 0.25*((9*y-2)**2)) + term2 = 0.75*np.exp(-((9*x+1)**2)/49.0 - 0.1*(9*y+1)) + term3 = 0.5*np.exp(-(9*x-7)**2/4.0 - 0.25*((9*y-3)**2)) + term4 = -0.2*np.exp(-(9*x-4)**2 - (9*y-7)**2) + return term1 + term2 + term3 + term4 + + +z = FrankeFunction(x, y) + +# Plot the surface. +surf = ax.plot_surface(x, y, z, cmap=cm.coolwarm, + linewidth=0, antialiased=False) + +# Customize the z axis. +ax.set_zlim(-0.10, 1.40) +ax.zaxis.set_major_locator(LinearLocator(10)) +ax.zaxis.set_major_formatter(FormatStrFormatter('%.02f')) + +# Add a color bar which maps values to colors. +fig.colorbar(surf, shrink=0.5, aspect=5) + +plt.show() + +!ec + + +We will thus again generate our own dataset for a function $\mathrm{FrankeFunction}(x,y)$ where +$x,y \in [0,1]$ could be defined by random numbers computed with the uniform +distribution. The function $f(x,y)$ is the Franke function. You should explore also the addition +an added stochastic noise to this function using the normal distribution $\cal{N}(0,1)$. + +Write your own code (using either a matrix inversion or a singular value decomposition from e.g., _numpy_ ) or use your code from exercises 1 and 3 +and perform a standard least square regression analysis using polynomials in $x$ and $y$ up to fifth order. Find the confidence intervals of the parameters $\beta$ by computing their variances, evaluate the Mean Squared error (MSE) +!bt +\[ MSE(\hat{y},\hat{\tilde{y}}) = \frac{1}{n} +\sum_{i=0}^{n-1}(y_i-\tilde{y}_i)^2, +\] +!et +and the $R^2$ score function. +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 +!bt +\[ +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}, +\] +!et +where we have defined the mean value of $\hat{y}$ as +!bt +\[ +\bar{y} = \frac{1}{n} \sum_{i=0}^{n - 1} y_i. +\] +!et + +Perform a resampling of the data where you split the data in training data and test data. Implement the $k$-fold cross-validation algorithm and/or the bootstrap algorithm +and evaluate again the MSE and the $R^2$ functions resulting from the test data. Evaluate also the bias and variance of the final models. + + +Write then your own code for the Ridge method, either using matrix +inversion or the singular value decomposition as done for standard OLS. Perform the same analysis as in the +previous exercise (for the same polynomials and include resampling +techniques) but now for different values of $\lambda$. Compare and +analyze your results with those obtained with standard OLS. Study the +dependence on $\lambda$ while also varying eventually the strength of +the noise in your expression for $\mathrm{FrankeFunction}(x,y)$. + +Then perform the same studies but now with Lasso regression. Use the functionalities of +_scikit-learn_. Give a critical discussion of the three methods and a +judgement of which model fits the data best. + + + + + + + +======= Optimization and Gradient Methods ======= ===== Optimization, the central part of any Machine Learning algortithm ===== @@ -7287,8 +5079,6 @@ p(y_i=0|x_i,\hat{\beta}) &= 1 - p(y_i=1|x_i,\hat{\beta}), where $\hat{\beta}$ are the weights we wish to extract from data, in our case $\beta_0$ and $\beta_1$. -===== The equations to solve ===== - Our compact equations used a definition of a vector $\hat{y}$ with $n$ elements $y_i$, an $n\times p$ matrix $\hat{X}$ which contains the $x_i$ values and a vector $\hat{p}$ of fitted probabilities @@ -7336,8 +5126,6 @@ If we can compute these matrices, in particular the Hessian, the above is often -===== Brief reminder on Newton-Raphson's method ===== - Let us quickly remind ourselves how we derive the above method. Perhaps the most celebrated of all one-dimensional root-finding @@ -7349,7 +5137,6 @@ numerically and/or your function is not of the smooth type, we normally discourage the use of this method. -===== The equations ===== The Newton-Raphson formula consists geometrically of extending the tangent line at a current point until it crosses zero, then setting @@ -7389,8 +5176,6 @@ Having in mind an iterative procedure, it is natural to start iterating with !et -===== Simple geometric interpretation ===== - The above is Newton-Raphson's method. It has a simple geometric interpretation, namely $x_{n+1}$ is the point where the tangent from $(x_n,f(x_n))$ crosses the $x$-axis. Close to the solution, @@ -7405,8 +5190,6 @@ vanishes, then Newton-Raphson may fail totally -===== Extending to more than one variable ===== - Newton's method can be generalized to systems of several non-linear equations and variables. Consider the case with two equations !bt @@ -7428,10 +5211,10 @@ which we Taylor expand to obtain \end{array}. \] !et -Defining the Jacobian matrix $\hat{J}$ we have +Defining the Jacobian matrix $\bm{J}$ we have !bt \[ - \hat{J}=\left( \begin{array}{cc} + \bm{J}=\left( \begin{array}{cc} \partial f_1/\partial x_1 & \partial f_1/\partial x_2 \\ \partial f_2/\partial x_1 &\partial f_2/\partial x_2 \end{array} \right), @@ -7449,13 +5232,13 @@ where we have defined !bt \[ \left(\begin{array}{c} h_1^{n} \\ h_2^{n} \end{array} \right)= - -\hat{J}^{-1} + -{\bm{J}}^{-1} \left(\begin{array}{c} f_1(x_1^{n},x_2^{n}) \\ f_2(x_1^{n},x_2^{n}) \end{array} \right). \] !et We need thus to compute the inverse of the Jacobian matrix and it is to understand that difficulties may -arise in case $\hat{J}$ is nearly singular. +arise in case $\bm{J}$ is nearly singular. It is rather straightforward to extend the above scheme to systems of more than two non-linear equations. In our case, the Jacobian matrix is given by the Hessian that represents the second derivative of cost function. @@ -7482,8 +5265,6 @@ For $\gamma_k$ small enough, then $F(\mathbf{x}_{k+1}) \leq F(\mathbf{x}_k)$. This means that for a sufficiently small $\gamma_k$ we are always moving towards smaller function values, i.e a minimum. - -===== More on Steepest descent ===== The previous observation is the basis of the method of steepest descent, which is also referred to as just gradient descent (GD). One @@ -7499,8 +5280,7 @@ computes new approximations according to The parameter $\gamma_k$ is often referred to as the step length or the learning rate within the context of Machine Learning. - -===== The ideal ===== + Ideally the sequence $\{\mathbf{x}_k \}_{k=0}$ converges to a global minimum of the function $F$. In general we do not know if we are in a @@ -7521,8 +5301,6 @@ Note that the gradient is a function of $\mathbf{x} = (x_1,\cdots,x_n)$ which makes it expensive to compute numerically. - -===== The sensitiveness of the gradient descent ===== The gradient descent method is sensitive to the choice of learning rate $\gamma_k$. This is due @@ -7537,8 +5315,6 @@ randomness. One such method is that of Stochastic Gradient Descent (SGD), see below. - -===== Convex functions ===== Ideally we want our cost/loss function to be convex(concave). @@ -7558,8 +5334,6 @@ regular polygons (triangles, rectangles, pentagons, etc...). _Convex function_: Let $X \subset \mathbb{R}^n$ be a convex set. Assume that the function $f: X \rightarrow \mathbb{R}$ is continuous, then $f$ is said to be convex if $$f(tx_1 + (1-t)x_2) \leq tf(x_1) + (1-t)f(x_2) $$ for all $x_1, x_2 \in X$ and for all $t \in [0,1]$. If $\leq$ is replaced with a strict inequaltiy in the definition, we demand $x_1 \neq x_2$ and $t\in(0,1)$ then $f$ is said to be strictly convex. For a single variable function, convexity means that if you draw a straight line connecting $f(x_1)$ and $f(x_2)$, the value of the function on the interval $[x_1,x_2]$ is always below the line as illustrated below. -===== Conditions on convex functions ===== - In the following we state first and second-order conditions which ensures convexity of a function $f$. We write $D_f$ to denote the domain of $f$, i.e the subset of $R^n$ where $f$ is defined. For more @@ -7588,8 +5362,6 @@ everywhere. This condition is particularly useful since it gives us an procedure for determining if the function under consideration is convex, apart from using the definition. -===== More on convex functions ===== - The next result is of great importance to us and the reason why we are going on about convex functions. In machine learning we frequently have to minimize a loss/cost function in order to find the best @@ -7657,8 +5429,6 @@ where $\hat{r}$ is the so-called residual or error in the iterative process. When we have found the exact solution, $\hat{r}=0$. -===== Gradient method ===== - The residual is zero when we reach the minimum of the quadratic equation !bt \begin{equation*} @@ -7671,8 +5441,6 @@ symmetric. This defines also the Hessian and we want it to be positive definit -===== Steepest descent method ===== - We denote the initial guess for $\hat{x}$ as $\hat{x}_0$. We can assume without loss of generality that !bt @@ -7690,8 +5458,6 @@ instead. -===== Steepest descent method ===== -!bblock One can show that the solution $\hat{x}$ is also the unique minimizer of the quadratic form !bt \begin{equation*} @@ -7709,11 +5475,6 @@ which equals and $\hat{x}_0=0$ it is equal $-\hat{b}$. -!eblock - - -===== Final expressions ===== -!bblock We can compute the residual iteratively as !bt \begin{equation*} @@ -7745,15 +5506,9 @@ leading to the iterative scheme \hat{x}_{k+1}=\hat{x}_k-\alpha_k\hat{r}_{k}, \end{equation*} !et -!eblock - - - -===== Code examples for steepest descent ===== - ===== Simple codes for steepest descent and conjugate gradient using a $2\times 2$ matrix, in c++, Python code to come ===== -!bblock + !bc cppcod #include #include @@ -7781,11 +5536,9 @@ int main(int argc, char * argv[]){ cout << endl; } !ec -!eblock -===== The routine for the steepest descent method ===== -!bblock + !bc cppcod Vector SteepestDescent(Matrix A, Vector b, Vector x0){ int IterMax, i; @@ -7809,9 +5562,6 @@ Vector SteepestDescent(Matrix A, Vector b, Vector x0){ return x; } !ec -!eblock - - ===== Steepest descent example ===== @@ -7868,7 +5618,7 @@ pt.plot(it_array.T[0], it_array.T[1], "x-") ===== Conjugate gradient method ===== -!bblock + In the CG method we define so-called conjugate directions and two vectors $\hat{s}$ and $\hat{t}$ are said to be @@ -7887,11 +5637,7 @@ of our vectors $\hat{x}_i$ obeying the above criterion, namely !et Two vectors are conjugate if they are orthogonal with respect to this inner product. Being conjugate is a symmetric relation: if $\hat{s}$ is conjugate to $\hat{t}$, then $\hat{t}$ is conjugate to $\hat{s}$. -!eblock - -===== Conjugate gradient method ===== -!bblock An example is given by the eigenvectors of the matrix !bt \begin{equation*} @@ -7899,12 +5645,7 @@ An example is given by the eigenvectors of the matrix \end{equation*} !et which is zero unless $i=j$. -!eblock - - -===== Conjugate gradient method ===== -!bblock Assume now that we have a symmetric positive-definite matrix $\hat{A}$ of size $n\times n$. At each iteration $i+1$ we obtain the conjugate direction of a vector !bt @@ -7921,11 +5662,7 @@ $ \hat{A}\hat{x} = \hat{b}$ in this basis, namely \hat{x} = \sum^{n}_{i=1} \alpha_i \hat{p}_i. \end{equation*} !et -!eblock - -===== Conjugate gradient method ===== -!bblock The coefficients are given by !bt \begin{equation*} @@ -7946,11 +5683,6 @@ and we can define the coefficients $\alpha_k$ as \alpha_k = \frac{\hat{p}_k^T \hat{b}}{\hat{p}_k^T \hat{A} \hat{p}_k} \end{equation*} !et -!eblock - - -===== Conjugate gradient method and iterations ===== -!bblock If we choose the conjugate vectors $\hat{p}_k$ carefully, then we may not need all of them to obtain a good approximation to the solution @@ -7973,12 +5705,7 @@ or consider the system \end{equation*} !et instead. -!eblock - - -===== Conjugate gradient method ===== -!bblock One can show that the solution $\hat{x}$ is also the unique minimizer of the quadratic form !bt \begin{equation*} @@ -7997,12 +5724,7 @@ and $\hat{x}_0=0$ it is equal $-\hat{b}$. The other vectors in the basis will be conjugate to the gradient, hence the name conjugate gradient method. -!eblock - - -===== Conjugate gradient method ===== -!bblock Let $\hat{r}_k$ be the residual at the $k$-th step: !bt \begin{equation*} @@ -8021,11 +5743,7 @@ This gives the following expression \hat{p}_{k+1}=\hat{r}_k-\frac{\hat{p}_k^T \hat{A}\hat{r}_k}{\hat{p}_k^T\hat{A}\hat{p}_k} \hat{p}_k. \end{equation*} !et -!eblock - -===== Conjugate gradient method ===== -!bblock We can also compute the residual iteratively as !bt \begin{equation*} @@ -8051,13 +5769,9 @@ which gives \hat{r}_{k+1}=\hat{r}_k-\hat{A}\hat{p}_{k}, \end{equation*} !et -!eblock - - - ===== Simple implementation of the Conjugate gradient algorithm ===== -!bblock + !bc cppcod Vector ConjugateGradient(Matrix A, Vector b, Vector x0){ int dim = x0.Dimension(); @@ -8084,12 +5798,9 @@ which gives return x; } !ec -!eblock - - ===== Broyden–Fletcher–Goldfarb–Shanno algorithm ===== -!bblock + The optimization problem is to minimize $f(\mathbf {x} )$ where $\mathbf {x}$ is a vector in $R^{n}$, and $f$ is a differentiable scalar function. There are no constraints on the values that $\mathbf {x}$ can take. The algorithm begins at an initial estimate for the optimal value $\mathbf {x}_{0}$ and proceeds iteratively to get a better estimate at each stage. @@ -8114,21 +5825,13 @@ f(\mathbf {x}_{k}+\alpha \mathbf {p}_{k}), !et over the scalar $\alpha > 0$. -!eblock - - - - - - -===== Revisiting our first homework ===== We will use linear regression as a case study for the gradient descent methods. Linear regression is a great test case for the gradient descent methods discussed in the lectures since it has several desirable properties such as: -o An analytical solution (recall homework set 1). +o An analytical solution. o The gradient can be computed analytically. o The cost function is convex which guarantees that gradient descent converges for small enough learning rates @@ -8152,7 +5855,7 @@ such that \] !et - + ===== Gradient descent example ===== Let $\mathbf{y} = (y_1,\cdots,y_n)^T$, $\mathbf{\hat{y}} = (\hat{y}_1,\cdots,\hat{y}_n)^T$ and $\beta = (\beta_0, \beta_1)^T$ @@ -8176,8 +5879,6 @@ C(\beta) = ||X\beta-\mathbf{y}||^2 = ||X\beta||^2 - 2 \mathbf{y}^T X\beta + ||\m and we want to find $\beta$ such that $C(\beta)$ is minimized. -===== The derivative of the cost/loss function ===== - Computing $\partial C(\beta) / \partial \beta_0$ and $\partial C(\beta) / \partial \beta_1$ we can show that the gradient can be written as !bt \[ @@ -8189,7 +5890,6 @@ Computing $\partial C(\beta) / \partial \beta_0$ and $\partial C(\beta) / \parti where $X$ is the design matrix defined above. -===== The Hessian matrix ===== The Hessian matrix of $C(\beta)$ is given by !bt \[ @@ -8203,8 +5903,6 @@ This result implies that $C(\beta)$ is a convex function since the matrix $X^T X - - ===== Simple program ===== We can now write a program that minimizes $C(\beta)$ using the gradient descent method with a constant learning rate $\gamma$ according to @@ -8242,8 +5940,6 @@ print(beta_NE) !ec -===== Gradient Descent Example ===== - Another simple example is here !bc pycod @@ -8312,7 +6008,7 @@ print(sgdreg.intercept_, sgdreg.coef_) - + ===== Gradient descent and Ridge ===== We have also discussed Ridge regression where the loss function contains a regularized given by the $L_2$ norm of $\beta$, @@ -8422,7 +6118,7 @@ plt.show() print("The max absolute difference is: %g"%(np.max(np.abs(computed - analytic)))) !ec - + ===== Using autograd ===== Here we @@ -8528,7 +6224,7 @@ using arrays to represent the variables, the output from Autograd might be easier to work with, as the output is closer to what one could expect form a gradient-evaluting function. - + ===== Functions using mathematical functions from Numpy ===== !bc pycod @@ -8553,8 +6249,6 @@ print("The analytical gradient of f4 at x = %g is: %g"%(x,f4_grad_analytical)) -===== More autograd ===== - !bc pycod import autograd.numpy as np from autograd import grad @@ -8573,9 +6267,6 @@ print("The computed derivative of f5 at x = %g is: %g"%(x,f5_grad(x))) !ec - -===== And with loops ===== - !bc pycod import autograd.numpy as np from autograd import grad @@ -8732,8 +6423,6 @@ C(\mathbf{\beta}) = \sum_{i=1}^n c_i(\mathbf{x}_i, !et -===== Computation of gradients ===== - This in turn means that the gradient can be computed as a sum over $i$-gradients !bt @@ -8750,7 +6439,6 @@ minibatches. We denote these minibatches by $B_k$ where $k=1,\cdots,n/M$. -===== SGD example ===== As an example, suppose we have $10$ data points $(\mathbf{x}_1,\cdots, \mathbf{x}_{10})$ and we choose to have $M=5$ minibathces, then each minibatch contains two data points. In particular we have @@ -8773,7 +6461,6 @@ c_i(\mathbf{x}_i, \mathbf{\beta}). !et -===== The gradient step ===== Thus a gradient descent step now looks like !bt @@ -8790,8 +6477,6 @@ typical to choose a number of epochs and for each epoch iterate over the number of minibatches, as exemplified in the code below. -===== Simple example code ===== - !bc pycod import numpy as np @@ -8818,8 +6503,6 @@ cheaper since we sum over the datapoints in the $k-th$ minibatch and not all $n$ datapoints. -===== When do we stop? ===== - A natural question is when do we stop the search for a new minimum? One possibility is to compute the full gradient after a given number of epochs and check if the norm of the gradient is smaller than some @@ -8832,8 +6515,6 @@ compare the values of the cost function and keep the $\beta$ that gave the lowest value. -===== Slightly different approach ===== - Another approach is to let the step length $\gamma_j$ depend on the number of epochs in such a way that it becomes very small after a reasonable time such that we do not move at all. @@ -8875,11 +6556,6 @@ print("gamma_j after %d epochs: %g" % (n_epochs,gamma_j)) - - - -===== Program for stochastic gradient ===== - !bc pycod # Importing various packages from math import exp, sqrt @@ -8955,10 +6631,6 @@ plt.show() !ec - - - - ===== Using gradient descent methods, limitations ===== * _Gradient descent (GD) finds local minima of our function_. Since the GD algorithm is deterministic, if it converges, it will converge to a local minimum of our energy function. Because in ML we are often dealing with extremely rugged landscapes with many local minima, this can lead to poor performance. @@ -9042,9 +6714,6 @@ One of the major advantages of NAG is that it allows for the use of a larger lea -===== Second moment of the gradient ===== - - In stochastic gradient descent, with and without momentum, we still have to specify a schedule for tuning the learning rates $\eta_t$ as a function of time. As discussed in the context of Newton's @@ -9115,3135 +6784,3 @@ Like in RMSprop, the effective step size of a parameter depends on the magnitude * _Adaptive optimization methods don't always have good generalization._ Recent studies have shown that adaptive methods such as ADAM, RMSPorp, and AdaGrad tend to have poor generalization compared to SGD or SGD with momentum, particularly in the high-dimensional limit (i.e. the number of parameters exceeds the number of data points). Although it is not clear at this stage why these methods perform so well in training deep neural networks, simpler procedures like properly-tuned SGD may work as well or better in these applications. -======= Logistic Regression ======= - -In linear regression our main interest was centered on learning the -coefficients of a functional fit (say a polynomial) in order to be -able to predict the response of a continuous variable on some unseen -data. The fit to the continuous variable $y_i$ is based on some -independent variables $\hat{x}_i$. Linear regression resulted in -analytical expressions (in terms of matrices to invert) for several -quantities, ranging from the variance and thereby the confidence -intervals of the parameters $\hat{\beta}$ to the mean squared -error. If we can invert the product of the design matrices, linear -regression gives then a simple recipe for fitting our data. - - -Classification problems, however, are concerned with outcomes taking -the form of discrete variables (i.e. categories). We may for example, -on the basis of DNA sequencing for a number of patients, like to find -out which mutations are important for a certain disease; or based on -scans of various patients' brains, figure out if there is a tumor or -not; or given a specific physical system, we'd like to identify its -state, say whether it is an ordered or disordered system (typical -situation in solid state physics); or classify the status of a -patient, whether she/he has a stroke or not and many other similar -situations. - -The most common situation we encounter when we apply logistic -regression is that of two possible outcomes, normally denoted as a -binary outcome, true or false, positive or negative, success or -failure etc. - - -===== Optimization and Deep learning ===== - -Logistic regression will also serve as our stepping stone towards neural -network algorithms and supervised deep learning. For logistic -learning, the minimization of the cost function leads to a non-linear -equation in the parameters $\hat{\beta}$. The optmization of the problem calls therefore for minimization algorithms. This forms the bottle neck of all machine learning algorithms, namely how to find reliable minima of a multi-variable function. This leads us to the family of gradient descent methods. The latter are the working horses of basically all modern machine learning algorithms. - -We note also that many of the topics discussed here -regression are also commonly used in modern supervised Deep Learning -models, as we will see later. - - - -===== Basics ===== - -We consider the case where the dependent variables, also called the -responses or the outcomes, $y_i$ are discrete and only take values -from $k=0,\dots,K-1$ (i.e. $K$ classes). - -The goal is to predict the -output classes from the design matrix $\hat{X}\in\mathbb{R}^{n\times p}$ -made of $n$ samples, each of which carries $p$ features or predictors. The -primary goal is to identify the classes to which new unseen samples -belong. - -Let us specialize to the case of two classes only, with outputs $y_i=0$ and $y_i=1$. Our outcomes could represent the status of a credit card user who could default or not on her/his credit card debt. That is -!bt -\[ -y_i = \begin{bmatrix} 0 & \mathrm{no}\\ 1 & \mathrm{yes} \end{bmatrix}. -\] -!et - - - - -===== Linear classifier ===== - -Before moving to the logistic model, let us try to use our linear regression model to classify these two outcomes. We could for example fit a linear model to the default case if $y_i > 0.5$ and the no default case $y_i \leq 0.5$. - -We would then have our -weighted linear combination, namely -!bt -\begin{equation} -\hat{y} = \hat{X}^T\hat{\beta} + \hat{\epsilon}, -\end{equation} -!et -where $\hat{y}$ is a vector representing the possible outcomes, $\hat{X}$ is our -$n\times p$ design matrix and $\hat{\beta}$ represents our estimators/predictors. - - -===== Some selected properties ===== - -The main problem with our function is that it -takes values on the entire real axis. In the case of -logistic regression, however, the labels $y_i$ are discrete -variables. - -One simple way to get a discrete output is to have sign -functions that map the output of a linear regressor to values $\{0,1\}$, -$f(s_i)=sign(s_i)=1$ if $s_i\ge 0$ and 0 if otherwise. -We will encounter this model in our first demonstration of neural networks. Historically it is called the ``perceptron" model in the machine learning -literature. This model is extremely simple. However, in many cases it is more -favorable to use a ``soft" classifier that outputs -the probability of a given category. This leads us to the logistic function. - -The code for plotting the perceptron can be seen here. This si nothing but the standard "Heaviside step function":"https://en.wikipedia.org/wiki/Heaviside_step_function". -!bc pycod - -!ec - - - -===== The logistic function ===== - -The perceptron is an example of a ``hard classification'' model. We -will encounter this model when we discuss neural networks as -well. Each datapoint is deterministically assigned to a category (i.e -$y_i=0$ or $y_i=1$). In many cases, it is favorable to have a ``soft'' -classifier that outputs the probability of a given category rather -than a single value. For example, given $x_i$, the classifier -outputs the probability of being in a category $k$. Logistic regression -is the most common example of a so-called soft classifier. In logistic -regression, the probability that a data point $x_i$ -belongs to a category $y_i=\{0,1\}$ is given by the so-called logit function (or Sigmoid) which is meant to represent the likelihood for a given event, -!bt -\[ -p(t) = \frac{1}{1+\mathrm \exp{-t}}=\frac{\exp{t}}{1+\mathrm \exp{t}}. -\] -!et -Note that $1-p(t)= p(-t)$. -The following code plots the logistic function. -!bc pycod - -!ec - - - - -===== Two parameters ===== - -We assume now that we have two classes with $y_i$ either $0$ or $1$. Furthermore we assume also that we have only two parameters $\beta$ in our fitting of the Sigmoid function, that is we define probabilities -!bt -\begin{align*} -p(y_i=1|x_i,\hat{\beta}) &= \frac{\exp{(\beta_0+\beta_1x_i)}}{1+\exp{(\beta_0+\beta_1x_i)}},\nonumber\\ -p(y_i=0|x_i,\hat{\beta}) &= 1 - p(y_i=1|x_i,\hat{\beta}), -\end{align*} -!et -where $\hat{\beta}$ are the weights we wish to extract from data, in our case $\beta_0$ and $\beta_1$. - -Note that we used -!bt -\[ -p(y_i=0\vert x_i, \hat{\beta}) = 1-p(y_i=1\vert x_i, \hat{\beta}). -\] -!et - - -===== Maximum likelihood ===== - -In order to define the total likelihood for all possible outcomes from a -dataset $\mathcal{D}=\{(y_i,x_i)\}$, with the binary labels -$y_i\in\{0,1\}$ and where the data points are drawn independently, we use the so-called "Maximum Likelihood Estimation":"https://en.wikipedia.org/wiki/Maximum_likelihood_estimation" (MLE) principle. -We aim thus at maximizing -the probability of seeing the observed data. We can then approximate the -likelihood in terms of the product of the individual probabilities of a specific outcome $y_i$, that is -!bt -\begin{align*} -P(\mathcal{D}|\hat{\beta})& = \prod_{i=1}^n \left[p(y_i=1|x_i,\hat{\beta})\right]^{y_i}\left[1-p(y_i=1|x_i,\hat{\beta}))\right]^{1-y_i}\nonumber \\ -\end{align*} -!et -from which we obtain the log-likelihood and our _cost/loss_ function -!bt -\[ -\mathcal{C}(\hat{\beta}) = \sum_{i=1}^n \left( y_i\log{p(y_i=1|x_i,\hat{\beta})} + (1-y_i)\log\left[1-p(y_i=1|x_i,\hat{\beta}))\right]\right). -\] -!et - - -===== The cost function rewritten ===== - -Reordering the logarithms, we can rewrite the _cost/loss_ function as -!bt -\[ -\mathcal{C}(\hat{\beta}) = \sum_{i=1}^n \left(y_i(\beta_0+\beta_1x_i) -\log{(1+\exp{(\beta_0+\beta_1x_i)})}\right). -\] -!et - -The maximum likelihood estimator is defined as the set of parameters that maximize the log-likelihood where we maximize with respect to $\beta$. -Since the cost (error) function is just the negative log-likelihood, for logistic regression we have that -!bt -\[ -\mathcal{C}(\hat{\beta})=-\sum_{i=1}^n \left(y_i(\beta_0+\beta_1x_i) -\log{(1+\exp{(\beta_0+\beta_1x_i)})}\right). -\] -!et -This equation is known in statistics as the _cross entropy_. Finally, we note that just as in linear regression, -in practice we often supplement the cross-entropy with additional regularization terms, usually $L_1$ and $L_2$ regularization as we did for Ridge and Lasso regression. - - -===== Minimizing the cross entropy ===== - -The cross entropy is a convex function of the weights $\hat{\beta}$ and, -therefore, any local minimizer is a global minimizer. - - -Minimizing this -cost function with respect to the two parameters $\beta_0$ and $\beta_1$ we obtain - -!bt -\[ -\frac{\partial \mathcal{C}(\hat{\beta})}{\partial \beta_0} = -\sum_{i=1}^n \left(y_i -\frac{\exp{(\beta_0+\beta_1x_i)}}{1+\exp{(\beta_0+\beta_1x_i)}}\right), -\] -!et -and -!bt -\[ -\frac{\partial \mathcal{C}(\hat{\beta})}{\partial \beta_1} = -\sum_{i=1}^n \left(y_ix_i -x_i\frac{\exp{(\beta_0+\beta_1x_i)}}{1+\exp{(\beta_0+\beta_1x_i)}}\right). -\] -!et - - -===== A more compact expression ===== - -Let us now define a vector $\hat{y}$ with $n$ elements $y_i$, an -$n\times p$ matrix $\hat{X}$ which contains the $x_i$ values and a -vector $\hat{p}$ of fitted probabilities $p(y_i\vert x_i,\hat{\beta})$. We can rewrite in a more compact form the first -derivative of cost function as - -!bt -\[ -\frac{\partial \mathcal{C}(\hat{\beta})}{\partial \hat{\beta}} = -\hat{X}^T\left(\hat{y}-\hat{p}\right). -\] -!et - -If we in addition define a diagonal matrix $\hat{W}$ with elements -$p(y_i\vert x_i,\hat{\beta})(1-p(y_i\vert x_i,\hat{\beta})$, we can obtain a compact expression of the second derivative as - -!bt -\[ -\frac{\partial^2 \mathcal{C}(\hat{\beta})}{\partial \hat{\beta}\partial \hat{\beta}^T} = \hat{X}^T\hat{W}\hat{X}. -\] -!et - - -===== Extending to more predictors ===== - -Within a binary classification problem, we can easily expand our model to include multiple predictors. Our ratio between likelihoods is then with $p$ predictors -!bt -\[ -\log{ \frac{p(\hat{\beta}\hat{x})}{1-p(\hat{\beta}\hat{x})}} = \beta_0+\beta_1x_1+\beta_2x_2+\dots+\beta_px_p. -\] -!et -Here we defined $\hat{x}=[1,x_1,x_2,\dots,x_p]$ and $\hat{\beta}=[\beta_0, \beta_1, \dots, \beta_p]$ leading to -!bt -\[ -p(\hat{\beta}\hat{x})=\frac{ \exp{(\beta_0+\beta_1x_1+\beta_2x_2+\dots+\beta_px_p)}}{1+\exp{(\beta_0+\beta_1x_1+\beta_2x_2+\dots+\beta_px_p)}}. -\] -!et - - -===== Including more classes ===== - -Till now we have mainly focused on two classes, the so-called binary system. Suppose we wish to extend to $K$ classes. -Let us for the sake of simplicity assume we have only two predictors. We have then following model -!bt -\[ -\log{\frac{p(C=1\vert x)}{p(K\vert x)}} = \beta_{10}+\beta_{11}x_1, -\] -!et -!bt -\[ -\log{\frac{p(C=2\vert x)}{p(K\vert x)}} = \beta_{20}+\beta_{21}x_1, -\] -!et -and so on till the class $C=K-1$ class -!bt -\[ -\log{\frac{p(C=K-1\vert x)}{p(K\vert x)}} = \beta_{(K-1)0}+\beta_{(K-1)1}x_1, -\] -!et -and the model is specified in term of $K-1$ so-called log-odds or _logit_ transformations. - - - -===== The Softmax function ===== - -In our discussion of neural networks we will encounter the above again in terms of the so-called _Softmax_ function. - -The softmax function is used in various multiclass classification -methods, such as multinomial logistic regression (also known as -softmax regression), multiclass linear discriminant -analysis, naive Bayes classifiers, and artificial neural networks. -Specifically, in multinomial logistic regression and linear -discriminant analysis, the input to the function is the result of $K$ -distinct linear functions, and the predicted probability for the $k$-th -class given a sample vector $\hat{x}$ and a weighting vector $\hat{\beta}$ is (with two predictors): - -!bt -\[ -p(C=k\vert \mathbf {x} )=\frac{\exp{(\beta_{k0}+\beta_{k1}x_1)}}{1+\sum_{l=1}^{K-1}\exp{(\beta_{l0}+\beta_{l1}x_1)}}. -\] -!et -It is easy to extend to more predictors. The final class is -!bt -\[ -p(C=K\vert \mathbf {x} )=\frac{1}{1+\sum_{l=1}^{K-1}\exp{(\beta_{l0}+\beta_{l1}x_1)}}, -\] -!et -and they sum to one. Our earlier discussions were all specialized to the case with two classes only. It is easy to see from the above that what we derived earlier is compatible with these equations. - -To find the optimal parameters we would typically use a gradient descent method. -Newton's method and gradient descent methods are discussed in the material on "optimization methods":"https://compphysics.github.io/MachineLearning/doc/pub/Splines/html/Splines-bs.html". - - - - -===== A _scikit-learn_ example ===== - -!bc pycod -import numpy as np -import matplotlib.pyplot as plt -from sklearn import datasets -iris = datasets.load_iris() -list(iris.keys()) -['data', 'target_names', 'feature_names', 'target', 'DESCR'] -X = iris["data"][:, 3:] # petal width -y = (iris["target"] == 2).astype(np.int) # 1 if Iris-Virginica, else 0 - -from sklearn.linear_model import LogisticRegression -log_reg = LogisticRegression() -log_reg.fit(X, y) - -X_new = np.linspace(0, 3, 1000).reshape(-1, 1) -y_proba = log_reg.predict_proba(X_new) -plt.plot(X_new, y_proba[:, 1], "g-", label="Iris-Virginica") -plt.plot(X_new, y_proba[:, 0], "b--", label="Not Iris-Virginica") -plt.show() - -!ec - - - -===== A simple classification problem ===== -!bc pycod -import numpy as np -from sklearn import datasets, linear_model -import matplotlib.pyplot as plt - - -def generate_data(): - np.random.seed(0) - X, y = datasets.make_moons(200, noise=0.20) - return X, y - - -def visualize(X, y, clf): - # plt.scatter(X[:, 0], X[:, 1], s=40, c=y, cmap=plt.cm.Spectral) - # plt.show() - plot_decision_boundary(lambda x: clf.predict(x), X, y) - plt.title("Logistic Regression") - - -def plot_decision_boundary(pred_func, X, y): - # Set min and max values and give it some padding - x_min, x_max = X[:, 0].min() - .5, X[:, 0].max() + .5 - y_min, y_max = X[:, 1].min() - .5, X[:, 1].max() + .5 - h = 0.01 - # Generate a grid of points with distance h between them - xx, yy = np.meshgrid(np.arange(x_min, x_max, h), np.arange(y_min, y_max, h)) - # Predict the function value for the whole gid - Z = pred_func(np.c_[xx.ravel(), yy.ravel()]) - Z = Z.reshape(xx.shape) - # Plot the contour and training examples - plt.contourf(xx, yy, Z, cmap=plt.cm.Spectral) - plt.scatter(X[:, 0], X[:, 1], c=y, cmap=plt.cm.Spectral) - plt.show() - - -def classify(X, y): - clf = linear_model.LogisticRegressionCV() - clf.fit(X, y) - return clf - - -def main(): - X, y = generate_data() - # visualize(X, y) - clf = classify(X, y) - visualize(X, y, clf) - - -if __name__ == "__main__": - main() -!ec - - -===== The two-dimensional Ising model, Predicting phase transition of the two-dimensional Ising model ===== - -The Hamiltonian of the two-dimensional Ising model without an external field for a constant coupling constant $J$ is given by -!bt -\begin{align} - H = -J \sum_{\langle ij\rangle} S_i S_j, -\end{align} -!et -where $S_i \in \{-1, 1\}$ and $\langle ij \rangle$ signifies that we only iterate over the nearest neighbors in the lattice. We will be looking at a system of $L = 40$ spins in each dimension, i.e., $L^2 = 1600$ spins in total. Opposed to the one-dimensional Ising model we will get a phase transition from an _ordered_ phase to a _disordered_ phase at the critical temperature - -!bt -\begin{align} - \frac{T_c}{J} = \frac{2}{\log\left(1 + \sqrt{2}\right)} \approx 2.26, -\end{align} -!et -as shown by Lars Onsager. - - -Here we use _logistic regression_ to predict when a phase transition -occurs. The data we will look at is a set of spin configurations, -i.e., individual lattices with spins, labeled _ordered_ `1` or -_disordered_ `0`. Our job is to build a model which will take in a -spin configuration and predict whether or not the spin configuration -constitutes an ordered or a disordered phase. To achieve this we will -represent the lattices as flattened arrays with $1600$ elements -instead of a matrix of $40 \times 40$ elements. As an extra test of -the performance of the algorithms we will divide the dataset into -three pieces. We will do a conventional train-test-split on a -combination of totally ordered and totally disordered phases. The -remaining "critical-like" states will be used as test data which we -hope the model will be able to make good extrapolated predictions on. - - -!bc pycod -import pickle -import os -import glob -import numpy as np -import pandas as pd -import matplotlib.pyplot as plt -import seaborn as sns -import sklearn.model_selection as skms -import sklearn.linear_model as skl -import sklearn.metrics as skm -import tqdm -import copy -import time -from IPython.display import display - -%matplotlib inline - -sns.set(color_codes=True) -!ec - - -===== Reading in the data ===== - -Using the data from "Mehta et al.":"https://physics.bu.edu/~pankajm/ML-Review-Datasets/isingMC/" (specifically the two datasets named `Ising2DFM_reSample_L40_T=All.pkl` and `Ising2DFM_reSample_L40_T=All_labels.pkl`) we have to unpack the data into numpy arrays. - - -!bc pycod -filenames = glob.glob(os.path.join("..", "dat", "*")) -label_filename = list(filter(lambda x: "label" in x, filenames))[0] -dat_filename = list(filter(lambda x: "label" not in x, filenames))[0] - -# Read in the labels -with open(label_filename, "rb") as f: - labels = pickle.load(f) - -# Read in the corresponding configurations -with open(dat_filename, "rb") as f: - data = np.unpackbits(pickle.load(f)).reshape(-1, 1600).astype("int") - -# Set spin-down to -1 -data[data == 0] = -1 -!ec - -This dataset consists of $10000$ samples, i.e., $10000$ spin -configurations with $40 \times 40$ spins each, for $16$ temperatures -between $0.25$ to $4.0$. Next we create a train/test-split and keep -the data in the critical phase as a separate dataset for -extrapolation-testing. - - -!bc pycod -# Set up slices of the dataset -ordered = slice(0, 70000) -critical = slice(70000, 100000) -disordered = slice(100000, 160000) - -X_train, X_test, y_train, y_test = skms.train_test_split( - np.concatenate((data[ordered], data[disordered])), - np.concatenate((labels[ordered], labels[disordered])), - test_size=0.95 -) -!ec - -Using a small training set yields a better accuracy. This will be discussed in the end. - - -===== Logistic regression ===== - -Logistic regression is a linear model for classification. Recalling -the cost function for ordinary least squares with both L2 (ridge) and -L1 (LASSO) penalties we will see that the logistic cost function is -very similar. In OLS we wish to predict a continuous variable -$\hat{y}$ using -!bt -\begin{align} - \hat{y} = X\omega, -\end{align} -!et - -where $X \in \mathbb{R}^{n \times p}$ is the input data and $\omega^{p -\times d}$ are the weights of the regression. In a classification -setting (binary classification in our situation) we are interested in -a positive or negative answer. We can thus define either answer to be -above or below some threshold. But, in order to limit the size of the -answer and also to get a probability interpretation on how sure we are -for either answer we can compute the sigmoid function of OLS. That is, - -!bt -\begin{align} - f(X\omega) = \frac{1}{1 + \exp(-X\omega)}. -\end{align} -!et -We are thus interested in minizming the following cost function -!bt -\begin{align} - C(X, \omega) = \sum_{i = 1}^n \left\{ - - y_i\log\left( f(x_i^T\omega) \right) - - (1 - y_i)\log\left[1 - f(x_i^T\omega)\right] - \right\}, -\end{align} -!et - -where we will restrict ourselves to a value for $f(z)$ as the sigmoid -described above. We can also tack on a L2 (Ridge) or L1 (LASSO) -penalization to this cost function in the same manner we did for -linear regression. - - -===== Exploring the logistic regression ===== - -The penalization factor $\lambda$ is inverted in the case of the -logistic regression model we use. We will explore several values of -$\lambda$ using both L1 and L2 penalization. We do this using a grid -search over different parameters and run a 3-fold cross validation for -each configuration. In other words, we fit a model 3 times for each -configuration of the hyper parameters. - - -!bc pycod -lambdas = np.logspace(-7, -1, 7) - -param_grid = { - "C": list(1.0/lambdas), - "penalty": ["l1", "l2"] -} -clf = skms.GridSearchCV( - skl.LogisticRegression(), - param_grid=param_grid, - n_jobs=-1, - return_train_score=True -) -t0 = time.time() -clf.fit(X_train, y_train) -t1 = time.time() - -print ( - "Time spent fitting GridSearchCV(LogisticRegression): {0:.3f} sec".format( - t1 - t0 - ) -) -!ec - -We can see that logistic regression is quite slow and using the grid -search and cross validation results in quite a heavy -computation. Below we show the results of the different -configurations. - - -!bc pycod -logreg_df = pd.DataFrame(clf.cv_results_) - -display(logreg_df) -!ec - - -===== Accuracy of a classification model ===== - -To determine how well a classification model is performing we count -the number of correctly labeled classes and divide by the number of -classes in total. The accuracy is thus given by - -!bt -\begin{align} - a(y, \hat{y}) = \frac{1}{n}\sum_{i = 1}^{n} I(y_i = \hat{y}_i), -\end{align} -!et - -where $I(y_i = \hat{y}_i)$ is the indicator function given by - -!bt -\begin{align} - I(x = y) = \begin{array}{cc} - 1 & x = y, \\ - 0 & x \neq y. - \end{array} -\end{align} -!et - -This is the accuracy provided by Scikit-learn when using _sklearn.metrics.accuracyscore_. - -Below we compute the accuracy of the best fit model on the training data (which should give a good accuracy), the test data (which has not been shown to the model) and the critical data (completely new data that needs to be extrapolated). - - -!bc pycod -train_accuracy = skm.accuracy_score(y_train, clf.predict(X_train)) -test_accuracy = skm.accuracy_score(y_test, clf.predict(X_test)) -critical_accuracy = skm.accuracy_score(labels[critical], clf.predict(data[critical])) - -print ("Accuracy on train data: {0}".format(train_accuracy)) -print ("Accuracy on test data: {0}".format(test_accuracy)) -print ("Accuracy on critical data: {0}".format(critical_accuracy)) -!ec - -We can see that we get quite good accuracy on the training data, but gradually worsening accuracy on the test and critical data. - - -===== Analyzing the results ===== - -Below we show a different metric for determining the quality of our -model, namely the _reciever operating characteristic_ (ROC). The ROC -curve tells us how well the model correctly classifies the different -labels. We plot the _true positive rate_ (the rate of predicted -positive classes that are positive) versus the _false positive rate_ -(the rate of predicted positive classes that are negative). The ROC -curve is built by computing the true positive rate and the false -positive rate for varying _thresholds_, i.e, which probability we -should acredit a certain class. - -By computing the _area under the curve_ (AUC) of the ROC curve we get an estimate of how well our model is performing. Pure guessing will get an AUC of $0.5$. A perfect score will get an AUC of $1.0$. - - -!bc pycod -fig = plt.figure(figsize=(20, 14)) - -for (_X, _y), label in zip( - [ - (X_train, y_train), - (X_test, y_test), - (data[critical], labels[critical]) - ], - ["Train", "Test", "Critical"] -): - proba = clf.predict_proba(_X) - fpr, tpr, _ = skm.roc_curve(_y, proba[:, 1]) - roc_auc = skm.auc(fpr, tpr) - - print ("LogisticRegression AUC ({0}): {1}".format(label, roc_auc)) - - plt.plot(fpr, tpr, label="{0} (AUC = {1})".format(label, roc_auc), linewidth=4.0) - -plt.plot([0, 1], [0, 1], "--", label="Guessing (AUC = 0.5)", linewidth=4.0) - -plt.title(r"The ROC curve for LogisticRegression", fontsize=18) -plt.xlabel(r"False positive rate", fontsize=18) -plt.ylabel(r"True positive rate", fontsize=18) -plt.axis([-0.01, 1.01, -0.01, 1.01]) -plt.xticks(fontsize=18) -plt.yticks(fontsize=18) -plt.legend(loc="best", fontsize=18) -plt.show() -!ec - -We can see that this plot of the ROC looks very strange. This tells us -that logistic regression is quite inept at predicting the Ising model -transition and is therefore highly non-linear. The ROC curve for the -training data looks quite good, but as the testing data is so far off -we see that we are dealing with an overfit model. - -A previous run with $50\%$ of the data used for training yielded a -worse performance than using a smaller training set. This again gives -confidence to the fact that logistic regression is not able to -correctly fit the Ising model as it is not a linear model. - - - - - - - -======= Neural networks ======= - -Artificial neural networks are computational systems that can learn to -perform tasks by considering examples, generally without being -programmed with any task-specific rules. It is supposed to mimic a -biological system, wherein neurons interact by sending signals in the -form of mathematical functions between layers. All layers can contain -an arbitrary number of neurons, and each connection is represented by -a weight variable. - - - -===== Artificial neurons ===== - -The field of artificial neural networks has a long history of -development, and is closely connected with the advancement of computer -science and computers in general. A model of artificial neurons was -first developed by McCulloch and Pitts in 1943 to study signal -processing in the brain and has later been refined by others. The -general idea is to mimic neural networks in the human brain, which is -composed of billions of neurons that communicate with each other by -sending electrical signals. Each neuron accumulates its incoming -signals, which must exceed an activation threshold to yield an -output. If the threshold is not overcome, the neuron remains inactive, -i.e. has zero output. - -This behaviour has inspired a simple mathematical model for an artificial neuron. - -!bt -\begin{equation} - y = f\left(\sum_{i=1}^n w_ix_i\right) = f(u) - label{artificialNeuron} -\end{equation} -!et -Here, the output $y$ of the neuron is the value of its activation function, which have as input -a weighted sum of signals $x_i, \dots ,x_n$ received by $n$ other neurons. - -Conceptually, it is helpful to divide neural networks into four -categories: -o general purpose neural networks for supervised learning, -o neural networks designed specifically for image processing, the most prominent example of this class being Convolutional Neural Networks (CNNs), -o neural networks for sequential data such as Recurrent Neural Networks (RNNs), and -o neural networks for unsupervised learning such as Deep Boltzmann Machines. - - -In natural science, DNNs and CNNs have already found numerous -applications. In statistical physics, they have been applied to detect -phase transitions in 2D Ising and Potts models, lattice gauge -theories, and different phases of polymers, or solving the -Navier-Stokes equation in weather forecasting. Deep learning has also -found interesting applications in quantum physics. Various quantum -phase transitions can be detected and studied using DNNs and CNNs, -topological phases, and even non-equilibrium many-body -localization. Representing quantum states as DNNs quantum state -tomography are among some of the impressive achievements to reveal the -potential of DNNs to facilitate the study of quantum systems. - -In quantum information theory, it has been shown that one can perform -gate decompositions with the help of neural. - -The applications are not limited to the natural sciences. There is a -plethora of applications in essentially all disciplines, from the -humanities to life science and medicine. - - -===== Neural network types ===== - -An artificial neural network (ANN), is a computational model that -consists of layers of connected neurons, or nodes or units. We will -refer to these interchangeably as units or nodes, and sometimes as -neurons. - -It is supposed to mimic a biological nervous system by letting each -neuron interact with other neurons by sending signals in the form of -mathematical functions between layers. A wide variety of different -ANNs have been developed, but most of them consist of an input layer, -an output layer and eventual layers in-between, called *hidden -layers*. All layers can contain an arbitrary number of nodes, and each -connection between two nodes is associated with a weight variable. - -Neural networks (also called neural nets) are neural-inspired -nonlinear models for supervised learning. As we will see, neural nets -can be viewed as natural, more powerful extensions of supervised -learning methods such as linear and logistic regression and soft-max -methods we discussed earlier. - - - -===== Feed-forward neural networks ===== - -The feed-forward neural network (FFNN) was the first and simplest type -of ANNs that were devised. In this network, the information moves in -only one direction: forward through the layers. - -Nodes are represented by circles, while the arrows display the -connections between the nodes, including the direction of information -flow. Additionally, each arrow corresponds to a weight variable -(figure to come). We observe that each node in a layer is connected -to *all* nodes in the subsequent layer, making this a so-called -*fully-connected* FFNN. - - - - -===== Convolutional Neural Network ===== - -A different variant of FFNNs are *convolutional neural networks* -(CNNs), which have a connectivity pattern inspired by the animal -visual cortex. Individual neurons in the visual cortex only respond to -stimuli from small sub-regions of the visual field, called a receptive -field. This makes the neurons well-suited to exploit the strong -spatially local correlation present in natural images. The response of -each neuron can be approximated mathematically as a convolution -operation. (figure to come) - -Convolutional neural networks emulate the behaviour of neurons in the -visual cortex by enforcing a *local* connectivity pattern between -nodes of adjacent layers: Each node in a convolutional layer is -connected only to a subset of the nodes in the previous layer, in -contrast to the fully-connected FFNN. Often, CNNs consist of several -convolutional layers that learn local features of the input, with a -fully-connected layer at the end, which gathers all the local data and -produces the outputs. They have wide applications in image and video -recognition. - - -===== Recurrent neural networks ===== - -So far we have only mentioned ANNs where information flows in one -direction: forward. *Recurrent neural networks* on the other hand, -have connections between nodes that form directed *cycles*. This -creates a form of internal memory which are able to capture -information on what has been calculated before; the output is -dependent on the previous computations. Recurrent NNs make use of -sequential information by performing the same task for every element -in a sequence, where each element depends on previous elements. An -example of such information is sentences, making recurrent NNs -especially well-suited for handwriting and speech recognition. - - -===== Other types of networks ===== - -There are many other kinds of ANNs that have been developed. One type -that is specifically designed for interpolation in multidimensional -space is the radial basis function (RBF) network. RBFs are typically -made up of three layers: an input layer, a hidden layer with -non-linear radial symmetric activation functions and a linear output -layer (''linear'' here means that each node in the output layer has a -linear activation function). The layers are normally fully-connected -and there are no cycles, thus RBFs can be viewed as a type of -fully-connected FFNN. They are however usually treated as a separate -type of NN due the unusual activation functions. - - -===== Multilayer perceptrons ===== - -One uses often so-called fully-connected feed-forward neural networks -with three or more layers (an input layer, one or more hidden layers -and an output layer) consisting of neurons that have non-linear -activation functions. - -Such networks are often called *multilayer perceptrons* (MLPs). - - -===== Why multilayer perceptrons? ===== - -According to the *Universal approximation theorem*, a feed-forward -neural network with just a single hidden layer containing a finite -number of neurons can approximate a continuous multidimensional -function to arbitrary accuracy, assuming the activation function for -the hidden layer is a _non-constant, bounded and -monotonically-increasing continuous function_. - -Note that the requirements on the activation function only applies to -the hidden layer, the output nodes are always assumed to be linear, so -as to not restrict the range of output values. - - - -===== Mathematical model ===== - -The output $y$ is produced via the activation function $f$ -!bt -\[ - y = f\left(\sum_{i=1}^n w_ix_i + b_i\right) = f(z), -\] -!et -This function receives $x_i$ as inputs. -Here the activation $z=(\sum_{i=1}^n w_ix_i+b_i)$. -In an FFNN of such neurons, the *inputs* $x_i$ are the *outputs* of -the neurons in the preceding layer. Furthermore, an MLP is -fully-connected, which means that each neuron receives a weighted sum -of the outputs of *all* neurons in the previous layer. - - -===== Mathematical model ===== - -First, for each node $i$ in the first hidden layer, we calculate a weighted sum $z_i^1$ of the input coordinates $x_j$, - -!bt -\begin{equation} z_i^1 = \sum_{j=1}^{M} w_{ij}^1 x_j + b_i^1 -\end{equation} -!et - -Here $b_i$ is the so-called bias which is normally needed in -case of zero activation weights or inputs. How to fix the biases and -the weights will be discussed below. The value of $z_i^1$ is the -argument to the activation function $f_i$ of each node $i$, The -variable $M$ stands for all possible inputs to a given node $i$ in the -first layer. We define the output $y_i^1$ of all neurons in layer 1 as - -!bt -\begin{equation} - y_i^1 = f(z_i^1) = f\left(\sum_{j=1}^M w_{ij}^1 x_j + b_i^1\right) - label{outputLayer1} -\end{equation} -!et - -where we assume that all nodes in the same layer have identical -activation functions, hence the notation $f$. In general, we could assume in the more general case that different layers have different activation functions. -In this case we would identify these functions with a superscript $l$ for the $l$-th layer, - -!bt -\begin{equation} - y_i^l = f^l(u_i^l) = f^l\left(\sum_{j=1}^{N_{l-1}} w_{ij}^l y_j^{l-1} + b_i^l\right) - label{generalLayer} -\end{equation} -!et - -where $N_l$ is the number of nodes in layer $l$. When the output of -all the nodes in the first hidden layer are computed, the values of -the subsequent layer can be calculated and so forth until the output -is obtained. - - - - -===== Mathematical model ===== - -The output of neuron $i$ in layer 2 is thus, - -!bt -\begin{align} - y_i^2 &= f^2\left(\sum_{j=1}^N w_{ij}^2 y_j^1 + b_i^2\right) \\ - &= f^2\left[\sum_{j=1}^N w_{ij}^2f^1\left(\sum_{k=1}^M w_{jk}^1 x_k + b_j^1\right) + b_i^2\right] - label{outputLayer2} -\end{align} -!et -where we have substituted $y_k^1$ with the inputs $x_k$. Finally, the ANN output reads - -!bt -\begin{align} - y_i^3 &= f^3\left(\sum_{j=1}^N w_{ij}^3 y_j^2 + b_i^3\right) \\ - &= f_3\left[\sum_{j} w_{ij}^3 f^2\left(\sum_{k} w_{jk}^2 f^1\left(\sum_{m} w_{km}^1 x_m + b_k^1\right) + b_j^2\right) - + b_1^3\right] -\end{align} -!et - - -===== Mathematical model ===== - -We can generalize this expression to an MLP with $l$ hidden -layers. The complete functional form is, - -!bt -\begin{align} -&y^{l+1}_i = f^{l+1}\left[\!\sum_{j=1}^{N_l} w_{ij}^3 f^l\left(\sum_{k=1}^{N_{l-1}}w_{jk}^{l-1}\left(\dots f^1\left(\sum_{n=1}^{N_0} w_{mn}^1 x_n+ b_m^1\right)\dots\right)+b_k^2\right)+b_1^3\right] && - label{completeNN} -\end{align} -!et - -which illustrates a basic property of MLPs: The only independent -variables are the input values $x_n$. - - -===== Mathematical model ===== - -This confirms that an MLP, despite its quite convoluted mathematical -form, is nothing more than an analytic function, specifically a -mapping of real-valued vectors $\hat{x} \in \mathbb{R}^n \rightarrow -\hat{y} \in \mathbb{R}^m$. - -Furthermore, the flexibility and universality of an MLP can be -illustrated by realizing that the expression is essentially a nested -sum of scaled activation functions of the form - -!bt -\begin{equation} - f(x) = c_1 f(c_2 x + c_3) + c_4 -\end{equation} -!et - -where the parameters $c_i$ are weights and biases. By adjusting these -parameters, the activation functions can be shifted up and down or -left and right, change slope or be rescaled which is the key to the -flexibility of a neural network. - - -=== Matrix-vector notation === - -We can introduce a more convenient notation for the activations in an A NN. - -Additionally, we can represent the biases and activations -as layer-wise column vectors $\hat{b}_l$ and $\hat{y}_l$, so that the $i$-th element of each vector -is the bias $b_i^l$ and activation $y_i^l$ of node $i$ in layer $l$ respectively. - -We have that $\mathrm{W}_l$ is an $N_{l-1} \times N_l$ matrix, while $\hat{b}_l$ and $\hat{y}_l$ are $N_l \times 1$ column vectors. -With this notation, the sum becomes a matrix-vector multiplication, and we can write -the equation for the activations of hidden layer 2 (assuming three nodes for simplicity) as -!bt -\begin{equation} - \hat{y}_2 = f_2(\mathrm{W}_2 \hat{y}_{1} + \hat{b}_{2}) = - f_2\left(\left[\begin{array}{ccc} - w^2_{11} &w^2_{12} &w^2_{13} \\ - w^2_{21} &w^2_{22} &w^2_{23} \\ - w^2_{31} &w^2_{32} &w^2_{33} \\ - \end{array} \right] \cdot - \left[\begin{array}{c} - y^1_1 \\ - y^1_2 \\ - y^1_3 \\ - \end{array}\right] + - \left[\begin{array}{c} - b^2_1 \\ - b^2_2 \\ - b^2_3 \\ - \end{array}\right]\right). -\end{equation} -!et - - -=== Matrix-vector notation and activation === - -The activation of node $i$ in layer 2 is - -!bt -\begin{equation} - y^2_i = f_2\Bigr(w^2_{i1}y^1_1 + w^2_{i2}y^1_2 + w^2_{i3}y^1_3 + b^2_i\Bigr) = - f_2\left(\sum_{j=1}^3 w^2_{ij} y_j^1 + b^2_i\right). -\end{equation} -!et - -This is not just a convenient and compact notation, but also a useful -and intuitive way to think about MLPs: The output is calculated by a -series of matrix-vector multiplications and vector additions that are -used as input to the activation functions. For each operation -$\mathrm{W}_l \hat{y}_{l-1}$ we move forward one layer. - - - -=== Activation functions === - - -A property that characterizes a neural network, other than its -connectivity, is the choice of activation function(s). As described -in, the following restrictions are imposed on an activation function -for a FFNN to fulfill the universal approximation theorem - - * Non-constant - - * Bounded - - * Monotonically-increasing - - * Continuous - - -=== Activation functions, Logistic and Hyperbolic ones === - -The second requirement excludes all linear functions. Furthermore, in -a MLP with only linear activation functions, each layer simply -performs a linear transformation of its inputs. - -Regardless of the number of layers, the output of the NN will be -nothing but a linear function of the inputs. Thus we need to introduce -some kind of non-linearity to the NN to be able to fit non-linear -functions Typical examples are the logistic *Sigmoid* - -!bt -\[ - f(x) = \frac{1}{1 + e^{-x}}, -\] -!et -and the *hyperbolic tangent* function -!bt -\[ - f(x) = \tanh(x) -\] -!et - - -=== Relevance === - -The *sigmoid* function are more biologically plausible because the -output of inactive neurons are zero. Such activation function are -called *one-sided*. However, it has been shown that the hyperbolic -tangent performs better than the sigmoid for training MLPs. has -become the most popular for *deep neural networks* - -!bc pycod -"""The sigmoid function (or the logistic curve) is a -function that takes any real number, z, and outputs a number (0,1). -It is useful in neural networks for assigning weights on a relative scale. -The value z is the weighted sum of parameters involved in the learning algorithm.""" - -import numpy -import matplotlib.pyplot as plt -import math as mt - -z = numpy.arange(-5, 5, .1) -sigma_fn = numpy.vectorize(lambda z: 1/(1+numpy.exp(-z))) -sigma = sigma_fn(z) - -fig = plt.figure() -ax = fig.add_subplot(111) -ax.plot(z, sigma) -ax.set_ylim([-0.1, 1.1]) -ax.set_xlim([-5,5]) -ax.grid(True) -ax.set_xlabel('z') -ax.set_title('sigmoid function') - -plt.show() - -"""Step Function""" -z = numpy.arange(-5, 5, .02) -step_fn = numpy.vectorize(lambda z: 1.0 if z >= 0.0 else 0.0) -step = step_fn(z) - -fig = plt.figure() -ax = fig.add_subplot(111) -ax.plot(z, step) -ax.set_ylim([-0.5, 1.5]) -ax.set_xlim([-5,5]) -ax.grid(True) -ax.set_xlabel('z') -ax.set_title('step function') - -plt.show() - -"""Sine Function""" -z = numpy.arange(-2*mt.pi, 2*mt.pi, 0.1) -t = numpy.sin(z) - -fig = plt.figure() -ax = fig.add_subplot(111) -ax.plot(z, t) -ax.set_ylim([-1.0, 1.0]) -ax.set_xlim([-2*mt.pi,2*mt.pi]) -ax.grid(True) -ax.set_xlabel('z') -ax.set_title('sine function') - -plt.show() - -"""Plots a graph of the squashing function used by a rectified linear -unit""" -z = numpy.arange(-2, 2, .1) -zero = numpy.zeros(len(z)) -y = numpy.max([zero, z], axis=0) - -fig = plt.figure() -ax = fig.add_subplot(111) -ax.plot(z, y) -ax.set_ylim([-2.0, 2.0]) -ax.set_xlim([-2.0, 2.0]) -ax.grid(True) -ax.set_xlabel('z') -ax.set_title('Rectified linear unit') - -plt.show() -!ec - - - -===== The multilayer perceptron (MLP) ===== - -The multilayer perceptron is a very popular, and easy to implement approach, to deep learning. It consists of -o A neural network with one or more layers of nodes between the input and the output nodes. -o The multilayer network structure, or architecture, or topology, consists of an input layer, one or more hidden layers, and one output layer. -o The input nodes pass values to the first hidden layer, its nodes pass the information on to the second and so on till we reach the output layer. - -As a convention it is normal to call a network with one layer of input units, one layer of hidden -units and one layer of output units as a two-layer network. A network with two layers of hidden units is called a three-layer network etc etc. - -For an MLP network there is no direct connection between the output nodes/neurons/units and the input nodes/neurons/units. -Hereafter we will call the various entities of a layer for nodes. -There are also no connections within a single layer. - -The number of input nodes does not need to equal the number of output -nodes. This applies also to the hidden layers. Each layer may have its -own number of nodes and activation functions. - -The hidden layers have their name from the fact that they are not -linked to observables and as we will see below when we define the -so-called activation $\hat{z}$, we can think of this as a basis -expansion of the original inputs $\hat{x}$. The difference however -between neural networks and say linear regression is that now these -basis functions (which will correspond to the weights in the network) -are learned from data. This results in an important difference between -neural networks and deep learning approaches on one side and methods -like logistic regression or linear regression and their modifications on the other side. - - - -===== From one to many layers, the universal approximation theorem ===== - - -A neural network with only one layer, what we called the simple -perceptron, is best suited if we have a standard binary model with -clear (linear) boundaries between the outcomes. As such it could -equally well be replaced by standard linear regression or logistic -regression. Networks with one or more hidden layers approximate -systems with more complex boundaries. - -As stated earlier, -an important theorem in studies of neural networks, restated without -proof here, is the "universal approximation -theorem":"http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.441.7873&rep=rep1&type=pdf". - -It states that a feed-forward network with a single hidden layer -containing a finite number of neurons can approximate continuous -functions on compact subsets of real functions. The theorem thus -states that simple neural networks can represent a wide variety of -interesting functions when given appropriate parameters. It is the -multilayer feedforward architecture itself which gives neural networks -the potential of being universal approximators. - - - -===== Deriving the back propagation code for a multilayer perceptron model ===== - - -_Note: figures will be inserted later!_ - -As we have seen now in a feed forward network, we can express the final output of our network in terms of basic matrix-vector multiplications. -The unknowwn quantities are our weights $w_{ij}$ and we need to find an algorithm for changing them so that our errors are as small as possible. -This leads us to the famous "back propagation algorithm":"https://www.nature.com/articles/323533a0". - -The questions we want to ask are how do changes in the biases and the -weights in our network change the cost function and how can we use the -final output to modify the weights? - -To derive these equations let us start with a plain regression problem -and define our cost function as - -!bt -\[ -{\cal C}(\hat{W}) = \frac{1}{2}\sum_{i=1}^n\left(y_i - t_i\right)^2, -\] -!et - -where the $t_i$s are our $n$ targets (the values we want to -reproduce), while the outputs of the network after having propagated -all inputs $\hat{x}$ are given by $y_i$. Below we will demonstrate -how the basic equations arising from the back propagation algorithm -can be modified in order to study classification problems with $K$ -classes. - - -===== Definitions ===== - -With our definition of the targets $\hat{t}$, the outputs of the -network $\hat{y}$ and the inputs $\hat{x}$ we -define now the activation $z_j^l$ of node/neuron/unit $j$ of the -$l$-th layer as a function of the bias, the weights which add up from -the previous layer $l-1$ and the forward passes/outputs -$\hat{a}^{l-1}$ from the previous layer as - - -!bt -\[ -z_j^l = \sum_{i=1}^{M_{l-1}}w_{ij}^la_i^{l-1}+b_j^l, -\] -!et - -where $b_k^l$ are the biases from layer $l$. Here $M_{l-1}$ -represents the total number of nodes/neurons/units of layer $l-1$. The -figure here illustrates this equation. We can rewrite this in a more -compact form as the matrix-vector products we discussed earlier, - -!bt -\[ -\hat{z}^l = \left(\hat{W}^l\right)^T\hat{a}^{l-1}+\hat{b}^l. -\] -!et - -With the activation values $\hat{z}^l$ we can in turn define the -output of layer $l$ as $\hat{a}^l = f(\hat{z}^l)$ where $f$ is our -activation function. In the examples here we will use the sigmoid -function discussed in our logistic regression lectures. We will also use the same activation function $f$ for all layers -and their nodes. It means we have - -!bt -\[ -a_j^l = f(z_j^l) = \frac{1}{1+\exp{-(z_j^l)}}. -\] -!et - - - -===== Derivatives and the chain rule ===== - -From the definition of the activation $z_j^l$ we have -!bt -\[ -\frac{\partial z_j^l}{\partial w_{ij}^l} = a_i^{l-1}, -\] -!et -and -!bt -\[ -\frac{\partial z_j^l}{\partial a_i^{l-1}} = w_{ji}^l. -\] -!et - -With our definition of the activation function we have that (note that this function depends only on $z_j^l$) -!bt -\[ -\frac{\partial a_j^l}{\partial z_j^{l}} = a_j^l(1-a_j^l)=f(z_j^l)(1-f(z_j^l)). -\] -!et - - - -===== Derivative of the cost function ===== - -With these definitions we can now compute the derivative of the cost function in terms of the weights. - -Let us specialize to the output layer $l=L$. Our cost function is -!bt -\[ -{\cal C}(\hat{W^L}) = \frac{1}{2}\sum_{i=1}^n\left(y_i - t_i\right)^2=\frac{1}{2}\sum_{i=1}^n\left(a_i^L - t_i\right)^2, -\] -!et -The derivative of this function with respect to the weights is - -!bt -\[ -\frac{\partial{\cal C}(\hat{W^L})}{\partial w_{jk}^L} = \left(a_j^L - t_j\right)\frac{\partial a_j^L}{\partial w_{jk}^{L}}, -\] -!et -The last partial derivative can easily be computed and reads (by applying the chain rule) -!bt -\[ -\frac{\partial a_j^L}{\partial w_{jk}^{L}} = \frac{\partial a_j^L}{\partial z_{j}^{L}}\frac{\partial z_j^L}{\partial w_{jk}^{L}}=a_j^L(1-a_j^L)a_k^{L-1}, -\] -!et - - - - -===== Bringing it together, first back propagation equation ===== - -We have thus -!bt -\[ -\frac{\partial{\cal C}(\hat{W^L})}{\partial w_{jk}^L} = \left(a_j^L - t_j\right)a_j^L(1-a_j^L)a_k^{L-1}, -\] -!et - -Defining -!bt -\[ -\delta_j^L = a_j^L(1-a_j^L)\left(a_j^L - t_j\right) = f'(z_j^L)\frac{\partial {\cal C}}{\partial (a_j^L)}, -\] -!et -and using the Hadamard product of two vectors we can write this as -!bt -\[ -\hat{\delta}^L = f'(\hat{z}^L)\circ\frac{\partial {\cal C}}{\partial (\hat{a}L)}. -\] -!et - -This is an important expression. The second term on the right handside -measures how fast the cost function is changing as a function of the $j$th -output activation. If, for example, the cost function doesn't depend -much on a particular output node $j$, then $\delta_j^L$ will be small, -which is what we would expect. The first term on the right, measures -how fast the activation function $f$ is changing at a given activation -value $z_j^L$. - -Notice that everything in the above equations is easily computed. In -particular, we compute $z_j^L$ while computing the behaviour of the -network, and it is only a small additional overhead to compute -$f'(z^L_j)$. The exact form of the derivative with respect to the -output depends on the form of the cost function. -However, provided the cost function is known there should be little -trouble in calculating - -!bt -\[ -\frac{\partial {\cal C}}{\partial (a_j^L)} -\] -!et - -With the definition of $\delta_j^L$ we have a more compact definition of the derivative of the cost function in terms of the weights, namely -!bt -\[ -\frac{\partial{\cal C}(\hat{W^L})}{\partial w_{jk}^L} = \delta_j^La_k^{L-1}. -\] -!et - - -===== Derivatives in terms of $z_j^L$ ===== - -It is also easy to see that our previous equation can be written as - -!bt -\[ -\delta_j^L =\frac{\partial {\cal C}}{\partial z_j^L}= \frac{\partial {\cal C}}{\partial a_j^L}\frac{\partial a_j^L}{\partial z_j^L}, -\] -!et -which can also be interpreted as the partial derivative of the cost function with respect to the biases $b_j^L$, namely -!bt -\[ -\delta_j^L = \frac{\partial {\cal C}}{\partial b_j^L}\frac{\partial b_j^L}{\partial z_j^L}=\frac{\partial {\cal C}}{\partial b_j^L}, -\] -!et -That is, the error $\delta_j^L$ is exactly equal to the rate of change of the cost function as a function of the bias. - -===== Bringing it together ===== - -We have now three equations that are essential for the computations of the derivatives of the cost function at the output layer. These equations are needed to start the algorithm and they are - -!bblock The starting equations - -!bt -\begin{equation} -\frac{\partial{\cal C}(\hat{W^L})}{\partial w_{jk}^L} = \delta_j^La_k^{L-1}, -\end{equation} -!et -and -!bt -\begin{equation} -\delta_j^L = f'(z_j^L)\frac{\partial {\cal C}}{\partial (a_j^L)}, -\end{equation} -!et -and - -!bt -\begin{equation} -\delta_j^L = \frac{\partial {\cal C}}{\partial b_j^L}, -\end{equation} -!et -!eblock - - -An interesting consequence of the above equations is that when the -activation $a_k^{L-1}$ is small, the gradient term, that is the -derivative of the cost function with respect to the weights, will also -tend to be small. We say then that the weight learns slowly, meaning -that it changes slowly when we minimize the weights via say gradient -descent. In this case we say the system learns slowly. - -Another interesting feature is that is when the activation function, -represented by the sigmoid function here, is rather flat when we move towards -its end values $0$ and $1$ (see the above Python codes). In these -cases, the derivatives of the activation function will also be close -to zero, meaning again that the gradients will be small and the -network learns slowly again. - - - -We need a fourth equation and we are set. We are going to propagate -backwards in order to the determine the weights and biases. In order -to do so we need to represent the error in the layer before the final -one $L-1$ in terms of the errors in the final output layer. - - -===== Final back propagating equation ===== - -We have that (replacing $L$ with a general layer $l$) -!bt -\[ -\delta_j^l =\frac{\partial {\cal C}}{\partial z_j^l}. -\] -!et -We want to express this in terms of the equations for layer $l+1$. Using the chain rule and summing over all $k$ entries we have - -!bt -\[ -\delta_j^l =\sum_k \frac{\partial {\cal C}}{\partial z_k^{l+1}}\frac{\partial z_k^{l+1}}{\partial z_j^{l}}=\sum_k \delta_k^{l+1}\frac{\partial z_k^{l+1}}{\partial z_j^{l}}, -\] -!et -and recalling that -!bt -\[ -z_j^{l+1} = \sum_{i=1}^{M_{l}}w_{ij}^{l+1}a_j^{l}+b_j^{l+1}, -\] -!et -with $M_l$ being the number of nodes in layer $l$, we obtain -!bt -\[ -\delta_j^l =\sum_k \delta_k^{l+1}w_{kj}^{l+1}f'(z_j^l), -\] -!et -This is our final equation. - -We are now ready to set up the algorithm for back propagation and learning the weights and biases. - - -===== Setting up the Back propagation algorithm ===== - - - -The four equations provide us with a way of computing the gradient of the cost function. Let us write this out in the form of an algorithm. - -!bblock -First, we set up the input data $\hat{x}$ and the activations -$\hat{z}_1$ of the input layer and compute the activation function and -the pertinent outputs $\hat{a}^1$. -!eblock - -!bblock -Secondly, we perform then the feed forward till we reach the output -layer and compute all $\hat{z}_l$ of the input layer and compute the -activation function and the pertinent outputs $\hat{a}^l$ for -$l=2,3,\dots,L$. -!eblock - -!bblock -Thereafter we compute the ouput error $\hat{\delta}^L$ by computing all -!bt -\[ -\delta_j^L = f'(z_j^L)\frac{\partial {\cal C}}{\partial (a_j^L)}. -\] -!et -!eblock - -!bblock -Then we compute the back propagate error for each $l=L-1,L-2,\dots,2$ as -!bt -\[ -\delta_j^l = \sum_k \delta_k^{l+1}w_{kj}^{l+1}f'(z_j^l). -\] -!et -!eblock - -!bblock -Finally, we update the weights and the biases using gradient descent for each $l=L-1,L-2,\dots,2$ and update the weights and biases according to the rules -!bt -\[ -w_{jk}^l\leftarrow = w_{jk}^l- \eta \delta_j^la_k^{l-1}, -\] -!et - -!bt -\[ -b_j^l \leftarrow b_j^l-\eta \frac{\partial {\cal C}}{\partial b_j^l}=b_j^l-\eta \delta_j^l, -\] -!et -!eblock - -The parameter $\eta$ is the learning parameter discussed in connection with the gradient descent methods. -Here it is convenient to use stochastic gradient descent (see the examples below) with mini-batches with an outer loop that steps through multiple epochs of training. - - - -===== Setting up a Multi-layer perceptron model for classification ===== - -We are now gong to develop an example based on the MNIST data -base. This is a classification problem and we need to use our -cross-entropy function we discussed in connection with logistic -regression. The cross-entropy defines our cost function for the -classificaton problems with neural networks. - -In binary classification with two classes $(0, 1)$ we define the -logistic/sigmoid function as the probability that a particular input -is in class $0$ or $1$. This is possible because the logistic -function takes any input from the real numbers and inputs a number -between 0 and 1, and can therefore be interpreted as a probability. It -also has other nice properties, such as a derivative that is simple to -calculate. - -For an input $\boldsymbol{a}$ from the hidden layer, the probability that the input $\boldsymbol{x}$ -is in class 0 or 1 is just. We let $\theta$ represent the unknown weights and biases to be adjusted by our equations). The variable $x$ -represents our activation values $z$. We have -!bt -\[ -P(y = 0 \mid \hat{x}, \hat{\theta}) = \frac{1}{1 + \exp{(- \hat{x}})} , -\] -!et -and -!bt -\[ -P(y = 1 \mid \hat{x}, \hat{\theta}) = 1 - P(y = 0 \mid \hat{x}, \hat{\theta}) , -\] -!et - -where $y \in \{0, 1\}$ and $\hat{\theta}$ represents the weights and biases -of our network. - - - -===== Defining the cost function ===== - -Our cost function is given as (see the Logistic regression lectures) -!bt -\[ -\mathcal{C}(\hat{\theta}) = - \ln P(\mathcal{D} \mid \hat{\theta}) = - \sum_{i=1}^n -y_i \ln[P(y_i = 0)] + (1 - y_i) \ln [1 - P(y_i = 0)] = \sum_{i=1}^n \mathcal{L}_i(\hat{\theta}) . -\] -!et - -This last equality means that we can interpret our *cost* function as a sum over the *loss* function -for each point in the dataset $\mathcal{L}_i(\hat{\theta})$. -The negative sign is just so that we can think about our algorithm as minimizing a positive number, rather -than maximizing a negative number. - -In *multiclass* classification it is common to treat each integer label as a so called *one-hot* vector: - -$y = 5 \quad \rightarrow \quad \hat{y} = (0, 0, 0, 0, 0, 1, 0, 0, 0, 0) ,$ and - - -$y = 1 \quad \rightarrow \quad \hat{y} = (0, 1, 0, 0, 0, 0, 0, 0, 0, 0) ,$ - - -i.e. a binary bit string of length $C$, where $C = 10$ is the number of classes in the MNIST dataset (numbers from $0$ to $9$).. - -If $\hat{x}_i$ is the $i$-th input (image), $y_{ic}$ refers to the $c$-th component of the $i$-th -output vector $\hat{y}_i$. -The probability of $\hat{x}_i$ being in class $c$ will be given by the softmax function: - -!bt -\[ -P(y_{ic} = 1 \mid \hat{x}_i, \hat{\theta}) = \frac{\exp{((\hat{a}_i^{hidden})^T \hat{w}_c)}} -{\sum_{c'=0}^{C-1} \exp{((\hat{a}_i^{hidden})^T \hat{w}_{c'})}} , -\] -!et - -which reduces to the logistic function in the binary case. -The likelihood of this $C$-class classifier -is now given as: - -!bt -\[ -P(\mathcal{D} \mid \hat{\theta}) = \prod_{i=1}^n \prod_{c=0}^{C-1} [P(y_{ic} = 1)]^{y_{ic}} . -\] -!et -Again we take the negative log-likelihood to define our cost function: - -!bt -\[ -\mathcal{C}(\hat{\theta}) = - \log{P(\mathcal{D} \mid \hat{\theta})}. -\] -!et -See the logistic regression lectures for a full definition of the cost function. - -The back propagation equations need now only a small change, namely the definition of a new cost function. We are thus ready to use the same equations as before! - - -===== Example: binary classification problem ===== - -As an example of the above, relevant for project 2 as well, let us consider a binary class. As discussed in our logistic regression lectures, we defined a cost function in terms of the parameters $\beta$ as -!bt -\[ -\mathcal{C}(\hat{\beta}) = - \sum_{i=1}^n \left(y_i\log{p(y_i \vert x_i,\hat{\beta})}+(i-y_i)\log{1-p(y_i \vert x_i,\hat{\beta})}\right), -\] -!et -where we had defined the logistic (sigmoid) function -!bt -\[ -p(y_i =1\vert x_i,\hat{\beta})=\frac{\exp{(\beta_0+\beta_1 x_i)}}{1+\exp{(\beta_0+\beta_1 x_i)}}, -\] -!et -and -!bt -\[ -p(y_i =0\vert x_i,\hat{\beta})=1-p(y_i =1\vert x_i,\hat{\beta}). -\] -!et -The parameters $\hat{\beta}$ were defined using a minimization method like gradient descent or Newton-Raphson's method. - -Now we replace $x_i$ with the activation $z_i^l$ for a given layer $l$ and the outputs as $y_i=a_i^l=f(z_i^l)$, with $z_i^l$ now being a function of the weights $w_{ij}^l$ and biases $b_i^l$. -We have then -!bt -\[ -a_i^l = y_i = \frac{\exp{(z_i^l)}}{1+\exp{(z_i^l)}}, -\] -!et -with -!bt -\[ -z_i^l = \sum_{j}w_{ij}^l a_j^{l-1}+b_i^l, -\] -!et -where the superscript $l-1$ indicates that these are the outputs from layer $l-1$. -Our cost function at the final layer $l=L$ is now -!bt -\[ -\mathcal{C}(\hat{W}) = - \sum_{i=1}^n \left(t_i\log{a_i^L}+(i-t_i)\log{(1-a_i^L)}\right), -\] -!et -where we have defined the targets $t_i$. The derivatives of the cost function with respect to the output $a_i^L$ are then easily calculated and we get -!bt -\[ -\frac{\partial \mathcal{C}(\hat{W})}{\partial a_i^L} = \frac{a_i^L-t_i}{a_i^L(1-a_i^L)}. -\] -!et -In case we use another activation function than the logistic one, we need to evaluate other derivatives. - - - -===== The Softmax function ===== -In case we employ the more general case given by the Softmax equation, we need to evaluate the derivative of the activation function with respect to the activation $z_i^l$, that is we need -!bt -\[ -\frac{\partial f(z_i^l)}{\partial w_{jk}^l} = -\frac{\partial f(z_i^l)}{\partial z_j^l} \frac{\partial z_j^l}{\partial w_{jk}^l}= \frac{\partial f(z_i^l)}{\partial z_j^l}a_k^{l-1}. -\] -!et -For the Softmax function we have -!bt -\[ -f(z_i^l) = \frac{\exp{(z_i^l)}}{\sum_{m=1}^K\exp{(z_m^l)}}. -\] -!et -Its derivative with respect to $z_j^l$ gives -!bt -\[ -\frac{\partial f(z_i^l)}{\partial z_j^l}= f(z_i^l)\left(\delta_{ij}-f(z_j^l)\right), -\] -!et -which in case of the simply binary model reduces to having $i=j$. - - -===== Developing a code for doing neural networks with back propagation ===== - - -One can identify a set of key steps when using neural networks to solve supervised learning problems: - -o Collect and pre-process data -o Define model and architecture -o Choose cost function and optimizer -o Train the model -o Evaluate model performance on test data -o Adjust hyperparameters (if necessary, network architecture) - - -===== Collect and pre-process data ===== - -Here we will be using the MNIST dataset, which is readily available through the _scikit-learn_ -package. You may also find it for example "here":"http://yann.lecun.com/exdb/mnist/". -The *MNIST* (Modified National Institute of Standards and Technology) database is a large database -of handwritten digits that is commonly used for training various image processing systems. -The MNIST dataset consists of 70 000 images of size 28x28 pixels, each labeled from 0 to 9. -The scikit-learn dataset we will use consists of a selection of 1797 images of size $8\times 8$ collected and processed from this database. - -To feed data into a feed-forward neural network we need to represent -the inputs as a feature matrix $X = (n_{inputs}, n_{features})$. Each -row represents an *input*, in this case a handwritten digit, and -each column represents a *feature*, in this case a pixel. The -correct answers, also known as *labels* or *targets* are -represented as a 1D array of integers -$Y = (n_{inputs}) = (5, 3, 1, 8,...)$. - -As an example, say we want to build a neural network using supervised learning to predict Body-Mass Index (BMI) from -measurements of height (in m) -and weight (in kg). If we have measurements of 5 people the feature matrix could be for example: - -$$ X = \begin{bmatrix} -1.85 & 81\\ -1.71 & 65\\ -1.95 & 103\\ -1.55 & 42\\ -1.63 & 56 -\end{bmatrix} ,$$ - -and the targets would be: - -$$ Y = (23.7, 22.2, 27.1, 17.5, 21.1) $$ - -Since each input image is a 2D matrix, we need to flatten the image -(i.e. "unravel" the 2D matrix into a 1D array) to turn the data into a -feature matrix. This means we lose all spatial information in the -image, such as locality and translational invariance. More complicated -architectures such as Convolutional Neural Networks can take advantage -of such information, and are most commonly applied when analyzing -images. - - -!bc pycod -# import necessary packages -import numpy as np -import matplotlib.pyplot as plt -from sklearn import datasets - - -# ensure the same random numbers appear every time -np.random.seed(0) - -# display images in notebook -%matplotlib inline -plt.rcParams['figure.figsize'] = (12,12) - - -# download MNIST dataset -digits = datasets.load_digits() - -# define inputs and labels -inputs = digits.images -labels = digits.target - -print("inputs = (n_inputs, pixel_width, pixel_height) = " + str(inputs.shape)) -print("labels = (n_inputs) = " + str(labels.shape)) - - -# flatten the image -# the value -1 means dimension is inferred from the remaining dimensions: 8x8 = 64 -n_inputs = len(inputs) -inputs = inputs.reshape(n_inputs, -1) -print("X = (n_inputs, n_features) = " + str(inputs.shape)) - - -# choose some random images to display -indices = np.arange(n_inputs) -random_indices = np.random.choice(indices, size=5) - -for i, image in enumerate(digits.images[random_indices]): - plt.subplot(1, 5, i+1) - plt.axis('off') - plt.imshow(image, cmap=plt.cm.gray_r, interpolation='nearest') - plt.title("Label: %d" % digits.target[random_indices[i]]) -plt.show() -!ec - - -===== Train and test datasets ===== - -Performing analysis before partitioning the dataset is a major error, that can lead to incorrect conclusions. - -We will reserve $80 \%$ of our dataset for training and $20 \%$ for testing. - -It is important that the train and test datasets are drawn randomly from our dataset, to ensure -no bias in the sampling. -Say you are taking measurements of weather data to predict the weather in the coming 5 days. -You don't want to train your model on measurements taken from the hours 00.00 to 12.00, and then test it on data -collected from 12.00 to 24.00. - - -!bc pycod -from sklearn.model_selection import train_test_split - -# one-liner from scikit-learn library -train_size = 0.8 -test_size = 1 - train_size -X_train, X_test, Y_train, Y_test = train_test_split(inputs, labels, train_size=train_size, - test_size=test_size) - -# equivalently in numpy -def train_test_split_numpy(inputs, labels, train_size, test_size): - n_inputs = len(inputs) - inputs_shuffled = inputs.copy() - labels_shuffled = labels.copy() - - np.random.shuffle(inputs_shuffled) - np.random.shuffle(labels_shuffled) - - train_end = int(n_inputs*train_size) - X_train, X_test = inputs_shuffled[:train_end], inputs_shuffled[train_end:] - Y_train, Y_test = labels_shuffled[:train_end], labels_shuffled[train_end:] - - return X_train, X_test, Y_train, Y_test - -#X_train, X_test, Y_train, Y_test = train_test_split_numpy(inputs, labels, train_size, test_size) - -print("Number of training images: " + str(len(X_train))) -print("Number of test images: " + str(len(X_test))) -!ec - - -===== Define model and architecture ===== - -Our simple feed-forward neural network will consist of an *input* layer, a single *hidden* layer and an *output* layer. The activation $y$ of each neuron is a weighted sum of inputs, passed through an activation function. In case of the simple perceptron model we have - -$$ z = \sum_{i=1}^n w_i a_i ,$$ - -$$ y = f(z) ,$$ - -where $f$ is the activation function, $a_i$ represents input from neuron $i$ in the preceding layer -and $w_i$ is the weight to input $i$. -The activation of the neurons in the input layer is just the features (e.g. a pixel value). - -The simplest activation function for a neuron is the *Heaviside* function: - -$$ f(z) = -\begin{cases} -1, & z > 0\\ -0, & \text{otherwise} -\end{cases} -$$ - -A feed-forward neural network with this activation is known as a *perceptron*. -For a binary classifier (i.e. two classes, 0 or 1, dog or not-dog) we can also use this in our output layer. -This activation can be generalized to $k$ classes (using e.g. the *one-against-all* strategy), -and we call these architectures *multiclass perceptrons*. - -However, it is now common to use the terms Single Layer Perceptron (SLP) (1 hidden layer) and -Multilayer Perceptron (MLP) (2 or more hidden layers) to refer to feed-forward neural networks with any activation function. - -Typical choices for activation functions include the sigmoid function, hyperbolic tangent, and Rectified Linear Unit (ReLU). -We will be using the sigmoid function $\sigma(x)$: - -$$ f(x) = \sigma(x) = \frac{1}{1 + e^{-x}} ,$$ - -which is inspired by probability theory (see logistic regression) and was most commonly used until about 2011. See the discussion below concerning other activation functions. - - -===== Layers ===== - -* Input -Since each input image has 8x8 = 64 pixels or features, we have an input layer of 64 neurons. - -* Hidden layer -We will use 50 neurons in the hidden layer receiving input from the neurons in the input layer. -Since each neuron in the hidden layer is connected to the 64 inputs we have 64x50 = 3200 weights to the hidden layer. - -* Output -If we were building a binary classifier, it would be sufficient with a single neuron in the output layer, -which could output 0 or 1 according to the Heaviside function. This would be an example of a *hard* classifier, meaning it outputs the class of the input directly. However, if we are dealing with noisy data it is often beneficial to use a *soft* classifier, which outputs the probability of being in class 0 or 1. - -For a soft binary classifier, we could use a single neuron and interpret the output as either being the probability of being in class 0 or the probability of being in class 1. Alternatively we could use 2 neurons, and interpret each neuron as the probability of being in each class. - -Since we are doing multiclass classification, with 10 categories, it is natural to use 10 neurons in the output layer. We number the neurons $j = 0,1,...,9$. The activation of each output neuron $j$ will be according to the *softmax* function: - -$$ P(\text{class $j$} \mid \text{input $\hat{a}$}) = \frac{\exp{(\hat{a}^T \hat{w}_j)}} -{\sum_{c=0}^{9} \exp{(\hat{a}^T \hat{w}_c)}} ,$$ - -i.e. each neuron $j$ outputs the probability of being in class $j$ given an input from the hidden layer $\hat{a}$, with $\hat{w}_j$ the weights of neuron $j$ to the inputs. -The denominator is a normalization factor to ensure the outputs (probabilities) sum up to 1. -The exponent is just the weighted sum of inputs as before: - -$$ z_j = \sum_{i=1}^n w_ {ij} a_i+b_j.$$ - -Since each neuron in the output layer is connected to the 50 inputs from the hidden layer we have 50x10 = 500 -weights to the output layer. - - -===== Weights and biases ===== - -Typically weights are initialized with small values distributed around zero, drawn from a uniform -or normal distribution. Setting all weights to zero means all neurons give the same output, making the network useless. - -Adding a bias value to the weighted sum of inputs allows the neural network to represent a greater range -of values. Without it, any input with the value 0 will be mapped to zero (before being passed through the activation). The bias unit has an output of 1, and a weight to each neuron $j$, $b_j$: - -$$ z_j = \sum_{i=1}^n w_ {ij} a_i + b_j.$$ - -The bias weights $\hat{b}$ are often initialized to zero, but a small value like $0.01$ ensures all neurons have some output which can be backpropagated in the first training cycle. -!bc pycod -# building our neural network - -n_inputs, n_features = X_train.shape -n_hidden_neurons = 50 -n_categories = 10 - -# we make the weights normally distributed using numpy.random.randn - -# weights and bias in the hidden layer -hidden_weights = np.random.randn(n_features, n_hidden_neurons) -hidden_bias = np.zeros(n_hidden_neurons) + 0.01 - -# weights and bias in the output layer -output_weights = np.random.randn(n_hidden_neurons, n_categories) -output_bias = np.zeros(n_categories) + 0.01 -!ec - - -===== Feed-forward pass ===== - -Denote $F$ the number of features, $H$ the number of hidden neurons and $C$ the number of categories. -For each input image we calculate a weighted sum of input features (pixel values) to each neuron $j$ in the hidden layer $l$: - -$$ z_{j}^{l} = \sum_{i=1}^{F} w_{ij}^{l} x_i + b_{j}^{l},$$ - -this is then passed through our activation function - -$$ a_{j}^{l} = f(z_{j}^{l}) .$$ - -We calculate a weighted sum of inputs (activations in the hidden layer) to each neuron $j$ in the output layer: - -$$ z_{j}^{L} = \sum_{i=1}^{H} w_{ij}^{L} a_{i}^{l} + b_{j}^{L}.$$ - -Finally we calculate the output of neuron $j$ in the output layer using the softmax function: - -$$ a_{j}^{L} = \frac{\exp{(z_j^{L})}} -{\sum_{c=0}^{C-1} \exp{(z_c^{L})}} .$$ - - -===== Matrix multiplications ===== - -Since our data has the dimensions $X = (n_{inputs}, n_{features})$ and our weights to the hidden -layer have the dimensions -$W_{hidden} = (n_{features}, n_{hidden})$, -we can easily feed the network all our training data in one go by taking the matrix product - -$$ X W^{h} = (n_{inputs}, n_{hidden}),$$ - -and obtain a matrix that holds the weighted sum of inputs to the hidden layer -for each input image and each hidden neuron. -We also add the bias to obtain a matrix of weighted sums to the hidden layer $Z^{h}$: - -$$ \hat{z}^{l} = \hat{X} \hat{W}^{l} + \hat{b}^{l} ,$$ - -meaning the same bias (1D array with size equal number of hidden neurons) is added to each input image. -This is then passed through the activation: - -$$ \hat{a}^{l} = f(\hat{z}^l) .$$ - -This is fed to the output layer: - -$$ \hat{z}^{L} = \hat{a}^{L} \hat{W}^{L} + \hat{b}^{L} .$$ - -Finally we receive our output values for each image and each category by passing it through the softmax function: - -$$ output = softmax (\hat{z}^{L}) = (n_{inputs}, n_{categories}) .$$ - - -!bc pycod -# setup the feed-forward pass, subscript h = hidden layer - -def sigmoid(x): - return 1/(1 + np.exp(-x)) - -def feed_forward(X): - # weighted sum of inputs to the hidden layer - z_h = np.matmul(X, hidden_weights) + hidden_bias - # activation in the hidden layer - a_h = sigmoid(z_h) - - # weighted sum of inputs to the output layer - z_o = np.matmul(a_h, output_weights) + output_bias - # softmax output - # axis 0 holds each input and axis 1 the probabilities of each category - exp_term = np.exp(z_o) - probabilities = exp_term / np.sum(exp_term, axis=1, keepdims=True) - - return probabilities - -probabilities = feed_forward(X_train) -print("probabilities = (n_inputs, n_categories) = " + str(probabilities.shape)) -print("probability that image 0 is in category 0,1,2,...,9 = \n" + str(probabilities[0])) -print("probabilities sum up to: " + str(probabilities[0].sum())) -print() - -# we obtain a prediction by taking the class with the highest likelihood -def predict(X): - probabilities = feed_forward(X) - return np.argmax(probabilities, axis=1) - -predictions = predict(X_train) -print("predictions = (n_inputs) = " + str(predictions.shape)) -print("prediction for image 0: " + str(predictions[0])) -print("correct label for image 0: " + str(Y_train[0])) -!ec - - -===== Choose cost function and optimizer ===== - -To measure how well our neural network is doing we need to introduce a cost function. -We will call the function that gives the error of a single sample output the *loss* function, and the function -that gives the total error of our network across all samples the *cost* function. -A typical choice for multiclass classification is the *cross-entropy* loss, also known as the negative log likelihood. - -In *multiclass* classification it is common to treat each integer label as a so called *one-hot* vector: - -$$ y = 5 \quad \rightarrow \quad \hat{y} = (0, 0, 0, 0, 0, 1, 0, 0, 0, 0) ,$$ - - -$$ y = 1 \quad \rightarrow \quad \hat{y} = (0, 1, 0, 0, 0, 0, 0, 0, 0, 0) ,$$ - - -i.e. a binary bit string of length $C$, where $C = 10$ is the number of classes in the MNIST dataset. - -Let $y_{ic}$ denote the $c$-th component of the $i$-th one-hot vector. -We define the cost function $\mathcal{C}$ as a sum over the cross-entropy loss for each point $\hat{x}_i$ in the dataset. - -In the one-hot representation only one of the terms in the loss function is non-zero, namely the -probability of the correct category $c'$ -(i.e. the category $c'$ such that $y_{ic'} = 1$). This means that the cross entropy loss only punishes you for how wrong -you got the correct label. The probability of category $c$ is given by the softmax function. The vector $\hat{\theta}$ represents the parameters of our network, i.e. all the weights and biases. - - - -===== Optimizing the cost function ===== - -The network is trained by finding the weights and biases that minimize the cost function. One of the most widely used classes of methods is *gradient descent* and its generalizations. The idea behind gradient descent -is simply to adjust the weights in the direction where the gradient of the cost function is large and negative. This ensures we flow toward a *local* minimum of the cost function. -Each parameter $\theta$ is iteratively adjusted according to the rule - -$$ \theta_{i+1} = \theta_i - \eta \nabla \mathcal{C}(\theta_i) ,$$ - -where $\eta$ is known as the *learning rate*, which controls how big a step we take towards the minimum. -This update can be repeated for any number of iterations, or until we are satisfied with the result. - -A simple and effective improvement is a variant called *Batch Gradient Descent*. -Instead of calculating the gradient on the whole dataset, we calculate an approximation of the gradient -on a subset of the data called a *minibatch*. -If there are $N$ data points and we have a minibatch size of $M$, the total number of batches -is $N/M$. -We denote each minibatch $B_k$, with $k = 1, 2,...,N/M$. The gradient then becomes: - -$$ \nabla \mathcal{C}(\theta) = \frac{1}{N} \sum_{i=1}^N \nabla \mathcal{L}_i(\theta) \quad \rightarrow \quad -\frac{1}{M} \sum_{i \in B_k} \nabla \mathcal{L}_i(\theta) ,$$ - -i.e. instead of averaging the loss over the entire dataset, we average over a minibatch. - -This has two important benefits: -o Introducing stochasticity decreases the chance that the algorithm becomes stuck in a local minima. -o It significantly speeds up the calculation, since we do not have to use the entire dataset to calculate the gradient. - -The various optmization methods, with codes and algorithms, are discussed in our lectures on "Gradient descent approaches":"https://compphysics.github.io/MachineLearning/doc/pub/Splines/html/Splines-bs.html". - - -===== Regularization ===== - -It is common to add an extra term to the cost function, proportional -to the size of the weights. This is equivalent to constraining the -size of the weights, so that they do not grow out of control. -Constraining the size of the weights means that the weights cannot -grow arbitrarily large to fit the training data, and in this way -reduces *overfitting*. - -We will measure the size of the weights using the so called *L2-norm*, meaning our cost function becomes: - -$$ \nabla \mathcal{C}(\theta) = \frac{1}{N} \sum_{i=1}^N \nabla \mathcal{L}_i(\theta) \quad \rightarrow \quad -\frac{1}{N} \sum_{i=1}^N \nabla \mathcal{L}_i(\theta) + \lambda \lvert \lvert \hat{w} \rvert \rvert_2^2 -= \frac{1}{N} \sum_{i=1}^N \nabla \mathcal{L}(\theta) + \lambda \sum_{ij} w_{ij}^2,$$ - -i.e. we sum up all the weights squared. The factor $\lambda$ is known as a regularization parameter. - - -In order to train the model, we need to calculate the derivative of -the cost function with respect to every bias and weight in the -network. In total our network has $(64 + 1)\times 50=3250$ weights in -the hidden layer and $(50 + 1)\times 10=510$ weights to the output -layer ($+1$ for the bias), and the gradient must be calculated for -every parameter. We use the *backpropagation* algorithm discussed -above. This is a clever use of the chain rule that allows us to -calculate the gradient efficently. - - - -===== Matrix multiplication ===== - -To more efficently train our network these equations are implemented using matrix operations. -The error in the output layer is calculated simply as, with $\hat{t}$ being our targets, - -$$ \delta_L = \hat{t} - \hat{y} = (n_{inputs}, n_{categories}) .$$ - -The gradient for the output weights is calculated as - -$$ \nabla W_{L} = \hat{a}^T \delta_L = (n_{hidden}, n_{categories}) ,$$ - -where $\hat{a} = (n_{inputs}, n_{hidden})$. This simply means that we are summing up the gradients for each input. -Since we are going backwards we have to transpose the activation matrix. - -The gradient with respect to the output bias is then - -$$ \nabla \hat{b}_{L} = \sum_{i=1}^{n_{inputs}} \delta_L = (n_{categories}) .$$ - -The error in the hidden layer is - -$$ \Delta_h = \delta_L W_{L}^T \circ f'(z_{h}) = \delta_L W_{L}^T \circ a_{h} \circ (1 - a_{h}) = (n_{inputs}, n_{hidden}) ,$$ - -where $f'(a_{h})$ is the derivative of the activation in the hidden layer. The matrix products mean -that we are summing up the products for each neuron in the output layer. The symbol $\circ$ denotes -the *Hadamard product*, meaning element-wise multiplication. - -This again gives us the gradients in the hidden layer: - -$$ \nabla W_{h} = X^T \delta_h = (n_{features}, n_{hidden}) ,$$ - -$$ \nabla b_{h} = \sum_{i=1}^{n_{inputs}} \delta_h = (n_{hidden}) .$$ - - -!bc pycod -# to categorical turns our integer vector into a onehot representation -from sklearn.metrics import accuracy_score - -# one-hot in numpy -def to_categorical_numpy(integer_vector): - n_inputs = len(integer_vector) - n_categories = np.max(integer_vector) + 1 - onehot_vector = np.zeros((n_inputs, n_categories)) - onehot_vector[range(n_inputs), integer_vector] = 1 - - return onehot_vector - -#Y_train_onehot, Y_test_onehot = to_categorical(Y_train), to_categorical(Y_test) -Y_train_onehot, Y_test_onehot = to_categorical_numpy(Y_train), to_categorical_numpy(Y_test) - -def feed_forward_train(X): - # weighted sum of inputs to the hidden layer - z_h = np.matmul(X, hidden_weights) + hidden_bias - # activation in the hidden layer - a_h = sigmoid(z_h) - - # weighted sum of inputs to the output layer - z_o = np.matmul(a_h, output_weights) + output_bias - # softmax output - # axis 0 holds each input and axis 1 the probabilities of each category - exp_term = np.exp(z_o) - probabilities = exp_term / np.sum(exp_term, axis=1, keepdims=True) - - # for backpropagation need activations in hidden and output layers - return a_h, probabilities - -def backpropagation(X, Y): - a_h, probabilities = feed_forward_train(X) - - # error in the output layer - error_output = probabilities - Y - # error in the hidden layer - error_hidden = np.matmul(error_output, output_weights.T) * a_h * (1 - a_h) - - # gradients for the output layer - output_weights_gradient = np.matmul(a_h.T, error_output) - output_bias_gradient = np.sum(error_output, axis=0) - - # gradient for the hidden layer - hidden_weights_gradient = np.matmul(X.T, error_hidden) - hidden_bias_gradient = np.sum(error_hidden, axis=0) - - return output_weights_gradient, output_bias_gradient, hidden_weights_gradient, hidden_bias_gradient - -print("Old accuracy on training data: " + str(accuracy_score(predict(X_train), Y_train))) - -eta = 0.01 -lmbd = 0.01 -for i in range(1000): - # calculate gradients - dWo, dBo, dWh, dBh = backpropagation(X_train, Y_train_onehot) - - # regularization term gradients - dWo += lmbd * output_weights - dWh += lmbd * hidden_weights - - # update weights and biases - output_weights -= eta * dWo - output_bias -= eta * dBo - hidden_weights -= eta * dWh - hidden_bias -= eta * dBh - -print("New accuracy on training data: " + str(accuracy_score(predict(X_train), Y_train))) -!ec - - -===== Improving performance ===== - -As we can see the network does not seem to be learning at all. It seems to be just guessing the label for each image. -In order to obtain a network that does something useful, we will have to do a bit more work. - -The choice of *hyperparameters* such as learning rate and regularization parameter is hugely influential for the performance of the network. Typically a *grid-search* is performed, wherein we test different hyperparameters separated by orders of magnitude. For example we could test the learning rates $\eta = 10^{-6}, 10^{-5},...,10^{-1}$ with different regularization parameters $\lambda = 10^{-6},...,10^{-0}$. - -Next, we haven't implemented minibatching yet, which introduces stochasticity and is though to act as an important regularizer on the weights. We call a feed-forward + backward pass with a minibatch an *iteration*, and a full training period -going through the entire dataset ($n/M$ batches) an *epoch*. - -If this does not improve network performance, you may want to consider altering the network architecture, adding more neurons or hidden layers. -Andrew Ng goes through some of these considerations in this "video":"https://youtu.be/F1ka6a13S9I". You can find a summary of the video "here":"https://kevinzakka.github.io/2016/09/26/applying-deep-learning/". - - -===== Full object-oriented implementation ===== - -It is very natural to think of the network as an object, with specific instances of the network -being realizations of this object with different hyperparameters. An implementation using Python classes provides a clean structure and interface, and the full implementation of our neural network is given below. - - -!bc pycod -class NeuralNetwork: - def __init__( - self, - X_data, - Y_data, - n_hidden_neurons=50, - n_categories=10, - epochs=10, - batch_size=100, - eta=0.1, - lmbd=0.0, - - ): - self.X_data_full = X_data - self.Y_data_full = Y_data - - self.n_inputs = X_data.shape[0] - self.n_features = X_data.shape[1] - self.n_hidden_neurons = n_hidden_neurons - self.n_categories = n_categories - - self.epochs = epochs - self.batch_size = batch_size - self.iterations = self.n_inputs // self.batch_size - self.eta = eta - self.lmbd = lmbd - - self.create_biases_and_weights() - - def create_biases_and_weights(self): - self.hidden_weights = np.random.randn(self.n_features, self.n_hidden_neurons) - self.hidden_bias = np.zeros(self.n_hidden_neurons) + 0.01 - - self.output_weights = np.random.randn(self.n_hidden_neurons, self.n_categories) - self.output_bias = np.zeros(self.n_categories) + 0.01 - - def feed_forward(self): - # feed-forward for training - self.z_h = np.matmul(self.X_data, self.hidden_weights) + self.hidden_bias - self.a_h = sigmoid(self.z_h) - - self.z_o = np.matmul(self.a_h, self.output_weights) + self.output_bias - - exp_term = np.exp(self.z_o) - self.probabilities = exp_term / np.sum(exp_term, axis=1, keepdims=True) - - def feed_forward_out(self, X): - # feed-forward for output - z_h = np.matmul(X, self.hidden_weights) + self.hidden_bias - a_h = sigmoid(z_h) - - z_o = np.matmul(a_h, self.output_weights) + self.output_bias - - exp_term = np.exp(z_o) - probabilities = exp_term / np.sum(exp_term, axis=1, keepdims=True) - return probabilities - - def backpropagation(self): - error_output = self.probabilities - self.Y_data - error_hidden = np.matmul(error_output, self.output_weights.T) * self.a_h * (1 - self.a_h) - - self.output_weights_gradient = np.matmul(self.a_h.T, error_output) - self.output_bias_gradient = np.sum(error_output, axis=0) - - self.hidden_weights_gradient = np.matmul(self.X_data.T, error_hidden) - self.hidden_bias_gradient = np.sum(error_hidden, axis=0) - - if self.lmbd > 0.0: - self.output_weights_gradient += self.lmbd * self.output_weights - self.hidden_weights_gradient += self.lmbd * self.hidden_weights - - self.output_weights -= self.eta * self.output_weights_gradient - self.output_bias -= self.eta * self.output_bias_gradient - self.hidden_weights -= self.eta * self.hidden_weights_gradient - self.hidden_bias -= self.eta * self.hidden_bias_gradient - - def predict(self, X): - probabilities = self.feed_forward_out(X) - return np.argmax(probabilities, axis=1) - - def predict_probabilities(self, X): - probabilities = self.feed_forward_out(X) - return probabilities - - def train(self): - data_indices = np.arange(self.n_inputs) - - for i in range(self.epochs): - for j in range(self.iterations): - # pick datapoints with replacement - chosen_datapoints = np.random.choice( - data_indices, size=self.batch_size, replace=False - ) - - # minibatch training data - self.X_data = self.X_data_full[chosen_datapoints] - self.Y_data = self.Y_data_full[chosen_datapoints] - - self.feed_forward() - self.backpropagation() -!ec - - -===== Evaluate model performance on test data ===== - -To measure the performance of our network we evaluate how well it does it data it has never seen before, i.e. the test data. -We measure the performance of the network using the *accuracy* score. -The accuracy is as you would expect just the number of images correctly labeled divided by the total number of images. A perfect classifier will have an accuracy score of $1$. - -$$ \text{Accuracy} = \frac{\sum_{i=1}^n I(\hat{y}_i = y_i)}{n} ,$$ - -where $I$ is the indicator function, $1$ if $\hat{y}_i = y_i$ and $0$ otherwise. - - -!bc pycod -epochs = 100 -batch_size = 100 - -dnn = NeuralNetwork(X_train, Y_train_onehot, eta=eta, lmbd=lmbd, epochs=epochs, batch_size=batch_size, - n_hidden_neurons=n_hidden_neurons, n_categories=n_categories) -dnn.train() -test_predict = dnn.predict(X_test) - -# accuracy score from scikit library -print("Accuracy score on test set: ", accuracy_score(Y_test, test_predict)) - -# equivalent in numpy -def accuracy_score_numpy(Y_test, Y_pred): - return np.sum(Y_test == Y_pred) / len(Y_test) - -#print("Accuracy score on test set: ", accuracy_score_numpy(Y_test, test_predict)) -!ec - - -===== Adjust hyperparameters ===== - -We now perform a grid search to find the optimal hyperparameters for the network. -Note that we are only using 1 layer with 50 neurons, and human performance is estimated to be around $98\%$ ($2\%$ error rate). - -!bc pycod -eta_vals = np.logspace(-5, 1, 7) -lmbd_vals = np.logspace(-5, 1, 7) -# store the models for later use -DNN_numpy = np.zeros((len(eta_vals), len(lmbd_vals)), dtype=object) - -# grid search -for i, eta in enumerate(eta_vals): - for j, lmbd in enumerate(lmbd_vals): - dnn = NeuralNetwork(X_train, Y_train_onehot, eta=eta, lmbd=lmbd, epochs=epochs, batch_size=batch_size, - n_hidden_neurons=n_hidden_neurons, n_categories=n_categories) - dnn.train() - - DNN_numpy[i][j] = dnn - - test_predict = dnn.predict(X_test) - - print("Learning rate = ", eta) - print("Lambda = ", lmbd) - print("Accuracy score on test set: ", accuracy_score(Y_test, test_predict)) - print() -!ec - - -===== Visualization ===== - -!bc pycod -# visual representation of grid search -# uses seaborn heatmap, you can also do this with matplotlib imshow -import seaborn as sns - -sns.set() - -train_accuracy = np.zeros((len(eta_vals), len(lmbd_vals))) -test_accuracy = np.zeros((len(eta_vals), len(lmbd_vals))) - -for i in range(len(eta_vals)): - for j in range(len(lmbd_vals)): - dnn = DNN_numpy[i][j] - - train_pred = dnn.predict(X_train) - test_pred = dnn.predict(X_test) - - train_accuracy[i][j] = accuracy_score(Y_train, train_pred) - test_accuracy[i][j] = accuracy_score(Y_test, test_pred) - - -fig, ax = plt.subplots(figsize = (10, 10)) -sns.heatmap(train_accuracy, annot=True, ax=ax, cmap="viridis") -ax.set_title("Training Accuracy") -ax.set_ylabel("$\eta$") -ax.set_xlabel("$\lambda$") -plt.show() - -fig, ax = plt.subplots(figsize = (10, 10)) -sns.heatmap(test_accuracy, annot=True, ax=ax, cmap="viridis") -ax.set_title("Test Accuracy") -ax.set_ylabel("$\eta$") -ax.set_xlabel("$\lambda$") -plt.show() -!ec - - -===== scikit-learn implementation ===== - -_scikit-learn_ focuses more -on traditional machine learning methods, such as regression, -clustering, decision trees, etc. As such, it has only two types of -neural networks: Multi Layer Perceptron outputting continuous values, -*MPLRegressor*, and Multi Layer Perceptron outputting labels, -*MLPClassifier*. We will see how simple it is to use these classes. - -_scikit-learn_ implements a few improvements from our neural network, -such as early stopping, a varying learning rate, different -optimization methods, etc. We would therefore expect a better -performance overall. - -!bc pycod -from sklearn.neural_network import MLPClassifier -# store models for later use -DNN_scikit = np.zeros((len(eta_vals), len(lmbd_vals)), dtype=object) - -for i, eta in enumerate(eta_vals): - for j, lmbd in enumerate(lmbd_vals): - dnn = MLPClassifier(hidden_layer_sizes=(n_hidden_neurons), activation='logistic', - alpha=lmbd, learning_rate_init=eta, max_iter=epochs) - dnn.fit(X_train, Y_train) - - DNN_scikit[i][j] = dnn - - print("Learning rate = ", eta) - print("Lambda = ", lmbd) - print("Accuracy score on test set: ", dnn.score(X_test, Y_test)) - print() -!ec - - - -===== Visualization ===== -!bc pycod -# optional -# visual representation of grid search -# uses seaborn heatmap, could probably do this in matplotlib -import seaborn as sns - -sns.set() - -train_accuracy = np.zeros((len(eta_vals), len(lmbd_vals))) -test_accuracy = np.zeros((len(eta_vals), len(lmbd_vals))) - -for i in range(len(eta_vals)): - for j in range(len(lmbd_vals)): - dnn = DNN_scikit[i][j] - - train_pred = dnn.predict(X_train) - test_pred = dnn.predict(X_test) - - train_accuracy[i][j] = accuracy_score(Y_train, train_pred) - test_accuracy[i][j] = accuracy_score(Y_test, test_pred) - - -fig, ax = plt.subplots(figsize = (10, 10)) -sns.heatmap(train_accuracy, annot=True, ax=ax, cmap="viridis") -ax.set_title("Training Accuracy") -ax.set_ylabel("$\eta$") -ax.set_xlabel("$\lambda$") -plt.show() - -fig, ax = plt.subplots(figsize = (10, 10)) -sns.heatmap(test_accuracy, annot=True, ax=ax, cmap="viridis") -ax.set_title("Test Accuracy") -ax.set_ylabel("$\eta$") -ax.set_xlabel("$\lambda$") -plt.show() -!ec - - - -===== Building neural networks in Tensorflow and Keras ===== - -Now we want to build on the experience gained from our neural network implementation in NumPy and scikit-learn -and use it to construct a neural network in Tensorflow. Once we have constructed a neural network in NumPy -and Tensorflow, building one in Keras is really quite trivial, though the performance may suffer. - -In our previous example we used only one hidden layer, and in this we will use two. From this it should be quite -clear how to build one using an arbitrary number of hidden layers, using data structures such as Python lists or -NumPy arrays. - - -===== Tensorflow ===== - -Tensorflow is an open source library machine learning library -developed by the Google Brain team for internal use. It was released -under the Apache 2.0 open source license in November 9, 2015. - -Tensorflow is a computational framework that allows you to construct -machine learning models at different levels of abstraction, from -high-level, object-oriented APIs like Keras, down to the C++ kernels -that Tensorflow is built upon. The higher levels of abstraction are -simpler to use, but less flexible, and our choice of implementation -should reflect the problems we are trying to solve. - -"Tensorflow uses":"https://www.tensorflow.org/guide/graphs" so-called graphs to represent your computation -in terms of the dependencies between individual operations, such that you first build a Tensorflow *graph* -to represent your model, and then create a Tensorflow *session* to run the graph. - -In this guide we will analyze the same data as we did in our NumPy and -scikit-learn tutorial, gathered from the MNIST database of images. We -will give an introduction to the lower level Python Application -Program Interfaces (APIs), and see how we use them to build our graph. -Then we will build (effectively) the same graph in Keras, to see just -how simple solving a machine learning problem can be. - -To install tensorflow on Unix/Linux systems, use pip as -!bc pycod -pip3 install tensorflow -!ec -and/or if you use _anaconda_, just write (or install from the graphical user interface) -!bc pycod -conda install tensorflow -!ec - - -===== Collect and pre-process data ===== - -!bc pycod -# import necessary packages -import numpy as np -import matplotlib.pyplot as plt -from sklearn import datasets - - -# ensure the same random numbers appear every time -np.random.seed(0) - -# display images in notebook -%matplotlib inline -plt.rcParams['figure.figsize'] = (12,12) - - -# download MNIST dataset -digits = datasets.load_digits() - -# define inputs and labels -inputs = digits.images -labels = digits.target - -print("inputs = (n_inputs, pixel_width, pixel_height) = " + str(inputs.shape)) -print("labels = (n_inputs) = " + str(labels.shape)) - - -# flatten the image -# the value -1 means dimension is inferred from the remaining dimensions: 8x8 = 64 -n_inputs = len(inputs) -inputs = inputs.reshape(n_inputs, -1) -print("X = (n_inputs, n_features) = " + str(inputs.shape)) - - -# choose some random images to display -indices = np.arange(n_inputs) -random_indices = np.random.choice(indices, size=5) - -for i, image in enumerate(digits.images[random_indices]): - plt.subplot(1, 5, i+1) - plt.axis('off') - plt.imshow(image, cmap=plt.cm.gray_r, interpolation='nearest') - plt.title("Label: %d" % digits.target[random_indices[i]]) -plt.show() -!ec - -!bc pycod -from keras.utils import to_categorical -from sklearn.model_selection import train_test_split - -# one-hot representation of labels -labels = to_categorical(labels) - -# split into train and test data -train_size = 0.8 -test_size = 1 - train_size -X_train, X_test, Y_train, Y_test = train_test_split(inputs, labels, train_size=train_size, - test_size=test_size) -!ec - - -===== Using TensorFlow backend ===== - -o Define model and architecture -o Choose cost function and optimizer - -!bc pycod -import tensorflow as tf - -class NeuralNetworkTensorflow: - def __init__( - self, - X_train, - Y_train, - X_test, - Y_test, - n_neurons_layer1=100, - n_neurons_layer2=50, - n_categories=2, - epochs=10, - batch_size=100, - eta=0.1, - lmbd=0.0, - ): - - # keep track of number of steps - self.global_step = tf.Variable(0, dtype=tf.int32, trainable=False, name='global_step') - - self.X_train = X_train - self.Y_train = Y_train - self.X_test = X_test - self.Y_test = Y_test - - self.n_inputs = X_train.shape[0] - self.n_features = X_train.shape[1] - self.n_neurons_layer1 = n_neurons_layer1 - self.n_neurons_layer2 = n_neurons_layer2 - self.n_categories = n_categories - - self.epochs = epochs - self.batch_size = batch_size - self.iterations = self.n_inputs // self.batch_size - self.eta = eta - self.lmbd = lmbd - - # build network piece by piece - # name scopes (with) are used to enforce creation of new variables - # https://www.tensorflow.org/guide/variables - self.create_placeholders() - self.create_DNN() - self.create_loss() - self.create_optimiser() - self.create_accuracy() - - def create_placeholders(self): - # placeholders are fine here, but "Datasets" are the preferred method - # of streaming data into a model - with tf.name_scope('data'): - self.X = tf.placeholder(tf.float32, shape=(None, self.n_features), name='X_data') - self.Y = tf.placeholder(tf.float32, shape=(None, self.n_categories), name='Y_data') - - def create_DNN(self): - with tf.name_scope('DNN'): - # the weights are stored to calculate regularization loss later - - # Fully connected layer 1 - self.W_fc1 = self.weight_variable([self.n_features, self.n_neurons_layer1], name='fc1', dtype=tf.float32) - b_fc1 = self.bias_variable([self.n_neurons_layer1], name='fc1', dtype=tf.float32) - a_fc1 = tf.nn.sigmoid(tf.matmul(self.X, self.W_fc1) + b_fc1) - - # Fully connected layer 2 - self.W_fc2 = self.weight_variable([self.n_neurons_layer1, self.n_neurons_layer2], name='fc2', dtype=tf.float32) - b_fc2 = self.bias_variable([self.n_neurons_layer2], name='fc2', dtype=tf.float32) - a_fc2 = tf.nn.sigmoid(tf.matmul(a_fc1, self.W_fc2) + b_fc2) - - # Output layer - self.W_out = self.weight_variable([self.n_neurons_layer2, self.n_categories], name='out', dtype=tf.float32) - b_out = self.bias_variable([self.n_categories], name='out', dtype=tf.float32) - self.z_out = tf.matmul(a_fc2, self.W_out) + b_out - - def create_loss(self): - with tf.name_scope('loss'): - softmax_loss = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits_v2(labels=self.Y, logits=self.z_out)) - - regularizer_loss_fc1 = tf.nn.l2_loss(self.W_fc1) - regularizer_loss_fc2 = tf.nn.l2_loss(self.W_fc2) - regularizer_loss_out = tf.nn.l2_loss(self.W_out) - regularizer_loss = self.lmbd*(regularizer_loss_fc1 + regularizer_loss_fc2 + regularizer_loss_out) - - self.loss = softmax_loss + regularizer_loss - - def create_accuracy(self): - with tf.name_scope('accuracy'): - probabilities = tf.nn.softmax(self.z_out) - predictions = tf.argmax(probabilities, axis=1) - labels = tf.argmax(self.Y, axis=1) - - correct_predictions = tf.equal(predictions, labels) - correct_predictions = tf.cast(correct_predictions, tf.float32) - self.accuracy = tf.reduce_mean(correct_predictions) - - def create_optimiser(self): - with tf.name_scope('optimizer'): - self.optimizer = tf.train.GradientDescentOptimizer(learning_rate=self.eta).minimize(self.loss, global_step=self.global_step) - - def weight_variable(self, shape, name='', dtype=tf.float32): - initial = tf.truncated_normal(shape, stddev=0.1) - return tf.Variable(initial, name=name, dtype=dtype) - - def bias_variable(self, shape, name='', dtype=tf.float32): - initial = tf.constant(0.1, shape=shape) - return tf.Variable(initial, name=name, dtype=dtype) - - def fit(self): - data_indices = np.arange(self.n_inputs) - - with tf.Session() as sess: - sess.run(tf.global_variables_initializer()) - for i in range(self.epochs): - for j in range(self.iterations): - chosen_datapoints = np.random.choice(data_indices, size=self.batch_size, replace=False) - batch_X, batch_Y = self.X_train[chosen_datapoints], self.Y_train[chosen_datapoints] - - sess.run([DNN.loss, DNN.optimizer], - feed_dict={DNN.X: batch_X, - DNN.Y: batch_Y}) - accuracy = sess.run(DNN.accuracy, - feed_dict={DNN.X: batch_X, - DNN.Y: batch_Y}) - step = sess.run(DNN.global_step) - - self.train_loss, self.train_accuracy = sess.run([DNN.loss, DNN.accuracy], - feed_dict={DNN.X: self.X_train, - DNN.Y: self.Y_train}) - - self.test_loss, self.test_accuracy = sess.run([DNN.loss, DNN.accuracy], - feed_dict={DNN.X: self.X_test, - DNN.Y: self.Y_test}) -!ec - - - -===== Optimizing and using gradient descent ===== - -!bc pycod -epochs = 100 -batch_size = 100 -n_neurons_layer1 = 100 -n_neurons_layer2 = 50 -n_categories = 10 -eta_vals = np.logspace(-5, 1, 7) -lmbd_vals = np.logspace(-5, 1, 7) -!ec - - -!bc pycod -DNN_tf = np.zeros((len(eta_vals), len(lmbd_vals)), dtype=object) - -for i, eta in enumerate(eta_vals): - for j, lmbd in enumerate(lmbd_vals): - DNN = NeuralNetworkTensorflow(X_train, Y_train, X_test, Y_test, - n_neurons_layer1, n_neurons_layer2, n_categories, - epochs=epochs, batch_size=batch_size, eta=eta, lmbd=lmbd) - DNN.fit() - - DNN_tf[i][j] = DNN - - print("Learning rate = ", eta) - print("Lambda = ", lmbd) - print("Test accuracy: %.3f" % DNN.test_accuracy) - print() -!ec - -!bc pycod -# optional -# visual representation of grid search -# uses seaborn heatmap, could probably do this in matplotlib -import seaborn as sns - -sns.set() - -train_accuracy = np.zeros((len(eta_vals), len(lmbd_vals))) -test_accuracy = np.zeros((len(eta_vals), len(lmbd_vals))) - -for i in range(len(eta_vals)): - for j in range(len(lmbd_vals)): - DNN = DNN_tf[i][j] - - train_accuracy[i][j] = DNN.train_accuracy - test_accuracy[i][j] = DNN.test_accuracy - - -fig, ax = plt.subplots(figsize = (10, 10)) -sns.heatmap(train_accuracy, annot=True, ax=ax, cmap="viridis") -ax.set_title("Training Accuracy") -ax.set_ylabel("$\eta$") -ax.set_xlabel("$\lambda$") -plt.show() - -fig, ax = plt.subplots(figsize = (10, 10)) -sns.heatmap(test_accuracy, annot=True, ax=ax, cmap="viridis") -ax.set_title("Test Accuracy") -ax.set_ylabel("$\eta$") -ax.set_xlabel("$\lambda$") -plt.show() -!ec - -!bc pycod -# optional -# we can use log files to visualize our graph in Tensorboard -writer = tf.summary.FileWriter('logs/') -writer.add_graph(tf.get_default_graph()) -!ec - - - -===== Using Keras ===== - -Keras is a high level "neural network":"https://en.wikipedia.org/wiki/Application_programming_interface" -that supports Tensorflow, CTNK and Theano as backends. -If you have Tensorflow installed Keras is available through the *tf.keras* module. -If you have Anaconda installed you may run the following command -!bc pycod -conda install keras -!ec - -Alternatively, if you have Tensorflow or one of the other supported backends install you may use the pip package manager: - -!bc pycod -pip3 install keras -!ec -or look up the "instructions here":"https://keras.io/". - -!bc pycod -from keras.models import Sequential -from keras.layers import Dense -from keras.regularizers import l2 -from keras.optimizers import SGD - -def create_neural_network_keras(n_neurons_layer1, n_neurons_layer2, n_categories, eta, lmbd): - model = Sequential() - model.add(Dense(n_neurons_layer1, activation='sigmoid', kernel_regularizer=l2(lmbd))) - model.add(Dense(n_neurons_layer2, activation='sigmoid', kernel_regularizer=l2(lmbd))) - model.add(Dense(n_categories, activation='softmax')) - - sgd = SGD(lr=eta) - model.compile(loss='categorical_crossentropy', optimizer=sgd, metrics=['accuracy']) - - return model -!ec - -!bc pycod -DNN_keras = np.zeros((len(eta_vals), len(lmbd_vals)), dtype=object) - -for i, eta in enumerate(eta_vals): - for j, lmbd in enumerate(lmbd_vals): - DNN = create_neural_network_keras(n_neurons_layer1, n_neurons_layer2, n_categories, - eta=eta, lmbd=lmbd) - DNN.fit(X_train, Y_train, epochs=epochs, batch_size=batch_size, verbose=0) - scores = DNN.evaluate(X_test, Y_test) - - DNN_keras[i][j] = DNN - - print("Learning rate = ", eta) - print("Lambda = ", lmbd) - print("Test accuracy: %.3f" % scores[1]) - print() -!ec - -!bc pycod -# optional -# visual representation of grid search -# uses seaborn heatmap, could probably do this in matplotlib -import seaborn as sns - -sns.set() - -train_accuracy = np.zeros((len(eta_vals), len(lmbd_vals))) -test_accuracy = np.zeros((len(eta_vals), len(lmbd_vals))) - -for i in range(len(eta_vals)): - for j in range(len(lmbd_vals)): - DNN = DNN_keras[i][j] - - train_accuracy[i][j] = DNN.evaluate(X_train, Y_train)[1] - test_accuracy[i][j] = DNN.evaluate(X_test, Y_test)[1] - - -fig, ax = plt.subplots(figsize = (10, 10)) -sns.heatmap(train_accuracy, annot=True, ax=ax, cmap="viridis") -ax.set_title("Training Accuracy") -ax.set_ylabel("$\eta$") -ax.set_xlabel("$\lambda$") -plt.show() - -fig, ax = plt.subplots(figsize = (10, 10)) -sns.heatmap(test_accuracy, annot=True, ax=ax, cmap="viridis") -ax.set_title("Test Accuracy") -ax.set_ylabel("$\eta$") -ax.set_xlabel("$\lambda$") -plt.show() -!ec - - - - - -===== Which activation function should I use? ===== - -The Back propagation algorithm we derived above works by going from -the output layer to the input layer, propagating the error gradient on -the way. Once the algorithm has computed the gradient of the cost -function with regards to each parameter in the network, it uses these -gradients to update each parameter with a Gradient Descent (GD) step. - - -Unfortunately for us, the gradients often get smaller and smaller as the -algorithm progresses down to the first hidden layers. As a result, the -GD update leaves the lower layer connection weights -virtually unchanged, and training never converges to a good -solution. This is known in the literature as -_the vanishing gradients problem_. - -In other cases, the opposite can happen, namely the the gradients can grow bigger and -bigger. The result is that many of the layers get large updates of the -weights the -algorithm diverges. This is the _exploding gradients problem_, which is -mostly encountered in recurrent neural networks. More generally, deep -neural networks suffer from unstable gradients, different layers may -learn at widely different speeds - - -===== Is the Logistic activation function (Sigmoid) our choice? ===== - -Although this unfortunate behavior has been empirically observed for -quite a while (it was one of the reasons why deep neural networks were -mostly abandoned for a long time), it is only around 2010 that -significant progress was made in understanding it. - -A paper titled "Understanding the Difficulty of Training Deep -Feedforward Neural Networks by Xavier Glorot and Yoshua Bengio":"http://proceedings.mlr.press/v9/glorot10a.html" found that -the problems with the popular logistic -sigmoid activation function and the weight initialization technique -that was most popular at the time, namely random initialization using -a normal distribution with a mean of 0 and a standard deviation of -1. - -They showed that with this activation function and this -initialization scheme, the variance of the outputs of each layer is -much greater than the variance of its inputs. Going forward in the -network, the variance keeps increasing after each layer until the -activation function saturates at the top layers. This is actually made -worse by the fact that the logistic function has a mean of 0.5, not 0 -(the hyperbolic tangent function has a mean of 0 and behaves slightly -better than the logistic function in deep networks). - - - -===== The derivative of the Logistic funtion ===== - -Looking at the logistic activation function, when inputs become large -(negative or positive), the function saturates at 0 or 1, with a -derivative extremely close to 0. Thus when backpropagation kicks in, -it has virtually no gradient to propagate back through the network, -and what little gradient exists keeps getting diluted as -backpropagation progresses down through the top layers, so there is -really nothing left for the lower layers. - -In their paper, Glorot and Bengio propose a way to significantly -alleviate this problem. We need the signal to flow properly in both -directions: in the forward direction when making predictions, and in -the reverse direction when backpropagating gradients. We don’t want -the signal to die out, nor do we want it to explode and saturate. For -the signal to flow properly, the authors argue that we need the -variance of the outputs of each layer to be equal to the variance of -its inputs, and we also need the gradients to have equal variance -before and after flowing through a layer in the reverse direction. - - - -One of the insights in the 2010 paper by Glorot and Bengio was that -the vanishing/exploding gradients problems were in part due to a poor -choice of activation function. Until then most people had assumed that -if Nature had chosen to use roughly sigmoid activation functions in -biological neurons, they must be an excellent choice. But it turns out -that other activation functions behave much better in deep neural -networks, in particular the ReLU activation function, mostly because -it does not saturate for positive values (and also because it is quite -fast to compute). - - - -===== The RELU function family ===== - -The ReLU activation function suffers from a problem known as the dying -ReLUs: during training, some neurons effectively die, meaning they -stop outputting anything other than 0. - -In some cases, you may find that half of your network’s neurons are -dead, especially if you used a large learning rate. During training, -if a neuron’s weights get updated such that the weighted sum of the -neuron’s inputs is negative, it will start outputting 0. When this -happen, the neuron is unlikely to come back to life since the gradient -of the ReLU function is 0 when its input is negative. - -To solve this problem, nowadays practitioners use a variant of the ReLU -function, such as the leaky ReLU discussed above or the so-called -exponential linear unit (ELU) function - - -!bt -\[ -ELU(z) = \left\{\begin{array}{cc} \alpha\left( \exp{(z)}-1\right) & z < 0,\\ z & z \ge 0.\end{array}\right. -\] -!et - - -===== Which activation function should we use? ===== - -In general it seems that the ELU activation function is better than -the leaky ReLU function (and its variants), which is better than -ReLU. ReLU performs better than $\tanh$ which in turn performs better -than the logistic function. - -If runtime -performance is an issue, then you may opt for the leaky ReLU function over the -ELU function If you don’t -want to tweak yet another hyperparameter, you may just use the default -$\alpha$ of $0.01$ for the leaky ReLU, and $1$ for ELU. If you have -spare time and computing power, you can use cross-validation or -bootstrap to evaluate other activation functions. - - - -===== A top-down perspective on Neural networks ===== - - -The first thing we would like to do is divide the data into two or three -parts. A training set, a validation or dev (development) set, and a -test set. The test set is the data on which we want to make -predictions. The dev set is a subset of the training data we use to -check how well we are doing out-of-sample, after training the model on -the training dataset. We use the validation error as a proxy for the -test error in order to make tweaks to our model. It is crucial that we -do not use any of the test data to train the algorithm. This is a -cardinal sin in ML. Then: - - -* Estimate optimal error rate - -* Minimize underfitting (bias) on training data set. - -* Make sure you are not overfitting. - -If the validation and test sets are drawn from the same distributions, -then a good performance on the validation set should lead to similarly -good performance on the test set. - -However, sometimes -the training data and test data differ in subtle ways because, for -example, they are collected using slightly different methods, or -because it is cheaper to collect data in one way versus another. In -this case, there can be a mismatch between the training and test -data. This can lead to the neural network overfitting these small -differences between the test and training sets, and a poor performance -on the test set despite having a good performance on the validation -set. To rectify this, Andrew Ng suggests making two validation or dev -sets, one constructed from the training data and one constructed from -the test data. The difference between the performance of the algorithm -on these two validation sets quantifies the train-test mismatch. This -can serve as another important diagnostic when using DNNs for -supervised learning. - - -===== Limitations of supervised learning with deep networks ===== - -Like all statistical methods, supervised learning using neural -networks has important limitations. This is especially important when -one seeks to apply these methods, especially to physics problems. Like -all tools, DNNs are not a universal solution. Often, the same or -better performance on a task can be achieved by using a few -hand-engineered features (or even a collection of random -features). - -Here we list some of the important limitations of supervised neural network based models. - - - -* _Need labeled data_. All supervised learning methods, DNNs for supervised learning require labeled data. Often, labeled data is harder to acquire than unlabeled data (e.g. one must pay for human experts to label images). -* _Supervised neural networks are extremely data intensive._ DNNs are data hungry. They perform best when data is plentiful. This is doubly so for supervised methods where the data must also be labeled. The utility of DNNs is extremely limited if data is hard to acquire or the datasets are small (hundreds to a few thousand samples). In this case, the performance of other methods that utilize hand-engineered features can exceed that of DNNs. -* _Homogeneous data._ Almost all DNNs deal with homogeneous data of one type. It is very hard to design architectures that mix and match data types (i.e.~some continuous variables, some discrete variables, some time series). In applications beyond images, video, and language, this is often what is required. In contrast, ensemble models like random forests or gradient-boosted trees have no difficulty handling mixed data types. -* _Many problems are not about prediction._ In natural science we are often interested in learning something about the underlying distribution that generates the data. In this case, it is often difficult to cast these ideas in a supervised learning setting. While the problems are related, it is possible to make good predictions with a *wrong* model. The model might or might not be useful for understanding the underlying science. - -Some of these remarks are particular to DNNs, others are shared by all supervised learning methods. This motivates the use of unsupervised methods which in part circumnavigate these problems. - - - - - - diff --git a/doc/LectureNotes/book.ipynb b/doc/LectureNotes/book.ipynb index 0194b9deb..c2fdcab63 100644 --- a/doc/LectureNotes/book.ipynb +++ b/doc/LectureNotes/book.ipynb @@ -10,10 +10,9 @@ " \n", "**Morten Hjorth-Jensen**, Department of Physics, University of Oslo and Department of Physics and Astronomy and National Superconducting Cyclotron Laboratory, Michigan State University\n", "\n", - "Date: **Oct 16, 2018**\n", - "\n", - "Copyright 1999-2018, Morten Hjorth-Jensen. Released under CC Attribution-NonCommercial 4.0 license\n", + "Date: **Aug 15, 2019**\n", "\n", + "Copyright 1999-2019, Morten Hjorth-Jensen. Released under CC Attribution-NonCommercial 4.0 license\n", "\n", "\n", "\n", @@ -25,6 +24,370 @@ "\n", "# Introduction\n", "\n", + "During the last two decades there has been a swift and amazing\n", + "development of Machine Learning techniques and algorithms that impact\n", + "many areas in not only Science and Technology but also the Humanities,\n", + "Social Sciences, Medicine, Law, indeed, almost all possible\n", + "disciplines. The applications are incredibly many, from self-driving\n", + "cars to solving high-dimensional differential equations or complicated\n", + "quantum mechanical many-body problems. Machine Learning is perceived\n", + "by many as one of the main disruptive techniques nowadays. \n", + "\n", + "Statistics, Data science and Machine Learning form important\n", + "fields of research in modern science. They describe how to learn and\n", + "make predictions from data, as well as allowing us to extract\n", + "important correlations about physical process and the underlying laws\n", + "of motion in large data sets. The latter, big data sets, appear\n", + "frequently in essentially all disciplines, from the traditional\n", + "Science, Technology, Mathematics and Engineering fields to Life\n", + "Science, Law, education research, the Humanities and the Social\n", + "Sciences.\n", + "\n", + "It has become more\n", + "and more common to see research projects on big data in for example\n", + "the Social Sciences where extracting patterns from complicated survey\n", + "data is one of many research directions. Having a solid grasp of data\n", + "analysis and machine learning is thus becoming central to scientific\n", + "computing in many fields, and competences and skills within the fields\n", + "of machine learning and scientific computing are nowadays strongly\n", + "requested by many potential employers. The latter cannot be\n", + "overstated, familiarity with machine learning has almost become a\n", + "prerequisite for many of the most exciting employment opportunities,\n", + "whether they are in bioinformatics, life science, physics or finance,\n", + "in the private or the public sector. This author has had several\n", + "students or met students who have been hired recently based on their\n", + "skills and competences in scientific computing and data science, often\n", + "with marginal knowledge of machine learning.\n", + "\n", + "Machine learning is a subfield of computer science, and is closely\n", + "related to computational statistics. It evolved from the study of\n", + "pattern recognition in artificial intelligence (AI) research, and has\n", + "made contributions to AI tasks like computer vision, natural language\n", + "processing and speech recognition. Many of the methods we will study are also \n", + "strongly rooted in basic mathematics and physics research. \n", + "\n", + "Ideally, machine learning represents the science of giving computers\n", + "the ability to learn without being explicitly programmed. The idea is\n", + "that there exist generic algorithms which can be used to find patterns\n", + "in a broad class of data sets without having to write code\n", + "specifically for each problem. The algorithm will build its own logic\n", + "based on the data. You should however always keep in mind that\n", + "machines and algorithms are to a large extent developed by humans. The\n", + "insights and knowledge we have about a specific system, play a central\n", + "role when we develop a specific machine learning algorithm. \n", + "\n", + "Machine learning is an extremely rich field, in spite of its young\n", + "age. The increases we have seen during the last three decades in\n", + "computational capabilities have been followed by developments of\n", + "methods and techniques for analyzing and handling large date sets,\n", + "relying heavily on statistics, computer science and mathematics. The\n", + "field is rather new and developing rapidly. Popular software packages\n", + "written in Python for machine learning like\n", + "[Scikit-learn](http://scikit-learn.org/stable/),\n", + "[Tensorflow](https://www.tensorflow.org/),\n", + "[PyTorch](http://pytorch.org/) and [Keras](https://keras.io/), all\n", + "freely available at their respective GitHub sites, encompass\n", + "communities of developers in the thousands or more. And the number of\n", + "code developers and contributors keeps increasing. Not all the\n", + "algorithms and methods can be given a rigorous mathematical\n", + "justification, opening up thereby large rooms for experimenting and\n", + "trial and error and thereby exciting new developments. However, a\n", + "solid command of linear algebra, multivariate theory, probability\n", + "theory, statistical data analysis, understanding errors and Monte\n", + "Carlo methods are central elements in a proper understanding of many\n", + "of algorithms and methods we will discuss.\n", + "\n", + "\n", + "\n", + "## Learning outcomes\n", + "\n", + "These sets of lectures aim at giving you an overview of central aspects of\n", + "statistical data analysis as well as some of the central algorithms\n", + "used in machine learning. We will introduce a variety of central\n", + "algorithms and methods essential for studies of data analysis and\n", + "machine learning. \n", + "\n", + "Hands-on projects and experimenting with data and algorithms plays a central role in\n", + "these lectures, and our hope is, through the various\n", + "projects and exercises, to expose you to fundamental\n", + "research problems in these fields, with the aim to reproduce state of\n", + "the art scientific results. You will learn to develop and\n", + "structure codes for studying these systems, get acquainted with\n", + "computing facilities and learn to handle large scientific projects. A\n", + "good scientific and ethical conduct is emphasized throughout the\n", + "course. More specifically, you will\n", + "\n", + "1. Learn about basic data analysis, Bayesian statistics, Monte Carlo methods, data optimization and machine learning;\n", + "\n", + "2. Be capable of extending the acquired knowledge to other systems and cases;\n", + "\n", + "3. Have an understanding of central algorithms used in data analysis and machine learning;\n", + "\n", + "4. Gain knowledge of central aspects of Monte Carlo methods, Markov chains, Gibbs samplers and their possible applications, from numerical integration to simulation of stock markets;\n", + "\n", + "5. Understand methods for regression and classification;\n", + "\n", + "6. Learn about neural network, genetic algorithms and Boltzmann machines;\n", + "\n", + "7. Work on numerical projects to illustrate the theory. The projects play a central role and you are expected to know modern programming languages like Python or C++, in addition to a basic knowledge of linear algebra (typically taught during the first one or two years of undergraduate studies).\n", + "\n", + "There are several topics we will cover here, spanning from \n", + "statistical data analysis and its basic concepts such as expectation\n", + "values, variance, covariance, correlation functions and errors, via\n", + "well-known probability distribution functions like the uniform\n", + "distribution, the binomial distribution, the Poisson distribution and\n", + "simple and multivariate normal distributions to central elements of\n", + "Bayesian statistics and modeling. We will also remind the reader about\n", + "central elements from linear algebra and standard methods based on\n", + "linear algebra used to optimize (minimize) functions (the family of gradient descent methods)\n", + "and the Singular-value decomposition and\n", + "least square methods for parameterizing data.\n", + "\n", + "We will also cover Monte Carlo methods, Markov chains, well-known\n", + "algorithms for sampling stochastic events like the Metropolis-Hastings\n", + "and Gibbs sampling methods. An important aspect of all our\n", + "calculations is a proper estimation of errors. Here we will also\n", + "discuss famous resampling techniques like the blocking, the bootstrapping\n", + "and the jackknife methods and the infamous bias-variance tradeoff. \n", + "\n", + "The second part of the material covers several algorithms used in\n", + "machine learning.\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "## Types of Machine Learning\n", + "\n", + "\n", + "The approaches to machine learning are many, but are often split into\n", + "two main categories. In *supervised learning* we know the answer to a\n", + "problem, and let the computer deduce the logic behind it. On the other\n", + "hand, *unsupervised learning* is a method for finding patterns and\n", + "relationship in data sets without any prior knowledge of the system.\n", + "Some authours also operate with a third category, namely\n", + "*reinforcement learning*. This is a paradigm of learning inspired by\n", + "behavioral psychology, where learning is achieved by trial-and-error,\n", + "solely from rewards and punishment.\n", + "\n", + "Another way to categorize machine learning tasks is to consider the\n", + "desired output of a system. Some of the most common tasks are:\n", + "\n", + " * Classification: Outputs are divided into two or more classes. The goal is to produce a model that assigns inputs into one of these classes. An example is to identify digits based on pictures of hand-written ones. Classification is typically supervised learning.\n", + "\n", + " * Regression: Finding a functional relationship between an input data set and a reference data set. The goal is to construct a function that maps input data to continuous output values.\n", + "\n", + " * Clustering: Data are divided into groups with certain common traits, without knowing the different groups beforehand. It is thus a form of unsupervised learning.\n", + "\n", + "The methods we cover have three main topics in common, irrespective of\n", + "whether we deal with supervised or unsupervised learning. The first\n", + "ingredient is normally our data set (which can be subdivided into\n", + "training and test data), the second item is a model which is normally\n", + "a function of some parameters. The model reflects our knowledge of\n", + "the system (or lack thereof). As an example, if we know that our data\n", + "show a behavior similar to what would be predicted by a polynomial,\n", + "fitting our data to a polynomial of some degree would then determin\n", + "our model.\n", + "\n", + "The last ingredient is a so-called **cost**\n", + "function which allows us to present an estimate on how good our model\n", + "is in reproducing the data it is supposed to train. \n", + "\n", + "Here we will build our machine learning approach on elements of the\n", + "statistical foundation discussed above, with elements from data\n", + "analysis, stochastic processes etc. We will discuss the following\n", + "machine learning algorithms\n", + "\n", + "1. Linear regression and its variants\n", + "\n", + "2. Decision tree algorithms, from single trees to random forests\n", + "\n", + "3. Bayesian statistics and regression\n", + "\n", + "4. Support vector machines and finally various variants of\n", + "\n", + "5. Artifical neural networks and deep learning, including convolutional neural networks and Bayesian neural networks\n", + "\n", + "6. Networks for unsupervised learning using for example reduced Boltzmann machines.\n", + "\n", + "## Choice of programming language\n", + "\n", + "Python plays nowadays a central role in the development of machine\n", + "learning techniques and tools for data analysis. In particular, seen\n", + "the wealth of machine learning and data analysis libraries written in\n", + "Python, easy to use libraries with immediate visualization(and not the\n", + "least impressive galleries of existing examples), the popularity of the\n", + "Jupyter notebook framework with the possibility to run **R** codes or\n", + "compiled programs written in C++, and much more made our choice of\n", + "programming language for this series of lectures easy. However,\n", + "since the focus here is not only on using existing Python libraries such\n", + "as **Scikit-Learn** or **Tensorflow**, but also on developing your own\n", + "algorithms and codes, we will as far as possible present many of these\n", + "algorithms either as a Python codes or C++ or Fortran (or other languages) codes. \n", + "\n", + "The reason we also focus on compiled languages like C++ (or\n", + "Fortran), is that Python is still notoriously slow when we do not\n", + "utilize highly streamlined computational libraries like\n", + "[Lapack](http://www.netlib.org/lapack/) or other numerical libraries\n", + "written in compiled languages (many of these libraries are written in\n", + "Fortran). Although a project like [Numba](https://numba.pydata.org/)\n", + "holds great promise for speeding up the unrolling of lengthy loops, C++\n", + "and Fortran are presently still the performance winners. Numba gives\n", + "you potentially the power to speed up your applications with high\n", + "performance functions written directly in Python. In particular,\n", + "array-oriented and math-heavy Python code can achieve similar\n", + "performance to C, C++ and Fortran. However, even with these speed-ups,\n", + "for codes involving heavy Markov Chain Monte Carlo analyses and\n", + "optimizations of cost functions, C++/C or Fortran codes tend to\n", + "outperform Python codes. \n", + "\n", + "Presently thus, the community tends to let\n", + "code written in C++/C or Fortran do the heavy duty numerical\n", + "number crunching and leave the post-analysis of the data to the above\n", + "mentioned Python modules or software packages. However, with the developments taking place in for example the Python community, and seen\n", + "the changes during the last decade, the above situation may change swiftly in the not too distant future. \n", + "\n", + "Many of the examples we discuss in this series of lectures come with\n", + "existing data files or provide code examples which produce the data to\n", + "be analyzed. Most of the applications we will discuss deal with\n", + "small data sets (less than a terabyte of information) and can easily\n", + "be analyzed and tested on standard off the shelf laptops you find in general \n", + "stores.\n", + "\n", + "## Data handling, machine learning and ethical aspects\n", + "\n", + "In most of the cases we will study, we will either generate the data\n", + "to analyze ourselves (both for supervised learning and unsupervised\n", + "learning) or we will recur again and again to data present in say\n", + "**Scikit-Learn** or **Tensorflow**. Many of the examples we end up\n", + "dealing with are from a privacy and data protection point of view,\n", + "rather inoccuous and boring results of numerical\n", + "calculations. However, this does not hinder us from developing a sound\n", + "ethical attitude to the data we use, how we analyze the data and how\n", + "we handle the data.\n", + "\n", + "The most immediate and simplest possible ethical aspects deal with our\n", + "approach to the scientific process. Nowadays, with version control\n", + "software like [Git](https://git-scm.com/) and various online\n", + "repositories like [Github](https://github.com/),\n", + "[Gitlab](https://about.gitlab.com/) etc, we can easily make our codes\n", + "and data sets we have used, freely and easily accessible to a wider\n", + "community. This helps us almost automagically in making our science\n", + "reproducible. The large open-source development communities involved\n", + "in say [Scikit-Learn](http://scikit-learn.org/stable/),\n", + "[Tensorflow](https://www.tensorflow.org/),\n", + "[PyTorch](http://pytorch.org/) and [Keras](https://keras.io/), are\n", + "all excellent examples of this. The codes can be tested and improved\n", + "upon continuosly, helping thereby our scientific community at large in\n", + "developing data analysis and machine learning tools. It is much\n", + "easier today to gain traction and acceptance for making your science\n", + "reproducible. From a societal stand, this is an important element\n", + "since many of the developers are employees of large public institutions like\n", + "universities and research labs. Our fellow taxpayers do deserve to get\n", + "something back for their bucks.\n", + "\n", + "However, this more mechanical aspect of the ethics of science (in\n", + "particular the reproducibility of scientific results) is something\n", + "which is obvious and everybody should do so as part of the dialectics of\n", + "science. The fact that many scientists are not willing to share their codes or \n", + "data is detrimental to the scientific discourse.\n", + "\n", + "Before we proceed, we should add a disclaimer. Even though\n", + "we may dream of computers developing some kind of higher learning\n", + "capabilities, at the end (even if the artificial intelligence\n", + "community keeps touting our ears full of fancy futuristic avenues), it is we, yes you reading these lines,\n", + "who end up constructing and instructing, via various algorithms, the\n", + "machine learning approaches. Self-driving cars for example, rely on sofisticated\n", + "programs which take into account all possible situations a car can\n", + "encounter. In addition, extensive usage of training data from GPS\n", + "information, maps etc, are typically fed into the software for\n", + "self-driving cars. Adding to this various sensors and cameras that\n", + "feed information to the programs, there are zillions of ethical issues\n", + "which arise from this.\n", + "\n", + "For self-driving cars, where basically many of the standard machine\n", + "learning algorithms discussed here enter into the codes, at a certain\n", + "stage we have to make choices. Yes, we , the lads and lasses who wrote\n", + "a program for a specific brand of a self-driving car. As an example,\n", + "all carmakers have as their utmost priority the security of the\n", + "driver and the accompanying passengers. A famous European carmaker, which is\n", + "one of the leaders in the market of self-driving cars, had **if**\n", + "statements of the following type: suppose there are two obstacles in\n", + "front of you and you cannot avoid to collide with one of them. One of\n", + "the obstacles is a monstertruck while the other one is a kindergarten\n", + "class trying to cross the road. The self-driving car algo would then\n", + "opt for the hitting the small folks instead of the monstertruck, since\n", + "the likelihood of surving a collision with our future citizens, is\n", + "much higher.\n", + "\n", + "This leads to serious ethical aspects. Why should we\n", + "opt for such an option? Who decides and who is entitled to make such\n", + "choices? Keep in mind that many of the algorithms you will encounter in\n", + "this series of lectures or hear about later, are indeed based on\n", + "simple programming instructions. And you are very likely to be one of\n", + "the people who may end up writing such a code. Thus, developing a\n", + "sound ethical attitude to what we do, an approach well beyond the\n", + "simple mechanistic one of making our science available and\n", + "reproducible, is much needed. The example of the self-driving cars is\n", + "just one of infinitely many cases where we have to make choices. When\n", + "you analyze data on economic inequalities, who guarantees that you are\n", + "not weighting some data in a particular way, perhaps because you dearly want a\n", + "specific conclusion which may support your political views?\n", + "\n", + "We do not have the answers here, nor will we venture into a deeper\n", + "discussions of these aspects, but we want you think over these topics\n", + "in a more overarching way. A statistical data analysis with its dry\n", + "numbers and graphs meant to guide the eye, does not necessarily\n", + "reflect the truth, whatever that is. As a scientist, and after a\n", + "university education, you are supposedly a better citizen, with an\n", + "improved critical view and understanding of the scientific method, and\n", + "perhaps some deeper understanding of the ethics of science at\n", + "large. Use these insights. Be a critical citizen. You owe it to our\n", + "society.\n", + "\n", + "\n", + "\n", + "\n", + "# Getting started with Machine Learning\n", + "\n", + "Our emphasis throughout this series of lectures \n", + "is on understanding the mathematical aspects of\n", + "different algorithms used in the fields of data analysis and machine learning. \n", + "\n", + "However, where possible we will emphasize the\n", + "importance of using available software. We start thus with a hands-on\n", + "and top-down approach to machine learning. The aim is thus to start with\n", + "relevant data or data we have produced \n", + "and use these to introduce statistical data analysis\n", + "concepts and machine learning algorithms before we delve into the\n", + "algorithms themselves. The examples we will use in the beginning, start with simple\n", + "polynomials with random noise added. We will use the Python\n", + "software package [Scikit-Learn](http://scikit-learn.org/stable/) and\n", + "introduce various machine learning algorithms to make fits of\n", + "the data and predictions. We move thereafter to more interesting\n", + "cases such as data from say experiments (below we will look at experimental nuclear binding energies as an example).\n", + "These are examples where we can easily set up the data and\n", + "then use machine learning algorithms included in for example\n", + "**Scikit-Learn**. \n", + "\n", + "These examples will serve us the purpose of getting\n", + "started. Furthermore, they allow us to catch more than two birds with\n", + "a stone. They will allow us to bring in some programming specific\n", + "topics and tools as well as showing the power of various Python \n", + "libraries for machine learning and statistical data analysis. \n", + "\n", + "Here, we will mainly focus on two\n", + "specific Python packages for Machine Learning, Scikit-Learn and\n", + "Tensorflow (see below for links etc). Moreover, the examples we\n", + "introduce will serve as inputs to many of our discussions later, as\n", + "well as allowing you to set up models and produce your own data and\n", + "get started with programming.\n", + "\n", + "\n", + "\n", + "## What is Machine Learning?\n", + "\n", "Statistics, data science and machine learning form important fields of\n", "research in modern science. They describe how to learn and make\n", "predictions from data, as well as allowing us to extract important\n", @@ -90,65 +453,6 @@ "\n", "\n", "\n", - "## Learning outcomes\n", - "\n", - "These setsof lectures aim at giving you an overview of central aspects of\n", - "statistical data analysis as well as some of the central algorithms\n", - "used in machine learning. We will introduce a variety of central\n", - "algorithms and methods essential for studies of data analysis and\n", - "machine learning. \n", - "\n", - "Hands-on projects and experimenting with data and algorithms plays a central role in\n", - "these lectures, and our hope is, through the various\n", - "projects and exercies, to expose you to fundamental\n", - "research problems in these fields, with the aim to reproduce state of\n", - "the art scientific results. You will learn to develop and\n", - "structure large codes for studying these systems, get acquainted with\n", - "computing facilities and learn to handle large scientific projects. A\n", - "good scientific and ethical conduct is emphasized throughout the\n", - "course. More specifically, you will\n", - "\n", - "1. learn about basic data analysis, Bayesian statistics, Monte Carlo methods, data optimization and machine learning;\n", - "\n", - "2. be capable of extending the acquired knowledge to other systems and cases;\n", - "\n", - "3. Have an understanding of central algorithms used in data analysis and machine learning;\n", - "\n", - "4. Gain knowledge of central aspects of Monte Carlo methods, Markov chains, Gibbs samplers and their possible applications, from numerical integration to simulation of stock markets;\n", - "\n", - "5. Understand methods for regression and classification;\n", - "\n", - "6. Learn about neural network, genetic algorithms and Boltzmann machines;\n", - "\n", - "7. Work on numerical projects to illustrate the theory. The projects play a central role and you are expected to know modern programming languages like Python or C++, in addition to a basic knowledge of linear algebra (typically taught during the first one or two years of undergraduate studies).\n", - "\n", - "There are several topics we will cover here, spanning from a\n", - "statistical data analysis and its basic concepts such expectation\n", - "values, variance, covariance, correlation functions and errors, via\n", - "well-known probability distribution functions like uniform\n", - "distribution, the binomial distribution, the Poisson distribution and\n", - "simple and multivariate normal distributions to central elements of\n", - "Bayesian statistics and modeling. We will also remind the reader about\n", - "central elements from linear algebra and standard methods based on\n", - "linear algebra used to fit functions such Cubic splines and gradient\n", - "methods for data optimization and the Singular-value decomposition and\n", - "least square methods for parameterizing data.\n", - "\n", - "We will also cover Monte Carlo methods, Markov chains, well-known\n", - "algorithms for sampling stochastic events like the Metropolis-Hastings\n", - "and Gibbs sampling methods. An important aspect of all our\n", - "calculations is a proper estimation of errors. Here we will also\n", - "discuss famous resampling techniques like the blocking, bootstrapping\n", - "and jackknife methods.\n", - "\n", - "The second part of the material covers several algorithms used in\n", - "machine learning.\n", - "\n", - "\n", - "\n", - "\n", - "\n", - "\n", "## Types of Machine Learning\n", "\n", "\n", @@ -180,224 +484,26 @@ "The last ingredient is a so-called **cost**\n", "function which allows us to present an estimate on how good our model\n", "is in reproducing the data it is supposed to train. \n", - "\n", - "Here we will build our machine learning approach on elements of the\n", - "statistical foundation discussed above, with elements from data\n", - "analysis, stochastic processes etc. We will discuss the following\n", - "machine learning algorithms\n", - "\n", - "1. Linear regression and its variants, in essence polynomial regression\n", - "\n", - "2. Decision tree algorithms, from simpler to more complex ones\n", - "\n", - "3. Nearest neighbors models\n", - "\n", - "4. Bayesian statistics and regression\n", - "\n", - "5. Support vector machines and finally various variants of\n", - "\n", - "6. Artifical neural networks and deep learning\n", - "\n", - "7. Networks for unsupervised learning using for example reduced Boltzmann machines.\n", - "\n", - "## Choice of programming language\n", - "\n", - "Python plays nowadays a central role in the development of machine\n", - "learning techniques and tools for data analysis. In particular, seen\n", - "the wealth of machine learning and data analysis packages written in\n", - "Python, easy to use libraries with immediate visualization(and not the\n", - "least impressive galleries of existing example), the popularity of the\n", - "Jupyter notebook framework with the possibility to run **R** codes or\n", - "compiled programs written in C++, and much more made our choice of\n", - "programming language for this series of lectures of easy. However,\n", - "since the focus here is not only on using existing Python tools such\n", - "as **scikit-learn** or **tensorflow**, but also on developing your own\n", - "algorithms and codes, we will as far as possible present many of these\n", - "algorithms eithers a Python codes or C++ codes. Finally, we will, as\n", - "far as possible keep parallel versions of the data analysis and\n", - "machine larning programming aspects in **R** as\n", - "well. [R](https://www.r-project.org/) is a language and environment\n", - "for statistical computing and graphics which is widely used in\n", - "statistics and mathematics applications.\n", - "\n", - "The reason we also focus on compiled languages like C++ (or\n", - "Fortran), is that Python is still notoriously slow when we do not\n", - "utilize highly streamlined computational libraries like\n", - "[Lapack](http://www.netlib.org/lapack/) or other numerical libraries\n", - "written in compiled languages (many of these libraries are written in\n", - "Fortran). Although a project like [Numba](https://numba.pydata.org/)\n", - "holds great promise for speeding up the unrolling of lengthy loops, C+\n", - "and Fortran are presently still the performance winners. Numba gives\n", - "you potentially the power to speed up your applications with high\n", - "performance functions written directly in Python. In particular,\n", - "array-oriented and math-heavy Python code can achieve similar\n", - "performance to C, C++ and Fortran. However, even with these speed-ups,\n", - "for codes involving heavy Markov Chain Monte Carlo analyses and\n", - "optimizations of cost functions, C++/C or Fortran codes tend to\n", - "outperform Python codes. \n", - "\n", - "Presently thus, the community tends to let\n", - "code written in C++/C or Fortran do the heavy duty numerical\n", - "number crunching and leave the post-analysis of the data to the above\n", - "mentioned Python modules or software packages. However, with the developments taking place in for example the Python community, and seen\n", - "the changes during the last decade, the above situation may change swiftly in the not too distant future. \n", - "\n", - "Many of the examples we discuss in this series of lectures come with\n", - "existing data files or provide code examples which produce the data to\n", - "be analyzed. Most of the applications we will discuss deal with\n", - "small data sets (less than a terabyte of information) and can easily\n", - "be analyzed and tested on standard off the shelf laptops you find in general \n", - "grocery stores.\n", - "\n", - "## Data handling, machine learning and ethical aspects\n", - "\n", - "In most of the cases we will study, we will either generate the data\n", - "to analyze ourselves (both for supervised learning and unsupervised\n", - "learning) or we will recur again and again to data present in say\n", - "**scikit-learn** or **tensorflow**. Many of the examples we end up\n", - "dealing with are from a privacy and data protection point of view,\n", - "rather inoccuous and boring results of numerical\n", - "calculations. However, this does not hinder us from developing a sound\n", - "ethical attitude to the data we use, how we analyze the data and how\n", - "we handle the data.\n", - "\n", - "The most immediate and simplest possible ethical aspects deal with our\n", - "approach to the scientific process. Nowadays, with version control\n", - "software like [Git](https://git-scm.com/) and various online\n", - "repositories like [Github](https://github.com/),\n", - "[Gitlab](https://about.gitlab.com/) etc, we can easily make our codes\n", - "and data sets we have used, freely and easily accessible to a wider\n", - "community. This helps us almost automagically in making our science\n", - "reproducible. The large open-source development communities involved\n", - "in say [Scikit-learn](http://scikit-learn.org/stable/),\n", - "[Tensorflow](https://www.tensorflow.org/),\n", - "[PyTorch](http://pytorch.org/) and [Keras](https://keras.io/), are\n", - "all excellent examples of this. The codes can be tested and improved\n", - "upon continuosly, helping thereby our scientific community at large in\n", - "developing data analysis and machine learning tools. It is much\n", - "easier today to gain traction and acceptance for making your science\n", - "reproducible. From a societal stand, this is an important element\n", - "since many of the developers are employees of large public institutions like\n", - "universities and research labs. Our taxpayer do deserve to get\n", - "something back for their bucks.\n", - "\n", - "However, this more mechanical aspect of the ethics of science (in\n", - "particular the reproducibility of scientific results) is something\n", - "which is obvious and everybody should do as part of the dialectics of\n", - "science. The fact that many scientists are not willing to share their codes or \n", - "data is detrimental to the scientific discourse.\n", - "\n", - "Before we proceed, we should add a disclaimer. Even though\n", - "we may dream of computers developing some kind of higher learning\n", - "capabilities, at the end (even if the artificial intelligence\n", - "community keeps touting our ears full of fancy futuristic avenues), it is we\n", - "who end up constructing and instructing, via various algorithms, the\n", - "computers. Self-driving cars for example, rely on sofisticated\n", - "programs which take into account all possible situations a car can\n", - "encounter. In addition, extensive usage of training datas from GPS\n", - "information, maps etc, are typically fed into the software for\n", - "self-driving cars. Adding to this various sensors and cameras that\n", - "feed information to the programs, there are zillions of ethical issues\n", - "which arise from this.\n", - "\n", - "For self-driving cars, where basically many of the standard machine\n", - "learning algorithms discussed here enter into the codes, at a certain\n", - "stage we have to make choices. Yes, we , the lads and lasses who wrote\n", - "a program for a specific brand of a self-driving car. As an example,\n", - "a most carmakers have as their utmost priority the security of the\n", - "driver and the accompanying passengers. A famous carmaker, which is\n", - "one of the leaders in the market of self-driving cars, had **if**\n", - "statements of the following type: suppose there are two obstacles in\n", - "front of you and you cannot avoid to collide with one of them. One of\n", - "the obstacles is a monstertruck while the other one is a kindergarten\n", - "class trying to cross the road. The self-driving car algo would then\n", - "opt for the hitting the small folks instead of the monstertruck, since\n", - "the likelihood of surving a collision with our future citizens, is\n", - "much higher.\n", - "\n", - "This brings us leads then to serious ethical aspects. Why should we\n", - "opt for such an option? Who decides and who is entitled to make such\n", - "choices? Keep in mind that many of the algorithms you will about in\n", - "this series of lectures or hear about later, are indeed based on\n", - "simple programming instructions. And you are very likely to be one of\n", - "the people who may end up writing such a code. Thus, developing a\n", - "sound ethical attitude to what we do, an approach well beyond the\n", - "simple mechanistic one of making our science available and\n", - "reproducible, is much needed. The example of the self-driving cars is\n", - "just one of infinitely many cases where we have to make choices. When\n", - "you analyze data on economic inequalities, who guarantees that you are\n", - "not weighting some data in a particular way, perhaps because you dearly want a\n", - "specific conclusion which may support your political views?\n", - "\n", - "We do not have the answers here, but we want you think over these\n", - "topics in a more overarching way. A statistical data analysis with\n", - "its dry numbers and graphs meant to guide the eye, do not necessarily\n", - "reflect the truth, whatever that is. As a scientist, and after a\n", - "university education, you are supposedly a better citizen, with an\n", - "improved critical view and understanding of the scientific method, and\n", - "perhaps some deeper understandings of the ethics of science at\n", - "large. Use these insights. Be a critical citizen. You owe it to our\n", - "societies.\n", + "At the heart of basically all ML algorithms there are so-called minimization algorithms, often we end up with various variants of **gradient** methods.\n", "\n", "\n", "\n", "\n", "\n", - "## Software\n", - "\n", - "Our emphasis throughout this series of lectures \n", - "is on understanding the mathematical aspects of\n", - "different algorithms used in the fields of data analysis and machine learning. \n", - "\n", - "However, where possible we will emphasize the\n", - "importance of using available software. We start thus with a hands-on\n", - "and top-down approach to machine learning. The aim is thus to start with\n", - "relevant data or data we have produced \n", - "and use these to introduce statistical data analysis\n", - "concepts and machine learning algorithms before we delve into the\n", - "algorithms themselves. The examples we will use in the beginning, start with simple\n", - "polynomials with random noise added. We will use the Python\n", - "software package [Scikit-learn](http://scikit-learn.org/stable/) and\n", - "introduce various machine learning algorithms to make fits of\n", - "the data and predictions. We move thereafter to more interesting\n", - "cases such as the simulation of financial transactions or disease\n", - "models. These are examples where we can easily set up the data and\n", - "then use machine learning algorithms included in for example\n", - "**scikit-learn**. \n", - "\n", - "These examples will serve us the purpose of getting\n", - "started. Furthermore, they allow us to catch more than two birds with\n", - "a stone. They will allow us to bring in some programming specific\n", - "topics and tools as well as showing the power of various Python (and\n", - "R) packages for machine learning and statistical data analysis. In the\n", - "lectures on linear algebra we cover in more detail various programming\n", - "features of languages like Python and C++ (and other), we will also\n", - "look into more specific linear functions which are relevant for the\n", - "various algorithms we will discuss. Here, we will mainly focus on two\n", - "specific Python packages for Machine Learning, scikit-learn and\n", - "tensorflow (see below for links etc). Moreover, the examples we\n", - "introduce will serve as inputs to many of our discussions later, as\n", - "well as allowing you to set up models and produce your own data and\n", - "get started with programming.\n", - "\n", - "\n", - "\n", "\n", "\n", "## Software and needed installations\n", "\n", "We will make extensive use of Python as programming language and its\n", "myriad of available libraries. You will find\n", - "IPython/Jupyter notebooks invaluable in your work. You can run **R**\n", + "Jupyter notebooks invaluable in your work. You can run **R**\n", "codes in the Jupyter/IPython notebooks, with the immediate benefit of\n", "visualizing your data. You can also use compiled languages like C++,\n", - "Rust, Fortran etc if you prefer. The focus in these lectures will be\n", - "on Python, but we will provide many code examples for those of you who\n", - "prefer R or compiled languages. You can integrate C++ codes and R in for example\n", - "a Jupyter notebook. \n", + "Rust, Julia, Fortran etc if you prefer. The focus in these lectures will be\n", + "on Python.\n", "\n", "\n", - "If you have Python installed (we recommend Python3) and you feel\n", + "If you have Python installed (we strongly recommend Python3) and you feel\n", "pretty familiar with installing different packages, we recommend that\n", "you install the following Python packages via **pip** as \n", "\n", @@ -419,6 +525,7 @@ "etc etc. \n", "\n", "\n", + "\n", "## Python installers\n", "\n", "If you don't want to perform these operations separately and venture\n", @@ -441,20 +548,46 @@ "analysis environment, available for free and under a commercial\n", "license.\n", "\n", + "Furthermore, [Google's Colab](https://colab.research.google.com/notebooks/welcome.ipynb) is a free Jupyter notebook environment that requires \n", + "no setup and runs entirely in the cloud. Try it out!\n", "\n", + "## Useful Python libraries\n", + "Here we list several useful Python libraries we strongly recommend (if you use anaconda many of these are already there)\n", + "\n", + "* [NumPy](https://www.numpy.org/) is a highly popular library for large, multi-dimensional arrays and matrices, along with a large collection of high-level mathematical functions to operate on these arrays\n", + "\n", + "* [The pandas](https://pandas.pydata.org/) library provides high-performance, easy-to-use data structures and data analysis tools \n", + "\n", + "* [Xarray](http://xarray.pydata.org/en/stable/) is a Python package that makes working with labelled multi-dimensional arrays simple, efficient, and fun!\n", + "\n", + "* [Scipy](https://www.scipy.org/) (pronounced “Sigh Pie”) is a Python-based ecosystem of open-source software for mathematics, science, and engineering. \n", + "\n", + "* [Matplotlib](https://matplotlib.org/) is a Python 2D plotting library which produces publication quality figures in a variety of hardcopy formats and interactive environments across platforms.\n", + "\n", + "* [Autograd](https://github.com/HIPS/autograd) can automatically differentiate native Python and Numpy code. It can handle a large subset of Python's features, including loops, ifs, recursion and closures, and it can even take derivatives of derivatives of derivatives\n", + "\n", + "* [SymPy](https://www.sympy.org/en/index.html) is a Python library for symbolic mathematics. \n", + "\n", + "* [scikit-learn](https://scikit-learn.org/stable/) has simple and efficient tools for machine learning, data mining and data analysis\n", + "\n", + "* [TensorFlow](https://www.tensorflow.org/) is a Python library for fast numerical computing created and released by Google\n", + "\n", + "* [Keras](https://keras.io/) is a high-level neural networks API, written in Python and capable of running on top of TensorFlow, CNTK, or Theano\n", + "\n", + "* And many more such as [pytorch](https://pytorch.org/), [Theano](https://pypi.org/project/Theano/) etc \n", "\n", "## Installing R, C++, cython or Julia\n", "\n", - "You will also find it convenient to utilize R. Although we will mainly\n", - "use Python during lectures and in various projects and exercises, we\n", - "provide a full R set of codes for the same examples. Those of you\n", - "already familiar with R should feel free to continue using R, keeping\n", + "You will also find it convenient to utilize **R**. We will mainly\n", + "use Python during our lectures and in various projects and exercises.\n", + "Those of you\n", + "already familiar with **R** should feel free to continue using **R**, keeping\n", "however an eye on the parallel Python set ups. Similarly, if you are a\n", - "Python afecionado, feel free to explore R as well. Jupyter/Ipython\n", + "Python afecionado, feel free to explore **R** as well. Jupyter/Ipython\n", "notebook allows you to run **R** codes interactively in your\n", - "browser. The software library **R** is tuned to statistically analysis\n", - "and allows for an easy usage of the tools we will discuss in these\n", - "texts.\n", + "browser. The software library **R** is really tailored for statistical data analysis\n", + "and allows for an easy usage of the tools and algorithms we will discuss in these\n", + "lectures.\n", "\n", "To install **R** with Jupyter notebook \n", "[follow the link here](https://mpacer.org/maths/r-kernel-for-ipython-notebook)\n", @@ -472,13 +605,13 @@ "languages.\n", "\n", "To add more entropy, **cython** can also be used when running your\n", - "notebooks. It means that Python with the Jupyter/IPython notebook\n", + "notebooks. It means that Python with the jupyter notebook\n", "setup allows you to integrate widely popular softwares and tools for\n", "scientific computing. Similarly, the \n", "[Numba Python package](https://numba.pydata.org/) delivers increased performance\n", "capabilities with minimal rewrites of your codes. With its\n", "versatility, including symbolic operations, Python offers a unique\n", - "computational environment. Your Jupyter/IPython notebook can easily be\n", + "computational environment. Your jupyter notebook can easily be\n", "converted into a nicely rendered **PDF** file or a Latex file for\n", "further processing. For example, convert to latex as" ] @@ -498,1538 +631,13 @@ "\n", "Finally, if you wish to use the light mark-up language \n", "[doconce](https://github.com/hplgit/doconce) you can convert a standard ascii text file into various HTML \n", - "formats, ipython notebooks, latex files, pdf files etc with minimal edits.\n", + "formats, ipython notebooks, latex files, pdf files etc with minimal edits. These lectures were generated using **doconce**.\n", "\n", "\n", - "## Simple linear regression model using **scikit-learn**\n", "\n", - "We start with perhaps our simplest possible example, using **scikit-learn** to perform linear regression analysis on a data set produced by us. \n", - "What follows is a simple Python code where we have defined function $y$ in terms of the variable $x$. Both are defined as vectors of dimension $1\\times 100$. The entries to the vector $\\hat{x}$ are given by random numbers generated with a uniform distribution with entries $x_i \\in [0,1]$ (more about probability distribution functions later). These values are then used to define a function $y(x)$ (tabulated again as a vector) with a linear dependence on $x$ plus a random noise added via the normal distribution.\n", + "## Numpy examples and Important Matrix and vector handling packages\n", "\n", - "\n", - "The Numpy functions are imported used the **import numpy as np**\n", - "statement and the random number generator for the uniform distribution\n", - "is called using the function **np.random.rand()**, where we specificy\n", - "that we want $100$ random variables. Using Numpy we define\n", - "automatically an array with the specified number of elements, $100$ in\n", - "our case. With the Numpy function **randn()** we can compute random\n", - "numbers with the normal distribution (mean value $\\mu$ equal to zero and\n", - "variance $\\sigma^2$ set to one) and produce the values of $y$ assuming a linear\n", - "dependence as function of $x$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "y = 2x+N(0,1),\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "where $N(0,1)$ represents random numbers generated by the normal\n", - "distribution. From **scikit-learn** we import then the\n", - "**LinearRegression** functionality and make a prediction $\\tilde{y} =\n", - "\\alpha + \\beta x$ using the function **fit(x,y)**. We call the set of\n", - "data $(\\hat{x},\\hat{y})$ for our training data. The Python package\n", - "**scikit-learn** has also a functionality which extracts the above\n", - "fitting parameters $\\alpha$ and $\\beta$ (see below). Later we will\n", - "distinguish between training data and test data.\n", - "\n", - "For plotting we use the Python package\n", - "[matplotlib](https://matplotlib.org/) which produces publication\n", - "quality figures. Feel free to explore the extensive\n", - "[gallery](https://matplotlib.org/gallery/index.html) of examples. In\n", - "this example we plot our original values of $x$ and $y$ as well as the\n", - "prediction **ypredict** ($\\tilde{y}$), which attempts at fitting our\n", - "data with a straight line.\n", - "\n", - "The Python code follows here." - ] - }, - { - "cell_type": "code", - "execution_count": 1, - "metadata": { - "collapsed": false - }, - "outputs": [], - "source": [ - "%matplotlib inline\n", - "\n", - "# Importing various packages\n", - "import numpy as np\n", - "import matplotlib.pyplot as plt\n", - "from sklearn.linear_model import LinearRegression\n", - "\n", - "x = np.random.rand(100,1)\n", - "y = 2*x+np.random.randn(100,1)\n", - "linreg = LinearRegression()\n", - "linreg.fit(x,y)\n", - "xnew = np.array([[0],[1]])\n", - "ypredict = linreg.predict(xnew)\n", - "\n", - "plt.plot(xnew, ypredict, \"r-\")\n", - "plt.plot(x, y ,'ro')\n", - "plt.axis([0,1.0,0, 5.0])\n", - "plt.xlabel(r'$x$')\n", - "plt.ylabel(r'$y$')\n", - "plt.title(r'Simple Linear Regression')\n", - "plt.show()" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "This example serves several aims. It allows us to demonstrate several\n", - "aspects of data analysis and later machine learning algorithms. The\n", - "immediate visualization shows that our linear fit is not\n", - "impressive. It goes through the data points, but there are many\n", - "outliers which are not reproduced by our linear regression. We could\n", - "now play around with this small program and change for example the\n", - "factor in front of $x$ and the normal distribution. Try to change the\n", - "function $y$ to" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "y = 10x+0.01 \\times N(0,1),\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "where $x$ is defined as before. Does the fit look better? Indeed, by\n", - "reducing the role of the normal distribution we see immediately that\n", - "our linear prediction seemingly reproduces better the training\n", - "set. However, this testing 'by the eye' is obviouly not satisfactory in the\n", - "long run. Here we have only defined the training data and our model, and \n", - "have not discussed a more rigorous approach to the **cost** function.\n", - "\n", - "We need more rigorous criteria in defining whether we have succeeded or\n", - "not in modeling our training data. You will be surprised to see that\n", - "many scientists seldomly venture beyond this 'by the eye' approach. A\n", - "standard approach for the *cost* function is the so-called $\\chi^2$\n", - "function" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "\\chi^2 = \\frac{1}{n}\n", - "\\sum_{i=0}^{n-1}\\frac{(y_i-\\tilde{y}_i)^2}{\\sigma_i^2},\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "where $\\sigma_i^2$ is the variance (to be defined later) of the entry\n", - "$y_i$. We may not know the explicit value of $\\sigma_i^2$, it serves\n", - "however the aim of scaling the equations and make the cost function\n", - "dimensionless. \n", - "\n", - "Minimizing the cost function is a central aspect of\n", - "our discussions to come. Finding its minima as function of the model\n", - "parameters ($\\alpha$ and $\\beta$ in our case) will be a recurring\n", - "theme in these series of lectures. Essentially all machine learning\n", - "algorithms we will discuss center around the minimization of the\n", - "chosen cost function. This depends in turn on our specific\n", - "model for describing the data, a typical situation in supervised\n", - "learning. Automatizing the search for the minima of the cost function is a\n", - "central ingredient in all algorithms. Typical methods which are\n", - "employed are various variants of **gradient** methods. These will be\n", - "discussed in more detail later. Again, you'll be surprised to hear that\n", - "many practitioners minimize the above function ''by the eye', popularly dubbed as \n", - "'chi by the eye'. That is, change a parameter and see (visually and numerically) that \n", - "the $\\chi^2$ function becomes smaller. \n", - "\n", - "There are many ways to define the cost function. A simpler approach is to look at the relative difference between the training data and the predicted data, that is we define \n", - "the relative error as" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "\\epsilon_{\\mathrm{relative}}= \\frac{\\vert \\hat{y} -\\hat{\\tilde{y}}\\vert}{\\vert \\hat{y}\\vert}.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "We can modify easily the above Python code and plot the relative instead" - ] - }, - { - "cell_type": "code", - "execution_count": 2, - "metadata": { - "collapsed": false - }, - "outputs": [], - "source": [ - "import numpy as np\n", - "import matplotlib.pyplot as plt\n", - "from sklearn.linear_model import LinearRegression\n", - "\n", - "x = np.random.rand(100,1)\n", - "y = 5*x+0.01*np.random.randn(100,1)\n", - "linreg = LinearRegression()\n", - "linreg.fit(x,y)\n", - "ypredict = linreg.predict(x)\n", - "\n", - "plt.plot(x, np.abs(ypredict-y)/abs(y), \"ro\")\n", - "plt.axis([0,1.0,0.0, 0.5])\n", - "plt.xlabel(r'$x$')\n", - "plt.ylabel(r'$\\epsilon_{\\mathrm{relative}}$')\n", - "plt.title(r'Relative error')\n", - "plt.show()" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "Depending on the parameter in front of the normal distribution, we may\n", - "have a small or larger relative error. Try to play around with\n", - "different training data sets and study (graphically) the value of the\n", - "relative error.\n", - "\n", - "As mentioned above, **scikit-learn** has an impressive functionality.\n", - "We can for example extract the values of $\\alpha$ and $\\beta$ and\n", - "their error estimates, or the variance and standard deviation and many\n", - "other properties from the statistical data analysis. \n", - "\n", - "Here we show an\n", - "example of the functionality of scikit-learn." - ] - }, - { - "cell_type": "code", - "execution_count": 3, - "metadata": { - "collapsed": false - }, - "outputs": [], - "source": [ - "import numpy as np \n", - "import matplotlib.pyplot as plt \n", - "from sklearn.linear_model import LinearRegression \n", - "from sklearn.metrics import mean_squared_error, r2_score, mean_squared_log_error, mean_absolute_error\n", - "\n", - "x = np.random.rand(100,1)\n", - "y = 2.0+ 5*x+0.5*np.random.randn(100,1)\n", - "linreg = LinearRegression()\n", - "linreg.fit(x,y)\n", - "ypredict = linreg.predict(x)\n", - "print('The intercept alpha: \\n', linreg.intercept_)\n", - "print('Coefficient beta : \\n', linreg.coef_)\n", - "# The mean squared error \n", - "print(\"Mean squared error: %.2f\" % mean_squared_error(y, ypredict))\n", - "# Explained variance score: 1 is perfect prediction \n", - "print('Variance score: %.2f' % r2_score(y, ypredict))\n", - "# Mean squared log error \n", - "print('Mean squared log error: %.2f' % mean_squared_log_error(y, ypredict) )\n", - "# Mean absolute error \n", - "print('Mean absolute error: %.2f' % mean_absolute_error(y, ypredict))\n", - "plt.plot(x, ypredict, \"r-\")\n", - "plt.plot(x, y ,'ro')\n", - "plt.axis([0.0,1.0,1.5, 7.0])\n", - "plt.xlabel(r'$x$')\n", - "plt.ylabel(r'$y$')\n", - "plt.title(r'Linear Regression fit ')\n", - "plt.show()" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "The function **coef** gives us the parameter $\\beta$ of our fit while **intercept** yields \n", - "$\\alpha$. Depending on the constant in front of the normal distribution, we get values near or far from $alpha =2$ and $\\beta =5$. Try to play around with different parameters in front of the normal distribution. The function **meansquarederror** gives us the mean square error, a risk metric corresponding to the expected value of the squared (quadratic) error or loss defined as" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "MSE(\\hat{y},\\hat{\\tilde{y}}) = \\frac{1}{n}\n", - "\\sum_{i=0}^{n-1}(y_i-\\tilde{y}_i)^2,\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "The smaller the value, the better the fit. Ideally we would like to\n", - "have an MSE equal zero. The attentive reader has probably recognized\n", - "this function as being similar to the $\\chi^2$ function defined above.\n", - "\n", - "The **r2score** function computes $R^2$, the coefficient of\n", - "determination. It provides a measure of how well future samples are\n", - "likely to be predicted by the model. Best possible score is 1.0 and it\n", - "can be negative (because the model can be arbitrarily worse). A\n", - "constant model that always predicts the expected value of $\\hat{y}$,\n", - "disregarding the input features, would get a $R^2$ score of $0.0$.\n", - "\n", - "If $\\tilde{\\hat{y}}_i$ is the predicted value of the $i-th$ sample and $y_i$ is the corresponding true value, then the score $R^2$ is defined as" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "R^2(\\hat{y}, \\tilde{\\hat{y}}) = 1 - \\frac{\\sum_{i=0}^{n - 1} (y_i - \\tilde{y}_i)^2}{\\sum_{i=0}^{n - 1} (y_i - \\bar{y})^2},\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "where we have defined the mean value of $\\hat{y}$ as" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "\\bar{y} = \\frac{1}{n} \\sum_{i=0}^{n - 1} y_i.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "Another quantity will meet again in our discussions of regression analysis is \n", - " mean absolute error (MAE), a risk metric corresponding to the expected value of the absolute error loss or what we call the $l1$-norm loss. In our discussion above we presented the relative error.\n", - "The MAE is defined as follows" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "\\text{MAE}(\\hat{y}, \\hat{\\tilde{y}}) = \\frac{1}{n} \\sum_{i=0}^{n-1} \\left| y_i - \\tilde{y}_i \\right|.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "Finally we present the \n", - "squared logarithmic (quadratic) error" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "\\text{MSLE}(\\hat{y}, \\hat{\\tilde{y}}) = \\frac{1}{n} \\sum_{i=0}^{n - 1} (\\log_e (1 + y_i) - \\log_e (1 + \\tilde{y}_i) )^2,\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "where $\\log_e (x)$ stands for the natural logarithm of $x$. This error\n", - "estimate is best to use when targets having exponential growth, such\n", - "as population counts, average sales of a commodity over a span of\n", - "years etc. \n", - "\n", - "We will discuss in more\n", - "detail these and other functions in the various lectures. We conclude this part with another example. Instead of \n", - "a linear $x$-dependence we study now a cubic polynomial and use the polynomial regression analysis tools of scikit-learn." - ] - }, - { - "cell_type": "code", - "execution_count": 4, - "metadata": { - "collapsed": false - }, - "outputs": [], - "source": [ - "import matplotlib.pyplot as plt\n", - "import numpy as np\n", - "import random\n", - "from sklearn.linear_model import Ridge\n", - "from sklearn.preprocessing import PolynomialFeatures\n", - "from sklearn.pipeline import make_pipeline\n", - "from sklearn.linear_model import LinearRegression\n", - "\n", - "x=np.linspace(0.02,0.98,200)\n", - "noise = np.asarray(random.sample((range(200)),200))\n", - "y=x**3*noise\n", - "yn=x**3*100\n", - "poly3 = PolynomialFeatures(degree=3)\n", - "X = poly3.fit_transform(x[:,np.newaxis])\n", - "clf3 = LinearRegression()\n", - "clf3.fit(X,y)\n", - "\n", - "Xplot=poly3.fit_transform(x[:,np.newaxis])\n", - "poly3_plot=plt.plot(x, clf3.predict(Xplot), label='Cubic Fit')\n", - "plt.plot(x,yn, color='red', label=\"True Cubic\")\n", - "plt.scatter(x, y, label='Data', color='orange', s=15)\n", - "plt.legend()\n", - "plt.show()\n", - "\n", - "def error(a):\n", - " for i in y:\n", - " err=(y-yn)/yn\n", - " return abs(np.sum(err))/len(err)\n", - "\n", - "print (error(y))" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "Similarly, using **R**, we can perform similar studies. The following **R** code illustrates this.\n", - "(more details on **R** will be inserted later).\n", - "\n", - "## Non-Linear Least squares in R" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - " set.seed(1485)\n", - " len = 24\n", - " x = runif(len)\n", - " y = x^3+rnorm(len, 0,0.06)\n", - " ds = data.frame(x = x, y = y)\n", - " str(ds)\n", - " plot( y ~ x, main =\"Known cubic with noise\")\n", - " s = seq(0,1,length =100)\n", - " lines(s, s^3, lty =2, col =\"green\")\n", - " m = nls(y ~ I(x^power), data = ds, start = list(power=1), trace = T)\n", - " class(m)\n", - " summary(m)\n", - " power = round(summary(m)$coefficients[1], 3)\n", - " power.se = round(summary(m)$coefficients[2], 3)\n", - " plot(y ~ x, main = \"Fitted power model\", sub = \"Blue: fit; green: known\")\n", - " s = seq(0, 1, length = 100)\n", - " lines(s, s^3, lty = 2, col = \"green\")\n", - " lines(s, predict(m, list(x = s)), lty = 1, col = \"blue\")\n", - " text(0, 0.5, paste(\"y =x^ (\", power, \" +/- \", power.se, \")\", sep = \"\"), pos = 4)\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "In our lectures on regression analysis (and other ones as well), we will discuss in more details various **R** functionalities. \n", - "\n", - "\n", - "Another useful Python package is\n", - "[pandas](https://pandas.pydata.org/), which is an open source library\n", - "providing high-performance, easy-to-use data structures and data\n", - "analysis tools for Python. The following simple example shows how we can, in an easy way make tables of our data. Here we define a data set which includes names, city of residence and age, and displays the data in an easy to read way. We will see repeated use of **pandas**, in particular in connection with classification of data." - ] - }, - { - "cell_type": "code", - "execution_count": 5, - "metadata": { - "collapsed": false - }, - "outputs": [], - "source": [ - "import pandas as pd\n", - "from IPython.display import display\n", - "data = {'Name': [\"John\", \"Anna\", \"Peter\", \"Linda\"], 'Location': [\"Nairobi\", \"Napoli\", \"London\", \"Buenos Aires\"], 'Age':[51, 21, 34, 45]}\n", - "data_pandas = pd.DataFrame(data)\n", - "display(data_pandas)" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "## Examples\n", - "\n", - "We present here several examples, with pertinent Python codes that we\n", - "will use to illustrate various machine learning methods and ways to\n", - "analyze, from simple to complex, various data sets. Many of these\n", - "examples allow us to generate the data we want to analyze, following\n", - "much of the same philosophy we discussed above when\n", - "fitting various polynomials.\n", - "\n", - "We start with a simple exponential growth model that is meant to mimick an ecoli lab experiment.\n", - "We can easily model this system and then produce the data used to train various machine learning algorithms.\n", - "Another model from the life sciences is the so-called predator-prey model from ecology. Thereafter we present \n", - "a simple model for financial transactions before moving to a random walk model and ending with \n", - "the simulation of velocities of a non-interacting atom or molecule confined to move in a one-dimensional region.\n", - "\n", - "\n", - "### Ecoli lab experiment\n", - "\n", - "A typical pattern seen in population models is that the population grows faster and faster. [Why? Is there an underlying (general) mechanism](http://www.zo.utexas.edu/courses/Thoc/PopGrowth.html)?\n", - "Here we will construct a model for cell growth based on a simple difference equation for the growth. We make the following assumptions\n", - "\n", - "1. Cells divide after $T$ seconds on average (one generation)\n", - "\n", - "2. $2N$ celles divide into twice as many new cells $\\Delta N$ in a time\n", - " interval $\\Delta t$ as $N$ cells would: $\\Delta N \\propto N$\n", - "\n", - "3. $N$ cells result in twice as many new individuals $\\Delta N$ in\n", - " time $2\\Delta t$ as in time $\\Delta t$: $\\Delta N \\propto\\Delta t$\n", - "\n", - "4. Same proportionality with respect to death \n", - "\n", - "5. Proposed model: $\\Delta N = b\\Delta t N - d\\Delta tN$ for some unknown\n", - " constants $b$ (births) and $d$ (deaths)\n", - "\n", - "6. Describe evolution in discrete time: $t_n=n\\Delta t$\n", - "\n", - "7. Program-friendly notation: $N$ at $t_n$ is $N^n$\n", - "\n", - "8. Math model: $N^{n+1} = N^n + r\\Delta t\\, N$ (with $\\ r=b-d$)\n", - "\n", - "9. Program model: `N[n+1] = N[n] + r*dt*N[n]`\n", - "\n", - "The difference equation can be programmed in a simple way, and in order to get started we\n", - "set $r=1.5$, $N^0=1$, $\\Delta t=0.5$. The program reads" - ] - }, - { - "cell_type": "code", - "execution_count": 6, - "metadata": { - "collapsed": false - }, - "outputs": [], - "source": [ - "import numpy as np\n", - "\n", - "t = np.linspace(0, 10, 21) # 20 intervals in [0, 10]\n", - "dt = t[1] - t[0]\n", - "N = np.zeros(t.size)\n", - "N[0] = 1\n", - "r = 0.5\n", - "\n", - "for n in range(0, N.size-1, 1):\n", - " N[n+1] = N[n] + r*dt*N[n]\n", - " print('N[%d]=%.1f' % (n+1, N[n+1]))" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "and it generates the following output" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - " N[1]=1.2\n", - " N[2]=1.6\n", - " N[3]=2.0\n", - " N[4]=2.4\n", - " N[5]=3.1\n", - " N[6]=3.8\n", - " N[7]=4.8\n", - " N[8]=6.0\n", - " N[9]=7.5\n", - " N[10]=9.3\n", - " N[11]=11.6\n", - " N[12]=14.6\n", - " N[13]=18.2\n", - " N[14]=22.7\n", - " N[15]=28.4\n", - " N[16]=35.5\n", - " N[17]=44.4\n", - " N[18]=55.5\n", - " N[19]=69.4\n", - " N[20]=86.7\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "This forms our data which later will define our training set. \n", - "In this case we defined the value of the parameter $r$. We could alternatively assume that we just received the \n", - "above data file and where asked to find $r$. How can we estimate $r$ from data? This will be one of our tasks later.\n", - "\n", - "We can use the difference equation with the experimental data" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "N^{n+1} = N^n + r\\Delta t N^n\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "Suppose now that $N^{n+1}$ and $N^n$ are known from data. Then we could solve with respect to $r$ as follows" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "r = \\frac{N^{n+1}-N^n}{N^n\\Delta t}\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "Suppose we set $t_1=600$, $t_2=1200$,\n", - "$N^1=140$ and $N^2=250$. \n", - "The following code plots the data" - ] - }, - { - "cell_type": "code", - "execution_count": 7, - "metadata": { - "collapsed": false - }, - "outputs": [], - "source": [ - "import numpy as np\n", - "import matplotlib.pyplot as plt\n", - "\n", - "# Estimate r\n", - "data = np.loadtxt('ecoli.csv', delimiter=',')\n", - "t_e = data[:,0]\n", - "N_e = data[:,1]\n", - "i = 2 # Data point (i,i+1) used to estimate r\n", - "r = (N_e[i+1] - N_e[i])/(N_e[i]*(t_e[i+1] - t_e[i]))\n", - "print('Estimated r=%.5f' % r)\n", - "# Can experiment with r values and see if the model can\n", - "# match the data better\n", - "T = 1200 # cell can divide after T sec\n", - "t_max = 5*T # 5 generations in experiment\n", - "t = np.linspace(0, t_max, 1000)\n", - "dt = t[1] - t[0]\n", - "N = np.zeros(t.size)\n", - "\n", - "N[0] = 100\n", - "for n in range(0, len(t)-1, 1):\n", - " N[n+1] = N[n] + r*dt*N[n]\n", - "\n", - "plt.plot(t, N, 'r-', t_e, N_e, 'bo')\n", - "plt.xlabel('time [s]'); plt.ylabel('N')\n", - "plt.legend(['model', 'experiment'], loc='upper left')\n", - "plt.show()" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "We can then change the parameter $r$ in the program and play around to make a better fit. By now we know that this\n", - "'search bythe eye' approach is not the most optimal one. \n", - "\n", - "\n", - "### Predator-Prey model from ecology\n", - "\n", - "The population dynamics of a simple predator-prey system is a\n", - "classical example shown in many biology textbooks when ecological\n", - "systems are discussed. The system contains all elements of the\n", - "scientific method:\n", - "\n", - " * The set up of a specific hypothesis combined with\n", - "\n", - " * the experimental methods needed (one can study existing data or perform experiments)\n", - "\n", - " * analyzing and interpreting the data and performing further experiments if needed\n", - "\n", - " * trying to extract general behaviors and extract eventual laws or patterns\n", - "\n", - " * develop mathematical relations for the uncovered regularities/laws and test these by per forming new experiments\n", - "\n", - "Lots of data about populations of hares and lynx collected from furs in Hudson Bay, Canada, are available. It is known that the populations oscillate. Why?\n", - "Here we start by\n", - "\n", - "1. plotting the data\n", - "\n", - "2. derive a simple model for the population dynamics\n", - "\n", - "3. (fitting parameters in the model to the data)\n", - "\n", - "4. using the model predict the evolution other predator-pray systems\n", - "\n", - "Most mammalian predators rely on a variety of prey, which complicates mathematical modeling; however, a few predators have become highly specialized and seek almost exclusively a single prey species. An example of this simplified predator-prey interaction is seen in Canadian northern forests, where the populations of the lynx and the snowshoe hare are intertwined in a life and death struggle.\n", - "\n", - "One reason that this particular system has been so extensively studied is that the Hudson Bay company kept careful records of all furs from the early 1800s into the 1900s. The records for the furs collected by the Hudson Bay company showed distinct oscillations (approximately 12 year periods), suggesting that these species caused almost periodic fluctuations of each other's populations. The table here shows data from 1900 to 1920.\n", - "\n", - "\n", - "\n", - "\n", - "\n", - "\n", - "\n", - "\n", - "\n", - "\n", - "\n", - "\n", - "\n", - "\n", - "\n", - "\n", - "\n", - "\n", - "\n", - "\n", - "\n", - "\n", - "\n", - "\n", - "\n", - "\n", - "\n", - "\n", - "\n", - "
Year Hares (x1000) Lynx (x1000)
1900 30.0 4.0
1901 47.2 6.1
1902 70.2 9.8
1903 77.4 35.2
1904 36.3 59.4
1905 20.6 41.7
1906 18.1 19.0
1907 21.4 13.0
1908 22.0 8.3
1909 25.4 9.1
1910 27.1 7.4
1911 40.3 8.0
1912 57 12.3
1913 76.6 19.5
1914 52.3 45.7
1915 19.5 51.1
1916 11.2 29.7
1917 7.6 15.8
1918 14.6 9.7
1919 16.2 10.1
1920 24.7 8.6
" - ] - }, - { - "cell_type": "code", - "execution_count": 8, - "metadata": { - "collapsed": false - }, - "outputs": [], - "source": [ - "import numpy as np\n", - "from matplotlib import pyplot as plt\n", - "\n", - "# Load in data file\n", - "data = np.loadtxt('src/Hudson_Bay.csv', delimiter=',', skiprows=1)\n", - "# Make arrays containing x-axis and hares and lynx populations\n", - "year = data[:,0]\n", - "hares = data[:,1]\n", - "lynx = data[:,2]\n", - "\n", - "plt.plot(year, hares ,'b-+', year, lynx, 'r-o')\n", - "plt.axis([1900,1920,0, 100.0])\n", - "plt.xlabel(r'Year')\n", - "plt.ylabel(r'Numbers of hares and lynx ')\n", - "plt.legend(('Hares','Lynx'), loc='upper right')\n", - "plt.title(r'Population of hares and lynx from 1900-1920 (x1000)}')\n", - "plt.savefig('Hudson_Bay_data.pdf')\n", - "plt.savefig('Hudson_Bay_data.png')\n", - "plt.show()" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "\n", - "\n", - "\n", - "

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

\n", - "\n", - "\n", - "\n", - "\n", - "\n", - "We will later perform a least-square fitting. Then we can find optimal\n", - "values for the parameters $a$, $b$, $d$, $c$. In our calculations here\n", - "we set $a=0.4807$, $b=0.02482$, $d=0.9272$ and $c=0.02756$. These\n", - "parameters result in a slightly modified initial conditions, namely\n", - "$H(0) = 34.91$ and $L(0)=3.857$. \n", - "\n", - "\n", - "The following Python code demonstrates how we can use linear regression to fit for example the population of lynx.\n", - "Similarly, we have also used a decision tree algorithm to fit the lynx population data. As expected, the linear regression is not exactly impressive" - ] - }, - { - "cell_type": "code", - "execution_count": 10, - "metadata": { - "collapsed": false - }, - "outputs": [], - "source": [ - "import numpy as np\n", - "import matplotlib.pyplot as plt\n", - "from IPython.display import display\n", - "import sklearn\n", - "from sklearn.linear_model import LinearRegression\n", - "from sklearn.tree import DecisionTreeRegressor\n", - "\n", - "\n", - "data = np.loadtxt('src/Hudson_Bay.csv', delimiter=',', skiprows=1)\n", - "x = data[:,0]\n", - "y = data[:,1]\n", - "line = np.linspace(1900,1920,1000,endpoint=False).reshape(-1,1)\n", - "reg = DecisionTreeRegressor(min_samples_split=3).fit(x.reshape(-1,1),y.reshape(-1,1))\n", - "plt.plot(line, reg.predict(line), label=\"decision tree\")\n", - "regline = LinearRegression().fit(x.reshape(-1,1),y.reshape(-1,1))\n", - "plt.plot(line, regline.predict(line), label= \"Linear Regression\")\n", - "plt.plot(x, y, label= \"Linear Regression\")\n", - "plt.show()" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "The similar code for linear regression in **R** reads (more details to come)" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - " HudsonBay = read.csv(\"src/Hudson_Bay.csv\",header=T)\n", - " fix(HudsonBay)\n", - " dim(HudsonBay)\n", - " names(HudsonBay)\n", - " plot(HudsonBay$Year, HudsonBay$Hares..x1000.)\n", - " attach(HudsonBay)\n", - " plot(Year, Hares..x1000.)\n", - " plot(Year, Hares..x1000., col=\"red\", varwidth=T, xlab=\"Years\", ylab=\"Haresx 1000\")\n", - " summary(HudsonBay)\n", - " summary(Hares..x1000.)\n", - " library(MASS)\n", - " library(ISLR)\n", - " scatter.smooth(x=Year, y = Hares..x1000.)\n", - " linearMod = lm(Hares..x1000. ~ Year)\n", - " print(linearMod)\n", - " summary(linearMod)\n", - " plot(linearMod)\n", - " confint(linearMod)\n", - " predict(linearMod,data.frame(Year=c(1910,1914,1920)),interval=\"confidence\")\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "### Simulating financial transactions\n", - "\n", - "The aim here is to simulate financial transactions among financial agents\n", - "using Monte Carlo methods. The final goal is to extract a distribution of income as function\n", - "of the income $m$. From Pareto's work ([V. Pareto, 1897](http://www.institutcoppet.org/2012/05/08/cours-deconomie-politique-1896-de-vilfredo-pareto)) it is known from empirical studies\n", - "that the higher end of the distribution of money follows a distribution" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "w_m\\propto m^{-1-\\alpha},\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "with $\\alpha\\in [1,2]$. We will here follow the analysis made by [Patriarca and collaborators](http://www.sciencedirect.com/science/article/pii/S0378437104004327). \n", - "\n", - "Here we will study numerically the relation between the micro-dynamic relations among financial \n", - "agents and the resulting macroscopic money distribution.\n", - "\n", - "We assume we have $N$ agents that exchange money in pairs $(i,j)$. We assume also that all agents\n", - "start with the same amount of money $m_0 > 0$. At a given 'time step', we choose randomly a pair\n", - "of agents $(i,j)$ and let a transaction take place. This means that agent $i$'s money $m_i$ changes\n", - "to $m_i'$ and similarly we have $m_j\\rightarrow m_j'$. \n", - "Money is conserved during a transaction, meaning that" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "\n", - "
\n", - "\n", - "$$\n", - "\\begin{equation}\n", - " m_i+m_j=m_i'+m_j'.\n", - "\\label{eq:conserve} \\tag{1}\n", - "\\end{equation}\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "The change is done via a random reassignement (a random number) $\\epsilon$, meaning that" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "m_i' = \\epsilon(m_i+m_j),\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "leading to" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "m_j'= (1-\\epsilon)(m_i+m_j).\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "The number $\\epsilon$ is extracted from a uniform distribution.\n", - "In this simple model, no agents are left with a debt, that is $m\\ge 0$.\n", - "Due to the conservation law above, one can show that the system relaxes toward an equilibrium\n", - "state given by a Gibbs distribution" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "w_m=\\beta \\exp{(-\\beta m)},\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "with" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "\\beta = \\frac{1}{\\langle m\\rangle},\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "and $\\langle m\\rangle=\\sum_i m_i/N=m_0$, the average money.\n", - "It means that after equilibrium has been reached that the majority of agents is left with a small\n", - "number of money, while the number of richest agents, those with $m$ larger than a specific value $m'$,\n", - "exponentially decreases with $m'$.\n", - "\n", - "We assume that we have $N=500$ agents. In each simulation, we need a sufficiently large number of transactions, say $10^7$. Our aim is find the final equilibrium distribution $w_m$. In order to do that we would need\n", - "several runs of the above simulations, at least $10^3-10^4$ runs (experiments).\n", - "\n", - "Our task is to first set up an algorithm which simulates the above transactions with an initial\n", - " amount $m_0$.\n", - " The challenge here is to figure out a Monte Carlo simulation based on the\n", - " above equations.\n", - " You will in particular need to make an algorithm which sets up a histogram as function of $m$.\n", - " This histogram contains the number of times a value $m$ is registered and represents\n", - " $w_m\\Delta m$. You will need to set up a value for the interval $\\Delta m$ (typically $0.01-0.05$).\n", - " That means you need to account for the number of times you register an income in the interval\n", - " $m,m+\\Delta m$. The number of times you register this income, represents the value that enters the histogram." - ] - }, - { - "cell_type": "code", - "execution_count": 11, - "metadata": { - "collapsed": false - }, - "outputs": [], - "source": [ - "#!/usr/bin/env python\n", - "import numpy as np\n", - "import matplotlib.mlab as mlab\n", - "import matplotlib.pyplot as plt\n", - "import random\n", - "\n", - "# initialize the rng with a seed\n", - "random.seed()\n", - "# Hard coding of input parameters\n", - "Agents = 500\n", - "MCcounts = 1000\n", - "Transactions = 100000\n", - "startMoney = 1.0\n", - "Lambda = 0.0\n", - "FinancialAgents = startMoney*np.ones(Agents)\n", - "for i in range (1, MCcounts, 1):\n", - " for j in range (1, Transactions, 1):\n", - " agent_i = int(Agents*random.random())\n", - " agent_j = int(Agents*random.random())\n", - " epsilon = random.random()\n", - " if agent_i != agent_j:\n", - " m1 = Lambda*FinancialAgents[agent_i] + (1-Lambda)*epsilon*(FinancialAgents[agent_i] + FinancialAgents[agent_j])\n", - " m2 = Lambda*FinancialAgents[agent_j] + (1-Lambda)*(1-epsilon)*(FinancialAgents[agent_i] + FinancialAgents[agent_j])\n", - " FinancialAgents[agent_i] = m1\n", - " FinancialAgents[agent_j] = m2\n", - "\n", - "# the histogram of the data\n", - "n, bins, patches = plt.hist(FinancialAgents, 50, facecolor='green')\n", - "\n", - "plt.xlabel('$x$')\n", - "plt.ylabel('Distribution of wealth')\n", - "plt.title(r'Money')\n", - "plt.axis([0, 10, 0, 500])\n", - "plt.grid(True)\n", - "plt.show()" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "We can then change our model to allow for a saving criterion, meaning that the agents save\n", - " a fraction $\\lambda$ of the money they have before the transaction is made. The final distribution will then no longer be given by Gibbs distribution. It could also include a taxation on financial transactions.\n", - "\n", - " The conservation law of Eq. ([eq:conserve](#eq:conserve)) holds, but the money to be shared in a transaction between\n", - " agent $i$ and agent $j$ is now $(1-\\lambda)(m_i+m_j)$. This means that we have" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "m_i' = \\lambda m_i+\\epsilon(1-\\lambda)(m_i+m_j),\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "and" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "m_j' = \\lambda m_j+(1-\\epsilon)(1-\\lambda)(m_i+m_j),\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "which can be written as" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "m_i'=m_i+\\delta m\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "and" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "m_j'=m_j-\\delta m,\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "with" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "\\delta m=(1-\\lambda)(\\epsilon m_j-(1-\\epsilon)m_i),\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "showing how money is conserved during a transaction.\n", - " Select values of $\\lambda =0.25,0.5$ and $\\lambda=0.9$ and try to extract the corresponding\n", - " equilibrium distributions and compare these with the Gibbs distribution. We will use this model to \n", - "extract a parametrization of the above curves, see for example [Patriarca and collaborators](http://www.sciencedirect.com/science/article/pii/S0378437104004327).\n", - "\n", - "\n", - "### Particle in one dimension and velocity distribution" - ] - }, - { - "cell_type": "code", - "execution_count": 12, - "metadata": { - "collapsed": false - }, - "outputs": [], - "source": [ - "# Program to test the Metropolis algorithm with one particle at given temp in one dimension\n", - "import numpy as np\n", - "import matplotlib.mlab as mlab\n", - "import matplotlib.pyplot as plt\n", - "import random\n", - "from math import sqrt, exp, log\n", - "# initialize the rng with a seed\n", - "random.seed()\n", - "# Hard coding of input parameters\n", - "MCcycles = 100000\n", - "Temperature = 2.0\n", - "beta = 1./Temperature\n", - "InitialVelocity = -2.0\n", - "CurrentVelocity = InitialVelocity\n", - "Energy = 0.5*InitialVelocity*InitialVelocity\n", - "VelocityRange = 10*sqrt(Temperature)\n", - "VelocityStep = 2*VelocityRange/10.\n", - "AverageEnergy = Energy\n", - "AverageEnergy2 = Energy*Energy\n", - "VelocityValues = np.zeros(MCcycles)\n", - "# The Monte Carlo sampling with Metropolis starts here\n", - "for i in range (1, MCcycles, 1):\n", - " TrialVelocity = CurrentVelocity + (2.0*random.random() - 1.0)*VelocityStep\n", - " EnergyChange = 0.5*(TrialVelocity*TrialVelocity -CurrentVelocity*CurrentVelocity);\n", - " if random.random() <= exp(-beta*EnergyChange):\n", - " CurrentVelocity = TrialVelocity\n", - " Energy += EnergyChange\n", - " VelocityValues[i] = CurrentVelocity\n", - " AverageEnergy += Energy\n", - " AverageEnergy2 += Energy*Energy\n", - "#Final averages\n", - "AverageEnergy = AverageEnergy/MCcycles\n", - "AverageEnergy2 = AverageEnergy2/MCcycles\n", - "Variance = AverageEnergy2 - AverageEnergy*AverageEnergy\n", - "print(AverageEnergy, Variance)\n", - "n, bins, patches = plt.hist(VelocityValues, 400, facecolor='green')\n", - "\n", - "plt.xlabel('$v$')\n", - "plt.ylabel('Velocity distribution P(v)')\n", - "plt.title(r'Velocity histogram at $k_BT=2$')\n", - "plt.axis([-5, 5, 0, 600])\n", - "plt.grid(True)\n", - "plt.show()" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "### Random walk model" - ] - }, - { - "cell_type": "code", - "execution_count": 13, - "metadata": { - "collapsed": false - }, - "outputs": [], - "source": [ - "import numpy as np\n", - "import matplotlib.pyplot as plt\n", - "from sklearn.preprocessing import PolynomialFeatures\n", - "from sklearn.linear_model import LinearRegression\n", - "\n", - "steps=250\n", - "\n", - "distance=0\n", - "x=0\n", - "distance_list=[]\n", - "steps_list=[]\n", - "while x\n", - "## Important Matrix and vector handling packages\n", - "\n", - "There are several central software packages for linear algebra and eigenvalue problems. Several of the more\n", + "There are several central software libraries for linear algebra and eigenvalue problems. Several of the more\n", "popular ones have been wrapped into ofter software packages like those from the widely used text **Numerical Recipes**. The original source codes in many of the available packages are often taken from the widely used\n", "software package LAPACK, which follows two other popular packages\n", "developed in the 1970s, namely EISPACK and LINPACK. We describe them shortly here.\n", @@ -2040,27 +648,7 @@ "\n", " * BLAS (I, II and III): (Basic Linear Algebra Subprograms) are routines that provide standard building blocks for performing basic vector and matrix operations. Blas I is vector operations, II vector-matrix operations and III matrix-matrix operations. Highly parallelized and efficient codes, all available for download from .\n", "\n", - "When dealing with matrices and vectors a central issue is memory\n", - "handling and allocation. If our code is written in Python the way we\n", - "declare these objects and the way they are handled, interpreted and\n", - "used by say a linear algebra library, requires codes that interface\n", - "our Python program with such libraries. For Python programmers,\n", - "**Numpy** is by now the standard Python package for numerical arrays in\n", - "Python as well as the source of functions which act on these\n", - "arrays. These functions span from eigenvalue solvers to functions that\n", - "compute the mean value, variance or the covariance matrix. If you are\n", - "not familiar with how arrays are handled in say Python or compiled\n", - "languages like C++ and Fortran, the sections in this chapter may be\n", - "useful. For C++ programmer, **Armadillo** is widely used library for\n", - "linear algebra and eigenvalue problems. In addition it offers a\n", - "convenient way to handle and organize arrays. We discuss this library\n", - "as well. Before we proceed we believe it may be convenient to repeat some basic features of \n", - " matrices and vectors.\n", - "\n", - "\n", - "## Basic Matrix Features\n", - "\n", - " Matrix properties reminder" + "## Basic Matrix Features" ] }, { @@ -2087,9 +675,6 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "## Basic Matrix Features\n", - "\n", - "\n", "The inverse of a matrix is defined by" ] }, @@ -2106,10 +691,6 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "## Basic Matrix Features\n", - "\n", - " Matrix Properties Reminder\n", - "\n", "\n", "\n", "\n", @@ -2124,7 +705,8 @@ "
Relations Name matrix elements
\n", "\n", "\n", - "## Some famous Matrices\n", + "\n", + "### Some famous Matrices\n", "\n", " * Diagonal if $a_{ij}=0$ for $i\\ne j$\n", "\n", @@ -2144,9 +726,9 @@ "\n", " * Banded, block upper triangular, block lower triangular....\n", "\n", - "## Basic Matrix Features\n", + "### More Basic Matrix Features\n", "\n", - " Some Equivalent Statements\n", + "Some Equivalent Statements\n", "For an $N\\times N$ matrix $\\mathbf{A}$ the following properties are all equivalent\n", "\n", " * If the inverse of $\\mathbf{A}$ exists, $\\mathbf{A}$ is nonsingular.\n", @@ -2167,13 +749,30 @@ }, { "cell_type": "code", - "execution_count": 14, + "execution_count": 1, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "import numpy as np" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Here follows a simple example where we set up an array of ten elements, all determined by random numbers drawn according to the normal distribution," + ] + }, + { + "cell_type": "code", + "execution_count": 2, "metadata": { "collapsed": false }, "outputs": [], "source": [ - "import numpy as np\n", "n = 10\n", "x = np.random.normal(size=n)\n", "print(x)" @@ -2183,13 +782,13 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "Here we have defined a vector $x$ with $n=10$ elements with its values given by the Normal distribution $N(0,1)$.\n", + "We defined a vector $x$ with $n=10$ elements with its values given by the Normal distribution $N(0,1)$.\n", "Another alternative is to declare a vector as follows" ] }, { "cell_type": "code", - "execution_count": 15, + "execution_count": 3, "metadata": { "collapsed": false }, @@ -2210,7 +809,7 @@ }, { "cell_type": "code", - "execution_count": 16, + "execution_count": 4, "metadata": { "collapsed": false }, @@ -2225,7 +824,7 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "Here we have used Numpy's unary function $np.log$. This function is\n", + "In the last example we used Numpy's unary function $np.log$. This function is\n", "highly tuned to compute array elements since the code is vectorized\n", "and does not require looping. We normaly recommend that you use the\n", "Numpy intrinsic functions instead of the corresponding **log** function\n", @@ -2236,7 +835,7 @@ }, { "cell_type": "code", - "execution_count": 17, + "execution_count": 5, "metadata": { "collapsed": false }, @@ -2255,12 +854,12 @@ "metadata": {}, "source": [ "We note that our code is much longer already and we need to import the **log** function from the **math** module. \n", - "The attentive reader will also notice that the output is $[1, 1, 2]$. Python interprets automacally our numbers as integers (like the **automatic** keyword in C++). To change this we could define our array elements to be double precision numbers as" + "The attentive reader will also notice that the output is $[1, 1, 2]$. Python interprets automagically our numbers as integers (like the **automatic** keyword in C++). To change this we could define our array elements to be double precision numbers as" ] }, { "cell_type": "code", - "execution_count": 18, + "execution_count": 6, "metadata": { "collapsed": false }, @@ -2280,7 +879,7 @@ }, { "cell_type": "code", - "execution_count": 19, + "execution_count": 7, "metadata": { "collapsed": false }, @@ -2300,7 +899,7 @@ }, { "cell_type": "code", - "execution_count": 20, + "execution_count": 8, "metadata": { "collapsed": false }, @@ -2316,13 +915,15 @@ "metadata": {}, "source": [ "## Matrices in Python\n", - "Having defined vectors, we are now ready to try out matrices. We can define a $3 \\times 3 $ real matrix $\\hat{A}$\n", - "as (recall that we user lowercase letters for vectors and uppercase letters for matrices)" + "\n", + "Having defined vectors, we are now ready to try out matrices. We can\n", + "define a $3 \\times 3 $ real matrix $\\hat{A}$ as (recall that we user\n", + "lowercase letters for vectors and uppercase letters for matrices)" ] }, { "cell_type": "code", - "execution_count": 21, + "execution_count": 9, "metadata": { "collapsed": false }, @@ -2342,7 +943,7 @@ }, { "cell_type": "code", - "execution_count": 22, + "execution_count": 10, "metadata": { "collapsed": false }, @@ -2363,7 +964,7 @@ }, { "cell_type": "code", - "execution_count": 23, + "execution_count": 11, "metadata": { "collapsed": false }, @@ -2384,7 +985,7 @@ }, { "cell_type": "code", - "execution_count": 24, + "execution_count": 12, "metadata": { "collapsed": false }, @@ -2406,7 +1007,7 @@ }, { "cell_type": "code", - "execution_count": 25, + "execution_count": 13, "metadata": { "collapsed": false }, @@ -2428,7 +1029,7 @@ }, { "cell_type": "code", - "execution_count": 26, + "execution_count": 14, "metadata": { "collapsed": false }, @@ -2482,8 +1083,8 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "The Numpy function **np.cov** calculates the covariance elements using the factor $1/(n-1)$ instead of $1/n$ since it assumes we do not have the exact mean values. For a more in-depth discussion of the covariance and covariance matrix and its meaning, we refer you to the lectures on statistics. \n", - "The following simple function uses the **np.vstack** function which takes each vector of dimension $1\\times n$ and produces a $ 3\\times n$ matrix $\\hat{W}$" + "The Numpy function **np.cov** calculates the covariance elements using the factor $1/(n-1)$ instead of $1/n$ since it assumes we do not have the exact mean values. \n", + "The following simple function uses the **np.vstack** function which takes each vector of dimension $1\\times n$ and produces a $3\\times n$ matrix $\\hat{W}$" ] }, { @@ -2505,10 +1106,8 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "which in turn is converted into into the $3 times 3$ covariance matrix\n", - "$\\hat{\\Sigma}$ via the Numpy function **np.cov()**. In our review of\n", - "statistical functions and quantities we will discuss more about the\n", - "meaning of the covariance matrix. Here we note that we can calculate\n", + "which in turn is converted into into the $3\\times 3$ covariance matrix\n", + "$\\hat{\\Sigma}$ via the Numpy function **np.cov()**. We note that we can also calculate\n", "the mean value of each set of samples $\\hat{x}$ etc using the Numpy\n", "function **np.mean(x)**. We can also extract the eigenvalues of the\n", "covariance matrix through the **np.linalg.eig()** function." @@ -2516,7 +1115,7 @@ }, { "cell_type": "code", - "execution_count": 27, + "execution_count": 15, "metadata": { "collapsed": false }, @@ -2541,12 +1140,14 @@ }, { "cell_type": "code", - "execution_count": 28, + "execution_count": 16, "metadata": { "collapsed": false }, "outputs": [], "source": [ + "%matplotlib inline\n", + "\n", "import numpy as np\n", "import matplotlib.pyplot as plt\n", "from scipy import sparse\n", @@ -2564,38 +1165,268 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "## Matrix Handling in C/C++, Static and Dynamical allocation\n", + "## Meet the Pandas\n", "\n", - " Static\n", - "We have an $N\\times N$ matrix A with $N=100$\n", - "In C/C++ this would be defined as" + "\n", + "\n", + "\n", + "\n", + "

\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "Another useful Python package is\n", + "[pandas](https://pandas.pydata.org/), which is an open source library\n", + "providing high-performance, easy-to-use data structures and data\n", + "analysis tools for Python. **pandas** stands for panel data, a term borrowed from econometrics and is an efficient library for data analysis with an emphasis on tabular data.\n", + "**pandas** has two major classes, the **DataFrame** class with two-dimensional data objects and tabular data organized in columns and the class **Series** with a focus on one-dimensional data objects. Both classes allow you to index data easily as we will see in the examples below. \n", + "**pandas** allows you also to perform mathematical operations on the data, spanning from simple reshapings of vectors and matrices to statistical operations. \n", + "\n", + "The following simple example shows how we can, in an easy way make tables of our data. Here we define a data set which includes names, place of birth and date of birth, and displays the data in an easy to read way. We will see repeated use of **pandas**, in particular in connection with classification of data." + ] + }, + { + "cell_type": "code", + "execution_count": 17, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "import pandas as pd\n", + "from IPython.display import display\n", + "data = {'First Name': [\"Frodo\", \"Bilbo\", \"Aragorn II\", \"Samwise\"],\n", + " 'Last Name': [\"Baggins\", \"Baggins\",\"Elessar\",\"Gamgee\"],\n", + " 'Place of birth': [\"Shire\", \"Shire\", \"Eriador\", \"Shire\"],\n", + " 'Date of Birth T.A.': [2968, 2890, 2931, 2980]\n", + " }\n", + "data_pandas = pd.DataFrame(data)\n", + "display(data_pandas)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ - " int N = 100;\n", - " double A[100][100];\n", - " // initialize all elements to zero\n", - " for(i=0 ; i < N ; i++) {\n", - " for(j=0 ; j < N ; j++) {\n", - " A[i][j] = 0.0;\n", - " \n" + "In the above we have imported **pandas** with the shorthand **pd**, the latter has become the standard way we import **pandas**. We make then a list of various variables\n", + "and reorganize the aboves lists into a **DataFrame** and then print out a neat table with specific column labels as *Name*, *place of birth* and *date of birth*.\n", + "Displaying these results, we see that the indices are given by the default numbers from zero to three.\n", + "**pandas** is extremely flexible and we can easily change the above indices by defining a new type of indexing as" + ] + }, + { + "cell_type": "code", + "execution_count": 18, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "data_pandas = pd.DataFrame(data,index=['Frodo','Bilbo','Aragorn','Sam'])\n", + "display(data_pandas)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ - "Note the way the matrix is organized, row-major order.\n", + "Thereafter we display the content of the row which begins with the index **Aragorn**" + ] + }, + { + "cell_type": "code", + "execution_count": 19, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "display(data_pandas.loc['Aragorn'])" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "We can easily append data to this, for example" + ] + }, + { + "cell_type": "code", + "execution_count": 20, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "new_hobbit = {'First Name': [\"Peregrin\"],\n", + " 'Last Name': [\"Took\"],\n", + " 'Place of birth': [\"Shire\"],\n", + " 'Date of Birth T.A.': [2990]\n", + " }\n", + "data_pandas=data_pandas.append(pd.DataFrame(new_hobbit, index=['Pippin']))\n", + "display(data_pandas)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Here are other examples where we use the **DataFrame** functionality to handle arrays, now with more interesting features for us, namely numbers. We set up a matrix \n", + "of dimensionality $10\\times 5$ and compute the mean value and standard deviation of each column. Similarly, we can perform mathematial operations like squaring the matrix elements and many other operations." + ] + }, + { + "cell_type": "code", + "execution_count": 21, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "import numpy as np\n", + "import pandas as pd\n", + "from IPython.display import display\n", + "np.random.seed(100)\n", + "# setting up a 10 x 5 matrix\n", + "rows = 10\n", + "cols = 5\n", + "a = np.random.randn(rows,cols)\n", + "df = pd.DataFrame(a)\n", + "display(df)\n", + "print(df.mean())\n", + "print(df.std())\n", + "display(df**2)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Thereafter we can select specific columns only and plot final results" + ] + }, + { + "cell_type": "code", + "execution_count": 22, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "df.columns = ['First', 'Second', 'Third', 'Fourth', 'Fifth']\n", + "df.index = np.arange(10)\n", + "\n", + "display(df)\n", + "print(df['Second'].mean() )\n", + "print(df.info())\n", + "print(df.describe())\n", + "\n", + "from pylab import plt, mpl\n", + "plt.style.use('seaborn')\n", + "mpl.rcParams['font.family'] = 'serif'\n", + "\n", + "df.cumsum().plot(lw=2.0, figsize=(10,6))\n", + "plt.show()\n", "\n", "\n", - "## Matrix Handling in C/C++\n", + "df.plot.bar(figsize=(10,6), rot=15)\n", + "plt.show()" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "We can produce a $4\\times 4$ matrix" + ] + }, + { + "cell_type": "code", + "execution_count": 23, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "b = np.arange(16).reshape((4,4))\n", + "print(b)\n", + "df1 = pd.DataFrame(b)\n", + "print(df1)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "and many other operations. \n", "\n", - " Row Major Order, Addition\n", - "We have $N\\times N$ matrices A, B and C and we wish to\n", - "evaluate $A=B+C$." + "The **Series** class is another important class included in\n", + "**pandas**. You can view it as a specialization of **DataFrame** but where\n", + "we have just a single column of data. It shares many of the same features as _DataFrame. As with **DataFrame**,\n", + "most operations are vectorized, achieving thereby a high performance when dealing with computations of arrays, in particular labeled arrays.\n", + "As we will see below it leads also to a very concice code close to the mathematical operations we may be interested in.\n", + "For multidimensional arrays, we recommend strongly [xarray](http://xarray.pydata.org/en/stable/). **xarray** has much of the same flexibility as **pandas**, but allows for the extension to higher dimensions than two. We will see examples later of the usage of both **pandas** and **xarray**. \n", + "\n", + "\n", + "\n", + "## Reading Data and fitting\n", + "\n", + "In order to study various Machine Learning algorithms, we need to\n", + "access data. Acccessing data is an essential step in all machine\n", + "learning algorithms. In particular, setting up the so-called **design\n", + "matrix** (to be defined below) is often the first element we need in\n", + "order to perform our calculations. To set up the design matrix means\n", + "reading (and later, when the calculations are done, writing) data\n", + "in various formats, The formats span from reading files from disk,\n", + "loading data from databases and interacting with online sources\n", + "like web application programming interfaces (APIs).\n", + "\n", + "In handling various input formats, as discussed above, we will mainly stay with **pandas**,\n", + "a Python package which allows us, in a seamless and painless way, to\n", + "deal with a multitude of formats, from standard **csv** (comma separated\n", + "values) files, via **excel**, **html** to **hdf5** formats. With **pandas**\n", + "and the **DataFrame** and **Series** functionalities we are able to convert text data\n", + "into the calculational formats we need for a specific algorithm. And our code is going to be \n", + "pretty close the basic mathematical expressions.\n", + "\n", + "Our first data set is going to be a classic from nuclear physics, namely all\n", + "available data on binding energies. Don't be intimidated if you are not familiar with nuclear physics. It serves simply as an example here of a data set. \n", + "\n", + "We will show some of the\n", + "strengths of packages like **Scikit-Learn** in fitting nuclear binding energies to\n", + "specific functions using linear regression first. Then, as a teaser, we will show you how \n", + "you can easily implement other algorithms like decision trees and random forests and neural networks.\n", + "\n", + "But before we really start with nuclear physics data, let's just look at some simpler polynomial fitting cases, such as,\n", + "(don't be offended) fitting straight lines!\n", + "\n", + "\n", + "### Simple linear regression model using **scikit-learn**\n", + "\n", + "We start with perhaps our simplest possible example, using **Scikit-Learn** to perform linear regression analysis on a data set produced by us. \n", + "\n", + "What follows is a simple Python code where we have defined a function\n", + "$y$ in terms of the variable $x$. Both are defined as vectors with $100$ entries. \n", + "The numbers in the vector $\\hat{x}$ are given\n", + "by random numbers generated with a uniform distribution with entries\n", + "$x_i \\in [0,1]$ (more about probability distribution functions\n", + "later). These values are then used to define a function $y(x)$\n", + "(tabulated again as a vector) with a linear dependence on $x$ plus a\n", + "random noise added via the normal distribution.\n", + "\n", + "\n", + "The Numpy functions are imported used the **import numpy as np**\n", + "statement and the random number generator for the uniform distribution\n", + "is called using the function **np.random.rand()**, where we specificy\n", + "that we want $100$ random variables. Using Numpy we define\n", + "automatically an array with the specified number of elements, $100$ in\n", + "our case. With the Numpy function **randn()** we can compute random\n", + "numbers with the normal distribution (mean value $\\mu$ equal to zero and\n", + "variance $\\sigma^2$ set to one) and produce the values of $y$ assuming a linear\n", + "dependence as function of $x$" ] }, { @@ -2603,7 +1434,7 @@ "metadata": {}, "source": [ "$$\n", - "\\mathbf{A}= \\mathbf{B}\\pm\\mathbf{C} \\Longrightarrow a_{ij} = b_{ij}\\pm c_{ij},\n", + "y = 2x+N(0,1),\n", "$$" ] }, @@ -2611,28 +1442,67 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "In C/C++ this would be coded like" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - " for(i=0 ; i < N ; i++) {\n", - " for(j=0 ; j < N ; j++) {\n", - " a[i][j] = b[i][j]+c[i][j]\n", - " \n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "## Matrix Handling in C/C++\n", + "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", - " Row Major Order, Multiplication\n", - "We have $N\\times N$ matrices A, B and C and we wish to\n", - "evaluate $A=BC$." + "For plotting we use the Python package\n", + "[matplotlib](https://matplotlib.org/) which produces publication\n", + "quality figures. Feel free to explore the extensive\n", + "[gallery](https://matplotlib.org/gallery/index.html) of examples. In\n", + "this example we plot our original values of $x$ and $y$ as well as the\n", + "prediction **ypredict** ($\\tilde{y}$), which attempts at fitting our\n", + "data with a straight line.\n", + "\n", + "The Python code follows here." + ] + }, + { + "cell_type": "code", + "execution_count": 24, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "# Importing various packages\n", + "import numpy as np\n", + "import matplotlib.pyplot as plt\n", + "from sklearn.linear_model import LinearRegression\n", + "\n", + "x = np.random.rand(100,1)\n", + "y = 2*x+np.random.randn(100,1)\n", + "linreg = LinearRegression()\n", + "linreg.fit(x,y)\n", + "xnew = np.array([[0],[1]])\n", + "ypredict = linreg.predict(xnew)\n", + "\n", + "plt.plot(xnew, ypredict, \"r-\")\n", + "plt.plot(x, y ,'ro')\n", + "plt.axis([0,1.0,0, 5.0])\n", + "plt.xlabel(r'$x$')\n", + "plt.ylabel(r'$y$')\n", + "plt.title(r'Simple Linear Regression')\n", + "plt.show()" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "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" ] }, { @@ -2640,7 +1510,7 @@ "metadata": {}, "source": [ "$$\n", - "\\mathbf{A}=\\mathbf{BC} \\Longrightarrow a_{ij} = \\sum_{k=1}^{n} b_{ik}c_{kj},\n", + "y = 10x+0.01 \\times N(0,1),\n", "$$" ] }, @@ -2648,401 +1518,18 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "In C/C++ this would be coded like" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - " for(i=0 ; i < N ; i++) {\n", - " for(j=0 ; j < N ; j++) {\n", - " for(k=0 ; k < N ; k++) {\n", - " a[i][j]+=b[i][k]*c[k][j];\n", - " \n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "## Dynamic memory allocation in C/C++\n", + "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", - "At least three possibilities in this course\n", - "\n", - " * Do it yourself\n", - "\n", - " * Use the functions provided in the library package lib.cpp\n", - "\n", - " * Use Armadillo (a C++ linear algebra library, discussion both here and at lab). \n", - "\n", - "## Matrix Handling in C/C++, Dynamic Allocation\n", - "\n", - " Do it yourself" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - " int N;\n", - " double ** A;\n", - " A = new double*[N]\n", - " for ( i = 0; i < N; i++)\n", - " A[i] = new double[N];\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "Always free space when you don't need an array anymore." - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - " for ( i = 0; i < N; i++)\n", - " delete[] A[i];\n", - " delete[] A;\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "## Armadillo, recommended!!\n", - "\n", - " * Armadillo is a C++ linear algebra library (matrix maths) aiming towards a good balance between speed and ease of use. The syntax is deliberately similar to Matlab.\n", - "\n", - " * Integer, floating point and complex numbers are supported, as well as a subset of trigonometric and statistics functions. Various matrix decompositions are provided through optional integration with LAPACK, or one of its high performance drop-in replacements (such as the multi-threaded MKL or ACML libraries).\n", - "\n", - " * A delayed evaluation approach is employed (at compile-time) to combine several operations into one and reduce (or eliminate) the need for temporaries. This is accomplished through recursive templates and template meta-programming.\n", - "\n", - " * Useful for conversion of research code into production environments, or if C++ has been decided as the language of choice, due to speed and/or integration capabilities.\n", - "\n", - " * The library is open-source software, and is distributed under a license that is useful in both open-source and commercial/proprietary contexts.\n", - "\n", - "## Armadillo, simple examples" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - " #include \n", - " #include \n", - " \n", - " using namespace std;\n", - " using namespace arma;\n", - " \n", - " int main(int argc, char** argv)\n", - " {\n", - " mat A = randu(5,5);\n", - " mat B = randu(5,5);\n", - " \n", - " cout << A*B << endl;\n", - " \n", - " return 0;\n", - " \n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "## Armadillo, how to compile and install\n", - "\n", - "For people using Ubuntu, Debian, Linux Mint, simply go to the synaptic package manager and install\n", - "armadillo from there.\n", - "You may have to install Lapack as well.\n", - "For Mac and Windows users, follow the instructions from the webpage\n", - ".\n", - "To compile, use for example (linux/ubuntu)" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - " c++ -O2 -o program.x program.cpp -larmadillo -llapack -lblas\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "where the `-l` option indicates the library you wish to link to.\n", - "\n", - "For OS X users you may have to declare the paths to the include files and the libraries as" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - " c++ -O2 -o program.x program.cpp -L/usr/local/lib -I/usr/local/include -larmadillo -llapack -lblas\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "## Armadillo, simple examples" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - " #include \n", - " #include \"armadillo\"\n", - " using namespace arma;\n", - " using namespace std;\n", - " \n", - " int main(int argc, char** argv)\n", - " {\n", - " // directly specify the matrix size (elements are uninitialised)\n", - " mat A(2,3);\n", - " // .n_rows = number of rows (read only)\n", - " // .n_cols = number of columns (read only)\n", - " cout << \"A.n_rows = \" << A.n_rows << endl;\n", - " cout << \"A.n_cols = \" << A.n_cols << endl;\n", - " // directly access an element (indexing starts at 0)\n", - " A(1,2) = 456.0;\n", - " A.print(\"A:\");\n", - " // scalars are treated as a 1x1 matrix,\n", - " // hence the code below will set A to have a size of 1x1\n", - " A = 5.0;\n", - " A.print(\"A:\");\n", - " // if you want a matrix with all elements set to a particular value\n", - " // the .fill() member function can be used\n", - " A.set_size(3,3);\n", - " A.fill(5.0); A.print(\"A:\");\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "## Armadillo, simple examples" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - " mat B;\n", - " \n", - " // endr indicates \"end of row\"\n", - " B << 0.555950 << 0.274690 << 0.540605 << 0.798938 << endr\n", - " << 0.108929 << 0.830123 << 0.891726 << 0.895283 << endr\n", - " << 0.948014 << 0.973234 << 0.216504 << 0.883152 << endr\n", - " << 0.023787 << 0.675382 << 0.231751 << 0.450332 << endr;\n", - " \n", - " // print to the cout stream\n", - " // with an optional string before the contents of the matrix\n", - " B.print(\"B:\");\n", - " \n", - " // the << operator can also be used to print the matrix\n", - " // to an arbitrary stream (cout in this case)\n", - " cout << \"B:\" << endl << B << endl;\n", - " // save to disk\n", - " B.save(\"B.txt\", raw_ascii);\n", - " // load from disk\n", - " mat C;\n", - " C.load(\"B.txt\");\n", - " C += 2.0 * B;\n", - " C.print(\"C:\");\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "## Armadillo, simple examples" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - " // submatrix types:\n", - " //\n", - " // .submat(first_row, first_column, last_row, last_column)\n", - " // .row(row_number)\n", - " // .col(column_number)\n", - " // .cols(first_column, last_column)\n", - " // .rows(first_row, last_row)\n", - " \n", - " cout << \"C.submat(0,0,3,1) =\" << endl;\n", - " cout << C.submat(0,0,3,1) << endl;\n", - " \n", - " // generate the identity matrix\n", - " mat D = eye(4,4);\n", - " \n", - " D.submat(0,0,3,1) = C.cols(1,2);\n", - " D.print(\"D:\");\n", - " \n", - " // transpose\n", - " cout << \"trans(B) =\" << endl;\n", - " cout << trans(B) << endl;\n", - " \n", - " // maximum from each column (traverse along rows)\n", - " cout << \"max(B) =\" << endl;\n", - " cout << max(B) << endl;\n", - " \n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "## Armadillo, simple examples" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - " // maximum from each row (traverse along columns)\n", - " cout << \"max(B,1) =\" << endl;\n", - " cout << max(B,1) << endl;\n", - " // maximum value in B\n", - " cout << \"max(max(B)) = \" << max(max(B)) << endl;\n", - " // sum of each column (traverse along rows)\n", - " cout << \"sum(B) =\" << endl;\n", - " cout << sum(B) << endl;\n", - " // sum of each row (traverse along columns)\n", - " cout << \"sum(B,1) =\" << endl;\n", - " cout << sum(B,1) << endl;\n", - " // sum of all elements\n", - " cout << \"sum(sum(B)) = \" << sum(sum(B)) << endl;\n", - " cout << \"accu(B) = \" << accu(B) << endl;\n", - " // trace = sum along diagonal\n", - " cout << \"trace(B) = \" << trace(B) << endl;\n", - " // random matrix -- values are uniformly distributed in the [0,1] interval\n", - " mat E = randu(4,4);\n", - " E.print(\"E:\");\n", - " \n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "## Armadillo, simple examples" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - " // row vectors are treated like a matrix with one row\n", - " rowvec r;\n", - " r << 0.59499 << 0.88807 << 0.88532 << 0.19968;\n", - " r.print(\"r:\");\n", - " \n", - " // column vectors are treated like a matrix with one column\n", - " colvec q;\n", - " q << 0.81114 << 0.06256 << 0.95989 << 0.73628;\n", - " q.print(\"q:\");\n", - " \n", - " // dot or inner product\n", - " cout << \"as_scalar(r*q) = \" << as_scalar(r*q) << endl;\n", - " \n", - " // outer product\n", - " cout << \"q*r =\" << endl;\n", - " cout << q*r << endl;\n", - " \n", - " \n", - " // sum of three matrices (no temporary matrices are created)\n", - " mat F = B + C + D;\n", - " F.print(\"F:\");\n", - " \n", - " return 0;\n", - " \n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "## Armadillo, simple examples" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - " #include \n", - " #include \"armadillo\"\n", - " using namespace arma;\n", - " using namespace std;\n", - " \n", - " int main(int argc, char** argv)\n", - " {\n", - " cout << \"Armadillo version: \" << arma_version::as_string() << endl;\n", - " \n", - " mat A;\n", - " \n", - " A << 0.165300 << 0.454037 << 0.995795 << 0.124098 << 0.047084 << endr\n", - " << 0.688782 << 0.036549 << 0.552848 << 0.937664 << 0.866401 << endr\n", - " << 0.348740 << 0.479388 << 0.506228 << 0.145673 << 0.491547 << endr\n", - " << 0.148678 << 0.682258 << 0.571154 << 0.874724 << 0.444632 << endr\n", - " << 0.245726 << 0.595218 << 0.409327 << 0.367827 << 0.385736 << endr;\n", - " \n", - " A.print(\"A =\");\n", - " \n", - " // determinant\n", - " cout << \"det(A) = \" << det(A) << endl;\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "## Armadillo, simple examples" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - " // inverse\n", - " cout << \"inv(A) = \" << endl << inv(A) << endl;\n", - " double k = 1.23;\n", - " \n", - " mat B = randu(5,5);\n", - " mat C = randu(5,5);\n", - " \n", - " rowvec r = randu(5);\n", - " colvec q = randu(5);\n", - " \n", - " \n", - " // examples of some expressions\n", - " // for which optimised implementations exist\n", - " // optimised implementation of a trinary expression\n", - " // that results in a scalar\n", - " cout << \"as_scalar( r*inv(diagmat(B))*q ) = \";\n", - " cout << as_scalar( r*inv(diagmat(B))*q ) << endl;\n", - " \n", - " // example of an expression which is optimised\n", - " // as a call to the dgemm() function in BLAS:\n", - " cout << \"k*trans(B)*C = \" << endl << k*trans(B)*C;\n", - " \n", - " return 0;\n", - " \n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "## Gaussian Elimination\n", - "\n", - "We start with the linear set of equations" + "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))" ] }, { @@ -3050,7 +1537,8 @@ "metadata": {}, "source": [ "$$\n", - "\\mathbf{A}\\mathbf{x} = \\mathbf{w}.\n", + "\\chi^2 = \\frac{1}{n}\n", + "\\sum_{i=0}^{n-1}\\frac{(y_i-\\tilde{y}_i)^2}{\\sigma_i^2},\n", "$$" ] }, @@ -3058,89 +1546,28 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "We assume also that the matrix $\\mathbf{A}$ is non-singular and that the\n", - "matrix elements along the diagonal satisfy $a_{ii} \\ne 0$. Simple $4\\times 4 $ example" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "\\begin{bmatrix}\n", - " a_{11}& a_{12} &a_{13}& a_{14}\\\\\n", - " a_{21}& a_{22} &a_{23}& a_{24}\\\\\n", - " a_{31}& a_{32} &a_{33}& a_{34}\\\\\n", - " a_{41}& a_{42} &a_{43}& a_{44}\\\\\n", - " \\end{bmatrix} \\begin{bmatrix}\n", - " x_1\\\\\n", - " x_2\\\\\n", - " x_3 \\\\\n", - " x_4 \\\\\n", - " \\end{bmatrix}\n", - " =\\begin{bmatrix}\n", - " w_1\\\\\n", - " w_2\\\\\n", - " w_3 \\\\\n", - " w_4\\\\\n", - " \\end{bmatrix}.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "## Gaussian Elimination\n", - "or" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "a_{11}x_1 +a_{12}x_2 +a_{13}x_3 + a_{14}x_4=w_1 \\nonumber\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "a_{21}x_1 + a_{22}x_2 + a_{23}x_3 + a_{24}x_4=w_2 \\nonumber\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "a_{31}x_1 + a_{32}x_2 + a_{33}x_3 + a_{34}x_4=w_3 \\nonumber\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "a_{41}x_1 + a_{42}x_2 + a_{43}x_3 + a_{44}x_4=w_4. \\nonumber\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "## Gaussian Elimination\n", + "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", - "The basic idea of Gaussian elimination is to use the first equation to eliminate the first unknown $x_1$\n", - "from the remaining $n-1$ equations. Then we use the new second equation to eliminate the second unknown\n", - "$x_2$ from the remaining $n-2$ equations. With $n-1$ such eliminations\n", - "we obtain a so-called upper triangular set of equations of the form" + "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" ] }, { @@ -3148,25 +1575,140 @@ "metadata": {}, "source": [ "$$\n", - "b_{11}x_1 +b_{12}x_2 +b_{13}x_3 + b_{14}x_4=y_1 \\nonumber\n", + "\\epsilon_{\\mathrm{relative}}= \\frac{\\vert \\hat{y} -\\hat{\\tilde{y}}\\vert}{\\vert \\hat{y}\\vert}.\n", "$$" ] }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "We can modify easily the above Python code and plot the relative error instead" + ] + }, + { + "cell_type": "code", + "execution_count": 25, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "import numpy as np\n", + "import matplotlib.pyplot as plt\n", + "from sklearn.linear_model import LinearRegression\n", + "\n", + "x = np.random.rand(100,1)\n", + "y = 5*x+0.01*np.random.randn(100,1)\n", + "linreg = LinearRegression()\n", + "linreg.fit(x,y)\n", + "ypredict = linreg.predict(x)\n", + "\n", + "plt.plot(x, np.abs(ypredict-y)/abs(y), \"ro\")\n", + "plt.axis([0,1.0,0.0, 0.5])\n", + "plt.xlabel(r'$x$')\n", + "plt.ylabel(r'$\\epsilon_{\\mathrm{relative}}$')\n", + "plt.title(r'Relative error')\n", + "plt.show()" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Depending on the parameter in front of the normal distribution, we may\n", + "have a small or larger relative error. Try to play around with\n", + "different training data sets and study (graphically) the value of the\n", + "relative error.\n", + "\n", + "As mentioned above, **Scikit-Learn** has an impressive functionality.\n", + "We can for example extract the values of $\\alpha$ and $\\beta$ and\n", + "their error estimates, or the variance and standard deviation and many\n", + "other properties from the statistical data analysis. \n", + "\n", + "Here we show an\n", + "example of the functionality of **Scikit-Learn**." + ] + }, + { + "cell_type": "code", + "execution_count": 26, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "import numpy as np \n", + "import matplotlib.pyplot as plt \n", + "from sklearn.linear_model import LinearRegression \n", + "from sklearn.metrics import mean_squared_error, r2_score, mean_squared_log_error, mean_absolute_error\n", + "\n", + "x = np.random.rand(100,1)\n", + "y = 2.0+ 5*x+0.5*np.random.randn(100,1)\n", + "linreg = LinearRegression()\n", + "linreg.fit(x,y)\n", + "ypredict = linreg.predict(x)\n", + "print('The intercept alpha: \\n', linreg.intercept_)\n", + "print('Coefficient beta : \\n', linreg.coef_)\n", + "# The mean squared error \n", + "print(\"Mean squared error: %.2f\" % mean_squared_error(y, ypredict))\n", + "# Explained variance score: 1 is perfect prediction \n", + "print('Variance score: %.2f' % r2_score(y, ypredict))\n", + "# Mean squared log error \n", + "print('Mean squared log error: %.2f' % mean_squared_log_error(y, ypredict) )\n", + "# Mean absolute error \n", + "print('Mean absolute error: %.2f' % mean_absolute_error(y, ypredict))\n", + "plt.plot(x, ypredict, \"r-\")\n", + "plt.plot(x, y ,'ro')\n", + "plt.axis([0.0,1.0,1.5, 7.0])\n", + "plt.xlabel(r'$x$')\n", + "plt.ylabel(r'$y$')\n", + "plt.title(r'Linear Regression fit ')\n", + "plt.show()" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "The function **coef** gives us the parameter $\\beta$ of our fit while **intercept** yields \n", + "$\\alpha$. Depending on the constant in front of the normal distribution, we get values near or far from $alpha =2$ and $\\beta =5$. Try to play around with different parameters in front of the normal distribution. The function **meansquarederror** gives us the mean square error, a risk metric corresponding to the expected value of the squared (quadratic) error or loss defined as" + ] + }, { "cell_type": "markdown", "metadata": {}, "source": [ "$$\n", - "b_{22}x_2 + b_{23}x_3 + b_{24}x_4=y_2 \\nonumber\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", - "b_{33}x_3 + b_{34}x_4=y_3 \\nonumber\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", "$$" ] }, @@ -3174,12 +1716,15 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "\n", - "
\n", - "\n", + "where we have defined the mean value of $\\hat{y}$ as" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ "$$\n", - "b_{44}x_4=y_4. \\nonumber\n", - "\\label{eq:gaussbacksub} \\tag{2}\n", + "\\bar{y} = \\frac{1}{n} \\sum_{i=0}^{n - 1} y_i.\n", "$$" ] }, @@ -3187,25 +1732,17 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "We can solve this system of equations recursively starting from $x_n$ (in our case $x_4$) and proceed with\n", - "what is called a backward substitution. \n", - "\n", - "## Gaussian Elimination\n", - "This process can be expressed mathematically as" + "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", - "
\n", - "\n", "$$\n", - "\\begin{equation}\n", - " x_m = \\frac{1}{b_{mm}}\\left(y_m-\\sum_{k=m+1}^nb_{mk}x_k\\right)\\quad m=n-1,n-2,\\dots,1.\n", - "\\label{_auto1} \\tag{3}\n", - "\\end{equation}\n", + "\\text{MAE}(\\hat{y}, \\hat{\\tilde{y}}) = \\frac{1}{n} \\sum_{i=0}^{n-1} \\left| y_i - \\tilde{y}_i \\right|.\n", "$$" ] }, @@ -3213,14 +1750,8 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "To arrive at such an upper triangular system of equations, we start by eliminating\n", - "the unknown $x_1$ for $j=2,n$. We achieve this by multiplying the first equation by $a_{j1}/a_{11}$ and then subtract\n", - "the result from the $j$th equation. We assume obviously that $a_{11}\\ne 0$ and that\n", - "$\\mathbf{A}$ is not singular.\n", - "\n", - "## Gaussian Elimination\n", - "\n", - "Our actual $4\\times 4$ example reads after the first operation" + "Finally we present the \n", + "squared logarithmic (quadratic) error" ] }, { @@ -3228,23 +1759,7 @@ "metadata": {}, "source": [ "$$\n", - "\\begin{bmatrix}\n", - " a_{11}& a_{12} &a_{13}& a_{14}\\\\\n", - " 0& (a_{22}-\\frac{a_{21}a_{12}}{a_{11}}) &(a_{23}-\\frac{a_{21}a_{13}}{a_{11}}) & (a_{24}-\\frac{a_{21}a_{14}}{a_{11}})\\\\\n", - "0& (a_{32}-\\frac{a_{31}a_{12}}{a_{11}})& (a_{33}-\\frac{a_{31}a_{13}}{a_{11}})& (a_{34}-\\frac{a_{31}a_{14}}{a_{11}})\\\\\n", - "0&(a_{42}-\\frac{a_{41}a_{12}}{a_{11}}) &(a_{43}-\\frac{a_{41}a_{13}}{a_{11}}) & (a_{44}-\\frac{a_{41}a_{14}}{a_{11}}) \\\\\n", - " \\end{bmatrix} \\begin{bmatrix}\n", - " x_1\\\\\n", - " x_2\\\\\n", - " x_3 \\\\\n", - " x_4 \\\\\n", - " \\end{bmatrix} \n", - " =\\begin{bmatrix}\n", - " y_1\\\\\n", - " w_2^{(2)}\\\\\n", - " w_3^{(2)} \\\\\n", - " w_4^{(2)}\\\\\n", - " \\end{bmatrix},\n", + "\\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", "$$" ] }, @@ -3252,7 +1767,68 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "or" + "where $\\log_e (x)$ stands for the natural logarithm of $x$. This error\n", + "estimate is best to use when targets having exponential growth, such\n", + "as population counts, average sales of a commodity over a span of\n", + "years etc. \n", + "\n", + "We will discuss in more\n", + "detail these and other functions in the various lectures. We conclude this part with another example. Instead of \n", + "a linear $x$-dependence we study now a cubic polynomial and use the polynomial regression analysis tools of scikit-learn." + ] + }, + { + "cell_type": "code", + "execution_count": 27, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "import matplotlib.pyplot as plt\n", + "import numpy as np\n", + "import random\n", + "from sklearn.linear_model import Ridge\n", + "from sklearn.preprocessing import PolynomialFeatures\n", + "from sklearn.pipeline import make_pipeline\n", + "from sklearn.linear_model import LinearRegression\n", + "\n", + "x=np.linspace(0.02,0.98,200)\n", + "noise = np.asarray(random.sample((range(200)),200))\n", + "y=x**3*noise\n", + "yn=x**3*100\n", + "poly3 = PolynomialFeatures(degree=3)\n", + "X = poly3.fit_transform(x[:,np.newaxis])\n", + "clf3 = LinearRegression()\n", + "clf3.fit(X,y)\n", + "\n", + "Xplot=poly3.fit_transform(x[:,np.newaxis])\n", + "poly3_plot=plt.plot(x, clf3.predict(Xplot), label='Cubic Fit')\n", + "plt.plot(x,yn, color='red', label=\"True Cubic\")\n", + "plt.scatter(x, y, label='Data', color='orange', s=15)\n", + "plt.legend()\n", + "plt.show()\n", + "\n", + "def error(a):\n", + " for i in y:\n", + " err=(y-yn)/yn\n", + " return abs(np.sum(err))/len(err)\n", + "\n", + "print (error(y))" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### To our real data: nuclear binding energies. Brief reminder on masses and binding energies\n", + "\n", + "Let us now dive into nuclear physics and remind ourselves briefly about some basic features about binding\n", + "energies. A basic quantity which can be measured for the ground\n", + "states of nuclei is the atomic mass $M(N, Z)$ of the neutral atom with\n", + "atomic mass number $A$ and charge $Z$. The number of neutrons is $N$. There are indeed several sophisticated experiments worldwide which allow us to measure this quantity to high precision (parts per million even). \n", + "\n", + "Atomic masses are usually tabulated in terms of the mass excess defined by" ] }, { @@ -3260,16 +1836,23 @@ "metadata": {}, "source": [ "$$\n", - "b_{11}x_1 +b_{12}x_2 +b_{13}x_3 + b_{14}x_4=y_1 \\nonumber\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", - "a^{(2)}_{22}x_2 + a^{(2)}_{23}x_3 + a^{(2)}_{24}x_4=w^{(2)}_2 \\nonumber\n", + "u = M(^{12}\\mathrm{C})/12 = 931.4940954(57) \\hspace{0.1cm} \\mathrm{MeV}/c^2.\n", "$$" ] }, @@ -3277,9 +1860,7 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "$$\n", - "a^{(2)}_{32}x_2 + a^{(2)}_{33}x_3 + a^{(2)}_{34}x_4=w^{(2)}_3 \\nonumber\n", - "$$" + "The nucleon masses are" ] }, { @@ -3287,476 +1868,7 @@ "metadata": {}, "source": [ "$$\n", - "a^{(2)}_{42}x_2 + a^{(2)}_{43}x_3 + a^{(2)}_{44}x_4=w^{(2)}_4, \\nonumber\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "\n", - "
\n", - "\n", - "$$\n", - "\\begin{equation} \n", - "\\label{_auto2} \\tag{4}\n", - "\\end{equation}\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "## Gaussian Elimination\n", - "\n", - "The new coefficients are" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "\n", - "
\n", - "\n", - "$$\n", - "\\begin{equation}\n", - " b_{1k} = a_{1k}^{(1)} \\quad k=1,\\dots,n,\n", - "\\label{_auto3} \\tag{5}\n", - "\\end{equation}\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "where each $a_{1k}^{(1)}$ is equal to the original $a_{1k}$ element. The other coefficients are" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "\n", - "
\n", - "\n", - "$$\n", - "\\begin{equation}\n", - "a_{jk}^{(2)} = a_{jk}^{(1)}-\\frac{a_{j1}^{(1)}a_{1k}^{(1)}}{a_{11}^{(1)}} \\quad j,k=2,\\dots,n,\n", - "\\label{_auto4} \\tag{6}\n", - "\\end{equation}\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "with a new right-hand side given by" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "\n", - "
\n", - "\n", - "$$\n", - "\\begin{equation}\n", - "y_{1}=w_1^{(1)}, \\quad w_j^{(2)} =w_j^{(1)}-\\frac{a_{j1}^{(1)}w_1^{(1)}}{a_{11}^{(1)}} \\quad j=2,\\dots,n.\n", - "\\label{_auto5} \\tag{7}\n", - "\\end{equation}\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "We have also set $w_1^{(1)}=w_1$, the original vector element.\n", - "We see that the system of unknowns $x_1,\\dots,x_n$ is transformed into an $(n-1)\\times (n-1)$ problem.\n", - "\n", - "## Gaussian Elimination\n", - "\n", - "This step is called forward substitution.\n", - "Proceeding with these substitutions, we obtain the\n", - "general expressions for the new coefficients" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "\n", - "
\n", - "\n", - "$$\n", - "\\begin{equation}\n", - " a_{jk}^{(m+1)} = a_{jk}^{(m)}-\\frac{a_{jm}^{(m)}a_{mk}^{(m)}}{a_{mm}^{(m)}} \\quad j,k=m+1,\\dots,n,\n", - "\\label{_auto6} \\tag{8}\n", - "\\end{equation}\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "with $m=1,\\dots,n-1$ and a\n", - "right-hand side given by" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "\n", - "
\n", - "\n", - "$$\n", - "\\begin{equation}\n", - " w_j^{(m+1)} =w_j^{(m)}-\\frac{a_{jm}^{(m)}w_m^{(m)}}{a_{mm}^{(m)}}\\quad j=m+1,\\dots,n.\n", - "\\label{_auto7} \\tag{9}\n", - "\\end{equation}\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "This set of $n-1$ elimations leads us to an equations which is solved by back substitution.\n", - "If the arithmetics is exact and the matrix $\\mathbf{A}$ is not singular, then the computed answer will be exact.\n", - "\n", - "Even though the matrix elements along the diagonal are not zero,\n", - "numerically small numbers may appear and subsequent divisions may lead to large numbers, which, if added\n", - "to a small number may yield losses of precision. Suppose for example that our first division in $(a_{22}-a_{21}a_{12}/a_{11})$\n", - "results in $-10^{-7}$ and that $a_{22}$ is one.\n", - "one. We are then\n", - "adding $10^7+1$. With single precision this results in $10^7$.\n", - "\n", - "\n", - "\n", - "## Linear Algebra Methods\n", - "\n", - " * Gaussian elimination, $O(2/3n^3)$ flops, general matrix\n", - "\n", - " * LU decomposition, upper triangular and lower tridiagonal matrices, $O(2/3n^3)$ flops, general matrix. Get easily the inverse, determinant and can solve linear equations with back-substitution only, $O(n^2)$ flops\n", - "\n", - " * Cholesky decomposition. Real symmetric or hermitian positive definite matrix, $O(1/3n^3)$ flops.\n", - "\n", - " * Tridiagonal linear systems, important for differential equations. Normally positive definite and non-singular. $O(8n)$ flops for symmetric. Special case of banded matrices.\n", - "\n", - " * Singular value decomposition\n", - "\n", - " * the QR method will be discussed in chapter 7 in connection with eigenvalue systems. $O(4/3n^3)$ flops.\n", - "\n", - "## LU Decomposition\n", - "\n", - "The LU decomposition method means that we can rewrite\n", - "this matrix as the product of two matrices $\\mathbf{L}$ and $\\mathbf{U}$\n", - "where" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "\\begin{bmatrix}\n", - " a_{11} & a_{12} & a_{13} & a_{14} \\\\\n", - " a_{21} & a_{22} & a_{23} & a_{24} \\\\\n", - " a_{31} & a_{32} & a_{33} & a_{34} \\\\\n", - " a_{41} & a_{42} & a_{43} & a_{44}\n", - " \\end{bmatrix}\n", - " = \\begin{bmatrix}\n", - " 1 & 0 & 0 & 0 \\\\\n", - " l_{21} & 1 & 0 & 0 \\\\\n", - " l_{31} & l_{32} & 1 & 0 \\\\\n", - " l_{41} & l_{42} & l_{43} & 1\n", - " \\end{bmatrix}\n", - " \\begin{bmatrix}\n", - " u_{11} & u_{12} & u_{13} & u_{14} \\\\\n", - " 0 & u_{22} & u_{23} & u_{24} \\\\\n", - " 0 & 0 & u_{33} & u_{34} \\\\\n", - " 0 & 0 & 0 & u_{44}\n", - " \\end{bmatrix}.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "## LU Decomposition\n", - "\n", - "LU decomposition forms the backbone of other algorithms in linear algebra, such as the\n", - "solution of linear equations given by" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "a_{11}x_1 +a_{12}x_2 +a_{13}x_3 + a_{14}x_4=w_1 \\nonumber\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "a_{21}x_1 + a_{22}x_2 + a_{23}x_3 + a_{24}x_4=w_2 \\nonumber\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "a_{31}x_1 + a_{32}x_2 + a_{33}x_3 + a_{34}x_4=w_3 \\nonumber\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "a_{41}x_1 + a_{42}x_2 + a_{43}x_3 + a_{44}x_4=w_4. \\nonumber\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "The above set of equations is conveniently solved by using LU decomposition as an intermediate step.\n", - "\n", - "The matrix $\\mathbf{A}\\in \\mathbb{R}^{n\\times n}$ has an LU factorization if the determinant\n", - "is different from zero. If the LU factorization exists and $\\mathbf{A}$ is non-singular, then the LU factorization\n", - "is unique and the determinant is given by" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "det\\{\\mathbf{A}\\}=det\\{\\mathbf{LU}\\}= det\\{\\mathbf{L}\\}det\\{\\mathbf{U}\\}=u_{11}u_{22}\\dots u_{nn}.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "## LU Decomposition, why?\n", - "\n", - "There are at least three main advantages with LU decomposition compared with standard Gaussian elimination:\n", - "\n", - " * It is straightforward to compute the determinant of a matrix\n", - "\n", - " * If we have to solve sets of linear equations with the same matrix but with different vectors $\\mathbf{y}$, the number of FLOPS is of the order $n^3$.\n", - "\n", - " * The inverse is such an operation \n", - "\n", - "## LU Decomposition, linear equations\n", - "\n", - "With the LU decomposition it is rather\n", - "simple to solve a system of linear equations" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "a_{11}x_1 +a_{12}x_2 +a_{13}x_3 + a_{14}x_4=w_1 \\nonumber\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "a_{21}x_1 + a_{22}x_2 + a_{23}x_3 + a_{24}x_4=w_2 \\nonumber\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "a_{31}x_1 + a_{32}x_2 + a_{33}x_3 + a_{34}x_4=w_3 \\nonumber\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "a_{41}x_1 + a_{42}x_2 + a_{43}x_3 + a_{44}x_4=w_4. \\nonumber\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "This can be written in matrix form as" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "\\mathbf{Ax}=\\mathbf{w}.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "where $\\mathbf{A}$ and $\\mathbf{w}$ are known and we have to solve for\n", - "$\\mathbf{x}$. Using the LU dcomposition we write" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "\\mathbf{A} \\mathbf{x} \\equiv \\mathbf{L} \\mathbf{U} \\mathbf{x} =\\mathbf{w}.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "## LU Decomposition, linear equations\n", - "\n", - "The previous equation can be calculated in two steps" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "\\mathbf{L} \\mathbf{y} = \\mathbf{w};\\qquad \\mathbf{Ux}=\\mathbf{y}.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "To show that this is correct we use to the LU decomposition\n", - "to rewrite our system of linear equations as" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "\\mathbf{LUx}=\\mathbf{w},\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "and since the determinant of $\\mathbf{L}$ is equal to 1 (by construction\n", - "since the diagonals of $\\mathbf{L}$ equal 1) we can use the inverse of\n", - "$\\mathbf{L}$ to obtain" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "\\mathbf{Ux}=\\mathbf{L^{-1}w}=\\mathbf{y},\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "which yields the intermediate step" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "\\mathbf{L^{-1}w}=\\mathbf{y}\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "and as soon as we have $\\mathbf{y}$ we can obtain $\\mathbf{x}$\n", - "through $\\mathbf{Ux}=\\mathbf{y}$.\n", - "\n", - "## LU Decomposition, why?\n", - "\n", - "For our four-dimentional example this takes the form" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "y_1=w_1 \\nonumber\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "l_{21}y_1 + y_2=w_2\\nonumber\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "l_{31}y_1 + l_{32}y_2 + y_3 =w_3\\nonumber\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "l_{41}y_1 + l_{42}y_2 + l_{43}y_3 + y_4=w_4. \\nonumber\n", + "m_p = 1.00727646693(9)u,\n", "$$" ] }, @@ -3772,34 +1884,67 @@ "metadata": {}, "source": [ "$$\n", - "u_{11}x_1 +u_{12}x_2 +u_{13}x_3 + u_{14}x_4=y_1 \\nonumber\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", - "u_{22}x_2 + u_{23}x_3 + u_{24}x_4=y_2\\nonumber\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", - "u_{33}x_3 + u_{34}x_4=y_3\\nonumber\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", - "u_{44}x_4=y_4 \\nonumber\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", "$$" ] }, @@ -3807,480 +1952,85 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "This example shows the basis for the algorithm\n", - "needed to solve the set of $n$ linear equations.\n", - "\n", - "## LU Decomposition, linear equations\n", - "\n", - "The algorithm goes as follows\n", - "\n", - " * Set up the matrix $\\bf A$ and the vector $\\bf w$ with their correct dimensions. This determines the dimensionality of the unknown vector $\\bf x$.\n", - "\n", - " * Then LU decompose the matrix $\\bf A$ through a call to the function `ludcmp(double a, int n, int indx, double &d)`. This functions returns the LU decomposed matrix $\\bf A$, its determinant and the vector indx which keeps track of the number of interchanges of rows. If the determinant is zero, the solution is malconditioned.\n", - "\n", - " * Thereafter you call the function `lubksb(double a, int n, int indx, double w)` which uses the LU decomposed matrix $\\bf A$ and the vector $\\bf w$ and returns $\\bf x$ in the same place as $\\bf w$. Upon exit the original content in $\\bf w$ is destroyed. If you wish to keep this information, you should make a backup of it in your calling function.\n", - "\n", - "## LU Decomposition, the inverse of a matrix\n", - "\n", - "If the inverse exists then" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "\\mathbf{A}^{-1}\\mathbf{A}=\\mathbf{I},\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "the identity matrix. With an LU decomposed matrix we can rewrite the last equation as" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "\\mathbf{LU}\\mathbf{A}^{-1}=\\mathbf{I}.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "## LU Decomposition, the inverse of a matrix\n", - "\n", - "If we assume that the first column (that is column 1) of the inverse matrix\n", - "can be written as a vector with unknown entries" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "\\mathbf{A}_1^{-1}= \\begin{bmatrix}\n", - " a_{11}^{-1} \\\\\n", - " a_{21}^{-1} \\\\\n", - " \\dots \\\\\n", - " a_{n1}^{-1} \\\\\n", - " \\end{bmatrix},\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "then we have a linear set of equations" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "\\mathbf{LU}\\begin{bmatrix}\n", - " a_{11}^{-1} \\\\\n", - " a_{21}^{-1} \\\\\n", - " \\dots \\\\\n", - " a_{n1}^{-1} \\\\\n", - " \\end{bmatrix} =\\begin{bmatrix}\n", - " 1 \\\\\n", - " 0 \\\\\n", - " \\dots \\\\\n", - " 0 \\\\\n", - " \\end{bmatrix}.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "## LU Decomposition, the inverse\n", - "\n", - "In a similar way we can compute the unknow entries of the second column," - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "\\mathbf{LU}\\begin{bmatrix}\n", - " a_{12}^{-1} \\\\\n", - " a_{22}^{-1} \\\\\n", - " \\dots \\\\\n", - " a_{n2}^{-1} \\\\\n", - " \\end{bmatrix}=\\begin{bmatrix}\n", - " 0 \\\\\n", - " 1 \\\\\n", - " \\dots \\\\\n", - " 0 \\\\\n", - " \\end{bmatrix},\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "and continue till we have solved all $n$ sets of linear equations.\n", - "\n", - "\n", - "## [Using Armadillo to perform an LU decomposition](https://github.com/CompPhysics/ComputationalPhysicsMSU/blob/master/doc/Programs/CppQtCodesLectures/MatrixTest/main.cpp)" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - " #include \n", - " #include \"armadillo\"\n", - " using namespace arma;\n", - " using namespace std;\n", - " \n", - " int main()\n", - " {\n", - " mat A = randu(5,5);\n", - " vec b = randu(5);\n", - " \n", - " A.print(\"A =\");\n", - " b.print(\"b=\");\n", - " // solve Ax = b\n", - " vec x = solve(A,b);\n", - " // print x\n", - " x.print(\"x=\");\n", - " // find LU decomp of A, if needed, P is the permutation matrix\n", - " mat L, U;\n", - " lu(L,U,A);\n", - " // print l\n", - " L.print(\" L= \");\n", - " // print U\n", - " U.print(\" U= \");\n", - " //Check that A = LU\n", - " (A-L*U).print(\"Test of LU decomposition\");\n", - " return 0;\n", - " }\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "# Review of Statistics\n", - "\n", - "\n", - "## Domains and probabilities\n", - "\n", - "Consider the following simple example, namely the tossing of two dice, resulting in the following possible values" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "\\{2,3,4,5,6,7,8,9,10,11,12\\}.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "These values are called the *domain*. \n", - "To this domain we have the corresponding *probabilities*" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "\\{1/36,2/36/,3/36,4/36,5/36,6/36,5/36,4/36,3/36,2/36,1/36\\}.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "## Tossing the dice\n", - "\n", - "The numbers in the domain are the outcomes of the physical process of tossing say two dice.\n", - "We cannot tell beforehand whether the outcome is 3 or 5 or any other number in this domain.\n", - "This defines the randomness of the outcome, or unexpectedness or any other synonimous word which\n", - "encompasses the uncertitude of the final outcome. \n", - "\n", - "The only thing we can tell beforehand\n", - "is that say the outcome 2 has a certain probability. \n", - "If our favorite hobby is to spend an hour every evening throwing dice and \n", - "registering the sequence of outcomes, we will note that the numbers in the above domain" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "\\{2,3,4,5,6,7,8,9,10,11,12\\},\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "appear in a random order. After 11 throws the results may look like" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "\\{10,8,6,3,6,9,11,8,12,4,5\\}.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "## Stochastic variables\n", - "\n", - "\n", - "**Random variables are characterized by a domain which contains all possible values that the random value may take. This domain has a corresponding probability distribution function(PDF)**.\n", + "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", - "## Stochastic variables and the main concepts, the discrete case\n", "\n", - "There are two main concepts associated with a stochastic variable. The\n", - "*domain* is the set $\\mathbb D = \\{x\\}$ of all accessible values\n", - "the variable can assume, so that $X \\in \\mathbb D$. An example of a\n", - "discrete domain is the set of six different numbers that we may get by\n", - "throwing of a dice, $x\\in\\{1,\\,2,\\,3,\\,4,\\,5,\\,6\\}$.\n", + "To arrive at the above expression we have assumed that we can make the following assumptions:\n", "\n", - "The *probability distribution function (PDF)* is a function\n", - "$p(x)$ on the domain which, in the discrete case, gives us the\n", - "probability or relative frequency with which these values of $X$\n", - "occur" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "p(x) = \\mathrm{Prob}(X=x).\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "## Stochastic variables and the main concepts, the continuous case\n", + " * 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", - "In the continuous case, the PDF does not directly depict the\n", - "actual probability. Instead we define the probability for the\n", - "stochastic variable to assume any value on an infinitesimal interval\n", - "around $x$ to be $p(x)dx$. The continuous function $p(x)$ then gives us\n", - "the *density* of the probability rather than the probability\n", - "itself. The probability for a stochastic variable to assume any value\n", - "on a non-infinitesimal interval $[a,\\,b]$ is then just the integral" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "\\mathrm{Prob}(a\\leq X\\leq b) = \\int_a^b p(x)dx.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "Qualitatively speaking, a stochastic variable represents the values of\n", - "numbers chosen as if by chance from some specified PDF so that the\n", - "selection of a large set of these numbers reproduces this PDF.\n", + " * 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", - "## The cumulative probability\n", - "\n", - "Of interest to us is the *cumulative probability\n", - "distribution function* (**CDF**), $P(x)$, which is just the probability\n", - "for a stochastic variable $X$ to assume any value less than $x$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "P(x)=\\mathrm{Prob(}X\\leq x\\mathrm{)} =\n", - "\\int_{-\\infty}^x p(x^{\\prime})dx^{\\prime}.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "The relation between a CDF and its corresponding PDF is then" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "p(x) = \\frac{d}{dx}P(x).\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "## Properties of PDFs\n", + "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", - "There are two properties that all PDFs must satisfy. The first one is\n", - "positivity (assuming that the PDF is normalized)" + "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": "markdown", - "metadata": {}, + "cell_type": "code", + "execution_count": 28, + "metadata": { + "collapsed": false + }, + "outputs": [], "source": [ - "$$\n", - "0 \\leq p(x) \\leq 1.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "Naturally, it would be nonsensical for any of the values of the domain\n", - "to occur with a probability greater than $1$ or less than $0$. Also,\n", - "the PDF must be normalized. That is, all the probabilities must add up\n", - "to unity. The probability of \"anything\" to happen is always unity. For\n", - "both discrete and continuous PDFs, this condition is" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "\\begin{align*}\n", - "\\sum_{x_i\\in\\mathbb D} p(x_i) & = 1,\\\\\n", - "\\int_{x\\in\\mathbb D} p(x)\\,dx & = 1.\n", - "\\end{align*}\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "## Important distributions, the uniform distribution\n", + "# 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", - "The first one\n", - "is the most basic PDF; namely the uniform distribution" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "\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", - "$$\n", - "\\begin{equation}\n", - "p(x) = \\frac{1}{b-a}\\theta(x-a)\\theta(b-x).\n", - "\\label{eq:unifromPDF} \\tag{10}\n", - "\\end{equation}\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "For $a=0$ and $b=1$ we have" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "\\begin{array}{ll}\n", - "p(x)dx = dx & \\in [0,1].\n", - "\\end{array}\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "The latter distribution is used to generate random numbers. For other PDFs, one needs normally a mapping from this distribution to say for example the exponential distribution. \n", + "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", - "## Gaussian distribution\n", + "def image_path(fig_id):\n", + " return os.path.join(FIGURE_ID, fig_id)\n", "\n", - "The second one is the Gaussian Distribution" + "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": [ - "$$\n", - "p(x) = \\frac{1}{\\sigma\\sqrt{2\\pi}} \\exp{(-\\frac{(x-\\mu)^2}{2\\sigma^2})},\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "with mean value $\\mu$ and standard deviation $\\sigma$. If $\\mu=0$ and $\\sigma=1$, it is normally called the **standard normal distribution**" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "p(x) = \\frac{1}{\\sqrt{2\\pi}} \\exp{(-\\frac{x^2}{2})},\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "The following simple Python code plots the above distribution for different values of $\\mu$ and $\\sigma$." + "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." ] }, { @@ -4291,754 +2041,31 @@ }, "outputs": [], "source": [ - "import numpy as np\n", - "from math import acos, exp, sqrt\n", - "from matplotlib import pyplot as plt\n", - "from matplotlib import rc, rcParams\n", - "import matplotlib.units as units\n", - "import matplotlib.ticker as ticker\n", - "rc('text',usetex=True)\n", - "rc('font',**{'family':'serif','serif':['Gaussian distribution']})\n", - "font = {'family' : 'serif',\n", - " 'color' : 'darkred',\n", - " 'weight' : 'normal',\n", - " 'size' : 16,\n", - " }\n", - "pi = acos(-1.0)\n", - "mu0 = 0.0\n", - "sigma0 = 1.0\n", - "mu1= 1.0\n", - "sigma1 = 2.0\n", - "mu2 = 2.0\n", - "sigma2 = 4.0\n", + "from pylab import plt, mpl\n", + "plt.style.use('seaborn')\n", + "mpl.rcParams['font.family'] = 'serif'\n", "\n", - "x = np.linspace(-20.0, 20.0)\n", - "v0 = np.exp(-(x*x-2*x*mu0+mu0*mu0)/(2*sigma0*sigma0))/sqrt(2*pi*sigma0*sigma0)\n", - "v1 = np.exp(-(x*x-2*x*mu1+mu1*mu1)/(2*sigma1*sigma1))/sqrt(2*pi*sigma1*sigma1)\n", - "v2 = np.exp(-(x*x-2*x*mu2+mu2*mu2)/(2*sigma2*sigma2))/sqrt(2*pi*sigma2*sigma2)\n", - "plt.plot(x, v0, 'b-', x, v1, 'r-', x, v2, 'g-')\n", - "plt.title(r'{\\bf Gaussian distributions}', fontsize=20)\n", - "plt.text(-19, 0.3, r'Parameters: $\\mu = 0$, $\\sigma = 1$', fontdict=font)\n", - "plt.text(-19, 0.18, r'Parameters: $\\mu = 1$, $\\sigma = 2$', fontdict=font)\n", - "plt.text(-19, 0.08, r'Parameters: $\\mu = 2$, $\\sigma = 4$', fontdict=font)\n", - "plt.xlabel(r'$x$',fontsize=20)\n", - "plt.ylabel(r'$p(x)$ [MeV]',fontsize=20)\n", - "\n", - "# Tweak spacing to prevent clipping of ylabel \n", - "plt.subplots_adjust(left=0.15)\n", - "plt.savefig('gaussian.pdf', format='pdf')\n", - "plt.show()" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "## Exponential distribution\n", - "\n", - "Another important distribution in science is the exponential distribution" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "p(x) = \\alpha\\exp{-(\\alpha x)}.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "## Expectation values\n", - "\n", - "Let $h(x)$ be an arbitrary continuous function on the domain of the stochastic\n", - "variable $X$ whose PDF is $p(x)$. We define the *expectation value*\n", - "of $h$ with respect to $p$ as follows" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "\n", - "
\n", - "\n", - "$$\n", - "\\begin{equation}\n", - "\\langle h \\rangle_X \\equiv \\int\\! h(x)p(x)\\,dx\n", - "\\label{eq:expectation_value_of_h_wrt_p} \\tag{11}\n", - "\\end{equation}\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "Whenever the PDF is known implicitly, like in this case, we will drop\n", - "the index $X$ for clarity. \n", - "A particularly useful class of special expectation values are the\n", - "*moments*. The $n$-th moment of the PDF $p$ is defined as\n", - "follows" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "\\langle x^n \\rangle \\equiv \\int\\! x^n p(x)\\,dx\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "## Stochastic variables and the main concepts, mean values\n", - "\n", - "The zero-th moment $\\langle 1\\rangle$ is just the normalization condition of\n", - "$p$. The first moment, $\\langle x\\rangle$, is called the *mean* of $p$\n", - "and often denoted by the letter $\\mu$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "\\langle x\\rangle = \\mu \\equiv \\int x p(x)dx,\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "for a continuous distribution and" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "\\langle x\\rangle = \\mu \\equiv \\sum_{i=1}^N x_i p(x_i),\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "for a discrete distribution. \n", - "Qualitatively it represents the centroid or the average value of the\n", - "PDF and is therefore simply called the expectation value of $p(x)$.\n", - "\n", - "\n", - "\n", - "## Stochastic variables and the main concepts, central moments, the variance\n", - "\n", - "\n", - "A special version of the moments is the set of *central moments*, the n-th central moment defined as" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "\\langle (x-\\langle x\\rangle )^n\\rangle \\equiv \\int\\! (x-\\langle x\\rangle)^n p(x)\\,dx\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "The zero-th and first central moments are both trivial, equal $1$ and\n", - "$0$, respectively. But the second central moment, known as the\n", - "*variance* of $p$, is of particular interest. For the stochastic\n", - "variable $X$, the variance is denoted as $\\sigma^2_X$ or $\\mathrm{Var}(X)$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "\\begin{align*}\n", - "\\sigma^2_X &=\\mathrm{Var}(X) = \\langle (x-\\langle x\\rangle)^2\\rangle =\n", - "\\int (x-\\langle x\\rangle)^2 p(x)dx\\\\\n", - "& = \\int\\left(x^2 - 2 x \\langle x\\rangle^{2} +\\langle x\\rangle^2\\right)p(x)dx\\\\\n", - "& = \\langle x^2\\rangle - 2 \\langle x\\rangle\\langle x\\rangle + \\langle x\\rangle^2\\\\\n", - "& = \\langle x^2 \\rangle - \\langle x\\rangle^2\n", - "\\end{align*}\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "The square root of the variance, $\\sigma =\\sqrt{\\langle (x-\\langle x\\rangle)^2\\rangle}$ is called the \n", - "**standard deviation** of $p$. It is the RMS (root-mean-square)\n", - "value of the deviation of the PDF from its mean value, interpreted\n", - "qualitatively as the \"spread\" of $p$ around its mean.\n", - "\n", - "\n", - "\n", - "\n", - "\n", - "## Probability Distribution Functions\n", - "\n", - "\n", - "The following table collects properties of probability distribution functions.\n", - "In our notation we reserve the label $p(x)$ for the probability of a certain event,\n", - "while $P(x)$ is the cumulative probability. \n", - "\n", - "\n", - "\n", - "\n", - "\n", - "\n", - "\n", - "\n", - "\n", - "\n", - "\n", - "\n", - "\n", - "\n", - "\n", - "
Discrete PDF Continuous PDF
Domain $\\left\\{x_1, x_2, x_3, \\dots, x_N\\right\\}$ $[a,b]$
Probability $p(x_i)$ $p(x)dx$
Cumulative $P_i=\\sum_{l=1}^ip(x_l)$ $P(x)=\\int_a^xp(t)dt$
Positivity $0 \\le p(x_i) \\le 1$ $p(x) \\ge 0$
Positivity $0 \\le P_i \\le 1$ $0 \\le P(x) \\le 1$
Monotonic $P_i \\ge P_j$ if $x_i \\ge x_j$ $P(x_i) \\ge P(x_j)$ if $x_i \\ge x_j$
Normalization $P_N=1$ $P(b)=1$
\n", - "\n", - "\n", - "\n", - "\n", - "## Probability Distribution Functions\n", - "\n", - "With a PDF we can compute expectation values of selected quantities such as" + "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": [ - "$$\n", - "\\langle x^k\\rangle=\\sum_{i=1}^{N}x_i^kp(x_i),\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "if we have a discrete PDF or" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "\\langle x^k\\rangle=\\int_a^b x^kp(x)dx,\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "in the case of a continuous PDF. We have already defined the mean value $\\mu$\n", - "and the variance $\\sigma^2$. \n", - "\n", - "\n", - "\n", - "## The three famous Probability Distribution Functions\n", - "\n", - "\n", - "There are at least three PDFs which one may encounter. These are the\n", - "\n", - "**Uniform distribution**" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "p(x)=\\frac{1}{b-a}\\Theta(x-a)\\Theta(b-x),\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "yielding probabilities different from zero in the interval $[a,b]$.\n", - "\n", - "**The exponential distribution**" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "p(x)=\\alpha \\exp{(-\\alpha x)},\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "yielding probabilities different from zero in the interval $[0,\\infty)$ and with mean value" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "\\mu = \\int_0^{\\infty}xp(x)dx=\\int_0^{\\infty}x\\alpha \\exp{(-\\alpha x)}dx=\\frac{1}{\\alpha},\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "with variance" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "\\sigma^2=\\int_0^{\\infty}x^2p(x)dx-\\mu^2 = \\frac{1}{\\alpha^2}.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "## Probability Distribution Functions, the normal distribution\n", - "\n", - "Finally, we have the so-called univariate normal distribution, or just the **normal distribution**" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "p(x)=\\frac{1}{b\\sqrt{2\\pi}}\\exp{\\left(-\\frac{(x-a)^2}{2b^2}\\right)}\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "with probabilities different from zero in the interval $(-\\infty,\\infty)$.\n", - "The integral $\\int_{-\\infty}^{\\infty}\\exp{\\left(-(x^2\\right)}dx$ appears in many calculations, its value\n", - "is $\\sqrt{\\pi}$, a result we will need when we compute the mean value and the variance.\n", - "The mean value is" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "\\mu = \\int_0^{\\infty}xp(x)dx=\\frac{1}{b\\sqrt{2\\pi}}\\int_{-\\infty}^{\\infty}x \\exp{\\left(-\\frac{(x-a)^2}{2b^2}\\right)}dx,\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "which becomes with a suitable change of variables" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "\\mu =\\frac{1}{b\\sqrt{2\\pi}}\\int_{-\\infty}^{\\infty}b\\sqrt{2}(a+b\\sqrt{2}y)\\exp{-y^2}dy=a.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "## Probability Distribution Functions, the normal distribution\n", - "\n", - "Similarly, the variance becomes" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "\\sigma^2 = \\frac{1}{b\\sqrt{2\\pi}}\\int_{-\\infty}^{\\infty}(x-\\mu)^2 \\exp{\\left(-\\frac{(x-a)^2}{2b^2}\\right)}dx,\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "and inserting the mean value and performing a variable change we obtain" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "\\sigma^2 = \\frac{1}{b\\sqrt{2\\pi}}\\int_{-\\infty}^{\\infty}b\\sqrt{2}(b\\sqrt{2}y)^2\\exp{\\left(-y^2\\right)}dy=\n", - "\\frac{2b^2}{\\sqrt{\\pi}}\\int_{-\\infty}^{\\infty}y^2\\exp{\\left(-y^2\\right)}dy,\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "and performing a final integration by parts we obtain the well-known result $\\sigma^2=b^2$.\n", - "It is useful to introduce the standard normal distribution as well, defined by $\\mu=a=0$, viz. a distribution\n", - "centered around zero and with a variance $\\sigma^2=1$, leading to" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "\n", - "
\n", - "\n", - "$$\n", - "\\begin{equation}\n", - " p(x)=\\frac{1}{\\sqrt{2\\pi}}\\exp{\\left(-\\frac{x^2}{2}\\right)}.\n", - "\\label{_auto8} \\tag{12}\n", - "\\end{equation}\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "## Probability Distribution Functions, the cumulative distribution\n", - "\n", - "\n", - "The exponential and uniform distributions have simple cumulative functions,\n", - "whereas the normal distribution does not, being proportional to the so-called\n", - "error function $erf(x)$, given by" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "P(x) = \\frac{1}{\\sqrt{2\\pi}}\\int_{-\\infty}^x\\exp{\\left(-\\frac{t^2}{2}\\right)}dt,\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "which is difficult to evaluate in a quick way. \n", - "\n", - "\n", - "\n", - "\n", - "## Probability Distribution Functions, other important distribution\n", - "\n", - "\n", - "Some other PDFs which one encounters often in the natural sciences are the binomial distribution" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "p(x) = \\left(\\begin{array}{c} n \\\\ x\\end{array}\\right)y^x(1-y)^{n-x} \\hspace{0.5cm}x=0,1,\\dots,n,\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "where $y$ is the probability for a specific event, such as the tossing of a coin or moving left or right\n", - "in case of a random walker. Note that $x$ is a discrete stochastic variable. \n", - "\n", - "The sequence of binomial trials is characterized by the following definitions\n", - "\n", - " * Every experiment is thought to consist of $N$ independent trials.\n", - "\n", - " * In every independent trial one registers if a specific situation happens or not, such as the jump to the left or right of a random walker.\n", - "\n", - " * The probability for every outcome in a single trial has the same value, for example the outcome of tossing (either heads or tails) a coin is always $1/2$.\n", - "\n", - "## Probability Distribution Functions, the binomial distribution\n", - "\n", - "\n", - "In order to compute the mean and variance we need to recall Newton's binomial\n", - "formula" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "(a+b)^m=\\sum_{n=0}^m \\left(\\begin{array}{c} m \\\\ n\\end{array}\\right)a^nb^{m-n},\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "which can be used to show that" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "\\sum_{x=0}^n\\left(\\begin{array}{c} n \\\\ x\\end{array}\\right)y^x(1-y)^{n-x} = (y+1-y)^n = 1,\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "the PDF is normalized to one. \n", - "The mean value is" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "\\mu = \\sum_{x=0}^n x\\left(\\begin{array}{c} n \\\\ x\\end{array}\\right)y^x(1-y)^{n-x} =\n", - "\\sum_{x=0}^n x\\frac{n!}{x!(n-x)!}y^x(1-y)^{n-x},\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "resulting in" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "\\mu = \n", - "\\sum_{x=0}^n x\\frac{(n-1)!}{(x-1)!(n-1-(x-1))!}y^{x-1}(1-y)^{n-1-(x-1)},\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "which we rewrite as" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "\\mu=ny\\sum_{\\nu=0}^n\\left(\\begin{array}{c} n-1 \\\\ \\nu\\end{array}\\right)y^{\\nu}(1-y)^{n-1-\\nu} =ny(y+1-y)^{n-1}=ny.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "The variance is slightly trickier to get. It reads $\\sigma^2=ny(1-y)$. \n", - "\n", - "\n", - "## Probability Distribution Functions, Poisson's distribution\n", - "\n", - "\n", - "Another important distribution with discrete stochastic variables $x$ is \n", - "the Poisson model, which resembles the exponential distribution and reads" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "p(x) = \\frac{\\lambda^x}{x!} e^{-\\lambda} \\hspace{0.5cm}x=0,1,\\dots,;\\lambda > 0.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "In this case both the mean value and the variance are easier to calculate," - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "\\mu = \\sum_{x=0}^{\\infty} x \\frac{\\lambda^x}{x!} e^{-\\lambda} = \\lambda e^{-\\lambda}\\sum_{x=1}^{\\infty}\n", - "\\frac{\\lambda^{x-1}}{(x-1)!}=\\lambda,\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "and the variance is $\\sigma^2=\\lambda$. \n", - "\n", - "\n", - "\n", - "\n", - "\n", - "## Probability Distribution Functions, Poisson's distribution\n", - "\n", - "An example of applications of the Poisson distribution could be the counting\n", - "of the number of $\\alpha$-particles emitted from a radioactive source in a given time interval.\n", - "In the limit of $n\\rightarrow \\infty$ and for small probabilities $y$, the binomial distribution\n", - "approaches the Poisson distribution. Setting $\\lambda = ny$, with $y$ the probability for an event in\n", - "the binomial distribution we can show that" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "\\lim_{n\\rightarrow \\infty}\\left(\\begin{array}{c} n \\\\ x\\end{array}\\right)y^x(1-y)^{n-x} e^{-\\lambda}=\\sum_{x=1}^{\\infty}\\frac{\\lambda^x}{x!} e^{-\\lambda}.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "## Meet the covariance!\n", - "\n", - "An important quantity in a statistical analysis is the so-called covariance. \n", - "\n", - "Consider the set $\\{X_i\\}$ of $n$\n", - "stochastic variables (not necessarily uncorrelated) with the\n", - "multivariate PDF $P(x_1,\\dots,x_n)$. The *covariance* of two\n", - "of the stochastic variables, $X_i$ and $X_j$, is defined as follows" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "\n", - "
\n", - "\n", - "$$\n", - "\\begin{equation}\n", - "\\mathrm{Cov}(X_i,\\,X_j) = \\langle (x_i-\\langle x_i\\rangle)(x_j-\\langle x_j\\rangle)\\rangle \n", - "\\label{_auto9} \\tag{13}\n", - "\\end{equation}\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "\n", - "
\n", - "\n", - "$$\n", - "\\begin{equation} \n", - "=\\int\\cdots\\int (x_i-\\langle x_i\\rangle)(x_j-\\langle x_j\\rangle)P(x_1,\\dots,x_n)\\,dx_1\\dots dx_n,\n", - "\\label{eq:def_covariance} \\tag{14}\n", - "\\end{equation}\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "with" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "\\langle x_i\\rangle =\n", - "\\int\\cdots\\int x_i P(x_1,\\dots,x_n)\\,dx_1\\dots dx_n.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "## Meet the covariance in matrix disguise\n", - "\n", - "If we consider the above covariance as a matrix" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "C_{ij} =\\mathrm{Cov}(X_i,\\,X_j),\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "then the diagonal elements are just the familiar\n", - "variances, $C_{ii} = \\mathrm{Cov}(X_i,\\,X_i) = \\mathrm{Var}(X_i)$. It turns out that\n", - "all the off-diagonal elements are zero if the stochastic variables are\n", - "uncorrelated. \n", - "\n", + "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", - "## Covariance" + "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." ] }, { @@ -5049,551 +2076,26 @@ }, "outputs": [], "source": [ - "# Importing various packages\n", - "from math import exp, sqrt\n", - "from random import random, seed\n", - "import numpy as np\n", - "import matplotlib.pyplot as plt\n", - "\n", - "def covariance(x, y, n):\n", - " sum = 0.0\n", - " mean_x = np.mean(x)\n", - " mean_y = np.mean(y)\n", - " for i in range(0, n):\n", - " sum += (x[(i)]-mean_x)*(y[i]-mean_y)\n", - " return sum/n\n", - "\n", - "n = 10\n", - "\n", - "x=np.random.normal(size=n)\n", - "y = 4+3*x+np.random.normal(size=n)\n", - "covxy = covariance(x,y,n)\n", - "print(covxy)\n", - "z = np.vstack((x, y))\n", - "c = np.cov(z.T)\n", - "\n", - "print(c)" + "\"\"\" \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": [ - "## Meet the covariance, uncorrelated events\n", - "\n", - "\n", - "Consider the stochastic variables $X_i$ and $X_j$, ($i\\neq j$). We have" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "\\begin{align*}\n", - "Cov(X_i,\\,X_j) &= \\langle (x_i-\\langle x_i\\rangle)(x_j-\\langle x_j\\rangle)\\rangle\\\\\n", - "&=\\langle x_i x_j - x_i\\langle x_j\\rangle - \\langle x_i\\rangle x_j + \\langle x_i\\rangle\\langle x_j\\rangle\\rangle\\\\\n", - "&=\\langle x_i x_j\\rangle - \\langle x_i\\langle x_j\\rangle\\rangle - \\langle \\langle x_i\\rangle x_j \\rangle +\n", - "\\langle \\langle x_i\\rangle\\langle x_j\\rangle\\rangle \\\\\n", - "&=\\langle x_i x_j\\rangle - \\langle x_i\\rangle\\langle x_j\\rangle - \\langle x_i\\rangle\\langle x_j\\rangle +\n", - "\\langle x_i\\rangle\\langle x_j\\rangle \\\\\n", - "&=\\langle x_i x_j\\rangle - \\langle x_i\\rangle\\langle x_j\\rangle\n", - "\\end{align*}\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "If $X_i$ and $X_j$ are independent (assuming $i \\neq j$), we have that" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "\\langle x_i x_j\\rangle = \\langle x_i\\rangle\\langle x_j\\rangle,\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "leading to" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "Cov(X_i, X_j) = 0 \\hspace{0.1cm} (i\\neq j).\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "## Numerical experiments and the covariance\n", - "\n", - "\n", - "Now that we have constructed an idealized mathematical framework, let\n", - "us try to apply it to empirical observations. Examples of relevant\n", - "physical phenomena may be spontaneous decays of nuclei, or a purely\n", - "mathematical set of numbers produced by some deterministic\n", - "mechanism. It is the latter we will deal with, using so-called pseudo-random\n", - "number generators. In general our observations will contain only a limited set of\n", - "observables. We remind the reader that\n", - "a *stochastic process* is a process that produces sequentially a\n", - "chain of values" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "\\{x_1, x_2,\\dots\\,x_k,\\dots\\}.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "## Numerical experiments and the covariance\n", - "\n", - "We will call these\n", - "values our *measurements* and the entire set as our measured\n", - "*sample*. The action of measuring all the elements of a sample\n", - "we will call a stochastic *experiment* (since, operationally,\n", - "they are often associated with results of empirical observation of\n", - "some physical or mathematical phenomena; precisely an experiment). We\n", - "assume that these values are distributed according to some \n", - "PDF $p_X^{\\phantom X}(x)$, where $X$ is just the formal symbol for the\n", - "stochastic variable whose PDF is $p_X^{\\phantom X}(x)$. Instead of\n", - "trying to determine the full distribution $p$ we are often only\n", - "interested in finding the few lowest moments, like the mean\n", - "$\\mu_X^{\\phantom X}$ and the variance $\\sigma_X^{\\phantom X}$.\n", - "\n", - "\n", - "\n", - "\n", - "## Numerical experiments and the covariance, actual situations\n", - "\n", - "In practical situations however, a sample is always of finite size. Let that\n", - "size be $n$. The expectation value of a sample $\\alpha$, the **sample mean**, is then defined as follows" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "\\langle x_{\\alpha} \\rangle \\equiv \\frac{1}{n}\\sum_{k=1}^n x_{\\alpha,k}.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "The *sample variance* is:" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "\\mathrm{Var}(x) \\equiv \\frac{1}{n}\\sum_{k=1}^n (x_{\\alpha,k} - \\langle x_{\\alpha} \\rangle)^2,\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "with its square root being the *standard deviation of the sample*. \n", - "\n", - "\n", - "\n", - "\n", - "## Numerical experiments and the covariance, our observables\n", - "\n", - "You can think of the above observables as a set of quantities which define\n", - "a given experiment. This experiment is then repeated several times, say $m$ times.\n", - "The total average is then" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "\n", - "
\n", - "\n", - "$$\n", - "\\begin{equation}\n", - "\\langle X_m \\rangle= \\frac{1}{m}\\sum_{\\alpha=1}^mx_{\\alpha}=\\frac{1}{mn}\\sum_{\\alpha, k} x_{\\alpha,k},\n", - "\\label{eq:exptmean} \\tag{15}\n", - "\\end{equation}\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "where the last sums end at $m$ and $n$.\n", - "The total variance is" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "\\sigma^2_m= \\frac{1}{mn^2}\\sum_{\\alpha=1}^m(\\langle x_{\\alpha} \\rangle-\\langle X_m \\rangle)^2,\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "which we rewrite as" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "\n", - "
\n", - "\n", - "$$\n", - "\\begin{equation}\n", - "\\sigma^2_m=\\frac{1}{m}\\sum_{\\alpha=1}^m\\sum_{kl=1}^n (x_{\\alpha,k}-\\langle X_m \\rangle)(x_{\\alpha,l}-\\langle X_m \\rangle).\n", - "\\label{eq:exptvariance} \\tag{16}\n", - "\\end{equation}\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "## Numerical experiments and the covariance, the sample variance\n", - "\n", - "\n", - "We define also the sample variance $\\sigma^2$ of all $mn$ individual experiments as" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "\n", - "
\n", - "\n", - "$$\n", - "\\begin{equation}\n", - "\\sigma^2=\\frac{1}{mn}\\sum_{\\alpha=1}^m\\sum_{k=1}^n (x_{\\alpha,k}-\\langle X_m \\rangle)^2.\n", - "\\label{eq:sampleexptvariance} \\tag{17}\n", - "\\end{equation}\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "These quantities, being known experimental values or the results from our calculations, \n", - "may differ, in some cases\n", - "significantly, from the similarly named\n", - "exact values for the mean value $\\mu_X$, the variance $\\mathrm{Var}(X)$\n", - "and the covariance $\\mathrm{Cov}(X,Y)$. \n", - "\n", - "\n", - "\n", - "## Numerical experiments and the covariance, central limit theorem\n", - "\n", - "\n", - "The central limit theorem states that the PDF $\\tilde{p}(z)$ of\n", - "the average of $m$ random values corresponding to a PDF $p(x)$ \n", - "is a normal distribution whose mean is the \n", - "mean value of the PDF $p(x)$ and whose variance is the variance\n", - "of the PDF $p(x)$ divided by $m$, the number of values used to compute $z$.\n", - "\n", - "The central limit theorem leads then to the well-known expression for the\n", - "standard deviation, given by" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "\\sigma_m=\n", - "\\frac{\\sigma}{\\sqrt{m}}.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "In many cases the above estimate for the standard deviation, in particular if correlations are strong, may be too simplistic. We need therefore a more precise defintion of the error and the variance in our results.\n", - "\n", - "\n", - "\n", - "## Definition of Correlation Functions and Standard Deviation\n", - "\n", - "Our estimate of the true average $\\mu_{X}$ is the sample mean $\\langle X_m \\rangle$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "\\mu_{X}^{\\phantom X} \\approx X_m=\\frac{1}{mn}\\sum_{\\alpha=1}^m\\sum_{k=1}^n x_{\\alpha,k}.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "We can then use Eq. ([eq:exptvariance](#eq:exptvariance))" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "\\sigma^2_m=\\frac{1}{mn^2}\\sum_{\\alpha=1}^m\\sum_{kl=1}^n (x_{\\alpha,k}-\\langle X_m \\rangle)(x_{\\alpha,l}-\\langle X_m \\rangle),\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "and rewrite it as" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "\\sigma^2_m=\\frac{\\sigma^2}{n}+\\frac{2}{mn^2}\\sum_{\\alpha=1}^m\\sum_{k\n", - "
\n", - "\n", - "$$\n", - "\\begin{equation}\n", - "\\kappa_d = \\frac{f_d}{\\sigma^2}\n", - "\\label{eq:autocorrelformal} \\tag{18}\n", - "\\end{equation}\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "which gives us a useful measure of the correlation pair correlation\n", - "starting always at $1$ for $d=0$.\n", - "\n", - "\n", - "\n", - "## Definition of Correlation Functions and Standard Deviation, sample variance\n", - "\n", - "\n", - "The sample variance of the $mn$ experiments can now be\n", - "written in terms of the autocorrelation function" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "\n", - "
\n", - "\n", - "$$\n", - "\\begin{equation}\n", - "\\sigma_m^2=\\frac{\\sigma^2}{n}+\\frac{2}{n}\\cdot\\sigma^2\\sum_{d=1}^{n-1}\n", - "\\frac{f_d}{\\sigma^2}=\\left(1+2\\sum_{d=1}^{n-1}\\kappa_d\\right)\\frac{1}{n}\\sigma^2=\\frac{\\tau}{n}\\cdot\\sigma^2\n", - "\\label{eq:error_estimate_corr_time} \\tag{19}\n", - "\\end{equation}\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "and we see that $\\sigma_m$ can be expressed in terms of the\n", - "uncorrelated sample variance times a correction factor $\\tau$ which\n", - "accounts for the correlation between measurements. We call this\n", - "correction factor the *autocorrelation time*" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "\n", - "
\n", - "\n", - "$$\n", - "\\begin{equation}\n", - "\\tau = 1+2\\sum_{d=1}^{n-1}\\kappa_d\n", - "\\label{eq:autocorrelation_time} \\tag{20}\n", - "\\end{equation}\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "\n", - "\n", - "For a correlation free experiment, $\\tau$\n", - "equals 1. \n", - "\n", - "\n", - "\n", - "\n", - "\n", - "## Definition of Correlation Functions and Standard Deviation\n", - "\n", - "From the point of view of\n", - "Eq. ([eq:error_estimate_corr_time](#eq:error_estimate_corr_time)) we can interpret a sequential\n", - "correlation as an effective reduction of the number of measurements by\n", - "a factor $\\tau$. The effective number of measurements becomes" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "n_\\mathrm{eff} = \\frac{n}{\\tau}\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "To neglect the autocorrelation time $\\tau$ will always cause our\n", - "simple uncorrelated estimate of $\\sigma_m^2\\approx \\sigma^2/n$ to\n", - "be less than the true sample error. The estimate of the error will be\n", - "too \"good\". On the other hand, the calculation of the full\n", - "autocorrelation time poses an efficiency problem if the set of\n", - "measurements is very large. The solution to this problem is given by \n", - "more practically oriented methods like the blocking technique.\n", - "\n", - "\n", - "\n", - "\n", - "\n", - "## Code to compute the Covariance matrix and the Covariance" + "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." ] }, { @@ -5604,606 +2106,40 @@ }, "outputs": [], "source": [ - "# Importing various packages\n", - "from math import exp, sqrt\n", - "from random import random, seed\n", - "import numpy as np\n", - "import matplotlib.pyplot as plt\n", + "# 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", - "# Sample covariance, note the factor 1/(n-1)\n", - "def covariance(x, y, n):\n", - " sum = 0.0\n", - " mean_x = np.mean(x)\n", - " mean_y = np.mean(y)\n", - " for i in range(0, n):\n", - " sum += (x[(i)]-mean_x)*(y[i]-mean_y)\n", - " return sum/(n-1.)\n", + "# 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", - "n = 100\n", - "x = np.random.normal(size=n)\n", - "print(np.mean(x))\n", - "y = 4+3*x+np.random.normal(size=n)\n", - "print(np.mean(y))\n", - "z = x**3+np.random.normal(size=n)\n", - "print(np.mean(z))\n", - "covxx = covariance(x,x,n)\n", - "covyy = covariance(y,y,n)\n", - "covzz = covariance(z,z,n)\n", - "covxy = covariance(x,y,n)\n", - "covxz = covariance(x,z,n)\n", - "covyz = covariance(y,z,n)\n", - "print(covxx,covyy, covzz)\n", - "print(covxy,covxz, covyz)\n", - "w = np.vstack((x, y, z))\n", - "#print(w)\n", - "c = np.cov(w)\n", - "print(c)\n", - "#eigen = np.zeros(n)\n", - "Eigvals, Eigvecs = np.linalg.eig(c)\n", - "print(Eigvals)" + "# 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": [ - "# Random Numbers\n", - "\n", - "\n", - "Uniform deviates are just random numbers that lie within a specified range\n", - "(typically 0 to 1), with any one number in the range just as likely as any other. They\n", - "are, in other words, what you probably think random numbers are. However,\n", - "we want to distinguish uniform deviates from other sorts of random numbers, for\n", - "example numbers drawn from a normal (Gaussian) distribution of specified mean\n", - "and standard deviation. These other sorts of deviates are almost always generated by\n", - "performing appropriate operations on one or more uniform deviates, as we will see\n", - "in subsequent sections. So, a reliable source of random uniform deviates, the subject\n", - "of this section, is an essential building block for any sort of stochastic modeling\n", - "or Monte Carlo computer work.\n", - "\n", - "\n", - "\n", - "\n", - "# Random Numbers, better name: pseudo random numbers\n", - "\n", - "\n", - "A disclaimer is however appropriate. It should be fairly obvious that \n", - "something as deterministic as a computer cannot generate purely random numbers.\n", - "\n", - "Numbers generated by any of the standard algorithms are in reality pseudo random\n", - "numbers, hopefully abiding to the following criteria:\n", - "\n", - " * they produce a uniform distribution in the interval [0,1].\n", - "\n", - " * correlations between random numbers are negligible\n", - "\n", - " * the period before the same sequence of random numbers is repeated is as large as possible and finally\n", - "\n", - " * the algorithm should be fast.\n", - "\n", - "# Random number generator RNG\n", - "\n", - " The most common random number generators are based on so-called\n", - "Linear congruential relations of the type" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "N_i=(aN_{i-1}+c) \\mathrm{MOD} (M),\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "which yield a number in the interval [0,1] through" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "x_i=N_i/M\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "The number \n", - "$M$ is called the period and it should be as large as possible \n", - " and \n", - "$N_0$ is the starting value, or seed. The function $\\mathrm{MOD}$ means the remainder,\n", - "that is if we were to evaluate $(13)\\mathrm{MOD}(9)$, the outcome is the remainder\n", - "of the division $13/9$, namely $4$.\n", - "\n", - "\n", - "\n", - "# Random number generator RNG and periodic outputs\n", - "\n", - "\n", - "The problem with such generators is that their outputs are periodic;\n", - "they \n", - "will start to repeat themselves with a period that is at most $M$. If however\n", - "the parameters $a$ and $c$ are badly chosen, the period may be even shorter.\n", - "\n", - "Consider the following example" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "N_i=(6N_{i-1}+7) \\mathrm{MOD} (5),\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "with a seed $N_0=2$. This generator produces the sequence\n", - "$4,1,3,0,2,4,1,3,0,2,...\\dots$, i.e., a sequence with period $5$.\n", - "However, increasing $M$ may not guarantee a larger period as the following\n", - "example shows" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "N_i=(27N_{i-1}+11) \\mathrm{MOD} (54),\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "which still, with $N_0=2$, results in $11,38,11,38,11,38,\\dots$, a period of\n", - "just $2$.\n", - "\n", - "\n", - "\n", - "# Random number generator RNG and its period\n", - "\n", - "Typical periods for the random generators provided in the program library \n", - "are of the order of $\\sim 10^9$ or larger. Other random number generators which have\n", - "become increasingly popular are so-called shift-register generators.\n", - "In these generators each successive number depends on many preceding\n", - "values (rather than the last values as in the linear congruential\n", - "generator).\n", - "For example, you could make a shift register generator whose $l$th \n", - "number is the sum of the $l-i$th and $l-j$th values with modulo $M$," - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "N_l=(aN_{l-i}+cN_{l-j})\\mathrm{MOD}(M).\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "# Random number generator RNG, other examples\n", - "\n", - "Such a generator again produces a sequence of pseudorandom numbers\n", - "but this time with a period much larger than $M$.\n", - "It is also possible to construct more elaborate algorithms by including\n", - "more than two past terms in the sum of each iteration.\n", - "One example is the generator of [Marsaglia and Zaman](http://dl.acm.org/citation.cfm?id=187154)\n", - "which consists of two congruential relations" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "\n", - "
\n", - "\n", - "$$\n", - "\\begin{equation}\n", - " N_l=(N_{l-3}-N_{l-1})\\mathrm{MOD}(2^{31}-69),\n", - "\\label{eq:mz1} \\tag{21}\n", - "\\end{equation}\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "followed by" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "\n", - "
\n", - "\n", - "$$\n", - "\\begin{equation}\n", - " N_l=(69069N_{l-1}+1013904243)\\mathrm{MOD}(2^{32}),\n", - "\\label{eq:mz2} \\tag{22}\n", - "\\end{equation}\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "which according to the authors has a period larger than $2^{94}$.\n", - "\n", - "\n", - "\n", - "# Random number generator RNG, other examples\n", - "\n", - "Instead of using modular addition, we could use the bitwise\n", - "exclusive-OR ($\\oplus$) operation so that" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "N_l=(N_{l-i})\\oplus (N_{l-j})\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "where the bitwise action of $\\oplus$ means that if $N_{l-i}=N_{l-j}$ the result is\n", - "$0$ whereas if $N_{l-i}\\ne N_{l-j}$ the result is\n", - "$1$. As an example, consider the case where $N_{l-i}=6$ and $N_{l-j}=11$. The first\n", - "one has a bit representation (using 4 bits only) which reads $0110$ whereas the \n", - "second number is $1011$. Employing the $\\oplus$ operator yields \n", - "$1101$, or $2^3+2^2+2^0=13$.\n", - "\n", - "In Fortran90, the bitwise $\\oplus$ operation is coded through the intrinsic\n", - "function $\\mathrm{IEOR}(m,n)$ where $m$ and $n$ are the input numbers, while in $C$\n", - "it is given by $m\\wedge n$. \n", - "\n", - "\n", - "\n", - "\n", - "# Random number generator RNG, RAN0\n", - "\n", - "\n", - "We show here how the linear congruential algorithm can be implemented, namely" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "N_i=(aN_{i-1}) \\mathrm{MOD} (M).\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "However, since $a$ and $N_{i-1}$ are integers and their multiplication \n", - "could become greater than the standard 32 bit integer, there is a trick via \n", - "Schrage's algorithm which approximates the multiplication\n", - "of large integers through the factorization" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "M=aq+r,\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "where we have defined" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "q=[M/a],\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "and" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "r = M\\hspace{0.1cm}\\mathrm{MOD} \\hspace{0.1cm}a.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "where the brackets denote integer division. In the code below the numbers \n", - "$q$ and $r$ are chosen so that $r < q$.\n", - "\n", - "\n", - "\n", - "\n", - "\n", - "# Random number generator RNG, RAN0\n", - "\n", - "\n", - "To see how this works we note first that" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "\n", - "
\n", - "\n", - "$$\n", - "\\begin{equation}\n", - "(aN_{i-1}) \\mathrm{MOD} (M)= (aN_{i-1}-[N_{i-1}/q]M)\\mathrm{MOD} (M),\n", - "\\label{eq:rntrick1} \\tag{23}\n", - "\\end{equation}\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "since we can add or subtract any integer multiple of $M$ from $aN_{i-1}$.\n", - "The last term $[N_{i-1}/q]M\\mathrm{MOD}(M)$ is zero since the integer division \n", - "$[N_{i-1}/q]$ just yields a constant which is multiplied with $M$. \n", - "\n", - "\n", - "\n", - "\n", - "# Random number generator RNG, RAN0\n", - "\n", - "We can now rewrite Eq. ([eq:rntrick1](#eq:rntrick1)) as" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "\n", - "
\n", - "\n", - "$$\n", - "\\begin{equation}\n", - "(aN_{i-1}) \\mathrm{MOD} (M)= (aN_{i-1}-[N_{i-1}/q](aq+r))\\mathrm{MOD} (M),\n", - "\\label{eq:rntrick2} \\tag{24}\n", - "\\end{equation}\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "which results\n", - "in" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "\n", - "
\n", - "\n", - "$$\n", - "\\begin{equation}\n", - "(aN_{i-1}) \\mathrm{MOD} (M)= \\left(a(N_{i-1}-[N_{i-1}/q]q)-[N_{i-1}/q]r)\\right)\\mathrm{MOD} (M),\n", - "\\label{eq:rntrick3} \\tag{25}\n", - "\\end{equation}\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "yielding" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "\n", - "
\n", - "\n", - "$$\n", - "\\begin{equation}\n", - "(aN_{i-1}) \\mathrm{MOD} (M)= \\left(a(N_{i-1}\\mathrm{MOD} (q)) -[N_{i-1}/q]r)\\right)\\mathrm{MOD} (M).\n", - "\\label{eq:rntrick4} \\tag{26}\n", - "\\end{equation}\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "# Random number generator RNG, RAN0\n", - "\n", - "The term $[N_{i-1}/q]r$ is always smaller or equal $N_{i-1}(r/q)$ and with $r < q$ we obtain always a \n", - "number smaller than $N_{i-1}$, which is smaller than $M$. \n", - "And since the number $N_{i-1}\\mathrm{MOD} (q)$ is between zero and $q-1$ then\n", - "$a(N_{i-1}\\mathrm{MOD} (q))< aq$. Combined with our definition of $q=[M/a]$ ensures that \n", - "this term is also smaller than $M$ meaning that both terms fit into a\n", - "32-bit signed integer. None of these two terms can be negative, but their difference could.\n", - "The algorithm below adds $M$ if their difference is negative.\n", - "Note that the program uses the bitwise $\\oplus$ operator to generate\n", - "the starting point for each generation of a random number. The period\n", - "of $ran0$ is $\\sim 2.1\\times 10^{9}$. A special feature of this\n", - "algorithm is that is should never be called with the initial seed \n", - "set to $0$. \n", - "\n", - "\n", - "\n", - "\n", - "# Random number generator RNG, RAN0 code" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - " /*\n", - " ** The function\n", - " ** ran0()\n", - " ** is an \"Minimal\" random number generator of Park and Miller\n", - " ** Set or reset the input value\n", - " ** idum to any integer value (except the unlikely value MASK)\n", - " ** to initialize the sequence; idum must not be altered between\n", - " ** calls for sucessive deviates in a sequence.\n", - " ** The function returns a uniform deviate between 0.0 and 1.0.\n", - " */\n", - " double ran0(long &idum)\n", - " {\n", - " const int a = 16807, m = 2147483647, q = 127773;\n", - " const int r = 2836, MASK = 123459876;\n", - " const double am = 1./m;\n", - " long k;\n", - " double ans;\n", - " idum ^= MASK;\n", - " k = (*idum)/q;\n", - " idum = a*(idum - k*q) - r*k;\n", - " // add m if negative difference\n", - " if(idum < 0) idum += m;\n", - " ans=am*(idum);\n", - " idum ^= MASK;\n", - " return ans;\n", - " } // End: function ran0() \n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "## Properties of Selected Random Number Generators\n", - "\n", - "\n", - "As mentioned previously, the underlying PDF for the generation of\n", - "random numbers is the uniform distribution, meaning that the \n", - "probability for finding a number $x$ in the interval [0,1] is $p(x)=1$.\n", - "\n", - "A random number generator should produce numbers which are uniformly distributed\n", - "in this interval. The table shows the distribution of $N=10000$ random\n", - "numbers generated by the functions in the program library.\n", - "We note in this table that the number of points in the various\n", - "intervals $0.0-0.1$, $0.1-0.2$ etc are fairly close to $1000$, with some minor\n", - "deviations. \n", - "\n", - "Two additional measures are the standard deviation $\\sigma$ and the mean\n", - "$\\mu=\\langle x\\rangle$.\n", - "\n", - "\n", - "\n", - "## Properties of Selected Random Number Generators\n", - "\n", - "For the uniform distribution, the mean value $\\mu$ is then" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "\\mu=\\langle x\\rangle=\\frac{1}{2}\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "while the standard deviation is" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "\\sigma=\\sqrt{\\langle x^2\\rangle-\\mu^2}=\\frac{1}{\\sqrt{12}}=0.2886.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "## Properties of Selected Random Number Generators\n", - "\n", - "The various random number generators produce results which agree rather well with\n", - "these limiting values. \n", - "\n", - "\n", - "\n", - "\n", - "\n", - "\n", - "\n", - "\n", - "\n", - "\n", - "\n", - "\n", - "\n", - "\n", - "\n", - "\n", - "\n", - "\n", - "\n", - "
$x$-bin ran0 ran1 ran2 ran3
0.0-0.1 1013 991 938 1047
0.1-0.2 1002 1009 1040 1030
0.2-0.3 989 999 1030 993
0.3-0.4 939 960 1023 937
0.4-0.5 1038 1001 1002 992
0.5-0.6 1037 1047 1009 1009
0.6-0.7 1005 989 1003 989
0.7-0.8 986 962 985 954
0.8-0.9 1000 1027 1009 1023
0.9-1.0 991 1015 961 1026
$\\mu$ 0.4997 0.5018 0.4992 0.4990
$\\sigma$ 0.2882 0.2892 0.2861 0.2915
\n", - "\n", - "\n", - "\n", - "## Simple demonstration of RNGs using python\n", - "\n", - "The following simple Python code plots the distribution of the produced random numbers using the linear congruential RNG employed by Python. The trend displayed in the previous table is seen rather clearly." + "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." ] }, { @@ -6214,85 +2150,20 @@ }, "outputs": [], "source": [ - "#!/usr/bin/env python\n", - "import numpy as np\n", - "import matplotlib.mlab as mlab\n", - "import matplotlib.pyplot as plt\n", - "import random\n", - "\n", - "# initialize the rng with a seed\n", - "random.seed() \n", - "counts = 10000\n", - "values = np.zeros(counts) \n", - "for i in range (1, counts, 1):\n", - " values[i] = random.random()\n", - "\n", - "# the histogram of the data\n", - "n, bins, patches = plt.hist(values, 10, facecolor='green')\n", - "\n", - "plt.xlabel('$x$')\n", - "plt.ylabel('Number of counts')\n", - "plt.title(r'Test of uniform distribution')\n", - "plt.axis([0, 1, 0, 1100])\n", - "plt.grid(True)\n", - "plt.show()" + "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": [ - "## Properties of Selected Random Number Generators\n", - "\n", - "Since our random numbers, which are typically generated via a linear congruential algorithm,\n", - "are never fully independent, we can then define \n", - "an important test which measures the degree of correlation, namely the so-called \n", - "auto-correlation function defined previously, see again Eq. ([eq:autocorrelformal](#eq:autocorrelformal)).\n", - "We rewrite it here as" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "C_k=\\frac{f_d}\n", - " {\\sigma^2},\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "with $C_0=1$. Recall that \n", - "$\\sigma^2=\\langle x_i^2\\rangle-\\langle x_i\\rangle^2$ and that" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "f_d = \\frac{1}{nm}\\sum_{\\alpha=1}^m\\sum_{k=1}^{n-d}(x_{\\alpha,k}-\\langle X_m \\rangle)(x_{\\alpha,k+d}-\\langle X_m \\rangle),\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "The non-vanishing of $C_k$ for $k\\ne 0$ means that the random\n", - "numbers are not independent. The independence of the random numbers is crucial \n", - "in the evaluation of other expectation values. If they are not independent, our\n", - "assumption for approximating $\\sigma_N$ is no longer valid.\n", - "\n", - "\n", - "\n", - "\n", - "\n", - "## Autocorrelation function\n", - "This program computes the autocorrelation function as discussed in the equation on the previous slide for random numbers generated with the normal distribution $N(0,1)$." + "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." ] }, { @@ -6303,382 +2174,20 @@ }, "outputs": [], "source": [ - "# Importing various packages\n", - "from math import exp, sqrt\n", - "from random import random, seed\n", - "import numpy as np\n", - "import matplotlib.pyplot as plt\n", - "\n", - "def autocovariance(x, n, k, mean_x):\n", - " sum = 0.0\n", - " for i in range(0, n-k):\n", - " sum += (x[(i+k)]-mean_x)*(x[i]-mean_x)\n", - " return sum/n\n", - "\n", - "n = 1000\n", - "x=np.random.normal(size=n)\n", - "autocor = np.zeros(n)\n", - "figaxis = np.zeros(n)\n", - "mean_x=np.mean(x)\n", - "var_x = np.var(x)\n", - "print(mean_x, var_x)\n", - "for i in range (0, n):\n", - " figaxis[i] = i\n", - " autocor[i]=(autocovariance(x, n, i, mean_x))/var_x \n", - "\n", - "plt.plot(figaxis, autocor, \"r-\")\n", - "plt.axis([0,n,-0.1, 1.0])\n", - "plt.xlabel(r'$i$')\n", - "plt.ylabel(r'$\\gamma_i$')\n", - "plt.title(r'Autocorrelation function')\n", - "plt.show()" + "# 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": [ - "As can be seen from the plot, the first point gives back the variance and a value of one. \n", - "For the remaining values we notice that there are still non-zero values for the auto-correlation function.\n", - "\n", - "\n", - "\n", - "\n", - "\n", - "\n", - "\n", - "\n", - "\n", - "\n", - "\n", - "\n", - "\n", - "\n", - "\n", - "\n", - "\n", - "## Correlation function and which random number generators should I use\n", - "\n", - "The program here computes the correlation function for one of the standard functions included with the c++ compiler." - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - " // This function computes the autocorrelation function for \n", - " // the standard c++ random number generator\n", - " \n", - " #include \n", - " #include \n", - " #include \n", - " #include \n", - " using namespace std;\n", - " // output file as global variable\n", - " ofstream ofile; \n", - " \n", - " // Main function begins here \n", - " int main(int argc, char* argv[])\n", - " {\n", - " int n;\n", - " char *outfilename;\n", - " \n", - " cin >> n;\n", - " double MCint = 0.; double MCintsqr2=0.;\n", - " double invers_period = 1./RAND_MAX; // initialise the random number generator\n", - " srand(time(NULL)); // This produces the so-called seed in MC jargon\n", - " // Compute the variance and the mean value of the uniform distribution\n", - " // Compute also the specific values x for each cycle in order to be able to\n", - " // the covariance and the correlation function \n", - " // Read in output file, abort if there are too few command-line arguments\n", - " if( argc <= 2 ){\n", - " cout << \"Bad Usage: \" << argv[0] << \n", - " \t \" read also output file and number of cycles on same line\" << endl;\n", - " exit(1);\n", - " }\n", - " else{\n", - " outfilename=argv[1];\n", - " }\n", - " ofile.open(outfilename); \n", - " // Get the number of Monte-Carlo samples\n", - " n = atoi(argv[2]);\n", - " double *X; \n", - " X = new double[n];\n", - " for (int i = 0; i < n; i++){\n", - " double x = double(rand())*invers_period; \n", - " X[i] = x;\n", - " MCint += x;\n", - " MCintsqr2 += x*x;\n", - " }\n", - " double Mean = MCint/((double) n );\n", - " MCintsqr2 = MCintsqr2/((double) n );\n", - " double STDev = sqrt(MCintsqr2-Mean*Mean);\n", - " double Variance = MCintsqr2-Mean*Mean;\n", - " // Write mean value and standard deviation \n", - " cout << \" Standard deviation= \" << STDev << \" Integral = \" << Mean << endl;\n", - " \n", - " // Now we compute the autocorrelation function\n", - " double *autocor; autocor = new double[n];\n", - " for (int j = 0; j < n; j++){\n", - " double sum = 0.0;\n", - " for (int k = 0; k < (n-j); k++){\n", - " \t sum += (X[k]-Mean)*(X[k+j]-Mean); \n", - " }\n", - " autocor[j] = sum/Variance/((double) n );\n", - " ofile << setiosflags(ios::showpoint | ios::uppercase);\n", - " ofile << setw(15) << setprecision(8) << j;\n", - " ofile << setw(15) << setprecision(8) << autocor[j] << endl;\n", - " }\n", - " ofile.close(); // close output file\n", - " return 0;\n", - " } // end of main program \n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "# Which RNG should I use?\n", - "\n", - "* C++ has a class called **random**. The [random class](http://www.cplusplus.com/reference/random/) contains a large selection of RNGs and is highly recommended. Some of these RNGs have very large periods making it thereby very safe to use these RNGs in case one is performing large calculations. In particular, the [Mersenne twister random number engine](http://www.cplusplus.com/reference/random/mersenne_twister_engine/) has a period of $2^{19937}$. \n", - "\n", - "* Add RNGs in Python\n", - "\n", - "## How to use the Mersenne generator\n", - "\n", - "The following part of a c++ code (from project 4) sets up the uniform distribution for $x\\in [0,1]$." - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - " /*\n", - " \n", - " // You need this \n", - " #include \n", - " \n", - " // Initialize the seed and call the Mersienne algo\n", - " std::random_device rd;\n", - " std::mt19937_64 gen(rd());\n", - " // Set up the uniform distribution for x \\in [[0, 1]\n", - " std::uniform_real_distribution RandomNumberGenerator(0.0,1.0);\n", - " \n", - " // Now use the RNG\n", - " int ix = (int) (RandomNumberGenerator(gen)*NSpins);\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "## Why blocking?\n", - " Statistical analysis\n", - " * Monte Carlo simulations can be treated as *computer experiments*\n", - "\n", - " * The results can be analysed with the same statistical tools as we would use analysing experimental data.\n", - "\n", - " * As in all experiments, we are looking for expectation values and an estimate of how accurate they are, i.e., possible sources for errors.\n", - "\n", - "A very good article which explains blocking is H. Flyvbjerg and H. G. Petersen, *Error estimates on averages of correlated data*, [Journal of Chemical Physics 91, 461-466 (1989)](http://scitation.aip.org/content/aip/journal/jcp/91/1/10.1063/1.457480).\n", - "\n", - "\n", - "\n", - "\n", - "\n", - "\n", - "## Why blocking?\n", - " Statistical analysis\n", - " * As in other experiments, Monte Carlo experiments have two classes of errors:\n", - "\n", - " * Statistical errors\n", - "\n", - " * Systematical errors\n", - "\n", - "\n", - " * Statistical errors can be estimated using standard tools from statistics\n", - "\n", - " * Systematical errors are method specific and must be treated differently from case to case. (In VMC a common source is the step length or time step in importance sampling)\n", - "\n", - "## Code to demonstrate the calculation of the autocorrelation function\n", - "The following code computes the autocorrelation function, the covariance and the standard deviation\n", - "for standard RNG. \n", - "The [following file](https://github.com/CompPhysics/ComputationalPhysics2/tree/gh-pages/doc/Programs/LecturePrograms/programs/Blocking/autocorrelation.cpp) gives the code." - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - " // This function computes the autocorrelation function for \n", - " // the Mersenne random number generator with a uniform distribution\n", - " #include \n", - " #include \n", - " #include \n", - " #include \n", - " #include \n", - " #include \n", - " #include \n", - " #include \n", - " using namespace std;\n", - " using namespace arma;\n", - " // output file\n", - " ofstream ofile;\n", - " \n", - " // Main function begins here \n", - " int main(int argc, char* argv[])\n", - " {\n", - " int MonteCarloCycles;\n", - " string filename;\n", - " if (argc > 1) {\n", - " filename=argv[1];\n", - " MonteCarloCycles = atoi(argv[2]);\n", - " string fileout = filename;\n", - " string argument = to_string(MonteCarloCycles);\n", - " fileout.append(argument);\n", - " ofile.open(fileout);\n", - " }\n", - " \n", - " // Compute the variance and the mean value of the uniform distribution\n", - " // Compute also the specific values x for each cycle in order to be able to\n", - " // compute the covariance and the correlation function \n", - " \n", - " vec X = zeros(MonteCarloCycles);\n", - " double MCint = 0.; double MCintsqr2=0.;\n", - " std::random_device rd;\n", - " std::mt19937_64 gen(rd());\n", - " // Set up the uniform distribution for x \\in [[0, 1]\n", - " std::uniform_real_distribution RandomNumberGenerator(0.0,1.0);\n", - " for (int i = 0; i < MonteCarloCycles; i++){\n", - " double x = RandomNumberGenerator(gen); \n", - " X(i) = x;\n", - " MCint += x;\n", - " MCintsqr2 += x*x;\n", - " }\n", - " double Mean = MCint/((double) MonteCarloCycles );\n", - " MCintsqr2 = MCintsqr2/((double) MonteCarloCycles );\n", - " double STDev = sqrt(MCintsqr2-Mean*Mean);\n", - " double Variance = MCintsqr2-Mean*Mean;\n", - " // Write mean value and variance\n", - " cout << \" Sample variance= \" << Variance << \" Mean value = \" << Mean << endl;\n", - " // Now we compute the autocorrelation function\n", - " vec autocorrelation = zeros(MonteCarloCycles);\n", - " for (int j = 0; j < MonteCarloCycles; j++){\n", - " double sum = 0.0;\n", - " for (int k = 0; k < (MonteCarloCycles-j); k++){\n", - " sum += (X(k)-Mean)*(X(k+j)-Mean); \n", - " }\n", - " autocorrelation(j) = sum/Variance/((double) MonteCarloCycles );\n", - " ofile << setiosflags(ios::showpoint | ios::uppercase);\n", - " ofile << setw(15) << setprecision(8) << j;\n", - " ofile << setw(15) << setprecision(8) << autocorrelation(j) << endl;\n", - " }\n", - " // Now compute the exact covariance using the autocorrelation function\n", - " double Covariance = 0.0;\n", - " for (int j = 0; j < MonteCarloCycles; j++){\n", - " Covariance += autocorrelation(j);\n", - " }\n", - " Covariance *= 2.0/((double) MonteCarloCycles);\n", - " // Compute now the total variance, including the covariance, and obtain the standard deviation\n", - " double TotalVariance = (Variance/((double) MonteCarloCycles ))+Covariance;\n", - " cout << \"Covariance =\" << Covariance << \"Totalvariance= \" << TotalVariance << \"Sample Variance/n= \" << (Variance/((double) MonteCarloCycles )) << endl;\n", - " cout << \" STD from sample variance= \" << sqrt(Variance/((double) MonteCarloCycles )) << \" STD with covariance = \" << sqrt(TotalVariance) << endl;\n", - " \n", - " ofile.close(); // close output file\n", - " return 0;\n", - " } // end of main program \n", - " \n", - " \n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "## What is blocking?\n", - " Blocking\n", - " * Say that we have a set of samples from a Monte Carlo experiment\n", - "\n", - " * Assuming (wrongly) that our samples are uncorrelated our best estimate of the standard deviation of the mean $\\langle \\mathbf{M}\\rangle$ is given by" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "\\sigma=\\sqrt{\\frac{1}{n}\\left(\\langle \\mathbf{M}^2\\rangle-\\langle \\mathbf{M}\\rangle^2\\right)}\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "* If the samples are correlated we can rewrite our results to show that" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "\\sigma=\\sqrt{\\frac{1+2\\tau/\\Delta t}{n}\\left(\\langle \\mathbf{M}^2\\rangle-\\langle \\mathbf{M}\\rangle^2\\right)}\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "where $\\tau$ is the correlation time (the time between a sample and the next uncorrelated sample) and $\\Delta t$ is time between each sample\n", - "\n", - "\n", - "\n", - "## What is blocking?\n", - " Blocking \n", - " * If $\\Delta t\\gg\\tau$ our first estimate of $\\sigma$ still holds\n", - "\n", - " * Much more common that $\\Delta t<\\tau$\n", - "\n", - " * In the method of data blocking we divide the sequence of samples into blocks\n", - "\n", - " * We then take the mean $\\langle \\mathbf{M}_i\\rangle$ of block $i=1\\ldots n_{blocks}$ to calculate the total mean and variance\n", - "\n", - " * The size of each block must be so large that sample $j$ of block $i$ is not correlated with sample $j$ of block $i+1$\n", - "\n", - " * The correlation time $\\tau$ would be a good choice\n", - "\n", - "## What is blocking?\n", - " Blocking\n", - " * Problem: We don't know $\\tau$ or it is too expensive to compute\n", - "\n", - " * Solution: Make a plot of std. dev. as a function of blocksize\n", - "\n", - " * The estimate of std. dev. of correlated data is too low $\\to$ the error will increase with increasing block size until the blocks are uncorrelated, where we reach a plateau\n", - "\n", - " * When the std. dev. stops increasing the blocks are uncorrelated\n", - "\n", - "## Implementation\n", - "\n", - " * Do a Monte Carlo simulation, storing all samples to file\n", - "\n", - " * Do the statistical analysis on this file, independently of your Monte Carlo program\n", - "\n", - " * Read the file into an array\n", - "\n", - " * Loop over various block sizes\n", - "\n", - " * For each block size $n_b$, loop over the array in steps of $n_b$ taking the mean of elements $i n_b,\\ldots,(i+1) n_b$\n", - "\n", - " * Take the mean and variance of the resulting array\n", - "\n", - " * Write the results for each block size to file for later\n", - " analysis\n", - "\n", - "## Actual implementation with code, main function\n", - "When the file gets large, it can be useful to write your data in binary mode instead of ascii characters.\n", - "The [following python file](https://github.com/CompPhysics/MachineLearning/blob/master/doc/Programs/Sampling/analysis.py) reads data from file with the output from every Monte Carlo cycle." + "With **scikitlearn** we are now ready to use linear regression and fit our data." ] }, { @@ -6689,199 +2198,261 @@ }, "outputs": [], "source": [ - "# Blocking\n", - " @timeFunction\n", - " def blocking(self, blockSizeMax = 500):\n", - " blockSizeMin = 1\n", - "\n", - " self.blockSizes = []\n", - " self.meanVec = []\n", - " self.varVec = []\n", - "\n", - " for i in range(blockSizeMin, blockSizeMax):\n", - " if(len(self.data) % i != 0):\n", - " pass#continue\n", - " blockSize = i\n", - " meanTempVec = []\n", - " varTempVec = []\n", - " startPoint = 0\n", - " endPoint = blockSize\n", - "\n", - " while endPoint <= len(self.data):\n", - " meanTempVec.append(np.average(self.data[startPoint:endPoint]))\n", - " startPoint = endPoint\n", - " endPoint += blockSize\n", - " mean, var = np.average(meanTempVec), np.var(meanTempVec)/len(meanTempVec)\n", - " self.meanVec.append(mean)\n", - " self.varVec.append(var)\n", - " self.blockSizes.append(blockSize)\n", - "\n", - " self.blockingAvg = np.average(self.meanVec[-200:])\n", - " self.blockingVar = (np.average(self.varVec[-200:]))\n", - " self.blockingStd = np.sqrt(self.blockingVar)" + "clf = skl.LinearRegression().fit(X, Energies)\n", + "fity = clf.predict(X)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ - "## The Bootstrap method\n", + "Pretty simple! \n", + "Now we can print measures of how our fit is doing, the coefficients from the fits and plot the final fit together with our data." + ] + }, + { + "cell_type": "code", + "execution_count": 35, + "metadata": { + "collapsed": false + }, + "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", - "The Bootstrap resampling method is also very popular. It is very simple:\n", - "\n", - "1. Start with your sample of measurements and compute the sample variance and the mean values\n", - "\n", - "2. Then start again but pick in a random way the numbers in the sample and recalculate the mean and the sample variance.\n", - "\n", - "3. Repeat this $K$ times.\n", - "\n", - "It can be shown, see the article by [Efron](https://projecteuclid.org/download/pdf_1/euclid.aos/1176344552)\n", - "that it produces the correct standard deviation.\n", - "\n", - "This method is very useful for small ensembles of data points. \n", - "\n", - "\n", - "## Bootstrapping\n", - "Given a set of $N$ data, assume that we are interested in some \n", - "observable $\\theta$ which may be estimated from that set. This observable can also be for example the result of a fit based on all $N$ raw data. \n", - "Let us call the value of the observable obtained from the original \n", - "data set $\\hat{\\theta}$. One recreates from the sample repeatedly \n", - "other samples by choosing randomly $N$ data out of the original set. \n", - "This costs essentially nothing, since we just recycle the original data set for the building of new sets. \n", - "\n", - "\n", - "## Bootstrapping, recipe\n", - "Let us assume we have done this $K$ times and thus have $K$ sets of $N$ \n", - "data values each. \n", - "Of course some values will enter more than once in the new sets. For each of these sets one computes the observable $\\theta$ resulting in values $\\theta_k$ with $k = 1,...,K$. Then one determines" + "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": [ - "$$\n", - "\\tilde{\\theta} = \\frac{1}{K} \\sum_{k=1}^K \\theta_k,\n", - "$$" + "### Seeing the wood for the trees\n", + "\n", + "As a teaser, let us now see how we can do this with decision trees using **scikit-learn**. Later we will switch to so-called **random forests**!" + ] + }, + { + "cell_type": "code", + "execution_count": 36, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "\n", + "#Decision Tree Regression\n", + "from sklearn.tree import DecisionTreeRegressor\n", + "regr_1=DecisionTreeRegressor(max_depth=5)\n", + "regr_2=DecisionTreeRegressor(max_depth=7)\n", + "regr_3=DecisionTreeRegressor(max_depth=9)\n", + "regr_1.fit(X, Energies)\n", + "regr_2.fit(X, Energies)\n", + "regr_3.fit(X, Energies)\n", + "\n", + "\n", + "y_1 = regr_1.predict(X)\n", + "y_2 = regr_2.predict(X)\n", + "y_3=regr_3.predict(X)\n", + "Masses['Eapprox'] = y_3\n", + "# Plot the results\n", + "plt.figure()\n", + "plt.plot(A, Energies, color=\"blue\", label=\"Data\", linewidth=2)\n", + "plt.plot(A, y_1, color=\"red\", label=\"max_depth=5\", linewidth=2)\n", + "plt.plot(A, y_2, color=\"green\", label=\"max_depth=7\", linewidth=2)\n", + "plt.plot(A, y_3, color=\"m\", label=\"max_depth=9\", linewidth=2)\n", + "\n", + "plt.xlabel(\"$A$\")\n", + "plt.ylabel(\"$E$[MeV]\")\n", + "plt.title(\"Decision Tree Regression\")\n", + "plt.legend()\n", + "save_fig(\"Masses2016Trees\")\n", + "plt.show()\n", + "print(Masses)\n", + "print(np.mean( (Energies-y_1)**2))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ - "and" + "### And what about using neural networks?\n", + "\n", + "The **seaborn** package allows us to visualize data in an efficient way. Note that we use **scikit-learn**'s multi-layer perceptron (or feed forward neural network) \n", + "functionality." + ] + }, + { + "cell_type": "code", + "execution_count": 37, + "metadata": { + "collapsed": false + }, + "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": [ - "$$\n", - "sigma^2_{\\tilde{\\theta}} = \\frac{1}{K} \\sum_{k=1}^K \\left(\\theta_k-\\tilde{\\theta}\\right)^2.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "These are estimators for $\\angle\\theta\\rangle$ and its variance. They are not unbiased and therefore \n", - "$\\tilde{\\theta}\\neq\\hat{\\theta}$ for finite K. \n", + "## A first summary\n", "\n", - "The difference is called bias and gives an idea on how far away the result may be from \n", - "the true $\\angle\\theta\\rangle$. As final result for the observable one quotes $\\angle\\theta\\rangle = \\tilde{\\theta} \\pm \\sigma_{\\tilde{\\theta}}$ .\n", + "The aim behind these introductory words was to present to you various\n", + "Python libraries and their functionalities, in particular libraries like\n", + "**numpy**, **pandas**, **xarray** and **matplotlib** and other that make our life much easier\n", + "in handling various data sets and visualizing data. \n", + "\n", + "Furthermore,\n", + "**Scikit-Learn** allows us with few lines of code to implement popular\n", + "Machine Learning algorithms for supervised learning. Later we will meet **Tensorflow**, a powerful library for deep learning. \n", + "Now it is time to dive more into the details of various methods. We will start with linear regression and try to take a deeper look at what it entails.\n", "\n", "\n", "\n", - "## Bootstrapping, [code](https://github.com/CompPhysics/MachineLearning/blob/master/doc/Programs/Sampling/analysis.py)" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - " # Bootstrap\n", - " @timeFunction\n", - " def bootstrap(self, nBoots = 1000):\n", - " bootVec = np.zeros(nBoots)\n", - " for k in range(0,nBoots):\n", - " bootVec[k] = np.average(np.random.choice(self.data, len(self.data)))\n", - " self.bootAvg = np.average(bootVec)\n", - " self.bootVar = np.var(bootVec)\n", - " self.bootStd = np.std(bootVec)\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "## Jackknife, [code](https://github.com/CompPhysics/MachineLearning/blob/master/doc/Programs/Sampling/analysis.py)" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - " # Jackknife\n", - " @timeFunction\n", - " def jackknife(self):\n", - " jackknVec = np.zeros(len(self.data))\n", - " for k in range(0,len(self.data)):\n", - " jackknVec[k] = np.average(np.delete(self.data, k))\n", - " self.jackknAvg = self.avg - (len(self.data) - 1) * (np.average(jackknVec) - self.avg)\n", - " self.jackknVar = float(len(self.data) - 1) * np.var(jackknVec)\n", - " self.jackknStd = np.sqrt(self.jackknVar)\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "# Regression analysis, overarching aims\n", "\n", "\n", - "Regression modeling deals with the description of the sampling distribution of a given random variable $y$ varies as function of another variable or a set of such variables $\\hat{x} =[x_0, x_1,\\dots, x_p]^T$. \n", - "The first variable is called the **dependent**, the **outcome** or the **response** variable while the set of variables $\\hat{x}$ is called the independent variable, or the predictor variable or the explanatory variable. \n", "\n", - "A regression model aims at finding a likelihood function $p(y\\vert \\hat{x})$, that is the conditional distribution for $y$ with a given $\\hat{x}$. The estimation of $p(y\\vert \\hat{x})$ is made using a data set with \n", + "\n", + "\n", + "# Why Linear Regression (aka Ordinary Least Squares and family)\n", + "\n", + "Fitting a continuous function with linear parameterization in terms of the parameters $\\boldsymbol{\\beta}$.\n", + "* Method of choice for fitting a continuous function!\n", + "\n", + "* Gives an excellent introduction to central Machine Learning features with **understandable pedagogical** links to other methods like **Neural Networks**, **Support Vector Machines** etc\n", + "\n", + "* Analytical expression for the fitting parameters $\\boldsymbol{\\beta}$\n", + "\n", + "* Analytical expressions for statistical propertiers like mean values, variances, confidence intervals and more\n", + "\n", + "* Analytical relation with probabilistic interpretations \n", + "\n", + "* Easy to introduce basic concepts like bias-variance tradeoff, cross-validation, resampling and regularization techniques and many other ML topics\n", + "\n", + "* Easy to code! And links well with classification problems and logistic regression and neural networks\n", + "\n", + "* Allows for **easy** hands-on understanding of gradient descent methods\n", + "\n", + "* and many more features\n", + "\n", + "For more discussions of Ridge and Lasso regression, [Wessel van Wieringen's](https://arxiv.org/abs/1509.09169) article is highly recommended.\n", + "Similarly, [Mehta et al's article](https://arxiv.org/abs/1803.08823) is also recommended.\n", + "\n", + "\n", + "### Regression analysis, overarching aims\n", + "\n", + "Regression modeling deals with the description of the sampling distribution of a given random variable $y$ and how it varies as function of another variable or a set of such variables $\\boldsymbol{x} =[x_0, x_1,\\dots, x_{n-1}]^T$. \n", + "The first variable is called the **dependent**, the **outcome** or the **response** variable while the set of variables $\\boldsymbol{x}$ is called the independent variable, or the predictor variable or the explanatory variable. \n", + "\n", + "A regression model aims at finding a likelihood function $p(\\boldsymbol{y}\\vert \\boldsymbol{x})$, that is the conditional distribution for $\\boldsymbol{y}$ with a given $\\boldsymbol{x}$. The estimation of $p(\\boldsymbol{y}\\vert \\boldsymbol{x})$ is made using a data set with \n", "* $n$ cases $i = 0, 1, 2, \\dots, n-1$ \n", "\n", - "* Response (dependent or outcome) variable $y_i$ with $i = 0, 1, 2, \\dots, n-1$ \n", + "* Response (target, dependent or outcome) variable $y_i$ with $i = 0, 1, 2, \\dots, n-1$ \n", "\n", - "* $p$ Explanatory (independent or predictor) variables $\\hat{x}_i=[x_{i0}, x_{i1}, \\dots, x_{ip}]$ with $i = 0, 1, 2, \\dots, n-1$ \n", - "\n", - " The goal of the regression analysis is to extract/exploit relationship between $y_i$ and $\\hat{x}_i$ in or to infer causal dependencies, approximations to the likelihood functions, functional relationships and to make predictions .\n", - "\n", - "\n", - "\n", - "## Regression analysis, overarching aims II\n", + "* $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 are denoted $\\mathbf{X}$, with\n", - "$\\mathbf{X}$ as above. The matrix $\\mathbf{X}$ is called the *design\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 $\\mathbf{Y}$ (also as above). The variable $\\mathbf{Y}$ is\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 $\\mathbf{Y}$ in terms of\n", - "$\\mathbf{X}$ through a functional relationship like $Y_i =\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 $\\mathbf{X}$ and $\\mathbf{Y}$. This assumption gives rise to\n", - "the *linear regression model* where $\\beta = (\\beta_1, \\ldots,\n", - "\\beta_p)^{\\top}$ is the *regression parameter*. The parameter\n", - "$\\beta_j$, $j=1, \\ldots, p$, represents the effect size of covariate\n", - "$j$ on the response. That is, for each unit change in covariate $j$\n", - "(while keeping the other covariates fixed) the observed change in the\n", - "response is equal to $\\beta_j$. \n", + "between $\\boldsymbol{X}$ and $\\boldsymbol{y}$. This assumption gives rise to\n", + "the *linear regression model* where $\\boldsymbol{\\beta} = [\\beta_0, \\ldots,\n", + "\\beta_{p-1}]^{T}$ are the *regression parameters*. \n", + "\n", + "Linear regression gives us a set of analytical equations for the parameters $\\beta_j$.\n", "\n", "\n", + "### Examples\n", + "\n", + "In order to understand the relation among the predictors $p$, the set of data $n$ and the target (outcome, output etc) $\\boldsymbol{y}$,\n", + "consider the model we discussed for describing nuclear binding energies. \n", + "\n", + "There we assumed that we could parametrize the data using a polynomial approximation based on the liquid drop model.\n", + "Assuming" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "$$\n", + "BE(A) = a_0+a_1A+a_2A^{2/3}+a_3A^{-1/3}+a_4A^{-1},\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "we have five predictors, that is the intercept, the $A$ dependent term, the $A^{2/3}$ term and the $A^{-1/3}$ and $A^{-1}$ terms.\n", + "This gives $p=0,1,2,3,4$. Furthermore we have $n$ entries for each predictor. It means that our design matrix is a \n", + "$p\\times n$ matrix $\\boldsymbol{X}$.\n", + "\n", + "Here the predictors are based on a model we have made. A popular data set which is widely encountered in ML applications is the\n", + "so-called [credit card default data from Taiwan](https://www.sciencedirect.com/science/article/pii/S0957417407006719?via%3Dihub). The data set contains data on $n=30000$ credit card holders with predictors like gender, marital status, age, profession, education, etc. In total there are $24$ such predictors or attributes leading to a design matrix of dimensionality $24 \\times 30000$\n", "\n", "\n", "## General linear models\n", "\n", - "Before we proceed let us study a case from linear algebra where we aim at fitting a set of data $\\hat{y}=[y_0,y_1,\\dots,y_{n-1}]$. We could think of these data as a result of an experiment or a complicated numerical experiment. These data are functions of a series of variables $\\hat{x}=[x_0,x_1,\\dots,x_{n-1}]$, that is $y_i = y(x_i)$ with $i=0,1,2,\\dots,n-1$. The variables $x_i$ could represent physical quantities like time, temperature, position etc. We assume that $y(x)$ is a smooth function. \n", + "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" ] @@ -6891,7 +2462,7 @@ "metadata": {}, "source": [ "$$\n", - "y=y(x) \\rightarrow y(x_i)=\\tilde{y}_i+\\epsilon_i=\\sum_{j=0}^{n-1} \\beta_i x_i^j+\\epsilon_i,\n", + "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", "$$" ] }, @@ -6902,11 +2473,6 @@ "where $\\epsilon_i$ is the error in our approximation. \n", "\n", "\n", - "\n", - "\n", - "\n", - "## Rewriting the fitting procedure as a linear algebra problem\n", - "\n", "For every set of values $y_i,x_i$ we have thus the corresponding set of equations" ] }, @@ -6920,7 +2486,7 @@ "y_1&=\\beta_0+\\beta_1x_1^1+\\beta_2x_1^2+\\dots+\\beta_{n-1}x_1^{n-1}+\\epsilon_1\\\\\n", "y_2&=\\beta_0+\\beta_1x_2^1+\\beta_2x_2^2+\\dots+\\beta_{n-1}x_2^{n-1}+\\epsilon_2\\\\\n", "\\dots & \\dots \\\\\n", - "y_{n-1}&=\\beta_0+\\beta_1x_{n-1}^1+\\beta_2x_{n-1}^2+\\dots+\\beta_1x_{n-1}^{n-1}+\\epsilon_{n-1}.\\\\\n", + "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", "$$" ] @@ -6929,8 +2495,6 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "## Rewriting the fitting procedure as a linear algebra problem, follows\n", - "\n", "Defining the vectors" ] }, @@ -6939,7 +2503,7 @@ "metadata": {}, "source": [ "$$\n", - "\\hat{y} = [y_0,y_1, y_2,\\dots, y_{n-1}]^T,\n", + "\\boldsymbol{y} = [y_0,y_1, y_2,\\dots, y_{n-1}]^T,\n", "$$" ] }, @@ -6955,7 +2519,7 @@ "metadata": {}, "source": [ "$$\n", - "\\hat{\\beta} = [\\beta_0,\\beta_1, \\beta_2,\\dots, \\beta_{n-1}]^T,\n", + "\\boldsymbol{\\beta} = [\\beta_0,\\beta_1, \\beta_2,\\dots, \\beta_{n-1}]^T,\n", "$$" ] }, @@ -6971,7 +2535,7 @@ "metadata": {}, "source": [ "$$\n", - "\\hat{\\epsilon} = [\\epsilon_0,\\epsilon_1, \\epsilon_2,\\dots, \\epsilon_{n-1}]^T,\n", + "\\boldsymbol{\\epsilon} = [\\epsilon_0,\\epsilon_1, \\epsilon_2,\\dots, \\epsilon_{n-1}]^T,\n", "$$" ] }, @@ -6979,7 +2543,7 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "and the matrix" + "and the design matrix" ] }, { @@ -6987,7 +2551,7 @@ "metadata": {}, "source": [ "$$\n", - "\\hat{X}=\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", @@ -7010,7 +2574,7 @@ "metadata": {}, "source": [ "$$\n", - "\\hat{y} = \\hat{X}\\hat{\\beta}+\\hat{\\epsilon}.\n", + "\\boldsymbol{y} = \\boldsymbol{X}\\boldsymbol{\\beta}+\\boldsymbol{\\epsilon}.\n", "$$" ] }, @@ -7018,10 +2582,18 @@ "cell_type": "markdown", "metadata": {}, "source": [ + "The above design matrix is called a [Vandermonde matrix](https://en.wikipedia.org/wiki/Vandermonde_matrix).\n", + "\n", + "\n", + "\n", + "\n", "## Generalizing the fitting procedure as a linear algebra problem\n", "\n", - "We are obviously not limited to the above polynomial. We could replace the various powers of $x$ with elements of Fourier series, that is, instead of $x_i^j$ we could have $\\cos{(j x_i)}$ or $\\sin{(j x_i)}$, or time series or other orthogonal functions.\n", - "For every set of values $y_i,x_i$ we can then generalize the equations to" + "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" ] }, { @@ -7036,7 +2608,7 @@ "\\dots & \\dots \\\\\n", "y_{i}&=\\beta_0x_{i0}+\\beta_1x_{i1}+\\beta_2x_{i2}+\\dots+\\beta_{n-1}x_{in-1}+\\epsilon_i\\\\\n", "\\dots & \\dots \\\\\n", - "y_{n-1}&=\\beta_0x_{n-1,0}+\\beta_1x_{n-1,2}+\\beta_2x_{n-1,2}+\\dots+\\beta_1x_{n-1,n-1}+\\epsilon_{n-1}.\\\\\n", + "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", "$$" ] @@ -7045,9 +2617,9 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "## Generalizing the fitting procedure as a linear algebra problem\n", + "**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 $\\hat{X}$ as" + "We redefine in turn the matrix $\\boldsymbol{X}$ as" ] }, { @@ -7055,7 +2627,7 @@ "metadata": {}, "source": [ "$$\n", - "\\hat{X}=\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", @@ -7078,7 +2650,7 @@ "metadata": {}, "source": [ "$$\n", - "\\hat{y} = \\hat{X}\\hat{\\beta}+\\hat{\\epsilon}.\n", + "\\boldsymbol{y} = \\boldsymbol{X}\\boldsymbol{\\beta}+\\boldsymbol{\\epsilon}.\n", "$$" ] }, @@ -7086,14 +2658,9 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "The left-hand side of this equation forms know. Our error vector $\\hat{\\epsilon}$ and the parameter vector $\\hat{\\beta}$ are our unknow quantities. How can we obtain the optimal set of $\\beta_i$ values? \n", + "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", - "\n", - "\n", - "\n", - "## Optimizing our parameters\n", - "\n", - "We have defined the matrix $\\hat{X}$" + "We have defined the matrix $\\boldsymbol{X}$ via the equations" ] }, { @@ -7108,7 +2675,7 @@ "\\dots & \\dots \\\\\n", "y_{i}&=\\beta_0x_{i0}+\\beta_1x_{i1}+\\beta_2x_{i2}+\\dots+\\beta_{n-1}x_{in-1}+\\epsilon_1\\\\\n", "\\dots & \\dots \\\\\n", - "y_{n-1}&=\\beta_0x_{n-1,0}+\\beta_1x_{n-1,2}+\\beta_2x_{n-1,2}+\\dots+\\beta_1x_{n-1,n-1}+\\epsilon_{n-1}.\\\\\n", + "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", "$$" ] @@ -7117,9 +2684,102 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "## Optimizing our parameters, more details\n", + "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", - "We well use this matrix to define the approximation $\\hat{\\tilde{y}}$ via the unknown quantity $\\hat{\\beta}$ as" + "\n", + "## Our model for the nuclear binding energies\n", + "\n", + "In our introductory notes we looked at the so-called [liguid drop model](https://en.wikipedia.org/wiki/Semi-empirical_mass_formula). Let us remind ourselves about what we did by looking at the code.\n", + "\n", + "We restate the parts of the code we are most interested in." + ] + }, + { + "cell_type": "code", + "execution_count": 38, + "metadata": { + "collapsed": false + }, + "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" ] }, { @@ -7127,7 +2787,7 @@ "metadata": {}, "source": [ "$$\n", - "\\hat{\\tilde{y}}= \\hat{X}\\hat{\\beta},\n", + "\\boldsymbol{\\tilde{y}}= \\boldsymbol{X}\\boldsymbol{\\beta},\n", "$$" ] }, @@ -7135,7 +2795,11 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "and in order to find the optimal parameters $\\beta_i$ instead of solving the above linear algebra problem, we define a function which gives a measure of the spread between the values $y_i$ (which represent hopefully the exact values) and the parametrized values $\\tilde{y}_i$, namely" + "throughout these lectures. \n", + "\n", + "\n", + "\n", + "With the above we use the design matrix to define the approximation $\\boldsymbol{\\tilde{y}}$ via the unknown quantity $\\boldsymbol{\\beta}$ as" ] }, { @@ -7143,7 +2807,7 @@ "metadata": {}, "source": [ "$$\n", - "Q(\\hat{\\beta})=\\sum_{i=0}^{n-1}\\left(y_i-\\tilde{y}_i\\right)^2=\\left(\\hat{y}-\\hat{\\tilde{y}}\\right)^T\\left(\\hat{y}-\\hat{\\tilde{y}}\\right),\n", + "\\boldsymbol{\\tilde{y}}= \\boldsymbol{X}\\boldsymbol{\\beta},\n", "$$" ] }, @@ -7151,7 +2815,7 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "or using the matrix $\\hat{X}$ as" + "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" ] }, { @@ -7159,7 +2823,7 @@ "metadata": {}, "source": [ "$$\n", - "Q(\\hat{\\beta})=\\left(\\hat{y}-\\hat{X}\\hat{\\beta}\\right)^T\\left(\\hat{y}-\\hat{X}\\hat{\\beta}\\right).\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", "$$" ] }, @@ -7167,8 +2831,51 @@ "cell_type": "markdown", "metadata": {}, "source": [ + "or using the matrix $\\boldsymbol{X}$ and in a more compact matrix-vector notation as" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "$$\n", + "C(\\boldsymbol{\\beta})=\\frac{1}{n}\\left\\{\\left(\\boldsymbol{y}-\\boldsymbol{X}^T\\boldsymbol{\\beta}\\right)^T\\left(\\boldsymbol{y}-\\boldsymbol{X}^T\\boldsymbol{\\beta}\\right)\\right\\}.\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "This function is one possible way to define the so-called cost function.\n", + "\n", + "\n", + "\n", + "It is also common to define\n", + "the function $Q$ as" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "$$\n", + "C(\\boldsymbol{\\beta})=\\frac{1}{2n}\\sum_{i=0}^{n-1}\\left(y_i-\\tilde{y}_i\\right)^2,\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "since when taking the first derivative with respect to the unknown parameters $\\beta$, the factor of $2$ cancels out. \n", + "\n", + "\n", + "\n", + "\n", "## Interpretations and optimizing our parameters\n", "\n", + "\n", "The function" ] }, @@ -7177,7 +2884,7 @@ "metadata": {}, "source": [ "$$\n", - "Q(\\hat{\\beta})=\\left(\\hat{y}-\\hat{X}\\hat{\\beta}\\right)^T\\left(\\hat{y}-\\hat{X}\\hat{\\beta}\\right),\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", "$$" ] }, @@ -7185,7 +2892,8 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "can be linked to the variance of the quantity $y_i$ if we interpret the latter as the mean value of for example a numerical experiment. When linking below with the maximum likelihood approach below, we will indeed interpret $y_i$ as a mean value" + "can be linked to the variance of the quantity $y_i$ if we interpret the latter as the mean value. \n", + "When linking below with the maximum likelihood approach below, we will indeed interpret $y_i$ as a mean value (see exercises)" ] }, { @@ -7201,9 +2909,16 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "where $\\langle y_i \\rangle$ is the mean value. Keep in mind also that till now we have treated $y_i$ as the exact value. Normally, the response (dependent or outcome) variable $y_i$ the outcome of a numerical experiment or another type of experiment and is thus only an approximation to the true value. It is then always accompanied by an error estimate, often limited to a statistical error estimate given by the standard deviation discussed earlier. In the discussion here we will treat $y_i$ as our exact value for the response variable.\n", + "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 $Q(\\hat{\\beta})$ by requiring" + "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" ] }, { @@ -7211,7 +2926,24 @@ "metadata": {}, "source": [ "$$\n", - "\\frac{\\partial Q(\\hat{\\beta})}{\\partial \\beta_j} = \\frac{\\partial }{\\partial \\beta_j}\\left[ \\sum_{i=0}^{n-1}\\left(y_i-\\beta_0x_{i,0}-\\beta_1x_{i,1}-\\beta_2x_{i,2}-\\dots-\\beta_{n-1}x_{i,n-1}\\right)^2\\right]=0,\n", + "{\\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", "$$" ] }, @@ -7227,7 +2959,7 @@ "metadata": {}, "source": [ "$$\n", - "\\frac{\\partial Q(\\hat{\\beta})}{\\partial \\beta_j} = -2\\left[ \\sum_{i=0}^{n-1}x_{ij}\\left(y_i-\\beta_0x_{i,0}-\\beta_1x_{i,1}-\\beta_2x_{i,2}-\\dots-\\beta_{n-1}x_{i,n-1}\\right)\\right]=0,\n", + "\\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", "$$" ] }, @@ -7243,7 +2975,7 @@ "metadata": {}, "source": [ "$$\n", - "\\frac{\\partial Q(\\hat{\\beta})}{\\partial \\hat{\\beta}} = 0 = \\hat{X}^T\\left( \\hat{y}-\\hat{X}\\hat{\\beta}\\right).\n", + "\\frac{\\partial C(\\boldsymbol{\\beta})}{\\partial \\boldsymbol{\\beta}} = 0 = \\boldsymbol{X}^T\\left( \\boldsymbol{y}-\\boldsymbol{X}\\boldsymbol{\\beta}\\right).\n", "$$" ] }, @@ -7251,8 +2983,6 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "## Interpretations and optimizing our parameters\n", - "\n", "We can rewrite" ] }, @@ -7261,7 +2991,7 @@ "metadata": {}, "source": [ "$$\n", - "\\frac{\\partial Q(\\hat{\\beta})}{\\partial \\hat{\\beta}} = 0 = \\hat{X}^T\\left( \\hat{y}-\\hat{X}\\hat{\\beta}\\right),\n", + "\\frac{\\partial C(\\boldsymbol{\\beta})}{\\partial \\boldsymbol{\\beta}} = 0 = \\boldsymbol{X}^T\\left( \\boldsymbol{y}-\\boldsymbol{X}\\boldsymbol{\\beta}\\right),\n", "$$" ] }, @@ -7277,7 +3007,7 @@ "metadata": {}, "source": [ "$$\n", - "\\hat{X}^T\\hat{y} = \\hat{X}^T\\hat{X}\\hat{\\beta},\n", + "\\boldsymbol{X}^T\\boldsymbol{y} = \\boldsymbol{X}^T\\boldsymbol{X}\\boldsymbol{\\beta},\n", "$$" ] }, @@ -7285,7 +3015,7 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "and if the matrix $\\hat{X}^T\\hat{X}$ is invertible we have the solution" + "and if the matrix $\\boldsymbol{X}^T\\boldsymbol{X}$ is invertible we have the solution" ] }, { @@ -7293,7 +3023,7 @@ "metadata": {}, "source": [ "$$\n", - "\\hat{\\beta} =\\left(\\hat{X}^T\\hat{X}\\right)^{-1}\\hat{X}^T\\hat{y}.\n", + "\\boldsymbol{\\beta} =\\left(\\boldsymbol{X}^T\\boldsymbol{X}\\right)^{-1}\\boldsymbol{X}^T\\boldsymbol{y}.\n", "$$" ] }, @@ -7301,9 +3031,20 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "## Interpretations and optimizing our parameters\n", + "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", - "The residuals $\\hat{\\epsilon}$ are in turn given by" + "\n", + "\n", + "The residuals $\\boldsymbol{\\epsilon}$ are in turn given by" ] }, { @@ -7311,7 +3052,7 @@ "metadata": {}, "source": [ "$$\n", - "\\hat{\\epsilon} = \\hat{y}-\\hat{\\tilde{y}} = \\hat{y}-\\hat{X}\\hat{\\beta},\n", + "\\boldsymbol{\\epsilon} = \\boldsymbol{y}-\\boldsymbol{\\tilde{y}} = \\boldsymbol{y}-\\boldsymbol{X}\\boldsymbol{\\beta},\n", "$$" ] }, @@ -7327,7 +3068,7 @@ "metadata": {}, "source": [ "$$\n", - "\\hat{X}^T\\left( \\hat{y}-\\hat{X}\\hat{\\beta}\\right)= 0,\n", + "\\boldsymbol{X}^T\\left( \\boldsymbol{y}-\\boldsymbol{X}\\boldsymbol{\\beta}\\right)= 0,\n", "$$" ] }, @@ -7343,7 +3084,7 @@ "metadata": {}, "source": [ "$$\n", - "\\hat{X}^T\\hat{\\epsilon}=\\hat{X}^T\\left( \\hat{y}-\\hat{X}\\hat{\\beta}\\right)= 0,\n", + "\\boldsymbol{X}^T\\boldsymbol{\\epsilon}=\\boldsymbol{X}^T\\left( \\boldsymbol{y}-\\boldsymbol{X}\\boldsymbol{\\beta}\\right)= 0,\n", "$$" ] }, @@ -7351,18 +3092,176 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "meaning that the solution for $\\hat{\\beta}$ is the one which minimizes the residuals. Later we will link this with the maximum likelihood approach.\n", + "meaning that the solution for $\\boldsymbol{\\beta}$ is the one which minimizes the residuals. Later we will link this with the maximum likelihood approach.\n", "\n", "\n", + "Let us now return to our nuclear binding energies and simply code the above equations. \n", "\n", + "It is rather straightforward to implement the matrix inversion and obtain the parameters $\\boldsymbol{\\beta}$. After having defined the matrix $\\boldsymbol{X}$ we simply need to \n", + "write" + ] + }, + { + "cell_type": "code", + "execution_count": 39, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "# matrix inversion to find beta\n", + "beta = np.linalg.inv(X.T.dot(X)).dot(X.T).dot(Energies)\n", + "# and then make the prediction\n", + "ytilde = X @ beta" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Alternatively, you can use the least squares functionality in **Numpy** as" + ] + }, + { + "cell_type": "code", + "execution_count": 40, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "fit = np.linalg.lstsq(X, Energies, rcond =None)[0]\n", + "ytildenp = np.dot(fit,X.T)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "And finally we plot our fit with and compare with data" + ] + }, + { + "cell_type": "code", + "execution_count": 41, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "Masses['Eapprox'] = ytilde\n", + "# Generate a plot comparing the experimental with the fitted values values.\n", + "fig, ax = plt.subplots()\n", + "ax.set_xlabel(r'$A = N + Z$')\n", + "ax.set_ylabel(r'$E_\\mathrm{bind}\\,/\\mathrm{MeV}$')\n", + "ax.plot(Masses['A'], Masses['Ebinding'], alpha=0.7, lw=2,\n", + " label='Ame2016')\n", + "ax.plot(Masses['A'], Masses['Eapprox'], alpha=0.7, lw=2, c='m',\n", + " label='Fit')\n", + "ax.legend()\n", + "save_fig(\"Masses2016OLS\")\n", + "plt.show()" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Adding error analysis and training set up\n", "\n", + "We can easily test our fit by computing the $R2$ score that we discussed in connection with the functionality of _Scikit_Learn_ in the introductory slides.\n", + "Since we are not using _Scikit-Learn here we can define our own $R2$ function as" + ] + }, + { + "cell_type": "code", + "execution_count": 42, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "def R2(y_data, y_model):\n", + " return 1 - np.sum((y_data - y_model) ** 2) / np.sum((y_data - np.mean(y_model)) ** 2)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "and we would be using it as" + ] + }, + { + "cell_type": "code", + "execution_count": 43, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "print(R2(Energies,ytilde))" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "We can easily add our **MSE** score as" + ] + }, + { + "cell_type": "code", + "execution_count": 44, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "def MSE(y_data,y_model):\n", + " n = np.size(y_model)\n", + " return np.sum((y_data-y_model)**2)/n\n", "\n", + "print(MSE(Energies,ytilde))" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "and finally the relative error as" + ] + }, + { + "cell_type": "code", + "execution_count": 45, + "metadata": { + "collapsed": false + }, + "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", - "Normally, the response (dependent or outcome) variable $y_i$ the outcome of a numerical experiment or another type of experiment and is thus only an approximation to the true value. It is then always accompanied by an error estimate, often limited to a statistical error estimate given by the standard deviation discussed earlier. In the discussion here we will treat $y_i$ as our exact value for the response variable.\n", - "\n", - "Introducing the standard deviation $\\sigma_i$ for each measurement $y_i$, we define now the $\\chi^2$ function as" + "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" ] }, { @@ -7370,7 +3269,7 @@ "metadata": {}, "source": [ "$$\n", - "\\chi^2(\\hat{\\beta})=\\sum_{i=0}^{n-1}\\frac{\\left(y_i-\\tilde{y}_i\\right)^2}{\\sigma_i^2}=\\left(\\hat{y}-\\hat{\\tilde{y}}\\right)^T\\frac{1}{\\hat{\\Sigma^2}}\\left(\\hat{y}-\\hat{\\tilde{y}}\\right),\n", + "\\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", "$$" ] }, @@ -7378,15 +3277,10 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "where the matrix $\\hat{\\Sigma}$ is a diagonal matrix with $\\sigma_i$ as matrix elements. \n", + "where the matrix $\\boldsymbol{\\Sigma}$ is a diagonal matrix with $\\sigma_i$ as matrix elements. \n", "\n", "\n", - "\n", - "\n", - "## The $\\chi^2$ function\n", - "\n", - "\n", - "In order to find the parameters $\\beta_i$ we will then minimize the spread of $\\chi^2(\\hat{\\beta})$ by requiring" + "In order to find the parameters $\\beta_i$ we will then minimize the spread of $\\chi^2(\\boldsymbol{\\beta})$ by requiring" ] }, { @@ -7394,7 +3288,7 @@ "metadata": {}, "source": [ "$$\n", - "\\frac{\\partial \\chi^2(\\hat{\\beta})}{\\partial \\beta_j} = \\frac{\\partial }{\\partial \\beta_j}\\left[ \\sum_{i=0}^{n-1}\\left(\\frac{y_i-\\beta_0x_{i,0}-\\beta_1x_{i,1}-\\beta_2x_{i,2}-\\dots-\\beta_{n-1}x_{i,n-1}}{\\sigma_i}\\right)^2\\right]=0,\n", + "\\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", "$$" ] }, @@ -7410,7 +3304,7 @@ "metadata": {}, "source": [ "$$\n", - "\\frac{\\partial \\chi^2(\\hat{\\beta})}{\\partial \\beta_j} = -2\\left[ \\sum_{i=0}^{n-1}\\frac{x_{ij}}{\\sigma_i}\\left(\\frac{y_i-\\beta_0x_{i,0}-\\beta_1x_{i,1}-\\beta_2x_{i,2}-\\dots-\\beta_{n-1}x_{i,n-1}}{\\sigma_i}\\right)\\right]=0,\n", + "\\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", "$$" ] }, @@ -7426,7 +3320,7 @@ "metadata": {}, "source": [ "$$\n", - "\\frac{\\partial \\chi^2(\\hat{\\beta})}{\\partial \\hat{\\beta}} = 0 = \\hat{A}^T\\left( \\hat{b}-\\hat{A}\\hat{\\beta}\\right).\n", + "\\frac{\\partial \\chi^2(\\boldsymbol{\\beta})}{\\partial \\boldsymbol{\\beta}} = 0 = \\boldsymbol{A}^T\\left( \\boldsymbol{b}-\\boldsymbol{A}\\boldsymbol{\\beta}\\right).\n", "$$" ] }, @@ -7434,12 +3328,7 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "where we have defined the matrix $\\hat{A} =\\hat{X}/\\hat{\\Sigma}$ with matrix elements $a_{ij} = x_{ij}/\\sigma_i$ and the vector $\\hat{b}$ with elements $b_i = y_i/\\sigma_i$. \n", - "\n", - "\n", - "\n", - "## The $\\chi^2$ function\n", - "\n", + "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" ] @@ -7449,7 +3338,7 @@ "metadata": {}, "source": [ "$$\n", - "\\frac{\\partial \\chi^2(\\hat{\\beta})}{\\partial \\hat{\\beta}} = 0 = \\hat{A}^T\\left( \\hat{b}-\\hat{A}\\hat{\\beta}\\right),\n", + "\\frac{\\partial \\chi^2(\\boldsymbol{\\beta})}{\\partial \\boldsymbol{\\beta}} = 0 = \\boldsymbol{A}^T\\left( \\boldsymbol{b}-\\boldsymbol{A}\\boldsymbol{\\beta}\\right),\n", "$$" ] }, @@ -7465,7 +3354,7 @@ "metadata": {}, "source": [ "$$\n", - "\\hat{A}^T\\hat{b} = \\hat{A}^T\\hat{A}\\hat{\\beta},\n", + "\\boldsymbol{A}^T\\boldsymbol{b} = \\boldsymbol{A}^T\\boldsymbol{A}\\boldsymbol{\\beta},\n", "$$" ] }, @@ -7473,7 +3362,7 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "and if the matrix $\\hat{A}^T\\hat{A}$ is invertible we have the solution" + "and if the matrix $\\boldsymbol{A}^T\\boldsymbol{A}$ is invertible we have the solution" ] }, { @@ -7481,7 +3370,7 @@ "metadata": {}, "source": [ "$$\n", - "\\hat{\\beta} =\\left(\\hat{A}^T\\hat{A}\\right)^{-1}\\hat{A}^T\\hat{b}.\n", + "\\boldsymbol{\\beta} =\\left(\\boldsymbol{A}^T\\boldsymbol{A}\\right)^{-1}\\boldsymbol{A}^T\\boldsymbol{b}.\n", "$$" ] }, @@ -7489,9 +3378,6 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "## The $\\chi^2$ function\n", - "\n", - "\n", "If we then introduce the matrix" ] }, @@ -7500,7 +3386,7 @@ "metadata": {}, "source": [ "$$\n", - "\\hat{H} = \\left(\\hat{A}^T\\hat{A}\\right)^{-1},\n", + "\\boldsymbol{H} = \\left(\\boldsymbol{A}^T\\boldsymbol{A}\\right)^{-1},\n", "$$" ] }, @@ -7508,7 +3394,7 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "we have then the following expression for the parameters $\\beta_j$ (the matrix elements of $\\hat{H}$ are $h_{ij}$)" + "we have then the following expression for the parameters $\\beta_j$ (the matrix elements of $\\boldsymbol{H}$ are $h_{ij}$)" ] }, { @@ -7556,8 +3442,6 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "## The $\\chi^2$ function\n", - "\n", "The first step here is to approximate the function $y$ with a first-order polynomial, that is we write" ] }, @@ -7582,7 +3466,7 @@ "metadata": {}, "source": [ "$$\n", - "\\frac{\\partial \\chi^2(\\hat{\\beta})}{\\partial \\beta_0} = -2\\left[ \\sum_{i=0}^{n-1}\\left(\\frac{y_i-\\beta_0-\\beta_1x_{i}}{\\sigma_i^2}\\right)\\right]=0,\n", + "\\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", "$$" ] }, @@ -7598,7 +3482,7 @@ "metadata": {}, "source": [ "$$\n", - "\\frac{\\partial \\chi^2(\\hat{\\beta})}{\\partial \\beta_0} = -2\\left[ \\sum_{i=0}^{n-1}x_i\\left(\\frac{y_i-\\beta_0-\\beta_1x_{i}}{\\sigma_i^2}\\right)\\right]=0.\n", + "\\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", "$$" ] }, @@ -7606,10 +3490,7 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "## The $\\chi^2$ function\n", - "\n", - "\n", - "For a linear fit we don't need to invert a matrix!! \n", + "For a linear fit (a first-order polynomial) we don't need to invert a matrix!! \n", "Defining" ] }, @@ -7626,75 +3507,27 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "2\n", - "1\n", - "7\n", - " \n", - "<\n", - "<\n", - "<\n", - "!\n", - "!\n", - "M\n", - "A\n", - "T\n", - "H\n", - "_\n", - "B\n", - "L\n", - "O\n", - "C\n", - "K" + "$$\n", + "\\gamma_x = \\sum_{i=0}^{n-1}\\frac{x_{i}}{\\sigma_i^2},\n", + "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ - "2\n", - "1\n", - "8\n", - " \n", - "<\n", - "<\n", - "<\n", - "!\n", - "!\n", - "M\n", - "A\n", - "T\n", - "H\n", - "_\n", - "B\n", - "L\n", - "O\n", - "C\n", - "K" + "$$\n", + "\\gamma_y = \\sum_{i=0}^{n-1}\\left(\\frac{y_i}{\\sigma_i^2}\\right),\n", + "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ - "2\n", - "1\n", - "9\n", - " \n", - "<\n", - "<\n", - "<\n", - "!\n", - "!\n", - "M\n", - "A\n", - "T\n", - "H\n", - "_\n", - "B\n", - "L\n", - "O\n", - "C\n", - "K" + "$$\n", + "\\gamma_{xx} = \\sum_{i=0}^{n-1}\\frac{x_ix_{i}}{\\sigma_i^2},\n", + "$$" ] }, { @@ -7717,25 +3550,9 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "2\n", - "2\n", - "1\n", - " \n", - "<\n", - "<\n", - "<\n", - "!\n", - "!\n", - "M\n", - "A\n", - "T\n", - "H\n", - "_\n", - "B\n", - "L\n", - "O\n", - "C\n", - "K" + "$$\n", + "\\beta_0 = \\frac{\\gamma_{xx}\\gamma_y-\\gamma_x\\gamma_y}{\\gamma\\gamma_{xx}-\\gamma_x^2},\n", + "$$" ] }, { @@ -7751,386 +3568,127 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "This approach (different linear and non-linear regression) suffers often from both being underdetermined and overdetermined in the unknown coefficients $\\beta_i$. A better approach is to use the Singular Value Decomposition (SVD) method discussed below. Or using Lasso and Ridge regression. See below.\n", + "This approach (different linear and non-linear regression) suffers\n", + "often from both being underdetermined and overdetermined in the\n", + "unknown coefficients $\\beta_i$. A better approach is to use the\n", + "Singular Value Decomposition (SVD) method discussed below. Or using\n", + "Lasso and Ridge regression. See below.\n", "\n", "\n", + "## Fitting an Equation of State for Dense Nuclear Matter\n", "\n", + "Before we continue, let us introduce yet another example. We are going to fit the\n", + "nuclear equation of state using results from many-body calculations.\n", + "The equation of state we have made available here, as function of\n", + "density, has been derived using modern nucleon-nucleon potentials with\n", + "[the addition of three-body\n", + "forces](https://www.sciencedirect.com/science/article/pii/S0370157399001106). This\n", + "time the file is presented as a standard **csv** file.\n", "\n", + "The beginning of the Python code here is similar to what you have seen before,\n", + "with the same initializations and declarations. We use also **pandas**\n", + "again, rather extensively in order to organize our data.\n", "\n", + "The difference now is that we use **Scikit-Learn's** regression tools\n", + "instead of our own matrix inversion implementation. Furthermore, we\n", + "sneak in **Ridge** regression (to be discussed below) which includes a\n", + "hyperparameter $\\lambda$, also to be explained below.\n", "\n", - "## Simple regression model\n", - "We are now ready to write our first program which aims at solving the above linear regression equations. We start with data we have produced ourselves, in this case normally distributed random numbers along the $x$-axis. These numbers define then the value of a function $y(x)=4+3x+N(0,1)$. Thereafter we order the $x$ values and employ our linear regression algorithm to set up the best fit. Here we find it useful to use the numpy function $c\\_$ arrays where arrays are stacked along their last axis after being upgraded to at least two dimensions with ones post-pended to the shape. The following examples help in understanding what happens" + "## The code" ] }, { "cell_type": "code", - "execution_count": 35, + "execution_count": 46, "metadata": { "collapsed": false }, "outputs": [], "source": [ + "# Common imports\n", + "import os\n", "import numpy as np\n", - "print(np.c_[np.array([1,2,3]), np.array([4,5,6])])\n", - "print(np.c_[np.array([[1,2,3]]), 0, 0, np.array([[4,5,6]])])" - ] - }, - { - "cell_type": "code", - "execution_count": 36, - "metadata": { - "collapsed": false - }, - "outputs": [], - "source": [ - "# Importing various packages\n", - "from random import random, seed\n", - "import numpy as np\n", + "import pandas as pd\n", "import matplotlib.pyplot as plt\n", - "\n", - "x = 2*np.random.rand(100,1)\n", - "y = 4+3*x+np.random.randn(100,1)\n", - "\n", - "xb = np.c_[np.ones((100,1)), x]\n", - "beta = np.linalg.inv(xb.T.dot(xb)).dot(xb.T).dot(y)\n", - "xnew = np.array([[0],[2]])\n", - "xbnew = np.c_[np.ones((2,1)), xnew]\n", - "ypredict = xbnew.dot(beta)\n", - "\n", - "plt.plot(xnew, ypredict, \"r-\")\n", - "plt.plot(x, y ,'ro')\n", - "plt.axis([0,2.0,0, 15.0])\n", - "plt.xlabel(r'$x$')\n", - "plt.ylabel(r'$y$')\n", - "plt.title(r'Linear Regression')\n", - "plt.show()" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "We see that, as expected, a linear fit gives a seemingly (from the graph) good representation of the data.\n", - "\n", - "\n", - "\n", - "\n", - "\n", - "## Simple regression model, now using **scikit-learn**\n", - "\n", - "\n", - "We can repeat the above algorithm using **scikit-learn** as follows" - ] - }, - { - "cell_type": "code", - "execution_count": 37, - "metadata": { - "collapsed": false - }, - "outputs": [], - "source": [ - "# Importing various packages\n", - "from random import random, seed\n", - "import numpy as np\n", "import matplotlib.pyplot as plt\n", - "from sklearn.linear_model import LinearRegression\n", + "import sklearn.linear_model as skl\n", + "from sklearn.metrics import mean_squared_error, r2_score, mean_absolute_error\n", "\n", - "x = 2*np.random.rand(100,1)\n", - "y = 4+3*x+np.random.randn(100,1)\n", - "linreg = LinearRegression()\n", - "linreg.fit(x,y)\n", - "xnew = np.array([[0],[2]])\n", - "ypredict = linreg.predict(xnew)\n", + "# Where to save the figures and data files\n", + "PROJECT_ROOT_DIR = \"Results\"\n", + "FIGURE_ID = \"Results/FigureFiles\"\n", + "DATA_ID = \"DataFiles/\"\n", "\n", - "plt.plot(xnew, ypredict, \"r-\")\n", - "plt.plot(x, y ,'ro')\n", - "plt.axis([0,2.0,0, 15.0])\n", - "plt.xlabel(r'$x$')\n", - "plt.ylabel(r'$y$')\n", - "plt.title(r'Random numbers ')\n", - "plt.show()" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "## Simple linear regression model using **scikit-learn**\n", + "if not os.path.exists(PROJECT_ROOT_DIR):\n", + " os.mkdir(PROJECT_ROOT_DIR)\n", "\n", - "We start with perhaps our simplest possible example, using **scikit-learn** to perform linear regression analysis on a data set produced by us. \n", - "What follows is a simple Python code where we have defined function $y$ in terms of the variable $x$. Both are defined as vectors of dimension $1\\times 100$. The entries to the vector $\\hat{x}$ are given by random numbers generated with a uniform distribution with entries $x_i \\in [0,1]$ (more about probability distribution functions later). These values are then used to define a function $y(x)$ (tabulated again as a vector) with a linear dependence on $x$ plus a random noise added via the normal distribution.\n", + "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", - "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", + "def image_path(fig_id):\n", + " return os.path.join(FIGURE_ID, fig_id)\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", + "def data_path(dat_id):\n", + " return os.path.join(DATA_ID, dat_id)\n", "\n", - "The Python code follows here." - ] - }, - { - "cell_type": "code", - "execution_count": 38, - "metadata": { - "collapsed": false - }, - "outputs": [], - "source": [ - "# Importing various packages\n", - "import numpy as np\n", - "import matplotlib.pyplot as plt\n", - "from sklearn.linear_model import LinearRegression\n", + "def save_fig(fig_id):\n", + " plt.savefig(image_path(fig_id) + \".png\", format='png')\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", + "infile = open(data_path(\"EoS.csv\"),'r')\n", "\n", - "plt.plot(xnew, ypredict, \"r-\")\n", - "plt.plot(x, y ,'ro')\n", - "plt.axis([0,1.0,0, 5.0])\n", - "plt.xlabel(r'$x$')\n", - "plt.ylabel(r'$y$')\n", - "plt.title(r'Simple Linear Regression')\n", - "plt.show()" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "## Simple linear regression model\n", + "# 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", - "This example serves several aims. It allows us to demonstrate several\n", - "aspects of data analysis and later machine learning algorithms. The\n", - "immediate visualization shows that our linear fit is not\n", - "impressive. It goes through the data points, but there are many\n", - "outliers which are not reproduced by our linear regression. We could\n", - "now play around with this small program and change for example the\n", - "factor in front of $x$ and the normal distribution. Try to change the\n", - "function $y$ to" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "y = 10x+0.01 \\times N(0,1),\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "where $x$ is defined as before. \n", - "\n", - "\n", - "\n", - "## Less noise\n", - "\n", - "Does the fit look better? Indeed, by\n", - "reducing the role of the normal distribution we see immediately that\n", - "our linear prediction seemingly reproduces better the training\n", - "set. However, this testing 'by the eye' is obviouly not satisfactory in the\n", - "long run. Here we have only defined the training data and our model, and \n", - "have not discussed a more rigorous approach to the **cost** function.\n", - "\n", - "\n", - "\n", - "## How to study our fits\n", - "\n", - "We need more rigorous criteria in defining whether we have succeeded or\n", - "not in modeling our training data. You will be surprised to see that\n", - "many scientists seldomly venture beyond this 'by the eye' approach. A\n", - "standard approach for the *cost* function is the so-called $\\chi^2$\n", - "function" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "\\chi^2 = \\frac{1}{n}\n", - "\\sum_{i=0}^{n-1}\\frac{(y_i-\\tilde{y}_i)^2}{\\sigma_i^2},\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "where $\\sigma_i^2$ is the variance (to be defined later) of the entry\n", - "$y_i$. We may not know the explicit value of $\\sigma_i^2$, it serves\n", - "however the aim of scaling the equations and make the cost function\n", - "dimensionless. \n", - "\n", - "\n", - "\n", - "## Minimizing the cost function\n", - "\n", - "Minimizing the cost function is a central aspect of\n", - "our discussions to come. Finding its minima as function of the model\n", - "parameters ($\\alpha$ and $\\beta$ in our case) will be a recurring\n", - "theme in these series of lectures. Essentially all machine learning\n", - "algorithms we will discuss center around the minimization of the\n", - "chosen cost function. This depends in turn on our specific\n", - "model for describing the data, a typical situation in supervised\n", - "learning. Automatizing the search for the minima of the cost function is a\n", - "central ingredient in all algorithms. Typical methods which are\n", - "employed are various variants of **gradient** methods. These will be\n", - "discussed in more detail later. Again, you'll be surprised to hear that\n", - "many practitioners minimize the above function ''by the eye', popularly dubbed as \n", - "'chi by the eye'. That is, change a parameter and see (visually and numerically) that \n", - "the $\\chi^2$ function becomes smaller. \n", - "\n", - "\n", - "## Relative error\n", - "\n", - "There are many ways to define the cost function. A simpler approach is to look at the relative difference between the training data and the predicted data, that is we define \n", - "the relative error as" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "\\epsilon_{\\mathrm{relative}}= \\frac{\\vert \\hat{y} -\\hat{\\tilde{y}}\\vert}{\\vert \\hat{y}\\vert}.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "We can modify easily the above Python code and plot the relative error instead" - ] - }, - { - "cell_type": "code", - "execution_count": 39, - "metadata": { - "collapsed": false - }, - "outputs": [], - "source": [ - "import numpy as np\n", - "import matplotlib.pyplot as plt\n", - "from sklearn.linear_model import LinearRegression\n", - "\n", - "x = np.random.rand(100,1)\n", - "y = 5*x+0.01*np.random.randn(100,1)\n", - "linreg = LinearRegression()\n", - "linreg.fit(x,y)\n", - "ypredict = linreg.predict(x)\n", - "\n", - "plt.plot(x, np.abs(ypredict-y)/abs(y), \"ro\")\n", - "plt.axis([0,1.0,0.0, 0.5])\n", - "plt.xlabel(r'$x$')\n", - "plt.ylabel(r'$\\epsilon_{\\mathrm{relative}}$')\n", - "plt.title(r'Relative error')\n", - "plt.show()" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "Depending on the parameter in front of the normal distribution, we may\n", - "have a small or larger relative error. Try to play around with\n", - "different training data sets and study (graphically) the value of the\n", - "relative error.\n", - "\n", - "\n", - "\n", - "## The richness of **scikit-learn**\n", - "\n", - "As mentioned above, **scikit-learn** has an impressive functionality.\n", - "We can for example extract the values of $\\alpha$ and $\\beta$ and\n", - "their error estimates, or the variance and standard deviation and many\n", - "other properties from the statistical data analysis. \n", - "\n", - "Here we show an\n", - "example of the functionality of scikit-learn." - ] - }, - { - "cell_type": "code", - "execution_count": 40, - "metadata": { - "collapsed": false - }, - "outputs": [], - "source": [ - "import numpy as np \n", - "import matplotlib.pyplot as plt \n", - "from sklearn.linear_model import LinearRegression \n", - "from sklearn.metrics import mean_squared_error, r2_score, mean_squared_log_error, mean_absolute_error\n", - "\n", - "x = np.random.rand(100,1)\n", - "y = 2.0+ 5*x+0.5*np.random.randn(100,1)\n", - "linreg = LinearRegression()\n", - "linreg.fit(x,y)\n", - "ypredict = linreg.predict(x)\n", - "print('The intercept alpha: \\n', linreg.intercept_)\n", - "print('Coefficient beta : \\n', linreg.coef_)\n", + "# 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(y, ypredict))\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(y, ypredict))\n", - "# Mean squared log error \n", - "print('Mean squared log error: %.2f' % mean_squared_log_error(y, ypredict) )\n", + "print('Variance score: %.2f' % r2_score(Energies, ytilde))\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", + "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()" ] }, @@ -8138,209 +3696,505 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "## Functions in **scikit-learn**\n", - "\n", - "The function **coef** gives us the parameter $\\beta$ of our fit while **intercept** yields \n", - "$\\alpha$. Depending on the constant in front of the normal distribution, we get values near or far from $alpha =2$ and $\\beta =5$. Try to play around with different parameters in front of the normal distribution. The function **meansquarederror** gives us the mean square error, a risk metric corresponding to the expected value of the squared (quadratic) error or loss defined as" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "MSE(\\hat{y},\\hat{\\tilde{y}}) = \\frac{1}{n}\n", - "\\sum_{i=0}^{n-1}(y_i-\\tilde{y}_i)^2,\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "The smaller the value, the better the fit. Ideally we would like to\n", - "have an MSE equal zero. The attentive reader has probably recognized\n", - "this function as being similar to the $\\chi^2$ function defined above.\n", + "The above simple polynomial in density $\\rho$ gives an excellent fit\n", + "to the data. \n", + "We note also that there is a small deviation between the\n", + "standard OLS and the Ridge regression at higher densities. We discuss this in more detail\n", + "below.\n", "\n", "\n", - "## Other functions in **scikit-learn**\n", + "## Splitting our Data in Training and Test data\n", "\n", - "The **r2score** function computes $R^2$, the coefficient of\n", - "determination. It provides a measure of how well future samples are\n", - "likely to be predicted by the model. Best possible score is 1.0 and it\n", - "can be negative (because the model can be arbitrarily worse). A\n", - "constant model that always predicts the expected value of $\\hat{y}$,\n", - "disregarding the input features, would get a $R^2$ score of $0.0$.\n", - "\n", - "If $\\tilde{\\hat{y}}_i$ is the predicted value of the $i-th$ sample and $y_i$ is the corresponding true value, then the score $R^2$ is defined as" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "R^2(\\hat{y}, \\tilde{\\hat{y}}) = 1 - \\frac{\\sum_{i=0}^{n - 1} (y_i - \\tilde{y}_i)^2}{\\sum_{i=0}^{n - 1} (y_i - \\bar{y})^2},\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "where we have defined the mean value of $\\hat{y}$ as" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "\\bar{y} = \\frac{1}{n} \\sum_{i=0}^{n - 1} y_i.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "## The mean absolute error and other functions in **scikit-learn**\n", - "\n", - "Another quantity will meet again in our discussions of regression analysis is \n", - " mean absolute error (MAE), a risk metric corresponding to the expected value of the absolute error loss or what we call the $l1$-norm loss. In our discussion above we presented the relative error.\n", - "The MAE is defined as follows" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "\\text{MAE}(\\hat{y}, \\hat{\\tilde{y}}) = \\frac{1}{n} \\sum_{i=0}^{n-1} \\left| y_i - \\tilde{y}_i \\right|.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "Finally we present the \n", - "squared logarithmic (quadratic) error" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "\\text{MSLE}(\\hat{y}, \\hat{\\tilde{y}}) = \\frac{1}{n} \\sum_{i=0}^{n - 1} (\\log_e (1 + y_i) - \\log_e (1 + \\tilde{y}_i) )^2,\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "where $\\log_e (x)$ stands for the natural logarithm of $x$. This error\n", - "estimate is best to use when targets having exponential growth, such\n", - "as population counts, average sales of a commodity over a span of\n", - "years etc. \n", - "\n", - "\n", - "\n", - "## Cubic polynomial in **scikit-learn**\n", - "\n", - "We will discuss in more\n", - "detail these and other functions in the various lectures. We conclude this part with another example. Instead of \n", - "a linear $x$-dependence we study now a cubic polynomial and use the polynomial regression analysis tools of scikit-learn. \n", - "Add description of the various python commands." + "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": 41, + "execution_count": 47, "metadata": { "collapsed": false }, "outputs": [], "source": [ - "import matplotlib.pyplot as plt\n", + "import os\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", + "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", - "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", + "if not os.path.exists(PROJECT_ROOT_DIR):\n", + " os.mkdir(PROJECT_ROOT_DIR)\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", + "if not os.path.exists(FIGURE_ID):\n", + " os.makedirs(FIGURE_ID)\n", "\n", - "def error(a):\n", - " for i in y:\n", - " err=(y-yn)/yn\n", - " return abs(np.sum(err))/len(err)\n", + "if not os.path.exists(DATA_ID):\n", + " os.makedirs(DATA_ID)\n", "\n", - "print (error(y))" + "def image_path(fig_id):\n", + " return os.path.join(FIGURE_ID, fig_id)\n", + "\n", + "def data_path(dat_id):\n", + " return os.path.join(DATA_ID, dat_id)\n", + "\n", + "def save_fig(fig_id):\n", + " plt.savefig(image_path(fig_id) + \".png\", format='png')\n", + "\n", + "def R2(y_data, y_model):\n", + " return 1 - np.sum((y_data - y_model) ** 2) / np.sum((y_data - np.mean(y_model)) ** 2)\n", + "def MSE(y_data,y_model):\n", + " n = np.size(y_model)\n", + " return np.sum((y_data-y_model)**2)/n\n", + "\n", + "infile = open(data_path(\"EoS.csv\"),'r')\n", + "\n", + "# Read the EoS data as csv file and organized into two arrays with density and energies\n", + "EoS = pd.read_csv(infile, names=('Density', 'Energy'))\n", + "EoS['Energy'] = pd.to_numeric(EoS['Energy'], errors='coerce')\n", + "EoS = EoS.dropna()\n", + "Energies = EoS['Energy']\n", + "Density = EoS['Density']\n", + "# The design matrix now as function of various polytrops\n", + "X = np.zeros((len(Density),5))\n", + "X[:,0] = 1\n", + "X[:,1] = Density**(2.0/3.0)\n", + "X[:,2] = Density\n", + "X[:,3] = Density**(4.0/3.0)\n", + "X[:,4] = Density**(5.0/3.0)\n", + "# We split the data in test and training data\n", + "X_train, X_test, y_train, y_test = train_test_split(X, Energies, test_size=0.2)\n", + "# matrix inversion to find beta\n", + "beta = np.linalg.inv(X_train.T.dot(X_train)).dot(X_train.T).dot(y_train)\n", + "# and then make the prediction\n", + "ytilde = X_train @ beta\n", + "print(\"Training R2\")\n", + "print(R2(y_train,ytilde))\n", + "print(\"Training MSE\")\n", + "print(MSE(y_train,ytilde))\n", + "ypredict = X_test @ beta\n", + "print(\"Test R2\")\n", + "print(R2(y_test,ypredict))\n", + "print(\"Test MSE\")\n", + "print(MSE(y_test,ypredict))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ - "Using **R**, we can perform similar studies. \n", + "## The singular value decomposition\n", + "\n", + "The examples we have looked at so far are cases where we normally can\n", + "invert the matrix $\\boldsymbol{X}^T\\boldsymbol{X}$. Using a polynomial expansion as we\n", + "did both for the masses and the fitting of the equation of state,\n", + "leads to row vectors of the design matrix which are essentially\n", + "orthogonal due to the polynomial character of our model. This may\n", + "however not the be case in general and a standard matrix inversion\n", + "algorithm based on say LU decomposition may lead to singularities. We will see an example of this below when we try to fit\n", + "the coupling constant of the widely used Ising model. \n", + "There is however a way to partially circumvent this problem and also gain some insight about the ordinary least squares approach. \n", + "\n", + "This is given by the **Singular Value Decomposition** algorithm, perhaps\n", + "the most powerful linear algebra algorithm. Let us look at a\n", + "different example where we may have problems with the standard matrix\n", + "inversion algorithm. Thereafter we dive into the math of the SVD.\n", "\n", "\n", + "## The Ising model\n", "\n", + "The one-dimensional Ising model with nearest neighbor interaction, no\n", + "external field and a constant coupling constant $J$ is given by" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + "
\n", "\n", + "$$\n", + "\\begin{equation}\n", + " H = -J \\sum_{k}^L s_k s_{k + 1},\n", + "\\label{_auto1} \\tag{1}\n", + "\\end{equation}\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "where $s_i \\in \\{-1, 1\\}$ and $s_{N + 1} = s_1$. The number of spins\n", + "in the system is determined by $L$. For the one-dimensional system\n", + "there is no phase transition.\n", "\n", - "\n", - "\n", - "## Polynomial Regression" + "We will look at a system of $L = 40$ spins with a coupling constant of\n", + "$J = 1$. To get enough training data we will generate 10000 states\n", + "with their respective energies." ] }, { "cell_type": "code", - "execution_count": 42, + "execution_count": 48, "metadata": { "collapsed": false }, "outputs": [], "source": [ - "# Importing various packages\n", - "from math import exp, sqrt\n", - "from random import random, seed\n", "import numpy as np\n", "import matplotlib.pyplot as plt\n", + "from mpl_toolkits.axes_grid1 import make_axes_locatable\n", + "import seaborn as sns\n", + "import scipy.linalg as scl\n", + "from sklearn.model_selection import train_test_split\n", + "import tqdm\n", + "sns.set(color_codes=True)\n", + "cmap_args=dict(vmin=-1., vmax=1., cmap='seismic')\n", "\n", - "m = 100\n", - "x = 2*np.random.rand(m,1)+4.\n", - "y = 4+3*x*x+ +x-np.random.randn(m,1)\n", + "L = 40\n", + "n = int(1e4)\n", "\n", - "xb = np.c_[np.ones((m,1)), x]\n", - "theta = np.linalg.inv(xb.T.dot(xb)).dot(xb.T).dot(y)\n", - "xnew = np.array([[0],[2]])\n", - "xbnew = np.c_[np.ones((2,1)), xnew]\n", - "ypredict = xbnew.dot(theta)\n", + "spins = np.random.choice([-1, 1], size=(n, L))\n", + "J = 1.0\n", "\n", - "plt.plot(xnew, ypredict, \"r-\")\n", - "plt.plot(x, y ,'ro')\n", - "plt.axis([0,2.0,0, 15.0])\n", - "plt.xlabel(r'$x$')\n", - "plt.ylabel(r'$y$')\n", - "plt.title(r'Random numbers ')\n", + "energies = np.zeros(n)\n", + "\n", + "for i in range(n):\n", + " energies[i] = - J * np.dot(spins[i], np.roll(spins[i], 1))" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Here we use ordinary least squares\n", + "regression to predict the energy for the nearest neighbor\n", + "one-dimensional Ising model on a ring, i.e., the endpoints wrap\n", + "around. We will use linear regression to fit a value for\n", + "the coupling constant to achieve this.\n", + "\n", + "## Reformulating the problem to suit regression\n", + "\n", + "A more general form for the one-dimensional Ising model is" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + "
\n", + "\n", + "$$\n", + "\\begin{equation}\n", + " H = - \\sum_j^L \\sum_k^L s_j s_k J_{jk}.\n", + "\\label{_auto2} \\tag{2}\n", + "\\end{equation}\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Here we allow for interactions beyond the nearest neighbors and a state dependent\n", + "coupling constant. This latter expression can be formulated as\n", + "a matrix-product" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + "
\n", + "\n", + "$$\n", + "\\begin{equation}\n", + " \\boldsymbol{H} = \\boldsymbol{X} J,\n", + "\\label{_auto3} \\tag{3}\n", + "\\end{equation}\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "where $X_{jk} = s_j s_k$ and $J$ is a matrix which consists of the\n", + "elements $-J_{jk}$. This form of writing the energy fits perfectly\n", + "with the form utilized in linear regression, that is" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + "
\n", + "\n", + "$$\n", + "\\begin{equation}\n", + " \\boldsymbol{y} = \\boldsymbol{X}\\boldsymbol{\\beta} + \\boldsymbol{\\epsilon},\n", + "\\label{_auto4} \\tag{4}\n", + "\\end{equation}\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "We split the data in training and test data as discussed in the previous example" + ] + }, + { + "cell_type": "code", + "execution_count": 49, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "X = np.zeros((n, L ** 2))\n", + "for i in range(n):\n", + " X[i] = np.outer(spins[i], spins[i]).ravel()\n", + "y = energies\n", + "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "In the ordinary least squares method we choose the cost function" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + "
\n", + "\n", + "$$\n", + "\\begin{equation}\n", + " C(\\boldsymbol{X}, \\boldsymbol{\\beta})= \\frac{1}{n}\\left\\{(\\boldsymbol{X}\\boldsymbol{\\beta} - \\boldsymbol{y})^T(\\boldsymbol{X}\\boldsymbol{\\beta} - \\boldsymbol{y})\\right\\}.\n", + "\\label{_auto5} \\tag{5}\n", + "\\end{equation}\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "We then find the extremal point of $C$ by taking the derivative with respect to $\\boldsymbol{\\beta}$ as discussed above.\n", + "This yields the expression for $\\boldsymbol{\\beta}$ to be" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "$$\n", + "\\boldsymbol{\\beta} = \\frac{\\boldsymbol{X}^T \\boldsymbol{y}}{\\boldsymbol{X}^T \\boldsymbol{X}},\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "which immediately imposes some requirements on $\\boldsymbol{X}$ as there must exist\n", + "an inverse of $\\boldsymbol{X}^T \\boldsymbol{X}$. If the expression we are modeling contains an\n", + "intercept, i.e., a constant term, we must make sure that the\n", + "first column of $\\boldsymbol{X}$ consists of $1$. We do this here" + ] + }, + { + "cell_type": "code", + "execution_count": 50, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "X_train_own = np.concatenate(\n", + " (np.ones(len(X_train))[:, np.newaxis], X_train),\n", + " axis=1\n", + ")\n", + "X_test_own = np.concatenate(\n", + " (np.ones(len(X_test))[:, np.newaxis], X_test),\n", + " axis=1\n", + ")" + ] + }, + { + "cell_type": "code", + "execution_count": 51, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "def ols_inv(x: np.ndarray, y: np.ndarray) -> np.ndarray:\n", + " return scl.inv(x.T @ x) @ (x.T @ y)\n", + "beta = ols_inv(X_train_own, y_train)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Singular Value decomposition\n", + "\n", + "Doing the inversion directly turns out to be a bad idea since the matrix\n", + "$\\boldsymbol{X}^T\\boldsymbol{X}$ is singular. An alternative approach is to use the **singular\n", + "value decomposition**. Using the definition of the Moore-Penrose\n", + "pseudoinverse we can write the equation for $\\boldsymbol{\\beta}$ as" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "$$\n", + "\\boldsymbol{\\beta} = \\boldsymbol{X}^{+}\\boldsymbol{y},\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "where the pseudoinverse of $\\boldsymbol{X}$ is given by" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "$$\n", + "\\boldsymbol{X}^{+} = \\frac{\\boldsymbol{X}^T}{\\boldsymbol{X}^T\\boldsymbol{X}}.\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Using singular value decomposition we can decompose the matrix $\\boldsymbol{X} = \\boldsymbol{U}\\boldsymbol{\\Sigma} \\boldsymbol{V}^T$,\n", + "where $\\boldsymbol{U}$ and $\\boldsymbol{V}$ are orthogonal(unitary) matrices and $\\boldsymbol{\\Sigma}$ contains the singular values (more details below).\n", + "where $X^{+} = V\\Sigma^{+} U^T$. This reduces the equation for\n", + "$\\omega$ to" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + "
\n", + "\n", + "$$\n", + "\\begin{equation}\n", + " \\boldsymbol{\\beta} = \\boldsymbol{V}\\boldsymbol{\\Sigma}^{+} \\boldsymbol{U}^T \\boldsymbol{y}.\n", + "\\label{_auto6} \\tag{6}\n", + "\\end{equation}\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Note that solving this equation by actually doing the pseudoinverse\n", + "(which is what we will do) is not a good idea as this operation scales\n", + "as $\\mathcal{O}(n^3)$, where $n$ is the number of elements in a\n", + "general matrix. Instead, doing $QR$-factorization and solving the\n", + "linear system as an equation would reduce this down to\n", + "$\\mathcal{O}(n^2)$ operations." + ] + }, + { + "cell_type": "code", + "execution_count": 52, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "def ols_svd(x: np.ndarray, y: np.ndarray) -> np.ndarray:\n", + " u, s, v = scl.svd(x)\n", + " return v.T @ scl.pinv(scl.diagsvd(s, u.shape[0], v.shape[0])) @ u.T @ y" + ] + }, + { + "cell_type": "code", + "execution_count": 53, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "beta = ols_svd(X_train_own,y_train)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "When extracting the $J$-matrix we need to make sure that we remove the intercept, as is done here" + ] + }, + { + "cell_type": "code", + "execution_count": 54, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "J = beta[1:].reshape(L, L)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "A way of looking at the coefficients in $J$ is to plot the matrices as images." + ] + }, + { + "cell_type": "code", + "execution_count": 55, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "fig = plt.figure(figsize=(20, 14))\n", + "im = plt.imshow(J, **cmap_args)\n", + "plt.title(\"OLS\", fontsize=18)\n", + "plt.xticks(fontsize=18)\n", + "plt.yticks(fontsize=18)\n", + "cb = fig.colorbar(im)\n", + "cb.ax.set_yticklabels(cb.ax.get_yticklabels(), fontsize=18)\n", "plt.show()" ] }, @@ -8348,128 +4202,21 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "## Linking the regression analysis with a statistical interpretation\n", + "It is interesting to note that OLS\n", + "considers both $J_{j, j + 1} = -0.5$ and $J_{j, j - 1} = -0.5$ as\n", + "valid matrix elements for $J$.\n", + "In our discussion below on hyperparameters and Ridge and Lasso regression we will see that\n", + "this problem can be removed, partly and only with Lasso regression. \n", "\n", - "Before we proceed, and to link with our discussions of Bayesian statistics to come, it is useful the derive the standard regression analysis equations using a statistical interpretation. This allows us also to derive quantities like the variance and other expectation values in a rather straightforward way. \n", - "\n", - "It is assumed that $\\varepsilon_i\n", - "\\sim \\mathcal{N}(0, \\sigma^2)$ and the $\\varepsilon_{i}$ are\n", - "independent, i.e.:" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "\\begin{align*} \n", - "\\mbox{Cov}(\\varepsilon_{i_1},\n", - "\\varepsilon_{i_2}) & = \\left\\{ \\begin{array}{lcc} \\sigma^2 & \\mbox{if}\n", - "& i_1 = i_2, \\\\ 0 & \\mbox{if} & i_1 \\not= i_2. \\end{array} \\right.\n", - "\\end{align*}\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "The randomness of $\\varepsilon_i$ implies that\n", - "$\\mathbf{Y}_i$ is also a random variable. In particular,\n", - "$\\mathbf{Y}_i$ is normally distributed, because $\\varepsilon_i \\sim\n", - "\\mathcal{N}(0, \\sigma^2)$ and $\\mathbf{X}_{i,\\ast} \\, \\beta$ is a\n", - "non-random scalar. To specify the parameters of the distribution of\n", - "$\\mathbf{Y}_i$ we need to calculate its first two moments. \n", - "\n", - "\n", - "## Expectation value and variance\n", - "\n", - "Its expectation equals:" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "\\begin{align*} \n", - "\\mathbb{E}(Y_i) & =\n", - "\\mathbb{E}(\\mathbf{X}_{i, \\ast} \\, \\beta) + \\mathbb{E}(\\varepsilon_i)\n", - "\\, \\, \\, = \\, \\, \\, \\mathbf{X}_{i, \\ast} \\, \\beta, \n", - "\\end{align*}\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "while\n", - "its variance is" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "\\begin{align*} \\mbox{Var}(Y_i) & = \\mathbb{E} \\{ [Y_i\n", - "- \\mathbb{E}(Y_i)]^2 \\} \\, \\, \\, = \\, \\, \\, \\mathbb{E} ( Y_i^2 ) -\n", - "[\\mathbb{E}(Y_i)]^2 \\\\ & = \\mathbb{E} [ ( \\mathbf{X}_{i, \\ast} \\,\n", - "\\beta + \\varepsilon_i )^2] - ( \\mathbf{X}_{i, \\ast} \\, \\beta)^2 \\\\ &\n", - "= \\mathbb{E} [ ( \\mathbf{X}_{i, \\ast} \\, \\beta)^2 + 2 \\varepsilon_i\n", - "\\mathbf{X}_{i, \\ast} \\, \\beta + \\varepsilon_i^2 ] - ( \\mathbf{X}_{i,\n", - "\\ast} \\, \\beta)^2 \\\\ & = ( \\mathbf{X}_{i, \\ast} \\, \\beta)^2 + 2\n", - "\\mathbb{E}(\\varepsilon_i) \\mathbf{X}_{i, \\ast} \\, \\beta +\n", - "\\mathbb{E}(\\varepsilon_i^2 ) - ( \\mathbf{X}_{i, \\ast} \\, \\beta)^2 \n", - "\\\\ & = \\mathbb{E}(\\varepsilon_i^2 ) \\, \\, \\, = \\, \\, \\,\n", - "\\mbox{Var}(\\varepsilon_i) \\, \\, \\, = \\, \\, \\, \\sigma^2. \n", - "\\end{align*}\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "Hence, $Y_i \\sim \\mathcal{N}( \\mathbf{X}_{i, \\ast} \\, \\beta, \\sigma^2)$. \n", + "In this case our matrix inversion was actually possible. The obvious question now is what is the mathematics behind the SVD?\n", "\n", "\n", "\n", - "\n", - "\n", - "\n", - "\n", - "## The singular value decompostion\n", - "\n", - "\n", - "\n", - "A general\n", - "$m\\times n$ matrix $\\hat{A}$ can be written in terms of a diagonal\n", - "matrix $\\hat{D}$ of dimensionality $n\\times n$ and two orthognal\n", - "matrices $\\hat{U}$ and $\\hat{V}$, where the first has dimensionality\n", - "$m \\times m$ and the last dimensionality $n\\times n$. \n", - "We have then" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "\\hat{A} = \\hat{U}\\hat{D}\\hat{V}^T\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "## From standard regression to Ridge regressions\n", + "## Linear Regression Problems\n", "\n", "One of the typical problems we encounter with linear regression, in particular \n", - "when the matrix $\\hat{X}$ (our so-called design matrix) is high-dimensional, \n", - "are problems with near singular or singular matrices. The column vectors of $\\hat{X}$ \n", + "when the matrix $\\boldsymbol{X}$ (our so-called design matrix) is high-dimensional, \n", + "are problems with near singular or singular matrices. The column vectors of $\\boldsymbol{X}$ \n", "may be linearly dependent, normally referred to as super-collinearity. \n", "This means that the matrix may be rank deficient and it is basically impossible to \n", "to model the data using linear regression. As an example, consider the matrix" @@ -8499,14 +4246,14 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "The columns of $\\hat{X}$ are linearly dependent. We se this easily since the \n", + "The columns of $\\boldsymbol{X}$ are linearly dependent. We see this easily since the \n", "the first column is the row-wise sum of the other two columns. The rank (more correct,\n", "the column rank) of a matrix is the dimension of the space spanned by the\n", "column vectors. Hence, the rank of $\\mathbf{X}$ is equal to the number\n", "of linearly independent columns. In this particular case the matrix has rank 2.\n", "\n", "Super-collinearity of an $(n \\times p)$-dimensional design matrix $\\mathbf{X}$ implies\n", - "that the inverse of the matrix $\\hat{X}^T\\hat{x}$ (the matrix we needto invert to solve the linear regression equations) is non-invertible. If we have a square matrix that does not have an inverse, we say this matrix singular. The example here demonstrates this" + "that the inverse of the matrix $\\boldsymbol{X}^T\\boldsymbol{x}$ (the matrix we need to invert to solve the linear regression equations) is non-invertible. If we have a square matrix that does not have an inverse, we say this matrix singular. The example here demonstrates this" ] }, { @@ -8515,7 +4262,7 @@ "source": [ "$$\n", "\\begin{align*}\n", - "\\hat{X} & = \\left[\n", + "\\boldsymbol{X} & = \\left[\n", "\\begin{array}{rr}\n", "1 & -1\n", "\\\\\n", @@ -8529,13 +4276,14 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "We see easily that $\\mbox{det}(\\hat{X}) = x_{11} x_{22} - x_{12} x_{21} = 1 \\times (-1) - 1 \\times (-1) = 0$. Hence, $\\mathbf{X}$ is singular and its inverse is undefined.\n", - "This is equivalent to saying that the matrix $\\hat{X}$ has at least an eigenvalue which is zero.\n", + "We see easily that $\\mbox{det}(\\boldsymbol{X}) = x_{11} x_{22} - x_{12} x_{21} = 1 \\times (-1) - 1 \\times (-1) = 0$. Hence, $\\mathbf{X}$ is singular and its inverse is undefined.\n", + "This is equivalent to saying that the matrix $\\boldsymbol{X}$ has at least an eigenvalue which is zero.\n", + "\n", "\n", "\n", "## Fixing the singularity\n", "\n", - "If our design matrix $\\hat{X}$ which enters the linear regression problem" + "If our design matrix $\\boldsymbol{X}$ which enters the linear regression problem" ] }, { @@ -8543,12 +4291,12 @@ "metadata": {}, "source": [ "\n", - "
\n", + "
\n", "\n", "$$\n", "\\begin{equation}\n", - "\\hat{\\beta} = (\\hat{X}^{T} \\hat{X})^{-1} \\hat{X}^{T} \\hat{y},\n", - "\\label{_auto10} \\tag{27}\n", + "\\boldsymbol{\\beta} = (\\boldsymbol{X}^{T} \\boldsymbol{X})^{-1} \\boldsymbol{X}^{T} \\boldsymbol{y},\n", + "\\label{_auto7} \\tag{7}\n", "\\end{equation}\n", "$$" ] @@ -8558,12 +4306,12 @@ "metadata": {}, "source": [ "has linearly dependent column vectors, we will not be able to compute the inverse\n", - "of $\\hat{X}^T\\hat{X}$ and we cannot find the parameters (estimators) $\\beta_i$. \n", - "The estimators are only well-defined if $(\\hat{X}^{T}\\hat{X})^{-1}$ exits. \n", - "This is more likely to happen when the matrix $\\hat{X}$ is high-dimensional. In this case it is likely to encounter a situation where \n", + "of $\\boldsymbol{X}^T\\boldsymbol{X}$ and we cannot find the parameters (estimators) $\\beta_i$. \n", + "The estimators are only well-defined if $(\\boldsymbol{X}^{T}\\boldsymbol{X})^{-1}$ exits. \n", + "This is more likely to happen when the matrix $\\boldsymbol{X}$ is high-dimensional. In this case it is likely to encounter a situation where \n", "the regression parameters $\\beta_i$ cannot be estimated.\n", "\n", - "The *ad hoc* approach which was introduced in the 70s was simply to add a diagonal component to the matrix to invert, that is we change" + "A cheap *ad hoc* approach is simply to add a small diagonal component to the matrix to invert, that is we change" ] }, { @@ -8571,7 +4319,7 @@ "metadata": {}, "source": [ "$$\n", - "\\hat{X}^{T} \\hat{X} \\rightarrow \\hat{X}^{T} \\hat{X}+\\lambda \\hat{I},\n", + "\\boldsymbol{X}^{T} \\boldsymbol{X} \\rightarrow \\boldsymbol{X}^{T} \\boldsymbol{X}+\\lambda \\boldsymbol{I},\n", "$$" ] }, @@ -8579,421 +4327,641 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "where $\\hat{I}$ is the identity matrix.\n", + "where $\\boldsymbol{I}$ is the identity matrix. When we discuss **Ridge** regression this is actually what we end up evaluating. The parameter $\\lambda$ is called a hyperparameter. More about this later. \n", "\n", "\n", "\n", "\n", + "## Basic math of the SVD\n", "\n", "\n", - "## Fitting vs. predicting when data is in the model class\n", - "\n", - "We start by considering the case\n", - "$f(x)=2x$.\n", - "\n", - "Then the data is clearly generated by a model that is contained within\n", - "all three model classes we are using to make predictions (linear\n", - "models, third order polynomials, and tenth order polynomials).\n", - "\n", - "Run the code for the following cases:\n", - "\n", - "1. For $f(x)=2x$ , $Ntrain=10$ and $\\sigma =0$ (noiseless case), train the three classes of models (linear, third-order polynomial, and tenth order polynomial) for a training set when $x \\in [0,1]$ . Make graphs comparing fits for different order of polynomials. Which model fits the data the best?\n", - "\n", - "2. Do you think that the data that has the least error on the training set will also make the best predictions? Why or why not? Can you try to discuss and formalize your intuition? What can go right and what can go wrong?\n", - "\n", - "3. Check your answer by seeing how well your fits predict newly generated test data (including on data outside the range you fit on, for example $x \\in [0,1.2]$ ) using the code below. How well do you do on points in the range of x where you trained the model? How about points outside the original training data set?\n", - "\n", - "4. Repeat the above for $f(x)=2x$ , $Ntrain=10$ , and $\\sigma=1$ . What changes?\n", - "\n", - "Repeat the exercises above for $f(x)=2x$ , $Ntrain=100$ , and $\\sigma=1$ . What changes?\n", - "Summarize what you have learned about the relationship between model complexity (number of parameters), goodness of fit on training data, and the ability to predict well.\n", - "\n", - "\n", - "\n", - "## Fitting versus predicting when data is not in the model class\n", - "\n", - "Thus far, we have considered the case where the data is generated using a model contained in the model class. Now consider $f(x)=2x-10x^5+15x^{10}$ . Notice that the for linear and third-order polynomial the true model $f(x)$ is not contained in model class.\n", - "\n", - "1. Do better fits lead to better predictions?\n", - "\n", - "2. What is the relationship between the true model for generating the data and the model class that has the most predictive power? How is this related to the model complexity? How does this depend on the number of data points $Ntrain$ and $\\sigma$?\n", - "\n", - "Summarize what you think you learned about the relationship of knowing the true model class and predictive power.\n", - "\n", - "\n", - "## An example code without the model assessment part" - ] - }, - { - "cell_type": "code", - "execution_count": 43, - "metadata": { - "collapsed": false - }, - "outputs": [], - "source": [ - "import numpy as np\n", - "import sklearn as sk\n", - "from sklearn import datasets, linear_model\n", - "from sklearn.preprocessing import PolynomialFeatures\n", - "\n", - "import matplotlib as mpl\n", - "from matplotlib import pyplot as plt\n", - "\n", - "%matplotlib notebook\n", - "\n", - "# The Training Data\n", - "\n", - "N_train=100\n", - "\n", - "sigma_train=1;\n", - "\n", - "# Train on integers\n", - "x=np.linspace(0.05,0.95,N_train)\n", - "# Draw random noise\n", - "s = sigma_train*np.random.randn(N_train)\n", - "\n", - "#linear\n", - "y=2*x+s\n", - "\n", - "#Tenth Order\n", - "#y=2*x-10*x**5+15*x**10+s\n", - "\n", - "p1=plt.plot(x,y, \"o\",ms=15, label='Training')\n", - "\n", - "#Linear Regression\n", - "# Create linear regression object\n", - "clf = linear_model.LinearRegression()\n", - "\n", - "# Train the model using the training sets\n", - "clf.fit(x[:, np.newaxis], y)\n", - "# The coefficients\n", - "\n", - "xplot=np.linspace(0.02,0.98,200)\n", - "linear_plot=plt.plot(xplot, clf.predict(xplot[:, np.newaxis]),label='Linear')\n", - "\n", - "#Polynomial Regression\n", - "\n", - "\n", - "poly3 = PolynomialFeatures(degree=3)\n", - "X = poly3.fit_transform(x[:,np.newaxis])\n", - "clf3 = linear_model.LinearRegression()\n", - "clf3.fit(X,y)\n", - "\n", - "\n", - "Xplot=poly3.fit_transform(xplot[:,np.newaxis])\n", - "poly3_plot=plt.plot(xplot, clf3.predict(Xplot), label='Poly 3')\n", - "\n", - "\n", - "\n", - "#poly5 = PolynomialFeatures(degree=5)\n", - "#X = poly5.fit_transform(x[:,np.newaxis])\n", - "#clf5 = linear_model.LinearRegression()\n", - "#clf5.fit(X,y)\n", - "\n", - "#Xplot=poly5.fit_transform(xplot[:,np.newaxis])\n", - "#plt.plot(xplot, clf5.predict(Xplot), 'r--',linewidth=1)\n", - "\n", - "poly10 = PolynomialFeatures(degree=10)\n", - "X = poly10.fit_transform(x[:,np.newaxis])\n", - "clf10 = linear_model.LinearRegression()\n", - "clf10.fit(X,y)\n", - "\n", - "Xplot=poly10.fit_transform(xplot[:,np.newaxis])\n", - "poly10_plot=plt.plot(xplot, clf10.predict(Xplot), label='Poly 10')\n", - "\n", - "axes = plt.gca()\n", - "axes.set_ylim([-7,7])\n", - "\n", - "handles, labels=axes.get_legend_handles_labels()\n", - "plt.legend(handles,labels, loc='lower center')\n", - "plt.xlabel(\"$x$\")\n", - "plt.ylabel(\"$y$\")\n", - "Title=\"$N=$\"+str(N_train)+\", $\\sigma=$\"+str(sigma_train)\n", - "plt.title(Title+\" (train)\")\n", - "plt.tight_layout()\n", - "plt.show()" + "From standard linear algebra we know that a square matrix $\\boldsymbol{X}$ can be diagonalized if and only it is \n", + "a so-called [normal matrix](https://en.wikipedia.org/wiki/Normal_matrix), that is if $\\boldsymbol{X}\\in {\\mathbb{R}}^{n\\times n}$\n", + "we have $\\boldsymbol{X}\\boldsymbol{X}^T=\\boldsymbol{X}^T\\boldsymbol{X}$ or if $\\boldsymbol{X}\\in {\\mathbb{C}}^{n\\times n}$ we have $\\boldsymbol{X}\\boldsymbol{X}^{\\dagger}=\\boldsymbol{X}^{\\dagger}\\boldsymbol{X}$.\n", + "The matrix has then a set of eigenpairs" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ - "## Generating test data" - ] - }, - { - "cell_type": "code", - "execution_count": 44, - "metadata": { - "collapsed": false - }, - "outputs": [], - "source": [ - "# Generate Test Data\n", - "\n", - "#Number of test data\n", - "N_test=20\n", - "\n", - "sigma_test=sigma_train\n", - "\n", - "max_x=1.2\n", - "x_test=max_x*np.random.random(N_test)\n", - "# Draw random noise\n", - "s_test = sigma_test*np.random.randn(N_test)\n", - "\n", - "#Linear\n", - "y_test=2*x_test+s_test\n", - "#Tenth order\n", - "#y_test=2*x_test-10*x_test**5+15*x_test**10+s_test\n", - "\n", - "#Make design matrices for prediction\n", - "x_plot=np.linspace(0,max_x, 200)\n", - "X3 = poly3.fit_transform(x_plot[:,np.newaxis])\n", - "X10 = poly10.fit_transform(x_plot[:,np.newaxis])\n", - "\n", - "%matplotlib notebook\n", - "\n", - "fig = plt.figure() \n", - "p1=plt.plot(x_test,y_test.transpose(), 'o', ms=12, label='data')\n", - "p2=plt.plot(x_plot,clf.predict(x_plot[:,np.newaxis]), label='linear')\n", - "p3=plt.plot(x_plot,clf3.predict(X3), label='3rd order')\n", - "p10=plt.plot(x_plot,clf10.predict(X10), label='10th order')\n", - "\n", - "\n", - "plt.legend(loc=2)\n", - "plt.xlabel('$x$')\n", - "plt.ylabel('$y$')\n", - "plt.legend(loc='best')\n", - "plt.title(Title+\" (pred.)\")\n", - "plt.tight_layout()\n", - "plt.show()" + "$$\n", + "(\\lambda_1,\\boldsymbol{u}_1),\\dots, (\\lambda_n,\\boldsymbol{u}_n),\n", + "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ - "## How can we effectively evaluate the various models?\n", - "\n", - "In Ridge regression and the subsequent discussion of its properties\n", - "the bias or penalty parameter is considered known or `given'. In\n", - "practice, it is unknown and the user needs to make an informed\n", - "decision on its value. How do we do that? Much of the same considerations apply to the Lasso method. \n", - "\n", - "\n", - "## Code examples for Ridge and Lasso Regression" - ] - }, - { - "cell_type": "code", - "execution_count": 45, - "metadata": { - "collapsed": false - }, - "outputs": [], - "source": [ - "import matplotlib.pyplot as plt\n", - "import numpy as np\n", - "from sklearn import linear_model\n", - "from sklearn.linear_model import LinearRegression\n", - "from sklearn.metrics import mean_squared_error, r2_score\n", - "\n", - "#creating data with random noise\n", - "x=np.arange(50)\n", - "\n", - "delta=np.random.uniform(-2.5,2.5, size=(50))\n", - "np.random.shuffle(delta)\n", - "y =0.5*x+5+delta\n", - "\n", - "#arranging data into 2x50 matrix\n", - "a=np.array(x) #inputs\n", - "b=np.array(y) #outputs\n", - "\n", - "#Split into training and test\n", - "X_train=a[:37, np.newaxis]\n", - "X_test=a[37:, np.newaxis]\n", - "y_train=b[:37]\n", - "y_test=b[37:]\n", - "\n", - "print (\"X_train: \", X_train.shape)\n", - "print (\"y_train: \", y_train.shape)\n", - "print (\"X_test: \", X_test.shape)\n", - "print (\"y_test: \", y_test.shape)\n", - "\n", - "print (\"------------------------------------\")\n", - "\n", - "print (\"Ordinary Least Squares\")\n", - "#Add Ordinary Least Squares fit\n", - "reg=LinearRegression()\n", - "reg.fit(X_train, y_train)\n", - "pred=reg.predict(X_test)\n", - "print (\"Prediction Shape: \", pred.shape)\n", - "\n", - "print('Coefficients: \\n', reg.coef_)\n", - "# The mean squared error\n", - "print(\"Mean squared error: %.2f\"\n", - " % mean_squared_error(y_test, pred))\n", - "# Explained variance score: 1 is perfect prediction\n", - "print('Variance score: %.2f' % r2_score(y_test, pred))\n", - "\n", - "#plot\n", - "plt.scatter(X_test,y_test,color='green', label=\"Training Data\")\n", - "plt.plot(X_test, pred, color='black', label=\"Fit Line\")\n", - "plt.legend()\n", - "plt.show()\n", - "\n", - "print (\"------------------------------------\")\n", - "\n", - "print (\"Ridge Regression\")\n", - "\n", - "ridge=linear_model.RidgeCV(alphas=[0.1,1.0,10.0])\n", - "ridge.fit(X_train,y_train)\n", - "print (\"Ridge Coefficient: \",ridge.coef_)\n", - "print (\"Ridge Intercept: \", ridge.intercept_)\n", - "#Look into graphing with Ridge fit\n", - "\n", - "print (\"------------------------------------\")\n", - "\n", - "print (\"Lasso\")\n", - "lasso=linear_model.Lasso(alpha=0.1)\n", - "lasso.fit(X_train,y_train)\n", - "predl=lasso.predict(X_test)\n", - "print(\"Lasso Coefficient: \", lasso.coef_)\n", - "print(\"Lasso Intercept: \", lasso.intercept_)\n", - "plt.scatter(X_test,y_test,color='green', label=\"Training Data\")\n", - "plt.plot(X_test, predl, color='blue', label=\"Lasso\")\n", - "plt.legend()\n", - "plt.show()" + "and the eigenvalues are given by the diagonal matrix" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ - "## A second-order polynomial with Ridge and Lasso" - ] - }, - { - "cell_type": "code", - "execution_count": 46, - "metadata": { - "collapsed": false - }, - "outputs": [], - "source": [ - "import numpy as np\n", - "import matplotlib.pyplot as plt\n", - "from sklearn.linear_model import Ridge\n", - "from sklearn.metrics import r2_score\n", - "\n", - "np.random.seed(4155)\n", - "\n", - "n_samples = 100\n", - "\n", - "x = np.random.rand(n_samples,1)\n", - "y = 5*x*x + 0.1*np.random.rand(n_samples,1)\n", - "\n", - "# Centering x and y.\n", - "x_ = x - np.mean(x)\n", - "y_ = y - np.mean(y) # beta_0 = mean(y)\n", - "\n", - "X = np.c_[np.ones((n_samples,1)), x, x**2]\n", - "X_ = np.c_[x_, x_**2]\n", - "\n", - "\n", - "### 1.\n", - "lmb_values = [1e-4, 1e-3, 1e-2, 10, 1e2, 1e4]\n", - "num_values = len(lmb_values)\n", - "\n", - "## Ridge-regression of centered and not centered data\n", - "beta_ridge = np.zeros((3,num_values))\n", - "beta_ridge_centered = np.zeros((3,num_values))\n", - "\n", - "I3 = np.eye(3)\n", - "I2 = np.eye(2)\n", - "\n", - "for i,lmb in enumerate(lmb_values):\n", - " beta_ridge[:,i] = (np.linalg.inv( X.T @ X + lmb*I3) @ X.T @ y).flatten()\n", - " beta_ridge_centered[1:,i] = (np.linalg.inv( X_.T @ X_ + lmb*I2) @ X_.T @ y_).flatten()\n", - "\n", - "# sett beta_0 = np.mean(y)\n", - "beta_ridge_centered[0,:] = np.mean(y)\n", - "\n", - "## OLS (ordinary least squares) solution \n", - "beta_ls = np.linalg.inv( X.T @ X ) @ X.T @ y\n", - "\n", - "## Evaluate the models\n", - "pred_ls = X @ beta_ls\n", - "pred_ridge = X @ beta_ridge\n", - "pred_ridge_centered = X_ @ beta_ridge_centered[1:] + beta_ridge_centered[0,:]\n", - "\n", - "## Plot the results\n", - "\n", - "# Sorting\n", - "sort_ind = np.argsort(x[:,0])\n", - "\n", - "x_plot = x[sort_ind,0]\n", - "x_centered_plot = x_[sort_ind,0]\n", - "\n", - "pred_ls_plot = pred_ls[sort_ind,0]\n", - "pred_ridge_plot = pred_ridge[sort_ind,:]\n", - "pred_ridge_centered_plot = pred_ridge_centered[sort_ind,:]\n", - "\n", - "# Plott not centered\n", - "plt.plot(x_plot,pred_ls_plot,label='ls')\n", - "\n", - "for i in range(num_values):\n", - " plt.plot(x_plot,pred_ridge_plot[:,i],label='ridge, lmb=%g'%lmb_values[i])\n", - "\n", - "plt.plot(x,y,'ro')\n", - "\n", - "plt.title('linear regression on un-centered data')\n", - "plt.legend()\n", - "\n", - "# Plott centered\n", - "plt.figure()\n", - "\n", - "for i in range(num_values):\n", - " plt.plot(x_centered_plot,pred_ridge_centered_plot[:,i],label='ridge, lmb=%g'%lmb_values[i])\n", - "\n", - "plt.plot(x_,y,'ro')\n", - "\n", - "plt.title('linear regression on centered data')\n", - "plt.legend()\n", - "\n", - "\n", - "# 2.\n", - "\n", - "pred_ridge_scikit = np.zeros((n_samples,num_values))\n", - "for i,lmb in enumerate(lmb_values):\n", - " pred_ridge_scikit[:,i] = (Ridge(alpha=lmb,fit_intercept=False).fit(X,y).predict(X)).flatten() # fit_intercept=False fordi bias er allerede i X\n", - "\n", - "plt.figure()\n", - "\n", - "plt.plot(x_plot,pred_ls_plot,label='ls')\n", - "\n", - "for i in range(num_values):\n", - " plt.plot(x_plot,pred_ridge_scikit[sort_ind,i],label='scikit-ridge, lmb=%g'%lmb_values[i])\n", - "\n", - "plt.plot(x,y,'ro')\n", - "plt.legend()\n", - "plt.title('linear regression using scikit')\n", - "\n", - "plt.show()\n", - "\n", - "### R2-score of the results\n", - "for i in range(num_values):\n", - " print('lambda = %g'%lmb_values[i])\n", - " print('r2 for scikit: %g'%r2_score(y,pred_ridge_scikit[:,i]))\n", - " print('r2 for own code, not centered: %g'%r2_score(y,pred_ridge[:,i]))\n", - " print('r2 for own, centered: %g\\n'%r2_score(y,pred_ridge_centered[:,i]))" + "$$\n", + "\\boldsymbol{\\Sigma}=\\mathrm{Diag}(\\lambda_1, \\dots,\\lambda_n).\n", + "$$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ + "The matrix $\\boldsymbol{X}$ can be written in terms of an orthogonal/unitary transformation $\\boldsymbol{U}$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "$$\n", + "\\boldsymbol{X} = \\boldsymbol{U}\\boldsymbol{\\Sigma}\\boldsymbol{V}^T,\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "with $\\boldsymbol{U}\\boldsymbol{U}^T=\\boldsymbol{I}$ or $\\boldsymbol{U}\\boldsymbol{U}^{\\dagger}=\\boldsymbol{I}$.\n", + "\n", + "Not all square matrices are diagonalizable. A matrix like the one discussed above" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "$$\n", + "\\boldsymbol{X} = \\begin{bmatrix} \n", + "1& -1 \\\\\n", + "1& -1\\\\\n", + "\\end{bmatrix}\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "is not diagonalizable, it is a so-called [defective matrix](https://en.wikipedia.org/wiki/Defective_matrix). It is easy to see that the condition\n", + "$\\boldsymbol{X}\\boldsymbol{X}^T=\\boldsymbol{X}^T\\boldsymbol{X}$ is not fulfilled. \n", + "\n", + "\n", + "\n", + "## The SVD, a Fantastic Algorithm\n", + "\n", + "\n", + "However, and this is the strength of the SVD algorithm, any general\n", + "matrix $\\boldsymbol{X}$ can be decomposed in terms of a diagonal matrix and\n", + "two orthogonal/unitary matrices. The [Singular Value Decompostion\n", + "(SVD) theorem](https://en.wikipedia.org/wiki/Singular_value_decomposition)\n", + "states that a general $m\\times n$ matrix $\\boldsymbol{X}$ can be written in\n", + "terms of a diagonal matrix $\\boldsymbol{\\Sigma}$ of dimensionality $n\\times n$\n", + "and two orthognal matrices $\\boldsymbol{U}$ and $\\boldsymbol{V}$, where the first has\n", + "dimensionality $m \\times m$ and the last dimensionality $n\\times n$.\n", + "We have then" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "$$\n", + "\\boldsymbol{X} = \\boldsymbol{U}\\boldsymbol{\\Sigma}\\boldsymbol{V}^T\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "As an example, the above defective matrix can be decomposed as" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "$$\n", + "\\boldsymbol{X} = \\frac{1}{\\sqrt{2}}\\begin{bmatrix} 1& 1 \\\\ 1& -1\\\\ \\end{bmatrix} \\begin{bmatrix} 2& 0 \\\\ 0& 0\\\\ \\end{bmatrix} \\frac{1}{\\sqrt{2}}\\begin{bmatrix} 1& -1 \\\\ 1& 1\\\\ \\end{bmatrix}=\\boldsymbol{U}\\boldsymbol{\\Sigma}\\boldsymbol{V}^T,\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "with eigenvalues $\\sigma_1=2$ and $\\sigma_2=0$. \n", + "The SVD exits always! \n", + "\n", + "\n", + "\n", + "## Another Example\n", + "\n", + "Consider the following matrix which can be SVD decomposed as" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "$$\n", + "\\boldsymbol{X} = \\frac{1}{15}\\begin{bmatrix} 14 & 2\\\\ 4 & 22\\\\ 16 & 13\\end{matrix}=\\frac{1}{3}\\begin{bmatrix} 1& 2 & 2 \\\\ 2& -1 & 1\\\\ 2 & 1& -2\\end{bmatrix} \\begin{bmatrix} 2& 0 \\\\ 0& 1\\\\ 0 & 0\\end{bmatrix}\\frac{1}{5}\\begin{bmatrix} 3& 4 \\\\ 4& -3\\end{bmatrix}=\\boldsymbol{U}\\boldsymbol{\\Sigma}\\boldsymbol{V}^T.\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "This is a $3\\times 2$ matrix which is decomposed in terms of a\n", + "$3\\times 3$ matrix $\\boldsymbol{U}$, and a $2\\times 2$ matrix $\\boldsymbol{V}$. It is easy to see\n", + "that $\\boldsymbol{U}$ and $\\boldsymbol{V}$ are orthogonal (how?). \n", + "\n", + "And the SVD\n", + "decomposition (singular values) gives eigenvalues \n", + "$\\sigma_i\\geq\\sigma_{i+1}$ for all $i$ and for dimensions larger than $i=2$, the\n", + "eigenvalues (singular values) are zero.\n", + "\n", + "In the general case, where our design matrix $\\boldsymbol{X}$ has dimension\n", + "$n\\times p$, the matrix is thus decomposed into an $n\\times n$\n", + "orthogonal matrix $\\boldsymbol{U}$, a $p\\times p$ orthogonal matrix $\\boldsymbol{V}$\n", + "and a diagonal matrix $\\boldsymbol{\\Sigma}$ with $r=\\mathrm{min}(n,p)$\n", + "singular values $\\sigma_i\\lg 0$ on the main diagonal and zeros filling\n", + "the rest of the matrix. There are at most $p$ singular values\n", + "assuming that $n > p$. In our regression examples for the nuclear\n", + "masses and the equation of state this is indeed the case, while for\n", + "the Ising model we have $p > n$. These are often cases that lead to\n", + "near singular or singular matrices.\n", + "\n", + "The columns of $\\boldsymbol{U}$ are called the left singular vectors while the columns of $\\boldsymbol{V}$ are the right singular vectors.\n", + "\n", + "\n", + "## Economy-size SVD\n", + "\n", + "If we assume that $n > p$, then our matrix $\\boldsymbol{U}$ has dimension $n\n", + "\\times n$. The last $n-p$ columns of $\\boldsymbol{U}$ become however\n", + "irrelevant in our calculations since they are multiplied with the\n", + "zeros in $\\boldsymbol{\\Sigma}$.\n", + "\n", + "The economy-size decomposition removes extra rows or columns of zeros\n", + "from the diagonal matrix of singular values, $\\boldsymbol{\\Sigma}$, along with the columns\n", + "in either $\\boldsymbol{U}$ or $\\boldsymbol{V}$ that multiply those zeros in the expression. \n", + "Removing these zeros and columns can improve execution time\n", + "and reduce storage requirements without compromising the accuracy of\n", + "the decomposition.\n", + "\n", + "If $n > p$, we keep only the first $p$ columns of $\\boldsymbol{U}$ and $\\boldsymbol{\\Sigma}$ has dimension $p\\times p$. \n", + "If $p > n$, then only the first $n$ columns of $\\boldsymbol{V}$ are computed and $\\boldsymbol{\\Sigma}$ has dimension $n\\times n$.\n", + "The $n=p$ case is obvious, we retain the full SVD. \n", + "In general the economy-size SVD leads to less FLOPS and still conserving the desired accuracy.\n", + "\n", + "\n", + "## Mathematical Properties\n", + "\n", + "There are several interesting mathematical properties which will be\n", + "relevant when we are going to discuss the differences between say\n", + "ordinary least squares (OLS) and **Ridge** regression.\n", + "\n", + "We have from OLS that the parameters of the linear approximation are given by" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "$$\n", + "\\boldsymbol{\\tilde{y}} = \\boldsymbol{X}\\boldsymbol{\\beta} = \\boldsymbol{X}\\left(\\boldsymbol{X}^T\\boldsymbol{X}\\right)^{-1}\\boldsymbol{X}^T\\boldsymbol{y}.\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "The matrix to invert can be rewritten in terms of our SVD decomposition as" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "$$\n", + "\\boldsymbol{X}^T\\boldsymbol{X} = \\boldsymbol{V}\\boldsymbol{\\Sigma}^T\\boldsymbol{U}^T\\boldsymbol{U}\\boldsymbol{\\Sigma}\\boldsymbol{V}^T.\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Using the orthogonality properties of $\\boldsymbol{U}$ we have" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "$$\n", + "\\boldsymbol{X}^T\\boldsymbol{X} = \\boldsymbol{V}\\boldsymbol{\\Sigma}^T\\boldsymbol{\\Sigma}\\boldsymbol{V}^T = \\boldsymbol{V}\\boldsymbol{D}\\boldsymbol{V}^T,\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "with $\\boldsymbol{D}$ being a diagonal matrix with values along the diagonal given by the singular values squared. \n", + "\n", + "This means that" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "$$\n", + "(\\boldsymbol{X}^T\\boldsymbol{X})\\boldsymbol{V} = \\boldsymbol{V}\\boldsymbol{D},\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "that is the eigenvectors of $(\\boldsymbol{X}^T\\boldsymbol{X})$ are given by the columns of the right singular matrix of $\\boldsymbol{X}$ and the eigenvalues are the squared singular values. It is easy to show (show this) that" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "$$\n", + "(\\boldsymbol{X}\\boldsymbol{X}^T)\\boldsymbol{U} = \\boldsymbol{U}\\boldsymbol{D},\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "that is, the eigenvectors of $(\\boldsymbol{X}\\boldsymbol{X})^T$ are the columns of the left singular matrix and the eigenvalues are the same. \n", + "\n", + "Going back to our OLS equation we have" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "$$\n", + "\\boldsymbol{X}\\boldsymbol{\\beta} = \\boldsymbol{X}\\left(\\boldsymbol{V}\\boldsymbol{D}\\boldsymbol{V}^T \\right)^{-1}\\boldsymbol{X}^T\\boldsymbol{y}=\\boldsymbol{U\\Sigma V^T}\\left(\\boldsymbol{V}\\boldsymbol{D}\\boldsymbol{V}^T \\right)^{-1}(\\boldsymbol{U\\Sigma V^T})^T\\boldsymbol{y}=\\boldsymbol{U}\\boldsymbol{U}^T\\boldsymbol{y}.\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "We will come back to this expression when we discuss Ridge regression. \n", + "\n", + "\n", + "\n", + "## Ridge and LASSO Regression\n", + "\n", + "Let us remind ourselves about the expression for the standard Mean Squared Error (MSE) which we used to define our cost function and the equations for the ordinary least squares (OLS) method, that is \n", + "our optimization problem is" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "$$\n", + "{\\displaystyle \\min_{\\boldsymbol{\\beta}\\in {\\mathbb{R}}^{p}}}\\frac{1}{n}\\left\\{\\left(\\boldsymbol{y}-\\boldsymbol{X}\\boldsymbol{\\beta}\\right)^T\\left(\\boldsymbol{y}-\\boldsymbol{X}\\boldsymbol{\\beta}\\right)\\right\\}.\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "or we can state it as" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "$$\n", + "{\\displaystyle \\min_{\\boldsymbol{\\beta}\\in\n", + "{\\mathbb{R}}^{p}}}\\frac{1}{n}\\sum_{i=0}^{n-1}\\left(y_i-\\tilde{y}_i\\right)^2=\\frac{1}{n}\\vert\\vert \\boldsymbol{y}-\\boldsymbol{X}\\boldsymbol{\\beta}\\vert\\vert_2^2,\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "where we have used the definition of a norm-2 vector, that is" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "$$\n", + "\\vert\\vert \\boldsymbol{x}\\vert\\vert_2 = \\sqrt{\\sum_i x_i^2}.\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "By minimizing the above equation with respect to the parameters\n", + "$\\boldsymbol{\\beta}$ we could then obtain an analytical expression for the\n", + "parameters $\\boldsymbol{\\beta}$. We can add a regularization parameter $\\lambda$ by\n", + "defining a new cost function to be optimized, that is" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "$$\n", + "{\\displaystyle \\min_{\\boldsymbol{\\beta}\\in\n", + "{\\mathbb{R}}^{p}}}\\frac{1}{n}\\vert\\vert \\boldsymbol{y}-\\boldsymbol{X}\\boldsymbol{\\beta}\\vert\\vert_2^2+\\lambda\\vert\\vert \\boldsymbol{\\beta}\\vert\\vert_2^2\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "which leads to the Ridge regression minimization problem where we\n", + "require that $\\vert\\vert \\boldsymbol{\\beta}\\vert\\vert_2^2\\le t$, where $t$ is\n", + "a finite number larger than zero. By defining" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "$$\n", + "C(\\boldsymbol{X},\\boldsymbol{\\beta})=\\frac{1}{n}\\vert\\vert \\boldsymbol{y}-\\boldsymbol{X}\\boldsymbol{\\beta}\\vert\\vert_2^2+\\lambda\\vert\\vert \\boldsymbol{\\beta}\\vert\\vert_1,\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "we have a new optimization equation" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "$$\n", + "{\\displaystyle \\min_{\\boldsymbol{\\beta}\\in\n", + "{\\mathbb{R}}^{p}}}\\frac{1}{n}\\vert\\vert \\boldsymbol{y}-\\boldsymbol{X}\\boldsymbol{\\beta}\\vert\\vert_2^2+\\lambda\\vert\\vert \\boldsymbol{\\beta}\\vert\\vert_1\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "which leads to Lasso regression. Lasso stands for least absolute shrinkage and selection operator. \n", + "\n", + "Here we have defined the norm-1 as" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "$$\n", + "\\vert\\vert \\boldsymbol{x}\\vert\\vert_1 = \\sum_i \\vert x_i\\vert.\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Using the matrix-vector expression for Ridge regression," + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "$$\n", + "C(\\boldsymbol{X},\\boldsymbol{\\beta})=\\frac{1}{n}\\left\\{(\\boldsymbol{y}-\\boldsymbol{X}\\boldsymbol{\\beta})^T(\\boldsymbol{y}-\\boldsymbol{X}\\boldsymbol{\\beta})\\right\\}+\\lambda\\boldsymbol{\\beta}^T\\boldsymbol{\\beta},\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "by taking the derivatives with respect to $\\boldsymbol{\\beta}$ we obtain then\n", + "a slightly modified matrix inversion problem which for finite values\n", + "of $\\lambda$ does not suffer from singularity problems. We obtain" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "$$\n", + "\\boldsymbol{\\beta}^{\\mathrm{Ridge}} = \\left(\\boldsymbol{X}^T\\boldsymbol{X}+\\lambda\\boldsymbol{I}\\right)^{-1}\\boldsymbol{X}^T\\boldsymbol{y},\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "with $\\boldsymbol{I}$ being a $p\\times p$ identity matrix with the constraint that" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "$$\n", + "\\sum_{i=0}^{p-1} \\beta_i^2 \\leq t,\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "with $t$ a finite positive number. \n", + "\n", + "We see that Ridge regression is nothing but the standard\n", + "OLS with a modified diagonal term added to $\\boldsymbol{X}^T\\boldsymbol{X}$. The\n", + "consequences, in particular for our discussion of the bias-variance\n", + "are rather interesting.\n", + "\n", + "Furthermore, if we use the result above in terms of the SVD decomposition (our analysis was done for the OLS method), we had" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "$$\n", + "(\\boldsymbol{X}\\boldsymbol{X}^T)\\boldsymbol{U} = \\boldsymbol{U}\\boldsymbol{D}.\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "We can analyse the OLS solutions in terms of the eigenvectors (the columns) of the right singular value matrix $\\boldsymbol{U}$ as" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "$$\n", + "\\boldsymbol{X}\\boldsymbol{\\beta} = \\boldsymbol{X}\\left(\\boldsymbol{V}\\boldsymbol{D}\\boldsymbol{V}^T \\right)^{-1}\\boldsymbol{X}^T\\boldsymbol{y}=\\boldsymbol{U\\Sigma V^T}\\left(\\boldsymbol{V}\\boldsymbol{D}\\boldsymbol{V}^T \\right)^{-1}(\\boldsymbol{U\\Sigma V^T})^T\\boldsymbol{y}=\\boldsymbol{U}\\boldsymbol{U}^T\\boldsymbol{y}\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "For Ridge regression this becomes" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "$$\n", + "\\boldsymbol{X}\\boldsymbol{\\beta}^{\\mathrm{Ridge}} = \\boldsymbol{U\\Sigma V^T}\\left(\\boldsymbol{V}\\boldsymbol{D}\\boldsymbol{V}^T+\\lambda\\boldsymbol{I} \\right)^{-1}(\\boldsymbol{U\\Sigma V^T})^T\\boldsymbol{y}=\\sum_{j=0}^{p-1}\\boldsymbol{u}_j\\boldsymbol{u}_j^T\\frac{\\sigma_j^2}{\\sigma_j^2+\\lambda}\\boldsymbol{y},\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "with the vectors $\\boldsymbol{u}_j$ being the columns of $\\boldsymbol{U}$. \n", + "\n", + "## Interpreting the Ridge results\n", + "\n", + "Since $\\lambda \\geq 0$, it means that compared to OLS, we have" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "$$\n", + "\\frac{\\sigma_j^2}{\\sigma_j^2+\\lambda} \\leq 1.\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Ridge regression finds the coordinates of $\\boldsymbol{y}$ with respect to the\n", + "orthonormal basis $\\boldsymbol{U}$, it then shrinks the coordinates by\n", + "$\\frac{\\sigma_j^2}{\\sigma_j^2+\\lambda}$. Recall that the SVD has\n", + "eigenvalues ordered in a descending way, that is $\\sigma_i \\geq\n", + "\\sigma_{i+1}$.\n", + "\n", + "For small eigenvalues $\\sigma_i$ it means that their contributions become less important, a fact which can be used to reduce the number of degrees of freedom.\n", + "Actually, calculating the variance of $\\boldsymbol{X}\\boldsymbol{v}_j$ shows that this quantity is equal to $\\sigma_j^2/n$.\n", + "With a parameter $\\lambda$ we can thus shrink the role of specific parameters. \n", + "\n", + "\n", + "For the sake of simplicity, let us assume that the design matrix is orthonormal, that is" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "$$\n", + "\\boldsymbol{X}^T\\boldsymbol{X}=(\\boldsymbol{X}^T\\boldsymbol{X})^{-1} =\\boldsymbol{I}.\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "In this case the standard OLS results in" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "$$\n", + "\\boldsymbol{\\beta}^{\\mathrm{OLS}} = \\boldsymbol{X}^T\\boldsymbol{y}=\\sum_{i=0}^{p-1}\\boldsymbol{u}_j\\boldsymbol{u}_j^T\\boldsymbol{y},\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "and" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "$$\n", + "\\boldsymbol{\\beta}^{\\mathrm{Ridge}} = \\left(\\boldsymbol{I}+\\lambda\\boldsymbol{I}\\right)^{-1}\\boldsymbol{X}^T\\boldsymbol{y}=\\left(1+\\lambda\\right)^{-1}\\boldsymbol{\\beta}^{\\mathrm{OLS}},\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "that is the Ridge estimator scales the OLS estimator by the inverse of a factor $1+\\lambda$, and\n", + "the Ridge estimator converges to zero when the hyperparameter goes to\n", + "infinity.\n", + "\n", + "We will come back to more interpreations after we have gone through some of the statistical analysis part. \n", + "\n", + "For more discussions of Ridge and Lasso regression, [Wessel van Wieringen's](https://arxiv.org/abs/1509.09169) article is highly recommended.\n", + "Similarly, [Mehta et al's article](https://arxiv.org/abs/1803.08823) is also recommended.\n", + "\n", + "## Where are we going?\n", + "\n", + "Before we proceed, we need to rethink what we have been doing. In our\n", + "eager to fit the data, we have omitted several important elements in\n", + "our regression analysis. In what follows we will\n", + "1. look at statistical properties, including a discussion of mean values, variance and the so-called bias-variance tradeoff\n", + "\n", + "2. introduce resampling techniques like cross-validation, bootstrapping and jackknife and more\n", + "\n", + "This will allow us to link the standard linear algebra methods we have discussed above to a statistical interpretation of the methods. \n", + "\n", + "\n", + "\n", "## Resampling methods\n", "\n", "Resampling methods are an indispensable tool in modern\n", @@ -9008,9 +4976,6 @@ "once using the original training sample.\n", "\n", "\n", - "\n", - "## Resampling approaches can be computationally expensive\n", - "\n", "Resampling approaches can be computationally expensive, because they\n", "involve fitting the same statistical method multiple times using\n", "different subsets of the training data. However, due to recent\n", @@ -9027,28 +4992,24 @@ "level of flexibility for a model is known as model selection. The\n", "bootstrap is widely used.\n", "\n", - "\n", - "\n", "## Why resampling methods ?\n", - " Statistical analysis\n", - " * Our simulations can be treated as *computer experiments*. This is particularly the case for Monte Carlo methods\n", "\n", - " * The results can be analysed with the same statistical tools as we would use analysing experimental data.\n", + "* Our simulations can be treated as *computer experiments*. This is particularly the case for Monte Carlo methods\n", "\n", - " * As in all experiments, we are looking for expectation values and an estimate of how accurate they are, i.e., possible sources for errors.\n", + "* The results can be analysed with the same statistical tools as we would use analysing experimental data.\n", "\n", - "## Statistical analysis\n", + "* As in all experiments, we are looking for expectation values and an estimate of how accurate they are, i.e., possible sources for errors.\n", "\n", - " * As in other experiments, many numerical experiments have two classes of errors:\n", + "* As in other experiments, many numerical experiments have two classes of errors:\n", "\n", - " * Statistical errors\n", + " * Statistical errors\n", "\n", - " * Systematical errors\n", + " * Systematical errors\n", "\n", "\n", - " * Statistical errors can be estimated using standard tools from statistics\n", + "* Statistical errors can be estimated using standard tools from statistics\n", "\n", - " * Systematical errors are method specific and must be treated differently from case to case. \n", + "* Systematical errors are method specific and must be treated differently from case to case. \n", "\n", "## Statistics\n", "\n", @@ -9096,27 +5057,9 @@ "numbers chosen as if by chance from some specified PDF so that the\n", "selection of a large set of these numbers reproduces this PDF.\n", "\n", - "\n", - "\n", - "\n", - "\n", - "\n", - "\n", - "## Log-likelihood\n", - "\n", - "A popular strategy is to choose a penalty parameter that yields a good\n", - "but parsimonious model. Information criteria measure the balance\n", - "between model fit and model complexity. One possibility is Aikaike's\n", - "information criterion (AIC).\n", - "The AIC measures model fit by the log-likelihood\n", - "and model complexity is measured by the number of parameters used by\n", - "the model. The number of model parameters in regular regression simply\n", - "corresponds to the number of covariates in the model. Or, by the\n", - "degrees of freedom consumed by the model, which is equivalent to the\n", - "trace of the hat matrix. For ridge regression it thus seems natural to\n", - "define model complexity analogously by the trace of the ridge hat\n", - "matrix. This yields the AIC for the linear regression model with ridge\n", - "estimates:" + "A particularly useful class of special expectation values are the\n", + "*moments*. The $n$-th moment of the PDF $p$ is defined as\n", + "follows:" ] }, { @@ -9124,13 +5067,1056 @@ "metadata": {}, "source": [ "$$\n", - "\\begin{align*}\n", - "\\mbox{AIC}(\\lambda) & = 2 \\, p - 2 \\log(\\hat{L})\n", - "\\\\\n", - "& = 2 \\, \\mbox{tr} [\\mathbf{H}(\\lambda)] - 2 \\log\\{L[\\hat{\\beta}(\\lambda), \\hat{\\sigma}^2(\\lambda)]\\}\n", - "\\\\\n", - "& = 2 \\, \\sum_{j=1}^p \\frac{d_{jj}^2}{d_{jj}^2 + \\lambda}\n", - "+ 2 n \\, \\log[\\sqrt{2 \\, \\pi} \\, \\hat{\\sigma}(\\lambda)] + \\frac{1}{\\hat{\\sigma}^2(\\lambda)} \\sum_{i=1}^n [y_i - \\mathbf{X}_{i, \\ast} \\, \\hat{\\beta}(\\lambda)]^2.\n", + "\\langle x^n\\rangle \\equiv \\int\\! x^n p(x)\\,dx\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "The zero-th moment $\\langle 1\\rangle$ is just the normalization condition of\n", + "$p$. The first moment, $\\langle x\\rangle$, is called the *mean* of $p$\n", + "and often denoted by the letter $\\mu$:" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "$$\n", + "\\langle x\\rangle = \\mu \\equiv \\int\\! x p(x)\\,dx\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "A special version of the moments is the set of *central moments*,\n", + "the n-th central moment defined as:" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "$$\n", + "\\langle (x-\\langle x \\rangle )^n\\rangle \\equiv \\int\\! (x-\\langle x\\rangle)^n p(x)\\,dx\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "The zero-th and first central moments are both trivial, equal $1$ and\n", + "$0$, respectively. But the second central moment, known as the\n", + "*variance* of $p$, is of particular interest. For the stochastic\n", + "variable $X$, the variance is denoted as $\\sigma^2_X$ or $\\mathrm{var}(X)$:" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + "
\n", + "\n", + "$$\n", + "\\begin{equation}\n", + "\\sigma^2_X\\ \\ =\\ \\ \\mathrm{var}(X) = \\langle (x-\\langle x\\rangle)^2\\rangle =\n", + "\\int\\! (x-\\langle x\\rangle)^2 p(x)\\,dx\n", + "\\label{_auto8} \\tag{8}\n", + "\\end{equation}\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + "
\n", + "\n", + "$$\n", + "\\begin{equation} \n", + " = \\int\\! \\left(x^2 - 2 x \\langle x\\rangle^{2} +\n", + " \\langle x\\rangle^2\\right)p(x)\\,dx\n", + "\\label{_auto9} \\tag{9}\n", + "\\end{equation}\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + "
\n", + "\n", + "$$\n", + "\\begin{equation} \n", + " = \\langle x^2\\rangle - 2 \\langle x\\rangle\\langle x\\rangle + \\langle x\\rangle^2\n", + "\\label{_auto10} \\tag{10}\n", + "\\end{equation}\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + "
\n", + "\n", + "$$\n", + "\\begin{equation} \n", + " = \\langle x^2\\rangle - \\langle x\\rangle^2\n", + "\\label{_auto11} \\tag{11}\n", + "\\end{equation}\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "The square root of the variance, $\\sigma =\\sqrt{\\langle (x-\\langle x\\rangle)^2\\rangle}$ is called the *standard deviation* of $p$. It is clearly just the RMS (root-mean-square)\n", + "value of the deviation of the PDF from its mean value, interpreted\n", + "qualitatively as the *spread* of $p$ around its mean.\n", + "\n", + "\n", + "\n", + "## Statistics, covariance\n", + "\n", + "Another important quantity is the so called covariance, a variant of\n", + "the above defined variance. Consider again the set $\\{X_i\\}$ of $n$\n", + "stochastic variables (not necessarily uncorrelated) with the\n", + "multivariate PDF $P(x_1,\\dots,x_n)$. The *covariance* of two\n", + "of the stochastic variables, $X_i$ and $X_j$, is defined as follows:" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "$$\n", + "\\mathrm{cov}(X_i,\\,X_j) \\equiv \\langle (x_i-\\langle x_i\\rangle)(x_j-\\langle x_j\\rangle)\\rangle\n", + "\\nonumber\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + "
\n", + "\n", + "$$\n", + "\\begin{equation} \n", + "=\n", + "\\int\\!\\cdots\\!\\int\\!(x_i-\\langle x_i \\rangle)(x_j-\\langle x_j \\rangle)\\,\n", + "P(x_1,\\dots,x_n)\\,dx_1\\dots dx_n\n", + "\\label{eq:def_covariance} \\tag{12}\n", + "\\end{equation}\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "with" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "$$\n", + "\\langle x_i\\rangle =\n", + "\\int\\!\\cdots\\!\\int\\!x_i\\,P(x_1,\\dots,x_n)\\,dx_1\\dots dx_n\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "If we consider the above covariance as a matrix $C_{ij}=\\mathrm{cov}(X_i,\\,X_j)$, then the diagonal elements are just the familiar\n", + "variances, $C_{ii} = \\mathrm{cov}(X_i,\\,X_i) = \\mathrm{var}(X_i)$. It turns out that\n", + "all the off-diagonal elements are zero if the stochastic variables are\n", + "uncorrelated. This is easy to show, keeping in mind the linearity of\n", + "the expectation value. Consider the stochastic variables $X_i$ and\n", + "$X_j$, ($i\\neq j$):" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + "
\n", + "\n", + "$$\n", + "\\begin{equation}\n", + "\\mathrm{cov}(X_i,\\,X_j) = \\langle(x_i-\\langle x_i\\rangle)(x_j-\\langle x_j\\rangle)\\rangle\n", + "\\label{_auto12} \\tag{13}\n", + "\\end{equation}\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + "
\n", + "\n", + "$$\n", + "\\begin{equation} \n", + "=\\langle x_i x_j - x_i\\langle x_j\\rangle - \\langle x_i\\rangle x_j + \\langle x_i\\rangle\\langle x_j\\rangle\\rangle \n", + "\\label{_auto13} \\tag{14}\n", + "\\end{equation}\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + "
\n", + "\n", + "$$\n", + "\\begin{equation} \n", + "=\\langle x_i x_j\\rangle - \\langle x_i\\langle x_j\\rangle\\rangle - \\langle \\langle x_i\\rangle x_j\\rangle +\n", + "\\langle \\langle x_i\\rangle\\langle x_j\\rangle\\rangle\n", + "\\label{_auto14} \\tag{15}\n", + "\\end{equation}\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + "
\n", + "\n", + "$$\n", + "\\begin{equation} \n", + "=\\langle x_i x_j\\rangle - \\langle x_i\\rangle\\langle x_j\\rangle - \\langle x_i\\rangle\\langle x_j\\rangle +\n", + "\\langle x_i\\rangle\\langle x_j\\rangle\n", + "\\label{_auto15} \\tag{16}\n", + "\\end{equation}\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + "
\n", + "\n", + "$$\n", + "\\begin{equation} \n", + "=\\langle x_i x_j\\rangle - \\langle x_i\\rangle\\langle x_j\\rangle\n", + "\\label{_auto16} \\tag{17}\n", + "\\end{equation}\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Statistics, independent variables\n", + "\n", + "If $X_i$ and $X_j$ are independent, we get \n", + "$\\langle x_i x_j\\rangle =\\langle x_i\\rangle\\langle x_j\\rangle$, resulting in $\\mathrm{cov}(X_i, X_j) = 0\\ \\ (i\\neq j)$.\n", + "\n", + "Also useful for us is the covariance of linear combinations of\n", + "stochastic variables. Let $\\{X_i\\}$ and $\\{Y_i\\}$ be two sets of\n", + "stochastic variables. Let also $\\{a_i\\}$ and $\\{b_i\\}$ be two sets of\n", + "scalars. Consider the linear combination:" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "$$\n", + "U = \\sum_i a_i X_i \\qquad V = \\sum_j b_j Y_j\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "By the linearity of the expectation value" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "$$\n", + "\\mathrm{cov}(U, V) = \\sum_{i,j}a_i b_j \\mathrm{cov}(X_i, Y_j)\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Now, since the variance is just $\\mathrm{var}(X_i) = \\mathrm{cov}(X_i, X_i)$, we get\n", + "the variance of the linear combination $U = \\sum_i a_i X_i$:" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + "
\n", + "\n", + "$$\n", + "\\begin{equation}\n", + "\\mathrm{var}(U) = \\sum_{i,j}a_i a_j \\mathrm{cov}(X_i, X_j)\n", + "\\label{eq:variance_linear_combination} \\tag{18}\n", + "\\end{equation}\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "And in the special case when the stochastic variables are\n", + "uncorrelated, the off-diagonal elements of the covariance are as we\n", + "know zero, resulting in:" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "1\n", + "3\n", + "4\n", + " \n", + "<\n", + "<\n", + "<\n", + "!\n", + "!\n", + "M\n", + "A\n", + "T\n", + "H\n", + "_\n", + "B\n", + "L\n", + "O\n", + "C\n", + "K" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "$$\n", + "\\mathrm{var}(\\sum_i a_i X_i) = \\sum_i a_i^2 \\mathrm{var}(X_i)\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "which will become very useful in our study of the error in the mean\n", + "value of a set of measurements.\n", + "\n", + "## Statistics and stochastic processes\n", + "\n", + "A *stochastic process* is a process that produces sequentially a\n", + "chain of values:" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "$$\n", + "\\{x_1, x_2,\\dots\\,x_k,\\dots\\}.\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "We will call these\n", + "values our *measurements* and the entire set as our measured\n", + "*sample*. The action of measuring all the elements of a sample\n", + "we will call a stochastic *experiment* since, operationally,\n", + "they are often associated with results of empirical observation of\n", + "some physical or mathematical phenomena; precisely an experiment. We\n", + "assume that these values are distributed according to some \n", + "PDF $p_X^{\\phantom X}(x)$, where $X$ is just the formal symbol for the\n", + "stochastic variable whose PDF is $p_X^{\\phantom X}(x)$. Instead of\n", + "trying to determine the full distribution $p$ we are often only\n", + "interested in finding the few lowest moments, like the mean\n", + "$\\mu_X^{\\phantom X}$ and the variance $\\sigma_X^{\\phantom X}$.\n", + "\n", + "In practical situations a sample is always of finite size. Let that\n", + "size be $n$. The expectation value of a sample, the *sample mean*, is then defined as follows:" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "$$\n", + "\\bar{x}_n \\equiv \\frac{1}{n}\\sum_{k=1}^n x_k\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "The *sample variance* is:" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "$$\n", + "\\mathrm{var}(x) \\equiv \\frac{1}{n}\\sum_{k=1}^n (x_k - \\bar{x}_n)^2\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "its square root being the *standard deviation of the sample*. The\n", + "*sample covariance* is:" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "$$\n", + "\\mathrm{cov}(x)\\equiv\\frac{1}{n}\\sum_{kl}(x_k - \\bar{x}_n)(x_l - \\bar{x}_n)\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Note that the sample variance is the sample covariance without the\n", + "cross terms. In a similar manner as the covariance in Eq. ([12](#eq:def_covariance)) is a measure of the correlation between\n", + "two stochastic variables, the above defined sample covariance is a\n", + "measure of the sequential correlation between succeeding measurements\n", + "of a sample.\n", + "\n", + "These quantities, being known experimental values, differ\n", + "significantly from and must not be confused with the similarly named\n", + "quantities for stochastic variables, mean $\\mu_X$, variance $\\mathrm{var}(X)$\n", + "and covariance $\\mathrm{cov}(X,Y)$.\n", + "\n", + "The law of large numbers\n", + "states that as the size of our sample grows to infinity, the sample\n", + "mean approaches the true mean $\\mu_X^{\\phantom X}$ of the chosen PDF:" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "$$\n", + "\\lim_{n\\to\\infty}\\bar{x}_n = \\mu_X^{\\phantom X}\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "The sample mean $\\bar{x}_n$ works therefore as an estimate of the true\n", + "mean $\\mu_X^{\\phantom X}$.\n", + "\n", + "What we need to find out is how good an approximation $\\bar{x}_n$ is to\n", + "$\\mu_X^{\\phantom X}$. In any stochastic measurement, an estimated\n", + "mean is of no use to us without a measure of its error. A quantity\n", + "that tells us how well we can reproduce it in another experiment. We\n", + "are therefore interested in the PDF of the sample mean itself. Its\n", + "standard deviation will be a measure of the spread of sample means,\n", + "and we will simply call it the *error* of the sample mean, or\n", + "just sample error, and denote it by $\\mathrm{err}_X^{\\phantom X}$. In\n", + "practice, we will only be able to produce an *estimate* of the\n", + "sample error since the exact value would require the knowledge of the\n", + "true PDFs behind, which we usually do not have.\n", + "\n", + "## Statistics, more on sample error\n", + "\n", + "Let us first take a look at what happens to the sample error as the\n", + "size of the sample grows. In a sample, each of the measurements $x_i$\n", + "can be associated with its own stochastic variable $X_i$. The\n", + "stochastic variable $\\overline X_n$ for the sample mean $\\bar{x}_n$ is\n", + "then just a linear combination, already familiar to us:" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "$$\n", + "\\overline X_n = \\frac{1}{n}\\sum_{i=1}^n X_i\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "All the coefficients are just equal $1/n$. The PDF of $\\overline X_n$,\n", + "denoted by $p_{\\overline X_n}(x)$ is the desired PDF of the sample\n", + "means. \n", + "\n", + "The probability density of obtaining a sample mean $\\bar x_n$\n", + "is the product of probabilities of obtaining arbitrary values $x_1,\n", + "x_2,\\dots,x_n$ with the constraint that the mean of the set $\\{x_i\\}$\n", + "is $\\bar x_n$:" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "$$\n", + "p_{\\overline X_n}(x) = \\int p_X^{\\phantom X}(x_1)\\cdots\n", + "\\int p_X^{\\phantom X}(x_n)\\ \n", + "\\delta\\!\\left(x - \\frac{x_1+x_2+\\dots+x_n}{n}\\right)dx_n \\cdots dx_1\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "And in particular we are interested in its variance $\\mathrm{var}(\\overline X_n)$.\n", + "\n", + "## Statistics, central limit theorem\n", + "\n", + "It is generally not possible to express $p_{\\overline X_n}(x)$ in a\n", + "closed form given an arbitrary PDF $p_X^{\\phantom X}$ and a number\n", + "$n$. But for the limit $n\\to\\infty$ it is possible to make an\n", + "approximation. The very important result is called *the central limit theorem*. It tells us that as $n$ goes to infinity,\n", + "$p_{\\overline X_n}(x)$ approaches a Gaussian distribution whose mean\n", + "and variance equal the true mean and variance, $\\mu_{X}^{\\phantom X}$\n", + "and $\\sigma_{X}^{2}$, respectively:" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + "
\n", + "\n", + "$$\n", + "\\begin{equation}\n", + "\\lim_{n\\to\\infty} p_{\\overline X_n}(x) =\n", + "\\left(\\frac{n}{2\\pi\\mathrm{var}(X)}\\right)^{1/2}\n", + "e^{-\\frac{n(x-\\bar x_n)^2}{2\\mathrm{var}(X)}}\n", + "\\label{eq:central_limit_gaussian} \\tag{19}\n", + "\\end{equation}\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "The desired variance\n", + "$\\mathrm{var}(\\overline X_n)$, i.e. the sample error squared\n", + "$\\mathrm{err}_X^2$, is given by:" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + "
\n", + "\n", + "$$\n", + "\\begin{equation}\n", + "\\mathrm{err}_X^2 = \\mathrm{var}(\\overline X_n) = \\frac{1}{n^2}\n", + "\\sum_{ij} \\mathrm{cov}(X_i, X_j)\n", + "\\label{eq:error_exact} \\tag{20}\n", + "\\end{equation}\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "We see now that in order to calculate the exact error of the sample\n", + "with the above expression, we would need the true means\n", + "$\\mu_{X_i}^{\\phantom X}$ of the stochastic variables $X_i$. To\n", + "calculate these requires that we know the true multivariate PDF of all\n", + "the $X_i$. But this PDF is unknown to us, we have only got the measurements of\n", + "one sample. The best we can do is to let the sample itself be an\n", + "estimate of the PDF of each of the $X_i$, estimating all properties of\n", + "$X_i$ through the measurements of the sample.\n", + "\n", + "Our estimate of $\\mu_{X_i}^{\\phantom X}$ is then the sample mean $\\bar x$\n", + "itself, in accordance with the the central limit theorem:" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "$$\n", + "\\mu_{X_i}^{\\phantom X} = \\langle x_i\\rangle \\approx \\frac{1}{n}\\sum_{k=1}^n x_k = \\bar x\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Using $\\bar x$ in place of $\\mu_{X_i}^{\\phantom X}$ we can give an\n", + "*estimate* of the covariance in Eq. ([20](#eq:error_exact))" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "$$\n", + "\\mathrm{cov}(X_i, X_j) = \\langle (x_i-\\langle x_i\\rangle)(x_j-\\langle x_j\\rangle)\\rangle\n", + "\\approx\\langle (x_i - \\bar x)(x_j - \\bar{x})\\rangle,\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "resulting in" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "$$\n", + "\\frac{1}{n} \\sum_{l}^n \\left(\\frac{1}{n}\\sum_{k}^n (x_k -\\bar x_n)(x_l - \\bar x_n)\\right)=\\frac{1}{n}\\frac{1}{n} \\sum_{kl} (x_k -\\bar x_n)(x_l - \\bar x_n)=\\frac{1}{n}\\mathrm{cov}(x)\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "By the same procedure we can use the sample variance as an\n", + "estimate of the variance of any of the stochastic variables $X_i$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "$$\n", + "\\mathrm{var}(X_i)=\\langle x_i - \\langle x_i\\rangle\\rangle \\approx \\langle x_i - \\bar x_n\\rangle\\nonumber,\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "which is approximated as" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + "
\n", + "\n", + "$$\n", + "\\begin{equation}\n", + "\\mathrm{var}(X_i)\\approx \\frac{1}{n}\\sum_{k=1}^n (x_k - \\bar x_n)=\\mathrm{var}(x)\n", + "\\label{eq:var_estimate_i_think} \\tag{21}\n", + "\\end{equation}\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Now we can calculate an estimate of the error\n", + "$\\mathrm{err}_X^{\\phantom X}$ of the sample mean $\\bar x_n$:" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "$$\n", + "\\mathrm{err}_X^2\n", + "=\\frac{1}{n^2}\\sum_{ij} \\mathrm{cov}(X_i, X_j) \\nonumber\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "$$\n", + "\\approx\\frac{1}{n^2}\\sum_{ij}\\frac{1}{n}\\mathrm{cov}(x) =\\frac{1}{n^2}n^2\\frac{1}{n}\\mathrm{cov}(x)\\nonumber\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + "
\n", + "\n", + "$$\n", + "\\begin{equation} \n", + "=\\frac{1}{n}\\mathrm{cov}(x)\n", + "\\label{eq:error_estimate} \\tag{22}\n", + "\\end{equation}\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "which is nothing but the sample covariance divided by the number of\n", + "measurements in the sample.\n", + "\n", + "In the special case that the measurements of the sample are\n", + "uncorrelated (equivalently the stochastic variables $X_i$ are\n", + "uncorrelated) we have that the off-diagonal elements of the covariance\n", + "are zero. This gives the following estimate of the sample error:" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "$$\n", + "\\mathrm{err}_X^2=\\frac{1}{n^2}\\sum_{ij} \\mathrm{cov}(X_i, X_j) =\n", + "\\frac{1}{n^2} \\sum_i \\mathrm{var}(X_i),\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "resulting in" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + "
\n", + "\n", + "$$\n", + "\\begin{equation}\n", + "\\mathrm{err}_X^2\\approx \\frac{1}{n^2} \\sum_i \\mathrm{var}(x)= \\frac{1}{n}\\mathrm{var}(x)\n", + "\\label{eq:error_estimate_uncorrel} \\tag{23}\n", + "\\end{equation}\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "where in the second step we have used Eq. ([21](#eq:var_estimate_i_think)).\n", + "The error of the sample is then just its standard deviation divided by\n", + "the square root of the number of measurements the sample contains.\n", + "This is a very useful formula which is easy to compute. It acts as a\n", + "first approximation to the error, but in numerical experiments, we\n", + "cannot overlook the always present correlations.\n", + "\n", + "For computational purposes one usually splits up the estimate of\n", + "$\\mathrm{err}_X^2$, given by Eq. ([22](#eq:error_estimate)), into two\n", + "parts" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "$$\n", + "\\mathrm{err}_X^2 = \\frac{1}{n}\\mathrm{var}(x) + \\frac{1}{n}(\\mathrm{cov}(x)-\\mathrm{var}(x)),\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "which equals" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + "
\n", + "\n", + "$$\n", + "\\begin{equation}\n", + "\\frac{1}{n^2}\\sum_{k=1}^n (x_k - \\bar x_n)^2 +\\frac{2}{n^2}\\sum_{k\n", + "
\n", + "\n", + "$$\n", + "\\begin{equation} \n", + "=\\frac{\\tau}{n}\\cdot\\mathrm{var}(x)\n", + "\\label{eq:error_estimate_corr_time} \\tag{25}\n", + "\\end{equation}\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "and we see that $\\mathrm{err}_X$ can be expressed in terms the\n", + "uncorrelated sample variance times a correction factor $\\tau$ which\n", + "accounts for the correlation between measurements. We call this\n", + "correction factor the *autocorrelation time*:" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + "
\n", + "\n", + "$$\n", + "\\begin{equation}\n", + "\\tau = 1+2\\sum_{d=1}^{n-1}\\kappa_d\n", + "\\label{eq:autocorrelation_time} \\tag{26}\n", + "\\end{equation}\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "For a correlation free experiment, $\\tau$\n", + "equals 1. From the point of view of\n", + "eq. ([25](#eq:error_estimate_corr_time)) we can interpret a sequential\n", + "correlation as an effective reduction of the number of measurements by\n", + "a factor $\\tau$. The effective number of measurements becomes:" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "$$\n", + "n_\\mathrm{eff} = \\frac{n}{\\tau}\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "To neglect the autocorrelation time $\\tau$ will always cause our\n", + "simple uncorrelated estimate of $\\mathrm{err}_X^2\\approx \\mathrm{var}(x)/n$ to\n", + "be less than the true sample error. The estimate of the error will be\n", + "too *good*. On the other hand, the calculation of the full\n", + "autocorrelation time poses an efficiency problem if the set of\n", + "measurements is very large.\n", + "\n", + "## Linking the regression analysis with a statistical interpretation\n", + "\n", + "Finally, we are going to discuss several statistical properties which can be obtained in terms of analytical expressions. \n", + "The\n", + "advantage of doing linear regression is that we actually end up with\n", + "analytical expressions for several statistical quantities. \n", + "Standard least squares and Ridge regression allow us to\n", + "derive quantities like the variance and other expectation values in a\n", + "rather straightforward way.\n", + "\n", + "\n", + "It is assumed that $\\varepsilon_i\n", + "\\sim \\mathcal{N}(0, \\sigma^2)$ and the $\\varepsilon_{i}$ are\n", + "independent, i.e.:" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "$$\n", + "\\begin{align*} \n", + "\\mbox{Cov}(\\varepsilon_{i_1},\n", + "\\varepsilon_{i_2}) & = \\left\\{ \\begin{array}{lcc} \\sigma^2 & \\mbox{if}\n", + "& i_1 = i_2, \\\\ 0 & \\mbox{if} & i_1 \\not= i_2. \\end{array} \\right.\n", "\\end{align*}\n", "$$" ] @@ -9139,8 +6125,234 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "The value of $\\lambda$ which minimizes $\\mbox{AIC}(\\lambda)$ corresponds to the `optimal' balance of model complexity and overfitting.\n", + "The randomness of $\\varepsilon_i$ implies that\n", + "$\\mathbf{y}_i$ is also a random variable. In particular,\n", + "$\\mathbf{y}_i$ is normally distributed, because $\\varepsilon_i \\sim\n", + "\\mathcal{N}(0, \\sigma^2)$ and $\\mathbf{X}_{i,\\ast} \\, \\boldsymbol{\\beta}$ is a\n", + "non-random scalar. To specify the parameters of the distribution of\n", + "$\\mathbf{y}_i$ we need to calculate its first two moments. \n", "\n", + "Recall that $\\boldsymbol{X}$ is a matrix of dimensionality $n\\times p$. The\n", + "notation above $\\mathbf{X}_{i,\\ast}$ means that we are looking at the\n", + "row number $i$ and perform a sum over all values $p$.\n", + "\n", + "\n", + "## Assumptions made\n", + "\n", + "The assumption we have made here can be summarized as (and this is going to useful when we discuss the bias-variance trade off)\n", + "that there exists a function $f(\\boldsymbol{x})$ and a normal distributed error $\\boldsymbol{\\varepsilon}\\sim \\mathcal{N}(0, \\sigma^2)$\n", + "which describes our data" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "$$\n", + "\\boldsymbol{y} = f(\\boldsymbol{x})+\\boldsymbol{\\varepsilon}\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "We approximate this function with our model from the solution of the linear regression equations, that is our\n", + "function $f$ is approximated by $\\boldsymbol{\\tilde{y}}$ where we want to minimize $(\\boldsymbol{y}-\\boldsymbol{\\tilde{y}})^2$, our MSE, with" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "$$\n", + "\\boldsymbol{\\tilde{y}} = \\boldsymbol{X}\\boldsymbol{\\beta}.\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "We can calculate the expectation value of $\\boldsymbol{y}$ for a given element $i$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "$$\n", + "\\begin{align*} \n", + "\\mathbb{E}(y_i) & =\n", + "\\mathbb{E}(\\mathbf{X}_{i, \\ast} \\, \\boldsymbol{\\beta}) + \\mathbb{E}(\\varepsilon_i)\n", + "\\, \\, \\, = \\, \\, \\, \\mathbf{X}_{i, \\ast} \\, \\beta, \n", + "\\end{align*}\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "while\n", + "its variance is" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "$$\n", + "\\begin{align*} \\mbox{Var}(y_i) & = \\mathbb{E} \\{ [y_i\n", + "- \\mathbb{E}(y_i)]^2 \\} \\, \\, \\, = \\, \\, \\, \\mathbb{E} ( y_i^2 ) -\n", + "[\\mathbb{E}(y_i)]^2 \\\\ & = \\mathbb{E} [ ( \\mathbf{X}_{i, \\ast} \\,\n", + "\\beta + \\varepsilon_i )^2] - ( \\mathbf{X}_{i, \\ast} \\, \\boldsymbol{\\beta})^2 \\\\ &\n", + "= \\mathbb{E} [ ( \\mathbf{X}_{i, \\ast} \\, \\boldsymbol{\\beta})^2 + 2 \\varepsilon_i\n", + "\\mathbf{X}_{i, \\ast} \\, \\boldsymbol{\\beta} + \\varepsilon_i^2 ] - ( \\mathbf{X}_{i,\n", + "\\ast} \\, \\beta)^2 \\\\ & = ( \\mathbf{X}_{i, \\ast} \\, \\boldsymbol{\\beta})^2 + 2\n", + "\\mathbb{E}(\\varepsilon_i) \\mathbf{X}_{i, \\ast} \\, \\boldsymbol{\\beta} +\n", + "\\mathbb{E}(\\varepsilon_i^2 ) - ( \\mathbf{X}_{i, \\ast} \\, \\boldsymbol{\\beta})^2 \n", + "\\\\ & = \\mathbb{E}(\\varepsilon_i^2 ) \\, \\, \\, = \\, \\, \\,\n", + "\\mbox{Var}(\\varepsilon_i) \\, \\, \\, = \\, \\, \\, \\sigma^2. \n", + "\\end{align*}\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Hence, $y_i \\sim \\mathcal{N}( \\mathbf{X}_{i, \\ast} \\, \\boldsymbol{\\beta}, \\sigma^2)$, that is $\\boldsymbol{y}$ follows a normal distribution with \n", + "mean value $\\boldsymbol{X}\\boldsymbol{\\beta}$ and variance $\\sigma^2$ (not be confused with the singular values of the SVD). \n", + "\n", + "\n", + "## Expectation value and variance for $\\boldsymbol{\\beta}$\n", + "\n", + "With the OLS expressions for the parameters $\\boldsymbol{\\beta}$ we can evaluate the expectation value" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "$$\n", + "\\mathbb{E}(\\boldsymbol{\\beta}) = \\mathbb{E}[ (\\mathbf{X}^{\\top} \\mathbf{X})^{-1}\\mathbf{X}^{T} \\mathbf{Y}]=(\\mathbf{X}^{T} \\mathbf{X})^{-1}\\mathbf{X}^{T} \\mathbb{E}[ \\mathbf{Y}]=(\\mathbf{X}^{T} \\mathbf{X})^{-1} \\mathbf{X}^{T}\\mathbf{X}\\boldsymbol{\\beta}=\\boldsymbol{\\beta}.\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "This means that the estimator of the regression parameters is unbiased.\n", + "\n", + "We can also calculate the variance\n", + "\n", + "The variance of $\\boldsymbol{\\beta}$ is" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "$$\n", + "\\begin{eqnarray*}\n", + "\\mbox{Var}(\\boldsymbol{\\beta}) & = & \\mathbb{E} \\{ [\\boldsymbol{\\beta} - \\mathbb{E}(\\boldsymbol{\\beta})] [\\boldsymbol{\\beta} - \\mathbb{E}(\\boldsymbol{\\beta})]^{T} \\}\n", + "\\\\\n", + "& = & \\mathbb{E} \\{ [(\\mathbf{X}^{T} \\mathbf{X})^{-1} \\, \\mathbf{X}^{T} \\mathbf{Y} - \\boldsymbol{\\beta}] \\, [(\\mathbf{X}^{T} \\mathbf{X})^{-1} \\, \\mathbf{X}^{T} \\mathbf{Y} - \\boldsymbol{\\beta}]^{T} \\}\n", + "\\\\\n", + "% & = & \\mathbb{E} \\{ [(\\mathbf{X}^{T} \\mathbf{X})^{-1} \\, \\mathbf{X}^{T} \\mathbf{Y}] \\, [(\\mathbf{X}^{T} \\mathbf{X})^{-1} \\, \\mathbf{X}^{T} \\mathbf{Y}]^{T} \\} - \\boldsymbol{\\beta} \\, \\boldsymbol{\\beta}^{T}\n", + "% \\\\\n", + "% & = & \\mathbb{E} \\{ (\\mathbf{X}^{T} \\mathbf{X})^{-1} \\, \\mathbf{X}^{T} \\mathbf{Y} \\, \\mathbf{Y}^{T} \\, \\mathbf{X} \\, (\\mathbf{X}^{T} \\mathbf{X})^{-1} \\} - \\boldsymbol{\\beta} \\, \\boldsymbol{\\beta}^{T}\n", + "% \\\\\n", + "& = & (\\mathbf{X}^{T} \\mathbf{X})^{-1} \\, \\mathbf{X}^{T} \\, \\mathbb{E} \\{ \\mathbf{Y} \\, \\mathbf{Y}^{T} \\} \\, \\mathbf{X} \\, (\\mathbf{X}^{T} \\mathbf{X})^{-1} - \\boldsymbol{\\beta} \\, \\boldsymbol{\\beta}^{T}\n", + "\\\\\n", + "& = & (\\mathbf{X}^{T} \\mathbf{X})^{-1} \\, \\mathbf{X}^{T} \\, \\{ \\mathbf{X} \\, \\boldsymbol{\\beta} \\, \\boldsymbol{\\beta}^{T} \\, \\mathbf{X}^{T} + \\sigma^2 \\} \\, \\mathbf{X} \\, (\\mathbf{X}^{T} \\mathbf{X})^{-1} - \\boldsymbol{\\beta} \\, \\boldsymbol{\\beta}^{T}\n", + "% \\\\\n", + "% & = & (\\mathbf{X}^T \\mathbf{X})^{-1} \\, \\mathbf{X}^T \\, \\mathbf{X} \\, \\boldsymbol{\\beta} \\, \\boldsymbol{\\beta}^T \\, \\mathbf{X}^T \\, \\mathbf{X} \\, (\\mathbf{X}^T % \\mathbf{X})^{-1}\n", + "% \\\\\n", + "% & & + \\, \\, \\sigma^2 \\, (\\mathbf{X}^T \\mathbf{X})^{-1} \\, \\mathbf{X}^T \\, \\mathbf{X} \\, (\\mathbf{X}^T \\mathbf{X})^{-1} - \\boldsymbol{\\beta} \\boldsymbol{\\beta}^T\n", + "\\\\\n", + "& = & \\boldsymbol{\\beta} \\, \\boldsymbol{\\beta}^{T} + \\sigma^2 \\, (\\mathbf{X}^{T} \\mathbf{X})^{-1} - \\boldsymbol{\\beta} \\, \\boldsymbol{\\beta}^{T}\n", + "\\, \\, \\, = \\, \\, \\, \\sigma^2 \\, (\\mathbf{X}^{T} \\mathbf{X})^{-1},\n", + "\\end{eqnarray*}\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "where we have used that $\\mathbb{E} (\\mathbf{Y} \\mathbf{Y}^{T}) =\n", + "\\mathbf{X} \\, \\boldsymbol{\\beta} \\, \\boldsymbol{\\beta}^{T} \\, \\mathbf{X}^{T} +\n", + "\\sigma^2 \\, \\mathbf{I}_{nn}$. From $\\mbox{Var}(\\boldsymbol{\\beta}) = \\sigma^2\n", + "\\, (\\mathbf{X}^{T} \\mathbf{X})^{-1}$, one obtains an estimate of the\n", + "variance of the estimate of the $j$-th regression coefficient:\n", + "$\\hat{\\sigma}^2 (\\hat{\\beta}_j ) = \\hat{\\sigma}^2 \\sqrt{\n", + "[(\\mathbf{X}^{T} \\mathbf{X})^{-1}]_{jj} }$. This may be used to\n", + "construct a confidence interval for the estimates.\n", + "\n", + "\n", + "In a similar way, we cna obtain analytical expressions for say the\n", + "expectation values of the parameters $\\boldsymbol{\\beta}$ and their variance\n", + "when we employ Ridge regression, and thereby a confidence interval. \n", + "\n", + "It is rather straightforward to show that" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "$$\n", + "\\mathbb{E} \\big[ \\boldsymbol{\\beta}^{\\mathrm{Ridge}} \\big]=(\\mathbf{X}^{T} \\mathbf{X} + \\lambda \\mathbf{I}_{pp})^{-1} (\\mathbf{X}^{\\top} \\mathbf{X})\\boldsymbol{\\beta}^{\\mathrm{OLS}}.\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "We see clearly that \n", + "$\\mathbb{E} \\big[ \\boldsymbol{\\beta}^{\\mathrm{Ridge}} \\big] \\not= \\boldsymbol{\\beta}^{\\mathrm{OLS}}$ for any $\\lambda > 0$. We say then that the ridge estimator is biased.\n", + "\n", + "We can also compute the variance as" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "$$\n", + "\\mbox{Var}[\\boldsymbol{\\beta}^{\\mathrm{Ridge}}]=\\sigma^2[ \\mathbf{X}^{T} \\mathbf{X} + \\lambda \\mathbf{I} ]^{-1} \\mathbf{X}^{T} \\mathbf{X} \\{ [ \\mathbf{X}^{\\top} \\mathbf{X} + \\lambda \\mathbf{I} ]^{-1}\\}^{T},\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "and it is easy to see that if the parameter $\\lambda$ goes to infinity then the variance of Ridge parameters $\\boldsymbol{\\beta}$ goes to zero. \n", + "\n", + "With this, we can compute the difference" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "$$\n", + "\\mbox{Var}[\\boldsymbol{\\beta}^{\\mathrm{OLS}}]-\\mbox{Var}(\\boldsymbol{\\beta}^{\\mathrm{Ridge}})=\\sigma^2 [ \\mathbf{X}^{T} \\mathbf{X} + \\lambda \\mathbf{I} ]^{-1}[ 2\\lambda\\mathbf{I} + \\lambda^2 (\\mathbf{X}^{T} \\mathbf{X})^{-1} ] \\{ [ \\mathbf{X}^{T} \\mathbf{X} + \\lambda \\mathbf{I} ]^{-1}\\}^{T}.\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "The difference is non-negative definite since each component of the\n", + "matrix product is non-negative definite. \n", + "This means the variance we obtain with the standard OLS will always for $\\lambda > 0$ be larger than the variance of $\\boldsymbol{\\beta}$ obtained with the Ridge estimator. This has interesting consequences when we discuss the so-called bias-variance trade-off below. \n", "\n", "\n", "## Cross-validation\n", @@ -9150,12 +6362,14 @@ "parameter) to yield a model with good prediction\n", "performance. Commonly, this performance is evaluated on novel\n", "data. Novel data need not be easy to come by and one has to make do\n", - "with the data at hand. The setting of `original' and novel data is\n", + "with the data at hand.\n", + "\n", + "The setting of **original** and novel data is\n", "then mimicked by sample splitting: the data set is divided into two\n", - "(groups of samples). One of these two data sets, called the *training\n", - "set*, plays the role of `original' data on which the model is\n", + "(groups of samples). One of these two data sets, called the \n", + "*training set*, plays the role of **original** data on which the model is\n", "built. The second of these data sets, called the *test set*, plays the\n", - "role of the `novel' data and is used to evaluate the prediction\n", + "role of the **novel** data and is used to evaluate the prediction\n", "performance (often operationalized as the log-likelihood or the\n", "prediction error or its square or the R2 score) of the model built on the training data set. This\n", "procedure (model building and prediction evaluation on training and\n", @@ -9204,7 +6418,7 @@ "\n", "* Divide the data set into training and test set comprising samples $\\{1, \\ldots, n\\} \\setminus i$ and $\\{ i \\}$, respectively.\n", "\n", - "* Fit the linear regression model by means of ridge estimation for each $\\lambda$ in the grid using the training set, and the corresponding estimate of the error variance $\\hat{\\sigma}_{-i}^2(\\lambda)$, as" + "* Fit the linear regression model by means of ridge estimation for each $\\lambda$ in the grid using the training set, and the corresponding estimate of the error variance $\\boldsymbol{\\sigma}_{-i}^2(\\lambda)$, as" ] }, { @@ -9213,9 +6427,9 @@ "source": [ "$$\n", "\\begin{align*}\n", - "\\hat{\\beta}_{-i}(\\lambda) & = ( \\hat{X}_{-i, \\ast}^{\\top}\n", - "\\hat{X}_{-i, \\ast} + \\lambda \\hat{I}_{pp})^{-1}\n", - "\\hat{X}_{-i, \\ast}^{\\top} \\hat{y}_{-i}\n", + "\\boldsymbol{\\beta}_{-i}(\\lambda) & = ( \\boldsymbol{X}_{-i, \\ast}^{T}\n", + "\\boldsymbol{X}_{-i, \\ast} + \\lambda \\boldsymbol{I}_{pp})^{-1}\n", + "\\boldsymbol{X}_{-i, \\ast}^{T} \\boldsymbol{y}_{-i}\n", "\\end{align*}\n", "$$" ] @@ -9224,7 +6438,7 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "* Evaluate the prediction performance of these models on the test set by $\\log\\{L[y_i, \\hat{X}_{i, \\ast}; \\hat{\\beta}_{-i}(\\lambda), \\hat{\\sigma}_{-i}^2(\\lambda)]\\}$. Or, by the prediction error $|y_i - \\hat{X}_{i, \\ast} \\hat{\\beta}_{-i}(\\lambda)|$, the relative error, the error squared or the R2 score function.\n", + "* Evaluate the prediction performance of these models on the test set by $\\log\\{L[y_i, \\boldsymbol{X}_{i, \\ast}; \\boldsymbol{\\beta}_{-i}(\\lambda), \\boldsymbol{\\sigma}_{-i}^2(\\lambda)]\\}$. Or, by the prediction error $|y_i - \\boldsymbol{X}_{i, \\ast} \\boldsymbol{\\beta}_{-i}(\\lambda)|$, the relative error, the error squared or the R2 score function.\n", "\n", "* Repeat the first three steps such that each sample plays the role of the test set once.\n", "\n", @@ -9237,7 +6451,7 @@ "source": [ "$$\n", "\\begin{align*}\n", - "\\frac{1}{n} \\sum_{i = 1}^n \\log\\{L[y_i, \\mathbf{X}_{i, \\ast}; \\hat{\\beta}_{-i}(\\lambda), \\hat{\\sigma}_{-i}^2(\\lambda)]\\}.\n", + "\\frac{1}{n} \\sum_{i = 1}^n \\log\\{L[y_i, \\mathbf{X}_{i, \\ast}; \\boldsymbol{\\beta}_{-i}(\\lambda), \\boldsymbol{\\sigma}_{-i}^2(\\lambda)]\\}.\n", "\\end{align*}\n", "$$" ] @@ -9248,35 +6462,6 @@ "source": [ "* The value of the penalty parameter that maximizes the cross-validated log-likelihood is the value of choice. Or we can use the MSE or the R2 score functions.\n", "\n", - "## Predicted Residual Error Sum of Squares\n", - "\n", - "Another approach in the LOOCV scheme is to the use the so-called Predicted Residual Error Sum of Squares (PRESS). \n", - "\n", - "We can define the optimal penalty parameter to minimize" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "\\begin{align*}\n", - "\\lambda_{\\mbox{{\\tiny opt}}} = \\arg \\min_{\\lambda} \\frac{1}{n} \\sum_{i=1}^n [y_i - \\hat{X}_{i, \\ast} \\hat{\\beta}_{-i}(\\lambda)]^2.\n", - "\\end{align*}\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "The LOOCV prediction performance can be\n", - "expressed analytically in terms of the known quantities derived from\n", - "the design matrix and the parameters $\\beta$.\n", - "\n", - "\n", - "\n", - "\n", "## Resampling methods: Jackknife and Bootstrap\n", "\n", "Two famous\n", @@ -9298,8 +6483,8 @@ "## Resampling methods: Jackknife\n", "\n", "The Jackknife works by making many replicas of the estimator $\\widehat{\\theta}$. \n", - "The jackknife is a resampling method, we explained that this happens by scrambling the data in some way. When using the jackknife, this is done by systematically leaving out one observation from the vector of observed values $\\hat{x} = (x_1,x_2,\\cdots,X_n)$. \n", - "Let $\\hat{x}_i$ denote the vector" + "The jackknife is a resampling method where we systematically leave out one observation from the vector of observed values $\\boldsymbol{x} = (x_1,x_2,\\cdots,X_n)$. \n", + "Let $\\boldsymbol{x}_i$ denote the vector" ] }, { @@ -9307,7 +6492,7 @@ "metadata": {}, "source": [ "$$\n", - "\\hat{x}_i = (x_1,x_2,\\cdots,x_{i-1},x_{i+1},\\cdots,x_n),\n", + "\\boldsymbol{x}_i = (x_1,x_2,\\cdots,x_{i-1},x_{i+1},\\cdots,x_n),\n", "$$" ] }, @@ -9315,38 +6500,19 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "which equals the vector $\\hat{x}$ with the exception that observation\n", + "which equals the vector $\\boldsymbol{x}$ with the exception that observation\n", "number $i$ is left out. Using this notation, define\n", "$\\widehat{\\theta}_i$ to be the estimator\n", "$\\widehat{\\theta}$ computed using $\\vec{X}_i$. \n", "\n", "\n", - "## Resampling methods: Jackknife estimator\n", "\n", - "To get an estimate for the bias and\n", - "standard error of $\\widehat{\\theta}$, use the following\n", - "estimators for each component of $\\widehat{\\theta}$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "\\widehat{\\mathrm{Bias}}(\\widehat \\theta,\\theta) = (n-1)\\left( - \\widehat{\\theta} + \\frac{1}{n}\\sum_{i=1}^{n} \\widehat \\theta_i \\right) \\qquad \\text{and} \\qquad \\widehat{\\sigma}^2_{\\widehat{\\theta} } = \\frac{n-1}{n}\\sum_{i=1}^{n}( \\widehat{\\theta}_i - \\frac{1}{n}\\sum_{j=1}^{n}\\widehat \\theta_j )^2.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ "## Jackknife code example" ] }, { "cell_type": "code", - "execution_count": 47, + "execution_count": 56, "metadata": { "collapsed": false }, @@ -9402,14 +6568,14 @@ "\n", "## Resampling methods: Bootstrap background\n", "\n", - "Since $\\widehat{\\theta} = \\widehat{\\theta}(\\hat{X})$ is a function of random variables,\n", + "Since $\\widehat{\\theta} = \\widehat{\\theta}(\\boldsymbol{X})$ is a function of random variables,\n", "$\\widehat{\\theta}$ itself must be a random variable. Thus it has\n", - "a pdf, call this function $p(\\hat{t})$. The aim of the bootstrap is to\n", - "estimate $p(\\hat{t})$ by the relative frequency of\n", + "a pdf, call this function $p(\\boldsymbol{t})$. The aim of the bootstrap is to\n", + "estimate $p(\\boldsymbol{t})$ by the relative frequency of\n", "$\\widehat{\\theta}$. You can think of this as using a histogram\n", - "in the place of $p(\\hat{t})$. If the relative frequency closely\n", + "in the place of $p(\\boldsymbol{t})$. If the relative frequency closely\n", "resembles $p(\\vec{t})$, then using numerics, it is straight forward to\n", - "estimate all the interesting parameters of $p(\\hat{t})$ using point\n", + "estimate all the interesting parameters of $p(\\boldsymbol{t})$ using point\n", "estimators. \n", "\n", "\n", @@ -9428,7 +6594,7 @@ "By repeated use of (1) and (2), many\n", "estimates of $\\widehat{\\theta}$ could have been obtained. The\n", "idea is to use the relative frequency of $\\widehat{\\theta}^*$\n", - "(think of a histogram) as an estimate of $p(\\hat{t})$.\n", + "(think of a histogram) as an estimate of $p(\\boldsymbol{t})$.\n", "\n", "\n", "## Resampling methods: Bootstrap approach\n", @@ -9446,32 +6612,52 @@ "Instead of generating the histogram for the relative\n", "frequency of the observation $X_i$, just draw the values\n", "$(X_1^*,X_2^*,\\cdots,X_n^*)$ with replacement from the vector\n", - "$\\hat{X}$. \n", + "$\\boldsymbol{X}$. \n", "\n", "\n", "## Resampling methods: Bootstrap steps\n", "\n", "The independent bootstrap works like this: \n", "\n", - "1. Draw with replacement $n$ numbers for the observed variables $\\hat{x} = (x_1,x_2,\\cdots,x_n)$. \n", + "1. Draw with replacement $n$ numbers for the observed variables $\\boldsymbol{x} = (x_1,x_2,\\cdots,x_n)$. \n", "\n", - "2. Define a vector $\\hat{x}^*$ containing the values which were drawn from $\\hat{x}$. \n", + "2. Define a vector $\\boldsymbol{x}^*$ containing the values which were drawn from $\\boldsymbol{x}$. \n", "\n", - "3. Using the vector $\\hat{x}^*$ compute $\\widehat{\\theta}^*$ by evaluating $\\widehat \\theta$ under the observations $\\hat{x}^*$. \n", + "3. Using the vector $\\boldsymbol{x}^*$ compute $\\widehat{\\theta}^*$ by evaluating $\\widehat \\theta$ under the observations $\\boldsymbol{x}^*$. \n", "\n", "4. Repeat this process $k$ times. \n", "\n", - "When you are done, you can draw a histogram of the relative frequency of $\\widehat \\theta^*$. This is your estimate of the probability distribution $p(t)$. Using this probability distribution you can estimate any statistics thereof. In principle you never draw the histogram of the relative frequency of $\\widehat{\\theta}^*$. Instead you use the estimators corresponding to the statistic of interest. For example, if you are interested in estimating the variance of $\\widehat \\theta$, apply the etsimator $\\widehat \\sigma^2$ to the values $\\widehat \\theta ^*$.\n", + "When you are done, you can draw a histogram of the relative frequency\n", + "of $\\widehat \\theta^*$. This is your estimate of the probability\n", + "distribution $p(t)$. Using this probability distribution you can\n", + "estimate any statistics thereof. In principle you never draw the\n", + "histogram of the relative frequency of $\\widehat{\\theta}^*$. Instead\n", + "you use the estimators corresponding to the statistic of interest. For\n", + "example, if you are interested in estimating the variance of $\\widehat\n", + "\\theta$, apply the etsimator $\\widehat \\sigma^2$ to the values\n", + "$\\widehat \\theta ^*$.\n", "\n", "\n", "\n", "## Code example for the Bootstrap method\n", - "The following code starts with a Gaussian distribution with mean value $\\mu =100$ and variance $\\sigma=15$. We use this to generate the data used in the bootstrap analysis. The bootstrap analysis returns a data set after a given number of bootstrap operations (as many as we have data points). This data set consists of estimated mean values for each bootstrap operation. The histogram generated by the bootstrap method shows that the distribution for these mean values is also a Gaussian, centered around the mean value $\\mu=100$ but with standard deviation $\\sigma/\\sqrt{n}$, where $n$ is the number of bootstrap samples (in this case the same as the number of original data points). The value of the standard deviation is what we expect from the central limit theorem." + "\n", + "The following code starts with a Gaussian distribution with mean value\n", + "$\\mu =100$ and variance $\\sigma=15$. We use this to generate the data\n", + "used in the bootstrap analysis. The bootstrap analysis returns a data\n", + "set after a given number of bootstrap operations (as many as we have\n", + "data points). This data set consists of estimated mean values for each\n", + "bootstrap operation. The histogram generated by the bootstrap method\n", + "shows that the distribution for these mean values is also a Gaussian,\n", + "centered around the mean value $\\mu=100$ but with standard deviation\n", + "$\\sigma/\\sqrt{n}$, where $n$ is the number of bootstrap samples (in\n", + "this case the same as the number of original data points). The value\n", + "of the standard deviation is what we expect from the central limit\n", + "theorem." ] }, { "cell_type": "code", - "execution_count": 48, + "execution_count": 57, "metadata": { "collapsed": false }, @@ -9487,30 +6673,29 @@ "def stat(data):\n", " return mean(data)\n", "\n", - "# Bootstrap algorithm \n", + "# Bootstrap algorithm\n", "def bootstrap(data, statistic, R):\n", " t = zeros(R); n = len(data); inds = arange(n); t0 = time()\n", - "\n", - " # non-parametric bootstrap \n", + " # non-parametric bootstrap \n", " for i in range(R):\n", " t[i] = statistic(data[randint(0,n,n)])\n", "\n", - " # analysis \n", + " # analysis \n", " print(\"Runtime: %g sec\" % (time()-t0)); print(\"Bootstrap Statistics :\")\n", " print(\"original bias std. error\")\n", - " print(\"%8g %8g %14g %15g\" % (statistic(data), std(data),\\\n", - " mean(t), \\\n", - " std(t)))\n", + " print(\"%8g %8g %14g %15g\" % (statistic(data), std(data),mean(t),std(t)))\n", " return t\n", "\n", "\n", "mu, sigma = 100, 15\n", "datapoints = 10000\n", "x = mu + sigma*random.randn(datapoints)\n", - "# bootstrap returns the data sample t = bootstrap(x, stat, datapoints)\n", - "# the histogram of the bootstrapped data n, binsboot, patches = plt.hist(t, 50, normed=1, facecolor='red', alpha=0.75)\n", + "# bootstrap returns the data sample \n", + "t = bootstrap(x, stat, datapoints)\n", + "# the histogram of the bootstrapped data \n", + "n, binsboot, patches = plt.hist(t, 50, normed=1, facecolor='red', alpha=0.75)\n", "\n", - "# add a 'best fit' line \n", + "# add a 'best fit' line \n", "y = mlab.normpdf( binsboot, mean(t), std(t))\n", "lt = plt.plot(binsboot, y, 'r--', linewidth=1)\n", "plt.xlabel('Smarts')\n", @@ -9525,498 +6710,108 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "## Resampling methods: Blocking\n", + "## Code Example for Cross-validation and $k$-fold Cross-validation\n", "\n", - "The blocking method was made popular by [Flyvbjerg and Pedersen (1989)](https://aip.scitation.org/doi/10.1063/1.457480)\n", - "and has become one of the standard ways to estimate\n", - "$V(\\widehat{\\theta})$ for exactly one $\\widehat{\\theta}$, namely\n", - "$\\widehat{\\theta} = \\overline{X}$. \n", - "\n", - "Assume $n = 2^d$ for some integer $d>1$ and $X_1,X_2,\\cdots, X_n$ is a stationary time series to begin with. \n", - "Moreover, assume that the time series is asymptotically uncorrelated. We switch to vector notation by arranging $X_1,X_2,\\cdots,X_n$ in an $n$-tuple. Define:" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "\\begin{align*}\n", - "\\hat{X} = (X_1,X_2,\\cdots,X_n).\n", - "\\end{align*}\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "The strength of the blocking method is when the number of\n", - "observations, $n$ is large. For large $n$, the complexity of dependent\n", - "bootstrapping scales poorly, but the blocking method does not,\n", - "moreover, it becomes more accurate the larger $n$ is.\n", - "\n", - "\n", - "## Blocking Transformations\n", - " We now define\n", - "blocking transformations. The idea is to take the mean of subsequent\n", - "pair of elements from $\\vec{X}$ and form a new vector\n", - "$\\vec{X}_1$. Continuing in the same way by taking the mean of\n", - "subsequent pairs of elements of $\\vec{X}_1$ we obtain $\\vec{X}_2$, and\n", - "so on. \n", - "Define $\\vec{X}_i$ recursively by:" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "(\\vec{X}_0)_k \\equiv (\\vec{X})_k \\nonumber\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "\n", - "
\n", - "\n", - "$$\n", - "\\begin{equation} \n", - "(\\vec{X}_{i+1})_k \\equiv \\frac{1}{2}\\Big( (\\vec{X}_i)_{2k-1} +\n", - "(\\vec{X}_i)_{2k} \\Big) \\qquad \\text{for all} \\qquad 1 \\leq i \\leq d-1\n", - "\\label{_auto11} \\tag{28}\n", - "\\end{equation}\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "The quantity $\\vec{X}_k$ is\n", - "subject to $k$ **blocking transformations**. We now have $d$ vectors\n", - "$\\vec{X}_0, \\vec{X}_1,\\cdots,\\vec X_{d-1}$ containing the subsequent\n", - "averages of observations. It turns out that if the components of\n", - "$\\vec{X}$ is a stationary time series, then the components of\n", - "$\\vec{X}_i$ is a stationary time series for all $0 \\leq i \\leq d-1$\n", - "\n", - "We can then compute the autocovariance, the variance, sample mean, and\n", - "number of observations for each $i$. \n", - "Let $\\gamma_i, \\sigma_i^2,\n", - "\\overline{X}_i$ denote the autocovariance, variance and average of the\n", - "elements of $\\vec{X}_i$ and let $n_i$ be the number of elements of\n", - "$\\vec{X}_i$. It follows by induction that $n_i = n/2^i$. \n", - "\n", - "\n", - "## Blocking Transformations\n", - "\n", - "Using the\n", - "definition of the blocking transformation and the distributive\n", - "property of the covariance, it is clear that since $h =|i-j|$\n", - "we can define" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "\\gamma_{k+1}(h) = cov\\left( ({X}_{k+1})_{i}, ({X}_{k+1})_{j} \\right) \\nonumber\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "= \\frac{1}{4}cov\\left( ({X}_{k})_{2i-1} + ({X}_{k})_{2i}, ({X}_{k})_{2j-1} + ({X}_{k})_{2j} \\right) \\nonumber\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "\n", - "
\n", - "\n", - "$$\n", - "\\begin{equation} \n", - "= \\frac{1}{2}\\gamma_{k}(2h) + \\frac{1}{2}\\gamma_k(2h+1) \\hspace{0.1cm} \\mathrm{h = 0} \n", - "\\label{_auto12} \\tag{29}\n", - "\\end{equation}\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "\n", - "
\n", - "\n", - "$$\n", - "\\begin{equation} \n", - "=\\frac{1}{4}\\gamma_k(2h-1) + \\frac{1}{2}\\gamma_k(2h) + \\frac{1}{4}\\gamma_k(2h+1) \\quad \\mathrm{else}\n", - "\\label{_auto13} \\tag{30}\n", - "\\end{equation}\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "The quantity $\\hat{X}$ is asymptotic uncorrelated by assumption, $\\hat{X}_k$ is also asymptotic uncorrelated. Let's turn our attention to the variance of the sample mean $V(\\overline{X})$. \n", - "\n", - "\n", - "## Blocking Transformations, getting there\n", - "We have" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "\n", - "
\n", - "\n", - "$$\n", - "\\begin{equation}\n", - "V(\\overline{X}_k) = \\frac{\\sigma_k^2}{n_k} + \\underbrace{\\frac{2}{n_k} \\sum_{h=1}^{n_k-1}\\left( 1 - \\frac{h}{n_k} \\right)\\gamma_k(h)}_{\\equiv e_k} = \\frac{\\sigma^2_k}{n_k} + e_k \\quad \\text{if} \\quad \\gamma_k(0) = \\sigma_k^2. \n", - "\\label{_auto14} \\tag{31}\n", - "\\end{equation}\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "The term $e_k$ is called the **truncation error**:" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "\n", - "
\n", - "\n", - "$$\n", - "\\begin{equation}\n", - "e_k = \\frac{2}{n_k} \\sum_{h=1}^{n_k-1}\\left( 1 - \\frac{h}{n_k} \\right)\\gamma_k(h). \n", - "\\label{_auto15} \\tag{32}\n", - "\\end{equation}\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "We can show that $V(\\overline{X}_i) = V(\\overline{X}_j)$ for all $0 \\leq i \\leq d-1$ and $0 \\leq j \\leq d-1$. \n", - "\n", - "\n", - "## Blocking Transformations, final expressions\n", - "\n", - "We can then wrap up" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "n_{j+1} \\overline{X}_{j+1} = \\sum_{i=1}^{n_{j+1}} (\\hat{X}_{j+1})_i = \\frac{1}{2}\\sum_{i=1}^{n_{j}/2} (\\hat{X}_{j})_{2i-1} + (\\hat{X}_{j})_{2i} \\nonumber\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "\n", - "
\n", - "\n", - "$$\n", - "\\begin{equation} \n", - "= \\frac{1}{2}\\left[ (\\hat{X}_j)_1 + (\\hat{X}_j)_2 + \\cdots + (\\hat{X}_j)_{n_j} \\right] = \\underbrace{\\frac{n_j}{2}}_{=n_{j+1}} \\overline{X}_j = n_{j+1}\\overline{X}_j. \n", - "\\label{_auto16} \\tag{33}\n", - "\\end{equation}\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "By repeated use of this equation we get $V(\\overline{X}_i) = V(\\overline{X}_0) = V(\\overline{X})$ for all $0 \\leq i \\leq d-1$. This has the consequence that" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "\n", - "
\n", - "\n", - "$$\n", - "\\begin{equation}\n", - "V(\\overline{X}) = \\frac{\\sigma_k^2}{n_k} + e_k \\qquad \\text{for all} \\qquad 0 \\leq k \\leq d-1. \\label{eq:convergence} \\tag{34}\n", - "\\end{equation}\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "Fyvbjerg and Petersen demonstrated that the sequence\n", - "$\\{e_k\\}_{k=0}^{d-1}$ is decreasing, and conjecture that the term\n", - "$e_k$ can be made as small as we would like by making $k$ (and hence\n", - "$d$) sufficiently large. The sequence is decreasing (Master of Science thesis by Marius Jonsson, UiO 2018).\n", - "It means we can apply blocking transformations until\n", - "$e_k$ is sufficiently small, and then estimate $V(\\overline{X})$ by\n", - "$\\widehat{\\sigma}^2_k/n_k$. \n", - "\n", - "\n", - "\n", - "## [Code examples for Blocking, Jackknife and bootstrap](https://github.com/CompPhysics/MachineLearning/tree/master/doc/Programs/ResamplingAnalysisScripts)" + "The code here uses Ridge regression with cross-validation (CV) resampling and $k$-fold CV in order to fit a specific polynomial." ] }, { "cell_type": "code", - "execution_count": 49, + "execution_count": 58, "metadata": { "collapsed": false }, "outputs": [], "source": [ - "from sys import argv\n", - "from os import mkdir, path\n", - "import time\n", "import numpy as np\n", "import matplotlib.pyplot as plt\n", - "from matplotlib.ticker import FormatStrFormatter\n", - "from matplotlib.font_manager import FontProperties\n", + "from sklearn.model_selection import KFold\n", + "from sklearn.linear_model import Ridge\n", + "from sklearn.model_selection import cross_val_score\n", + "from sklearn.preprocessing import PolynomialFeatures\n", "\n", - "# Timing Decorator\n", - "def timeFunction(f):\n", - " def wrap(*args):\n", - " time1 = time.time()\n", - " ret = f(*args)\n", - " time2 = time.time()\n", - " print '%s Function Took: \\t %0.3f s' % (f.func_name.title(), (time2-time1))\n", - " return ret\n", - " return wrap\n", + "# A seed just to ensure that the random numbers are the same for every run.\n", + "# Useful for eventual debugging.\n", + "np.random.seed(3155)\n", "\n", - "class dataAnalysisClass:\n", - " # General Init functions\n", - " def __init__(self, fileName, size=0):\n", - " self.inputFileName = fileName\n", - " self.loadData(size)\n", - " self.createOutputFolder()\n", - " self.avg = np.average(self.data)\n", - " self.var = np.var(self.data)\n", - " self.std = np.std(self.data)\n", + "# Generate the data.\n", + "nsamples = 100\n", + "x = np.random.randn(nsamples)\n", + "y = 3*x**2 + np.random.randn(nsamples)\n", "\n", - " def loadData(self, size=0):\n", - " if size != 0:\n", - " with open(self.inputFileName) as inputFile:\n", - " self.data = np.zeros(size)\n", - " for x in xrange(size):\n", - " self.data[x] = float(next(inputFile))\n", - " else:\n", - " self.data = np.loadtxt(self.inputFileName)\n", + "## Cross-validation on Ridge regression using KFold only\n", "\n", - " # Statistical Analysis with Multiple Methods\n", - " def runAllAnalyses(self):\n", - " if len(self.data) <= 100000:\n", - " print \"Autocorrelation...\"\n", - " self.autocorrelation()\n", - " print \"Bootstrap...\"\n", - " self.bootstrap()\n", - " print \"Jackknife...\"\n", - " self.jackknife()\n", - " print \"Blocking...\"\n", - " self.blocking()\n", + "# Decide degree on polynomial to fit\n", + "poly = PolynomialFeatures(degree = 6)\n", "\n", - " # Standard Autocorrelation\n", - " @timeFunction\n", - " def autocorrelation(self):\n", - " self.acf = np.zeros(len(self.data)/2)\n", - " for k in range(0, len(self.data)/2):\n", - " self.acf[k] = np.corrcoef(np.array([self.data[0:len(self.data)-k], \\\n", - " self.data[k:len(self.data)]]))[0,1]\n", + "# Decide which values of lambda to use\n", + "nlambdas = 500\n", + "lambdas = np.logspace(-3, 5, nlambdas)\n", "\n", - " # Bootstrap\n", - " @timeFunction\n", - " def bootstrap(self, nBoots = 1000):\n", - " bootVec = np.zeros(nBoots)\n", - " for k in range(0,nBoots):\n", - " bootVec[k] = np.average(np.random.choice(self.data, len(self.data)))\n", - " self.bootAvg = np.average(bootVec)\n", - " self.bootVar = np.var(bootVec)\n", - " self.bootStd = np.std(bootVec)\n", + "# Initialize a KFold instance\n", + "k = 5\n", + "kfold = KFold(n_splits = k)\n", "\n", - " # Jackknife\n", - " @timeFunction\n", - " def jackknife(self):\n", - " jackknVec = np.zeros(len(self.data))\n", - " for k in range(0,len(self.data)):\n", - " jackknVec[k] = np.average(np.delete(self.data, k))\n", - " self.jackknAvg = self.avg - (len(self.data) - 1) * (np.average(jackknVec) - self.avg)\n", - " self.jackknVar = float(len(self.data) - 1) * np.var(jackknVec)\n", - " self.jackknStd = np.sqrt(self.jackknVar)\n", + "# Perform the cross-validation to estimate MSE\n", + "scores_KFold = np.zeros((nlambdas, k))\n", "\n", - " # Blocking\n", - " @timeFunction\n", - " def blocking(self, blockSizeMax = 500):\n", - " blockSizeMin = 1\n", + "i = 0\n", + "for lmb in lambdas:\n", + " ridge = Ridge(alpha = lmb)\n", + " j = 0\n", + " for train_inds, test_inds in kfold.split(x):\n", + " xtrain = x[train_inds]\n", + " ytrain = y[train_inds]\n", "\n", - " self.blockSizes = []\n", - " self.meanVec = []\n", - " self.varVec = []\n", + " xtest = x[test_inds]\n", + " ytest = y[test_inds]\n", "\n", - " for i in range(blockSizeMin, blockSizeMax):\n", - " if(len(self.data) % i != 0):\n", - " pass#continue\n", - " blockSize = i\n", - " meanTempVec = []\n", - " varTempVec = []\n", - " startPoint = 0\n", - " endPoint = blockSize\n", + " Xtrain = poly.fit_transform(xtrain[:, np.newaxis])\n", + " ridge.fit(Xtrain, ytrain[:, np.newaxis])\n", "\n", - " while endPoint <= len(self.data):\n", - " meanTempVec.append(np.average(self.data[startPoint:endPoint]))\n", - " startPoint = endPoint\n", - " endPoint += blockSize\n", - " mean, var = np.average(meanTempVec), np.var(meanTempVec)/len(meanTempVec)\n", - " self.meanVec.append(mean)\n", - " self.varVec.append(var)\n", - " self.blockSizes.append(blockSize)\n", + " Xtest = poly.fit_transform(xtest[:, np.newaxis])\n", + " ypred = ridge.predict(Xtest)\n", "\n", - " self.blockingAvg = np.average(self.meanVec[-200:])\n", - " self.blockingVar = (np.average(self.varVec[-200:]))\n", - " self.blockingStd = np.sqrt(self.blockingVar)\n", + " scores_KFold[i,j] = np.sum((ypred - ytest[:, np.newaxis])**2)/np.size(ypred)\n", + "\n", + " j += 1\n", + " i += 1\n", "\n", "\n", + "estimated_mse_KFold = np.mean(scores_KFold, axis = 1)\n", "\n", - " # Plot of Data, Autocorrelation Function and Histogram\n", - " def plotAll(self):\n", - " self.createOutputFolder()\n", - " if len(self.data) <= 100000:\n", - " self.plotAutocorrelation()\n", - " self.plotData()\n", - " self.plotHistogram()\n", - " self.plotBlocking()\n", + "## Cross-validation using cross_val_score from sklearn along with KFold\n", "\n", - " # Create Output Plots Folder\n", - " def createOutputFolder(self):\n", - " self.outName = self.inputFileName[:-4]\n", - " if not path.exists(self.outName):\n", - " mkdir(self.outName)\n", + "# kfold is an instance initialized above as:\n", + "# kfold = KFold(n_splits = k)\n", "\n", - " # Plot the Dataset, Mean and Std\n", - " def plotData(self):\n", - " # Far away plot\n", - " font = {'fontname':'serif'}\n", - " plt.plot(range(0, len(self.data)), self.data, 'r-', linewidth=1)\n", - " plt.plot([0, len(self.data)], [self.avg, self.avg], 'b-', linewidth=1)\n", - " plt.plot([0, len(self.data)], [self.avg + self.std, self.avg + self.std], 'g--', linewidth=1)\n", - " plt.plot([0, len(self.data)], [self.avg - self.std, self.avg - self.std], 'g--', linewidth=1)\n", - " plt.ylim(self.avg - 5*self.std, self.avg + 5*self.std)\n", - " plt.gca().yaxis.set_major_formatter(FormatStrFormatter('%.4f'))\n", - " plt.xlim(0, len(self.data))\n", - " plt.ylabel(self.outName.title() + ' Monte Carlo Evolution', **font)\n", - " plt.xlabel('MonteCarlo History', **font)\n", - " plt.title(self.outName.title(), **font)\n", - " plt.savefig(self.outName + \"/data.eps\")\n", - " plt.savefig(self.outName + \"/data.png\")\n", - " plt.clf()\n", + "estimated_mse_sklearn = np.zeros(nlambdas)\n", + "i = 0\n", + "for lmb in lambdas:\n", + " ridge = Ridge(alpha = lmb)\n", "\n", - " # Plot Histogram of Dataset and Gaussian around it\n", - " def plotHistogram(self):\n", - " binNumber = 50\n", - " font = {'fontname':'serif'}\n", - " count, bins, ignore = plt.hist(self.data, bins=np.linspace(self.avg - 5*self.std, self.avg + 5*self.std, binNumber))\n", - " plt.plot([self.avg, self.avg], [0,np.max(count)+10], 'b-', linewidth=1)\n", - " plt.ylim(0,np.max(count)+10)\n", - " plt.ylabel(self.outName.title() + ' Histogram', **font)\n", - " plt.xlabel(self.outName.title() , **font)\n", - " plt.title('Counts', **font)\n", + " X = poly.fit_transform(x[:, np.newaxis])\n", + " estimated_mse_folds = cross_val_score(ridge, X, y[:, np.newaxis], scoring='neg_mean_squared_error', cv=kfold)\n", "\n", - " #gaussian\n", - " norm = 0\n", - " for i in range(0,len(bins)-1):\n", - " norm += (bins[i+1]-bins[i])*count[i]\n", - " plt.plot(bins, norm/(self.std * np.sqrt(2 * np.pi)) * np.exp( - (bins - self.avg)**2 / (2 * self.std**2) ), linewidth=1, color='r')\n", - " plt.savefig(self.outName + \"/hist.eps\")\n", - " plt.savefig(self.outName + \"/hist.png\")\n", - " plt.clf()\n", + " # cross_val_score return an array containing the estimated negative mse for every fold.\n", + " # we have to the the mean of every array in order to get an estimate of the mse of the model\n", + " estimated_mse_sklearn[i] = np.mean(-estimated_mse_folds)\n", "\n", - " # Plot the Autocorrelation Function\n", - " def plotAutocorrelation(self):\n", - " font = {'fontname':'serif'}\n", - " plt.plot(range(1, len(self.data)/2), self.acf[1:], 'r-')\n", - " plt.ylim(-1, 1)\n", - " plt.xlim(0, len(self.data)/2)\n", - " plt.ylabel('Autocorrelation Function', **font)\n", - " plt.xlabel('Lag', **font)\n", - " plt.title('Autocorrelation', **font)\n", - " plt.savefig(self.outName + \"/autocorrelation.eps\")\n", - " plt.savefig(self.outName + \"/autocorrelation.png\")\n", - " plt.clf()\n", + " i += 1\n", "\n", - " def plotBlocking(self):\n", - " font = {'fontname':'serif'}\n", - " plt.plot(self.blockSizes, self.varVec, 'r-')\n", - " plt.ylabel('Variance', **font)\n", - " plt.xlabel('Block Size', **font)\n", - " plt.title('Blocking', **font)\n", - " plt.savefig(self.outName + \"/blocking.eps\")\n", - " plt.savefig(self.outName + \"/blocking.png\")\n", - " plt.clf()\n", + "## Plot and compare the slightly different ways to perform cross-validation\n", "\n", - " # Print Stuff to the Terminal\n", - " def printOutput(self):\n", - " print \"\\nSample Size: \\t\", len(self.data)\n", - " print \"\\n=========================================\\n\"\n", - " print \"Sample Average: \\t\", self.avg\n", - " print \"Sample Variance:\\t\", self.var\n", - " print \"Sample Std: \\t\", self.std\n", - " print \"\\n=========================================\\n\"\n", - " print \"Bootstrap Average: \\t\", self.bootAvg\n", - " print \"Bootstrap Variance:\\t\", self.bootVar\n", - " print \"Bootstrap Error: \\t\", self.bootStd\n", - " print \"\\n=========================================\\n\"\n", - " print \"Jackknife Average: \\t\", self.jackknAvg\n", - " print \"Jackknife Variance:\\t\", self.jackknVar\n", - " print \"Jackknife Error: \\t\", self.jackknStd\n", - " print \"\\n=========================================\\n\"\n", - " print \"Blocking Average: \\t\", self.blockingAvg\n", - " print \"Blocking Variance:\\t\", self.blockingVar\n", - " print \"Blocking Error: \\t\", self.blockingStd, \"\\n\"\n", + "plt.figure()\n", "\n", - "# Initialize the class\n", - "if len(argv) > 2:\n", - " dataAnalysis = dataAnalysisClass(argv[1], int(argv[2]))\n", - "else:\n", - " dataAnalysis = dataAnalysisClass(argv[1])\n", + "plt.plot(np.log10(lambdas), estimated_mse_sklearn, label = 'cross_val_score')\n", + "plt.plot(np.log10(lambdas), estimated_mse_KFold, 'r--', label = 'KFold')\n", "\n", - "# Run Analyses\n", - "dataAnalysis.runAllAnalyses()\n", + "plt.xlabel('log10(lambda)')\n", + "plt.ylabel('mse')\n", "\n", - "# Plot the data\n", - "dataAnalysis.plotAll()\n", + "plt.legend()\n", "\n", - "# Print Some Output\n", - "dataAnalysis.printOutput()" + "plt.show()" ] }, { @@ -10025,27 +6820,14 @@ "source": [ "## The bias-variance tradeoff\n", "\n", - "We begin with an unknown function $y=f(x)$ and fix a \\emph{hypothesis set}\n", - " $\\mathcal{H}$ consisting of all functions we are willing to consider,\n", - " defined also on the domain of $f$. This set may be uncountably\n", - " infinite (e.g. if there are real-valued parameters to fit). \n", - "The\n", - " choice of which functions to include in $\\mathcal{H}$ usually depends\n", - " on our intuition about the problem of interest. The function $f(x)$\n", - " produces a set of pairs $(x_i,y_i)$, $i=1\\dots N$, which serve as the\n", - " observable data. Our goal is to select a function from the hypothesis\n", - " set $h\\in\\mathcal{H}$ which approximates $f(x)$ as best as possible,\n", - " namely, we would like to find $h\\in\\mathcal{H}$ such that $h\\approx\n", - " f$ in some strict mathematical sense which we specify below. If this\n", - " is possible, we say that we \\emph{learned} $f(x)$. But if the\n", - " function $f(x)$ can, in principle, take any value on\n", - " \\emph{unobserved} inputs, how is it possible to learn in any\n", - " meaningful sense?\n", "\n", + "We will discuss the bias-variance tradeoff in the context of\n", + "continuous predictions such as regression. However, many of the\n", + "intuitions and ideas discussed here also carry over to classification\n", + "tasks. Consider a dataset $\\mathcal{L}$ consisting of the data\n", + "$\\mathbf{X}_\\mathcal{L}=\\{(y_j, \\boldsymbol{x}_j), j=0\\ldots n-1\\}$. \n", "\n", - "## Training and testing data\n", - "\n", - "We will discuss the bias-variance tradeoff in the context of continuous predictions such as regression. However, many of the intuitions and ideas discussed here also carry over to classification tasks. Consider a dataset $\\mathcal{L}$ consisting of the data $\\mathbf{X}_\\mathcal{L}=\\{(y_j, \\boldsymbol{x}_j), j=1\\ldots N\\}$. Let us assume that the true data is generated from a noisy model" + "Let us assume that the true data is generated from a noisy model" ] }, { @@ -10053,7 +6835,7 @@ "metadata": {}, "source": [ "$$\n", - "y=f(\\boldsymbol{x}) + \\epsilon\n", + "\\boldsymbol{y}=f(\\boldsymbol{x}) + \\boldsymbol{\\epsilon}\n", "$$" ] }, @@ -10061,16 +6843,14 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "where $\\epsilon$ is normally distributed with mean zero and standard deviation $\\sigma_\\epsilon$.\n", + "where $\\epsilon$ is normally distributed with mean zero and standard deviation $\\sigma^2$.\n", "\n", + "In our derivation of the ordinary least squares method we defined then\n", + "an approximation to the function $f$ in terms of the parameters\n", + "$\\boldsymbol{\\beta}$ and the design matrix $\\boldsymbol{X}$ which embody our model,\n", + "that is $\\boldsymbol{\\tilde{y}}=\\boldsymbol{X}\\boldsymbol{\\beta}$. \n", "\n", - "## Procedure to find a predictor\n", - "\n", - "We have a statistical procedure (e.g. least-squares regression) for\n", - "forming a predictor $\\hat{g}_{\\mathcal{L}}(\\boldsymbol{x})$ that gives the\n", - "prediction of our model for a new data point $\\boldsymbol{x}$. This estimator\n", - "is chosen by minimizing a cost function which we take to be the\n", - "squared error" + "Thereafter we found the parameters $\\boldsymbol{\\beta}$ by optimizing the means squared error via the so-called cost function" ] }, { @@ -10078,7 +6858,7 @@ "metadata": {}, "source": [ "$$\n", - "\\mathcal{C}( \\boldsymbol{X}, \\hat{g}(\\boldsymbol{x})) = \\sum_i (y_i - \\hat{g}_\\mathcal{L}(\\boldsymbol{x}_i))^2.\n", + "C(\\boldsymbol{X},\\boldsymbol{\\beta}) =\\frac{1}{n}\\sum_{i=0}^{n-1}(y_i-\\tilde{y}_i)^2=\\mathbb{E}\\left[(\\boldsymbol{y}-\\boldsymbol{\\tilde{y}})^2\\right].\n", "$$" ] }, @@ -10086,27 +6866,7 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "## What we want\n", - "\n", - "We are interested in the generalization error on all data drawn from\n", - "the true model, not just the error on the particular training dataset\n", - "$\\mathcal{L}$ that we have in hand. This is just the expectation of\n", - "the cost function over many different data sets\n", - "$\\{\\mathcal{L}_j\\}$. Denote this expectation value by\n", - "$E_{\\mathcal{L}}$. In other words, we can view $\\hat{g}_{\\mathcal{L}}$\n", - "as a stochastic functional that depends on the dataset $\\mathcal{L}$\n", - "and we can think of $E_{\\mathcal{L}}$ as the expected value of the\n", - "functional if we drew an infinite number of datasets $\\{\\mathcal{L}_1,\n", - "\\mathcal{L}_2, \\ldots \\}$.\n", - "\n", - "\n", - "\n", - "## The expected generalization error\n", - "\n", - "We would also like to average over different instances of the\n", - "\"noise\" $\\epsilon$ and we denote the expectation value over the\n", - "noise by $E_\\epsilon$. Thus, we can decompose the expected\n", - "generalization error as" + "We can rewrite this as" ] }, { @@ -10114,7 +6874,7 @@ "metadata": {}, "source": [ "$$\n", - "E_\\mathcal{L, \\epsilon}[\\mathcal{C}( \\boldsymbol{X}, \\hat{g}(\\boldsymbol{x})) ]= E_\\mathcal{L,\\epsilon}\\left[ \\sum_i ({y}_i - \\hat{g}_\\mathcal{L}(\\boldsymbol{x}_i))^2 \\right] \\nonumber\n", + "\\mathbb{E}\\left[(\\boldsymbol{y}-\\boldsymbol{\\tilde{y}})^2\\right]=\\frac{1}{n}\\sum_i(f_i-\\mathbb{E}\\left[\\boldsymbol{\\tilde{y}}\\right])^2+\\frac{1}{n}\\sum_i(\\tilde{y}_i-\\mathbb{E}\\left[\\boldsymbol{\\tilde{y}}\\right])^2+\\sigma^2.\n", "$$" ] }, @@ -10122,32 +6882,22 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "$$\n", - "= E_\\mathcal{L, \\epsilon}\\left[ \\sum_{i}({y}_i -f(\\boldsymbol{x}_i) +f(\\boldsymbol{x}_i)- \\hat{g}_\\mathcal{L}(\\boldsymbol{x}_i))^2\\right] \\nonumber\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "= \\sum_i E_\\epsilon[ ({y}_i -f(\\boldsymbol{x}_i))^2 ]+ E_\\mathcal{L, \\epsilon}[(f(\\boldsymbol{x}_i)- \\hat{g}_\\mathcal{L}(\\boldsymbol{x}_i))^2] + 2E_\\epsilon[{y}_i -f(\\boldsymbol{x}_i)]E_\\mathcal{L}[f(\\boldsymbol{x}_i)- \\hat{g}_\\mathcal{L}(\\boldsymbol{x}_i)] \\nonumber\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "\n", - "
\n", + "The three terms represent the square of the bias of the learning\n", + "method, which can be thought of as the error caused by the simplifying\n", + "assumptions built into the method. The second term represents the\n", + "variance of the chosen model and finally the last terms is variance of\n", + "the error $\\boldsymbol{\\epsilon}$.\n", "\n", + "To derive this equation, we need to recall that the variance of $\\boldsymbol{y}$ and $\\boldsymbol{\\epsilon}$ are both equal to $\\sigma^2$. The mean value of $\\boldsymbol{\\epsilon}$ is by definition equal to zero. Furthermore, the function $f$ is not a stochastics variable, idem for $\\boldsymbol{\\tilde{y}}$.\n", + "We use a more compact notation in terms of the expectation value" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ "$$\n", - "\\begin{equation} \n", - " =\\sum_i \\sigma_\\epsilon^2 + E_\\mathcal{L}[(f(\\boldsymbol{x}_i)- \\hat{g}_\\mathcal{L}(\\boldsymbol{x}_i))^2],\n", - "\\label{_auto17} \\tag{35}\n", - "\\end{equation}\n", + "\\mathbb{E}\\left[(\\boldsymbol{y}-\\boldsymbol{\\tilde{y}})^2\\right]=\\mathbb{E}\\left[(\\boldsymbol{f}+\\boldsymbol{\\epsilon}-\\boldsymbol{\\tilde{y}})^2\\right],\n", "$$" ] }, @@ -10155,128 +6905,193 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "where in the last line we used the fact that our noise has zero mean\n", - "and variance $\\sigma_\\epsilon^2$ and the sum over $i$ applies to all\n", - "terms. \n", + "and adding and subtracting $\\mathbb{E}\\left[\\boldsymbol{\\tilde{y}}\\right]$ we get" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "$$\n", + "\\mathbb{E}\\left[(\\boldsymbol{y}-\\boldsymbol{\\tilde{y}})^2\\right]=\\mathbb{E}\\left[(\\boldsymbol{f}+\\boldsymbol{\\epsilon}-\\boldsymbol{\\tilde{y}}+\\mathbb{E}\\left[\\boldsymbol{\\tilde{y}}\\right]-\\mathbb{E}\\left[\\boldsymbol{\\tilde{y}}\\right])^2\\right],\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "which, using the abovementioned expectation values can be rewritten as" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "$$\n", + "\\mathbb{E}\\left[(\\boldsymbol{y}-\\boldsymbol{\\tilde{y}})^2\\right]=\\mathbb{E}\\left[(\\boldsymbol{y}-\\mathbb{E}\\left[\\boldsymbol{\\tilde{y}}\\right])^2\\right]+\\mathrm{Var}\\left[\\boldsymbol{\\tilde{y}}\\right]+\\sigma^2,\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "that is the rewriting in terms of the so-called bias, the variance of the model $\\boldsymbol{\\tilde{y}}$ and the variance of $\\boldsymbol{\\epsilon}$.\n", "\n", "\n", - "## Elaborating a little bit more\n", - "\n", - "It is also helpful to further decompose the second term as\n", - "follows:" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "E_\\mathcal{L}[(f(\\boldsymbol{x}_i)- \\hat{g}_\\mathcal{L}(\\boldsymbol{x}_i))^2] =E_\\mathcal{L}[(f(\\mathbf{x}_i)-E_\\mathcal{L}[\\hat{g}_\\mathcal{L}(\\boldsymbol{x}_i)]+ E_\\mathcal{L}[\\hat{g}_\\mathcal{L}(\\boldsymbol{x}_i)]- \\hat{g}_\\mathcal{L}(\\boldsymbol{x}_i))^2] \\nonumber\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "=E_\\mathcal{L}[(f(\\boldsymbol{x}_i)-E_\\mathcal{L}[\\hat{g}_\\mathcal{L}(\\boldsymbol{x}_i)])^2] + E_\\mathcal{L}[( \\hat{g}_\\mathcal{L}(\\boldsymbol{x}_i)-E_\\mathcal{L}[\\hat{g}_\\mathcal{L}(\\boldsymbol{x}_i)])^2] \\nonumber\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "+2E_\\mathcal{L}[(f(\\boldsymbol{x}_i)-E_\\mathcal{L}[\\hat{g}_\\mathcal{L}(\\boldsymbol{x}_i)])( \\hat{g}_\\mathcal{L}(\\boldsymbol{x}_i)-E_\\mathcal{L}[\\hat{g}_\\mathcal{L}(\\boldsymbol{x}_i)])] \\nonumber\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "\n", - "
\n", - "\n", - "$$\n", - "\\begin{equation} \n", - "=(f(\\boldsymbol{x}_i)-E_\\mathcal{L}[\\hat{g}_\\mathcal{L}(\\boldsymbol{x}_i)])^2+E_\\mathcal{L}[( \\hat{g}_\\mathcal{L}(\\boldsymbol{x}_i)-E_\\mathcal{L}[\\hat{g}_\\mathcal{L}(\\boldsymbol{x}_i)])^2].\n", - "\\label{_auto18} \\tag{36}\n", - "\\end{equation}\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "## The bias\n", - "\n", - "The first term is called the bias" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "Bias^2= \\sum_i (f(\\boldsymbol{x}_i)-E_\\mathcal{L}[\\hat{g}_\\mathcal{L}(\\boldsymbol{x}_i)])^2\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "and measures the deviation of the expectation value of our estimator (i.e. the asymptotic value of our estimator in the infinite data limit) from the true value. \n", "\n", "\n", - "## The variance\n", - "The second term is called the variance" + "\n", + "## Example code for Bias-Variance tradeoff" + ] + }, + { + "cell_type": "code", + "execution_count": 59, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "import matplotlib.pyplot as plt\n", + "import numpy as np\n", + "from sklearn.linear_model import LinearRegression, Ridge, Lasso\n", + "from sklearn.preprocessing import PolynomialFeatures\n", + "from sklearn.model_selection import train_test_split\n", + "from sklearn.pipeline import make_pipeline\n", + "from sklearn.utils import resample\n", + "\n", + "np.random.seed(2018)\n", + "\n", + "n = 500\n", + "n_boostraps = 100\n", + "degree = 18 # A quite high value, just to show.\n", + "noise = 0.1\n", + "\n", + "# Make data set.\n", + "x = np.linspace(-1, 3, n).reshape(-1, 1)\n", + "y = np.exp(-x**2) + 1.5 * np.exp(-(x-2)**2) + np.random.normal(0, 0.1, x.shape)\n", + "\n", + "# Hold out some test data that is never used in training.\n", + "x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.2)\n", + "\n", + "# Combine x transformation and model into one operation.\n", + "# Not neccesary, but convenient.\n", + "model = make_pipeline(PolynomialFeatures(degree=degree), LinearRegression(fit_intercept=False))\n", + "\n", + "# The following (m x n_bootstraps) matrix holds the column vectors y_pred\n", + "# for each bootstrap iteration.\n", + "y_pred = np.empty((y_test.shape[0], n_boostraps))\n", + "for i in range(n_boostraps):\n", + " x_, y_ = resample(x_train, y_train)\n", + "\n", + " # Evaluate the new model on the same test data each time.\n", + " y_pred[:, i] = model.fit(x_, y_).predict(x_test).ravel()\n", + "\n", + "# Note: Expectations and variances taken w.r.t. different training\n", + "# data sets, hence the axis=1. Subsequent means are taken across the test data\n", + "# set in order to obtain a total value, but before this we have error/bias/variance\n", + "# calculated per data point in the test set.\n", + "# Note 2: The use of keepdims=True is important in the calculation of bias as this \n", + "# maintains the column vector form. Dropping this yields very unexpected results.\n", + "error = np.mean( np.mean((y_test - y_pred)**2, axis=1, keepdims=True) )\n", + "bias = np.mean( (y_test - np.mean(y_pred, axis=1, keepdims=True))**2 )\n", + "variance = np.mean( np.var(y_pred, axis=1, keepdims=True) )\n", + "print('Error:', error)\n", + "print('Bias^2:', bias)\n", + "print('Var:', variance)\n", + "print('{} >= {} + {} = {}'.format(error, bias, variance, bias+variance))\n", + "\n", + "plt.plot(x[::5, :], y[::5, :], label='f(x)')\n", + "plt.scatter(x_test, y_test, label='Data points')\n", + "plt.scatter(x_test, np.mean(y_pred, axis=1), label='Pred')\n", + "plt.legend()\n", + "plt.show()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ - "$$\n", - "Var=\\sum_i E_\\mathcal{L}[( \\hat{g}_\\mathcal{L}(\\boldsymbol{x}_i)-E_\\mathcal{L}[\\hat{g}_\\mathcal{L}(\\boldsymbol{x}_i)])^2],\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "and measures how much our estimator fluctuates due to finite-sample effects. Combining these expressions, we see that the expected out-of-sample error of our model can be decomposed as" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "E_\\mathrm{out}=E_\\mathcal{L, \\epsilon}[\\mathcal{C}( \\boldsymbol{X}, \\hat{g}(\\boldsymbol{x})) ] = Bias^2 + Var + Noise.\n", - "$$" + "## Understanding what happens" + ] + }, + { + "cell_type": "code", + "execution_count": 60, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "import matplotlib.pyplot as plt\n", + "import numpy as np\n", + "from sklearn.linear_model import LinearRegression, Ridge, Lasso\n", + "from sklearn.preprocessing import PolynomialFeatures\n", + "from sklearn.model_selection import train_test_split\n", + "from sklearn.pipeline import make_pipeline\n", + "from sklearn.utils import resample\n", + "\n", + "np.random.seed(2018)\n", + "\n", + "n = 40\n", + "n_boostraps = 100\n", + "maxdegree = 14\n", + "\n", + "\n", + "# Make data set.\n", + "x = np.linspace(-3, 3, n).reshape(-1, 1)\n", + "y = np.exp(-x**2) + 1.5 * np.exp(-(x-2)**2)+ np.random.normal(0, 0.1, x.shape)\n", + "error = np.zeros(maxdegree)\n", + "bias = np.zeros(maxdegree)\n", + "variance = np.zeros(maxdegree)\n", + "polydegree = np.zeros(maxdegree)\n", + "x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.2)\n", + "\n", + "for degree in range(maxdegree):\n", + " model = make_pipeline(PolynomialFeatures(degree=degree), LinearRegression(fit_intercept=False))\n", + " y_pred = np.empty((y_test.shape[0], n_boostraps))\n", + " for i in range(n_boostraps):\n", + " x_, y_ = resample(x_train, y_train)\n", + " y_pred[:, i] = model.fit(x_, y_).predict(x_test).ravel()\n", + "\n", + " polydegree[degree] = degree\n", + " error[degree] = np.mean( np.mean((y_test - y_pred)**2, axis=1, keepdims=True) )\n", + " bias[degree] = np.mean( (y_test - np.mean(y_pred, axis=1, keepdims=True))**2 )\n", + " variance[degree] = np.mean( np.var(y_pred, axis=1, keepdims=True) )\n", + " print('Polynomial degree:', degree)\n", + " print('Error:', error[degree])\n", + " print('Bias^2:', bias[degree])\n", + " print('Var:', variance[degree])\n", + " print('{} >= {} + {} = {}'.format(error[degree], bias[degree], variance[degree], bias[degree]+variance[degree]))\n", + "\n", + "plt.plot(polydegree, np.log10(error), label='Error')\n", + "plt.plot(polydegree, bias, label='bias')\n", + "plt.plot(polydegree, variance, label='Variance')\n", + "plt.legend()\n", + "plt.show()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ + "## Summing up\n", + "\n", + "\n", + "\n", + "\n", "The bias-variance tradeoff summarizes the fundamental tension in\n", "machine learning, particularly supervised learning, between the\n", "complexity of a model and the amount of training data needed to train\n", "it. Since data is often limited, in practice it is often useful to\n", - "use a less-complex model with higher bias - a model whose asymptotic\n", - "performance is worse than another model - because it is easier to\n", + "use a less-complex model with higher bias, that is a model whose asymptotic\n", + "performance is worse than another model because it is easier to\n", "train and less sensitive to sampling noise arising from having a\n", "finite-sized training dataset (smaller variance). \n", "\n", "\n", - "## Summing up\n", "\n", "The above equations tell us that in\n", "order to minimize the expected test error, we need to select a\n", @@ -10298,9 +7113,102 @@ "\n", "\n", "\n", - "## The one-dimensional Ising model, project 2\n", + "## Another Example rom Scikit-Learn's Repository" + ] + }, + { + "cell_type": "code", + "execution_count": 61, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "\"\"\"\n", + "============================\n", + "Underfitting vs. Overfitting\n", + "============================\n", "\n", - "The one-dimensional Ising model with nearest neighbor interaction, no external field and a constant coupling constant $J$ is given by" + "This example demonstrates the problems of underfitting and overfitting and\n", + "how we can use linear regression with polynomial features to approximate\n", + "nonlinear functions. The plot shows the function that we want to approximate,\n", + "which is a part of the cosine function. In addition, the samples from the\n", + "real function and the approximations of different models are displayed. The\n", + "models have polynomial features of different degrees. We can see that a\n", + "linear function (polynomial with degree 1) is not sufficient to fit the\n", + "training samples. This is called **underfitting**. A polynomial of degree 4\n", + "approximates the true function almost perfectly. However, for higher degrees\n", + "the model will **overfit** the training data, i.e. it learns the noise of the\n", + "training data.\n", + "We evaluate quantitatively **overfitting** / **underfitting** by using\n", + "cross-validation. We calculate the mean squared error (MSE) on the validation\n", + "set, the higher, the less likely the model generalizes correctly from the\n", + "training data.\n", + "\"\"\"\n", + "\n", + "print(__doc__)\n", + "\n", + "import numpy as np\n", + "import matplotlib.pyplot as plt\n", + "from sklearn.pipeline import Pipeline\n", + "from sklearn.preprocessing import PolynomialFeatures\n", + "from sklearn.linear_model import LinearRegression\n", + "from sklearn.model_selection import cross_val_score\n", + "\n", + "\n", + "def true_fun(X):\n", + " return np.cos(1.5 * np.pi * X)\n", + "\n", + "np.random.seed(0)\n", + "\n", + "n_samples = 30\n", + "degrees = [1, 4, 15]\n", + "\n", + "X = np.sort(np.random.rand(n_samples))\n", + "y = true_fun(X) + np.random.randn(n_samples) * 0.1\n", + "\n", + "plt.figure(figsize=(14, 5))\n", + "for i in range(len(degrees)):\n", + " ax = plt.subplot(1, len(degrees), i + 1)\n", + " plt.setp(ax, xticks=(), yticks=())\n", + "\n", + " polynomial_features = PolynomialFeatures(degree=degrees[i],\n", + " include_bias=False)\n", + " linear_regression = LinearRegression()\n", + " pipeline = Pipeline([(\"polynomial_features\", polynomial_features),\n", + " (\"linear_regression\", linear_regression)])\n", + " pipeline.fit(X[:, np.newaxis], y)\n", + "\n", + " # Evaluate the models using crossvalidation\n", + " scores = cross_val_score(pipeline, X[:, np.newaxis], y,\n", + " scoring=\"neg_mean_squared_error\", cv=10)\n", + "\n", + " X_test = np.linspace(0, 1, 100)\n", + " plt.plot(X_test, pipeline.predict(X_test[:, np.newaxis]), label=\"Model\")\n", + " plt.plot(X_test, true_fun(X_test), label=\"True function\")\n", + " plt.scatter(X, y, edgecolor='b', s=20, label=\"Samples\")\n", + " plt.xlabel(\"x\")\n", + " plt.ylabel(\"y\")\n", + " plt.xlim((0, 1))\n", + " plt.ylim((-2, 2))\n", + " plt.legend(loc=\"best\")\n", + " plt.title(\"Degree {}\\nMSE = {:.2e}(+/- {:.2e})\".format(\n", + " degrees[i], -scores.mean(), scores.std()))\n", + "plt.show()" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## The one-dimensional Ising model\n", + "\n", + "Let us bring back the Ising model again, but now with an additional\n", + "focus on Ridge and Lasso regression as well. We repeat some of the\n", + "basic parts of the Ising model and the setup of the training and test\n", + "data. The one-dimensional Ising model with nearest neighbor\n", + "interaction, no external field and a constant coupling constant $J$ is\n", + "given by" ] }, { @@ -10308,12 +7216,12 @@ "metadata": {}, "source": [ "\n", - "
\n", + "
\n", "\n", "$$\n", "\\begin{equation}\n", " H = -J \\sum_{k}^L s_k s_{k + 1},\n", - "\\label{_auto19} \\tag{37}\n", + "\\label{_auto17} \\tag{27}\n", "\\end{equation}\n", "$$" ] @@ -10329,7 +7237,7 @@ }, { "cell_type": "code", - "execution_count": 50, + "execution_count": 62, "metadata": { "collapsed": false }, @@ -10362,15 +7270,6 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "Here we use linear (ordinary least squares), ridge and LASSO\n", - "regression to predict the energy in the nearest neighbor\n", - "one-dimensional Ising model on a ring, i.e., the endpoints wrap\n", - "around. We will use the linear regression models to fit a value for\n", - "the coupling constant to achieve this.\n", - "\n", - "\n", - "## Reformulating the problem to suit regression\n", - "\n", "A more general form for the one-dimensional Ising model is" ] }, @@ -10379,12 +7278,12 @@ "metadata": {}, "source": [ "\n", - "
\n", + "
\n", "\n", "$$\n", "\\begin{equation}\n", " H = - \\sum_j^L \\sum_k^L s_j s_k J_{jk}.\n", - "\\label{_auto20} \\tag{38}\n", + "\\label{_auto18} \\tag{28}\n", "\\end{equation}\n", "$$" ] @@ -10403,12 +7302,12 @@ "metadata": {}, "source": [ "\n", - "
\n", + "
\n", "\n", "$$\n", "\\begin{equation}\n", " H = X J,\n", - "\\label{_auto21} \\tag{39}\n", + "\\label{_auto19} \\tag{29}\n", "\\end{equation}\n", "$$" ] @@ -10427,19 +7326,26 @@ "metadata": {}, "source": [ "\n", - "
\n", + "
\n", "\n", "$$\n", "\\begin{equation}\n", - " y = X\\omega + \\epsilon,\n", - "\\label{_auto22} \\tag{40}\n", + " \\boldsymbol{y} = \\boldsymbol{X}\\boldsymbol{\\beta} + \\boldsymbol{\\epsilon}.\n", + "\\label{_auto20} \\tag{30}\n", "\\end{equation}\n", "$$" ] }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "We organize the data as we did above" + ] + }, { "cell_type": "code", - "execution_count": 51, + "execution_count": 63, "metadata": { "collapsed": false }, @@ -10466,277 +7372,12 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "## Linear regression\n", - "\n", - "The problem at hand is to try to fit the equation" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "\n", - "
\n", - "\n", - "$$\n", - "\\begin{equation}\n", - " y = f(x) + \\epsilon,\n", - "\\label{_auto23} \\tag{41}\n", - "\\end{equation}\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "where $f(x)$ is some unknown function of the data $x$ and $\\epsilon$\n", - "is normally distributed with mean zero noise with standard deviation\n", - "$\\sigma_{\\epsilon}$. Our job is to try to find a predictor which\n", - "estimates the function $f(x)$. In linear regression we assume that we\n", - "can formulate the problem as" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "\n", - "
\n", - "\n", - "$$\n", - "\\begin{equation}\n", - " y = X\\omega + \\epsilon,\n", - "\\label{_auto24} \\tag{42}\n", - "\\end{equation}\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "where $X$ and $\\omega$ are now matrices. Our job at hand is now to\n", - "find a **cost function** $C$, which we wish to minimize in order to find\n", - "the best estimate of $\\omega$.\n", - "\n", - "\n", - "## Ordinary least squares\n", - "\n", - "In the ordinary least squares method we choose the cost function" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "\n", - "
\n", - "\n", - "$$\n", - "\\begin{equation}\n", - " C(X, \\omega) = ||X\\omega - y||^2\n", - " = (X\\omega - y)^T(X\\omega - y)\n", - "\\label{_auto25} \\tag{43}\n", - "\\end{equation}\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "We then find the extremal point of $C$ by taking the derivative with respect to $\\omega$ and setting it to zero, i.e.," - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "\n", - "
\n", - "\n", - "$$\n", - "\\begin{equation}\n", - " \\dfrac{\\mathrm{d}C}{\\mathrm{d}\\omega}\n", - " = 0.\n", - "\\label{_auto26} \\tag{44}\n", - "\\end{equation}\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "This yields the expression for $\\omega$ to be" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "\n", - "
\n", - "\n", - "$$\n", - "\\begin{equation}\n", - " \\omega = \\frac{X^T y}{X^T X},\n", - "\\label{_auto27} \\tag{45}\n", - "\\end{equation}\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "which immediately imposes some requirements on $X$ as there must exist\n", - "an inverse of $X^T X$. If the expression we are modelling contains an\n", - "intercept, i.e., a constant expression we must make sure that the\n", - "first column of $X$ consists of $1$." + "We will do all fitting with **Scikit-Learn**," ] }, { "cell_type": "code", - "execution_count": 52, - "metadata": { - "collapsed": false - }, - "outputs": [], - "source": [ - "def get_ols_weights_naive(x: np.ndarray, y: np.ndarray) -> np.ndarray:\n", - " return scl.inv(x.T @ x) @ (x.T @ y)\n", - "omega = get_ols_weights_naive(X_train_own, y_train)" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "## Singular Value decomposition\n", - "Doing the inversion directly turns out to be a bad idea as the matrix\n", - "$X^TX$ is singular. An alternative approach is to use the **singular\n", - "value decomposition**. Using the definition of the Moore-Penrose\n", - "pseudoinverse we can write the equation for $\\omega$ as" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "\n", - "
\n", - "\n", - "$$\n", - "\\begin{equation}\n", - " \\omega = X^{+}y,\n", - "\\label{_auto28} \\tag{46}\n", - "\\end{equation}\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "where the pseudoinverse of $X$ is given by" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "\n", - "
\n", - "\n", - "$$\n", - "\\begin{equation}\n", - " X^{+} = \\frac{X^T}{X^T X}.\n", - "\\label{_auto29} \\tag{47}\n", - "\\end{equation}\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "Using singular value decomposition we have that $X = U\\Sigma V^T$,\n", - "where $X^{+} = V\\Sigma^{+} U^T$. This reduces the equation for\n", - "$\\omega$ to" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "\n", - "
\n", - "\n", - "$$\n", - "\\begin{equation}\n", - " \\omega = V\\Sigma^{+} U^T y.\n", - "\\label{_auto30} \\tag{48}\n", - "\\end{equation}\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "Note that solving this equation by actually doing the pseudoinverse\n", - "(which is what we will do) is not a good idea as this operation scales\n", - "as $\\mathcal{O}(n^3)$, where $n$ is the number of elements in a\n", - "general matrix. Instead, doing $QR$-factorization and solving the\n", - "linear system as an equation would reduce this down to\n", - "$\\mathcal{O}(n^2)$ operations." - ] - }, - { - "cell_type": "code", - "execution_count": 53, - "metadata": { - "collapsed": false - }, - "outputs": [], - "source": [ - "def get_ols_weights(x: np.ndarray, y: np.ndarray) -> np.ndarray:\n", - " u, s, v = scl.svd(x)\n", - " return v.T @ scl.pinv(scl.diagsvd(s, u.shape[0], v.shape[0])) @ u.T @ y" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "Before passing in the data to the function we append a column with ones to the training data." - ] - }, - { - "cell_type": "code", - "execution_count": 54, - "metadata": { - "collapsed": false - }, - "outputs": [], - "source": [ - "omega = get_ols_weights(X_train_own,y_train)" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "## Fitting with scikit-learn\n", - "\n", - "Next we fit a `LinearRegression`-model from Scikit-learn for comparison." - ] - }, - { - "cell_type": "code", - "execution_count": 55, + "execution_count": 64, "metadata": { "collapsed": false }, @@ -10749,18 +7390,17 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "Extracting the $J$-matrix from both our own method and the Scikit-learn model where we make sure to remove the intercept." + "When extracting the $J$-matrix we make sure to remove the intercept" ] }, { "cell_type": "code", - "execution_count": 56, + "execution_count": 65, "metadata": { "collapsed": false }, "outputs": [], "source": [ - "J_own = omega[1:].reshape(L, L)\n", "J_sk = clf.coef_.reshape(L, L)" ] }, @@ -10768,25 +7408,17 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "A way of looking at the coefficients in $J$ is to plot the matrices as images." + "And then we plot the results" ] }, { "cell_type": "code", - "execution_count": 57, + "execution_count": 66, "metadata": { "collapsed": false }, "outputs": [], "source": [ - "fig = plt.figure(figsize=(20, 14))\n", - "im = plt.imshow(J_own, **cmap_args)\n", - "plt.title(\"Home-made OLS\", fontsize=18)\n", - "plt.xticks(fontsize=18)\n", - "plt.yticks(fontsize=18)\n", - "cb = fig.colorbar(im)\n", - "cb.ax.set_yticklabels(cb.ax.get_yticklabels(), fontsize=18)\n", - "\n", "fig = plt.figure(figsize=(20, 14))\n", "im = plt.imshow(J_sk, **cmap_args)\n", "plt.title(\"LinearRegression from Scikit-learn\", fontsize=18)\n", @@ -10801,10 +7433,7 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "We can see that our model for the least squares method performes close\n", - "to the benchmark from Scikit-learn. It is interesting to note that OLS\n", - "considers both $J_{j, j + 1} = -0.5$ and $J_{j, j - 1} = -0.5$ as\n", - "valid matrix elements for $J$.\n", + "The results perfectly with our previous discussion where we used our own code.\n", "\n", "\n", "## Ridge regression\n", @@ -10812,7 +7441,7 @@ "Having explored the ordinary least squares we move on to ridge\n", "regression. In ridge regression we include a **regularizer**. This\n", "involves a new cost function which leads to a new estimate for the\n", - "weights $\\omega$. This results in a penalized regression problem. The\n", + "weights $\\boldsymbol{\\beta}$. This results in a penalized regression problem. The\n", "cost function is given by" ] }, @@ -10820,76 +7449,39 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "\n", - "
\n", - "\n", - "$$\n", - "\\begin{equation}\n", - " C(X, \\omega; \\lambda) = ||X\\omega - y||^2 + \\lambda ||\\omega||^2\n", - " = (X\\omega - y)^T(X\\omega - y) + \\lambda \\omega^T\\omega.\n", - "\\label{_auto31} \\tag{49}\n", - "\\end{equation}\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "Finding the extremum of this function yields the weights" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "\n", - "
\n", - "\n", - "$$\n", - "\\begin{equation}\n", - " \\omega(\\lambda) = \\frac{X^Ty}{X^TX + \\lambda} \\to \\frac{\\omega_{\\text{LS}}}{1 + \\lambda},\n", - "\\label{_auto32} \\tag{50}\n", - "\\end{equation}\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "where $\\omega_{\\text{LS}}$ is the weights from ordinary least\n", - "squares. The last assumption assumes that $X$ is orthogonal, which it\n", - "is not. We will therefore resort to solving the equation as it stands\n", - "on the left hand side." + "1\n", + "8\n", + "9\n", + " \n", + "<\n", + "<\n", + "<\n", + "!\n", + "!\n", + "M\n", + "A\n", + "T\n", + "H\n", + "_\n", + "B\n", + "L\n", + "O\n", + "C\n", + "K" ] }, { "cell_type": "code", - "execution_count": 58, + "execution_count": 67, "metadata": { "collapsed": false }, "outputs": [], "source": [ - "def get_ridge_weights(x: np.ndarray, y: np.ndarray, _lambda: float) -> np.ndarray:\n", - " return x.T @ y @ scl.inv(\n", - " x.T @ x + np.eye(x.shape[1], x.shape[1]) * _lambda\n", - " )\n", - "lambda = 0.1\n", - "omega_ridge = get_ridge_weights(X_train_own, y_train, np.array([_lambda]))\n", + "_lambda = 0.1\n", "clf_ridge = skl.Ridge(alpha=_lambda).fit(X_train, y_train)\n", - "J_ridge_own = omega_ridge[1:].reshape(L, L)\n", "J_ridge_sk = clf_ridge.coef_.reshape(L, L)\n", "fig = plt.figure(figsize=(20, 14))\n", - "im = plt.imshow(J_ridge_own, **cmap_args)\n", - "plt.title(\"Home-made ridge regression\", fontsize=18)\n", - "plt.xticks(fontsize=18)\n", - "plt.yticks(fontsize=18)\n", - "cb = fig.colorbar(im)\n", - "cb.ax.set_yticklabels(cb.ax.get_yticklabels(), fontsize=18)\n", - "\n", - "fig = plt.figure(figsize=(20, 14))\n", "im = plt.imshow(J_ridge_sk, **cmap_args)\n", "plt.title(\"Ridge from Scikit-learn\", fontsize=18)\n", "plt.xticks(fontsize=18)\n", @@ -10914,14 +7506,12 @@ "metadata": {}, "source": [ "\n", - "
\n", + "
\n", "\n", "$$\n", "\\begin{equation}\n", - " C(X, \\omega; \\lambda) =\n", - " ||X\\omega - y||^2 + \\lambda ||\\omega||\n", - " = (X\\omega - y)^T(X\\omega - y) + \\lambda \\sqrt{\\omega^T\\omega}.\n", - "\\label{_auto33} \\tag{51}\n", + " C(\\boldsymbol{X}, \\boldsymbol{\\beta}; \\lambda) = (\\boldsymbol{X}\\boldsymbol{\\beta} - \\boldsymbol{y})^T(\\boldsymbol{X}\\boldsymbol{\\beta} - \\boldsymbol{y}) + \\lambda \\sqrt{\\boldsymbol{\\beta}^T\\boldsymbol{\\beta}}.\n", + "\\label{_auto22} \\tag{32}\n", "\\end{equation}\n", "$$" ] @@ -10930,12 +7520,12 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "Finding the extremal point of this cost function is not so straight-forward as in least squares and ridge. We will therefore rely solely on the function ``Lasso`` from Scikit-learn." + "Finding the extremal point of this cost function is not so straight-forward as in least squares and ridge. We will therefore rely solely on the function ``Lasso`` from **Scikit-Learn**." ] }, { "cell_type": "code", - "execution_count": 59, + "execution_count": 68, "metadata": { "collapsed": false }, @@ -10964,71 +7554,7 @@ "\n", "\n", "\n", - "## Performance of the different models\n", "\n", - "In order to judge which model performs best at varying values of $\\lambda$ (for ridge and LASSO) we compute $R^2$ which is given by" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "\n", - "
\n", - "\n", - "$$\n", - "\\begin{equation}\n", - " R^2 = 1 - \\frac{(y - \\hat{y})^2}{(y - \\bar{y})^2},\n", - "\\label{_auto34} \\tag{52}\n", - "\\end{equation}\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "where $y$ is a vector with the true values of the energy, $\\hat{y}$ is the predicted values of $y$ from the models and $\\bar{y}$ is the mean of $\\hat{y}$." - ] - }, - { - "cell_type": "code", - "execution_count": 60, - "metadata": { - "collapsed": false - }, - "outputs": [], - "source": [ - "def r_squared(y, y_hat):\n", - " return 1 - np.sum((y - y_hat) ** 2) / np.sum((y - np.mean(y_hat)) ** 2)" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "This is the same metric used by Scikit-learn for their regression models when scoring." - ] - }, - { - "cell_type": "code", - "execution_count": 61, - "metadata": { - "collapsed": false - }, - "outputs": [], - "source": [ - "y_hat = clf.predict(X_test)\n", - "r_test = r_squared(y_test, y_hat)\n", - "sk_r_test = clf.score(X_test, y_test)\n", - "\n", - "assert abs(r_test - sk_r_test) < 1e-2" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ "## Performance as function of the regularization parameter\n", "\n", "We see how the different models perform for a different set of values for $\\lambda$." @@ -11036,7 +7562,7 @@ }, { "cell_type": "code", - "execution_count": 62, + "execution_count": 69, "metadata": { "collapsed": false }, @@ -11045,17 +7571,13 @@ "lambdas = np.logspace(-4, 5, 10)\n", "\n", "train_errors = {\n", - " \"ols_own\": np.zeros(lambdas.size),\n", " \"ols_sk\": np.zeros(lambdas.size),\n", - " \"ridge_own\": np.zeros(lambdas.size),\n", " \"ridge_sk\": np.zeros(lambdas.size),\n", " \"lasso_sk\": np.zeros(lambdas.size)\n", "}\n", "\n", "test_errors = {\n", - " \"ols_own\": np.zeros(lambdas.size),\n", " \"ols_sk\": np.zeros(lambdas.size),\n", - " \"ridge_own\": np.zeros(lambdas.size),\n", " \"ridge_sk\": np.zeros(lambdas.size),\n", " \"lasso_sk\": np.zeros(lambdas.size)\n", "}\n", @@ -11065,30 +7587,6 @@ "fig = plt.figure(figsize=(32, 54))\n", "\n", "for i, _lambda in enumerate(tqdm.tqdm(lambdas)):\n", - " omega = get_ols_weights(X_train_own, y_train)\n", - " y_hat_train = X_train_own @ omega\n", - " y_hat_test = X_test_own @ omega\n", - "\n", - " train_errors[\"ols_own\"][i] = r_squared(y_train, y_hat_train)\n", - " test_errors[\"ols_own\"][i] = r_squared(y_test, y_hat_test)\n", - "\n", - " plt.subplot(10, 5, plot_counter)\n", - " plt.imshow(omega[1:].reshape(L, L), **cmap_args)\n", - " plt.title(\"Home made OLS\")\n", - " plot_counter += 1\n", - "\n", - " omega = get_ridge_weights(X_train_own, y_train, _lambda)\n", - " y_hat_train = X_train_own @ omega\n", - " y_hat_test = X_test_own @ omega\n", - "\n", - " train_errors[\"ridge_own\"][i] = r_squared(y_train, y_hat_train)\n", - " test_errors[\"ridge_own\"][i] = r_squared(y_test, y_hat_test)\n", - "\n", - " plt.subplot(10, 5, plot_counter)\n", - " plt.imshow(omega[1:].reshape(L, L), **cmap_args)\n", - " plt.title(r\"Home made ridge, $\\lambda = %.4f$\" % _lambda)\n", - " plot_counter += 1\n", - "\n", " for key, method in zip(\n", " [\"ols_sk\", \"ridge_sk\", \"lasso_sk\"],\n", " [skl.LinearRegression(), skl.Ridge(alpha=_lambda), skl.Lasso(alpha=_lambda)]\n", @@ -11112,7 +7610,7 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "We can see that LASSO quite fast reaches a good solution for low\n", + "We see that LASSO reaches a good solution for low\n", "values of $\\lambda$, but will \"wither\" when we increase $\\lambda$ too\n", "much. Ridge is more stable over a larger range of values for\n", "$\\lambda$, but eventually also fades away.\n", @@ -11130,7 +7628,7 @@ }, { "cell_type": "code", - "execution_count": 63, + "execution_count": 70, "metadata": { "collapsed": false }, @@ -11139,8 +7637,6 @@ "fig = plt.figure(figsize=(20, 14))\n", "\n", "colors = {\n", - " \"ols_own\": \"b\",\n", - " \"ridge_own\": \"g\",\n", " \"ols_sk\": \"r\",\n", " \"ridge_sk\": \"y\",\n", " \"lasso_sk\": \"c\"\n", @@ -11163,9 +7659,6 @@ " label=\"Test {0}\".format(key),\n", " linewidth=4.0\n", " )\n", - "#plt.semilogx(lambdas, train_errors[\"ols_own\"], label=\"Train (OLS own)\")\n", - "#plt.semilogx(lambdas, test_errors[\"ols_own\"], label=\"Test (OLS own)\")\n", - "\n", "plt.legend(loc=\"best\", fontsize=18)\n", "plt.xlabel(r\"$\\lambda$\", fontsize=18)\n", "plt.ylabel(r\"$R^2$\", fontsize=18)\n", @@ -11178,13 +7671,1459 @@ "metadata": {}, "source": [ "From the above figure we can see that LASSO with $\\lambda = 10^{-2}$\n", - "achieve a very good accuracy on the test set. This by far surpases the\n", + "achieves a very good accuracy on the test set. This by far surpasses the\n", "other models for all values of $\\lambda$.\n", "\n", "\n", "\n", - "# Optimization and Gradient Methods\n", "\n", + "## Further Exercises\n", + "\n", + "### Exercise 1\n", + "\n", + "We will generate our own dataset for a function $y(x)$ where $x \\in [0,1]$ and defined by random numbers computed with the uniform distribution. The function $y$ is a quadratic polynomial in $x$ with added stochastic noise according to the normal distribution $\\cal {N}(0,1)$.\n", + "The following simple Python instructions define our $x$ and $y$ values (with 100 data points)." + ] + }, + { + "cell_type": "code", + "execution_count": 71, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "x = np.random.rand(100,1)\n", + "y = 5*x*x+0.1*np.random.randn(100,1)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "1. Write your own code (following the examples above) for computing the parametrization of the data set fitting a second-order polynomial. \n", + "\n", + "2. Use thereafter **scikit-learn** (see again the examples in the regression slides) and compare with your own code. \n", + "\n", + "3. Using scikit-learn, compute also the mean square error, a risk metric corresponding to the expected value of the squared (quadratic) error defined as" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "$$\n", + "MSE(\\hat{y},\\hat{\\tilde{y}}) = \\frac{1}{n}\n", + "\\sum_{i=0}^{n-1}(y_i-\\tilde{y}_i)^2,\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "and the $R^2$ score function.\n", + "If $\\tilde{\\hat{y}}_i$ is the predicted value of the $i-th$ sample and $y_i$ is the corresponding true value, then the score $R^2$ is defined as" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "$$\n", + "R^2(\\hat{y}, \\tilde{\\hat{y}}) = 1 - \\frac{\\sum_{i=0}^{n - 1} (y_i - \\tilde{y}_i)^2}{\\sum_{i=0}^{n - 1} (y_i - \\bar{y})^2},\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "where we have defined the mean value of $\\hat{y}$ as" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "$$\n", + "\\bar{y} = \\frac{1}{n} \\sum_{i=0}^{n - 1} y_i.\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "You can use the functionality included in scikit-learn. If you feel\n", + "for it, you can use your own program and define functions which\n", + "compute the above two functions. Discuss the meaning of these\n", + "results. Try also to vary the coefficient in front of the added\n", + "stochastic noise term and discuss the quality of the fits.\n", + "\n", + "\n", + "\n", + "\n", + "### Exercise 2, variance of the parameters $\\beta$ in linear regression\n", + "\n", + "Show that the variance of the parameters $\\beta$ in the linear regression method (chapter 3, equation (3.8) of [Trevor Hastie, Robert Tibshirani, Jerome H. Friedman, The Elements of Statistical Learning, Springer](https://www.springer.com/gp/book/9780387848570)) is given as" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "$$\n", + "\\mathrm{Var}(\\hat{\\beta}) = \\left(\\hat{X}^T\\hat{X}\\right)^{-1}\\sigma^2,\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "with" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "$$\n", + "\\sigma^2 = \\frac{1}{N-p-1}\\sum_{i=1}^{N} (y_i-\\tilde{y}_i)^2,\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "where we have assumed that we fit a function of degree $p-1$ (for example a polynomial in $x$). \n", + "\n", + "\n", + "\n", + "### Exercise 3\n", + "\n", + "This exercise is a continuation of exercise 1. We will\n", + "use the same function to generate our data set, still staying with a\n", + "simple function $y(x)$ which we want to fit using linear regression,\n", + "but now extending the analysis to include the Ridge and the Lasso\n", + "regression methods. You can use the code under the Regression as an example on how to use the Ridge and the Lasso methods.\n", + "\n", + "We will thus again generate our own dataset for a function $y(x)$ where \n", + "$x \\in [0,1]$ and defined by random numbers computed with the uniform\n", + "distribution. The function $y$ is a quadratic polynomial in $x$ with\n", + "added stochastic noise according to the normal distribution $\\cal{N}(0,1)$.\n", + "\n", + "The following simple Python instructions define our $x$ and $y$ values (with 100 data points)." + ] + }, + { + "cell_type": "code", + "execution_count": 72, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "x = np.random.rand(100,1)\n", + "y = 5*x*x+0.1*np.random.randn(100,1)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "1. Write your own code for the Ridge method and compute the parametrization for different values of $\\lambda$. Compare and analyze your results with those from exercise 1. Study the dependence on $\\lambda$ while also varying the strength of the noise in your expression for $y(x)$. \n", + "\n", + "2. Repeat the above but using the functionality of **scikit-learn**. Compare your code with the results from **scikit-learn**. Remember to run with the same random numbers for generating $x$ and $y$. \n", + "\n", + "3. Our next step is to study the variance of the parameters $\\beta_1$ and $\\beta_2$ (assuming that we are parametrizing our function with a second-order polynomial. We will use standard linear regression and the Ridge regression. You can now opt for either writing your own function that calculates the variance of these paramaters (recall that this is equal to the diagonal elements of the matrix $(\\hat{X}^T\\hat{X})+\\lambda\\hat{I})^{-1}$) or use the functionality of **scikit-learn** and compute their variances. Discuss the results of these variances as functions \n", + "\n", + "4. Repeat the previous step but add now the Lasso method. Discuss your results and compare with standard regression and the Ridge regression results.\n", + "\n", + "5. Try to implement the cross-validation as well. \n", + "\n", + "6. Finally, using **scikit-learn** or your own code, compute also the mean square error, a risk metric corresponding to the expected value of the squared (quadratic) error defined as" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "$$\n", + "MSE(\\hat{y},\\hat{\\tilde{y}}) = \\frac{1}{n}\n", + "\\sum_{i=0}^{n-1}(y_i-\\tilde{y}_i)^2,\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "and the $R^2$ score function.\n", + "If $\\tilde{\\hat{y}}_i$ is the predicted value of the $i-th$ sample and $y_i$ is the corresponding true value, then the score $R^2$ is defined as" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "$$\n", + "R^2(\\hat{y}, \\tilde{\\hat{y}}) = 1 - \\frac{\\sum_{i=0}^{n - 1} (y_i - \\tilde{y}_i)^2}{\\sum_{i=0}^{n - 1} (y_i - \\bar{y})^2},\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "where we have defined the mean value of $\\hat{y}$ as" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "$$\n", + "\\bar{y} = \\frac{1}{n} \\sum_{i=0}^{n - 1} y_i.\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Discuss these quantities as functions of the variable $\\lambda$ in the Ridge and Lasso regression methods. \n", + "\n", + "### Exercise 4\n", + "\n", + "We will study how\n", + "to fit polynomials to a specific two-dimensional function called\n", + "[Franke's\n", + "function](http://www.dtic.mil/dtic/tr/fulltext/u2/a081688.pdf). This\n", + "is a function which has been widely used when testing various interpolation and fitting\n", + "algorithms. Furthermore, after having established the model and the\n", + "method, we will employ resamling techniques such as the cross-validation and/or\n", + "the bootstrap methods, in order to perform a proper assessment of our models.\n", + "\n", + "\n", + "The Franke function, which is a weighted sum of four exponentials reads as follows" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "$$\n", + "\\begin{align*}\n", + "f(x,y) &= \\frac{3}{4}\\exp{\\left(-\\frac{(9x-2)^2}{4} - \\frac{(9y-2)^2}{4}\\right)}+\\frac{3}{4}\\exp{\\left(-\\frac{(9x+1)^2}{49}- \\frac{(9y+1)}{10}\\right)} \\\\\n", + "&+\\frac{1}{2}\\exp{\\left(-\\frac{(9x-7)^2}{4} - \\frac{(9y-3)^2}{4}\\right)} -\\frac{1}{5}\\exp{\\left(-(9x-4)^2 - (9y-7)^2\\right) }.\n", + "\\end{align*}\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "The function will be defined for $x,y\\in [0,1]$. Our first step will\n", + "be to perform an OLS regression analysis of this function, trying out\n", + "a polynomial fit with an $x$ and $y$ dependence of the form $[x, y,\n", + "x^2, y^2, xy, \\dots]$. We will also include cross-validation and\n", + "bootstrap as resampling techniques. As in homeworks 1 and 2, we\n", + "can use a uniform distribution to set up the arrays of values for $x$\n", + "and $y$, or as in the example below just a fix values for $x$ and $y$ with a given step size.\n", + "In this case we will have two predictors and need to fit a\n", + "function (for example a polynomial) of $x$ and $y$. Thereafter we will\n", + "repeat much of the same procedure using the the Ridge and\n", + "Lasso regression methods, introducing thus a dependence on the bias\n", + "(penalty) $\\lambda$.\n", + "\n", + "\n", + "The Python function for the Franke function is included here (it performs also a three-dimensional plot of it)" + ] + }, + { + "cell_type": "code", + "execution_count": 73, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "from mpl_toolkits.mplot3d import Axes3D\n", + "import matplotlib.pyplot as plt\n", + "from matplotlib import cm\n", + "from matplotlib.ticker import LinearLocator, FormatStrFormatter\n", + "import numpy as np\n", + "from random import random, seed\n", + "\n", + "fig = plt.figure()\n", + "ax = fig.gca(projection='3d')\n", + "\n", + "# Make data.\n", + "x = np.arange(0, 1, 0.05)\n", + "y = np.arange(0, 1, 0.05)\n", + "x, y = np.meshgrid(x,y)\n", + "\n", + "\n", + "def FrankeFunction(x,y):\n", + " term1 = 0.75*np.exp(-(0.25*(9*x-2)**2) - 0.25*((9*y-2)**2))\n", + " term2 = 0.75*np.exp(-((9*x+1)**2)/49.0 - 0.1*(9*y+1))\n", + " term3 = 0.5*np.exp(-(9*x-7)**2/4.0 - 0.25*((9*y-3)**2))\n", + " term4 = -0.2*np.exp(-(9*x-4)**2 - (9*y-7)**2)\n", + " return term1 + term2 + term3 + term4\n", + "\n", + "\n", + "z = FrankeFunction(x, y)\n", + "\n", + "# Plot the surface.\n", + "surf = ax.plot_surface(x, y, z, cmap=cm.coolwarm,\n", + " linewidth=0, antialiased=False)\n", + "\n", + "# Customize the z axis.\n", + "ax.set_zlim(-0.10, 1.40)\n", + "ax.zaxis.set_major_locator(LinearLocator(10))\n", + "ax.zaxis.set_major_formatter(FormatStrFormatter('%.02f'))\n", + "\n", + "# Add a color bar which maps values to colors.\n", + "fig.colorbar(surf, shrink=0.5, aspect=5)\n", + "\n", + "plt.show()" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "We will thus again generate our own dataset for a function $\\mathrm{FrankeFunction}(x,y)$ where \n", + "$x,y \\in [0,1]$ could be defined by random numbers computed with the uniform\n", + "distribution. The function $f(x,y)$ is the Franke function. You should explore also the addition\n", + "an added stochastic noise to this function using the normal distribution $\\cal{N}(0,1)$.\n", + "\n", + "Write your own code (using either a matrix inversion or a singular value decomposition from e.g., **numpy** ) or use your code from exercises 1 and 3\n", + "and perform a standard least square regression analysis using polynomials in $x$ and $y$ up to fifth order. Find the confidence intervals of the parameters $\\beta$ by computing their variances, evaluate the Mean Squared error (MSE)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "$$\n", + "MSE(\\hat{y},\\hat{\\tilde{y}}) = \\frac{1}{n}\n", + "\\sum_{i=0}^{n-1}(y_i-\\tilde{y}_i)^2,\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "and the $R^2$ score function.\n", + "If $\\tilde{\\hat{y}}_i$ is the predicted value of the $i-th$ sample and $y_i$ is the corresponding true value, then the score $R^2$ is defined as" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "$$\n", + "R^2(\\hat{y}, \\tilde{\\hat{y}}) = 1 - \\frac{\\sum_{i=0}^{n - 1} (y_i - \\tilde{y}_i)^2}{\\sum_{i=0}^{n - 1} (y_i - \\bar{y})^2},\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "where we have defined the mean value of $\\hat{y}$ as" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "$$\n", + "\\bar{y} = \\frac{1}{n} \\sum_{i=0}^{n - 1} y_i.\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Perform a resampling of the data where you split the data in training data and test data. Implement the $k$-fold cross-validation algorithm and/or the bootstrap algorithm\n", + "and evaluate again the MSE and the $R^2$ functions resulting from the test data. Evaluate also the bias and variance of the final models.\n", + "\n", + "\n", + "Write then your own code for the Ridge method, either using matrix\n", + "inversion or the singular value decomposition as done for standard OLS. Perform the same analysis as in the\n", + "previous exercise (for the same polynomials and include resampling\n", + "techniques) but now for different values of $\\lambda$. Compare and\n", + "analyze your results with those obtained with standard OLS. Study the\n", + "dependence on $\\lambda$ while also varying eventually the strength of\n", + "the noise in your expression for $\\mathrm{FrankeFunction}(x,y)$.\n", + "\n", + "Then perform the same studies but now with Lasso regression. Use the functionalities of\n", + "**scikit-learn**. Give a critical discussion of the three methods and a\n", + "judgement of which model fits the data best.\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "# Logistic Regression\n", + "\n", + "In linear regression our main interest was centered on learning the\n", + "coefficients of a functional fit (say a polynomial) in order to be\n", + "able to predict the response of a continuous variable on some unseen\n", + "data. The fit to the continuous variable $y_i$ is based on some\n", + "independent variables $\\hat{x}_i$. Linear regression resulted in\n", + "analytical expressions (in terms of matrices to invert) for several\n", + "quantities, ranging from the variance and thereby the confidence\n", + "intervals of the parameters $\\hat{\\beta}$ to the mean squared\n", + "error. If we can invert the product of the design matrices, linear\n", + "regression gives then a simple recipe for fitting our data.\n", + "\n", + "\n", + "Classification problems, however, are concerned with outcomes taking\n", + "the form of discrete variables (i.e. categories). We may for example,\n", + "on the basis of DNA sequencing for a number of patients, like to find\n", + "out which mutations are important for a certain disease; or based on\n", + "scans of various patients' brains, figure out if there is a tumor or\n", + "not; or given a specific physical system, we'd like to identify its\n", + "state, say whether it is an ordered or disordered system (typical\n", + "situation in solid state physics); or classify the status of a\n", + "patient, whether she/he has a stroke or not and many other similar\n", + "situations.\n", + "\n", + "The most common situation we encounter when we apply logistic\n", + "regression is that of two possible outcomes, normally denoted as a\n", + "binary outcome, true or false, positive or negative, success or\n", + "failure etc.\n", + "\n", + "\n", + "## Optimization and Deep learning\n", + "\n", + "Logistic regression will also serve as our stepping stone towards neural\n", + "network algorithms and supervised deep learning. For logistic\n", + "learning, the minimization of the cost function leads to a non-linear\n", + "equation in the parameters $\\hat{\\beta}$. The optmization of the problem calls therefore for minimization algorithms. This forms the bottle neck of all machine learning algorithms, namely how to find reliable minima of a multi-variable function. This leads us to the family of gradient descent methods. The latter are the working horses of basically all modern machine learning algorithms. \n", + "\n", + "We note also that many of the topics discussed here \n", + "regression are also commonly used in modern supervised Deep Learning\n", + "models, as we will see later.\n", + "\n", + "\n", + "\n", + "## Basics\n", + "\n", + "We consider the case where the dependent variables, also called the\n", + "responses or the outcomes, $y_i$ are discrete and only take values\n", + "from $k=0,\\dots,K-1$ (i.e. $K$ classes).\n", + "\n", + "The goal is to predict the\n", + "output classes from the design matrix $\\hat{X}\\in\\mathbb{R}^{n\\times p}$\n", + "made of $n$ samples, each of which carries $p$ features or predictors. The\n", + "primary goal is to identify the classes to which new unseen samples\n", + "belong.\n", + "\n", + "Let us specialize to the case of two classes only, with outputs $y_i=0$ and $y_i=1$. Our outcomes could represent the status of a credit card user who could default or not on her/his credit card debt. That is" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "$$\n", + "y_i = \\begin{bmatrix} 0 & \\mathrm{no}\\\\ 1 & \\mathrm{yes} \\end{bmatrix}.\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Before moving to the logistic model, let us try to use our linear regression model to classify these two outcomes. We could for example fit a linear model to the default case if $y_i > 0.5$ and the no default case $y_i \\leq 0.5$. \n", + "\n", + "We would then have our \n", + "weighted linear combination, namely" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + "
\n", + "\n", + "$$\n", + "\\begin{equation}\n", + "\\hat{y} = \\hat{X}^T\\hat{\\beta} + \\hat{\\epsilon},\n", + "\\label{_auto23} \\tag{33}\n", + "\\end{equation}\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "where $\\hat{y}$ is a vector representing the possible outcomes, $\\hat{X}$ is our\n", + "$n\\times p$ design matrix and $\\hat{\\beta}$ represents our estimators/predictors.\n", + "\n", + "\n", + "The main problem with our function is that it \n", + "takes values on the entire real axis. In the case of\n", + "logistic regression, however, the labels $y_i$ are discrete\n", + "variables. \n", + "\n", + "One simple way to get a discrete output is to have sign\n", + "functions that map the output of a linear regressor to values $\\{0,1\\}$,\n", + "$f(s_i)=sign(s_i)=1$ if $s_i\\ge 0$ and 0 if otherwise. \n", + "We will encounter this model in our first demonstration of neural networks. Historically it is called the \"perceptron\" model in the machine learning\n", + "literature. This model is extremely simple. However, in many cases it is more\n", + "favorable to use a ``soft\" classifier that outputs\n", + "the probability of a given category. This leads us to the logistic function.\n", + "\n", + "The code for plotting the perceptron can be seen here. This si nothing but the standard [Heaviside step function](https://en.wikipedia.org/wiki/Heaviside_step_function)." + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "The perceptron is an example of a ``hard classification\" model. We\n", + "will encounter this model when we discuss neural networks as\n", + "well. Each datapoint is deterministically assigned to a category (i.e\n", + "$y_i=0$ or $y_i=1$). In many cases, it is favorable to have a \"soft\"\n", + "classifier that outputs the probability of a given category rather\n", + "than a single value. For example, given $x_i$, the classifier\n", + "outputs the probability of being in a category $k$. Logistic regression\n", + "is the most common example of a so-called soft classifier. In logistic\n", + "regression, the probability that a data point $x_i$\n", + "belongs to a category $y_i=\\{0,1\\}$ is given by the so-called logit function (or Sigmoid) which is meant to represent the likelihood for a given event," + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "$$\n", + "p(t) = \\frac{1}{1+\\mathrm \\exp{-t}}=\\frac{\\exp{t}}{1+\\mathrm \\exp{t}}.\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Note that $1-p(t)= p(-t)$.\n", + "The following code plots the logistic function." + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "We assume now that we have two classes with $y_i$ either $0$ or $1$. Furthermore we assume also that we have only two parameters $\\beta$ in our fitting of the Sigmoid function, that is we define probabilities" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "$$\n", + "\\begin{align*}\n", + "p(y_i=1|x_i,\\hat{\\beta}) &= \\frac{\\exp{(\\beta_0+\\beta_1x_i)}}{1+\\exp{(\\beta_0+\\beta_1x_i)}},\\nonumber\\\\\n", + "p(y_i=0|x_i,\\hat{\\beta}) &= 1 - p(y_i=1|x_i,\\hat{\\beta}),\n", + "\\end{align*}\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "where $\\hat{\\beta}$ are the weights we wish to extract from data, in our case $\\beta_0$ and $\\beta_1$. \n", + "\n", + "Note that we used" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "$$\n", + "p(y_i=0\\vert x_i, \\hat{\\beta}) = 1-p(y_i=1\\vert x_i, \\hat{\\beta}).\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Maximum likelihood\n", + "\n", + "In order to define the total likelihood for all possible outcomes from a \n", + "dataset $\\mathcal{D}=\\{(y_i,x_i)\\}$, with the binary labels\n", + "$y_i\\in\\{0,1\\}$ and where the data points are drawn independently, we use the so-called [Maximum Likelihood Estimation](https://en.wikipedia.org/wiki/Maximum_likelihood_estimation) (MLE) principle. \n", + "We aim thus at maximizing \n", + "the probability of seeing the observed data. We can then approximate the \n", + "likelihood in terms of the product of the individual probabilities of a specific outcome $y_i$, that is" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "$$\n", + "\\begin{align*}\n", + "P(\\mathcal{D}|\\hat{\\beta})& = \\prod_{i=1}^n \\left[p(y_i=1|x_i,\\hat{\\beta})\\right]^{y_i}\\left[1-p(y_i=1|x_i,\\hat{\\beta}))\\right]^{1-y_i}\\nonumber \\\\\n", + "\\end{align*}\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "from which we obtain the log-likelihood and our **cost/loss** function" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "$$\n", + "\\mathcal{C}(\\hat{\\beta}) = \\sum_{i=1}^n \\left( y_i\\log{p(y_i=1|x_i,\\hat{\\beta})} + (1-y_i)\\log\\left[1-p(y_i=1|x_i,\\hat{\\beta}))\\right]\\right).\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## The cost function rewritten\n", + "\n", + "Reordering the logarithms, we can rewrite the **cost/loss** function as" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "$$\n", + "\\mathcal{C}(\\hat{\\beta}) = \\sum_{i=1}^n \\left(y_i(\\beta_0+\\beta_1x_i) -\\log{(1+\\exp{(\\beta_0+\\beta_1x_i)})}\\right).\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "The maximum likelihood estimator is defined as the set of parameters that maximize the log-likelihood where we maximize with respect to $\\beta$.\n", + "Since the cost (error) function is just the negative log-likelihood, for logistic regression we have that" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "$$\n", + "\\mathcal{C}(\\hat{\\beta})=-\\sum_{i=1}^n \\left(y_i(\\beta_0+\\beta_1x_i) -\\log{(1+\\exp{(\\beta_0+\\beta_1x_i)})}\\right).\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "This equation is known in statistics as the **cross entropy**. Finally, we note that just as in linear regression, \n", + "in practice we often supplement the cross-entropy with additional regularization terms, usually $L_1$ and $L_2$ regularization as we did for Ridge and Lasso regression.\n", + "\n", + "\n", + "The cross entropy is a convex function of the weights $\\hat{\\beta}$ and,\n", + "therefore, any local minimizer is a global minimizer. \n", + "\n", + "\n", + "Minimizing this\n", + "cost function with respect to the two parameters $\\beta_0$ and $\\beta_1$ we obtain" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "$$\n", + "\\frac{\\partial \\mathcal{C}(\\hat{\\beta})}{\\partial \\beta_0} = -\\sum_{i=1}^n \\left(y_i -\\frac{\\exp{(\\beta_0+\\beta_1x_i)}}{1+\\exp{(\\beta_0+\\beta_1x_i)}}\\right),\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "and" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "$$\n", + "\\frac{\\partial \\mathcal{C}(\\hat{\\beta})}{\\partial \\beta_1} = -\\sum_{i=1}^n \\left(y_ix_i -x_i\\frac{\\exp{(\\beta_0+\\beta_1x_i)}}{1+\\exp{(\\beta_0+\\beta_1x_i)}}\\right).\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Let us now define a vector $\\hat{y}$ with $n$ elements $y_i$, an\n", + "$n\\times p$ matrix $\\hat{X}$ which contains the $x_i$ values and a\n", + "vector $\\hat{p}$ of fitted probabilities $p(y_i\\vert x_i,\\hat{\\beta})$. We can rewrite in a more compact form the first\n", + "derivative of cost function as" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "$$\n", + "\\frac{\\partial \\mathcal{C}(\\hat{\\beta})}{\\partial \\hat{\\beta}} = -\\hat{X}^T\\left(\\hat{y}-\\hat{p}\\right).\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "If we in addition define a diagonal matrix $\\hat{W}$ with elements \n", + "$p(y_i\\vert x_i,\\hat{\\beta})(1-p(y_i\\vert x_i,\\hat{\\beta})$, we can obtain a compact expression of the second derivative as" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "$$\n", + "\\frac{\\partial^2 \\mathcal{C}(\\hat{\\beta})}{\\partial \\hat{\\beta}\\partial \\hat{\\beta}^T} = \\hat{X}^T\\hat{W}\\hat{X}.\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Extending to more predictors\n", + "\n", + "Within a binary classification problem, we can easily expand our model to include multiple predictors. Our ratio between likelihoods is then with $p$ predictors" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "$$\n", + "\\log{ \\frac{p(\\hat{\\beta}\\hat{x})}{1-p(\\hat{\\beta}\\hat{x})}} = \\beta_0+\\beta_1x_1+\\beta_2x_2+\\dots+\\beta_px_p.\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Here we defined $\\hat{x}=[1,x_1,x_2,\\dots,x_p]$ and $\\hat{\\beta}=[\\beta_0, \\beta_1, \\dots, \\beta_p]$ leading to" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "$$\n", + "p(\\hat{\\beta}\\hat{x})=\\frac{ \\exp{(\\beta_0+\\beta_1x_1+\\beta_2x_2+\\dots+\\beta_px_p)}}{1+\\exp{(\\beta_0+\\beta_1x_1+\\beta_2x_2+\\dots+\\beta_px_p)}}.\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Till now we have mainly focused on two classes, the so-called binary system. Suppose we wish to extend to $K$ classes.\n", + "Let us for the sake of simplicity assume we have only two predictors. We have then following model" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "2\n", + "1\n", + "8\n", + " \n", + "<\n", + "<\n", + "<\n", + "!\n", + "!\n", + "M\n", + "A\n", + "T\n", + "H\n", + "_\n", + "B\n", + "L\n", + "O\n", + "C\n", + "K" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "$$\n", + "\\log{\\frac{p(C=2\\vert x)}{p(K\\vert x)}} = \\beta_{20}+\\beta_{21}x_1,\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "and so on till the class $C=K-1$ class" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "$$\n", + "\\log{\\frac{p(C=K-1\\vert x)}{p(K\\vert x)}} = \\beta_{(K-1)0}+\\beta_{(K-1)1}x_1,\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "and the model is specified in term of $K-1$ so-called log-odds or **logit** transformations.\n", + "\n", + "\n", + "\n", + "## The Softmax function\n", + "\n", + "In our discussion of neural networks we will encounter the above again in terms of the so-called **Softmax** function.\n", + "\n", + "The softmax function is used in various multiclass classification\n", + "methods, such as multinomial logistic regression (also known as\n", + "softmax regression), multiclass linear discriminant\n", + "analysis, naive Bayes classifiers, and artificial neural networks.\n", + "Specifically, in multinomial logistic regression and linear\n", + "discriminant analysis, the input to the function is the result of $K$\n", + "distinct linear functions, and the predicted probability for the $k$-th\n", + "class given a sample vector $\\hat{x}$ and a weighting vector $\\hat{\\beta}$ is (with two predictors):" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "$$\n", + "p(C=k\\vert \\mathbf {x} )=\\frac{\\exp{(\\beta_{k0}+\\beta_{k1}x_1)}}{1+\\sum_{l=1}^{K-1}\\exp{(\\beta_{l0}+\\beta_{l1}x_1)}}.\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "It is easy to extend to more predictors. The final class is" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "$$\n", + "p(C=K\\vert \\mathbf {x} )=\\frac{1}{1+\\sum_{l=1}^{K-1}\\exp{(\\beta_{l0}+\\beta_{l1}x_1)}},\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "and they sum to one. Our earlier discussions were all specialized to the case with two classes only. It is easy to see from the above that what we derived earlier is compatible with these equations. \n", + "\n", + "To find the optimal parameters we would typically use a gradient descent method.\n", + "Newton's method and gradient descent methods are discussed in the material on [optimization methods](https://compphysics.github.io/MachineLearning/doc/pub/Splines/html/Splines-bs.html). \n", + "\n", + "\n", + "\n", + "\n", + "## A **scikit-learn** example" + ] + }, + { + "cell_type": "code", + "execution_count": 74, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "import numpy as np\n", + "import matplotlib.pyplot as plt\n", + "from sklearn import datasets\n", + "iris = datasets.load_iris()\n", + "list(iris.keys())\n", + "['data', 'target_names', 'feature_names', 'target', 'DESCR']\n", + "X = iris[\"data\"][:, 3:] # petal width\n", + "y = (iris[\"target\"] == 2).astype(np.int) # 1 if Iris-Virginica, else 0\n", + "\n", + "from sklearn.linear_model import LogisticRegression\n", + "log_reg = LogisticRegression()\n", + "log_reg.fit(X, y)\n", + "\n", + "X_new = np.linspace(0, 3, 1000).reshape(-1, 1)\n", + "y_proba = log_reg.predict_proba(X_new)\n", + "plt.plot(X_new, y_proba[:, 1], \"g-\", label=\"Iris-Virginica\")\n", + "plt.plot(X_new, y_proba[:, 0], \"b--\", label=\"Not Iris-Virginica\")\n", + "plt.show()" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## A simple classification problem" + ] + }, + { + "cell_type": "code", + "execution_count": 75, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "import numpy as np\n", + "from sklearn import datasets, linear_model\n", + "import matplotlib.pyplot as plt\n", + "\n", + "\n", + "def generate_data():\n", + " np.random.seed(0)\n", + " X, y = datasets.make_moons(200, noise=0.20)\n", + " return X, y\n", + "\n", + "\n", + "def visualize(X, y, clf):\n", + " # plt.scatter(X[:, 0], X[:, 1], s=40, c=y, cmap=plt.cm.Spectral)\n", + " # plt.show()\n", + " plot_decision_boundary(lambda x: clf.predict(x), X, y)\n", + " plt.title(\"Logistic Regression\")\n", + "\n", + "\n", + "def plot_decision_boundary(pred_func, X, y):\n", + " # Set min and max values and give it some padding\n", + " x_min, x_max = X[:, 0].min() - .5, X[:, 0].max() + .5\n", + " y_min, y_max = X[:, 1].min() - .5, X[:, 1].max() + .5\n", + " h = 0.01\n", + " # Generate a grid of points with distance h between them\n", + " xx, yy = np.meshgrid(np.arange(x_min, x_max, h), np.arange(y_min, y_max, h))\n", + " # Predict the function value for the whole gid\n", + " Z = pred_func(np.c_[xx.ravel(), yy.ravel()])\n", + " Z = Z.reshape(xx.shape)\n", + " # Plot the contour and training examples\n", + " plt.contourf(xx, yy, Z, cmap=plt.cm.Spectral)\n", + " plt.scatter(X[:, 0], X[:, 1], c=y, cmap=plt.cm.Spectral)\n", + " plt.show()\n", + "\n", + "\n", + "def classify(X, y):\n", + " clf = linear_model.LogisticRegressionCV()\n", + " clf.fit(X, y)\n", + " return clf\n", + "\n", + "\n", + "def main():\n", + " X, y = generate_data()\n", + " # visualize(X, y)\n", + " clf = classify(X, y)\n", + " visualize(X, y, clf)\n", + "\n", + "\n", + "if __name__ == \"__main__\":\n", + " main()" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## The two-dimensional Ising model, Predicting phase transition of the two-dimensional Ising model\n", + "\n", + "The Hamiltonian of the two-dimensional Ising model without an external field for a constant coupling constant $J$ is given by" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + "
\n", + "\n", + "$$\n", + "\\begin{equation}\n", + " H = -J \\sum_{\\langle ij\\rangle} S_i S_j,\n", + "\\label{_auto24} \\tag{34}\n", + "\\end{equation}\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "where $S_i \\in \\{-1, 1\\}$ and $\\langle ij \\rangle$ signifies that we only iterate over the nearest neighbors in the lattice. We will be looking at a system of $L = 40$ spins in each dimension, i.e., $L^2 = 1600$ spins in total. Opposed to the one-dimensional Ising model we will get a phase transition from an **ordered** phase to a **disordered** phase at the critical temperature" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + "
\n", + "\n", + "$$\n", + "\\begin{equation}\n", + " \\frac{T_c}{J} = \\frac{2}{\\log\\left(1 + \\sqrt{2}\\right)} \\approx 2.26,\n", + "\\label{_auto25} \\tag{35}\n", + "\\end{equation}\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "as shown by Lars Onsager.\n", + "\n", + "\n", + "Here we use **logistic regression** to predict when a phase transition\n", + "occurs. The data we will look at is a set of spin configurations,\n", + "i.e., individual lattices with spins, labeled **ordered** `1` or\n", + "**disordered** `0`. Our job is to build a model which will take in a\n", + "spin configuration and predict whether or not the spin configuration\n", + "constitutes an ordered or a disordered phase. To achieve this we will\n", + "represent the lattices as flattened arrays with $1600$ elements\n", + "instead of a matrix of $40 \\times 40$ elements. As an extra test of\n", + "the performance of the algorithms we will divide the dataset into\n", + "three pieces. We will do a conventional train-test-split on a\n", + "combination of totally ordered and totally disordered phases. The\n", + "remaining \"critical-like\" states will be used as test data which we\n", + "hope the model will be able to make good extrapolated predictions on." + ] + }, + { + "cell_type": "code", + "execution_count": 76, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "import pickle\n", + "import os\n", + "import glob\n", + "import numpy as np\n", + "import pandas as pd\n", + "import matplotlib.pyplot as plt\n", + "import seaborn as sns\n", + "import sklearn.model_selection as skms\n", + "import sklearn.linear_model as skl\n", + "import sklearn.metrics as skm\n", + "import tqdm\n", + "import copy\n", + "import time\n", + "from IPython.display import display\n", + "\n", + "%matplotlib inline\n", + "\n", + "sns.set(color_codes=True)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Using the data from [Mehta et al.](https://physics.bu.edu/~pankajm/ML-Review-Datasets/isingMC/) (specifically the two datasets named `Ising2DFM_reSample_L40_T=All.pkl` and `Ising2DFM_reSample_L40_T=All_labels.pkl`) we have to unpack the data into numpy arrays." + ] + }, + { + "cell_type": "code", + "execution_count": 77, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "filenames = glob.glob(os.path.join(\"..\", \"dat\", \"*\"))\n", + "label_filename = list(filter(lambda x: \"label\" in x, filenames))[0]\n", + "dat_filename = list(filter(lambda x: \"label\" not in x, filenames))[0]\n", + "\n", + "# Read in the labels\n", + "with open(label_filename, \"rb\") as f:\n", + " labels = pickle.load(f)\n", + "\n", + "# Read in the corresponding configurations\n", + "with open(dat_filename, \"rb\") as f:\n", + " data = np.unpackbits(pickle.load(f)).reshape(-1, 1600).astype(\"int\")\n", + "\n", + "# Set spin-down to -1\n", + "data[data == 0] = -1" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "This dataset consists of $10000$ samples, i.e., $10000$ spin\n", + "configurations with $40 \\times 40$ spins each, for $16$ temperatures\n", + "between $0.25$ to $4.0$. Next we create a train/test-split and keep\n", + "the data in the critical phase as a separate dataset for\n", + "extrapolation-testing." + ] + }, + { + "cell_type": "code", + "execution_count": 78, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "# Set up slices of the dataset\n", + "ordered = slice(0, 70000)\n", + "critical = slice(70000, 100000)\n", + "disordered = slice(100000, 160000)\n", + "\n", + "X_train, X_test, y_train, y_test = skms.train_test_split(\n", + " np.concatenate((data[ordered], data[disordered])),\n", + " np.concatenate((labels[ordered], labels[disordered])),\n", + " test_size=0.95\n", + ")" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Logistic regression\n", + "\n", + "Logistic regression is a linear model for classification. Recalling\n", + "the cost function for ordinary least squares with both L2 (ridge) and\n", + "L1 (LASSO) penalties we will see that the logistic cost function is\n", + "very similar. In OLS we wish to predict a continuous variable\n", + "$\\hat{y}$ using" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + "
\n", + "\n", + "$$\n", + "\\begin{equation}\n", + " \\hat{y} = X\\omega,\n", + "\\label{_auto26} \\tag{36}\n", + "\\end{equation}\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "where $X \\in \\mathbb{R}^{n \\times p}$ is the input data and $\\omega^{p\n", + "\\times d}$ are the weights of the regression. In a classification\n", + "setting (binary classification in our situation) we are interested in\n", + "a positive or negative answer. We can thus define either answer to be\n", + "above or below some threshold. But, in order to limit the size of the\n", + "answer and also to get a probability interpretation on how sure we are\n", + "for either answer we can compute the sigmoid function of OLS. That is," + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + "
\n", + "\n", + "$$\n", + "\\begin{equation}\n", + " f(X\\omega) = \\frac{1}{1 + \\exp(-X\\omega)}.\n", + "\\label{_auto27} \\tag{37}\n", + "\\end{equation}\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "We are thus interested in minizming the following cost function" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + "
\n", + "\n", + "$$\n", + "\\begin{equation}\n", + " C(X, \\omega) = \\sum_{i = 1}^n \\left\\{\n", + " - y_i\\log\\left( f(x_i^T\\omega) \\right)\n", + " - (1 - y_i)\\log\\left[1 - f(x_i^T\\omega)\\right]\n", + " \\right\\},\n", + "\\label{_auto28} \\tag{38}\n", + "\\end{equation}\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "where we will restrict ourselves to a value for $f(z)$ as the sigmoid\n", + "described above. We can also tack on a L2 (Ridge) or L1 (LASSO)\n", + "penalization to this cost function in the same manner we did for\n", + "linear regression.\n", + "\n", + "\n", + "The penalization factor $\\lambda$ is inverted in the case of the\n", + "logistic regression model we use. We will explore several values of\n", + "$\\lambda$ using both L1 and L2 penalization. We do this using a grid\n", + "search over different parameters and run a 3-fold cross validation for\n", + "each configuration. In other words, we fit a model 3 times for each\n", + "configuration of the hyper parameters." + ] + }, + { + "cell_type": "code", + "execution_count": 79, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "lambdas = np.logspace(-7, -1, 7)\n", + "\n", + "param_grid = {\n", + " \"C\": list(1.0/lambdas),\n", + " \"penalty\": [\"l1\", \"l2\"]\n", + "}\n", + "clf = skms.GridSearchCV(\n", + " skl.LogisticRegression(),\n", + " param_grid=param_grid,\n", + " n_jobs=-1,\n", + " return_train_score=True\n", + ")\n", + "t0 = time.time()\n", + "clf.fit(X_train, y_train)\n", + "t1 = time.time()\n", + "\n", + "print (\n", + " \"Time spent fitting GridSearchCV(LogisticRegression): {0:.3f} sec\".format(\n", + " t1 - t0\n", + " )\n", + ")" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "We can see that logistic regression is quite slow and using the grid\n", + "search and cross validation results in quite a heavy\n", + "computation. Below we show the results of the different\n", + "configurations." + ] + }, + { + "cell_type": "code", + "execution_count": 80, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "logreg_df = pd.DataFrame(clf.cv_results_)\n", + "\n", + "display(logreg_df)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Accuracy of a classification model\n", + "\n", + "To determine how well a classification model is performing we count\n", + "the number of correctly labeled classes and divide by the number of\n", + "classes in total. The accuracy is thus given by" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + "
\n", + "\n", + "$$\n", + "\\begin{equation}\n", + " a(y, \\hat{y}) = \\frac{1}{n}\\sum_{i = 1}^{n} I(y_i = \\hat{y}_i),\n", + "\\label{_auto29} \\tag{39}\n", + "\\end{equation}\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "where $I(y_i = \\hat{y}_i)$ is the indicator function given by" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + "
\n", + "\n", + "$$\n", + "\\begin{equation}\n", + " I(x = y) = \\begin{array}{cc}\n", + " 1 & x = y, \\\\\n", + " 0 & x \\neq y.\n", + " \\end{array}\n", + "\\label{_auto30} \\tag{40}\n", + "\\end{equation}\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "This is the accuracy provided by Scikit-learn when using **sklearn.metrics.accuracyscore**.\n", + "\n", + "Below we compute the accuracy of the best fit model on the training data (which should give a good accuracy), the test data (which has not been shown to the model) and the critical data (completely new data that needs to be extrapolated)." + ] + }, + { + "cell_type": "code", + "execution_count": 81, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "train_accuracy = skm.accuracy_score(y_train, clf.predict(X_train))\n", + "test_accuracy = skm.accuracy_score(y_test, clf.predict(X_test))\n", + "critical_accuracy = skm.accuracy_score(labels[critical], clf.predict(data[critical]))\n", + "\n", + "print (\"Accuracy on train data: {0}\".format(train_accuracy))\n", + "print (\"Accuracy on test data: {0}\".format(test_accuracy))\n", + "print (\"Accuracy on critical data: {0}\".format(critical_accuracy))" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "We can see that we get quite good accuracy on the training data, but gradually worsening accuracy on the test and critical data.\n", + "\n", + "\n", + "## Analyzing the results\n", + "\n", + "Below we show a different metric for determining the quality of our\n", + "model, namely the **reciever operating characteristic** (ROC). The ROC\n", + "curve tells us how well the model correctly classifies the different\n", + "labels. We plot the **true positive rate** (the rate of predicted\n", + "positive classes that are positive) versus the **false positive rate**\n", + "(the rate of predicted positive classes that are negative). The ROC\n", + "curve is built by computing the true positive rate and the false\n", + "positive rate for varying **thresholds**, i.e, which probability we\n", + "should acredit a certain class.\n", + "\n", + "By computing the **area under the curve** (AUC) of the ROC curve we get an estimate of how well our model is performing. Pure guessing will get an AUC of $0.5$. A perfect score will get an AUC of $1.0$." + ] + }, + { + "cell_type": "code", + "execution_count": 82, + "metadata": { + "collapsed": false + }, + "outputs": [], + "source": [ + "fig = plt.figure(figsize=(20, 14))\n", + "\n", + "for (_X, _y), label in zip(\n", + " [\n", + " (X_train, y_train),\n", + " (X_test, y_test),\n", + " (data[critical], labels[critical])\n", + " ],\n", + " [\"Train\", \"Test\", \"Critical\"]\n", + "):\n", + " proba = clf.predict_proba(_X)\n", + " fpr, tpr, _ = skm.roc_curve(_y, proba[:, 1])\n", + " roc_auc = skm.auc(fpr, tpr)\n", + "\n", + " print (\"LogisticRegression AUC ({0}): {1}\".format(label, roc_auc))\n", + "\n", + " plt.plot(fpr, tpr, label=\"{0} (AUC = {1})\".format(label, roc_auc), linewidth=4.0)\n", + "\n", + "plt.plot([0, 1], [0, 1], \"--\", label=\"Guessing (AUC = 0.5)\", linewidth=4.0)\n", + "\n", + "plt.title(r\"The ROC curve for LogisticRegression\", fontsize=18)\n", + "plt.xlabel(r\"False positive rate\", fontsize=18)\n", + "plt.ylabel(r\"True positive rate\", fontsize=18)\n", + "plt.axis([-0.01, 1.01, -0.01, 1.01])\n", + "plt.xticks(fontsize=18)\n", + "plt.yticks(fontsize=18)\n", + "plt.legend(loc=\"best\", fontsize=18)\n", + "plt.show()" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "We can see that this plot of the ROC looks very strange. This tells us\n", + "that logistic regression is quite inept at predicting the Ising model\n", + "transition and is therefore highly non-linear. The ROC curve for the\n", + "training data looks quite good, but as the testing data is so far off\n", + "we see that we are dealing with an overfit model.\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "# Optimization and Gradient Methods\n", "\n", "\n", "## Optimization, the central part of any Machine Learning algortithm\n", @@ -11229,8 +9168,6 @@ "where $\\hat{\\beta}$ are the weights we wish to extract from data, in our case $\\beta_0$ and $\\beta_1$. \n", "\n", "\n", - "## The equations to solve\n", - "\n", "Our compact equations used a definition of a vector $\\hat{y}$ with $n$\n", "elements $y_i$, an $n\\times p$ matrix $\\hat{X}$ which contains the\n", "$x_i$ values and a vector $\\hat{p}$ of fitted probabilities\n", @@ -11313,8 +9250,6 @@ "\n", "\n", "\n", - "## Brief reminder on Newton-Raphson's method\n", - "\n", "Let us quickly remind ourselves how we derive the above method.\n", "\n", "Perhaps the most celebrated of all one-dimensional root-finding\n", @@ -11326,7 +9261,6 @@ "normally discourage the use of this method.\n", "\n", "\n", - "## The equations\n", "\n", "The Newton-Raphson formula consists geometrically of extending the\n", "tangent line at a current point until it crosses zero, then setting\n", @@ -11344,7 +9278,7 @@ "\n", "$$\n", "f(s)=0=f(x)+(s-x)f'(x)+\\frac{(s-x)^2}{2}f''(x) +\\dots.\n", - " \\label{eq:taylornr} \\tag{53}\n", + " \\label{eq:taylornr} \\tag{41}\n", "$$" ] }, @@ -11401,8 +9335,6 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "## Simple geometric interpretation\n", - "\n", "The above is Newton-Raphson's method. It has a simple geometric\n", "interpretation, namely $x_{n+1}$ is the point where the tangent from\n", "$(x_n,f(x_n))$ crosses the $x$-axis. Close to the solution,\n", @@ -11417,8 +9349,6 @@ "\n", "\n", "\n", - "## Extending to more than one variable\n", - "\n", "Newton's method can be generalized to systems of several non-linear equations\n", "and variables. Consider the case with two equations" ] @@ -11459,7 +9389,7 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "Defining the Jacobian matrix $\\hat{J}$ we have" + "Defining the Jacobian matrix $\\boldsymbol{J}$ we have" ] }, { @@ -11467,7 +9397,7 @@ "metadata": {}, "source": [ "$$\n", - "\\hat{J}=\\left( \\begin{array}{cc}\n", + "\\boldsymbol{J}=\\left( \\begin{array}{cc}\n", " \\partial f_1/\\partial x_1 & \\partial f_1/\\partial x_2 \\\\\n", " \\partial f_2/\\partial x_1 &\\partial f_2/\\partial x_2\n", " \\end{array} \\right),\n", @@ -11505,7 +9435,7 @@ "source": [ "$$\n", "\\left(\\begin{array}{c} h_1^{n} \\\\ h_2^{n} \\end{array} \\right)=\n", - " -\\hat{J}^{-1}\n", + " -{\\boldsymbol{J}}^{-1}\n", " \\left(\\begin{array}{c} f_1(x_1^{n},x_2^{n}) \\\\ f_2(x_1^{n},x_2^{n}) \\end{array} \\right).\n", "$$" ] @@ -11516,7 +9446,7 @@ "source": [ "We need thus to compute the inverse of the Jacobian matrix and it\n", "is to understand that difficulties may\n", - "arise in case $\\hat{J}$ is nearly singular.\n", + "arise in case $\\boldsymbol{J}$ is nearly singular.\n", "\n", "It is rather straightforward to extend the above scheme to systems of\n", "more than two non-linear equations. In our case, the Jacobian matrix is given by the Hessian that represents the second derivative of cost function. \n", @@ -11554,8 +9484,6 @@ "we are always moving towards smaller function values, i.e a minimum.\n", "\n", "\n", - "## More on Steepest descent\n", - "\n", "The previous observation is the basis of the method of steepest\n", "descent, which is also referred to as just gradient descent (GD). One\n", "starts with an initial guess $\\mathbf{x}_0$ for a minimum of $F$ and\n", @@ -11579,7 +9507,6 @@ "the learning rate within the context of Machine Learning.\n", "\n", "\n", - "## The ideal\n", "\n", "Ideally the sequence $\\{\\mathbf{x}_k \\}_{k=0}$ converges to a global\n", "minimum of the function $F$. In general we do not know if we are in a\n", @@ -11601,8 +9528,6 @@ "\n", "\n", "\n", - "## The sensitiveness of the gradient descent\n", - "\n", "The gradient descent method \n", "is sensitive to the choice of learning rate $\\gamma_k$. This is due\n", "to the fact that we are only guaranteed that $F(\\mathbf{x}_{k+1}) \\leq\n", @@ -11617,8 +9542,6 @@ "\n", "\n", "\n", - "## Convex functions\n", - "\n", "Ideally we want our cost/loss function to be convex(concave).\n", "\n", "First we give the definition of a convex set: A set $C$ in\n", @@ -11637,14 +9560,13 @@ "**Convex function**: Let $X \\subset \\mathbb{R}^n$ be a convex set. Assume that the function $f: X \\rightarrow \\mathbb{R}$ is continuous, then $f$ is said to be convex if $$f(tx_1 + (1-t)x_2) \\leq tf(x_1) + (1-t)f(x_2) $$ for all $x_1, x_2 \\in X$ and for all $t \\in [0,1]$. If $\\leq$ is replaced with a strict inequaltiy in the definition, we demand $x_1 \\neq x_2$ and $t\\in(0,1)$ then $f$ is said to be strictly convex. For a single variable function, convexity means that if you draw a straight line connecting $f(x_1)$ and $f(x_2)$, the value of the function on the interval $[x_1,x_2]$ is always below the line as illustrated below.\n", "\n", "\n", - "## Conditions on convex functions\n", - "\n", "In the following we state first and second-order conditions which\n", "ensures convexity of a function $f$. We write $D_f$ to denote the\n", "domain of $f$, i.e the subset of $R^n$ where $f$ is defined. For more\n", "details and proofs we refer to: [S. Boyd and L. Vandenberghe. Convex Optimization. Cambridge University Press](http://stanford.edu/boyd/cvxbook/, 2004).\n", "\n", - " First order condition\n", + "**First order condition.**\n", + "\n", "Suppose $f$ is differentiable (i.e $\\nabla f(x)$ is well defined for\n", "all $x$ in the domain of $f$). Then $f$ is convex if and only if $D_f$\n", "is a convex set and $$f(y) \\geq f(x) + \\nabla f(x)^T (y-x) $$ holds\n", @@ -11652,10 +9574,12 @@ "the first order Taylor expansion (right hand side above) at any point\n", "a global under estimator of the function. To convince yourself you can\n", "make a drawing of $f(x) = x^2+1$ and draw the tangent line to $f(x)$ and\n", - "note that it is always below the graph. \n", + "note that it is always below the graph.\n", "\n", "\n", - " Second order condition \n", + "\n", + "**Second order condition.**\n", + "\n", "Assume that $f$ is twice\n", "differentiable, i.e the Hessian matrix exists at each point in\n", "$D_f$. Then $f$ is convex if and only if $D_f$ is a convex set and its\n", @@ -11664,11 +9588,10 @@ "everywhere.\n", "\n", "\n", + "\n", "This condition is particularly useful since it gives us an procedure for determining if the function under consideration is convex, apart from using the definition.\n", "\n", "\n", - "## More on convex functions\n", - "\n", "The next result is of great importance to us and the reason why we are\n", "going on about convex functions. In machine learning we frequently\n", "have to minimize a loss/cost function in order to find the best\n", @@ -11679,12 +9602,14 @@ "if we have local or global minimum). However, if the cost/loss function\n", "is convex the following result provides invaluable information:\n", "\n", - " Any minimum is global for convex functions\n", + "**Any minimum is global for convex functions.**\n", + "\n", "Consider the problem of finding $x \\in \\mathbb{R}^n$ such that $f(x)$\n", "is minimal, where $f$ is convex and differentiable. Then, any point\n", "$x^*$ that satisfies $\\nabla f(x^*) = 0$ is a global minimum.\n", "\n", "\n", + "\n", "This result means that if we know that the cost/loss function is convex and we are able to find a minimum, we are guaranteed that it is a global minimum.\n", "\n", "\n", @@ -11762,8 +9687,6 @@ "When we have found the exact solution, $\\hat{r}=0$.\n", "\n", "\n", - "## Gradient method\n", - "\n", "The residual is zero when we reach the minimum of the quadratic equation" ] }, @@ -11785,8 +9708,6 @@ "\n", "\n", "\n", - "## Steepest descent method\n", - "\n", "We denote the initial guess for $\\hat{x}$ as $\\hat{x}_0$. \n", "We can assume without loss of generality that" ] @@ -11824,8 +9745,6 @@ "\n", "\n", "\n", - "## Steepest descent method\n", - "\n", "One can show that the solution $\\hat{x}$ is also the unique minimizer of the quadratic form" ] }, @@ -11863,11 +9782,6 @@ "and \n", "$\\hat{x}_0=0$ it is equal $-\\hat{b}$.\n", "\n", - "\n", - "\n", - "\n", - "## Final expressions\n", - "\n", "We can compute the residual iteratively as" ] }, @@ -11948,9 +9862,6 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "## Code examples for steepest descent\n", - "\n", - "\n", "## Simple codes for steepest descent and conjugate gradient using a $2\\times 2$ matrix, in c++, Python code to come" ] }, @@ -11985,13 +9896,6 @@ " }\n" ] }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "## The routine for the steepest descent method" - ] - }, { "cell_type": "markdown", "metadata": {}, @@ -12028,7 +9932,7 @@ }, { "cell_type": "code", - "execution_count": 64, + "execution_count": 83, "metadata": { "collapsed": false }, @@ -12065,7 +9969,7 @@ }, { "cell_type": "code", - "execution_count": 65, + "execution_count": 84, "metadata": { "collapsed": false }, @@ -12085,7 +9989,7 @@ }, { "cell_type": "code", - "execution_count": 66, + "execution_count": 85, "metadata": { "collapsed": false }, @@ -12104,7 +10008,7 @@ }, { "cell_type": "code", - "execution_count": 67, + "execution_count": 86, "metadata": { "collapsed": false }, @@ -12128,7 +10032,7 @@ }, { "cell_type": "code", - "execution_count": 68, + "execution_count": 87, "metadata": { "collapsed": false }, @@ -12185,10 +10089,6 @@ "Two vectors are conjugate if they are orthogonal with respect to \n", "this inner product. Being conjugate is a symmetric relation: if $\\hat{s}$ is conjugate to $\\hat{t}$, then $\\hat{t}$ is conjugate to $\\hat{s}$.\n", "\n", - "\n", - "\n", - "## Conjugate gradient method\n", - "\n", "An example is given by the eigenvectors of the matrix" ] }, @@ -12207,11 +10107,6 @@ "source": [ "which is zero unless $i=j$. \n", "\n", - "\n", - "\n", - "\n", - "## Conjugate gradient method\n", - "\n", "Assume now that we have a symmetric positive-definite matrix $\\hat{A}$ of size\n", "$n\\times n$. At each iteration $i+1$ we obtain the conjugate direction of a vector" ] @@ -12247,8 +10142,6 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "## Conjugate gradient method\n", - "\n", "The coefficients are given by" ] }, @@ -12297,9 +10190,6 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "## Conjugate gradient method and iterations\n", - "\n", - "\n", "If we choose the conjugate vectors $\\hat{p}_k$ carefully, \n", "then we may not need all of them to obtain a good approximation to the solution \n", "$\\hat{x}$. \n", @@ -12342,11 +10232,6 @@ "source": [ "instead.\n", "\n", - "\n", - "\n", - "\n", - "## Conjugate gradient method\n", - "\n", "One can show that the solution $\\hat{x}$ is also the unique minimizer of the quadratic form" ] }, @@ -12386,11 +10271,6 @@ "The other vectors in the basis will be conjugate to the gradient, \n", "hence the name conjugate gradient method.\n", "\n", - "\n", - "\n", - "\n", - "## Conjugate gradient method\n", - "\n", "Let $\\hat{r}_k$ be the residual at the $k$-th step:" ] }, @@ -12429,8 +10309,6 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "## Conjugate gradient method\n", - "\n", "We can also compute the residual iteratively as" ] }, @@ -12578,20 +10456,12 @@ "over the scalar $\\alpha > 0$.\n", "\n", "\n", - "\n", - "\n", - "\n", - "\n", - "\n", - "\n", - "## Revisiting our first homework\n", - "\n", "We will use linear regression as a case study for the gradient descent\n", "methods. Linear regression is a great test case for the gradient\n", "descent methods discussed in the lectures since it has several\n", "desirable properties such as:\n", "\n", - "1. An analytical solution (recall homework set 1).\n", + "1. An analytical solution.\n", "\n", "2. The gradient can be computed analytically.\n", "\n", @@ -12689,8 +10559,6 @@ "and we want to find $\\beta$ such that $C(\\beta)$ is minimized.\n", "\n", "\n", - "## The derivative of the cost/loss function\n", - "\n", "Computing $\\partial C(\\beta) / \\partial \\beta_0$ and $\\partial C(\\beta) / \\partial \\beta_1$ we can show that the gradient can be written as" ] }, @@ -12712,7 +10580,6 @@ "where $X$ is the design matrix defined above.\n", "\n", "\n", - "## The Hessian matrix\n", "The Hessian matrix of $C(\\beta)$ is given by" ] }, @@ -12736,8 +10603,6 @@ "\n", "\n", "\n", - "\n", - "\n", "## Simple program\n", "\n", "We can now write a program that minimizes $C(\\beta)$ using the gradient descent method with a constant learning rate $\\gamma$ according to" @@ -12766,7 +10631,7 @@ }, { "cell_type": "code", - "execution_count": 69, + "execution_count": 88, "metadata": { "collapsed": false }, @@ -12796,14 +10661,12 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "## Gradient Descent Example\n", - "\n", "Another simple example is here" ] }, { "cell_type": "code", - "execution_count": 70, + "execution_count": 89, "metadata": { "collapsed": false }, @@ -12859,7 +10722,7 @@ }, { "cell_type": "code", - "execution_count": 71, + "execution_count": 90, "metadata": { "collapsed": false }, @@ -12944,7 +10807,7 @@ }, { "cell_type": "code", - "execution_count": 72, + "execution_count": 91, "metadata": { "collapsed": false }, @@ -13020,7 +10883,7 @@ }, { "cell_type": "code", - "execution_count": 73, + "execution_count": 92, "metadata": { "collapsed": false }, @@ -13077,7 +10940,7 @@ }, { "cell_type": "code", - "execution_count": 74, + "execution_count": 93, "metadata": { "collapsed": false }, @@ -13115,7 +10978,7 @@ }, { "cell_type": "code", - "execution_count": 75, + "execution_count": 94, "metadata": { "collapsed": false }, @@ -13169,7 +11032,7 @@ }, { "cell_type": "code", - "execution_count": 76, + "execution_count": 95, "metadata": { "collapsed": false }, @@ -13211,7 +11074,7 @@ }, { "cell_type": "code", - "execution_count": 77, + "execution_count": 96, "metadata": { "collapsed": false }, @@ -13236,16 +11099,9 @@ "print(\"The analytical gradient of f4 at x = %g is: %g\"%(x,f4_grad_analytical))" ] }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "## More autograd" - ] - }, { "cell_type": "code", - "execution_count": 78, + "execution_count": 97, "metadata": { "collapsed": false }, @@ -13267,20 +11123,13 @@ "print(\"The computed derivative of f5 at x = %g is: %g\"%(x,f5_grad(x)))" ] }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "## And with loops" - ] - }, { "cell_type": "markdown", "metadata": {}, "source": [ "1\n", "0\n", - "7\n", + "3\n", " \n", "<\n", "<\n", @@ -13308,7 +11157,7 @@ }, { "cell_type": "code", - "execution_count": 79, + "execution_count": 98, "metadata": { "collapsed": false }, @@ -13334,7 +11183,7 @@ }, { "cell_type": "code", - "execution_count": 80, + "execution_count": 99, "metadata": { "collapsed": false }, @@ -13384,7 +11233,7 @@ }, { "cell_type": "code", - "execution_count": 81, + "execution_count": 100, "metadata": { "collapsed": false }, @@ -13415,7 +11264,7 @@ }, { "cell_type": "code", - "execution_count": 82, + "execution_count": 101, "metadata": { "collapsed": false }, @@ -13445,7 +11294,7 @@ }, { "cell_type": "code", - "execution_count": 83, + "execution_count": 102, "metadata": { "collapsed": false }, @@ -13477,7 +11326,7 @@ }, { "cell_type": "code", - "execution_count": 84, + "execution_count": 103, "metadata": { "collapsed": false }, @@ -13517,8 +11366,6 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "## Computation of gradients\n", - "\n", "This in turn means that the gradient can be\n", "computed as a sum over $i$-gradients" ] @@ -13544,7 +11391,6 @@ "$k=1,\\cdots,n/M$.\n", "\n", "\n", - "## SGD example\n", "As an example, suppose we have $10$ data points $(\\mathbf{x}_1,\\cdots, \\mathbf{x}_{10})$ \n", "and we choose to have $M=5$ minibathces,\n", "then each minibatch contains two data points. In particular we have\n", @@ -13575,8 +11421,6 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "## The gradient step\n", - "\n", "Thus a gradient descent step now looks like" ] }, @@ -13598,15 +11442,12 @@ "probability from $[1,n/M]$. An iteration over the number of\n", "minibathces (n/M) is commonly referred to as an epoch. Thus it is\n", "typical to choose a number of epochs and for each epoch iterate over\n", - "the number of minibatches, as exemplified in the code below.\n", - "\n", - "\n", - "## Simple example code" + "the number of minibatches, as exemplified in the code below." ] }, { "cell_type": "code", - "execution_count": 85, + "execution_count": 104, "metadata": { "collapsed": false }, @@ -13641,8 +11482,6 @@ "all $n$ datapoints.\n", "\n", "\n", - "## When do we stop?\n", - "\n", "A natural question is when do we stop the search for a new minimum?\n", "One possibility is to compute the full gradient after a given number\n", "of epochs and check if the norm of the gradient is smaller than some\n", @@ -13655,8 +11494,6 @@ "gave the lowest value.\n", "\n", "\n", - "## Slightly different approach\n", - "\n", "Another approach is to let the step length $\\gamma_j$ depend on the\n", "number of epochs in such a way that it becomes very small after a\n", "reasonable time such that we do not move at all.\n", @@ -13672,7 +11509,7 @@ }, { "cell_type": "code", - "execution_count": 86, + "execution_count": 105, "metadata": { "collapsed": false }, @@ -13704,16 +11541,9 @@ "print(\"gamma_j after %d epochs: %g\" % (n_epochs,gamma_j))" ] }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "## Program for stochastic gradient" - ] - }, { "cell_type": "code", - "execution_count": 87, + "execution_count": 106, "metadata": { "collapsed": false }, @@ -13829,12 +11659,12 @@ "metadata": {}, "source": [ "\n", - "
\n", + "
\n", "\n", "$$\n", "\\begin{equation} \n", "\\boldsymbol{\\theta}_{t+1}= \\boldsymbol{\\theta}_t -\\mathbf{v}_{t},\n", - "\\label{_auto35} \\tag{54}\n", + "\\label{_auto31} \\tag{42}\n", "\\end{equation}\n", "$$" ] @@ -13954,12 +11784,12 @@ "metadata": {}, "source": [ "\n", - "
\n", + "
\n", "\n", "$$\n", "\\begin{equation} \n", "\\boldsymbol{\\theta}_{t+1}= \\boldsymbol{\\theta}_t -\\mathbf{v}_{t}.\n", - "\\label{_auto36} \\tag{55}\n", + "\\label{_auto32} \\tag{43}\n", "\\end{equation}\n", "$$" ] @@ -13972,9 +11802,6 @@ "\n", "\n", "\n", - "## Second moment of the gradient\n", - "\n", - "\n", "In stochastic gradient descent, with and without momentum, we still\n", "have to specify a schedule for tuning the learning rates $\\eta_t$\n", "as a function of time. As discussed in the context of Newton's\n", @@ -14004,12 +11831,12 @@ "metadata": {}, "source": [ "\n", - "
\n", + "
\n", "\n", "$$\n", "\\begin{equation}\n", "\\mathbf{g}_t = \\nabla_\\theta E(\\boldsymbol{\\theta}) \n", - "\\label{_auto37} \\tag{56}\n", + "\\label{_auto33} \\tag{44}\n", "\\end{equation}\n", "$$" ] @@ -14050,12 +11877,12 @@ "metadata": {}, "source": [ "\n", - "
\n", + "
\n", "\n", "$$\n", "\\begin{equation}\n", "\\mathbf{g}_t = \\nabla_\\theta E(\\boldsymbol{\\theta}) \n", - "\\label{_auto38} \\tag{57}\n", + "\\label{_auto34} \\tag{45}\n", "\\end{equation}\n", "$$" ] @@ -14110,11 +11937,11 @@ "metadata": {}, "source": [ "\n", - "
\n", + "
\n", "\n", "$$\n", "\\begin{equation} \n", - "\\label{_auto39} \\tag{58}\n", + "\\label{_auto35} \\tag{46}\n", "\\end{equation}\n", "$$" ] @@ -14149,4741 +11976,7 @@ "\n", "* **Monitor the out-of-sample performance.** Always monitor the performance of your model on a validation set (a small portion of the training data that is held out of the training process to serve as a proxy for the test set. If the validation error starts increasing, then the model is beginning to overfit. Terminate the learning process. This *early stopping* significantly improves performance in many settings.\n", "\n", - "* **Adaptive optimization methods don't always have good generalization.** Recent studies have shown that adaptive methods such as ADAM, RMSPorp, and AdaGrad tend to have poor generalization compared to SGD or SGD with momentum, particularly in the high-dimensional limit (i.e. the number of parameters exceeds the number of data points). Although it is not clear at this stage why these methods perform so well in training deep neural networks, simpler procedures like properly-tuned SGD may work as well or better in these applications.\n", - "\n", - "# Logistic Regression\n", - "\n", - "In linear regression our main interest was centered on learning the\n", - "coefficients of a functional fit (say a polynomial) in order to be\n", - "able to predict the response of a continuous variable on some unseen\n", - "data. The fit to the continuous variable $y_i$ is based on some\n", - "independent variables $\\hat{x}_i$. Linear regression resulted in\n", - "analytical expressions (in terms of matrices to invert) for several\n", - "quantities, ranging from the variance and thereby the confidence\n", - "intervals of the parameters $\\hat{\\beta}$ to the mean squared\n", - "error. If we can invert the product of the design matrices, linear\n", - "regression gives then a simple recipe for fitting our data.\n", - "\n", - "\n", - "Classification problems, however, are concerned with outcomes taking\n", - "the form of discrete variables (i.e. categories). We may for example,\n", - "on the basis of DNA sequencing for a number of patients, like to find\n", - "out which mutations are important for a certain disease; or based on\n", - "scans of various patients' brains, figure out if there is a tumor or\n", - "not; or given a specific physical system, we'd like to identify its\n", - "state, say whether it is an ordered or disordered system (typical\n", - "situation in solid state physics); or classify the status of a\n", - "patient, whether she/he has a stroke or not and many other similar\n", - "situations.\n", - "\n", - "The most common situation we encounter when we apply logistic\n", - "regression is that of two possible outcomes, normally denoted as a\n", - "binary outcome, true or false, positive or negative, success or\n", - "failure etc.\n", - "\n", - "\n", - "## Optimization and Deep learning\n", - "\n", - "Logistic regression will also serve as our stepping stone towards neural\n", - "network algorithms and supervised deep learning. For logistic\n", - "learning, the minimization of the cost function leads to a non-linear\n", - "equation in the parameters $\\hat{\\beta}$. The optmization of the problem calls therefore for minimization algorithms. This forms the bottle neck of all machine learning algorithms, namely how to find reliable minima of a multi-variable function. This leads us to the family of gradient descent methods. The latter are the working horses of basically all modern machine learning algorithms. \n", - "\n", - "We note also that many of the topics discussed here \n", - "regression are also commonly used in modern supervised Deep Learning\n", - "models, as we will see later.\n", - "\n", - "\n", - "\n", - "## Basics\n", - "\n", - "We consider the case where the dependent variables, also called the\n", - "responses or the outcomes, $y_i$ are discrete and only take values\n", - "from $k=0,\\dots,K-1$ (i.e. $K$ classes).\n", - "\n", - "The goal is to predict the\n", - "output classes from the design matrix $\\hat{X}\\in\\mathbb{R}^{n\\times p}$\n", - "made of $n$ samples, each of which carries $p$ features or predictors. The\n", - "primary goal is to identify the classes to which new unseen samples\n", - "belong.\n", - "\n", - "Let us specialize to the case of two classes only, with outputs $y_i=0$ and $y_i=1$. Our outcomes could represent the status of a credit card user who could default or not on her/his credit card debt. That is" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "y_i = \\begin{bmatrix} 0 & \\mathrm{no}\\\\ 1 & \\mathrm{yes} \\end{bmatrix}.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "## Linear classifier\n", - "\n", - "Before moving to the logistic model, let us try to use our linear regression model to classify these two outcomes. We could for example fit a linear model to the default case if $y_i > 0.5$ and the no default case $y_i \\leq 0.5$. \n", - "\n", - "We would then have our \n", - "weighted linear combination, namely" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "\n", - "
\n", - "\n", - "$$\n", - "\\begin{equation}\n", - "\\hat{y} = \\hat{X}^T\\hat{\\beta} + \\hat{\\epsilon},\n", - "\\label{_auto40} \\tag{59}\n", - "\\end{equation}\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "where $\\hat{y}$ is a vector representing the possible outcomes, $\\hat{X}$ is our\n", - "$n\\times p$ design matrix and $\\hat{\\beta}$ represents our estimators/predictors.\n", - "\n", - "\n", - "## Some selected properties\n", - "\n", - "The main problem with our function is that it \n", - "takes values on the entire real axis. In the case of\n", - "logistic regression, however, the labels $y_i$ are discrete\n", - "variables. \n", - "\n", - "One simple way to get a discrete output is to have sign\n", - "functions that map the output of a linear regressor to values $\\{0,1\\}$,\n", - "$f(s_i)=sign(s_i)=1$ if $s_i\\ge 0$ and 0 if otherwise. \n", - "We will encounter this model in our first demonstration of neural networks. Historically it is called the \"perceptron\" model in the machine learning\n", - "literature. This model is extremely simple. However, in many cases it is more\n", - "favorable to use a ``soft\" classifier that outputs\n", - "the probability of a given category. This leads us to the logistic function.\n", - "\n", - "The code for plotting the perceptron can be seen here. This si nothing but the standard [Heaviside step function](https://en.wikipedia.org/wiki/Heaviside_step_function)." - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "## The logistic function\n", - "\n", - "The perceptron is an example of a ``hard classification\" model. We\n", - "will encounter this model when we discuss neural networks as\n", - "well. Each datapoint is deterministically assigned to a category (i.e\n", - "$y_i=0$ or $y_i=1$). In many cases, it is favorable to have a \"soft\"\n", - "classifier that outputs the probability of a given category rather\n", - "than a single value. For example, given $x_i$, the classifier\n", - "outputs the probability of being in a category $k$. Logistic regression\n", - "is the most common example of a so-called soft classifier. In logistic\n", - "regression, the probability that a data point $x_i$\n", - "belongs to a category $y_i=\\{0,1\\}$ is given by the so-called logit function (or Sigmoid) which is meant to represent the likelihood for a given event," - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "p(t) = \\frac{1}{1+\\mathrm \\exp{-t}}=\\frac{\\exp{t}}{1+\\mathrm \\exp{t}}.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "Note that $1-p(t)= p(-t)$.\n", - "The following code plots the logistic function." - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "## Two parameters\n", - "\n", - "We assume now that we have two classes with $y_i$ either $0$ or $1$. Furthermore we assume also that we have only two parameters $\\beta$ in our fitting of the Sigmoid function, that is we define probabilities" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "\\begin{align*}\n", - "p(y_i=1|x_i,\\hat{\\beta}) &= \\frac{\\exp{(\\beta_0+\\beta_1x_i)}}{1+\\exp{(\\beta_0+\\beta_1x_i)}},\\nonumber\\\\\n", - "p(y_i=0|x_i,\\hat{\\beta}) &= 1 - p(y_i=1|x_i,\\hat{\\beta}),\n", - "\\end{align*}\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "where $\\hat{\\beta}$ are the weights we wish to extract from data, in our case $\\beta_0$ and $\\beta_1$. \n", - "\n", - "Note that we used" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "p(y_i=0\\vert x_i, \\hat{\\beta}) = 1-p(y_i=1\\vert x_i, \\hat{\\beta}).\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "## Maximum likelihood\n", - "\n", - "In order to define the total likelihood for all possible outcomes from a \n", - "dataset $\\mathcal{D}=\\{(y_i,x_i)\\}$, with the binary labels\n", - "$y_i\\in\\{0,1\\}$ and where the data points are drawn independently, we use the so-called [Maximum Likelihood Estimation](https://en.wikipedia.org/wiki/Maximum_likelihood_estimation) (MLE) principle. \n", - "We aim thus at maximizing \n", - "the probability of seeing the observed data. We can then approximate the \n", - "likelihood in terms of the product of the individual probabilities of a specific outcome $y_i$, that is" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "\\begin{align*}\n", - "P(\\mathcal{D}|\\hat{\\beta})& = \\prod_{i=1}^n \\left[p(y_i=1|x_i,\\hat{\\beta})\\right]^{y_i}\\left[1-p(y_i=1|x_i,\\hat{\\beta}))\\right]^{1-y_i}\\nonumber \\\\\n", - "\\end{align*}\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "from which we obtain the log-likelihood and our **cost/loss** function" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "\\mathcal{C}(\\hat{\\beta}) = \\sum_{i=1}^n \\left( y_i\\log{p(y_i=1|x_i,\\hat{\\beta})} + (1-y_i)\\log\\left[1-p(y_i=1|x_i,\\hat{\\beta}))\\right]\\right).\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "## The cost function rewritten\n", - "\n", - "Reordering the logarithms, we can rewrite the **cost/loss** function as" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "\\mathcal{C}(\\hat{\\beta}) = \\sum_{i=1}^n \\left(y_i(\\beta_0+\\beta_1x_i) -\\log{(1+\\exp{(\\beta_0+\\beta_1x_i)})}\\right).\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "The maximum likelihood estimator is defined as the set of parameters that maximize the log-likelihood where we maximize with respect to $\\beta$.\n", - "Since the cost (error) function is just the negative log-likelihood, for logistic regression we have that" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "\\mathcal{C}(\\hat{\\beta})=-\\sum_{i=1}^n \\left(y_i(\\beta_0+\\beta_1x_i) -\\log{(1+\\exp{(\\beta_0+\\beta_1x_i)})}\\right).\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "This equation is known in statistics as the **cross entropy**. Finally, we note that just as in linear regression, \n", - "in practice we often supplement the cross-entropy with additional regularization terms, usually $L_1$ and $L_2$ regularization as we did for Ridge and Lasso regression.\n", - "\n", - "\n", - "## Minimizing the cross entropy\n", - "\n", - "The cross entropy is a convex function of the weights $\\hat{\\beta}$ and,\n", - "therefore, any local minimizer is a global minimizer. \n", - "\n", - "\n", - "Minimizing this\n", - "cost function with respect to the two parameters $\\beta_0$ and $\\beta_1$ we obtain" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "\\frac{\\partial \\mathcal{C}(\\hat{\\beta})}{\\partial \\beta_0} = -\\sum_{i=1}^n \\left(y_i -\\frac{\\exp{(\\beta_0+\\beta_1x_i)}}{1+\\exp{(\\beta_0+\\beta_1x_i)}}\\right),\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "and" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "\\frac{\\partial \\mathcal{C}(\\hat{\\beta})}{\\partial \\beta_1} = -\\sum_{i=1}^n \\left(y_ix_i -x_i\\frac{\\exp{(\\beta_0+\\beta_1x_i)}}{1+\\exp{(\\beta_0+\\beta_1x_i)}}\\right).\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "## A more compact expression\n", - "\n", - "Let us now define a vector $\\hat{y}$ with $n$ elements $y_i$, an\n", - "$n\\times p$ matrix $\\hat{X}$ which contains the $x_i$ values and a\n", - "vector $\\hat{p}$ of fitted probabilities $p(y_i\\vert x_i,\\hat{\\beta})$. We can rewrite in a more compact form the first\n", - "derivative of cost function as" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "\\frac{\\partial \\mathcal{C}(\\hat{\\beta})}{\\partial \\hat{\\beta}} = -\\hat{X}^T\\left(\\hat{y}-\\hat{p}\\right).\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "If we in addition define a diagonal matrix $\\hat{W}$ with elements \n", - "$p(y_i\\vert x_i,\\hat{\\beta})(1-p(y_i\\vert x_i,\\hat{\\beta})$, we can obtain a compact expression of the second derivative as" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "\\frac{\\partial^2 \\mathcal{C}(\\hat{\\beta})}{\\partial \\hat{\\beta}\\partial \\hat{\\beta}^T} = \\hat{X}^T\\hat{W}\\hat{X}.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "## Extending to more predictors\n", - "\n", - "Within a binary classification problem, we can easily expand our model to include multiple predictors. Our ratio between likelihoods is then with $p$ predictors" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "\\log{ \\frac{p(\\hat{\\beta}\\hat{x})}{1-p(\\hat{\\beta}\\hat{x})}} = \\beta_0+\\beta_1x_1+\\beta_2x_2+\\dots+\\beta_px_p.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "Here we defined $\\hat{x}=[1,x_1,x_2,\\dots,x_p]$ and $\\hat{\\beta}=[\\beta_0, \\beta_1, \\dots, \\beta_p]$ leading to" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "p(\\hat{\\beta}\\hat{x})=\\frac{ \\exp{(\\beta_0+\\beta_1x_1+\\beta_2x_2+\\dots+\\beta_px_p)}}{1+\\exp{(\\beta_0+\\beta_1x_1+\\beta_2x_2+\\dots+\\beta_px_p)}}.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "## Including more classes\n", - "\n", - "Till now we have mainly focused on two classes, the so-called binary system. Suppose we wish to extend to $K$ classes.\n", - "Let us for the sake of simplicity assume we have only two predictors. We have then following model" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "3\n", - "8\n", - "9\n", - " \n", - "<\n", - "<\n", - "<\n", - "!\n", - "!\n", - "M\n", - "A\n", - "T\n", - "H\n", - "_\n", - "B\n", - "L\n", - "O\n", - "C\n", - "K" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "\\log{\\frac{p(C=2\\vert x)}{p(K\\vert x)}} = \\beta_{20}+\\beta_{21}x_1,\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "and so on till the class $C=K-1$ class" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "\\log{\\frac{p(C=K-1\\vert x)}{p(K\\vert x)}} = \\beta_{(K-1)0}+\\beta_{(K-1)1}x_1,\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "and the model is specified in term of $K-1$ so-called log-odds or **logit** transformations.\n", - "\n", - "\n", - "\n", - "## The Softmax function\n", - "\n", - "In our discussion of neural networks we will encounter the above again in terms of the so-called **Softmax** function.\n", - "\n", - "The softmax function is used in various multiclass classification\n", - "methods, such as multinomial logistic regression (also known as\n", - "softmax regression), multiclass linear discriminant\n", - "analysis, naive Bayes classifiers, and artificial neural networks.\n", - "Specifically, in multinomial logistic regression and linear\n", - "discriminant analysis, the input to the function is the result of $K$\n", - "distinct linear functions, and the predicted probability for the $k$-th\n", - "class given a sample vector $\\hat{x}$ and a weighting vector $\\hat{\\beta}$ is (with two predictors):" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "p(C=k\\vert \\mathbf {x} )=\\frac{\\exp{(\\beta_{k0}+\\beta_{k1}x_1)}}{1+\\sum_{l=1}^{K-1}\\exp{(\\beta_{l0}+\\beta_{l1}x_1)}}.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "It is easy to extend to more predictors. The final class is" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "p(C=K\\vert \\mathbf {x} )=\\frac{1}{1+\\sum_{l=1}^{K-1}\\exp{(\\beta_{l0}+\\beta_{l1}x_1)}},\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "and they sum to one. Our earlier discussions were all specialized to the case with two classes only. It is easy to see from the above that what we derived earlier is compatible with these equations. \n", - "\n", - "To find the optimal parameters we would typically use a gradient descent method.\n", - "Newton's method and gradient descent methods are discussed in the material on [optimization methods](https://compphysics.github.io/MachineLearning/doc/pub/Splines/html/Splines-bs.html). \n", - "\n", - "\n", - "\n", - "\n", - "## A **scikit-learn** example" - ] - }, - { - "cell_type": "code", - "execution_count": 88, - "metadata": { - "collapsed": false - }, - "outputs": [], - "source": [ - "import numpy as np\n", - "import matplotlib.pyplot as plt\n", - "from sklearn import datasets\n", - "iris = datasets.load_iris()\n", - "list(iris.keys())\n", - "['data', 'target_names', 'feature_names', 'target', 'DESCR']\n", - "X = iris[\"data\"][:, 3:] # petal width\n", - "y = (iris[\"target\"] == 2).astype(np.int) # 1 if Iris-Virginica, else 0\n", - "\n", - "from sklearn.linear_model import LogisticRegression\n", - "log_reg = LogisticRegression()\n", - "log_reg.fit(X, y)\n", - "\n", - "X_new = np.linspace(0, 3, 1000).reshape(-1, 1)\n", - "y_proba = log_reg.predict_proba(X_new)\n", - "plt.plot(X_new, y_proba[:, 1], \"g-\", label=\"Iris-Virginica\")\n", - "plt.plot(X_new, y_proba[:, 0], \"b--\", label=\"Not Iris-Virginica\")\n", - "plt.show()" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "## A simple classification problem" - ] - }, - { - "cell_type": "code", - "execution_count": 89, - "metadata": { - "collapsed": false - }, - "outputs": [], - "source": [ - "import numpy as np\n", - "from sklearn import datasets, linear_model\n", - "import matplotlib.pyplot as plt\n", - "\n", - "\n", - "def generate_data():\n", - " np.random.seed(0)\n", - " X, y = datasets.make_moons(200, noise=0.20)\n", - " return X, y\n", - "\n", - "\n", - "def visualize(X, y, clf):\n", - " # plt.scatter(X[:, 0], X[:, 1], s=40, c=y, cmap=plt.cm.Spectral)\n", - " # plt.show()\n", - " plot_decision_boundary(lambda x: clf.predict(x), X, y)\n", - " plt.title(\"Logistic Regression\")\n", - "\n", - "\n", - "def plot_decision_boundary(pred_func, X, y):\n", - " # Set min and max values and give it some padding\n", - " x_min, x_max = X[:, 0].min() - .5, X[:, 0].max() + .5\n", - " y_min, y_max = X[:, 1].min() - .5, X[:, 1].max() + .5\n", - " h = 0.01\n", - " # Generate a grid of points with distance h between them\n", - " xx, yy = np.meshgrid(np.arange(x_min, x_max, h), np.arange(y_min, y_max, h))\n", - " # Predict the function value for the whole gid\n", - " Z = pred_func(np.c_[xx.ravel(), yy.ravel()])\n", - " Z = Z.reshape(xx.shape)\n", - " # Plot the contour and training examples\n", - " plt.contourf(xx, yy, Z, cmap=plt.cm.Spectral)\n", - " plt.scatter(X[:, 0], X[:, 1], c=y, cmap=plt.cm.Spectral)\n", - " plt.show()\n", - "\n", - "\n", - "def classify(X, y):\n", - " clf = linear_model.LogisticRegressionCV()\n", - " clf.fit(X, y)\n", - " return clf\n", - "\n", - "\n", - "def main():\n", - " X, y = generate_data()\n", - " # visualize(X, y)\n", - " clf = classify(X, y)\n", - " visualize(X, y, clf)\n", - "\n", - "\n", - "if __name__ == \"__main__\":\n", - " main()" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "## The two-dimensional Ising model, Predicting phase transition of the two-dimensional Ising model\n", - "\n", - "The Hamiltonian of the two-dimensional Ising model without an external field for a constant coupling constant $J$ is given by" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "\n", - "
\n", - "\n", - "$$\n", - "\\begin{equation}\n", - " H = -J \\sum_{\\langle ij\\rangle} S_i S_j,\n", - "\\label{_auto41} \\tag{60}\n", - "\\end{equation}\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "where $S_i \\in \\{-1, 1\\}$ and $\\langle ij \\rangle$ signifies that we only iterate over the nearest neighbors in the lattice. We will be looking at a system of $L = 40$ spins in each dimension, i.e., $L^2 = 1600$ spins in total. Opposed to the one-dimensional Ising model we will get a phase transition from an **ordered** phase to a **disordered** phase at the critical temperature" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "\n", - "
\n", - "\n", - "$$\n", - "\\begin{equation}\n", - " \\frac{T_c}{J} = \\frac{2}{\\log\\left(1 + \\sqrt{2}\\right)} \\approx 2.26,\n", - "\\label{_auto42} \\tag{61}\n", - "\\end{equation}\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "as shown by Lars Onsager.\n", - "\n", - "\n", - "Here we use **logistic regression** to predict when a phase transition\n", - "occurs. The data we will look at is a set of spin configurations,\n", - "i.e., individual lattices with spins, labeled **ordered** `1` or\n", - "**disordered** `0`. Our job is to build a model which will take in a\n", - "spin configuration and predict whether or not the spin configuration\n", - "constitutes an ordered or a disordered phase. To achieve this we will\n", - "represent the lattices as flattened arrays with $1600$ elements\n", - "instead of a matrix of $40 \\times 40$ elements. As an extra test of\n", - "the performance of the algorithms we will divide the dataset into\n", - "three pieces. We will do a conventional train-test-split on a\n", - "combination of totally ordered and totally disordered phases. The\n", - "remaining \"critical-like\" states will be used as test data which we\n", - "hope the model will be able to make good extrapolated predictions on." - ] - }, - { - "cell_type": "code", - "execution_count": 90, - "metadata": { - "collapsed": false - }, - "outputs": [], - "source": [ - "import pickle\n", - "import os\n", - "import glob\n", - "import numpy as np\n", - "import pandas as pd\n", - "import matplotlib.pyplot as plt\n", - "import seaborn as sns\n", - "import sklearn.model_selection as skms\n", - "import sklearn.linear_model as skl\n", - "import sklearn.metrics as skm\n", - "import tqdm\n", - "import copy\n", - "import time\n", - "from IPython.display import display\n", - "\n", - "%matplotlib inline\n", - "\n", - "sns.set(color_codes=True)" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "## Reading in the data\n", - "\n", - "Using the data from [Mehta et al.](https://physics.bu.edu/~pankajm/ML-Review-Datasets/isingMC/) (specifically the two datasets named `Ising2DFM_reSample_L40_T=All.pkl` and `Ising2DFM_reSample_L40_T=All_labels.pkl`) we have to unpack the data into numpy arrays." - ] - }, - { - "cell_type": "code", - "execution_count": 91, - "metadata": { - "collapsed": false - }, - "outputs": [], - "source": [ - "filenames = glob.glob(os.path.join(\"..\", \"dat\", \"*\"))\n", - "label_filename = list(filter(lambda x: \"label\" in x, filenames))[0]\n", - "dat_filename = list(filter(lambda x: \"label\" not in x, filenames))[0]\n", - "\n", - "# Read in the labels\n", - "with open(label_filename, \"rb\") as f:\n", - " labels = pickle.load(f)\n", - "\n", - "# Read in the corresponding configurations\n", - "with open(dat_filename, \"rb\") as f:\n", - " data = np.unpackbits(pickle.load(f)).reshape(-1, 1600).astype(\"int\")\n", - "\n", - "# Set spin-down to -1\n", - "data[data == 0] = -1" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "This dataset consists of $10000$ samples, i.e., $10000$ spin\n", - "configurations with $40 \\times 40$ spins each, for $16$ temperatures\n", - "between $0.25$ to $4.0$. Next we create a train/test-split and keep\n", - "the data in the critical phase as a separate dataset for\n", - "extrapolation-testing." - ] - }, - { - "cell_type": "code", - "execution_count": 92, - "metadata": { - "collapsed": false - }, - "outputs": [], - "source": [ - "# Set up slices of the dataset\n", - "ordered = slice(0, 70000)\n", - "critical = slice(70000, 100000)\n", - "disordered = slice(100000, 160000)\n", - "\n", - "X_train, X_test, y_train, y_test = skms.train_test_split(\n", - " np.concatenate((data[ordered], data[disordered])),\n", - " np.concatenate((labels[ordered], labels[disordered])),\n", - " test_size=0.95\n", - ")" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "Using a small training set yields a better accuracy. This will be discussed in the end.\n", - "\n", - "\n", - "## Logistic regression\n", - "\n", - "Logistic regression is a linear model for classification. Recalling\n", - "the cost function for ordinary least squares with both L2 (ridge) and\n", - "L1 (LASSO) penalties we will see that the logistic cost function is\n", - "very similar. In OLS we wish to predict a continuous variable\n", - "$\\hat{y}$ using" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "\n", - "
\n", - "\n", - "$$\n", - "\\begin{equation}\n", - " \\hat{y} = X\\omega,\n", - "\\label{_auto43} \\tag{62}\n", - "\\end{equation}\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "where $X \\in \\mathbb{R}^{n \\times p}$ is the input data and $\\omega^{p\n", - "\\times d}$ are the weights of the regression. In a classification\n", - "setting (binary classification in our situation) we are interested in\n", - "a positive or negative answer. We can thus define either answer to be\n", - "above or below some threshold. But, in order to limit the size of the\n", - "answer and also to get a probability interpretation on how sure we are\n", - "for either answer we can compute the sigmoid function of OLS. That is," - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "\n", - "
\n", - "\n", - "$$\n", - "\\begin{equation}\n", - " f(X\\omega) = \\frac{1}{1 + \\exp(-X\\omega)}.\n", - "\\label{_auto44} \\tag{63}\n", - "\\end{equation}\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "We are thus interested in minizming the following cost function" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "\n", - "
\n", - "\n", - "$$\n", - "\\begin{equation}\n", - " C(X, \\omega) = \\sum_{i = 1}^n \\left\\{\n", - " - y_i\\log\\left( f(x_i^T\\omega) \\right)\n", - " - (1 - y_i)\\log\\left[1 - f(x_i^T\\omega)\\right]\n", - " \\right\\},\n", - "\\label{_auto45} \\tag{64}\n", - "\\end{equation}\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "where we will restrict ourselves to a value for $f(z)$ as the sigmoid\n", - "described above. We can also tack on a L2 (Ridge) or L1 (LASSO)\n", - "penalization to this cost function in the same manner we did for\n", - "linear regression.\n", - "\n", - "\n", - "## Exploring the logistic regression\n", - "\n", - "The penalization factor $\\lambda$ is inverted in the case of the\n", - "logistic regression model we use. We will explore several values of\n", - "$\\lambda$ using both L1 and L2 penalization. We do this using a grid\n", - "search over different parameters and run a 3-fold cross validation for\n", - "each configuration. In other words, we fit a model 3 times for each\n", - "configuration of the hyper parameters." - ] - }, - { - "cell_type": "code", - "execution_count": 93, - "metadata": { - "collapsed": false - }, - "outputs": [], - "source": [ - "lambdas = np.logspace(-7, -1, 7)\n", - "\n", - "param_grid = {\n", - " \"C\": list(1.0/lambdas),\n", - " \"penalty\": [\"l1\", \"l2\"]\n", - "}\n", - "clf = skms.GridSearchCV(\n", - " skl.LogisticRegression(),\n", - " param_grid=param_grid,\n", - " n_jobs=-1,\n", - " return_train_score=True\n", - ")\n", - "t0 = time.time()\n", - "clf.fit(X_train, y_train)\n", - "t1 = time.time()\n", - "\n", - "print (\n", - " \"Time spent fitting GridSearchCV(LogisticRegression): {0:.3f} sec\".format(\n", - " t1 - t0\n", - " )\n", - ")" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "We can see that logistic regression is quite slow and using the grid\n", - "search and cross validation results in quite a heavy\n", - "computation. Below we show the results of the different\n", - "configurations." - ] - }, - { - "cell_type": "code", - "execution_count": 94, - "metadata": { - "collapsed": false - }, - "outputs": [], - "source": [ - "logreg_df = pd.DataFrame(clf.cv_results_)\n", - "\n", - "display(logreg_df)" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "## Accuracy of a classification model\n", - "\n", - "To determine how well a classification model is performing we count\n", - "the number of correctly labeled classes and divide by the number of\n", - "classes in total. The accuracy is thus given by" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "\n", - "
\n", - "\n", - "$$\n", - "\\begin{equation}\n", - " a(y, \\hat{y}) = \\frac{1}{n}\\sum_{i = 1}^{n} I(y_i = \\hat{y}_i),\n", - "\\label{_auto46} \\tag{65}\n", - "\\end{equation}\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "where $I(y_i = \\hat{y}_i)$ is the indicator function given by" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "\n", - "
\n", - "\n", - "$$\n", - "\\begin{equation}\n", - " I(x = y) = \\begin{array}{cc}\n", - " 1 & x = y, \\\\\n", - " 0 & x \\neq y.\n", - " \\end{array}\n", - "\\label{_auto47} \\tag{66}\n", - "\\end{equation}\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "This is the accuracy provided by Scikit-learn when using **sklearn.metrics.accuracyscore**.\n", - "\n", - "Below we compute the accuracy of the best fit model on the training data (which should give a good accuracy), the test data (which has not been shown to the model) and the critical data (completely new data that needs to be extrapolated)." - ] - }, - { - "cell_type": "code", - "execution_count": 95, - "metadata": { - "collapsed": false - }, - "outputs": [], - "source": [ - "train_accuracy = skm.accuracy_score(y_train, clf.predict(X_train))\n", - "test_accuracy = skm.accuracy_score(y_test, clf.predict(X_test))\n", - "critical_accuracy = skm.accuracy_score(labels[critical], clf.predict(data[critical]))\n", - "\n", - "print (\"Accuracy on train data: {0}\".format(train_accuracy))\n", - "print (\"Accuracy on test data: {0}\".format(test_accuracy))\n", - "print (\"Accuracy on critical data: {0}\".format(critical_accuracy))" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "We can see that we get quite good accuracy on the training data, but gradually worsening accuracy on the test and critical data.\n", - "\n", - "\n", - "## Analyzing the results\n", - "\n", - "Below we show a different metric for determining the quality of our\n", - "model, namely the **reciever operating characteristic** (ROC). The ROC\n", - "curve tells us how well the model correctly classifies the different\n", - "labels. We plot the **true positive rate** (the rate of predicted\n", - "positive classes that are positive) versus the **false positive rate**\n", - "(the rate of predicted positive classes that are negative). The ROC\n", - "curve is built by computing the true positive rate and the false\n", - "positive rate for varying **thresholds**, i.e, which probability we\n", - "should acredit a certain class.\n", - "\n", - "By computing the **area under the curve** (AUC) of the ROC curve we get an estimate of how well our model is performing. Pure guessing will get an AUC of $0.5$. A perfect score will get an AUC of $1.0$." - ] - }, - { - "cell_type": "code", - "execution_count": 96, - "metadata": { - "collapsed": false - }, - "outputs": [], - "source": [ - "fig = plt.figure(figsize=(20, 14))\n", - "\n", - "for (_X, _y), label in zip(\n", - " [\n", - " (X_train, y_train),\n", - " (X_test, y_test),\n", - " (data[critical], labels[critical])\n", - " ],\n", - " [\"Train\", \"Test\", \"Critical\"]\n", - "):\n", - " proba = clf.predict_proba(_X)\n", - " fpr, tpr, _ = skm.roc_curve(_y, proba[:, 1])\n", - " roc_auc = skm.auc(fpr, tpr)\n", - "\n", - " print (\"LogisticRegression AUC ({0}): {1}\".format(label, roc_auc))\n", - "\n", - " plt.plot(fpr, tpr, label=\"{0} (AUC = {1})\".format(label, roc_auc), linewidth=4.0)\n", - "\n", - "plt.plot([0, 1], [0, 1], \"--\", label=\"Guessing (AUC = 0.5)\", linewidth=4.0)\n", - "\n", - "plt.title(r\"The ROC curve for LogisticRegression\", fontsize=18)\n", - "plt.xlabel(r\"False positive rate\", fontsize=18)\n", - "plt.ylabel(r\"True positive rate\", fontsize=18)\n", - "plt.axis([-0.01, 1.01, -0.01, 1.01])\n", - "plt.xticks(fontsize=18)\n", - "plt.yticks(fontsize=18)\n", - "plt.legend(loc=\"best\", fontsize=18)\n", - "plt.show()" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "We can see that this plot of the ROC looks very strange. This tells us\n", - "that logistic regression is quite inept at predicting the Ising model\n", - "transition and is therefore highly non-linear. The ROC curve for the\n", - "training data looks quite good, but as the testing data is so far off\n", - "we see that we are dealing with an overfit model.\n", - "\n", - "A previous run with $50\\%$ of the data used for training yielded a\n", - "worse performance than using a smaller training set. This again gives\n", - "confidence to the fact that logistic regression is not able to\n", - "correctly fit the Ising model as it is not a linear model.\n", - "\n", - "\n", - "\n", - "\n", - "\n", - "\n", - "\n", - "# Neural networks\n", - "\n", - "Artificial neural networks are computational systems that can learn to\n", - "perform tasks by considering examples, generally without being\n", - "programmed with any task-specific rules. It is supposed to mimic a\n", - "biological system, wherein neurons interact by sending signals in the\n", - "form of mathematical functions between layers. All layers can contain\n", - "an arbitrary number of neurons, and each connection is represented by\n", - "a weight variable.\n", - "\n", - "\n", - "\n", - "## Artificial neurons\n", - "\n", - "The field of artificial neural networks has a long history of\n", - "development, and is closely connected with the advancement of computer\n", - "science and computers in general. A model of artificial neurons was\n", - "first developed by McCulloch and Pitts in 1943 to study signal\n", - "processing in the brain and has later been refined by others. The\n", - "general idea is to mimic neural networks in the human brain, which is\n", - "composed of billions of neurons that communicate with each other by\n", - "sending electrical signals. Each neuron accumulates its incoming\n", - "signals, which must exceed an activation threshold to yield an\n", - "output. If the threshold is not overcome, the neuron remains inactive,\n", - "i.e. has zero output.\n", - "\n", - "This behaviour has inspired a simple mathematical model for an artificial neuron." - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "\n", - "
\n", - "\n", - "$$\n", - "\\begin{equation}\n", - " y = f\\left(\\sum_{i=1}^n w_ix_i\\right) = f(u)\n", - "\\label{artificialNeuron} \\tag{67}\n", - "\\end{equation}\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "Here, the output $y$ of the neuron is the value of its activation function, which have as input\n", - "a weighted sum of signals $x_i, \\dots ,x_n$ received by $n$ other neurons.\n", - "\n", - "Conceptually, it is helpful to divide neural networks into four\n", - "categories:\n", - "1. general purpose neural networks for supervised learning,\n", - "\n", - "2. neural networks designed specifically for image processing, the most prominent example of this class being Convolutional Neural Networks (CNNs),\n", - "\n", - "3. neural networks for sequential data such as Recurrent Neural Networks (RNNs), and\n", - "\n", - "4. neural networks for unsupervised learning such as Deep Boltzmann Machines.\n", - "\n", - "In natural science, DNNs and CNNs have already found numerous\n", - "applications. In statistical physics, they have been applied to detect\n", - "phase transitions in 2D Ising and Potts models, lattice gauge\n", - "theories, and different phases of polymers, or solving the\n", - "Navier-Stokes equation in weather forecasting. Deep learning has also\n", - "found interesting applications in quantum physics. Various quantum\n", - "phase transitions can be detected and studied using DNNs and CNNs,\n", - "topological phases, and even non-equilibrium many-body\n", - "localization. Representing quantum states as DNNs quantum state\n", - "tomography are among some of the impressive achievements to reveal the\n", - "potential of DNNs to facilitate the study of quantum systems.\n", - "\n", - "In quantum information theory, it has been shown that one can perform\n", - "gate decompositions with the help of neural. \n", - "\n", - "The applications are not limited to the natural sciences. There is a\n", - "plethora of applications in essentially all disciplines, from the\n", - "humanities to life science and medicine.\n", - "\n", - "\n", - "## Neural network types\n", - "\n", - "An artificial neural network (ANN), is a computational model that\n", - "consists of layers of connected neurons, or nodes or units. We will\n", - "refer to these interchangeably as units or nodes, and sometimes as\n", - "neurons.\n", - "\n", - "It is supposed to mimic a biological nervous system by letting each\n", - "neuron interact with other neurons by sending signals in the form of\n", - "mathematical functions between layers. A wide variety of different\n", - "ANNs have been developed, but most of them consist of an input layer,\n", - "an output layer and eventual layers in-between, called *hidden\n", - "layers*. All layers can contain an arbitrary number of nodes, and each\n", - "connection between two nodes is associated with a weight variable.\n", - "\n", - "Neural networks (also called neural nets) are neural-inspired\n", - "nonlinear models for supervised learning. As we will see, neural nets\n", - "can be viewed as natural, more powerful extensions of supervised\n", - "learning methods such as linear and logistic regression and soft-max\n", - "methods we discussed earlier.\n", - "\n", - "\n", - "\n", - "## Feed-forward neural networks\n", - "\n", - "The feed-forward neural network (FFNN) was the first and simplest type\n", - "of ANNs that were devised. In this network, the information moves in\n", - "only one direction: forward through the layers.\n", - "\n", - "Nodes are represented by circles, while the arrows display the\n", - "connections between the nodes, including the direction of information\n", - "flow. Additionally, each arrow corresponds to a weight variable\n", - "(figure to come). We observe that each node in a layer is connected\n", - "to *all* nodes in the subsequent layer, making this a so-called\n", - "*fully-connected* FFNN.\n", - "\n", - "\n", - "\n", - "\n", - "## Convolutional Neural Network\n", - "\n", - "A different variant of FFNNs are *convolutional neural networks*\n", - "(CNNs), which have a connectivity pattern inspired by the animal\n", - "visual cortex. Individual neurons in the visual cortex only respond to\n", - "stimuli from small sub-regions of the visual field, called a receptive\n", - "field. This makes the neurons well-suited to exploit the strong\n", - "spatially local correlation present in natural images. The response of\n", - "each neuron can be approximated mathematically as a convolution\n", - "operation. (figure to come)\n", - "\n", - "Convolutional neural networks emulate the behaviour of neurons in the\n", - "visual cortex by enforcing a *local* connectivity pattern between\n", - "nodes of adjacent layers: Each node in a convolutional layer is\n", - "connected only to a subset of the nodes in the previous layer, in\n", - "contrast to the fully-connected FFNN. Often, CNNs consist of several\n", - "convolutional layers that learn local features of the input, with a\n", - "fully-connected layer at the end, which gathers all the local data and\n", - "produces the outputs. They have wide applications in image and video\n", - "recognition.\n", - "\n", - "\n", - "## Recurrent neural networks\n", - "\n", - "So far we have only mentioned ANNs where information flows in one\n", - "direction: forward. *Recurrent neural networks* on the other hand,\n", - "have connections between nodes that form directed *cycles*. This\n", - "creates a form of internal memory which are able to capture\n", - "information on what has been calculated before; the output is\n", - "dependent on the previous computations. Recurrent NNs make use of\n", - "sequential information by performing the same task for every element\n", - "in a sequence, where each element depends on previous elements. An\n", - "example of such information is sentences, making recurrent NNs\n", - "especially well-suited for handwriting and speech recognition.\n", - "\n", - "\n", - "## Other types of networks\n", - "\n", - "There are many other kinds of ANNs that have been developed. One type\n", - "that is specifically designed for interpolation in multidimensional\n", - "space is the radial basis function (RBF) network. RBFs are typically\n", - "made up of three layers: an input layer, a hidden layer with\n", - "non-linear radial symmetric activation functions and a linear output\n", - "layer (''linear'' here means that each node in the output layer has a\n", - "linear activation function). The layers are normally fully-connected\n", - "and there are no cycles, thus RBFs can be viewed as a type of\n", - "fully-connected FFNN. They are however usually treated as a separate\n", - "type of NN due the unusual activation functions.\n", - "\n", - "\n", - "## Multilayer perceptrons\n", - "\n", - "One uses often so-called fully-connected feed-forward neural networks\n", - "with three or more layers (an input layer, one or more hidden layers\n", - "and an output layer) consisting of neurons that have non-linear\n", - "activation functions.\n", - "\n", - "Such networks are often called *multilayer perceptrons* (MLPs).\n", - "\n", - "\n", - "## Why multilayer perceptrons?\n", - "\n", - "According to the *Universal approximation theorem*, a feed-forward\n", - "neural network with just a single hidden layer containing a finite\n", - "number of neurons can approximate a continuous multidimensional\n", - "function to arbitrary accuracy, assuming the activation function for\n", - "the hidden layer is a **non-constant, bounded and\n", - "monotonically-increasing continuous function**.\n", - "\n", - "Note that the requirements on the activation function only applies to\n", - "the hidden layer, the output nodes are always assumed to be linear, so\n", - "as to not restrict the range of output values.\n", - "\n", - "\n", - "\n", - "## Mathematical model\n", - "\n", - "The output $y$ is produced via the activation function $f$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "y = f\\left(\\sum_{i=1}^n w_ix_i + b_i\\right) = f(z),\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "This function receives $x_i$ as inputs.\n", - "Here the activation $z=(\\sum_{i=1}^n w_ix_i+b_i)$. \n", - "In an FFNN of such neurons, the *inputs* $x_i$ are the *outputs* of\n", - "the neurons in the preceding layer. Furthermore, an MLP is\n", - "fully-connected, which means that each neuron receives a weighted sum\n", - "of the outputs of *all* neurons in the previous layer.\n", - "\n", - "\n", - "## Mathematical model\n", - "\n", - "First, for each node $i$ in the first hidden layer, we calculate a weighted sum $z_i^1$ of the input coordinates $x_j$," - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "\n", - "
\n", - "\n", - "$$\n", - "\\begin{equation} z_i^1 = \\sum_{j=1}^{M} w_{ij}^1 x_j + b_i^1\n", - "\\label{_auto48} \\tag{68}\n", - "\\end{equation}\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "Here $b_i$ is the so-called bias which is normally needed in\n", - "case of zero activation weights or inputs. How to fix the biases and\n", - "the weights will be discussed below. The value of $z_i^1$ is the\n", - "argument to the activation function $f_i$ of each node $i$, The\n", - "variable $M$ stands for all possible inputs to a given node $i$ in the\n", - "first layer. We define the output $y_i^1$ of all neurons in layer 1 as" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "\n", - "
\n", - "\n", - "$$\n", - "\\begin{equation}\n", - " y_i^1 = f(z_i^1) = f\\left(\\sum_{j=1}^M w_{ij}^1 x_j + b_i^1\\right)\n", - "\\label{outputLayer1} \\tag{69}\n", - "\\end{equation}\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "where we assume that all nodes in the same layer have identical\n", - "activation functions, hence the notation $f$. In general, we could assume in the more general case that different layers have different activation functions.\n", - "In this case we would identify these functions with a superscript $l$ for the $l$-th layer," - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "\n", - "
\n", - "\n", - "$$\n", - "\\begin{equation}\n", - " y_i^l = f^l(u_i^l) = f^l\\left(\\sum_{j=1}^{N_{l-1}} w_{ij}^l y_j^{l-1} + b_i^l\\right)\n", - "\\label{generalLayer} \\tag{70}\n", - "\\end{equation}\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "where $N_l$ is the number of nodes in layer $l$. When the output of\n", - "all the nodes in the first hidden layer are computed, the values of\n", - "the subsequent layer can be calculated and so forth until the output\n", - "is obtained.\n", - "\n", - "\n", - "\n", - "\n", - "## Mathematical model\n", - "\n", - "The output of neuron $i$ in layer 2 is thus," - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "\n", - "
\n", - "\n", - "$$\n", - "\\begin{equation}\n", - " y_i^2 = f^2\\left(\\sum_{j=1}^N w_{ij}^2 y_j^1 + b_i^2\\right) \n", - "\\label{_auto49} \\tag{71}\n", - "\\end{equation}\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "\n", - "
\n", - "\n", - "$$\n", - "\\begin{equation} \n", - " = f^2\\left[\\sum_{j=1}^N w_{ij}^2f^1\\left(\\sum_{k=1}^M w_{jk}^1 x_k + b_j^1\\right) + b_i^2\\right]\n", - "\\label{outputLayer2} \\tag{72}\n", - "\\end{equation}\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "where we have substituted $y_k^1$ with the inputs $x_k$. Finally, the ANN output reads" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "\n", - "
\n", - "\n", - "$$\n", - "\\begin{equation}\n", - " y_i^3 = f^3\\left(\\sum_{j=1}^N w_{ij}^3 y_j^2 + b_i^3\\right) \n", - "\\label{_auto50} \\tag{73}\n", - "\\end{equation}\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "\n", - "
\n", - "\n", - "$$\n", - "\\begin{equation} \n", - " = f_3\\left[\\sum_{j} w_{ij}^3 f^2\\left(\\sum_{k} w_{jk}^2 f^1\\left(\\sum_{m} w_{km}^1 x_m + b_k^1\\right) + b_j^2\\right)\n", - " + b_1^3\\right]\n", - "\\label{_auto51} \\tag{74}\n", - "\\end{equation}\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "## Mathematical model\n", - "\n", - "We can generalize this expression to an MLP with $l$ hidden\n", - "layers. The complete functional form is," - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "\n", - "
\n", - "\n", - "$$\n", - "\\begin{equation}\n", - "y^{l+1}_i = f^{l+1}\\left[\\!\\sum_{j=1}^{N_l} w_{ij}^3 f^l\\left(\\sum_{k=1}^{N_{l-1}}w_{jk}^{l-1}\\left(\\dots f^1\\left(\\sum_{n=1}^{N_0} w_{mn}^1 x_n+ b_m^1\\right)\\dots\\right)+b_k^2\\right)+b_1^3\\right] \n", - "\\label{completeNN} \\tag{75}\n", - "\\end{equation}\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "which illustrates a basic property of MLPs: The only independent\n", - "variables are the input values $x_n$.\n", - "\n", - "\n", - "## Mathematical model\n", - "\n", - "This confirms that an MLP, despite its quite convoluted mathematical\n", - "form, is nothing more than an analytic function, specifically a\n", - "mapping of real-valued vectors $\\hat{x} \\in \\mathbb{R}^n \\rightarrow\n", - "\\hat{y} \\in \\mathbb{R}^m$.\n", - "\n", - "Furthermore, the flexibility and universality of an MLP can be\n", - "illustrated by realizing that the expression is essentially a nested\n", - "sum of scaled activation functions of the form" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "\n", - "
\n", - "\n", - "$$\n", - "\\begin{equation}\n", - " f(x) = c_1 f(c_2 x + c_3) + c_4\n", - "\\label{_auto52} \\tag{76}\n", - "\\end{equation}\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "where the parameters $c_i$ are weights and biases. By adjusting these\n", - "parameters, the activation functions can be shifted up and down or\n", - "left and right, change slope or be rescaled which is the key to the\n", - "flexibility of a neural network.\n", - "\n", - "\n", - "### Matrix-vector notation\n", - "\n", - "We can introduce a more convenient notation for the activations in an A NN. \n", - "\n", - "Additionally, we can represent the biases and activations\n", - "as layer-wise column vectors $\\hat{b}_l$ and $\\hat{y}_l$, so that the $i$-th element of each vector \n", - "is the bias $b_i^l$ and activation $y_i^l$ of node $i$ in layer $l$ respectively. \n", - "\n", - "We have that $\\mathrm{W}_l$ is an $N_{l-1} \\times N_l$ matrix, while $\\hat{b}_l$ and $\\hat{y}_l$ are $N_l \\times 1$ column vectors. \n", - "With this notation, the sum becomes a matrix-vector multiplication, and we can write\n", - "the equation for the activations of hidden layer 2 (assuming three nodes for simplicity) as" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "\n", - "
\n", - "\n", - "$$\n", - "\\begin{equation}\n", - " \\hat{y}_2 = f_2(\\mathrm{W}_2 \\hat{y}_{1} + \\hat{b}_{2}) = \n", - " f_2\\left(\\left[\\begin{array}{ccc}\n", - " w^2_{11} &w^2_{12} &w^2_{13} \\\\\n", - " w^2_{21} &w^2_{22} &w^2_{23} \\\\\n", - " w^2_{31} &w^2_{32} &w^2_{33} \\\\\n", - " \\end{array} \\right] \\cdot\n", - " \\left[\\begin{array}{c}\n", - " y^1_1 \\\\\n", - " y^1_2 \\\\\n", - " y^1_3 \\\\\n", - " \\end{array}\\right] + \n", - " \\left[\\begin{array}{c}\n", - " b^2_1 \\\\\n", - " b^2_2 \\\\\n", - " b^2_3 \\\\\n", - " \\end{array}\\right]\\right).\n", - "\\label{_auto53} \\tag{77}\n", - "\\end{equation}\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "### Matrix-vector notation and activation\n", - "\n", - "The activation of node $i$ in layer 2 is" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "\n", - "
\n", - "\n", - "$$\n", - "\\begin{equation}\n", - " y^2_i = f_2\\Bigr(w^2_{i1}y^1_1 + w^2_{i2}y^1_2 + w^2_{i3}y^1_3 + b^2_i\\Bigr) = \n", - " f_2\\left(\\sum_{j=1}^3 w^2_{ij} y_j^1 + b^2_i\\right).\n", - "\\label{_auto54} \\tag{78}\n", - "\\end{equation}\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "This is not just a convenient and compact notation, but also a useful\n", - "and intuitive way to think about MLPs: The output is calculated by a\n", - "series of matrix-vector multiplications and vector additions that are\n", - "used as input to the activation functions. For each operation\n", - "$\\mathrm{W}_l \\hat{y}_{l-1}$ we move forward one layer.\n", - "\n", - "\n", - "\n", - "### Activation functions\n", - "\n", - "A property that characterizes a neural network, other than its\n", - "connectivity, is the choice of activation function(s). As described\n", - "in, the following restrictions are imposed on an activation function\n", - "for a FFNN to fulfill the universal approximation theorem\n", - "\n", - " * Non-constant\n", - "\n", - " * Bounded\n", - "\n", - " * Monotonically-increasing\n", - "\n", - " * Continuous\n", - "\n", - "### Activation functions, Logistic and Hyperbolic ones\n", - "\n", - "The second requirement excludes all linear functions. Furthermore, in\n", - "a MLP with only linear activation functions, each layer simply\n", - "performs a linear transformation of its inputs.\n", - "\n", - "Regardless of the number of layers, the output of the NN will be\n", - "nothing but a linear function of the inputs. Thus we need to introduce\n", - "some kind of non-linearity to the NN to be able to fit non-linear\n", - "functions Typical examples are the logistic *Sigmoid*" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "f(x) = \\frac{1}{1 + e^{-x}},\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "and the *hyperbolic tangent* function" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "f(x) = \\tanh(x)\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "### Relevance\n", - "\n", - "The *sigmoid* function are more biologically plausible because the\n", - "output of inactive neurons are zero. Such activation function are\n", - "called *one-sided*. However, it has been shown that the hyperbolic\n", - "tangent performs better than the sigmoid for training MLPs. has\n", - "become the most popular for *deep neural networks*" - ] - }, - { - "cell_type": "code", - "execution_count": 97, - "metadata": { - "collapsed": false - }, - "outputs": [], - "source": [ - "\"\"\"The sigmoid function (or the logistic curve) is a \n", - "function that takes any real number, z, and outputs a number (0,1).\n", - "It is useful in neural networks for assigning weights on a relative scale.\n", - "The value z is the weighted sum of parameters involved in the learning algorithm.\"\"\"\n", - "\n", - "import numpy\n", - "import matplotlib.pyplot as plt\n", - "import math as mt\n", - "\n", - "z = numpy.arange(-5, 5, .1)\n", - "sigma_fn = numpy.vectorize(lambda z: 1/(1+numpy.exp(-z)))\n", - "sigma = sigma_fn(z)\n", - "\n", - "fig = plt.figure()\n", - "ax = fig.add_subplot(111)\n", - "ax.plot(z, sigma)\n", - "ax.set_ylim([-0.1, 1.1])\n", - "ax.set_xlim([-5,5])\n", - "ax.grid(True)\n", - "ax.set_xlabel('z')\n", - "ax.set_title('sigmoid function')\n", - "\n", - "plt.show()\n", - "\n", - "\"\"\"Step Function\"\"\"\n", - "z = numpy.arange(-5, 5, .02)\n", - "step_fn = numpy.vectorize(lambda z: 1.0 if z >= 0.0 else 0.0)\n", - "step = step_fn(z)\n", - "\n", - "fig = plt.figure()\n", - "ax = fig.add_subplot(111)\n", - "ax.plot(z, step)\n", - "ax.set_ylim([-0.5, 1.5])\n", - "ax.set_xlim([-5,5])\n", - "ax.grid(True)\n", - "ax.set_xlabel('z')\n", - "ax.set_title('step function')\n", - "\n", - "plt.show()\n", - "\n", - "\"\"\"Sine Function\"\"\"\n", - "z = numpy.arange(-2*mt.pi, 2*mt.pi, 0.1)\n", - "t = numpy.sin(z)\n", - "\n", - "fig = plt.figure()\n", - "ax = fig.add_subplot(111)\n", - "ax.plot(z, t)\n", - "ax.set_ylim([-1.0, 1.0])\n", - "ax.set_xlim([-2*mt.pi,2*mt.pi])\n", - "ax.grid(True)\n", - "ax.set_xlabel('z')\n", - "ax.set_title('sine function')\n", - "\n", - "plt.show()\n", - "\n", - "\"\"\"Plots a graph of the squashing function used by a rectified linear\n", - "unit\"\"\"\n", - "z = numpy.arange(-2, 2, .1)\n", - "zero = numpy.zeros(len(z))\n", - "y = numpy.max([zero, z], axis=0)\n", - "\n", - "fig = plt.figure()\n", - "ax = fig.add_subplot(111)\n", - "ax.plot(z, y)\n", - "ax.set_ylim([-2.0, 2.0])\n", - "ax.set_xlim([-2.0, 2.0])\n", - "ax.grid(True)\n", - "ax.set_xlabel('z')\n", - "ax.set_title('Rectified linear unit')\n", - "\n", - "plt.show()" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "## The multilayer perceptron (MLP)\n", - "\n", - "The multilayer perceptron is a very popular, and easy to implement approach, to deep learning. It consists of\n", - "1. A neural network with one or more layers of nodes between the input and the output nodes.\n", - "\n", - "2. The multilayer network structure, or architecture, or topology, consists of an input layer, one or more hidden layers, and one output layer.\n", - "\n", - "3. The input nodes pass values to the first hidden layer, its nodes pass the information on to the second and so on till we reach the output layer.\n", - "\n", - "As a convention it is normal to call a network with one layer of input units, one layer of hidden\n", - "units and one layer of output units as a two-layer network. A network with two layers of hidden units is called a three-layer network etc etc.\n", - "\n", - "For an MLP network there is no direct connection between the output nodes/neurons/units and the input nodes/neurons/units.\n", - "Hereafter we will call the various entities of a layer for nodes.\n", - "There are also no connections within a single layer.\n", - "\n", - "The number of input nodes does not need to equal the number of output\n", - "nodes. This applies also to the hidden layers. Each layer may have its\n", - "own number of nodes and activation functions.\n", - "\n", - "The hidden layers have their name from the fact that they are not\n", - "linked to observables and as we will see below when we define the\n", - "so-called activation $\\hat{z}$, we can think of this as a basis\n", - "expansion of the original inputs $\\hat{x}$. The difference however\n", - "between neural networks and say linear regression is that now these\n", - "basis functions (which will correspond to the weights in the network)\n", - "are learned from data. This results in an important difference between\n", - "neural networks and deep learning approaches on one side and methods\n", - "like logistic regression or linear regression and their modifications on the other side.\n", - "\n", - "\n", - "\n", - "## From one to many layers, the universal approximation theorem\n", - "\n", - "\n", - "A neural network with only one layer, what we called the simple\n", - "perceptron, is best suited if we have a standard binary model with\n", - "clear (linear) boundaries between the outcomes. As such it could\n", - "equally well be replaced by standard linear regression or logistic\n", - "regression. Networks with one or more hidden layers approximate\n", - "systems with more complex boundaries.\n", - "\n", - "As stated earlier, \n", - "an important theorem in studies of neural networks, restated without\n", - "proof here, is the [universal approximation\n", - "theorem](http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.441.7873&rep=rep1&type=pdf).\n", - "\n", - "It states that a feed-forward network with a single hidden layer\n", - "containing a finite number of neurons can approximate continuous\n", - "functions on compact subsets of real functions. The theorem thus\n", - "states that simple neural networks can represent a wide variety of\n", - "interesting functions when given appropriate parameters. It is the\n", - "multilayer feedforward architecture itself which gives neural networks\n", - "the potential of being universal approximators.\n", - "\n", - "\n", - "\n", - "## Deriving the back propagation code for a multilayer perceptron model\n", - "\n", - "\n", - "**Note: figures will be inserted later!**\n", - "\n", - "As we have seen now in a feed forward network, we can express the final output of our network in terms of basic matrix-vector multiplications.\n", - "The unknowwn quantities are our weights $w_{ij}$ and we need to find an algorithm for changing them so that our errors are as small as possible.\n", - "This leads us to the famous [back propagation algorithm](https://www.nature.com/articles/323533a0).\n", - "\n", - "The questions we want to ask are how do changes in the biases and the\n", - "weights in our network change the cost function and how can we use the\n", - "final output to modify the weights?\n", - "\n", - "To derive these equations let us start with a plain regression problem\n", - "and define our cost function as" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "{\\cal C}(\\hat{W}) = \\frac{1}{2}\\sum_{i=1}^n\\left(y_i - t_i\\right)^2,\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "where the $t_i$s are our $n$ targets (the values we want to\n", - "reproduce), while the outputs of the network after having propagated\n", - "all inputs $\\hat{x}$ are given by $y_i$. Below we will demonstrate\n", - "how the basic equations arising from the back propagation algorithm\n", - "can be modified in order to study classification problems with $K$\n", - "classes.\n", - "\n", - "\n", - "## Definitions\n", - "\n", - "With our definition of the targets $\\hat{t}$, the outputs of the\n", - "network $\\hat{y}$ and the inputs $\\hat{x}$ we\n", - "define now the activation $z_j^l$ of node/neuron/unit $j$ of the\n", - "$l$-th layer as a function of the bias, the weights which add up from\n", - "the previous layer $l-1$ and the forward passes/outputs\n", - "$\\hat{a}^{l-1}$ from the previous layer as" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "z_j^l = \\sum_{i=1}^{M_{l-1}}w_{ij}^la_i^{l-1}+b_j^l,\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "where $b_k^l$ are the biases from layer $l$. Here $M_{l-1}$\n", - "represents the total number of nodes/neurons/units of layer $l-1$. The\n", - "figure here illustrates this equation. We can rewrite this in a more\n", - "compact form as the matrix-vector products we discussed earlier," - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "\\hat{z}^l = \\left(\\hat{W}^l\\right)^T\\hat{a}^{l-1}+\\hat{b}^l.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "With the activation values $\\hat{z}^l$ we can in turn define the\n", - "output of layer $l$ as $\\hat{a}^l = f(\\hat{z}^l)$ where $f$ is our\n", - "activation function. In the examples here we will use the sigmoid\n", - "function discussed in our logistic regression lectures. We will also use the same activation function $f$ for all layers\n", - "and their nodes. It means we have" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "a_j^l = f(z_j^l) = \\frac{1}{1+\\exp{-(z_j^l)}}.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "## Derivatives and the chain rule\n", - "\n", - "From the definition of the activation $z_j^l$ we have" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "\\frac{\\partial z_j^l}{\\partial w_{ij}^l} = a_i^{l-1},\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "and" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "\\frac{\\partial z_j^l}{\\partial a_i^{l-1}} = w_{ji}^l.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "With our definition of the activation function we have that (note that this function depends only on $z_j^l$)" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "\\frac{\\partial a_j^l}{\\partial z_j^{l}} = a_j^l(1-a_j^l)=f(z_j^l)(1-f(z_j^l)).\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "## Derivative of the cost function\n", - "\n", - "With these definitions we can now compute the derivative of the cost function in terms of the weights.\n", - "\n", - "Let us specialize to the output layer $l=L$. Our cost function is" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "{\\cal C}(\\hat{W^L}) = \\frac{1}{2}\\sum_{i=1}^n\\left(y_i - t_i\\right)^2=\\frac{1}{2}\\sum_{i=1}^n\\left(a_i^L - t_i\\right)^2,\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "The derivative of this function with respect to the weights is" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "\\frac{\\partial{\\cal C}(\\hat{W^L})}{\\partial w_{jk}^L} = \\left(a_j^L - t_j\\right)\\frac{\\partial a_j^L}{\\partial w_{jk}^{L}},\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "The last partial derivative can easily be computed and reads (by applying the chain rule)" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "\\frac{\\partial a_j^L}{\\partial w_{jk}^{L}} = \\frac{\\partial a_j^L}{\\partial z_{j}^{L}}\\frac{\\partial z_j^L}{\\partial w_{jk}^{L}}=a_j^L(1-a_j^L)a_k^{L-1},\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "## Bringing it together, first back propagation equation\n", - "\n", - "We have thus" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "\\frac{\\partial{\\cal C}(\\hat{W^L})}{\\partial w_{jk}^L} = \\left(a_j^L - t_j\\right)a_j^L(1-a_j^L)a_k^{L-1},\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "Defining" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "\\delta_j^L = a_j^L(1-a_j^L)\\left(a_j^L - t_j\\right) = f'(z_j^L)\\frac{\\partial {\\cal C}}{\\partial (a_j^L)},\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "and using the Hadamard product of two vectors we can write this as" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "\\hat{\\delta}^L = f'(\\hat{z}^L)\\circ\\frac{\\partial {\\cal C}}{\\partial (\\hat{a}L)}.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "This is an important expression. The second term on the right handside\n", - "measures how fast the cost function is changing as a function of the $j$th\n", - "output activation. If, for example, the cost function doesn't depend\n", - "much on a particular output node $j$, then $\\delta_j^L$ will be small,\n", - "which is what we would expect. The first term on the right, measures\n", - "how fast the activation function $f$ is changing at a given activation\n", - "value $z_j^L$.\n", - "\n", - "Notice that everything in the above equations is easily computed. In\n", - "particular, we compute $z_j^L$ while computing the behaviour of the\n", - "network, and it is only a small additional overhead to compute\n", - "$f'(z^L_j)$. The exact form of the derivative with respect to the\n", - "output depends on the form of the cost function.\n", - "However, provided the cost function is known there should be little\n", - "trouble in calculating" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "\\frac{\\partial {\\cal C}}{\\partial (a_j^L)}\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "With the definition of $\\delta_j^L$ we have a more compact definition of the derivative of the cost function in terms of the weights, namely" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "\\frac{\\partial{\\cal C}(\\hat{W^L})}{\\partial w_{jk}^L} = \\delta_j^La_k^{L-1}.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "## Derivatives in terms of $z_j^L$\n", - "\n", - "It is also easy to see that our previous equation can be written as" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "\\delta_j^L =\\frac{\\partial {\\cal C}}{\\partial z_j^L}= \\frac{\\partial {\\cal C}}{\\partial a_j^L}\\frac{\\partial a_j^L}{\\partial z_j^L},\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "which can also be interpreted as the partial derivative of the cost function with respect to the biases $b_j^L$, namely" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "\\delta_j^L = \\frac{\\partial {\\cal C}}{\\partial b_j^L}\\frac{\\partial b_j^L}{\\partial z_j^L}=\\frac{\\partial {\\cal C}}{\\partial b_j^L},\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "That is, the error $\\delta_j^L$ is exactly equal to the rate of change of the cost function as a function of the bias. \n", - "\n", - "## Bringing it together\n", - "\n", - "We have now three equations that are essential for the computations of the derivatives of the cost function at the output layer. These equations are needed to start the algorithm and they are\n", - "\n", - " The starting equations" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "\n", - "
\n", - "\n", - "$$\n", - "\\begin{equation}\n", - "\\frac{\\partial{\\cal C}(\\hat{W^L})}{\\partial w_{jk}^L} = \\delta_j^La_k^{L-1},\n", - "\\label{_auto55} \\tag{79}\n", - "\\end{equation}\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "and" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "\n", - "
\n", - "\n", - "$$\n", - "\\begin{equation}\n", - "\\delta_j^L = f'(z_j^L)\\frac{\\partial {\\cal C}}{\\partial (a_j^L)},\n", - "\\label{_auto56} \\tag{80}\n", - "\\end{equation}\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "and" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "\n", - "
\n", - "\n", - "$$\n", - "\\begin{equation}\n", - "\\delta_j^L = \\frac{\\partial {\\cal C}}{\\partial b_j^L},\n", - "\\label{_auto57} \\tag{81}\n", - "\\end{equation}\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "An interesting consequence of the above equations is that when the\n", - "activation $a_k^{L-1}$ is small, the gradient term, that is the\n", - "derivative of the cost function with respect to the weights, will also\n", - "tend to be small. We say then that the weight learns slowly, meaning\n", - "that it changes slowly when we minimize the weights via say gradient\n", - "descent. In this case we say the system learns slowly.\n", - "\n", - "Another interesting feature is that is when the activation function,\n", - "represented by the sigmoid function here, is rather flat when we move towards\n", - "its end values $0$ and $1$ (see the above Python codes). In these\n", - "cases, the derivatives of the activation function will also be close\n", - "to zero, meaning again that the gradients will be small and the\n", - "network learns slowly again.\n", - "\n", - "\n", - "\n", - "We need a fourth equation and we are set. We are going to propagate\n", - "backwards in order to the determine the weights and biases. In order\n", - "to do so we need to represent the error in the layer before the final\n", - "one $L-1$ in terms of the errors in the final output layer.\n", - "\n", - "\n", - "## Final back propagating equation\n", - "\n", - "We have that (replacing $L$ with a general layer $l$)" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "\\delta_j^l =\\frac{\\partial {\\cal C}}{\\partial z_j^l}.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "We want to express this in terms of the equations for layer $l+1$. Using the chain rule and summing over all $k$ entries we have" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "\\delta_j^l =\\sum_k \\frac{\\partial {\\cal C}}{\\partial z_k^{l+1}}\\frac{\\partial z_k^{l+1}}{\\partial z_j^{l}}=\\sum_k \\delta_k^{l+1}\\frac{\\partial z_k^{l+1}}{\\partial z_j^{l}},\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "and recalling that" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "z_j^{l+1} = \\sum_{i=1}^{M_{l}}w_{ij}^{l+1}a_j^{l}+b_j^{l+1},\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "with $M_l$ being the number of nodes in layer $l$, we obtain" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "\\delta_j^l =\\sum_k \\delta_k^{l+1}w_{kj}^{l+1}f'(z_j^l),\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "This is our final equation.\n", - "\n", - "We are now ready to set up the algorithm for back propagation and learning the weights and biases.\n", - "\n", - "\n", - "## Setting up the Back propagation algorithm\n", - "\n", - "\n", - "\n", - "The four equations provide us with a way of computing the gradient of the cost function. Let us write this out in the form of an algorithm.\n", - "\n", - "\n", - "First, we set up the input data $\\hat{x}$ and the activations\n", - "$\\hat{z}_1$ of the input layer and compute the activation function and\n", - "the pertinent outputs $\\hat{a}^1$.\n", - "\n", - "\n", - "\n", - "Secondly, we perform then the feed forward till we reach the output\n", - "layer and compute all $\\hat{z}_l$ of the input layer and compute the\n", - "activation function and the pertinent outputs $\\hat{a}^l$ for\n", - "$l=2,3,\\dots,L$.\n", - "\n", - "\n", - "\n", - "Thereafter we compute the ouput error $\\hat{\\delta}^L$ by computing all" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "\\delta_j^L = f'(z_j^L)\\frac{\\partial {\\cal C}}{\\partial (a_j^L)}.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "Then we compute the back propagate error for each $l=L-1,L-2,\\dots,2$ as" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "\\delta_j^l = \\sum_k \\delta_k^{l+1}w_{kj}^{l+1}f'(z_j^l).\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "Finally, we update the weights and the biases using gradient descent for each $l=L-1,L-2,\\dots,2$ and update the weights and biases according to the rules" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "w_{jk}^l\\leftarrow = w_{jk}^l- \\eta \\delta_j^la_k^{l-1},\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "b_j^l \\leftarrow b_j^l-\\eta \\frac{\\partial {\\cal C}}{\\partial b_j^l}=b_j^l-\\eta \\delta_j^l,\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "The parameter $\\eta$ is the learning parameter discussed in connection with the gradient descent methods.\n", - "Here it is convenient to use stochastic gradient descent (see the examples below) with mini-batches with an outer loop that steps through multiple epochs of training.\n", - "\n", - "\n", - "\n", - "## Setting up a Multi-layer perceptron model for classification\n", - "\n", - "We are now gong to develop an example based on the MNIST data\n", - "base. This is a classification problem and we need to use our\n", - "cross-entropy function we discussed in connection with logistic\n", - "regression. The cross-entropy defines our cost function for the\n", - "classificaton problems with neural networks.\n", - "\n", - "In binary classification with two classes $(0, 1)$ we define the\n", - "logistic/sigmoid function as the probability that a particular input\n", - "is in class $0$ or $1$. This is possible because the logistic\n", - "function takes any input from the real numbers and inputs a number\n", - "between 0 and 1, and can therefore be interpreted as a probability. It\n", - "also has other nice properties, such as a derivative that is simple to\n", - "calculate.\n", - "\n", - "For an input $\\boldsymbol{a}$ from the hidden layer, the probability that the input $\\boldsymbol{x}$\n", - "is in class 0 or 1 is just. We let $\\theta$ represent the unknown weights and biases to be adjusted by our equations). The variable $x$\n", - "represents our activation values $z$. We have" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "P(y = 0 \\mid \\hat{x}, \\hat{\\theta}) = \\frac{1}{1 + \\exp{(- \\hat{x}})} ,\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "and" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "P(y = 1 \\mid \\hat{x}, \\hat{\\theta}) = 1 - P(y = 0 \\mid \\hat{x}, \\hat{\\theta}) ,\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "where $y \\in \\{0, 1\\}$ and $\\hat{\\theta}$ represents the weights and biases\n", - "of our network.\n", - "\n", - "\n", - "\n", - "## Defining the cost function\n", - "\n", - "Our cost function is given as (see the Logistic regression lectures)" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "\\mathcal{C}(\\hat{\\theta}) = - \\ln P(\\mathcal{D} \\mid \\hat{\\theta}) = - \\sum_{i=1}^n\n", - "y_i \\ln[P(y_i = 0)] + (1 - y_i) \\ln [1 - P(y_i = 0)] = \\sum_{i=1}^n \\mathcal{L}_i(\\hat{\\theta}) .\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "This last equality means that we can interpret our *cost* function as a sum over the *loss* function\n", - "for each point in the dataset $\\mathcal{L}_i(\\hat{\\theta})$. \n", - "The negative sign is just so that we can think about our algorithm as minimizing a positive number, rather\n", - "than maximizing a negative number. \n", - "\n", - "In *multiclass* classification it is common to treat each integer label as a so called *one-hot* vector: \n", - "\n", - "$y = 5 \\quad \\rightarrow \\quad \\hat{y} = (0, 0, 0, 0, 0, 1, 0, 0, 0, 0) ,$ and\n", - "\n", - "\n", - "$y = 1 \\quad \\rightarrow \\quad \\hat{y} = (0, 1, 0, 0, 0, 0, 0, 0, 0, 0) ,$ \n", - "\n", - "\n", - "i.e. a binary bit string of length $C$, where $C = 10$ is the number of classes in the MNIST dataset (numbers from $0$ to $9$).. \n", - "\n", - "If $\\hat{x}_i$ is the $i$-th input (image), $y_{ic}$ refers to the $c$-th component of the $i$-th\n", - "output vector $\\hat{y}_i$. \n", - "The probability of $\\hat{x}_i$ being in class $c$ will be given by the softmax function:" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "P(y_{ic} = 1 \\mid \\hat{x}_i, \\hat{\\theta}) = \\frac{\\exp{((\\hat{a}_i^{hidden})^T \\hat{w}_c)}}\n", - "{\\sum_{c'=0}^{C-1} \\exp{((\\hat{a}_i^{hidden})^T \\hat{w}_{c'})}} ,\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "which reduces to the logistic function in the binary case. \n", - "The likelihood of this $C$-class classifier\n", - "is now given as:" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "P(\\mathcal{D} \\mid \\hat{\\theta}) = \\prod_{i=1}^n \\prod_{c=0}^{C-1} [P(y_{ic} = 1)]^{y_{ic}} .\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "Again we take the negative log-likelihood to define our cost function:" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "\\mathcal{C}(\\hat{\\theta}) = - \\log{P(\\mathcal{D} \\mid \\hat{\\theta})}.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "See the logistic regression lectures for a full definition of the cost function.\n", - "\n", - "The back propagation equations need now only a small change, namely the definition of a new cost function. We are thus ready to use the same equations as before!\n", - "\n", - "\n", - "## Example: binary classification problem\n", - "\n", - "As an example of the above, relevant for project 2 as well, let us consider a binary class. As discussed in our logistic regression lectures, we defined a cost function in terms of the parameters $\\beta$ as" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "\\mathcal{C}(\\hat{\\beta}) = - \\sum_{i=1}^n \\left(y_i\\log{p(y_i \\vert x_i,\\hat{\\beta})}+(i-y_i)\\log{1-p(y_i \\vert x_i,\\hat{\\beta})}\\right),\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "where we had defined the logistic (sigmoid) function" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "p(y_i =1\\vert x_i,\\hat{\\beta})=\\frac{\\exp{(\\beta_0+\\beta_1 x_i)}}{1+\\exp{(\\beta_0+\\beta_1 x_i)}},\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "and" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "p(y_i =0\\vert x_i,\\hat{\\beta})=1-p(y_i =1\\vert x_i,\\hat{\\beta}).\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "The parameters $\\hat{\\beta}$ were defined using a minimization method like gradient descent or Newton-Raphson's method. \n", - "\n", - "Now we replace $x_i$ with the activation $z_i^l$ for a given layer $l$ and the outputs as $y_i=a_i^l=f(z_i^l)$, with $z_i^l$ now being a function of the weights $w_{ij}^l$ and biases $b_i^l$. \n", - "We have then" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "a_i^l = y_i = \\frac{\\exp{(z_i^l)}}{1+\\exp{(z_i^l)}},\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "with" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "z_i^l = \\sum_{j}w_{ij}^l a_j^{l-1}+b_i^l,\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "where the superscript $l-1$ indicates that these are the outputs from layer $l-1$.\n", - "Our cost function at the final layer $l=L$ is now" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "\\mathcal{C}(\\hat{W}) = - \\sum_{i=1}^n \\left(t_i\\log{a_i^L}+(i-t_i)\\log{(1-a_i^L)}\\right),\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "where we have defined the targets $t_i$. The derivatives of the cost function with respect to the output $a_i^L$ are then easily calculated and we get" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "\\frac{\\partial \\mathcal{C}(\\hat{W})}{\\partial a_i^L} = \\frac{a_i^L-t_i}{a_i^L(1-a_i^L)}.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "In case we use another activation function than the logistic one, we need to evaluate other derivatives. \n", - "\n", - "\n", - "\n", - "## The Softmax function\n", - "In case we employ the more general case given by the Softmax equation, we need to evaluate the derivative of the activation function with respect to the activation $z_i^l$, that is we need" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "\\frac{\\partial f(z_i^l)}{\\partial w_{jk}^l} =\n", - "\\frac{\\partial f(z_i^l)}{\\partial z_j^l} \\frac{\\partial z_j^l}{\\partial w_{jk}^l}= \\frac{\\partial f(z_i^l)}{\\partial z_j^l}a_k^{l-1}.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "For the Softmax function we have" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "f(z_i^l) = \\frac{\\exp{(z_i^l)}}{\\sum_{m=1}^K\\exp{(z_m^l)}}.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "Its derivative with respect to $z_j^l$ gives" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "\\frac{\\partial f(z_i^l)}{\\partial z_j^l}= f(z_i^l)\\left(\\delta_{ij}-f(z_j^l)\\right),\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "which in case of the simply binary model reduces to having $i=j$. \n", - "\n", - "\n", - "## Developing a code for doing neural networks with back propagation\n", - "\n", - "\n", - "One can identify a set of key steps when using neural networks to solve supervised learning problems: \n", - "\n", - "1. Collect and pre-process data \n", - "\n", - "2. Define model and architecture \n", - "\n", - "3. Choose cost function and optimizer \n", - "\n", - "4. Train the model \n", - "\n", - "5. Evaluate model performance on test data \n", - "\n", - "6. Adjust hyperparameters (if necessary, network architecture)\n", - "\n", - "## Collect and pre-process data\n", - "\n", - "Here we will be using the MNIST dataset, which is readily available through the **scikit-learn**\n", - "package. You may also find it for example [here](http://yann.lecun.com/exdb/mnist/). \n", - "The *MNIST* (Modified National Institute of Standards and Technology) database is a large database\n", - "of handwritten digits that is commonly used for training various image processing systems. \n", - "The MNIST dataset consists of 70 000 images of size 28x28 pixels, each labeled from 0 to 9. \n", - "The scikit-learn dataset we will use consists of a selection of 1797 images of size $8\\times 8$ collected and processed from this database. \n", - "\n", - "To feed data into a feed-forward neural network we need to represent\n", - "the inputs as a feature matrix $X = (n_{inputs}, n_{features})$. Each\n", - "row represents an *input*, in this case a handwritten digit, and\n", - "each column represents a *feature*, in this case a pixel. The\n", - "correct answers, also known as *labels* or *targets* are\n", - "represented as a 1D array of integers \n", - "$Y = (n_{inputs}) = (5, 3, 1, 8,...)$.\n", - "\n", - "As an example, say we want to build a neural network using supervised learning to predict Body-Mass Index (BMI) from\n", - "measurements of height (in m) \n", - "and weight (in kg). If we have measurements of 5 people the feature matrix could be for example: \n", - "\n", - "$$ X = \\begin{bmatrix}\n", - "1.85 & 81\\\\\n", - "1.71 & 65\\\\\n", - "1.95 & 103\\\\\n", - "1.55 & 42\\\\\n", - "1.63 & 56\n", - "\\end{bmatrix} ,$$ \n", - "\n", - "and the targets would be: \n", - "\n", - "$$ Y = (23.7, 22.2, 27.1, 17.5, 21.1) $$ \n", - "\n", - "Since each input image is a 2D matrix, we need to flatten the image\n", - "(i.e. \"unravel\" the 2D matrix into a 1D array) to turn the data into a\n", - "feature matrix. This means we lose all spatial information in the\n", - "image, such as locality and translational invariance. More complicated\n", - "architectures such as Convolutional Neural Networks can take advantage\n", - "of such information, and are most commonly applied when analyzing\n", - "images." - ] - }, - { - "cell_type": "code", - "execution_count": 98, - "metadata": { - "collapsed": false - }, - "outputs": [], - "source": [ - "# import necessary packages\n", - "import numpy as np\n", - "import matplotlib.pyplot as plt\n", - "from sklearn import datasets\n", - "\n", - "\n", - "# ensure the same random numbers appear every time\n", - "np.random.seed(0)\n", - "\n", - "# display images in notebook\n", - "%matplotlib inline\n", - "plt.rcParams['figure.figsize'] = (12,12)\n", - "\n", - "\n", - "# download MNIST dataset\n", - "digits = datasets.load_digits()\n", - "\n", - "# define inputs and labels\n", - "inputs = digits.images\n", - "labels = digits.target\n", - "\n", - "print(\"inputs = (n_inputs, pixel_width, pixel_height) = \" + str(inputs.shape))\n", - "print(\"labels = (n_inputs) = \" + str(labels.shape))\n", - "\n", - "\n", - "# flatten the image\n", - "# the value -1 means dimension is inferred from the remaining dimensions: 8x8 = 64\n", - "n_inputs = len(inputs)\n", - "inputs = inputs.reshape(n_inputs, -1)\n", - "print(\"X = (n_inputs, n_features) = \" + str(inputs.shape))\n", - "\n", - "\n", - "# choose some random images to display\n", - "indices = np.arange(n_inputs)\n", - "random_indices = np.random.choice(indices, size=5)\n", - "\n", - "for i, image in enumerate(digits.images[random_indices]):\n", - " plt.subplot(1, 5, i+1)\n", - " plt.axis('off')\n", - " plt.imshow(image, cmap=plt.cm.gray_r, interpolation='nearest')\n", - " plt.title(\"Label: %d\" % digits.target[random_indices[i]])\n", - "plt.show()" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "## Train and test datasets\n", - "\n", - "Performing analysis before partitioning the dataset is a major error, that can lead to incorrect conclusions. \n", - "\n", - "We will reserve $80 \\%$ of our dataset for training and $20 \\%$ for testing. \n", - "\n", - "It is important that the train and test datasets are drawn randomly from our dataset, to ensure\n", - "no bias in the sampling. \n", - "Say you are taking measurements of weather data to predict the weather in the coming 5 days.\n", - "You don't want to train your model on measurements taken from the hours 00.00 to 12.00, and then test it on data\n", - "collected from 12.00 to 24.00." - ] - }, - { - "cell_type": "code", - "execution_count": 99, - "metadata": { - "collapsed": false - }, - "outputs": [], - "source": [ - "from sklearn.model_selection import train_test_split\n", - "\n", - "# one-liner from scikit-learn library\n", - "train_size = 0.8\n", - "test_size = 1 - train_size\n", - "X_train, X_test, Y_train, Y_test = train_test_split(inputs, labels, train_size=train_size,\n", - " test_size=test_size)\n", - "\n", - "# equivalently in numpy\n", - "def train_test_split_numpy(inputs, labels, train_size, test_size):\n", - " n_inputs = len(inputs)\n", - " inputs_shuffled = inputs.copy()\n", - " labels_shuffled = labels.copy()\n", - " \n", - " np.random.shuffle(inputs_shuffled)\n", - " np.random.shuffle(labels_shuffled)\n", - " \n", - " train_end = int(n_inputs*train_size)\n", - " X_train, X_test = inputs_shuffled[:train_end], inputs_shuffled[train_end:]\n", - " Y_train, Y_test = labels_shuffled[:train_end], labels_shuffled[train_end:]\n", - " \n", - " return X_train, X_test, Y_train, Y_test\n", - "\n", - "#X_train, X_test, Y_train, Y_test = train_test_split_numpy(inputs, labels, train_size, test_size)\n", - "\n", - "print(\"Number of training images: \" + str(len(X_train)))\n", - "print(\"Number of test images: \" + str(len(X_test)))" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "## Define model and architecture\n", - "\n", - "Our simple feed-forward neural network will consist of an *input* layer, a single *hidden* layer and an *output* layer. The activation $y$ of each neuron is a weighted sum of inputs, passed through an activation function. In case of the simple perceptron model we have \n", - "\n", - "$$ z = \\sum_{i=1}^n w_i a_i ,$$\n", - "\n", - "$$ y = f(z) ,$$\n", - "\n", - "where $f$ is the activation function, $a_i$ represents input from neuron $i$ in the preceding layer\n", - "and $w_i$ is the weight to input $i$. \n", - "The activation of the neurons in the input layer is just the features (e.g. a pixel value). \n", - "\n", - "The simplest activation function for a neuron is the *Heaviside* function:\n", - "\n", - "$$ f(z) = \n", - "\\begin{cases}\n", - "1, & z > 0\\\\\n", - "0, & \\text{otherwise}\n", - "\\end{cases}\n", - "$$\n", - "\n", - "A feed-forward neural network with this activation is known as a *perceptron*. \n", - "For a binary classifier (i.e. two classes, 0 or 1, dog or not-dog) we can also use this in our output layer. \n", - "This activation can be generalized to $k$ classes (using e.g. the *one-against-all* strategy), \n", - "and we call these architectures *multiclass perceptrons*. \n", - "\n", - "However, it is now common to use the terms Single Layer Perceptron (SLP) (1 hidden layer) and \n", - "Multilayer Perceptron (MLP) (2 or more hidden layers) to refer to feed-forward neural networks with any activation function. \n", - "\n", - "Typical choices for activation functions include the sigmoid function, hyperbolic tangent, and Rectified Linear Unit (ReLU). \n", - "We will be using the sigmoid function $\\sigma(x)$: \n", - "\n", - "$$ f(x) = \\sigma(x) = \\frac{1}{1 + e^{-x}} ,$$\n", - "\n", - "which is inspired by probability theory (see logistic regression) and was most commonly used until about 2011. See the discussion below concerning other activation functions.\n", - "\n", - "\n", - "## Layers\n", - "\n", - "* Input \n", - "\n", - "Since each input image has 8x8 = 64 pixels or features, we have an input layer of 64 neurons. \n", - "\n", - "* Hidden layer\n", - "\n", - "We will use 50 neurons in the hidden layer receiving input from the neurons in the input layer. \n", - "Since each neuron in the hidden layer is connected to the 64 inputs we have 64x50 = 3200 weights to the hidden layer. \n", - "\n", - "* Output\n", - "\n", - "If we were building a binary classifier, it would be sufficient with a single neuron in the output layer,\n", - "which could output 0 or 1 according to the Heaviside function. This would be an example of a *hard* classifier, meaning it outputs the class of the input directly. However, if we are dealing with noisy data it is often beneficial to use a *soft* classifier, which outputs the probability of being in class 0 or 1. \n", - "\n", - "For a soft binary classifier, we could use a single neuron and interpret the output as either being the probability of being in class 0 or the probability of being in class 1. Alternatively we could use 2 neurons, and interpret each neuron as the probability of being in each class. \n", - "\n", - "Since we are doing multiclass classification, with 10 categories, it is natural to use 10 neurons in the output layer. We number the neurons $j = 0,1,...,9$. The activation of each output neuron $j$ will be according to the *softmax* function: \n", - "\n", - "$$ P(\\text{class $j$} \\mid \\text{input $\\hat{a}$}) = \\frac{\\exp{(\\hat{a}^T \\hat{w}_j)}}\n", - "{\\sum_{c=0}^{9} \\exp{(\\hat{a}^T \\hat{w}_c)}} ,$$ \n", - "\n", - "i.e. each neuron $j$ outputs the probability of being in class $j$ given an input from the hidden layer $\\hat{a}$, with $\\hat{w}_j$ the weights of neuron $j$ to the inputs. \n", - "The denominator is a normalization factor to ensure the outputs (probabilities) sum up to 1. \n", - "The exponent is just the weighted sum of inputs as before: \n", - "\n", - "$$ z_j = \\sum_{i=1}^n w_ {ij} a_i+b_j.$$ \n", - "\n", - "Since each neuron in the output layer is connected to the 50 inputs from the hidden layer we have 50x10 = 500\n", - "weights to the output layer.\n", - "\n", - "\n", - "## Weights and biases\n", - "\n", - "Typically weights are initialized with small values distributed around zero, drawn from a uniform\n", - "or normal distribution. Setting all weights to zero means all neurons give the same output, making the network useless. \n", - "\n", - "Adding a bias value to the weighted sum of inputs allows the neural network to represent a greater range\n", - "of values. Without it, any input with the value 0 will be mapped to zero (before being passed through the activation). The bias unit has an output of 1, and a weight to each neuron $j$, $b_j$: \n", - "\n", - "$$ z_j = \\sum_{i=1}^n w_ {ij} a_i + b_j.$$ \n", - "\n", - "The bias weights $\\hat{b}$ are often initialized to zero, but a small value like $0.01$ ensures all neurons have some output which can be backpropagated in the first training cycle." - ] - }, - { - "cell_type": "code", - "execution_count": 100, - "metadata": { - "collapsed": false - }, - "outputs": [], - "source": [ - "# building our neural network\n", - "\n", - "n_inputs, n_features = X_train.shape\n", - "n_hidden_neurons = 50\n", - "n_categories = 10\n", - "\n", - "# we make the weights normally distributed using numpy.random.randn\n", - "\n", - "# weights and bias in the hidden layer\n", - "hidden_weights = np.random.randn(n_features, n_hidden_neurons)\n", - "hidden_bias = np.zeros(n_hidden_neurons) + 0.01\n", - "\n", - "# weights and bias in the output layer\n", - "output_weights = np.random.randn(n_hidden_neurons, n_categories)\n", - "output_bias = np.zeros(n_categories) + 0.01" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "## Feed-forward pass\n", - "\n", - "Denote $F$ the number of features, $H$ the number of hidden neurons and $C$ the number of categories. \n", - "For each input image we calculate a weighted sum of input features (pixel values) to each neuron $j$ in the hidden layer $l$: \n", - "\n", - "$$ z_{j}^{l} = \\sum_{i=1}^{F} w_{ij}^{l} x_i + b_{j}^{l},$$\n", - "\n", - "this is then passed through our activation function \n", - "\n", - "$$ a_{j}^{l} = f(z_{j}^{l}) .$$ \n", - "\n", - "We calculate a weighted sum of inputs (activations in the hidden layer) to each neuron $j$ in the output layer: \n", - "\n", - "$$ z_{j}^{L} = \\sum_{i=1}^{H} w_{ij}^{L} a_{i}^{l} + b_{j}^{L}.$$ \n", - "\n", - "Finally we calculate the output of neuron $j$ in the output layer using the softmax function: \n", - "\n", - "$$ a_{j}^{L} = \\frac{\\exp{(z_j^{L})}}\n", - "{\\sum_{c=0}^{C-1} \\exp{(z_c^{L})}} .$$ \n", - "\n", - "\n", - "## Matrix multiplications\n", - "\n", - "Since our data has the dimensions $X = (n_{inputs}, n_{features})$ and our weights to the hidden\n", - "layer have the dimensions \n", - "$W_{hidden} = (n_{features}, n_{hidden})$,\n", - "we can easily feed the network all our training data in one go by taking the matrix product \n", - "\n", - "$$ X W^{h} = (n_{inputs}, n_{hidden}),$$ \n", - "\n", - "and obtain a matrix that holds the weighted sum of inputs to the hidden layer\n", - "for each input image and each hidden neuron. \n", - "We also add the bias to obtain a matrix of weighted sums to the hidden layer $Z^{h}$: \n", - "\n", - "$$ \\hat{z}^{l} = \\hat{X} \\hat{W}^{l} + \\hat{b}^{l} ,$$\n", - "\n", - "meaning the same bias (1D array with size equal number of hidden neurons) is added to each input image. \n", - "This is then passed through the activation: \n", - "\n", - "$$ \\hat{a}^{l} = f(\\hat{z}^l) .$$ \n", - "\n", - "This is fed to the output layer: \n", - "\n", - "$$ \\hat{z}^{L} = \\hat{a}^{L} \\hat{W}^{L} + \\hat{b}^{L} .$$\n", - "\n", - "Finally we receive our output values for each image and each category by passing it through the softmax function: \n", - "\n", - "$$ output = softmax (\\hat{z}^{L}) = (n_{inputs}, n_{categories}) .$$" - ] - }, - { - "cell_type": "code", - "execution_count": 101, - "metadata": { - "collapsed": false - }, - "outputs": [], - "source": [ - "# setup the feed-forward pass, subscript h = hidden layer\n", - "\n", - "def sigmoid(x):\n", - " return 1/(1 + np.exp(-x))\n", - "\n", - "def feed_forward(X):\n", - " # weighted sum of inputs to the hidden layer\n", - " z_h = np.matmul(X, hidden_weights) + hidden_bias\n", - " # activation in the hidden layer\n", - " a_h = sigmoid(z_h)\n", - " \n", - " # weighted sum of inputs to the output layer\n", - " z_o = np.matmul(a_h, output_weights) + output_bias\n", - " # softmax output\n", - " # axis 0 holds each input and axis 1 the probabilities of each category\n", - " exp_term = np.exp(z_o)\n", - " probabilities = exp_term / np.sum(exp_term, axis=1, keepdims=True)\n", - " \n", - " return probabilities\n", - "\n", - "probabilities = feed_forward(X_train)\n", - "print(\"probabilities = (n_inputs, n_categories) = \" + str(probabilities.shape))\n", - "print(\"probability that image 0 is in category 0,1,2,...,9 = \\n\" + str(probabilities[0]))\n", - "print(\"probabilities sum up to: \" + str(probabilities[0].sum()))\n", - "print()\n", - "\n", - "# we obtain a prediction by taking the class with the highest likelihood\n", - "def predict(X):\n", - " probabilities = feed_forward(X)\n", - " return np.argmax(probabilities, axis=1)\n", - "\n", - "predictions = predict(X_train)\n", - "print(\"predictions = (n_inputs) = \" + str(predictions.shape))\n", - "print(\"prediction for image 0: \" + str(predictions[0]))\n", - "print(\"correct label for image 0: \" + str(Y_train[0]))" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "## Choose cost function and optimizer\n", - "\n", - "To measure how well our neural network is doing we need to introduce a cost function. \n", - "We will call the function that gives the error of a single sample output the *loss* function, and the function\n", - "that gives the total error of our network across all samples the *cost* function.\n", - "A typical choice for multiclass classification is the *cross-entropy* loss, also known as the negative log likelihood. \n", - "\n", - "In *multiclass* classification it is common to treat each integer label as a so called *one-hot* vector: \n", - "\n", - "$$ y = 5 \\quad \\rightarrow \\quad \\hat{y} = (0, 0, 0, 0, 0, 1, 0, 0, 0, 0) ,$$ \n", - "\n", - "\n", - "$$ y = 1 \\quad \\rightarrow \\quad \\hat{y} = (0, 1, 0, 0, 0, 0, 0, 0, 0, 0) ,$$ \n", - "\n", - "\n", - "i.e. a binary bit string of length $C$, where $C = 10$ is the number of classes in the MNIST dataset. \n", - "\n", - "Let $y_{ic}$ denote the $c$-th component of the $i$-th one-hot vector. \n", - "We define the cost function $\\mathcal{C}$ as a sum over the cross-entropy loss for each point $\\hat{x}_i$ in the dataset.\n", - "\n", - "In the one-hot representation only one of the terms in the loss function is non-zero, namely the\n", - "probability of the correct category $c'$ \n", - "(i.e. the category $c'$ such that $y_{ic'} = 1$). This means that the cross entropy loss only punishes you for how wrong\n", - "you got the correct label. The probability of category $c$ is given by the softmax function. The vector $\\hat{\\theta}$ represents the parameters of our network, i.e. all the weights and biases. \n", - "\n", - "\n", - "\n", - "## Optimizing the cost function\n", - "\n", - "The network is trained by finding the weights and biases that minimize the cost function. One of the most widely used classes of methods is *gradient descent* and its generalizations. The idea behind gradient descent\n", - "is simply to adjust the weights in the direction where the gradient of the cost function is large and negative. This ensures we flow toward a *local* minimum of the cost function. \n", - "Each parameter $\\theta$ is iteratively adjusted according to the rule \n", - "\n", - "$$ \\theta_{i+1} = \\theta_i - \\eta \\nabla \\mathcal{C}(\\theta_i) ,$$\n", - "\n", - "where $\\eta$ is known as the *learning rate*, which controls how big a step we take towards the minimum. \n", - "This update can be repeated for any number of iterations, or until we are satisfied with the result. \n", - "\n", - "A simple and effective improvement is a variant called *Batch Gradient Descent*. \n", - "Instead of calculating the gradient on the whole dataset, we calculate an approximation of the gradient\n", - "on a subset of the data called a *minibatch*. \n", - "If there are $N$ data points and we have a minibatch size of $M$, the total number of batches\n", - "is $N/M$. \n", - "We denote each minibatch $B_k$, with $k = 1, 2,...,N/M$. The gradient then becomes: \n", - "\n", - "$$ \\nabla \\mathcal{C}(\\theta) = \\frac{1}{N} \\sum_{i=1}^N \\nabla \\mathcal{L}_i(\\theta) \\quad \\rightarrow \\quad\n", - "\\frac{1}{M} \\sum_{i \\in B_k} \\nabla \\mathcal{L}_i(\\theta) ,$$\n", - "\n", - "i.e. instead of averaging the loss over the entire dataset, we average over a minibatch. \n", - "\n", - "This has two important benefits: \n", - "1. Introducing stochasticity decreases the chance that the algorithm becomes stuck in a local minima. \n", - "\n", - "2. It significantly speeds up the calculation, since we do not have to use the entire dataset to calculate the gradient. \n", - "\n", - "The various optmization methods, with codes and algorithms, are discussed in our lectures on [Gradient descent approaches](https://compphysics.github.io/MachineLearning/doc/pub/Splines/html/Splines-bs.html).\n", - "\n", - "\n", - "## Regularization\n", - "\n", - "It is common to add an extra term to the cost function, proportional\n", - "to the size of the weights. This is equivalent to constraining the\n", - "size of the weights, so that they do not grow out of control.\n", - "Constraining the size of the weights means that the weights cannot\n", - "grow arbitrarily large to fit the training data, and in this way\n", - "reduces *overfitting*.\n", - "\n", - "We will measure the size of the weights using the so called *L2-norm*, meaning our cost function becomes: \n", - "\n", - "$$ \\nabla \\mathcal{C}(\\theta) = \\frac{1}{N} \\sum_{i=1}^N \\nabla \\mathcal{L}_i(\\theta) \\quad \\rightarrow \\quad\n", - "\\frac{1}{N} \\sum_{i=1}^N \\nabla \\mathcal{L}_i(\\theta) + \\lambda \\lvert \\lvert \\hat{w} \\rvert \\rvert_2^2 \n", - "= \\frac{1}{N} \\sum_{i=1}^N \\nabla \\mathcal{L}(\\theta) + \\lambda \\sum_{ij} w_{ij}^2,$$ \n", - "\n", - "i.e. we sum up all the weights squared. The factor $\\lambda$ is known as a regularization parameter.\n", - "\n", - "\n", - "In order to train the model, we need to calculate the derivative of\n", - "the cost function with respect to every bias and weight in the\n", - "network. In total our network has $(64 + 1)\\times 50=3250$ weights in\n", - "the hidden layer and $(50 + 1)\\times 10=510$ weights to the output\n", - "layer ($+1$ for the bias), and the gradient must be calculated for\n", - "every parameter. We use the *backpropagation* algorithm discussed\n", - "above. This is a clever use of the chain rule that allows us to\n", - "calculate the gradient efficently. \n", - "\n", - "\n", - "\n", - "## Matrix multiplication\n", - "\n", - "To more efficently train our network these equations are implemented using matrix operations. \n", - "The error in the output layer is calculated simply as, with $\\hat{t}$ being our targets, \n", - "\n", - "$$ \\delta_L = \\hat{t} - \\hat{y} = (n_{inputs}, n_{categories}) .$$ \n", - "\n", - "The gradient for the output weights is calculated as \n", - "\n", - "$$ \\nabla W_{L} = \\hat{a}^T \\delta_L = (n_{hidden}, n_{categories}) ,$$\n", - "\n", - "where $\\hat{a} = (n_{inputs}, n_{hidden})$. This simply means that we are summing up the gradients for each input. \n", - "Since we are going backwards we have to transpose the activation matrix. \n", - "\n", - "The gradient with respect to the output bias is then \n", - "\n", - "$$ \\nabla \\hat{b}_{L} = \\sum_{i=1}^{n_{inputs}} \\delta_L = (n_{categories}) .$$ \n", - "\n", - "The error in the hidden layer is \n", - "\n", - "$$ \\Delta_h = \\delta_L W_{L}^T \\circ f'(z_{h}) = \\delta_L W_{L}^T \\circ a_{h} \\circ (1 - a_{h}) = (n_{inputs}, n_{hidden}) ,$$ \n", - "\n", - "where $f'(a_{h})$ is the derivative of the activation in the hidden layer. The matrix products mean\n", - "that we are summing up the products for each neuron in the output layer. The symbol $\\circ$ denotes\n", - "the *Hadamard product*, meaning element-wise multiplication. \n", - "\n", - "This again gives us the gradients in the hidden layer: \n", - "\n", - "$$ \\nabla W_{h} = X^T \\delta_h = (n_{features}, n_{hidden}) ,$$ \n", - "\n", - "$$ \\nabla b_{h} = \\sum_{i=1}^{n_{inputs}} \\delta_h = (n_{hidden}) .$$" - ] - }, - { - "cell_type": "code", - "execution_count": 102, - "metadata": { - "collapsed": false - }, - "outputs": [], - "source": [ - "# to categorical turns our integer vector into a onehot representation\n", - "from sklearn.metrics import accuracy_score\n", - "\n", - "# one-hot in numpy\n", - "def to_categorical_numpy(integer_vector):\n", - " n_inputs = len(integer_vector)\n", - " n_categories = np.max(integer_vector) + 1\n", - " onehot_vector = np.zeros((n_inputs, n_categories))\n", - " onehot_vector[range(n_inputs), integer_vector] = 1\n", - " \n", - " return onehot_vector\n", - "\n", - "#Y_train_onehot, Y_test_onehot = to_categorical(Y_train), to_categorical(Y_test)\n", - "Y_train_onehot, Y_test_onehot = to_categorical_numpy(Y_train), to_categorical_numpy(Y_test)\n", - "\n", - "def feed_forward_train(X):\n", - " # weighted sum of inputs to the hidden layer\n", - " z_h = np.matmul(X, hidden_weights) + hidden_bias\n", - " # activation in the hidden layer\n", - " a_h = sigmoid(z_h)\n", - " \n", - " # weighted sum of inputs to the output layer\n", - " z_o = np.matmul(a_h, output_weights) + output_bias\n", - " # softmax output\n", - " # axis 0 holds each input and axis 1 the probabilities of each category\n", - " exp_term = np.exp(z_o)\n", - " probabilities = exp_term / np.sum(exp_term, axis=1, keepdims=True)\n", - " \n", - " # for backpropagation need activations in hidden and output layers\n", - " return a_h, probabilities\n", - "\n", - "def backpropagation(X, Y):\n", - " a_h, probabilities = feed_forward_train(X)\n", - " \n", - " # error in the output layer\n", - " error_output = probabilities - Y\n", - " # error in the hidden layer\n", - " error_hidden = np.matmul(error_output, output_weights.T) * a_h * (1 - a_h)\n", - " \n", - " # gradients for the output layer\n", - " output_weights_gradient = np.matmul(a_h.T, error_output)\n", - " output_bias_gradient = np.sum(error_output, axis=0)\n", - " \n", - " # gradient for the hidden layer\n", - " hidden_weights_gradient = np.matmul(X.T, error_hidden)\n", - " hidden_bias_gradient = np.sum(error_hidden, axis=0)\n", - "\n", - " return output_weights_gradient, output_bias_gradient, hidden_weights_gradient, hidden_bias_gradient\n", - "\n", - "print(\"Old accuracy on training data: \" + str(accuracy_score(predict(X_train), Y_train)))\n", - "\n", - "eta = 0.01\n", - "lmbd = 0.01\n", - "for i in range(1000):\n", - " # calculate gradients\n", - " dWo, dBo, dWh, dBh = backpropagation(X_train, Y_train_onehot)\n", - " \n", - " # regularization term gradients\n", - " dWo += lmbd * output_weights\n", - " dWh += lmbd * hidden_weights\n", - " \n", - " # update weights and biases\n", - " output_weights -= eta * dWo\n", - " output_bias -= eta * dBo\n", - " hidden_weights -= eta * dWh\n", - " hidden_bias -= eta * dBh\n", - "\n", - "print(\"New accuracy on training data: \" + str(accuracy_score(predict(X_train), Y_train)))" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "## Improving performance\n", - "\n", - "As we can see the network does not seem to be learning at all. It seems to be just guessing the label for each image. \n", - "In order to obtain a network that does something useful, we will have to do a bit more work. \n", - "\n", - "The choice of *hyperparameters* such as learning rate and regularization parameter is hugely influential for the performance of the network. Typically a *grid-search* is performed, wherein we test different hyperparameters separated by orders of magnitude. For example we could test the learning rates $\\eta = 10^{-6}, 10^{-5},...,10^{-1}$ with different regularization parameters $\\lambda = 10^{-6},...,10^{-0}$. \n", - "\n", - "Next, we haven't implemented minibatching yet, which introduces stochasticity and is though to act as an important regularizer on the weights. We call a feed-forward + backward pass with a minibatch an *iteration*, and a full training period\n", - "going through the entire dataset ($n/M$ batches) an *epoch*.\n", - "\n", - "If this does not improve network performance, you may want to consider altering the network architecture, adding more neurons or hidden layers. \n", - "Andrew Ng goes through some of these considerations in this [video](https://youtu.be/F1ka6a13S9I). You can find a summary of the video [here](https://kevinzakka.github.io/2016/09/26/applying-deep-learning/). \n", - "\n", - "\n", - "## Full object-oriented implementation\n", - "\n", - "It is very natural to think of the network as an object, with specific instances of the network\n", - "being realizations of this object with different hyperparameters. An implementation using Python classes provides a clean structure and interface, and the full implementation of our neural network is given below." - ] - }, - { - "cell_type": "code", - "execution_count": 103, - "metadata": { - "collapsed": false - }, - "outputs": [], - "source": [ - "class NeuralNetwork:\n", - " def __init__(\n", - " self,\n", - " X_data,\n", - " Y_data,\n", - " n_hidden_neurons=50,\n", - " n_categories=10,\n", - " epochs=10,\n", - " batch_size=100,\n", - " eta=0.1,\n", - " lmbd=0.0,\n", - "\n", - " ):\n", - " self.X_data_full = X_data\n", - " self.Y_data_full = Y_data\n", - "\n", - " self.n_inputs = X_data.shape[0]\n", - " self.n_features = X_data.shape[1]\n", - " self.n_hidden_neurons = n_hidden_neurons\n", - " self.n_categories = n_categories\n", - "\n", - " self.epochs = epochs\n", - " self.batch_size = batch_size\n", - " self.iterations = self.n_inputs // self.batch_size\n", - " self.eta = eta\n", - " self.lmbd = lmbd\n", - "\n", - " self.create_biases_and_weights()\n", - "\n", - " def create_biases_and_weights(self):\n", - " self.hidden_weights = np.random.randn(self.n_features, self.n_hidden_neurons)\n", - " self.hidden_bias = np.zeros(self.n_hidden_neurons) + 0.01\n", - "\n", - " self.output_weights = np.random.randn(self.n_hidden_neurons, self.n_categories)\n", - " self.output_bias = np.zeros(self.n_categories) + 0.01\n", - "\n", - " def feed_forward(self):\n", - " # feed-forward for training\n", - " self.z_h = np.matmul(self.X_data, self.hidden_weights) + self.hidden_bias\n", - " self.a_h = sigmoid(self.z_h)\n", - "\n", - " self.z_o = np.matmul(self.a_h, self.output_weights) + self.output_bias\n", - "\n", - " exp_term = np.exp(self.z_o)\n", - " self.probabilities = exp_term / np.sum(exp_term, axis=1, keepdims=True)\n", - "\n", - " def feed_forward_out(self, X):\n", - " # feed-forward for output\n", - " z_h = np.matmul(X, self.hidden_weights) + self.hidden_bias\n", - " a_h = sigmoid(z_h)\n", - "\n", - " z_o = np.matmul(a_h, self.output_weights) + self.output_bias\n", - " \n", - " exp_term = np.exp(z_o)\n", - " probabilities = exp_term / np.sum(exp_term, axis=1, keepdims=True)\n", - " return probabilities\n", - "\n", - " def backpropagation(self):\n", - " error_output = self.probabilities - self.Y_data\n", - " error_hidden = np.matmul(error_output, self.output_weights.T) * self.a_h * (1 - self.a_h)\n", - "\n", - " self.output_weights_gradient = np.matmul(self.a_h.T, error_output)\n", - " self.output_bias_gradient = np.sum(error_output, axis=0)\n", - "\n", - " self.hidden_weights_gradient = np.matmul(self.X_data.T, error_hidden)\n", - " self.hidden_bias_gradient = np.sum(error_hidden, axis=0)\n", - "\n", - " if self.lmbd > 0.0:\n", - " self.output_weights_gradient += self.lmbd * self.output_weights\n", - " self.hidden_weights_gradient += self.lmbd * self.hidden_weights\n", - "\n", - " self.output_weights -= self.eta * self.output_weights_gradient\n", - " self.output_bias -= self.eta * self.output_bias_gradient\n", - " self.hidden_weights -= self.eta * self.hidden_weights_gradient\n", - " self.hidden_bias -= self.eta * self.hidden_bias_gradient\n", - "\n", - " def predict(self, X):\n", - " probabilities = self.feed_forward_out(X)\n", - " return np.argmax(probabilities, axis=1)\n", - "\n", - " def predict_probabilities(self, X):\n", - " probabilities = self.feed_forward_out(X)\n", - " return probabilities\n", - "\n", - " def train(self):\n", - " data_indices = np.arange(self.n_inputs)\n", - "\n", - " for i in range(self.epochs):\n", - " for j in range(self.iterations):\n", - " # pick datapoints with replacement\n", - " chosen_datapoints = np.random.choice(\n", - " data_indices, size=self.batch_size, replace=False\n", - " )\n", - "\n", - " # minibatch training data\n", - " self.X_data = self.X_data_full[chosen_datapoints]\n", - " self.Y_data = self.Y_data_full[chosen_datapoints]\n", - "\n", - " self.feed_forward()\n", - " self.backpropagation()" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "## Evaluate model performance on test data\n", - "\n", - "To measure the performance of our network we evaluate how well it does it data it has never seen before, i.e. the test data. \n", - "We measure the performance of the network using the *accuracy* score. \n", - "The accuracy is as you would expect just the number of images correctly labeled divided by the total number of images. A perfect classifier will have an accuracy score of $1$. \n", - "\n", - "$$ \\text{Accuracy} = \\frac{\\sum_{i=1}^n I(\\hat{y}_i = y_i)}{n} ,$$ \n", - "\n", - "where $I$ is the indicator function, $1$ if $\\hat{y}_i = y_i$ and $0$ otherwise." - ] - }, - { - "cell_type": "code", - "execution_count": 104, - "metadata": { - "collapsed": false - }, - "outputs": [], - "source": [ - "epochs = 100\n", - "batch_size = 100\n", - "\n", - "dnn = NeuralNetwork(X_train, Y_train_onehot, eta=eta, lmbd=lmbd, epochs=epochs, batch_size=batch_size,\n", - " n_hidden_neurons=n_hidden_neurons, n_categories=n_categories)\n", - "dnn.train()\n", - "test_predict = dnn.predict(X_test)\n", - "\n", - "# accuracy score from scikit library\n", - "print(\"Accuracy score on test set: \", accuracy_score(Y_test, test_predict))\n", - "\n", - "# equivalent in numpy\n", - "def accuracy_score_numpy(Y_test, Y_pred):\n", - " return np.sum(Y_test == Y_pred) / len(Y_test)\n", - "\n", - "#print(\"Accuracy score on test set: \", accuracy_score_numpy(Y_test, test_predict))" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "## Adjust hyperparameters\n", - "\n", - "We now perform a grid search to find the optimal hyperparameters for the network. \n", - "Note that we are only using 1 layer with 50 neurons, and human performance is estimated to be around $98\\%$ ($2\\%$ error rate)." - ] - }, - { - "cell_type": "code", - "execution_count": 105, - "metadata": { - "collapsed": false - }, - "outputs": [], - "source": [ - "eta_vals = np.logspace(-5, 1, 7)\n", - "lmbd_vals = np.logspace(-5, 1, 7)\n", - "# store the models for later use\n", - "DNN_numpy = np.zeros((len(eta_vals), len(lmbd_vals)), dtype=object)\n", - "\n", - "# grid search\n", - "for i, eta in enumerate(eta_vals):\n", - " for j, lmbd in enumerate(lmbd_vals):\n", - " dnn = NeuralNetwork(X_train, Y_train_onehot, eta=eta, lmbd=lmbd, epochs=epochs, batch_size=batch_size,\n", - " n_hidden_neurons=n_hidden_neurons, n_categories=n_categories)\n", - " dnn.train()\n", - " \n", - " DNN_numpy[i][j] = dnn\n", - " \n", - " test_predict = dnn.predict(X_test)\n", - " \n", - " print(\"Learning rate = \", eta)\n", - " print(\"Lambda = \", lmbd)\n", - " print(\"Accuracy score on test set: \", accuracy_score(Y_test, test_predict))\n", - " print()" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "## Visualization" - ] - }, - { - "cell_type": "code", - "execution_count": 106, - "metadata": { - "collapsed": false - }, - "outputs": [], - "source": [ - "# visual representation of grid search\n", - "# uses seaborn heatmap, you can also do this with matplotlib imshow\n", - "import seaborn as sns\n", - "\n", - "sns.set()\n", - "\n", - "train_accuracy = np.zeros((len(eta_vals), len(lmbd_vals)))\n", - "test_accuracy = np.zeros((len(eta_vals), len(lmbd_vals)))\n", - "\n", - "for i in range(len(eta_vals)):\n", - " for j in range(len(lmbd_vals)):\n", - " dnn = DNN_numpy[i][j]\n", - " \n", - " train_pred = dnn.predict(X_train) \n", - " test_pred = dnn.predict(X_test)\n", - "\n", - " train_accuracy[i][j] = accuracy_score(Y_train, train_pred)\n", - " test_accuracy[i][j] = accuracy_score(Y_test, test_pred)\n", - "\n", - " \n", - "fig, ax = plt.subplots(figsize = (10, 10))\n", - "sns.heatmap(train_accuracy, annot=True, ax=ax, cmap=\"viridis\")\n", - "ax.set_title(\"Training Accuracy\")\n", - "ax.set_ylabel(\"$\\eta$\")\n", - "ax.set_xlabel(\"$\\lambda$\")\n", - "plt.show()\n", - "\n", - "fig, ax = plt.subplots(figsize = (10, 10))\n", - "sns.heatmap(test_accuracy, annot=True, ax=ax, cmap=\"viridis\")\n", - "ax.set_title(\"Test Accuracy\")\n", - "ax.set_ylabel(\"$\\eta$\")\n", - "ax.set_xlabel(\"$\\lambda$\")\n", - "plt.show()" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "## scikit-learn implementation\n", - "\n", - "**scikit-learn** focuses more\n", - "on traditional machine learning methods, such as regression,\n", - "clustering, decision trees, etc. As such, it has only two types of\n", - "neural networks: Multi Layer Perceptron outputting continuous values,\n", - "*MPLRegressor*, and Multi Layer Perceptron outputting labels,\n", - "*MLPClassifier*. We will see how simple it is to use these classes.\n", - "\n", - "**scikit-learn** implements a few improvements from our neural network,\n", - "such as early stopping, a varying learning rate, different\n", - "optimization methods, etc. We would therefore expect a better\n", - "performance overall." - ] - }, - { - "cell_type": "code", - "execution_count": 107, - "metadata": { - "collapsed": false - }, - "outputs": [], - "source": [ - "from sklearn.neural_network import MLPClassifier\n", - "# store models for later use\n", - "DNN_scikit = np.zeros((len(eta_vals), len(lmbd_vals)), dtype=object)\n", - "\n", - "for i, eta in enumerate(eta_vals):\n", - " for j, lmbd in enumerate(lmbd_vals):\n", - " dnn = MLPClassifier(hidden_layer_sizes=(n_hidden_neurons), activation='logistic',\n", - " alpha=lmbd, learning_rate_init=eta, max_iter=epochs)\n", - " dnn.fit(X_train, Y_train)\n", - " \n", - " DNN_scikit[i][j] = dnn\n", - " \n", - " print(\"Learning rate = \", eta)\n", - " print(\"Lambda = \", lmbd)\n", - " print(\"Accuracy score on test set: \", dnn.score(X_test, Y_test))\n", - " print()" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "## Visualization" - ] - }, - { - "cell_type": "code", - "execution_count": 108, - "metadata": { - "collapsed": false - }, - "outputs": [], - "source": [ - "# optional\n", - "# visual representation of grid search\n", - "# uses seaborn heatmap, could probably do this in matplotlib\n", - "import seaborn as sns\n", - "\n", - "sns.set()\n", - "\n", - "train_accuracy = np.zeros((len(eta_vals), len(lmbd_vals)))\n", - "test_accuracy = np.zeros((len(eta_vals), len(lmbd_vals)))\n", - "\n", - "for i in range(len(eta_vals)):\n", - " for j in range(len(lmbd_vals)):\n", - " dnn = DNN_scikit[i][j]\n", - " \n", - " train_pred = dnn.predict(X_train) \n", - " test_pred = dnn.predict(X_test)\n", - "\n", - " train_accuracy[i][j] = accuracy_score(Y_train, train_pred)\n", - " test_accuracy[i][j] = accuracy_score(Y_test, test_pred)\n", - "\n", - " \n", - "fig, ax = plt.subplots(figsize = (10, 10))\n", - "sns.heatmap(train_accuracy, annot=True, ax=ax, cmap=\"viridis\")\n", - "ax.set_title(\"Training Accuracy\")\n", - "ax.set_ylabel(\"$\\eta$\")\n", - "ax.set_xlabel(\"$\\lambda$\")\n", - "plt.show()\n", - "\n", - "fig, ax = plt.subplots(figsize = (10, 10))\n", - "sns.heatmap(test_accuracy, annot=True, ax=ax, cmap=\"viridis\")\n", - "ax.set_title(\"Test Accuracy\")\n", - "ax.set_ylabel(\"$\\eta$\")\n", - "ax.set_xlabel(\"$\\lambda$\")\n", - "plt.show()" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "## Building neural networks in Tensorflow and Keras\n", - "\n", - "Now we want to build on the experience gained from our neural network implementation in NumPy and scikit-learn\n", - "and use it to construct a neural network in Tensorflow. Once we have constructed a neural network in NumPy\n", - "and Tensorflow, building one in Keras is really quite trivial, though the performance may suffer. \n", - "\n", - "In our previous example we used only one hidden layer, and in this we will use two. From this it should be quite\n", - "clear how to build one using an arbitrary number of hidden layers, using data structures such as Python lists or\n", - "NumPy arrays.\n", - "\n", - "\n", - "## Tensorflow\n", - "\n", - "Tensorflow is an open source library machine learning library\n", - "developed by the Google Brain team for internal use. It was released\n", - "under the Apache 2.0 open source license in November 9, 2015.\n", - "\n", - "Tensorflow is a computational framework that allows you to construct\n", - "machine learning models at different levels of abstraction, from\n", - "high-level, object-oriented APIs like Keras, down to the C++ kernels\n", - "that Tensorflow is built upon. The higher levels of abstraction are\n", - "simpler to use, but less flexible, and our choice of implementation\n", - "should reflect the problems we are trying to solve.\n", - "\n", - "[Tensorflow uses](https://www.tensorflow.org/guide/graphs) so-called graphs to represent your computation\n", - "in terms of the dependencies between individual operations, such that you first build a Tensorflow *graph*\n", - "to represent your model, and then create a Tensorflow *session* to run the graph.\n", - "\n", - "In this guide we will analyze the same data as we did in our NumPy and\n", - "scikit-learn tutorial, gathered from the MNIST database of images. We\n", - "will give an introduction to the lower level Python Application\n", - "Program Interfaces (APIs), and see how we use them to build our graph.\n", - "Then we will build (effectively) the same graph in Keras, to see just\n", - "how simple solving a machine learning problem can be.\n", - "\n", - "To install tensorflow on Unix/Linux systems, use pip as" - ] - }, - { - "cell_type": "code", - "execution_count": 109, - "metadata": { - "collapsed": false - }, - "outputs": [], - "source": [ - "pip3 install tensorflow" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "and/or if you use **anaconda**, just write (or install from the graphical user interface)" - ] - }, - { - "cell_type": "code", - "execution_count": 110, - "metadata": { - "collapsed": false - }, - "outputs": [], - "source": [ - "conda install tensorflow" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "## Collect and pre-process data" - ] - }, - { - "cell_type": "code", - "execution_count": 111, - "metadata": { - "collapsed": false - }, - "outputs": [], - "source": [ - "# import necessary packages\n", - "import numpy as np\n", - "import matplotlib.pyplot as plt\n", - "from sklearn import datasets\n", - "\n", - "\n", - "# ensure the same random numbers appear every time\n", - "np.random.seed(0)\n", - "\n", - "# display images in notebook\n", - "%matplotlib inline\n", - "plt.rcParams['figure.figsize'] = (12,12)\n", - "\n", - "\n", - "# download MNIST dataset\n", - "digits = datasets.load_digits()\n", - "\n", - "# define inputs and labels\n", - "inputs = digits.images\n", - "labels = digits.target\n", - "\n", - "print(\"inputs = (n_inputs, pixel_width, pixel_height) = \" + str(inputs.shape))\n", - "print(\"labels = (n_inputs) = \" + str(labels.shape))\n", - "\n", - "\n", - "# flatten the image\n", - "# the value -1 means dimension is inferred from the remaining dimensions: 8x8 = 64\n", - "n_inputs = len(inputs)\n", - "inputs = inputs.reshape(n_inputs, -1)\n", - "print(\"X = (n_inputs, n_features) = \" + str(inputs.shape))\n", - "\n", - "\n", - "# choose some random images to display\n", - "indices = np.arange(n_inputs)\n", - "random_indices = np.random.choice(indices, size=5)\n", - "\n", - "for i, image in enumerate(digits.images[random_indices]):\n", - " plt.subplot(1, 5, i+1)\n", - " plt.axis('off')\n", - " plt.imshow(image, cmap=plt.cm.gray_r, interpolation='nearest')\n", - " plt.title(\"Label: %d\" % digits.target[random_indices[i]])\n", - "plt.show()" - ] - }, - { - "cell_type": "code", - "execution_count": 112, - "metadata": { - "collapsed": false - }, - "outputs": [], - "source": [ - "from keras.utils import to_categorical\n", - "from sklearn.model_selection import train_test_split\n", - "\n", - "# one-hot representation of labels\n", - "labels = to_categorical(labels)\n", - "\n", - "# split into train and test data\n", - "train_size = 0.8\n", - "test_size = 1 - train_size\n", - "X_train, X_test, Y_train, Y_test = train_test_split(inputs, labels, train_size=train_size,\n", - " test_size=test_size)" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "## Using TensorFlow backend\n", - "\n", - "1. Define model and architecture\n", - "\n", - "2. Choose cost function and optimizer" - ] - }, - { - "cell_type": "code", - "execution_count": 113, - "metadata": { - "collapsed": false - }, - "outputs": [], - "source": [ - "import tensorflow as tf\n", - "\n", - "class NeuralNetworkTensorflow:\n", - " def __init__(\n", - " self,\n", - " X_train,\n", - " Y_train,\n", - " X_test,\n", - " Y_test,\n", - " n_neurons_layer1=100,\n", - " n_neurons_layer2=50,\n", - " n_categories=2,\n", - " epochs=10,\n", - " batch_size=100,\n", - " eta=0.1,\n", - " lmbd=0.0,\n", - " ):\n", - " \n", - " # keep track of number of steps\n", - " self.global_step = tf.Variable(0, dtype=tf.int32, trainable=False, name='global_step')\n", - " \n", - " self.X_train = X_train\n", - " self.Y_train = Y_train\n", - " self.X_test = X_test\n", - " self.Y_test = Y_test\n", - " \n", - " self.n_inputs = X_train.shape[0]\n", - " self.n_features = X_train.shape[1]\n", - " self.n_neurons_layer1 = n_neurons_layer1\n", - " self.n_neurons_layer2 = n_neurons_layer2\n", - " self.n_categories = n_categories\n", - " \n", - " self.epochs = epochs\n", - " self.batch_size = batch_size\n", - " self.iterations = self.n_inputs // self.batch_size\n", - " self.eta = eta\n", - " self.lmbd = lmbd\n", - " \n", - " # build network piece by piece\n", - " # name scopes (with) are used to enforce creation of new variables\n", - " # https://www.tensorflow.org/guide/variables\n", - " self.create_placeholders()\n", - " self.create_DNN()\n", - " self.create_loss()\n", - " self.create_optimiser()\n", - " self.create_accuracy()\n", - " \n", - " def create_placeholders(self):\n", - " # placeholders are fine here, but \"Datasets\" are the preferred method\n", - " # of streaming data into a model\n", - " with tf.name_scope('data'):\n", - " self.X = tf.placeholder(tf.float32, shape=(None, self.n_features), name='X_data')\n", - " self.Y = tf.placeholder(tf.float32, shape=(None, self.n_categories), name='Y_data')\n", - " \n", - " def create_DNN(self):\n", - " with tf.name_scope('DNN'):\n", - " # the weights are stored to calculate regularization loss later\n", - " \n", - " # Fully connected layer 1\n", - " self.W_fc1 = self.weight_variable([self.n_features, self.n_neurons_layer1], name='fc1', dtype=tf.float32)\n", - " b_fc1 = self.bias_variable([self.n_neurons_layer1], name='fc1', dtype=tf.float32)\n", - " a_fc1 = tf.nn.sigmoid(tf.matmul(self.X, self.W_fc1) + b_fc1)\n", - " \n", - " # Fully connected layer 2\n", - " self.W_fc2 = self.weight_variable([self.n_neurons_layer1, self.n_neurons_layer2], name='fc2', dtype=tf.float32)\n", - " b_fc2 = self.bias_variable([self.n_neurons_layer2], name='fc2', dtype=tf.float32)\n", - " a_fc2 = tf.nn.sigmoid(tf.matmul(a_fc1, self.W_fc2) + b_fc2)\n", - " \n", - " # Output layer\n", - " self.W_out = self.weight_variable([self.n_neurons_layer2, self.n_categories], name='out', dtype=tf.float32)\n", - " b_out = self.bias_variable([self.n_categories], name='out', dtype=tf.float32)\n", - " self.z_out = tf.matmul(a_fc2, self.W_out) + b_out\n", - " \n", - " def create_loss(self):\n", - " with tf.name_scope('loss'):\n", - " softmax_loss = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits_v2(labels=self.Y, logits=self.z_out))\n", - " \n", - " regularizer_loss_fc1 = tf.nn.l2_loss(self.W_fc1)\n", - " regularizer_loss_fc2 = tf.nn.l2_loss(self.W_fc2)\n", - " regularizer_loss_out = tf.nn.l2_loss(self.W_out)\n", - " regularizer_loss = self.lmbd*(regularizer_loss_fc1 + regularizer_loss_fc2 + regularizer_loss_out)\n", - " \n", - " self.loss = softmax_loss + regularizer_loss\n", - "\n", - " def create_accuracy(self):\n", - " with tf.name_scope('accuracy'):\n", - " probabilities = tf.nn.softmax(self.z_out)\n", - " predictions = tf.argmax(probabilities, axis=1)\n", - " labels = tf.argmax(self.Y, axis=1)\n", - " \n", - " correct_predictions = tf.equal(predictions, labels)\n", - " correct_predictions = tf.cast(correct_predictions, tf.float32)\n", - " self.accuracy = tf.reduce_mean(correct_predictions)\n", - " \n", - " def create_optimiser(self):\n", - " with tf.name_scope('optimizer'):\n", - " self.optimizer = tf.train.GradientDescentOptimizer(learning_rate=self.eta).minimize(self.loss, global_step=self.global_step)\n", - " \n", - " def weight_variable(self, shape, name='', dtype=tf.float32):\n", - " initial = tf.truncated_normal(shape, stddev=0.1)\n", - " return tf.Variable(initial, name=name, dtype=dtype)\n", - " \n", - " def bias_variable(self, shape, name='', dtype=tf.float32):\n", - " initial = tf.constant(0.1, shape=shape)\n", - " return tf.Variable(initial, name=name, dtype=dtype)\n", - " \n", - " def fit(self):\n", - " data_indices = np.arange(self.n_inputs)\n", - "\n", - " with tf.Session() as sess:\n", - " sess.run(tf.global_variables_initializer())\n", - " for i in range(self.epochs):\n", - " for j in range(self.iterations):\n", - " chosen_datapoints = np.random.choice(data_indices, size=self.batch_size, replace=False)\n", - " batch_X, batch_Y = self.X_train[chosen_datapoints], self.Y_train[chosen_datapoints]\n", - " \n", - " sess.run([DNN.loss, DNN.optimizer],\n", - " feed_dict={DNN.X: batch_X,\n", - " DNN.Y: batch_Y})\n", - " accuracy = sess.run(DNN.accuracy,\n", - " feed_dict={DNN.X: batch_X,\n", - " DNN.Y: batch_Y})\n", - " step = sess.run(DNN.global_step)\n", - " \n", - " self.train_loss, self.train_accuracy = sess.run([DNN.loss, DNN.accuracy],\n", - " feed_dict={DNN.X: self.X_train,\n", - " DNN.Y: self.Y_train})\n", - " \n", - " self.test_loss, self.test_accuracy = sess.run([DNN.loss, DNN.accuracy],\n", - " feed_dict={DNN.X: self.X_test,\n", - " DNN.Y: self.Y_test})" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "## Optimizing and using gradient descent" - ] - }, - { - "cell_type": "code", - "execution_count": 114, - "metadata": { - "collapsed": false - }, - "outputs": [], - "source": [ - "epochs = 100\n", - "batch_size = 100\n", - "n_neurons_layer1 = 100\n", - "n_neurons_layer2 = 50\n", - "n_categories = 10\n", - "eta_vals = np.logspace(-5, 1, 7)\n", - "lmbd_vals = np.logspace(-5, 1, 7)" - ] - }, - { - "cell_type": "code", - "execution_count": 115, - "metadata": { - "collapsed": false - }, - "outputs": [], - "source": [ - "DNN_tf = np.zeros((len(eta_vals), len(lmbd_vals)), dtype=object)\n", - " \n", - "for i, eta in enumerate(eta_vals):\n", - " for j, lmbd in enumerate(lmbd_vals):\n", - " DNN = NeuralNetworkTensorflow(X_train, Y_train, X_test, Y_test,\n", - " n_neurons_layer1, n_neurons_layer2, n_categories,\n", - " epochs=epochs, batch_size=batch_size, eta=eta, lmbd=lmbd)\n", - " DNN.fit()\n", - " \n", - " DNN_tf[i][j] = DNN\n", - " \n", - " print(\"Learning rate = \", eta)\n", - " print(\"Lambda = \", lmbd)\n", - " print(\"Test accuracy: %.3f\" % DNN.test_accuracy)\n", - " print()" - ] - }, - { - "cell_type": "code", - "execution_count": 116, - "metadata": { - "collapsed": false - }, - "outputs": [], - "source": [ - "# optional\n", - "# visual representation of grid search\n", - "# uses seaborn heatmap, could probably do this in matplotlib\n", - "import seaborn as sns\n", - "\n", - "sns.set()\n", - "\n", - "train_accuracy = np.zeros((len(eta_vals), len(lmbd_vals)))\n", - "test_accuracy = np.zeros((len(eta_vals), len(lmbd_vals)))\n", - "\n", - "for i in range(len(eta_vals)):\n", - " for j in range(len(lmbd_vals)):\n", - " DNN = DNN_tf[i][j]\n", - "\n", - " train_accuracy[i][j] = DNN.train_accuracy\n", - " test_accuracy[i][j] = DNN.test_accuracy\n", - "\n", - " \n", - "fig, ax = plt.subplots(figsize = (10, 10))\n", - "sns.heatmap(train_accuracy, annot=True, ax=ax, cmap=\"viridis\")\n", - "ax.set_title(\"Training Accuracy\")\n", - "ax.set_ylabel(\"$\\eta$\")\n", - "ax.set_xlabel(\"$\\lambda$\")\n", - "plt.show()\n", - "\n", - "fig, ax = plt.subplots(figsize = (10, 10))\n", - "sns.heatmap(test_accuracy, annot=True, ax=ax, cmap=\"viridis\")\n", - "ax.set_title(\"Test Accuracy\")\n", - "ax.set_ylabel(\"$\\eta$\")\n", - "ax.set_xlabel(\"$\\lambda$\")\n", - "plt.show()" - ] - }, - { - "cell_type": "code", - "execution_count": 117, - "metadata": { - "collapsed": false - }, - "outputs": [], - "source": [ - "# optional\n", - "# we can use log files to visualize our graph in Tensorboard\n", - "writer = tf.summary.FileWriter('logs/')\n", - "writer.add_graph(tf.get_default_graph())" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "## Using Keras\n", - "\n", - "Keras is a high level [neural network](https://en.wikipedia.org/wiki/Application_programming_interface)\n", - "that supports Tensorflow, CTNK and Theano as backends. \n", - "If you have Tensorflow installed Keras is available through the *tf.keras* module. \n", - "If you have Anaconda installed you may run the following command" - ] - }, - { - "cell_type": "code", - "execution_count": 118, - "metadata": { - "collapsed": false - }, - "outputs": [], - "source": [ - "conda install keras" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "Alternatively, if you have Tensorflow or one of the other supported backends install you may use the pip package manager:" - ] - }, - { - "cell_type": "code", - "execution_count": 119, - "metadata": { - "collapsed": false - }, - "outputs": [], - "source": [ - "pip3 install keras" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "or look up the [instructions here](https://keras.io/)." - ] - }, - { - "cell_type": "code", - "execution_count": 120, - "metadata": { - "collapsed": false - }, - "outputs": [], - "source": [ - "from keras.models import Sequential\n", - "from keras.layers import Dense\n", - "from keras.regularizers import l2\n", - "from keras.optimizers import SGD\n", - "\n", - "def create_neural_network_keras(n_neurons_layer1, n_neurons_layer2, n_categories, eta, lmbd):\n", - " model = Sequential()\n", - " model.add(Dense(n_neurons_layer1, activation='sigmoid', kernel_regularizer=l2(lmbd)))\n", - " model.add(Dense(n_neurons_layer2, activation='sigmoid', kernel_regularizer=l2(lmbd)))\n", - " model.add(Dense(n_categories, activation='softmax'))\n", - " \n", - " sgd = SGD(lr=eta)\n", - " model.compile(loss='categorical_crossentropy', optimizer=sgd, metrics=['accuracy'])\n", - " \n", - " return model" - ] - }, - { - "cell_type": "code", - "execution_count": 121, - "metadata": { - "collapsed": false - }, - "outputs": [], - "source": [ - "DNN_keras = np.zeros((len(eta_vals), len(lmbd_vals)), dtype=object)\n", - " \n", - "for i, eta in enumerate(eta_vals):\n", - " for j, lmbd in enumerate(lmbd_vals):\n", - " DNN = create_neural_network_keras(n_neurons_layer1, n_neurons_layer2, n_categories,\n", - " eta=eta, lmbd=lmbd)\n", - " DNN.fit(X_train, Y_train, epochs=epochs, batch_size=batch_size, verbose=0)\n", - " scores = DNN.evaluate(X_test, Y_test)\n", - " \n", - " DNN_keras[i][j] = DNN\n", - " \n", - " print(\"Learning rate = \", eta)\n", - " print(\"Lambda = \", lmbd)\n", - " print(\"Test accuracy: %.3f\" % scores[1])\n", - " print()" - ] - }, - { - "cell_type": "code", - "execution_count": 122, - "metadata": { - "collapsed": false - }, - "outputs": [], - "source": [ - "# optional\n", - "# visual representation of grid search\n", - "# uses seaborn heatmap, could probably do this in matplotlib\n", - "import seaborn as sns\n", - "\n", - "sns.set()\n", - "\n", - "train_accuracy = np.zeros((len(eta_vals), len(lmbd_vals)))\n", - "test_accuracy = np.zeros((len(eta_vals), len(lmbd_vals)))\n", - "\n", - "for i in range(len(eta_vals)):\n", - " for j in range(len(lmbd_vals)):\n", - " DNN = DNN_keras[i][j]\n", - "\n", - " train_accuracy[i][j] = DNN.evaluate(X_train, Y_train)[1]\n", - " test_accuracy[i][j] = DNN.evaluate(X_test, Y_test)[1]\n", - "\n", - " \n", - "fig, ax = plt.subplots(figsize = (10, 10))\n", - "sns.heatmap(train_accuracy, annot=True, ax=ax, cmap=\"viridis\")\n", - "ax.set_title(\"Training Accuracy\")\n", - "ax.set_ylabel(\"$\\eta$\")\n", - "ax.set_xlabel(\"$\\lambda$\")\n", - "plt.show()\n", - "\n", - "fig, ax = plt.subplots(figsize = (10, 10))\n", - "sns.heatmap(test_accuracy, annot=True, ax=ax, cmap=\"viridis\")\n", - "ax.set_title(\"Test Accuracy\")\n", - "ax.set_ylabel(\"$\\eta$\")\n", - "ax.set_xlabel(\"$\\lambda$\")\n", - "plt.show()" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "## Which activation function should I use?\n", - "\n", - "The Back propagation algorithm we derived above works by going from\n", - "the output layer to the input layer, propagating the error gradient on\n", - "the way. Once the algorithm has computed the gradient of the cost\n", - "function with regards to each parameter in the network, it uses these\n", - "gradients to update each parameter with a Gradient Descent (GD) step.\n", - "\n", - "\n", - "Unfortunately for us, the gradients often get smaller and smaller as the\n", - "algorithm progresses down to the first hidden layers. As a result, the\n", - "GD update leaves the lower layer connection weights\n", - "virtually unchanged, and training never converges to a good\n", - "solution. This is known in the literature as \n", - "**the vanishing gradients problem**. \n", - "\n", - "In other cases, the opposite can happen, namely the the gradients can grow bigger and\n", - "bigger. The result is that many of the layers get large updates of the \n", - "weights the\n", - "algorithm diverges. This is the **exploding gradients problem**, which is\n", - "mostly encountered in recurrent neural networks. More generally, deep\n", - "neural networks suffer from unstable gradients, different layers may\n", - "learn at widely different speeds\n", - "\n", - "\n", - "## Is the Logistic activation function (Sigmoid) our choice?\n", - "\n", - "Although this unfortunate behavior has been empirically observed for\n", - "quite a while (it was one of the reasons why deep neural networks were\n", - "mostly abandoned for a long time), it is only around 2010 that\n", - "significant progress was made in understanding it.\n", - "\n", - "A paper titled [Understanding the Difficulty of Training Deep\n", - "Feedforward Neural Networks by Xavier Glorot and Yoshua Bengio](http://proceedings.mlr.press/v9/glorot10a.html) found that\n", - "the problems with the popular logistic\n", - "sigmoid activation function and the weight initialization technique\n", - "that was most popular at the time, namely random initialization using\n", - "a normal distribution with a mean of 0 and a standard deviation of\n", - "1. \n", - "\n", - "They showed that with this activation function and this\n", - "initialization scheme, the variance of the outputs of each layer is\n", - "much greater than the variance of its inputs. Going forward in the\n", - "network, the variance keeps increasing after each layer until the\n", - "activation function saturates at the top layers. This is actually made\n", - "worse by the fact that the logistic function has a mean of 0.5, not 0\n", - "(the hyperbolic tangent function has a mean of 0 and behaves slightly\n", - "better than the logistic function in deep networks).\n", - "\n", - "\n", - "\n", - "## The derivative of the Logistic funtion\n", - "\n", - "Looking at the logistic activation function, when inputs become large\n", - "(negative or positive), the function saturates at 0 or 1, with a\n", - "derivative extremely close to 0. Thus when backpropagation kicks in,\n", - "it has virtually no gradient to propagate back through the network,\n", - "and what little gradient exists keeps getting diluted as\n", - "backpropagation progresses down through the top layers, so there is\n", - "really nothing left for the lower layers.\n", - "\n", - "In their paper, Glorot and Bengio propose a way to significantly\n", - "alleviate this problem. We need the signal to flow properly in both\n", - "directions: in the forward direction when making predictions, and in\n", - "the reverse direction when backpropagating gradients. We don’t want\n", - "the signal to die out, nor do we want it to explode and saturate. For\n", - "the signal to flow properly, the authors argue that we need the\n", - "variance of the outputs of each layer to be equal to the variance of\n", - "its inputs, and we also need the gradients to have equal variance\n", - "before and after flowing through a layer in the reverse direction.\n", - "\n", - "\n", - "\n", - "One of the insights in the 2010 paper by Glorot and Bengio was that\n", - "the vanishing/exploding gradients problems were in part due to a poor\n", - "choice of activation function. Until then most people had assumed that\n", - "if Nature had chosen to use roughly sigmoid activation functions in\n", - "biological neurons, they must be an excellent choice. But it turns out\n", - "that other activation functions behave much better in deep neural\n", - "networks, in particular the ReLU activation function, mostly because\n", - "it does not saturate for positive values (and also because it is quite\n", - "fast to compute).\n", - "\n", - "\n", - "\n", - "## The RELU function family\n", - "\n", - "The ReLU activation function suffers from a problem known as the dying\n", - "ReLUs: during training, some neurons effectively die, meaning they\n", - "stop outputting anything other than 0.\n", - "\n", - "In some cases, you may find that half of your network’s neurons are\n", - "dead, especially if you used a large learning rate. During training,\n", - "if a neuron’s weights get updated such that the weighted sum of the\n", - "neuron’s inputs is negative, it will start outputting 0. When this\n", - "happen, the neuron is unlikely to come back to life since the gradient\n", - "of the ReLU function is 0 when its input is negative.\n", - "\n", - "To solve this problem, nowadays practitioners use a variant of the ReLU\n", - "function, such as the leaky ReLU discussed above or the so-called\n", - "exponential linear unit (ELU) function" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "ELU(z) = \\left\\{\\begin{array}{cc} \\alpha\\left( \\exp{(z)}-1\\right) & z < 0,\\\\ z & z \\ge 0.\\end{array}\\right.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "## Which activation function should we use?\n", - "\n", - "In general it seems that the ELU activation function is better than\n", - "the leaky ReLU function (and its variants), which is better than\n", - "ReLU. ReLU performs better than $\\tanh$ which in turn performs better\n", - "than the logistic function. \n", - "\n", - "If runtime\n", - "performance is an issue, then you may opt for the leaky ReLU function over the \n", - "ELU function If you don’t\n", - "want to tweak yet another hyperparameter, you may just use the default\n", - "$\\alpha$ of $0.01$ for the leaky ReLU, and $1$ for ELU. If you have\n", - "spare time and computing power, you can use cross-validation or\n", - "bootstrap to evaluate other activation functions.\n", - "\n", - "\n", - "\n", - "## A top-down perspective on Neural networks\n", - "\n", - "\n", - "The first thing we would like to do is divide the data into two or three\n", - "parts. A training set, a validation or dev (development) set, and a\n", - "test set. The test set is the data on which we want to make\n", - "predictions. The dev set is a subset of the training data we use to\n", - "check how well we are doing out-of-sample, after training the model on\n", - "the training dataset. We use the validation error as a proxy for the\n", - "test error in order to make tweaks to our model. It is crucial that we\n", - "do not use any of the test data to train the algorithm. This is a\n", - "cardinal sin in ML. Then:\n", - "\n", - "\n", - "* Estimate optimal error rate\n", - "\n", - "* Minimize underfitting (bias) on training data set.\n", - "\n", - "* Make sure you are not overfitting.\n", - "\n", - "If the validation and test sets are drawn from the same distributions,\n", - "then a good performance on the validation set should lead to similarly\n", - "good performance on the test set. \n", - "\n", - "However, sometimes\n", - "the training data and test data differ in subtle ways because, for\n", - "example, they are collected using slightly different methods, or\n", - "because it is cheaper to collect data in one way versus another. In\n", - "this case, there can be a mismatch between the training and test\n", - "data. This can lead to the neural network overfitting these small\n", - "differences between the test and training sets, and a poor performance\n", - "on the test set despite having a good performance on the validation\n", - "set. To rectify this, Andrew Ng suggests making two validation or dev\n", - "sets, one constructed from the training data and one constructed from\n", - "the test data. The difference between the performance of the algorithm\n", - "on these two validation sets quantifies the train-test mismatch. This\n", - "can serve as another important diagnostic when using DNNs for\n", - "supervised learning.\n", - "\n", - "\n", - "## Limitations of supervised learning with deep networks\n", - "\n", - "Like all statistical methods, supervised learning using neural\n", - "networks has important limitations. This is especially important when\n", - "one seeks to apply these methods, especially to physics problems. Like\n", - "all tools, DNNs are not a universal solution. Often, the same or\n", - "better performance on a task can be achieved by using a few\n", - "hand-engineered features (or even a collection of random\n", - "features). \n", - "\n", - "Here we list some of the important limitations of supervised neural network based models. \n", - "\n", - "\n", - "\n", - "* **Need labeled data**. All supervised learning methods, DNNs for supervised learning require labeled data. Often, labeled data is harder to acquire than unlabeled data (e.g. one must pay for human experts to label images).\n", - "\n", - "* **Supervised neural networks are extremely data intensive.** DNNs are data hungry. They perform best when data is plentiful. This is doubly so for supervised methods where the data must also be labeled. The utility of DNNs is extremely limited if data is hard to acquire or the datasets are small (hundreds to a few thousand samples). In this case, the performance of other methods that utilize hand-engineered features can exceed that of DNNs.\n", - "\n", - "* **Homogeneous data.** Almost all DNNs deal with homogeneous data of one type. It is very hard to design architectures that mix and match data types (i.e. some continuous variables, some discrete variables, some time series). In applications beyond images, video, and language, this is often what is required. In contrast, ensemble models like random forests or gradient-boosted trees have no difficulty handling mixed data types.\n", - "\n", - "* **Many problems are not about prediction.** In natural science we are often interested in learning something about the underlying distribution that generates the data. In this case, it is often difficult to cast these ideas in a supervised learning setting. While the problems are related, it is possible to make good predictions with a *wrong* model. The model might or might not be useful for understanding the underlying science.\n", - "\n", - "Some of these remarks are particular to DNNs, others are shared by all supervised learning methods. This motivates the use of unsupervised methods which in part circumnavigate these problems.\n", - "\n", - "\n", - "# Nearest Neighbors and Decision Trees\n", - "\n", - "## Decision trees, overarching aims\n", - "\n", - "Add text about decision trees and include about random forests (use Ising model classification)\n", - "\n", - "\n", - "\n", - "## Nearest Neighbors" - ] - }, - { - "cell_type": "code", - "execution_count": 123, - "metadata": { - "collapsed": false - }, - "outputs": [], - "source": [ - "import mglearn\n", - "import numpy as np\n", - "from sklearn import linear_model\n", - "from sklearn.linear_model import LinearRegression\n", - "import matplotlib.pyplot as plt\n", - "from sklearn.preprocessing import PolynomialFeatures\n", - "from sklearn.pipeline import Pipeline\n", - "from sklearn.neighbors import KNeighborsClassifier\n", - "\n", - "# Generate sample data\n", - "X = np.sort(5*np.random.rand(40,1), axis=0)\n", - "y = X**3\n", - "y=y.ravel()\n", - "\n", - "# Add noise to targets\n", - "X[::4] +=(0.5 - np.random.rand(1))\n", - "y[::5] +=(0.5 - np.random.rand(8))\n", - "\n", - "a=np.array(X)\n", - "b=np.array(y)\n", - "\n", - "X_train=a[:19]\n", - "X_test=a[19:]\n", - "y_train=b[:19]\n", - "y_test=b[19:]\n", - "\n", - "model=Pipeline([('poly', PolynomialFeatures(degree=3)),('linear', LinearRegression(fit_intercept=False))])\n", - "model=model.fit(X_train, y_train)\n", - "pred=model.predict(X_test)\n", - "\n", - "\n", - "poly=PolynomialFeatures(degree=3)\n", - "poly.fit_transform(X_train, y_train)\n", - "plt.scatter(X_test, y_test)\n", - "plt.plot(X_test, pred, color='green')\n", - "plt.show()\n", - "\n", - "print (model.score(X_test,y_test))\n", - "\n", - "print (\"---------K-Nearest Neighbors-------\")\n", - "\"\"\"neighbors_settings=range(1,11)\n", - "for n_neighbors in neighbors_settings:\n", - " clf=KNeighborsClassifier(n_neighbors=n_neighbors)\n", - " clf.fit(X_train, y_train)\n", - " training_accuracy.append(clf.score(X_train, y_train))\n", - " test_accuracy.append(clf.score(X_test, y_test))\n", - "\n", - "\n", - "print (mglearn.plots.plot_knn_regression(n_neighbors=3))\"\"\"\n", - "\n", - "from sklearn.neighbors import KNeighborsRegressor\n", - "\n", - "X, y=mglearn.datasets.make_wave(n_samples=40)\n", - "reg = KNeighborsRegressor(n_neighbors=3)\n", - "reg.fit(X_train, y_train)" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "## Decision trees and Regression" - ] - }, - { - "cell_type": "code", - "execution_count": 124, - "metadata": { - "collapsed": false - }, - "outputs": [], - "source": [ - "import numpy as np\n", - "import matplotlib.pyplot as plt\n", - "from sklearn.preprocessing import PolynomialFeatures\n", - "from sklearn.linear_model import LinearRegression\n", - "\n", - "steps=250\n", - "\n", - "distance=0\n", - "x=0\n", - "distance_list=[]\n", - "steps_list=[]\n", - "while x