diff --git a/doc/LectureNotes/_build/.doctrees/chapter1.doctree b/doc/LectureNotes/_build/.doctrees/chapter1.doctree index 56d7d996c..5a49a4a82 100644 Binary files a/doc/LectureNotes/_build/.doctrees/chapter1.doctree and b/doc/LectureNotes/_build/.doctrees/chapter1.doctree differ diff --git a/doc/LectureNotes/_build/.doctrees/environment.pickle b/doc/LectureNotes/_build/.doctrees/environment.pickle index ff0a9aa96..d7e6f3bc0 100644 Binary files a/doc/LectureNotes/_build/.doctrees/environment.pickle and b/doc/LectureNotes/_build/.doctrees/environment.pickle differ diff --git a/doc/LectureNotes/_build/html/_images/chapter1_11_0.png b/doc/LectureNotes/_build/html/_images/chapter1_11_0.png new file mode 100644 index 000000000..9d454e64f Binary files /dev/null and b/doc/LectureNotes/_build/html/_images/chapter1_11_0.png differ diff --git a/doc/LectureNotes/_build/html/_images/chapter1_13_1.png b/doc/LectureNotes/_build/html/_images/chapter1_13_1.png new file mode 100644 index 000000000..d0c5b8666 Binary files /dev/null and b/doc/LectureNotes/_build/html/_images/chapter1_13_1.png differ diff --git a/doc/LectureNotes/_build/html/_images/chapter1_27_0.png b/doc/LectureNotes/_build/html/_images/chapter1_27_0.png new file mode 100644 index 000000000..7ff2f668b Binary files /dev/null and b/doc/LectureNotes/_build/html/_images/chapter1_27_0.png differ diff --git a/doc/LectureNotes/_build/html/_images/chapter1_3_0.png b/doc/LectureNotes/_build/html/_images/chapter1_3_0.png new file mode 100644 index 000000000..29f3f1818 Binary files /dev/null and b/doc/LectureNotes/_build/html/_images/chapter1_3_0.png differ diff --git a/doc/LectureNotes/_build/html/_sources/chapter1.ipynb b/doc/LectureNotes/_build/html/_sources/chapter1.ipynb index 7e2ad50e8..4ec42071b 100644 --- a/doc/LectureNotes/_build/html/_sources/chapter1.ipynb +++ b/doc/LectureNotes/_build/html/_sources/chapter1.ipynb @@ -4,7 +4,7 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "# Linear Regression, basic Elements\n", + "# Linear Regression\n", "\n", "[Video of Lecture](https://www.uio.no/studier/emner/matnat/fys/FYS-STK3155/h20/forelesningsvideoer/LectureAug21.mp4?vrtx=view-as-webpage)\n", "\n", @@ -15,7 +15,7 @@ "\n", "\n", "\n", - "Our emphasis throughout this series of lectures \n", + "Our emphasis throughout this series of lectures (small change) \n", "is on understanding the mathematical aspects of\n", "different algorithms used in the fields of data analysis and machine learning. \n", "\n", @@ -137,951 +137,98 @@ " * Clustering: Data are divided into groups with certain common traits, without knowing the different groups beforehand. It is thus a form of unsupervised learning.\n", "\n", "The methods we cover have three main topics in common, irrespective of\n", - "whether we deal with supervised or unsupervised learning. The first\n", - "ingredient is normally our data set (which can be subdivided into\n", - "training and test data), the second item is a model which is normally a\n", - "function of some parameters. The model reflects our knowledge of the system (or lack thereof). As an example, if we know that our data show a behavior similar to what would be predicted by a polynomial, fitting our data to a polynomial of some degree would then determin our model. \n", + "whether we deal with supervised or unsupervised learning.\n", + "* The first ingredient is normally our data set (which can be subdivided into training, validation and test data). Many find the most difficult part of using Machine Learning to be the set up of your data in a meaningful way. \n", "\n", - "The last ingredient is a so-called **cost**\n", - "function which allows us to present an estimate on how good our model\n", - "is in reproducing the data it is supposed to train. \n", - "At the heart of basically all ML algorithms there are so-called minimization algorithms, often we end up with various variants of **gradient** methods.\n", + "* The second item is a model which is normally a function of some parameters. The model reflects our knowledge of the system (or lack thereof). As an example, if we know that our data show a behavior similar to what would be predicted by a polynomial, fitting our data to a polynomial of some degree would then determin our model. \n", "\n", + "* The last ingredient is a so-called **cost/loss** function (or error or risk function) which allows us to present an estimate on how good our model is in reproducing the data it is supposed to train. \n", "\n", "\n", "\n", + "At the heart of basically all Machine Learning algorithms we will encounter so-called minimization or optimization algorithms. A large family of such methods are so-called **gradient methods**.\n", "\n", "\n", + "### A Frequentist approach to data analysis\n", "\n", - "## Software and needed installations\n", + "When you hear phrases like **predictions and estimations** and\n", + "**correlations and causations**, what do you think of? May be you think\n", + "of the difference between classifying new data points and generating\n", + "new data points.\n", + "Or perhaps you consider that correlations represent some kind of symmetric statements like\n", + "if $A$ is correlated with $B$, then $B$ is correlated with\n", + "$A$. Causation on the other hand is directional, that is if $A$ causes $B$, $B$ does not\n", + "necessarily cause $A$.\n", "\n", - "We will make extensive use of Python as programming language and its\n", - "myriad of available libraries. You will find\n", - "Jupyter notebooks invaluable in your work. You can run **R**\n", - "codes in the Jupyter/IPython notebooks, with the immediate benefit of\n", - "visualizing your data. You can also use compiled languages like C++,\n", - "Rust, Julia, Fortran etc if you prefer. The focus in these lectures will be\n", - "on Python.\n", + "These concepts are in some sense the difference between machine\n", + "learning and statistics. In machine learning and prediction based\n", + "tasks, we are often interested in developing algorithms that are\n", + "capable of learning patterns from given data in an automated fashion,\n", + "and then using these learned patterns to make predictions or\n", + "assessments of newly given data. In many cases, our primary concern\n", + "is the quality of the predictions or assessments, and we are less\n", + "concerned about the underlying patterns that were learned in order\n", + "to make these predictions.\n", "\n", + "In machine learning we normally use [a so-called frequentist approach](https://en.wikipedia.org/wiki/Frequentist_inference),\n", + "where the aim is to make predictions and find correlations. We focus\n", + "less on for example extracting a probability distribution function (PDF). The PDF can be\n", + "used in turn to make estimations and find causations such as given $A$\n", + "what is the likelihood of finding $B$.\n", "\n", - "If you have Python installed (we strongly recommend Python3) and you feel\n", - "pretty familiar with installing different packages, we recommend that\n", - "you install the following Python packages via **pip** as \n", "\n", - "1. pip install numpy scipy matplotlib ipython scikit-learn mglearn sympy pandas pillow \n", + "### What is a good model?\n", "\n", - "For Python3, replace **pip** with **pip3**.\n", + "In science and engineering we often end up in situations where we want to infer (or learn) a\n", + "quantitative model $M$ for a given set of sample points $\\boldsymbol{X} \\in [x_1, x_2,\\dots x_N]$.\n", "\n", - "For OSX users we recommend, after having installed Xcode, to\n", - "install **brew**. Brew allows for a seamless installation of additional\n", - "software via for example \n", + "As we will see repeatedely in these lectures, we could try to fit these data points to a model given by a\n", + "straight line, or if we wish to be more sophisticated to a more complex\n", + "function.\n", "\n", - "1. brew install python3\n", + "The reason for inferring such a model is that it\n", + "serves many useful purposes. On the one hand, the model can reveal information\n", + "encoded in the data or underlying mechanisms from which the data were generated. For instance, we could discover important\n", + "corelations that relate interesting physics interpretations.\n", "\n", - "For Linux users, with its variety of distributions like for example the widely popular Ubuntu distribution,\n", - "you can use **pip** as well and simply install Python as \n", + "In addition, it can simplify the representation of the given data set and help\n", + "us in making predictions about future data samples.\n", "\n", - "1. sudo apt-get install python3 (or python for pyhton2.7)\n", + "A first important consideration to keep in mind is that inferring the *correct* model\n", + "for a given data set is an elusive, if not impossible, task. The fundamental difficulty\n", + "is that if we are not specific about what we mean by a *correct* model, there\n", + "could easily be many different models that fit the given data set *equally well*.\n", "\n", - "etc etc. \n", "\n", "\n", "\n", - "## Python installers\n", + "The central question is this: what leads us to say that a model is correct or\n", + "optimal for a given data set? To make the model inference problem well posed, i.e.,\n", + "to guarantee that there is a unique optimal model for the given data, we need to\n", + "impose additional assumptions or restrictions on the class of models considered. To\n", + "this end, we should not be looking for just any model that can describe the data.\n", + "Instead, we should look for a **model** $M$ that is the best among a restricted class\n", + "of models. In addition, to make the model inference problem computationally\n", + "tractable, we need to specify how restricted the class of models needs to be. A\n", + "common strategy is to start \n", + "with the simplest possible class of models that is just necessary to describe the data\n", + "or solve the problem at hand. More precisely, the model class should be rich enough\n", + "to contain at least one model that can fit the data to a desired accuracy and yet be\n", + "restricted enough that it is relatively simple to find the best model for the given data.\n", "\n", - "If you don't want to perform these operations separately and venture\n", - "into the hassle of exploring how to set up dependencies and paths, we\n", - "recommend two widely used distrubutions which set up all relevant\n", - "dependencies for Python, namely \n", + "Thus, the most popular strategy is to start from the\n", + "simplest class of models and increase the complexity of the models only when the\n", + "simpler models become inadequate. For instance, if we work with a regression problem to fit a set of sample points, one\n", + "may first try the simplest class of models, namely linear models, followed obviously by more complex models.\n", "\n", - "* [Anaconda](https://docs.anaconda.com/), \n", + "How to evaluate which model fits best the data is something we will come back to over and over again in these sets of lectures.\n", "\n", - "which is an open source\n", - "distribution of the Python and R programming languages for large-scale\n", - "data processing, predictive analytics, and scientific computing, that\n", - "aims to simplify package management and deployment. Package versions\n", - "are managed by the package management system **conda**. \n", "\n", - "* [Enthought canopy](https://www.enthought.com/product/canopy/) \n", "\n", - "is a Python\n", - "distribution for scientific and analytic computing distribution and\n", - "analysis environment, available for free and under a commercial\n", - "license.\n", "\n", - "Furthermore, [Google's Colab](https://colab.research.google.com/notebooks/welcome.ipynb) is a free Jupyter notebook environment that requires \n", - "no setup and runs entirely in the cloud. Try it out!\n", "\n", "\n", - "## Useful Python libraries\n", - "Here we list several useful Python libraries we strongly recommend (if you use anaconda many of these are already there)\n", "\n", - "* [NumPy](https://www.numpy.org/) is a highly popular library for large, multi-dimensional arrays and matrices, along with a large collection of high-level mathematical functions to operate on these arrays\n", - "\n", - "* [The pandas](https://pandas.pydata.org/) library provides high-performance, easy-to-use data structures and data analysis tools \n", - "\n", - "* [Xarray](http://xarray.pydata.org/en/stable/) is a Python package that makes working with labelled multi-dimensional arrays simple, efficient, and fun!\n", - "\n", - "* [Scipy](https://www.scipy.org/) (pronounced “Sigh Pie”) is a Python-based ecosystem of open-source software for mathematics, science, and engineering. \n", - "\n", - "* [Matplotlib](https://matplotlib.org/) is a Python 2D plotting library which produces publication quality figures in a variety of hardcopy formats and interactive environments across platforms.\n", - "\n", - "* [Autograd](https://github.com/HIPS/autograd) can automatically differentiate native Python and Numpy code. It can handle a large subset of Python's features, including loops, ifs, recursion and closures, and it can even take derivatives of derivatives of derivatives\n", - "\n", - "* [SymPy](https://www.sympy.org/en/index.html) is a Python library for symbolic mathematics. \n", - "\n", - "* [scikit-learn](https://scikit-learn.org/stable/) has simple and efficient tools for machine learning, data mining and data analysis\n", - "\n", - "* [TensorFlow](https://www.tensorflow.org/) is a Python library for fast numerical computing created and released by Google\n", - "\n", - "* [Keras](https://keras.io/) is a high-level neural networks API, written in Python and capable of running on top of TensorFlow, CNTK, or Theano\n", - "\n", - "* And many more such as [pytorch](https://pytorch.org/), [Theano](https://pypi.org/project/Theano/) etc \n", - "\n", - "## Installing R, C++, cython or Julia\n", - "\n", - "You will also find it convenient to utilize **R**. We will mainly\n", - "use Python during our lectures and in various projects and exercises.\n", - "Those of you\n", - "already familiar with **R** should feel free to continue using **R**, keeping\n", - "however an eye on the parallel Python set ups. Similarly, if you are a\n", - "Python afecionado, feel free to explore **R** as well. Jupyter/Ipython\n", - "notebook allows you to run **R** codes interactively in your\n", - "browser. The software library **R** is really tailored for statistical data analysis\n", - "and allows for an easy usage of the tools and algorithms we will discuss in these\n", - "lectures.\n", - "\n", - "To install **R** with Jupyter notebook \n", - "[follow the link here](https://mpacer.org/maths/r-kernel-for-ipython-notebook)\n", - "\n", - "\n", - "\n", - "\n", - "## Installing R, C++, cython, Numba etc\n", - "\n", - "\n", - "For the C++ aficionados, Jupyter/IPython notebook allows you also to\n", - "install C++ and run codes written in this language interactively in\n", - "the browser. Since we will emphasize writing many of the algorithms\n", - "yourself, you can thus opt for either Python or C++ (or Fortran or other compiled languages) as programming\n", - "languages.\n", - "\n", - "To add more entropy, **cython** can also be used when running your\n", - "notebooks. It means that Python with the jupyter notebook\n", - "setup allows you to integrate widely popular softwares and tools for\n", - "scientific computing. Similarly, the \n", - "[Numba Python package](https://numba.pydata.org/) delivers increased performance\n", - "capabilities with minimal rewrites of your codes. With its\n", - "versatility, including symbolic operations, Python offers a unique\n", - "computational environment. Your jupyter notebook can easily be\n", - "converted into a nicely rendered **PDF** file or a Latex file for\n", - "further processing. For example, convert to latex as" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - " pycod jupyter nbconvert filename.ipynb --to latex \n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "And to add more versatility, the Python package [SymPy](http://www.sympy.org/en/index.html) is a Python library for symbolic mathematics. It aims to become a full-featured computer algebra system (CAS) and is entirely written in Python. \n", - "\n", - "Finally, if you wish to use the light mark-up language \n", - "[doconce](https://github.com/hplgit/doconce) you can convert a standard ascii text file into various HTML \n", - "formats, ipython notebooks, latex files, pdf files etc with minimal edits. These lectures were generated using **doconce**.\n", - "\n", - "\n", - "\n", - "## Numpy examples and Important Matrix and vector handling packages\n", - "\n", - "There are several central software libraries for linear algebra and eigenvalue problems. Several of the more\n", - "popular ones have been wrapped into ofter software packages like those from the widely used text **Numerical Recipes**. The original source codes in many of the available packages are often taken from the widely used\n", - "software package LAPACK, which follows two other popular packages\n", - "developed in the 1970s, namely EISPACK and LINPACK. We describe them shortly here.\n", - "\n", - " * LINPACK: package for linear equations and least square problems.\n", - "\n", - " * LAPACK:package for solving symmetric, unsymmetric and generalized eigenvalue problems. From LAPACK's website it is possible to download for free all source codes from this library. Both C/C++ and Fortran versions are available.\n", - "\n", - " * BLAS (I, II and III): (Basic Linear Algebra Subprograms) are routines that provide standard building blocks for performing basic vector and matrix operations. Blas I is vector operations, II vector-matrix operations and III matrix-matrix operations. Highly parallelized and efficient codes, all available for download from .\n", - "\n", - "## Basic Matrix Features\n", - "\n", - "Matrix properties reminder" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "\\mathbf{A} =\n", - " \\begin{bmatrix} a_{11} & a_{12} & a_{13} & a_{14} \\\\\n", - " a_{21} & a_{22} & a_{23} & a_{24} \\\\\n", - " a_{31} & a_{32} & a_{33} & a_{34} \\\\\n", - " a_{41} & a_{42} & a_{43} & a_{44}\n", - " \\end{bmatrix}\\qquad\n", - "\\mathbf{I} =\n", - " \\begin{bmatrix} 1 & 0 & 0 & 0 \\\\\n", - " 0 & 1 & 0 & 0 \\\\\n", - " 0 & 0 & 1 & 0 \\\\\n", - " 0 & 0 & 0 & 1\n", - " \\end{bmatrix}\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "The inverse of a matrix is defined by" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "\\mathbf{A}^{-1} \\cdot \\mathbf{A} = I\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "\n", - "\n", - "\n", - "\n", - "\n", - "\n", - "\n", - "\n", - "\n", - "\n", - "\n", - "
Relations Name matrix elements
$A = A^{T}$ symmetric $a_{ij} = a_{ji}$
$A = \\left (A^{T} \\right )^{-1}$ real orthogonal $\\sum_k a_{ik} a_{jk} = \\sum_k a_{ki} a_{kj} = \\delta_{ij}$
$A = A^{ * }$ real matrix $a_{ij} = a_{ij}^{ * }$
$A = A^{\\dagger}$ hermitian $a_{ij} = a_{ji}^{ * }$
$A = \\left (A^{\\dagger} \\right )^{-1}$ unitary $\\sum_k a_{ik} a_{jk}^{ * } = \\sum_k a_{ki}^{ * } a_{kj} = \\delta_{ij}$
\n", - "\n", - "\n", - "### Some famous Matrices\n", - "\n", - " * Diagonal if $a_{ij}=0$ for $i\\ne j$\n", - "\n", - " * Upper triangular if $a_{ij}=0$ for $i > j$\n", - "\n", - " * Lower triangular if $a_{ij}=0$ for $i < j$\n", - "\n", - " * Upper Hessenberg if $a_{ij}=0$ for $i > j+1$\n", - "\n", - " * Lower Hessenberg if $a_{ij}=0$ for $i < j+1$\n", - "\n", - " * Tridiagonal if $a_{ij}=0$ for $|i -j| > 1$\n", - "\n", - " * Lower banded with bandwidth $p$: $a_{ij}=0$ for $i > j+p$\n", - "\n", - " * Upper banded with bandwidth $p$: $a_{ij}=0$ for $i < j+p$\n", - "\n", - " * Banded, block upper triangular, block lower triangular....\n", - "\n", - "### More Basic Matrix Features\n", - "\n", - "Some Equivalent Statements\n", - "For an $N\\times N$ matrix $\\mathbf{A}$ the following properties are all equivalent\n", - "\n", - " * If the inverse of $\\mathbf{A}$ exists, $\\mathbf{A}$ is nonsingular.\n", - "\n", - " * The equation $\\mathbf{Ax}=0$ implies $\\mathbf{x}=0$.\n", - "\n", - " * The rows of $\\mathbf{A}$ form a basis of $R^N$.\n", - "\n", - " * The columns of $\\mathbf{A}$ form a basis of $R^N$.\n", - "\n", - " * $\\mathbf{A}$ is a product of elementary matrices.\n", - "\n", - " * $0$ is not eigenvalue of $\\mathbf{A}$.\n", - "\n", - "## Numpy and arrays\n", - "[Numpy](http://www.numpy.org/) provides an easy way to handle arrays in Python. The standard way to import this library is as" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": false, - "editable": true - }, - "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": null, - "metadata": { - "collapsed": false, - "editable": true - }, - "outputs": [], - "source": [ - "n = 10\n", - "x = np.random.normal(size=n)\n", - "print(x)" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "We defined a vector $x$ with $n=10$ elements with its values given by the Normal distribution $N(0,1)$.\n", - "Another alternative is to declare a vector as follows" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": false, - "editable": true - }, - "outputs": [], - "source": [ - "import numpy as np\n", - "x = np.array([1, 2, 3])\n", - "print(x)" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "Here we have defined a vector with three elements, with $x_0=1$, $x_1=2$ and $x_2=3$. Note that both Python and C++\n", - "start numbering array elements from $0$ and on. This means that a vector with $n$ elements has a sequence of entities $x_0, x_1, x_2, \\dots, x_{n-1}$. We could also let (recommended) Numpy to compute the logarithms of a specific array as" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": false, - "editable": true - }, - "outputs": [], - "source": [ - "import numpy as np\n", - "x = np.log(np.array([4, 7, 8]))\n", - "print(x)" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "In the last example we used Numpy's unary function $np.log$. This function is\n", - "highly tuned to compute array elements since the code is vectorized\n", - "and does not require looping. We normaly recommend that you use the\n", - "Numpy intrinsic functions instead of the corresponding **log** function\n", - "from Python's **math** module. The looping is done explicitely by the\n", - "**np.log** function. The alternative, and slower way to compute the\n", - "logarithms of a vector would be to write" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": false, - "editable": true - }, - "outputs": [], - "source": [ - "import numpy as np\n", - "from math import log\n", - "x = np.array([4, 7, 8])\n", - "for i in range(0, len(x)):\n", - " x[i] = log(x[i])\n", - "print(x)" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "We note that our code is much longer already and we need to import the **log** function from the **math** module. \n", - "The attentive reader will also notice that the output is $[1, 1, 2]$. Python interprets automagically our numbers as integers (like the **automatic** keyword in C++). To change this we could define our array elements to be double precision numbers as" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": false, - "editable": true - }, - "outputs": [], - "source": [ - "import numpy as np\n", - "x = np.log(np.array([4, 7, 8], dtype = np.float64))\n", - "print(x)" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "or simply write them as double precision numbers (Python uses 64 bits as default for floating point type variables), that is" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": false, - "editable": true - }, - "outputs": [], - "source": [ - "import numpy as np\n", - "x = np.log(np.array([4.0, 7.0, 8.0])\n", - "print(x)" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "To check the number of bytes (remember that one byte contains eight bits for double precision variables), you can use simple use the **itemsize** functionality (the array $x$ is actually an object which inherits the functionalities defined in Numpy) as" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": false, - "editable": true - }, - "outputs": [], - "source": [ - "import numpy as np\n", - "x = np.log(np.array([4.0, 7.0, 8.0])\n", - "print(x.itemsize)" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "## Matrices in Python\n", - "\n", - "Having defined vectors, we are now ready to try out matrices. We can\n", - "define a $3 \\times 3 $ real matrix $\\hat{A}$ as (recall that we user\n", - "lowercase letters for vectors and uppercase letters for matrices)" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": false, - "editable": true - }, - "outputs": [], - "source": [ - "import numpy as np\n", - "A = np.log(np.array([ [4.0, 7.0, 8.0], [3.0, 10.0, 11.0], [4.0, 5.0, 7.0] ]))\n", - "print(A)" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "If we use the **shape** function we would get $(3, 3)$ as output, that is verifying that our matrix is a $3\\times 3$ matrix. We can slice the matrix and print for example the first column (Python organized matrix elements in a row-major order, see below) as" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": false, - "editable": true - }, - "outputs": [], - "source": [ - "import numpy as np\n", - "A = np.log(np.array([ [4.0, 7.0, 8.0], [3.0, 10.0, 11.0], [4.0, 5.0, 7.0] ]))\n", - "# print the first column, row-major order and elements start with 0\n", - "print(A[:,0])" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "We can continue this was by printing out other columns or rows. The example here prints out the second column" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": false, - "editable": true - }, - "outputs": [], - "source": [ - "import numpy as np\n", - "A = np.log(np.array([ [4.0, 7.0, 8.0], [3.0, 10.0, 11.0], [4.0, 5.0, 7.0] ]))\n", - "# print the first column, row-major order and elements start with 0\n", - "print(A[1,:])" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "Numpy contains many other functionalities that allow us to slice, subdivide etc etc arrays. We strongly recommend that you look up the [Numpy website for more details](http://www.numpy.org/). Useful functions when defining a matrix are the **np.zeros** function which declares a matrix of a given dimension and sets all elements to zero" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": false, - "editable": true - }, - "outputs": [], - "source": [ - "import numpy as np\n", - "n = 10\n", - "# define a matrix of dimension 10 x 10 and set all elements to zero\n", - "A = np.zeros( (n, n) )\n", - "print(A)" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "or initializing all elements to" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": false, - "editable": true - }, - "outputs": [], - "source": [ - "import numpy as np\n", - "n = 10\n", - "# define a matrix of dimension 10 x 10 and set all elements to one\n", - "A = np.ones( (n, n) )\n", - "print(A)" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "or as unitarily distributed random numbers (see the material on random number generators in the statistics part)" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": false, - "editable": true - }, - "outputs": [], - "source": [ - "import numpy as np\n", - "n = 10\n", - "# define a matrix of dimension 10 x 10 and set all elements to random numbers with x \\in [0, 1]\n", - "A = np.random.rand(n, n)\n", - "print(A)" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "As we will see throughout these lectures, there are several extremely useful functionalities in Numpy.\n", - "As an example, consider the discussion of the covariance matrix. Suppose we have defined three vectors\n", - "$\\hat{x}, \\hat{y}, \\hat{z}$ with $n$ elements each. The covariance matrix is defined as" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "\\hat{\\Sigma} = \\begin{bmatrix} \\sigma_{xx} & \\sigma_{xy} & \\sigma_{xz} \\\\\n", - " \\sigma_{yx} & \\sigma_{yy} & \\sigma_{yz} \\\\\n", - " \\sigma_{zx} & \\sigma_{zy} & \\sigma_{zz} \n", - " \\end{bmatrix},\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "where for example" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "\\sigma_{xy} =\\frac{1}{n} \\sum_{i=0}^{n-1}(x_i- \\overline{x})(y_i- \\overline{y}).\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "The Numpy function **np.cov** calculates the covariance elements using the factor $1/(n-1)$ instead of $1/n$ since it assumes we do not have the exact mean values. \n", - "The following simple function uses the **np.vstack** function which takes each vector of dimension $1\\times n$ and produces a $3\\times n$ matrix $\\hat{W}$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "\\hat{W} = \\begin{bmatrix} x_0 & y_0 & z_0 \\\\\n", - " x_1 & y_1 & z_1 \\\\\n", - " x_2 & y_2 & z_2 \\\\\n", - " \\dots & \\dots & \\dots \\\\\n", - " x_{n-2} & y_{n-2} & z_{n-2} \\\\\n", - " x_{n-1} & y_{n-1} & z_{n-1}\n", - " \\end{bmatrix},\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "which in turn is converted into into the $3\\times 3$ covariance matrix\n", - "$\\hat{\\Sigma}$ via the Numpy function **np.cov()**. We note that we can also calculate\n", - "the mean value of each set of samples $\\hat{x}$ etc using the Numpy\n", - "function **np.mean(x)**. We can also extract the eigenvalues of the\n", - "covariance matrix through the **np.linalg.eig()** function." - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": false, - "editable": true - }, - "outputs": [], - "source": [ - "# Importing various packages\n", - "import numpy as np\n", - "\n", - "n = 100\n", - "x = np.random.normal(size=n)\n", - "print(np.mean(x))\n", - "y = 4+3*x+np.random.normal(size=n)\n", - "print(np.mean(y))\n", - "z = x**3+np.random.normal(size=n)\n", - "print(np.mean(z))\n", - "W = np.vstack((x, y, z))\n", - "Sigma = np.cov(W)\n", - "print(Sigma)\n", - "Eigvals, Eigvecs = np.linalg.eig(Sigma)\n", - "print(Eigvals)" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": false, - "editable": true - }, - "outputs": [], - "source": [ - "%matplotlib inline\n", - "\n", - "import numpy as np\n", - "import matplotlib.pyplot as plt\n", - "from scipy import sparse\n", - "eye = np.eye(4)\n", - "print(eye)\n", - "sparse_mtx = sparse.csr_matrix(eye)\n", - "print(sparse_mtx)\n", - "x = np.linspace(-10,10,100)\n", - "y = np.sin(x)\n", - "plt.plot(x,y,marker='x')\n", - "plt.show()" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "## Meet the Pandas\n", - "\n", - "\n", - "\n", - "\n", - "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": null, - "metadata": { - "collapsed": false, - "editable": true - }, - "outputs": [], - "source": [ - "import pandas as pd\n", - "from IPython.display import display\n", - "data = {'First Name': [\"Frodo\", \"Bilbo\", \"Aragorn II\", \"Samwise\"],\n", - " 'Last Name': [\"Baggins\", \"Baggins\",\"Elessar\",\"Gamgee\"],\n", - " 'Place of birth': [\"Shire\", \"Shire\", \"Eriador\", \"Shire\"],\n", - " 'Date of Birth T.A.': [2968, 2890, 2931, 2980]\n", - " }\n", - "data_pandas = pd.DataFrame(data)\n", - "display(data_pandas)" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "In the above we have imported **pandas** with the shorthand **pd**, the latter has become the standard way we import **pandas**. We make then a list of various variables\n", - "and reorganize the aboves lists into a **DataFrame** and then print out a neat table with specific column labels as *Name*, *place of birth* and *date of birth*.\n", - "Displaying these results, we see that the indices are given by the default numbers from zero to three.\n", - "**pandas** is extremely flexible and we can easily change the above indices by defining a new type of indexing as" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": false, - "editable": true - }, - "outputs": [], - "source": [ - "data_pandas = pd.DataFrame(data,index=['Frodo','Bilbo','Aragorn','Sam'])\n", - "display(data_pandas)" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "Thereafter we display the content of the row which begins with the index **Aragorn**" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": false, - "editable": true - }, - "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": null, - "metadata": { - "collapsed": false, - "editable": true - }, - "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": null, - "metadata": { - "collapsed": false, - "editable": true - }, - "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": null, - "metadata": { - "collapsed": false, - "editable": true - }, - "outputs": [], - "source": [ - "df.columns = ['First', 'Second', 'Third', 'Fourth', 'Fifth']\n", - "df.index = np.arange(10)\n", - "\n", - "display(df)\n", - "print(df['Second'].mean() )\n", - "print(df.info())\n", - "print(df.describe())\n", - "\n", - "from pylab import plt, mpl\n", - "plt.style.use('seaborn')\n", - "mpl.rcParams['font.family'] = 'serif'\n", - "\n", - "df.cumsum().plot(lw=2.0, figsize=(10,6))\n", - "plt.show()\n", - "\n", - "\n", - "df.plot.bar(figsize=(10,6), rot=15)\n", - "plt.show()" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "We can produce a $4\\times 4$ matrix" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": false, - "editable": true - }, - "outputs": [], - "source": [ - "b = np.arange(16).reshape((4,4))\n", - "print(b)\n", - "df1 = pd.DataFrame(b)\n", - "print(df1)" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "and many other operations. \n", - "\n", - "The **Series** class is another important class included in\n", - "**pandas**. You can view it as a specialization of **DataFrame** but where\n", - "we have just a single column of data. It shares many of the same features as _DataFrame. As with **DataFrame**,\n", - "most operations are vectorized, achieving thereby a high performance when dealing with computations of arrays, in particular labeled arrays.\n", - "As we will see below it leads also to a very concice code close to the mathematical operations we may be interested in.\n", - "For multidimensional arrays, we recommend strongly [xarray](http://xarray.pydata.org/en/stable/). **xarray** has much of the same flexibility as **pandas**, but allows for the extension to higher dimensions than two. We will see examples later of the usage of both **pandas** and **xarray**. \n", - "\n", - "\n", - "\n", - "\n", - "\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", "\n", @@ -1153,6 +300,8 @@ }, "outputs": [], "source": [ + "%matplotlib inline\n", + "\n", "# Importing various packages\n", "import numpy as np\n", "import matplotlib.pyplot as plt\n", @@ -1480,7 +629,8 @@ "metadata": {}, "source": [ "$$\n", - "H_{\\delta}(a)={\\begin{cases}{\\frac {1}{2}}{a^{2}}&{\\text{for }}|a|\\leq \\delta ,\\\\\\delta (|a|-{\\frac {1}{2}}\\delta ),&{\\text{otherwise.}}\\end{cases}}}.\n", + "H_{\\delta}(a)=\\left\\{\\begin{array}\\frac{1}{2}a^{2}&{\\text{for }}|a|\\leq \\delta ,\\\\ \\delta (|a|-\\frac {1}{2}\\del\\\n", + "ta ),&{\\text{otherwise.}\\end{array}\\right.\n", "$$" ] }, @@ -2741,7 +1891,7 @@ "metadata": {}, "source": [ "4\n", - "8\n", + "3\n", " \n", "<\n", "<\n", @@ -2765,7 +1915,7 @@ "metadata": {}, "source": [ "4\n", - "9\n", + "4\n", " \n", "<\n", "<\n", @@ -2788,8 +1938,8 @@ "cell_type": "markdown", "metadata": {}, "source": [ + "4\n", "5\n", - "0\n", " \n", "<\n", "<\n", @@ -4058,6 +3208,348 @@ "print(\"MSE after scaling: {:.2f}\".format(mean_squared_error(clf.predict(X_test_scaled), y_test)))\n", "print(\"R2 score for scaled data: {:.2f}\".format(clf.score(X_test_scaled,y_test)))" ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Exercises\n", + "\n", + "### Exercise: Setting up various Python environments\n", + "\n", + "The first exercise here is of a mere technical art. We want you to have \n", + "* git as a version control software and to establish a user account on a provider like GitHub. Other providers like GitLab etc are equally fine. You can also use the University of Oslo [GitHub facilities](https://www.uio.no/tjenester/it/maskin/filer/versjonskontroll/github.html). \n", + "\n", + "* Install various Python packages\n", + "\n", + "We will make extensive use of Python as programming language and its\n", + "myriad of available libraries. You will find\n", + "IPython/Jupyter notebooks invaluable in your work. You can run **R**\n", + "codes in the Jupyter/IPython notebooks, with the immediate benefit of\n", + "visualizing your data. You can also use compiled languages like C++,\n", + "Rust, Fortran etc if you prefer. The focus in these lectures will be\n", + "on Python.\n", + "\n", + "If you have Python installed (we recommend Python3) and you feel\n", + "pretty familiar with installing different packages, we recommend that\n", + "you install the following Python packages via **pip** as \n", + "\n", + "1. pip install numpy scipy matplotlib ipython scikit-learn sympy pandas pillow \n", + "\n", + "For **Tensorflow**, we recommend following the instructions in the text of \n", + "[Aurelien Geron, Hands‑On Machine Learning with Scikit‑Learn and TensorFlow, O'Reilly](http://shop.oreilly.com/product/0636920052289.do)\n", + "\n", + "We will come back to **tensorflow** later. \n", + "\n", + "For Python3, replace **pip** with **pip3**.\n", + "\n", + "For OSX users we recommend, after having installed Xcode, to\n", + "install **brew**. Brew allows for a seamless installation of additional\n", + "software via for example \n", + "\n", + "1. brew install python3\n", + "\n", + "For Linux users, with its variety of distributions like for example the widely popular Ubuntu distribution,\n", + "you can use **pip** as well and simply install Python as \n", + "\n", + "1. sudo apt-get install python3 (or python for Python2.7)\n", + "\n", + "If you don't want to perform these operations separately and venture\n", + "into the hassle of exploring how to set up dependencies and paths, we\n", + "recommend two widely used distrubutions which set up all relevant\n", + "dependencies for Python, namely \n", + "\n", + "* [Anaconda](https://docs.anaconda.com/), \n", + "\n", + "which is an open source\n", + "distribution of the Python and R programming languages for large-scale\n", + "data processing, predictive analytics, and scientific computing, that\n", + "aims to simplify package management and deployment. Package versions\n", + "are managed by the package management system **conda**. \n", + "\n", + "* [Enthought canopy](https://www.enthought.com/product/canopy/) \n", + "\n", + "is a Python\n", + "distribution for scientific and analytic computing distribution and\n", + "analysis environment, available for free and under a commercial\n", + "license.\n", + "\n", + "We recommend using **Anaconda** if you are not too familiar with setting paths in a terminal environment.\n", + "\n", + "\n", + "\n", + "\n", + "### Exercise: making your own data and exploring scikit-learn\n", + "\n", + "We will generate our own dataset for a function $y(x)$ where $x \\in [0,1]$ and defined by random numbers computed with the uniform distribution. The function $y$ is a quadratic polynomial in $x$ with added stochastic noise according to the normal distribution $\\cal {N}(0,1)$.\n", + "The following simple Python instructions define our $x$ and $y$ values (with 100 data points)." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false, + "editable": true + }, + "outputs": [], + "source": [ + "x = np.random.rand(100,1)\n", + "y = 2.0+5*x*x+0.1*np.random.randn(100,1)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "1. Write your own code (following the examples under the [regression notes](https://compphysics.github.io/MachineLearning/doc/LectureNotes/_build/html/chapter1.html)) for computing the parametrization of the data set fitting a second-order polynomial. \n", + "\n", + "2. Use thereafter **scikit-learn** (see again the examples in the regression slides) and compare with your own code. \n", + "\n", + "3. Using scikit-learn, compute also the mean square error, a risk metric corresponding to the expected value of the squared (quadratic) error defined as" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "$$\n", + "MSE(\\hat{y},\\hat{\\tilde{y}}) = \\frac{1}{n}\n", + "\\sum_{i=0}^{n-1}(y_i-\\tilde{y}_i)^2,\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "and the $R^2$ score function.\n", + "If $\\tilde{\\hat{y}}_i$ is the predicted value of the $i-th$ sample and $y_i$ is the corresponding true value, then the score $R^2$ is defined as" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "$$\n", + "R^2(\\hat{y}, \\tilde{\\hat{y}}) = 1 - \\frac{\\sum_{i=0}^{n - 1} (y_i - \\tilde{y}_i)^2}{\\sum_{i=0}^{n - 1} (y_i - \\bar{y})^2},\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "where we have defined the mean value of $\\hat{y}$ as" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "$$\n", + "\\bar{y} = \\frac{1}{n} \\sum_{i=0}^{n - 1} y_i.\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "You can use the functionality included in scikit-learn. If you feel for it, you can use your own program and define functions which compute the above two functions. \n", + "Discuss the meaning of these results. Try also to vary the coefficient in front of the added stochastic noise term and discuss the quality of the fits.\n", + "\n", + "!bsol\n", + "The code here is an example of where we define our own design matrix and fit parameters $\\beta$." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false, + "editable": true + }, + "outputs": [], + "source": [ + "import os\n", + "import numpy as np\n", + "import pandas as pd\n", + "import matplotlib.pyplot as plt\n", + "from sklearn.model_selection import train_test_split\n", + "\n", + "def save_fig(fig_id):\n", + " plt.savefig(image_path(fig_id) + \".png\", format='png')\n", + "\n", + "def R2(y_data, y_model):\n", + " return 1 - np.sum((y_data - y_model) ** 2) / np.sum((y_data - np.mean(y_data)) ** 2)\n", + "def MSE(y_data,y_model):\n", + " n = np.size(y_model)\n", + " return np.sum((y_data-y_model)**2)/n\n", + "\n", + "x = np.random.rand(100)\n", + "y = 2.0+5*x*x+0.1*np.random.randn(100)\n", + "\n", + "\n", + "# The design matrix now as function of a given polynomial\n", + "X = np.zeros((len(x),3))\n", + "X[:,0] = 1.0\n", + "X[:,1] = x\n", + "X[:,2] = x**2\n", + "# We split the data in test and training data\n", + "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2)\n", + "# matrix inversion to find beta\n", + "beta = np.linalg.inv(X_train.T @ X_train) @ X_train.T @ y_train\n", + "print(beta)\n", + "# and then make the prediction\n", + "ytilde = X_train @ beta\n", + "print(\"Training R2\")\n", + "print(R2(y_train,ytilde))\n", + "print(\"Training MSE\")\n", + "print(MSE(y_train,ytilde))\n", + "ypredict = X_test @ beta\n", + "print(\"Test R2\")\n", + "print(R2(y_test,ypredict))\n", + "print(\"Test MSE\")\n", + "print(MSE(y_test,ypredict))" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "!esol\n", + "\n", + "\n", + "\n", + "### Exercise: Normalizing our data\n", + "\n", + "A much used approach before starting to train the data is to preprocess our\n", + "data. Normally the data may need a rescaling and/or may be sensitive\n", + "to extreme values. Scaling the data renders our inputs much more\n", + "suitable for the algorithms we want to employ.\n", + "\n", + "**Scikit-Learn** has several functions which allow us to rescale the\n", + "data, normally resulting in much better results in terms of various\n", + "accuracy scores. The **StandardScaler** function in **Scikit-Learn**\n", + "ensures that for each feature/predictor we study the mean value is\n", + "zero and the variance is one (every column in the design/feature\n", + "matrix). This scaling has the drawback that it does not ensure that\n", + "we have a particular maximum or minimum in our data set. Another\n", + "function included in **Scikit-Learn** is the **MinMaxScaler** which\n", + "ensures that all features are exactly between $0$ and $1$. The\n", + "\n", + "\n", + "The **Normalizer** scales each data\n", + "point such that the feature vector has a euclidean length of one. In other words, it\n", + "projects a data point on the circle (or sphere in the case of higher dimensions) with a\n", + "radius of 1. This means every data point is scaled by a different number (by the\n", + "inverse of it’s length).\n", + "This normalization is often used when only the direction (or angle) of the data matters,\n", + "not the length of the feature vector.\n", + "\n", + "The **RobustScaler** works similarly to the StandardScaler in that it\n", + "ensures statistical properties for each feature that guarantee that\n", + "they are on the same scale. However, the RobustScaler uses the median\n", + "and quartiles, instead of mean and variance. This makes the\n", + "RobustScaler ignore data points that are very different from the rest\n", + "(like measurement errors). These odd data points are also called\n", + "outliers, and might often lead to trouble for other scaling\n", + "techniques.\n", + "\n", + "\n", + "It also common to split the data in a **training** set and a **testing** set. A typical split is to use $80\\%$ of the data for training and the rest\n", + "for testing. This can be done as follows with our design matrix $\\boldsymbol{X}$ and data $\\boldsymbol{y}$ (remember to import **scikit-learn**)" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false, + "editable": true + }, + "outputs": [], + "source": [ + "# split in training and test data\n", + "X_train, X_test, y_train, y_test = train_test_split(X,y,test_size=0.2)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Then we can use the standard scaler to scale our data as" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false, + "editable": true + }, + "outputs": [], + "source": [ + "scaler = StandardScaler()\n", + "scaler.fit(X_train)\n", + "X_train_scaled = scaler.transform(X_train)\n", + "X_test_scaled = scaler.transform(X_test)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "In this exercise we want you to to compute the MSE for the training\n", + "data and the test data as function of the complexity of a polynomial,\n", + "that is the degree of a given polynomial. We want you also to compute the $R2$ score as function of the complexity of the model for both training data and test data. You should also run the calculation with and without scaling. \n", + "\n", + "One of \n", + "the aims is to reproduce Figure 2.11 of [Hastie et al](https://github.com/CompPhysics/MLErasmus/blob/master/doc/Textbooks/elementsstat.pdf).\n", + "\n", + "\n", + "\n", + "Our data is defined by $x\\in [-3,3]$ with a total of for example $100$ data points." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false, + "editable": true + }, + "outputs": [], + "source": [ + "np.random.seed()\n", + "n = 100\n", + "maxdegree = 14\n", + "# Make data set.\n", + "x = np.linspace(-3, 3, n).reshape(-1, 1)\n", + "y = np.exp(-x**2) + 1.5 * np.exp(-(x-2)**2)+ np.random.normal(0, 0.1, x.shape)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "where $y$ is the function we want to fit with a given polynomial.\n", + "!bsubex\n", + "Write a first code which sets up a design matrix $X$ defined by a fifth-order polynomial. Scale your data and split it in training and test data. \n", + "!esubex\n", + "\n", + "!bsubex\n", + "Perform an ordinary least squares and compute the means squared error and the $R2$ factor for the training data and the test data, with and without scaling.\n", + "!esubex\n", + "\n", + "!bsubex\n", + "Add now a model which allows you to make polynomials up to degree $15$. Perform a standard OLS fitting of the training data and compute the MSE and $R2$ for the training and test data and plot both test and training data MSE and $R2$ as functions of the polynomial degree. Compare what you see with Figure 2.11 of Hastie et al. Comment your results. For which polynomial degree do you find an optimal MSE (smallest value)?\n", + "!bsol\n", + "Here you simply need to change the degree of the polynomial in the above code to $n=15$.\n", + "!esol\n", + "!esubex" + ] } ], "metadata": {}, diff --git a/doc/LectureNotes/_build/html/chapter1.html b/doc/LectureNotes/_build/html/chapter1.html index bdc472e82..e1802b5f1 100644 --- a/doc/LectureNotes/_build/html/chapter1.html +++ b/doc/LectureNotes/_build/html/chapter1.html @@ -5,7 +5,7 @@ - 3. Linear Regression, basic Elements — Applied Data Analysis and Machine Learning + 3. Linear Regression — Applied Data Analysis and Machine Learning @@ -139,7 +139,7 @@

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.
-At the heart of basically all ML algorithms there are so-called minimization algorithms, often we end up with various variants of gradient methods.

- -
-

3.3. Software and needed installations

-

We will make extensive use of Python as programming language and its -myriad of available libraries. You will find -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, Julia, Fortran etc if you prefer. The focus in these lectures will be -on Python.

-

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

-
    -
  1. pip install numpy scipy matplotlib ipython scikit-learn mglearn sympy pandas pillow

  2. -
-

For Python3, replace pip with pip3.

-

For OSX users we recommend, after having installed Xcode, to -install brew. Brew allows for a seamless installation of additional -software via for example

-
    -
  1. brew install python3

  2. -
-

For Linux users, with its variety of distributions like for example the widely popular Ubuntu distribution, -you can use pip as well and simply install Python as

-
    -
  1. sudo apt-get install python3 (or python for pyhton2.7)

  2. -
-

etc etc.

-
-
-

3.4. Python installers

-

If you don’t want to perform these operations separately and venture -into the hassle of exploring how to set up dependencies and paths, we -recommend two widely used distrubutions which set up all relevant -dependencies for Python, namely

+whether we deal with supervised or unsupervised learning.

    -
  • Anaconda,

  • +
  • The first ingredient is normally our data set (which can be subdivided into training, validation and test data). Many find the most difficult part of using Machine Learning to be the set up of your data in a meaningful way.

  • +
  • 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/loss function (or error or risk function) which allows us to present an estimate on how good our model is in reproducing the data it is supposed to train.

-

which is an open source -distribution of the Python and R programming languages for large-scale -data processing, predictive analytics, and scientific computing, that -aims to simplify package management and deployment. Package versions -are managed by the package management system conda.

- -

is a Python -distribution for scientific and analytic computing distribution and -analysis environment, available for free and under a commercial -license.

-

Furthermore, Google’s Colab is a free Jupyter notebook environment that requires -no setup and runs entirely in the cloud. Try it out!

+

At the heart of basically all Machine Learning algorithms we will encounter so-called minimization or optimization algorithms. A large family of such methods are so-called gradient methods.

+
+

3.2.1. A Frequentist approach to data analysis

+

When you hear phrases like predictions and estimations and +correlations and causations, what do you think of? May be you think +of the difference between classifying new data points and generating +new data points. +Or perhaps you consider that correlations represent some kind of symmetric statements like +if \(A\) is correlated with \(B\), then \(B\) is correlated with +\(A\). Causation on the other hand is directional, that is if \(A\) causes \(B\), \(B\) does not +necessarily cause \(A\).

+

These concepts are in some sense the difference between machine +learning and statistics. In machine learning and prediction based +tasks, we are often interested in developing algorithms that are +capable of learning patterns from given data in an automated fashion, +and then using these learned patterns to make predictions or +assessments of newly given data. In many cases, our primary concern +is the quality of the predictions or assessments, and we are less +concerned about the underlying patterns that were learned in order +to make these predictions.

+

In machine learning we normally use a so-called frequentist approach, +where the aim is to make predictions and find correlations. We focus +less on for example extracting a probability distribution function (PDF). The PDF can be +used in turn to make estimations and find causations such as given \(A\) +what is the likelihood of finding \(B\).

+
+
+

3.2.2. What is a good model?

+

In science and engineering we often end up in situations where we want to infer (or learn) a +quantitative model \(M\) for a given set of sample points \(\boldsymbol{X} \in [x_1, x_2,\dots x_N]\).

+

As we will see repeatedely in these lectures, we could try to fit these data points to a model given by a +straight line, or if we wish to be more sophisticated to a more complex +function.

+

The reason for inferring such a model is that it +serves many useful purposes. On the one hand, the model can reveal information +encoded in the data or underlying mechanisms from which the data were generated. For instance, we could discover important +corelations that relate interesting physics interpretations.

+

In addition, it can simplify the representation of the given data set and help +us in making predictions about future data samples.

+

A first important consideration to keep in mind is that inferring the correct model +for a given data set is an elusive, if not impossible, task. The fundamental difficulty +is that if we are not specific about what we mean by a correct model, there +could easily be many different models that fit the given data set equally well.

+

The central question is this: what leads us to say that a model is correct or +optimal for a given data set? To make the model inference problem well posed, i.e., +to guarantee that there is a unique optimal model for the given data, we need to +impose additional assumptions or restrictions on the class of models considered. To +this end, we should not be looking for just any model that can describe the data. +Instead, we should look for a model \(M\) that is the best among a restricted class +of models. In addition, to make the model inference problem computationally +tractable, we need to specify how restricted the class of models needs to be. A +common strategy is to start +with the simplest possible class of models that is just necessary to describe the data +or solve the problem at hand. More precisely, the model class should be rich enough +to contain at least one model that can fit the data to a desired accuracy and yet be +restricted enough that it is relatively simple to find the best model for the given data.

+

Thus, the most popular strategy is to start from the +simplest class of models and increase the complexity of the models only when the +simpler models become inadequate. For instance, if we work with a regression problem to fit a set of sample points, one +may first try the simplest class of models, namely linear models, followed obviously by more complex models.

+

How to evaluate which model fits best the data is something we will come back to over and over again in these sets of lectures.

-
-

3.5. Useful Python libraries

-

Here we list several useful Python libraries we strongly recommend (if you use anaconda many of these are already there)

-
    -
  • NumPy 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 library provides high-performance, easy-to-use data structures and data analysis tools

  • -
  • Xarray is a Python package that makes working with labelled multi-dimensional arrays simple, efficient, and fun!

  • -
  • Scipy (pronounced “Sigh Pie”) is a Python-based ecosystem of open-source software for mathematics, science, and engineering.

  • -
  • Matplotlib is a Python 2D plotting library which produces publication quality figures in a variety of hardcopy formats and interactive environments across platforms.

  • -
  • 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 is a Python library for symbolic mathematics.

  • -
  • scikit-learn has simple and efficient tools for machine learning, data mining and data analysis

  • -
  • TensorFlow is a Python library for fast numerical computing created and released by Google

  • -
  • Keras 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, Theano etc

  • -
-
-
-

3.6. Installing R, C++, cython or Julia

-

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 -notebook allows you to run R codes interactively in your -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

-
-
-

3.7. Installing R, C++, cython, Numba etc

-

For the C++ aficionados, Jupyter/IPython notebook allows you also to -install C++ and run codes written in this language interactively in -the browser. Since we will emphasize writing many of the algorithms -yourself, you can thus opt for either Python or C++ (or Fortran or other compiled languages) as programming -languages.

-

To add more entropy, cython can also be used when running your -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 delivers increased performance -capabilities with minimal rewrites of your codes. With its -versatility, including symbolic operations, Python offers a unique -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

-
    pycod jupyter nbconvert filename.ipynb --to latex 
-
-
-

And to add more versatility, the Python package SymPy is a Python library for symbolic mathematics. It aims to become a full-featured computer algebra system (CAS) and is entirely written in Python.

-

Finally, if you wish to use the light mark-up language -doconce you can convert a standard ascii text file into various HTML -formats, ipython notebooks, latex files, pdf files etc with minimal edits. These lectures were generated using doconce.

-
-
-

3.8. Numpy examples and Important Matrix and vector handling packages

-

There are several central software libraries for linear algebra and eigenvalue problems. Several of the more -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 -software package LAPACK, which follows two other popular packages -developed in the 1970s, namely EISPACK and LINPACK. We describe them shortly here.

-
    -
  • LINPACK: package for linear equations and least square problems.

  • -
  • LAPACK:package for solving symmetric, unsymmetric and generalized eigenvalue problems. From LAPACK’s website http://www.netlib.org it is possible to download for free all source codes from this library. Both C/C++ and Fortran versions are available.

  • -
  • 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 http://www.netlib.org.

  • -
-
-
-

3.9. Basic Matrix Features

-

Matrix properties reminder

-
-\[\begin{split} -\mathbf{A} = - \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}\qquad -\mathbf{I} = - \begin{bmatrix} 1 & 0 & 0 & 0 \\ - 0 & 1 & 0 & 0 \\ - 0 & 0 & 1 & 0 \\ - 0 & 0 & 0 & 1 - \end{bmatrix} -\end{split}\]
-

