diff --git a/doc/pub/week35/html/._week35-bs000.html b/doc/pub/week35/html/._week35-bs000.html index f1a81b669..1d8b1baef 100644 --- a/doc/pub/week35/html/._week35-bs000.html +++ b/doc/pub/week35/html/._week35-bs000.html @@ -38,7 +38,6 @@ doconce format html week35.do.txt --html_style=bootstrap --pygments_html_style=d {'highest level': 2, 'sections': [('Plans for week 35', 2, None, 'plans-for-week-35'), ('Reading recommendations:', 3, None, 'reading-recommendations'), - ('Topics of week 35', 2, None, 'topics-of-week-35'), ('Why Linear Regression (aka Ordinary Least Squares and family), ' 'repeat from last week', 2, @@ -301,78 +300,77 @@ MathJax.Hub.Config({ @@ -402,7 +400,7 @@ MathJax.Hub.Config({
-

May 29, 2023

+

Jul 5, 2023


@@ -427,7 +425,7 @@ MathJax.Hub.Config({
  • 9
  • 10
  • ...
  • -
  • 69
  • +
  • 68
  • »
  • diff --git a/doc/pub/week35/html/._week35-bs001.html b/doc/pub/week35/html/._week35-bs001.html index e6c12bfb4..6fa4b56fc 100644 --- a/doc/pub/week35/html/._week35-bs001.html +++ b/doc/pub/week35/html/._week35-bs001.html @@ -38,7 +38,6 @@ doconce format html week35.do.txt --html_style=bootstrap --pygments_html_style=d {'highest level': 2, 'sections': [('Plans for week 35', 2, None, 'plans-for-week-35'), ('Reading recommendations:', 3, None, 'reading-recommendations'), - ('Topics of week 35', 2, None, 'topics-of-week-35'), ('Why Linear Regression (aka Ordinary Least Squares and family), ' 'repeat from last week', 2, @@ -301,78 +300,77 @@ MathJax.Hub.Config({ @@ -386,10 +384,14 @@ MathJax.Hub.Config({

    Plans for week 35

    - +

    The main topics are:

    +
      +
    1. Repetition from last week on linear regression
    2. +
    3. Reminder on statistics with quantities like mean values, variance abd covariance
    4. +
    5. Discussion of how to prepare data and examples of applications of linear regression
    6. +
    7. Mathematical interpretations of Linear Regression
    8. +
    9. Start discussing Ridge and Lasso regression and Singular Value Decomposition
    10. +

    Reading recommendations:

    1. See lecture notes for week 35 at https://compphysics.github.io/MachineLearning/doc/web/course.html
    2. @@ -414,7 +416,7 @@ MathJax.Hub.Config({
    3. 10
    4. 11
    5. ...
    6. -
    7. 69
    8. +
    9. 68
    10. »
    11. diff --git a/doc/pub/week35/html/._week35-bs002.html b/doc/pub/week35/html/._week35-bs002.html index d8b4543c8..ac172751e 100644 --- a/doc/pub/week35/html/._week35-bs002.html +++ b/doc/pub/week35/html/._week35-bs002.html @@ -38,7 +38,6 @@ doconce format html week35.do.txt --html_style=bootstrap --pygments_html_style=d {'highest level': 2, 'sections': [('Plans for week 35', 2, None, 'plans-for-week-35'), ('Reading recommendations:', 3, None, 'reading-recommendations'), - ('Topics of week 35', 2, None, 'topics-of-week-35'), ('Why Linear Regression (aka Ordinary Least Squares and family), ' 'repeat from last week', 2, @@ -301,78 +300,77 @@ MathJax.Hub.Config({ @@ -384,16 +382,26 @@ MathJax.Hub.Config({

       

       

       

      -

      Topics of week 35

      +

      Why Linear Regression (aka Ordinary Least Squares and family), repeat from last week

      + +

      We need first a reminder from last week about linear regression.

      + +

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

      + +

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

      -

      The main topics are:

      -
        -
      1. Repetition from last week on linear regression
      2. -
      3. Reminder on statistics with quantities like mean values, variance abd covariance
      4. -
      5. Discussion of how to prepare data and examples of applications of linear regression
      6. -
      7. Mathematical interpretations of Linear Regression
      8. -
      9. Start discussing Ridge and Lasso regression and Singular Value Decomposition
      10. -

      diff --git a/doc/pub/week35/html/._week35-bs003.html b/doc/pub/week35/html/._week35-bs003.html index c9c25dd0b..193110ba2 100644 --- a/doc/pub/week35/html/._week35-bs003.html +++ b/doc/pub/week35/html/._week35-bs003.html @@ -38,7 +38,6 @@ doconce format html week35.do.txt --html_style=bootstrap --pygments_html_style=d {'highest level': 2, 'sections': [('Plans for week 35', 2, None, 'plans-for-week-35'), ('Reading recommendations:', 3, None, 'reading-recommendations'), - ('Topics of week 35', 2, None, 'topics-of-week-35'), ('Why Linear Regression (aka Ordinary Least Squares and family), ' 'repeat from last week', 2, @@ -301,78 +300,77 @@ MathJax.Hub.Config({ @@ -384,26 +382,26 @@ MathJax.Hub.Config({

       

       

       

      -

      Why Linear Regression (aka Ordinary Least Squares and family), repeat from last week

      +

      Regression analysis, overarching aims

      +
      +
      + -

      We need first a reminder from last week about linear regression.

      - -

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

      +
      +
      + +

      diff --git a/doc/pub/week35/html/._week35-bs004.html b/doc/pub/week35/html/._week35-bs004.html index 61a8ddd8b..cbd3a0a00 100644 --- a/doc/pub/week35/html/._week35-bs004.html +++ b/doc/pub/week35/html/._week35-bs004.html @@ -38,7 +38,6 @@ doconce format html week35.do.txt --html_style=bootstrap --pygments_html_style=d {'highest level': 2, 'sections': [('Plans for week 35', 2, None, 'plans-for-week-35'), ('Reading recommendations:', 3, None, 'reading-recommendations'), - ('Topics of week 35', 2, None, 'topics-of-week-35'), ('Why Linear Regression (aka Ordinary Least Squares and family), ' 'repeat from last week', 2, @@ -301,78 +300,77 @@ MathJax.Hub.Config({ @@ -384,22 +382,30 @@ MathJax.Hub.Config({

       

       

       

      -

      Regression analysis, overarching aims

      +

      Regression analysis, overarching aims II

      -

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

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

      -

      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.

      +

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

      @@ -423,7 +429,7 @@ The first variable is called the dependent, the outcome or the
    12. 13
    13. 14
    14. ...
    15. -
    16. 69
    17. +
    18. 68
    19. »
    20. diff --git a/doc/pub/week35/html/._week35-bs005.html b/doc/pub/week35/html/._week35-bs005.html index 6f5d792f8..90eb6106b 100644 --- a/doc/pub/week35/html/._week35-bs005.html +++ b/doc/pub/week35/html/._week35-bs005.html @@ -38,7 +38,6 @@ doconce format html week35.do.txt --html_style=bootstrap --pygments_html_style=d {'highest level': 2, 'sections': [('Plans for week 35', 2, None, 'plans-for-week-35'), ('Reading recommendations:', 3, None, 'reading-recommendations'), - ('Topics of week 35', 2, None, 'topics-of-week-35'), ('Why Linear Regression (aka Ordinary Least Squares and family), ' 'repeat from last week', 2, @@ -301,78 +300,77 @@ MathJax.Hub.Config({ @@ -384,30 +382,29 @@ MathJax.Hub.Config({

       

       

       

      -

      Regression analysis, overarching aims II

      +

      Examples

      - -

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

      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.

      -

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

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

      -

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

      +

      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 \). This is however a classification problem and we will come back to it when we discuss Logistic Regression. +

      @@ -432,7 +429,7 @@ the linear regression model where \( \boldsymbol{\beta} = [\beta_0, \ld
    21. 14
    22. 15
    23. ...
    24. -
    25. 69
    26. +
    27. 68
    28. »
    29. diff --git a/doc/pub/week35/html/._week35-bs006.html b/doc/pub/week35/html/._week35-bs006.html index 5dcb354e6..ebe28a33e 100644 --- a/doc/pub/week35/html/._week35-bs006.html +++ b/doc/pub/week35/html/._week35-bs006.html @@ -38,7 +38,6 @@ doconce format html week35.do.txt --html_style=bootstrap --pygments_html_style=d {'highest level': 2, 'sections': [('Plans for week 35', 2, None, 'plans-for-week-35'), ('Reading recommendations:', 3, None, 'reading-recommendations'), - ('Topics of week 35', 2, None, 'topics-of-week-35'), ('Why Linear Regression (aka Ordinary Least Squares and family), ' 'repeat from last week', 2, @@ -301,78 +300,77 @@ MathJax.Hub.Config({ @@ -384,29 +382,18 @@ MathJax.Hub.Config({

       

       

       

      -

      Examples

      +

      General linear models

      -

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

      +

      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.

      -

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

      +

      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

      $$ -BE(A) = a_0+a_1A+a_2A^{2/3}+a_3A^{-1/3}+a_4A^{-1}, +y=y(x) \rightarrow y(x_i)=\tilde{y}_i+\epsilon_i=\sum_{j=0}^{n-1} \beta_j x_i^j+\epsilon_i, $$ -

      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 \). This is however a classification problem and we will come back to it when we discuss Logistic Regression. -

      +

      where \( \epsilon_i \) is the error in our approximation.

      @@ -432,7 +419,7 @@ so-called 15
    30. 16
    31. ...
    32. -
    33. 69
    34. +
    35. 68
    36. »
    37. diff --git a/doc/pub/week35/html/._week35-bs007.html b/doc/pub/week35/html/._week35-bs007.html index 8e7c3cbef..0f5a1ee91 100644 --- a/doc/pub/week35/html/._week35-bs007.html +++ b/doc/pub/week35/html/._week35-bs007.html @@ -38,7 +38,6 @@ doconce format html week35.do.txt --html_style=bootstrap --pygments_html_style=d {'highest level': 2, 'sections': [('Plans for week 35', 2, None, 'plans-for-week-35'), ('Reading recommendations:', 3, None, 'reading-recommendations'), - ('Topics of week 35', 2, None, 'topics-of-week-35'), ('Why Linear Regression (aka Ordinary Least Squares and family), ' 'repeat from last week', 2, @@ -301,78 +300,77 @@ MathJax.Hub.Config({ @@ -384,18 +382,20 @@ MathJax.Hub.Config({

       

       

       

      -

      General linear models

      +

      Rewriting the fitting procedure as a linear algebra problem

      -

      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

      +

      For every set of values \( y_i,x_i \) we have thus the corresponding set of equations

      $$ -y=y(x) \rightarrow y(x_i)=\tilde{y}_i+\epsilon_i=\sum_{j=0}^{n-1} \beta_j x_i^j+\epsilon_i, +\begin{align*} +y_0&=\beta_0+\beta_1x_0^1+\beta_2x_0^2+\dots+\beta_{n-1}x_0^{n-1}+\epsilon_0\\ +y_1&=\beta_0+\beta_1x_1^1+\beta_2x_1^2+\dots+\beta_{n-1}x_1^{n-1}+\epsilon_1\\ +y_2&=\beta_0+\beta_1x_2^1+\beta_2x_2^2+\dots+\beta_{n-1}x_2^{n-1}+\epsilon_2\\ +\dots & \dots \\ +y_{n-1}&=\beta_0+\beta_1x_{n-1}^1+\beta_2x_{n-1}^2+\dots+\beta_{n-1}x_{n-1}^{n-1}+\epsilon_{n-1}.\\ +\end{align*} $$ - -

      where \( \epsilon_i \) is the error in our approximation.

      @@ -422,7 +422,7 @@ $$
    38. 16
    39. 17
    40. ...
    41. -
    42. 69
    43. +
    44. 68
    45. »
    46. diff --git a/doc/pub/week35/html/._week35-bs008.html b/doc/pub/week35/html/._week35-bs008.html index 0351c18fe..89791fcec 100644 --- a/doc/pub/week35/html/._week35-bs008.html +++ b/doc/pub/week35/html/._week35-bs008.html @@ -38,7 +38,6 @@ doconce format html week35.do.txt --html_style=bootstrap --pygments_html_style=d {'highest level': 2, 'sections': [('Plans for week 35', 2, None, 'plans-for-week-35'), ('Reading recommendations:', 3, None, 'reading-recommendations'), - ('Topics of week 35', 2, None, 'topics-of-week-35'), ('Why Linear Regression (aka Ordinary Least Squares and family), ' 'repeat from last week', 2, @@ -301,78 +300,77 @@ MathJax.Hub.Config({ @@ -384,20 +382,43 @@ MathJax.Hub.Config({

       

       

       

      -

      Rewriting the fitting procedure as a linear algebra problem

      +

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

      -

      For every set of values \( y_i,x_i \) we have thus the corresponding set of equations

      +

      Defining the vectors

      $$ -\begin{align*} -y_0&=\beta_0+\beta_1x_0^1+\beta_2x_0^2+\dots+\beta_{n-1}x_0^{n-1}+\epsilon_0\\ -y_1&=\beta_0+\beta_1x_1^1+\beta_2x_1^2+\dots+\beta_{n-1}x_1^{n-1}+\epsilon_1\\ -y_2&=\beta_0+\beta_1x_2^1+\beta_2x_2^2+\dots+\beta_{n-1}x_2^{n-1}+\epsilon_2\\ -\dots & \dots \\ -y_{n-1}&=\beta_0+\beta_1x_{n-1}^1+\beta_2x_{n-1}^2+\dots+\beta_{n-1}x_{n-1}^{n-1}+\epsilon_{n-1}.\\ -\end{align*} +\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} +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

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

      The above design matrix is called a Vandermonde matrix.

      @@ -425,7 +446,7 @@ $$
    47. 17
    48. 18
    49. ...
    50. -
    51. 69
    52. +
    53. 68
    54. »
    55. diff --git a/doc/pub/week35/html/._week35-bs009.html b/doc/pub/week35/html/._week35-bs009.html index 68ffa7cc6..dbc73c491 100644 --- a/doc/pub/week35/html/._week35-bs009.html +++ b/doc/pub/week35/html/._week35-bs009.html @@ -38,7 +38,6 @@ doconce format html week35.do.txt --html_style=bootstrap --pygments_html_style=d {'highest level': 2, 'sections': [('Plans for week 35', 2, None, 'plans-for-week-35'), ('Reading recommendations:', 3, None, 'reading-recommendations'), - ('Topics of week 35', 2, None, 'topics-of-week-35'), ('Why Linear Regression (aka Ordinary Least Squares and family), ' 'repeat from last week', 2, @@ -301,78 +300,77 @@ MathJax.Hub.Config({ @@ -384,43 +382,32 @@ MathJax.Hub.Config({

       

       

       

      -

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

      +

      Generalizing the fitting procedure as a linear algebra problem

      -

      Defining the vectors

      + +

      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 +

      + $$ -\boldsymbol{y} = [y_0,y_1, y_2,\dots, y_{n-1}]^T, +\begin{align*} +y_0&=\beta_0x_{00}+\beta_1x_{01}+\beta_2x_{02}+\dots+\beta_{n-1}x_{0n-1}+\epsilon_0\\ +y_1&=\beta_0x_{10}+\beta_1x_{11}+\beta_2x_{12}+\dots+\beta_{n-1}x_{1n-1}+\epsilon_1\\ +y_2&=\beta_0x_{20}+\beta_1x_{21}+\beta_2x_{22}+\dots+\beta_{n-1}x_{2n-1}+\epsilon_2\\ +\dots & \dots \\ +y_{i}&=\beta_0x_{i0}+\beta_1x_{i1}+\beta_2x_{i2}+\dots+\beta_{n-1}x_{in-1}+\epsilon_i\\ +\dots & \dots \\ +y_{n-1}&=\beta_0x_{n-1,0}+\beta_1x_{n-1,2}+\beta_2x_{n-1,2}+\dots+\beta_{n-1}x_{n-1,n-1}+\epsilon_{n-1}.\\ +\end{align*} $$ -

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

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

      The above design matrix is called a Vandermonde matrix.

      +Note that we have \( p=n \) here. The matrix is symmetric. This is generally not the case!
      @@ -449,7 +436,7 @@ $$
    56. 18
    57. 19
    58. ...
    59. -
    60. 69
    61. +
    62. 68
    63. »
    64. diff --git a/doc/pub/week35/html/._week35-bs010.html b/doc/pub/week35/html/._week35-bs010.html index 0260011bc..50df538a8 100644 --- a/doc/pub/week35/html/._week35-bs010.html +++ b/doc/pub/week35/html/._week35-bs010.html @@ -38,7 +38,6 @@ doconce format html week35.do.txt --html_style=bootstrap --pygments_html_style=d {'highest level': 2, 'sections': [('Plans for week 35', 2, None, 'plans-for-week-35'), ('Reading recommendations:', 3, None, 'reading-recommendations'), - ('Topics of week 35', 2, None, 'topics-of-week-35'), ('Why Linear Regression (aka Ordinary Least Squares and family), ' 'repeat from last week', 2, @@ -301,78 +300,77 @@ MathJax.Hub.Config({ @@ -388,28 +386,24 @@ MathJax.Hub.Config({
      - -

      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 -

      - +

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

      $$ -\begin{align*} -y_0&=\beta_0x_{00}+\beta_1x_{01}+\beta_2x_{02}+\dots+\beta_{n-1}x_{0n-1}+\epsilon_0\\ -y_1&=\beta_0x_{10}+\beta_1x_{11}+\beta_2x_{12}+\dots+\beta_{n-1}x_{1n-1}+\epsilon_1\\ -y_2&=\beta_0x_{20}+\beta_1x_{21}+\beta_2x_{22}+\dots+\beta_{n-1}x_{2n-1}+\epsilon_2\\ -\dots & \dots \\ -y_{i}&=\beta_0x_{i0}+\beta_1x_{i1}+\beta_2x_{i2}+\dots+\beta_{n-1}x_{in-1}+\epsilon_i\\ -\dots & \dots \\ -y_{n-1}&=\beta_0x_{n-1,0}+\beta_1x_{n-1,2}+\beta_2x_{n-1,2}+\dots+\beta_{n-1}x_{n-1,n-1}+\epsilon_{n-1}.\\ -\end{align*} +\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 without loss of generality we rewrite again our equations as

      +$$ +\boldsymbol{y} = \boldsymbol{X}\boldsymbol{\beta}+\boldsymbol{\epsilon}. +$$ -Note that we have \( p=n \) here. The matrix is symmetric. This is generally not the case! +

      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?

      @@ -439,7 +433,7 @@ $$
    65. 19
    66. 20
    67. ...
    68. -
    69. 69
    70. +
    71. 68
    72. »
    73. diff --git a/doc/pub/week35/html/._week35-bs011.html b/doc/pub/week35/html/._week35-bs011.html index f31e17159..3dc9f73f1 100644 --- a/doc/pub/week35/html/._week35-bs011.html +++ b/doc/pub/week35/html/._week35-bs011.html @@ -38,7 +38,6 @@ doconce format html week35.do.txt --html_style=bootstrap --pygments_html_style=d {'highest level': 2, 'sections': [('Plans for week 35', 2, None, 'plans-for-week-35'), ('Reading recommendations:', 3, None, 'reading-recommendations'), - ('Topics of week 35', 2, None, 'topics-of-week-35'), ('Why Linear Regression (aka Ordinary Least Squares and family), ' 'repeat from last week', 2, @@ -301,78 +300,77 @@ MathJax.Hub.Config({ @@ -384,28 +382,27 @@ MathJax.Hub.Config({

       

       

       

      -

      Generalizing the fitting procedure as a linear algebra problem

      +

      Optimizing our parameters

      -

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

      +

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

      $$ -\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} +\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*} $$ -

      and without loss of generality we rewrite again our equations as

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

      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?

      +

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

      @@ -435,7 +432,7 @@ $$
    74. 20
    75. 21
    76. ...
    77. -
    78. 69
    79. +
    80. 68
    81. »
    82. diff --git a/doc/pub/week35/html/._week35-bs012.html b/doc/pub/week35/html/._week35-bs012.html index 726d9e950..ed3a6cbee 100644 --- a/doc/pub/week35/html/._week35-bs012.html +++ b/doc/pub/week35/html/._week35-bs012.html @@ -38,7 +38,6 @@ doconce format html week35.do.txt --html_style=bootstrap --pygments_html_style=d {'highest level': 2, 'sections': [('Plans for week 35', 2, None, 'plans-for-week-35'), ('Reading recommendations:', 3, None, 'reading-recommendations'), - ('Topics of week 35', 2, None, 'topics-of-week-35'), ('Why Linear Regression (aka Ordinary Least Squares and family), ' 'repeat from last week', 2, @@ -301,78 +300,77 @@ MathJax.Hub.Config({ @@ -384,30 +382,108 @@ MathJax.Hub.Config({

       

       

       

      -

      Optimizing our parameters

      -
      -
      - -

      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\\ -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*} -$$ +

      Our model for the nuclear binding energies

      -

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

      +

      In our introductory notes we looked at the so-called liquid 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.

      @@ -434,7 +510,7 @@ our matrix as \( \boldsymbol{X}\in {\mathbb{R}}^{n\times p} \), with the predict

    83. 21
    84. 22
    85. ...
    86. -
    87. 69
    88. +
    89. 68
    90. »
    91. diff --git a/doc/pub/week35/html/._week35-bs013.html b/doc/pub/week35/html/._week35-bs013.html index 5ecfeba4f..8f688de2c 100644 --- a/doc/pub/week35/html/._week35-bs013.html +++ b/doc/pub/week35/html/._week35-bs013.html @@ -38,7 +38,6 @@ doconce format html week35.do.txt --html_style=bootstrap --pygments_html_style=d {'highest level': 2, 'sections': [('Plans for week 35', 2, None, 'plans-for-week-35'), ('Reading recommendations:', 3, None, 'reading-recommendations'), - ('Topics of week 35', 2, None, 'topics-of-week-35'), ('Why Linear Regression (aka Ordinary Least Squares and family), ' 'repeat from last week', 2, @@ -301,78 +300,77 @@ MathJax.Hub.Config({ @@ -384,108 +382,39 @@ MathJax.Hub.Config({

       

       

       

      -

      Our model for the nuclear binding energies

      - -

      In our introductory notes we looked at the so-called liquid 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

      +

      Optimizing our parameters, more details

      +
      +
      + +

      With the above we use the design matrix to define the approximation \( \boldsymbol{\tilde{y}} \) via the unknown quantity \( \boldsymbol{\beta} \) as

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

      throughout these lectures.

      +

      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

      +$$ +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 \( \boldsymbol{X} \) and in a more compact matrix-vector notation as

      +$$ +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\}. +$$ + +

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

      + +

      It is also common to define +the function \( C \) 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.

      +
      +
      +

      @@ -512,7 +441,7 @@ $$

    92. 22
    93. 23
    94. ...
    95. -
    96. 69
    97. +
    98. 68
    99. »
    100. diff --git a/doc/pub/week35/html/._week35-bs014.html b/doc/pub/week35/html/._week35-bs014.html index 69638e430..821813e45 100644 --- a/doc/pub/week35/html/._week35-bs014.html +++ b/doc/pub/week35/html/._week35-bs014.html @@ -38,7 +38,6 @@ doconce format html week35.do.txt --html_style=bootstrap --pygments_html_style=d {'highest level': 2, 'sections': [('Plans for week 35', 2, None, 'plans-for-week-35'), ('Reading recommendations:', 3, None, 'reading-recommendations'), - ('Topics of week 35', 2, None, 'topics-of-week-35'), ('Why Linear Regression (aka Ordinary Least Squares and family), ' 'repeat from last week', 2, @@ -301,78 +300,77 @@ MathJax.Hub.Config({ @@ -384,36 +382,53 @@ MathJax.Hub.Config({

       

       

       

      -

      Optimizing our parameters, more details

      +

      Interpretations and optimizing our parameters

      -

      With the above we use the design matrix to define the approximation \( \boldsymbol{\tilde{y}} \) via the unknown quantity \( \boldsymbol{\beta} \) as

      + +

      The function

      $$ -\boldsymbol{\tilde{y}}= \boldsymbol{X}\boldsymbol{\beta}, +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\}, $$ -

      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

      +

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

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

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

      -$$ -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\}. -$$ - -

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

      - -

      It is also common to define -the function \( C \) 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

      $$ -C(\boldsymbol{\beta})=\frac{1}{2n}\sum_{i=0}^{n-1}\left(y_i-\tilde{y}_i\right)^2, +{\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\}. $$ -

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

      +

      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). +$$
      @@ -443,7 +458,7 @@ $$
    101. 23
    102. 24
    103. ...
    104. -
    105. 69
    106. +
    107. 68
    108. »
    109. diff --git a/doc/pub/week35/html/._week35-bs015.html b/doc/pub/week35/html/._week35-bs015.html index abc16f46d..52adfb9b5 100644 --- a/doc/pub/week35/html/._week35-bs015.html +++ b/doc/pub/week35/html/._week35-bs015.html @@ -38,7 +38,6 @@ doconce format html week35.do.txt --html_style=bootstrap --pygments_html_style=d {'highest level': 2, 'sections': [('Plans for week 35', 2, None, 'plans-for-week-35'), ('Reading recommendations:', 3, None, 'reading-recommendations'), - ('Topics of week 35', 2, None, 'topics-of-week-35'), ('Why Linear Regression (aka Ordinary Least Squares and family), ' 'repeat from last week', 2, @@ -301,78 +300,77 @@ MathJax.Hub.Config({ @@ -388,49 +386,40 @@ MathJax.Hub.Config({
      - -

      The function

      +

      We can rewrite

      $$ -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\}, +\frac{\partial C(\boldsymbol{\beta})}{\partial \boldsymbol{\beta}} = 0 = \boldsymbol{X}^T\left( \boldsymbol{y}-\boldsymbol{X}\boldsymbol{\beta}\right), $$ -

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

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

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

      -$$ -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 \( C(\boldsymbol{\beta}) \), that is we are going to solve the problem

      -$$ -{\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 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). -$$ +
      +
      + +

      Small question: Do you think the example we have at hand here (the nuclear binding energies) can lead to problems in inverting the matrix \( \boldsymbol{X}^T\boldsymbol{X} \)? What kind of problems can we expect?

      @@ -460,7 +449,7 @@ $$
    110. 24
    111. 25
    112. ...
    113. -
    114. 69
    115. +
    116. 68
    117. »
    118. diff --git a/doc/pub/week35/html/._week35-bs016.html b/doc/pub/week35/html/._week35-bs016.html index 5e0e10cb7..0808e325d 100644 --- a/doc/pub/week35/html/._week35-bs016.html +++ b/doc/pub/week35/html/._week35-bs016.html @@ -38,7 +38,6 @@ doconce format html week35.do.txt --html_style=bootstrap --pygments_html_style=d {'highest level': 2, 'sections': [('Plans for week 35', 2, None, 'plans-for-week-35'), ('Reading recommendations:', 3, None, 'reading-recommendations'), - ('Topics of week 35', 2, None, 'topics-of-week-35'), ('Why Linear Regression (aka Ordinary Least Squares and family), ' 'repeat from last week', 2, @@ -301,78 +300,77 @@ MathJax.Hub.Config({ @@ -384,47 +382,29 @@ MathJax.Hub.Config({

       

       

       

      -

      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), -$$ +

      Some useful matrix and vector expressions

      -

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

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

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

      -
      -
      +$$ +\frac{\partial (\boldsymbol{b}^T\boldsymbol{a})}{\partial \boldsymbol{a}} = \boldsymbol{b}, +$$ -
      -
      - -

      Small question: Do you think the example we have at hand here (the nuclear binding energies) can lead to problems in inverting the matrix \( \boldsymbol{X}^T\boldsymbol{X} \)? What kind of problems can we expect?

      -
      -
      +$$ +\frac{\partial (\boldsymbol{a}^T\boldsymbol{A}\boldsymbol{a})}{\partial \boldsymbol{a}} = (\boldsymbol{A}+\boldsymbol{A}^T)\boldsymbol{a}, +$$ +$$ +\frac{\partial tr(\boldsymbol{B}\boldsymbol{A})}{\partial \boldsymbol{A}} = \boldsymbol{B}^T, +$$ + +$$ +\frac{\partial \log{\vert\boldsymbol{A}\vert}}{\partial \boldsymbol{A}} = (\boldsymbol{A}^{-1})^T. +$$ + +

      See the jupyter-book (complete lecture notes) for the derivations of these relations.

      @@ -451,7 +431,7 @@ allow for the usage of direct linear algebra methods such as LU decomposi

    119. 25
    120. 26
    121. ...
    122. -
    123. 69
    124. +
    125. 68
    126. »
    127. diff --git a/doc/pub/week35/html/._week35-bs017.html b/doc/pub/week35/html/._week35-bs017.html index 54923b104..48d1bf6a7 100644 --- a/doc/pub/week35/html/._week35-bs017.html +++ b/doc/pub/week35/html/._week35-bs017.html @@ -38,7 +38,6 @@ doconce format html week35.do.txt --html_style=bootstrap --pygments_html_style=d {'highest level': 2, 'sections': [('Plans for week 35', 2, None, 'plans-for-week-35'), ('Reading recommendations:', 3, None, 'reading-recommendations'), - ('Topics of week 35', 2, None, 'topics-of-week-35'), ('Why Linear Regression (aka Ordinary Least Squares and family), ' 'repeat from last week', 2, @@ -301,78 +300,77 @@ MathJax.Hub.Config({ @@ -384,29 +382,35 @@ MathJax.Hub.Config({

       

       

       

      -

      Some useful matrix and vector expressions

      +

      Meet the Hessian Matrix

      -

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

      A very important matrix we will meet again and again in Machine +Learning is the Hessian. It is given by the second derivative of the +cost function with respect to the parameter \( \beta \). Using the above +expression for derivatives of vectors and matrices, we find that the +second derivative of the cost function is,

      $$ -\frac{\partial (\boldsymbol{b}^T\boldsymbol{a})}{\partial \boldsymbol{a}} = \boldsymbol{b}, +\frac{\partial}{\partial \boldsymbol{\beta}^T}\frac{\partial C(\boldsymbol{\beta})}{\partial \boldsymbol{\beta}} =\frac{\partial}{\partial \boldsymbol{\beta}}\left[-\frac{2}{n}\boldsymbol{X}^T\left( \boldsymbol{y}-\boldsymbol{X}\boldsymbol{\beta}\right)\right]=\frac{2}{n}\boldsymbol{X}^T\boldsymbol{X}. $$ -$$ -\frac{\partial (\boldsymbol{a}^T\boldsymbol{A}\boldsymbol{a})}{\partial \boldsymbol{a}} = (\boldsymbol{A}+\boldsymbol{A}^T)\boldsymbol{a}, -$$ +

      The Hessian matrix plays an important role and is defined here as

      $$ -\frac{\partial tr(\boldsymbol{B}\boldsymbol{A})}{\partial \boldsymbol{A}} = \boldsymbol{B}^T, +\boldsymbol{H}=\boldsymbol{X}^T\boldsymbol{X}. $$ -$$ -\frac{\partial \log{\vert\boldsymbol{A}\vert}}{\partial \boldsymbol{A}} = (\boldsymbol{A}^{-1})^T. -$$ +

      For ordinary least squares, it is inversely proportional (derivation +next week) with the variance of the optimal parameters +\( \hat{\boldsymbol{\beta}} \). Furthermore, we will see later this week that is +(beside \( 1/n \)) equal to the covariance matrix. It plays also a very +important role in optmization algorithms and Principal Component +Analysis as a way to reduce the dimensionality of a machine learning +problem. +

      -

      See the jupyter-book (complete lecture notes) for the derivations of these relations.

      +

      Linear algebra question: Can we use the Hessian matrix to say something about properties of the cost function (our optmization problem)? (hint: think about convex or concave problems and how to relate these to a matrix!).

      @@ -433,7 +437,7 @@ $$

    128. 26
    129. 27
    130. ...
    131. -
    132. 69
    133. +
    134. 68
    135. »
    136. diff --git a/doc/pub/week35/html/._week35-bs018.html b/doc/pub/week35/html/._week35-bs018.html index 11df12099..cfdd469d6 100644 --- a/doc/pub/week35/html/._week35-bs018.html +++ b/doc/pub/week35/html/._week35-bs018.html @@ -38,7 +38,6 @@ doconce format html week35.do.txt --html_style=bootstrap --pygments_html_style=d {'highest level': 2, 'sections': [('Plans for week 35', 2, None, 'plans-for-week-35'), ('Reading recommendations:', 3, None, 'reading-recommendations'), - ('Topics of week 35', 2, None, 'topics-of-week-35'), ('Why Linear Regression (aka Ordinary Least Squares and family), ' 'repeat from last week', 2, @@ -301,78 +300,77 @@ MathJax.Hub.Config({ @@ -384,35 +382,29 @@ MathJax.Hub.Config({

       

       

       

      -

      Meet the Hessian Matrix

      - -

      A very important matrix we will meet again and again in Machine -Learning is the Hessian. It is given by the second derivative of the -cost function with respect to the parameter \( \beta \). Using the above -expression for derivatives of vectors and matrices, we find that the -second derivative of the cost function is, -

      - +

      Interpretations and optimizing our parameters

      +
      +
      + +

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

      $$ -\frac{\partial}{\partial \boldsymbol{\beta}^T}\frac{\partial C(\boldsymbol{\beta})}{\partial \boldsymbol{\beta}} =\frac{\partial}{\partial \boldsymbol{\beta}}\left[-\frac{2}{n}\boldsymbol{X}^T\left( \boldsymbol{y}-\boldsymbol{X}\boldsymbol{\beta}\right)\right]=\frac{2}{n}\boldsymbol{X}^T\boldsymbol{X}. +\boldsymbol{\epsilon} = \boldsymbol{y}-\boldsymbol{\tilde{y}} = \boldsymbol{y}-\boldsymbol{X}\boldsymbol{\beta}, $$ -

      The Hessian matrix plays an important role and is defined here as

      - +

      and with

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

      For ordinary least squares, it is inversely proportional (derivation -next week) with the variance of the optimal parameters -\( \hat{\boldsymbol{\beta}} \). Furthermore, we will see later this week that is -(beside \( 1/n \)) equal to the covariance matrix. It plays also a very -important role in optmization algorithms and Principal Component -Analysis as a way to reduce the dimensionality of a machine learning -problem. -

      +

      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.

      +
      +
      -

      Linear algebra question: Can we use the Hessian matrix to say something about properties of the cost function (our optmization problem)? (hint: think about convex or concave problems and how to relate these to a matrix!).

      @@ -439,7 +431,7 @@ problem.

    137. 27
    138. 28
    139. ...
    140. -
    141. 69
    142. +
    143. 68
    144. »
    145. diff --git a/doc/pub/week35/html/._week35-bs019.html b/doc/pub/week35/html/._week35-bs019.html index 26c6889eb..ce304ac04 100644 --- a/doc/pub/week35/html/._week35-bs019.html +++ b/doc/pub/week35/html/._week35-bs019.html @@ -38,7 +38,6 @@ doconce format html week35.do.txt --html_style=bootstrap --pygments_html_style=d {'highest level': 2, 'sections': [('Plans for week 35', 2, None, 'plans-for-week-35'), ('Reading recommendations:', 3, None, 'reading-recommendations'), - ('Topics of week 35', 2, None, 'topics-of-week-35'), ('Why Linear Regression (aka Ordinary Least Squares and family), ' 'repeat from last week', 2, @@ -301,78 +300,77 @@ MathJax.Hub.Config({ @@ -384,27 +382,95 @@ MathJax.Hub.Config({

       

       

       

      -

      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}, -$$ +

      Own code for Ordinary Least Squares

      -

      and with

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

      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

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

      + +
      +
      +
      +
      +
      +
      # 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()
      +
      +
      +
      +
      +
      +
      +
      +
      +
      +
      +
      +
      +
      @@ -433,7 +499,7 @@ $$
    146. 28
    147. 29
    148. ...
    149. -
    150. 69
    151. +
    152. 68
    153. »
    154. diff --git a/doc/pub/week35/html/._week35-bs020.html b/doc/pub/week35/html/._week35-bs020.html index b8b7ca4cd..6e183d78d 100644 --- a/doc/pub/week35/html/._week35-bs020.html +++ b/doc/pub/week35/html/._week35-bs020.html @@ -38,7 +38,6 @@ doconce format html week35.do.txt --html_style=bootstrap --pygments_html_style=d {'highest level': 2, 'sections': [('Plans for week 35', 2, None, 'plans-for-week-35'), ('Reading recommendations:', 3, None, 'reading-recommendations'), - ('Topics of week 35', 2, None, 'topics-of-week-35'), ('Why Linear Regression (aka Ordinary Least Squares and family), ' 'repeat from last week', 2, @@ -301,78 +300,77 @@ MathJax.Hub.Config({ @@ -384,10 +382,10 @@ MathJax.Hub.Config({

       

       

       

      -

      Own code for Ordinary Least Squares

      +

      Adding error analysis and training set up

      -

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

      @@ -396,10 +394,8 @@ 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
      +  
      def R2(y_data, y_model):
      +    return 1 - np.sum((y_data - y_model) ** 2) / np.sum((y_data - np.mean(y_data)) ** 2)
       
      @@ -415,7 +411,7 @@ ytilde = X @
      -

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

      +

      and we would be using it as

      @@ -423,8 +419,7 @@ ytilde = X @
      -
      fit = np.linalg.lstsq(X, Energies, rcond =None)[0]
      -ytildenp = np.dot(fit,X.T)
      +  
      print(R2(Energies,ytilde))
       
      @@ -440,7 +435,7 @@ ytildenp = np.<
      -

      And finally we plot our fit with and compare with data

      +

      We can easily add our MSE score as

      @@ -448,18 +443,37 @@ ytildenp = np.<
      -
      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()
      +  
      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))
       
      @@ -501,7 +515,7 @@ plt.show()
    155. 29
    156. 30
    157. ...
    158. -
    159. 69
    160. +
    161. 68
    162. »
    163. diff --git a/doc/pub/week35/html/._week35-bs021.html b/doc/pub/week35/html/._week35-bs021.html index 6e1fde160..e709e75c2 100644 --- a/doc/pub/week35/html/._week35-bs021.html +++ b/doc/pub/week35/html/._week35-bs021.html @@ -38,7 +38,6 @@ doconce format html week35.do.txt --html_style=bootstrap --pygments_html_style=d {'highest level': 2, 'sections': [('Plans for week 35', 2, None, 'plans-for-week-35'), ('Reading recommendations:', 3, None, 'reading-recommendations'), - ('Topics of week 35', 2, None, 'topics-of-week-35'), ('Why Linear Regression (aka Ordinary Least Squares and family), ' 'repeat from last week', 2, @@ -301,78 +300,77 @@ MathJax.Hub.Config({ @@ -384,111 +382,24 @@ MathJax.Hub.Config({

       

       

       

      -

      Adding error analysis and training set up

      +

      Splitting our Data in Training and Test data

      -

      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 +

      +
      + + +

      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.

      - - -
      -
      -
      -
      -
      -
      def R2(y_data, y_model):
      -    return 1 - np.sum((y_data - y_model) ** 2) / np.sum((y_data - np.mean(y_data)) ** 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))
      -
      -
      -
      -
      -
      -
      -
      -
      -
      -
      -
      -
      -
      @@ -517,7 +428,7 @@ Since we are not using Scikit-Learn here we can define our own \( R2 \) f
    164. 30
    165. 31
    166. ...
    167. -
    168. 69
    169. +
    170. 68
    171. »
    172. diff --git a/doc/pub/week35/html/._week35-bs022.html b/doc/pub/week35/html/._week35-bs022.html index b8ba72e6a..0d21f1237 100644 --- a/doc/pub/week35/html/._week35-bs022.html +++ b/doc/pub/week35/html/._week35-bs022.html @@ -38,7 +38,6 @@ doconce format html week35.do.txt --html_style=bootstrap --pygments_html_style=d {'highest level': 2, 'sections': [('Plans for week 35', 2, None, 'plans-for-week-35'), ('Reading recommendations:', 3, None, 'reading-recommendations'), - ('Topics of week 35', 2, None, 'topics-of-week-35'), ('Why Linear Regression (aka Ordinary Least Squares and family), ' 'repeat from last week', 2, @@ -301,78 +300,77 @@ MathJax.Hub.Config({ @@ -384,24 +382,66 @@ MathJax.Hub.Config({

       

       

       

      -

      Splitting our Data in Training and Test data

      +

      Examples

      -
      -
      - -

      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 os
      +import numpy as np
      +import pandas as pd
      +import matplotlib.pyplot as plt
      +from sklearn.model_selection import train_test_split
      +
      +
      +def R2(y_data, y_model):
      +    return 1 - np.sum((y_data - y_model) ** 2) / np.sum((y_data - np.mean(y_data)) ** 2)
      +def MSE(y_data,y_model):
      +    n = np.size(y_model)
      +    return np.sum((y_data-y_model)**2)/n
      +
      +x = np.random.rand(100)
      +y = 2.0+5*x*x+0.1*np.random.randn(100)
      +
      +
      +#  The design matrix now as function of a given polynomial
      +X = np.zeros((len(x),3))
      +X[:,0] = 1.0
      +X[:,1] = x
      +X[:,2] = x**2
      +# We split the data in test and training data
      +X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2)
      +# matrix inversion to find beta
      +beta = np.linalg.inv(X_train.T @ X_train) @ X_train.T @ y_train
      +print(beta)
      +# and then make the prediction
      +ytilde = X_train @ beta
      +print("Training R2")
      +print(R2(y_train,ytilde))
      +print("Training MSE")
      +print(MSE(y_train,ytilde))
      +ypredict = X_test @ beta
      +print("Test R2")
      +print(R2(y_test,ypredict))
      +print("Test MSE")
      +print(MSE(y_test,ypredict))
      +
      +
      +
      +
      +
      +
      +
      +
      +
      +
      +
      +
      @@ -430,7 +470,7 @@ but now splitting the data into a training set and a test set.
    173. 31
    174. 32
    175. ...
    176. -
    177. 69
    178. +
    179. 68
    180. »
    181. diff --git a/doc/pub/week35/html/._week35-bs023.html b/doc/pub/week35/html/._week35-bs023.html index ae375502a..52ec3b025 100644 --- a/doc/pub/week35/html/._week35-bs023.html +++ b/doc/pub/week35/html/._week35-bs023.html @@ -38,7 +38,6 @@ doconce format html week35.do.txt --html_style=bootstrap --pygments_html_style=d {'highest level': 2, 'sections': [('Plans for week 35', 2, None, 'plans-for-week-35'), ('Reading recommendations:', 3, None, 'reading-recommendations'), - ('Topics of week 35', 2, None, 'topics-of-week-35'), ('Why Linear Regression (aka Ordinary Least Squares and family), ' 'repeat from last week', 2, @@ -301,78 +300,77 @@ MathJax.Hub.Config({ @@ -384,7 +382,7 @@ MathJax.Hub.Config({

       

       

       

      -

      Examples

      +

      Making your own test-train splitting

      @@ -393,44 +391,20 @@ MathJax.Hub.Config({
      -
      import os
      -import numpy as np
      -import pandas as pd
      -import matplotlib.pyplot as plt
      -from sklearn.model_selection import train_test_split
      +  
      # equivalently in numpy
      +def train_test_split_numpy(inputs, labels, train_size, test_size):
      +    n_inputs = len(inputs)
      +    inputs_shuffled = inputs.copy()
      +    labels_shuffled = labels.copy()
       
      +    np.random.shuffle(inputs_shuffled)
      +    np.random.shuffle(labels_shuffled)
       
      -def R2(y_data, y_model):
      -    return 1 - np.sum((y_data - y_model) ** 2) / np.sum((y_data - np.mean(y_data)) ** 2)
      -def MSE(y_data,y_model):
      -    n = np.size(y_model)
      -    return np.sum((y_data-y_model)**2)/n
      +    train_end = int(n_inputs*train_size)
      +    X_train, X_test = inputs_shuffled[:train_end], inputs_shuffled[train_end:]
      +    Y_train, Y_test = labels_shuffled[:train_end], labels_shuffled[train_end:]
       
      -x = np.random.rand(100)
      -y = 2.0+5*x*x+0.1*np.random.randn(100)
      -
      -
      -#  The design matrix now as function of a given polynomial
      -X = np.zeros((len(x),3))
      -X[:,0] = 1.0
      -X[:,1] = x
      -X[:,2] = x**2
      -# We split the data in test and training data
      -X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2)
      -# matrix inversion to find beta
      -beta = np.linalg.inv(X_train.T @ X_train) @ X_train.T @ y_train
      -print(beta)
      -# and then make the prediction
      -ytilde = X_train @ beta
      -print("Training R2")
      -print(R2(y_train,ytilde))
      -print("Training MSE")
      -print(MSE(y_train,ytilde))
      -ypredict = X_test @ beta
      -print("Test R2")
      -print(R2(y_test,ypredict))
      -print("Test MSE")
      -print(MSE(y_test,ypredict))
      +    return X_train, X_test, Y_train, Y_test
       
      @@ -446,6 +420,10 @@ ypredict = X_test = X_test 32
    182. 33
    183. ...
    184. -
    185. 69
    186. +
    187. 68
    188. »
    189. diff --git a/doc/pub/week35/html/._week35-bs024.html b/doc/pub/week35/html/._week35-bs024.html index d16c5842b..f9fc90548 100644 --- a/doc/pub/week35/html/._week35-bs024.html +++ b/doc/pub/week35/html/._week35-bs024.html @@ -38,7 +38,6 @@ doconce format html week35.do.txt --html_style=bootstrap --pygments_html_style=d {'highest level': 2, 'sections': [('Plans for week 35', 2, None, 'plans-for-week-35'), ('Reading recommendations:', 3, None, 'reading-recommendations'), - ('Topics of week 35', 2, None, 'topics-of-week-35'), ('Why Linear Regression (aka Ordinary Least Squares and family), ' 'repeat from last week', 2, @@ -301,78 +300,77 @@ MathJax.Hub.Config({ @@ -383,50 +381,33 @@ MathJax.Hub.Config({

       

       

       

      - -

      Making your own test-train splitting

      + +

      The Boston housing data example

      - - -
      -
      -
      -
      -
      -
      # equivalently in numpy
      -def train_test_split_numpy(inputs, labels, train_size, test_size):
      -    n_inputs = len(inputs)
      -    inputs_shuffled = inputs.copy()
      -    labels_shuffled = labels.copy()
      -
      -    np.random.shuffle(inputs_shuffled)
      -    np.random.shuffle(labels_shuffled)
      -
      -    train_end = int(n_inputs*train_size)
      -    X_train, X_test = inputs_shuffled[:train_end], inputs_shuffled[train_end:]
      -    Y_train, Y_test = labels_shuffled[:train_end], labels_shuffled[train_end:]
      -
      -    return X_train, X_test, Y_train, Y_test
      -
      -
      -
      -
      -
      -
      -
      -
      -
      -
      -
      -
      -
      -
      - -

      But since scikit-learn has its own function for doing this and since -it interfaces easily with tensorflow and other libraries, we -normally recommend using the latter functionality. +

      The Boston housing +data set was originally a part of UCI Machine Learning Repository +and has been removed now. The data set is now included in Scikit-Learn's +library. There are 506 samples and 13 feature (predictor) variables +in this data set. The objective is to predict the value of prices of +the house using the features (predictors) listed here.

      +

      The features/predictors are

      +
        +
      1. CRIM: Per capita crime rate by town
      2. +
      3. ZN: Proportion of residential land zoned for lots over 25000 square feet
      4. +
      5. INDUS: Proportion of non-retail business acres per town
      6. +
      7. CHAS: Charles River dummy variable (= 1 if tract bounds river; 0 otherwise)
      8. +
      9. NOX: Nitric oxide concentration (parts per 10 million)
      10. +
      11. RM: Average number of rooms per dwelling
      12. +
      13. AGE: Proportion of owner-occupied units built prior to 1940
      14. +
      15. DIS: Weighted distances to five Boston employment centers
      16. +
      17. RAD: Index of accessibility to radial highways
      18. +
      19. TAX: Full-value property tax rate per USD10000
      20. +
      21. B: \( 1000(Bk - 0.63)^2 \), where \( Bk \) is the proportion of [people of African American descent] by town
      22. +
      23. LSTAT: Percentage of lower status of the population
      24. +
      25. MEDV: Median value of owner-occupied homes in USD 1000s
      26. +

        @@ -452,7 +433,7 @@ normally recommend using the latter functionality.
      • 33
      • 34
      • ...
      • -
      • 69
      • +
      • 68
      • »
      diff --git a/doc/pub/week35/html/._week35-bs025.html b/doc/pub/week35/html/._week35-bs025.html index 11cac818b..2f1ea72c1 100644 --- a/doc/pub/week35/html/._week35-bs025.html +++ b/doc/pub/week35/html/._week35-bs025.html @@ -38,7 +38,6 @@ doconce format html week35.do.txt --html_style=bootstrap --pygments_html_style=d {'highest level': 2, 'sections': [('Plans for week 35', 2, None, 'plans-for-week-35'), ('Reading recommendations:', 3, None, 'reading-recommendations'), - ('Topics of week 35', 2, None, 'topics-of-week-35'), ('Why Linear Regression (aka Ordinary Least Squares and family), ' 'repeat from last week', 2, @@ -301,78 +300,77 @@ MathJax.Hub.Config({ @@ -383,33 +381,348 @@ MathJax.Hub.Config({

       

       

       

      - -

      The Boston housing data example

      + +

      Housing data, the code

      +

      We start by importing the libraries

      + + +
      +
      +
      +
      +
      +
      import numpy as np
      +import matplotlib.pyplot as plt 
      +
      +import pandas as pd  
      +import seaborn as sns 
      +
      +
      +
      +
      +
      +
      +
      +
      +
      +
      +
      +
      +
      +
      + +

      and load the Boston Housing DataSet from Scikit-Learn

      + + + +
      +
      +
      +
      +
      +
      from sklearn.datasets import load_boston
      +
      +boston_dataset = load_boston()
      +
      +# boston_dataset is a dictionary
      +# let's check what it contains
      +boston_dataset.keys()
      +
      +
      +
      +
      +
      +
      +
      +
      +
      +
      +
      +
      +
      +
      + +

      Then we invoke Pandas

      + + +
      +
      +
      +
      +
      +
      boston = pd.DataFrame(boston_dataset.data, columns=boston_dataset.feature_names)
      +boston.head()
      +boston['MEDV'] = boston_dataset.target
      +
      +
      +
      +
      +
      +
      +
      +
      +
      +
      +
      +
      +
      +
      + +

      and preprocess the data

      + + +
      +
      +
      +
      +
      +
      # check for missing values in all the columns
      +boston.isnull().sum()
      +
      +
      +
      +
      +
      +
      +
      +
      +
      +
      +
      +
      +
      +
      + +

      We can then visualize the data

      + + +
      +
      +
      +
      +
      +
      # set the size of the figure
      +sns.set(rc={'figure.figsize':(11.7,8.27)})
      +
      +# plot a histogram showing the distribution of the target values
      +sns.distplot(boston['MEDV'], bins=30)
      +plt.show()
      +
      +
      +
      +
      +
      +
      +
      +
      +
      +
      +
      +
      +
      +
      + +

      It is now useful to look at the correlation matrix

      + + +
      +
      +
      +
      +
      +
      # compute the pair wise correlation for all columns  
      +correlation_matrix = boston.corr().round(2)
      +# use the heatmap function from seaborn to plot the correlation matrix
      +# annot = True to print the values inside the square
      +sns.heatmap(data=correlation_matrix, annot=True)
      +
      +
      +
      +
      +
      +
      +
      +
      +
      +
      +
      +
      +
      +
      + +

      From the above coorelation plot we can see that MEDV is strongly correlated to LSTAT and RM. We see also that RAD and TAX are stronly correlated, but we don't include this in our features together to avoid multi-colinearity

      + + + +
      +
      +
      +
      +
      +
      plt.figure(figsize=(20, 5))
      +
      +features = ['LSTAT', 'RM']
      +target = boston['MEDV']
      +
      +for i, col in enumerate(features):
      +    plt.subplot(1, len(features) , i+1)
      +    x = boston[col]
      +    y = target
      +    plt.scatter(x, y, marker='o')
      +    plt.title(col)
      +    plt.xlabel(col)
      +    plt.ylabel('MEDV')
      +
      +
      +
      +
      +
      +
      +
      +
      +
      +
      +
      +
      +
      +
      + +

      Now we start training our model

      + + +
      +
      +
      +
      +
      +
      X = pd.DataFrame(np.c_[boston['LSTAT'], boston['RM']], columns = ['LSTAT','RM'])
      +Y = boston['MEDV']
      +
      +
      +
      +
      +
      +
      +
      +
      +
      +
      +
      +
      +
      +
      + +

      We split the data into training and test sets

      + + + +
      +
      +
      +
      +
      +
      from sklearn.model_selection import train_test_split
      +
      +# splits the training and test data set in 80% : 20%
      +# assign random_state to any value.This ensures consistency.
      +X_train, X_test, Y_train, Y_test = train_test_split(X, Y, test_size = 0.2, random_state=5)
      +print(X_train.shape)
      +print(X_test.shape)
      +print(Y_train.shape)
      +print(Y_test.shape)
      +
      +
      +
      +
      +
      +
      +
      +
      +
      +
      +
      +
      +
      +
      + +

      Then we use the linear regression functionality from Scikit-Learn

      + + +
      +
      +
      +
      +
      +
      from sklearn.linear_model import LinearRegression
      +from sklearn.metrics import mean_squared_error, r2_score
      +
      +lin_model = LinearRegression()
      +lin_model.fit(X_train, Y_train)
      +
      +# model evaluation for training set
      +
      +y_train_predict = lin_model.predict(X_train)
      +rmse = (np.sqrt(mean_squared_error(Y_train, y_train_predict)))
      +r2 = r2_score(Y_train, y_train_predict)
      +
      +print("The model performance for training set")
      +print("--------------------------------------")
      +print('RMSE is {}'.format(rmse))
      +print('R2 score is {}'.format(r2))
      +print("\n")
      +
      +# model evaluation for testing set
      +
      +y_test_predict = lin_model.predict(X_test)
      +# root mean square error of the model
      +rmse = (np.sqrt(mean_squared_error(Y_test, y_test_predict)))
      +
      +# r-squared score of the model
      +r2 = r2_score(Y_test, y_test_predict)
      +
      +print("The model performance for testing set")
      +print("--------------------------------------")
      +print('RMSE is {}'.format(rmse))
      +print('R2 score is {}'.format(r2))
      +
      +
      +
      +
      +
      +
      +
      +
      +
      +
      +
      +
      +
      + +
      +
      +
      +
      +
      +
      # plotting the y_test vs y_pred
      +# ideally should have been a straight line
      +plt.scatter(Y_test, y_test_predict)
      +plt.show()
      +
      +
      +
      +
      +
      +
      +
      +
      +
      +
      +
      +
      +
      +
      -

      The Boston housing -data set was originally a part of UCI Machine Learning Repository -and has been removed now. The data set is now included in Scikit-Learn's -library. There are 506 samples and 13 feature (predictor) variables -in this data set. The objective is to predict the value of prices of -the house using the features (predictors) listed here. -

      -

      The features/predictors are

      -
        -
      1. CRIM: Per capita crime rate by town
      2. -
      3. ZN: Proportion of residential land zoned for lots over 25000 square feet
      4. -
      5. INDUS: Proportion of non-retail business acres per town
      6. -
      7. CHAS: Charles River dummy variable (= 1 if tract bounds river; 0 otherwise)
      8. -
      9. NOX: Nitric oxide concentration (parts per 10 million)
      10. -
      11. RM: Average number of rooms per dwelling
      12. -
      13. AGE: Proportion of owner-occupied units built prior to 1940
      14. -
      15. DIS: Weighted distances to five Boston employment centers
      16. -
      17. RAD: Index of accessibility to radial highways
      18. -
      19. TAX: Full-value property tax rate per USD10000
      20. -
      21. B: \( 1000(Bk - 0.63)^2 \), where \( Bk \) is the proportion of [people of African American descent] by town
      22. -
      23. LSTAT: Percentage of lower status of the population
      24. -
      25. MEDV: Median value of owner-occupied homes in USD 1000s
      26. -

        @@ -435,7 +748,7 @@ the house using the features (predictors) listed here.
      • 34
      • 35
      • ...
      • -
      • 69
      • +
      • 68
      • »
      diff --git a/doc/pub/week35/html/._week35-bs026.html b/doc/pub/week35/html/._week35-bs026.html index f1fd59b6c..656571691 100644 --- a/doc/pub/week35/html/._week35-bs026.html +++ b/doc/pub/week35/html/._week35-bs026.html @@ -38,7 +38,6 @@ doconce format html week35.do.txt --html_style=bootstrap --pygments_html_style=d {'highest level': 2, 'sections': [('Plans for week 35', 2, None, 'plans-for-week-35'), ('Reading recommendations:', 3, None, 'reading-recommendations'), - ('Topics of week 35', 2, None, 'topics-of-week-35'), ('Why Linear Regression (aka Ordinary Least Squares and family), ' 'repeat from last week', 2, @@ -301,78 +300,77 @@ MathJax.Hub.Config({ @@ -384,344 +382,33 @@ MathJax.Hub.Config({

       

       

       

      -

      Housing data, the code

      -

      We start by importing the libraries

      +

      Reducing the number of degrees of freedom, overarching view

      +
      +
      + - -
      -
      -
      -
      -
      -
      import numpy as np
      -import matplotlib.pyplot as plt 
      +

      Many Machine Learning problems involve thousands or even millions of +features for each training instance. Not only does this make training +extremely slow, it can also make it much harder to find a good +solution, as we will see. This problem is often referred to as the +curse of dimensionality. Fortunately, in real-world problems, it is +often possible to reduce the number of features considerably, turning +an intractable problem into a tractable one. +

      -import pandas as pd -import seaborn as sns -
      +

      Later we will discuss some of the most popular dimensionality reduction +techniques: the principal component analysis (PCA), Kernel PCA, and +Locally Linear Embedding (LLE). +

      + +

      Principal component analysis and its various variants deal with the +problem of fitting a low-dimensional affine +subspace to a set of of +data points in a high-dimensional space. With its family of methods it +is one of the most used tools in data modeling, compression and +visualization. +

      -
      -
      -
      -
      -
      -
      -
      -
      -
      -
      -
      -
      - -

      and load the Boston Housing DataSet from Scikit-Learn

      - - - -
      -
      -
      -
      -
      -
      from sklearn.datasets import load_boston
      -
      -boston_dataset = load_boston()
      -
      -# boston_dataset is a dictionary
      -# let's check what it contains
      -boston_dataset.keys()
      -
      -
      -
      -
      -
      -
      -
      -
      -
      -
      -
      -
      -
      -
      - -

      Then we invoke Pandas

      - - -
      -
      -
      -
      -
      -
      boston = pd.DataFrame(boston_dataset.data, columns=boston_dataset.feature_names)
      -boston.head()
      -boston['MEDV'] = boston_dataset.target
      -
      -
      -
      -
      -
      -
      -
      -
      -
      -
      -
      -
      -
      -
      - -

      and preprocess the data

      - - -
      -
      -
      -
      -
      -
      # check for missing values in all the columns
      -boston.isnull().sum()
      -
      -
      -
      -
      -
      -
      -
      -
      -
      -
      -
      -
      -
      -
      - -

      We can then visualize the data

      - - -
      -
      -
      -
      -
      -
      # set the size of the figure
      -sns.set(rc={'figure.figsize':(11.7,8.27)})
      -
      -# plot a histogram showing the distribution of the target values
      -sns.distplot(boston['MEDV'], bins=30)
      -plt.show()
      -
      -
      -
      -
      -
      -
      -
      -
      -
      -
      -
      -
      -
      -
      - -

      It is now useful to look at the correlation matrix

      - - -
      -
      -
      -
      -
      -
      # compute the pair wise correlation for all columns  
      -correlation_matrix = boston.corr().round(2)
      -# use the heatmap function from seaborn to plot the correlation matrix
      -# annot = True to print the values inside the square
      -sns.heatmap(data=correlation_matrix, annot=True)
      -
      -
      -
      -
      -
      -
      -
      -
      -
      -
      -
      -
      -
      -
      - -

      From the above coorelation plot we can see that MEDV is strongly correlated to LSTAT and RM. We see also that RAD and TAX are stronly correlated, but we don't include this in our features together to avoid multi-colinearity

      - - - -
      -
      -
      -
      -
      -
      plt.figure(figsize=(20, 5))
      -
      -features = ['LSTAT', 'RM']
      -target = boston['MEDV']
      -
      -for i, col in enumerate(features):
      -    plt.subplot(1, len(features) , i+1)
      -    x = boston[col]
      -    y = target
      -    plt.scatter(x, y, marker='o')
      -    plt.title(col)
      -    plt.xlabel(col)
      -    plt.ylabel('MEDV')
      -
      -
      -
      -
      -
      -
      -
      -
      -
      -
      -
      -
      -
      -
      - -

      Now we start training our model

      - - -
      -
      -
      -
      -
      -
      X = pd.DataFrame(np.c_[boston['LSTAT'], boston['RM']], columns = ['LSTAT','RM'])
      -Y = boston['MEDV']
      -
      -
      -
      -
      -
      -
      -
      -
      -
      -
      -
      -
      -
      -
      - -

      We split the data into training and test sets

      - - - -
      -
      -
      -
      -
      -
      from sklearn.model_selection import train_test_split
      -
      -# splits the training and test data set in 80% : 20%
      -# assign random_state to any value.This ensures consistency.
      -X_train, X_test, Y_train, Y_test = train_test_split(X, Y, test_size = 0.2, random_state=5)
      -print(X_train.shape)
      -print(X_test.shape)
      -print(Y_train.shape)
      -print(Y_test.shape)
      -
      -
      -
      -
      -
      -
      -
      -
      -
      -
      -
      -
      -
      -
      - -

      Then we use the linear regression functionality from Scikit-Learn

      - - -
      -
      -
      -
      -
      -
      from sklearn.linear_model import LinearRegression
      -from sklearn.metrics import mean_squared_error, r2_score
      -
      -lin_model = LinearRegression()
      -lin_model.fit(X_train, Y_train)
      -
      -# model evaluation for training set
      -
      -y_train_predict = lin_model.predict(X_train)
      -rmse = (np.sqrt(mean_squared_error(Y_train, y_train_predict)))
      -r2 = r2_score(Y_train, y_train_predict)
      -
      -print("The model performance for training set")
      -print("--------------------------------------")
      -print('RMSE is {}'.format(rmse))
      -print('R2 score is {}'.format(r2))
      -print("\n")
      -
      -# model evaluation for testing set
      -
      -y_test_predict = lin_model.predict(X_test)
      -# root mean square error of the model
      -rmse = (np.sqrt(mean_squared_error(Y_test, y_test_predict)))
      -
      -# r-squared score of the model
      -r2 = r2_score(Y_test, y_test_predict)
      -
      -print("The model performance for testing set")
      -print("--------------------------------------")
      -print('RMSE is {}'.format(rmse))
      -print('R2 score is {}'.format(r2))
      -
      -
      -
      -
      -
      -
      -
      -
      -
      -
      -
      -
      -
      - -
      -
      -
      -
      -
      -
      # plotting the y_test vs y_pred
      -# ideally should have been a straight line
      -plt.scatter(Y_test, y_test_predict)
      -plt.show()
      -
      -
      -
      -
      -
      -
      -
      -
      -
      -
      -
      -
      -
      @@ -750,7 +437,7 @@ plt.show()
    190. 35
    191. 36
    192. ...
    193. -
    194. 69
    195. +
    196. 68
    197. »
    198. diff --git a/doc/pub/week35/html/._week35-bs027.html b/doc/pub/week35/html/._week35-bs027.html index bb00cb200..5ff54e024 100644 --- a/doc/pub/week35/html/._week35-bs027.html +++ b/doc/pub/week35/html/._week35-bs027.html @@ -38,7 +38,6 @@ doconce format html week35.do.txt --html_style=bootstrap --pygments_html_style=d {'highest level': 2, 'sections': [('Plans for week 35', 2, None, 'plans-for-week-35'), ('Reading recommendations:', 3, None, 'reading-recommendations'), - ('Topics of week 35', 2, None, 'topics-of-week-35'), ('Why Linear Regression (aka Ordinary Least Squares and family), ' 'repeat from last week', 2, @@ -301,78 +300,77 @@ MathJax.Hub.Config({ @@ -384,31 +382,26 @@ MathJax.Hub.Config({

       

       

       

      -

      Reducing the number of degrees of freedom, overarching view

      +

      Preprocessing our data

      -

      Many Machine Learning problems involve thousands or even millions of -features for each training instance. Not only does this make training -extremely slow, it can also make it much harder to find a good -solution, as we will see. This problem is often referred to as the -curse of dimensionality. Fortunately, in real-world problems, it is -often possible to reduce the number of features considerably, turning -an intractable problem into a tractable one. +

      Before we proceed however, we will discuss how to preprocess our +data. Till now and in connection with our previous examples we have +not met so many cases where we are too sensitive to the scaling of our +data. Normally the data may need a rescaling and/or may be sensitive +to extreme values. Scaling the data renders our inputs much more +suitable for the algorithms we want to employ.

      -

      Later we will discuss some of the most popular dimensionality reduction -techniques: the principal component analysis (PCA), Kernel PCA, and -Locally Linear Embedding (LLE). -

      - -

      Principal component analysis and its various variants deal with the -problem of fitting a low-dimensional affine -subspace to a set of of -data points in a high-dimensional space. With its family of methods it -is one of the most used tools in data modeling, compression and -visualization. +

      For data sets gathered for real world applications, it is rather normal that +different features have very different units and +numerical scales. For example, a data set detailing health habits may include +features such as age in the range \( 0-80 \), and caloric intake of order \( 2000 \). +Many machine learning methods sensitive to the scales of the features and may perform poorly if they +are very different scales. Therefore, it is typical to scale +the features in a way to avoid such outlier values.

      @@ -439,7 +432,7 @@ visualization.
    199. 36
    200. 37
    201. ...
    202. -
    203. 69
    204. +
    205. 68
    206. »
    207. diff --git a/doc/pub/week35/html/._week35-bs028.html b/doc/pub/week35/html/._week35-bs028.html index 5c0afbcbe..5e344cbfe 100644 --- a/doc/pub/week35/html/._week35-bs028.html +++ b/doc/pub/week35/html/._week35-bs028.html @@ -38,7 +38,6 @@ doconce format html week35.do.txt --html_style=bootstrap --pygments_html_style=d {'highest level': 2, 'sections': [('Plans for week 35', 2, None, 'plans-for-week-35'), ('Reading recommendations:', 3, None, 'reading-recommendations'), - ('Topics of week 35', 2, None, 'topics-of-week-35'), ('Why Linear Regression (aka Ordinary Least Squares and family), ' 'repeat from last week', 2, @@ -301,78 +300,77 @@ MathJax.Hub.Config({ @@ -384,31 +382,19 @@ MathJax.Hub.Config({

       

       

       

      -

      Preprocessing our data

      -
      -
      - +

      Functionality in Scikit-Learn

      -

      Before we proceed however, we will discuss how to preprocess our -data. Till now and in connection with our previous examples we have -not met so many cases where we are too sensitive to the scaling of our -data. Normally the data may need a rescaling and/or may be sensitive -to extreme values. Scaling the data renders our inputs much more -suitable for the algorithms we want to employ. +

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

      -

      For data sets gathered for real world applications, it is rather normal that -different features have very different units and -numerical scales. For example, a data set detailing health habits may include -features such as age in the range \( 0-80 \), and caloric intake of order \( 2000 \). -Many machine learning methods sensitive to the scales of the features and may perform poorly if they -are very different scales. Therefore, it is typical to scale -the features in a way to avoid such outlier values. -

      -
      -
      - -

        @@ -434,7 +420,7 @@ the features in a way to avoid such outlier values.
      • 37
      • 38
      • ...
      • -
      • 69
      • +
      • 68
      • »
      diff --git a/doc/pub/week35/html/._week35-bs029.html b/doc/pub/week35/html/._week35-bs029.html index cd5ea9507..185a34d2e 100644 --- a/doc/pub/week35/html/._week35-bs029.html +++ b/doc/pub/week35/html/._week35-bs029.html @@ -38,7 +38,6 @@ doconce format html week35.do.txt --html_style=bootstrap --pygments_html_style=d {'highest level': 2, 'sections': [('Plans for week 35', 2, None, 'plans-for-week-35'), ('Reading recommendations:', 3, None, 'reading-recommendations'), - ('Topics of week 35', 2, None, 'topics-of-week-35'), ('Why Linear Regression (aka Ordinary Least Squares and family), ' 'repeat from last week', 2, @@ -301,78 +300,77 @@ MathJax.Hub.Config({ @@ -384,19 +382,33 @@ MathJax.Hub.Config({

       

       

       

      -

      Functionality in Scikit-Learn

      +

      More preprocessing

      -

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

      +
      + +

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

      +

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

      +
      +
      + +

        @@ -422,7 +434,7 @@ ensures that all features are exactly between \( 0 \) and \( 1 \). The
      • 38
      • 39
      • ...
      • -
      • 69
      • +
      • 68
      • »
      diff --git a/doc/pub/week35/html/._week35-bs030.html b/doc/pub/week35/html/._week35-bs030.html index 91533c617..d301bd2d8 100644 --- a/doc/pub/week35/html/._week35-bs030.html +++ b/doc/pub/week35/html/._week35-bs030.html @@ -38,7 +38,6 @@ doconce format html week35.do.txt --html_style=bootstrap --pygments_html_style=d {'highest level': 2, 'sections': [('Plans for week 35', 2, None, 'plans-for-week-35'), ('Reading recommendations:', 3, None, 'reading-recommendations'), - ('Topics of week 35', 2, None, 'topics-of-week-35'), ('Why Linear Regression (aka Ordinary Least Squares and family), ' 'repeat from last week', 2, @@ -301,78 +300,77 @@ MathJax.Hub.Config({ @@ -384,32 +382,19 @@ MathJax.Hub.Config({

       

       

       

      -

      More preprocessing

      +

      Frequently used scaling functions

      -
      -
      - -

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

      Many features are often scaled using standardization to improve performance. In Scikit-Learn this is given by the StandardScaler function as discussed above. It is easy however to write your own. +Mathematically, this involves subtracting the mean and divide by the standard deviation over the data set, for each feature:

      -

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

      -
      -
      +$$ + x_j^{(i)} \rightarrow \frac{x_j^{(i)} - \overline{x}_j}{\sigma(x_j)}, +$$ +

      where \( \overline{x}_j \) and \( \sigma(x_j) \) are the mean and standard deviation, respectively, of the feature \( x_j \). +This ensures that each feature has zero mean and unit standard deviation. For data sets where we do not have the standard deviation or don't wish to calculate it, it is then common to simply set it to one. +

      @@ -436,7 +421,7 @@ techniques.

    208. 39
    209. 40
    210. ...
    211. -
    212. 69
    213. +
    214. 68
    215. »
    216. diff --git a/doc/pub/week35/html/._week35-bs031.html b/doc/pub/week35/html/._week35-bs031.html index 34a7fbf22..2df66069b 100644 --- a/doc/pub/week35/html/._week35-bs031.html +++ b/doc/pub/week35/html/._week35-bs031.html @@ -38,7 +38,6 @@ doconce format html week35.do.txt --html_style=bootstrap --pygments_html_style=d {'highest level': 2, 'sections': [('Plans for week 35', 2, None, 'plans-for-week-35'), ('Reading recommendations:', 3, None, 'reading-recommendations'), - ('Topics of week 35', 2, None, 'topics-of-week-35'), ('Why Linear Regression (aka Ordinary Least Squares and family), ' 'repeat from last week', 2, @@ -301,78 +300,77 @@ MathJax.Hub.Config({ @@ -384,19 +382,60 @@ MathJax.Hub.Config({

       

       

       

      -

      Frequently used scaling functions

      +

      Example of own Standard scaling

      -

      Many features are often scaled using standardization to improve performance. In Scikit-Learn this is given by the StandardScaler function as discussed above. It is easy however to write your own. -Mathematically, this involves subtracting the mean and divide by the standard deviation over the data set, for each feature: +

      Let us consider the following vanilla example where we use both +Scikit-Learn and write our own function as well. We produce a +simple test design matrix with random numbers. Each column could then +represent a specific feature whose mean value is subracted.

      -$$ - x_j^{(i)} \rightarrow \frac{x_j^{(i)} - \overline{x}_j}{\sigma(x_j)}, -$$ -

      where \( \overline{x}_j \) and \( \sigma(x_j) \) are the mean and standard deviation, respectively, of the feature \( x_j \). -This ensures that each feature has zero mean and unit standard deviation. For data sets where we do not have the standard deviation or don't wish to calculate it, it is then common to simply set it to one. -

      + +
      +
      +
      +
      +
      +
      import sklearn.linear_model as skl
      +from sklearn.metrics import mean_squared_error
      +from sklearn.model_selection import  train_test_split
      +from sklearn.preprocessing import MinMaxScaler, StandardScaler, Normalizer
      +import numpy as np
      +import pandas as pd
      +from IPython.display import display
      +np.random.seed(100)
      +# setting up a 10 x 5 matrix
      +rows = 10
      +cols = 5
      +X = np.random.randn(rows,cols)
      +XPandas = pd.DataFrame(X)
      +display(XPandas)
      +print(XPandas.mean())
      +print(XPandas.std())
      +XPandas = (XPandas -XPandas.mean())
      +display(XPandas)
      +#  This option does not include the standard deviation
      +scaler = StandardScaler(with_std=False)
      +scaler.fit(X)
      +Xscaled = scaler.transform(X)
      +display(XPandas-Xscaled)
      +
      +
      +
      +
      +
      +
      +
      +
      +
      +
      +
      +
      +
      +
      + +

      Small exercise: perform the standard scaling by including the standard deviation and compare with what Scikit-Learn gives.

      @@ -423,7 +462,7 @@ This ensures that each feature has zero mean and unit standard deviation. For d

    217. 40
    218. 41
    219. ...
    220. -
    221. 69
    222. +
    223. 68
    224. »
    225. diff --git a/doc/pub/week35/html/._week35-bs032.html b/doc/pub/week35/html/._week35-bs032.html index 0a7a4685f..301a2cf3e 100644 --- a/doc/pub/week35/html/._week35-bs032.html +++ b/doc/pub/week35/html/._week35-bs032.html @@ -38,7 +38,6 @@ doconce format html week35.do.txt --html_style=bootstrap --pygments_html_style=d {'highest level': 2, 'sections': [('Plans for week 35', 2, None, 'plans-for-week-35'), ('Reading recommendations:', 3, None, 'reading-recommendations'), - ('Topics of week 35', 2, None, 'topics-of-week-35'), ('Why Linear Regression (aka Ordinary Least Squares and family), ' 'repeat from last week', 2, @@ -301,78 +300,77 @@ MathJax.Hub.Config({ @@ -384,60 +382,19 @@ MathJax.Hub.Config({

       

       

       

      -

      Example of own Standard scaling

      +

      Min-Max Scaling

      -

      Let us consider the following vanilla example where we use both -Scikit-Learn and write our own function as well. We produce a -simple test design matrix with random numbers. Each column could then -represent a specific feature whose mean value is subracted. +

      Another commonly used scaling method is min-max scaling. This is very +useful for when we want the features to lie in a certain interval. To +scale the feature \( x_j \) to the interval \( [a, b] \), we can apply the +transformation

      +$$ +x_j^{(i)} \rightarrow (b-a)\frac{x_j^{(i)} - \min(x_j)}{\max(x_j) - \min(x_j)} - a +$$ - -
      -
      -
      -
      -
      -
      import sklearn.linear_model as skl
      -from sklearn.metrics import mean_squared_error
      -from sklearn.model_selection import  train_test_split
      -from sklearn.preprocessing import MinMaxScaler, StandardScaler, Normalizer
      -import numpy as np
      -import pandas as pd
      -from IPython.display import display
      -np.random.seed(100)
      -# setting up a 10 x 5 matrix
      -rows = 10
      -cols = 5
      -X = np.random.randn(rows,cols)
      -XPandas = pd.DataFrame(X)
      -display(XPandas)
      -print(XPandas.mean())
      -print(XPandas.std())
      -XPandas = (XPandas -XPandas.mean())
      -display(XPandas)
      -#  This option does not include the standard deviation
      -scaler = StandardScaler(with_std=False)
      -scaler.fit(X)
      -Xscaled = scaler.transform(X)
      -display(XPandas-Xscaled)
      -
      -
      -
      -
      -
      -
      -
      -
      -
      -
      -
      -
      -
      -
      - -

      Small exercise: perform the standard scaling by including the standard deviation and compare with what Scikit-Learn gives.

      +

      where \( \min(x_j) \) and \( \max(x_j) \) return the minimum and maximum value of \( x_j \) over the data set, respectively.

      @@ -464,7 +421,7 @@ display(XPandas-Xscaled)

    226. 41
    227. 42
    228. ...
    229. -
    230. 69
    231. +
    232. 68
    233. »
    234. diff --git a/doc/pub/week35/html/._week35-bs033.html b/doc/pub/week35/html/._week35-bs033.html index 823f51a5f..626259b26 100644 --- a/doc/pub/week35/html/._week35-bs033.html +++ b/doc/pub/week35/html/._week35-bs033.html @@ -38,7 +38,6 @@ doconce format html week35.do.txt --html_style=bootstrap --pygments_html_style=d {'highest level': 2, 'sections': [('Plans for week 35', 2, None, 'plans-for-week-35'), ('Reading recommendations:', 3, None, 'reading-recommendations'), - ('Topics of week 35', 2, None, 'topics-of-week-35'), ('Why Linear Regression (aka Ordinary Least Squares and family), ' 'repeat from last week', 2, @@ -301,78 +300,77 @@ MathJax.Hub.Config({ @@ -384,19 +382,102 @@ MathJax.Hub.Config({

       

       

       

      -

      Min-Max Scaling

      - -

      Another commonly used scaling method is min-max scaling. This is very -useful for when we want the features to lie in a certain interval. To -scale the feature \( x_j \) to the interval \( [a, b] \), we can apply the -transformation +

      Testing the Means Squared Error as function of Complexity

      +

      One of +the aims is to reproduce Figure 2.11 of Hastie et al. +We will also use Ridge and Lasso regression.

      -$$ -x_j^{(i)} \rightarrow (b-a)\frac{x_j^{(i)} - \min(x_j)}{\max(x_j) - \min(x_j)} - a -$$ +

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

      + + +
      +
      +
      +
      +
      +
      np.random.seed()
      +n = 100
      +maxdegree = 14
      +# Make data set.
      +x = np.linspace(-3, 3, n).reshape(-1, 1)
      +y = np.exp(-x**2) + 1.5 * np.exp(-(x-2)**2)+ np.random.normal(0, 0.1, x.shape)
      +
      +
      +
      +
      +
      +
      +
      +
      +
      +
      +
      +
      +
      +
      + +

      where \( y \) is the function we want to fit with a given polynomial.

      + +

      Write a first code which sets up a design matrix \( X \) defined by a fifth-order polynomial. Scale your data and split it in training and test data.

      + + +
      +
      +
      +
      +
      +
      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
      +
      +
      +np.random.seed(2018)
      +n = 50
      +maxdegree = 5
      +# 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)
      +TestError = np.zeros(maxdegree)
      +TrainError = np.zeros(maxdegree)
      +polydegree = np.zeros(maxdegree)
      +x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.2)
      +scaler = StandardScaler()
      +scaler.fit(x_train)
      +x_train_scaled = scaler.transform(x_train)
      +x_test_scaled = scaler.transform(x_test)
      +
      +for degree in range(maxdegree):
      +    model = make_pipeline(PolynomialFeatures(degree=degree), LinearRegression(fit_intercept=False))
      +    clf = model.fit(x_train_scaled,y_train)
      +    y_fit = clf.predict(x_train_scaled)
      +    y_pred = clf.predict(x_test_scaled) 
      +    polydegree[degree] = degree
      +    TestError[degree] = np.mean( np.mean((y_test - y_pred)**2) )
      +    TrainError[degree] = np.mean( np.mean((y_train - y_fit)**2) )
      +
      +plt.plot(polydegree, TestError, label='Test Error')
      +plt.plot(polydegree, TrainError, label='Train Error')
      +plt.legend()
      +plt.show()
      +
      +
      +
      +
      +
      +
      +
      +
      +
      +
      +
      +
      +
      +
      -

      where \( \min(x_j) \) and \( \max(x_j) \) return the minimum and maximum value of \( x_j \) over the data set, respectively.

      @@ -423,7 +504,7 @@ $$

    235. 42
    236. 43
    237. ...
    238. -
    239. 69
    240. +
    241. 68
    242. »
    243. diff --git a/doc/pub/week35/html/._week35-bs034.html b/doc/pub/week35/html/._week35-bs034.html index 06c42defd..a8d7b3711 100644 --- a/doc/pub/week35/html/._week35-bs034.html +++ b/doc/pub/week35/html/._week35-bs034.html @@ -38,7 +38,6 @@ doconce format html week35.do.txt --html_style=bootstrap --pygments_html_style=d {'highest level': 2, 'sections': [('Plans for week 35', 2, None, 'plans-for-week-35'), ('Reading recommendations:', 3, None, 'reading-recommendations'), - ('Topics of week 35', 2, None, 'topics-of-week-35'), ('Why Linear Regression (aka Ordinary Least Squares and family), ' 'repeat from last week', 2, @@ -301,78 +300,77 @@ MathJax.Hub.Config({ @@ -384,13 +382,8 @@ MathJax.Hub.Config({

       

       

       

      -

      Testing the Means Squared Error as function of Complexity

      -

      One of -the aims is to reproduce Figure 2.11 of Hastie et al. -We will also use Ridge and Lasso regression. -

      +

      More preprocessing examples, Franke function and regression

      -

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

      @@ -398,73 +391,98 @@ We will also use Ridge and Lasso regression.
      -
      np.random.seed()
      -n = 100
      -maxdegree = 14
      -# Make data set.
      -x = np.linspace(-3, 3, n).reshape(-1, 1)
      -y = np.exp(-x**2) + 1.5 * np.exp(-(x-2)**2)+ np.random.normal(0, 0.1, x.shape)
      -
      -
      -
      -
      -
      -
      -
      -
      -
      -
      -
      -
      -
      -
      - -

      where \( y \) is the function we want to fit with a given polynomial.

      - -

      Write a first code which sets up a design matrix \( X \) defined by a fifth-order polynomial. Scale your data and split it in training and test data.

      - - -
      -
      -
      -
      -
      -
      import matplotlib.pyplot as plt
      +  
      # Common imports
      +import os
       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
      +import pandas as pd
      +import matplotlib.pyplot as plt
      +import sklearn.linear_model as skl
      +from sklearn.metrics import mean_squared_error
      +from sklearn.model_selection import  train_test_split
      +from sklearn.preprocessing import MinMaxScaler, StandardScaler, Normalizer
      +
      +# 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')
       
       
      -np.random.seed(2018)
      -n = 50
      -maxdegree = 5
      -# 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)
      -TestError = np.zeros(maxdegree)
      -TrainError = np.zeros(maxdegree)
      -polydegree = np.zeros(maxdegree)
      -x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.2)
      +def FrankeFunction(x,y):
      +	term1 = 0.75*np.exp(-(0.25*(9*x-2)**2) - 0.25*((9*y-2)**2))
      +	term2 = 0.75*np.exp(-((9*x+1)**2)/49.0 - 0.1*(9*y+1))
      +	term3 = 0.5*np.exp(-(9*x-7)**2/4.0 - 0.25*((9*y-3)**2))
      +	term4 = -0.2*np.exp(-(9*x-4)**2 - (9*y-7)**2)
      +	return term1 + term2 + term3 + term4
      +
      +
      +def create_X(x, y, n ):
      +	if len(x.shape) > 1:
      +		x = np.ravel(x)
      +		y = np.ravel(y)
      +
      +	N = len(x)
      +	l = int((n+1)*(n+2)/2)		# Number of elements in beta
      +	X = np.ones((N,l))
      +
      +	for i in range(1,n+1):
      +		q = int((i)*(i+1)/2)
      +		for k in range(i+1):
      +			X[:,q+k] = (x**(i-k))*(y**k)
      +
      +	return X
      +
      +
      +# Making meshgrid of datapoints and compute Franke's function
      +n = 5
      +N = 1000
      +x = np.sort(np.random.uniform(0, 1, N))
      +y = np.sort(np.random.uniform(0, 1, N))
      +z = FrankeFunction(x, y)
      +X = create_X(x, y, n=n)    
      +# split in training and test data
      +X_train, X_test, y_train, y_test = train_test_split(X,z,test_size=0.2)
      +
      +
      +clf = skl.LinearRegression().fit(X_train, y_train)
      +
      +# The mean squared error and R2 score
      +print("MSE before scaling: {:.2f}".format(mean_squared_error(clf.predict(X_test), y_test)))
      +print("R2 score before scaling {:.2f}".format(clf.score(X_test,y_test)))
      +
       scaler = StandardScaler()
      -scaler.fit(x_train)
      -x_train_scaled = scaler.transform(x_train)
      -x_test_scaled = scaler.transform(x_test)
      +scaler.fit(X_train)
      +X_train_scaled = scaler.transform(X_train)
      +X_test_scaled = scaler.transform(X_test)
       
      -for degree in range(maxdegree):
      -    model = make_pipeline(PolynomialFeatures(degree=degree), LinearRegression(fit_intercept=False))
      -    clf = model.fit(x_train_scaled,y_train)
      -    y_fit = clf.predict(x_train_scaled)
      -    y_pred = clf.predict(x_test_scaled) 
      -    polydegree[degree] = degree
      -    TestError[degree] = np.mean( np.mean((y_test - y_pred)**2) )
      -    TrainError[degree] = np.mean( np.mean((y_train - y_fit)**2) )
      +print("Feature min values before scaling:\n {}".format(X_train.min(axis=0)))
      +print("Feature max values before scaling:\n {}".format(X_train.max(axis=0)))
       
      -plt.plot(polydegree, TestError, label='Test Error')
      -plt.plot(polydegree, TrainError, label='Train Error')
      -plt.legend()
      -plt.show()
      +print("Feature min values after scaling:\n {}".format(X_train_scaled.min(axis=0)))
      +print("Feature max values after scaling:\n {}".format(X_train_scaled.max(axis=0)))
      +
      +clf = skl.LinearRegression().fit(X_train_scaled, y_train)
      +
      +
      +print("MSE after  scaling: {:.2f}".format(mean_squared_error(clf.predict(X_test_scaled), y_test)))
      +print("R2 score for  scaled data: {:.2f}".format(clf.score(X_test_scaled,y_test)))
       
      @@ -506,7 +524,7 @@ plt.show()
    244. 43
    245. 44
    246. ...
    247. -
    248. 69
    249. +
    250. 68
    251. »
    252. diff --git a/doc/pub/week35/html/._week35-bs035.html b/doc/pub/week35/html/._week35-bs035.html index 4111a749f..4b189917a 100644 --- a/doc/pub/week35/html/._week35-bs035.html +++ b/doc/pub/week35/html/._week35-bs035.html @@ -38,7 +38,6 @@ doconce format html week35.do.txt --html_style=bootstrap --pygments_html_style=d {'highest level': 2, 'sections': [('Plans for week 35', 2, None, 'plans-for-week-35'), ('Reading recommendations:', 3, None, 'reading-recommendations'), - ('Topics of week 35', 2, None, 'topics-of-week-35'), ('Why Linear Regression (aka Ordinary Least Squares and family), ' 'repeat from last week', 2, @@ -301,78 +300,77 @@ MathJax.Hub.Config({ @@ -384,122 +382,37 @@ MathJax.Hub.Config({

       

       

       

      -

      More preprocessing examples, Franke function and regression

      +

      Mathematical Interpretation of Ordinary Least Squares

      +

      What is presented here is a mathematical analysis of various regression algorithms (ordinary least squares, Ridge and Lasso Regression). The analysis is based on an important algorithm in linear algebra, the so-called Singular Value Decomposition (SVD).

      - -
      -
      -
      -
      -
      -
      # Common imports
      -import os
      -import numpy as np
      -import pandas as pd
      -import matplotlib.pyplot as plt
      -import sklearn.linear_model as skl
      -from sklearn.metrics import mean_squared_error
      -from sklearn.model_selection import  train_test_split
      -from sklearn.preprocessing import MinMaxScaler, StandardScaler, Normalizer
      +

      We have shown that in ordinary least squares the optimal parameters \( \beta \) are given by

      -# Where to save the figures and data files -PROJECT_ROOT_DIR = "Results" -FIGURE_ID = "Results/FigureFiles" -DATA_ID = "DataFiles/" +$$ +\hat{\boldsymbol{\beta}} = \left(\boldsymbol{X}^T\boldsymbol{X}\right)^{-1}\boldsymbol{X}^T\boldsymbol{y}. +$$ -if not os.path.exists(PROJECT_ROOT_DIR): - os.mkdir(PROJECT_ROOT_DIR) +

      The hat over \( \boldsymbol{\beta} \) means we have the optimal parameters after minimization of the cost function.

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

      This means that our best model is defined as

      -if not os.path.exists(DATA_ID): - os.makedirs(DATA_ID) +$$ +\tilde{\boldsymbol{y}}=\boldsymbol{X}\hat{\boldsymbol{\beta}} = \boldsymbol{X}\left(\boldsymbol{X}^T\boldsymbol{X}\right)^{-1}\boldsymbol{X}^T\boldsymbol{y}. +$$ -def image_path(fig_id): - return os.path.join(FIGURE_ID, fig_id) +

      We now define a matrix

      +$$ +\boldsymbol{A}=\boldsymbol{X}\left(\boldsymbol{X}^T\boldsymbol{X}\right)^{-1}\boldsymbol{X}^T. +$$ -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 FrankeFunction(x,y): - term1 = 0.75*np.exp(-(0.25*(9*x-2)**2) - 0.25*((9*y-2)**2)) - term2 = 0.75*np.exp(-((9*x+1)**2)/49.0 - 0.1*(9*y+1)) - term3 = 0.5*np.exp(-(9*x-7)**2/4.0 - 0.25*((9*y-3)**2)) - term4 = -0.2*np.exp(-(9*x-4)**2 - (9*y-7)**2) - return term1 + term2 + term3 + term4 - - -def create_X(x, y, n ): - if len(x.shape) > 1: - x = np.ravel(x) - y = np.ravel(y) - - N = len(x) - l = int((n+1)*(n+2)/2) # Number of elements in beta - X = np.ones((N,l)) - - for i in range(1,n+1): - q = int((i)*(i+1)/2) - for k in range(i+1): - X[:,q+k] = (x**(i-k))*(y**k) - - return X - - -# Making meshgrid of datapoints and compute Franke's function -n = 5 -N = 1000 -x = np.sort(np.random.uniform(0, 1, N)) -y = np.sort(np.random.uniform(0, 1, N)) -z = FrankeFunction(x, y) -X = create_X(x, y, n=n) -# split in training and test data -X_train, X_test, y_train, y_test = train_test_split(X,z,test_size=0.2) - - -clf = skl.LinearRegression().fit(X_train, y_train) - -# The mean squared error and R2 score -print("MSE before scaling: {:.2f}".format(mean_squared_error(clf.predict(X_test), y_test))) -print("R2 score before scaling {:.2f}".format(clf.score(X_test,y_test))) - -scaler = StandardScaler() -scaler.fit(X_train) -X_train_scaled = scaler.transform(X_train) -X_test_scaled = scaler.transform(X_test) - -print("Feature min values before scaling:\n {}".format(X_train.min(axis=0))) -print("Feature max values before scaling:\n {}".format(X_train.max(axis=0))) - -print("Feature min values after scaling:\n {}".format(X_train_scaled.min(axis=0))) -print("Feature max values after scaling:\n {}".format(X_train_scaled.max(axis=0))) - -clf = skl.LinearRegression().fit(X_train_scaled, y_train) - - -print("MSE after scaling: {:.2f}".format(mean_squared_error(clf.predict(X_test_scaled), y_test))) -print("R2 score for scaled data: {:.2f}".format(clf.score(X_test_scaled,y_test))) -
      -
      -
      -
      -
      -
      -
      -
      -
      -
      -
      -
      -
      -
      +

      We can rewrite

      +$$ +\tilde{\boldsymbol{y}}=\boldsymbol{X}\hat{\boldsymbol{\beta}} = \boldsymbol{A}\boldsymbol{y}. +$$ +

      The matrix \( \boldsymbol{A} \) has the important property that \( \boldsymbol{A}^2=\boldsymbol{A} \). This is the definition of a projection matrix. +We can then interpret our optimal model \( \tilde{\boldsymbol{y}} \) as being represented by an orthogonal projection of \( \boldsymbol{y} \) onto a space defined by the column vectors of \( \boldsymbol{X} \). In our case here the matrix \( \boldsymbol{A} \) is a square matrix. If it is a general rectangular matrix we have an oblique projection matrix. +

      @@ -526,7 +439,7 @@ clf = skl.44

    253. 45
    254. ...
    255. -
    256. 69
    257. +
    258. 68
    259. »
    260. diff --git a/doc/pub/week35/html/._week35-bs036.html b/doc/pub/week35/html/._week35-bs036.html index cdadc7649..9246a46c1 100644 --- a/doc/pub/week35/html/._week35-bs036.html +++ b/doc/pub/week35/html/._week35-bs036.html @@ -38,7 +38,6 @@ doconce format html week35.do.txt --html_style=bootstrap --pygments_html_style=d {'highest level': 2, 'sections': [('Plans for week 35', 2, None, 'plans-for-week-35'), ('Reading recommendations:', 3, None, 'reading-recommendations'), - ('Topics of week 35', 2, None, 'topics-of-week-35'), ('Why Linear Regression (aka Ordinary Least Squares and family), ' 'repeat from last week', 2, @@ -301,78 +300,77 @@ MathJax.Hub.Config({ @@ -384,37 +382,14 @@ MathJax.Hub.Config({

       

       

       

      -

      Mathematical Interpretation of Ordinary Least Squares

      - -

      What is presented here is a mathematical analysis of various regression algorithms (ordinary least squares, Ridge and Lasso Regression). The analysis is based on an important algorithm in linear algebra, the so-called Singular Value Decomposition (SVD).

      - -

      We have shown that in ordinary least squares the optimal parameters \( \beta \) are given by

      +

      Residual Error

      +

      We have defined the residual error as

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

      The hat over \( \boldsymbol{\beta} \) means we have the optimal parameters after minimization of the cost function.

      - -

      This means that our best model is defined as

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

      We now define a matrix

      -$$ -\boldsymbol{A}=\boldsymbol{X}\left(\boldsymbol{X}^T\boldsymbol{X}\right)^{-1}\boldsymbol{X}^T. -$$ - -

      We can rewrite

      -$$ -\tilde{\boldsymbol{y}}=\boldsymbol{X}\hat{\boldsymbol{\beta}} = \boldsymbol{A}\boldsymbol{y}. -$$ - -

      The matrix \( \boldsymbol{A} \) has the important property that \( \boldsymbol{A}^2=\boldsymbol{A} \). This is the definition of a projection matrix. -We can then interpret our optimal model \( \tilde{\boldsymbol{y}} \) as being represented by an orthogonal projection of \( \boldsymbol{y} \) onto a space defined by the column vectors of \( \boldsymbol{X} \). In our case here the matrix \( \boldsymbol{A} \) is a square matrix. If it is a general rectangular matrix we have an oblique projection matrix. -

      +

      The residual errors are then the projections of \( \boldsymbol{y} \) onto the orthogonal component of the space defined by the column vectors of \( \boldsymbol{X} \).

      @@ -441,7 +416,7 @@ We can then interpret our optimal model \( \tilde{\boldsymbol{y}} \) as being re

    261. 45
    262. 46
    263. ...
    264. -
    265. 69
    266. +
    267. 68
    268. »
    269. diff --git a/doc/pub/week35/html/._week35-bs037.html b/doc/pub/week35/html/._week35-bs037.html index 307f5e687..aad8047bb 100644 --- a/doc/pub/week35/html/._week35-bs037.html +++ b/doc/pub/week35/html/._week35-bs037.html @@ -38,7 +38,6 @@ doconce format html week35.do.txt --html_style=bootstrap --pygments_html_style=d {'highest level': 2, 'sections': [('Plans for week 35', 2, None, 'plans-for-week-35'), ('Reading recommendations:', 3, None, 'reading-recommendations'), - ('Topics of week 35', 2, None, 'topics-of-week-35'), ('Why Linear Regression (aka Ordinary Least Squares and family), ' 'repeat from last week', 2, @@ -301,78 +300,77 @@ MathJax.Hub.Config({ @@ -384,14 +382,25 @@ MathJax.Hub.Config({

       

       

       

      -

      Residual Error

      +

      Simple case

      + +

      If the matrix \( \boldsymbol{X} \) is an orthogonal (or unitary in case of complex values) matrix, we have

      -

      We have defined the residual error as

      $$ -\boldsymbol{\epsilon}=\boldsymbol{y}-\tilde{\boldsymbol{y}}=\left[\boldsymbol{I}-\boldsymbol{X}\left(\boldsymbol{X}^T\boldsymbol{X}\right)^{-1}\boldsymbol{X}^T\right]\boldsymbol{y}. +\boldsymbol{X}^T\boldsymbol{X}=\boldsymbol{X}\boldsymbol{X}^T = \boldsymbol{I}. $$ -

      The residual errors are then the projections of \( \boldsymbol{y} \) onto the orthogonal component of the space defined by the column vectors of \( \boldsymbol{X} \).

      +

      In this case the matrix \( \boldsymbol{A} \) becomes

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

      and we have the obvious case

      +$$ +\boldsymbol{\epsilon}=\boldsymbol{y}-\tilde{\boldsymbol{y}}=0. +$$ + +

      This serves also as a useful test of our codes.

      @@ -418,7 +427,7 @@ $$

    270. 46
    271. 47
    272. ...
    273. -
    274. 69
    275. +
    276. 68
    277. »
    278. diff --git a/doc/pub/week35/html/._week35-bs038.html b/doc/pub/week35/html/._week35-bs038.html index c87eeb8c0..c75ba5ff3 100644 --- a/doc/pub/week35/html/._week35-bs038.html +++ b/doc/pub/week35/html/._week35-bs038.html @@ -38,7 +38,6 @@ doconce format html week35.do.txt --html_style=bootstrap --pygments_html_style=d {'highest level': 2, 'sections': [('Plans for week 35', 2, None, 'plans-for-week-35'), ('Reading recommendations:', 3, None, 'reading-recommendations'), - ('Topics of week 35', 2, None, 'topics-of-week-35'), ('Why Linear Regression (aka Ordinary Least Squares and family), ' 'repeat from last week', 2, @@ -301,78 +300,77 @@ MathJax.Hub.Config({ @@ -384,25 +382,49 @@ MathJax.Hub.Config({

       

       

       

      -

      Simple case

      +

      The singular value decomposition

      -

      If the matrix \( \boldsymbol{X} \) is an orthogonal (or unitary in case of complex values) matrix, we have

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

      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 where we fit of various functions leads to +row vectors of the design matrix which are essentially orthogonal due +to the polynomial character of our model. Obtaining the inverse of the +design matrix is then often done via a so-called LU, QR or Cholesky +decomposition. +

      -

      In this case the matrix \( \boldsymbol{A} \) becomes

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

      As we will also see in the first project, +this may +however not the be case in general and a standard matrix inversion +algorithm based on say LU, QR or Cholesky decomposition may lead to singularities. We will see examples of this below. +

      -

      and we have the obvious case

      -$$ -\boldsymbol{\epsilon}=\boldsymbol{y}-\tilde{\boldsymbol{y}}=0. -$$ +

      There is however a way to circumvent this problem and also +gain some insights about the ordinary least squares approach, and +later shrinkage methods like Ridge and Lasso regressions. +

      + +

      This is given by the Singular Value Decomposition (SVD) algorithm, +perhaps the most powerful linear algebra algorithm. The SVD provides +a numerically stable matrix decomposition that is used in a large +swath oc applications and the decomposition is always stable +numerically. +

      + +

      In machine learning it plays a central role in dealing with for +example design matrices that may be near singular or singular. +Furthermore, as we will see here, the singular values can be related +to the covariance matrix (and thereby the correlation matrix) and in +turn the variance of a given quantity. It plays also an important role +in the principal component analysis where high-dimensional data can be +reduced to the statistically relevant features. +

      +
      +
      -

      This serves also as a useful test of our codes.

      @@ -429,7 +451,7 @@ $$

    279. 47
    280. 48
    281. ...
    282. -
    283. 69
    284. +
    285. 68
    286. »
    287. diff --git a/doc/pub/week35/html/._week35-bs039.html b/doc/pub/week35/html/._week35-bs039.html index d25d527fd..caa03cae7 100644 --- a/doc/pub/week35/html/._week35-bs039.html +++ b/doc/pub/week35/html/._week35-bs039.html @@ -38,7 +38,6 @@ doconce format html week35.do.txt --html_style=bootstrap --pygments_html_style=d {'highest level': 2, 'sections': [('Plans for week 35', 2, None, 'plans-for-week-35'), ('Reading recommendations:', 3, None, 'reading-recommendations'), - ('Topics of week 35', 2, None, 'topics-of-week-35'), ('Why Linear Regression (aka Ordinary Least Squares and family), ' 'repeat from last week', 2, @@ -301,78 +300,77 @@ MathJax.Hub.Config({ @@ -384,50 +382,55 @@ MathJax.Hub.Config({

       

       

       

      -

      The singular value decomposition

      +

      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*} +$$ -

      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 where we fit of various functions leads to -row vectors of the design matrix which are essentially orthogonal due -to the polynomial character of our model. Obtaining the inverse of the -design matrix is then often done via a so-called LU, QR or Cholesky -decomposition. +

      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.

      -

      As we will also see in the first project, -this may -however not the be case in general and a standard matrix inversion -algorithm based on say LU, QR or Cholesky decomposition may lead to singularities. We will see examples of this below. +

      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*} +$$ -

      There is however a way to circumvent this problem and also -gain some insights about the ordinary least squares approach, and -later shrinkage methods like Ridge and Lasso regressions. +

      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.

      -

      This is given by the Singular Value Decomposition (SVD) algorithm, -perhaps the most powerful linear algebra algorithm. The SVD provides -a numerically stable matrix decomposition that is used in a large -swath oc applications and the decomposition is always stable -numerically. -

      - -

      In machine learning it plays a central role in dealing with for -example design matrices that may be near singular or singular. -Furthermore, as we will see here, the singular values can be related -to the covariance matrix (and thereby the correlation matrix) and in -turn the variance of a given quantity. It plays also an important role -in the principal component analysis where high-dimensional data can be -reduced to the statistically relevant features. -

      -
      -
      - -

        @@ -453,7 +456,7 @@ reduced to the statistically relevant features.
      • 48
      • 49
      • ...
      • -
      • 69
      • +
      • 68
      • »
      diff --git a/doc/pub/week35/html/._week35-bs040.html b/doc/pub/week35/html/._week35-bs040.html index 2a5cfad5c..9401a36e4 100644 --- a/doc/pub/week35/html/._week35-bs040.html +++ b/doc/pub/week35/html/._week35-bs040.html @@ -38,7 +38,6 @@ doconce format html week35.do.txt --html_style=bootstrap --pygments_html_style=d {'highest level': 2, 'sections': [('Plans for week 35', 2, None, 'plans-for-week-35'), ('Reading recommendations:', 3, None, 'reading-recommendations'), - ('Topics of week 35', 2, None, 'topics-of-week-35'), ('Why Linear Regression (aka Ordinary Least Squares and family), ' 'repeat from last week', 2, @@ -301,78 +300,77 @@ MathJax.Hub.Config({ @@ -384,54 +382,29 @@ MathJax.Hub.Config({

       

       

       

      -

      Linear Regression Problems

      +

      Fixing the singularity

      -

      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 -

      +

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

      $$ -\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*} +\begin{align} +\boldsymbol{\beta} & = (\boldsymbol{X}^{T} \boldsymbol{X})^{-1} \boldsymbol{X}^{T} \boldsymbol{y}, +\tag{1} +\end{align} $$ -

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

      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.

      -

      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 -

      +

      A cheap ad hoc approach is simply to add a small diagonal component to the matrix to invert, that is we change

      $$ -\begin{align*} -\boldsymbol{X} & = \left[ -\begin{array}{rr} -1 & -1 -\\ -1 & -1 -\end{array} \right]. -\end{align*} +\boldsymbol{X}^{T} \boldsymbol{X} \rightarrow \boldsymbol{X}^{T} \boldsymbol{X}+\lambda \boldsymbol{I}, $$ -

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

      +

      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.

      @@ -458,7 +431,7 @@ This is equivalent to saying that the matrix \( \boldsymbol{X} \) has at least a

    288. 49
    289. 50
    290. ...
    291. -
    292. 69
    293. +
    294. 68
    295. »
    296. diff --git a/doc/pub/week35/html/._week35-bs041.html b/doc/pub/week35/html/._week35-bs041.html index 1e6e2c14b..58e19c4fb 100644 --- a/doc/pub/week35/html/._week35-bs041.html +++ b/doc/pub/week35/html/._week35-bs041.html @@ -38,7 +38,6 @@ doconce format html week35.do.txt --html_style=bootstrap --pygments_html_style=d {'highest level': 2, 'sections': [('Plans for week 35', 2, None, 'plans-for-week-35'), ('Reading recommendations:', 3, None, 'reading-recommendations'), - ('Topics of week 35', 2, None, 'topics-of-week-35'), ('Why Linear Regression (aka Ordinary Least Squares and family), ' 'repeat from last week', 2, @@ -301,78 +300,77 @@ MathJax.Hub.Config({ @@ -384,29 +382,41 @@ MathJax.Hub.Config({

       

       

       

      -

      Fixing the singularity

      +

      Basic math of the SVD

      -

      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{1} -\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. +

      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

      -

      A cheap ad hoc approach is simply to add a small diagonal component to the matrix to invert, that is we change

      $$ -\boldsymbol{X}^{T} \boldsymbol{X} \rightarrow \boldsymbol{X}^{T} \boldsymbol{X}+\lambda \boldsymbol{I}, +(\lambda_1,\boldsymbol{u}_1),\dots, (\lambda_n,\boldsymbol{u}_n), $$ -

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

      +

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

      + +

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

      @@ -433,7 +443,7 @@ $$

    297. 50
    298. 51
    299. ...
    300. -
    301. 69
    302. +
    303. 68
    304. »
    305. diff --git a/doc/pub/week35/html/._week35-bs042.html b/doc/pub/week35/html/._week35-bs042.html index de0f4492f..45e2a6bf5 100644 --- a/doc/pub/week35/html/._week35-bs042.html +++ b/doc/pub/week35/html/._week35-bs042.html @@ -38,7 +38,6 @@ doconce format html week35.do.txt --html_style=bootstrap --pygments_html_style=d {'highest level': 2, 'sections': [('Plans for week 35', 2, None, 'plans-for-week-35'), ('Reading recommendations:', 3, None, 'reading-recommendations'), - ('Topics of week 35', 2, None, 'topics-of-week-35'), ('Why Linear Regression (aka Ordinary Least Squares and family), ' 'repeat from last week', 2, @@ -301,78 +300,77 @@ MathJax.Hub.Config({ @@ -384,42 +382,53 @@ MathJax.Hub.Config({

       

       

       

      -

      Basic math of the SVD

      +

      The SVD, a Fantastic Algorithm

      -

      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 +

      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 \( m\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

      -$$ -(\lambda_1,\boldsymbol{u}_1),\dots, (\lambda_n,\boldsymbol{u}_n), +$$ +\boldsymbol{X} = \boldsymbol{U}\boldsymbol{\Sigma}\boldsymbol{V}^T $$ -

      and the eigenvalues are given by the diagonal matrix

      +

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

      + $$ -\boldsymbol{\Sigma}=\mathrm{Diag}(\lambda_1, \dots,\lambda_n). +\boldsymbol{X} = \frac{1}{\sqrt{2}}\begin{bmatrix} 1& 1 \\ 1& -1\\ \end{bmatrix} \begin{bmatrix} 2& 0 \\ 0& 0\\ \end{bmatrix} \frac{1}{\sqrt{2}}\begin{bmatrix} 1& -1 \\ 1& 1\\ \end{bmatrix}=\boldsymbol{U}\boldsymbol{\Sigma}\boldsymbol{V}^T, $$ -

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

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

      +

      The SVD +decomposition (singular values) gives eigenvalues +\( \sigma_i\geq\sigma_{i+1} \) for all \( i \) and for dimensions larger than \( i=p \), 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\geq 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.

      +

      diff --git a/doc/pub/week35/html/._week35-bs043.html b/doc/pub/week35/html/._week35-bs043.html index 0c01daa79..87cb23f65 100644 --- a/doc/pub/week35/html/._week35-bs043.html +++ b/doc/pub/week35/html/._week35-bs043.html @@ -38,7 +38,6 @@ doconce format html week35.do.txt --html_style=bootstrap --pygments_html_style=d {'highest level': 2, 'sections': [('Plans for week 35', 2, None, 'plans-for-week-35'), ('Reading recommendations:', 3, None, 'reading-recommendations'), - ('Topics of week 35', 2, None, 'topics-of-week-35'), ('Why Linear Regression (aka Ordinary Least Squares and family), ' 'repeat from last week', 2, @@ -301,78 +300,77 @@ MathJax.Hub.Config({ @@ -384,53 +382,28 @@ MathJax.Hub.Config({

       

       

       

      -

      The SVD, a Fantastic Algorithm

      +

      Economy-size SVD

      -

      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 \( m\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 +

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

      -$$ -\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! +

      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.

      -

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

      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.

      -

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

      -

        @@ -456,7 +429,7 @@ near singular or singular matrices.
      • 52
      • 53
      • ...
      • -
      • 69
      • +
      • 68
      • »
      diff --git a/doc/pub/week35/html/._week35-bs044.html b/doc/pub/week35/html/._week35-bs044.html index 02e5f002f..65bc8e2fb 100644 --- a/doc/pub/week35/html/._week35-bs044.html +++ b/doc/pub/week35/html/._week35-bs044.html @@ -38,7 +38,6 @@ doconce format html week35.do.txt --html_style=bootstrap --pygments_html_style=d {'highest level': 2, 'sections': [('Plans for week 35', 2, None, 'plans-for-week-35'), ('Reading recommendations:', 3, None, 'reading-recommendations'), - ('Topics of week 35', 2, None, 'topics-of-week-35'), ('Why Linear Regression (aka Ordinary Least Squares and family), ' 'repeat from last week', 2, @@ -301,78 +300,77 @@ MathJax.Hub.Config({ @@ -384,26 +382,67 @@ MathJax.Hub.Config({

       

       

       

      -

      Economy-size SVD

      +

      Codes for the 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. -

      + +
      +
      +
      +
      +
      +
      import numpy as np
      +# SVD inversion
      +def SVD(A):
      +    ''' Takes as input a numpy matrix A and returns inv(A) based on singular value decomposition (SVD).
      +    SVD is numerically more stable than the inversion algorithms provided by
      +    numpy and scipy.linalg at the cost of being slower.
      +    '''
      +    U, S, VT = np.linalg.svd(A,full_matrices=True)
      +    print('test U')
      +    print( (np.transpose(U) @ U - U @np.transpose(U)))
      +    print('test VT')
      +    print( (np.transpose(VT) @ VT - VT @np.transpose(VT)))
      +    print(U)
      +    print(S)
      +    print(VT)
       
      -

      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. + D = np.zeros((len(U),len(VT))) + for i in range(0,len(VT)): + D[i,i]=S[i] + return U @ D @ VT + + +X = np.array([ [1.0,-1.0], [1.0,-1.0]]) +#X = np.array([[1, 2], [3, 4], [5, 6]]) + +print(X) +C = SVD(X) +# Print the difference between the original matrix and the SVD one +print(C-X) +

      +
      +
      +
      +
      +
      +
      +
      +
      +
      +
      +
      +
      +
      + +

      The matrix \( \boldsymbol{X} \) has columns that are linearly dependent. The first +column is the row-wise sum of the other two columns. The rank of a +matrix (the column rank) is the dimension of space spanned by the +column vectors. The rank of the matrix is the number of linearly +independent columns, in this case just \( 2 \). We see this from the +singular values when running the above code. Running the standard +inversion algorithm for matrix inversion with \( \boldsymbol{X}^T\boldsymbol{X} \) results +in the program terminating due to a singular matrix.

      @@ -431,7 +470,7 @@ In general the economy-size SVD leads to less FLOPS and still conserving the des

    306. 53
    307. 54
    308. ...
    309. -
    310. 69
    311. +
    312. 68
    313. »
    314. diff --git a/doc/pub/week35/html/._week35-bs045.html b/doc/pub/week35/html/._week35-bs045.html index e56c72218..046d02f49 100644 --- a/doc/pub/week35/html/._week35-bs045.html +++ b/doc/pub/week35/html/._week35-bs045.html @@ -38,7 +38,6 @@ doconce format html week35.do.txt --html_style=bootstrap --pygments_html_style=d {'highest level': 2, 'sections': [('Plans for week 35', 2, None, 'plans-for-week-35'), ('Reading recommendations:', 3, None, 'reading-recommendations'), - ('Topics of week 35', 2, None, 'topics-of-week-35'), ('Why Linear Regression (aka Ordinary Least Squares and family), ' 'repeat from last week', 2, @@ -301,78 +300,77 @@ MathJax.Hub.Config({ @@ -384,67 +382,22 @@ MathJax.Hub.Config({

       

       

       

      -

      Codes for the SVD

      +

      Note about SVD Calculations

      +

      The \( U \), \( S \), and \( V \) matrices returned from the svd() function +cannot be multiplied directly. +

      - -
      -
      -
      -
      -
      -
      import numpy as np
      -# SVD inversion
      -def SVD(A):
      -    ''' Takes as input a numpy matrix A and returns inv(A) based on singular value decomposition (SVD).
      -    SVD is numerically more stable than the inversion algorithms provided by
      -    numpy and scipy.linalg at the cost of being slower.
      -    '''
      -    U, S, VT = np.linalg.svd(A,full_matrices=True)
      -    print('test U')
      -    print( (np.transpose(U) @ U - U @np.transpose(U)))
      -    print('test VT')
      -    print( (np.transpose(VT) @ VT - VT @np.transpose(VT)))
      -    print(U)
      -    print(S)
      -    print(VT)
      +

      As you can see from the code, the \( S \) vector must be converted into a +diagonal matrix. This may cause a problem as the size of the matrices +do not fit the rules of matrix multiplication, where the number of +columns in a matrix must match the number of rows in the subsequent +matrix. +

      - D = np.zeros((len(U),len(VT))) - for i in range(0,len(VT)): - D[i,i]=S[i] - return U @ D @ VT - - -X = np.array([ [1.0,-1.0], [1.0,-1.0]]) -#X = np.array([[1, 2], [3, 4], [5, 6]]) - -print(X) -C = SVD(X) -# Print the difference between the original matrix and the SVD one -print(C-X) -
      -
      -
      -
      -
      -
      -
      -
      -
      -
      -
      -
      -
      -
      - -

      The matrix \( \boldsymbol{X} \) has columns that are linearly dependent. The first -column is the row-wise sum of the other two columns. The rank of a -matrix (the column rank) is the dimension of space spanned by the -column vectors. The rank of the matrix is the number of linearly -independent columns, in this case just \( 2 \). We see this from the -singular values when running the above code. Running the standard -inversion algorithm for matrix inversion with \( \boldsymbol{X}^T\boldsymbol{X} \) results -in the program terminating due to a singular matrix. +

      If you wish to include the zero singular values, you will need to +resize the matrices and set up a diagonal matrix as done in the above +example

      @@ -472,7 +425,7 @@ in the program terminating due to a singular matrix.

    315. 54
    316. 55
    317. ...
    318. -
    319. 69
    320. +
    321. 68
    322. »
    323. diff --git a/doc/pub/week35/html/._week35-bs046.html b/doc/pub/week35/html/._week35-bs046.html index a93a9a37d..713a3e716 100644 --- a/doc/pub/week35/html/._week35-bs046.html +++ b/doc/pub/week35/html/._week35-bs046.html @@ -38,7 +38,6 @@ doconce format html week35.do.txt --html_style=bootstrap --pygments_html_style=d {'highest level': 2, 'sections': [('Plans for week 35', 2, None, 'plans-for-week-35'), ('Reading recommendations:', 3, None, 'reading-recommendations'), - ('Topics of week 35', 2, None, 'topics-of-week-35'), ('Why Linear Regression (aka Ordinary Least Squares and family), ' 'repeat from last week', 2, @@ -301,78 +300,77 @@ MathJax.Hub.Config({ @@ -384,23 +382,38 @@ MathJax.Hub.Config({

       

       

       

      -

      Note about SVD Calculations

      +

      Mathematics of the SVD and implications

      -

      The \( U \), \( S \), and \( V \) matrices returned from the svd() function -cannot be multiplied directly. -

      +

      Let us take a closer look at the mathematics of the SVD and the various implications for machine learning studies.

      -

      As you can see from the code, the \( S \) vector must be converted into a -diagonal matrix. This may cause a problem as the size of the matrices -do not fit the rules of matrix multiplication, where the number of -columns in a matrix must match the number of rows in the subsequent -matrix. -

      +

      Our starting point is our design matrix \( \boldsymbol{X} \) of dimension \( n\times p \)

      +$$ +\boldsymbol{X}=\begin{bmatrix} +x_{0,0} & x_{0,1} & x_{0,2}& \dots & \dots x_{0,p-1}\\ +x_{1,0} & x_{1,1} & x_{1,2}& \dots & \dots x_{1,p-1}\\ +x_{2,0} & x_{2,1} & x_{2,2}& \dots & \dots x_{2,p-1}\\ +\dots & \dots & \dots & \dots \dots & \dots \\ +x_{n-2,0} & x_{n-2,1} & x_{n-2,2}& \dots & \dots x_{n-2,p-1}\\ +x_{n-1,0} & x_{n-1,1} & x_{n-1,2}& \dots & \dots x_{n-1,p-1}\\ +\end{bmatrix}. +$$ -

      If you wish to include the zero singular values, you will need to -resize the matrices and set up a diagonal matrix as done in the above -example -

      +

      We can SVD decompose our matrix as

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

      where \( \boldsymbol{U} \) is an orthogonal matrix of dimension \( n\times n \), meaning that \( \boldsymbol{U}\boldsymbol{U}^T=\boldsymbol{U}^T\boldsymbol{U}=\boldsymbol{I}_n \). Here \( \boldsymbol{I}_n \) is the unit matrix of dimension \( n \times n \).

      + +

      Similarly, \( \boldsymbol{V} \) is an orthogonal matrix of dimension \( p\times p \), meaning that \( \boldsymbol{V}\boldsymbol{V}^T=\boldsymbol{V}^T\boldsymbol{V}=\boldsymbol{I}_p \). Here \( \boldsymbol{I}_n \) is the unit matrix of dimension \( p \times p \).

      + +

      Finally \( \boldsymbol{\Sigma} \) contains the singular values \( \sigma_i \). This matrix has dimension \( n\times p \) and the singular values \( \sigma_i \) are all positive. The non-zero values are ordered in descending order, that is

      + +$$ +\sigma_0 > \sigma_1 > \sigma_2 > \dots > \sigma_{p-1} > 0. +$$ + +

      All values beyond \( p-1 \) are all zero.

      @@ -427,7 +440,7 @@ example

    324. 55
    325. 56
    326. ...
    327. -
    328. 69
    329. +
    330. 68
    331. »
    332. diff --git a/doc/pub/week35/html/._week35-bs047.html b/doc/pub/week35/html/._week35-bs047.html index e313461d7..c089b6d2e 100644 --- a/doc/pub/week35/html/._week35-bs047.html +++ b/doc/pub/week35/html/._week35-bs047.html @@ -38,7 +38,6 @@ doconce format html week35.do.txt --html_style=bootstrap --pygments_html_style=d {'highest level': 2, 'sections': [('Plans for week 35', 2, None, 'plans-for-week-35'), ('Reading recommendations:', 3, None, 'reading-recommendations'), - ('Topics of week 35', 2, None, 'topics-of-week-35'), ('Why Linear Regression (aka Ordinary Least Squares and family), ' 'repeat from last week', 2, @@ -301,78 +300,77 @@ MathJax.Hub.Config({ @@ -384,38 +382,62 @@ MathJax.Hub.Config({

       

       

       

      -

      Mathematics of the SVD and implications

      +

      Example Matrix

      -

      Let us take a closer look at the mathematics of the SVD and the various implications for machine learning studies.

      - -

      Our starting point is our design matrix \( \boldsymbol{X} \) of dimension \( n\times p \)

      -$$ -\boldsymbol{X}=\begin{bmatrix} -x_{0,0} & x_{0,1} & x_{0,2}& \dots & \dots x_{0,p-1}\\ -x_{1,0} & x_{1,1} & x_{1,2}& \dots & \dots x_{1,p-1}\\ -x_{2,0} & x_{2,1} & x_{2,2}& \dots & \dots x_{2,p-1}\\ -\dots & \dots & \dots & \dots \dots & \dots \\ -x_{n-2,0} & x_{n-2,1} & x_{n-2,2}& \dots & \dots x_{n-2,p-1}\\ -x_{n-1,0} & x_{n-1,1} & x_{n-1,2}& \dots & \dots x_{n-1,p-1}\\ -\end{bmatrix}. -$$ - -

      We can SVD decompose our matrix as

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

      where \( \boldsymbol{U} \) is an orthogonal matrix of dimension \( n\times n \), meaning that \( \boldsymbol{U}\boldsymbol{U}^T=\boldsymbol{U}^T\boldsymbol{U}=\boldsymbol{I}_n \). Here \( \boldsymbol{I}_n \) is the unit matrix of dimension \( n \times n \).

      - -

      Similarly, \( \boldsymbol{V} \) is an orthogonal matrix of dimension \( p\times p \), meaning that \( \boldsymbol{V}\boldsymbol{V}^T=\boldsymbol{V}^T\boldsymbol{V}=\boldsymbol{I}_p \). Here \( \boldsymbol{I}_n \) is the unit matrix of dimension \( p \times p \).

      - -

      Finally \( \boldsymbol{\Sigma} \) contains the singular values \( \sigma_i \). This matrix has dimension \( n\times p \) and the singular values \( \sigma_i \) are all positive. The non-zero values are ordered in descending order, that is

      +

      As an example, consider the following \( 3\times 2 \) example for the matrix \( \boldsymbol{\Sigma} \)

      $$ -\sigma_0 > \sigma_1 > \sigma_2 > \dots > \sigma_{p-1} > 0. +\boldsymbol{\Sigma}= +\begin{bmatrix} +2& 0 \\ +0 & 1 \\ +0 & 0 \\ +\end{bmatrix} $$ -

      All values beyond \( p-1 \) are all zero.

      +

      The singular values are \( \sigma_0=2 \) and \( \sigma_1=1 \). It is common to rewrite the matrix \( \boldsymbol{\Sigma} \) as

      + +$$ +\boldsymbol{\Sigma}= +\begin{bmatrix} +\boldsymbol{\tilde{\Sigma}}\\ +\boldsymbol{0}\\ +\end{bmatrix}, +$$ + +

      where

      +$$ +\boldsymbol{\tilde{\Sigma}}= +\begin{bmatrix} +2& 0 \\ +0 & 1 \\ +\end{bmatrix}, +$$ + +

      contains only the singular values. Note also (and we will use this below) that

      + +$$ +\boldsymbol{\Sigma}^T\boldsymbol{\Sigma}= +\begin{bmatrix} +4& 0 \\ +0 & 1 \\ +\end{bmatrix}, +$$ + +

      which is a \( 2\times 2 \) matrix while

      +$$ +\boldsymbol{\Sigma}\boldsymbol{\Sigma}^T= +\begin{bmatrix} +4& 0 & 0\\ +0 & 1 & 0\\ +0 & 0 & 0\\ +\end{bmatrix}, +$$ + +

      is a \( 3\times 3 \) matrix. The last row and column of this last matrix +contain only zeros. This will have important consequences for our SVD +decomposition of the design matrix. +

      @@ -442,7 +464,7 @@ $$

    333. 56
    334. 57
    335. ...
    336. -
    337. 69
    338. +
    339. 68
    340. »
    341. diff --git a/doc/pub/week35/html/._week35-bs048.html b/doc/pub/week35/html/._week35-bs048.html index 4cf0eed5f..46d7cbb48 100644 --- a/doc/pub/week35/html/._week35-bs048.html +++ b/doc/pub/week35/html/._week35-bs048.html @@ -38,7 +38,6 @@ doconce format html week35.do.txt --html_style=bootstrap --pygments_html_style=d {'highest level': 2, 'sections': [('Plans for week 35', 2, None, 'plans-for-week-35'), ('Reading recommendations:', 3, None, 'reading-recommendations'), - ('Topics of week 35', 2, None, 'topics-of-week-35'), ('Why Linear Regression (aka Ordinary Least Squares and family), ' 'repeat from last week', 2, @@ -301,78 +300,77 @@ MathJax.Hub.Config({ @@ -384,61 +382,45 @@ MathJax.Hub.Config({

       

       

       

      -

      Example Matrix

      +

      Setting up the Matrix to be inverted

      -

      As an example, consider the following \( 3\times 2 \) example for the matrix \( \boldsymbol{\Sigma} \)

      +

      The matrix that may cause problems for us is \( \boldsymbol{X}^T\boldsymbol{X} \). Using the SVD we can rewrite this matrix as

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

      The singular values are \( \sigma_0=2 \) and \( \sigma_1=1 \). It is common to rewrite the matrix \( \boldsymbol{\Sigma} \) as

      +

      and using the orthogonality of the matrix \( \boldsymbol{U} \) we have

      $$ -\boldsymbol{\Sigma}= -\begin{bmatrix} -\boldsymbol{\tilde{\Sigma}}\\ -\boldsymbol{0}\\ -\end{bmatrix}, +\boldsymbol{X}^T\boldsymbol{X}=\boldsymbol{V}\boldsymbol{\Sigma}^T\boldsymbol{\Sigma}\boldsymbol{V}^T. $$ -

      where

      -$$ -\boldsymbol{\tilde{\Sigma}}= -\begin{bmatrix} -2& 0 \\ -0 & 1 \\ -\end{bmatrix}, -$$ +

      We define \( \boldsymbol{\Sigma}^T\boldsymbol{\Sigma}=\tilde{\boldsymbol{\Sigma}}^2 \) which is a diagonal matrix containing only the singular values squared. It has dimensionality \( p \times p \).

      -

      contains only the singular values. Note also (and we will use this below) that

      +

      We can now insert the result for the matrix \( \boldsymbol{X}^T\boldsymbol{X} \) into our equation for ordinary least squares where

      $$ -\boldsymbol{\Sigma}^T\boldsymbol{\Sigma}= -\begin{bmatrix} -4& 0 \\ -0 & 1 \\ -\end{bmatrix}, +\tilde{y}_{\mathrm{OLS}}=\boldsymbol{X}\left(\boldsymbol{X}^T\boldsymbol{X}\right)^{-1}\boldsymbol{X}^T\boldsymbol{y}, $$ -

      which is a \( 2\times 2 \) matrix while

      +

      and using our SVD decomposition of \( \boldsymbol{X} \) we have

      + $$ -\boldsymbol{\Sigma}\boldsymbol{\Sigma}^T= -\begin{bmatrix} -4& 0 & 0\\ -0 & 1 & 0\\ -0 & 0 & 0\\ -\end{bmatrix}, +\tilde{y}_{\mathrm{OLS}}=\boldsymbol{U}\boldsymbol{\Sigma}\boldsymbol{V}^T\left(\boldsymbol{V}\tilde{\boldsymbol{\Sigma}}^{2}(\boldsymbol{V}^T\right)^{-1}\boldsymbol{V}\boldsymbol{\Sigma}^T\boldsymbol{U}^T\boldsymbol{y}, $$ -

      is a \( 3\times 3 \) matrix. The last row and column of this last matrix -contain only zeros. This will have important consequences for our SVD -decomposition of the design matrix. +

      which gives us, using the orthogonality of the matrices \( \boldsymbol{U} \) and \( \boldsymbol{V} \),

      + +$$ +\tilde{y}_{\mathrm{OLS}}=\boldsymbol{U}\boldsymbol{U}^T\boldsymbol{y}=\sum_{i=0}^{p-1}\boldsymbol{u}_i\boldsymbol{u}^T_i\boldsymbol{y}, +$$ + +

      It means that the ordinary least square model (with the optimal +parameters) \( \boldsymbol{\tilde{y}} \), corresponds to an orthogonal +transformation of the output (or target) vector \( \boldsymbol{y} \) by the +vectors of the matrix \( \boldsymbol{U} \). Note that the summation ends at \( p-1 \), +that is \( \boldsymbol{\tilde{y}}\ne \boldsymbol{y} \).

      @@ -466,7 +448,7 @@ decomposition of the design matrix.

    342. 57
    343. 58
    344. ...
    345. -
    346. 69
    347. +
    348. 68
    349. »
    350. diff --git a/doc/pub/week35/html/._week35-bs049.html b/doc/pub/week35/html/._week35-bs049.html index b8c605c6c..59a199607 100644 --- a/doc/pub/week35/html/._week35-bs049.html +++ b/doc/pub/week35/html/._week35-bs049.html @@ -38,7 +38,6 @@ doconce format html week35.do.txt --html_style=bootstrap --pygments_html_style=d {'highest level': 2, 'sections': [('Plans for week 35', 2, None, 'plans-for-week-35'), ('Reading recommendations:', 3, None, 'reading-recommendations'), - ('Topics of week 35', 2, None, 'topics-of-week-35'), ('Why Linear Regression (aka Ordinary Least Squares and family), ' 'repeat from last week', 2, @@ -301,78 +300,77 @@ MathJax.Hub.Config({ @@ -384,45 +382,52 @@ MathJax.Hub.Config({

       

       

       

      -

      Setting up the Matrix to be inverted

      - -

      The matrix that may cause problems for us is \( \boldsymbol{X}^T\boldsymbol{X} \). Using the SVD we can rewrite this matrix as

      +

      Further properties (important for our analyses later)

      +

      Let us study again \( \boldsymbol{X}^T\boldsymbol{X} \) in terms of our SVD,

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

      and using the orthogonality of the matrix \( \boldsymbol{U} \) we have

      - +

      If we now multiply from the right with \( \boldsymbol{V} \) (using the orthogonality of \( \boldsymbol{V} \)) we get

      $$ -\boldsymbol{X}^T\boldsymbol{X}=\boldsymbol{V}\boldsymbol{\Sigma}^T\boldsymbol{\Sigma}\boldsymbol{V}^T. +\left(\boldsymbol{X}^T\boldsymbol{X}\right)\boldsymbol{V}=\boldsymbol{V}\boldsymbol{\Sigma}^T\boldsymbol{\Sigma}. $$ -

      We define \( \boldsymbol{\Sigma}^T\boldsymbol{\Sigma}=\tilde{\boldsymbol{\Sigma}}^2 \) which is a diagonal matrix containing only the singular values squared. It has dimensionality \( p \times p \).

      - -

      We can now insert the result for the matrix \( \boldsymbol{X}^T\boldsymbol{X} \) into our equation for ordinary least squares where

      - +

      This means the vectors \( \boldsymbol{v}_i \) of the orthogonal matrix \( \boldsymbol{V} \) are the eigenvectors of the matrix \( \boldsymbol{X}^T\boldsymbol{X} \) +with eigenvalues given by the singular values squared, that is +

      $$ -\tilde{y}_{\mathrm{OLS}}=\boldsymbol{X}\left(\boldsymbol{X}^T\boldsymbol{X}\right)^{-1}\boldsymbol{X}^T\boldsymbol{y}, +\left(\boldsymbol{X}^T\boldsymbol{X}\right)\boldsymbol{v}_i=\boldsymbol{v}_i\sigma_i^2. $$ -

      and using our SVD decomposition of \( \boldsymbol{X} \) we have

      - +

      Similarly, if we use the SVD decomposition for the matrix \( \boldsymbol{X}\boldsymbol{X}^T \), we have

      $$ -\tilde{y}_{\mathrm{OLS}}=\boldsymbol{U}\boldsymbol{\Sigma}\boldsymbol{V}^T\left(\boldsymbol{V}\tilde{\boldsymbol{\Sigma}}^{2}(\boldsymbol{V}^T\right)^{-1}\boldsymbol{V}\boldsymbol{\Sigma}^T\boldsymbol{U}^T\boldsymbol{y}, +\boldsymbol{X}\boldsymbol{X}^T=\boldsymbol{U}\boldsymbol{\Sigma}\boldsymbol{V}^T\boldsymbol{V}\boldsymbol{\Sigma}^T\boldsymbol{U}^T=\boldsymbol{U}\boldsymbol{\Sigma}\boldsymbol{\Sigma}^T\boldsymbol{U}^T. $$ -

      which gives us, using the orthogonality of the matrices \( \boldsymbol{U} \) and \( \boldsymbol{V} \),

      - +

      If we now multiply from the right with \( \boldsymbol{U} \) (using the orthogonality of \( \boldsymbol{U} \)) we get

      $$ -\tilde{y}_{\mathrm{OLS}}=\boldsymbol{U}\boldsymbol{U}^T\boldsymbol{y}=\sum_{i=0}^{p-1}\boldsymbol{u}_i\boldsymbol{u}^T_i\boldsymbol{y}, +\left(\boldsymbol{X}\boldsymbol{X}^T\right)\boldsymbol{U}=\boldsymbol{U}\boldsymbol{\Sigma}\boldsymbol{\Sigma}^T. $$ -

      It means that the ordinary least square model (with the optimal -parameters) \( \boldsymbol{\tilde{y}} \), corresponds to an orthogonal -transformation of the output (or target) vector \( \boldsymbol{y} \) by the -vectors of the matrix \( \boldsymbol{U} \). Note that the summation ends at \( p-1 \), -that is \( \boldsymbol{\tilde{y}}\ne \boldsymbol{y} \). +

      This means the vectors \( \boldsymbol{u}_i \) of the orthogonal matrix \( \boldsymbol{U} \) are the eigenvectors of the matrix \( \boldsymbol{X}\boldsymbol{X}^T \) +with eigenvalues given by the singular values squared, that is +

      +$$ +\left(\boldsymbol{X}\boldsymbol{X}^T\right)\boldsymbol{u}_i=\boldsymbol{u}_i\sigma_i^2. +$$ + +

      Important note: we have defined our design matrix \( \boldsymbol{X} \) to be an +\( n\times p \) matrix. In most supervised learning cases we have that \( n +\ge p \), and quite often we have \( n >> p \). For linear algebra based methods like ordinary least squares or Ridge regression, this leads to a matrix \( \boldsymbol{X}^T\boldsymbol{X} \) which is small and thereby easier to handle from a computational point of view (in terms of number of floating point operations). +

      + +

      In our lectures, the number of columns will +always refer to the number of features in our data set, while the +number of rows represents the number of data inputs. Note that in +other texts you may find the opposite notation. This has consequences +for the definition of for example the covariance matrix and its relation to the SVD.

      @@ -450,7 +455,7 @@ that is \( \boldsymbol{\tilde{y}}\ne \boldsymbol{y} \).

    351. 58
    352. 59
    353. ...
    354. -
    355. 69
    356. +
    357. 68
    358. »
    359. diff --git a/doc/pub/week35/html/._week35-bs050.html b/doc/pub/week35/html/._week35-bs050.html index 66add929b..b711a47bc 100644 --- a/doc/pub/week35/html/._week35-bs050.html +++ b/doc/pub/week35/html/._week35-bs050.html @@ -38,7 +38,6 @@ doconce format html week35.do.txt --html_style=bootstrap --pygments_html_style=d {'highest level': 2, 'sections': [('Plans for week 35', 2, None, 'plans-for-week-35'), ('Reading recommendations:', 3, None, 'reading-recommendations'), - ('Topics of week 35', 2, None, 'topics-of-week-35'), ('Why Linear Regression (aka Ordinary Least Squares and family), ' 'repeat from last week', 2, @@ -301,78 +300,77 @@ MathJax.Hub.Config({ @@ -384,52 +382,31 @@ MathJax.Hub.Config({

       

       

       

      -

      Further properties (important for our analyses later)

      +

      Meet the Covariance Matrix

      -

      Let us study again \( \boldsymbol{X}^T\boldsymbol{X} \) in terms of our SVD,

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

      Before we move on to a discussion of Ridge and Lasso regression, we want to show an important example of the above.

      -

      If we now multiply from the right with \( \boldsymbol{V} \) (using the orthogonality of \( \boldsymbol{V} \)) we get

      -$$ -\left(\boldsymbol{X}^T\boldsymbol{X}\right)\boldsymbol{V}=\boldsymbol{V}\boldsymbol{\Sigma}^T\boldsymbol{\Sigma}. -$$ - -

      This means the vectors \( \boldsymbol{v}_i \) of the orthogonal matrix \( \boldsymbol{V} \) are the eigenvectors of the matrix \( \boldsymbol{X}^T\boldsymbol{X} \) -with eigenvalues given by the singular values squared, that is -

      -$$ -\left(\boldsymbol{X}^T\boldsymbol{X}\right)\boldsymbol{v}_i=\boldsymbol{v}_i\sigma_i^2. -$$ - -

      Similarly, if we use the SVD decomposition for the matrix \( \boldsymbol{X}\boldsymbol{X}^T \), we have

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

      If we now multiply from the right with \( \boldsymbol{U} \) (using the orthogonality of \( \boldsymbol{U} \)) we get

      -$$ -\left(\boldsymbol{X}\boldsymbol{X}^T\right)\boldsymbol{U}=\boldsymbol{U}\boldsymbol{\Sigma}\boldsymbol{\Sigma}^T. -$$ - -

      This means the vectors \( \boldsymbol{u}_i \) of the orthogonal matrix \( \boldsymbol{U} \) are the eigenvectors of the matrix \( \boldsymbol{X}\boldsymbol{X}^T \) -with eigenvalues given by the singular values squared, that is -

      -$$ -\left(\boldsymbol{X}\boldsymbol{X}^T\right)\boldsymbol{u}_i=\boldsymbol{u}_i\sigma_i^2. -$$ - -

      Important note: we have defined our design matrix \( \boldsymbol{X} \) to be an -\( n\times p \) matrix. In most supervised learning cases we have that \( n -\ge p \), and quite often we have \( n >> p \). For linear algebra based methods like ordinary least squares or Ridge regression, this leads to a matrix \( \boldsymbol{X}^T\boldsymbol{X} \) which is small and thereby easier to handle from a computational point of view (in terms of number of floating point operations). +

      We have already noted that the matrix \( \boldsymbol{X}^T\boldsymbol{X} \) in ordinary +least squares is proportional to the second derivative of the cost +function, that is we have

      -

      In our lectures, the number of columns will -always refer to the number of features in our data set, while the -number of rows represents the number of data inputs. Note that in -other texts you may find the opposite notation. This has consequences -for the definition of for example the covariance matrix and its relation to the SVD. +$$ +\frac{\partial^2 C(\boldsymbol{\beta})}{\partial \boldsymbol{\beta}^T\partial \boldsymbol{\beta}} =\frac{2}{n}\boldsymbol{X}^T\boldsymbol{X}. +$$ + +

      This quantity defines was what is called the Hessian matrix (the second derivative of a function we want to optimize).

      + +

      The Hessian matrix plays an important role and is defined in this course as

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

      The Hessian matrix for ordinary least squares is also proportional to +the covariance matrix. This means also that we can use the SVD to find +the eigenvalues of the covariance matrix and the Hessian matrix in +terms of the singular values. Let us develop these arguments, as they will play an important role in our machine learning studies.

      @@ -457,7 +434,7 @@ for the definition of for example the covariance matrix and its relation to the

    360. 59
    361. 60
    362. ...
    363. -
    364. 69
    365. +
    366. 68
    367. »
    368. diff --git a/doc/pub/week35/html/._week35-bs051.html b/doc/pub/week35/html/._week35-bs051.html index 0a5131325..5678c23c3 100644 --- a/doc/pub/week35/html/._week35-bs051.html +++ b/doc/pub/week35/html/._week35-bs051.html @@ -38,7 +38,6 @@ doconce format html week35.do.txt --html_style=bootstrap --pygments_html_style=d {'highest level': 2, 'sections': [('Plans for week 35', 2, None, 'plans-for-week-35'), ('Reading recommendations:', 3, None, 'reading-recommendations'), - ('Topics of week 35', 2, None, 'topics-of-week-35'), ('Why Linear Regression (aka Ordinary Least Squares and family), ' 'repeat from last week', 2, @@ -301,78 +300,77 @@ MathJax.Hub.Config({ @@ -384,31 +382,46 @@ MathJax.Hub.Config({

       

       

       

      -

      Meet the Covariance Matrix

      +

      Introducing the Covariance and Correlation functions

      -

      Before we move on to a discussion of Ridge and Lasso regression, we want to show an important example of the above.

      - -

      We have already noted that the matrix \( \boldsymbol{X}^T\boldsymbol{X} \) in ordinary -least squares is proportional to the second derivative of the cost -function, that is we have +

      Before we discuss the link between for example Ridge regression and the singular value decomposition, we need to remind ourselves about +the definition of the covariance and the correlation function. These are quantities that play a central role in machine learning methods.

      +

      Suppose we have defined two vectors +\( \hat{x} \) and \( \hat{y} \) with \( n \) elements each. The covariance matrix \( \boldsymbol{C} \) is defined as +

      $$ -\frac{\partial^2 C(\boldsymbol{\beta})}{\partial \boldsymbol{\beta}^T\partial \boldsymbol{\beta}} =\frac{2}{n}\boldsymbol{X}^T\boldsymbol{X}. +\boldsymbol{C}[\boldsymbol{x},\boldsymbol{y}] = \begin{bmatrix} \mathrm{cov}[\boldsymbol{x},\boldsymbol{x}] & \mathrm{cov}[\boldsymbol{x},\boldsymbol{y}] \\ + \mathrm{cov}[\boldsymbol{y},\boldsymbol{x}] & \mathrm{cov}[\boldsymbol{y},\boldsymbol{y}] \\ + \end{bmatrix}, $$ -

      This quantity defines was what is called the Hessian matrix (the second derivative of a function we want to optimize).

      - -

      The Hessian matrix plays an important role and is defined in this course as

      - +

      where for example

      $$ -\boldsymbol{H}=\boldsymbol{X}^T\boldsymbol{X}. +\mathrm{cov}[\boldsymbol{x},\boldsymbol{y}] =\frac{1}{n} \sum_{i=0}^{n-1}(x_i- \overline{x})(y_i- \overline{y}). $$ -

      The Hessian matrix for ordinary least squares is also proportional to -the covariance matrix. This means also that we can use the SVD to find -the eigenvalues of the covariance matrix and the Hessian matrix in -terms of the singular values. Let us develop these arguments, as they will play an important role in our machine learning studies. +

      With this definition and recalling that the variance is defined as

      +$$ +\mathrm{var}[\boldsymbol{x}]=\frac{1}{n} \sum_{i=0}^{n-1}(x_i- \overline{x})^2, +$$ + +

      we can rewrite the covariance matrix as

      +$$ +\boldsymbol{C}[\boldsymbol{x},\boldsymbol{y}] = \begin{bmatrix} \mathrm{var}[\boldsymbol{x}] & \mathrm{cov}[\boldsymbol{x},\boldsymbol{y}] \\ + \mathrm{cov}[\boldsymbol{x},\boldsymbol{y}] & \mathrm{var}[\boldsymbol{y}] \\ + \end{bmatrix}. +$$ + +

      Note: we have used \( 1/n \) in the above definitions of the sample variance and covariance. We assume then that we can calculate the exact mean value. +What you will find in essentially all statistics texts are equations +with a factor \( 1/(n-1) \). This is called Bessel's correction. This +method corrects the bias in the estimation of the population variance +and covariance. It also partially corrects the bias in the estimation +of the population standard deviation. If you use a library like +Scikit-Learn or nunmpy's function calculate the covariance, this +quantity will be computed with a factor \( 1/(n-1) \).

      @@ -436,7 +449,7 @@ terms of the singular values. Let us develop these arguments, as they will pla

    369. 60
    370. 61
    371. ...
    372. -
    373. 69
    374. +
    375. 68
    376. »
    377. diff --git a/doc/pub/week35/html/._week35-bs052.html b/doc/pub/week35/html/._week35-bs052.html index 6d9ee9e8b..fd636c0fe 100644 --- a/doc/pub/week35/html/._week35-bs052.html +++ b/doc/pub/week35/html/._week35-bs052.html @@ -38,7 +38,6 @@ doconce format html week35.do.txt --html_style=bootstrap --pygments_html_style=d {'highest level': 2, 'sections': [('Plans for week 35', 2, None, 'plans-for-week-35'), ('Reading recommendations:', 3, None, 'reading-recommendations'), - ('Topics of week 35', 2, None, 'topics-of-week-35'), ('Why Linear Regression (aka Ordinary Least Squares and family), ' 'repeat from last week', 2, @@ -301,78 +300,77 @@ MathJax.Hub.Config({ @@ -384,47 +382,32 @@ MathJax.Hub.Config({

       

       

       

      -

      Introducing the Covariance and Correlation functions

      +

      Covariance and Correlation Matrix

      -

      Before we discuss the link between for example Ridge regression and the singular value decomposition, we need to remind ourselves about -the definition of the covariance and the correlation function. These are quantities that play a central role in machine learning methods. +

      The covariance takes values between zero and infinity and may thus +lead to problems with loss of numerical precision for particularly +large values. It is common to scale the covariance matrix by +introducing instead the correlation matrix defined via the so-called +correlation function

      -

      Suppose we have defined two vectors -\( \hat{x} \) and \( \hat{y} \) with \( n \) elements each. The covariance matrix \( \boldsymbol{C} \) is defined as -

      $$ -\boldsymbol{C}[\boldsymbol{x},\boldsymbol{y}] = \begin{bmatrix} \mathrm{cov}[\boldsymbol{x},\boldsymbol{x}] & \mathrm{cov}[\boldsymbol{x},\boldsymbol{y}] \\ - \mathrm{cov}[\boldsymbol{y},\boldsymbol{x}] & \mathrm{cov}[\boldsymbol{y},\boldsymbol{y}] \\ +\mathrm{corr}[\boldsymbol{x},\boldsymbol{y}]=\frac{\mathrm{cov}[\boldsymbol{x},\boldsymbol{y}]}{\sqrt{\mathrm{var}[\boldsymbol{x}] \mathrm{var}[\boldsymbol{y}]}}. +$$ + +

      The correlation function is then given by values \( \mathrm{corr}[\boldsymbol{x},\boldsymbol{y}] +\in [-1,1] \). This avoids eventual problems with too large values. We +can then define the correlation matrix for the two vectors \( \boldsymbol{x} \) +and \( \boldsymbol{y} \) as +

      + +$$ +\boldsymbol{K}[\boldsymbol{x},\boldsymbol{y}] = \begin{bmatrix} 1 & \mathrm{corr}[\boldsymbol{x},\boldsymbol{y}] \\ + \mathrm{corr}[\boldsymbol{y},\boldsymbol{x}] & 1 \\ \end{bmatrix}, $$ -

      where for example

      -$$ -\mathrm{cov}[\boldsymbol{x},\boldsymbol{y}] =\frac{1}{n} \sum_{i=0}^{n-1}(x_i- \overline{x})(y_i- \overline{y}). -$$ - -

      With this definition and recalling that the variance is defined as

      -$$ -\mathrm{var}[\boldsymbol{x}]=\frac{1}{n} \sum_{i=0}^{n-1}(x_i- \overline{x})^2, -$$ - -

      we can rewrite the covariance matrix as

      -$$ -\boldsymbol{C}[\boldsymbol{x},\boldsymbol{y}] = \begin{bmatrix} \mathrm{var}[\boldsymbol{x}] & \mathrm{cov}[\boldsymbol{x},\boldsymbol{y}] \\ - \mathrm{cov}[\boldsymbol{x},\boldsymbol{y}] & \mathrm{var}[\boldsymbol{y}] \\ - \end{bmatrix}. -$$ - -

      Note: we have used \( 1/n \) in the above definitions of the sample variance and covariance. We assume then that we can calculate the exact mean value. -What you will find in essentially all statistics texts are equations -with a factor \( 1/(n-1) \). This is called Bessel's correction. This -method corrects the bias in the estimation of the population variance -and covariance. It also partially corrects the bias in the estimation -of the population standard deviation. If you use a library like -Scikit-Learn or nunmpy's function calculate the covariance, this -quantity will be computed with a factor \( 1/(n-1) \). -

      +

      In the above example this is the function we constructed using pandas.

      @@ -451,7 +434,7 @@ quantity will be computed with a factor \( 1/(n-1) \).

    378. 61
    379. 62
    380. ...
    381. -
    382. 69
    383. +
    384. 68
    385. »
    386. diff --git a/doc/pub/week35/html/._week35-bs053.html b/doc/pub/week35/html/._week35-bs053.html index cad21d5b3..4edec9a76 100644 --- a/doc/pub/week35/html/._week35-bs053.html +++ b/doc/pub/week35/html/._week35-bs053.html @@ -38,7 +38,6 @@ doconce format html week35.do.txt --html_style=bootstrap --pygments_html_style=d {'highest level': 2, 'sections': [('Plans for week 35', 2, None, 'plans-for-week-35'), ('Reading recommendations:', 3, None, 'reading-recommendations'), - ('Topics of week 35', 2, None, 'topics-of-week-35'), ('Why Linear Regression (aka Ordinary Least Squares and family), ' 'repeat from last week', 2, @@ -301,78 +300,77 @@ MathJax.Hub.Config({ @@ -384,32 +382,65 @@ MathJax.Hub.Config({

       

       

       

      -

      Covariance and Correlation Matrix

      +

      Correlation Function and Design/Feature Matrix

      -

      The covariance takes values between zero and infinity and may thus -lead to problems with loss of numerical precision for particularly -large values. It is common to scale the covariance matrix by -introducing instead the correlation matrix defined via the so-called -correlation function +

      In our derivation of the various regression algorithms like Ordinary Least Squares or Ridge regression +we defined the design/feature matrix \( \boldsymbol{X} \) as

      $$ -\mathrm{corr}[\boldsymbol{x},\boldsymbol{y}]=\frac{\mathrm{cov}[\boldsymbol{x},\boldsymbol{y}]}{\sqrt{\mathrm{var}[\boldsymbol{x}] \mathrm{var}[\boldsymbol{y}]}}. +\boldsymbol{X}=\begin{bmatrix} +x_{0,0} & x_{0,1} & x_{0,2}& \dots & \dots x_{0,p-1}\\ +x_{1,0} & x_{1,1} & x_{1,2}& \dots & \dots x_{1,p-1}\\ +x_{2,0} & x_{2,1} & x_{2,2}& \dots & \dots x_{2,p-1}\\ +\dots & \dots & \dots & \dots \dots & \dots \\ +x_{n-2,0} & x_{n-2,1} & x_{n-2,2}& \dots & \dots x_{n-2,p-1}\\ +x_{n-1,0} & x_{n-1,1} & x_{n-1,2}& \dots & \dots x_{n-1,p-1}\\ +\end{bmatrix}, $$ -

      The correlation function is then given by values \( \mathrm{corr}[\boldsymbol{x},\boldsymbol{y}] -\in [-1,1] \). This avoids eventual problems with too large values. We -can then define the correlation matrix for the two vectors \( \boldsymbol{x} \) -and \( \boldsymbol{y} \) as +

      with \( \boldsymbol{X}\in {\mathbb{R}}^{n\times p} \), with the predictors/features \( p \) refering to the column numbers and the +entries \( n \) being the row elements. +We can rewrite the design/feature matrix in terms of its column vectors as +

      +$$ +\boldsymbol{X}=\begin{bmatrix} \boldsymbol{x}_0 & \boldsymbol{x}_1 & \boldsymbol{x}_2 & \dots & \dots & \boldsymbol{x}_{p-1}\end{bmatrix}, +$$ + +

      with a given vector

      +$$ +\boldsymbol{x}_i^T = \begin{bmatrix}x_{0,i} & x_{1,i} & x_{2,i}& \dots & \dots x_{n-1,i}\end{bmatrix}. +$$ + +

      With these definitions, we can now rewrite our \( 2\times 2 \) +correlation/covariance matrix in terms of a moe general design/feature +matrix \( \boldsymbol{X}\in {\mathbb{R}}^{n\times p} \). This leads to a \( p\times p \) +covariance matrix for the vectors \( \boldsymbol{x}_i \) with \( i=0,1,\dots,p-1 \)

      $$ -\boldsymbol{K}[\boldsymbol{x},\boldsymbol{y}] = \begin{bmatrix} 1 & \mathrm{corr}[\boldsymbol{x},\boldsymbol{y}] \\ - \mathrm{corr}[\boldsymbol{y},\boldsymbol{x}] & 1 \\ - \end{bmatrix}, +\boldsymbol{C}[\boldsymbol{x}] = \begin{bmatrix} +\mathrm{var}[\boldsymbol{x}_0] & \mathrm{cov}[\boldsymbol{x}_0,\boldsymbol{x}_1] & \mathrm{cov}[\boldsymbol{x}_0,\boldsymbol{x}_2] & \dots & \dots & \mathrm{cov}[\boldsymbol{x}_0,\boldsymbol{x}_{p-1}]\\ +\mathrm{cov}[\boldsymbol{x}_1,\boldsymbol{x}_0] & \mathrm{var}[\boldsymbol{x}_1] & \mathrm{cov}[\boldsymbol{x}_1,\boldsymbol{x}_2] & \dots & \dots & \mathrm{cov}[\boldsymbol{x}_1,\boldsymbol{x}_{p-1}]\\ +\mathrm{cov}[\boldsymbol{x}_2,\boldsymbol{x}_0] & \mathrm{cov}[\boldsymbol{x}_2,\boldsymbol{x}_1] & \mathrm{var}[\boldsymbol{x}_2] & \dots & \dots & \mathrm{cov}[\boldsymbol{x}_2,\boldsymbol{x}_{p-1}]\\ +\dots & \dots & \dots & \dots & \dots & \dots \\ +\dots & \dots & \dots & \dots & \dots & \dots \\ +\mathrm{cov}[\boldsymbol{x}_{p-1},\boldsymbol{x}_0] & \mathrm{cov}[\boldsymbol{x}_{p-1},\boldsymbol{x}_1] & \mathrm{cov}[\boldsymbol{x}_{p-1},\boldsymbol{x}_{2}] & \dots & \dots & \mathrm{var}[\boldsymbol{x}_{p-1}]\\ +\end{bmatrix}, +$$ + +

      and the correlation matrix

      +$$ +\boldsymbol{K}[\boldsymbol{x}] = \begin{bmatrix} +1 & \mathrm{corr}[\boldsymbol{x}_0,\boldsymbol{x}_1] & \mathrm{corr}[\boldsymbol{x}_0,\boldsymbol{x}_2] & \dots & \dots & \mathrm{corr}[\boldsymbol{x}_0,\boldsymbol{x}_{p-1}]\\ +\mathrm{corr}[\boldsymbol{x}_1,\boldsymbol{x}_0] & 1 & \mathrm{corr}[\boldsymbol{x}_1,\boldsymbol{x}_2] & \dots & \dots & \mathrm{corr}[\boldsymbol{x}_1,\boldsymbol{x}_{p-1}]\\ +\mathrm{corr}[\boldsymbol{x}_2,\boldsymbol{x}_0] & \mathrm{corr}[\boldsymbol{x}_2,\boldsymbol{x}_1] & 1 & \dots & \dots & \mathrm{corr}[\boldsymbol{x}_2,\boldsymbol{x}_{p-1}]\\ +\dots & \dots & \dots & \dots & \dots & \dots \\ +\dots & \dots & \dots & \dots & \dots & \dots \\ +\mathrm{corr}[\boldsymbol{x}_{p-1},\boldsymbol{x}_0] & \mathrm{corr}[\boldsymbol{x}_{p-1},\boldsymbol{x}_1] & \mathrm{corr}[\boldsymbol{x}_{p-1},\boldsymbol{x}_{2}] & \dots & \dots & 1\\ +\end{bmatrix}, $$ -

      In the above example this is the function we constructed using pandas.

      @@ -436,7 +467,7 @@ $$

    387. 62
    388. 63
    389. ...
    390. -
    391. 69
    392. +
    393. 68
    394. »
    395. diff --git a/doc/pub/week35/html/._week35-bs054.html b/doc/pub/week35/html/._week35-bs054.html index 274c95e41..595d32a0f 100644 --- a/doc/pub/week35/html/._week35-bs054.html +++ b/doc/pub/week35/html/._week35-bs054.html @@ -38,7 +38,6 @@ doconce format html week35.do.txt --html_style=bootstrap --pygments_html_style=d {'highest level': 2, 'sections': [('Plans for week 35', 2, None, 'plans-for-week-35'), ('Reading recommendations:', 3, None, 'reading-recommendations'), - ('Topics of week 35', 2, None, 'topics-of-week-35'), ('Why Linear Regression (aka Ordinary Least Squares and family), ' 'repeat from last week', 2, @@ -301,78 +300,77 @@ MathJax.Hub.Config({ @@ -384,64 +382,60 @@ MathJax.Hub.Config({

       

       

       

      -

      Correlation Function and Design/Feature Matrix

      +

      Covariance Matrix Examples

      -

      In our derivation of the various regression algorithms like Ordinary Least Squares or Ridge regression -we defined the design/feature matrix \( \boldsymbol{X} \) as +

      The Numpy function np.cov calculates the covariance elements using +the factor \( 1/(n-1) \) instead of \( 1/n \) since it assumes we do not have +the exact mean values. The following simple function uses the +np.vstack function which takes each vector of dimension \( 1\times n \) +and produces a \( 2\times n \) matrix \( \boldsymbol{W} \)

      +

      Note that this assumes you have the features as the rows, and the inputs as columns, that is

      $$ -\boldsymbol{X}=\begin{bmatrix} -x_{0,0} & x_{0,1} & x_{0,2}& \dots & \dots x_{0,p-1}\\ -x_{1,0} & x_{1,1} & x_{1,2}& \dots & \dots x_{1,p-1}\\ -x_{2,0} & x_{2,1} & x_{2,2}& \dots & \dots x_{2,p-1}\\ -\dots & \dots & \dots & \dots \dots & \dots \\ -x_{n-2,0} & x_{n-2,1} & x_{n-2,2}& \dots & \dots x_{n-2,p-1}\\ -x_{n-1,0} & x_{n-1,1} & x_{n-1,2}& \dots & \dots x_{n-1,p-1}\\ -\end{bmatrix}, +\boldsymbol{W} = \begin{bmatrix} x_0 & x_1 & x_2 & \dots & x_{n-2} & x_{n-1} \\ + y_0 & y_1 & y_2 & \dots & y_{n-2} & y_{n-1} \\ + \end{bmatrix}, $$ -

      with \( \boldsymbol{X}\in {\mathbb{R}}^{n\times p} \), with the predictors/features \( p \) refering to the column numbers and the -entries \( n \) being the row elements. -We can rewrite the design/feature matrix in terms of its column vectors as -

      -$$ -\boldsymbol{X}=\begin{bmatrix} \boldsymbol{x}_0 & \boldsymbol{x}_1 & \boldsymbol{x}_2 & \dots & \dots & \boldsymbol{x}_{p-1}\end{bmatrix}, -$$ - -

      with a given vector

      -$$ -\boldsymbol{x}_i^T = \begin{bmatrix}x_{0,i} & x_{1,i} & x_{2,i}& \dots & \dots x_{n-1,i}\end{bmatrix}. -$$ - -

      With these definitions, we can now rewrite our \( 2\times 2 \) -correlation/covariance matrix in terms of a moe general design/feature -matrix \( \boldsymbol{X}\in {\mathbb{R}}^{n\times p} \). This leads to a \( p\times p \) -covariance matrix for the vectors \( \boldsymbol{x}_i \) with \( i=0,1,\dots,p-1 \) +

      which in turn is converted into into the \( 2\times 2 \) covariance matrix +\( \boldsymbol{C} \) via the Numpy function np.cov(). We note that we can also calculate +the mean value of each set of samples \( \boldsymbol{x} \) etc using the Numpy +function np.mean(x). We can also extract the eigenvalues of the +covariance matrix through the np.linalg.eig() function.

      -$$ -\boldsymbol{C}[\boldsymbol{x}] = \begin{bmatrix} -\mathrm{var}[\boldsymbol{x}_0] & \mathrm{cov}[\boldsymbol{x}_0,\boldsymbol{x}_1] & \mathrm{cov}[\boldsymbol{x}_0,\boldsymbol{x}_2] & \dots & \dots & \mathrm{cov}[\boldsymbol{x}_0,\boldsymbol{x}_{p-1}]\\ -\mathrm{cov}[\boldsymbol{x}_1,\boldsymbol{x}_0] & \mathrm{var}[\boldsymbol{x}_1] & \mathrm{cov}[\boldsymbol{x}_1,\boldsymbol{x}_2] & \dots & \dots & \mathrm{cov}[\boldsymbol{x}_1,\boldsymbol{x}_{p-1}]\\ -\mathrm{cov}[\boldsymbol{x}_2,\boldsymbol{x}_0] & \mathrm{cov}[\boldsymbol{x}_2,\boldsymbol{x}_1] & \mathrm{var}[\boldsymbol{x}_2] & \dots & \dots & \mathrm{cov}[\boldsymbol{x}_2,\boldsymbol{x}_{p-1}]\\ -\dots & \dots & \dots & \dots & \dots & \dots \\ -\dots & \dots & \dots & \dots & \dots & \dots \\ -\mathrm{cov}[\boldsymbol{x}_{p-1},\boldsymbol{x}_0] & \mathrm{cov}[\boldsymbol{x}_{p-1},\boldsymbol{x}_1] & \mathrm{cov}[\boldsymbol{x}_{p-1},\boldsymbol{x}_{2}] & \dots & \dots & \mathrm{var}[\boldsymbol{x}_{p-1}]\\ -\end{bmatrix}, -$$ -

      and the correlation matrix

      -$$ -\boldsymbol{K}[\boldsymbol{x}] = \begin{bmatrix} -1 & \mathrm{corr}[\boldsymbol{x}_0,\boldsymbol{x}_1] & \mathrm{corr}[\boldsymbol{x}_0,\boldsymbol{x}_2] & \dots & \dots & \mathrm{corr}[\boldsymbol{x}_0,\boldsymbol{x}_{p-1}]\\ -\mathrm{corr}[\boldsymbol{x}_1,\boldsymbol{x}_0] & 1 & \mathrm{corr}[\boldsymbol{x}_1,\boldsymbol{x}_2] & \dots & \dots & \mathrm{corr}[\boldsymbol{x}_1,\boldsymbol{x}_{p-1}]\\ -\mathrm{corr}[\boldsymbol{x}_2,\boldsymbol{x}_0] & \mathrm{corr}[\boldsymbol{x}_2,\boldsymbol{x}_1] & 1 & \dots & \dots & \mathrm{corr}[\boldsymbol{x}_2,\boldsymbol{x}_{p-1}]\\ -\dots & \dots & \dots & \dots & \dots & \dots \\ -\dots & \dots & \dots & \dots & \dots & \dots \\ -\mathrm{corr}[\boldsymbol{x}_{p-1},\boldsymbol{x}_0] & \mathrm{corr}[\boldsymbol{x}_{p-1},\boldsymbol{x}_1] & \mathrm{corr}[\boldsymbol{x}_{p-1},\boldsymbol{x}_{2}] & \dots & \dots & 1\\ -\end{bmatrix}, -$$ + +
      +
      +
      +
      +
      +
      # Importing various packages
      +import numpy as np
      +n = 100
      +x = np.random.normal(size=n)
      +print(np.mean(x))
      +y = 4+3*x+np.random.normal(size=n)
      +print(np.mean(y))
      +W = np.vstack((x, y))
      +C = np.cov(W)
      +print(C)
      +
      +
      +
      +
      +
      +
      +
      +
      +
      +
      +
      +
      +
      +

      @@ -469,7 +463,7 @@ $$

    396. 63
    397. 64
    398. ...
    399. -
    400. 69
    401. +
    402. 68
    403. »
    404. diff --git a/doc/pub/week35/html/._week35-bs055.html b/doc/pub/week35/html/._week35-bs055.html index 93aaaeb24..bf3eee13e 100644 --- a/doc/pub/week35/html/._week35-bs055.html +++ b/doc/pub/week35/html/._week35-bs055.html @@ -38,7 +38,6 @@ doconce format html week35.do.txt --html_style=bootstrap --pygments_html_style=d {'highest level': 2, 'sections': [('Plans for week 35', 2, None, 'plans-for-week-35'), ('Reading recommendations:', 3, None, 'reading-recommendations'), - ('Topics of week 35', 2, None, 'topics-of-week-35'), ('Why Linear Regression (aka Ordinary Least Squares and family), ' 'repeat from last week', 2, @@ -301,78 +300,77 @@ MathJax.Hub.Config({ @@ -384,27 +382,13 @@ MathJax.Hub.Config({

       

       

       

      -

      Covariance Matrix Examples

      +

      Correlation Matrix

      -

      The Numpy function np.cov calculates the covariance elements using -the factor \( 1/(n-1) \) instead of \( 1/n \) since it assumes we do not have -the exact mean values. The following simple function uses the -np.vstack function which takes each vector of dimension \( 1\times n \) -and produces a \( 2\times n \) matrix \( \boldsymbol{W} \) -

      - -

      Note that this assumes you have the features as the rows, and the inputs as columns, that is

      -$$ -\boldsymbol{W} = \begin{bmatrix} x_0 & x_1 & x_2 & \dots & x_{n-2} & x_{n-1} \\ - y_0 & y_1 & y_2 & \dots & y_{n-2} & y_{n-1} \\ - \end{bmatrix}, -$$ - -

      which in turn is converted into into the \( 2\times 2 \) covariance matrix -\( \boldsymbol{C} \) via the Numpy function np.cov(). We note that we can also calculate -the mean value of each set of samples \( \boldsymbol{x} \) etc using the Numpy -function np.mean(x). We can also extract the eigenvalues of the -covariance matrix through the np.linalg.eig() function. +

      The previous example can be converted into the correlation matrix by +simply scaling the matrix elements with the variances. We should also +subtract the mean values for each column. This leads to the following +code which sets up the correlations matrix for the previous example in +a more brute force way. Here we scale the mean values for each column of the design matrix, calculate the relevant mean values and variances and then finally set up the \( 2\times 2 \) correlation matrix (since we have only two vectors).

      @@ -414,15 +398,26 @@ covariance matrix through the np.linalg.eig() function.
      -
      # Importing various packages
      -import numpy as np
      +  
      import numpy as np
       n = 100
      -x = np.random.normal(size=n)
      -print(np.mean(x))
      +# define two vectors                                                                                           
      +x = np.random.random(size=n)
       y = 4+3*x+np.random.normal(size=n)
      -print(np.mean(y))
      -W = np.vstack((x, y))
      -C = np.cov(W)
      +#scaling the x and y vectors                                                                                   
      +x = x - np.mean(x)
      +y = y - np.mean(y)
      +variance_x = np.sum(x@x)/n
      +variance_y = np.sum(y@y)/n
      +print(variance_x)
      +print(variance_y)
      +cov_xy = np.sum(x@y)/n
      +cov_xx = np.sum(x@x)/n
      +cov_yy = np.sum(y@y)/n
      +C = np.zeros((2,2))
      +C[0,0]= cov_xx/variance_x
      +C[1,1]= cov_yy/variance_y
      +C[0,1]= cov_xy/np.sqrt(variance_y*variance_x)
      +C[1,0]= C[0,1]
       print(C)
       
      @@ -439,6 +434,12 @@ C = np.c
      +

      We see that the matrix elements along the diagonal are one as they +should be and that the matrix is symmetric. Furthermore, diagonalizing +this matrix we easily see that it is a positive definite matrix. +

      + +

      The above procedure with numpy can be made more compact if we use pandas.

      @@ -465,7 +466,7 @@ C = np.c

    405. 64
    406. 65
    407. ...
    408. -
    409. 69
    410. +
    411. 68
    412. »
    413. diff --git a/doc/pub/week35/html/._week35-bs056.html b/doc/pub/week35/html/._week35-bs056.html index c0fc630df..4b6d548a3 100644 --- a/doc/pub/week35/html/._week35-bs056.html +++ b/doc/pub/week35/html/._week35-bs056.html @@ -38,7 +38,6 @@ doconce format html week35.do.txt --html_style=bootstrap --pygments_html_style=d {'highest level': 2, 'sections': [('Plans for week 35', 2, None, 'plans-for-week-35'), ('Reading recommendations:', 3, None, 'reading-recommendations'), - ('Topics of week 35', 2, None, 'topics-of-week-35'), ('Why Linear Regression (aka Ordinary Least Squares and family), ' 'repeat from last week', 2, @@ -301,78 +300,77 @@ MathJax.Hub.Config({ @@ -384,15 +382,9 @@ MathJax.Hub.Config({

       

       

       

      -

      Correlation Matrix

      - -

      The previous example can be converted into the correlation matrix by -simply scaling the matrix elements with the variances. We should also -subtract the mean values for each column. This leads to the following -code which sets up the correlations matrix for the previous example in -a more brute force way. Here we scale the mean values for each column of the design matrix, calculate the relevant mean values and variances and then finally set up the \( 2\times 2 \) correlation matrix (since we have only two vectors). -

      +

      Correlation Matrix with Pandas

      +

      We whow here how we can set up the correlation matrix using pandas, as done in this simple code

      @@ -401,26 +393,19 @@ a more brute force way. Here we scale the mean values for each column of the des
      import numpy as np
      -n = 100
      -# define two vectors                                                                                           
      -x = np.random.random(size=n)
      -y = 4+3*x+np.random.normal(size=n)
      -#scaling the x and y vectors                                                                                   
      +import pandas as pd
      +n = 10
      +x = np.random.normal(size=n)
       x = x - np.mean(x)
      +y = 4+3*x+np.random.normal(size=n)
       y = y - np.mean(y)
      -variance_x = np.sum(x@x)/n
      -variance_y = np.sum(y@y)/n
      -print(variance_x)
      -print(variance_y)
      -cov_xy = np.sum(x@y)/n
      -cov_xx = np.sum(x@x)/n
      -cov_yy = np.sum(y@y)/n
      -C = np.zeros((2,2))
      -C[0,0]= cov_xx/variance_x
      -C[1,1]= cov_yy/variance_y
      -C[0,1]= cov_xy/np.sqrt(variance_y*variance_x)
      -C[1,0]= C[0,1]
      -print(C)
      +# Note that we transpose the matrix in order to stay with our ordering n x p
      +X = (np.vstack((x, y))).T
      +print(X)
      +Xpd = pd.DataFrame(X)
      +print(Xpd)
      +correlation_matrix = Xpd.corr()
      +print(correlation_matrix)
       
      @@ -436,12 +421,7 @@ C[1,0]
      -

      We see that the matrix elements along the diagonal are one as they -should be and that the matrix is symmetric. Furthermore, diagonalizing -this matrix we easily see that it is a positive definite matrix. -

      - -

      The above procedure with numpy can be made more compact if we use pandas.

      +

      We expand this model to the Franke function discussed above.

      @@ -468,7 +448,7 @@ this matrix we easily see that it is a positive definite matrix.

    414. 65
    415. 66
    416. ...
    417. -
    418. 69
    419. +
    420. 68
    421. »
    422. diff --git a/doc/pub/week35/html/._week35-bs057.html b/doc/pub/week35/html/._week35-bs057.html index ad4cb064e..5fb43b876 100644 --- a/doc/pub/week35/html/._week35-bs057.html +++ b/doc/pub/week35/html/._week35-bs057.html @@ -38,7 +38,6 @@ doconce format html week35.do.txt --html_style=bootstrap --pygments_html_style=d {'highest level': 2, 'sections': [('Plans for week 35', 2, None, 'plans-for-week-35'), ('Reading recommendations:', 3, None, 'reading-recommendations'), - ('Topics of week 35', 2, None, 'topics-of-week-35'), ('Why Linear Regression (aka Ordinary Least Squares and family), ' 'repeat from last week', 2, @@ -301,78 +300,77 @@ MathJax.Hub.Config({ @@ -384,9 +382,8 @@ MathJax.Hub.Config({

       

       

       

      -

      Correlation Matrix with Pandas

      +

      Correlation Matrix with Pandas and the Franke function

      -

      We whow here how we can set up the correlation matrix using pandas, as done in this simple code

      @@ -394,20 +391,49 @@ MathJax.Hub.Config({
      -
      import numpy as np
      +  
      # Common imports
      +import numpy as np
       import pandas as pd
      -n = 10
      -x = np.random.normal(size=n)
      -x = x - np.mean(x)
      -y = 4+3*x+np.random.normal(size=n)
      -y = y - np.mean(y)
      -# Note that we transpose the matrix in order to stay with our ordering n x p
      -X = (np.vstack((x, y))).T
      -print(X)
      +
      +
      +def FrankeFunction(x,y):
      +	term1 = 0.75*np.exp(-(0.25*(9*x-2)**2) - 0.25*((9*y-2)**2))
      +	term2 = 0.75*np.exp(-((9*x+1)**2)/49.0 - 0.1*(9*y+1))
      +	term3 = 0.5*np.exp(-(9*x-7)**2/4.0 - 0.25*((9*y-3)**2))
      +	term4 = -0.2*np.exp(-(9*x-4)**2 - (9*y-7)**2)
      +	return term1 + term2 + term3 + term4
      +
      +
      +def create_X(x, y, n ):
      +	if len(x.shape) > 1:
      +		x = np.ravel(x)
      +		y = np.ravel(y)
      +
      +	N = len(x)
      +	l = int((n+1)*(n+2)/2)		# Number of elements in beta
      +	X = np.ones((N,l))
      +
      +	for i in range(1,n+1):
      +		q = int((i)*(i+1)/2)
      +		for k in range(i+1):
      +			X[:,q+k] = (x**(i-k))*(y**k)
      +
      +	return X
      +
      +
      +# Making meshgrid of datapoints and compute Franke's function
      +n = 4
      +N = 100
      +x = np.sort(np.random.uniform(0, 1, N))
      +y = np.sort(np.random.uniform(0, 1, N))
      +z = FrankeFunction(x, y)
      +X = create_X(x, y, n=n)    
      +
       Xpd = pd.DataFrame(X)
      -print(Xpd)
      -correlation_matrix = Xpd.corr()
      -print(correlation_matrix)
      +# subtract the mean values and set up the covariance matrix
      +Xpd = Xpd - Xpd.mean()
      +covariance_matrix = Xpd.cov()
      +print(covariance_matrix)
       
      @@ -423,7 +449,16 @@ correlation_matrix = Xpd= Xpd66
    423. 67
    424. ...
    425. -
    426. 69
    427. +
    428. 68
    429. »
    430. diff --git a/doc/pub/week35/html/._week35-bs058.html b/doc/pub/week35/html/._week35-bs058.html index 073ab3249..b42efbf7d 100644 --- a/doc/pub/week35/html/._week35-bs058.html +++ b/doc/pub/week35/html/._week35-bs058.html @@ -38,7 +38,6 @@ doconce format html week35.do.txt --html_style=bootstrap --pygments_html_style=d {'highest level': 2, 'sections': [('Plans for week 35', 2, None, 'plans-for-week-35'), ('Reading recommendations:', 3, None, 'reading-recommendations'), - ('Topics of week 35', 2, None, 'topics-of-week-35'), ('Why Linear Regression (aka Ordinary Least Squares and family), ' 'repeat from last week', 2, @@ -301,78 +300,77 @@ MathJax.Hub.Config({ @@ -384,83 +382,41 @@ MathJax.Hub.Config({

       

       

       

      -

      Correlation Matrix with Pandas and the Franke function

      +

      Rewriting the Covariance and/or Correlation Matrix

      +

      We can rewrite the covariance matrix in a more compact form in terms of the design/feature matrix \( \boldsymbol{X} \) as

      +$$ +\boldsymbol{C}[\boldsymbol{x}] = \frac{1}{n}\boldsymbol{X}^T\boldsymbol{X}= \mathbb{E}[\boldsymbol{X}^T\boldsymbol{X}]. +$$ - -
      -
      -
      -
      -
      -
      # Common imports
      -import numpy as np
      -import pandas as pd
      +

      To see this let us simply look at a design matrix \( \boldsymbol{X}\in {\mathbb{R}}^{2\times 2} \)

      +$$ +\boldsymbol{X}=\begin{bmatrix} +x_{00} & x_{01}\\ +x_{10} & x_{11}\\ +\end{bmatrix}=\begin{bmatrix} +\boldsymbol{x}_{0} & \boldsymbol{x}_{1}\\ +\end{bmatrix}. +$$ +

      If we then compute the expectation value (note the \( 1/n \) factor instead of \( 1/(n-1) \))

      +$$ +\mathbb{E}[\boldsymbol{X}^T\boldsymbol{X}] = \frac{1}{n}\boldsymbol{X}^T\boldsymbol{X}=\frac{1}{n}\begin{bmatrix} +x_{00}^2+x_{10}^2 & x_{00}x_{01}+x_{10}x_{11}\\ +x_{01}x_{00}+x_{11}x_{10} & x_{01}^2+x_{11}^2\\ +\end{bmatrix}, +$$ -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 +

      which is just

      +$$ +\boldsymbol{C}[\boldsymbol{x}_0,\boldsymbol{x}_1] = \boldsymbol{C}[\boldsymbol{x}]=\begin{bmatrix} \mathrm{var}[\boldsymbol{x}_0] & \mathrm{cov}[\boldsymbol{x}_0,\boldsymbol{x}_1] \\ + \mathrm{cov}[\boldsymbol{x}_1,\boldsymbol{x}_0] & \mathrm{var}[\boldsymbol{x}_1] \\ + \end{bmatrix}, +$$ +

      where we wrote $$\boldsymbol{C}[\boldsymbol{x}_0,\boldsymbol{x}_1] = \boldsymbol{C}[\boldsymbol{x}]$$ to indicate that this is the covariance of the vectors \( \boldsymbol{x} \) of the design/feature matrix \( \boldsymbol{X} \).

      -def create_X(x, y, n ): - if len(x.shape) > 1: - x = np.ravel(x) - y = np.ravel(y) - - N = len(x) - l = int((n+1)*(n+2)/2) # Number of elements in beta - X = np.ones((N,l)) - - for i in range(1,n+1): - q = int((i)*(i+1)/2) - for k in range(i+1): - X[:,q+k] = (x**(i-k))*(y**k) - - return X - - -# Making meshgrid of datapoints and compute Franke's function -n = 4 -N = 100 -x = np.sort(np.random.uniform(0, 1, N)) -y = np.sort(np.random.uniform(0, 1, N)) -z = FrankeFunction(x, y) -X = create_X(x, y, n=n) - -Xpd = pd.DataFrame(X) -# subtract the mean values and set up the covariance matrix -Xpd = Xpd - Xpd.mean() -covariance_matrix = Xpd.cov() -print(covariance_matrix) -
      -
      -
      -
      -
      -
      -
      -
      -
      -
      -
      -
      -
      -
      - -

      We note here that the covariance is zero for the first rows and -columns since all matrix elements in the design matrix were set to one -(we are fitting the function in terms of a polynomial of degree \( n \)). -

      - -

      This means that the variance for these elements will be zero and will -cause problems when we set up the correlation matrix. We can simply -drop these elements and construct a correlation -matrix without these elements. -

      +

      It is easy to generalize this to a matrix \( \boldsymbol{X}\in {\mathbb{R}}^{n\times p} \).

      @@ -486,8 +442,6 @@ matrix without these elements.

    431. 66
    432. 67
    433. 68
    434. -
    435. ...
    436. -
    437. 69
    438. »
    439. diff --git a/doc/pub/week35/html/._week35-bs059.html b/doc/pub/week35/html/._week35-bs059.html index 517e970f2..95d74cfd2 100644 --- a/doc/pub/week35/html/._week35-bs059.html +++ b/doc/pub/week35/html/._week35-bs059.html @@ -38,7 +38,6 @@ doconce format html week35.do.txt --html_style=bootstrap --pygments_html_style=d {'highest level': 2, 'sections': [('Plans for week 35', 2, None, 'plans-for-week-35'), ('Reading recommendations:', 3, None, 'reading-recommendations'), - ('Topics of week 35', 2, None, 'topics-of-week-35'), ('Why Linear Regression (aka Ordinary Least Squares and family), ' 'repeat from last week', 2, @@ -301,78 +300,77 @@ MathJax.Hub.Config({ @@ -384,41 +382,39 @@ MathJax.Hub.Config({

       

       

       

      -

      Rewriting the Covariance and/or Correlation Matrix

      +

      Linking with the SVD

      -

      We can rewrite the covariance matrix in a more compact form in terms of the design/feature matrix \( \boldsymbol{X} \) as

      +

      We saw earlier that

      $$ -\boldsymbol{C}[\boldsymbol{x}] = \frac{1}{n}\boldsymbol{X}^T\boldsymbol{X}= \mathbb{E}[\boldsymbol{X}^T\boldsymbol{X}]. +\boldsymbol{X}^T\boldsymbol{X}=\boldsymbol{V}\boldsymbol{\Sigma}^T\boldsymbol{U}^T\boldsymbol{U}\boldsymbol{\Sigma}\boldsymbol{V}^T=\boldsymbol{V}\boldsymbol{\Sigma}^T\boldsymbol{\Sigma}\boldsymbol{V}^T. $$ -

      To see this let us simply look at a design matrix \( \boldsymbol{X}\in {\mathbb{R}}^{2\times 2} \)

      +

      Since the matrices here have dimension \( p\times p \), with \( p \) corresponding to the singular values, we defined earlier the matrix

      $$ -\boldsymbol{X}=\begin{bmatrix} -x_{00} & x_{01}\\ -x_{10} & x_{11}\\ -\end{bmatrix}=\begin{bmatrix} -\boldsymbol{x}_{0} & \boldsymbol{x}_{1}\\ -\end{bmatrix}. +\boldsymbol{\Sigma}^T\boldsymbol{\Sigma} = \begin{bmatrix} \tilde{\boldsymbol{\Sigma}} & \boldsymbol{0}\\ \end{bmatrix}\begin{bmatrix} \tilde{\boldsymbol{\Sigma}} \\ \boldsymbol{0}\\ \end{bmatrix}, $$ -

      If we then compute the expectation value (note the \( 1/n \) factor instead of \( 1/(n-1) \))

      +

      where the tilde-matrix \( \tilde{\boldsymbol{\Sigma}} \) is a matrix of dimension \( p\times p \) containing only the singular values \( \sigma_i \), that is

      + $$ -\mathbb{E}[\boldsymbol{X}^T\boldsymbol{X}] = \frac{1}{n}\boldsymbol{X}^T\boldsymbol{X}=\frac{1}{n}\begin{bmatrix} -x_{00}^2+x_{10}^2 & x_{00}x_{01}+x_{10}x_{11}\\ -x_{01}x_{00}+x_{11}x_{10} & x_{01}^2+x_{11}^2\\ +\tilde{\boldsymbol{\Sigma}}=\begin{bmatrix} \sigma_0 & 0 & 0 & \dots & 0 & 0 \\ + 0 & \sigma_1 & 0 & \dots & 0 & 0 \\ + 0 & 0 & \sigma_2 & \dots & 0 & 0 \\ + 0 & 0 & 0 & \dots & \sigma_{p-2} & 0 \\ + 0 & 0 & 0 & \dots & 0 & \sigma_{p-1} \\ \end{bmatrix}, $$ -

      which is just

      +

      meaning we can write

      $$ -\boldsymbol{C}[\boldsymbol{x}_0,\boldsymbol{x}_1] = \boldsymbol{C}[\boldsymbol{x}]=\begin{bmatrix} \mathrm{var}[\boldsymbol{x}_0] & \mathrm{cov}[\boldsymbol{x}_0,\boldsymbol{x}_1] \\ - \mathrm{cov}[\boldsymbol{x}_1,\boldsymbol{x}_0] & \mathrm{var}[\boldsymbol{x}_1] \\ - \end{bmatrix}, +\boldsymbol{X}^T\boldsymbol{X}=\boldsymbol{V}\tilde{\boldsymbol{\Sigma}}^2\boldsymbol{V}^T. $$ -

      where we wrote $$\boldsymbol{C}[\boldsymbol{x}_0,\boldsymbol{x}_1] = \boldsymbol{C}[\boldsymbol{x}]$$ to indicate that this is the covariance of the vectors \( \boldsymbol{x} \) of the design/feature matrix \( \boldsymbol{X} \).

      +

      Multiplying from the right with \( \boldsymbol{V} \) (using the orthogonality of \( \boldsymbol{V} \)) we get

      +$$ +\left(\boldsymbol{X}^T\boldsymbol{X}\right)\boldsymbol{V}=\boldsymbol{V}\tilde{\boldsymbol{\Sigma}}^2. +$$ -

      It is easy to generalize this to a matrix \( \boldsymbol{X}\in {\mathbb{R}}^{n\times p} \).

      @@ -443,7 +439,6 @@ $$

    440. 66
    441. 67
    442. 68
    443. -
    444. 69
    445. »
    446. diff --git a/doc/pub/week35/html/._week35-bs060.html b/doc/pub/week35/html/._week35-bs060.html index a2ef024ba..831ac57e3 100644 --- a/doc/pub/week35/html/._week35-bs060.html +++ b/doc/pub/week35/html/._week35-bs060.html @@ -38,7 +38,6 @@ doconce format html week35.do.txt --html_style=bootstrap --pygments_html_style=d {'highest level': 2, 'sections': [('Plans for week 35', 2, None, 'plans-for-week-35'), ('Reading recommendations:', 3, None, 'reading-recommendations'), - ('Topics of week 35', 2, None, 'topics-of-week-35'), ('Why Linear Regression (aka Ordinary Least Squares and family), ' 'repeat from last week', 2, @@ -301,78 +300,77 @@ MathJax.Hub.Config({ @@ -384,39 +382,45 @@ MathJax.Hub.Config({

       

       

       

      -

      Linking with the SVD

      +

      What does it mean?

      -

      We saw earlier that

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

      Since the matrices here have dimension \( p\times p \), with \( p \) corresponding to the singular values, we defined earlier the matrix

      -$$ -\boldsymbol{\Sigma}^T\boldsymbol{\Sigma} = \begin{bmatrix} \tilde{\boldsymbol{\Sigma}} & \boldsymbol{0}\\ \end{bmatrix}\begin{bmatrix} \tilde{\boldsymbol{\Sigma}} \\ \boldsymbol{0}\\ \end{bmatrix}, -$$ - -

      where the tilde-matrix \( \tilde{\boldsymbol{\Sigma}} \) is a matrix of dimension \( p\times p \) containing only the singular values \( \sigma_i \), that is

      +

      This means the vectors \( \boldsymbol{v}_i \) of the orthogonal matrix \( \boldsymbol{V} \) +are the eigenvectors of the matrix \( \boldsymbol{X}^T\boldsymbol{X} \) with eigenvalues +given by the singular values squared, that is +

      $$ -\tilde{\boldsymbol{\Sigma}}=\begin{bmatrix} \sigma_0 & 0 & 0 & \dots & 0 & 0 \\ - 0 & \sigma_1 & 0 & \dots & 0 & 0 \\ - 0 & 0 & \sigma_2 & \dots & 0 & 0 \\ - 0 & 0 & 0 & \dots & \sigma_{p-2} & 0 \\ - 0 & 0 & 0 & \dots & 0 & \sigma_{p-1} \\ -\end{bmatrix}, +\left(\boldsymbol{X}^T\boldsymbol{X}\right)\boldsymbol{v}_i=\boldsymbol{v}_i\sigma_i^2. $$ -

      meaning we can write

      +

      In other words, each non-zero singular value of \( \boldsymbol{X} \) is a positive +square root of an eigenvalue of \( \boldsymbol{X}^T\boldsymbol{X} \). It means also that +the columns of \( \boldsymbol{V} \) are the eigenvectors of +\( \boldsymbol{X}^T\boldsymbol{X} \). Since we have ordered the singular values of +\( \boldsymbol{X} \) in a descending order, it means that the column vectors +\( \boldsymbol{v}_i \) are hierarchically ordered by how much correlation they +encode from the columns of \( \boldsymbol{X} \). +

      + +

      Note that these are also the eigenvectors and eigenvalues of the +Hessian matrix. +

      + +

      If we now recall the definition of the covariance matrix (not using +Bessel's correction) we have +

      + $$ -\boldsymbol{X}^T\boldsymbol{X}=\boldsymbol{V}\tilde{\boldsymbol{\Sigma}}^2\boldsymbol{V}^T. -$$ - -

      Multiplying from the right with \( \boldsymbol{V} \) (using the orthogonality of \( \boldsymbol{V} \)) we get

      -$$ -\left(\boldsymbol{X}^T\boldsymbol{X}\right)\boldsymbol{V}=\boldsymbol{V}\tilde{\boldsymbol{\Sigma}}^2. +\boldsymbol{C}[\boldsymbol{X}]=\frac{1}{n}\boldsymbol{X}^T\boldsymbol{X}, $$ +

      meaning that every squared non-singular value of \( \boldsymbol{X} \) divided by \( n \) ( +the number of samples) are the eigenvalues of the covariance +matrix. Every singular value of \( \boldsymbol{X} \) is thus a positive square +root of an eigenvalue of \( \boldsymbol{X}^T\boldsymbol{X} \). If the matrix \( \boldsymbol{X} \) is +self-adjoint, the singular values of \( \boldsymbol{X} \) are equal to the +absolute value of the eigenvalues of \( \boldsymbol{X} \). +

      @@ -440,7 +444,6 @@ $$

    447. 66
    448. 67
    449. 68
    450. -
    451. 69
    452. »
    453. diff --git a/doc/pub/week35/html/._week35-bs061.html b/doc/pub/week35/html/._week35-bs061.html index e46aea8a9..287982539 100644 --- a/doc/pub/week35/html/._week35-bs061.html +++ b/doc/pub/week35/html/._week35-bs061.html @@ -38,7 +38,6 @@ doconce format html week35.do.txt --html_style=bootstrap --pygments_html_style=d {'highest level': 2, 'sections': [('Plans for week 35', 2, None, 'plans-for-week-35'), ('Reading recommendations:', 3, None, 'reading-recommendations'), - ('Topics of week 35', 2, None, 'topics-of-week-35'), ('Why Linear Regression (aka Ordinary Least Squares and family), ' 'repeat from last week', 2, @@ -301,78 +300,77 @@ MathJax.Hub.Config({ @@ -384,44 +382,38 @@ MathJax.Hub.Config({

       

       

       

      -

      What does it mean?

      +

      And finally \( \boldsymbol{X}\boldsymbol{X}^T \)

      -

      This means the vectors \( \boldsymbol{v}_i \) of the orthogonal matrix \( \boldsymbol{V} \) -are the eigenvectors of the matrix \( \boldsymbol{X}^T\boldsymbol{X} \) with eigenvalues -given by the singular values squared, that is -

      +

      For \( \boldsymbol{X}\boldsymbol{X}^T \) we found

      $$ -\left(\boldsymbol{X}^T\boldsymbol{X}\right)\boldsymbol{v}_i=\boldsymbol{v}_i\sigma_i^2. +\boldsymbol{X}\boldsymbol{X}^T=\boldsymbol{U}\boldsymbol{\Sigma}\boldsymbol{V}^T\boldsymbol{V}\boldsymbol{\Sigma}^T\boldsymbol{U}^T=\boldsymbol{U}\boldsymbol{\Sigma}^T\boldsymbol{\Sigma}\boldsymbol{U}^T. $$ -

      In other words, each non-zero singular value of \( \boldsymbol{X} \) is a positive -square root of an eigenvalue of \( \boldsymbol{X}^T\boldsymbol{X} \). It means also that -the columns of \( \boldsymbol{V} \) are the eigenvectors of -\( \boldsymbol{X}^T\boldsymbol{X} \). Since we have ordered the singular values of -\( \boldsymbol{X} \) in a descending order, it means that the column vectors -\( \boldsymbol{v}_i \) are hierarchically ordered by how much correlation they -encode from the columns of \( \boldsymbol{X} \). -

      - -

      Note that these are also the eigenvectors and eigenvalues of the -Hessian matrix. -

      - -

      If we now recall the definition of the covariance matrix (not using -Bessel's correction) we have -

      - +

      Since the matrices here have dimension \( n\times n \), we have

      $$ -\boldsymbol{C}[\boldsymbol{X}]=\frac{1}{n}\boldsymbol{X}^T\boldsymbol{X}, +\boldsymbol{\Sigma}\boldsymbol{\Sigma}^T = \begin{bmatrix} \tilde{\boldsymbol{\Sigma}} \\ \boldsymbol{0}\\ \end{bmatrix}\begin{bmatrix} \tilde{\boldsymbol{\Sigma}} \boldsymbol{0}\\ \end{bmatrix}=\begin{bmatrix} \tilde{\boldsymbol{\Sigma}} & \boldsymbol{0} \\ \boldsymbol{0} & \boldsymbol{0}\\ \end{bmatrix}, $$ -

      meaning that every squared non-singular value of \( \boldsymbol{X} \) divided by \( n \) ( -the number of samples) are the eigenvalues of the covariance -matrix. Every singular value of \( \boldsymbol{X} \) is thus a positive square -root of an eigenvalue of \( \boldsymbol{X}^T\boldsymbol{X} \). If the matrix \( \boldsymbol{X} \) is -self-adjoint, the singular values of \( \boldsymbol{X} \) are equal to the -absolute value of the eigenvalues of \( \boldsymbol{X} \). +

      leading to

      +$$ +\boldsymbol{X}\boldsymbol{X}^T=\boldsymbol{U}\begin{bmatrix} \tilde{\boldsymbol{\Sigma}} & \boldsymbol{0} \\ \boldsymbol{0} & \boldsymbol{0}\\ \end{bmatrix}\boldsymbol{U}^T. +$$ + +

      Multiplying with \( \boldsymbol{U} \) from the right gives us the eigenvalue problem

      +$$ +(\boldsymbol{X}\boldsymbol{X}^T)\boldsymbol{U}=\boldsymbol{U}\begin{bmatrix} \tilde{\boldsymbol{\Sigma}} & \boldsymbol{0} \\ \boldsymbol{0} & \boldsymbol{0}\\ \end{bmatrix}. +$$ + +

      It means that the eigenvalues of \( \boldsymbol{X}\boldsymbol{X}^T \) are again given by +the non-zero singular values plus now a series of zeros. The column +vectors of \( \boldsymbol{U} \) are the eigenvectors of \( \boldsymbol{X}\boldsymbol{X}^T \) and +measure how much correlations are contained in the rows of \( \boldsymbol{X} \). +

      + +

      Since we will mainly be interested in the correlations among the features +of our data (the columns of \( \boldsymbol{X} \), the quantity of interest for us are the non-zero singular +values and the column vectors of \( \boldsymbol{V} \).

      @@ -445,7 +437,6 @@ absolute value of the eigenvalues of \( \boldsymbol{X} \).

    454. 66
    455. 67
    456. 68
    457. -
    458. 69
    459. »
    460. diff --git a/doc/pub/week35/html/._week35-bs062.html b/doc/pub/week35/html/._week35-bs062.html index 8072dfad4..e8b14ac05 100644 --- a/doc/pub/week35/html/._week35-bs062.html +++ b/doc/pub/week35/html/._week35-bs062.html @@ -38,7 +38,6 @@ doconce format html week35.do.txt --html_style=bootstrap --pygments_html_style=d {'highest level': 2, 'sections': [('Plans for week 35', 2, None, 'plans-for-week-35'), ('Reading recommendations:', 3, None, 'reading-recommendations'), - ('Topics of week 35', 2, None, 'topics-of-week-35'), ('Why Linear Regression (aka Ordinary Least Squares and family), ' 'repeat from last week', 2, @@ -301,78 +300,77 @@ MathJax.Hub.Config({ @@ -384,40 +382,60 @@ MathJax.Hub.Config({

       

       

       

      -

      And finally \( \boldsymbol{X}\boldsymbol{X}^T \)

      - -

      For \( \boldsymbol{X}\boldsymbol{X}^T \) we found

      +

      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 +

      $$ -\boldsymbol{X}\boldsymbol{X}^T=\boldsymbol{U}\boldsymbol{\Sigma}\boldsymbol{V}^T\boldsymbol{V}\boldsymbol{\Sigma}^T\boldsymbol{U}^T=\boldsymbol{U}\boldsymbol{\Sigma}^T\boldsymbol{\Sigma}\boldsymbol{U}^T. +{\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\}. $$ -

      Since the matrices here have dimension \( n\times n \), we have

      +

      or we can state it as

      $$ -\boldsymbol{\Sigma}\boldsymbol{\Sigma}^T = \begin{bmatrix} \tilde{\boldsymbol{\Sigma}} \\ \boldsymbol{0}\\ \end{bmatrix}\begin{bmatrix} \tilde{\boldsymbol{\Sigma}} \boldsymbol{0}\\ \end{bmatrix}=\begin{bmatrix} \tilde{\boldsymbol{\Sigma}} & \boldsymbol{0} \\ \boldsymbol{0} & \boldsymbol{0}\\ \end{bmatrix}, +{\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, $$ -

      leading to

      +

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

      $$ -\boldsymbol{X}\boldsymbol{X}^T=\boldsymbol{U}\begin{bmatrix} \tilde{\boldsymbol{\Sigma}} & \boldsymbol{0} \\ \boldsymbol{0} & \boldsymbol{0}\\ \end{bmatrix}\boldsymbol{U}^T. +\vert\vert \boldsymbol{x}\vert\vert_2 = \sqrt{\sum_i x_i^2}. $$ -

      Multiplying with \( \boldsymbol{U} \) from the right gives us the eigenvalue problem

      -$$ -(\boldsymbol{X}\boldsymbol{X}^T)\boldsymbol{U}=\boldsymbol{U}\begin{bmatrix} \tilde{\boldsymbol{\Sigma}} & \boldsymbol{0} \\ \boldsymbol{0} & \boldsymbol{0}\\ \end{bmatrix}. -$$ - -

      It means that the eigenvalues of \( \boldsymbol{X}\boldsymbol{X}^T \) are again given by -the non-zero singular values plus now a series of zeros. The column -vectors of \( \boldsymbol{U} \) are the eigenvectors of \( \boldsymbol{X}\boldsymbol{X}^T \) and -measure how much correlations are contained in the rows of \( \boldsymbol{X} \). +

      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

      -

      Since we will mainly be interested in the correlations among the features -of our data (the columns of \( \boldsymbol{X} \), the quantity of interest for us are the non-zero singular -values and the column vectors of \( \boldsymbol{V} \). +$$ +{\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. +$$ + +

        @@ -438,7 +456,6 @@ values and the column vectors of \( \boldsymbol{V} \).
      • 66
      • 67
      • 68
      • -
      • 69
      • »
      diff --git a/doc/pub/week35/html/._week35-bs063.html b/doc/pub/week35/html/._week35-bs063.html index 5866d0cfb..ccf414d14 100644 --- a/doc/pub/week35/html/._week35-bs063.html +++ b/doc/pub/week35/html/._week35-bs063.html @@ -38,7 +38,6 @@ doconce format html week35.do.txt --html_style=bootstrap --pygments_html_style=d {'highest level': 2, 'sections': [('Plans for week 35', 2, None, 'plans-for-week-35'), ('Reading recommendations:', 3, None, 'reading-recommendations'), - ('Topics of week 35', 2, None, 'topics-of-week-35'), ('Why Linear Regression (aka Ordinary Least Squares and family), ' 'repeat from last week', 2, @@ -301,78 +300,77 @@ MathJax.Hub.Config({ @@ -384,59 +382,67 @@ MathJax.Hub.Config({

       

       

       

      -

      Ridge and LASSO Regression

      +

      Deriving the Ridge Regression Equations

      -

      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 +

      Using the matrix-vector expression for Ridge regression and dropping the parameter \( 1/n \) in front of the standard means squared error equation, we have

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

      and +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 +the optimal parameters

      $$ -{\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\}. +\hat{\boldsymbol{\beta}}_{\mathrm{Ridge}} = \left(\boldsymbol{X}^T\boldsymbol{X}+\lambda\boldsymbol{I}\right)^{-1}\boldsymbol{X}^T\boldsymbol{y}, $$ -

      or we can state it as

      +

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

      + $$ -{\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, +\sum_{i=0}^{p-1} \beta_i^2 \leq t, $$ -

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

      +

      with \( t \) a finite positive number.

      + +

      If we keep the \( 1/n \) factor, the equation for the optimal \( \beta \) changes to

      $$ -\vert\vert \boldsymbol{x}\vert\vert_2 = \sqrt{\sum_i x_i^2}. +\hat{\boldsymbol{\beta}}_{\mathrm{Ridge}} = \left(\boldsymbol{X}^T\boldsymbol{X}+n\lambda\boldsymbol{I}\right)^{-1}\boldsymbol{X}^T\boldsymbol{y}. $$ -

      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 +

      In many textbooks the \( 1/n \) term is often omitted. Note that a library like Scikit-Learn does not include the \( 1/n \) factor in the setup of the cost function.

      + +

      When we compare this with the ordinary least squares result we have

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

      which can lead to singular matrices. However, with the SVD, we can always compute the inverse of the matrix \( \boldsymbol{X}^T\boldsymbol{X} \).

      + +

      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 tradeoff are rather +interesting. We will see that for specific values of \( \lambda \), we may +even reduce the variance of the optimal parameters \( \boldsymbol{\beta} \). These topics and other related ones, will be discussed after the more linear algebra oriented analysis here.

      -$$ -{\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 +

      Using our insights about the SVD of the design matrix \( \boldsymbol{X} \) +We have already analyzed the OLS solutions in terms of the eigenvectors (the columns) of the right singular value matrix \( \boldsymbol{U} \) as

      - $$ -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, +\tilde{\boldsymbol{y}}_{\mathrm{OLS}}=\boldsymbol{X}\boldsymbol{\beta} =\boldsymbol{U}\boldsymbol{U}^T\boldsymbol{y}. $$ -

      we have a new optimization equation

      +

      For Ridge regression this becomes

      + $$ -{\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. +\tilde{\boldsymbol{y}}_{\mathrm{Ridge}}=\boldsymbol{X}\boldsymbol{\beta}_{\mathrm{Ridge}} = \boldsymbol{U\Sigma V^T}\left(\boldsymbol{V}\boldsymbol{\Sigma}^2\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} \) from the SVD of the matrix \( \boldsymbol{X} \).

      @@ -457,7 +463,6 @@ $$

    461. 66
    462. 67
    463. 68
    464. -
    465. 69
    466. »
    467. diff --git a/doc/pub/week35/html/._week35-bs064.html b/doc/pub/week35/html/._week35-bs064.html index 95311150d..750f36254 100644 --- a/doc/pub/week35/html/._week35-bs064.html +++ b/doc/pub/week35/html/._week35-bs064.html @@ -38,7 +38,6 @@ doconce format html week35.do.txt --html_style=bootstrap --pygments_html_style=d {'highest level': 2, 'sections': [('Plans for week 35', 2, None, 'plans-for-week-35'), ('Reading recommendations:', 3, None, 'reading-recommendations'), - ('Topics of week 35', 2, None, 'topics-of-week-35'), ('Why Linear Regression (aka Ordinary Least Squares and family), ' 'repeat from last week', 2, @@ -301,78 +300,77 @@ MathJax.Hub.Config({ @@ -384,67 +382,22 @@ MathJax.Hub.Config({

       

       

       

      -

      Deriving the Ridge Regression Equations

      +

      Interpreting the Ridge results

      -

      Using the matrix-vector expression for Ridge regression and dropping the parameter \( 1/n \) in front of the standard means squared error equation, we have

      +

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

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

      and -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 -the optimal parameters -

      -$$ -\hat{\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.

      - -

      If we keep the \( 1/n \) factor, the equation for the optimal \( \beta \) changes to

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

      In many textbooks the \( 1/n \) term is often omitted. Note that a library like Scikit-Learn does not include the \( 1/n \) factor in the setup of the cost function.

      - -

      When we compare this with the ordinary least squares result we have

      -$$ -\hat{\boldsymbol{\beta}}_{\mathrm{OLS}} = \left(\boldsymbol{X}^T\boldsymbol{X}\right)^{-1}\boldsymbol{X}^T\boldsymbol{y}, -$$ - -

      which can lead to singular matrices. However, with the SVD, we can always compute the inverse of the matrix \( \boldsymbol{X}^T\boldsymbol{X} \).

      - -

      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 tradeoff are rather -interesting. We will see that for specific values of \( \lambda \), we may -even reduce the variance of the optimal parameters \( \boldsymbol{\beta} \). These topics and other related ones, will be discussed after the more linear algebra oriented analysis here. +

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

      -

      Using our insights about the SVD of the design matrix \( \boldsymbol{X} \) -We have already analyzed the OLS solutions in terms of the eigenvectors (the columns) of the right singular value matrix \( \boldsymbol{U} \) as -

      -$$ -\tilde{\boldsymbol{y}}_{\mathrm{OLS}}=\boldsymbol{X}\boldsymbol{\beta} =\boldsymbol{U}\boldsymbol{U}^T\boldsymbol{y}. -$$ - -

      For Ridge regression this becomes

      - -$$ -\tilde{\boldsymbol{y}}_{\mathrm{Ridge}}=\boldsymbol{X}\boldsymbol{\beta}_{\mathrm{Ridge}} = \boldsymbol{U\Sigma V^T}\left(\boldsymbol{V}\boldsymbol{\Sigma}^2\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} \) from the SVD of the matrix \( \boldsymbol{X} \).

      +

      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. More about this when we have covered the material on a statistical interpretation of various linear regression methods.

      @@ -464,7 +417,6 @@ $$

    468. 66
    469. 67
    470. 68
    471. -
    472. 69
    473. »
    474. diff --git a/doc/pub/week35/html/._week35-bs065.html b/doc/pub/week35/html/._week35-bs065.html index 372e31f82..6b58f2d3a 100644 --- a/doc/pub/week35/html/._week35-bs065.html +++ b/doc/pub/week35/html/._week35-bs065.html @@ -38,7 +38,6 @@ doconce format html week35.do.txt --html_style=bootstrap --pygments_html_style=d {'highest level': 2, 'sections': [('Plans for week 35', 2, None, 'plans-for-week-35'), ('Reading recommendations:', 3, None, 'reading-recommendations'), - ('Topics of week 35', 2, None, 'topics-of-week-35'), ('Why Linear Regression (aka Ordinary Least Squares and family), ' 'repeat from last week', 2, @@ -301,78 +300,77 @@ MathJax.Hub.Config({ @@ -384,22 +382,35 @@ MathJax.Hub.Config({

       

       

       

      -

      Interpreting the Ridge results

      +

      More interpretations

      -

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

      +

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

      $$ -\frac{\sigma_j^2}{\sigma_j^2+\lambda} \leq 1. +\boldsymbol{X}^T\boldsymbol{X}=(\boldsymbol{X}^T\boldsymbol{X})^{-1} =\boldsymbol{I}. $$ -

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

      In this case the standard OLS results in

      +$$ +\boldsymbol{\beta}^{\mathrm{OLS}} = \boldsymbol{X}^T\boldsymbol{y}=\sum_{i=0}^{n-1}\boldsymbol{u}_i\boldsymbol{u}_i^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.

      -

      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. More about this when we have covered the material on a statistical interpretation of various linear regression methods.

      +

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

      @@ -418,7 +429,6 @@ eigenvalues ordered in a descending way, that is \( \sigma_i \geq

    475. 66
    476. 67
    477. 68
    478. -
    479. 69
    480. »
    481. diff --git a/doc/pub/week35/html/._week35-bs066.html b/doc/pub/week35/html/._week35-bs066.html index c084647bb..e40cdc4ae 100644 --- a/doc/pub/week35/html/._week35-bs066.html +++ b/doc/pub/week35/html/._week35-bs066.html @@ -38,7 +38,6 @@ doconce format html week35.do.txt --html_style=bootstrap --pygments_html_style=d {'highest level': 2, 'sections': [('Plans for week 35', 2, None, 'plans-for-week-35'), ('Reading recommendations:', 3, None, 'reading-recommendations'), - ('Topics of week 35', 2, None, 'topics-of-week-35'), ('Why Linear Regression (aka Ordinary Least Squares and family), ' 'repeat from last week', 2, @@ -301,78 +300,77 @@ MathJax.Hub.Config({ @@ -384,35 +382,31 @@ MathJax.Hub.Config({

       

       

       

      -

      More interpretations

      +

      Deriving the Lasso Regression Equations

      -

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

      +

      Using the matrix-vector expression for Lasso regression and dropping the parameter \( 1/n \) in front of the standard means squared error equation, we have the following cost function

      $$ -\boldsymbol{X}^T\boldsymbol{X}=(\boldsymbol{X}^T\boldsymbol{X})^{-1} =\boldsymbol{I}. +C(\boldsymbol{X},\boldsymbol{\beta})=\left\{(\boldsymbol{y}-\boldsymbol{X}\boldsymbol{\beta})^T(\boldsymbol{y}-\boldsymbol{X}\boldsymbol{\beta})\right\}+\lambda\vert\vert\boldsymbol{\beta}\vert\vert_1, $$ -

      In this case the standard OLS results in

      +

      Taking the derivative with respect to \( \boldsymbol{\beta} \) and recalling that the derivative of the absolute value is (we drop the boldfaced vector symbol for simplicty)

      $$ -\boldsymbol{\beta}^{\mathrm{OLS}} = \boldsymbol{X}^T\boldsymbol{y}=\sum_{i=0}^{n-1}\boldsymbol{u}_i\boldsymbol{u}_i^T\boldsymbol{y}, +\frac{d \vert \beta\vert}{d \boldsymbol{\beta}}=\mathrm{sgn}(\boldsymbol{\beta})=\left\{\begin{array}{cc} 1 & \beta > 0 \\-1 & \beta < 0, \end{array}\right. $$ -

      and

      +

      we have that the derivative of the cost function is

      $$ -\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}}, +\frac{\partial C(\boldsymbol{X},\boldsymbol{\beta})}{\partial \boldsymbol{\beta}}=-2\boldsymbol{X}^T(\boldsymbol{y}-\boldsymbol{X}\boldsymbol{\beta})+\lambda sgn(\boldsymbol{\beta})=0, $$ -

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

      +

      and reordering we have

      +$$ +\boldsymbol{X}^T\boldsymbol{X}\boldsymbol{\beta}+\lambda sgn(\boldsymbol{\beta})=2\boldsymbol{X}^T\boldsymbol{y}. +$$ -

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

      +

      This equation does not lead to a nice analytical equation as in either Ridge regression or ordinary least squares. This equation can however be solved by using standard convex optimization algorithms using for example the Python package CVXOPT. We will discuss this later.

      @@ -430,7 +424,6 @@ Similarly, Mehta et al

    482. 66
    483. 67
    484. 68
    485. -
    486. 69
    487. »
    488. diff --git a/doc/pub/week35/html/._week35-bs067.html b/doc/pub/week35/html/._week35-bs067.html index 37654e43c..fe1b686be 100644 --- a/doc/pub/week35/html/._week35-bs067.html +++ b/doc/pub/week35/html/._week35-bs067.html @@ -38,7 +38,6 @@ doconce format html week35.do.txt --html_style=bootstrap --pygments_html_style=d {'highest level': 2, 'sections': [('Plans for week 35', 2, None, 'plans-for-week-35'), ('Reading recommendations:', 3, None, 'reading-recommendations'), - ('Topics of week 35', 2, None, 'topics-of-week-35'), ('Why Linear Regression (aka Ordinary Least Squares and family), ' 'repeat from last week', 2, @@ -301,78 +300,77 @@ MathJax.Hub.Config({ @@ -384,32 +382,610 @@ MathJax.Hub.Config({

       

       

       

      -

      Deriving the Lasso Regression Equations

      +

      Exercises for week 35

      -

      Using the matrix-vector expression for Lasso regression and dropping the parameter \( 1/n \) in front of the standard means squared error equation, we have the following cost function

      +

      The exercises here are meant to prepare you for work with project 1. The first exercise is a follow-up of exercise 2 from week 35 August 30-September 3).

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

      Exercise 1: Setting up various Python environments

      + +

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

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

      We will make extensive use of Python as programming language and its +myriad of available libraries. You will find +IPython/Jupyter notebooks invaluable in your work. You can run R +codes in the Jupyter/IPython notebooks, with the immediate benefit of +visualizing your data. You can also use compiled languages like C++, +Rust, Fortran etc if you prefer. The focus in these lectures will be +on Python. +

      + +

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

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

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

      + +

      We will come back to tensorflow later.

      + +

      For Python3, replace pip with pip3.

      + +

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

      + +
        +
      1. brew install python3
      2. +
      +

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

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

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

      + + +

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

      + + +

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

      + +

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

      + + + + +

      Exercise 2: making your own data and exploring scikit-learn

      + +

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

      + + +
      +
      +
      +
      +
      +
      x = np.random.rand(100,1)
      +y = 2.0+5*x*x+0.1*np.random.randn(100,1)
      +
      +
      +
      +
      +
      +
      +
      +
      +
      +
      +
      +
      +
      +
      + + +
        +
      1. Write your own code (following the examples under the regression notes) for computing the parametrization of the data set fitting a second-order polynomial.
      2. +
      3. Use thereafter scikit-learn (see again the examples in the regression slides) and compare with your own code. When compairing with _scikit_learn_, make sure you set the option for the intercept to FALSE, see https://scikit-learn.org/stable/modules/generated/sklearn.linear_model.LinearRegression.html. This feature will be explained in more detail during the lectures of week 35 and week 36. You can find more in https://compphysics.github.io/MachineLearning/doc/LectureNotes/_build/html/chapter3.html#more-on-rescaling-data.
      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(\boldsymbol{y},\boldsymbol{\tilde{y}}) = \frac{1}{n} +\sum_{i=0}^{n-1}(y_i-\tilde{y}_i)^2, $$ -

      Taking the derivative with respect to \( \boldsymbol{\beta} \) and recalling that the derivative of the absolute value is (we drop the boldfaced vector symbol for simplicty)

      +

      and the \( R^2 \) score function. +If \( \tilde{\boldsymbol{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 +

      $$ -\frac{d \vert \beta\vert}{d \boldsymbol{\beta}}=\mathrm{sgn}(\boldsymbol{\beta})=\left\{\begin{array}{cc} 1 & \beta > 0 \\-1 & \beta < 0, \end{array}\right. +R^2(\boldsymbol{y}, \tilde{\boldsymbol{y}}) = 1 - \frac{\sum_{i=0}^{n - 1} (y_i - \tilde{y}_i)^2}{\sum_{i=0}^{n - 1} (y_i - \bar{y})^2}, $$ -

      we have that the derivative of the cost function is

      - +

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

      $$ -\frac{\partial C(\boldsymbol{X},\boldsymbol{\beta})}{\partial \boldsymbol{\beta}}=-2\boldsymbol{X}^T(\boldsymbol{y}-\boldsymbol{X}\boldsymbol{\beta})+\lambda sgn(\boldsymbol{\beta})=0, +\bar{y} = \frac{1}{n} \sum_{i=0}^{n - 1} y_i. $$ -

      and reordering we have

      -$$ -\boldsymbol{X}^T\boldsymbol{X}\boldsymbol{\beta}+\lambda sgn(\boldsymbol{\beta})=2\boldsymbol{X}^T\boldsymbol{y}. +

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

      + + + +

      +

      +

      + +

      +Solution. +

      +
      +
      +

      + +

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

      + + +
      +
      +
      +
      +
      +
      import os
      +import numpy as np
      +import pandas as pd
      +import matplotlib.pyplot as plt
      +from sklearn.model_selection import train_test_split
      +
      +def save_fig(fig_id):
      +    plt.savefig(image_path(fig_id) + ".png", format='png')
      +
      +def R2(y_data, y_model):
      +    return 1 - np.sum((y_data - y_model) ** 2) / np.sum((y_data - np.mean(y_data)) ** 2)
      +def MSE(y_data,y_model):
      +    n = np.size(y_model)
      +    return np.sum((y_data-y_model)**2)/n
      +
      +x = np.random.rand(100)
      +y = 2.0+5*x*x+0.1*np.random.randn(100)
      +
      +
      +#  The design matrix now as function of a given polynomial
      +X = np.zeros((len(x),3))
      +X[:,0] = 1.0
      +X[:,1] = x
      +X[:,2] = x**2
      +# We split the data in test and training data
      +X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2)
      +# matrix inversion to find beta
      +beta = np.linalg.inv(X_train.T @ X_train) @ X_train.T @ y_train
      +print(beta)
      +# and then make the prediction
      +ytilde = X_train @ beta
      +print("Training R2")
      +print(R2(y_train,ytilde))
      +print("Training MSE")
      +print(MSE(y_train,ytilde))
      +ypredict = X_test @ beta
      +print("Test R2")
      +print(R2(y_test,ypredict))
      +print("Test MSE")
      +print(MSE(y_test,ypredict))
      +
      +
      +
      +
      +
      +
      +
      +
      +
      +
      +
      +
      +
      +
      + + +

      +
      +

      + + + + + + +

      Exercise 3: Normalizing our data

      + +

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

      + +

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

      + +

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

      + +

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

      + +

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

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

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

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

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

      + +

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

      + +

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

      + + +
      +
      +
      +
      +
      +
      np.random.seed()
      +n = 100
      +maxdegree = 14
      +# Make data set.
      +x = np.linspace(-3, 3, n).reshape(-1, 1)
      +y = np.exp(-x**2) + 1.5 * np.exp(-(x-2)**2)+ np.random.normal(0, 0.1, x.shape)
      +
      +
      +
      +
      +
      +
      +
      +
      +
      +
      +
      +
      +
      +
      + +

      where \( y \) is the function we want to fit with a given polynomial.

      + + +

      +a) +Write a first code which sets up a design matrix \( X \) defined by a fifth-order polynomial. Scale your data and split it in training and test data. +

      + + + + +

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

      + + + + +

      +c) +Add now a model which allows you to make polynomials up to degree \( 15 \). Perform a standard OLS fitting of the training data and compute the MSE and \( R2 \) for the training and test data and plot both test and training data MSE and \( R2 \) as functions of the polynomial degree. Compare what you see with Figure 2.11 of Hastie et al. Comment your results. For which polynomial degree do you find an optimal MSE (smallest value)? +

      + + + + + + +

      Exercise 4: Adding Ridge Regression

      + +

      This exercise is a continuation of exercise 2. 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 regression method. +

      + +

      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)
      +y = 2.0+5*x*x+0.1*np.random.randn(100)
      +
      +
      +
      +
      +
      +
      +
      +
      +
      +
      +
      +
      +
      +
      + +

      Write your own code for the Ridge method (see chapter 3.4 of Hastie et al., equations (3.43) and (3.44)) and compute the parametrization for different values of \( \lambda \). Compare and analyze your results with those from exercise 3. Study the dependence on \( \lambda \) while also varying the strength of the noise in your expression for \( y(x) \).

      + +

      The code here allows you to perform your own Ridge calculation and +perform calculations for various values of the regularization +parameter \( \lambda \). This program can easily be extended upon. +

      + + + +
      +
      +
      +
      +
      +
      import os
      +import numpy as np
      +import pandas as pd
      +import matplotlib.pyplot as plt
      +from sklearn.model_selection import train_test_split
      +from sklearn.preprocessing import StandardScaler
      +
      +def R2(y_data, y_model):
      +    return 1 - np.sum((y_data - y_model) ** 2) / np.sum((y_data - np.mean(y_data)) ** 2)
      +def MSE(y_data,y_model):
      +    n = np.size(y_model)
      +    return np.sum((y_data-y_model)**2)/n
      +
      +
      +# A seed just to ensure that the random numbers are the same for every run.
      +# Useful for eventual debugging.
      +np.random.seed(3155)
      +
      +x = np.random.rand(100)
      +y = 2.0+5*x*x+0.1*np.random.randn(100)
      +
      +# number of features p (here degree of polynomial
      +p = 3
      +#  The design matrix now as function of a given polynomial
      +X = np.zeros((len(x),p))
      +X[:,0] = 1.0
      +X[:,1] = x
      +X[:,2] = x*x
      +# We split the data in test and training data
      +X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2)
      +
      +# matrix inversion to find beta
      +OLSbeta = np.linalg.inv(X_train.T @ X_train) @ X_train.T @ y_train
      +print(OLSbeta)
      +# and then make the prediction
      +ytildeOLS = X_train @ OLSbeta
      +print("Training R2 for OLS")
      +print(R2(y_train,ytildeOLS))
      +print("Training MSE for OLS")
      +print(MSE(y_train,ytildeOLS))
      +ypredictOLS = X_test @ OLSbeta
      +print("Test R2 for OLS")
      +print(R2(y_test,ypredictOLS))
      +print("Test MSE OLS")
      +print(MSE(y_test,ypredictOLS))
      +
      +# Repeat now for Ridge regression and various values of the regularization parameter
      +I = np.eye(p,p)
      +# Decide which values of lambda to use
      +nlambdas = 20
      +MSEPredict = np.zeros(nlambdas)
      +MSETrain = np.zeros(nlambdas)
      +lambdas = np.logspace(-4, 1, nlambdas)
      +for i in range(nlambdas):
      +    lmb = lambdas[i]
      +    Ridgebeta = np.linalg.inv(X_train.T @ X_train+lmb*I) @ X_train.T @ y_train
      +    # and then make the prediction
      +    ytildeRidge = X_train @ Ridgebeta
      +    ypredictRidge = X_test @ Ridgebeta
      +    MSEPredict[i] = MSE(y_test,ypredictRidge)
      +    MSETrain[i] = MSE(y_train,ytildeRidge)
      +# Now plot the results
      +plt.figure()
      +plt.plot(np.log10(lambdas), MSETrain, label = 'MSE Ridge train')
      +plt.plot(np.log10(lambdas), MSEPredict, 'r--', label = 'MSE Ridge Test')
      +plt.xlabel('log10(lambda)')
      +plt.ylabel('MSE')
      +plt.legend()
      +plt.show()
      +
      +
      +
      +
      +
      +
      +
      +
      +
      +
      +
      +
      +
      +
      + +

      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 \). Observe also that when you compare with Scikit-Learn, you need to pay attention to how the intercept is dealt with. +

      + +

      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

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

      This equation does not lead to a nice analytical equation as in either Ridge regression or ordinary least squares. This equation can however be solved by using standard convex optimization algorithms using for example the Python package CVXOPT. We will discuss this later.

      +

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

      + + + + +

      Exercise 5: Analytical exercises

      + +

      In this exercise we derive the expressions for various derivatives of +products of vectors and matrices. Such derivatives are central to the +optimization of various cost functions. Although we will often use +automatic differentiation in actual calculations, to be able to have +analytical expressions is extremely helpful in case we have simpler +derivatives as well as when we analyze various properties (like second +derivatives) of the chosen cost functions. Vectors are always written +as boldfaced lower case letters and matrices as upper case boldfaced +letters. +

      + +

      Show that

      +$$ +\frac{\partial (\boldsymbol{b}^T\boldsymbol{a})}{\partial \boldsymbol{a}} = \boldsymbol{b}, +$$ + +

      and

      +$$ +\frac{\partial (\boldsymbol{a}^T\boldsymbol{A}\boldsymbol{a})}{\partial \boldsymbol{a}} = \boldsymbol{a}^T(\boldsymbol{A}+\boldsymbol{A}^T), +$$ + +

      and

      +$$ +\frac{\partial \left(\boldsymbol{x}-\boldsymbol{A}\boldsymbol{s}\right)^T\left(\boldsymbol{x}-\boldsymbol{A}\boldsymbol{s}\right)}{\partial \boldsymbol{s}} = -2\left(\boldsymbol{x}-\boldsymbol{A}\boldsymbol{s}\right)^T\boldsymbol{A}, +$$ + +

      and finally find the second derivative of this function with respect to the vector \( \boldsymbol{s} \).

      + +

      Hint: In these exercises it is always useful to write out with summation indices the various quantities. +As an example, consider the function +

      + +$$ +f(\boldsymbol{x}) =\boldsymbol{A}\boldsymbol{x}, +$$ + +

      which reads for a specific component \( f_i \) (we define the matrix \( \boldsymbol{A} \) to have dimension \( n\times n \) and the vector $\boldsymbol{x} to have length \( n \))

      + +$$ +f_i =\sum_{j=0}^{n-1}a_{ij}x_j, +$$ + +

      which leads to

      +$$ +\frac{\partial f_i}{\partial x_j}= a_{ij}, +$$ + +

      and written out in terms of the vector \( \boldsymbol{x} \) we have

      +$$ +\frac{\partial f(\boldsymbol{x})}{\partial \boldsymbol{x}}= \boldsymbol{A}. +$$ + + +

      diff --git a/doc/pub/week35/html/week35-bs.html b/doc/pub/week35/html/week35-bs.html index f1a81b669..1d8b1baef 100644 --- a/doc/pub/week35/html/week35-bs.html +++ b/doc/pub/week35/html/week35-bs.html @@ -38,7 +38,6 @@ doconce format html week35.do.txt --html_style=bootstrap --pygments_html_style=d {'highest level': 2, 'sections': [('Plans for week 35', 2, None, 'plans-for-week-35'), ('Reading recommendations:', 3, None, 'reading-recommendations'), - ('Topics of week 35', 2, None, 'topics-of-week-35'), ('Why Linear Regression (aka Ordinary Least Squares and family), ' 'repeat from last week', 2, @@ -301,78 +300,77 @@ MathJax.Hub.Config({ @@ -402,7 +400,7 @@ MathJax.Hub.Config({
      -

      May 29, 2023

      +

      Jul 5, 2023


      @@ -427,7 +425,7 @@ MathJax.Hub.Config({
    489. 9
    490. 10
    491. ...
    492. -
    493. 69
    494. +
    495. 68
    496. »
    497. diff --git a/doc/pub/week35/html/week35-reveal.html b/doc/pub/week35/html/week35-reveal.html index d42af93e6..616f18026 100644 --- a/doc/pub/week35/html/week35-reveal.html +++ b/doc/pub/week35/html/week35-reveal.html @@ -184,7 +184,7 @@ MathJax.Hub.Config({
      -

      May 29, 2023

      +

      Jul 5, 2023


      @@ -197,10 +197,14 @@ MathJax.Hub.Config({

      Plans for week 35

      -
        -

      • Review of ordinary Least Squares with applications. Discussion of Ridge and Lasso Regression and links with Singular Value Decomposition
      • -

      • Exercises and hands-on demonstrations
      • -
      +

      The main topics are:

      +
        +

      1. Repetition from last week on linear regression
      2. +

      3. Reminder on statistics with quantities like mean values, variance abd covariance
      4. +

      5. Discussion of how to prepare data and examples of applications of linear regression
      6. +

      7. Mathematical interpretations of Linear Regression
      8. +

      9. Start discussing Ridge and Lasso regression and Singular Value Decomposition
      10. +

      Reading recommendations:

        @@ -212,19 +216,6 @@ MathJax.Hub.Config({
      -
      -

      Topics of week 35

      - -

      The main topics are:

      -
        -

      1. Repetition from last week on linear regression
      2. -

      3. Reminder on statistics with quantities like mean values, variance abd covariance
      4. -

      5. Discussion of how to prepare data and examples of applications of linear regression
      6. -

      7. Mathematical interpretations of Linear Regression
      8. -

      9. Start discussing Ridge and Lasso regression and Singular Value Decomposition
      10. -
      -
      -

      Why Linear Regression (aka Ordinary Least Squares and family), repeat from last week

      diff --git a/doc/pub/week35/html/week35-solarized.html b/doc/pub/week35/html/week35-solarized.html index a31c0dff4..855a43037 100644 --- a/doc/pub/week35/html/week35-solarized.html +++ b/doc/pub/week35/html/week35-solarized.html @@ -65,7 +65,6 @@ div.toc p,a { {'highest level': 2, 'sections': [('Plans for week 35', 2, None, 'plans-for-week-35'), ('Reading recommendations:', 3, None, 'reading-recommendations'), - ('Topics of week 35', 2, None, 'topics-of-week-35'), ('Why Linear Regression (aka Ordinary Least Squares and family), ' 'repeat from last week', 2, @@ -329,28 +328,13 @@ MathJax.Hub.Config({
      -

      May 29, 2023

      +

      Jul 5, 2023












      Plans for week 35

      -
        -
      • Review of ordinary Least Squares with applications. Discussion of Ridge and Lasso Regression and links with Singular Value Decomposition
      • -
      • Exercises and hands-on demonstrations
      • -
      -

      Reading recommendations:

      -
        -
      1. See lecture notes for week 35 at https://compphysics.github.io/MachineLearning/doc/web/course.html
      2. -
      3. For a review on statistics see jupyter-book https://compphysics.github.io/MachineLearning/doc/LectureNotes/_build/html/statistics.html, the most relevant parts are covered by sections 1.1.1-1.1.5
      4. -
      5. HTF chapter 3. GBC chapters 1 and and sections 3.1-3.11 and 5.1
      6. -
      7. CMB sections 1.1 and 3.1
      8. -
      9. A good review on statistics is given by Murphy's text, chapter 2, see https://github.com/CompPhysics/MachineLearning/blob/master/doc/Textbooks/MachineLearningMurphy.pdf
      10. -
      -









      -

      Topics of week 35

      -

      The main topics are:

      1. Repetition from last week on linear regression
      2. @@ -359,6 +343,14 @@ MathJax.Hub.Config({
      3. Mathematical interpretations of Linear Regression
      4. Start discussing Ridge and Lasso regression and Singular Value Decomposition
      +

      Reading recommendations:

      +
        +
      1. See lecture notes for week 35 at https://compphysics.github.io/MachineLearning/doc/web/course.html
      2. +
      3. For a review on statistics see jupyter-book https://compphysics.github.io/MachineLearning/doc/LectureNotes/_build/html/statistics.html, the most relevant parts are covered by sections 1.1.1-1.1.5
      4. +
      5. HTF chapter 3. GBC chapters 1 and and sections 3.1-3.11 and 5.1
      6. +
      7. CMB sections 1.1 and 3.1
      8. +
      9. A good review on statistics is given by Murphy's text, chapter 2, see https://github.com/CompPhysics/MachineLearning/blob/master/doc/Textbooks/MachineLearningMurphy.pdf
      10. +










      Why Linear Regression (aka Ordinary Least Squares and family), repeat from last week

      diff --git a/doc/pub/week35/html/week35.html b/doc/pub/week35/html/week35.html index aea9dfa9f..0c426287d 100644 --- a/doc/pub/week35/html/week35.html +++ b/doc/pub/week35/html/week35.html @@ -142,7 +142,6 @@ div.toc p,a { {'highest level': 2, 'sections': [('Plans for week 35', 2, None, 'plans-for-week-35'), ('Reading recommendations:', 3, None, 'reading-recommendations'), - ('Topics of week 35', 2, None, 'topics-of-week-35'), ('Why Linear Regression (aka Ordinary Least Squares and family), ' 'repeat from last week', 2, @@ -406,28 +405,13 @@ MathJax.Hub.Config({
      -

      May 29, 2023

      +

      Jul 5, 2023












      Plans for week 35

      -
        -
      • Review of ordinary Least Squares with applications. Discussion of Ridge and Lasso Regression and links with Singular Value Decomposition
      • -
      • Exercises and hands-on demonstrations
      • -
      -

      Reading recommendations:

      -
        -
      1. See lecture notes for week 35 at https://compphysics.github.io/MachineLearning/doc/web/course.html
      2. -
      3. For a review on statistics see jupyter-book https://compphysics.github.io/MachineLearning/doc/LectureNotes/_build/html/statistics.html, the most relevant parts are covered by sections 1.1.1-1.1.5
      4. -
      5. HTF chapter 3. GBC chapters 1 and and sections 3.1-3.11 and 5.1
      6. -
      7. CMB sections 1.1 and 3.1
      8. -
      9. A good review on statistics is given by Murphy's text, chapter 2, see https://github.com/CompPhysics/MachineLearning/blob/master/doc/Textbooks/MachineLearningMurphy.pdf
      10. -
      -









      -

      Topics of week 35

      -

      The main topics are:

      1. Repetition from last week on linear regression
      2. @@ -436,6 +420,14 @@ MathJax.Hub.Config({
      3. Mathematical interpretations of Linear Regression
      4. Start discussing Ridge and Lasso regression and Singular Value Decomposition
      +

      Reading recommendations:

      +
        +
      1. See lecture notes for week 35 at https://compphysics.github.io/MachineLearning/doc/web/course.html
      2. +
      3. For a review on statistics see jupyter-book https://compphysics.github.io/MachineLearning/doc/LectureNotes/_build/html/statistics.html, the most relevant parts are covered by sections 1.1.1-1.1.5
      4. +
      5. HTF chapter 3. GBC chapters 1 and and sections 3.1-3.11 and 5.1
      6. +
      7. CMB sections 1.1 and 3.1
      8. +
      9. A good review on statistics is given by Murphy's text, chapter 2, see https://github.com/CompPhysics/MachineLearning/blob/master/doc/Textbooks/MachineLearningMurphy.pdf
      10. +










      Why Linear Regression (aka Ordinary Least Squares and family), repeat from last week

      diff --git a/doc/pub/week35/ipynb/ipynb-week35-src.tar.gz b/doc/pub/week35/ipynb/ipynb-week35-src.tar.gz index 24c4e9559..8b7787352 100644 Binary files a/doc/pub/week35/ipynb/ipynb-week35-src.tar.gz and b/doc/pub/week35/ipynb/ipynb-week35-src.tar.gz differ diff --git a/doc/pub/week35/ipynb/week35.ipynb b/doc/pub/week35/ipynb/week35.ipynb index ef8d44db6..ad26ffa80 100644 --- a/doc/pub/week35/ipynb/week35.ipynb +++ b/doc/pub/week35/ipynb/week35.ipynb @@ -2,7 +2,7 @@ "cells": [ { "cell_type": "markdown", - "id": "68b5c9f4", + "id": "7b57ad6c", "metadata": { "editable": true }, @@ -14,7 +14,7 @@ }, { "cell_type": "markdown", - "id": "72fbd020", + "id": "07ee3add", "metadata": { "editable": true }, @@ -22,28 +22,35 @@ "# Week 35: From Ordinary Linear Regression to Ridge and Lasso Regression\n", "**Morten Hjorth-Jensen**, Department of Physics, University of Oslo and Department of Physics and Astronomy and National Superconducting Cyclotron Laboratory, Michigan State University\n", "\n", - "Date: **May 29, 2023**\n", + "Date: **Jul 5, 2023**\n", "\n", "Copyright 1999-2023, Morten Hjorth-Jensen. Released under CC Attribution-NonCommercial 4.0 license" ] }, { "cell_type": "markdown", - "id": "dcddb42b", + "id": "139693a5", "metadata": { "editable": true }, "source": [ "## Plans for week 35\n", "\n", - "* Review of ordinary Least Squares with applications. Discussion of Ridge and Lasso Regression and links with Singular Value Decomposition\n", + "The main topics are:\n", + "1. Repetition from last week on linear regression\n", "\n", - "* Exercises and hands-on demonstrations" + "2. Reminder on statistics with quantities like mean values, variance abd covariance\n", + "\n", + "3. Discussion of how to prepare data and examples of applications of linear regression\n", + "\n", + "4. Mathematical interpretations of Linear Regression\n", + "\n", + "5. Start discussing Ridge and Lasso regression and Singular Value Decomposition" ] }, { "cell_type": "markdown", - "id": "51853e51", + "id": "e729ca93", "metadata": { "editable": true }, @@ -63,28 +70,7 @@ }, { "cell_type": "markdown", - "id": "15a7304c", - "metadata": { - "editable": true - }, - "source": [ - "## Topics of week 35\n", - "\n", - "The main topics are:\n", - "1. Repetition from last week on linear regression\n", - "\n", - "2. Reminder on statistics with quantities like mean values, variance abd covariance\n", - "\n", - "3. Discussion of how to prepare data and examples of applications of linear regression\n", - "\n", - "4. Mathematical interpretations of Linear Regression\n", - "\n", - "5. Start discussing Ridge and Lasso regression and Singular Value Decomposition" - ] - }, - { - "cell_type": "markdown", - "id": "25d2e250", + "id": "23ea3ebd", "metadata": { "editable": true }, @@ -118,7 +104,7 @@ }, { "cell_type": "markdown", - "id": "0fe94f81", + "id": "4a2f0462", "metadata": { "editable": true }, @@ -140,7 +126,7 @@ }, { "cell_type": "markdown", - "id": "10ac1bae", + "id": "381ec5e4", "metadata": { "editable": true }, @@ -168,7 +154,7 @@ }, { "cell_type": "markdown", - "id": "96defb48", + "id": "ffa2beaa", "metadata": { "editable": true }, @@ -183,7 +169,7 @@ }, { "cell_type": "markdown", - "id": "cc47c67f", + "id": "51f2f37f", "metadata": { "editable": true }, @@ -195,7 +181,7 @@ }, { "cell_type": "markdown", - "id": "fe2d745c", + "id": "83c28be9", "metadata": { "editable": true }, @@ -210,7 +196,7 @@ }, { "cell_type": "markdown", - "id": "f3b3694c", + "id": "11400dfb", "metadata": { "editable": true }, @@ -223,7 +209,7 @@ }, { "cell_type": "markdown", - "id": "aad24c77", + "id": "da004425", "metadata": { "editable": true }, @@ -235,7 +221,7 @@ }, { "cell_type": "markdown", - "id": "be082b82", + "id": "eaf3f45c", "metadata": { "editable": true }, @@ -245,7 +231,7 @@ }, { "cell_type": "markdown", - "id": "df9c4a6b", + "id": "6daf4c04", "metadata": { "editable": true }, @@ -256,7 +242,7 @@ }, { "cell_type": "markdown", - "id": "410e5b62", + "id": "c886bcf3", "metadata": { "editable": true }, @@ -274,7 +260,7 @@ }, { "cell_type": "markdown", - "id": "df9fe0d2", + "id": "dde3d0d2", "metadata": { "editable": true }, @@ -285,7 +271,7 @@ }, { "cell_type": "markdown", - "id": "cbd065b6", + "id": "4a59eefe", "metadata": { "editable": true }, @@ -297,7 +283,7 @@ }, { "cell_type": "markdown", - "id": "c0282a14", + "id": "5e63a16f", "metadata": { "editable": true }, @@ -307,7 +293,7 @@ }, { "cell_type": "markdown", - "id": "433cd901", + "id": "3808207e", "metadata": { "editable": true }, @@ -319,7 +305,7 @@ }, { "cell_type": "markdown", - "id": "38a0fff8", + "id": "5faec99f", "metadata": { "editable": true }, @@ -329,7 +315,7 @@ }, { "cell_type": "markdown", - "id": "1d164c9e", + "id": "c0307961", "metadata": { "editable": true }, @@ -341,7 +327,7 @@ }, { "cell_type": "markdown", - "id": "f4e7a7d1", + "id": "45febdbc", "metadata": { "editable": true }, @@ -351,7 +337,7 @@ }, { "cell_type": "markdown", - "id": "a36a262d", + "id": "2a9da026", "metadata": { "editable": true }, @@ -370,7 +356,7 @@ }, { "cell_type": "markdown", - "id": "dd4a11de", + "id": "fd6ea26e", "metadata": { "editable": true }, @@ -380,7 +366,7 @@ }, { "cell_type": "markdown", - "id": "3dc4b052", + "id": "bed89e47", "metadata": { "editable": true }, @@ -392,7 +378,7 @@ }, { "cell_type": "markdown", - "id": "91bb8b5e", + "id": "3523b12f", "metadata": { "editable": true }, @@ -402,7 +388,7 @@ }, { "cell_type": "markdown", - "id": "9324fa90", + "id": "75836a80", "metadata": { "editable": true }, @@ -418,7 +404,7 @@ }, { "cell_type": "markdown", - "id": "119f08fa", + "id": "525b71bb", "metadata": { "editable": true }, @@ -438,7 +424,7 @@ }, { "cell_type": "markdown", - "id": "d398d0c3", + "id": "a288b524", "metadata": { "editable": true }, @@ -448,7 +434,7 @@ }, { "cell_type": "markdown", - "id": "d06b2bdc", + "id": "796a5003", "metadata": { "editable": true }, @@ -459,7 +445,7 @@ }, { "cell_type": "markdown", - "id": "85b598cf", + "id": "8c5afbe7", "metadata": { "editable": true }, @@ -478,7 +464,7 @@ }, { "cell_type": "markdown", - "id": "0b244390", + "id": "1561f48c", "metadata": { "editable": true }, @@ -488,7 +474,7 @@ }, { "cell_type": "markdown", - "id": "f71d82cb", + "id": "8a6ef58f", "metadata": { "editable": true }, @@ -500,7 +486,7 @@ }, { "cell_type": "markdown", - "id": "d9b51cb9", + "id": "e73fc4e4", "metadata": { "editable": true }, @@ -510,7 +496,7 @@ }, { "cell_type": "markdown", - "id": "62e3140a", + "id": "f8af864e", "metadata": { "editable": true }, @@ -521,7 +507,7 @@ }, { "cell_type": "markdown", - "id": "d8af9400", + "id": "a4ba2281", "metadata": { "editable": true }, @@ -541,7 +527,7 @@ }, { "cell_type": "markdown", - "id": "cd4daf2c", + "id": "c6831091", "metadata": { "editable": true }, @@ -553,7 +539,7 @@ }, { "cell_type": "markdown", - "id": "fe963463", + "id": "13ab872f", "metadata": { "editable": true }, @@ -568,7 +554,7 @@ { "cell_type": "code", "execution_count": 1, - "id": "ede9110f", + "id": "bc336755", "metadata": { "collapsed": false, "editable": true @@ -650,7 +636,7 @@ }, { "cell_type": "markdown", - "id": "1135bdee", + "id": "41c9ed9e", "metadata": { "editable": true }, @@ -660,7 +646,7 @@ }, { "cell_type": "markdown", - "id": "48a99e12", + "id": "3c4d25d8", "metadata": { "editable": true }, @@ -672,7 +658,7 @@ }, { "cell_type": "markdown", - "id": "f9401b16", + "id": "abb64145", "metadata": { "editable": true }, @@ -682,7 +668,7 @@ }, { "cell_type": "markdown", - "id": "86264b86", + "id": "5cf25eae", "metadata": { "editable": true }, @@ -693,7 +679,7 @@ }, { "cell_type": "markdown", - "id": "048e5c38", + "id": "4855e40c", "metadata": { "editable": true }, @@ -705,7 +691,7 @@ }, { "cell_type": "markdown", - "id": "b1bba499", + "id": "53c63a95", "metadata": { "editable": true }, @@ -715,7 +701,7 @@ }, { "cell_type": "markdown", - "id": "ec938825", + "id": "ad3eb9e2", "metadata": { "editable": true }, @@ -727,7 +713,7 @@ }, { "cell_type": "markdown", - "id": "bdee42b9", + "id": "36070ac0", "metadata": { "editable": true }, @@ -737,7 +723,7 @@ }, { "cell_type": "markdown", - "id": "4fd26888", + "id": "c9fffaca", "metadata": { "editable": true }, @@ -749,7 +735,7 @@ }, { "cell_type": "markdown", - "id": "87132dfb", + "id": "c7bb9ee2", "metadata": { "editable": true }, @@ -762,7 +748,7 @@ }, { "cell_type": "markdown", - "id": "c825532a", + "id": "25333ae8", "metadata": { "editable": true }, @@ -774,7 +760,7 @@ }, { "cell_type": "markdown", - "id": "50ee906e", + "id": "bdcb8887", "metadata": { "editable": true }, @@ -784,7 +770,7 @@ }, { "cell_type": "markdown", - "id": "4adf10aa", + "id": "62fa4e68", "metadata": { "editable": true }, @@ -796,7 +782,7 @@ }, { "cell_type": "markdown", - "id": "eb827c9a", + "id": "b23b3f61", "metadata": { "editable": true }, @@ -808,7 +794,7 @@ }, { "cell_type": "markdown", - "id": "02ae6d08", + "id": "7f857fac", "metadata": { "editable": true }, @@ -819,7 +805,7 @@ }, { "cell_type": "markdown", - "id": "23470b49", + "id": "7c0b8fbc", "metadata": { "editable": true }, @@ -831,7 +817,7 @@ }, { "cell_type": "markdown", - "id": "abd20c9a", + "id": "ca37ab98", "metadata": { "editable": true }, @@ -850,7 +836,7 @@ }, { "cell_type": "markdown", - "id": "5e8e9d7a", + "id": "94abf405", "metadata": { "editable": true }, @@ -863,7 +849,7 @@ }, { "cell_type": "markdown", - "id": "09e979d5", + "id": "7653c09e", "metadata": { "editable": true }, @@ -873,7 +859,7 @@ }, { "cell_type": "markdown", - "id": "bc7717a8", + "id": "0ded9e94", "metadata": { "editable": true }, @@ -885,7 +871,7 @@ }, { "cell_type": "markdown", - "id": "6455db02", + "id": "3b160c26", "metadata": { "editable": true }, @@ -895,7 +881,7 @@ }, { "cell_type": "markdown", - "id": "6c982663", + "id": "ee990fde", "metadata": { "editable": true }, @@ -907,7 +893,7 @@ }, { "cell_type": "markdown", - "id": "6c9f78c6", + "id": "c2483dfa", "metadata": { "editable": true }, @@ -917,7 +903,7 @@ }, { "cell_type": "markdown", - "id": "eda01a85", + "id": "0f9ac2ea", "metadata": { "editable": true }, @@ -929,7 +915,7 @@ }, { "cell_type": "markdown", - "id": "098a6d51", + "id": "bdf61656", "metadata": { "editable": true }, @@ -940,7 +926,7 @@ }, { "cell_type": "markdown", - "id": "1a26f29b", + "id": "16d320e4", "metadata": { "editable": true }, @@ -952,7 +938,7 @@ }, { "cell_type": "markdown", - "id": "d12e614f", + "id": "287bf270", "metadata": { "editable": true }, @@ -962,7 +948,7 @@ }, { "cell_type": "markdown", - "id": "11eaab60", + "id": "09abacad", "metadata": { "editable": true }, @@ -974,7 +960,7 @@ }, { "cell_type": "markdown", - "id": "95d04ecc", + "id": "d4fb2d6a", "metadata": { "editable": true }, @@ -984,7 +970,7 @@ }, { "cell_type": "markdown", - "id": "6ea996a9", + "id": "40481229", "metadata": { "editable": true }, @@ -996,7 +982,7 @@ }, { "cell_type": "markdown", - "id": "1477d180", + "id": "e364b319", "metadata": { "editable": true }, @@ -1017,7 +1003,7 @@ }, { "cell_type": "markdown", - "id": "4eb7760c", + "id": "fd53ca74", "metadata": { "editable": true }, @@ -1030,7 +1016,7 @@ }, { "cell_type": "markdown", - "id": "9d3dc897", + "id": "9cbb2a26", "metadata": { "editable": true }, @@ -1042,7 +1028,7 @@ }, { "cell_type": "markdown", - "id": "9e2258ba", + "id": "7e324336", "metadata": { "editable": true }, @@ -1054,7 +1040,7 @@ }, { "cell_type": "markdown", - "id": "77c5a42a", + "id": "e8becdc2", "metadata": { "editable": true }, @@ -1066,7 +1052,7 @@ }, { "cell_type": "markdown", - "id": "fab919c0", + "id": "9fdb093f", "metadata": { "editable": true }, @@ -1078,7 +1064,7 @@ }, { "cell_type": "markdown", - "id": "482be0d1", + "id": "7ffc4190", "metadata": { "editable": true }, @@ -1088,7 +1074,7 @@ }, { "cell_type": "markdown", - "id": "7f3b9e0e", + "id": "1ccbe001", "metadata": { "editable": true }, @@ -1104,7 +1090,7 @@ }, { "cell_type": "markdown", - "id": "d56125e2", + "id": "24e1543a", "metadata": { "editable": true }, @@ -1116,7 +1102,7 @@ }, { "cell_type": "markdown", - "id": "e557e6fb", + "id": "38001b76", "metadata": { "editable": true }, @@ -1126,7 +1112,7 @@ }, { "cell_type": "markdown", - "id": "59a4e5bf", + "id": "80e0bf75", "metadata": { "editable": true }, @@ -1138,7 +1124,7 @@ }, { "cell_type": "markdown", - "id": "5dc1fec2", + "id": "9b5ab4c0", "metadata": { "editable": true }, @@ -1156,7 +1142,7 @@ }, { "cell_type": "markdown", - "id": "7d4277fb", + "id": "a035eae8", "metadata": { "editable": true }, @@ -1167,7 +1153,7 @@ }, { "cell_type": "markdown", - "id": "4cfa7978", + "id": "2d3aafe5", "metadata": { "editable": true }, @@ -1179,7 +1165,7 @@ }, { "cell_type": "markdown", - "id": "794b6ae9", + "id": "9ad750e6", "metadata": { "editable": true }, @@ -1189,7 +1175,7 @@ }, { "cell_type": "markdown", - "id": "e8723581", + "id": "dc78f08f", "metadata": { "editable": true }, @@ -1201,7 +1187,7 @@ }, { "cell_type": "markdown", - "id": "79013d19", + "id": "1e87767a", "metadata": { "editable": true }, @@ -1211,7 +1197,7 @@ }, { "cell_type": "markdown", - "id": "6e8bee84", + "id": "b98eecde", "metadata": { "editable": true }, @@ -1223,7 +1209,7 @@ }, { "cell_type": "markdown", - "id": "ccc81be9", + "id": "eedc8397", "metadata": { "editable": true }, @@ -1233,7 +1219,7 @@ }, { "cell_type": "markdown", - "id": "63eb9970", + "id": "80d31267", "metadata": { "editable": true }, @@ -1247,7 +1233,7 @@ { "cell_type": "code", "execution_count": 2, - "id": "53c8a84b", + "id": "b8561a00", "metadata": { "collapsed": false, "editable": true @@ -1262,7 +1248,7 @@ }, { "cell_type": "markdown", - "id": "a4072ebf", + "id": "942df122", "metadata": { "editable": true }, @@ -1273,7 +1259,7 @@ { "cell_type": "code", "execution_count": 3, - "id": "38bc494a", + "id": "350dfd81", "metadata": { "collapsed": false, "editable": true @@ -1286,7 +1272,7 @@ }, { "cell_type": "markdown", - "id": "d96d92db", + "id": "0406ba1b", "metadata": { "editable": true }, @@ -1297,7 +1283,7 @@ { "cell_type": "code", "execution_count": 4, - "id": "d0844e9c", + "id": "6e76d535", "metadata": { "collapsed": false, "editable": true @@ -1320,7 +1306,7 @@ }, { "cell_type": "markdown", - "id": "2fc6ded6", + "id": "b8a8d20b", "metadata": { "editable": true }, @@ -1334,7 +1320,7 @@ { "cell_type": "code", "execution_count": 5, - "id": "6c3d09f7", + "id": "1d123d6d", "metadata": { "collapsed": false, "editable": true @@ -1347,7 +1333,7 @@ }, { "cell_type": "markdown", - "id": "37f5ce39", + "id": "bf65a431", "metadata": { "editable": true }, @@ -1358,7 +1344,7 @@ { "cell_type": "code", "execution_count": 6, - "id": "5925bd56", + "id": "ce6f2a8b", "metadata": { "collapsed": false, "editable": true @@ -1370,7 +1356,7 @@ }, { "cell_type": "markdown", - "id": "daa51e3a", + "id": "f5f5c570", "metadata": { "editable": true }, @@ -1381,7 +1367,7 @@ { "cell_type": "code", "execution_count": 7, - "id": "3e803617", + "id": "75a7a450", "metadata": { "collapsed": false, "editable": true @@ -1397,7 +1383,7 @@ }, { "cell_type": "markdown", - "id": "87c8440d", + "id": "e44301bb", "metadata": { "editable": true }, @@ -1408,7 +1394,7 @@ { "cell_type": "code", "execution_count": 8, - "id": "ec4cc7ad", + "id": "911c2fee", "metadata": { "collapsed": false, "editable": true @@ -1422,7 +1408,7 @@ }, { "cell_type": "markdown", - "id": "641a6d52", + "id": "95878159", "metadata": { "editable": true }, @@ -1443,7 +1429,7 @@ }, { "cell_type": "markdown", - "id": "758d4c2e", + "id": "a99c97ad", "metadata": { "editable": true }, @@ -1454,7 +1440,7 @@ { "cell_type": "code", "execution_count": 9, - "id": "f1339bc4", + "id": "4010c1ec", "metadata": { "collapsed": false, "editable": true @@ -1503,7 +1489,7 @@ }, { "cell_type": "markdown", - "id": "9fa72f3c", + "id": "adfdccc6", "metadata": { "editable": true }, @@ -1514,7 +1500,7 @@ { "cell_type": "code", "execution_count": 10, - "id": "5386450d", + "id": "34e98567", "metadata": { "collapsed": false, "editable": true @@ -1539,7 +1525,7 @@ }, { "cell_type": "markdown", - "id": "91fd6a2a", + "id": "9148d7bc", "metadata": { "editable": true }, @@ -1551,7 +1537,7 @@ }, { "cell_type": "markdown", - "id": "2867c932", + "id": "1c917c75", "metadata": { "editable": true }, @@ -1595,7 +1581,7 @@ }, { "cell_type": "markdown", - "id": "6019d1cd", + "id": "d73dcf20", "metadata": { "editable": true }, @@ -1607,7 +1593,7 @@ { "cell_type": "code", "execution_count": 11, - "id": "dc5f50f7", + "id": "0195ea99", "metadata": { "collapsed": false, "editable": true @@ -1623,7 +1609,7 @@ }, { "cell_type": "markdown", - "id": "d840f15f", + "id": "5823fed3", "metadata": { "editable": true }, @@ -1634,7 +1620,7 @@ { "cell_type": "code", "execution_count": 12, - "id": "63a64fbb", + "id": "d3ddd2b5", "metadata": { "collapsed": false, "editable": true @@ -1652,7 +1638,7 @@ }, { "cell_type": "markdown", - "id": "eb869dd7", + "id": "512e8d10", "metadata": { "editable": true }, @@ -1663,7 +1649,7 @@ { "cell_type": "code", "execution_count": 13, - "id": "1f5322ec", + "id": "07981b7b", "metadata": { "collapsed": false, "editable": true @@ -1677,7 +1663,7 @@ }, { "cell_type": "markdown", - "id": "51f33235", + "id": "dbf53730", "metadata": { "editable": true }, @@ -1688,7 +1674,7 @@ { "cell_type": "code", "execution_count": 14, - "id": "ef32dd15", + "id": "6acf807a", "metadata": { "collapsed": false, "editable": true @@ -1701,7 +1687,7 @@ }, { "cell_type": "markdown", - "id": "60da4baa", + "id": "1720c9b1", "metadata": { "editable": true }, @@ -1712,7 +1698,7 @@ { "cell_type": "code", "execution_count": 15, - "id": "a1349f06", + "id": "c1bf8c10", "metadata": { "collapsed": false, "editable": true @@ -1729,7 +1715,7 @@ }, { "cell_type": "markdown", - "id": "3b5ca502", + "id": "2d2d4f81", "metadata": { "editable": true }, @@ -1740,7 +1726,7 @@ { "cell_type": "code", "execution_count": 16, - "id": "c5acfacc", + "id": "e0e599b3", "metadata": { "collapsed": false, "editable": true @@ -1756,7 +1742,7 @@ }, { "cell_type": "markdown", - "id": "09f8fb1d", + "id": "935a79c6", "metadata": { "editable": true }, @@ -1767,7 +1753,7 @@ { "cell_type": "code", "execution_count": 17, - "id": "ae1b3447", + "id": "c7bedcc5", "metadata": { "collapsed": false, "editable": true @@ -1791,7 +1777,7 @@ }, { "cell_type": "markdown", - "id": "9ee582dd", + "id": "c082bc35", "metadata": { "editable": true }, @@ -1802,7 +1788,7 @@ { "cell_type": "code", "execution_count": 18, - "id": "29e7f3a6", + "id": "ef7fea72", "metadata": { "collapsed": false, "editable": true @@ -1815,7 +1801,7 @@ }, { "cell_type": "markdown", - "id": "6fd3b0c6", + "id": "480ebeb8", "metadata": { "editable": true }, @@ -1826,7 +1812,7 @@ { "cell_type": "code", "execution_count": 19, - "id": "b4346c58", + "id": "5bb3bcf7", "metadata": { "collapsed": false, "editable": true @@ -1846,7 +1832,7 @@ }, { "cell_type": "markdown", - "id": "79132cb6", + "id": "f464a0ca", "metadata": { "editable": true }, @@ -1857,7 +1843,7 @@ { "cell_type": "code", "execution_count": 20, - "id": "f1231ed3", + "id": "238fbe31", "metadata": { "collapsed": false, "editable": true @@ -1900,7 +1886,7 @@ { "cell_type": "code", "execution_count": 21, - "id": "15b7c753", + "id": "5f5cfcdd", "metadata": { "collapsed": false, "editable": true @@ -1915,7 +1901,7 @@ }, { "cell_type": "markdown", - "id": "29c95749", + "id": "50c7eb6b", "metadata": { "editable": true }, @@ -1944,7 +1930,7 @@ }, { "cell_type": "markdown", - "id": "de725212", + "id": "2de393a7", "metadata": { "editable": true }, @@ -1969,7 +1955,7 @@ }, { "cell_type": "markdown", - "id": "a696ae7e", + "id": "2072b9be", "metadata": { "editable": true }, @@ -1989,7 +1975,7 @@ }, { "cell_type": "markdown", - "id": "104b40dd", + "id": "9f685304", "metadata": { "editable": true }, @@ -2016,7 +2002,7 @@ }, { "cell_type": "markdown", - "id": "4e915a2e", + "id": "541fd149", "metadata": { "editable": true }, @@ -2029,7 +2015,7 @@ }, { "cell_type": "markdown", - "id": "80ce850f", + "id": "8ebbbb5c", "metadata": { "editable": true }, @@ -2041,7 +2027,7 @@ }, { "cell_type": "markdown", - "id": "a18b212a", + "id": "c290853b", "metadata": { "editable": true }, @@ -2052,7 +2038,7 @@ }, { "cell_type": "markdown", - "id": "6c6cba47", + "id": "83ef2fa9", "metadata": { "editable": true }, @@ -2068,7 +2054,7 @@ { "cell_type": "code", "execution_count": 22, - "id": "f936cb45", + "id": "954eddcb", "metadata": { "collapsed": false, "editable": true @@ -2102,7 +2088,7 @@ }, { "cell_type": "markdown", - "id": "78ee572c", + "id": "9ea31a31", "metadata": { "editable": true }, @@ -2112,7 +2098,7 @@ }, { "cell_type": "markdown", - "id": "f0637d69", + "id": "a89240ef", "metadata": { "editable": true }, @@ -2127,7 +2113,7 @@ }, { "cell_type": "markdown", - "id": "368385c7", + "id": "99674132", "metadata": { "editable": true }, @@ -2139,7 +2125,7 @@ }, { "cell_type": "markdown", - "id": "6bf8f4fe", + "id": "72bd1412", "metadata": { "editable": true }, @@ -2149,7 +2135,7 @@ }, { "cell_type": "markdown", - "id": "e8d46ebb", + "id": "bd0458fd", "metadata": { "editable": true }, @@ -2165,7 +2151,7 @@ { "cell_type": "code", "execution_count": 23, - "id": "fb4286ec", + "id": "433f173f", "metadata": { "collapsed": false, "editable": true @@ -2182,7 +2168,7 @@ }, { "cell_type": "markdown", - "id": "45ea44ea", + "id": "e0eb3d29", "metadata": { "editable": true }, @@ -2195,7 +2181,7 @@ { "cell_type": "code", "execution_count": 24, - "id": "4ab144ff", + "id": "811c7436", "metadata": { "collapsed": false, "editable": true @@ -2242,7 +2228,7 @@ }, { "cell_type": "markdown", - "id": "6b8d977a", + "id": "3805e3fe", "metadata": { "editable": true }, @@ -2253,7 +2239,7 @@ { "cell_type": "code", "execution_count": 25, - "id": "fb8683a0", + "id": "0256a0d8", "metadata": { "collapsed": false, "editable": true @@ -2356,7 +2342,7 @@ }, { "cell_type": "markdown", - "id": "056725ae", + "id": "83f391ff", "metadata": { "editable": true }, @@ -2370,7 +2356,7 @@ }, { "cell_type": "markdown", - "id": "4aac1b5d", + "id": "56c50b72", "metadata": { "editable": true }, @@ -2382,7 +2368,7 @@ }, { "cell_type": "markdown", - "id": "15cb88f8", + "id": "a6a7c639", "metadata": { "editable": true }, @@ -2394,7 +2380,7 @@ }, { "cell_type": "markdown", - "id": "2ddee2cf", + "id": "4c5828df", "metadata": { "editable": true }, @@ -2406,7 +2392,7 @@ }, { "cell_type": "markdown", - "id": "d4ea9f1d", + "id": "174bd42a", "metadata": { "editable": true }, @@ -2416,7 +2402,7 @@ }, { "cell_type": "markdown", - "id": "a0bc1d2c", + "id": "e66bf034", "metadata": { "editable": true }, @@ -2428,7 +2414,7 @@ }, { "cell_type": "markdown", - "id": "55cf148d", + "id": "c7c34d54", "metadata": { "editable": true }, @@ -2438,7 +2424,7 @@ }, { "cell_type": "markdown", - "id": "6542b462", + "id": "06ffb5c0", "metadata": { "editable": true }, @@ -2450,7 +2436,7 @@ }, { "cell_type": "markdown", - "id": "b6873bf9", + "id": "fd56d9b4", "metadata": { "editable": true }, @@ -2461,7 +2447,7 @@ }, { "cell_type": "markdown", - "id": "ec5e544e", + "id": "3e61139b", "metadata": { "editable": true }, @@ -2473,7 +2459,7 @@ }, { "cell_type": "markdown", - "id": "40a925fc", + "id": "a514701e", "metadata": { "editable": true }, @@ -2485,7 +2471,7 @@ }, { "cell_type": "markdown", - "id": "500e941a", + "id": "b88fbc4d", "metadata": { "editable": true }, @@ -2495,7 +2481,7 @@ }, { "cell_type": "markdown", - "id": "d5a76ef3", + "id": "f5e636e3", "metadata": { "editable": true }, @@ -2507,7 +2493,7 @@ }, { "cell_type": "markdown", - "id": "86a4a773", + "id": "00b4842c", "metadata": { "editable": true }, @@ -2519,7 +2505,7 @@ }, { "cell_type": "markdown", - "id": "26b6895c", + "id": "74df0706", "metadata": { "editable": true }, @@ -2529,7 +2515,7 @@ }, { "cell_type": "markdown", - "id": "a5bf8e8c", + "id": "cc3aa64c", "metadata": { "editable": true }, @@ -2541,7 +2527,7 @@ }, { "cell_type": "markdown", - "id": "4b5a72ad", + "id": "cd90799d", "metadata": { "editable": true }, @@ -2551,7 +2537,7 @@ }, { "cell_type": "markdown", - "id": "93c5da3f", + "id": "e2d0230d", "metadata": { "editable": true }, @@ -2563,7 +2549,7 @@ }, { "cell_type": "markdown", - "id": "4dc7035e", + "id": "899e7339", "metadata": { "editable": true }, @@ -2573,7 +2559,7 @@ }, { "cell_type": "markdown", - "id": "c1b8a4f3", + "id": "bfc7685b", "metadata": { "editable": true }, @@ -2613,7 +2599,7 @@ }, { "cell_type": "markdown", - "id": "0426f44f", + "id": "df4cbc89", "metadata": { "editable": true }, @@ -2630,7 +2616,7 @@ }, { "cell_type": "markdown", - "id": "40532b9b", + "id": "aa10407c", "metadata": { "editable": true }, @@ -2653,7 +2639,7 @@ }, { "cell_type": "markdown", - "id": "8529a875", + "id": "6f04a106", "metadata": { "editable": true }, @@ -2670,7 +2656,7 @@ }, { "cell_type": "markdown", - "id": "33f2fe2d", + "id": "c0b5f228", "metadata": { "editable": true }, @@ -2689,7 +2675,7 @@ }, { "cell_type": "markdown", - "id": "b8803cd0", + "id": "c86ac4dd", "metadata": { "editable": true }, @@ -2700,7 +2686,7 @@ }, { "cell_type": "markdown", - "id": "532710d8", + "id": "79278942", "metadata": { "editable": true }, @@ -2712,7 +2698,7 @@ }, { "cell_type": "markdown", - "id": "feeee6da", + "id": "ce786427", "metadata": { "editable": true }, @@ -2730,7 +2716,7 @@ }, { "cell_type": "markdown", - "id": "606151fd", + "id": "ffb08a69", "metadata": { "editable": true }, @@ -2746,7 +2732,7 @@ }, { "cell_type": "markdown", - "id": "9431290c", + "id": "1dad7d34", "metadata": { "editable": true }, @@ -2758,7 +2744,7 @@ }, { "cell_type": "markdown", - "id": "817c92eb", + "id": "c34dd2ec", "metadata": { "editable": true }, @@ -2768,7 +2754,7 @@ }, { "cell_type": "markdown", - "id": "ff7809c6", + "id": "f3c90637", "metadata": { "editable": true }, @@ -2783,7 +2769,7 @@ }, { "cell_type": "markdown", - "id": "c8b60474", + "id": "1b433bc1", "metadata": { "editable": true }, @@ -2795,7 +2781,7 @@ }, { "cell_type": "markdown", - "id": "1b0cf41c", + "id": "7002b705", "metadata": { "editable": true }, @@ -2805,7 +2791,7 @@ }, { "cell_type": "markdown", - "id": "84596440", + "id": "983c2ef5", "metadata": { "editable": true }, @@ -2817,7 +2803,7 @@ }, { "cell_type": "markdown", - "id": "3651c4b2", + "id": "1aaf2fd5", "metadata": { "editable": true }, @@ -2827,7 +2813,7 @@ }, { "cell_type": "markdown", - "id": "340923c0", + "id": "5f6fc7b1", "metadata": { "editable": true }, @@ -2839,7 +2825,7 @@ }, { "cell_type": "markdown", - "id": "2951f8cf", + "id": "2c8d0ffb", "metadata": { "editable": true }, @@ -2851,7 +2837,7 @@ }, { "cell_type": "markdown", - "id": "eed2368e", + "id": "cd36a201", "metadata": { "editable": true }, @@ -2866,7 +2852,7 @@ }, { "cell_type": "markdown", - "id": "bdbd7653", + "id": "115d6ba0", "metadata": { "editable": true }, @@ -2877,7 +2863,7 @@ }, { "cell_type": "markdown", - "id": "123e2787", + "id": "37beedc1", "metadata": { "editable": true }, @@ -2897,7 +2883,7 @@ }, { "cell_type": "markdown", - "id": "5f77a47e", + "id": "923e40ed", "metadata": { "editable": true }, @@ -2909,7 +2895,7 @@ }, { "cell_type": "markdown", - "id": "4fa7c9b0", + "id": "f49c6a9a", "metadata": { "editable": true }, @@ -2919,7 +2905,7 @@ }, { "cell_type": "markdown", - "id": "ac15c1af", + "id": "3a1ab10c", "metadata": { "editable": true }, @@ -2931,7 +2917,7 @@ }, { "cell_type": "markdown", - "id": "73fd82c2", + "id": "f5a7ee66", "metadata": { "editable": true }, @@ -2960,7 +2946,7 @@ }, { "cell_type": "markdown", - "id": "a0ca7478", + "id": "8f7c75e4", "metadata": { "editable": true }, @@ -2987,7 +2973,7 @@ }, { "cell_type": "markdown", - "id": "f5f824e4", + "id": "e3d18a00", "metadata": { "editable": true }, @@ -2998,7 +2984,7 @@ { "cell_type": "code", "execution_count": 26, - "id": "38251168", + "id": "69438b5f", "metadata": { "collapsed": false, "editable": true @@ -3038,7 +3024,7 @@ }, { "cell_type": "markdown", - "id": "d0dad300", + "id": "86983ba4", "metadata": { "editable": true }, @@ -3055,7 +3041,7 @@ }, { "cell_type": "markdown", - "id": "e7d5d587", + "id": "75ef3bda", "metadata": { "editable": true }, @@ -3078,7 +3064,7 @@ }, { "cell_type": "markdown", - "id": "86e39f46", + "id": "2c35c775", "metadata": { "editable": true }, @@ -3092,7 +3078,7 @@ }, { "cell_type": "markdown", - "id": "fc865bda", + "id": "97e3341d", "metadata": { "editable": true }, @@ -3111,7 +3097,7 @@ }, { "cell_type": "markdown", - "id": "34ac7dbe", + "id": "20c72273", "metadata": { "editable": true }, @@ -3121,7 +3107,7 @@ }, { "cell_type": "markdown", - "id": "ce9ed40b", + "id": "221a4748", "metadata": { "editable": true }, @@ -3133,7 +3119,7 @@ }, { "cell_type": "markdown", - "id": "e0c1753f", + "id": "14eafee7", "metadata": { "editable": true }, @@ -3147,7 +3133,7 @@ }, { "cell_type": "markdown", - "id": "b2f55210", + "id": "e2f49ffc", "metadata": { "editable": true }, @@ -3159,7 +3145,7 @@ }, { "cell_type": "markdown", - "id": "993d236a", + "id": "dee05f1b", "metadata": { "editable": true }, @@ -3169,7 +3155,7 @@ }, { "cell_type": "markdown", - "id": "0d00c733", + "id": "fe76b78a", "metadata": { "editable": true }, @@ -3181,7 +3167,7 @@ }, { "cell_type": "markdown", - "id": "0065169f", + "id": "bfa17979", "metadata": { "editable": true }, @@ -3198,7 +3184,7 @@ }, { "cell_type": "markdown", - "id": "17559f8b", + "id": "a9807675", "metadata": { "editable": true }, @@ -3208,7 +3194,7 @@ }, { "cell_type": "markdown", - "id": "bb8f29a5", + "id": "a9462fed", "metadata": { "editable": true }, @@ -3224,7 +3210,7 @@ }, { "cell_type": "markdown", - "id": "a06d444d", + "id": "0c955419", "metadata": { "editable": true }, @@ -3234,7 +3220,7 @@ }, { "cell_type": "markdown", - "id": "d540ec4b", + "id": "83c3303f", "metadata": { "editable": true }, @@ -3250,7 +3236,7 @@ }, { "cell_type": "markdown", - "id": "b1a6615b", + "id": "221e6d9f", "metadata": { "editable": true }, @@ -3260,7 +3246,7 @@ }, { "cell_type": "markdown", - "id": "51a48167", + "id": "3d2a0896", "metadata": { "editable": true }, @@ -3276,7 +3262,7 @@ }, { "cell_type": "markdown", - "id": "1b7f0fed", + "id": "4229708b", "metadata": { "editable": true }, @@ -3286,7 +3272,7 @@ }, { "cell_type": "markdown", - "id": "9abf9e55", + "id": "916d2d1b", "metadata": { "editable": true }, @@ -3303,7 +3289,7 @@ }, { "cell_type": "markdown", - "id": "32d9652b", + "id": "4453ac66", "metadata": { "editable": true }, @@ -3315,7 +3301,7 @@ }, { "cell_type": "markdown", - "id": "2a465226", + "id": "8e7f3e74", "metadata": { "editable": true }, @@ -3327,7 +3313,7 @@ }, { "cell_type": "markdown", - "id": "8ac566da", + "id": "adcd21eb", "metadata": { "editable": true }, @@ -3339,7 +3325,7 @@ }, { "cell_type": "markdown", - "id": "9f92ca58", + "id": "a394b3f4", "metadata": { "editable": true }, @@ -3349,7 +3335,7 @@ }, { "cell_type": "markdown", - "id": "2e4790c8", + "id": "ce12cfc0", "metadata": { "editable": true }, @@ -3361,7 +3347,7 @@ }, { "cell_type": "markdown", - "id": "2b0a1201", + "id": "c83e5500", "metadata": { "editable": true }, @@ -3373,7 +3359,7 @@ }, { "cell_type": "markdown", - "id": "1d856b1e", + "id": "0af9db24", "metadata": { "editable": true }, @@ -3385,7 +3371,7 @@ }, { "cell_type": "markdown", - "id": "7d734884", + "id": "fe461d27", "metadata": { "editable": true }, @@ -3395,7 +3381,7 @@ }, { "cell_type": "markdown", - "id": "282f629e", + "id": "f3e67596", "metadata": { "editable": true }, @@ -3407,7 +3393,7 @@ }, { "cell_type": "markdown", - "id": "1c92b30f", + "id": "ad848da0", "metadata": { "editable": true }, @@ -3417,7 +3403,7 @@ }, { "cell_type": "markdown", - "id": "823f783c", + "id": "2c371aba", "metadata": { "editable": true }, @@ -3429,7 +3415,7 @@ }, { "cell_type": "markdown", - "id": "4be0525b", + "id": "3d1b5fd7", "metadata": { "editable": true }, @@ -3443,7 +3429,7 @@ }, { "cell_type": "markdown", - "id": "6c460cbb", + "id": "5dd54f0e", "metadata": { "editable": true }, @@ -3455,7 +3441,7 @@ }, { "cell_type": "markdown", - "id": "6e876e2b", + "id": "ee587e89", "metadata": { "editable": true }, @@ -3467,7 +3453,7 @@ }, { "cell_type": "markdown", - "id": "dd35e114", + "id": "c6e29c61", "metadata": { "editable": true }, @@ -3477,7 +3463,7 @@ }, { "cell_type": "markdown", - "id": "e41e4b24", + "id": "92c5fd54", "metadata": { "editable": true }, @@ -3489,7 +3475,7 @@ }, { "cell_type": "markdown", - "id": "a660f050", + "id": "0c7feb8e", "metadata": { "editable": true }, @@ -3500,7 +3486,7 @@ }, { "cell_type": "markdown", - "id": "1bfed6c0", + "id": "b39cb6c5", "metadata": { "editable": true }, @@ -3512,7 +3498,7 @@ }, { "cell_type": "markdown", - "id": "079641aa", + "id": "19f56051", "metadata": { "editable": true }, @@ -3522,7 +3508,7 @@ }, { "cell_type": "markdown", - "id": "1c2ba9ba", + "id": "767527bf", "metadata": { "editable": true }, @@ -3534,7 +3520,7 @@ }, { "cell_type": "markdown", - "id": "c90c925b", + "id": "38c3b6c5", "metadata": { "editable": true }, @@ -3544,7 +3530,7 @@ }, { "cell_type": "markdown", - "id": "096d7272", + "id": "a451be21", "metadata": { "editable": true }, @@ -3556,7 +3542,7 @@ }, { "cell_type": "markdown", - "id": "ab428dfa", + "id": "f444fbcf", "metadata": { "editable": true }, @@ -3567,7 +3553,7 @@ }, { "cell_type": "markdown", - "id": "32676667", + "id": "1e60bc66", "metadata": { "editable": true }, @@ -3579,7 +3565,7 @@ }, { "cell_type": "markdown", - "id": "ff6a8c71", + "id": "0af64d6d", "metadata": { "editable": true }, @@ -3597,7 +3583,7 @@ }, { "cell_type": "markdown", - "id": "23c0d9f1", + "id": "32c90048", "metadata": { "editable": true }, @@ -3613,7 +3599,7 @@ }, { "cell_type": "markdown", - "id": "32aa4f0c", + "id": "eaa30f71", "metadata": { "editable": true }, @@ -3625,7 +3611,7 @@ }, { "cell_type": "markdown", - "id": "2dad0497", + "id": "420a67ad", "metadata": { "editable": true }, @@ -3637,7 +3623,7 @@ }, { "cell_type": "markdown", - "id": "2dc59fbf", + "id": "feca2f69", "metadata": { "editable": true }, @@ -3649,7 +3635,7 @@ }, { "cell_type": "markdown", - "id": "7cdbf049", + "id": "6872d66a", "metadata": { "editable": true }, @@ -3662,7 +3648,7 @@ }, { "cell_type": "markdown", - "id": "59a9818e", + "id": "bc5ee8f5", "metadata": { "editable": true }, @@ -3678,7 +3664,7 @@ }, { "cell_type": "markdown", - "id": "02c8612d", + "id": "60a8b1d6", "metadata": { "editable": true }, @@ -3692,7 +3678,7 @@ }, { "cell_type": "markdown", - "id": "e3918f3a", + "id": "5ac92d41", "metadata": { "editable": true }, @@ -3702,7 +3688,7 @@ }, { "cell_type": "markdown", - "id": "7c12adaa", + "id": "a9b059cd", "metadata": { "editable": true }, @@ -3714,7 +3700,7 @@ }, { "cell_type": "markdown", - "id": "a90918b1", + "id": "bb8c2adc", "metadata": { "editable": true }, @@ -3724,7 +3710,7 @@ }, { "cell_type": "markdown", - "id": "b98d4711", + "id": "b3427bf1", "metadata": { "editable": true }, @@ -3736,7 +3722,7 @@ }, { "cell_type": "markdown", - "id": "909544f4", + "id": "fe7a128a", "metadata": { "editable": true }, @@ -3746,7 +3732,7 @@ }, { "cell_type": "markdown", - "id": "eda7c78a", + "id": "2c720705", "metadata": { "editable": true }, @@ -3760,7 +3746,7 @@ }, { "cell_type": "markdown", - "id": "97f43eaf", + "id": "44cef833", "metadata": { "editable": true }, @@ -3777,7 +3763,7 @@ }, { "cell_type": "markdown", - "id": "151a02db", + "id": "c86aca20", "metadata": { "editable": true }, @@ -3793,7 +3779,7 @@ }, { "cell_type": "markdown", - "id": "e50cecd3", + "id": "5d9914c7", "metadata": { "editable": true }, @@ -3805,7 +3791,7 @@ }, { "cell_type": "markdown", - "id": "5fff7114", + "id": "176bf13b", "metadata": { "editable": true }, @@ -3818,7 +3804,7 @@ }, { "cell_type": "markdown", - "id": "36ea2210", + "id": "c242e5fa", "metadata": { "editable": true }, @@ -3832,7 +3818,7 @@ }, { "cell_type": "markdown", - "id": "5ad8fe9e", + "id": "2f7b23be", "metadata": { "editable": true }, @@ -3842,7 +3828,7 @@ }, { "cell_type": "markdown", - "id": "bebd7b45", + "id": "0cf91285", "metadata": { "editable": true }, @@ -3855,7 +3841,7 @@ }, { "cell_type": "markdown", - "id": "053d3619", + "id": "e4d93a26", "metadata": { "editable": true }, @@ -3874,7 +3860,7 @@ }, { "cell_type": "markdown", - "id": "596c0971", + "id": "5a0ae813", "metadata": { "editable": true }, @@ -3886,7 +3872,7 @@ }, { "cell_type": "markdown", - "id": "d17344e3", + "id": "72018907", "metadata": { "editable": true }, @@ -3898,7 +3884,7 @@ }, { "cell_type": "markdown", - "id": "b241bb6c", + "id": "020de5b8", "metadata": { "editable": true }, @@ -3908,7 +3894,7 @@ }, { "cell_type": "markdown", - "id": "21fc65b4", + "id": "a30ee045", "metadata": { "editable": true }, @@ -3920,7 +3906,7 @@ }, { "cell_type": "markdown", - "id": "9ce3fb65", + "id": "027b8e22", "metadata": { "editable": true }, @@ -3933,7 +3919,7 @@ }, { "cell_type": "markdown", - "id": "52ccc9a5", + "id": "8831de1d", "metadata": { "editable": true }, @@ -3952,7 +3938,7 @@ }, { "cell_type": "markdown", - "id": "38fda0bc", + "id": "5b408358", "metadata": { "editable": true }, @@ -3962,7 +3948,7 @@ }, { "cell_type": "markdown", - "id": "9150dc48", + "id": "ad714813", "metadata": { "editable": true }, @@ -3981,7 +3967,7 @@ }, { "cell_type": "markdown", - "id": "01af4a7f", + "id": "82d0f4ae", "metadata": { "editable": true }, @@ -3999,7 +3985,7 @@ }, { "cell_type": "markdown", - "id": "13471a6a", + "id": "e9fe7802", "metadata": { "editable": true }, @@ -4013,7 +3999,7 @@ }, { "cell_type": "markdown", - "id": "2af3e8fc", + "id": "d0ecdb3f", "metadata": { "editable": true }, @@ -4028,7 +4014,7 @@ { "cell_type": "code", "execution_count": 27, - "id": "3ab62cb4", + "id": "e08ab5c0", "metadata": { "collapsed": false, "editable": true @@ -4049,7 +4035,7 @@ }, { "cell_type": "markdown", - "id": "bdb2cb62", + "id": "674e0a39", "metadata": { "editable": true }, @@ -4066,7 +4052,7 @@ { "cell_type": "code", "execution_count": 28, - "id": "47e08b89", + "id": "b116a39b", "metadata": { "collapsed": false, "editable": true @@ -4098,7 +4084,7 @@ }, { "cell_type": "markdown", - "id": "fdd0f33e", + "id": "2e02d35e", "metadata": { "editable": true }, @@ -4112,7 +4098,7 @@ }, { "cell_type": "markdown", - "id": "a6146784", + "id": "46562525", "metadata": { "editable": true }, @@ -4125,7 +4111,7 @@ { "cell_type": "code", "execution_count": 29, - "id": "a53c5cc6", + "id": "ddcceacc", "metadata": { "collapsed": false, "editable": true @@ -4150,7 +4136,7 @@ }, { "cell_type": "markdown", - "id": "4ede1141", + "id": "e35ffa7c", "metadata": { "editable": true }, @@ -4160,7 +4146,7 @@ }, { "cell_type": "markdown", - "id": "4ae526bb", + "id": "1bbd2d9b", "metadata": { "editable": true }, @@ -4171,7 +4157,7 @@ { "cell_type": "code", "execution_count": 30, - "id": "33cad860", + "id": "2f4a549a", "metadata": { "collapsed": false, "editable": true @@ -4225,7 +4211,7 @@ }, { "cell_type": "markdown", - "id": "b406a48a", + "id": "0636cde4", "metadata": { "editable": true }, @@ -4242,7 +4228,7 @@ }, { "cell_type": "markdown", - "id": "149b55a8", + "id": "bf709f33", "metadata": { "editable": true }, @@ -4254,7 +4240,7 @@ }, { "cell_type": "markdown", - "id": "fcfb2992", + "id": "8dfd3988", "metadata": { "editable": true }, @@ -4266,7 +4252,7 @@ }, { "cell_type": "markdown", - "id": "a0863a01", + "id": "d410839a", "metadata": { "editable": true }, @@ -4276,7 +4262,7 @@ }, { "cell_type": "markdown", - "id": "a1e44c03", + "id": "838cbc10", "metadata": { "editable": true }, @@ -4293,7 +4279,7 @@ }, { "cell_type": "markdown", - "id": "57feea7c", + "id": "a52bc2d6", "metadata": { "editable": true }, @@ -4303,7 +4289,7 @@ }, { "cell_type": "markdown", - "id": "1b862ff7", + "id": "31a9e0cc", "metadata": { "editable": true }, @@ -4318,7 +4304,7 @@ }, { "cell_type": "markdown", - "id": "0f8fe30e", + "id": "280c65f6", "metadata": { "editable": true }, @@ -4328,7 +4314,7 @@ }, { "cell_type": "markdown", - "id": "64b5ac2a", + "id": "65c53a03", "metadata": { "editable": true }, @@ -4342,7 +4328,7 @@ }, { "cell_type": "markdown", - "id": "657466bd", + "id": "da50d152", "metadata": { "editable": true }, @@ -4354,7 +4340,7 @@ }, { "cell_type": "markdown", - "id": "98fc3a82", + "id": "3b273035", "metadata": { "editable": true }, @@ -4366,7 +4352,7 @@ }, { "cell_type": "markdown", - "id": "5a70feef", + "id": "02a447e5", "metadata": { "editable": true }, @@ -4378,7 +4364,7 @@ }, { "cell_type": "markdown", - "id": "aefc9f52", + "id": "879e0d71", "metadata": { "editable": true }, @@ -4388,7 +4374,7 @@ }, { "cell_type": "markdown", - "id": "227adc50", + "id": "7fad5ef6", "metadata": { "editable": true }, @@ -4400,7 +4386,7 @@ }, { "cell_type": "markdown", - "id": "535fe860", + "id": "dd0ae36b", "metadata": { "editable": true }, @@ -4410,7 +4396,7 @@ }, { "cell_type": "markdown", - "id": "115d3697", + "id": "d1997fa4", "metadata": { "editable": true }, @@ -4427,7 +4413,7 @@ }, { "cell_type": "markdown", - "id": "89838d8d", + "id": "987a899c", "metadata": { "editable": true }, @@ -4437,7 +4423,7 @@ }, { "cell_type": "markdown", - "id": "46d327c2", + "id": "1cf47e49", "metadata": { "editable": true }, @@ -4449,7 +4435,7 @@ }, { "cell_type": "markdown", - "id": "06339014", + "id": "bac226f1", "metadata": { "editable": true }, @@ -4459,7 +4445,7 @@ }, { "cell_type": "markdown", - "id": "4e0d3fd1", + "id": "67ccbc9e", "metadata": { "editable": true }, @@ -4471,7 +4457,7 @@ }, { "cell_type": "markdown", - "id": "056f9d49", + "id": "f14e52e5", "metadata": { "editable": true }, @@ -4485,7 +4471,7 @@ }, { "cell_type": "markdown", - "id": "d3a482c9", + "id": "6c97f17d", "metadata": { "editable": true }, @@ -4497,7 +4483,7 @@ }, { "cell_type": "markdown", - "id": "784798c7", + "id": "9ead5fe3", "metadata": { "editable": true }, @@ -4519,7 +4505,7 @@ }, { "cell_type": "markdown", - "id": "55d2d9e5", + "id": "ea907858", "metadata": { "editable": true }, @@ -4531,7 +4517,7 @@ }, { "cell_type": "markdown", - "id": "ea49bdbd", + "id": "6dfd4616", "metadata": { "editable": true }, @@ -4546,7 +4532,7 @@ }, { "cell_type": "markdown", - "id": "010830dd", + "id": "627ea3dc", "metadata": { "editable": true }, @@ -4558,7 +4544,7 @@ }, { "cell_type": "markdown", - "id": "0753e93e", + "id": "2d14aa81", "metadata": { "editable": true }, @@ -4570,7 +4556,7 @@ }, { "cell_type": "markdown", - "id": "5acfe108", + "id": "4d72f6e4", "metadata": { "editable": true }, @@ -4580,7 +4566,7 @@ }, { "cell_type": "markdown", - "id": "0d558c44", + "id": "20d513e2", "metadata": { "editable": true }, @@ -4592,7 +4578,7 @@ }, { "cell_type": "markdown", - "id": "032564e7", + "id": "f839540c", "metadata": { "editable": true }, @@ -4602,7 +4588,7 @@ }, { "cell_type": "markdown", - "id": "4de10b38", + "id": "6599fdd9", "metadata": { "editable": true }, @@ -4614,7 +4600,7 @@ }, { "cell_type": "markdown", - "id": "8dc9e551", + "id": "61046410", "metadata": { "editable": true }, @@ -4624,7 +4610,7 @@ }, { "cell_type": "markdown", - "id": "98241069", + "id": "4c6703cb", "metadata": { "editable": true }, @@ -4636,7 +4622,7 @@ }, { "cell_type": "markdown", - "id": "ca757ff9", + "id": "036d4e19", "metadata": { "editable": true }, @@ -4653,7 +4639,7 @@ }, { "cell_type": "markdown", - "id": "0f04b41a", + "id": "cebd1928", "metadata": { "editable": true }, @@ -4666,7 +4652,7 @@ }, { "cell_type": "markdown", - "id": "d2f050a3", + "id": "1b77a77c", "metadata": { "editable": true }, @@ -4678,7 +4664,7 @@ }, { "cell_type": "markdown", - "id": "bc3ff38a", + "id": "d517c9e5", "metadata": { "editable": true }, @@ -4688,7 +4674,7 @@ }, { "cell_type": "markdown", - "id": "b82b46ba", + "id": "57b8d925", "metadata": { "editable": true }, @@ -4701,7 +4687,7 @@ }, { "cell_type": "markdown", - "id": "160ce640", + "id": "bfe8deea", "metadata": { "editable": true }, @@ -4711,7 +4697,7 @@ }, { "cell_type": "markdown", - "id": "19b97ea4", + "id": "05d514b0", "metadata": { "editable": true }, @@ -4723,7 +4709,7 @@ }, { "cell_type": "markdown", - "id": "8219c09a", + "id": "7dadcb05", "metadata": { "editable": true }, @@ -4736,7 +4722,7 @@ }, { "cell_type": "markdown", - "id": "4607e793", + "id": "7d532953", "metadata": { "editable": true }, @@ -4749,7 +4735,7 @@ }, { "cell_type": "markdown", - "id": "fccab9af", + "id": "cf2e4274", "metadata": { "editable": true }, @@ -4761,7 +4747,7 @@ }, { "cell_type": "markdown", - "id": "0c4dbdcd", + "id": "bdcec14e", "metadata": { "editable": true }, @@ -4773,7 +4759,7 @@ }, { "cell_type": "markdown", - "id": "944d1a58", + "id": "88eb65f4", "metadata": { "editable": true }, @@ -4783,7 +4769,7 @@ }, { "cell_type": "markdown", - "id": "acf74694", + "id": "c038ea32", "metadata": { "editable": true }, @@ -4796,7 +4782,7 @@ }, { "cell_type": "markdown", - "id": "e2b50541", + "id": "cdea3904", "metadata": { "editable": true }, @@ -4808,7 +4794,7 @@ }, { "cell_type": "markdown", - "id": "416bc2b7", + "id": "1a6373a5", "metadata": { "editable": true }, @@ -4820,7 +4806,7 @@ }, { "cell_type": "markdown", - "id": "21ee3cee", + "id": "b3adc7fc", "metadata": { "editable": true }, @@ -4832,7 +4818,7 @@ }, { "cell_type": "markdown", - "id": "6e906d12", + "id": "d7ca9ba7", "metadata": { "editable": true }, @@ -4844,7 +4830,7 @@ }, { "cell_type": "markdown", - "id": "8548aa98", + "id": "06012674", "metadata": { "editable": true }, @@ -4858,7 +4844,7 @@ }, { "cell_type": "markdown", - "id": "214d7c50", + "id": "48b3151b", "metadata": { "editable": true }, @@ -4870,7 +4856,7 @@ }, { "cell_type": "markdown", - "id": "70ecc6ae", + "id": "a9a36106", "metadata": { "editable": true }, @@ -4880,7 +4866,7 @@ }, { "cell_type": "markdown", - "id": "8234faa0", + "id": "95fda605", "metadata": { "editable": true }, @@ -4892,7 +4878,7 @@ }, { "cell_type": "markdown", - "id": "bfe1b41a", + "id": "cacb77bc", "metadata": { "editable": true }, @@ -4904,7 +4890,7 @@ }, { "cell_type": "markdown", - "id": "5cc43268", + "id": "e4716af8", "metadata": { "editable": true }, @@ -4916,7 +4902,7 @@ }, { "cell_type": "markdown", - "id": "dc2612b3", + "id": "cac731cb", "metadata": { "editable": true }, @@ -4928,7 +4914,7 @@ }, { "cell_type": "markdown", - "id": "657c789e", + "id": "b8b1ad89", "metadata": { "editable": true }, @@ -4940,7 +4926,7 @@ }, { "cell_type": "markdown", - "id": "a3bad5d2", + "id": "6d3a9f74", "metadata": { "editable": true }, @@ -4959,7 +4945,7 @@ }, { "cell_type": "markdown", - "id": "e2e2fc68", + "id": "b79fb043", "metadata": { "editable": true }, @@ -4971,7 +4957,7 @@ }, { "cell_type": "markdown", - "id": "374ff20e", + "id": "351e8cf3", "metadata": { "editable": true }, @@ -4981,7 +4967,7 @@ }, { "cell_type": "markdown", - "id": "da09d41e", + "id": "0c1b38df", "metadata": { "editable": true }, @@ -4993,7 +4979,7 @@ }, { "cell_type": "markdown", - "id": "a73ae19a", + "id": "466d8aff", "metadata": { "editable": true }, @@ -5003,7 +4989,7 @@ }, { "cell_type": "markdown", - "id": "bbb0e3c0", + "id": "8e19edce", "metadata": { "editable": true }, @@ -5015,7 +5001,7 @@ }, { "cell_type": "markdown", - "id": "51489d15", + "id": "ff01cea8", "metadata": { "editable": true }, @@ -5027,7 +5013,7 @@ }, { "cell_type": "markdown", - "id": "7e1c308b", + "id": "4b2d8e64", "metadata": { "editable": true }, @@ -5043,7 +5029,7 @@ }, { "cell_type": "markdown", - "id": "f8de0f57", + "id": "b4af2390", "metadata": { "editable": true }, @@ -5055,7 +5041,7 @@ }, { "cell_type": "markdown", - "id": "d2cb6d29", + "id": "df07f076", "metadata": { "editable": true }, @@ -5067,7 +5053,7 @@ }, { "cell_type": "markdown", - "id": "1687106e", + "id": "c288e6cc", "metadata": { "editable": true }, @@ -5077,7 +5063,7 @@ }, { "cell_type": "markdown", - "id": "84ae6921", + "id": "cb9a7b39", "metadata": { "editable": true }, @@ -5089,7 +5075,7 @@ }, { "cell_type": "markdown", - "id": "a18bbb0b", + "id": "da106ea1", "metadata": { "editable": true }, @@ -5099,7 +5085,7 @@ }, { "cell_type": "markdown", - "id": "5cd013a1", + "id": "de16c65c", "metadata": { "editable": true }, @@ -5111,7 +5097,7 @@ }, { "cell_type": "markdown", - "id": "f369ea50", + "id": "d0c505e8", "metadata": { "editable": true }, @@ -5128,7 +5114,7 @@ }, { "cell_type": "markdown", - "id": "dbc46dac", + "id": "5649fd07", "metadata": { "editable": true }, @@ -5140,7 +5126,7 @@ }, { "cell_type": "markdown", - "id": "67c74718", + "id": "221146bb", "metadata": { "editable": true }, @@ -5152,7 +5138,7 @@ }, { "cell_type": "markdown", - "id": "4c03c75b", + "id": "0b6b1111", "metadata": { "editable": true }, @@ -5162,7 +5148,7 @@ }, { "cell_type": "markdown", - "id": "d51e1346", + "id": "116a85ea", "metadata": { "editable": true }, @@ -5174,7 +5160,7 @@ }, { "cell_type": "markdown", - "id": "3e83948b", + "id": "d1140a8d", "metadata": { "editable": true }, @@ -5184,7 +5170,7 @@ }, { "cell_type": "markdown", - "id": "0dd2fc65", + "id": "d429e163", "metadata": { "editable": true }, @@ -5196,7 +5182,7 @@ }, { "cell_type": "markdown", - "id": "ff8fbae7", + "id": "7a44eb3c", "metadata": { "editable": true }, @@ -5206,7 +5192,7 @@ }, { "cell_type": "markdown", - "id": "bc8ce3ca", + "id": "79edfc40", "metadata": { "editable": true }, @@ -5218,7 +5204,7 @@ }, { "cell_type": "markdown", - "id": "f0b4e0cc", + "id": "17b4ee35", "metadata": { "editable": true }, @@ -5228,7 +5214,7 @@ }, { "cell_type": "markdown", - "id": "f51a973b", + "id": "cfec8c09", "metadata": { "editable": true }, @@ -5240,7 +5226,7 @@ }, { "cell_type": "markdown", - "id": "63682d83", + "id": "d643f208", "metadata": { "editable": true }, @@ -5309,7 +5295,7 @@ }, { "cell_type": "markdown", - "id": "44645870", + "id": "861cc690", "metadata": { "editable": true }, @@ -5323,7 +5309,7 @@ { "cell_type": "code", "execution_count": 31, - "id": "419d6ce7", + "id": "36d583bb", "metadata": { "collapsed": false, "editable": true @@ -5336,7 +5322,7 @@ }, { "cell_type": "markdown", - "id": "5a2ff45c", + "id": "a036b038", "metadata": { "editable": true }, @@ -5350,7 +5336,7 @@ }, { "cell_type": "markdown", - "id": "cfdb14a7", + "id": "63e8fc1a", "metadata": { "editable": true }, @@ -5363,7 +5349,7 @@ }, { "cell_type": "markdown", - "id": "6589944b", + "id": "bc103f90", "metadata": { "editable": true }, @@ -5374,7 +5360,7 @@ }, { "cell_type": "markdown", - "id": "2fe64c31", + "id": "cc09af8b", "metadata": { "editable": true }, @@ -5386,7 +5372,7 @@ }, { "cell_type": "markdown", - "id": "7aa7b27a", + "id": "db0af726", "metadata": { "editable": true }, @@ -5396,7 +5382,7 @@ }, { "cell_type": "markdown", - "id": "af75a4c6", + "id": "113ba6e2", "metadata": { "editable": true }, @@ -5408,7 +5394,7 @@ }, { "cell_type": "markdown", - "id": "5eb599ea", + "id": "217bba68", "metadata": { "editable": true }, @@ -5424,7 +5410,7 @@ { "cell_type": "code", "execution_count": 32, - "id": "4ed9167a", + "id": "9db08d7c", "metadata": { "collapsed": false, "editable": true @@ -5475,7 +5461,7 @@ }, { "cell_type": "markdown", - "id": "28e4a11c", + "id": "b8138b07", "metadata": { "editable": true }, @@ -5485,7 +5471,7 @@ }, { "cell_type": "markdown", - "id": "1ac51d89", + "id": "a95a9e55", "metadata": { "editable": true }, @@ -5531,7 +5517,7 @@ { "cell_type": "code", "execution_count": 33, - "id": "9d7a34d3", + "id": "c0b27a62", "metadata": { "collapsed": false, "editable": true @@ -5544,7 +5530,7 @@ }, { "cell_type": "markdown", - "id": "32f9f5ab", + "id": "e69d081c", "metadata": { "editable": true }, @@ -5555,7 +5541,7 @@ { "cell_type": "code", "execution_count": 34, - "id": "9bc9826c", + "id": "1e21f3bc", "metadata": { "collapsed": false, "editable": true @@ -5570,7 +5556,7 @@ }, { "cell_type": "markdown", - "id": "23ec3500", + "id": "7c290025", "metadata": { "editable": true }, @@ -5588,7 +5574,7 @@ { "cell_type": "code", "execution_count": 35, - "id": "9de87124", + "id": "c83dad3a", "metadata": { "collapsed": false, "editable": true @@ -5605,7 +5591,7 @@ }, { "cell_type": "markdown", - "id": "b879c3e8", + "id": "60dce5d0", "metadata": { "editable": true }, @@ -5615,7 +5601,7 @@ }, { "cell_type": "markdown", - "id": "86795200", + "id": "1958f713", "metadata": { "editable": true }, @@ -5626,7 +5612,7 @@ }, { "cell_type": "markdown", - "id": "5ef7cd1a", + "id": "9b4a3732", "metadata": { "editable": true }, @@ -5637,7 +5623,7 @@ }, { "cell_type": "markdown", - "id": "5a607c80", + "id": "1de0cd14", "metadata": { "editable": true }, @@ -5648,7 +5634,7 @@ }, { "cell_type": "markdown", - "id": "f01bfffb", + "id": "346c7eb2", "metadata": { "editable": true }, @@ -5671,7 +5657,7 @@ { "cell_type": "code", "execution_count": 36, - "id": "a10a0c7b", + "id": "763a9d9c", "metadata": { "collapsed": false, "editable": true @@ -5684,7 +5670,7 @@ }, { "cell_type": "markdown", - "id": "5a3f95a5", + "id": "0ffd69b3", "metadata": { "editable": true }, @@ -5699,7 +5685,7 @@ { "cell_type": "code", "execution_count": 37, - "id": "ae42653e", + "id": "e02ee496", "metadata": { "collapsed": false, "editable": true @@ -5779,7 +5765,7 @@ }, { "cell_type": "markdown", - "id": "15088d89", + "id": "1edbeb58", "metadata": { "editable": true }, @@ -5794,7 +5780,7 @@ }, { "cell_type": "markdown", - "id": "bd5959cb", + "id": "c2231042", "metadata": { "editable": true }, @@ -5807,7 +5793,7 @@ }, { "cell_type": "markdown", - "id": "673ce1ea", + "id": "e76e4c11", "metadata": { "editable": true }, @@ -5818,7 +5804,7 @@ }, { "cell_type": "markdown", - "id": "65a5f4fb", + "id": "a963aecb", "metadata": { "editable": true }, @@ -5830,7 +5816,7 @@ }, { "cell_type": "markdown", - "id": "ddca5918", + "id": "223eb14a", "metadata": { "editable": true }, @@ -5840,7 +5826,7 @@ }, { "cell_type": "markdown", - "id": "d225bbe1", + "id": "ffb9694e", "metadata": { "editable": true }, @@ -5852,7 +5838,7 @@ }, { "cell_type": "markdown", - "id": "f00b2ce8", + "id": "39c68ba3", "metadata": { "editable": true }, @@ -5862,7 +5848,7 @@ }, { "cell_type": "markdown", - "id": "c1adf677", + "id": "23c5c82d", "metadata": { "editable": true }, @@ -5884,7 +5870,7 @@ }, { "cell_type": "markdown", - "id": "14b346d4", + "id": "93dd6e83", "metadata": { "editable": true }, @@ -5896,7 +5882,7 @@ }, { "cell_type": "markdown", - "id": "17e71493", + "id": "f41f1577", "metadata": { "editable": true }, @@ -5906,7 +5892,7 @@ }, { "cell_type": "markdown", - "id": "86e987b5", + "id": "09b91336", "metadata": { "editable": true }, @@ -5918,7 +5904,7 @@ }, { "cell_type": "markdown", - "id": "17de1b27", + "id": "648749ff", "metadata": { "editable": true }, @@ -5928,7 +5914,7 @@ }, { "cell_type": "markdown", - "id": "f563e336", + "id": "ad0c48b4", "metadata": { "editable": true }, @@ -5940,7 +5926,7 @@ }, { "cell_type": "markdown", - "id": "412c7346", + "id": "3e437dfe", "metadata": { "editable": true }, @@ -5953,7 +5939,7 @@ }, { "cell_type": "markdown", - "id": "2f1679ed", + "id": "71415d23", "metadata": { "editable": true }, @@ -5965,7 +5951,7 @@ }, { "cell_type": "markdown", - "id": "7c8da0b5", + "id": "3e166441", "metadata": { "editable": true }, @@ -5975,7 +5961,7 @@ }, { "cell_type": "markdown", - "id": "d054a2b4", + "id": "8fe76a21", "metadata": { "editable": true }, @@ -5987,7 +5973,7 @@ }, { "cell_type": "markdown", - "id": "beafad7d", + "id": "38ee9b1c", "metadata": { "editable": true }, @@ -5997,7 +5983,7 @@ }, { "cell_type": "markdown", - "id": "e64d5113", + "id": "b4fe0bcd", "metadata": { "editable": true }, @@ -6009,7 +5995,7 @@ }, { "cell_type": "markdown", - "id": "2434c10a", + "id": "79fe6d2e", "metadata": { "editable": true }, @@ -6019,7 +6005,7 @@ }, { "cell_type": "markdown", - "id": "ae7de129", + "id": "ba05c308", "metadata": { "editable": true }, diff --git a/doc/src/week35/week35.do.txt b/doc/src/week35/week35.do.txt index a99e49d4f..1629ccf26 100644 --- a/doc/src/week35/week35.do.txt +++ b/doc/src/week35/week35.do.txt @@ -6,8 +6,15 @@ DATE: today !split ===== Plans for week 35 ===== -* Review of ordinary Least Squares with applications. Discussion of Ridge and Lasso Regression and links with Singular Value Decomposition -* Exercises and hands-on demonstrations +The main topics are: +o Repetition from last week on linear regression +o Reminder on statistics with quantities like mean values, variance abd covariance +o Discussion of how to prepare data and examples of applications of linear regression +o Mathematical interpretations of Linear Regression +o Start discussing Ridge and Lasso regression and Singular Value Decomposition + + + === Reading recommendations: === o See lecture notes for week 35 at URL:"https://compphysics.github.io/MachineLearning/doc/web/course.html" o For a review on statistics see jupyter-book URL:"https://compphysics.github.io/MachineLearning/doc/LectureNotes/_build/html/statistics.html", the most relevant parts are covered by sections 1.1.1-1.1.5 @@ -18,15 +25,7 @@ DATE: today -!split -===== Topics of week 35 ===== -The main topics are: -o Repetition from last week on linear regression -o Reminder on statistics with quantities like mean values, variance abd covariance -o Discussion of how to prepare data and examples of applications of linear regression -o Mathematical interpretations of Linear Regression -o Start discussing Ridge and Lasso regression and Singular Value Decomposition