From 3fdabd3871c5bfd64f915a6b04b9804d85507b5a Mon Sep 17 00:00:00 2001 From: mhjensen Date: Mon, 10 Jun 2019 22:10:42 -0400 Subject: [PATCH] revising regression --- .../Regression/html/._Regression-bs000.html | 513 +- .../Regression/html/._Regression-bs001.html | 538 +- .../Regression/html/._Regression-bs002.html | 539 +- .../Regression/html/._Regression-bs003.html | 535 +- .../Regression/html/._Regression-bs004.html | 536 +- .../Regression/html/._Regression-bs005.html | 545 +- .../Regression/html/._Regression-bs006.html | 524 +- .../Regression/html/._Regression-bs007.html | 544 +- .../Regression/html/._Regression-bs008.html | 529 +- .../Regression/html/._Regression-bs009.html | 531 +- .../Regression/html/._Regression-bs010.html | 547 +- .../Regression/html/._Regression-bs011.html | 613 +- .../Regression/html/._Regression-bs012.html | 533 +- .../Regression/html/._Regression-bs013.html | 552 +- .../Regression/html/._Regression-bs014.html | 551 +- .../Regression/html/._Regression-bs015.html | 544 +- .../Regression/html/._Regression-bs016.html | 567 +- .../Regression/html/._Regression-bs017.html | 561 +- .../Regression/html/._Regression-bs018.html | 559 +- .../Regression/html/._Regression-bs019.html | 560 +- .../Regression/html/._Regression-bs020.html | 551 +- .../Regression/html/._Regression-bs021.html | 585 +- .../Regression/html/._Regression-bs022.html | 542 +- .../Regression/html/._Regression-bs023.html | 569 +- .../Regression/html/._Regression-bs024.html | 540 +- .../Regression/html/._Regression-bs025.html | 621 +- .../Regression/html/._Regression-bs026.html | 608 +- .../Regression/html/._Regression-bs027.html | 566 +- .../Regression/html/._Regression-bs028.html | 565 +- .../Regression/html/._Regression-bs029.html | 557 +- .../Regression/html/._Regression-bs030.html | 560 +- .../Regression/html/._Regression-bs031.html | 620 +- .../Regression/html/._Regression-bs032.html | 575 +- .../Regression/html/._Regression-bs033.html | 544 +- .../Regression/html/._Regression-bs034.html | 558 +- .../Regression/html/._Regression-bs035.html | 548 +- .../Regression/html/._Regression-bs036.html | 572 +- .../Regression/html/._Regression-bs037.html | 544 +- .../Regression/html/._Regression-bs038.html | 564 +- .../Regression/html/._Regression-bs039.html | 566 +- .../Regression/html/._Regression-bs040.html | 622 +- .../Regression/html/._Regression-bs041.html | 565 +- .../Regression/html/._Regression-bs042.html | 545 +- .../Regression/html/._Regression-bs043.html | 591 +- .../Regression/html/._Regression-bs044.html | 634 +- .../Regression/html/._Regression-bs045.html | 540 +- .../Regression/html/._Regression-bs046.html | 532 +- .../Regression/html/._Regression-bs047.html | 523 +- .../Regression/html/._Regression-bs048.html | 540 +- .../Regression/html/._Regression-bs049.html | 535 +- .../Regression/html/._Regression-bs050.html | 542 +- .../Regression/html/._Regression-bs051.html | 550 +- .../Regression/html/._Regression-bs052.html | 546 +- .../Regression/html/._Regression-bs053.html | 545 +- .../Regression/html/._Regression-bs054.html | 539 +- .../Regression/html/._Regression-bs055.html | 545 +- .../Regression/html/._Regression-bs056.html | 541 +- .../Regression/html/._Regression-bs057.html | 538 +- .../Regression/html/._Regression-bs058.html | 540 +- .../Regression/html/._Regression-bs059.html | 539 +- .../Regression/html/._Regression-bs060.html | 528 +- .../Regression/html/._Regression-bs061.html | 533 +- .../Regression/html/._Regression-bs062.html | 537 +- .../Regression/html/._Regression-bs063.html | 541 +- .../Regression/html/._Regression-bs064.html | 543 +- .../Regression/html/._Regression-bs065.html | 549 +- .../Regression/html/._Regression-bs066.html | 539 +- .../Regression/html/._Regression-bs067.html | 536 +- .../Regression/html/._Regression-bs068.html | 540 +- .../Regression/html/._Regression-bs069.html | 547 +- .../Regression/html/._Regression-bs070.html | 543 +- .../Regression/html/._Regression-bs071.html | 559 +- .../Regression/html/._Regression-bs072.html | 544 +- .../Regression/html/._Regression-bs073.html | 565 +- .../Regression/html/._Regression-bs074.html | 594 +- .../Regression/html/._Regression-bs075.html | 552 +- .../Regression/html/._Regression-bs076.html | 547 +- .../Regression/html/._Regression-bs077.html | 545 +- .../Regression/html/._Regression-bs078.html | 558 +- .../Regression/html/._Regression-bs079.html | 535 +- .../Regression/html/._Regression-bs080.html | 528 +- .../Regression/html/._Regression-bs081.html | 509 +- .../Regression/html/._Regression-bs082.html | 509 +- .../Regression/html/._Regression-bs083.html | 519 +- .../Regression/html/._Regression-bs084.html | 511 +- .../Regression/html/._Regression-bs085.html | 511 +- .../Regression/html/._Regression-bs086.html | 525 +- .../Regression/html/._Regression-bs087.html | 544 +- .../Regression/html/._Regression-bs088.html | 619 +- .../Regression/html/._Regression-bs089.html | 590 +- .../Regression/html/._Regression-bs090.html | 583 +- .../Regression/html/._Regression-bs091.html | 574 +- .../Regression/html/._Regression-bs092.html | 562 +- .../Regression/html/._Regression-bs093.html | 784 +-- .../Regression/html/._Regression-bs094.html | 658 +- .../Regression/html/._Regression-bs095.html | 546 +- .../Regression/html/._Regression-bs096.html | 551 +- .../Regression/html/._Regression-bs097.html | 575 +- .../Regression/html/._Regression-bs098.html | 579 +- .../Regression/html/._Regression-bs099.html | 750 ++- doc/pub/Regression/html/Regression-bs.html | 513 +- .../Regression/html/Regression-reveal.html | 4234 +++++++------ .../Regression/html/Regression-solarized.html | 4286 +++++++------ doc/pub/Regression/html/Regression.html | 4286 +++++++------ doc/pub/Regression/html/reveal.js/.gitignore | 7 +- doc/pub/Regression/html/reveal.js/.travis.yml | 6 +- doc/pub/Regression/html/reveal.js/LICENSE | 2 +- doc/pub/Regression/html/reveal.js/README.md | 592 +- doc/pub/Regression/html/reveal.js/bower.json | 6 +- .../html/reveal.js/css/print/paper.css | 7 +- .../html/reveal.js/css/print/pdf.css | 97 +- .../Regression/html/reveal.js/css/reveal.scss | 588 +- .../html/reveal.js/css/theme/README.md | 6 +- .../reveal.js/css/theme/source/black.scss | 4 +- .../reveal.js/css/theme/source/white.scss | 4 +- doc/pub/Regression/html/reveal.js/index.html | 390 +- .../Regression/html/reveal.js/js/reveal.js | 1419 +---- .../html/reveal.js/lib/css/zenburn.css | 119 +- .../html/reveal.js/lib/js/head.min.js | 17 +- .../Regression/html/reveal.js/package.json | 42 +- .../reveal.js/plugin/highlight/highlight.js | 55 +- .../reveal.js/plugin/markdown/example.html | 7 - .../html/reveal.js/plugin/markdown/example.md | 5 - .../reveal.js/plugin/markdown/markdown.js | 57 +- .../html/reveal.js/plugin/markdown/marked.js | 2 +- .../html/reveal.js/plugin/math/math.js | 7 +- .../html/reveal.js/plugin/multiplex/client.js | 2 +- .../html/reveal.js/plugin/multiplex/index.js | 38 +- .../html/reveal.js/plugin/multiplex/master.js | 61 +- .../reveal.js/plugin/notes-server/client.js | 7 +- .../reveal.js/plugin/notes-server/index.js | 31 +- .../reveal.js/plugin/notes-server/notes.html | 241 +- .../html/reveal.js/plugin/notes/notes.html | 417 +- .../html/reveal.js/plugin/notes/notes.js | 45 +- .../reveal.js/plugin/print-pdf/print-pdf.js | 75 +- .../html/reveal.js/plugin/search/search.js | 72 +- .../html/reveal.js/plugin/zoom-js/zoom.js | 40 +- .../html/reveal.js/test/examples/math.html | 2 +- .../test/examples/slide-backgrounds.html | 2 +- .../html/reveal.js/test/test-markdown.html | 2 +- .../Regression/html/reveal.js/test/test.html | 3 +- .../Regression/html/reveal.js/test/test.js | 10 +- doc/pub/Regression/ipynb/Regression.ipynb | 5581 +++++++++-------- .../ipynb/ipynb-Regression-src.tar.gz | Bin 211 -> 212 bytes doc/pub/Regression/pdf/Regression-minted.pdf | Bin 543661 -> 459188 bytes doc/src/Regression/Regression.do.txt | 3533 ++++++----- doc/src/Regression/backup2018.do.txt | 3381 ++++++++++ doc/src/Regression/make.sh | 23 - 148 files changed, 43274 insertions(+), 42840 deletions(-) create mode 100644 doc/src/Regression/backup2018.do.txt diff --git a/doc/pub/Regression/html/._Regression-bs000.html b/doc/pub/Regression/html/._Regression-bs000.html index f2952f17c..cf5feb8ed 100644 --- a/doc/pub/Regression/html/._Regression-bs000.html +++ b/doc/pub/Regression/html/._Regression-bs000.html @@ -6,6 +6,7 @@ Automatically generated HTML file from DocOnce source + Data Analysis and Machine Learning: Linear Regression and more Advanced Regression Analysis @@ -40,160 +41,151 @@ Automatically generated HTML file from DocOnce source @@ -286,119 +263,109 @@ MathJax.Hub.Config({ @@ -433,7 +400,7 @@ MathJax.Hub.Config({
[2] Department of Physics and Astronomy and National Superconducting Cyclotron Laboratory, Michigan State University

-

Oct 18, 2018

+

Jun 10, 2019


@@ -457,7 +424,7 @@ MathJax.Hub.Config({

  • 9
  • 10
  • ...
  • -
  • 114
  • +
  • 100
  • »
  • @@ -475,7 +442,7 @@ MathJax.Hub.Config({
    - © 1999-2018, Morten Hjorth-Jensen. Released under CC Attribution-NonCommercial 4.0 license + © 1999-2019, Morten Hjorth-Jensen. Released under CC Attribution-NonCommercial 4.0 license
    diff --git a/doc/pub/Regression/html/._Regression-bs001.html b/doc/pub/Regression/html/._Regression-bs001.html index e4e344db2..3401b90d4 100644 --- a/doc/pub/Regression/html/._Regression-bs001.html +++ b/doc/pub/Regression/html/._Regression-bs001.html @@ -6,6 +6,7 @@ Automatically generated HTML file from DocOnce source + Data Analysis and Machine Learning: Linear Regression and more Advanced Regression Analysis @@ -40,160 +41,151 @@ Automatically generated HTML file from DocOnce source @@ -286,119 +263,109 @@ MathJax.Hub.Config({ @@ -414,28 +381,25 @@ MathJax.Hub.Config({ -

    Regression analysis, overarching aims

    -
    -
    -

    +

    Why Linear Regression (aka Ordinary Least Squares and family)

    -Regression modeling deals with the description of the sampling distribution of a given random variable \( y \) varies as function of another variable or a set of such variables \( \hat{x} =[x_0, x_1,\dots, x_p]^T \). -The first variable is called the dependent, the outcome or the response variable while the set of variables \( \hat{x} \) is called the independent variable, or the predictor variable or the explanatory variable. - -

    -A regression model aims at finding a likelihood function \( p(y\vert \hat{x}) \), that is the conditional distribution for \( y \) with a given \( \hat{x} \). The estimation of \( p(y\vert \hat{x}) \) is made using a data set with +Fitting a continuous function with linear parameterization in terms of the parameters \( \boldsymbol{\beta} \).

      -
    • \( n \) cases \( i = 0, 1, 2, \dots, n-1 \)
    • -
    • Response (dependent or outcome) variable \( y_i \) with \( i = 0, 1, 2, \dots, n-1 \)
    • -
    • \( p \) Explanatory (independent or predictor) variables \( \hat{x}_i=[x_{i0}, x_{i1}, \dots, x_{ip}] \) with \( i = 0, 1, 2, \dots, n-1 \)
    • +
    • Method of choice for fitting a continuous function!
    • +
    • Gives an excellent introduction to central Machine Learning features with understandable pedagogical links to other methods like Neural Networks, Support Vector Machines etc
    • +
    • Analytical expression for the fitting parameters \( \boldsymbol{\beta} \)
    • +
    • Analytical expressions for statistical propertiers like mean values, variances, confidence intervals and more
    • +
    • Analytical relation with probabilistic interpretations
    • +
    • Easy to introduce basic concepts like bias-variance tradeoff, cross-validation, resampling and regularization techniques and many other ML topics
    • +
    • Easy to code! And links well with classification problems and logistic regression and neural networks
    • +
    • Allows for easy hands-on understanding of gradient descent methods
    • +
    • and many more features
    - The goal of the regression analysis is to extract/exploit relationship between \( y_i \) and \( \hat{x}_i \) in or to infer causal dependencies, approximations to the likelihood functions, functional relationships and to make predictions . -
    -
    - +For more discussions of Ridge and Lasso regression, Wessel van Wieringen's article is highly recommended. +Similarly, Mehta et al's article is also recommended.

    @@ -454,7 +418,7 @@ A regression model aims at finding a likelihood function \( p(y\vert \hat{x}) \)

  • 10
  • 11
  • ...
  • -
  • 114
  • +
  • 100
  • »
  • diff --git a/doc/pub/Regression/html/._Regression-bs002.html b/doc/pub/Regression/html/._Regression-bs002.html index d9ad537df..dee6ad935 100644 --- a/doc/pub/Regression/html/._Regression-bs002.html +++ b/doc/pub/Regression/html/._Regression-bs002.html @@ -6,6 +6,7 @@ Automatically generated HTML file from DocOnce source + Data Analysis and Machine Learning: Linear Regression and more Advanced Regression Analysis @@ -40,160 +41,151 @@ Automatically generated HTML file from DocOnce source @@ -286,119 +263,109 @@ MathJax.Hub.Config({ @@ -414,31 +381,25 @@ MathJax.Hub.Config({ -

    Regression analysis, overarching aims II

    +

    Regression analysis, overarching aims

    -Consider an experiment in which \( p \) characteristics of \( n \) samples are -measured. The data from this experiment are denoted \( \mathbf{X} \), with -\( \mathbf{X} \) as above. The matrix \( \mathbf{X} \) is called the design -matrix. Additional information of the samples is available in the -form of \( \mathbf{Y} \) (also as above). The variable \( \mathbf{Y} \) is -generally referred to as the response variable. The aim of -regression analysis is to explain \( \mathbf{Y} \) in terms of -\( \mathbf{X} \) through a functional relationship like \( Y_i = -f(\mathbf{X}_{i,\ast}) \). When no prior knowledge on the form of -\( f(\cdot) \) is available, it is common to assume a linear relationship -between \( \mathbf{X} \) and \( \mathbf{Y} \). This assumption gives rise to -the linear regression model where \( \beta = (\beta_1, \ldots, -\beta_p)^{\top} \) is the regression parameter. The parameter -\( \beta_j \), \( j=1, \ldots, p \), represents the effect size of covariate -\( j \) on the response. That is, for each unit change in covariate \( j \) -(while keeping the other covariates fixed) the observed change in the -response is equal to \( \beta_j \). +Regression modeling deals with the description of the sampling distribution of a given random variable \( y \) and how it varies as function of another variable or a set of such variables \( \boldsymbol{x} =[x_0, x_1,\dots, x_{n-1}]^T \). +The first variable is called the dependent, the outcome or the response variable while the set of variables \( \boldsymbol{x} \) is called the independent variable, or the predictor variable or the explanatory variable.

    +A regression model aims at finding a likelihood function \( p(\boldsymbol{y}\vert \boldsymbol{x}) \), that is the conditional distribution for \( \boldsymbol{y} \) with a given \( \boldsymbol{x} \). The estimation of \( p(\boldsymbol{y}\vert \boldsymbol{x}) \) is made using a data set with + +

      +
    • \( n \) cases \( i = 0, 1, 2, \dots, n-1 \)
    • +
    • Response (target, dependent or outcome) variable \( y_i \) with \( i = 0, 1, 2, \dots, n-1 \)
    • +
    • \( p \) so-called explanatory (independent or predictor) variables \( \boldsymbol{x}_i=[x_{i0}, x_{i1}, \dots, x_{ip-1}] \) with \( i = 0, 1, 2, \dots, n-1 \) and explanatory variables running from \( 0 \) to \( p-1 \). See below for more explicit examples.
    • +
    + + The goal of the regression analysis is to extract/exploit relationship between \( \boldsymbol{y} \) and \( \boldsymbol{X} \) in or to infer causal dependencies, approximations to the likelihood functions, functional relationships and to make predictions, making fits and many other things.
    @@ -461,7 +422,7 @@ response is equal to \( \beta_j \).
  • 11
  • 12
  • ...
  • -
  • 114
  • +
  • 100
  • »
  • diff --git a/doc/pub/Regression/html/._Regression-bs003.html b/doc/pub/Regression/html/._Regression-bs003.html index d553e6a21..88f261dee 100644 --- a/doc/pub/Regression/html/._Regression-bs003.html +++ b/doc/pub/Regression/html/._Regression-bs003.html @@ -6,6 +6,7 @@ Automatically generated HTML file from DocOnce source + Data Analysis and Machine Learning: Linear Regression and more Advanced Regression Analysis @@ -40,160 +41,151 @@ Automatically generated HTML file from DocOnce source @@ -286,119 +263,109 @@ MathJax.Hub.Config({ @@ -414,19 +381,31 @@ MathJax.Hub.Config({ -

    General linear models

    +

    Regression analysis, overarching aims II

    -Before we proceed let us study a case from linear algebra where we aim at fitting a set of data \( \hat{y}=[y_0,y_1,\dots,y_{n-1}] \). We could think of these data as a result of an experiment or a complicated numerical experiment. These data are functions of a series of variables \( \hat{x}=[x_0,x_1,\dots,x_{n-1}] \), that is \( y_i = y(x_i) \) with \( i=0,1,2,\dots,n-1 \). The variables \( x_i \) could represent physical quantities like time, temperature, position etc. We assume that \( y(x) \) is a smooth function.

    -Since obtaining these data points may not be trivial, we want to use these data to fit a function which can allow us to make predictions for values of \( y \) which are not in the present set. The perhaps simplest approach is to assume we can parametrize our function in terms of a polynomial of degree \( n-1 \) with \( n \) points, that is -$$ -y=y(x) \rightarrow y(x_i)=\tilde{y}_i+\epsilon_i=\sum_{j=0}^{n-1} \beta_i x_i^j+\epsilon_i, -$$ +Consider an experiment in which \( p \) characteristics of \( n \) samples are +measured. The data from this experiment, for various explanatory variables \( p \) are normally represented by a matrix +\( \mathbf{X} \). -where \( \epsilon_i \) is the error in our approximation. +

    +The matrix \( \mathbf{X} \) is called the design +matrix. Additional information of the samples is available in the +form of \( \boldsymbol{y} \) (also as above). The variable \( \boldsymbol{y} \) is +generally referred to as the response variable. The aim of +regression analysis is to explain \( \boldsymbol{y} \) in terms of +\( \boldsymbol{X} \) through a functional relationship like \( y_i = +f(\mathbf{X}_{i,\ast}) \). When no prior knowledge on the form of +\( f(\cdot) \) is available, it is common to assume a linear relationship +between \( \boldsymbol{X} \) and \( \boldsymbol{y} \). This assumption gives rise to +the linear regression model where \( \boldsymbol{\beta} = [\beta_0, \ldots, +\beta_{p-1}]^{T} \) are the regression parameters. + +

    +Linear regression gives us a set of analytical equations for the parameters \( \beta_j \).

    @@ -452,7 +431,7 @@ where \( \epsilon_i \) is the error in our approximation.
  • 12
  • 13
  • ...
  • -
  • 114
  • +
  • 100
  • »
  • diff --git a/doc/pub/Regression/html/._Regression-bs004.html b/doc/pub/Regression/html/._Regression-bs004.html index 48ba718f5..6e9d3daca 100644 --- a/doc/pub/Regression/html/._Regression-bs004.html +++ b/doc/pub/Regression/html/._Regression-bs004.html @@ -6,6 +6,7 @@ Automatically generated HTML file from DocOnce source + Data Analysis and Machine Learning: Linear Regression and more Advanced Regression Analysis @@ -40,160 +41,151 @@ Automatically generated HTML file from DocOnce source @@ -286,119 +263,109 @@ MathJax.Hub.Config({ @@ -414,20 +381,29 @@ MathJax.Hub.Config({ -

    Rewriting the fitting procedure as a linear algebra problem

    +

    Examples

    -For every set of values \( y_i,x_i \) we have thus the corresponding set of equations +In order to understand the relation among the predictors \( p \), the set of data \( n \) and the target (outcome, output etc) \( \boldsymbol{y} \), +consider the model we discussed for describing nuclear binding energies. + +

    +There we assumed that we could parametrize the data using a polynomial approximation based on the liquid drop model. +Assuming $$ -\begin{align*} -y_0&=\beta_0+\beta_1x_0^1+\beta_2x_0^2+\dots+\beta_{n-1}x_0^{n-1}+\epsilon_0\\ -y_1&=\beta_0+\beta_1x_1^1+\beta_2x_1^2+\dots+\beta_{n-1}x_1^{n-1}+\epsilon_1\\ -y_2&=\beta_0+\beta_1x_2^1+\beta_2x_2^2+\dots+\beta_{n-1}x_2^{n-1}+\epsilon_2\\ -\dots & \dots \\ -y_{n-1}&=\beta_0+\beta_1x_{n-1}^1+\beta_2x_{n-1}^2+\dots+\beta_1x_{n-1}^{n-1}+\epsilon_{n-1}.\\ -\end{align*} +BE(A) = a_0+a_1A+a_2A^{2/3}+a_3A^{-1/3}+a_4A^{-1}, $$ + +we have five predictors, that is the intercept, the \( A \) dependent term, the \( A^{2/3} \) term and the \( A^{-1/3} \) and \( A^{-1} \) terms. +This gives \( p=0,1,2,3,4 \). Furthermore we have \( n \) entries for each predictor. It means that our design matrix is a +\( p\times n \) matrix \( \boldsymbol{X} \). + +

    +Here the predictors are based on a model we have made. A popular data set which is widely encountered in ML applications is the +so-called credit card default data from Taiwan. The data set contains data on \( n=30000 \) credit card holders with predictors like gender, marital status, age, profession, education, etc. In total there are \( 24 \) such predictors or attributes leading to a design matrix of dimensionality \( 24 \times 30000 \) + +

    @@ -452,7 +428,7 @@ $$
  • 13
  • 14
  • ...
  • -
  • 114
  • +
  • 100
  • »
  • diff --git a/doc/pub/Regression/html/._Regression-bs005.html b/doc/pub/Regression/html/._Regression-bs005.html index 6b638d7fb..35f7c9bdb 100644 --- a/doc/pub/Regression/html/._Regression-bs005.html +++ b/doc/pub/Regression/html/._Regression-bs005.html @@ -6,6 +6,7 @@ Automatically generated HTML file from DocOnce source + Data Analysis and Machine Learning: Linear Regression and more Advanced Regression Analysis @@ -40,160 +41,151 @@ Automatically generated HTML file from DocOnce source @@ -286,119 +263,109 @@ MathJax.Hub.Config({ @@ -414,41 +381,21 @@ MathJax.Hub.Config({ -

    Rewriting the fitting procedure as a linear algebra problem, follows

    +

    General linear models

    -Defining the vectors +Before we proceed let us study a case from linear algebra where we aim at fitting a set of data \( \boldsymbol{y}=[y_0,y_1,\dots,y_{n-1}] \). We could think of these data as a result of an experiment or a complicated numerical experiment. These data are functions of a series of variables \( \boldsymbol{x}=[x_0,x_1,\dots,x_{n-1}] \), that is \( y_i = y(x_i) \) with \( i=0,1,2,\dots,n-1 \). The variables \( x_i \) could represent physical quantities like time, temperature, position etc. We assume that \( y(x) \) is a smooth function. + +

    +Since obtaining these data points may not be trivial, we want to use these data to fit a function which can allow us to make predictions for values of \( y \) which are not in the present set. The perhaps simplest approach is to assume we can parametrize our function in terms of a polynomial of degree \( n-1 \) with \( n \) points, that is $$ -\hat{y} = [y_0,y_1, y_2,\dots, y_{n-1}]^T, +y=y(x) \rightarrow y(x_i)=\tilde{y}_i+\epsilon_i=\sum_{j=0}^{n-1} \beta_j x_i^j+\epsilon_i, $$ -and -$$ -\hat{\beta} = [\beta_0,\beta_1, \beta_2,\dots, \beta_{n-1}]^T, -$$ +where \( \epsilon_i \) is the error in our approximation. -and -$$ -\hat{\epsilon} = [\epsilon_0,\epsilon_1, \epsilon_2,\dots, \epsilon_{n-1}]^T, -$$ - -and the matrix -$$ -\hat{X}= -\begin{bmatrix} -1& x_{0}^1 &x_{0}^2& \dots & \dots &x_{0}^{n-1}\\ -1& x_{1}^1 &x_{1}^2& \dots & \dots &x_{1}^{n-1}\\ -1& x_{2}^1 &x_{2}^2& \dots & \dots &x_{2}^{n-1}\\ -\dots& \dots &\dots& \dots & \dots &\dots\\ -1& x_{n-1}^1 &x_{n-1}^2& \dots & \dots &x_{n-1}^{n-1}\\ -\end{bmatrix} -$$ - -we can rewrite our equations as -$$ -\hat{y} = \hat{X}\hat{\beta}+\hat{\epsilon}. -$$ +

    @@ -474,7 +421,7 @@ $$
  • 14
  • 15
  • ...
  • -
  • 114
  • +
  • 100
  • »
  • diff --git a/doc/pub/Regression/html/._Regression-bs006.html b/doc/pub/Regression/html/._Regression-bs006.html index 6dbbe5b24..cf2ff155f 100644 --- a/doc/pub/Regression/html/._Regression-bs006.html +++ b/doc/pub/Regression/html/._Regression-bs006.html @@ -6,6 +6,7 @@ Automatically generated HTML file from DocOnce source + Data Analysis and Machine Learning: Linear Regression and more Advanced Regression Analysis @@ -40,160 +41,151 @@ Automatically generated HTML file from DocOnce source @@ -286,119 +263,109 @@ MathJax.Hub.Config({ @@ -414,21 +381,18 @@ MathJax.Hub.Config({ -

    Generalizing the fitting procedure as a linear algebra problem

    +

    Rewriting the fitting procedure as a linear algebra problem

    -We are obviously not limited to the above polynomial. We could replace the various powers of \( x \) with elements of Fourier series, that is, instead of \( x_i^j \) we could have \( \cos{(j x_i)} \) or \( \sin{(j x_i)} \), or time series or other orthogonal functions. -For every set of values \( y_i,x_i \) we can then generalize the equations to +For every set of values \( y_i,x_i \) we have thus the corresponding set of equations $$ \begin{align*} -y_0&=\beta_0x_{00}+\beta_1x_{01}+\beta_2x_{02}+\dots+\beta_{n-1}x_{0n-1}+\epsilon_0\\ -y_1&=\beta_0x_{10}+\beta_1x_{11}+\beta_2x_{12}+\dots+\beta_{n-1}x_{1n-1}+\epsilon_1\\ -y_2&=\beta_0x_{20}+\beta_1x_{21}+\beta_2x_{22}+\dots+\beta_{n-1}x_{2n-1}+\epsilon_2\\ +y_0&=\beta_0+\beta_1x_0^1+\beta_2x_0^2+\dots+\beta_{n-1}x_0^{n-1}+\epsilon_0\\ +y_1&=\beta_0+\beta_1x_1^1+\beta_2x_1^2+\dots+\beta_{n-1}x_1^{n-1}+\epsilon_1\\ +y_2&=\beta_0+\beta_1x_2^1+\beta_2x_2^2+\dots+\beta_{n-1}x_2^{n-1}+\epsilon_2\\ \dots & \dots \\ -y_{i}&=\beta_0x_{i0}+\beta_1x_{i1}+\beta_2x_{i2}+\dots+\beta_{n-1}x_{in-1}+\epsilon_i\\ -\dots & \dots \\ -y_{n-1}&=\beta_0x_{n-1,0}+\beta_1x_{n-1,2}+\beta_2x_{n-1,2}+\dots+\beta_1x_{n-1,n-1}+\epsilon_{n-1}.\\ +y_{n-1}&=\beta_0+\beta_1x_{n-1}^1+\beta_2x_{n-1}^2+\dots+\beta_{n-1}x_{n-1}^{n-1}+\epsilon_{n-1}.\\ \end{align*} $$

    @@ -457,7 +421,7 @@ $$
  • 15
  • 16
  • ...
  • -
  • 114
  • +
  • 100
  • »
  • diff --git a/doc/pub/Regression/html/._Regression-bs007.html b/doc/pub/Regression/html/._Regression-bs007.html index 755da484a..ee1cfb7c7 100644 --- a/doc/pub/Regression/html/._Regression-bs007.html +++ b/doc/pub/Regression/html/._Regression-bs007.html @@ -6,6 +6,7 @@ Automatically generated HTML file from DocOnce source + Data Analysis and Machine Learning: Linear Regression and more Advanced Regression Analysis @@ -40,160 +41,151 @@ Automatically generated HTML file from DocOnce source @@ -286,119 +263,109 @@ MathJax.Hub.Config({ @@ -414,28 +381,43 @@ MathJax.Hub.Config({ -

    Generalizing the fitting procedure as a linear algebra problem

    +

    Rewriting the fitting procedure as a linear algebra problem, more details

    -We redefine in turn the matrix \( \hat{X} \) as +Defining the vectors $$ -\hat{X}= +\boldsymbol{y} = [y_0,y_1, y_2,\dots, y_{n-1}]^T, +$$ + +and +$$ +\boldsymbol{\beta} = [\beta_0,\beta_1, \beta_2,\dots, \beta_{n-1}]^T, +$$ + +and +$$ +\boldsymbol{\epsilon} = [\epsilon_0,\epsilon_1, \epsilon_2,\dots, \epsilon_{n-1}]^T, +$$ + +and the design matrix +$$ +\boldsymbol{X}= \begin{bmatrix} -x_{00}& x_{01} &x_{02}& \dots & \dots &x_{0,n-1}\\ -x_{10}& x_{11} &x_{12}& \dots & \dots &x_{1,n-1}\\ -x_{20}& x_{21} &x_{22}& \dots & \dots &x_{2,n-1}\\ +1& x_{0}^1 &x_{0}^2& \dots & \dots &x_{0}^{n-1}\\ +1& x_{1}^1 &x_{1}^2& \dots & \dots &x_{1}^{n-1}\\ +1& x_{2}^1 &x_{2}^2& \dots & \dots &x_{2}^{n-1}\\ \dots& \dots &\dots& \dots & \dots &\dots\\ -x_{n-1,0}& x_{n-1,1} &x_{n-1,2}& \dots & \dots &x_{n-1,n-1}\\ +1& x_{n-1}^1 &x_{n-1}^2& \dots & \dots &x_{n-1}^{n-1}\\ \end{bmatrix} $$ -and without loss of generality we rewrite again our equations as +we can rewrite our equations as $$ -\hat{y} = \hat{X}\hat{\beta}+\hat{\epsilon}. +\boldsymbol{y} = \boldsymbol{X}\boldsymbol{\beta}+\boldsymbol{\epsilon}. $$ -The left-hand side of this equation forms know. Our error vector \( \hat{\epsilon} \) and the parameter vector \( \hat{\beta} \) are our unknow quantities. How can we obtain the optimal set of \( \beta_i \) values? +The above design matrix is called a Vandermonde matrix.

    @@ -463,7 +445,7 @@ The left-hand side of this equation forms know. Our error vector \( \hat{\epsilo
  • 16
  • 17
  • ...
  • -
  • 114
  • +
  • 100
  • »
  • diff --git a/doc/pub/Regression/html/._Regression-bs008.html b/doc/pub/Regression/html/._Regression-bs008.html index 2b27ec1ca..2976e41a3 100644 --- a/doc/pub/Regression/html/._Regression-bs008.html +++ b/doc/pub/Regression/html/._Regression-bs008.html @@ -6,6 +6,7 @@ Automatically generated HTML file from DocOnce source + Data Analysis and Machine Learning: Linear Regression and more Advanced Regression Analysis @@ -40,160 +41,151 @@ Automatically generated HTML file from DocOnce source @@ -286,119 +263,109 @@ MathJax.Hub.Config({ @@ -414,22 +381,32 @@ MathJax.Hub.Config({ -

    Optimizing our parameters

    +

    Generalizing the fitting procedure as a linear algebra problem

    -We have defined the matrix \( \hat{X} \) + +

    +We are obviously not limited to the above polynomial expansions. We +could replace the various powers of \( x \) with elements of Fourier +series or instead of \( x_i^j \) we could have \( \cos{(j x_i)} \) or \( \sin{(j +x_i)} \), or time series or other orthogonal functions. For every set +of values \( y_i,x_i \) we can then generalize the equations to + $$ \begin{align*} y_0&=\beta_0x_{00}+\beta_1x_{01}+\beta_2x_{02}+\dots+\beta_{n-1}x_{0n-1}+\epsilon_0\\ y_1&=\beta_0x_{10}+\beta_1x_{11}+\beta_2x_{12}+\dots+\beta_{n-1}x_{1n-1}+\epsilon_1\\ -y_2&=\beta_0x_{20}+\beta_1x_{21}+\beta_2x_{22}+\dots+\beta_{n-1}x_{2n-1}+\epsilon_1\\ +y_2&=\beta_0x_{20}+\beta_1x_{21}+\beta_2x_{22}+\dots+\beta_{n-1}x_{2n-1}+\epsilon_2\\ \dots & \dots \\ -y_{i}&=\beta_0x_{i0}+\beta_1x_{i1}+\beta_2x_{i2}+\dots+\beta_{n-1}x_{in-1}+\epsilon_1\\ +y_{i}&=\beta_0x_{i0}+\beta_1x_{i1}+\beta_2x_{i2}+\dots+\beta_{n-1}x_{in-1}+\epsilon_i\\ \dots & \dots \\ -y_{n-1}&=\beta_0x_{n-1,0}+\beta_1x_{n-1,2}+\beta_2x_{n-1,2}+\dots+\beta_1x_{n-1,n-1}+\epsilon_{n-1}.\\ +y_{n-1}&=\beta_0x_{n-1,0}+\beta_1x_{n-1,2}+\beta_2x_{n-1,2}+\dots+\beta_{n-1}x_{n-1,n-1}+\epsilon_{n-1}.\\ \end{align*} $$ + +

    +Note that we have \( p=n \) here. The matrix is symmetric. This is generally not the case!

    @@ -458,7 +435,7 @@ $$
  • 17
  • 18
  • ...
  • -
  • 114
  • +
  • 100
  • »
  • diff --git a/doc/pub/Regression/html/._Regression-bs009.html b/doc/pub/Regression/html/._Regression-bs009.html index 08b854152..12a0d62fa 100644 --- a/doc/pub/Regression/html/._Regression-bs009.html +++ b/doc/pub/Regression/html/._Regression-bs009.html @@ -6,6 +6,7 @@ Automatically generated HTML file from DocOnce source + Data Analysis and Machine Learning: Linear Regression and more Advanced Regression Analysis @@ -40,160 +41,151 @@ Automatically generated HTML file from DocOnce source @@ -286,119 +263,109 @@ MathJax.Hub.Config({ @@ -414,24 +381,28 @@ MathJax.Hub.Config({ -

    Optimizing our parameters, more details

    +

    Generalizing the fitting procedure as a linear algebra problem

    -We well use this matrix to define the approximation \( \hat{\tilde{y}} \) via the unknown quantity \( \hat{\beta} \) as +We redefine in turn the matrix \( \boldsymbol{X} \) as $$ -\hat{\tilde{y}}= \hat{X}\hat{\beta}, +\boldsymbol{X}= +\begin{bmatrix} +x_{00}& x_{01} &x_{02}& \dots & \dots &x_{0,n-1}\\ +x_{10}& x_{11} &x_{12}& \dots & \dots &x_{1,n-1}\\ +x_{20}& x_{21} &x_{22}& \dots & \dots &x_{2,n-1}\\ +\dots& \dots &\dots& \dots & \dots &\dots\\ +x_{n-1,0}& x_{n-1,1} &x_{n-1,2}& \dots & \dots &x_{n-1,n-1}\\ +\end{bmatrix} $$ -and in order to find the optimal parameters \( \beta_i \) instead of solving the above linear algebra problem, we define a function which gives a measure of the spread between the values \( y_i \) (which represent hopefully the exact values) and the parametrized values \( \tilde{y}_i \), namely +and without loss of generality we rewrite again our equations as $$ -Q(\hat{\beta})=\sum_{i=0}^{n-1}\left(y_i-\tilde{y}_i\right)^2=\left(\hat{y}-\hat{\tilde{y}}\right)^T\left(\hat{y}-\hat{\tilde{y}}\right), +\boldsymbol{y} = \boldsymbol{X}\boldsymbol{\beta}+\boldsymbol{\epsilon}. $$ -or using the matrix \( \hat{X} \) as -$$ -Q(\hat{\beta})=\left(\hat{y}-\hat{X}\hat{\beta}\right)^T\left(\hat{y}-\hat{X}\hat{\beta}\right). -$$ +The left-hand side of this equation is kwown. Our error vector \( \boldsymbol{\epsilon} \) and the parameter vector \( \boldsymbol{\beta} \) are our unknow quantities. How can we obtain the optimal set of \( \beta_i \) values?

    @@ -461,7 +432,7 @@ $$
  • 18
  • 19
  • ...
  • -
  • 114
  • +
  • 100
  • »
  • diff --git a/doc/pub/Regression/html/._Regression-bs010.html b/doc/pub/Regression/html/._Regression-bs010.html index cefcbef9e..96f43a65d 100644 --- a/doc/pub/Regression/html/._Regression-bs010.html +++ b/doc/pub/Regression/html/._Regression-bs010.html @@ -6,6 +6,7 @@ Automatically generated HTML file from DocOnce source + Data Analysis and Machine Learning: Linear Regression and more Advanced Regression Analysis @@ -40,160 +41,151 @@ Automatically generated HTML file from DocOnce source @@ -286,119 +263,109 @@ MathJax.Hub.Config({ @@ -414,37 +381,27 @@ MathJax.Hub.Config({ -

    Interpretations and optimizing our parameters

    +

    Optimizing our parameters

    -The function +We have defined the matrix \( \boldsymbol{X} \) via the equations $$ -Q(\hat{\beta})=\left(\hat{y}-\hat{X}\hat{\beta}\right)^T\left(\hat{y}-\hat{X}\hat{\beta}\right), +\begin{align*} +y_0&=\beta_0x_{00}+\beta_1x_{01}+\beta_2x_{02}+\dots+\beta_{n-1}x_{0n-1}+\epsilon_0\\ +y_1&=\beta_0x_{10}+\beta_1x_{11}+\beta_2x_{12}+\dots+\beta_{n-1}x_{1n-1}+\epsilon_1\\ +y_2&=\beta_0x_{20}+\beta_1x_{21}+\beta_2x_{22}+\dots+\beta_{n-1}x_{2n-1}+\epsilon_1\\ +\dots & \dots \\ +y_{i}&=\beta_0x_{i0}+\beta_1x_{i1}+\beta_2x_{i2}+\dots+\beta_{n-1}x_{in-1}+\epsilon_1\\ +\dots & \dots \\ +y_{n-1}&=\beta_0x_{n-1,0}+\beta_1x_{n-1,2}+\beta_2x_{n-1,2}+\dots+\beta_{n-1}x_{n-1,n-1}+\epsilon_{n-1}.\\ +\end{align*} $$ -can be linked to the variance of the quantity \( y_i \) if we interpret the latter as the mean value of for example a numerical experiment. When linking below with the maximum likelihood approach below, we will indeed interpret \( y_i \) as a mean value -$$ -y_{i}=\langle y_i \rangle = \beta_0x_{i,0}+\beta_1x_{i,1}+\beta_2x_{i,2}+\dots+\beta_{n-1}x_{i,n-1}+\epsilon_i, -$$ - -where \( \langle y_i \rangle \) is the mean value. Keep in mind also that till now we have treated \( y_i \) as the exact value. Normally, the response (dependent or outcome) variable \( y_i \) the outcome of a numerical experiment or another type of experiment and is thus only an approximation to the true value. It is then always accompanied by an error estimate, often limited to a statistical error estimate given by the standard deviation discussed earlier. In the discussion here we will treat \( y_i \) as our exact value for the response variable. -

    -In order to find the parameters \( \beta_i \) we will then minimize the spread of \( Q(\hat{\beta}) \) by requiring -$$ -\frac{\partial Q(\hat{\beta})}{\partial \beta_j} = \frac{\partial }{\partial \beta_j}\left[ \sum_{i=0}^{n-1}\left(y_i-\beta_0x_{i,0}-\beta_1x_{i,1}-\beta_2x_{i,2}-\dots-\beta_{n-1}x_{i,n-1}\right)^2\right]=0, -$$ - -which results in -$$ -\frac{\partial Q(\hat{\beta})}{\partial \beta_j} = -2\left[ \sum_{i=0}^{n-1}x_{ij}\left(y_i-\beta_0x_{i,0}-\beta_1x_{i,1}-\beta_2x_{i,2}-\dots-\beta_{n-1}x_{i,n-1}\right)\right]=0, -$$ - -or in a matrix-vector form as -$$ -\frac{\partial Q(\hat{\beta})}{\partial \hat{\beta}} = 0 = \hat{X}^T\left( \hat{y}-\hat{X}\hat{\beta}\right). -$$ +As we noted above, we stayed with a system with the design matrix + \( \boldsymbol{X}\in {\mathbb{R}}^{n\times n} \), that is we have \( p=n \). For reasons to come later (algorithmic arguments) we will hereafter define +our matrix as \( \boldsymbol{X}\in {\mathbb{R}}^{n\times p} \), with the predictors refering to the column numbers and the entries \( n \) being the row elements.

    @@ -477,7 +434,7 @@ $$
  • 19
  • 20
  • ...
  • -
  • 114
  • +
  • 100
  • »
  • diff --git a/doc/pub/Regression/html/._Regression-bs011.html b/doc/pub/Regression/html/._Regression-bs011.html index 4156574b0..9c489cc58 100644 --- a/doc/pub/Regression/html/._Regression-bs011.html +++ b/doc/pub/Regression/html/._Regression-bs011.html @@ -6,6 +6,7 @@ Automatically generated HTML file from DocOnce source + Data Analysis and Machine Learning: Linear Regression and more Advanced Regression Analysis @@ -40,160 +41,151 @@ Automatically generated HTML file from DocOnce source @@ -286,119 +263,109 @@ MathJax.Hub.Config({ @@ -414,29 +381,93 @@ MathJax.Hub.Config({ -

    Interpretations and optimizing our parameters

    -
    -
    -

    -We can rewrite -$$ -\frac{\partial Q(\hat{\beta})}{\partial \hat{\beta}} = 0 = \hat{X}^T\left( \hat{y}-\hat{X}\hat{\beta}\right), -$$ - -as -$$ -\hat{X}^T\hat{y} = \hat{X}^T\hat{X}\hat{\beta}, -$$ - -and if the matrix \( \hat{X}^T\hat{X} \) is invertible we have the solution -$$ -\hat{\beta} =\left(\hat{X}^T\hat{X}\right)^{-1}\hat{X}^T\hat{y}. -$$ +

    Our model for the nuclear binding energies

    -

    -
    +In our introductory notes we looked at the so-called liguid drop model. Let us remind ourselves about what we did by looking at the code. +

    +We restate the parts of the code we are most interested in. +

    + + +

    # Common imports
    +import numpy as np
    +import pandas as pd
    +import matplotlib.pyplot as plt
    +from IPython.display import display
    +import os
    +
    +# Where to save the figures and data files
    +PROJECT_ROOT_DIR = "Results"
    +FIGURE_ID = "Results/FigureFiles"
    +DATA_ID = "DataFiles/"
    +
    +if not os.path.exists(PROJECT_ROOT_DIR):
    +    os.mkdir(PROJECT_ROOT_DIR)
    +
    +if not os.path.exists(FIGURE_ID):
    +    os.makedirs(FIGURE_ID)
    +
    +if not os.path.exists(DATA_ID):
    +    os.makedirs(DATA_ID)
    +
    +def image_path(fig_id):
    +    return os.path.join(FIGURE_ID, fig_id)
    +
    +def data_path(dat_id):
    +    return os.path.join(DATA_ID, dat_id)
    +
    +def save_fig(fig_id):
    +    plt.savefig(image_path(fig_id) + ".png", format='png')
    +
    +infile = open(data_path("MassEval2016.dat"),'r')
    +
    +
    +# Read the experimental data with Pandas
    +Masses = pd.read_fwf(infile, usecols=(2,3,4,6,11),
    +              names=('N', 'Z', 'A', 'Element', 'Ebinding'),
    +              widths=(1,3,5,5,5,1,3,4,1,13,11,11,9,1,2,11,9,1,3,1,12,11,1),
    +              header=39,
    +              index_col=False)
    +
    +# Extrapolated values are indicated by '#' in place of the decimal place, so
    +# the Ebinding column won't be numeric. Coerce to float and drop these entries.
    +Masses['Ebinding'] = pd.to_numeric(Masses['Ebinding'], errors='coerce')
    +Masses = Masses.dropna()
    +# Convert from keV to MeV.
    +Masses['Ebinding'] /= 1000
    +
    +# Group the DataFrame by nucleon number, A.
    +Masses = Masses.groupby('A')
    +# Find the rows of the grouped DataFrame with the maximum binding energy.
    +Masses = Masses.apply(lambda t: t[t.Ebinding==t.Ebinding.max()])
    +A = Masses['A']
    +Z = Masses['Z']
    +N = Masses['N']
    +Element = Masses['Element']
    +Energies = Masses['Ebinding']
    +
    +# Now we set up the design matrix X
    +X = np.zeros((len(A),5))
    +X[:,0] = 1
    +X[:,1] = A
    +X[:,2] = A**(2.0/3.0)
    +X[:,3] = A**(-1.0/3.0)
    +X[:,4] = A**(-1.0)
    +# Then nice printout using pandas
    +DesignMatrix = pd.DataFrame(X)
    +DesignMatrix.index = A
    +DesignMatrix.columns = ['1', 'A', 'A^(2/3)', 'A^(-1/3)', '1/A']
    +display(DesignMatrix)
    +
    +

    +With \( \boldsymbol{\beta}\in {\mathbb{R}}^{p\times 1} \), it means that we will hereafter write our equations for the approximation as +$$ +\boldsymbol{\tilde{y}}= \boldsymbol{X}\boldsymbol{\beta}, +$$ + +throughout these lectures.

    @@ -464,7 +495,7 @@ $$

  • 20
  • 21
  • ...
  • -
  • 114
  • +
  • 100
  • »
  • diff --git a/doc/pub/Regression/html/._Regression-bs012.html b/doc/pub/Regression/html/._Regression-bs012.html index 12b57d27a..26a0feef8 100644 --- a/doc/pub/Regression/html/._Regression-bs012.html +++ b/doc/pub/Regression/html/._Regression-bs012.html @@ -6,6 +6,7 @@ Automatically generated HTML file from DocOnce source + Data Analysis and Machine Learning: Linear Regression and more Advanced Regression Analysis @@ -40,160 +41,151 @@ Automatically generated HTML file from DocOnce source @@ -286,119 +263,109 @@ MathJax.Hub.Config({ @@ -414,28 +381,36 @@ MathJax.Hub.Config({ -

    Interpretations and optimizing our parameters

    +

    Optimizing our parameters, more details

    -The residuals \( \hat{\epsilon} \) are in turn given by +With the above we use the design matrix to define the approximation \( \boldsymbol{\tilde{y}} \) via the unknown quantity \( \boldsymbol{\beta} \) as $$ -\hat{\epsilon} = \hat{y}-\hat{\tilde{y}} = \hat{y}-\hat{X}\hat{\beta}, +\boldsymbol{\tilde{y}}= \boldsymbol{X}\boldsymbol{\beta}, $$ -and with +and in order to find the optimal parameters \( \beta_i \) instead of solving the above linear algebra problem, we define a function which gives a measure of the spread between the values \( y_i \) (which represent hopefully the exact values) and the parameterized values \( \tilde{y}_i \), namely $$ -\hat{X}^T\left( \hat{y}-\hat{X}\hat{\beta}\right)= 0, +C(\boldsymbol{\beta})=\frac{1}{n}\sum_{i=0}^{n-1}\left(y_i-\tilde{y}_i\right)^2=\frac{1}{n}\left\{\left(\boldsymbol{y}-\boldsymbol{\tilde{y}}\right)^T\left(\boldsymbol{y}-\boldsymbol{\tilde{y}}\right)\right\}, $$ -we have +or using the matrix \( \boldsymbol{X} \) and in a more compact matrix-vector notation as $$ -\hat{X}^T\hat{\epsilon}=\hat{X}^T\left( \hat{y}-\hat{X}\hat{\beta}\right)= 0, +C(\boldsymbol{\beta})=\frac{1}{n}\left\{\left(\boldsymbol{y}-\boldsymbol{X}^T\boldsymbol{\beta}\right)^T\left(\boldsymbol{y}-\boldsymbol{X}^T\boldsymbol{\beta}\right)\right\}. $$ -meaning that the solution for \( \hat{\beta} \) is the one which minimizes the residuals. Later we will link this with the maximum likelihood approach. +This function is one possible way to define the so-called cost function.

    +It is also common to define +the function \( Q \) as + +$$ +C(\boldsymbol{\beta})=\frac{1}{2n}\sum_{i=0}^{n-1}\left(y_i-\tilde{y}_i\right)^2, +$$ + +since when taking the first derivative with respect to the unknown parameters \( \beta \), the factor of \( 2 \) cancels out.

    @@ -466,7 +441,7 @@ meaning that the solution for \( \hat{\beta} \) is the one which minimizes the r
  • 21
  • 22
  • ...
  • -
  • 114
  • +
  • 100
  • »
  • diff --git a/doc/pub/Regression/html/._Regression-bs013.html b/doc/pub/Regression/html/._Regression-bs013.html index 84862b867..e4d1547cc 100644 --- a/doc/pub/Regression/html/._Regression-bs013.html +++ b/doc/pub/Regression/html/._Regression-bs013.html @@ -6,6 +6,7 @@ Automatically generated HTML file from DocOnce source + Data Analysis and Machine Learning: Linear Regression and more Advanced Regression Analysis @@ -40,160 +41,151 @@ Automatically generated HTML file from DocOnce source @@ -286,119 +263,109 @@ MathJax.Hub.Config({ @@ -414,21 +381,54 @@ MathJax.Hub.Config({ -

    The \( \chi^2 \) function

    +

    Interpretations and optimizing our parameters

    -Normally, the response (dependent or outcome) variable \( y_i \) the outcome of a numerical experiment or another type of experiment and is thus only an approximation to the true value. It is then always accompanied by an error estimate, often limited to a statistical error estimate given by the standard deviation discussed earlier. In the discussion here we will treat \( y_i \) as our exact value for the response variable. +The function +$$ +C(\boldsymbol{\beta})=\frac{1}{n}\left\{\left(\boldsymbol{y}-\boldsymbol{X}\boldsymbol{\beta}\right)^T\left(\boldsymbol{y}-\boldsymbol{X}\boldsymbol{\beta}\right)\right\}, +$$ + +can be linked to the variance of the quantity \( y_i \) if we interpret the latter as the mean value. +When linking below with the maximum likelihood approach below, we will indeed interpret \( y_i \) as a mean value (see exercises) +$$ +y_{i}=\langle y_i \rangle = \beta_0x_{i,0}+\beta_1x_{i,1}+\beta_2x_{i,2}+\dots+\beta_{n-1}x_{i,n-1}+\epsilon_i, +$$

    -Introducing the standard deviation \( \sigma_i \) for each measurement \( y_i \), we define now the \( \chi^2 \) function as +where \( \langle y_i \rangle \) is the mean value. Keep in mind also that +till now we have treated \( y_i \) as the exact value. Normally, the +response (dependent or outcome) variable \( y_i \) the outcome of a +numerical experiment or another type of experiment and is thus only an +approximation to the true value. It is then always accompanied by an +error estimate, often limited to a statistical error estimate given by +the standard deviation discussed earlier. In the discussion here we +will treat \( y_i \) as our exact value for the response variable. + +

    +In order to find the parameters \( \beta_i \) we will then minimize the spread of \( C(\boldsymbol{\beta}) \), that is we are going to solve the problem $$ -\chi^2(\hat{\beta})=\sum_{i=0}^{n-1}\frac{\left(y_i-\tilde{y}_i\right)^2}{\sigma_i^2}=\left(\hat{y}-\hat{\tilde{y}}\right)^T\frac{1}{\hat{\Sigma^2}}\left(\hat{y}-\hat{\tilde{y}}\right), +{\displaystyle \min_{\boldsymbol{\beta}\in +{\mathbb{R}}^{p}}}\frac{1}{n}\left\{\left(\boldsymbol{y}-\boldsymbol{X}\boldsymbol{\beta}\right)^T\left(\boldsymbol{y}-\boldsymbol{X}\boldsymbol{\beta}\right)\right\}. $$ -where the matrix \( \hat{\Sigma} \) is a diagonal matrix with \( \sigma_i \) as matrix elements. +In practical terms it means we will require +$$ +\frac{\partial C(\boldsymbol{\beta})}{\partial \beta_j} = \frac{\partial }{\partial \beta_j}\left[ \frac{1}{n}\sum_{i=0}^{n-1}\left(y_i-\beta_0x_{i,0}-\beta_1x_{i,1}-\beta_2x_{i,2}-\dots-\beta_{n-1}x_{i,n-1}\right)^2\right]=0, +$$ + +which results in +$$ +\frac{\partial C(\boldsymbol{\beta})}{\partial \beta_j} = -\frac{2}{n}\left[ \sum_{i=0}^{n-1}x_{ij}\left(y_i-\beta_0x_{i,0}-\beta_1x_{i,1}-\beta_2x_{i,2}-\dots-\beta_{n-1}x_{i,n-1}\right)\right]=0, +$$ + +or in a matrix-vector form as +$$ +\frac{\partial C(\boldsymbol{\beta})}{\partial \boldsymbol{\beta}} = 0 = \boldsymbol{X}^T\left( \boldsymbol{y}-\boldsymbol{X}\boldsymbol{\beta}\right). +$$

    @@ -461,7 +461,7 @@ where the matrix \( \hat{\Sigma} \) is a diagonal matrix with \( \sigma_i \) as
  • 22
  • 23
  • ...
  • -
  • 114
  • +
  • 100
  • »
  • diff --git a/doc/pub/Regression/html/._Regression-bs014.html b/doc/pub/Regression/html/._Regression-bs014.html index 628aa970c..fd3112740 100644 --- a/doc/pub/Regression/html/._Regression-bs014.html +++ b/doc/pub/Regression/html/._Regression-bs014.html @@ -6,6 +6,7 @@ Automatically generated HTML file from DocOnce source + Data Analysis and Machine Learning: Linear Regression and more Advanced Regression Analysis @@ -40,160 +41,151 @@ Automatically generated HTML file from DocOnce source @@ -286,119 +263,109 @@ MathJax.Hub.Config({ @@ -414,28 +381,38 @@ MathJax.Hub.Config({ -

    The \( \chi^2 \) function

    +

    Interpretations and optimizing our parameters

    +We can rewrite +$$ +\frac{\partial C(\boldsymbol{\beta})}{\partial \boldsymbol{\beta}} = 0 = \boldsymbol{X}^T\left( \boldsymbol{y}-\boldsymbol{X}\boldsymbol{\beta}\right), +$$ + +as +$$ +\boldsymbol{X}^T\boldsymbol{y} = \boldsymbol{X}^T\boldsymbol{X}\boldsymbol{\beta}, +$$ + +and if the matrix \( \boldsymbol{X}^T\boldsymbol{X} \) is invertible we have the solution +$$ +\boldsymbol{\beta} =\left(\boldsymbol{X}^T\boldsymbol{X}\right)^{-1}\boldsymbol{X}^T\boldsymbol{y}. +$$

    -In order to find the parameters \( \beta_i \) we will then minimize the spread of \( \chi^2(\hat{\beta}) \) by requiring -$$ -\frac{\partial \chi^2(\hat{\beta})}{\partial \beta_j} = \frac{\partial }{\partial \beta_j}\left[ \sum_{i=0}^{n-1}\left(\frac{y_i-\beta_0x_{i,0}-\beta_1x_{i,1}-\beta_2x_{i,2}-\dots-\beta_{n-1}x_{i,n-1}}{\sigma_i}\right)^2\right]=0, -$$ +We note also that since our design matrix is defined as \( \boldsymbol{X}\in +{\mathbb{R}}^{n\times p} \), the product \( \boldsymbol{X}^T\boldsymbol{X} \in +{\mathbb{R}}^{p\times p} \). In the above case we have that \( p \ll n \), +in our case \( p=5 \) meaning that we end up with inverting a small +\( 5\times 5 \) matrix. This is a rather common situation, in many cases we end up with low-dimensional +matrices to invert. The methods discussed here and for many other +supervised learning algorithms like classification with logistic +regression or support vector machines, exhibit dimensionalities which +allow for the usage of direct linear algebra methods such as LU decomposition or Singular Value Decomposition (SVD) for finding the inverse of the matrix +\( \boldsymbol{X}^T\boldsymbol{X} \). -which results in -$$ -\frac{\partial \chi^2(\hat{\beta})}{\partial \beta_j} = -2\left[ \sum_{i=0}^{n-1}\frac{x_{ij}}{\sigma_i}\left(\frac{y_i-\beta_0x_{i,0}-\beta_1x_{i,1}-\beta_2x_{i,2}-\dots-\beta_{n-1}x_{i,n-1}}{\sigma_i}\right)\right]=0, -$$ - -or in a matrix-vector form as -$$ -\frac{\partial \chi^2(\hat{\beta})}{\partial \hat{\beta}} = 0 = \hat{A}^T\left( \hat{b}-\hat{A}\hat{\beta}\right). -$$ - -where we have defined the matrix \( \hat{A} =\hat{X}/\hat{\Sigma} \) with matrix elements \( a_{ij} = x_{ij}/\sigma_i \) and the vector \( \hat{b} \) with elements \( b_i = y_i/\sigma_i \). +

    @@ -466,7 +443,7 @@ where we have defined the matrix \( \hat{A} =\hat{X}/\hat{\Sigma} \) with matrix
  • 23
  • 24
  • ...
  • -
  • 114
  • +
  • 100
  • »
  • diff --git a/doc/pub/Regression/html/._Regression-bs015.html b/doc/pub/Regression/html/._Regression-bs015.html index e54edd4e9..82a9581f1 100644 --- a/doc/pub/Regression/html/._Regression-bs015.html +++ b/doc/pub/Regression/html/._Regression-bs015.html @@ -6,6 +6,7 @@ Automatically generated HTML file from DocOnce source + Data Analysis and Machine Learning: Linear Regression and more Advanced Regression Analysis @@ -40,160 +41,151 @@ Automatically generated HTML file from DocOnce source @@ -286,119 +263,109 @@ MathJax.Hub.Config({ @@ -414,30 +381,35 @@ MathJax.Hub.Config({ -

    The \( \chi^2 \) function

    +

    Interpretations and optimizing our parameters

    +The residuals \( \boldsymbol{\epsilon} \) are in turn given by +$$ +\boldsymbol{\epsilon} = \boldsymbol{y}-\boldsymbol{\tilde{y}} = \boldsymbol{y}-\boldsymbol{X}\boldsymbol{\beta}, +$$ + +and with +$$ +\boldsymbol{X}^T\left( \boldsymbol{y}-\boldsymbol{X}\boldsymbol{\beta}\right)= 0, +$$ + +we have +$$ +\boldsymbol{X}^T\boldsymbol{\epsilon}=\boldsymbol{X}^T\left( \boldsymbol{y}-\boldsymbol{X}\boldsymbol{\beta}\right)= 0, +$$ + +meaning that the solution for \( \boldsymbol{\beta} \) is the one which minimizes the residuals. Later we will link this with the maximum likelihood approach.

    -We can rewrite -$$ -\frac{\partial \chi^2(\hat{\beta})}{\partial \hat{\beta}} = 0 = \hat{A}^T\left( \hat{b}-\hat{A}\hat{\beta}\right), -$$ - -as -$$ -\hat{A}^T\hat{b} = \hat{A}^T\hat{A}\hat{\beta}, -$$ - -and if the matrix \( \hat{A}^T\hat{A} \) is invertible we have the solution -$$ -\hat{\beta} =\left(\hat{A}^T\hat{A}\right)^{-1}\hat{A}^T\hat{b}. -$$

    +

    +Let us now return to our nuclear binding energies and simply code the above equations. +

    @@ -464,7 +436,7 @@ $$

  • 24
  • 25
  • ...
  • -
  • 114
  • +
  • 100
  • »
  • diff --git a/doc/pub/Regression/html/._Regression-bs016.html b/doc/pub/Regression/html/._Regression-bs016.html index e23ad4851..45a289cd6 100644 --- a/doc/pub/Regression/html/._Regression-bs016.html +++ b/doc/pub/Regression/html/._Regression-bs016.html @@ -6,6 +6,7 @@ Automatically generated HTML file from DocOnce source + Data Analysis and Machine Learning: Linear Regression and more Advanced Regression Analysis @@ -40,160 +41,151 @@ Automatically generated HTML file from DocOnce source @@ -286,119 +263,109 @@ MathJax.Hub.Config({ @@ -414,35 +381,45 @@ MathJax.Hub.Config({ -

    The \( \chi^2 \) function

    -
    -
    -

    +

    Own code for Ordinary Least Squares

    -If we then introduce the matrix -$$ -\hat{H} = \left(\hat{A}^T\hat{A}\right)^{-1}, -$$ +It is rather straightforward to implement the matrix inversion and obtain the parameters \( \boldsymbol{\beta} \). After having defined the matrix \( \boldsymbol{X} \) we simply need to +write +

    -we have then the following expression for the parameters \( \beta_j \) (the matrix elements of \( \hat{H} \) are \( h_{ij} \)) -$$ -\beta_j = \sum_{k=0}^{p-1}h_{jk}\sum_{i=0}^{n-1}\frac{y_i}{\sigma_i}\frac{x_{ik}}{\sigma_i} = \sum_{k=0}^{p-1}h_{jk}\sum_{i=0}^{n-1}b_ia_{ik} -$$ - -We state without proof the expression for the uncertainty in the parameters \( \beta_j \) as (we leave this as an exercise) -$$ -\sigma^2(\beta_j) = \sum_{i=0}^{n-1}\sigma_i^2\left( \frac{\partial \beta_j}{\partial y_i}\right)^2, -$$ - -resulting in -$$ -\sigma^2(\beta_j) = \left(\sum_{k=0}^{p-1}h_{jk}\sum_{i=0}^{n-1}a_{ik}\right)\left(\sum_{l=0}^{p-1}h_{jl}\sum_{m=0}^{n-1}a_{ml}\right) = h_{jj}! -$$ -

    -
    + +
    # matrix inversion to find beta
    +beta = np.linalg.inv(X.T.dot(X)).dot(X.T).dot(Energies)
    +# and then make the prediction
    +ytilde = X @ beta
    +
    +

    +Alternatively, you can use the least squares functionality in Numpy as +

    + +

    fit = np.linalg.lstsq(X, Energies, rcond =None)[0]
    +ytildenp = np.dot(fit,X.T)
    +
    +

    +And finally we plot our fit with and compare with data +

    + +

    Masses['Eapprox']  = ytilde
    +# Generate a plot comparing the experimental with the fitted values values.
    +fig, ax = plt.subplots()
    +ax.set_xlabel(r'$A = N + Z$')
    +ax.set_ylabel(r'$E_\mathrm{bind}\,/\mathrm{MeV}$')
    +ax.plot(Masses['A'], Masses['Ebinding'], alpha=0.7, lw=2,
    +            label='Ame2016')
    +ax.plot(Masses['A'], Masses['Eapprox'], alpha=0.7, lw=2, c='m',
    +            label='Fit')
    +ax.legend()
    +save_fig("Masses2016OLS")
    +plt.show()
    +

    @@ -469,7 +446,7 @@ $$

  • 25
  • 26
  • ...
  • -
  • 114
  • +
  • 100
  • »
  • diff --git a/doc/pub/Regression/html/._Regression-bs017.html b/doc/pub/Regression/html/._Regression-bs017.html index 92991e8ab..0ee4b2985 100644 --- a/doc/pub/Regression/html/._Regression-bs017.html +++ b/doc/pub/Regression/html/._Regression-bs017.html @@ -6,6 +6,7 @@ Automatically generated HTML file from DocOnce source + Data Analysis and Machine Learning: Linear Regression and more Advanced Regression Analysis @@ -40,160 +41,151 @@ Automatically generated HTML file from DocOnce source @@ -286,119 +263,109 @@ MathJax.Hub.Config({ @@ -414,28 +381,44 @@ MathJax.Hub.Config({ -

    The \( \chi^2 \) function

    -
    -
    -

    -The first step here is to approximate the function \( y \) with a first-order polynomial, that is we write -$$ -y=y(x) \rightarrow y(x_i) \approx \beta_0+\beta_1 x_i. -$$ +

    Adding error analysis and training set up

    -By computing the derivatives of \( \chi^2 \) with respect to \( \beta_0 \) and \( \beta_1 \) show that these are given by -$$ -\frac{\partial \chi^2(\hat{\beta})}{\partial \beta_0} = -2\left[ \sum_{i=0}^{n-1}\left(\frac{y_i-\beta_0-\beta_1x_{i}}{\sigma_i^2}\right)\right]=0, -$$ +

    +We can easily test our fit by computing the \( R2 \) score that we discussed in connection with the functionality of _Scikit_Learn_ in the introductory slides. +Since we are not using _Scikit-Learn here we can define our own \( R2 \) function as +

    -and -$$ -\frac{\partial \chi^2(\hat{\beta})}{\partial \beta_0} = -2\left[ \sum_{i=0}^{n-1}x_i\left(\frac{y_i-\beta_0-\beta_1x_{i}}{\sigma_i^2}\right)\right]=0. -$$ -

    -
    + +
    def R2(y_data, y_model):
    +    return 1 - np.sum((y_data - y_model) ** 2) / np.sum((y_data - np.mean(y_model)) ** 2)
    +
    +

    +and we would be using it as +

    + +

    print(R2(Energies,ytilde))
    +
    +

    +We can easily add our MSE score as +

    + +

    def MSE(y_data,y_model):
    +    n = np.size(y_model)
    +    return np.sum((y_data-y_model)**2)/n
    +
    +print(MSE(Energies,ytilde))
    +
    +

    +and finally the relative error as +

    + + +

    def RelativeError(y_data,y_model):
    +    return abs((y_data-y_model)/y_data)
    +print(RelativeError(Energies, ytilde))
    +

    @@ -462,7 +445,7 @@ $$

  • 26
  • 27
  • ...
  • -
  • 114
  • +
  • 100
  • »
  • diff --git a/doc/pub/Regression/html/._Regression-bs018.html b/doc/pub/Regression/html/._Regression-bs018.html index 6af2e59e2..7a9d6f4d6 100644 --- a/doc/pub/Regression/html/._Regression-bs018.html +++ b/doc/pub/Regression/html/._Regression-bs018.html @@ -6,6 +6,7 @@ Automatically generated HTML file from DocOnce source + Data Analysis and Machine Learning: Linear Regression and more Advanced Regression Analysis @@ -40,160 +41,151 @@ Automatically generated HTML file from DocOnce source @@ -286,119 +263,109 @@ MathJax.Hub.Config({ @@ -420,40 +387,26 @@ MathJax.Hub.Config({

    -For a linear fit we don't need to invert a matrix!! -Defining -$$ -\gamma = \sum_{i=0}^{n-1}\frac{1}{\sigma_i^2}, -$$ - - -$$ -\gamma_x = \sum_{i=0}^{n-1}\frac{x_{i}}{\sigma_i^2}, -$$ - -$$ -\gamma_y = \sum_{i=0}^{n-1}\left(\frac{y_i}{\sigma_i^2}\right), -$$ - -$$ -\gamma_{xx} = \sum_{i=0}^{n-1}\frac{x_ix_{i}}{\sigma_i^2}, -$$ - -$$ -\gamma_{xy} = \sum_{i=0}^{n-1}\frac{y_ix_{i}}{\sigma_i^2}, -$$ - -we obtain -$$ -\beta_0 = \frac{\gamma_{xx}\gamma_y-\gamma_x\gamma_y}{\gamma\gamma_{xx}-\gamma_x^2}, -$$ - -$$ -\beta_1 = \frac{\gamma_{xy}\gamma-\gamma_x\gamma_y}{\gamma\gamma_{xx}-\gamma_x^2}. -$$ +Normally, the response (dependent or outcome) variable \( y_i \) is the +outcome of a numerical experiment or another type of experiment and is +thus only an approximation to the true value. It is then always +accompanied by an error estimate, often limited to a statistical error +estimate given by the standard deviation discussed earlier. In the +discussion here we will treat \( y_i \) as our exact value for the +response variable. + +

    +Introducing the standard deviation \( \sigma_i \) for each measurement +\( y_i \), we define now the \( \chi^2 \) function (omitting the \( 1/n \) term) +as + +$$ +\chi^2(\boldsymbol{\beta})=\frac{1}{n}\sum_{i=0}^{n-1}\frac{\left(y_i-\tilde{y}_i\right)^2}{\sigma_i^2}=\frac{1}{n}\left\{\left(\boldsymbol{y}-\boldsymbol{\tilde{y}}\right)^T\frac{1}{\boldsymbol{\Sigma^2}}\left(\boldsymbol{y}-\boldsymbol{\tilde{y}}\right)\right\}, +$$ + +where the matrix \( \boldsymbol{\Sigma} \) is a diagonal matrix with \( \sigma_i \) as matrix elements.

    -This approach (different linear and non-linear regression) suffers often from both being underdetermined and overdetermined in the unknown coefficients \( \beta_i \). A better approach is to use the Singular Value Decomposition (SVD) method discussed below. Or using Lasso and Ridge regression. See below.

    @@ -484,7 +437,7 @@ This approach (different linear and non-linear regression) suffers often from bo
  • 27
  • 28
  • ...
  • -
  • 114
  • +
  • 100
  • »
  • diff --git a/doc/pub/Regression/html/._Regression-bs019.html b/doc/pub/Regression/html/._Regression-bs019.html index 000421535..3be490b51 100644 --- a/doc/pub/Regression/html/._Regression-bs019.html +++ b/doc/pub/Regression/html/._Regression-bs019.html @@ -6,6 +6,7 @@ Automatically generated HTML file from DocOnce source + Data Analysis and Machine Learning: Linear Regression and more Advanced Regression Analysis @@ -40,160 +41,151 @@ Automatically generated HTML file from DocOnce source @@ -286,119 +263,109 @@ MathJax.Hub.Config({ @@ -414,42 +381,31 @@ MathJax.Hub.Config({ -

    Simple regression model

    -We are now ready to write our first program which aims at solving the above linear regression equations. We start with data we have produced ourselves, in this case normally distributed random numbers along the \( x \)-axis. These numbers define then the value of a function \( y(x)=4+3x+N(0,1) \). Thereafter we order the \( x \) values and employ our linear regression algorithm to set up the best fit. Here we find it useful to use the numpy function \( c\_ \) arrays where arrays are stacked along their last axis after being upgraded to at least two dimensions with ones post-pended to the shape. The following examples help in understanding what happens +

    The \( \chi^2 \) function

    +
    +
    +

    +

    +In order to find the parameters \( \beta_i \) we will then minimize the spread of \( \chi^2(\boldsymbol{\beta}) \) by requiring +$$ +\frac{\partial \chi^2(\boldsymbol{\beta})}{\partial \beta_j} = \frac{\partial }{\partial \beta_j}\left[ \frac{1}{n}\sum_{i=0}^{n-1}\left(\frac{y_i-\beta_0x_{i,0}-\beta_1x_{i,1}-\beta_2x_{i,2}-\dots-\beta_{n-1}x_{i,n-1}}{\sigma_i}\right)^2\right]=0, +$$ - -

    import numpy as np
    -print(np.c_[np.array([1,2,3]), np.array([4,5,6])])
    -print(np.c_[np.array([[1,2,3]]), 0, 0, np.array([[4,5,6]])])
    -
    -

    +which results in +$$ +\frac{\partial \chi^2(\boldsymbol{\beta})}{\partial \beta_j} = -\frac{2}{n}\left[ \sum_{i=0}^{n-1}\frac{x_{ij}}{\sigma_i}\left(\frac{y_i-\beta_0x_{i,0}-\beta_1x_{i,1}-\beta_2x_{i,2}-\dots-\beta_{n-1}x_{i,n-1}}{\sigma_i}\right)\right]=0, +$$ - -

    # Importing various packages
    -from random import random, seed
    -import numpy as np
    -import matplotlib.pyplot as plt
    +or in a matrix-vector form as
    +$$
    +\frac{\partial \chi^2(\boldsymbol{\beta})}{\partial \boldsymbol{\beta}} = 0 = \boldsymbol{A}^T\left( \boldsymbol{b}-\boldsymbol{A}\boldsymbol{\beta}\right).  
    +$$
     
    -x = 2*np.random.rand(100,1)
    -y = 4+3*x+np.random.randn(100,1)
    +where we have defined the matrix \( \boldsymbol{A} =\boldsymbol{X}/\boldsymbol{\Sigma} \) with matrix elements \( a_{ij} = x_{ij}/\sigma_i \) and the vector \( \boldsymbol{b} \) with elements \( b_i = y_i/\sigma_i \).
    +
    +
    -xb = np.c_[np.ones((100,1)), x] -beta = np.linalg.inv(xb.T.dot(xb)).dot(xb.T).dot(y) -xnew = np.array([[0],[2]]) -xbnew = np.c_[np.ones((2,1)), xnew] -ypredict = xbnew.dot(beta) - -plt.plot(xnew, ypredict, "r-") -plt.plot(x, y ,'ro') -plt.axis([0,2.0,0, 15.0]) -plt.xlabel(r'$x$') -plt.ylabel(r'$y$') -plt.title(r'Linear Regression') -plt.show() -
    -

    -We see that, as expected, a linear fit gives a seemingly (from the graph) good representation of the data.

    @@ -477,7 +433,7 @@ We see that, as expected, a linear fit gives a seemingly (from the graph) good r

  • 28
  • 29
  • ...
  • -
  • 114
  • +
  • 100
  • »
  • diff --git a/doc/pub/Regression/html/._Regression-bs020.html b/doc/pub/Regression/html/._Regression-bs020.html index b22404498..ea9d4bb03 100644 --- a/doc/pub/Regression/html/._Regression-bs020.html +++ b/doc/pub/Regression/html/._Regression-bs020.html @@ -6,6 +6,7 @@ Automatically generated HTML file from DocOnce source + Data Analysis and Machine Learning: Linear Regression and more Advanced Regression Analysis @@ -40,160 +41,151 @@ Automatically generated HTML file from DocOnce source @@ -286,119 +263,109 @@ MathJax.Hub.Config({ @@ -414,34 +381,30 @@ MathJax.Hub.Config({ -

    Simple regression model, now using scikit-learn

    +

    The \( \chi^2 \) function

    +
    +
    +

    -We can repeat the above algorithm using scikit-learn as follows -

    +We can rewrite +$$ +\frac{\partial \chi^2(\boldsymbol{\beta})}{\partial \boldsymbol{\beta}} = 0 = \boldsymbol{A}^T\left( \boldsymbol{b}-\boldsymbol{A}\boldsymbol{\beta}\right), +$$ - -

    # Importing various packages
    -from random import random, seed
    -import numpy as np
    -import matplotlib.pyplot as plt
    -from sklearn.linear_model import LinearRegression
    +as
    +$$
    +\boldsymbol{A}^T\boldsymbol{b} = \boldsymbol{A}^T\boldsymbol{A}\boldsymbol{\beta},  
    +$$
    +
    +and if the matrix \( \boldsymbol{A}^T\boldsymbol{A} \) is invertible we have the solution
    +$$
    +\boldsymbol{\beta} =\left(\boldsymbol{A}^T\boldsymbol{A}\right)^{-1}\boldsymbol{A}^T\boldsymbol{b}.
    +$$
    +
    +
    -x = 2*np.random.rand(100,1) -y = 4+3*x+np.random.randn(100,1) -linreg = LinearRegression() -linreg.fit(x,y) -xnew = np.array([[0],[2]]) -ypredict = linreg.predict(xnew) -plt.plot(xnew, ypredict, "r-") -plt.plot(x, y ,'ro') -plt.axis([0,2.0,0, 15.0]) -plt.xlabel(r'$x$') -plt.ylabel(r'$y$') -plt.title(r'Random numbers ') -plt.show() -

    @@ -468,7 +431,7 @@ plt.show()

  • 29
  • 30
  • ...
  • -
  • 114
  • +
  • 100
  • »
  • diff --git a/doc/pub/Regression/html/._Regression-bs021.html b/doc/pub/Regression/html/._Regression-bs021.html index 367def1a7..89068013d 100644 --- a/doc/pub/Regression/html/._Regression-bs021.html +++ b/doc/pub/Regression/html/._Regression-bs021.html @@ -6,6 +6,7 @@ Automatically generated HTML file from DocOnce source + Data Analysis and Machine Learning: Linear Regression and more Advanced Regression Analysis @@ -40,160 +41,151 @@ Automatically generated HTML file from DocOnce source @@ -286,119 +263,109 @@ MathJax.Hub.Config({ @@ -414,71 +381,35 @@ MathJax.Hub.Config({ -

    Simple linear regression model using scikit-learn

    +

    The \( \chi^2 \) function

    +
    +
    +

    -We start with perhaps our simplest possible example, using scikit-learn to perform linear regression analysis on a data set produced by us. -What follows is a simple Python code where we have defined function \( y \) in terms of the variable \( x \). Both are defined as vectors of dimension \( 1\times 100 \). The entries to the vector \( \hat{x} \) are given by random numbers generated with a uniform distribution with entries \( x_i \in [0,1] \) (more about probability distribution functions later). These values are then used to define a function \( y(x) \) (tabulated again as a vector) with a linear dependence on \( x \) plus a random noise added via the normal distribution. - -

    -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 \) - +If we then introduce the matrix $$ -y = 2x+N(0,1), +\boldsymbol{H} = \left(\boldsymbol{A}^T\boldsymbol{A}\right)^{-1}, $$ -

    -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. +we have then the following expression for the parameters \( \beta_j \) (the matrix elements of \( \boldsymbol{H} \) are \( h_{ij} \)) +$$ +\beta_j = \sum_{k=0}^{p-1}h_{jk}\sum_{i=0}^{n-1}\frac{y_i}{\sigma_i}\frac{x_{ik}}{\sigma_i} = \sum_{k=0}^{p-1}h_{jk}\sum_{i=0}^{n-1}b_ia_{ik} +$$ -

    -For plotting we use the Python package -matplotlib which produces publication -quality figures. Feel free to explore the extensive -gallery 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. +We state without proof the expression for the uncertainty in the parameters \( \beta_j \) as (we leave this as an exercise) +$$ +\sigma^2(\beta_j) = \sum_{i=0}^{n-1}\sigma_i^2\left( \frac{\partial \beta_j}{\partial y_i}\right)^2, +$$ -

    -The Python code follows here. -

    +resulting in +$$ +\sigma^2(\beta_j) = \left(\sum_{k=0}^{p-1}h_{jk}\sum_{i=0}^{n-1}a_{ik}\right)\left(\sum_{l=0}^{p-1}h_{jl}\sum_{m=0}^{n-1}a_{ml}\right) = h_{jj}! +$$ +

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

    @@ -505,7 +436,7 @@ plt.show()

  • 30
  • 31
  • ...
  • -
  • 114
  • +
  • 100
  • »
  • diff --git a/doc/pub/Regression/html/._Regression-bs022.html b/doc/pub/Regression/html/._Regression-bs022.html index ac0d72217..968b64515 100644 --- a/doc/pub/Regression/html/._Regression-bs022.html +++ b/doc/pub/Regression/html/._Regression-bs022.html @@ -6,6 +6,7 @@ Automatically generated HTML file from DocOnce source + Data Analysis and Machine Learning: Linear Regression and more Advanced Regression Analysis @@ -40,160 +41,151 @@ Automatically generated HTML file from DocOnce source @@ -286,119 +263,109 @@ MathJax.Hub.Config({ @@ -414,24 +381,27 @@ MathJax.Hub.Config({ -

    Simple linear regression model

    - -

    -This example serves several aims. It allows us to demonstrate several -aspects of data analysis and later machine learning algorithms. The -immediate visualization shows that our linear fit is not -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 - +

    The \( \chi^2 \) function

    +
    +
    +

    +The first step here is to approximate the function \( y \) with a first-order polynomial, that is we write $$ -y = 10x+0.01 \times N(0,1), +y=y(x) \rightarrow y(x_i) \approx \beta_0+\beta_1 x_i. $$ -

    -where \( x \) is defined as before. +By computing the derivatives of \( \chi^2 \) with respect to \( \beta_0 \) and \( \beta_1 \) show that these are given by +$$ +\frac{\partial \chi^2(\boldsymbol{\beta})}{\partial \beta_0} = -2\left[ \frac{1}{n}\sum_{i=0}^{n-1}\left(\frac{y_i-\beta_0-\beta_1x_{i}}{\sigma_i^2}\right)\right]=0, +$$ + +and +$$ +\frac{\partial \chi^2(\boldsymbol{\beta})}{\partial \beta_1} = -\frac{2}{n}\left[ \sum_{i=0}^{n-1}x_i\left(\frac{y_i-\beta_0-\beta_1x_{i}}{\sigma_i^2}\right)\right]=0. +$$ +

    +
    +

    @@ -459,7 +429,7 @@ where \( x \) is defined as before.

  • 31
  • 32
  • ...
  • -
  • 114
  • +
  • 100
  • »
  • diff --git a/doc/pub/Regression/html/._Regression-bs023.html b/doc/pub/Regression/html/._Regression-bs023.html index f0ce692c0..301726fe5 100644 --- a/doc/pub/Regression/html/._Regression-bs023.html +++ b/doc/pub/Regression/html/._Regression-bs023.html @@ -6,6 +6,7 @@ Automatically generated HTML file from DocOnce source + Data Analysis and Machine Learning: Linear Regression and more Advanced Regression Analysis @@ -40,160 +41,151 @@ Automatically generated HTML file from DocOnce source @@ -286,119 +263,109 @@ MathJax.Hub.Config({ @@ -414,15 +381,61 @@ MathJax.Hub.Config({ -

    Less noise

    +

    The \( \chi^2 \) function

    +
    +
    +

    -Does the fit look better? Indeed, by -reducing the role of the normal distribution we see immediately that -our linear prediction seemingly reproduces better the training -set. However, this testing 'by the eye' is obviouly not satisfactory in the -long run. Here we have only defined the training data and our model, and -have not discussed a more rigorous approach to the cost function. +For a linear fit (a first-order polynomial) we don't need to invert a matrix!! +Defining +$$ +\gamma = \sum_{i=0}^{n-1}\frac{1}{\sigma_i^2}, +$$ + + +$$ +\gamma_x = \sum_{i=0}^{n-1}\frac{x_{i}}{\sigma_i^2}, +$$ + + +$$ +\gamma_y = \sum_{i=0}^{n-1}\left(\frac{y_i}{\sigma_i^2}\right), +$$ + + +$$ +\gamma_{xx} = \sum_{i=0}^{n-1}\frac{x_ix_{i}}{\sigma_i^2}, +$$ + + +$$ +\gamma_{xy} = \sum_{i=0}^{n-1}\frac{y_ix_{i}}{\sigma_i^2}, +$$ + +

    +we obtain + +$$ +\beta_0 = \frac{\gamma_{xx}\gamma_y-\gamma_x\gamma_y}{\gamma\gamma_{xx}-\gamma_x^2}, +$$ + + +$$ +\beta_1 = \frac{\gamma_{xy}\gamma-\gamma_x\gamma_y}{\gamma\gamma_{xx}-\gamma_x^2}. +$$ + +

    +This approach (different linear and non-linear regression) suffers +often from both being underdetermined and overdetermined in the +unknown coefficients \( \beta_i \). A better approach is to use the +Singular Value Decomposition (SVD) method discussed below. Or using +Lasso and Ridge regression. See below. + +

    +

    +
    +

    @@ -450,7 +463,7 @@ have not discussed a more rigorous approach to the cost function.

  • 32
  • 33
  • ...
  • -
  • 114
  • +
  • 100
  • »
  • diff --git a/doc/pub/Regression/html/._Regression-bs024.html b/doc/pub/Regression/html/._Regression-bs024.html index 28f29803d..2a1d4586f 100644 --- a/doc/pub/Regression/html/._Regression-bs024.html +++ b/doc/pub/Regression/html/._Regression-bs024.html @@ -6,6 +6,7 @@ Automatically generated HTML file from DocOnce source + Data Analysis and Machine Learning: Linear Regression and more Advanced Regression Analysis @@ -40,160 +41,151 @@ Automatically generated HTML file from DocOnce source @@ -286,119 +263,109 @@ MathJax.Hub.Config({ @@ -414,24 +381,27 @@ MathJax.Hub.Config({ -

    How to study our fits

    +

    Fitting an Equation of State for Dense Nuclear Matter

    -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 - -$$ \chi^2 = \frac{1}{n} -\sum_{i=0}^{n-1}\frac{(y_i-\tilde{y}_i)^2}{\sigma_i^2}, -$$ +Before we continue, let us introduce yet another example. We are going to fit the +nuclear equation of state using results from many-body calculations. +The equation of state we have made available here, as function of +density, has been derived using modern nucleon-nucleon potentials with +the addition of three-body +forces. This +time the file is presented as a standard csv file.

    -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. +The beginning of the Python code here is similar to what you have seen before, +with the same initializations and declarations. We use also pandas +again, rather extensively in order to organize our data. + +

    +The difference now is that we use Scikit-Learn's regression tools +instead of our own matrix inversion implementation. Furthermore, we +sneak in Ridge regression (to be discussed below) which includes a +hyperparameter \( \lambda \), also to be explained below.

    @@ -459,7 +429,7 @@ dimensionless.

  • 33
  • 34
  • ...
  • -
  • 114
  • +
  • 100
  • »
  • diff --git a/doc/pub/Regression/html/._Regression-bs025.html b/doc/pub/Regression/html/._Regression-bs025.html index 39a81d6a0..336b45fca 100644 --- a/doc/pub/Regression/html/._Regression-bs025.html +++ b/doc/pub/Regression/html/._Regression-bs025.html @@ -6,6 +6,7 @@ Automatically generated HTML file from DocOnce source + Data Analysis and Machine Learning: Linear Regression and more Advanced Regression Analysis @@ -40,160 +41,151 @@ Automatically generated HTML file from DocOnce source @@ -286,119 +263,109 @@ MathJax.Hub.Config({ @@ -414,23 +381,105 @@ MathJax.Hub.Config({ -

    Minimizing the cost function

    +

    The code

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

    # Common imports
    +import os
    +import numpy as np
    +import pandas as pd
    +import matplotlib.pyplot as plt
    +import matplotlib.pyplot as plt
    +import sklearn.linear_model as skl
    +from sklearn.metrics import mean_squared_error, r2_score, mean_absolute_error
    +
    +# Where to save the figures and data files
    +PROJECT_ROOT_DIR = "Results"
    +FIGURE_ID = "Results/FigureFiles"
    +DATA_ID = "DataFiles/"
    +
    +if not os.path.exists(PROJECT_ROOT_DIR):
    +    os.mkdir(PROJECT_ROOT_DIR)
    +
    +if not os.path.exists(FIGURE_ID):
    +    os.makedirs(FIGURE_ID)
    +
    +if not os.path.exists(DATA_ID):
    +    os.makedirs(DATA_ID)
    +
    +def image_path(fig_id):
    +    return os.path.join(FIGURE_ID, fig_id)
    +
    +def data_path(dat_id):
    +    return os.path.join(DATA_ID, dat_id)
    +
    +def save_fig(fig_id):
    +    plt.savefig(image_path(fig_id) + ".png", format='png')
    +
    +infile = open(data_path("EoS.csv"),'r')
    +
    +# Read the EoS data as  csv file and organize the data into two arrays with density and energies
    +EoS = pd.read_csv(infile, names=('Density', 'Energy'))
    +EoS['Energy'] = pd.to_numeric(EoS['Energy'], errors='coerce')
    +EoS = EoS.dropna()
    +Energies = EoS['Energy']
    +Density = EoS['Density']
    +#  The design matrix now as function of various polytrops
    +X = np.zeros((len(Density),4))
    +X[:,3] = Density**(4.0/3.0)
    +X[:,2] = Density
    +X[:,1] = Density**(2.0/3.0)
    +X[:,0] = 1
    +
    +# We use now Scikit-Learn's linear regressor and ridge regressor
    +# OLS part
    +clf = skl.LinearRegression().fit(X, Energies)
    +ytilde = clf.predict(X)
    +EoS['Eols']  = ytilde
    +# The mean squared error                               
    +print("Mean squared error: %.2f" % mean_squared_error(Energies, ytilde))
    +# Explained variance score: 1 is perfect prediction                                 
    +print('Variance score: %.2f' % r2_score(Energies, ytilde))
    +# Mean absolute error                                                           
    +print('Mean absolute error: %.2f' % mean_absolute_error(Energies, ytilde))
    +print(clf.coef_, clf.intercept_)
    +
    +# The Ridge regression with a hyperparameter lambda = 0.1
    +_lambda = 0.1
    +clf_ridge = skl.Ridge(alpha=_lambda).fit(X, Energies)
    +yridge = clf_ridge.predict(X)
    +EoS['Eridge']  = yridge
    +# The mean squared error                               
    +print("Mean squared error: %.2f" % mean_squared_error(Energies, yridge))
    +# Explained variance score: 1 is perfect prediction                                 
    +print('Variance score: %.2f' % r2_score(Energies, yridge))
    +# Mean absolute error                                                           
    +print('Mean absolute error: %.2f' % mean_absolute_error(Energies, yridge))
    +print(clf_ridge.coef_, clf_ridge.intercept_)
    +
    +fig, ax = plt.subplots()
    +ax.set_xlabel(r'$\rho[\mathrm{fm}^{-3}]$')
    +ax.set_ylabel(r'Energy per particle')
    +ax.plot(EoS['Density'], EoS['Energy'], alpha=0.7, lw=2,
    +            label='Theoretical data')
    +ax.plot(EoS['Density'], EoS['Eols'], alpha=0.7, lw=2, c='m',
    +            label='OLS')
    +ax.plot(EoS['Density'], EoS['Eridge'], alpha=0.7, lw=2, c='g',
    +            label='Ridge $\lambda = 0.1$')
    +ax.legend()
    +save_fig("EoSfitting")
    +plt.show()
    +
    +

    +The above simple polynomial in density \( \rho \) gives an excellent fit +to the data. Can you give an interpretation of the various powers of \( \rho \)? + +

    +We note also that there is a small deviation between the +standard OLS and the Ridge regression at higher densities. We discuss this in more detail +below.

    @@ -458,7 +507,7 @@ the \( \chi^2 \) function becomes smaller.

  • 34
  • 35
  • ...
  • -
  • 114
  • +
  • 100
  • »
  • diff --git a/doc/pub/Regression/html/._Regression-bs026.html b/doc/pub/Regression/html/._Regression-bs026.html index 938c80c85..ca22d9f9b 100644 --- a/doc/pub/Regression/html/._Regression-bs026.html +++ b/doc/pub/Regression/html/._Regression-bs026.html @@ -6,6 +6,7 @@ Automatically generated HTML file from DocOnce source + Data Analysis and Machine Learning: Linear Regression and more Advanced Regression Analysis @@ -40,160 +41,151 @@ Automatically generated HTML file from DocOnce source @@ -286,119 +263,109 @@ MathJax.Hub.Config({ @@ -414,43 +381,88 @@ MathJax.Hub.Config({ -

    Relative error

    +

    Splitting our Data in Training and Test data

    -There are many ways to define the cost function. A simpler approach is to look at the relative difference between the training data and the predicted data, that is we define -the relative error as +It is normal in essentially all Machine Learning studies to split the +data in a training set and a test set (sometimes also an additional +validation set). Scikit-Learn has an own function for this. There +is no explicit recipe for how much data should be included as training +data and say test data. An accepted rule of thumb is to use +approximately \( 2/3 \) to \( 4/5 \) of the data as training data. We will +postpone a discussion of this splitting to the end of these notes and +our discussion of the so-called bias-variance tradeoff. Here we +limit ourselves to repeat the above equation of state fitting example +but now splitting the data into a training set and a test set. -$$ -\epsilon_{\mathrm{relative}}= \frac{\vert \hat{y} -\hat{\tilde{y}}\vert}{\vert \hat{y}\vert}. -$$ - -We can modify easily the above Python code and plot the relative error instead

    -

    import numpy as np
    +
    import os
    +import numpy as np
    +import pandas as pd
     import matplotlib.pyplot as plt
    -from sklearn.linear_model import LinearRegression
    +from sklearn.model_selection import train_test_split
    +# Where to save the figures and data files
    +PROJECT_ROOT_DIR = "Results"
    +FIGURE_ID = "Results/FigureFiles"
    +DATA_ID = "DataFiles/"
     
    -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)
    +if not os.path.exists(PROJECT_ROOT_DIR):
    +    os.mkdir(PROJECT_ROOT_DIR)
     
    -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()
    +if not os.path.exists(FIGURE_ID):
    +    os.makedirs(FIGURE_ID)
    +
    +if not os.path.exists(DATA_ID):
    +    os.makedirs(DATA_ID)
    +
    +def image_path(fig_id):
    +    return os.path.join(FIGURE_ID, fig_id)
    +
    +def data_path(dat_id):
    +    return os.path.join(DATA_ID, dat_id)
    +
    +def save_fig(fig_id):
    +    plt.savefig(image_path(fig_id) + ".png", format='png')
    +
    +def R2(y_data, y_model):
    +    return 1 - np.sum((y_data - y_model) ** 2) / np.sum((y_data - np.mean(y_model)) ** 2)
    +def MSE(y_data,y_model):
    +    n = np.size(y_model)
    +    return np.sum((y_data-y_model)**2)/n
    +
    +infile = open(data_path("EoS.csv"),'r')
    +
    +# Read the EoS data as  csv file and organized into two arrays with density and energies
    +EoS = pd.read_csv(infile, names=('Density', 'Energy'))
    +EoS['Energy'] = pd.to_numeric(EoS['Energy'], errors='coerce')
    +EoS = EoS.dropna()
    +Energies = EoS['Energy']
    +Density = EoS['Density']
    +#  The design matrix now as function of various polytrops
    +X = np.zeros((len(Density),5))
    +X[:,0] = 1
    +X[:,1] = Density**(2.0/3.0)
    +X[:,2] = Density
    +X[:,3] = Density**(4.0/3.0)
    +X[:,4] = Density**(5.0/3.0)
    +# We split the data in test and training data
    +X_train, X_test, y_train, y_test = train_test_split(X, Energies, test_size=0.2)
    +# matrix inversion to find beta
    +beta = np.linalg.inv(X_train.T.dot(X_train)).dot(X_train.T).dot(y_train)
    +# and then make the prediction
    +ytilde = X_train @ beta
    +print("Training R2")
    +print(R2(y_train,ytilde))
    +print("Training MSE")
    +print(MSE(y_train,ytilde))
    +ypredict = X_test @ beta
    +print("Test R2")
    +print(R2(y_test,ypredict))
    +print("Test MSE")
    +print(MSE(y_test,ypredict))
     
    -

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

    @@ -477,7 +489,7 @@ relative error.

  • 35
  • 36
  • ...
  • -
  • 114
  • +
  • 100
  • »
  • diff --git a/doc/pub/Regression/html/._Regression-bs027.html b/doc/pub/Regression/html/._Regression-bs027.html index a3af232ea..50e915fc9 100644 --- a/doc/pub/Regression/html/._Regression-bs027.html +++ b/doc/pub/Regression/html/._Regression-bs027.html @@ -6,6 +6,7 @@ Automatically generated HTML file from DocOnce source + Data Analysis and Machine Learning: Linear Regression and more Advanced Regression Analysis @@ -40,160 +41,151 @@ Automatically generated HTML file from DocOnce source @@ -286,119 +263,109 @@ MathJax.Hub.Config({ @@ -414,48 +381,35 @@ MathJax.Hub.Config({ -

    The richness of scikit-learn

    +

    The singular value decomposition

    -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. +The examples we have looked at so far are cases where we normally can +invert the matrix \( \boldsymbol{X}^T\boldsymbol{X} \). Using a polynomial expansion as we +did both for the masses and the fitting of the equation of state, +leads to row vectors of the design matrix which are essentially +orthogonal due to the polynomial character of our model. This may +however not the be case in general and a standard matrix inversion +algorithm based on say LU decomposition may lead to singularities. We will see an example of this below when we try to fit +the coupling constant of the widely used Ising model. +There is however a way to partially circumvent this problem and also gain some insight about the ordinary least squares approach. +

    +This is given by the Singular Value Decomposition algorithm, perhaps +the most powerful linear algebra algorithm. Let us look at a +different example where we may have problems with the standard matrix +inversion algorithm. Thereafter we dive into the math of the SVD. + +

    +

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

    @@ -482,7 +436,7 @@ plt.show()

  • 36
  • 37
  • ...
  • -
  • 114
  • +
  • 100
  • »
  • diff --git a/doc/pub/Regression/html/._Regression-bs028.html b/doc/pub/Regression/html/._Regression-bs028.html index 683652ca9..39cfa7990 100644 --- a/doc/pub/Regression/html/._Regression-bs028.html +++ b/doc/pub/Regression/html/._Regression-bs028.html @@ -6,6 +6,7 @@ Automatically generated HTML file from DocOnce source + Data Analysis and Machine Learning: Linear Regression and more Advanced Regression Analysis @@ -40,160 +41,151 @@ Automatically generated HTML file from DocOnce source @@ -286,119 +263,109 @@ MathJax.Hub.Config({ @@ -414,19 +381,59 @@ MathJax.Hub.Config({ -

    Functions in scikit-learn

    +

    The Ising model

    -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 -$$ MSE(\hat{y},\hat{\tilde{y}}) = \frac{1}{n} -\sum_{i=0}^{n-1}(y_i-\tilde{y}_i)^2, +The one-dimensional Ising model with nearest neighbor interaction, no +external field and a constant coupling constant \( J \) is given by + +$$ +\begin{align} + H = -J \sum_{k}^L s_k s_{k + 1}, +\tag{1} +\end{align} $$

    -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. +where \( s_i \in \{-1, 1\} \) and \( s_{N + 1} = s_1 \). The number of spins +in the system is determined by \( L \). For the one-dimensional system +there is no phase transition. + +

    +We will look at a system of \( L = 40 \) spins with a coupling constant of +\( J = 1 \). To get enough training data we will generate 10000 states +with their respective energies. + +

    + + +

    import numpy as np
    +import matplotlib.pyplot as plt
    +from mpl_toolkits.axes_grid1 import make_axes_locatable
    +import seaborn as sns
    +import scipy.linalg as scl
    +from sklearn.model_selection import train_test_split
    +import tqdm
    +sns.set(color_codes=True)
    +cmap_args=dict(vmin=-1., vmax=1., cmap='seismic')
    +
    +L = 40
    +n = int(1e4)
    +
    +spins = np.random.choice([-1, 1], size=(n, L))
    +J = 1.0
    +
    +energies = np.zeros(n)
    +
    +for i in range(n):
    +    energies[i] = - J * np.dot(spins[i], np.roll(spins[i], 1))
    +
    +

    +Here we use ordinary least squares +regression to predict the energy for the nearest neighbor +one-dimensional Ising model on a ring, i.e., the endpoints wrap +around. We will use linear regression to fit a value for +the coupling constant to achieve this.

    @@ -454,7 +461,7 @@ this function as being similar to the \( \chi^2 \) function defined above.

  • 37
  • 38
  • ...
  • -
  • 114
  • +
  • 100
  • »
  • diff --git a/doc/pub/Regression/html/._Regression-bs029.html b/doc/pub/Regression/html/._Regression-bs029.html index e00a84877..336d2cacf 100644 --- a/doc/pub/Regression/html/._Regression-bs029.html +++ b/doc/pub/Regression/html/._Regression-bs029.html @@ -6,6 +6,7 @@ Automatically generated HTML file from DocOnce source + Data Analysis and Machine Learning: Linear Regression and more Advanced Regression Analysis @@ -40,160 +41,151 @@ Automatically generated HTML file from DocOnce source @@ -286,119 +263,109 @@ MathJax.Hub.Config({ @@ -414,27 +381,53 @@ MathJax.Hub.Config({ -

    Other functions in scikit-learn

    +

    Reformulating the problem to suit regression

    -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 \). +A more general form for the one-dimensional Ising model is + +$$ +\begin{align} + H = - \sum_j^L \sum_k^L s_j s_k J_{jk}. +\tag{2} +\end{align} +$$

    -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 +Here we allow for interactions beyond the nearest neighbors and a state dependent +coupling constant. This latter expression can be formulated as +a matrix-product $$ -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}, +\begin{align} + \boldsymbol{H} = \boldsymbol{X} J, +\tag{3} +\end{align} $$ -where we have defined the mean value of \( \hat{y} \) as +

    +where \( X_{jk} = s_j s_k \) and \( J \) is a matrix which consists of the +elements \( -J_{jk} \). This form of writing the energy fits perfectly +with the form utilized in linear regression, that is + $$ -\bar{y} = \frac{1}{n} \sum_{i=0}^{n - 1} y_i. +\begin{align} + \boldsymbol{y} = \boldsymbol{X}\boldsymbol{\beta} + \boldsymbol{\epsilon}, +\tag{4} +\end{align} $$ +

    +We split the data in training and test data as discussed in the previous example + +

    + + +

    X = np.zeros((n, L ** 2))
    +for i in range(n):
    +    X[i] = np.outer(spins[i], spins[i]).ravel()
    +y = energies
    +X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2)
    +

    @@ -461,7 +454,7 @@ $$

  • 38
  • 39
  • ...
  • -
  • 114
  • +
  • 100
  • »
  • diff --git a/doc/pub/Regression/html/._Regression-bs030.html b/doc/pub/Regression/html/._Regression-bs030.html index 966cd5dfc..559929638 100644 --- a/doc/pub/Regression/html/._Regression-bs030.html +++ b/doc/pub/Regression/html/._Regression-bs030.html @@ -6,6 +6,7 @@ Automatically generated HTML file from DocOnce source + Data Analysis and Machine Learning: Linear Regression and more Advanced Regression Analysis @@ -40,160 +41,151 @@ Automatically generated HTML file from DocOnce source @@ -286,119 +263,109 @@ MathJax.Hub.Config({ @@ -414,28 +381,51 @@ MathJax.Hub.Config({ -

    The mean absolute error and other functions in scikit-learn

    +

    Linear regression

    -Another quantity will meet again in our discussions of regression analysis is - mean absolute error (MAE), a risk metric corresponding to the expected value of the absolute error loss or what we call the \( l1 \)-norm loss. In our discussion above we presented the relative error. -The MAE is defined as follows -$$ -\text{MAE}(\hat{y}, \hat{\tilde{y}}) = \frac{1}{n} \sum_{i=0}^{n-1} \left| y_i - \tilde{y}_i \right|. -$$ +In the ordinary least squares method we choose the cost function -Finally we present the -squared logarithmic (quadratic) error $$ -\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, +\begin{align} + C(\boldsymbol{X}, \boldsymbol{\beta})= \frac{1}{n}\left\{(\boldsymbol{X}\boldsymbol{\beta} - \boldsymbol{y})^T(\boldsymbol{X}\boldsymbol{\beta} - \boldsymbol{y})\right\}. +\tag{5} +\end{align} $$

    -where \( \log_e (x) \) stands for the natural logarithm of \( x \). This error -estimate is best to use when targets having exponential growth, such -as population counts, average sales of a commodity over a span of -years etc. +We then find the extremal point of \( C \) by taking the derivative with respect to \( \boldsymbol{\beta} \) as discussed above. +This yields the expression for \( \boldsymbol{\beta} \) to be +$$ + \boldsymbol{\beta} = \frac{\boldsymbol{X}^T \boldsymbol{y}}{\boldsymbol{X}^T \boldsymbol{X}}, +$$ + +

    +which immediately imposes some requirements on \( \boldsymbol{X} \) as there must exist +an inverse of \( \boldsymbol{X}^T \boldsymbol{X} \). If the expression we are modeling contains an +intercept, i.e., a constant term, we must make sure that the +first column of \( \boldsymbol{X} \) consists of \( 1 \). We do this here + +

    + + +

    X_train_own = np.concatenate(
    +    (np.ones(len(X_train))[:, np.newaxis], X_train),
    +    axis=1
    +)
    +X_test_own = np.concatenate(
    +    (np.ones(len(X_test))[:, np.newaxis], X_test),
    +    axis=1
    +)
    +
    +

    + + +

    def ols_inv(x: np.ndarray, y: np.ndarray) -> np.ndarray:
    +    return scl.inv(x.T @ x) @ (x.T @ y)
    +beta = ols_inv(X_train_own, y_train)
    +

    @@ -462,7 +452,7 @@ years etc.

  • 39
  • 40
  • ...
  • -
  • 114
  • +
  • 100
  • »
  • diff --git a/doc/pub/Regression/html/._Regression-bs031.html b/doc/pub/Regression/html/._Regression-bs031.html index 083f2547b..0a77e9794 100644 --- a/doc/pub/Regression/html/._Regression-bs031.html +++ b/doc/pub/Regression/html/._Regression-bs031.html @@ -6,6 +6,7 @@ Automatically generated HTML file from DocOnce source + Data Analysis and Machine Learning: Linear Regression and more Advanced Regression Analysis @@ -40,160 +41,151 @@ Automatically generated HTML file from DocOnce source @@ -286,119 +263,109 @@ MathJax.Hub.Config({ @@ -414,50 +381,89 @@ MathJax.Hub.Config({ -

    Cubic polynomial in scikit-learn

    +

    Singular Value decomposition

    -We will discuss in more -detail these and other functions in the various lectures. We conclude this part with another example. Instead of -a linear \( x \)-dependence we study now a cubic polynomial and use the polynomial regression analysis tools of scikit-learn. -Add description of the various python commands. +Doing the inversion directly turns out to be a bad idea since the matrix +\( \boldsymbol{X}^T\boldsymbol{X} \) is singular. An alternative approach is to use the singular +value decomposition. Using the definition of the Moore-Penrose +pseudoinverse we can write the equation for \( \boldsymbol{\beta} \) as + +$$ + \boldsymbol{\beta} = \boldsymbol{X}^{+}\boldsymbol{y}, +$$ + +

    +where the pseudoinverse of \( \boldsymbol{X} \) is given by + +$$ + \boldsymbol{X}^{+} = \frac{\boldsymbol{X}^T}{\boldsymbol{X}^T\boldsymbol{X}}. +$$ + +

    +Using singular value decomposition we can decompose the matrix \( \boldsymbol{X} = \boldsymbol{U}\boldsymbol{\Sigma} \boldsymbol{V}^T \), +where \( \boldsymbol{U} \) and \( \boldsymbol{V} \) are orthogonal(unitary) matrices and \( \boldsymbol{\Sigma} \) contains the singular values (more details below). +where \( X^{+} = V\Sigma^{+} U^T \). This reduces the equation for +\( \omega \) to +$$ +\begin{align} + \boldsymbol{\beta} = \boldsymbol{V}\boldsymbol{\Sigma}^{+} \boldsymbol{U}^T \boldsymbol{y}. +\tag{6} +\end{align} +$$ + +

    +Note that solving this equation by actually doing the pseudoinverse +(which is what we will do) is not a good idea as this operation scales +as \( \mathcal{O}(n^3) \), where \( n \) is the number of elements in a +general matrix. Instead, doing \( QR \)-factorization and solving the +linear system as an equation would reduce this down to +\( \mathcal{O}(n^2) \) operations.

    -

    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))
    +
    def ols_svd(x: np.ndarray, y: np.ndarray) -> np.ndarray:
    +    u, s, v = scl.svd(x)
    +    return v.T @ scl.pinv(scl.diagsvd(s, u.shape[0], v.shape[0])) @ u.T @ y
     

    -Using R, we can perform similar studies. + + +

    beta = ols_svd(X_train_own,y_train)
    +
    +

    +When extracting the \( J \)-matrix we need to make sure that we remove the intercept, as is done here + +

    + + +

    J = beta[1:].reshape(L, L)
    +
    +

    +A way of looking at the coefficients in \( J \) is to plot the matrices as images. + +

    + + +

    fig = plt.figure(figsize=(20, 14))
    +im = plt.imshow(J, **cmap_args)
    +plt.title("OLS", fontsize=18)
    +plt.xticks(fontsize=18)
    +plt.yticks(fontsize=18)
    +cb = fig.colorbar(im)
    +cb.ax.set_yticklabels(cb.ax.get_yticklabels(), fontsize=18)
    +plt.show()
    +
    +

    +It is interesting to note that OLS +considers both \( J_{j, j + 1} = -0.5 \) and \( J_{j, j - 1} = -0.5 \) as +valid matrix elements for \( J \). +In our discussion below on hyperparameters and Ridge and Lasso regression we will see that +this problem can be removed, partly and only with Lasso regression. + +

    +In this case our matrix inversion was actually possible. The obvious question now is what is the mathematics behind the SVD?

    @@ -485,7 +491,7 @@ Using R, we can perform similar studies.

  • 40
  • 41
  • ...
  • -
  • 114
  • +
  • 100
  • »
  • diff --git a/doc/pub/Regression/html/._Regression-bs032.html b/doc/pub/Regression/html/._Regression-bs032.html index a78d33731..e2d8e0601 100644 --- a/doc/pub/Regression/html/._Regression-bs032.html +++ b/doc/pub/Regression/html/._Regression-bs032.html @@ -6,6 +6,7 @@ Automatically generated HTML file from DocOnce source + Data Analysis and Machine Learning: Linear Regression and more Advanced Regression Analysis @@ -40,160 +41,151 @@ Automatically generated HTML file from DocOnce source @@ -286,119 +263,109 @@ MathJax.Hub.Config({ @@ -414,34 +381,54 @@ MathJax.Hub.Config({ -

    Polynomial Regression

    +

    Linear Regression Problems

    +

    +One of the typical problems we encounter with linear regression, in particular +when the matrix \( \boldsymbol{X} \) (our so-called design matrix) is high-dimensional, +are problems with near singular or singular matrices. The column vectors of \( \boldsymbol{X} \) +may be linearly dependent, normally referred to as super-collinearity. +This means that the matrix may be rank deficient and it is basically impossible to +to model the data using linear regression. As an example, consider the matrix +$$ +\begin{align*} +\mathbf{X} & = \left[ +\begin{array}{rrr} +1 & -1 & 2 +\\ +1 & 0 & 1 +\\ +1 & 2 & -1 +\\ +1 & 1 & 0 +\end{array} \right] +\end{align*} +$$ - -

    # Importing various packages
    -from math import exp, sqrt
    -from random import random, seed
    -import numpy as np
    -import matplotlib.pyplot as plt
    +

    +The columns of \( \boldsymbol{X} \) are linearly dependent. We see this easily since the +the first column is the row-wise sum of the other two columns. The rank (more correct, +the column rank) of a matrix is the dimension of the space spanned by the +column vectors. Hence, the rank of \( \mathbf{X} \) is equal to the number +of linearly independent columns. In this particular case the matrix has rank 2. -m = 100 -x = 2*np.random.rand(m,1)+4. -y = 4+3*x*x+ +x-np.random.randn(m,1) +

    +Super-collinearity of an \( (n \times p) \)-dimensional design matrix \( \mathbf{X} \) implies +that the inverse of the matrix \( \boldsymbol{X}^T\boldsymbol{x} \) (the matrix we need to invert to solve the linear regression equations) is non-invertible. If we have a square matrix that does not have an inverse, we say this matrix singular. The example here demonstrates this +$$ +\begin{align*} +\boldsymbol{X} & = \left[ +\begin{array}{rr} +1 & -1 +\\ +1 & -1 +\end{array} \right]. +\end{align*} +$$ -xb = np.c_[np.ones((m,1)), x] -theta = np.linalg.inv(xb.T.dot(xb)).dot(xb.T).dot(y) -xnew = np.array([[0],[2]]) -xbnew = np.c_[np.ones((2,1)), xnew] -ypredict = xbnew.dot(theta) +We see easily that \( \mbox{det}(\boldsymbol{X}) = x_{11} x_{22} - x_{12} x_{21} = 1 \times (-1) - 1 \times (-1) = 0 \). Hence, \( \mathbf{X} \) is singular and its inverse is undefined. +This is equivalent to saying that the matrix \( \boldsymbol{X} \) has at least an eigenvalue which is zero. -plt.plot(xnew, ypredict, "r-") -plt.plot(x, y ,'ro') -plt.axis([0,2.0,0, 15.0]) -plt.xlabel(r'$x$') -plt.ylabel(r'$y$') -plt.title(r'Random numbers ') -plt.show() -

    @@ -468,7 +455,7 @@ plt.show()

  • 41
  • 42
  • ...
  • -
  • 114
  • +
  • 100
  • »
  • diff --git a/doc/pub/Regression/html/._Regression-bs033.html b/doc/pub/Regression/html/._Regression-bs033.html index 6ec4c2424..07e2b51a9 100644 --- a/doc/pub/Regression/html/._Regression-bs033.html +++ b/doc/pub/Regression/html/._Regression-bs033.html @@ -6,6 +6,7 @@ Automatically generated HTML file from DocOnce source + Data Analysis and Machine Learning: Linear Regression and more Advanced Regression Analysis @@ -40,160 +41,151 @@ Automatically generated HTML file from DocOnce source @@ -286,119 +263,109 @@ MathJax.Hub.Config({ @@ -412,31 +379,32 @@ MathJax.Hub.Config({

     

     

     

    - + -

    Linking the regression analysis with a statistical interpretation

    +

    Fixing the singularity

    -Before we proceed, and to link with our discussions of Bayesian statistics to come, it is useful the derive the standard regression analysis equations using a statistical interpretation. This allows us also to derive quantities like the variance and other expectation values in a rather straightforward way. +If our design matrix \( \boldsymbol{X} \) which enters the linear regression problem +$$ +\begin{align} +\boldsymbol{\beta} & = (\boldsymbol{X}^{T} \boldsymbol{X})^{-1} \boldsymbol{X}^{T} \boldsymbol{y}, +\tag{7} +\end{align} +$$ + +has linearly dependent column vectors, we will not be able to compute the inverse +of \( \boldsymbol{X}^T\boldsymbol{X} \) and we cannot find the parameters (estimators) \( \beta_i \). +The estimators are only well-defined if \( (\boldsymbol{X}^{T}\boldsymbol{X})^{-1} \) exits. +This is more likely to happen when the matrix \( \boldsymbol{X} \) is high-dimensional. In this case it is likely to encounter a situation where +the regression parameters \( \beta_i \) cannot be estimated.

    -It is assumed that \( \varepsilon_i -\sim \mathcal{N}(0, \sigma^2) \) and the \( \varepsilon_{i} \) are -independent, i.e.: +A cheap ad hoc approach is simply to add a small diagonal component to the matrix to invert, that is we change $$ -\begin{align*} -\mbox{Cov}(\varepsilon_{i_1}, -\varepsilon_{i_2}) & = \left\{ \begin{array}{lcc} \sigma^2 & \mbox{if} -& i_1 = i_2, \\ 0 & \mbox{if} & i_1 \not= i_2. \end{array} \right. -\end{align*} +\boldsymbol{X}^{T} \boldsymbol{X} \rightarrow \boldsymbol{X}^{T} \boldsymbol{X}+\lambda \boldsymbol{I}, $$ -The randomness of \( \varepsilon_i \) implies that -\( \mathbf{Y}_i \) is also a random variable. In particular, -\( \mathbf{Y}_i \) is normally distributed, because \( \varepsilon_i \sim -\mathcal{N}(0, \sigma^2) \) and \( \mathbf{X}_{i,\ast} \, \beta \) is a -non-random scalar. To specify the parameters of the distribution of -\( \mathbf{Y}_i \) we need to calculate its first two moments. +where \( \boldsymbol{I} \) is the identity matrix. When we discuss Ridge regression this is actually what we end up evaluating. The parameter \( \lambda \) is called a hyperparameter. More about this later.

    @@ -464,7 +432,7 @@ non-random scalar. To specify the parameters of the distribution of

  • 42
  • 43
  • ...
  • -
  • 114
  • +
  • 100
  • »
  • diff --git a/doc/pub/Regression/html/._Regression-bs034.html b/doc/pub/Regression/html/._Regression-bs034.html index b91f5c9ad..de4b3316b 100644 --- a/doc/pub/Regression/html/._Regression-bs034.html +++ b/doc/pub/Regression/html/._Regression-bs034.html @@ -6,6 +6,7 @@ Automatically generated HTML file from DocOnce source + Data Analysis and Machine Learning: Linear Regression and more Advanced Regression Analysis @@ -40,160 +41,151 @@ Automatically generated HTML file from DocOnce source @@ -286,119 +263,109 @@ MathJax.Hub.Config({ @@ -414,36 +381,41 @@ MathJax.Hub.Config({ -

    Expectation value and variance

    +

    Basic math of the SVD

    -Its expectation equals: +From standard linear algebra we know that a square matrix \( \boldsymbol{X} \) can be diagonalized if and only it is +a so-called normal matrix, that is if \( \boldsymbol{X}\in {\mathbb{R}}^{n\times n} \) +we have \( \boldsymbol{X}\boldsymbol{X}^T=\boldsymbol{X}^T\boldsymbol{X} \) or if \( \boldsymbol{X}\in {\mathbb{C}}^{n\times n} \) we have \( \boldsymbol{X}\boldsymbol{X}^{\dagger}=\boldsymbol{X}^{\dagger}\boldsymbol{X} \). +The matrix has then a set of eigenpairs + $$ -\begin{align*} -\mathbb{E}(Y_i) & = -\mathbb{E}(\mathbf{X}_{i, \ast} \, \beta) + \mathbb{E}(\varepsilon_i) -\, \, \, = \, \, \, \mathbf{X}_{i, \ast} \, \beta, -\end{align*} +(\lambda_1,\boldsymbol{u}_1),\dots, (\lambda_n,\boldsymbol{u}_n), $$ -while -its variance is +and the eigenvalues are given by the diagonal matrix $$ -\begin{align*} \mbox{Var}(Y_i) & = \mathbb{E} \{ [Y_i -- \mathbb{E}(Y_i)]^2 \} \, \, \, = \, \, \, \mathbb{E} ( Y_i^2 ) - -[\mathbb{E}(Y_i)]^2 \\ & = \mathbb{E} [ ( \mathbf{X}_{i, \ast} \, -\beta + \varepsilon_i )^2] - ( \mathbf{X}_{i, \ast} \, \beta)^2 \\ & -= \mathbb{E} [ ( \mathbf{X}_{i, \ast} \, \beta)^2 + 2 \varepsilon_i -\mathbf{X}_{i, \ast} \, \beta + \varepsilon_i^2 ] - ( \mathbf{X}_{i, -\ast} \, \beta)^2 \\ & = ( \mathbf{X}_{i, \ast} \, \beta)^2 + 2 -\mathbb{E}(\varepsilon_i) \mathbf{X}_{i, \ast} \, \beta + -\mathbb{E}(\varepsilon_i^2 ) - ( \mathbf{X}_{i, \ast} \, \beta)^2 -\\ & = \mathbb{E}(\varepsilon_i^2 ) \, \, \, = \, \, \, -\mbox{Var}(\varepsilon_i) \, \, \, = \, \, \, \sigma^2. -\end{align*} +\boldsymbol{\Sigma}=\mathrm{Diag}(\lambda_1, \dots,\lambda_n). $$ -Hence, \( Y_i \sim \mathcal{N}( \mathbf{X}_{i, \ast} \, \beta, \sigma^2) \). +The matrix \( \boldsymbol{X} \) can be written in terms of an orthogonal/unitary transformation \( \boldsymbol{U} \) +$$ +\boldsymbol{X} = \boldsymbol{U}\boldsymbol{\Sigma}\boldsymbol{V}^T, +$$ + +with \( \boldsymbol{U}\boldsymbol{U}^T=\boldsymbol{I} \) or \( \boldsymbol{U}\boldsymbol{U}^{\dagger}=\boldsymbol{I} \). + +

    +Not all square matrices are diagonalizable. A matrix like the one discussed above +$$ +\boldsymbol{X} = \begin{bmatrix} +1& -1 \\ +1& -1\\ +\end{bmatrix} +$$ + +is not diagonalizable, it is a so-called defective matrix. It is easy to see that the condition +\( \boldsymbol{X}\boldsymbol{X}^T=\boldsymbol{X}^T\boldsymbol{X} \) is not fulfilled.

    @@ -471,7 +443,7 @@ Hence, \( Y_i \sim \mathcal{N}( \mathbf{X}_{i, \ast} \, \beta, \sigma^2) \).

  • 43
  • 44
  • ...
  • -
  • 114
  • +
  • 100
  • »
  • diff --git a/doc/pub/Regression/html/._Regression-bs035.html b/doc/pub/Regression/html/._Regression-bs035.html index fb33510a7..12ca2541d 100644 --- a/doc/pub/Regression/html/._Regression-bs035.html +++ b/doc/pub/Regression/html/._Regression-bs035.html @@ -6,6 +6,7 @@ Automatically generated HTML file from DocOnce source + Data Analysis and Machine Learning: Linear Regression and more Advanced Regression Analysis @@ -40,160 +41,151 @@ Automatically generated HTML file from DocOnce source @@ -286,119 +263,109 @@ MathJax.Hub.Config({ @@ -414,24 +381,33 @@ MathJax.Hub.Config({ -

    The singular value decompostion

    -
    -
    -

    +

    The SVD, a Fantastic Algorithm

    -A general -\( m\times n \) matrix \( \hat{A} \) can be written in terms of a diagonal -matrix \( \hat{D} \) of dimensionality \( n\times n \) and two orthognal -matrices \( \hat{U} \) and \( \hat{V} \), where the first has dimensionality -\( m \times m \) and the last dimensionality \( n\times n \). -We have then -$$ -\hat{A} = \hat{U}\hat{D}\hat{V}^T -$$ -

    -
    +However, and this is the strength of the SVD algorithm, any general +matrix \( \boldsymbol{X} \) can be decomposed in terms of a diagonal matrix and +two orthogonal/unitary matrices. The Singular Value Decompostion +(SVD) theorem +states that a general \( m\times n \) matrix \( \boldsymbol{X} \) can be written in +terms of a diagonal matrix \( \boldsymbol{\Sigma} \) of dimensionality \( n\times n \) +and two orthognal matrices \( \boldsymbol{U} \) and \( \boldsymbol{V} \), where the first has +dimensionality \( m \times m \) and the last dimensionality \( n\times n \). +We have then +$$ +\boldsymbol{X} = \boldsymbol{U}\boldsymbol{\Sigma}\boldsymbol{V}^T +$$ + +

    +As an example, the above defective matrix can be decomposed as + +$$ +\boldsymbol{X} = \frac{1}{\sqrt{2}}\begin{bmatrix} 1& 1 \\ 1& -1\\ \end{bmatrix} \begin{bmatrix} 2& 0 \\ 0& 0\\ \end{bmatrix} \frac{1}{\sqrt{2}}\begin{bmatrix} 1& -1 \\ 1& 1\\ \end{bmatrix}=\boldsymbol{U}\boldsymbol{\Sigma}\boldsymbol{V}^T, +$$ + +

    +with eigenvalues \( \sigma_1=2 \) and \( \sigma_2=0 \). +The SVD exits always!

    @@ -459,7 +435,7 @@ $$

  • 44
  • 45
  • ...
  • -
  • 114
  • +
  • 100
  • »
  • diff --git a/doc/pub/Regression/html/._Regression-bs036.html b/doc/pub/Regression/html/._Regression-bs036.html index a04c4f228..f0d68b336 100644 --- a/doc/pub/Regression/html/._Regression-bs036.html +++ b/doc/pub/Regression/html/._Regression-bs036.html @@ -6,6 +6,7 @@ Automatically generated HTML file from DocOnce source + Data Analysis and Machine Learning: Linear Regression and more Advanced Regression Analysis @@ -40,160 +41,151 @@ Automatically generated HTML file from DocOnce source @@ -286,119 +263,109 @@ MathJax.Hub.Config({ @@ -414,53 +381,40 @@ MathJax.Hub.Config({ -

    From standard regression to Ridge regressions

    +

    Another Example

    -One of the typical problems we encounter with linear regression, in particular -when the matrix \( \hat{X} \) (our so-called design matrix) is high-dimensional, -are problems with near singular or singular matrices. The column vectors of \( \hat{X} \) -may be linearly dependent, normally referred to as super-collinearity. -This means that the matrix may be rank deficient and it is basically impossible to -to model the data using linear regression. As an example, consider the matrix +Consider the following matrix which can be SVD decomposed as + $$ -\begin{align*} -\mathbf{X} & = \left[ -\begin{array}{rrr} -1 & -1 & 2 -\\ -1 & 0 & 1 -\\ -1 & 2 & -1 -\\ -1 & 1 & 0 -\end{array} \right] -\end{align*} +\boldsymbol{X} = \frac{1}{15}\begin{bmatrix} 14 & 2\\ 4 & 22\\ 16 & 13\end{matrix}=\frac{1}{3}\begin{bmatrix} 1& 2 & 2 \\ 2& -1 & 1\\ 2 & 1& -2\end{bmatrix} \begin{bmatrix} 2& 0 \\ 0& 1\\ 0 & 0\end{bmatrix}\frac{1}{5}\begin{bmatrix} 3& 4 \\ 4& -3\end{bmatrix}=\boldsymbol{U}\boldsymbol{\Sigma}\boldsymbol{V}^T. $$

    -The columns of \( \hat{X} \) are linearly dependent. We se this easily since the -the first column is the row-wise sum of the other two columns. The rank (more correct, -the column rank) of a matrix is the dimension of the space spanned by the -column vectors. Hence, the rank of \( \mathbf{X} \) is equal to the number -of linearly independent columns. In this particular case the matrix has rank 2. +This is a \( 3\times 2 \) matrix which is decomposed in terms of a +\( 3\times 3 \) matrix \( \boldsymbol{U} \), and a \( 2\times 2 \) matrix \( \boldsymbol{V} \). It is easy to see +that \( \boldsymbol{U} \) and \( \boldsymbol{V} \) are orthogonal (how?).

    -Super-collinearity of an \( (n \times p) \)-dimensional design matrix \( \mathbf{X} \) implies -that the inverse of the matrix \( \hat{X}^T\hat{x} \) (the matrix we needto invert to solve the linear regression equations) is non-invertible. If we have a square matrix that does not have an inverse, we say this matrix singular. The example here demonstrates this -$$ -\begin{align*} -\hat{X} & = \left[ -\begin{array}{rr} -1 & -1 -\\ -1 & -1 -\end{array} \right]. -\end{align*} -$$ +And the SVD +decomposition (singular values) gives eigenvalues +\( \sigma_i\geq\sigma_{i+1} \) for all \( i \) and for dimensions larger than \( i=2 \), the +eigenvalues (singular values) are zero. -We see easily that \( \mbox{det}(\hat{X}) = x_{11} x_{22} - x_{12} x_{21} = 1 \times (-1) - 1 \times (-1) = 0 \). Hence, \( \mathbf{X} \) is singular and its inverse is undefined. -This is equivalent to saying that the matrix \( \hat{X} \) has at least an eigenvalue which is zero. +

    +In the general case, where our design matrix \( \boldsymbol{X} \) has dimension +\( n\times p \), the matrix is thus decomposed into an \( n\times n \) +orthogonal matrix \( \boldsymbol{U} \), a \( p\times p \) orthogonal matrix \( \boldsymbol{V} \) +and a diagonal matrix \( \boldsymbol{\Sigma} \) with \( r=\mathrm{min}(n,p) \) +singular values \( \sigma_i\lg 0 \) on the main diagonal and zeros filling +the rest of the matrix. There are at most \( p \) singular values +assuming that \( n > p \). In our regression examples for the nuclear +masses and the equation of state this is indeed the case, while for +the Ising model we have \( p > n \). These are often cases that lead to +near singular or singular matrices. + +

    +The columns of \( \boldsymbol{U} \) are called the left singular vectors while the columns of \( \boldsymbol{V} \) are the right singular vectors.

    @@ -488,7 +442,7 @@ This is equivalent to saying that the matrix \( \hat{X} \) has at least an eigen

  • 45
  • 46
  • ...
  • -
  • 114
  • +
  • 100
  • »
  • diff --git a/doc/pub/Regression/html/._Regression-bs037.html b/doc/pub/Regression/html/._Regression-bs037.html index fe3429fea..87e2a3326 100644 --- a/doc/pub/Regression/html/._Regression-bs037.html +++ b/doc/pub/Regression/html/._Regression-bs037.html @@ -6,6 +6,7 @@ Automatically generated HTML file from DocOnce source + Data Analysis and Machine Learning: Linear Regression and more Advanced Regression Analysis @@ -40,160 +41,151 @@ Automatically generated HTML file from DocOnce source @@ -286,119 +263,109 @@ MathJax.Hub.Config({ @@ -414,30 +381,27 @@ MathJax.Hub.Config({ -

    Fixing the singularity

    +

    Economy-size SVD

    -If our design matrix \( \hat{X} \) which enters the linear regression problem -$$ -\begin{align} -\hat{\beta} & = (\hat{X}^{T} \hat{X})^{-1} \hat{X}^{T} \hat{y}, -\tag{1} -\end{align} -$$ - -has linearly dependent column vectors, we will not be able to compute the inverse -of \( \hat{X}^T\hat{X} \) and we cannot find the parameters (estimators) \( \beta_i \). -The estimators are only well-defined if \( (\hat{X}^{T}\hat{X})^{-1} \) exits. -This is more likely to happen when the matrix \( \hat{X} \) is high-dimensional. In this case it is likely to encounter a situation where -the regression parameters \( \beta_i \) cannot be estimated. +If we assume that \( n > p \), then our matrix \( \boldsymbol{U} \) has dimension \( n +\times n \). The last \( n-p \) columns of \( \boldsymbol{U} \) become however +irrelevant in our calculations since they are multiplied with the +zeros in \( \boldsymbol{\Sigma} \).

    -The ad hoc approach which was introduced in the 70s was simply to add a diagonal component to the matrix to invert, that is we change -$$ -\hat{X}^{T} \hat{X} \rightarrow \hat{X}^{T} \hat{X}+\lambda \hat{I}, -$$ +The economy-size decomposition removes extra rows or columns of zeros +from the diagonal matrix of singular values, \( \boldsymbol{\Sigma} \), along with the columns +in either \( \boldsymbol{U} \) or \( \boldsymbol{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. -where \( \hat{I} \) is the identity matrix. +

    +If \( n > p \), we keep only the first \( p \) columns of \( \boldsymbol{U} \) and \( \boldsymbol{\Sigma} \) has dimension \( p\times p \). +If \( p > n \), then only the first \( n \) columns of \( \boldsymbol{V} \) are computed and \( \boldsymbol{\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.

    @@ -465,7 +429,7 @@ where \( \hat{I} \) is the identity matrix.

  • 46
  • 47
  • ...
  • -
  • 114
  • +
  • 100
  • »
  • diff --git a/doc/pub/Regression/html/._Regression-bs038.html b/doc/pub/Regression/html/._Regression-bs038.html index 480cbe132..882badd18 100644 --- a/doc/pub/Regression/html/._Regression-bs038.html +++ b/doc/pub/Regression/html/._Regression-bs038.html @@ -6,6 +6,7 @@ Automatically generated HTML file from DocOnce source + Data Analysis and Machine Learning: Linear Regression and more Advanced Regression Analysis @@ -40,160 +41,151 @@ Automatically generated HTML file from DocOnce source @@ -286,119 +263,109 @@ MathJax.Hub.Config({ @@ -414,29 +381,54 @@ MathJax.Hub.Config({ -

    Fitting vs. predicting when data is in the model class

    +

    Mathematical Properties

    -We start by considering the case -\( f(x)=2x \). +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.

    -Then the data is clearly generated by a model that is contained within -all three model classes we are using to make predictions (linear -models, third order polynomials, and tenth order polynomials). +We have from OLS that the parameters of the linear approximation are given by +$$ +\boldsymbol{\tilde{y}} = \boldsymbol{X}\boldsymbol{\beta} = \boldsymbol{X}\left(\boldsymbol{X}^T\boldsymbol{X}\right)^{-1}\boldsymbol{X}^T\boldsymbol{y}. +$$

    -Run the code for the following cases: +The matrix to invert can be rewritten in terms of our SVD decomposition as -

      -
    1. For \( f(x)=2x \) , \( Ntrain=10 \) and \( \sigma =0 \) (noiseless case), train the three classes of models (linear, third-order polynomial, and tenth order polynomial) for a training set when \( x \in [0,1] \) . Make graphs comparing fits for different order of polynomials. Which model fits the data the best?
    2. -
    3. Do you think that the data that has the least error on the training set will also make the best predictions? Why or why not? Can you try to discuss and formalize your intuition? What can go right and what can go wrong?
    4. -
    5. Check your answer by seeing how well your fits predict newly generated test data (including on data outside the range you fit on, for example \( x \in [0,1.2] \) ) using the code below. How well do you do on points in the range of x where you trained the model? How about points outside the original training data set?
    6. -
    7. Repeat the above for \( f(x)=2x \) , \( Ntrain=10 \) , and \( \sigma=1 \) . What changes?
    8. -
    +$$ +\boldsymbol{X}^T\boldsymbol{X} = \boldsymbol{V}\boldsymbol{\Sigma}^T\boldsymbol{U}^T\boldsymbol{U}\boldsymbol{\Sigma}\boldsymbol{V}^T. +$$ -Repeat the exercises above for \( f(x)=2x \) , \( Ntrain=100 \) , and \( \sigma=1 \) . What changes? -Summarize what you have learned about the relationship between model complexity (number of parameters), goodness of fit on training data, and the ability to predict well. +Using the orthogonality properties of \( \boldsymbol{U} \) we have + +$$ +\boldsymbol{X}^T\boldsymbol{X} = \boldsymbol{V}\boldsymbol{\Sigma}^T\boldsymbol{\Sigma}\boldsymbol{V}^T = \boldsymbol{V}\boldsymbol{D}\boldsymbol{V}^T, +$$ + +with \( \boldsymbol{D} \) being a diagonal matrix with values along the diagonal given by the singular values squared. + +

    +This means that +$$ +(\boldsymbol{X}^T\boldsymbol{X})\boldsymbol{V} = \boldsymbol{V}\boldsymbol{D}, +$$ + +that is the eigenvectors of \( (\boldsymbol{X}^T\boldsymbol{X}) \) are given by the columns of the right singular matrix of \( \boldsymbol{X} \) and the eigenvalues are the squared singular values. It is easy to show (show this) that +$$ +(\boldsymbol{X}\boldsymbol{X}^T)\boldsymbol{U} = \boldsymbol{U}\boldsymbol{D}, +$$ + +that is, the eigenvectors of \( (\boldsymbol{X}\boldsymbol{X})^T \) are the columns of the left singular matrix and the eigenvalues are the same. + +

    +Going back to our OLS equation we have +$$ +\boldsymbol{X}\boldsymbol{\beta} = \boldsymbol{X}\left(\boldsymbol{V}\boldsymbol{D}\boldsymbol{V}^T \right)^{-1}\boldsymbol{X}^T\boldsymbol{y}=\boldsymbol{U\Sigma V^T}\left(\boldsymbol{V}\boldsymbol{D}\boldsymbol{V}^T \right)^{-1}(\boldsymbol{U\Sigma V^T})^T\boldsymbol{y}=\boldsymbol{U}\boldsymbol{U}^T\boldsymbol{y}. +$$ + +We will come back to this expression when we discuss Ridge regression.

    @@ -464,7 +456,7 @@ Summarize what you have learned about the relationship between model complexity

  • 47
  • 48
  • ...
  • -
  • 114
  • +
  • 100
  • »
  • diff --git a/doc/pub/Regression/html/._Regression-bs039.html b/doc/pub/Regression/html/._Regression-bs039.html index ffe39b2a5..b779e21a2 100644 --- a/doc/pub/Regression/html/._Regression-bs039.html +++ b/doc/pub/Regression/html/._Regression-bs039.html @@ -6,6 +6,7 @@ Automatically generated HTML file from DocOnce source + Data Analysis and Machine Learning: Linear Regression and more Advanced Regression Analysis @@ -40,160 +41,151 @@ Automatically generated HTML file from DocOnce source @@ -286,119 +263,109 @@ MathJax.Hub.Config({ @@ -414,17 +381,60 @@ MathJax.Hub.Config({ -

    Fitting versus predicting when data is not in the model class

    +

    Ridge and LASSO Regression

    -Thus far, we have considered the case where the data is generated using a model contained in the model class. Now consider \( f(x)=2x-10x^5+15x^{10} \) . Notice that the for linear and third-order polynomial the true model \( f(x) \) is not contained in model class. +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 +$$ +{\displaystyle \min_{\boldsymbol{\beta}\in {\mathbb{R}}^{p}}}\frac{1}{n}\left\{\left(\boldsymbol{y}-\boldsymbol{X}\boldsymbol{\beta}\right)^T\left(\boldsymbol{y}-\boldsymbol{X}\boldsymbol{\beta}\right)\right\}. +$$ -

      -
    1. Do better fits lead to better predictions?
    2. -
    3. What is the relationship between the true model for generating the data and the model class that has the most predictive power? How is this related to the model complexity? How does this depend on the number of data points \( Ntrain \) and \( \sigma \)?
    4. -
    +or we can state it as +$$ +{\displaystyle \min_{\boldsymbol{\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 \boldsymbol{y}-\boldsymbol{X}\boldsymbol{\beta}\vert\vert_2^2, +$$ -Summarize what you think you learned about the relationship of knowing the true model class and predictive power. +where we have used the definition of a norm-2 vector, that is +$$ +\vert\vert \boldsymbol{x}\vert\vert_2 = \sqrt{\sum_i x_i^2}. +$$ + +

    +By minimizing the above equation with respect to the parameters +\( \boldsymbol{\beta} \) we could then obtain an analytical expression for the +parameters \( \boldsymbol{\beta} \). We can add a regularization parameter \( \lambda \) by +defining a new cost function to be optimized, that is + +$$ +{\displaystyle \min_{\boldsymbol{\beta}\in +{\mathbb{R}}^{p}}}\frac{1}{n}\vert\vert \boldsymbol{y}-\boldsymbol{X}\boldsymbol{\beta}\vert\vert_2^2+\lambda\vert\vert \boldsymbol{\beta}\vert\vert_2^2 +$$ + +

    +which leads to the Ridge regression minimization problem where we +require that \( \vert\vert \boldsymbol{\beta}\vert\vert_2^2\le t \), where \( t \) is +a finite number larger than zero. By defining + +$$ +C(\boldsymbol{X},\boldsymbol{\beta})=\frac{1}{n}\vert\vert \boldsymbol{y}-\boldsymbol{X}\boldsymbol{\beta}\vert\vert_2^2+\lambda\vert\vert \boldsymbol{\beta}\vert\vert_1, +$$ + +

    +we have a new optimization equation +$$ +{\displaystyle \min_{\boldsymbol{\beta}\in +{\mathbb{R}}^{p}}}\frac{1}{n}\vert\vert \boldsymbol{y}-\boldsymbol{X}\boldsymbol{\beta}\vert\vert_2^2+\lambda\vert\vert \boldsymbol{\beta}\vert\vert_1 +$$ + +which leads to Lasso regression. Lasso stands for least absolute shrinkage and selection operator. + +

    +Here we have defined the norm-1 as +$$ +\vert\vert \boldsymbol{x}\vert\vert_1 = \sum_i \vert x_i\vert. +$$

    @@ -452,7 +462,7 @@ Summarize what you think you learned about the relationship of knowing the true

  • 48
  • 49
  • ...
  • -
  • 114
  • +
  • 100
  • »
  • diff --git a/doc/pub/Regression/html/._Regression-bs040.html b/doc/pub/Regression/html/._Regression-bs040.html index 889ad0ad4..79442e146 100644 --- a/doc/pub/Regression/html/._Regression-bs040.html +++ b/doc/pub/Regression/html/._Regression-bs040.html @@ -6,6 +6,7 @@ Automatically generated HTML file from DocOnce source + Data Analysis and Machine Learning: Linear Regression and more Advanced Regression Analysis @@ -40,160 +41,151 @@ Automatically generated HTML file from DocOnce source @@ -286,119 +263,109 @@ MathJax.Hub.Config({ @@ -414,93 +381,62 @@ MathJax.Hub.Config({ -

    An example code without the model assessment part

    +

    More on Ridge Regression

    +Using the matrix-vector expression for Ridge regression, - -

    import numpy as np
    -import sklearn as sk
    -from sklearn import datasets, linear_model
    -from sklearn.preprocessing import PolynomialFeatures
    +$$
    +C(\boldsymbol{X},\boldsymbol{\beta})=\frac{1}{n}\left\{(\boldsymbol{y}-\boldsymbol{X}\boldsymbol{\beta})^T(\boldsymbol{y}-\boldsymbol{X}\boldsymbol{\beta})\right\}+\lambda\boldsymbol{\beta}^T\boldsymbol{\beta},
    +$$
     
    -import matplotlib as mpl
    -from matplotlib import pyplot as plt
    +

    +by taking the derivatives with respect to \( \boldsymbol{\beta} \) we obtain then +a slightly modified matrix inversion problem which for finite values +of \( \lambda \) does not suffer from singularity problems. We obtain -%matplotlib notebook +$$ +\boldsymbol{\beta}^{\mathrm{Ridge}} = \left(\boldsymbol{X}^T\boldsymbol{X}+\lambda\boldsymbol{I}\right)^{-1}\boldsymbol{X}^T\boldsymbol{y}, +$$ -# The Training Data +

    +with \( \boldsymbol{I} \) being a \( p\times p \) identity matrix with the constraint that -N_train=100 +$$ +\sum_{i=0}^{p-1} \beta_i^2 \leq t, +$$ -sigma_train=1; +

    +with \( t \) a finite positive number. -# Train on integers -x=np.linspace(0.05,0.95,N_train) -# Draw random noise -s = sigma_train*np.random.randn(N_train) +

    +We see that Ridge regression is nothing but the standard +OLS with a modified diagonal term added to \( \boldsymbol{X}^T\boldsymbol{X} \). The +consequences, in particular for our discussion of the bias-variance +are rather interesting. -#linear -y=2*x+s +

    +Furthermore, if we use the result above in terms of the SVD decomposition (our analysis was done for the OLS method), we had +$$ +(\boldsymbol{X}\boldsymbol{X}^T)\boldsymbol{U} = \boldsymbol{U}\boldsymbol{D}. +$$ -#Tenth Order -#y=2*x-10*x**5+15*x**10+s +

    +We can analyse the OLS solutions in terms of the eigenvectors (the columns) of the right singular value matrix \( \boldsymbol{U} \) as +$$ +\boldsymbol{X}\boldsymbol{\beta} = \boldsymbol{X}\left(\boldsymbol{V}\boldsymbol{D}\boldsymbol{V}^T \right)^{-1}\boldsymbol{X}^T\boldsymbol{y}=\boldsymbol{U\Sigma V^T}\left(\boldsymbol{V}\boldsymbol{D}\boldsymbol{V}^T \right)^{-1}(\boldsymbol{U\Sigma V^T})^T\boldsymbol{y}=\boldsymbol{U}\boldsymbol{U}^T\boldsymbol{y} +$$ -p1=plt.plot(x,y, "o",ms=15, label='Training') +

    +For Ridge regression this becomes -#Linear Regression -# Create linear regression object -clf = linear_model.LinearRegression() +$$ +\boldsymbol{X}\boldsymbol{\beta}^{\mathrm{Ridge}} = \boldsymbol{U\Sigma V^T}\left(\boldsymbol{V}\boldsymbol{D}\boldsymbol{V}^T+\lambda\boldsymbol{I} \right)^{-1}(\boldsymbol{U\Sigma V^T})^T\boldsymbol{y}=\sum_{j=0}^{p-1}\boldsymbol{u}_j\boldsymbol{u}_j^T\frac{\sigma_j^2}{\sigma_j^2+\lambda}\boldsymbol{y}, +$$ -# Train the model using the training sets -clf.fit(x[:, np.newaxis], y) -# The coefficients +

    +with the vectors \( \boldsymbol{u}_j \) being the columns of \( \boldsymbol{U} \). -xplot=np.linspace(0.02,0.98,200) -linear_plot=plt.plot(xplot, clf.predict(xplot[:, np.newaxis]),label='Linear') - -#Polynomial Regression - - -poly3 = PolynomialFeatures(degree=3) -X = poly3.fit_transform(x[:,np.newaxis]) -clf3 = linear_model.LinearRegression() -clf3.fit(X,y) - - -Xplot=poly3.fit_transform(xplot[:,np.newaxis]) -poly3_plot=plt.plot(xplot, clf3.predict(Xplot), label='Poly 3') - - - -#poly5 = PolynomialFeatures(degree=5) -#X = poly5.fit_transform(x[:,np.newaxis]) -#clf5 = linear_model.LinearRegression() -#clf5.fit(X,y) - -#Xplot=poly5.fit_transform(xplot[:,np.newaxis]) -#plt.plot(xplot, clf5.predict(Xplot), 'r--',linewidth=1) - -poly10 = PolynomialFeatures(degree=10) -X = poly10.fit_transform(x[:,np.newaxis]) -clf10 = linear_model.LinearRegression() -clf10.fit(X,y) - -Xplot=poly10.fit_transform(xplot[:,np.newaxis]) -poly10_plot=plt.plot(xplot, clf10.predict(Xplot), label='Poly 10') - -axes = plt.gca() -axes.set_ylim([-7,7]) - -handles, labels=axes.get_legend_handles_labels() -plt.legend(handles,labels, loc='lower center') -plt.xlabel("$x$") -plt.ylabel("$y$") -Title="$N=$"+str(N_train)+", $\sigma=$"+str(sigma_train) -plt.title(Title+" (train)") -plt.tight_layout() -plt.show() -

    @@ -527,7 +463,7 @@ plt.show()

  • 49
  • 50
  • ...
  • -
  • 114
  • +
  • 100
  • »
  • diff --git a/doc/pub/Regression/html/._Regression-bs041.html b/doc/pub/Regression/html/._Regression-bs041.html index 96cbe1e26..4f7064b9e 100644 --- a/doc/pub/Regression/html/._Regression-bs041.html +++ b/doc/pub/Regression/html/._Regression-bs041.html @@ -6,6 +6,7 @@ Automatically generated HTML file from DocOnce source + Data Analysis and Machine Learning: Linear Regression and more Advanced Regression Analysis @@ -40,160 +41,151 @@ Automatically generated HTML file from DocOnce source @@ -286,119 +263,109 @@ MathJax.Hub.Config({ @@ -412,51 +379,29 @@ MathJax.Hub.Config({

     

     

     

    - + + +

    Interpreting the Ridge results

    -

    Generating test data

    +Since \( \lambda \geq 0 \), it means that compared to OLS, we have - -

    # Generate Test Data
    +$$
    +\frac{\sigma_j^2}{\sigma_j^2+\lambda} \leq 1. 
    +$$
     
    -#Number of test data
    -N_test=20
    +

    +Ridge regression finds the coordinates of \( \boldsymbol{y} \) with respect to the +orthonormal basis \( \boldsymbol{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} \). -sigma_test=sigma_train +

    +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 \( \boldsymbol{X}\boldsymbol{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. -max_x=1.2 -x_test=max_x*np.random.random(N_test) -# Draw random noise -s_test = sigma_test*np.random.randn(N_test) - -#Linear -y_test=2*x_test+s_test -#Tenth order -#y_test=2*x_test-10*x_test**5+15*x_test**10+s_test - -#Make design matrices for prediction -x_plot=np.linspace(0,max_x, 200) -X3 = poly3.fit_transform(x_plot[:,np.newaxis]) -X10 = poly10.fit_transform(x_plot[:,np.newaxis]) - -%matplotlib notebook - -fig = plt.figure() -p1=plt.plot(x_test,y_test.transpose(), 'o', ms=12, label='data') -p2=plt.plot(x_plot,clf.predict(x_plot[:,np.newaxis]), label='linear') -p3=plt.plot(x_plot,clf3.predict(X3), label='3rd order') -p10=plt.plot(x_plot,clf10.predict(X10), label='10th order') - - -plt.legend(loc=2) -plt.xlabel('$x$') -plt.ylabel('$y$') -plt.legend(loc='best') -plt.title(Title+" (pred.)") -plt.tight_layout() -plt.show() -

    @@ -483,7 +428,7 @@ plt.show()

  • 50
  • 51
  • ...
  • -
  • 114
  • +
  • 100
  • »
  • diff --git a/doc/pub/Regression/html/._Regression-bs042.html b/doc/pub/Regression/html/._Regression-bs042.html index fcbc663f5..0c995529e 100644 --- a/doc/pub/Regression/html/._Regression-bs042.html +++ b/doc/pub/Regression/html/._Regression-bs042.html @@ -6,6 +6,7 @@ Automatically generated HTML file from DocOnce source + Data Analysis and Machine Learning: Linear Regression and more Advanced Regression Analysis @@ -40,160 +41,151 @@ Automatically generated HTML file from DocOnce source @@ -286,119 +263,109 @@ MathJax.Hub.Config({ @@ -414,13 +381,39 @@ MathJax.Hub.Config({ -

    How can we effectively evaluate the various models?

    +

    More interpretations

    -In Ridge regression and the subsequent discussion of its properties -the bias or penalty parameter is considered known or `given'. In -practice, it is unknown and the user needs to make an informed -decision on its value. How do we do that? Much of the same considerations apply to the Lasso method. +For the sake of simplicity, let us assume that the design matrix is orthonormal, that is + +$$ +\boldsymbol{X}^T\boldsymbol{X}=(\boldsymbol{X}^T\boldsymbol{X})^{-1} =\boldsymbol{I}. +$$ + +

    +In this case the standard OLS results in +$$ +\boldsymbol{\beta}^{\mathrm{OLS}} = \boldsymbol{X}^T\boldsymbol{y}=\sum_{i=0}^{p-1}\boldsymbol{u}_j\boldsymbol{u}_j^T\boldsymbol{y}, +$$ + +

    +and + +$$ +\boldsymbol{\beta}^{\mathrm{Ridge}} = \left(\boldsymbol{I}+\lambda\boldsymbol{I}\right)^{-1}\boldsymbol{X}^T\boldsymbol{y}=\left(1+\lambda\right)^{-1}\boldsymbol{\beta}^{\mathrm{OLS}}, +$$ + +

    +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 article is highly recommended. +Similarly, Mehta et al's article is also recommended.

    @@ -448,7 +441,7 @@ decision on its value. How do we do that? Much of the same considerations apply

  • 51
  • 52
  • ...
  • -
  • 114
  • +
  • 100
  • »
  • diff --git a/doc/pub/Regression/html/._Regression-bs043.html b/doc/pub/Regression/html/._Regression-bs043.html index 52e238d29..c44c78991 100644 --- a/doc/pub/Regression/html/._Regression-bs043.html +++ b/doc/pub/Regression/html/._Regression-bs043.html @@ -6,6 +6,7 @@ Automatically generated HTML file from DocOnce source + Data Analysis and Machine Learning: Linear Regression and more Advanced Regression Analysis @@ -40,160 +41,151 @@ Automatically generated HTML file from DocOnce source @@ -286,119 +263,109 @@ MathJax.Hub.Config({ @@ -414,84 +381,20 @@ MathJax.Hub.Config({ -

    Code examples for Ridge and Lasso Regression

    +

    Where are we going?

    +Before we proceed, we need to rethink what we have been doing. In our +eager to fit the data, we have omitted several important elements in +our regression analysis. In what follows we will - -

    import matplotlib.pyplot as plt
    -import numpy as np
    -from sklearn import linear_model
    -from sklearn.linear_model import LinearRegression
    -from sklearn.metrics import mean_squared_error, r2_score
    +
      +
    1. look at statistical properties, including a discussion of mean values, variance and the so-called bias-variance tradeoff
    2. +
    3. introduce resampling techniques like cross-validation, bootstrapping and jackknife and more
    4. +
    -#creating data with random noise -x=np.arange(50) +This will allow us to link the standard linear algebra methods we have discussed above to a statistical interpretation of the methods. -delta=np.random.uniform(-2.5,2.5, size=(50)) -np.random.shuffle(delta) -y =0.5*x+5+delta - -#arranging data into 2x50 matrix -a=np.array(x) #inputs -b=np.array(y) #outputs - -#Split into training and test -X_train=a[:37, np.newaxis] -X_test=a[37:, np.newaxis] -y_train=b[:37] -y_test=b[37:] - -print ("X_train: ", X_train.shape) -print ("y_train: ", y_train.shape) -print ("X_test: ", X_test.shape) -print ("y_test: ", y_test.shape) - -print ("------------------------------------") - -print ("Ordinary Least Squares") -#Add Ordinary Least Squares fit -reg=LinearRegression() -reg.fit(X_train, y_train) -pred=reg.predict(X_test) -print ("Prediction Shape: ", pred.shape) - -print('Coefficients: \n', reg.coef_) -# The mean squared error -print("Mean squared error: %.2f" - % mean_squared_error(y_test, pred)) -# Explained variance score: 1 is perfect prediction -print('Variance score: %.2f' % r2_score(y_test, pred)) - -#plot -plt.scatter(X_test,y_test,color='green', label="Training Data") -plt.plot(X_test, pred, color='black', label="Fit Line") -plt.legend() -plt.show() - -print ("------------------------------------") - -print ("Ridge Regression") - -ridge=linear_model.RidgeCV(alphas=[0.1,1.0,10.0]) -ridge.fit(X_train,y_train) -print ("Ridge Coefficient: ",ridge.coef_) -print ("Ridge Intercept: ", ridge.intercept_) -#Look into graphing with Ridge fit - -print ("------------------------------------") - -print ("Lasso") -lasso=linear_model.Lasso(alpha=0.1) -lasso.fit(X_train,y_train) -predl=lasso.predict(X_test) -print("Lasso Coefficient: ", lasso.coef_) -print("Lasso Intercept: ", lasso.intercept_) -plt.scatter(X_test,y_test,color='green', label="Training Data") -plt.plot(X_test, predl, color='blue', label="Lasso") -plt.legend() -plt.show() -

    @@ -518,7 +421,7 @@ plt.show()

  • 52
  • 53
  • ...
  • -
  • 114
  • +
  • 100
  • »
  • diff --git a/doc/pub/Regression/html/._Regression-bs044.html b/doc/pub/Regression/html/._Regression-bs044.html index 1e8fd3f87..fc2bf6ad7 100644 --- a/doc/pub/Regression/html/._Regression-bs044.html +++ b/doc/pub/Regression/html/._Regression-bs044.html @@ -6,6 +6,7 @@ Automatically generated HTML file from DocOnce source + Data Analysis and Machine Learning: Linear Regression and more Advanced Regression Analysis @@ -40,160 +41,151 @@ Automatically generated HTML file from DocOnce source @@ -286,119 +263,109 @@ MathJax.Hub.Config({ @@ -414,117 +381,24 @@ MathJax.Hub.Config({ -

    A second-order polynomial with Ridge and Lasso

    -

    - - -

    import numpy as np
    -import matplotlib.pyplot as plt
    -from sklearn.linear_model import Ridge
    -from sklearn.metrics import r2_score
    -
    -np.random.seed(4155)
    -
    -n_samples = 100
    -
    -x = np.random.rand(n_samples,1)
    -y = 5*x*x + 0.1*np.random.rand(n_samples,1)
    -
    -# Centering  x and y.
    -x_ = x - np.mean(x)
    -y_ = y - np.mean(y) # beta_0 = mean(y)
    -
    -X = np.c_[np.ones((n_samples,1)), x, x**2]
    -X_ = np.c_[x_, x_**2]
    +

    Resampling methods

    +
    +
    +

    +Resampling methods are an indispensable tool in modern +statistics. They involve repeatedly drawing samples from a training +set and refitting a model of interest on each sample in order to +obtain additional information about the fitted model. For example, in +order to estimate the variability of a linear regression fit, we can +repeatedly draw different samples from the training data, fit a linear +regression to each new sample, and then examine the extent to which +the resulting fits differ. Such an approach may allow us to obtain +information that would not be available from fitting the model only +once using the original training sample. +

    +
    -### 1. -lmb_values = [1e-4, 1e-3, 1e-2, 10, 1e2, 1e4] -num_values = len(lmb_values) - -## Ridge-regression of centered and not centered data -beta_ridge = np.zeros((3,num_values)) -beta_ridge_centered = np.zeros((3,num_values)) - -I3 = np.eye(3) -I2 = np.eye(2) - -for i,lmb in enumerate(lmb_values): - beta_ridge[:,i] = (np.linalg.inv( X.T @ X + lmb*I3) @ X.T @ y).flatten() - beta_ridge_centered[1:,i] = (np.linalg.inv( X_.T @ X_ + lmb*I2) @ X_.T @ y_).flatten() - -# sett beta_0 = np.mean(y) -beta_ridge_centered[0,:] = np.mean(y) - -## OLS (ordinary least squares) solution -beta_ls = np.linalg.inv( X.T @ X ) @ X.T @ y - -## Evaluate the models -pred_ls = X @ beta_ls -pred_ridge = X @ beta_ridge -pred_ridge_centered = X_ @ beta_ridge_centered[1:] + beta_ridge_centered[0,:] - -## Plot the results - -# Sorting -sort_ind = np.argsort(x[:,0]) - -x_plot = x[sort_ind,0] -x_centered_plot = x_[sort_ind,0] - -pred_ls_plot = pred_ls[sort_ind,0] -pred_ridge_plot = pred_ridge[sort_ind,:] -pred_ridge_centered_plot = pred_ridge_centered[sort_ind,:] - -# Plott not centered -plt.plot(x_plot,pred_ls_plot,label='ls') - -for i in range(num_values): - plt.plot(x_plot,pred_ridge_plot[:,i],label='ridge, lmb=%g'%lmb_values[i]) - -plt.plot(x,y,'ro') - -plt.title('linear regression on un-centered data') -plt.legend() - -# Plott centered -plt.figure() - -for i in range(num_values): - plt.plot(x_centered_plot,pred_ridge_centered_plot[:,i],label='ridge, lmb=%g'%lmb_values[i]) - -plt.plot(x_,y,'ro') - -plt.title('linear regression on centered data') -plt.legend() - - -# 2. - -pred_ridge_scikit = np.zeros((n_samples,num_values)) -for i,lmb in enumerate(lmb_values): - pred_ridge_scikit[:,i] = (Ridge(alpha=lmb,fit_intercept=False).fit(X,y).predict(X)).flatten() # fit_intercept=False fordi bias er allerede i X - -plt.figure() - -plt.plot(x_plot,pred_ls_plot,label='ls') - -for i in range(num_values): - plt.plot(x_plot,pred_ridge_scikit[sort_ind,i],label='scikit-ridge, lmb=%g'%lmb_values[i]) - -plt.plot(x,y,'ro') -plt.legend() -plt.title('linear regression using scikit') - -plt.show() - -### R2-score of the results -for i in range(num_values): - print('lambda = %g'%lmb_values[i]) - print('r2 for scikit: %g'%r2_score(y,pred_ridge_scikit[:,i])) - print('r2 for own code, not centered: %g'%r2_score(y,pred_ridge[:,i])) - print('r2 for own, centered: %g\n'%r2_score(y,pred_ridge_centered[:,i])) -

    @@ -551,7 +425,7 @@ plt.show()

  • 53
  • 54
  • ...
  • -
  • 114
  • +
  • 100
  • »
  • diff --git a/doc/pub/Regression/html/._Regression-bs045.html b/doc/pub/Regression/html/._Regression-bs045.html index 7d66761e5..082121081 100644 --- a/doc/pub/Regression/html/._Regression-bs045.html +++ b/doc/pub/Regression/html/._Regression-bs045.html @@ -6,6 +6,7 @@ Automatically generated HTML file from DocOnce source + Data Analysis and Machine Learning: Linear Regression and more Advanced Regression Analysis @@ -40,160 +41,151 @@ Automatically generated HTML file from DocOnce source @@ -286,119 +263,109 @@ MathJax.Hub.Config({ @@ -414,20 +381,29 @@ MathJax.Hub.Config({ -

    Resampling methods

    +

    Resampling approaches can be computationally expensive

    -Resampling methods are an indispensable tool in modern -statistics. They involve repeatedly drawing samples from a training -set and refitting a model of interest on each sample in order to -obtain additional information about the fitted model. For example, in -order to estimate the variability of a linear regression fit, we can -repeatedly draw different samples from the training data, fit a linear -regression to each new sample, and then examine the extent to which -the resulting fits differ. Such an approach may allow us to obtain -information that would not be available from fitting the model only -once using the original training sample. + +

    +Resampling approaches can be computationally expensive, because they +involve fitting the same statistical method multiple times using +different subsets of the training data. However, due to recent +advances in computing power, the computational requirements of +resampling methods generally are not prohibitive. In this chapter, we +discuss two of the most commonly used resampling methods, +cross-validation and the bootstrap. Both methods are important tools +in the practical application of many statistical learning +procedures. For example, cross-validation can be used to estimate the +test error associated with a given statistical learning method in +order to evaluate its performance, or to select the appropriate level +of flexibility. The process of evaluating a model’s performance is +known as model assessment, whereas the process of selecting the proper +level of flexibility for a model is known as model selection. The +bootstrap is widely used. + +

    @@ -458,7 +434,7 @@ once using the original training sample.
  • 54
  • 55
  • ...
  • -
  • 114
  • +
  • 100
  • »
  • diff --git a/doc/pub/Regression/html/._Regression-bs046.html b/doc/pub/Regression/html/._Regression-bs046.html index 34d53eedf..77b3f2369 100644 --- a/doc/pub/Regression/html/._Regression-bs046.html +++ b/doc/pub/Regression/html/._Regression-bs046.html @@ -6,6 +6,7 @@ Automatically generated HTML file from DocOnce source + Data Analysis and Machine Learning: Linear Regression and more Advanced Regression Analysis @@ -40,160 +41,151 @@ Automatically generated HTML file from DocOnce source @@ -286,119 +263,109 @@ MathJax.Hub.Config({ @@ -414,25 +381,16 @@ MathJax.Hub.Config({ -

    Resampling approaches can be computationally expensive

    +

    Why resampling methods ?

    -Resampling approaches can be computationally expensive, because they -involve fitting the same statistical method multiple times using -different subsets of the training data. However, due to recent -advances in computing power, the computational requirements of -resampling methods generally are not prohibitive. In this chapter, we -discuss two of the most commonly used resampling methods, -cross-validation and the bootstrap. Both methods are important tools -in the practical application of many statistical learning -procedures. For example, cross-validation can be used to estimate the -test error associated with a given statistical learning method in -order to evaluate its performance, or to select the appropriate level -of flexibility. The process of evaluating a model’s performance is -known as model assessment, whereas the process of selecting the proper -level of flexibility for a model is known as model selection. The -bootstrap is widely used. + +

      +
    • Our simulations can be treated as computer experiments. This is particularly the case for Monte Carlo methods
    • +
    • The results can be analysed with the same statistical tools as we would use analysing experimental data.
    • +
    • As in all experiments, we are looking for expectation values and an estimate of how accurate they are, i.e., possible sources for errors.
    • +
    @@ -463,7 +421,7 @@ bootstrap is widely used.
  • 55
  • 56
  • ...
  • -
  • 114
  • +
  • 100
  • »
  • diff --git a/doc/pub/Regression/html/._Regression-bs047.html b/doc/pub/Regression/html/._Regression-bs047.html index fb176bcbf..927b9be13 100644 --- a/doc/pub/Regression/html/._Regression-bs047.html +++ b/doc/pub/Regression/html/._Regression-bs047.html @@ -6,6 +6,7 @@ Automatically generated HTML file from DocOnce source + Data Analysis and Machine Learning: Linear Regression and more Advanced Regression Analysis @@ -40,160 +41,151 @@ Automatically generated HTML file from DocOnce source @@ -286,119 +263,109 @@ MathJax.Hub.Config({ @@ -414,15 +381,21 @@ MathJax.Hub.Config({ -

    Why resampling methods ?

    +

    Statistical analysis

      -
    • Our simulations can be treated as computer experiments. This is particularly the case for Monte Carlo methods
    • -
    • The results can be analysed with the same statistical tools as we would use analysing experimental data.
    • -
    • As in all experiments, we are looking for expectation values and an estimate of how accurate they are, i.e., possible sources for errors.
    • +
    • As in other experiments, many numerical experiments have two classes of errors:
    • + +
        +
      • Statistical errors
      • +
      • Systematical errors
      • +
      + +
    • Statistical errors can be estimated using standard tools from statistics
    • +
    • Systematical errors are method specific and must be treated differently from case to case.
    @@ -454,7 +427,7 @@ MathJax.Hub.Config({
  • 56
  • 57
  • ...
  • -
  • 114
  • +
  • 100
  • »
  • diff --git a/doc/pub/Regression/html/._Regression-bs048.html b/doc/pub/Regression/html/._Regression-bs048.html index f91dc6263..6beabb135 100644 --- a/doc/pub/Regression/html/._Regression-bs048.html +++ b/doc/pub/Regression/html/._Regression-bs048.html @@ -6,6 +6,7 @@ Automatically generated HTML file from DocOnce source + Data Analysis and Machine Learning: Linear Regression and more Advanced Regression Analysis @@ -40,160 +41,151 @@ Automatically generated HTML file from DocOnce source @@ -286,119 +263,109 @@ MathJax.Hub.Config({ @@ -414,22 +381,31 @@ MathJax.Hub.Config({ -

    Statistical analysis

    +

    Statistics

    +The probability distribution function (PDF) is a function +\( p(x) \) on the domain which, in the discrete case, gives us the +probability or relative frequency with which these values of \( X \) occur: +$$ +p(x) = \mathrm{prob}(X=x) +$$ -

      -
    • As in other experiments, many numerical experiments have two classes of errors:
    • +In the continuous case, the PDF does not directly depict the +actual probability. Instead we define the probability for the +stochastic variable to assume any value on an infinitesimal interval +around \( x \) to be \( p(x)dx \). The continuous function \( p(x) \) then gives us +the density of the probability rather than the probability +itself. The probability for a stochastic variable to assume any value +on a non-infinitesimal interval \( [a,\,b] \) is then just the integral: +$$ +\mathrm{prob}(a\leq X\leq b) = \int_a^b p(x)dx +$$ -
        -
      • Statistical errors
      • -
      • Systematical errors
      • -
      - -
    • Statistical errors can be estimated using standard tools from statistics
    • -
    • Systematical errors are method specific and must be treated differently from case to case.
    • -
    +Qualitatively speaking, a stochastic variable represents the values of +numbers chosen as if by chance from some specified PDF so that the +selection of a large set of these numbers reproduces this PDF.
    @@ -460,7 +436,7 @@ MathJax.Hub.Config({
  • 57
  • 58
  • ...
  • -
  • 114
  • +
  • 100
  • »
  • diff --git a/doc/pub/Regression/html/._Regression-bs049.html b/doc/pub/Regression/html/._Regression-bs049.html index 33b6d6914..70d02b6a2 100644 --- a/doc/pub/Regression/html/._Regression-bs049.html +++ b/doc/pub/Regression/html/._Regression-bs049.html @@ -6,6 +6,7 @@ Automatically generated HTML file from DocOnce source + Data Analysis and Machine Learning: Linear Regression and more Advanced Regression Analysis @@ -40,160 +41,151 @@ Automatically generated HTML file from DocOnce source @@ -286,119 +263,109 @@ MathJax.Hub.Config({ @@ -414,31 +381,23 @@ MathJax.Hub.Config({ -

    Statistics

    +

    Statistics, moments

    -The probability distribution function (PDF) is a function -\( p(x) \) on the domain which, in the discrete case, gives us the -probability or relative frequency with which these values of \( X \) occur: +A particularly useful class of special expectation values are the +moments. The \( n \)-th moment of the PDF \( p \) is defined as +follows: $$ -p(x) = \mathrm{prob}(X=x) +\langle x^n\rangle \equiv \int\! x^n p(x)\,dx $$ -In the continuous case, the PDF does not directly depict the -actual probability. Instead we define the probability for the -stochastic variable to assume any value on an infinitesimal interval -around \( x \) to be \( p(x)dx \). The continuous function \( p(x) \) then gives us -the density of the probability rather than the probability -itself. The probability for a stochastic variable to assume any value -on a non-infinitesimal interval \( [a,\,b] \) is then just the integral: +The zero-th moment \( \langle 1\rangle \) is just the normalization condition of +\( p \). The first moment, \( \langle x\rangle \), is called the mean of \( p \) +and often denoted by the letter \( \mu \): $$ -\mathrm{prob}(a\leq X\leq b) = \int_a^b p(x)dx +\langle x\rangle = \mu \equiv \int\! x p(x)\,dx $$ - -Qualitatively speaking, a stochastic variable represents the values of -numbers chosen as if by chance from some specified PDF so that the -selection of a large set of these numbers reproduces this PDF.

    @@ -469,7 +428,7 @@ selection of a large set of these numbers reproduces this PDF.
  • 58
  • 59
  • ...
  • -
  • 114
  • +
  • 100
  • »
  • diff --git a/doc/pub/Regression/html/._Regression-bs050.html b/doc/pub/Regression/html/._Regression-bs050.html index 5df54a162..fd305b0a5 100644 --- a/doc/pub/Regression/html/._Regression-bs050.html +++ b/doc/pub/Regression/html/._Regression-bs050.html @@ -6,6 +6,7 @@ Automatically generated HTML file from DocOnce source + Data Analysis and Machine Learning: Linear Regression and more Advanced Regression Analysis @@ -40,160 +41,151 @@ Automatically generated HTML file from DocOnce source @@ -286,119 +263,109 @@ MathJax.Hub.Config({ @@ -414,23 +381,38 @@ MathJax.Hub.Config({ -

    Statistics, moments

    +

    Statistics, central moments

    -A particularly useful class of special expectation values are the -moments. The \( n \)-th moment of the PDF \( p \) is defined as -follows: +A special version of the moments is the set of central moments, +the n-th central moment defined as: $$ -\langle x^n\rangle \equiv \int\! x^n p(x)\,dx +\langle (x-\langle x \rangle )^n\rangle \equiv \int\! (x-\langle x\rangle)^n p(x)\,dx $$ -The zero-th moment \( \langle 1\rangle \) is just the normalization condition of -\( p \). The first moment, \( \langle x\rangle \), is called the mean of \( p \) -and often denoted by the letter \( \mu \): +The zero-th and first central moments are both trivial, equal \( 1 \) and +\( 0 \), respectively. But the second central moment, known as the +variance of \( p \), is of particular interest. For the stochastic +variable \( X \), the variance is denoted as \( \sigma^2_X \) or \( \mathrm{var}(X) \): $$ -\langle x\rangle = \mu \equiv \int\! x p(x)\,dx +\begin{align} +\sigma^2_X\ \ =\ \ \mathrm{var}(X) & = \langle (x-\langle x\rangle)^2\rangle = +\int\! (x-\langle x\rangle)^2 p(x)\,dx +\tag{8}\\ +& = \int\! \left(x^2 - 2 x \langle x\rangle^{2} + + \langle x\rangle^2\right)p(x)\,dx +\tag{9}\\ +& = \langle x^2\rangle - 2 \langle x\rangle\langle x\rangle + \langle x\rangle^2 +\tag{10}\\ +& = \langle x^2\rangle - \langle x\rangle^2 +\tag{11} +\end{align} $$ + +The square root of the variance, \( \sigma =\sqrt{\langle (x-\langle x\rangle)^2\rangle} \) is called the standard deviation of \( p \). It is clearly just the RMS (root-mean-square) +value of the deviation of the PDF from its mean value, interpreted +qualitatively as the spread of \( p \) around its mean.

    @@ -461,7 +443,7 @@ $$
  • 59
  • 60
  • ...
  • -
  • 114
  • +
  • 100
  • »
  • diff --git a/doc/pub/Regression/html/._Regression-bs051.html b/doc/pub/Regression/html/._Regression-bs051.html index 25ad4a2c5..1f7e91c6d 100644 --- a/doc/pub/Regression/html/._Regression-bs051.html +++ b/doc/pub/Regression/html/._Regression-bs051.html @@ -6,6 +6,7 @@ Automatically generated HTML file from DocOnce source + Data Analysis and Machine Learning: Linear Regression and more Advanced Regression Analysis @@ -40,160 +41,151 @@ Automatically generated HTML file from DocOnce source @@ -286,119 +263,109 @@ MathJax.Hub.Config({ @@ -414,38 +381,31 @@ MathJax.Hub.Config({ -

    Statistics, central moments

    +

    Statistics, covariance

    -A special version of the moments is the set of central moments, -the n-th central moment defined as: -$$ -\langle (x-\langle x \rangle )^n\rangle \equiv \int\! (x-\langle x\rangle)^n p(x)\,dx -$$ - -The zero-th and first central moments are both trivial, equal \( 1 \) and -\( 0 \), respectively. But the second central moment, known as the -variance of \( p \), is of particular interest. For the stochastic -variable \( X \), the variance is denoted as \( \sigma^2_X \) or \( \mathrm{var}(X) \): +Another important quantity is the so called covariance, a variant of +the above defined variance. Consider again the set \( \{X_i\} \) of \( n \) +stochastic variables (not necessarily uncorrelated) with the +multivariate PDF \( P(x_1,\dots,x_n) \). The covariance of two +of the stochastic variables, \( X_i \) and \( X_j \), is defined as follows: $$ \begin{align} -\sigma^2_X\ \ =\ \ \mathrm{var}(X) & = \langle (x-\langle x\rangle)^2\rangle = -\int\! (x-\langle x\rangle)^2 p(x)\,dx -\tag{2}\\ -& = \int\! \left(x^2 - 2 x \langle x\rangle^{2} + - \langle x\rangle^2\right)p(x)\,dx -\tag{3}\\ -& = \langle x^2\rangle - 2 \langle x\rangle\langle x\rangle + \langle x\rangle^2 -\tag{4}\\ -& = \langle x^2\rangle - \langle x\rangle^2 -\tag{5} +\mathrm{cov}(X_i,\,X_j) &\equiv \langle (x_i-\langle x_i\rangle)(x_j-\langle x_j\rangle)\rangle +\nonumber\\ +&= +\int\!\cdots\!\int\!(x_i-\langle x_i \rangle)(x_j-\langle x_j \rangle)\, +P(x_1,\dots,x_n)\,dx_1\dots dx_n +\tag{12} \end{align} $$ -The square root of the variance, \( \sigma =\sqrt{\langle (x-\langle x\rangle)^2\rangle} \) is called the standard deviation of \( p \). It is clearly just the RMS (root-mean-square) -value of the deviation of the PDF from its mean value, interpreted -qualitatively as the spread of \( p \) around its mean. +with +$$ +\langle x_i\rangle = +\int\!\cdots\!\int\!x_i\,P(x_1,\dots,x_n)\,dx_1\dots dx_n +$$

    @@ -476,7 +436,7 @@ qualitatively as the spread of \( p \) around its mean.
  • 60
  • 61
  • ...
  • -
  • 114
  • +
  • 100
  • »
  • diff --git a/doc/pub/Regression/html/._Regression-bs052.html b/doc/pub/Regression/html/._Regression-bs052.html index dd62c0b68..bb072b2f6 100644 --- a/doc/pub/Regression/html/._Regression-bs052.html +++ b/doc/pub/Regression/html/._Regression-bs052.html @@ -6,6 +6,7 @@ Automatically generated HTML file from DocOnce source + Data Analysis and Machine Learning: Linear Regression and more Advanced Regression Analysis @@ -40,160 +41,151 @@ Automatically generated HTML file from DocOnce source @@ -286,119 +263,109 @@ MathJax.Hub.Config({ @@ -414,31 +381,32 @@ MathJax.Hub.Config({ -

    Statistics, covariance

    +

    Statistics, more covariance

    -Another important quantity is the so called covariance, a variant of -the above defined variance. Consider again the set \( \{X_i\} \) of \( n \) -stochastic variables (not necessarily uncorrelated) with the -multivariate PDF \( P(x_1,\dots,x_n) \). The covariance of two -of the stochastic variables, \( X_i \) and \( X_j \), is defined as follows: +If we consider the above covariance as a matrix \( C_{ij}=\mathrm{cov}(X_i,\,X_j) \), then the diagonal elements are just the familiar +variances, \( C_{ii} = \mathrm{cov}(X_i,\,X_i) = \mathrm{var}(X_i) \). It turns out that +all the off-diagonal elements are zero if the stochastic variables are +uncorrelated. This is easy to show, keeping in mind the linearity of +the expectation value. Consider the stochastic variables \( X_i \) and +\( X_j \), (\( i\neq j \)): $$ \begin{align} -\mathrm{cov}(X_i,\,X_j) &\equiv \langle (x_i-\langle x_i\rangle)(x_j-\langle x_j\rangle)\rangle -\nonumber\\ -&= -\int\!\cdots\!\int\!(x_i-\langle x_i \rangle)(x_j-\langle x_j \rangle)\, -P(x_1,\dots,x_n)\,dx_1\dots dx_n -\tag{6} +\mathrm{cov}(X_i,\,X_j) &= \langle(x_i-\langle x_i\rangle)(x_j-\langle x_j\rangle)\rangle +\tag{13}\\ +&=\langle x_i x_j - x_i\langle x_j\rangle - \langle x_i\rangle x_j + \langle x_i\rangle\langle x_j\rangle\rangle +\tag{14}\\ +&=\langle x_i x_j\rangle - \langle x_i\langle x_j\rangle\rangle - \langle \langle x_i\rangle x_j\rangle + +\langle \langle x_i\rangle\langle x_j\rangle\rangle +\tag{15}\\ +&=\langle x_i x_j\rangle - \langle x_i\rangle\langle x_j\rangle - \langle x_i\rangle\langle x_j\rangle + +\langle x_i\rangle\langle x_j\rangle +\tag{16}\\ +&=\langle x_i x_j\rangle - \langle x_i\rangle\langle x_j\rangle +\tag{17} \end{align} $$ - -with -$$ -\langle x_i\rangle = -\int\!\cdots\!\int\!x_i\,P(x_1,\dots,x_n)\,dx_1\dots dx_n -$$

    @@ -469,7 +437,7 @@ $$
  • 61
  • 62
  • ...
  • -
  • 114
  • +
  • 100
  • »
  • diff --git a/doc/pub/Regression/html/._Regression-bs053.html b/doc/pub/Regression/html/._Regression-bs053.html index 0b235efbb..bb2d31a84 100644 --- a/doc/pub/Regression/html/._Regression-bs053.html +++ b/doc/pub/Regression/html/._Regression-bs053.html @@ -6,6 +6,7 @@ Automatically generated HTML file from DocOnce source + Data Analysis and Machine Learning: Linear Regression and more Advanced Regression Analysis @@ -40,160 +41,151 @@ Automatically generated HTML file from DocOnce source @@ -286,119 +263,109 @@ MathJax.Hub.Config({ @@ -414,31 +381,25 @@ MathJax.Hub.Config({ -

    Statistics, more covariance

    +

    Statistics, independent variables

    -If we consider the above covariance as a matrix \( C_{ij}=\mathrm{cov}(X_i,\,X_j) \), then the diagonal elements are just the familiar -variances, \( C_{ii} = \mathrm{cov}(X_i,\,X_i) = \mathrm{var}(X_i) \). It turns out that -all the off-diagonal elements are zero if the stochastic variables are -uncorrelated. This is easy to show, keeping in mind the linearity of -the expectation value. Consider the stochastic variables \( X_i \) and -\( X_j \), (\( i\neq j \)): +If \( X_i \) and \( X_j \) are independent, we get +\( \langle x_i x_j\rangle =\langle x_i\rangle\langle x_j\rangle \), resulting in \( \mathrm{cov}(X_i, X_j) = 0\ \ (i\neq j) \). + +

    +Also useful for us is the covariance of linear combinations of +stochastic variables. Let \( \{X_i\} \) and \( \{Y_i\} \) be two sets of +stochastic variables. Let also \( \{a_i\} \) and \( \{b_i\} \) be two sets of +scalars. Consider the linear combination: $$ -\begin{align} -\mathrm{cov}(X_i,\,X_j) &= \langle(x_i-\langle x_i\rangle)(x_j-\langle x_j\rangle)\rangle -\tag{7}\\ -&=\langle x_i x_j - x_i\langle x_j\rangle - \langle x_i\rangle x_j + \langle x_i\rangle\langle x_j\rangle\rangle -\tag{8}\\ -&=\langle x_i x_j\rangle - \langle x_i\langle x_j\rangle\rangle - \langle \langle x_i\rangle x_j\rangle + -\langle \langle x_i\rangle\langle x_j\rangle\rangle -\tag{9}\\ -&=\langle x_i x_j\rangle - \langle x_i\rangle\langle x_j\rangle - \langle x_i\rangle\langle x_j\rangle + -\langle x_i\rangle\langle x_j\rangle -\tag{10}\\ -&=\langle x_i x_j\rangle - \langle x_i\rangle\langle x_j\rangle -\tag{11} -\end{align} +U = \sum_i a_i X_i \qquad V = \sum_j b_j Y_j +$$ + +By the linearity of the expectation value +$$ +\mathrm{cov}(U, V) = \sum_{i,j}a_i b_j \mathrm{cov}(X_i, Y_j) $$

    @@ -470,7 +431,7 @@ $$
  • 62
  • 63
  • ...
  • -
  • 114
  • +
  • 100
  • »
  • diff --git a/doc/pub/Regression/html/._Regression-bs054.html b/doc/pub/Regression/html/._Regression-bs054.html index 315684694..941746562 100644 --- a/doc/pub/Regression/html/._Regression-bs054.html +++ b/doc/pub/Regression/html/._Regression-bs054.html @@ -6,6 +6,7 @@ Automatically generated HTML file from DocOnce source + Data Analysis and Machine Learning: Linear Regression and more Advanced Regression Analysis @@ -40,160 +41,151 @@ Automatically generated HTML file from DocOnce source @@ -286,119 +263,109 @@ MathJax.Hub.Config({ @@ -414,26 +381,32 @@ MathJax.Hub.Config({ -

    Statistics, independent variables

    +

    Statistics, more variance

    -If \( X_i \) and \( X_j \) are independent, we get -\( \langle x_i x_j\rangle =\langle x_i\rangle\langle x_j\rangle \), resulting in \( \mathrm{cov}(X_i, X_j) = 0\ \ (i\neq j) \). - -

    -Also useful for us is the covariance of linear combinations of -stochastic variables. Let \( \{X_i\} \) and \( \{Y_i\} \) be two sets of -stochastic variables. Let also \( \{a_i\} \) and \( \{b_i\} \) be two sets of -scalars. Consider the linear combination: +Now, since the variance is just \( \mathrm{var}(X_i) = \mathrm{cov}(X_i, X_i) \), we get +the variance of the linear combination \( U = \sum_i a_i X_i \): $$ -U = \sum_i a_i X_i \qquad V = \sum_j b_j Y_j +\begin{equation} +\mathrm{var}(U) = \sum_{i,j}a_i a_j \mathrm{cov}(X_i, X_j) +\tag{18} +\end{equation} $$ -By the linearity of the expectation value +And in the special case when the stochastic variables are +uncorrelated, the off-diagonal elements of the covariance are as we +know zero, resulting in: $$ -\mathrm{cov}(U, V) = \sum_{i,j}a_i b_j \mathrm{cov}(X_i, Y_j) +\mathrm{var}(U) = \sum_i a_i^2 \mathrm{cov}(X_i, X_i) = \sum_i a_i^2 \mathrm{var}(X_i) $$ + +$$ +\mathrm{var}(\sum_i a_i X_i) = \sum_i a_i^2 \mathrm{var}(X_i) +$$ + +which will become very useful in our study of the error in the mean +value of a set of measurements.

    @@ -464,7 +437,7 @@ $$
  • 63
  • 64
  • ...
  • -
  • 114
  • +
  • 100
  • »
  • diff --git a/doc/pub/Regression/html/._Regression-bs055.html b/doc/pub/Regression/html/._Regression-bs055.html index 768ad98b4..beaf91621 100644 --- a/doc/pub/Regression/html/._Regression-bs055.html +++ b/doc/pub/Regression/html/._Regression-bs055.html @@ -6,6 +6,7 @@ Automatically generated HTML file from DocOnce source + Data Analysis and Machine Learning: Linear Regression and more Advanced Regression Analysis @@ -40,160 +41,151 @@ Automatically generated HTML file from DocOnce source @@ -286,119 +263,109 @@ MathJax.Hub.Config({ @@ -414,32 +381,28 @@ MathJax.Hub.Config({ -

    Statistics, more variance

    +

    Statistics and stochastic processes

    -Now, since the variance is just \( \mathrm{var}(X_i) = \mathrm{cov}(X_i, X_i) \), we get -the variance of the linear combination \( U = \sum_i a_i X_i \): +A stochastic process is a process that produces sequentially a +chain of values: $$ -\begin{equation} -\mathrm{var}(U) = \sum_{i,j}a_i a_j \mathrm{cov}(X_i, X_j) -\tag{12} -\end{equation} +\{x_1, x_2,\dots\,x_k,\dots\}. $$ -And in the special case when the stochastic variables are -uncorrelated, the off-diagonal elements of the covariance are as we -know zero, resulting in: -$$ -\mathrm{var}(U) = \sum_i a_i^2 \mathrm{cov}(X_i, X_i) = \sum_i a_i^2 \mathrm{var}(X_i) -$$ - -$$ -\mathrm{var}(\sum_i a_i X_i) = \sum_i a_i^2 \mathrm{var}(X_i) -$$ - -which will become very useful in our study of the error in the mean -value of a set of measurements. +We will call these +values our measurements and the entire set as our measured +sample. The action of measuring all the elements of a sample +we will call a stochastic experiment since, operationally, +they are often associated with results of empirical observation of +some physical or mathematical phenomena; precisely an experiment. We +assume that these values are distributed according to some +PDF \( p_X^{\phantom X}(x) \), where \( X \) is just the formal symbol for the +stochastic variable whose PDF is \( p_X^{\phantom X}(x) \). Instead of +trying to determine the full distribution \( p \) we are often only +interested in finding the few lowest moments, like the mean +\( \mu_X^{\phantom X} \) and the variance \( \sigma_X^{\phantom X} \).

    @@ -470,7 +433,7 @@ value of a set of measurements.
  • 64
  • 65
  • ...
  • -
  • 114
  • +
  • 100
  • »
  • diff --git a/doc/pub/Regression/html/._Regression-bs056.html b/doc/pub/Regression/html/._Regression-bs056.html index 713c99c8c..572f7309b 100644 --- a/doc/pub/Regression/html/._Regression-bs056.html +++ b/doc/pub/Regression/html/._Regression-bs056.html @@ -6,6 +6,7 @@ Automatically generated HTML file from DocOnce source + Data Analysis and Machine Learning: Linear Regression and more Advanced Regression Analysis @@ -40,160 +41,151 @@ Automatically generated HTML file from DocOnce source @@ -286,119 +263,109 @@ MathJax.Hub.Config({ @@ -412,30 +379,28 @@ MathJax.Hub.Config({

     

     

     

    - + -

    Statistics and stochastic processes

    +

    Statistics and sample variables

    -A stochastic process is a process that produces sequentially a -chain of values: +In practical situations a sample is always of finite size. Let that +size be \( n \). The expectation value of a sample, the sample mean, is then defined as follows: $$ -\{x_1, x_2,\dots\,x_k,\dots\}. +\bar{x}_n \equiv \frac{1}{n}\sum_{k=1}^n x_k $$ -We will call these -values our measurements and the entire set as our measured -sample. The action of measuring all the elements of a sample -we will call a stochastic experiment since, operationally, -they are often associated with results of empirical observation of -some physical or mathematical phenomena; precisely an experiment. We -assume that these values are distributed according to some -PDF \( p_X^{\phantom X}(x) \), where \( X \) is just the formal symbol for the -stochastic variable whose PDF is \( p_X^{\phantom X}(x) \). Instead of -trying to determine the full distribution \( p \) we are often only -interested in finding the few lowest moments, like the mean -\( \mu_X^{\phantom X} \) and the variance \( \sigma_X^{\phantom X} \). +The sample variance is: +$$ +\mathrm{var}(x) \equiv \frac{1}{n}\sum_{k=1}^n (x_k - \bar{x}_n)^2 +$$ + +its square root being the standard deviation of the sample. The +sample covariance is: +$$ +\mathrm{cov}(x)\equiv\frac{1}{n}\sum_{kl}(x_k - \bar{x}_n)(x_l - \bar{x}_n) +$$

    @@ -466,7 +431,7 @@ interested in finding the few lowest moments, like the mean
  • 65
  • 66
  • ...
  • -
  • 114
  • +
  • 100
  • »
  • diff --git a/doc/pub/Regression/html/._Regression-bs057.html b/doc/pub/Regression/html/._Regression-bs057.html index 83fba2452..48e567830 100644 --- a/doc/pub/Regression/html/._Regression-bs057.html +++ b/doc/pub/Regression/html/._Regression-bs057.html @@ -6,6 +6,7 @@ Automatically generated HTML file from DocOnce source + Data Analysis and Machine Learning: Linear Regression and more Advanced Regression Analysis @@ -40,160 +41,151 @@ Automatically generated HTML file from DocOnce source @@ -286,119 +263,109 @@ MathJax.Hub.Config({ @@ -412,28 +379,23 @@ MathJax.Hub.Config({

     

     

     

    - + -

    Statistics and sample variables

    +

    Statistics, sample variance and covariance

    -In practical situations a sample is always of finite size. Let that -size be \( n \). The expectation value of a sample, the sample mean, is then defined as follows: -$$ -\bar{x}_n \equiv \frac{1}{n}\sum_{k=1}^n x_k -$$ +Note that the sample variance is the sample covariance without the +cross terms. In a similar manner as the covariance in Eq. (12) is a measure of the correlation between +two stochastic variables, the above defined sample covariance is a +measure of the sequential correlation between succeeding measurements +of a sample. -The sample variance is: -$$ -\mathrm{var}(x) \equiv \frac{1}{n}\sum_{k=1}^n (x_k - \bar{x}_n)^2 -$$ - -its square root being the standard deviation of the sample. The -sample covariance is: -$$ -\mathrm{cov}(x)\equiv\frac{1}{n}\sum_{kl}(x_k - \bar{x}_n)(x_l - \bar{x}_n) -$$ +

    +These quantities, being known experimental values, differ +significantly from and must not be confused with the similarly named +quantities for stochastic variables, mean \( \mu_X \), variance \( \mathrm{var}(X) \) +and covariance \( \mathrm{cov}(X,Y) \).

    @@ -464,7 +426,7 @@ $$
  • 66
  • 67
  • ...
  • -
  • 114
  • +
  • 100
  • »
  • diff --git a/doc/pub/Regression/html/._Regression-bs058.html b/doc/pub/Regression/html/._Regression-bs058.html index aadb0d209..a0dc42c2a 100644 --- a/doc/pub/Regression/html/._Regression-bs058.html +++ b/doc/pub/Regression/html/._Regression-bs058.html @@ -6,6 +6,7 @@ Automatically generated HTML file from DocOnce source + Data Analysis and Machine Learning: Linear Regression and more Advanced Regression Analysis @@ -40,160 +41,151 @@ Automatically generated HTML file from DocOnce source @@ -286,119 +263,109 @@ MathJax.Hub.Config({ @@ -414,21 +381,32 @@ MathJax.Hub.Config({ -

    Statistics, sample variance and covariance

    +

    Statistics, law of large numbers

    -Note that the sample variance is the sample covariance without the -cross terms. In a similar manner as the covariance in Eq. (6) is a measure of the correlation between -two stochastic variables, the above defined sample covariance is a -measure of the sequential correlation between succeeding measurements -of a sample. +The law of large numbers +states that as the size of our sample grows to infinity, the sample +mean approaches the true mean \( \mu_X^{\phantom X} \) of the chosen PDF: +$$ +\lim_{n\to\infty}\bar{x}_n = \mu_X^{\phantom X} +$$ + +The sample mean \( \bar{x}_n \) works therefore as an estimate of the true +mean \( \mu_X^{\phantom X} \).

    -These quantities, being known experimental values, differ -significantly from and must not be confused with the similarly named -quantities for stochastic variables, mean \( \mu_X \), variance \( \mathrm{var}(X) \) -and covariance \( \mathrm{cov}(X,Y) \). +What we need to find out is how good an approximation \( \bar{x}_n \) is to +\( \mu_X^{\phantom X} \). In any stochastic measurement, an estimated +mean is of no use to us without a measure of its error. A quantity +that tells us how well we can reproduce it in another experiment. We +are therefore interested in the PDF of the sample mean itself. Its +standard deviation will be a measure of the spread of sample means, +and we will simply call it the error of the sample mean, or +just sample error, and denote it by \( \mathrm{err}_X^{\phantom X} \). In +practice, we will only be able to produce an estimate of the +sample error since the exact value would require the knowledge of the +true PDFs behind, which we usually do not have.

    @@ -459,7 +437,7 @@ and covariance \( \mathrm{cov}(X,Y) \).
  • 67
  • 68
  • ...
  • -
  • 114
  • +
  • 100
  • »
  • diff --git a/doc/pub/Regression/html/._Regression-bs059.html b/doc/pub/Regression/html/._Regression-bs059.html index 8c3582ffe..65d131b1d 100644 --- a/doc/pub/Regression/html/._Regression-bs059.html +++ b/doc/pub/Regression/html/._Regression-bs059.html @@ -6,6 +6,7 @@ Automatically generated HTML file from DocOnce source + Data Analysis and Machine Learning: Linear Regression and more Advanced Regression Analysis @@ -40,160 +41,151 @@ Automatically generated HTML file from DocOnce source @@ -286,119 +263,109 @@ MathJax.Hub.Config({ @@ -414,32 +381,22 @@ MathJax.Hub.Config({ -

    Statistics, law of large numbers

    +

    Statistics, more on sample error

    -The law of large numbers -states that as the size of our sample grows to infinity, the sample -mean approaches the true mean \( \mu_X^{\phantom X} \) of the chosen PDF: +Let us first take a look at what happens to the sample error as the +size of the sample grows. In a sample, each of the measurements \( x_i \) +can be associated with its own stochastic variable \( X_i \). The +stochastic variable \( \overline X_n \) for the sample mean \( \bar{x}_n \) is +then just a linear combination, already familiar to us: $$ -\lim_{n\to\infty}\bar{x}_n = \mu_X^{\phantom X} +\overline X_n = \frac{1}{n}\sum_{i=1}^n X_i $$ -The sample mean \( \bar{x}_n \) works therefore as an estimate of the true -mean \( \mu_X^{\phantom X} \). - -

    -What we need to find out is how good an approximation \( \bar{x}_n \) is to -\( \mu_X^{\phantom X} \). In any stochastic measurement, an estimated -mean is of no use to us without a measure of its error. A quantity -that tells us how well we can reproduce it in another experiment. We -are therefore interested in the PDF of the sample mean itself. Its -standard deviation will be a measure of the spread of sample means, -and we will simply call it the error of the sample mean, or -just sample error, and denote it by \( \mathrm{err}_X^{\phantom X} \). In -practice, we will only be able to produce an estimate of the -sample error since the exact value would require the knowledge of the -true PDFs behind, which we usually do not have. +All the coefficients are just equal \( 1/n \). The PDF of \( \overline X_n \), +denoted by \( p_{\overline X_n}(x) \) is the desired PDF of the sample +means.

    @@ -470,7 +427,7 @@ true PDFs behind, which we usually do not have.
  • 68
  • 69
  • ...
  • -
  • 114
  • +
  • 100
  • »
  • diff --git a/doc/pub/Regression/html/._Regression-bs060.html b/doc/pub/Regression/html/._Regression-bs060.html index f1406b77e..af1206cdd 100644 --- a/doc/pub/Regression/html/._Regression-bs060.html +++ b/doc/pub/Regression/html/._Regression-bs060.html @@ -6,6 +6,7 @@ Automatically generated HTML file from DocOnce source + Data Analysis and Machine Learning: Linear Regression and more Advanced Regression Analysis @@ -40,160 +41,151 @@ Automatically generated HTML file from DocOnce source @@ -286,119 +263,109 @@ MathJax.Hub.Config({ @@ -414,22 +381,21 @@ MathJax.Hub.Config({ -

    Statistics, more on sample error

    +

    Statistics

    -Let us first take a look at what happens to the sample error as the -size of the sample grows. In a sample, each of the measurements \( x_i \) -can be associated with its own stochastic variable \( X_i \). The -stochastic variable \( \overline X_n \) for the sample mean \( \bar{x}_n \) is -then just a linear combination, already familiar to us: +The probability density of obtaining a sample mean \( \bar x_n \) +is the product of probabilities of obtaining arbitrary values \( x_1, +x_2,\dots,x_n \) with the constraint that the mean of the set \( \{x_i\} \) +is \( \bar x_n \): $$ -\overline X_n = \frac{1}{n}\sum_{i=1}^n X_i +p_{\overline X_n}(x) = \int p_X^{\phantom X}(x_1)\cdots +\int p_X^{\phantom X}(x_n)\ +\delta\!\left(x - \frac{x_1+x_2+\dots+x_n}{n}\right)dx_n \cdots dx_1 $$ -All the coefficients are just equal \( 1/n \). The PDF of \( \overline X_n \), -denoted by \( p_{\overline X_n}(x) \) is the desired PDF of the sample -means. +And in particular we are interested in its variance \( \mathrm{var}(\overline X_n) \).

    @@ -460,7 +426,7 @@ means.
  • 69
  • 70
  • ...
  • -
  • 114
  • +
  • 100
  • »
  • diff --git a/doc/pub/Regression/html/._Regression-bs061.html b/doc/pub/Regression/html/._Regression-bs061.html index 27cc0477e..201c00019 100644 --- a/doc/pub/Regression/html/._Regression-bs061.html +++ b/doc/pub/Regression/html/._Regression-bs061.html @@ -6,6 +6,7 @@ Automatically generated HTML file from DocOnce source + Data Analysis and Machine Learning: Linear Regression and more Advanced Regression Analysis @@ -40,160 +41,151 @@ Automatically generated HTML file from DocOnce source @@ -286,119 +263,109 @@ MathJax.Hub.Config({ @@ -414,21 +381,25 @@ MathJax.Hub.Config({ -

    Statistics

    +

    Statistics, central limit theorem

    -The probability density of obtaining a sample mean \( \bar x_n \) -is the product of probabilities of obtaining arbitrary values \( x_1, -x_2,\dots,x_n \) with the constraint that the mean of the set \( \{x_i\} \) -is \( \bar x_n \): +It is generally not possible to express \( p_{\overline X_n}(x) \) in a +closed form given an arbitrary PDF \( p_X^{\phantom X} \) and a number +\( n \). But for the limit \( n\to\infty \) it is possible to make an +approximation. The very important result is called the central limit theorem. It tells us that as \( n \) goes to infinity, +\( p_{\overline X_n}(x) \) approaches a Gaussian distribution whose mean +and variance equal the true mean and variance, \( \mu_{X}^{\phantom X} \) +and \( \sigma_{X}^{2} \), respectively: $$ -p_{\overline X_n}(x) = \int p_X^{\phantom X}(x_1)\cdots -\int p_X^{\phantom X}(x_n)\ -\delta\!\left(x - \frac{x_1+x_2+\dots+x_n}{n}\right)dx_n \cdots dx_1 +\begin{equation} +\lim_{n\to\infty} p_{\overline X_n}(x) = +\left(\frac{n}{2\pi\mathrm{var}(X)}\right)^{1/2} +e^{-\frac{n(x-\bar x_n)^2}{2\mathrm{var}(X)}} +\tag{19} +\end{equation} $$ - -And in particular we are interested in its variance \( \mathrm{var}(\overline X_n) \).

    @@ -459,7 +430,7 @@ And in particular we are interested in its variance \( \mathrm{var}(\overline X_
  • 70
  • 71
  • ...
  • -
  • 114
  • +
  • 100
  • »
  • diff --git a/doc/pub/Regression/html/._Regression-bs062.html b/doc/pub/Regression/html/._Regression-bs062.html index 169d7c5ad..d7f70e544 100644 --- a/doc/pub/Regression/html/._Regression-bs062.html +++ b/doc/pub/Regression/html/._Regression-bs062.html @@ -6,6 +6,7 @@ Automatically generated HTML file from DocOnce source + Data Analysis and Machine Learning: Linear Regression and more Advanced Regression Analysis @@ -40,160 +41,151 @@ Automatically generated HTML file from DocOnce source @@ -286,119 +263,109 @@ MathJax.Hub.Config({ @@ -414,25 +381,29 @@ MathJax.Hub.Config({ -

    Statistics, central limit theorem

    +

    Statistics, more technicalities

    -It is generally not possible to express \( p_{\overline X_n}(x) \) in a -closed form given an arbitrary PDF \( p_X^{\phantom X} \) and a number -\( n \). But for the limit \( n\to\infty \) it is possible to make an -approximation. The very important result is called the central limit theorem. It tells us that as \( n \) goes to infinity, -\( p_{\overline X_n}(x) \) approaches a Gaussian distribution whose mean -and variance equal the true mean and variance, \( \mu_{X}^{\phantom X} \) -and \( \sigma_{X}^{2} \), respectively: +The desired variance +\( \mathrm{var}(\overline X_n) \), i.e. the sample error squared +\( \mathrm{err}_X^2 \), is given by: $$ \begin{equation} -\lim_{n\to\infty} p_{\overline X_n}(x) = -\left(\frac{n}{2\pi\mathrm{var}(X)}\right)^{1/2} -e^{-\frac{n(x-\bar x_n)^2}{2\mathrm{var}(X)}} -\tag{13} +\mathrm{err}_X^2 = \mathrm{var}(\overline X_n) = \frac{1}{n^2} +\sum_{ij} \mathrm{cov}(X_i, X_j) +\tag{20} \end{equation} $$ + +We see now that in order to calculate the exact error of the sample +with the above expression, we would need the true means +\( \mu_{X_i}^{\phantom X} \) of the stochastic variables \( X_i \). To +calculate these requires that we know the true multivariate PDF of all +the \( X_i \). But this PDF is unknown to us, we have only got the measurements of +one sample. The best we can do is to let the sample itself be an +estimate of the PDF of each of the \( X_i \), estimating all properties of +\( X_i \) through the measurements of the sample.

    @@ -463,7 +434,7 @@ $$
  • 71
  • 72
  • ...
  • -
  • 114
  • +
  • 100
  • »
  • diff --git a/doc/pub/Regression/html/._Regression-bs063.html b/doc/pub/Regression/html/._Regression-bs063.html index af25abf2b..853fd1a25 100644 --- a/doc/pub/Regression/html/._Regression-bs063.html +++ b/doc/pub/Regression/html/._Regression-bs063.html @@ -6,6 +6,7 @@ Automatically generated HTML file from DocOnce source + Data Analysis and Machine Learning: Linear Regression and more Advanced Regression Analysis @@ -40,160 +41,151 @@ Automatically generated HTML file from DocOnce source @@ -286,119 +263,109 @@ MathJax.Hub.Config({ @@ -414,29 +381,27 @@ MathJax.Hub.Config({ -

    Statistics, more technicalities

    +

    Statistics

    -The desired variance -\( \mathrm{var}(\overline X_n) \), i.e. the sample error squared -\( \mathrm{err}_X^2 \), is given by: +Our estimate of \( \mu_{X_i}^{\phantom X} \) is then the sample mean \( \bar x \) +itself, in accordance with the the central limit theorem: $$ -\begin{equation} -\mathrm{err}_X^2 = \mathrm{var}(\overline X_n) = \frac{1}{n^2} -\sum_{ij} \mathrm{cov}(X_i, X_j) -\tag{14} -\end{equation} +\mu_{X_i}^{\phantom X} = \langle x_i\rangle \approx \frac{1}{n}\sum_{k=1}^n x_k = \bar x $$ -We see now that in order to calculate the exact error of the sample -with the above expression, we would need the true means -\( \mu_{X_i}^{\phantom X} \) of the stochastic variables \( X_i \). To -calculate these requires that we know the true multivariate PDF of all -the \( X_i \). But this PDF is unknown to us, we have only got the measurements of -one sample. The best we can do is to let the sample itself be an -estimate of the PDF of each of the \( X_i \), estimating all properties of -\( X_i \) through the measurements of the sample. +Using \( \bar x \) in place of \( \mu_{X_i}^{\phantom X} \) we can give an +estimate of the covariance in Eq. (20) +$$ +\mathrm{cov}(X_i, X_j) = \langle (x_i-\langle x_i\rangle)(x_j-\langle x_j\rangle)\rangle +\approx\langle (x_i - \bar x)(x_j - \bar{x})\rangle, +$$ + +resulting in +$$ +\frac{1}{n} \sum_{l}^n \left(\frac{1}{n}\sum_{k}^n (x_k -\bar x_n)(x_l - \bar x_n)\right)=\frac{1}{n}\frac{1}{n} \sum_{kl} (x_k -\bar x_n)(x_l - \bar x_n)=\frac{1}{n}\mathrm{cov}(x) +$$

    @@ -467,7 +432,7 @@ estimate of the PDF of each of the \( X_i \), estimating all properties of
  • 72
  • 73
  • ...
  • -
  • 114
  • +
  • 100
  • »
  • diff --git a/doc/pub/Regression/html/._Regression-bs064.html b/doc/pub/Regression/html/._Regression-bs064.html index 35094512c..841a90caa 100644 --- a/doc/pub/Regression/html/._Regression-bs064.html +++ b/doc/pub/Regression/html/._Regression-bs064.html @@ -6,6 +6,7 @@ Automatically generated HTML file from DocOnce source + Data Analysis and Machine Learning: Linear Regression and more Advanced Regression Analysis @@ -40,160 +41,151 @@ Automatically generated HTML file from DocOnce source @@ -286,119 +263,109 @@ MathJax.Hub.Config({ @@ -414,27 +381,39 @@ MathJax.Hub.Config({ -

    Statistics

    +

    Statistics and sample variance

    -Our estimate of \( \mu_{X_i}^{\phantom X} \) is then the sample mean \( \bar x \) -itself, in accordance with the the central limit theorem: +By the same procedure we can use the sample variance as an +estimate of the variance of any of the stochastic variables \( X_i \) $$ -\mu_{X_i}^{\phantom X} = \langle x_i\rangle \approx \frac{1}{n}\sum_{k=1}^n x_k = \bar x +\mathrm{var}(X_i)=\langle x_i - \langle x_i\rangle\rangle \approx \langle x_i - \bar x_n\rangle\nonumber, $$ -Using \( \bar x \) in place of \( \mu_{X_i}^{\phantom X} \) we can give an -estimate of the covariance in Eq. (14) +which is approximated as $$ -\mathrm{cov}(X_i, X_j) = \langle (x_i-\langle x_i\rangle)(x_j-\langle x_j\rangle)\rangle -\approx\langle (x_i - \bar x)(x_j - \bar{x})\rangle, +\begin{equation} +\mathrm{var}(X_i)\approx \frac{1}{n}\sum_{k=1}^n (x_k - \bar x_n)=\mathrm{var}(x) +\tag{21} +\end{equation} $$ -resulting in -$$ -\frac{1}{n} \sum_{l}^n \left(\frac{1}{n}\sum_{k}^n (x_k -\bar x_n)(x_l - \bar x_n)\right)=\frac{1}{n}\frac{1}{n} \sum_{kl} (x_k -\bar x_n)(x_l - \bar x_n)=\frac{1}{n}\mathrm{cov}(x) +

    +Now we can calculate an estimate of the error +\( \mathrm{err}_X^{\phantom X} \) of the sample mean \( \bar x_n \): $$ +\begin{align} +\mathrm{err}_X^2 +&=\frac{1}{n^2}\sum_{ij} \mathrm{cov}(X_i, X_j) \nonumber \\ +&\approx&\frac{1}{n^2}\sum_{ij}\frac{1}{n}\mathrm{cov}(x) =\frac{1}{n^2}n^2\frac{1}{n}\mathrm{cov}(x)\nonumber\\ +&=\frac{1}{n}\mathrm{cov}(x) +\tag{22} +\end{align} +$$ + +which is nothing but the sample covariance divided by the number of +measurements in the sample.

    @@ -465,7 +444,7 @@ $$
  • 73
  • 74
  • ...
  • -
  • 114
  • +
  • 100
  • »
  • diff --git a/doc/pub/Regression/html/._Regression-bs065.html b/doc/pub/Regression/html/._Regression-bs065.html index 6f5a350e3..08333bcdf 100644 --- a/doc/pub/Regression/html/._Regression-bs065.html +++ b/doc/pub/Regression/html/._Regression-bs065.html @@ -6,6 +6,7 @@ Automatically generated HTML file from DocOnce source + Data Analysis and Machine Learning: Linear Regression and more Advanced Regression Analysis @@ -40,160 +41,151 @@ Automatically generated HTML file from DocOnce source @@ -286,119 +263,109 @@ MathJax.Hub.Config({ @@ -414,39 +381,35 @@ MathJax.Hub.Config({ -

    Statistics and sample variance

    +

    Statistics, uncorrelated results

    -By the same procedure we can use the sample variance as an -estimate of the variance of any of the stochastic variables \( X_i \) + +

    +In the special case that the measurements of the sample are +uncorrelated (equivalently the stochastic variables \( X_i \) are +uncorrelated) we have that the off-diagonal elements of the covariance +are zero. This gives the following estimate of the sample error: $$ -\mathrm{var}(X_i)=\langle x_i - \langle x_i\rangle\rangle \approx \langle x_i - \bar x_n\rangle\nonumber, +\mathrm{err}_X^2=\frac{1}{n^2}\sum_{ij} \mathrm{cov}(X_i, X_j) = +\frac{1}{n^2} \sum_i \mathrm{var}(X_i), $$ -which is approximated as +resulting in $$ \begin{equation} -\mathrm{var}(X_i)\approx \frac{1}{n}\sum_{k=1}^n (x_k - \bar x_n)=\mathrm{var}(x) -\tag{15} +\mathrm{err}_X^2\approx \frac{1}{n^2} \sum_i \mathrm{var}(x)= \frac{1}{n}\mathrm{var}(x) +\tag{23} \end{equation} $$ -

    -Now we can calculate an estimate of the error -\( \mathrm{err}_X^{\phantom X} \) of the sample mean \( \bar x_n \): -$$ -\begin{align} -\mathrm{err}_X^2 -&=\frac{1}{n^2}\sum_{ij} \mathrm{cov}(X_i, X_j) \nonumber \\ -&\approx&\frac{1}{n^2}\sum_{ij}\frac{1}{n}\mathrm{cov}(x) =\frac{1}{n^2}n^2\frac{1}{n}\mathrm{cov}(x)\nonumber\\ -&=\frac{1}{n}\mathrm{cov}(x) -\tag{16} -\end{align} -$$ - -which is nothing but the sample covariance divided by the number of -measurements in the sample. +where in the second step we have used Eq. (21). +The error of the sample is then just its standard deviation divided by +the square root of the number of measurements the sample contains. +This is a very useful formula which is easy to compute. It acts as a +first approximation to the error, but in numerical experiments, we +cannot overlook the always present correlations.

    @@ -477,7 +440,7 @@ measurements in the sample.
  • 74
  • 75
  • ...
  • -
  • 114
  • +
  • 100
  • »
  • diff --git a/doc/pub/Regression/html/._Regression-bs066.html b/doc/pub/Regression/html/._Regression-bs066.html index 4e140373b..6c7f7f24e 100644 --- a/doc/pub/Regression/html/._Regression-bs066.html +++ b/doc/pub/Regression/html/._Regression-bs066.html @@ -6,6 +6,7 @@ Automatically generated HTML file from DocOnce source + Data Analysis and Machine Learning: Linear Regression and more Advanced Regression Analysis @@ -40,160 +41,151 @@ Automatically generated HTML file from DocOnce source @@ -286,119 +263,109 @@ MathJax.Hub.Config({ @@ -414,35 +381,29 @@ MathJax.Hub.Config({ -

    Statistics, uncorrelated results

    +

    Statistics, computations

    - -

    -In the special case that the measurements of the sample are -uncorrelated (equivalently the stochastic variables \( X_i \) are -uncorrelated) we have that the off-diagonal elements of the covariance -are zero. This gives the following estimate of the sample error: +For computational purposes one usually splits up the estimate of +\( \mathrm{err}_X^2 \), given by Eq. (22), into two +parts $$ -\mathrm{err}_X^2=\frac{1}{n^2}\sum_{ij} \mathrm{cov}(X_i, X_j) = -\frac{1}{n^2} \sum_i \mathrm{var}(X_i), +\mathrm{err}_X^2 = \frac{1}{n}\mathrm{var}(x) + \frac{1}{n}(\mathrm{cov}(x)-\mathrm{var}(x)), $$ -resulting in +which equals $$ \begin{equation} -\mathrm{err}_X^2\approx \frac{1}{n^2} \sum_i \mathrm{var}(x)= \frac{1}{n}\mathrm{var}(x) -\tag{17} +\frac{1}{n^2}\sum_{k=1}^n (x_k - \bar x_n)^2 +\frac{2}{n^2}\sum_{k < l} (x_k - \bar x_n)(x_l - \bar x_n) +\tag{24} \end{equation} $$ -where in the second step we have used Eq. (15). -The error of the sample is then just its standard deviation divided by -the square root of the number of measurements the sample contains. -This is a very useful formula which is easy to compute. It acts as a -first approximation to the error, but in numerical experiments, we -cannot overlook the always present correlations. +The first term is the same as the error in the uncorrelated case, +Eq. (23). This means that the second +term accounts for the error correction due to correlation between the +measurements. For uncorrelated measurements this second term is zero.

    @@ -473,7 +434,7 @@ cannot overlook the always present correlations.
  • 75
  • 76
  • ...
  • -
  • 114
  • +
  • 100
  • »
  • diff --git a/doc/pub/Regression/html/._Regression-bs067.html b/doc/pub/Regression/html/._Regression-bs067.html index af794d498..1f4897191 100644 --- a/doc/pub/Regression/html/._Regression-bs067.html +++ b/doc/pub/Regression/html/._Regression-bs067.html @@ -6,6 +6,7 @@ Automatically generated HTML file from DocOnce source + Data Analysis and Machine Learning: Linear Regression and more Advanced Regression Analysis @@ -40,160 +41,151 @@ Automatically generated HTML file from DocOnce source @@ -286,119 +263,109 @@ MathJax.Hub.Config({ @@ -414,29 +381,22 @@ MathJax.Hub.Config({ -

    Statistics, computations

    +

    Statistics, more on computations of errors

    -For computational purposes one usually splits up the estimate of -\( \mathrm{err}_X^2 \), given by Eq. (16), into two -parts +Computationally the uncorrelated first term is much easier to treat +efficiently than the second. $$ -\mathrm{err}_X^2 = \frac{1}{n}\mathrm{var}(x) + \frac{1}{n}(\mathrm{cov}(x)-\mathrm{var}(x)), +\mathrm{var}(x) = \frac{1}{n}\sum_{k=1}^n (x_k - \bar x_n)^2 = +\left(\frac{1}{n}\sum_{k=1}^n x_k^2\right) - \bar x_n^2 $$ -which equals -$$ -\begin{equation} -\frac{1}{n^2}\sum_{k=1}^n (x_k - \bar x_n)^2 +\frac{2}{n^2}\sum_{k < l} (x_k - \bar x_n)(x_l - \bar x_n) -\tag{18} -\end{equation} -$$ - -The first term is the same as the error in the uncorrelated case, -Eq. (17). This means that the second -term accounts for the error correction due to correlation between the -measurements. For uncorrelated measurements this second term is zero. +We just accumulate separately the values \( x^2 \) and \( x \) for every +measurement \( x \) we receive. The correlation term, though, has to be +calculated at the end of the experiment since we need all the +measurements to calculate the cross terms. Therefore, all measurements +have to be stored throughout the experiment.

    @@ -467,7 +427,7 @@ measurements. For uncorrelated measurements this second term is zero.
  • 76
  • 77
  • ...
  • -
  • 114
  • +
  • 100
  • »
  • diff --git a/doc/pub/Regression/html/._Regression-bs068.html b/doc/pub/Regression/html/._Regression-bs068.html index 872e031fa..fed0a66ef 100644 --- a/doc/pub/Regression/html/._Regression-bs068.html +++ b/doc/pub/Regression/html/._Regression-bs068.html @@ -6,6 +6,7 @@ Automatically generated HTML file from DocOnce source + Data Analysis and Machine Learning: Linear Regression and more Advanced Regression Analysis @@ -40,160 +41,151 @@ Automatically generated HTML file from DocOnce source @@ -286,119 +263,109 @@ MathJax.Hub.Config({ @@ -414,22 +381,33 @@ MathJax.Hub.Config({ -

    Statistics, more on computations of errors

    +

    Statistics, wrapping up 1

    -Computationally the uncorrelated first term is much easier to treat -efficiently than the second. +Let us analyze the problem by splitting up the correlation term into +partial sums of the form: $$ -\mathrm{var}(x) = \frac{1}{n}\sum_{k=1}^n (x_k - \bar x_n)^2 = -\left(\frac{1}{n}\sum_{k=1}^n x_k^2\right) - \bar x_n^2 +f_d = \frac{1}{n-d}\sum_{k=1}^{n-d}(x_k - \bar x_n)(x_{k+d} - \bar x_n) $$ -We just accumulate separately the values \( x^2 \) and \( x \) for every -measurement \( x \) we receive. The correlation term, though, has to be -calculated at the end of the experiment since we need all the -measurements to calculate the cross terms. Therefore, all measurements -have to be stored throughout the experiment. +The correlation term of the error can now be rewritten in terms of +\( f_d \) +$$ +\frac{2}{n}\sum_{k < l} (x_k - \bar x_n)(x_l - \bar x_n) = +2\sum_{d=1}^{n-1} f_d +$$ + +The value of \( f_d \) reflects the correlation between measurements +separated by the distance \( d \) in the sample samples. Notice that for +\( d=0 \), \( f \) is just the sample variance, \( \mathrm{var}(x) \). If we divide \( f_d \) +by \( \mathrm{var}(x) \), we arrive at the so called autocorrelation function +$$ +\kappa_d = \frac{f_d}{\mathrm{var}(x)} +$$ + +which gives us a useful measure of pairwise correlations +starting always at \( 1 \) for \( d=0 \).

    @@ -460,7 +438,7 @@ have to be stored throughout the experiment.
  • 77
  • 78
  • ...
  • -
  • 114
  • +
  • 100
  • »
  • diff --git a/doc/pub/Regression/html/._Regression-bs069.html b/doc/pub/Regression/html/._Regression-bs069.html index 603d4c3bf..67c484a91 100644 --- a/doc/pub/Regression/html/._Regression-bs069.html +++ b/doc/pub/Regression/html/._Regression-bs069.html @@ -6,6 +6,7 @@ Automatically generated HTML file from DocOnce source + Data Analysis and Machine Learning: Linear Regression and more Advanced Regression Analysis @@ -40,160 +41,151 @@ Automatically generated HTML file from DocOnce source @@ -286,119 +263,109 @@ MathJax.Hub.Config({ @@ -414,33 +381,33 @@ MathJax.Hub.Config({ -

    Statistics, wrapping up 1

    +

    Statistics, final expression

    -Let us analyze the problem by splitting up the correlation term into -partial sums of the form: +The sample error (see eq. (24)) can now be +written in terms of the autocorrelation function: $$ -f_d = \frac{1}{n-d}\sum_{k=1}^{n-d}(x_k - \bar x_n)(x_{k+d} - \bar x_n) +\begin{align} +\mathrm{err}_X^2 &= +\frac{1}{n}\mathrm{var}(x)+\frac{2}{n}\cdot\mathrm{var}(x)\sum_{d=1}^{n-1} +\frac{f_d}{\mathrm{var}(x)}\nonumber\\ &=& +\left(1+2\sum_{d=1}^{n-1}\kappa_d\right)\frac{1}{n}\mathrm{var}(x)\nonumber\\ +&=\frac{\tau}{n}\cdot\mathrm{var}(x) +\tag{25} +\end{align} $$ -The correlation term of the error can now be rewritten in terms of -\( f_d \) +and we see that \( \mathrm{err}_X \) can be expressed in terms the +uncorrelated sample variance times a correction factor \( \tau \) which +accounts for the correlation between measurements. We call this +correction factor the autocorrelation time: $$ -\frac{2}{n}\sum_{k < l} (x_k - \bar x_n)(x_l - \bar x_n) = -2\sum_{d=1}^{n-1} f_d +\begin{equation} +\tau = 1+2\sum_{d=1}^{n-1}\kappa_d +\tag{26} +\end{equation} $$ - -The value of \( f_d \) reflects the correlation between measurements -separated by the distance \( d \) in the sample samples. Notice that for -\( d=0 \), \( f \) is just the sample variance, \( \mathrm{var}(x) \). If we divide \( f_d \) -by \( \mathrm{var}(x) \), we arrive at the so called autocorrelation function -$$ -\kappa_d = \frac{f_d}{\mathrm{var}(x)} -$$ - -which gives us a useful measure of pairwise correlations -starting always at \( 1 \) for \( d=0 \).

    @@ -471,7 +438,7 @@ starting always at \( 1 \) for \( d=0 \).
  • 78
  • 79
  • ...
  • -
  • 114
  • +
  • 100
  • »
  • diff --git a/doc/pub/Regression/html/._Regression-bs070.html b/doc/pub/Regression/html/._Regression-bs070.html index 6502040af..b5cb2bae8 100644 --- a/doc/pub/Regression/html/._Regression-bs070.html +++ b/doc/pub/Regression/html/._Regression-bs070.html @@ -6,6 +6,7 @@ Automatically generated HTML file from DocOnce source + Data Analysis and Machine Learning: Linear Regression and more Advanced Regression Analysis @@ -40,160 +41,151 @@ Automatically generated HTML file from DocOnce source @@ -286,119 +263,109 @@ MathJax.Hub.Config({ @@ -414,33 +381,25 @@ MathJax.Hub.Config({ -

    Statistics, final expression

    +

    Statistics, effective number of correlations

    -The sample error (see eq. (18)) can now be -written in terms of the autocorrelation function: +For a correlation free experiment, \( \tau \) +equals 1. From the point of view of +eq. (25) we can interpret a sequential +correlation as an effective reduction of the number of measurements by +a factor \( \tau \). The effective number of measurements becomes: $$ -\begin{align} -\mathrm{err}_X^2 &= -\frac{1}{n}\mathrm{var}(x)+\frac{2}{n}\cdot\mathrm{var}(x)\sum_{d=1}^{n-1} -\frac{f_d}{\mathrm{var}(x)}\nonumber\\ &=& -\left(1+2\sum_{d=1}^{n-1}\kappa_d\right)\frac{1}{n}\mathrm{var}(x)\nonumber\\ -&=\frac{\tau}{n}\cdot\mathrm{var}(x) -\tag{19} -\end{align} +n_\mathrm{eff} = \frac{n}{\tau} $$ -and we see that \( \mathrm{err}_X \) can be expressed in terms the -uncorrelated sample variance times a correction factor \( \tau \) which -accounts for the correlation between measurements. We call this -correction factor the autocorrelation time: -$$ -\begin{equation} -\tau = 1+2\sum_{d=1}^{n-1}\kappa_d -\tag{20} -\end{equation} -$$ +To neglect the autocorrelation time \( \tau \) will always cause our +simple uncorrelated estimate of \( \mathrm{err}_X^2\approx \mathrm{var}(x)/n \) to +be less than the true sample error. The estimate of the error will be +too good. On the other hand, the calculation of the full +autocorrelation time poses an efficiency problem if the set of +measurements is very large.

    @@ -471,7 +430,7 @@ $$
  • 79
  • 80
  • ...
  • -
  • 114
  • +
  • 100
  • »
  • diff --git a/doc/pub/Regression/html/._Regression-bs071.html b/doc/pub/Regression/html/._Regression-bs071.html index 40f048bf9..c8d786d91 100644 --- a/doc/pub/Regression/html/._Regression-bs071.html +++ b/doc/pub/Regression/html/._Regression-bs071.html @@ -6,6 +6,7 @@ Automatically generated HTML file from DocOnce source + Data Analysis and Machine Learning: Linear Regression and more Advanced Regression Analysis @@ -40,160 +41,151 @@ Automatically generated HTML file from DocOnce source @@ -286,119 +263,109 @@ MathJax.Hub.Config({ @@ -412,30 +379,42 @@ MathJax.Hub.Config({

     

     

     

    - + -

    Statistics, effective number of correlations

    -
    -
    -

    -For a correlation free experiment, \( \tau \) -equals 1. From the point of view of -eq. (19) we can interpret a sequential -correlation as an effective reduction of the number of measurements by -a factor \( \tau \). The effective number of measurements becomes: +

    Linking the regression analysis with a statistical interpretation

    + +

    +Finally, we are going to discuss several statistical properties which can be obtained in terms of analytical expressions. +The +advantage of doing linear regression is that we actually end up with +analytical expressions for several statistical quantities. +Standard least squares and Ridge regression allow us to +derive quantities like the variance and other expectation values in a +rather straightforward way. + +

    +It is assumed that \( \varepsilon_i +\sim \mathcal{N}(0, \sigma^2) \) and the \( \varepsilon_{i} \) are +independent, i.e.: $$ -n_\mathrm{eff} = \frac{n}{\tau} +\begin{align*} +\mbox{Cov}(\varepsilon_{i_1}, +\varepsilon_{i_2}) & = \left\{ \begin{array}{lcc} \sigma^2 & \mbox{if} +& i_1 = i_2, \\ 0 & \mbox{if} & i_1 \not= i_2. \end{array} \right. +\end{align*} $$ -To neglect the autocorrelation time \( \tau \) will always cause our -simple uncorrelated estimate of \( \mathrm{err}_X^2\approx \mathrm{var}(x)/n \) to -be less than the true sample error. The estimate of the error will be -too good. On the other hand, the calculation of the full -autocorrelation time poses an efficiency problem if the set of -measurements is very large. -

    -
    +The randomness of \( \varepsilon_i \) implies that +\( \mathbf{y}_i \) is also a random variable. In particular, +\( \mathbf{y}_i \) is normally distributed, because \( \varepsilon_i \sim +\mathcal{N}(0, \sigma^2) \) and \( \mathbf{X}_{i,\ast} \, \boldsymbol{\beta} \) is a +non-random scalar. To specify the parameters of the distribution of +\( \mathbf{y}_i \) we need to calculate its first two moments. +

    +Recall that \( \boldsymbol{X} \) is a matrix of dimensionality \( n\times p \). The +notation above \( \mathbf{X}_{i,\ast} \) means that we are looking at the +row number \( i \) and perform a sum over all values \( p \).

    @@ -463,7 +442,7 @@ measurements is very large.

  • 80
  • 81
  • ...
  • -
  • 114
  • +
  • 100
  • »
  • diff --git a/doc/pub/Regression/html/._Regression-bs072.html b/doc/pub/Regression/html/._Regression-bs072.html index 9f6983b36..ea9f32047 100644 --- a/doc/pub/Regression/html/._Regression-bs072.html +++ b/doc/pub/Regression/html/._Regression-bs072.html @@ -6,6 +6,7 @@ Automatically generated HTML file from DocOnce source + Data Analysis and Machine Learning: Linear Regression and more Advanced Regression Analysis @@ -40,160 +41,151 @@ Automatically generated HTML file from DocOnce source @@ -286,119 +263,109 @@ MathJax.Hub.Config({ @@ -414,35 +381,22 @@ MathJax.Hub.Config({ -

    Log-likelihood

    +

    Assumptions made

    -A popular strategy is to choose a penalty parameter that yields a good -but parsimonious model. Information criteria measure the balance -between model fit and model complexity. One possibility is Aikaike's -information criterion (AIC). -The AIC measures model fit by the log-likelihood -and model complexity is measured by the number of parameters used by -the model. The number of model parameters in regular regression simply -corresponds to the number of covariates in the model. Or, by the -degrees of freedom consumed by the model, which is equivalent to the -trace of the hat matrix. For ridge regression it thus seems natural to -define model complexity analogously by the trace of the ridge hat -matrix. This yields the AIC for the linear regression model with ridge -estimates: - +The assumption we have made here can be summarized as (and this is going to useful when we discuss the bias-variance trade off) +that there exists a function \( f(\boldsymbol{x}) \) and a normal distributed error \( \boldsymbol{\varepsilon}\sim \mathcal{N}(0, \sigma^2) \) +which describes our data $$ -\begin{align*} -\mbox{AIC}(\lambda) & = 2 \, p - 2 \log(\hat{L}) -\\ -& = 2 \, \mbox{tr} [\mathbf{H}(\lambda)] - 2 \log\{L[\hat{\beta}(\lambda), \hat{\sigma}^2(\lambda)]\} -\\ -& = 2 \, \sum_{j=1}^p \frac{d_{jj}^2}{d_{jj}^2 + \lambda} -+ 2 n \, \log[\sqrt{2 \, \pi} \, \hat{\sigma}(\lambda)] + \frac{1}{\hat{\sigma}^2(\lambda)} \sum_{i=1}^n [y_i - \mathbf{X}_{i, \ast} \, \hat{\beta}(\lambda)]^2. -\end{align*} +\boldsymbol{y} = f(\boldsymbol{x})+\boldsymbol{\varepsilon} $$ -The value of \( \lambda \) which minimizes \( \mbox{AIC}(\lambda) \) corresponds to the `optimal' balance of model complexity and overfitting. +

    +We approximate this function with our model from the solution of the linear regression equations, that is our +function \( f \) is approximated by \( \boldsymbol{\tilde{y}} \) where we want to minimize \( (\boldsymbol{y}-\boldsymbol{\tilde{y}})^2 \), our MSE, with +$$ +\boldsymbol{\tilde{y}} = \boldsymbol{X}\boldsymbol{\beta}. +$$

    @@ -470,7 +424,7 @@ The value of \( \lambda \) which minimizes \( \mbox{AIC}(\lambda) \) corresponds

  • 81
  • 82
  • ...
  • -
  • 114
  • +
  • 100
  • »
  • diff --git a/doc/pub/Regression/html/._Regression-bs073.html b/doc/pub/Regression/html/._Regression-bs073.html index 25a81a5ed..f6c1a7d10 100644 --- a/doc/pub/Regression/html/._Regression-bs073.html +++ b/doc/pub/Regression/html/._Regression-bs073.html @@ -6,6 +6,7 @@ Automatically generated HTML file from DocOnce source + Data Analysis and Machine Learning: Linear Regression and more Advanced Regression Analysis @@ -40,160 +41,151 @@ Automatically generated HTML file from DocOnce source @@ -286,119 +263,109 @@ MathJax.Hub.Config({ @@ -412,35 +379,39 @@ MathJax.Hub.Config({

     

     

     

    - + -

    Cross-validation

    +

    Expectation value and variance

    -Instead of choosing the penalty parameter to balance model fit with -model complexity, cross-validation requires it (i.e. the penalty -parameter) to yield a model with good prediction -performance. Commonly, this performance is evaluated on novel -data. Novel data need not be easy to come by and one has to make do -with the data at hand. The setting of `original' and novel data is -then mimicked by sample splitting: the data set is divided into two -(groups of samples). One of these two data sets, called the training -set, plays the role of `original' data on which the model is -built. The second of these data sets, called the test set, plays the -role of the `novel' data and is used to evaluate the prediction -performance (often operationalized as the log-likelihood or the -prediction error or its square or the R2 score) of the model built on the training data set. This -procedure (model building and prediction evaluation on training and -test set, respectively) is done for a collection of possible penalty -parameter choices. The penalty parameter that yields the model with -the best prediction performance is to be preferred. The thus obtained -performance evaluation depends on the actual split of the data set. To -remove this dependence the data set is split many times into a -training and test set. For each split the model parameters are -estimated for all choices of \( \lambda \) using the training data and -estimated parameters are evaluated on the corresponding test set. The -penalty parameter that on average over the test sets performs best (in -some sense) is then selected. +We can calculate the expectation value of \( \boldsymbol{y} \) for a given element \( i \) +$$ +\begin{align*} +\mathbb{E}(y_i) & = +\mathbb{E}(\mathbf{X}_{i, \ast} \, \boldsymbol{\beta}) + \mathbb{E}(\varepsilon_i) +\, \, \, = \, \, \, \mathbf{X}_{i, \ast} \, \beta, +\end{align*} +$$ + +while +its variance is +$$ +\begin{align*} \mbox{Var}(y_i) & = \mathbb{E} \{ [y_i +- \mathbb{E}(y_i)]^2 \} \, \, \, = \, \, \, \mathbb{E} ( y_i^2 ) - +[\mathbb{E}(y_i)]^2 \\ & = \mathbb{E} [ ( \mathbf{X}_{i, \ast} \, +\beta + \varepsilon_i )^2] - ( \mathbf{X}_{i, \ast} \, \boldsymbol{\beta})^2 \\ & += \mathbb{E} [ ( \mathbf{X}_{i, \ast} \, \boldsymbol{\beta})^2 + 2 \varepsilon_i +\mathbf{X}_{i, \ast} \, \boldsymbol{\beta} + \varepsilon_i^2 ] - ( \mathbf{X}_{i, +\ast} \, \beta)^2 \\ & = ( \mathbf{X}_{i, \ast} \, \boldsymbol{\beta})^2 + 2 +\mathbb{E}(\varepsilon_i) \mathbf{X}_{i, \ast} \, \boldsymbol{\beta} + +\mathbb{E}(\varepsilon_i^2 ) - ( \mathbf{X}_{i, \ast} \, \boldsymbol{\beta})^2 +\\ & = \mathbb{E}(\varepsilon_i^2 ) \, \, \, = \, \, \, +\mbox{Var}(\varepsilon_i) \, \, \, = \, \, \, \sigma^2. +\end{align*} +$$ + +Hence, \( y_i \sim \mathcal{N}( \mathbf{X}_{i, \ast} \, \boldsymbol{\beta}, \sigma^2) \), that is \( \boldsymbol{y} \) follows a normal distribution with +mean value \( \boldsymbol{X}\boldsymbol{\beta} \) and variance \( \sigma^2 \) (not be confused with the singular values of the SVD).

    @@ -468,7 +439,7 @@ some sense) is then selected.

  • 82
  • 83
  • ...
  • -
  • 114
  • +
  • 100
  • »
  • diff --git a/doc/pub/Regression/html/._Regression-bs074.html b/doc/pub/Regression/html/._Regression-bs074.html index 576a2a9db..0d34e7d64 100644 --- a/doc/pub/Regression/html/._Regression-bs074.html +++ b/doc/pub/Regression/html/._Regression-bs074.html @@ -6,6 +6,7 @@ Automatically generated HTML file from DocOnce source + Data Analysis and Machine Learning: Linear Regression and more Advanced Regression Analysis @@ -40,160 +41,151 @@ Automatically generated HTML file from DocOnce source @@ -286,119 +263,109 @@ MathJax.Hub.Config({ @@ -414,16 +381,89 @@ MathJax.Hub.Config({ -

    Computationally expensive

    +

    Expectation value and variance for \( \boldsymbol{\beta} \)

    -The validation set approach is conceptually simple and is easy to implement. But it has two potential drawbacks: +With the OLS expressions for the parameters \( \boldsymbol{\beta} \) we can evaluate the expectation value +$$ +\mathbb{E}(\boldsymbol{\beta}) = \mathbb{E}[ (\mathbf{X}^{\top} \mathbf{X})^{-1}\mathbf{X}^{T} \mathbf{Y}]=(\mathbf{X}^{T} \mathbf{X})^{-1}\mathbf{X}^{T} \mathbb{E}[ \mathbf{Y}]=(\mathbf{X}^{T} \mathbf{X})^{-1} \mathbf{X}^{T}\mathbf{X}\boldsymbol{\beta}=\boldsymbol{\beta}. +$$ -

      -
    • The validation estimate of the test error rate can be highly variable, depending on precisely which observations are included in the training set and which observations are included in the validation set.
    • -
    • In the validation approach, only a subset of the observations, those that are included in the training set rather than in the validation set are used to fit the model. Since statistical methods tend to perform worse when trained on fewer observations, this suggests that the validation set error rate may tend to overestimate the test error rate for the model fit on the entire data set.
    • -
    +This means that the estimator of the regression parameters is unbiased. +

    +We can also calculate the variance + +

    +The variance of \( \boldsymbol{\beta} \) is +$$ +\begin{eqnarray*} +\mbox{Var}(\boldsymbol{\beta}) & = & \mathbb{E} \{ [\boldsymbol{\beta} - \mathbb{E}(\boldsymbol{\beta})] [\boldsymbol{\beta} - \mathbb{E}(\boldsymbol{\beta})]^{T} \} +\\ +& = & \mathbb{E} \{ [(\mathbf{X}^{T} \mathbf{X})^{-1} \, \mathbf{X}^{T} \mathbf{Y} - \boldsymbol{\beta}] \, [(\mathbf{X}^{T} \mathbf{X})^{-1} \, \mathbf{X}^{T} \mathbf{Y} - \boldsymbol{\beta}]^{T} \} +\\ +% & = & \mathbb{E} \{ [(\mathbf{X}^{T} \mathbf{X})^{-1} \, \mathbf{X}^{T} \mathbf{Y}] \, [(\mathbf{X}^{T} \mathbf{X})^{-1} \, \mathbf{X}^{T} \mathbf{Y}]^{T} \} - \boldsymbol{\beta} \, \boldsymbol{\beta}^{T} +% \\ +% & = & \mathbb{E} \{ (\mathbf{X}^{T} \mathbf{X})^{-1} \, \mathbf{X}^{T} \mathbf{Y} \, \mathbf{Y}^{T} \, \mathbf{X} \, (\mathbf{X}^{T} \mathbf{X})^{-1} \} - \boldsymbol{\beta} \, \boldsymbol{\beta}^{T} +% \\ +& = & (\mathbf{X}^{T} \mathbf{X})^{-1} \, \mathbf{X}^{T} \, \mathbb{E} \{ \mathbf{Y} \, \mathbf{Y}^{T} \} \, \mathbf{X} \, (\mathbf{X}^{T} \mathbf{X})^{-1} - \boldsymbol{\beta} \, \boldsymbol{\beta}^{T} +\\ +& = & (\mathbf{X}^{T} \mathbf{X})^{-1} \, \mathbf{X}^{T} \, \{ \mathbf{X} \, \boldsymbol{\beta} \, \boldsymbol{\beta}^{T} \, \mathbf{X}^{T} + \sigma^2 \} \, \mathbf{X} \, (\mathbf{X}^{T} \mathbf{X})^{-1} - \boldsymbol{\beta} \, \boldsymbol{\beta}^{T} +% \\ +% & = & (\mathbf{X}^T \mathbf{X})^{-1} \, \mathbf{X}^T \, \mathbf{X} \, \boldsymbol{\beta} \, \boldsymbol{\beta}^T \, \mathbf{X}^T \, \mathbf{X} \, (\mathbf{X}^T % \mathbf{X})^{-1} +% \\ +% & & + \, \, \sigma^2 \, (\mathbf{X}^T \mathbf{X})^{-1} \, \mathbf{X}^T \, \mathbf{X} \, (\mathbf{X}^T \mathbf{X})^{-1} - \boldsymbol{\beta} \boldsymbol{\beta}^T +\\ +& = & \boldsymbol{\beta} \, \boldsymbol{\beta}^{T} + \sigma^2 \, (\mathbf{X}^{T} \mathbf{X})^{-1} - \boldsymbol{\beta} \, \boldsymbol{\beta}^{T} +\, \, \, = \, \, \, \sigma^2 \, (\mathbf{X}^{T} \mathbf{X})^{-1}, +\end{eqnarray*} +$$ + +

    +where we have used that \( \mathbb{E} (\mathbf{Y} \mathbf{Y}^{T}) = +\mathbf{X} \, \boldsymbol{\beta} \, \boldsymbol{\beta}^{T} \, \mathbf{X}^{T} + +\sigma^2 \, \mathbf{I}_{nn} \). From \( \mbox{Var}(\boldsymbol{\beta}) = \sigma^2 +\, (\mathbf{X}^{T} \mathbf{X})^{-1} \), one obtains an estimate of the +variance of the estimate of the \( j \)-th regression coefficient: +\( \hat{\sigma}^2 (\hat{\beta}_j ) = \hat{\sigma}^2 \sqrt{ +[(\mathbf{X}^{T} \mathbf{X})^{-1}]_{jj} } \). This may be used to +construct a confidence interval for the estimates. + +

    +In a similar way, we cna obtain analytical expressions for say the +expectation values of the parameters \( \boldsymbol{\beta} \) and their variance +when we employ Ridge regression, and thereby a confidence interval. + +

    +It is rather straightforward to show that +$$ +\mathbb{E} \big[ \boldsymbol{\beta}^{\mathrm{Ridge}} \big]=(\mathbf{X}^{T} \mathbf{X} + \lambda \mathbf{I}_{pp})^{-1} (\mathbf{X}^{\top} \mathbf{X})\boldsymbol{\beta}^{\mathrm{OLS}}. +$$ + +We see clearly that +\( \mathbb{E} \big[ \boldsymbol{\beta}^{\mathrm{Ridge}} \big] \not= \boldsymbol{\beta}^{\mathrm{OLS}} \) for any \( \lambda > 0 \). We say then that the ridge estimator is biased. + +

    +We can also compute the variance as + +$$ +\mbox{Var}[\boldsymbol{\beta}^{\mathrm{Ridge}}]=\sigma^2[ \mathbf{X}^{T} \mathbf{X} + \lambda \mathbf{I} ]^{-1} \mathbf{X}^{T} \mathbf{X} \{ [ \mathbf{X}^{\top} \mathbf{X} + \lambda \mathbf{I} ]^{-1}\}^{T}, +$$ + +and it is easy to see that if the parameter \( \lambda \) goes to infinity then the variance of Ridge parameters \( \boldsymbol{\beta} \) goes to zero. + +

    +With this, we can compute the difference + +$$ +\mbox{Var}[\boldsymbol{\beta}^{\mathrm{OLS}}]-\mbox{Var}(\boldsymbol{\beta}^{\mathrm{Ridge}})=\sigma^2 [ \mathbf{X}^{T} \mathbf{X} + \lambda \mathbf{I} ]^{-1}[ 2\lambda\mathbf{I} + \lambda^2 (\mathbf{X}^{T} \mathbf{X})^{-1} ] \{ [ \mathbf{X}^{T} \mathbf{X} + \lambda \mathbf{I} ]^{-1}\}^{T}. +$$ + +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 \( \boldsymbol{\beta} \) obtained with the Ridge estimator. This has interesting consequences when we discuss the so-called bias-variance trade-off below. + +

      @@ -449,7 +489,7 @@ The validation set approach is conceptually simple and is easy to implement. But
    • 83
    • 84
    • ...
    • -
    • 114
    • +
    • 100
    • »
    diff --git a/doc/pub/Regression/html/._Regression-bs075.html b/doc/pub/Regression/html/._Regression-bs075.html index 7379b6274..63a117fc0 100644 --- a/doc/pub/Regression/html/._Regression-bs075.html +++ b/doc/pub/Regression/html/._Regression-bs075.html @@ -6,6 +6,7 @@ Automatically generated HTML file from DocOnce source + Data Analysis and Machine Learning: Linear Regression and more Advanced Regression Analysis @@ -40,160 +41,151 @@ Automatically generated HTML file from DocOnce source @@ -286,119 +263,109 @@ MathJax.Hub.Config({ @@ -414,23 +381,36 @@ MathJax.Hub.Config({ -

    Various steps in cross-validation

    +

    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). +Instead of choosing the penalty parameter to balance model fit with +model complexity, cross-validation requires it (i.e. the penalty +parameter) to yield a model with good prediction +performance. Commonly, this performance is evaluated on novel +data. Novel data need not be easy to come by and one has to make do +with the data at hand. + +

    +The setting of original and novel data is +then mimicked by sample splitting: the data set is divided into two +(groups of samples). One of these two data sets, called the +training set, plays the role of original data on which the model is +built. The second of these data sets, called the test set, plays the +role of the novel data and is used to evaluate the prediction +performance (often operationalized as the log-likelihood or the +prediction error or its square or the R2 score) of the model built on the training data set. This +procedure (model building and prediction evaluation on training and +test set, respectively) is done for a collection of possible penalty +parameter choices. The penalty parameter that yields the model with +the best prediction performance is to be preferred. The thus obtained +performance evaluation depends on the actual split of the data set. To +remove this dependence the data set is split many times into a +training and test set. For each split the model parameters are +estimated for all choices of \( \lambda \) using the training data and +estimated parameters are evaluated on the corresponding test set. The +penalty parameter that on average over the test sets performs best (in +some sense) is then selected.

    @@ -458,7 +438,7 @@ cross-validation (LOOCV).

  • 84
  • 85
  • ...
  • -
  • 114
  • +
  • 100
  • »
  • diff --git a/doc/pub/Regression/html/._Regression-bs076.html b/doc/pub/Regression/html/._Regression-bs076.html index 7bb679faf..1307d54da 100644 --- a/doc/pub/Regression/html/._Regression-bs076.html +++ b/doc/pub/Regression/html/._Regression-bs076.html @@ -6,6 +6,7 @@ Automatically generated HTML file from DocOnce source + Data Analysis and Machine Learning: Linear Regression and more Advanced Regression Analysis @@ -40,160 +41,151 @@ Automatically generated HTML file from DocOnce source @@ -286,119 +263,109 @@ MathJax.Hub.Config({ @@ -412,40 +379,16 @@ MathJax.Hub.Config({

     

     

     

    - + -

    How to set up the cross-validation for Ridge and/or Lasso

    +

    Computationally expensive

    + +

    +The validation set approach is conceptually simple and is easy to implement. But it has two potential drawbacks:

      -
    • Define a range of interest for the penalty parameter.
    • -
    • Divide the data set into training and test set comprising samples \( \{1, \ldots, n\} \setminus i \) and \( \{ i \} \), respectively.
    • -
    • Fit the linear regression model by means of ridge estimation for each \( \lambda \) in the grid using the training set, and the corresponding estimate of the error variance \( \hat{\sigma}_{-i}^2(\lambda) \), as
    • -
    - -$$ -\begin{align*} -\hat{\beta}_{-i}(\lambda) & = ( \hat{X}_{-i, \ast}^{\top} -\hat{X}_{-i, \ast} + \lambda \hat{I}_{pp})^{-1} -\hat{X}_{-i, \ast}^{\top} \hat{y}_{-i} -\end{align*} -$$ - - -
      -
    • Evaluate the prediction performance of these models on the test set by \( \log\{L[y_i, \hat{X}_{i, \ast}; \hat{\beta}_{-i}(\lambda), \hat{\sigma}_{-i}^2(\lambda)]\} \). Or, by the prediction error \( |y_i - \hat{X}_{i, \ast} \hat{\beta}_{-i}(\lambda)| \), the relative error, the error squared or the R2 score function.
    • -
    • Repeat the first three steps such that each sample plays the role of the test set once.
    • -
    • Average the prediction performances of the test sets at each grid point of the penalty bias/parameter by computing the cross-validated log-likelihood. It is an estimate of the prediction performance of the model corresponding to this value of the penalty parameter on novel data. It is defined as
    • -
    - -$$ -\begin{align*} -\frac{1}{n} \sum_{i = 1}^n \log\{L[y_i, \mathbf{X}_{i, \ast}; \hat{\beta}_{-i}(\lambda), \hat{\sigma}_{-i}^2(\lambda)]\}. -\end{align*} -$$ - - -
      -
    • The value of the penalty parameter that maximizes the cross-validated log-likelihood is the value of choice. Or we can use the MSE or the R2 score functions.
    • +
    • The validation estimate of the test error rate can be highly variable, depending on precisely which observations are included in the training set and which observations are included in the validation set.
    • +
    • In the validation approach, only a subset of the observations, those that are included in the training set rather than in the validation set are used to fit the model. Since statistical methods tend to perform worse when trained on fewer observations, this suggests that the validation set error rate may tend to overestimate the test error rate for the model fit on the entire data set.

    @@ -473,7 +416,7 @@ $$

  • 85
  • 86
  • ...
  • -
  • 114
  • +
  • 100
  • »
  • diff --git a/doc/pub/Regression/html/._Regression-bs077.html b/doc/pub/Regression/html/._Regression-bs077.html index 0dcd30563..f9822b325 100644 --- a/doc/pub/Regression/html/._Regression-bs077.html +++ b/doc/pub/Regression/html/._Regression-bs077.html @@ -6,6 +6,7 @@ Automatically generated HTML file from DocOnce source + Data Analysis and Machine Learning: Linear Regression and more Advanced Regression Analysis @@ -40,160 +41,151 @@ Automatically generated HTML file from DocOnce source @@ -286,119 +263,109 @@ MathJax.Hub.Config({ @@ -412,29 +379,25 @@ MathJax.Hub.Config({

     

     

     

    - + -

    Predicted Residual Error Sum of Squares

    -
    -
    -

    -Another approach in the LOOCV scheme is to the use the so-called Predicted Residual Error Sum of Squares (PRESS). +

    Various steps in cross-validation

    -We can define the optimal penalty parameter to minimize -$$ -\begin{align*} -\lambda_{\mbox{{\tiny opt}}} = \arg \min_{\lambda} \frac{1}{n} \sum_{i=1}^n [y_i - \hat{X}_{i, \ast} \hat{\beta}_{-i}(\lambda)]^2. -\end{align*} -$$ - -

    -The LOOCV prediction performance can be -expressed analytically in terms of the known quantities derived from -the design matrix and the parameters \( \beta \). -

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

    @@ -462,7 +425,7 @@ the design matrix and the parameters \( \beta \).

  • 86
  • 87
  • ...
  • -
  • 114
  • +
  • 100
  • »
  • diff --git a/doc/pub/Regression/html/._Regression-bs078.html b/doc/pub/Regression/html/._Regression-bs078.html index a036fb8f0..bfe54afc5 100644 --- a/doc/pub/Regression/html/._Regression-bs078.html +++ b/doc/pub/Regression/html/._Regression-bs078.html @@ -6,6 +6,7 @@ Automatically generated HTML file from DocOnce source + Data Analysis and Machine Learning: Linear Regression and more Advanced Regression Analysis @@ -40,160 +41,151 @@ Automatically generated HTML file from DocOnce source @@ -286,119 +263,109 @@ MathJax.Hub.Config({ @@ -412,29 +379,42 @@ MathJax.Hub.Config({

     

     

     

    - + -

    Resampling methods: Jackknife and Bootstrap

    +

    How to set up the cross-validation for Ridge and/or Lasso

    -

    -Two famous -resampling methods are the independent bootstrap and the jackknife. +

      +
    • 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 \( \boldsymbol{\sigma}_{-i}^2(\lambda) \), as
    • +
    -

    -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. +$$ +\begin{align*} +\boldsymbol{\beta}_{-i}(\lambda) & = ( \boldsymbol{X}_{-i, \ast}^{T} +\boldsymbol{X}_{-i, \ast} + \lambda \boldsymbol{I}_{pp})^{-1} +\boldsymbol{X}_{-i, \ast}^{T} \boldsymbol{y}_{-i} +\end{align*} +$$ -

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

    +

      +
    • Evaluate the prediction performance of these models on the test set by \( \log\{L[y_i, \boldsymbol{X}_{i, \ast}; \boldsymbol{\beta}_{-i}(\lambda), \boldsymbol{\sigma}_{-i}^2(\lambda)]\} \). Or, by the prediction error \( |y_i - \boldsymbol{X}_{i, \ast} \boldsymbol{\beta}_{-i}(\lambda)| \), the relative error, the error squared or the R2 score function.
    • +
    • Repeat the first three steps such that each sample plays the role of the test set once.
    • +
    • Average the prediction performances of the test sets at each grid point of the penalty bias/parameter by computing the cross-validated log-likelihood. It is an estimate of the prediction performance of the model corresponding to this value of the penalty parameter on novel data. It is defined as
    • +
    + +$$ +\begin{align*} +\frac{1}{n} \sum_{i = 1}^n \log\{L[y_i, \mathbf{X}_{i, \ast}; \boldsymbol{\beta}_{-i}(\lambda), \boldsymbol{\sigma}_{-i}^2(\lambda)]\}. +\end{align*} +$$ + + +
      +
    • The value of the penalty parameter that maximizes the cross-validated log-likelihood is the value of choice. Or we can use the MSE or the R2 score functions.
    • +
    +

    diff --git a/doc/pub/Regression/html/._Regression-bs079.html b/doc/pub/Regression/html/._Regression-bs079.html index 085b050b8..79e1d53f1 100644 --- a/doc/pub/Regression/html/._Regression-bs079.html +++ b/doc/pub/Regression/html/._Regression-bs079.html @@ -6,6 +6,7 @@ Automatically generated HTML file from DocOnce source + Data Analysis and Machine Learning: Linear Regression and more Advanced Regression Analysis @@ -40,160 +41,151 @@ Automatically generated HTML file from DocOnce source @@ -286,119 +263,109 @@ MathJax.Hub.Config({ @@ -414,21 +381,25 @@ MathJax.Hub.Config({ -

    Resampling methods: Jackknife

    +

    Resampling methods: Jackknife and Bootstrap

    -The Jackknife works by making many replicas of the estimator \( \widehat{\theta} \). -The jackknife is a resampling method, we explained that this happens by scrambling the data in some way. When using the jackknife, this is done by systematically leaving out one observation from the vector of observed values \( \hat{x} = (x_1,x_2,\cdots,X_n) \). -Let \( \hat{x}_i \) denote the vector -$$ -\hat{x}_i = (x_1,x_2,\cdots,x_{i-1},x_{i+1},\cdots,x_n), -$$ +Two famous +resampling methods are the independent bootstrap and the jackknife.

    -which equals the vector \( \hat{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 \). +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.

    @@ -456,7 +427,7 @@ number \( i \) is left out. Using this notation, define

  • 88
  • 89
  • ...
  • -
  • 114
  • +
  • 100
  • »
  • diff --git a/doc/pub/Regression/html/._Regression-bs080.html b/doc/pub/Regression/html/._Regression-bs080.html index ecd481bcd..efecd3647 100644 --- a/doc/pub/Regression/html/._Regression-bs080.html +++ b/doc/pub/Regression/html/._Regression-bs080.html @@ -6,6 +6,7 @@ Automatically generated HTML file from DocOnce source + Data Analysis and Machine Learning: Linear Regression and more Advanced Regression Analysis @@ -40,160 +41,151 @@ Automatically generated HTML file from DocOnce source @@ -286,119 +263,109 @@ MathJax.Hub.Config({ @@ -414,16 +381,21 @@ MathJax.Hub.Config({ -

    Resampling methods: Jackknife estimator

    +

    Resampling methods: Jackknife

    -To get an estimate for the bias and -standard error of \( \widehat{\theta} \), use the following -estimators for each component of \( \widehat{\theta} \) +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 \( \boldsymbol{x} = (x_1,x_2,\cdots,X_n) \). +Let \( \boldsymbol{x}_i \) denote the vector +$$ +\boldsymbol{x}_i = (x_1,x_2,\cdots,x_{i-1},x_{i+1},\cdots,x_n), +$$ -$$ -\widehat{\mathrm{Bias}}(\widehat \theta,\theta) = (n-1)\left( - \widehat{\theta} + \frac{1}{n}\sum_{i=1}^{n} \widehat \theta_i \right) \qquad \text{and} \qquad \widehat{\sigma}^2_{\widehat{\theta} } = \frac{n-1}{n}\sum_{i=1}^{n}( \widehat{\theta}_i - \frac{1}{n}\sum_{j=1}^{n}\widehat \theta_j )^2. -$$ +

    +which equals the vector \( \boldsymbol{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 \).

    @@ -451,7 +423,7 @@ $$

  • 89
  • 90
  • ...
  • -
  • 114
  • +
  • 100
  • »
  • diff --git a/doc/pub/Regression/html/._Regression-bs081.html b/doc/pub/Regression/html/._Regression-bs081.html index 7e303dfcd..d69fce222 100644 --- a/doc/pub/Regression/html/._Regression-bs081.html +++ b/doc/pub/Regression/html/._Regression-bs081.html @@ -6,6 +6,7 @@ Automatically generated HTML file from DocOnce source + Data Analysis and Machine Learning: Linear Regression and more Advanced Regression Analysis @@ -40,160 +41,151 @@ Automatically generated HTML file from DocOnce source @@ -286,119 +263,109 @@ MathJax.Hub.Config({ @@ -473,7 +440,7 @@ t = jackknife(x, stat)
  • 90
  • 91
  • ...
  • -
  • 114
  • +
  • 100
  • »
  • diff --git a/doc/pub/Regression/html/._Regression-bs082.html b/doc/pub/Regression/html/._Regression-bs082.html index 56b16a767..88c2e3683 100644 --- a/doc/pub/Regression/html/._Regression-bs082.html +++ b/doc/pub/Regression/html/._Regression-bs082.html @@ -6,6 +6,7 @@ Automatically generated HTML file from DocOnce source + Data Analysis and Machine Learning: Linear Regression and more Advanced Regression Analysis @@ -40,160 +41,151 @@ Automatically generated HTML file from DocOnce source @@ -286,119 +263,109 @@ MathJax.Hub.Config({ @@ -459,7 +426,7 @@ advantages:
  • 91
  • 92
  • ...
  • -
  • 114
  • +
  • 100
  • »
  • diff --git a/doc/pub/Regression/html/._Regression-bs083.html b/doc/pub/Regression/html/._Regression-bs083.html index cf4050f4b..f13ff3412 100644 --- a/doc/pub/Regression/html/._Regression-bs083.html +++ b/doc/pub/Regression/html/._Regression-bs083.html @@ -6,6 +6,7 @@ Automatically generated HTML file from DocOnce source + Data Analysis and Machine Learning: Linear Regression and more Advanced Regression Analysis @@ -40,160 +41,151 @@ Automatically generated HTML file from DocOnce source @@ -286,119 +263,109 @@ MathJax.Hub.Config({ @@ -417,14 +384,14 @@ MathJax.Hub.Config({

    Resampling methods: Bootstrap background

    -Since \( \widehat{\theta} = \widehat{\theta}(\hat{X}) \) is a function of random variables, +Since \( \widehat{\theta} = \widehat{\theta}(\boldsymbol{X}) \) is a function of random variables, \( \widehat{\theta} \) itself must be a random variable. Thus it has -a pdf, call this function \( p(\hat{t}) \). The aim of the bootstrap is to -estimate \( p(\hat{t}) \) by the relative frequency of +a pdf, call this function \( p(\boldsymbol{t}) \). The aim of the bootstrap is to +estimate \( p(\boldsymbol{t}) \) by the relative frequency of \( \widehat{\theta} \). You can think of this as using a histogram -in the place of \( p(\hat{t}) \). If the relative frequency closely +in the place of \( p(\boldsymbol{t}) \). If the relative frequency closely resembles \( p(\vec{t}) \), then using numerics, it is straight forward to -estimate all the interesting parameters of \( p(\hat{t}) \) using point +estimate all the interesting parameters of \( p(\boldsymbol{t}) \) using point estimators.

    @@ -453,7 +420,7 @@ estimators.

  • 92
  • 93
  • ...
  • -
  • 114
  • +
  • 100
  • »
  • diff --git a/doc/pub/Regression/html/._Regression-bs084.html b/doc/pub/Regression/html/._Regression-bs084.html index 3d671f1dd..563450133 100644 --- a/doc/pub/Regression/html/._Regression-bs084.html +++ b/doc/pub/Regression/html/._Regression-bs084.html @@ -6,6 +6,7 @@ Automatically generated HTML file from DocOnce source + Data Analysis and Machine Learning: Linear Regression and more Advanced Regression Analysis @@ -40,160 +41,151 @@ Automatically generated HTML file from DocOnce source @@ -286,119 +263,109 @@ MathJax.Hub.Config({ @@ -431,7 +398,7 @@ been straight forward to do this by: By repeated use of (1) and (2), many estimates of \( \widehat{\theta} \) could have been obtained. The idea is to use the relative frequency of \( \widehat{\theta}^* \) -(think of a histogram) as an estimate of \( p(\hat{t}) \). +(think of a histogram) as an estimate of \( p(\boldsymbol{t}) \).

    @@ -459,7 +426,7 @@ idea is to use the relative frequency of \( \widehat{\theta}^* \)

  • 93
  • 94
  • ...
  • -
  • 114
  • +
  • 100
  • »
  • diff --git a/doc/pub/Regression/html/._Regression-bs085.html b/doc/pub/Regression/html/._Regression-bs085.html index f179675cc..ae9cc591e 100644 --- a/doc/pub/Regression/html/._Regression-bs085.html +++ b/doc/pub/Regression/html/._Regression-bs085.html @@ -6,6 +6,7 @@ Automatically generated HTML file from DocOnce source + Data Analysis and Machine Learning: Linear Regression and more Advanced Regression Analysis @@ -40,160 +41,151 @@ Automatically generated HTML file from DocOnce source @@ -286,119 +263,109 @@ MathJax.Hub.Config({ @@ -430,7 +397,7 @@ result in some asymptotic sense? The answer is yes. Instead of generating the histogram for the relative frequency of the observation \( X_i \), just draw the values \( (X_1^*,X_2^*,\cdots,X_n^*) \) with replacement from the vector -\( \hat{X} \). +\( \boldsymbol{X} \).

    @@ -458,7 +425,7 @@ frequency of the observation \( X_i \), just draw the values

  • 94
  • 95
  • ...
  • -
  • 114
  • +
  • 100
  • »
  • diff --git a/doc/pub/Regression/html/._Regression-bs086.html b/doc/pub/Regression/html/._Regression-bs086.html index d8e74b8ca..784594eb9 100644 --- a/doc/pub/Regression/html/._Regression-bs086.html +++ b/doc/pub/Regression/html/._Regression-bs086.html @@ -6,6 +6,7 @@ Automatically generated HTML file from DocOnce source + Data Analysis and Machine Learning: Linear Regression and more Advanced Regression Analysis @@ -40,160 +41,151 @@ Automatically generated HTML file from DocOnce source @@ -286,119 +263,109 @@ MathJax.Hub.Config({ @@ -420,13 +387,21 @@ MathJax.Hub.Config({ The independent bootstrap works like this:
      -
    1. Draw with replacement \( n \) numbers for the observed variables \( \hat{x} = (x_1,x_2,\cdots,x_n) \).
    2. -
    3. Define a vector \( \hat{x}^* \) containing the values which were drawn from \( \hat{x} \).
    4. -
    5. Using the vector \( \hat{x}^* \) compute \( \widehat{\theta}^* \) by evaluating \( \widehat \theta \) under the observations \( \hat{x}^* \).
    6. +
    7. Draw with replacement \( n \) numbers for the observed variables \( \boldsymbol{x} = (x_1,x_2,\cdots,x_n) \).
    8. +
    9. Define a vector \( \boldsymbol{x}^* \) containing the values which were drawn from \( \boldsymbol{x} \).
    10. +
    11. Using the vector \( \boldsymbol{x}^* \) compute \( \widehat{\theta}^* \) by evaluating \( \widehat \theta \) under the observations \( \boldsymbol{x}^* \).
    12. Repeat this process \( k \) times.
    -When you are done, you can draw a histogram of the relative frequency of \( \widehat \theta^* \). This is your estimate of the probability distribution \( p(t) \). Using this probability distribution you can estimate any statistics thereof. In principle you never draw the histogram of the relative frequency of \( \widehat{\theta}^* \). Instead you use the estimators corresponding to the statistic of interest. For example, if you are interested in estimating the variance of \( \widehat \theta \), apply the etsimator \( \widehat \sigma^2 \) to the values \( \widehat \theta ^* \). +When you are done, you can draw a histogram of the relative frequency +of \( \widehat \theta^* \). This is your estimate of the probability +distribution \( p(t) \). Using this probability distribution you can +estimate any statistics thereof. In principle you never draw the +histogram of the relative frequency of \( \widehat{\theta}^* \). Instead +you use the estimators corresponding to the statistic of interest. For +example, if you are interested in estimating the variance of \( \widehat +\theta \), apply the etsimator \( \widehat \sigma^2 \) to the values +\( \widehat \theta ^* \).

    @@ -454,7 +429,7 @@ When you are done, you can draw a histogram of the relative frequency of \( \wid

  • 95
  • 96
  • ...
  • -
  • 114
  • +
  • 100
  • »
  • diff --git a/doc/pub/Regression/html/._Regression-bs087.html b/doc/pub/Regression/html/._Regression-bs087.html index 12202de9d..a2bb69c80 100644 --- a/doc/pub/Regression/html/._Regression-bs087.html +++ b/doc/pub/Regression/html/._Regression-bs087.html @@ -6,6 +6,7 @@ Automatically generated HTML file from DocOnce source + Data Analysis and Machine Learning: Linear Regression and more Advanced Regression Analysis @@ -40,160 +41,151 @@ Automatically generated HTML file from DocOnce source @@ -286,119 +263,109 @@ MathJax.Hub.Config({ @@ -415,7 +382,21 @@ MathJax.Hub.Config({

    Code example for the Bootstrap method

    -The following code starts with a Gaussian distribution with mean value \( \mu =100 \) and variance \( \sigma=15 \). We use this to generate the data used in the bootstrap analysis. The bootstrap analysis returns a data set after a given number of bootstrap operations (as many as we have data points). This data set consists of estimated mean values for each bootstrap operation. The histogram generated by the bootstrap method shows that the distribution for these mean values is also a Gaussian, centered around the mean value \( \mu=100 \) but with standard deviation \( \sigma/\sqrt{n} \), where \( n \) is the number of bootstrap samples (in this case the same as the number of original data points). The value of the standard deviation is what we expect from the central limit theorem. + +

    +The following code starts with a Gaussian distribution with mean value +\( \mu =100 \) and variance \( \sigma=15 \). We use this to generate the data +used in the bootstrap analysis. The bootstrap analysis returns a data +set after a given number of bootstrap operations (as many as we have +data points). This data set consists of estimated mean values for each +bootstrap operation. The histogram generated by the bootstrap method +shows that the distribution for these mean values is also a Gaussian, +centered around the mean value \( \mu=100 \) but with standard deviation +\( \sigma/\sqrt{n} \), where \( n \) is the number of bootstrap samples (in +this case the same as the number of original data points). The value +of the standard deviation is what we expect from the central limit +theorem. +

    @@ -429,30 +410,29 @@ The following code starts with a Gaussian distribution with mean value \( \mu =1 def stat(data): return mean(data) -# Bootstrap algorithm +# Bootstrap algorithm def bootstrap(data, statistic, R): t = zeros(R); n = len(data); inds = arange(n); t0 = time() - - # non-parametric bootstrap + # non-parametric bootstrap for i in range(R): t[i] = statistic(data[randint(0,n,n)]) - # analysis + # analysis print("Runtime: %g sec" % (time()-t0)); print("Bootstrap Statistics :") print("original bias std. error") - print("%8g %8g %14g %15g" % (statistic(data), std(data),\ - mean(t), \ - std(t))) + print("%8g %8g %14g %15g" % (statistic(data), std(data),mean(t),std(t))) return t mu, sigma = 100, 15 datapoints = 10000 x = mu + sigma*random.randn(datapoints) -# bootstrap returns the data sample t = bootstrap(x, stat, datapoints) -# the histogram of the bootstrapped data n, binsboot, patches = plt.hist(t, 50, normed=1, facecolor='red', alpha=0.75) +# bootstrap returns the data sample +t = bootstrap(x, stat, datapoints) +# the histogram of the bootstrapped data +n, binsboot, patches = plt.hist(t, 50, normed=1, facecolor='red', alpha=0.75) -# add a 'best fit' line +# add a 'best fit' line y = mlab.normpdf( binsboot, mean(t), std(t)) lt = plt.plot(binsboot, y, 'r--', linewidth=1) plt.xlabel('Smarts') @@ -488,7 +468,7 @@ plt.show()

  • 96
  • 97
  • ...
  • -
  • 114
  • +
  • 100
  • »
  • diff --git a/doc/pub/Regression/html/._Regression-bs088.html b/doc/pub/Regression/html/._Regression-bs088.html index 50e9bcb92..712697d73 100644 --- a/doc/pub/Regression/html/._Regression-bs088.html +++ b/doc/pub/Regression/html/._Regression-bs088.html @@ -6,6 +6,7 @@ Automatically generated HTML file from DocOnce source + Data Analysis and Machine Learning: Linear Regression and more Advanced Regression Analysis @@ -40,160 +41,151 @@ Automatically generated HTML file from DocOnce source @@ -286,119 +263,109 @@ MathJax.Hub.Config({ @@ -414,29 +381,103 @@ MathJax.Hub.Config({ -

    Resampling methods: Blocking

    +

    Code Example for Cross-validation and \( k \)-fold Cross-validation

    -The blocking method was made popular by Flyvbjerg and Pedersen (1989) -and has become one of the standard ways to estimate -\( V(\widehat{\theta}) \) for exactly one \( \widehat{\theta} \), namely -\( \widehat{\theta} = \overline{X} \). - +The code here uses Ridge regression with cross-validation (CV) resampling and \( k \)-fold CV in order to fit a specific polynomial.

    -Assume \( n = 2^d \) for some integer \( d>1 \) and \( X_1,X_2,\cdots, X_n \) is a stationary time series to begin with. -Moreover, assume that the time series is asymptotically uncorrelated. We switch to vector notation by arranging \( X_1,X_2,\cdots,X_n \) in an \( n \)-tuple. Define: -$$ -\begin{align*} -\hat{X} = (X_1,X_2,\cdots,X_n). -\end{align*} -$$ -

    -The strength of the blocking method is when the number of -observations, \( n \) is large. For large \( n \), the complexity of dependent -bootstrapping scales poorly, but the blocking method does not, -moreover, it becomes more accurate the larger \( n \) is. + +

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

    @@ -463,7 +504,7 @@ moreover, it becomes more accurate the larger \( n \) is.

  • 97
  • 98
  • ...
  • -
  • 114
  • +
  • 100
  • »
  • diff --git a/doc/pub/Regression/html/._Regression-bs089.html b/doc/pub/Regression/html/._Regression-bs089.html index 0996fba10..76d15ca46 100644 --- a/doc/pub/Regression/html/._Regression-bs089.html +++ b/doc/pub/Regression/html/._Regression-bs089.html @@ -6,6 +6,7 @@ Automatically generated HTML file from DocOnce source + Data Analysis and Machine Learning: Linear Regression and more Advanced Regression Analysis @@ -40,160 +41,151 @@ Automatically generated HTML file from DocOnce source @@ -286,119 +263,109 @@ MathJax.Hub.Config({ @@ -414,39 +381,68 @@ MathJax.Hub.Config({ -

    Blocking Transformations

    - We now define -blocking transformations. The idea is to take the mean of subsequent -pair of elements from \( \vec{X} \) and form a new vector -\( \vec{X}_1 \). Continuing in the same way by taking the mean of -subsequent pairs of elements of \( \vec{X}_1 \) we obtain \( \vec{X}_2 \), and -so on. -Define \( \vec{X}_i \) recursively by: +

    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 $$ -\begin{align} -(\vec{X}_0)_k &\equiv (\vec{X})_k \nonumber \\ -(\vec{X}_{i+1})_k &\equiv \frac{1}{2}\Big( (\vec{X}_i)_{2k-1} + -(\vec{X}_i)_{2k} \Big) \qquad \text{for all} \qquad 1 \leq i \leq d-1 -\tag{21} -\end{align} +\boldsymbol{y}=f(\boldsymbol{x}) + \boldsymbol{\epsilon} $$

    -The quantity \( \vec{X}_k \) is -subject to \( k \) blocking transformations. We now have \( d \) vectors -\( \vec{X}_0, \vec{X}_1,\cdots,\vec X_{d-1} \) containing the subsequent -averages of observations. It turns out that if the components of -\( \vec{X} \) is a stationary time series, then the components of -\( \vec{X}_i \) is a stationary time series for all \( 0 \leq i \leq d-1 \) +where \( \epsilon \) is normally distributed with mean zero and standard deviation \( \sigma^2 \).

    -We can then compute the autocovariance, the variance, sample mean, and -number of observations for each \( i \). -Let \( \gamma_i, \sigma_i^2, -\overline{X}_i \) denote the autocovariance, variance and average of the -elements of \( \vec{X}_i \) and let \( n_i \) be the number of elements of -\( \vec{X}_i \). It follows by induction that \( n_i = n/2^i \). +In our derivation of the ordinary least squares method we defined then +an approximation to the function \( f \) in terms of the parameters +\( \boldsymbol{\beta} \) and the design matrix \( \boldsymbol{X} \) which embody our model, +that is \( \boldsymbol{\tilde{y}}=\boldsymbol{X}\boldsymbol{\beta} \). + +

    +Thereafter we found the parameters \( \boldsymbol{\beta} \) by optimizing the means squared error via the so-called cost function +$$ +C(\boldsymbol{X},\boldsymbol{\beta}) =\frac{1}{n}\sum_{i=0}^{n-1}(y_i-\tilde{y}_i)^2=\mathbb{E}\left[(\boldsymbol{y}-\boldsymbol{\tilde{y}})^2\right]. +$$ + +

    +We can rewrite this as +$$ +\mathbb{E}\left[(\boldsymbol{y}-\boldsymbol{\tilde{y}})^2\right]=\frac{1}{n}\sum_i(f_i-\mathbb{E}\left[\boldsymbol{\tilde{y}}\right])^2+\frac{1}{n}\sum_i(\tilde{y}_i-\mathbb{E}\left[\boldsymbol{\tilde{y}}\right])^2+\sigma^2. +$$ + +

    +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 \( \boldsymbol{\epsilon} \). + +

    +To derive this equation, we need to recall that the variance of \( \boldsymbol{y} \) and \( \boldsymbol{\epsilon} \) are both equal to \( \sigma^2 \). The mean value of \( \boldsymbol{\epsilon} \) is by definition equal to zero. Furthermore, the function \( f \) is not a stochastics variable, idem for \( \boldsymbol{\tilde{y}} \). +We use a more compact notation in terms of the expectation value +$$ +\mathbb{E}\left[(\boldsymbol{y}-\boldsymbol{\tilde{y}})^2\right]=\mathbb{E}\left[(\boldsymbol{f}+\boldsymbol{\epsilon}-\boldsymbol{\tilde{y}})^2\right], +$$ + +and adding and subtracting \( \mathbb{E}\left[\boldsymbol{\tilde{y}}\right] \) we get +$$ +\mathbb{E}\left[(\boldsymbol{y}-\boldsymbol{\tilde{y}})^2\right]=\mathbb{E}\left[(\boldsymbol{f}+\boldsymbol{\epsilon}-\boldsymbol{\tilde{y}}+\mathbb{E}\left[\boldsymbol{\tilde{y}}\right]-\mathbb{E}\left[\boldsymbol{\tilde{y}}\right])^2\right], +$$ + +which, using the abovementioned expectation values can be rewritten as +$$ +\mathbb{E}\left[(\boldsymbol{y}-\boldsymbol{\tilde{y}})^2\right]=\mathbb{E}\left[(\boldsymbol{y}-\mathbb{E}\left[\boldsymbol{\tilde{y}}\right])^2\right]+\mathrm{Var}\left[\boldsymbol{\tilde{y}}\right]+\sigma^2, +$$ + +that is the rewriting in terms of the so-called bias, the variance of the model \( \boldsymbol{\tilde{y}} \) and the variance of \( \boldsymbol{\epsilon} \).

    @@ -474,7 +470,7 @@ elements of \( \vec{X}_i \) and let \( n_i \) be the number of elements of

  • 98
  • 99
  • ...
  • -
  • 114
  • +
  • 100
  • »
  • diff --git a/doc/pub/Regression/html/._Regression-bs090.html b/doc/pub/Regression/html/._Regression-bs090.html index 6f3641195..4262a3a91 100644 --- a/doc/pub/Regression/html/._Regression-bs090.html +++ b/doc/pub/Regression/html/._Regression-bs090.html @@ -6,6 +6,7 @@ Automatically generated HTML file from DocOnce source + Data Analysis and Machine Learning: Linear Regression and more Advanced Regression Analysis @@ -40,160 +41,151 @@ Automatically generated HTML file from DocOnce source @@ -286,119 +263,109 @@ MathJax.Hub.Config({ @@ -414,27 +381,65 @@ MathJax.Hub.Config({ -

    Blocking Transformations

    - +

    Example code for Bias-Variance tradeoff

    -Using the -definition of the blocking transformation and the distributive -property of the covariance, it is clear that since \( h =|i-j| \) -we can define -$$ -\begin{align} -\gamma_{k+1}(h) &= cov\left( ({X}_{k+1})_{i}, ({X}_{k+1})_{j} \right) \nonumber \\ -&= \frac{1}{4}cov\left( ({X}_{k})_{2i-1} + ({X}_{k})_{2i}, ({X}_{k})_{2j-1} + ({X}_{k})_{2j} \right) \nonumber \\ -&= \frac{1}{2}\gamma_{k}(2h) + \frac{1}{2}\gamma_k(2h+1) \hspace{0.1cm} \mathrm{h = 0} -\tag{22}\\ -&=\frac{1}{4}\gamma_k(2h-1) + \frac{1}{2}\gamma_k(2h) + \frac{1}{4}\gamma_k(2h+1) \quad \mathrm{else} -\tag{23} -\end{align} -$$ -

    -The quantity \( \hat{X} \) is asymptotic uncorrelated by assumption, \( \hat{X}_k \) is also asymptotic uncorrelated. Let's turn our attention to the variance of the sample mean \( V(\overline{X}) \). + +

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

    @@ -460,8 +465,6 @@ The quantity \( \hat{X} \) is asymptotic uncorrelated by assumption, \( \hat{X}_

  • 98
  • 99
  • 100
  • -
  • ...
  • -
  • 114
  • »
  • diff --git a/doc/pub/Regression/html/._Regression-bs091.html b/doc/pub/Regression/html/._Regression-bs091.html index fbe298fe1..900edcfc0 100644 --- a/doc/pub/Regression/html/._Regression-bs091.html +++ b/doc/pub/Regression/html/._Regression-bs091.html @@ -6,6 +6,7 @@ Automatically generated HTML file from DocOnce source + Data Analysis and Machine Learning: Linear Regression and more Advanced Regression Analysis @@ -40,160 +41,151 @@ Automatically generated HTML file from DocOnce source @@ -286,119 +263,109 @@ MathJax.Hub.Config({ @@ -414,25 +381,57 @@ MathJax.Hub.Config({ -

    Blocking Transformations, getting there

    -We have -$$ -\begin{align} -V(\overline{X}_k) = \frac{\sigma_k^2}{n_k} + \underbrace{\frac{2}{n_k} \sum_{h=1}^{n_k-1}\left( 1 - \frac{h}{n_k} \right)\gamma_k(h)}_{\equiv e_k} = \frac{\sigma^2_k}{n_k} + e_k \quad \text{if} \quad \gamma_k(0) = \sigma_k^2. -\tag{24} -\end{align} -$$ +

    Understanding what happens

    +

    -The term \( e_k \) is called the truncation error: -$$ -\begin{equation} -e_k = \frac{2}{n_k} \sum_{h=1}^{n_k-1}\left( 1 - \frac{h}{n_k} \right)\gamma_k(h). -\tag{25} -\end{equation} -$$ + +

    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
     
    -We can show that \( V(\overline{X}_i) = V(\overline{X}_j) \) for all \( 0 \leq i \leq d-1 \) and \( 0 \leq j \leq d-1 \).
    +np.random.seed(2018)
     
    +n = 40
    +n_boostraps = 100
    +maxdegree = 14
    +
    +
    +# Make data set.
    +x = np.linspace(-3, 3, n).reshape(-1, 1)
    +y = np.exp(-x**2) + 1.5 * np.exp(-(x-2)**2)+ np.random.normal(0, 0.1, x.shape)
    +error = np.zeros(maxdegree)
    +bias = np.zeros(maxdegree)
    +variance = np.zeros(maxdegree)
    +polydegree = np.zeros(maxdegree)
    +x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.2)
    +
    +for degree in range(maxdegree):
    +    model = make_pipeline(PolynomialFeatures(degree=degree), LinearRegression(fit_intercept=False))
    +    y_pred = np.empty((y_test.shape[0], n_boostraps))
    +    for i in range(n_boostraps):
    +        x_, y_ = resample(x_train, y_train)
    +        y_pred[:, i] = model.fit(x_, y_).predict(x_test).ravel()
    +
    +    polydegree[degree] = degree
    +    error[degree] = np.mean( np.mean((y_test - y_pred)**2, axis=1, keepdims=True) )
    +    bias[degree] = np.mean( (y_test - np.mean(y_pred, axis=1, keepdims=True))**2 )
    +    variance[degree] = np.mean( np.var(y_pred, axis=1, keepdims=True) )
    +    print('Polynomial degree:', degree)
    +    print('Error:', error[degree])
    +    print('Bias^2:', bias[degree])
    +    print('Var:', variance[degree])
    +    print('{} >= {} + {} = {}'.format(error[degree], bias[degree], variance[degree], bias[degree]+variance[degree]))
    +
    +plt.plot(polydegree, np.log10(error), label='Error')
    +plt.plot(polydegree, bias, label='bias')
    +plt.plot(polydegree, variance, label='Variance')
    +plt.legend()
    +plt.show()
    +

    @@ -457,9 +456,6 @@ We can show that \( V(\overline{X}_i) = V(\overline{X}_j) \) for all \( 0 \leq i

  • 98
  • 99
  • 100
  • -
  • 101
  • -
  • ...
  • -
  • 114
  • »
  • diff --git a/doc/pub/Regression/html/._Regression-bs092.html b/doc/pub/Regression/html/._Regression-bs092.html index 8eb337970..15286cf43 100644 --- a/doc/pub/Regression/html/._Regression-bs092.html +++ b/doc/pub/Regression/html/._Regression-bs092.html @@ -6,6 +6,7 @@ Automatically generated HTML file from DocOnce source + Data Analysis and Machine Learning: Linear Regression and more Advanced Regression Analysis @@ -40,160 +41,151 @@ Automatically generated HTML file from DocOnce source @@ -286,119 +263,109 @@ MathJax.Hub.Config({ @@ -412,35 +379,38 @@ MathJax.Hub.Config({

     

     

     

    - + -

    Blocking Transformations, final expressions

    +

    Summing up

    -We can then wrap up -$$ -\begin{align} -n_{j+1} \overline{X}_{j+1} &= \sum_{i=1}^{n_{j+1}} (\hat{X}_{j+1})_i = \frac{1}{2}\sum_{i=1}^{n_{j}/2} (\hat{X}_{j})_{2i-1} + (\hat{X}_{j})_{2i} \nonumber \\ -&= \frac{1}{2}\left[ (\hat{X}_j)_1 + (\hat{X}_j)_2 + \cdots + (\hat{X}_j)_{n_j} \right] = \underbrace{\frac{n_j}{2}}_{=n_{j+1}} \overline{X}_j = n_{j+1}\overline{X}_j. -\tag{26} -\end{align} -$$ - -By repeated use of this equation we get \( V(\overline{X}_i) = V(\overline{X}_0) = V(\overline{X}) \) for all \( 0 \leq i \leq d-1 \). This has the consequence that -$$ -\begin{align} -V(\overline{X}) = \frac{\sigma_k^2}{n_k} + e_k \qquad \text{for all} \qquad 0 \leq k \leq d-1. \tag{27} -\end{align} -$$ +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).

    -Fyvbjerg and Petersen demonstrated that the sequence -\( \{e_k\}_{k=0}^{d-1} \) is decreasing, and conjecture that the term -\( e_k \) can be made as small as we would like by making \( k \) (and hence -\( d \)) sufficiently large. The sequence is decreasing (Master of Science thesis by Marius Jonsson, UiO 2018). -It means we can apply blocking transformations until -\( e_k \) is sufficiently small, and then estimate \( V(\overline{X}) \) by -\( \widehat{\sigma}^2_k/n_k \). +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.

    @@ -465,10 +435,6 @@ It means we can apply blocking transformations until

  • 98
  • 99
  • 100
  • -
  • 101
  • -
  • 102
  • -
  • ...
  • -
  • 114
  • »
  • diff --git a/doc/pub/Regression/html/._Regression-bs093.html b/doc/pub/Regression/html/._Regression-bs093.html index c920cc72f..96afec3c3 100644 --- a/doc/pub/Regression/html/._Regression-bs093.html +++ b/doc/pub/Regression/html/._Regression-bs093.html @@ -6,6 +6,7 @@ Automatically generated HTML file from DocOnce source + Data Analysis and Machine Learning: Linear Regression and more Advanced Regression Analysis @@ -40,160 +41,151 @@ Automatically generated HTML file from DocOnce source @@ -286,119 +263,109 @@ MathJax.Hub.Config({ @@ -414,231 +381,81 @@ MathJax.Hub.Config({ -

    Code examples for Blocking, Jackknife and bootstrap

    - +

    Another Example rom Scikit-Learn's Repository

    -

    from sys import argv
    -from os import mkdir, path
    -import time
    +
    """
    +============================
    +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 matplotlib.ticker import FormatStrFormatter
    -from matplotlib.font_manager import FontProperties
    -
    -# Timing Decorator
    -def timeFunction(f):
    -    def wrap(*args):
    -        time1 = time.time()
    -        ret = f(*args)
    -        time2 = time.time()
    -        print '%s Function Took: \t %0.3f s' % (f.func_name.title(), (time2-time1))
    -        return ret
    -    return wrap
    -
    -class dataAnalysisClass:
    -    # General Init functions
    -    def __init__(self, fileName, size=0):
    -        self.inputFileName = fileName
    -        self.loadData(size)
    -        self.createOutputFolder()
    -        self.avg = np.average(self.data)
    -        self.var = np.var(self.data)
    -        self.std = np.std(self.data)
    -
    -    def loadData(self, size=0):
    -        if size != 0:
    -            with open(self.inputFileName) as inputFile:
    -                self.data = np.zeros(size)
    -                for x in xrange(size):
    -                    self.data[x] = float(next(inputFile))
    -        else:
    -            self.data = np.loadtxt(self.inputFileName)
    -
    -    # Statistical Analysis with Multiple Methods
    -    def runAllAnalyses(self):
    -        if len(self.data) <= 100000:
    -            print "Autocorrelation..."
    -            self.autocorrelation()
    -        print "Bootstrap..."
    -        self.bootstrap()
    -        print "Jackknife..."
    -        self.jackknife()
    -        print "Blocking..."
    -        self.blocking()
    -
    -    # Standard Autocorrelation
    -    @timeFunction
    -    def autocorrelation(self):
    -        self.acf = np.zeros(len(self.data)/2)
    -        for k in range(0, len(self.data)/2):
    -            self.acf[k] = np.corrcoef(np.array([self.data[0:len(self.data)-k], \
    -                                            self.data[k:len(self.data)]]))[0,1]
    -
    -    # Bootstrap
    -    @timeFunction
    -    def bootstrap(self, nBoots = 1000):
    -        bootVec = np.zeros(nBoots)
    -        for k in range(0,nBoots):
    -            bootVec[k] = np.average(np.random.choice(self.data, len(self.data)))
    -        self.bootAvg = np.average(bootVec)
    -        self.bootVar = np.var(bootVec)
    -        self.bootStd = np.std(bootVec)
    -
    -    # Jackknife
    -    @timeFunction
    -    def jackknife(self):
    -        jackknVec = np.zeros(len(self.data))
    -        for k in range(0,len(self.data)):
    -            jackknVec[k] = np.average(np.delete(self.data, k))
    -        self.jackknAvg = self.avg - (len(self.data) - 1) * (np.average(jackknVec) - self.avg)
    -        self.jackknVar = float(len(self.data) - 1) * np.var(jackknVec)
    -        self.jackknStd = np.sqrt(self.jackknVar)
    -
    -    # Blocking
    -    @timeFunction
    -    def blocking(self, blockSizeMax = 500):
    -        blockSizeMin = 1
    -
    -        self.blockSizes = []
    -        self.meanVec = []
    -        self.varVec = []
    -
    -        for i in range(blockSizeMin, blockSizeMax):
    -            if(len(self.data) % i != 0):
    -                pass#continue
    -            blockSize = i
    -            meanTempVec = []
    -            varTempVec = []
    -            startPoint = 0
    -            endPoint = blockSize
    -
    -            while endPoint <= len(self.data):
    -                meanTempVec.append(np.average(self.data[startPoint:endPoint]))
    -                startPoint = endPoint
    -                endPoint += blockSize
    -            mean, var = np.average(meanTempVec), np.var(meanTempVec)/len(meanTempVec)
    -            self.meanVec.append(mean)
    -            self.varVec.append(var)
    -            self.blockSizes.append(blockSize)
    -
    -        self.blockingAvg = np.average(self.meanVec[-200:])
    -        self.blockingVar = (np.average(self.varVec[-200:]))
    -        self.blockingStd = np.sqrt(self.blockingVar)
    +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)
     
    -    # Plot of Data, Autocorrelation Function and Histogram
    -    def plotAll(self):
    -        self.createOutputFolder()
    -        if len(self.data) <= 100000:
    -            self.plotAutocorrelation()
    -        self.plotData()
    -        self.plotHistogram()
    -        self.plotBlocking()
    +np.random.seed(0)
     
    -    # Create Output Plots Folder
    -    def createOutputFolder(self):
    -        self.outName = self.inputFileName[:-4]
    -        if not path.exists(self.outName):
    -            mkdir(self.outName)
    +n_samples = 30
    +degrees = [1, 4, 15]
     
    -    # Plot the Dataset, Mean and Std
    -    def plotData(self):
    -        # Far away plot
    -        font = {'fontname':'serif'}
    -        plt.plot(range(0, len(self.data)), self.data, 'r-', linewidth=1)
    -        plt.plot([0, len(self.data)], [self.avg, self.avg], 'b-', linewidth=1)
    -        plt.plot([0, len(self.data)], [self.avg + self.std, self.avg + self.std], 'g--', linewidth=1)
    -        plt.plot([0, len(self.data)], [self.avg - self.std, self.avg - self.std], 'g--', linewidth=1)
    -        plt.ylim(self.avg - 5*self.std, self.avg + 5*self.std)
    -        plt.gca().yaxis.set_major_formatter(FormatStrFormatter('%.4f'))
    -        plt.xlim(0, len(self.data))
    -        plt.ylabel(self.outName.title() + ' Monte Carlo Evolution', **font)
    -        plt.xlabel('MonteCarlo History', **font)
    -        plt.title(self.outName.title(), **font)
    -        plt.savefig(self.outName + "/data.eps")
    -        plt.savefig(self.outName + "/data.png")
    -        plt.clf()
    +X = np.sort(np.random.rand(n_samples))
    +y = true_fun(X) + np.random.randn(n_samples) * 0.1
     
    -    # Plot Histogram of Dataset and Gaussian around it
    -    def plotHistogram(self):
    -        binNumber = 50
    -        font = {'fontname':'serif'}
    -        count, bins, ignore = plt.hist(self.data, bins=np.linspace(self.avg - 5*self.std, self.avg + 5*self.std, binNumber))
    -        plt.plot([self.avg, self.avg], [0,np.max(count)+10], 'b-', linewidth=1)
    -        plt.ylim(0,np.max(count)+10)
    -        plt.ylabel(self.outName.title() + ' Histogram', **font)
    -        plt.xlabel(self.outName.title() , **font)
    -        plt.title('Counts', **font)
    +plt.figure(figsize=(14, 5))
    +for i in range(len(degrees)):
    +    ax = plt.subplot(1, len(degrees), i + 1)
    +    plt.setp(ax, xticks=(), yticks=())
     
    -        #gaussian
    -        norm = 0
    -        for i in range(0,len(bins)-1):
    -            norm += (bins[i+1]-bins[i])*count[i]
    -        plt.plot(bins,  norm/(self.std * np.sqrt(2 * np.pi)) * np.exp( - (bins - self.avg)**2 / (2 * self.std**2) ), linewidth=1, color='r')
    -        plt.savefig(self.outName + "/hist.eps")
    -        plt.savefig(self.outName + "/hist.png")
    -        plt.clf()
    +    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)
     
    -    # Plot the Autocorrelation Function
    -    def plotAutocorrelation(self):
    -        font = {'fontname':'serif'}
    -        plt.plot(range(1, len(self.data)/2), self.acf[1:], 'r-')
    -        plt.ylim(-1, 1)
    -        plt.xlim(0, len(self.data)/2)
    -        plt.ylabel('Autocorrelation Function', **font)
    -        plt.xlabel('Lag', **font)
    -        plt.title('Autocorrelation', **font)
    -        plt.savefig(self.outName + "/autocorrelation.eps")
    -        plt.savefig(self.outName + "/autocorrelation.png")
    -        plt.clf()
    +    # Evaluate the models using crossvalidation
    +    scores = cross_val_score(pipeline, X[:, np.newaxis], y,
    +                             scoring="neg_mean_squared_error", cv=10)
     
    -    def plotBlocking(self):
    -        font = {'fontname':'serif'}
    -        plt.plot(self.blockSizes, self.varVec, 'r-')
    -        plt.ylabel('Variance', **font)
    -        plt.xlabel('Block Size', **font)
    -        plt.title('Blocking', **font)
    -        plt.savefig(self.outName + "/blocking.eps")
    -        plt.savefig(self.outName + "/blocking.png")
    -        plt.clf()
    -
    -    # Print Stuff to the Terminal
    -    def printOutput(self):
    -        print "\nSample Size:    \t", len(self.data)
    -        print "\n=========================================\n"
    -        print "Sample Average: \t", self.avg
    -        print "Sample Variance:\t", self.var
    -        print "Sample Std:     \t", self.std
    -        print "\n=========================================\n"
    -        print "Bootstrap Average: \t", self.bootAvg
    -        print "Bootstrap Variance:\t", self.bootVar
    -        print "Bootstrap Error:   \t", self.bootStd
    -        print "\n=========================================\n"
    -        print "Jackknife Average: \t", self.jackknAvg
    -        print "Jackknife Variance:\t", self.jackknVar
    -        print "Jackknife Error:   \t", self.jackknStd
    -        print "\n=========================================\n"
    -        print "Blocking Average: \t", self.blockingAvg
    -        print "Blocking Variance:\t", self.blockingVar
    -        print "Blocking Error:   \t", self.blockingStd, "\n"
    -
    -# Initialize the class
    -if len(argv) > 2:
    -    dataAnalysis = dataAnalysisClass(argv[1], int(argv[2]))
    -else:
    -    dataAnalysis = dataAnalysisClass(argv[1])
    -
    -# Run Analyses
    -dataAnalysis.runAllAnalyses()
    -
    -# Plot the data
    -dataAnalysis.plotAll()
    -
    -# Print Some Output
    -dataAnalysis.printOutput()
    +    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()
     

    @@ -662,11 +479,6 @@ dataAnalysis.printOutput()

  • 98
  • 99
  • 100
  • -
  • 101
  • -
  • 102
  • -
  • 103
  • -
  • ...
  • -
  • 114
  • »
  • diff --git a/doc/pub/Regression/html/._Regression-bs094.html b/doc/pub/Regression/html/._Regression-bs094.html index bc286e726..f84d240d0 100644 --- a/doc/pub/Regression/html/._Regression-bs094.html +++ b/doc/pub/Regression/html/._Regression-bs094.html @@ -6,6 +6,7 @@ Automatically generated HTML file from DocOnce source + Data Analysis and Machine Learning: Linear Regression and more Advanced Regression Analysis @@ -40,160 +41,151 @@ Automatically generated HTML file from DocOnce source @@ -286,119 +263,109 @@ MathJax.Hub.Config({ @@ -414,25 +381,136 @@ MathJax.Hub.Config({ -

    The bias-variance tradeoff

    +

    The one-dimensional Ising model

    -We begin with an unknown function \( y=f(x) \) and fix a \emph{hypothesis set} - \( \mathcal{H} \) consisting of all functions we are willing to consider, - defined also on the domain of \( f \). This set may be uncountably - infinite (e.g. if there are real-valued parameters to fit). -The - choice of which functions to include in \( \mathcal{H} \) usually depends - on our intuition about the problem of interest. The function \( f(x) \) - produces a set of pairs \( (x_i,y_i) \), \( i=1\dots N \), which serve as the - observable data. Our goal is to select a function from the hypothesis - set \( h\in\mathcal{H} \) which approximates \( f(x) \) as best as possible, - namely, we would like to find \( h\in\mathcal{H} \) such that \( h\approx - f \) in some strict mathematical sense which we specify below. If this - is possible, we say that we \emph{learned} \( f(x) \). But if the - function \( f(x) \) can, in principle, take any value on - \emph{unobserved} inputs, how is it possible to learn in any - meaningful sense? +Let us bring back the Ising model again, but now with an additional +focus on Ridge and Lasso regression as well. We repeat some of the +basic parts of the Ising model and the setup of the training and test +data. The one-dimensional Ising model with nearest neighbor +interaction, no external field and a constant coupling constant \( J \) is +given by + +$$ +\begin{align} + H = -J \sum_{k}^L s_k s_{k + 1}, +\tag{27} +\end{align} +$$ + +where \( s_i \in \{-1, 1\} \) and \( s_{N + 1} = s_1 \). The number of spins in the system is determined by \( L \). For the one-dimensional system there is no phase transition. + +

    +We will look at a system of \( L = 40 \) spins with a coupling constant of \( J = 1 \). To get enough training data we will generate 10000 states with their respective energies. + +

    + + +

    import numpy as np
    +import matplotlib.pyplot as plt
    +from mpl_toolkits.axes_grid1 import make_axes_locatable
    +import seaborn as sns
    +import scipy.linalg as scl
    +from sklearn.model_selection import train_test_split
    +import sklearn.linear_model as skl
    +import tqdm
    +sns.set(color_codes=True)
    +cmap_args=dict(vmin=-1., vmax=1., cmap='seismic')
    +
    +L = 40
    +n = int(1e4)
    +
    +spins = np.random.choice([-1, 1], size=(n, L))
    +J = 1.0
    +
    +energies = np.zeros(n)
    +
    +for i in range(n):
    +    energies[i] = - J * np.dot(spins[i], np.roll(spins[i], 1))
    +
    +

    +A more general form for the one-dimensional Ising model is + +$$ +\begin{align} + H = - \sum_j^L \sum_k^L s_j s_k J_{jk}. +\tag{28} +\end{align} +$$ + +

    +Here we allow for interactions beyond the nearest neighbors and a more +adaptive coupling matrix. This latter expression can be formulated as +a matrix-product on the form +$$ +\begin{align} + H = X J, +\tag{29} +\end{align} +$$ + +

    +where \( X_{jk} = s_j s_k \) and \( J \) is the matrix consisting of the +elements \( -J_{jk} \). This form of writing the energy fits perfectly +with the form utilized in linear regression, viz. +$$ +\begin{align} + \boldsymbol{y} = \boldsymbol{X}\boldsymbol{\beta} + \boldsymbol{\epsilon}. +\tag{30} +\end{align} +$$ + +We organize the data as we did above +

    + + +

    X = np.zeros((n, L ** 2))
    +for i in range(n):
    +    X[i] = np.outer(spins[i], spins[i]).ravel()
    +y = energies
    +X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.96)
    +
    +X_train_own = np.concatenate(
    +    (np.ones(len(X_train))[:, np.newaxis], X_train),
    +    axis=1
    +)
    +
    +X_test_own = np.concatenate(
    +    (np.ones(len(X_test))[:, np.newaxis], X_test),
    +    axis=1
    +)
    +
    +

    +We will do all fitting with Scikit-Learn, + +

    + + +

    clf = skl.LinearRegression().fit(X_train, y_train)
    +
    +

    +When extracting the \( J \)-matrix we make sure to remove the intercept +

    + + +

    J_sk = clf.coef_.reshape(L, L)
    +
    +

    +And then we plot the results +

    + + +

    fig = plt.figure(figsize=(20, 14))
    +im = plt.imshow(J_sk, **cmap_args)
    +plt.title("LinearRegression from Scikit-learn", fontsize=18)
    +plt.xticks(fontsize=18)
    +plt.yticks(fontsize=18)
    +cb = fig.colorbar(im)
    +cb.ax.set_yticklabels(cb.ax.get_yticklabels(), fontsize=18)
    +plt.show()
    +
    +

    +The results perfectly with our previous discussion where we used our own code.

    @@ -455,12 +533,6 @@ The

  • 98
  • 99
  • 100
  • -
  • 101
  • -
  • 102
  • -
  • 103
  • -
  • 104
  • -
  • ...
  • -
  • 114
  • »
  • diff --git a/doc/pub/Regression/html/._Regression-bs095.html b/doc/pub/Regression/html/._Regression-bs095.html index dd2a7d757..51156d4a3 100644 --- a/doc/pub/Regression/html/._Regression-bs095.html +++ b/doc/pub/Regression/html/._Regression-bs095.html @@ -6,6 +6,7 @@ Automatically generated HTML file from DocOnce source + Data Analysis and Machine Learning: Linear Regression and more Advanced Regression Analysis @@ -40,160 +41,151 @@ Automatically generated HTML file from DocOnce source @@ -286,119 +263,109 @@ MathJax.Hub.Config({ @@ -412,18 +379,40 @@ MathJax.Hub.Config({

     

     

     

    - + -

    Training and testing data

    +

    Ridge regression

    -We will discuss the bias-variance tradeoff in the context of continuous predictions such as regression. However, many of the intuitions and ideas discussed here also carry over to classification tasks. Consider a dataset \( \mathcal{L} \) consisting of the data \( \mathbf{X}_\mathcal{L}=\{(y_j, \boldsymbol{x}_j), j=1\ldots N\} \). Let us assume that the true data is generated from a noisy model +Having explored the ordinary least squares we move on to ridge +regression. In ridge regression we include a regularizer. This +involves a new cost function which leads to a new estimate for the +weights \( \boldsymbol{\beta} \). This results in a penalized regression problem. The +cost function is given by + $$ -y=f(\boldsymbol{x}) + \epsilon +\begin{align} + C(\boldsymbol{X}, \boldsymbol{\beta}; \lambda) = (\boldsymbol{X}\boldsymbol{\beta} - \boldsymbol{y})^T(\boldsymbol{X}\boldsymbol{\beta} - \boldsymbol{y}) + \lambda \boldsymbol{\beta}^T\boldsymbol{\beta}. +\tag{31} +\end{align} $$ -where \( \epsilon \) is normally distributed with mean zero and standard deviation \( \sigma_\epsilon \). +

    + +

    _lambda = 0.1
    +clf_ridge = skl.Ridge(alpha=_lambda).fit(X_train, y_train)
    +J_ridge_sk = clf_ridge.coef_.reshape(L, L)
    +fig = plt.figure(figsize=(20, 14))
    +im = plt.imshow(J_ridge_sk, **cmap_args)
    +plt.title("Ridge from Scikit-learn", fontsize=18)
    +plt.xticks(fontsize=18)
    +plt.yticks(fontsize=18)
    +cb = fig.colorbar(im)
    +cb.ax.set_yticklabels(cb.ax.get_yticklabels(), fontsize=18)
    +
    +plt.show()
    +

    @@ -444,13 +433,6 @@ where \( \epsilon \) is normally distributed with mean zero and standard deviati

  • 98
  • 99
  • 100
  • -
  • 101
  • -
  • 102
  • -
  • 103
  • -
  • 104
  • -
  • 105
  • -
  • ...
  • -
  • 114
  • »
  • diff --git a/doc/pub/Regression/html/._Regression-bs096.html b/doc/pub/Regression/html/._Regression-bs096.html index 3a7bdd300..9b8d9e10e 100644 --- a/doc/pub/Regression/html/._Regression-bs096.html +++ b/doc/pub/Regression/html/._Regression-bs096.html @@ -6,6 +6,7 @@ Automatically generated HTML file from DocOnce source + Data Analysis and Machine Learning: Linear Regression and more Advanced Regression Analysis @@ -40,160 +41,151 @@ Automatically generated HTML file from DocOnce source @@ -286,119 +263,109 @@ MathJax.Hub.Config({ @@ -414,19 +381,41 @@ MathJax.Hub.Config({ -

    Procedure to find a predictor

    +

    LASSO regression

    -We have a statistical procedure (e.g. least-squares regression) for -forming a predictor \( \hat{g}_{\mathcal{L}}(\boldsymbol{x}) \) that gives the -prediction of our model for a new data point \( \boldsymbol{x} \). This estimator -is chosen by minimizing a cost function which we take to be the -squared error +In the Least Absolute Shrinkage and Selection Operator (LASSO)-method we get a third cost function. $$ - \mathcal{C}( \boldsymbol{X}, \hat{g}(\boldsymbol{x})) = \sum_i (y_i - \hat{g}_\mathcal{L}(\boldsymbol{x}_i))^2. +\begin{align} + C(\boldsymbol{X}, \boldsymbol{\beta}; \lambda) = (\boldsymbol{X}\boldsymbol{\beta} - \boldsymbol{y})^T(\boldsymbol{X}\boldsymbol{\beta} - \boldsymbol{y}) + \lambda \sqrt{\boldsymbol{\beta}^T\boldsymbol{\beta}}. +\tag{32} +\end{align} $$ +

    +Finding the extremal point of this cost function is not so straight-forward as in least squares and ridge. We will therefore rely solely on the function ``Lasso`` from Scikit-Learn. + +

    + + +

    clf_lasso = skl.Lasso(alpha=_lambda).fit(X_train, y_train)
    +J_lasso_sk = clf_lasso.coef_.reshape(L, L)
    +fig = plt.figure(figsize=(20, 14))
    +im = plt.imshow(J_lasso_sk, **cmap_args)
    +plt.title("Lasso from Scikit-learn", fontsize=18)
    +plt.xticks(fontsize=18)
    +plt.yticks(fontsize=18)
    +cb = fig.colorbar(im)
    +cb.ax.set_yticklabels(cb.ax.get_yticklabels(), fontsize=18)
    +
    +plt.show()
    +
    +

    +It is quite striking how LASSO breaks the symmetry of the coupling +constant as opposed to ridge and OLS. We get a sparse solution with +\( J_{j, j + 1} = -1 \). +

    @@ -446,14 +435,6 @@ $$

  • 98
  • 99
  • 100
  • -
  • 101
  • -
  • 102
  • -
  • 103
  • -
  • 104
  • -
  • 105
  • -
  • 106
  • -
  • ...
  • -
  • 114
  • »
  • diff --git a/doc/pub/Regression/html/._Regression-bs097.html b/doc/pub/Regression/html/._Regression-bs097.html index 2e2730446..9399d436b 100644 --- a/doc/pub/Regression/html/._Regression-bs097.html +++ b/doc/pub/Regression/html/._Regression-bs097.html @@ -6,6 +6,7 @@ Automatically generated HTML file from DocOnce source + Data Analysis and Machine Learning: Linear Regression and more Advanced Regression Analysis @@ -40,160 +41,151 @@ Automatically generated HTML file from DocOnce source @@ -286,119 +263,109 @@ MathJax.Hub.Config({ @@ -414,19 +381,56 @@ MathJax.Hub.Config({ -

    What we want

    +

    Performance as function of the regularization parameter

    -We are interested in the generalization error on all data drawn from -the true model, not just the error on the particular training dataset -\( \mathcal{L} \) that we have in hand. This is just the expectation of -the cost function over many different data sets -\( \{\mathcal{L}_j\} \). Denote this expectation value by -\( E_{\mathcal{L}} \). In other words, we can view \( \hat{g}_{\mathcal{L}} \) -as a stochastic functional that depends on the dataset \( \mathcal{L} \) -and we can think of \( E_{\mathcal{L}} \) as the expected value of the -functional if we drew an infinite number of datasets \( \{\mathcal{L}_1, -\mathcal{L}_2, \ldots \} \). +We see how the different models perform for a different set of values for \( \lambda \). + +

    + + +

    lambdas = np.logspace(-4, 5, 10)
    +
    +train_errors = {
    +    "ols_sk": np.zeros(lambdas.size),
    +    "ridge_sk": np.zeros(lambdas.size),
    +    "lasso_sk": np.zeros(lambdas.size)
    +}
    +
    +test_errors = {
    +    "ols_sk": np.zeros(lambdas.size),
    +    "ridge_sk": np.zeros(lambdas.size),
    +    "lasso_sk": np.zeros(lambdas.size)
    +}
    +
    +plot_counter = 1
    +
    +fig = plt.figure(figsize=(32, 54))
    +
    +for i, _lambda in enumerate(tqdm.tqdm(lambdas)):
    +    for key, method in zip(
    +        ["ols_sk", "ridge_sk", "lasso_sk"],
    +        [skl.LinearRegression(), skl.Ridge(alpha=_lambda), skl.Lasso(alpha=_lambda)]
    +    ):
    +        method = method.fit(X_train, y_train)
    +
    +        train_errors[key][i] = method.score(X_train, y_train)
    +        test_errors[key][i] = method.score(X_test, y_test)
    +
    +        omega = method.coef_.reshape(L, L)
    +
    +        plt.subplot(10, 5, plot_counter)
    +        plt.imshow(omega, **cmap_args)
    +        plt.title(r"%s, $\lambda = %.4f$" % (key, _lambda))
    +        plot_counter += 1
    +
    +plt.show()
    +
    +

    +We see that LASSO reaches a good solution for low +values of \( \lambda \), but will "wither" when we increase \( \lambda \) too +much. Ridge is more stable over a larger range of values for +\( \lambda \), but eventually also fades away.

    @@ -446,15 +450,6 @@ functional if we drew an infinite number of datasets \( \{\mathcal{L}_1,

  • 98
  • 99
  • 100
  • -
  • 101
  • -
  • 102
  • -
  • 103
  • -
  • 104
  • -
  • 105
  • -
  • 106
  • -
  • 107
  • -
  • ...
  • -
  • 114
  • »
  • diff --git a/doc/pub/Regression/html/._Regression-bs098.html b/doc/pub/Regression/html/._Regression-bs098.html index 9715e431d..205ff2efa 100644 --- a/doc/pub/Regression/html/._Regression-bs098.html +++ b/doc/pub/Regression/html/._Regression-bs098.html @@ -6,6 +6,7 @@ Automatically generated HTML file from DocOnce source + Data Analysis and Machine Learning: Linear Regression and more Advanced Regression Analysis @@ -40,160 +41,151 @@ Automatically generated HTML file from DocOnce source @@ -286,119 +263,109 @@ MathJax.Hub.Config({ @@ -414,28 +381,54 @@ MathJax.Hub.Config({ -

    The expected generalization error

    +

    Finding the optimal value of \( \lambda \)

    -We would also like to average over different instances of the -"noise" \( \epsilon \) and we denote the expectation value over the -noise by \( E_\epsilon \). Thus, we can decompose the expected -generalization error as - -$$ -\begin{align} -E_\mathcal{L, \epsilon}[\mathcal{C}( \boldsymbol{X}, \hat{g}(\boldsymbol{x})) ]&= E_\mathcal{L,\epsilon}\left[ \sum_i ({y}_i - \hat{g}_\mathcal{L}(\boldsymbol{x}_i))^2 \right] \nonumber \\ - &= E_\mathcal{L, \epsilon}\left[ \sum_{i}({y}_i -f(\boldsymbol{x}_i) +f(\boldsymbol{x}_i)- \hat{g}_\mathcal{L}(\boldsymbol{x}_i))^2\right] \nonumber \\ - &= \sum_i E_\epsilon[ ({y}_i -f(\boldsymbol{x}_i))^2 ]+ E_\mathcal{L, \epsilon}[(f(\boldsymbol{x}_i)- \hat{g}_\mathcal{L}(\boldsymbol{x}_i))^2] + 2E_\epsilon[{y}_i -f(\boldsymbol{x}_i)]E_\mathcal{L}[f(\boldsymbol{x}_i)- \hat{g}_\mathcal{L}(\boldsymbol{x}_i)] \nonumber \\ - &=\sum_i \sigma_\epsilon^2 + E_\mathcal{L}[(f(\boldsymbol{x}_i)- \hat{g}_\mathcal{L}(\boldsymbol{x}_i))^2], -\tag{28} -\end{align} -$$ +To determine which value of \( \lambda \) is best we plot the accuracy of +the models when predicting the training and the testing set. We expect +the accuracy of the training set to be quite good, but if the accuracy +of the testing set is much lower this tells us that we might be +subject to an overfit model. The ideal scenario is an accuracy on the +testing set that is close to the accuracy of the training set.

    -where in the last line we used the fact that our noise has zero mean -and variance \( \sigma_\epsilon^2 \) and the sum over \( i \) applies to all -terms. + + +

    fig = plt.figure(figsize=(20, 14))
    +
    +colors = {
    +    "ols_sk": "r",
    +    "ridge_sk": "y",
    +    "lasso_sk": "c"
    +}
    +
    +for key in train_errors:
    +    plt.semilogx(
    +        lambdas,
    +        train_errors[key],
    +        colors[key],
    +        label="Train {0}".format(key),
    +        linewidth=4.0
    +    )
    +
    +for key in test_errors:
    +    plt.semilogx(
    +        lambdas,
    +        test_errors[key],
    +        colors[key] + "--",
    +        label="Test {0}".format(key),
    +        linewidth=4.0
    +    )
    +plt.legend(loc="best", fontsize=18)
    +plt.xlabel(r"$\lambda$", fontsize=18)
    +plt.ylabel(r"$R^2$", fontsize=18)
    +plt.tick_params(labelsize=18)
    +plt.show()
    +
    +

    +From the above figure we can see that LASSO with \( \lambda = 10^{-2} \) +achieves a very good accuracy on the test set. This by far surpasses the +other models for all values of \( \lambda \).

    @@ -454,16 +447,6 @@ terms.

  • 98
  • 99
  • 100
  • -
  • 101
  • -
  • 102
  • -
  • 103
  • -
  • 104
  • -
  • 105
  • -
  • 106
  • -
  • 107
  • -
  • 108
  • -
  • ...
  • -
  • 114
  • »
  • diff --git a/doc/pub/Regression/html/._Regression-bs099.html b/doc/pub/Regression/html/._Regression-bs099.html index 90fd9cece..89e30924b 100644 --- a/doc/pub/Regression/html/._Regression-bs099.html +++ b/doc/pub/Regression/html/._Regression-bs099.html @@ -6,6 +6,7 @@ Automatically generated HTML file from DocOnce source + Data Analysis and Machine Learning: Linear Regression and more Advanced Regression Analysis @@ -40,160 +41,151 @@ Automatically generated HTML file from DocOnce source @@ -286,119 +263,109 @@ MathJax.Hub.Config({ @@ -414,23 +381,234 @@ MathJax.Hub.Config({ -

    Elaborating a little bit more

    +

    Further Exercises

    + +

    Exercise 1

    -It is also helpful to further decompose the second term as -follows: +We will generate our own dataset for a function \( y(x) \) where \( x \in [0,1] \) and defined by random numbers computed with the uniform distribution. The function \( y \) is a quadratic polynomial in \( x \) with added stochastic noise according to the normal distribution \( \cal {N}(0,1) \). +The following simple Python instructions define our \( x \) and \( y \) values (with 100 data points). +

    + +

    x = np.random.rand(100,1)
    +y = 5*x*x+0.1*np.random.randn(100,1)
    +
    +
      +
    1. Write your own code (following the examples above) for computing the parametrization of the data set fitting a second-order polynomial.
    2. +
    3. Use thereafter scikit-learn (see again the examples in the regression slides) and compare with your own code.
    4. +
    5. Using scikit-learn, compute also the mean square error, a risk metric corresponding to the expected value of the squared (quadratic) error defined as
    6. +
    + +$$ MSE(\hat{y},\hat{\tilde{y}}) = \frac{1}{n} +\sum_{i=0}^{n-1}(y_i-\tilde{y}_i)^2, $$ -\begin{align} -E_\mathcal{L}[(f(\boldsymbol{x}_i)- \hat{g}_\mathcal{L}(\boldsymbol{x}_i))^2] &=E_\mathcal{L}[(f(\mathbf{x}_i)-E_\mathcal{L}[\hat{g}_\mathcal{L}(\boldsymbol{x}_i)]+ E_\mathcal{L}[\hat{g}_\mathcal{L}(\boldsymbol{x}_i)]- \hat{g}_\mathcal{L}(\boldsymbol{x}_i))^2] \nonumber \\ -&=E_\mathcal{L}[(f(\boldsymbol{x}_i)-E_\mathcal{L}[\hat{g}_\mathcal{L}(\boldsymbol{x}_i)])^2] + E_\mathcal{L}[( \hat{g}_\mathcal{L}(\boldsymbol{x}_i)-E_\mathcal{L}[\hat{g}_\mathcal{L}(\boldsymbol{x}_i)])^2] \nonumber \\ -&+2E_\mathcal{L}[(f(\boldsymbol{x}_i)-E_\mathcal{L}[\hat{g}_\mathcal{L}(\boldsymbol{x}_i)])( \hat{g}_\mathcal{L}(\boldsymbol{x}_i)-E_\mathcal{L}[\hat{g}_\mathcal{L}(\boldsymbol{x}_i)])] \nonumber \\ -&=(f(\boldsymbol{x}_i)-E_\mathcal{L}[\hat{g}_\mathcal{L}(\boldsymbol{x}_i)])^2+E_\mathcal{L}[( \hat{g}_\mathcal{L}(\boldsymbol{x}_i)-E_\mathcal{L}[\hat{g}_\mathcal{L}(\boldsymbol{x}_i)])^2]. -\tag{29} -\end{align} + +and the \( R^2 \) score function. +If \( \tilde{\hat{y}}_i \) is the predicted value of the \( i-th \) sample and \( y_i \) is the corresponding true value, then the score \( R^2 \) is defined as +$$ +R^2(\hat{y}, \tilde{\hat{y}}) = 1 - \frac{\sum_{i=0}^{n - 1} (y_i - \tilde{y}_i)^2}{\sum_{i=0}^{n - 1} (y_i - \bar{y})^2}, +$$ + +where we have defined the mean value of \( \hat{y} \) as +$$ +\bar{y} = \frac{1}{n} \sum_{i=0}^{n - 1} y_i. $$

    +You can use the functionality included in scikit-learn. If you feel +for it, you can use your own program and define functions which +compute the above two functions. Discuss the meaning of these +results. Try also to vary the coefficient in front of the added +stochastic noise term and discuss the quality of the fits. + +

    Exercise 2, variance of the parameters \( \beta \) in linear regression

    + +

    +Show that the variance of the parameters \( \beta \) in the linear regression method (chapter 3, equation (3.8) of Trevor Hastie, Robert Tibshirani, Jerome H. Friedman, The Elements of Statistical Learning, Springer) is given as + +$$ +\mathrm{Var}(\hat{\beta}) = \left(\hat{X}^T\hat{X}\right)^{-1}\sigma^2, +$$ + +with +$$ +\sigma^2 = \frac{1}{N-p-1}\sum_{i=1}^{N} (y_i-\tilde{y}_i)^2, +$$ + +where we have assumed that we fit a function of degree \( p-1 \) (for example a polynomial in \( x \)). + +

    Exercise 3

    + +

    +This exercise is a continuation of exercise 1. We will +use the same function to generate our data set, still staying with a +simple function \( y(x) \) which we want to fit using linear regression, +but now extending the analysis to include the Ridge and the Lasso +regression methods. You can use the code under the Regression as an example on how to use the Ridge and the Lasso methods. + +

    +We will thus again generate our own dataset for a function \( y(x) \) where +\( x \in [0,1] \) and defined by random numbers computed with the uniform +distribution. The function \( y \) is a quadratic polynomial in \( x \) with +added stochastic noise according to the normal distribution \( \cal{N}(0,1) \). + +

    +The following simple Python instructions define our \( x \) and \( y \) values (with 100 data points). +

    + + +

    x = np.random.rand(100,1)
    +y = 5*x*x+0.1*np.random.randn(100,1)
    +
    +
      +
    1. Write your own code for the Ridge method and compute the parametrization for different values of \( \lambda \). Compare and analyze your results with those from exercise 1. Study the dependence on \( \lambda \) while also varying the strength of the noise in your expression for \( y(x) \).
    2. +
    3. Repeat the above but using the functionality of scikit-learn. Compare your code with the results from scikit-learn. Remember to run with the same random numbers for generating \( x \) and \( y \).
    4. +
    5. Our next step is to study the variance of the parameters \( \beta_1 \) and \( \beta_2 \) (assuming that we are parametrizing our function with a second-order polynomial. We will use standard linear regression and the Ridge regression. You can now opt for either writing your own function that calculates the variance of these paramaters (recall that this is equal to the diagonal elements of the matrix \( (\hat{X}^T\hat{X})+\lambda\hat{I})^{-1} \)) or use the functionality of scikit-learn and compute their variances. Discuss the results of these variances as functions
    6. +
    7. Repeat the previous step but add now the Lasso method. Discuss your results and compare with standard regression and the Ridge regression results.
    8. +
    9. Try to implement the cross-validation as well.
    10. +
    11. Finally, using scikit-learn or your own code, compute also the mean square error, a risk metric corresponding to the expected value of the squared (quadratic) error defined as
    12. +
    + +$$ MSE(\hat{y},\hat{\tilde{y}}) = \frac{1}{n} +\sum_{i=0}^{n-1}(y_i-\tilde{y}_i)^2, +$$ + +and the \( R^2 \) score function. +If \( \tilde{\hat{y}}_i \) is the predicted value of the \( i-th \) sample and \( y_i \) is the corresponding true value, then the score \( R^2 \) is defined as +$$ +R^2(\hat{y}, \tilde{\hat{y}}) = 1 - \frac{\sum_{i=0}^{n - 1} (y_i - \tilde{y}_i)^2}{\sum_{i=0}^{n - 1} (y_i - \bar{y})^2}, +$$ + +where we have defined the mean value of \( \hat{y} \) as +$$ +\bar{y} = \frac{1}{n} \sum_{i=0}^{n - 1} y_i. +$$ + +Discuss these quantities as functions of the variable \( \lambda \) in the Ridge and Lasso regression methods. + +

    Exercise 4

    + +

    +We will study how +to fit polynomials to a specific two-dimensional function called +Franke's +function. This +is a function which has been widely used when testing various interpolation and fitting +algorithms. Furthermore, after having established the model and the +method, we will employ resamling techniques such as the cross-validation and/or +the bootstrap methods, in order to perform a proper assessment of our models. + +

    +The Franke function, which is a weighted sum of four exponentials reads as follows +$$ +\begin{align*} +f(x,y) &= \frac{3}{4}\exp{\left(-\frac{(9x-2)^2}{4} - \frac{(9y-2)^2}{4}\right)}+\frac{3}{4}\exp{\left(-\frac{(9x+1)^2}{49}- \frac{(9y+1)}{10}\right)} \\ +&+\frac{1}{2}\exp{\left(-\frac{(9x-7)^2}{4} - \frac{(9y-3)^2}{4}\right)} -\frac{1}{5}\exp{\left(-(9x-4)^2 - (9y-7)^2\right) }. +\end{align*} +$$ + +

    +The function will be defined for \( x,y\in [0,1] \). Our first step will +be to perform an OLS regression analysis of this function, trying out +a polynomial fit with an \( x \) and \( y \) dependence of the form \( [x, y, +x^2, y^2, xy, \dots] \). We will also include cross-validation and +bootstrap as resampling techniques. As in homeworks 1 and 2, we +can use a uniform distribution to set up the arrays of values for \( x \) +and \( y \), or as in the example below just a fix values for \( x \) and \( y \) with a given step size. +In this case we will have two predictors and need to fit a +function (for example a polynomial) of \( x \) and \( y \). Thereafter we will +repeat much of the same procedure using the the Ridge and +Lasso regression methods, introducing thus a dependence on the bias +(penalty) \( \lambda \). + +

    +The Python fucntion for the Franke function is included here (it performs also a three-dimensional plot of it) +

    + + +

    from mpl_toolkits.mplot3d import Axes3D
    +import matplotlib.pyplot as plt
    +from matplotlib import cm
    +from matplotlib.ticker import LinearLocator, FormatStrFormatter
    +import numpy as np
    +from random import random, seed
    +
    +fig = plt.figure()
    +ax = fig.gca(projection='3d')
    +
    +# Make data.
    +x = np.arange(0, 1, 0.05)
    +y = np.arange(0, 1, 0.05)
    +x, y = np.meshgrid(x,y)
    +
    +
    +def FrankeFunction(x,y):
    +    term1 = 0.75*np.exp(-(0.25*(9*x-2)**2) - 0.25*((9*y-2)**2))
    +    term2 = 0.75*np.exp(-((9*x+1)**2)/49.0 - 0.1*(9*y+1))
    +    term3 = 0.5*np.exp(-(9*x-7)**2/4.0 - 0.25*((9*y-3)**2))
    +    term4 = -0.2*np.exp(-(9*x-4)**2 - (9*y-7)**2)
    +    return term1 + term2 + term3 + term4
    +
    +
    +z = FrankeFunction(x, y)
    +
    +# Plot the surface.
    +surf = ax.plot_surface(x, y, z, cmap=cm.coolwarm,
    +                       linewidth=0, antialiased=False)
    +
    +# Customize the z axis.
    +ax.set_zlim(-0.10, 1.40)
    +ax.zaxis.set_major_locator(LinearLocator(10))
    +ax.zaxis.set_major_formatter(FormatStrFormatter('%.02f'))
    +
    +# Add a color bar which maps values to colors.
    +fig.colorbar(surf, shrink=0.5, aspect=5)
    +
    +plt.show()
    +
    +

    +We will thus again generate our own dataset for a function \( \mathrm{FrankeFunction}(x,y) \) where +\( x,y \in [0,1] \) could be defined by random numbers computed with the uniform +distribution. The function \( f(x,y) \) is the Franke function. You should explore also the addition +an added stochastic noise to this function using the normal distribution \( \cal{N}(0,1) \). + +

    +Write your own code (using either a matrix inversion or a singular value decomposition from e.g., numpy ) or use your code from exercises 1 and 3 +and perform a standard least square regression analysis using polynomials in \( x \) and \( y \) up to fifth order. Find the confidence intervals of the parameters \( \beta \) by computing their variances, evaluate the Mean Squared error (MSE) +$$ MSE(\hat{y},\hat{\tilde{y}}) = \frac{1}{n} +\sum_{i=0}^{n-1}(y_i-\tilde{y}_i)^2, +$$ + +and the \( R^2 \) score function. +If \( \tilde{\hat{y}}_i \) is the predicted value of the \( i-th \) sample and \( y_i \) is the corresponding true value, then the score \( R^2 \) is defined as +$$ +R^2(\hat{y}, \tilde{\hat{y}}) = 1 - \frac{\sum_{i=0}^{n - 1} (y_i - \tilde{y}_i)^2}{\sum_{i=0}^{n - 1} (y_i - \bar{y})^2}, +$$ + +where we have defined the mean value of \( \hat{y} \) as +$$ +\bar{y} = \frac{1}{n} \sum_{i=0}^{n - 1} y_i. +$$ + +

    +Perform a resampling of the data where you split the data in training data and test data. Implement the \( k \)-fold cross-validation algorithm and/or the bootstrap algorithm +and evaluate again the MSE and the \( R^2 \) functions resulting from the test data. Evaluate also the bias and variance of the final models. + +

    +Write then your own code for the Ridge method, either using matrix +inversion or the singular value decomposition as done for standard OLS. Perform the same analysis as in the +previous exercise (for the same polynomials and include resampling +techniques) but now for different values of \( \lambda \). Compare and +analyze your results with those obtained with standard OLS. Study the +dependence on \( \lambda \) while also varying eventually the strength of +the noise in your expression for \( \mathrm{FrankeFunction}(x,y) \). + +

    +Then perform the same studies but now with Lasso regression. Use the functionalities of +scikit-learn. Give a critical discussion of the three methods and a +judgement of which model fits the data best. +

    diff --git a/doc/pub/Regression/html/Regression-bs.html b/doc/pub/Regression/html/Regression-bs.html index f2952f17c..cf5feb8ed 100644 --- a/doc/pub/Regression/html/Regression-bs.html +++ b/doc/pub/Regression/html/Regression-bs.html @@ -6,6 +6,7 @@ Automatically generated HTML file from DocOnce source + Data Analysis and Machine Learning: Linear Regression and more Advanced Regression Analysis @@ -40,160 +41,151 @@ Automatically generated HTML file from DocOnce source @@ -286,119 +263,109 @@ MathJax.Hub.Config({ @@ -433,7 +400,7 @@ MathJax.Hub.Config({
    [2] Department of Physics and Astronomy and National Superconducting Cyclotron Laboratory, Michigan State University

    -

    Oct 18, 2018

    +

    Jun 10, 2019


    @@ -457,7 +424,7 @@ MathJax.Hub.Config({

  • 9
  • 10
  • ...
  • -
  • 114
  • +
  • 100
  • »
  • @@ -475,7 +442,7 @@ MathJax.Hub.Config({
    - © 1999-2018, Morten Hjorth-Jensen. Released under CC Attribution-NonCommercial 4.0 license + © 1999-2019, Morten Hjorth-Jensen. Released under CC Attribution-NonCommercial 4.0 license
    diff --git a/doc/pub/Regression/html/Regression-reveal.html b/doc/pub/Regression/html/Regression-reveal.html index b5a627cb8..2c150b03f 100644 --- a/doc/pub/Regression/html/Regression-reveal.html +++ b/doc/pub/Regression/html/Regression-reveal.html @@ -1,8 +1,8 @@ -\ + Data Analysis and Machine Learning: Linear Regression and more Advanced Regression Analysis @@ -148,61 +148,87 @@ MathJax.Hub.Config({
    [2] Department of Physics and Astronomy and National Superconducting Cyclotron Laboratory, Michigan State University

     
    -

    Oct 18, 2018

    +

    Jun 10, 2019


    - © 1999-2018, Morten Hjorth-Jensen. Released under CC Attribution-NonCommercial 4.0 license + © 1999-2019, Morten Hjorth-Jensen. Released under CC Attribution-NonCommercial 4.0 license
    -

    Regression analysis, overarching aims

    -
    - -

    -Regression modeling deals with the description of the sampling distribution of a given random variable \( y \) varies as function of another variable or a set of such variables \( \hat{x} =[x_0, x_1,\dots, x_p]^T \). -The first variable is called the dependent, the outcome or the response variable while the set of variables \( \hat{x} \) is called the independent variable, or the predictor variable or the explanatory variable. +

    Why Linear Regression (aka Ordinary Least Squares and family)

    -A regression model aims at finding a likelihood function \( p(y\vert \hat{x}) \), that is the conditional distribution for \( y \) with a given \( \hat{x} \). The estimation of \( p(y\vert \hat{x}) \) is made using a data set with +Fitting a continuous function with linear parameterization in terms of the parameters \( \boldsymbol{\beta} \).

      -

    • \( n \) cases \( i = 0, 1, 2, \dots, n-1 \)
    • -

    • Response (dependent or outcome) variable \( y_i \) with \( i = 0, 1, 2, \dots, n-1 \)
    • -

    • \( p \) Explanatory (independent or predictor) variables \( \hat{x}_i=[x_{i0}, x_{i1}, \dots, x_{ip}] \) with \( i = 0, 1, 2, \dots, n-1 \)
    • +

    • Method of choice for fitting a continuous function!
    • +

    • Gives an excellent introduction to central Machine Learning features with understandable pedagogical links to other methods like Neural Networks, Support Vector Machines etc
    • +

    • Analytical expression for the fitting parameters \( \boldsymbol{\beta} \)
    • +

    • Analytical expressions for statistical propertiers like mean values, variances, confidence intervals and more
    • +

    • Analytical relation with probabilistic interpretations
    • +

    • Easy to introduce basic concepts like bias-variance tradeoff, cross-validation, resampling and regularization techniques and many other ML topics
    • +

    • Easy to code! And links well with classification problems and logistic regression and neural networks
    • +

    • Allows for easy hands-on understanding of gradient descent methods
    • +

    • and many more features

    - The goal of the regression analysis is to extract/exploit relationship between \( y_i \) and \( \hat{x}_i \) in or to infer causal dependencies, approximations to the likelihood functions, functional relationships and to make predictions . +For more discussions of Ridge and Lasso regression, Wessel van Wieringen's article is highly recommended. +Similarly, Mehta et al's article is also recommended. +

    + + +
    +

    Regression analysis, overarching aims

    +
    + +

    +Regression modeling deals with the description of the sampling distribution of a given random variable \( y \) and how it varies as function of another variable or a set of such variables \( \boldsymbol{x} =[x_0, x_1,\dots, x_{n-1}]^T \). +The first variable is called the dependent, the outcome or the response variable while the set of variables \( \boldsymbol{x} \) is called the independent variable, or the predictor variable or the explanatory variable. + +

    +A regression model aims at finding a likelihood function \( p(\boldsymbol{y}\vert \boldsymbol{x}) \), that is the conditional distribution for \( \boldsymbol{y} \) with a given \( \boldsymbol{x} \). The estimation of \( p(\boldsymbol{y}\vert \boldsymbol{x}) \) is made using a data set with + +

      +

    • \( n \) cases \( i = 0, 1, 2, \dots, n-1 \)
    • +

    • Response (target, dependent or outcome) variable \( y_i \) with \( i = 0, 1, 2, \dots, n-1 \)
    • +

    • \( p \) so-called explanatory (independent or predictor) variables \( \boldsymbol{x}_i=[x_{i0}, x_{i1}, \dots, x_{ip-1}] \) with \( i = 0, 1, 2, \dots, n-1 \) and explanatory variables running from \( 0 \) to \( p-1 \). See below for more explicit examples.
    • +
    +

    + + The goal of the regression analysis is to extract/exploit relationship between \( \boldsymbol{y} \) and \( \boldsymbol{X} \) in or to infer causal dependencies, approximations to the likelihood functions, functional relationships and to make predictions, making fits and many other things.

    -

    Regression analysis, overarching aims II

    +

    Regression analysis, overarching aims II

    Consider an experiment in which \( p \) characteristics of \( n \) samples are -measured. The data from this experiment are denoted \( \mathbf{X} \), with -\( \mathbf{X} \) as above. The matrix \( \mathbf{X} \) is called the design +measured. The data from this experiment, for various explanatory variables \( p \) are normally represented by a matrix +\( \mathbf{X} \). + +

    +The matrix \( \mathbf{X} \) is called the design matrix. Additional information of the samples is available in the -form of \( \mathbf{Y} \) (also as above). The variable \( \mathbf{Y} \) is +form of \( \boldsymbol{y} \) (also as above). The variable \( \boldsymbol{y} \) is generally referred to as the response variable. The aim of -regression analysis is to explain \( \mathbf{Y} \) in terms of -\( \mathbf{X} \) through a functional relationship like \( Y_i = +regression analysis is to explain \( \boldsymbol{y} \) in terms of +\( \boldsymbol{X} \) through a functional relationship like \( y_i = f(\mathbf{X}_{i,\ast}) \). When no prior knowledge on the form of \( f(\cdot) \) is available, it is common to assume a linear relationship -between \( \mathbf{X} \) and \( \mathbf{Y} \). This assumption gives rise to -the linear regression model where \( \beta = (\beta_1, \ldots, -\beta_p)^{\top} \) is the regression parameter. The parameter -\( \beta_j \), \( j=1, \ldots, p \), represents the effect size of covariate -\( j \) on the response. That is, for each unit change in covariate \( j \) -(while keeping the other covariates fixed) the observed change in the -response is equal to \( \beta_j \). +between \( \boldsymbol{X} \) and \( \boldsymbol{y} \). This assumption gives rise to +the linear regression model where \( \boldsymbol{\beta} = [\beta_0, \ldots, +\beta_{p-1}]^{T} \) are the regression parameters. + +

    +Linear regression gives us a set of analytical equations for the parameters \( \beta_j \).

    @@ -210,17 +236,47 @@ response is equal to \( \beta_j \).
    -

    General linear models

    +

    Examples

    -Before we proceed let us study a case from linear algebra where we aim at fitting a set of data \( \hat{y}=[y_0,y_1,\dots,y_{n-1}] \). We could think of these data as a result of an experiment or a complicated numerical experiment. These data are functions of a series of variables \( \hat{x}=[x_0,x_1,\dots,x_{n-1}] \), that is \( y_i = y(x_i) \) with \( i=0,1,2,\dots,n-1 \). The variables \( x_i \) could represent physical quantities like time, temperature, position etc. We assume that \( y(x) \) is a smooth function. +In order to understand the relation among the predictors \( p \), the set of data \( n \) and the target (outcome, output etc) \( \boldsymbol{y} \), +consider the model we discussed for describing nuclear binding energies. + +

    +There we assumed that we could parametrize the data using a polynomial approximation based on the liquid drop model. +Assuming +

     
    +$$ +BE(A) = a_0+a_1A+a_2A^{2/3}+a_3A^{-1/3}+a_4A^{-1}, +$$ +

     
    + +we have five predictors, that is the intercept, the \( A \) dependent term, the \( A^{2/3} \) term and the \( A^{-1/3} \) and \( A^{-1} \) terms. +This gives \( p=0,1,2,3,4 \). Furthermore we have \( n \) entries for each predictor. It means that our design matrix is a +\( p\times n \) matrix \( \boldsymbol{X} \). + +

    +Here the predictors are based on a model we have made. A popular data set which is widely encountered in ML applications is the +so-called credit card default data from Taiwan. The data set contains data on \( n=30000 \) credit card holders with predictors like gender, marital status, age, profession, education, etc. In total there are \( 24 \) such predictors or attributes leading to a design matrix of dimensionality \( 24 \times 30000 \) + + +

    +
    + + +
    +

    General linear models

    +
    + +

    +Before we proceed let us study a case from linear algebra where we aim at fitting a set of data \( \boldsymbol{y}=[y_0,y_1,\dots,y_{n-1}] \). We could think of these data as a result of an experiment or a complicated numerical experiment. These data are functions of a series of variables \( \boldsymbol{x}=[x_0,x_1,\dots,x_{n-1}] \), that is \( y_i = y(x_i) \) with \( i=0,1,2,\dots,n-1 \). The variables \( x_i \) could represent physical quantities like time, temperature, position etc. We assume that \( y(x) \) is a smooth function.

    Since obtaining these data points may not be trivial, we want to use these data to fit a function which can allow us to make predictions for values of \( y \) which are not in the present set. The perhaps simplest approach is to assume we can parametrize our function in terms of a polynomial of degree \( n-1 \) with \( n \) points, that is

     
    $$ -y=y(x) \rightarrow y(x_i)=\tilde{y}_i+\epsilon_i=\sum_{j=0}^{n-1} \beta_i x_i^j+\epsilon_i, +y=y(x) \rightarrow y(x_i)=\tilde{y}_i+\epsilon_i=\sum_{j=0}^{n-1} \beta_j x_i^j+\epsilon_i, $$

     
    @@ -232,7 +288,7 @@ where \( \epsilon_i \) is the error in our approximation.

    -

    Rewriting the fitting procedure as a linear algebra problem

    +

    Rewriting the fitting procedure as a linear algebra problem

    @@ -244,7 +300,7 @@ y_0&=\beta_0+\beta_1x_0^1+\beta_2x_0^2+\dots+\beta_{n-1}x_0^{n-1}+\epsilon_0\\ y_1&=\beta_0+\beta_1x_1^1+\beta_2x_1^2+\dots+\beta_{n-1}x_1^{n-1}+\epsilon_1\\ y_2&=\beta_0+\beta_1x_2^1+\beta_2x_2^2+\dots+\beta_{n-1}x_2^{n-1}+\epsilon_2\\ \dots & \dots \\ -y_{n-1}&=\beta_0+\beta_1x_{n-1}^1+\beta_2x_{n-1}^2+\dots+\beta_1x_{n-1}^{n-1}+\epsilon_{n-1}.\\ +y_{n-1}&=\beta_0+\beta_1x_{n-1}^1+\beta_2x_{n-1}^2+\dots+\beta_{n-1}x_{n-1}^{n-1}+\epsilon_{n-1}.\\ \end{align*} $$

     
    @@ -253,35 +309,35 @@ $$

    -

    Rewriting the fitting procedure as a linear algebra problem, follows

    +

    Rewriting the fitting procedure as a linear algebra problem, more details

    Defining the vectors

     
    $$ -\hat{y} = [y_0,y_1, y_2,\dots, y_{n-1}]^T, +\boldsymbol{y} = [y_0,y_1, y_2,\dots, y_{n-1}]^T, $$

     
    and

     
    $$ -\hat{\beta} = [\beta_0,\beta_1, \beta_2,\dots, \beta_{n-1}]^T, +\boldsymbol{\beta} = [\beta_0,\beta_1, \beta_2,\dots, \beta_{n-1}]^T, $$

     
    and

     
    $$ -\hat{\epsilon} = [\epsilon_0,\epsilon_1, \epsilon_2,\dots, \epsilon_{n-1}]^T, +\boldsymbol{\epsilon} = [\epsilon_0,\epsilon_1, \epsilon_2,\dots, \epsilon_{n-1}]^T, $$

     
    -and the matrix +and the design matrix

     
    $$ -\hat{X}= +\boldsymbol{X}= \begin{bmatrix} 1& x_{0}^1 &x_{0}^2& \dots & \dots &x_{0}^{n-1}\\ 1& x_{1}^1 &x_{1}^2& \dots & \dots &x_{1}^{n-1}\\ @@ -295,20 +351,26 @@ $$ we can rewrite our equations as

     
    $$ -\hat{y} = \hat{X}\hat{\beta}+\hat{\epsilon}. +\boldsymbol{y} = \boldsymbol{X}\boldsymbol{\beta}+\boldsymbol{\epsilon}. $$

     
    + +The above design matrix is called a Vandermonde matrix.

    -

    Generalizing the fitting procedure as a linear algebra problem

    +

    Generalizing the fitting procedure as a linear algebra problem

    -We are obviously not limited to the above polynomial. We could replace the various powers of \( x \) with elements of Fourier series, that is, instead of \( x_i^j \) we could have \( \cos{(j x_i)} \) or \( \sin{(j x_i)} \), or time series or other orthogonal functions. -For every set of values \( y_i,x_i \) we can then generalize the equations to +We are obviously not limited to the above polynomial expansions. We +could replace the various powers of \( x \) with elements of Fourier +series or instead of \( x_i^j \) we could have \( \cos{(j x_i)} \) or \( \sin{(j +x_i)} \), or time series or other orthogonal functions. For every set +of values \( y_i,x_i \) we can then generalize the equations to +

     
    $$ \begin{align*} @@ -318,23 +380,26 @@ y_2&=\beta_0x_{20}+\beta_1x_{21}+\beta_2x_{22}+\dots+\beta_{n-1}x_{2n-1}+\epsilo \dots & \dots \\ y_{i}&=\beta_0x_{i0}+\beta_1x_{i1}+\beta_2x_{i2}+\dots+\beta_{n-1}x_{in-1}+\epsilon_i\\ \dots & \dots \\ -y_{n-1}&=\beta_0x_{n-1,0}+\beta_1x_{n-1,2}+\beta_2x_{n-1,2}+\dots+\beta_1x_{n-1,n-1}+\epsilon_{n-1}.\\ +y_{n-1}&=\beta_0x_{n-1,0}+\beta_1x_{n-1,2}+\beta_2x_{n-1,2}+\dots+\beta_{n-1}x_{n-1,n-1}+\epsilon_{n-1}.\\ \end{align*} $$

     
    + +

    +Note that we have \( p=n \) here. The matrix is symmetric. This is generally not the case!

    -

    Generalizing the fitting procedure as a linear algebra problem

    +

    Generalizing the fitting procedure as a linear algebra problem

    -We redefine in turn the matrix \( \hat{X} \) as +We redefine in turn the matrix \( \boldsymbol{X} \) as

     
    $$ -\hat{X}= +\boldsymbol{X}= \begin{bmatrix} x_{00}& x_{01} &x_{02}& \dots & \dots &x_{0,n-1}\\ x_{10}& x_{11} &x_{12}& \dots & \dots &x_{1,n-1}\\ @@ -348,21 +413,21 @@ $$ and without loss of generality we rewrite again our equations as

     
    $$ -\hat{y} = \hat{X}\hat{\beta}+\hat{\epsilon}. +\boldsymbol{y} = \boldsymbol{X}\boldsymbol{\beta}+\boldsymbol{\epsilon}. $$

     
    -The left-hand side of this equation forms know. Our error vector \( \hat{\epsilon} \) and the parameter vector \( \hat{\beta} \) are our unknow quantities. How can we obtain the optimal set of \( \beta_i \) values? +The left-hand side of this equation is kwown. Our error vector \( \boldsymbol{\epsilon} \) and the parameter vector \( \boldsymbol{\beta} \) are our unknow quantities. How can we obtain the optimal set of \( \beta_i \) values?

    -

    Optimizing our parameters

    +

    Optimizing our parameters

    -We have defined the matrix \( \hat{X} \) +We have defined the matrix \( \boldsymbol{X} \) via the equations

     
    $$ \begin{align*} @@ -372,83 +437,214 @@ y_2&=\beta_0x_{20}+\beta_1x_{21}+\beta_2x_{22}+\dots+\beta_{n-1}x_{2n-1}+\epsilo \dots & \dots \\ y_{i}&=\beta_0x_{i0}+\beta_1x_{i1}+\beta_2x_{i2}+\dots+\beta_{n-1}x_{in-1}+\epsilon_1\\ \dots & \dots \\ -y_{n-1}&=\beta_0x_{n-1,0}+\beta_1x_{n-1,2}+\beta_2x_{n-1,2}+\dots+\beta_1x_{n-1,n-1}+\epsilon_{n-1}.\\ +y_{n-1}&=\beta_0x_{n-1,0}+\beta_1x_{n-1,2}+\beta_2x_{n-1,2}+\dots+\beta_{n-1}x_{n-1,n-1}+\epsilon_{n-1}.\\ \end{align*} $$

     
    + +

    +As we noted above, we stayed with a system with the design matrix + \( \boldsymbol{X}\in {\mathbb{R}}^{n\times n} \), that is we have \( p=n \). For reasons to come later (algorithmic arguments) we will hereafter define +our matrix as \( \boldsymbol{X}\in {\mathbb{R}}^{n\times p} \), with the predictors refering to the column numbers and the entries \( n \) being the row elements. + +

    -

    Optimizing our parameters, more details

    +

    Our model for the nuclear binding energies

    + +

    +In our introductory notes we looked at the so-called liguid drop model. Let us remind ourselves about what we did by looking at the code. + +

    +We restate the parts of the code we are most interested in. +

    + + +

    # Common imports
    +import numpy as np
    +import pandas as pd
    +import matplotlib.pyplot as plt
    +from IPython.display import display
    +import os
    +
    +# Where to save the figures and data files
    +PROJECT_ROOT_DIR = "Results"
    +FIGURE_ID = "Results/FigureFiles"
    +DATA_ID = "DataFiles/"
    +
    +if not os.path.exists(PROJECT_ROOT_DIR):
    +    os.mkdir(PROJECT_ROOT_DIR)
    +
    +if not os.path.exists(FIGURE_ID):
    +    os.makedirs(FIGURE_ID)
    +
    +if not os.path.exists(DATA_ID):
    +    os.makedirs(DATA_ID)
    +
    +def image_path(fig_id):
    +    return os.path.join(FIGURE_ID, fig_id)
    +
    +def data_path(dat_id):
    +    return os.path.join(DATA_ID, dat_id)
    +
    +def save_fig(fig_id):
    +    plt.savefig(image_path(fig_id) + ".png", format='png')
    +
    +infile = open(data_path("MassEval2016.dat"),'r')
    +
    +
    +# Read the experimental data with Pandas
    +Masses = pd.read_fwf(infile, usecols=(2,3,4,6,11),
    +              names=('N', 'Z', 'A', 'Element', 'Ebinding'),
    +              widths=(1,3,5,5,5,1,3,4,1,13,11,11,9,1,2,11,9,1,3,1,12,11,1),
    +              header=39,
    +              index_col=False)
    +
    +# Extrapolated values are indicated by '#' in place of the decimal place, so
    +# the Ebinding column won't be numeric. Coerce to float and drop these entries.
    +Masses['Ebinding'] = pd.to_numeric(Masses['Ebinding'], errors='coerce')
    +Masses = Masses.dropna()
    +# Convert from keV to MeV.
    +Masses['Ebinding'] /= 1000
    +
    +# Group the DataFrame by nucleon number, A.
    +Masses = Masses.groupby('A')
    +# Find the rows of the grouped DataFrame with the maximum binding energy.
    +Masses = Masses.apply(lambda t: t[t.Ebinding==t.Ebinding.max()])
    +A = Masses['A']
    +Z = Masses['Z']
    +N = Masses['N']
    +Element = Masses['Element']
    +Energies = Masses['Ebinding']
    +
    +# Now we set up the design matrix X
    +X = np.zeros((len(A),5))
    +X[:,0] = 1
    +X[:,1] = A
    +X[:,2] = A**(2.0/3.0)
    +X[:,3] = A**(-1.0/3.0)
    +X[:,4] = A**(-1.0)
    +# Then nice printout using pandas
    +DesignMatrix = pd.DataFrame(X)
    +DesignMatrix.index = A
    +DesignMatrix.columns = ['1', 'A', 'A^(2/3)', 'A^(-1/3)', '1/A']
    +display(DesignMatrix)
    +
    +

    +With \( \boldsymbol{\beta}\in {\mathbb{R}}^{p\times 1} \), it means that we will hereafter write our equations for the approximation as +

     
    +$$ +\boldsymbol{\tilde{y}}= \boldsymbol{X}\boldsymbol{\beta}, +$$ +

     
    + +throughout these lectures. +

    + + +
    +

    Optimizing our parameters, more details

    -We well use this matrix to define the approximation \( \hat{\tilde{y}} \) via the unknown quantity \( \hat{\beta} \) as +With the above we use the design matrix to define the approximation \( \boldsymbol{\tilde{y}} \) via the unknown quantity \( \boldsymbol{\beta} \) as

     
    $$ -\hat{\tilde{y}}= \hat{X}\hat{\beta}, +\boldsymbol{\tilde{y}}= \boldsymbol{X}\boldsymbol{\beta}, $$

     
    -and in order to find the optimal parameters \( \beta_i \) instead of solving the above linear algebra problem, we define a function which gives a measure of the spread between the values \( y_i \) (which represent hopefully the exact values) and the parametrized values \( \tilde{y}_i \), namely +and in order to find the optimal parameters \( \beta_i \) instead of solving the above linear algebra problem, we define a function which gives a measure of the spread between the values \( y_i \) (which represent hopefully the exact values) and the parameterized values \( \tilde{y}_i \), namely

     
    $$ -Q(\hat{\beta})=\sum_{i=0}^{n-1}\left(y_i-\tilde{y}_i\right)^2=\left(\hat{y}-\hat{\tilde{y}}\right)^T\left(\hat{y}-\hat{\tilde{y}}\right), +C(\boldsymbol{\beta})=\frac{1}{n}\sum_{i=0}^{n-1}\left(y_i-\tilde{y}_i\right)^2=\frac{1}{n}\left\{\left(\boldsymbol{y}-\boldsymbol{\tilde{y}}\right)^T\left(\boldsymbol{y}-\boldsymbol{\tilde{y}}\right)\right\}, $$

     
    -or using the matrix \( \hat{X} \) as +or using the matrix \( \boldsymbol{X} \) and in a more compact matrix-vector notation as

     
    $$ -Q(\hat{\beta})=\left(\hat{y}-\hat{X}\hat{\beta}\right)^T\left(\hat{y}-\hat{X}\hat{\beta}\right). +C(\boldsymbol{\beta})=\frac{1}{n}\left\{\left(\boldsymbol{y}-\boldsymbol{X}^T\boldsymbol{\beta}\right)^T\left(\boldsymbol{y}-\boldsymbol{X}^T\boldsymbol{\beta}\right)\right\}. $$

     
    + +This function is one possible way to define the so-called cost function. + +

    +It is also common to define +the function \( Q \) as + +

     
    +$$ +C(\boldsymbol{\beta})=\frac{1}{2n}\sum_{i=0}^{n-1}\left(y_i-\tilde{y}_i\right)^2, +$$ +

     
    + +since when taking the first derivative with respect to the unknown parameters \( \beta \), the factor of \( 2 \) cancels out.

    -

    Interpretations and optimizing our parameters

    +

    Interpretations and optimizing our parameters

    The function

     
    $$ -Q(\hat{\beta})=\left(\hat{y}-\hat{X}\hat{\beta}\right)^T\left(\hat{y}-\hat{X}\hat{\beta}\right), +C(\boldsymbol{\beta})=\frac{1}{n}\left\{\left(\boldsymbol{y}-\boldsymbol{X}\boldsymbol{\beta}\right)^T\left(\boldsymbol{y}-\boldsymbol{X}\boldsymbol{\beta}\right)\right\}, $$

     
    -can be linked to the variance of the quantity \( y_i \) if we interpret the latter as the mean value of for example a numerical experiment. When linking below with the maximum likelihood approach below, we will indeed interpret \( y_i \) as a mean value +can be linked to the variance of the quantity \( y_i \) if we interpret the latter as the mean value. +When linking below with the maximum likelihood approach below, we will indeed interpret \( y_i \) as a mean value (see exercises)

     
    $$ y_{i}=\langle y_i \rangle = \beta_0x_{i,0}+\beta_1x_{i,1}+\beta_2x_{i,2}+\dots+\beta_{n-1}x_{i,n-1}+\epsilon_i, $$

     
    -where \( \langle y_i \rangle \) is the mean value. Keep in mind also that till now we have treated \( y_i \) as the exact value. Normally, the response (dependent or outcome) variable \( y_i \) the outcome of a numerical experiment or another type of experiment and is thus only an approximation to the true value. It is then always accompanied by an error estimate, often limited to a statistical error estimate given by the standard deviation discussed earlier. In the discussion here we will treat \( y_i \) as our exact value for the response variable. +

    +where \( \langle y_i \rangle \) is the mean value. Keep in mind also that +till now we have treated \( y_i \) as the exact value. Normally, the +response (dependent or outcome) variable \( y_i \) the outcome of a +numerical experiment or another type of experiment and is thus only an +approximation to the true value. It is then always accompanied by an +error estimate, often limited to a statistical error estimate given by +the standard deviation discussed earlier. In the discussion here we +will treat \( y_i \) as our exact value for the response variable.

    -In order to find the parameters \( \beta_i \) we will then minimize the spread of \( Q(\hat{\beta}) \) by requiring +In order to find the parameters \( \beta_i \) we will then minimize the spread of \( C(\boldsymbol{\beta}) \), that is we are going to solve the problem

     
    $$ -\frac{\partial Q(\hat{\beta})}{\partial \beta_j} = \frac{\partial }{\partial \beta_j}\left[ \sum_{i=0}^{n-1}\left(y_i-\beta_0x_{i,0}-\beta_1x_{i,1}-\beta_2x_{i,2}-\dots-\beta_{n-1}x_{i,n-1}\right)^2\right]=0, +{\displaystyle \min_{\boldsymbol{\beta}\in +{\mathbb{R}}^{p}}}\frac{1}{n}\left\{\left(\boldsymbol{y}-\boldsymbol{X}\boldsymbol{\beta}\right)^T\left(\boldsymbol{y}-\boldsymbol{X}\boldsymbol{\beta}\right)\right\}. +$$ +

     
    + +In practical terms it means we will require +

     
    +$$ +\frac{\partial C(\boldsymbol{\beta})}{\partial \beta_j} = \frac{\partial }{\partial \beta_j}\left[ \frac{1}{n}\sum_{i=0}^{n-1}\left(y_i-\beta_0x_{i,0}-\beta_1x_{i,1}-\beta_2x_{i,2}-\dots-\beta_{n-1}x_{i,n-1}\right)^2\right]=0, $$

     
    which results in

     
    $$ -\frac{\partial Q(\hat{\beta})}{\partial \beta_j} = -2\left[ \sum_{i=0}^{n-1}x_{ij}\left(y_i-\beta_0x_{i,0}-\beta_1x_{i,1}-\beta_2x_{i,2}-\dots-\beta_{n-1}x_{i,n-1}\right)\right]=0, +\frac{\partial C(\boldsymbol{\beta})}{\partial \beta_j} = -\frac{2}{n}\left[ \sum_{i=0}^{n-1}x_{ij}\left(y_i-\beta_0x_{i,0}-\beta_1x_{i,1}-\beta_2x_{i,2}-\dots-\beta_{n-1}x_{i,n-1}\right)\right]=0, $$

     
    or in a matrix-vector form as

     
    $$ -\frac{\partial Q(\hat{\beta})}{\partial \hat{\beta}} = 0 = \hat{X}^T\left( \hat{y}-\hat{X}\hat{\beta}\right). +\frac{\partial C(\boldsymbol{\beta})}{\partial \boldsymbol{\beta}} = 0 = \boldsymbol{X}^T\left( \boldsymbol{y}-\boldsymbol{X}\boldsymbol{\beta}\right). $$

     
    @@ -458,63 +654,194 @@ $$

    -

    Interpretations and optimizing our parameters

    +

    Interpretations and optimizing our parameters

    We can rewrite

     
    $$ -\frac{\partial Q(\hat{\beta})}{\partial \hat{\beta}} = 0 = \hat{X}^T\left( \hat{y}-\hat{X}\hat{\beta}\right), +\frac{\partial C(\boldsymbol{\beta})}{\partial \boldsymbol{\beta}} = 0 = \boldsymbol{X}^T\left( \boldsymbol{y}-\boldsymbol{X}\boldsymbol{\beta}\right), $$

     
    as

     
    $$ -\hat{X}^T\hat{y} = \hat{X}^T\hat{X}\hat{\beta}, +\boldsymbol{X}^T\boldsymbol{y} = \boldsymbol{X}^T\boldsymbol{X}\boldsymbol{\beta}, $$

     
    -and if the matrix \( \hat{X}^T\hat{X} \) is invertible we have the solution +and if the matrix \( \boldsymbol{X}^T\boldsymbol{X} \) is invertible we have the solution

     
    $$ -\hat{\beta} =\left(\hat{X}^T\hat{X}\right)^{-1}\hat{X}^T\hat{y}. +\boldsymbol{\beta} =\left(\boldsymbol{X}^T\boldsymbol{X}\right)^{-1}\boldsymbol{X}^T\boldsymbol{y}. $$

     
    +

    +We note also that since our design matrix is defined as \( \boldsymbol{X}\in +{\mathbb{R}}^{n\times p} \), the product \( \boldsymbol{X}^T\boldsymbol{X} \in +{\mathbb{R}}^{p\times p} \). In the above case we have that \( p \ll n \), +in our case \( p=5 \) meaning that we end up with inverting a small +\( 5\times 5 \) matrix. This is a rather common situation, in many cases we end up with low-dimensional +matrices to invert. The methods discussed here and for many other +supervised learning algorithms like classification with logistic +regression or support vector machines, exhibit dimensionalities which +allow for the usage of direct linear algebra methods such as LU decomposition or Singular Value Decomposition (SVD) for finding the inverse of the matrix +\( \boldsymbol{X}^T\boldsymbol{X} \). +

    -

    Interpretations and optimizing our parameters

    +

    Interpretations and optimizing our parameters

    -The residuals \( \hat{\epsilon} \) are in turn given by +The residuals \( \boldsymbol{\epsilon} \) are in turn given by

     
    $$ -\hat{\epsilon} = \hat{y}-\hat{\tilde{y}} = \hat{y}-\hat{X}\hat{\beta}, +\boldsymbol{\epsilon} = \boldsymbol{y}-\boldsymbol{\tilde{y}} = \boldsymbol{y}-\boldsymbol{X}\boldsymbol{\beta}, $$

     
    and with

     
    $$ -\hat{X}^T\left( \hat{y}-\hat{X}\hat{\beta}\right)= 0, +\boldsymbol{X}^T\left( \boldsymbol{y}-\boldsymbol{X}\boldsymbol{\beta}\right)= 0, $$

     
    we have

     
    $$ -\hat{X}^T\hat{\epsilon}=\hat{X}^T\left( \hat{y}-\hat{X}\hat{\beta}\right)= 0, +\boldsymbol{X}^T\boldsymbol{\epsilon}=\boldsymbol{X}^T\left( \boldsymbol{y}-\boldsymbol{X}\boldsymbol{\beta}\right)= 0, $$

     
    -meaning that the solution for \( \hat{\beta} \) is the one which minimizes the residuals. Later we will link this with the maximum likelihood approach. +meaning that the solution for \( \boldsymbol{\beta} \) is the one which minimizes the residuals. Later we will link this with the maximum likelihood approach. + + +

    + +

    +Let us now return to our nuclear binding energies and simply code the above equations. +

    + + +
    +

    Own code for Ordinary Least Squares

    + +

    +It is rather straightforward to implement the matrix inversion and obtain the parameters \( \boldsymbol{\beta} \). After having defined the matrix \( \boldsymbol{X} \) we simply need to +write +

    + + +

    # matrix inversion to find beta
    +beta = np.linalg.inv(X.T.dot(X)).dot(X.T).dot(Energies)
    +# and then make the prediction
    +ytilde = X @ beta
    +
    +

    +Alternatively, you can use the least squares functionality in Numpy as +

    + + +

    fit = np.linalg.lstsq(X, Energies, rcond =None)[0]
    +ytildenp = np.dot(fit,X.T)
    +
    +

    +And finally we plot our fit with and compare with data +

    + + +

    Masses['Eapprox']  = ytilde
    +# Generate a plot comparing the experimental with the fitted values values.
    +fig, ax = plt.subplots()
    +ax.set_xlabel(r'$A = N + Z$')
    +ax.set_ylabel(r'$E_\mathrm{bind}\,/\mathrm{MeV}$')
    +ax.plot(Masses['A'], Masses['Ebinding'], alpha=0.7, lw=2,
    +            label='Ame2016')
    +ax.plot(Masses['A'], Masses['Eapprox'], alpha=0.7, lw=2, c='m',
    +            label='Fit')
    +ax.legend()
    +save_fig("Masses2016OLS")
    +plt.show()
    +
    +
    + + +
    +

    Adding error analysis and training set up

    + +

    +We can easily test our fit by computing the \( R2 \) score that we discussed in connection with the functionality of _Scikit_Learn_ in the introductory slides. +Since we are not using _Scikit-Learn here we can define our own \( R2 \) function as +

    + + +

    def R2(y_data, y_model):
    +    return 1 - np.sum((y_data - y_model) ** 2) / np.sum((y_data - np.mean(y_model)) ** 2)
    +
    +

    +and we would be using it as +

    + + +

    print(R2(Energies,ytilde))
    +
    +

    +We can easily add our MSE score as +

    + + +

    def MSE(y_data,y_model):
    +    n = np.size(y_model)
    +    return np.sum((y_data-y_model)**2)/n
    +
    +print(MSE(Energies,ytilde))
    +
    +

    +and finally the relative error as +

    + + +

    def RelativeError(y_data,y_model):
    +    return abs((y_data-y_model)/y_data)
    +print(RelativeError(Energies, ytilde))
    +
    +
    + + +
    +

    The \( \chi^2 \) function

    +
    + +

    +Normally, the response (dependent or outcome) variable \( y_i \) is the +outcome of a numerical experiment or another type of experiment and is +thus only an approximation to the true value. It is then always +accompanied by an error estimate, often limited to a statistical error +estimate given by the standard deviation discussed earlier. In the +discussion here we will treat \( y_i \) as our exact value for the +response variable. + +

    +Introducing the standard deviation \( \sigma_i \) for each measurement +\( y_i \), we define now the \( \chi^2 \) function (omitting the \( 1/n \) term) +as + +

     
    +$$ +\chi^2(\boldsymbol{\beta})=\frac{1}{n}\sum_{i=0}^{n-1}\frac{\left(y_i-\tilde{y}_i\right)^2}{\sigma_i^2}=\frac{1}{n}\left\{\left(\boldsymbol{y}-\boldsymbol{\tilde{y}}\right)^T\frac{1}{\boldsymbol{\Sigma^2}}\left(\boldsymbol{y}-\boldsymbol{\tilde{y}}\right)\right\}, +$$ +

     
    + +where the matrix \( \boldsymbol{\Sigma} \) is a diagonal matrix with \( \sigma_i \) as matrix elements.

    @@ -522,82 +849,59 @@ meaning that the solution for \( \hat{\beta} \) is the one which minimizes the r
    -

    The \( \chi^2 \) function

    +

    The \( \chi^2 \) function

    -Normally, the response (dependent or outcome) variable \( y_i \) the outcome of a numerical experiment or another type of experiment and is thus only an approximation to the true value. It is then always accompanied by an error estimate, often limited to a statistical error estimate given by the standard deviation discussed earlier. In the discussion here we will treat \( y_i \) as our exact value for the response variable. - -

    -Introducing the standard deviation \( \sigma_i \) for each measurement \( y_i \), we define now the \( \chi^2 \) function as - +In order to find the parameters \( \beta_i \) we will then minimize the spread of \( \chi^2(\boldsymbol{\beta}) \) by requiring

     
    $$ -\chi^2(\hat{\beta})=\sum_{i=0}^{n-1}\frac{\left(y_i-\tilde{y}_i\right)^2}{\sigma_i^2}=\left(\hat{y}-\hat{\tilde{y}}\right)^T\frac{1}{\hat{\Sigma^2}}\left(\hat{y}-\hat{\tilde{y}}\right), -$$ -

     
    - -where the matrix \( \hat{\Sigma} \) is a diagonal matrix with \( \sigma_i \) as matrix elements. - - -

    -
    - - -
    -

    The \( \chi^2 \) function

    -
    - -

    -In order to find the parameters \( \beta_i \) we will then minimize the spread of \( \chi^2(\hat{\beta}) \) by requiring -

     
    -$$ -\frac{\partial \chi^2(\hat{\beta})}{\partial \beta_j} = \frac{\partial }{\partial \beta_j}\left[ \sum_{i=0}^{n-1}\left(\frac{y_i-\beta_0x_{i,0}-\beta_1x_{i,1}-\beta_2x_{i,2}-\dots-\beta_{n-1}x_{i,n-1}}{\sigma_i}\right)^2\right]=0, +\frac{\partial \chi^2(\boldsymbol{\beta})}{\partial \beta_j} = \frac{\partial }{\partial \beta_j}\left[ \frac{1}{n}\sum_{i=0}^{n-1}\left(\frac{y_i-\beta_0x_{i,0}-\beta_1x_{i,1}-\beta_2x_{i,2}-\dots-\beta_{n-1}x_{i,n-1}}{\sigma_i}\right)^2\right]=0, $$

     
    which results in

     
    $$ -\frac{\partial \chi^2(\hat{\beta})}{\partial \beta_j} = -2\left[ \sum_{i=0}^{n-1}\frac{x_{ij}}{\sigma_i}\left(\frac{y_i-\beta_0x_{i,0}-\beta_1x_{i,1}-\beta_2x_{i,2}-\dots-\beta_{n-1}x_{i,n-1}}{\sigma_i}\right)\right]=0, +\frac{\partial \chi^2(\boldsymbol{\beta})}{\partial \beta_j} = -\frac{2}{n}\left[ \sum_{i=0}^{n-1}\frac{x_{ij}}{\sigma_i}\left(\frac{y_i-\beta_0x_{i,0}-\beta_1x_{i,1}-\beta_2x_{i,2}-\dots-\beta_{n-1}x_{i,n-1}}{\sigma_i}\right)\right]=0, $$

     
    or in a matrix-vector form as

     
    $$ -\frac{\partial \chi^2(\hat{\beta})}{\partial \hat{\beta}} = 0 = \hat{A}^T\left( \hat{b}-\hat{A}\hat{\beta}\right). +\frac{\partial \chi^2(\boldsymbol{\beta})}{\partial \boldsymbol{\beta}} = 0 = \boldsymbol{A}^T\left( \boldsymbol{b}-\boldsymbol{A}\boldsymbol{\beta}\right). $$

     
    -where we have defined the matrix \( \hat{A} =\hat{X}/\hat{\Sigma} \) with matrix elements \( a_{ij} = x_{ij}/\sigma_i \) and the vector \( \hat{b} \) with elements \( b_i = y_i/\sigma_i \). +where we have defined the matrix \( \boldsymbol{A} =\boldsymbol{X}/\boldsymbol{\Sigma} \) with matrix elements \( a_{ij} = x_{ij}/\sigma_i \) and the vector \( \boldsymbol{b} \) with elements \( b_i = y_i/\sigma_i \).

    -

    The \( \chi^2 \) function

    +

    The \( \chi^2 \) function

    We can rewrite

     
    $$ -\frac{\partial \chi^2(\hat{\beta})}{\partial \hat{\beta}} = 0 = \hat{A}^T\left( \hat{b}-\hat{A}\hat{\beta}\right), +\frac{\partial \chi^2(\boldsymbol{\beta})}{\partial \boldsymbol{\beta}} = 0 = \boldsymbol{A}^T\left( \boldsymbol{b}-\boldsymbol{A}\boldsymbol{\beta}\right), $$

     
    as

     
    $$ -\hat{A}^T\hat{b} = \hat{A}^T\hat{A}\hat{\beta}, +\boldsymbol{A}^T\boldsymbol{b} = \boldsymbol{A}^T\boldsymbol{A}\boldsymbol{\beta}, $$

     
    -and if the matrix \( \hat{A}^T\hat{A} \) is invertible we have the solution +and if the matrix \( \boldsymbol{A}^T\boldsymbol{A} \) is invertible we have the solution

     
    $$ -\hat{\beta} =\left(\hat{A}^T\hat{A}\right)^{-1}\hat{A}^T\hat{b}. +\boldsymbol{\beta} =\left(\boldsymbol{A}^T\boldsymbol{A}\right)^{-1}\boldsymbol{A}^T\boldsymbol{b}. $$

     

    @@ -605,18 +909,18 @@ $$
    -

    The \( \chi^2 \) function

    +

    The \( \chi^2 \) function

    If we then introduce the matrix

     
    $$ -\hat{H} = \left(\hat{A}^T\hat{A}\right)^{-1}, +\boldsymbol{H} = \left(\boldsymbol{A}^T\boldsymbol{A}\right)^{-1}, $$

     
    -we have then the following expression for the parameters \( \beta_j \) (the matrix elements of \( \hat{H} \) are \( h_{ij} \)) +we have then the following expression for the parameters \( \beta_j \) (the matrix elements of \( \boldsymbol{H} \) are \( h_{ij} \))

     
    $$ \beta_j = \sum_{k=0}^{p-1}h_{jk}\sum_{i=0}^{n-1}\frac{y_i}{\sigma_i}\frac{x_{ik}}{\sigma_i} = \sum_{k=0}^{p-1}h_{jk}\sum_{i=0}^{n-1}b_ia_{ik} @@ -641,7 +945,7 @@ $$

    -

    The \( \chi^2 \) function

    +

    The \( \chi^2 \) function

    @@ -655,14 +959,14 @@ $$ By computing the derivatives of \( \chi^2 \) with respect to \( \beta_0 \) and \( \beta_1 \) show that these are given by

     
    $$ -\frac{\partial \chi^2(\hat{\beta})}{\partial \beta_0} = -2\left[ \sum_{i=0}^{n-1}\left(\frac{y_i-\beta_0-\beta_1x_{i}}{\sigma_i^2}\right)\right]=0, +\frac{\partial \chi^2(\boldsymbol{\beta})}{\partial \beta_0} = -2\left[ \frac{1}{n}\sum_{i=0}^{n-1}\left(\frac{y_i-\beta_0-\beta_1x_{i}}{\sigma_i^2}\right)\right]=0, $$

     
    and

     
    $$ -\frac{\partial \chi^2(\hat{\beta})}{\partial \beta_0} = -2\left[ \sum_{i=0}^{n-1}x_i\left(\frac{y_i-\beta_0-\beta_1x_{i}}{\sigma_i^2}\right)\right]=0. +\frac{\partial \chi^2(\boldsymbol{\beta})}{\partial \beta_1} = -\frac{2}{n}\left[ \sum_{i=0}^{n-1}x_i\left(\frac{y_i-\beta_0-\beta_1x_{i}}{\sigma_i^2}\right)\right]=0. $$

     

    @@ -670,11 +974,11 @@ $$
    -

    The \( \chi^2 \) function

    +

    The \( \chi^2 \) function

    -For a linear fit we don't need to invert a matrix!! +For a linear fit (a first-order polynomial) we don't need to invert a matrix!! Defining

     
    $$ @@ -706,7 +1010,9 @@ $$ $$

     
    +

    we obtain +

     
    $$ \beta_0 = \frac{\gamma_{xx}\gamma_y-\gamma_x\gamma_y}{\gamma\gamma_{xx}-\gamma_x^2}, @@ -720,574 +1026,528 @@ $$

     

    -This approach (different linear and non-linear regression) suffers often from both being underdetermined and overdetermined in the unknown coefficients \( \beta_i \). A better approach is to use the Singular Value Decomposition (SVD) method discussed below. Or using Lasso and Ridge regression. See below. +This approach (different linear and non-linear regression) suffers +often from both being underdetermined and overdetermined in the +unknown coefficients \( \beta_i \). A better approach is to use the +Singular Value Decomposition (SVD) method discussed below. Or using +Lasso and Ridge regression. See below. + +

    -

    Simple regression model

    -We are now ready to write our first program which aims at solving the above linear regression equations. We start with data we have produced ourselves, in this case normally distributed random numbers along the \( x \)-axis. These numbers define then the value of a function \( y(x)=4+3x+N(0,1) \). Thereafter we order the \( x \) values and employ our linear regression algorithm to set up the best fit. Here we find it useful to use the numpy function \( c\_ \) arrays where arrays are stacked along their last axis after being upgraded to at least two dimensions with ones post-pended to the shape. The following examples help in understanding what happens +

    Fitting an Equation of State for Dense Nuclear Matter

    + +

    +Before we continue, let us introduce yet another example. We are going to fit the +nuclear equation of state using results from many-body calculations. +The equation of state we have made available here, as function of +density, has been derived using modern nucleon-nucleon potentials with +the addition of three-body +forces. This +time the file is presented as a standard csv file. + +

    +The beginning of the Python code here is similar to what you have seen before, +with the same initializations and declarations. We use also pandas +again, rather extensively in order to organize our data. + +

    +The difference now is that we use Scikit-Learn's regression tools +instead of our own matrix inversion implementation. Furthermore, we +sneak in Ridge regression (to be discussed below) which includes a +hyperparameter \( \lambda \), also to be explained below. +

    + + +
    +

    The code

    +

    -

    import numpy as np
    -print(np.c_[np.array([1,2,3]), np.array([4,5,6])])
    -print(np.c_[np.array([[1,2,3]]), 0, 0, np.array([[4,5,6]])])
    -
    -

    - - -

    # Importing various packages
    -from random import random, seed
    +
    # Common imports
    +import os
     import numpy as np
    +import pandas as pd
     import matplotlib.pyplot as plt
    -
    -x = 2*np.random.rand(100,1)
    -y = 4+3*x+np.random.randn(100,1)
    -
    -xb = np.c_[np.ones((100,1)), x]
    -beta = np.linalg.inv(xb.T.dot(xb)).dot(xb.T).dot(y)
    -xnew = np.array([[0],[2]])
    -xbnew = np.c_[np.ones((2,1)), xnew]
    -ypredict = xbnew.dot(beta)
    -
    -plt.plot(xnew, ypredict, "r-")
    -plt.plot(x, y ,'ro')
    -plt.axis([0,2.0,0, 15.0])
    -plt.xlabel(r'$x$')
    -plt.ylabel(r'$y$')
    -plt.title(r'Linear Regression')
    -plt.show()
    -
    -

    -We see that, as expected, a linear fit gives a seemingly (from the graph) good representation of the data. -

    - - -
    -

    Simple regression model, now using scikit-learn

    - -

    -We can repeat the above algorithm using scikit-learn as follows -

    - - -

    # Importing various packages
    -from random import random, seed
    -import numpy as np
     import matplotlib.pyplot as plt
    -from sklearn.linear_model import LinearRegression
    +import sklearn.linear_model as skl
    +from sklearn.metrics import mean_squared_error, r2_score, mean_absolute_error
     
    -x = 2*np.random.rand(100,1)
    -y = 4+3*x+np.random.randn(100,1)
    -linreg = LinearRegression()
    -linreg.fit(x,y)
    -xnew = np.array([[0],[2]])
    -ypredict = linreg.predict(xnew)
    +# Where to save the figures and data files
    +PROJECT_ROOT_DIR = "Results"
    +FIGURE_ID = "Results/FigureFiles"
    +DATA_ID = "DataFiles/"
     
    -plt.plot(xnew, ypredict, "r-")
    -plt.plot(x, y ,'ro')
    -plt.axis([0,2.0,0, 15.0])
    -plt.xlabel(r'$x$')
    -plt.ylabel(r'$y$')
    -plt.title(r'Random numbers ')
    -plt.show()
    -
    -
    +if not os.path.exists(PROJECT_ROOT_DIR): + os.mkdir(PROJECT_ROOT_DIR) +if not os.path.exists(FIGURE_ID): + os.makedirs(FIGURE_ID) -
    -

    Simple linear regression model using scikit-learn

    +if not os.path.exists(DATA_ID): + os.makedirs(DATA_ID) -

    -We start with perhaps our simplest possible example, using scikit-learn to perform linear regression analysis on a data set produced by us. -What follows is a simple Python code where we have defined function \( y \) in terms of the variable \( x \). Both are defined as vectors of dimension \( 1\times 100 \). The entries to the vector \( \hat{x} \) are given by random numbers generated with a uniform distribution with entries \( x_i \in [0,1] \) (more about probability distribution functions later). These values are then used to define a function \( y(x) \) (tabulated again as a vector) with a linear dependence on \( x \) plus a random noise added via the normal distribution. +def image_path(fig_id): + return os.path.join(FIGURE_ID, fig_id) -

    -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 \) +def data_path(dat_id): + return os.path.join(DATA_ID, dat_id) -

     
    -$$ -y = 2x+N(0,1), -$$ -

     
    +def save_fig(fig_id): + plt.savefig(image_path(fig_id) + ".png", format='png') -

    -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. +infile = open(data_path("EoS.csv"),'r') -

    -For plotting we use the Python package -matplotlib which produces publication -quality figures. Feel free to explore the extensive -gallery 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. +# Read the EoS data as csv file and organize the data into two arrays with density and energies +EoS = pd.read_csv(infile, names=('Density', 'Energy')) +EoS['Energy'] = pd.to_numeric(EoS['Energy'], errors='coerce') +EoS = EoS.dropna() +Energies = EoS['Energy'] +Density = EoS['Density'] +# The design matrix now as function of various polytrops +X = np.zeros((len(Density),4)) +X[:,3] = Density**(4.0/3.0) +X[:,2] = Density +X[:,1] = Density**(2.0/3.0) +X[:,0] = 1 -

    -The Python code follows here. -

    - - -

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

    Simple linear regression model

    - -

    -This example serves several aims. It allows us to demonstrate several -aspects of data analysis and later machine learning algorithms. The -immediate visualization shows that our linear fit is not -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 - -

     
    -$$ -y = 10x+0.01 \times N(0,1), -$$ -

     
    - -

    -where \( x \) is defined as before. -

    - - -
    -

    Less noise

    - -

    -Does the fit look better? Indeed, by -reducing the role of the normal distribution we see immediately that -our linear prediction seemingly reproduces better the training -set. However, this testing 'by the eye' is obviouly not satisfactory in the -long run. Here we have only defined the training data and our model, and -have not discussed a more rigorous approach to the cost function. -

    - - -
    -

    How to study our fits

    - -

    -We need more rigorous criteria in defining whether we have succeeded or -not in modeling our training data. You will be surprised to see that -many scientists seldomly venture beyond this 'by the eye' approach. A -standard approach for the cost function is the so-called \( \chi^2 \) -function - -

     
    -$$ \chi^2 = \frac{1}{n} -\sum_{i=0}^{n-1}\frac{(y_i-\tilde{y}_i)^2}{\sigma_i^2}, -$$ -

     
    - -

    -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

    - -

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

    - - -
    -

    Relative error

    - -

    -There are many ways to define the cost function. A simpler approach is to look at the relative difference between the training data and the predicted data, that is we define -the relative error as - -

     
    -$$ -\epsilon_{\mathrm{relative}}= \frac{\vert \hat{y} -\hat{\tilde{y}}\vert}{\vert \hat{y}\vert}. -$$ -

     
    - -We can modify easily the above Python code and plot the relative error instead -

    - - -

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

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

    - - -
    -

    The richness of scikit-learn

    - -

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

    - - -

    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_)
    +# We use now Scikit-Learn's linear regressor and ridge regressor
    +# OLS part
    +clf = skl.LinearRegression().fit(X, Energies)
    +ytilde = clf.predict(X)
    +EoS['Eols']  = ytilde
     # The mean squared error                               
    -print("Mean squared error: %.2f" % mean_squared_error(y, ypredict))
    +print("Mean squared error: %.2f" % mean_squared_error(Energies, ytilde))
     # 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) )
    +print('Variance score: %.2f' % r2_score(Energies, ytilde))
     # 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 ')
    +print('Mean absolute error: %.2f' % mean_absolute_error(Energies, ytilde))
    +print(clf.coef_, clf.intercept_)
    +
    +# The Ridge regression with a hyperparameter lambda = 0.1
    +_lambda = 0.1
    +clf_ridge = skl.Ridge(alpha=_lambda).fit(X, Energies)
    +yridge = clf_ridge.predict(X)
    +EoS['Eridge']  = yridge
    +# The mean squared error                               
    +print("Mean squared error: %.2f" % mean_squared_error(Energies, yridge))
    +# Explained variance score: 1 is perfect prediction                                 
    +print('Variance score: %.2f' % r2_score(Energies, yridge))
    +# Mean absolute error                                                           
    +print('Mean absolute error: %.2f' % mean_absolute_error(Energies, yridge))
    +print(clf_ridge.coef_, clf_ridge.intercept_)
    +
    +fig, ax = plt.subplots()
    +ax.set_xlabel(r'$\rho[\mathrm{fm}^{-3}]$')
    +ax.set_ylabel(r'Energy per particle')
    +ax.plot(EoS['Density'], EoS['Energy'], alpha=0.7, lw=2,
    +            label='Theoretical data')
    +ax.plot(EoS['Density'], EoS['Eols'], alpha=0.7, lw=2, c='m',
    +            label='OLS')
    +ax.plot(EoS['Density'], EoS['Eridge'], alpha=0.7, lw=2, c='g',
    +            label='Ridge $\lambda = 0.1$')
    +ax.legend()
    +save_fig("EoSfitting")
     plt.show()
     
    +

    +The above simple polynomial in density \( \rho \) gives an excellent fit +to the data. Can you give an interpretation of the various powers of \( \rho \)? + +

    +We note also that there is a small deviation between the +standard OLS and the Ridge regression at higher densities. We discuss this in more detail +below.

    -

    Functions in scikit-learn

    +

    Splitting our Data in Training and Test data

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

     
    -$$ MSE(\hat{y},\hat{\tilde{y}}) = \frac{1}{n} -\sum_{i=0}^{n-1}(y_i-\tilde{y}_i)^2, -$$ -

     
    - -

    -The smaller the value, the better the fit. Ideally we would like to -have an MSE equal zero. The attentive reader has probably recognized -this function as being similar to the \( \chi^2 \) function defined above. -

    - - -
    -

    Other functions in scikit-learn

    - -

    -The r2score function computes \( R^2 \), the coefficient of -determination. It provides a measure of how well future samples are -likely to be predicted by the model. Best possible score is 1.0 and it -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 -

     
    -$$ -R^2(\hat{y}, \tilde{\hat{y}}) = 1 - \frac{\sum_{i=0}^{n - 1} (y_i - \tilde{y}_i)^2}{\sum_{i=0}^{n - 1} (y_i - \bar{y})^2}, -$$ -

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

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

     
    -

    - - -
    -

    The mean absolute error and other functions in scikit-learn

    - -

    -Another quantity will meet again in our discussions of regression analysis is - mean absolute error (MAE), a risk metric corresponding to the expected value of the absolute error loss or what we call the \( l1 \)-norm loss. In our discussion above we presented the relative error. -The MAE is defined as follows -

     
    -$$ -\text{MAE}(\hat{y}, \hat{\tilde{y}}) = \frac{1}{n} \sum_{i=0}^{n-1} \left| y_i - \tilde{y}_i \right|. -$$ -

     
    - -Finally we present the -squared logarithmic (quadratic) error -

     
    -$$ -\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, -$$ -

     
    - -

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

    - - -
    -

    Cubic polynomial in scikit-learn

    - -

    -We will discuss in more -detail these and other functions in the various lectures. We conclude this part with another example. Instead of -a linear \( x \)-dependence we study now a cubic polynomial and use the polynomial regression analysis tools of scikit-learn. -Add description of the various python commands. +It is normal in essentially all Machine Learning studies to split the +data in a training set and a test set (sometimes also an additional +validation set). Scikit-Learn has an own function for this. There +is no explicit recipe for how much data should be included as training +data and say test data. An accepted rule of thumb is to use +approximately \( 2/3 \) to \( 4/5 \) of the data as training data. We will +postpone a discussion of this splitting to the end of these notes and +our discussion of the so-called bias-variance tradeoff. Here we +limit ourselves to repeat the above equation of state fitting example +but now splitting the data into a training set and a test set.

    -

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

    -Using R, we can perform similar studies. -

    - - -
    -

    Polynomial Regression

    -

    - - -

    # Importing various packages
    -from math import exp, sqrt
    -from random import random, seed
    +
    import os
     import numpy as np
    +import pandas as pd
     import matplotlib.pyplot as plt
    +from sklearn.model_selection import train_test_split
    +# Where to save the figures and data files
    +PROJECT_ROOT_DIR = "Results"
    +FIGURE_ID = "Results/FigureFiles"
    +DATA_ID = "DataFiles/"
     
    -m = 100
    -x = 2*np.random.rand(m,1)+4.
    -y = 4+3*x*x+ +x-np.random.randn(m,1)
    +if not os.path.exists(PROJECT_ROOT_DIR):
    +    os.mkdir(PROJECT_ROOT_DIR)
     
    -xb = np.c_[np.ones((m,1)), x]
    -theta = np.linalg.inv(xb.T.dot(xb)).dot(xb.T).dot(y)
    -xnew = np.array([[0],[2]])
    -xbnew = np.c_[np.ones((2,1)), xnew]
    -ypredict = xbnew.dot(theta)
    +if not os.path.exists(FIGURE_ID):
    +    os.makedirs(FIGURE_ID)
     
    -plt.plot(xnew, ypredict, "r-")
    -plt.plot(x, y ,'ro')
    -plt.axis([0,2.0,0, 15.0])
    -plt.xlabel(r'$x$')
    -plt.ylabel(r'$y$')
    -plt.title(r'Random numbers ')
    -plt.show()
    +if not os.path.exists(DATA_ID):
    +    os.makedirs(DATA_ID)
    +
    +def image_path(fig_id):
    +    return os.path.join(FIGURE_ID, fig_id)
    +
    +def data_path(dat_id):
    +    return os.path.join(DATA_ID, dat_id)
    +
    +def save_fig(fig_id):
    +    plt.savefig(image_path(fig_id) + ".png", format='png')
    +
    +def R2(y_data, y_model):
    +    return 1 - np.sum((y_data - y_model) ** 2) / np.sum((y_data - np.mean(y_model)) ** 2)
    +def MSE(y_data,y_model):
    +    n = np.size(y_model)
    +    return np.sum((y_data-y_model)**2)/n
    +
    +infile = open(data_path("EoS.csv"),'r')
    +
    +# Read the EoS data as  csv file and organized into two arrays with density and energies
    +EoS = pd.read_csv(infile, names=('Density', 'Energy'))
    +EoS['Energy'] = pd.to_numeric(EoS['Energy'], errors='coerce')
    +EoS = EoS.dropna()
    +Energies = EoS['Energy']
    +Density = EoS['Density']
    +#  The design matrix now as function of various polytrops
    +X = np.zeros((len(Density),5))
    +X[:,0] = 1
    +X[:,1] = Density**(2.0/3.0)
    +X[:,2] = Density
    +X[:,3] = Density**(4.0/3.0)
    +X[:,4] = Density**(5.0/3.0)
    +# We split the data in test and training data
    +X_train, X_test, y_train, y_test = train_test_split(X, Energies, test_size=0.2)
    +# matrix inversion to find beta
    +beta = np.linalg.inv(X_train.T.dot(X_train)).dot(X_train.T).dot(y_train)
    +# and then make the prediction
    +ytilde = X_train @ beta
    +print("Training R2")
    +print(R2(y_train,ytilde))
    +print("Training MSE")
    +print(MSE(y_train,ytilde))
    +ypredict = X_test @ beta
    +print("Test R2")
    +print(R2(y_test,ypredict))
    +print("Test MSE")
    +print(MSE(y_test,ypredict))
     
    -

    Linking the regression analysis with a statistical interpretation

    +

    The singular value decomposition

    -Before we proceed, and to link with our discussions of Bayesian statistics to come, it is useful the derive the standard regression analysis equations using a statistical interpretation. This allows us also to derive quantities like the variance and other expectation values in a rather straightforward way. - -

    -It is assumed that \( \varepsilon_i -\sim \mathcal{N}(0, \sigma^2) \) and the \( \varepsilon_{i} \) are -independent, i.e.: -

     
    -$$ -\begin{align*} -\mbox{Cov}(\varepsilon_{i_1}, -\varepsilon_{i_2}) & = \left\{ \begin{array}{lcc} \sigma^2 & \mbox{if} -& i_1 = i_2, \\ 0 & \mbox{if} & i_1 \not= i_2. \end{array} \right. -\end{align*} -$$ -

     
    - -The randomness of \( \varepsilon_i \) implies that -\( \mathbf{Y}_i \) is also a random variable. In particular, -\( \mathbf{Y}_i \) is normally distributed, because \( \varepsilon_i \sim -\mathcal{N}(0, \sigma^2) \) and \( \mathbf{X}_{i,\ast} \, \beta \) is a -non-random scalar. To specify the parameters of the distribution of -\( \mathbf{Y}_i \) we need to calculate its first two moments. -

    - - -
    -

    Expectation value and variance

    - -

    -Its expectation equals: -

     
    -$$ -\begin{align*} -\mathbb{E}(Y_i) & = -\mathbb{E}(\mathbf{X}_{i, \ast} \, \beta) + \mathbb{E}(\varepsilon_i) -\, \, \, = \, \, \, \mathbf{X}_{i, \ast} \, \beta, -\end{align*} -$$ -

     
    - -while -its variance is -

     
    -$$ -\begin{align*} \mbox{Var}(Y_i) & = \mathbb{E} \{ [Y_i -- \mathbb{E}(Y_i)]^2 \} \, \, \, = \, \, \, \mathbb{E} ( Y_i^2 ) - -[\mathbb{E}(Y_i)]^2 \\ & = \mathbb{E} [ ( \mathbf{X}_{i, \ast} \, -\beta + \varepsilon_i )^2] - ( \mathbf{X}_{i, \ast} \, \beta)^2 \\ & -= \mathbb{E} [ ( \mathbf{X}_{i, \ast} \, \beta)^2 + 2 \varepsilon_i -\mathbf{X}_{i, \ast} \, \beta + \varepsilon_i^2 ] - ( \mathbf{X}_{i, -\ast} \, \beta)^2 \\ & = ( \mathbf{X}_{i, \ast} \, \beta)^2 + 2 -\mathbb{E}(\varepsilon_i) \mathbf{X}_{i, \ast} \, \beta + -\mathbb{E}(\varepsilon_i^2 ) - ( \mathbf{X}_{i, \ast} \, \beta)^2 -\\ & = \mathbb{E}(\varepsilon_i^2 ) \, \, \, = \, \, \, -\mbox{Var}(\varepsilon_i) \, \, \, = \, \, \, \sigma^2. -\end{align*} -$$ -

     
    - -Hence, \( Y_i \sim \mathcal{N}( \mathbf{X}_{i, \ast} \, \beta, \sigma^2) \). -

    - - -
    -

    The singular value decompostion

    -A general -\( m\times n \) matrix \( \hat{A} \) can be written in terms of a diagonal -matrix \( \hat{D} \) of dimensionality \( n\times n \) and two orthognal -matrices \( \hat{U} \) and \( \hat{V} \), where the first has dimensionality -\( m \times m \) and the last dimensionality \( n\times n \). -We have then -

     
    -$$ -\hat{A} = \hat{U}\hat{D}\hat{V}^T -$$ -

     
    +The examples we have looked at so far are cases where we normally can +invert the matrix \( \boldsymbol{X}^T\boldsymbol{X} \). Using a polynomial expansion as we +did both for the masses and the fitting of the equation of state, +leads to row vectors of the design matrix which are essentially +orthogonal due to the polynomial character of our model. This may +however not the be case in general and a standard matrix inversion +algorithm based on say LU decomposition may lead to singularities. We will see an example of this below when we try to fit +the coupling constant of the widely used Ising model. +There is however a way to partially circumvent this problem and also gain some insight about the ordinary least squares approach. + +

    +This is given by the Singular Value Decomposition algorithm, perhaps +the most powerful linear algebra algorithm. Let us look at a +different example where we may have problems with the standard matrix +inversion algorithm. Thereafter we dive into the math of the SVD. + +

    -

    From standard regression to Ridge regressions

    +

    The Ising model

    + +

    +The one-dimensional Ising model with nearest neighbor interaction, no +external field and a constant coupling constant \( J \) is given by + +

     
    +$$ +\begin{align} + H = -J \sum_{k}^L s_k s_{k + 1}, +\tag{1} +\end{align} +$$ +

     
    + +

    +where \( s_i \in \{-1, 1\} \) and \( s_{N + 1} = s_1 \). The number of spins +in the system is determined by \( L \). For the one-dimensional system +there is no phase transition. + +

    +We will look at a system of \( L = 40 \) spins with a coupling constant of +\( J = 1 \). To get enough training data we will generate 10000 states +with their respective energies. + +

    + + +

    import numpy as np
    +import matplotlib.pyplot as plt
    +from mpl_toolkits.axes_grid1 import make_axes_locatable
    +import seaborn as sns
    +import scipy.linalg as scl
    +from sklearn.model_selection import train_test_split
    +import tqdm
    +sns.set(color_codes=True)
    +cmap_args=dict(vmin=-1., vmax=1., cmap='seismic')
    +
    +L = 40
    +n = int(1e4)
    +
    +spins = np.random.choice([-1, 1], size=(n, L))
    +J = 1.0
    +
    +energies = np.zeros(n)
    +
    +for i in range(n):
    +    energies[i] = - J * np.dot(spins[i], np.roll(spins[i], 1))
    +
    +

    +Here we use ordinary least squares +regression to predict the energy for the nearest neighbor +one-dimensional Ising model on a ring, i.e., the endpoints wrap +around. We will use linear regression to fit a value for +the coupling constant to achieve this. +

    + + +
    +

    Reformulating the problem to suit regression

    + +

    +A more general form for the one-dimensional Ising model is + +

     
    +$$ +\begin{align} + H = - \sum_j^L \sum_k^L s_j s_k J_{jk}. +\tag{2} +\end{align} +$$ +

     
    + +

    +Here we allow for interactions beyond the nearest neighbors and a state dependent +coupling constant. This latter expression can be formulated as +a matrix-product +

     
    +$$ +\begin{align} + \boldsymbol{H} = \boldsymbol{X} J, +\tag{3} +\end{align} +$$ +

     
    + +

    +where \( X_{jk} = s_j s_k \) and \( J \) is a matrix which consists of the +elements \( -J_{jk} \). This form of writing the energy fits perfectly +with the form utilized in linear regression, that is + +

     
    +$$ +\begin{align} + \boldsymbol{y} = \boldsymbol{X}\boldsymbol{\beta} + \boldsymbol{\epsilon}, +\tag{4} +\end{align} +$$ +

     
    + +

    +We split the data in training and test data as discussed in the previous example + +

    + + +

    X = np.zeros((n, L ** 2))
    +for i in range(n):
    +    X[i] = np.outer(spins[i], spins[i]).ravel()
    +y = energies
    +X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2)
    +
    +
    + + +
    +

    Linear regression

    + +

    +In the ordinary least squares method we choose the cost function + +

     
    +$$ +\begin{align} + C(\boldsymbol{X}, \boldsymbol{\beta})= \frac{1}{n}\left\{(\boldsymbol{X}\boldsymbol{\beta} - \boldsymbol{y})^T(\boldsymbol{X}\boldsymbol{\beta} - \boldsymbol{y})\right\}. +\tag{5} +\end{align} +$$ +

     
    + +

    +We then find the extremal point of \( C \) by taking the derivative with respect to \( \boldsymbol{\beta} \) as discussed above. +This yields the expression for \( \boldsymbol{\beta} \) to be + +

     
    +$$ + \boldsymbol{\beta} = \frac{\boldsymbol{X}^T \boldsymbol{y}}{\boldsymbol{X}^T \boldsymbol{X}}, +$$ +

     
    + +

    +which immediately imposes some requirements on \( \boldsymbol{X} \) as there must exist +an inverse of \( \boldsymbol{X}^T \boldsymbol{X} \). If the expression we are modeling contains an +intercept, i.e., a constant term, we must make sure that the +first column of \( \boldsymbol{X} \) consists of \( 1 \). We do this here + +

    + + +

    X_train_own = np.concatenate(
    +    (np.ones(len(X_train))[:, np.newaxis], X_train),
    +    axis=1
    +)
    +X_test_own = np.concatenate(
    +    (np.ones(len(X_test))[:, np.newaxis], X_test),
    +    axis=1
    +)
    +
    +

    + + +

    def ols_inv(x: np.ndarray, y: np.ndarray) -> np.ndarray:
    +    return scl.inv(x.T @ x) @ (x.T @ y)
    +beta = ols_inv(X_train_own, y_train)
    +
    +
    + + +
    +

    Singular Value decomposition

    + +

    +Doing the inversion directly turns out to be a bad idea since the matrix +\( \boldsymbol{X}^T\boldsymbol{X} \) is singular. An alternative approach is to use the singular +value decomposition. Using the definition of the Moore-Penrose +pseudoinverse we can write the equation for \( \boldsymbol{\beta} \) as + +

     
    +$$ + \boldsymbol{\beta} = \boldsymbol{X}^{+}\boldsymbol{y}, +$$ +

     
    + +

    +where the pseudoinverse of \( \boldsymbol{X} \) is given by + +

     
    +$$ + \boldsymbol{X}^{+} = \frac{\boldsymbol{X}^T}{\boldsymbol{X}^T\boldsymbol{X}}. +$$ +

     
    + +

    +Using singular value decomposition we can decompose the matrix \( \boldsymbol{X} = \boldsymbol{U}\boldsymbol{\Sigma} \boldsymbol{V}^T \), +where \( \boldsymbol{U} \) and \( \boldsymbol{V} \) are orthogonal(unitary) matrices and \( \boldsymbol{\Sigma} \) contains the singular values (more details below). +where \( X^{+} = V\Sigma^{+} U^T \). This reduces the equation for +\( \omega \) to +

     
    +$$ +\begin{align} + \boldsymbol{\beta} = \boldsymbol{V}\boldsymbol{\Sigma}^{+} \boldsymbol{U}^T \boldsymbol{y}. +\tag{6} +\end{align} +$$ +

     
    + +

    +Note that solving this equation by actually doing the pseudoinverse +(which is what we will do) is not a good idea as this operation scales +as \( \mathcal{O}(n^3) \), where \( n \) is the number of elements in a +general matrix. Instead, doing \( QR \)-factorization and solving the +linear system as an equation would reduce this down to +\( \mathcal{O}(n^2) \) operations. + +

    + + +

    def ols_svd(x: np.ndarray, y: np.ndarray) -> np.ndarray:
    +    u, s, v = scl.svd(x)
    +    return v.T @ scl.pinv(scl.diagsvd(s, u.shape[0], v.shape[0])) @ u.T @ y
    +
    +

    + + +

    beta = ols_svd(X_train_own,y_train)
    +
    +

    +When extracting the \( J \)-matrix we need to make sure that we remove the intercept, as is done here + +

    + + +

    J = beta[1:].reshape(L, L)
    +
    +

    +A way of looking at the coefficients in \( J \) is to plot the matrices as images. + +

    + + +

    fig = plt.figure(figsize=(20, 14))
    +im = plt.imshow(J, **cmap_args)
    +plt.title("OLS", fontsize=18)
    +plt.xticks(fontsize=18)
    +plt.yticks(fontsize=18)
    +cb = fig.colorbar(im)
    +cb.ax.set_yticklabels(cb.ax.get_yticklabels(), fontsize=18)
    +plt.show()
    +
    +

    +It is interesting to note that OLS +considers both \( J_{j, j + 1} = -0.5 \) and \( J_{j, j - 1} = -0.5 \) as +valid matrix elements for \( J \). +In our discussion below on hyperparameters and Ridge and Lasso regression we will see that +this problem can be removed, partly and only with Lasso regression. + +

    +In this case our matrix inversion was actually possible. The obvious question now is what is the mathematics behind the SVD? +

    + + +
    +

    Linear Regression Problems

    One of the typical problems we encounter with linear regression, in particular -when the matrix \( \hat{X} \) (our so-called design matrix) is high-dimensional, -are problems with near singular or singular matrices. The column vectors of \( \hat{X} \) +when the matrix \( \boldsymbol{X} \) (our so-called design matrix) is high-dimensional, +are problems with near singular or singular matrices. The column vectors of \( \boldsymbol{X} \) may be linearly dependent, normally referred to as super-collinearity. This means that the matrix may be rank deficient and it is basically impossible to to model the data using linear regression. As an example, consider the matrix @@ -1309,7 +1569,7 @@ $$

     

    -The columns of \( \hat{X} \) are linearly dependent. We se this easily since the +The columns of \( \boldsymbol{X} \) are linearly dependent. We see this easily since the the first column is the row-wise sum of the other two columns. The rank (more correct, the column rank) of a matrix is the dimension of the space spanned by the column vectors. Hence, the rank of \( \mathbf{X} \) is equal to the number @@ -1317,11 +1577,11 @@ of linearly independent columns. In this particular case the matrix has rank 2.

    Super-collinearity of an \( (n \times p) \)-dimensional design matrix \( \mathbf{X} \) implies -that the inverse of the matrix \( \hat{X}^T\hat{x} \) (the matrix we needto invert to solve the linear regression equations) is non-invertible. If we have a square matrix that does not have an inverse, we say this matrix singular. The example here demonstrates this +that the inverse of the matrix \( \boldsymbol{X}^T\boldsymbol{x} \) (the matrix we need to invert to solve the linear regression equations) is non-invertible. If we have a square matrix that does not have an inverse, we say this matrix singular. The example here demonstrates this

     
    $$ \begin{align*} -\hat{X} & = \left[ +\boldsymbol{X} & = \left[ \begin{array}{rr} 1 & -1 \\ @@ -1331,435 +1591,486 @@ $$ $$

     
    -We see easily that \( \mbox{det}(\hat{X}) = x_{11} x_{22} - x_{12} x_{21} = 1 \times (-1) - 1 \times (-1) = 0 \). Hence, \( \mathbf{X} \) is singular and its inverse is undefined. -This is equivalent to saying that the matrix \( \hat{X} \) has at least an eigenvalue which is zero. +We see easily that \( \mbox{det}(\boldsymbol{X}) = x_{11} x_{22} - x_{12} x_{21} = 1 \times (-1) - 1 \times (-1) = 0 \). Hence, \( \mathbf{X} \) is singular and its inverse is undefined. +This is equivalent to saying that the matrix \( \boldsymbol{X} \) has at least an eigenvalue which is zero.

    -

    Fixing the singularity

    +

    Fixing the singularity

    -If our design matrix \( \hat{X} \) which enters the linear regression problem +If our design matrix \( \boldsymbol{X} \) which enters the linear regression problem

     
    $$ \begin{align} -\hat{\beta} & = (\hat{X}^{T} \hat{X})^{-1} \hat{X}^{T} \hat{y}, -\tag{1} +\boldsymbol{\beta} & = (\boldsymbol{X}^{T} \boldsymbol{X})^{-1} \boldsymbol{X}^{T} \boldsymbol{y}, +\tag{7} \end{align} $$

     
    has linearly dependent column vectors, we will not be able to compute the inverse -of \( \hat{X}^T\hat{X} \) and we cannot find the parameters (estimators) \( \beta_i \). -The estimators are only well-defined if \( (\hat{X}^{T}\hat{X})^{-1} \) exits. -This is more likely to happen when the matrix \( \hat{X} \) is high-dimensional. In this case it is likely to encounter a situation where +of \( \boldsymbol{X}^T\boldsymbol{X} \) and we cannot find the parameters (estimators) \( \beta_i \). +The estimators are only well-defined if \( (\boldsymbol{X}^{T}\boldsymbol{X})^{-1} \) exits. +This is more likely to happen when the matrix \( \boldsymbol{X} \) is high-dimensional. In this case it is likely to encounter a situation where the regression parameters \( \beta_i \) cannot be estimated.

    -The ad hoc approach which was introduced in the 70s was simply to add a diagonal component to the matrix to invert, that is we change +A cheap ad hoc approach is simply to add a small diagonal component to the matrix to invert, that is we change

     
    $$ -\hat{X}^{T} \hat{X} \rightarrow \hat{X}^{T} \hat{X}+\lambda \hat{I}, +\boldsymbol{X}^{T} \boldsymbol{X} \rightarrow \boldsymbol{X}^{T} \boldsymbol{X}+\lambda \boldsymbol{I}, $$

     
    -where \( \hat{I} \) is the identity matrix. +where \( \boldsymbol{I} \) is the identity matrix. When we discuss Ridge regression this is actually what we end up evaluating. The parameter \( \lambda \) is called a hyperparameter. More about this later.

    -

    Fitting vs. predicting when data is in the model class

    +

    Basic math of the SVD

    -We start by considering the case -\( f(x)=2x \). +From standard linear algebra we know that a square matrix \( \boldsymbol{X} \) can be diagonalized if and only it is +a so-called normal matrix, that is if \( \boldsymbol{X}\in {\mathbb{R}}^{n\times n} \) +we have \( \boldsymbol{X}\boldsymbol{X}^T=\boldsymbol{X}^T\boldsymbol{X} \) or if \( \boldsymbol{X}\in {\mathbb{C}}^{n\times n} \) we have \( \boldsymbol{X}\boldsymbol{X}^{\dagger}=\boldsymbol{X}^{\dagger}\boldsymbol{X} \). +The matrix has then a set of eigenpairs + +

     
    +$$ +(\lambda_1,\boldsymbol{u}_1),\dots, (\lambda_n,\boldsymbol{u}_n), +$$ +

     
    + +and the eigenvalues are given by the diagonal matrix +

     
    +$$ +\boldsymbol{\Sigma}=\mathrm{Diag}(\lambda_1, \dots,\lambda_n). +$$ +

     
    + +The matrix \( \boldsymbol{X} \) can be written in terms of an orthogonal/unitary transformation \( \boldsymbol{U} \) +

     
    +$$ +\boldsymbol{X} = \boldsymbol{U}\boldsymbol{\Sigma}\boldsymbol{V}^T, +$$ +

     
    + +with \( \boldsymbol{U}\boldsymbol{U}^T=\boldsymbol{I} \) or \( \boldsymbol{U}\boldsymbol{U}^{\dagger}=\boldsymbol{I} \).

    -Then the data is clearly generated by a model that is contained within -all three model classes we are using to make predictions (linear -models, third order polynomials, and tenth order polynomials). +Not all square matrices are diagonalizable. A matrix like the one discussed above +

     
    +$$ +\boldsymbol{X} = \begin{bmatrix} +1& -1 \\ +1& -1\\ +\end{bmatrix} +$$ +

     
    + +is not diagonalizable, it is a so-called defective matrix. It is easy to see that the condition +\( \boldsymbol{X}\boldsymbol{X}^T=\boldsymbol{X}^T\boldsymbol{X} \) is not fulfilled. +

    + + +
    +

    The SVD, a Fantastic Algorithm

    -Run the code for the following cases: +However, and this is the strength of the SVD algorithm, any general +matrix \( \boldsymbol{X} \) can be decomposed in terms of a diagonal matrix and +two orthogonal/unitary matrices. The Singular Value Decompostion +(SVD) theorem +states that a general \( m\times n \) matrix \( \boldsymbol{X} \) can be written in +terms of a diagonal matrix \( \boldsymbol{\Sigma} \) of dimensionality \( n\times n \) +and two orthognal matrices \( \boldsymbol{U} \) and \( \boldsymbol{V} \), where the first has +dimensionality \( m \times m \) and the last dimensionality \( n\times n \). +We have then + +

     
    +$$ +\boldsymbol{X} = \boldsymbol{U}\boldsymbol{\Sigma}\boldsymbol{V}^T +$$ +

     
    + +

    +As an example, the above defective matrix can be decomposed as + +

     
    +$$ +\boldsymbol{X} = \frac{1}{\sqrt{2}}\begin{bmatrix} 1& 1 \\ 1& -1\\ \end{bmatrix} \begin{bmatrix} 2& 0 \\ 0& 0\\ \end{bmatrix} \frac{1}{\sqrt{2}}\begin{bmatrix} 1& -1 \\ 1& 1\\ \end{bmatrix}=\boldsymbol{U}\boldsymbol{\Sigma}\boldsymbol{V}^T, +$$ +

     
    + +

    +with eigenvalues \( \sigma_1=2 \) and \( \sigma_2=0 \). +The SVD exits always! +

    + + +
    +

    Another Example

    + +

    +Consider the following matrix which can be SVD decomposed as + +

     
    +$$ +\boldsymbol{X} = \frac{1}{15}\begin{bmatrix} 14 & 2\\ 4 & 22\\ 16 & 13\end{matrix}=\frac{1}{3}\begin{bmatrix} 1& 2 & 2 \\ 2& -1 & 1\\ 2 & 1& -2\end{bmatrix} \begin{bmatrix} 2& 0 \\ 0& 1\\ 0 & 0\end{bmatrix}\frac{1}{5}\begin{bmatrix} 3& 4 \\ 4& -3\end{bmatrix}=\boldsymbol{U}\boldsymbol{\Sigma}\boldsymbol{V}^T. +$$ +

     
    + +

    +This is a \( 3\times 2 \) matrix which is decomposed in terms of a +\( 3\times 3 \) matrix \( \boldsymbol{U} \), and a \( 2\times 2 \) matrix \( \boldsymbol{V} \). It is easy to see +that \( \boldsymbol{U} \) and \( \boldsymbol{V} \) are orthogonal (how?). + +

    +And the SVD +decomposition (singular values) gives eigenvalues +\( \sigma_i\geq\sigma_{i+1} \) for all \( i \) and for dimensions larger than \( i=2 \), the +eigenvalues (singular values) are zero. + +

    +In the general case, where our design matrix \( \boldsymbol{X} \) has dimension +\( n\times p \), the matrix is thus decomposed into an \( n\times n \) +orthogonal matrix \( \boldsymbol{U} \), a \( p\times p \) orthogonal matrix \( \boldsymbol{V} \) +and a diagonal matrix \( \boldsymbol{\Sigma} \) with \( r=\mathrm{min}(n,p) \) +singular values \( \sigma_i\lg 0 \) on the main diagonal and zeros filling +the rest of the matrix. There are at most \( p \) singular values +assuming that \( n > p \). In our regression examples for the nuclear +masses and the equation of state this is indeed the case, while for +the Ising model we have \( p > n \). These are often cases that lead to +near singular or singular matrices. + +

    +The columns of \( \boldsymbol{U} \) are called the left singular vectors while the columns of \( \boldsymbol{V} \) are the right singular vectors. +

    + + +
    +

    Economy-size SVD

    + +

    +If we assume that \( n > p \), then our matrix \( \boldsymbol{U} \) has dimension \( n +\times n \). The last \( n-p \) columns of \( \boldsymbol{U} \) become however +irrelevant in our calculations since they are multiplied with the +zeros in \( \boldsymbol{\Sigma} \). + +

    +The economy-size decomposition removes extra rows or columns of zeros +from the diagonal matrix of singular values, \( \boldsymbol{\Sigma} \), along with the columns +in either \( \boldsymbol{U} \) or \( \boldsymbol{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 \( \boldsymbol{U} \) and \( \boldsymbol{\Sigma} \) has dimension \( p\times p \). +If \( p > n \), then only the first \( n \) columns of \( \boldsymbol{V} \) are computed and \( \boldsymbol{\Sigma} \) has dimension \( n\times n \). +The \( n=p \) case is obvious, we retain the full SVD. +In general the economy-size SVD leads to less FLOPS and still conserving the desired accuracy. +

    + + +
    +

    Mathematical Properties

    + +

    +There are several interesting mathematical properties which will be +relevant when we are going to discuss the differences between say +ordinary least squares (OLS) and Ridge regression. + +

    +We have from OLS that the parameters of the linear approximation are given by +

     
    +$$ +\boldsymbol{\tilde{y}} = \boldsymbol{X}\boldsymbol{\beta} = \boldsymbol{X}\left(\boldsymbol{X}^T\boldsymbol{X}\right)^{-1}\boldsymbol{X}^T\boldsymbol{y}. +$$ +

     
    + +

    +The matrix to invert can be rewritten in terms of our SVD decomposition as + +

     
    +$$ +\boldsymbol{X}^T\boldsymbol{X} = \boldsymbol{V}\boldsymbol{\Sigma}^T\boldsymbol{U}^T\boldsymbol{U}\boldsymbol{\Sigma}\boldsymbol{V}^T. +$$ +

     
    + +Using the orthogonality properties of \( \boldsymbol{U} \) we have + +

     
    +$$ +\boldsymbol{X}^T\boldsymbol{X} = \boldsymbol{V}\boldsymbol{\Sigma}^T\boldsymbol{\Sigma}\boldsymbol{V}^T = \boldsymbol{V}\boldsymbol{D}\boldsymbol{V}^T, +$$ +

     
    + +with \( \boldsymbol{D} \) being a diagonal matrix with values along the diagonal given by the singular values squared. + +

    +This means that +

     
    +$$ +(\boldsymbol{X}^T\boldsymbol{X})\boldsymbol{V} = \boldsymbol{V}\boldsymbol{D}, +$$ +

     
    + +that is the eigenvectors of \( (\boldsymbol{X}^T\boldsymbol{X}) \) are given by the columns of the right singular matrix of \( \boldsymbol{X} \) and the eigenvalues are the squared singular values. It is easy to show (show this) that +

     
    +$$ +(\boldsymbol{X}\boldsymbol{X}^T)\boldsymbol{U} = \boldsymbol{U}\boldsymbol{D}, +$$ +

     
    + +that is, the eigenvectors of \( (\boldsymbol{X}\boldsymbol{X})^T \) are the columns of the left singular matrix and the eigenvalues are the same. + +

    +Going back to our OLS equation we have +

     
    +$$ +\boldsymbol{X}\boldsymbol{\beta} = \boldsymbol{X}\left(\boldsymbol{V}\boldsymbol{D}\boldsymbol{V}^T \right)^{-1}\boldsymbol{X}^T\boldsymbol{y}=\boldsymbol{U\Sigma V^T}\left(\boldsymbol{V}\boldsymbol{D}\boldsymbol{V}^T \right)^{-1}(\boldsymbol{U\Sigma V^T})^T\boldsymbol{y}=\boldsymbol{U}\boldsymbol{U}^T\boldsymbol{y}. +$$ +

     
    + +We will come back to this expression when we discuss Ridge regression. +

    + + +
    +

    Ridge and LASSO Regression

    + +

    +Let us remind ourselves about the expression for the standard Mean Squared Error (MSE) which we used to define our cost function and the equations for the ordinary least squares (OLS) method, that is +our optimization problem is +

     
    +$$ +{\displaystyle \min_{\boldsymbol{\beta}\in {\mathbb{R}}^{p}}}\frac{1}{n}\left\{\left(\boldsymbol{y}-\boldsymbol{X}\boldsymbol{\beta}\right)^T\left(\boldsymbol{y}-\boldsymbol{X}\boldsymbol{\beta}\right)\right\}. +$$ +

     
    + +or we can state it as +

     
    +$$ +{\displaystyle \min_{\boldsymbol{\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 \boldsymbol{y}-\boldsymbol{X}\boldsymbol{\beta}\vert\vert_2^2, +$$ +

     
    + +where we have used the definition of a norm-2 vector, that is +

     
    +$$ +\vert\vert \boldsymbol{x}\vert\vert_2 = \sqrt{\sum_i x_i^2}. +$$ +

     
    + +

    +By minimizing the above equation with respect to the parameters +\( \boldsymbol{\beta} \) we could then obtain an analytical expression for the +parameters \( \boldsymbol{\beta} \). We can add a regularization parameter \( \lambda \) by +defining a new cost function to be optimized, that is + +

     
    +$$ +{\displaystyle \min_{\boldsymbol{\beta}\in +{\mathbb{R}}^{p}}}\frac{1}{n}\vert\vert \boldsymbol{y}-\boldsymbol{X}\boldsymbol{\beta}\vert\vert_2^2+\lambda\vert\vert \boldsymbol{\beta}\vert\vert_2^2 +$$ +

     
    + +

    +which leads to the Ridge regression minimization problem where we +require that \( \vert\vert \boldsymbol{\beta}\vert\vert_2^2\le t \), where \( t \) is +a finite number larger than zero. By defining + +

     
    +$$ +C(\boldsymbol{X},\boldsymbol{\beta})=\frac{1}{n}\vert\vert \boldsymbol{y}-\boldsymbol{X}\boldsymbol{\beta}\vert\vert_2^2+\lambda\vert\vert \boldsymbol{\beta}\vert\vert_1, +$$ +

     
    + +

    +we have a new optimization equation +

     
    +$$ +{\displaystyle \min_{\boldsymbol{\beta}\in +{\mathbb{R}}^{p}}}\frac{1}{n}\vert\vert \boldsymbol{y}-\boldsymbol{X}\boldsymbol{\beta}\vert\vert_2^2+\lambda\vert\vert \boldsymbol{\beta}\vert\vert_1 +$$ +

     
    + +which leads to Lasso regression. Lasso stands for least absolute shrinkage and selection operator. + +

    +Here we have defined the norm-1 as +

     
    +$$ +\vert\vert \boldsymbol{x}\vert\vert_1 = \sum_i \vert x_i\vert. +$$ +

     
    +

    + + +
    +

    More on Ridge Regression

    + +

    +Using the matrix-vector expression for Ridge regression, + +

     
    +$$ +C(\boldsymbol{X},\boldsymbol{\beta})=\frac{1}{n}\left\{(\boldsymbol{y}-\boldsymbol{X}\boldsymbol{\beta})^T(\boldsymbol{y}-\boldsymbol{X}\boldsymbol{\beta})\right\}+\lambda\boldsymbol{\beta}^T\boldsymbol{\beta}, +$$ +

     
    + +

    +by taking the derivatives with respect to \( \boldsymbol{\beta} \) we obtain then +a slightly modified matrix inversion problem which for finite values +of \( \lambda \) does not suffer from singularity problems. We obtain + +

     
    +$$ +\boldsymbol{\beta}^{\mathrm{Ridge}} = \left(\boldsymbol{X}^T\boldsymbol{X}+\lambda\boldsymbol{I}\right)^{-1}\boldsymbol{X}^T\boldsymbol{y}, +$$ +

     
    + +

    +with \( \boldsymbol{I} \) being a \( p\times p \) identity matrix with the constraint that + +

     
    +$$ +\sum_{i=0}^{p-1} \beta_i^2 \leq t, +$$ +

     
    + +

    +with \( t \) a finite positive number. + +

    +We see that Ridge regression is nothing but the standard +OLS with a modified diagonal term added to \( \boldsymbol{X}^T\boldsymbol{X} \). The +consequences, in particular for our discussion of the bias-variance +are rather interesting. + +

    +Furthermore, if we use the result above in terms of the SVD decomposition (our analysis was done for the OLS method), we had +

     
    +$$ +(\boldsymbol{X}\boldsymbol{X}^T)\boldsymbol{U} = \boldsymbol{U}\boldsymbol{D}. +$$ +

     
    + +

    +We can analyse the OLS solutions in terms of the eigenvectors (the columns) of the right singular value matrix \( \boldsymbol{U} \) as +

     
    +$$ +\boldsymbol{X}\boldsymbol{\beta} = \boldsymbol{X}\left(\boldsymbol{V}\boldsymbol{D}\boldsymbol{V}^T \right)^{-1}\boldsymbol{X}^T\boldsymbol{y}=\boldsymbol{U\Sigma V^T}\left(\boldsymbol{V}\boldsymbol{D}\boldsymbol{V}^T \right)^{-1}(\boldsymbol{U\Sigma V^T})^T\boldsymbol{y}=\boldsymbol{U}\boldsymbol{U}^T\boldsymbol{y} +$$ +

     
    + +

    +For Ridge regression this becomes + +

     
    +$$ +\boldsymbol{X}\boldsymbol{\beta}^{\mathrm{Ridge}} = \boldsymbol{U\Sigma V^T}\left(\boldsymbol{V}\boldsymbol{D}\boldsymbol{V}^T+\lambda\boldsymbol{I} \right)^{-1}(\boldsymbol{U\Sigma V^T})^T\boldsymbol{y}=\sum_{j=0}^{p-1}\boldsymbol{u}_j\boldsymbol{u}_j^T\frac{\sigma_j^2}{\sigma_j^2+\lambda}\boldsymbol{y}, +$$ +

     
    + +

    +with the vectors \( \boldsymbol{u}_j \) being the columns of \( \boldsymbol{U} \). +

    + + +
    +

    Interpreting the Ridge results

    + +

    +Since \( \lambda \geq 0 \), it means that compared to OLS, we have + +

     
    +$$ +\frac{\sigma_j^2}{\sigma_j^2+\lambda} \leq 1. +$$ +

     
    + +

    +Ridge regression finds the coordinates of \( \boldsymbol{y} \) with respect to the +orthonormal basis \( \boldsymbol{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 \( \boldsymbol{X}\boldsymbol{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. +

    + + +
    +

    More interpretations

    + +

    +For the sake of simplicity, let us assume that the design matrix is orthonormal, that is + +

     
    +$$ +\boldsymbol{X}^T\boldsymbol{X}=(\boldsymbol{X}^T\boldsymbol{X})^{-1} =\boldsymbol{I}. +$$ +

     
    + +

    +In this case the standard OLS results in +

     
    +$$ +\boldsymbol{\beta}^{\mathrm{OLS}} = \boldsymbol{X}^T\boldsymbol{y}=\sum_{i=0}^{p-1}\boldsymbol{u}_j\boldsymbol{u}_j^T\boldsymbol{y}, +$$ +

     
    + +

    +and + +

     
    +$$ +\boldsymbol{\beta}^{\mathrm{Ridge}} = \left(\boldsymbol{I}+\lambda\boldsymbol{I}\right)^{-1}\boldsymbol{X}^T\boldsymbol{y}=\left(1+\lambda\right)^{-1}\boldsymbol{\beta}^{\mathrm{OLS}}, +$$ +

     
    + +

    +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 article is highly recommended. +Similarly, Mehta et al's article is also recommended. +

    + + +
    +

    Where are we going?

    + +

    +Before we proceed, we need to rethink what we have been doing. In our +eager to fit the data, we have omitted several important elements in +our regression analysis. In what follows we will

      -

    1. For \( f(x)=2x \) , \( Ntrain=10 \) and \( \sigma =0 \) (noiseless case), train the three classes of models (linear, third-order polynomial, and tenth order polynomial) for a training set when \( x \in [0,1] \) . Make graphs comparing fits for different order of polynomials. Which model fits the data the best?
    2. -

    3. Do you think that the data that has the least error on the training set will also make the best predictions? Why or why not? Can you try to discuss and formalize your intuition? What can go right and what can go wrong?
    4. -

    5. Check your answer by seeing how well your fits predict newly generated test data (including on data outside the range you fit on, for example \( x \in [0,1.2] \) ) using the code below. How well do you do on points in the range of x where you trained the model? How about points outside the original training data set?
    6. -

    7. Repeat the above for \( f(x)=2x \) , \( Ntrain=10 \) , and \( \sigma=1 \) . What changes?
    8. +

    9. look at statistical properties, including a discussion of mean values, variance and the so-called bias-variance tradeoff
    10. +

    11. introduce resampling techniques like cross-validation, bootstrapping and jackknife and more

    -Repeat the exercises above for \( f(x)=2x \) , \( Ntrain=100 \) , and \( \sigma=1 \) . What changes? -Summarize what you have learned about the relationship between model complexity (number of parameters), goodness of fit on training data, and the ability to predict well. +This will allow us to link the standard linear algebra methods we have discussed above to a statistical interpretation of the methods.

    -

    Fitting versus predicting when data is not in the model class

    - -

    -Thus far, we have considered the case where the data is generated using a model contained in the model class. Now consider \( f(x)=2x-10x^5+15x^{10} \) . Notice that the for linear and third-order polynomial the true model \( f(x) \) is not contained in model class. - -

      -

    1. Do better fits lead to better predictions?
    2. -

    3. What is the relationship between the true model for generating the data and the model class that has the most predictive power? How is this related to the model complexity? How does this depend on the number of data points \( Ntrain \) and \( \sigma \)?
    4. -
    -

    - -Summarize what you think you learned about the relationship of knowing the true model class and predictive power. -

    - - -
    -

    An example code without the model assessment part

    - -

    - - -

    import numpy as np
    -import sklearn as sk
    -from sklearn import datasets, linear_model
    -from sklearn.preprocessing import PolynomialFeatures
    -
    -import matplotlib as mpl
    -from matplotlib import pyplot as plt
    -
    -%matplotlib notebook
    -
    -# The Training Data
    -
    -N_train=100
    -
    -sigma_train=1;
    -
    -# Train on integers
    -x=np.linspace(0.05,0.95,N_train)
    -# Draw random noise
    -s = sigma_train*np.random.randn(N_train)
    -
    -#linear
    -y=2*x+s
    -
    -#Tenth Order
    -#y=2*x-10*x**5+15*x**10+s
    -
    -p1=plt.plot(x,y, "o",ms=15, label='Training')
    -
    -#Linear Regression
    -# Create linear regression object
    -clf = linear_model.LinearRegression()
    -
    -# Train the model using the training sets
    -clf.fit(x[:, np.newaxis], y)
    -# The coefficients
    -
    -xplot=np.linspace(0.02,0.98,200)
    -linear_plot=plt.plot(xplot, clf.predict(xplot[:, np.newaxis]),label='Linear')
    -
    -#Polynomial Regression
    -
    -
    -poly3 = PolynomialFeatures(degree=3)
    -X = poly3.fit_transform(x[:,np.newaxis])
    -clf3 = linear_model.LinearRegression()
    -clf3.fit(X,y)
    -
    -
    -Xplot=poly3.fit_transform(xplot[:,np.newaxis])
    -poly3_plot=plt.plot(xplot, clf3.predict(Xplot), label='Poly 3')
    -
    -
    -
    -#poly5 = PolynomialFeatures(degree=5)
    -#X = poly5.fit_transform(x[:,np.newaxis])
    -#clf5 = linear_model.LinearRegression()
    -#clf5.fit(X,y)
    -
    -#Xplot=poly5.fit_transform(xplot[:,np.newaxis])
    -#plt.plot(xplot, clf5.predict(Xplot), 'r--',linewidth=1)
    -
    -poly10 = PolynomialFeatures(degree=10)
    -X = poly10.fit_transform(x[:,np.newaxis])
    -clf10 = linear_model.LinearRegression()
    -clf10.fit(X,y)
    -
    -Xplot=poly10.fit_transform(xplot[:,np.newaxis])
    -poly10_plot=plt.plot(xplot, clf10.predict(Xplot), label='Poly 10')
    -
    -axes = plt.gca()
    -axes.set_ylim([-7,7])
    -
    -handles, labels=axes.get_legend_handles_labels()
    -plt.legend(handles,labels, loc='lower center')
    -plt.xlabel("$x$")
    -plt.ylabel("$y$")
    -Title="$N=$"+str(N_train)+", $\sigma=$"+str(sigma_train)
    -plt.title(Title+" (train)")
    -plt.tight_layout()
    -plt.show()
    -
    -
    - - -
    -

    Generating test data

    -

    - - -

    # Generate Test Data
    -
    -#Number of test data
    -N_test=20
    -
    -sigma_test=sigma_train
    -
    -max_x=1.2
    -x_test=max_x*np.random.random(N_test)
    -# Draw random noise
    -s_test = sigma_test*np.random.randn(N_test)
    -
    -#Linear
    -y_test=2*x_test+s_test
    -#Tenth order
    -#y_test=2*x_test-10*x_test**5+15*x_test**10+s_test
    -
    -#Make design matrices for prediction
    -x_plot=np.linspace(0,max_x, 200)
    -X3 = poly3.fit_transform(x_plot[:,np.newaxis])
    -X10 = poly10.fit_transform(x_plot[:,np.newaxis])
    -
    -%matplotlib notebook
    -
    -fig = plt.figure() 
    -p1=plt.plot(x_test,y_test.transpose(), 'o', ms=12, label='data')
    -p2=plt.plot(x_plot,clf.predict(x_plot[:,np.newaxis]), label='linear')
    -p3=plt.plot(x_plot,clf3.predict(X3), label='3rd order')
    -p10=plt.plot(x_plot,clf10.predict(X10), label='10th order')
    -
    -
    -plt.legend(loc=2)
    -plt.xlabel('$x$')
    -plt.ylabel('$y$')
    -plt.legend(loc='best')
    -plt.title(Title+" (pred.)")
    -plt.tight_layout()
    -plt.show()
    -
    -
    - - -
    -

    How can we effectively evaluate the various models?

    - -

    -In Ridge regression and the subsequent discussion of its properties -the bias or penalty parameter is considered known or `given'. In -practice, it is unknown and the user needs to make an informed -decision on its value. How do we do that? Much of the same considerations apply to the Lasso method. -

    - - -
    -

    Code examples for Ridge and Lasso Regression

    - -

    - - -

    import matplotlib.pyplot as plt
    -import numpy as np
    -from sklearn import linear_model
    -from sklearn.linear_model import LinearRegression
    -from sklearn.metrics import mean_squared_error, r2_score
    -
    -#creating data with random noise
    -x=np.arange(50)
    -
    -delta=np.random.uniform(-2.5,2.5, size=(50))
    -np.random.shuffle(delta)
    -y =0.5*x+5+delta
    -
    -#arranging data into 2x50 matrix
    -a=np.array(x) #inputs
    -b=np.array(y) #outputs
    -
    -#Split into training and test
    -X_train=a[:37, np.newaxis]
    -X_test=a[37:, np.newaxis]
    -y_train=b[:37]
    -y_test=b[37:]
    -
    -print ("X_train: ", X_train.shape)
    -print ("y_train: ", y_train.shape)
    -print ("X_test: ", X_test.shape)
    -print ("y_test: ", y_test.shape)
    -
    -print ("------------------------------------")
    -
    -print ("Ordinary Least Squares")
    -#Add Ordinary Least Squares fit
    -reg=LinearRegression()
    -reg.fit(X_train, y_train)
    -pred=reg.predict(X_test)
    -print ("Prediction Shape: ", pred.shape)
    -
    -print('Coefficients: \n', reg.coef_)
    -# The mean squared error
    -print("Mean squared error: %.2f"
    -      % mean_squared_error(y_test, pred))
    -# Explained variance score: 1 is perfect prediction
    -print('Variance score: %.2f' % r2_score(y_test, pred))
    -
    -#plot
    -plt.scatter(X_test,y_test,color='green', label="Training Data")
    -plt.plot(X_test, pred, color='black', label="Fit Line")
    -plt.legend()
    -plt.show()
    -
    -print ("------------------------------------")
    -
    -print ("Ridge Regression")
    -
    -ridge=linear_model.RidgeCV(alphas=[0.1,1.0,10.0])
    -ridge.fit(X_train,y_train)
    -print ("Ridge Coefficient: ",ridge.coef_)
    -print ("Ridge Intercept: ", ridge.intercept_)
    -#Look into graphing with Ridge fit
    -
    -print ("------------------------------------")
    -
    -print ("Lasso")
    -lasso=linear_model.Lasso(alpha=0.1)
    -lasso.fit(X_train,y_train)
    -predl=lasso.predict(X_test)
    -print("Lasso Coefficient: ", lasso.coef_)
    -print("Lasso Intercept: ", lasso.intercept_)
    -plt.scatter(X_test,y_test,color='green', label="Training Data")
    -plt.plot(X_test, predl, color='blue', label="Lasso")
    -plt.legend()
    -plt.show()
    -
    -
    - - -
    -

    A second-order polynomial with Ridge and Lasso

    -

    - - -

    import numpy as np
    -import matplotlib.pyplot as plt
    -from sklearn.linear_model import Ridge
    -from sklearn.metrics import r2_score
    -
    -np.random.seed(4155)
    -
    -n_samples = 100
    -
    -x = np.random.rand(n_samples,1)
    -y = 5*x*x + 0.1*np.random.rand(n_samples,1)
    -
    -# Centering  x and y.
    -x_ = x - np.mean(x)
    -y_ = y - np.mean(y) # beta_0 = mean(y)
    -
    -X = np.c_[np.ones((n_samples,1)), x, x**2]
    -X_ = np.c_[x_, x_**2]
    -
    -
    -### 1.
    -lmb_values = [1e-4, 1e-3, 1e-2, 10, 1e2, 1e4]
    -num_values = len(lmb_values)
    -
    -## Ridge-regression of centered and not centered data
    -beta_ridge = np.zeros((3,num_values))
    -beta_ridge_centered = np.zeros((3,num_values))
    -
    -I3 = np.eye(3)
    -I2 = np.eye(2)
    -
    -for i,lmb in enumerate(lmb_values):
    -    beta_ridge[:,i] = (np.linalg.inv( X.T @ X + lmb*I3) @ X.T @ y).flatten()
    -    beta_ridge_centered[1:,i] = (np.linalg.inv( X_.T @ X_ + lmb*I2) @ X_.T @ y_).flatten()
    -
    -# sett beta_0 = np.mean(y)
    -beta_ridge_centered[0,:] = np.mean(y)
    -
    -## OLS (ordinary least squares) solution 
    -beta_ls = np.linalg.inv( X.T @ X ) @ X.T @ y
    -
    -## Evaluate the models
    -pred_ls = X @ beta_ls
    -pred_ridge =  X @ beta_ridge
    -pred_ridge_centered =  X_ @ beta_ridge_centered[1:] + beta_ridge_centered[0,:]
    -
    -## Plot the results
    -
    -# Sorting
    -sort_ind = np.argsort(x[:,0])
    -
    -x_plot = x[sort_ind,0]
    -x_centered_plot = x_[sort_ind,0]
    -
    -pred_ls_plot = pred_ls[sort_ind,0]
    -pred_ridge_plot = pred_ridge[sort_ind,:]
    -pred_ridge_centered_plot = pred_ridge_centered[sort_ind,:]
    -
    -# Plott not centered
    -plt.plot(x_plot,pred_ls_plot,label='ls')
    -
    -for i in range(num_values):
    -    plt.plot(x_plot,pred_ridge_plot[:,i],label='ridge, lmb=%g'%lmb_values[i])
    -
    -plt.plot(x,y,'ro')
    -
    -plt.title('linear regression on un-centered data')
    -plt.legend()
    -
    -# Plott centered
    -plt.figure()
    -
    -for i in range(num_values):
    -    plt.plot(x_centered_plot,pred_ridge_centered_plot[:,i],label='ridge, lmb=%g'%lmb_values[i])
    -
    -plt.plot(x_,y,'ro')
    -
    -plt.title('linear regression on centered data')
    -plt.legend()
    -
    -
    -# 2.
    -
    -pred_ridge_scikit =  np.zeros((n_samples,num_values))
    -for i,lmb in enumerate(lmb_values):
    -    pred_ridge_scikit[:,i] = (Ridge(alpha=lmb,fit_intercept=False).fit(X,y).predict(X)).flatten() # fit_intercept=False fordi bias er allerede i X
    -
    -plt.figure()
    -
    -plt.plot(x_plot,pred_ls_plot,label='ls')
    -
    -for i in range(num_values):
    -    plt.plot(x_plot,pred_ridge_scikit[sort_ind,i],label='scikit-ridge, lmb=%g'%lmb_values[i])
    -
    -plt.plot(x,y,'ro')
    -plt.legend()
    -plt.title('linear regression using scikit')
    -
    -plt.show()
    -
    -### R2-score of the results
    -for i in range(num_values):
    -    print('lambda = %g'%lmb_values[i])
    -    print('r2 for scikit: %g'%r2_score(y,pred_ridge_scikit[:,i]))
    -    print('r2 for own code, not centered: %g'%r2_score(y,pred_ridge[:,i]))
    -    print('r2 for own, centered: %g\n'%r2_score(y,pred_ridge_centered[:,i]))
    -
    -
    - - -
    -

    Resampling methods

    +

    Resampling methods

    @@ -1778,7 +2089,7 @@ once using the original training sample.

    -

    Resampling approaches can be computationally expensive

    +

    Resampling approaches can be computationally expensive

    @@ -1797,20 +2108,19 @@ of flexibility. The process of evaluating a model’s performance is known as model assessment, whereas the process of selecting the proper level of flexibility for a model is known as model selection. The bootstrap is widely used. + +

    -

    Why resampling methods ?

    +

    Why resampling methods ?

    Statistical analysis.
      -

    • Our simulations can be treated as computer experiments. This is particularly the case for Monte Carlo methods
    • -

    • The results can be analysed with the same statistical tools as we would use analysing experimental data.
    • -

    • As in all experiments, we are looking for expectation values and an estimate of how accurate they are, i.e., possible sources for errors.
    @@ -1818,11 +2128,10 @@ bootstrap is widely used.
    -

    Statistical analysis

    +

    Statistical analysis

      -

    • As in other experiments, many numerical experiments have two classes of errors:
      • @@ -1832,7 +2141,6 @@ bootstrap is widely used.

      • Systematical errors

    • Statistical errors can be estimated using standard tools from statistics
    • -

    • Systematical errors are method specific and must be treated differently from case to case.
    @@ -1840,7 +2148,7 @@ bootstrap is widely used.
    -

    Statistics

    +

    Statistics

    @@ -1874,7 +2182,7 @@ selection of a large set of these numbers reproduces this PDF.

    -

    Statistics, moments

    +

    Statistics, moments

    @@ -1900,7 +2208,7 @@ $$

    -

    Statistics, central moments

    +

    Statistics, central moments

    @@ -1921,14 +2229,14 @@ $$ \begin{align} \sigma^2_X\ \ =\ \ \mathrm{var}(X) & = \langle (x-\langle x\rangle)^2\rangle = \int\! (x-\langle x\rangle)^2 p(x)\,dx -\tag{2}\\ +\tag{8}\\ & = \int\! \left(x^2 - 2 x \langle x\rangle^{2} + \langle x\rangle^2\right)p(x)\,dx -\tag{3}\\ +\tag{9}\\ & = \langle x^2\rangle - 2 \langle x\rangle\langle x\rangle + \langle x\rangle^2 -\tag{4}\\ +\tag{10}\\ & = \langle x^2\rangle - \langle x\rangle^2 -\tag{5} +\tag{11} \end{align} $$

     
    @@ -1941,7 +2249,7 @@ qualitatively as the spread of \( p \) around its mean.

    -

    Statistics, covariance

    +

    Statistics, covariance

    @@ -1958,7 +2266,7 @@ $$ &= \int\!\cdots\!\int\!(x_i-\langle x_i \rangle)(x_j-\langle x_j \rangle)\, P(x_1,\dots,x_n)\,dx_1\dots dx_n -\tag{6} +\tag{12} \end{align} $$

     
    @@ -1975,7 +2283,7 @@ $$

    -

    Statistics, more covariance

    +

    Statistics, more covariance

    @@ -1989,17 +2297,17 @@ the expectation value. Consider the stochastic variables \( X_i \) and $$ \begin{align} \mathrm{cov}(X_i,\,X_j) &= \langle(x_i-\langle x_i\rangle)(x_j-\langle x_j\rangle)\rangle -\tag{7}\\ +\tag{13}\\ &=\langle x_i x_j - x_i\langle x_j\rangle - \langle x_i\rangle x_j + \langle x_i\rangle\langle x_j\rangle\rangle -\tag{8}\\ +\tag{14}\\ &=\langle x_i x_j\rangle - \langle x_i\langle x_j\rangle\rangle - \langle \langle x_i\rangle x_j\rangle + \langle \langle x_i\rangle\langle x_j\rangle\rangle -\tag{9}\\ +\tag{15}\\ &=\langle x_i x_j\rangle - \langle x_i\rangle\langle x_j\rangle - \langle x_i\rangle\langle x_j\rangle + \langle x_i\rangle\langle x_j\rangle -\tag{10}\\ +\tag{16}\\ &=\langle x_i x_j\rangle - \langle x_i\rangle\langle x_j\rangle -\tag{11} +\tag{17} \end{align} $$

     
    @@ -2008,7 +2316,7 @@ $$

    -

    Statistics, independent variables

    +

    Statistics, independent variables

    @@ -2037,7 +2345,7 @@ $$

    -

    Statistics, more variance

    +

    Statistics, more variance

    @@ -2047,7 +2355,7 @@ the variance of the linear combination \( U = \sum_i a_i X_i \): $$ \begin{equation} \mathrm{var}(U) = \sum_{i,j}a_i a_j \mathrm{cov}(X_i, X_j) -\tag{12} +\tag{18} \end{equation} $$

     
    @@ -2074,7 +2382,7 @@ value of a set of measurements.

    -

    Statistics and stochastic processes

    +

    Statistics and stochastic processes

    @@ -2103,7 +2411,7 @@ interested in finding the few lowest moments, like the mean

    -

    Statistics and sample variables

    +

    Statistics and sample variables

    @@ -2134,12 +2442,12 @@ $$

    -

    Statistics, sample variance and covariance

    +

    Statistics, sample variance and covariance

    Note that the sample variance is the sample covariance without the -cross terms. In a similar manner as the covariance in Eq. (6) is a measure of the correlation between +cross terms. In a similar manner as the covariance in Eq. (12) is a measure of the correlation between two stochastic variables, the above defined sample covariance is a measure of the sequential correlation between succeeding measurements of a sample. @@ -2154,7 +2462,7 @@ and covariance \( \mathrm{cov}(X,Y) \).

    -

    Statistics, law of large numbers

    +

    Statistics, law of large numbers

    @@ -2187,7 +2495,7 @@ true PDFs behind, which we usually do not have.

    -

    Statistics, more on sample error

    +

    Statistics, more on sample error

    @@ -2210,7 +2518,7 @@ means.

    -

    Statistics

    +

    Statistics

    @@ -2232,7 +2540,7 @@ And in particular we are interested in its variance \( \mathrm{var}(\overline X_

    -

    Statistics, central limit theorem

    +

    Statistics, central limit theorem

    @@ -2249,7 +2557,7 @@ $$ \lim_{n\to\infty} p_{\overline X_n}(x) = \left(\frac{n}{2\pi\mathrm{var}(X)}\right)^{1/2} e^{-\frac{n(x-\bar x_n)^2}{2\mathrm{var}(X)}} -\tag{13} +\tag{19} \end{equation} $$

     
    @@ -2258,7 +2566,7 @@ $$

    -

    Statistics, more technicalities

    +

    Statistics, more technicalities

    @@ -2270,7 +2578,7 @@ $$ \begin{equation} \mathrm{err}_X^2 = \mathrm{var}(\overline X_n) = \frac{1}{n^2} \sum_{ij} \mathrm{cov}(X_i, X_j) -\tag{14} +\tag{20} \end{equation} $$

     
    @@ -2288,7 +2596,7 @@ estimate of the PDF of each of the \( X_i \), estimating all properties of

    -

    Statistics

    +

    Statistics

    @@ -2301,7 +2609,7 @@ $$

     
    Using \( \bar x \) in place of \( \mu_{X_i}^{\phantom X} \) we can give an -estimate of the covariance in Eq. (14) +estimate of the covariance in Eq. (20)

     
    $$ \mathrm{cov}(X_i, X_j) = \langle (x_i-\langle x_i\rangle)(x_j-\langle x_j\rangle)\rangle @@ -2320,7 +2628,7 @@ $$

    -

    Statistics and sample variance

    +

    Statistics and sample variance

    @@ -2337,7 +2645,7 @@ which is approximated as $$ \begin{equation} \mathrm{var}(X_i)\approx \frac{1}{n}\sum_{k=1}^n (x_k - \bar x_n)=\mathrm{var}(x) -\tag{15} +\tag{21} \end{equation} $$

     
    @@ -2352,7 +2660,7 @@ $$ &=\frac{1}{n^2}\sum_{ij} \mathrm{cov}(X_i, X_j) \nonumber \\ &\approx&\frac{1}{n^2}\sum_{ij}\frac{1}{n}\mathrm{cov}(x) =\frac{1}{n^2}n^2\frac{1}{n}\mathrm{cov}(x)\nonumber\\ &=\frac{1}{n}\mathrm{cov}(x) -\tag{16} +\tag{22} \end{align} $$

     
    @@ -2364,7 +2672,7 @@ measurements in the sample.

    -

    Statistics, uncorrelated results

    +

    Statistics, uncorrelated results

    @@ -2384,12 +2692,12 @@ resulting in $$ \begin{equation} \mathrm{err}_X^2\approx \frac{1}{n^2} \sum_i \mathrm{var}(x)= \frac{1}{n}\mathrm{var}(x) -\tag{17} +\tag{23} \end{equation} $$

     
    -where in the second step we have used Eq. (15). +where in the second step we have used Eq. (21). The error of the sample is then just its standard deviation divided by the square root of the number of measurements the sample contains. This is a very useful formula which is easy to compute. It acts as a @@ -2400,12 +2708,12 @@ cannot overlook the always present correlations.

    -

    Statistics, computations

    +

    Statistics, computations

    For computational purposes one usually splits up the estimate of -\( \mathrm{err}_X^2 \), given by Eq. (16), into two +\( \mathrm{err}_X^2 \), given by Eq. (22), into two parts

     
    $$ @@ -2418,13 +2726,13 @@ which equals $$ \begin{equation} \frac{1}{n^2}\sum_{k=1}^n (x_k - \bar x_n)^2 +\frac{2}{n^2}\sum_{k < l} (x_k - \bar x_n)(x_l - \bar x_n) -\tag{18} +\tag{24} \end{equation} $$

     
    The first term is the same as the error in the uncorrelated case, -Eq. (17). This means that the second +Eq. (23). This means that the second term accounts for the error correction due to correlation between the measurements. For uncorrelated measurements this second term is zero.

    @@ -2432,7 +2740,7 @@ measurements. For uncorrelated measurements this second term is zero.
    -

    Statistics, more on computations of errors

    +

    Statistics, more on computations of errors

    @@ -2455,7 +2763,7 @@ have to be stored throughout the experiment.

    -

    Statistics, wrapping up 1

    +

    Statistics, wrapping up 1

    @@ -2493,11 +2801,11 @@ starting always at \( 1 \) for \( d=0 \).

    -

    Statistics, final expression

    +

    Statistics, final expression

    -The sample error (see eq. (18)) can now be +The sample error (see eq. (24)) can now be written in terms of the autocorrelation function:

     
    $$ @@ -2507,7 +2815,7 @@ $$ \frac{f_d}{\mathrm{var}(x)}\nonumber\\ &=& \left(1+2\sum_{d=1}^{n-1}\kappa_d\right)\frac{1}{n}\mathrm{var}(x)\nonumber\\ &=\frac{\tau}{n}\cdot\mathrm{var}(x) -\tag{19} +\tag{25} \end{align} $$

     
    @@ -2520,7 +2828,7 @@ correction factor the autocorrelation time: $$ \begin{equation} \tau = 1+2\sum_{d=1}^{n-1}\kappa_d -\tag{20} +\tag{26} \end{equation} $$

     
    @@ -2529,13 +2837,13 @@ $$

    -

    Statistics, effective number of correlations

    +

    Statistics, effective number of correlations

    For a correlation free experiment, \( \tau \) equals 1. From the point of view of -eq. (19) we can interpret a sequential +eq. (25) we can interpret a sequential correlation as an effective reduction of the number of measurements by a factor \( \tau \). The effective number of measurements becomes:

     
    @@ -2555,42 +2863,205 @@ measurements is very large.

    -

    Log-likelihood

    +

    Linking the regression analysis with a statistical interpretation

    -A popular strategy is to choose a penalty parameter that yields a good -but parsimonious model. Information criteria measure the balance -between model fit and model complexity. One possibility is Aikaike's -information criterion (AIC). -The AIC measures model fit by the log-likelihood -and model complexity is measured by the number of parameters used by -the model. The number of model parameters in regular regression simply -corresponds to the number of covariates in the model. Or, by the -degrees of freedom consumed by the model, which is equivalent to the -trace of the hat matrix. For ridge regression it thus seems natural to -define model complexity analogously by the trace of the ridge hat -matrix. This yields the AIC for the linear regression model with ridge -estimates: +Finally, we are going to discuss several statistical properties which can be obtained in terms of analytical expressions. +The +advantage of doing linear regression is that we actually end up with +analytical expressions for several statistical quantities. +Standard least squares and Ridge regression allow us to +derive quantities like the variance and other expectation values in a +rather straightforward way. +

    +It is assumed that \( \varepsilon_i +\sim \mathcal{N}(0, \sigma^2) \) and the \( \varepsilon_{i} \) are +independent, i.e.:

     
    $$ -\begin{align*} -\mbox{AIC}(\lambda) & = 2 \, p - 2 \log(\hat{L}) -\\ -& = 2 \, \mbox{tr} [\mathbf{H}(\lambda)] - 2 \log\{L[\hat{\beta}(\lambda), \hat{\sigma}^2(\lambda)]\} -\\ -& = 2 \, \sum_{j=1}^p \frac{d_{jj}^2}{d_{jj}^2 + \lambda} -+ 2 n \, \log[\sqrt{2 \, \pi} \, \hat{\sigma}(\lambda)] + \frac{1}{\hat{\sigma}^2(\lambda)} \sum_{i=1}^n [y_i - \mathbf{X}_{i, \ast} \, \hat{\beta}(\lambda)]^2. -\end{align*} +\begin{align*} +\mbox{Cov}(\varepsilon_{i_1}, +\varepsilon_{i_2}) & = \left\{ \begin{array}{lcc} \sigma^2 & \mbox{if} +& i_1 = i_2, \\ 0 & \mbox{if} & i_1 \not= i_2. \end{array} \right. +\end{align*} $$

     
    -The value of \( \lambda \) which minimizes \( \mbox{AIC}(\lambda) \) corresponds to the `optimal' balance of model complexity and overfitting. +The randomness of \( \varepsilon_i \) implies that +\( \mathbf{y}_i \) is also a random variable. In particular, +\( \mathbf{y}_i \) is normally distributed, because \( \varepsilon_i \sim +\mathcal{N}(0, \sigma^2) \) and \( \mathbf{X}_{i,\ast} \, \boldsymbol{\beta} \) is a +non-random scalar. To specify the parameters of the distribution of +\( \mathbf{y}_i \) we need to calculate its first two moments. + +

    +Recall that \( \boldsymbol{X} \) is a matrix of dimensionality \( n\times p \). The +notation above \( \mathbf{X}_{i,\ast} \) means that we are looking at the +row number \( i \) and perform a sum over all values \( p \).

    -

    Cross-validation

    +

    Assumptions made

    + +

    +The assumption we have made here can be summarized as (and this is going to useful when we discuss the bias-variance trade off) +that there exists a function \( f(\boldsymbol{x}) \) and a normal distributed error \( \boldsymbol{\varepsilon}\sim \mathcal{N}(0, \sigma^2) \) +which describes our data +

     
    +$$ +\boldsymbol{y} = f(\boldsymbol{x})+\boldsymbol{\varepsilon} +$$ +

     
    + +

    +We approximate this function with our model from the solution of the linear regression equations, that is our +function \( f \) is approximated by \( \boldsymbol{\tilde{y}} \) where we want to minimize \( (\boldsymbol{y}-\boldsymbol{\tilde{y}})^2 \), our MSE, with +

     
    +$$ +\boldsymbol{\tilde{y}} = \boldsymbol{X}\boldsymbol{\beta}. +$$ +

     
    +

    + + +
    +

    Expectation value and variance

    + +

    +We can calculate the expectation value of \( \boldsymbol{y} \) for a given element \( i \) +

     
    +$$ +\begin{align*} +\mathbb{E}(y_i) & = +\mathbb{E}(\mathbf{X}_{i, \ast} \, \boldsymbol{\beta}) + \mathbb{E}(\varepsilon_i) +\, \, \, = \, \, \, \mathbf{X}_{i, \ast} \, \beta, +\end{align*} +$$ +

     
    + +while +its variance is +

     
    +$$ +\begin{align*} \mbox{Var}(y_i) & = \mathbb{E} \{ [y_i +- \mathbb{E}(y_i)]^2 \} \, \, \, = \, \, \, \mathbb{E} ( y_i^2 ) - +[\mathbb{E}(y_i)]^2 \\ & = \mathbb{E} [ ( \mathbf{X}_{i, \ast} \, +\beta + \varepsilon_i )^2] - ( \mathbf{X}_{i, \ast} \, \boldsymbol{\beta})^2 \\ & += \mathbb{E} [ ( \mathbf{X}_{i, \ast} \, \boldsymbol{\beta})^2 + 2 \varepsilon_i +\mathbf{X}_{i, \ast} \, \boldsymbol{\beta} + \varepsilon_i^2 ] - ( \mathbf{X}_{i, +\ast} \, \beta)^2 \\ & = ( \mathbf{X}_{i, \ast} \, \boldsymbol{\beta})^2 + 2 +\mathbb{E}(\varepsilon_i) \mathbf{X}_{i, \ast} \, \boldsymbol{\beta} + +\mathbb{E}(\varepsilon_i^2 ) - ( \mathbf{X}_{i, \ast} \, \boldsymbol{\beta})^2 +\\ & = \mathbb{E}(\varepsilon_i^2 ) \, \, \, = \, \, \, +\mbox{Var}(\varepsilon_i) \, \, \, = \, \, \, \sigma^2. +\end{align*} +$$ +

     
    + +Hence, \( y_i \sim \mathcal{N}( \mathbf{X}_{i, \ast} \, \boldsymbol{\beta}, \sigma^2) \), that is \( \boldsymbol{y} \) follows a normal distribution with +mean value \( \boldsymbol{X}\boldsymbol{\beta} \) and variance \( \sigma^2 \) (not be confused with the singular values of the SVD). +

    + + +
    +

    Expectation value and variance for \( \boldsymbol{\beta} \)

    + +

    +With the OLS expressions for the parameters \( \boldsymbol{\beta} \) we can evaluate the expectation value +

     
    +$$ +\mathbb{E}(\boldsymbol{\beta}) = \mathbb{E}[ (\mathbf{X}^{\top} \mathbf{X})^{-1}\mathbf{X}^{T} \mathbf{Y}]=(\mathbf{X}^{T} \mathbf{X})^{-1}\mathbf{X}^{T} \mathbb{E}[ \mathbf{Y}]=(\mathbf{X}^{T} \mathbf{X})^{-1} \mathbf{X}^{T}\mathbf{X}\boldsymbol{\beta}=\boldsymbol{\beta}. +$$ +

     
    + +This means that the estimator of the regression parameters is unbiased. + +

    +We can also calculate the variance + +

    +The variance of \( \boldsymbol{\beta} \) is +

     
    +$$ +\begin{eqnarray*} +\mbox{Var}(\boldsymbol{\beta}) & = & \mathbb{E} \{ [\boldsymbol{\beta} - \mathbb{E}(\boldsymbol{\beta})] [\boldsymbol{\beta} - \mathbb{E}(\boldsymbol{\beta})]^{T} \} +\\ +& = & \mathbb{E} \{ [(\mathbf{X}^{T} \mathbf{X})^{-1} \, \mathbf{X}^{T} \mathbf{Y} - \boldsymbol{\beta}] \, [(\mathbf{X}^{T} \mathbf{X})^{-1} \, \mathbf{X}^{T} \mathbf{Y} - \boldsymbol{\beta}]^{T} \} +\\ +% & = & \mathbb{E} \{ [(\mathbf{X}^{T} \mathbf{X})^{-1} \, \mathbf{X}^{T} \mathbf{Y}] \, [(\mathbf{X}^{T} \mathbf{X})^{-1} \, \mathbf{X}^{T} \mathbf{Y}]^{T} \} - \boldsymbol{\beta} \, \boldsymbol{\beta}^{T} +% \\ +% & = & \mathbb{E} \{ (\mathbf{X}^{T} \mathbf{X})^{-1} \, \mathbf{X}^{T} \mathbf{Y} \, \mathbf{Y}^{T} \, \mathbf{X} \, (\mathbf{X}^{T} \mathbf{X})^{-1} \} - \boldsymbol{\beta} \, \boldsymbol{\beta}^{T} +% \\ +& = & (\mathbf{X}^{T} \mathbf{X})^{-1} \, \mathbf{X}^{T} \, \mathbb{E} \{ \mathbf{Y} \, \mathbf{Y}^{T} \} \, \mathbf{X} \, (\mathbf{X}^{T} \mathbf{X})^{-1} - \boldsymbol{\beta} \, \boldsymbol{\beta}^{T} +\\ +& = & (\mathbf{X}^{T} \mathbf{X})^{-1} \, \mathbf{X}^{T} \, \{ \mathbf{X} \, \boldsymbol{\beta} \, \boldsymbol{\beta}^{T} \, \mathbf{X}^{T} + \sigma^2 \} \, \mathbf{X} \, (\mathbf{X}^{T} \mathbf{X})^{-1} - \boldsymbol{\beta} \, \boldsymbol{\beta}^{T} +% \\ +% & = & (\mathbf{X}^T \mathbf{X})^{-1} \, \mathbf{X}^T \, \mathbf{X} \, \boldsymbol{\beta} \, \boldsymbol{\beta}^T \, \mathbf{X}^T \, \mathbf{X} \, (\mathbf{X}^T % \mathbf{X})^{-1} +% \\ +% & & + \, \, \sigma^2 \, (\mathbf{X}^T \mathbf{X})^{-1} \, \mathbf{X}^T \, \mathbf{X} \, (\mathbf{X}^T \mathbf{X})^{-1} - \boldsymbol{\beta} \boldsymbol{\beta}^T +\\ +& = & \boldsymbol{\beta} \, \boldsymbol{\beta}^{T} + \sigma^2 \, (\mathbf{X}^{T} \mathbf{X})^{-1} - \boldsymbol{\beta} \, \boldsymbol{\beta}^{T} +\, \, \, = \, \, \, \sigma^2 \, (\mathbf{X}^{T} \mathbf{X})^{-1}, +\end{eqnarray*} +$$ +

     
    + +

    +where we have used that \( \mathbb{E} (\mathbf{Y} \mathbf{Y}^{T}) = +\mathbf{X} \, \boldsymbol{\beta} \, \boldsymbol{\beta}^{T} \, \mathbf{X}^{T} + +\sigma^2 \, \mathbf{I}_{nn} \). From \( \mbox{Var}(\boldsymbol{\beta}) = \sigma^2 +\, (\mathbf{X}^{T} \mathbf{X})^{-1} \), one obtains an estimate of the +variance of the estimate of the \( j \)-th regression coefficient: +\( \hat{\sigma}^2 (\hat{\beta}_j ) = \hat{\sigma}^2 \sqrt{ +[(\mathbf{X}^{T} \mathbf{X})^{-1}]_{jj} } \). This may be used to +construct a confidence interval for the estimates. + +

    +In a similar way, we cna obtain analytical expressions for say the +expectation values of the parameters \( \boldsymbol{\beta} \) and their variance +when we employ Ridge regression, and thereby a confidence interval. + +

    +It is rather straightforward to show that +

     
    +$$ +\mathbb{E} \big[ \boldsymbol{\beta}^{\mathrm{Ridge}} \big]=(\mathbf{X}^{T} \mathbf{X} + \lambda \mathbf{I}_{pp})^{-1} (\mathbf{X}^{\top} \mathbf{X})\boldsymbol{\beta}^{\mathrm{OLS}}. +$$ +

     
    + +We see clearly that +\( \mathbb{E} \big[ \boldsymbol{\beta}^{\mathrm{Ridge}} \big] \not= \boldsymbol{\beta}^{\mathrm{OLS}} \) for any \( \lambda > 0 \). We say then that the ridge estimator is biased. + +

    +We can also compute the variance as + +

     
    +$$ +\mbox{Var}[\boldsymbol{\beta}^{\mathrm{Ridge}}]=\sigma^2[ \mathbf{X}^{T} \mathbf{X} + \lambda \mathbf{I} ]^{-1} \mathbf{X}^{T} \mathbf{X} \{ [ \mathbf{X}^{\top} \mathbf{X} + \lambda \mathbf{I} ]^{-1}\}^{T}, +$$ +

     
    + +and it is easy to see that if the parameter \( \lambda \) goes to infinity then the variance of Ridge parameters \( \boldsymbol{\beta} \) goes to zero. + +

    +With this, we can compute the difference + +

     
    +$$ +\mbox{Var}[\boldsymbol{\beta}^{\mathrm{OLS}}]-\mbox{Var}(\boldsymbol{\beta}^{\mathrm{Ridge}})=\sigma^2 [ \mathbf{X}^{T} \mathbf{X} + \lambda \mathbf{I} ]^{-1}[ 2\lambda\mathbf{I} + \lambda^2 (\mathbf{X}^{T} \mathbf{X})^{-1} ] \{ [ \mathbf{X}^{T} \mathbf{X} + \lambda \mathbf{I} ]^{-1}\}^{T}. +$$ +

     
    + +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 \( \boldsymbol{\beta} \) obtained with the Ridge estimator. This has interesting consequences when we discuss the so-called bias-variance trade-off below. +

    + + +
    +

    Cross-validation

    Instead of choosing the penalty parameter to balance model fit with @@ -2598,12 +3069,15 @@ model complexity, cross-validation requires it (i.e. the penalty parameter) to yield a model with good prediction performance. Commonly, this performance is evaluated on novel data. Novel data need not be easy to come by and one has to make do -with the data at hand. The setting of `original' and novel data is +with the data at hand. + +

    +The setting of original and novel data is then mimicked by sample splitting: the data set is divided into two -(groups of samples). One of these two data sets, called the training -set, plays the role of `original' data on which the model is +(groups of samples). One of these two data sets, called the +training set, plays the role of original data on which the model is built. The second of these data sets, called the test set, plays the -role of the `novel' data and is used to evaluate the prediction +role of the novel data and is used to evaluate the prediction performance (often operationalized as the log-likelihood or the prediction error or its square or the R2 score) of the model built on the training data set. This procedure (model building and prediction evaluation on training and @@ -2621,7 +3095,7 @@ some sense) is then selected.

    -

    Computationally expensive

    +

    Computationally expensive

    The validation set approach is conceptually simple and is easy to implement. But it has two potential drawbacks: @@ -2634,7 +3108,7 @@ The validation set approach is conceptually simple and is easy to implement. But

    -

    Various steps in cross-validation

    +

    Various steps in cross-validation

    When the repetitive splitting of the data set is done randomly, @@ -2655,33 +3129,33 @@ cross-validation (LOOCV).

    -

    How to set up the cross-validation for Ridge and/or Lasso

    +

    How to set up the cross-validation for Ridge and/or Lasso

    • Define a range of interest for the penalty parameter.
    • Divide the data set into training and test set comprising samples \( \{1, \ldots, n\} \setminus i \) and \( \{ i \} \), respectively.
    • -

    • Fit the linear regression model by means of ridge estimation for each \( \lambda \) in the grid using the training set, and the corresponding estimate of the error variance \( \hat{\sigma}_{-i}^2(\lambda) \), as
    • +

    • Fit the linear regression model by means of ridge estimation for each \( \lambda \) in the grid using the training set, and the corresponding estimate of the error variance \( \boldsymbol{\sigma}_{-i}^2(\lambda) \), as

     
    $$ \begin{align*} -\hat{\beta}_{-i}(\lambda) & = ( \hat{X}_{-i, \ast}^{\top} -\hat{X}_{-i, \ast} + \lambda \hat{I}_{pp})^{-1} -\hat{X}_{-i, \ast}^{\top} \hat{y}_{-i} +\boldsymbol{\beta}_{-i}(\lambda) & = ( \boldsymbol{X}_{-i, \ast}^{T} +\boldsymbol{X}_{-i, \ast} + \lambda \boldsymbol{I}_{pp})^{-1} +\boldsymbol{X}_{-i, \ast}^{T} \boldsymbol{y}_{-i} \end{align*} $$

     

      -

    • Evaluate the prediction performance of these models on the test set by \( \log\{L[y_i, \hat{X}_{i, \ast}; \hat{\beta}_{-i}(\lambda), \hat{\sigma}_{-i}^2(\lambda)]\} \). Or, by the prediction error \( |y_i - \hat{X}_{i, \ast} \hat{\beta}_{-i}(\lambda)| \), the relative error, the error squared or the R2 score function.
    • +

    • Evaluate the prediction performance of these models on the test set by \( \log\{L[y_i, \boldsymbol{X}_{i, \ast}; \boldsymbol{\beta}_{-i}(\lambda), \boldsymbol{\sigma}_{-i}^2(\lambda)]\} \). Or, by the prediction error \( |y_i - \boldsymbol{X}_{i, \ast} \boldsymbol{\beta}_{-i}(\lambda)| \), the relative error, the error squared or the R2 score function.
    • Repeat the first three steps such that each sample plays the role of the test set once.
    • Average the prediction performances of the test sets at each grid point of the penalty bias/parameter by computing the cross-validated log-likelihood. It is an estimate of the prediction performance of the model corresponding to this value of the penalty parameter on novel data. It is defined as

     
    $$ \begin{align*} -\frac{1}{n} \sum_{i = 1}^n \log\{L[y_i, \mathbf{X}_{i, \ast}; \hat{\beta}_{-i}(\lambda), \hat{\sigma}_{-i}^2(\lambda)]\}. +\frac{1}{n} \sum_{i = 1}^n \log\{L[y_i, \mathbf{X}_{i, \ast}; \boldsymbol{\beta}_{-i}(\lambda), \boldsymbol{\sigma}_{-i}^2(\lambda)]\}. \end{align*} $$

     
    @@ -2694,32 +3168,7 @@ $$

    -

    Predicted Residual Error Sum of Squares

    -
    - -

    -Another approach in the LOOCV scheme is to the use the so-called Predicted Residual Error Sum of Squares (PRESS). - -

    -We can define the optimal penalty parameter to minimize -

     
    -$$ -\begin{align*} -\lambda_{\mbox{{\tiny opt}}} = \arg \min_{\lambda} \frac{1}{n} \sum_{i=1}^n [y_i - \hat{X}_{i, \ast} \hat{\beta}_{-i}(\lambda)]^2. -\end{align*} -$$ -

     
    - -

    -The LOOCV prediction performance can be -expressed analytically in terms of the known quantities derived from -the design matrix and the parameters \( \beta \). -

    -
    - - -
    -

    Resampling methods: Jackknife and Bootstrap

    +

    Resampling methods: Jackknife and Bootstrap

    Two famous @@ -2742,42 +3191,26 @@ need for bootstrapping.

    -

    Resampling methods: Jackknife

    +

    Resampling methods: Jackknife

    The Jackknife works by making many replicas of the estimator \( \widehat{\theta} \). -The jackknife is a resampling method, we explained that this happens by scrambling the data in some way. When using the jackknife, this is done by systematically leaving out one observation from the vector of observed values \( \hat{x} = (x_1,x_2,\cdots,X_n) \). -Let \( \hat{x}_i \) denote the vector +The jackknife is a resampling method where we systematically leave out one observation from the vector of observed values \( \boldsymbol{x} = (x_1,x_2,\cdots,X_n) \). +Let \( \boldsymbol{x}_i \) denote the vector

     
    $$ -\hat{x}_i = (x_1,x_2,\cdots,x_{i-1},x_{i+1},\cdots,x_n), +\boldsymbol{x}_i = (x_1,x_2,\cdots,x_{i-1},x_{i+1},\cdots,x_n), $$

     

    -which equals the vector \( \hat{x} \) with the exception that observation +which equals the vector \( \boldsymbol{x} \) with the exception that observation number \( i \) is left out. Using this notation, define \( \widehat{\theta}_i \) to be the estimator \( \widehat{\theta} \) computed using \( \vec{X}_i \).

    -
    -

    Resampling methods: Jackknife estimator

    - -

    -To get an estimate for the bias and -standard error of \( \widehat{\theta} \), use the following -estimators for each component of \( \widehat{\theta} \) - -

     
    -$$ -\widehat{\mathrm{Bias}}(\widehat \theta,\theta) = (n-1)\left( - \widehat{\theta} + \frac{1}{n}\sum_{i=1}^{n} \widehat \theta_i \right) \qquad \text{and} \qquad \widehat{\sigma}^2_{\widehat{\theta} } = \frac{n-1}{n}\sum_{i=1}^{n}( \widehat{\theta}_i - \frac{1}{n}\sum_{j=1}^{n}\widehat \theta_j )^2. -$$ -

     
    -

    - -

    Jackknife code example

    @@ -2841,14 +3274,14 @@ advantages:

    Resampling methods: Bootstrap background

    -Since \( \widehat{\theta} = \widehat{\theta}(\hat{X}) \) is a function of random variables, +Since \( \widehat{\theta} = \widehat{\theta}(\boldsymbol{X}) \) is a function of random variables, \( \widehat{\theta} \) itself must be a random variable. Thus it has -a pdf, call this function \( p(\hat{t}) \). The aim of the bootstrap is to -estimate \( p(\hat{t}) \) by the relative frequency of +a pdf, call this function \( p(\boldsymbol{t}) \). The aim of the bootstrap is to +estimate \( p(\boldsymbol{t}) \) by the relative frequency of \( \widehat{\theta} \). You can think of this as using a histogram -in the place of \( p(\hat{t}) \). If the relative frequency closely +in the place of \( p(\boldsymbol{t}) \). If the relative frequency closely resembles \( p(\vec{t}) \), then using numerics, it is straight forward to -estimate all the interesting parameters of \( p(\hat{t}) \) using point +estimate all the interesting parameters of \( p(\boldsymbol{t}) \) using point estimators.

    @@ -2872,7 +3305,7 @@ been straight forward to do this by: By repeated use of (1) and (2), many estimates of \( \widehat{\theta} \) could have been obtained. The idea is to use the relative frequency of \( \widehat{\theta}^* \) -(think of a histogram) as an estimate of \( p(\hat{t}) \). +(think of a histogram) as an estimate of \( p(\boldsymbol{t}) \).
    @@ -2893,7 +3326,7 @@ result in some asymptotic sense? The answer is yes. Instead of generating the histogram for the relative frequency of the observation \( X_i \), just draw the values \( (X_1^*,X_2^*,\cdots,X_n^*) \) with replacement from the vector -\( \hat{X} \). +\( \boldsymbol{X} \).
    @@ -2904,20 +3337,42 @@ frequency of the observation \( X_i \), just draw the values The independent bootstrap works like this:
      -

    1. Draw with replacement \( n \) numbers for the observed variables \( \hat{x} = (x_1,x_2,\cdots,x_n) \).
    2. -

    3. Define a vector \( \hat{x}^* \) containing the values which were drawn from \( \hat{x} \).
    4. -

    5. Using the vector \( \hat{x}^* \) compute \( \widehat{\theta}^* \) by evaluating \( \widehat \theta \) under the observations \( \hat{x}^* \).
    6. +

    7. Draw with replacement \( n \) numbers for the observed variables \( \boldsymbol{x} = (x_1,x_2,\cdots,x_n) \).
    8. +

    9. Define a vector \( \boldsymbol{x}^* \) containing the values which were drawn from \( \boldsymbol{x} \).
    10. +

    11. Using the vector \( \boldsymbol{x}^* \) compute \( \widehat{\theta}^* \) by evaluating \( \widehat \theta \) under the observations \( \boldsymbol{x}^* \).
    12. Repeat this process \( k \) times.

    -When you are done, you can draw a histogram of the relative frequency of \( \widehat \theta^* \). This is your estimate of the probability distribution \( p(t) \). Using this probability distribution you can estimate any statistics thereof. In principle you never draw the histogram of the relative frequency of \( \widehat{\theta}^* \). Instead you use the estimators corresponding to the statistic of interest. For example, if you are interested in estimating the variance of \( \widehat \theta \), apply the etsimator \( \widehat \sigma^2 \) to the values \( \widehat \theta ^* \). +When you are done, you can draw a histogram of the relative frequency +of \( \widehat \theta^* \). This is your estimate of the probability +distribution \( p(t) \). Using this probability distribution you can +estimate any statistics thereof. In principle you never draw the +histogram of the relative frequency of \( \widehat{\theta}^* \). Instead +you use the estimators corresponding to the statistic of interest. For +example, if you are interested in estimating the variance of \( \widehat +\theta \), apply the etsimator \( \widehat \sigma^2 \) to the values +\( \widehat \theta ^* \).

    Code example for the Bootstrap method

    -The following code starts with a Gaussian distribution with mean value \( \mu =100 \) and variance \( \sigma=15 \). We use this to generate the data used in the bootstrap analysis. The bootstrap analysis returns a data set after a given number of bootstrap operations (as many as we have data points). This data set consists of estimated mean values for each bootstrap operation. The histogram generated by the bootstrap method shows that the distribution for these mean values is also a Gaussian, centered around the mean value \( \mu=100 \) but with standard deviation \( \sigma/\sqrt{n} \), where \( n \) is the number of bootstrap samples (in this case the same as the number of original data points). The value of the standard deviation is what we expect from the central limit theorem. + +

    +The following code starts with a Gaussian distribution with mean value +\( \mu =100 \) and variance \( \sigma=15 \). We use this to generate the data +used in the bootstrap analysis. The bootstrap analysis returns a data +set after a given number of bootstrap operations (as many as we have +data points). This data set consists of estimated mean values for each +bootstrap operation. The histogram generated by the bootstrap method +shows that the distribution for these mean values is also a Gaussian, +centered around the mean value \( \mu=100 \) but with standard deviation +\( \sigma/\sqrt{n} \), where \( n \) is the number of bootstrap samples (in +this case the same as the number of original data points). The value +of the standard deviation is what we expect from the central limit +theorem. +

    @@ -2931,30 +3386,29 @@ The following code starts with a Gaussian distribution with mean value \( \mu =1 def stat(data): return mean(data) -# Bootstrap algorithm +# Bootstrap algorithm def bootstrap(data, statistic, R): t = zeros(R); n = len(data); inds = arange(n); t0 = time() - - # non-parametric bootstrap + # non-parametric bootstrap for i in range(R): t[i] = statistic(data[randint(0,n,n)]) - # analysis + # analysis print("Runtime: %g sec" % (time()-t0)); print("Bootstrap Statistics :") print("original bias std. error") - print("%8g %8g %14g %15g" % (statistic(data), std(data),\ - mean(t), \ - std(t))) + print("%8g %8g %14g %15g" % (statistic(data), std(data),mean(t),std(t))) return t mu, sigma = 100, 15 datapoints = 10000 x = mu + sigma*random.randn(datapoints) -# bootstrap returns the data sample t = bootstrap(x, stat, datapoints) -# the histogram of the bootstrapped data n, binsboot, patches = plt.hist(t, 50, normed=1, facecolor='red', alpha=0.75) +# bootstrap returns the data sample +t = bootstrap(x, stat, datapoints) +# the histogram of the bootstrapped data +n, binsboot, patches = plt.hist(t, 50, normed=1, facecolor='red', alpha=0.75) -# add a 'best fit' line +# add a 'best fit' line y = mlab.normpdf( binsboot, mean(t), std(t)) lt = plt.plot(binsboot, y, 'r--', linewidth=1) plt.xlabel('Smarts') @@ -2968,557 +3422,314 @@ plt.show()

    -

    Resampling methods: Blocking

    +

    Code Example for Cross-validation and \( k \)-fold Cross-validation

    -The blocking method was made popular by Flyvbjerg and Pedersen (1989) -and has become one of the standard ways to estimate -\( V(\widehat{\theta}) \) for exactly one \( \widehat{\theta} \), namely -\( \widehat{\theta} = \overline{X} \). - -

    -Assume \( n = 2^d \) for some integer \( d>1 \) and \( X_1,X_2,\cdots, X_n \) is a stationary time series to begin with. -Moreover, assume that the time series is asymptotically uncorrelated. We switch to vector notation by arranging \( X_1,X_2,\cdots,X_n \) in an \( n \)-tuple. Define: -

     
    -$$ -\begin{align*} -\hat{X} = (X_1,X_2,\cdots,X_n). -\end{align*} -$$ -

     
    - -

    -The strength of the blocking method is when the number of -observations, \( n \) is large. For large \( n \), the complexity of dependent -bootstrapping scales poorly, but the blocking method does not, -moreover, it becomes more accurate the larger \( n \) is. -

    - - -
    -

    Blocking Transformations

    - We now define -blocking transformations. The idea is to take the mean of subsequent -pair of elements from \( \vec{X} \) and form a new vector -\( \vec{X}_1 \). Continuing in the same way by taking the mean of -subsequent pairs of elements of \( \vec{X}_1 \) we obtain \( \vec{X}_2 \), and -so on. -Define \( \vec{X}_i \) recursively by: - -

     
    -$$ -\begin{align} -(\vec{X}_0)_k &\equiv (\vec{X})_k \nonumber \\ -(\vec{X}_{i+1})_k &\equiv \frac{1}{2}\Big( (\vec{X}_i)_{2k-1} + -(\vec{X}_i)_{2k} \Big) \qquad \text{for all} \qquad 1 \leq i \leq d-1 -\tag{21} -\end{align} -$$ -

     
    - -

    -The quantity \( \vec{X}_k \) is -subject to \( k \) blocking transformations. We now have \( d \) vectors -\( \vec{X}_0, \vec{X}_1,\cdots,\vec X_{d-1} \) containing the subsequent -averages of observations. It turns out that if the components of -\( \vec{X} \) is a stationary time series, then the components of -\( \vec{X}_i \) is a stationary time series for all \( 0 \leq i \leq d-1 \) - -

    -We can then compute the autocovariance, the variance, sample mean, and -number of observations for each \( i \). -Let \( \gamma_i, \sigma_i^2, -\overline{X}_i \) denote the autocovariance, variance and average of the -elements of \( \vec{X}_i \) and let \( n_i \) be the number of elements of -\( \vec{X}_i \). It follows by induction that \( n_i = n/2^i \). -

    - - -
    -

    Blocking Transformations

    - -

    -Using the -definition of the blocking transformation and the distributive -property of the covariance, it is clear that since \( h =|i-j| \) -we can define -

     
    -$$ -\begin{align} -\gamma_{k+1}(h) &= cov\left( ({X}_{k+1})_{i}, ({X}_{k+1})_{j} \right) \nonumber \\ -&= \frac{1}{4}cov\left( ({X}_{k})_{2i-1} + ({X}_{k})_{2i}, ({X}_{k})_{2j-1} + ({X}_{k})_{2j} \right) \nonumber \\ -&= \frac{1}{2}\gamma_{k}(2h) + \frac{1}{2}\gamma_k(2h+1) \hspace{0.1cm} \mathrm{h = 0} -\tag{22}\\ -&=\frac{1}{4}\gamma_k(2h-1) + \frac{1}{2}\gamma_k(2h) + \frac{1}{4}\gamma_k(2h+1) \quad \mathrm{else} -\tag{23} -\end{align} -$$ -

     
    - -

    -The quantity \( \hat{X} \) is asymptotic uncorrelated by assumption, \( \hat{X}_k \) is also asymptotic uncorrelated. Let's turn our attention to the variance of the sample mean \( V(\overline{X}) \). -

    - - -
    -

    Blocking Transformations, getting there

    -We have -

     
    -$$ -\begin{align} -V(\overline{X}_k) = \frac{\sigma_k^2}{n_k} + \underbrace{\frac{2}{n_k} \sum_{h=1}^{n_k-1}\left( 1 - \frac{h}{n_k} \right)\gamma_k(h)}_{\equiv e_k} = \frac{\sigma^2_k}{n_k} + e_k \quad \text{if} \quad \gamma_k(0) = \sigma_k^2. -\tag{24} -\end{align} -$$ -

     
    - -The term \( e_k \) is called the truncation error: -

     
    -$$ -\begin{equation} -e_k = \frac{2}{n_k} \sum_{h=1}^{n_k-1}\left( 1 - \frac{h}{n_k} \right)\gamma_k(h). -\tag{25} -\end{equation} -$$ -

     
    - -We can show that \( V(\overline{X}_i) = V(\overline{X}_j) \) for all \( 0 \leq i \leq d-1 \) and \( 0 \leq j \leq d-1 \). -

    - - -
    -

    Blocking Transformations, final expressions

    - -

    -We can then wrap up -

     
    -$$ -\begin{align} -n_{j+1} \overline{X}_{j+1} &= \sum_{i=1}^{n_{j+1}} (\hat{X}_{j+1})_i = \frac{1}{2}\sum_{i=1}^{n_{j}/2} (\hat{X}_{j})_{2i-1} + (\hat{X}_{j})_{2i} \nonumber \\ -&= \frac{1}{2}\left[ (\hat{X}_j)_1 + (\hat{X}_j)_2 + \cdots + (\hat{X}_j)_{n_j} \right] = \underbrace{\frac{n_j}{2}}_{=n_{j+1}} \overline{X}_j = n_{j+1}\overline{X}_j. -\tag{26} -\end{align} -$$ -

     
    - -By repeated use of this equation we get \( V(\overline{X}_i) = V(\overline{X}_0) = V(\overline{X}) \) for all \( 0 \leq i \leq d-1 \). This has the consequence that -

     
    -$$ -\begin{align} -V(\overline{X}) = \frac{\sigma_k^2}{n_k} + e_k \qquad \text{for all} \qquad 0 \leq k \leq d-1. \tag{27} -\end{align} -$$ -

     
    - -

    -Fyvbjerg and Petersen demonstrated that the sequence -\( \{e_k\}_{k=0}^{d-1} \) is decreasing, and conjecture that the term -\( e_k \) can be made as small as we would like by making \( k \) (and hence -\( d \)) sufficiently large. The sequence is decreasing (Master of Science thesis by Marius Jonsson, UiO 2018). -It means we can apply blocking transformations until -\( e_k \) is sufficiently small, and then estimate \( V(\overline{X}) \) by -\( \widehat{\sigma}^2_k/n_k \). -

    - - -
    -

    Code examples for Blocking, Jackknife and bootstrap

    - +The code here uses Ridge regression with cross-validation (CV) resampling and \( k \)-fold CV in order to fit a specific polynomial.

    -

    from sys import argv
    -from os import mkdir, path
    -import time
    -import numpy as np
    +
    import numpy as np
     import matplotlib.pyplot as plt
    -from matplotlib.ticker import FormatStrFormatter
    -from matplotlib.font_manager import FontProperties
    +from sklearn.model_selection import KFold
    +from sklearn.linear_model import Ridge
    +from sklearn.model_selection import cross_val_score
    +from sklearn.preprocessing import PolynomialFeatures
     
    -# Timing Decorator
    -def timeFunction(f):
    -    def wrap(*args):
    -        time1 = time.time()
    -        ret = f(*args)
    -        time2 = time.time()
    -        print '%s Function Took: \t %0.3f s' % (f.func_name.title(), (time2-time1))
    -        return ret
    -    return wrap
    +# A seed just to ensure that the random numbers are the same for every run.
    +# Useful for eventual debugging.
    +np.random.seed(3155)
     
    -class dataAnalysisClass:
    -    # General Init functions
    -    def __init__(self, fileName, size=0):
    -        self.inputFileName = fileName
    -        self.loadData(size)
    -        self.createOutputFolder()
    -        self.avg = np.average(self.data)
    -        self.var = np.var(self.data)
    -        self.std = np.std(self.data)
    +# Generate the data.
    +nsamples = 100
    +x = np.random.randn(nsamples)
    +y = 3*x**2 + np.random.randn(nsamples)
     
    -    def loadData(self, size=0):
    -        if size != 0:
    -            with open(self.inputFileName) as inputFile:
    -                self.data = np.zeros(size)
    -                for x in xrange(size):
    -                    self.data[x] = float(next(inputFile))
    -        else:
    -            self.data = np.loadtxt(self.inputFileName)
    +## Cross-validation on Ridge regression using KFold only
     
    -    # Statistical Analysis with Multiple Methods
    -    def runAllAnalyses(self):
    -        if len(self.data) <= 100000:
    -            print "Autocorrelation..."
    -            self.autocorrelation()
    -        print "Bootstrap..."
    -        self.bootstrap()
    -        print "Jackknife..."
    -        self.jackknife()
    -        print "Blocking..."
    -        self.blocking()
    +# Decide degree on polynomial to fit
    +poly = PolynomialFeatures(degree = 6)
     
    -    # Standard Autocorrelation
    -    @timeFunction
    -    def autocorrelation(self):
    -        self.acf = np.zeros(len(self.data)/2)
    -        for k in range(0, len(self.data)/2):
    -            self.acf[k] = np.corrcoef(np.array([self.data[0:len(self.data)-k], \
    -                                            self.data[k:len(self.data)]]))[0,1]
    +# Decide which values of lambda to use
    +nlambdas = 500
    +lambdas = np.logspace(-3, 5, nlambdas)
     
    -    # Bootstrap
    -    @timeFunction
    -    def bootstrap(self, nBoots = 1000):
    -        bootVec = np.zeros(nBoots)
    -        for k in range(0,nBoots):
    -            bootVec[k] = np.average(np.random.choice(self.data, len(self.data)))
    -        self.bootAvg = np.average(bootVec)
    -        self.bootVar = np.var(bootVec)
    -        self.bootStd = np.std(bootVec)
    +# Initialize a KFold instance
    +k = 5
    +kfold = KFold(n_splits = k)
     
    -    # Jackknife
    -    @timeFunction
    -    def jackknife(self):
    -        jackknVec = np.zeros(len(self.data))
    -        for k in range(0,len(self.data)):
    -            jackknVec[k] = np.average(np.delete(self.data, k))
    -        self.jackknAvg = self.avg - (len(self.data) - 1) * (np.average(jackknVec) - self.avg)
    -        self.jackknVar = float(len(self.data) - 1) * np.var(jackknVec)
    -        self.jackknStd = np.sqrt(self.jackknVar)
    +# Perform the cross-validation to estimate MSE
    +scores_KFold = np.zeros((nlambdas, k))
     
    -    # Blocking
    -    @timeFunction
    -    def blocking(self, blockSizeMax = 500):
    -        blockSizeMin = 1
    +i = 0
    +for lmb in lambdas:
    +    ridge = Ridge(alpha = lmb)
    +    j = 0
    +    for train_inds, test_inds in kfold.split(x):
    +        xtrain = x[train_inds]
    +        ytrain = y[train_inds]
     
    -        self.blockSizes = []
    -        self.meanVec = []
    -        self.varVec = []
    +        xtest = x[test_inds]
    +        ytest = y[test_inds]
     
    -        for i in range(blockSizeMin, blockSizeMax):
    -            if(len(self.data) % i != 0):
    -                pass#continue
    -            blockSize = i
    -            meanTempVec = []
    -            varTempVec = []
    -            startPoint = 0
    -            endPoint = blockSize
    +        Xtrain = poly.fit_transform(xtrain[:, np.newaxis])
    +        ridge.fit(Xtrain, ytrain[:, np.newaxis])
     
    -            while endPoint <= len(self.data):
    -                meanTempVec.append(np.average(self.data[startPoint:endPoint]))
    -                startPoint = endPoint
    -                endPoint += blockSize
    -            mean, var = np.average(meanTempVec), np.var(meanTempVec)/len(meanTempVec)
    -            self.meanVec.append(mean)
    -            self.varVec.append(var)
    -            self.blockSizes.append(blockSize)
    +        Xtest = poly.fit_transform(xtest[:, np.newaxis])
    +        ypred = ridge.predict(Xtest)
     
    -        self.blockingAvg = np.average(self.meanVec[-200:])
    -        self.blockingVar = (np.average(self.varVec[-200:]))
    -        self.blockingStd = np.sqrt(self.blockingVar)
    +        scores_KFold[i,j] = np.sum((ypred - ytest[:, np.newaxis])**2)/np.size(ypred)
    +
    +        j += 1
    +    i += 1
     
     
    +estimated_mse_KFold = np.mean(scores_KFold, axis = 1)
     
    -    # Plot of Data, Autocorrelation Function and Histogram
    -    def plotAll(self):
    -        self.createOutputFolder()
    -        if len(self.data) <= 100000:
    -            self.plotAutocorrelation()
    -        self.plotData()
    -        self.plotHistogram()
    -        self.plotBlocking()
    +## Cross-validation using cross_val_score from sklearn along with KFold
     
    -    # Create Output Plots Folder
    -    def createOutputFolder(self):
    -        self.outName = self.inputFileName[:-4]
    -        if not path.exists(self.outName):
    -            mkdir(self.outName)
    +# kfold is an instance initialized above as:
    +# kfold = KFold(n_splits = k)
     
    -    # Plot the Dataset, Mean and Std
    -    def plotData(self):
    -        # Far away plot
    -        font = {'fontname':'serif'}
    -        plt.plot(range(0, len(self.data)), self.data, 'r-', linewidth=1)
    -        plt.plot([0, len(self.data)], [self.avg, self.avg], 'b-', linewidth=1)
    -        plt.plot([0, len(self.data)], [self.avg + self.std, self.avg + self.std], 'g--', linewidth=1)
    -        plt.plot([0, len(self.data)], [self.avg - self.std, self.avg - self.std], 'g--', linewidth=1)
    -        plt.ylim(self.avg - 5*self.std, self.avg + 5*self.std)
    -        plt.gca().yaxis.set_major_formatter(FormatStrFormatter('%.4f'))
    -        plt.xlim(0, len(self.data))
    -        plt.ylabel(self.outName.title() + ' Monte Carlo Evolution', **font)
    -        plt.xlabel('MonteCarlo History', **font)
    -        plt.title(self.outName.title(), **font)
    -        plt.savefig(self.outName + "/data.eps")
    -        plt.savefig(self.outName + "/data.png")
    -        plt.clf()
    +estimated_mse_sklearn = np.zeros(nlambdas)
    +i = 0
    +for lmb in lambdas:
    +    ridge = Ridge(alpha = lmb)
     
    -    # Plot Histogram of Dataset and Gaussian around it
    -    def plotHistogram(self):
    -        binNumber = 50
    -        font = {'fontname':'serif'}
    -        count, bins, ignore = plt.hist(self.data, bins=np.linspace(self.avg - 5*self.std, self.avg + 5*self.std, binNumber))
    -        plt.plot([self.avg, self.avg], [0,np.max(count)+10], 'b-', linewidth=1)
    -        plt.ylim(0,np.max(count)+10)
    -        plt.ylabel(self.outName.title() + ' Histogram', **font)
    -        plt.xlabel(self.outName.title() , **font)
    -        plt.title('Counts', **font)
    +    X = poly.fit_transform(x[:, np.newaxis])
    +    estimated_mse_folds = cross_val_score(ridge, X, y[:, np.newaxis], scoring='neg_mean_squared_error', cv=kfold)
     
    -        #gaussian
    -        norm = 0
    -        for i in range(0,len(bins)-1):
    -            norm += (bins[i+1]-bins[i])*count[i]
    -        plt.plot(bins,  norm/(self.std * np.sqrt(2 * np.pi)) * np.exp( - (bins - self.avg)**2 / (2 * self.std**2) ), linewidth=1, color='r')
    -        plt.savefig(self.outName + "/hist.eps")
    -        plt.savefig(self.outName + "/hist.png")
    -        plt.clf()
    +    # cross_val_score return an array containing the estimated negative mse for every fold.
    +    # we have to the the mean of every array in order to get an estimate of the mse of the model
    +    estimated_mse_sklearn[i] = np.mean(-estimated_mse_folds)
     
    -    # Plot the Autocorrelation Function
    -    def plotAutocorrelation(self):
    -        font = {'fontname':'serif'}
    -        plt.plot(range(1, len(self.data)/2), self.acf[1:], 'r-')
    -        plt.ylim(-1, 1)
    -        plt.xlim(0, len(self.data)/2)
    -        plt.ylabel('Autocorrelation Function', **font)
    -        plt.xlabel('Lag', **font)
    -        plt.title('Autocorrelation', **font)
    -        plt.savefig(self.outName + "/autocorrelation.eps")
    -        plt.savefig(self.outName + "/autocorrelation.png")
    -        plt.clf()
    +    i += 1
     
    -    def plotBlocking(self):
    -        font = {'fontname':'serif'}
    -        plt.plot(self.blockSizes, self.varVec, 'r-')
    -        plt.ylabel('Variance', **font)
    -        plt.xlabel('Block Size', **font)
    -        plt.title('Blocking', **font)
    -        plt.savefig(self.outName + "/blocking.eps")
    -        plt.savefig(self.outName + "/blocking.png")
    -        plt.clf()
    +## Plot and compare the slightly different ways to perform cross-validation
     
    -    # Print Stuff to the Terminal
    -    def printOutput(self):
    -        print "\nSample Size:    \t", len(self.data)
    -        print "\n=========================================\n"
    -        print "Sample Average: \t", self.avg
    -        print "Sample Variance:\t", self.var
    -        print "Sample Std:     \t", self.std
    -        print "\n=========================================\n"
    -        print "Bootstrap Average: \t", self.bootAvg
    -        print "Bootstrap Variance:\t", self.bootVar
    -        print "Bootstrap Error:   \t", self.bootStd
    -        print "\n=========================================\n"
    -        print "Jackknife Average: \t", self.jackknAvg
    -        print "Jackknife Variance:\t", self.jackknVar
    -        print "Jackknife Error:   \t", self.jackknStd
    -        print "\n=========================================\n"
    -        print "Blocking Average: \t", self.blockingAvg
    -        print "Blocking Variance:\t", self.blockingVar
    -        print "Blocking Error:   \t", self.blockingStd, "\n"
    +plt.figure()
     
    -# Initialize the class
    -if len(argv) > 2:
    -    dataAnalysis = dataAnalysisClass(argv[1], int(argv[2]))
    -else:
    -    dataAnalysis = dataAnalysisClass(argv[1])
    +plt.plot(np.log10(lambdas), estimated_mse_sklearn, label = 'cross_val_score')
    +plt.plot(np.log10(lambdas), estimated_mse_KFold, 'r--', label = 'KFold')
     
    -# Run Analyses
    -dataAnalysis.runAllAnalyses()
    +plt.xlabel('log10(lambda)')
    +plt.ylabel('mse')
     
    -# Plot the data
    -dataAnalysis.plotAll()
    +plt.legend()
     
    -# Print Some Output
    -dataAnalysis.printOutput()
    +plt.show()
     
    -

    The bias-variance tradeoff

    +

    The bias-variance tradeoff

    -We begin with an unknown function \( y=f(x) \) and fix a \emph{hypothesis set} - \( \mathcal{H} \) consisting of all functions we are willing to consider, - defined also on the domain of \( f \). This set may be uncountably - infinite (e.g. if there are real-valued parameters to fit). -The - choice of which functions to include in \( \mathcal{H} \) usually depends - on our intuition about the problem of interest. The function \( f(x) \) - produces a set of pairs \( (x_i,y_i) \), \( i=1\dots N \), which serve as the - observable data. Our goal is to select a function from the hypothesis - set \( h\in\mathcal{H} \) which approximates \( f(x) \) as best as possible, - namely, we would like to find \( h\in\mathcal{H} \) such that \( h\approx - f \) in some strict mathematical sense which we specify below. If this - is possible, we say that we \emph{learned} \( f(x) \). But if the - function \( f(x) \) can, in principle, take any value on - \emph{unobserved} inputs, how is it possible to learn in any - meaningful sense? +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 + +

     
    +$$ +\boldsymbol{y}=f(\boldsymbol{x}) + \boldsymbol{\epsilon} +$$ +

     
    + +

    +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 +\( \boldsymbol{\beta} \) and the design matrix \( \boldsymbol{X} \) which embody our model, +that is \( \boldsymbol{\tilde{y}}=\boldsymbol{X}\boldsymbol{\beta} \). + +

    +Thereafter we found the parameters \( \boldsymbol{\beta} \) by optimizing the means squared error via the so-called cost function +

     
    +$$ +C(\boldsymbol{X},\boldsymbol{\beta}) =\frac{1}{n}\sum_{i=0}^{n-1}(y_i-\tilde{y}_i)^2=\mathbb{E}\left[(\boldsymbol{y}-\boldsymbol{\tilde{y}})^2\right]. +$$ +

     
    + +

    +We can rewrite this as +

     
    +$$ +\mathbb{E}\left[(\boldsymbol{y}-\boldsymbol{\tilde{y}})^2\right]=\frac{1}{n}\sum_i(f_i-\mathbb{E}\left[\boldsymbol{\tilde{y}}\right])^2+\frac{1}{n}\sum_i(\tilde{y}_i-\mathbb{E}\left[\boldsymbol{\tilde{y}}\right])^2+\sigma^2. +$$ +

     
    + +

    +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 \( \boldsymbol{\epsilon} \). + +

    +To derive this equation, we need to recall that the variance of \( \boldsymbol{y} \) and \( \boldsymbol{\epsilon} \) are both equal to \( \sigma^2 \). The mean value of \( \boldsymbol{\epsilon} \) is by definition equal to zero. Furthermore, the function \( f \) is not a stochastics variable, idem for \( \boldsymbol{\tilde{y}} \). +We use a more compact notation in terms of the expectation value +

     
    +$$ +\mathbb{E}\left[(\boldsymbol{y}-\boldsymbol{\tilde{y}})^2\right]=\mathbb{E}\left[(\boldsymbol{f}+\boldsymbol{\epsilon}-\boldsymbol{\tilde{y}})^2\right], +$$ +

     
    + +and adding and subtracting \( \mathbb{E}\left[\boldsymbol{\tilde{y}}\right] \) we get +

     
    +$$ +\mathbb{E}\left[(\boldsymbol{y}-\boldsymbol{\tilde{y}})^2\right]=\mathbb{E}\left[(\boldsymbol{f}+\boldsymbol{\epsilon}-\boldsymbol{\tilde{y}}+\mathbb{E}\left[\boldsymbol{\tilde{y}}\right]-\mathbb{E}\left[\boldsymbol{\tilde{y}}\right])^2\right], +$$ +

     
    + +which, using the abovementioned expectation values can be rewritten as +

     
    +$$ +\mathbb{E}\left[(\boldsymbol{y}-\boldsymbol{\tilde{y}})^2\right]=\mathbb{E}\left[(\boldsymbol{y}-\mathbb{E}\left[\boldsymbol{\tilde{y}}\right])^2\right]+\mathrm{Var}\left[\boldsymbol{\tilde{y}}\right]+\sigma^2, +$$ +

     
    + +that is the rewriting in terms of the so-called bias, the variance of the model \( \boldsymbol{\tilde{y}} \) and the variance of \( \boldsymbol{\epsilon} \).

    -

    Training and testing data

    - +

    Example code for 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=1\ldots N\} \). Let us assume that the true data is generated from a noisy model -

     
    -$$ -y=f(\boldsymbol{x}) + \epsilon -$$ -

     
    -where \( \epsilon \) is normally distributed with mean zero and standard deviation \( \sigma_\epsilon \). + +

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

    Procedure to find a predictor

    - +

    Understanding what happens

    -We have a statistical procedure (e.g. least-squares regression) for -forming a predictor \( \hat{g}_{\mathcal{L}}(\boldsymbol{x}) \) that gives the -prediction of our model for a new data point \( \boldsymbol{x} \). This estimator -is chosen by minimizing a cost function which we take to be the -squared error -

     
    -$$ - \mathcal{C}( \boldsymbol{X}, \hat{g}(\boldsymbol{x})) = \sum_i (y_i - \hat{g}_\mathcal{L}(\boldsymbol{x}_i))^2. -$$ -

     
    + +

    import matplotlib.pyplot as plt
    +import numpy as np
    +from sklearn.linear_model import LinearRegression, Ridge, Lasso
    +from sklearn.preprocessing import PolynomialFeatures
    +from sklearn.model_selection import train_test_split
    +from sklearn.pipeline import make_pipeline
    +from sklearn.utils import resample
    +
    +np.random.seed(2018)
    +
    +n = 40
    +n_boostraps = 100
    +maxdegree = 14
    +
    +
    +# Make data set.
    +x = np.linspace(-3, 3, n).reshape(-1, 1)
    +y = np.exp(-x**2) + 1.5 * np.exp(-(x-2)**2)+ np.random.normal(0, 0.1, x.shape)
    +error = np.zeros(maxdegree)
    +bias = np.zeros(maxdegree)
    +variance = np.zeros(maxdegree)
    +polydegree = np.zeros(maxdegree)
    +x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.2)
    +
    +for degree in range(maxdegree):
    +    model = make_pipeline(PolynomialFeatures(degree=degree), LinearRegression(fit_intercept=False))
    +    y_pred = np.empty((y_test.shape[0], n_boostraps))
    +    for i in range(n_boostraps):
    +        x_, y_ = resample(x_train, y_train)
    +        y_pred[:, i] = model.fit(x_, y_).predict(x_test).ravel()
    +
    +    polydegree[degree] = degree
    +    error[degree] = np.mean( np.mean((y_test - y_pred)**2, axis=1, keepdims=True) )
    +    bias[degree] = np.mean( (y_test - np.mean(y_pred, axis=1, keepdims=True))**2 )
    +    variance[degree] = np.mean( np.var(y_pred, axis=1, keepdims=True) )
    +    print('Polynomial degree:', degree)
    +    print('Error:', error[degree])
    +    print('Bias^2:', bias[degree])
    +    print('Var:', variance[degree])
    +    print('{} >= {} + {} = {}'.format(error[degree], bias[degree], variance[degree], bias[degree]+variance[degree]))
    +
    +plt.plot(polydegree, np.log10(error), label='Error')
    +plt.plot(polydegree, bias, label='bias')
    +plt.plot(polydegree, variance, label='Variance')
    +plt.legend()
    +plt.show()
    +
    -

    What we want

    - -

    -We are interested in the generalization error on all data drawn from -the true model, not just the error on the particular training dataset -\( \mathcal{L} \) that we have in hand. This is just the expectation of -the cost function over many different data sets -\( \{\mathcal{L}_j\} \). Denote this expectation value by -\( E_{\mathcal{L}} \). In other words, we can view \( \hat{g}_{\mathcal{L}} \) -as a stochastic functional that depends on the dataset \( \mathcal{L} \) -and we can think of \( E_{\mathcal{L}} \) as the expected value of the -functional if we drew an infinite number of datasets \( \{\mathcal{L}_1, -\mathcal{L}_2, \ldots \} \). -

    - - -
    -

    The expected generalization error

    - -

    -We would also like to average over different instances of the -"noise" \( \epsilon \) and we denote the expectation value over the -noise by \( E_\epsilon \). Thus, we can decompose the expected -generalization error as - -

     
    -$$ -\begin{align} -E_\mathcal{L, \epsilon}[\mathcal{C}( \boldsymbol{X}, \hat{g}(\boldsymbol{x})) ]&= E_\mathcal{L,\epsilon}\left[ \sum_i ({y}_i - \hat{g}_\mathcal{L}(\boldsymbol{x}_i))^2 \right] \nonumber \\ - &= E_\mathcal{L, \epsilon}\left[ \sum_{i}({y}_i -f(\boldsymbol{x}_i) +f(\boldsymbol{x}_i)- \hat{g}_\mathcal{L}(\boldsymbol{x}_i))^2\right] \nonumber \\ - &= \sum_i E_\epsilon[ ({y}_i -f(\boldsymbol{x}_i))^2 ]+ E_\mathcal{L, \epsilon}[(f(\boldsymbol{x}_i)- \hat{g}_\mathcal{L}(\boldsymbol{x}_i))^2] + 2E_\epsilon[{y}_i -f(\boldsymbol{x}_i)]E_\mathcal{L}[f(\boldsymbol{x}_i)- \hat{g}_\mathcal{L}(\boldsymbol{x}_i)] \nonumber \\ - &=\sum_i \sigma_\epsilon^2 + E_\mathcal{L}[(f(\boldsymbol{x}_i)- \hat{g}_\mathcal{L}(\boldsymbol{x}_i))^2], -\tag{28} -\end{align} -$$ -

     
    - -

    -where in the last line we used the fact that our noise has zero mean -and variance \( \sigma_\epsilon^2 \) and the sum over \( i \) applies to all -terms. -

    - - -
    -

    Elaborating a little bit more

    - -

    -It is also helpful to further decompose the second term as -follows: - -

     
    -$$ -\begin{align} -E_\mathcal{L}[(f(\boldsymbol{x}_i)- \hat{g}_\mathcal{L}(\boldsymbol{x}_i))^2] &=E_\mathcal{L}[(f(\mathbf{x}_i)-E_\mathcal{L}[\hat{g}_\mathcal{L}(\boldsymbol{x}_i)]+ E_\mathcal{L}[\hat{g}_\mathcal{L}(\boldsymbol{x}_i)]- \hat{g}_\mathcal{L}(\boldsymbol{x}_i))^2] \nonumber \\ -&=E_\mathcal{L}[(f(\boldsymbol{x}_i)-E_\mathcal{L}[\hat{g}_\mathcal{L}(\boldsymbol{x}_i)])^2] + E_\mathcal{L}[( \hat{g}_\mathcal{L}(\boldsymbol{x}_i)-E_\mathcal{L}[\hat{g}_\mathcal{L}(\boldsymbol{x}_i)])^2] \nonumber \\ -&+2E_\mathcal{L}[(f(\boldsymbol{x}_i)-E_\mathcal{L}[\hat{g}_\mathcal{L}(\boldsymbol{x}_i)])( \hat{g}_\mathcal{L}(\boldsymbol{x}_i)-E_\mathcal{L}[\hat{g}_\mathcal{L}(\boldsymbol{x}_i)])] \nonumber \\ -&=(f(\boldsymbol{x}_i)-E_\mathcal{L}[\hat{g}_\mathcal{L}(\boldsymbol{x}_i)])^2+E_\mathcal{L}[( \hat{g}_\mathcal{L}(\boldsymbol{x}_i)-E_\mathcal{L}[\hat{g}_\mathcal{L}(\boldsymbol{x}_i)])^2]. -\tag{29} -\end{align} -$$ -

     
    -

    - - -
    -

    The bias

    - -

    -The first term is called the bias -

     
    -$$ -Bias^2= \sum_i (f(\boldsymbol{x}_i)-E_\mathcal{L}[\hat{g}_\mathcal{L}(\boldsymbol{x}_i)])^2 -$$ -

     
    - -and measures the deviation of the expectation value of our estimator (i.e. the asymptotic value of our estimator in the infinite data limit) from the true value. -

    - - -
    -

    The variance

    -The second term is called the variance -

     
    -$$ -Var=\sum_i E_\mathcal{L}[( \hat{g}_\mathcal{L}(\boldsymbol{x}_i)-E_\mathcal{L}[\hat{g}_\mathcal{L}(\boldsymbol{x}_i)])^2], -$$ -

     
    - -

    -and measures how much our estimator fluctuates due to finite-sample effects. Combining these expressions, we see that the expected out-of-sample error of our model can be decomposed as -

     
    -$$ -E_\mathrm{out}=E_\mathcal{L, \epsilon}[\mathcal{C}( \boldsymbol{X}, \hat{g}(\boldsymbol{x})) ] = Bias^2 + Var + Noise. -$$ -

     
    +

    Summing up

    The bias-variance tradeoff summarizes the fundamental tension in machine learning, particularly supervised learning, between the complexity of a model and the amount of training data needed to train it. Since data is often limited, in practice it is often useful to -use a less-complex model with higher bias – a model whose asymptotic -performance is worse than another model – because it is easier to +use a less-complex model with higher bias, that is a model whose asymptotic +performance is worse than another model because it is easier to train and less sensitive to sampling noise arising from having a finite-sized training dataset (smaller variance). -

    - - -
    -

    Summing up

    The above equations tell us that in @@ -3542,16 +3753,101 @@ flexible statistical methods have higher variance.

    -

    The one-dimensional Ising model, project 2

    +

    Another Example rom Scikit-Learn's Repository

    +

    + + +

    """
    +============================
    +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()
    +
    +
    + + +
    +

    The one-dimensional Ising model

    -The one-dimensional Ising model with nearest neighbor interaction, no external field and a constant coupling constant \( J \) is given by +Let us bring back the Ising model again, but now with an additional +focus on Ridge and Lasso regression as well. We repeat some of the +basic parts of the Ising model and the setup of the training and test +data. The one-dimensional Ising model with nearest neighbor +interaction, no external field and a constant coupling constant \( J \) is +given by

     
    $$ \begin{align} H = -J \sum_{k}^L s_k s_{k + 1}, -\tag{30} +\tag{27} \end{align} $$

     
    @@ -3586,18 +3882,6 @@ energies = np.zeros(n) for i in range(n): energies[i] = - J * np.dot(spins[i], np.roll(spins[i], 1))

    -

    -Here we use linear (ordinary least squares), ridge and LASSO -regression to predict the energy in the nearest neighbor -one-dimensional Ising model on a ring, i.e., the endpoints wrap -around. We will use the linear regression models to fit a value for -the coupling constant to achieve this. - - - -

    -

    Reformulating the problem to suit regression

    -

    A more general form for the one-dimensional Ising model is @@ -3605,7 +3889,7 @@ A more general form for the one-dimensional Ising model is $$ \begin{align} H = - \sum_j^L \sum_k^L s_j s_k J_{jk}. -\tag{31} +\tag{28} \end{align} $$

     
    @@ -3618,7 +3902,7 @@ a matrix-product on the form $$ \begin{align} H = X J, -\tag{32} +\tag{29} \end{align} $$

     
    @@ -3630,12 +3914,13 @@ with the form utilized in linear regression, viz.

     
    $$ \begin{align} - y = X\omega + \epsilon, -\tag{33} + \boldsymbol{y} = \boldsymbol{X}\boldsymbol{\beta} + \boldsymbol{\epsilon}. +\tag{30} \end{align} $$

     
    +We organize the data as we did above

    @@ -3655,169 +3940,8 @@ X_test_own = np.concatenate( axis=1 )

    - - - -
    -

    Linear regression

    -

    -The problem at hand is to try to fit the equation -

     
    -$$ -\begin{align} - y = f(x) + \epsilon, -\tag{34} -\end{align} -$$ -

     
    - -

    -where \( f(x) \) is some unknown function of the data \( x \) and \( \epsilon \) -is normally distributed with mean zero noise with standard deviation -\( \sigma_{\epsilon} \). Our job is to try to find a predictor which -estimates the function \( f(x) \). In linear regression we assume that we -can formulate the problem as - -

     
    -$$ -\begin{align} - y = X\omega + \epsilon, -\tag{35} -\end{align} -$$ -

     
    - -

    -where \( X \) and \( \omega \) are now matrices. Our job at hand is now to -find a cost function \( C \), which we wish to minimize in order to find -the best estimate of \( \omega \). -

    - - -
    -

    Ordinary least squares

    - -

    -In the ordinary least squares method we choose the cost function -

     
    -$$ -\begin{align} - C(X, \omega) = ||X\omega - y||^2 - = (X\omega - y)^T(X\omega - y) -\tag{36} -\end{align} -$$ -

     
    - -We then find the extremal point of \( C \) by taking the derivative with respect to \( \omega \) and setting it to zero, i.e., - -

     
    -$$ -\begin{align} - \dfrac{\mathrm{d}C}{\mathrm{d}\omega} - = 0. -\tag{37} -\end{align} -$$ -

     
    - -This yields the expression for \( \omega \) to be -

     
    -$$ -\begin{align} - \omega = \frac{X^T y}{X^T X}, -\tag{38} -\end{align} -$$ -

     
    - -

    -which immediately imposes some requirements on \( X \) as there must exist -an inverse of \( X^T X \). If the expression we are modelling contains an -intercept, i.e., a constant expression we must make sure that the -first column of \( X \) consists of \( 1 \). - -

    - - -

    def get_ols_weights_naive(x: np.ndarray, y: np.ndarray) -> np.ndarray:
    -    return scl.inv(x.T @ x) @ (x.T @ y)
    -omega = get_ols_weights_naive(X_train_own, y_train)
    -
    -
    - - -
    -

    Singular Value decomposition

    -Doing the inversion directly turns out to be a bad idea as the matrix -\( X^TX \) is singular. An alternative approach is to use the singular -value decomposition. Using the definition of the Moore-Penrose -pseudoinverse we can write the equation for \( \omega \) as - -

     
    -$$ -\begin{align} - \omega = X^{+}y, -\tag{39} -\end{align} -$$ -

     
    - -where the pseudoinverse of \( X \) is given by -

     
    -$$ -\begin{align} - X^{+} = \frac{X^T}{X^T X}. -\tag{40} -\end{align} -$$ -

     
    - -

    -Using singular value decomposition we have that \( X = U\Sigma V^T \), -where \( X^{+} = V\Sigma^{+} U^T \). This reduces the equation for -\( \omega \) to -

     
    -$$ -\begin{align} - \omega = V\Sigma^{+} U^T y. -\tag{41} -\end{align} -$$ -

     
    - -

    -Note that solving this equation by actually doing the pseudoinverse -(which is what we will do) is not a good idea as this operation scales -as \( \mathcal{O}(n^3) \), where \( n \) is the number of elements in a -general matrix. Instead, doing \( QR \)-factorization and solving the -linear system as an equation would reduce this down to -\( \mathcal{O}(n^2) \) operations. - -

    - - -

    def get_ols_weights(x: np.ndarray, y: np.ndarray) -> np.ndarray:
    -    u, s, v = scl.svd(x)
    -    return v.T @ scl.pinv(scl.diagsvd(s, u.shape[0], v.shape[0])) @ u.T @ y
    -
    -

    -Before passing in the data to the function we append a column with ones to the training data. - -

    - - -

    omega = get_ols_weights(X_train_own,y_train)
    -
    -
    - - -
    -

    Fitting with scikit-learn

    - -

    -Next we fit a LinearRegression-model from Scikit-learn for comparison. +We will do all fitting with Scikit-Learn,

    @@ -3825,29 +3949,18 @@ Next we fit a LinearRegression-model from Scikit-learn for comparis

    clf = skl.LinearRegression().fit(X_train, y_train)
     

    -Extracting the \( J \)-matrix from both our own method and the Scikit-learn model where we make sure to remove the intercept. - +When extracting the \( J \)-matrix we make sure to remove the intercept

    -

    J_own = omega[1:].reshape(L, L)
    -J_sk = clf.coef_.reshape(L, L)
    +
    J_sk = clf.coef_.reshape(L, L)
     

    -A way of looking at the coefficients in \( J \) is to plot the matrices as images. - +And then we plot the results

    fig = plt.figure(figsize=(20, 14))
    -im = plt.imshow(J_own, **cmap_args)
    -plt.title("Home-made OLS", fontsize=18)
    -plt.xticks(fontsize=18)
    -plt.yticks(fontsize=18)
    -cb = fig.colorbar(im)
    -cb.ax.set_yticklabels(cb.ax.get_yticklabels(), fontsize=18)
    -
    -fig = plt.figure(figsize=(20, 14))
     im = plt.imshow(J_sk, **cmap_args)
     plt.title("LinearRegression from Scikit-learn", fontsize=18)
     plt.xticks(fontsize=18)
    @@ -3857,70 +3970,35 @@ cb.ax.set_yticklabels(cb.ax.get_yticklabels(), fontsize=Ridge regression 
    +

    Ridge regression

    Having explored the ordinary least squares we move on to ridge regression. In ridge regression we include a regularizer. This involves a new cost function which leads to a new estimate for the -weights \( \omega \). This results in a penalized regression problem. The +weights \( \boldsymbol{\beta} \). This results in a penalized regression problem. The cost function is given by

     
    $$ \begin{align} - C(X, \omega; \lambda) = ||X\omega - y||^2 + \lambda ||\omega||^2 - = (X\omega - y)^T(X\omega - y) + \lambda \omega^T\omega. -\tag{42} + C(\boldsymbol{X}, \boldsymbol{\beta}; \lambda) = (\boldsymbol{X}\boldsymbol{\beta} - \boldsymbol{y})^T(\boldsymbol{X}\boldsymbol{\beta} - \boldsymbol{y}) + \lambda \boldsymbol{\beta}^T\boldsymbol{\beta}. +\tag{31} \end{align} $$

     
    -Finding the extremum of this function yields the weights - -

     
    -$$ -\begin{align} - \omega(\lambda) = \frac{X^Ty}{X^TX + \lambda} \to \frac{\omega_{\text{LS}}}{1 + \lambda}, -\tag{43} -\end{align} -$$ -

     
    - -

    -where \( \omega_{\text{LS}} \) is the weights from ordinary least -squares. The last assumption assumes that \( X \) is orthogonal, which it -is not. We will therefore resort to solving the equation as it stands -on the left hand side. -

    -

    def get_ridge_weights(x: np.ndarray, y: np.ndarray, _lambda: float) -> np.ndarray:
    -    return x.T @ y @ scl.inv(
    -        x.T @ x + np.eye(x.shape[1], x.shape[1]) * _lambda
    -    )
    -_lambda = 0.1
    -omega_ridge = get_ridge_weights(X_train_own, y_train, np.array([_lambda]))
    +
    _lambda = 0.1
     clf_ridge = skl.Ridge(alpha=_lambda).fit(X_train, y_train)
    -J_ridge_own = omega_ridge[1:].reshape(L, L)
     J_ridge_sk = clf_ridge.coef_.reshape(L, L)
    -fig = plt.figure(figsize=(20, 14))
    -im = plt.imshow(J_ridge_own, **cmap_args)
    -plt.title("Home-made ridge regression", fontsize=18)
    -plt.xticks(fontsize=18)
    -plt.yticks(fontsize=18)
    -cb = fig.colorbar(im)
    -cb.ax.set_yticklabels(cb.ax.get_yticklabels(), fontsize=18)
    -
     fig = plt.figure(figsize=(20, 14))
     im = plt.imshow(J_ridge_sk, **cmap_args)
     plt.title("Ridge from Scikit-learn", fontsize=18)
    @@ -3935,22 +4013,22 @@ plt.show()
     
     
     
    -

    LASSO regression

    +

    LASSO regression

    In the Least Absolute Shrinkage and Selection Operator (LASSO)-method we get a third cost function. +

     
    $$ \begin{align} - C(X, \omega; \lambda) = - ||X\omega - y||^2 + \lambda ||\omega|| - = (X\omega - y)^T(X\omega - y) + \lambda \sqrt{\omega^T\omega}. -\tag{44} + C(\boldsymbol{X}, \boldsymbol{\beta}; \lambda) = (\boldsymbol{X}\boldsymbol{\beta} - \boldsymbol{y})^T(\boldsymbol{X}\boldsymbol{\beta} - \boldsymbol{y}) + \lambda \sqrt{\boldsymbol{\beta}^T\boldsymbol{\beta}}. +\tag{32} \end{align} $$

     
    -Finding the extremal point of this cost function is not so straight-forward as in least squares and ridge. We will therefore rely solely on the function ``Lasso`` from Scikit-learn. +

    +Finding the extremal point of this cost function is not so straight-forward as in least squares and ridge. We will therefore rely solely on the function ``Lasso`` from Scikit-Learn.

    @@ -3975,44 +4053,7 @@ constant as opposed to ridge and OLS. We get a sparse solution with

    -

    Performance of the different models

    - -

    -In order to judge which model performs best at varying values of \( \lambda \) (for ridge and LASSO) we compute \( R^2 \) which is given by - -

     
    -$$ -\begin{align} - R^2 = 1 - \frac{(y - \hat{y})^2}{(y - \bar{y})^2}, -\tag{45} -\end{align} -$$ -

     
    - -where \( y \) is a vector with the true values of the energy, \( \hat{y} \) is the predicted values of \( y \) from the models and \( \bar{y} \) is the mean of \( \hat{y} \). - -

    - - -

    def r_squared(y, y_hat):
    -    return 1 - np.sum((y - y_hat) ** 2) / np.sum((y - np.mean(y_hat)) ** 2)
    -
    -

    -This is the same metric used by Scikit-learn for their regression models when scoring. -

    - - -

    y_hat = clf.predict(X_test)
    -r_test = r_squared(y_test, y_hat)
    -sk_r_test = clf.score(X_test, y_test)
    -
    -assert abs(r_test - sk_r_test) < 1e-2
    -
    -
    - - -
    -

    Performance as function of the regularization parameter

    +

    Performance as function of the regularization parameter

    We see how the different models perform for a different set of values for \( \lambda \). @@ -4023,17 +4064,13 @@ We see how the different models perform for a different set of values for \( \la

    lambdas = np.logspace(-4, 5, 10)
     
     train_errors = {
    -    "ols_own": np.zeros(lambdas.size),
         "ols_sk": np.zeros(lambdas.size),
    -    "ridge_own": np.zeros(lambdas.size),
         "ridge_sk": np.zeros(lambdas.size),
         "lasso_sk": np.zeros(lambdas.size)
     }
     
     test_errors = {
    -    "ols_own": np.zeros(lambdas.size),
         "ols_sk": np.zeros(lambdas.size),
    -    "ridge_own": np.zeros(lambdas.size),
         "ridge_sk": np.zeros(lambdas.size),
         "lasso_sk": np.zeros(lambdas.size)
     }
    @@ -4043,30 +4080,6 @@ plot_counter = 1
     fig = plt.figure(figsize=(32, 54))
     
     for i, _lambda in enumerate(tqdm.tqdm(lambdas)):
    -    omega = get_ols_weights(X_train_own, y_train)
    -    y_hat_train = X_train_own @ omega
    -    y_hat_test = X_test_own @ omega
    -
    -    train_errors["ols_own"][i] = r_squared(y_train, y_hat_train)
    -    test_errors["ols_own"][i] = r_squared(y_test, y_hat_test)
    -
    -    plt.subplot(10, 5, plot_counter)
    -    plt.imshow(omega[1:].reshape(L, L), **cmap_args)
    -    plt.title("Home made OLS")
    -    plot_counter += 1
    -
    -    omega = get_ridge_weights(X_train_own, y_train, _lambda)
    -    y_hat_train = X_train_own @ omega
    -    y_hat_test = X_test_own @ omega
    -
    -    train_errors["ridge_own"][i] = r_squared(y_train, y_hat_train)
    -    test_errors["ridge_own"][i] = r_squared(y_test, y_hat_test)
    -
    -    plt.subplot(10, 5, plot_counter)
    -    plt.imshow(omega[1:].reshape(L, L), **cmap_args)
    -    plt.title(r"Home made ridge, $\lambda = %.4f$" % _lambda)
    -    plot_counter += 1
    -
         for key, method in zip(
             ["ols_sk", "ridge_sk", "lasso_sk"],
             [skl.LinearRegression(), skl.Ridge(alpha=_lambda), skl.Lasso(alpha=_lambda)]
    @@ -4086,7 +4099,7 @@ fig = plt.figure(figsize=(32, 
    -

    Finding the optimal value of \( \lambda \)

    +

    Finding the optimal value of \( \lambda \)

    To determine which value of \( \lambda \) is best we plot the accuracy of @@ -4110,8 +4123,6 @@ testing set that is close to the accuracy of the training set.

    fig = plt.figure(figsize=(20, 14))
     
     colors = {
    -    "ols_own": "b",
    -    "ridge_own": "g",
         "ols_sk": "r",
         "ridge_sk": "y",
         "lasso_sk": "c"
    @@ -4134,9 +4145,6 @@ colors = {
             label="Test {0}".format(key),
             linewidth=4.0
         )
    -#plt.semilogx(lambdas, train_errors["ols_own"], label="Train (OLS own)")
    -#plt.semilogx(lambdas, test_errors["ols_own"], label="Test (OLS own)")
    -
     plt.legend(loc="best", fontsize=18)
     plt.xlabel(r"$\lambda$", fontsize=18)
     plt.ylabel(r"$R^2$", fontsize=18)
    @@ -4145,11 +4153,265 @@ plt.show()
     

    From the above figure we can see that LASSO with \( \lambda = 10^{-2} \) -achieve a very good accuracy on the test set. This by far surpases the +achieves a very good accuracy on the test set. This by far surpasses the other models for all values of \( \lambda \).

    +
    +

    Further Exercises

    + +

    Exercise 1

    + +

    +We will generate our own dataset for a function \( y(x) \) where \( x \in [0,1] \) and defined by random numbers computed with the uniform distribution. The function \( y \) is a quadratic polynomial in \( x \) with added stochastic noise according to the normal distribution \( \cal {N}(0,1) \). +The following simple Python instructions define our \( x \) and \( y \) values (with 100 data points). +

    + + +

    x = np.random.rand(100,1)
    +y = 5*x*x+0.1*np.random.randn(100,1)
    +
    +
      +

    1. Write your own code (following the examples above) for computing the parametrization of the data set fitting a second-order polynomial.
    2. +

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

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

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

     
    + +and the \( R^2 \) score function. +If \( \tilde{\hat{y}}_i \) is the predicted value of the \( i-th \) sample and \( y_i \) is the corresponding true value, then the score \( R^2 \) is defined as +

     
    +$$ +R^2(\hat{y}, \tilde{\hat{y}}) = 1 - \frac{\sum_{i=0}^{n - 1} (y_i - \tilde{y}_i)^2}{\sum_{i=0}^{n - 1} (y_i - \bar{y})^2}, +$$ +

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

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

     
    + +

    +You can use the functionality included in scikit-learn. If you feel +for it, you can use your own program and define functions which +compute the above two functions. Discuss the meaning of these +results. Try also to vary the coefficient in front of the added +stochastic noise term and discuss the quality of the fits. + +

    Exercise 2, variance of the parameters \( \beta \) in linear regression

    + +

    +Show that the variance of the parameters \( \beta \) in the linear regression method (chapter 3, equation (3.8) of Trevor Hastie, Robert Tibshirani, Jerome H. Friedman, The Elements of Statistical Learning, Springer) is given as + +

     
    +$$ +\mathrm{Var}(\hat{\beta}) = \left(\hat{X}^T\hat{X}\right)^{-1}\sigma^2, +$$ +

     
    + +with +

     
    +$$ +\sigma^2 = \frac{1}{N-p-1}\sum_{i=1}^{N} (y_i-\tilde{y}_i)^2, +$$ +

     
    + +where we have assumed that we fit a function of degree \( p-1 \) (for example a polynomial in \( x \)). + +

    Exercise 3

    + +

    +This exercise is a continuation of exercise 1. We will +use the same function to generate our data set, still staying with a +simple function \( y(x) \) which we want to fit using linear regression, +but now extending the analysis to include the Ridge and the Lasso +regression methods. You can use the code under the Regression as an example on how to use the Ridge and the Lasso methods. + +

    +We will thus again generate our own dataset for a function \( y(x) \) where +\( x \in [0,1] \) and defined by random numbers computed with the uniform +distribution. The function \( y \) is a quadratic polynomial in \( x \) with +added stochastic noise according to the normal distribution \( \cal{N}(0,1) \). + +

    +The following simple Python instructions define our \( x \) and \( y \) values (with 100 data points). +

    + + +

    x = np.random.rand(100,1)
    +y = 5*x*x+0.1*np.random.randn(100,1)
    +
    +
      +

    1. Write your own code for the Ridge method and compute the parametrization for different values of \( \lambda \). Compare and analyze your results with those from exercise 1. Study the dependence on \( \lambda \) while also varying the strength of the noise in your expression for \( y(x) \).
    2. +

    3. Repeat the above but using the functionality of scikit-learn. Compare your code with the results from scikit-learn. Remember to run with the same random numbers for generating \( x \) and \( y \).
    4. +

    5. Our next step is to study the variance of the parameters \( \beta_1 \) and \( \beta_2 \) (assuming that we are parametrizing our function with a second-order polynomial. We will use standard linear regression and the Ridge regression. You can now opt for either writing your own function that calculates the variance of these paramaters (recall that this is equal to the diagonal elements of the matrix \( (\hat{X}^T\hat{X})+\lambda\hat{I})^{-1} \)) or use the functionality of scikit-learn and compute their variances. Discuss the results of these variances as functions
    6. +

    7. Repeat the previous step but add now the Lasso method. Discuss your results and compare with standard regression and the Ridge regression results.
    8. +

    9. Try to implement the cross-validation as well.
    10. +

    11. Finally, using scikit-learn or your own code, compute also the mean square error, a risk metric corresponding to the expected value of the squared (quadratic) error defined as
    12. +
    +

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

     
    + +and the \( R^2 \) score function. +If \( \tilde{\hat{y}}_i \) is the predicted value of the \( i-th \) sample and \( y_i \) is the corresponding true value, then the score \( R^2 \) is defined as +

     
    +$$ +R^2(\hat{y}, \tilde{\hat{y}}) = 1 - \frac{\sum_{i=0}^{n - 1} (y_i - \tilde{y}_i)^2}{\sum_{i=0}^{n - 1} (y_i - \bar{y})^2}, +$$ +

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

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

     
    + +Discuss these quantities as functions of the variable \( \lambda \) in the Ridge and Lasso regression methods. + +

    Exercise 4

    + +

    +We will study how +to fit polynomials to a specific two-dimensional function called +Franke's +function. This +is a function which has been widely used when testing various interpolation and fitting +algorithms. Furthermore, after having established the model and the +method, we will employ resamling techniques such as the cross-validation and/or +the bootstrap methods, in order to perform a proper assessment of our models. + +

    +The Franke function, which is a weighted sum of four exponentials reads as follows +

     
    +$$ +\begin{align*} +f(x,y) &= \frac{3}{4}\exp{\left(-\frac{(9x-2)^2}{4} - \frac{(9y-2)^2}{4}\right)}+\frac{3}{4}\exp{\left(-\frac{(9x+1)^2}{49}- \frac{(9y+1)}{10}\right)} \\ +&+\frac{1}{2}\exp{\left(-\frac{(9x-7)^2}{4} - \frac{(9y-3)^2}{4}\right)} -\frac{1}{5}\exp{\left(-(9x-4)^2 - (9y-7)^2\right) }. +\end{align*} +$$ +

     
    + +

    +The function will be defined for \( x,y\in [0,1] \). Our first step will +be to perform an OLS regression analysis of this function, trying out +a polynomial fit with an \( x \) and \( y \) dependence of the form \( [x, y, +x^2, y^2, xy, \dots] \). We will also include cross-validation and +bootstrap as resampling techniques. As in homeworks 1 and 2, we +can use a uniform distribution to set up the arrays of values for \( x \) +and \( y \), or as in the example below just a fix values for \( x \) and \( y \) with a given step size. +In this case we will have two predictors and need to fit a +function (for example a polynomial) of \( x \) and \( y \). Thereafter we will +repeat much of the same procedure using the the Ridge and +Lasso regression methods, introducing thus a dependence on the bias +(penalty) \( \lambda \). + +

    +The Python fucntion for the Franke function is included here (it performs also a three-dimensional plot of it) +

    + + +

    from mpl_toolkits.mplot3d import Axes3D
    +import matplotlib.pyplot as plt
    +from matplotlib import cm
    +from matplotlib.ticker import LinearLocator, FormatStrFormatter
    +import numpy as np
    +from random import random, seed
    +
    +fig = plt.figure()
    +ax = fig.gca(projection='3d')
    +
    +# Make data.
    +x = np.arange(0, 1, 0.05)
    +y = np.arange(0, 1, 0.05)
    +x, y = np.meshgrid(x,y)
    +
    +
    +def FrankeFunction(x,y):
    +    term1 = 0.75*np.exp(-(0.25*(9*x-2)**2) - 0.25*((9*y-2)**2))
    +    term2 = 0.75*np.exp(-((9*x+1)**2)/49.0 - 0.1*(9*y+1))
    +    term3 = 0.5*np.exp(-(9*x-7)**2/4.0 - 0.25*((9*y-3)**2))
    +    term4 = -0.2*np.exp(-(9*x-4)**2 - (9*y-7)**2)
    +    return term1 + term2 + term3 + term4
    +
    +
    +z = FrankeFunction(x, y)
    +
    +# Plot the surface.
    +surf = ax.plot_surface(x, y, z, cmap=cm.coolwarm,
    +                       linewidth=0, antialiased=False)
    +
    +# Customize the z axis.
    +ax.set_zlim(-0.10, 1.40)
    +ax.zaxis.set_major_locator(LinearLocator(10))
    +ax.zaxis.set_major_formatter(FormatStrFormatter('%.02f'))
    +
    +# Add a color bar which maps values to colors.
    +fig.colorbar(surf, shrink=0.5, aspect=5)
    +
    +plt.show()
    +
    +

    +We will thus again generate our own dataset for a function \( \mathrm{FrankeFunction}(x,y) \) where +\( x,y \in [0,1] \) could be defined by random numbers computed with the uniform +distribution. The function \( f(x,y) \) is the Franke function. You should explore also the addition +an added stochastic noise to this function using the normal distribution \( \cal{N}(0,1) \). + +

    +Write your own code (using either a matrix inversion or a singular value decomposition from e.g., numpy ) or use your code from exercises 1 and 3 +and perform a standard least square regression analysis using polynomials in \( x \) and \( y \) up to fifth order. Find the confidence intervals of the parameters \( \beta \) by computing their variances, evaluate the Mean Squared error (MSE) +

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

     
    + +and the \( R^2 \) score function. +If \( \tilde{\hat{y}}_i \) is the predicted value of the \( i-th \) sample and \( y_i \) is the corresponding true value, then the score \( R^2 \) is defined as +

     
    +$$ +R^2(\hat{y}, \tilde{\hat{y}}) = 1 - \frac{\sum_{i=0}^{n - 1} (y_i - \tilde{y}_i)^2}{\sum_{i=0}^{n - 1} (y_i - \bar{y})^2}, +$$ +

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

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

     
    + +

    +Perform a resampling of the data where you split the data in training data and test data. Implement the \( k \)-fold cross-validation algorithm and/or the bootstrap algorithm +and evaluate again the MSE and the \( R^2 \) functions resulting from the test data. Evaluate also the bias and variance of the final models. + +

    +Write then your own code for the Ridge method, either using matrix +inversion or the singular value decomposition as done for standard OLS. Perform the same analysis as in the +previous exercise (for the same polynomials and include resampling +techniques) but now for different values of \( \lambda \). Compare and +analyze your results with those obtained with standard OLS. Study the +dependence on \( \lambda \) while also varying eventually the strength of +the noise in your expression for \( \mathrm{FrankeFunction}(x,y) \). + +

    +Then perform the same studies but now with Lasso regression. Use the functionalities of +scikit-learn. Give a critical discussion of the three methods and a +judgement of which model fits the data best. +

    + +
    diff --git a/doc/pub/Regression/html/Regression-solarized.html b/doc/pub/Regression/html/Regression-solarized.html index fc93c73e8..78714de20 100644 --- a/doc/pub/Regression/html/Regression-solarized.html +++ b/doc/pub/Regression/html/Regression-solarized.html @@ -6,6 +6,7 @@ Automatically generated HTML file from DocOnce source + Data Analysis and Machine Learning: Linear Regression and more Advanced Regression Analysis @@ -60,160 +61,151 @@ div { text-align: justify; text-justify: inter-word; } @@ -310,59 +287,84 @@ MathJax.Hub.Config({
    [2] Department of Physics and Astronomy and National Superconducting Cyclotron Laboratory, Michigan State University

    -

    Oct 18, 2018

    +

    Jun 10, 2019












    -

    Regression analysis, overarching aims

    +

    Why Linear Regression (aka Ordinary Least Squares and family)

    + +

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

      +
    • Method of choice for fitting a continuous function!
    • +
    • Gives an excellent introduction to central Machine Learning features with understandable pedagogical links to other methods like Neural Networks, Support Vector Machines etc
    • +
    • Analytical expression for the fitting parameters \( \boldsymbol{\beta} \)
    • +
    • Analytical expressions for statistical propertiers like mean values, variances, confidence intervals and more
    • +
    • Analytical relation with probabilistic interpretations
    • +
    • Easy to introduce basic concepts like bias-variance tradeoff, cross-validation, resampling and regularization techniques and many other ML topics
    • +
    • Easy to code! And links well with classification problems and logistic regression and neural networks
    • +
    • Allows for easy hands-on understanding of gradient descent methods
    • +
    • and many more features
    • +
    + +For more discussions of Ridge and Lasso regression, Wessel van Wieringen's article is highly recommended. +Similarly, Mehta et al's article is also recommended. + +

    +









    + +

    Regression analysis, overarching aims

    -Regression modeling deals with the description of the sampling distribution of a given random variable \( y \) varies as function of another variable or a set of such variables \( \hat{x} =[x_0, x_1,\dots, x_p]^T \). -The first variable is called the dependent, the outcome or the response variable while the set of variables \( \hat{x} \) is called the independent variable, or the predictor variable or the explanatory variable. +Regression modeling deals with the description of the sampling distribution of a given random variable \( y \) and how it varies as function of another variable or a set of such variables \( \boldsymbol{x} =[x_0, x_1,\dots, x_{n-1}]^T \). +The first variable is called the dependent, the outcome or the response variable while the set of variables \( \boldsymbol{x} \) is called the independent variable, or the predictor variable or the explanatory variable.

    -A regression model aims at finding a likelihood function \( p(y\vert \hat{x}) \), that is the conditional distribution for \( y \) with a given \( \hat{x} \). The estimation of \( p(y\vert \hat{x}) \) is made using a data set with +A regression model aims at finding a likelihood function \( p(\boldsymbol{y}\vert \boldsymbol{x}) \), that is the conditional distribution for \( \boldsymbol{y} \) with a given \( \boldsymbol{x} \). The estimation of \( p(\boldsymbol{y}\vert \boldsymbol{x}) \) is made using a data set with

    • \( n \) cases \( i = 0, 1, 2, \dots, n-1 \)
    • -
    • Response (dependent or outcome) variable \( y_i \) with \( i = 0, 1, 2, \dots, n-1 \)
    • -
    • \( p \) Explanatory (independent or predictor) variables \( \hat{x}_i=[x_{i0}, x_{i1}, \dots, x_{ip}] \) with \( i = 0, 1, 2, \dots, n-1 \)
    • +
    • Response (target, dependent or outcome) variable \( y_i \) with \( i = 0, 1, 2, \dots, n-1 \)
    • +
    • \( p \) so-called explanatory (independent or predictor) variables \( \boldsymbol{x}_i=[x_{i0}, x_{i1}, \dots, x_{ip-1}] \) with \( i = 0, 1, 2, \dots, n-1 \) and explanatory variables running from \( 0 \) to \( p-1 \). See below for more explicit examples.
    - The goal of the regression analysis is to extract/exploit relationship between \( y_i \) and \( \hat{x}_i \) in or to infer causal dependencies, approximations to the likelihood functions, functional relationships and to make predictions . + The goal of the regression analysis is to extract/exploit relationship between \( \boldsymbol{y} \) and \( \boldsymbol{X} \) in or to infer causal dependencies, approximations to the likelihood functions, functional relationships and to make predictions, making fits and many other things.











    -

    Regression analysis, overarching aims II

    +

    Regression analysis, overarching aims II

    Consider an experiment in which \( p \) characteristics of \( n \) samples are -measured. The data from this experiment are denoted \( \mathbf{X} \), with -\( \mathbf{X} \) as above. The matrix \( \mathbf{X} \) is called the design +measured. The data from this experiment, for various explanatory variables \( p \) are normally represented by a matrix +\( \mathbf{X} \). + +

    +The matrix \( \mathbf{X} \) is called the design matrix. Additional information of the samples is available in the -form of \( \mathbf{Y} \) (also as above). The variable \( \mathbf{Y} \) is +form of \( \boldsymbol{y} \) (also as above). The variable \( \boldsymbol{y} \) is generally referred to as the response variable. The aim of -regression analysis is to explain \( \mathbf{Y} \) in terms of -\( \mathbf{X} \) through a functional relationship like \( Y_i = +regression analysis is to explain \( \boldsymbol{y} \) in terms of +\( \boldsymbol{X} \) through a functional relationship like \( y_i = f(\mathbf{X}_{i,\ast}) \). When no prior knowledge on the form of \( f(\cdot) \) is available, it is common to assume a linear relationship -between \( \mathbf{X} \) and \( \mathbf{Y} \). This assumption gives rise to -the linear regression model where \( \beta = (\beta_1, \ldots, -\beta_p)^{\top} \) is the regression parameter. The parameter -\( \beta_j \), \( j=1, \ldots, p \), represents the effect size of covariate -\( j \) on the response. That is, for each unit change in covariate \( j \) -(while keeping the other covariates fixed) the observed change in the -response is equal to \( \beta_j \). +between \( \boldsymbol{X} \) and \( \boldsymbol{y} \). This assumption gives rise to +the linear regression model where \( \boldsymbol{\beta} = [\beta_0, \ldots, +\beta_{p-1}]^{T} \) are the regression parameters. + +

    +Linear regression gives us a set of analytical equations for the parameters \( \beta_j \).

    @@ -371,16 +373,45 @@ response is equal to \( \beta_j \).











    -

    General linear models

    +

    Examples

    -Before we proceed let us study a case from linear algebra where we aim at fitting a set of data \( \hat{y}=[y_0,y_1,\dots,y_{n-1}] \). We could think of these data as a result of an experiment or a complicated numerical experiment. These data are functions of a series of variables \( \hat{x}=[x_0,x_1,\dots,x_{n-1}] \), that is \( y_i = y(x_i) \) with \( i=0,1,2,\dots,n-1 \). The variables \( x_i \) could represent physical quantities like time, temperature, position etc. We assume that \( y(x) \) is a smooth function. +In order to understand the relation among the predictors \( p \), the set of data \( n \) and the target (outcome, output etc) \( \boldsymbol{y} \), +consider the model we discussed for describing nuclear binding energies. + +

    +There we assumed that we could parametrize the data using a polynomial approximation based on the liquid drop model. +Assuming +$$ +BE(A) = a_0+a_1A+a_2A^{2/3}+a_3A^{-1/3}+a_4A^{-1}, +$$ + +we have five predictors, that is the intercept, the \( A \) dependent term, the \( A^{2/3} \) term and the \( A^{-1/3} \) and \( A^{-1} \) terms. +This gives \( p=0,1,2,3,4 \). Furthermore we have \( n \) entries for each predictor. It means that our design matrix is a +\( p\times n \) matrix \( \boldsymbol{X} \). + +

    +Here the predictors are based on a model we have made. A popular data set which is widely encountered in ML applications is the +so-called credit card default data from Taiwan. The data set contains data on \( n=30000 \) credit card holders with predictors like gender, marital status, age, profession, education, etc. In total there are \( 24 \) such predictors or attributes leading to a design matrix of dimensionality \( 24 \times 30000 \) + + +

    + + +

    +









    + +

    General linear models

    +
    + +

    +Before we proceed let us study a case from linear algebra where we aim at fitting a set of data \( \boldsymbol{y}=[y_0,y_1,\dots,y_{n-1}] \). We could think of these data as a result of an experiment or a complicated numerical experiment. These data are functions of a series of variables \( \boldsymbol{x}=[x_0,x_1,\dots,x_{n-1}] \), that is \( y_i = y(x_i) \) with \( i=0,1,2,\dots,n-1 \). The variables \( x_i \) could represent physical quantities like time, temperature, position etc. We assume that \( y(x) \) is a smooth function.

    Since obtaining these data points may not be trivial, we want to use these data to fit a function which can allow us to make predictions for values of \( y \) which are not in the present set. The perhaps simplest approach is to assume we can parametrize our function in terms of a polynomial of degree \( n-1 \) with \( n \) points, that is $$ -y=y(x) \rightarrow y(x_i)=\tilde{y}_i+\epsilon_i=\sum_{j=0}^{n-1} \beta_i x_i^j+\epsilon_i, +y=y(x) \rightarrow y(x_i)=\tilde{y}_i+\epsilon_i=\sum_{j=0}^{n-1} \beta_j x_i^j+\epsilon_i, $$ where \( \epsilon_i \) is the error in our approximation. @@ -392,7 +423,7 @@ where \( \epsilon_i \) is the error in our approximation.











    -

    Rewriting the fitting procedure as a linear algebra problem

    +

    Rewriting the fitting procedure as a linear algebra problem

    @@ -403,7 +434,7 @@ y_0&=\beta_0+\beta_1x_0^1+\beta_2x_0^2+\dots+\beta_{n-1}x_0^{n-1}+\epsilon_0\\ y_1&=\beta_0+\beta_1x_1^1+\beta_2x_1^2+\dots+\beta_{n-1}x_1^{n-1}+\epsilon_1\\ y_2&=\beta_0+\beta_1x_2^1+\beta_2x_2^2+\dots+\beta_{n-1}x_2^{n-1}+\epsilon_2\\ \dots & \dots \\ -y_{n-1}&=\beta_0+\beta_1x_{n-1}^1+\beta_2x_{n-1}^2+\dots+\beta_1x_{n-1}^{n-1}+\epsilon_{n-1}.\\ +y_{n-1}&=\beta_0+\beta_1x_{n-1}^1+\beta_2x_{n-1}^2+\dots+\beta_{n-1}x_{n-1}^{n-1}+\epsilon_{n-1}.\\ \end{align*} $$

    @@ -412,28 +443,28 @@ $$











    -

    Rewriting the fitting procedure as a linear algebra problem, follows

    +

    Rewriting the fitting procedure as a linear algebra problem, more details

    Defining the vectors $$ -\hat{y} = [y_0,y_1, y_2,\dots, y_{n-1}]^T, +\boldsymbol{y} = [y_0,y_1, y_2,\dots, y_{n-1}]^T, $$ and $$ -\hat{\beta} = [\beta_0,\beta_1, \beta_2,\dots, \beta_{n-1}]^T, +\boldsymbol{\beta} = [\beta_0,\beta_1, \beta_2,\dots, \beta_{n-1}]^T, $$ and $$ -\hat{\epsilon} = [\epsilon_0,\epsilon_1, \epsilon_2,\dots, \epsilon_{n-1}]^T, +\boldsymbol{\epsilon} = [\epsilon_0,\epsilon_1, \epsilon_2,\dots, \epsilon_{n-1}]^T, $$ -and the matrix +and the design matrix $$ -\hat{X}= +\boldsymbol{X}= \begin{bmatrix} 1& x_{0}^1 &x_{0}^2& \dots & \dots &x_{0}^{n-1}\\ 1& x_{1}^1 &x_{1}^2& \dots & \dots &x_{1}^{n-1}\\ @@ -445,20 +476,28 @@ $$ we can rewrite our equations as $$ -\hat{y} = \hat{X}\hat{\beta}+\hat{\epsilon}. +\boldsymbol{y} = \boldsymbol{X}\boldsymbol{\beta}+\boldsymbol{\epsilon}. $$ + +The above design matrix is called a Vandermonde matrix.











    -

    Generalizing the fitting procedure as a linear algebra problem

    +

    Generalizing the fitting procedure as a linear algebra problem

    -We are obviously not limited to the above polynomial. We could replace the various powers of \( x \) with elements of Fourier series, that is, instead of \( x_i^j \) we could have \( \cos{(j x_i)} \) or \( \sin{(j x_i)} \), or time series or other orthogonal functions. -For every set of values \( y_i,x_i \) we can then generalize the equations to + +

    +We are obviously not limited to the above polynomial expansions. We +could replace the various powers of \( x \) with elements of Fourier +series or instead of \( x_i^j \) we could have \( \cos{(j x_i)} \) or \( \sin{(j +x_i)} \), or time series or other orthogonal functions. For every set +of values \( y_i,x_i \) we can then generalize the equations to + $$ \begin{align*} y_0&=\beta_0x_{00}+\beta_1x_{01}+\beta_2x_{02}+\dots+\beta_{n-1}x_{0n-1}+\epsilon_0\\ @@ -467,22 +506,25 @@ y_2&=\beta_0x_{20}+\beta_1x_{21}+\beta_2x_{22}+\dots+\beta_{n-1}x_{2n-1}+\epsilo \dots & \dots \\ y_{i}&=\beta_0x_{i0}+\beta_1x_{i1}+\beta_2x_{i2}+\dots+\beta_{n-1}x_{in-1}+\epsilon_i\\ \dots & \dots \\ -y_{n-1}&=\beta_0x_{n-1,0}+\beta_1x_{n-1,2}+\beta_2x_{n-1,2}+\dots+\beta_1x_{n-1,n-1}+\epsilon_{n-1}.\\ +y_{n-1}&=\beta_0x_{n-1,0}+\beta_1x_{n-1,2}+\beta_2x_{n-1,2}+\dots+\beta_{n-1}x_{n-1,n-1}+\epsilon_{n-1}.\\ \end{align*} $$ + +

    +Note that we have \( p=n \) here. The matrix is symmetric. This is generally not the case!











    -

    Generalizing the fitting procedure as a linear algebra problem

    +

    Generalizing the fitting procedure as a linear algebra problem

    -We redefine in turn the matrix \( \hat{X} \) as +We redefine in turn the matrix \( \boldsymbol{X} \) as $$ -\hat{X}= +\boldsymbol{X}= \begin{bmatrix} x_{00}& x_{01} &x_{02}& \dots & \dots &x_{0,n-1}\\ x_{10}& x_{11} &x_{12}& \dots & \dots &x_{1,n-1}\\ @@ -494,21 +536,21 @@ $$ and without loss of generality we rewrite again our equations as $$ -\hat{y} = \hat{X}\hat{\beta}+\hat{\epsilon}. +\boldsymbol{y} = \boldsymbol{X}\boldsymbol{\beta}+\boldsymbol{\epsilon}. $$ -The left-hand side of this equation forms know. Our error vector \( \hat{\epsilon} \) and the parameter vector \( \hat{\beta} \) are our unknow quantities. How can we obtain the optimal set of \( \beta_i \) values? +The left-hand side of this equation is kwown. Our error vector \( \boldsymbol{\epsilon} \) and the parameter vector \( \boldsymbol{\beta} \) are our unknow quantities. How can we obtain the optimal set of \( \beta_i \) values?











    -

    Optimizing our parameters

    +

    Optimizing our parameters

    -We have defined the matrix \( \hat{X} \) +We have defined the matrix \( \boldsymbol{X} \) via the equations $$ \begin{align*} y_0&=\beta_0x_{00}+\beta_1x_{01}+\beta_2x_{02}+\dots+\beta_{n-1}x_{0n-1}+\epsilon_0\\ @@ -517,69 +559,196 @@ y_2&=\beta_0x_{20}+\beta_1x_{21}+\beta_2x_{22}+\dots+\beta_{n-1}x_{2n-1}+\epsilo \dots & \dots \\ y_{i}&=\beta_0x_{i0}+\beta_1x_{i1}+\beta_2x_{i2}+\dots+\beta_{n-1}x_{in-1}+\epsilon_1\\ \dots & \dots \\ -y_{n-1}&=\beta_0x_{n-1,0}+\beta_1x_{n-1,2}+\beta_2x_{n-1,2}+\dots+\beta_1x_{n-1,n-1}+\epsilon_{n-1}.\\ +y_{n-1}&=\beta_0x_{n-1,0}+\beta_1x_{n-1,2}+\beta_2x_{n-1,2}+\dots+\beta_{n-1}x_{n-1,n-1}+\epsilon_{n-1}.\\ \end{align*} $$ + +

    +As we noted above, we stayed with a system with the design matrix + \( \boldsymbol{X}\in {\mathbb{R}}^{n\times n} \), that is we have \( p=n \). For reasons to come later (algorithmic arguments) we will hereafter define +our matrix as \( \boldsymbol{X}\in {\mathbb{R}}^{n\times p} \), with the predictors refering to the column numbers and the entries \( n \) being the row elements. + +











    -

    Optimizing our parameters, more details

    +

    Our model for the nuclear binding energies

    + +

    +In our introductory notes we looked at the so-called liguid drop model. Let us remind ourselves about what we did by looking at the code. + +

    +We restate the parts of the code we are most interested in. +

    + + +

    # Common imports
    +import numpy as np
    +import pandas as pd
    +import matplotlib.pyplot as plt
    +from IPython.display import display
    +import os
    +
    +# Where to save the figures and data files
    +PROJECT_ROOT_DIR = "Results"
    +FIGURE_ID = "Results/FigureFiles"
    +DATA_ID = "DataFiles/"
    +
    +if not os.path.exists(PROJECT_ROOT_DIR):
    +    os.mkdir(PROJECT_ROOT_DIR)
    +
    +if not os.path.exists(FIGURE_ID):
    +    os.makedirs(FIGURE_ID)
    +
    +if not os.path.exists(DATA_ID):
    +    os.makedirs(DATA_ID)
    +
    +def image_path(fig_id):
    +    return os.path.join(FIGURE_ID, fig_id)
    +
    +def data_path(dat_id):
    +    return os.path.join(DATA_ID, dat_id)
    +
    +def save_fig(fig_id):
    +    plt.savefig(image_path(fig_id) + ".png", format='png')
    +
    +infile = open(data_path("MassEval2016.dat"),'r')
    +
    +
    +# Read the experimental data with Pandas
    +Masses = pd.read_fwf(infile, usecols=(2,3,4,6,11),
    +              names=('N', 'Z', 'A', 'Element', 'Ebinding'),
    +              widths=(1,3,5,5,5,1,3,4,1,13,11,11,9,1,2,11,9,1,3,1,12,11,1),
    +              header=39,
    +              index_col=False)
    +
    +# Extrapolated values are indicated by '#' in place of the decimal place, so
    +# the Ebinding column won't be numeric. Coerce to float and drop these entries.
    +Masses['Ebinding'] = pd.to_numeric(Masses['Ebinding'], errors='coerce')
    +Masses = Masses.dropna()
    +# Convert from keV to MeV.
    +Masses['Ebinding'] /= 1000
    +
    +# Group the DataFrame by nucleon number, A.
    +Masses = Masses.groupby('A')
    +# Find the rows of the grouped DataFrame with the maximum binding energy.
    +Masses = Masses.apply(lambda t: t[t.Ebinding==t.Ebinding.max()])
    +A = Masses['A']
    +Z = Masses['Z']
    +N = Masses['N']
    +Element = Masses['Element']
    +Energies = Masses['Ebinding']
    +
    +# Now we set up the design matrix X
    +X = np.zeros((len(A),5))
    +X[:,0] = 1
    +X[:,1] = A
    +X[:,2] = A**(2.0/3.0)
    +X[:,3] = A**(-1.0/3.0)
    +X[:,4] = A**(-1.0)
    +# Then nice printout using pandas
    +DesignMatrix = pd.DataFrame(X)
    +DesignMatrix.index = A
    +DesignMatrix.columns = ['1', 'A', 'A^(2/3)', 'A^(-1/3)', '1/A']
    +display(DesignMatrix)
    +
    +

    +With \( \boldsymbol{\beta}\in {\mathbb{R}}^{p\times 1} \), it means that we will hereafter write our equations for the approximation as +$$ +\boldsymbol{\tilde{y}}= \boldsymbol{X}\boldsymbol{\beta}, +$$ + +throughout these lectures. + +

    +









    + +

    Optimizing our parameters, more details

    -We well use this matrix to define the approximation \( \hat{\tilde{y}} \) via the unknown quantity \( \hat{\beta} \) as +With the above we use the design matrix to define the approximation \( \boldsymbol{\tilde{y}} \) via the unknown quantity \( \boldsymbol{\beta} \) as $$ -\hat{\tilde{y}}= \hat{X}\hat{\beta}, +\boldsymbol{\tilde{y}}= \boldsymbol{X}\boldsymbol{\beta}, $$ -and in order to find the optimal parameters \( \beta_i \) instead of solving the above linear algebra problem, we define a function which gives a measure of the spread between the values \( y_i \) (which represent hopefully the exact values) and the parametrized values \( \tilde{y}_i \), namely +and in order to find the optimal parameters \( \beta_i \) instead of solving the above linear algebra problem, we define a function which gives a measure of the spread between the values \( y_i \) (which represent hopefully the exact values) and the parameterized values \( \tilde{y}_i \), namely $$ -Q(\hat{\beta})=\sum_{i=0}^{n-1}\left(y_i-\tilde{y}_i\right)^2=\left(\hat{y}-\hat{\tilde{y}}\right)^T\left(\hat{y}-\hat{\tilde{y}}\right), +C(\boldsymbol{\beta})=\frac{1}{n}\sum_{i=0}^{n-1}\left(y_i-\tilde{y}_i\right)^2=\frac{1}{n}\left\{\left(\boldsymbol{y}-\boldsymbol{\tilde{y}}\right)^T\left(\boldsymbol{y}-\boldsymbol{\tilde{y}}\right)\right\}, $$ -or using the matrix \( \hat{X} \) as +or using the matrix \( \boldsymbol{X} \) and in a more compact matrix-vector notation as $$ -Q(\hat{\beta})=\left(\hat{y}-\hat{X}\hat{\beta}\right)^T\left(\hat{y}-\hat{X}\hat{\beta}\right). +C(\boldsymbol{\beta})=\frac{1}{n}\left\{\left(\boldsymbol{y}-\boldsymbol{X}^T\boldsymbol{\beta}\right)^T\left(\boldsymbol{y}-\boldsymbol{X}^T\boldsymbol{\beta}\right)\right\}. $$ + +This function is one possible way to define the so-called cost function. + +

    +It is also common to define +the function \( Q \) as + +$$ +C(\boldsymbol{\beta})=\frac{1}{2n}\sum_{i=0}^{n-1}\left(y_i-\tilde{y}_i\right)^2, +$$ + +since when taking the first derivative with respect to the unknown parameters \( \beta \), the factor of \( 2 \) cancels out.











    -

    Interpretations and optimizing our parameters

    +

    Interpretations and optimizing our parameters

    +

    +

    The function $$ -Q(\hat{\beta})=\left(\hat{y}-\hat{X}\hat{\beta}\right)^T\left(\hat{y}-\hat{X}\hat{\beta}\right), +C(\boldsymbol{\beta})=\frac{1}{n}\left\{\left(\boldsymbol{y}-\boldsymbol{X}\boldsymbol{\beta}\right)^T\left(\boldsymbol{y}-\boldsymbol{X}\boldsymbol{\beta}\right)\right\}, $$ -can be linked to the variance of the quantity \( y_i \) if we interpret the latter as the mean value of for example a numerical experiment. When linking below with the maximum likelihood approach below, we will indeed interpret \( y_i \) as a mean value +can be linked to the variance of the quantity \( y_i \) if we interpret the latter as the mean value. +When linking below with the maximum likelihood approach below, we will indeed interpret \( y_i \) as a mean value (see exercises) $$ y_{i}=\langle y_i \rangle = \beta_0x_{i,0}+\beta_1x_{i,1}+\beta_2x_{i,2}+\dots+\beta_{n-1}x_{i,n-1}+\epsilon_i, $$ -where \( \langle y_i \rangle \) is the mean value. Keep in mind also that till now we have treated \( y_i \) as the exact value. Normally, the response (dependent or outcome) variable \( y_i \) the outcome of a numerical experiment or another type of experiment and is thus only an approximation to the true value. It is then always accompanied by an error estimate, often limited to a statistical error estimate given by the standard deviation discussed earlier. In the discussion here we will treat \( y_i \) as our exact value for the response variable. +

    +where \( \langle y_i \rangle \) is the mean value. Keep in mind also that +till now we have treated \( y_i \) as the exact value. Normally, the +response (dependent or outcome) variable \( y_i \) the outcome of a +numerical experiment or another type of experiment and is thus only an +approximation to the true value. It is then always accompanied by an +error estimate, often limited to a statistical error estimate given by +the standard deviation discussed earlier. In the discussion here we +will treat \( y_i \) as our exact value for the response variable.

    -In order to find the parameters \( \beta_i \) we will then minimize the spread of \( Q(\hat{\beta}) \) by requiring +In order to find the parameters \( \beta_i \) we will then minimize the spread of \( C(\boldsymbol{\beta}) \), that is we are going to solve the problem $$ -\frac{\partial Q(\hat{\beta})}{\partial \beta_j} = \frac{\partial }{\partial \beta_j}\left[ \sum_{i=0}^{n-1}\left(y_i-\beta_0x_{i,0}-\beta_1x_{i,1}-\beta_2x_{i,2}-\dots-\beta_{n-1}x_{i,n-1}\right)^2\right]=0, +{\displaystyle \min_{\boldsymbol{\beta}\in +{\mathbb{R}}^{p}}}\frac{1}{n}\left\{\left(\boldsymbol{y}-\boldsymbol{X}\boldsymbol{\beta}\right)^T\left(\boldsymbol{y}-\boldsymbol{X}\boldsymbol{\beta}\right)\right\}. +$$ + +In practical terms it means we will require +$$ +\frac{\partial C(\boldsymbol{\beta})}{\partial \beta_j} = \frac{\partial }{\partial \beta_j}\left[ \frac{1}{n}\sum_{i=0}^{n-1}\left(y_i-\beta_0x_{i,0}-\beta_1x_{i,1}-\beta_2x_{i,2}-\dots-\beta_{n-1}x_{i,n-1}\right)^2\right]=0, $$ which results in $$ -\frac{\partial Q(\hat{\beta})}{\partial \beta_j} = -2\left[ \sum_{i=0}^{n-1}x_{ij}\left(y_i-\beta_0x_{i,0}-\beta_1x_{i,1}-\beta_2x_{i,2}-\dots-\beta_{n-1}x_{i,n-1}\right)\right]=0, +\frac{\partial C(\boldsymbol{\beta})}{\partial \beta_j} = -\frac{2}{n}\left[ \sum_{i=0}^{n-1}x_{ij}\left(y_i-\beta_0x_{i,0}-\beta_1x_{i,1}-\beta_2x_{i,2}-\dots-\beta_{n-1}x_{i,n-1}\right)\right]=0, $$ or in a matrix-vector form as $$ -\frac{\partial Q(\hat{\beta})}{\partial \hat{\beta}} = 0 = \hat{X}^T\left( \hat{y}-\hat{X}\hat{\beta}\right). +\frac{\partial C(\boldsymbol{\beta})}{\partial \boldsymbol{\beta}} = 0 = \boldsymbol{X}^T\left( \boldsymbol{y}-\boldsymbol{X}\boldsymbol{\beta}\right). $$ @@ -589,25 +758,37 @@ $$











    -

    Interpretations and optimizing our parameters

    +

    Interpretations and optimizing our parameters

    We can rewrite $$ -\frac{\partial Q(\hat{\beta})}{\partial \hat{\beta}} = 0 = \hat{X}^T\left( \hat{y}-\hat{X}\hat{\beta}\right), +\frac{\partial C(\boldsymbol{\beta})}{\partial \boldsymbol{\beta}} = 0 = \boldsymbol{X}^T\left( \boldsymbol{y}-\boldsymbol{X}\boldsymbol{\beta}\right), $$ as $$ -\hat{X}^T\hat{y} = \hat{X}^T\hat{X}\hat{\beta}, +\boldsymbol{X}^T\boldsymbol{y} = \boldsymbol{X}^T\boldsymbol{X}\boldsymbol{\beta}, $$ -and if the matrix \( \hat{X}^T\hat{X} \) is invertible we have the solution +and if the matrix \( \boldsymbol{X}^T\boldsymbol{X} \) is invertible we have the solution $$ -\hat{\beta} =\left(\hat{X}^T\hat{X}\right)^{-1}\hat{X}^T\hat{y}. +\boldsymbol{\beta} =\left(\boldsymbol{X}^T\boldsymbol{X}\right)^{-1}\boldsymbol{X}^T\boldsymbol{y}. $$ +

    +We note also that since our design matrix is defined as \( \boldsymbol{X}\in +{\mathbb{R}}^{n\times p} \), the product \( \boldsymbol{X}^T\boldsymbol{X} \in +{\mathbb{R}}^{p\times p} \). In the above case we have that \( p \ll n \), +in our case \( p=5 \) meaning that we end up with inverting a small +\( 5\times 5 \) matrix. This is a rather common situation, in many cases we end up with low-dimensional +matrices to invert. The methods discussed here and for many other +supervised learning algorithms like classification with logistic +regression or support vector machines, exhibit dimensionalities which +allow for the usage of direct linear algebra methods such as LU decomposition or Singular Value Decomposition (SVD) for finding the inverse of the matrix +\( \boldsymbol{X}^T\boldsymbol{X} \). +

    @@ -615,26 +796,144 @@ $$











    -

    Interpretations and optimizing our parameters

    +

    Interpretations and optimizing our parameters

    -The residuals \( \hat{\epsilon} \) are in turn given by +The residuals \( \boldsymbol{\epsilon} \) are in turn given by $$ -\hat{\epsilon} = \hat{y}-\hat{\tilde{y}} = \hat{y}-\hat{X}\hat{\beta}, +\boldsymbol{\epsilon} = \boldsymbol{y}-\boldsymbol{\tilde{y}} = \boldsymbol{y}-\boldsymbol{X}\boldsymbol{\beta}, $$ and with $$ -\hat{X}^T\left( \hat{y}-\hat{X}\hat{\beta}\right)= 0, +\boldsymbol{X}^T\left( \boldsymbol{y}-\boldsymbol{X}\boldsymbol{\beta}\right)= 0, $$ we have $$ -\hat{X}^T\hat{\epsilon}=\hat{X}^T\left( \hat{y}-\hat{X}\hat{\beta}\right)= 0, +\boldsymbol{X}^T\boldsymbol{\epsilon}=\boldsymbol{X}^T\left( \boldsymbol{y}-\boldsymbol{X}\boldsymbol{\beta}\right)= 0, $$ -meaning that the solution for \( \hat{\beta} \) is the one which minimizes the residuals. Later we will link this with the maximum likelihood approach. +meaning that the solution for \( \boldsymbol{\beta} \) is the one which minimizes the residuals. Later we will link this with the maximum likelihood approach. + + +

    + + +

    +Let us now return to our nuclear binding energies and simply code the above equations. + +

    +









    + +

    Own code for Ordinary Least Squares

    + +

    +It is rather straightforward to implement the matrix inversion and obtain the parameters \( \boldsymbol{\beta} \). After having defined the matrix \( \boldsymbol{X} \) we simply need to +write +

    + + +

    # matrix inversion to find beta
    +beta = np.linalg.inv(X.T.dot(X)).dot(X.T).dot(Energies)
    +# and then make the prediction
    +ytilde = X @ beta
    +
    +

    +Alternatively, you can use the least squares functionality in Numpy as +

    + + +

    fit = np.linalg.lstsq(X, Energies, rcond =None)[0]
    +ytildenp = np.dot(fit,X.T)
    +
    +

    +And finally we plot our fit with and compare with data +

    + + +

    Masses['Eapprox']  = ytilde
    +# Generate a plot comparing the experimental with the fitted values values.
    +fig, ax = plt.subplots()
    +ax.set_xlabel(r'$A = N + Z$')
    +ax.set_ylabel(r'$E_\mathrm{bind}\,/\mathrm{MeV}$')
    +ax.plot(Masses['A'], Masses['Ebinding'], alpha=0.7, lw=2,
    +            label='Ame2016')
    +ax.plot(Masses['A'], Masses['Eapprox'], alpha=0.7, lw=2, c='m',
    +            label='Fit')
    +ax.legend()
    +save_fig("Masses2016OLS")
    +plt.show()
    +
    +

    +









    + +

    Adding error analysis and training set up

    + +

    +We can easily test our fit by computing the \( R2 \) score that we discussed in connection with the functionality of _Scikit_Learn_ in the introductory slides. +Since we are not using _Scikit-Learn here we can define our own \( R2 \) function as +

    + + +

    def R2(y_data, y_model):
    +    return 1 - np.sum((y_data - y_model) ** 2) / np.sum((y_data - np.mean(y_model)) ** 2)
    +
    +

    +and we would be using it as +

    + + +

    print(R2(Energies,ytilde))
    +
    +

    +We can easily add our MSE score as +

    + + +

    def MSE(y_data,y_model):
    +    n = np.size(y_model)
    +    return np.sum((y_data-y_model)**2)/n
    +
    +print(MSE(Energies,ytilde))
    +
    +

    +and finally the relative error as +

    + + +

    def RelativeError(y_data,y_model):
    +    return abs((y_data-y_model)/y_data)
    +print(RelativeError(Energies, ytilde))
    +
    +

    +









    + +

    The \( \chi^2 \) function

    +
    + +

    + +

    +Normally, the response (dependent or outcome) variable \( y_i \) is the +outcome of a numerical experiment or another type of experiment and is +thus only an approximation to the true value. It is then always +accompanied by an error estimate, often limited to a statistical error +estimate given by the standard deviation discussed earlier. In the +discussion here we will treat \( y_i \) as our exact value for the +response variable. + +

    +Introducing the standard deviation \( \sigma_i \) for each measurement +\( y_i \), we define now the \( \chi^2 \) function (omitting the \( 1/n \) term) +as + +$$ +\chi^2(\boldsymbol{\beta})=\frac{1}{n}\sum_{i=0}^{n-1}\frac{\left(y_i-\tilde{y}_i\right)^2}{\sigma_i^2}=\frac{1}{n}\left\{\left(\boldsymbol{y}-\boldsymbol{\tilde{y}}\right)^T\frac{1}{\boldsymbol{\Sigma^2}}\left(\boldsymbol{y}-\boldsymbol{\tilde{y}}\right)\right\}, +$$ + +where the matrix \( \boldsymbol{\Sigma} \) is a diagonal matrix with \( \sigma_i \) as matrix elements.

    @@ -643,58 +942,35 @@ meaning that the solution for \( \hat{\beta} \) is the one which minimizes the r











    -

    The \( \chi^2 \) function

    +

    The \( \chi^2 \) function

    -Normally, the response (dependent or outcome) variable \( y_i \) the outcome of a numerical experiment or another type of experiment and is thus only an approximation to the true value. It is then always accompanied by an error estimate, often limited to a statistical error estimate given by the standard deviation discussed earlier. In the discussion here we will treat \( y_i \) as our exact value for the response variable. - -

    -Introducing the standard deviation \( \sigma_i \) for each measurement \( y_i \), we define now the \( \chi^2 \) function as +In order to find the parameters \( \beta_i \) we will then minimize the spread of \( \chi^2(\boldsymbol{\beta}) \) by requiring $$ -\chi^2(\hat{\beta})=\sum_{i=0}^{n-1}\frac{\left(y_i-\tilde{y}_i\right)^2}{\sigma_i^2}=\left(\hat{y}-\hat{\tilde{y}}\right)^T\frac{1}{\hat{\Sigma^2}}\left(\hat{y}-\hat{\tilde{y}}\right), -$$ - -where the matrix \( \hat{\Sigma} \) is a diagonal matrix with \( \sigma_i \) as matrix elements. - - -

    - - -

    -









    - -

    The \( \chi^2 \) function

    -
    - -

    - -

    -In order to find the parameters \( \beta_i \) we will then minimize the spread of \( \chi^2(\hat{\beta}) \) by requiring -$$ -\frac{\partial \chi^2(\hat{\beta})}{\partial \beta_j} = \frac{\partial }{\partial \beta_j}\left[ \sum_{i=0}^{n-1}\left(\frac{y_i-\beta_0x_{i,0}-\beta_1x_{i,1}-\beta_2x_{i,2}-\dots-\beta_{n-1}x_{i,n-1}}{\sigma_i}\right)^2\right]=0, +\frac{\partial \chi^2(\boldsymbol{\beta})}{\partial \beta_j} = \frac{\partial }{\partial \beta_j}\left[ \frac{1}{n}\sum_{i=0}^{n-1}\left(\frac{y_i-\beta_0x_{i,0}-\beta_1x_{i,1}-\beta_2x_{i,2}-\dots-\beta_{n-1}x_{i,n-1}}{\sigma_i}\right)^2\right]=0, $$ which results in $$ -\frac{\partial \chi^2(\hat{\beta})}{\partial \beta_j} = -2\left[ \sum_{i=0}^{n-1}\frac{x_{ij}}{\sigma_i}\left(\frac{y_i-\beta_0x_{i,0}-\beta_1x_{i,1}-\beta_2x_{i,2}-\dots-\beta_{n-1}x_{i,n-1}}{\sigma_i}\right)\right]=0, +\frac{\partial \chi^2(\boldsymbol{\beta})}{\partial \beta_j} = -\frac{2}{n}\left[ \sum_{i=0}^{n-1}\frac{x_{ij}}{\sigma_i}\left(\frac{y_i-\beta_0x_{i,0}-\beta_1x_{i,1}-\beta_2x_{i,2}-\dots-\beta_{n-1}x_{i,n-1}}{\sigma_i}\right)\right]=0, $$ or in a matrix-vector form as $$ -\frac{\partial \chi^2(\hat{\beta})}{\partial \hat{\beta}} = 0 = \hat{A}^T\left( \hat{b}-\hat{A}\hat{\beta}\right). +\frac{\partial \chi^2(\boldsymbol{\beta})}{\partial \boldsymbol{\beta}} = 0 = \boldsymbol{A}^T\left( \boldsymbol{b}-\boldsymbol{A}\boldsymbol{\beta}\right). $$ -where we have defined the matrix \( \hat{A} =\hat{X}/\hat{\Sigma} \) with matrix elements \( a_{ij} = x_{ij}/\sigma_i \) and the vector \( \hat{b} \) with elements \( b_i = y_i/\sigma_i \). +where we have defined the matrix \( \boldsymbol{A} =\boldsymbol{X}/\boldsymbol{\Sigma} \) with matrix elements \( a_{ij} = x_{ij}/\sigma_i \) and the vector \( \boldsymbol{b} \) with elements \( b_i = y_i/\sigma_i \).











    -

    The \( \chi^2 \) function

    +

    The \( \chi^2 \) function

    @@ -702,17 +978,17 @@ where we have defined the matrix \( \hat{A} =\hat{X}/\hat{\Sigma} \) with matrix

    We can rewrite $$ -\frac{\partial \chi^2(\hat{\beta})}{\partial \hat{\beta}} = 0 = \hat{A}^T\left( \hat{b}-\hat{A}\hat{\beta}\right), +\frac{\partial \chi^2(\boldsymbol{\beta})}{\partial \boldsymbol{\beta}} = 0 = \boldsymbol{A}^T\left( \boldsymbol{b}-\boldsymbol{A}\boldsymbol{\beta}\right), $$ as $$ -\hat{A}^T\hat{b} = \hat{A}^T\hat{A}\hat{\beta}, +\boldsymbol{A}^T\boldsymbol{b} = \boldsymbol{A}^T\boldsymbol{A}\boldsymbol{\beta}, $$ -and if the matrix \( \hat{A}^T\hat{A} \) is invertible we have the solution +and if the matrix \( \boldsymbol{A}^T\boldsymbol{A} \) is invertible we have the solution $$ -\hat{\beta} =\left(\hat{A}^T\hat{A}\right)^{-1}\hat{A}^T\hat{b}. +\boldsymbol{\beta} =\left(\boldsymbol{A}^T\boldsymbol{A}\right)^{-1}\boldsymbol{A}^T\boldsymbol{b}. $$

    @@ -720,7 +996,7 @@ $$











    -

    The \( \chi^2 \) function

    +

    The \( \chi^2 \) function

    @@ -728,10 +1004,10 @@ $$

    If we then introduce the matrix $$ -\hat{H} = \left(\hat{A}^T\hat{A}\right)^{-1}, +\boldsymbol{H} = \left(\boldsymbol{A}^T\boldsymbol{A}\right)^{-1}, $$ -we have then the following expression for the parameters \( \beta_j \) (the matrix elements of \( \hat{H} \) are \( h_{ij} \)) +we have then the following expression for the parameters \( \beta_j \) (the matrix elements of \( \boldsymbol{H} \) are \( h_{ij} \)) $$ \beta_j = \sum_{k=0}^{p-1}h_{jk}\sum_{i=0}^{n-1}\frac{y_i}{\sigma_i}\frac{x_{ik}}{\sigma_i} = \sum_{k=0}^{p-1}h_{jk}\sum_{i=0}^{n-1}b_ia_{ik} $$ @@ -751,7 +1027,7 @@ $$











    -

    The \( \chi^2 \) function

    +

    The \( \chi^2 \) function

    @@ -762,12 +1038,12 @@ $$ By computing the derivatives of \( \chi^2 \) with respect to \( \beta_0 \) and \( \beta_1 \) show that these are given by $$ -\frac{\partial \chi^2(\hat{\beta})}{\partial \beta_0} = -2\left[ \sum_{i=0}^{n-1}\left(\frac{y_i-\beta_0-\beta_1x_{i}}{\sigma_i^2}\right)\right]=0, +\frac{\partial \chi^2(\boldsymbol{\beta})}{\partial \beta_0} = -2\left[ \frac{1}{n}\sum_{i=0}^{n-1}\left(\frac{y_i-\beta_0-\beta_1x_{i}}{\sigma_i^2}\right)\right]=0, $$ and $$ -\frac{\partial \chi^2(\hat{\beta})}{\partial \beta_0} = -2\left[ \sum_{i=0}^{n-1}x_i\left(\frac{y_i-\beta_0-\beta_1x_{i}}{\sigma_i^2}\right)\right]=0. +\frac{\partial \chi^2(\boldsymbol{\beta})}{\partial \beta_1} = -\frac{2}{n}\left[ \sum_{i=0}^{n-1}x_i\left(\frac{y_i-\beta_0-\beta_1x_{i}}{\sigma_i^2}\right)\right]=0. $$

    @@ -775,13 +1051,13 @@ $$











    -

    The \( \chi^2 \) function

    +

    The \( \chi^2 \) function

    -For a linear fit we don't need to invert a matrix!! +For a linear fit (a first-order polynomial) we don't need to invert a matrix!! Defining $$ \gamma = \sum_{i=0}^{n-1}\frac{1}{\sigma_i^2}, @@ -792,570 +1068,539 @@ $$ \gamma_x = \sum_{i=0}^{n-1}\frac{x_{i}}{\sigma_i^2}, $$ + $$ \gamma_y = \sum_{i=0}^{n-1}\left(\frac{y_i}{\sigma_i^2}\right), $$ + $$ \gamma_{xx} = \sum_{i=0}^{n-1}\frac{x_ix_{i}}{\sigma_i^2}, $$ + $$ \gamma_{xy} = \sum_{i=0}^{n-1}\frac{y_ix_{i}}{\sigma_i^2}, $$ +

    we obtain + $$ \beta_0 = \frac{\gamma_{xx}\gamma_y-\gamma_x\gamma_y}{\gamma\gamma_{xx}-\gamma_x^2}, $$ + $$ \beta_1 = \frac{\gamma_{xy}\gamma-\gamma_x\gamma_y}{\gamma\gamma_{xx}-\gamma_x^2}. $$

    -This approach (different linear and non-linear regression) suffers often from both being underdetermined and overdetermined in the unknown coefficients \( \beta_i \). A better approach is to use the Singular Value Decomposition (SVD) method discussed below. Or using Lasso and Ridge regression. See below. +This approach (different linear and non-linear regression) suffers +often from both being underdetermined and overdetermined in the +unknown coefficients \( \beta_i \). A better approach is to use the +Singular Value Decomposition (SVD) method discussed below. Or using +Lasso and Ridge regression. See below. + +











    -

    Simple regression model

    -We are now ready to write our first program which aims at solving the above linear regression equations. We start with data we have produced ourselves, in this case normally distributed random numbers along the \( x \)-axis. These numbers define then the value of a function \( y(x)=4+3x+N(0,1) \). Thereafter we order the \( x \) values and employ our linear regression algorithm to set up the best fit. Here we find it useful to use the numpy function \( c\_ \) arrays where arrays are stacked along their last axis after being upgraded to at least two dimensions with ones post-pended to the shape. The following examples help in understanding what happens +

    Fitting an Equation of State for Dense Nuclear Matter

    + +

    +Before we continue, let us introduce yet another example. We are going to fit the +nuclear equation of state using results from many-body calculations. +The equation of state we have made available here, as function of +density, has been derived using modern nucleon-nucleon potentials with +the addition of three-body +forces. This +time the file is presented as a standard csv file. + +

    +The beginning of the Python code here is similar to what you have seen before, +with the same initializations and declarations. We use also pandas +again, rather extensively in order to organize our data. + +

    +The difference now is that we use Scikit-Learn's regression tools +instead of our own matrix inversion implementation. Furthermore, we +sneak in Ridge regression (to be discussed below) which includes a +hyperparameter \( \lambda \), also to be explained below. + +

    +









    + +

    The code

    +

    -

    import numpy as np
    -print(np.c_[np.array([1,2,3]), np.array([4,5,6])])
    -print(np.c_[np.array([[1,2,3]]), 0, 0, np.array([[4,5,6]])])
    -
    -

    - - -

    # Importing various packages
    -from random import random, seed
    +
    # Common imports
    +import os
     import numpy as np
    +import pandas as pd
     import matplotlib.pyplot as plt
    -
    -x = 2*np.random.rand(100,1)
    -y = 4+3*x+np.random.randn(100,1)
    -
    -xb = np.c_[np.ones((100,1)), x]
    -beta = np.linalg.inv(xb.T.dot(xb)).dot(xb.T).dot(y)
    -xnew = np.array([[0],[2]])
    -xbnew = np.c_[np.ones((2,1)), xnew]
    -ypredict = xbnew.dot(beta)
    -
    -plt.plot(xnew, ypredict, "r-")
    -plt.plot(x, y ,'ro')
    -plt.axis([0,2.0,0, 15.0])
    -plt.xlabel(r'$x$')
    -plt.ylabel(r'$y$')
    -plt.title(r'Linear Regression')
    -plt.show()
    -
    -

    -We see that, as expected, a linear fit gives a seemingly (from the graph) good representation of the data. - -

    -









    - -

    Simple regression model, now using scikit-learn

    - -

    -We can repeat the above algorithm using scikit-learn as follows -

    - - -

    # Importing various packages
    -from random import random, seed
    -import numpy as np
     import matplotlib.pyplot as plt
    -from sklearn.linear_model import LinearRegression
    +import sklearn.linear_model as skl
    +from sklearn.metrics import mean_squared_error, r2_score, mean_absolute_error
     
    -x = 2*np.random.rand(100,1)
    -y = 4+3*x+np.random.randn(100,1)
    -linreg = LinearRegression()
    -linreg.fit(x,y)
    -xnew = np.array([[0],[2]])
    -ypredict = linreg.predict(xnew)
    +# Where to save the figures and data files
    +PROJECT_ROOT_DIR = "Results"
    +FIGURE_ID = "Results/FigureFiles"
    +DATA_ID = "DataFiles/"
     
    -plt.plot(xnew, ypredict, "r-")
    -plt.plot(x, y ,'ro')
    -plt.axis([0,2.0,0, 15.0])
    -plt.xlabel(r'$x$')
    -plt.ylabel(r'$y$')
    -plt.title(r'Random numbers ')
    -plt.show()
    -
    -

    -









    +if not os.path.exists(PROJECT_ROOT_DIR): + os.mkdir(PROJECT_ROOT_DIR) -

    Simple linear regression model using scikit-learn

    +if not os.path.exists(FIGURE_ID): + os.makedirs(FIGURE_ID) -

    -We start with perhaps our simplest possible example, using scikit-learn to perform linear regression analysis on a data set produced by us. -What follows is a simple Python code where we have defined function \( y \) in terms of the variable \( x \). Both are defined as vectors of dimension \( 1\times 100 \). The entries to the vector \( \hat{x} \) are given by random numbers generated with a uniform distribution with entries \( x_i \in [0,1] \) (more about probability distribution functions later). These values are then used to define a function \( y(x) \) (tabulated again as a vector) with a linear dependence on \( x \) plus a random noise added via the normal distribution. +if not os.path.exists(DATA_ID): + os.makedirs(DATA_ID) -

    -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 \) +def image_path(fig_id): + return os.path.join(FIGURE_ID, fig_id) -$$ -y = 2x+N(0,1), -$$ +def data_path(dat_id): + return os.path.join(DATA_ID, dat_id) -

    -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. +def save_fig(fig_id): + plt.savefig(image_path(fig_id) + ".png", format='png') -

    -For plotting we use the Python package -matplotlib which produces publication -quality figures. Feel free to explore the extensive -gallery 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. +infile = open(data_path("EoS.csv"),'r') -

    -The Python code follows here. -

    +# Read the EoS data as csv file and organize the data into two arrays with density and energies +EoS = pd.read_csv(infile, names=('Density', 'Energy')) +EoS['Energy'] = pd.to_numeric(EoS['Energy'], errors='coerce') +EoS = EoS.dropna() +Energies = EoS['Energy'] +Density = EoS['Density'] +# The design matrix now as function of various polytrops +X = np.zeros((len(Density),4)) +X[:,3] = Density**(4.0/3.0) +X[:,2] = Density +X[:,1] = Density**(2.0/3.0) +X[:,0] = 1 - -

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

    -









    - -

    Simple linear regression model

    - -

    -This example serves several aims. It allows us to demonstrate several -aspects of data analysis and later machine learning algorithms. The -immediate visualization shows that our linear fit is not -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 - -$$ -y = 10x+0.01 \times N(0,1), -$$ - -

    -where \( x \) is defined as before. - -

    -









    - -

    Less noise

    - -

    -Does the fit look better? Indeed, by -reducing the role of the normal distribution we see immediately that -our linear prediction seemingly reproduces better the training -set. However, this testing 'by the eye' is obviouly not satisfactory in the -long run. Here we have only defined the training data and our model, and -have not discussed a more rigorous approach to the cost function. - -

    -









    - -

    How to study our fits

    - -

    -We need more rigorous criteria in defining whether we have succeeded or -not in modeling our training data. You will be surprised to see that -many scientists seldomly venture beyond this 'by the eye' approach. A -standard approach for the cost function is the so-called \( \chi^2 \) -function - -$$ \chi^2 = \frac{1}{n} -\sum_{i=0}^{n-1}\frac{(y_i-\tilde{y}_i)^2}{\sigma_i^2}, -$$ - -

    -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

    - -

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

    -









    - -

    Relative error

    - -

    -There are many ways to define the cost function. A simpler approach is to look at the relative difference between the training data and the predicted data, that is we define -the relative error as - -$$ -\epsilon_{\mathrm{relative}}= \frac{\vert \hat{y} -\hat{\tilde{y}}\vert}{\vert \hat{y}\vert}. -$$ - -We can modify easily the above Python code and plot the relative error instead -

    - - -

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

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

    -









    - -

    The richness of scikit-learn

    - -

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

    - - -

    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_)
    +# We use now Scikit-Learn's linear regressor and ridge regressor
    +# OLS part
    +clf = skl.LinearRegression().fit(X, Energies)
    +ytilde = clf.predict(X)
    +EoS['Eols']  = ytilde
     # The mean squared error                               
    -print("Mean squared error: %.2f" % mean_squared_error(y, ypredict))
    +print("Mean squared error: %.2f" % mean_squared_error(Energies, ytilde))
     # 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) )
    +print('Variance score: %.2f' % r2_score(Energies, ytilde))
     # 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 ')
    +print('Mean absolute error: %.2f' % mean_absolute_error(Energies, ytilde))
    +print(clf.coef_, clf.intercept_)
    +
    +# The Ridge regression with a hyperparameter lambda = 0.1
    +_lambda = 0.1
    +clf_ridge = skl.Ridge(alpha=_lambda).fit(X, Energies)
    +yridge = clf_ridge.predict(X)
    +EoS['Eridge']  = yridge
    +# The mean squared error                               
    +print("Mean squared error: %.2f" % mean_squared_error(Energies, yridge))
    +# Explained variance score: 1 is perfect prediction                                 
    +print('Variance score: %.2f' % r2_score(Energies, yridge))
    +# Mean absolute error                                                           
    +print('Mean absolute error: %.2f' % mean_absolute_error(Energies, yridge))
    +print(clf_ridge.coef_, clf_ridge.intercept_)
    +
    +fig, ax = plt.subplots()
    +ax.set_xlabel(r'$\rho[\mathrm{fm}^{-3}]$')
    +ax.set_ylabel(r'Energy per particle')
    +ax.plot(EoS['Density'], EoS['Energy'], alpha=0.7, lw=2,
    +            label='Theoretical data')
    +ax.plot(EoS['Density'], EoS['Eols'], alpha=0.7, lw=2, c='m',
    +            label='OLS')
    +ax.plot(EoS['Density'], EoS['Eridge'], alpha=0.7, lw=2, c='g',
    +            label='Ridge $\lambda = 0.1$')
    +ax.legend()
    +save_fig("EoSfitting")
     plt.show()
     

    -









    - -

    Functions in scikit-learn

    +The above simple polynomial in density \( \rho \) gives an excellent fit +to the data. Can you give an interpretation of the various powers of \( \rho \)?

    -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 -$$ MSE(\hat{y},\hat{\tilde{y}}) = \frac{1}{n} -\sum_{i=0}^{n-1}(y_i-\tilde{y}_i)^2, -$$ - -

    -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. +We note also that there is a small deviation between the +standard OLS and the Ridge regression at higher densities. We discuss this in more detail +below.











    -

    Other functions in scikit-learn

    +

    Splitting our Data in Training and Test data

    -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 -$$ -R^2(\hat{y}, \tilde{\hat{y}}) = 1 - \frac{\sum_{i=0}^{n - 1} (y_i - \tilde{y}_i)^2}{\sum_{i=0}^{n - 1} (y_i - \bar{y})^2}, -$$ - -where we have defined the mean value of \( \hat{y} \) as -$$ -\bar{y} = \frac{1}{n} \sum_{i=0}^{n - 1} y_i. -$$ - -

    -









    - -

    The mean absolute error and other functions in scikit-learn

    - -

    -Another quantity will meet again in our discussions of regression analysis is - mean absolute error (MAE), a risk metric corresponding to the expected value of the absolute error loss or what we call the \( l1 \)-norm loss. In our discussion above we presented the relative error. -The MAE is defined as follows -$$ -\text{MAE}(\hat{y}, \hat{\tilde{y}}) = \frac{1}{n} \sum_{i=0}^{n-1} \left| y_i - \tilde{y}_i \right|. -$$ - -Finally we present the -squared logarithmic (quadratic) error -$$ -\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, -$$ - -

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

    -









    - -

    Cubic polynomial in scikit-learn

    - -

    -We will discuss in more -detail these and other functions in the various lectures. We conclude this part with another example. Instead of -a linear \( x \)-dependence we study now a cubic polynomial and use the polynomial regression analysis tools of scikit-learn. -Add description of the various python commands. +It is normal in essentially all Machine Learning studies to split the +data in a training set and a test set (sometimes also an additional +validation set). Scikit-Learn has an own function for this. There +is no explicit recipe for how much data should be included as training +data and say test data. An accepted rule of thumb is to use +approximately \( 2/3 \) to \( 4/5 \) of the data as training data. We will +postpone a discussion of this splitting to the end of these notes and +our discussion of the so-called bias-variance tradeoff. Here we +limit ourselves to repeat the above equation of state fitting example +but now splitting the data into a training set and a test set.

    -

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

    -Using R, we can perform similar studies. - -

    -









    - -

    Polynomial Regression

    -

    - - -

    # Importing various packages
    -from math import exp, sqrt
    -from random import random, seed
    +
    import os
     import numpy as np
    +import pandas as pd
     import matplotlib.pyplot as plt
    +from sklearn.model_selection import train_test_split
    +# Where to save the figures and data files
    +PROJECT_ROOT_DIR = "Results"
    +FIGURE_ID = "Results/FigureFiles"
    +DATA_ID = "DataFiles/"
     
    -m = 100
    -x = 2*np.random.rand(m,1)+4.
    -y = 4+3*x*x+ +x-np.random.randn(m,1)
    +if not os.path.exists(PROJECT_ROOT_DIR):
    +    os.mkdir(PROJECT_ROOT_DIR)
     
    -xb = np.c_[np.ones((m,1)), x]
    -theta = np.linalg.inv(xb.T.dot(xb)).dot(xb.T).dot(y)
    -xnew = np.array([[0],[2]])
    -xbnew = np.c_[np.ones((2,1)), xnew]
    -ypredict = xbnew.dot(theta)
    +if not os.path.exists(FIGURE_ID):
    +    os.makedirs(FIGURE_ID)
     
    -plt.plot(xnew, ypredict, "r-")
    -plt.plot(x, y ,'ro')
    -plt.axis([0,2.0,0, 15.0])
    -plt.xlabel(r'$x$')
    -plt.ylabel(r'$y$')
    -plt.title(r'Random numbers ')
    -plt.show()
    +if not os.path.exists(DATA_ID):
    +    os.makedirs(DATA_ID)
    +
    +def image_path(fig_id):
    +    return os.path.join(FIGURE_ID, fig_id)
    +
    +def data_path(dat_id):
    +    return os.path.join(DATA_ID, dat_id)
    +
    +def save_fig(fig_id):
    +    plt.savefig(image_path(fig_id) + ".png", format='png')
    +
    +def R2(y_data, y_model):
    +    return 1 - np.sum((y_data - y_model) ** 2) / np.sum((y_data - np.mean(y_model)) ** 2)
    +def MSE(y_data,y_model):
    +    n = np.size(y_model)
    +    return np.sum((y_data-y_model)**2)/n
    +
    +infile = open(data_path("EoS.csv"),'r')
    +
    +# Read the EoS data as  csv file and organized into two arrays with density and energies
    +EoS = pd.read_csv(infile, names=('Density', 'Energy'))
    +EoS['Energy'] = pd.to_numeric(EoS['Energy'], errors='coerce')
    +EoS = EoS.dropna()
    +Energies = EoS['Energy']
    +Density = EoS['Density']
    +#  The design matrix now as function of various polytrops
    +X = np.zeros((len(Density),5))
    +X[:,0] = 1
    +X[:,1] = Density**(2.0/3.0)
    +X[:,2] = Density
    +X[:,3] = Density**(4.0/3.0)
    +X[:,4] = Density**(5.0/3.0)
    +# We split the data in test and training data
    +X_train, X_test, y_train, y_test = train_test_split(X, Energies, test_size=0.2)
    +# matrix inversion to find beta
    +beta = np.linalg.inv(X_train.T.dot(X_train)).dot(X_train.T).dot(y_train)
    +# and then make the prediction
    +ytilde = X_train @ beta
    +print("Training R2")
    +print(R2(y_train,ytilde))
    +print("Training MSE")
    +print(MSE(y_train,ytilde))
    +ypredict = X_test @ beta
    +print("Test R2")
    +print(R2(y_test,ypredict))
    +print("Test MSE")
    +print(MSE(y_test,ypredict))
     
    -

    - - -

    Linking the regression analysis with a statistical interpretation

    - -

    -Before we proceed, and to link with our discussions of Bayesian statistics to come, it is useful the derive the standard regression analysis equations using a statistical interpretation. This allows us also to derive quantities like the variance and other expectation values in a rather straightforward way. - -

    -It is assumed that \( \varepsilon_i -\sim \mathcal{N}(0, \sigma^2) \) and the \( \varepsilon_{i} \) are -independent, i.e.: -$$ -\begin{align*} -\mbox{Cov}(\varepsilon_{i_1}, -\varepsilon_{i_2}) & = \left\{ \begin{array}{lcc} \sigma^2 & \mbox{if} -& i_1 = i_2, \\ 0 & \mbox{if} & i_1 \not= i_2. \end{array} \right. -\end{align*} -$$ - -The randomness of \( \varepsilon_i \) implies that -\( \mathbf{Y}_i \) is also a random variable. In particular, -\( \mathbf{Y}_i \) is normally distributed, because \( \varepsilon_i \sim -\mathcal{N}(0, \sigma^2) \) and \( \mathbf{X}_{i,\ast} \, \beta \) is a -non-random scalar. To specify the parameters of the distribution of -\( \mathbf{Y}_i \) we need to calculate its first two moments. -











    -

    Expectation value and variance

    +

    The singular value decomposition

    -Its expectation equals: -$$ -\begin{align*} -\mathbb{E}(Y_i) & = -\mathbb{E}(\mathbf{X}_{i, \ast} \, \beta) + \mathbb{E}(\varepsilon_i) -\, \, \, = \, \, \, \mathbf{X}_{i, \ast} \, \beta, -\end{align*} -$$ - -while -its variance is -$$ -\begin{align*} \mbox{Var}(Y_i) & = \mathbb{E} \{ [Y_i -- \mathbb{E}(Y_i)]^2 \} \, \, \, = \, \, \, \mathbb{E} ( Y_i^2 ) - -[\mathbb{E}(Y_i)]^2 \\ & = \mathbb{E} [ ( \mathbf{X}_{i, \ast} \, -\beta + \varepsilon_i )^2] - ( \mathbf{X}_{i, \ast} \, \beta)^2 \\ & -= \mathbb{E} [ ( \mathbf{X}_{i, \ast} \, \beta)^2 + 2 \varepsilon_i -\mathbf{X}_{i, \ast} \, \beta + \varepsilon_i^2 ] - ( \mathbf{X}_{i, -\ast} \, \beta)^2 \\ & = ( \mathbf{X}_{i, \ast} \, \beta)^2 + 2 -\mathbb{E}(\varepsilon_i) \mathbf{X}_{i, \ast} \, \beta + -\mathbb{E}(\varepsilon_i^2 ) - ( \mathbf{X}_{i, \ast} \, \beta)^2 -\\ & = \mathbb{E}(\varepsilon_i^2 ) \, \, \, = \, \, \, -\mbox{Var}(\varepsilon_i) \, \, \, = \, \, \, \sigma^2. -\end{align*} -$$ - -Hence, \( Y_i \sim \mathcal{N}( \mathbf{X}_{i, \ast} \, \beta, \sigma^2) \). - -

    -









    - -

    The singular value decompostion

    -A general -\( m\times n \) matrix \( \hat{A} \) can be written in terms of a diagonal -matrix \( \hat{D} \) of dimensionality \( n\times n \) and two orthognal -matrices \( \hat{U} \) and \( \hat{V} \), where the first has dimensionality -\( m \times m \) and the last dimensionality \( n\times n \). -We have then -$$ -\hat{A} = \hat{U}\hat{D}\hat{V}^T -$$ +The examples we have looked at so far are cases where we normally can +invert the matrix \( \boldsymbol{X}^T\boldsymbol{X} \). Using a polynomial expansion as we +did both for the masses and the fitting of the equation of state, +leads to row vectors of the design matrix which are essentially +orthogonal due to the polynomial character of our model. This may +however not the be case in general and a standard matrix inversion +algorithm based on say LU decomposition may lead to singularities. We will see an example of this below when we try to fit +the coupling constant of the widely used Ising model. +There is however a way to partially circumvent this problem and also gain some insight about the ordinary least squares approach. + +

    +This is given by the Singular Value Decomposition algorithm, perhaps +the most powerful linear algebra algorithm. Let us look at a +different example where we may have problems with the standard matrix +inversion algorithm. Thereafter we dive into the math of the SVD. + +











    -

    From standard regression to Ridge regressions

    +

    The Ising model

    + +

    +The one-dimensional Ising model with nearest neighbor interaction, no +external field and a constant coupling constant \( J \) is given by + +$$ +\begin{align} + H = -J \sum_{k}^L s_k s_{k + 1}, +\label{_auto1} +\end{align} +$$ + +

    +where \( s_i \in \{-1, 1\} \) and \( s_{N + 1} = s_1 \). The number of spins +in the system is determined by \( L \). For the one-dimensional system +there is no phase transition. + +

    +We will look at a system of \( L = 40 \) spins with a coupling constant of +\( J = 1 \). To get enough training data we will generate 10000 states +with their respective energies. + +

    + + +

    import numpy as np
    +import matplotlib.pyplot as plt
    +from mpl_toolkits.axes_grid1 import make_axes_locatable
    +import seaborn as sns
    +import scipy.linalg as scl
    +from sklearn.model_selection import train_test_split
    +import tqdm
    +sns.set(color_codes=True)
    +cmap_args=dict(vmin=-1., vmax=1., cmap='seismic')
    +
    +L = 40
    +n = int(1e4)
    +
    +spins = np.random.choice([-1, 1], size=(n, L))
    +J = 1.0
    +
    +energies = np.zeros(n)
    +
    +for i in range(n):
    +    energies[i] = - J * np.dot(spins[i], np.roll(spins[i], 1))
    +
    +

    +Here we use ordinary least squares +regression to predict the energy for the nearest neighbor +one-dimensional Ising model on a ring, i.e., the endpoints wrap +around. We will use linear regression to fit a value for +the coupling constant to achieve this. + +

    +









    + +

    Reformulating the problem to suit regression

    + +

    +A more general form for the one-dimensional Ising model is + +$$ +\begin{align} + H = - \sum_j^L \sum_k^L s_j s_k J_{jk}. +\label{_auto2} +\end{align} +$$ + +

    +Here we allow for interactions beyond the nearest neighbors and a state dependent +coupling constant. This latter expression can be formulated as +a matrix-product +$$ +\begin{align} + \boldsymbol{H} = \boldsymbol{X} J, +\label{_auto3} +\end{align} +$$ + +

    +where \( X_{jk} = s_j s_k \) and \( J \) is a matrix which consists of the +elements \( -J_{jk} \). This form of writing the energy fits perfectly +with the form utilized in linear regression, that is + +$$ +\begin{align} + \boldsymbol{y} = \boldsymbol{X}\boldsymbol{\beta} + \boldsymbol{\epsilon}, +\label{_auto4} +\end{align} +$$ + +

    +We split the data in training and test data as discussed in the previous example + +

    + + +

    X = np.zeros((n, L ** 2))
    +for i in range(n):
    +    X[i] = np.outer(spins[i], spins[i]).ravel()
    +y = energies
    +X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2)
    +
    +

    +









    + +

    Linear regression

    + +

    +In the ordinary least squares method we choose the cost function + +$$ +\begin{align} + C(\boldsymbol{X}, \boldsymbol{\beta})= \frac{1}{n}\left\{(\boldsymbol{X}\boldsymbol{\beta} - \boldsymbol{y})^T(\boldsymbol{X}\boldsymbol{\beta} - \boldsymbol{y})\right\}. +\label{_auto5} +\end{align} +$$ + +

    +We then find the extremal point of \( C \) by taking the derivative with respect to \( \boldsymbol{\beta} \) as discussed above. +This yields the expression for \( \boldsymbol{\beta} \) to be + +$$ + \boldsymbol{\beta} = \frac{\boldsymbol{X}^T \boldsymbol{y}}{\boldsymbol{X}^T \boldsymbol{X}}, +$$ + +

    +which immediately imposes some requirements on \( \boldsymbol{X} \) as there must exist +an inverse of \( \boldsymbol{X}^T \boldsymbol{X} \). If the expression we are modeling contains an +intercept, i.e., a constant term, we must make sure that the +first column of \( \boldsymbol{X} \) consists of \( 1 \). We do this here + +

    + + +

    X_train_own = np.concatenate(
    +    (np.ones(len(X_train))[:, np.newaxis], X_train),
    +    axis=1
    +)
    +X_test_own = np.concatenate(
    +    (np.ones(len(X_test))[:, np.newaxis], X_test),
    +    axis=1
    +)
    +
    +

    + + +

    def ols_inv(x: np.ndarray, y: np.ndarray) -> np.ndarray:
    +    return scl.inv(x.T @ x) @ (x.T @ y)
    +beta = ols_inv(X_train_own, y_train)
    +
    +

    +









    + +

    Singular Value decomposition

    + +

    +Doing the inversion directly turns out to be a bad idea since the matrix +\( \boldsymbol{X}^T\boldsymbol{X} \) is singular. An alternative approach is to use the singular +value decomposition. Using the definition of the Moore-Penrose +pseudoinverse we can write the equation for \( \boldsymbol{\beta} \) as + +$$ + \boldsymbol{\beta} = \boldsymbol{X}^{+}\boldsymbol{y}, +$$ + +

    +where the pseudoinverse of \( \boldsymbol{X} \) is given by + +$$ + \boldsymbol{X}^{+} = \frac{\boldsymbol{X}^T}{\boldsymbol{X}^T\boldsymbol{X}}. +$$ + +

    +Using singular value decomposition we can decompose the matrix \( \boldsymbol{X} = \boldsymbol{U}\boldsymbol{\Sigma} \boldsymbol{V}^T \), +where \( \boldsymbol{U} \) and \( \boldsymbol{V} \) are orthogonal(unitary) matrices and \( \boldsymbol{\Sigma} \) contains the singular values (more details below). +where \( X^{+} = V\Sigma^{+} U^T \). This reduces the equation for +\( \omega \) to +$$ +\begin{align} + \boldsymbol{\beta} = \boldsymbol{V}\boldsymbol{\Sigma}^{+} \boldsymbol{U}^T \boldsymbol{y}. +\label{_auto6} +\end{align} +$$ + +

    +Note that solving this equation by actually doing the pseudoinverse +(which is what we will do) is not a good idea as this operation scales +as \( \mathcal{O}(n^3) \), where \( n \) is the number of elements in a +general matrix. Instead, doing \( QR \)-factorization and solving the +linear system as an equation would reduce this down to +\( \mathcal{O}(n^2) \) operations. + +

    + + +

    def ols_svd(x: np.ndarray, y: np.ndarray) -> np.ndarray:
    +    u, s, v = scl.svd(x)
    +    return v.T @ scl.pinv(scl.diagsvd(s, u.shape[0], v.shape[0])) @ u.T @ y
    +
    +

    + + +

    beta = ols_svd(X_train_own,y_train)
    +
    +

    +When extracting the \( J \)-matrix we need to make sure that we remove the intercept, as is done here + +

    + + +

    J = beta[1:].reshape(L, L)
    +
    +

    +A way of looking at the coefficients in \( J \) is to plot the matrices as images. + +

    + + +

    fig = plt.figure(figsize=(20, 14))
    +im = plt.imshow(J, **cmap_args)
    +plt.title("OLS", fontsize=18)
    +plt.xticks(fontsize=18)
    +plt.yticks(fontsize=18)
    +cb = fig.colorbar(im)
    +cb.ax.set_yticklabels(cb.ax.get_yticklabels(), fontsize=18)
    +plt.show()
    +
    +

    +It is interesting to note that OLS +considers both \( J_{j, j + 1} = -0.5 \) and \( J_{j, j - 1} = -0.5 \) as +valid matrix elements for \( J \). +In our discussion below on hyperparameters and Ridge and Lasso regression we will see that +this problem can be removed, partly and only with Lasso regression. + +

    +In this case our matrix inversion was actually possible. The obvious question now is what is the mathematics behind the SVD? + +

    +









    + +

    Linear Regression Problems

    One of the typical problems we encounter with linear regression, in particular -when the matrix \( \hat{X} \) (our so-called design matrix) is high-dimensional, -are problems with near singular or singular matrices. The column vectors of \( \hat{X} \) +when the matrix \( \boldsymbol{X} \) (our so-called design matrix) is high-dimensional, +are problems with near singular or singular matrices. The column vectors of \( \boldsymbol{X} \) may be linearly dependent, normally referred to as super-collinearity. This means that the matrix may be rank deficient and it is basically impossible to to model the data using linear regression. As an example, consider the matrix @@ -1375,7 +1620,7 @@ $$ $$

    -The columns of \( \hat{X} \) are linearly dependent. We se this easily since the +The columns of \( \boldsymbol{X} \) are linearly dependent. We see this easily since the the first column is the row-wise sum of the other two columns. The rank (more correct, the column rank) of a matrix is the dimension of the space spanned by the column vectors. Hence, the rank of \( \mathbf{X} \) is equal to the number @@ -1383,10 +1628,10 @@ of linearly independent columns. In this particular case the matrix has rank 2.

    Super-collinearity of an \( (n \times p) \)-dimensional design matrix \( \mathbf{X} \) implies -that the inverse of the matrix \( \hat{X}^T\hat{x} \) (the matrix we needto invert to solve the linear regression equations) is non-invertible. If we have a square matrix that does not have an inverse, we say this matrix singular. The example here demonstrates this +that the inverse of the matrix \( \boldsymbol{X}^T\boldsymbol{x} \) (the matrix we need to invert to solve the linear regression equations) is non-invertible. If we have a square matrix that does not have an inverse, we say this matrix singular. The example here demonstrates this $$ \begin{align*} -\hat{X} & = \left[ +\boldsymbol{X} & = \left[ \begin{array}{rr} 1 & -1 \\ @@ -1395,425 +1640,421 @@ $$ \end{align*} $$ -We see easily that \( \mbox{det}(\hat{X}) = x_{11} x_{22} - x_{12} x_{21} = 1 \times (-1) - 1 \times (-1) = 0 \). Hence, \( \mathbf{X} \) is singular and its inverse is undefined. -This is equivalent to saying that the matrix \( \hat{X} \) has at least an eigenvalue which is zero. +We see easily that \( \mbox{det}(\boldsymbol{X}) = x_{11} x_{22} - x_{12} x_{21} = 1 \times (-1) - 1 \times (-1) = 0 \). Hence, \( \mathbf{X} \) is singular and its inverse is undefined. +This is equivalent to saying that the matrix \( \boldsymbol{X} \) has at least an eigenvalue which is zero.











    -

    Fixing the singularity

    +

    Fixing the singularity

    -If our design matrix \( \hat{X} \) which enters the linear regression problem +If our design matrix \( \boldsymbol{X} \) which enters the linear regression problem $$ \begin{align} -\hat{\beta} & = (\hat{X}^{T} \hat{X})^{-1} \hat{X}^{T} \hat{y}, -\label{_auto1} +\boldsymbol{\beta} & = (\boldsymbol{X}^{T} \boldsymbol{X})^{-1} \boldsymbol{X}^{T} \boldsymbol{y}, +\label{_auto7} \end{align} $$ has linearly dependent column vectors, we will not be able to compute the inverse -of \( \hat{X}^T\hat{X} \) and we cannot find the parameters (estimators) \( \beta_i \). -The estimators are only well-defined if \( (\hat{X}^{T}\hat{X})^{-1} \) exits. -This is more likely to happen when the matrix \( \hat{X} \) is high-dimensional. In this case it is likely to encounter a situation where +of \( \boldsymbol{X}^T\boldsymbol{X} \) and we cannot find the parameters (estimators) \( \beta_i \). +The estimators are only well-defined if \( (\boldsymbol{X}^{T}\boldsymbol{X})^{-1} \) exits. +This is more likely to happen when the matrix \( \boldsymbol{X} \) is high-dimensional. In this case it is likely to encounter a situation where the regression parameters \( \beta_i \) cannot be estimated.

    -The ad hoc approach which was introduced in the 70s was simply to add a diagonal component to the matrix to invert, that is we change +A cheap ad hoc approach is simply to add a small diagonal component to the matrix to invert, that is we change $$ -\hat{X}^{T} \hat{X} \rightarrow \hat{X}^{T} \hat{X}+\lambda \hat{I}, +\boldsymbol{X}^{T} \boldsymbol{X} \rightarrow \boldsymbol{X}^{T} \boldsymbol{X}+\lambda \boldsymbol{I}, $$ -where \( \hat{I} \) is the identity matrix. +where \( \boldsymbol{I} \) is the identity matrix. When we discuss Ridge regression this is actually what we end up evaluating. The parameter \( \lambda \) is called a hyperparameter. More about this later.











    -

    Fitting vs. predicting when data is in the model class

    +

    Basic math of the SVD

    -We start by considering the case -\( f(x)=2x \). +From standard linear algebra we know that a square matrix \( \boldsymbol{X} \) can be diagonalized if and only it is +a so-called normal matrix, that is if \( \boldsymbol{X}\in {\mathbb{R}}^{n\times n} \) +we have \( \boldsymbol{X}\boldsymbol{X}^T=\boldsymbol{X}^T\boldsymbol{X} \) or if \( \boldsymbol{X}\in {\mathbb{C}}^{n\times n} \) we have \( \boldsymbol{X}\boldsymbol{X}^{\dagger}=\boldsymbol{X}^{\dagger}\boldsymbol{X} \). +The matrix has then a set of eigenpairs + +$$ +(\lambda_1,\boldsymbol{u}_1),\dots, (\lambda_n,\boldsymbol{u}_n), +$$ + +and the eigenvalues are given by the diagonal matrix +$$ +\boldsymbol{\Sigma}=\mathrm{Diag}(\lambda_1, \dots,\lambda_n). +$$ + +The matrix \( \boldsymbol{X} \) can be written in terms of an orthogonal/unitary transformation \( \boldsymbol{U} \) +$$ +\boldsymbol{X} = \boldsymbol{U}\boldsymbol{\Sigma}\boldsymbol{V}^T, +$$ + +with \( \boldsymbol{U}\boldsymbol{U}^T=\boldsymbol{I} \) or \( \boldsymbol{U}\boldsymbol{U}^{\dagger}=\boldsymbol{I} \).

    -Then the data is clearly generated by a model that is contained within -all three model classes we are using to make predictions (linear -models, third order polynomials, and tenth order polynomials). +Not all square matrices are diagonalizable. A matrix like the one discussed above +$$ +\boldsymbol{X} = \begin{bmatrix} +1& -1 \\ +1& -1\\ +\end{bmatrix} +$$ + +is not diagonalizable, it is a so-called defective matrix. It is easy to see that the condition +\( \boldsymbol{X}\boldsymbol{X}^T=\boldsymbol{X}^T\boldsymbol{X} \) is not fulfilled.

    -Run the code for the following cases: +









    + +

    The SVD, a Fantastic Algorithm

    + +

    +However, and this is the strength of the SVD algorithm, any general +matrix \( \boldsymbol{X} \) can be decomposed in terms of a diagonal matrix and +two orthogonal/unitary matrices. The Singular Value Decompostion +(SVD) theorem +states that a general \( m\times n \) matrix \( \boldsymbol{X} \) can be written in +terms of a diagonal matrix \( \boldsymbol{\Sigma} \) of dimensionality \( n\times n \) +and two orthognal matrices \( \boldsymbol{U} \) and \( \boldsymbol{V} \), where the first has +dimensionality \( m \times m \) and the last dimensionality \( n\times n \). +We have then + +$$ +\boldsymbol{X} = \boldsymbol{U}\boldsymbol{\Sigma}\boldsymbol{V}^T +$$ + +

    +As an example, the above defective matrix can be decomposed as + +$$ +\boldsymbol{X} = \frac{1}{\sqrt{2}}\begin{bmatrix} 1& 1 \\ 1& -1\\ \end{bmatrix} \begin{bmatrix} 2& 0 \\ 0& 0\\ \end{bmatrix} \frac{1}{\sqrt{2}}\begin{bmatrix} 1& -1 \\ 1& 1\\ \end{bmatrix}=\boldsymbol{U}\boldsymbol{\Sigma}\boldsymbol{V}^T, +$$ + +

    +with eigenvalues \( \sigma_1=2 \) and \( \sigma_2=0 \). +The SVD exits always! + +

    +









    + +

    Another Example

    + +

    +Consider the following matrix which can be SVD decomposed as + +$$ +\boldsymbol{X} = \frac{1}{15}\begin{bmatrix} 14 & 2\\ 4 & 22\\ 16 & 13\end{matrix}=\frac{1}{3}\begin{bmatrix} 1& 2 & 2 \\ 2& -1 & 1\\ 2 & 1& -2\end{bmatrix} \begin{bmatrix} 2& 0 \\ 0& 1\\ 0 & 0\end{bmatrix}\frac{1}{5}\begin{bmatrix} 3& 4 \\ 4& -3\end{bmatrix}=\boldsymbol{U}\boldsymbol{\Sigma}\boldsymbol{V}^T. +$$ + +

    +This is a \( 3\times 2 \) matrix which is decomposed in terms of a +\( 3\times 3 \) matrix \( \boldsymbol{U} \), and a \( 2\times 2 \) matrix \( \boldsymbol{V} \). It is easy to see +that \( \boldsymbol{U} \) and \( \boldsymbol{V} \) are orthogonal (how?). + +

    +And the SVD +decomposition (singular values) gives eigenvalues +\( \sigma_i\geq\sigma_{i+1} \) for all \( i \) and for dimensions larger than \( i=2 \), the +eigenvalues (singular values) are zero. + +

    +In the general case, where our design matrix \( \boldsymbol{X} \) has dimension +\( n\times p \), the matrix is thus decomposed into an \( n\times n \) +orthogonal matrix \( \boldsymbol{U} \), a \( p\times p \) orthogonal matrix \( \boldsymbol{V} \) +and a diagonal matrix \( \boldsymbol{\Sigma} \) with \( r=\mathrm{min}(n,p) \) +singular values \( \sigma_i\lg 0 \) on the main diagonal and zeros filling +the rest of the matrix. There are at most \( p \) singular values +assuming that \( n > p \). In our regression examples for the nuclear +masses and the equation of state this is indeed the case, while for +the Ising model we have \( p > n \). These are often cases that lead to +near singular or singular matrices. + +

    +The columns of \( \boldsymbol{U} \) are called the left singular vectors while the columns of \( \boldsymbol{V} \) are the right singular vectors. + +

    +









    + +

    Economy-size SVD

    + +

    +If we assume that \( n > p \), then our matrix \( \boldsymbol{U} \) has dimension \( n +\times n \). The last \( n-p \) columns of \( \boldsymbol{U} \) become however +irrelevant in our calculations since they are multiplied with the +zeros in \( \boldsymbol{\Sigma} \). + +

    +The economy-size decomposition removes extra rows or columns of zeros +from the diagonal matrix of singular values, \( \boldsymbol{\Sigma} \), along with the columns +in either \( \boldsymbol{U} \) or \( \boldsymbol{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 \( \boldsymbol{U} \) and \( \boldsymbol{\Sigma} \) has dimension \( p\times p \). +If \( p > n \), then only the first \( n \) columns of \( \boldsymbol{V} \) are computed and \( \boldsymbol{\Sigma} \) has dimension \( n\times n \). +The \( n=p \) case is obvious, we retain the full SVD. +In general the economy-size SVD leads to less FLOPS and still conserving the desired accuracy. + +

    +









    + +

    Mathematical Properties

    + +

    +There are several interesting mathematical properties which will be +relevant when we are going to discuss the differences between say +ordinary least squares (OLS) and Ridge regression. + +

    +We have from OLS that the parameters of the linear approximation are given by +$$ +\boldsymbol{\tilde{y}} = \boldsymbol{X}\boldsymbol{\beta} = \boldsymbol{X}\left(\boldsymbol{X}^T\boldsymbol{X}\right)^{-1}\boldsymbol{X}^T\boldsymbol{y}. +$$ + +

    +The matrix to invert can be rewritten in terms of our SVD decomposition as + +$$ +\boldsymbol{X}^T\boldsymbol{X} = \boldsymbol{V}\boldsymbol{\Sigma}^T\boldsymbol{U}^T\boldsymbol{U}\boldsymbol{\Sigma}\boldsymbol{V}^T. +$$ + +Using the orthogonality properties of \( \boldsymbol{U} \) we have + +$$ +\boldsymbol{X}^T\boldsymbol{X} = \boldsymbol{V}\boldsymbol{\Sigma}^T\boldsymbol{\Sigma}\boldsymbol{V}^T = \boldsymbol{V}\boldsymbol{D}\boldsymbol{V}^T, +$$ + +with \( \boldsymbol{D} \) being a diagonal matrix with values along the diagonal given by the singular values squared. + +

    +This means that +$$ +(\boldsymbol{X}^T\boldsymbol{X})\boldsymbol{V} = \boldsymbol{V}\boldsymbol{D}, +$$ + +that is the eigenvectors of \( (\boldsymbol{X}^T\boldsymbol{X}) \) are given by the columns of the right singular matrix of \( \boldsymbol{X} \) and the eigenvalues are the squared singular values. It is easy to show (show this) that +$$ +(\boldsymbol{X}\boldsymbol{X}^T)\boldsymbol{U} = \boldsymbol{U}\boldsymbol{D}, +$$ + +that is, the eigenvectors of \( (\boldsymbol{X}\boldsymbol{X})^T \) are the columns of the left singular matrix and the eigenvalues are the same. + +

    +Going back to our OLS equation we have +$$ +\boldsymbol{X}\boldsymbol{\beta} = \boldsymbol{X}\left(\boldsymbol{V}\boldsymbol{D}\boldsymbol{V}^T \right)^{-1}\boldsymbol{X}^T\boldsymbol{y}=\boldsymbol{U\Sigma V^T}\left(\boldsymbol{V}\boldsymbol{D}\boldsymbol{V}^T \right)^{-1}(\boldsymbol{U\Sigma V^T})^T\boldsymbol{y}=\boldsymbol{U}\boldsymbol{U}^T\boldsymbol{y}. +$$ + +We will come back to this expression when we discuss Ridge regression. + +

    +









    + +

    Ridge and LASSO Regression

    + +

    +Let us remind ourselves about the expression for the standard Mean Squared Error (MSE) which we used to define our cost function and the equations for the ordinary least squares (OLS) method, that is +our optimization problem is +$$ +{\displaystyle \min_{\boldsymbol{\beta}\in {\mathbb{R}}^{p}}}\frac{1}{n}\left\{\left(\boldsymbol{y}-\boldsymbol{X}\boldsymbol{\beta}\right)^T\left(\boldsymbol{y}-\boldsymbol{X}\boldsymbol{\beta}\right)\right\}. +$$ + +or we can state it as +$$ +{\displaystyle \min_{\boldsymbol{\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 \boldsymbol{y}-\boldsymbol{X}\boldsymbol{\beta}\vert\vert_2^2, +$$ + +where we have used the definition of a norm-2 vector, that is +$$ +\vert\vert \boldsymbol{x}\vert\vert_2 = \sqrt{\sum_i x_i^2}. +$$ + +

    +By minimizing the above equation with respect to the parameters +\( \boldsymbol{\beta} \) we could then obtain an analytical expression for the +parameters \( \boldsymbol{\beta} \). We can add a regularization parameter \( \lambda \) by +defining a new cost function to be optimized, that is + +$$ +{\displaystyle \min_{\boldsymbol{\beta}\in +{\mathbb{R}}^{p}}}\frac{1}{n}\vert\vert \boldsymbol{y}-\boldsymbol{X}\boldsymbol{\beta}\vert\vert_2^2+\lambda\vert\vert \boldsymbol{\beta}\vert\vert_2^2 +$$ + +

    +which leads to the Ridge regression minimization problem where we +require that \( \vert\vert \boldsymbol{\beta}\vert\vert_2^2\le t \), where \( t \) is +a finite number larger than zero. By defining + +$$ +C(\boldsymbol{X},\boldsymbol{\beta})=\frac{1}{n}\vert\vert \boldsymbol{y}-\boldsymbol{X}\boldsymbol{\beta}\vert\vert_2^2+\lambda\vert\vert \boldsymbol{\beta}\vert\vert_1, +$$ + +

    +we have a new optimization equation +$$ +{\displaystyle \min_{\boldsymbol{\beta}\in +{\mathbb{R}}^{p}}}\frac{1}{n}\vert\vert \boldsymbol{y}-\boldsymbol{X}\boldsymbol{\beta}\vert\vert_2^2+\lambda\vert\vert \boldsymbol{\beta}\vert\vert_1 +$$ + +which leads to Lasso regression. Lasso stands for least absolute shrinkage and selection operator. + +

    +Here we have defined the norm-1 as +$$ +\vert\vert \boldsymbol{x}\vert\vert_1 = \sum_i \vert x_i\vert. +$$ + +

    +









    + +

    More on Ridge Regression

    + +

    +Using the matrix-vector expression for Ridge regression, + +$$ +C(\boldsymbol{X},\boldsymbol{\beta})=\frac{1}{n}\left\{(\boldsymbol{y}-\boldsymbol{X}\boldsymbol{\beta})^T(\boldsymbol{y}-\boldsymbol{X}\boldsymbol{\beta})\right\}+\lambda\boldsymbol{\beta}^T\boldsymbol{\beta}, +$$ + +

    +by taking the derivatives with respect to \( \boldsymbol{\beta} \) we obtain then +a slightly modified matrix inversion problem which for finite values +of \( \lambda \) does not suffer from singularity problems. We obtain + +$$ +\boldsymbol{\beta}^{\mathrm{Ridge}} = \left(\boldsymbol{X}^T\boldsymbol{X}+\lambda\boldsymbol{I}\right)^{-1}\boldsymbol{X}^T\boldsymbol{y}, +$$ + +

    +with \( \boldsymbol{I} \) being a \( p\times p \) identity matrix with the constraint that + +$$ +\sum_{i=0}^{p-1} \beta_i^2 \leq t, +$$ + +

    +with \( t \) a finite positive number. + +

    +We see that Ridge regression is nothing but the standard +OLS with a modified diagonal term added to \( \boldsymbol{X}^T\boldsymbol{X} \). The +consequences, in particular for our discussion of the bias-variance +are rather interesting. + +

    +Furthermore, if we use the result above in terms of the SVD decomposition (our analysis was done for the OLS method), we had +$$ +(\boldsymbol{X}\boldsymbol{X}^T)\boldsymbol{U} = \boldsymbol{U}\boldsymbol{D}. +$$ + +

    +We can analyse the OLS solutions in terms of the eigenvectors (the columns) of the right singular value matrix \( \boldsymbol{U} \) as +$$ +\boldsymbol{X}\boldsymbol{\beta} = \boldsymbol{X}\left(\boldsymbol{V}\boldsymbol{D}\boldsymbol{V}^T \right)^{-1}\boldsymbol{X}^T\boldsymbol{y}=\boldsymbol{U\Sigma V^T}\left(\boldsymbol{V}\boldsymbol{D}\boldsymbol{V}^T \right)^{-1}(\boldsymbol{U\Sigma V^T})^T\boldsymbol{y}=\boldsymbol{U}\boldsymbol{U}^T\boldsymbol{y} +$$ + +

    +For Ridge regression this becomes + +$$ +\boldsymbol{X}\boldsymbol{\beta}^{\mathrm{Ridge}} = \boldsymbol{U\Sigma V^T}\left(\boldsymbol{V}\boldsymbol{D}\boldsymbol{V}^T+\lambda\boldsymbol{I} \right)^{-1}(\boldsymbol{U\Sigma V^T})^T\boldsymbol{y}=\sum_{j=0}^{p-1}\boldsymbol{u}_j\boldsymbol{u}_j^T\frac{\sigma_j^2}{\sigma_j^2+\lambda}\boldsymbol{y}, +$$ + +

    +with the vectors \( \boldsymbol{u}_j \) being the columns of \( \boldsymbol{U} \). + +

    +









    + +

    Interpreting the Ridge results

    + +

    +Since \( \lambda \geq 0 \), it means that compared to OLS, we have + +$$ +\frac{\sigma_j^2}{\sigma_j^2+\lambda} \leq 1. +$$ + +

    +Ridge regression finds the coordinates of \( \boldsymbol{y} \) with respect to the +orthonormal basis \( \boldsymbol{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 \( \boldsymbol{X}\boldsymbol{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. + +

    +









    + +

    More interpretations

    + +

    +For the sake of simplicity, let us assume that the design matrix is orthonormal, that is + +$$ +\boldsymbol{X}^T\boldsymbol{X}=(\boldsymbol{X}^T\boldsymbol{X})^{-1} =\boldsymbol{I}. +$$ + +

    +In this case the standard OLS results in +$$ +\boldsymbol{\beta}^{\mathrm{OLS}} = \boldsymbol{X}^T\boldsymbol{y}=\sum_{i=0}^{p-1}\boldsymbol{u}_j\boldsymbol{u}_j^T\boldsymbol{y}, +$$ + +

    +and + +$$ +\boldsymbol{\beta}^{\mathrm{Ridge}} = \left(\boldsymbol{I}+\lambda\boldsymbol{I}\right)^{-1}\boldsymbol{X}^T\boldsymbol{y}=\left(1+\lambda\right)^{-1}\boldsymbol{\beta}^{\mathrm{OLS}}, +$$ + +

    +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 article is highly recommended. +Similarly, Mehta et al's article is also recommended. + +

    +









    + +

    Where are we going?

    + +

    +Before we proceed, we need to rethink what we have been doing. In our +eager to fit the data, we have omitted several important elements in +our regression analysis. In what follows we will

      -
    1. For \( f(x)=2x \) , \( Ntrain=10 \) and \( \sigma =0 \) (noiseless case), train the three classes of models (linear, third-order polynomial, and tenth order polynomial) for a training set when \( x \in [0,1] \) . Make graphs comparing fits for different order of polynomials. Which model fits the data the best?
    2. -
    3. Do you think that the data that has the least error on the training set will also make the best predictions? Why or why not? Can you try to discuss and formalize your intuition? What can go right and what can go wrong?
    4. -
    5. Check your answer by seeing how well your fits predict newly generated test data (including on data outside the range you fit on, for example \( x \in [0,1.2] \) ) using the code below. How well do you do on points in the range of x where you trained the model? How about points outside the original training data set?
    6. -
    7. Repeat the above for \( f(x)=2x \) , \( Ntrain=10 \) , and \( \sigma=1 \) . What changes?
    8. +
    9. look at statistical properties, including a discussion of mean values, variance and the so-called bias-variance tradeoff
    10. +
    11. introduce resampling techniques like cross-validation, bootstrapping and jackknife and more
    -Repeat the exercises above for \( f(x)=2x \) , \( Ntrain=100 \) , and \( \sigma=1 \) . What changes? -Summarize what you have learned about the relationship between model complexity (number of parameters), goodness of fit on training data, and the ability to predict well. +This will allow us to link the standard linear algebra methods we have discussed above to a statistical interpretation of the methods.











    -

    Fitting versus predicting when data is not in the model class

    - -

    -Thus far, we have considered the case where the data is generated using a model contained in the model class. Now consider \( f(x)=2x-10x^5+15x^{10} \) . Notice that the for linear and third-order polynomial the true model \( f(x) \) is not contained in model class. - -

      -
    1. Do better fits lead to better predictions?
    2. -
    3. What is the relationship between the true model for generating the data and the model class that has the most predictive power? How is this related to the model complexity? How does this depend on the number of data points \( Ntrain \) and \( \sigma \)?
    4. -
    - -Summarize what you think you learned about the relationship of knowing the true model class and predictive power. - -

    -









    - -

    An example code without the model assessment part

    - -

    - - -

    import numpy as np
    -import sklearn as sk
    -from sklearn import datasets, linear_model
    -from sklearn.preprocessing import PolynomialFeatures
    -
    -import matplotlib as mpl
    -from matplotlib import pyplot as plt
    -
    -%matplotlib notebook
    -
    -# The Training Data
    -
    -N_train=100
    -
    -sigma_train=1;
    -
    -# Train on integers
    -x=np.linspace(0.05,0.95,N_train)
    -# Draw random noise
    -s = sigma_train*np.random.randn(N_train)
    -
    -#linear
    -y=2*x+s
    -
    -#Tenth Order
    -#y=2*x-10*x**5+15*x**10+s
    -
    -p1=plt.plot(x,y, "o",ms=15, label='Training')
    -
    -#Linear Regression
    -# Create linear regression object
    -clf = linear_model.LinearRegression()
    -
    -# Train the model using the training sets
    -clf.fit(x[:, np.newaxis], y)
    -# The coefficients
    -
    -xplot=np.linspace(0.02,0.98,200)
    -linear_plot=plt.plot(xplot, clf.predict(xplot[:, np.newaxis]),label='Linear')
    -
    -#Polynomial Regression
    -
    -
    -poly3 = PolynomialFeatures(degree=3)
    -X = poly3.fit_transform(x[:,np.newaxis])
    -clf3 = linear_model.LinearRegression()
    -clf3.fit(X,y)
    -
    -
    -Xplot=poly3.fit_transform(xplot[:,np.newaxis])
    -poly3_plot=plt.plot(xplot, clf3.predict(Xplot), label='Poly 3')
    -
    -
    -
    -#poly5 = PolynomialFeatures(degree=5)
    -#X = poly5.fit_transform(x[:,np.newaxis])
    -#clf5 = linear_model.LinearRegression()
    -#clf5.fit(X,y)
    -
    -#Xplot=poly5.fit_transform(xplot[:,np.newaxis])
    -#plt.plot(xplot, clf5.predict(Xplot), 'r--',linewidth=1)
    -
    -poly10 = PolynomialFeatures(degree=10)
    -X = poly10.fit_transform(x[:,np.newaxis])
    -clf10 = linear_model.LinearRegression()
    -clf10.fit(X,y)
    -
    -Xplot=poly10.fit_transform(xplot[:,np.newaxis])
    -poly10_plot=plt.plot(xplot, clf10.predict(Xplot), label='Poly 10')
    -
    -axes = plt.gca()
    -axes.set_ylim([-7,7])
    -
    -handles, labels=axes.get_legend_handles_labels()
    -plt.legend(handles,labels, loc='lower center')
    -plt.xlabel("$x$")
    -plt.ylabel("$y$")
    -Title="$N=$"+str(N_train)+", $\sigma=$"+str(sigma_train)
    -plt.title(Title+" (train)")
    -plt.tight_layout()
    -plt.show()
    -
    -

    - - -

    Generating test data

    -

    - - -

    # Generate Test Data
    -
    -#Number of test data
    -N_test=20
    -
    -sigma_test=sigma_train
    -
    -max_x=1.2
    -x_test=max_x*np.random.random(N_test)
    -# Draw random noise
    -s_test = sigma_test*np.random.randn(N_test)
    -
    -#Linear
    -y_test=2*x_test+s_test
    -#Tenth order
    -#y_test=2*x_test-10*x_test**5+15*x_test**10+s_test
    -
    -#Make design matrices for prediction
    -x_plot=np.linspace(0,max_x, 200)
    -X3 = poly3.fit_transform(x_plot[:,np.newaxis])
    -X10 = poly10.fit_transform(x_plot[:,np.newaxis])
    -
    -%matplotlib notebook
    -
    -fig = plt.figure() 
    -p1=plt.plot(x_test,y_test.transpose(), 'o', ms=12, label='data')
    -p2=plt.plot(x_plot,clf.predict(x_plot[:,np.newaxis]), label='linear')
    -p3=plt.plot(x_plot,clf3.predict(X3), label='3rd order')
    -p10=plt.plot(x_plot,clf10.predict(X10), label='10th order')
    -
    -
    -plt.legend(loc=2)
    -plt.xlabel('$x$')
    -plt.ylabel('$y$')
    -plt.legend(loc='best')
    -plt.title(Title+" (pred.)")
    -plt.tight_layout()
    -plt.show()
    -
    -

    -









    - -

    How can we effectively evaluate the various models?

    - -

    -In Ridge regression and the subsequent discussion of its properties -the bias or penalty parameter is considered known or `given'. In -practice, it is unknown and the user needs to make an informed -decision on its value. How do we do that? Much of the same considerations apply to the Lasso method. - -

    -









    - -

    Code examples for Ridge and Lasso Regression

    - -

    - - -

    import matplotlib.pyplot as plt
    -import numpy as np
    -from sklearn import linear_model
    -from sklearn.linear_model import LinearRegression
    -from sklearn.metrics import mean_squared_error, r2_score
    -
    -#creating data with random noise
    -x=np.arange(50)
    -
    -delta=np.random.uniform(-2.5,2.5, size=(50))
    -np.random.shuffle(delta)
    -y =0.5*x+5+delta
    -
    -#arranging data into 2x50 matrix
    -a=np.array(x) #inputs
    -b=np.array(y) #outputs
    -
    -#Split into training and test
    -X_train=a[:37, np.newaxis]
    -X_test=a[37:, np.newaxis]
    -y_train=b[:37]
    -y_test=b[37:]
    -
    -print ("X_train: ", X_train.shape)
    -print ("y_train: ", y_train.shape)
    -print ("X_test: ", X_test.shape)
    -print ("y_test: ", y_test.shape)
    -
    -print ("------------------------------------")
    -
    -print ("Ordinary Least Squares")
    -#Add Ordinary Least Squares fit
    -reg=LinearRegression()
    -reg.fit(X_train, y_train)
    -pred=reg.predict(X_test)
    -print ("Prediction Shape: ", pred.shape)
    -
    -print('Coefficients: \n', reg.coef_)
    -# The mean squared error
    -print("Mean squared error: %.2f"
    -      % mean_squared_error(y_test, pred))
    -# Explained variance score: 1 is perfect prediction
    -print('Variance score: %.2f' % r2_score(y_test, pred))
    -
    -#plot
    -plt.scatter(X_test,y_test,color='green', label="Training Data")
    -plt.plot(X_test, pred, color='black', label="Fit Line")
    -plt.legend()
    -plt.show()
    -
    -print ("------------------------------------")
    -
    -print ("Ridge Regression")
    -
    -ridge=linear_model.RidgeCV(alphas=[0.1,1.0,10.0])
    -ridge.fit(X_train,y_train)
    -print ("Ridge Coefficient: ",ridge.coef_)
    -print ("Ridge Intercept: ", ridge.intercept_)
    -#Look into graphing with Ridge fit
    -
    -print ("------------------------------------")
    -
    -print ("Lasso")
    -lasso=linear_model.Lasso(alpha=0.1)
    -lasso.fit(X_train,y_train)
    -predl=lasso.predict(X_test)
    -print("Lasso Coefficient: ", lasso.coef_)
    -print("Lasso Intercept: ", lasso.intercept_)
    -plt.scatter(X_test,y_test,color='green', label="Training Data")
    -plt.plot(X_test, predl, color='blue', label="Lasso")
    -plt.legend()
    -plt.show()
    -
    -

    -









    - -

    A second-order polynomial with Ridge and Lasso

    -

    - - -

    import numpy as np
    -import matplotlib.pyplot as plt
    -from sklearn.linear_model import Ridge
    -from sklearn.metrics import r2_score
    -
    -np.random.seed(4155)
    -
    -n_samples = 100
    -
    -x = np.random.rand(n_samples,1)
    -y = 5*x*x + 0.1*np.random.rand(n_samples,1)
    -
    -# Centering  x and y.
    -x_ = x - np.mean(x)
    -y_ = y - np.mean(y) # beta_0 = mean(y)
    -
    -X = np.c_[np.ones((n_samples,1)), x, x**2]
    -X_ = np.c_[x_, x_**2]
    -
    -
    -### 1.
    -lmb_values = [1e-4, 1e-3, 1e-2, 10, 1e2, 1e4]
    -num_values = len(lmb_values)
    -
    -## Ridge-regression of centered and not centered data
    -beta_ridge = np.zeros((3,num_values))
    -beta_ridge_centered = np.zeros((3,num_values))
    -
    -I3 = np.eye(3)
    -I2 = np.eye(2)
    -
    -for i,lmb in enumerate(lmb_values):
    -    beta_ridge[:,i] = (np.linalg.inv( X.T @ X + lmb*I3) @ X.T @ y).flatten()
    -    beta_ridge_centered[1:,i] = (np.linalg.inv( X_.T @ X_ + lmb*I2) @ X_.T @ y_).flatten()
    -
    -# sett beta_0 = np.mean(y)
    -beta_ridge_centered[0,:] = np.mean(y)
    -
    -## OLS (ordinary least squares) solution 
    -beta_ls = np.linalg.inv( X.T @ X ) @ X.T @ y
    -
    -## Evaluate the models
    -pred_ls = X @ beta_ls
    -pred_ridge =  X @ beta_ridge
    -pred_ridge_centered =  X_ @ beta_ridge_centered[1:] + beta_ridge_centered[0,:]
    -
    -## Plot the results
    -
    -# Sorting
    -sort_ind = np.argsort(x[:,0])
    -
    -x_plot = x[sort_ind,0]
    -x_centered_plot = x_[sort_ind,0]
    -
    -pred_ls_plot = pred_ls[sort_ind,0]
    -pred_ridge_plot = pred_ridge[sort_ind,:]
    -pred_ridge_centered_plot = pred_ridge_centered[sort_ind,:]
    -
    -# Plott not centered
    -plt.plot(x_plot,pred_ls_plot,label='ls')
    -
    -for i in range(num_values):
    -    plt.plot(x_plot,pred_ridge_plot[:,i],label='ridge, lmb=%g'%lmb_values[i])
    -
    -plt.plot(x,y,'ro')
    -
    -plt.title('linear regression on un-centered data')
    -plt.legend()
    -
    -# Plott centered
    -plt.figure()
    -
    -for i in range(num_values):
    -    plt.plot(x_centered_plot,pred_ridge_centered_plot[:,i],label='ridge, lmb=%g'%lmb_values[i])
    -
    -plt.plot(x_,y,'ro')
    -
    -plt.title('linear regression on centered data')
    -plt.legend()
    -
    -
    -# 2.
    -
    -pred_ridge_scikit =  np.zeros((n_samples,num_values))
    -for i,lmb in enumerate(lmb_values):
    -    pred_ridge_scikit[:,i] = (Ridge(alpha=lmb,fit_intercept=False).fit(X,y).predict(X)).flatten() # fit_intercept=False fordi bias er allerede i X
    -
    -plt.figure()
    -
    -plt.plot(x_plot,pred_ls_plot,label='ls')
    -
    -for i in range(num_values):
    -    plt.plot(x_plot,pred_ridge_scikit[sort_ind,i],label='scikit-ridge, lmb=%g'%lmb_values[i])
    -
    -plt.plot(x,y,'ro')
    -plt.legend()
    -plt.title('linear regression using scikit')
    -
    -plt.show()
    -
    -### R2-score of the results
    -for i in range(num_values):
    -    print('lambda = %g'%lmb_values[i])
    -    print('r2 for scikit: %g'%r2_score(y,pred_ridge_scikit[:,i]))
    -    print('r2 for own code, not centered: %g'%r2_score(y,pred_ridge[:,i]))
    -    print('r2 for own, centered: %g\n'%r2_score(y,pred_ridge_centered[:,i]))
    -
    -

    -









    - -

    Resampling methods

    +

    Resampling methods

    @@ -1833,9 +2074,11 @@ once using the original training sample.











    -

    Resampling approaches can be computationally expensive

    +

    Resampling approaches can be computationally expensive

    +

    +

    Resampling approaches can be computationally expensive, because they involve fitting the same statistical method multiple times using @@ -1852,21 +2095,23 @@ of flexibility. The process of evaluating a model’s performance is known as model assessment, whereas the process of selecting the proper level of flexibility for a model is known as model selection. The bootstrap is widely used. + +











    -

    Why resampling methods ?

    +

    Why resampling methods ?

    Statistical analysis.

      -
    • Our simulations can be treated as computer experiments. This is particularly the case for Monte Carlo methods
    • -
    • The results can be analysed with the same statistical tools as we would use analysing experimental data.
    • -
    • As in all experiments, we are looking for expectation values and an estimate of how accurate they are, i.e., possible sources for errors.
    • +
    • Our simulations can be treated as computer experiments. This is particularly the case for Monte Carlo methods
    • +
    • The results can be analysed with the same statistical tools as we would use analysing experimental data.
    • +
    • As in all experiments, we are looking for expectation values and an estimate of how accurate they are, i.e., possible sources for errors.
    @@ -1874,21 +2119,21 @@ bootstrap is widely used.











    -

    Statistical analysis

    +

    Statistical analysis

      -
    • As in other experiments, many numerical experiments have two classes of errors:
    • +
    • As in other experiments, many numerical experiments have two classes of errors:
      • -
      • Statistical errors
      • -
      • Systematical errors
      • +
      • Statistical errors
      • +
      • Systematical errors
      -
    • Statistical errors can be estimated using standard tools from statistics
    • -
    • Systematical errors are method specific and must be treated differently from case to case.
    • +
    • Statistical errors can be estimated using standard tools from statistics
    • +
    • Systematical errors are method specific and must be treated differently from case to case.
    @@ -1896,7 +2141,7 @@ bootstrap is widely used.











    -

    Statistics

    +

    Statistics

    @@ -1927,7 +2172,7 @@ selection of a large set of these numbers reproduces this PDF.











    -

    Statistics, moments

    +

    Statistics, moments

    @@ -1950,7 +2195,7 @@ $$











    -

    Statistics, central moments

    +

    Statistics, central moments

    @@ -1968,14 +2213,14 @@ $$ \begin{align} \sigma^2_X\ \ =\ \ \mathrm{var}(X) & = \langle (x-\langle x\rangle)^2\rangle = \int\! (x-\langle x\rangle)^2 p(x)\,dx -\label{_auto2}\\ +\label{_auto8}\\ & = \int\! \left(x^2 - 2 x \langle x\rangle^{2} + \langle x\rangle^2\right)p(x)\,dx -\label{_auto3}\\ +\label{_auto9}\\ & = \langle x^2\rangle - 2 \langle x\rangle\langle x\rangle + \langle x\rangle^2 -\label{_auto4}\\ +\label{_auto10}\\ & = \langle x^2\rangle - \langle x\rangle^2 -\label{_auto5} +\label{_auto11} \end{align} $$ @@ -1988,7 +2233,7 @@ qualitatively as the spread of \( p \) around its mean.











    -

    Statistics, covariance

    +

    Statistics, covariance

    @@ -2019,7 +2264,7 @@ $$











    -

    Statistics, more covariance

    +

    Statistics, more covariance

    @@ -2032,17 +2277,17 @@ the expectation value. Consider the stochastic variables \( X_i \) and $$ \begin{align} \mathrm{cov}(X_i,\,X_j) &= \langle(x_i-\langle x_i\rangle)(x_j-\langle x_j\rangle)\rangle -\label{_auto6}\\ +\label{_auto12}\\ &=\langle x_i x_j - x_i\langle x_j\rangle - \langle x_i\rangle x_j + \langle x_i\rangle\langle x_j\rangle\rangle -\label{_auto7}\\ +\label{_auto13}\\ &=\langle x_i x_j\rangle - \langle x_i\langle x_j\rangle\rangle - \langle \langle x_i\rangle x_j\rangle + \langle \langle x_i\rangle\langle x_j\rangle\rangle -\label{_auto8}\\ +\label{_auto14}\\ &=\langle x_i x_j\rangle - \langle x_i\rangle\langle x_j\rangle - \langle x_i\rangle\langle x_j\rangle + \langle x_i\rangle\langle x_j\rangle -\label{_auto9}\\ +\label{_auto15}\\ &=\langle x_i x_j\rangle - \langle x_i\rangle\langle x_j\rangle -\label{_auto10} +\label{_auto16} \end{align} $$

    @@ -2051,7 +2296,7 @@ $$











    -

    Statistics, independent variables

    +

    Statistics, independent variables

    @@ -2077,7 +2322,7 @@ $$











    -

    Statistics, more variance

    +

    Statistics, more variance

    @@ -2109,7 +2354,7 @@ value of a set of measurements.











    -

    Statistics and stochastic processes

    +

    Statistics and stochastic processes

    @@ -2137,7 +2382,7 @@ interested in finding the few lowest moments, like the mean

    -

    Statistics and sample variables

    +

    Statistics and sample variables

    @@ -2163,7 +2408,7 @@ $$











    -

    Statistics, sample variance and covariance

    +

    Statistics, sample variance and covariance

    @@ -2184,7 +2429,7 @@ and covariance \( \mathrm{cov}(X,Y) \).











    -

    Statistics, law of large numbers

    +

    Statistics, law of large numbers

    @@ -2216,7 +2461,7 @@ true PDFs behind, which we usually do not have.











    -

    Statistics, more on sample error

    +

    Statistics, more on sample error

    @@ -2238,7 +2483,7 @@ means.











    -

    Statistics

    +

    Statistics

    @@ -2259,7 +2504,7 @@ And in particular we are interested in its variance \( \mathrm{var}(\overline X_











    -

    Statistics, central limit theorem

    +

    Statistics, central limit theorem

    @@ -2284,7 +2529,7 @@ $$











    -

    Statistics, more technicalities

    +

    Statistics, more technicalities

    @@ -2313,7 +2558,7 @@ estimate of the PDF of each of the \( X_i \), estimating all properties of











    -

    Statistics

    +

    Statistics

    @@ -2340,7 +2585,7 @@ $$











    -

    Statistics and sample variance

    +

    Statistics and sample variance

    @@ -2379,7 +2624,7 @@ measurements in the sample.











    -

    Statistics, uncorrelated results

    +

    Statistics, uncorrelated results

    @@ -2414,7 +2659,7 @@ cannot overlook the always present correlations.











    -

    Statistics, computations

    +

    Statistics, computations

    @@ -2443,7 +2688,7 @@ measurements. For uncorrelated measurements this second term is zero.











    -

    Statistics, more on computations of errors

    +

    Statistics, more on computations of errors

    @@ -2465,7 +2710,7 @@ have to be stored throughout the experiment.











    -

    Statistics, wrapping up 1

    +

    Statistics, wrapping up 1

    @@ -2498,7 +2743,7 @@ starting always at \( 1 \) for \( d=0 \).











    -

    Statistics, final expression

    +

    Statistics, final expression

    @@ -2531,7 +2776,7 @@ $$











    -

    Statistics, effective number of correlations

    +

    Statistics, effective number of correlations

    @@ -2554,42 +2799,187 @@ measurements is very large.

    -









    + -

    Log-likelihood

    +

    Linking the regression analysis with a statistical interpretation

    -A popular strategy is to choose a penalty parameter that yields a good -but parsimonious model. Information criteria measure the balance -between model fit and model complexity. One possibility is Aikaike's -information criterion (AIC). -The AIC measures model fit by the log-likelihood -and model complexity is measured by the number of parameters used by -the model. The number of model parameters in regular regression simply -corresponds to the number of covariates in the model. Or, by the -degrees of freedom consumed by the model, which is equivalent to the -trace of the hat matrix. For ridge regression it thus seems natural to -define model complexity analogously by the trace of the ridge hat -matrix. This yields the AIC for the linear regression model with ridge -estimates: +Finally, we are going to discuss several statistical properties which can be obtained in terms of analytical expressions. +The +advantage of doing linear regression is that we actually end up with +analytical expressions for several statistical quantities. +Standard least squares and Ridge regression allow us to +derive quantities like the variance and other expectation values in a +rather straightforward way. +

    +It is assumed that \( \varepsilon_i +\sim \mathcal{N}(0, \sigma^2) \) and the \( \varepsilon_{i} \) are +independent, i.e.: $$ -\begin{align*} -\mbox{AIC}(\lambda) & = 2 \, p - 2 \log(\hat{L}) -\\ -& = 2 \, \mbox{tr} [\mathbf{H}(\lambda)] - 2 \log\{L[\hat{\beta}(\lambda), \hat{\sigma}^2(\lambda)]\} -\\ -& = 2 \, \sum_{j=1}^p \frac{d_{jj}^2}{d_{jj}^2 + \lambda} -+ 2 n \, \log[\sqrt{2 \, \pi} \, \hat{\sigma}(\lambda)] + \frac{1}{\hat{\sigma}^2(\lambda)} \sum_{i=1}^n [y_i - \mathbf{X}_{i, \ast} \, \hat{\beta}(\lambda)]^2. +\begin{align*} +\mbox{Cov}(\varepsilon_{i_1}, +\varepsilon_{i_2}) & = \left\{ \begin{array}{lcc} \sigma^2 & \mbox{if} +& i_1 = i_2, \\ 0 & \mbox{if} & i_1 \not= i_2. \end{array} \right. +\end{align*} +$$ + +The randomness of \( \varepsilon_i \) implies that +\( \mathbf{y}_i \) is also a random variable. In particular, +\( \mathbf{y}_i \) is normally distributed, because \( \varepsilon_i \sim +\mathcal{N}(0, \sigma^2) \) and \( \mathbf{X}_{i,\ast} \, \boldsymbol{\beta} \) is a +non-random scalar. To specify the parameters of the distribution of +\( \mathbf{y}_i \) we need to calculate its first two moments. + +

    +Recall that \( \boldsymbol{X} \) is a matrix of dimensionality \( n\times p \). The +notation above \( \mathbf{X}_{i,\ast} \) means that we are looking at the +row number \( i \) and perform a sum over all values \( p \). + +

    +









    + +

    Assumptions made

    + +

    +The assumption we have made here can be summarized as (and this is going to useful when we discuss the bias-variance trade off) +that there exists a function \( f(\boldsymbol{x}) \) and a normal distributed error \( \boldsymbol{\varepsilon}\sim \mathcal{N}(0, \sigma^2) \) +which describes our data +$$ +\boldsymbol{y} = f(\boldsymbol{x})+\boldsymbol{\varepsilon} +$$ + +

    +We approximate this function with our model from the solution of the linear regression equations, that is our +function \( f \) is approximated by \( \boldsymbol{\tilde{y}} \) where we want to minimize \( (\boldsymbol{y}-\boldsymbol{\tilde{y}})^2 \), our MSE, with +$$ +\boldsymbol{\tilde{y}} = \boldsymbol{X}\boldsymbol{\beta}. +$$ + +

    +









    + +

    Expectation value and variance

    + +

    +We can calculate the expectation value of \( \boldsymbol{y} \) for a given element \( i \) +$$ +\begin{align*} +\mathbb{E}(y_i) & = +\mathbb{E}(\mathbf{X}_{i, \ast} \, \boldsymbol{\beta}) + \mathbb{E}(\varepsilon_i) +\, \, \, = \, \, \, \mathbf{X}_{i, \ast} \, \beta, +\end{align*} +$$ + +while +its variance is +$$ +\begin{align*} \mbox{Var}(y_i) & = \mathbb{E} \{ [y_i +- \mathbb{E}(y_i)]^2 \} \, \, \, = \, \, \, \mathbb{E} ( y_i^2 ) - +[\mathbb{E}(y_i)]^2 \\ & = \mathbb{E} [ ( \mathbf{X}_{i, \ast} \, +\beta + \varepsilon_i )^2] - ( \mathbf{X}_{i, \ast} \, \boldsymbol{\beta})^2 \\ & += \mathbb{E} [ ( \mathbf{X}_{i, \ast} \, \boldsymbol{\beta})^2 + 2 \varepsilon_i +\mathbf{X}_{i, \ast} \, \boldsymbol{\beta} + \varepsilon_i^2 ] - ( \mathbf{X}_{i, +\ast} \, \beta)^2 \\ & = ( \mathbf{X}_{i, \ast} \, \boldsymbol{\beta})^2 + 2 +\mathbb{E}(\varepsilon_i) \mathbf{X}_{i, \ast} \, \boldsymbol{\beta} + +\mathbb{E}(\varepsilon_i^2 ) - ( \mathbf{X}_{i, \ast} \, \boldsymbol{\beta})^2 +\\ & = \mathbb{E}(\varepsilon_i^2 ) \, \, \, = \, \, \, +\mbox{Var}(\varepsilon_i) \, \, \, = \, \, \, \sigma^2. \end{align*} $$ -The value of \( \lambda \) which minimizes \( \mbox{AIC}(\lambda) \) corresponds to the `optimal' balance of model complexity and overfitting. +Hence, \( y_i \sim \mathcal{N}( \mathbf{X}_{i, \ast} \, \boldsymbol{\beta}, \sigma^2) \), that is \( \boldsymbol{y} \) follows a normal distribution with +mean value \( \boldsymbol{X}\boldsymbol{\beta} \) and variance \( \sigma^2 \) (not be confused with the singular values of the SVD). + +

    +









    + +

    Expectation value and variance for \( \boldsymbol{\beta} \)

    + +

    +With the OLS expressions for the parameters \( \boldsymbol{\beta} \) we can evaluate the expectation value +$$ +\mathbb{E}(\boldsymbol{\beta}) = \mathbb{E}[ (\mathbf{X}^{\top} \mathbf{X})^{-1}\mathbf{X}^{T} \mathbf{Y}]=(\mathbf{X}^{T} \mathbf{X})^{-1}\mathbf{X}^{T} \mathbb{E}[ \mathbf{Y}]=(\mathbf{X}^{T} \mathbf{X})^{-1} \mathbf{X}^{T}\mathbf{X}\boldsymbol{\beta}=\boldsymbol{\beta}. +$$ + +This means that the estimator of the regression parameters is unbiased. + +

    +We can also calculate the variance + +

    +The variance of \( \boldsymbol{\beta} \) is +$$ +\begin{eqnarray*} +\mbox{Var}(\boldsymbol{\beta}) & = & \mathbb{E} \{ [\boldsymbol{\beta} - \mathbb{E}(\boldsymbol{\beta})] [\boldsymbol{\beta} - \mathbb{E}(\boldsymbol{\beta})]^{T} \} +\\ +& = & \mathbb{E} \{ [(\mathbf{X}^{T} \mathbf{X})^{-1} \, \mathbf{X}^{T} \mathbf{Y} - \boldsymbol{\beta}] \, [(\mathbf{X}^{T} \mathbf{X})^{-1} \, \mathbf{X}^{T} \mathbf{Y} - \boldsymbol{\beta}]^{T} \} +\\ +% & = & \mathbb{E} \{ [(\mathbf{X}^{T} \mathbf{X})^{-1} \, \mathbf{X}^{T} \mathbf{Y}] \, [(\mathbf{X}^{T} \mathbf{X})^{-1} \, \mathbf{X}^{T} \mathbf{Y}]^{T} \} - \boldsymbol{\beta} \, \boldsymbol{\beta}^{T} +% \\ +% & = & \mathbb{E} \{ (\mathbf{X}^{T} \mathbf{X})^{-1} \, \mathbf{X}^{T} \mathbf{Y} \, \mathbf{Y}^{T} \, \mathbf{X} \, (\mathbf{X}^{T} \mathbf{X})^{-1} \} - \boldsymbol{\beta} \, \boldsymbol{\beta}^{T} +% \\ +& = & (\mathbf{X}^{T} \mathbf{X})^{-1} \, \mathbf{X}^{T} \, \mathbb{E} \{ \mathbf{Y} \, \mathbf{Y}^{T} \} \, \mathbf{X} \, (\mathbf{X}^{T} \mathbf{X})^{-1} - \boldsymbol{\beta} \, \boldsymbol{\beta}^{T} +\\ +& = & (\mathbf{X}^{T} \mathbf{X})^{-1} \, \mathbf{X}^{T} \, \{ \mathbf{X} \, \boldsymbol{\beta} \, \boldsymbol{\beta}^{T} \, \mathbf{X}^{T} + \sigma^2 \} \, \mathbf{X} \, (\mathbf{X}^{T} \mathbf{X})^{-1} - \boldsymbol{\beta} \, \boldsymbol{\beta}^{T} +% \\ +% & = & (\mathbf{X}^T \mathbf{X})^{-1} \, \mathbf{X}^T \, \mathbf{X} \, \boldsymbol{\beta} \, \boldsymbol{\beta}^T \, \mathbf{X}^T \, \mathbf{X} \, (\mathbf{X}^T % \mathbf{X})^{-1} +% \\ +% & & + \, \, \sigma^2 \, (\mathbf{X}^T \mathbf{X})^{-1} \, \mathbf{X}^T \, \mathbf{X} \, (\mathbf{X}^T \mathbf{X})^{-1} - \boldsymbol{\beta} \boldsymbol{\beta}^T +\\ +& = & \boldsymbol{\beta} \, \boldsymbol{\beta}^{T} + \sigma^2 \, (\mathbf{X}^{T} \mathbf{X})^{-1} - \boldsymbol{\beta} \, \boldsymbol{\beta}^{T} +\, \, \, = \, \, \, \sigma^2 \, (\mathbf{X}^{T} \mathbf{X})^{-1}, +\end{eqnarray*} +$$ + +

    +where we have used that \( \mathbb{E} (\mathbf{Y} \mathbf{Y}^{T}) = +\mathbf{X} \, \boldsymbol{\beta} \, \boldsymbol{\beta}^{T} \, \mathbf{X}^{T} + +\sigma^2 \, \mathbf{I}_{nn} \). From \( \mbox{Var}(\boldsymbol{\beta}) = \sigma^2 +\, (\mathbf{X}^{T} \mathbf{X})^{-1} \), one obtains an estimate of the +variance of the estimate of the \( j \)-th regression coefficient: +\( \hat{\sigma}^2 (\hat{\beta}_j ) = \hat{\sigma}^2 \sqrt{ +[(\mathbf{X}^{T} \mathbf{X})^{-1}]_{jj} } \). This may be used to +construct a confidence interval for the estimates. + +

    +In a similar way, we cna obtain analytical expressions for say the +expectation values of the parameters \( \boldsymbol{\beta} \) and their variance +when we employ Ridge regression, and thereby a confidence interval. + +

    +It is rather straightforward to show that +$$ +\mathbb{E} \big[ \boldsymbol{\beta}^{\mathrm{Ridge}} \big]=(\mathbf{X}^{T} \mathbf{X} + \lambda \mathbf{I}_{pp})^{-1} (\mathbf{X}^{\top} \mathbf{X})\boldsymbol{\beta}^{\mathrm{OLS}}. +$$ + +We see clearly that +\( \mathbb{E} \big[ \boldsymbol{\beta}^{\mathrm{Ridge}} \big] \not= \boldsymbol{\beta}^{\mathrm{OLS}} \) for any \( \lambda > 0 \). We say then that the ridge estimator is biased. + +

    +We can also compute the variance as + +$$ +\mbox{Var}[\boldsymbol{\beta}^{\mathrm{Ridge}}]=\sigma^2[ \mathbf{X}^{T} \mathbf{X} + \lambda \mathbf{I} ]^{-1} \mathbf{X}^{T} \mathbf{X} \{ [ \mathbf{X}^{\top} \mathbf{X} + \lambda \mathbf{I} ]^{-1}\}^{T}, +$$ + +and it is easy to see that if the parameter \( \lambda \) goes to infinity then the variance of Ridge parameters \( \boldsymbol{\beta} \) goes to zero. + +

    +With this, we can compute the difference + +$$ +\mbox{Var}[\boldsymbol{\beta}^{\mathrm{OLS}}]-\mbox{Var}(\boldsymbol{\beta}^{\mathrm{Ridge}})=\sigma^2 [ \mathbf{X}^{T} \mathbf{X} + \lambda \mathbf{I} ]^{-1}[ 2\lambda\mathbf{I} + \lambda^2 (\mathbf{X}^{T} \mathbf{X})^{-1} ] \{ [ \mathbf{X}^{T} \mathbf{X} + \lambda \mathbf{I} ]^{-1}\}^{T}. +$$ + +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 \( \boldsymbol{\beta} \) obtained with the Ridge estimator. This has interesting consequences when we discuss the so-called bias-variance trade-off below.

    -

    Cross-validation

    +

    Cross-validation

    Instead of choosing the penalty parameter to balance model fit with @@ -2597,12 +2987,15 @@ model complexity, cross-validation requires it (i.e. the penalty parameter) to yield a model with good prediction performance. Commonly, this performance is evaluated on novel data. Novel data need not be easy to come by and one has to make do -with the data at hand. The setting of `original' and novel data is +with the data at hand. + +

    +The setting of original and novel data is then mimicked by sample splitting: the data set is divided into two -(groups of samples). One of these two data sets, called the training -set, plays the role of `original' data on which the model is +(groups of samples). One of these two data sets, called the +training set, plays the role of original data on which the model is built. The second of these data sets, called the test set, plays the -role of the `novel' data and is used to evaluate the prediction +role of the novel data and is used to evaluate the prediction performance (often operationalized as the log-likelihood or the prediction error or its square or the R2 score) of the model built on the training data set. This procedure (model building and prediction evaluation on training and @@ -2620,7 +3013,7 @@ some sense) is then selected.











    -

    Computationally expensive

    +

    Computationally expensive

    The validation set approach is conceptually simple and is easy to implement. But it has two potential drawbacks: @@ -2632,7 +3025,7 @@ The validation set approach is conceptually simple and is easy to implement. But -

    Various steps in cross-validation

    +

    Various steps in cross-validation

    When the repetitive splitting of the data set is done randomly, @@ -2653,32 +3046,32 @@ cross-validation (LOOCV).

    -

    How to set up the cross-validation for Ridge and/or Lasso

    +

    How to set up the cross-validation for Ridge and/or Lasso

    • Define a range of interest for the penalty parameter.
    • Divide the data set into training and test set comprising samples \( \{1, \ldots, n\} \setminus i \) and \( \{ i \} \), respectively.
    • -
    • Fit the linear regression model by means of ridge estimation for each \( \lambda \) in the grid using the training set, and the corresponding estimate of the error variance \( \hat{\sigma}_{-i}^2(\lambda) \), as
    • +
    • Fit the linear regression model by means of ridge estimation for each \( \lambda \) in the grid using the training set, and the corresponding estimate of the error variance \( \boldsymbol{\sigma}_{-i}^2(\lambda) \), as
    $$ \begin{align*} -\hat{\beta}_{-i}(\lambda) & = ( \hat{X}_{-i, \ast}^{\top} -\hat{X}_{-i, \ast} + \lambda \hat{I}_{pp})^{-1} -\hat{X}_{-i, \ast}^{\top} \hat{y}_{-i} +\boldsymbol{\beta}_{-i}(\lambda) & = ( \boldsymbol{X}_{-i, \ast}^{T} +\boldsymbol{X}_{-i, \ast} + \lambda \boldsymbol{I}_{pp})^{-1} +\boldsymbol{X}_{-i, \ast}^{T} \boldsymbol{y}_{-i} \end{align*} $$
      -
    • Evaluate the prediction performance of these models on the test set by \( \log\{L[y_i, \hat{X}_{i, \ast}; \hat{\beta}_{-i}(\lambda), \hat{\sigma}_{-i}^2(\lambda)]\} \). Or, by the prediction error \( |y_i - \hat{X}_{i, \ast} \hat{\beta}_{-i}(\lambda)| \), the relative error, the error squared or the R2 score function.
    • +
    • Evaluate the prediction performance of these models on the test set by \( \log\{L[y_i, \boldsymbol{X}_{i, \ast}; \boldsymbol{\beta}_{-i}(\lambda), \boldsymbol{\sigma}_{-i}^2(\lambda)]\} \). Or, by the prediction error \( |y_i - \boldsymbol{X}_{i, \ast} \boldsymbol{\beta}_{-i}(\lambda)| \), the relative error, the error squared or the R2 score function.
    • Repeat the first three steps such that each sample plays the role of the test set once.
    • Average the prediction performances of the test sets at each grid point of the penalty bias/parameter by computing the cross-validated log-likelihood. It is an estimate of the prediction performance of the model corresponding to this value of the penalty parameter on novel data. It is defined as
    $$ \begin{align*} -\frac{1}{n} \sum_{i = 1}^n \log\{L[y_i, \mathbf{X}_{i, \ast}; \hat{\beta}_{-i}(\lambda), \hat{\sigma}_{-i}^2(\lambda)]\}. +\frac{1}{n} \sum_{i = 1}^n \log\{L[y_i, \mathbf{X}_{i, \ast}; \boldsymbol{\beta}_{-i}(\lambda), \boldsymbol{\sigma}_{-i}^2(\lambda)]\}. \end{align*} $$ @@ -2689,31 +3082,7 @@ $$









    -

    Predicted Residual Error Sum of Squares

    -
    - -

    -Another approach in the LOOCV scheme is to the use the so-called Predicted Residual Error Sum of Squares (PRESS). - -

    -We can define the optimal penalty parameter to minimize -$$ -\begin{align*} -\lambda_{\mbox{{\tiny opt}}} = \arg \min_{\lambda} \frac{1}{n} \sum_{i=1}^n [y_i - \hat{X}_{i, \ast} \hat{\beta}_{-i}(\lambda)]^2. -\end{align*} -$$ - -

    -The LOOCV prediction performance can be -expressed analytically in terms of the known quantities derived from -the design matrix and the parameters \( \beta \). -

    - - -

    -









    - -

    Resampling methods: Jackknife and Bootstrap

    +

    Resampling methods: Jackknife and Bootstrap

    Two famous @@ -2736,18 +3105,18 @@ need for bootstrapping.











    -

    Resampling methods: Jackknife

    +

    Resampling methods: Jackknife

    The Jackknife works by making many replicas of the estimator \( \widehat{\theta} \). -The jackknife is a resampling method, we explained that this happens by scrambling the data in some way. When using the jackknife, this is done by systematically leaving out one observation from the vector of observed values \( \hat{x} = (x_1,x_2,\cdots,X_n) \). -Let \( \hat{x}_i \) denote the vector +The jackknife is a resampling method where we systematically leave out one observation from the vector of observed values \( \boldsymbol{x} = (x_1,x_2,\cdots,X_n) \). +Let \( \boldsymbol{x}_i \) denote the vector $$ -\hat{x}_i = (x_1,x_2,\cdots,x_{i-1},x_{i+1},\cdots,x_n), +\boldsymbol{x}_i = (x_1,x_2,\cdots,x_{i-1},x_{i+1},\cdots,x_n), $$

    -which equals the vector \( \hat{x} \) with the exception that observation +which equals the vector \( \boldsymbol{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 \). @@ -2755,20 +3124,6 @@ number \( i \) is left out. Using this notation, define











    -

    Resampling methods: Jackknife estimator

    - -

    -To get an estimate for the bias and -standard error of \( \widehat{\theta} \), use the following -estimators for each component of \( \widehat{\theta} \) - -$$ -\widehat{\mathrm{Bias}}(\widehat \theta,\theta) = (n-1)\left( - \widehat{\theta} + \frac{1}{n}\sum_{i=1}^{n} \widehat \theta_i \right) \qquad \text{and} \qquad \widehat{\sigma}^2_{\widehat{\theta} } = \frac{n-1}{n}\sum_{i=1}^{n}( \widehat{\theta}_i - \frac{1}{n}\sum_{j=1}^{n}\widehat \theta_j )^2. -$$ - -

    -









    -

    Jackknife code example

    @@ -2829,14 +3184,14 @@ advantages:

    Resampling methods: Bootstrap background

    -Since \( \widehat{\theta} = \widehat{\theta}(\hat{X}) \) is a function of random variables, +Since \( \widehat{\theta} = \widehat{\theta}(\boldsymbol{X}) \) is a function of random variables, \( \widehat{\theta} \) itself must be a random variable. Thus it has -a pdf, call this function \( p(\hat{t}) \). The aim of the bootstrap is to -estimate \( p(\hat{t}) \) by the relative frequency of +a pdf, call this function \( p(\boldsymbol{t}) \). The aim of the bootstrap is to +estimate \( p(\boldsymbol{t}) \) by the relative frequency of \( \widehat{\theta} \). You can think of this as using a histogram -in the place of \( p(\hat{t}) \). If the relative frequency closely +in the place of \( p(\boldsymbol{t}) \). If the relative frequency closely resembles \( p(\vec{t}) \), then using numerics, it is straight forward to -estimate all the interesting parameters of \( p(\hat{t}) \) using point +estimate all the interesting parameters of \( p(\boldsymbol{t}) \) using point estimators.

    @@ -2859,7 +3214,7 @@ been straight forward to do this by: By repeated use of (1) and (2), many estimates of \( \widehat{\theta} \) could have been obtained. The idea is to use the relative frequency of \( \widehat{\theta}^* \) -(think of a histogram) as an estimate of \( p(\hat{t}) \). +(think of a histogram) as an estimate of \( p(\boldsymbol{t}) \).











    @@ -2880,7 +3235,7 @@ result in some asymptotic sense? The answer is yes. Instead of generating the histogram for the relative frequency of the observation \( X_i \), just draw the values \( (X_1^*,X_2^*,\cdots,X_n^*) \) with replacement from the vector -\( \hat{X} \). +\( \boldsymbol{X} \).











    @@ -2891,19 +3246,41 @@ frequency of the observation \( X_i \), just draw the values The independent bootstrap works like this:

      -
    1. Draw with replacement \( n \) numbers for the observed variables \( \hat{x} = (x_1,x_2,\cdots,x_n) \).
    2. -
    3. Define a vector \( \hat{x}^* \) containing the values which were drawn from \( \hat{x} \).
    4. -
    5. Using the vector \( \hat{x}^* \) compute \( \widehat{\theta}^* \) by evaluating \( \widehat \theta \) under the observations \( \hat{x}^* \).
    6. +
    7. Draw with replacement \( n \) numbers for the observed variables \( \boldsymbol{x} = (x_1,x_2,\cdots,x_n) \).
    8. +
    9. Define a vector \( \boldsymbol{x}^* \) containing the values which were drawn from \( \boldsymbol{x} \).
    10. +
    11. Using the vector \( \boldsymbol{x}^* \) compute \( \widehat{\theta}^* \) by evaluating \( \widehat \theta \) under the observations \( \boldsymbol{x}^* \).
    12. Repeat this process \( k \) times.
    -When you are done, you can draw a histogram of the relative frequency of \( \widehat \theta^* \). This is your estimate of the probability distribution \( p(t) \). Using this probability distribution you can estimate any statistics thereof. In principle you never draw the histogram of the relative frequency of \( \widehat{\theta}^* \). Instead you use the estimators corresponding to the statistic of interest. For example, if you are interested in estimating the variance of \( \widehat \theta \), apply the etsimator \( \widehat \sigma^2 \) to the values \( \widehat \theta ^* \). +When you are done, you can draw a histogram of the relative frequency +of \( \widehat \theta^* \). This is your estimate of the probability +distribution \( p(t) \). Using this probability distribution you can +estimate any statistics thereof. In principle you never draw the +histogram of the relative frequency of \( \widehat{\theta}^* \). Instead +you use the estimators corresponding to the statistic of interest. For +example, if you are interested in estimating the variance of \( \widehat +\theta \), apply the etsimator \( \widehat \sigma^2 \) to the values +\( \widehat \theta ^* \).











    Code example for the Bootstrap method

    -The following code starts with a Gaussian distribution with mean value \( \mu =100 \) and variance \( \sigma=15 \). We use this to generate the data used in the bootstrap analysis. The bootstrap analysis returns a data set after a given number of bootstrap operations (as many as we have data points). This data set consists of estimated mean values for each bootstrap operation. The histogram generated by the bootstrap method shows that the distribution for these mean values is also a Gaussian, centered around the mean value \( \mu=100 \) but with standard deviation \( \sigma/\sqrt{n} \), where \( n \) is the number of bootstrap samples (in this case the same as the number of original data points). The value of the standard deviation is what we expect from the central limit theorem. + +

    +The following code starts with a Gaussian distribution with mean value +\( \mu =100 \) and variance \( \sigma=15 \). We use this to generate the data +used in the bootstrap analysis. The bootstrap analysis returns a data +set after a given number of bootstrap operations (as many as we have +data points). This data set consists of estimated mean values for each +bootstrap operation. The histogram generated by the bootstrap method +shows that the distribution for these mean values is also a Gaussian, +centered around the mean value \( \mu=100 \) but with standard deviation +\( \sigma/\sqrt{n} \), where \( n \) is the number of bootstrap samples (in +this case the same as the number of original data points). The value +of the standard deviation is what we expect from the central limit +theorem. +

    @@ -2917,30 +3294,29 @@ The following code starts with a Gaussian distribution with mean value \( \mu =1 def stat(data): return mean(data) -# Bootstrap algorithm +# Bootstrap algorithm def bootstrap(data, statistic, R): t = zeros(R); n = len(data); inds = arange(n); t0 = time() - - # non-parametric bootstrap + # non-parametric bootstrap for i in range(R): t[i] = statistic(data[randint(0,n,n)]) - # analysis + # analysis print("Runtime: %g sec" % (time()-t0)); print("Bootstrap Statistics :") print("original bias std. error") - print("%8g %8g %14g %15g" % (statistic(data), std(data),\ - mean(t), \ - std(t))) + print("%8g %8g %14g %15g" % (statistic(data), std(data),mean(t),std(t))) return t mu, sigma = 100, 15 datapoints = 10000 x = mu + sigma*random.randn(datapoints) -# bootstrap returns the data sample t = bootstrap(x, stat, datapoints) -# the histogram of the bootstrapped data n, binsboot, patches = plt.hist(t, 50, normed=1, facecolor='red', alpha=0.75) +# bootstrap returns the data sample +t = bootstrap(x, stat, datapoints) +# the histogram of the bootstrapped data +n, binsboot, patches = plt.hist(t, 50, normed=1, facecolor='red', alpha=0.75) -# add a 'best fit' line +# add a 'best fit' line y = mlab.normpdf( binsboot, mean(t), std(t)) lt = plt.plot(binsboot, y, 'r--', linewidth=1) plt.xlabel('Smarts') @@ -2953,529 +3329,300 @@ plt.show()











    -

    Resampling methods: Blocking

    +

    Code Example for Cross-validation and \( k \)-fold Cross-validation

    -The blocking method was made popular by Flyvbjerg and Pedersen (1989) -and has become one of the standard ways to estimate -\( V(\widehat{\theta}) \) for exactly one \( \widehat{\theta} \), namely -\( \widehat{\theta} = \overline{X} \). - -

    -Assume \( n = 2^d \) for some integer \( d>1 \) and \( X_1,X_2,\cdots, X_n \) is a stationary time series to begin with. -Moreover, assume that the time series is asymptotically uncorrelated. We switch to vector notation by arranging \( X_1,X_2,\cdots,X_n \) in an \( n \)-tuple. Define: -$$ -\begin{align*} -\hat{X} = (X_1,X_2,\cdots,X_n). -\end{align*} -$$ - -

    -The strength of the blocking method is when the number of -observations, \( n \) is large. For large \( n \), the complexity of dependent -bootstrapping scales poorly, but the blocking method does not, -moreover, it becomes more accurate the larger \( n \) is. - -

    -









    - -

    Blocking Transformations

    - We now define -blocking transformations. The idea is to take the mean of subsequent -pair of elements from \( \vec{X} \) and form a new vector -\( \vec{X}_1 \). Continuing in the same way by taking the mean of -subsequent pairs of elements of \( \vec{X}_1 \) we obtain \( \vec{X}_2 \), and -so on. -Define \( \vec{X}_i \) recursively by: - -$$ -\begin{align} -(\vec{X}_0)_k &\equiv (\vec{X})_k \nonumber \\ -(\vec{X}_{i+1})_k &\equiv \frac{1}{2}\Big( (\vec{X}_i)_{2k-1} + -(\vec{X}_i)_{2k} \Big) \qquad \text{for all} \qquad 1 \leq i \leq d-1 -\label{_auto11} -\end{align} -$$ - -

    -The quantity \( \vec{X}_k \) is -subject to \( k \) blocking transformations. We now have \( d \) vectors -\( \vec{X}_0, \vec{X}_1,\cdots,\vec X_{d-1} \) containing the subsequent -averages of observations. It turns out that if the components of -\( \vec{X} \) is a stationary time series, then the components of -\( \vec{X}_i \) is a stationary time series for all \( 0 \leq i \leq d-1 \) - -

    -We can then compute the autocovariance, the variance, sample mean, and -number of observations for each \( i \). -Let \( \gamma_i, \sigma_i^2, -\overline{X}_i \) denote the autocovariance, variance and average of the -elements of \( \vec{X}_i \) and let \( n_i \) be the number of elements of -\( \vec{X}_i \). It follows by induction that \( n_i = n/2^i \). - -

    -









    - -

    Blocking Transformations

    - -

    -Using the -definition of the blocking transformation and the distributive -property of the covariance, it is clear that since \( h =|i-j| \) -we can define -$$ -\begin{align} -\gamma_{k+1}(h) &= cov\left( ({X}_{k+1})_{i}, ({X}_{k+1})_{j} \right) \nonumber \\ -&= \frac{1}{4}cov\left( ({X}_{k})_{2i-1} + ({X}_{k})_{2i}, ({X}_{k})_{2j-1} + ({X}_{k})_{2j} \right) \nonumber \\ -&= \frac{1}{2}\gamma_{k}(2h) + \frac{1}{2}\gamma_k(2h+1) \hspace{0.1cm} \mathrm{h = 0} -\label{_auto12}\\ -&=\frac{1}{4}\gamma_k(2h-1) + \frac{1}{2}\gamma_k(2h) + \frac{1}{4}\gamma_k(2h+1) \quad \mathrm{else} -\label{_auto13} -\end{align} -$$ - -

    -The quantity \( \hat{X} \) is asymptotic uncorrelated by assumption, \( \hat{X}_k \) is also asymptotic uncorrelated. Let's turn our attention to the variance of the sample mean \( V(\overline{X}) \). - -

    -









    - -

    Blocking Transformations, getting there

    -We have -$$ -\begin{align} -V(\overline{X}_k) = \frac{\sigma_k^2}{n_k} + \underbrace{\frac{2}{n_k} \sum_{h=1}^{n_k-1}\left( 1 - \frac{h}{n_k} \right)\gamma_k(h)}_{\equiv e_k} = \frac{\sigma^2_k}{n_k} + e_k \quad \text{if} \quad \gamma_k(0) = \sigma_k^2. -\label{_auto14} -\end{align} -$$ - -The term \( e_k \) is called the truncation error: -$$ -\begin{equation} -e_k = \frac{2}{n_k} \sum_{h=1}^{n_k-1}\left( 1 - \frac{h}{n_k} \right)\gamma_k(h). -\label{_auto15} -\end{equation} -$$ - -We can show that \( V(\overline{X}_i) = V(\overline{X}_j) \) for all \( 0 \leq i \leq d-1 \) and \( 0 \leq j \leq d-1 \). - -

    -









    - -

    Blocking Transformations, final expressions

    - -

    -We can then wrap up -$$ -\begin{align} -n_{j+1} \overline{X}_{j+1} &= \sum_{i=1}^{n_{j+1}} (\hat{X}_{j+1})_i = \frac{1}{2}\sum_{i=1}^{n_{j}/2} (\hat{X}_{j})_{2i-1} + (\hat{X}_{j})_{2i} \nonumber \\ -&= \frac{1}{2}\left[ (\hat{X}_j)_1 + (\hat{X}_j)_2 + \cdots + (\hat{X}_j)_{n_j} \right] = \underbrace{\frac{n_j}{2}}_{=n_{j+1}} \overline{X}_j = n_{j+1}\overline{X}_j. -\label{_auto16} -\end{align} -$$ - -By repeated use of this equation we get \( V(\overline{X}_i) = V(\overline{X}_0) = V(\overline{X}) \) for all \( 0 \leq i \leq d-1 \). This has the consequence that -$$ -\begin{align} -V(\overline{X}) = \frac{\sigma_k^2}{n_k} + e_k \qquad \text{for all} \qquad 0 \leq k \leq d-1. \label{eq:convergence} -\end{align} -$$ - -

    -Fyvbjerg and Petersen demonstrated that the sequence -\( \{e_k\}_{k=0}^{d-1} \) is decreasing, and conjecture that the term -\( e_k \) can be made as small as we would like by making \( k \) (and hence -\( d \)) sufficiently large. The sequence is decreasing (Master of Science thesis by Marius Jonsson, UiO 2018). -It means we can apply blocking transformations until -\( e_k \) is sufficiently small, and then estimate \( V(\overline{X}) \) by -\( \widehat{\sigma}^2_k/n_k \). - -

    -









    - -

    Code examples for Blocking, Jackknife and bootstrap

    - +The code here uses Ridge regression with cross-validation (CV) resampling and \( k \)-fold CV in order to fit a specific polynomial.

    -

    from sys import argv
    -from os import mkdir, path
    -import time
    -import numpy as np
    +
    import numpy as np
     import matplotlib.pyplot as plt
    -from matplotlib.ticker import FormatStrFormatter
    -from matplotlib.font_manager import FontProperties
    +from sklearn.model_selection import KFold
    +from sklearn.linear_model import Ridge
    +from sklearn.model_selection import cross_val_score
    +from sklearn.preprocessing import PolynomialFeatures
     
    -# Timing Decorator
    -def timeFunction(f):
    -    def wrap(*args):
    -        time1 = time.time()
    -        ret = f(*args)
    -        time2 = time.time()
    -        print '%s Function Took: \t %0.3f s' % (f.func_name.title(), (time2-time1))
    -        return ret
    -    return wrap
    +# A seed just to ensure that the random numbers are the same for every run.
    +# Useful for eventual debugging.
    +np.random.seed(3155)
     
    -class dataAnalysisClass:
    -    # General Init functions
    -    def __init__(self, fileName, size=0):
    -        self.inputFileName = fileName
    -        self.loadData(size)
    -        self.createOutputFolder()
    -        self.avg = np.average(self.data)
    -        self.var = np.var(self.data)
    -        self.std = np.std(self.data)
    +# Generate the data.
    +nsamples = 100
    +x = np.random.randn(nsamples)
    +y = 3*x**2 + np.random.randn(nsamples)
     
    -    def loadData(self, size=0):
    -        if size != 0:
    -            with open(self.inputFileName) as inputFile:
    -                self.data = np.zeros(size)
    -                for x in xrange(size):
    -                    self.data[x] = float(next(inputFile))
    -        else:
    -            self.data = np.loadtxt(self.inputFileName)
    +## Cross-validation on Ridge regression using KFold only
     
    -    # Statistical Analysis with Multiple Methods
    -    def runAllAnalyses(self):
    -        if len(self.data) <= 100000:
    -            print "Autocorrelation..."
    -            self.autocorrelation()
    -        print "Bootstrap..."
    -        self.bootstrap()
    -        print "Jackknife..."
    -        self.jackknife()
    -        print "Blocking..."
    -        self.blocking()
    +# Decide degree on polynomial to fit
    +poly = PolynomialFeatures(degree = 6)
     
    -    # Standard Autocorrelation
    -    @timeFunction
    -    def autocorrelation(self):
    -        self.acf = np.zeros(len(self.data)/2)
    -        for k in range(0, len(self.data)/2):
    -            self.acf[k] = np.corrcoef(np.array([self.data[0:len(self.data)-k], \
    -                                            self.data[k:len(self.data)]]))[0,1]
    +# Decide which values of lambda to use
    +nlambdas = 500
    +lambdas = np.logspace(-3, 5, nlambdas)
     
    -    # Bootstrap
    -    @timeFunction
    -    def bootstrap(self, nBoots = 1000):
    -        bootVec = np.zeros(nBoots)
    -        for k in range(0,nBoots):
    -            bootVec[k] = np.average(np.random.choice(self.data, len(self.data)))
    -        self.bootAvg = np.average(bootVec)
    -        self.bootVar = np.var(bootVec)
    -        self.bootStd = np.std(bootVec)
    +# Initialize a KFold instance
    +k = 5
    +kfold = KFold(n_splits = k)
     
    -    # Jackknife
    -    @timeFunction
    -    def jackknife(self):
    -        jackknVec = np.zeros(len(self.data))
    -        for k in range(0,len(self.data)):
    -            jackknVec[k] = np.average(np.delete(self.data, k))
    -        self.jackknAvg = self.avg - (len(self.data) - 1) * (np.average(jackknVec) - self.avg)
    -        self.jackknVar = float(len(self.data) - 1) * np.var(jackknVec)
    -        self.jackknStd = np.sqrt(self.jackknVar)
    +# Perform the cross-validation to estimate MSE
    +scores_KFold = np.zeros((nlambdas, k))
     
    -    # Blocking
    -    @timeFunction
    -    def blocking(self, blockSizeMax = 500):
    -        blockSizeMin = 1
    +i = 0
    +for lmb in lambdas:
    +    ridge = Ridge(alpha = lmb)
    +    j = 0
    +    for train_inds, test_inds in kfold.split(x):
    +        xtrain = x[train_inds]
    +        ytrain = y[train_inds]
     
    -        self.blockSizes = []
    -        self.meanVec = []
    -        self.varVec = []
    +        xtest = x[test_inds]
    +        ytest = y[test_inds]
     
    -        for i in range(blockSizeMin, blockSizeMax):
    -            if(len(self.data) % i != 0):
    -                pass#continue
    -            blockSize = i
    -            meanTempVec = []
    -            varTempVec = []
    -            startPoint = 0
    -            endPoint = blockSize
    +        Xtrain = poly.fit_transform(xtrain[:, np.newaxis])
    +        ridge.fit(Xtrain, ytrain[:, np.newaxis])
     
    -            while endPoint <= len(self.data):
    -                meanTempVec.append(np.average(self.data[startPoint:endPoint]))
    -                startPoint = endPoint
    -                endPoint += blockSize
    -            mean, var = np.average(meanTempVec), np.var(meanTempVec)/len(meanTempVec)
    -            self.meanVec.append(mean)
    -            self.varVec.append(var)
    -            self.blockSizes.append(blockSize)
    +        Xtest = poly.fit_transform(xtest[:, np.newaxis])
    +        ypred = ridge.predict(Xtest)
     
    -        self.blockingAvg = np.average(self.meanVec[-200:])
    -        self.blockingVar = (np.average(self.varVec[-200:]))
    -        self.blockingStd = np.sqrt(self.blockingVar)
    +        scores_KFold[i,j] = np.sum((ypred - ytest[:, np.newaxis])**2)/np.size(ypred)
    +
    +        j += 1
    +    i += 1
     
     
    +estimated_mse_KFold = np.mean(scores_KFold, axis = 1)
     
    -    # Plot of Data, Autocorrelation Function and Histogram
    -    def plotAll(self):
    -        self.createOutputFolder()
    -        if len(self.data) <= 100000:
    -            self.plotAutocorrelation()
    -        self.plotData()
    -        self.plotHistogram()
    -        self.plotBlocking()
    +## Cross-validation using cross_val_score from sklearn along with KFold
     
    -    # Create Output Plots Folder
    -    def createOutputFolder(self):
    -        self.outName = self.inputFileName[:-4]
    -        if not path.exists(self.outName):
    -            mkdir(self.outName)
    +# kfold is an instance initialized above as:
    +# kfold = KFold(n_splits = k)
     
    -    # Plot the Dataset, Mean and Std
    -    def plotData(self):
    -        # Far away plot
    -        font = {'fontname':'serif'}
    -        plt.plot(range(0, len(self.data)), self.data, 'r-', linewidth=1)
    -        plt.plot([0, len(self.data)], [self.avg, self.avg], 'b-', linewidth=1)
    -        plt.plot([0, len(self.data)], [self.avg + self.std, self.avg + self.std], 'g--', linewidth=1)
    -        plt.plot([0, len(self.data)], [self.avg - self.std, self.avg - self.std], 'g--', linewidth=1)
    -        plt.ylim(self.avg - 5*self.std, self.avg + 5*self.std)
    -        plt.gca().yaxis.set_major_formatter(FormatStrFormatter('%.4f'))
    -        plt.xlim(0, len(self.data))
    -        plt.ylabel(self.outName.title() + ' Monte Carlo Evolution', **font)
    -        plt.xlabel('MonteCarlo History', **font)
    -        plt.title(self.outName.title(), **font)
    -        plt.savefig(self.outName + "/data.eps")
    -        plt.savefig(self.outName + "/data.png")
    -        plt.clf()
    +estimated_mse_sklearn = np.zeros(nlambdas)
    +i = 0
    +for lmb in lambdas:
    +    ridge = Ridge(alpha = lmb)
     
    -    # Plot Histogram of Dataset and Gaussian around it
    -    def plotHistogram(self):
    -        binNumber = 50
    -        font = {'fontname':'serif'}
    -        count, bins, ignore = plt.hist(self.data, bins=np.linspace(self.avg - 5*self.std, self.avg + 5*self.std, binNumber))
    -        plt.plot([self.avg, self.avg], [0,np.max(count)+10], 'b-', linewidth=1)
    -        plt.ylim(0,np.max(count)+10)
    -        plt.ylabel(self.outName.title() + ' Histogram', **font)
    -        plt.xlabel(self.outName.title() , **font)
    -        plt.title('Counts', **font)
    +    X = poly.fit_transform(x[:, np.newaxis])
    +    estimated_mse_folds = cross_val_score(ridge, X, y[:, np.newaxis], scoring='neg_mean_squared_error', cv=kfold)
     
    -        #gaussian
    -        norm = 0
    -        for i in range(0,len(bins)-1):
    -            norm += (bins[i+1]-bins[i])*count[i]
    -        plt.plot(bins,  norm/(self.std * np.sqrt(2 * np.pi)) * np.exp( - (bins - self.avg)**2 / (2 * self.std**2) ), linewidth=1, color='r')
    -        plt.savefig(self.outName + "/hist.eps")
    -        plt.savefig(self.outName + "/hist.png")
    -        plt.clf()
    +    # cross_val_score return an array containing the estimated negative mse for every fold.
    +    # we have to the the mean of every array in order to get an estimate of the mse of the model
    +    estimated_mse_sklearn[i] = np.mean(-estimated_mse_folds)
     
    -    # Plot the Autocorrelation Function
    -    def plotAutocorrelation(self):
    -        font = {'fontname':'serif'}
    -        plt.plot(range(1, len(self.data)/2), self.acf[1:], 'r-')
    -        plt.ylim(-1, 1)
    -        plt.xlim(0, len(self.data)/2)
    -        plt.ylabel('Autocorrelation Function', **font)
    -        plt.xlabel('Lag', **font)
    -        plt.title('Autocorrelation', **font)
    -        plt.savefig(self.outName + "/autocorrelation.eps")
    -        plt.savefig(self.outName + "/autocorrelation.png")
    -        plt.clf()
    +    i += 1
     
    -    def plotBlocking(self):
    -        font = {'fontname':'serif'}
    -        plt.plot(self.blockSizes, self.varVec, 'r-')
    -        plt.ylabel('Variance', **font)
    -        plt.xlabel('Block Size', **font)
    -        plt.title('Blocking', **font)
    -        plt.savefig(self.outName + "/blocking.eps")
    -        plt.savefig(self.outName + "/blocking.png")
    -        plt.clf()
    +## Plot and compare the slightly different ways to perform cross-validation
     
    -    # Print Stuff to the Terminal
    -    def printOutput(self):
    -        print "\nSample Size:    \t", len(self.data)
    -        print "\n=========================================\n"
    -        print "Sample Average: \t", self.avg
    -        print "Sample Variance:\t", self.var
    -        print "Sample Std:     \t", self.std
    -        print "\n=========================================\n"
    -        print "Bootstrap Average: \t", self.bootAvg
    -        print "Bootstrap Variance:\t", self.bootVar
    -        print "Bootstrap Error:   \t", self.bootStd
    -        print "\n=========================================\n"
    -        print "Jackknife Average: \t", self.jackknAvg
    -        print "Jackknife Variance:\t", self.jackknVar
    -        print "Jackknife Error:   \t", self.jackknStd
    -        print "\n=========================================\n"
    -        print "Blocking Average: \t", self.blockingAvg
    -        print "Blocking Variance:\t", self.blockingVar
    -        print "Blocking Error:   \t", self.blockingStd, "\n"
    +plt.figure()
     
    -# Initialize the class
    -if len(argv) > 2:
    -    dataAnalysis = dataAnalysisClass(argv[1], int(argv[2]))
    -else:
    -    dataAnalysis = dataAnalysisClass(argv[1])
    +plt.plot(np.log10(lambdas), estimated_mse_sklearn, label = 'cross_val_score')
    +plt.plot(np.log10(lambdas), estimated_mse_KFold, 'r--', label = 'KFold')
     
    -# Run Analyses
    -dataAnalysis.runAllAnalyses()
    +plt.xlabel('log10(lambda)')
    +plt.ylabel('mse')
     
    -# Plot the data
    -dataAnalysis.plotAll()
    +plt.legend()
     
    -# Print Some Output
    -dataAnalysis.printOutput()
    +plt.show()
     











    -

    The bias-variance tradeoff

    +

    The bias-variance tradeoff

    -We begin with an unknown function \( y=f(x) \) and fix a \emph{hypothesis set} - \( \mathcal{H} \) consisting of all functions we are willing to consider, - defined also on the domain of \( f \). This set may be uncountably - infinite (e.g. if there are real-valued parameters to fit). -The - choice of which functions to include in \( \mathcal{H} \) usually depends - on our intuition about the problem of interest. The function \( f(x) \) - produces a set of pairs \( (x_i,y_i) \), \( i=1\dots N \), which serve as the - observable data. Our goal is to select a function from the hypothesis - set \( h\in\mathcal{H} \) which approximates \( f(x) \) as best as possible, - namely, we would like to find \( h\in\mathcal{H} \) such that \( h\approx - f \) in some strict mathematical sense which we specify below. If this - is possible, we say that we \emph{learned} \( f(x) \). But if the - function \( f(x) \) can, in principle, take any value on - \emph{unobserved} inputs, how is it possible to learn in any - meaningful sense? +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 + +$$ +\boldsymbol{y}=f(\boldsymbol{x}) + \boldsymbol{\epsilon} +$$ + +

    +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 +\( \boldsymbol{\beta} \) and the design matrix \( \boldsymbol{X} \) which embody our model, +that is \( \boldsymbol{\tilde{y}}=\boldsymbol{X}\boldsymbol{\beta} \). + +

    +Thereafter we found the parameters \( \boldsymbol{\beta} \) by optimizing the means squared error via the so-called cost function +$$ +C(\boldsymbol{X},\boldsymbol{\beta}) =\frac{1}{n}\sum_{i=0}^{n-1}(y_i-\tilde{y}_i)^2=\mathbb{E}\left[(\boldsymbol{y}-\boldsymbol{\tilde{y}})^2\right]. +$$ + +

    +We can rewrite this as +$$ +\mathbb{E}\left[(\boldsymbol{y}-\boldsymbol{\tilde{y}})^2\right]=\frac{1}{n}\sum_i(f_i-\mathbb{E}\left[\boldsymbol{\tilde{y}}\right])^2+\frac{1}{n}\sum_i(\tilde{y}_i-\mathbb{E}\left[\boldsymbol{\tilde{y}}\right])^2+\sigma^2. +$$ + +

    +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 \( \boldsymbol{\epsilon} \). + +

    +To derive this equation, we need to recall that the variance of \( \boldsymbol{y} \) and \( \boldsymbol{\epsilon} \) are both equal to \( \sigma^2 \). The mean value of \( \boldsymbol{\epsilon} \) is by definition equal to zero. Furthermore, the function \( f \) is not a stochastics variable, idem for \( \boldsymbol{\tilde{y}} \). +We use a more compact notation in terms of the expectation value +$$ +\mathbb{E}\left[(\boldsymbol{y}-\boldsymbol{\tilde{y}})^2\right]=\mathbb{E}\left[(\boldsymbol{f}+\boldsymbol{\epsilon}-\boldsymbol{\tilde{y}})^2\right], +$$ + +and adding and subtracting \( \mathbb{E}\left[\boldsymbol{\tilde{y}}\right] \) we get +$$ +\mathbb{E}\left[(\boldsymbol{y}-\boldsymbol{\tilde{y}})^2\right]=\mathbb{E}\left[(\boldsymbol{f}+\boldsymbol{\epsilon}-\boldsymbol{\tilde{y}}+\mathbb{E}\left[\boldsymbol{\tilde{y}}\right]-\mathbb{E}\left[\boldsymbol{\tilde{y}}\right])^2\right], +$$ + +which, using the abovementioned expectation values can be rewritten as +$$ +\mathbb{E}\left[(\boldsymbol{y}-\boldsymbol{\tilde{y}})^2\right]=\mathbb{E}\left[(\boldsymbol{y}-\mathbb{E}\left[\boldsymbol{\tilde{y}}\right])^2\right]+\mathrm{Var}\left[\boldsymbol{\tilde{y}}\right]+\sigma^2, +$$ + +that is the rewriting in terms of the so-called bias, the variance of the model \( \boldsymbol{\tilde{y}} \) and the variance of \( \boldsymbol{\epsilon} \). + +

    +









    + +

    Example code for Bias-Variance tradeoff

    +

    + + +

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

    +









    + +

    Understanding what happens

    +

    + + +

    import matplotlib.pyplot as plt
    +import numpy as np
    +from sklearn.linear_model import LinearRegression, Ridge, Lasso
    +from sklearn.preprocessing import PolynomialFeatures
    +from sklearn.model_selection import train_test_split
    +from sklearn.pipeline import make_pipeline
    +from sklearn.utils import resample
    +
    +np.random.seed(2018)
    +
    +n = 40
    +n_boostraps = 100
    +maxdegree = 14
    +
    +
    +# Make data set.
    +x = np.linspace(-3, 3, n).reshape(-1, 1)
    +y = np.exp(-x**2) + 1.5 * np.exp(-(x-2)**2)+ np.random.normal(0, 0.1, x.shape)
    +error = np.zeros(maxdegree)
    +bias = np.zeros(maxdegree)
    +variance = np.zeros(maxdegree)
    +polydegree = np.zeros(maxdegree)
    +x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.2)
    +
    +for degree in range(maxdegree):
    +    model = make_pipeline(PolynomialFeatures(degree=degree), LinearRegression(fit_intercept=False))
    +    y_pred = np.empty((y_test.shape[0], n_boostraps))
    +    for i in range(n_boostraps):
    +        x_, y_ = resample(x_train, y_train)
    +        y_pred[:, i] = model.fit(x_, y_).predict(x_test).ravel()
    +
    +    polydegree[degree] = degree
    +    error[degree] = np.mean( np.mean((y_test - y_pred)**2, axis=1, keepdims=True) )
    +    bias[degree] = np.mean( (y_test - np.mean(y_pred, axis=1, keepdims=True))**2 )
    +    variance[degree] = np.mean( np.var(y_pred, axis=1, keepdims=True) )
    +    print('Polynomial degree:', degree)
    +    print('Error:', error[degree])
    +    print('Bias^2:', bias[degree])
    +    print('Var:', variance[degree])
    +    print('{} >= {} + {} = {}'.format(error[degree], bias[degree], variance[degree], bias[degree]+variance[degree]))
    +
    +plt.plot(polydegree, np.log10(error), label='Error')
    +plt.plot(polydegree, bias, label='bias')
    +plt.plot(polydegree, variance, label='Variance')
    +plt.legend()
    +plt.show()
    +

    -

    Training and testing data

    - -

    -We will discuss the bias-variance tradeoff in the context of continuous predictions such as regression. However, many of the intuitions and ideas discussed here also carry over to classification tasks. Consider a dataset \( \mathcal{L} \) consisting of the data \( \mathbf{X}_\mathcal{L}=\{(y_j, \boldsymbol{x}_j), j=1\ldots N\} \). Let us assume that the true data is generated from a noisy model -$$ -y=f(\boldsymbol{x}) + \epsilon -$$ - -where \( \epsilon \) is normally distributed with mean zero and standard deviation \( \sigma_\epsilon \). - -

    -









    - -

    Procedure to find a predictor

    - -

    -We have a statistical procedure (e.g. least-squares regression) for -forming a predictor \( \hat{g}_{\mathcal{L}}(\boldsymbol{x}) \) that gives the -prediction of our model for a new data point \( \boldsymbol{x} \). This estimator -is chosen by minimizing a cost function which we take to be the -squared error - -$$ - \mathcal{C}( \boldsymbol{X}, \hat{g}(\boldsymbol{x})) = \sum_i (y_i - \hat{g}_\mathcal{L}(\boldsymbol{x}_i))^2. -$$ - -

    -









    - -

    What we want

    - -

    -We are interested in the generalization error on all data drawn from -the true model, not just the error on the particular training dataset -\( \mathcal{L} \) that we have in hand. This is just the expectation of -the cost function over many different data sets -\( \{\mathcal{L}_j\} \). Denote this expectation value by -\( E_{\mathcal{L}} \). In other words, we can view \( \hat{g}_{\mathcal{L}} \) -as a stochastic functional that depends on the dataset \( \mathcal{L} \) -and we can think of \( E_{\mathcal{L}} \) as the expected value of the -functional if we drew an infinite number of datasets \( \{\mathcal{L}_1, -\mathcal{L}_2, \ldots \} \). - -

    -









    - -

    The expected generalization error

    - -

    -We would also like to average over different instances of the -"noise" \( \epsilon \) and we denote the expectation value over the -noise by \( E_\epsilon \). Thus, we can decompose the expected -generalization error as - -$$ -\begin{align} -E_\mathcal{L, \epsilon}[\mathcal{C}( \boldsymbol{X}, \hat{g}(\boldsymbol{x})) ]&= E_\mathcal{L,\epsilon}\left[ \sum_i ({y}_i - \hat{g}_\mathcal{L}(\boldsymbol{x}_i))^2 \right] \nonumber \\ - &= E_\mathcal{L, \epsilon}\left[ \sum_{i}({y}_i -f(\boldsymbol{x}_i) +f(\boldsymbol{x}_i)- \hat{g}_\mathcal{L}(\boldsymbol{x}_i))^2\right] \nonumber \\ - &= \sum_i E_\epsilon[ ({y}_i -f(\boldsymbol{x}_i))^2 ]+ E_\mathcal{L, \epsilon}[(f(\boldsymbol{x}_i)- \hat{g}_\mathcal{L}(\boldsymbol{x}_i))^2] + 2E_\epsilon[{y}_i -f(\boldsymbol{x}_i)]E_\mathcal{L}[f(\boldsymbol{x}_i)- \hat{g}_\mathcal{L}(\boldsymbol{x}_i)] \nonumber \\ - &=\sum_i \sigma_\epsilon^2 + E_\mathcal{L}[(f(\boldsymbol{x}_i)- \hat{g}_\mathcal{L}(\boldsymbol{x}_i))^2], -\label{_auto17} -\end{align} -$$ - -

    -where in the last line we used the fact that our noise has zero mean -and variance \( \sigma_\epsilon^2 \) and the sum over \( i \) applies to all -terms. - -

    -









    - -

    Elaborating a little bit more

    - -

    -It is also helpful to further decompose the second term as -follows: - -$$ -\begin{align} -E_\mathcal{L}[(f(\boldsymbol{x}_i)- \hat{g}_\mathcal{L}(\boldsymbol{x}_i))^2] &=E_\mathcal{L}[(f(\mathbf{x}_i)-E_\mathcal{L}[\hat{g}_\mathcal{L}(\boldsymbol{x}_i)]+ E_\mathcal{L}[\hat{g}_\mathcal{L}(\boldsymbol{x}_i)]- \hat{g}_\mathcal{L}(\boldsymbol{x}_i))^2] \nonumber \\ -&=E_\mathcal{L}[(f(\boldsymbol{x}_i)-E_\mathcal{L}[\hat{g}_\mathcal{L}(\boldsymbol{x}_i)])^2] + E_\mathcal{L}[( \hat{g}_\mathcal{L}(\boldsymbol{x}_i)-E_\mathcal{L}[\hat{g}_\mathcal{L}(\boldsymbol{x}_i)])^2] \nonumber \\ -&+2E_\mathcal{L}[(f(\boldsymbol{x}_i)-E_\mathcal{L}[\hat{g}_\mathcal{L}(\boldsymbol{x}_i)])( \hat{g}_\mathcal{L}(\boldsymbol{x}_i)-E_\mathcal{L}[\hat{g}_\mathcal{L}(\boldsymbol{x}_i)])] \nonumber \\ -&=(f(\boldsymbol{x}_i)-E_\mathcal{L}[\hat{g}_\mathcal{L}(\boldsymbol{x}_i)])^2+E_\mathcal{L}[( \hat{g}_\mathcal{L}(\boldsymbol{x}_i)-E_\mathcal{L}[\hat{g}_\mathcal{L}(\boldsymbol{x}_i)])^2]. -\label{_auto18} -\end{align} -$$ - -

    -









    - -

    The bias

    - -

    -The first term is called the bias -$$ -Bias^2= \sum_i (f(\boldsymbol{x}_i)-E_\mathcal{L}[\hat{g}_\mathcal{L}(\boldsymbol{x}_i)])^2 -$$ - -and measures the deviation of the expectation value of our estimator (i.e. the asymptotic value of our estimator in the infinite data limit) from the true value. - -

    -









    - -

    The variance

    -The second term is called the variance -$$ -Var=\sum_i E_\mathcal{L}[( \hat{g}_\mathcal{L}(\boldsymbol{x}_i)-E_\mathcal{L}[\hat{g}_\mathcal{L}(\boldsymbol{x}_i)])^2], -$$ - -

    -and measures how much our estimator fluctuates due to finite-sample effects. Combining these expressions, we see that the expected out-of-sample error of our model can be decomposed as -$$ -E_\mathrm{out}=E_\mathcal{L, \epsilon}[\mathcal{C}( \boldsymbol{X}, \hat{g}(\boldsymbol{x})) ] = Bias^2 + Var + Noise. -$$ +

    Summing up

    The bias-variance tradeoff summarizes the fundamental tension in machine learning, particularly supervised learning, between the complexity of a model and the amount of training data needed to train it. Since data is often limited, in practice it is often useful to -use a less-complex model with higher bias – a model whose asymptotic -performance is worse than another model – because it is easier to +use a less-complex model with higher bias, that is a model whose asymptotic +performance is worse than another model because it is easier to train and less sensitive to sampling noise arising from having a finite-sized training dataset (smaller variance). -

    - - -

    Summing up

    -

    The above equations tell us that in order to minimize the expected test error, we need to select a @@ -3498,15 +3645,99 @@ flexible statistical methods have higher variance.











    -

    The one-dimensional Ising model, project 2

    +

    Another Example rom Scikit-Learn's Repository

    +

    + + +

    """
    +============================
    +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()
    +
    +

    +









    + +

    The one-dimensional Ising model

    -The one-dimensional Ising model with nearest neighbor interaction, no external field and a constant coupling constant \( J \) is given by +Let us bring back the Ising model again, but now with an additional +focus on Ridge and Lasso regression as well. We repeat some of the +basic parts of the Ising model and the setup of the training and test +data. The one-dimensional Ising model with nearest neighbor +interaction, no external field and a constant coupling constant \( J \) is +given by $$ \begin{align} H = -J \sum_{k}^L s_k s_{k + 1}, -\label{_auto19} +\label{_auto17} \end{align} $$ @@ -3540,25 +3771,13 @@ energies = np.zeros(n) for i in range(n): energies[i] = - J * np.dot(spins[i], np.roll(spins[i], 1))

    -

    -Here we use linear (ordinary least squares), ridge and LASSO -regression to predict the energy in the nearest neighbor -one-dimensional Ising model on a ring, i.e., the endpoints wrap -around. We will use the linear regression models to fit a value for -the coupling constant to achieve this. - -

    -









    - -

    Reformulating the problem to suit regression

    -

    A more general form for the one-dimensional Ising model is $$ \begin{align} H = - \sum_j^L \sum_k^L s_j s_k J_{jk}. -\label{_auto20} +\label{_auto18} \end{align} $$ @@ -3569,7 +3788,7 @@ a matrix-product on the form $$ \begin{align} H = X J, -\label{_auto21} +\label{_auto19} \end{align} $$ @@ -3579,11 +3798,12 @@ elements \( -J_{jk} \). This form of writing the energy fits perfectly with the form utilized in linear regression, viz. $$ \begin{align} - y = X\omega + \epsilon, -\label{_auto22} + \boldsymbol{y} = \boldsymbol{X}\boldsymbol{\beta} + \boldsymbol{\epsilon}. +\label{_auto20} \end{align} $$ +We organize the data as we did above

    @@ -3604,149 +3824,7 @@ X_test_own = np.concatenate( )

    -









    - -

    Linear regression

    - -

    -The problem at hand is to try to fit the equation -$$ -\begin{align} - y = f(x) + \epsilon, -\label{_auto23} -\end{align} -$$ - -

    -where \( f(x) \) is some unknown function of the data \( x \) and \( \epsilon \) -is normally distributed with mean zero noise with standard deviation -\( \sigma_{\epsilon} \). Our job is to try to find a predictor which -estimates the function \( f(x) \). In linear regression we assume that we -can formulate the problem as - -$$ -\begin{align} - y = X\omega + \epsilon, -\label{_auto24} -\end{align} -$$ - -

    -where \( X \) and \( \omega \) are now matrices. Our job at hand is now to -find a cost function \( C \), which we wish to minimize in order to find -the best estimate of \( \omega \). - -

    -









    - -

    Ordinary least squares

    - -

    -In the ordinary least squares method we choose the cost function -$$ -\begin{align} - C(X, \omega) = ||X\omega - y||^2 - = (X\omega - y)^T(X\omega - y) -\label{_auto25} -\end{align} -$$ - -We then find the extremal point of \( C \) by taking the derivative with respect to \( \omega \) and setting it to zero, i.e., - -$$ -\begin{align} - \dfrac{\mathrm{d}C}{\mathrm{d}\omega} - = 0. -\label{_auto26} -\end{align} -$$ - -This yields the expression for \( \omega \) to be -$$ -\begin{align} - \omega = \frac{X^T y}{X^T X}, -\label{_auto27} -\end{align} -$$ - -

    -which immediately imposes some requirements on \( X \) as there must exist -an inverse of \( X^T X \). If the expression we are modelling contains an -intercept, i.e., a constant expression we must make sure that the -first column of \( X \) consists of \( 1 \). - -

    - - -

    def get_ols_weights_naive(x: np.ndarray, y: np.ndarray) -> np.ndarray:
    -    return scl.inv(x.T @ x) @ (x.T @ y)
    -omega = get_ols_weights_naive(X_train_own, y_train)
    -
    -

    -









    - -

    Singular Value decomposition

    -Doing the inversion directly turns out to be a bad idea as the matrix -\( X^TX \) is singular. An alternative approach is to use the singular -value decomposition. Using the definition of the Moore-Penrose -pseudoinverse we can write the equation for \( \omega \) as - -$$ -\begin{align} - \omega = X^{+}y, -\label{_auto28} -\end{align} -$$ - -where the pseudoinverse of \( X \) is given by -$$ -\begin{align} - X^{+} = \frac{X^T}{X^T X}. -\label{_auto29} -\end{align} -$$ - -

    -Using singular value decomposition we have that \( X = U\Sigma V^T \), -where \( X^{+} = V\Sigma^{+} U^T \). This reduces the equation for -\( \omega \) to -$$ -\begin{align} - \omega = V\Sigma^{+} U^T y. -\label{_auto30} -\end{align} -$$ - -

    -Note that solving this equation by actually doing the pseudoinverse -(which is what we will do) is not a good idea as this operation scales -as \( \mathcal{O}(n^3) \), where \( n \) is the number of elements in a -general matrix. Instead, doing \( QR \)-factorization and solving the -linear system as an equation would reduce this down to -\( \mathcal{O}(n^2) \) operations. - -

    - - -

    def get_ols_weights(x: np.ndarray, y: np.ndarray) -> np.ndarray:
    -    u, s, v = scl.svd(x)
    -    return v.T @ scl.pinv(scl.diagsvd(s, u.shape[0], v.shape[0])) @ u.T @ y
    -
    -

    -Before passing in the data to the function we append a column with ones to the training data. - -

    - - -

    omega = get_ols_weights(X_train_own,y_train)
    -
    -

    -









    - -

    Fitting with scikit-learn

    - -

    -Next we fit a LinearRegression-model from Scikit-learn for comparison. +We will do all fitting with Scikit-Learn,

    @@ -3754,29 +3832,18 @@ Next we fit a LinearRegression-model from Scikit-learn for comparis

    clf = skl.LinearRegression().fit(X_train, y_train)
     

    -Extracting the \( J \)-matrix from both our own method and the Scikit-learn model where we make sure to remove the intercept. - +When extracting the \( J \)-matrix we make sure to remove the intercept

    -

    J_own = omega[1:].reshape(L, L)
    -J_sk = clf.coef_.reshape(L, L)
    +
    J_sk = clf.coef_.reshape(L, L)
     

    -A way of looking at the coefficients in \( J \) is to plot the matrices as images. - +And then we plot the results

    fig = plt.figure(figsize=(20, 14))
    -im = plt.imshow(J_own, **cmap_args)
    -plt.title("Home-made OLS", fontsize=18)
    -plt.xticks(fontsize=18)
    -plt.yticks(fontsize=18)
    -cb = fig.colorbar(im)
    -cb.ax.set_yticklabels(cb.ax.get_yticklabels(), fontsize=18)
    -
    -fig = plt.figure(figsize=(20, 14))
     im = plt.imshow(J_sk, **cmap_args)
     plt.title("LinearRegression from Scikit-learn", fontsize=18)
     plt.xticks(fontsize=18)
    @@ -3786,66 +3853,33 @@ cb.ax.set_yticklabels(cb.ax.get_yticklabels(), fontsize=Ridge regression 
    +

    Ridge regression

    Having explored the ordinary least squares we move on to ridge regression. In ridge regression we include a regularizer. This involves a new cost function which leads to a new estimate for the -weights \( \omega \). This results in a penalized regression problem. The +weights \( \boldsymbol{\beta} \). This results in a penalized regression problem. The cost function is given by $$ \begin{align} - C(X, \omega; \lambda) = ||X\omega - y||^2 + \lambda ||\omega||^2 - = (X\omega - y)^T(X\omega - y) + \lambda \omega^T\omega. -\label{_auto31} + C(\boldsymbol{X}, \boldsymbol{\beta}; \lambda) = (\boldsymbol{X}\boldsymbol{\beta} - \boldsymbol{y})^T(\boldsymbol{X}\boldsymbol{\beta} - \boldsymbol{y}) + \lambda \boldsymbol{\beta}^T\boldsymbol{\beta}. +\label{_auto21} \end{align} $$ -Finding the extremum of this function yields the weights - -$$ -\begin{align} - \omega(\lambda) = \frac{X^Ty}{X^TX + \lambda} \to \frac{\omega_{\text{LS}}}{1 + \lambda}, -\label{_auto32} -\end{align} -$$ - -

    -where \( \omega_{\text{LS}} \) is the weights from ordinary least -squares. The last assumption assumes that \( X \) is orthogonal, which it -is not. We will therefore resort to solving the equation as it stands -on the left hand side. -

    -

    def get_ridge_weights(x: np.ndarray, y: np.ndarray, _lambda: float) -> np.ndarray:
    -    return x.T @ y @ scl.inv(
    -        x.T @ x + np.eye(x.shape[1], x.shape[1]) * _lambda
    -    )
    -_lambda = 0.1
    -omega_ridge = get_ridge_weights(X_train_own, y_train, np.array([_lambda]))
    +
    _lambda = 0.1
     clf_ridge = skl.Ridge(alpha=_lambda).fit(X_train, y_train)
    -J_ridge_own = omega_ridge[1:].reshape(L, L)
     J_ridge_sk = clf_ridge.coef_.reshape(L, L)
    -fig = plt.figure(figsize=(20, 14))
    -im = plt.imshow(J_ridge_own, **cmap_args)
    -plt.title("Home-made ridge regression", fontsize=18)
    -plt.xticks(fontsize=18)
    -plt.yticks(fontsize=18)
    -cb = fig.colorbar(im)
    -cb.ax.set_yticklabels(cb.ax.get_yticklabels(), fontsize=18)
    -
     fig = plt.figure(figsize=(20, 14))
     im = plt.imshow(J_ridge_sk, **cmap_args)
     plt.title("Ridge from Scikit-learn", fontsize=18)
    @@ -3859,20 +3893,20 @@ plt.show()
     











    -

    LASSO regression

    +

    LASSO regression

    In the Least Absolute Shrinkage and Selection Operator (LASSO)-method we get a third cost function. + $$ \begin{align} - C(X, \omega; \lambda) = - ||X\omega - y||^2 + \lambda ||\omega|| - = (X\omega - y)^T(X\omega - y) + \lambda \sqrt{\omega^T\omega}. -\label{_auto33} + C(\boldsymbol{X}, \boldsymbol{\beta}; \lambda) = (\boldsymbol{X}\boldsymbol{\beta} - \boldsymbol{y})^T(\boldsymbol{X}\boldsymbol{\beta} - \boldsymbol{y}) + \lambda \sqrt{\boldsymbol{\beta}^T\boldsymbol{\beta}}. +\label{_auto22} \end{align} $$ -Finding the extremal point of this cost function is not so straight-forward as in least squares and ridge. We will therefore rely solely on the function ``Lasso`` from Scikit-learn. +

    +Finding the extremal point of this cost function is not so straight-forward as in least squares and ridge. We will therefore rely solely on the function ``Lasso`` from Scikit-Learn.

    @@ -3897,41 +3931,7 @@ constant as opposed to ridge and OLS. We get a sparse solution with











    -

    Performance of the different models

    - -

    -In order to judge which model performs best at varying values of \( \lambda \) (for ridge and LASSO) we compute \( R^2 \) which is given by - -$$ -\begin{align} - R^2 = 1 - \frac{(y - \hat{y})^2}{(y - \bar{y})^2}, -\label{_auto34} -\end{align} -$$ - -where \( y \) is a vector with the true values of the energy, \( \hat{y} \) is the predicted values of \( y \) from the models and \( \bar{y} \) is the mean of \( \hat{y} \). - -

    - - -

    def r_squared(y, y_hat):
    -    return 1 - np.sum((y - y_hat) ** 2) / np.sum((y - np.mean(y_hat)) ** 2)
    -
    -

    -This is the same metric used by Scikit-learn for their regression models when scoring. -

    - - -

    y_hat = clf.predict(X_test)
    -r_test = r_squared(y_test, y_hat)
    -sk_r_test = clf.score(X_test, y_test)
    -
    -assert abs(r_test - sk_r_test) < 1e-2
    -
    -

    -









    - -

    Performance as function of the regularization parameter

    +

    Performance as function of the regularization parameter

    We see how the different models perform for a different set of values for \( \lambda \). @@ -3942,17 +3942,13 @@ We see how the different models perform for a different set of values for \( \la

    lambdas = np.logspace(-4, 5, 10)
     
     train_errors = {
    -    "ols_own": np.zeros(lambdas.size),
         "ols_sk": np.zeros(lambdas.size),
    -    "ridge_own": np.zeros(lambdas.size),
         "ridge_sk": np.zeros(lambdas.size),
         "lasso_sk": np.zeros(lambdas.size)
     }
     
     test_errors = {
    -    "ols_own": np.zeros(lambdas.size),
         "ols_sk": np.zeros(lambdas.size),
    -    "ridge_own": np.zeros(lambdas.size),
         "ridge_sk": np.zeros(lambdas.size),
         "lasso_sk": np.zeros(lambdas.size)
     }
    @@ -3962,30 +3958,6 @@ plot_counter = 1
     fig = plt.figure(figsize=(32, 54))
     
     for i, _lambda in enumerate(tqdm.tqdm(lambdas)):
    -    omega = get_ols_weights(X_train_own, y_train)
    -    y_hat_train = X_train_own @ omega
    -    y_hat_test = X_test_own @ omega
    -
    -    train_errors["ols_own"][i] = r_squared(y_train, y_hat_train)
    -    test_errors["ols_own"][i] = r_squared(y_test, y_hat_test)
    -
    -    plt.subplot(10, 5, plot_counter)
    -    plt.imshow(omega[1:].reshape(L, L), **cmap_args)
    -    plt.title("Home made OLS")
    -    plot_counter += 1
    -
    -    omega = get_ridge_weights(X_train_own, y_train, _lambda)
    -    y_hat_train = X_train_own @ omega
    -    y_hat_test = X_test_own @ omega
    -
    -    train_errors["ridge_own"][i] = r_squared(y_train, y_hat_train)
    -    test_errors["ridge_own"][i] = r_squared(y_test, y_hat_test)
    -
    -    plt.subplot(10, 5, plot_counter)
    -    plt.imshow(omega[1:].reshape(L, L), **cmap_args)
    -    plt.title(r"Home made ridge, $\lambda = %.4f$" % _lambda)
    -    plot_counter += 1
    -
         for key, method in zip(
             ["ols_sk", "ridge_sk", "lasso_sk"],
             [skl.LinearRegression(), skl.Ridge(alpha=_lambda), skl.Lasso(alpha=_lambda)]
    @@ -4005,7 +3977,7 @@ fig = plt.figure(figsize=(32, 
     









    -

    Finding the optimal value of \( \lambda \)

    +

    Finding the optimal value of \( \lambda \)

    To determine which value of \( \lambda \) is best we plot the accuracy of @@ -4029,8 +4001,6 @@ testing set that is close to the accuracy of the training set.

    fig = plt.figure(figsize=(20, 14))
     
     colors = {
    -    "ols_own": "b",
    -    "ridge_own": "g",
         "ols_sk": "r",
         "ridge_sk": "y",
         "lasso_sk": "c"
    @@ -4053,9 +4023,6 @@ colors = {
             label="Test {0}".format(key),
             linewidth=4.0
         )
    -#plt.semilogx(lambdas, train_errors["ols_own"], label="Train (OLS own)")
    -#plt.semilogx(lambdas, test_errors["ols_own"], label="Test (OLS own)")
    -
     plt.legend(loc="best", fontsize=18)
     plt.xlabel(r"$\lambda$", fontsize=18)
     plt.ylabel(r"$R^2$", fontsize=18)
    @@ -4064,14 +4031,245 @@ plt.show()
     

    From the above figure we can see that LASSO with \( \lambda = 10^{-2} \) -achieve a very good accuracy on the test set. This by far surpases the +achieves a very good accuracy on the test set. This by far surpasses the other models for all values of \( \lambda \). +

    +









    + +

    Further Exercises

    + +

    Exercise 1

    + +

    +We will generate our own dataset for a function \( y(x) \) where \( x \in [0,1] \) and defined by random numbers computed with the uniform distribution. The function \( y \) is a quadratic polynomial in \( x \) with added stochastic noise according to the normal distribution \( \cal {N}(0,1) \). +The following simple Python instructions define our \( x \) and \( y \) values (with 100 data points). +

    + + +

    x = np.random.rand(100,1)
    +y = 5*x*x+0.1*np.random.randn(100,1)
    +
    +
      +
    1. Write your own code (following the examples above) for computing the parametrization of the data set fitting a second-order polynomial.
    2. +
    3. Use thereafter scikit-learn (see again the examples in the regression slides) and compare with your own code.
    4. +
    5. Using scikit-learn, compute also the mean square error, a risk metric corresponding to the expected value of the squared (quadratic) error defined as
    6. +
    + +$$ MSE(\hat{y},\hat{\tilde{y}}) = \frac{1}{n} +\sum_{i=0}^{n-1}(y_i-\tilde{y}_i)^2, +$$ + +and the \( R^2 \) score function. +If \( \tilde{\hat{y}}_i \) is the predicted value of the \( i-th \) sample and \( y_i \) is the corresponding true value, then the score \( R^2 \) is defined as +$$ +R^2(\hat{y}, \tilde{\hat{y}}) = 1 - \frac{\sum_{i=0}^{n - 1} (y_i - \tilde{y}_i)^2}{\sum_{i=0}^{n - 1} (y_i - \bar{y})^2}, +$$ + +where we have defined the mean value of \( \hat{y} \) as +$$ +\bar{y} = \frac{1}{n} \sum_{i=0}^{n - 1} y_i. +$$ + +

    +You can use the functionality included in scikit-learn. If you feel +for it, you can use your own program and define functions which +compute the above two functions. Discuss the meaning of these +results. Try also to vary the coefficient in front of the added +stochastic noise term and discuss the quality of the fits. + +

    Exercise 2, variance of the parameters \( \beta \) in linear regression

    + +

    +Show that the variance of the parameters \( \beta \) in the linear regression method (chapter 3, equation (3.8) of Trevor Hastie, Robert Tibshirani, Jerome H. Friedman, The Elements of Statistical Learning, Springer) is given as + +$$ +\mathrm{Var}(\hat{\beta}) = \left(\hat{X}^T\hat{X}\right)^{-1}\sigma^2, +$$ + +with +$$ +\sigma^2 = \frac{1}{N-p-1}\sum_{i=1}^{N} (y_i-\tilde{y}_i)^2, +$$ + +where we have assumed that we fit a function of degree \( p-1 \) (for example a polynomial in \( x \)). + +

    Exercise 3

    + +

    +This exercise is a continuation of exercise 1. We will +use the same function to generate our data set, still staying with a +simple function \( y(x) \) which we want to fit using linear regression, +but now extending the analysis to include the Ridge and the Lasso +regression methods. You can use the code under the Regression as an example on how to use the Ridge and the Lasso methods. + +

    +We will thus again generate our own dataset for a function \( y(x) \) where +\( x \in [0,1] \) and defined by random numbers computed with the uniform +distribution. The function \( y \) is a quadratic polynomial in \( x \) with +added stochastic noise according to the normal distribution \( \cal{N}(0,1) \). + +

    +The following simple Python instructions define our \( x \) and \( y \) values (with 100 data points). +

    + + +

    x = np.random.rand(100,1)
    +y = 5*x*x+0.1*np.random.randn(100,1)
    +
    +
      +
    1. Write your own code for the Ridge method and compute the parametrization for different values of \( \lambda \). Compare and analyze your results with those from exercise 1. Study the dependence on \( \lambda \) while also varying the strength of the noise in your expression for \( y(x) \).
    2. +
    3. Repeat the above but using the functionality of scikit-learn. Compare your code with the results from scikit-learn. Remember to run with the same random numbers for generating \( x \) and \( y \).
    4. +
    5. Our next step is to study the variance of the parameters \( \beta_1 \) and \( \beta_2 \) (assuming that we are parametrizing our function with a second-order polynomial. We will use standard linear regression and the Ridge regression. You can now opt for either writing your own function that calculates the variance of these paramaters (recall that this is equal to the diagonal elements of the matrix \( (\hat{X}^T\hat{X})+\lambda\hat{I})^{-1} \)) or use the functionality of scikit-learn and compute their variances. Discuss the results of these variances as functions
    6. +
    7. Repeat the previous step but add now the Lasso method. Discuss your results and compare with standard regression and the Ridge regression results.
    8. +
    9. Try to implement the cross-validation as well.
    10. +
    11. Finally, using scikit-learn or your own code, compute also the mean square error, a risk metric corresponding to the expected value of the squared (quadratic) error defined as
    12. +
    + +$$ MSE(\hat{y},\hat{\tilde{y}}) = \frac{1}{n} +\sum_{i=0}^{n-1}(y_i-\tilde{y}_i)^2, +$$ + +and the \( R^2 \) score function. +If \( \tilde{\hat{y}}_i \) is the predicted value of the \( i-th \) sample and \( y_i \) is the corresponding true value, then the score \( R^2 \) is defined as +$$ +R^2(\hat{y}, \tilde{\hat{y}}) = 1 - \frac{\sum_{i=0}^{n - 1} (y_i - \tilde{y}_i)^2}{\sum_{i=0}^{n - 1} (y_i - \bar{y})^2}, +$$ + +where we have defined the mean value of \( \hat{y} \) as +$$ +\bar{y} = \frac{1}{n} \sum_{i=0}^{n - 1} y_i. +$$ + +Discuss these quantities as functions of the variable \( \lambda \) in the Ridge and Lasso regression methods. + +

    Exercise 4

    + +

    +We will study how +to fit polynomials to a specific two-dimensional function called +Franke's +function. This +is a function which has been widely used when testing various interpolation and fitting +algorithms. Furthermore, after having established the model and the +method, we will employ resamling techniques such as the cross-validation and/or +the bootstrap methods, in order to perform a proper assessment of our models. + +

    +The Franke function, which is a weighted sum of four exponentials reads as follows +$$ +\begin{align*} +f(x,y) &= \frac{3}{4}\exp{\left(-\frac{(9x-2)^2}{4} - \frac{(9y-2)^2}{4}\right)}+\frac{3}{4}\exp{\left(-\frac{(9x+1)^2}{49}- \frac{(9y+1)}{10}\right)} \\ +&+\frac{1}{2}\exp{\left(-\frac{(9x-7)^2}{4} - \frac{(9y-3)^2}{4}\right)} -\frac{1}{5}\exp{\left(-(9x-4)^2 - (9y-7)^2\right) }. +\end{align*} +$$ + +

    +The function will be defined for \( x,y\in [0,1] \). Our first step will +be to perform an OLS regression analysis of this function, trying out +a polynomial fit with an \( x \) and \( y \) dependence of the form \( [x, y, +x^2, y^2, xy, \dots] \). We will also include cross-validation and +bootstrap as resampling techniques. As in homeworks 1 and 2, we +can use a uniform distribution to set up the arrays of values for \( x \) +and \( y \), or as in the example below just a fix values for \( x \) and \( y \) with a given step size. +In this case we will have two predictors and need to fit a +function (for example a polynomial) of \( x \) and \( y \). Thereafter we will +repeat much of the same procedure using the the Ridge and +Lasso regression methods, introducing thus a dependence on the bias +(penalty) \( \lambda \). + +

    +The Python fucntion for the Franke function is included here (it performs also a three-dimensional plot of it) +

    + + +

    from mpl_toolkits.mplot3d import Axes3D
    +import matplotlib.pyplot as plt
    +from matplotlib import cm
    +from matplotlib.ticker import LinearLocator, FormatStrFormatter
    +import numpy as np
    +from random import random, seed
    +
    +fig = plt.figure()
    +ax = fig.gca(projection='3d')
    +
    +# Make data.
    +x = np.arange(0, 1, 0.05)
    +y = np.arange(0, 1, 0.05)
    +x, y = np.meshgrid(x,y)
    +
    +
    +def FrankeFunction(x,y):
    +    term1 = 0.75*np.exp(-(0.25*(9*x-2)**2) - 0.25*((9*y-2)**2))
    +    term2 = 0.75*np.exp(-((9*x+1)**2)/49.0 - 0.1*(9*y+1))
    +    term3 = 0.5*np.exp(-(9*x-7)**2/4.0 - 0.25*((9*y-3)**2))
    +    term4 = -0.2*np.exp(-(9*x-4)**2 - (9*y-7)**2)
    +    return term1 + term2 + term3 + term4
    +
    +
    +z = FrankeFunction(x, y)
    +
    +# Plot the surface.
    +surf = ax.plot_surface(x, y, z, cmap=cm.coolwarm,
    +                       linewidth=0, antialiased=False)
    +
    +# Customize the z axis.
    +ax.set_zlim(-0.10, 1.40)
    +ax.zaxis.set_major_locator(LinearLocator(10))
    +ax.zaxis.set_major_formatter(FormatStrFormatter('%.02f'))
    +
    +# Add a color bar which maps values to colors.
    +fig.colorbar(surf, shrink=0.5, aspect=5)
    +
    +plt.show()
    +
    +

    +We will thus again generate our own dataset for a function \( \mathrm{FrankeFunction}(x,y) \) where +\( x,y \in [0,1] \) could be defined by random numbers computed with the uniform +distribution. The function \( f(x,y) \) is the Franke function. You should explore also the addition +an added stochastic noise to this function using the normal distribution \( \cal{N}(0,1) \). + +

    +Write your own code (using either a matrix inversion or a singular value decomposition from e.g., numpy ) or use your code from exercises 1 and 3 +and perform a standard least square regression analysis using polynomials in \( x \) and \( y \) up to fifth order. Find the confidence intervals of the parameters \( \beta \) by computing their variances, evaluate the Mean Squared error (MSE) +$$ MSE(\hat{y},\hat{\tilde{y}}) = \frac{1}{n} +\sum_{i=0}^{n-1}(y_i-\tilde{y}_i)^2, +$$ + +and the \( R^2 \) score function. +If \( \tilde{\hat{y}}_i \) is the predicted value of the \( i-th \) sample and \( y_i \) is the corresponding true value, then the score \( R^2 \) is defined as +$$ +R^2(\hat{y}, \tilde{\hat{y}}) = 1 - \frac{\sum_{i=0}^{n - 1} (y_i - \tilde{y}_i)^2}{\sum_{i=0}^{n - 1} (y_i - \bar{y})^2}, +$$ + +where we have defined the mean value of \( \hat{y} \) as +$$ +\bar{y} = \frac{1}{n} \sum_{i=0}^{n - 1} y_i. +$$ + +

    +Perform a resampling of the data where you split the data in training data and test data. Implement the \( k \)-fold cross-validation algorithm and/or the bootstrap algorithm +and evaluate again the MSE and the \( R^2 \) functions resulting from the test data. Evaluate also the bias and variance of the final models. + +

    +Write then your own code for the Ridge method, either using matrix +inversion or the singular value decomposition as done for standard OLS. Perform the same analysis as in the +previous exercise (for the same polynomials and include resampling +techniques) but now for different values of \( \lambda \). Compare and +analyze your results with those obtained with standard OLS. Study the +dependence on \( \lambda \) while also varying eventually the strength of +the noise in your expression for \( \mathrm{FrankeFunction}(x,y) \). + +

    +Then perform the same studies but now with Lasso regression. Use the functionalities of +scikit-learn. Give a critical discussion of the three methods and a +judgement of which model fits the data best. +

    - © 1999-2018, Morten Hjorth-Jensen. Released under CC Attribution-NonCommercial 4.0 license + © 1999-2019, Morten Hjorth-Jensen. Released under CC Attribution-NonCommercial 4.0 license
    diff --git a/doc/pub/Regression/html/Regression.html b/doc/pub/Regression/html/Regression.html index bd9eb1210..bb0bdb606 100644 --- a/doc/pub/Regression/html/Regression.html +++ b/doc/pub/Regression/html/Regression.html @@ -6,6 +6,7 @@ Automatically generated HTML file from DocOnce source + Data Analysis and Machine Learning: Linear Regression and more Advanced Regression Analysis @@ -65,160 +66,151 @@ div { text-align: justify; text-justify: inter-word; } @@ -315,59 +292,84 @@ MathJax.Hub.Config({
    [2] Department of Physics and Astronomy and National Superconducting Cyclotron Laboratory, Michigan State University

    -

    Oct 18, 2018

    +

    Jun 10, 2019












    -

    Regression analysis, overarching aims

    +

    Why Linear Regression (aka Ordinary Least Squares and family)

    + +

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

      +
    • Method of choice for fitting a continuous function!
    • +
    • Gives an excellent introduction to central Machine Learning features with understandable pedagogical links to other methods like Neural Networks, Support Vector Machines etc
    • +
    • Analytical expression for the fitting parameters \( \boldsymbol{\beta} \)
    • +
    • Analytical expressions for statistical propertiers like mean values, variances, confidence intervals and more
    • +
    • Analytical relation with probabilistic interpretations
    • +
    • Easy to introduce basic concepts like bias-variance tradeoff, cross-validation, resampling and regularization techniques and many other ML topics
    • +
    • Easy to code! And links well with classification problems and logistic regression and neural networks
    • +
    • Allows for easy hands-on understanding of gradient descent methods
    • +
    • and many more features
    • +
    + +For more discussions of Ridge and Lasso regression, Wessel van Wieringen's article is highly recommended. +Similarly, Mehta et al's article is also recommended. + +

    +









    + +

    Regression analysis, overarching aims

    -Regression modeling deals with the description of the sampling distribution of a given random variable \( y \) varies as function of another variable or a set of such variables \( \hat{x} =[x_0, x_1,\dots, x_p]^T \). -The first variable is called the dependent, the outcome or the response variable while the set of variables \( \hat{x} \) is called the independent variable, or the predictor variable or the explanatory variable. +Regression modeling deals with the description of the sampling distribution of a given random variable \( y \) and how it varies as function of another variable or a set of such variables \( \boldsymbol{x} =[x_0, x_1,\dots, x_{n-1}]^T \). +The first variable is called the dependent, the outcome or the response variable while the set of variables \( \boldsymbol{x} \) is called the independent variable, or the predictor variable or the explanatory variable.

    -A regression model aims at finding a likelihood function \( p(y\vert \hat{x}) \), that is the conditional distribution for \( y \) with a given \( \hat{x} \). The estimation of \( p(y\vert \hat{x}) \) is made using a data set with +A regression model aims at finding a likelihood function \( p(\boldsymbol{y}\vert \boldsymbol{x}) \), that is the conditional distribution for \( \boldsymbol{y} \) with a given \( \boldsymbol{x} \). The estimation of \( p(\boldsymbol{y}\vert \boldsymbol{x}) \) is made using a data set with

    • \( n \) cases \( i = 0, 1, 2, \dots, n-1 \)
    • -
    • Response (dependent or outcome) variable \( y_i \) with \( i = 0, 1, 2, \dots, n-1 \)
    • -
    • \( p \) Explanatory (independent or predictor) variables \( \hat{x}_i=[x_{i0}, x_{i1}, \dots, x_{ip}] \) with \( i = 0, 1, 2, \dots, n-1 \)
    • +
    • Response (target, dependent or outcome) variable \( y_i \) with \( i = 0, 1, 2, \dots, n-1 \)
    • +
    • \( p \) so-called explanatory (independent or predictor) variables \( \boldsymbol{x}_i=[x_{i0}, x_{i1}, \dots, x_{ip-1}] \) with \( i = 0, 1, 2, \dots, n-1 \) and explanatory variables running from \( 0 \) to \( p-1 \). See below for more explicit examples.
    - The goal of the regression analysis is to extract/exploit relationship between \( y_i \) and \( \hat{x}_i \) in or to infer causal dependencies, approximations to the likelihood functions, functional relationships and to make predictions . + The goal of the regression analysis is to extract/exploit relationship between \( \boldsymbol{y} \) and \( \boldsymbol{X} \) in or to infer causal dependencies, approximations to the likelihood functions, functional relationships and to make predictions, making fits and many other things.











    -

    Regression analysis, overarching aims II

    +

    Regression analysis, overarching aims II

    Consider an experiment in which \( p \) characteristics of \( n \) samples are -measured. The data from this experiment are denoted \( \mathbf{X} \), with -\( \mathbf{X} \) as above. The matrix \( \mathbf{X} \) is called the design +measured. The data from this experiment, for various explanatory variables \( p \) are normally represented by a matrix +\( \mathbf{X} \). + +

    +The matrix \( \mathbf{X} \) is called the design matrix. Additional information of the samples is available in the -form of \( \mathbf{Y} \) (also as above). The variable \( \mathbf{Y} \) is +form of \( \boldsymbol{y} \) (also as above). The variable \( \boldsymbol{y} \) is generally referred to as the response variable. The aim of -regression analysis is to explain \( \mathbf{Y} \) in terms of -\( \mathbf{X} \) through a functional relationship like \( Y_i = +regression analysis is to explain \( \boldsymbol{y} \) in terms of +\( \boldsymbol{X} \) through a functional relationship like \( y_i = f(\mathbf{X}_{i,\ast}) \). When no prior knowledge on the form of \( f(\cdot) \) is available, it is common to assume a linear relationship -between \( \mathbf{X} \) and \( \mathbf{Y} \). This assumption gives rise to -the linear regression model where \( \beta = (\beta_1, \ldots, -\beta_p)^{\top} \) is the regression parameter. The parameter -\( \beta_j \), \( j=1, \ldots, p \), represents the effect size of covariate -\( j \) on the response. That is, for each unit change in covariate \( j \) -(while keeping the other covariates fixed) the observed change in the -response is equal to \( \beta_j \). +between \( \boldsymbol{X} \) and \( \boldsymbol{y} \). This assumption gives rise to +the linear regression model where \( \boldsymbol{\beta} = [\beta_0, \ldots, +\beta_{p-1}]^{T} \) are the regression parameters. + +

    +Linear regression gives us a set of analytical equations for the parameters \( \beta_j \).

    @@ -376,16 +378,45 @@ response is equal to \( \beta_j \).











    -

    General linear models

    +

    Examples

    -Before we proceed let us study a case from linear algebra where we aim at fitting a set of data \( \hat{y}=[y_0,y_1,\dots,y_{n-1}] \). We could think of these data as a result of an experiment or a complicated numerical experiment. These data are functions of a series of variables \( \hat{x}=[x_0,x_1,\dots,x_{n-1}] \), that is \( y_i = y(x_i) \) with \( i=0,1,2,\dots,n-1 \). The variables \( x_i \) could represent physical quantities like time, temperature, position etc. We assume that \( y(x) \) is a smooth function. +In order to understand the relation among the predictors \( p \), the set of data \( n \) and the target (outcome, output etc) \( \boldsymbol{y} \), +consider the model we discussed for describing nuclear binding energies. + +

    +There we assumed that we could parametrize the data using a polynomial approximation based on the liquid drop model. +Assuming +$$ +BE(A) = a_0+a_1A+a_2A^{2/3}+a_3A^{-1/3}+a_4A^{-1}, +$$ + +we have five predictors, that is the intercept, the \( A \) dependent term, the \( A^{2/3} \) term and the \( A^{-1/3} \) and \( A^{-1} \) terms. +This gives \( p=0,1,2,3,4 \). Furthermore we have \( n \) entries for each predictor. It means that our design matrix is a +\( p\times n \) matrix \( \boldsymbol{X} \). + +

    +Here the predictors are based on a model we have made. A popular data set which is widely encountered in ML applications is the +so-called credit card default data from Taiwan. The data set contains data on \( n=30000 \) credit card holders with predictors like gender, marital status, age, profession, education, etc. In total there are \( 24 \) such predictors or attributes leading to a design matrix of dimensionality \( 24 \times 30000 \) + + +

    + + +

    +









    + +

    General linear models

    +
    + +

    +Before we proceed let us study a case from linear algebra where we aim at fitting a set of data \( \boldsymbol{y}=[y_0,y_1,\dots,y_{n-1}] \). We could think of these data as a result of an experiment or a complicated numerical experiment. These data are functions of a series of variables \( \boldsymbol{x}=[x_0,x_1,\dots,x_{n-1}] \), that is \( y_i = y(x_i) \) with \( i=0,1,2,\dots,n-1 \). The variables \( x_i \) could represent physical quantities like time, temperature, position etc. We assume that \( y(x) \) is a smooth function.

    Since obtaining these data points may not be trivial, we want to use these data to fit a function which can allow us to make predictions for values of \( y \) which are not in the present set. The perhaps simplest approach is to assume we can parametrize our function in terms of a polynomial of degree \( n-1 \) with \( n \) points, that is $$ -y=y(x) \rightarrow y(x_i)=\tilde{y}_i+\epsilon_i=\sum_{j=0}^{n-1} \beta_i x_i^j+\epsilon_i, +y=y(x) \rightarrow y(x_i)=\tilde{y}_i+\epsilon_i=\sum_{j=0}^{n-1} \beta_j x_i^j+\epsilon_i, $$ where \( \epsilon_i \) is the error in our approximation. @@ -397,7 +428,7 @@ where \( \epsilon_i \) is the error in our approximation.











    -

    Rewriting the fitting procedure as a linear algebra problem

    +

    Rewriting the fitting procedure as a linear algebra problem

    @@ -408,7 +439,7 @@ y_0&=\beta_0+\beta_1x_0^1+\beta_2x_0^2+\dots+\beta_{n-1}x_0^{n-1}+\epsilon_0\\ y_1&=\beta_0+\beta_1x_1^1+\beta_2x_1^2+\dots+\beta_{n-1}x_1^{n-1}+\epsilon_1\\ y_2&=\beta_0+\beta_1x_2^1+\beta_2x_2^2+\dots+\beta_{n-1}x_2^{n-1}+\epsilon_2\\ \dots & \dots \\ -y_{n-1}&=\beta_0+\beta_1x_{n-1}^1+\beta_2x_{n-1}^2+\dots+\beta_1x_{n-1}^{n-1}+\epsilon_{n-1}.\\ +y_{n-1}&=\beta_0+\beta_1x_{n-1}^1+\beta_2x_{n-1}^2+\dots+\beta_{n-1}x_{n-1}^{n-1}+\epsilon_{n-1}.\\ \end{align*} $$

    @@ -417,28 +448,28 @@ $$











    -

    Rewriting the fitting procedure as a linear algebra problem, follows

    +

    Rewriting the fitting procedure as a linear algebra problem, more details

    Defining the vectors $$ -\hat{y} = [y_0,y_1, y_2,\dots, y_{n-1}]^T, +\boldsymbol{y} = [y_0,y_1, y_2,\dots, y_{n-1}]^T, $$ and $$ -\hat{\beta} = [\beta_0,\beta_1, \beta_2,\dots, \beta_{n-1}]^T, +\boldsymbol{\beta} = [\beta_0,\beta_1, \beta_2,\dots, \beta_{n-1}]^T, $$ and $$ -\hat{\epsilon} = [\epsilon_0,\epsilon_1, \epsilon_2,\dots, \epsilon_{n-1}]^T, +\boldsymbol{\epsilon} = [\epsilon_0,\epsilon_1, \epsilon_2,\dots, \epsilon_{n-1}]^T, $$ -and the matrix +and the design matrix $$ -\hat{X}= +\boldsymbol{X}= \begin{bmatrix} 1& x_{0}^1 &x_{0}^2& \dots & \dots &x_{0}^{n-1}\\ 1& x_{1}^1 &x_{1}^2& \dots & \dots &x_{1}^{n-1}\\ @@ -450,20 +481,28 @@ $$ we can rewrite our equations as $$ -\hat{y} = \hat{X}\hat{\beta}+\hat{\epsilon}. +\boldsymbol{y} = \boldsymbol{X}\boldsymbol{\beta}+\boldsymbol{\epsilon}. $$ + +The above design matrix is called a Vandermonde matrix.











    -

    Generalizing the fitting procedure as a linear algebra problem

    +

    Generalizing the fitting procedure as a linear algebra problem

    -We are obviously not limited to the above polynomial. We could replace the various powers of \( x \) with elements of Fourier series, that is, instead of \( x_i^j \) we could have \( \cos{(j x_i)} \) or \( \sin{(j x_i)} \), or time series or other orthogonal functions. -For every set of values \( y_i,x_i \) we can then generalize the equations to + +

    +We are obviously not limited to the above polynomial expansions. We +could replace the various powers of \( x \) with elements of Fourier +series or instead of \( x_i^j \) we could have \( \cos{(j x_i)} \) or \( \sin{(j +x_i)} \), or time series or other orthogonal functions. For every set +of values \( y_i,x_i \) we can then generalize the equations to + $$ \begin{align*} y_0&=\beta_0x_{00}+\beta_1x_{01}+\beta_2x_{02}+\dots+\beta_{n-1}x_{0n-1}+\epsilon_0\\ @@ -472,22 +511,25 @@ y_2&=\beta_0x_{20}+\beta_1x_{21}+\beta_2x_{22}+\dots+\beta_{n-1}x_{2n-1}+\epsilo \dots & \dots \\ y_{i}&=\beta_0x_{i0}+\beta_1x_{i1}+\beta_2x_{i2}+\dots+\beta_{n-1}x_{in-1}+\epsilon_i\\ \dots & \dots \\ -y_{n-1}&=\beta_0x_{n-1,0}+\beta_1x_{n-1,2}+\beta_2x_{n-1,2}+\dots+\beta_1x_{n-1,n-1}+\epsilon_{n-1}.\\ +y_{n-1}&=\beta_0x_{n-1,0}+\beta_1x_{n-1,2}+\beta_2x_{n-1,2}+\dots+\beta_{n-1}x_{n-1,n-1}+\epsilon_{n-1}.\\ \end{align*} $$ + +

    +Note that we have \( p=n \) here. The matrix is symmetric. This is generally not the case!











    -

    Generalizing the fitting procedure as a linear algebra problem

    +

    Generalizing the fitting procedure as a linear algebra problem

    -We redefine in turn the matrix \( \hat{X} \) as +We redefine in turn the matrix \( \boldsymbol{X} \) as $$ -\hat{X}= +\boldsymbol{X}= \begin{bmatrix} x_{00}& x_{01} &x_{02}& \dots & \dots &x_{0,n-1}\\ x_{10}& x_{11} &x_{12}& \dots & \dots &x_{1,n-1}\\ @@ -499,21 +541,21 @@ $$ and without loss of generality we rewrite again our equations as $$ -\hat{y} = \hat{X}\hat{\beta}+\hat{\epsilon}. +\boldsymbol{y} = \boldsymbol{X}\boldsymbol{\beta}+\boldsymbol{\epsilon}. $$ -The left-hand side of this equation forms know. Our error vector \( \hat{\epsilon} \) and the parameter vector \( \hat{\beta} \) are our unknow quantities. How can we obtain the optimal set of \( \beta_i \) values? +The left-hand side of this equation is kwown. Our error vector \( \boldsymbol{\epsilon} \) and the parameter vector \( \boldsymbol{\beta} \) are our unknow quantities. How can we obtain the optimal set of \( \beta_i \) values?











    -

    Optimizing our parameters

    +

    Optimizing our parameters

    -We have defined the matrix \( \hat{X} \) +We have defined the matrix \( \boldsymbol{X} \) via the equations $$ \begin{align*} y_0&=\beta_0x_{00}+\beta_1x_{01}+\beta_2x_{02}+\dots+\beta_{n-1}x_{0n-1}+\epsilon_0\\ @@ -522,69 +564,196 @@ y_2&=\beta_0x_{20}+\beta_1x_{21}+\beta_2x_{22}+\dots+\beta_{n-1}x_{2n-1}+\epsilo \dots & \dots \\ y_{i}&=\beta_0x_{i0}+\beta_1x_{i1}+\beta_2x_{i2}+\dots+\beta_{n-1}x_{in-1}+\epsilon_1\\ \dots & \dots \\ -y_{n-1}&=\beta_0x_{n-1,0}+\beta_1x_{n-1,2}+\beta_2x_{n-1,2}+\dots+\beta_1x_{n-1,n-1}+\epsilon_{n-1}.\\ +y_{n-1}&=\beta_0x_{n-1,0}+\beta_1x_{n-1,2}+\beta_2x_{n-1,2}+\dots+\beta_{n-1}x_{n-1,n-1}+\epsilon_{n-1}.\\ \end{align*} $$ + +

    +As we noted above, we stayed with a system with the design matrix + \( \boldsymbol{X}\in {\mathbb{R}}^{n\times n} \), that is we have \( p=n \). For reasons to come later (algorithmic arguments) we will hereafter define +our matrix as \( \boldsymbol{X}\in {\mathbb{R}}^{n\times p} \), with the predictors refering to the column numbers and the entries \( n \) being the row elements. + +











    -

    Optimizing our parameters, more details

    +

    Our model for the nuclear binding energies

    + +

    +In our introductory notes we looked at the so-called liguid drop model. Let us remind ourselves about what we did by looking at the code. + +

    +We restate the parts of the code we are most interested in. +

    + + +

    # Common imports
    +import numpy as np
    +import pandas as pd
    +import matplotlib.pyplot as plt
    +from IPython.display import display
    +import os
    +
    +# Where to save the figures and data files
    +PROJECT_ROOT_DIR = "Results"
    +FIGURE_ID = "Results/FigureFiles"
    +DATA_ID = "DataFiles/"
    +
    +if not os.path.exists(PROJECT_ROOT_DIR):
    +    os.mkdir(PROJECT_ROOT_DIR)
    +
    +if not os.path.exists(FIGURE_ID):
    +    os.makedirs(FIGURE_ID)
    +
    +if not os.path.exists(DATA_ID):
    +    os.makedirs(DATA_ID)
    +
    +def image_path(fig_id):
    +    return os.path.join(FIGURE_ID, fig_id)
    +
    +def data_path(dat_id):
    +    return os.path.join(DATA_ID, dat_id)
    +
    +def save_fig(fig_id):
    +    plt.savefig(image_path(fig_id) + ".png", format='png')
    +
    +infile = open(data_path("MassEval2016.dat"),'r')
    +
    +
    +# Read the experimental data with Pandas
    +Masses = pd.read_fwf(infile, usecols=(2,3,4,6,11),
    +              names=('N', 'Z', 'A', 'Element', 'Ebinding'),
    +              widths=(1,3,5,5,5,1,3,4,1,13,11,11,9,1,2,11,9,1,3,1,12,11,1),
    +              header=39,
    +              index_col=False)
    +
    +# Extrapolated values are indicated by '#' in place of the decimal place, so
    +# the Ebinding column won't be numeric. Coerce to float and drop these entries.
    +Masses['Ebinding'] = pd.to_numeric(Masses['Ebinding'], errors='coerce')
    +Masses = Masses.dropna()
    +# Convert from keV to MeV.
    +Masses['Ebinding'] /= 1000
    +
    +# Group the DataFrame by nucleon number, A.
    +Masses = Masses.groupby('A')
    +# Find the rows of the grouped DataFrame with the maximum binding energy.
    +Masses = Masses.apply(lambda t: t[t.Ebinding==t.Ebinding.max()])
    +A = Masses['A']
    +Z = Masses['Z']
    +N = Masses['N']
    +Element = Masses['Element']
    +Energies = Masses['Ebinding']
    +
    +# Now we set up the design matrix X
    +X = np.zeros((len(A),5))
    +X[:,0] = 1
    +X[:,1] = A
    +X[:,2] = A**(2.0/3.0)
    +X[:,3] = A**(-1.0/3.0)
    +X[:,4] = A**(-1.0)
    +# Then nice printout using pandas
    +DesignMatrix = pd.DataFrame(X)
    +DesignMatrix.index = A
    +DesignMatrix.columns = ['1', 'A', 'A^(2/3)', 'A^(-1/3)', '1/A']
    +display(DesignMatrix)
    +
    +

    +With \( \boldsymbol{\beta}\in {\mathbb{R}}^{p\times 1} \), it means that we will hereafter write our equations for the approximation as +$$ +\boldsymbol{\tilde{y}}= \boldsymbol{X}\boldsymbol{\beta}, +$$ + +throughout these lectures. + +

    +









    + +

    Optimizing our parameters, more details

    -We well use this matrix to define the approximation \( \hat{\tilde{y}} \) via the unknown quantity \( \hat{\beta} \) as +With the above we use the design matrix to define the approximation \( \boldsymbol{\tilde{y}} \) via the unknown quantity \( \boldsymbol{\beta} \) as $$ -\hat{\tilde{y}}= \hat{X}\hat{\beta}, +\boldsymbol{\tilde{y}}= \boldsymbol{X}\boldsymbol{\beta}, $$ -and in order to find the optimal parameters \( \beta_i \) instead of solving the above linear algebra problem, we define a function which gives a measure of the spread between the values \( y_i \) (which represent hopefully the exact values) and the parametrized values \( \tilde{y}_i \), namely +and in order to find the optimal parameters \( \beta_i \) instead of solving the above linear algebra problem, we define a function which gives a measure of the spread between the values \( y_i \) (which represent hopefully the exact values) and the parameterized values \( \tilde{y}_i \), namely $$ -Q(\hat{\beta})=\sum_{i=0}^{n-1}\left(y_i-\tilde{y}_i\right)^2=\left(\hat{y}-\hat{\tilde{y}}\right)^T\left(\hat{y}-\hat{\tilde{y}}\right), +C(\boldsymbol{\beta})=\frac{1}{n}\sum_{i=0}^{n-1}\left(y_i-\tilde{y}_i\right)^2=\frac{1}{n}\left\{\left(\boldsymbol{y}-\boldsymbol{\tilde{y}}\right)^T\left(\boldsymbol{y}-\boldsymbol{\tilde{y}}\right)\right\}, $$ -or using the matrix \( \hat{X} \) as +or using the matrix \( \boldsymbol{X} \) and in a more compact matrix-vector notation as $$ -Q(\hat{\beta})=\left(\hat{y}-\hat{X}\hat{\beta}\right)^T\left(\hat{y}-\hat{X}\hat{\beta}\right). +C(\boldsymbol{\beta})=\frac{1}{n}\left\{\left(\boldsymbol{y}-\boldsymbol{X}^T\boldsymbol{\beta}\right)^T\left(\boldsymbol{y}-\boldsymbol{X}^T\boldsymbol{\beta}\right)\right\}. $$ + +This function is one possible way to define the so-called cost function. + +

    +It is also common to define +the function \( Q \) as + +$$ +C(\boldsymbol{\beta})=\frac{1}{2n}\sum_{i=0}^{n-1}\left(y_i-\tilde{y}_i\right)^2, +$$ + +since when taking the first derivative with respect to the unknown parameters \( \beta \), the factor of \( 2 \) cancels out.











    -

    Interpretations and optimizing our parameters

    +

    Interpretations and optimizing our parameters

    +

    +

    The function $$ -Q(\hat{\beta})=\left(\hat{y}-\hat{X}\hat{\beta}\right)^T\left(\hat{y}-\hat{X}\hat{\beta}\right), +C(\boldsymbol{\beta})=\frac{1}{n}\left\{\left(\boldsymbol{y}-\boldsymbol{X}\boldsymbol{\beta}\right)^T\left(\boldsymbol{y}-\boldsymbol{X}\boldsymbol{\beta}\right)\right\}, $$ -can be linked to the variance of the quantity \( y_i \) if we interpret the latter as the mean value of for example a numerical experiment. When linking below with the maximum likelihood approach below, we will indeed interpret \( y_i \) as a mean value +can be linked to the variance of the quantity \( y_i \) if we interpret the latter as the mean value. +When linking below with the maximum likelihood approach below, we will indeed interpret \( y_i \) as a mean value (see exercises) $$ y_{i}=\langle y_i \rangle = \beta_0x_{i,0}+\beta_1x_{i,1}+\beta_2x_{i,2}+\dots+\beta_{n-1}x_{i,n-1}+\epsilon_i, $$ -where \( \langle y_i \rangle \) is the mean value. Keep in mind also that till now we have treated \( y_i \) as the exact value. Normally, the response (dependent or outcome) variable \( y_i \) the outcome of a numerical experiment or another type of experiment and is thus only an approximation to the true value. It is then always accompanied by an error estimate, often limited to a statistical error estimate given by the standard deviation discussed earlier. In the discussion here we will treat \( y_i \) as our exact value for the response variable. +

    +where \( \langle y_i \rangle \) is the mean value. Keep in mind also that +till now we have treated \( y_i \) as the exact value. Normally, the +response (dependent or outcome) variable \( y_i \) the outcome of a +numerical experiment or another type of experiment and is thus only an +approximation to the true value. It is then always accompanied by an +error estimate, often limited to a statistical error estimate given by +the standard deviation discussed earlier. In the discussion here we +will treat \( y_i \) as our exact value for the response variable.

    -In order to find the parameters \( \beta_i \) we will then minimize the spread of \( Q(\hat{\beta}) \) by requiring +In order to find the parameters \( \beta_i \) we will then minimize the spread of \( C(\boldsymbol{\beta}) \), that is we are going to solve the problem $$ -\frac{\partial Q(\hat{\beta})}{\partial \beta_j} = \frac{\partial }{\partial \beta_j}\left[ \sum_{i=0}^{n-1}\left(y_i-\beta_0x_{i,0}-\beta_1x_{i,1}-\beta_2x_{i,2}-\dots-\beta_{n-1}x_{i,n-1}\right)^2\right]=0, +{\displaystyle \min_{\boldsymbol{\beta}\in +{\mathbb{R}}^{p}}}\frac{1}{n}\left\{\left(\boldsymbol{y}-\boldsymbol{X}\boldsymbol{\beta}\right)^T\left(\boldsymbol{y}-\boldsymbol{X}\boldsymbol{\beta}\right)\right\}. +$$ + +In practical terms it means we will require +$$ +\frac{\partial C(\boldsymbol{\beta})}{\partial \beta_j} = \frac{\partial }{\partial \beta_j}\left[ \frac{1}{n}\sum_{i=0}^{n-1}\left(y_i-\beta_0x_{i,0}-\beta_1x_{i,1}-\beta_2x_{i,2}-\dots-\beta_{n-1}x_{i,n-1}\right)^2\right]=0, $$ which results in $$ -\frac{\partial Q(\hat{\beta})}{\partial \beta_j} = -2\left[ \sum_{i=0}^{n-1}x_{ij}\left(y_i-\beta_0x_{i,0}-\beta_1x_{i,1}-\beta_2x_{i,2}-\dots-\beta_{n-1}x_{i,n-1}\right)\right]=0, +\frac{\partial C(\boldsymbol{\beta})}{\partial \beta_j} = -\frac{2}{n}\left[ \sum_{i=0}^{n-1}x_{ij}\left(y_i-\beta_0x_{i,0}-\beta_1x_{i,1}-\beta_2x_{i,2}-\dots-\beta_{n-1}x_{i,n-1}\right)\right]=0, $$ or in a matrix-vector form as $$ -\frac{\partial Q(\hat{\beta})}{\partial \hat{\beta}} = 0 = \hat{X}^T\left( \hat{y}-\hat{X}\hat{\beta}\right). +\frac{\partial C(\boldsymbol{\beta})}{\partial \boldsymbol{\beta}} = 0 = \boldsymbol{X}^T\left( \boldsymbol{y}-\boldsymbol{X}\boldsymbol{\beta}\right). $$ @@ -594,25 +763,37 @@ $$











    -

    Interpretations and optimizing our parameters

    +

    Interpretations and optimizing our parameters

    We can rewrite $$ -\frac{\partial Q(\hat{\beta})}{\partial \hat{\beta}} = 0 = \hat{X}^T\left( \hat{y}-\hat{X}\hat{\beta}\right), +\frac{\partial C(\boldsymbol{\beta})}{\partial \boldsymbol{\beta}} = 0 = \boldsymbol{X}^T\left( \boldsymbol{y}-\boldsymbol{X}\boldsymbol{\beta}\right), $$ as $$ -\hat{X}^T\hat{y} = \hat{X}^T\hat{X}\hat{\beta}, +\boldsymbol{X}^T\boldsymbol{y} = \boldsymbol{X}^T\boldsymbol{X}\boldsymbol{\beta}, $$ -and if the matrix \( \hat{X}^T\hat{X} \) is invertible we have the solution +and if the matrix \( \boldsymbol{X}^T\boldsymbol{X} \) is invertible we have the solution $$ -\hat{\beta} =\left(\hat{X}^T\hat{X}\right)^{-1}\hat{X}^T\hat{y}. +\boldsymbol{\beta} =\left(\boldsymbol{X}^T\boldsymbol{X}\right)^{-1}\boldsymbol{X}^T\boldsymbol{y}. $$ +

    +We note also that since our design matrix is defined as \( \boldsymbol{X}\in +{\mathbb{R}}^{n\times p} \), the product \( \boldsymbol{X}^T\boldsymbol{X} \in +{\mathbb{R}}^{p\times p} \). In the above case we have that \( p \ll n \), +in our case \( p=5 \) meaning that we end up with inverting a small +\( 5\times 5 \) matrix. This is a rather common situation, in many cases we end up with low-dimensional +matrices to invert. The methods discussed here and for many other +supervised learning algorithms like classification with logistic +regression or support vector machines, exhibit dimensionalities which +allow for the usage of direct linear algebra methods such as LU decomposition or Singular Value Decomposition (SVD) for finding the inverse of the matrix +\( \boldsymbol{X}^T\boldsymbol{X} \). +

    @@ -620,26 +801,144 @@ $$











    -

    Interpretations and optimizing our parameters

    +

    Interpretations and optimizing our parameters

    -The residuals \( \hat{\epsilon} \) are in turn given by +The residuals \( \boldsymbol{\epsilon} \) are in turn given by $$ -\hat{\epsilon} = \hat{y}-\hat{\tilde{y}} = \hat{y}-\hat{X}\hat{\beta}, +\boldsymbol{\epsilon} = \boldsymbol{y}-\boldsymbol{\tilde{y}} = \boldsymbol{y}-\boldsymbol{X}\boldsymbol{\beta}, $$ and with $$ -\hat{X}^T\left( \hat{y}-\hat{X}\hat{\beta}\right)= 0, +\boldsymbol{X}^T\left( \boldsymbol{y}-\boldsymbol{X}\boldsymbol{\beta}\right)= 0, $$ we have $$ -\hat{X}^T\hat{\epsilon}=\hat{X}^T\left( \hat{y}-\hat{X}\hat{\beta}\right)= 0, +\boldsymbol{X}^T\boldsymbol{\epsilon}=\boldsymbol{X}^T\left( \boldsymbol{y}-\boldsymbol{X}\boldsymbol{\beta}\right)= 0, $$ -meaning that the solution for \( \hat{\beta} \) is the one which minimizes the residuals. Later we will link this with the maximum likelihood approach. +meaning that the solution for \( \boldsymbol{\beta} \) is the one which minimizes the residuals. Later we will link this with the maximum likelihood approach. + + +

    + + +

    +Let us now return to our nuclear binding energies and simply code the above equations. + +

    +









    + +

    Own code for Ordinary Least Squares

    + +

    +It is rather straightforward to implement the matrix inversion and obtain the parameters \( \boldsymbol{\beta} \). After having defined the matrix \( \boldsymbol{X} \) we simply need to +write +

    + + +

    # matrix inversion to find beta
    +beta = np.linalg.inv(X.T.dot(X)).dot(X.T).dot(Energies)
    +# and then make the prediction
    +ytilde = X @ beta
    +
    +

    +Alternatively, you can use the least squares functionality in Numpy as +

    + + +

    fit = np.linalg.lstsq(X, Energies, rcond =None)[0]
    +ytildenp = np.dot(fit,X.T)
    +
    +

    +And finally we plot our fit with and compare with data +

    + + +

    Masses['Eapprox']  = ytilde
    +# Generate a plot comparing the experimental with the fitted values values.
    +fig, ax = plt.subplots()
    +ax.set_xlabel(r'$A = N + Z$')
    +ax.set_ylabel(r'$E_\mathrm{bind}\,/\mathrm{MeV}$')
    +ax.plot(Masses['A'], Masses['Ebinding'], alpha=0.7, lw=2,
    +            label='Ame2016')
    +ax.plot(Masses['A'], Masses['Eapprox'], alpha=0.7, lw=2, c='m',
    +            label='Fit')
    +ax.legend()
    +save_fig("Masses2016OLS")
    +plt.show()
    +
    +

    +









    + +

    Adding error analysis and training set up

    + +

    +We can easily test our fit by computing the \( R2 \) score that we discussed in connection with the functionality of _Scikit_Learn_ in the introductory slides. +Since we are not using _Scikit-Learn here we can define our own \( R2 \) function as +

    + + +

    def R2(y_data, y_model):
    +    return 1 - np.sum((y_data - y_model) ** 2) / np.sum((y_data - np.mean(y_model)) ** 2)
    +
    +

    +and we would be using it as +

    + + +

    print(R2(Energies,ytilde))
    +
    +

    +We can easily add our MSE score as +

    + + +

    def MSE(y_data,y_model):
    +    n = np.size(y_model)
    +    return np.sum((y_data-y_model)**2)/n
    +
    +print(MSE(Energies,ytilde))
    +
    +

    +and finally the relative error as +

    + + +

    def RelativeError(y_data,y_model):
    +    return abs((y_data-y_model)/y_data)
    +print(RelativeError(Energies, ytilde))
    +
    +

    +









    + +

    The \( \chi^2 \) function

    +
    + +

    + +

    +Normally, the response (dependent or outcome) variable \( y_i \) is the +outcome of a numerical experiment or another type of experiment and is +thus only an approximation to the true value. It is then always +accompanied by an error estimate, often limited to a statistical error +estimate given by the standard deviation discussed earlier. In the +discussion here we will treat \( y_i \) as our exact value for the +response variable. + +

    +Introducing the standard deviation \( \sigma_i \) for each measurement +\( y_i \), we define now the \( \chi^2 \) function (omitting the \( 1/n \) term) +as + +$$ +\chi^2(\boldsymbol{\beta})=\frac{1}{n}\sum_{i=0}^{n-1}\frac{\left(y_i-\tilde{y}_i\right)^2}{\sigma_i^2}=\frac{1}{n}\left\{\left(\boldsymbol{y}-\boldsymbol{\tilde{y}}\right)^T\frac{1}{\boldsymbol{\Sigma^2}}\left(\boldsymbol{y}-\boldsymbol{\tilde{y}}\right)\right\}, +$$ + +where the matrix \( \boldsymbol{\Sigma} \) is a diagonal matrix with \( \sigma_i \) as matrix elements.

    @@ -648,58 +947,35 @@ meaning that the solution for \( \hat{\beta} \) is the one which minimizes the r











    -

    The \( \chi^2 \) function

    +

    The \( \chi^2 \) function

    -Normally, the response (dependent or outcome) variable \( y_i \) the outcome of a numerical experiment or another type of experiment and is thus only an approximation to the true value. It is then always accompanied by an error estimate, often limited to a statistical error estimate given by the standard deviation discussed earlier. In the discussion here we will treat \( y_i \) as our exact value for the response variable. - -

    -Introducing the standard deviation \( \sigma_i \) for each measurement \( y_i \), we define now the \( \chi^2 \) function as +In order to find the parameters \( \beta_i \) we will then minimize the spread of \( \chi^2(\boldsymbol{\beta}) \) by requiring $$ -\chi^2(\hat{\beta})=\sum_{i=0}^{n-1}\frac{\left(y_i-\tilde{y}_i\right)^2}{\sigma_i^2}=\left(\hat{y}-\hat{\tilde{y}}\right)^T\frac{1}{\hat{\Sigma^2}}\left(\hat{y}-\hat{\tilde{y}}\right), -$$ - -where the matrix \( \hat{\Sigma} \) is a diagonal matrix with \( \sigma_i \) as matrix elements. - - -

    - - -

    -









    - -

    The \( \chi^2 \) function

    -
    - -

    - -

    -In order to find the parameters \( \beta_i \) we will then minimize the spread of \( \chi^2(\hat{\beta}) \) by requiring -$$ -\frac{\partial \chi^2(\hat{\beta})}{\partial \beta_j} = \frac{\partial }{\partial \beta_j}\left[ \sum_{i=0}^{n-1}\left(\frac{y_i-\beta_0x_{i,0}-\beta_1x_{i,1}-\beta_2x_{i,2}-\dots-\beta_{n-1}x_{i,n-1}}{\sigma_i}\right)^2\right]=0, +\frac{\partial \chi^2(\boldsymbol{\beta})}{\partial \beta_j} = \frac{\partial }{\partial \beta_j}\left[ \frac{1}{n}\sum_{i=0}^{n-1}\left(\frac{y_i-\beta_0x_{i,0}-\beta_1x_{i,1}-\beta_2x_{i,2}-\dots-\beta_{n-1}x_{i,n-1}}{\sigma_i}\right)^2\right]=0, $$ which results in $$ -\frac{\partial \chi^2(\hat{\beta})}{\partial \beta_j} = -2\left[ \sum_{i=0}^{n-1}\frac{x_{ij}}{\sigma_i}\left(\frac{y_i-\beta_0x_{i,0}-\beta_1x_{i,1}-\beta_2x_{i,2}-\dots-\beta_{n-1}x_{i,n-1}}{\sigma_i}\right)\right]=0, +\frac{\partial \chi^2(\boldsymbol{\beta})}{\partial \beta_j} = -\frac{2}{n}\left[ \sum_{i=0}^{n-1}\frac{x_{ij}}{\sigma_i}\left(\frac{y_i-\beta_0x_{i,0}-\beta_1x_{i,1}-\beta_2x_{i,2}-\dots-\beta_{n-1}x_{i,n-1}}{\sigma_i}\right)\right]=0, $$ or in a matrix-vector form as $$ -\frac{\partial \chi^2(\hat{\beta})}{\partial \hat{\beta}} = 0 = \hat{A}^T\left( \hat{b}-\hat{A}\hat{\beta}\right). +\frac{\partial \chi^2(\boldsymbol{\beta})}{\partial \boldsymbol{\beta}} = 0 = \boldsymbol{A}^T\left( \boldsymbol{b}-\boldsymbol{A}\boldsymbol{\beta}\right). $$ -where we have defined the matrix \( \hat{A} =\hat{X}/\hat{\Sigma} \) with matrix elements \( a_{ij} = x_{ij}/\sigma_i \) and the vector \( \hat{b} \) with elements \( b_i = y_i/\sigma_i \). +where we have defined the matrix \( \boldsymbol{A} =\boldsymbol{X}/\boldsymbol{\Sigma} \) with matrix elements \( a_{ij} = x_{ij}/\sigma_i \) and the vector \( \boldsymbol{b} \) with elements \( b_i = y_i/\sigma_i \).











    -

    The \( \chi^2 \) function

    +

    The \( \chi^2 \) function

    @@ -707,17 +983,17 @@ where we have defined the matrix \( \hat{A} =\hat{X}/\hat{\Sigma} \) with matrix

    We can rewrite $$ -\frac{\partial \chi^2(\hat{\beta})}{\partial \hat{\beta}} = 0 = \hat{A}^T\left( \hat{b}-\hat{A}\hat{\beta}\right), +\frac{\partial \chi^2(\boldsymbol{\beta})}{\partial \boldsymbol{\beta}} = 0 = \boldsymbol{A}^T\left( \boldsymbol{b}-\boldsymbol{A}\boldsymbol{\beta}\right), $$ as $$ -\hat{A}^T\hat{b} = \hat{A}^T\hat{A}\hat{\beta}, +\boldsymbol{A}^T\boldsymbol{b} = \boldsymbol{A}^T\boldsymbol{A}\boldsymbol{\beta}, $$ -and if the matrix \( \hat{A}^T\hat{A} \) is invertible we have the solution +and if the matrix \( \boldsymbol{A}^T\boldsymbol{A} \) is invertible we have the solution $$ -\hat{\beta} =\left(\hat{A}^T\hat{A}\right)^{-1}\hat{A}^T\hat{b}. +\boldsymbol{\beta} =\left(\boldsymbol{A}^T\boldsymbol{A}\right)^{-1}\boldsymbol{A}^T\boldsymbol{b}. $$

    @@ -725,7 +1001,7 @@ $$











    -

    The \( \chi^2 \) function

    +

    The \( \chi^2 \) function

    @@ -733,10 +1009,10 @@ $$

    If we then introduce the matrix $$ -\hat{H} = \left(\hat{A}^T\hat{A}\right)^{-1}, +\boldsymbol{H} = \left(\boldsymbol{A}^T\boldsymbol{A}\right)^{-1}, $$ -we have then the following expression for the parameters \( \beta_j \) (the matrix elements of \( \hat{H} \) are \( h_{ij} \)) +we have then the following expression for the parameters \( \beta_j \) (the matrix elements of \( \boldsymbol{H} \) are \( h_{ij} \)) $$ \beta_j = \sum_{k=0}^{p-1}h_{jk}\sum_{i=0}^{n-1}\frac{y_i}{\sigma_i}\frac{x_{ik}}{\sigma_i} = \sum_{k=0}^{p-1}h_{jk}\sum_{i=0}^{n-1}b_ia_{ik} $$ @@ -756,7 +1032,7 @@ $$











    -

    The \( \chi^2 \) function

    +

    The \( \chi^2 \) function

    @@ -767,12 +1043,12 @@ $$ By computing the derivatives of \( \chi^2 \) with respect to \( \beta_0 \) and \( \beta_1 \) show that these are given by $$ -\frac{\partial \chi^2(\hat{\beta})}{\partial \beta_0} = -2\left[ \sum_{i=0}^{n-1}\left(\frac{y_i-\beta_0-\beta_1x_{i}}{\sigma_i^2}\right)\right]=0, +\frac{\partial \chi^2(\boldsymbol{\beta})}{\partial \beta_0} = -2\left[ \frac{1}{n}\sum_{i=0}^{n-1}\left(\frac{y_i-\beta_0-\beta_1x_{i}}{\sigma_i^2}\right)\right]=0, $$ and $$ -\frac{\partial \chi^2(\hat{\beta})}{\partial \beta_0} = -2\left[ \sum_{i=0}^{n-1}x_i\left(\frac{y_i-\beta_0-\beta_1x_{i}}{\sigma_i^2}\right)\right]=0. +\frac{\partial \chi^2(\boldsymbol{\beta})}{\partial \beta_1} = -\frac{2}{n}\left[ \sum_{i=0}^{n-1}x_i\left(\frac{y_i-\beta_0-\beta_1x_{i}}{\sigma_i^2}\right)\right]=0. $$

    @@ -780,13 +1056,13 @@ $$











    -

    The \( \chi^2 \) function

    +

    The \( \chi^2 \) function

    -For a linear fit we don't need to invert a matrix!! +For a linear fit (a first-order polynomial) we don't need to invert a matrix!! Defining $$ \gamma = \sum_{i=0}^{n-1}\frac{1}{\sigma_i^2}, @@ -797,570 +1073,539 @@ $$ \gamma_x = \sum_{i=0}^{n-1}\frac{x_{i}}{\sigma_i^2}, $$ + $$ \gamma_y = \sum_{i=0}^{n-1}\left(\frac{y_i}{\sigma_i^2}\right), $$ + $$ \gamma_{xx} = \sum_{i=0}^{n-1}\frac{x_ix_{i}}{\sigma_i^2}, $$ + $$ \gamma_{xy} = \sum_{i=0}^{n-1}\frac{y_ix_{i}}{\sigma_i^2}, $$ +

    we obtain + $$ \beta_0 = \frac{\gamma_{xx}\gamma_y-\gamma_x\gamma_y}{\gamma\gamma_{xx}-\gamma_x^2}, $$ + $$ \beta_1 = \frac{\gamma_{xy}\gamma-\gamma_x\gamma_y}{\gamma\gamma_{xx}-\gamma_x^2}. $$

    -This approach (different linear and non-linear regression) suffers often from both being underdetermined and overdetermined in the unknown coefficients \( \beta_i \). A better approach is to use the Singular Value Decomposition (SVD) method discussed below. Or using Lasso and Ridge regression. See below. +This approach (different linear and non-linear regression) suffers +often from both being underdetermined and overdetermined in the +unknown coefficients \( \beta_i \). A better approach is to use the +Singular Value Decomposition (SVD) method discussed below. Or using +Lasso and Ridge regression. See below. + +











    -

    Simple regression model

    -We are now ready to write our first program which aims at solving the above linear regression equations. We start with data we have produced ourselves, in this case normally distributed random numbers along the \( x \)-axis. These numbers define then the value of a function \( y(x)=4+3x+N(0,1) \). Thereafter we order the \( x \) values and employ our linear regression algorithm to set up the best fit. Here we find it useful to use the numpy function \( c\_ \) arrays where arrays are stacked along their last axis after being upgraded to at least two dimensions with ones post-pended to the shape. The following examples help in understanding what happens +

    Fitting an Equation of State for Dense Nuclear Matter

    + +

    +Before we continue, let us introduce yet another example. We are going to fit the +nuclear equation of state using results from many-body calculations. +The equation of state we have made available here, as function of +density, has been derived using modern nucleon-nucleon potentials with +the addition of three-body +forces. This +time the file is presented as a standard csv file. + +

    +The beginning of the Python code here is similar to what you have seen before, +with the same initializations and declarations. We use also pandas +again, rather extensively in order to organize our data. + +

    +The difference now is that we use Scikit-Learn's regression tools +instead of our own matrix inversion implementation. Furthermore, we +sneak in Ridge regression (to be discussed below) which includes a +hyperparameter \( \lambda \), also to be explained below. + +

    +









    + +

    The code

    +

    -

    import numpy as np
    -print(np.c_[np.array([1,2,3]), np.array([4,5,6])])
    -print(np.c_[np.array([[1,2,3]]), 0, 0, np.array([[4,5,6]])])
    -
    -

    - - -

    # Importing various packages
    -from random import random, seed
    +
    # Common imports
    +import os
     import numpy as np
    +import pandas as pd
     import matplotlib.pyplot as plt
    -
    -x = 2*np.random.rand(100,1)
    -y = 4+3*x+np.random.randn(100,1)
    -
    -xb = np.c_[np.ones((100,1)), x]
    -beta = np.linalg.inv(xb.T.dot(xb)).dot(xb.T).dot(y)
    -xnew = np.array([[0],[2]])
    -xbnew = np.c_[np.ones((2,1)), xnew]
    -ypredict = xbnew.dot(beta)
    -
    -plt.plot(xnew, ypredict, "r-")
    -plt.plot(x, y ,'ro')
    -plt.axis([0,2.0,0, 15.0])
    -plt.xlabel(r'$x$')
    -plt.ylabel(r'$y$')
    -plt.title(r'Linear Regression')
    -plt.show()
    -
    -

    -We see that, as expected, a linear fit gives a seemingly (from the graph) good representation of the data. - -

    -









    - -

    Simple regression model, now using scikit-learn

    - -

    -We can repeat the above algorithm using scikit-learn as follows -

    - - -

    # Importing various packages
    -from random import random, seed
    -import numpy as np
     import matplotlib.pyplot as plt
    -from sklearn.linear_model import LinearRegression
    +import sklearn.linear_model as skl
    +from sklearn.metrics import mean_squared_error, r2_score, mean_absolute_error
     
    -x = 2*np.random.rand(100,1)
    -y = 4+3*x+np.random.randn(100,1)
    -linreg = LinearRegression()
    -linreg.fit(x,y)
    -xnew = np.array([[0],[2]])
    -ypredict = linreg.predict(xnew)
    +# Where to save the figures and data files
    +PROJECT_ROOT_DIR = "Results"
    +FIGURE_ID = "Results/FigureFiles"
    +DATA_ID = "DataFiles/"
     
    -plt.plot(xnew, ypredict, "r-")
    -plt.plot(x, y ,'ro')
    -plt.axis([0,2.0,0, 15.0])
    -plt.xlabel(r'$x$')
    -plt.ylabel(r'$y$')
    -plt.title(r'Random numbers ')
    -plt.show()
    -
    -

    -









    +if not os.path.exists(PROJECT_ROOT_DIR): + os.mkdir(PROJECT_ROOT_DIR) -

    Simple linear regression model using scikit-learn

    +if not os.path.exists(FIGURE_ID): + os.makedirs(FIGURE_ID) -

    -We start with perhaps our simplest possible example, using scikit-learn to perform linear regression analysis on a data set produced by us. -What follows is a simple Python code where we have defined function \( y \) in terms of the variable \( x \). Both are defined as vectors of dimension \( 1\times 100 \). The entries to the vector \( \hat{x} \) are given by random numbers generated with a uniform distribution with entries \( x_i \in [0,1] \) (more about probability distribution functions later). These values are then used to define a function \( y(x) \) (tabulated again as a vector) with a linear dependence on \( x \) plus a random noise added via the normal distribution. +if not os.path.exists(DATA_ID): + os.makedirs(DATA_ID) -

    -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 \) +def image_path(fig_id): + return os.path.join(FIGURE_ID, fig_id) -$$ -y = 2x+N(0,1), -$$ +def data_path(dat_id): + return os.path.join(DATA_ID, dat_id) -

    -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. +def save_fig(fig_id): + plt.savefig(image_path(fig_id) + ".png", format='png') -

    -For plotting we use the Python package -matplotlib which produces publication -quality figures. Feel free to explore the extensive -gallery 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. +infile = open(data_path("EoS.csv"),'r') -

    -The Python code follows here. -

    +# Read the EoS data as csv file and organize the data into two arrays with density and energies +EoS = pd.read_csv(infile, names=('Density', 'Energy')) +EoS['Energy'] = pd.to_numeric(EoS['Energy'], errors='coerce') +EoS = EoS.dropna() +Energies = EoS['Energy'] +Density = EoS['Density'] +# The design matrix now as function of various polytrops +X = np.zeros((len(Density),4)) +X[:,3] = Density**(4.0/3.0) +X[:,2] = Density +X[:,1] = Density**(2.0/3.0) +X[:,0] = 1 - -

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

    -









    - -

    Simple linear regression model

    - -

    -This example serves several aims. It allows us to demonstrate several -aspects of data analysis and later machine learning algorithms. The -immediate visualization shows that our linear fit is not -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 - -$$ -y = 10x+0.01 \times N(0,1), -$$ - -

    -where \( x \) is defined as before. - -

    -









    - -

    Less noise

    - -

    -Does the fit look better? Indeed, by -reducing the role of the normal distribution we see immediately that -our linear prediction seemingly reproduces better the training -set. However, this testing 'by the eye' is obviouly not satisfactory in the -long run. Here we have only defined the training data and our model, and -have not discussed a more rigorous approach to the cost function. - -

    -









    - -

    How to study our fits

    - -

    -We need more rigorous criteria in defining whether we have succeeded or -not in modeling our training data. You will be surprised to see that -many scientists seldomly venture beyond this 'by the eye' approach. A -standard approach for the cost function is the so-called \( \chi^2 \) -function - -$$ \chi^2 = \frac{1}{n} -\sum_{i=0}^{n-1}\frac{(y_i-\tilde{y}_i)^2}{\sigma_i^2}, -$$ - -

    -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

    - -

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

    -









    - -

    Relative error

    - -

    -There are many ways to define the cost function. A simpler approach is to look at the relative difference between the training data and the predicted data, that is we define -the relative error as - -$$ -\epsilon_{\mathrm{relative}}= \frac{\vert \hat{y} -\hat{\tilde{y}}\vert}{\vert \hat{y}\vert}. -$$ - -We can modify easily the above Python code and plot the relative error instead -

    - - -

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

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

    -









    - -

    The richness of scikit-learn

    - -

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

    - - -

    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_)
    +# We use now Scikit-Learn's linear regressor and ridge regressor
    +# OLS part
    +clf = skl.LinearRegression().fit(X, Energies)
    +ytilde = clf.predict(X)
    +EoS['Eols']  = ytilde
     # The mean squared error                               
    -print("Mean squared error: %.2f" % mean_squared_error(y, ypredict))
    +print("Mean squared error: %.2f" % mean_squared_error(Energies, ytilde))
     # 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) )
    +print('Variance score: %.2f' % r2_score(Energies, ytilde))
     # 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 ')
    +print('Mean absolute error: %.2f' % mean_absolute_error(Energies, ytilde))
    +print(clf.coef_, clf.intercept_)
    +
    +# The Ridge regression with a hyperparameter lambda = 0.1
    +_lambda = 0.1
    +clf_ridge = skl.Ridge(alpha=_lambda).fit(X, Energies)
    +yridge = clf_ridge.predict(X)
    +EoS['Eridge']  = yridge
    +# The mean squared error                               
    +print("Mean squared error: %.2f" % mean_squared_error(Energies, yridge))
    +# Explained variance score: 1 is perfect prediction                                 
    +print('Variance score: %.2f' % r2_score(Energies, yridge))
    +# Mean absolute error                                                           
    +print('Mean absolute error: %.2f' % mean_absolute_error(Energies, yridge))
    +print(clf_ridge.coef_, clf_ridge.intercept_)
    +
    +fig, ax = plt.subplots()
    +ax.set_xlabel(r'$\rho[\mathrm{fm}^{-3}]$')
    +ax.set_ylabel(r'Energy per particle')
    +ax.plot(EoS['Density'], EoS['Energy'], alpha=0.7, lw=2,
    +            label='Theoretical data')
    +ax.plot(EoS['Density'], EoS['Eols'], alpha=0.7, lw=2, c='m',
    +            label='OLS')
    +ax.plot(EoS['Density'], EoS['Eridge'], alpha=0.7, lw=2, c='g',
    +            label='Ridge $\lambda = 0.1$')
    +ax.legend()
    +save_fig("EoSfitting")
     plt.show()
     

    -









    - -

    Functions in scikit-learn

    +The above simple polynomial in density \( \rho \) gives an excellent fit +to the data. Can you give an interpretation of the various powers of \( \rho \)?

    -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 -$$ MSE(\hat{y},\hat{\tilde{y}}) = \frac{1}{n} -\sum_{i=0}^{n-1}(y_i-\tilde{y}_i)^2, -$$ - -

    -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. +We note also that there is a small deviation between the +standard OLS and the Ridge regression at higher densities. We discuss this in more detail +below.











    -

    Other functions in scikit-learn

    +

    Splitting our Data in Training and Test data

    -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 -$$ -R^2(\hat{y}, \tilde{\hat{y}}) = 1 - \frac{\sum_{i=0}^{n - 1} (y_i - \tilde{y}_i)^2}{\sum_{i=0}^{n - 1} (y_i - \bar{y})^2}, -$$ - -where we have defined the mean value of \( \hat{y} \) as -$$ -\bar{y} = \frac{1}{n} \sum_{i=0}^{n - 1} y_i. -$$ - -

    -









    - -

    The mean absolute error and other functions in scikit-learn

    - -

    -Another quantity will meet again in our discussions of regression analysis is - mean absolute error (MAE), a risk metric corresponding to the expected value of the absolute error loss or what we call the \( l1 \)-norm loss. In our discussion above we presented the relative error. -The MAE is defined as follows -$$ -\text{MAE}(\hat{y}, \hat{\tilde{y}}) = \frac{1}{n} \sum_{i=0}^{n-1} \left| y_i - \tilde{y}_i \right|. -$$ - -Finally we present the -squared logarithmic (quadratic) error -$$ -\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, -$$ - -

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

    -









    - -

    Cubic polynomial in scikit-learn

    - -

    -We will discuss in more -detail these and other functions in the various lectures. We conclude this part with another example. Instead of -a linear \( x \)-dependence we study now a cubic polynomial and use the polynomial regression analysis tools of scikit-learn. -Add description of the various python commands. +It is normal in essentially all Machine Learning studies to split the +data in a training set and a test set (sometimes also an additional +validation set). Scikit-Learn has an own function for this. There +is no explicit recipe for how much data should be included as training +data and say test data. An accepted rule of thumb is to use +approximately \( 2/3 \) to \( 4/5 \) of the data as training data. We will +postpone a discussion of this splitting to the end of these notes and +our discussion of the so-called bias-variance tradeoff. Here we +limit ourselves to repeat the above equation of state fitting example +but now splitting the data into a training set and a test set.

    -

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

    -Using R, we can perform similar studies. - -

    -









    - -

    Polynomial Regression

    -

    - - -

    # Importing various packages
    -from math import exp, sqrt
    -from random import random, seed
    +
    import os
     import numpy as np
    +import pandas as pd
     import matplotlib.pyplot as plt
    +from sklearn.model_selection import train_test_split
    +# Where to save the figures and data files
    +PROJECT_ROOT_DIR = "Results"
    +FIGURE_ID = "Results/FigureFiles"
    +DATA_ID = "DataFiles/"
     
    -m = 100
    -x = 2*np.random.rand(m,1)+4.
    -y = 4+3*x*x+ +x-np.random.randn(m,1)
    +if not os.path.exists(PROJECT_ROOT_DIR):
    +    os.mkdir(PROJECT_ROOT_DIR)
     
    -xb = np.c_[np.ones((m,1)), x]
    -theta = np.linalg.inv(xb.T.dot(xb)).dot(xb.T).dot(y)
    -xnew = np.array([[0],[2]])
    -xbnew = np.c_[np.ones((2,1)), xnew]
    -ypredict = xbnew.dot(theta)
    +if not os.path.exists(FIGURE_ID):
    +    os.makedirs(FIGURE_ID)
     
    -plt.plot(xnew, ypredict, "r-")
    -plt.plot(x, y ,'ro')
    -plt.axis([0,2.0,0, 15.0])
    -plt.xlabel(r'$x$')
    -plt.ylabel(r'$y$')
    -plt.title(r'Random numbers ')
    -plt.show()
    +if not os.path.exists(DATA_ID):
    +    os.makedirs(DATA_ID)
    +
    +def image_path(fig_id):
    +    return os.path.join(FIGURE_ID, fig_id)
    +
    +def data_path(dat_id):
    +    return os.path.join(DATA_ID, dat_id)
    +
    +def save_fig(fig_id):
    +    plt.savefig(image_path(fig_id) + ".png", format='png')
    +
    +def R2(y_data, y_model):
    +    return 1 - np.sum((y_data - y_model) ** 2) / np.sum((y_data - np.mean(y_model)) ** 2)
    +def MSE(y_data,y_model):
    +    n = np.size(y_model)
    +    return np.sum((y_data-y_model)**2)/n
    +
    +infile = open(data_path("EoS.csv"),'r')
    +
    +# Read the EoS data as  csv file and organized into two arrays with density and energies
    +EoS = pd.read_csv(infile, names=('Density', 'Energy'))
    +EoS['Energy'] = pd.to_numeric(EoS['Energy'], errors='coerce')
    +EoS = EoS.dropna()
    +Energies = EoS['Energy']
    +Density = EoS['Density']
    +#  The design matrix now as function of various polytrops
    +X = np.zeros((len(Density),5))
    +X[:,0] = 1
    +X[:,1] = Density**(2.0/3.0)
    +X[:,2] = Density
    +X[:,3] = Density**(4.0/3.0)
    +X[:,4] = Density**(5.0/3.0)
    +# We split the data in test and training data
    +X_train, X_test, y_train, y_test = train_test_split(X, Energies, test_size=0.2)
    +# matrix inversion to find beta
    +beta = np.linalg.inv(X_train.T.dot(X_train)).dot(X_train.T).dot(y_train)
    +# and then make the prediction
    +ytilde = X_train @ beta
    +print("Training R2")
    +print(R2(y_train,ytilde))
    +print("Training MSE")
    +print(MSE(y_train,ytilde))
    +ypredict = X_test @ beta
    +print("Test R2")
    +print(R2(y_test,ypredict))
    +print("Test MSE")
    +print(MSE(y_test,ypredict))
     
    -

    - - -

    Linking the regression analysis with a statistical interpretation

    - -

    -Before we proceed, and to link with our discussions of Bayesian statistics to come, it is useful the derive the standard regression analysis equations using a statistical interpretation. This allows us also to derive quantities like the variance and other expectation values in a rather straightforward way. - -

    -It is assumed that \( \varepsilon_i -\sim \mathcal{N}(0, \sigma^2) \) and the \( \varepsilon_{i} \) are -independent, i.e.: -$$ -\begin{align*} -\mbox{Cov}(\varepsilon_{i_1}, -\varepsilon_{i_2}) & = \left\{ \begin{array}{lcc} \sigma^2 & \mbox{if} -& i_1 = i_2, \\ 0 & \mbox{if} & i_1 \not= i_2. \end{array} \right. -\end{align*} -$$ - -The randomness of \( \varepsilon_i \) implies that -\( \mathbf{Y}_i \) is also a random variable. In particular, -\( \mathbf{Y}_i \) is normally distributed, because \( \varepsilon_i \sim -\mathcal{N}(0, \sigma^2) \) and \( \mathbf{X}_{i,\ast} \, \beta \) is a -non-random scalar. To specify the parameters of the distribution of -\( \mathbf{Y}_i \) we need to calculate its first two moments. -











    -

    Expectation value and variance

    +

    The singular value decomposition

    -Its expectation equals: -$$ -\begin{align*} -\mathbb{E}(Y_i) & = -\mathbb{E}(\mathbf{X}_{i, \ast} \, \beta) + \mathbb{E}(\varepsilon_i) -\, \, \, = \, \, \, \mathbf{X}_{i, \ast} \, \beta, -\end{align*} -$$ - -while -its variance is -$$ -\begin{align*} \mbox{Var}(Y_i) & = \mathbb{E} \{ [Y_i -- \mathbb{E}(Y_i)]^2 \} \, \, \, = \, \, \, \mathbb{E} ( Y_i^2 ) - -[\mathbb{E}(Y_i)]^2 \\ & = \mathbb{E} [ ( \mathbf{X}_{i, \ast} \, -\beta + \varepsilon_i )^2] - ( \mathbf{X}_{i, \ast} \, \beta)^2 \\ & -= \mathbb{E} [ ( \mathbf{X}_{i, \ast} \, \beta)^2 + 2 \varepsilon_i -\mathbf{X}_{i, \ast} \, \beta + \varepsilon_i^2 ] - ( \mathbf{X}_{i, -\ast} \, \beta)^2 \\ & = ( \mathbf{X}_{i, \ast} \, \beta)^2 + 2 -\mathbb{E}(\varepsilon_i) \mathbf{X}_{i, \ast} \, \beta + -\mathbb{E}(\varepsilon_i^2 ) - ( \mathbf{X}_{i, \ast} \, \beta)^2 -\\ & = \mathbb{E}(\varepsilon_i^2 ) \, \, \, = \, \, \, -\mbox{Var}(\varepsilon_i) \, \, \, = \, \, \, \sigma^2. -\end{align*} -$$ - -Hence, \( Y_i \sim \mathcal{N}( \mathbf{X}_{i, \ast} \, \beta, \sigma^2) \). - -

    -









    - -

    The singular value decompostion

    -A general -\( m\times n \) matrix \( \hat{A} \) can be written in terms of a diagonal -matrix \( \hat{D} \) of dimensionality \( n\times n \) and two orthognal -matrices \( \hat{U} \) and \( \hat{V} \), where the first has dimensionality -\( m \times m \) and the last dimensionality \( n\times n \). -We have then -$$ -\hat{A} = \hat{U}\hat{D}\hat{V}^T -$$ +The examples we have looked at so far are cases where we normally can +invert the matrix \( \boldsymbol{X}^T\boldsymbol{X} \). Using a polynomial expansion as we +did both for the masses and the fitting of the equation of state, +leads to row vectors of the design matrix which are essentially +orthogonal due to the polynomial character of our model. This may +however not the be case in general and a standard matrix inversion +algorithm based on say LU decomposition may lead to singularities. We will see an example of this below when we try to fit +the coupling constant of the widely used Ising model. +There is however a way to partially circumvent this problem and also gain some insight about the ordinary least squares approach. + +

    +This is given by the Singular Value Decomposition algorithm, perhaps +the most powerful linear algebra algorithm. Let us look at a +different example where we may have problems with the standard matrix +inversion algorithm. Thereafter we dive into the math of the SVD. + +











    -

    From standard regression to Ridge regressions

    +

    The Ising model

    + +

    +The one-dimensional Ising model with nearest neighbor interaction, no +external field and a constant coupling constant \( J \) is given by + +$$ +\begin{align} + H = -J \sum_{k}^L s_k s_{k + 1}, +\label{_auto1} +\end{align} +$$ + +

    +where \( s_i \in \{-1, 1\} \) and \( s_{N + 1} = s_1 \). The number of spins +in the system is determined by \( L \). For the one-dimensional system +there is no phase transition. + +

    +We will look at a system of \( L = 40 \) spins with a coupling constant of +\( J = 1 \). To get enough training data we will generate 10000 states +with their respective energies. + +

    + + +

    import numpy as np
    +import matplotlib.pyplot as plt
    +from mpl_toolkits.axes_grid1 import make_axes_locatable
    +import seaborn as sns
    +import scipy.linalg as scl
    +from sklearn.model_selection import train_test_split
    +import tqdm
    +sns.set(color_codes=True)
    +cmap_args=dict(vmin=-1., vmax=1., cmap='seismic')
    +
    +L = 40
    +n = int(1e4)
    +
    +spins = np.random.choice([-1, 1], size=(n, L))
    +J = 1.0
    +
    +energies = np.zeros(n)
    +
    +for i in range(n):
    +    energies[i] = - J * np.dot(spins[i], np.roll(spins[i], 1))
    +
    +

    +Here we use ordinary least squares +regression to predict the energy for the nearest neighbor +one-dimensional Ising model on a ring, i.e., the endpoints wrap +around. We will use linear regression to fit a value for +the coupling constant to achieve this. + +

    +









    + +

    Reformulating the problem to suit regression

    + +

    +A more general form for the one-dimensional Ising model is + +$$ +\begin{align} + H = - \sum_j^L \sum_k^L s_j s_k J_{jk}. +\label{_auto2} +\end{align} +$$ + +

    +Here we allow for interactions beyond the nearest neighbors and a state dependent +coupling constant. This latter expression can be formulated as +a matrix-product +$$ +\begin{align} + \boldsymbol{H} = \boldsymbol{X} J, +\label{_auto3} +\end{align} +$$ + +

    +where \( X_{jk} = s_j s_k \) and \( J \) is a matrix which consists of the +elements \( -J_{jk} \). This form of writing the energy fits perfectly +with the form utilized in linear regression, that is + +$$ +\begin{align} + \boldsymbol{y} = \boldsymbol{X}\boldsymbol{\beta} + \boldsymbol{\epsilon}, +\label{_auto4} +\end{align} +$$ + +

    +We split the data in training and test data as discussed in the previous example + +

    + + +

    X = np.zeros((n, L ** 2))
    +for i in range(n):
    +    X[i] = np.outer(spins[i], spins[i]).ravel()
    +y = energies
    +X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2)
    +
    +

    +









    + +

    Linear regression

    + +

    +In the ordinary least squares method we choose the cost function + +$$ +\begin{align} + C(\boldsymbol{X}, \boldsymbol{\beta})= \frac{1}{n}\left\{(\boldsymbol{X}\boldsymbol{\beta} - \boldsymbol{y})^T(\boldsymbol{X}\boldsymbol{\beta} - \boldsymbol{y})\right\}. +\label{_auto5} +\end{align} +$$ + +

    +We then find the extremal point of \( C \) by taking the derivative with respect to \( \boldsymbol{\beta} \) as discussed above. +This yields the expression for \( \boldsymbol{\beta} \) to be + +$$ + \boldsymbol{\beta} = \frac{\boldsymbol{X}^T \boldsymbol{y}}{\boldsymbol{X}^T \boldsymbol{X}}, +$$ + +

    +which immediately imposes some requirements on \( \boldsymbol{X} \) as there must exist +an inverse of \( \boldsymbol{X}^T \boldsymbol{X} \). If the expression we are modeling contains an +intercept, i.e., a constant term, we must make sure that the +first column of \( \boldsymbol{X} \) consists of \( 1 \). We do this here + +

    + + +

    X_train_own = np.concatenate(
    +    (np.ones(len(X_train))[:, np.newaxis], X_train),
    +    axis=1
    +)
    +X_test_own = np.concatenate(
    +    (np.ones(len(X_test))[:, np.newaxis], X_test),
    +    axis=1
    +)
    +
    +

    + + +

    def ols_inv(x: np.ndarray, y: np.ndarray) -> np.ndarray:
    +    return scl.inv(x.T @ x) @ (x.T @ y)
    +beta = ols_inv(X_train_own, y_train)
    +
    +

    +









    + +

    Singular Value decomposition

    + +

    +Doing the inversion directly turns out to be a bad idea since the matrix +\( \boldsymbol{X}^T\boldsymbol{X} \) is singular. An alternative approach is to use the singular +value decomposition. Using the definition of the Moore-Penrose +pseudoinverse we can write the equation for \( \boldsymbol{\beta} \) as + +$$ + \boldsymbol{\beta} = \boldsymbol{X}^{+}\boldsymbol{y}, +$$ + +

    +where the pseudoinverse of \( \boldsymbol{X} \) is given by + +$$ + \boldsymbol{X}^{+} = \frac{\boldsymbol{X}^T}{\boldsymbol{X}^T\boldsymbol{X}}. +$$ + +

    +Using singular value decomposition we can decompose the matrix \( \boldsymbol{X} = \boldsymbol{U}\boldsymbol{\Sigma} \boldsymbol{V}^T \), +where \( \boldsymbol{U} \) and \( \boldsymbol{V} \) are orthogonal(unitary) matrices and \( \boldsymbol{\Sigma} \) contains the singular values (more details below). +where \( X^{+} = V\Sigma^{+} U^T \). This reduces the equation for +\( \omega \) to +$$ +\begin{align} + \boldsymbol{\beta} = \boldsymbol{V}\boldsymbol{\Sigma}^{+} \boldsymbol{U}^T \boldsymbol{y}. +\label{_auto6} +\end{align} +$$ + +

    +Note that solving this equation by actually doing the pseudoinverse +(which is what we will do) is not a good idea as this operation scales +as \( \mathcal{O}(n^3) \), where \( n \) is the number of elements in a +general matrix. Instead, doing \( QR \)-factorization and solving the +linear system as an equation would reduce this down to +\( \mathcal{O}(n^2) \) operations. + +

    + + +

    def ols_svd(x: np.ndarray, y: np.ndarray) -> np.ndarray:
    +    u, s, v = scl.svd(x)
    +    return v.T @ scl.pinv(scl.diagsvd(s, u.shape[0], v.shape[0])) @ u.T @ y
    +
    +

    + + +

    beta = ols_svd(X_train_own,y_train)
    +
    +

    +When extracting the \( J \)-matrix we need to make sure that we remove the intercept, as is done here + +

    + + +

    J = beta[1:].reshape(L, L)
    +
    +

    +A way of looking at the coefficients in \( J \) is to plot the matrices as images. + +

    + + +

    fig = plt.figure(figsize=(20, 14))
    +im = plt.imshow(J, **cmap_args)
    +plt.title("OLS", fontsize=18)
    +plt.xticks(fontsize=18)
    +plt.yticks(fontsize=18)
    +cb = fig.colorbar(im)
    +cb.ax.set_yticklabels(cb.ax.get_yticklabels(), fontsize=18)
    +plt.show()
    +
    +

    +It is interesting to note that OLS +considers both \( J_{j, j + 1} = -0.5 \) and \( J_{j, j - 1} = -0.5 \) as +valid matrix elements for \( J \). +In our discussion below on hyperparameters and Ridge and Lasso regression we will see that +this problem can be removed, partly and only with Lasso regression. + +

    +In this case our matrix inversion was actually possible. The obvious question now is what is the mathematics behind the SVD? + +

    +









    + +

    Linear Regression Problems

    One of the typical problems we encounter with linear regression, in particular -when the matrix \( \hat{X} \) (our so-called design matrix) is high-dimensional, -are problems with near singular or singular matrices. The column vectors of \( \hat{X} \) +when the matrix \( \boldsymbol{X} \) (our so-called design matrix) is high-dimensional, +are problems with near singular or singular matrices. The column vectors of \( \boldsymbol{X} \) may be linearly dependent, normally referred to as super-collinearity. This means that the matrix may be rank deficient and it is basically impossible to to model the data using linear regression. As an example, consider the matrix @@ -1380,7 +1625,7 @@ $$ $$

    -The columns of \( \hat{X} \) are linearly dependent. We se this easily since the +The columns of \( \boldsymbol{X} \) are linearly dependent. We see this easily since the the first column is the row-wise sum of the other two columns. The rank (more correct, the column rank) of a matrix is the dimension of the space spanned by the column vectors. Hence, the rank of \( \mathbf{X} \) is equal to the number @@ -1388,10 +1633,10 @@ of linearly independent columns. In this particular case the matrix has rank 2.

    Super-collinearity of an \( (n \times p) \)-dimensional design matrix \( \mathbf{X} \) implies -that the inverse of the matrix \( \hat{X}^T\hat{x} \) (the matrix we needto invert to solve the linear regression equations) is non-invertible. If we have a square matrix that does not have an inverse, we say this matrix singular. The example here demonstrates this +that the inverse of the matrix \( \boldsymbol{X}^T\boldsymbol{x} \) (the matrix we need to invert to solve the linear regression equations) is non-invertible. If we have a square matrix that does not have an inverse, we say this matrix singular. The example here demonstrates this $$ \begin{align*} -\hat{X} & = \left[ +\boldsymbol{X} & = \left[ \begin{array}{rr} 1 & -1 \\ @@ -1400,425 +1645,421 @@ $$ \end{align*} $$ -We see easily that \( \mbox{det}(\hat{X}) = x_{11} x_{22} - x_{12} x_{21} = 1 \times (-1) - 1 \times (-1) = 0 \). Hence, \( \mathbf{X} \) is singular and its inverse is undefined. -This is equivalent to saying that the matrix \( \hat{X} \) has at least an eigenvalue which is zero. +We see easily that \( \mbox{det}(\boldsymbol{X}) = x_{11} x_{22} - x_{12} x_{21} = 1 \times (-1) - 1 \times (-1) = 0 \). Hence, \( \mathbf{X} \) is singular and its inverse is undefined. +This is equivalent to saying that the matrix \( \boldsymbol{X} \) has at least an eigenvalue which is zero.











    -

    Fixing the singularity

    +

    Fixing the singularity

    -If our design matrix \( \hat{X} \) which enters the linear regression problem +If our design matrix \( \boldsymbol{X} \) which enters the linear regression problem $$ \begin{align} -\hat{\beta} & = (\hat{X}^{T} \hat{X})^{-1} \hat{X}^{T} \hat{y}, -\label{_auto1} +\boldsymbol{\beta} & = (\boldsymbol{X}^{T} \boldsymbol{X})^{-1} \boldsymbol{X}^{T} \boldsymbol{y}, +\label{_auto7} \end{align} $$ has linearly dependent column vectors, we will not be able to compute the inverse -of \( \hat{X}^T\hat{X} \) and we cannot find the parameters (estimators) \( \beta_i \). -The estimators are only well-defined if \( (\hat{X}^{T}\hat{X})^{-1} \) exits. -This is more likely to happen when the matrix \( \hat{X} \) is high-dimensional. In this case it is likely to encounter a situation where +of \( \boldsymbol{X}^T\boldsymbol{X} \) and we cannot find the parameters (estimators) \( \beta_i \). +The estimators are only well-defined if \( (\boldsymbol{X}^{T}\boldsymbol{X})^{-1} \) exits. +This is more likely to happen when the matrix \( \boldsymbol{X} \) is high-dimensional. In this case it is likely to encounter a situation where the regression parameters \( \beta_i \) cannot be estimated.

    -The ad hoc approach which was introduced in the 70s was simply to add a diagonal component to the matrix to invert, that is we change +A cheap ad hoc approach is simply to add a small diagonal component to the matrix to invert, that is we change $$ -\hat{X}^{T} \hat{X} \rightarrow \hat{X}^{T} \hat{X}+\lambda \hat{I}, +\boldsymbol{X}^{T} \boldsymbol{X} \rightarrow \boldsymbol{X}^{T} \boldsymbol{X}+\lambda \boldsymbol{I}, $$ -where \( \hat{I} \) is the identity matrix. +where \( \boldsymbol{I} \) is the identity matrix. When we discuss Ridge regression this is actually what we end up evaluating. The parameter \( \lambda \) is called a hyperparameter. More about this later.











    -

    Fitting vs. predicting when data is in the model class

    +

    Basic math of the SVD

    -We start by considering the case -\( f(x)=2x \). +From standard linear algebra we know that a square matrix \( \boldsymbol{X} \) can be diagonalized if and only it is +a so-called normal matrix, that is if \( \boldsymbol{X}\in {\mathbb{R}}^{n\times n} \) +we have \( \boldsymbol{X}\boldsymbol{X}^T=\boldsymbol{X}^T\boldsymbol{X} \) or if \( \boldsymbol{X}\in {\mathbb{C}}^{n\times n} \) we have \( \boldsymbol{X}\boldsymbol{X}^{\dagger}=\boldsymbol{X}^{\dagger}\boldsymbol{X} \). +The matrix has then a set of eigenpairs + +$$ +(\lambda_1,\boldsymbol{u}_1),\dots, (\lambda_n,\boldsymbol{u}_n), +$$ + +and the eigenvalues are given by the diagonal matrix +$$ +\boldsymbol{\Sigma}=\mathrm{Diag}(\lambda_1, \dots,\lambda_n). +$$ + +The matrix \( \boldsymbol{X} \) can be written in terms of an orthogonal/unitary transformation \( \boldsymbol{U} \) +$$ +\boldsymbol{X} = \boldsymbol{U}\boldsymbol{\Sigma}\boldsymbol{V}^T, +$$ + +with \( \boldsymbol{U}\boldsymbol{U}^T=\boldsymbol{I} \) or \( \boldsymbol{U}\boldsymbol{U}^{\dagger}=\boldsymbol{I} \).

    -Then the data is clearly generated by a model that is contained within -all three model classes we are using to make predictions (linear -models, third order polynomials, and tenth order polynomials). +Not all square matrices are diagonalizable. A matrix like the one discussed above +$$ +\boldsymbol{X} = \begin{bmatrix} +1& -1 \\ +1& -1\\ +\end{bmatrix} +$$ + +is not diagonalizable, it is a so-called defective matrix. It is easy to see that the condition +\( \boldsymbol{X}\boldsymbol{X}^T=\boldsymbol{X}^T\boldsymbol{X} \) is not fulfilled.

    -Run the code for the following cases: +









    + +

    The SVD, a Fantastic Algorithm

    + +

    +However, and this is the strength of the SVD algorithm, any general +matrix \( \boldsymbol{X} \) can be decomposed in terms of a diagonal matrix and +two orthogonal/unitary matrices. The Singular Value Decompostion +(SVD) theorem +states that a general \( m\times n \) matrix \( \boldsymbol{X} \) can be written in +terms of a diagonal matrix \( \boldsymbol{\Sigma} \) of dimensionality \( n\times n \) +and two orthognal matrices \( \boldsymbol{U} \) and \( \boldsymbol{V} \), where the first has +dimensionality \( m \times m \) and the last dimensionality \( n\times n \). +We have then + +$$ +\boldsymbol{X} = \boldsymbol{U}\boldsymbol{\Sigma}\boldsymbol{V}^T +$$ + +

    +As an example, the above defective matrix can be decomposed as + +$$ +\boldsymbol{X} = \frac{1}{\sqrt{2}}\begin{bmatrix} 1& 1 \\ 1& -1\\ \end{bmatrix} \begin{bmatrix} 2& 0 \\ 0& 0\\ \end{bmatrix} \frac{1}{\sqrt{2}}\begin{bmatrix} 1& -1 \\ 1& 1\\ \end{bmatrix}=\boldsymbol{U}\boldsymbol{\Sigma}\boldsymbol{V}^T, +$$ + +

    +with eigenvalues \( \sigma_1=2 \) and \( \sigma_2=0 \). +The SVD exits always! + +

    +









    + +

    Another Example

    + +

    +Consider the following matrix which can be SVD decomposed as + +$$ +\boldsymbol{X} = \frac{1}{15}\begin{bmatrix} 14 & 2\\ 4 & 22\\ 16 & 13\end{matrix}=\frac{1}{3}\begin{bmatrix} 1& 2 & 2 \\ 2& -1 & 1\\ 2 & 1& -2\end{bmatrix} \begin{bmatrix} 2& 0 \\ 0& 1\\ 0 & 0\end{bmatrix}\frac{1}{5}\begin{bmatrix} 3& 4 \\ 4& -3\end{bmatrix}=\boldsymbol{U}\boldsymbol{\Sigma}\boldsymbol{V}^T. +$$ + +

    +This is a \( 3\times 2 \) matrix which is decomposed in terms of a +\( 3\times 3 \) matrix \( \boldsymbol{U} \), and a \( 2\times 2 \) matrix \( \boldsymbol{V} \). It is easy to see +that \( \boldsymbol{U} \) and \( \boldsymbol{V} \) are orthogonal (how?). + +

    +And the SVD +decomposition (singular values) gives eigenvalues +\( \sigma_i\geq\sigma_{i+1} \) for all \( i \) and for dimensions larger than \( i=2 \), the +eigenvalues (singular values) are zero. + +

    +In the general case, where our design matrix \( \boldsymbol{X} \) has dimension +\( n\times p \), the matrix is thus decomposed into an \( n\times n \) +orthogonal matrix \( \boldsymbol{U} \), a \( p\times p \) orthogonal matrix \( \boldsymbol{V} \) +and a diagonal matrix \( \boldsymbol{\Sigma} \) with \( r=\mathrm{min}(n,p) \) +singular values \( \sigma_i\lg 0 \) on the main diagonal and zeros filling +the rest of the matrix. There are at most \( p \) singular values +assuming that \( n > p \). In our regression examples for the nuclear +masses and the equation of state this is indeed the case, while for +the Ising model we have \( p > n \). These are often cases that lead to +near singular or singular matrices. + +

    +The columns of \( \boldsymbol{U} \) are called the left singular vectors while the columns of \( \boldsymbol{V} \) are the right singular vectors. + +

    +









    + +

    Economy-size SVD

    + +

    +If we assume that \( n > p \), then our matrix \( \boldsymbol{U} \) has dimension \( n +\times n \). The last \( n-p \) columns of \( \boldsymbol{U} \) become however +irrelevant in our calculations since they are multiplied with the +zeros in \( \boldsymbol{\Sigma} \). + +

    +The economy-size decomposition removes extra rows or columns of zeros +from the diagonal matrix of singular values, \( \boldsymbol{\Sigma} \), along with the columns +in either \( \boldsymbol{U} \) or \( \boldsymbol{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 \( \boldsymbol{U} \) and \( \boldsymbol{\Sigma} \) has dimension \( p\times p \). +If \( p > n \), then only the first \( n \) columns of \( \boldsymbol{V} \) are computed and \( \boldsymbol{\Sigma} \) has dimension \( n\times n \). +The \( n=p \) case is obvious, we retain the full SVD. +In general the economy-size SVD leads to less FLOPS and still conserving the desired accuracy. + +

    +









    + +

    Mathematical Properties

    + +

    +There are several interesting mathematical properties which will be +relevant when we are going to discuss the differences between say +ordinary least squares (OLS) and Ridge regression. + +

    +We have from OLS that the parameters of the linear approximation are given by +$$ +\boldsymbol{\tilde{y}} = \boldsymbol{X}\boldsymbol{\beta} = \boldsymbol{X}\left(\boldsymbol{X}^T\boldsymbol{X}\right)^{-1}\boldsymbol{X}^T\boldsymbol{y}. +$$ + +

    +The matrix to invert can be rewritten in terms of our SVD decomposition as + +$$ +\boldsymbol{X}^T\boldsymbol{X} = \boldsymbol{V}\boldsymbol{\Sigma}^T\boldsymbol{U}^T\boldsymbol{U}\boldsymbol{\Sigma}\boldsymbol{V}^T. +$$ + +Using the orthogonality properties of \( \boldsymbol{U} \) we have + +$$ +\boldsymbol{X}^T\boldsymbol{X} = \boldsymbol{V}\boldsymbol{\Sigma}^T\boldsymbol{\Sigma}\boldsymbol{V}^T = \boldsymbol{V}\boldsymbol{D}\boldsymbol{V}^T, +$$ + +with \( \boldsymbol{D} \) being a diagonal matrix with values along the diagonal given by the singular values squared. + +

    +This means that +$$ +(\boldsymbol{X}^T\boldsymbol{X})\boldsymbol{V} = \boldsymbol{V}\boldsymbol{D}, +$$ + +that is the eigenvectors of \( (\boldsymbol{X}^T\boldsymbol{X}) \) are given by the columns of the right singular matrix of \( \boldsymbol{X} \) and the eigenvalues are the squared singular values. It is easy to show (show this) that +$$ +(\boldsymbol{X}\boldsymbol{X}^T)\boldsymbol{U} = \boldsymbol{U}\boldsymbol{D}, +$$ + +that is, the eigenvectors of \( (\boldsymbol{X}\boldsymbol{X})^T \) are the columns of the left singular matrix and the eigenvalues are the same. + +

    +Going back to our OLS equation we have +$$ +\boldsymbol{X}\boldsymbol{\beta} = \boldsymbol{X}\left(\boldsymbol{V}\boldsymbol{D}\boldsymbol{V}^T \right)^{-1}\boldsymbol{X}^T\boldsymbol{y}=\boldsymbol{U\Sigma V^T}\left(\boldsymbol{V}\boldsymbol{D}\boldsymbol{V}^T \right)^{-1}(\boldsymbol{U\Sigma V^T})^T\boldsymbol{y}=\boldsymbol{U}\boldsymbol{U}^T\boldsymbol{y}. +$$ + +We will come back to this expression when we discuss Ridge regression. + +

    +









    + +

    Ridge and LASSO Regression

    + +

    +Let us remind ourselves about the expression for the standard Mean Squared Error (MSE) which we used to define our cost function and the equations for the ordinary least squares (OLS) method, that is +our optimization problem is +$$ +{\displaystyle \min_{\boldsymbol{\beta}\in {\mathbb{R}}^{p}}}\frac{1}{n}\left\{\left(\boldsymbol{y}-\boldsymbol{X}\boldsymbol{\beta}\right)^T\left(\boldsymbol{y}-\boldsymbol{X}\boldsymbol{\beta}\right)\right\}. +$$ + +or we can state it as +$$ +{\displaystyle \min_{\boldsymbol{\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 \boldsymbol{y}-\boldsymbol{X}\boldsymbol{\beta}\vert\vert_2^2, +$$ + +where we have used the definition of a norm-2 vector, that is +$$ +\vert\vert \boldsymbol{x}\vert\vert_2 = \sqrt{\sum_i x_i^2}. +$$ + +

    +By minimizing the above equation with respect to the parameters +\( \boldsymbol{\beta} \) we could then obtain an analytical expression for the +parameters \( \boldsymbol{\beta} \). We can add a regularization parameter \( \lambda \) by +defining a new cost function to be optimized, that is + +$$ +{\displaystyle \min_{\boldsymbol{\beta}\in +{\mathbb{R}}^{p}}}\frac{1}{n}\vert\vert \boldsymbol{y}-\boldsymbol{X}\boldsymbol{\beta}\vert\vert_2^2+\lambda\vert\vert \boldsymbol{\beta}\vert\vert_2^2 +$$ + +

    +which leads to the Ridge regression minimization problem where we +require that \( \vert\vert \boldsymbol{\beta}\vert\vert_2^2\le t \), where \( t \) is +a finite number larger than zero. By defining + +$$ +C(\boldsymbol{X},\boldsymbol{\beta})=\frac{1}{n}\vert\vert \boldsymbol{y}-\boldsymbol{X}\boldsymbol{\beta}\vert\vert_2^2+\lambda\vert\vert \boldsymbol{\beta}\vert\vert_1, +$$ + +

    +we have a new optimization equation +$$ +{\displaystyle \min_{\boldsymbol{\beta}\in +{\mathbb{R}}^{p}}}\frac{1}{n}\vert\vert \boldsymbol{y}-\boldsymbol{X}\boldsymbol{\beta}\vert\vert_2^2+\lambda\vert\vert \boldsymbol{\beta}\vert\vert_1 +$$ + +which leads to Lasso regression. Lasso stands for least absolute shrinkage and selection operator. + +

    +Here we have defined the norm-1 as +$$ +\vert\vert \boldsymbol{x}\vert\vert_1 = \sum_i \vert x_i\vert. +$$ + +

    +









    + +

    More on Ridge Regression

    + +

    +Using the matrix-vector expression for Ridge regression, + +$$ +C(\boldsymbol{X},\boldsymbol{\beta})=\frac{1}{n}\left\{(\boldsymbol{y}-\boldsymbol{X}\boldsymbol{\beta})^T(\boldsymbol{y}-\boldsymbol{X}\boldsymbol{\beta})\right\}+\lambda\boldsymbol{\beta}^T\boldsymbol{\beta}, +$$ + +

    +by taking the derivatives with respect to \( \boldsymbol{\beta} \) we obtain then +a slightly modified matrix inversion problem which for finite values +of \( \lambda \) does not suffer from singularity problems. We obtain + +$$ +\boldsymbol{\beta}^{\mathrm{Ridge}} = \left(\boldsymbol{X}^T\boldsymbol{X}+\lambda\boldsymbol{I}\right)^{-1}\boldsymbol{X}^T\boldsymbol{y}, +$$ + +

    +with \( \boldsymbol{I} \) being a \( p\times p \) identity matrix with the constraint that + +$$ +\sum_{i=0}^{p-1} \beta_i^2 \leq t, +$$ + +

    +with \( t \) a finite positive number. + +

    +We see that Ridge regression is nothing but the standard +OLS with a modified diagonal term added to \( \boldsymbol{X}^T\boldsymbol{X} \). The +consequences, in particular for our discussion of the bias-variance +are rather interesting. + +

    +Furthermore, if we use the result above in terms of the SVD decomposition (our analysis was done for the OLS method), we had +$$ +(\boldsymbol{X}\boldsymbol{X}^T)\boldsymbol{U} = \boldsymbol{U}\boldsymbol{D}. +$$ + +

    +We can analyse the OLS solutions in terms of the eigenvectors (the columns) of the right singular value matrix \( \boldsymbol{U} \) as +$$ +\boldsymbol{X}\boldsymbol{\beta} = \boldsymbol{X}\left(\boldsymbol{V}\boldsymbol{D}\boldsymbol{V}^T \right)^{-1}\boldsymbol{X}^T\boldsymbol{y}=\boldsymbol{U\Sigma V^T}\left(\boldsymbol{V}\boldsymbol{D}\boldsymbol{V}^T \right)^{-1}(\boldsymbol{U\Sigma V^T})^T\boldsymbol{y}=\boldsymbol{U}\boldsymbol{U}^T\boldsymbol{y} +$$ + +

    +For Ridge regression this becomes + +$$ +\boldsymbol{X}\boldsymbol{\beta}^{\mathrm{Ridge}} = \boldsymbol{U\Sigma V^T}\left(\boldsymbol{V}\boldsymbol{D}\boldsymbol{V}^T+\lambda\boldsymbol{I} \right)^{-1}(\boldsymbol{U\Sigma V^T})^T\boldsymbol{y}=\sum_{j=0}^{p-1}\boldsymbol{u}_j\boldsymbol{u}_j^T\frac{\sigma_j^2}{\sigma_j^2+\lambda}\boldsymbol{y}, +$$ + +

    +with the vectors \( \boldsymbol{u}_j \) being the columns of \( \boldsymbol{U} \). + +

    +









    + +

    Interpreting the Ridge results

    + +

    +Since \( \lambda \geq 0 \), it means that compared to OLS, we have + +$$ +\frac{\sigma_j^2}{\sigma_j^2+\lambda} \leq 1. +$$ + +

    +Ridge regression finds the coordinates of \( \boldsymbol{y} \) with respect to the +orthonormal basis \( \boldsymbol{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 \( \boldsymbol{X}\boldsymbol{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. + +

    +









    + +

    More interpretations

    + +

    +For the sake of simplicity, let us assume that the design matrix is orthonormal, that is + +$$ +\boldsymbol{X}^T\boldsymbol{X}=(\boldsymbol{X}^T\boldsymbol{X})^{-1} =\boldsymbol{I}. +$$ + +

    +In this case the standard OLS results in +$$ +\boldsymbol{\beta}^{\mathrm{OLS}} = \boldsymbol{X}^T\boldsymbol{y}=\sum_{i=0}^{p-1}\boldsymbol{u}_j\boldsymbol{u}_j^T\boldsymbol{y}, +$$ + +

    +and + +$$ +\boldsymbol{\beta}^{\mathrm{Ridge}} = \left(\boldsymbol{I}+\lambda\boldsymbol{I}\right)^{-1}\boldsymbol{X}^T\boldsymbol{y}=\left(1+\lambda\right)^{-1}\boldsymbol{\beta}^{\mathrm{OLS}}, +$$ + +

    +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 article is highly recommended. +Similarly, Mehta et al's article is also recommended. + +

    +









    + +

    Where are we going?

    + +

    +Before we proceed, we need to rethink what we have been doing. In our +eager to fit the data, we have omitted several important elements in +our regression analysis. In what follows we will

      -
    1. For \( f(x)=2x \) , \( Ntrain=10 \) and \( \sigma =0 \) (noiseless case), train the three classes of models (linear, third-order polynomial, and tenth order polynomial) for a training set when \( x \in [0,1] \) . Make graphs comparing fits for different order of polynomials. Which model fits the data the best?
    2. -
    3. Do you think that the data that has the least error on the training set will also make the best predictions? Why or why not? Can you try to discuss and formalize your intuition? What can go right and what can go wrong?
    4. -
    5. Check your answer by seeing how well your fits predict newly generated test data (including on data outside the range you fit on, for example \( x \in [0,1.2] \) ) using the code below. How well do you do on points in the range of x where you trained the model? How about points outside the original training data set?
    6. -
    7. Repeat the above for \( f(x)=2x \) , \( Ntrain=10 \) , and \( \sigma=1 \) . What changes?
    8. +
    9. look at statistical properties, including a discussion of mean values, variance and the so-called bias-variance tradeoff
    10. +
    11. introduce resampling techniques like cross-validation, bootstrapping and jackknife and more
    -Repeat the exercises above for \( f(x)=2x \) , \( Ntrain=100 \) , and \( \sigma=1 \) . What changes? -Summarize what you have learned about the relationship between model complexity (number of parameters), goodness of fit on training data, and the ability to predict well. +This will allow us to link the standard linear algebra methods we have discussed above to a statistical interpretation of the methods.











    -

    Fitting versus predicting when data is not in the model class

    - -

    -Thus far, we have considered the case where the data is generated using a model contained in the model class. Now consider \( f(x)=2x-10x^5+15x^{10} \) . Notice that the for linear and third-order polynomial the true model \( f(x) \) is not contained in model class. - -

      -
    1. Do better fits lead to better predictions?
    2. -
    3. What is the relationship between the true model for generating the data and the model class that has the most predictive power? How is this related to the model complexity? How does this depend on the number of data points \( Ntrain \) and \( \sigma \)?
    4. -
    - -Summarize what you think you learned about the relationship of knowing the true model class and predictive power. - -

    -









    - -

    An example code without the model assessment part

    - -

    - - -

    import numpy as np
    -import sklearn as sk
    -from sklearn import datasets, linear_model
    -from sklearn.preprocessing import PolynomialFeatures
    -
    -import matplotlib as mpl
    -from matplotlib import pyplot as plt
    -
    -%matplotlib notebook
    -
    -# The Training Data
    -
    -N_train=100
    -
    -sigma_train=1;
    -
    -# Train on integers
    -x=np.linspace(0.05,0.95,N_train)
    -# Draw random noise
    -s = sigma_train*np.random.randn(N_train)
    -
    -#linear
    -y=2*x+s
    -
    -#Tenth Order
    -#y=2*x-10*x**5+15*x**10+s
    -
    -p1=plt.plot(x,y, "o",ms=15, label='Training')
    -
    -#Linear Regression
    -# Create linear regression object
    -clf = linear_model.LinearRegression()
    -
    -# Train the model using the training sets
    -clf.fit(x[:, np.newaxis], y)
    -# The coefficients
    -
    -xplot=np.linspace(0.02,0.98,200)
    -linear_plot=plt.plot(xplot, clf.predict(xplot[:, np.newaxis]),label='Linear')
    -
    -#Polynomial Regression
    -
    -
    -poly3 = PolynomialFeatures(degree=3)
    -X = poly3.fit_transform(x[:,np.newaxis])
    -clf3 = linear_model.LinearRegression()
    -clf3.fit(X,y)
    -
    -
    -Xplot=poly3.fit_transform(xplot[:,np.newaxis])
    -poly3_plot=plt.plot(xplot, clf3.predict(Xplot), label='Poly 3')
    -
    -
    -
    -#poly5 = PolynomialFeatures(degree=5)
    -#X = poly5.fit_transform(x[:,np.newaxis])
    -#clf5 = linear_model.LinearRegression()
    -#clf5.fit(X,y)
    -
    -#Xplot=poly5.fit_transform(xplot[:,np.newaxis])
    -#plt.plot(xplot, clf5.predict(Xplot), 'r--',linewidth=1)
    -
    -poly10 = PolynomialFeatures(degree=10)
    -X = poly10.fit_transform(x[:,np.newaxis])
    -clf10 = linear_model.LinearRegression()
    -clf10.fit(X,y)
    -
    -Xplot=poly10.fit_transform(xplot[:,np.newaxis])
    -poly10_plot=plt.plot(xplot, clf10.predict(Xplot), label='Poly 10')
    -
    -axes = plt.gca()
    -axes.set_ylim([-7,7])
    -
    -handles, labels=axes.get_legend_handles_labels()
    -plt.legend(handles,labels, loc='lower center')
    -plt.xlabel("$x$")
    -plt.ylabel("$y$")
    -Title="$N=$"+str(N_train)+", $\sigma=$"+str(sigma_train)
    -plt.title(Title+" (train)")
    -plt.tight_layout()
    -plt.show()
    -
    -

    - - -

    Generating test data

    -

    - - -

    # Generate Test Data
    -
    -#Number of test data
    -N_test=20
    -
    -sigma_test=sigma_train
    -
    -max_x=1.2
    -x_test=max_x*np.random.random(N_test)
    -# Draw random noise
    -s_test = sigma_test*np.random.randn(N_test)
    -
    -#Linear
    -y_test=2*x_test+s_test
    -#Tenth order
    -#y_test=2*x_test-10*x_test**5+15*x_test**10+s_test
    -
    -#Make design matrices for prediction
    -x_plot=np.linspace(0,max_x, 200)
    -X3 = poly3.fit_transform(x_plot[:,np.newaxis])
    -X10 = poly10.fit_transform(x_plot[:,np.newaxis])
    -
    -%matplotlib notebook
    -
    -fig = plt.figure() 
    -p1=plt.plot(x_test,y_test.transpose(), 'o', ms=12, label='data')
    -p2=plt.plot(x_plot,clf.predict(x_plot[:,np.newaxis]), label='linear')
    -p3=plt.plot(x_plot,clf3.predict(X3), label='3rd order')
    -p10=plt.plot(x_plot,clf10.predict(X10), label='10th order')
    -
    -
    -plt.legend(loc=2)
    -plt.xlabel('$x$')
    -plt.ylabel('$y$')
    -plt.legend(loc='best')
    -plt.title(Title+" (pred.)")
    -plt.tight_layout()
    -plt.show()
    -
    -

    -









    - -

    How can we effectively evaluate the various models?

    - -

    -In Ridge regression and the subsequent discussion of its properties -the bias or penalty parameter is considered known or `given'. In -practice, it is unknown and the user needs to make an informed -decision on its value. How do we do that? Much of the same considerations apply to the Lasso method. - -

    -









    - -

    Code examples for Ridge and Lasso Regression

    - -

    - - -

    import matplotlib.pyplot as plt
    -import numpy as np
    -from sklearn import linear_model
    -from sklearn.linear_model import LinearRegression
    -from sklearn.metrics import mean_squared_error, r2_score
    -
    -#creating data with random noise
    -x=np.arange(50)
    -
    -delta=np.random.uniform(-2.5,2.5, size=(50))
    -np.random.shuffle(delta)
    -y =0.5*x+5+delta
    -
    -#arranging data into 2x50 matrix
    -a=np.array(x) #inputs
    -b=np.array(y) #outputs
    -
    -#Split into training and test
    -X_train=a[:37, np.newaxis]
    -X_test=a[37:, np.newaxis]
    -y_train=b[:37]
    -y_test=b[37:]
    -
    -print ("X_train: ", X_train.shape)
    -print ("y_train: ", y_train.shape)
    -print ("X_test: ", X_test.shape)
    -print ("y_test: ", y_test.shape)
    -
    -print ("------------------------------------")
    -
    -print ("Ordinary Least Squares")
    -#Add Ordinary Least Squares fit
    -reg=LinearRegression()
    -reg.fit(X_train, y_train)
    -pred=reg.predict(X_test)
    -print ("Prediction Shape: ", pred.shape)
    -
    -print('Coefficients: \n', reg.coef_)
    -# The mean squared error
    -print("Mean squared error: %.2f"
    -      % mean_squared_error(y_test, pred))
    -# Explained variance score: 1 is perfect prediction
    -print('Variance score: %.2f' % r2_score(y_test, pred))
    -
    -#plot
    -plt.scatter(X_test,y_test,color='green', label="Training Data")
    -plt.plot(X_test, pred, color='black', label="Fit Line")
    -plt.legend()
    -plt.show()
    -
    -print ("------------------------------------")
    -
    -print ("Ridge Regression")
    -
    -ridge=linear_model.RidgeCV(alphas=[0.1,1.0,10.0])
    -ridge.fit(X_train,y_train)
    -print ("Ridge Coefficient: ",ridge.coef_)
    -print ("Ridge Intercept: ", ridge.intercept_)
    -#Look into graphing with Ridge fit
    -
    -print ("------------------------------------")
    -
    -print ("Lasso")
    -lasso=linear_model.Lasso(alpha=0.1)
    -lasso.fit(X_train,y_train)
    -predl=lasso.predict(X_test)
    -print("Lasso Coefficient: ", lasso.coef_)
    -print("Lasso Intercept: ", lasso.intercept_)
    -plt.scatter(X_test,y_test,color='green', label="Training Data")
    -plt.plot(X_test, predl, color='blue', label="Lasso")
    -plt.legend()
    -plt.show()
    -
    -

    -









    - -

    A second-order polynomial with Ridge and Lasso

    -

    - - -

    import numpy as np
    -import matplotlib.pyplot as plt
    -from sklearn.linear_model import Ridge
    -from sklearn.metrics import r2_score
    -
    -np.random.seed(4155)
    -
    -n_samples = 100
    -
    -x = np.random.rand(n_samples,1)
    -y = 5*x*x + 0.1*np.random.rand(n_samples,1)
    -
    -# Centering  x and y.
    -x_ = x - np.mean(x)
    -y_ = y - np.mean(y) # beta_0 = mean(y)
    -
    -X = np.c_[np.ones((n_samples,1)), x, x**2]
    -X_ = np.c_[x_, x_**2]
    -
    -
    -### 1.
    -lmb_values = [1e-4, 1e-3, 1e-2, 10, 1e2, 1e4]
    -num_values = len(lmb_values)
    -
    -## Ridge-regression of centered and not centered data
    -beta_ridge = np.zeros((3,num_values))
    -beta_ridge_centered = np.zeros((3,num_values))
    -
    -I3 = np.eye(3)
    -I2 = np.eye(2)
    -
    -for i,lmb in enumerate(lmb_values):
    -    beta_ridge[:,i] = (np.linalg.inv( X.T @ X + lmb*I3) @ X.T @ y).flatten()
    -    beta_ridge_centered[1:,i] = (np.linalg.inv( X_.T @ X_ + lmb*I2) @ X_.T @ y_).flatten()
    -
    -# sett beta_0 = np.mean(y)
    -beta_ridge_centered[0,:] = np.mean(y)
    -
    -## OLS (ordinary least squares) solution 
    -beta_ls = np.linalg.inv( X.T @ X ) @ X.T @ y
    -
    -## Evaluate the models
    -pred_ls = X @ beta_ls
    -pred_ridge =  X @ beta_ridge
    -pred_ridge_centered =  X_ @ beta_ridge_centered[1:] + beta_ridge_centered[0,:]
    -
    -## Plot the results
    -
    -# Sorting
    -sort_ind = np.argsort(x[:,0])
    -
    -x_plot = x[sort_ind,0]
    -x_centered_plot = x_[sort_ind,0]
    -
    -pred_ls_plot = pred_ls[sort_ind,0]
    -pred_ridge_plot = pred_ridge[sort_ind,:]
    -pred_ridge_centered_plot = pred_ridge_centered[sort_ind,:]
    -
    -# Plott not centered
    -plt.plot(x_plot,pred_ls_plot,label='ls')
    -
    -for i in range(num_values):
    -    plt.plot(x_plot,pred_ridge_plot[:,i],label='ridge, lmb=%g'%lmb_values[i])
    -
    -plt.plot(x,y,'ro')
    -
    -plt.title('linear regression on un-centered data')
    -plt.legend()
    -
    -# Plott centered
    -plt.figure()
    -
    -for i in range(num_values):
    -    plt.plot(x_centered_plot,pred_ridge_centered_plot[:,i],label='ridge, lmb=%g'%lmb_values[i])
    -
    -plt.plot(x_,y,'ro')
    -
    -plt.title('linear regression on centered data')
    -plt.legend()
    -
    -
    -# 2.
    -
    -pred_ridge_scikit =  np.zeros((n_samples,num_values))
    -for i,lmb in enumerate(lmb_values):
    -    pred_ridge_scikit[:,i] = (Ridge(alpha=lmb,fit_intercept=False).fit(X,y).predict(X)).flatten() # fit_intercept=False fordi bias er allerede i X
    -
    -plt.figure()
    -
    -plt.plot(x_plot,pred_ls_plot,label='ls')
    -
    -for i in range(num_values):
    -    plt.plot(x_plot,pred_ridge_scikit[sort_ind,i],label='scikit-ridge, lmb=%g'%lmb_values[i])
    -
    -plt.plot(x,y,'ro')
    -plt.legend()
    -plt.title('linear regression using scikit')
    -
    -plt.show()
    -
    -### R2-score of the results
    -for i in range(num_values):
    -    print('lambda = %g'%lmb_values[i])
    -    print('r2 for scikit: %g'%r2_score(y,pred_ridge_scikit[:,i]))
    -    print('r2 for own code, not centered: %g'%r2_score(y,pred_ridge[:,i]))
    -    print('r2 for own, centered: %g\n'%r2_score(y,pred_ridge_centered[:,i]))
    -
    -

    -









    - -

    Resampling methods

    +

    Resampling methods

    @@ -1838,9 +2079,11 @@ once using the original training sample.











    -

    Resampling approaches can be computationally expensive

    +

    Resampling approaches can be computationally expensive

    +

    +

    Resampling approaches can be computationally expensive, because they involve fitting the same statistical method multiple times using @@ -1857,21 +2100,23 @@ of flexibility. The process of evaluating a model’s performance is known as model assessment, whereas the process of selecting the proper level of flexibility for a model is known as model selection. The bootstrap is widely used. + +











    -

    Why resampling methods ?

    +

    Why resampling methods ?

    Statistical analysis.

      -
    • Our simulations can be treated as computer experiments. This is particularly the case for Monte Carlo methods
    • -
    • The results can be analysed with the same statistical tools as we would use analysing experimental data.
    • -
    • As in all experiments, we are looking for expectation values and an estimate of how accurate they are, i.e., possible sources for errors.
    • +
    • Our simulations can be treated as computer experiments. This is particularly the case for Monte Carlo methods
    • +
    • The results can be analysed with the same statistical tools as we would use analysing experimental data.
    • +
    • As in all experiments, we are looking for expectation values and an estimate of how accurate they are, i.e., possible sources for errors.
    @@ -1879,21 +2124,21 @@ bootstrap is widely used.











    -

    Statistical analysis

    +

    Statistical analysis

      -
    • As in other experiments, many numerical experiments have two classes of errors:
    • +
    • As in other experiments, many numerical experiments have two classes of errors:
      • -
      • Statistical errors
      • -
      • Systematical errors
      • +
      • Statistical errors
      • +
      • Systematical errors
      -
    • Statistical errors can be estimated using standard tools from statistics
    • -
    • Systematical errors are method specific and must be treated differently from case to case.
    • +
    • Statistical errors can be estimated using standard tools from statistics
    • +
    • Systematical errors are method specific and must be treated differently from case to case.
    @@ -1901,7 +2146,7 @@ bootstrap is widely used.











    -

    Statistics

    +

    Statistics

    @@ -1932,7 +2177,7 @@ selection of a large set of these numbers reproduces this PDF.











    -

    Statistics, moments

    +

    Statistics, moments

    @@ -1955,7 +2200,7 @@ $$











    -

    Statistics, central moments

    +

    Statistics, central moments

    @@ -1973,14 +2218,14 @@ $$ \begin{align} \sigma^2_X\ \ =\ \ \mathrm{var}(X) & = \langle (x-\langle x\rangle)^2\rangle = \int\! (x-\langle x\rangle)^2 p(x)\,dx -\label{_auto2}\\ +\label{_auto8}\\ & = \int\! \left(x^2 - 2 x \langle x\rangle^{2} + \langle x\rangle^2\right)p(x)\,dx -\label{_auto3}\\ +\label{_auto9}\\ & = \langle x^2\rangle - 2 \langle x\rangle\langle x\rangle + \langle x\rangle^2 -\label{_auto4}\\ +\label{_auto10}\\ & = \langle x^2\rangle - \langle x\rangle^2 -\label{_auto5} +\label{_auto11} \end{align} $$ @@ -1993,7 +2238,7 @@ qualitatively as the spread of \( p \) around its mean.











    -

    Statistics, covariance

    +

    Statistics, covariance

    @@ -2024,7 +2269,7 @@ $$











    -

    Statistics, more covariance

    +

    Statistics, more covariance

    @@ -2037,17 +2282,17 @@ the expectation value. Consider the stochastic variables \( X_i \) and $$ \begin{align} \mathrm{cov}(X_i,\,X_j) &= \langle(x_i-\langle x_i\rangle)(x_j-\langle x_j\rangle)\rangle -\label{_auto6}\\ +\label{_auto12}\\ &=\langle x_i x_j - x_i\langle x_j\rangle - \langle x_i\rangle x_j + \langle x_i\rangle\langle x_j\rangle\rangle -\label{_auto7}\\ +\label{_auto13}\\ &=\langle x_i x_j\rangle - \langle x_i\langle x_j\rangle\rangle - \langle \langle x_i\rangle x_j\rangle + \langle \langle x_i\rangle\langle x_j\rangle\rangle -\label{_auto8}\\ +\label{_auto14}\\ &=\langle x_i x_j\rangle - \langle x_i\rangle\langle x_j\rangle - \langle x_i\rangle\langle x_j\rangle + \langle x_i\rangle\langle x_j\rangle -\label{_auto9}\\ +\label{_auto15}\\ &=\langle x_i x_j\rangle - \langle x_i\rangle\langle x_j\rangle -\label{_auto10} +\label{_auto16} \end{align} $$

    @@ -2056,7 +2301,7 @@ $$











    -

    Statistics, independent variables

    +

    Statistics, independent variables

    @@ -2082,7 +2327,7 @@ $$











    -

    Statistics, more variance

    +

    Statistics, more variance

    @@ -2114,7 +2359,7 @@ value of a set of measurements.











    -

    Statistics and stochastic processes

    +

    Statistics and stochastic processes

    @@ -2142,7 +2387,7 @@ interested in finding the few lowest moments, like the mean

    -

    Statistics and sample variables

    +

    Statistics and sample variables

    @@ -2168,7 +2413,7 @@ $$











    -

    Statistics, sample variance and covariance

    +

    Statistics, sample variance and covariance

    @@ -2189,7 +2434,7 @@ and covariance \( \mathrm{cov}(X,Y) \).











    -

    Statistics, law of large numbers

    +

    Statistics, law of large numbers

    @@ -2221,7 +2466,7 @@ true PDFs behind, which we usually do not have.











    -

    Statistics, more on sample error

    +

    Statistics, more on sample error

    @@ -2243,7 +2488,7 @@ means.











    -

    Statistics

    +

    Statistics

    @@ -2264,7 +2509,7 @@ And in particular we are interested in its variance \( \mathrm{var}(\overline X_











    -

    Statistics, central limit theorem

    +

    Statistics, central limit theorem

    @@ -2289,7 +2534,7 @@ $$











    -

    Statistics, more technicalities

    +

    Statistics, more technicalities

    @@ -2318,7 +2563,7 @@ estimate of the PDF of each of the \( X_i \), estimating all properties of











    -

    Statistics

    +

    Statistics

    @@ -2345,7 +2590,7 @@ $$











    -

    Statistics and sample variance

    +

    Statistics and sample variance

    @@ -2384,7 +2629,7 @@ measurements in the sample.











    -

    Statistics, uncorrelated results

    +

    Statistics, uncorrelated results

    @@ -2419,7 +2664,7 @@ cannot overlook the always present correlations.











    -

    Statistics, computations

    +

    Statistics, computations

    @@ -2448,7 +2693,7 @@ measurements. For uncorrelated measurements this second term is zero.











    -

    Statistics, more on computations of errors

    +

    Statistics, more on computations of errors

    @@ -2470,7 +2715,7 @@ have to be stored throughout the experiment.











    -

    Statistics, wrapping up 1

    +

    Statistics, wrapping up 1

    @@ -2503,7 +2748,7 @@ starting always at \( 1 \) for \( d=0 \).











    -

    Statistics, final expression

    +

    Statistics, final expression

    @@ -2536,7 +2781,7 @@ $$











    -

    Statistics, effective number of correlations

    +

    Statistics, effective number of correlations

    @@ -2559,42 +2804,187 @@ measurements is very large.

    -









    + -

    Log-likelihood

    +

    Linking the regression analysis with a statistical interpretation

    -A popular strategy is to choose a penalty parameter that yields a good -but parsimonious model. Information criteria measure the balance -between model fit and model complexity. One possibility is Aikaike's -information criterion (AIC). -The AIC measures model fit by the log-likelihood -and model complexity is measured by the number of parameters used by -the model. The number of model parameters in regular regression simply -corresponds to the number of covariates in the model. Or, by the -degrees of freedom consumed by the model, which is equivalent to the -trace of the hat matrix. For ridge regression it thus seems natural to -define model complexity analogously by the trace of the ridge hat -matrix. This yields the AIC for the linear regression model with ridge -estimates: +Finally, we are going to discuss several statistical properties which can be obtained in terms of analytical expressions. +The +advantage of doing linear regression is that we actually end up with +analytical expressions for several statistical quantities. +Standard least squares and Ridge regression allow us to +derive quantities like the variance and other expectation values in a +rather straightforward way. +

    +It is assumed that \( \varepsilon_i +\sim \mathcal{N}(0, \sigma^2) \) and the \( \varepsilon_{i} \) are +independent, i.e.: $$ -\begin{align*} -\mbox{AIC}(\lambda) & = 2 \, p - 2 \log(\hat{L}) -\\ -& = 2 \, \mbox{tr} [\mathbf{H}(\lambda)] - 2 \log\{L[\hat{\beta}(\lambda), \hat{\sigma}^2(\lambda)]\} -\\ -& = 2 \, \sum_{j=1}^p \frac{d_{jj}^2}{d_{jj}^2 + \lambda} -+ 2 n \, \log[\sqrt{2 \, \pi} \, \hat{\sigma}(\lambda)] + \frac{1}{\hat{\sigma}^2(\lambda)} \sum_{i=1}^n [y_i - \mathbf{X}_{i, \ast} \, \hat{\beta}(\lambda)]^2. +\begin{align*} +\mbox{Cov}(\varepsilon_{i_1}, +\varepsilon_{i_2}) & = \left\{ \begin{array}{lcc} \sigma^2 & \mbox{if} +& i_1 = i_2, \\ 0 & \mbox{if} & i_1 \not= i_2. \end{array} \right. +\end{align*} +$$ + +The randomness of \( \varepsilon_i \) implies that +\( \mathbf{y}_i \) is also a random variable. In particular, +\( \mathbf{y}_i \) is normally distributed, because \( \varepsilon_i \sim +\mathcal{N}(0, \sigma^2) \) and \( \mathbf{X}_{i,\ast} \, \boldsymbol{\beta} \) is a +non-random scalar. To specify the parameters of the distribution of +\( \mathbf{y}_i \) we need to calculate its first two moments. + +

    +Recall that \( \boldsymbol{X} \) is a matrix of dimensionality \( n\times p \). The +notation above \( \mathbf{X}_{i,\ast} \) means that we are looking at the +row number \( i \) and perform a sum over all values \( p \). + +

    +









    + +

    Assumptions made

    + +

    +The assumption we have made here can be summarized as (and this is going to useful when we discuss the bias-variance trade off) +that there exists a function \( f(\boldsymbol{x}) \) and a normal distributed error \( \boldsymbol{\varepsilon}\sim \mathcal{N}(0, \sigma^2) \) +which describes our data +$$ +\boldsymbol{y} = f(\boldsymbol{x})+\boldsymbol{\varepsilon} +$$ + +

    +We approximate this function with our model from the solution of the linear regression equations, that is our +function \( f \) is approximated by \( \boldsymbol{\tilde{y}} \) where we want to minimize \( (\boldsymbol{y}-\boldsymbol{\tilde{y}})^2 \), our MSE, with +$$ +\boldsymbol{\tilde{y}} = \boldsymbol{X}\boldsymbol{\beta}. +$$ + +

    +









    + +

    Expectation value and variance

    + +

    +We can calculate the expectation value of \( \boldsymbol{y} \) for a given element \( i \) +$$ +\begin{align*} +\mathbb{E}(y_i) & = +\mathbb{E}(\mathbf{X}_{i, \ast} \, \boldsymbol{\beta}) + \mathbb{E}(\varepsilon_i) +\, \, \, = \, \, \, \mathbf{X}_{i, \ast} \, \beta, +\end{align*} +$$ + +while +its variance is +$$ +\begin{align*} \mbox{Var}(y_i) & = \mathbb{E} \{ [y_i +- \mathbb{E}(y_i)]^2 \} \, \, \, = \, \, \, \mathbb{E} ( y_i^2 ) - +[\mathbb{E}(y_i)]^2 \\ & = \mathbb{E} [ ( \mathbf{X}_{i, \ast} \, +\beta + \varepsilon_i )^2] - ( \mathbf{X}_{i, \ast} \, \boldsymbol{\beta})^2 \\ & += \mathbb{E} [ ( \mathbf{X}_{i, \ast} \, \boldsymbol{\beta})^2 + 2 \varepsilon_i +\mathbf{X}_{i, \ast} \, \boldsymbol{\beta} + \varepsilon_i^2 ] - ( \mathbf{X}_{i, +\ast} \, \beta)^2 \\ & = ( \mathbf{X}_{i, \ast} \, \boldsymbol{\beta})^2 + 2 +\mathbb{E}(\varepsilon_i) \mathbf{X}_{i, \ast} \, \boldsymbol{\beta} + +\mathbb{E}(\varepsilon_i^2 ) - ( \mathbf{X}_{i, \ast} \, \boldsymbol{\beta})^2 +\\ & = \mathbb{E}(\varepsilon_i^2 ) \, \, \, = \, \, \, +\mbox{Var}(\varepsilon_i) \, \, \, = \, \, \, \sigma^2. \end{align*} $$ -The value of \( \lambda \) which minimizes \( \mbox{AIC}(\lambda) \) corresponds to the `optimal' balance of model complexity and overfitting. +Hence, \( y_i \sim \mathcal{N}( \mathbf{X}_{i, \ast} \, \boldsymbol{\beta}, \sigma^2) \), that is \( \boldsymbol{y} \) follows a normal distribution with +mean value \( \boldsymbol{X}\boldsymbol{\beta} \) and variance \( \sigma^2 \) (not be confused with the singular values of the SVD). + +

    +









    + +

    Expectation value and variance for \( \boldsymbol{\beta} \)

    + +

    +With the OLS expressions for the parameters \( \boldsymbol{\beta} \) we can evaluate the expectation value +$$ +\mathbb{E}(\boldsymbol{\beta}) = \mathbb{E}[ (\mathbf{X}^{\top} \mathbf{X})^{-1}\mathbf{X}^{T} \mathbf{Y}]=(\mathbf{X}^{T} \mathbf{X})^{-1}\mathbf{X}^{T} \mathbb{E}[ \mathbf{Y}]=(\mathbf{X}^{T} \mathbf{X})^{-1} \mathbf{X}^{T}\mathbf{X}\boldsymbol{\beta}=\boldsymbol{\beta}. +$$ + +This means that the estimator of the regression parameters is unbiased. + +

    +We can also calculate the variance + +

    +The variance of \( \boldsymbol{\beta} \) is +$$ +\begin{eqnarray*} +\mbox{Var}(\boldsymbol{\beta}) & = & \mathbb{E} \{ [\boldsymbol{\beta} - \mathbb{E}(\boldsymbol{\beta})] [\boldsymbol{\beta} - \mathbb{E}(\boldsymbol{\beta})]^{T} \} +\\ +& = & \mathbb{E} \{ [(\mathbf{X}^{T} \mathbf{X})^{-1} \, \mathbf{X}^{T} \mathbf{Y} - \boldsymbol{\beta}] \, [(\mathbf{X}^{T} \mathbf{X})^{-1} \, \mathbf{X}^{T} \mathbf{Y} - \boldsymbol{\beta}]^{T} \} +\\ +% & = & \mathbb{E} \{ [(\mathbf{X}^{T} \mathbf{X})^{-1} \, \mathbf{X}^{T} \mathbf{Y}] \, [(\mathbf{X}^{T} \mathbf{X})^{-1} \, \mathbf{X}^{T} \mathbf{Y}]^{T} \} - \boldsymbol{\beta} \, \boldsymbol{\beta}^{T} +% \\ +% & = & \mathbb{E} \{ (\mathbf{X}^{T} \mathbf{X})^{-1} \, \mathbf{X}^{T} \mathbf{Y} \, \mathbf{Y}^{T} \, \mathbf{X} \, (\mathbf{X}^{T} \mathbf{X})^{-1} \} - \boldsymbol{\beta} \, \boldsymbol{\beta}^{T} +% \\ +& = & (\mathbf{X}^{T} \mathbf{X})^{-1} \, \mathbf{X}^{T} \, \mathbb{E} \{ \mathbf{Y} \, \mathbf{Y}^{T} \} \, \mathbf{X} \, (\mathbf{X}^{T} \mathbf{X})^{-1} - \boldsymbol{\beta} \, \boldsymbol{\beta}^{T} +\\ +& = & (\mathbf{X}^{T} \mathbf{X})^{-1} \, \mathbf{X}^{T} \, \{ \mathbf{X} \, \boldsymbol{\beta} \, \boldsymbol{\beta}^{T} \, \mathbf{X}^{T} + \sigma^2 \} \, \mathbf{X} \, (\mathbf{X}^{T} \mathbf{X})^{-1} - \boldsymbol{\beta} \, \boldsymbol{\beta}^{T} +% \\ +% & = & (\mathbf{X}^T \mathbf{X})^{-1} \, \mathbf{X}^T \, \mathbf{X} \, \boldsymbol{\beta} \, \boldsymbol{\beta}^T \, \mathbf{X}^T \, \mathbf{X} \, (\mathbf{X}^T % \mathbf{X})^{-1} +% \\ +% & & + \, \, \sigma^2 \, (\mathbf{X}^T \mathbf{X})^{-1} \, \mathbf{X}^T \, \mathbf{X} \, (\mathbf{X}^T \mathbf{X})^{-1} - \boldsymbol{\beta} \boldsymbol{\beta}^T +\\ +& = & \boldsymbol{\beta} \, \boldsymbol{\beta}^{T} + \sigma^2 \, (\mathbf{X}^{T} \mathbf{X})^{-1} - \boldsymbol{\beta} \, \boldsymbol{\beta}^{T} +\, \, \, = \, \, \, \sigma^2 \, (\mathbf{X}^{T} \mathbf{X})^{-1}, +\end{eqnarray*} +$$ + +

    +where we have used that \( \mathbb{E} (\mathbf{Y} \mathbf{Y}^{T}) = +\mathbf{X} \, \boldsymbol{\beta} \, \boldsymbol{\beta}^{T} \, \mathbf{X}^{T} + +\sigma^2 \, \mathbf{I}_{nn} \). From \( \mbox{Var}(\boldsymbol{\beta}) = \sigma^2 +\, (\mathbf{X}^{T} \mathbf{X})^{-1} \), one obtains an estimate of the +variance of the estimate of the \( j \)-th regression coefficient: +\( \hat{\sigma}^2 (\hat{\beta}_j ) = \hat{\sigma}^2 \sqrt{ +[(\mathbf{X}^{T} \mathbf{X})^{-1}]_{jj} } \). This may be used to +construct a confidence interval for the estimates. + +

    +In a similar way, we cna obtain analytical expressions for say the +expectation values of the parameters \( \boldsymbol{\beta} \) and their variance +when we employ Ridge regression, and thereby a confidence interval. + +

    +It is rather straightforward to show that +$$ +\mathbb{E} \big[ \boldsymbol{\beta}^{\mathrm{Ridge}} \big]=(\mathbf{X}^{T} \mathbf{X} + \lambda \mathbf{I}_{pp})^{-1} (\mathbf{X}^{\top} \mathbf{X})\boldsymbol{\beta}^{\mathrm{OLS}}. +$$ + +We see clearly that +\( \mathbb{E} \big[ \boldsymbol{\beta}^{\mathrm{Ridge}} \big] \not= \boldsymbol{\beta}^{\mathrm{OLS}} \) for any \( \lambda > 0 \). We say then that the ridge estimator is biased. + +

    +We can also compute the variance as + +$$ +\mbox{Var}[\boldsymbol{\beta}^{\mathrm{Ridge}}]=\sigma^2[ \mathbf{X}^{T} \mathbf{X} + \lambda \mathbf{I} ]^{-1} \mathbf{X}^{T} \mathbf{X} \{ [ \mathbf{X}^{\top} \mathbf{X} + \lambda \mathbf{I} ]^{-1}\}^{T}, +$$ + +and it is easy to see that if the parameter \( \lambda \) goes to infinity then the variance of Ridge parameters \( \boldsymbol{\beta} \) goes to zero. + +

    +With this, we can compute the difference + +$$ +\mbox{Var}[\boldsymbol{\beta}^{\mathrm{OLS}}]-\mbox{Var}(\boldsymbol{\beta}^{\mathrm{Ridge}})=\sigma^2 [ \mathbf{X}^{T} \mathbf{X} + \lambda \mathbf{I} ]^{-1}[ 2\lambda\mathbf{I} + \lambda^2 (\mathbf{X}^{T} \mathbf{X})^{-1} ] \{ [ \mathbf{X}^{T} \mathbf{X} + \lambda \mathbf{I} ]^{-1}\}^{T}. +$$ + +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 \( \boldsymbol{\beta} \) obtained with the Ridge estimator. This has interesting consequences when we discuss the so-called bias-variance trade-off below.

    -

    Cross-validation

    +

    Cross-validation

    Instead of choosing the penalty parameter to balance model fit with @@ -2602,12 +2992,15 @@ model complexity, cross-validation requires it (i.e. the penalty parameter) to yield a model with good prediction performance. Commonly, this performance is evaluated on novel data. Novel data need not be easy to come by and one has to make do -with the data at hand. The setting of `original' and novel data is +with the data at hand. + +

    +The setting of original and novel data is then mimicked by sample splitting: the data set is divided into two -(groups of samples). One of these two data sets, called the training -set, plays the role of `original' data on which the model is +(groups of samples). One of these two data sets, called the +training set, plays the role of original data on which the model is built. The second of these data sets, called the test set, plays the -role of the `novel' data and is used to evaluate the prediction +role of the novel data and is used to evaluate the prediction performance (often operationalized as the log-likelihood or the prediction error or its square or the R2 score) of the model built on the training data set. This procedure (model building and prediction evaluation on training and @@ -2625,7 +3018,7 @@ some sense) is then selected.











    -

    Computationally expensive

    +

    Computationally expensive

    The validation set approach is conceptually simple and is easy to implement. But it has two potential drawbacks: @@ -2637,7 +3030,7 @@ The validation set approach is conceptually simple and is easy to implement. But -

    Various steps in cross-validation

    +

    Various steps in cross-validation

    When the repetitive splitting of the data set is done randomly, @@ -2658,32 +3051,32 @@ cross-validation (LOOCV).

    -

    How to set up the cross-validation for Ridge and/or Lasso

    +

    How to set up the cross-validation for Ridge and/or Lasso

    • Define a range of interest for the penalty parameter.
    • Divide the data set into training and test set comprising samples \( \{1, \ldots, n\} \setminus i \) and \( \{ i \} \), respectively.
    • -
    • Fit the linear regression model by means of ridge estimation for each \( \lambda \) in the grid using the training set, and the corresponding estimate of the error variance \( \hat{\sigma}_{-i}^2(\lambda) \), as
    • +
    • Fit the linear regression model by means of ridge estimation for each \( \lambda \) in the grid using the training set, and the corresponding estimate of the error variance \( \boldsymbol{\sigma}_{-i}^2(\lambda) \), as
    $$ \begin{align*} -\hat{\beta}_{-i}(\lambda) & = ( \hat{X}_{-i, \ast}^{\top} -\hat{X}_{-i, \ast} + \lambda \hat{I}_{pp})^{-1} -\hat{X}_{-i, \ast}^{\top} \hat{y}_{-i} +\boldsymbol{\beta}_{-i}(\lambda) & = ( \boldsymbol{X}_{-i, \ast}^{T} +\boldsymbol{X}_{-i, \ast} + \lambda \boldsymbol{I}_{pp})^{-1} +\boldsymbol{X}_{-i, \ast}^{T} \boldsymbol{y}_{-i} \end{align*} $$
      -
    • Evaluate the prediction performance of these models on the test set by \( \log\{L[y_i, \hat{X}_{i, \ast}; \hat{\beta}_{-i}(\lambda), \hat{\sigma}_{-i}^2(\lambda)]\} \). Or, by the prediction error \( |y_i - \hat{X}_{i, \ast} \hat{\beta}_{-i}(\lambda)| \), the relative error, the error squared or the R2 score function.
    • +
    • Evaluate the prediction performance of these models on the test set by \( \log\{L[y_i, \boldsymbol{X}_{i, \ast}; \boldsymbol{\beta}_{-i}(\lambda), \boldsymbol{\sigma}_{-i}^2(\lambda)]\} \). Or, by the prediction error \( |y_i - \boldsymbol{X}_{i, \ast} \boldsymbol{\beta}_{-i}(\lambda)| \), the relative error, the error squared or the R2 score function.
    • Repeat the first three steps such that each sample plays the role of the test set once.
    • Average the prediction performances of the test sets at each grid point of the penalty bias/parameter by computing the cross-validated log-likelihood. It is an estimate of the prediction performance of the model corresponding to this value of the penalty parameter on novel data. It is defined as
    $$ \begin{align*} -\frac{1}{n} \sum_{i = 1}^n \log\{L[y_i, \mathbf{X}_{i, \ast}; \hat{\beta}_{-i}(\lambda), \hat{\sigma}_{-i}^2(\lambda)]\}. +\frac{1}{n} \sum_{i = 1}^n \log\{L[y_i, \mathbf{X}_{i, \ast}; \boldsymbol{\beta}_{-i}(\lambda), \boldsymbol{\sigma}_{-i}^2(\lambda)]\}. \end{align*} $$ @@ -2694,31 +3087,7 @@ $$









    -

    Predicted Residual Error Sum of Squares

    -
    - -

    -Another approach in the LOOCV scheme is to the use the so-called Predicted Residual Error Sum of Squares (PRESS). - -

    -We can define the optimal penalty parameter to minimize -$$ -\begin{align*} -\lambda_{\mbox{{\tiny opt}}} = \arg \min_{\lambda} \frac{1}{n} \sum_{i=1}^n [y_i - \hat{X}_{i, \ast} \hat{\beta}_{-i}(\lambda)]^2. -\end{align*} -$$ - -

    -The LOOCV prediction performance can be -expressed analytically in terms of the known quantities derived from -the design matrix and the parameters \( \beta \). -

    - - -

    -









    - -

    Resampling methods: Jackknife and Bootstrap

    +

    Resampling methods: Jackknife and Bootstrap

    Two famous @@ -2741,18 +3110,18 @@ need for bootstrapping.











    -

    Resampling methods: Jackknife

    +

    Resampling methods: Jackknife

    The Jackknife works by making many replicas of the estimator \( \widehat{\theta} \). -The jackknife is a resampling method, we explained that this happens by scrambling the data in some way. When using the jackknife, this is done by systematically leaving out one observation from the vector of observed values \( \hat{x} = (x_1,x_2,\cdots,X_n) \). -Let \( \hat{x}_i \) denote the vector +The jackknife is a resampling method where we systematically leave out one observation from the vector of observed values \( \boldsymbol{x} = (x_1,x_2,\cdots,X_n) \). +Let \( \boldsymbol{x}_i \) denote the vector $$ -\hat{x}_i = (x_1,x_2,\cdots,x_{i-1},x_{i+1},\cdots,x_n), +\boldsymbol{x}_i = (x_1,x_2,\cdots,x_{i-1},x_{i+1},\cdots,x_n), $$

    -which equals the vector \( \hat{x} \) with the exception that observation +which equals the vector \( \boldsymbol{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 \). @@ -2760,20 +3129,6 @@ number \( i \) is left out. Using this notation, define











    -

    Resampling methods: Jackknife estimator

    - -

    -To get an estimate for the bias and -standard error of \( \widehat{\theta} \), use the following -estimators for each component of \( \widehat{\theta} \) - -$$ -\widehat{\mathrm{Bias}}(\widehat \theta,\theta) = (n-1)\left( - \widehat{\theta} + \frac{1}{n}\sum_{i=1}^{n} \widehat \theta_i \right) \qquad \text{and} \qquad \widehat{\sigma}^2_{\widehat{\theta} } = \frac{n-1}{n}\sum_{i=1}^{n}( \widehat{\theta}_i - \frac{1}{n}\sum_{j=1}^{n}\widehat \theta_j )^2. -$$ - -

    -









    -

    Jackknife code example

    @@ -2834,14 +3189,14 @@ advantages:

    Resampling methods: Bootstrap background

    -Since \( \widehat{\theta} = \widehat{\theta}(\hat{X}) \) is a function of random variables, +Since \( \widehat{\theta} = \widehat{\theta}(\boldsymbol{X}) \) is a function of random variables, \( \widehat{\theta} \) itself must be a random variable. Thus it has -a pdf, call this function \( p(\hat{t}) \). The aim of the bootstrap is to -estimate \( p(\hat{t}) \) by the relative frequency of +a pdf, call this function \( p(\boldsymbol{t}) \). The aim of the bootstrap is to +estimate \( p(\boldsymbol{t}) \) by the relative frequency of \( \widehat{\theta} \). You can think of this as using a histogram -in the place of \( p(\hat{t}) \). If the relative frequency closely +in the place of \( p(\boldsymbol{t}) \). If the relative frequency closely resembles \( p(\vec{t}) \), then using numerics, it is straight forward to -estimate all the interesting parameters of \( p(\hat{t}) \) using point +estimate all the interesting parameters of \( p(\boldsymbol{t}) \) using point estimators.

    @@ -2864,7 +3219,7 @@ been straight forward to do this by: By repeated use of (1) and (2), many estimates of \( \widehat{\theta} \) could have been obtained. The idea is to use the relative frequency of \( \widehat{\theta}^* \) -(think of a histogram) as an estimate of \( p(\hat{t}) \). +(think of a histogram) as an estimate of \( p(\boldsymbol{t}) \).











    @@ -2885,7 +3240,7 @@ result in some asymptotic sense? The answer is yes. Instead of generating the histogram for the relative frequency of the observation \( X_i \), just draw the values \( (X_1^*,X_2^*,\cdots,X_n^*) \) with replacement from the vector -\( \hat{X} \). +\( \boldsymbol{X} \).











    @@ -2896,19 +3251,41 @@ frequency of the observation \( X_i \), just draw the values The independent bootstrap works like this:

      -
    1. Draw with replacement \( n \) numbers for the observed variables \( \hat{x} = (x_1,x_2,\cdots,x_n) \).
    2. -
    3. Define a vector \( \hat{x}^* \) containing the values which were drawn from \( \hat{x} \).
    4. -
    5. Using the vector \( \hat{x}^* \) compute \( \widehat{\theta}^* \) by evaluating \( \widehat \theta \) under the observations \( \hat{x}^* \).
    6. +
    7. Draw with replacement \( n \) numbers for the observed variables \( \boldsymbol{x} = (x_1,x_2,\cdots,x_n) \).
    8. +
    9. Define a vector \( \boldsymbol{x}^* \) containing the values which were drawn from \( \boldsymbol{x} \).
    10. +
    11. Using the vector \( \boldsymbol{x}^* \) compute \( \widehat{\theta}^* \) by evaluating \( \widehat \theta \) under the observations \( \boldsymbol{x}^* \).
    12. Repeat this process \( k \) times.
    -When you are done, you can draw a histogram of the relative frequency of \( \widehat \theta^* \). This is your estimate of the probability distribution \( p(t) \). Using this probability distribution you can estimate any statistics thereof. In principle you never draw the histogram of the relative frequency of \( \widehat{\theta}^* \). Instead you use the estimators corresponding to the statistic of interest. For example, if you are interested in estimating the variance of \( \widehat \theta \), apply the etsimator \( \widehat \sigma^2 \) to the values \( \widehat \theta ^* \). +When you are done, you can draw a histogram of the relative frequency +of \( \widehat \theta^* \). This is your estimate of the probability +distribution \( p(t) \). Using this probability distribution you can +estimate any statistics thereof. In principle you never draw the +histogram of the relative frequency of \( \widehat{\theta}^* \). Instead +you use the estimators corresponding to the statistic of interest. For +example, if you are interested in estimating the variance of \( \widehat +\theta \), apply the etsimator \( \widehat \sigma^2 \) to the values +\( \widehat \theta ^* \).











    Code example for the Bootstrap method

    -The following code starts with a Gaussian distribution with mean value \( \mu =100 \) and variance \( \sigma=15 \). We use this to generate the data used in the bootstrap analysis. The bootstrap analysis returns a data set after a given number of bootstrap operations (as many as we have data points). This data set consists of estimated mean values for each bootstrap operation. The histogram generated by the bootstrap method shows that the distribution for these mean values is also a Gaussian, centered around the mean value \( \mu=100 \) but with standard deviation \( \sigma/\sqrt{n} \), where \( n \) is the number of bootstrap samples (in this case the same as the number of original data points). The value of the standard deviation is what we expect from the central limit theorem. + +

    +The following code starts with a Gaussian distribution with mean value +\( \mu =100 \) and variance \( \sigma=15 \). We use this to generate the data +used in the bootstrap analysis. The bootstrap analysis returns a data +set after a given number of bootstrap operations (as many as we have +data points). This data set consists of estimated mean values for each +bootstrap operation. The histogram generated by the bootstrap method +shows that the distribution for these mean values is also a Gaussian, +centered around the mean value \( \mu=100 \) but with standard deviation +\( \sigma/\sqrt{n} \), where \( n \) is the number of bootstrap samples (in +this case the same as the number of original data points). The value +of the standard deviation is what we expect from the central limit +theorem. +

    @@ -2922,30 +3299,29 @@ The following code starts with a Gaussian distribution with mean value \( \mu =1 def stat(data): return mean(data) -# Bootstrap algorithm +# Bootstrap algorithm def bootstrap(data, statistic, R): t = zeros(R); n = len(data); inds = arange(n); t0 = time() - - # non-parametric bootstrap + # non-parametric bootstrap for i in range(R): t[i] = statistic(data[randint(0,n,n)]) - # analysis + # analysis print("Runtime: %g sec" % (time()-t0)); print("Bootstrap Statistics :") print("original bias std. error") - print("%8g %8g %14g %15g" % (statistic(data), std(data),\ - mean(t), \ - std(t))) + print("%8g %8g %14g %15g" % (statistic(data), std(data),mean(t),std(t))) return t mu, sigma = 100, 15 datapoints = 10000 x = mu + sigma*random.randn(datapoints) -# bootstrap returns the data sample t = bootstrap(x, stat, datapoints) -# the histogram of the bootstrapped data n, binsboot, patches = plt.hist(t, 50, normed=1, facecolor='red', alpha=0.75) +# bootstrap returns the data sample +t = bootstrap(x, stat, datapoints) +# the histogram of the bootstrapped data +n, binsboot, patches = plt.hist(t, 50, normed=1, facecolor='red', alpha=0.75) -# add a 'best fit' line +# add a 'best fit' line y = mlab.normpdf( binsboot, mean(t), std(t)) lt = plt.plot(binsboot, y, 'r--', linewidth=1) plt.xlabel('Smarts') @@ -2958,529 +3334,300 @@ plt.show()











    -

    Resampling methods: Blocking

    +

    Code Example for Cross-validation and \( k \)-fold Cross-validation

    -The blocking method was made popular by Flyvbjerg and Pedersen (1989) -and has become one of the standard ways to estimate -\( V(\widehat{\theta}) \) for exactly one \( \widehat{\theta} \), namely -\( \widehat{\theta} = \overline{X} \). - -

    -Assume \( n = 2^d \) for some integer \( d>1 \) and \( X_1,X_2,\cdots, X_n \) is a stationary time series to begin with. -Moreover, assume that the time series is asymptotically uncorrelated. We switch to vector notation by arranging \( X_1,X_2,\cdots,X_n \) in an \( n \)-tuple. Define: -$$ -\begin{align*} -\hat{X} = (X_1,X_2,\cdots,X_n). -\end{align*} -$$ - -

    -The strength of the blocking method is when the number of -observations, \( n \) is large. For large \( n \), the complexity of dependent -bootstrapping scales poorly, but the blocking method does not, -moreover, it becomes more accurate the larger \( n \) is. - -

    -









    - -

    Blocking Transformations

    - We now define -blocking transformations. The idea is to take the mean of subsequent -pair of elements from \( \vec{X} \) and form a new vector -\( \vec{X}_1 \). Continuing in the same way by taking the mean of -subsequent pairs of elements of \( \vec{X}_1 \) we obtain \( \vec{X}_2 \), and -so on. -Define \( \vec{X}_i \) recursively by: - -$$ -\begin{align} -(\vec{X}_0)_k &\equiv (\vec{X})_k \nonumber \\ -(\vec{X}_{i+1})_k &\equiv \frac{1}{2}\Big( (\vec{X}_i)_{2k-1} + -(\vec{X}_i)_{2k} \Big) \qquad \text{for all} \qquad 1 \leq i \leq d-1 -\label{_auto11} -\end{align} -$$ - -

    -The quantity \( \vec{X}_k \) is -subject to \( k \) blocking transformations. We now have \( d \) vectors -\( \vec{X}_0, \vec{X}_1,\cdots,\vec X_{d-1} \) containing the subsequent -averages of observations. It turns out that if the components of -\( \vec{X} \) is a stationary time series, then the components of -\( \vec{X}_i \) is a stationary time series for all \( 0 \leq i \leq d-1 \) - -

    -We can then compute the autocovariance, the variance, sample mean, and -number of observations for each \( i \). -Let \( \gamma_i, \sigma_i^2, -\overline{X}_i \) denote the autocovariance, variance and average of the -elements of \( \vec{X}_i \) and let \( n_i \) be the number of elements of -\( \vec{X}_i \). It follows by induction that \( n_i = n/2^i \). - -

    -









    - -

    Blocking Transformations

    - -

    -Using the -definition of the blocking transformation and the distributive -property of the covariance, it is clear that since \( h =|i-j| \) -we can define -$$ -\begin{align} -\gamma_{k+1}(h) &= cov\left( ({X}_{k+1})_{i}, ({X}_{k+1})_{j} \right) \nonumber \\ -&= \frac{1}{4}cov\left( ({X}_{k})_{2i-1} + ({X}_{k})_{2i}, ({X}_{k})_{2j-1} + ({X}_{k})_{2j} \right) \nonumber \\ -&= \frac{1}{2}\gamma_{k}(2h) + \frac{1}{2}\gamma_k(2h+1) \hspace{0.1cm} \mathrm{h = 0} -\label{_auto12}\\ -&=\frac{1}{4}\gamma_k(2h-1) + \frac{1}{2}\gamma_k(2h) + \frac{1}{4}\gamma_k(2h+1) \quad \mathrm{else} -\label{_auto13} -\end{align} -$$ - -

    -The quantity \( \hat{X} \) is asymptotic uncorrelated by assumption, \( \hat{X}_k \) is also asymptotic uncorrelated. Let's turn our attention to the variance of the sample mean \( V(\overline{X}) \). - -

    -









    - -

    Blocking Transformations, getting there

    -We have -$$ -\begin{align} -V(\overline{X}_k) = \frac{\sigma_k^2}{n_k} + \underbrace{\frac{2}{n_k} \sum_{h=1}^{n_k-1}\left( 1 - \frac{h}{n_k} \right)\gamma_k(h)}_{\equiv e_k} = \frac{\sigma^2_k}{n_k} + e_k \quad \text{if} \quad \gamma_k(0) = \sigma_k^2. -\label{_auto14} -\end{align} -$$ - -The term \( e_k \) is called the truncation error: -$$ -\begin{equation} -e_k = \frac{2}{n_k} \sum_{h=1}^{n_k-1}\left( 1 - \frac{h}{n_k} \right)\gamma_k(h). -\label{_auto15} -\end{equation} -$$ - -We can show that \( V(\overline{X}_i) = V(\overline{X}_j) \) for all \( 0 \leq i \leq d-1 \) and \( 0 \leq j \leq d-1 \). - -

    -









    - -

    Blocking Transformations, final expressions

    - -

    -We can then wrap up -$$ -\begin{align} -n_{j+1} \overline{X}_{j+1} &= \sum_{i=1}^{n_{j+1}} (\hat{X}_{j+1})_i = \frac{1}{2}\sum_{i=1}^{n_{j}/2} (\hat{X}_{j})_{2i-1} + (\hat{X}_{j})_{2i} \nonumber \\ -&= \frac{1}{2}\left[ (\hat{X}_j)_1 + (\hat{X}_j)_2 + \cdots + (\hat{X}_j)_{n_j} \right] = \underbrace{\frac{n_j}{2}}_{=n_{j+1}} \overline{X}_j = n_{j+1}\overline{X}_j. -\label{_auto16} -\end{align} -$$ - -By repeated use of this equation we get \( V(\overline{X}_i) = V(\overline{X}_0) = V(\overline{X}) \) for all \( 0 \leq i \leq d-1 \). This has the consequence that -$$ -\begin{align} -V(\overline{X}) = \frac{\sigma_k^2}{n_k} + e_k \qquad \text{for all} \qquad 0 \leq k \leq d-1. \label{eq:convergence} -\end{align} -$$ - -

    -Fyvbjerg and Petersen demonstrated that the sequence -\( \{e_k\}_{k=0}^{d-1} \) is decreasing, and conjecture that the term -\( e_k \) can be made as small as we would like by making \( k \) (and hence -\( d \)) sufficiently large. The sequence is decreasing (Master of Science thesis by Marius Jonsson, UiO 2018). -It means we can apply blocking transformations until -\( e_k \) is sufficiently small, and then estimate \( V(\overline{X}) \) by -\( \widehat{\sigma}^2_k/n_k \). - -

    -









    - -

    Code examples for Blocking, Jackknife and bootstrap

    - +The code here uses Ridge regression with cross-validation (CV) resampling and \( k \)-fold CV in order to fit a specific polynomial.

    -

    from sys import argv
    -from os import mkdir, path
    -import time
    -import numpy as np
    +
    import numpy as np
     import matplotlib.pyplot as plt
    -from matplotlib.ticker import FormatStrFormatter
    -from matplotlib.font_manager import FontProperties
    +from sklearn.model_selection import KFold
    +from sklearn.linear_model import Ridge
    +from sklearn.model_selection import cross_val_score
    +from sklearn.preprocessing import PolynomialFeatures
     
    -# Timing Decorator
    -def timeFunction(f):
    -    def wrap(*args):
    -        time1 = time.time()
    -        ret = f(*args)
    -        time2 = time.time()
    -        print '%s Function Took: \t %0.3f s' % (f.func_name.title(), (time2-time1))
    -        return ret
    -    return wrap
    +# A seed just to ensure that the random numbers are the same for every run.
    +# Useful for eventual debugging.
    +np.random.seed(3155)
     
    -class dataAnalysisClass:
    -    # General Init functions
    -    def __init__(self, fileName, size=0):
    -        self.inputFileName = fileName
    -        self.loadData(size)
    -        self.createOutputFolder()
    -        self.avg = np.average(self.data)
    -        self.var = np.var(self.data)
    -        self.std = np.std(self.data)
    +# Generate the data.
    +nsamples = 100
    +x = np.random.randn(nsamples)
    +y = 3*x**2 + np.random.randn(nsamples)
     
    -    def loadData(self, size=0):
    -        if size != 0:
    -            with open(self.inputFileName) as inputFile:
    -                self.data = np.zeros(size)
    -                for x in xrange(size):
    -                    self.data[x] = float(next(inputFile))
    -        else:
    -            self.data = np.loadtxt(self.inputFileName)
    +## Cross-validation on Ridge regression using KFold only
     
    -    # Statistical Analysis with Multiple Methods
    -    def runAllAnalyses(self):
    -        if len(self.data) <= 100000:
    -            print "Autocorrelation..."
    -            self.autocorrelation()
    -        print "Bootstrap..."
    -        self.bootstrap()
    -        print "Jackknife..."
    -        self.jackknife()
    -        print "Blocking..."
    -        self.blocking()
    +# Decide degree on polynomial to fit
    +poly = PolynomialFeatures(degree = 6)
     
    -    # Standard Autocorrelation
    -    @timeFunction
    -    def autocorrelation(self):
    -        self.acf = np.zeros(len(self.data)/2)
    -        for k in range(0, len(self.data)/2):
    -            self.acf[k] = np.corrcoef(np.array([self.data[0:len(self.data)-k], \
    -                                            self.data[k:len(self.data)]]))[0,1]
    +# Decide which values of lambda to use
    +nlambdas = 500
    +lambdas = np.logspace(-3, 5, nlambdas)
     
    -    # Bootstrap
    -    @timeFunction
    -    def bootstrap(self, nBoots = 1000):
    -        bootVec = np.zeros(nBoots)
    -        for k in range(0,nBoots):
    -            bootVec[k] = np.average(np.random.choice(self.data, len(self.data)))
    -        self.bootAvg = np.average(bootVec)
    -        self.bootVar = np.var(bootVec)
    -        self.bootStd = np.std(bootVec)
    +# Initialize a KFold instance
    +k = 5
    +kfold = KFold(n_splits = k)
     
    -    # Jackknife
    -    @timeFunction
    -    def jackknife(self):
    -        jackknVec = np.zeros(len(self.data))
    -        for k in range(0,len(self.data)):
    -            jackknVec[k] = np.average(np.delete(self.data, k))
    -        self.jackknAvg = self.avg - (len(self.data) - 1) * (np.average(jackknVec) - self.avg)
    -        self.jackknVar = float(len(self.data) - 1) * np.var(jackknVec)
    -        self.jackknStd = np.sqrt(self.jackknVar)
    +# Perform the cross-validation to estimate MSE
    +scores_KFold = np.zeros((nlambdas, k))
     
    -    # Blocking
    -    @timeFunction
    -    def blocking(self, blockSizeMax = 500):
    -        blockSizeMin = 1
    +i = 0
    +for lmb in lambdas:
    +    ridge = Ridge(alpha = lmb)
    +    j = 0
    +    for train_inds, test_inds in kfold.split(x):
    +        xtrain = x[train_inds]
    +        ytrain = y[train_inds]
     
    -        self.blockSizes = []
    -        self.meanVec = []
    -        self.varVec = []
    +        xtest = x[test_inds]
    +        ytest = y[test_inds]
     
    -        for i in range(blockSizeMin, blockSizeMax):
    -            if(len(self.data) % i != 0):
    -                pass#continue
    -            blockSize = i
    -            meanTempVec = []
    -            varTempVec = []
    -            startPoint = 0
    -            endPoint = blockSize
    +        Xtrain = poly.fit_transform(xtrain[:, np.newaxis])
    +        ridge.fit(Xtrain, ytrain[:, np.newaxis])
     
    -            while endPoint <= len(self.data):
    -                meanTempVec.append(np.average(self.data[startPoint:endPoint]))
    -                startPoint = endPoint
    -                endPoint += blockSize
    -            mean, var = np.average(meanTempVec), np.var(meanTempVec)/len(meanTempVec)
    -            self.meanVec.append(mean)
    -            self.varVec.append(var)
    -            self.blockSizes.append(blockSize)
    +        Xtest = poly.fit_transform(xtest[:, np.newaxis])
    +        ypred = ridge.predict(Xtest)
     
    -        self.blockingAvg = np.average(self.meanVec[-200:])
    -        self.blockingVar = (np.average(self.varVec[-200:]))
    -        self.blockingStd = np.sqrt(self.blockingVar)
    +        scores_KFold[i,j] = np.sum((ypred - ytest[:, np.newaxis])**2)/np.size(ypred)
    +
    +        j += 1
    +    i += 1
     
     
    +estimated_mse_KFold = np.mean(scores_KFold, axis = 1)
     
    -    # Plot of Data, Autocorrelation Function and Histogram
    -    def plotAll(self):
    -        self.createOutputFolder()
    -        if len(self.data) <= 100000:
    -            self.plotAutocorrelation()
    -        self.plotData()
    -        self.plotHistogram()
    -        self.plotBlocking()
    +## Cross-validation using cross_val_score from sklearn along with KFold
     
    -    # Create Output Plots Folder
    -    def createOutputFolder(self):
    -        self.outName = self.inputFileName[:-4]
    -        if not path.exists(self.outName):
    -            mkdir(self.outName)
    +# kfold is an instance initialized above as:
    +# kfold = KFold(n_splits = k)
     
    -    # Plot the Dataset, Mean and Std
    -    def plotData(self):
    -        # Far away plot
    -        font = {'fontname':'serif'}
    -        plt.plot(range(0, len(self.data)), self.data, 'r-', linewidth=1)
    -        plt.plot([0, len(self.data)], [self.avg, self.avg], 'b-', linewidth=1)
    -        plt.plot([0, len(self.data)], [self.avg + self.std, self.avg + self.std], 'g--', linewidth=1)
    -        plt.plot([0, len(self.data)], [self.avg - self.std, self.avg - self.std], 'g--', linewidth=1)
    -        plt.ylim(self.avg - 5*self.std, self.avg + 5*self.std)
    -        plt.gca().yaxis.set_major_formatter(FormatStrFormatter('%.4f'))
    -        plt.xlim(0, len(self.data))
    -        plt.ylabel(self.outName.title() + ' Monte Carlo Evolution', **font)
    -        plt.xlabel('MonteCarlo History', **font)
    -        plt.title(self.outName.title(), **font)
    -        plt.savefig(self.outName + "/data.eps")
    -        plt.savefig(self.outName + "/data.png")
    -        plt.clf()
    +estimated_mse_sklearn = np.zeros(nlambdas)
    +i = 0
    +for lmb in lambdas:
    +    ridge = Ridge(alpha = lmb)
     
    -    # Plot Histogram of Dataset and Gaussian around it
    -    def plotHistogram(self):
    -        binNumber = 50
    -        font = {'fontname':'serif'}
    -        count, bins, ignore = plt.hist(self.data, bins=np.linspace(self.avg - 5*self.std, self.avg + 5*self.std, binNumber))
    -        plt.plot([self.avg, self.avg], [0,np.max(count)+10], 'b-', linewidth=1)
    -        plt.ylim(0,np.max(count)+10)
    -        plt.ylabel(self.outName.title() + ' Histogram', **font)
    -        plt.xlabel(self.outName.title() , **font)
    -        plt.title('Counts', **font)
    +    X = poly.fit_transform(x[:, np.newaxis])
    +    estimated_mse_folds = cross_val_score(ridge, X, y[:, np.newaxis], scoring='neg_mean_squared_error', cv=kfold)
     
    -        #gaussian
    -        norm = 0
    -        for i in range(0,len(bins)-1):
    -            norm += (bins[i+1]-bins[i])*count[i]
    -        plt.plot(bins,  norm/(self.std * np.sqrt(2 * np.pi)) * np.exp( - (bins - self.avg)**2 / (2 * self.std**2) ), linewidth=1, color='r')
    -        plt.savefig(self.outName + "/hist.eps")
    -        plt.savefig(self.outName + "/hist.png")
    -        plt.clf()
    +    # cross_val_score return an array containing the estimated negative mse for every fold.
    +    # we have to the the mean of every array in order to get an estimate of the mse of the model
    +    estimated_mse_sklearn[i] = np.mean(-estimated_mse_folds)
     
    -    # Plot the Autocorrelation Function
    -    def plotAutocorrelation(self):
    -        font = {'fontname':'serif'}
    -        plt.plot(range(1, len(self.data)/2), self.acf[1:], 'r-')
    -        plt.ylim(-1, 1)
    -        plt.xlim(0, len(self.data)/2)
    -        plt.ylabel('Autocorrelation Function', **font)
    -        plt.xlabel('Lag', **font)
    -        plt.title('Autocorrelation', **font)
    -        plt.savefig(self.outName + "/autocorrelation.eps")
    -        plt.savefig(self.outName + "/autocorrelation.png")
    -        plt.clf()
    +    i += 1
     
    -    def plotBlocking(self):
    -        font = {'fontname':'serif'}
    -        plt.plot(self.blockSizes, self.varVec, 'r-')
    -        plt.ylabel('Variance', **font)
    -        plt.xlabel('Block Size', **font)
    -        plt.title('Blocking', **font)
    -        plt.savefig(self.outName + "/blocking.eps")
    -        plt.savefig(self.outName + "/blocking.png")
    -        plt.clf()
    +## Plot and compare the slightly different ways to perform cross-validation
     
    -    # Print Stuff to the Terminal
    -    def printOutput(self):
    -        print "\nSample Size:    \t", len(self.data)
    -        print "\n=========================================\n"
    -        print "Sample Average: \t", self.avg
    -        print "Sample Variance:\t", self.var
    -        print "Sample Std:     \t", self.std
    -        print "\n=========================================\n"
    -        print "Bootstrap Average: \t", self.bootAvg
    -        print "Bootstrap Variance:\t", self.bootVar
    -        print "Bootstrap Error:   \t", self.bootStd
    -        print "\n=========================================\n"
    -        print "Jackknife Average: \t", self.jackknAvg
    -        print "Jackknife Variance:\t", self.jackknVar
    -        print "Jackknife Error:   \t", self.jackknStd
    -        print "\n=========================================\n"
    -        print "Blocking Average: \t", self.blockingAvg
    -        print "Blocking Variance:\t", self.blockingVar
    -        print "Blocking Error:   \t", self.blockingStd, "\n"
    +plt.figure()
     
    -# Initialize the class
    -if len(argv) > 2:
    -    dataAnalysis = dataAnalysisClass(argv[1], int(argv[2]))
    -else:
    -    dataAnalysis = dataAnalysisClass(argv[1])
    +plt.plot(np.log10(lambdas), estimated_mse_sklearn, label = 'cross_val_score')
    +plt.plot(np.log10(lambdas), estimated_mse_KFold, 'r--', label = 'KFold')
     
    -# Run Analyses
    -dataAnalysis.runAllAnalyses()
    +plt.xlabel('log10(lambda)')
    +plt.ylabel('mse')
     
    -# Plot the data
    -dataAnalysis.plotAll()
    +plt.legend()
     
    -# Print Some Output
    -dataAnalysis.printOutput()
    +plt.show()
     











    -

    The bias-variance tradeoff

    +

    The bias-variance tradeoff

    -We begin with an unknown function \( y=f(x) \) and fix a \emph{hypothesis set} - \( \mathcal{H} \) consisting of all functions we are willing to consider, - defined also on the domain of \( f \). This set may be uncountably - infinite (e.g. if there are real-valued parameters to fit). -The - choice of which functions to include in \( \mathcal{H} \) usually depends - on our intuition about the problem of interest. The function \( f(x) \) - produces a set of pairs \( (x_i,y_i) \), \( i=1\dots N \), which serve as the - observable data. Our goal is to select a function from the hypothesis - set \( h\in\mathcal{H} \) which approximates \( f(x) \) as best as possible, - namely, we would like to find \( h\in\mathcal{H} \) such that \( h\approx - f \) in some strict mathematical sense which we specify below. If this - is possible, we say that we \emph{learned} \( f(x) \). But if the - function \( f(x) \) can, in principle, take any value on - \emph{unobserved} inputs, how is it possible to learn in any - meaningful sense? +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 + +$$ +\boldsymbol{y}=f(\boldsymbol{x}) + \boldsymbol{\epsilon} +$$ + +

    +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 +\( \boldsymbol{\beta} \) and the design matrix \( \boldsymbol{X} \) which embody our model, +that is \( \boldsymbol{\tilde{y}}=\boldsymbol{X}\boldsymbol{\beta} \). + +

    +Thereafter we found the parameters \( \boldsymbol{\beta} \) by optimizing the means squared error via the so-called cost function +$$ +C(\boldsymbol{X},\boldsymbol{\beta}) =\frac{1}{n}\sum_{i=0}^{n-1}(y_i-\tilde{y}_i)^2=\mathbb{E}\left[(\boldsymbol{y}-\boldsymbol{\tilde{y}})^2\right]. +$$ + +

    +We can rewrite this as +$$ +\mathbb{E}\left[(\boldsymbol{y}-\boldsymbol{\tilde{y}})^2\right]=\frac{1}{n}\sum_i(f_i-\mathbb{E}\left[\boldsymbol{\tilde{y}}\right])^2+\frac{1}{n}\sum_i(\tilde{y}_i-\mathbb{E}\left[\boldsymbol{\tilde{y}}\right])^2+\sigma^2. +$$ + +

    +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 \( \boldsymbol{\epsilon} \). + +

    +To derive this equation, we need to recall that the variance of \( \boldsymbol{y} \) and \( \boldsymbol{\epsilon} \) are both equal to \( \sigma^2 \). The mean value of \( \boldsymbol{\epsilon} \) is by definition equal to zero. Furthermore, the function \( f \) is not a stochastics variable, idem for \( \boldsymbol{\tilde{y}} \). +We use a more compact notation in terms of the expectation value +$$ +\mathbb{E}\left[(\boldsymbol{y}-\boldsymbol{\tilde{y}})^2\right]=\mathbb{E}\left[(\boldsymbol{f}+\boldsymbol{\epsilon}-\boldsymbol{\tilde{y}})^2\right], +$$ + +and adding and subtracting \( \mathbb{E}\left[\boldsymbol{\tilde{y}}\right] \) we get +$$ +\mathbb{E}\left[(\boldsymbol{y}-\boldsymbol{\tilde{y}})^2\right]=\mathbb{E}\left[(\boldsymbol{f}+\boldsymbol{\epsilon}-\boldsymbol{\tilde{y}}+\mathbb{E}\left[\boldsymbol{\tilde{y}}\right]-\mathbb{E}\left[\boldsymbol{\tilde{y}}\right])^2\right], +$$ + +which, using the abovementioned expectation values can be rewritten as +$$ +\mathbb{E}\left[(\boldsymbol{y}-\boldsymbol{\tilde{y}})^2\right]=\mathbb{E}\left[(\boldsymbol{y}-\mathbb{E}\left[\boldsymbol{\tilde{y}}\right])^2\right]+\mathrm{Var}\left[\boldsymbol{\tilde{y}}\right]+\sigma^2, +$$ + +that is the rewriting in terms of the so-called bias, the variance of the model \( \boldsymbol{\tilde{y}} \) and the variance of \( \boldsymbol{\epsilon} \). + +

    +









    + +

    Example code for Bias-Variance tradeoff

    +

    + + +

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

    +









    + +

    Understanding what happens

    +

    + + +

    import matplotlib.pyplot as plt
    +import numpy as np
    +from sklearn.linear_model import LinearRegression, Ridge, Lasso
    +from sklearn.preprocessing import PolynomialFeatures
    +from sklearn.model_selection import train_test_split
    +from sklearn.pipeline import make_pipeline
    +from sklearn.utils import resample
    +
    +np.random.seed(2018)
    +
    +n = 40
    +n_boostraps = 100
    +maxdegree = 14
    +
    +
    +# Make data set.
    +x = np.linspace(-3, 3, n).reshape(-1, 1)
    +y = np.exp(-x**2) + 1.5 * np.exp(-(x-2)**2)+ np.random.normal(0, 0.1, x.shape)
    +error = np.zeros(maxdegree)
    +bias = np.zeros(maxdegree)
    +variance = np.zeros(maxdegree)
    +polydegree = np.zeros(maxdegree)
    +x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.2)
    +
    +for degree in range(maxdegree):
    +    model = make_pipeline(PolynomialFeatures(degree=degree), LinearRegression(fit_intercept=False))
    +    y_pred = np.empty((y_test.shape[0], n_boostraps))
    +    for i in range(n_boostraps):
    +        x_, y_ = resample(x_train, y_train)
    +        y_pred[:, i] = model.fit(x_, y_).predict(x_test).ravel()
    +
    +    polydegree[degree] = degree
    +    error[degree] = np.mean( np.mean((y_test - y_pred)**2, axis=1, keepdims=True) )
    +    bias[degree] = np.mean( (y_test - np.mean(y_pred, axis=1, keepdims=True))**2 )
    +    variance[degree] = np.mean( np.var(y_pred, axis=1, keepdims=True) )
    +    print('Polynomial degree:', degree)
    +    print('Error:', error[degree])
    +    print('Bias^2:', bias[degree])
    +    print('Var:', variance[degree])
    +    print('{} >= {} + {} = {}'.format(error[degree], bias[degree], variance[degree], bias[degree]+variance[degree]))
    +
    +plt.plot(polydegree, np.log10(error), label='Error')
    +plt.plot(polydegree, bias, label='bias')
    +plt.plot(polydegree, variance, label='Variance')
    +plt.legend()
    +plt.show()
    +

    -

    Training and testing data

    - -

    -We will discuss the bias-variance tradeoff in the context of continuous predictions such as regression. However, many of the intuitions and ideas discussed here also carry over to classification tasks. Consider a dataset \( \mathcal{L} \) consisting of the data \( \mathbf{X}_\mathcal{L}=\{(y_j, \boldsymbol{x}_j), j=1\ldots N\} \). Let us assume that the true data is generated from a noisy model -$$ -y=f(\boldsymbol{x}) + \epsilon -$$ - -where \( \epsilon \) is normally distributed with mean zero and standard deviation \( \sigma_\epsilon \). - -

    -









    - -

    Procedure to find a predictor

    - -

    -We have a statistical procedure (e.g. least-squares regression) for -forming a predictor \( \hat{g}_{\mathcal{L}}(\boldsymbol{x}) \) that gives the -prediction of our model for a new data point \( \boldsymbol{x} \). This estimator -is chosen by minimizing a cost function which we take to be the -squared error - -$$ - \mathcal{C}( \boldsymbol{X}, \hat{g}(\boldsymbol{x})) = \sum_i (y_i - \hat{g}_\mathcal{L}(\boldsymbol{x}_i))^2. -$$ - -

    -









    - -

    What we want

    - -

    -We are interested in the generalization error on all data drawn from -the true model, not just the error on the particular training dataset -\( \mathcal{L} \) that we have in hand. This is just the expectation of -the cost function over many different data sets -\( \{\mathcal{L}_j\} \). Denote this expectation value by -\( E_{\mathcal{L}} \). In other words, we can view \( \hat{g}_{\mathcal{L}} \) -as a stochastic functional that depends on the dataset \( \mathcal{L} \) -and we can think of \( E_{\mathcal{L}} \) as the expected value of the -functional if we drew an infinite number of datasets \( \{\mathcal{L}_1, -\mathcal{L}_2, \ldots \} \). - -

    -









    - -

    The expected generalization error

    - -

    -We would also like to average over different instances of the -"noise" \( \epsilon \) and we denote the expectation value over the -noise by \( E_\epsilon \). Thus, we can decompose the expected -generalization error as - -$$ -\begin{align} -E_\mathcal{L, \epsilon}[\mathcal{C}( \boldsymbol{X}, \hat{g}(\boldsymbol{x})) ]&= E_\mathcal{L,\epsilon}\left[ \sum_i ({y}_i - \hat{g}_\mathcal{L}(\boldsymbol{x}_i))^2 \right] \nonumber \\ - &= E_\mathcal{L, \epsilon}\left[ \sum_{i}({y}_i -f(\boldsymbol{x}_i) +f(\boldsymbol{x}_i)- \hat{g}_\mathcal{L}(\boldsymbol{x}_i))^2\right] \nonumber \\ - &= \sum_i E_\epsilon[ ({y}_i -f(\boldsymbol{x}_i))^2 ]+ E_\mathcal{L, \epsilon}[(f(\boldsymbol{x}_i)- \hat{g}_\mathcal{L}(\boldsymbol{x}_i))^2] + 2E_\epsilon[{y}_i -f(\boldsymbol{x}_i)]E_\mathcal{L}[f(\boldsymbol{x}_i)- \hat{g}_\mathcal{L}(\boldsymbol{x}_i)] \nonumber \\ - &=\sum_i \sigma_\epsilon^2 + E_\mathcal{L}[(f(\boldsymbol{x}_i)- \hat{g}_\mathcal{L}(\boldsymbol{x}_i))^2], -\label{_auto17} -\end{align} -$$ - -

    -where in the last line we used the fact that our noise has zero mean -and variance \( \sigma_\epsilon^2 \) and the sum over \( i \) applies to all -terms. - -

    -









    - -

    Elaborating a little bit more

    - -

    -It is also helpful to further decompose the second term as -follows: - -$$ -\begin{align} -E_\mathcal{L}[(f(\boldsymbol{x}_i)- \hat{g}_\mathcal{L}(\boldsymbol{x}_i))^2] &=E_\mathcal{L}[(f(\mathbf{x}_i)-E_\mathcal{L}[\hat{g}_\mathcal{L}(\boldsymbol{x}_i)]+ E_\mathcal{L}[\hat{g}_\mathcal{L}(\boldsymbol{x}_i)]- \hat{g}_\mathcal{L}(\boldsymbol{x}_i))^2] \nonumber \\ -&=E_\mathcal{L}[(f(\boldsymbol{x}_i)-E_\mathcal{L}[\hat{g}_\mathcal{L}(\boldsymbol{x}_i)])^2] + E_\mathcal{L}[( \hat{g}_\mathcal{L}(\boldsymbol{x}_i)-E_\mathcal{L}[\hat{g}_\mathcal{L}(\boldsymbol{x}_i)])^2] \nonumber \\ -&+2E_\mathcal{L}[(f(\boldsymbol{x}_i)-E_\mathcal{L}[\hat{g}_\mathcal{L}(\boldsymbol{x}_i)])( \hat{g}_\mathcal{L}(\boldsymbol{x}_i)-E_\mathcal{L}[\hat{g}_\mathcal{L}(\boldsymbol{x}_i)])] \nonumber \\ -&=(f(\boldsymbol{x}_i)-E_\mathcal{L}[\hat{g}_\mathcal{L}(\boldsymbol{x}_i)])^2+E_\mathcal{L}[( \hat{g}_\mathcal{L}(\boldsymbol{x}_i)-E_\mathcal{L}[\hat{g}_\mathcal{L}(\boldsymbol{x}_i)])^2]. -\label{_auto18} -\end{align} -$$ - -

    -









    - -

    The bias

    - -

    -The first term is called the bias -$$ -Bias^2= \sum_i (f(\boldsymbol{x}_i)-E_\mathcal{L}[\hat{g}_\mathcal{L}(\boldsymbol{x}_i)])^2 -$$ - -and measures the deviation of the expectation value of our estimator (i.e. the asymptotic value of our estimator in the infinite data limit) from the true value. - -

    -









    - -

    The variance

    -The second term is called the variance -$$ -Var=\sum_i E_\mathcal{L}[( \hat{g}_\mathcal{L}(\boldsymbol{x}_i)-E_\mathcal{L}[\hat{g}_\mathcal{L}(\boldsymbol{x}_i)])^2], -$$ - -

    -and measures how much our estimator fluctuates due to finite-sample effects. Combining these expressions, we see that the expected out-of-sample error of our model can be decomposed as -$$ -E_\mathrm{out}=E_\mathcal{L, \epsilon}[\mathcal{C}( \boldsymbol{X}, \hat{g}(\boldsymbol{x})) ] = Bias^2 + Var + Noise. -$$ +

    Summing up

    The bias-variance tradeoff summarizes the fundamental tension in machine learning, particularly supervised learning, between the complexity of a model and the amount of training data needed to train it. Since data is often limited, in practice it is often useful to -use a less-complex model with higher bias – a model whose asymptotic -performance is worse than another model – because it is easier to +use a less-complex model with higher bias, that is a model whose asymptotic +performance is worse than another model because it is easier to train and less sensitive to sampling noise arising from having a finite-sized training dataset (smaller variance). -

    - - -

    Summing up

    -

    The above equations tell us that in order to minimize the expected test error, we need to select a @@ -3503,15 +3650,99 @@ flexible statistical methods have higher variance.











    -

    The one-dimensional Ising model, project 2

    +

    Another Example rom Scikit-Learn's Repository

    +

    + + +

    """
    +============================
    +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()
    +
    +

    +









    + +

    The one-dimensional Ising model

    -The one-dimensional Ising model with nearest neighbor interaction, no external field and a constant coupling constant \( J \) is given by +Let us bring back the Ising model again, but now with an additional +focus on Ridge and Lasso regression as well. We repeat some of the +basic parts of the Ising model and the setup of the training and test +data. The one-dimensional Ising model with nearest neighbor +interaction, no external field and a constant coupling constant \( J \) is +given by $$ \begin{align} H = -J \sum_{k}^L s_k s_{k + 1}, -\label{_auto19} +\label{_auto17} \end{align} $$ @@ -3545,25 +3776,13 @@ energies = np.< for i in range(n): energies[i] = - J * np.dot(spins[i], np.roll(spins[i], 1))

    -

    -Here we use linear (ordinary least squares), ridge and LASSO -regression to predict the energy in the nearest neighbor -one-dimensional Ising model on a ring, i.e., the endpoints wrap -around. We will use the linear regression models to fit a value for -the coupling constant to achieve this. - -

    -









    - -

    Reformulating the problem to suit regression

    -

    A more general form for the one-dimensional Ising model is $$ \begin{align} H = - \sum_j^L \sum_k^L s_j s_k J_{jk}. -\label{_auto20} +\label{_auto18} \end{align} $$ @@ -3574,7 +3793,7 @@ a matrix-product on the form $$ \begin{align} H = X J, -\label{_auto21} +\label{_auto19} \end{align} $$ @@ -3584,11 +3803,12 @@ elements \( -J_{jk} \). This form of writing the energy fits perfectly with the form utilized in linear regression, viz. $$ \begin{align} - y = X\omega + \epsilon, -\label{_auto22} + \boldsymbol{y} = \boldsymbol{X}\boldsymbol{\beta} + \boldsymbol{\epsilon}. +\label{_auto20} \end{align} $$ +We organize the data as we did above

    @@ -3609,149 +3829,7 @@ X_test_own = np )

    -









    - -

    Linear regression

    - -

    -The problem at hand is to try to fit the equation -$$ -\begin{align} - y = f(x) + \epsilon, -\label{_auto23} -\end{align} -$$ - -

    -where \( f(x) \) is some unknown function of the data \( x \) and \( \epsilon \) -is normally distributed with mean zero noise with standard deviation -\( \sigma_{\epsilon} \). Our job is to try to find a predictor which -estimates the function \( f(x) \). In linear regression we assume that we -can formulate the problem as - -$$ -\begin{align} - y = X\omega + \epsilon, -\label{_auto24} -\end{align} -$$ - -

    -where \( X \) and \( \omega \) are now matrices. Our job at hand is now to -find a cost function \( C \), which we wish to minimize in order to find -the best estimate of \( \omega \). - -

    -









    - -

    Ordinary least squares

    - -

    -In the ordinary least squares method we choose the cost function -$$ -\begin{align} - C(X, \omega) = ||X\omega - y||^2 - = (X\omega - y)^T(X\omega - y) -\label{_auto25} -\end{align} -$$ - -We then find the extremal point of \( C \) by taking the derivative with respect to \( \omega \) and setting it to zero, i.e., - -$$ -\begin{align} - \dfrac{\mathrm{d}C}{\mathrm{d}\omega} - = 0. -\label{_auto26} -\end{align} -$$ - -This yields the expression for \( \omega \) to be -$$ -\begin{align} - \omega = \frac{X^T y}{X^T X}, -\label{_auto27} -\end{align} -$$ - -

    -which immediately imposes some requirements on \( X \) as there must exist -an inverse of \( X^T X \). If the expression we are modelling contains an -intercept, i.e., a constant expression we must make sure that the -first column of \( X \) consists of \( 1 \). - -

    - - -

    def get_ols_weights_naive(x: np.ndarray, y: np.ndarray) -> np.ndarray:
    -    return scl.inv(x.T @ x) @ (x.T @ y)
    -omega = get_ols_weights_naive(X_train_own, y_train)
    -
    -

    -









    - -

    Singular Value decomposition

    -Doing the inversion directly turns out to be a bad idea as the matrix -\( X^TX \) is singular. An alternative approach is to use the singular -value decomposition. Using the definition of the Moore-Penrose -pseudoinverse we can write the equation for \( \omega \) as - -$$ -\begin{align} - \omega = X^{+}y, -\label{_auto28} -\end{align} -$$ - -where the pseudoinverse of \( X \) is given by -$$ -\begin{align} - X^{+} = \frac{X^T}{X^T X}. -\label{_auto29} -\end{align} -$$ - -

    -Using singular value decomposition we have that \( X = U\Sigma V^T \), -where \( X^{+} = V\Sigma^{+} U^T \). This reduces the equation for -\( \omega \) to -$$ -\begin{align} - \omega = V\Sigma^{+} U^T y. -\label{_auto30} -\end{align} -$$ - -

    -Note that solving this equation by actually doing the pseudoinverse -(which is what we will do) is not a good idea as this operation scales -as \( \mathcal{O}(n^3) \), where \( n \) is the number of elements in a -general matrix. Instead, doing \( QR \)-factorization and solving the -linear system as an equation would reduce this down to -\( \mathcal{O}(n^2) \) operations. - -

    - - -

    def get_ols_weights(x: np.ndarray, y: np.ndarray) -> np.ndarray:
    -    u, s, v = scl.svd(x)
    -    return v.T @ scl.pinv(scl.diagsvd(s, u.shape[0], v.shape[0])) @ u.T @ y
    -
    -

    -Before passing in the data to the function we append a column with ones to the training data. - -

    - - -

    omega = get_ols_weights(X_train_own,y_train)
    -
    -

    -









    - -

    Fitting with scikit-learn

    - -

    -Next we fit a LinearRegression-model from Scikit-learn for comparison. +We will do all fitting with Scikit-Learn,

    @@ -3759,29 +3837,18 @@ Next we fit a LinearRegression-model from Scikit-learn for comparis

    clf = skl.LinearRegression().fit(X_train, y_train)
     

    -Extracting the \( J \)-matrix from both our own method and the Scikit-learn model where we make sure to remove the intercept. - +When extracting the \( J \)-matrix we make sure to remove the intercept

    -

    J_own = omega[1:].reshape(L, L)
    -J_sk = clf.coef_.reshape(L, L)
    +
    J_sk = clf.coef_.reshape(L, L)
     

    -A way of looking at the coefficients in \( J \) is to plot the matrices as images. - +And then we plot the results

    fig = plt.figure(figsize=(20, 14))
    -im = plt.imshow(J_own, **cmap_args)
    -plt.title("Home-made OLS", fontsize=18)
    -plt.xticks(fontsize=18)
    -plt.yticks(fontsize=18)
    -cb = fig.colorbar(im)
    -cb.ax.set_yticklabels(cb.ax.get_yticklabels(), fontsize=18)
    -
    -fig = plt.figure(figsize=(20, 14))
     im = plt.imshow(J_sk, **cmap_args)
     plt.title("LinearRegression from Scikit-learn", fontsize=18)
     plt.xticks(fontsize=18)
    @@ -3791,66 +3858,33 @@ cb.ax.se
     plt.show()
     

    -We can see that our model for the least squares method performes close -to the benchmark from Scikit-learn. It is interesting to note that OLS -considers both \( J_{j, j + 1} = -0.5 \) and \( J_{j, j - 1} = -0.5 \) as -valid matrix elements for \( J \). +The results perfectly with our previous discussion where we used our own code.











    -

    Ridge regression

    +

    Ridge regression

    Having explored the ordinary least squares we move on to ridge regression. In ridge regression we include a regularizer. This involves a new cost function which leads to a new estimate for the -weights \( \omega \). This results in a penalized regression problem. The +weights \( \boldsymbol{\beta} \). This results in a penalized regression problem. The cost function is given by $$ \begin{align} - C(X, \omega; \lambda) = ||X\omega - y||^2 + \lambda ||\omega||^2 - = (X\omega - y)^T(X\omega - y) + \lambda \omega^T\omega. -\label{_auto31} + C(\boldsymbol{X}, \boldsymbol{\beta}; \lambda) = (\boldsymbol{X}\boldsymbol{\beta} - \boldsymbol{y})^T(\boldsymbol{X}\boldsymbol{\beta} - \boldsymbol{y}) + \lambda \boldsymbol{\beta}^T\boldsymbol{\beta}. +\label{_auto21} \end{align} $$ -Finding the extremum of this function yields the weights - -$$ -\begin{align} - \omega(\lambda) = \frac{X^Ty}{X^TX + \lambda} \to \frac{\omega_{\text{LS}}}{1 + \lambda}, -\label{_auto32} -\end{align} -$$ - -

    -where \( \omega_{\text{LS}} \) is the weights from ordinary least -squares. The last assumption assumes that \( X \) is orthogonal, which it -is not. We will therefore resort to solving the equation as it stands -on the left hand side. -

    -

    def get_ridge_weights(x: np.ndarray, y: np.ndarray, _lambda: float) -> np.ndarray:
    -    return x.T @ y @ scl.inv(
    -        x.T @ x + np.eye(x.shape[1], x.shape[1]) * _lambda
    -    )
    -_lambda = 0.1
    -omega_ridge = get_ridge_weights(X_train_own, y_train, np.array([_lambda]))
    +
    _lambda = 0.1
     clf_ridge = skl.Ridge(alpha=_lambda).fit(X_train, y_train)
    -J_ridge_own = omega_ridge[1:].reshape(L, L)
     J_ridge_sk = clf_ridge.coef_.reshape(L, L)
    -fig = plt.figure(figsize=(20, 14))
    -im = plt.imshow(J_ridge_own, **cmap_args)
    -plt.title("Home-made ridge regression", fontsize=18)
    -plt.xticks(fontsize=18)
    -plt.yticks(fontsize=18)
    -cb = fig.colorbar(im)
    -cb.ax.set_yticklabels(cb.ax.get_yticklabels(), fontsize=18)
    -
     fig = plt.figure(figsize=(20, 14))
     im = plt.imshow(J_ridge_sk, **cmap_args)
     plt.title("Ridge from Scikit-learn", fontsize=18)
    @@ -3864,20 +3898,20 @@ plt.show()
     











    -

    LASSO regression

    +

    LASSO regression

    In the Least Absolute Shrinkage and Selection Operator (LASSO)-method we get a third cost function. + $$ \begin{align} - C(X, \omega; \lambda) = - ||X\omega - y||^2 + \lambda ||\omega|| - = (X\omega - y)^T(X\omega - y) + \lambda \sqrt{\omega^T\omega}. -\label{_auto33} + C(\boldsymbol{X}, \boldsymbol{\beta}; \lambda) = (\boldsymbol{X}\boldsymbol{\beta} - \boldsymbol{y})^T(\boldsymbol{X}\boldsymbol{\beta} - \boldsymbol{y}) + \lambda \sqrt{\boldsymbol{\beta}^T\boldsymbol{\beta}}. +\label{_auto22} \end{align} $$ -Finding the extremal point of this cost function is not so straight-forward as in least squares and ridge. We will therefore rely solely on the function ``Lasso`` from Scikit-learn. +

    +Finding the extremal point of this cost function is not so straight-forward as in least squares and ridge. We will therefore rely solely on the function ``Lasso`` from Scikit-Learn.

    @@ -3902,41 +3936,7 @@ constant as opposed to ridge and OLS. We get a sparse solution with











    -

    Performance of the different models

    - -

    -In order to judge which model performs best at varying values of \( \lambda \) (for ridge and LASSO) we compute \( R^2 \) which is given by - -$$ -\begin{align} - R^2 = 1 - \frac{(y - \hat{y})^2}{(y - \bar{y})^2}, -\label{_auto34} -\end{align} -$$ - -where \( y \) is a vector with the true values of the energy, \( \hat{y} \) is the predicted values of \( y \) from the models and \( \bar{y} \) is the mean of \( \hat{y} \). - -

    - - -

    def r_squared(y, y_hat):
    -    return 1 - np.sum((y - y_hat) ** 2) / np.sum((y - np.mean(y_hat)) ** 2)
    -
    -

    -This is the same metric used by Scikit-learn for their regression models when scoring. -

    - - -

    y_hat = clf.predict(X_test)
    -r_test = r_squared(y_test, y_hat)
    -sk_r_test = clf.score(X_test, y_test)
    -
    -assert abs(r_test - sk_r_test) < 1e-2
    -
    -

    -









    - -

    Performance as function of the regularization parameter

    +

    Performance as function of the regularization parameter

    We see how the different models perform for a different set of values for \( \lambda \). @@ -3947,17 +3947,13 @@ We see how the different models perform for a different set of values for \( \la

    lambdas = np.logspace(-4, 5, 10)
     
     train_errors = {
    -    "ols_own": np.zeros(lambdas.size),
         "ols_sk": np.zeros(lambdas.size),
    -    "ridge_own": np.zeros(lambdas.size),
         "ridge_sk": np.zeros(lambdas.size),
         "lasso_sk": np.zeros(lambdas.size)
     }
     
     test_errors = {
    -    "ols_own": np.zeros(lambdas.size),
         "ols_sk": np.zeros(lambdas.size),
    -    "ridge_own": np.zeros(lambdas.size),
         "ridge_sk": np.zeros(lambdas.size),
         "lasso_sk": np.zeros(lambdas.size)
     }
    @@ -3967,30 +3963,6 @@ plot_counter = 
     fig = plt.figure(figsize=(32, 54))
     
     for i, _lambda in enumerate(tqdm.tqdm(lambdas)):
    -    omega = get_ols_weights(X_train_own, y_train)
    -    y_hat_train = X_train_own @ omega
    -    y_hat_test = X_test_own @ omega
    -
    -    train_errors["ols_own"][i] = r_squared(y_train, y_hat_train)
    -    test_errors["ols_own"][i] = r_squared(y_test, y_hat_test)
    -
    -    plt.subplot(10, 5, plot_counter)
    -    plt.imshow(omega[1:].reshape(L, L), **cmap_args)
    -    plt.title("Home made OLS")
    -    plot_counter += 1
    -
    -    omega = get_ridge_weights(X_train_own, y_train, _lambda)
    -    y_hat_train = X_train_own @ omega
    -    y_hat_test = X_test_own @ omega
    -
    -    train_errors["ridge_own"][i] = r_squared(y_train, y_hat_train)
    -    test_errors["ridge_own"][i] = r_squared(y_test, y_hat_test)
    -
    -    plt.subplot(10, 5, plot_counter)
    -    plt.imshow(omega[1:].reshape(L, L), **cmap_args)
    -    plt.title(r"Home made ridge, $\lambda = %.4f$" % _lambda)
    -    plot_counter += 1
    -
         for key, method in zip(
             ["ols_sk", "ridge_sk", "lasso_sk"],
             [skl.LinearRegression(), skl.Ridge(alpha=_lambda), skl.Lasso(alpha=_lambda)]
    @@ -4010,7 +3982,7 @@ fig = plt..show()
     

    -We can see that LASSO quite fast reaches a good solution for low +We see that LASSO reaches a good solution for low values of \( \lambda \), but will "wither" when we increase \( \lambda \) too much. Ridge is more stable over a larger range of values for \( \lambda \), but eventually also fades away. @@ -4018,7 +3990,7 @@ much. Ridge is more stable over a larger range of values for











    -

    Finding the optimal value of \( \lambda \)

    +

    Finding the optimal value of \( \lambda \)

    To determine which value of \( \lambda \) is best we plot the accuracy of @@ -4034,8 +4006,6 @@ testing set that is close to the accuracy of the training set.

    fig = plt.figure(figsize=(20, 14))
     
     colors = {
    -    "ols_own": "b",
    -    "ridge_own": "g",
         "ols_sk": "r",
         "ridge_sk": "y",
         "lasso_sk": "c"
    @@ -4058,9 +4028,6 @@ colors = {
             label="Test {0}".format(key),
             linewidth=4.0
         )
    -#plt.semilogx(lambdas, train_errors["ols_own"], label="Train (OLS own)")
    -#plt.semilogx(lambdas, test_errors["ols_own"], label="Test (OLS own)")
    -
     plt.legend(loc="best", fontsize=18)
     plt.xlabel(r"$\lambda$", fontsize=18)
     plt.ylabel(r"$R^2$", fontsize=18)
    @@ -4069,14 +4036,245 @@ plt.show()
     

    From the above figure we can see that LASSO with \( \lambda = 10^{-2} \) -achieve a very good accuracy on the test set. This by far surpases the +achieves a very good accuracy on the test set. This by far surpasses the other models for all values of \( \lambda \). +

    +









    + +

    Further Exercises

    + +

    Exercise 1

    + +

    +We will generate our own dataset for a function \( y(x) \) where \( x \in [0,1] \) and defined by random numbers computed with the uniform distribution. The function \( y \) is a quadratic polynomial in \( x \) with added stochastic noise according to the normal distribution \( \cal {N}(0,1) \). +The following simple Python instructions define our \( x \) and \( y \) values (with 100 data points). +

    + + +

    x = np.random.rand(100,1)
    +y = 5*x*x+0.1*np.random.randn(100,1)
    +
    +
      +
    1. Write your own code (following the examples above) for computing the parametrization of the data set fitting a second-order polynomial.
    2. +
    3. Use thereafter scikit-learn (see again the examples in the regression slides) and compare with your own code.
    4. +
    5. Using scikit-learn, compute also the mean square error, a risk metric corresponding to the expected value of the squared (quadratic) error defined as
    6. +
    + +$$ MSE(\hat{y},\hat{\tilde{y}}) = \frac{1}{n} +\sum_{i=0}^{n-1}(y_i-\tilde{y}_i)^2, +$$ + +and the \( R^2 \) score function. +If \( \tilde{\hat{y}}_i \) is the predicted value of the \( i-th \) sample and \( y_i \) is the corresponding true value, then the score \( R^2 \) is defined as +$$ +R^2(\hat{y}, \tilde{\hat{y}}) = 1 - \frac{\sum_{i=0}^{n - 1} (y_i - \tilde{y}_i)^2}{\sum_{i=0}^{n - 1} (y_i - \bar{y})^2}, +$$ + +where we have defined the mean value of \( \hat{y} \) as +$$ +\bar{y} = \frac{1}{n} \sum_{i=0}^{n - 1} y_i. +$$ + +

    +You can use the functionality included in scikit-learn. If you feel +for it, you can use your own program and define functions which +compute the above two functions. Discuss the meaning of these +results. Try also to vary the coefficient in front of the added +stochastic noise term and discuss the quality of the fits. + +

    Exercise 2, variance of the parameters \( \beta \) in linear regression

    + +

    +Show that the variance of the parameters \( \beta \) in the linear regression method (chapter 3, equation (3.8) of Trevor Hastie, Robert Tibshirani, Jerome H. Friedman, The Elements of Statistical Learning, Springer) is given as + +$$ +\mathrm{Var}(\hat{\beta}) = \left(\hat{X}^T\hat{X}\right)^{-1}\sigma^2, +$$ + +with +$$ +\sigma^2 = \frac{1}{N-p-1}\sum_{i=1}^{N} (y_i-\tilde{y}_i)^2, +$$ + +where we have assumed that we fit a function of degree \( p-1 \) (for example a polynomial in \( x \)). + +

    Exercise 3

    + +

    +This exercise is a continuation of exercise 1. We will +use the same function to generate our data set, still staying with a +simple function \( y(x) \) which we want to fit using linear regression, +but now extending the analysis to include the Ridge and the Lasso +regression methods. You can use the code under the Regression as an example on how to use the Ridge and the Lasso methods. + +

    +We will thus again generate our own dataset for a function \( y(x) \) where +\( x \in [0,1] \) and defined by random numbers computed with the uniform +distribution. The function \( y \) is a quadratic polynomial in \( x \) with +added stochastic noise according to the normal distribution \( \cal{N}(0,1) \). + +

    +The following simple Python instructions define our \( x \) and \( y \) values (with 100 data points). +

    + + +

    x = np.random.rand(100,1)
    +y = 5*x*x+0.1*np.random.randn(100,1)
    +
    +
      +
    1. Write your own code for the Ridge method and compute the parametrization for different values of \( \lambda \). Compare and analyze your results with those from exercise 1. Study the dependence on \( \lambda \) while also varying the strength of the noise in your expression for \( y(x) \).
    2. +
    3. Repeat the above but using the functionality of scikit-learn. Compare your code with the results from scikit-learn. Remember to run with the same random numbers for generating \( x \) and \( y \).
    4. +
    5. Our next step is to study the variance of the parameters \( \beta_1 \) and \( \beta_2 \) (assuming that we are parametrizing our function with a second-order polynomial. We will use standard linear regression and the Ridge regression. You can now opt for either writing your own function that calculates the variance of these paramaters (recall that this is equal to the diagonal elements of the matrix \( (\hat{X}^T\hat{X})+\lambda\hat{I})^{-1} \)) or use the functionality of scikit-learn and compute their variances. Discuss the results of these variances as functions
    6. +
    7. Repeat the previous step but add now the Lasso method. Discuss your results and compare with standard regression and the Ridge regression results.
    8. +
    9. Try to implement the cross-validation as well.
    10. +
    11. Finally, using scikit-learn or your own code, compute also the mean square error, a risk metric corresponding to the expected value of the squared (quadratic) error defined as
    12. +
    + +$$ MSE(\hat{y},\hat{\tilde{y}}) = \frac{1}{n} +\sum_{i=0}^{n-1}(y_i-\tilde{y}_i)^2, +$$ + +and the \( R^2 \) score function. +If \( \tilde{\hat{y}}_i \) is the predicted value of the \( i-th \) sample and \( y_i \) is the corresponding true value, then the score \( R^2 \) is defined as +$$ +R^2(\hat{y}, \tilde{\hat{y}}) = 1 - \frac{\sum_{i=0}^{n - 1} (y_i - \tilde{y}_i)^2}{\sum_{i=0}^{n - 1} (y_i - \bar{y})^2}, +$$ + +where we have defined the mean value of \( \hat{y} \) as +$$ +\bar{y} = \frac{1}{n} \sum_{i=0}^{n - 1} y_i. +$$ + +Discuss these quantities as functions of the variable \( \lambda \) in the Ridge and Lasso regression methods. + +

    Exercise 4

    + +

    +We will study how +to fit polynomials to a specific two-dimensional function called +Franke's +function. This +is a function which has been widely used when testing various interpolation and fitting +algorithms. Furthermore, after having established the model and the +method, we will employ resamling techniques such as the cross-validation and/or +the bootstrap methods, in order to perform a proper assessment of our models. + +

    +The Franke function, which is a weighted sum of four exponentials reads as follows +$$ +\begin{align*} +f(x,y) &= \frac{3}{4}\exp{\left(-\frac{(9x-2)^2}{4} - \frac{(9y-2)^2}{4}\right)}+\frac{3}{4}\exp{\left(-\frac{(9x+1)^2}{49}- \frac{(9y+1)}{10}\right)} \\ +&+\frac{1}{2}\exp{\left(-\frac{(9x-7)^2}{4} - \frac{(9y-3)^2}{4}\right)} -\frac{1}{5}\exp{\left(-(9x-4)^2 - (9y-7)^2\right) }. +\end{align*} +$$ + +

    +The function will be defined for \( x,y\in [0,1] \). Our first step will +be to perform an OLS regression analysis of this function, trying out +a polynomial fit with an \( x \) and \( y \) dependence of the form \( [x, y, +x^2, y^2, xy, \dots] \). We will also include cross-validation and +bootstrap as resampling techniques. As in homeworks 1 and 2, we +can use a uniform distribution to set up the arrays of values for \( x \) +and \( y \), or as in the example below just a fix values for \( x \) and \( y \) with a given step size. +In this case we will have two predictors and need to fit a +function (for example a polynomial) of \( x \) and \( y \). Thereafter we will +repeat much of the same procedure using the the Ridge and +Lasso regression methods, introducing thus a dependence on the bias +(penalty) \( \lambda \). + +

    +The Python fucntion for the Franke function is included here (it performs also a three-dimensional plot of it) +

    + + +

    from mpl_toolkits.mplot3d import Axes3D
    +import matplotlib.pyplot as plt
    +from matplotlib import cm
    +from matplotlib.ticker import LinearLocator, FormatStrFormatter
    +import numpy as np
    +from random import random, seed
    +
    +fig = plt.figure()
    +ax = fig.gca(projection='3d')
    +
    +# Make data.
    +x = np.arange(0, 1, 0.05)
    +y = np.arange(0, 1, 0.05)
    +x, y = np.meshgrid(x,y)
    +
    +
    +def FrankeFunction(x,y):
    +    term1 = 0.75*np.exp(-(0.25*(9*x-2)**2) - 0.25*((9*y-2)**2))
    +    term2 = 0.75*np.exp(-((9*x+1)**2)/49.0 - 0.1*(9*y+1))
    +    term3 = 0.5*np.exp(-(9*x-7)**2/4.0 - 0.25*((9*y-3)**2))
    +    term4 = -0.2*np.exp(-(9*x-4)**2 - (9*y-7)**2)
    +    return term1 + term2 + term3 + term4
    +
    +
    +z = FrankeFunction(x, y)
    +
    +# Plot the surface.
    +surf = ax.plot_surface(x, y, z, cmap=cm.coolwarm,
    +                       linewidth=0, antialiased=False)
    +
    +# Customize the z axis.
    +ax.set_zlim(-0.10, 1.40)
    +ax.zaxis.set_major_locator(LinearLocator(10))
    +ax.zaxis.set_major_formatter(FormatStrFormatter('%.02f'))
    +
    +# Add a color bar which maps values to colors.
    +fig.colorbar(surf, shrink=0.5, aspect=5)
    +
    +plt.show()
    +
    +

    +We will thus again generate our own dataset for a function \( \mathrm{FrankeFunction}(x,y) \) where +\( x,y \in [0,1] \) could be defined by random numbers computed with the uniform +distribution. The function \( f(x,y) \) is the Franke function. You should explore also the addition +an added stochastic noise to this function using the normal distribution \( \cal{N}(0,1) \). + +

    +Write your own code (using either a matrix inversion or a singular value decomposition from e.g., numpy ) or use your code from exercises 1 and 3 +and perform a standard least square regression analysis using polynomials in \( x \) and \( y \) up to fifth order. Find the confidence intervals of the parameters \( \beta \) by computing their variances, evaluate the Mean Squared error (MSE) +$$ MSE(\hat{y},\hat{\tilde{y}}) = \frac{1}{n} +\sum_{i=0}^{n-1}(y_i-\tilde{y}_i)^2, +$$ + +and the \( R^2 \) score function. +If \( \tilde{\hat{y}}_i \) is the predicted value of the \( i-th \) sample and \( y_i \) is the corresponding true value, then the score \( R^2 \) is defined as +$$ +R^2(\hat{y}, \tilde{\hat{y}}) = 1 - \frac{\sum_{i=0}^{n - 1} (y_i - \tilde{y}_i)^2}{\sum_{i=0}^{n - 1} (y_i - \bar{y})^2}, +$$ + +where we have defined the mean value of \( \hat{y} \) as +$$ +\bar{y} = \frac{1}{n} \sum_{i=0}^{n - 1} y_i. +$$ + +

    +Perform a resampling of the data where you split the data in training data and test data. Implement the \( k \)-fold cross-validation algorithm and/or the bootstrap algorithm +and evaluate again the MSE and the \( R^2 \) functions resulting from the test data. Evaluate also the bias and variance of the final models. + +

    +Write then your own code for the Ridge method, either using matrix +inversion or the singular value decomposition as done for standard OLS. Perform the same analysis as in the +previous exercise (for the same polynomials and include resampling +techniques) but now for different values of \( \lambda \). Compare and +analyze your results with those obtained with standard OLS. Study the +dependence on \( \lambda \) while also varying eventually the strength of +the noise in your expression for \( \mathrm{FrankeFunction}(x,y) \). + +

    +Then perform the same studies but now with Lasso regression. Use the functionalities of +scikit-learn. Give a critical discussion of the three methods and a +judgement of which model fits the data best. +

    - © 1999-2018, Morten Hjorth-Jensen. Released under CC Attribution-NonCommercial 4.0 license + © 1999-2019, Morten Hjorth-Jensen. Released under CC Attribution-NonCommercial 4.0 license
    diff --git a/doc/pub/Regression/html/reveal.js/.gitignore b/doc/pub/Regression/html/reveal.js/.gitignore index e7b4f216a..a5df3133d 100644 --- a/doc/pub/Regression/html/reveal.js/.gitignore +++ b/doc/pub/Regression/html/reveal.js/.gitignore @@ -1,8 +1,3 @@ -.idea/ -*.iml -*.iws -*.eml -out/ .DS_Store .svn log/*.log @@ -10,4 +5,4 @@ tmp/** node_modules/ .sass-cache css/reveal.min.css -js/reveal.min.js \ No newline at end of file +js/reveal.min.js diff --git a/doc/pub/Regression/html/reveal.js/.travis.yml b/doc/pub/Regression/html/reveal.js/.travis.yml index ec3b27d5d..165d9ae9f 100644 --- a/doc/pub/Regression/html/reveal.js/.travis.yml +++ b/doc/pub/Regression/html/reveal.js/.travis.yml @@ -1,7 +1,5 @@ language: node_js node_js: - - 4 + - 0.10 before_script: - - npm install -g grunt-cli -after_script: - - grunt retire + - npm install -g grunt-cli \ No newline at end of file diff --git a/doc/pub/Regression/html/reveal.js/LICENSE b/doc/pub/Regression/html/reveal.js/LICENSE index c3e6e5fd6..09623076f 100644 --- a/doc/pub/Regression/html/reveal.js/LICENSE +++ b/doc/pub/Regression/html/reveal.js/LICENSE @@ -1,4 +1,4 @@ -Copyright (C) 2017 Hakim El Hattab, http://hakim.se, and reveal.js contributors +Copyright (C) 2015 Hakim El Hattab, http://hakim.se Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal diff --git a/doc/pub/Regression/html/reveal.js/README.md b/doc/pub/Regression/html/reveal.js/README.md index f2ab6ca88..573b19597 100644 --- a/doc/pub/Regression/html/reveal.js/README.md +++ b/doc/pub/Regression/html/reveal.js/README.md @@ -1,58 +1,12 @@ -# reveal.js [![Build Status](https://travis-ci.org/hakimel/reveal.js.svg?branch=master)](https://travis-ci.org/hakimel/reveal.js) Slides +# reveal.js [![Build Status](https://travis-ci.org/hakimel/reveal.js.svg?branch=master)](https://travis-ci.org/hakimel/reveal.js) -A framework for easily creating beautiful presentations using HTML. [Check out the live demo](http://revealjs.com/). +A framework for easily creating beautiful presentations using HTML. [Check out the live demo](http://lab.hakim.se/reveal-js/). -reveal.js comes with a broad range of features including [nested slides](https://github.com/hakimel/reveal.js#markup), [Markdown contents](https://github.com/hakimel/reveal.js#markdown), [PDF export](https://github.com/hakimel/reveal.js#pdf-export), [speaker notes](https://github.com/hakimel/reveal.js#speaker-notes) and a [JavaScript API](https://github.com/hakimel/reveal.js#api). There's also a fully featured visual editor and platform for sharing reveal.js presentations at [slides.com](https://slides.com?ref=github). +reveal.js comes with a broad range of features including [nested slides](https://github.com/hakimel/reveal.js#markup), [Markdown contents](https://github.com/hakimel/reveal.js#markdown), [PDF export](https://github.com/hakimel/reveal.js#pdf-export), [speaker notes](https://github.com/hakimel/reveal.js#speaker-notes) and a [JavaScript API](https://github.com/hakimel/reveal.js#api). It's best viewed in a modern browser but [fallbacks](https://github.com/hakimel/reveal.js/wiki/Browser-Support) are available to make sure your presentation can still be viewed elsewhere. -## Table of contents -- [Online Editor](#online-editor) -- [Instructions](#instructions) - - [Markup](#markup) - - [Markdown](#markdown) - - [Element Attributes](#element-attributes) - - [Slide Attributes](#slide-attributes) -- [Configuration](#configuration) -- [Presentation Size](#presentation-size) -- [Dependencies](#dependencies) -- [Ready Event](#ready-event) -- [Auto-sliding](#auto-sliding) -- [Keyboard Bindings](#keyboard-bindings) -- [Touch Navigation](#touch-navigation) -- [Lazy Loading](#lazy-loading) -- [API](#api) - - [Slide Changed Event](#slide-changed-event) - - [Presentation State](#presentation-state) - - [Slide States](#slide-states) - - [Slide Backgrounds](#slide-backgrounds) - - [Parallax Background](#parallax-background) - - [Slide Transitions](#slide-transitions) - - [Internal links](#internal-links) - - [Fragments](#fragments) - - [Fragment events](#fragment-events) - - [Code syntax highlighting](#code-syntax-highlighting) - - [Slide number](#slide-number) - - [Overview mode](#overview-mode) - - [Fullscreen mode](#fullscreen-mode) - - [Embedded media](#embedded-media) - - [Stretching elements](#stretching-elements) - - [postMessage API](#postmessage-api) -- [PDF Export](#pdf-export) -- [Theming](#theming) -- [Speaker Notes](#speaker-notes) - - [Share and Print Speaker Notes](#share-and-print-speaker-notes) - - [Server Side Speaker Notes](#server-side-speaker-notes) -- [Multiplexing](#multiplexing) - - [Master presentation](#master-presentation) - - [Client presentation](#client-presentation) - - [Socket.io server](#socketio-server) -- [MathJax](#mathjax) -- [Installation](#installation) - - [Basic setup](#basic-setup) - - [Full setup](#full-setup) - - [Folder Structure](#folder-structure) -- [License](#license) -#### More reading +#### More reading: +- [Installation](#installation): Step-by-step instructions for getting reveal.js running on your computer. - [Changelog](https://github.com/hakimel/reveal.js/releases): Up-to-date version history. - [Examples](https://github.com/hakimel/reveal.js/wiki/Example-Presentations): Presentations created with reveal.js, add your own! - [Browser Support](https://github.com/hakimel/reveal.js/wiki/Browser-Support): Explanation of browser support and fallbacks. @@ -60,36 +14,14 @@ reveal.js comes with a broad range of features including [nested slides](https:/ ## Online Editor -Presentations are written using HTML or Markdown but there's also an online editor for those of you who prefer a graphical interface. Give it a try at [https://slides.com](https://slides.com?ref=github). +Presentations are written using HTML or Markdown but there's also an online editor for those of you who prefer a graphical interface. Give it a try at [http://slides.com](http://slides.com). ## Instructions ### Markup -Here's a barebones example of a fully working reveal.js presentation: -```html - - - - - - -
    -
    -
    Slide 1
    -
    Slide 2
    -
    -
    - - - - -``` - -The presentation markup hierarchy needs to be `.reveal > .slides > section` where the `section` represents one slide and can be repeated indefinitely. If you place multiple `section` elements inside of another `section` they will be shown as vertical slides. The first of the vertical slides is the "root" of the others (at the top), and will be included in the horizontal sequence. For example: +Markup hierarchy needs to be ``
    `` where the ``
    `` represents one slide and can be repeated indefinitely. If you place multiple ``
    ``'s inside of another ``
    `` they will be shown as vertical slides. The first of the vertical slides is the "root" of the others (at the top), and it will be included in the horizontal sequence. For example: ```html
    @@ -105,36 +37,32 @@ The presentation markup hierarchy needs to be `.reveal > .slides > section` wher ### Markdown -It's possible to write your slides using Markdown. To enable Markdown, add the `data-markdown` attribute to your `
    ` elements and wrap the contents in a ` +
    ``` #### External Markdown -You can write your content as a separate file and have reveal.js load it at runtime. Note the separator arguments which determine how slides are delimited in the external file: the `data-separator` attribute defines a regular expression for horizontal slides (defaults to `^\r?\n---\r?\n$`, a newline-bounded horizontal rule) and `data-separator-vertical` defines vertical slides (disabled by default). The `data-separator-notes` attribute is a regular expression for specifying the beginning of the current slide's speaker notes (defaults to `note:`). The `data-charset` attribute is optional and specifies which charset to use when loading the external file. +You can write your content as a separate file and have reveal.js load it at runtime. Note the separator arguments which determine how slides are delimited in the external file. The ```data-charset``` attribute is optional and specifies which charset to use when loading the external file. -When used locally, this feature requires that reveal.js [runs from a local web server](#full-setup). The following example customises all available options: +When used locally, this feature requires that reveal.js [runs from a local web server](#full-setup). ```html -
    -
    ``` @@ -164,19 +92,6 @@ Special syntax (in html comment) is available for adding attributes to the slide
    ``` -#### Configuring *marked* - -We use [marked](https://github.com/chjj/marked) to parse Markdown. To customise marked's rendering, you can pass in options when [configuring Reveal](#configuration): - -```javascript -Reveal.initialize({ - // Options which are passed into marked - // See https://github.com/chjj/marked#options-1 - markdown: { - smartypants: true - } -}); -``` ### Configuration @@ -185,26 +100,12 @@ At the end of your page you need to initialize reveal by running the following c ```javascript Reveal.initialize({ - // Display presentation control arrows + // Display controls in the bottom right corner controls: true, - // Help the user learn the controls by providing hints, for example by - // bouncing the down arrow when they first encounter a vertical slide - controlsTutorial: true, - - // Determines where controls appear, "edges" or "bottom-right" - controlsLayout: 'bottom-right', - - // Visibility rule for backwards navigation arrows; "faded", "hidden" - // or "visible" - controlsBackArrows: 'faded', - // Display a presentation progress bar progress: true, - // Set default timing of 2 minutes per slide - defaultTiming: 120, - // Display the page number of the current slide slideNumber: false, @@ -229,9 +130,6 @@ Reveal.initialize({ // Change the presentation direction to be RTL rtl: false, - // Randomizes the order of slides each time the presentation loads - shuffle: false, - // Turns fragments on and off globally fragments: true, @@ -243,15 +141,6 @@ Reveal.initialize({ // key is pressed help: true, - // Flags if speaker notes should be visible to all viewers - showNotes: false, - - // Global override for autoplaying embedded media (video/audio/iframe) - // - null: Media will only autoplay if data-autoplay is present - // - true: All media will autoplay, regardless of individual setting - // - false: No media will autoplay, regardless of individual setting - autoPlayMedia: null, - // Number of milliseconds between automatically proceeding to the // next slide, disabled when set to 0, this value can be overwritten // by using a data-autoslide attribute on your slides @@ -260,9 +149,6 @@ Reveal.initialize({ // Stop auto-sliding after user input autoSlideStoppable: true, - // Use this method for navigation when auto-sliding - autoSlideMethod: Reveal.navigateNext, - // Enable slide navigation via mouse wheel mouseWheel: false, @@ -270,18 +156,16 @@ Reveal.initialize({ hideAddressBar: true, // Opens links in an iframe preview overlay - // Add `data-preview-link` and `data-preview-link="false"` to customise each link - // individually previewLinks: false, // Transition style - transition: 'slide', // none/fade/slide/convex/concave/zoom + transition: 'default', // none/fade/slide/convex/concave/zoom // Transition speed transitionSpeed: 'default', // default/fast/slow // Transition style for full page slide backgrounds - backgroundTransition: 'fade', // none/fade/slide/convex/concave/zoom + backgroundTransition: 'default', // none/fade/slide/convex/concave/zoom // Number of slides away from the current that are visible viewDistance: 3, @@ -292,14 +176,10 @@ Reveal.initialize({ // Parallax background size parallaxBackgroundSize: '', // CSS syntax, e.g. "2100px 900px" - // Number of pixels to move the parallax background per slide - // - Calculated automatically unless specified - // - Set to 0 to disable movement along an axis - parallaxBackgroundHorizontal: null, - parallaxBackgroundVertical: null, - - // The display mode that will be used to show slides - display: 'block' + // Amount to move parallax background (horizontal and vertical) on slide change + // Number, e.g. 100 + parallaxBackgroundHorizontal: '', + parallaxBackgroundVertical: '' }); ``` @@ -316,6 +196,56 @@ Reveal.configure({ autoSlide: 5000 }); ``` +### Dependencies + +Reveal.js doesn't _rely_ on any third party scripts to work but a few optional libraries are included by default. These libraries are loaded as dependencies in the order they appear, for example: + +```javascript +Reveal.initialize({ + dependencies: [ + // Cross-browser shim that fully implements classList - https://github.com/eligrey/classList.js/ + { src: 'lib/js/classList.js', condition: function() { return !document.body.classList; } }, + + // Interpret Markdown in
    elements + { src: 'plugin/markdown/marked.js', condition: function() { return !!document.querySelector( '[data-markdown]' ); } }, + { src: 'plugin/markdown/markdown.js', condition: function() { return !!document.querySelector( '[data-markdown]' ); } }, + + // Syntax highlight for elements + { src: 'plugin/highlight/highlight.js', async: true, callback: function() { hljs.initHighlightingOnLoad(); } }, + + // Zoom in and out with Alt+click + { src: 'plugin/zoom-js/zoom.js', async: true }, + + // Speaker notes + { src: 'plugin/notes/notes.js', async: true }, + + // Remote control your reveal.js presentation using a touch device + { src: 'plugin/remotes/remotes.js', async: true }, + + // MathJax + { src: 'plugin/math/math.js', async: true } + ] +}); +``` + +You can add your own extensions using the same syntax. The following properties are available for each dependency object: +- **src**: Path to the script to load +- **async**: [optional] Flags if the script should load after reveal.js has started, defaults to false +- **callback**: [optional] Function to execute when the script has loaded +- **condition**: [optional] Function which must return true for the script to be loaded + + +### Ready Event + +A 'ready' event is fired when reveal.js has loaded all non-async dependencies and is ready to start navigating. To check if reveal.js is already 'ready' you can call `Reveal.isReady()`. + +```javascript +Reveal.addEventListener( 'ready', function( event ) { + // event.currentSlide, event.indexh, event.indexv +} ); +``` + + ### Presentation Size All presentations have a normal size, that is the resolution at which they are authored. The framework will automatically scale presentations uniformly based on this size to ensure that everything fits on any given display or viewport. @@ -343,69 +273,6 @@ Reveal.initialize({ }); ``` -If you wish to disable this behavior and do your own scaling (e.g. using media queries), try these settings: - -```javascript -Reveal.initialize({ - - ... - - width: "100%", - height: "100%", - margin: 0, - minScale: 1, - maxScale: 1 -}); -``` - -### Dependencies - -Reveal.js doesn't _rely_ on any third party scripts to work but a few optional libraries are included by default. These libraries are loaded as dependencies in the order they appear, for example: - -```javascript -Reveal.initialize({ - dependencies: [ - // Cross-browser shim that fully implements classList - https://github.com/eligrey/classList.js/ - { src: 'lib/js/classList.js', condition: function() { return !document.body.classList; } }, - - // Interpret Markdown in
    elements - { src: 'plugin/markdown/marked.js', condition: function() { return !!document.querySelector( '[data-markdown]' ); } }, - { src: 'plugin/markdown/markdown.js', condition: function() { return !!document.querySelector( '[data-markdown]' ); } }, - - // Syntax highlight for elements - { src: 'plugin/highlight/highlight.js', async: true, callback: function() { hljs.initHighlightingOnLoad(); } }, - - // Zoom in and out with Alt+click - { src: 'plugin/zoom-js/zoom.js', async: true }, - - // Speaker notes - { src: 'plugin/notes/notes.js', async: true }, - - // MathJax - { src: 'plugin/math/math.js', async: true } - ] -}); -``` - -You can add your own extensions using the same syntax. The following properties are available for each dependency object: -- **src**: Path to the script to load -- **async**: [optional] Flags if the script should load after reveal.js has started, defaults to false -- **callback**: [optional] Function to execute when the script has loaded -- **condition**: [optional] Function which must return true for the script to be loaded - -To load these dependencies, reveal.js requires [head.js](http://headjs.com/) *(a script loading library)* to be loaded before reveal.js. - -### Ready Event - -A 'ready' event is fired when reveal.js has loaded all non-async dependencies and is ready to start navigating. To check if reveal.js is already 'ready' you can call `Reveal.isReady()`. - -```javascript -Reveal.addEventListener( 'ready', function( event ) { - // event.currentSlide, event.indexh, event.indexv -} ); -``` - -Note that we also add a `.ready` class to the `.reveal` element so that you can hook into this with CSS. ### Auto-sliding @@ -429,8 +296,6 @@ You can also override the slide duration for individual slides and fragments by
    ``` -To override the method used for navigation when auto-sliding, you can specify the ```autoSlideMethod``` setting. To only navigate along the top layer and ignore vertical slides, set this to ```Reveal.navigateRight```. - Whenever the auto-slide mode is resumed or paused the ```autoslideresumed``` and ```autoslidepaused``` events are fired. @@ -448,13 +313,6 @@ Reveal.configure({ }); ``` -### Touch Navigation - -You can swipe to navigate through a presentation on any touch-enabled device. Horizontal swipes change between horizontal slides, vertical swipes change between vertical slides. If you wish to disable this you can set the `touch` config option to false when initializing reveal.js. - -If there's some part of your content that needs to remain accessible to touch events you'll need to highlight this by adding a `data-prevent-swipe` attribute to the element. One common example where this is useful is elements that need to be scrolled. - - ### Lazy Loading When working on presentation with a lot of media or iframe content it's important to load lazily. Lazy loading means that reveal.js will only load content for the few slides nearest to the current slide. The number of slides that are preloaded is determined by the `viewDistance` configuration option. @@ -489,18 +347,11 @@ Reveal.next(); Reveal.prevFragment(); Reveal.nextFragment(); -// Randomize the order of slides -Reveal.shuffle(); - // Toggle presentation states, optionally pass true/false to force on/off Reveal.toggleOverview(); Reveal.togglePause(); Reveal.toggleAutoSlide(); -// Shows a help overlay with keyboard shortcuts, optionally pass true/false -// to force on/off -Reveal.toggleHelp(); - // Change a config value at runtime Reveal.configure({ controls: true }); @@ -514,14 +365,9 @@ Reveal.getScale(); Reveal.getPreviousSlide(); Reveal.getCurrentSlide(); -Reveal.getIndices(); // { h: 0, v: 0 } } -Reveal.getPastSlideCount(); -Reveal.getProgress(); // (0 == first slide, 1 == last slide) -Reveal.getSlides(); // Array of all slides -Reveal.getTotalSlides(); // total number of slides - -// Returns the speaker notes for the current slide -Reveal.getSlideNotes(); +Reveal.getIndices(); // { h: 0, v: 0 } } +Reveal.getProgress(); // 0-1 +Reveal.getTotalSlides(); // State checks Reveal.isFirstSlide(); @@ -574,59 +420,26 @@ Reveal.addEventListener( 'somestate', function() { ### Slide Backgrounds -Slides are contained within a limited portion of the screen by default to allow them to fit any display and scale uniformly. You can apply full page backgrounds outside of the slide area by adding a ```data-background``` attribute to your ```
    ``` elements. Four different types of backgrounds are supported: color, image, video and iframe. +Slides are contained within a limited portion of the screen by default to allow them to fit any display and scale uniformly. You can apply full page backgrounds outside of the slide area by adding a ```data-background``` attribute to your ```
    ``` elements. Four different types of backgrounds are supported: color, image, video and iframe. Below are a few examples. -#### Color Backgrounds -All CSS color formats are supported, like rgba() or hsl(). ```html -
    -

    Color

    +
    +

    All CSS color formats are supported, like rgba() or hsl().

    +
    +
    +

    This slide will have a full-size background image.

    +
    +
    +

    This background image will be sized to 100px and repeated.

    +
    +
    +

    Video. Multiple sources can be defined using a comma separated list. Video will loop when the data-background-video-loop attribute is provided.

    +
    +
    +

    Embeds a web page as a background. Note that the page won't be interactive.

    ``` -#### Image Backgrounds -By default, background images are resized to cover the full page. Available options: - -| Attribute | Default | Description | -| :--------------------------- | :--------- | :---------- | -| data-background-image | | URL of the image to show. GIFs restart when the slide opens. | -| data-background-size | cover | See [background-size](https://developer.mozilla.org/docs/Web/CSS/background-size) on MDN. | -| data-background-position | center | See [background-position](https://developer.mozilla.org/docs/Web/CSS/background-position) on MDN. | -| data-background-repeat | no-repeat | See [background-repeat](https://developer.mozilla.org/docs/Web/CSS/background-repeat) on MDN. | -```html -
    -

    Image

    -
    -
    -

    This background image will be sized to 100px and repeated

    -
    -``` - -#### Video Backgrounds -Automatically plays a full size video behind the slide. - -| Attribute | Default | Description | -| :--------------------------- | :------ | :---------- | -| data-background-video | | A single video source, or a comma separated list of video sources. | -| data-background-video-loop | false | Flags if the video should play repeatedly. | -| data-background-video-muted | false | Flags if the audio should be muted. | -| data-background-size | cover | Use `cover` for full screen and some cropping or `contain` for letterboxing. | - -```html -
    -

    Video

    -
    -``` - -#### Iframe Backgrounds -Embeds a web page as a slide background that covers 100% of the reveal.js width and height. The iframe is in the background layer, behind your slides, and as such it's not possible to interact with it by default. To make your background interactive, you can add the `data-background-interactive` attribute. -```html -
    -

    Iframe

    -
    -``` - -#### Background Transitions Backgrounds transition using a fade animation by default. This can be changed to a linear sliding transition by passing ```backgroundTransition: 'slide'``` to the ```Reveal.initialize()``` call. Alternatively you can set ```data-background-transition``` on any section with a background to override that specific transition. @@ -643,16 +456,16 @@ Reveal.initialize({ // Parallax background size parallaxBackgroundSize: '', // CSS syntax, e.g. "2100px 900px" - currently only pixels are supported (don't use % or auto) - // Number of pixels to move the parallax background per slide - // - Calculated automatically unless specified - // - Set to 0 to disable movement along an axis + // Amount of pixels to move the parallax background per slide step, + // a value of 0 disables movement along the given axis + // These are optional, if they aren't specified they'll be calculated automatically parallaxBackgroundHorizontal: 200, parallaxBackgroundVertical: 50 }); ``` -Make sure that the background size is much bigger than screen size to allow for some scrolling. [View example](http://revealjs.com/?parallaxBackgroundImage=https%3A%2F%2Fs3.amazonaws.com%2Fhakim-static%2Freveal-js%2Freveal-parallax-1.jpg¶llaxBackgroundSize=2100px%20900px). +Make sure that the background size is much bigger than screen size to allow for some scrolling. [View example](http://lab.hakim.se/reveal-js/?parallaxBackgroundImage=https%3A%2F%2Fs3.amazonaws.com%2Fhakim-static%2Freveal-js%2Freveal-parallax-1.jpg¶llaxBackgroundSize=2100px%20900px). @@ -673,15 +486,15 @@ You can also use different in and out transitions for the same slide: ```html
    - The train goes on … + The train goes on …
    -
    - and on … +
    + and on …
    -
    +
    and stops.
    -
    +
    (Passengers entering and leaving)
    @@ -690,6 +503,9 @@ You can also use different in and out transitions for the same slide: ``` +Note that this does not work with the page and cube transitions. + + ### Internal links It's easy to link between slides. The first example below targets the index of another slide whereas the second targets a slide with an ID attribute (```
    ```): @@ -712,7 +528,7 @@ You can also add relative navigation links, similar to the built in reveal.js co ### Fragments -Fragments are used to highlight individual elements on a slide. Every element with the class ```fragment``` will be stepped through before moving on to the next slide. Here's an example: http://revealjs.com/#/fragments +Fragments are used to highlight individual elements on a slide. Every element with the class ```fragment``` will be stepped through before moving on to the next slide. Here's an example: http://lab.hakim.se/reveal-js/#/fragments The default fragment style is to start out invisible and fade in. This style can be changed by appending a different class to the fragment: @@ -721,7 +537,6 @@ The default fragment style is to start out invisible and fade in. This style can

    grow

    shrink

    fade-out

    -

    fade-up (also down, left and right!)

    visible only once

    blue only once

    highlight-red

    @@ -767,41 +582,33 @@ Reveal.addEventListener( 'fragmenthidden', function( event ) { ### Code syntax highlighting -By default, Reveal is configured with [highlight.js](https://highlightjs.org/) for code syntax highlighting. To enable syntax highlighting, you'll have to load the highlight plugin ([plugin/highlight/highlight.js](plugin/highlight/highlight.js)) and a highlight.js CSS theme (Reveal comes packaged with the zenburn theme: [lib/css/zenburn.css](lib/css/zenburn.css)). - -Below is an example with clojure code that will be syntax highlighted. When the `data-trim` attribute is present, surrounding whitespace is automatically removed. HTML will be escaped by default. To avoid this, for example if you are using `` to call out a line of code, add the `data-noescape` attribute to the `` element. +By default, Reveal is configured with [highlight.js](http://softwaremaniacs.org/soft/highlight/en/) for code syntax highlighting. Below is an example with clojure code that will be syntax highlighted. When the `data-trim` attribute is present surrounding whitespace is automatically removed. ```html
    -
    
    +	
    
     (def lazy-fib
       (concat
        [0 1]
    -   ((fn rfib [a b]
    +   ((fn rfib [a b]
             (lazy-cons (+ a b) (rfib b (+ a b)))) 0 1)))
     	
    ``` ### Slide number -If you would like to display the page number of the current slide you can do so using the ```slideNumber``` and ```showSlideNumber``` configuration values. +If you would like to display the page number of the current slide you can do so using the ```slideNumber``` configuration value. ```javascript // Shows the slide number using default formatting Reveal.configure({ slideNumber: true }); // Slide number formatting can be configured using these variables: -// "h.v": horizontal . vertical slide number (default) -// "h/v": horizontal / vertical slide number -// "c": flattened slide number -// "c/t": flattened slide number / total slides -Reveal.configure({ slideNumber: 'c/t' }); - -// Control which views the slide number displays on using the "showSlideNumber" value: -// "all": show on all views (default) -// "speaker": only show slide numbers on speaker notes view -// "print": only show slide numbers when printing to PDF -Reveal.configure({ showSlideNumber: 'speaker' }); +// h: current slide's horizontal index +// v: current slide's vertical index +// c: current slide index (flattened) +// t: total number of slides (flattened) +Reveal.configure({ slideNumber: 'c / t' }); ``` @@ -819,26 +626,20 @@ Reveal.addEventListener( 'overviewhidden', function( event ) { /* ... */ } ); Reveal.toggleOverview(); ``` - ### Fullscreen mode Just press »F« on your keyboard to show your presentation in fullscreen mode. Press the »ESC« key to exit fullscreen mode. ### Embedded media +Embedded HTML5 `
    diff --git a/doc/pub/Regression/html/reveal.js/plugin/markdown/example.md b/doc/pub/Regression/html/reveal.js/plugin/markdown/example.md index 89c75345e..6f6f577a1 100644 --- a/doc/pub/Regression/html/reveal.js/plugin/markdown/example.md +++ b/doc/pub/Regression/html/reveal.js/plugin/markdown/example.md @@ -29,8 +29,3 @@ Content 3.1 ## External 3.2 Content 3.2 - - -## External 3.3 - -![External Image](https://s3.amazonaws.com/static.slid.es/logo/v2/slides-symbol-512x512.png) diff --git a/doc/pub/Regression/html/reveal.js/plugin/markdown/markdown.js b/doc/pub/Regression/html/reveal.js/plugin/markdown/markdown.js index aa08ee5ed..15e3b40b3 100644 --- a/doc/pub/Regression/html/reveal.js/plugin/markdown/markdown.js +++ b/doc/pub/Regression/html/reveal.js/plugin/markdown/markdown.js @@ -4,26 +4,33 @@ * of external markdown documents. */ (function( root, factory ) { - if (typeof define === 'function' && define.amd) { - root.marked = require( './marked' ); - root.RevealMarkdown = factory( root.marked ); - root.RevealMarkdown.initialize(); - } else if( typeof exports === 'object' ) { + if( typeof exports === 'object' ) { module.exports = factory( require( './marked' ) ); - } else { + } + else { // Browser globals (root is window) root.RevealMarkdown = factory( root.marked ); root.RevealMarkdown.initialize(); } }( this, function( marked ) { + if( typeof marked === 'undefined' ) { + throw 'The reveal.js Markdown plugin requires marked to be loaded'; + } + + if( typeof hljs !== 'undefined' ) { + marked.setOptions({ + highlight: function( lang, code ) { + return hljs.highlightAuto( lang, code ).value; + } + }); + } + var DEFAULT_SLIDE_SEPARATOR = '^\r?\n---\r?\n$', - DEFAULT_NOTES_SEPARATOR = 'notes?:', + DEFAULT_NOTES_SEPARATOR = 'note:', DEFAULT_ELEMENT_ATTRIBUTES_SEPARATOR = '\\\.element\\\s*?(.+?)$', DEFAULT_SLIDE_ATTRIBUTES_SEPARATOR = '\\\.slide:\\\s*?(\\\S.+?)$'; - var SCRIPT_END_PLACEHOLDER = '__SCRIPT_END__'; - /** * Retrieves the markdown contents of a slide section @@ -31,15 +38,11 @@ */ function getMarkdownFromSlide( section ) { - // look for a ' ); - var leadingWs = text.match( /^\n?(\s*)/ )[1].length, leadingTabs = text.match( /^\n?(\t*)/ )[1].length; @@ -109,13 +112,9 @@ var notesMatch = content.split( new RegExp( options.notesSeparator, 'mgi' ) ); if( notesMatch.length === 2 ) { - content = notesMatch[0] + ''; + content = notesMatch[0] + ''; } - // prevent script end tags in the content from interfering - // with parsing - content = content.replace( /<\/script>/g, SCRIPT_END_PLACEHOLDER ); - return ''; } @@ -178,7 +177,7 @@ markdownSections += '
    '; sectionStack[i].forEach( function( child ) { - markdownSections += '
    ' + createMarkdownSlide( child, options ) + '
    '; + markdownSections += '
    ' + createMarkdownSlide( child, options ) + '
    '; } ); markdownSections += '
    '; @@ -380,24 +379,6 @@ return { initialize: function() { - if( typeof marked === 'undefined' ) { - throw 'The reveal.js Markdown plugin requires marked to be loaded'; - } - - if( typeof hljs !== 'undefined' ) { - marked.setOptions({ - highlight: function( code, lang ) { - return hljs.highlightAuto( code, [lang] ).value; - } - }); - } - - var options = Reveal.getConfig().markdown; - - if ( options ) { - marked.setOptions( options ); - } - processSlides(); convertSlides(); }, diff --git a/doc/pub/Regression/html/reveal.js/plugin/markdown/marked.js b/doc/pub/Regression/html/reveal.js/plugin/markdown/marked.js index 555c1dc1d..70af29bf9 100644 --- a/doc/pub/Regression/html/reveal.js/plugin/markdown/marked.js +++ b/doc/pub/Regression/html/reveal.js/plugin/markdown/marked.js @@ -3,4 +3,4 @@ * Copyright (c) 2011-2014, Christopher Jeffrey. (MIT Licensed) * https://github.com/chjj/marked */ -(function(){var block={newline:/^\n+/,code:/^( {4}[^\n]+\n*)+/,fences:noop,hr:/^( *[-*_]){3,} *(?:\n+|$)/,heading:/^ *(#{1,6}) *([^\n]+?) *#* *(?:\n+|$)/,nptable:noop,lheading:/^([^\n]+)\n *(=|-){2,} *(?:\n+|$)/,blockquote:/^( *>[^\n]+(\n(?!def)[^\n]+)*\n*)+/,list:/^( *)(bull) [\s\S]+?(?:hr|def|\n{2,}(?! )(?!\1bull )\n*|\s*$)/,html:/^ *(?:comment *(?:\n|\s*$)|closed *(?:\n{2,}|\s*$)|closing *(?:\n{2,}|\s*$))/,def:/^ *\[([^\]]+)\]: *]+)>?(?: +["(]([^\n]+)[")])? *(?:\n+|$)/,table:noop,paragraph:/^((?:[^\n]+\n?(?!hr|heading|lheading|blockquote|tag|def))+)\n*/,text:/^[^\n]+/};block.bullet=/(?:[*+-]|\d+\.)/;block.item=/^( *)(bull) [^\n]*(?:\n(?!\1bull )[^\n]*)*/;block.item=replace(block.item,"gm")(/bull/g,block.bullet)();block.list=replace(block.list)(/bull/g,block.bullet)("hr","\\n+(?=\\1?(?:[-*_] *){3,}(?:\\n+|$))")("def","\\n+(?="+block.def.source+")")();block.blockquote=replace(block.blockquote)("def",block.def)();block._tag="(?!(?:"+"a|em|strong|small|s|cite|q|dfn|abbr|data|time|code"+"|var|samp|kbd|sub|sup|i|b|u|mark|ruby|rt|rp|bdi|bdo"+"|span|br|wbr|ins|del|img)\\b)\\w+(?!:/|[^\\w\\s@]*@)\\b";block.html=replace(block.html)("comment",//)("closed",/<(tag)[\s\S]+?<\/\1>/)("closing",/])*?>/)(/tag/g,block._tag)();block.paragraph=replace(block.paragraph)("hr",block.hr)("heading",block.heading)("lheading",block.lheading)("blockquote",block.blockquote)("tag","<"+block._tag)("def",block.def)();block.normal=merge({},block);block.gfm=merge({},block.normal,{fences:/^ *(`{3,}|~{3,})[ \.]*(\S+)? *\n([\s\S]*?)\s*\1 *(?:\n+|$)/,paragraph:/^/,heading:/^ *(#{1,6}) +([^\n]+?) *#* *(?:\n+|$)/});block.gfm.paragraph=replace(block.paragraph)("(?!","(?!"+block.gfm.fences.source.replace("\\1","\\2")+"|"+block.list.source.replace("\\1","\\3")+"|")();block.tables=merge({},block.gfm,{nptable:/^ *(\S.*\|.*)\n *([-:]+ *\|[-| :]*)\n((?:.*\|.*(?:\n|$))*)\n*/,table:/^ *\|(.+)\n *\|( *[-:]+[-| :]*)\n((?: *\|.*(?:\n|$))*)\n*/});function Lexer(options){this.tokens=[];this.tokens.links={};this.options=options||marked.defaults;this.rules=block.normal;if(this.options.gfm){if(this.options.tables){this.rules=block.tables}else{this.rules=block.gfm}}}Lexer.rules=block;Lexer.lex=function(src,options){var lexer=new Lexer(options);return lexer.lex(src)};Lexer.prototype.lex=function(src){src=src.replace(/\r\n|\r/g,"\n").replace(/\t/g," ").replace(/\u00a0/g," ").replace(/\u2424/g,"\n");return this.token(src,true)};Lexer.prototype.token=function(src,top,bq){var src=src.replace(/^ +$/gm,""),next,loose,cap,bull,b,item,space,i,l;while(src){if(cap=this.rules.newline.exec(src)){src=src.substring(cap[0].length);if(cap[0].length>1){this.tokens.push({type:"space"})}}if(cap=this.rules.code.exec(src)){src=src.substring(cap[0].length);cap=cap[0].replace(/^ {4}/gm,"");this.tokens.push({type:"code",text:!this.options.pedantic?cap.replace(/\n+$/,""):cap});continue}if(cap=this.rules.fences.exec(src)){src=src.substring(cap[0].length);this.tokens.push({type:"code",lang:cap[2],text:cap[3]||""});continue}if(cap=this.rules.heading.exec(src)){src=src.substring(cap[0].length);this.tokens.push({type:"heading",depth:cap[1].length,text:cap[2]});continue}if(top&&(cap=this.rules.nptable.exec(src))){src=src.substring(cap[0].length);item={type:"table",header:cap[1].replace(/^ *| *\| *$/g,"").split(/ *\| */),align:cap[2].replace(/^ *|\| *$/g,"").split(/ *\| */),cells:cap[3].replace(/\n$/,"").split("\n")};for(i=0;i ?/gm,"");this.token(cap,top,true);this.tokens.push({type:"blockquote_end"});continue}if(cap=this.rules.list.exec(src)){src=src.substring(cap[0].length);bull=cap[2];this.tokens.push({type:"list_start",ordered:bull.length>1});cap=cap[0].match(this.rules.item);next=false;l=cap.length;i=0;for(;i1&&b.length>1)){src=cap.slice(i+1).join("\n")+src;i=l-1}}loose=next||/\n\n(?!\s*$)/.test(item);if(i!==l-1){next=item.charAt(item.length-1)==="\n";if(!loose)loose=next}this.tokens.push({type:loose?"loose_item_start":"list_item_start"});this.token(item,false,bq);this.tokens.push({type:"list_item_end"})}this.tokens.push({type:"list_end"});continue}if(cap=this.rules.html.exec(src)){src=src.substring(cap[0].length);this.tokens.push({type:this.options.sanitize?"paragraph":"html",pre:!this.options.sanitizer&&(cap[1]==="pre"||cap[1]==="script"||cap[1]==="style"),text:cap[0]});continue}if(!bq&&top&&(cap=this.rules.def.exec(src))){src=src.substring(cap[0].length);this.tokens.links[cap[1].toLowerCase()]={href:cap[2],title:cap[3]};continue}if(top&&(cap=this.rules.table.exec(src))){src=src.substring(cap[0].length);item={type:"table",header:cap[1].replace(/^ *| *\| *$/g,"").split(/ *\| */),align:cap[2].replace(/^ *|\| *$/g,"").split(/ *\| */),cells:cap[3].replace(/(?: *\| *)?\n$/,"").split("\n")};for(i=0;i])/,autolink:/^<([^ >]+(@|:\/)[^ >]+)>/,url:noop,tag:/^|^<\/?\w+(?:"[^"]*"|'[^']*'|[^'">])*?>/,link:/^!?\[(inside)\]\(href\)/,reflink:/^!?\[(inside)\]\s*\[([^\]]*)\]/,nolink:/^!?\[((?:\[[^\]]*\]|[^\[\]])*)\]/,strong:/^__([\s\S]+?)__(?!_)|^\*\*([\s\S]+?)\*\*(?!\*)/,em:/^\b_((?:[^_]|__)+?)_\b|^\*((?:\*\*|[\s\S])+?)\*(?!\*)/,code:/^(`+)\s*([\s\S]*?[^`])\s*\1(?!`)/,br:/^ {2,}\n(?!\s*$)/,del:noop,text:/^[\s\S]+?(?=[\\?(?:\s+['"]([\s\S]*?)['"])?\s*/;inline.link=replace(inline.link)("inside",inline._inside)("href",inline._href)();inline.reflink=replace(inline.reflink)("inside",inline._inside)();inline.normal=merge({},inline);inline.pedantic=merge({},inline.normal,{strong:/^__(?=\S)([\s\S]*?\S)__(?!_)|^\*\*(?=\S)([\s\S]*?\S)\*\*(?!\*)/,em:/^_(?=\S)([\s\S]*?\S)_(?!_)|^\*(?=\S)([\s\S]*?\S)\*(?!\*)/});inline.gfm=merge({},inline.normal,{escape:replace(inline.escape)("])","~|])")(),url:/^(https?:\/\/[^\s<]+[^<.,:;"')\]\s])/,del:/^~~(?=\S)([\s\S]*?\S)~~/,text:replace(inline.text)("]|","~]|")("|","|https?://|")()});inline.breaks=merge({},inline.gfm,{br:replace(inline.br)("{2,}","*")(),text:replace(inline.gfm.text)("{2,}","*")()});function InlineLexer(links,options){this.options=options||marked.defaults;this.links=links;this.rules=inline.normal;this.renderer=this.options.renderer||new Renderer;this.renderer.options=this.options;if(!this.links){throw new Error("Tokens array requires a `links` property.")}if(this.options.gfm){if(this.options.breaks){this.rules=inline.breaks}else{this.rules=inline.gfm}}else if(this.options.pedantic){this.rules=inline.pedantic}}InlineLexer.rules=inline;InlineLexer.output=function(src,links,options){var inline=new InlineLexer(links,options);return inline.output(src)};InlineLexer.prototype.output=function(src){var out="",link,text,href,cap;while(src){if(cap=this.rules.escape.exec(src)){src=src.substring(cap[0].length);out+=cap[1];continue}if(cap=this.rules.autolink.exec(src)){src=src.substring(cap[0].length);if(cap[2]==="@"){text=cap[1].charAt(6)===":"?this.mangle(cap[1].substring(7)):this.mangle(cap[1]);href=this.mangle("mailto:")+text}else{text=escape(cap[1]);href=text}out+=this.renderer.link(href,null,text);continue}if(!this.inLink&&(cap=this.rules.url.exec(src))){src=src.substring(cap[0].length);text=escape(cap[1]);href=text;out+=this.renderer.link(href,null,text);continue}if(cap=this.rules.tag.exec(src)){if(!this.inLink&&/^/i.test(cap[0])){this.inLink=false}src=src.substring(cap[0].length);out+=this.options.sanitize?this.options.sanitizer?this.options.sanitizer(cap[0]):escape(cap[0]):cap[0];continue}if(cap=this.rules.link.exec(src)){src=src.substring(cap[0].length);this.inLink=true;out+=this.outputLink(cap,{href:cap[2],title:cap[3]});this.inLink=false;continue}if((cap=this.rules.reflink.exec(src))||(cap=this.rules.nolink.exec(src))){src=src.substring(cap[0].length);link=(cap[2]||cap[1]).replace(/\s+/g," ");link=this.links[link.toLowerCase()];if(!link||!link.href){out+=cap[0].charAt(0);src=cap[0].substring(1)+src;continue}this.inLink=true;out+=this.outputLink(cap,link);this.inLink=false;continue}if(cap=this.rules.strong.exec(src)){src=src.substring(cap[0].length);out+=this.renderer.strong(this.output(cap[2]||cap[1]));continue}if(cap=this.rules.em.exec(src)){src=src.substring(cap[0].length);out+=this.renderer.em(this.output(cap[2]||cap[1]));continue}if(cap=this.rules.code.exec(src)){src=src.substring(cap[0].length);out+=this.renderer.codespan(escape(cap[2],true));continue}if(cap=this.rules.br.exec(src)){src=src.substring(cap[0].length);out+=this.renderer.br();continue}if(cap=this.rules.del.exec(src)){src=src.substring(cap[0].length);out+=this.renderer.del(this.output(cap[1]));continue}if(cap=this.rules.text.exec(src)){src=src.substring(cap[0].length);out+=this.renderer.text(escape(this.smartypants(cap[0])));continue}if(src){throw new Error("Infinite loop on byte: "+src.charCodeAt(0))}}return out};InlineLexer.prototype.outputLink=function(cap,link){var href=escape(link.href),title=link.title?escape(link.title):null;return cap[0].charAt(0)!=="!"?this.renderer.link(href,title,this.output(cap[1])):this.renderer.image(href,title,escape(cap[1]))};InlineLexer.prototype.smartypants=function(text){if(!this.options.smartypants)return text;return text.replace(/---/g,"—").replace(/--/g,"–").replace(/(^|[-\u2014/(\[{"\s])'/g,"$1‘").replace(/'/g,"’").replace(/(^|[-\u2014/(\[{\u2018\s])"/g,"$1“").replace(/"/g,"”").replace(/\.{3}/g,"…")};InlineLexer.prototype.mangle=function(text){if(!this.options.mangle)return text;var out="",l=text.length,i=0,ch;for(;i.5){ch="x"+ch.toString(16)}out+="&#"+ch+";"}return out};function Renderer(options){this.options=options||{}}Renderer.prototype.code=function(code,lang,escaped){if(this.options.highlight){var out=this.options.highlight(code,lang);if(out!=null&&out!==code){escaped=true;code=out}}if(!lang){return"
    "+(escaped?code:escape(code,true))+"\n
    "}return'
    '+(escaped?code:escape(code,true))+"\n
    \n"};Renderer.prototype.blockquote=function(quote){return"
    \n"+quote+"
    \n"};Renderer.prototype.html=function(html){return html};Renderer.prototype.heading=function(text,level,raw){return"'+text+"\n"};Renderer.prototype.hr=function(){return this.options.xhtml?"
    \n":"
    \n"};Renderer.prototype.list=function(body,ordered){var type=ordered?"ol":"ul";return"<"+type+">\n"+body+"\n"};Renderer.prototype.listitem=function(text){return"
  • "+text+"
  • \n"};Renderer.prototype.paragraph=function(text){return"

    "+text+"

    \n"};Renderer.prototype.table=function(header,body){return"\n"+"\n"+header+"\n"+"\n"+body+"\n"+"
    \n"};Renderer.prototype.tablerow=function(content){return"\n"+content+"\n"};Renderer.prototype.tablecell=function(content,flags){var type=flags.header?"th":"td";var tag=flags.align?"<"+type+' style="text-align:'+flags.align+'">':"<"+type+">";return tag+content+"\n"};Renderer.prototype.strong=function(text){return""+text+""};Renderer.prototype.em=function(text){return""+text+""};Renderer.prototype.codespan=function(text){return""+text+""};Renderer.prototype.br=function(){return this.options.xhtml?"
    ":"
    "};Renderer.prototype.del=function(text){return""+text+""};Renderer.prototype.link=function(href,title,text){if(this.options.sanitize){try{var prot=decodeURIComponent(unescape(href)).replace(/[^\w:]/g,"").toLowerCase()}catch(e){return""}if(prot.indexOf("javascript:")===0||prot.indexOf("vbscript:")===0){return""}}var out='
    ";return out};Renderer.prototype.image=function(href,title,text){var out=''+text+'":">";return out};Renderer.prototype.text=function(text){return text};function Parser(options){this.tokens=[];this.token=null;this.options=options||marked.defaults;this.options.renderer=this.options.renderer||new Renderer;this.renderer=this.options.renderer;this.renderer.options=this.options}Parser.parse=function(src,options,renderer){var parser=new Parser(options,renderer);return parser.parse(src)};Parser.prototype.parse=function(src){this.inline=new InlineLexer(src.links,this.options,this.renderer);this.tokens=src.reverse();var out="";while(this.next()){out+=this.tok()}return out};Parser.prototype.next=function(){return this.token=this.tokens.pop()};Parser.prototype.peek=function(){return this.tokens[this.tokens.length-1]||0};Parser.prototype.parseText=function(){var body=this.token.text;while(this.peek().type==="text"){body+="\n"+this.next().text}return this.inline.output(body)};Parser.prototype.tok=function(){switch(this.token.type){case"space":{return""}case"hr":{return this.renderer.hr()}case"heading":{return this.renderer.heading(this.inline.output(this.token.text),this.token.depth,this.token.text)}case"code":{return this.renderer.code(this.token.text,this.token.lang,this.token.escaped)}case"table":{var header="",body="",i,row,cell,flags,j;cell="";for(i=0;i/g,">").replace(/"/g,""").replace(/'/g,"'")}function unescape(html){return html.replace(/&([#\w]+);/g,function(_,n){n=n.toLowerCase();if(n==="colon")return":";if(n.charAt(0)==="#"){return n.charAt(1)==="x"?String.fromCharCode(parseInt(n.substring(2),16)):String.fromCharCode(+n.substring(1))}return""})}function replace(regex,opt){regex=regex.source;opt=opt||"";return function self(name,val){if(!name)return new RegExp(regex,opt);val=val.source||val;val=val.replace(/(^|[^\[])\^/g,"$1");regex=regex.replace(name,val);return self}}function noop(){}noop.exec=noop;function merge(obj){var i=1,target,key;for(;iAn error occured:

    "+escape(e.message+"",true)+"
    "}throw e}}marked.options=marked.setOptions=function(opt){merge(marked.defaults,opt);return marked};marked.defaults={gfm:true,tables:true,breaks:false,pedantic:false,sanitize:false,sanitizer:null,mangle:true,smartLists:false,silent:false,highlight:null,langPrefix:"lang-",smartypants:false,headerPrefix:"",renderer:new Renderer,xhtml:false};marked.Parser=Parser;marked.parser=Parser.parse;marked.Renderer=Renderer;marked.Lexer=Lexer;marked.lexer=Lexer.lex;marked.InlineLexer=InlineLexer;marked.inlineLexer=InlineLexer.output;marked.parse=marked;if(typeof module!=="undefined"&&typeof exports==="object"){module.exports=marked}else if(typeof define==="function"&&define.amd){define(function(){return marked})}else{this.marked=marked}}).call(function(){return this||(typeof window!=="undefined"?window:global)}()); \ No newline at end of file +(function(){function e(e){this.tokens=[],this.tokens.links={},this.options=e||a.defaults,this.rules=p.normal,this.options.gfm&&(this.rules=this.options.tables?p.tables:p.gfm)}function t(e,t){if(this.options=t||a.defaults,this.links=e,this.rules=u.normal,this.renderer=this.options.renderer||new n,this.renderer.options=this.options,!this.links)throw new Error("Tokens array requires a `links` property.");this.options.gfm?this.rules=this.options.breaks?u.breaks:u.gfm:this.options.pedantic&&(this.rules=u.pedantic)}function n(e){this.options=e||{}}function r(e){this.tokens=[],this.token=null,this.options=e||a.defaults,this.options.renderer=this.options.renderer||new n,this.renderer=this.options.renderer,this.renderer.options=this.options}function s(e,t){return e.replace(t?/&/g:/&(?!#?\w+;)/g,"&").replace(//g,">").replace(/"/g,""").replace(/'/g,"'")}function i(e){return e.replace(/&([#\w]+);/g,function(e,t){return t=t.toLowerCase(),"colon"===t?":":"#"===t.charAt(0)?String.fromCharCode("x"===t.charAt(1)?parseInt(t.substring(2),16):+t.substring(1)):""})}function l(e,t){return e=e.source,t=t||"",function n(r,s){return r?(s=s.source||s,s=s.replace(/(^|[^\[])\^/g,"$1"),e=e.replace(r,s),n):new RegExp(e,t)}}function o(){}function h(e){for(var t,n,r=1;rAn error occured:

    "+s(c.message+"",!0)+"
    ";throw c}}var p={newline:/^\n+/,code:/^( {4}[^\n]+\n*)+/,fences:o,hr:/^( *[-*_]){3,} *(?:\n+|$)/,heading:/^ *(#{1,6}) *([^\n]+?) *#* *(?:\n+|$)/,nptable:o,lheading:/^([^\n]+)\n *(=|-){2,} *(?:\n+|$)/,blockquote:/^( *>[^\n]+(\n(?!def)[^\n]+)*\n*)+/,list:/^( *)(bull) [\s\S]+?(?:hr|def|\n{2,}(?! )(?!\1bull )\n*|\s*$)/,html:/^ *(?:comment *(?:\n|\s*$)|closed *(?:\n{2,}|\s*$)|closing *(?:\n{2,}|\s*$))/,def:/^ *\[([^\]]+)\]: *]+)>?(?: +["(]([^\n]+)[")])? *(?:\n+|$)/,table:o,paragraph:/^((?:[^\n]+\n?(?!hr|heading|lheading|blockquote|tag|def))+)\n*/,text:/^[^\n]+/};p.bullet=/(?:[*+-]|\d+\.)/,p.item=/^( *)(bull) [^\n]*(?:\n(?!\1bull )[^\n]*)*/,p.item=l(p.item,"gm")(/bull/g,p.bullet)(),p.list=l(p.list)(/bull/g,p.bullet)("hr","\\n+(?=\\1?(?:[-*_] *){3,}(?:\\n+|$))")("def","\\n+(?="+p.def.source+")")(),p.blockquote=l(p.blockquote)("def",p.def)(),p._tag="(?!(?:a|em|strong|small|s|cite|q|dfn|abbr|data|time|code|var|samp|kbd|sub|sup|i|b|u|mark|ruby|rt|rp|bdi|bdo|span|br|wbr|ins|del|img)\\b)\\w+(?!:/|[^\\w\\s@]*@)\\b",p.html=l(p.html)("comment",//)("closed",/<(tag)[\s\S]+?<\/\1>/)("closing",/])*?>/)(/tag/g,p._tag)(),p.paragraph=l(p.paragraph)("hr",p.hr)("heading",p.heading)("lheading",p.lheading)("blockquote",p.blockquote)("tag","<"+p._tag)("def",p.def)(),p.normal=h({},p),p.gfm=h({},p.normal,{fences:/^ *(`{3,}|~{3,}) *(\S+)? *\n([\s\S]+?)\s*\1 *(?:\n+|$)/,paragraph:/^/}),p.gfm.paragraph=l(p.paragraph)("(?!","(?!"+p.gfm.fences.source.replace("\\1","\\2")+"|"+p.list.source.replace("\\1","\\3")+"|")(),p.tables=h({},p.gfm,{nptable:/^ *(\S.*\|.*)\n *([-:]+ *\|[-| :]*)\n((?:.*\|.*(?:\n|$))*)\n*/,table:/^ *\|(.+)\n *\|( *[-:]+[-| :]*)\n((?: *\|.*(?:\n|$))*)\n*/}),e.rules=p,e.lex=function(t,n){var r=new e(n);return r.lex(t)},e.prototype.lex=function(e){return e=e.replace(/\r\n|\r/g,"\n").replace(/\t/g," ").replace(/\u00a0/g," ").replace(/\u2424/g,"\n"),this.token(e,!0)},e.prototype.token=function(e,t,n){for(var r,s,i,l,o,h,a,u,c,e=e.replace(/^ +$/gm,"");e;)if((i=this.rules.newline.exec(e))&&(e=e.substring(i[0].length),i[0].length>1&&this.tokens.push({type:"space"})),i=this.rules.code.exec(e))e=e.substring(i[0].length),i=i[0].replace(/^ {4}/gm,""),this.tokens.push({type:"code",text:this.options.pedantic?i:i.replace(/\n+$/,"")});else if(i=this.rules.fences.exec(e))e=e.substring(i[0].length),this.tokens.push({type:"code",lang:i[2],text:i[3]});else if(i=this.rules.heading.exec(e))e=e.substring(i[0].length),this.tokens.push({type:"heading",depth:i[1].length,text:i[2]});else if(t&&(i=this.rules.nptable.exec(e))){for(e=e.substring(i[0].length),h={type:"table",header:i[1].replace(/^ *| *\| *$/g,"").split(/ *\| */),align:i[2].replace(/^ *|\| *$/g,"").split(/ *\| */),cells:i[3].replace(/\n$/,"").split("\n")},u=0;u ?/gm,""),this.token(i,t,!0),this.tokens.push({type:"blockquote_end"});else if(i=this.rules.list.exec(e)){for(e=e.substring(i[0].length),l=i[2],this.tokens.push({type:"list_start",ordered:l.length>1}),i=i[0].match(this.rules.item),r=!1,c=i.length,u=0;c>u;u++)h=i[u],a=h.length,h=h.replace(/^ *([*+-]|\d+\.) +/,""),~h.indexOf("\n ")&&(a-=h.length,h=this.options.pedantic?h.replace(/^ {1,4}/gm,""):h.replace(new RegExp("^ {1,"+a+"}","gm"),"")),this.options.smartLists&&u!==c-1&&(o=p.bullet.exec(i[u+1])[0],l===o||l.length>1&&o.length>1||(e=i.slice(u+1).join("\n")+e,u=c-1)),s=r||/\n\n(?!\s*$)/.test(h),u!==c-1&&(r="\n"===h.charAt(h.length-1),s||(s=r)),this.tokens.push({type:s?"loose_item_start":"list_item_start"}),this.token(h,!1,n),this.tokens.push({type:"list_item_end"});this.tokens.push({type:"list_end"})}else if(i=this.rules.html.exec(e))e=e.substring(i[0].length),this.tokens.push({type:this.options.sanitize?"paragraph":"html",pre:"pre"===i[1]||"script"===i[1]||"style"===i[1],text:i[0]});else if(!n&&t&&(i=this.rules.def.exec(e)))e=e.substring(i[0].length),this.tokens.links[i[1].toLowerCase()]={href:i[2],title:i[3]};else if(t&&(i=this.rules.table.exec(e))){for(e=e.substring(i[0].length),h={type:"table",header:i[1].replace(/^ *| *\| *$/g,"").split(/ *\| */),align:i[2].replace(/^ *|\| *$/g,"").split(/ *\| */),cells:i[3].replace(/(?: *\| *)?\n$/,"").split("\n")},u=0;u])/,autolink:/^<([^ >]+(@|:\/)[^ >]+)>/,url:o,tag:/^|^<\/?\w+(?:"[^"]*"|'[^']*'|[^'">])*?>/,link:/^!?\[(inside)\]\(href\)/,reflink:/^!?\[(inside)\]\s*\[([^\]]*)\]/,nolink:/^!?\[((?:\[[^\]]*\]|[^\[\]])*)\]/,strong:/^__([\s\S]+?)__(?!_)|^\*\*([\s\S]+?)\*\*(?!\*)/,em:/^\b_((?:__|[\s\S])+?)_\b|^\*((?:\*\*|[\s\S])+?)\*(?!\*)/,code:/^(`+)\s*([\s\S]*?[^`])\s*\1(?!`)/,br:/^ {2,}\n(?!\s*$)/,del:o,text:/^[\s\S]+?(?=[\\?(?:\s+['"]([\s\S]*?)['"])?\s*/,u.link=l(u.link)("inside",u._inside)("href",u._href)(),u.reflink=l(u.reflink)("inside",u._inside)(),u.normal=h({},u),u.pedantic=h({},u.normal,{strong:/^__(?=\S)([\s\S]*?\S)__(?!_)|^\*\*(?=\S)([\s\S]*?\S)\*\*(?!\*)/,em:/^_(?=\S)([\s\S]*?\S)_(?!_)|^\*(?=\S)([\s\S]*?\S)\*(?!\*)/}),u.gfm=h({},u.normal,{escape:l(u.escape)("])","~|])")(),url:/^(https?:\/\/[^\s<]+[^<.,:;"')\]\s])/,del:/^~~(?=\S)([\s\S]*?\S)~~/,text:l(u.text)("]|","~]|")("|","|https?://|")()}),u.breaks=h({},u.gfm,{br:l(u.br)("{2,}","*")(),text:l(u.gfm.text)("{2,}","*")()}),t.rules=u,t.output=function(e,n,r){var s=new t(n,r);return s.output(e)},t.prototype.output=function(e){for(var t,n,r,i,l="";e;)if(i=this.rules.escape.exec(e))e=e.substring(i[0].length),l+=i[1];else if(i=this.rules.autolink.exec(e))e=e.substring(i[0].length),"@"===i[2]?(n=this.mangle(":"===i[1].charAt(6)?i[1].substring(7):i[1]),r=this.mangle("mailto:")+n):(n=s(i[1]),r=n),l+=this.renderer.link(r,null,n);else if(this.inLink||!(i=this.rules.url.exec(e))){if(i=this.rules.tag.exec(e))!this.inLink&&/^
    /i.test(i[0])&&(this.inLink=!1),e=e.substring(i[0].length),l+=this.options.sanitize?s(i[0]):i[0];else if(i=this.rules.link.exec(e))e=e.substring(i[0].length),this.inLink=!0,l+=this.outputLink(i,{href:i[2],title:i[3]}),this.inLink=!1;else if((i=this.rules.reflink.exec(e))||(i=this.rules.nolink.exec(e))){if(e=e.substring(i[0].length),t=(i[2]||i[1]).replace(/\s+/g," "),t=this.links[t.toLowerCase()],!t||!t.href){l+=i[0].charAt(0),e=i[0].substring(1)+e;continue}this.inLink=!0,l+=this.outputLink(i,t),this.inLink=!1}else if(i=this.rules.strong.exec(e))e=e.substring(i[0].length),l+=this.renderer.strong(this.output(i[2]||i[1]));else if(i=this.rules.em.exec(e))e=e.substring(i[0].length),l+=this.renderer.em(this.output(i[2]||i[1]));else if(i=this.rules.code.exec(e))e=e.substring(i[0].length),l+=this.renderer.codespan(s(i[2],!0));else if(i=this.rules.br.exec(e))e=e.substring(i[0].length),l+=this.renderer.br();else if(i=this.rules.del.exec(e))e=e.substring(i[0].length),l+=this.renderer.del(this.output(i[1]));else if(i=this.rules.text.exec(e))e=e.substring(i[0].length),l+=s(this.smartypants(i[0]));else if(e)throw new Error("Infinite loop on byte: "+e.charCodeAt(0))}else e=e.substring(i[0].length),n=s(i[1]),r=n,l+=this.renderer.link(r,null,n);return l},t.prototype.outputLink=function(e,t){var n=s(t.href),r=t.title?s(t.title):null;return"!"!==e[0].charAt(0)?this.renderer.link(n,r,this.output(e[1])):this.renderer.image(n,r,s(e[1]))},t.prototype.smartypants=function(e){return this.options.smartypants?e.replace(/--/g,"—").replace(/(^|[-\u2014/(\[{"\s])'/g,"$1‘").replace(/'/g,"’").replace(/(^|[-\u2014/(\[{\u2018\s])"/g,"$1“").replace(/"/g,"”").replace(/\.{3}/g,"…"):e},t.prototype.mangle=function(e){for(var t,n="",r=e.length,s=0;r>s;s++)t=e.charCodeAt(s),Math.random()>.5&&(t="x"+t.toString(16)),n+="&#"+t+";";return n},n.prototype.code=function(e,t,n){if(this.options.highlight){var r=this.options.highlight(e,t);null!=r&&r!==e&&(n=!0,e=r)}return t?'
    '+(n?e:s(e,!0))+"\n
    \n":"
    "+(n?e:s(e,!0))+"\n
    "},n.prototype.blockquote=function(e){return"
    \n"+e+"
    \n"},n.prototype.html=function(e){return e},n.prototype.heading=function(e,t,n){return"'+e+"\n"},n.prototype.hr=function(){return this.options.xhtml?"
    \n":"
    \n"},n.prototype.list=function(e,t){var n=t?"ol":"ul";return"<"+n+">\n"+e+"\n"},n.prototype.listitem=function(e){return"
  • "+e+"
  • \n"},n.prototype.paragraph=function(e){return"

    "+e+"

    \n"},n.prototype.table=function(e,t){return"\n\n"+e+"\n\n"+t+"\n
    \n"},n.prototype.tablerow=function(e){return"\n"+e+"\n"},n.prototype.tablecell=function(e,t){var n=t.header?"th":"td",r=t.align?"<"+n+' style="text-align:'+t.align+'">':"<"+n+">";return r+e+"\n"},n.prototype.strong=function(e){return""+e+""},n.prototype.em=function(e){return""+e+""},n.prototype.codespan=function(e){return""+e+""},n.prototype.br=function(){return this.options.xhtml?"
    ":"
    "},n.prototype.del=function(e){return""+e+""},n.prototype.link=function(e,t,n){if(this.options.sanitize){try{var r=decodeURIComponent(i(e)).replace(/[^\w:]/g,"").toLowerCase()}catch(s){return""}if(0===r.indexOf("javascript:")||0===r.indexOf("vbscript:"))return""}var l='
    "},n.prototype.image=function(e,t,n){var r=''+n+'":">"},r.parse=function(e,t,n){var s=new r(t,n);return s.parse(e)},r.prototype.parse=function(e){this.inline=new t(e.links,this.options,this.renderer),this.tokens=e.reverse();for(var n="";this.next();)n+=this.tok();return n},r.prototype.next=function(){return this.token=this.tokens.pop()},r.prototype.peek=function(){return this.tokens[this.tokens.length-1]||0},r.prototype.parseText=function(){for(var e=this.token.text;"text"===this.peek().type;)e+="\n"+this.next().text;return this.inline.output(e)},r.prototype.tok=function(){switch(this.token.type){case"space":return"";case"hr":return this.renderer.hr();case"heading":return this.renderer.heading(this.inline.output(this.token.text),this.token.depth,this.token.text);case"code":return this.renderer.code(this.token.text,this.token.lang,this.token.escaped);case"table":var e,t,n,r,s,i="",l="";for(n="",e=0;ebody{font-family: sans-serif;}

    reveal.js multiplex server.

    Generate token'); - res.end(); - }); - stream.on('readable', function() { - stream.pipe(res); - }); + fs.createReadStream(opts.baseDir + '/index.html').pipe(res); }); app.get("/token", function(req,res) { @@ -55,7 +47,7 @@ var createHash = function(secret) { }; // Actually listen -server.listen( opts.port || null ); +app.listen(opts.port || null); var brown = '\033[33m', green = '\033[32m', diff --git a/doc/pub/Regression/html/reveal.js/plugin/multiplex/master.js b/doc/pub/Regression/html/reveal.js/plugin/multiplex/master.js index 7f4bf4511..b6a7eb7dc 100644 --- a/doc/pub/Regression/html/reveal.js/plugin/multiplex/master.js +++ b/doc/pub/Regression/html/reveal.js/plugin/multiplex/master.js @@ -1,34 +1,51 @@ (function() { - // Don't emit events from inside of notes windows if ( window.location.search.match( /receiver/gi ) ) { return; } var multiplex = Reveal.getConfig().multiplex; - var socket = io.connect( multiplex.url ); + var socket = io.connect(multiplex.url); - function post() { + var notify = function( slideElement, indexh, indexv, origin ) { + if( typeof origin === 'undefined' && origin !== 'remote' ) { + var nextindexh; + var nextindexv; - var messageData = { - state: Reveal.getState(), - secret: multiplex.secret, - socketId: multiplex.id - }; + var fragmentindex = Reveal.getIndices().f; + if (typeof fragmentindex == 'undefined') { + fragmentindex = 0; + } - socket.emit( 'multiplex-statechanged', messageData ); + if (slideElement.nextElementSibling && slideElement.parentNode.nodeName == 'SECTION') { + nextindexh = indexh; + nextindexv = indexv + 1; + } else { + nextindexh = indexh + 1; + nextindexv = 0; + } + var slideData = { + indexh : indexh, + indexv : indexv, + indexf : fragmentindex, + nextindexh : nextindexh, + nextindexv : nextindexv, + secret: multiplex.secret, + socketId : multiplex.id + }; + + socket.emit('slidechanged', slideData); + } + } + + Reveal.addEventListener( 'slidechanged', function( event ) { + notify( event.currentSlide, event.indexh, event.indexv, event.origin ); + } ); + + var fragmentNotify = function( event ) { + notify( Reveal.getCurrentSlide(), Reveal.getIndices().h, Reveal.getIndices().v, event.origin ); }; - // post once the page is loaded, so the client follows also on "open URL". - window.addEventListener( 'load', post ); - - // Monitor events that trigger a change in state - Reveal.addEventListener( 'slidechanged', post ); - Reveal.addEventListener( 'fragmentshown', post ); - Reveal.addEventListener( 'fragmenthidden', post ); - Reveal.addEventListener( 'overviewhidden', post ); - Reveal.addEventListener( 'overviewshown', post ); - Reveal.addEventListener( 'paused', post ); - Reveal.addEventListener( 'resumed', post ); - -}()); + Reveal.addEventListener( 'fragmentshown', fragmentNotify ); + Reveal.addEventListener( 'fragmenthidden', fragmentNotify ); +}()); \ No newline at end of file diff --git a/doc/pub/Regression/html/reveal.js/plugin/notes-server/client.js b/doc/pub/Regression/html/reveal.js/plugin/notes-server/client.js index 00b277baf..628586ffb 100644 --- a/doc/pub/Regression/html/reveal.js/plugin/notes-server/client.js +++ b/doc/pub/Regression/html/reveal.js/plugin/notes-server/client.js @@ -41,15 +41,10 @@ } // When a new notes window connects, post our current state - socket.on( 'new-subscriber', function( data ) { + socket.on( 'connect', function( data ) { post(); } ); - // When the state changes from inside of the speaker view - socket.on( 'statechanged-speaker', function( data ) { - Reveal.setState( data.state ); - } ); - // Monitor events that trigger a change in state Reveal.addEventListener( 'slidechanged', post ); Reveal.addEventListener( 'fragmentshown', post ); diff --git a/doc/pub/Regression/html/reveal.js/plugin/notes-server/index.js b/doc/pub/Regression/html/reveal.js/plugin/notes-server/index.js index b95f07188..df917f112 100644 --- a/doc/pub/Regression/html/reveal.js/plugin/notes-server/index.js +++ b/doc/pub/Regression/html/reveal.js/plugin/notes-server/index.js @@ -1,40 +1,37 @@ -var http = require('http'); var express = require('express'); var fs = require('fs'); var io = require('socket.io'); +var _ = require('underscore'); var Mustache = require('mustache'); -var app = express(); +var app = express.createServer(); var staticDir = express.static; -var server = http.createServer(app); -io = io(server); +io = io.listen(app); var opts = { port : 1947, baseDir : __dirname + '/../../' }; -io.on( 'connection', function( socket ) { +io.sockets.on( 'connection', function( socket ) { - socket.on( 'new-subscriber', function( data ) { - socket.broadcast.emit( 'new-subscriber', data ); + socket.on( 'connect', function( data ) { + socket.broadcast.emit( 'connect', data ); }); socket.on( 'statechanged', function( data ) { - delete data.state.overview; socket.broadcast.emit( 'statechanged', data ); }); - socket.on( 'statechanged-speaker', function( data ) { - delete data.state.overview; - socket.broadcast.emit( 'statechanged-speaker', data ); - }); - }); -[ 'css', 'js', 'images', 'plugin', 'lib' ].forEach( function( dir ) { - app.use( '/' + dir, staticDir( opts.baseDir + dir ) ); +app.configure( function() { + + [ 'css', 'js', 'images', 'plugin', 'lib' ].forEach( function( dir ) { + app.use( '/' + dir, staticDir( opts.baseDir + dir ) ); + }); + }); app.get('/', function( req, res ) { @@ -55,7 +52,7 @@ app.get( '/notes/:socketId', function( req, res ) { }); // Actually listen -server.listen( opts.port || null ); +app.listen( opts.port || null ); var brown = '\033[33m', green = '\033[32m', @@ -65,5 +62,5 @@ var slidesLocation = 'http://localhost' + ( opts.port ? ( ':' + opts.port ) : '' console.log( brown + 'reveal.js - Speaker Notes' + reset ); console.log( '1. Open the slides at ' + green + slidesLocation + reset ); -console.log( '2. Click on the link in your JS console to go to the notes page' ); +console.log( '2. Click on the link your JS console to go to the notes page' ); console.log( '3. Advance through your slides and your notes will advance automatically' ); diff --git a/doc/pub/Regression/html/reveal.js/plugin/notes-server/notes.html b/doc/pub/Regression/html/reveal.js/plugin/notes-server/notes.html index ab8c5b17a..72d0317f1 100644 --- a/doc/pub/Regression/html/reveal.js/plugin/notes-server/notes.html +++ b/doc/pub/Regression/html/reveal.js/plugin/notes-server/notes.html @@ -8,7 +8,6 @@ @@ -247,7 +152,7 @@
    -
    Upcoming
    +
    UPCOMING:

    Time Click to Reset

    @@ -265,10 +170,6 @@
    -
    - - -
    @@ -281,20 +182,11 @@ currentState, currentSlide, upcomingSlide, - layoutLabel, - layoutDropdown, connected = false; var socket = io.connect( window.location.origin ), socketId = '{{socketId}}'; - var SPEAKER_LAYOUTS = { - 'default': 'Default', - 'wide': 'Wide', - 'tall': 'Tall', - 'notes-only': 'Notes only' - }; - socket.on( 'statechanged', function( data ) { // ignore data from sockets that aren't ours @@ -303,6 +195,7 @@ if( connected === false ) { connected = true; + setupIframes( data ); setupKeyboard(); setupNotes(); setupTimer(); @@ -313,28 +206,13 @@ } ); - setupLayout(); - - // Load our presentation iframes - setupIframes(); - - // Once the iframes have loaded, emit a signal saying there's - // a new subscriber which will trigger a 'statechanged' - // message to be sent back window.addEventListener( 'message', function( event ) { var data = JSON.parse( event.data ); if( data && data.namespace === 'reveal' ) { if( /ready/.test( data.eventName ) ) { - socket.emit( 'new-subscriber', { socketId: socketId } ); - } - } - - // Messages sent by reveal.js inside of the current slide preview - if( data && data.namespace === 'reveal' ) { - if( /slidechanged|fragmentshown|fragmenthidden|overviewshown|overviewhidden|paused|resumed/.test( data.eventName ) && currentState !== JSON.stringify( data.state ) ) { - socket.emit( 'statechanged-speaker', { state: data.state } ); + socket.emit( 'connect', { socketId: socketId } ); } } @@ -389,7 +267,7 @@ /** * Creates the preview iframes. */ - function setupIframes() { + function setupIframes( data ) { var params = [ 'receiver', @@ -399,8 +277,9 @@ 'backgroundTransition=none' ].join( '&' ); - var currentURL = '/?' + params + '&postMessageEvents=true'; - var upcomingURL = '/?' + params + '&controls=false'; + var hash = '#/' + data.state.indexh + '/' + data.state.indexv; + var currentURL = '/?' + params + '&postMessageEvents=true' + hash; + var upcomingURL = '/?' + params + '&controls=false' + hash; currentSlide = document.createElement( 'iframe' ); currentSlide.setAttribute( 'width', 1280 ); @@ -472,74 +351,6 @@ } - /** - * Sets up the speaker view layout and layout selector. - */ - function setupLayout() { - - layoutDropdown = document.querySelector( '.speaker-layout-dropdown' ); - layoutLabel = document.querySelector( '.speaker-layout-label' ); - - // Render the list of available layouts - for( var id in SPEAKER_LAYOUTS ) { - var option = document.createElement( 'option' ); - option.setAttribute( 'value', id ); - option.textContent = SPEAKER_LAYOUTS[ id ]; - layoutDropdown.appendChild( option ); - } - - // Monitor the dropdown for changes - layoutDropdown.addEventListener( 'change', function( event ) { - - setLayout( layoutDropdown.value ); - - }, false ); - - // Restore any currently persisted layout - setLayout( getLayout() ); - - } - - /** - * Sets a new speaker view layout. The layout is persisted - * in local storage. - */ - function setLayout( value ) { - - var title = SPEAKER_LAYOUTS[ value ]; - - layoutLabel.innerHTML = 'Layout' + ( title ? ( ': ' + title ) : '' ); - layoutDropdown.value = value; - - document.body.setAttribute( 'data-speaker-layout', value ); - - // Persist locally - if( window.localStorage ) { - window.localStorage.setItem( 'reveal-speaker-layout', value ); - } - - } - - /** - * Returns the ID of the most recently set speaker layout - * or our default layout if none has been set. - */ - function getLayout() { - - if( window.localStorage ) { - var layout = window.localStorage.getItem( 'reveal-speaker-layout' ); - if( layout ) { - return layout; - } - } - - // Default to the first record in the layouts hash - for( var id in SPEAKER_LAYOUTS ) { - return id; - } - - } - function zeroPadInteger( num ) { var str = '00' + parseInt( num ); diff --git a/doc/pub/Regression/html/reveal.js/plugin/notes/notes.html b/doc/pub/Regression/html/reveal.js/plugin/notes/notes.html index 4c5b799b5..0cc8cf612 100644 --- a/doc/pub/Regression/html/reveal.js/plugin/notes/notes.html +++ b/doc/pub/Regression/html/reveal.js/plugin/notes/notes.html @@ -8,7 +8,6 @@