The inverse of a matrix is defined by

-
-\[ -\mathbf{A}^{-1} \cdot \mathbf{A} = I -\]
- - - - - - - - - - - -
Relations Name matrix elements
$A = A^{T}$ symmetric $a_{ij} = a_{ji}$
$A = \left (A^{T} \right )^{-1}$ real orthogonal $\sum_k a_{ik} a_{jk} = \sum_k a_{ki} a_{kj} = \delta_{ij}$
$A = A^{ * }$ real matrix $a_{ij} = a_{ij}^{ * }$
$A = A^{\dagger}$ hermitian $a_{ij} = a_{ji}^{ * }$
$A = \left (A^{\dagger} \right )^{-1}$ unitary $\sum_k a_{ik} a_{jk}^{ * } = \sum_k a_{ki}^{ * } a_{kj} = \delta_{ij}$
-
-

3.9.1. Some famous Matrices

-
    -
  • Diagonal if \(a_{ij}=0\) for \(i\ne j\)

  • -
  • Upper triangular if \(a_{ij}=0\) for \(i > j\)

  • -
  • Lower triangular if \(a_{ij}=0\) for \(i < j\)

  • -
  • Upper Hessenberg if \(a_{ij}=0\) for \(i > j+1\)

  • -
  • Lower Hessenberg if \(a_{ij}=0\) for \(i < j+1\)

  • -
  • Tridiagonal if \(a_{ij}=0\) for \(|i -j| > 1\)

  • -
  • Lower banded with bandwidth \(p\): \(a_{ij}=0\) for \(i > j+p\)

  • -
  • Upper banded with bandwidth \(p\): \(a_{ij}=0\) for \(i < j+p\)

  • -
  • Banded, block upper triangular, block lower triangular….

  • -
