diff --git a/doc/src/Regression/.Regression.copyright b/doc/src/Regression/.Regression.copyright new file mode 100644 index 000000000..3de6c1104 --- /dev/null +++ b/doc/src/Regression/.Regression.copyright @@ -0,0 +1 @@ +{'year': '1999-2020', 'holder': ['Morten Hjorth-Jensen'], 'cite doconce': False, 'license': 'Released under CC Attribution-NonCommercial 4.0 license'} \ No newline at end of file diff --git a/doc/src/Regression/Regression.dlog b/doc/src/Regression/Regression.dlog new file mode 100644 index 000000000..8d82056a9 --- /dev/null +++ b/doc/src/Regression/Regression.dlog @@ -0,0 +1,243 @@ +translating doconce text in Regression.do.txt to ipynb +*** replacing \bm{...} by \boldsymbol{...} (\bm is not supported by MathJax) +*** warning: latex envir \begin{bmatrix} does not work well in Markdown. + Stick to \[ ... \], equation, equation*, align, or align* + environments in math environments. + +*** warning: latex envir \begin{bmatrix} does not work well in Markdown. + Stick to \[ ... \], equation, equation*, align, or align* + environments in math environments. + +*** warning: latex envir \begin{bmatrix} does not work well in Markdown. + Stick to \[ ... \], equation, equation*, align, or align* + environments in math environments. + +*** warning: latex envir \begin{bmatrix} does not work well in Markdown. + Stick to \[ ... \], equation, equation*, align, or align* + environments in math environments. + +*** warning: latex envir \begin{bmatrix} does not work well in Markdown. + Stick to \[ ... \], equation, equation*, align, or align* + environments in math environments. + +*** warning: latex envir \begin{bmatrix} does not work well in Markdown. + Stick to \[ ... \], equation, equation*, align, or align* + environments in math environments. + +*** warning: latex envir \begin{bmatrix} does not work well in Markdown. + Stick to \[ ... \], equation, equation*, align, or align* + environments in math environments. + +*** warning: latex envir \begin{bmatrix} does not work well in Markdown. + Stick to \[ ... \], equation, equation*, align, or align* + environments in math environments. + +*** warning: latex envir \begin{bmatrix} does not work well in Markdown. + Stick to \[ ... \], equation, equation*, align, or align* + environments in math environments. + +*** warning: latex envir \begin{bmatrix} does not work well in Markdown. + Stick to \[ ... \], equation, equation*, align, or align* + environments in math environments. + +*** warning: latex envir \begin{bmatrix} does not work well in Markdown. + Stick to \[ ... \], equation, equation*, align, or align* + environments in math environments. + +*** warning: latex envir \begin{bmatrix} does not work well in Markdown. + Stick to \[ ... \], equation, equation*, align, or align* + environments in math environments. + +*** warning: latex envir \begin{bmatrix} does not work well in Markdown. + Stick to \[ ... \], equation, equation*, align, or align* + environments in math environments. + +*** warning: latex envir \begin{bmatrix} does not work well in Markdown. + Stick to \[ ... \], equation, equation*, align, or align* + environments in math environments. + +*** warning: latex envir \begin{bmatrix} does not work well in Markdown. + Stick to \[ ... \], equation, equation*, align, or align* + environments in math environments. + +*** warning: latex envir \begin{bmatrix} does not work well in Markdown. + Stick to \[ ... \], equation, equation*, align, or align* + environments in math environments. + +*** warning: latex envir \begin{bmatrix} does not work well in Markdown. + Stick to \[ ... \], equation, equation*, align, or align* + environments in math environments. + +*** warning: latex envir \begin{bmatrix} does not work well in Markdown. + Stick to \[ ... \], equation, equation*, align, or align* + environments in math environments. + +*** warning: latex envir \begin{bmatrix} does not work well in Markdown. + Stick to \[ ... \], equation, equation*, align, or align* + environments in math environments. + +*** warning: latex envir \begin{eqnarray*} does not work well in Markdown. + Stick to \[ ... \], equation, equation*, align, or align* + environments in math environments. + +Failed to remove ans_at_end environment +Failed to remove sol_at_end environment +output in Regression.ipynb +translating doconce text in Regression.do.txt to ipynb +*** replacing \bm{...} by \boldsymbol{...} (\bm is not supported by MathJax) +*** warning: latex envir \begin{bmatrix} does not work well in Markdown. + Stick to \[ ... \], equation, equation*, align, or align* + environments in math environments. + +*** warning: latex envir \begin{bmatrix} does not work well in Markdown. + Stick to \[ ... \], equation, equation*, align, or align* + environments in math environments. + +*** warning: latex envir \begin{bmatrix} does not work well in Markdown. + Stick to \[ ... \], equation, equation*, align, or align* + environments in math environments. + +*** warning: latex envir \begin{bmatrix} does not work well in Markdown. + Stick to \[ ... \], equation, equation*, align, or align* + environments in math environments. + +*** warning: latex envir \begin{bmatrix} does not work well in Markdown. + Stick to \[ ... \], equation, equation*, align, or align* + environments in math environments. + +*** warning: latex envir \begin{bmatrix} does not work well in Markdown. + Stick to \[ ... \], equation, equation*, align, or align* + environments in math environments. + +*** warning: latex envir \begin{bmatrix} does not work well in Markdown. + Stick to \[ ... \], equation, equation*, align, or align* + environments in math environments. + +*** warning: latex envir \begin{bmatrix} does not work well in Markdown. + Stick to \[ ... \], equation, equation*, align, or align* + environments in math environments. + +*** warning: latex envir \begin{bmatrix} does not work well in Markdown. + Stick to \[ ... \], equation, equation*, align, or align* + environments in math environments. + +*** warning: latex envir \begin{bmatrix} does not work well in Markdown. + Stick to \[ ... \], equation, equation*, align, or align* + environments in math environments. + +*** warning: latex envir \begin{bmatrix} does not work well in Markdown. + Stick to \[ ... \], equation, equation*, align, or align* + environments in math environments. + +*** warning: latex envir \begin{bmatrix} does not work well in Markdown. + Stick to \[ ... \], equation, equation*, align, or align* + environments in math environments. + +*** warning: latex envir \begin{bmatrix} does not work well in Markdown. + Stick to \[ ... \], equation, equation*, align, or align* + environments in math environments. + +*** warning: latex envir \begin{bmatrix} does not work well in Markdown. + Stick to \[ ... \], equation, equation*, align, or align* + environments in math environments. + +*** warning: latex envir \begin{bmatrix} does not work well in Markdown. + Stick to \[ ... \], equation, equation*, align, or align* + environments in math environments. + +*** warning: latex envir \begin{bmatrix} does not work well in Markdown. + Stick to \[ ... \], equation, equation*, align, or align* + environments in math environments. + +*** warning: latex envir \begin{bmatrix} does not work well in Markdown. + Stick to \[ ... \], equation, equation*, align, or align* + environments in math environments. + +*** warning: latex envir \begin{bmatrix} does not work well in Markdown. + Stick to \[ ... \], equation, equation*, align, or align* + environments in math environments. + +*** warning: latex envir \begin{bmatrix} does not work well in Markdown. + Stick to \[ ... \], equation, equation*, align, or align* + environments in math environments. + +*** warning: latex envir \begin{eqnarray*} does not work well in Markdown. + Stick to \[ ... \], equation, equation*, align, or align* + environments in math environments. + +Failed to remove ans_at_end environment +Failed to remove sol_at_end environment +output in Regression.ipynb +translating doconce text in Regression.do.txt to ipynb +*** replacing \bm{...} by \boldsymbol{...} (\bm is not supported by MathJax) +*** warning: latex envir \begin{bmatrix} does not work well in Markdown. + Stick to \[ ... \], equation, equation*, align, or align* + environments in math environments. + +*** warning: latex envir \begin{bmatrix} does not work well in Markdown. + Stick to \[ ... \], equation, equation*, align, or align* + environments in math environments. + +*** warning: latex envir \begin{bmatrix} does not work well in Markdown. + Stick to \[ ... \], equation, equation*, align, or align* + environments in math environments. + +*** warning: latex envir \begin{bmatrix} does not work well in Markdown. + Stick to \[ ... \], equation, equation*, align, or align* + environments in math environments. + +*** warning: latex envir \begin{bmatrix} does not work well in Markdown. + Stick to \[ ... \], equation, equation*, align, or align* + environments in math environments. + +*** warning: latex envir \begin{bmatrix} does not work well in Markdown. + Stick to \[ ... \], equation, equation*, align, or align* + environments in math environments. + +*** warning: latex envir \begin{bmatrix} does not work well in Markdown. + Stick to \[ ... \], equation, equation*, align, or align* + environments in math environments. + +*** warning: latex envir \begin{bmatrix} does not work well in Markdown. + Stick to \[ ... \], equation, equation*, align, or align* + environments in math environments. + +*** warning: latex envir \begin{bmatrix} does not work well in Markdown. + Stick to \[ ... \], equation, equation*, align, or align* + environments in math environments. + +*** warning: latex envir \begin{bmatrix} does not work well in Markdown. + Stick to \[ ... \], equation, equation*, align, or align* + environments in math environments. + +*** warning: latex envir \begin{bmatrix} does not work well in Markdown. + Stick to \[ ... \], equation, equation*, align, or align* + environments in math environments. + +*** warning: latex envir \begin{bmatrix} does not work well in Markdown. + Stick to \[ ... \], equation, equation*, align, or align* + environments in math environments. + +*** warning: latex envir \begin{bmatrix} does not work well in Markdown. + Stick to \[ ... \], equation, equation*, align, or align* + environments in math environments. + +*** warning: latex envir \begin{bmatrix} does not work well in Markdown. + Stick to \[ ... \], equation, equation*, align, or align* + environments in math environments. + +*** warning: latex envir \begin{bmatrix} does not work well in Markdown. + Stick to \[ ... \], equation, equation*, align, or align* + environments in math environments. + +*** warning: latex envir \begin{bmatrix} does not work well in Markdown. + Stick to \[ ... \], equation, equation*, align, or align* + environments in math environments. + +*** warning: latex envir \begin{eqnarray*} does not work well in Markdown. + Stick to \[ ... \], equation, equation*, align, or align* + environments in math environments. + +Failed to remove ans_at_end environment +Failed to remove sol_at_end environment +output in Regression.ipynb diff --git a/doc/src/week34/clean.sh b/doc/src/week34/clean.sh new file mode 100755 index 000000000..2e5da2c72 --- /dev/null +++ b/doc/src/week34/clean.sh @@ -0,0 +1,3 @@ +#!/bin/sh +doconce clean +rm -rf *.pdf *.tex ipynb*.tar.gz *.html ._*.html *~ reveal.js Trash README.txt diff --git a/doc/src/week34/fig/Hudson_Bay_data.pdf b/doc/src/week34/fig/Hudson_Bay_data.pdf new file mode 100644 index 000000000..6a81e9928 Binary files /dev/null and b/doc/src/week34/fig/Hudson_Bay_data.pdf differ diff --git a/doc/src/week34/fig/Hudson_Bay_data.png b/doc/src/week34/fig/Hudson_Bay_data.png new file mode 100644 index 000000000..7c6a56222 Binary files /dev/null and b/doc/src/week34/fig/Hudson_Bay_data.png differ diff --git a/doc/src/week34/fig/Hudson_Bay_sim.pdf b/doc/src/week34/fig/Hudson_Bay_sim.pdf new file mode 100644 index 000000000..b0e391469 Binary files /dev/null and b/doc/src/week34/fig/Hudson_Bay_sim.pdf differ diff --git a/doc/src/week34/fig/Hudson_Bay_sim.png b/doc/src/week34/fig/Hudson_Bay_sim.png new file mode 100644 index 000000000..d377d071b Binary files /dev/null and b/doc/src/week34/fig/Hudson_Bay_sim.png differ diff --git a/doc/src/week34/fig/SIR1.pdf b/doc/src/week34/fig/SIR1.pdf new file mode 100644 index 000000000..210259c62 Binary files /dev/null and b/doc/src/week34/fig/SIR1.pdf differ diff --git a/doc/src/week34/fig/SIR1.png b/doc/src/week34/fig/SIR1.png new file mode 100644 index 000000000..377c38043 Binary files /dev/null and b/doc/src/week34/fig/SIR1.png differ diff --git a/doc/src/week34/fig/SIR2.pdf b/doc/src/week34/fig/SIR2.pdf new file mode 100644 index 000000000..798ab1d89 Binary files /dev/null and b/doc/src/week34/fig/SIR2.pdf differ diff --git a/doc/src/week34/fig/SIR2.png b/doc/src/week34/fig/SIR2.png new file mode 100644 index 000000000..b073a1509 Binary files /dev/null and b/doc/src/week34/fig/SIR2.png differ diff --git a/doc/src/week34/fig/SIR2_025b.pdf b/doc/src/week34/fig/SIR2_025b.pdf new file mode 100644 index 000000000..70714575a Binary files /dev/null and b/doc/src/week34/fig/SIR2_025b.pdf differ diff --git a/doc/src/week34/fig/SIR2_025b.png b/doc/src/week34/fig/SIR2_025b.png new file mode 100644 index 000000000..d388e020e Binary files /dev/null and b/doc/src/week34/fig/SIR2_025b.png differ diff --git a/doc/src/week34/fig/SIR2_05b.pdf b/doc/src/week34/fig/SIR2_05b.pdf new file mode 100644 index 000000000..696e79323 Binary files /dev/null and b/doc/src/week34/fig/SIR2_05b.pdf differ diff --git a/doc/src/week34/fig/SIR2_05b.png b/doc/src/week34/fig/SIR2_05b.png new file mode 100644 index 000000000..11a398c27 Binary files /dev/null and b/doc/src/week34/fig/SIR2_05b.png differ diff --git a/doc/src/week34/fig/SIRV1.pdf b/doc/src/week34/fig/SIRV1.pdf new file mode 100644 index 000000000..c8e404c97 Binary files /dev/null and b/doc/src/week34/fig/SIRV1.pdf differ diff --git a/doc/src/week34/fig/SIRV1.png b/doc/src/week34/fig/SIRV1.png new file mode 100644 index 000000000..b25787dcd Binary files /dev/null and b/doc/src/week34/fig/SIRV1.png differ diff --git a/doc/src/week34/fig/SIRV2.pdf b/doc/src/week34/fig/SIRV2.pdf new file mode 100644 index 000000000..d4b19e31b Binary files /dev/null and b/doc/src/week34/fig/SIRV2.pdf differ diff --git a/doc/src/week34/fig/SIRV2.png b/doc/src/week34/fig/SIRV2.png new file mode 100644 index 000000000..aa4dd6615 Binary files /dev/null and b/doc/src/week34/fig/SIRV2.png differ diff --git a/doc/src/week34/fig/TNotLD.pdf b/doc/src/week34/fig/TNotLD.pdf new file mode 100644 index 000000000..ea3432785 Binary files /dev/null and b/doc/src/week34/fig/TNotLD.pdf differ diff --git a/doc/src/week34/fig/TNotLD.png b/doc/src/week34/fig/TNotLD.png new file mode 100644 index 000000000..088e11e4e Binary files /dev/null and b/doc/src/week34/fig/TNotLD.png differ diff --git a/doc/src/week34/fig/categories_SIR.png b/doc/src/week34/fig/categories_SIR.png new file mode 100644 index 000000000..8da217e98 Binary files /dev/null and b/doc/src/week34/fig/categories_SIR.png differ diff --git a/doc/src/week34/fig/categories_SIRV.png b/doc/src/week34/fig/categories_SIRV.png new file mode 100644 index 000000000..a71cec7e9 Binary files /dev/null and b/doc/src/week34/fig/categories_SIRV.png differ diff --git a/doc/src/week34/fig/categories_SIRV2.png b/doc/src/week34/fig/categories_SIRV2.png new file mode 100644 index 000000000..6db4dea23 Binary files /dev/null and b/doc/src/week34/fig/categories_SIRV2.png differ diff --git a/doc/src/week34/fig/categories_SIRV_feedback.png b/doc/src/week34/fig/categories_SIRV_feedback.png new file mode 100644 index 000000000..817d55b36 Binary files /dev/null and b/doc/src/week34/fig/categories_SIRV_feedback.png differ diff --git a/doc/src/week34/fig/categories_SIR_feedback.png b/doc/src/week34/fig/categories_SIR_feedback.png new file mode 100644 index 000000000..ff121d330 Binary files /dev/null and b/doc/src/week34/fig/categories_SIR_feedback.png differ diff --git a/doc/src/week34/fig/categories_SIR_wtext.png b/doc/src/week34/fig/categories_SIR_wtext.png new file mode 100644 index 000000000..38065483c Binary files /dev/null and b/doc/src/week34/fig/categories_SIR_wtext.png differ diff --git a/doc/src/week34/fig/categories_SIZR.png b/doc/src/week34/fig/categories_SIZR.png new file mode 100644 index 000000000..d6bf7c987 Binary files /dev/null and b/doc/src/week34/fig/categories_SIZR.png differ diff --git a/doc/src/week34/fig/categories_figs.odp b/doc/src/week34/fig/categories_figs.odp new file mode 100644 index 000000000..d05f8ad7e Binary files /dev/null and b/doc/src/week34/fig/categories_figs.odp differ diff --git a/doc/src/week34/fig/disease1.jpg b/doc/src/week34/fig/disease1.jpg new file mode 100644 index 000000000..1912909b2 Binary files /dev/null and b/doc/src/week34/fig/disease1.jpg differ diff --git a/doc/src/week34/fig/disease2.jpg b/doc/src/week34/fig/disease2.jpg new file mode 100644 index 000000000..27d660940 Binary files /dev/null and b/doc/src/week34/fig/disease2.jpg differ diff --git a/doc/src/week34/fig/p_discont.pdf b/doc/src/week34/fig/p_discont.pdf new file mode 100644 index 000000000..3d76332ea Binary files /dev/null and b/doc/src/week34/fig/p_discont.pdf differ diff --git a/doc/src/week34/fig/p_discont.png b/doc/src/week34/fig/p_discont.png new file mode 100644 index 000000000..4ade8ca48 Binary files /dev/null and b/doc/src/week34/fig/p_discont.png differ diff --git a/doc/src/week34/fig/pandas.jpg b/doc/src/week34/fig/pandas.jpg new file mode 100644 index 000000000..4236914f8 Binary files /dev/null and b/doc/src/week34/fig/pandas.jpg differ diff --git a/doc/src/week34/fig/zombie1.jpg b/doc/src/week34/fig/zombie1.jpg new file mode 100644 index 000000000..5a10db491 Binary files /dev/null and b/doc/src/week34/fig/zombie1.jpg differ diff --git a/doc/src/week34/make.sh b/doc/src/week34/make.sh new file mode 100755 index 000000000..4722a0918 --- /dev/null +++ b/doc/src/week34/make.sh @@ -0,0 +1,79 @@ +#!/bin/sh +set -x + +function system { + "$@" + if [ $? -ne 0 ]; then + echo "make.sh: unsuccessful command $@" + echo "abort!" + exit 1 + fi +} + +if [ $# -eq 0 ]; then +echo 'bash make.sh slides1|slides2' +exit 1 +fi + +name=$1 +rm -f *.tar.gz + +opt="--encoding=utf-8" +# Note: Makefile examples contain constructions like ${PROG} which +# looks like Mako constructions, but they are not. Use --no_mako +# to turn off Mako processing. +opt="--no_mako" + +rm -f *.aux + + +html=${name}-reveal +system doconce format html $name --pygments_html_style=perldoc --keep_pygments_html_bg --html_links_in_new_window --html_output=$html $opt +system doconce slides_html $html reveal --html_slide_theme=beige + +# Plain HTML documents + +html=${name}-solarized +system doconce format html $name --pygments_html_style=perldoc --html_style=solarized3 --html_links_in_new_window --html_output=$html $opt +system doconce split_html $html.html --method=space10 + +html=${name} +system doconce format html $name --pygments_html_style=default --html_style=bloodish --html_links_in_new_window --html_output=$html $opt +system doconce split_html $html.html --method=space10 + +# Bootstrap style +html=${name}-bs +system doconce format html $name --html_style=bootstrap --pygments_html_style=default --html_admon=bootstrap_panel --html_output=$html $opt +system doconce split_html $html.html --method=split --pagination --nav_button=bottom + +# IPython notebook +system doconce format ipynb $name $opt + + +# Publish +dest=../../pub +if [ ! -d $dest/$name ]; then +mkdir $dest/$name +mkdir $dest/$name/html +mkdir $dest/$name/ipynb +fi +cp -r ${name}*.html ._${name}*.html reveal.js $dest/$name/html + +# Figures: cannot just copy link, need to physically copy the files +if [ -d fig-${name} ]; then +if [ ! -d $dest/$name/html/fig-$name ]; then +mkdir $dest/$name/html/fig-$name +fi +cp -r fig-${name}/* $dest/$name/html/fig-$name +fi + +cp ${name}.ipynb $dest/$name/ipynb +ipynb_tarfile=ipynb-${name}-src.tar.gz +if [ ! -f ${ipynb_tarfile} ]; then +cat > README.txt < 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.... + + +!split +=== More Basic Matrix Features === + +!bblock 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}$. +!eblock + +!split +===== Numpy and arrays ===== +"Numpy":"http://www.numpy.org/" provides an easy way to handle arrays in Python. The standard way to import this library is as + +!bc pycod +import numpy as np +!ec +Here follows a simple example where we set up an array of ten elements, all determined by random numbers drawn according to the normal distribution, +!bc pycod +n = 10 +x = np.random.normal(size=n) +print(x) +!ec +We defined a vector $x$ with $n=10$ elements with its values given by the Normal distribution $N(0,1)$. +Another alternative is to declare a vector as follows +!bc pycod +import numpy as np +x = np.array([1, 2, 3]) +print(x) +!ec +Here we have defined a vector with three elements, with $x_0=1$, $x_1=2$ and $x_2=3$. Note that both Python and C++ +start numbering array elements from $0$ and on. This means that a vector with $n$ elements has a sequence of entities $x_0, x_1, x_2, \dots, x_{n-1}$. We could also let (recommended) Numpy to compute the logarithms of a specific array as +!bc pycod +import numpy as np +x = np.log(np.array([4, 7, 8])) +print(x) +!ec + +In the last example we used Numpy's unary function $np.log$. This function is +highly tuned to compute array elements since the code is vectorized +and does not require looping. We normaly recommend that you use the +Numpy intrinsic functions instead of the corresponding _log_ function +from Python's _math_ module. The looping is done explicitely by the +_np.log_ function. The alternative, and slower way to compute the +logarithms of a vector would be to write + +!bc pycod +import numpy as np +from math import log +x = np.array([4, 7, 8]) +for i in range(0, len(x)): + x[i] = log(x[i]) +print(x) +!ec +We note that our code is much longer already and we need to import the _log_ function from the _math_ module. +The attentive reader will also notice that the output is $[1, 1, 2]$. Python interprets automagically our numbers as integers (like the _automatic_ keyword in C++). To change this we could define our array elements to be double precision numbers as +!bc pycod +import numpy as np +x = np.log(np.array([4, 7, 8], dtype = np.float64)) +print(x) +!ec +or simply write them as double precision numbers (Python uses 64 bits as default for floating point type variables), that is +!bc pycod +import numpy as np +x = np.log(np.array([4.0, 7.0, 8.0]) +print(x) +!ec +To check the number of bytes (remember that one byte contains eight bits for double precision variables), you can use simple use the _itemsize_ functionality (the array $x$ is actually an object which inherits the functionalities defined in Numpy) as +!bc pycod +import numpy as np +x = np.log(np.array([4.0, 7.0, 8.0]) +print(x.itemsize) +!ec + +!split +===== Matrices in Python ===== + +Having defined vectors, we are now ready to try out matrices. We can +define a $3 \times 3 $ real matrix $\hat{A}$ as (recall that we user +lowercase letters for vectors and uppercase letters for matrices) + +!bc pycod +import numpy as np +A = np.log(np.array([ [4.0, 7.0, 8.0], [3.0, 10.0, 11.0], [4.0, 5.0, 7.0] ])) +print(A) +!ec +If we use the _shape_ function we would get $(3, 3)$ as output, that is verifying that our matrix is a $3\times 3$ matrix. We can slice the matrix and print for example the first column (Python organized matrix elements in a row-major order, see below) as +!bc pycod +import numpy as np +A = np.log(np.array([ [4.0, 7.0, 8.0], [3.0, 10.0, 11.0], [4.0, 5.0, 7.0] ])) +# print the first column, row-major order and elements start with 0 +print(A[:,0]) +!ec +We can continue this was by printing out other columns or rows. The example here prints out the second column +!bc pycod +import numpy as np +A = np.log(np.array([ [4.0, 7.0, 8.0], [3.0, 10.0, 11.0], [4.0, 5.0, 7.0] ])) +# print the first column, row-major order and elements start with 0 +print(A[1,:]) +!ec +Numpy contains many other functionalities that allow us to slice, subdivide etc etc arrays. We strongly recommend that you look up the "Numpy website for more details":"http://www.numpy.org/". Useful functions when defining a matrix are the _np.zeros_ function which declares a matrix of a given dimension and sets all elements to zero +!bc pycod +import numpy as np +n = 10 +# define a matrix of dimension 10 x 10 and set all elements to zero +A = np.zeros( (n, n) ) +print(A) +!ec +or initializing all elements to +!bc pycod +import numpy as np +n = 10 +# define a matrix of dimension 10 x 10 and set all elements to one +A = np.ones( (n, n) ) +print(A) +!ec +or as unitarily distributed random numbers (see the material on random number generators in the statistics part) +!bc pycod +import numpy as np +n = 10 +# define a matrix of dimension 10 x 10 and set all elements to random numbers with x \in [0, 1] +A = np.random.rand(n, n) +print(A) +!ec + +As we will see throughout these lectures, there are several extremely useful functionalities in Numpy. +As an example, consider the discussion of the covariance matrix. Suppose we have defined three vectors +$\hat{x}, \hat{y}, \hat{z}$ with $n$ elements each. The covariance matrix is defined as +!bt +\[ +\hat{\Sigma} = \begin{bmatrix} \sigma_{xx} & \sigma_{xy} & \sigma_{xz} \\ + \sigma_{yx} & \sigma_{yy} & \sigma_{yz} \\ + \sigma_{zx} & \sigma_{zy} & \sigma_{zz} + \end{bmatrix}, +\] +!et +where for example +!bt +\[ +\sigma_{xy} =\frac{1}{n} \sum_{i=0}^{n-1}(x_i- \overline{x})(y_i- \overline{y}). +\] +!et +The Numpy function _np.cov_ calculates the covariance elements using the factor $1/(n-1)$ instead of $1/n$ since it assumes we do not have the exact mean values. +The following simple function uses the _np.vstack_ function which takes each vector of dimension $1\times n$ and produces a $3\times n$ matrix $\hat{W}$ +!bt +\[ +\hat{W} = \begin{bmatrix} x_0 & y_0 & z_0 \\ + x_1 & y_1 & z_1 \\ + x_2 & y_2 & z_2 \\ + \dots & \dots & \dots \\ + x_{n-2} & y_{n-2} & z_{n-2} \\ + x_{n-1} & y_{n-1} & z_{n-1} + \end{bmatrix}, +\] +!et + +which in turn is converted into into the $3\times 3$ covariance matrix +$\hat{\Sigma}$ via the Numpy function _np.cov()_. We note that we can also calculate +the mean value of each set of samples $\hat{x}$ etc using the Numpy +function _np.mean(x)_. We can also extract the eigenvalues of the +covariance matrix through the _np.linalg.eig()_ function. + +!bc pycod +# Importing various packages +import numpy as np + +n = 100 +x = np.random.normal(size=n) +print(np.mean(x)) +y = 4+3*x+np.random.normal(size=n) +print(np.mean(y)) +z = x**3+np.random.normal(size=n) +print(np.mean(z)) +W = np.vstack((x, y, z)) +Sigma = np.cov(W) +print(Sigma) +Eigvals, Eigvecs = np.linalg.eig(Sigma) +print(Eigvals) +!ec + + +!bc pycod +import numpy as np +import matplotlib.pyplot as plt +from scipy import sparse +eye = np.eye(4) +print(eye) +sparse_mtx = sparse.csr_matrix(eye) +print(sparse_mtx) +x = np.linspace(-10,10,100) +y = np.sin(x) +plt.plot(x,y,marker='x') +plt.show() +!ec + +!split +===== Meet the Pandas ===== + + +FIGURE: [fig/pandas.jpg, width=600 frac=0.8] + +Another useful Python package is +"pandas":"https://pandas.pydata.org/", which is an open source library +providing high-performance, easy-to-use data structures and data +analysis tools for Python. _pandas_ stands for panel data, a term borrowed from econometrics and is an efficient library for data analysis with an emphasis on tabular data. +_pandas_ has two major classes, the _DataFrame_ class with two-dimensional data objects and tabular data organized in columns and the class _Series_ with a focus on one-dimensional data objects. Both classes allow you to index data easily as we will see in the examples below. +_pandas_ allows you also to perform mathematical operations on the data, spanning from simple reshapings of vectors and matrices to statistical operations. + +The following simple example shows how we can, in an easy way make tables of our data. Here we define a data set which includes names, place of birth and date of birth, and displays the data in an easy to read way. We will see repeated use of _pandas_, in particular in connection with classification of data. + +!bc pycod +import pandas as pd +from IPython.display import display +data = {'First Name': ["Frodo", "Bilbo", "Aragorn II", "Samwise"], + 'Last Name': ["Baggins", "Baggins","Elessar","Gamgee"], + 'Place of birth': ["Shire", "Shire", "Eriador", "Shire"], + 'Date of Birth T.A.': [2968, 2890, 2931, 2980] + } +data_pandas = pd.DataFrame(data) +display(data_pandas) +!ec + +In the above we have imported _pandas_ with the shorthand _pd_, the latter has become the standard way we import _pandas_. We make then a list of various variables +and reorganize the aboves lists into a _DataFrame_ and then print out a neat table with specific column labels as *Name*, *place of birth* and *date of birth*. +Displaying these results, we see that the indices are given by the default numbers from zero to three. +_pandas_ is extremely flexible and we can easily change the above indices by defining a new type of indexing as +!bc pycod +data_pandas = pd.DataFrame(data,index=['Frodo','Bilbo','Aragorn','Sam']) +display(data_pandas) +!ec +Thereafter we display the content of the row which begins with the index _Aragorn_ +!bc pycod +display(data_pandas.loc['Aragorn']) +!ec + +We can easily append data to this, for example +!bc pycod +new_hobbit = {'First Name': ["Peregrin"], + 'Last Name': ["Took"], + 'Place of birth': ["Shire"], + 'Date of Birth T.A.': [2990] + } +data_pandas=data_pandas.append(pd.DataFrame(new_hobbit, index=['Pippin'])) +display(data_pandas) +!ec + + +Here are other examples where we use the _DataFrame_ functionality to handle arrays, now with more interesting features for us, namely numbers. We set up a matrix +of dimensionality $10\times 5$ and compute the mean value and standard deviation of each column. Similarly, we can perform mathematial operations like squaring the matrix elements and many other operations. +!bc pycod +import numpy as np +import pandas as pd +from IPython.display import display +np.random.seed(100) +# setting up a 10 x 5 matrix +rows = 10 +cols = 5 +a = np.random.randn(rows,cols) +df = pd.DataFrame(a) +display(df) +print(df.mean()) +print(df.std()) +display(df**2) +!ec + +Thereafter we can select specific columns only and plot final results +!bc pycod +df.columns = ['First', 'Second', 'Third', 'Fourth', 'Fifth'] +df.index = np.arange(10) + +display(df) +print(df['Second'].mean() ) +print(df.info()) +print(df.describe()) + +from pylab import plt, mpl +plt.style.use('seaborn') +mpl.rcParams['font.family'] = 'serif' + +df.cumsum().plot(lw=2.0, figsize=(10,6)) +plt.show() + + +df.plot.bar(figsize=(10,6), rot=15) +plt.show() +!ec +We can produce a $4\times 4$ matrix +!bc pycod +b = np.arange(16).reshape((4,4)) +print(b) +df1 = pd.DataFrame(b) +print(df1) +!ec +and many other operations. + +The _Series_ class is another important class included in +_pandas_. You can view it as a specialization of _DataFrame_ but where +we have just a single column of data. It shares many of the same features as _DataFrame. As with _DataFrame_, +most operations are vectorized, achieving thereby a high performance when dealing with computations of arrays, in particular labeled arrays. +As we will see below it leads also to a very concice code close to the mathematical operations we may be interested in. +For multidimensional arrays, we recommend strongly "xarray":"http://xarray.pydata.org/en/stable/". _xarray_ has much of the same flexibility as _pandas_, but allows for the extension to higher dimensions than two. We will see examples later of the usage of both _pandas_ and _xarray_. + + +!split +===== Reading Data and fitting ===== + +In order to study various Machine Learning algorithms, we need to +access data. Acccessing data is an essential step in all machine +learning algorithms. In particular, setting up the so-called _design +matrix_ (to be defined below) is often the first element we need in +order to perform our calculations. To set up the design matrix means +reading (and later, when the calculations are done, writing) data +in various formats, The formats span from reading files from disk, +loading data from databases and interacting with online sources +like web application programming interfaces (APIs). + +In handling various input formats, as discussed above, we will mainly stay with _pandas_, +a Python package which allows us, in a seamless and painless way, to +deal with a multitude of formats, from standard _csv_ (comma separated +values) files, via _excel_, _html_ to _hdf5_ formats. With _pandas_ +and the _DataFrame_ and _Series_ functionalities we are able to convert text data +into the calculational formats we need for a specific algorithm. And our code is going to be +pretty close the basic mathematical expressions. + +Our first data set is going to be a classic from nuclear physics, namely all +available data on binding energies. Don't be intimidated if you are not familiar with nuclear physics. It serves simply as an example here of a data set. + +We will show some of the +strengths of packages like _Scikit-Learn_ in fitting nuclear binding energies to +specific functions using linear regression first. Then, as a teaser, we will show you how +you can easily implement other algorithms like decision trees and random forests and neural networks. + +But before we really start with nuclear physics data, let's just look at some simpler polynomial fitting cases, such as, +(don't be offended) fitting straight lines! + +!split +===== Friday August 21 ===== + +!split +=== Simple linear regression model using _scikit-learn_ === + +We start with perhaps our simplest possible example, using _Scikit-Learn_ to perform linear regression analysis on a data set produced by us. + +What follows is a simple Python code where we have defined a function +$y$ in terms of the variable $x$. Both are defined as vectors with $100$ entries. +The numbers in the vector $\hat{x}$ are given +by random numbers generated with a uniform distribution with entries +$x_i \in [0,1]$ (more about probability distribution functions +later). These values are then used to define a function $y(x)$ +(tabulated again as a vector) with a linear dependence on $x$ plus a +random noise added via the normal distribution. + + +The Numpy functions are imported used the _import numpy as np_ +statement and the random number generator for the uniform distribution +is called using the function _np.random.rand()_, where we specificy +that we want $100$ random variables. Using Numpy we define +automatically an array with the specified number of elements, $100$ in +our case. With the Numpy function _randn()_ we can compute random +numbers with the normal distribution (mean value $\mu$ equal to zero and +variance $\sigma^2$ set to one) and produce the values of $y$ assuming a linear +dependence as function of $x$ + +!bt +\[ +y = 2x+N(0,1), +\] +!et + +where $N(0,1)$ represents random numbers generated by the normal +distribution. From _Scikit-Learn_ we import then the +_LinearRegression_ functionality and make a prediction $\tilde{y} = +\alpha + \beta x$ using the function _fit(x,y)_. We call the set of +data $(\hat{x},\hat{y})$ for our training data. The Python package +_scikit-learn_ has also a functionality which extracts the above +fitting parameters $\alpha$ and $\beta$ (see below). Later we will +distinguish between training data and test data. + +For plotting we use the Python package +"matplotlib":"https://matplotlib.org/" which produces publication +quality figures. Feel free to explore the extensive +"gallery":"https://matplotlib.org/gallery/index.html" of examples. In +this example we plot our original values of $x$ and $y$ as well as the +prediction _ypredict_ ($\tilde{y}$), which attempts at fitting our +data with a straight line. + +The Python code follows here. +!bc pycod +# Importing various packages +import numpy as np +import matplotlib.pyplot as plt +from sklearn.linear_model import LinearRegression + +x = np.random.rand(100,1) +y = 2*x+np.random.randn(100,1) +linreg = LinearRegression() +linreg.fit(x,y) +xnew = np.array([[0],[1]]) +ypredict = linreg.predict(xnew) + +plt.plot(xnew, ypredict, "r-") +plt.plot(x, y ,'ro') +plt.axis([0,1.0,0, 5.0]) +plt.xlabel(r'$x$') +plt.ylabel(r'$y$') +plt.title(r'Simple Linear Regression') +plt.show() +!ec + +This example serves several aims. It allows us to demonstrate several +aspects of data analysis and later machine learning algorithms. The +immediate visualization shows that our linear fit is not +impressive. It goes through the data points, but there are many +outliers which are not reproduced by our linear regression. We could +now play around with this small program and change for example the +factor in front of $x$ and the normal distribution. Try to change the +function $y$ to + +!bt +\[ +y = 10x+0.01 \times N(0,1), +\] +!et + +where $x$ is defined as before. Does the fit look better? Indeed, by +reducing the role of the noise given by the normal distribution we see immediately that +our linear prediction seemingly reproduces better the training +set. However, this testing 'by the eye' is obviouly not satisfactory in the +long run. Here we have only defined the training data and our model, and +have not discussed a more rigorous approach to the _cost_ function. + +We need more rigorous criteria in defining whether we have succeeded or +not in modeling our training data. You will be surprised to see that +many scientists seldomly venture beyond this 'by the eye' approach. A +standard approach for the *cost* function is the so-called $\chi^2$ +function (a variant of the mean-squared error (MSE)) + +!bt +\[ \chi^2 = \frac{1}{n} +\sum_{i=0}^{n-1}\frac{(y_i-\tilde{y}_i)^2}{\sigma_i^2}, +\] +!et + +where $\sigma_i^2$ is the variance (to be defined later) of the entry +$y_i$. We may not know the explicit value of $\sigma_i^2$, it serves +however the aim of scaling the equations and make the cost function +dimensionless. + +Minimizing the cost function is a central aspect of +our discussions to come. Finding its minima as function of the model +parameters ($\alpha$ and $\beta$ in our case) will be a recurring +theme in these series of lectures. Essentially all machine learning +algorithms we will discuss center around the minimization of the +chosen cost function. This depends in turn on our specific +model for describing the data, a typical situation in supervised +learning. Automatizing the search for the minima of the cost function is a +central ingredient in all algorithms. Typical methods which are +employed are various variants of _gradient_ methods. These will be +discussed in more detail later. Again, you'll be surprised to hear that +many practitioners minimize the above function ''by the eye', popularly dubbed as +'chi by the eye'. That is, change a parameter and see (visually and numerically) that +the $\chi^2$ function becomes smaller. + +There are many ways to define the cost function. A simpler approach is to look at the relative difference between the training data and the predicted data, that is we define +the relative error (why would we prefer the MSE instead of the relative error?) as + +!bt +\[ +\epsilon_{\mathrm{relative}}= \frac{\vert \hat{y} -\hat{\tilde{y}}\vert}{\vert \hat{y}\vert}. +\] +!et + +The squared cost function results in an arithmetic mean-unbiased +estimator, and the absolute-value cost function results in a +median-unbiased estimator (in the one-dimensional case, and a +geometric median-unbiased estimator for the multi-dimensional +case). The squared cost function has the disadvantage that it has the tendency +to be dominated by outliers. + +We can modify easily the above Python code and plot the relative error instead +!bc pycod +import numpy as np +import matplotlib.pyplot as plt +from sklearn.linear_model import LinearRegression + +x = np.random.rand(100,1) +y = 5*x+0.01*np.random.randn(100,1) +linreg = LinearRegression() +linreg.fit(x,y) +ypredict = linreg.predict(x) + +plt.plot(x, np.abs(ypredict-y)/abs(y), "ro") +plt.axis([0,1.0,0.0, 0.5]) +plt.xlabel(r'$x$') +plt.ylabel(r'$\epsilon_{\mathrm{relative}}$') +plt.title(r'Relative error') +plt.show() +!ec + +Depending on the parameter in front of the normal distribution, we may +have a small or larger relative error. Try to play around with +different training data sets and study (graphically) the value of the +relative error. + +As mentioned above, _Scikit-Learn_ has an impressive functionality. +We can for example extract the values of $\alpha$ and $\beta$ and +their error estimates, or the variance and standard deviation and many +other properties from the statistical data analysis. + +Here we show an +example of the functionality of _Scikit-Learn_. +!bc pycod +import numpy as np +import matplotlib.pyplot as plt +from sklearn.linear_model import LinearRegression +from sklearn.metrics import mean_squared_error, r2_score, mean_squared_log_error, mean_absolute_error + +x = np.random.rand(100,1) +y = 2.0+ 5*x+0.5*np.random.randn(100,1) +linreg = LinearRegression() +linreg.fit(x,y) +ypredict = linreg.predict(x) +print('The intercept alpha: \n', linreg.intercept_) +print('Coefficient beta : \n', linreg.coef_) +# The mean squared error +print("Mean squared error: %.2f" % mean_squared_error(y, ypredict)) +# Explained variance score: 1 is perfect prediction +print('Variance score: %.2f' % r2_score(y, ypredict)) +# Mean squared log error +print('Mean squared log error: %.2f' % mean_squared_log_error(y, ypredict) ) +# Mean absolute error +print('Mean absolute error: %.2f' % mean_absolute_error(y, ypredict)) +plt.plot(x, ypredict, "r-") +plt.plot(x, y ,'ro') +plt.axis([0.0,1.0,1.5, 7.0]) +plt.xlabel(r'$x$') +plt.ylabel(r'$y$') +plt.title(r'Linear Regression fit ') +plt.show() + +!ec +The function _coef_ gives us the parameter $\beta$ of our fit while _intercept_ yields +$\alpha$. Depending on the constant in front of the normal distribution, we get values near or far from $alpha =2$ and $\beta =5$. Try to play around with different parameters in front of the normal distribution. The function _meansquarederror_ gives us the mean square error, a risk metric corresponding to the expected value of the squared (quadratic) error or loss defined as +!bt +\[ MSE(\hat{y},\hat{\tilde{y}}) = \frac{1}{n} +\sum_{i=0}^{n-1}(y_i-\tilde{y}_i)^2, +\] +!et + +The smaller the value, the better the fit. Ideally we would like to +have an MSE equal zero. The attentive reader has probably recognized +this function as being similar to the $\chi^2$ function defined above. + +The _r2score_ function computes $R^2$, the coefficient of +determination. It provides a measure of how well future samples are +likely to be predicted by the model. Best possible score is 1.0 and it +can be negative (because the model can be arbitrarily worse). A +constant model that always predicts the expected value of $\hat{y}$, +disregarding the input features, would get a $R^2$ score of $0.0$. + +If $\tilde{\hat{y}}_i$ is the predicted value of the $i-th$ sample and $y_i$ is the corresponding true value, then the score $R^2$ is defined as +!bt +\[ +R^2(\hat{y}, \tilde{\hat{y}}) = 1 - \frac{\sum_{i=0}^{n - 1} (y_i - \tilde{y}_i)^2}{\sum_{i=0}^{n - 1} (y_i - \bar{y})^2}, +\] +!et +where we have defined the mean value of $\hat{y}$ as +!bt +\[ +\bar{y} = \frac{1}{n} \sum_{i=0}^{n - 1} y_i. +\] +!et +Another quantity taht we will meet again in our discussions of regression analysis is + the mean absolute error (MAE), a risk metric corresponding to the expected value of the absolute error loss or what we call the $l1$-norm loss. In our discussion above we presented the relative error. +The MAE is defined as follows +!bt +\[ +\text{MAE}(\hat{y}, \hat{\tilde{y}}) = \frac{1}{n} \sum_{i=0}^{n-1} \left| y_i - \tilde{y}_i \right|. +\] +!et +We present the +squared logarithmic (quadratic) error +!bt +\[ +\text{MSLE}(\hat{y}, \hat{\tilde{y}}) = \frac{1}{n} \sum_{i=0}^{n - 1} (\log_e (1 + y_i) - \log_e (1 + \tilde{y}_i) )^2, +\] +!et + +where $\log_e (x)$ stands for the natural logarithm of $x$. This error +estimate is best to use when targets having exponential growth, such +as population counts, average sales of a commodity over a span of +years etc. + + +Finally, another cost function is the Huber cost function used in robust regression. + +The rationale behind this possible cost function is its reduced +sensitivity to outliers in the data set. In our discussions on +dimensionality reduction and normalization of data we will meet other +ways of dealing with outliers. + +The Huber cost function is defined as +!bt +\[ +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}}}. +\] +!et +Here $a=\bm{y} - \bm{\tilde{y}}$. +We will discuss in more +detail these and other functions in the various lectures. We conclude this part with another example. Instead of +a linear $x$-dependence we study now a cubic polynomial and use the polynomial regression analysis tools of scikit-learn. + +!bc pycod +import matplotlib.pyplot as plt +import numpy as np +import random +from sklearn.linear_model import Ridge +from sklearn.preprocessing import PolynomialFeatures +from sklearn.pipeline import make_pipeline +from sklearn.linear_model import LinearRegression + +x=np.linspace(0.02,0.98,200) +noise = np.asarray(random.sample((range(200)),200)) +y=x**3*noise +yn=x**3*100 +poly3 = PolynomialFeatures(degree=3) +X = poly3.fit_transform(x[:,np.newaxis]) +clf3 = LinearRegression() +clf3.fit(X,y) + +Xplot=poly3.fit_transform(x[:,np.newaxis]) +poly3_plot=plt.plot(x, clf3.predict(Xplot), label='Cubic Fit') +plt.plot(x,yn, color='red', label="True Cubic") +plt.scatter(x, y, label='Data', color='orange', s=15) +plt.legend() +plt.show() + +def error(a): + for i in y: + err=(y-yn)/yn + return abs(np.sum(err))/len(err) + +print (error(y)) +!ec + + + + +=== To our real data: nuclear binding energies. Brief reminder on masses and binding energies === + +Let us now dive into nuclear physics and remind ourselves briefly about some basic features about binding +energies. A basic quantity which can be measured for the ground +states of nuclei is the atomic mass $M(N, Z)$ of the neutral atom with +atomic mass number $A$ and charge $Z$. The number of neutrons is $N$. There are indeed several sophisticated experiments worldwide which allow us to measure this quantity to high precision (parts per million even). + +Atomic masses are usually tabulated in terms of the mass excess defined by +!bt +\[ +\Delta M(N, Z) = M(N, Z) - uA, +\] +!et +where $u$ is the Atomic Mass Unit +!bt +\[ +u = M(^{12}\mathrm{C})/12 = 931.4940954(57) \hspace{0.1cm} \mathrm{MeV}/c^2. +\] +!et +The nucleon masses are +!bt +\[ +m_p = 1.00727646693(9)u, +\] +!et +and +!bt +\[ +m_n = 939.56536(8)\hspace{0.1cm} \mathrm{MeV}/c^2 = 1.0086649156(6)u. +\] +!et + +In the "2016 mass evaluation of by W.J.Huang, G.Audi, M.Wang, F.G.Kondev, S.Naimi and X.Xu":"http://nuclearmasses.org/resources_folder/Wang_2017_Chinese_Phys_C_41_030003.pdf" +there are data on masses and decays of 3437 nuclei. + +The nuclear binding energy is defined as the energy required to break +up a given nucleus into its constituent parts of $N$ neutrons and $Z$ +protons. In terms of the atomic masses $M(N, Z)$ the binding energy is +defined by + + +!bt +\[ +BE(N, Z) = ZM_H c^2 + Nm_n c^2 - M(N, Z)c^2 , +\] +!et +where $M_H$ is the mass of the hydrogen atom and $m_n$ is the mass of the neutron. +In terms of the mass excess the binding energy is given by +!bt +\[ +BE(N, Z) = Z\Delta_H c^2 + N\Delta_n c^2 -\Delta(N, Z)c^2 , +\] +!et +where $\Delta_H c^2 = 7.2890$ MeV and $\Delta_n c^2 = 8.0713$ MeV. + + +A popular and physically intuitive model which can be used to parametrize +the experimental binding energies as function of $A$, is the so-called +_liquid drop model_. The ansatz is based on the following expression + +!bt +\[ +BE(N,Z) = a_1A-a_2A^{2/3}-a_3\frac{Z^2}{A^{1/3}}-a_4\frac{(N-Z)^2}{A}, +\] +!et + +where $A$ stands for the number of nucleons and the $a_i$s are parameters which are determined by a fit +to the experimental data. + + + + +To arrive at the above expression we have assumed that we can make the following assumptions: + + * There is a volume term $a_1A$ proportional with the number of nucleons (the energy is also an extensive quantity). When an assembly of nucleons of the same size is packed together into the smallest volume, each interior nucleon has a certain number of other nucleons in contact with it. This contribution is proportional to the volume. + + * There is a surface energy term $a_2A^{2/3}$. The assumption here is that a nucleon at the surface of a nucleus interacts with fewer other nucleons than one in the interior of the nucleus and hence its binding energy is less. This surface energy term takes that into account and is therefore negative and is proportional to the surface area. + + + * There is a Coulomb energy term $a_3\frac{Z^2}{A^{1/3}}$. The electric repulsion between each pair of protons in a nucleus yields less binding. + + * There is an asymmetry term $a_4\frac{(N-Z)^2}{A}$. This term is associated with the Pauli exclusion principle and reflects the fact that the proton-neutron interaction is more attractive on the average than the neutron-neutron and proton-proton interactions. + +We could also add a so-called pairing term, which is a correction term that +arises from the tendency of proton pairs and neutron pairs to +occur. An even number of particles is more stable than an odd number. + + +=== Organizing our data === + +Let us start with reading and organizing our data. +We start with the compilation of masses and binding energies from 2016. +After having downloaded this file to our own computer, we are now ready to read the file and start structuring our data. + + +We start with preparing folders for storing our calculations and the data file over masses and binding energies. We import also various modules that we will find useful in order to present various Machine Learning methods. Here we focus mainly on the functionality of _scikit-learn_. +!bc pycod +# Common imports +import numpy as np +import pandas as pd +import matplotlib.pyplot as plt +import sklearn.linear_model as skl +from sklearn.model_selection import train_test_split +from sklearn.metrics import mean_squared_error, r2_score, mean_absolute_error +import os + +# Where to save the figures and data files +PROJECT_ROOT_DIR = "Results" +FIGURE_ID = "Results/FigureFiles" +DATA_ID = "DataFiles/" + +if not os.path.exists(PROJECT_ROOT_DIR): + os.mkdir(PROJECT_ROOT_DIR) + +if not os.path.exists(FIGURE_ID): + os.makedirs(FIGURE_ID) + +if not os.path.exists(DATA_ID): + os.makedirs(DATA_ID) + +def image_path(fig_id): + return os.path.join(FIGURE_ID, fig_id) + +def data_path(dat_id): + return os.path.join(DATA_ID, dat_id) + +def save_fig(fig_id): + plt.savefig(image_path(fig_id) + ".png", format='png') + +infile = open(data_path("MassEval2016.dat"),'r') +!ec + + +Before we proceed, we define also a function for making our plots. You can obviously avoid this and simply set up various _matplotlib_ commands every time you need them. You may however find it convenient to collect all such commands in one function and simply call this function. +!bc pycod +from pylab import plt, mpl +plt.style.use('seaborn') +mpl.rcParams['font.family'] = 'serif' + +def MakePlot(x,y, styles, labels, axlabels): + plt.figure(figsize=(10,6)) + for i in range(len(x)): + plt.plot(x[i], y[i], styles[i], label = labels[i]) + plt.xlabel(axlabels[0]) + plt.ylabel(axlabels[1]) + plt.legend(loc=0) +!ec + +Our next step is to read the data on experimental binding energies and +reorganize them as functions of the mass number $A$, the number of +protons $Z$ and neutrons $N$ using _pandas_. Before we do this it is +always useful (unless you have a binary file or other types of compressed +data) to actually open the file and simply take a look at it! + + +In particular, the program that outputs the final nuclear masses is written in Fortran with a specific format. It means that we need to figure out the format and which columns contain the data we are interested in. Pandas comes with a function that reads formatted output. After having admired the file, we are now ready to start massaging it with _pandas_. The file begins with some basic format information. +!bc pycod +""" +This is taken from the data file of the mass 2016 evaluation. +All files are 3436 lines long with 124 character per line. + Headers are 39 lines long. + col 1 : Fortran character control: 1 = page feed 0 = line feed + format : a1,i3,i5,i5,i5,1x,a3,a4,1x,f13.5,f11.5,f11.3,f9.3,1x,a2,f11.3,f9.3,1x,i3,1x,f12.5,f11.5 + These formats are reflected in the pandas widths variable below, see the statement + widths=(1,3,5,5,5,1,3,4,1,13,11,11,9,1,2,11,9,1,3,1,12,11,1), + Pandas has also a variable header, with length 39 in this case. +""" +!ec + +The data we are interested in are in columns 2, 3, 4 and 11, giving us +the number of neutrons, protons, mass numbers and binding energies, +respectively. We add also for the sake of completeness the element name. The data are in fixed-width formatted lines and we will +covert them into the _pandas_ DataFrame structure. + +!bc pycod +# Read the experimental data with Pandas +Masses = pd.read_fwf(infile, usecols=(2,3,4,6,11), + names=('N', 'Z', 'A', 'Element', 'Ebinding'), + widths=(1,3,5,5,5,1,3,4,1,13,11,11,9,1,2,11,9,1,3,1,12,11,1), + header=39, + index_col=False) + +# Extrapolated values are indicated by '#' in place of the decimal place, so +# the Ebinding column won't be numeric. Coerce to float and drop these entries. +Masses['Ebinding'] = pd.to_numeric(Masses['Ebinding'], errors='coerce') +Masses = Masses.dropna() +# Convert from keV to MeV. +Masses['Ebinding'] /= 1000 + +# Group the DataFrame by nucleon number, A. +Masses = Masses.groupby('A') +# Find the rows of the grouped DataFrame with the maximum binding energy. +Masses = Masses.apply(lambda t: t[t.Ebinding==t.Ebinding.max()]) +!ec + +We have now read in the data, grouped them according to the variables we are interested in. +We see how easy it is to reorganize the data using _pandas_. If we +were to do these operations in C/C++ or Fortran, we would have had to +write various functions/subroutines which perform the above +reorganizations for us. Having reorganized the data, we can now start +to make some simple fits using both the functionalities in _numpy_ and +_Scikit-Learn_ afterwards. + +Now we define five variables which contain +the number of nucleons $A$, the number of protons $Z$ and the number of neutrons $N$, the element name and finally the energies themselves. +!bc pycod +A = Masses['A'] +Z = Masses['Z'] +N = Masses['N'] +Element = Masses['Element'] +Energies = Masses['Ebinding'] +print(Masses) +!ec +The next step, and we will define this mathematically later, is to set up the so-called _design matrix_. We will throughout call this matrix $\bm{X}$. +It has dimensionality $p\times n$, where $n$ is the number of data points and $p$ are the so-called predictors. In our case here they are given by the number of polynomials in $A$ we wish to include in the fit. +!bc pycod +# Now we set up the design matrix X +X = np.zeros((len(A),5)) +X[:,0] = 1 +X[:,1] = A +X[:,2] = A**(2.0/3.0) +X[:,3] = A**(-1.0/3.0) +X[:,4] = A**(-1.0) +!ec +With _scikitlearn_ we are now ready to use linear regression and fit our data. +!bc pycod +clf = skl.LinearRegression().fit(X, Energies) +fity = clf.predict(X) +!ec +Pretty simple! +Now we can print measures of how our fit is doing, the coefficients from the fits and plot the final fit together with our data. +!bc pycod +# The mean squared error +print("Mean squared error: %.2f" % mean_squared_error(Energies, fity)) +# Explained variance score: 1 is perfect prediction +print('Variance score: %.2f' % r2_score(Energies, fity)) +# Mean absolute error +print('Mean absolute error: %.2f' % mean_absolute_error(Energies, fity)) +print(clf.coef_, clf.intercept_) + +Masses['Eapprox'] = fity +# Generate a plot comparing the experimental with the fitted values values. +fig, ax = plt.subplots() +ax.set_xlabel(r'$A = N + Z$') +ax.set_ylabel(r'$E_\mathrm{bind}\,/\mathrm{MeV}$') +ax.plot(Masses['A'], Masses['Ebinding'], alpha=0.7, lw=2, + label='Ame2016') +ax.plot(Masses['A'], Masses['Eapprox'], alpha=0.7, lw=2, c='m', + label='Fit') +ax.legend() +save_fig("Masses2016") +plt.show() +!ec + + +=== Seeing the wood for the trees === + +As a teaser, let us now see how we can do this with decision trees using _scikit-learn_. Later we will switch to so-called _random forests_! + + +!bc pycod + +#Decision Tree Regression +from sklearn.tree import DecisionTreeRegressor +regr_1=DecisionTreeRegressor(max_depth=5) +regr_2=DecisionTreeRegressor(max_depth=7) +regr_3=DecisionTreeRegressor(max_depth=9) +regr_1.fit(X, Energies) +regr_2.fit(X, Energies) +regr_3.fit(X, Energies) + + +y_1 = regr_1.predict(X) +y_2 = regr_2.predict(X) +y_3=regr_3.predict(X) +Masses['Eapprox'] = y_3 +# Plot the results +plt.figure() +plt.plot(A, Energies, color="blue", label="Data", linewidth=2) +plt.plot(A, y_1, color="red", label="max_depth=5", linewidth=2) +plt.plot(A, y_2, color="green", label="max_depth=7", linewidth=2) +plt.plot(A, y_3, color="m", label="max_depth=9", linewidth=2) + +plt.xlabel("$A$") +plt.ylabel("$E$[MeV]") +plt.title("Decision Tree Regression") +plt.legend() +save_fig("Masses2016Trees") +plt.show() +print(Masses) +print(np.mean( (Energies-y_1)**2)) +!ec + + +=== And what about using neural networks? === +The _seaborn_ package allows us to visualize data in an efficient way. Note that we use _scikit-learn_'s multi-layer perceptron (or feed forward neural network) +functionality. +!bc pycod +from sklearn.neural_network import MLPRegressor +from sklearn.metrics import accuracy_score +import seaborn as sns + +X_train = X +Y_train = Energies +n_hidden_neurons = 100 +epochs = 100 +# store models for later use +eta_vals = np.logspace(-5, 1, 7) +lmbd_vals = np.logspace(-5, 1, 7) +# store the models for later use +DNN_scikit = np.zeros((len(eta_vals), len(lmbd_vals)), dtype=object) +train_accuracy = np.zeros((len(eta_vals), len(lmbd_vals))) +sns.set() +for i, eta in enumerate(eta_vals): + for j, lmbd in enumerate(lmbd_vals): + dnn = MLPRegressor(hidden_layer_sizes=(n_hidden_neurons), activation='logistic', + alpha=lmbd, learning_rate_init=eta, max_iter=epochs) + dnn.fit(X_train, Y_train) + DNN_scikit[i][j] = dnn + train_accuracy[i][j] = dnn.score(X_train, Y_train) + +fig, ax = plt.subplots(figsize = (10, 10)) +sns.heatmap(train_accuracy, annot=True, ax=ax, cmap="viridis") +ax.set_title("Training Accuracy") +ax.set_ylabel("$\eta$") +ax.set_xlabel("$\lambda$") +plt.show() + + + +!ec + + + + + + +===== A first summary ===== + +The aim behind these introductory words was to present to you various +Python libraries and their functionalities, in particular libraries like +_numpy_, _pandas_, _xarray_ and _matplotlib_ and other that make our life much easier +in handling various data sets and visualizing data. + +Furthermore, +_Scikit-Learn_ allows us with few lines of code to implement popular +Machine Learning algorithms for supervised learning. Later we will meet _Tensorflow_, a powerful library for deep learning. +Now it is time to dive more into the details of various methods. We will start with linear regression and try to take a deeper look at what it entails. + + + + diff --git a/doc/src/week35/clean.sh b/doc/src/week35/clean.sh new file mode 100755 index 000000000..2e5da2c72 --- /dev/null +++ b/doc/src/week35/clean.sh @@ -0,0 +1,3 @@ +#!/bin/sh +doconce clean +rm -rf *.pdf *.tex ipynb*.tar.gz *.html ._*.html *~ reveal.js Trash README.txt diff --git a/doc/src/week35/make.sh b/doc/src/week35/make.sh new file mode 100755 index 000000000..4722a0918 --- /dev/null +++ b/doc/src/week35/make.sh @@ -0,0 +1,79 @@ +#!/bin/sh +set -x + +function system { + "$@" + if [ $? -ne 0 ]; then + echo "make.sh: unsuccessful command $@" + echo "abort!" + exit 1 + fi +} + +if [ $# -eq 0 ]; then +echo 'bash make.sh slides1|slides2' +exit 1 +fi + +name=$1 +rm -f *.tar.gz + +opt="--encoding=utf-8" +# Note: Makefile examples contain constructions like ${PROG} which +# looks like Mako constructions, but they are not. Use --no_mako +# to turn off Mako processing. +opt="--no_mako" + +rm -f *.aux + + +html=${name}-reveal +system doconce format html $name --pygments_html_style=perldoc --keep_pygments_html_bg --html_links_in_new_window --html_output=$html $opt +system doconce slides_html $html reveal --html_slide_theme=beige + +# Plain HTML documents + +html=${name}-solarized +system doconce format html $name --pygments_html_style=perldoc --html_style=solarized3 --html_links_in_new_window --html_output=$html $opt +system doconce split_html $html.html --method=space10 + +html=${name} +system doconce format html $name --pygments_html_style=default --html_style=bloodish --html_links_in_new_window --html_output=$html $opt +system doconce split_html $html.html --method=space10 + +# Bootstrap style +html=${name}-bs +system doconce format html $name --html_style=bootstrap --pygments_html_style=default --html_admon=bootstrap_panel --html_output=$html $opt +system doconce split_html $html.html --method=split --pagination --nav_button=bottom + +# IPython notebook +system doconce format ipynb $name $opt + + +# Publish +dest=../../pub +if [ ! -d $dest/$name ]; then +mkdir $dest/$name +mkdir $dest/$name/html +mkdir $dest/$name/ipynb +fi +cp -r ${name}*.html ._${name}*.html reveal.js $dest/$name/html + +# Figures: cannot just copy link, need to physically copy the files +if [ -d fig-${name} ]; then +if [ ! -d $dest/$name/html/fig-$name ]; then +mkdir $dest/$name/html/fig-$name +fi +cp -r fig-${name}/* $dest/$name/html/fig-$name +fi + +cp ${name}.ipynb $dest/$name/ipynb +ipynb_tarfile=ipynb-${name}-src.tar.gz +if [ ! -f ${ipynb_tarfile} ]; then +cat > README.txt < 1: + x = np.ravel(x) + y = np.ravel(y) + + N = len(x) + l = int((n+1)*(n+2)/2) # Number of elements in beta + X = np.ones((N,l)) + + for i in range(1,n+1): + q = int((i)*(i+1)/2) + for k in range(i+1): + X[:,q+k] = (x**(i-k))*(y**k) + + return X + + +# Making meshgrid of datapoints and compute Franke's function +n = 5 +N = 1000 +x = np.sort(np.random.uniform(0, 1, N)) +y = np.sort(np.random.uniform(0, 1, N)) +z = FrankeFunction(x, y) +X = create_X(x, y, n=n) +# split in training and test data +X_train, X_test, y_train, y_test = train_test_split(X,z,test_size=0.2) + + +clf = skl.LinearRegression().fit(X_train, y_train) + +# The mean squared error and R2 score +print("MSE before scaling: {:.2f}".format(mean_squared_error(clf.predict(X_test), y_test))) +print("R2 score before scaling {:.2f}".format(clf.score(X_test,y_test))) + +scaler = StandardScaler() +scaler.fit(X_train) +X_train_scaled = scaler.transform(X_train) +X_test_scaled = scaler.transform(X_test) + +print("Feature min values before scaling:\n {}".format(X_train.min(axis=0))) +print("Feature max values before scaling:\n {}".format(X_train.max(axis=0))) + +print("Feature min values after scaling:\n {}".format(X_train_scaled.min(axis=0))) +print("Feature max values after scaling:\n {}".format(X_train_scaled.max(axis=0))) + +clf = skl.LinearRegression().fit(X_train_scaled, y_train) + + +print("MSE after scaling: {:.2f}".format(mean_squared_error(clf.predict(X_test_scaled), y_test))) +print("R2 score for scaled data: {:.2f}".format(clf.score(X_test_scaled,y_test))) + +!ec + + + diff --git a/doc/src/week36/clean.sh b/doc/src/week36/clean.sh new file mode 100755 index 000000000..2e5da2c72 --- /dev/null +++ b/doc/src/week36/clean.sh @@ -0,0 +1,3 @@ +#!/bin/sh +doconce clean +rm -rf *.pdf *.tex ipynb*.tar.gz *.html ._*.html *~ reveal.js Trash README.txt diff --git a/doc/src/week36/make.sh b/doc/src/week36/make.sh new file mode 100755 index 000000000..4722a0918 --- /dev/null +++ b/doc/src/week36/make.sh @@ -0,0 +1,79 @@ +#!/bin/sh +set -x + +function system { + "$@" + if [ $? -ne 0 ]; then + echo "make.sh: unsuccessful command $@" + echo "abort!" + exit 1 + fi +} + +if [ $# -eq 0 ]; then +echo 'bash make.sh slides1|slides2' +exit 1 +fi + +name=$1 +rm -f *.tar.gz + +opt="--encoding=utf-8" +# Note: Makefile examples contain constructions like ${PROG} which +# looks like Mako constructions, but they are not. Use --no_mako +# to turn off Mako processing. +opt="--no_mako" + +rm -f *.aux + + +html=${name}-reveal +system doconce format html $name --pygments_html_style=perldoc --keep_pygments_html_bg --html_links_in_new_window --html_output=$html $opt +system doconce slides_html $html reveal --html_slide_theme=beige + +# Plain HTML documents + +html=${name}-solarized +system doconce format html $name --pygments_html_style=perldoc --html_style=solarized3 --html_links_in_new_window --html_output=$html $opt +system doconce split_html $html.html --method=space10 + +html=${name} +system doconce format html $name --pygments_html_style=default --html_style=bloodish --html_links_in_new_window --html_output=$html $opt +system doconce split_html $html.html --method=space10 + +# Bootstrap style +html=${name}-bs +system doconce format html $name --html_style=bootstrap --pygments_html_style=default --html_admon=bootstrap_panel --html_output=$html $opt +system doconce split_html $html.html --method=split --pagination --nav_button=bottom + +# IPython notebook +system doconce format ipynb $name $opt + + +# Publish +dest=../../pub +if [ ! -d $dest/$name ]; then +mkdir $dest/$name +mkdir $dest/$name/html +mkdir $dest/$name/ipynb +fi +cp -r ${name}*.html ._${name}*.html reveal.js $dest/$name/html + +# Figures: cannot just copy link, need to physically copy the files +if [ -d fig-${name} ]; then +if [ ! -d $dest/$name/html/fig-$name ]; then +mkdir $dest/$name/html/fig-$name +fi +cp -r fig-${name}/* $dest/$name/html/fig-$name +fi + +cp ${name}.ipynb $dest/$name/ipynb +ipynb_tarfile=ipynb-${name}-src.tar.gz +if [ ! -f ${ipynb_tarfile} ]; then +cat > README.txt < 0$. We say then that the ridge estimator is biased. + +We can also compute the variance as + +!bt +\[ +\mbox{Var}[\bm{\beta}^{\mathrm{Ridge}}]=\sigma^2[ \mathbf{X}^{T} \mathbf{X} + \lambda \mathbf{I} ]^{-1} \mathbf{X}^{T} \mathbf{X} \{ [ \mathbf{X}^{\top} \mathbf{X} + \lambda \mathbf{I} ]^{-1}\}^{T}, +\] +!et +and it is easy to see that if the parameter $\lambda$ goes to infinity then the variance of Ridge parameters $\bm{\beta}$ goes to zero. + +With this, we can compute the difference + +!bt +\[ +\mbox{Var}[\bm{\beta}^{\mathrm{OLS}}]-\mbox{Var}(\bm{\beta}^{\mathrm{Ridge}})=\sigma^2 [ \mathbf{X}^{T} \mathbf{X} + \lambda \mathbf{I} ]^{-1}[ 2\lambda\mathbf{I} + \lambda^2 (\mathbf{X}^{T} \mathbf{X})^{-1} ] \{ [ \mathbf{X}^{T} \mathbf{X} + \lambda \mathbf{I} ]^{-1}\}^{T}. +\] +!et +The difference is non-negative definite since each component of the +matrix product is non-negative definite. +This means the variance we obtain with the standard OLS will always for $\lambda > 0$ be larger than the variance of $\bm{\beta}$ obtained with the Ridge estimator. This has interesting consequences when we discuss the so-called bias-variance trade-off below. + + +!split +===== Resampling methods ===== + +With all these analytical equations for both the OLS and Ridge +regression, we will now outline how to assess a given model. This will +lead us to a discussion of the so-called bias-variance tradeoff (see +below) and so-called resampling methods. + +One of the quantities we have discussed as a way to measure errors is +the mean-squared error (MSE), mainly used for fitting of continuous +functions. Another choice is the absolute error. + +In the discussions below we will focus on the MSE and in particular since we will split the data into test and training data, +we discuss the +o prediction error or simply the _test error_ $\mathrm{Err_{Test}}$, where we have a fixed training set and the test error is the MSE arising from the data reserved for testing. We discuss also the +o training error $\mathrm{Err_{Train}}$, which is the average loss over the training data. + +As our model becomes more and more complex, more of the training data tends to used. The training may thence adapt to more complicated structures in the data. This may lead to a decrease in the bias (see below for code example) and a slight increase of the variance for the test error. +For a certain level of complexity the test error will reach minimum, before starting to increase again. The +training error reaches a saturation. + + + + +!split +===== Resampling methods: Jackknife and Bootstrap ===== + +Two famous +resampling methods are the _independent bootstrap_ and _the jackknife_. + +The jackknife is a special case of the independent bootstrap. Still, the jackknife was made +popular prior to the independent bootstrap. And as the popularity of +the independent bootstrap soared, new variants, such as _the dependent bootstrap_. + +The Jackknife and independent bootstrap work for +independent, identically distributed random variables. +If these conditions are not +satisfied, the methods will fail. Yet, it should be said that if the data are +independent, identically distributed, and we only want to estimate the +variance of $\overline{X}$ (which often is the case), then there is no +need for bootstrapping. + +!split +===== Resampling methods: Jackknife ===== + +The Jackknife works by making many replicas of the estimator $\widehat{\theta}$. +The jackknife is a resampling method where we systematically leave out one observation from the vector of observed values $\bm{x} = (x_1,x_2,\cdots,X_n)$. +Let $\bm{x}_i$ denote the vector +!bt +\[ +\bm{x}_i = (x_1,x_2,\cdots,x_{i-1},x_{i+1},\cdots,x_n), +\] +!et + +which equals the vector $\bm{x}$ with the exception that observation +number $i$ is left out. Using this notation, define +$\widehat{\theta}_i$ to be the estimator +$\widehat{\theta}$ computed using $\vec{X}_i$. + + +!split +===== Jackknife code example ===== +!bc pycod +from numpy import * +from numpy.random import randint, randn +from time import time + +def jackknife(data, stat): + n = len(data);t = zeros(n); inds = arange(n); t0 = time() + ## 'jackknifing' by leaving out an observation for each i + for i in range(n): + t[i] = stat(delete(data,i) ) + + # analysis + print("Runtime: %g sec" % (time()-t0)); print("Jackknife Statistics :") + print("original bias std. error") + print("%8g %14g %15g" % (stat(data),(n-1)*mean(t)/n, (n*var(t))**.5)) + + return t + + +# Returns mean of data samples +def stat(data): + return mean(data) + + +mu, sigma = 100, 15 +datapoints = 10000 +x = mu + sigma*random.randn(datapoints) +# jackknife returns the data sample +t = jackknife(x, stat) + +!ec + + +!split +===== Resampling methods: Bootstrap ===== +!bblock +Bootstrapping is a nonparametric approach to statistical inference +that substitutes computation for more traditional distributional +assumptions and asymptotic results. Bootstrapping offers a number of +advantages: +o The bootstrap is quite general, although there are some cases in which it fails. +o Because it does not require distributional assumptions (such as normally distributed errors), the bootstrap can provide more accurate inferences when the data are not well behaved or when the sample size is small. +o It is possible to apply the bootstrap to statistics with sampling distributions that are difficult to derive, even asymptotically. +o It is relatively simple to apply the bootstrap to complex data-collection plans (such as stratified and clustered samples). +!eblock + + +!split +===== Resampling methods: Bootstrap background ===== + +Since $\widehat{\theta} = \widehat{\theta}(\bm{X})$ is a function of random variables, +$\widehat{\theta}$ itself must be a random variable. Thus it has +a pdf, call this function $p(\bm{t})$. The aim of the bootstrap is to +estimate $p(\bm{t})$ by the relative frequency of +$\widehat{\theta}$. You can think of this as using a histogram +in the place of $p(\bm{t})$. If the relative frequency closely +resembles $p(\vec{t})$, then using numerics, it is straight forward to +estimate all the interesting parameters of $p(\bm{t})$ using point +estimators. + + +!split +===== Resampling methods: More Bootstrap background ===== + +In the case that $\widehat{\theta}$ has +more than one component, and the components are independent, we use the +same estimator on each component separately. If the probability +density function of $X_i$, $p(x)$, had been known, then it would have +been straight forward to do this by: +o Drawing lots of numbers from $p(x)$, suppose we call one such set of numbers $(X_1^*, X_2^*, \cdots, X_n^*)$. +o Then using these numbers, we could compute a replica of $\widehat{\theta}$ called $\widehat{\theta}^*$. + +By repeated use of (1) and (2), many +estimates of $\widehat{\theta}$ could have been obtained. The +idea is to use the relative frequency of $\widehat{\theta}^*$ +(think of a histogram) as an estimate of $p(\bm{t})$. + +!split +===== Resampling methods: Bootstrap approach ===== + +But +unless there is enough information available about the process that +generated $X_1,X_2,\cdots,X_n$, $p(x)$ is in general +unknown. Therefore, "Efron in 1979":"https://projecteuclid.org/euclid.aos/1176344552" asked the +question: What if we replace $p(x)$ by the relative frequency +of the observation $X_i$; if we draw observations in accordance with +the relative frequency of the observations, will we obtain the same +result in some asymptotic sense? The answer is yes. + + +Instead of generating the histogram for the relative +frequency of the observation $X_i$, just draw the values +$(X_1^*,X_2^*,\cdots,X_n^*)$ with replacement from the vector +$\bm{X}$. + +!split +===== Resampling methods: Bootstrap steps ===== + +The independent bootstrap works like this: + +o Draw with replacement $n$ numbers for the observed variables $\bm{x} = (x_1,x_2,\cdots,x_n)$. +o Define a vector $\bm{x}^*$ containing the values which were drawn from $\bm{x}$. +o Using the vector $\bm{x}^*$ compute $\widehat{\theta}^*$ by evaluating $\widehat \theta$ under the observations $\bm{x}^*$. +o Repeat this process $k$ times. + +When you are done, you can draw a histogram of the relative frequency +of $\widehat \theta^*$. This is your estimate of the probability +distribution $p(t)$. Using this probability distribution you can +estimate any statistics thereof. In principle you never draw the +histogram of the relative frequency of $\widehat{\theta}^*$. Instead +you use the estimators corresponding to the statistic of interest. For +example, if you are interested in estimating the variance of $\widehat +\theta$, apply the etsimator $\widehat \sigma^2$ to the values +$\widehat \theta ^*$. + + +!split +===== Code example for the Bootstrap method ===== + +The following code starts with a Gaussian distribution with mean value +$\mu =100$ and variance $\sigma=15$. We use this to generate the data +used in the bootstrap analysis. The bootstrap analysis returns a data +set after a given number of bootstrap operations (as many as we have +data points). This data set consists of estimated mean values for each +bootstrap operation. The histogram generated by the bootstrap method +shows that the distribution for these mean values is also a Gaussian, +centered around the mean value $\mu=100$ but with standard deviation +$\sigma/\sqrt{n}$, where $n$ is the number of bootstrap samples (in +this case the same as the number of original data points). The value +of the standard deviation is what we expect from the central limit +theorem. + + +!bc pycod +from numpy import * +from numpy.random import randint, randn +from time import time +import matplotlib.mlab as mlab +import matplotlib.pyplot as plt + +# Returns mean of bootstrap samples +def stat(data): + return mean(data) + +# Bootstrap algorithm +def bootstrap(data, statistic, R): + t = zeros(R); n = len(data); inds = arange(n); t0 = time() + # non-parametric bootstrap + for i in range(R): + t[i] = statistic(data[randint(0,n,n)]) + + # analysis + print("Runtime: %g sec" % (time()-t0)); print("Bootstrap Statistics :") + print("original bias std. error") + print("%8g %8g %14g %15g" % (statistic(data), std(data),mean(t),std(t))) + return t + + +mu, sigma = 100, 15 +datapoints = 10000 +x = mu + sigma*random.randn(datapoints) +# bootstrap returns the data sample +t = bootstrap(x, stat, datapoints) +# the histogram of the bootstrapped data +n, binsboot, patches = plt.hist(t, 50, normed=1, facecolor='red', alpha=0.75) + +# add a 'best fit' line +y = mlab.normpdf( binsboot, mean(t), std(t)) +lt = plt.plot(binsboot, y, 'r--', linewidth=1) +plt.xlabel('Smarts') +plt.ylabel('Probability') +plt.axis([99.5, 100.6, 0, 3.0]) +plt.grid(True) + +plt.show() + +!ec + + +!split +===== Various steps in cross-validation ===== + +When the repetitive splitting of the data set is done randomly, +samples may accidently end up in a fast majority of the splits in +either training or test set. Such samples may have an unbalanced +influence on either model building or prediction evaluation. To avoid +this $k$-fold cross-validation structures the data splitting. The +samples are divided into $k$ more or less equally sized exhaustive and +mutually exclusive subsets. In turn (at each split) one of these +subsets plays the role of the test set while the union of the +remaining subsets constitutes the training set. Such a splitting +warrants a balanced representation of each sample in both training and +test set over the splits. Still the division into the $k$ subsets +involves a degree of randomness. This may be fully excluded when +choosing $k=n$. This particular case is referred to as leave-one-out +cross-validation (LOOCV). + +!split +===== How to set up the cross-validation for Ridge and/or Lasso ===== + +* Define a range of interest for the penalty parameter. + +* Divide the data set into training and test set comprising samples $\{1, \ldots, n\} \setminus i$ and $\{ i \}$, respectively. + +* Fit the linear regression model by means of ridge estimation for each $\lambda$ in the grid using the training set, and the corresponding estimate of the error variance $\bm{\sigma}_{-i}^2(\lambda)$, as +!bt +\begin{align*} +\bm{\beta}_{-i}(\lambda) & = ( \bm{X}_{-i, \ast}^{T} +\bm{X}_{-i, \ast} + \lambda \bm{I}_{pp})^{-1} +\bm{X}_{-i, \ast}^{T} \bm{y}_{-i} +\end{align*} +!et + +* Evaluate the prediction performance of these models on the test set by $\log\{L[y_i, \bm{X}_{i, \ast}; \bm{\beta}_{-i}(\lambda), \bm{\sigma}_{-i}^2(\lambda)]\}$. Or, by the prediction error $|y_i - \bm{X}_{i, \ast} \bm{\beta}_{-i}(\lambda)|$, the relative error, the error squared or the R2 score function. + +* Repeat the first three steps such that each sample plays the role of the test set once. + +* Average the prediction performances of the test sets at each grid point of the penalty bias/parameter. It is an estimate of the prediction performance of the model corresponding to this value of the penalty parameter on novel data. It is defined as +!bt +\begin{align*} +\frac{1}{n} \sum_{i = 1}^n \log\{L[y_i, \mathbf{X}_{i, \ast}; \bm{\beta}_{-i}(\lambda), \bm{\sigma}_{-i}^2(\lambda)]\}. +\end{align*} +!et + +!split +===== Cross-validation in brief ===== + +For the various values of $k$ + +o shuffle the dataset randomly. +o Split the dataset into $k$ groups. +o For each unique group: + o Decide which group to use as set for test data + o Take the remaining groups as a training data set + o Fit a model on the training set and evaluate it on the test set + o Retain the evaluation score and discard the model +o Summarize the model using the sample of model evaluation scores + + + +!split +===== Code Example for Cross-validation and $k$-fold Cross-validation ===== + +The code here uses Ridge regression with cross-validation (CV) resampling and $k$-fold CV in order to fit a specific polynomial. +!bc pycod +import numpy as np +import matplotlib.pyplot as plt +from sklearn.model_selection import KFold +from sklearn.linear_model import Ridge +from sklearn.model_selection import cross_val_score +from sklearn.preprocessing import PolynomialFeatures + +# A seed just to ensure that the random numbers are the same for every run. +# Useful for eventual debugging. +np.random.seed(3155) + +# Generate the data. +nsamples = 100 +x = np.random.randn(nsamples) +y = 3*x**2 + np.random.randn(nsamples) + +## Cross-validation on Ridge regression using KFold only + +# Decide degree on polynomial to fit +poly = PolynomialFeatures(degree = 6) + +# Decide which values of lambda to use +nlambdas = 500 +lambdas = np.logspace(-3, 5, nlambdas) + +# Initialize a KFold instance +k = 5 +kfold = KFold(n_splits = k) + +# Perform the cross-validation to estimate MSE +scores_KFold = np.zeros((nlambdas, k)) + +i = 0 +for lmb in lambdas: + ridge = Ridge(alpha = lmb) + j = 0 + for train_inds, test_inds in kfold.split(x): + xtrain = x[train_inds] + ytrain = y[train_inds] + + xtest = x[test_inds] + ytest = y[test_inds] + + Xtrain = poly.fit_transform(xtrain[:, np.newaxis]) + ridge.fit(Xtrain, ytrain[:, np.newaxis]) + + Xtest = poly.fit_transform(xtest[:, np.newaxis]) + ypred = ridge.predict(Xtest) + + scores_KFold[i,j] = np.sum((ypred - ytest[:, np.newaxis])**2)/np.size(ypred) + + j += 1 + i += 1 + + +estimated_mse_KFold = np.mean(scores_KFold, axis = 1) + +## Cross-validation using cross_val_score from sklearn along with KFold + +# kfold is an instance initialized above as: +# kfold = KFold(n_splits = k) + +estimated_mse_sklearn = np.zeros(nlambdas) +i = 0 +for lmb in lambdas: + ridge = Ridge(alpha = lmb) + + X = poly.fit_transform(x[:, np.newaxis]) + estimated_mse_folds = cross_val_score(ridge, X, y[:, np.newaxis], scoring='neg_mean_squared_error', cv=kfold) + + # cross_val_score return an array containing the estimated negative mse for every fold. + # we have to the the mean of every array in order to get an estimate of the mse of the model + estimated_mse_sklearn[i] = np.mean(-estimated_mse_folds) + + i += 1 + +## Plot and compare the slightly different ways to perform cross-validation + +plt.figure() + +plt.plot(np.log10(lambdas), estimated_mse_sklearn, label = 'cross_val_score') +plt.plot(np.log10(lambdas), estimated_mse_KFold, 'r--', label = 'KFold') + +plt.xlabel('log10(lambda)') +plt.ylabel('mse') + +plt.legend() + +plt.show() + +!ec + + +!split +===== The bias-variance tradeoff ===== + + +We will discuss the bias-variance tradeoff in the context of +continuous predictions such as regression. However, many of the +intuitions and ideas discussed here also carry over to classification +tasks. Consider a dataset $\mathcal{L}$ consisting of the data +$\mathbf{X}_\mathcal{L}=\{(y_j, \boldsymbol{x}_j), j=0\ldots n-1\}$. + +Let us assume that the true data is generated from a noisy model + +!bt +\[ +\bm{y}=f(\boldsymbol{x}) + \bm{\epsilon} +\] +!et + +where $\epsilon$ is normally distributed with mean zero and standard deviation $\sigma^2$. + +In our derivation of the ordinary least squares method we defined then +an approximation to the function $f$ in terms of the parameters +$\bm{\beta}$ and the design matrix $\bm{X}$ which embody our model, +that is $\bm{\tilde{y}}=\bm{X}\bm{\beta}$. + +Thereafter we found the parameters $\bm{\beta}$ by optimizing the means squared error via the so-called cost function +!bt +\[ +C(\bm{X},\bm{\beta}) =\frac{1}{n}\sum_{i=0}^{n-1}(y_i-\tilde{y}_i)^2=\mathbb{E}\left[(\bm{y}-\bm{\tilde{y}})^2\right]. +\] +!et + +We can rewrite this as +!bt +\[ +\mathbb{E}\left[(\bm{y}-\bm{\tilde{y}})^2\right]=\frac{1}{n}\sum_i(f_i-\mathbb{E}\left[\bm{\tilde{y}}\right])^2+\frac{1}{n}\sum_i(\tilde{y}_i-\mathbb{E}\left[\bm{\tilde{y}}\right])^2+\sigma^2. +\] +!et + +The three terms represent the square of the bias of the learning +method, which can be thought of as the error caused by the simplifying +assumptions built into the method. The second term represents the +variance of the chosen model and finally the last terms is variance of +the error $\bm{\epsilon}$. + +To derive this equation, we need to recall that the variance of $\bm{y}$ and $\bm{\epsilon}$ are both equal to $\sigma^2$. The mean value of $\bm{\epsilon}$ is by definition equal to zero. Furthermore, the function $f$ is not a stochastics variable, idem for $\bm{\tilde{y}}$. +We use a more compact notation in terms of the expectation value +!bt +\[ +\mathbb{E}\left[(\bm{y}-\bm{\tilde{y}})^2\right]=\mathbb{E}\left[(\bm{f}+\bm{\epsilon}-\bm{\tilde{y}})^2\right], +\] +!et +and adding and subtracting $\mathbb{E}\left[\bm{\tilde{y}}\right]$ we get +!bt +\[ +\mathbb{E}\left[(\bm{y}-\bm{\tilde{y}})^2\right]=\mathbb{E}\left[(\bm{f}+\bm{\epsilon}-\bm{\tilde{y}}+\mathbb{E}\left[\bm{\tilde{y}}\right]-\mathbb{E}\left[\bm{\tilde{y}}\right])^2\right], +\] +!et +which, using the abovementioned expectation values can be rewritten as +!bt +\[ +\mathbb{E}\left[(\bm{y}-\bm{\tilde{y}})^2\right]=\mathbb{E}\left[(\bm{y}-\mathbb{E}\left[\bm{\tilde{y}}\right])^2\right]+\mathrm{Var}\left[\bm{\tilde{y}}\right]+\sigma^2, +\] +!et +that is the rewriting in terms of the so-called bias, the variance of the model $\bm{\tilde{y}}$ and the variance of $\bm{\epsilon}$. + + + + + +!split +===== Example code for Bias-Variance tradeoff ===== +!bc pycod +import matplotlib.pyplot as plt +import numpy as np +from sklearn.linear_model import LinearRegression, Ridge, Lasso +from sklearn.preprocessing import PolynomialFeatures +from sklearn.model_selection import train_test_split +from sklearn.pipeline import make_pipeline +from sklearn.utils import resample + +np.random.seed(2018) + +n = 500 +n_boostraps = 100 +degree = 18 # A quite high value, just to show. +noise = 0.1 + +# Make data set. +x = np.linspace(-1, 3, n).reshape(-1, 1) +y = np.exp(-x**2) + 1.5 * np.exp(-(x-2)**2) + np.random.normal(0, 0.1, x.shape) + +# Hold out some test data that is never used in training. +x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.2) + +# Combine x transformation and model into one operation. +# Not neccesary, but convenient. +model = make_pipeline(PolynomialFeatures(degree=degree), LinearRegression(fit_intercept=False)) + +# The following (m x n_bootstraps) matrix holds the column vectors y_pred +# for each bootstrap iteration. +y_pred = np.empty((y_test.shape[0], n_boostraps)) +for i in range(n_boostraps): + x_, y_ = resample(x_train, y_train) + + # Evaluate the new model on the same test data each time. + y_pred[:, i] = model.fit(x_, y_).predict(x_test).ravel() + +# Note: Expectations and variances taken w.r.t. different training +# data sets, hence the axis=1. Subsequent means are taken across the test data +# set in order to obtain a total value, but before this we have error/bias/variance +# calculated per data point in the test set. +# Note 2: The use of keepdims=True is important in the calculation of bias as this +# maintains the column vector form. Dropping this yields very unexpected results. +error = np.mean( np.mean((y_test - y_pred)**2, axis=1, keepdims=True) ) +bias = np.mean( (y_test - np.mean(y_pred, axis=1, keepdims=True))**2 ) +variance = np.mean( np.var(y_pred, axis=1, keepdims=True) ) +print('Error:', error) +print('Bias^2:', bias) +print('Var:', variance) +print('{} >= {} + {} = {}'.format(error, bias, variance, bias+variance)) + +plt.plot(x[::5, :], y[::5, :], label='f(x)') +plt.scatter(x_test, y_test, label='Data points') +plt.scatter(x_test, np.mean(y_pred, axis=1), label='Pred') +plt.legend() +plt.show() + +!ec + + +!split +===== Understanding what happens ===== +!bc pycod +import matplotlib.pyplot as plt +import numpy as np +from sklearn.linear_model import LinearRegression, Ridge, Lasso +from sklearn.preprocessing import PolynomialFeatures +from sklearn.model_selection import train_test_split +from sklearn.pipeline import make_pipeline +from sklearn.utils import resample + +np.random.seed(2018) + +n = 40 +n_boostraps = 100 +maxdegree = 14 + + +# Make data set. +x = np.linspace(-3, 3, n).reshape(-1, 1) +y = np.exp(-x**2) + 1.5 * np.exp(-(x-2)**2)+ np.random.normal(0, 0.1, x.shape) +error = np.zeros(maxdegree) +bias = np.zeros(maxdegree) +variance = np.zeros(maxdegree) +polydegree = np.zeros(maxdegree) +x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.2) + +for degree in range(maxdegree): + model = make_pipeline(PolynomialFeatures(degree=degree), LinearRegression(fit_intercept=False)) + y_pred = np.empty((y_test.shape[0], n_boostraps)) + for i in range(n_boostraps): + x_, y_ = resample(x_train, y_train) + y_pred[:, i] = model.fit(x_, y_).predict(x_test).ravel() + + polydegree[degree] = degree + error[degree] = np.mean( np.mean((y_test - y_pred)**2, axis=1, keepdims=True) ) + bias[degree] = np.mean( (y_test - np.mean(y_pred, axis=1, keepdims=True))**2 ) + variance[degree] = np.mean( np.var(y_pred, axis=1, keepdims=True) ) + print('Polynomial degree:', degree) + print('Error:', error[degree]) + print('Bias^2:', bias[degree]) + print('Var:', variance[degree]) + print('{} >= {} + {} = {}'.format(error[degree], bias[degree], variance[degree], bias[degree]+variance[degree])) + +plt.plot(polydegree, error, label='Error') +plt.plot(polydegree, bias, label='bias') +plt.plot(polydegree, variance, label='Variance') +plt.legend() +plt.show() + + + + +!ec + +!split +===== Summing up ===== + + + + +The bias-variance tradeoff summarizes the fundamental tension in +machine learning, particularly supervised learning, between the +complexity of a model and the amount of training data needed to train +it. Since data is often limited, in practice it is often useful to +use a less-complex model with higher bias, that is a model whose asymptotic +performance is worse than another model because it is easier to +train and less sensitive to sampling noise arising from having a +finite-sized training dataset (smaller variance). + + + +The above equations tell us that in +order to minimize the expected test error, we need to select a +statistical learning method that simultaneously achieves low variance +and low bias. Note that variance is inherently a nonnegative quantity, +and squared bias is also nonnegative. Hence, we see that the expected +test MSE can never lie below $Var(\epsilon)$, the irreducible error. + + +What do we mean by the variance and bias of a statistical learning +method? The variance refers to the amount by which our model would change if we +estimated it using a different training data set. Since the training +data are used to fit the statistical learning method, different +training data sets will result in a different estimate. But ideally the +estimate for our model should not vary too much between training +sets. However, if a method has high variance then small changes in +the training data can result in large changes in the model. In general, more +flexible statistical methods have higher variance. + + +You may also find this recent "article":"https://www.pnas.org/content/116/32/15849" of interest. + +!split +===== Another Example from Scikit-Learn's Repository ===== +!bc pycod +""" +============================ +Underfitting vs. Overfitting +============================ + +This example demonstrates the problems of underfitting and overfitting and +how we can use linear regression with polynomial features to approximate +nonlinear functions. The plot shows the function that we want to approximate, +which is a part of the cosine function. In addition, the samples from the +real function and the approximations of different models are displayed. The +models have polynomial features of different degrees. We can see that a +linear function (polynomial with degree 1) is not sufficient to fit the +training samples. This is called **underfitting**. A polynomial of degree 4 +approximates the true function almost perfectly. However, for higher degrees +the model will **overfit** the training data, i.e. it learns the noise of the +training data. +We evaluate quantitatively **overfitting** / **underfitting** by using +cross-validation. We calculate the mean squared error (MSE) on the validation +set, the higher, the less likely the model generalizes correctly from the +training data. +""" + +print(__doc__) + +import numpy as np +import matplotlib.pyplot as plt +from sklearn.pipeline import Pipeline +from sklearn.preprocessing import PolynomialFeatures +from sklearn.linear_model import LinearRegression +from sklearn.model_selection import cross_val_score + + +def true_fun(X): + return np.cos(1.5 * np.pi * X) + +np.random.seed(0) + +n_samples = 30 +degrees = [1, 4, 15] + +X = np.sort(np.random.rand(n_samples)) +y = true_fun(X) + np.random.randn(n_samples) * 0.1 + +plt.figure(figsize=(14, 5)) +for i in range(len(degrees)): + ax = plt.subplot(1, len(degrees), i + 1) + plt.setp(ax, xticks=(), yticks=()) + + polynomial_features = PolynomialFeatures(degree=degrees[i], + include_bias=False) + linear_regression = LinearRegression() + pipeline = Pipeline([("polynomial_features", polynomial_features), + ("linear_regression", linear_regression)]) + pipeline.fit(X[:, np.newaxis], y) + + # Evaluate the models using crossvalidation + scores = cross_val_score(pipeline, X[:, np.newaxis], y, + scoring="neg_mean_squared_error", cv=10) + + X_test = np.linspace(0, 1, 100) + plt.plot(X_test, pipeline.predict(X_test[:, np.newaxis]), label="Model") + plt.plot(X_test, true_fun(X_test), label="True function") + plt.scatter(X, y, edgecolor='b', s=20, label="Samples") + plt.xlabel("x") + plt.ylabel("y") + plt.xlim((0, 1)) + plt.ylim((-2, 2)) + plt.legend(loc="best") + plt.title("Degree {}\nMSE = {:.2e}(+/- {:.2e})".format( + degrees[i], -scores.mean(), scores.std())) +plt.show() +!ec + + +!split +===== More examples on bootstrap and cross-validation and errors ===== + +!bc pycod +# Common imports +import os +import numpy as np +import pandas as pd +import matplotlib.pyplot as plt +from sklearn.linear_model import LinearRegression, Ridge, Lasso +from sklearn.model_selection import train_test_split +from sklearn.utils import resample +from sklearn.metrics import mean_squared_error +# Where to save the figures and data files +PROJECT_ROOT_DIR = "Results" +FIGURE_ID = "Results/FigureFiles" +DATA_ID = "DataFiles/" + +if not os.path.exists(PROJECT_ROOT_DIR): + os.mkdir(PROJECT_ROOT_DIR) + +if not os.path.exists(FIGURE_ID): + os.makedirs(FIGURE_ID) + +if not os.path.exists(DATA_ID): + os.makedirs(DATA_ID) + +def image_path(fig_id): + return os.path.join(FIGURE_ID, fig_id) + +def data_path(dat_id): + return os.path.join(DATA_ID, dat_id) + +def save_fig(fig_id): + plt.savefig(image_path(fig_id) + ".png", format='png') + +infile = open(data_path("EoS.csv"),'r') + +# Read the EoS data as csv file and organize the data into two arrays with density and energies +EoS = pd.read_csv(infile, names=('Density', 'Energy')) +EoS['Energy'] = pd.to_numeric(EoS['Energy'], errors='coerce') +EoS = EoS.dropna() +Energies = EoS['Energy'] +Density = EoS['Density'] +# The design matrix now as function of various polytrops + +Maxpolydegree = 30 +X = np.zeros((len(Density),Maxpolydegree)) +X[:,0] = 1.0 +testerror = np.zeros(Maxpolydegree) +trainingerror = np.zeros(Maxpolydegree) +polynomial = np.zeros(Maxpolydegree) + +trials = 100 +for polydegree in range(1, Maxpolydegree): + polynomial[polydegree] = polydegree + for degree in range(polydegree): + X[:,degree] = Density**(degree/3.0) + +# loop over trials in order to estimate the expectation value of the MSE + testerror[polydegree] = 0.0 + trainingerror[polydegree] = 0.0 + for samples in range(trials): + x_train, x_test, y_train, y_test = train_test_split(X, Energies, test_size=0.2) + model = LinearRegression(fit_intercept=True).fit(x_train, y_train) + ypred = model.predict(x_train) + ytilde = model.predict(x_test) + testerror[polydegree] += mean_squared_error(y_test, ytilde) + trainingerror[polydegree] += mean_squared_error(y_train, ypred) + + testerror[polydegree] /= trials + trainingerror[polydegree] /= trials + print("Degree of polynomial: %3d"% polynomial[polydegree]) + print("Mean squared error on training data: %.8f" % trainingerror[polydegree]) + print("Mean squared error on test data: %.8f" % testerror[polydegree]) + +plt.plot(polynomial, np.log10(trainingerror), label='Training Error') +plt.plot(polynomial, np.log10(testerror), label='Test Error') +plt.xlabel('Polynomial degree') +plt.ylabel('log10[MSE]') +plt.legend() +plt.show() + +!ec + + +!split +===== The same example but now with cross-validation ===== + +!bc pycod +# Common imports +import os +import numpy as np +import pandas as pd +import matplotlib.pyplot as plt +from sklearn.linear_model import LinearRegression, Ridge, Lasso +from sklearn.metrics import mean_squared_error +from sklearn.model_selection import KFold +from sklearn.model_selection import cross_val_score + + +# Where to save the figures and data files +PROJECT_ROOT_DIR = "Results" +FIGURE_ID = "Results/FigureFiles" +DATA_ID = "DataFiles/" + +if not os.path.exists(PROJECT_ROOT_DIR): + os.mkdir(PROJECT_ROOT_DIR) + +if not os.path.exists(FIGURE_ID): + os.makedirs(FIGURE_ID) + +if not os.path.exists(DATA_ID): + os.makedirs(DATA_ID) + +def image_path(fig_id): + return os.path.join(FIGURE_ID, fig_id) + +def data_path(dat_id): + return os.path.join(DATA_ID, dat_id) + +def save_fig(fig_id): + plt.savefig(image_path(fig_id) + ".png", format='png') + +infile = open(data_path("EoS.csv"),'r') + +# Read the EoS data as csv file and organize the data into two arrays with density and energies +EoS = pd.read_csv(infile, names=('Density', 'Energy')) +EoS['Energy'] = pd.to_numeric(EoS['Energy'], errors='coerce') +EoS = EoS.dropna() +Energies = EoS['Energy'] +Density = EoS['Density'] +# The design matrix now as function of various polytrops + +Maxpolydegree = 30 +X = np.zeros((len(Density),Maxpolydegree)) +X[:,0] = 1.0 +estimated_mse_sklearn = np.zeros(Maxpolydegree) +polynomial = np.zeros(Maxpolydegree) +k =5 +kfold = KFold(n_splits = k) + +for polydegree in range(1, Maxpolydegree): + polynomial[polydegree] = polydegree + for degree in range(polydegree): + X[:,degree] = Density**(degree/3.0) + OLS = LinearRegression() +# loop over trials in order to estimate the expectation value of the MSE + estimated_mse_folds = cross_val_score(OLS, X, Energies, scoring='neg_mean_squared_error', cv=kfold) +#[:, np.newaxis] + estimated_mse_sklearn[polydegree] = np.mean(-estimated_mse_folds) + +plt.plot(polynomial, np.log10(estimated_mse_sklearn), label='Test Error') +plt.xlabel('Polynomial degree') +plt.ylabel('log10[MSE]') +plt.legend() +plt.show() + +!ec + +!split +===== Cross-validation with Ridge ===== +!bc pycod +import numpy as np +import matplotlib.pyplot as plt +from sklearn.model_selection import KFold +from sklearn.linear_model import Ridge +from sklearn.model_selection import cross_val_score +from sklearn.preprocessing import PolynomialFeatures + +# A seed just to ensure that the random numbers are the same for every run. +np.random.seed(3155) +# Generate the data. +n = 100 +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) +# Decide degree on polynomial to fit +poly = PolynomialFeatures(degree = 10) + +# Decide which values of lambda to use +nlambdas = 500 +lambdas = np.logspace(-3, 5, nlambdas) +# Initialize a KFold instance +k = 5 +kfold = KFold(n_splits = k) +estimated_mse_sklearn = np.zeros(nlambdas) +i = 0 +for lmb in lambdas: + ridge = Ridge(alpha = lmb) + estimated_mse_folds = cross_val_score(ridge, x, y, scoring='neg_mean_squared_error', cv=kfold) + estimated_mse_sklearn[i] = np.mean(-estimated_mse_folds) + i += 1 +plt.figure() +plt.plot(np.log10(lambdas), estimated_mse_sklearn, label = 'cross_val_score') +plt.xlabel('log10(lambda)') +plt.ylabel('MSE') +plt.legend() +plt.show() + + +!ec + + + + + + diff --git a/doc/src/week37/clean.sh b/doc/src/week37/clean.sh new file mode 100755 index 000000000..2e5da2c72 --- /dev/null +++ b/doc/src/week37/clean.sh @@ -0,0 +1,3 @@ +#!/bin/sh +doconce clean +rm -rf *.pdf *.tex ipynb*.tar.gz *.html ._*.html *~ reveal.js Trash README.txt diff --git a/doc/src/week37/make.sh b/doc/src/week37/make.sh new file mode 100755 index 000000000..4722a0918 --- /dev/null +++ b/doc/src/week37/make.sh @@ -0,0 +1,79 @@ +#!/bin/sh +set -x + +function system { + "$@" + if [ $? -ne 0 ]; then + echo "make.sh: unsuccessful command $@" + echo "abort!" + exit 1 + fi +} + +if [ $# -eq 0 ]; then +echo 'bash make.sh slides1|slides2' +exit 1 +fi + +name=$1 +rm -f *.tar.gz + +opt="--encoding=utf-8" +# Note: Makefile examples contain constructions like ${PROG} which +# looks like Mako constructions, but they are not. Use --no_mako +# to turn off Mako processing. +opt="--no_mako" + +rm -f *.aux + + +html=${name}-reveal +system doconce format html $name --pygments_html_style=perldoc --keep_pygments_html_bg --html_links_in_new_window --html_output=$html $opt +system doconce slides_html $html reveal --html_slide_theme=beige + +# Plain HTML documents + +html=${name}-solarized +system doconce format html $name --pygments_html_style=perldoc --html_style=solarized3 --html_links_in_new_window --html_output=$html $opt +system doconce split_html $html.html --method=space10 + +html=${name} +system doconce format html $name --pygments_html_style=default --html_style=bloodish --html_links_in_new_window --html_output=$html $opt +system doconce split_html $html.html --method=space10 + +# Bootstrap style +html=${name}-bs +system doconce format html $name --html_style=bootstrap --pygments_html_style=default --html_admon=bootstrap_panel --html_output=$html $opt +system doconce split_html $html.html --method=split --pagination --nav_button=bottom + +# IPython notebook +system doconce format ipynb $name $opt + + +# Publish +dest=../../pub +if [ ! -d $dest/$name ]; then +mkdir $dest/$name +mkdir $dest/$name/html +mkdir $dest/$name/ipynb +fi +cp -r ${name}*.html ._${name}*.html reveal.js $dest/$name/html + +# Figures: cannot just copy link, need to physically copy the files +if [ -d fig-${name} ]; then +if [ ! -d $dest/$name/html/fig-$name ]; then +mkdir $dest/$name/html/fig-$name +fi +cp -r fig-${name}/* $dest/$name/html/fig-$name +fi + +cp ${name}.ipynb $dest/$name/ipynb +ipynb_tarfile=ipynb-${name}-src.tar.gz +if [ ! -f ${ipynb_tarfile} ]; then +cat > README.txt < p$. In our regression examples for the nuclear +masses and the equation of state this is indeed the case, while for +the Ising model we have $p > n$. These are often cases that lead to +near singular or singular matrices. + +The columns of $\bm{U}$ are called the left singular vectors while the columns of $\bm{V}$ are the right singular vectors. + +!split +===== Economy-size SVD ===== + +If we assume that $n > p$, then our matrix $\bm{U}$ has dimension $n +\times n$. The last $n-p$ columns of $\bm{U}$ become however +irrelevant in our calculations since they are multiplied with the +zeros in $\bm{\Sigma}$. + +The economy-size decomposition removes extra rows or columns of zeros +from the diagonal matrix of singular values, $\bm{\Sigma}$, along with the columns +in either $\bm{U}$ or $\bm{V}$ that multiply those zeros in the expression. +Removing these zeros and columns can improve execution time +and reduce storage requirements without compromising the accuracy of +the decomposition. + +If $n > p$, we keep only the first $p$ columns of $\bm{U}$ and $\bm{\Sigma}$ has dimension $p\times p$. +If $p > n$, then only the first $n$ columns of $\bm{V}$ are computed and $\bm{\Sigma}$ has dimension $n\times n$. +The $n=p$ case is obvious, we retain the full SVD. +In general the economy-size SVD leads to less FLOPS and still conserving the desired accuracy. + +!split +===== Codes for the SVD ===== + +!bc pycod +import numpy as np +# SVD inversion +def SVDinv(A): + ''' Takes as input a numpy matrix A and returns inv(A) based on singular value decomposition (SVD). + SVD is numerically more stable than the inversion algorithms provided by + numpy and scipy.linalg at the cost of being slower. + ''' + U, s, VT = np.linalg.svd(A) +# print('test U') +# print( (np.transpose(U) @ U - U @np.transpose(U))) +# print('test VT') +# print( (np.transpose(VT) @ VT - VT @np.transpose(VT))) + print(U) + print(s) + print(VT) + + D = np.zeros((len(U),len(VT))) + for i in range(0,len(VT)): + D[i,i]=s[i] + UT = np.transpose(U); V = np.transpose(VT); invD = np.linalg.inv(D) + return np.matmul(V,np.matmul(invD,UT)) + + +X = np.array([ [1.0, -1.0, 2.0], [1.0, 0.0, 1.0], [1.0, 2.0, -1.0], [1.0, 1.0, 0.0] ]) +print(X) +A = np.transpose(X) @ X +print(A) +# Brute force inversion of super-collinear matrix +#B = np.linalg.inv(A) +#print(B) +C = SVDinv(A) +print(C) + +!ec + +The matrix $\bm{X}$ has columns that are linearly dependent. The first +column is the row-wise sum of the other two columns. The rank of a +matrix (the column rank) is the dimension of space spanned by the +column vectors. The rank of the matrix is the number of linearly +independent columns, in this case just $2$. We see this from the +singular values when running the above code. Running the standard +inversion algorithm for matrix inversion with $\bm{X}^T\bm{X}$ results +in the program terminating due to a singular matrix. + + + +!split +===== Mathematical Properties ===== + +There are several interesting mathematical properties which will be +relevant when we are going to discuss the differences between say +ordinary least squares (OLS) and _Ridge_ regression. + +We have from OLS that the parameters of the linear approximation are given by +!bt +\[ +\bm{\tilde{y}} = \bm{X}\bm{\beta} = \bm{X}\left(\bm{X}^T\bm{X}\right)^{-1}\bm{X}^T\bm{y}. +\] +!et + +The matrix to invert can be rewritten in terms of our SVD decomposition as + +!bt +\[ +\bm{X}^T\bm{X} = \bm{V}\bm{\Sigma}^T\bm{U}^T\bm{U}\bm{\Sigma}\bm{V}^T. +\] +!et +Using the orthogonality properties of $\bm{U}$ we have + +!bt +\[ +\bm{X}^T\bm{X} = \bm{V}\bm{\Sigma}^T\bm{\Sigma}\bm{V}^T = \bm{V}\bm{D}\bm{V}^T, +\] +!et +with $\bm{D}$ being a diagonal matrix with values along the diagonal given by the singular values squared. + +This means that +!bt +\[ +(\bm{X}^T\bm{X})\bm{V} = \bm{V}\bm{D}, +\] +!et +that is the eigenvectors of $(\bm{X}^T\bm{X})$ are given by the columns of the right singular matrix of $\bm{X}$ and the eigenvalues are the squared singular values. It is easy to show (show this) that +!bt +\[ +(\bm{X}\bm{X}^T)\bm{U} = \bm{U}\bm{D}, +\] +!et +that is, the eigenvectors of $(\bm{X}\bm{X})^T$ are the columns of the left singular matrix and the eigenvalues are the same. + +Going back to our OLS equation we have +!bt +\[ +\bm{X}\bm{\beta} = \bm{X}\left(\bm{V}\bm{D}\bm{V}^T \right)^{-1}\bm{X}^T\bm{y}=\bm{U\Sigma V^T}\left(\bm{V}\bm{D}\bm{V}^T \right)^{-1}(\bm{U\Sigma V^T})^T\bm{y}=\bm{U}\bm{U}^T\bm{y}. +\] +!et +We will come back to this expression when we discuss Ridge regression. + + +$$ \tilde{y}^{OLS}={\bf X}\hat{\beta}^{OLS}=\sum_{j=1}^p {\bf u}_j{\bf u}_j^T{\bf y}$$ and for Ridge we have  + +$$ \tilde{y}^{Ridge}={\bf X}\hat{\beta}^{Ridge}=\sum_{j=1}^p {\bf u}_j\frac{\sigma_j^2}{\sigma_j^2+\lambda}{\bf u}_j^T{\bf y}$$ .  + +It is indeed the economy-sized SVD, note the summation runs up tp $$p$$ only and not $$n$$.  + +Here we have that $${\bf X} = {\bf U}{\bf \Sigma}{\bf V}^T$$, with $$\Sigma$$ being an $$ n\times p$$ matrix and $${\bf V}$$ being a $$ p\times p$$ matrix. We also have assumed here that $$ n > p$$.  + + +!split +===== Ridge and LASSO Regression ===== + +Let us remind ourselves about the expression for the standard Mean Squared Error (MSE) which we used to define our cost function and the equations for the ordinary least squares (OLS) method, that is +our optimization problem is +!bt +\[ +{\displaystyle \min_{\bm{\beta}\in {\mathbb{R}}^{p}}}\frac{1}{n}\left\{\left(\bm{y}-\bm{X}\bm{\beta}\right)^T\left(\bm{y}-\bm{X}\bm{\beta}\right)\right\}. +\] +!et +or we can state it as +!bt +\[ +{\displaystyle \min_{\bm{\beta}\in +{\mathbb{R}}^{p}}}\frac{1}{n}\sum_{i=0}^{n-1}\left(y_i-\tilde{y}_i\right)^2=\frac{1}{n}\vert\vert \bm{y}-\bm{X}\bm{\beta}\vert\vert_2^2, +\] +!et +where we have used the definition of a norm-2 vector, that is +!bt +\[ +\vert\vert \bm{x}\vert\vert_2 = \sqrt{\sum_i x_i^2}. +\] +!et + +By minimizing the above equation with respect to the parameters +$\bm{\beta}$ we could then obtain an analytical expression for the +parameters $\bm{\beta}$. We can add a regularization parameter $\lambda$ by +defining a new cost function to be optimized, that is + +!bt +\[ +{\displaystyle \min_{\bm{\beta}\in +{\mathbb{R}}^{p}}}\frac{1}{n}\vert\vert \bm{y}-\bm{X}\bm{\beta}\vert\vert_2^2+\lambda\vert\vert \bm{\beta}\vert\vert_2^2 +\] +!et + +which leads to the Ridge regression minimization problem where we +require that $\vert\vert \bm{\beta}\vert\vert_2^2\le t$, where $t$ is +a finite number larger than zero. By defining + +!bt +\[ +C(\bm{X},\bm{\beta})=\frac{1}{n}\vert\vert \bm{y}-\bm{X}\bm{\beta}\vert\vert_2^2+\lambda\vert\vert \bm{\beta}\vert\vert_1, +\] +!et + +we have a new optimization equation +!bt +\[ +{\displaystyle \min_{\bm{\beta}\in +{\mathbb{R}}^{p}}}\frac{1}{n}\vert\vert \bm{y}-\bm{X}\bm{\beta}\vert\vert_2^2+\lambda\vert\vert \bm{\beta}\vert\vert_1 +\] +!et +which leads to Lasso regression. Lasso stands for least absolute shrinkage and selection operator. + +Here we have defined the norm-1 as +!bt +\[ +\vert\vert \bm{x}\vert\vert_1 = \sum_i \vert x_i\vert. +\] +!et + + +!split +===== More on Ridge Regression ===== + +Using the matrix-vector expression for Ridge regression, + +!bt +\[ +C(\bm{X},\bm{\beta})=\frac{1}{n}\left\{(\bm{y}-\bm{X}\bm{\beta})^T(\bm{y}-\bm{X}\bm{\beta})\right\}+\lambda\bm{\beta}^T\bm{\beta}, +\] +!et + +by taking the derivatives with respect to $\bm{\beta}$ we obtain then +a slightly modified matrix inversion problem which for finite values +of $\lambda$ does not suffer from singularity problems. We obtain + +!bt +\[ +\bm{\beta}^{\mathrm{Ridge}} = \left(\bm{X}^T\bm{X}+\lambda\bm{I}\right)^{-1}\bm{X}^T\bm{y}, +\] +!et + +with $\bm{I}$ being a $p\times p$ identity matrix with the constraint that + +!bt +\[ +\sum_{i=0}^{p-1} \beta_i^2 \leq t, +\] +!et + +with $t$ a finite positive number. + +We see that Ridge regression is nothing but the standard +OLS with a modified diagonal term added to $\bm{X}^T\bm{X}$. The +consequences, in particular for our discussion of the bias-variance tradeoff +are rather interesting. + +Furthermore, if we use the result above in terms of the SVD decomposition (our analysis was done for the OLS method), we had +!bt +\[ +(\bm{X}\bm{X}^T)\bm{U} = \bm{U}\bm{D}. +\] +!et + +We can analyse the OLS solutions in terms of the eigenvectors (the columns) of the right singular value matrix $\bm{U}$ as +!bt +\[ +\bm{X}\bm{\beta} = \bm{X}\left(\bm{V}\bm{D}\bm{V}^T \right)^{-1}\bm{X}^T\bm{y}=\bm{U\Sigma V^T}\left(\bm{V}\bm{D}\bm{V}^T \right)^{-1}(\bm{U\Sigma V^T})^T\bm{y}=\bm{U}\bm{U}^T\bm{y} +\] +!et + + +For Ridge regression this becomes + +!bt +\[ +\bm{X}\bm{\beta}^{\mathrm{Ridge}} = \bm{U\Sigma V^T}\left(\bm{V}\bm{D}\bm{V}^T+\lambda\bm{I} \right)^{-1}(\bm{U\Sigma V^T})^T\bm{y}=\sum_{j=0}^{p-1}\bm{u}_j\bm{u}_j^T\frac{\sigma_j^2}{\sigma_j^2+\lambda}\bm{y}, +\] +!et + +with the vectors $\bm{u}_j$ being the columns of $\bm{U}$. + +!split +===== Interpreting the Ridge results ===== + +Since $\lambda \geq 0$, it means that compared to OLS, we have + +!bt +\[ +\frac{\sigma_j^2}{\sigma_j^2+\lambda} \leq 1. +\] +!et + +Ridge regression finds the coordinates of $\bm{y}$ with respect to the +orthonormal basis $\bm{U}$, it then shrinks the coordinates by +$\frac{\sigma_j^2}{\sigma_j^2+\lambda}$. Recall that the SVD has +eigenvalues ordered in a descending way, that is $\sigma_i \geq +\sigma_{i+1}$. + +For small eigenvalues $\sigma_i$ it means that their contributions become less important, a fact which can be used to reduce the number of degrees of freedom. +Actually, calculating the variance of $\bm{X}\bm{v}_j$ shows that this quantity is equal to $\sigma_j^2/n$. +With a parameter $\lambda$ we can thus shrink the role of specific parameters. + + +!split +===== More interpretations ===== + +For the sake of simplicity, let us assume that the design matrix is orthonormal, that is + +!bt +\[ +\bm{X}^T\bm{X}=(\bm{X}^T\bm{X})^{-1} =\bm{I}. +\] +!et + +In this case the standard OLS results in +!bt +\[ +\bm{\beta}^{\mathrm{OLS}} = \bm{X}^T\bm{y}=\sum_{i=0}^{p-1}\bm{u}_j\bm{u}_j^T\bm{y}, +\] +!et + +and + +!bt +\[ +\bm{\beta}^{\mathrm{Ridge}} = \left(\bm{I}+\lambda\bm{I}\right)^{-1}\bm{X}^T\bm{y}=\left(1+\lambda\right)^{-1}\bm{\beta}^{\mathrm{OLS}}, +\] +!et + +that is the Ridge estimator scales the OLS estimator by the inverse of a factor $1+\lambda$, and +the Ridge estimator converges to zero when the hyperparameter goes to +infinity. + +We will come back to more interpreations after we have gone through some of the statistical analysis part. + +For more discussions of Ridge and Lasso regression, "Wessel van Wieringen's":"https://arxiv.org/abs/1509.09169" article is highly recommended. +Similarly, "Mehta et al's article":"https://arxiv.org/abs/1803.08823" is also recommended. + + +!split +===== A better understanding of regularization ===== + +The parameter $\lambda$ that we have introduced in the Ridge (and +Lasso as well) regression is often called a regularization parameter +or shrinkage parameter. It is common to call it a hyperparameter. What does it mean mathemtically? + +Here we will first look at how to analyze the difference between the +standard OLS equations and the Ridge expressions in terms of a linear +algebra analysis using the SVD algorithm. Thereafter, we will link +(see the material on the bias-variance tradeoff below) these +observation to the statisical analysis of the results. In particular +we consider how the variance of the parameters $\bm{\beta}$ is +affected by changing the parameter $\lambda$. + +!split +===== Decomposing the OLS and Ridge expressions ===== + +We have our design matrix + $\bm{X}\in {\mathbb{R}}^{n\times p}$. With the SVD we decompose it as + +!bt +\[ +\bm{X} = \bm{U\Sigma V^T}, +\] +!et + +with $\bm{U}\in {\mathbb{R}}^{n\times n}$, $\bm{\Sigma}\in {\mathbb{R}}^{n\times p}$ +and $\bm{V}\in {\mathbb{R}}^{p\times p}$. + +The matrices $\bm{U}$ and $\bm{V}$ are unitary/orthonormal matrices, that is in case the matrices are real we have $\bm{U}^T\bm{U}=\bm{U}\bm{U}^T=\bm{I}$ and $\bm{V}^T\bm{V}=\bm{V}\bm{V}^T=\bm{I}$. + + + +!split +===== Introducing the Covariance and Correlation functions ===== + +Before we discuss the link between for example Ridge regression and the singular value decomposition, we need to remind ourselves about +the definition of the covariance and the correlation function. These are quantities + +Suppose we have defined two vectors +$\hat{x}$ and $\hat{y}$ with $n$ elements each. The covariance matrix $\bm{C}$ is defined as +!bt +\[ +\bm{C}[\bm{x},\bm{y}] = \begin{bmatrix} \mathrm{cov}[\bm{x},\bm{x}] & \mathrm{cov}[\bm{x},\bm{y}] \\ + \mathrm{cov}[\bm{y},\bm{x}] & \mathrm{cov}[\bm{y},\bm{y}] \\ + \end{bmatrix}, +\] +!et +where for example +!bt +\[ +\mathrm{cov}[\bm{x},\bm{y}] =\frac{1}{n} \sum_{i=0}^{n-1}(x_i- \overline{x})(y_i- \overline{y}). +\] +!et +With this definition and recalling that the variance is defined as +!bt +\[ +\mathrm{var}[\bm{x}]=\frac{1}{n} \sum_{i=0}^{n-1}(x_i- \overline{x})^2, +\] +!et +we can rewrite the covariance matrix as +!bt +\[ +\bm{C}[\bm{x},\bm{y}] = \begin{bmatrix} \mathrm{var}[\bm{x}] & \mathrm{cov}[\bm{x},\bm{y}] \\ + \mathrm{cov}[\bm{x},\bm{y}] & \mathrm{var}[\bm{y}] \\ + \end{bmatrix}. +\] +!et + +The covariance takes values between zero and infinity and may thus +lead to problems with loss of numerical precision for particularly +large values. It is common to scale the covariance matrix by +introducing instead the correlation matrix defined via the so-called +correlation function + +!bt +\[ +\mathrm{corr}[\bm{x},\bm{y}]=\frac{\mathrm{cov}[\bm{x},\bm{y}]}{\sqrt{\mathrm{var}[\bm{x}] \mathrm{var}[\bm{y}]}}. +\] +!et + +The correlation function is then given by values $\mathrm{corr}[\bm{x},\bm{y}] +\in [-1,1]$. This avoids eventual problems with too large values. We +can then define the correlation matrix for the two vectors $\bm{x}$ +and $\bm{y}$ as + +!bt +\[ +\bm{K}[\bm{x},\bm{y}] = \begin{bmatrix} 1 & \mathrm{corr}[\bm{x},\bm{y}] \\ + \mathrm{corr}[\bm{y},\bm{x}] & 1 \\ + \end{bmatrix}, +\] +!et + +In the above example this is the function we constructed using _pandas_. + +!split +===== Correlation Function and Design/Feature Matrix ===== + +In our derivation of the various regression algorithms like _Ordinary Least Squares_ or _Ridge regression_ +we defined the design/feature matrix $\bm{X}$ as + +!bt +\[ +\bm{X}=\begin{bmatrix} +x_{0,0} & x_{0,1} & x_{0,2}& \dots & \dots x_{0,p-1}\\ +x_{1,0} & x_{1,1} & x_{1,2}& \dots & \dots x_{1,p-1}\\ +x_{2,0} & x_{2,1} & x_{2,2}& \dots & \dots x_{2,p-1}\\ +\dots & \dots & \dots & \dots \dots & \dots \\ +x_{n-2,0} & x_{n-2,1} & x_{n-2,2}& \dots & \dots x_{n-2,p-1}\\ +x_{n-1,0} & x_{n-1,1} & x_{n-1,2}& \dots & \dots x_{n-1,p-1}\\ +\end{bmatrix}, +\] +!et +with $\bm{X}\in {\mathbb{R}}^{n\times p}$, with the predictors/features $p$ refering to the column numbers and the +entries $n$ being the row elements. +We can rewrite the design/feature matrix in terms of its column vectors as +!bt +\[ +\bm{X}=\begin{bmatrix} \bm{x}_0 & \bm{x}_1 & \bm{x}_2 & \dots & \dots & \bm{x}_{p-1}\end{bmatrix}, +\] +!et +with a given vector +!bt +\[ +\bm{x}_i^T = \begin{bmatrix}x_{0,i} & x_{1,i} & x_{2,i}& \dots & \dots x_{n-1,i}\end{bmatrix}. +\] +!et + +With these definitions, we can now rewrite our $2\times 2$ +correaltion/covariance matrix in terms of a moe general design/feature +matrix $\bm{X}\in {\mathbb{R}}^{n\times p}$. This leads to a $p\times p$ +covariance matrix for the vectors $\bm{x}_i$ with $i=0,1,\dots,p-1$ + +!bt +\[ +\bm{C}[\bm{x}] = \begin{bmatrix} +\mathrm{var}[\bm{x}_0] & \mathrm{cov}[\bm{x}_0,\bm{x}_1] & \mathrm{cov}[\bm{x}_0,\bm{x}_2] & \dots & \dots & \mathrm{cov}[\bm{x}_0,\bm{x}_{p-1}]\\ +\mathrm{cov}[\bm{x}_1,\bm{x}_0] & \mathrm{var}[\bm{x}_1] & \mathrm{cov}[\bm{x}_1,\bm{x}_2] & \dots & \dots & \mathrm{cov}[\bm{x}_1,\bm{x}_{p-1}]\\ +\mathrm{cov}[\bm{x}_2,\bm{x}_0] & \mathrm{cov}[\bm{x}_2,\bm{x}_1] & \mathrm{var}[\bm{x}_2] & \dots & \dots & \mathrm{cov}[\bm{x}_2,\bm{x}_{p-1}]\\ +\dots & \dots & \dots & \dots & \dots & \dots \\ +\dots & \dots & \dots & \dots & \dots & \dots \\ +\mathrm{cov}[\bm{x}_{p-1},\bm{x}_0] & \mathrm{cov}[\bm{x}_{p-1},\bm{x}_1] & \mathrm{cov}[\bm{x}_{p-1},\bm{x}_{2}] & \dots & \dots & \mathrm{var}[\bm{x}_{p-1}]\\ +\end{bmatrix}, +\] +!et +and the correlation matrix +!bt +\[ +\bm{K}[\bm{x}] = \begin{bmatrix} +1 & \mathrm{corr}[\bm{x}_0,\bm{x}_1] & \mathrm{corr}[\bm{x}_0,\bm{x}_2] & \dots & \dots & \mathrm{corr}[\bm{x}_0,\bm{x}_{p-1}]\\ +\mathrm{corr}[\bm{x}_1,\bm{x}_0] & 1 & \mathrm{corr}[\bm{x}_1,\bm{x}_2] & \dots & \dots & \mathrm{corr}[\bm{x}_1,\bm{x}_{p-1}]\\ +\mathrm{corr}[\bm{x}_2,\bm{x}_0] & \mathrm{corr}[\bm{x}_2,\bm{x}_1] & 1 & \dots & \dots & \mathrm{corr}[\bm{x}_2,\bm{x}_{p-1}]\\ +\dots & \dots & \dots & \dots & \dots & \dots \\ +\dots & \dots & \dots & \dots & \dots & \dots \\ +\mathrm{corr}[\bm{x}_{p-1},\bm{x}_0] & \mathrm{corr}[\bm{x}_{p-1},\bm{x}_1] & \mathrm{corr}[\bm{x}_{p-1},\bm{x}_{2}] & \dots & \dots & 1\\ +\end{bmatrix}, +\] +!et + + +!split +===== Covariance Matrix Examples ===== + + +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 $2\times n$ matrix $\bm{W}$ + + +!bt +\[ +\bm{W} = \begin{bmatrix} x_0 & y_0 \\ + x_1 & y_1 \\ + x_2 & y_2\\ + \dots & \dots \\ + x_{n-2} & y_{n-2}\\ + x_{n-1} & y_{n-1} & + \end{bmatrix}, +\] +!et + +which in turn is converted into into the $2\times 2$ covariance matrix +$\bm{C}$ via the Numpy function _np.cov()_. We note that we can also calculate +the mean value of each set of samples $\bm{x}$ etc using the Numpy +function _np.mean(x)_. We can also extract the eigenvalues of the +covariance matrix through the _np.linalg.eig()_ function. + +!bc pycod +# Importing various packages +import numpy as np +n = 100 +x = np.random.normal(size=n) +print(np.mean(x)) +y = 4+3*x+np.random.normal(size=n) +print(np.mean(y)) +W = np.vstack((x, y)) +C = np.cov(W) +print(C) +!ec + +!split +===== Correlation Matrix ===== + +The previous example can be converted into the correlation matrix by +simply scaling the matrix elements with the variances. We should also +subtract the mean values for each column. This leads to the following +code which sets up the correlations matrix for the previous example in +a more brute force way. Here we scale the mean values for each column of the design matrix, calculate the relevant mean values and variances and then finally set up the $2\times 2$ correlation matrix (since we have only two vectors). + +!bc pycod +import numpy as np +n = 100 +# define two vectors +x = np.random.random(size=n) +y = 4+3*x+np.random.normal(size=n) +#scaling the x and y vectors +x = x - np.mean(x) +y = y - np.mean(y) +variance_x = np.sum(x@x)/n +variance_y = np.sum(y@y)/n +print(variance_x) +print(variance_y) +cov_xy = np.sum(x@y)/n +cov_xx = np.sum(x@x)/n +cov_yy = np.sum(y@y)/n +C = np.zeros((2,2)) +C[0,0]= cov_xx/variance_x +C[1,1]= cov_yy/variance_y +C[0,1]= cov_xy/np.sqrt(variance_y*variance_x) +C[1,0]= C[0,1] +print(C) +!ec + +We see that the matrix elements along the diagonal are one as they +should be and that the matrix is symmetric. Furthermore, diagonalizing +this matrix we easily see that it is a positive definite matrix. + +The above procedure with _numpy_ can be made more compact if we use _pandas_. + +!split +===== Correlation Matrix with Pandas ===== + +We whow here how we can set up the correlation matrix using _pandas_, as done in this simple code +!bc pycod +import numpy as np +import pandas as pd +n = 10 +x = np.random.normal(size=n) +x = x - np.mean(x) +y = 4+3*x+np.random.normal(size=n) +y = y - np.mean(y) +X = (np.vstack((x, y))).T +print(X) +Xpd = pd.DataFrame(X) +print(Xpd) +correlation_matrix = Xpd.corr() +print(correlation_matrix) +!ec + + +We expand this model to the Franke function discussed above. + +!split +===== Correlation Matrix with Pandas and the Franke function ===== + +!bc pycod +# Common imports +import numpy as np +import pandas as pd + + +def FrankeFunction(x,y): + term1 = 0.75*np.exp(-(0.25*(9*x-2)**2) - 0.25*((9*y-2)**2)) + term2 = 0.75*np.exp(-((9*x+1)**2)/49.0 - 0.1*(9*y+1)) + term3 = 0.5*np.exp(-(9*x-7)**2/4.0 - 0.25*((9*y-3)**2)) + term4 = -0.2*np.exp(-(9*x-4)**2 - (9*y-7)**2) + return term1 + term2 + term3 + term4 + + +def create_X(x, y, n ): + if len(x.shape) > 1: + x = np.ravel(x) + y = np.ravel(y) + + N = len(x) + l = int((n+1)*(n+2)/2) # Number of elements in beta + X = np.ones((N,l)) + + for i in range(1,n+1): + q = int((i)*(i+1)/2) + for k in range(i+1): + X[:,q+k] = (x**(i-k))*(y**k) + + return X + + +# Making meshgrid of datapoints and compute Franke's function +n = 4 +N = 100 +x = np.sort(np.random.uniform(0, 1, N)) +y = np.sort(np.random.uniform(0, 1, N)) +z = FrankeFunction(x, y) +X = create_X(x, y, n=n) + +Xpd = pd.DataFrame(X) +# subtract the mean values and set up the covariance matrix +Xpd = Xpd - Xpd.mean() +covariance_matrix = Xpd.cov() +print(covariance_matrix) +!ec + +We note here that the covariance is zero for the first rows and +columns since all matrix elements in the design matrix were set to one +(we are fitting the function in terms of a polynomial of degree $n$). + +This means that the variance for these elements will be zero and will +cause problems when we set up the correlation matrix. We can simply +drop these elements and construct a correlation +matrix without these elements. + + +!split +===== Rewriting the Covariance and/or Correlation Matrix ===== + +We can rewrite the covariance matrix in a more compact form in terms of the design/feature matrix $\bm{X}$ as +!bt +\[ +\bm{C}[\bm{x}] = \frac{1}{n}\bm{X}^T\bm{X}= \mathbb{E}[\bm{X}^T\bm{X}]. +\] +!et + +To see this let us simply look at a design matrix $\bm{X}\in {\mathbb{R}}^{2\times 2}$ +!bt +\[ +\bm{X}=\begin{bmatrix} +x_{00} & x_{01}\\ +x_{10} & x_{11}\\ +\end{bmatrix}=\begin{bmatrix} +\bm{x}_{0} & \bm{x}_{1}\\ +\end{bmatrix}. +\] +!et + +If we then compute the expectation value +!bt +\[ +\mathbb{E}[\bm{X}^T\bm{X}] = \frac{1}{n}\bm{X}^T\bm{X}=\begin{bmatrix} +x_{00}^2+x_{01}^2 & x_{00}x_{10}+x_{01}x_{11}\\ +x_{10}x_{00}+x_{11}x_{01} & x_{10}^2+x_{11}^2\\ +\end{bmatrix}, +\] +!et +which is just +!bt +\[ +\bm{C}[\bm{x}_0,\bm{x}_1] = \bm{C}[\bm{x}]=\begin{bmatrix} \mathrm{var}[\bm{x}_0] & \mathrm{cov}[\bm{x}_0,\bm{x}_1] \\ + \mathrm{cov}[\bm{x}_1,\bm{x}_0] & \mathrm{var}[\bm{x}_1] \\ + \end{bmatrix}, +\] +!et +where we wrote $$\bm{C}[\bm{x}_0,\bm{x}_1] = \bm{C}[\bm{x}]$$ to indicate that this the covariance of the vectors $\bm{x}$ of the design/feature matrix $\bm{X}$. + +It is easy to generalize this to a matrix $\bm{X}\in {\mathbb{R}}^{n\times p}$. + + +!split +===== Linking with SVD ===== + diff --git a/doc/src/week38/clean.sh b/doc/src/week38/clean.sh new file mode 100755 index 000000000..2e5da2c72 --- /dev/null +++ b/doc/src/week38/clean.sh @@ -0,0 +1,3 @@ +#!/bin/sh +doconce clean +rm -rf *.pdf *.tex ipynb*.tar.gz *.html ._*.html *~ reveal.js Trash README.txt diff --git a/doc/src/week38/make.sh b/doc/src/week38/make.sh new file mode 100755 index 000000000..4722a0918 --- /dev/null +++ b/doc/src/week38/make.sh @@ -0,0 +1,79 @@ +#!/bin/sh +set -x + +function system { + "$@" + if [ $? -ne 0 ]; then + echo "make.sh: unsuccessful command $@" + echo "abort!" + exit 1 + fi +} + +if [ $# -eq 0 ]; then +echo 'bash make.sh slides1|slides2' +exit 1 +fi + +name=$1 +rm -f *.tar.gz + +opt="--encoding=utf-8" +# Note: Makefile examples contain constructions like ${PROG} which +# looks like Mako constructions, but they are not. Use --no_mako +# to turn off Mako processing. +opt="--no_mako" + +rm -f *.aux + + +html=${name}-reveal +system doconce format html $name --pygments_html_style=perldoc --keep_pygments_html_bg --html_links_in_new_window --html_output=$html $opt +system doconce slides_html $html reveal --html_slide_theme=beige + +# Plain HTML documents + +html=${name}-solarized +system doconce format html $name --pygments_html_style=perldoc --html_style=solarized3 --html_links_in_new_window --html_output=$html $opt +system doconce split_html $html.html --method=space10 + +html=${name} +system doconce format html $name --pygments_html_style=default --html_style=bloodish --html_links_in_new_window --html_output=$html $opt +system doconce split_html $html.html --method=space10 + +# Bootstrap style +html=${name}-bs +system doconce format html $name --html_style=bootstrap --pygments_html_style=default --html_admon=bootstrap_panel --html_output=$html $opt +system doconce split_html $html.html --method=split --pagination --nav_button=bottom + +# IPython notebook +system doconce format ipynb $name $opt + + +# Publish +dest=../../pub +if [ ! -d $dest/$name ]; then +mkdir $dest/$name +mkdir $dest/$name/html +mkdir $dest/$name/ipynb +fi +cp -r ${name}*.html ._${name}*.html reveal.js $dest/$name/html + +# Figures: cannot just copy link, need to physically copy the files +if [ -d fig-${name} ]; then +if [ ! -d $dest/$name/html/fig-$name ]; then +mkdir $dest/$name/html/fig-$name +fi +cp -r fig-${name}/* $dest/$name/html/fig-$name +fi + +cp ${name}.ipynb $dest/$name/ipynb +ipynb_tarfile=ipynb-${name}-src.tar.gz +if [ ! -f ${ipynb_tarfile} ]; then +cat > README.txt < 0.5$ and the no +default case $y_i \leq 0.5$. + +We would then have our +weighted linear combination, namely +!bt +\begin{equation} +\hat{y} = \hat{X}^T\hat{\beta} + \hat{\epsilon}, +\end{equation} +!et +where $\hat{y}$ is a vector representing the possible outcomes, $\hat{X}$ is our +$n\times p$ design matrix and $\hat{\beta}$ represents our estimators/predictors. + +!split +===== Some selected properties ===== + +The main problem with our function is that it takes values on the +entire real axis. In the case of logistic regression, however, the +labels $y_i$ are discrete variables. A typical example is the credit +card data discussed below here, where we can set the state of +defaulting the debt to $y_i=1$ and not to $y_i=0$ for one the persons +in the data set (see the full example below). + +One simple way to get a discrete output is to have sign +functions that map the output of a linear regressor to values $\{0,1\}$, +$f(s_i)=sign(s_i)=1$ if $s_i\ge 0$ and 0 if otherwise. +We will encounter this model in our first demonstration of neural networks. Historically it is called the ``perceptron" model in the machine learning +literature. This model is extremely simple. However, in many cases it is more +favorable to use a ``soft" classifier that outputs +the probability of a given category. This leads us to the logistic function. + + +!split +===== The logistic function ===== + +The perceptron is an example of a ``hard classification'' model. We +will encounter this model when we discuss neural networks as +well. Each datapoint is deterministically assigned to a category (i.e +$y_i=0$ or $y_i=1$). In many cases, it is favorable to have a ``soft'' +classifier that outputs the probability of a given category rather +than a single value. For example, given $x_i$, the classifier +outputs the probability of being in a category $k$. Logistic regression +is the most common example of a so-called soft classifier. In logistic +regression, the probability that a data point $x_i$ +belongs to a category $y_i=\{0,1\}$ is given by the so-called logit function (or Sigmoid) which is meant to represent the likelihood for a given event, +!bt +\[ +p(t) = \frac{1}{1+\mathrm \exp{-t}}=\frac{\exp{t}}{1+\mathrm \exp{t}}. +\] +!et +Note that $1-p(t)= p(-t)$. + +!split +===== Examples of likelihood functions used in logistic regression and nueral networks ===== + + +The following code plots the logistic function, the step function and other functions we will encounter from here and on. + + +!bc pycod +"""The sigmoid function (or the logistic curve) is a +function that takes any real number, z, and outputs a number (0,1). +It is useful in neural networks for assigning weights on a relative scale. +The value z is the weighted sum of parameters involved in the learning algorithm.""" + +import numpy +import matplotlib.pyplot as plt +import math as mt + +z = numpy.arange(-5, 5, .1) +sigma_fn = numpy.vectorize(lambda z: 1/(1+numpy.exp(-z))) +sigma = sigma_fn(z) + +fig = plt.figure() +ax = fig.add_subplot(111) +ax.plot(z, sigma) +ax.set_ylim([-0.1, 1.1]) +ax.set_xlim([-5,5]) +ax.grid(True) +ax.set_xlabel('z') +ax.set_title('sigmoid function') + +plt.show() + +"""Step Function""" +z = numpy.arange(-5, 5, .02) +step_fn = numpy.vectorize(lambda z: 1.0 if z >= 0.0 else 0.0) +step = step_fn(z) + +fig = plt.figure() +ax = fig.add_subplot(111) +ax.plot(z, step) +ax.set_ylim([-0.5, 1.5]) +ax.set_xlim([-5,5]) +ax.grid(True) +ax.set_xlabel('z') +ax.set_title('step function') + +plt.show() + +"""tanh Function""" +z = numpy.arange(-2*mt.pi, 2*mt.pi, 0.1) +t = numpy.tanh(z) + +fig = plt.figure() +ax = fig.add_subplot(111) +ax.plot(z, t) +ax.set_ylim([-1.0, 1.0]) +ax.set_xlim([-2*mt.pi,2*mt.pi]) +ax.grid(True) +ax.set_xlabel('z') +ax.set_title('tanh function') + +plt.show() +!ec + + + + + + + +!split +===== Two parameters ===== + +We assume now that we have two classes with $y_i$ either $0$ or $1$. Furthermore we assume also that we have only two parameters $\beta$ in our fitting of the Sigmoid function, that is we define probabilities +!bt +\begin{align*} +p(y_i=1|x_i,\hat{\beta}) &= \frac{\exp{(\beta_0+\beta_1x_i)}}{1+\exp{(\beta_0+\beta_1x_i)}},\nonumber\\ +p(y_i=0|x_i,\hat{\beta}) &= 1 - p(y_i=1|x_i,\hat{\beta}), +\end{align*} +!et +where $\hat{\beta}$ are the weights we wish to extract from data, in our case $\beta_0$ and $\beta_1$. + +Note that we used +!bt +\[ +p(y_i=0\vert x_i, \hat{\beta}) = 1-p(y_i=1\vert x_i, \hat{\beta}). +\] +!et + +!split +===== Maximum likelihood ===== + +In order to define the total likelihood for all possible outcomes from a +dataset $\mathcal{D}=\{(y_i,x_i)\}$, with the binary labels +$y_i\in\{0,1\}$ and where the data points are drawn independently, we use the so-called "Maximum Likelihood Estimation":"https://en.wikipedia.org/wiki/Maximum_likelihood_estimation" (MLE) principle. +We aim thus at maximizing +the probability of seeing the observed data. We can then approximate the +likelihood in terms of the product of the individual probabilities of a specific outcome $y_i$, that is +!bt +\begin{align*} +P(\mathcal{D}|\hat{\beta})& = \prod_{i=1}^n \left[p(y_i=1|x_i,\hat{\beta})\right]^{y_i}\left[1-p(y_i=1|x_i,\hat{\beta}))\right]^{1-y_i}\nonumber \\ +\end{align*} +!et +from which we obtain the log-likelihood and our _cost/loss_ function +!bt +\[ +\mathcal{C}(\hat{\beta}) = \sum_{i=1}^n \left( y_i\log{p(y_i=1|x_i,\hat{\beta})} + (1-y_i)\log\left[1-p(y_i=1|x_i,\hat{\beta}))\right]\right). +\] +!et + +!split +===== The cost function rewritten ===== + +Reordering the logarithms, we can rewrite the _cost/loss_ function as +!bt +\[ +\mathcal{C}(\hat{\beta}) = \sum_{i=1}^n \left(y_i(\beta_0+\beta_1x_i) -\log{(1+\exp{(\beta_0+\beta_1x_i)})}\right). +\] +!et + +The maximum likelihood estimator is defined as the set of parameters that maximize the log-likelihood where we maximize with respect to $\beta$. +Since the cost (error) function is just the negative log-likelihood, for logistic regression we have that +!bt +\[ +\mathcal{C}(\hat{\beta})=-\sum_{i=1}^n \left(y_i(\beta_0+\beta_1x_i) -\log{(1+\exp{(\beta_0+\beta_1x_i)})}\right). +\] +!et +This equation is known in statistics as the _cross entropy_. Finally, we note that just as in linear regression, +in practice we often supplement the cross-entropy with additional regularization terms, usually $L_1$ and $L_2$ regularization as we did for Ridge and Lasso regression. + +!split +===== Minimizing the cross entropy ===== + +The cross entropy is a convex function of the weights $\hat{\beta}$ and, +therefore, any local minimizer is a global minimizer. + + +Minimizing this +cost function with respect to the two parameters $\beta_0$ and $\beta_1$ we obtain + +!bt +\[ +\frac{\partial \mathcal{C}(\hat{\beta})}{\partial \beta_0} = -\sum_{i=1}^n \left(y_i -\frac{\exp{(\beta_0+\beta_1x_i)}}{1+\exp{(\beta_0+\beta_1x_i)}}\right), +\] +!et +and +!bt +\[ +\frac{\partial \mathcal{C}(\hat{\beta})}{\partial \beta_1} = -\sum_{i=1}^n \left(y_ix_i -x_i\frac{\exp{(\beta_0+\beta_1x_i)}}{1+\exp{(\beta_0+\beta_1x_i)}}\right). +\] +!et + +!split +===== A more compact expression ===== + +Let us now define a vector $\hat{y}$ with $n$ elements $y_i$, an +$n\times p$ matrix $\hat{X}$ which contains the $x_i$ values and a +vector $\hat{p}$ of fitted probabilities $p(y_i\vert x_i,\hat{\beta})$. We can rewrite in a more compact form the first +derivative of cost function as + +!bt +\[ +\frac{\partial \mathcal{C}(\hat{\beta})}{\partial \hat{\beta}} = -\hat{X}^T\left(\hat{y}-\hat{p}\right). +\] +!et + +If we in addition define a diagonal matrix $\hat{W}$ with elements +$p(y_i\vert x_i,\hat{\beta})(1-p(y_i\vert x_i,\hat{\beta})$, we can obtain a compact expression of the second derivative as + +!bt +\[ +\frac{\partial^2 \mathcal{C}(\hat{\beta})}{\partial \hat{\beta}\partial \hat{\beta}^T} = \hat{X}^T\hat{W}\hat{X}. +\] +!et + +!split +===== Extending to more predictors ===== + +Within a binary classification problem, we can easily expand our model to include multiple predictors. Our ratio between likelihoods is then with $p$ predictors +!bt +\[ +\log{ \frac{p(\hat{\beta}\hat{x})}{1-p(\hat{\beta}\hat{x})}} = \beta_0+\beta_1x_1+\beta_2x_2+\dots+\beta_px_p. +\] +!et +Here we defined $\hat{x}=[1,x_1,x_2,\dots,x_p]$ and $\hat{\beta}=[\beta_0, \beta_1, \dots, \beta_p]$ leading to +!bt +\[ +p(\hat{\beta}\hat{x})=\frac{ \exp{(\beta_0+\beta_1x_1+\beta_2x_2+\dots+\beta_px_p)}}{1+\exp{(\beta_0+\beta_1x_1+\beta_2x_2+\dots+\beta_px_p)}}. +\] +!et + +!split +===== Including more classes ===== + +Till now we have mainly focused on two classes, the so-called binary +system. Suppose we wish to extend to $K$ classes. Let us for the sake +of simplicity assume we have only two predictors. We have then +following model + +!bt +\[ +\log{\frac{p(C=1\vert x)}{p(K\vert x)}} = \beta_{10}+\beta_{11}x_1, +\] +!et +!bt +\[ +\log{\frac{p(C=2\vert x)}{p(K\vert x)}} = \beta_{20}+\beta_{21}x_1, +\] +!et +and so on till the class $C=K-1$ class +!bt +\[ +\log{\frac{p(C=K-1\vert x)}{p(K\vert x)}} = \beta_{(K-1)0}+\beta_{(K-1)1}x_1, +\] +!et + +and the model is specified in term of $K-1$ so-called log-odds or +_logit_ transformations. + + +!split +===== More classes ===== + +In our discussion of neural networks we will encounter the above again +in terms of a slightly modified function, the so-called _Softmax_ function. + +The softmax function is used in various multiclass classification +methods, such as multinomial logistic regression (also known as +softmax regression), multiclass linear discriminant analysis, naive +Bayes classifiers, and artificial neural networks. Specifically, in +multinomial logistic regression and linear discriminant analysis, the +input to the function is the result of $K$ distinct linear functions, +and the predicted probability for the $k$-th class given a sample +vector $\hat{x}$ and a weighting vector $\hat{\beta}$ is (with two +predictors): + +!bt +\[ +p(C=k\vert \mathbf {x} )=\frac{\exp{(\beta_{k0}+\beta_{k1}x_1)}}{1+\sum_{l=1}^{K-1}\exp{(\beta_{l0}+\beta_{l1}x_1)}}. +\] +!et +It is easy to extend to more predictors. The final class is +!bt +\[ +p(C=K\vert \mathbf {x} )=\frac{1}{1+\sum_{l=1}^{K-1}\exp{(\beta_{l0}+\beta_{l1}x_1)}}, +\] +!et + +and they sum to one. Our earlier discussions were all specialized to +the case with two classes only. It is easy to see from the above that +what we derived earlier is compatible with these equations. + +To find the optimal parameters we would typically use a gradient +descent method. Newton's method and gradient descent methods are +discussed in the material on "optimization +methods":"https://compphysics.github.io/MachineLearning/doc/pub/Splines/html/Splines-bs.html". + + + + +!split +===== A simple classification problem ===== +!bc pycod +import numpy as np +from sklearn import datasets, linear_model +import matplotlib.pyplot as plt + + +def generate_data(): + np.random.seed(0) + X, y = datasets.make_moons(200, noise=0.20) + return X, y + + +def visualize(X, y, clf): + plot_decision_boundary(lambda x: clf.predict(x), X, y) + +def plot_decision_boundary(pred_func, X, y): + # Set min and max values and give it some padding + x_min, x_max = X[:, 0].min() - .5, X[:, 0].max() + .5 + y_min, y_max = X[:, 1].min() - .5, X[:, 1].max() + .5 + h = 0.01 + # Generate a grid of points with distance h between them + xx, yy = np.meshgrid(np.arange(x_min, x_max, h), np.arange(y_min, y_max, h)) + # Predict the function value for the whole gid + Z = pred_func(np.c_[xx.ravel(), yy.ravel()]) + Z = Z.reshape(xx.shape) + # Plot the contour and training examples + plt.contourf(xx, yy, Z, cmap=plt.cm.Spectral) + plt.scatter(X[:, 0], X[:, 1], c=y, cmap=plt.cm.Spectral) + plt.show() + + +def classify(X, y): + clf = linear_model.LogisticRegressionCV() + clf.fit(X, y) + return clf + + +def main(): + X, y = generate_data() + # visualize(X, y) + clf = classify(X, y) + visualize(X, y, clf) + +if __name__ == "__main__": + main() +!ec + + + +!split +===== Cancer Data again now with Decision Trees and other Methods ===== +!bc pycod +import matplotlib.pyplot as plt +import numpy as np +from sklearn.model_selection import train_test_split +from sklearn.datasets import load_breast_cancer +from sklearn.linear_model import LogisticRegression + +# Load the data +cancer = load_breast_cancer() + +X_train, X_test, y_train, y_test = train_test_split(cancer.data,cancer.target,random_state=0) +print(X_train.shape) +print(X_test.shape) +# Logistic Regression +logreg = LogisticRegression(solver='lbfgs') +logreg.fit(X_train, y_train) +print("Test set accuracy with Logistic Regression: {:.2f}".format(logreg.score(X_test,y_test))) +#now scale the data +from sklearn.preprocessing import StandardScaler +scaler = StandardScaler() +scaler.fit(X_train) +X_train_scaled = scaler.transform(X_train) +X_test_scaled = scaler.transform(X_test) +# Logistic Regression +logreg.fit(X_train_scaled, y_train) +print("Test set accuracy Logistic Regression with scaled data: {:.2f}".format(logreg.score(X_test_scaled,y_test))) +!ec + + +!split +===== Other measures in classification studies: Cancer Data again ===== +!bc pycod +import matplotlib.pyplot as plt +import numpy as np +from sklearn.model_selection import train_test_split +from sklearn.datasets import load_breast_cancer +from sklearn.linear_model import LogisticRegression + +# Load the data +cancer = load_breast_cancer() + +X_train, X_test, y_train, y_test = train_test_split(cancer.data,cancer.target,random_state=0) +print(X_train.shape) +print(X_test.shape) +# Logistic Regression +logreg = LogisticRegression(solver='lbfgs') +logreg.fit(X_train, y_train) +print("Test set accuracy with Logistic Regression: {:.2f}".format(logreg.score(X_test,y_test))) +#now scale the data +from sklearn.preprocessing import StandardScaler +scaler = StandardScaler() +scaler.fit(X_train) +X_train_scaled = scaler.transform(X_train) +X_test_scaled = scaler.transform(X_test) +# Logistic Regression +logreg.fit(X_train_scaled, y_train) +print("Test set accuracy Logistic Regression with scaled data: {:.2f}".format(logreg.score(X_test_scaled,y_test))) + + +from sklearn.preprocessing import LabelEncoder +from sklearn.model_selection import cross_validate +#Cross validation +accuracy = cross_validate(logreg,X_test_scaled,y_test,cv=10)['test_score'] +print(accuracy) +print("Test set accuracy with Logistic Regression and scaled data: {:.2f}".format(logreg.score(X_test_scaled,y_test))) + + +import scikitplot as skplt +y_pred = logreg.predict(X_test_scaled) +skplt.metrics.plot_confusion_matrix(y_test, y_pred, normalize=True) +plt.show() +y_probas = logreg.predict_proba(X_test_scaled) +skplt.metrics.plot_roc(y_test, y_probas) +plt.show() +skplt.metrics.plot_cumulative_gain(y_test, y_probas) +plt.show() + +!ec + + + diff --git a/doc/src/week39/clean.sh b/doc/src/week39/clean.sh new file mode 100755 index 000000000..2e5da2c72 --- /dev/null +++ b/doc/src/week39/clean.sh @@ -0,0 +1,3 @@ +#!/bin/sh +doconce clean +rm -rf *.pdf *.tex ipynb*.tar.gz *.html ._*.html *~ reveal.js Trash README.txt diff --git a/doc/src/week39/make.sh b/doc/src/week39/make.sh new file mode 100755 index 000000000..4722a0918 --- /dev/null +++ b/doc/src/week39/make.sh @@ -0,0 +1,79 @@ +#!/bin/sh +set -x + +function system { + "$@" + if [ $? -ne 0 ]; then + echo "make.sh: unsuccessful command $@" + echo "abort!" + exit 1 + fi +} + +if [ $# -eq 0 ]; then +echo 'bash make.sh slides1|slides2' +exit 1 +fi + +name=$1 +rm -f *.tar.gz + +opt="--encoding=utf-8" +# Note: Makefile examples contain constructions like ${PROG} which +# looks like Mako constructions, but they are not. Use --no_mako +# to turn off Mako processing. +opt="--no_mako" + +rm -f *.aux + + +html=${name}-reveal +system doconce format html $name --pygments_html_style=perldoc --keep_pygments_html_bg --html_links_in_new_window --html_output=$html $opt +system doconce slides_html $html reveal --html_slide_theme=beige + +# Plain HTML documents + +html=${name}-solarized +system doconce format html $name --pygments_html_style=perldoc --html_style=solarized3 --html_links_in_new_window --html_output=$html $opt +system doconce split_html $html.html --method=space10 + +html=${name} +system doconce format html $name --pygments_html_style=default --html_style=bloodish --html_links_in_new_window --html_output=$html $opt +system doconce split_html $html.html --method=space10 + +# Bootstrap style +html=${name}-bs +system doconce format html $name --html_style=bootstrap --pygments_html_style=default --html_admon=bootstrap_panel --html_output=$html $opt +system doconce split_html $html.html --method=split --pagination --nav_button=bottom + +# IPython notebook +system doconce format ipynb $name $opt + + +# Publish +dest=../../pub +if [ ! -d $dest/$name ]; then +mkdir $dest/$name +mkdir $dest/$name/html +mkdir $dest/$name/ipynb +fi +cp -r ${name}*.html ._${name}*.html reveal.js $dest/$name/html + +# Figures: cannot just copy link, need to physically copy the files +if [ -d fig-${name} ]; then +if [ ! -d $dest/$name/html/fig-$name ]; then +mkdir $dest/$name/html/fig-$name +fi +cp -r fig-${name}/* $dest/$name/html/fig-$name +fi + +cp ${name}.ipynb $dest/$name/ipynb +ipynb_tarfile=ipynb-${name}-src.tar.gz +if [ ! -f ${ipynb_tarfile} ]; then +cat > README.txt < README.txt < README.txt < README.txt < README.txt < README.txt < README.txt < README.txt < README.txt < README.txt <