-
-
-

3.9.2. 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.

  • -
  • The equation \(\mathbf{Ax}=0\) implies \(\mathbf{x}=0\).

  • -
  • The rows of \(\mathbf{A}\) form a basis of \(R^N\).

  • -
  • 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}\).

  • -
-
-
-
-

3.10. Numpy and arrays

-

Numpy provides an easy way to handle arrays in Python. The standard way to import this library is as

-
-
-
import numpy as np
-
-
-
-
-

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,

-
-
-
n = 10
-x = np.random.normal(size=n)
-print(x)
-
-
-
-
-
[ 0.03607832  0.57781668 -2.61124978 -0.08271336 -1.17654307  2.45019484
-  1.40902095 -0.07159175 -0.52722156 -0.83614019]
-
-
-
-
-

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

-
-
-
import numpy as np
-x = np.array([1, 2, 3])
-print(x)
-
-
-
-
-
[1 2 3]
-
-
-
-
-

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

-
-
-
import numpy as np
-x = np.log(np.array([4, 7, 8]))
-print(x)
-
-
-
-
-
[1.38629436 1.94591015 2.07944154]
-
-
-
-
-

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

-
-
-
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)
-
-
-
-
-
[1 1 2]
-
-
-
-
-

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

-
-
-
import numpy as np
-x = np.log(np.array([4, 7, 8], dtype = np.float64))
-print(x)
-
-
-
-
-
[1.38629436 1.94591015 2.07944154]
-
-
-
-
-

or simply write them as double precision numbers (Python uses 64 bits as default for floating point type variables), that is

-
-
-
import numpy as np
-x = np.log(np.array([4.0, 7.0, 8.0])
-print(x)
-
-
-
-
-
  File "<ipython-input-7-f6d7a289d493>", line 3
-    print(x)
-    ^
-SyntaxError: invalid syntax
-
-
-
-
-

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

-
-
-
import numpy as np
-x = np.log(np.array([4.0, 7.0, 8.0])
-print(x.itemsize)
-
-
-
-
-
-
-

3.11. 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)

-
-
-
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)
-
-
-
-
-

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

-
-
-
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])
-
-
-
-
-

We can continue this was by printing out other columns or rows. The example here prints out the second column

-
-
-
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,:])
-
-
-
-
-

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. 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

-
-
-
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)
-
-
-
-
-

or initializing all elements to

-
-
-
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)
-
-
-
-
-

or as unitarily distributed random numbers (see the material on random number generators in the statistics part)

-
-
-
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)
-
-
-
-
-

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

-
-\[\begin{split} -\hat{\Sigma} = \begin{bmatrix} \sigma_{xx} & \sigma_{xy} & \sigma_{xz} \\ - \sigma_{yx} & \sigma_{yy} & \sigma_{yz} \\ - \sigma_{zx} & \sigma_{zy} & \sigma_{zz} - \end{bmatrix}, -\end{split}\]
-

where for example

-
-\[ -\sigma_{xy} =\frac{1}{n} \sum_{i=0}^{n-1}(x_i- \overline{x})(y_i- \overline{y}). -\]
-

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}\)

-
-\[\begin{split} -\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}, -\end{split}\]
-

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.

-
-
-
# 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)
-
-
-
-
-
-
-
%matplotlib inline
-
-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()
-
-
-
-
-
-
-

3.12. Meet the Pandas

- -

Another useful Python package is -pandas, 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.

-
-
-
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)
-
-
-
-
-

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

-
-
-
data_pandas = pd.DataFrame(data,index=['Frodo','Bilbo','Aragorn','Sam'])
-display(data_pandas)
-
-
-
-
-

Thereafter we display the content of the row which begins with the index Aragorn

-
-
-
display(data_pandas.loc['Aragorn'])
-
-
-
-
-

We can easily append data to this, for example

-
-
-
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)
-
-
-
-
-

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.

-
-
-
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)
-
-
-
-
-

Thereafter we can select specific columns only and plot final results

-
-
-
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()
-
-
-
-
-

We can produce a \(4\times 4\) matrix

-
-
-
b = np.arange(16).reshape((4,4))
-print(b)
-df1 = pd.DataFrame(b)
-print(df1)
-
-
-
-
-

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. 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.

-

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!

-

3.13. Simple linear regression model using scikit-learn

+

3.3. 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. @@ -1198,7 +625,9 @@ data with a straight line.

The Python code follows here.

-
# Importing various packages
+
%matplotlib inline
+
+# Importing various packages
 import numpy as np
 import matplotlib.pyplot as plt
 from sklearn.linear_model import LinearRegression
@@ -1220,6 +649,9 @@ data with a straight line.

+
+_images/chapter1_3_0.png +

This example serves several aims. It allows us to demonstrate several aspects of data analysis and later machine learning algorithms. The @@ -1301,6 +733,9 @@ to be dominated by outliers.

+
+_images/chapter1_11_0.png +

Depending on the parameter in front of the normal distribution, we may have a small or larger relative error. Try to play around with @@ -1344,6 +779,19 @@ example of the functionality of Scikit-Learn.

+
+
The intercept alpha: 
+ [2.18954529]
+Coefficient beta : 
+ [[4.57051369]]
+Mean squared error: 0.23
+Variance score: 0.88
+Mean squared log error: 0.01
+Mean absolute error: 0.39
+
+
+_images/chapter1_13_1.png +

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

@@ -1396,7 +844,8 @@ ways of dealing with outliers.

The Huber cost function is defined as

\[\begin{split} -H_{\delta}(a)={\begin{cases}{\frac {1}{2}}{a^{2}}&{\text{for }}|a|\leq \delta ,\\\delta (|a|-{\frac {1}{2}}\delta ),&{\text{otherwise.}}\end{cases}}}. +H_{\delta}(a)=\left\{\begin{array}\frac{1}{2}a^{2}&{\text{for }}|a|\leq \delta ,\\ \delta (|a|-\frac {1}{2}\del\ +ta ),&{\text{otherwise.}\end{array}\right. \end{split}\]

Here \(a=\boldsymbol{y} - \boldsymbol{\tilde{y}}\). We will discuss in more @@ -1437,6 +886,12 @@ a linear \(x\)-dependence we s +

+_images/chapter1_27_0.png +
0.004999999999999997
+
+
+

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 @@ -1499,7 +954,7 @@ to the experimental data.

arises from the tendency of proton pairs and neutron pairs to occur. An even number of particles is more stable than an odd number.

-

3.13.1. Organizing our data

+

3.3.1. 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.

@@ -1542,6 +997,18 @@ After having downloaded this file to our own computer, we are now ready to read
+
+
---------------------------------------------------------------------------
+FileNotFoundError                         Traceback (most recent call last)
+<ipython-input-5-3cd19a0768e1> in <module>
+     31     plt.savefig(image_path(fig_id) + ".png", format='png')
+     32 
+---> 33 infile = open(data_path("MassEval2016.dat"),'r')
+
+FileNotFoundError: [Errno 2] No such file or directory: 'DataFiles/MassEval2016.dat'
+
+
+

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.

@@ -1759,8 +1226,8 @@ functionality.

-
-

3.14. Linear Regression, basic elements

+
+

3.4. Linear Regression, basic elements

Video of Lecture.

Fitting a continuous function with linear parameterization in terms of the parameters \(\boldsymbol{\beta}\).

    @@ -2091,7 +1558,7 @@ allow for the usage of direct linear algebra methods such as LU

    The following matrix and vector relation will be useful here and for the rest of the course. Vectors are always written as boldfaced lower case letters and matrices as upper case boldfaced letters.

    4 -8

    +3

    < < < @@ -2108,7 +1575,7 @@ O C K

    4 -9

    +4

    < < < @@ -2124,8 +1591,8 @@ L O C K

    -

    5 -0

    +

    4 +5

    < < < @@ -2243,7 +1710,7 @@ Since we are not using Scikit-Learn here we can define our own

-

3.14.1. The \(\chi^2\) function

+

3.4.1. 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 @@ -2363,7 +1830,7 @@ Singular Value Decomposition (SVD) method discussed below. Or using Lasso and Ridge regression. See below.

-

3.14.2. Fitting an Equation of State for Dense Nuclear Matter

+

3.4.2. 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 @@ -2477,7 +1944,7 @@ below.

-

3.15. Splitting our Data in Training and Test data

+

3.5. 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 @@ -2560,7 +2027,7 @@ but now splitting the data into a training set and a test set.

-

3.16. The Boston housing data example

+

3.6. The Boston housing data example

The Boston housing
data set was originally a part of UCI Machine Learning Repository and has been removed now. The data set is now included in Scikit-Learn’s @@ -2585,7 +2052,7 @@ the house using the features (predictors) listed here.

-

3.17. Housing data, the code

+

3.7. Housing data, the code

We start by importing the libraries

@@ -2751,7 +2218,7 @@ the house using the features (predictors) listed here.

-

3.18. Reducing the number of degrees of freedom, overarching view

+

3.8. Reducing the number of degrees of freedom, overarching view

Many Machine Learning problems involve thousands or even millions of features for each training instance. Not only does this make training extremely slow, it can also make it much harder to find a good @@ -2799,7 +2266,7 @@ RobustScaler ignore data points that are very different from the rest outliers, and might often lead to trouble for other scaling techniques.

-

3.18.1. Simple preprocessing examples, Franke function and regression

+

3.8.1. Simple preprocessing examples, Franke function and regression

# Common imports
@@ -2900,6 +2367,233 @@ techniques.

+
+

3.9. Exercises

+
+

3.9.1. Exercise: Setting up various Python environments

+

The first exercise here is of a mere technical art. We want you to have

+
    +
  • git as a version control software and to establish a user account on a provider like GitHub. Other providers like GitLab etc are equally fine. You can also use the University of Oslo GitHub facilities.

  • +
  • Install various Python packages

  • +
+

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 +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.

+

If you have Python installed (we recommend Python3) and you feel +pretty familiar with installing different packages, we recommend that +you install the following Python packages via pip as

+
    +
  1. pip install numpy scipy matplotlib ipython scikit-learn sympy pandas pillow

  2. +
+

For Tensorflow, we recommend following the instructions in the text of +Aurelien Geron, Hands‑On Machine Learning with Scikit‑Learn and TensorFlow, O’Reilly

+

We will come back to tensorflow later.

+

For Python3, replace pip with pip3.

+

For OSX users we recommend, after having installed Xcode, to +install brew. Brew allows for a seamless installation of additional +software via for example

+
    +
  1. brew install python3

  2. +
+

For Linux users, with its variety of distributions like for example the widely popular Ubuntu distribution, +you can use pip as well and simply install Python as

+
    +
  1. sudo apt-get install python3 (or python for Python2.7)

  2. +
+

If you don’t want to perform these operations separately and venture +into the hassle of exploring how to set up dependencies and paths, we +recommend two widely used distrubutions which set up all relevant +dependencies for Python, namely

+ +

which is an open source +distribution of the Python and R programming languages for large-scale +data processing, predictive analytics, and scientific computing, that +aims to simplify package management and deployment. Package versions +are managed by the package management system conda.

+ +

is a Python +distribution for scientific and analytic computing distribution and +analysis environment, available for free and under a commercial +license.

+

We recommend using Anaconda if you are not too familiar with setting paths in a terminal environment.

+
+
+

3.9.2. Exercise: making your own data and exploring scikit-learn

+

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).

+
+
+
x = np.random.rand(100,1)
+y = 2.0+5*x*x+0.1*np.random.randn(100,1)
+
+
+
+
+
    +
  1. Write your own code (following the examples under the regression notes) for computing the parametrization of the data set fitting a second-order polynomial.

  2. +
  3. Use thereafter scikit-learn (see again the examples in the regression slides) and compare with your own code.

  4. +
  5. Using scikit-learn, compute also the mean square error, a risk metric corresponding to the expected value of the squared (quadratic) error defined as

  6. +
+
+\[ +MSE(\hat{y},\hat{\tilde{y}}) = \frac{1}{n} +\sum_{i=0}^{n-1}(y_i-\tilde{y}_i)^2, +\]
+

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

+
+\[ +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}, +\]
+

where we have defined the mean value of \(\hat{y}\) as

+
+\[ +\bar{y} = \frac{1}{n} \sum_{i=0}^{n - 1} y_i. +\]
+

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.

+

!bsol +The code here is an example of where we define our own design matrix and fit parameters \(\beta\).

+
+
+
import os
+import numpy as np
+import pandas as pd
+import matplotlib.pyplot as plt
+from sklearn.model_selection import train_test_split
+
+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_data)) ** 2)
+def MSE(y_data,y_model):
+    n = np.size(y_model)
+    return np.sum((y_data-y_model)**2)/n
+
+x = np.random.rand(100)
+y = 2.0+5*x*x+0.1*np.random.randn(100)
+
+
+#  The design matrix now as function of a given polynomial
+X = np.zeros((len(x),3))
+X[:,0] = 1.0
+X[:,1] = x
+X[:,2] = x**2
+# We split the data in test and training data
+X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2)
+# matrix inversion to find beta
+beta = np.linalg.inv(X_train.T @ X_train) @ X_train.T @ y_train
+print(beta)
+# 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))
+
+
+
+
+

!esol

+
+
+

3.9.3. Exercise: Normalizing our data

+

A much used approach before starting to train the data is to preprocess our +data. Normally the data may need a rescaling and/or may be sensitive +to extreme values. Scaling the data renders our inputs much more +suitable for the algorithms we want to employ.

+

Scikit-Learn has several functions which allow us to rescale the +data, normally resulting in much better results in terms of various +accuracy scores. The StandardScaler function in Scikit-Learn +ensures that for each feature/predictor we study the mean value is +zero and the variance is one (every column in the design/feature +matrix). This scaling has the drawback that it does not ensure that +we have a particular maximum or minimum in our data set. Another +function included in Scikit-Learn is the MinMaxScaler which +ensures that all features are exactly between \(0\) and \(1\). The

+

The Normalizer scales each data +point such that the feature vector has a euclidean length of one. In other words, it +projects a data point on the circle (or sphere in the case of higher dimensions) with a +radius of 1. This means every data point is scaled by a different number (by the +inverse of it’s length). +This normalization is often used when only the direction (or angle) of the data matters, +not the length of the feature vector.

+

The RobustScaler works similarly to the StandardScaler in that it +ensures statistical properties for each feature that guarantee that +they are on the same scale. However, the RobustScaler uses the median +and quartiles, instead of mean and variance. This makes the +RobustScaler ignore data points that are very different from the rest +(like measurement errors). These odd data points are also called +outliers, and might often lead to trouble for other scaling +techniques.

+

It also common to split the data in a training set and a testing set. A typical split is to use \(80\%\) of the data for training and the rest +for testing. This can be done as follows with our design matrix \(\boldsymbol{X}\) and data \(\boldsymbol{y}\) (remember to import scikit-learn)

+
+
+
# split in training and test data
+X_train, X_test, y_train, y_test = train_test_split(X,y,test_size=0.2)
+
+
+
+
+

Then we can use the standard scaler to scale our data as

+
+
+
scaler = StandardScaler()
+scaler.fit(X_train)
+X_train_scaled = scaler.transform(X_train)
+X_test_scaled = scaler.transform(X_test)
+
+
+
+
+

In this exercise we want you to to compute the MSE for the training +data and the test data as function of the complexity of a polynomial, +that is the degree of a given polynomial. We want you also to compute the \(R2\) score as function of the complexity of the model for both training data and test data. You should also run the calculation with and without scaling.

+

One of +the aims is to reproduce Figure 2.11 of Hastie et al.

+

Our data is defined by \(x\in [-3,3]\) with a total of for example \(100\) data points.

+
+
+
np.random.seed()
+n = 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)
+
+
+
+
+

where \(y\) is the function we want to fit with a given polynomial. +!bsubex +Write a first code which sets up a design matrix \(X\) defined by a fifth-order polynomial. Scale your data and split it in training and test data. +!esubex

+

!bsubex +Perform an ordinary least squares and compute the means squared error and the \(R2\) factor for the training data and the test data, with and without scaling. +!esubex

+

!bsubex +Add now a model which allows you to make polynomials up to degree \(15\). Perform a standard OLS fitting of the training data and compute the MSE and \(R2\) for the training and test data and plot both test and training data MSE and \(R2\) as functions of the polynomial degree. Compare what you see with Figure 2.11 of Hastie et al. Comment your results. For which polynomial degree do you find an optimal MSE (smallest value)? +!bsol +Here you simply need to change the degree of the polynomial in the above code to \(n=15\). +!esol +!esubex

+
+