From fa2ef12d8f9a73038e8c7a21312956e729b02c7a Mon Sep 17 00:00:00 2001 From: Morten Hjorth-Jensen Date: Mon, 28 Aug 2023 07:41:11 +0200 Subject: [PATCH] update week 35 --- doc/pub/week35/html/._week35-bs000.html | 171 +- doc/pub/week35/html/._week35-bs001.html | 175 +- doc/pub/week35/html/._week35-bs002.html | 171 +- doc/pub/week35/html/._week35-bs003.html | 184 +- doc/pub/week35/html/._week35-bs004.html | 171 +- doc/pub/week35/html/._week35-bs005.html | 175 +- doc/pub/week35/html/._week35-bs006.html | 171 +- doc/pub/week35/html/._week35-bs007.html | 171 +- doc/pub/week35/html/._week35-bs008.html | 171 +- doc/pub/week35/html/._week35-bs009.html | 171 +- doc/pub/week35/html/._week35-bs010.html | 171 +- doc/pub/week35/html/._week35-bs011.html | 171 +- doc/pub/week35/html/._week35-bs012.html | 171 +- doc/pub/week35/html/._week35-bs013.html | 171 +- doc/pub/week35/html/._week35-bs014.html | 171 +- doc/pub/week35/html/._week35-bs015.html | 175 +- doc/pub/week35/html/._week35-bs016.html | 171 +- doc/pub/week35/html/._week35-bs017.html | 180 +- doc/pub/week35/html/._week35-bs018.html | 212 +- doc/pub/week35/html/._week35-bs019.html | 171 +- doc/pub/week35/html/._week35-bs020.html | 171 +- doc/pub/week35/html/._week35-bs021.html | 179 +- doc/pub/week35/html/._week35-bs022.html | 171 +- doc/pub/week35/html/._week35-bs023.html | 223 +- doc/pub/week35/html/._week35-bs024.html | 525 +-- doc/pub/week35/html/._week35-bs025.html | 208 +- doc/pub/week35/html/._week35-bs026.html | 203 +- doc/pub/week35/html/._week35-bs027.html | 192 +- doc/pub/week35/html/._week35-bs028.html | 239 +- doc/pub/week35/html/._week35-bs029.html | 185 +- doc/pub/week35/html/._week35-bs030.html | 271 +- doc/pub/week35/html/._week35-bs031.html | 294 +- doc/pub/week35/html/._week35-bs032.html | 283 +- doc/pub/week35/html/._week35-bs033.html | 309 +- doc/pub/week35/html/._week35-bs034.html | 214 +- doc/pub/week35/html/._week35-bs035.html | 232 +- doc/pub/week35/html/._week35-bs036.html | 210 +- doc/pub/week35/html/._week35-bs037.html | 192 +- doc/pub/week35/html/._week35-bs038.html | 339 +- doc/pub/week35/html/._week35-bs039.html | 242 +- doc/pub/week35/html/._week35-bs040.html | 526 ++- doc/pub/week35/html/._week35-bs041.html | 207 +- doc/pub/week35/html/._week35-bs042.html | 230 +- doc/pub/week35/html/._week35-bs043.html | 196 +- doc/pub/week35/html/._week35-bs044.html | 242 +- doc/pub/week35/html/._week35-bs045.html | 219 +- doc/pub/week35/html/._week35-bs046.html | 237 +- doc/pub/week35/html/._week35-bs047.html | 240 +- doc/pub/week35/html/._week35-bs048.html | 214 +- doc/pub/week35/html/._week35-bs049.html | 256 +- doc/pub/week35/html/._week35-bs050.html | 208 +- doc/pub/week35/html/._week35-bs051.html | 260 +- doc/pub/week35/html/._week35-bs052.html | 204 +- doc/pub/week35/html/._week35-bs053.html | 222 +- doc/pub/week35/html/._week35-bs054.html | 270 +- doc/pub/week35/html/._week35-bs055.html | 265 +- doc/pub/week35/html/._week35-bs056.html | 252 +- doc/pub/week35/html/._week35-bs057.html | 264 +- doc/pub/week35/html/._week35-bs058.html | 233 +- doc/pub/week35/html/._week35-bs059.html | 215 +- doc/pub/week35/html/._week35-bs060.html | 243 +- doc/pub/week35/html/._week35-bs061.html | 254 +- doc/pub/week35/html/._week35-bs062.html | 274 +- doc/pub/week35/html/._week35-bs063.html | 271 +- doc/pub/week35/html/._week35-bs064.html | 258 +- doc/pub/week35/html/._week35-bs065.html | 215 +- doc/pub/week35/html/._week35-bs066.html | 205 +- doc/pub/week35/html/._week35-bs067.html | 798 +---- doc/pub/week35/html/._week35-bs068.html | 309 +- doc/pub/week35/html/._week35-bs069.html | 315 +- doc/pub/week35/html/._week35-bs070.html | 329 +- doc/pub/week35/html/._week35-bs071.html | 318 +- doc/pub/week35/html/week35-bs.html | 171 +- doc/pub/week35/html/week35-reveal.html | 1901 +++++------ doc/pub/week35/html/week35-solarized.html | 1876 +++++------ doc/pub/week35/html/week35.html | 1876 +++++------ doc/pub/week35/ipynb/ipynb-week35-src.tar.gz | Bin 192 -> 192 bytes doc/pub/week35/ipynb/week35.ipynb | 3007 ++++++++---------- doc/src/week35/exercisesweek35.do.txt | 151 + doc/src/week35/week35.do.txt | 1139 +++---- 80 files changed, 12822 insertions(+), 14425 deletions(-) create mode 100644 doc/src/week35/exercisesweek35.do.txt diff --git a/doc/pub/week35/html/._week35-bs000.html b/doc/pub/week35/html/._week35-bs000.html index d90915830..2656060af 100644 --- a/doc/pub/week35/html/._week35-bs000.html +++ b/doc/pub/week35/html/._week35-bs000.html @@ -75,10 +75,10 @@ doconce format html week35.do.txt --html_style=bootstrap --pygments_html_style=d 2, None, 'interpretations-and-optimizing-our-parameters'), - ('Examples relevant for the exercises', + ('Example relevant for the exercises', 2, None, - 'examples-relevant-for-the-exercises'), + 'example-relevant-for-the-exercises'), ('Own code for Ordinary Least Squares', 2, None, @@ -91,16 +91,14 @@ doconce format html week35.do.txt --html_style=bootstrap --pygments_html_style=d 2, None, 'splitting-our-data-in-training-and-test-data'), - ('Examples', 2, None, 'examples'), + ('The complete code with a simple data set', + 2, + None, + 'the-complete-code-with-a-simple-data-set'), ('Making your own test-train splitting', 2, None, 'making-your-own-test-train-splitting'), - ('The Boston housing data example', - 2, - None, - 'the-boston-housing-data-example'), - ('Housing data, the code', 2, None, 'housing-data-the-code'), ('Reducing the number of degrees of freedom, overarching view', 2, None, @@ -124,10 +122,33 @@ doconce format html week35.do.txt --html_style=bootstrap --pygments_html_style=d 2, None, 'testing-the-means-squared-error-as-function-of-complexity'), - ('More preprocessing examples, Franke function and regression', + ('More preprocessing examples, two-dimensional example, the ' + 'Franke function', 2, None, - 'more-preprocessing-examples-franke-function-and-regression'), + 'more-preprocessing-examples-two-dimensional-example-the-franke-function'), + ('To think about, first part', + 2, + None, + 'to-think-about-first-part'), + ('More thinking', 2, None, 'more-thinking'), + ('Still thinking', 2, None, 'still-thinking'), + ('What does centering (subtracting the mean values) mean ' + 'mathematically?', + 2, + None, + 'what-does-centering-subtracting-the-mean-values-mean-mathematically'), + ('Further Manipulations', 2, None, 'further-manipulations'), + ('Wrapping it up', 2, None, 'wrapping-it-up'), + ('Linear Regression code, Intercept handling first', + 2, + None, + 'linear-regression-code-intercept-handling-first'), + ('The Boston housing data example', + 2, + None, + 'the-boston-housing-data-example'), + ('Housing data, the code', 2, None, 'housing-data-the-code'), ('Material for lecture Thursday, August 31', 2, None, @@ -226,28 +247,7 @@ doconce format html week35.do.txt --html_style=bootstrap --pygments_html_style=d ('Deriving the Lasso Regression Equations', 2, None, - 'deriving-the-lasso-regression-equations'), - ('Exercises for week 35', 2, None, 'exercises-for-week-35'), - ('Exercise 1: Setting up various Python environments', - 2, - None, - 'exercise-1-setting-up-various-python-environments'), - ('Exercise 2: making your own data and exploring scikit-learn', - 2, - None, - 'exercise-2-making-your-own-data-and-exploring-scikit-learn'), - ('Exercise 3: Normalizing our data', - 2, - None, - 'exercise-3-normalizing-our-data'), - ('Exercise 4: Adding Ridge Regression', - 2, - None, - 'exercise-4-adding-ridge-regression'), - ('Exercise 5: Analytical exercises', - 2, - None, - 'exercise-5-analytical-exercises')]} + 'deriving-the-lasso-regression-equations')]} end of tocinfo --> @@ -299,62 +299,63 @@ MathJax.Hub.Config({
  • Other useful relations
  • Meet the Hessian Matrix
  • Interpretations and optimizing our parameters
  • -
  • Examples relevant for the exercises
  • +
  • Example relevant for the exercises
  • Own code for Ordinary Least Squares
  • Adding error analysis and training set up
  • Splitting our Data in Training and Test data
  • -
  • Examples
  • +
  • The complete code with a simple data set
  • Making your own test-train splitting
  • -
  • The Boston housing data example
  • -
  • Housing data, the code
  • -
  • Reducing the number of degrees of freedom, overarching view
  • -
  • Preprocessing our data
  • -
  • Functionality in Scikit-Learn
  • -
  • More preprocessing
  • -
  • Frequently used scaling functions
  • -
  • Example of own Standard scaling
  • -
  • Min-Max Scaling
  • -
  • Testing the Means Squared Error as function of Complexity
  • -
  • More preprocessing examples, Franke function and regression
  • -
  • Material for lecture Thursday, August 31
  • -
  • Mathematical Interpretation of Ordinary Least Squares
  • -
  • Residual Error
  • -
  • Simple case
  • -
  • The singular value decomposition
  • -
  • Linear Regression Problems
  • -
  • Fixing the singularity
  • -
  • Basic math of the SVD
  • -
  • The SVD, a Fantastic Algorithm
  • -
  • Economy-size SVD
  • -
  • Codes for the SVD
  • -
  • Note about SVD Calculations
  • -
  • Mathematics of the SVD and implications
  • -
  • Example Matrix
  • -
  • Setting up the Matrix to be inverted
  • -
  • Further properties (important for our analyses later)
  • -
  • Meet the Covariance Matrix
  • -
  • Introducing the Covariance and Correlation functions
  • -
  • Covariance and Correlation Matrix
  • -
  • Correlation Function and Design/Feature Matrix
  • -
  • Covariance Matrix Examples
  • -
  • Correlation Matrix
  • -
  • Correlation Matrix with Pandas
  • -
  • Correlation Matrix with Pandas and the Franke function
  • -
  • Rewriting the Covariance and/or Correlation Matrix
  • -
  • Linking with the SVD
  • -
  • What does it mean?
  • -
  • And finally \( \boldsymbol{X}\boldsymbol{X}^T \)
  • -
  • Ridge and LASSO Regression
  • -
  • Deriving the Ridge Regression Equations
  • -
  • Interpreting the Ridge results
  • -
  • More interpretations
  • -
  • Deriving the Lasso Regression Equations
  • -
  • Exercises for week 35
  • -
  • Exercise 1: Setting up various Python environments
  • -
  • Exercise 2: making your own data and exploring scikit-learn
  • -
  • Exercise 3: Normalizing our data
  • -
  • Exercise 4: Adding Ridge Regression
  • -
  • Exercise 5: Analytical exercises
  • +
  • Reducing the number of degrees of freedom, overarching view
  • +
  • Preprocessing our data
  • +
  • Functionality in Scikit-Learn
  • +
  • More preprocessing
  • +
  • Frequently used scaling functions
  • +
  • Example of own Standard scaling
  • +
  • Min-Max Scaling
  • +
  • Testing the Means Squared Error as function of Complexity
  • +
  • More preprocessing examples, two-dimensional example, the Franke function
  • +
  • To think about, first part
  • +
  • More thinking
  • +
  • Still thinking
  • +
  • What does centering (subtracting the mean values) mean mathematically?
  • +
  • Further Manipulations
  • +
  • Wrapping it up
  • +
  • Linear Regression code, Intercept handling first
  • +
  • The Boston housing data example
  • +
  • Housing data, the code
  • +
  • Material for lecture Thursday, August 31
  • +
  • Mathematical Interpretation of Ordinary Least Squares
  • +
  • Residual Error
  • +
  • Simple case
  • +
  • The singular value decomposition
  • +
  • Linear Regression Problems
  • +
  • Fixing the singularity
  • +
  • Basic math of the SVD
  • +
  • The SVD, a Fantastic Algorithm
  • +
  • Economy-size SVD
  • +
  • Codes for the SVD
  • +
  • Note about SVD Calculations
  • +
  • Mathematics of the SVD and implications
  • +
  • Example Matrix
  • +
  • Setting up the Matrix to be inverted
  • +
  • Further properties (important for our analyses later)
  • +
  • Meet the Covariance Matrix
  • +
  • Introducing the Covariance and Correlation functions
  • +
  • Covariance and Correlation Matrix
  • +
  • Correlation Function and Design/Feature Matrix
  • +
  • Covariance Matrix Examples
  • +
  • Correlation Matrix
  • +
  • Correlation Matrix with Pandas
  • +
  • Correlation Matrix with Pandas and the Franke function
  • +
  • Rewriting the Covariance and/or Correlation Matrix
  • +
  • Linking with the SVD
  • +
  • What does it mean?
  • +
  • And finally \( \boldsymbol{X}\boldsymbol{X}^T \)
  • +
  • Ridge and LASSO Regression
  • +
  • Deriving the Ridge Regression Equations
  • +
  • Interpreting the Ridge results
  • +
  • More interpretations
  • +
  • Deriving the Lasso Regression Equations
  • @@ -409,7 +410,7 @@ MathJax.Hub.Config({
  • 9
  • 10
  • ...
  • -
  • 68
  • +
  • 74
  • »
  • diff --git a/doc/pub/week35/html/._week35-bs001.html b/doc/pub/week35/html/._week35-bs001.html index ae3632cb4..125ef36bf 100644 --- a/doc/pub/week35/html/._week35-bs001.html +++ b/doc/pub/week35/html/._week35-bs001.html @@ -75,10 +75,10 @@ doconce format html week35.do.txt --html_style=bootstrap --pygments_html_style=d 2, None, 'interpretations-and-optimizing-our-parameters'), - ('Examples relevant for the exercises', + ('Example relevant for the exercises', 2, None, - 'examples-relevant-for-the-exercises'), + 'example-relevant-for-the-exercises'), ('Own code for Ordinary Least Squares', 2, None, @@ -91,16 +91,14 @@ doconce format html week35.do.txt --html_style=bootstrap --pygments_html_style=d 2, None, 'splitting-our-data-in-training-and-test-data'), - ('Examples', 2, None, 'examples'), + ('The complete code with a simple data set', + 2, + None, + 'the-complete-code-with-a-simple-data-set'), ('Making your own test-train splitting', 2, None, 'making-your-own-test-train-splitting'), - ('The Boston housing data example', - 2, - None, - 'the-boston-housing-data-example'), - ('Housing data, the code', 2, None, 'housing-data-the-code'), ('Reducing the number of degrees of freedom, overarching view', 2, None, @@ -124,10 +122,33 @@ doconce format html week35.do.txt --html_style=bootstrap --pygments_html_style=d 2, None, 'testing-the-means-squared-error-as-function-of-complexity'), - ('More preprocessing examples, Franke function and regression', + ('More preprocessing examples, two-dimensional example, the ' + 'Franke function', 2, None, - 'more-preprocessing-examples-franke-function-and-regression'), + 'more-preprocessing-examples-two-dimensional-example-the-franke-function'), + ('To think about, first part', + 2, + None, + 'to-think-about-first-part'), + ('More thinking', 2, None, 'more-thinking'), + ('Still thinking', 2, None, 'still-thinking'), + ('What does centering (subtracting the mean values) mean ' + 'mathematically?', + 2, + None, + 'what-does-centering-subtracting-the-mean-values-mean-mathematically'), + ('Further Manipulations', 2, None, 'further-manipulations'), + ('Wrapping it up', 2, None, 'wrapping-it-up'), + ('Linear Regression code, Intercept handling first', + 2, + None, + 'linear-regression-code-intercept-handling-first'), + ('The Boston housing data example', + 2, + None, + 'the-boston-housing-data-example'), + ('Housing data, the code', 2, None, 'housing-data-the-code'), ('Material for lecture Thursday, August 31', 2, None, @@ -226,28 +247,7 @@ doconce format html week35.do.txt --html_style=bootstrap --pygments_html_style=d ('Deriving the Lasso Regression Equations', 2, None, - 'deriving-the-lasso-regression-equations'), - ('Exercises for week 35', 2, None, 'exercises-for-week-35'), - ('Exercise 1: Setting up various Python environments', - 2, - None, - 'exercise-1-setting-up-various-python-environments'), - ('Exercise 2: making your own data and exploring scikit-learn', - 2, - None, - 'exercise-2-making-your-own-data-and-exploring-scikit-learn'), - ('Exercise 3: Normalizing our data', - 2, - None, - 'exercise-3-normalizing-our-data'), - ('Exercise 4: Adding Ridge Regression', - 2, - None, - 'exercise-4-adding-ridge-regression'), - ('Exercise 5: Analytical exercises', - 2, - None, - 'exercise-5-analytical-exercises')]} + 'deriving-the-lasso-regression-equations')]} end of tocinfo --> @@ -299,62 +299,63 @@ MathJax.Hub.Config({
  • Other useful relations
  • Meet the Hessian Matrix
  • Interpretations and optimizing our parameters
  • -
  • Examples relevant for the exercises
  • +
  • Example relevant for the exercises
  • Own code for Ordinary Least Squares
  • Adding error analysis and training set up
  • Splitting our Data in Training and Test data
  • -
  • Examples
  • +
  • The complete code with a simple data set
  • Making your own test-train splitting
  • -
  • The Boston housing data example
  • -
  • Housing data, the code
  • -
  • Reducing the number of degrees of freedom, overarching view
  • -
  • Preprocessing our data
  • -
  • Functionality in Scikit-Learn
  • -
  • More preprocessing
  • -
  • Frequently used scaling functions
  • -
  • Example of own Standard scaling
  • -
  • Min-Max Scaling
  • -
  • Testing the Means Squared Error as function of Complexity
  • -
  • More preprocessing examples, Franke function and regression
  • -
  • Material for lecture Thursday, August 31
  • -
  • Mathematical Interpretation of Ordinary Least Squares
  • -
  • Residual Error
  • -
  • Simple case
  • -
  • The singular value decomposition
  • -
  • Linear Regression Problems
  • -
  • Fixing the singularity
  • -
  • Basic math of the SVD
  • -
  • The SVD, a Fantastic Algorithm
  • -
  • Economy-size SVD
  • -
  • Codes for the SVD
  • -
  • Note about SVD Calculations
  • -
  • Mathematics of the SVD and implications
  • -
  • Example Matrix
  • -
  • Setting up the Matrix to be inverted
  • -
  • Further properties (important for our analyses later)
  • -
  • Meet the Covariance Matrix
  • -
  • Introducing the Covariance and Correlation functions
  • -
  • Covariance and Correlation Matrix
  • -
  • Correlation Function and Design/Feature Matrix
  • -
  • Covariance Matrix Examples
  • -
  • Correlation Matrix
  • -
  • Correlation Matrix with Pandas
  • -
  • Correlation Matrix with Pandas and the Franke function
  • -
  • Rewriting the Covariance and/or Correlation Matrix
  • -
  • Linking with the SVD
  • -
  • What does it mean?
  • -
  • And finally \( \boldsymbol{X}\boldsymbol{X}^T \)
  • -
  • Ridge and LASSO Regression
  • -
  • Deriving the Ridge Regression Equations
  • -
  • Interpreting the Ridge results
  • -
  • More interpretations
  • -
  • Deriving the Lasso Regression Equations
  • -
  • Exercises for week 35
  • -
  • Exercise 1: Setting up various Python environments
  • -
  • Exercise 2: making your own data and exploring scikit-learn
  • -
  • Exercise 3: Normalizing our data
  • -
  • Exercise 4: Adding Ridge Regression
  • -
  • Exercise 5: Analytical exercises
  • +
  • Reducing the number of degrees of freedom, overarching view
  • +
  • Preprocessing our data
  • +
  • Functionality in Scikit-Learn
  • +
  • More preprocessing
  • +
  • Frequently used scaling functions
  • +
  • Example of own Standard scaling
  • +
  • Min-Max Scaling
  • +
  • Testing the Means Squared Error as function of Complexity
  • +
  • More preprocessing examples, two-dimensional example, the Franke function
  • +
  • To think about, first part
  • +
  • More thinking
  • +
  • Still thinking
  • +
  • What does centering (subtracting the mean values) mean mathematically?
  • +
  • Further Manipulations
  • +
  • Wrapping it up
  • +
  • Linear Regression code, Intercept handling first
  • +
  • The Boston housing data example
  • +
  • Housing data, the code
  • +
  • Material for lecture Thursday, August 31
  • +
  • Mathematical Interpretation of Ordinary Least Squares
  • +
  • Residual Error
  • +
  • Simple case
  • +
  • The singular value decomposition
  • +
  • Linear Regression Problems
  • +
  • Fixing the singularity
  • +
  • Basic math of the SVD
  • +
  • The SVD, a Fantastic Algorithm
  • +
  • Economy-size SVD
  • +
  • Codes for the SVD
  • +
  • Note about SVD Calculations
  • +
  • Mathematics of the SVD and implications
  • +
  • Example Matrix
  • +
  • Setting up the Matrix to be inverted
  • +
  • Further properties (important for our analyses later)
  • +
  • Meet the Covariance Matrix
  • +
  • Introducing the Covariance and Correlation functions
  • +
  • Covariance and Correlation Matrix
  • +
  • Correlation Function and Design/Feature Matrix
  • +
  • Covariance Matrix Examples
  • +
  • Correlation Matrix
  • +
  • Correlation Matrix with Pandas
  • +
  • Correlation Matrix with Pandas and the Franke function
  • +
  • Rewriting the Covariance and/or Correlation Matrix
  • +
  • Linking with the SVD
  • +
  • What does it mean?
  • +
  • And finally \( \boldsymbol{X}\boldsymbol{X}^T \)
  • +
  • Ridge and LASSO Regression
  • +
  • Deriving the Ridge Regression Equations
  • +
  • Interpreting the Ridge results
  • +
  • More interpretations
  • +
  • Deriving the Lasso Regression Equations
  • @@ -374,8 +375,8 @@ MathJax.Hub.Config({
  • Brief repetition from last week
  • Derivation of the equations for ordinary least squares
  • Discussion on how to prepare data and examples of applications of linear regression
  • -
  • Mathematical interpretations of linear regression
  • -
  • Ridge and Lasso regression and Singular Value Decomposition
  • +
  • Material for the lecture on Thursday: Mathematical interpretations of linear regression
  • +
  • Thursday: Ridge and Lasso regression and Singular Value Decomposition
  • Reading recommendations:

    @@ -399,7 +400,7 @@ MathJax.Hub.Config({
  • 10
  • 11
  • ...
  • -
  • 68
  • +
  • 74
  • »
  • diff --git a/doc/pub/week35/html/._week35-bs002.html b/doc/pub/week35/html/._week35-bs002.html index badb7c71b..277455408 100644 --- a/doc/pub/week35/html/._week35-bs002.html +++ b/doc/pub/week35/html/._week35-bs002.html @@ -75,10 +75,10 @@ doconce format html week35.do.txt --html_style=bootstrap --pygments_html_style=d 2, None, 'interpretations-and-optimizing-our-parameters'), - ('Examples relevant for the exercises', + ('Example relevant for the exercises', 2, None, - 'examples-relevant-for-the-exercises'), + 'example-relevant-for-the-exercises'), ('Own code for Ordinary Least Squares', 2, None, @@ -91,16 +91,14 @@ doconce format html week35.do.txt --html_style=bootstrap --pygments_html_style=d 2, None, 'splitting-our-data-in-training-and-test-data'), - ('Examples', 2, None, 'examples'), + ('The complete code with a simple data set', + 2, + None, + 'the-complete-code-with-a-simple-data-set'), ('Making your own test-train splitting', 2, None, 'making-your-own-test-train-splitting'), - ('The Boston housing data example', - 2, - None, - 'the-boston-housing-data-example'), - ('Housing data, the code', 2, None, 'housing-data-the-code'), ('Reducing the number of degrees of freedom, overarching view', 2, None, @@ -124,10 +122,33 @@ doconce format html week35.do.txt --html_style=bootstrap --pygments_html_style=d 2, None, 'testing-the-means-squared-error-as-function-of-complexity'), - ('More preprocessing examples, Franke function and regression', + ('More preprocessing examples, two-dimensional example, the ' + 'Franke function', 2, None, - 'more-preprocessing-examples-franke-function-and-regression'), + 'more-preprocessing-examples-two-dimensional-example-the-franke-function'), + ('To think about, first part', + 2, + None, + 'to-think-about-first-part'), + ('More thinking', 2, None, 'more-thinking'), + ('Still thinking', 2, None, 'still-thinking'), + ('What does centering (subtracting the mean values) mean ' + 'mathematically?', + 2, + None, + 'what-does-centering-subtracting-the-mean-values-mean-mathematically'), + ('Further Manipulations', 2, None, 'further-manipulations'), + ('Wrapping it up', 2, None, 'wrapping-it-up'), + ('Linear Regression code, Intercept handling first', + 2, + None, + 'linear-regression-code-intercept-handling-first'), + ('The Boston housing data example', + 2, + None, + 'the-boston-housing-data-example'), + ('Housing data, the code', 2, None, 'housing-data-the-code'), ('Material for lecture Thursday, August 31', 2, None, @@ -226,28 +247,7 @@ doconce format html week35.do.txt --html_style=bootstrap --pygments_html_style=d ('Deriving the Lasso Regression Equations', 2, None, - 'deriving-the-lasso-regression-equations'), - ('Exercises for week 35', 2, None, 'exercises-for-week-35'), - ('Exercise 1: Setting up various Python environments', - 2, - None, - 'exercise-1-setting-up-various-python-environments'), - ('Exercise 2: making your own data and exploring scikit-learn', - 2, - None, - 'exercise-2-making-your-own-data-and-exploring-scikit-learn'), - ('Exercise 3: Normalizing our data', - 2, - None, - 'exercise-3-normalizing-our-data'), - ('Exercise 4: Adding Ridge Regression', - 2, - None, - 'exercise-4-adding-ridge-regression'), - ('Exercise 5: Analytical exercises', - 2, - None, - 'exercise-5-analytical-exercises')]} + 'deriving-the-lasso-regression-equations')]} end of tocinfo --> @@ -299,62 +299,63 @@ MathJax.Hub.Config({
  • Other useful relations
  • Meet the Hessian Matrix
  • Interpretations and optimizing our parameters
  • -
  • Examples relevant for the exercises
  • +
  • Example relevant for the exercises
  • Own code for Ordinary Least Squares
  • Adding error analysis and training set up
  • Splitting our Data in Training and Test data
  • -
  • Examples
  • +
  • The complete code with a simple data set
  • Making your own test-train splitting
  • -
  • The Boston housing data example
  • -
  • Housing data, the code
  • -
  • Reducing the number of degrees of freedom, overarching view
  • -
  • Preprocessing our data
  • -
  • Functionality in Scikit-Learn
  • -
  • More preprocessing
  • -
  • Frequently used scaling functions
  • -
  • Example of own Standard scaling
  • -
  • Min-Max Scaling
  • -
  • Testing the Means Squared Error as function of Complexity
  • -
  • More preprocessing examples, Franke function and regression
  • -
  • Material for lecture Thursday, August 31
  • -
  • Mathematical Interpretation of Ordinary Least Squares
  • -
  • Residual Error
  • -
  • Simple case
  • -
  • The singular value decomposition
  • -
  • Linear Regression Problems
  • -
  • Fixing the singularity
  • -
  • Basic math of the SVD
  • -
  • The SVD, a Fantastic Algorithm
  • -
  • Economy-size SVD
  • -
  • Codes for the SVD
  • -
  • Note about SVD Calculations
  • -
  • Mathematics of the SVD and implications
  • -
  • Example Matrix
  • -
  • Setting up the Matrix to be inverted
  • -
  • Further properties (important for our analyses later)
  • -
  • Meet the Covariance Matrix
  • -
  • Introducing the Covariance and Correlation functions
  • -
  • Covariance and Correlation Matrix
  • -
  • Correlation Function and Design/Feature Matrix
  • -
  • Covariance Matrix Examples
  • -
  • Correlation Matrix
  • -
  • Correlation Matrix with Pandas
  • -
  • Correlation Matrix with Pandas and the Franke function
  • -
  • Rewriting the Covariance and/or Correlation Matrix
  • -
  • Linking with the SVD
  • -
  • What does it mean?
  • -
  • And finally \( \boldsymbol{X}\boldsymbol{X}^T \)
  • -
  • Ridge and LASSO Regression
  • -
  • Deriving the Ridge Regression Equations
  • -
  • Interpreting the Ridge results
  • -
  • More interpretations
  • -
  • Deriving the Lasso Regression Equations
  • -
  • Exercises for week 35
  • -
  • Exercise 1: Setting up various Python environments
  • -
  • Exercise 2: making your own data and exploring scikit-learn
  • -
  • Exercise 3: Normalizing our data
  • -
  • Exercise 4: Adding Ridge Regression
  • -
  • Exercise 5: Analytical exercises
  • +
  • Reducing the number of degrees of freedom, overarching view
  • +
  • Preprocessing our data
  • +
  • Functionality in Scikit-Learn
  • +
  • More preprocessing
  • +
  • Frequently used scaling functions
  • +
  • Example of own Standard scaling
  • +
  • Min-Max Scaling
  • +
  • Testing the Means Squared Error as function of Complexity
  • +
  • More preprocessing examples, two-dimensional example, the Franke function
  • +
  • To think about, first part
  • +
  • More thinking
  • +
  • Still thinking
  • +
  • What does centering (subtracting the mean values) mean mathematically?
  • +
  • Further Manipulations
  • +
  • Wrapping it up
  • +
  • Linear Regression code, Intercept handling first
  • +
  • The Boston housing data example
  • +
  • Housing data, the code
  • +
  • Material for lecture Thursday, August 31
  • +
  • Mathematical Interpretation of Ordinary Least Squares
  • +
  • Residual Error
  • +
  • Simple case
  • +
  • The singular value decomposition
  • +
  • Linear Regression Problems
  • +
  • Fixing the singularity
  • +
  • Basic math of the SVD
  • +
  • The SVD, a Fantastic Algorithm
  • +
  • Economy-size SVD
  • +
  • Codes for the SVD
  • +
  • Note about SVD Calculations
  • +
  • Mathematics of the SVD and implications
  • +
  • Example Matrix
  • +
  • Setting up the Matrix to be inverted
  • +
  • Further properties (important for our analyses later)
  • +
  • Meet the Covariance Matrix
  • +
  • Introducing the Covariance and Correlation functions
  • +
  • Covariance and Correlation Matrix
  • +
  • Correlation Function and Design/Feature Matrix
  • +
  • Covariance Matrix Examples
  • +
  • Correlation Matrix
  • +
  • Correlation Matrix with Pandas
  • +
  • Correlation Matrix with Pandas and the Franke function
  • +
  • Rewriting the Covariance and/or Correlation Matrix
  • +
  • Linking with the SVD
  • +
  • What does it mean?
  • +
  • And finally \( \boldsymbol{X}\boldsymbol{X}^T \)
  • +
  • Ridge and LASSO Regression
  • +
  • Deriving the Ridge Regression Equations
  • +
  • Interpreting the Ridge results
  • +
  • More interpretations
  • +
  • Deriving the Lasso Regression Equations
  • @@ -403,7 +404,7 @@ Similarly, Mehta et al
  • 11
  • 12
  • ...
  • -
  • 68
  • +
  • 74
  • »
  • diff --git a/doc/pub/week35/html/._week35-bs003.html b/doc/pub/week35/html/._week35-bs003.html index 0263c9e82..6aff0fed8 100644 --- a/doc/pub/week35/html/._week35-bs003.html +++ b/doc/pub/week35/html/._week35-bs003.html @@ -75,10 +75,10 @@ doconce format html week35.do.txt --html_style=bootstrap --pygments_html_style=d 2, None, 'interpretations-and-optimizing-our-parameters'), - ('Examples relevant for the exercises', + ('Example relevant for the exercises', 2, None, - 'examples-relevant-for-the-exercises'), + 'example-relevant-for-the-exercises'), ('Own code for Ordinary Least Squares', 2, None, @@ -91,16 +91,14 @@ doconce format html week35.do.txt --html_style=bootstrap --pygments_html_style=d 2, None, 'splitting-our-data-in-training-and-test-data'), - ('Examples', 2, None, 'examples'), + ('The complete code with a simple data set', + 2, + None, + 'the-complete-code-with-a-simple-data-set'), ('Making your own test-train splitting', 2, None, 'making-your-own-test-train-splitting'), - ('The Boston housing data example', - 2, - None, - 'the-boston-housing-data-example'), - ('Housing data, the code', 2, None, 'housing-data-the-code'), ('Reducing the number of degrees of freedom, overarching view', 2, None, @@ -124,10 +122,33 @@ doconce format html week35.do.txt --html_style=bootstrap --pygments_html_style=d 2, None, 'testing-the-means-squared-error-as-function-of-complexity'), - ('More preprocessing examples, Franke function and regression', + ('More preprocessing examples, two-dimensional example, the ' + 'Franke function', 2, None, - 'more-preprocessing-examples-franke-function-and-regression'), + 'more-preprocessing-examples-two-dimensional-example-the-franke-function'), + ('To think about, first part', + 2, + None, + 'to-think-about-first-part'), + ('More thinking', 2, None, 'more-thinking'), + ('Still thinking', 2, None, 'still-thinking'), + ('What does centering (subtracting the mean values) mean ' + 'mathematically?', + 2, + None, + 'what-does-centering-subtracting-the-mean-values-mean-mathematically'), + ('Further Manipulations', 2, None, 'further-manipulations'), + ('Wrapping it up', 2, None, 'wrapping-it-up'), + ('Linear Regression code, Intercept handling first', + 2, + None, + 'linear-regression-code-intercept-handling-first'), + ('The Boston housing data example', + 2, + None, + 'the-boston-housing-data-example'), + ('Housing data, the code', 2, None, 'housing-data-the-code'), ('Material for lecture Thursday, August 31', 2, None, @@ -226,28 +247,7 @@ doconce format html week35.do.txt --html_style=bootstrap --pygments_html_style=d ('Deriving the Lasso Regression Equations', 2, None, - 'deriving-the-lasso-regression-equations'), - ('Exercises for week 35', 2, None, 'exercises-for-week-35'), - ('Exercise 1: Setting up various Python environments', - 2, - None, - 'exercise-1-setting-up-various-python-environments'), - ('Exercise 2: making your own data and exploring scikit-learn', - 2, - None, - 'exercise-2-making-your-own-data-and-exploring-scikit-learn'), - ('Exercise 3: Normalizing our data', - 2, - None, - 'exercise-3-normalizing-our-data'), - ('Exercise 4: Adding Ridge Regression', - 2, - None, - 'exercise-4-adding-ridge-regression'), - ('Exercise 5: Analytical exercises', - 2, - None, - 'exercise-5-analytical-exercises')]} + 'deriving-the-lasso-regression-equations')]} end of tocinfo --> @@ -299,62 +299,63 @@ MathJax.Hub.Config({
  • Other useful relations
  • Meet the Hessian Matrix
  • Interpretations and optimizing our parameters
  • -
  • Examples relevant for the exercises
  • +
  • Example relevant for the exercises
  • Own code for Ordinary Least Squares
  • Adding error analysis and training set up
  • Splitting our Data in Training and Test data
  • -
  • Examples
  • +
  • The complete code with a simple data set
  • Making your own test-train splitting
  • -
  • The Boston housing data example
  • -
  • Housing data, the code
  • -
  • Reducing the number of degrees of freedom, overarching view
  • -
  • Preprocessing our data
  • -
  • Functionality in Scikit-Learn
  • -
  • More preprocessing
  • -
  • Frequently used scaling functions
  • -
  • Example of own Standard scaling
  • -
  • Min-Max Scaling
  • -
  • Testing the Means Squared Error as function of Complexity
  • -
  • More preprocessing examples, Franke function and regression
  • -
  • Material for lecture Thursday, August 31
  • -
  • Mathematical Interpretation of Ordinary Least Squares
  • -
  • Residual Error
  • -
  • Simple case
  • -
  • The singular value decomposition
  • -
  • Linear Regression Problems
  • -
  • Fixing the singularity
  • -
  • Basic math of the SVD
  • -
  • The SVD, a Fantastic Algorithm
  • -
  • Economy-size SVD
  • -
  • Codes for the SVD
  • -
  • Note about SVD Calculations
  • -
  • Mathematics of the SVD and implications
  • -
  • Example Matrix
  • -
  • Setting up the Matrix to be inverted
  • -
  • Further properties (important for our analyses later)
  • -
  • Meet the Covariance Matrix
  • -
  • Introducing the Covariance and Correlation functions
  • -
  • Covariance and Correlation Matrix
  • -
  • Correlation Function and Design/Feature Matrix
  • -
  • Covariance Matrix Examples
  • -
  • Correlation Matrix
  • -
  • Correlation Matrix with Pandas
  • -
  • Correlation Matrix with Pandas and the Franke function
  • -
  • Rewriting the Covariance and/or Correlation Matrix
  • -
  • Linking with the SVD
  • -
  • What does it mean?
  • -
  • And finally \( \boldsymbol{X}\boldsymbol{X}^T \)
  • -
  • Ridge and LASSO Regression
  • -
  • Deriving the Ridge Regression Equations
  • -
  • Interpreting the Ridge results
  • -
  • More interpretations
  • -
  • Deriving the Lasso Regression Equations
  • -
  • Exercises for week 35
  • -
  • Exercise 1: Setting up various Python environments
  • -
  • Exercise 2: making your own data and exploring scikit-learn
  • -
  • Exercise 3: Normalizing our data
  • -
  • Exercise 4: Adding Ridge Regression
  • -
  • Exercise 5: Analytical exercises
  • +
  • Reducing the number of degrees of freedom, overarching view
  • +
  • Preprocessing our data
  • +
  • Functionality in Scikit-Learn
  • +
  • More preprocessing
  • +
  • Frequently used scaling functions
  • +
  • Example of own Standard scaling
  • +
  • Min-Max Scaling
  • +
  • Testing the Means Squared Error as function of Complexity
  • +
  • More preprocessing examples, two-dimensional example, the Franke function
  • +
  • To think about, first part
  • +
  • More thinking
  • +
  • Still thinking
  • +
  • What does centering (subtracting the mean values) mean mathematically?
  • +
  • Further Manipulations
  • +
  • Wrapping it up
  • +
  • Linear Regression code, Intercept handling first
  • +
  • The Boston housing data example
  • +
  • Housing data, the code
  • +
  • Material for lecture Thursday, August 31
  • +
  • Mathematical Interpretation of Ordinary Least Squares
  • +
  • Residual Error
  • +
  • Simple case
  • +
  • The singular value decomposition
  • +
  • Linear Regression Problems
  • +
  • Fixing the singularity
  • +
  • Basic math of the SVD
  • +
  • The SVD, a Fantastic Algorithm
  • +
  • Economy-size SVD
  • +
  • Codes for the SVD
  • +
  • Note about SVD Calculations
  • +
  • Mathematics of the SVD and implications
  • +
  • Example Matrix
  • +
  • Setting up the Matrix to be inverted
  • +
  • Further properties (important for our analyses later)
  • +
  • Meet the Covariance Matrix
  • +
  • Introducing the Covariance and Correlation functions
  • +
  • Covariance and Correlation Matrix
  • +
  • Correlation Function and Design/Feature Matrix
  • +
  • Covariance Matrix Examples
  • +
  • Correlation Matrix
  • +
  • Correlation Matrix with Pandas
  • +
  • Correlation Matrix with Pandas and the Franke function
  • +
  • Rewriting the Covariance and/or Correlation Matrix
  • +
  • Linking with the SVD
  • +
  • What does it mean?
  • +
  • And finally \( \boldsymbol{X}\boldsymbol{X}^T \)
  • +
  • Ridge and LASSO Regression
  • +
  • Deriving the Ridge Regression Equations
  • +
  • Interpreting the Ridge results
  • +
  • More interpretations
  • +
  • Deriving the Lasso Regression Equations
  • @@ -371,16 +372,21 @@ MathJax.Hub.Config({

    Our data which we want to apply a machine learning method on, consist of a set of inputs \( \boldsymbol{x}^T=[x_0,x_1,x_2,\dots,x_{n-1}] \) and the outputs we want to model \( \boldsymbol{x}^T=[y_0,y_1,y_2,\dots,y_{n-1}] \). -We assumed also that the output data can be represented for a regression case by continuous function \( f \) +We assume that the output data can be represented (for a regression case) by a continuous function \( f \) through

    $$ y_i=f(x_i)+\epsilon_i, $$ -

    where \( \epsilon_i \) represents some noise which is normally assumed to +

    or in general

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

    where \( \boldsymbol{\epsilon} \) represents some noise which is normally assumed to be distributed via a normal probability distribution with zero mean -value and a variance \( \sigma_i^ \). +value and a variance \( \sigma^2 \).

    In linear regression we approximate the unknown function with another @@ -400,7 +406,7 @@ $$

    and in order to find the optimal parameters \( \beta_i \) we defined a function which gives a measure of the spread between the values \( y_i \) (which -represent output values we want to reproduce) and the parametrized +represent the output values we want to reproduce) and the parametrized values \( \tilde{y}_i \), namely the so-called cost/loss function.

    @@ -422,7 +428,7 @@ values \( \tilde{y}_i \), namely the so-called cost/loss function.
  • 12
  • 13
  • ...
  • -
  • 68
  • +
  • 74
  • »
  • diff --git a/doc/pub/week35/html/._week35-bs004.html b/doc/pub/week35/html/._week35-bs004.html index 31ac29276..90cb0959d 100644 --- a/doc/pub/week35/html/._week35-bs004.html +++ b/doc/pub/week35/html/._week35-bs004.html @@ -75,10 +75,10 @@ doconce format html week35.do.txt --html_style=bootstrap --pygments_html_style=d 2, None, 'interpretations-and-optimizing-our-parameters'), - ('Examples relevant for the exercises', + ('Example relevant for the exercises', 2, None, - 'examples-relevant-for-the-exercises'), + 'example-relevant-for-the-exercises'), ('Own code for Ordinary Least Squares', 2, None, @@ -91,16 +91,14 @@ doconce format html week35.do.txt --html_style=bootstrap --pygments_html_style=d 2, None, 'splitting-our-data-in-training-and-test-data'), - ('Examples', 2, None, 'examples'), + ('The complete code with a simple data set', + 2, + None, + 'the-complete-code-with-a-simple-data-set'), ('Making your own test-train splitting', 2, None, 'making-your-own-test-train-splitting'), - ('The Boston housing data example', - 2, - None, - 'the-boston-housing-data-example'), - ('Housing data, the code', 2, None, 'housing-data-the-code'), ('Reducing the number of degrees of freedom, overarching view', 2, None, @@ -124,10 +122,33 @@ doconce format html week35.do.txt --html_style=bootstrap --pygments_html_style=d 2, None, 'testing-the-means-squared-error-as-function-of-complexity'), - ('More preprocessing examples, Franke function and regression', + ('More preprocessing examples, two-dimensional example, the ' + 'Franke function', 2, None, - 'more-preprocessing-examples-franke-function-and-regression'), + 'more-preprocessing-examples-two-dimensional-example-the-franke-function'), + ('To think about, first part', + 2, + None, + 'to-think-about-first-part'), + ('More thinking', 2, None, 'more-thinking'), + ('Still thinking', 2, None, 'still-thinking'), + ('What does centering (subtracting the mean values) mean ' + 'mathematically?', + 2, + None, + 'what-does-centering-subtracting-the-mean-values-mean-mathematically'), + ('Further Manipulations', 2, None, 'further-manipulations'), + ('Wrapping it up', 2, None, 'wrapping-it-up'), + ('Linear Regression code, Intercept handling first', + 2, + None, + 'linear-regression-code-intercept-handling-first'), + ('The Boston housing data example', + 2, + None, + 'the-boston-housing-data-example'), + ('Housing data, the code', 2, None, 'housing-data-the-code'), ('Material for lecture Thursday, August 31', 2, None, @@ -226,28 +247,7 @@ doconce format html week35.do.txt --html_style=bootstrap --pygments_html_style=d ('Deriving the Lasso Regression Equations', 2, None, - 'deriving-the-lasso-regression-equations'), - ('Exercises for week 35', 2, None, 'exercises-for-week-35'), - ('Exercise 1: Setting up various Python environments', - 2, - None, - 'exercise-1-setting-up-various-python-environments'), - ('Exercise 2: making your own data and exploring scikit-learn', - 2, - None, - 'exercise-2-making-your-own-data-and-exploring-scikit-learn'), - ('Exercise 3: Normalizing our data', - 2, - None, - 'exercise-3-normalizing-our-data'), - ('Exercise 4: Adding Ridge Regression', - 2, - None, - 'exercise-4-adding-ridge-regression'), - ('Exercise 5: Analytical exercises', - 2, - None, - 'exercise-5-analytical-exercises')]} + 'deriving-the-lasso-regression-equations')]} end of tocinfo --> @@ -299,62 +299,63 @@ MathJax.Hub.Config({
  • Other useful relations
  • Meet the Hessian Matrix
  • Interpretations and optimizing our parameters
  • -
  • Examples relevant for the exercises
  • +
  • Example relevant for the exercises
  • Own code for Ordinary Least Squares
  • Adding error analysis and training set up
  • Splitting our Data in Training and Test data
  • -
  • Examples
  • +
  • The complete code with a simple data set
  • Making your own test-train splitting
  • -
  • The Boston housing data example
  • -
  • Housing data, the code
  • -
  • Reducing the number of degrees of freedom, overarching view
  • -
  • Preprocessing our data
  • -
  • Functionality in Scikit-Learn
  • -
  • More preprocessing
  • -
  • Frequently used scaling functions
  • -
  • Example of own Standard scaling
  • -
  • Min-Max Scaling
  • -
  • Testing the Means Squared Error as function of Complexity
  • -
  • More preprocessing examples, Franke function and regression
  • -
  • Material for lecture Thursday, August 31
  • -
  • Mathematical Interpretation of Ordinary Least Squares
  • -
  • Residual Error
  • -
  • Simple case
  • -
  • The singular value decomposition
  • -
  • Linear Regression Problems
  • -
  • Fixing the singularity
  • -
  • Basic math of the SVD
  • -
  • The SVD, a Fantastic Algorithm
  • -
  • Economy-size SVD
  • -
  • Codes for the SVD
  • -
  • Note about SVD Calculations
  • -
  • Mathematics of the SVD and implications
  • -
  • Example Matrix
  • -
  • Setting up the Matrix to be inverted
  • -
  • Further properties (important for our analyses later)
  • -
  • Meet the Covariance Matrix
  • -
  • Introducing the Covariance and Correlation functions
  • -
  • Covariance and Correlation Matrix
  • -
  • Correlation Function and Design/Feature Matrix
  • -
  • Covariance Matrix Examples
  • -
  • Correlation Matrix
  • -
  • Correlation Matrix with Pandas
  • -
  • Correlation Matrix with Pandas and the Franke function
  • -
  • Rewriting the Covariance and/or Correlation Matrix
  • -
  • Linking with the SVD
  • -
  • What does it mean?
  • -
  • And finally \( \boldsymbol{X}\boldsymbol{X}^T \)
  • -
  • Ridge and LASSO Regression
  • -
  • Deriving the Ridge Regression Equations
  • -
  • Interpreting the Ridge results
  • -
  • More interpretations
  • -
  • Deriving the Lasso Regression Equations
  • -
  • Exercises for week 35
  • -
  • Exercise 1: Setting up various Python environments
  • -
  • Exercise 2: making your own data and exploring scikit-learn
  • -
  • Exercise 3: Normalizing our data
  • -
  • Exercise 4: Adding Ridge Regression
  • -
  • Exercise 5: Analytical exercises
  • +
  • Reducing the number of degrees of freedom, overarching view
  • +
  • Preprocessing our data
  • +
  • Functionality in Scikit-Learn
  • +
  • More preprocessing
  • +
  • Frequently used scaling functions
  • +
  • Example of own Standard scaling
  • +
  • Min-Max Scaling
  • +
  • Testing the Means Squared Error as function of Complexity
  • +
  • More preprocessing examples, two-dimensional example, the Franke function
  • +
  • To think about, first part
  • +
  • More thinking
  • +
  • Still thinking
  • +
  • What does centering (subtracting the mean values) mean mathematically?
  • +
  • Further Manipulations
  • +
  • Wrapping it up
  • +
  • Linear Regression code, Intercept handling first
  • +
  • The Boston housing data example
  • +
  • Housing data, the code
  • +
  • Material for lecture Thursday, August 31
  • +
  • Mathematical Interpretation of Ordinary Least Squares
  • +
  • Residual Error
  • +
  • Simple case
  • +
  • The singular value decomposition
  • +
  • Linear Regression Problems
  • +
  • Fixing the singularity
  • +
  • Basic math of the SVD
  • +
  • The SVD, a Fantastic Algorithm
  • +
  • Economy-size SVD
  • +
  • Codes for the SVD
  • +
  • Note about SVD Calculations
  • +
  • Mathematics of the SVD and implications
  • +
  • Example Matrix
  • +
  • Setting up the Matrix to be inverted
  • +
  • Further properties (important for our analyses later)
  • +
  • Meet the Covariance Matrix
  • +
  • Introducing the Covariance and Correlation functions
  • +
  • Covariance and Correlation Matrix
  • +
  • Correlation Function and Design/Feature Matrix
  • +
  • Covariance Matrix Examples
  • +
  • Correlation Matrix
  • +
  • Correlation Matrix with Pandas
  • +
  • Correlation Matrix with Pandas and the Franke function
  • +
  • Rewriting the Covariance and/or Correlation Matrix
  • +
  • Linking with the SVD
  • +
  • What does it mean?
  • +
  • And finally \( \boldsymbol{X}\boldsymbol{X}^T \)
  • +
  • Ridge and LASSO Regression
  • +
  • Deriving the Ridge Regression Equations
  • +
  • Interpreting the Ridge results
  • +
  • More interpretations
  • +
  • Deriving the Lasso Regression Equations
  • @@ -409,7 +410,7 @@ $$
  • 13
  • 14
  • ...
  • -
  • 68
  • +
  • 74
  • »
  • diff --git a/doc/pub/week35/html/._week35-bs005.html b/doc/pub/week35/html/._week35-bs005.html index 28739a72c..f35c1a82b 100644 --- a/doc/pub/week35/html/._week35-bs005.html +++ b/doc/pub/week35/html/._week35-bs005.html @@ -75,10 +75,10 @@ doconce format html week35.do.txt --html_style=bootstrap --pygments_html_style=d 2, None, 'interpretations-and-optimizing-our-parameters'), - ('Examples relevant for the exercises', + ('Example relevant for the exercises', 2, None, - 'examples-relevant-for-the-exercises'), + 'example-relevant-for-the-exercises'), ('Own code for Ordinary Least Squares', 2, None, @@ -91,16 +91,14 @@ doconce format html week35.do.txt --html_style=bootstrap --pygments_html_style=d 2, None, 'splitting-our-data-in-training-and-test-data'), - ('Examples', 2, None, 'examples'), + ('The complete code with a simple data set', + 2, + None, + 'the-complete-code-with-a-simple-data-set'), ('Making your own test-train splitting', 2, None, 'making-your-own-test-train-splitting'), - ('The Boston housing data example', - 2, - None, - 'the-boston-housing-data-example'), - ('Housing data, the code', 2, None, 'housing-data-the-code'), ('Reducing the number of degrees of freedom, overarching view', 2, None, @@ -124,10 +122,33 @@ doconce format html week35.do.txt --html_style=bootstrap --pygments_html_style=d 2, None, 'testing-the-means-squared-error-as-function-of-complexity'), - ('More preprocessing examples, Franke function and regression', + ('More preprocessing examples, two-dimensional example, the ' + 'Franke function', 2, None, - 'more-preprocessing-examples-franke-function-and-regression'), + 'more-preprocessing-examples-two-dimensional-example-the-franke-function'), + ('To think about, first part', + 2, + None, + 'to-think-about-first-part'), + ('More thinking', 2, None, 'more-thinking'), + ('Still thinking', 2, None, 'still-thinking'), + ('What does centering (subtracting the mean values) mean ' + 'mathematically?', + 2, + None, + 'what-does-centering-subtracting-the-mean-values-mean-mathematically'), + ('Further Manipulations', 2, None, 'further-manipulations'), + ('Wrapping it up', 2, None, 'wrapping-it-up'), + ('Linear Regression code, Intercept handling first', + 2, + None, + 'linear-regression-code-intercept-handling-first'), + ('The Boston housing data example', + 2, + None, + 'the-boston-housing-data-example'), + ('Housing data, the code', 2, None, 'housing-data-the-code'), ('Material for lecture Thursday, August 31', 2, None, @@ -226,28 +247,7 @@ doconce format html week35.do.txt --html_style=bootstrap --pygments_html_style=d ('Deriving the Lasso Regression Equations', 2, None, - 'deriving-the-lasso-regression-equations'), - ('Exercises for week 35', 2, None, 'exercises-for-week-35'), - ('Exercise 1: Setting up various Python environments', - 2, - None, - 'exercise-1-setting-up-various-python-environments'), - ('Exercise 2: making your own data and exploring scikit-learn', - 2, - None, - 'exercise-2-making-your-own-data-and-exploring-scikit-learn'), - ('Exercise 3: Normalizing our data', - 2, - None, - 'exercise-3-normalizing-our-data'), - ('Exercise 4: Adding Ridge Regression', - 2, - None, - 'exercise-4-adding-ridge-regression'), - ('Exercise 5: Analytical exercises', - 2, - None, - 'exercise-5-analytical-exercises')]} + 'deriving-the-lasso-regression-equations')]} end of tocinfo --> @@ -299,62 +299,63 @@ MathJax.Hub.Config({
  • Other useful relations
  • Meet the Hessian Matrix
  • Interpretations and optimizing our parameters
  • -
  • Examples relevant for the exercises
  • +
  • Example relevant for the exercises
  • Own code for Ordinary Least Squares
  • Adding error analysis and training set up
  • Splitting our Data in Training and Test data
  • -
  • Examples
  • +
  • The complete code with a simple data set
  • Making your own test-train splitting
  • -
  • The Boston housing data example
  • -
  • Housing data, the code
  • -
  • Reducing the number of degrees of freedom, overarching view
  • -
  • Preprocessing our data
  • -
  • Functionality in Scikit-Learn
  • -
  • More preprocessing
  • -
  • Frequently used scaling functions
  • -
  • Example of own Standard scaling
  • -
  • Min-Max Scaling
  • -
  • Testing the Means Squared Error as function of Complexity
  • -
  • More preprocessing examples, Franke function and regression
  • -
  • Material for lecture Thursday, August 31
  • -
  • Mathematical Interpretation of Ordinary Least Squares
  • -
  • Residual Error
  • -
  • Simple case
  • -
  • The singular value decomposition
  • -
  • Linear Regression Problems
  • -
  • Fixing the singularity
  • -
  • Basic math of the SVD
  • -
  • The SVD, a Fantastic Algorithm
  • -
  • Economy-size SVD
  • -
  • Codes for the SVD
  • -
  • Note about SVD Calculations
  • -
  • Mathematics of the SVD and implications
  • -
  • Example Matrix
  • -
  • Setting up the Matrix to be inverted
  • -
  • Further properties (important for our analyses later)
  • -
  • Meet the Covariance Matrix
  • -
  • Introducing the Covariance and Correlation functions
  • -
  • Covariance and Correlation Matrix
  • -
  • Correlation Function and Design/Feature Matrix
  • -
  • Covariance Matrix Examples
  • -
  • Correlation Matrix
  • -
  • Correlation Matrix with Pandas
  • -
  • Correlation Matrix with Pandas and the Franke function
  • -
  • Rewriting the Covariance and/or Correlation Matrix
  • -
  • Linking with the SVD
  • -
  • What does it mean?
  • -
  • And finally \( \boldsymbol{X}\boldsymbol{X}^T \)
  • -
  • Ridge and LASSO Regression
  • -
  • Deriving the Ridge Regression Equations
  • -
  • Interpreting the Ridge results
  • -
  • More interpretations
  • -
  • Deriving the Lasso Regression Equations
  • -
  • Exercises for week 35
  • -
  • Exercise 1: Setting up various Python environments
  • -
  • Exercise 2: making your own data and exploring scikit-learn
  • -
  • Exercise 3: Normalizing our data
  • -
  • Exercise 4: Adding Ridge Regression
  • -
  • Exercise 5: Analytical exercises
  • +
  • Reducing the number of degrees of freedom, overarching view
  • +
  • Preprocessing our data
  • +
  • Functionality in Scikit-Learn
  • +
  • More preprocessing
  • +
  • Frequently used scaling functions
  • +
  • Example of own Standard scaling
  • +
  • Min-Max Scaling
  • +
  • Testing the Means Squared Error as function of Complexity
  • +
  • More preprocessing examples, two-dimensional example, the Franke function
  • +
  • To think about, first part
  • +
  • More thinking
  • +
  • Still thinking
  • +
  • What does centering (subtracting the mean values) mean mathematically?
  • +
  • Further Manipulations
  • +
  • Wrapping it up
  • +
  • Linear Regression code, Intercept handling first
  • +
  • The Boston housing data example
  • +
  • Housing data, the code
  • +
  • Material for lecture Thursday, August 31
  • +
  • Mathematical Interpretation of Ordinary Least Squares
  • +
  • Residual Error
  • +
  • Simple case
  • +
  • The singular value decomposition
  • +
  • Linear Regression Problems
  • +
  • Fixing the singularity
  • +
  • Basic math of the SVD
  • +
  • The SVD, a Fantastic Algorithm
  • +
  • Economy-size SVD
  • +
  • Codes for the SVD
  • +
  • Note about SVD Calculations
  • +
  • Mathematics of the SVD and implications
  • +
  • Example Matrix
  • +
  • Setting up the Matrix to be inverted
  • +
  • Further properties (important for our analyses later)
  • +
  • Meet the Covariance Matrix
  • +
  • Introducing the Covariance and Correlation functions
  • +
  • Covariance and Correlation Matrix
  • +
  • Correlation Function and Design/Feature Matrix
  • +
  • Covariance Matrix Examples
  • +
  • Correlation Matrix
  • +
  • Correlation Matrix with Pandas
  • +
  • Correlation Matrix with Pandas and the Franke function
  • +
  • Rewriting the Covariance and/or Correlation Matrix
  • +
  • Linking with the SVD
  • +
  • What does it mean?
  • +
  • And finally \( \boldsymbol{X}\boldsymbol{X}^T \)
  • +
  • Ridge and LASSO Regression
  • +
  • Deriving the Ridge Regression Equations
  • +
  • Interpreting the Ridge results
  • +
  • More interpretations
  • +
  • Deriving the Lasso Regression Equations
  • @@ -374,7 +375,7 @@ C(\boldsymbol{\beta})=\frac{1}{n}\left\{\left(\boldsymbol{y}-\boldsymbol{X}\bold $$

    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 +When linking (see the discussions next week) with the maximum likelihood approach below, we will indeed interpret \( y_i \) as a mean value

    $$ y_{i}=\langle y_i \rangle = \beta_0x_{i,0}+\beta_1x_{i,1}+\beta_2x_{i,2}+\dots+\beta_{n-1}x_{i,n-1}+\epsilon_i, @@ -406,7 +407,7 @@ $$ \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

    +

    or in a matrix-vector form as (multiplying away the factor \( -2/n \))

    $$ \frac{\partial C(\boldsymbol{\beta})}{\partial \boldsymbol{\beta}} = 0 = \boldsymbol{X}^T\left( \boldsymbol{y}-\boldsymbol{X}\boldsymbol{\beta}\right). $$ @@ -432,7 +433,7 @@ $$
  • 14
  • 15
  • ...
  • -
  • 68
  • +
  • 74
  • »
  • diff --git a/doc/pub/week35/html/._week35-bs006.html b/doc/pub/week35/html/._week35-bs006.html index 77b312418..68947dd3a 100644 --- a/doc/pub/week35/html/._week35-bs006.html +++ b/doc/pub/week35/html/._week35-bs006.html @@ -75,10 +75,10 @@ doconce format html week35.do.txt --html_style=bootstrap --pygments_html_style=d 2, None, 'interpretations-and-optimizing-our-parameters'), - ('Examples relevant for the exercises', + ('Example relevant for the exercises', 2, None, - 'examples-relevant-for-the-exercises'), + 'example-relevant-for-the-exercises'), ('Own code for Ordinary Least Squares', 2, None, @@ -91,16 +91,14 @@ doconce format html week35.do.txt --html_style=bootstrap --pygments_html_style=d 2, None, 'splitting-our-data-in-training-and-test-data'), - ('Examples', 2, None, 'examples'), + ('The complete code with a simple data set', + 2, + None, + 'the-complete-code-with-a-simple-data-set'), ('Making your own test-train splitting', 2, None, 'making-your-own-test-train-splitting'), - ('The Boston housing data example', - 2, - None, - 'the-boston-housing-data-example'), - ('Housing data, the code', 2, None, 'housing-data-the-code'), ('Reducing the number of degrees of freedom, overarching view', 2, None, @@ -124,10 +122,33 @@ doconce format html week35.do.txt --html_style=bootstrap --pygments_html_style=d 2, None, 'testing-the-means-squared-error-as-function-of-complexity'), - ('More preprocessing examples, Franke function and regression', + ('More preprocessing examples, two-dimensional example, the ' + 'Franke function', 2, None, - 'more-preprocessing-examples-franke-function-and-regression'), + 'more-preprocessing-examples-two-dimensional-example-the-franke-function'), + ('To think about, first part', + 2, + None, + 'to-think-about-first-part'), + ('More thinking', 2, None, 'more-thinking'), + ('Still thinking', 2, None, 'still-thinking'), + ('What does centering (subtracting the mean values) mean ' + 'mathematically?', + 2, + None, + 'what-does-centering-subtracting-the-mean-values-mean-mathematically'), + ('Further Manipulations', 2, None, 'further-manipulations'), + ('Wrapping it up', 2, None, 'wrapping-it-up'), + ('Linear Regression code, Intercept handling first', + 2, + None, + 'linear-regression-code-intercept-handling-first'), + ('The Boston housing data example', + 2, + None, + 'the-boston-housing-data-example'), + ('Housing data, the code', 2, None, 'housing-data-the-code'), ('Material for lecture Thursday, August 31', 2, None, @@ -226,28 +247,7 @@ doconce format html week35.do.txt --html_style=bootstrap --pygments_html_style=d ('Deriving the Lasso Regression Equations', 2, None, - 'deriving-the-lasso-regression-equations'), - ('Exercises for week 35', 2, None, 'exercises-for-week-35'), - ('Exercise 1: Setting up various Python environments', - 2, - None, - 'exercise-1-setting-up-various-python-environments'), - ('Exercise 2: making your own data and exploring scikit-learn', - 2, - None, - 'exercise-2-making-your-own-data-and-exploring-scikit-learn'), - ('Exercise 3: Normalizing our data', - 2, - None, - 'exercise-3-normalizing-our-data'), - ('Exercise 4: Adding Ridge Regression', - 2, - None, - 'exercise-4-adding-ridge-regression'), - ('Exercise 5: Analytical exercises', - 2, - None, - 'exercise-5-analytical-exercises')]} + 'deriving-the-lasso-regression-equations')]} end of tocinfo --> @@ -299,62 +299,63 @@ MathJax.Hub.Config({
  • Other useful relations
  • Meet the Hessian Matrix
  • Interpretations and optimizing our parameters
  • -
  • Examples relevant for the exercises
  • +
  • Example relevant for the exercises
  • Own code for Ordinary Least Squares
  • Adding error analysis and training set up
  • Splitting our Data in Training and Test data
  • -
  • Examples
  • +
  • The complete code with a simple data set
  • Making your own test-train splitting
  • -
  • The Boston housing data example
  • -
  • Housing data, the code
  • -
  • Reducing the number of degrees of freedom, overarching view
  • -
  • Preprocessing our data
  • -
  • Functionality in Scikit-Learn
  • -
  • More preprocessing
  • -
  • Frequently used scaling functions
  • -
  • Example of own Standard scaling
  • -
  • Min-Max Scaling
  • -
  • Testing the Means Squared Error as function of Complexity
  • -
  • More preprocessing examples, Franke function and regression
  • -
  • Material for lecture Thursday, August 31
  • -
  • Mathematical Interpretation of Ordinary Least Squares
  • -
  • Residual Error
  • -
  • Simple case
  • -
  • The singular value decomposition
  • -
  • Linear Regression Problems
  • -
  • Fixing the singularity
  • -
  • Basic math of the SVD
  • -
  • The SVD, a Fantastic Algorithm
  • -
  • Economy-size SVD
  • -
  • Codes for the SVD
  • -
  • Note about SVD Calculations
  • -
  • Mathematics of the SVD and implications
  • -
  • Example Matrix
  • -
  • Setting up the Matrix to be inverted
  • -
  • Further properties (important for our analyses later)
  • -
  • Meet the Covariance Matrix
  • -
  • Introducing the Covariance and Correlation functions
  • -
  • Covariance and Correlation Matrix
  • -
  • Correlation Function and Design/Feature Matrix
  • -
  • Covariance Matrix Examples
  • -
  • Correlation Matrix
  • -
  • Correlation Matrix with Pandas
  • -
  • Correlation Matrix with Pandas and the Franke function
  • -
  • Rewriting the Covariance and/or Correlation Matrix
  • -
  • Linking with the SVD
  • -
  • What does it mean?
  • -
  • And finally \( \boldsymbol{X}\boldsymbol{X}^T \)
  • -
  • Ridge and LASSO Regression
  • -
  • Deriving the Ridge Regression Equations
  • -
  • Interpreting the Ridge results
  • -
  • More interpretations
  • -
  • Deriving the Lasso Regression Equations
  • -
  • Exercises for week 35
  • -
  • Exercise 1: Setting up various Python environments
  • -
  • Exercise 2: making your own data and exploring scikit-learn
  • -
  • Exercise 3: Normalizing our data
  • -
  • Exercise 4: Adding Ridge Regression
  • -
  • Exercise 5: Analytical exercises
  • +
  • Reducing the number of degrees of freedom, overarching view
  • +
  • Preprocessing our data
  • +
  • Functionality in Scikit-Learn
  • +
  • More preprocessing
  • +
  • Frequently used scaling functions
  • +
  • Example of own Standard scaling
  • +
  • Min-Max Scaling
  • +
  • Testing the Means Squared Error as function of Complexity
  • +
  • More preprocessing examples, two-dimensional example, the Franke function
  • +
  • To think about, first part
  • +
  • More thinking
  • +
  • Still thinking
  • +
  • What does centering (subtracting the mean values) mean mathematically?
  • +
  • Further Manipulations
  • +
  • Wrapping it up
  • +
  • Linear Regression code, Intercept handling first
  • +
  • The Boston housing data example
  • +
  • Housing data, the code
  • +
  • Material for lecture Thursday, August 31
  • +
  • Mathematical Interpretation of Ordinary Least Squares
  • +
  • Residual Error
  • +
  • Simple case
  • +
  • The singular value decomposition
  • +
  • Linear Regression Problems
  • +
  • Fixing the singularity
  • +
  • Basic math of the SVD
  • +
  • The SVD, a Fantastic Algorithm
  • +
  • Economy-size SVD
  • +
  • Codes for the SVD
  • +
  • Note about SVD Calculations
  • +
  • Mathematics of the SVD and implications
  • +
  • Example Matrix
  • +
  • Setting up the Matrix to be inverted
  • +
  • Further properties (important for our analyses later)
  • +
  • Meet the Covariance Matrix
  • +
  • Introducing the Covariance and Correlation functions
  • +
  • Covariance and Correlation Matrix
  • +
  • Correlation Function and Design/Feature Matrix
  • +
  • Covariance Matrix Examples
  • +
  • Correlation Matrix
  • +
  • Correlation Matrix with Pandas
  • +
  • Correlation Matrix with Pandas and the Franke function
  • +
  • Rewriting the Covariance and/or Correlation Matrix
  • +
  • Linking with the SVD
  • +
  • What does it mean?
  • +
  • And finally \( \boldsymbol{X}\boldsymbol{X}^T \)
  • +
  • Ridge and LASSO Regression
  • +
  • Deriving the Ridge Regression Equations
  • +
  • Interpreting the Ridge results
  • +
  • More interpretations
  • +
  • Deriving the Lasso Regression Equations
  • @@ -429,7 +430,7 @@ allow for the usage of direct linear algebra methods such as LU decomposi
  • 15
  • 16
  • ...
  • -
  • 68
  • +
  • 74
  • »
  • diff --git a/doc/pub/week35/html/._week35-bs007.html b/doc/pub/week35/html/._week35-bs007.html index 154eb9f9b..7507a88f8 100644 --- a/doc/pub/week35/html/._week35-bs007.html +++ b/doc/pub/week35/html/._week35-bs007.html @@ -75,10 +75,10 @@ doconce format html week35.do.txt --html_style=bootstrap --pygments_html_style=d 2, None, 'interpretations-and-optimizing-our-parameters'), - ('Examples relevant for the exercises', + ('Example relevant for the exercises', 2, None, - 'examples-relevant-for-the-exercises'), + 'example-relevant-for-the-exercises'), ('Own code for Ordinary Least Squares', 2, None, @@ -91,16 +91,14 @@ doconce format html week35.do.txt --html_style=bootstrap --pygments_html_style=d 2, None, 'splitting-our-data-in-training-and-test-data'), - ('Examples', 2, None, 'examples'), + ('The complete code with a simple data set', + 2, + None, + 'the-complete-code-with-a-simple-data-set'), ('Making your own test-train splitting', 2, None, 'making-your-own-test-train-splitting'), - ('The Boston housing data example', - 2, - None, - 'the-boston-housing-data-example'), - ('Housing data, the code', 2, None, 'housing-data-the-code'), ('Reducing the number of degrees of freedom, overarching view', 2, None, @@ -124,10 +122,33 @@ doconce format html week35.do.txt --html_style=bootstrap --pygments_html_style=d 2, None, 'testing-the-means-squared-error-as-function-of-complexity'), - ('More preprocessing examples, Franke function and regression', + ('More preprocessing examples, two-dimensional example, the ' + 'Franke function', 2, None, - 'more-preprocessing-examples-franke-function-and-regression'), + 'more-preprocessing-examples-two-dimensional-example-the-franke-function'), + ('To think about, first part', + 2, + None, + 'to-think-about-first-part'), + ('More thinking', 2, None, 'more-thinking'), + ('Still thinking', 2, None, 'still-thinking'), + ('What does centering (subtracting the mean values) mean ' + 'mathematically?', + 2, + None, + 'what-does-centering-subtracting-the-mean-values-mean-mathematically'), + ('Further Manipulations', 2, None, 'further-manipulations'), + ('Wrapping it up', 2, None, 'wrapping-it-up'), + ('Linear Regression code, Intercept handling first', + 2, + None, + 'linear-regression-code-intercept-handling-first'), + ('The Boston housing data example', + 2, + None, + 'the-boston-housing-data-example'), + ('Housing data, the code', 2, None, 'housing-data-the-code'), ('Material for lecture Thursday, August 31', 2, None, @@ -226,28 +247,7 @@ doconce format html week35.do.txt --html_style=bootstrap --pygments_html_style=d ('Deriving the Lasso Regression Equations', 2, None, - 'deriving-the-lasso-regression-equations'), - ('Exercises for week 35', 2, None, 'exercises-for-week-35'), - ('Exercise 1: Setting up various Python environments', - 2, - None, - 'exercise-1-setting-up-various-python-environments'), - ('Exercise 2: making your own data and exploring scikit-learn', - 2, - None, - 'exercise-2-making-your-own-data-and-exploring-scikit-learn'), - ('Exercise 3: Normalizing our data', - 2, - None, - 'exercise-3-normalizing-our-data'), - ('Exercise 4: Adding Ridge Regression', - 2, - None, - 'exercise-4-adding-ridge-regression'), - ('Exercise 5: Analytical exercises', - 2, - None, - 'exercise-5-analytical-exercises')]} + 'deriving-the-lasso-regression-equations')]} end of tocinfo --> @@ -299,62 +299,63 @@ MathJax.Hub.Config({
  • Other useful relations
  • Meet the Hessian Matrix
  • Interpretations and optimizing our parameters
  • -
  • Examples relevant for the exercises
  • +
  • Example relevant for the exercises
  • Own code for Ordinary Least Squares
  • Adding error analysis and training set up
  • Splitting our Data in Training and Test data
  • -
  • Examples
  • +
  • The complete code with a simple data set
  • Making your own test-train splitting
  • -
  • The Boston housing data example
  • -
  • Housing data, the code
  • -
  • Reducing the number of degrees of freedom, overarching view
  • -
  • Preprocessing our data
  • -
  • Functionality in Scikit-Learn
  • -
  • More preprocessing
  • -
  • Frequently used scaling functions
  • -
  • Example of own Standard scaling
  • -
  • Min-Max Scaling
  • -
  • Testing the Means Squared Error as function of Complexity
  • -
  • More preprocessing examples, Franke function and regression
  • -
  • Material for lecture Thursday, August 31
  • -
  • Mathematical Interpretation of Ordinary Least Squares
  • -
  • Residual Error
  • -
  • Simple case
  • -
  • The singular value decomposition
  • -
  • Linear Regression Problems
  • -
  • Fixing the singularity
  • -
  • Basic math of the SVD
  • -
  • The SVD, a Fantastic Algorithm
  • -
  • Economy-size SVD
  • -
  • Codes for the SVD
  • -
  • Note about SVD Calculations
  • -
  • Mathematics of the SVD and implications
  • -
  • Example Matrix
  • -
  • Setting up the Matrix to be inverted
  • -
  • Further properties (important for our analyses later)
  • -
  • Meet the Covariance Matrix
  • -
  • Introducing the Covariance and Correlation functions
  • -
  • Covariance and Correlation Matrix
  • -
  • Correlation Function and Design/Feature Matrix
  • -
  • Covariance Matrix Examples
  • -
  • Correlation Matrix
  • -
  • Correlation Matrix with Pandas
  • -
  • Correlation Matrix with Pandas and the Franke function
  • -
  • Rewriting the Covariance and/or Correlation Matrix
  • -
  • Linking with the SVD
  • -
  • What does it mean?
  • -
  • And finally \( \boldsymbol{X}\boldsymbol{X}^T \)
  • -
  • Ridge and LASSO Regression
  • -
  • Deriving the Ridge Regression Equations
  • -
  • Interpreting the Ridge results
  • -
  • More interpretations
  • -
  • Deriving the Lasso Regression Equations
  • -
  • Exercises for week 35
  • -
  • Exercise 1: Setting up various Python environments
  • -
  • Exercise 2: making your own data and exploring scikit-learn
  • -
  • Exercise 3: Normalizing our data
  • -
  • Exercise 4: Adding Ridge Regression
  • -
  • Exercise 5: Analytical exercises
  • +
  • Reducing the number of degrees of freedom, overarching view
  • +
  • Preprocessing our data
  • +
  • Functionality in Scikit-Learn
  • +
  • More preprocessing
  • +
  • Frequently used scaling functions
  • +
  • Example of own Standard scaling
  • +
  • Min-Max Scaling
  • +
  • Testing the Means Squared Error as function of Complexity
  • +
  • More preprocessing examples, two-dimensional example, the Franke function
  • +
  • To think about, first part
  • +
  • More thinking
  • +
  • Still thinking
  • +
  • What does centering (subtracting the mean values) mean mathematically?
  • +
  • Further Manipulations
  • +
  • Wrapping it up
  • +
  • Linear Regression code, Intercept handling first
  • +
  • The Boston housing data example
  • +
  • Housing data, the code
  • +
  • Material for lecture Thursday, August 31
  • +
  • Mathematical Interpretation of Ordinary Least Squares
  • +
  • Residual Error
  • +
  • Simple case
  • +
  • The singular value decomposition
  • +
  • Linear Regression Problems
  • +
  • Fixing the singularity
  • +
  • Basic math of the SVD
  • +
  • The SVD, a Fantastic Algorithm
  • +
  • Economy-size SVD
  • +
  • Codes for the SVD
  • +
  • Note about SVD Calculations
  • +
  • Mathematics of the SVD and implications
  • +
  • Example Matrix
  • +
  • Setting up the Matrix to be inverted
  • +
  • Further properties (important for our analyses later)
  • +
  • Meet the Covariance Matrix
  • +
  • Introducing the Covariance and Correlation functions
  • +
  • Covariance and Correlation Matrix
  • +
  • Correlation Function and Design/Feature Matrix
  • +
  • Covariance Matrix Examples
  • +
  • Correlation Matrix
  • +
  • Correlation Matrix with Pandas
  • +
  • Correlation Matrix with Pandas and the Franke function
  • +
  • Rewriting the Covariance and/or Correlation Matrix
  • +
  • Linking with the SVD
  • +
  • What does it mean?
  • +
  • And finally \( \boldsymbol{X}\boldsymbol{X}^T \)
  • +
  • Ridge and LASSO Regression
  • +
  • Deriving the Ridge Regression Equations
  • +
  • Interpreting the Ridge results
  • +
  • More interpretations
  • +
  • Deriving the Lasso Regression Equations
  • @@ -415,7 +416,7 @@ $$
  • 16
  • 17
  • ...
  • -
  • 68
  • +
  • 74
  • »
  • diff --git a/doc/pub/week35/html/._week35-bs008.html b/doc/pub/week35/html/._week35-bs008.html index c1cd15753..a573f9a7f 100644 --- a/doc/pub/week35/html/._week35-bs008.html +++ b/doc/pub/week35/html/._week35-bs008.html @@ -75,10 +75,10 @@ doconce format html week35.do.txt --html_style=bootstrap --pygments_html_style=d 2, None, 'interpretations-and-optimizing-our-parameters'), - ('Examples relevant for the exercises', + ('Example relevant for the exercises', 2, None, - 'examples-relevant-for-the-exercises'), + 'example-relevant-for-the-exercises'), ('Own code for Ordinary Least Squares', 2, None, @@ -91,16 +91,14 @@ doconce format html week35.do.txt --html_style=bootstrap --pygments_html_style=d 2, None, 'splitting-our-data-in-training-and-test-data'), - ('Examples', 2, None, 'examples'), + ('The complete code with a simple data set', + 2, + None, + 'the-complete-code-with-a-simple-data-set'), ('Making your own test-train splitting', 2, None, 'making-your-own-test-train-splitting'), - ('The Boston housing data example', - 2, - None, - 'the-boston-housing-data-example'), - ('Housing data, the code', 2, None, 'housing-data-the-code'), ('Reducing the number of degrees of freedom, overarching view', 2, None, @@ -124,10 +122,33 @@ doconce format html week35.do.txt --html_style=bootstrap --pygments_html_style=d 2, None, 'testing-the-means-squared-error-as-function-of-complexity'), - ('More preprocessing examples, Franke function and regression', + ('More preprocessing examples, two-dimensional example, the ' + 'Franke function', 2, None, - 'more-preprocessing-examples-franke-function-and-regression'), + 'more-preprocessing-examples-two-dimensional-example-the-franke-function'), + ('To think about, first part', + 2, + None, + 'to-think-about-first-part'), + ('More thinking', 2, None, 'more-thinking'), + ('Still thinking', 2, None, 'still-thinking'), + ('What does centering (subtracting the mean values) mean ' + 'mathematically?', + 2, + None, + 'what-does-centering-subtracting-the-mean-values-mean-mathematically'), + ('Further Manipulations', 2, None, 'further-manipulations'), + ('Wrapping it up', 2, None, 'wrapping-it-up'), + ('Linear Regression code, Intercept handling first', + 2, + None, + 'linear-regression-code-intercept-handling-first'), + ('The Boston housing data example', + 2, + None, + 'the-boston-housing-data-example'), + ('Housing data, the code', 2, None, 'housing-data-the-code'), ('Material for lecture Thursday, August 31', 2, None, @@ -226,28 +247,7 @@ doconce format html week35.do.txt --html_style=bootstrap --pygments_html_style=d ('Deriving the Lasso Regression Equations', 2, None, - 'deriving-the-lasso-regression-equations'), - ('Exercises for week 35', 2, None, 'exercises-for-week-35'), - ('Exercise 1: Setting up various Python environments', - 2, - None, - 'exercise-1-setting-up-various-python-environments'), - ('Exercise 2: making your own data and exploring scikit-learn', - 2, - None, - 'exercise-2-making-your-own-data-and-exploring-scikit-learn'), - ('Exercise 3: Normalizing our data', - 2, - None, - 'exercise-3-normalizing-our-data'), - ('Exercise 4: Adding Ridge Regression', - 2, - None, - 'exercise-4-adding-ridge-regression'), - ('Exercise 5: Analytical exercises', - 2, - None, - 'exercise-5-analytical-exercises')]} + 'deriving-the-lasso-regression-equations')]} end of tocinfo --> @@ -299,62 +299,63 @@ MathJax.Hub.Config({
  • Other useful relations
  • Meet the Hessian Matrix
  • Interpretations and optimizing our parameters
  • -
  • Examples relevant for the exercises
  • +
  • Example relevant for the exercises
  • Own code for Ordinary Least Squares
  • Adding error analysis and training set up
  • Splitting our Data in Training and Test data
  • -
  • Examples
  • +
  • The complete code with a simple data set
  • Making your own test-train splitting
  • -
  • The Boston housing data example
  • -
  • Housing data, the code
  • -
  • Reducing the number of degrees of freedom, overarching view
  • -
  • Preprocessing our data
  • -
  • Functionality in Scikit-Learn
  • -
  • More preprocessing
  • -
  • Frequently used scaling functions
  • -
  • Example of own Standard scaling
  • -
  • Min-Max Scaling
  • -
  • Testing the Means Squared Error as function of Complexity
  • -
  • More preprocessing examples, Franke function and regression
  • -
  • Material for lecture Thursday, August 31
  • -
  • Mathematical Interpretation of Ordinary Least Squares
  • -
  • Residual Error
  • -
  • Simple case
  • -
  • The singular value decomposition
  • -
  • Linear Regression Problems
  • -
  • Fixing the singularity
  • -
  • Basic math of the SVD
  • -
  • The SVD, a Fantastic Algorithm
  • -
  • Economy-size SVD
  • -
  • Codes for the SVD
  • -
  • Note about SVD Calculations
  • -
  • Mathematics of the SVD and implications
  • -
  • Example Matrix
  • -
  • Setting up the Matrix to be inverted
  • -
  • Further properties (important for our analyses later)
  • -
  • Meet the Covariance Matrix
  • -
  • Introducing the Covariance and Correlation functions
  • -
  • Covariance and Correlation Matrix
  • -
  • Correlation Function and Design/Feature Matrix
  • -
  • Covariance Matrix Examples
  • -
  • Correlation Matrix
  • -
  • Correlation Matrix with Pandas
  • -
  • Correlation Matrix with Pandas and the Franke function
  • -
  • Rewriting the Covariance and/or Correlation Matrix
  • -
  • Linking with the SVD
  • -
  • What does it mean?
  • -
  • And finally \( \boldsymbol{X}\boldsymbol{X}^T \)
  • -
  • Ridge and LASSO Regression
  • -
  • Deriving the Ridge Regression Equations
  • -
  • Interpreting the Ridge results
  • -
  • More interpretations
  • -
  • Deriving the Lasso Regression Equations
  • -
  • Exercises for week 35
  • -
  • Exercise 1: Setting up various Python environments
  • -
  • Exercise 2: making your own data and exploring scikit-learn
  • -
  • Exercise 3: Normalizing our data
  • -
  • Exercise 4: Adding Ridge Regression
  • -
  • Exercise 5: Analytical exercises
  • +
  • Reducing the number of degrees of freedom, overarching view
  • +
  • Preprocessing our data
  • +
  • Functionality in Scikit-Learn
  • +
  • More preprocessing
  • +
  • Frequently used scaling functions
  • +
  • Example of own Standard scaling
  • +
  • Min-Max Scaling
  • +
  • Testing the Means Squared Error as function of Complexity
  • +
  • More preprocessing examples, two-dimensional example, the Franke function
  • +
  • To think about, first part
  • +
  • More thinking
  • +
  • Still thinking
  • +
  • What does centering (subtracting the mean values) mean mathematically?
  • +
  • Further Manipulations
  • +
  • Wrapping it up
  • +
  • Linear Regression code, Intercept handling first
  • +
  • The Boston housing data example
  • +
  • Housing data, the code
  • +
  • Material for lecture Thursday, August 31
  • +
  • Mathematical Interpretation of Ordinary Least Squares
  • +
  • Residual Error
  • +
  • Simple case
  • +
  • The singular value decomposition
  • +
  • Linear Regression Problems
  • +
  • Fixing the singularity
  • +
  • Basic math of the SVD
  • +
  • The SVD, a Fantastic Algorithm
  • +
  • Economy-size SVD
  • +
  • Codes for the SVD
  • +
  • Note about SVD Calculations
  • +
  • Mathematics of the SVD and implications
  • +
  • Example Matrix
  • +
  • Setting up the Matrix to be inverted
  • +
  • Further properties (important for our analyses later)
  • +
  • Meet the Covariance Matrix
  • +
  • Introducing the Covariance and Correlation functions
  • +
  • Covariance and Correlation Matrix
  • +
  • Correlation Function and Design/Feature Matrix
  • +
  • Covariance Matrix Examples
  • +
  • Correlation Matrix
  • +
  • Correlation Matrix with Pandas
  • +
  • Correlation Matrix with Pandas and the Franke function
  • +
  • Rewriting the Covariance and/or Correlation Matrix
  • +
  • Linking with the SVD
  • +
  • What does it mean?
  • +
  • And finally \( \boldsymbol{X}\boldsymbol{X}^T \)
  • +
  • Ridge and LASSO Regression
  • +
  • Deriving the Ridge Regression Equations
  • +
  • Interpreting the Ridge results
  • +
  • More interpretations
  • +
  • Deriving the Lasso Regression Equations
  • @@ -413,7 +414,7 @@ vector is differentiable.
  • 17
  • 18
  • ...
  • -
  • 68
  • +
  • 74
  • »
  • diff --git a/doc/pub/week35/html/._week35-bs009.html b/doc/pub/week35/html/._week35-bs009.html index 6f341a734..56472ad79 100644 --- a/doc/pub/week35/html/._week35-bs009.html +++ b/doc/pub/week35/html/._week35-bs009.html @@ -75,10 +75,10 @@ doconce format html week35.do.txt --html_style=bootstrap --pygments_html_style=d 2, None, 'interpretations-and-optimizing-our-parameters'), - ('Examples relevant for the exercises', + ('Example relevant for the exercises', 2, None, - 'examples-relevant-for-the-exercises'), + 'example-relevant-for-the-exercises'), ('Own code for Ordinary Least Squares', 2, None, @@ -91,16 +91,14 @@ doconce format html week35.do.txt --html_style=bootstrap --pygments_html_style=d 2, None, 'splitting-our-data-in-training-and-test-data'), - ('Examples', 2, None, 'examples'), + ('The complete code with a simple data set', + 2, + None, + 'the-complete-code-with-a-simple-data-set'), ('Making your own test-train splitting', 2, None, 'making-your-own-test-train-splitting'), - ('The Boston housing data example', - 2, - None, - 'the-boston-housing-data-example'), - ('Housing data, the code', 2, None, 'housing-data-the-code'), ('Reducing the number of degrees of freedom, overarching view', 2, None, @@ -124,10 +122,33 @@ doconce format html week35.do.txt --html_style=bootstrap --pygments_html_style=d 2, None, 'testing-the-means-squared-error-as-function-of-complexity'), - ('More preprocessing examples, Franke function and regression', + ('More preprocessing examples, two-dimensional example, the ' + 'Franke function', 2, None, - 'more-preprocessing-examples-franke-function-and-regression'), + 'more-preprocessing-examples-two-dimensional-example-the-franke-function'), + ('To think about, first part', + 2, + None, + 'to-think-about-first-part'), + ('More thinking', 2, None, 'more-thinking'), + ('Still thinking', 2, None, 'still-thinking'), + ('What does centering (subtracting the mean values) mean ' + 'mathematically?', + 2, + None, + 'what-does-centering-subtracting-the-mean-values-mean-mathematically'), + ('Further Manipulations', 2, None, 'further-manipulations'), + ('Wrapping it up', 2, None, 'wrapping-it-up'), + ('Linear Regression code, Intercept handling first', + 2, + None, + 'linear-regression-code-intercept-handling-first'), + ('The Boston housing data example', + 2, + None, + 'the-boston-housing-data-example'), + ('Housing data, the code', 2, None, 'housing-data-the-code'), ('Material for lecture Thursday, August 31', 2, None, @@ -226,28 +247,7 @@ doconce format html week35.do.txt --html_style=bootstrap --pygments_html_style=d ('Deriving the Lasso Regression Equations', 2, None, - 'deriving-the-lasso-regression-equations'), - ('Exercises for week 35', 2, None, 'exercises-for-week-35'), - ('Exercise 1: Setting up various Python environments', - 2, - None, - 'exercise-1-setting-up-various-python-environments'), - ('Exercise 2: making your own data and exploring scikit-learn', - 2, - None, - 'exercise-2-making-your-own-data-and-exploring-scikit-learn'), - ('Exercise 3: Normalizing our data', - 2, - None, - 'exercise-3-normalizing-our-data'), - ('Exercise 4: Adding Ridge Regression', - 2, - None, - 'exercise-4-adding-ridge-regression'), - ('Exercise 5: Analytical exercises', - 2, - None, - 'exercise-5-analytical-exercises')]} + 'deriving-the-lasso-regression-equations')]} end of tocinfo --> @@ -299,62 +299,63 @@ MathJax.Hub.Config({
  • Other useful relations
  • Meet the Hessian Matrix
  • Interpretations and optimizing our parameters
  • -
  • Examples relevant for the exercises
  • +
  • Example relevant for the exercises
  • Own code for Ordinary Least Squares
  • Adding error analysis and training set up
  • Splitting our Data in Training and Test data
  • -
  • Examples
  • +
  • The complete code with a simple data set
  • Making your own test-train splitting
  • -
  • The Boston housing data example
  • -
  • Housing data, the code
  • -
  • Reducing the number of degrees of freedom, overarching view
  • -
  • Preprocessing our data
  • -
  • Functionality in Scikit-Learn
  • -
  • More preprocessing
  • -
  • Frequently used scaling functions
  • -
  • Example of own Standard scaling
  • -
  • Min-Max Scaling
  • -
  • Testing the Means Squared Error as function of Complexity
  • -
  • More preprocessing examples, Franke function and regression
  • -
  • Material for lecture Thursday, August 31
  • -
  • Mathematical Interpretation of Ordinary Least Squares
  • -
  • Residual Error
  • -
  • Simple case
  • -
  • The singular value decomposition
  • -
  • Linear Regression Problems
  • -
  • Fixing the singularity
  • -
  • Basic math of the SVD
  • -
  • The SVD, a Fantastic Algorithm
  • -
  • Economy-size SVD
  • -
  • Codes for the SVD
  • -
  • Note about SVD Calculations
  • -
  • Mathematics of the SVD and implications
  • -
  • Example Matrix
  • -
  • Setting up the Matrix to be inverted
  • -
  • Further properties (important for our analyses later)
  • -
  • Meet the Covariance Matrix
  • -
  • Introducing the Covariance and Correlation functions
  • -
  • Covariance and Correlation Matrix
  • -
  • Correlation Function and Design/Feature Matrix
  • -
  • Covariance Matrix Examples
  • -
  • Correlation Matrix
  • -
  • Correlation Matrix with Pandas
  • -
  • Correlation Matrix with Pandas and the Franke function
  • -
  • Rewriting the Covariance and/or Correlation Matrix
  • -
  • Linking with the SVD
  • -
  • What does it mean?
  • -
  • And finally \( \boldsymbol{X}\boldsymbol{X}^T \)
  • -
  • Ridge and LASSO Regression
  • -
  • Deriving the Ridge Regression Equations
  • -
  • Interpreting the Ridge results
  • -
  • More interpretations
  • -
  • Deriving the Lasso Regression Equations
  • -
  • Exercises for week 35
  • -
  • Exercise 1: Setting up various Python environments
  • -
  • Exercise 2: making your own data and exploring scikit-learn
  • -
  • Exercise 3: Normalizing our data
  • -
  • Exercise 4: Adding Ridge Regression
  • -
  • Exercise 5: Analytical exercises
  • +
  • Reducing the number of degrees of freedom, overarching view
  • +
  • Preprocessing our data
  • +
  • Functionality in Scikit-Learn
  • +
  • More preprocessing
  • +
  • Frequently used scaling functions
  • +
  • Example of own Standard scaling
  • +
  • Min-Max Scaling
  • +
  • Testing the Means Squared Error as function of Complexity
  • +
  • More preprocessing examples, two-dimensional example, the Franke function
  • +
  • To think about, first part
  • +
  • More thinking
  • +
  • Still thinking
  • +
  • What does centering (subtracting the mean values) mean mathematically?
  • +
  • Further Manipulations
  • +
  • Wrapping it up
  • +
  • Linear Regression code, Intercept handling first
  • +
  • The Boston housing data example
  • +
  • Housing data, the code
  • +
  • Material for lecture Thursday, August 31
  • +
  • Mathematical Interpretation of Ordinary Least Squares
  • +
  • Residual Error
  • +
  • Simple case
  • +
  • The singular value decomposition
  • +
  • Linear Regression Problems
  • +
  • Fixing the singularity
  • +
  • Basic math of the SVD
  • +
  • The SVD, a Fantastic Algorithm
  • +
  • Economy-size SVD
  • +
  • Codes for the SVD
  • +
  • Note about SVD Calculations
  • +
  • Mathematics of the SVD and implications
  • +
  • Example Matrix
  • +
  • Setting up the Matrix to be inverted
  • +
  • Further properties (important for our analyses later)
  • +
  • Meet the Covariance Matrix
  • +
  • Introducing the Covariance and Correlation functions
  • +
  • Covariance and Correlation Matrix
  • +
  • Correlation Function and Design/Feature Matrix
  • +
  • Covariance Matrix Examples
  • +
  • Correlation Matrix
  • +
  • Correlation Matrix with Pandas
  • +
  • Correlation Matrix with Pandas and the Franke function
  • +
  • Rewriting the Covariance and/or Correlation Matrix
  • +
  • Linking with the SVD
  • +
  • What does it mean?
  • +
  • And finally \( \boldsymbol{X}\boldsymbol{X}^T \)
  • +
  • Ridge and LASSO Regression
  • +
  • Deriving the Ridge Regression Equations
  • +
  • Interpreting the Ridge results
  • +
  • More interpretations
  • +
  • Deriving the Lasso Regression Equations
  • @@ -412,7 +413,7 @@ $$
  • 18
  • 19
  • ...
  • -
  • 68
  • +
  • 74
  • »
  • diff --git a/doc/pub/week35/html/._week35-bs010.html b/doc/pub/week35/html/._week35-bs010.html index 9da4869b3..408f18d6c 100644 --- a/doc/pub/week35/html/._week35-bs010.html +++ b/doc/pub/week35/html/._week35-bs010.html @@ -75,10 +75,10 @@ doconce format html week35.do.txt --html_style=bootstrap --pygments_html_style=d 2, None, 'interpretations-and-optimizing-our-parameters'), - ('Examples relevant for the exercises', + ('Example relevant for the exercises', 2, None, - 'examples-relevant-for-the-exercises'), + 'example-relevant-for-the-exercises'), ('Own code for Ordinary Least Squares', 2, None, @@ -91,16 +91,14 @@ doconce format html week35.do.txt --html_style=bootstrap --pygments_html_style=d 2, None, 'splitting-our-data-in-training-and-test-data'), - ('Examples', 2, None, 'examples'), + ('The complete code with a simple data set', + 2, + None, + 'the-complete-code-with-a-simple-data-set'), ('Making your own test-train splitting', 2, None, 'making-your-own-test-train-splitting'), - ('The Boston housing data example', - 2, - None, - 'the-boston-housing-data-example'), - ('Housing data, the code', 2, None, 'housing-data-the-code'), ('Reducing the number of degrees of freedom, overarching view', 2, None, @@ -124,10 +122,33 @@ doconce format html week35.do.txt --html_style=bootstrap --pygments_html_style=d 2, None, 'testing-the-means-squared-error-as-function-of-complexity'), - ('More preprocessing examples, Franke function and regression', + ('More preprocessing examples, two-dimensional example, the ' + 'Franke function', 2, None, - 'more-preprocessing-examples-franke-function-and-regression'), + 'more-preprocessing-examples-two-dimensional-example-the-franke-function'), + ('To think about, first part', + 2, + None, + 'to-think-about-first-part'), + ('More thinking', 2, None, 'more-thinking'), + ('Still thinking', 2, None, 'still-thinking'), + ('What does centering (subtracting the mean values) mean ' + 'mathematically?', + 2, + None, + 'what-does-centering-subtracting-the-mean-values-mean-mathematically'), + ('Further Manipulations', 2, None, 'further-manipulations'), + ('Wrapping it up', 2, None, 'wrapping-it-up'), + ('Linear Regression code, Intercept handling first', + 2, + None, + 'linear-regression-code-intercept-handling-first'), + ('The Boston housing data example', + 2, + None, + 'the-boston-housing-data-example'), + ('Housing data, the code', 2, None, 'housing-data-the-code'), ('Material for lecture Thursday, August 31', 2, None, @@ -226,28 +247,7 @@ doconce format html week35.do.txt --html_style=bootstrap --pygments_html_style=d ('Deriving the Lasso Regression Equations', 2, None, - 'deriving-the-lasso-regression-equations'), - ('Exercises for week 35', 2, None, 'exercises-for-week-35'), - ('Exercise 1: Setting up various Python environments', - 2, - None, - 'exercise-1-setting-up-various-python-environments'), - ('Exercise 2: making your own data and exploring scikit-learn', - 2, - None, - 'exercise-2-making-your-own-data-and-exploring-scikit-learn'), - ('Exercise 3: Normalizing our data', - 2, - None, - 'exercise-3-normalizing-our-data'), - ('Exercise 4: Adding Ridge Regression', - 2, - None, - 'exercise-4-adding-ridge-regression'), - ('Exercise 5: Analytical exercises', - 2, - None, - 'exercise-5-analytical-exercises')]} + 'deriving-the-lasso-regression-equations')]} end of tocinfo --> @@ -299,62 +299,63 @@ MathJax.Hub.Config({
  • Other useful relations
  • Meet the Hessian Matrix
  • Interpretations and optimizing our parameters
  • -
  • Examples relevant for the exercises
  • +
  • Example relevant for the exercises
  • Own code for Ordinary Least Squares
  • Adding error analysis and training set up
  • Splitting our Data in Training and Test data
  • -
  • Examples
  • +
  • The complete code with a simple data set
  • Making your own test-train splitting
  • -
  • The Boston housing data example
  • -
  • Housing data, the code
  • -
  • Reducing the number of degrees of freedom, overarching view
  • -
  • Preprocessing our data
  • -
  • Functionality in Scikit-Learn
  • -
  • More preprocessing
  • -
  • Frequently used scaling functions
  • -
  • Example of own Standard scaling
  • -
  • Min-Max Scaling
  • -
  • Testing the Means Squared Error as function of Complexity
  • -
  • More preprocessing examples, Franke function and regression
  • -
  • Material for lecture Thursday, August 31
  • -
  • Mathematical Interpretation of Ordinary Least Squares
  • -
  • Residual Error
  • -
  • Simple case
  • -
  • The singular value decomposition
  • -
  • Linear Regression Problems
  • -
  • Fixing the singularity
  • -
  • Basic math of the SVD
  • -
  • The SVD, a Fantastic Algorithm
  • -
  • Economy-size SVD
  • -
  • Codes for the SVD
  • -
  • Note about SVD Calculations
  • -
  • Mathematics of the SVD and implications
  • -
  • Example Matrix
  • -
  • Setting up the Matrix to be inverted
  • -
  • Further properties (important for our analyses later)
  • -
  • Meet the Covariance Matrix
  • -
  • Introducing the Covariance and Correlation functions
  • -
  • Covariance and Correlation Matrix
  • -
  • Correlation Function and Design/Feature Matrix
  • -
  • Covariance Matrix Examples
  • -
  • Correlation Matrix
  • -
  • Correlation Matrix with Pandas
  • -
  • Correlation Matrix with Pandas and the Franke function
  • -
  • Rewriting the Covariance and/or Correlation Matrix
  • -
  • Linking with the SVD
  • -
  • What does it mean?
  • -
  • And finally \( \boldsymbol{X}\boldsymbol{X}^T \)
  • -
  • Ridge and LASSO Regression
  • -
  • Deriving the Ridge Regression Equations
  • -
  • Interpreting the Ridge results
  • -
  • More interpretations
  • -
  • Deriving the Lasso Regression Equations
  • -
  • Exercises for week 35
  • -
  • Exercise 1: Setting up various Python environments
  • -
  • Exercise 2: making your own data and exploring scikit-learn
  • -
  • Exercise 3: Normalizing our data
  • -
  • Exercise 4: Adding Ridge Regression
  • -
  • Exercise 5: Analytical exercises
  • +
  • Reducing the number of degrees of freedom, overarching view
  • +
  • Preprocessing our data
  • +
  • Functionality in Scikit-Learn
  • +
  • More preprocessing
  • +
  • Frequently used scaling functions
  • +
  • Example of own Standard scaling
  • +
  • Min-Max Scaling
  • +
  • Testing the Means Squared Error as function of Complexity
  • +
  • More preprocessing examples, two-dimensional example, the Franke function
  • +
  • To think about, first part
  • +
  • More thinking
  • +
  • Still thinking
  • +
  • What does centering (subtracting the mean values) mean mathematically?
  • +
  • Further Manipulations
  • +
  • Wrapping it up
  • +
  • Linear Regression code, Intercept handling first
  • +
  • The Boston housing data example
  • +
  • Housing data, the code
  • +
  • Material for lecture Thursday, August 31
  • +
  • Mathematical Interpretation of Ordinary Least Squares
  • +
  • Residual Error
  • +
  • Simple case
  • +
  • The singular value decomposition
  • +
  • Linear Regression Problems
  • +
  • Fixing the singularity
  • +
  • Basic math of the SVD
  • +
  • The SVD, a Fantastic Algorithm
  • +
  • Economy-size SVD
  • +
  • Codes for the SVD
  • +
  • Note about SVD Calculations
  • +
  • Mathematics of the SVD and implications
  • +
  • Example Matrix
  • +
  • Setting up the Matrix to be inverted
  • +
  • Further properties (important for our analyses later)
  • +
  • Meet the Covariance Matrix
  • +
  • Introducing the Covariance and Correlation functions
  • +
  • Covariance and Correlation Matrix
  • +
  • Correlation Function and Design/Feature Matrix
  • +
  • Covariance Matrix Examples
  • +
  • Correlation Matrix
  • +
  • Correlation Matrix with Pandas
  • +
  • Correlation Matrix with Pandas and the Franke function
  • +
  • Rewriting the Covariance and/or Correlation Matrix
  • +
  • Linking with the SVD
  • +
  • What does it mean?
  • +
  • And finally \( \boldsymbol{X}\boldsymbol{X}^T \)
  • +
  • Ridge and LASSO Regression
  • +
  • Deriving the Ridge Regression Equations
  • +
  • Interpreting the Ridge results
  • +
  • More interpretations
  • +
  • Deriving the Lasso Regression Equations
  • @@ -421,7 +422,7 @@ $$
  • 19
  • 20
  • ...
  • -
  • 68
  • +
  • 74
  • »
  • diff --git a/doc/pub/week35/html/._week35-bs011.html b/doc/pub/week35/html/._week35-bs011.html index 5c714b7ca..f8c386446 100644 --- a/doc/pub/week35/html/._week35-bs011.html +++ b/doc/pub/week35/html/._week35-bs011.html @@ -75,10 +75,10 @@ doconce format html week35.do.txt --html_style=bootstrap --pygments_html_style=d 2, None, 'interpretations-and-optimizing-our-parameters'), - ('Examples relevant for the exercises', + ('Example relevant for the exercises', 2, None, - 'examples-relevant-for-the-exercises'), + 'example-relevant-for-the-exercises'), ('Own code for Ordinary Least Squares', 2, None, @@ -91,16 +91,14 @@ doconce format html week35.do.txt --html_style=bootstrap --pygments_html_style=d 2, None, 'splitting-our-data-in-training-and-test-data'), - ('Examples', 2, None, 'examples'), + ('The complete code with a simple data set', + 2, + None, + 'the-complete-code-with-a-simple-data-set'), ('Making your own test-train splitting', 2, None, 'making-your-own-test-train-splitting'), - ('The Boston housing data example', - 2, - None, - 'the-boston-housing-data-example'), - ('Housing data, the code', 2, None, 'housing-data-the-code'), ('Reducing the number of degrees of freedom, overarching view', 2, None, @@ -124,10 +122,33 @@ doconce format html week35.do.txt --html_style=bootstrap --pygments_html_style=d 2, None, 'testing-the-means-squared-error-as-function-of-complexity'), - ('More preprocessing examples, Franke function and regression', + ('More preprocessing examples, two-dimensional example, the ' + 'Franke function', 2, None, - 'more-preprocessing-examples-franke-function-and-regression'), + 'more-preprocessing-examples-two-dimensional-example-the-franke-function'), + ('To think about, first part', + 2, + None, + 'to-think-about-first-part'), + ('More thinking', 2, None, 'more-thinking'), + ('Still thinking', 2, None, 'still-thinking'), + ('What does centering (subtracting the mean values) mean ' + 'mathematically?', + 2, + None, + 'what-does-centering-subtracting-the-mean-values-mean-mathematically'), + ('Further Manipulations', 2, None, 'further-manipulations'), + ('Wrapping it up', 2, None, 'wrapping-it-up'), + ('Linear Regression code, Intercept handling first', + 2, + None, + 'linear-regression-code-intercept-handling-first'), + ('The Boston housing data example', + 2, + None, + 'the-boston-housing-data-example'), + ('Housing data, the code', 2, None, 'housing-data-the-code'), ('Material for lecture Thursday, August 31', 2, None, @@ -226,28 +247,7 @@ doconce format html week35.do.txt --html_style=bootstrap --pygments_html_style=d ('Deriving the Lasso Regression Equations', 2, None, - 'deriving-the-lasso-regression-equations'), - ('Exercises for week 35', 2, None, 'exercises-for-week-35'), - ('Exercise 1: Setting up various Python environments', - 2, - None, - 'exercise-1-setting-up-various-python-environments'), - ('Exercise 2: making your own data and exploring scikit-learn', - 2, - None, - 'exercise-2-making-your-own-data-and-exploring-scikit-learn'), - ('Exercise 3: Normalizing our data', - 2, - None, - 'exercise-3-normalizing-our-data'), - ('Exercise 4: Adding Ridge Regression', - 2, - None, - 'exercise-4-adding-ridge-regression'), - ('Exercise 5: Analytical exercises', - 2, - None, - 'exercise-5-analytical-exercises')]} + 'deriving-the-lasso-regression-equations')]} end of tocinfo --> @@ -299,62 +299,63 @@ MathJax.Hub.Config({
  • Other useful relations
  • Meet the Hessian Matrix
  • Interpretations and optimizing our parameters
  • -
  • Examples relevant for the exercises
  • +
  • Example relevant for the exercises
  • Own code for Ordinary Least Squares
  • Adding error analysis and training set up
  • Splitting our Data in Training and Test data
  • -
  • Examples
  • +
  • The complete code with a simple data set
  • Making your own test-train splitting
  • -
  • The Boston housing data example
  • -
  • Housing data, the code
  • -
  • Reducing the number of degrees of freedom, overarching view
  • -
  • Preprocessing our data
  • -
  • Functionality in Scikit-Learn
  • -
  • More preprocessing
  • -
  • Frequently used scaling functions
  • -
  • Example of own Standard scaling
  • -
  • Min-Max Scaling
  • -
  • Testing the Means Squared Error as function of Complexity
  • -
  • More preprocessing examples, Franke function and regression
  • -
  • Material for lecture Thursday, August 31
  • -
  • Mathematical Interpretation of Ordinary Least Squares
  • -
  • Residual Error
  • -
  • Simple case
  • -
  • The singular value decomposition
  • -
  • Linear Regression Problems
  • -
  • Fixing the singularity
  • -
  • Basic math of the SVD
  • -
  • The SVD, a Fantastic Algorithm
  • -
  • Economy-size SVD
  • -
  • Codes for the SVD
  • -
  • Note about SVD Calculations
  • -
  • Mathematics of the SVD and implications
  • -
  • Example Matrix
  • -
  • Setting up the Matrix to be inverted
  • -
  • Further properties (important for our analyses later)
  • -
  • Meet the Covariance Matrix
  • -
  • Introducing the Covariance and Correlation functions
  • -
  • Covariance and Correlation Matrix
  • -
  • Correlation Function and Design/Feature Matrix
  • -
  • Covariance Matrix Examples
  • -
  • Correlation Matrix
  • -
  • Correlation Matrix with Pandas
  • -
  • Correlation Matrix with Pandas and the Franke function
  • -
  • Rewriting the Covariance and/or Correlation Matrix
  • -
  • Linking with the SVD
  • -
  • What does it mean?
  • -
  • And finally \( \boldsymbol{X}\boldsymbol{X}^T \)
  • -
  • Ridge and LASSO Regression
  • -
  • Deriving the Ridge Regression Equations
  • -
  • Interpreting the Ridge results
  • -
  • More interpretations
  • -
  • Deriving the Lasso Regression Equations
  • -
  • Exercises for week 35
  • -
  • Exercise 1: Setting up various Python environments
  • -
  • Exercise 2: making your own data and exploring scikit-learn
  • -
  • Exercise 3: Normalizing our data
  • -
  • Exercise 4: Adding Ridge Regression
  • -
  • Exercise 5: Analytical exercises
  • +
  • Reducing the number of degrees of freedom, overarching view
  • +
  • Preprocessing our data
  • +
  • Functionality in Scikit-Learn
  • +
  • More preprocessing
  • +
  • Frequently used scaling functions
  • +
  • Example of own Standard scaling
  • +
  • Min-Max Scaling
  • +
  • Testing the Means Squared Error as function of Complexity
  • +
  • More preprocessing examples, two-dimensional example, the Franke function
  • +
  • To think about, first part
  • +
  • More thinking
  • +
  • Still thinking
  • +
  • What does centering (subtracting the mean values) mean mathematically?
  • +
  • Further Manipulations
  • +
  • Wrapping it up
  • +
  • Linear Regression code, Intercept handling first
  • +
  • The Boston housing data example
  • +
  • Housing data, the code
  • +
  • Material for lecture Thursday, August 31
  • +
  • Mathematical Interpretation of Ordinary Least Squares
  • +
  • Residual Error
  • +
  • Simple case
  • +
  • The singular value decomposition
  • +
  • Linear Regression Problems
  • +
  • Fixing the singularity
  • +
  • Basic math of the SVD
  • +
  • The SVD, a Fantastic Algorithm
  • +
  • Economy-size SVD
  • +
  • Codes for the SVD
  • +
  • Note about SVD Calculations
  • +
  • Mathematics of the SVD and implications
  • +
  • Example Matrix
  • +
  • Setting up the Matrix to be inverted
  • +
  • Further properties (important for our analyses later)
  • +
  • Meet the Covariance Matrix
  • +
  • Introducing the Covariance and Correlation functions
  • +
  • Covariance and Correlation Matrix
  • +
  • Correlation Function and Design/Feature Matrix
  • +
  • Covariance Matrix Examples
  • +
  • Correlation Matrix
  • +
  • Correlation Matrix with Pandas
  • +
  • Correlation Matrix with Pandas and the Franke function
  • +
  • Rewriting the Covariance and/or Correlation Matrix
  • +
  • Linking with the SVD
  • +
  • What does it mean?
  • +
  • And finally \( \boldsymbol{X}\boldsymbol{X}^T \)
  • +
  • Ridge and LASSO Regression
  • +
  • Deriving the Ridge Regression Equations
  • +
  • Interpreting the Ridge results
  • +
  • More interpretations
  • +
  • Deriving the Lasso Regression Equations
  • @@ -425,7 +426,7 @@ $$
  • 20
  • 21
  • ...
  • -
  • 68
  • +
  • 74
  • »
  • diff --git a/doc/pub/week35/html/._week35-bs012.html b/doc/pub/week35/html/._week35-bs012.html index 19dae0ae4..bef21dda8 100644 --- a/doc/pub/week35/html/._week35-bs012.html +++ b/doc/pub/week35/html/._week35-bs012.html @@ -75,10 +75,10 @@ doconce format html week35.do.txt --html_style=bootstrap --pygments_html_style=d 2, None, 'interpretations-and-optimizing-our-parameters'), - ('Examples relevant for the exercises', + ('Example relevant for the exercises', 2, None, - 'examples-relevant-for-the-exercises'), + 'example-relevant-for-the-exercises'), ('Own code for Ordinary Least Squares', 2, None, @@ -91,16 +91,14 @@ doconce format html week35.do.txt --html_style=bootstrap --pygments_html_style=d 2, None, 'splitting-our-data-in-training-and-test-data'), - ('Examples', 2, None, 'examples'), + ('The complete code with a simple data set', + 2, + None, + 'the-complete-code-with-a-simple-data-set'), ('Making your own test-train splitting', 2, None, 'making-your-own-test-train-splitting'), - ('The Boston housing data example', - 2, - None, - 'the-boston-housing-data-example'), - ('Housing data, the code', 2, None, 'housing-data-the-code'), ('Reducing the number of degrees of freedom, overarching view', 2, None, @@ -124,10 +122,33 @@ doconce format html week35.do.txt --html_style=bootstrap --pygments_html_style=d 2, None, 'testing-the-means-squared-error-as-function-of-complexity'), - ('More preprocessing examples, Franke function and regression', + ('More preprocessing examples, two-dimensional example, the ' + 'Franke function', 2, None, - 'more-preprocessing-examples-franke-function-and-regression'), + 'more-preprocessing-examples-two-dimensional-example-the-franke-function'), + ('To think about, first part', + 2, + None, + 'to-think-about-first-part'), + ('More thinking', 2, None, 'more-thinking'), + ('Still thinking', 2, None, 'still-thinking'), + ('What does centering (subtracting the mean values) mean ' + 'mathematically?', + 2, + None, + 'what-does-centering-subtracting-the-mean-values-mean-mathematically'), + ('Further Manipulations', 2, None, 'further-manipulations'), + ('Wrapping it up', 2, None, 'wrapping-it-up'), + ('Linear Regression code, Intercept handling first', + 2, + None, + 'linear-regression-code-intercept-handling-first'), + ('The Boston housing data example', + 2, + None, + 'the-boston-housing-data-example'), + ('Housing data, the code', 2, None, 'housing-data-the-code'), ('Material for lecture Thursday, August 31', 2, None, @@ -226,28 +247,7 @@ doconce format html week35.do.txt --html_style=bootstrap --pygments_html_style=d ('Deriving the Lasso Regression Equations', 2, None, - 'deriving-the-lasso-regression-equations'), - ('Exercises for week 35', 2, None, 'exercises-for-week-35'), - ('Exercise 1: Setting up various Python environments', - 2, - None, - 'exercise-1-setting-up-various-python-environments'), - ('Exercise 2: making your own data and exploring scikit-learn', - 2, - None, - 'exercise-2-making-your-own-data-and-exploring-scikit-learn'), - ('Exercise 3: Normalizing our data', - 2, - None, - 'exercise-3-normalizing-our-data'), - ('Exercise 4: Adding Ridge Regression', - 2, - None, - 'exercise-4-adding-ridge-regression'), - ('Exercise 5: Analytical exercises', - 2, - None, - 'exercise-5-analytical-exercises')]} + 'deriving-the-lasso-regression-equations')]} end of tocinfo --> @@ -299,62 +299,63 @@ MathJax.Hub.Config({
  • Other useful relations
  • Meet the Hessian Matrix
  • Interpretations and optimizing our parameters
  • -
  • Examples relevant for the exercises
  • +
  • Example relevant for the exercises
  • Own code for Ordinary Least Squares
  • Adding error analysis and training set up
  • Splitting our Data in Training and Test data
  • -
  • Examples
  • +
  • The complete code with a simple data set
  • Making your own test-train splitting
  • -
  • The Boston housing data example
  • -
  • Housing data, the code
  • -
  • Reducing the number of degrees of freedom, overarching view
  • -
  • Preprocessing our data
  • -
  • Functionality in Scikit-Learn
  • -
  • More preprocessing
  • -
  • Frequently used scaling functions
  • -
  • Example of own Standard scaling
  • -
  • Min-Max Scaling
  • -
  • Testing the Means Squared Error as function of Complexity
  • -
  • More preprocessing examples, Franke function and regression
  • -
  • Material for lecture Thursday, August 31
  • -
  • Mathematical Interpretation of Ordinary Least Squares
  • -
  • Residual Error
  • -
  • Simple case
  • -
  • The singular value decomposition
  • -
  • Linear Regression Problems
  • -
  • Fixing the singularity
  • -
  • Basic math of the SVD
  • -
  • The SVD, a Fantastic Algorithm
  • -
  • Economy-size SVD
  • -
  • Codes for the SVD
  • -
  • Note about SVD Calculations
  • -
  • Mathematics of the SVD and implications
  • -
  • Example Matrix
  • -
  • Setting up the Matrix to be inverted
  • -
  • Further properties (important for our analyses later)
  • -
  • Meet the Covariance Matrix
  • -
  • Introducing the Covariance and Correlation functions
  • -
  • Covariance and Correlation Matrix
  • -
  • Correlation Function and Design/Feature Matrix
  • -
  • Covariance Matrix Examples
  • -
  • Correlation Matrix
  • -
  • Correlation Matrix with Pandas
  • -
  • Correlation Matrix with Pandas and the Franke function
  • -
  • Rewriting the Covariance and/or Correlation Matrix
  • -
  • Linking with the SVD
  • -
  • What does it mean?
  • -
  • And finally \( \boldsymbol{X}\boldsymbol{X}^T \)
  • -
  • Ridge and LASSO Regression
  • -
  • Deriving the Ridge Regression Equations
  • -
  • Interpreting the Ridge results
  • -
  • More interpretations
  • -
  • Deriving the Lasso Regression Equations
  • -
  • Exercises for week 35
  • -
  • Exercise 1: Setting up various Python environments
  • -
  • Exercise 2: making your own data and exploring scikit-learn
  • -
  • Exercise 3: Normalizing our data
  • -
  • Exercise 4: Adding Ridge Regression
  • -
  • Exercise 5: Analytical exercises
  • +
  • Reducing the number of degrees of freedom, overarching view
  • +
  • Preprocessing our data
  • +
  • Functionality in Scikit-Learn
  • +
  • More preprocessing
  • +
  • Frequently used scaling functions
  • +
  • Example of own Standard scaling
  • +
  • Min-Max Scaling
  • +
  • Testing the Means Squared Error as function of Complexity
  • +
  • More preprocessing examples, two-dimensional example, the Franke function
  • +
  • To think about, first part
  • +
  • More thinking
  • +
  • Still thinking
  • +
  • What does centering (subtracting the mean values) mean mathematically?
  • +
  • Further Manipulations
  • +
  • Wrapping it up
  • +
  • Linear Regression code, Intercept handling first
  • +
  • The Boston housing data example
  • +
  • Housing data, the code
  • +
  • Material for lecture Thursday, August 31
  • +
  • Mathematical Interpretation of Ordinary Least Squares
  • +
  • Residual Error
  • +
  • Simple case
  • +
  • The singular value decomposition
  • +
  • Linear Regression Problems
  • +
  • Fixing the singularity
  • +
  • Basic math of the SVD
  • +
  • The SVD, a Fantastic Algorithm
  • +
  • Economy-size SVD
  • +
  • Codes for the SVD
  • +
  • Note about SVD Calculations
  • +
  • Mathematics of the SVD and implications
  • +
  • Example Matrix
  • +
  • Setting up the Matrix to be inverted
  • +
  • Further properties (important for our analyses later)
  • +
  • Meet the Covariance Matrix
  • +
  • Introducing the Covariance and Correlation functions
  • +
  • Covariance and Correlation Matrix
  • +
  • Correlation Function and Design/Feature Matrix
  • +
  • Covariance Matrix Examples
  • +
  • Correlation Matrix
  • +
  • Correlation Matrix with Pandas
  • +
  • Correlation Matrix with Pandas and the Franke function
  • +
  • Rewriting the Covariance and/or Correlation Matrix
  • +
  • Linking with the SVD
  • +
  • What does it mean?
  • +
  • And finally \( \boldsymbol{X}\boldsymbol{X}^T \)
  • +
  • Ridge and LASSO Regression
  • +
  • Deriving the Ridge Regression Equations
  • +
  • Interpreting the Ridge results
  • +
  • More interpretations
  • +
  • Deriving the Lasso Regression Equations
  • @@ -426,7 +427,7 @@ $$
  • 21
  • 22
  • ...
  • -
  • 68
  • +
  • 74
  • »
  • diff --git a/doc/pub/week35/html/._week35-bs013.html b/doc/pub/week35/html/._week35-bs013.html index bda547f66..1a557f07b 100644 --- a/doc/pub/week35/html/._week35-bs013.html +++ b/doc/pub/week35/html/._week35-bs013.html @@ -75,10 +75,10 @@ doconce format html week35.do.txt --html_style=bootstrap --pygments_html_style=d 2, None, 'interpretations-and-optimizing-our-parameters'), - ('Examples relevant for the exercises', + ('Example relevant for the exercises', 2, None, - 'examples-relevant-for-the-exercises'), + 'example-relevant-for-the-exercises'), ('Own code for Ordinary Least Squares', 2, None, @@ -91,16 +91,14 @@ doconce format html week35.do.txt --html_style=bootstrap --pygments_html_style=d 2, None, 'splitting-our-data-in-training-and-test-data'), - ('Examples', 2, None, 'examples'), + ('The complete code with a simple data set', + 2, + None, + 'the-complete-code-with-a-simple-data-set'), ('Making your own test-train splitting', 2, None, 'making-your-own-test-train-splitting'), - ('The Boston housing data example', - 2, - None, - 'the-boston-housing-data-example'), - ('Housing data, the code', 2, None, 'housing-data-the-code'), ('Reducing the number of degrees of freedom, overarching view', 2, None, @@ -124,10 +122,33 @@ doconce format html week35.do.txt --html_style=bootstrap --pygments_html_style=d 2, None, 'testing-the-means-squared-error-as-function-of-complexity'), - ('More preprocessing examples, Franke function and regression', + ('More preprocessing examples, two-dimensional example, the ' + 'Franke function', 2, None, - 'more-preprocessing-examples-franke-function-and-regression'), + 'more-preprocessing-examples-two-dimensional-example-the-franke-function'), + ('To think about, first part', + 2, + None, + 'to-think-about-first-part'), + ('More thinking', 2, None, 'more-thinking'), + ('Still thinking', 2, None, 'still-thinking'), + ('What does centering (subtracting the mean values) mean ' + 'mathematically?', + 2, + None, + 'what-does-centering-subtracting-the-mean-values-mean-mathematically'), + ('Further Manipulations', 2, None, 'further-manipulations'), + ('Wrapping it up', 2, None, 'wrapping-it-up'), + ('Linear Regression code, Intercept handling first', + 2, + None, + 'linear-regression-code-intercept-handling-first'), + ('The Boston housing data example', + 2, + None, + 'the-boston-housing-data-example'), + ('Housing data, the code', 2, None, 'housing-data-the-code'), ('Material for lecture Thursday, August 31', 2, None, @@ -226,28 +247,7 @@ doconce format html week35.do.txt --html_style=bootstrap --pygments_html_style=d ('Deriving the Lasso Regression Equations', 2, None, - 'deriving-the-lasso-regression-equations'), - ('Exercises for week 35', 2, None, 'exercises-for-week-35'), - ('Exercise 1: Setting up various Python environments', - 2, - None, - 'exercise-1-setting-up-various-python-environments'), - ('Exercise 2: making your own data and exploring scikit-learn', - 2, - None, - 'exercise-2-making-your-own-data-and-exploring-scikit-learn'), - ('Exercise 3: Normalizing our data', - 2, - None, - 'exercise-3-normalizing-our-data'), - ('Exercise 4: Adding Ridge Regression', - 2, - None, - 'exercise-4-adding-ridge-regression'), - ('Exercise 5: Analytical exercises', - 2, - None, - 'exercise-5-analytical-exercises')]} + 'deriving-the-lasso-regression-equations')]} end of tocinfo --> @@ -299,62 +299,63 @@ MathJax.Hub.Config({
  • Other useful relations
  • Meet the Hessian Matrix
  • Interpretations and optimizing our parameters
  • -
  • Examples relevant for the exercises
  • +
  • Example relevant for the exercises
  • Own code for Ordinary Least Squares
  • Adding error analysis and training set up
  • Splitting our Data in Training and Test data
  • -
  • Examples
  • +
  • The complete code with a simple data set
  • Making your own test-train splitting
  • -
  • The Boston housing data example
  • -
  • Housing data, the code
  • -
  • Reducing the number of degrees of freedom, overarching view
  • -
  • Preprocessing our data
  • -
  • Functionality in Scikit-Learn
  • -
  • More preprocessing
  • -
  • Frequently used scaling functions
  • -
  • Example of own Standard scaling
  • -
  • Min-Max Scaling
  • -
  • Testing the Means Squared Error as function of Complexity
  • -
  • More preprocessing examples, Franke function and regression
  • -
  • Material for lecture Thursday, August 31
  • -
  • Mathematical Interpretation of Ordinary Least Squares
  • -
  • Residual Error
  • -
  • Simple case
  • -
  • The singular value decomposition
  • -
  • Linear Regression Problems
  • -
  • Fixing the singularity
  • -
  • Basic math of the SVD
  • -
  • The SVD, a Fantastic Algorithm
  • -
  • Economy-size SVD
  • -
  • Codes for the SVD
  • -
  • Note about SVD Calculations
  • -
  • Mathematics of the SVD and implications
  • -
  • Example Matrix
  • -
  • Setting up the Matrix to be inverted
  • -
  • Further properties (important for our analyses later)
  • -
  • Meet the Covariance Matrix
  • -
  • Introducing the Covariance and Correlation functions
  • -
  • Covariance and Correlation Matrix
  • -
  • Correlation Function and Design/Feature Matrix
  • -
  • Covariance Matrix Examples
  • -
  • Correlation Matrix
  • -
  • Correlation Matrix with Pandas
  • -
  • Correlation Matrix with Pandas and the Franke function
  • -
  • Rewriting the Covariance and/or Correlation Matrix
  • -
  • Linking with the SVD
  • -
  • What does it mean?
  • -
  • And finally \( \boldsymbol{X}\boldsymbol{X}^T \)
  • -
  • Ridge and LASSO Regression
  • -
  • Deriving the Ridge Regression Equations
  • -
  • Interpreting the Ridge results
  • -
  • More interpretations
  • -
  • Deriving the Lasso Regression Equations
  • -
  • Exercises for week 35
  • -
  • Exercise 1: Setting up various Python environments
  • -
  • Exercise 2: making your own data and exploring scikit-learn
  • -
  • Exercise 3: Normalizing our data
  • -
  • Exercise 4: Adding Ridge Regression
  • -
  • Exercise 5: Analytical exercises
  • +
  • Reducing the number of degrees of freedom, overarching view
  • +
  • Preprocessing our data
  • +
  • Functionality in Scikit-Learn
  • +
  • More preprocessing
  • +
  • Frequently used scaling functions
  • +
  • Example of own Standard scaling
  • +
  • Min-Max Scaling
  • +
  • Testing the Means Squared Error as function of Complexity
  • +
  • More preprocessing examples, two-dimensional example, the Franke function
  • +
  • To think about, first part
  • +
  • More thinking
  • +
  • Still thinking
  • +
  • What does centering (subtracting the mean values) mean mathematically?
  • +
  • Further Manipulations
  • +
  • Wrapping it up
  • +
  • Linear Regression code, Intercept handling first
  • +
  • The Boston housing data example
  • +
  • Housing data, the code
  • +
  • Material for lecture Thursday, August 31
  • +
  • Mathematical Interpretation of Ordinary Least Squares
  • +
  • Residual Error
  • +
  • Simple case
  • +
  • The singular value decomposition
  • +
  • Linear Regression Problems
  • +
  • Fixing the singularity
  • +
  • Basic math of the SVD
  • +
  • The SVD, a Fantastic Algorithm
  • +
  • Economy-size SVD
  • +
  • Codes for the SVD
  • +
  • Note about SVD Calculations
  • +
  • Mathematics of the SVD and implications
  • +
  • Example Matrix
  • +
  • Setting up the Matrix to be inverted
  • +
  • Further properties (important for our analyses later)
  • +
  • Meet the Covariance Matrix
  • +
  • Introducing the Covariance and Correlation functions
  • +
  • Covariance and Correlation Matrix
  • +
  • Correlation Function and Design/Feature Matrix
  • +
  • Covariance Matrix Examples
  • +
  • Correlation Matrix
  • +
  • Correlation Matrix with Pandas
  • +
  • Correlation Matrix with Pandas and the Franke function
  • +
  • Rewriting the Covariance and/or Correlation Matrix
  • +
  • Linking with the SVD
  • +
  • What does it mean?
  • +
  • And finally \( \boldsymbol{X}\boldsymbol{X}^T \)
  • +
  • Ridge and LASSO Regression
  • +
  • Deriving the Ridge Regression Equations
  • +
  • Interpreting the Ridge results
  • +
  • More interpretations
  • +
  • Deriving the Lasso Regression Equations
  • @@ -438,7 +439,7 @@ $$
  • 22
  • 23
  • ...
  • -
  • 68
  • +
  • 74
  • »
  • diff --git a/doc/pub/week35/html/._week35-bs014.html b/doc/pub/week35/html/._week35-bs014.html index a3b38b73d..1d94a7359 100644 --- a/doc/pub/week35/html/._week35-bs014.html +++ b/doc/pub/week35/html/._week35-bs014.html @@ -75,10 +75,10 @@ doconce format html week35.do.txt --html_style=bootstrap --pygments_html_style=d 2, None, 'interpretations-and-optimizing-our-parameters'), - ('Examples relevant for the exercises', + ('Example relevant for the exercises', 2, None, - 'examples-relevant-for-the-exercises'), + 'example-relevant-for-the-exercises'), ('Own code for Ordinary Least Squares', 2, None, @@ -91,16 +91,14 @@ doconce format html week35.do.txt --html_style=bootstrap --pygments_html_style=d 2, None, 'splitting-our-data-in-training-and-test-data'), - ('Examples', 2, None, 'examples'), + ('The complete code with a simple data set', + 2, + None, + 'the-complete-code-with-a-simple-data-set'), ('Making your own test-train splitting', 2, None, 'making-your-own-test-train-splitting'), - ('The Boston housing data example', - 2, - None, - 'the-boston-housing-data-example'), - ('Housing data, the code', 2, None, 'housing-data-the-code'), ('Reducing the number of degrees of freedom, overarching view', 2, None, @@ -124,10 +122,33 @@ doconce format html week35.do.txt --html_style=bootstrap --pygments_html_style=d 2, None, 'testing-the-means-squared-error-as-function-of-complexity'), - ('More preprocessing examples, Franke function and regression', + ('More preprocessing examples, two-dimensional example, the ' + 'Franke function', 2, None, - 'more-preprocessing-examples-franke-function-and-regression'), + 'more-preprocessing-examples-two-dimensional-example-the-franke-function'), + ('To think about, first part', + 2, + None, + 'to-think-about-first-part'), + ('More thinking', 2, None, 'more-thinking'), + ('Still thinking', 2, None, 'still-thinking'), + ('What does centering (subtracting the mean values) mean ' + 'mathematically?', + 2, + None, + 'what-does-centering-subtracting-the-mean-values-mean-mathematically'), + ('Further Manipulations', 2, None, 'further-manipulations'), + ('Wrapping it up', 2, None, 'wrapping-it-up'), + ('Linear Regression code, Intercept handling first', + 2, + None, + 'linear-regression-code-intercept-handling-first'), + ('The Boston housing data example', + 2, + None, + 'the-boston-housing-data-example'), + ('Housing data, the code', 2, None, 'housing-data-the-code'), ('Material for lecture Thursday, August 31', 2, None, @@ -226,28 +247,7 @@ doconce format html week35.do.txt --html_style=bootstrap --pygments_html_style=d ('Deriving the Lasso Regression Equations', 2, None, - 'deriving-the-lasso-regression-equations'), - ('Exercises for week 35', 2, None, 'exercises-for-week-35'), - ('Exercise 1: Setting up various Python environments', - 2, - None, - 'exercise-1-setting-up-various-python-environments'), - ('Exercise 2: making your own data and exploring scikit-learn', - 2, - None, - 'exercise-2-making-your-own-data-and-exploring-scikit-learn'), - ('Exercise 3: Normalizing our data', - 2, - None, - 'exercise-3-normalizing-our-data'), - ('Exercise 4: Adding Ridge Regression', - 2, - None, - 'exercise-4-adding-ridge-regression'), - ('Exercise 5: Analytical exercises', - 2, - None, - 'exercise-5-analytical-exercises')]} + 'deriving-the-lasso-regression-equations')]} end of tocinfo --> @@ -299,62 +299,63 @@ MathJax.Hub.Config({
  • Other useful relations
  • Meet the Hessian Matrix
  • Interpretations and optimizing our parameters
  • -
  • Examples relevant for the exercises
  • +
  • Example relevant for the exercises
  • Own code for Ordinary Least Squares
  • Adding error analysis and training set up
  • Splitting our Data in Training and Test data
  • -
  • Examples
  • +
  • The complete code with a simple data set
  • Making your own test-train splitting
  • -
  • The Boston housing data example
  • -
  • Housing data, the code
  • -
  • Reducing the number of degrees of freedom, overarching view
  • -
  • Preprocessing our data
  • -
  • Functionality in Scikit-Learn
  • -
  • More preprocessing
  • -
  • Frequently used scaling functions
  • -
  • Example of own Standard scaling
  • -
  • Min-Max Scaling
  • -
  • Testing the Means Squared Error as function of Complexity
  • -
  • More preprocessing examples, Franke function and regression
  • -
  • Material for lecture Thursday, August 31
  • -
  • Mathematical Interpretation of Ordinary Least Squares
  • -
  • Residual Error
  • -
  • Simple case
  • -
  • The singular value decomposition
  • -
  • Linear Regression Problems
  • -
  • Fixing the singularity
  • -
  • Basic math of the SVD
  • -
  • The SVD, a Fantastic Algorithm
  • -
  • Economy-size SVD
  • -
  • Codes for the SVD
  • -
  • Note about SVD Calculations
  • -
  • Mathematics of the SVD and implications
  • -
  • Example Matrix
  • -
  • Setting up the Matrix to be inverted
  • -
  • Further properties (important for our analyses later)
  • -
  • Meet the Covariance Matrix
  • -
  • Introducing the Covariance and Correlation functions
  • -
  • Covariance and Correlation Matrix
  • -
  • Correlation Function and Design/Feature Matrix
  • -
  • Covariance Matrix Examples
  • -
  • Correlation Matrix
  • -
  • Correlation Matrix with Pandas
  • -
  • Correlation Matrix with Pandas and the Franke function
  • -
  • Rewriting the Covariance and/or Correlation Matrix
  • -
  • Linking with the SVD
  • -
  • What does it mean?
  • -
  • And finally \( \boldsymbol{X}\boldsymbol{X}^T \)
  • -
  • Ridge and LASSO Regression
  • -
  • Deriving the Ridge Regression Equations
  • -
  • Interpreting the Ridge results
  • -
  • More interpretations
  • -
  • Deriving the Lasso Regression Equations
  • -
  • Exercises for week 35
  • -
  • Exercise 1: Setting up various Python environments
  • -
  • Exercise 2: making your own data and exploring scikit-learn
  • -
  • Exercise 3: Normalizing our data
  • -
  • Exercise 4: Adding Ridge Regression
  • -
  • Exercise 5: Analytical exercises
  • +
  • Reducing the number of degrees of freedom, overarching view
  • +
  • Preprocessing our data
  • +
  • Functionality in Scikit-Learn
  • +
  • More preprocessing
  • +
  • Frequently used scaling functions
  • +
  • Example of own Standard scaling
  • +
  • Min-Max Scaling
  • +
  • Testing the Means Squared Error as function of Complexity
  • +
  • More preprocessing examples, two-dimensional example, the Franke function
  • +
  • To think about, first part
  • +
  • More thinking
  • +
  • Still thinking
  • +
  • What does centering (subtracting the mean values) mean mathematically?
  • +
  • Further Manipulations
  • +
  • Wrapping it up
  • +
  • Linear Regression code, Intercept handling first
  • +
  • The Boston housing data example
  • +
  • Housing data, the code
  • +
  • Material for lecture Thursday, August 31
  • +
  • Mathematical Interpretation of Ordinary Least Squares
  • +
  • Residual Error
  • +
  • Simple case
  • +
  • The singular value decomposition
  • +
  • Linear Regression Problems
  • +
  • Fixing the singularity
  • +
  • Basic math of the SVD
  • +
  • The SVD, a Fantastic Algorithm
  • +
  • Economy-size SVD
  • +
  • Codes for the SVD
  • +
  • Note about SVD Calculations
  • +
  • Mathematics of the SVD and implications
  • +
  • Example Matrix
  • +
  • Setting up the Matrix to be inverted
  • +
  • Further properties (important for our analyses later)
  • +
  • Meet the Covariance Matrix
  • +
  • Introducing the Covariance and Correlation functions
  • +
  • Covariance and Correlation Matrix
  • +
  • Correlation Function and Design/Feature Matrix
  • +
  • Covariance Matrix Examples
  • +
  • Correlation Matrix
  • +
  • Correlation Matrix with Pandas
  • +
  • Correlation Matrix with Pandas and the Franke function
  • +
  • Rewriting the Covariance and/or Correlation Matrix
  • +
  • Linking with the SVD
  • +
  • What does it mean?
  • +
  • And finally \( \boldsymbol{X}\boldsymbol{X}^T \)
  • +
  • Ridge and LASSO Regression
  • +
  • Deriving the Ridge Regression Equations
  • +
  • Interpreting the Ridge results
  • +
  • More interpretations
  • +
  • Deriving the Lasso Regression Equations
  • @@ -407,7 +408,7 @@ $$
  • 23
  • 24
  • ...
  • -
  • 68
  • +
  • 74
  • »
  • diff --git a/doc/pub/week35/html/._week35-bs015.html b/doc/pub/week35/html/._week35-bs015.html index 2d56c4b56..f84b9f759 100644 --- a/doc/pub/week35/html/._week35-bs015.html +++ b/doc/pub/week35/html/._week35-bs015.html @@ -75,10 +75,10 @@ doconce format html week35.do.txt --html_style=bootstrap --pygments_html_style=d 2, None, 'interpretations-and-optimizing-our-parameters'), - ('Examples relevant for the exercises', + ('Example relevant for the exercises', 2, None, - 'examples-relevant-for-the-exercises'), + 'example-relevant-for-the-exercises'), ('Own code for Ordinary Least Squares', 2, None, @@ -91,16 +91,14 @@ doconce format html week35.do.txt --html_style=bootstrap --pygments_html_style=d 2, None, 'splitting-our-data-in-training-and-test-data'), - ('Examples', 2, None, 'examples'), + ('The complete code with a simple data set', + 2, + None, + 'the-complete-code-with-a-simple-data-set'), ('Making your own test-train splitting', 2, None, 'making-your-own-test-train-splitting'), - ('The Boston housing data example', - 2, - None, - 'the-boston-housing-data-example'), - ('Housing data, the code', 2, None, 'housing-data-the-code'), ('Reducing the number of degrees of freedom, overarching view', 2, None, @@ -124,10 +122,33 @@ doconce format html week35.do.txt --html_style=bootstrap --pygments_html_style=d 2, None, 'testing-the-means-squared-error-as-function-of-complexity'), - ('More preprocessing examples, Franke function and regression', + ('More preprocessing examples, two-dimensional example, the ' + 'Franke function', 2, None, - 'more-preprocessing-examples-franke-function-and-regression'), + 'more-preprocessing-examples-two-dimensional-example-the-franke-function'), + ('To think about, first part', + 2, + None, + 'to-think-about-first-part'), + ('More thinking', 2, None, 'more-thinking'), + ('Still thinking', 2, None, 'still-thinking'), + ('What does centering (subtracting the mean values) mean ' + 'mathematically?', + 2, + None, + 'what-does-centering-subtracting-the-mean-values-mean-mathematically'), + ('Further Manipulations', 2, None, 'further-manipulations'), + ('Wrapping it up', 2, None, 'wrapping-it-up'), + ('Linear Regression code, Intercept handling first', + 2, + None, + 'linear-regression-code-intercept-handling-first'), + ('The Boston housing data example', + 2, + None, + 'the-boston-housing-data-example'), + ('Housing data, the code', 2, None, 'housing-data-the-code'), ('Material for lecture Thursday, August 31', 2, None, @@ -226,28 +247,7 @@ doconce format html week35.do.txt --html_style=bootstrap --pygments_html_style=d ('Deriving the Lasso Regression Equations', 2, None, - 'deriving-the-lasso-regression-equations'), - ('Exercises for week 35', 2, None, 'exercises-for-week-35'), - ('Exercise 1: Setting up various Python environments', - 2, - None, - 'exercise-1-setting-up-various-python-environments'), - ('Exercise 2: making your own data and exploring scikit-learn', - 2, - None, - 'exercise-2-making-your-own-data-and-exploring-scikit-learn'), - ('Exercise 3: Normalizing our data', - 2, - None, - 'exercise-3-normalizing-our-data'), - ('Exercise 4: Adding Ridge Regression', - 2, - None, - 'exercise-4-adding-ridge-regression'), - ('Exercise 5: Analytical exercises', - 2, - None, - 'exercise-5-analytical-exercises')]} + 'deriving-the-lasso-regression-equations')]} end of tocinfo --> @@ -299,62 +299,63 @@ MathJax.Hub.Config({
  • Other useful relations
  • Meet the Hessian Matrix
  • Interpretations and optimizing our parameters
  • -
  • Examples relevant for the exercises
  • +
  • Example relevant for the exercises
  • Own code for Ordinary Least Squares
  • Adding error analysis and training set up
  • Splitting our Data in Training and Test data
  • -
  • Examples
  • +
  • The complete code with a simple data set
  • Making your own test-train splitting
  • -
  • The Boston housing data example
  • -
  • Housing data, the code
  • -
  • Reducing the number of degrees of freedom, overarching view
  • -
  • Preprocessing our data
  • -
  • Functionality in Scikit-Learn
  • -
  • More preprocessing
  • -
  • Frequently used scaling functions
  • -
  • Example of own Standard scaling
  • -
  • Min-Max Scaling
  • -
  • Testing the Means Squared Error as function of Complexity
  • -
  • More preprocessing examples, Franke function and regression
  • -
  • Material for lecture Thursday, August 31
  • -
  • Mathematical Interpretation of Ordinary Least Squares
  • -
  • Residual Error
  • -
  • Simple case
  • -
  • The singular value decomposition
  • -
  • Linear Regression Problems
  • -
  • Fixing the singularity
  • -
  • Basic math of the SVD
  • -
  • The SVD, a Fantastic Algorithm
  • -
  • Economy-size SVD
  • -
  • Codes for the SVD
  • -
  • Note about SVD Calculations
  • -
  • Mathematics of the SVD and implications
  • -
  • Example Matrix
  • -
  • Setting up the Matrix to be inverted
  • -
  • Further properties (important for our analyses later)
  • -
  • Meet the Covariance Matrix
  • -
  • Introducing the Covariance and Correlation functions
  • -
  • Covariance and Correlation Matrix
  • -
  • Correlation Function and Design/Feature Matrix
  • -
  • Covariance Matrix Examples
  • -
  • Correlation Matrix
  • -
  • Correlation Matrix with Pandas
  • -
  • Correlation Matrix with Pandas and the Franke function
  • -
  • Rewriting the Covariance and/or Correlation Matrix
  • -
  • Linking with the SVD
  • -
  • What does it mean?
  • -
  • And finally \( \boldsymbol{X}\boldsymbol{X}^T \)
  • -
  • Ridge and LASSO Regression
  • -
  • Deriving the Ridge Regression Equations
  • -
  • Interpreting the Ridge results
  • -
  • More interpretations
  • -
  • Deriving the Lasso Regression Equations
  • -
  • Exercises for week 35
  • -
  • Exercise 1: Setting up various Python environments
  • -
  • Exercise 2: making your own data and exploring scikit-learn
  • -
  • Exercise 3: Normalizing our data
  • -
  • Exercise 4: Adding Ridge Regression
  • -
  • Exercise 5: Analytical exercises
  • +
  • Reducing the number of degrees of freedom, overarching view
  • +
  • Preprocessing our data
  • +
  • Functionality in Scikit-Learn
  • +
  • More preprocessing
  • +
  • Frequently used scaling functions
  • +
  • Example of own Standard scaling
  • +
  • Min-Max Scaling
  • +
  • Testing the Means Squared Error as function of Complexity
  • +
  • More preprocessing examples, two-dimensional example, the Franke function
  • +
  • To think about, first part
  • +
  • More thinking
  • +
  • Still thinking
  • +
  • What does centering (subtracting the mean values) mean mathematically?
  • +
  • Further Manipulations
  • +
  • Wrapping it up
  • +
  • Linear Regression code, Intercept handling first
  • +
  • The Boston housing data example
  • +
  • Housing data, the code
  • +
  • Material for lecture Thursday, August 31
  • +
  • Mathematical Interpretation of Ordinary Least Squares
  • +
  • Residual Error
  • +
  • Simple case
  • +
  • The singular value decomposition
  • +
  • Linear Regression Problems
  • +
  • Fixing the singularity
  • +
  • Basic math of the SVD
  • +
  • The SVD, a Fantastic Algorithm
  • +
  • Economy-size SVD
  • +
  • Codes for the SVD
  • +
  • Note about SVD Calculations
  • +
  • Mathematics of the SVD and implications
  • +
  • Example Matrix
  • +
  • Setting up the Matrix to be inverted
  • +
  • Further properties (important for our analyses later)
  • +
  • Meet the Covariance Matrix
  • +
  • Introducing the Covariance and Correlation functions
  • +
  • Covariance and Correlation Matrix
  • +
  • Correlation Function and Design/Feature Matrix
  • +
  • Covariance Matrix Examples
  • +
  • Correlation Matrix
  • +
  • Correlation Matrix with Pandas
  • +
  • Correlation Matrix with Pandas and the Franke function
  • +
  • Rewriting the Covariance and/or Correlation Matrix
  • +
  • Linking with the SVD
  • +
  • What does it mean?
  • +
  • And finally \( \boldsymbol{X}\boldsymbol{X}^T \)
  • +
  • Ridge and LASSO Regression
  • +
  • Deriving the Ridge Regression Equations
  • +
  • Interpreting the Ridge results
  • +
  • More interpretations
  • +
  • Deriving the Lasso Regression Equations
  • @@ -368,8 +369,8 @@ 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 +

    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 parameters \( \boldsymbol{\beta} \). Using the above expression for derivatives of vectors and matrices, we find that the second derivative of the mean squared error as cost function is, @@ -421,7 +422,7 @@ problem.

  • 24
  • 25
  • ...
  • -
  • 68
  • +
  • 74
  • »
  • diff --git a/doc/pub/week35/html/._week35-bs016.html b/doc/pub/week35/html/._week35-bs016.html index b7334fa58..f74c626fc 100644 --- a/doc/pub/week35/html/._week35-bs016.html +++ b/doc/pub/week35/html/._week35-bs016.html @@ -75,10 +75,10 @@ doconce format html week35.do.txt --html_style=bootstrap --pygments_html_style=d 2, None, 'interpretations-and-optimizing-our-parameters'), - ('Examples relevant for the exercises', + ('Example relevant for the exercises', 2, None, - 'examples-relevant-for-the-exercises'), + 'example-relevant-for-the-exercises'), ('Own code for Ordinary Least Squares', 2, None, @@ -91,16 +91,14 @@ doconce format html week35.do.txt --html_style=bootstrap --pygments_html_style=d 2, None, 'splitting-our-data-in-training-and-test-data'), - ('Examples', 2, None, 'examples'), + ('The complete code with a simple data set', + 2, + None, + 'the-complete-code-with-a-simple-data-set'), ('Making your own test-train splitting', 2, None, 'making-your-own-test-train-splitting'), - ('The Boston housing data example', - 2, - None, - 'the-boston-housing-data-example'), - ('Housing data, the code', 2, None, 'housing-data-the-code'), ('Reducing the number of degrees of freedom, overarching view', 2, None, @@ -124,10 +122,33 @@ doconce format html week35.do.txt --html_style=bootstrap --pygments_html_style=d 2, None, 'testing-the-means-squared-error-as-function-of-complexity'), - ('More preprocessing examples, Franke function and regression', + ('More preprocessing examples, two-dimensional example, the ' + 'Franke function', 2, None, - 'more-preprocessing-examples-franke-function-and-regression'), + 'more-preprocessing-examples-two-dimensional-example-the-franke-function'), + ('To think about, first part', + 2, + None, + 'to-think-about-first-part'), + ('More thinking', 2, None, 'more-thinking'), + ('Still thinking', 2, None, 'still-thinking'), + ('What does centering (subtracting the mean values) mean ' + 'mathematically?', + 2, + None, + 'what-does-centering-subtracting-the-mean-values-mean-mathematically'), + ('Further Manipulations', 2, None, 'further-manipulations'), + ('Wrapping it up', 2, None, 'wrapping-it-up'), + ('Linear Regression code, Intercept handling first', + 2, + None, + 'linear-regression-code-intercept-handling-first'), + ('The Boston housing data example', + 2, + None, + 'the-boston-housing-data-example'), + ('Housing data, the code', 2, None, 'housing-data-the-code'), ('Material for lecture Thursday, August 31', 2, None, @@ -226,28 +247,7 @@ doconce format html week35.do.txt --html_style=bootstrap --pygments_html_style=d ('Deriving the Lasso Regression Equations', 2, None, - 'deriving-the-lasso-regression-equations'), - ('Exercises for week 35', 2, None, 'exercises-for-week-35'), - ('Exercise 1: Setting up various Python environments', - 2, - None, - 'exercise-1-setting-up-various-python-environments'), - ('Exercise 2: making your own data and exploring scikit-learn', - 2, - None, - 'exercise-2-making-your-own-data-and-exploring-scikit-learn'), - ('Exercise 3: Normalizing our data', - 2, - None, - 'exercise-3-normalizing-our-data'), - ('Exercise 4: Adding Ridge Regression', - 2, - None, - 'exercise-4-adding-ridge-regression'), - ('Exercise 5: Analytical exercises', - 2, - None, - 'exercise-5-analytical-exercises')]} + 'deriving-the-lasso-regression-equations')]} end of tocinfo --> @@ -299,62 +299,63 @@ MathJax.Hub.Config({
  • Other useful relations
  • Meet the Hessian Matrix
  • Interpretations and optimizing our parameters
  • -
  • Examples relevant for the exercises
  • +
  • Example relevant for the exercises
  • Own code for Ordinary Least Squares
  • Adding error analysis and training set up
  • Splitting our Data in Training and Test data
  • -
  • Examples
  • +
  • The complete code with a simple data set
  • Making your own test-train splitting
  • -
  • The Boston housing data example
  • -
  • Housing data, the code
  • -
  • Reducing the number of degrees of freedom, overarching view
  • -
  • Preprocessing our data
  • -
  • Functionality in Scikit-Learn
  • -
  • More preprocessing
  • -
  • Frequently used scaling functions
  • -
  • Example of own Standard scaling
  • -
  • Min-Max Scaling
  • -
  • Testing the Means Squared Error as function of Complexity
  • -
  • More preprocessing examples, Franke function and regression
  • -
  • Material for lecture Thursday, August 31
  • -
  • Mathematical Interpretation of Ordinary Least Squares
  • -
  • Residual Error
  • -
  • Simple case
  • -
  • The singular value decomposition
  • -
  • Linear Regression Problems
  • -
  • Fixing the singularity
  • -
  • Basic math of the SVD
  • -
  • The SVD, a Fantastic Algorithm
  • -
  • Economy-size SVD
  • -
  • Codes for the SVD
  • -
  • Note about SVD Calculations
  • -
  • Mathematics of the SVD and implications
  • -
  • Example Matrix
  • -
  • Setting up the Matrix to be inverted
  • -
  • Further properties (important for our analyses later)
  • -
  • Meet the Covariance Matrix
  • -
  • Introducing the Covariance and Correlation functions
  • -
  • Covariance and Correlation Matrix
  • -
  • Correlation Function and Design/Feature Matrix
  • -
  • Covariance Matrix Examples
  • -
  • Correlation Matrix
  • -
  • Correlation Matrix with Pandas
  • -
  • Correlation Matrix with Pandas and the Franke function
  • -
  • Rewriting the Covariance and/or Correlation Matrix
  • -
  • Linking with the SVD
  • -
  • What does it mean?
  • -
  • And finally \( \boldsymbol{X}\boldsymbol{X}^T \)
  • -
  • Ridge and LASSO Regression
  • -
  • Deriving the Ridge Regression Equations
  • -
  • Interpreting the Ridge results
  • -
  • More interpretations
  • -
  • Deriving the Lasso Regression Equations
  • -
  • Exercises for week 35
  • -
  • Exercise 1: Setting up various Python environments
  • -
  • Exercise 2: making your own data and exploring scikit-learn
  • -
  • Exercise 3: Normalizing our data
  • -
  • Exercise 4: Adding Ridge Regression
  • -
  • Exercise 5: Analytical exercises
  • +
  • Reducing the number of degrees of freedom, overarching view
  • +
  • Preprocessing our data
  • +
  • Functionality in Scikit-Learn
  • +
  • More preprocessing
  • +
  • Frequently used scaling functions
  • +
  • Example of own Standard scaling
  • +
  • Min-Max Scaling
  • +
  • Testing the Means Squared Error as function of Complexity
  • +
  • More preprocessing examples, two-dimensional example, the Franke function
  • +
  • To think about, first part
  • +
  • More thinking
  • +
  • Still thinking
  • +
  • What does centering (subtracting the mean values) mean mathematically?
  • +
  • Further Manipulations
  • +
  • Wrapping it up
  • +
  • Linear Regression code, Intercept handling first
  • +
  • The Boston housing data example
  • +
  • Housing data, the code
  • +
  • Material for lecture Thursday, August 31
  • +
  • Mathematical Interpretation of Ordinary Least Squares
  • +
  • Residual Error
  • +
  • Simple case
  • +
  • The singular value decomposition
  • +
  • Linear Regression Problems
  • +
  • Fixing the singularity
  • +
  • Basic math of the SVD
  • +
  • The SVD, a Fantastic Algorithm
  • +
  • Economy-size SVD
  • +
  • Codes for the SVD
  • +
  • Note about SVD Calculations
  • +
  • Mathematics of the SVD and implications
  • +
  • Example Matrix
  • +
  • Setting up the Matrix to be inverted
  • +
  • Further properties (important for our analyses later)
  • +
  • Meet the Covariance Matrix
  • +
  • Introducing the Covariance and Correlation functions
  • +
  • Covariance and Correlation Matrix
  • +
  • Correlation Function and Design/Feature Matrix
  • +
  • Covariance Matrix Examples
  • +
  • Correlation Matrix
  • +
  • Correlation Matrix with Pandas
  • +
  • Correlation Matrix with Pandas and the Franke function
  • +
  • Rewriting the Covariance and/or Correlation Matrix
  • +
  • Linking with the SVD
  • +
  • What does it mean?
  • +
  • And finally \( \boldsymbol{X}\boldsymbol{X}^T \)
  • +
  • Ridge and LASSO Regression
  • +
  • Deriving the Ridge Regression Equations
  • +
  • Interpreting the Ridge results
  • +
  • More interpretations
  • +
  • Deriving the Lasso Regression Equations
  • @@ -416,7 +417,7 @@ $$
  • 25
  • 26
  • ...
  • -
  • 68
  • +
  • 74
  • »
  • diff --git a/doc/pub/week35/html/._week35-bs017.html b/doc/pub/week35/html/._week35-bs017.html index 071b50bea..cd22e9c60 100644 --- a/doc/pub/week35/html/._week35-bs017.html +++ b/doc/pub/week35/html/._week35-bs017.html @@ -75,10 +75,10 @@ doconce format html week35.do.txt --html_style=bootstrap --pygments_html_style=d 2, None, 'interpretations-and-optimizing-our-parameters'), - ('Examples relevant for the exercises', + ('Example relevant for the exercises', 2, None, - 'examples-relevant-for-the-exercises'), + 'example-relevant-for-the-exercises'), ('Own code for Ordinary Least Squares', 2, None, @@ -91,16 +91,14 @@ doconce format html week35.do.txt --html_style=bootstrap --pygments_html_style=d 2, None, 'splitting-our-data-in-training-and-test-data'), - ('Examples', 2, None, 'examples'), + ('The complete code with a simple data set', + 2, + None, + 'the-complete-code-with-a-simple-data-set'), ('Making your own test-train splitting', 2, None, 'making-your-own-test-train-splitting'), - ('The Boston housing data example', - 2, - None, - 'the-boston-housing-data-example'), - ('Housing data, the code', 2, None, 'housing-data-the-code'), ('Reducing the number of degrees of freedom, overarching view', 2, None, @@ -124,10 +122,33 @@ doconce format html week35.do.txt --html_style=bootstrap --pygments_html_style=d 2, None, 'testing-the-means-squared-error-as-function-of-complexity'), - ('More preprocessing examples, Franke function and regression', + ('More preprocessing examples, two-dimensional example, the ' + 'Franke function', 2, None, - 'more-preprocessing-examples-franke-function-and-regression'), + 'more-preprocessing-examples-two-dimensional-example-the-franke-function'), + ('To think about, first part', + 2, + None, + 'to-think-about-first-part'), + ('More thinking', 2, None, 'more-thinking'), + ('Still thinking', 2, None, 'still-thinking'), + ('What does centering (subtracting the mean values) mean ' + 'mathematically?', + 2, + None, + 'what-does-centering-subtracting-the-mean-values-mean-mathematically'), + ('Further Manipulations', 2, None, 'further-manipulations'), + ('Wrapping it up', 2, None, 'wrapping-it-up'), + ('Linear Regression code, Intercept handling first', + 2, + None, + 'linear-regression-code-intercept-handling-first'), + ('The Boston housing data example', + 2, + None, + 'the-boston-housing-data-example'), + ('Housing data, the code', 2, None, 'housing-data-the-code'), ('Material for lecture Thursday, August 31', 2, None, @@ -226,28 +247,7 @@ doconce format html week35.do.txt --html_style=bootstrap --pygments_html_style=d ('Deriving the Lasso Regression Equations', 2, None, - 'deriving-the-lasso-regression-equations'), - ('Exercises for week 35', 2, None, 'exercises-for-week-35'), - ('Exercise 1: Setting up various Python environments', - 2, - None, - 'exercise-1-setting-up-various-python-environments'), - ('Exercise 2: making your own data and exploring scikit-learn', - 2, - None, - 'exercise-2-making-your-own-data-and-exploring-scikit-learn'), - ('Exercise 3: Normalizing our data', - 2, - None, - 'exercise-3-normalizing-our-data'), - ('Exercise 4: Adding Ridge Regression', - 2, - None, - 'exercise-4-adding-ridge-regression'), - ('Exercise 5: Analytical exercises', - 2, - None, - 'exercise-5-analytical-exercises')]} + 'deriving-the-lasso-regression-equations')]} end of tocinfo --> @@ -299,62 +299,63 @@ MathJax.Hub.Config({
  • Other useful relations
  • Meet the Hessian Matrix
  • Interpretations and optimizing our parameters
  • -
  • Examples relevant for the exercises
  • +
  • Example relevant for the exercises
  • Own code for Ordinary Least Squares
  • Adding error analysis and training set up
  • Splitting our Data in Training and Test data
  • -
  • Examples
  • +
  • The complete code with a simple data set
  • Making your own test-train splitting
  • -
  • The Boston housing data example
  • -
  • Housing data, the code
  • -
  • Reducing the number of degrees of freedom, overarching view
  • -
  • Preprocessing our data
  • -
  • Functionality in Scikit-Learn
  • -
  • More preprocessing
  • -
  • Frequently used scaling functions
  • -
  • Example of own Standard scaling
  • -
  • Min-Max Scaling
  • -
  • Testing the Means Squared Error as function of Complexity
  • -
  • More preprocessing examples, Franke function and regression
  • -
  • Material for lecture Thursday, August 31
  • -
  • Mathematical Interpretation of Ordinary Least Squares
  • -
  • Residual Error
  • -
  • Simple case
  • -
  • The singular value decomposition
  • -
  • Linear Regression Problems
  • -
  • Fixing the singularity
  • -
  • Basic math of the SVD
  • -
  • The SVD, a Fantastic Algorithm
  • -
  • Economy-size SVD
  • -
  • Codes for the SVD
  • -
  • Note about SVD Calculations
  • -
  • Mathematics of the SVD and implications
  • -
  • Example Matrix
  • -
  • Setting up the Matrix to be inverted
  • -
  • Further properties (important for our analyses later)
  • -
  • Meet the Covariance Matrix
  • -
  • Introducing the Covariance and Correlation functions
  • -
  • Covariance and Correlation Matrix
  • -
  • Correlation Function and Design/Feature Matrix
  • -
  • Covariance Matrix Examples
  • -
  • Correlation Matrix
  • -
  • Correlation Matrix with Pandas
  • -
  • Correlation Matrix with Pandas and the Franke function
  • -
  • Rewriting the Covariance and/or Correlation Matrix
  • -
  • Linking with the SVD
  • -
  • What does it mean?
  • -
  • And finally \( \boldsymbol{X}\boldsymbol{X}^T \)
  • -
  • Ridge and LASSO Regression
  • -
  • Deriving the Ridge Regression Equations
  • -
  • Interpreting the Ridge results
  • -
  • More interpretations
  • -
  • Deriving the Lasso Regression Equations
  • -
  • Exercises for week 35
  • -
  • Exercise 1: Setting up various Python environments
  • -
  • Exercise 2: making your own data and exploring scikit-learn
  • -
  • Exercise 3: Normalizing our data
  • -
  • Exercise 4: Adding Ridge Regression
  • -
  • Exercise 5: Analytical exercises
  • +
  • Reducing the number of degrees of freedom, overarching view
  • +
  • Preprocessing our data
  • +
  • Functionality in Scikit-Learn
  • +
  • More preprocessing
  • +
  • Frequently used scaling functions
  • +
  • Example of own Standard scaling
  • +
  • Min-Max Scaling
  • +
  • Testing the Means Squared Error as function of Complexity
  • +
  • More preprocessing examples, two-dimensional example, the Franke function
  • +
  • To think about, first part
  • +
  • More thinking
  • +
  • Still thinking
  • +
  • What does centering (subtracting the mean values) mean mathematically?
  • +
  • Further Manipulations
  • +
  • Wrapping it up
  • +
  • Linear Regression code, Intercept handling first
  • +
  • The Boston housing data example
  • +
  • Housing data, the code
  • +
  • Material for lecture Thursday, August 31
  • +
  • Mathematical Interpretation of Ordinary Least Squares
  • +
  • Residual Error
  • +
  • Simple case
  • +
  • The singular value decomposition
  • +
  • Linear Regression Problems
  • +
  • Fixing the singularity
  • +
  • Basic math of the SVD
  • +
  • The SVD, a Fantastic Algorithm
  • +
  • Economy-size SVD
  • +
  • Codes for the SVD
  • +
  • Note about SVD Calculations
  • +
  • Mathematics of the SVD and implications
  • +
  • Example Matrix
  • +
  • Setting up the Matrix to be inverted
  • +
  • Further properties (important for our analyses later)
  • +
  • Meet the Covariance Matrix
  • +
  • Introducing the Covariance and Correlation functions
  • +
  • Covariance and Correlation Matrix
  • +
  • Correlation Function and Design/Feature Matrix
  • +
  • Covariance Matrix Examples
  • +
  • Correlation Matrix
  • +
  • Correlation Matrix with Pandas
  • +
  • Correlation Matrix with Pandas and the Franke function
  • +
  • Rewriting the Covariance and/or Correlation Matrix
  • +
  • Linking with the SVD
  • +
  • What does it mean?
  • +
  • And finally \( \boldsymbol{X}\boldsymbol{X}^T \)
  • +
  • Ridge and LASSO Regression
  • +
  • Deriving the Ridge Regression Equations
  • +
  • Interpreting the Ridge results
  • +
  • More interpretations
  • +
  • Deriving the Lasso Regression Equations
  • @@ -366,7 +367,7 @@ MathJax.Hub.Config({

     

     

     

    -

    Examples relevant for the exercises

    +

    Example relevant for the exercises

    In order to understand the relation among the predictors \( p \), the set of data \( n \) and the target (outcome, output etc) \( \boldsymbol{y} \), we condiser a simple polynomial fit. @@ -376,15 +377,10 @@ $$ \tilde{y}_i = \beta_0+\beta_1x_i+\beta_2x_i^2+\beta_3x_i^3+\beta_4x_i^4. $$ -

    we have five predictors, that is the intercept $\beta_0$and the other terms \( \beta_i \). -This gives \( p=0,1,2,3,4 \). Furthermore we have \( n \) entries for each predictor. It means that our design matrix is a +

    we have five predictors/features. The first is the intercept \( \beta_0 \). The other terms are \( \beta_i \) with \( i=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. -

    -

    diff --git a/doc/pub/week35/html/._week35-bs018.html b/doc/pub/week35/html/._week35-bs018.html index 34b35516c..9ae39f20e 100644 --- a/doc/pub/week35/html/._week35-bs018.html +++ b/doc/pub/week35/html/._week35-bs018.html @@ -75,10 +75,10 @@ doconce format html week35.do.txt --html_style=bootstrap --pygments_html_style=d 2, None, 'interpretations-and-optimizing-our-parameters'), - ('Examples relevant for the exercises', + ('Example relevant for the exercises', 2, None, - 'examples-relevant-for-the-exercises'), + 'example-relevant-for-the-exercises'), ('Own code for Ordinary Least Squares', 2, None, @@ -91,16 +91,14 @@ doconce format html week35.do.txt --html_style=bootstrap --pygments_html_style=d 2, None, 'splitting-our-data-in-training-and-test-data'), - ('Examples', 2, None, 'examples'), + ('The complete code with a simple data set', + 2, + None, + 'the-complete-code-with-a-simple-data-set'), ('Making your own test-train splitting', 2, None, 'making-your-own-test-train-splitting'), - ('The Boston housing data example', - 2, - None, - 'the-boston-housing-data-example'), - ('Housing data, the code', 2, None, 'housing-data-the-code'), ('Reducing the number of degrees of freedom, overarching view', 2, None, @@ -124,10 +122,33 @@ doconce format html week35.do.txt --html_style=bootstrap --pygments_html_style=d 2, None, 'testing-the-means-squared-error-as-function-of-complexity'), - ('More preprocessing examples, Franke function and regression', + ('More preprocessing examples, two-dimensional example, the ' + 'Franke function', 2, None, - 'more-preprocessing-examples-franke-function-and-regression'), + 'more-preprocessing-examples-two-dimensional-example-the-franke-function'), + ('To think about, first part', + 2, + None, + 'to-think-about-first-part'), + ('More thinking', 2, None, 'more-thinking'), + ('Still thinking', 2, None, 'still-thinking'), + ('What does centering (subtracting the mean values) mean ' + 'mathematically?', + 2, + None, + 'what-does-centering-subtracting-the-mean-values-mean-mathematically'), + ('Further Manipulations', 2, None, 'further-manipulations'), + ('Wrapping it up', 2, None, 'wrapping-it-up'), + ('Linear Regression code, Intercept handling first', + 2, + None, + 'linear-regression-code-intercept-handling-first'), + ('The Boston housing data example', + 2, + None, + 'the-boston-housing-data-example'), + ('Housing data, the code', 2, None, 'housing-data-the-code'), ('Material for lecture Thursday, August 31', 2, None, @@ -226,28 +247,7 @@ doconce format html week35.do.txt --html_style=bootstrap --pygments_html_style=d ('Deriving the Lasso Regression Equations', 2, None, - 'deriving-the-lasso-regression-equations'), - ('Exercises for week 35', 2, None, 'exercises-for-week-35'), - ('Exercise 1: Setting up various Python environments', - 2, - None, - 'exercise-1-setting-up-various-python-environments'), - ('Exercise 2: making your own data and exploring scikit-learn', - 2, - None, - 'exercise-2-making-your-own-data-and-exploring-scikit-learn'), - ('Exercise 3: Normalizing our data', - 2, - None, - 'exercise-3-normalizing-our-data'), - ('Exercise 4: Adding Ridge Regression', - 2, - None, - 'exercise-4-adding-ridge-regression'), - ('Exercise 5: Analytical exercises', - 2, - None, - 'exercise-5-analytical-exercises')]} + 'deriving-the-lasso-regression-equations')]} end of tocinfo --> @@ -299,62 +299,63 @@ MathJax.Hub.Config({
  • Other useful relations
  • Meet the Hessian Matrix
  • Interpretations and optimizing our parameters
  • -
  • Examples relevant for the exercises
  • +
  • Example relevant for the exercises
  • Own code for Ordinary Least Squares
  • Adding error analysis and training set up
  • Splitting our Data in Training and Test data
  • -
  • Examples
  • +
  • The complete code with a simple data set
  • Making your own test-train splitting
  • -
  • The Boston housing data example
  • -
  • Housing data, the code
  • -
  • Reducing the number of degrees of freedom, overarching view
  • -
  • Preprocessing our data
  • -
  • Functionality in Scikit-Learn
  • -
  • More preprocessing
  • -
  • Frequently used scaling functions
  • -
  • Example of own Standard scaling
  • -
  • Min-Max Scaling
  • -
  • Testing the Means Squared Error as function of Complexity
  • -
  • More preprocessing examples, Franke function and regression
  • -
  • Material for lecture Thursday, August 31
  • -
  • Mathematical Interpretation of Ordinary Least Squares
  • -
  • Residual Error
  • -
  • Simple case
  • -
  • The singular value decomposition
  • -
  • Linear Regression Problems
  • -
  • Fixing the singularity
  • -
  • Basic math of the SVD
  • -
  • The SVD, a Fantastic Algorithm
  • -
  • Economy-size SVD
  • -
  • Codes for the SVD
  • -
  • Note about SVD Calculations
  • -
  • Mathematics of the SVD and implications
  • -
  • Example Matrix
  • -
  • Setting up the Matrix to be inverted
  • -
  • Further properties (important for our analyses later)
  • -
  • Meet the Covariance Matrix
  • -
  • Introducing the Covariance and Correlation functions
  • -
  • Covariance and Correlation Matrix
  • -
  • Correlation Function and Design/Feature Matrix
  • -
  • Covariance Matrix Examples
  • -
  • Correlation Matrix
  • -
  • Correlation Matrix with Pandas
  • -
  • Correlation Matrix with Pandas and the Franke function
  • -
  • Rewriting the Covariance and/or Correlation Matrix
  • -
  • Linking with the SVD
  • -
  • What does it mean?
  • -
  • And finally \( \boldsymbol{X}\boldsymbol{X}^T \)
  • -
  • Ridge and LASSO Regression
  • -
  • Deriving the Ridge Regression Equations
  • -
  • Interpreting the Ridge results
  • -
  • More interpretations
  • -
  • Deriving the Lasso Regression Equations
  • -
  • Exercises for week 35
  • -
  • Exercise 1: Setting up various Python environments
  • -
  • Exercise 2: making your own data and exploring scikit-learn
  • -
  • Exercise 3: Normalizing our data
  • -
  • Exercise 4: Adding Ridge Regression
  • -
  • Exercise 5: Analytical exercises
  • +
  • Reducing the number of degrees of freedom, overarching view
  • +
  • Preprocessing our data
  • +
  • Functionality in Scikit-Learn
  • +
  • More preprocessing
  • +
  • Frequently used scaling functions
  • +
  • Example of own Standard scaling
  • +
  • Min-Max Scaling
  • +
  • Testing the Means Squared Error as function of Complexity
  • +
  • More preprocessing examples, two-dimensional example, the Franke function
  • +
  • To think about, first part
  • +
  • More thinking
  • +
  • Still thinking
  • +
  • What does centering (subtracting the mean values) mean mathematically?
  • +
  • Further Manipulations
  • +
  • Wrapping it up
  • +
  • Linear Regression code, Intercept handling first
  • +
  • The Boston housing data example
  • +
  • Housing data, the code
  • +
  • Material for lecture Thursday, August 31
  • +
  • Mathematical Interpretation of Ordinary Least Squares
  • +
  • Residual Error
  • +
  • Simple case
  • +
  • The singular value decomposition
  • +
  • Linear Regression Problems
  • +
  • Fixing the singularity
  • +
  • Basic math of the SVD
  • +
  • The SVD, a Fantastic Algorithm
  • +
  • Economy-size SVD
  • +
  • Codes for the SVD
  • +
  • Note about SVD Calculations
  • +
  • Mathematics of the SVD and implications
  • +
  • Example Matrix
  • +
  • Setting up the Matrix to be inverted
  • +
  • Further properties (important for our analyses later)
  • +
  • Meet the Covariance Matrix
  • +
  • Introducing the Covariance and Correlation functions
  • +
  • Covariance and Correlation Matrix
  • +
  • Correlation Function and Design/Feature Matrix
  • +
  • Covariance Matrix Examples
  • +
  • Correlation Matrix
  • +
  • Correlation Matrix with Pandas
  • +
  • Correlation Matrix with Pandas and the Franke function
  • +
  • Rewriting the Covariance and/or Correlation Matrix
  • +
  • Linking with the SVD
  • +
  • What does it mean?
  • +
  • And finally \( \boldsymbol{X}\boldsymbol{X}^T \)
  • +
  • Ridge and LASSO Regression
  • +
  • Deriving the Ridge Regression Equations
  • +
  • Interpreting the Ridge results
  • +
  • More interpretations
  • +
  • Deriving the Lasso Regression Equations
  • @@ -368,9 +369,7 @@ MathJax.Hub.Config({

    Own code for Ordinary Least Squares

    -

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

    +

    It is rather straightforward to implement the matrix inversion and obtain the parameters \( \boldsymbol{\beta} \). After having defined the matrix \( \boldsymbol{X} \) and the outputs \( \boldsymbol{y} \) we have

    @@ -379,7 +378,7 @@ write
    # matrix inversion to find beta
    -beta = np.linalg.inv(X.T.dot(X)).dot(X.T).dot(Energies)
    +beta = (np.linalg.inv(X.T @ X) @ X.T ) @ y
     # and then make the prediction
     ytilde = X @ beta
     
    @@ -422,41 +421,6 @@ ytildenp = np.<
    -

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

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

  • 27
  • 28
  • ...
  • -
  • 68
  • +
  • 74
  • »
  • diff --git a/doc/pub/week35/html/._week35-bs019.html b/doc/pub/week35/html/._week35-bs019.html index dd17d43f2..e0d876efa 100644 --- a/doc/pub/week35/html/._week35-bs019.html +++ b/doc/pub/week35/html/._week35-bs019.html @@ -75,10 +75,10 @@ doconce format html week35.do.txt --html_style=bootstrap --pygments_html_style=d 2, None, 'interpretations-and-optimizing-our-parameters'), - ('Examples relevant for the exercises', + ('Example relevant for the exercises', 2, None, - 'examples-relevant-for-the-exercises'), + 'example-relevant-for-the-exercises'), ('Own code for Ordinary Least Squares', 2, None, @@ -91,16 +91,14 @@ doconce format html week35.do.txt --html_style=bootstrap --pygments_html_style=d 2, None, 'splitting-our-data-in-training-and-test-data'), - ('Examples', 2, None, 'examples'), + ('The complete code with a simple data set', + 2, + None, + 'the-complete-code-with-a-simple-data-set'), ('Making your own test-train splitting', 2, None, 'making-your-own-test-train-splitting'), - ('The Boston housing data example', - 2, - None, - 'the-boston-housing-data-example'), - ('Housing data, the code', 2, None, 'housing-data-the-code'), ('Reducing the number of degrees of freedom, overarching view', 2, None, @@ -124,10 +122,33 @@ doconce format html week35.do.txt --html_style=bootstrap --pygments_html_style=d 2, None, 'testing-the-means-squared-error-as-function-of-complexity'), - ('More preprocessing examples, Franke function and regression', + ('More preprocessing examples, two-dimensional example, the ' + 'Franke function', 2, None, - 'more-preprocessing-examples-franke-function-and-regression'), + 'more-preprocessing-examples-two-dimensional-example-the-franke-function'), + ('To think about, first part', + 2, + None, + 'to-think-about-first-part'), + ('More thinking', 2, None, 'more-thinking'), + ('Still thinking', 2, None, 'still-thinking'), + ('What does centering (subtracting the mean values) mean ' + 'mathematically?', + 2, + None, + 'what-does-centering-subtracting-the-mean-values-mean-mathematically'), + ('Further Manipulations', 2, None, 'further-manipulations'), + ('Wrapping it up', 2, None, 'wrapping-it-up'), + ('Linear Regression code, Intercept handling first', + 2, + None, + 'linear-regression-code-intercept-handling-first'), + ('The Boston housing data example', + 2, + None, + 'the-boston-housing-data-example'), + ('Housing data, the code', 2, None, 'housing-data-the-code'), ('Material for lecture Thursday, August 31', 2, None, @@ -226,28 +247,7 @@ doconce format html week35.do.txt --html_style=bootstrap --pygments_html_style=d ('Deriving the Lasso Regression Equations', 2, None, - 'deriving-the-lasso-regression-equations'), - ('Exercises for week 35', 2, None, 'exercises-for-week-35'), - ('Exercise 1: Setting up various Python environments', - 2, - None, - 'exercise-1-setting-up-various-python-environments'), - ('Exercise 2: making your own data and exploring scikit-learn', - 2, - None, - 'exercise-2-making-your-own-data-and-exploring-scikit-learn'), - ('Exercise 3: Normalizing our data', - 2, - None, - 'exercise-3-normalizing-our-data'), - ('Exercise 4: Adding Ridge Regression', - 2, - None, - 'exercise-4-adding-ridge-regression'), - ('Exercise 5: Analytical exercises', - 2, - None, - 'exercise-5-analytical-exercises')]} + 'deriving-the-lasso-regression-equations')]} end of tocinfo --> @@ -299,62 +299,63 @@ MathJax.Hub.Config({
  • Other useful relations
  • Meet the Hessian Matrix
  • Interpretations and optimizing our parameters
  • -
  • Examples relevant for the exercises
  • +
  • Example relevant for the exercises
  • Own code for Ordinary Least Squares
  • Adding error analysis and training set up
  • Splitting our Data in Training and Test data
  • -
  • Examples
  • +
  • The complete code with a simple data set
  • Making your own test-train splitting
  • -
  • The Boston housing data example
  • -
  • Housing data, the code
  • -
  • Reducing the number of degrees of freedom, overarching view
  • -
  • Preprocessing our data
  • -
  • Functionality in Scikit-Learn
  • -
  • More preprocessing
  • -
  • Frequently used scaling functions
  • -
  • Example of own Standard scaling
  • -
  • Min-Max Scaling
  • -
  • Testing the Means Squared Error as function of Complexity
  • -
  • More preprocessing examples, Franke function and regression
  • -
  • Material for lecture Thursday, August 31
  • -
  • Mathematical Interpretation of Ordinary Least Squares
  • -
  • Residual Error
  • -
  • Simple case
  • -
  • The singular value decomposition
  • -
  • Linear Regression Problems
  • -
  • Fixing the singularity
  • -
  • Basic math of the SVD
  • -
  • The SVD, a Fantastic Algorithm
  • -
  • Economy-size SVD
  • -
  • Codes for the SVD
  • -
  • Note about SVD Calculations
  • -
  • Mathematics of the SVD and implications
  • -
  • Example Matrix
  • -
  • Setting up the Matrix to be inverted
  • -
  • Further properties (important for our analyses later)
  • -
  • Meet the Covariance Matrix
  • -
  • Introducing the Covariance and Correlation functions
  • -
  • Covariance and Correlation Matrix
  • -
  • Correlation Function and Design/Feature Matrix
  • -
  • Covariance Matrix Examples
  • -
  • Correlation Matrix
  • -
  • Correlation Matrix with Pandas
  • -
  • Correlation Matrix with Pandas and the Franke function
  • -
  • Rewriting the Covariance and/or Correlation Matrix
  • -
  • Linking with the SVD
  • -
  • What does it mean?
  • -
  • And finally \( \boldsymbol{X}\boldsymbol{X}^T \)
  • -
  • Ridge and LASSO Regression
  • -
  • Deriving the Ridge Regression Equations
  • -
  • Interpreting the Ridge results
  • -
  • More interpretations
  • -
  • Deriving the Lasso Regression Equations
  • -
  • Exercises for week 35
  • -
  • Exercise 1: Setting up various Python environments
  • -
  • Exercise 2: making your own data and exploring scikit-learn
  • -
  • Exercise 3: Normalizing our data
  • -
  • Exercise 4: Adding Ridge Regression
  • -
  • Exercise 5: Analytical exercises
  • +
  • Reducing the number of degrees of freedom, overarching view
  • +
  • Preprocessing our data
  • +
  • Functionality in Scikit-Learn
  • +
  • More preprocessing
  • +
  • Frequently used scaling functions
  • +
  • Example of own Standard scaling
  • +
  • Min-Max Scaling
  • +
  • Testing the Means Squared Error as function of Complexity
  • +
  • More preprocessing examples, two-dimensional example, the Franke function
  • +
  • To think about, first part
  • +
  • More thinking
  • +
  • Still thinking
  • +
  • What does centering (subtracting the mean values) mean mathematically?
  • +
  • Further Manipulations
  • +
  • Wrapping it up
  • +
  • Linear Regression code, Intercept handling first
  • +
  • The Boston housing data example
  • +
  • Housing data, the code
  • +
  • Material for lecture Thursday, August 31
  • +
  • Mathematical Interpretation of Ordinary Least Squares
  • +
  • Residual Error
  • +
  • Simple case
  • +
  • The singular value decomposition
  • +
  • Linear Regression Problems
  • +
  • Fixing the singularity
  • +
  • Basic math of the SVD
  • +
  • The SVD, a Fantastic Algorithm
  • +
  • Economy-size SVD
  • +
  • Codes for the SVD
  • +
  • Note about SVD Calculations
  • +
  • Mathematics of the SVD and implications
  • +
  • Example Matrix
  • +
  • Setting up the Matrix to be inverted
  • +
  • Further properties (important for our analyses later)
  • +
  • Meet the Covariance Matrix
  • +
  • Introducing the Covariance and Correlation functions
  • +
  • Covariance and Correlation Matrix
  • +
  • Correlation Function and Design/Feature Matrix
  • +
  • Covariance Matrix Examples
  • +
  • Correlation Matrix
  • +
  • Correlation Matrix with Pandas
  • +
  • Correlation Matrix with Pandas and the Franke function
  • +
  • Rewriting the Covariance and/or Correlation Matrix
  • +
  • Linking with the SVD
  • +
  • What does it mean?
  • +
  • And finally \( \boldsymbol{X}\boldsymbol{X}^T \)
  • +
  • Ridge and LASSO Regression
  • +
  • Deriving the Ridge Regression Equations
  • +
  • Interpreting the Ridge results
  • +
  • More interpretations
  • +
  • Deriving the Lasso Regression Equations
  • @@ -499,7 +500,7 @@ Since we are not using Scikit-Learn here we can define our own \( R2 \) f
  • 28
  • 29
  • ...
  • -
  • 68
  • +
  • 74
  • »
  • diff --git a/doc/pub/week35/html/._week35-bs020.html b/doc/pub/week35/html/._week35-bs020.html index 44f40dd5b..5dacb3bad 100644 --- a/doc/pub/week35/html/._week35-bs020.html +++ b/doc/pub/week35/html/._week35-bs020.html @@ -75,10 +75,10 @@ doconce format html week35.do.txt --html_style=bootstrap --pygments_html_style=d 2, None, 'interpretations-and-optimizing-our-parameters'), - ('Examples relevant for the exercises', + ('Example relevant for the exercises', 2, None, - 'examples-relevant-for-the-exercises'), + 'example-relevant-for-the-exercises'), ('Own code for Ordinary Least Squares', 2, None, @@ -91,16 +91,14 @@ doconce format html week35.do.txt --html_style=bootstrap --pygments_html_style=d 2, None, 'splitting-our-data-in-training-and-test-data'), - ('Examples', 2, None, 'examples'), + ('The complete code with a simple data set', + 2, + None, + 'the-complete-code-with-a-simple-data-set'), ('Making your own test-train splitting', 2, None, 'making-your-own-test-train-splitting'), - ('The Boston housing data example', - 2, - None, - 'the-boston-housing-data-example'), - ('Housing data, the code', 2, None, 'housing-data-the-code'), ('Reducing the number of degrees of freedom, overarching view', 2, None, @@ -124,10 +122,33 @@ doconce format html week35.do.txt --html_style=bootstrap --pygments_html_style=d 2, None, 'testing-the-means-squared-error-as-function-of-complexity'), - ('More preprocessing examples, Franke function and regression', + ('More preprocessing examples, two-dimensional example, the ' + 'Franke function', 2, None, - 'more-preprocessing-examples-franke-function-and-regression'), + 'more-preprocessing-examples-two-dimensional-example-the-franke-function'), + ('To think about, first part', + 2, + None, + 'to-think-about-first-part'), + ('More thinking', 2, None, 'more-thinking'), + ('Still thinking', 2, None, 'still-thinking'), + ('What does centering (subtracting the mean values) mean ' + 'mathematically?', + 2, + None, + 'what-does-centering-subtracting-the-mean-values-mean-mathematically'), + ('Further Manipulations', 2, None, 'further-manipulations'), + ('Wrapping it up', 2, None, 'wrapping-it-up'), + ('Linear Regression code, Intercept handling first', + 2, + None, + 'linear-regression-code-intercept-handling-first'), + ('The Boston housing data example', + 2, + None, + 'the-boston-housing-data-example'), + ('Housing data, the code', 2, None, 'housing-data-the-code'), ('Material for lecture Thursday, August 31', 2, None, @@ -226,28 +247,7 @@ doconce format html week35.do.txt --html_style=bootstrap --pygments_html_style=d ('Deriving the Lasso Regression Equations', 2, None, - 'deriving-the-lasso-regression-equations'), - ('Exercises for week 35', 2, None, 'exercises-for-week-35'), - ('Exercise 1: Setting up various Python environments', - 2, - None, - 'exercise-1-setting-up-various-python-environments'), - ('Exercise 2: making your own data and exploring scikit-learn', - 2, - None, - 'exercise-2-making-your-own-data-and-exploring-scikit-learn'), - ('Exercise 3: Normalizing our data', - 2, - None, - 'exercise-3-normalizing-our-data'), - ('Exercise 4: Adding Ridge Regression', - 2, - None, - 'exercise-4-adding-ridge-regression'), - ('Exercise 5: Analytical exercises', - 2, - None, - 'exercise-5-analytical-exercises')]} + 'deriving-the-lasso-regression-equations')]} end of tocinfo --> @@ -299,62 +299,63 @@ MathJax.Hub.Config({
  • Other useful relations
  • Meet the Hessian Matrix
  • Interpretations and optimizing our parameters
  • -
  • Examples relevant for the exercises
  • +
  • Example relevant for the exercises
  • Own code for Ordinary Least Squares
  • Adding error analysis and training set up
  • Splitting our Data in Training and Test data
  • -
  • Examples
  • +
  • The complete code with a simple data set
  • Making your own test-train splitting
  • -
  • The Boston housing data example
  • -
  • Housing data, the code
  • -
  • Reducing the number of degrees of freedom, overarching view
  • -
  • Preprocessing our data
  • -
  • Functionality in Scikit-Learn
  • -
  • More preprocessing
  • -
  • Frequently used scaling functions
  • -
  • Example of own Standard scaling
  • -
  • Min-Max Scaling
  • -
  • Testing the Means Squared Error as function of Complexity
  • -
  • More preprocessing examples, Franke function and regression
  • -
  • Material for lecture Thursday, August 31
  • -
  • Mathematical Interpretation of Ordinary Least Squares
  • -
  • Residual Error
  • -
  • Simple case
  • -
  • The singular value decomposition
  • -
  • Linear Regression Problems
  • -
  • Fixing the singularity
  • -
  • Basic math of the SVD
  • -
  • The SVD, a Fantastic Algorithm
  • -
  • Economy-size SVD
  • -
  • Codes for the SVD
  • -
  • Note about SVD Calculations
  • -
  • Mathematics of the SVD and implications
  • -
  • Example Matrix
  • -
  • Setting up the Matrix to be inverted
  • -
  • Further properties (important for our analyses later)
  • -
  • Meet the Covariance Matrix
  • -
  • Introducing the Covariance and Correlation functions
  • -
  • Covariance and Correlation Matrix
  • -
  • Correlation Function and Design/Feature Matrix
  • -
  • Covariance Matrix Examples
  • -
  • Correlation Matrix
  • -
  • Correlation Matrix with Pandas
  • -
  • Correlation Matrix with Pandas and the Franke function
  • -
  • Rewriting the Covariance and/or Correlation Matrix
  • -
  • Linking with the SVD
  • -
  • What does it mean?
  • -
  • And finally \( \boldsymbol{X}\boldsymbol{X}^T \)
  • -
  • Ridge and LASSO Regression
  • -
  • Deriving the Ridge Regression Equations
  • -
  • Interpreting the Ridge results
  • -
  • More interpretations
  • -
  • Deriving the Lasso Regression Equations
  • -
  • Exercises for week 35
  • -
  • Exercise 1: Setting up various Python environments
  • -
  • Exercise 2: making your own data and exploring scikit-learn
  • -
  • Exercise 3: Normalizing our data
  • -
  • Exercise 4: Adding Ridge Regression
  • -
  • Exercise 5: Analytical exercises
  • +
  • Reducing the number of degrees of freedom, overarching view
  • +
  • Preprocessing our data
  • +
  • Functionality in Scikit-Learn
  • +
  • More preprocessing
  • +
  • Frequently used scaling functions
  • +
  • Example of own Standard scaling
  • +
  • Min-Max Scaling
  • +
  • Testing the Means Squared Error as function of Complexity
  • +
  • More preprocessing examples, two-dimensional example, the Franke function
  • +
  • To think about, first part
  • +
  • More thinking
  • +
  • Still thinking
  • +
  • What does centering (subtracting the mean values) mean mathematically?
  • +
  • Further Manipulations
  • +
  • Wrapping it up
  • +
  • Linear Regression code, Intercept handling first
  • +
  • The Boston housing data example
  • +
  • Housing data, the code
  • +
  • Material for lecture Thursday, August 31
  • +
  • Mathematical Interpretation of Ordinary Least Squares
  • +
  • Residual Error
  • +
  • Simple case
  • +
  • The singular value decomposition
  • +
  • Linear Regression Problems
  • +
  • Fixing the singularity
  • +
  • Basic math of the SVD
  • +
  • The SVD, a Fantastic Algorithm
  • +
  • Economy-size SVD
  • +
  • Codes for the SVD
  • +
  • Note about SVD Calculations
  • +
  • Mathematics of the SVD and implications
  • +
  • Example Matrix
  • +
  • Setting up the Matrix to be inverted
  • +
  • Further properties (important for our analyses later)
  • +
  • Meet the Covariance Matrix
  • +
  • Introducing the Covariance and Correlation functions
  • +
  • Covariance and Correlation Matrix
  • +
  • Correlation Function and Design/Feature Matrix
  • +
  • Covariance Matrix Examples
  • +
  • Correlation Matrix
  • +
  • Correlation Matrix with Pandas
  • +
  • Correlation Matrix with Pandas and the Franke function
  • +
  • Rewriting the Covariance and/or Correlation Matrix
  • +
  • Linking with the SVD
  • +
  • What does it mean?
  • +
  • And finally \( \boldsymbol{X}\boldsymbol{X}^T \)
  • +
  • Ridge and LASSO Regression
  • +
  • Deriving the Ridge Regression Equations
  • +
  • Interpreting the Ridge results
  • +
  • More interpretations
  • +
  • Deriving the Lasso Regression Equations
  • @@ -412,7 +413,7 @@ but now splitting the data into a training set and a test set.
  • 29
  • 30
  • ...
  • -
  • 68
  • +
  • 74
  • »
  • diff --git a/doc/pub/week35/html/._week35-bs021.html b/doc/pub/week35/html/._week35-bs021.html index 08c7d6f0a..3c9cfd3e3 100644 --- a/doc/pub/week35/html/._week35-bs021.html +++ b/doc/pub/week35/html/._week35-bs021.html @@ -75,10 +75,10 @@ doconce format html week35.do.txt --html_style=bootstrap --pygments_html_style=d 2, None, 'interpretations-and-optimizing-our-parameters'), - ('Examples relevant for the exercises', + ('Example relevant for the exercises', 2, None, - 'examples-relevant-for-the-exercises'), + 'example-relevant-for-the-exercises'), ('Own code for Ordinary Least Squares', 2, None, @@ -91,16 +91,14 @@ doconce format html week35.do.txt --html_style=bootstrap --pygments_html_style=d 2, None, 'splitting-our-data-in-training-and-test-data'), - ('Examples', 2, None, 'examples'), + ('The complete code with a simple data set', + 2, + None, + 'the-complete-code-with-a-simple-data-set'), ('Making your own test-train splitting', 2, None, 'making-your-own-test-train-splitting'), - ('The Boston housing data example', - 2, - None, - 'the-boston-housing-data-example'), - ('Housing data, the code', 2, None, 'housing-data-the-code'), ('Reducing the number of degrees of freedom, overarching view', 2, None, @@ -124,10 +122,33 @@ doconce format html week35.do.txt --html_style=bootstrap --pygments_html_style=d 2, None, 'testing-the-means-squared-error-as-function-of-complexity'), - ('More preprocessing examples, Franke function and regression', + ('More preprocessing examples, two-dimensional example, the ' + 'Franke function', 2, None, - 'more-preprocessing-examples-franke-function-and-regression'), + 'more-preprocessing-examples-two-dimensional-example-the-franke-function'), + ('To think about, first part', + 2, + None, + 'to-think-about-first-part'), + ('More thinking', 2, None, 'more-thinking'), + ('Still thinking', 2, None, 'still-thinking'), + ('What does centering (subtracting the mean values) mean ' + 'mathematically?', + 2, + None, + 'what-does-centering-subtracting-the-mean-values-mean-mathematically'), + ('Further Manipulations', 2, None, 'further-manipulations'), + ('Wrapping it up', 2, None, 'wrapping-it-up'), + ('Linear Regression code, Intercept handling first', + 2, + None, + 'linear-regression-code-intercept-handling-first'), + ('The Boston housing data example', + 2, + None, + 'the-boston-housing-data-example'), + ('Housing data, the code', 2, None, 'housing-data-the-code'), ('Material for lecture Thursday, August 31', 2, None, @@ -226,28 +247,7 @@ doconce format html week35.do.txt --html_style=bootstrap --pygments_html_style=d ('Deriving the Lasso Regression Equations', 2, None, - 'deriving-the-lasso-regression-equations'), - ('Exercises for week 35', 2, None, 'exercises-for-week-35'), - ('Exercise 1: Setting up various Python environments', - 2, - None, - 'exercise-1-setting-up-various-python-environments'), - ('Exercise 2: making your own data and exploring scikit-learn', - 2, - None, - 'exercise-2-making-your-own-data-and-exploring-scikit-learn'), - ('Exercise 3: Normalizing our data', - 2, - None, - 'exercise-3-normalizing-our-data'), - ('Exercise 4: Adding Ridge Regression', - 2, - None, - 'exercise-4-adding-ridge-regression'), - ('Exercise 5: Analytical exercises', - 2, - None, - 'exercise-5-analytical-exercises')]} + 'deriving-the-lasso-regression-equations')]} end of tocinfo --> @@ -299,62 +299,63 @@ MathJax.Hub.Config({
  • Other useful relations
  • Meet the Hessian Matrix
  • Interpretations and optimizing our parameters
  • -
  • Examples relevant for the exercises
  • +
  • Example relevant for the exercises
  • Own code for Ordinary Least Squares
  • Adding error analysis and training set up
  • Splitting our Data in Training and Test data
  • -
  • Examples
  • +
  • The complete code with a simple data set
  • Making your own test-train splitting
  • -
  • The Boston housing data example
  • -
  • Housing data, the code
  • -
  • Reducing the number of degrees of freedom, overarching view
  • -
  • Preprocessing our data
  • -
  • Functionality in Scikit-Learn
  • -
  • More preprocessing
  • -
  • Frequently used scaling functions
  • -
  • Example of own Standard scaling
  • -
  • Min-Max Scaling
  • -
  • Testing the Means Squared Error as function of Complexity
  • -
  • More preprocessing examples, Franke function and regression
  • -
  • Material for lecture Thursday, August 31
  • -
  • Mathematical Interpretation of Ordinary Least Squares
  • -
  • Residual Error
  • -
  • Simple case
  • -
  • The singular value decomposition
  • -
  • Linear Regression Problems
  • -
  • Fixing the singularity
  • -
  • Basic math of the SVD
  • -
  • The SVD, a Fantastic Algorithm
  • -
  • Economy-size SVD
  • -
  • Codes for the SVD
  • -
  • Note about SVD Calculations
  • -
  • Mathematics of the SVD and implications
  • -
  • Example Matrix
  • -
  • Setting up the Matrix to be inverted
  • -
  • Further properties (important for our analyses later)
  • -
  • Meet the Covariance Matrix
  • -
  • Introducing the Covariance and Correlation functions
  • -
  • Covariance and Correlation Matrix
  • -
  • Correlation Function and Design/Feature Matrix
  • -
  • Covariance Matrix Examples
  • -
  • Correlation Matrix
  • -
  • Correlation Matrix with Pandas
  • -
  • Correlation Matrix with Pandas and the Franke function
  • -
  • Rewriting the Covariance and/or Correlation Matrix
  • -
  • Linking with the SVD
  • -
  • What does it mean?
  • -
  • And finally \( \boldsymbol{X}\boldsymbol{X}^T \)
  • -
  • Ridge and LASSO Regression
  • -
  • Deriving the Ridge Regression Equations
  • -
  • Interpreting the Ridge results
  • -
  • More interpretations
  • -
  • Deriving the Lasso Regression Equations
  • -
  • Exercises for week 35
  • -
  • Exercise 1: Setting up various Python environments
  • -
  • Exercise 2: making your own data and exploring scikit-learn
  • -
  • Exercise 3: Normalizing our data
  • -
  • Exercise 4: Adding Ridge Regression
  • -
  • Exercise 5: Analytical exercises
  • +
  • Reducing the number of degrees of freedom, overarching view
  • +
  • Preprocessing our data
  • +
  • Functionality in Scikit-Learn
  • +
  • More preprocessing
  • +
  • Frequently used scaling functions
  • +
  • Example of own Standard scaling
  • +
  • Min-Max Scaling
  • +
  • Testing the Means Squared Error as function of Complexity
  • +
  • More preprocessing examples, two-dimensional example, the Franke function
  • +
  • To think about, first part
  • +
  • More thinking
  • +
  • Still thinking
  • +
  • What does centering (subtracting the mean values) mean mathematically?
  • +
  • Further Manipulations
  • +
  • Wrapping it up
  • +
  • Linear Regression code, Intercept handling first
  • +
  • The Boston housing data example
  • +
  • Housing data, the code
  • +
  • Material for lecture Thursday, August 31
  • +
  • Mathematical Interpretation of Ordinary Least Squares
  • +
  • Residual Error
  • +
  • Simple case
  • +
  • The singular value decomposition
  • +
  • Linear Regression Problems
  • +
  • Fixing the singularity
  • +
  • Basic math of the SVD
  • +
  • The SVD, a Fantastic Algorithm
  • +
  • Economy-size SVD
  • +
  • Codes for the SVD
  • +
  • Note about SVD Calculations
  • +
  • Mathematics of the SVD and implications
  • +
  • Example Matrix
  • +
  • Setting up the Matrix to be inverted
  • +
  • Further properties (important for our analyses later)
  • +
  • Meet the Covariance Matrix
  • +
  • Introducing the Covariance and Correlation functions
  • +
  • Covariance and Correlation Matrix
  • +
  • Correlation Function and Design/Feature Matrix
  • +
  • Covariance Matrix Examples
  • +
  • Correlation Matrix
  • +
  • Correlation Matrix with Pandas
  • +
  • Correlation Matrix with Pandas and the Franke function
  • +
  • Rewriting the Covariance and/or Correlation Matrix
  • +
  • Linking with the SVD
  • +
  • What does it mean?
  • +
  • And finally \( \boldsymbol{X}\boldsymbol{X}^T \)
  • +
  • Ridge and LASSO Regression
  • +
  • Deriving the Ridge Regression Equations
  • +
  • Interpreting the Ridge results
  • +
  • More interpretations
  • +
  • Deriving the Lasso Regression Equations
  • @@ -366,7 +367,7 @@ MathJax.Hub.Config({

     

     

     

    -

    Examples

    +

    The complete code with a simple data set

    @@ -392,11 +393,13 @@ x = np.r 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)) +# The design matrix now as function of a fourth-order polynomial +X = np.zeros((len(x),5)) X[:,0] = 1.0 X[:,1] = x X[:,2] = x**2 +X[:,3] = x**3 +X[:,4] = x**4 # 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 @@ -454,7 +457,7 @@ ypredict = X_test 30
  • 31
  • ...
  • -
  • 68
  • +
  • 74
  • »
  • diff --git a/doc/pub/week35/html/._week35-bs022.html b/doc/pub/week35/html/._week35-bs022.html index e2a5dad87..c14066588 100644 --- a/doc/pub/week35/html/._week35-bs022.html +++ b/doc/pub/week35/html/._week35-bs022.html @@ -75,10 +75,10 @@ doconce format html week35.do.txt --html_style=bootstrap --pygments_html_style=d 2, None, 'interpretations-and-optimizing-our-parameters'), - ('Examples relevant for the exercises', + ('Example relevant for the exercises', 2, None, - 'examples-relevant-for-the-exercises'), + 'example-relevant-for-the-exercises'), ('Own code for Ordinary Least Squares', 2, None, @@ -91,16 +91,14 @@ doconce format html week35.do.txt --html_style=bootstrap --pygments_html_style=d 2, None, 'splitting-our-data-in-training-and-test-data'), - ('Examples', 2, None, 'examples'), + ('The complete code with a simple data set', + 2, + None, + 'the-complete-code-with-a-simple-data-set'), ('Making your own test-train splitting', 2, None, 'making-your-own-test-train-splitting'), - ('The Boston housing data example', - 2, - None, - 'the-boston-housing-data-example'), - ('Housing data, the code', 2, None, 'housing-data-the-code'), ('Reducing the number of degrees of freedom, overarching view', 2, None, @@ -124,10 +122,33 @@ doconce format html week35.do.txt --html_style=bootstrap --pygments_html_style=d 2, None, 'testing-the-means-squared-error-as-function-of-complexity'), - ('More preprocessing examples, Franke function and regression', + ('More preprocessing examples, two-dimensional example, the ' + 'Franke function', 2, None, - 'more-preprocessing-examples-franke-function-and-regression'), + 'more-preprocessing-examples-two-dimensional-example-the-franke-function'), + ('To think about, first part', + 2, + None, + 'to-think-about-first-part'), + ('More thinking', 2, None, 'more-thinking'), + ('Still thinking', 2, None, 'still-thinking'), + ('What does centering (subtracting the mean values) mean ' + 'mathematically?', + 2, + None, + 'what-does-centering-subtracting-the-mean-values-mean-mathematically'), + ('Further Manipulations', 2, None, 'further-manipulations'), + ('Wrapping it up', 2, None, 'wrapping-it-up'), + ('Linear Regression code, Intercept handling first', + 2, + None, + 'linear-regression-code-intercept-handling-first'), + ('The Boston housing data example', + 2, + None, + 'the-boston-housing-data-example'), + ('Housing data, the code', 2, None, 'housing-data-the-code'), ('Material for lecture Thursday, August 31', 2, None, @@ -226,28 +247,7 @@ doconce format html week35.do.txt --html_style=bootstrap --pygments_html_style=d ('Deriving the Lasso Regression Equations', 2, None, - 'deriving-the-lasso-regression-equations'), - ('Exercises for week 35', 2, None, 'exercises-for-week-35'), - ('Exercise 1: Setting up various Python environments', - 2, - None, - 'exercise-1-setting-up-various-python-environments'), - ('Exercise 2: making your own data and exploring scikit-learn', - 2, - None, - 'exercise-2-making-your-own-data-and-exploring-scikit-learn'), - ('Exercise 3: Normalizing our data', - 2, - None, - 'exercise-3-normalizing-our-data'), - ('Exercise 4: Adding Ridge Regression', - 2, - None, - 'exercise-4-adding-ridge-regression'), - ('Exercise 5: Analytical exercises', - 2, - None, - 'exercise-5-analytical-exercises')]} + 'deriving-the-lasso-regression-equations')]} end of tocinfo --> @@ -299,62 +299,63 @@ MathJax.Hub.Config({
  • Other useful relations
  • Meet the Hessian Matrix
  • Interpretations and optimizing our parameters
  • -
  • Examples relevant for the exercises
  • +
  • Example relevant for the exercises
  • Own code for Ordinary Least Squares
  • Adding error analysis and training set up
  • Splitting our Data in Training and Test data
  • -
  • Examples
  • +
  • The complete code with a simple data set
  • Making your own test-train splitting
  • -
  • The Boston housing data example
  • -
  • Housing data, the code
  • -
  • Reducing the number of degrees of freedom, overarching view
  • -
  • Preprocessing our data
  • -
  • Functionality in Scikit-Learn
  • -
  • More preprocessing
  • -
  • Frequently used scaling functions
  • -
  • Example of own Standard scaling
  • -
  • Min-Max Scaling
  • -
  • Testing the Means Squared Error as function of Complexity
  • -
  • More preprocessing examples, Franke function and regression
  • -
  • Material for lecture Thursday, August 31
  • -
  • Mathematical Interpretation of Ordinary Least Squares
  • -
  • Residual Error
  • -
  • Simple case
  • -
  • The singular value decomposition
  • -
  • Linear Regression Problems
  • -
  • Fixing the singularity
  • -
  • Basic math of the SVD
  • -
  • The SVD, a Fantastic Algorithm
  • -
  • Economy-size SVD
  • -
  • Codes for the SVD
  • -
  • Note about SVD Calculations
  • -
  • Mathematics of the SVD and implications
  • -
  • Example Matrix
  • -
  • Setting up the Matrix to be inverted
  • -
  • Further properties (important for our analyses later)
  • -
  • Meet the Covariance Matrix
  • -
  • Introducing the Covariance and Correlation functions
  • -
  • Covariance and Correlation Matrix
  • -
  • Correlation Function and Design/Feature Matrix
  • -
  • Covariance Matrix Examples
  • -
  • Correlation Matrix
  • -
  • Correlation Matrix with Pandas
  • -
  • Correlation Matrix with Pandas and the Franke function
  • -
  • Rewriting the Covariance and/or Correlation Matrix
  • -
  • Linking with the SVD
  • -
  • What does it mean?
  • -
  • And finally \( \boldsymbol{X}\boldsymbol{X}^T \)
  • -
  • Ridge and LASSO Regression
  • -
  • Deriving the Ridge Regression Equations
  • -
  • Interpreting the Ridge results
  • -
  • More interpretations
  • -
  • Deriving the Lasso Regression Equations
  • -
  • Exercises for week 35
  • -
  • Exercise 1: Setting up various Python environments
  • -
  • Exercise 2: making your own data and exploring scikit-learn
  • -
  • Exercise 3: Normalizing our data
  • -
  • Exercise 4: Adding Ridge Regression
  • -
  • Exercise 5: Analytical exercises
  • +
  • Reducing the number of degrees of freedom, overarching view
  • +
  • Preprocessing our data
  • +
  • Functionality in Scikit-Learn
  • +
  • More preprocessing
  • +
  • Frequently used scaling functions
  • +
  • Example of own Standard scaling
  • +
  • Min-Max Scaling
  • +
  • Testing the Means Squared Error as function of Complexity
  • +
  • More preprocessing examples, two-dimensional example, the Franke function
  • +
  • To think about, first part
  • +
  • More thinking
  • +
  • Still thinking
  • +
  • What does centering (subtracting the mean values) mean mathematically?
  • +
  • Further Manipulations
  • +
  • Wrapping it up
  • +
  • Linear Regression code, Intercept handling first
  • +
  • The Boston housing data example
  • +
  • Housing data, the code
  • +
  • Material for lecture Thursday, August 31
  • +
  • Mathematical Interpretation of Ordinary Least Squares
  • +
  • Residual Error
  • +
  • Simple case
  • +
  • The singular value decomposition
  • +
  • Linear Regression Problems
  • +
  • Fixing the singularity
  • +
  • Basic math of the SVD
  • +
  • The SVD, a Fantastic Algorithm
  • +
  • Economy-size SVD
  • +
  • Codes for the SVD
  • +
  • Note about SVD Calculations
  • +
  • Mathematics of the SVD and implications
  • +
  • Example Matrix
  • +
  • Setting up the Matrix to be inverted
  • +
  • Further properties (important for our analyses later)
  • +
  • Meet the Covariance Matrix
  • +
  • Introducing the Covariance and Correlation functions
  • +
  • Covariance and Correlation Matrix
  • +
  • Correlation Function and Design/Feature Matrix
  • +
  • Covariance Matrix Examples
  • +
  • Correlation Matrix
  • +
  • Correlation Matrix with Pandas
  • +
  • Correlation Matrix with Pandas and the Franke function
  • +
  • Rewriting the Covariance and/or Correlation Matrix
  • +
  • Linking with the SVD
  • +
  • What does it mean?
  • +
  • And finally \( \boldsymbol{X}\boldsymbol{X}^T \)
  • +
  • Ridge and LASSO Regression
  • +
  • Deriving the Ridge Regression Equations
  • +
  • Interpreting the Ridge results
  • +
  • More interpretations
  • +
  • Deriving the Lasso Regression Equations
  • @@ -434,7 +435,7 @@ normally recommend using the latter functionality.
  • 31
  • 32
  • ...
  • -
  • 68
  • +
  • 74
  • »
  • diff --git a/doc/pub/week35/html/._week35-bs023.html b/doc/pub/week35/html/._week35-bs023.html index 56aa23081..5620d98e6 100644 --- a/doc/pub/week35/html/._week35-bs023.html +++ b/doc/pub/week35/html/._week35-bs023.html @@ -75,10 +75,10 @@ doconce format html week35.do.txt --html_style=bootstrap --pygments_html_style=d 2, None, 'interpretations-and-optimizing-our-parameters'), - ('Examples relevant for the exercises', + ('Example relevant for the exercises', 2, None, - 'examples-relevant-for-the-exercises'), + 'example-relevant-for-the-exercises'), ('Own code for Ordinary Least Squares', 2, None, @@ -91,16 +91,14 @@ doconce format html week35.do.txt --html_style=bootstrap --pygments_html_style=d 2, None, 'splitting-our-data-in-training-and-test-data'), - ('Examples', 2, None, 'examples'), + ('The complete code with a simple data set', + 2, + None, + 'the-complete-code-with-a-simple-data-set'), ('Making your own test-train splitting', 2, None, 'making-your-own-test-train-splitting'), - ('The Boston housing data example', - 2, - None, - 'the-boston-housing-data-example'), - ('Housing data, the code', 2, None, 'housing-data-the-code'), ('Reducing the number of degrees of freedom, overarching view', 2, None, @@ -124,10 +122,33 @@ doconce format html week35.do.txt --html_style=bootstrap --pygments_html_style=d 2, None, 'testing-the-means-squared-error-as-function-of-complexity'), - ('More preprocessing examples, Franke function and regression', + ('More preprocessing examples, two-dimensional example, the ' + 'Franke function', 2, None, - 'more-preprocessing-examples-franke-function-and-regression'), + 'more-preprocessing-examples-two-dimensional-example-the-franke-function'), + ('To think about, first part', + 2, + None, + 'to-think-about-first-part'), + ('More thinking', 2, None, 'more-thinking'), + ('Still thinking', 2, None, 'still-thinking'), + ('What does centering (subtracting the mean values) mean ' + 'mathematically?', + 2, + None, + 'what-does-centering-subtracting-the-mean-values-mean-mathematically'), + ('Further Manipulations', 2, None, 'further-manipulations'), + ('Wrapping it up', 2, None, 'wrapping-it-up'), + ('Linear Regression code, Intercept handling first', + 2, + None, + 'linear-regression-code-intercept-handling-first'), + ('The Boston housing data example', + 2, + None, + 'the-boston-housing-data-example'), + ('Housing data, the code', 2, None, 'housing-data-the-code'), ('Material for lecture Thursday, August 31', 2, None, @@ -226,28 +247,7 @@ doconce format html week35.do.txt --html_style=bootstrap --pygments_html_style=d ('Deriving the Lasso Regression Equations', 2, None, - 'deriving-the-lasso-regression-equations'), - ('Exercises for week 35', 2, None, 'exercises-for-week-35'), - ('Exercise 1: Setting up various Python environments', - 2, - None, - 'exercise-1-setting-up-various-python-environments'), - ('Exercise 2: making your own data and exploring scikit-learn', - 2, - None, - 'exercise-2-making-your-own-data-and-exploring-scikit-learn'), - ('Exercise 3: Normalizing our data', - 2, - None, - 'exercise-3-normalizing-our-data'), - ('Exercise 4: Adding Ridge Regression', - 2, - None, - 'exercise-4-adding-ridge-regression'), - ('Exercise 5: Analytical exercises', - 2, - None, - 'exercise-5-analytical-exercises')]} + 'deriving-the-lasso-regression-equations')]} end of tocinfo --> @@ -299,62 +299,63 @@ MathJax.Hub.Config({
  • Other useful relations
  • Meet the Hessian Matrix
  • Interpretations and optimizing our parameters
  • -
  • Examples relevant for the exercises
  • +
  • Example relevant for the exercises
  • Own code for Ordinary Least Squares
  • Adding error analysis and training set up
  • Splitting our Data in Training and Test data
  • -
  • Examples
  • +
  • The complete code with a simple data set
  • Making your own test-train splitting
  • -
  • The Boston housing data example
  • -
  • Housing data, the code
  • -
  • Reducing the number of degrees of freedom, overarching view
  • -
  • Preprocessing our data
  • -
  • Functionality in Scikit-Learn
  • -
  • More preprocessing
  • -
  • Frequently used scaling functions
  • -
  • Example of own Standard scaling
  • -
  • Min-Max Scaling
  • -
  • Testing the Means Squared Error as function of Complexity
  • -
  • More preprocessing examples, Franke function and regression
  • -
  • Material for lecture Thursday, August 31
  • -
  • Mathematical Interpretation of Ordinary Least Squares
  • -
  • Residual Error
  • -
  • Simple case
  • -
  • The singular value decomposition
  • -
  • Linear Regression Problems
  • -
  • Fixing the singularity
  • -
  • Basic math of the SVD
  • -
  • The SVD, a Fantastic Algorithm
  • -
  • Economy-size SVD
  • -
  • Codes for the SVD
  • -
  • Note about SVD Calculations
  • -
  • Mathematics of the SVD and implications
  • -
  • Example Matrix
  • -
  • Setting up the Matrix to be inverted
  • -
  • Further properties (important for our analyses later)
  • -
  • Meet the Covariance Matrix
  • -
  • Introducing the Covariance and Correlation functions
  • -
  • Covariance and Correlation Matrix
  • -
  • Correlation Function and Design/Feature Matrix
  • -
  • Covariance Matrix Examples
  • -
  • Correlation Matrix
  • -
  • Correlation Matrix with Pandas
  • -
  • Correlation Matrix with Pandas and the Franke function
  • -
  • Rewriting the Covariance and/or Correlation Matrix
  • -
  • Linking with the SVD
  • -
  • What does it mean?
  • -
  • And finally \( \boldsymbol{X}\boldsymbol{X}^T \)
  • -
  • Ridge and LASSO Regression
  • -
  • Deriving the Ridge Regression Equations
  • -
  • Interpreting the Ridge results
  • -
  • More interpretations
  • -
  • Deriving the Lasso Regression Equations
  • -
  • Exercises for week 35
  • -
  • Exercise 1: Setting up various Python environments
  • -
  • Exercise 2: making your own data and exploring scikit-learn
  • -
  • Exercise 3: Normalizing our data
  • -
  • Exercise 4: Adding Ridge Regression
  • -
  • Exercise 5: Analytical exercises
  • +
  • Reducing the number of degrees of freedom, overarching view
  • +
  • Preprocessing our data
  • +
  • Functionality in Scikit-Learn
  • +
  • More preprocessing
  • +
  • Frequently used scaling functions
  • +
  • Example of own Standard scaling
  • +
  • Min-Max Scaling
  • +
  • Testing the Means Squared Error as function of Complexity
  • +
  • More preprocessing examples, two-dimensional example, the Franke function
  • +
  • To think about, first part
  • +
  • More thinking
  • +
  • Still thinking
  • +
  • What does centering (subtracting the mean values) mean mathematically?
  • +
  • Further Manipulations
  • +
  • Wrapping it up
  • +
  • Linear Regression code, Intercept handling first
  • +
  • The Boston housing data example
  • +
  • Housing data, the code
  • +
  • Material for lecture Thursday, August 31
  • +
  • Mathematical Interpretation of Ordinary Least Squares
  • +
  • Residual Error
  • +
  • Simple case
  • +
  • The singular value decomposition
  • +
  • Linear Regression Problems
  • +
  • Fixing the singularity
  • +
  • Basic math of the SVD
  • +
  • The SVD, a Fantastic Algorithm
  • +
  • Economy-size SVD
  • +
  • Codes for the SVD
  • +
  • Note about SVD Calculations
  • +
  • Mathematics of the SVD and implications
  • +
  • Example Matrix
  • +
  • Setting up the Matrix to be inverted
  • +
  • Further properties (important for our analyses later)
  • +
  • Meet the Covariance Matrix
  • +
  • Introducing the Covariance and Correlation functions
  • +
  • Covariance and Correlation Matrix
  • +
  • Correlation Function and Design/Feature Matrix
  • +
  • Covariance Matrix Examples
  • +
  • Correlation Matrix
  • +
  • Correlation Matrix with Pandas
  • +
  • Correlation Matrix with Pandas and the Franke function
  • +
  • Rewriting the Covariance and/or Correlation Matrix
  • +
  • Linking with the SVD
  • +
  • What does it mean?
  • +
  • And finally \( \boldsymbol{X}\boldsymbol{X}^T \)
  • +
  • Ridge and LASSO Regression
  • +
  • Deriving the Ridge Regression Equations
  • +
  • Interpreting the Ridge results
  • +
  • More interpretations
  • +
  • Deriving the Lasso Regression Equations
  • @@ -365,33 +366,37 @@ MathJax.Hub.Config({

     

     

     

    - -

    The Boston housing data example

    + +

    Reducing the number of degrees of freedom, overarching view

    +
    +
    + -

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

    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.

    -

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

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

    +
    +
    + +

      @@ -417,7 +422,7 @@ the house using the features (predictors) listed here.
    • 32
    • 33
    • ...
    • -
    • 68
    • +
    • 74
    • »
    diff --git a/doc/pub/week35/html/._week35-bs024.html b/doc/pub/week35/html/._week35-bs024.html index 2423afd17..df002501b 100644 --- a/doc/pub/week35/html/._week35-bs024.html +++ b/doc/pub/week35/html/._week35-bs024.html @@ -75,10 +75,10 @@ doconce format html week35.do.txt --html_style=bootstrap --pygments_html_style=d 2, None, 'interpretations-and-optimizing-our-parameters'), - ('Examples relevant for the exercises', + ('Example relevant for the exercises', 2, None, - 'examples-relevant-for-the-exercises'), + 'example-relevant-for-the-exercises'), ('Own code for Ordinary Least Squares', 2, None, @@ -91,16 +91,14 @@ doconce format html week35.do.txt --html_style=bootstrap --pygments_html_style=d 2, None, 'splitting-our-data-in-training-and-test-data'), - ('Examples', 2, None, 'examples'), + ('The complete code with a simple data set', + 2, + None, + 'the-complete-code-with-a-simple-data-set'), ('Making your own test-train splitting', 2, None, 'making-your-own-test-train-splitting'), - ('The Boston housing data example', - 2, - None, - 'the-boston-housing-data-example'), - ('Housing data, the code', 2, None, 'housing-data-the-code'), ('Reducing the number of degrees of freedom, overarching view', 2, None, @@ -124,10 +122,33 @@ doconce format html week35.do.txt --html_style=bootstrap --pygments_html_style=d 2, None, 'testing-the-means-squared-error-as-function-of-complexity'), - ('More preprocessing examples, Franke function and regression', + ('More preprocessing examples, two-dimensional example, the ' + 'Franke function', 2, None, - 'more-preprocessing-examples-franke-function-and-regression'), + 'more-preprocessing-examples-two-dimensional-example-the-franke-function'), + ('To think about, first part', + 2, + None, + 'to-think-about-first-part'), + ('More thinking', 2, None, 'more-thinking'), + ('Still thinking', 2, None, 'still-thinking'), + ('What does centering (subtracting the mean values) mean ' + 'mathematically?', + 2, + None, + 'what-does-centering-subtracting-the-mean-values-mean-mathematically'), + ('Further Manipulations', 2, None, 'further-manipulations'), + ('Wrapping it up', 2, None, 'wrapping-it-up'), + ('Linear Regression code, Intercept handling first', + 2, + None, + 'linear-regression-code-intercept-handling-first'), + ('The Boston housing data example', + 2, + None, + 'the-boston-housing-data-example'), + ('Housing data, the code', 2, None, 'housing-data-the-code'), ('Material for lecture Thursday, August 31', 2, None, @@ -226,28 +247,7 @@ doconce format html week35.do.txt --html_style=bootstrap --pygments_html_style=d ('Deriving the Lasso Regression Equations', 2, None, - 'deriving-the-lasso-regression-equations'), - ('Exercises for week 35', 2, None, 'exercises-for-week-35'), - ('Exercise 1: Setting up various Python environments', - 2, - None, - 'exercise-1-setting-up-various-python-environments'), - ('Exercise 2: making your own data and exploring scikit-learn', - 2, - None, - 'exercise-2-making-your-own-data-and-exploring-scikit-learn'), - ('Exercise 3: Normalizing our data', - 2, - None, - 'exercise-3-normalizing-our-data'), - ('Exercise 4: Adding Ridge Regression', - 2, - None, - 'exercise-4-adding-ridge-regression'), - ('Exercise 5: Analytical exercises', - 2, - None, - 'exercise-5-analytical-exercises')]} + 'deriving-the-lasso-regression-equations')]} end of tocinfo --> @@ -299,62 +299,63 @@ MathJax.Hub.Config({
  • Other useful relations
  • Meet the Hessian Matrix
  • Interpretations and optimizing our parameters
  • -
  • Examples relevant for the exercises
  • +
  • Example relevant for the exercises
  • Own code for Ordinary Least Squares
  • Adding error analysis and training set up
  • Splitting our Data in Training and Test data
  • -
  • Examples
  • +
  • The complete code with a simple data set
  • Making your own test-train splitting
  • -
  • The Boston housing data example
  • -
  • Housing data, the code
  • -
  • Reducing the number of degrees of freedom, overarching view
  • -
  • Preprocessing our data
  • -
  • Functionality in Scikit-Learn
  • -
  • More preprocessing
  • -
  • Frequently used scaling functions
  • -
  • Example of own Standard scaling
  • -
  • Min-Max Scaling
  • -
  • Testing the Means Squared Error as function of Complexity
  • -
  • More preprocessing examples, Franke function and regression
  • -
  • Material for lecture Thursday, August 31
  • -
  • Mathematical Interpretation of Ordinary Least Squares
  • -
  • Residual Error
  • -
  • Simple case
  • -
  • The singular value decomposition
  • -
  • Linear Regression Problems
  • -
  • Fixing the singularity
  • -
  • Basic math of the SVD
  • -
  • The SVD, a Fantastic Algorithm
  • -
  • Economy-size SVD
  • -
  • Codes for the SVD
  • -
  • Note about SVD Calculations
  • -
  • Mathematics of the SVD and implications
  • -
  • Example Matrix
  • -
  • Setting up the Matrix to be inverted
  • -
  • Further properties (important for our analyses later)
  • -
  • Meet the Covariance Matrix
  • -
  • Introducing the Covariance and Correlation functions
  • -
  • Covariance and Correlation Matrix
  • -
  • Correlation Function and Design/Feature Matrix
  • -
  • Covariance Matrix Examples
  • -
  • Correlation Matrix
  • -
  • Correlation Matrix with Pandas
  • -
  • Correlation Matrix with Pandas and the Franke function
  • -
  • Rewriting the Covariance and/or Correlation Matrix
  • -
  • Linking with the SVD
  • -
  • What does it mean?
  • -
  • And finally \( \boldsymbol{X}\boldsymbol{X}^T \)
  • -
  • Ridge and LASSO Regression
  • -
  • Deriving the Ridge Regression Equations
  • -
  • Interpreting the Ridge results
  • -
  • More interpretations
  • -
  • Deriving the Lasso Regression Equations
  • -
  • Exercises for week 35
  • -
  • Exercise 1: Setting up various Python environments
  • -
  • Exercise 2: making your own data and exploring scikit-learn
  • -
  • Exercise 3: Normalizing our data
  • -
  • Exercise 4: Adding Ridge Regression
  • -
  • Exercise 5: Analytical exercises
  • +
  • Reducing the number of degrees of freedom, overarching view
  • +
  • Preprocessing our data
  • +
  • Functionality in Scikit-Learn
  • +
  • More preprocessing
  • +
  • Frequently used scaling functions
  • +
  • Example of own Standard scaling
  • +
  • Min-Max Scaling
  • +
  • Testing the Means Squared Error as function of Complexity
  • +
  • More preprocessing examples, two-dimensional example, the Franke function
  • +
  • To think about, first part
  • +
  • More thinking
  • +
  • Still thinking
  • +
  • What does centering (subtracting the mean values) mean mathematically?
  • +
  • Further Manipulations
  • +
  • Wrapping it up
  • +
  • Linear Regression code, Intercept handling first
  • +
  • The Boston housing data example
  • +
  • Housing data, the code
  • +
  • Material for lecture Thursday, August 31
  • +
  • Mathematical Interpretation of Ordinary Least Squares
  • +
  • Residual Error
  • +
  • Simple case
  • +
  • The singular value decomposition
  • +
  • Linear Regression Problems
  • +
  • Fixing the singularity
  • +
  • Basic math of the SVD
  • +
  • The SVD, a Fantastic Algorithm
  • +
  • Economy-size SVD
  • +
  • Codes for the SVD
  • +
  • Note about SVD Calculations
  • +
  • Mathematics of the SVD and implications
  • +
  • Example Matrix
  • +
  • Setting up the Matrix to be inverted
  • +
  • Further properties (important for our analyses later)
  • +
  • Meet the Covariance Matrix
  • +
  • Introducing the Covariance and Correlation functions
  • +
  • Covariance and Correlation Matrix
  • +
  • Correlation Function and Design/Feature Matrix
  • +
  • Covariance Matrix Examples
  • +
  • Correlation Matrix
  • +
  • Correlation Matrix with Pandas
  • +
  • Correlation Matrix with Pandas and the Franke function
  • +
  • Rewriting the Covariance and/or Correlation Matrix
  • +
  • Linking with the SVD
  • +
  • What does it mean?
  • +
  • And finally \( \boldsymbol{X}\boldsymbol{X}^T \)
  • +
  • Ridge and LASSO Regression
  • +
  • Deriving the Ridge Regression Equations
  • +
  • Interpreting the Ridge results
  • +
  • More interpretations
  • +
  • Deriving the Lasso Regression Equations
  • @@ -366,344 +367,28 @@ MathJax.Hub.Config({

     

     

     

    -

    Housing data, the code

    -

    We start by importing the libraries

    +

    Preprocessing our data

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

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

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

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

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

    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()
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    @@ -732,7 +417,7 @@ plt.show()
  • 33
  • 34
  • ...
  • -
  • 68
  • +
  • 74
  • »
  • diff --git a/doc/pub/week35/html/._week35-bs025.html b/doc/pub/week35/html/._week35-bs025.html index 19b5ffbf6..fc5d62398 100644 --- a/doc/pub/week35/html/._week35-bs025.html +++ b/doc/pub/week35/html/._week35-bs025.html @@ -75,10 +75,10 @@ doconce format html week35.do.txt --html_style=bootstrap --pygments_html_style=d 2, None, 'interpretations-and-optimizing-our-parameters'), - ('Examples relevant for the exercises', + ('Example relevant for the exercises', 2, None, - 'examples-relevant-for-the-exercises'), + 'example-relevant-for-the-exercises'), ('Own code for Ordinary Least Squares', 2, None, @@ -91,16 +91,14 @@ doconce format html week35.do.txt --html_style=bootstrap --pygments_html_style=d 2, None, 'splitting-our-data-in-training-and-test-data'), - ('Examples', 2, None, 'examples'), + ('The complete code with a simple data set', + 2, + None, + 'the-complete-code-with-a-simple-data-set'), ('Making your own test-train splitting', 2, None, 'making-your-own-test-train-splitting'), - ('The Boston housing data example', - 2, - None, - 'the-boston-housing-data-example'), - ('Housing data, the code', 2, None, 'housing-data-the-code'), ('Reducing the number of degrees of freedom, overarching view', 2, None, @@ -124,10 +122,33 @@ doconce format html week35.do.txt --html_style=bootstrap --pygments_html_style=d 2, None, 'testing-the-means-squared-error-as-function-of-complexity'), - ('More preprocessing examples, Franke function and regression', + ('More preprocessing examples, two-dimensional example, the ' + 'Franke function', 2, None, - 'more-preprocessing-examples-franke-function-and-regression'), + 'more-preprocessing-examples-two-dimensional-example-the-franke-function'), + ('To think about, first part', + 2, + None, + 'to-think-about-first-part'), + ('More thinking', 2, None, 'more-thinking'), + ('Still thinking', 2, None, 'still-thinking'), + ('What does centering (subtracting the mean values) mean ' + 'mathematically?', + 2, + None, + 'what-does-centering-subtracting-the-mean-values-mean-mathematically'), + ('Further Manipulations', 2, None, 'further-manipulations'), + ('Wrapping it up', 2, None, 'wrapping-it-up'), + ('Linear Regression code, Intercept handling first', + 2, + None, + 'linear-regression-code-intercept-handling-first'), + ('The Boston housing data example', + 2, + None, + 'the-boston-housing-data-example'), + ('Housing data, the code', 2, None, 'housing-data-the-code'), ('Material for lecture Thursday, August 31', 2, None, @@ -226,28 +247,7 @@ doconce format html week35.do.txt --html_style=bootstrap --pygments_html_style=d ('Deriving the Lasso Regression Equations', 2, None, - 'deriving-the-lasso-regression-equations'), - ('Exercises for week 35', 2, None, 'exercises-for-week-35'), - ('Exercise 1: Setting up various Python environments', - 2, - None, - 'exercise-1-setting-up-various-python-environments'), - ('Exercise 2: making your own data and exploring scikit-learn', - 2, - None, - 'exercise-2-making-your-own-data-and-exploring-scikit-learn'), - ('Exercise 3: Normalizing our data', - 2, - None, - 'exercise-3-normalizing-our-data'), - ('Exercise 4: Adding Ridge Regression', - 2, - None, - 'exercise-4-adding-ridge-regression'), - ('Exercise 5: Analytical exercises', - 2, - None, - 'exercise-5-analytical-exercises')]} + 'deriving-the-lasso-regression-equations')]} end of tocinfo --> @@ -299,62 +299,63 @@ MathJax.Hub.Config({
  • Other useful relations
  • Meet the Hessian Matrix
  • Interpretations and optimizing our parameters
  • -
  • Examples relevant for the exercises
  • +
  • Example relevant for the exercises
  • Own code for Ordinary Least Squares
  • Adding error analysis and training set up
  • Splitting our Data in Training and Test data
  • -
  • Examples
  • +
  • The complete code with a simple data set
  • Making your own test-train splitting
  • -
  • The Boston housing data example
  • -
  • Housing data, the code
  • -
  • Reducing the number of degrees of freedom, overarching view
  • -
  • Preprocessing our data
  • -
  • Functionality in Scikit-Learn
  • -
  • More preprocessing
  • -
  • Frequently used scaling functions
  • -
  • Example of own Standard scaling
  • -
  • Min-Max Scaling
  • -
  • Testing the Means Squared Error as function of Complexity
  • -
  • More preprocessing examples, Franke function and regression
  • -
  • Material for lecture Thursday, August 31
  • -
  • Mathematical Interpretation of Ordinary Least Squares
  • -
  • Residual Error
  • -
  • Simple case
  • -
  • The singular value decomposition
  • -
  • Linear Regression Problems
  • -
  • Fixing the singularity
  • -
  • Basic math of the SVD
  • -
  • The SVD, a Fantastic Algorithm
  • -
  • Economy-size SVD
  • -
  • Codes for the SVD
  • -
  • Note about SVD Calculations
  • -
  • Mathematics of the SVD and implications
  • -
  • Example Matrix
  • -
  • Setting up the Matrix to be inverted
  • -
  • Further properties (important for our analyses later)
  • -
  • Meet the Covariance Matrix
  • -
  • Introducing the Covariance and Correlation functions
  • -
  • Covariance and Correlation Matrix
  • -
  • Correlation Function and Design/Feature Matrix
  • -
  • Covariance Matrix Examples
  • -
  • Correlation Matrix
  • -
  • Correlation Matrix with Pandas
  • -
  • Correlation Matrix with Pandas and the Franke function
  • -
  • Rewriting the Covariance and/or Correlation Matrix
  • -
  • Linking with the SVD
  • -
  • What does it mean?
  • -
  • And finally \( \boldsymbol{X}\boldsymbol{X}^T \)
  • -
  • Ridge and LASSO Regression
  • -
  • Deriving the Ridge Regression Equations
  • -
  • Interpreting the Ridge results
  • -
  • More interpretations
  • -
  • Deriving the Lasso Regression Equations
  • -
  • Exercises for week 35
  • -
  • Exercise 1: Setting up various Python environments
  • -
  • Exercise 2: making your own data and exploring scikit-learn
  • -
  • Exercise 3: Normalizing our data
  • -
  • Exercise 4: Adding Ridge Regression
  • -
  • Exercise 5: Analytical exercises
  • +
  • Reducing the number of degrees of freedom, overarching view
  • +
  • Preprocessing our data
  • +
  • Functionality in Scikit-Learn
  • +
  • More preprocessing
  • +
  • Frequently used scaling functions
  • +
  • Example of own Standard scaling
  • +
  • Min-Max Scaling
  • +
  • Testing the Means Squared Error as function of Complexity
  • +
  • More preprocessing examples, two-dimensional example, the Franke function
  • +
  • To think about, first part
  • +
  • More thinking
  • +
  • Still thinking
  • +
  • What does centering (subtracting the mean values) mean mathematically?
  • +
  • Further Manipulations
  • +
  • Wrapping it up
  • +
  • Linear Regression code, Intercept handling first
  • +
  • The Boston housing data example
  • +
  • Housing data, the code
  • +
  • Material for lecture Thursday, August 31
  • +
  • Mathematical Interpretation of Ordinary Least Squares
  • +
  • Residual Error
  • +
  • Simple case
  • +
  • The singular value decomposition
  • +
  • Linear Regression Problems
  • +
  • Fixing the singularity
  • +
  • Basic math of the SVD
  • +
  • The SVD, a Fantastic Algorithm
  • +
  • Economy-size SVD
  • +
  • Codes for the SVD
  • +
  • Note about SVD Calculations
  • +
  • Mathematics of the SVD and implications
  • +
  • Example Matrix
  • +
  • Setting up the Matrix to be inverted
  • +
  • Further properties (important for our analyses later)
  • +
  • Meet the Covariance Matrix
  • +
  • Introducing the Covariance and Correlation functions
  • +
  • Covariance and Correlation Matrix
  • +
  • Correlation Function and Design/Feature Matrix
  • +
  • Covariance Matrix Examples
  • +
  • Correlation Matrix
  • +
  • Correlation Matrix with Pandas
  • +
  • Correlation Matrix with Pandas and the Franke function
  • +
  • Rewriting the Covariance and/or Correlation Matrix
  • +
  • Linking with the SVD
  • +
  • What does it mean?
  • +
  • And finally \( \boldsymbol{X}\boldsymbol{X}^T \)
  • +
  • Ridge and LASSO Regression
  • +
  • Deriving the Ridge Regression Equations
  • +
  • Interpreting the Ridge results
  • +
  • More interpretations
  • +
  • Deriving the Lasso Regression Equations
  • @@ -366,36 +367,19 @@ MathJax.Hub.Config({

     

     

     

    -

    Reducing the number of degrees of freedom, overarching view

    -
    -
    - +

    Functionality in Scikit-Learn

    -

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

    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

    -

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

    -
    -
    - -

    diff --git a/doc/pub/week35/html/._week35-bs026.html b/doc/pub/week35/html/._week35-bs026.html index 3e034d48b..5c1308a5e 100644 --- a/doc/pub/week35/html/._week35-bs026.html +++ b/doc/pub/week35/html/._week35-bs026.html @@ -75,10 +75,10 @@ doconce format html week35.do.txt --html_style=bootstrap --pygments_html_style=d 2, None, 'interpretations-and-optimizing-our-parameters'), - ('Examples relevant for the exercises', + ('Example relevant for the exercises', 2, None, - 'examples-relevant-for-the-exercises'), + 'example-relevant-for-the-exercises'), ('Own code for Ordinary Least Squares', 2, None, @@ -91,16 +91,14 @@ doconce format html week35.do.txt --html_style=bootstrap --pygments_html_style=d 2, None, 'splitting-our-data-in-training-and-test-data'), - ('Examples', 2, None, 'examples'), + ('The complete code with a simple data set', + 2, + None, + 'the-complete-code-with-a-simple-data-set'), ('Making your own test-train splitting', 2, None, 'making-your-own-test-train-splitting'), - ('The Boston housing data example', - 2, - None, - 'the-boston-housing-data-example'), - ('Housing data, the code', 2, None, 'housing-data-the-code'), ('Reducing the number of degrees of freedom, overarching view', 2, None, @@ -124,10 +122,33 @@ doconce format html week35.do.txt --html_style=bootstrap --pygments_html_style=d 2, None, 'testing-the-means-squared-error-as-function-of-complexity'), - ('More preprocessing examples, Franke function and regression', + ('More preprocessing examples, two-dimensional example, the ' + 'Franke function', 2, None, - 'more-preprocessing-examples-franke-function-and-regression'), + 'more-preprocessing-examples-two-dimensional-example-the-franke-function'), + ('To think about, first part', + 2, + None, + 'to-think-about-first-part'), + ('More thinking', 2, None, 'more-thinking'), + ('Still thinking', 2, None, 'still-thinking'), + ('What does centering (subtracting the mean values) mean ' + 'mathematically?', + 2, + None, + 'what-does-centering-subtracting-the-mean-values-mean-mathematically'), + ('Further Manipulations', 2, None, 'further-manipulations'), + ('Wrapping it up', 2, None, 'wrapping-it-up'), + ('Linear Regression code, Intercept handling first', + 2, + None, + 'linear-regression-code-intercept-handling-first'), + ('The Boston housing data example', + 2, + None, + 'the-boston-housing-data-example'), + ('Housing data, the code', 2, None, 'housing-data-the-code'), ('Material for lecture Thursday, August 31', 2, None, @@ -226,28 +247,7 @@ doconce format html week35.do.txt --html_style=bootstrap --pygments_html_style=d ('Deriving the Lasso Regression Equations', 2, None, - 'deriving-the-lasso-regression-equations'), - ('Exercises for week 35', 2, None, 'exercises-for-week-35'), - ('Exercise 1: Setting up various Python environments', - 2, - None, - 'exercise-1-setting-up-various-python-environments'), - ('Exercise 2: making your own data and exploring scikit-learn', - 2, - None, - 'exercise-2-making-your-own-data-and-exploring-scikit-learn'), - ('Exercise 3: Normalizing our data', - 2, - None, - 'exercise-3-normalizing-our-data'), - ('Exercise 4: Adding Ridge Regression', - 2, - None, - 'exercise-4-adding-ridge-regression'), - ('Exercise 5: Analytical exercises', - 2, - None, - 'exercise-5-analytical-exercises')]} + 'deriving-the-lasso-regression-equations')]} end of tocinfo --> @@ -299,62 +299,63 @@ MathJax.Hub.Config({
  • Other useful relations
  • Meet the Hessian Matrix
  • Interpretations and optimizing our parameters
  • -
  • Examples relevant for the exercises
  • +
  • Example relevant for the exercises
  • Own code for Ordinary Least Squares
  • Adding error analysis and training set up
  • Splitting our Data in Training and Test data
  • -
  • Examples
  • +
  • The complete code with a simple data set
  • Making your own test-train splitting
  • -
  • The Boston housing data example
  • -
  • Housing data, the code
  • -
  • Reducing the number of degrees of freedom, overarching view
  • -
  • Preprocessing our data
  • -
  • Functionality in Scikit-Learn
  • -
  • More preprocessing
  • -
  • Frequently used scaling functions
  • -
  • Example of own Standard scaling
  • -
  • Min-Max Scaling
  • -
  • Testing the Means Squared Error as function of Complexity
  • -
  • More preprocessing examples, Franke function and regression
  • -
  • Material for lecture Thursday, August 31
  • -
  • Mathematical Interpretation of Ordinary Least Squares
  • -
  • Residual Error
  • -
  • Simple case
  • -
  • The singular value decomposition
  • -
  • Linear Regression Problems
  • -
  • Fixing the singularity
  • -
  • Basic math of the SVD
  • -
  • The SVD, a Fantastic Algorithm
  • -
  • Economy-size SVD
  • -
  • Codes for the SVD
  • -
  • Note about SVD Calculations
  • -
  • Mathematics of the SVD and implications
  • -
  • Example Matrix
  • -
  • Setting up the Matrix to be inverted
  • -
  • Further properties (important for our analyses later)
  • -
  • Meet the Covariance Matrix
  • -
  • Introducing the Covariance and Correlation functions
  • -
  • Covariance and Correlation Matrix
  • -
  • Correlation Function and Design/Feature Matrix
  • -
  • Covariance Matrix Examples
  • -
  • Correlation Matrix
  • -
  • Correlation Matrix with Pandas
  • -
  • Correlation Matrix with Pandas and the Franke function
  • -
  • Rewriting the Covariance and/or Correlation Matrix
  • -
  • Linking with the SVD
  • -
  • What does it mean?
  • -
  • And finally \( \boldsymbol{X}\boldsymbol{X}^T \)
  • -
  • Ridge and LASSO Regression
  • -
  • Deriving the Ridge Regression Equations
  • -
  • Interpreting the Ridge results
  • -
  • More interpretations
  • -
  • Deriving the Lasso Regression Equations
  • -
  • Exercises for week 35
  • -
  • Exercise 1: Setting up various Python environments
  • -
  • Exercise 2: making your own data and exploring scikit-learn
  • -
  • Exercise 3: Normalizing our data
  • -
  • Exercise 4: Adding Ridge Regression
  • -
  • Exercise 5: Analytical exercises
  • +
  • Reducing the number of degrees of freedom, overarching view
  • +
  • Preprocessing our data
  • +
  • Functionality in Scikit-Learn
  • +
  • More preprocessing
  • +
  • Frequently used scaling functions
  • +
  • Example of own Standard scaling
  • +
  • Min-Max Scaling
  • +
  • Testing the Means Squared Error as function of Complexity
  • +
  • More preprocessing examples, two-dimensional example, the Franke function
  • +
  • To think about, first part
  • +
  • More thinking
  • +
  • Still thinking
  • +
  • What does centering (subtracting the mean values) mean mathematically?
  • +
  • Further Manipulations
  • +
  • Wrapping it up
  • +
  • Linear Regression code, Intercept handling first
  • +
  • The Boston housing data example
  • +
  • Housing data, the code
  • +
  • Material for lecture Thursday, August 31
  • +
  • Mathematical Interpretation of Ordinary Least Squares
  • +
  • Residual Error
  • +
  • Simple case
  • +
  • The singular value decomposition
  • +
  • Linear Regression Problems
  • +
  • Fixing the singularity
  • +
  • Basic math of the SVD
  • +
  • The SVD, a Fantastic Algorithm
  • +
  • Economy-size SVD
  • +
  • Codes for the SVD
  • +
  • Note about SVD Calculations
  • +
  • Mathematics of the SVD and implications
  • +
  • Example Matrix
  • +
  • Setting up the Matrix to be inverted
  • +
  • Further properties (important for our analyses later)
  • +
  • Meet the Covariance Matrix
  • +
  • Introducing the Covariance and Correlation functions
  • +
  • Covariance and Correlation Matrix
  • +
  • Correlation Function and Design/Feature Matrix
  • +
  • Covariance Matrix Examples
  • +
  • Correlation Matrix
  • +
  • Correlation Matrix with Pandas
  • +
  • Correlation Matrix with Pandas and the Franke function
  • +
  • Rewriting the Covariance and/or Correlation Matrix
  • +
  • Linking with the SVD
  • +
  • What does it mean?
  • +
  • And finally \( \boldsymbol{X}\boldsymbol{X}^T \)
  • +
  • Ridge and LASSO Regression
  • +
  • Deriving the Ridge Regression Equations
  • +
  • Interpreting the Ridge results
  • +
  • More interpretations
  • +
  • Deriving the Lasso Regression Equations
  • @@ -366,26 +367,28 @@ MathJax.Hub.Config({

     

     

     

    -

    Preprocessing our data

    +

    More preprocessing

    +
    - -

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

    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.

    -

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

    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.

    @@ -416,7 +419,7 @@ the features in a way to avoid such outlier values.
  • 35
  • 36
  • ...
  • -
  • 68
  • +
  • 74
  • »
  • diff --git a/doc/pub/week35/html/._week35-bs027.html b/doc/pub/week35/html/._week35-bs027.html index 4711c9f79..fe56477ea 100644 --- a/doc/pub/week35/html/._week35-bs027.html +++ b/doc/pub/week35/html/._week35-bs027.html @@ -75,10 +75,10 @@ doconce format html week35.do.txt --html_style=bootstrap --pygments_html_style=d 2, None, 'interpretations-and-optimizing-our-parameters'), - ('Examples relevant for the exercises', + ('Example relevant for the exercises', 2, None, - 'examples-relevant-for-the-exercises'), + 'example-relevant-for-the-exercises'), ('Own code for Ordinary Least Squares', 2, None, @@ -91,16 +91,14 @@ doconce format html week35.do.txt --html_style=bootstrap --pygments_html_style=d 2, None, 'splitting-our-data-in-training-and-test-data'), - ('Examples', 2, None, 'examples'), + ('The complete code with a simple data set', + 2, + None, + 'the-complete-code-with-a-simple-data-set'), ('Making your own test-train splitting', 2, None, 'making-your-own-test-train-splitting'), - ('The Boston housing data example', - 2, - None, - 'the-boston-housing-data-example'), - ('Housing data, the code', 2, None, 'housing-data-the-code'), ('Reducing the number of degrees of freedom, overarching view', 2, None, @@ -124,10 +122,33 @@ doconce format html week35.do.txt --html_style=bootstrap --pygments_html_style=d 2, None, 'testing-the-means-squared-error-as-function-of-complexity'), - ('More preprocessing examples, Franke function and regression', + ('More preprocessing examples, two-dimensional example, the ' + 'Franke function', 2, None, - 'more-preprocessing-examples-franke-function-and-regression'), + 'more-preprocessing-examples-two-dimensional-example-the-franke-function'), + ('To think about, first part', + 2, + None, + 'to-think-about-first-part'), + ('More thinking', 2, None, 'more-thinking'), + ('Still thinking', 2, None, 'still-thinking'), + ('What does centering (subtracting the mean values) mean ' + 'mathematically?', + 2, + None, + 'what-does-centering-subtracting-the-mean-values-mean-mathematically'), + ('Further Manipulations', 2, None, 'further-manipulations'), + ('Wrapping it up', 2, None, 'wrapping-it-up'), + ('Linear Regression code, Intercept handling first', + 2, + None, + 'linear-regression-code-intercept-handling-first'), + ('The Boston housing data example', + 2, + None, + 'the-boston-housing-data-example'), + ('Housing data, the code', 2, None, 'housing-data-the-code'), ('Material for lecture Thursday, August 31', 2, None, @@ -226,28 +247,7 @@ doconce format html week35.do.txt --html_style=bootstrap --pygments_html_style=d ('Deriving the Lasso Regression Equations', 2, None, - 'deriving-the-lasso-regression-equations'), - ('Exercises for week 35', 2, None, 'exercises-for-week-35'), - ('Exercise 1: Setting up various Python environments', - 2, - None, - 'exercise-1-setting-up-various-python-environments'), - ('Exercise 2: making your own data and exploring scikit-learn', - 2, - None, - 'exercise-2-making-your-own-data-and-exploring-scikit-learn'), - ('Exercise 3: Normalizing our data', - 2, - None, - 'exercise-3-normalizing-our-data'), - ('Exercise 4: Adding Ridge Regression', - 2, - None, - 'exercise-4-adding-ridge-regression'), - ('Exercise 5: Analytical exercises', - 2, - None, - 'exercise-5-analytical-exercises')]} + 'deriving-the-lasso-regression-equations')]} end of tocinfo --> @@ -299,62 +299,63 @@ MathJax.Hub.Config({
  • Other useful relations
  • Meet the Hessian Matrix
  • Interpretations and optimizing our parameters
  • -
  • Examples relevant for the exercises
  • +
  • Example relevant for the exercises
  • Own code for Ordinary Least Squares
  • Adding error analysis and training set up
  • Splitting our Data in Training and Test data
  • -
  • Examples
  • +
  • The complete code with a simple data set
  • Making your own test-train splitting
  • -
  • The Boston housing data example
  • -
  • Housing data, the code
  • -
  • Reducing the number of degrees of freedom, overarching view
  • -
  • Preprocessing our data
  • -
  • Functionality in Scikit-Learn
  • -
  • More preprocessing
  • -
  • Frequently used scaling functions
  • -
  • Example of own Standard scaling
  • -
  • Min-Max Scaling
  • -
  • Testing the Means Squared Error as function of Complexity
  • -
  • More preprocessing examples, Franke function and regression
  • -
  • Material for lecture Thursday, August 31
  • -
  • Mathematical Interpretation of Ordinary Least Squares
  • -
  • Residual Error
  • -
  • Simple case
  • -
  • The singular value decomposition
  • -
  • Linear Regression Problems
  • -
  • Fixing the singularity
  • -
  • Basic math of the SVD
  • -
  • The SVD, a Fantastic Algorithm
  • -
  • Economy-size SVD
  • -
  • Codes for the SVD
  • -
  • Note about SVD Calculations
  • -
  • Mathematics of the SVD and implications
  • -
  • Example Matrix
  • -
  • Setting up the Matrix to be inverted
  • -
  • Further properties (important for our analyses later)
  • -
  • Meet the Covariance Matrix
  • -
  • Introducing the Covariance and Correlation functions
  • -
  • Covariance and Correlation Matrix
  • -
  • Correlation Function and Design/Feature Matrix
  • -
  • Covariance Matrix Examples
  • -
  • Correlation Matrix
  • -
  • Correlation Matrix with Pandas
  • -
  • Correlation Matrix with Pandas and the Franke function
  • -
  • Rewriting the Covariance and/or Correlation Matrix
  • -
  • Linking with the SVD
  • -
  • What does it mean?
  • -
  • And finally \( \boldsymbol{X}\boldsymbol{X}^T \)
  • -
  • Ridge and LASSO Regression
  • -
  • Deriving the Ridge Regression Equations
  • -
  • Interpreting the Ridge results
  • -
  • More interpretations
  • -
  • Deriving the Lasso Regression Equations
  • -
  • Exercises for week 35
  • -
  • Exercise 1: Setting up various Python environments
  • -
  • Exercise 2: making your own data and exploring scikit-learn
  • -
  • Exercise 3: Normalizing our data
  • -
  • Exercise 4: Adding Ridge Regression
  • -
  • Exercise 5: Analytical exercises
  • +
  • Reducing the number of degrees of freedom, overarching view
  • +
  • Preprocessing our data
  • +
  • Functionality in Scikit-Learn
  • +
  • More preprocessing
  • +
  • Frequently used scaling functions
  • +
  • Example of own Standard scaling
  • +
  • Min-Max Scaling
  • +
  • Testing the Means Squared Error as function of Complexity
  • +
  • More preprocessing examples, two-dimensional example, the Franke function
  • +
  • To think about, first part
  • +
  • More thinking
  • +
  • Still thinking
  • +
  • What does centering (subtracting the mean values) mean mathematically?
  • +
  • Further Manipulations
  • +
  • Wrapping it up
  • +
  • Linear Regression code, Intercept handling first
  • +
  • The Boston housing data example
  • +
  • Housing data, the code
  • +
  • Material for lecture Thursday, August 31
  • +
  • Mathematical Interpretation of Ordinary Least Squares
  • +
  • Residual Error
  • +
  • Simple case
  • +
  • The singular value decomposition
  • +
  • Linear Regression Problems
  • +
  • Fixing the singularity
  • +
  • Basic math of the SVD
  • +
  • The SVD, a Fantastic Algorithm
  • +
  • Economy-size SVD
  • +
  • Codes for the SVD
  • +
  • Note about SVD Calculations
  • +
  • Mathematics of the SVD and implications
  • +
  • Example Matrix
  • +
  • Setting up the Matrix to be inverted
  • +
  • Further properties (important for our analyses later)
  • +
  • Meet the Covariance Matrix
  • +
  • Introducing the Covariance and Correlation functions
  • +
  • Covariance and Correlation Matrix
  • +
  • Correlation Function and Design/Feature Matrix
  • +
  • Covariance Matrix Examples
  • +
  • Correlation Matrix
  • +
  • Correlation Matrix with Pandas
  • +
  • Correlation Matrix with Pandas and the Franke function
  • +
  • Rewriting the Covariance and/or Correlation Matrix
  • +
  • Linking with the SVD
  • +
  • What does it mean?
  • +
  • And finally \( \boldsymbol{X}\boldsymbol{X}^T \)
  • +
  • Ridge and LASSO Regression
  • +
  • Deriving the Ridge Regression Equations
  • +
  • Interpreting the Ridge results
  • +
  • More interpretations
  • +
  • Deriving the Lasso Regression Equations
  • @@ -366,17 +367,18 @@ MathJax.Hub.Config({

     

     

     

    -

    Functionality in Scikit-Learn

    +

    Frequently used scaling functions

    -

    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 +

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

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

    @@ -404,7 +406,7 @@ ensures that all features are exactly between \( 0 \) and \( 1 \). The

  • 36
  • 37
  • ...
  • -
  • 68
  • +
  • 74
  • »
  • diff --git a/doc/pub/week35/html/._week35-bs028.html b/doc/pub/week35/html/._week35-bs028.html index f1108dc60..2c50f39f7 100644 --- a/doc/pub/week35/html/._week35-bs028.html +++ b/doc/pub/week35/html/._week35-bs028.html @@ -75,10 +75,10 @@ doconce format html week35.do.txt --html_style=bootstrap --pygments_html_style=d 2, None, 'interpretations-and-optimizing-our-parameters'), - ('Examples relevant for the exercises', + ('Example relevant for the exercises', 2, None, - 'examples-relevant-for-the-exercises'), + 'example-relevant-for-the-exercises'), ('Own code for Ordinary Least Squares', 2, None, @@ -91,16 +91,14 @@ doconce format html week35.do.txt --html_style=bootstrap --pygments_html_style=d 2, None, 'splitting-our-data-in-training-and-test-data'), - ('Examples', 2, None, 'examples'), + ('The complete code with a simple data set', + 2, + None, + 'the-complete-code-with-a-simple-data-set'), ('Making your own test-train splitting', 2, None, 'making-your-own-test-train-splitting'), - ('The Boston housing data example', - 2, - None, - 'the-boston-housing-data-example'), - ('Housing data, the code', 2, None, 'housing-data-the-code'), ('Reducing the number of degrees of freedom, overarching view', 2, None, @@ -124,10 +122,33 @@ doconce format html week35.do.txt --html_style=bootstrap --pygments_html_style=d 2, None, 'testing-the-means-squared-error-as-function-of-complexity'), - ('More preprocessing examples, Franke function and regression', + ('More preprocessing examples, two-dimensional example, the ' + 'Franke function', 2, None, - 'more-preprocessing-examples-franke-function-and-regression'), + 'more-preprocessing-examples-two-dimensional-example-the-franke-function'), + ('To think about, first part', + 2, + None, + 'to-think-about-first-part'), + ('More thinking', 2, None, 'more-thinking'), + ('Still thinking', 2, None, 'still-thinking'), + ('What does centering (subtracting the mean values) mean ' + 'mathematically?', + 2, + None, + 'what-does-centering-subtracting-the-mean-values-mean-mathematically'), + ('Further Manipulations', 2, None, 'further-manipulations'), + ('Wrapping it up', 2, None, 'wrapping-it-up'), + ('Linear Regression code, Intercept handling first', + 2, + None, + 'linear-regression-code-intercept-handling-first'), + ('The Boston housing data example', + 2, + None, + 'the-boston-housing-data-example'), + ('Housing data, the code', 2, None, 'housing-data-the-code'), ('Material for lecture Thursday, August 31', 2, None, @@ -226,28 +247,7 @@ doconce format html week35.do.txt --html_style=bootstrap --pygments_html_style=d ('Deriving the Lasso Regression Equations', 2, None, - 'deriving-the-lasso-regression-equations'), - ('Exercises for week 35', 2, None, 'exercises-for-week-35'), - ('Exercise 1: Setting up various Python environments', - 2, - None, - 'exercise-1-setting-up-various-python-environments'), - ('Exercise 2: making your own data and exploring scikit-learn', - 2, - None, - 'exercise-2-making-your-own-data-and-exploring-scikit-learn'), - ('Exercise 3: Normalizing our data', - 2, - None, - 'exercise-3-normalizing-our-data'), - ('Exercise 4: Adding Ridge Regression', - 2, - None, - 'exercise-4-adding-ridge-regression'), - ('Exercise 5: Analytical exercises', - 2, - None, - 'exercise-5-analytical-exercises')]} + 'deriving-the-lasso-regression-equations')]} end of tocinfo --> @@ -299,62 +299,63 @@ MathJax.Hub.Config({
  • Other useful relations
  • Meet the Hessian Matrix
  • Interpretations and optimizing our parameters
  • -
  • Examples relevant for the exercises
  • +
  • Example relevant for the exercises
  • Own code for Ordinary Least Squares
  • Adding error analysis and training set up
  • Splitting our Data in Training and Test data
  • -
  • Examples
  • +
  • The complete code with a simple data set
  • Making your own test-train splitting
  • -
  • The Boston housing data example
  • -
  • Housing data, the code
  • -
  • Reducing the number of degrees of freedom, overarching view
  • -
  • Preprocessing our data
  • -
  • Functionality in Scikit-Learn
  • -
  • More preprocessing
  • -
  • Frequently used scaling functions
  • -
  • Example of own Standard scaling
  • -
  • Min-Max Scaling
  • -
  • Testing the Means Squared Error as function of Complexity
  • -
  • More preprocessing examples, Franke function and regression
  • -
  • Material for lecture Thursday, August 31
  • -
  • Mathematical Interpretation of Ordinary Least Squares
  • -
  • Residual Error
  • -
  • Simple case
  • -
  • The singular value decomposition
  • -
  • Linear Regression Problems
  • -
  • Fixing the singularity
  • -
  • Basic math of the SVD
  • -
  • The SVD, a Fantastic Algorithm
  • -
  • Economy-size SVD
  • -
  • Codes for the SVD
  • -
  • Note about SVD Calculations
  • -
  • Mathematics of the SVD and implications
  • -
  • Example Matrix
  • -
  • Setting up the Matrix to be inverted
  • -
  • Further properties (important for our analyses later)
  • -
  • Meet the Covariance Matrix
  • -
  • Introducing the Covariance and Correlation functions
  • -
  • Covariance and Correlation Matrix
  • -
  • Correlation Function and Design/Feature Matrix
  • -
  • Covariance Matrix Examples
  • -
  • Correlation Matrix
  • -
  • Correlation Matrix with Pandas
  • -
  • Correlation Matrix with Pandas and the Franke function
  • -
  • Rewriting the Covariance and/or Correlation Matrix
  • -
  • Linking with the SVD
  • -
  • What does it mean?
  • -
  • And finally \( \boldsymbol{X}\boldsymbol{X}^T \)
  • -
  • Ridge and LASSO Regression
  • -
  • Deriving the Ridge Regression Equations
  • -
  • Interpreting the Ridge results
  • -
  • More interpretations
  • -
  • Deriving the Lasso Regression Equations
  • -
  • Exercises for week 35
  • -
  • Exercise 1: Setting up various Python environments
  • -
  • Exercise 2: making your own data and exploring scikit-learn
  • -
  • Exercise 3: Normalizing our data
  • -
  • Exercise 4: Adding Ridge Regression
  • -
  • Exercise 5: Analytical exercises
  • +
  • Reducing the number of degrees of freedom, overarching view
  • +
  • Preprocessing our data
  • +
  • Functionality in Scikit-Learn
  • +
  • More preprocessing
  • +
  • Frequently used scaling functions
  • +
  • Example of own Standard scaling
  • +
  • Min-Max Scaling
  • +
  • Testing the Means Squared Error as function of Complexity
  • +
  • More preprocessing examples, two-dimensional example, the Franke function
  • +
  • To think about, first part
  • +
  • More thinking
  • +
  • Still thinking
  • +
  • What does centering (subtracting the mean values) mean mathematically?
  • +
  • Further Manipulations
  • +
  • Wrapping it up
  • +
  • Linear Regression code, Intercept handling first
  • +
  • The Boston housing data example
  • +
  • Housing data, the code
  • +
  • Material for lecture Thursday, August 31
  • +
  • Mathematical Interpretation of Ordinary Least Squares
  • +
  • Residual Error
  • +
  • Simple case
  • +
  • The singular value decomposition
  • +
  • Linear Regression Problems
  • +
  • Fixing the singularity
  • +
  • Basic math of the SVD
  • +
  • The SVD, a Fantastic Algorithm
  • +
  • Economy-size SVD
  • +
  • Codes for the SVD
  • +
  • Note about SVD Calculations
  • +
  • Mathematics of the SVD and implications
  • +
  • Example Matrix
  • +
  • Setting up the Matrix to be inverted
  • +
  • Further properties (important for our analyses later)
  • +
  • Meet the Covariance Matrix
  • +
  • Introducing the Covariance and Correlation functions
  • +
  • Covariance and Correlation Matrix
  • +
  • Correlation Function and Design/Feature Matrix
  • +
  • Covariance Matrix Examples
  • +
  • Correlation Matrix
  • +
  • Correlation Matrix with Pandas
  • +
  • Correlation Matrix with Pandas and the Franke function
  • +
  • Rewriting the Covariance and/or Correlation Matrix
  • +
  • Linking with the SVD
  • +
  • What does it mean?
  • +
  • And finally \( \boldsymbol{X}\boldsymbol{X}^T \)
  • +
  • Ridge and LASSO Regression
  • +
  • Deriving the Ridge Regression Equations
  • +
  • Interpreting the Ridge results
  • +
  • More interpretations
  • +
  • Deriving the Lasso Regression Equations
  • @@ -366,32 +367,60 @@ MathJax.Hub.Config({

     

     

     

    -

    More preprocessing

    +

    Example of own Standard scaling

    -
    -
    - -

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

    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.

    -

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

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

    @@ -418,7 +447,7 @@ techniques.

  • 37
  • 38
  • ...
  • -
  • 68
  • +
  • 74
  • »
  • diff --git a/doc/pub/week35/html/._week35-bs029.html b/doc/pub/week35/html/._week35-bs029.html index 80e1f4282..8696c38c8 100644 --- a/doc/pub/week35/html/._week35-bs029.html +++ b/doc/pub/week35/html/._week35-bs029.html @@ -75,10 +75,10 @@ doconce format html week35.do.txt --html_style=bootstrap --pygments_html_style=d 2, None, 'interpretations-and-optimizing-our-parameters'), - ('Examples relevant for the exercises', + ('Example relevant for the exercises', 2, None, - 'examples-relevant-for-the-exercises'), + 'example-relevant-for-the-exercises'), ('Own code for Ordinary Least Squares', 2, None, @@ -91,16 +91,14 @@ doconce format html week35.do.txt --html_style=bootstrap --pygments_html_style=d 2, None, 'splitting-our-data-in-training-and-test-data'), - ('Examples', 2, None, 'examples'), + ('The complete code with a simple data set', + 2, + None, + 'the-complete-code-with-a-simple-data-set'), ('Making your own test-train splitting', 2, None, 'making-your-own-test-train-splitting'), - ('The Boston housing data example', - 2, - None, - 'the-boston-housing-data-example'), - ('Housing data, the code', 2, None, 'housing-data-the-code'), ('Reducing the number of degrees of freedom, overarching view', 2, None, @@ -124,10 +122,33 @@ doconce format html week35.do.txt --html_style=bootstrap --pygments_html_style=d 2, None, 'testing-the-means-squared-error-as-function-of-complexity'), - ('More preprocessing examples, Franke function and regression', + ('More preprocessing examples, two-dimensional example, the ' + 'Franke function', 2, None, - 'more-preprocessing-examples-franke-function-and-regression'), + 'more-preprocessing-examples-two-dimensional-example-the-franke-function'), + ('To think about, first part', + 2, + None, + 'to-think-about-first-part'), + ('More thinking', 2, None, 'more-thinking'), + ('Still thinking', 2, None, 'still-thinking'), + ('What does centering (subtracting the mean values) mean ' + 'mathematically?', + 2, + None, + 'what-does-centering-subtracting-the-mean-values-mean-mathematically'), + ('Further Manipulations', 2, None, 'further-manipulations'), + ('Wrapping it up', 2, None, 'wrapping-it-up'), + ('Linear Regression code, Intercept handling first', + 2, + None, + 'linear-regression-code-intercept-handling-first'), + ('The Boston housing data example', + 2, + None, + 'the-boston-housing-data-example'), + ('Housing data, the code', 2, None, 'housing-data-the-code'), ('Material for lecture Thursday, August 31', 2, None, @@ -226,28 +247,7 @@ doconce format html week35.do.txt --html_style=bootstrap --pygments_html_style=d ('Deriving the Lasso Regression Equations', 2, None, - 'deriving-the-lasso-regression-equations'), - ('Exercises for week 35', 2, None, 'exercises-for-week-35'), - ('Exercise 1: Setting up various Python environments', - 2, - None, - 'exercise-1-setting-up-various-python-environments'), - ('Exercise 2: making your own data and exploring scikit-learn', - 2, - None, - 'exercise-2-making-your-own-data-and-exploring-scikit-learn'), - ('Exercise 3: Normalizing our data', - 2, - None, - 'exercise-3-normalizing-our-data'), - ('Exercise 4: Adding Ridge Regression', - 2, - None, - 'exercise-4-adding-ridge-regression'), - ('Exercise 5: Analytical exercises', - 2, - None, - 'exercise-5-analytical-exercises')]} + 'deriving-the-lasso-regression-equations')]} end of tocinfo --> @@ -299,62 +299,63 @@ MathJax.Hub.Config({
  • Other useful relations
  • Meet the Hessian Matrix
  • Interpretations and optimizing our parameters
  • -
  • Examples relevant for the exercises
  • +
  • Example relevant for the exercises
  • Own code for Ordinary Least Squares
  • Adding error analysis and training set up
  • Splitting our Data in Training and Test data
  • -
  • Examples
  • +
  • The complete code with a simple data set
  • Making your own test-train splitting
  • -
  • The Boston housing data example
  • -
  • Housing data, the code
  • -
  • Reducing the number of degrees of freedom, overarching view
  • -
  • Preprocessing our data
  • -
  • Functionality in Scikit-Learn
  • -
  • More preprocessing
  • -
  • Frequently used scaling functions
  • -
  • Example of own Standard scaling
  • -
  • Min-Max Scaling
  • -
  • Testing the Means Squared Error as function of Complexity
  • -
  • More preprocessing examples, Franke function and regression
  • -
  • Material for lecture Thursday, August 31
  • -
  • Mathematical Interpretation of Ordinary Least Squares
  • -
  • Residual Error
  • -
  • Simple case
  • -
  • The singular value decomposition
  • -
  • Linear Regression Problems
  • -
  • Fixing the singularity
  • -
  • Basic math of the SVD
  • -
  • The SVD, a Fantastic Algorithm
  • -
  • Economy-size SVD
  • -
  • Codes for the SVD
  • -
  • Note about SVD Calculations
  • -
  • Mathematics of the SVD and implications
  • -
  • Example Matrix
  • -
  • Setting up the Matrix to be inverted
  • -
  • Further properties (important for our analyses later)
  • -
  • Meet the Covariance Matrix
  • -
  • Introducing the Covariance and Correlation functions
  • -
  • Covariance and Correlation Matrix
  • -
  • Correlation Function and Design/Feature Matrix
  • -
  • Covariance Matrix Examples
  • -
  • Correlation Matrix
  • -
  • Correlation Matrix with Pandas
  • -
  • Correlation Matrix with Pandas and the Franke function
  • -
  • Rewriting the Covariance and/or Correlation Matrix
  • -
  • Linking with the SVD
  • -
  • What does it mean?
  • -
  • And finally \( \boldsymbol{X}\boldsymbol{X}^T \)
  • -
  • Ridge and LASSO Regression
  • -
  • Deriving the Ridge Regression Equations
  • -
  • Interpreting the Ridge results
  • -
  • More interpretations
  • -
  • Deriving the Lasso Regression Equations
  • -
  • Exercises for week 35
  • -
  • Exercise 1: Setting up various Python environments
  • -
  • Exercise 2: making your own data and exploring scikit-learn
  • -
  • Exercise 3: Normalizing our data
  • -
  • Exercise 4: Adding Ridge Regression
  • -
  • Exercise 5: Analytical exercises
  • +
  • Reducing the number of degrees of freedom, overarching view
  • +
  • Preprocessing our data
  • +
  • Functionality in Scikit-Learn
  • +
  • More preprocessing
  • +
  • Frequently used scaling functions
  • +
  • Example of own Standard scaling
  • +
  • Min-Max Scaling
  • +
  • Testing the Means Squared Error as function of Complexity
  • +
  • More preprocessing examples, two-dimensional example, the Franke function
  • +
  • To think about, first part
  • +
  • More thinking
  • +
  • Still thinking
  • +
  • What does centering (subtracting the mean values) mean mathematically?
  • +
  • Further Manipulations
  • +
  • Wrapping it up
  • +
  • Linear Regression code, Intercept handling first
  • +
  • The Boston housing data example
  • +
  • Housing data, the code
  • +
  • Material for lecture Thursday, August 31
  • +
  • Mathematical Interpretation of Ordinary Least Squares
  • +
  • Residual Error
  • +
  • Simple case
  • +
  • The singular value decomposition
  • +
  • Linear Regression Problems
  • +
  • Fixing the singularity
  • +
  • Basic math of the SVD
  • +
  • The SVD, a Fantastic Algorithm
  • +
  • Economy-size SVD
  • +
  • Codes for the SVD
  • +
  • Note about SVD Calculations
  • +
  • Mathematics of the SVD and implications
  • +
  • Example Matrix
  • +
  • Setting up the Matrix to be inverted
  • +
  • Further properties (important for our analyses later)
  • +
  • Meet the Covariance Matrix
  • +
  • Introducing the Covariance and Correlation functions
  • +
  • Covariance and Correlation Matrix
  • +
  • Correlation Function and Design/Feature Matrix
  • +
  • Covariance Matrix Examples
  • +
  • Correlation Matrix
  • +
  • Correlation Matrix with Pandas
  • +
  • Correlation Matrix with Pandas and the Franke function
  • +
  • Rewriting the Covariance and/or Correlation Matrix
  • +
  • Linking with the SVD
  • +
  • What does it mean?
  • +
  • And finally \( \boldsymbol{X}\boldsymbol{X}^T \)
  • +
  • Ridge and LASSO Regression
  • +
  • Deriving the Ridge Regression Equations
  • +
  • Interpreting the Ridge results
  • +
  • More interpretations
  • +
  • Deriving the Lasso Regression Equations
  • @@ -366,19 +367,19 @@ MathJax.Hub.Config({

     

     

     

    -

    Frequently used scaling functions

    +

    Min-Max 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: +

    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 \frac{x_j^{(i)} - \overline{x}_j}{\sigma(x_j)}, +x_j^{(i)} \rightarrow (b-a)\frac{x_j^{(i)} - \min(x_j)}{\max(x_j) - \min(x_j)} - a $$ -

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

    +

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

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

  • 38
  • 39
  • ...
  • -
  • 68
  • +
  • 74
  • »
  • diff --git a/doc/pub/week35/html/._week35-bs030.html b/doc/pub/week35/html/._week35-bs030.html index e40ded03d..dbb6e01da 100644 --- a/doc/pub/week35/html/._week35-bs030.html +++ b/doc/pub/week35/html/._week35-bs030.html @@ -75,10 +75,10 @@ doconce format html week35.do.txt --html_style=bootstrap --pygments_html_style=d 2, None, 'interpretations-and-optimizing-our-parameters'), - ('Examples relevant for the exercises', + ('Example relevant for the exercises', 2, None, - 'examples-relevant-for-the-exercises'), + 'example-relevant-for-the-exercises'), ('Own code for Ordinary Least Squares', 2, None, @@ -91,16 +91,14 @@ doconce format html week35.do.txt --html_style=bootstrap --pygments_html_style=d 2, None, 'splitting-our-data-in-training-and-test-data'), - ('Examples', 2, None, 'examples'), + ('The complete code with a simple data set', + 2, + None, + 'the-complete-code-with-a-simple-data-set'), ('Making your own test-train splitting', 2, None, 'making-your-own-test-train-splitting'), - ('The Boston housing data example', - 2, - None, - 'the-boston-housing-data-example'), - ('Housing data, the code', 2, None, 'housing-data-the-code'), ('Reducing the number of degrees of freedom, overarching view', 2, None, @@ -124,10 +122,33 @@ doconce format html week35.do.txt --html_style=bootstrap --pygments_html_style=d 2, None, 'testing-the-means-squared-error-as-function-of-complexity'), - ('More preprocessing examples, Franke function and regression', + ('More preprocessing examples, two-dimensional example, the ' + 'Franke function', 2, None, - 'more-preprocessing-examples-franke-function-and-regression'), + 'more-preprocessing-examples-two-dimensional-example-the-franke-function'), + ('To think about, first part', + 2, + None, + 'to-think-about-first-part'), + ('More thinking', 2, None, 'more-thinking'), + ('Still thinking', 2, None, 'still-thinking'), + ('What does centering (subtracting the mean values) mean ' + 'mathematically?', + 2, + None, + 'what-does-centering-subtracting-the-mean-values-mean-mathematically'), + ('Further Manipulations', 2, None, 'further-manipulations'), + ('Wrapping it up', 2, None, 'wrapping-it-up'), + ('Linear Regression code, Intercept handling first', + 2, + None, + 'linear-regression-code-intercept-handling-first'), + ('The Boston housing data example', + 2, + None, + 'the-boston-housing-data-example'), + ('Housing data, the code', 2, None, 'housing-data-the-code'), ('Material for lecture Thursday, August 31', 2, None, @@ -226,28 +247,7 @@ doconce format html week35.do.txt --html_style=bootstrap --pygments_html_style=d ('Deriving the Lasso Regression Equations', 2, None, - 'deriving-the-lasso-regression-equations'), - ('Exercises for week 35', 2, None, 'exercises-for-week-35'), - ('Exercise 1: Setting up various Python environments', - 2, - None, - 'exercise-1-setting-up-various-python-environments'), - ('Exercise 2: making your own data and exploring scikit-learn', - 2, - None, - 'exercise-2-making-your-own-data-and-exploring-scikit-learn'), - ('Exercise 3: Normalizing our data', - 2, - None, - 'exercise-3-normalizing-our-data'), - ('Exercise 4: Adding Ridge Regression', - 2, - None, - 'exercise-4-adding-ridge-regression'), - ('Exercise 5: Analytical exercises', - 2, - None, - 'exercise-5-analytical-exercises')]} + 'deriving-the-lasso-regression-equations')]} end of tocinfo --> @@ -299,62 +299,63 @@ MathJax.Hub.Config({
  • Other useful relations
  • Meet the Hessian Matrix
  • Interpretations and optimizing our parameters
  • -
  • Examples relevant for the exercises
  • +
  • Example relevant for the exercises
  • Own code for Ordinary Least Squares
  • Adding error analysis and training set up
  • Splitting our Data in Training and Test data
  • -
  • Examples
  • +
  • The complete code with a simple data set
  • Making your own test-train splitting
  • -
  • The Boston housing data example
  • -
  • Housing data, the code
  • -
  • Reducing the number of degrees of freedom, overarching view
  • -
  • Preprocessing our data
  • -
  • Functionality in Scikit-Learn
  • -
  • More preprocessing
  • -
  • Frequently used scaling functions
  • -
  • Example of own Standard scaling
  • -
  • Min-Max Scaling
  • -
  • Testing the Means Squared Error as function of Complexity
  • -
  • More preprocessing examples, Franke function and regression
  • -
  • Material for lecture Thursday, August 31
  • -
  • Mathematical Interpretation of Ordinary Least Squares
  • -
  • Residual Error
  • -
  • Simple case
  • -
  • The singular value decomposition
  • -
  • Linear Regression Problems
  • -
  • Fixing the singularity
  • -
  • Basic math of the SVD
  • -
  • The SVD, a Fantastic Algorithm
  • -
  • Economy-size SVD
  • -
  • Codes for the SVD
  • -
  • Note about SVD Calculations
  • -
  • Mathematics of the SVD and implications
  • -
  • Example Matrix
  • -
  • Setting up the Matrix to be inverted
  • -
  • Further properties (important for our analyses later)
  • -
  • Meet the Covariance Matrix
  • -
  • Introducing the Covariance and Correlation functions
  • -
  • Covariance and Correlation Matrix
  • -
  • Correlation Function and Design/Feature Matrix
  • -
  • Covariance Matrix Examples
  • -
  • Correlation Matrix
  • -
  • Correlation Matrix with Pandas
  • -
  • Correlation Matrix with Pandas and the Franke function
  • -
  • Rewriting the Covariance and/or Correlation Matrix
  • -
  • Linking with the SVD
  • -
  • What does it mean?
  • -
  • And finally \( \boldsymbol{X}\boldsymbol{X}^T \)
  • -
  • Ridge and LASSO Regression
  • -
  • Deriving the Ridge Regression Equations
  • -
  • Interpreting the Ridge results
  • -
  • More interpretations
  • -
  • Deriving the Lasso Regression Equations
  • -
  • Exercises for week 35
  • -
  • Exercise 1: Setting up various Python environments
  • -
  • Exercise 2: making your own data and exploring scikit-learn
  • -
  • Exercise 3: Normalizing our data
  • -
  • Exercise 4: Adding Ridge Regression
  • -
  • Exercise 5: Analytical exercises
  • +
  • Reducing the number of degrees of freedom, overarching view
  • +
  • Preprocessing our data
  • +
  • Functionality in Scikit-Learn
  • +
  • More preprocessing
  • +
  • Frequently used scaling functions
  • +
  • Example of own Standard scaling
  • +
  • Min-Max Scaling
  • +
  • Testing the Means Squared Error as function of Complexity
  • +
  • More preprocessing examples, two-dimensional example, the Franke function
  • +
  • To think about, first part
  • +
  • More thinking
  • +
  • Still thinking
  • +
  • What does centering (subtracting the mean values) mean mathematically?
  • +
  • Further Manipulations
  • +
  • Wrapping it up
  • +
  • Linear Regression code, Intercept handling first
  • +
  • The Boston housing data example
  • +
  • Housing data, the code
  • +
  • Material for lecture Thursday, August 31
  • +
  • Mathematical Interpretation of Ordinary Least Squares
  • +
  • Residual Error
  • +
  • Simple case
  • +
  • The singular value decomposition
  • +
  • Linear Regression Problems
  • +
  • Fixing the singularity
  • +
  • Basic math of the SVD
  • +
  • The SVD, a Fantastic Algorithm
  • +
  • Economy-size SVD
  • +
  • Codes for the SVD
  • +
  • Note about SVD Calculations
  • +
  • Mathematics of the SVD and implications
  • +
  • Example Matrix
  • +
  • Setting up the Matrix to be inverted
  • +
  • Further properties (important for our analyses later)
  • +
  • Meet the Covariance Matrix
  • +
  • Introducing the Covariance and Correlation functions
  • +
  • Covariance and Correlation Matrix
  • +
  • Correlation Function and Design/Feature Matrix
  • +
  • Covariance Matrix Examples
  • +
  • Correlation Matrix
  • +
  • Correlation Matrix with Pandas
  • +
  • Correlation Matrix with Pandas and the Franke function
  • +
  • Rewriting the Covariance and/or Correlation Matrix
  • +
  • Linking with the SVD
  • +
  • What does it mean?
  • +
  • And finally \( \boldsymbol{X}\boldsymbol{X}^T \)
  • +
  • Ridge and LASSO Regression
  • +
  • Deriving the Ridge Regression Equations
  • +
  • Interpreting the Ridge results
  • +
  • More interpretations
  • +
  • Deriving the Lasso Regression Equations
  • @@ -366,14 +367,13 @@ MathJax.Hub.Config({

     

     

     

    -

    Example of own Standard scaling

    +

    Testing the Means Squared Error as function of Complexity

    -

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

    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.

    @@ -381,29 +381,73 @@ represent a specific feature whose mean value is subracted.
    -
    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)
    +  
    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 fourth-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
    +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()
     
    @@ -419,7 +463,6 @@ display(XPandas-Xscaled)
    -

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

    @@ -446,7 +489,7 @@ display(XPandas-Xscaled)

  • 39
  • 40
  • ...
  • -
  • 68
  • +
  • 74
  • »
  • diff --git a/doc/pub/week35/html/._week35-bs031.html b/doc/pub/week35/html/._week35-bs031.html index 4936686af..34b84a9e5 100644 --- a/doc/pub/week35/html/._week35-bs031.html +++ b/doc/pub/week35/html/._week35-bs031.html @@ -75,10 +75,10 @@ doconce format html week35.do.txt --html_style=bootstrap --pygments_html_style=d 2, None, 'interpretations-and-optimizing-our-parameters'), - ('Examples relevant for the exercises', + ('Example relevant for the exercises', 2, None, - 'examples-relevant-for-the-exercises'), + 'example-relevant-for-the-exercises'), ('Own code for Ordinary Least Squares', 2, None, @@ -91,16 +91,14 @@ doconce format html week35.do.txt --html_style=bootstrap --pygments_html_style=d 2, None, 'splitting-our-data-in-training-and-test-data'), - ('Examples', 2, None, 'examples'), + ('The complete code with a simple data set', + 2, + None, + 'the-complete-code-with-a-simple-data-set'), ('Making your own test-train splitting', 2, None, 'making-your-own-test-train-splitting'), - ('The Boston housing data example', - 2, - None, - 'the-boston-housing-data-example'), - ('Housing data, the code', 2, None, 'housing-data-the-code'), ('Reducing the number of degrees of freedom, overarching view', 2, None, @@ -124,10 +122,33 @@ doconce format html week35.do.txt --html_style=bootstrap --pygments_html_style=d 2, None, 'testing-the-means-squared-error-as-function-of-complexity'), - ('More preprocessing examples, Franke function and regression', + ('More preprocessing examples, two-dimensional example, the ' + 'Franke function', 2, None, - 'more-preprocessing-examples-franke-function-and-regression'), + 'more-preprocessing-examples-two-dimensional-example-the-franke-function'), + ('To think about, first part', + 2, + None, + 'to-think-about-first-part'), + ('More thinking', 2, None, 'more-thinking'), + ('Still thinking', 2, None, 'still-thinking'), + ('What does centering (subtracting the mean values) mean ' + 'mathematically?', + 2, + None, + 'what-does-centering-subtracting-the-mean-values-mean-mathematically'), + ('Further Manipulations', 2, None, 'further-manipulations'), + ('Wrapping it up', 2, None, 'wrapping-it-up'), + ('Linear Regression code, Intercept handling first', + 2, + None, + 'linear-regression-code-intercept-handling-first'), + ('The Boston housing data example', + 2, + None, + 'the-boston-housing-data-example'), + ('Housing data, the code', 2, None, 'housing-data-the-code'), ('Material for lecture Thursday, August 31', 2, None, @@ -226,28 +247,7 @@ doconce format html week35.do.txt --html_style=bootstrap --pygments_html_style=d ('Deriving the Lasso Regression Equations', 2, None, - 'deriving-the-lasso-regression-equations'), - ('Exercises for week 35', 2, None, 'exercises-for-week-35'), - ('Exercise 1: Setting up various Python environments', - 2, - None, - 'exercise-1-setting-up-various-python-environments'), - ('Exercise 2: making your own data and exploring scikit-learn', - 2, - None, - 'exercise-2-making-your-own-data-and-exploring-scikit-learn'), - ('Exercise 3: Normalizing our data', - 2, - None, - 'exercise-3-normalizing-our-data'), - ('Exercise 4: Adding Ridge Regression', - 2, - None, - 'exercise-4-adding-ridge-regression'), - ('Exercise 5: Analytical exercises', - 2, - None, - 'exercise-5-analytical-exercises')]} + 'deriving-the-lasso-regression-equations')]} end of tocinfo --> @@ -299,62 +299,63 @@ MathJax.Hub.Config({
  • Other useful relations
  • Meet the Hessian Matrix
  • Interpretations and optimizing our parameters
  • -
  • Examples relevant for the exercises
  • +
  • Example relevant for the exercises
  • Own code for Ordinary Least Squares
  • Adding error analysis and training set up
  • Splitting our Data in Training and Test data
  • -
  • Examples
  • +
  • The complete code with a simple data set
  • Making your own test-train splitting
  • -
  • The Boston housing data example
  • -
  • Housing data, the code
  • -
  • Reducing the number of degrees of freedom, overarching view
  • -
  • Preprocessing our data
  • -
  • Functionality in Scikit-Learn
  • -
  • More preprocessing
  • -
  • Frequently used scaling functions
  • -
  • Example of own Standard scaling
  • -
  • Min-Max Scaling
  • -
  • Testing the Means Squared Error as function of Complexity
  • -
  • More preprocessing examples, Franke function and regression
  • -
  • Material for lecture Thursday, August 31
  • -
  • Mathematical Interpretation of Ordinary Least Squares
  • -
  • Residual Error
  • -
  • Simple case
  • -
  • The singular value decomposition
  • -
  • Linear Regression Problems
  • -
  • Fixing the singularity
  • -
  • Basic math of the SVD
  • -
  • The SVD, a Fantastic Algorithm
  • -
  • Economy-size SVD
  • -
  • Codes for the SVD
  • -
  • Note about SVD Calculations
  • -
  • Mathematics of the SVD and implications
  • -
  • Example Matrix
  • -
  • Setting up the Matrix to be inverted
  • -
  • Further properties (important for our analyses later)
  • -
  • Meet the Covariance Matrix
  • -
  • Introducing the Covariance and Correlation functions
  • -
  • Covariance and Correlation Matrix
  • -
  • Correlation Function and Design/Feature Matrix
  • -
  • Covariance Matrix Examples
  • -
  • Correlation Matrix
  • -
  • Correlation Matrix with Pandas
  • -
  • Correlation Matrix with Pandas and the Franke function
  • -
  • Rewriting the Covariance and/or Correlation Matrix
  • -
  • Linking with the SVD
  • -
  • What does it mean?
  • -
  • And finally \( \boldsymbol{X}\boldsymbol{X}^T \)
  • -
  • Ridge and LASSO Regression
  • -
  • Deriving the Ridge Regression Equations
  • -
  • Interpreting the Ridge results
  • -
  • More interpretations
  • -
  • Deriving the Lasso Regression Equations
  • -
  • Exercises for week 35
  • -
  • Exercise 1: Setting up various Python environments
  • -
  • Exercise 2: making your own data and exploring scikit-learn
  • -
  • Exercise 3: Normalizing our data
  • -
  • Exercise 4: Adding Ridge Regression
  • -
  • Exercise 5: Analytical exercises
  • +
  • Reducing the number of degrees of freedom, overarching view
  • +
  • Preprocessing our data
  • +
  • Functionality in Scikit-Learn
  • +
  • More preprocessing
  • +
  • Frequently used scaling functions
  • +
  • Example of own Standard scaling
  • +
  • Min-Max Scaling
  • +
  • Testing the Means Squared Error as function of Complexity
  • +
  • More preprocessing examples, two-dimensional example, the Franke function
  • +
  • To think about, first part
  • +
  • More thinking
  • +
  • Still thinking
  • +
  • What does centering (subtracting the mean values) mean mathematically?
  • +
  • Further Manipulations
  • +
  • Wrapping it up
  • +
  • Linear Regression code, Intercept handling first
  • +
  • The Boston housing data example
  • +
  • Housing data, the code
  • +
  • Material for lecture Thursday, August 31
  • +
  • Mathematical Interpretation of Ordinary Least Squares
  • +
  • Residual Error
  • +
  • Simple case
  • +
  • The singular value decomposition
  • +
  • Linear Regression Problems
  • +
  • Fixing the singularity
  • +
  • Basic math of the SVD
  • +
  • The SVD, a Fantastic Algorithm
  • +
  • Economy-size SVD
  • +
  • Codes for the SVD
  • +
  • Note about SVD Calculations
  • +
  • Mathematics of the SVD and implications
  • +
  • Example Matrix
  • +
  • Setting up the Matrix to be inverted
  • +
  • Further properties (important for our analyses later)
  • +
  • Meet the Covariance Matrix
  • +
  • Introducing the Covariance and Correlation functions
  • +
  • Covariance and Correlation Matrix
  • +
  • Correlation Function and Design/Feature Matrix
  • +
  • Covariance Matrix Examples
  • +
  • Correlation Matrix
  • +
  • Correlation Matrix with Pandas
  • +
  • Correlation Matrix with Pandas and the Franke function
  • +
  • Rewriting the Covariance and/or Correlation Matrix
  • +
  • Linking with the SVD
  • +
  • What does it mean?
  • +
  • And finally \( \boldsymbol{X}\boldsymbol{X}^T \)
  • +
  • Ridge and LASSO Regression
  • +
  • Deriving the Ridge Regression Equations
  • +
  • Interpreting the Ridge results
  • +
  • More interpretations
  • +
  • Deriving the Lasso Regression Equations
  • @@ -366,19 +367,122 @@ MathJax.Hub.Config({

     

     

     

    -

    Min-Max Scaling

    +

    More preprocessing examples, two-dimensional example, the Franke function

    -

    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 -$$ + +
    +
    +
    +
    +
    +
    # 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
    +
    +# Where to save the figures and data files
    +PROJECT_ROOT_DIR = "Results"
    +FIGURE_ID = "Results/FigureFiles"
    +DATA_ID = "DataFiles/"
    +
    +if not os.path.exists(PROJECT_ROOT_DIR):
    +    os.mkdir(PROJECT_ROOT_DIR)
    +
    +if not os.path.exists(FIGURE_ID):
    +    os.makedirs(FIGURE_ID)
    +
    +if not os.path.exists(DATA_ID):
    +    os.makedirs(DATA_ID)
    +
    +def image_path(fig_id):
    +    return os.path.join(FIGURE_ID, fig_id)
    +
    +def data_path(dat_id):
    +    return os.path.join(DATA_ID, dat_id)
    +
    +def save_fig(fig_id):
    +    plt.savefig(image_path(fig_id) + ".png", format='png')
    +
    +
    +def 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)))
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    -

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

    @@ -405,7 +509,7 @@ $$

  • 40
  • 41
  • ...
  • -
  • 68
  • +
  • 74
  • »
  • diff --git a/doc/pub/week35/html/._week35-bs032.html b/doc/pub/week35/html/._week35-bs032.html index 121b0961f..e3d2755a2 100644 --- a/doc/pub/week35/html/._week35-bs032.html +++ b/doc/pub/week35/html/._week35-bs032.html @@ -75,10 +75,10 @@ doconce format html week35.do.txt --html_style=bootstrap --pygments_html_style=d 2, None, 'interpretations-and-optimizing-our-parameters'), - ('Examples relevant for the exercises', + ('Example relevant for the exercises', 2, None, - 'examples-relevant-for-the-exercises'), + 'example-relevant-for-the-exercises'), ('Own code for Ordinary Least Squares', 2, None, @@ -91,16 +91,14 @@ doconce format html week35.do.txt --html_style=bootstrap --pygments_html_style=d 2, None, 'splitting-our-data-in-training-and-test-data'), - ('Examples', 2, None, 'examples'), + ('The complete code with a simple data set', + 2, + None, + 'the-complete-code-with-a-simple-data-set'), ('Making your own test-train splitting', 2, None, 'making-your-own-test-train-splitting'), - ('The Boston housing data example', - 2, - None, - 'the-boston-housing-data-example'), - ('Housing data, the code', 2, None, 'housing-data-the-code'), ('Reducing the number of degrees of freedom, overarching view', 2, None, @@ -124,10 +122,33 @@ doconce format html week35.do.txt --html_style=bootstrap --pygments_html_style=d 2, None, 'testing-the-means-squared-error-as-function-of-complexity'), - ('More preprocessing examples, Franke function and regression', + ('More preprocessing examples, two-dimensional example, the ' + 'Franke function', 2, None, - 'more-preprocessing-examples-franke-function-and-regression'), + 'more-preprocessing-examples-two-dimensional-example-the-franke-function'), + ('To think about, first part', + 2, + None, + 'to-think-about-first-part'), + ('More thinking', 2, None, 'more-thinking'), + ('Still thinking', 2, None, 'still-thinking'), + ('What does centering (subtracting the mean values) mean ' + 'mathematically?', + 2, + None, + 'what-does-centering-subtracting-the-mean-values-mean-mathematically'), + ('Further Manipulations', 2, None, 'further-manipulations'), + ('Wrapping it up', 2, None, 'wrapping-it-up'), + ('Linear Regression code, Intercept handling first', + 2, + None, + 'linear-regression-code-intercept-handling-first'), + ('The Boston housing data example', + 2, + None, + 'the-boston-housing-data-example'), + ('Housing data, the code', 2, None, 'housing-data-the-code'), ('Material for lecture Thursday, August 31', 2, None, @@ -226,28 +247,7 @@ doconce format html week35.do.txt --html_style=bootstrap --pygments_html_style=d ('Deriving the Lasso Regression Equations', 2, None, - 'deriving-the-lasso-regression-equations'), - ('Exercises for week 35', 2, None, 'exercises-for-week-35'), - ('Exercise 1: Setting up various Python environments', - 2, - None, - 'exercise-1-setting-up-various-python-environments'), - ('Exercise 2: making your own data and exploring scikit-learn', - 2, - None, - 'exercise-2-making-your-own-data-and-exploring-scikit-learn'), - ('Exercise 3: Normalizing our data', - 2, - None, - 'exercise-3-normalizing-our-data'), - ('Exercise 4: Adding Ridge Regression', - 2, - None, - 'exercise-4-adding-ridge-regression'), - ('Exercise 5: Analytical exercises', - 2, - None, - 'exercise-5-analytical-exercises')]} + 'deriving-the-lasso-regression-equations')]} end of tocinfo --> @@ -299,62 +299,63 @@ MathJax.Hub.Config({
  • Other useful relations
  • Meet the Hessian Matrix
  • Interpretations and optimizing our parameters
  • -
  • Examples relevant for the exercises
  • +
  • Example relevant for the exercises
  • Own code for Ordinary Least Squares
  • Adding error analysis and training set up
  • Splitting our Data in Training and Test data
  • -
  • Examples
  • +
  • The complete code with a simple data set
  • Making your own test-train splitting
  • -
  • The Boston housing data example
  • -
  • Housing data, the code
  • -
  • Reducing the number of degrees of freedom, overarching view
  • -
  • Preprocessing our data
  • -
  • Functionality in Scikit-Learn
  • -
  • More preprocessing
  • -
  • Frequently used scaling functions
  • -
  • Example of own Standard scaling
  • -
  • Min-Max Scaling
  • -
  • Testing the Means Squared Error as function of Complexity
  • -
  • More preprocessing examples, Franke function and regression
  • -
  • Material for lecture Thursday, August 31
  • -
  • Mathematical Interpretation of Ordinary Least Squares
  • -
  • Residual Error
  • -
  • Simple case
  • -
  • The singular value decomposition
  • -
  • Linear Regression Problems
  • -
  • Fixing the singularity
  • -
  • Basic math of the SVD
  • -
  • The SVD, a Fantastic Algorithm
  • -
  • Economy-size SVD
  • -
  • Codes for the SVD
  • -
  • Note about SVD Calculations
  • -
  • Mathematics of the SVD and implications
  • -
  • Example Matrix
  • -
  • Setting up the Matrix to be inverted
  • -
  • Further properties (important for our analyses later)
  • -
  • Meet the Covariance Matrix
  • -
  • Introducing the Covariance and Correlation functions
  • -
  • Covariance and Correlation Matrix
  • -
  • Correlation Function and Design/Feature Matrix
  • -
  • Covariance Matrix Examples
  • -
  • Correlation Matrix
  • -
  • Correlation Matrix with Pandas
  • -
  • Correlation Matrix with Pandas and the Franke function
  • -
  • Rewriting the Covariance and/or Correlation Matrix
  • -
  • Linking with the SVD
  • -
  • What does it mean?
  • -
  • And finally \( \boldsymbol{X}\boldsymbol{X}^T \)
  • -
  • Ridge and LASSO Regression
  • -
  • Deriving the Ridge Regression Equations
  • -
  • Interpreting the Ridge results
  • -
  • More interpretations
  • -
  • Deriving the Lasso Regression Equations
  • -
  • Exercises for week 35
  • -
  • Exercise 1: Setting up various Python environments
  • -
  • Exercise 2: making your own data and exploring scikit-learn
  • -
  • Exercise 3: Normalizing our data
  • -
  • Exercise 4: Adding Ridge Regression
  • -
  • Exercise 5: Analytical exercises
  • +
  • Reducing the number of degrees of freedom, overarching view
  • +
  • Preprocessing our data
  • +
  • Functionality in Scikit-Learn
  • +
  • More preprocessing
  • +
  • Frequently used scaling functions
  • +
  • Example of own Standard scaling
  • +
  • Min-Max Scaling
  • +
  • Testing the Means Squared Error as function of Complexity
  • +
  • More preprocessing examples, two-dimensional example, the Franke function
  • +
  • To think about, first part
  • +
  • More thinking
  • +
  • Still thinking
  • +
  • What does centering (subtracting the mean values) mean mathematically?
  • +
  • Further Manipulations
  • +
  • Wrapping it up
  • +
  • Linear Regression code, Intercept handling first
  • +
  • The Boston housing data example
  • +
  • Housing data, the code
  • +
  • Material for lecture Thursday, August 31
  • +
  • Mathematical Interpretation of Ordinary Least Squares
  • +
  • Residual Error
  • +
  • Simple case
  • +
  • The singular value decomposition
  • +
  • Linear Regression Problems
  • +
  • Fixing the singularity
  • +
  • Basic math of the SVD
  • +
  • The SVD, a Fantastic Algorithm
  • +
  • Economy-size SVD
  • +
  • Codes for the SVD
  • +
  • Note about SVD Calculations
  • +
  • Mathematics of the SVD and implications
  • +
  • Example Matrix
  • +
  • Setting up the Matrix to be inverted
  • +
  • Further properties (important for our analyses later)
  • +
  • Meet the Covariance Matrix
  • +
  • Introducing the Covariance and Correlation functions
  • +
  • Covariance and Correlation Matrix
  • +
  • Correlation Function and Design/Feature Matrix
  • +
  • Covariance Matrix Examples
  • +
  • Correlation Matrix
  • +
  • Correlation Matrix with Pandas
  • +
  • Correlation Matrix with Pandas and the Franke function
  • +
  • Rewriting the Covariance and/or Correlation Matrix
  • +
  • Linking with the SVD
  • +
  • What does it mean?
  • +
  • And finally \( \boldsymbol{X}\boldsymbol{X}^T \)
  • +
  • Ridge and LASSO Regression
  • +
  • Deriving the Ridge Regression Equations
  • +
  • Interpreting the Ridge results
  • +
  • More interpretations
  • +
  • Deriving the Lasso Regression Equations
  • @@ -366,102 +367,28 @@ 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. +

    To think about, first part

    + +

    When you are comparing your own code with for example Scikit-Learn's +library, there are some technicalities to keep in mind. The examples +here demonstrate some of these aspects with potential pitfalls.

    -

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

    The discussion here focuses on the role of the intercept, how we can +set up the design matrix, what scaling we should use and other topics +which tend confuse us. +

    +

    The intercept can be interpreted as the expected value of our +target/output variables when all other predictors are set to zero. +Thus, if we cannot assume that the expected outputs/targets are zero +when all predictors are zero (the columns in the design matrix), it +may be a bad idea to implement a model which penalizes the intercept. +Furthermore, in for example Ridge and Lasso regression, the default solutions +from the library Scikit-Learn (when not shrinking \( \beta_0 \)) for the unknown parameters +\( \boldsymbol{\beta} \), are derived under the assumption that both \( \boldsymbol{y} \) and +\( \boldsymbol{X} \) are zero centered, that is we subtract the mean values. +

    @@ -488,7 +415,7 @@ plt.show()

  • 41
  • 42
  • ...
  • -
  • 68
  • +
  • 74
  • »
  • diff --git a/doc/pub/week35/html/._week35-bs033.html b/doc/pub/week35/html/._week35-bs033.html index 6f1e8cabe..e2db58e5c 100644 --- a/doc/pub/week35/html/._week35-bs033.html +++ b/doc/pub/week35/html/._week35-bs033.html @@ -75,10 +75,10 @@ doconce format html week35.do.txt --html_style=bootstrap --pygments_html_style=d 2, None, 'interpretations-and-optimizing-our-parameters'), - ('Examples relevant for the exercises', + ('Example relevant for the exercises', 2, None, - 'examples-relevant-for-the-exercises'), + 'example-relevant-for-the-exercises'), ('Own code for Ordinary Least Squares', 2, None, @@ -91,16 +91,14 @@ doconce format html week35.do.txt --html_style=bootstrap --pygments_html_style=d 2, None, 'splitting-our-data-in-training-and-test-data'), - ('Examples', 2, None, 'examples'), + ('The complete code with a simple data set', + 2, + None, + 'the-complete-code-with-a-simple-data-set'), ('Making your own test-train splitting', 2, None, 'making-your-own-test-train-splitting'), - ('The Boston housing data example', - 2, - None, - 'the-boston-housing-data-example'), - ('Housing data, the code', 2, None, 'housing-data-the-code'), ('Reducing the number of degrees of freedom, overarching view', 2, None, @@ -124,10 +122,33 @@ doconce format html week35.do.txt --html_style=bootstrap --pygments_html_style=d 2, None, 'testing-the-means-squared-error-as-function-of-complexity'), - ('More preprocessing examples, Franke function and regression', + ('More preprocessing examples, two-dimensional example, the ' + 'Franke function', 2, None, - 'more-preprocessing-examples-franke-function-and-regression'), + 'more-preprocessing-examples-two-dimensional-example-the-franke-function'), + ('To think about, first part', + 2, + None, + 'to-think-about-first-part'), + ('More thinking', 2, None, 'more-thinking'), + ('Still thinking', 2, None, 'still-thinking'), + ('What does centering (subtracting the mean values) mean ' + 'mathematically?', + 2, + None, + 'what-does-centering-subtracting-the-mean-values-mean-mathematically'), + ('Further Manipulations', 2, None, 'further-manipulations'), + ('Wrapping it up', 2, None, 'wrapping-it-up'), + ('Linear Regression code, Intercept handling first', + 2, + None, + 'linear-regression-code-intercept-handling-first'), + ('The Boston housing data example', + 2, + None, + 'the-boston-housing-data-example'), + ('Housing data, the code', 2, None, 'housing-data-the-code'), ('Material for lecture Thursday, August 31', 2, None, @@ -226,28 +247,7 @@ doconce format html week35.do.txt --html_style=bootstrap --pygments_html_style=d ('Deriving the Lasso Regression Equations', 2, None, - 'deriving-the-lasso-regression-equations'), - ('Exercises for week 35', 2, None, 'exercises-for-week-35'), - ('Exercise 1: Setting up various Python environments', - 2, - None, - 'exercise-1-setting-up-various-python-environments'), - ('Exercise 2: making your own data and exploring scikit-learn', - 2, - None, - 'exercise-2-making-your-own-data-and-exploring-scikit-learn'), - ('Exercise 3: Normalizing our data', - 2, - None, - 'exercise-3-normalizing-our-data'), - ('Exercise 4: Adding Ridge Regression', - 2, - None, - 'exercise-4-adding-ridge-regression'), - ('Exercise 5: Analytical exercises', - 2, - None, - 'exercise-5-analytical-exercises')]} + 'deriving-the-lasso-regression-equations')]} end of tocinfo --> @@ -299,62 +299,63 @@ MathJax.Hub.Config({
  • Other useful relations
  • Meet the Hessian Matrix
  • Interpretations and optimizing our parameters
  • -
  • Examples relevant for the exercises
  • +
  • Example relevant for the exercises
  • Own code for Ordinary Least Squares
  • Adding error analysis and training set up
  • Splitting our Data in Training and Test data
  • -
  • Examples
  • +
  • The complete code with a simple data set
  • Making your own test-train splitting
  • -
  • The Boston housing data example
  • -
  • Housing data, the code
  • -
  • Reducing the number of degrees of freedom, overarching view
  • -
  • Preprocessing our data
  • -
  • Functionality in Scikit-Learn
  • -
  • More preprocessing
  • -
  • Frequently used scaling functions
  • -
  • Example of own Standard scaling
  • -
  • Min-Max Scaling
  • -
  • Testing the Means Squared Error as function of Complexity
  • -
  • More preprocessing examples, Franke function and regression
  • -
  • Material for lecture Thursday, August 31
  • -
  • Mathematical Interpretation of Ordinary Least Squares
  • -
  • Residual Error
  • -
  • Simple case
  • -
  • The singular value decomposition
  • -
  • Linear Regression Problems
  • -
  • Fixing the singularity
  • -
  • Basic math of the SVD
  • -
  • The SVD, a Fantastic Algorithm
  • -
  • Economy-size SVD
  • -
  • Codes for the SVD
  • -
  • Note about SVD Calculations
  • -
  • Mathematics of the SVD and implications
  • -
  • Example Matrix
  • -
  • Setting up the Matrix to be inverted
  • -
  • Further properties (important for our analyses later)
  • -
  • Meet the Covariance Matrix
  • -
  • Introducing the Covariance and Correlation functions
  • -
  • Covariance and Correlation Matrix
  • -
  • Correlation Function and Design/Feature Matrix
  • -
  • Covariance Matrix Examples
  • -
  • Correlation Matrix
  • -
  • Correlation Matrix with Pandas
  • -
  • Correlation Matrix with Pandas and the Franke function
  • -
  • Rewriting the Covariance and/or Correlation Matrix
  • -
  • Linking with the SVD
  • -
  • What does it mean?
  • -
  • And finally \( \boldsymbol{X}\boldsymbol{X}^T \)
  • -
  • Ridge and LASSO Regression
  • -
  • Deriving the Ridge Regression Equations
  • -
  • Interpreting the Ridge results
  • -
  • More interpretations
  • -
  • Deriving the Lasso Regression Equations
  • -
  • Exercises for week 35
  • -
  • Exercise 1: Setting up various Python environments
  • -
  • Exercise 2: making your own data and exploring scikit-learn
  • -
  • Exercise 3: Normalizing our data
  • -
  • Exercise 4: Adding Ridge Regression
  • -
  • Exercise 5: Analytical exercises
  • +
  • Reducing the number of degrees of freedom, overarching view
  • +
  • Preprocessing our data
  • +
  • Functionality in Scikit-Learn
  • +
  • More preprocessing
  • +
  • Frequently used scaling functions
  • +
  • Example of own Standard scaling
  • +
  • Min-Max Scaling
  • +
  • Testing the Means Squared Error as function of Complexity
  • +
  • More preprocessing examples, two-dimensional example, the Franke function
  • +
  • To think about, first part
  • +
  • More thinking
  • +
  • Still thinking
  • +
  • What does centering (subtracting the mean values) mean mathematically?
  • +
  • Further Manipulations
  • +
  • Wrapping it up
  • +
  • Linear Regression code, Intercept handling first
  • +
  • The Boston housing data example
  • +
  • Housing data, the code
  • +
  • Material for lecture Thursday, August 31
  • +
  • Mathematical Interpretation of Ordinary Least Squares
  • +
  • Residual Error
  • +
  • Simple case
  • +
  • The singular value decomposition
  • +
  • Linear Regression Problems
  • +
  • Fixing the singularity
  • +
  • Basic math of the SVD
  • +
  • The SVD, a Fantastic Algorithm
  • +
  • Economy-size SVD
  • +
  • Codes for the SVD
  • +
  • Note about SVD Calculations
  • +
  • Mathematics of the SVD and implications
  • +
  • Example Matrix
  • +
  • Setting up the Matrix to be inverted
  • +
  • Further properties (important for our analyses later)
  • +
  • Meet the Covariance Matrix
  • +
  • Introducing the Covariance and Correlation functions
  • +
  • Covariance and Correlation Matrix
  • +
  • Correlation Function and Design/Feature Matrix
  • +
  • Covariance Matrix Examples
  • +
  • Correlation Matrix
  • +
  • Correlation Matrix with Pandas
  • +
  • Correlation Matrix with Pandas and the Franke function
  • +
  • Rewriting the Covariance and/or Correlation Matrix
  • +
  • Linking with the SVD
  • +
  • What does it mean?
  • +
  • And finally \( \boldsymbol{X}\boldsymbol{X}^T \)
  • +
  • Ridge and LASSO Regression
  • +
  • Deriving the Ridge Regression Equations
  • +
  • Interpreting the Ridge results
  • +
  • More interpretations
  • +
  • Deriving the Lasso Regression Equations
  • @@ -366,122 +367,36 @@ MathJax.Hub.Config({

     

     

     

    -

    More preprocessing examples, Franke function and regression

    +

    More thinking

    +

    If our predictors represent different scales, then it is important to +standardize the design matrix \( \boldsymbol{X} \) by subtracting the mean of each +column from the corresponding column and dividing the column with its +standard deviation. Most machine learning libraries do this as a default. This means that if you compare your code with the results from a given library, +the results may differ. +

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

    The +Standadscaler +function in Scikit-Learn does this for us. For the data sets we +have been studying in our various examples, the data are in many cases +already scaled and there is no need to scale them. You as a user of different machine learning algorithms, should always perform a +survey of your data, with a critical assessment of them in case you need to scale the data. +

    -# Where to save the figures and data files -PROJECT_ROOT_DIR = "Results" -FIGURE_ID = "Results/FigureFiles" -DATA_ID = "DataFiles/" - -if not os.path.exists(PROJECT_ROOT_DIR): - os.mkdir(PROJECT_ROOT_DIR) - -if not os.path.exists(FIGURE_ID): - os.makedirs(FIGURE_ID) - -if not os.path.exists(DATA_ID): - os.makedirs(DATA_ID) - -def image_path(fig_id): - return os.path.join(FIGURE_ID, fig_id) - -def data_path(dat_id): - return os.path.join(DATA_ID, dat_id) - -def save_fig(fig_id): - plt.savefig(image_path(fig_id) + ".png", format='png') - - -def 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))) -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    +

    If you need to scale the data, not doing so will give an unfair +penalization of the parameters since their magnitude depends on the +scale of their corresponding predictor. +

    +

    Suppose as an example that you +you have an input variable given by the heights of different persons. +Human height might be measured in inches or meters or +kilometers. If measured in kilometers, a standard linear regression +model with this predictor would probably give a much bigger +coefficient term, than if measured in millimeters. +This can clearly lead to problems in evaluating the cost/loss functions. +

    @@ -508,7 +423,7 @@ clf = skl.42

  • 43
  • ...
  • -
  • 68
  • +
  • 74
  • »
  • diff --git a/doc/pub/week35/html/._week35-bs034.html b/doc/pub/week35/html/._week35-bs034.html index be39e6d6e..150c5f0d4 100644 --- a/doc/pub/week35/html/._week35-bs034.html +++ b/doc/pub/week35/html/._week35-bs034.html @@ -75,10 +75,10 @@ doconce format html week35.do.txt --html_style=bootstrap --pygments_html_style=d 2, None, 'interpretations-and-optimizing-our-parameters'), - ('Examples relevant for the exercises', + ('Example relevant for the exercises', 2, None, - 'examples-relevant-for-the-exercises'), + 'example-relevant-for-the-exercises'), ('Own code for Ordinary Least Squares', 2, None, @@ -91,16 +91,14 @@ doconce format html week35.do.txt --html_style=bootstrap --pygments_html_style=d 2, None, 'splitting-our-data-in-training-and-test-data'), - ('Examples', 2, None, 'examples'), + ('The complete code with a simple data set', + 2, + None, + 'the-complete-code-with-a-simple-data-set'), ('Making your own test-train splitting', 2, None, 'making-your-own-test-train-splitting'), - ('The Boston housing data example', - 2, - None, - 'the-boston-housing-data-example'), - ('Housing data, the code', 2, None, 'housing-data-the-code'), ('Reducing the number of degrees of freedom, overarching view', 2, None, @@ -124,10 +122,33 @@ doconce format html week35.do.txt --html_style=bootstrap --pygments_html_style=d 2, None, 'testing-the-means-squared-error-as-function-of-complexity'), - ('More preprocessing examples, Franke function and regression', + ('More preprocessing examples, two-dimensional example, the ' + 'Franke function', 2, None, - 'more-preprocessing-examples-franke-function-and-regression'), + 'more-preprocessing-examples-two-dimensional-example-the-franke-function'), + ('To think about, first part', + 2, + None, + 'to-think-about-first-part'), + ('More thinking', 2, None, 'more-thinking'), + ('Still thinking', 2, None, 'still-thinking'), + ('What does centering (subtracting the mean values) mean ' + 'mathematically?', + 2, + None, + 'what-does-centering-subtracting-the-mean-values-mean-mathematically'), + ('Further Manipulations', 2, None, 'further-manipulations'), + ('Wrapping it up', 2, None, 'wrapping-it-up'), + ('Linear Regression code, Intercept handling first', + 2, + None, + 'linear-regression-code-intercept-handling-first'), + ('The Boston housing data example', + 2, + None, + 'the-boston-housing-data-example'), + ('Housing data, the code', 2, None, 'housing-data-the-code'), ('Material for lecture Thursday, August 31', 2, None, @@ -226,28 +247,7 @@ doconce format html week35.do.txt --html_style=bootstrap --pygments_html_style=d ('Deriving the Lasso Regression Equations', 2, None, - 'deriving-the-lasso-regression-equations'), - ('Exercises for week 35', 2, None, 'exercises-for-week-35'), - ('Exercise 1: Setting up various Python environments', - 2, - None, - 'exercise-1-setting-up-various-python-environments'), - ('Exercise 2: making your own data and exploring scikit-learn', - 2, - None, - 'exercise-2-making-your-own-data-and-exploring-scikit-learn'), - ('Exercise 3: Normalizing our data', - 2, - None, - 'exercise-3-normalizing-our-data'), - ('Exercise 4: Adding Ridge Regression', - 2, - None, - 'exercise-4-adding-ridge-regression'), - ('Exercise 5: Analytical exercises', - 2, - None, - 'exercise-5-analytical-exercises')]} + 'deriving-the-lasso-regression-equations')]} end of tocinfo --> @@ -299,62 +299,63 @@ MathJax.Hub.Config({
  • Other useful relations
  • Meet the Hessian Matrix
  • Interpretations and optimizing our parameters
  • -
  • Examples relevant for the exercises
  • +
  • Example relevant for the exercises
  • Own code for Ordinary Least Squares
  • Adding error analysis and training set up
  • Splitting our Data in Training and Test data
  • -
  • Examples
  • +
  • The complete code with a simple data set
  • Making your own test-train splitting
  • -
  • The Boston housing data example
  • -
  • Housing data, the code
  • -
  • Reducing the number of degrees of freedom, overarching view
  • -
  • Preprocessing our data
  • -
  • Functionality in Scikit-Learn
  • -
  • More preprocessing
  • -
  • Frequently used scaling functions
  • -
  • Example of own Standard scaling
  • -
  • Min-Max Scaling
  • -
  • Testing the Means Squared Error as function of Complexity
  • -
  • More preprocessing examples, Franke function and regression
  • -
  • Material for lecture Thursday, August 31
  • -
  • Mathematical Interpretation of Ordinary Least Squares
  • -
  • Residual Error
  • -
  • Simple case
  • -
  • The singular value decomposition
  • -
  • Linear Regression Problems
  • -
  • Fixing the singularity
  • -
  • Basic math of the SVD
  • -
  • The SVD, a Fantastic Algorithm
  • -
  • Economy-size SVD
  • -
  • Codes for the SVD
  • -
  • Note about SVD Calculations
  • -
  • Mathematics of the SVD and implications
  • -
  • Example Matrix
  • -
  • Setting up the Matrix to be inverted
  • -
  • Further properties (important for our analyses later)
  • -
  • Meet the Covariance Matrix
  • -
  • Introducing the Covariance and Correlation functions
  • -
  • Covariance and Correlation Matrix
  • -
  • Correlation Function and Design/Feature Matrix
  • -
  • Covariance Matrix Examples
  • -
  • Correlation Matrix
  • -
  • Correlation Matrix with Pandas
  • -
  • Correlation Matrix with Pandas and the Franke function
  • -
  • Rewriting the Covariance and/or Correlation Matrix
  • -
  • Linking with the SVD
  • -
  • What does it mean?
  • -
  • And finally \( \boldsymbol{X}\boldsymbol{X}^T \)
  • -
  • Ridge and LASSO Regression
  • -
  • Deriving the Ridge Regression Equations
  • -
  • Interpreting the Ridge results
  • -
  • More interpretations
  • -
  • Deriving the Lasso Regression Equations
  • -
  • Exercises for week 35
  • -
  • Exercise 1: Setting up various Python environments
  • -
  • Exercise 2: making your own data and exploring scikit-learn
  • -
  • Exercise 3: Normalizing our data
  • -
  • Exercise 4: Adding Ridge Regression
  • -
  • Exercise 5: Analytical exercises
  • +
  • Reducing the number of degrees of freedom, overarching view
  • +
  • Preprocessing our data
  • +
  • Functionality in Scikit-Learn
  • +
  • More preprocessing
  • +
  • Frequently used scaling functions
  • +
  • Example of own Standard scaling
  • +
  • Min-Max Scaling
  • +
  • Testing the Means Squared Error as function of Complexity
  • +
  • More preprocessing examples, two-dimensional example, the Franke function
  • +
  • To think about, first part
  • +
  • More thinking
  • +
  • Still thinking
  • +
  • What does centering (subtracting the mean values) mean mathematically?
  • +
  • Further Manipulations
  • +
  • Wrapping it up
  • +
  • Linear Regression code, Intercept handling first
  • +
  • The Boston housing data example
  • +
  • Housing data, the code
  • +
  • Material for lecture Thursday, August 31
  • +
  • Mathematical Interpretation of Ordinary Least Squares
  • +
  • Residual Error
  • +
  • Simple case
  • +
  • The singular value decomposition
  • +
  • Linear Regression Problems
  • +
  • Fixing the singularity
  • +
  • Basic math of the SVD
  • +
  • The SVD, a Fantastic Algorithm
  • +
  • Economy-size SVD
  • +
  • Codes for the SVD
  • +
  • Note about SVD Calculations
  • +
  • Mathematics of the SVD and implications
  • +
  • Example Matrix
  • +
  • Setting up the Matrix to be inverted
  • +
  • Further properties (important for our analyses later)
  • +
  • Meet the Covariance Matrix
  • +
  • Introducing the Covariance and Correlation functions
  • +
  • Covariance and Correlation Matrix
  • +
  • Correlation Function and Design/Feature Matrix
  • +
  • Covariance Matrix Examples
  • +
  • Correlation Matrix
  • +
  • Correlation Matrix with Pandas
  • +
  • Correlation Matrix with Pandas and the Franke function
  • +
  • Rewriting the Covariance and/or Correlation Matrix
  • +
  • Linking with the SVD
  • +
  • What does it mean?
  • +
  • And finally \( \boldsymbol{X}\boldsymbol{X}^T \)
  • +
  • Ridge and LASSO Regression
  • +
  • Deriving the Ridge Regression Equations
  • +
  • Interpreting the Ridge results
  • +
  • More interpretations
  • +
  • Deriving the Lasso Regression Equations
  • @@ -366,7 +367,48 @@ MathJax.Hub.Config({

     

     

     

    -

    Material for lecture Thursday, August 31

    +

    Still thinking

    + +

    Keep in mind that when you transform your data set before training a model, the same transformation needs to be done +on your eventual new data set before making a prediction. If we translate this into a Python code, it would could be implemented as follows +

    + + + +
    +
    +
    +
    +
    +
    #Model training, we compute the mean value of y and X
    +y_train_mean = np.mean(y_train)
    +X_train_mean = np.mean(X_train,axis=0)
    +X_train = X_train - X_train_mean
    +y_train = y_train - y_train_mean
    +
    +# The we fit our model with the training data
    +trained_model = some_model.fit(X_train,y_train)
    +
    +
    +#Model prediction, we need also to transform our data set used for the prediction.
    +X_test = X_test - X_train_mean #Use mean from training data
    +y_pred = trained_model(X_test)
    +y_pred = y_pred + y_train_mean
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +

    @@ -393,7 +435,7 @@ MathJax.Hub.Config({

  • 43
  • 44
  • ...
  • -
  • 68
  • +
  • 74
  • »
  • diff --git a/doc/pub/week35/html/._week35-bs035.html b/doc/pub/week35/html/._week35-bs035.html index 74a917343..327287312 100644 --- a/doc/pub/week35/html/._week35-bs035.html +++ b/doc/pub/week35/html/._week35-bs035.html @@ -75,10 +75,10 @@ doconce format html week35.do.txt --html_style=bootstrap --pygments_html_style=d 2, None, 'interpretations-and-optimizing-our-parameters'), - ('Examples relevant for the exercises', + ('Example relevant for the exercises', 2, None, - 'examples-relevant-for-the-exercises'), + 'example-relevant-for-the-exercises'), ('Own code for Ordinary Least Squares', 2, None, @@ -91,16 +91,14 @@ doconce format html week35.do.txt --html_style=bootstrap --pygments_html_style=d 2, None, 'splitting-our-data-in-training-and-test-data'), - ('Examples', 2, None, 'examples'), + ('The complete code with a simple data set', + 2, + None, + 'the-complete-code-with-a-simple-data-set'), ('Making your own test-train splitting', 2, None, 'making-your-own-test-train-splitting'), - ('The Boston housing data example', - 2, - None, - 'the-boston-housing-data-example'), - ('Housing data, the code', 2, None, 'housing-data-the-code'), ('Reducing the number of degrees of freedom, overarching view', 2, None, @@ -124,10 +122,33 @@ doconce format html week35.do.txt --html_style=bootstrap --pygments_html_style=d 2, None, 'testing-the-means-squared-error-as-function-of-complexity'), - ('More preprocessing examples, Franke function and regression', + ('More preprocessing examples, two-dimensional example, the ' + 'Franke function', 2, None, - 'more-preprocessing-examples-franke-function-and-regression'), + 'more-preprocessing-examples-two-dimensional-example-the-franke-function'), + ('To think about, first part', + 2, + None, + 'to-think-about-first-part'), + ('More thinking', 2, None, 'more-thinking'), + ('Still thinking', 2, None, 'still-thinking'), + ('What does centering (subtracting the mean values) mean ' + 'mathematically?', + 2, + None, + 'what-does-centering-subtracting-the-mean-values-mean-mathematically'), + ('Further Manipulations', 2, None, 'further-manipulations'), + ('Wrapping it up', 2, None, 'wrapping-it-up'), + ('Linear Regression code, Intercept handling first', + 2, + None, + 'linear-regression-code-intercept-handling-first'), + ('The Boston housing data example', + 2, + None, + 'the-boston-housing-data-example'), + ('Housing data, the code', 2, None, 'housing-data-the-code'), ('Material for lecture Thursday, August 31', 2, None, @@ -226,28 +247,7 @@ doconce format html week35.do.txt --html_style=bootstrap --pygments_html_style=d ('Deriving the Lasso Regression Equations', 2, None, - 'deriving-the-lasso-regression-equations'), - ('Exercises for week 35', 2, None, 'exercises-for-week-35'), - ('Exercise 1: Setting up various Python environments', - 2, - None, - 'exercise-1-setting-up-various-python-environments'), - ('Exercise 2: making your own data and exploring scikit-learn', - 2, - None, - 'exercise-2-making-your-own-data-and-exploring-scikit-learn'), - ('Exercise 3: Normalizing our data', - 2, - None, - 'exercise-3-normalizing-our-data'), - ('Exercise 4: Adding Ridge Regression', - 2, - None, - 'exercise-4-adding-ridge-regression'), - ('Exercise 5: Analytical exercises', - 2, - None, - 'exercise-5-analytical-exercises')]} + 'deriving-the-lasso-regression-equations')]} end of tocinfo --> @@ -299,62 +299,63 @@ MathJax.Hub.Config({
  • Other useful relations
  • Meet the Hessian Matrix
  • Interpretations and optimizing our parameters
  • -
  • Examples relevant for the exercises
  • +
  • Example relevant for the exercises
  • Own code for Ordinary Least Squares
  • Adding error analysis and training set up
  • Splitting our Data in Training and Test data
  • -
  • Examples
  • +
  • The complete code with a simple data set
  • Making your own test-train splitting
  • -
  • The Boston housing data example
  • -
  • Housing data, the code
  • -
  • Reducing the number of degrees of freedom, overarching view
  • -
  • Preprocessing our data
  • -
  • Functionality in Scikit-Learn
  • -
  • More preprocessing
  • -
  • Frequently used scaling functions
  • -
  • Example of own Standard scaling
  • -
  • Min-Max Scaling
  • -
  • Testing the Means Squared Error as function of Complexity
  • -
  • More preprocessing examples, Franke function and regression
  • -
  • Material for lecture Thursday, August 31
  • -
  • Mathematical Interpretation of Ordinary Least Squares
  • -
  • Residual Error
  • -
  • Simple case
  • -
  • The singular value decomposition
  • -
  • Linear Regression Problems
  • -
  • Fixing the singularity
  • -
  • Basic math of the SVD
  • -
  • The SVD, a Fantastic Algorithm
  • -
  • Economy-size SVD
  • -
  • Codes for the SVD
  • -
  • Note about SVD Calculations
  • -
  • Mathematics of the SVD and implications
  • -
  • Example Matrix
  • -
  • Setting up the Matrix to be inverted
  • -
  • Further properties (important for our analyses later)
  • -
  • Meet the Covariance Matrix
  • -
  • Introducing the Covariance and Correlation functions
  • -
  • Covariance and Correlation Matrix
  • -
  • Correlation Function and Design/Feature Matrix
  • -
  • Covariance Matrix Examples
  • -
  • Correlation Matrix
  • -
  • Correlation Matrix with Pandas
  • -
  • Correlation Matrix with Pandas and the Franke function
  • -
  • Rewriting the Covariance and/or Correlation Matrix
  • -
  • Linking with the SVD
  • -
  • What does it mean?
  • -
  • And finally \( \boldsymbol{X}\boldsymbol{X}^T \)
  • -
  • Ridge and LASSO Regression
  • -
  • Deriving the Ridge Regression Equations
  • -
  • Interpreting the Ridge results
  • -
  • More interpretations
  • -
  • Deriving the Lasso Regression Equations
  • -
  • Exercises for week 35
  • -
  • Exercise 1: Setting up various Python environments
  • -
  • Exercise 2: making your own data and exploring scikit-learn
  • -
  • Exercise 3: Normalizing our data
  • -
  • Exercise 4: Adding Ridge Regression
  • -
  • Exercise 5: Analytical exercises
  • +
  • Reducing the number of degrees of freedom, overarching view
  • +
  • Preprocessing our data
  • +
  • Functionality in Scikit-Learn
  • +
  • More preprocessing
  • +
  • Frequently used scaling functions
  • +
  • Example of own Standard scaling
  • +
  • Min-Max Scaling
  • +
  • Testing the Means Squared Error as function of Complexity
  • +
  • More preprocessing examples, two-dimensional example, the Franke function
  • +
  • To think about, first part
  • +
  • More thinking
  • +
  • Still thinking
  • +
  • What does centering (subtracting the mean values) mean mathematically?
  • +
  • Further Manipulations
  • +
  • Wrapping it up
  • +
  • Linear Regression code, Intercept handling first
  • +
  • The Boston housing data example
  • +
  • Housing data, the code
  • +
  • Material for lecture Thursday, August 31
  • +
  • Mathematical Interpretation of Ordinary Least Squares
  • +
  • Residual Error
  • +
  • Simple case
  • +
  • The singular value decomposition
  • +
  • Linear Regression Problems
  • +
  • Fixing the singularity
  • +
  • Basic math of the SVD
  • +
  • The SVD, a Fantastic Algorithm
  • +
  • Economy-size SVD
  • +
  • Codes for the SVD
  • +
  • Note about SVD Calculations
  • +
  • Mathematics of the SVD and implications
  • +
  • Example Matrix
  • +
  • Setting up the Matrix to be inverted
  • +
  • Further properties (important for our analyses later)
  • +
  • Meet the Covariance Matrix
  • +
  • Introducing the Covariance and Correlation functions
  • +
  • Covariance and Correlation Matrix
  • +
  • Correlation Function and Design/Feature Matrix
  • +
  • Covariance Matrix Examples
  • +
  • Correlation Matrix
  • +
  • Correlation Matrix with Pandas
  • +
  • Correlation Matrix with Pandas and the Franke function
  • +
  • Rewriting the Covariance and/or Correlation Matrix
  • +
  • Linking with the SVD
  • +
  • What does it mean?
  • +
  • And finally \( \boldsymbol{X}\boldsymbol{X}^T \)
  • +
  • Ridge and LASSO Regression
  • +
  • Deriving the Ridge Regression Equations
  • +
  • Interpreting the Ridge results
  • +
  • More interpretations
  • +
  • Deriving the Lasso Regression Equations
  • @@ -366,38 +367,41 @@ MathJax.Hub.Config({

     

     

     

    -

    Mathematical Interpretation of Ordinary Least Squares

    +

    What does centering (subtracting the mean values) mean mathematically?

    -

    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

    - -$$ -\hat{\boldsymbol{\beta}} = \left(\boldsymbol{X}^T\boldsymbol{X}\right)^{-1}\boldsymbol{X}^T\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. +

    Let us try to understand what this may imply mathematically when we +subtract the mean values, also known as zero centering. For +simplicity, we will focus on ordinary regression, as done in the above example.

    +

    The cost/loss function for regression is

    +$$ +C(\beta_0, \beta_1, ... , \beta_{p-1}) = \frac{1}{n}\sum_{i=0}^{n} \left(y_i - \beta_0 - \sum_{j=1}^{p-1} X_{ij}\beta_j\right)^2,. +$$ + +

    Recall also that we use the squared value since this leads to an increase of the penalty for higher differences between predicted and output/target values.

    + +

    What we have done is to single out the \( \beta_0 \) term in the definition of the mean squared error (MSE). +The design matrix +\( X \) does in this case not contain any intercept column. +When we take the derivative with respect to \( \beta_0 \), we want the derivative to obey +

    +$$ +\frac{\partial C}{\partial \beta_j} = 0, +$$ + +

    for all \( j \). For \( \beta_0 \) we have

    + +$$ +\frac{\partial C}{\partial \beta_0} = -\frac{2}{n}\sum_{i=0}^{n-1} \left(y_i - \beta_0 - \sum_{j=1}^{p-1} X_{ij} \beta_j\right). +$$ + +

    Multiplying away the constant \( 2/n \), we obtain

    +$$ +\sum_{i=0}^{n-1} \beta_0 = \sum_{i=0}^{n-1}y_i - \sum_{i=0}^{n-1} \sum_{j=1}^{p-1} X_{ij} \beta_j. +$$ + +

      @@ -423,7 +427,7 @@ We can then interpret our optimal model \( \tilde{\boldsymbol{y}} \) as being re
    • 44
    • 45
    • ...
    • -
    • 68
    • +
    • 74
    • »
    diff --git a/doc/pub/week35/html/._week35-bs036.html b/doc/pub/week35/html/._week35-bs036.html index 8f55b6f48..6e974e6f4 100644 --- a/doc/pub/week35/html/._week35-bs036.html +++ b/doc/pub/week35/html/._week35-bs036.html @@ -75,10 +75,10 @@ doconce format html week35.do.txt --html_style=bootstrap --pygments_html_style=d 2, None, 'interpretations-and-optimizing-our-parameters'), - ('Examples relevant for the exercises', + ('Example relevant for the exercises', 2, None, - 'examples-relevant-for-the-exercises'), + 'example-relevant-for-the-exercises'), ('Own code for Ordinary Least Squares', 2, None, @@ -91,16 +91,14 @@ doconce format html week35.do.txt --html_style=bootstrap --pygments_html_style=d 2, None, 'splitting-our-data-in-training-and-test-data'), - ('Examples', 2, None, 'examples'), + ('The complete code with a simple data set', + 2, + None, + 'the-complete-code-with-a-simple-data-set'), ('Making your own test-train splitting', 2, None, 'making-your-own-test-train-splitting'), - ('The Boston housing data example', - 2, - None, - 'the-boston-housing-data-example'), - ('Housing data, the code', 2, None, 'housing-data-the-code'), ('Reducing the number of degrees of freedom, overarching view', 2, None, @@ -124,10 +122,33 @@ doconce format html week35.do.txt --html_style=bootstrap --pygments_html_style=d 2, None, 'testing-the-means-squared-error-as-function-of-complexity'), - ('More preprocessing examples, Franke function and regression', + ('More preprocessing examples, two-dimensional example, the ' + 'Franke function', 2, None, - 'more-preprocessing-examples-franke-function-and-regression'), + 'more-preprocessing-examples-two-dimensional-example-the-franke-function'), + ('To think about, first part', + 2, + None, + 'to-think-about-first-part'), + ('More thinking', 2, None, 'more-thinking'), + ('Still thinking', 2, None, 'still-thinking'), + ('What does centering (subtracting the mean values) mean ' + 'mathematically?', + 2, + None, + 'what-does-centering-subtracting-the-mean-values-mean-mathematically'), + ('Further Manipulations', 2, None, 'further-manipulations'), + ('Wrapping it up', 2, None, 'wrapping-it-up'), + ('Linear Regression code, Intercept handling first', + 2, + None, + 'linear-regression-code-intercept-handling-first'), + ('The Boston housing data example', + 2, + None, + 'the-boston-housing-data-example'), + ('Housing data, the code', 2, None, 'housing-data-the-code'), ('Material for lecture Thursday, August 31', 2, None, @@ -226,28 +247,7 @@ doconce format html week35.do.txt --html_style=bootstrap --pygments_html_style=d ('Deriving the Lasso Regression Equations', 2, None, - 'deriving-the-lasso-regression-equations'), - ('Exercises for week 35', 2, None, 'exercises-for-week-35'), - ('Exercise 1: Setting up various Python environments', - 2, - None, - 'exercise-1-setting-up-various-python-environments'), - ('Exercise 2: making your own data and exploring scikit-learn', - 2, - None, - 'exercise-2-making-your-own-data-and-exploring-scikit-learn'), - ('Exercise 3: Normalizing our data', - 2, - None, - 'exercise-3-normalizing-our-data'), - ('Exercise 4: Adding Ridge Regression', - 2, - None, - 'exercise-4-adding-ridge-regression'), - ('Exercise 5: Analytical exercises', - 2, - None, - 'exercise-5-analytical-exercises')]} + 'deriving-the-lasso-regression-equations')]} end of tocinfo --> @@ -299,62 +299,63 @@ MathJax.Hub.Config({
  • Other useful relations
  • Meet the Hessian Matrix
  • Interpretations and optimizing our parameters
  • -
  • Examples relevant for the exercises
  • +
  • Example relevant for the exercises
  • Own code for Ordinary Least Squares
  • Adding error analysis and training set up
  • Splitting our Data in Training and Test data
  • -
  • Examples
  • +
  • The complete code with a simple data set
  • Making your own test-train splitting
  • -
  • The Boston housing data example
  • -
  • Housing data, the code
  • -
  • Reducing the number of degrees of freedom, overarching view
  • -
  • Preprocessing our data
  • -
  • Functionality in Scikit-Learn
  • -
  • More preprocessing
  • -
  • Frequently used scaling functions
  • -
  • Example of own Standard scaling
  • -
  • Min-Max Scaling
  • -
  • Testing the Means Squared Error as function of Complexity
  • -
  • More preprocessing examples, Franke function and regression
  • -
  • Material for lecture Thursday, August 31
  • -
  • Mathematical Interpretation of Ordinary Least Squares
  • -
  • Residual Error
  • -
  • Simple case
  • -
  • The singular value decomposition
  • -
  • Linear Regression Problems
  • -
  • Fixing the singularity
  • -
  • Basic math of the SVD
  • -
  • The SVD, a Fantastic Algorithm
  • -
  • Economy-size SVD
  • -
  • Codes for the SVD
  • -
  • Note about SVD Calculations
  • -
  • Mathematics of the SVD and implications
  • -
  • Example Matrix
  • -
  • Setting up the Matrix to be inverted
  • -
  • Further properties (important for our analyses later)
  • -
  • Meet the Covariance Matrix
  • -
  • Introducing the Covariance and Correlation functions
  • -
  • Covariance and Correlation Matrix
  • -
  • Correlation Function and Design/Feature Matrix
  • -
  • Covariance Matrix Examples
  • -
  • Correlation Matrix
  • -
  • Correlation Matrix with Pandas
  • -
  • Correlation Matrix with Pandas and the Franke function
  • -
  • Rewriting the Covariance and/or Correlation Matrix
  • -
  • Linking with the SVD
  • -
  • What does it mean?
  • -
  • And finally \( \boldsymbol{X}\boldsymbol{X}^T \)
  • -
  • Ridge and LASSO Regression
  • -
  • Deriving the Ridge Regression Equations
  • -
  • Interpreting the Ridge results
  • -
  • More interpretations
  • -
  • Deriving the Lasso Regression Equations
  • -
  • Exercises for week 35
  • -
  • Exercise 1: Setting up various Python environments
  • -
  • Exercise 2: making your own data and exploring scikit-learn
  • -
  • Exercise 3: Normalizing our data
  • -
  • Exercise 4: Adding Ridge Regression
  • -
  • Exercise 5: Analytical exercises
  • +
  • Reducing the number of degrees of freedom, overarching view
  • +
  • Preprocessing our data
  • +
  • Functionality in Scikit-Learn
  • +
  • More preprocessing
  • +
  • Frequently used scaling functions
  • +
  • Example of own Standard scaling
  • +
  • Min-Max Scaling
  • +
  • Testing the Means Squared Error as function of Complexity
  • +
  • More preprocessing examples, two-dimensional example, the Franke function
  • +
  • To think about, first part
  • +
  • More thinking
  • +
  • Still thinking
  • +
  • What does centering (subtracting the mean values) mean mathematically?
  • +
  • Further Manipulations
  • +
  • Wrapping it up
  • +
  • Linear Regression code, Intercept handling first
  • +
  • The Boston housing data example
  • +
  • Housing data, the code
  • +
  • Material for lecture Thursday, August 31
  • +
  • Mathematical Interpretation of Ordinary Least Squares
  • +
  • Residual Error
  • +
  • Simple case
  • +
  • The singular value decomposition
  • +
  • Linear Regression Problems
  • +
  • Fixing the singularity
  • +
  • Basic math of the SVD
  • +
  • The SVD, a Fantastic Algorithm
  • +
  • Economy-size SVD
  • +
  • Codes for the SVD
  • +
  • Note about SVD Calculations
  • +
  • Mathematics of the SVD and implications
  • +
  • Example Matrix
  • +
  • Setting up the Matrix to be inverted
  • +
  • Further properties (important for our analyses later)
  • +
  • Meet the Covariance Matrix
  • +
  • Introducing the Covariance and Correlation functions
  • +
  • Covariance and Correlation Matrix
  • +
  • Correlation Function and Design/Feature Matrix
  • +
  • Covariance Matrix Examples
  • +
  • Correlation Matrix
  • +
  • Correlation Matrix with Pandas
  • +
  • Correlation Matrix with Pandas and the Franke function
  • +
  • Rewriting the Covariance and/or Correlation Matrix
  • +
  • Linking with the SVD
  • +
  • What does it mean?
  • +
  • And finally \( \boldsymbol{X}\boldsymbol{X}^T \)
  • +
  • Ridge and LASSO Regression
  • +
  • Deriving the Ridge Regression Equations
  • +
  • Interpreting the Ridge results
  • +
  • More interpretations
  • +
  • Deriving the Lasso Regression Equations
  • @@ -366,14 +367,45 @@ MathJax.Hub.Config({

     

     

     

    -

    Residual Error

    +

    Further Manipulations

    -

    We have defined the residual error as

    +

    Let us special first to the case where we have only two parameters \( \beta_0 \) and \( \beta_1 \). +Our result for \( \beta_0 \) simplifies then to +

    $$ -\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}. +n\beta_0 = \sum_{i=0}^{n-1}y_i - \sum_{i=0}^{n-1} X_{i1} \beta_1. +$$ + +

    We obtain then

    +$$ +\beta_0 = \frac{1}{n}\sum_{i=0}^{n-1}y_i - \beta_1\frac{1}{n}\sum_{i=0}^{n-1} X_{i1}. +$$ + +

    If we define

    +$$ +\mu_1=\frac{1}{n}\sum_{i=0}^{n-1} (X_{i1}, +$$ + +

    and if we define the mean value of the outputs as

    +$$ +\mu_y=\frac{1}{n}\sum_{i=0}^{n-1}y_i, +$$ + +

    we have

    +$$ +\beta_0 = \mu_y - \beta_1\mu_{1}. +$$ + +

    In the general case, that is we have more parameters than \( \beta_0 \) and \( \beta_1 \), we have

    +$$ +\beta_0 = \frac{1}{n}\sum_{i=0}^{n-1}y_i - \frac{1}{n}\sum_{i=0}^{n-1}\sum_{j=1}^{p-1} X_{ij}\beta_j. +$$ + +

    Replacing \( y_i \) with \( y_i - y_i - \overline{\boldsymbol{y}} \) and centering also our design matrix results in a cost function (in vector-matrix disguise)

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

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

    @@ -400,7 +432,7 @@ $$

  • 45
  • 46
  • ...
  • -
  • 68
  • +
  • 74
  • »
  • diff --git a/doc/pub/week35/html/._week35-bs037.html b/doc/pub/week35/html/._week35-bs037.html index 6ca0c72b6..415cbadf2 100644 --- a/doc/pub/week35/html/._week35-bs037.html +++ b/doc/pub/week35/html/._week35-bs037.html @@ -75,10 +75,10 @@ doconce format html week35.do.txt --html_style=bootstrap --pygments_html_style=d 2, None, 'interpretations-and-optimizing-our-parameters'), - ('Examples relevant for the exercises', + ('Example relevant for the exercises', 2, None, - 'examples-relevant-for-the-exercises'), + 'example-relevant-for-the-exercises'), ('Own code for Ordinary Least Squares', 2, None, @@ -91,16 +91,14 @@ doconce format html week35.do.txt --html_style=bootstrap --pygments_html_style=d 2, None, 'splitting-our-data-in-training-and-test-data'), - ('Examples', 2, None, 'examples'), + ('The complete code with a simple data set', + 2, + None, + 'the-complete-code-with-a-simple-data-set'), ('Making your own test-train splitting', 2, None, 'making-your-own-test-train-splitting'), - ('The Boston housing data example', - 2, - None, - 'the-boston-housing-data-example'), - ('Housing data, the code', 2, None, 'housing-data-the-code'), ('Reducing the number of degrees of freedom, overarching view', 2, None, @@ -124,10 +122,33 @@ doconce format html week35.do.txt --html_style=bootstrap --pygments_html_style=d 2, None, 'testing-the-means-squared-error-as-function-of-complexity'), - ('More preprocessing examples, Franke function and regression', + ('More preprocessing examples, two-dimensional example, the ' + 'Franke function', 2, None, - 'more-preprocessing-examples-franke-function-and-regression'), + 'more-preprocessing-examples-two-dimensional-example-the-franke-function'), + ('To think about, first part', + 2, + None, + 'to-think-about-first-part'), + ('More thinking', 2, None, 'more-thinking'), + ('Still thinking', 2, None, 'still-thinking'), + ('What does centering (subtracting the mean values) mean ' + 'mathematically?', + 2, + None, + 'what-does-centering-subtracting-the-mean-values-mean-mathematically'), + ('Further Manipulations', 2, None, 'further-manipulations'), + ('Wrapping it up', 2, None, 'wrapping-it-up'), + ('Linear Regression code, Intercept handling first', + 2, + None, + 'linear-regression-code-intercept-handling-first'), + ('The Boston housing data example', + 2, + None, + 'the-boston-housing-data-example'), + ('Housing data, the code', 2, None, 'housing-data-the-code'), ('Material for lecture Thursday, August 31', 2, None, @@ -226,28 +247,7 @@ doconce format html week35.do.txt --html_style=bootstrap --pygments_html_style=d ('Deriving the Lasso Regression Equations', 2, None, - 'deriving-the-lasso-regression-equations'), - ('Exercises for week 35', 2, None, 'exercises-for-week-35'), - ('Exercise 1: Setting up various Python environments', - 2, - None, - 'exercise-1-setting-up-various-python-environments'), - ('Exercise 2: making your own data and exploring scikit-learn', - 2, - None, - 'exercise-2-making-your-own-data-and-exploring-scikit-learn'), - ('Exercise 3: Normalizing our data', - 2, - None, - 'exercise-3-normalizing-our-data'), - ('Exercise 4: Adding Ridge Regression', - 2, - None, - 'exercise-4-adding-ridge-regression'), - ('Exercise 5: Analytical exercises', - 2, - None, - 'exercise-5-analytical-exercises')]} + 'deriving-the-lasso-regression-equations')]} end of tocinfo --> @@ -299,62 +299,63 @@ MathJax.Hub.Config({
  • Other useful relations
  • Meet the Hessian Matrix
  • Interpretations and optimizing our parameters
  • -
  • Examples relevant for the exercises
  • +
  • Example relevant for the exercises
  • Own code for Ordinary Least Squares
  • Adding error analysis and training set up
  • Splitting our Data in Training and Test data
  • -
  • Examples
  • +
  • The complete code with a simple data set
  • Making your own test-train splitting
  • -
  • The Boston housing data example
  • -
  • Housing data, the code
  • -
  • Reducing the number of degrees of freedom, overarching view
  • -
  • Preprocessing our data
  • -
  • Functionality in Scikit-Learn
  • -
  • More preprocessing
  • -
  • Frequently used scaling functions
  • -
  • Example of own Standard scaling
  • -
  • Min-Max Scaling
  • -
  • Testing the Means Squared Error as function of Complexity
  • -
  • More preprocessing examples, Franke function and regression
  • -
  • Material for lecture Thursday, August 31
  • -
  • Mathematical Interpretation of Ordinary Least Squares
  • -
  • Residual Error
  • -
  • Simple case
  • -
  • The singular value decomposition
  • -
  • Linear Regression Problems
  • -
  • Fixing the singularity
  • -
  • Basic math of the SVD
  • -
  • The SVD, a Fantastic Algorithm
  • -
  • Economy-size SVD
  • -
  • Codes for the SVD
  • -
  • Note about SVD Calculations
  • -
  • Mathematics of the SVD and implications
  • -
  • Example Matrix
  • -
  • Setting up the Matrix to be inverted
  • -
  • Further properties (important for our analyses later)
  • -
  • Meet the Covariance Matrix
  • -
  • Introducing the Covariance and Correlation functions
  • -
  • Covariance and Correlation Matrix
  • -
  • Correlation Function and Design/Feature Matrix
  • -
  • Covariance Matrix Examples
  • -
  • Correlation Matrix
  • -
  • Correlation Matrix with Pandas
  • -
  • Correlation Matrix with Pandas and the Franke function
  • -
  • Rewriting the Covariance and/or Correlation Matrix
  • -
  • Linking with the SVD
  • -
  • What does it mean?
  • -
  • And finally \( \boldsymbol{X}\boldsymbol{X}^T \)
  • -
  • Ridge and LASSO Regression
  • -
  • Deriving the Ridge Regression Equations
  • -
  • Interpreting the Ridge results
  • -
  • More interpretations
  • -
  • Deriving the Lasso Regression Equations
  • -
  • Exercises for week 35
  • -
  • Exercise 1: Setting up various Python environments
  • -
  • Exercise 2: making your own data and exploring scikit-learn
  • -
  • Exercise 3: Normalizing our data
  • -
  • Exercise 4: Adding Ridge Regression
  • -
  • Exercise 5: Analytical exercises
  • +
  • Reducing the number of degrees of freedom, overarching view
  • +
  • Preprocessing our data
  • +
  • Functionality in Scikit-Learn
  • +
  • More preprocessing
  • +
  • Frequently used scaling functions
  • +
  • Example of own Standard scaling
  • +
  • Min-Max Scaling
  • +
  • Testing the Means Squared Error as function of Complexity
  • +
  • More preprocessing examples, two-dimensional example, the Franke function
  • +
  • To think about, first part
  • +
  • More thinking
  • +
  • Still thinking
  • +
  • What does centering (subtracting the mean values) mean mathematically?
  • +
  • Further Manipulations
  • +
  • Wrapping it up
  • +
  • Linear Regression code, Intercept handling first
  • +
  • The Boston housing data example
  • +
  • Housing data, the code
  • +
  • Material for lecture Thursday, August 31
  • +
  • Mathematical Interpretation of Ordinary Least Squares
  • +
  • Residual Error
  • +
  • Simple case
  • +
  • The singular value decomposition
  • +
  • Linear Regression Problems
  • +
  • Fixing the singularity
  • +
  • Basic math of the SVD
  • +
  • The SVD, a Fantastic Algorithm
  • +
  • Economy-size SVD
  • +
  • Codes for the SVD
  • +
  • Note about SVD Calculations
  • +
  • Mathematics of the SVD and implications
  • +
  • Example Matrix
  • +
  • Setting up the Matrix to be inverted
  • +
  • Further properties (important for our analyses later)
  • +
  • Meet the Covariance Matrix
  • +
  • Introducing the Covariance and Correlation functions
  • +
  • Covariance and Correlation Matrix
  • +
  • Correlation Function and Design/Feature Matrix
  • +
  • Covariance Matrix Examples
  • +
  • Correlation Matrix
  • +
  • Correlation Matrix with Pandas
  • +
  • Correlation Matrix with Pandas and the Franke function
  • +
  • Rewriting the Covariance and/or Correlation Matrix
  • +
  • Linking with the SVD
  • +
  • What does it mean?
  • +
  • And finally \( \boldsymbol{X}\boldsymbol{X}^T \)
  • +
  • Ridge and LASSO Regression
  • +
  • Deriving the Ridge Regression Equations
  • +
  • Interpreting the Ridge results
  • +
  • More interpretations
  • +
  • Deriving the Lasso Regression Equations
  • @@ -366,25 +367,24 @@ MathJax.Hub.Config({

     

     

     

    -

    Simple case

    +

    Wrapping it up

    -

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

    +

    If we minimize with respect to \( \boldsymbol{\beta} \) we have then

    $$ -\boldsymbol{X}^T\boldsymbol{X}=\boldsymbol{X}\boldsymbol{X}^T = \boldsymbol{I}. +\hat{\boldsymbol{\beta}} = (\tilde{X}^T\tilde{X})^{-1}\tilde{X}^T\boldsymbol{\tilde{y}}, $$ -

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

    +

    where \( \boldsymbol{\tilde{y}} = \boldsymbol{y} - \overline{\boldsymbol{y}} \) +and \( \tilde{X}_{ij} = X_{ij} - \frac{1}{n}\sum_{k=0}^{n-1}X_{kj} \). +

    + +

    For Ridge regression we need to add \( \lambda \boldsymbol{\beta}^T\boldsymbol{\beta} \) to the cost function and get then

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

    and we have the obvious case

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

    This serves also as a useful test of our codes.

    +

    What does this mean? And why do we insist on all this? Let us look at some examples.

    @@ -411,7 +411,7 @@ $$

  • 46
  • 47
  • ...
  • -
  • 68
  • +
  • 74
  • »
  • diff --git a/doc/pub/week35/html/._week35-bs038.html b/doc/pub/week35/html/._week35-bs038.html index 75920eec2..1d11afbad 100644 --- a/doc/pub/week35/html/._week35-bs038.html +++ b/doc/pub/week35/html/._week35-bs038.html @@ -75,10 +75,10 @@ doconce format html week35.do.txt --html_style=bootstrap --pygments_html_style=d 2, None, 'interpretations-and-optimizing-our-parameters'), - ('Examples relevant for the exercises', + ('Example relevant for the exercises', 2, None, - 'examples-relevant-for-the-exercises'), + 'example-relevant-for-the-exercises'), ('Own code for Ordinary Least Squares', 2, None, @@ -91,16 +91,14 @@ doconce format html week35.do.txt --html_style=bootstrap --pygments_html_style=d 2, None, 'splitting-our-data-in-training-and-test-data'), - ('Examples', 2, None, 'examples'), + ('The complete code with a simple data set', + 2, + None, + 'the-complete-code-with-a-simple-data-set'), ('Making your own test-train splitting', 2, None, 'making-your-own-test-train-splitting'), - ('The Boston housing data example', - 2, - None, - 'the-boston-housing-data-example'), - ('Housing data, the code', 2, None, 'housing-data-the-code'), ('Reducing the number of degrees of freedom, overarching view', 2, None, @@ -124,10 +122,33 @@ doconce format html week35.do.txt --html_style=bootstrap --pygments_html_style=d 2, None, 'testing-the-means-squared-error-as-function-of-complexity'), - ('More preprocessing examples, Franke function and regression', + ('More preprocessing examples, two-dimensional example, the ' + 'Franke function', 2, None, - 'more-preprocessing-examples-franke-function-and-regression'), + 'more-preprocessing-examples-two-dimensional-example-the-franke-function'), + ('To think about, first part', + 2, + None, + 'to-think-about-first-part'), + ('More thinking', 2, None, 'more-thinking'), + ('Still thinking', 2, None, 'still-thinking'), + ('What does centering (subtracting the mean values) mean ' + 'mathematically?', + 2, + None, + 'what-does-centering-subtracting-the-mean-values-mean-mathematically'), + ('Further Manipulations', 2, None, 'further-manipulations'), + ('Wrapping it up', 2, None, 'wrapping-it-up'), + ('Linear Regression code, Intercept handling first', + 2, + None, + 'linear-regression-code-intercept-handling-first'), + ('The Boston housing data example', + 2, + None, + 'the-boston-housing-data-example'), + ('Housing data, the code', 2, None, 'housing-data-the-code'), ('Material for lecture Thursday, August 31', 2, None, @@ -226,28 +247,7 @@ doconce format html week35.do.txt --html_style=bootstrap --pygments_html_style=d ('Deriving the Lasso Regression Equations', 2, None, - 'deriving-the-lasso-regression-equations'), - ('Exercises for week 35', 2, None, 'exercises-for-week-35'), - ('Exercise 1: Setting up various Python environments', - 2, - None, - 'exercise-1-setting-up-various-python-environments'), - ('Exercise 2: making your own data and exploring scikit-learn', - 2, - None, - 'exercise-2-making-your-own-data-and-exploring-scikit-learn'), - ('Exercise 3: Normalizing our data', - 2, - None, - 'exercise-3-normalizing-our-data'), - ('Exercise 4: Adding Ridge Regression', - 2, - None, - 'exercise-4-adding-ridge-regression'), - ('Exercise 5: Analytical exercises', - 2, - None, - 'exercise-5-analytical-exercises')]} + 'deriving-the-lasso-regression-equations')]} end of tocinfo --> @@ -299,62 +299,63 @@ MathJax.Hub.Config({
  • Other useful relations
  • Meet the Hessian Matrix
  • Interpretations and optimizing our parameters
  • -
  • Examples relevant for the exercises
  • +
  • Example relevant for the exercises
  • Own code for Ordinary Least Squares
  • Adding error analysis and training set up
  • Splitting our Data in Training and Test data
  • -
  • Examples
  • +
  • The complete code with a simple data set
  • Making your own test-train splitting
  • -
  • The Boston housing data example
  • -
  • Housing data, the code
  • -
  • Reducing the number of degrees of freedom, overarching view
  • -
  • Preprocessing our data
  • -
  • Functionality in Scikit-Learn
  • -
  • More preprocessing
  • -
  • Frequently used scaling functions
  • -
  • Example of own Standard scaling
  • -
  • Min-Max Scaling
  • -
  • Testing the Means Squared Error as function of Complexity
  • -
  • More preprocessing examples, Franke function and regression
  • -
  • Material for lecture Thursday, August 31
  • -
  • Mathematical Interpretation of Ordinary Least Squares
  • -
  • Residual Error
  • -
  • Simple case
  • -
  • The singular value decomposition
  • -
  • Linear Regression Problems
  • -
  • Fixing the singularity
  • -
  • Basic math of the SVD
  • -
  • The SVD, a Fantastic Algorithm
  • -
  • Economy-size SVD
  • -
  • Codes for the SVD
  • -
  • Note about SVD Calculations
  • -
  • Mathematics of the SVD and implications
  • -
  • Example Matrix
  • -
  • Setting up the Matrix to be inverted
  • -
  • Further properties (important for our analyses later)
  • -
  • Meet the Covariance Matrix
  • -
  • Introducing the Covariance and Correlation functions
  • -
  • Covariance and Correlation Matrix
  • -
  • Correlation Function and Design/Feature Matrix
  • -
  • Covariance Matrix Examples
  • -
  • Correlation Matrix
  • -
  • Correlation Matrix with Pandas
  • -
  • Correlation Matrix with Pandas and the Franke function
  • -
  • Rewriting the Covariance and/or Correlation Matrix
  • -
  • Linking with the SVD
  • -
  • What does it mean?
  • -
  • And finally \( \boldsymbol{X}\boldsymbol{X}^T \)
  • -
  • Ridge and LASSO Regression
  • -
  • Deriving the Ridge Regression Equations
  • -
  • Interpreting the Ridge results
  • -
  • More interpretations
  • -
  • Deriving the Lasso Regression Equations
  • -
  • Exercises for week 35
  • -
  • Exercise 1: Setting up various Python environments
  • -
  • Exercise 2: making your own data and exploring scikit-learn
  • -
  • Exercise 3: Normalizing our data
  • -
  • Exercise 4: Adding Ridge Regression
  • -
  • Exercise 5: Analytical exercises
  • +
  • Reducing the number of degrees of freedom, overarching view
  • +
  • Preprocessing our data
  • +
  • Functionality in Scikit-Learn
  • +
  • More preprocessing
  • +
  • Frequently used scaling functions
  • +
  • Example of own Standard scaling
  • +
  • Min-Max Scaling
  • +
  • Testing the Means Squared Error as function of Complexity
  • +
  • More preprocessing examples, two-dimensional example, the Franke function
  • +
  • To think about, first part
  • +
  • More thinking
  • +
  • Still thinking
  • +
  • What does centering (subtracting the mean values) mean mathematically?
  • +
  • Further Manipulations
  • +
  • Wrapping it up
  • +
  • Linear Regression code, Intercept handling first
  • +
  • The Boston housing data example
  • +
  • Housing data, the code
  • +
  • Material for lecture Thursday, August 31
  • +
  • Mathematical Interpretation of Ordinary Least Squares
  • +
  • Residual Error
  • +
  • Simple case
  • +
  • The singular value decomposition
  • +
  • Linear Regression Problems
  • +
  • Fixing the singularity
  • +
  • Basic math of the SVD
  • +
  • The SVD, a Fantastic Algorithm
  • +
  • Economy-size SVD
  • +
  • Codes for the SVD
  • +
  • Note about SVD Calculations
  • +
  • Mathematics of the SVD and implications
  • +
  • Example Matrix
  • +
  • Setting up the Matrix to be inverted
  • +
  • Further properties (important for our analyses later)
  • +
  • Meet the Covariance Matrix
  • +
  • Introducing the Covariance and Correlation functions
  • +
  • Covariance and Correlation Matrix
  • +
  • Correlation Function and Design/Feature Matrix
  • +
  • Covariance Matrix Examples
  • +
  • Correlation Matrix
  • +
  • Correlation Matrix with Pandas
  • +
  • Correlation Matrix with Pandas and the Franke function
  • +
  • Rewriting the Covariance and/or Correlation Matrix
  • +
  • Linking with the SVD
  • +
  • What does it mean?
  • +
  • And finally \( \boldsymbol{X}\boldsymbol{X}^T \)
  • +
  • Ridge and LASSO Regression
  • +
  • Deriving the Ridge Regression Equations
  • +
  • Interpreting the Ridge results
  • +
  • More interpretations
  • +
  • Deriving the Lasso Regression Equations
  • @@ -366,49 +367,149 @@ MathJax.Hub.Config({

     

     

     

    -

    The singular value decomposition

    +

    Linear Regression code, Intercept handling first

    -
    -
    - - -

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

    This code shows a simple first-order fit to a data set using the above transformed data, where we consider the role of the intercept first, by either excluding it or including it (code example thanks to Øyvind Sigmundson Schøyen). Here our scaling of the data is done by subtracting the mean values only. +Note also that we do not split the data into training and test.

    -

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

    -

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

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

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

    +from sklearn.linear_model import LinearRegression -

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

    + +np.random.seed(2021) + +def MSE(y_data,y_model): + n = np.size(y_model) + return np.sum((y_data-y_model)**2)/n + + +def fit_beta(X, y): + return np.linalg.pinv(X.T @ X) @ X.T @ y + + +true_beta = [2, 0.5, 3.7] + +x = np.linspace(0, 1, 11) +y = np.sum( + np.asarray([x ** p * b for p, b in enumerate(true_beta)]), axis=0 +) + 0.1 * np.random.normal(size=len(x)) + +degree = 3 +X = np.zeros((len(x), degree)) + +# Include the intercept in the design matrix +for p in range(degree): + X[:, p] = x ** p + +beta = fit_beta(X, y) + +# Intercept is included in the design matrix +skl = LinearRegression(fit_intercept=False).fit(X, y) + +print(f"True beta: {true_beta}") +print(f"Fitted beta: {beta}") +print(f"Sklearn fitted beta: {skl.coef_}") +ypredictOwn = X @ beta +ypredictSKL = skl.predict(X) +print(f"MSE with intercept column") +print(MSE(y,ypredictOwn)) +print(f"MSE with intercept column from SKL") +print(MSE(y,ypredictSKL)) + + +plt.figure() +plt.scatter(x, y, label="Data") +plt.plot(x, X @ beta, label="Fit") +plt.plot(x, skl.predict(X), label="Sklearn (fit_intercept=False)") + + +# Do not include the intercept in the design matrix +X = np.zeros((len(x), degree - 1)) + +for p in range(degree - 1): + X[:, p] = x ** (p + 1) + +# Intercept is not included in the design matrix +skl = LinearRegression(fit_intercept=True).fit(X, y) + +# Use centered values for X and y when computing coefficients +y_offset = np.average(y, axis=0) +X_offset = np.average(X, axis=0) + +beta = fit_beta(X - X_offset, y - y_offset) +intercept = np.mean(y_offset - X_offset @ beta) + +print(f"Manual intercept: {intercept}") +print(f"Fitted beta (wiothout intercept): {beta}") +print(f"Sklearn intercept: {skl.intercept_}") +print(f"Sklearn fitted beta (without intercept): {skl.coef_}") +ypredictOwn = X @ beta +ypredictSKL = skl.predict(X) +print(f"MSE with Manual intercept") +print(MSE(y,ypredictOwn+intercept)) +print(f"MSE with Sklearn intercept") +print(MSE(y,ypredictSKL)) + +plt.plot(x, X @ beta + intercept, "--", label="Fit (manual intercept)") +plt.plot(x, skl.predict(X), "--", label="Sklearn (fit_intercept=True)") +plt.grid() +plt.legend() + +plt.show() +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +

    The intercept is the value of our output/target variable +when all our features are zero and our function crosses the \( y \)-axis (for a one-dimensional case). +

    + +

    Printing the MSE, we see first that both methods give the same MSE, as +they should. However, when we move to for example Ridge regression, +the way we treat the intercept may give a larger or smaller MSE, +meaning that the MSE can be penalized by the value of the +intercept. Not including the intercept in the fit, means that the +regularization term does not include \( \beta_0 \). For different values +of \( \lambda \), this may lead to differeing MSE values. +

    + +

    To remind the reader, the regularization term, with the intercept in Ridge regression is given by

    +$$ +\lambda \vert\vert \boldsymbol{\beta} \vert\vert_2^2 = \lambda \sum_{j=0}^{p-1}\beta_j^2, +$$ + +

    but when we take out the intercept, this equation becomes

    +$$ +\lambda \vert\vert \boldsymbol{\beta} \vert\vert_2^2 = \lambda \sum_{j=1}^{p-1}\beta_j^2. +$$ + +

    For Lasso regression we have

    +$$ +\lambda \vert\vert \boldsymbol{\beta} \vert\vert_1 = \lambda \sum_{j=1}^{p-1}\vert\beta_j\vert. +$$ + +

    It means that, when scaling the design matrix and the outputs/targets, by subtracting the mean values, we have an optimization problem which is not penalized by the intercept. The MSE value can then be smaller since it focuses only on the remaining quantities. If we however bring back the intercept, we will get an MSE which then contains the intercept. This becomes more important when we discuss Ridge and Lasso regression next week.

    @@ -435,7 +536,7 @@ reduced to the statistically relevant features.

  • 47
  • 48
  • ...
  • -
  • 68
  • +
  • 74
  • »
  • diff --git a/doc/pub/week35/html/._week35-bs039.html b/doc/pub/week35/html/._week35-bs039.html index 0bbb10d61..edea5ba23 100644 --- a/doc/pub/week35/html/._week35-bs039.html +++ b/doc/pub/week35/html/._week35-bs039.html @@ -75,10 +75,10 @@ doconce format html week35.do.txt --html_style=bootstrap --pygments_html_style=d 2, None, 'interpretations-and-optimizing-our-parameters'), - ('Examples relevant for the exercises', + ('Example relevant for the exercises', 2, None, - 'examples-relevant-for-the-exercises'), + 'example-relevant-for-the-exercises'), ('Own code for Ordinary Least Squares', 2, None, @@ -91,16 +91,14 @@ doconce format html week35.do.txt --html_style=bootstrap --pygments_html_style=d 2, None, 'splitting-our-data-in-training-and-test-data'), - ('Examples', 2, None, 'examples'), + ('The complete code with a simple data set', + 2, + None, + 'the-complete-code-with-a-simple-data-set'), ('Making your own test-train splitting', 2, None, 'making-your-own-test-train-splitting'), - ('The Boston housing data example', - 2, - None, - 'the-boston-housing-data-example'), - ('Housing data, the code', 2, None, 'housing-data-the-code'), ('Reducing the number of degrees of freedom, overarching view', 2, None, @@ -124,10 +122,33 @@ doconce format html week35.do.txt --html_style=bootstrap --pygments_html_style=d 2, None, 'testing-the-means-squared-error-as-function-of-complexity'), - ('More preprocessing examples, Franke function and regression', + ('More preprocessing examples, two-dimensional example, the ' + 'Franke function', 2, None, - 'more-preprocessing-examples-franke-function-and-regression'), + 'more-preprocessing-examples-two-dimensional-example-the-franke-function'), + ('To think about, first part', + 2, + None, + 'to-think-about-first-part'), + ('More thinking', 2, None, 'more-thinking'), + ('Still thinking', 2, None, 'still-thinking'), + ('What does centering (subtracting the mean values) mean ' + 'mathematically?', + 2, + None, + 'what-does-centering-subtracting-the-mean-values-mean-mathematically'), + ('Further Manipulations', 2, None, 'further-manipulations'), + ('Wrapping it up', 2, None, 'wrapping-it-up'), + ('Linear Regression code, Intercept handling first', + 2, + None, + 'linear-regression-code-intercept-handling-first'), + ('The Boston housing data example', + 2, + None, + 'the-boston-housing-data-example'), + ('Housing data, the code', 2, None, 'housing-data-the-code'), ('Material for lecture Thursday, August 31', 2, None, @@ -226,28 +247,7 @@ doconce format html week35.do.txt --html_style=bootstrap --pygments_html_style=d ('Deriving the Lasso Regression Equations', 2, None, - 'deriving-the-lasso-regression-equations'), - ('Exercises for week 35', 2, None, 'exercises-for-week-35'), - ('Exercise 1: Setting up various Python environments', - 2, - None, - 'exercise-1-setting-up-various-python-environments'), - ('Exercise 2: making your own data and exploring scikit-learn', - 2, - None, - 'exercise-2-making-your-own-data-and-exploring-scikit-learn'), - ('Exercise 3: Normalizing our data', - 2, - None, - 'exercise-3-normalizing-our-data'), - ('Exercise 4: Adding Ridge Regression', - 2, - None, - 'exercise-4-adding-ridge-regression'), - ('Exercise 5: Analytical exercises', - 2, - None, - 'exercise-5-analytical-exercises')]} + 'deriving-the-lasso-regression-equations')]} end of tocinfo --> @@ -299,62 +299,63 @@ MathJax.Hub.Config({
  • Other useful relations
  • Meet the Hessian Matrix
  • Interpretations and optimizing our parameters
  • -
  • Examples relevant for the exercises
  • +
  • Example relevant for the exercises
  • Own code for Ordinary Least Squares
  • Adding error analysis and training set up
  • Splitting our Data in Training and Test data
  • -
  • Examples
  • +
  • The complete code with a simple data set
  • Making your own test-train splitting
  • -
  • The Boston housing data example
  • -
  • Housing data, the code
  • -
  • Reducing the number of degrees of freedom, overarching view
  • -
  • Preprocessing our data
  • -
  • Functionality in Scikit-Learn
  • -
  • More preprocessing
  • -
  • Frequently used scaling functions
  • -
  • Example of own Standard scaling
  • -
  • Min-Max Scaling
  • -
  • Testing the Means Squared Error as function of Complexity
  • -
  • More preprocessing examples, Franke function and regression
  • -
  • Material for lecture Thursday, August 31
  • -
  • Mathematical Interpretation of Ordinary Least Squares
  • -
  • Residual Error
  • -
  • Simple case
  • -
  • The singular value decomposition
  • -
  • Linear Regression Problems
  • -
  • Fixing the singularity
  • -
  • Basic math of the SVD
  • -
  • The SVD, a Fantastic Algorithm
  • -
  • Economy-size SVD
  • -
  • Codes for the SVD
  • -
  • Note about SVD Calculations
  • -
  • Mathematics of the SVD and implications
  • -
  • Example Matrix
  • -
  • Setting up the Matrix to be inverted
  • -
  • Further properties (important for our analyses later)
  • -
  • Meet the Covariance Matrix
  • -
  • Introducing the Covariance and Correlation functions
  • -
  • Covariance and Correlation Matrix
  • -
  • Correlation Function and Design/Feature Matrix
  • -
  • Covariance Matrix Examples
  • -
  • Correlation Matrix
  • -
  • Correlation Matrix with Pandas
  • -
  • Correlation Matrix with Pandas and the Franke function
  • -
  • Rewriting the Covariance and/or Correlation Matrix
  • -
  • Linking with the SVD
  • -
  • What does it mean?
  • -
  • And finally \( \boldsymbol{X}\boldsymbol{X}^T \)
  • -
  • Ridge and LASSO Regression
  • -
  • Deriving the Ridge Regression Equations
  • -
  • Interpreting the Ridge results
  • -
  • More interpretations
  • -
  • Deriving the Lasso Regression Equations
  • -
  • Exercises for week 35
  • -
  • Exercise 1: Setting up various Python environments
  • -
  • Exercise 2: making your own data and exploring scikit-learn
  • -
  • Exercise 3: Normalizing our data
  • -
  • Exercise 4: Adding Ridge Regression
  • -
  • Exercise 5: Analytical exercises
  • +
  • Reducing the number of degrees of freedom, overarching view
  • +
  • Preprocessing our data
  • +
  • Functionality in Scikit-Learn
  • +
  • More preprocessing
  • +
  • Frequently used scaling functions
  • +
  • Example of own Standard scaling
  • +
  • Min-Max Scaling
  • +
  • Testing the Means Squared Error as function of Complexity
  • +
  • More preprocessing examples, two-dimensional example, the Franke function
  • +
  • To think about, first part
  • +
  • More thinking
  • +
  • Still thinking
  • +
  • What does centering (subtracting the mean values) mean mathematically?
  • +
  • Further Manipulations
  • +
  • Wrapping it up
  • +
  • Linear Regression code, Intercept handling first
  • +
  • The Boston housing data example
  • +
  • Housing data, the code
  • +
  • Material for lecture Thursday, August 31
  • +
  • Mathematical Interpretation of Ordinary Least Squares
  • +
  • Residual Error
  • +
  • Simple case
  • +
  • The singular value decomposition
  • +
  • Linear Regression Problems
  • +
  • Fixing the singularity
  • +
  • Basic math of the SVD
  • +
  • The SVD, a Fantastic Algorithm
  • +
  • Economy-size SVD
  • +
  • Codes for the SVD
  • +
  • Note about SVD Calculations
  • +
  • Mathematics of the SVD and implications
  • +
  • Example Matrix
  • +
  • Setting up the Matrix to be inverted
  • +
  • Further properties (important for our analyses later)
  • +
  • Meet the Covariance Matrix
  • +
  • Introducing the Covariance and Correlation functions
  • +
  • Covariance and Correlation Matrix
  • +
  • Correlation Function and Design/Feature Matrix
  • +
  • Covariance Matrix Examples
  • +
  • Correlation Matrix
  • +
  • Correlation Matrix with Pandas
  • +
  • Correlation Matrix with Pandas and the Franke function
  • +
  • Rewriting the Covariance and/or Correlation Matrix
  • +
  • Linking with the SVD
  • +
  • What does it mean?
  • +
  • And finally \( \boldsymbol{X}\boldsymbol{X}^T \)
  • +
  • Ridge and LASSO Regression
  • +
  • Deriving the Ridge Regression Equations
  • +
  • Interpreting the Ridge results
  • +
  • More interpretations
  • +
  • Deriving the Lasso Regression Equations
  • @@ -365,56 +366,33 @@ MathJax.Hub.Config({

     

     

     

    - -

    Linear Regression Problems

    + +

    The Boston housing data example

    -

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

    - -

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

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

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

      @@ -440,7 +418,7 @@ This is equivalent to saying that the matrix \( \boldsymbol{X} \) has at least a
    • 48
    • 49
    • ...
    • -
    • 68
    • +
    • 74
    • »
    diff --git a/doc/pub/week35/html/._week35-bs040.html b/doc/pub/week35/html/._week35-bs040.html index fcc11309b..c4753d962 100644 --- a/doc/pub/week35/html/._week35-bs040.html +++ b/doc/pub/week35/html/._week35-bs040.html @@ -75,10 +75,10 @@ doconce format html week35.do.txt --html_style=bootstrap --pygments_html_style=d 2, None, 'interpretations-and-optimizing-our-parameters'), - ('Examples relevant for the exercises', + ('Example relevant for the exercises', 2, None, - 'examples-relevant-for-the-exercises'), + 'example-relevant-for-the-exercises'), ('Own code for Ordinary Least Squares', 2, None, @@ -91,16 +91,14 @@ doconce format html week35.do.txt --html_style=bootstrap --pygments_html_style=d 2, None, 'splitting-our-data-in-training-and-test-data'), - ('Examples', 2, None, 'examples'), + ('The complete code with a simple data set', + 2, + None, + 'the-complete-code-with-a-simple-data-set'), ('Making your own test-train splitting', 2, None, 'making-your-own-test-train-splitting'), - ('The Boston housing data example', - 2, - None, - 'the-boston-housing-data-example'), - ('Housing data, the code', 2, None, 'housing-data-the-code'), ('Reducing the number of degrees of freedom, overarching view', 2, None, @@ -124,10 +122,33 @@ doconce format html week35.do.txt --html_style=bootstrap --pygments_html_style=d 2, None, 'testing-the-means-squared-error-as-function-of-complexity'), - ('More preprocessing examples, Franke function and regression', + ('More preprocessing examples, two-dimensional example, the ' + 'Franke function', 2, None, - 'more-preprocessing-examples-franke-function-and-regression'), + 'more-preprocessing-examples-two-dimensional-example-the-franke-function'), + ('To think about, first part', + 2, + None, + 'to-think-about-first-part'), + ('More thinking', 2, None, 'more-thinking'), + ('Still thinking', 2, None, 'still-thinking'), + ('What does centering (subtracting the mean values) mean ' + 'mathematically?', + 2, + None, + 'what-does-centering-subtracting-the-mean-values-mean-mathematically'), + ('Further Manipulations', 2, None, 'further-manipulations'), + ('Wrapping it up', 2, None, 'wrapping-it-up'), + ('Linear Regression code, Intercept handling first', + 2, + None, + 'linear-regression-code-intercept-handling-first'), + ('The Boston housing data example', + 2, + None, + 'the-boston-housing-data-example'), + ('Housing data, the code', 2, None, 'housing-data-the-code'), ('Material for lecture Thursday, August 31', 2, None, @@ -226,28 +247,7 @@ doconce format html week35.do.txt --html_style=bootstrap --pygments_html_style=d ('Deriving the Lasso Regression Equations', 2, None, - 'deriving-the-lasso-regression-equations'), - ('Exercises for week 35', 2, None, 'exercises-for-week-35'), - ('Exercise 1: Setting up various Python environments', - 2, - None, - 'exercise-1-setting-up-various-python-environments'), - ('Exercise 2: making your own data and exploring scikit-learn', - 2, - None, - 'exercise-2-making-your-own-data-and-exploring-scikit-learn'), - ('Exercise 3: Normalizing our data', - 2, - None, - 'exercise-3-normalizing-our-data'), - ('Exercise 4: Adding Ridge Regression', - 2, - None, - 'exercise-4-adding-ridge-regression'), - ('Exercise 5: Analytical exercises', - 2, - None, - 'exercise-5-analytical-exercises')]} + 'deriving-the-lasso-regression-equations')]} end of tocinfo --> @@ -299,62 +299,63 @@ MathJax.Hub.Config({
  • Other useful relations
  • Meet the Hessian Matrix
  • Interpretations and optimizing our parameters
  • -
  • Examples relevant for the exercises
  • +
  • Example relevant for the exercises
  • Own code for Ordinary Least Squares
  • Adding error analysis and training set up
  • Splitting our Data in Training and Test data
  • -
  • Examples
  • +
  • The complete code with a simple data set
  • Making your own test-train splitting
  • -
  • The Boston housing data example
  • -
  • Housing data, the code
  • -
  • Reducing the number of degrees of freedom, overarching view
  • -
  • Preprocessing our data
  • -
  • Functionality in Scikit-Learn
  • -
  • More preprocessing
  • -
  • Frequently used scaling functions
  • -
  • Example of own Standard scaling
  • -
  • Min-Max Scaling
  • -
  • Testing the Means Squared Error as function of Complexity
  • -
  • More preprocessing examples, Franke function and regression
  • -
  • Material for lecture Thursday, August 31
  • -
  • Mathematical Interpretation of Ordinary Least Squares
  • -
  • Residual Error
  • -
  • Simple case
  • -
  • The singular value decomposition
  • -
  • Linear Regression Problems
  • -
  • Fixing the singularity
  • -
  • Basic math of the SVD
  • -
  • The SVD, a Fantastic Algorithm
  • -
  • Economy-size SVD
  • -
  • Codes for the SVD
  • -
  • Note about SVD Calculations
  • -
  • Mathematics of the SVD and implications
  • -
  • Example Matrix
  • -
  • Setting up the Matrix to be inverted
  • -
  • Further properties (important for our analyses later)
  • -
  • Meet the Covariance Matrix
  • -
  • Introducing the Covariance and Correlation functions
  • -
  • Covariance and Correlation Matrix
  • -
  • Correlation Function and Design/Feature Matrix
  • -
  • Covariance Matrix Examples
  • -
  • Correlation Matrix
  • -
  • Correlation Matrix with Pandas
  • -
  • Correlation Matrix with Pandas and the Franke function
  • -
  • Rewriting the Covariance and/or Correlation Matrix
  • -
  • Linking with the SVD
  • -
  • What does it mean?
  • -
  • And finally \( \boldsymbol{X}\boldsymbol{X}^T \)
  • -
  • Ridge and LASSO Regression
  • -
  • Deriving the Ridge Regression Equations
  • -
  • Interpreting the Ridge results
  • -
  • More interpretations
  • -
  • Deriving the Lasso Regression Equations
  • -
  • Exercises for week 35
  • -
  • Exercise 1: Setting up various Python environments
  • -
  • Exercise 2: making your own data and exploring scikit-learn
  • -
  • Exercise 3: Normalizing our data
  • -
  • Exercise 4: Adding Ridge Regression
  • -
  • Exercise 5: Analytical exercises
  • +
  • Reducing the number of degrees of freedom, overarching view
  • +
  • Preprocessing our data
  • +
  • Functionality in Scikit-Learn
  • +
  • More preprocessing
  • +
  • Frequently used scaling functions
  • +
  • Example of own Standard scaling
  • +
  • Min-Max Scaling
  • +
  • Testing the Means Squared Error as function of Complexity
  • +
  • More preprocessing examples, two-dimensional example, the Franke function
  • +
  • To think about, first part
  • +
  • More thinking
  • +
  • Still thinking
  • +
  • What does centering (subtracting the mean values) mean mathematically?
  • +
  • Further Manipulations
  • +
  • Wrapping it up
  • +
  • Linear Regression code, Intercept handling first
  • +
  • The Boston housing data example
  • +
  • Housing data, the code
  • +
  • Material for lecture Thursday, August 31
  • +
  • Mathematical Interpretation of Ordinary Least Squares
  • +
  • Residual Error
  • +
  • Simple case
  • +
  • The singular value decomposition
  • +
  • Linear Regression Problems
  • +
  • Fixing the singularity
  • +
  • Basic math of the SVD
  • +
  • The SVD, a Fantastic Algorithm
  • +
  • Economy-size SVD
  • +
  • Codes for the SVD
  • +
  • Note about SVD Calculations
  • +
  • Mathematics of the SVD and implications
  • +
  • Example Matrix
  • +
  • Setting up the Matrix to be inverted
  • +
  • Further properties (important for our analyses later)
  • +
  • Meet the Covariance Matrix
  • +
  • Introducing the Covariance and Correlation functions
  • +
  • Covariance and Correlation Matrix
  • +
  • Correlation Function and Design/Feature Matrix
  • +
  • Covariance Matrix Examples
  • +
  • Correlation Matrix
  • +
  • Correlation Matrix with Pandas
  • +
  • Correlation Matrix with Pandas and the Franke function
  • +
  • Rewriting the Covariance and/or Correlation Matrix
  • +
  • Linking with the SVD
  • +
  • What does it mean?
  • +
  • And finally \( \boldsymbol{X}\boldsymbol{X}^T \)
  • +
  • Ridge and LASSO Regression
  • +
  • Deriving the Ridge Regression Equations
  • +
  • Interpreting the Ridge results
  • +
  • More interpretations
  • +
  • Deriving the Lasso Regression Equations
  • @@ -366,29 +367,346 @@ MathJax.Hub.Config({

     

     

     

    -

    Fixing the singularity

    +

    Housing data, the code

    +

    We start by importing the libraries

    -

    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} -$$ + +
    +
    +
    +
    +
    +
    import numpy as np
    +import matplotlib.pyplot as plt 
     
    -

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

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

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

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

    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.

    @@ -415,7 +733,7 @@ $$

  • 49
  • 50
  • ...
  • -
  • 68
  • +
  • 74
  • »
  • diff --git a/doc/pub/week35/html/._week35-bs041.html b/doc/pub/week35/html/._week35-bs041.html index fef10bca6..5215917d4 100644 --- a/doc/pub/week35/html/._week35-bs041.html +++ b/doc/pub/week35/html/._week35-bs041.html @@ -75,10 +75,10 @@ doconce format html week35.do.txt --html_style=bootstrap --pygments_html_style=d 2, None, 'interpretations-and-optimizing-our-parameters'), - ('Examples relevant for the exercises', + ('Example relevant for the exercises', 2, None, - 'examples-relevant-for-the-exercises'), + 'example-relevant-for-the-exercises'), ('Own code for Ordinary Least Squares', 2, None, @@ -91,16 +91,14 @@ doconce format html week35.do.txt --html_style=bootstrap --pygments_html_style=d 2, None, 'splitting-our-data-in-training-and-test-data'), - ('Examples', 2, None, 'examples'), + ('The complete code with a simple data set', + 2, + None, + 'the-complete-code-with-a-simple-data-set'), ('Making your own test-train splitting', 2, None, 'making-your-own-test-train-splitting'), - ('The Boston housing data example', - 2, - None, - 'the-boston-housing-data-example'), - ('Housing data, the code', 2, None, 'housing-data-the-code'), ('Reducing the number of degrees of freedom, overarching view', 2, None, @@ -124,10 +122,33 @@ doconce format html week35.do.txt --html_style=bootstrap --pygments_html_style=d 2, None, 'testing-the-means-squared-error-as-function-of-complexity'), - ('More preprocessing examples, Franke function and regression', + ('More preprocessing examples, two-dimensional example, the ' + 'Franke function', 2, None, - 'more-preprocessing-examples-franke-function-and-regression'), + 'more-preprocessing-examples-two-dimensional-example-the-franke-function'), + ('To think about, first part', + 2, + None, + 'to-think-about-first-part'), + ('More thinking', 2, None, 'more-thinking'), + ('Still thinking', 2, None, 'still-thinking'), + ('What does centering (subtracting the mean values) mean ' + 'mathematically?', + 2, + None, + 'what-does-centering-subtracting-the-mean-values-mean-mathematically'), + ('Further Manipulations', 2, None, 'further-manipulations'), + ('Wrapping it up', 2, None, 'wrapping-it-up'), + ('Linear Regression code, Intercept handling first', + 2, + None, + 'linear-regression-code-intercept-handling-first'), + ('The Boston housing data example', + 2, + None, + 'the-boston-housing-data-example'), + ('Housing data, the code', 2, None, 'housing-data-the-code'), ('Material for lecture Thursday, August 31', 2, None, @@ -226,28 +247,7 @@ doconce format html week35.do.txt --html_style=bootstrap --pygments_html_style=d ('Deriving the Lasso Regression Equations', 2, None, - 'deriving-the-lasso-regression-equations'), - ('Exercises for week 35', 2, None, 'exercises-for-week-35'), - ('Exercise 1: Setting up various Python environments', - 2, - None, - 'exercise-1-setting-up-various-python-environments'), - ('Exercise 2: making your own data and exploring scikit-learn', - 2, - None, - 'exercise-2-making-your-own-data-and-exploring-scikit-learn'), - ('Exercise 3: Normalizing our data', - 2, - None, - 'exercise-3-normalizing-our-data'), - ('Exercise 4: Adding Ridge Regression', - 2, - None, - 'exercise-4-adding-ridge-regression'), - ('Exercise 5: Analytical exercises', - 2, - None, - 'exercise-5-analytical-exercises')]} + 'deriving-the-lasso-regression-equations')]} end of tocinfo --> @@ -299,62 +299,63 @@ MathJax.Hub.Config({
  • Other useful relations
  • Meet the Hessian Matrix
  • Interpretations and optimizing our parameters
  • -
  • Examples relevant for the exercises
  • +
  • Example relevant for the exercises
  • Own code for Ordinary Least Squares
  • Adding error analysis and training set up
  • Splitting our Data in Training and Test data
  • -
  • Examples
  • +
  • The complete code with a simple data set
  • Making your own test-train splitting
  • -
  • The Boston housing data example
  • -
  • Housing data, the code
  • -
  • Reducing the number of degrees of freedom, overarching view
  • -
  • Preprocessing our data
  • -
  • Functionality in Scikit-Learn
  • -
  • More preprocessing
  • -
  • Frequently used scaling functions
  • -
  • Example of own Standard scaling
  • -
  • Min-Max Scaling
  • -
  • Testing the Means Squared Error as function of Complexity
  • -
  • More preprocessing examples, Franke function and regression
  • -
  • Material for lecture Thursday, August 31
  • -
  • Mathematical Interpretation of Ordinary Least Squares
  • -
  • Residual Error
  • -
  • Simple case
  • -
  • The singular value decomposition
  • -
  • Linear Regression Problems
  • -
  • Fixing the singularity
  • -
  • Basic math of the SVD
  • -
  • The SVD, a Fantastic Algorithm
  • -
  • Economy-size SVD
  • -
  • Codes for the SVD
  • -
  • Note about SVD Calculations
  • -
  • Mathematics of the SVD and implications
  • -
  • Example Matrix
  • -
  • Setting up the Matrix to be inverted
  • -
  • Further properties (important for our analyses later)
  • -
  • Meet the Covariance Matrix
  • -
  • Introducing the Covariance and Correlation functions
  • -
  • Covariance and Correlation Matrix
  • -
  • Correlation Function and Design/Feature Matrix
  • -
  • Covariance Matrix Examples
  • -
  • Correlation Matrix
  • -
  • Correlation Matrix with Pandas
  • -
  • Correlation Matrix with Pandas and the Franke function
  • -
  • Rewriting the Covariance and/or Correlation Matrix
  • -
  • Linking with the SVD
  • -
  • What does it mean?
  • -
  • And finally \( \boldsymbol{X}\boldsymbol{X}^T \)
  • -
  • Ridge and LASSO Regression
  • -
  • Deriving the Ridge Regression Equations
  • -
  • Interpreting the Ridge results
  • -
  • More interpretations
  • -
  • Deriving the Lasso Regression Equations
  • -
  • Exercises for week 35
  • -
  • Exercise 1: Setting up various Python environments
  • -
  • Exercise 2: making your own data and exploring scikit-learn
  • -
  • Exercise 3: Normalizing our data
  • -
  • Exercise 4: Adding Ridge Regression
  • -
  • Exercise 5: Analytical exercises
  • +
  • Reducing the number of degrees of freedom, overarching view
  • +
  • Preprocessing our data
  • +
  • Functionality in Scikit-Learn
  • +
  • More preprocessing
  • +
  • Frequently used scaling functions
  • +
  • Example of own Standard scaling
  • +
  • Min-Max Scaling
  • +
  • Testing the Means Squared Error as function of Complexity
  • +
  • More preprocessing examples, two-dimensional example, the Franke function
  • +
  • To think about, first part
  • +
  • More thinking
  • +
  • Still thinking
  • +
  • What does centering (subtracting the mean values) mean mathematically?
  • +
  • Further Manipulations
  • +
  • Wrapping it up
  • +
  • Linear Regression code, Intercept handling first
  • +
  • The Boston housing data example
  • +
  • Housing data, the code
  • +
  • Material for lecture Thursday, August 31
  • +
  • Mathematical Interpretation of Ordinary Least Squares
  • +
  • Residual Error
  • +
  • Simple case
  • +
  • The singular value decomposition
  • +
  • Linear Regression Problems
  • +
  • Fixing the singularity
  • +
  • Basic math of the SVD
  • +
  • The SVD, a Fantastic Algorithm
  • +
  • Economy-size SVD
  • +
  • Codes for the SVD
  • +
  • Note about SVD Calculations
  • +
  • Mathematics of the SVD and implications
  • +
  • Example Matrix
  • +
  • Setting up the Matrix to be inverted
  • +
  • Further properties (important for our analyses later)
  • +
  • Meet the Covariance Matrix
  • +
  • Introducing the Covariance and Correlation functions
  • +
  • Covariance and Correlation Matrix
  • +
  • Correlation Function and Design/Feature Matrix
  • +
  • Covariance Matrix Examples
  • +
  • Correlation Matrix
  • +
  • Correlation Matrix with Pandas
  • +
  • Correlation Matrix with Pandas and the Franke function
  • +
  • Rewriting the Covariance and/or Correlation Matrix
  • +
  • Linking with the SVD
  • +
  • What does it mean?
  • +
  • And finally \( \boldsymbol{X}\boldsymbol{X}^T \)
  • +
  • Ridge and LASSO Regression
  • +
  • Deriving the Ridge Regression Equations
  • +
  • Interpreting the Ridge results
  • +
  • More interpretations
  • +
  • Deriving the Lasso Regression Equations
  • @@ -366,41 +367,7 @@ MathJax.Hub.Config({

     

     

     

    -

    Basic math of the SVD

    - -

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

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

    and the eigenvalues are given by the diagonal matrix

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

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

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

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

    - -

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

    +

    Material for lecture Thursday, August 31

    @@ -427,7 +394,7 @@ $$

  • 50
  • 51
  • ...
  • -
  • 68
  • +
  • 74
  • »
  • diff --git a/doc/pub/week35/html/._week35-bs042.html b/doc/pub/week35/html/._week35-bs042.html index a09bb805e..0bd746378 100644 --- a/doc/pub/week35/html/._week35-bs042.html +++ b/doc/pub/week35/html/._week35-bs042.html @@ -75,10 +75,10 @@ doconce format html week35.do.txt --html_style=bootstrap --pygments_html_style=d 2, None, 'interpretations-and-optimizing-our-parameters'), - ('Examples relevant for the exercises', + ('Example relevant for the exercises', 2, None, - 'examples-relevant-for-the-exercises'), + 'example-relevant-for-the-exercises'), ('Own code for Ordinary Least Squares', 2, None, @@ -91,16 +91,14 @@ doconce format html week35.do.txt --html_style=bootstrap --pygments_html_style=d 2, None, 'splitting-our-data-in-training-and-test-data'), - ('Examples', 2, None, 'examples'), + ('The complete code with a simple data set', + 2, + None, + 'the-complete-code-with-a-simple-data-set'), ('Making your own test-train splitting', 2, None, 'making-your-own-test-train-splitting'), - ('The Boston housing data example', - 2, - None, - 'the-boston-housing-data-example'), - ('Housing data, the code', 2, None, 'housing-data-the-code'), ('Reducing the number of degrees of freedom, overarching view', 2, None, @@ -124,10 +122,33 @@ doconce format html week35.do.txt --html_style=bootstrap --pygments_html_style=d 2, None, 'testing-the-means-squared-error-as-function-of-complexity'), - ('More preprocessing examples, Franke function and regression', + ('More preprocessing examples, two-dimensional example, the ' + 'Franke function', 2, None, - 'more-preprocessing-examples-franke-function-and-regression'), + 'more-preprocessing-examples-two-dimensional-example-the-franke-function'), + ('To think about, first part', + 2, + None, + 'to-think-about-first-part'), + ('More thinking', 2, None, 'more-thinking'), + ('Still thinking', 2, None, 'still-thinking'), + ('What does centering (subtracting the mean values) mean ' + 'mathematically?', + 2, + None, + 'what-does-centering-subtracting-the-mean-values-mean-mathematically'), + ('Further Manipulations', 2, None, 'further-manipulations'), + ('Wrapping it up', 2, None, 'wrapping-it-up'), + ('Linear Regression code, Intercept handling first', + 2, + None, + 'linear-regression-code-intercept-handling-first'), + ('The Boston housing data example', + 2, + None, + 'the-boston-housing-data-example'), + ('Housing data, the code', 2, None, 'housing-data-the-code'), ('Material for lecture Thursday, August 31', 2, None, @@ -226,28 +247,7 @@ doconce format html week35.do.txt --html_style=bootstrap --pygments_html_style=d ('Deriving the Lasso Regression Equations', 2, None, - 'deriving-the-lasso-regression-equations'), - ('Exercises for week 35', 2, None, 'exercises-for-week-35'), - ('Exercise 1: Setting up various Python environments', - 2, - None, - 'exercise-1-setting-up-various-python-environments'), - ('Exercise 2: making your own data and exploring scikit-learn', - 2, - None, - 'exercise-2-making-your-own-data-and-exploring-scikit-learn'), - ('Exercise 3: Normalizing our data', - 2, - None, - 'exercise-3-normalizing-our-data'), - ('Exercise 4: Adding Ridge Regression', - 2, - None, - 'exercise-4-adding-ridge-regression'), - ('Exercise 5: Analytical exercises', - 2, - None, - 'exercise-5-analytical-exercises')]} + 'deriving-the-lasso-regression-equations')]} end of tocinfo --> @@ -299,62 +299,63 @@ MathJax.Hub.Config({
  • Other useful relations
  • Meet the Hessian Matrix
  • Interpretations and optimizing our parameters
  • -
  • Examples relevant for the exercises
  • +
  • Example relevant for the exercises
  • Own code for Ordinary Least Squares
  • Adding error analysis and training set up
  • Splitting our Data in Training and Test data
  • -
  • Examples
  • +
  • The complete code with a simple data set
  • Making your own test-train splitting
  • -
  • The Boston housing data example
  • -
  • Housing data, the code
  • -
  • Reducing the number of degrees of freedom, overarching view
  • -
  • Preprocessing our data
  • -
  • Functionality in Scikit-Learn
  • -
  • More preprocessing
  • -
  • Frequently used scaling functions
  • -
  • Example of own Standard scaling
  • -
  • Min-Max Scaling
  • -
  • Testing the Means Squared Error as function of Complexity
  • -
  • More preprocessing examples, Franke function and regression
  • -
  • Material for lecture Thursday, August 31
  • -
  • Mathematical Interpretation of Ordinary Least Squares
  • -
  • Residual Error
  • -
  • Simple case
  • -
  • The singular value decomposition
  • -
  • Linear Regression Problems
  • -
  • Fixing the singularity
  • -
  • Basic math of the SVD
  • -
  • The SVD, a Fantastic Algorithm
  • -
  • Economy-size SVD
  • -
  • Codes for the SVD
  • -
  • Note about SVD Calculations
  • -
  • Mathematics of the SVD and implications
  • -
  • Example Matrix
  • -
  • Setting up the Matrix to be inverted
  • -
  • Further properties (important for our analyses later)
  • -
  • Meet the Covariance Matrix
  • -
  • Introducing the Covariance and Correlation functions
  • -
  • Covariance and Correlation Matrix
  • -
  • Correlation Function and Design/Feature Matrix
  • -
  • Covariance Matrix Examples
  • -
  • Correlation Matrix
  • -
  • Correlation Matrix with Pandas
  • -
  • Correlation Matrix with Pandas and the Franke function
  • -
  • Rewriting the Covariance and/or Correlation Matrix
  • -
  • Linking with the SVD
  • -
  • What does it mean?
  • -
  • And finally \( \boldsymbol{X}\boldsymbol{X}^T \)
  • -
  • Ridge and LASSO Regression
  • -
  • Deriving the Ridge Regression Equations
  • -
  • Interpreting the Ridge results
  • -
  • More interpretations
  • -
  • Deriving the Lasso Regression Equations
  • -
  • Exercises for week 35
  • -
  • Exercise 1: Setting up various Python environments
  • -
  • Exercise 2: making your own data and exploring scikit-learn
  • -
  • Exercise 3: Normalizing our data
  • -
  • Exercise 4: Adding Ridge Regression
  • -
  • Exercise 5: Analytical exercises
  • +
  • Reducing the number of degrees of freedom, overarching view
  • +
  • Preprocessing our data
  • +
  • Functionality in Scikit-Learn
  • +
  • More preprocessing
  • +
  • Frequently used scaling functions
  • +
  • Example of own Standard scaling
  • +
  • Min-Max Scaling
  • +
  • Testing the Means Squared Error as function of Complexity
  • +
  • More preprocessing examples, two-dimensional example, the Franke function
  • +
  • To think about, first part
  • +
  • More thinking
  • +
  • Still thinking
  • +
  • What does centering (subtracting the mean values) mean mathematically?
  • +
  • Further Manipulations
  • +
  • Wrapping it up
  • +
  • Linear Regression code, Intercept handling first
  • +
  • The Boston housing data example
  • +
  • Housing data, the code
  • +
  • Material for lecture Thursday, August 31
  • +
  • Mathematical Interpretation of Ordinary Least Squares
  • +
  • Residual Error
  • +
  • Simple case
  • +
  • The singular value decomposition
  • +
  • Linear Regression Problems
  • +
  • Fixing the singularity
  • +
  • Basic math of the SVD
  • +
  • The SVD, a Fantastic Algorithm
  • +
  • Economy-size SVD
  • +
  • Codes for the SVD
  • +
  • Note about SVD Calculations
  • +
  • Mathematics of the SVD and implications
  • +
  • Example Matrix
  • +
  • Setting up the Matrix to be inverted
  • +
  • Further properties (important for our analyses later)
  • +
  • Meet the Covariance Matrix
  • +
  • Introducing the Covariance and Correlation functions
  • +
  • Covariance and Correlation Matrix
  • +
  • Correlation Function and Design/Feature Matrix
  • +
  • Covariance Matrix Examples
  • +
  • Correlation Matrix
  • +
  • Correlation Matrix with Pandas
  • +
  • Correlation Matrix with Pandas and the Franke function
  • +
  • Rewriting the Covariance and/or Correlation Matrix
  • +
  • Linking with the SVD
  • +
  • What does it mean?
  • +
  • And finally \( \boldsymbol{X}\boldsymbol{X}^T \)
  • +
  • Ridge and LASSO Regression
  • +
  • Deriving the Ridge Regression Equations
  • +
  • Interpreting the Ridge results
  • +
  • More interpretations
  • +
  • Deriving the Lasso Regression Equations
  • @@ -366,52 +367,37 @@ MathJax.Hub.Config({

     

     

     

    -

    The SVD, a Fantastic Algorithm

    +

    Mathematical Interpretation of Ordinary Least Squares

    -

    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 -

    +

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

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

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

    +

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

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

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

    +

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

    -

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

    +

    This means that our best model is defined as

    -

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

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

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

    +

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

    @@ -438,7 +424,7 @@ near singular or singular matrices.

  • 51
  • 52
  • ...
  • -
  • 68
  • +
  • 74
  • »
  • diff --git a/doc/pub/week35/html/._week35-bs043.html b/doc/pub/week35/html/._week35-bs043.html index a7975d188..83a212879 100644 --- a/doc/pub/week35/html/._week35-bs043.html +++ b/doc/pub/week35/html/._week35-bs043.html @@ -75,10 +75,10 @@ doconce format html week35.do.txt --html_style=bootstrap --pygments_html_style=d 2, None, 'interpretations-and-optimizing-our-parameters'), - ('Examples relevant for the exercises', + ('Example relevant for the exercises', 2, None, - 'examples-relevant-for-the-exercises'), + 'example-relevant-for-the-exercises'), ('Own code for Ordinary Least Squares', 2, None, @@ -91,16 +91,14 @@ doconce format html week35.do.txt --html_style=bootstrap --pygments_html_style=d 2, None, 'splitting-our-data-in-training-and-test-data'), - ('Examples', 2, None, 'examples'), + ('The complete code with a simple data set', + 2, + None, + 'the-complete-code-with-a-simple-data-set'), ('Making your own test-train splitting', 2, None, 'making-your-own-test-train-splitting'), - ('The Boston housing data example', - 2, - None, - 'the-boston-housing-data-example'), - ('Housing data, the code', 2, None, 'housing-data-the-code'), ('Reducing the number of degrees of freedom, overarching view', 2, None, @@ -124,10 +122,33 @@ doconce format html week35.do.txt --html_style=bootstrap --pygments_html_style=d 2, None, 'testing-the-means-squared-error-as-function-of-complexity'), - ('More preprocessing examples, Franke function and regression', + ('More preprocessing examples, two-dimensional example, the ' + 'Franke function', 2, None, - 'more-preprocessing-examples-franke-function-and-regression'), + 'more-preprocessing-examples-two-dimensional-example-the-franke-function'), + ('To think about, first part', + 2, + None, + 'to-think-about-first-part'), + ('More thinking', 2, None, 'more-thinking'), + ('Still thinking', 2, None, 'still-thinking'), + ('What does centering (subtracting the mean values) mean ' + 'mathematically?', + 2, + None, + 'what-does-centering-subtracting-the-mean-values-mean-mathematically'), + ('Further Manipulations', 2, None, 'further-manipulations'), + ('Wrapping it up', 2, None, 'wrapping-it-up'), + ('Linear Regression code, Intercept handling first', + 2, + None, + 'linear-regression-code-intercept-handling-first'), + ('The Boston housing data example', + 2, + None, + 'the-boston-housing-data-example'), + ('Housing data, the code', 2, None, 'housing-data-the-code'), ('Material for lecture Thursday, August 31', 2, None, @@ -226,28 +247,7 @@ doconce format html week35.do.txt --html_style=bootstrap --pygments_html_style=d ('Deriving the Lasso Regression Equations', 2, None, - 'deriving-the-lasso-regression-equations'), - ('Exercises for week 35', 2, None, 'exercises-for-week-35'), - ('Exercise 1: Setting up various Python environments', - 2, - None, - 'exercise-1-setting-up-various-python-environments'), - ('Exercise 2: making your own data and exploring scikit-learn', - 2, - None, - 'exercise-2-making-your-own-data-and-exploring-scikit-learn'), - ('Exercise 3: Normalizing our data', - 2, - None, - 'exercise-3-normalizing-our-data'), - ('Exercise 4: Adding Ridge Regression', - 2, - None, - 'exercise-4-adding-ridge-regression'), - ('Exercise 5: Analytical exercises', - 2, - None, - 'exercise-5-analytical-exercises')]} + 'deriving-the-lasso-regression-equations')]} end of tocinfo --> @@ -299,62 +299,63 @@ MathJax.Hub.Config({
  • Other useful relations
  • Meet the Hessian Matrix
  • Interpretations and optimizing our parameters
  • -
  • Examples relevant for the exercises
  • +
  • Example relevant for the exercises
  • Own code for Ordinary Least Squares
  • Adding error analysis and training set up
  • Splitting our Data in Training and Test data
  • -
  • Examples
  • +
  • The complete code with a simple data set
  • Making your own test-train splitting
  • -
  • The Boston housing data example
  • -
  • Housing data, the code
  • -
  • Reducing the number of degrees of freedom, overarching view
  • -
  • Preprocessing our data
  • -
  • Functionality in Scikit-Learn
  • -
  • More preprocessing
  • -
  • Frequently used scaling functions
  • -
  • Example of own Standard scaling
  • -
  • Min-Max Scaling
  • -
  • Testing the Means Squared Error as function of Complexity
  • -
  • More preprocessing examples, Franke function and regression
  • -
  • Material for lecture Thursday, August 31
  • -
  • Mathematical Interpretation of Ordinary Least Squares
  • -
  • Residual Error
  • -
  • Simple case
  • -
  • The singular value decomposition
  • -
  • Linear Regression Problems
  • -
  • Fixing the singularity
  • -
  • Basic math of the SVD
  • -
  • The SVD, a Fantastic Algorithm
  • -
  • Economy-size SVD
  • -
  • Codes for the SVD
  • -
  • Note about SVD Calculations
  • -
  • Mathematics of the SVD and implications
  • -
  • Example Matrix
  • -
  • Setting up the Matrix to be inverted
  • -
  • Further properties (important for our analyses later)
  • -
  • Meet the Covariance Matrix
  • -
  • Introducing the Covariance and Correlation functions
  • -
  • Covariance and Correlation Matrix
  • -
  • Correlation Function and Design/Feature Matrix
  • -
  • Covariance Matrix Examples
  • -
  • Correlation Matrix
  • -
  • Correlation Matrix with Pandas
  • -
  • Correlation Matrix with Pandas and the Franke function
  • -
  • Rewriting the Covariance and/or Correlation Matrix
  • -
  • Linking with the SVD
  • -
  • What does it mean?
  • -
  • And finally \( \boldsymbol{X}\boldsymbol{X}^T \)
  • -
  • Ridge and LASSO Regression
  • -
  • Deriving the Ridge Regression Equations
  • -
  • Interpreting the Ridge results
  • -
  • More interpretations
  • -
  • Deriving the Lasso Regression Equations
  • -
  • Exercises for week 35
  • -
  • Exercise 1: Setting up various Python environments
  • -
  • Exercise 2: making your own data and exploring scikit-learn
  • -
  • Exercise 3: Normalizing our data
  • -
  • Exercise 4: Adding Ridge Regression
  • -
  • Exercise 5: Analytical exercises
  • +
  • Reducing the number of degrees of freedom, overarching view
  • +
  • Preprocessing our data
  • +
  • Functionality in Scikit-Learn
  • +
  • More preprocessing
  • +
  • Frequently used scaling functions
  • +
  • Example of own Standard scaling
  • +
  • Min-Max Scaling
  • +
  • Testing the Means Squared Error as function of Complexity
  • +
  • More preprocessing examples, two-dimensional example, the Franke function
  • +
  • To think about, first part
  • +
  • More thinking
  • +
  • Still thinking
  • +
  • What does centering (subtracting the mean values) mean mathematically?
  • +
  • Further Manipulations
  • +
  • Wrapping it up
  • +
  • Linear Regression code, Intercept handling first
  • +
  • The Boston housing data example
  • +
  • Housing data, the code
  • +
  • Material for lecture Thursday, August 31
  • +
  • Mathematical Interpretation of Ordinary Least Squares
  • +
  • Residual Error
  • +
  • Simple case
  • +
  • The singular value decomposition
  • +
  • Linear Regression Problems
  • +
  • Fixing the singularity
  • +
  • Basic math of the SVD
  • +
  • The SVD, a Fantastic Algorithm
  • +
  • Economy-size SVD
  • +
  • Codes for the SVD
  • +
  • Note about SVD Calculations
  • +
  • Mathematics of the SVD and implications
  • +
  • Example Matrix
  • +
  • Setting up the Matrix to be inverted
  • +
  • Further properties (important for our analyses later)
  • +
  • Meet the Covariance Matrix
  • +
  • Introducing the Covariance and Correlation functions
  • +
  • Covariance and Correlation Matrix
  • +
  • Correlation Function and Design/Feature Matrix
  • +
  • Covariance Matrix Examples
  • +
  • Correlation Matrix
  • +
  • Correlation Matrix with Pandas
  • +
  • Correlation Matrix with Pandas and the Franke function
  • +
  • Rewriting the Covariance and/or Correlation Matrix
  • +
  • Linking with the SVD
  • +
  • What does it mean?
  • +
  • And finally \( \boldsymbol{X}\boldsymbol{X}^T \)
  • +
  • Ridge and LASSO Regression
  • +
  • Deriving the Ridge Regression Equations
  • +
  • Interpreting the Ridge results
  • +
  • More interpretations
  • +
  • Deriving the Lasso Regression Equations
  • @@ -366,27 +367,14 @@ MathJax.Hub.Config({

     

     

     

    -

    Economy-size SVD

    +

    Residual Error

    -

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

    +

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

    The economy-size decomposition removes extra rows or columns of zeros -from the diagonal matrix of singular values, \( \boldsymbol{\Sigma} \), along with the columns -in either \( \boldsymbol{U} \) or \( \boldsymbol{V} \) that multiply those zeros in the expression. -Removing these zeros and columns can improve execution time -and reduce storage requirements without compromising the accuracy of -the decomposition. -

    - -

    If \( n > p \), we keep only the first \( p \) columns of \( \boldsymbol{U} \) and \( \boldsymbol{\Sigma} \) has dimension \( p\times p \). -If \( p > n \), then only the first \( n \) columns of \( \boldsymbol{V} \) are computed and \( \boldsymbol{\Sigma} \) has dimension \( n\times n \). -The \( n=p \) case is obvious, we retain the full SVD. -In general the economy-size SVD leads to less FLOPS and still conserving the desired accuracy. -

    +

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

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

  • 52
  • 53
  • ...
  • -
  • 68
  • +
  • 74
  • »
  • diff --git a/doc/pub/week35/html/._week35-bs044.html b/doc/pub/week35/html/._week35-bs044.html index a9f494c54..591890c8e 100644 --- a/doc/pub/week35/html/._week35-bs044.html +++ b/doc/pub/week35/html/._week35-bs044.html @@ -75,10 +75,10 @@ doconce format html week35.do.txt --html_style=bootstrap --pygments_html_style=d 2, None, 'interpretations-and-optimizing-our-parameters'), - ('Examples relevant for the exercises', + ('Example relevant for the exercises', 2, None, - 'examples-relevant-for-the-exercises'), + 'example-relevant-for-the-exercises'), ('Own code for Ordinary Least Squares', 2, None, @@ -91,16 +91,14 @@ doconce format html week35.do.txt --html_style=bootstrap --pygments_html_style=d 2, None, 'splitting-our-data-in-training-and-test-data'), - ('Examples', 2, None, 'examples'), + ('The complete code with a simple data set', + 2, + None, + 'the-complete-code-with-a-simple-data-set'), ('Making your own test-train splitting', 2, None, 'making-your-own-test-train-splitting'), - ('The Boston housing data example', - 2, - None, - 'the-boston-housing-data-example'), - ('Housing data, the code', 2, None, 'housing-data-the-code'), ('Reducing the number of degrees of freedom, overarching view', 2, None, @@ -124,10 +122,33 @@ doconce format html week35.do.txt --html_style=bootstrap --pygments_html_style=d 2, None, 'testing-the-means-squared-error-as-function-of-complexity'), - ('More preprocessing examples, Franke function and regression', + ('More preprocessing examples, two-dimensional example, the ' + 'Franke function', 2, None, - 'more-preprocessing-examples-franke-function-and-regression'), + 'more-preprocessing-examples-two-dimensional-example-the-franke-function'), + ('To think about, first part', + 2, + None, + 'to-think-about-first-part'), + ('More thinking', 2, None, 'more-thinking'), + ('Still thinking', 2, None, 'still-thinking'), + ('What does centering (subtracting the mean values) mean ' + 'mathematically?', + 2, + None, + 'what-does-centering-subtracting-the-mean-values-mean-mathematically'), + ('Further Manipulations', 2, None, 'further-manipulations'), + ('Wrapping it up', 2, None, 'wrapping-it-up'), + ('Linear Regression code, Intercept handling first', + 2, + None, + 'linear-regression-code-intercept-handling-first'), + ('The Boston housing data example', + 2, + None, + 'the-boston-housing-data-example'), + ('Housing data, the code', 2, None, 'housing-data-the-code'), ('Material for lecture Thursday, August 31', 2, None, @@ -226,28 +247,7 @@ doconce format html week35.do.txt --html_style=bootstrap --pygments_html_style=d ('Deriving the Lasso Regression Equations', 2, None, - 'deriving-the-lasso-regression-equations'), - ('Exercises for week 35', 2, None, 'exercises-for-week-35'), - ('Exercise 1: Setting up various Python environments', - 2, - None, - 'exercise-1-setting-up-various-python-environments'), - ('Exercise 2: making your own data and exploring scikit-learn', - 2, - None, - 'exercise-2-making-your-own-data-and-exploring-scikit-learn'), - ('Exercise 3: Normalizing our data', - 2, - None, - 'exercise-3-normalizing-our-data'), - ('Exercise 4: Adding Ridge Regression', - 2, - None, - 'exercise-4-adding-ridge-regression'), - ('Exercise 5: Analytical exercises', - 2, - None, - 'exercise-5-analytical-exercises')]} + 'deriving-the-lasso-regression-equations')]} end of tocinfo --> @@ -299,62 +299,63 @@ MathJax.Hub.Config({
  • Other useful relations
  • Meet the Hessian Matrix
  • Interpretations and optimizing our parameters
  • -
  • Examples relevant for the exercises
  • +
  • Example relevant for the exercises
  • Own code for Ordinary Least Squares
  • Adding error analysis and training set up
  • Splitting our Data in Training and Test data
  • -
  • Examples
  • +
  • The complete code with a simple data set
  • Making your own test-train splitting
  • -
  • The Boston housing data example
  • -
  • Housing data, the code
  • -
  • Reducing the number of degrees of freedom, overarching view
  • -
  • Preprocessing our data
  • -
  • Functionality in Scikit-Learn
  • -
  • More preprocessing
  • -
  • Frequently used scaling functions
  • -
  • Example of own Standard scaling
  • -
  • Min-Max Scaling
  • -
  • Testing the Means Squared Error as function of Complexity
  • -
  • More preprocessing examples, Franke function and regression
  • -
  • Material for lecture Thursday, August 31
  • -
  • Mathematical Interpretation of Ordinary Least Squares
  • -
  • Residual Error
  • -
  • Simple case
  • -
  • The singular value decomposition
  • -
  • Linear Regression Problems
  • -
  • Fixing the singularity
  • -
  • Basic math of the SVD
  • -
  • The SVD, a Fantastic Algorithm
  • -
  • Economy-size SVD
  • -
  • Codes for the SVD
  • -
  • Note about SVD Calculations
  • -
  • Mathematics of the SVD and implications
  • -
  • Example Matrix
  • -
  • Setting up the Matrix to be inverted
  • -
  • Further properties (important for our analyses later)
  • -
  • Meet the Covariance Matrix
  • -
  • Introducing the Covariance and Correlation functions
  • -
  • Covariance and Correlation Matrix
  • -
  • Correlation Function and Design/Feature Matrix
  • -
  • Covariance Matrix Examples
  • -
  • Correlation Matrix
  • -
  • Correlation Matrix with Pandas
  • -
  • Correlation Matrix with Pandas and the Franke function
  • -
  • Rewriting the Covariance and/or Correlation Matrix
  • -
  • Linking with the SVD
  • -
  • What does it mean?
  • -
  • And finally \( \boldsymbol{X}\boldsymbol{X}^T \)
  • -
  • Ridge and LASSO Regression
  • -
  • Deriving the Ridge Regression Equations
  • -
  • Interpreting the Ridge results
  • -
  • More interpretations
  • -
  • Deriving the Lasso Regression Equations
  • -
  • Exercises for week 35
  • -
  • Exercise 1: Setting up various Python environments
  • -
  • Exercise 2: making your own data and exploring scikit-learn
  • -
  • Exercise 3: Normalizing our data
  • -
  • Exercise 4: Adding Ridge Regression
  • -
  • Exercise 5: Analytical exercises
  • +
  • Reducing the number of degrees of freedom, overarching view
  • +
  • Preprocessing our data
  • +
  • Functionality in Scikit-Learn
  • +
  • More preprocessing
  • +
  • Frequently used scaling functions
  • +
  • Example of own Standard scaling
  • +
  • Min-Max Scaling
  • +
  • Testing the Means Squared Error as function of Complexity
  • +
  • More preprocessing examples, two-dimensional example, the Franke function
  • +
  • To think about, first part
  • +
  • More thinking
  • +
  • Still thinking
  • +
  • What does centering (subtracting the mean values) mean mathematically?
  • +
  • Further Manipulations
  • +
  • Wrapping it up
  • +
  • Linear Regression code, Intercept handling first
  • +
  • The Boston housing data example
  • +
  • Housing data, the code
  • +
  • Material for lecture Thursday, August 31
  • +
  • Mathematical Interpretation of Ordinary Least Squares
  • +
  • Residual Error
  • +
  • Simple case
  • +
  • The singular value decomposition
  • +
  • Linear Regression Problems
  • +
  • Fixing the singularity
  • +
  • Basic math of the SVD
  • +
  • The SVD, a Fantastic Algorithm
  • +
  • Economy-size SVD
  • +
  • Codes for the SVD
  • +
  • Note about SVD Calculations
  • +
  • Mathematics of the SVD and implications
  • +
  • Example Matrix
  • +
  • Setting up the Matrix to be inverted
  • +
  • Further properties (important for our analyses later)
  • +
  • Meet the Covariance Matrix
  • +
  • Introducing the Covariance and Correlation functions
  • +
  • Covariance and Correlation Matrix
  • +
  • Correlation Function and Design/Feature Matrix
  • +
  • Covariance Matrix Examples
  • +
  • Correlation Matrix
  • +
  • Correlation Matrix with Pandas
  • +
  • Correlation Matrix with Pandas and the Franke function
  • +
  • Rewriting the Covariance and/or Correlation Matrix
  • +
  • Linking with the SVD
  • +
  • What does it mean?
  • +
  • And finally \( \boldsymbol{X}\boldsymbol{X}^T \)
  • +
  • Ridge and LASSO Regression
  • +
  • Deriving the Ridge Regression Equations
  • +
  • Interpreting the Ridge results
  • +
  • More interpretations
  • +
  • Deriving the Lasso Regression Equations
  • @@ -366,68 +367,25 @@ MathJax.Hub.Config({

     

     

     

    -

    Codes for the SVD

    +

    Simple case

    +

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

    - -
    -
    -
    -
    -
    -
    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)
    +$$
    +\boldsymbol{X}^T\boldsymbol{X}=\boldsymbol{X}\boldsymbol{X}^T = \boldsymbol{I}.
    +$$
     
    -    D = np.zeros((len(U),len(VT)))
    -    for i in range(0,len(VT)):
    -        D[i,i]=S[i]
    -    return U @ D @ VT
    +

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

    +

    This serves also as a useful test of our codes.

    @@ -454,7 +412,7 @@ in the program terminating due to a singular matrix.

  • 53
  • 54
  • ...
  • -
  • 68
  • +
  • 74
  • »
  • diff --git a/doc/pub/week35/html/._week35-bs045.html b/doc/pub/week35/html/._week35-bs045.html index ca62a3033..6520d645b 100644 --- a/doc/pub/week35/html/._week35-bs045.html +++ b/doc/pub/week35/html/._week35-bs045.html @@ -75,10 +75,10 @@ doconce format html week35.do.txt --html_style=bootstrap --pygments_html_style=d 2, None, 'interpretations-and-optimizing-our-parameters'), - ('Examples relevant for the exercises', + ('Example relevant for the exercises', 2, None, - 'examples-relevant-for-the-exercises'), + 'example-relevant-for-the-exercises'), ('Own code for Ordinary Least Squares', 2, None, @@ -91,16 +91,14 @@ doconce format html week35.do.txt --html_style=bootstrap --pygments_html_style=d 2, None, 'splitting-our-data-in-training-and-test-data'), - ('Examples', 2, None, 'examples'), + ('The complete code with a simple data set', + 2, + None, + 'the-complete-code-with-a-simple-data-set'), ('Making your own test-train splitting', 2, None, 'making-your-own-test-train-splitting'), - ('The Boston housing data example', - 2, - None, - 'the-boston-housing-data-example'), - ('Housing data, the code', 2, None, 'housing-data-the-code'), ('Reducing the number of degrees of freedom, overarching view', 2, None, @@ -124,10 +122,33 @@ doconce format html week35.do.txt --html_style=bootstrap --pygments_html_style=d 2, None, 'testing-the-means-squared-error-as-function-of-complexity'), - ('More preprocessing examples, Franke function and regression', + ('More preprocessing examples, two-dimensional example, the ' + 'Franke function', 2, None, - 'more-preprocessing-examples-franke-function-and-regression'), + 'more-preprocessing-examples-two-dimensional-example-the-franke-function'), + ('To think about, first part', + 2, + None, + 'to-think-about-first-part'), + ('More thinking', 2, None, 'more-thinking'), + ('Still thinking', 2, None, 'still-thinking'), + ('What does centering (subtracting the mean values) mean ' + 'mathematically?', + 2, + None, + 'what-does-centering-subtracting-the-mean-values-mean-mathematically'), + ('Further Manipulations', 2, None, 'further-manipulations'), + ('Wrapping it up', 2, None, 'wrapping-it-up'), + ('Linear Regression code, Intercept handling first', + 2, + None, + 'linear-regression-code-intercept-handling-first'), + ('The Boston housing data example', + 2, + None, + 'the-boston-housing-data-example'), + ('Housing data, the code', 2, None, 'housing-data-the-code'), ('Material for lecture Thursday, August 31', 2, None, @@ -226,28 +247,7 @@ doconce format html week35.do.txt --html_style=bootstrap --pygments_html_style=d ('Deriving the Lasso Regression Equations', 2, None, - 'deriving-the-lasso-regression-equations'), - ('Exercises for week 35', 2, None, 'exercises-for-week-35'), - ('Exercise 1: Setting up various Python environments', - 2, - None, - 'exercise-1-setting-up-various-python-environments'), - ('Exercise 2: making your own data and exploring scikit-learn', - 2, - None, - 'exercise-2-making-your-own-data-and-exploring-scikit-learn'), - ('Exercise 3: Normalizing our data', - 2, - None, - 'exercise-3-normalizing-our-data'), - ('Exercise 4: Adding Ridge Regression', - 2, - None, - 'exercise-4-adding-ridge-regression'), - ('Exercise 5: Analytical exercises', - 2, - None, - 'exercise-5-analytical-exercises')]} + 'deriving-the-lasso-regression-equations')]} end of tocinfo --> @@ -299,62 +299,63 @@ MathJax.Hub.Config({
  • Other useful relations
  • Meet the Hessian Matrix
  • Interpretations and optimizing our parameters
  • -
  • Examples relevant for the exercises
  • +
  • Example relevant for the exercises
  • Own code for Ordinary Least Squares
  • Adding error analysis and training set up
  • Splitting our Data in Training and Test data
  • -
  • Examples
  • +
  • The complete code with a simple data set
  • Making your own test-train splitting
  • -
  • The Boston housing data example
  • -
  • Housing data, the code
  • -
  • Reducing the number of degrees of freedom, overarching view
  • -
  • Preprocessing our data
  • -
  • Functionality in Scikit-Learn
  • -
  • More preprocessing
  • -
  • Frequently used scaling functions
  • -
  • Example of own Standard scaling
  • -
  • Min-Max Scaling
  • -
  • Testing the Means Squared Error as function of Complexity
  • -
  • More preprocessing examples, Franke function and regression
  • -
  • Material for lecture Thursday, August 31
  • -
  • Mathematical Interpretation of Ordinary Least Squares
  • -
  • Residual Error
  • -
  • Simple case
  • -
  • The singular value decomposition
  • -
  • Linear Regression Problems
  • -
  • Fixing the singularity
  • -
  • Basic math of the SVD
  • -
  • The SVD, a Fantastic Algorithm
  • -
  • Economy-size SVD
  • -
  • Codes for the SVD
  • -
  • Note about SVD Calculations
  • -
  • Mathematics of the SVD and implications
  • -
  • Example Matrix
  • -
  • Setting up the Matrix to be inverted
  • -
  • Further properties (important for our analyses later)
  • -
  • Meet the Covariance Matrix
  • -
  • Introducing the Covariance and Correlation functions
  • -
  • Covariance and Correlation Matrix
  • -
  • Correlation Function and Design/Feature Matrix
  • -
  • Covariance Matrix Examples
  • -
  • Correlation Matrix
  • -
  • Correlation Matrix with Pandas
  • -
  • Correlation Matrix with Pandas and the Franke function
  • -
  • Rewriting the Covariance and/or Correlation Matrix
  • -
  • Linking with the SVD
  • -
  • What does it mean?
  • -
  • And finally \( \boldsymbol{X}\boldsymbol{X}^T \)
  • -
  • Ridge and LASSO Regression
  • -
  • Deriving the Ridge Regression Equations
  • -
  • Interpreting the Ridge results
  • -
  • More interpretations
  • -
  • Deriving the Lasso Regression Equations
  • -
  • Exercises for week 35
  • -
  • Exercise 1: Setting up various Python environments
  • -
  • Exercise 2: making your own data and exploring scikit-learn
  • -
  • Exercise 3: Normalizing our data
  • -
  • Exercise 4: Adding Ridge Regression
  • -
  • Exercise 5: Analytical exercises
  • +
  • Reducing the number of degrees of freedom, overarching view
  • +
  • Preprocessing our data
  • +
  • Functionality in Scikit-Learn
  • +
  • More preprocessing
  • +
  • Frequently used scaling functions
  • +
  • Example of own Standard scaling
  • +
  • Min-Max Scaling
  • +
  • Testing the Means Squared Error as function of Complexity
  • +
  • More preprocessing examples, two-dimensional example, the Franke function
  • +
  • To think about, first part
  • +
  • More thinking
  • +
  • Still thinking
  • +
  • What does centering (subtracting the mean values) mean mathematically?
  • +
  • Further Manipulations
  • +
  • Wrapping it up
  • +
  • Linear Regression code, Intercept handling first
  • +
  • The Boston housing data example
  • +
  • Housing data, the code
  • +
  • Material for lecture Thursday, August 31
  • +
  • Mathematical Interpretation of Ordinary Least Squares
  • +
  • Residual Error
  • +
  • Simple case
  • +
  • The singular value decomposition
  • +
  • Linear Regression Problems
  • +
  • Fixing the singularity
  • +
  • Basic math of the SVD
  • +
  • The SVD, a Fantastic Algorithm
  • +
  • Economy-size SVD
  • +
  • Codes for the SVD
  • +
  • Note about SVD Calculations
  • +
  • Mathematics of the SVD and implications
  • +
  • Example Matrix
  • +
  • Setting up the Matrix to be inverted
  • +
  • Further properties (important for our analyses later)
  • +
  • Meet the Covariance Matrix
  • +
  • Introducing the Covariance and Correlation functions
  • +
  • Covariance and Correlation Matrix
  • +
  • Correlation Function and Design/Feature Matrix
  • +
  • Covariance Matrix Examples
  • +
  • Correlation Matrix
  • +
  • Correlation Matrix with Pandas
  • +
  • Correlation Matrix with Pandas and the Franke function
  • +
  • Rewriting the Covariance and/or Correlation Matrix
  • +
  • Linking with the SVD
  • +
  • What does it mean?
  • +
  • And finally \( \boldsymbol{X}\boldsymbol{X}^T \)
  • +
  • Ridge and LASSO Regression
  • +
  • Deriving the Ridge Regression Equations
  • +
  • Interpreting the Ridge results
  • +
  • More interpretations
  • +
  • Deriving the Lasso Regression Equations
  • @@ -366,24 +367,50 @@ MathJax.Hub.Config({

     

     

     

    -

    Note about SVD Calculations

    +

    The singular value decomposition

    -

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

    +
    + + +

    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.

    -

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

    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.

    -

    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 +

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

    +
    +
    + +

    diff --git a/doc/pub/week35/html/._week35-bs046.html b/doc/pub/week35/html/._week35-bs046.html index 711ff27c2..92b45adad 100644 --- a/doc/pub/week35/html/._week35-bs046.html +++ b/doc/pub/week35/html/._week35-bs046.html @@ -75,10 +75,10 @@ doconce format html week35.do.txt --html_style=bootstrap --pygments_html_style=d 2, None, 'interpretations-and-optimizing-our-parameters'), - ('Examples relevant for the exercises', + ('Example relevant for the exercises', 2, None, - 'examples-relevant-for-the-exercises'), + 'example-relevant-for-the-exercises'), ('Own code for Ordinary Least Squares', 2, None, @@ -91,16 +91,14 @@ doconce format html week35.do.txt --html_style=bootstrap --pygments_html_style=d 2, None, 'splitting-our-data-in-training-and-test-data'), - ('Examples', 2, None, 'examples'), + ('The complete code with a simple data set', + 2, + None, + 'the-complete-code-with-a-simple-data-set'), ('Making your own test-train splitting', 2, None, 'making-your-own-test-train-splitting'), - ('The Boston housing data example', - 2, - None, - 'the-boston-housing-data-example'), - ('Housing data, the code', 2, None, 'housing-data-the-code'), ('Reducing the number of degrees of freedom, overarching view', 2, None, @@ -124,10 +122,33 @@ doconce format html week35.do.txt --html_style=bootstrap --pygments_html_style=d 2, None, 'testing-the-means-squared-error-as-function-of-complexity'), - ('More preprocessing examples, Franke function and regression', + ('More preprocessing examples, two-dimensional example, the ' + 'Franke function', 2, None, - 'more-preprocessing-examples-franke-function-and-regression'), + 'more-preprocessing-examples-two-dimensional-example-the-franke-function'), + ('To think about, first part', + 2, + None, + 'to-think-about-first-part'), + ('More thinking', 2, None, 'more-thinking'), + ('Still thinking', 2, None, 'still-thinking'), + ('What does centering (subtracting the mean values) mean ' + 'mathematically?', + 2, + None, + 'what-does-centering-subtracting-the-mean-values-mean-mathematically'), + ('Further Manipulations', 2, None, 'further-manipulations'), + ('Wrapping it up', 2, None, 'wrapping-it-up'), + ('Linear Regression code, Intercept handling first', + 2, + None, + 'linear-regression-code-intercept-handling-first'), + ('The Boston housing data example', + 2, + None, + 'the-boston-housing-data-example'), + ('Housing data, the code', 2, None, 'housing-data-the-code'), ('Material for lecture Thursday, August 31', 2, None, @@ -226,28 +247,7 @@ doconce format html week35.do.txt --html_style=bootstrap --pygments_html_style=d ('Deriving the Lasso Regression Equations', 2, None, - 'deriving-the-lasso-regression-equations'), - ('Exercises for week 35', 2, None, 'exercises-for-week-35'), - ('Exercise 1: Setting up various Python environments', - 2, - None, - 'exercise-1-setting-up-various-python-environments'), - ('Exercise 2: making your own data and exploring scikit-learn', - 2, - None, - 'exercise-2-making-your-own-data-and-exploring-scikit-learn'), - ('Exercise 3: Normalizing our data', - 2, - None, - 'exercise-3-normalizing-our-data'), - ('Exercise 4: Adding Ridge Regression', - 2, - None, - 'exercise-4-adding-ridge-regression'), - ('Exercise 5: Analytical exercises', - 2, - None, - 'exercise-5-analytical-exercises')]} + 'deriving-the-lasso-regression-equations')]} end of tocinfo --> @@ -299,62 +299,63 @@ MathJax.Hub.Config({
  • Other useful relations
  • Meet the Hessian Matrix
  • Interpretations and optimizing our parameters
  • -
  • Examples relevant for the exercises
  • +
  • Example relevant for the exercises
  • Own code for Ordinary Least Squares
  • Adding error analysis and training set up
  • Splitting our Data in Training and Test data
  • -
  • Examples
  • +
  • The complete code with a simple data set
  • Making your own test-train splitting
  • -
  • The Boston housing data example
  • -
  • Housing data, the code
  • -
  • Reducing the number of degrees of freedom, overarching view
  • -
  • Preprocessing our data
  • -
  • Functionality in Scikit-Learn
  • -
  • More preprocessing
  • -
  • Frequently used scaling functions
  • -
  • Example of own Standard scaling
  • -
  • Min-Max Scaling
  • -
  • Testing the Means Squared Error as function of Complexity
  • -
  • More preprocessing examples, Franke function and regression
  • -
  • Material for lecture Thursday, August 31
  • -
  • Mathematical Interpretation of Ordinary Least Squares
  • -
  • Residual Error
  • -
  • Simple case
  • -
  • The singular value decomposition
  • -
  • Linear Regression Problems
  • -
  • Fixing the singularity
  • -
  • Basic math of the SVD
  • -
  • The SVD, a Fantastic Algorithm
  • -
  • Economy-size SVD
  • -
  • Codes for the SVD
  • -
  • Note about SVD Calculations
  • -
  • Mathematics of the SVD and implications
  • -
  • Example Matrix
  • -
  • Setting up the Matrix to be inverted
  • -
  • Further properties (important for our analyses later)
  • -
  • Meet the Covariance Matrix
  • -
  • Introducing the Covariance and Correlation functions
  • -
  • Covariance and Correlation Matrix
  • -
  • Correlation Function and Design/Feature Matrix
  • -
  • Covariance Matrix Examples
  • -
  • Correlation Matrix
  • -
  • Correlation Matrix with Pandas
  • -
  • Correlation Matrix with Pandas and the Franke function
  • -
  • Rewriting the Covariance and/or Correlation Matrix
  • -
  • Linking with the SVD
  • -
  • What does it mean?
  • -
  • And finally \( \boldsymbol{X}\boldsymbol{X}^T \)
  • -
  • Ridge and LASSO Regression
  • -
  • Deriving the Ridge Regression Equations
  • -
  • Interpreting the Ridge results
  • -
  • More interpretations
  • -
  • Deriving the Lasso Regression Equations
  • -
  • Exercises for week 35
  • -
  • Exercise 1: Setting up various Python environments
  • -
  • Exercise 2: making your own data and exploring scikit-learn
  • -
  • Exercise 3: Normalizing our data
  • -
  • Exercise 4: Adding Ridge Regression
  • -
  • Exercise 5: Analytical exercises
  • +
  • Reducing the number of degrees of freedom, overarching view
  • +
  • Preprocessing our data
  • +
  • Functionality in Scikit-Learn
  • +
  • More preprocessing
  • +
  • Frequently used scaling functions
  • +
  • Example of own Standard scaling
  • +
  • Min-Max Scaling
  • +
  • Testing the Means Squared Error as function of Complexity
  • +
  • More preprocessing examples, two-dimensional example, the Franke function
  • +
  • To think about, first part
  • +
  • More thinking
  • +
  • Still thinking
  • +
  • What does centering (subtracting the mean values) mean mathematically?
  • +
  • Further Manipulations
  • +
  • Wrapping it up
  • +
  • Linear Regression code, Intercept handling first
  • +
  • The Boston housing data example
  • +
  • Housing data, the code
  • +
  • Material for lecture Thursday, August 31
  • +
  • Mathematical Interpretation of Ordinary Least Squares
  • +
  • Residual Error
  • +
  • Simple case
  • +
  • The singular value decomposition
  • +
  • Linear Regression Problems
  • +
  • Fixing the singularity
  • +
  • Basic math of the SVD
  • +
  • The SVD, a Fantastic Algorithm
  • +
  • Economy-size SVD
  • +
  • Codes for the SVD
  • +
  • Note about SVD Calculations
  • +
  • Mathematics of the SVD and implications
  • +
  • Example Matrix
  • +
  • Setting up the Matrix to be inverted
  • +
  • Further properties (important for our analyses later)
  • +
  • Meet the Covariance Matrix
  • +
  • Introducing the Covariance and Correlation functions
  • +
  • Covariance and Correlation Matrix
  • +
  • Correlation Function and Design/Feature Matrix
  • +
  • Covariance Matrix Examples
  • +
  • Correlation Matrix
  • +
  • Correlation Matrix with Pandas
  • +
  • Correlation Matrix with Pandas and the Franke function
  • +
  • Rewriting the Covariance and/or Correlation Matrix
  • +
  • Linking with the SVD
  • +
  • What does it mean?
  • +
  • And finally \( \boldsymbol{X}\boldsymbol{X}^T \)
  • +
  • Ridge and LASSO Regression
  • +
  • Deriving the Ridge Regression Equations
  • +
  • Interpreting the Ridge results
  • +
  • More interpretations
  • +
  • Deriving the Lasso Regression Equations
  • @@ -366,38 +367,54 @@ MathJax.Hub.Config({

     

     

     

    -

    Mathematics of the SVD and implications

    +

    Linear Regression Problems

    -

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

    +

    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 +

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

    We can SVD decompose our matrix as

    +

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

    + +

    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 +

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

    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.

    +

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

    @@ -424,7 +441,7 @@ $$

  • 55
  • 56
  • ...
  • -
  • 68
  • +
  • 74
  • »
  • diff --git a/doc/pub/week35/html/._week35-bs047.html b/doc/pub/week35/html/._week35-bs047.html index 435c071b3..a431a0958 100644 --- a/doc/pub/week35/html/._week35-bs047.html +++ b/doc/pub/week35/html/._week35-bs047.html @@ -75,10 +75,10 @@ doconce format html week35.do.txt --html_style=bootstrap --pygments_html_style=d 2, None, 'interpretations-and-optimizing-our-parameters'), - ('Examples relevant for the exercises', + ('Example relevant for the exercises', 2, None, - 'examples-relevant-for-the-exercises'), + 'example-relevant-for-the-exercises'), ('Own code for Ordinary Least Squares', 2, None, @@ -91,16 +91,14 @@ doconce format html week35.do.txt --html_style=bootstrap --pygments_html_style=d 2, None, 'splitting-our-data-in-training-and-test-data'), - ('Examples', 2, None, 'examples'), + ('The complete code with a simple data set', + 2, + None, + 'the-complete-code-with-a-simple-data-set'), ('Making your own test-train splitting', 2, None, 'making-your-own-test-train-splitting'), - ('The Boston housing data example', - 2, - None, - 'the-boston-housing-data-example'), - ('Housing data, the code', 2, None, 'housing-data-the-code'), ('Reducing the number of degrees of freedom, overarching view', 2, None, @@ -124,10 +122,33 @@ doconce format html week35.do.txt --html_style=bootstrap --pygments_html_style=d 2, None, 'testing-the-means-squared-error-as-function-of-complexity'), - ('More preprocessing examples, Franke function and regression', + ('More preprocessing examples, two-dimensional example, the ' + 'Franke function', 2, None, - 'more-preprocessing-examples-franke-function-and-regression'), + 'more-preprocessing-examples-two-dimensional-example-the-franke-function'), + ('To think about, first part', + 2, + None, + 'to-think-about-first-part'), + ('More thinking', 2, None, 'more-thinking'), + ('Still thinking', 2, None, 'still-thinking'), + ('What does centering (subtracting the mean values) mean ' + 'mathematically?', + 2, + None, + 'what-does-centering-subtracting-the-mean-values-mean-mathematically'), + ('Further Manipulations', 2, None, 'further-manipulations'), + ('Wrapping it up', 2, None, 'wrapping-it-up'), + ('Linear Regression code, Intercept handling first', + 2, + None, + 'linear-regression-code-intercept-handling-first'), + ('The Boston housing data example', + 2, + None, + 'the-boston-housing-data-example'), + ('Housing data, the code', 2, None, 'housing-data-the-code'), ('Material for lecture Thursday, August 31', 2, None, @@ -226,28 +247,7 @@ doconce format html week35.do.txt --html_style=bootstrap --pygments_html_style=d ('Deriving the Lasso Regression Equations', 2, None, - 'deriving-the-lasso-regression-equations'), - ('Exercises for week 35', 2, None, 'exercises-for-week-35'), - ('Exercise 1: Setting up various Python environments', - 2, - None, - 'exercise-1-setting-up-various-python-environments'), - ('Exercise 2: making your own data and exploring scikit-learn', - 2, - None, - 'exercise-2-making-your-own-data-and-exploring-scikit-learn'), - ('Exercise 3: Normalizing our data', - 2, - None, - 'exercise-3-normalizing-our-data'), - ('Exercise 4: Adding Ridge Regression', - 2, - None, - 'exercise-4-adding-ridge-regression'), - ('Exercise 5: Analytical exercises', - 2, - None, - 'exercise-5-analytical-exercises')]} + 'deriving-the-lasso-regression-equations')]} end of tocinfo --> @@ -299,62 +299,63 @@ MathJax.Hub.Config({
  • Other useful relations
  • Meet the Hessian Matrix
  • Interpretations and optimizing our parameters
  • -
  • Examples relevant for the exercises
  • +
  • Example relevant for the exercises
  • Own code for Ordinary Least Squares
  • Adding error analysis and training set up
  • Splitting our Data in Training and Test data
  • -
  • Examples
  • +
  • The complete code with a simple data set
  • Making your own test-train splitting
  • -
  • The Boston housing data example
  • -
  • Housing data, the code
  • -
  • Reducing the number of degrees of freedom, overarching view
  • -
  • Preprocessing our data
  • -
  • Functionality in Scikit-Learn
  • -
  • More preprocessing
  • -
  • Frequently used scaling functions
  • -
  • Example of own Standard scaling
  • -
  • Min-Max Scaling
  • -
  • Testing the Means Squared Error as function of Complexity
  • -
  • More preprocessing examples, Franke function and regression
  • -
  • Material for lecture Thursday, August 31
  • -
  • Mathematical Interpretation of Ordinary Least Squares
  • -
  • Residual Error
  • -
  • Simple case
  • -
  • The singular value decomposition
  • -
  • Linear Regression Problems
  • -
  • Fixing the singularity
  • -
  • Basic math of the SVD
  • -
  • The SVD, a Fantastic Algorithm
  • -
  • Economy-size SVD
  • -
  • Codes for the SVD
  • -
  • Note about SVD Calculations
  • -
  • Mathematics of the SVD and implications
  • -
  • Example Matrix
  • -
  • Setting up the Matrix to be inverted
  • -
  • Further properties (important for our analyses later)
  • -
  • Meet the Covariance Matrix
  • -
  • Introducing the Covariance and Correlation functions
  • -
  • Covariance and Correlation Matrix
  • -
  • Correlation Function and Design/Feature Matrix
  • -
  • Covariance Matrix Examples
  • -
  • Correlation Matrix
  • -
  • Correlation Matrix with Pandas
  • -
  • Correlation Matrix with Pandas and the Franke function
  • -
  • Rewriting the Covariance and/or Correlation Matrix
  • -
  • Linking with the SVD
  • -
  • What does it mean?
  • -
  • And finally \( \boldsymbol{X}\boldsymbol{X}^T \)
  • -
  • Ridge and LASSO Regression
  • -
  • Deriving the Ridge Regression Equations
  • -
  • Interpreting the Ridge results
  • -
  • More interpretations
  • -
  • Deriving the Lasso Regression Equations
  • -
  • Exercises for week 35
  • -
  • Exercise 1: Setting up various Python environments
  • -
  • Exercise 2: making your own data and exploring scikit-learn
  • -
  • Exercise 3: Normalizing our data
  • -
  • Exercise 4: Adding Ridge Regression
  • -
  • Exercise 5: Analytical exercises
  • +
  • Reducing the number of degrees of freedom, overarching view
  • +
  • Preprocessing our data
  • +
  • Functionality in Scikit-Learn
  • +
  • More preprocessing
  • +
  • Frequently used scaling functions
  • +
  • Example of own Standard scaling
  • +
  • Min-Max Scaling
  • +
  • Testing the Means Squared Error as function of Complexity
  • +
  • More preprocessing examples, two-dimensional example, the Franke function
  • +
  • To think about, first part
  • +
  • More thinking
  • +
  • Still thinking
  • +
  • What does centering (subtracting the mean values) mean mathematically?
  • +
  • Further Manipulations
  • +
  • Wrapping it up
  • +
  • Linear Regression code, Intercept handling first
  • +
  • The Boston housing data example
  • +
  • Housing data, the code
  • +
  • Material for lecture Thursday, August 31
  • +
  • Mathematical Interpretation of Ordinary Least Squares
  • +
  • Residual Error
  • +
  • Simple case
  • +
  • The singular value decomposition
  • +
  • Linear Regression Problems
  • +
  • Fixing the singularity
  • +
  • Basic math of the SVD
  • +
  • The SVD, a Fantastic Algorithm
  • +
  • Economy-size SVD
  • +
  • Codes for the SVD
  • +
  • Note about SVD Calculations
  • +
  • Mathematics of the SVD and implications
  • +
  • Example Matrix
  • +
  • Setting up the Matrix to be inverted
  • +
  • Further properties (important for our analyses later)
  • +
  • Meet the Covariance Matrix
  • +
  • Introducing the Covariance and Correlation functions
  • +
  • Covariance and Correlation Matrix
  • +
  • Correlation Function and Design/Feature Matrix
  • +
  • Covariance Matrix Examples
  • +
  • Correlation Matrix
  • +
  • Correlation Matrix with Pandas
  • +
  • Correlation Matrix with Pandas and the Franke function
  • +
  • Rewriting the Covariance and/or Correlation Matrix
  • +
  • Linking with the SVD
  • +
  • What does it mean?
  • +
  • And finally \( \boldsymbol{X}\boldsymbol{X}^T \)
  • +
  • Ridge and LASSO Regression
  • +
  • Deriving the Ridge Regression Equations
  • +
  • Interpreting the Ridge results
  • +
  • More interpretations
  • +
  • Deriving the Lasso Regression Equations
  • @@ -366,63 +367,30 @@ MathJax.Hub.Config({

     

     

     

    -

    Example Matrix

    - -

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

    +

    Fixing the singularity

    +

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

    $$ -\boldsymbol{\Sigma}= -\begin{bmatrix} -2& 0 \\ -0 & 1 \\ -0 & 0 \\ -\end{bmatrix} +\begin{align} +\boldsymbol{\beta} & = (\boldsymbol{X}^{T} \boldsymbol{X})^{-1} \boldsymbol{X}^{T} \boldsymbol{y}, +\tag{1} +\end{align} $$ -

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

    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.

    +

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

    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.

    +

      @@ -448,7 +416,7 @@ decomposition of the design matrix.
    • 56
    • 57
    • ...
    • -
    • 68
    • +
    • 74
    • »
    diff --git a/doc/pub/week35/html/._week35-bs048.html b/doc/pub/week35/html/._week35-bs048.html index b70343582..ac8ba0180 100644 --- a/doc/pub/week35/html/._week35-bs048.html +++ b/doc/pub/week35/html/._week35-bs048.html @@ -75,10 +75,10 @@ doconce format html week35.do.txt --html_style=bootstrap --pygments_html_style=d 2, None, 'interpretations-and-optimizing-our-parameters'), - ('Examples relevant for the exercises', + ('Example relevant for the exercises', 2, None, - 'examples-relevant-for-the-exercises'), + 'example-relevant-for-the-exercises'), ('Own code for Ordinary Least Squares', 2, None, @@ -91,16 +91,14 @@ doconce format html week35.do.txt --html_style=bootstrap --pygments_html_style=d 2, None, 'splitting-our-data-in-training-and-test-data'), - ('Examples', 2, None, 'examples'), + ('The complete code with a simple data set', + 2, + None, + 'the-complete-code-with-a-simple-data-set'), ('Making your own test-train splitting', 2, None, 'making-your-own-test-train-splitting'), - ('The Boston housing data example', - 2, - None, - 'the-boston-housing-data-example'), - ('Housing data, the code', 2, None, 'housing-data-the-code'), ('Reducing the number of degrees of freedom, overarching view', 2, None, @@ -124,10 +122,33 @@ doconce format html week35.do.txt --html_style=bootstrap --pygments_html_style=d 2, None, 'testing-the-means-squared-error-as-function-of-complexity'), - ('More preprocessing examples, Franke function and regression', + ('More preprocessing examples, two-dimensional example, the ' + 'Franke function', 2, None, - 'more-preprocessing-examples-franke-function-and-regression'), + 'more-preprocessing-examples-two-dimensional-example-the-franke-function'), + ('To think about, first part', + 2, + None, + 'to-think-about-first-part'), + ('More thinking', 2, None, 'more-thinking'), + ('Still thinking', 2, None, 'still-thinking'), + ('What does centering (subtracting the mean values) mean ' + 'mathematically?', + 2, + None, + 'what-does-centering-subtracting-the-mean-values-mean-mathematically'), + ('Further Manipulations', 2, None, 'further-manipulations'), + ('Wrapping it up', 2, None, 'wrapping-it-up'), + ('Linear Regression code, Intercept handling first', + 2, + None, + 'linear-regression-code-intercept-handling-first'), + ('The Boston housing data example', + 2, + None, + 'the-boston-housing-data-example'), + ('Housing data, the code', 2, None, 'housing-data-the-code'), ('Material for lecture Thursday, August 31', 2, None, @@ -226,28 +247,7 @@ doconce format html week35.do.txt --html_style=bootstrap --pygments_html_style=d ('Deriving the Lasso Regression Equations', 2, None, - 'deriving-the-lasso-regression-equations'), - ('Exercises for week 35', 2, None, 'exercises-for-week-35'), - ('Exercise 1: Setting up various Python environments', - 2, - None, - 'exercise-1-setting-up-various-python-environments'), - ('Exercise 2: making your own data and exploring scikit-learn', - 2, - None, - 'exercise-2-making-your-own-data-and-exploring-scikit-learn'), - ('Exercise 3: Normalizing our data', - 2, - None, - 'exercise-3-normalizing-our-data'), - ('Exercise 4: Adding Ridge Regression', - 2, - None, - 'exercise-4-adding-ridge-regression'), - ('Exercise 5: Analytical exercises', - 2, - None, - 'exercise-5-analytical-exercises')]} + 'deriving-the-lasso-regression-equations')]} end of tocinfo --> @@ -299,62 +299,63 @@ MathJax.Hub.Config({
  • Other useful relations
  • Meet the Hessian Matrix
  • Interpretations and optimizing our parameters
  • -
  • Examples relevant for the exercises
  • +
  • Example relevant for the exercises
  • Own code for Ordinary Least Squares
  • Adding error analysis and training set up
  • Splitting our Data in Training and Test data
  • -
  • Examples
  • +
  • The complete code with a simple data set
  • Making your own test-train splitting
  • -
  • The Boston housing data example
  • -
  • Housing data, the code
  • -
  • Reducing the number of degrees of freedom, overarching view
  • -
  • Preprocessing our data
  • -
  • Functionality in Scikit-Learn
  • -
  • More preprocessing
  • -
  • Frequently used scaling functions
  • -
  • Example of own Standard scaling
  • -
  • Min-Max Scaling
  • -
  • Testing the Means Squared Error as function of Complexity
  • -
  • More preprocessing examples, Franke function and regression
  • -
  • Material for lecture Thursday, August 31
  • -
  • Mathematical Interpretation of Ordinary Least Squares
  • -
  • Residual Error
  • -
  • Simple case
  • -
  • The singular value decomposition
  • -
  • Linear Regression Problems
  • -
  • Fixing the singularity
  • -
  • Basic math of the SVD
  • -
  • The SVD, a Fantastic Algorithm
  • -
  • Economy-size SVD
  • -
  • Codes for the SVD
  • -
  • Note about SVD Calculations
  • -
  • Mathematics of the SVD and implications
  • -
  • Example Matrix
  • -
  • Setting up the Matrix to be inverted
  • -
  • Further properties (important for our analyses later)
  • -
  • Meet the Covariance Matrix
  • -
  • Introducing the Covariance and Correlation functions
  • -
  • Covariance and Correlation Matrix
  • -
  • Correlation Function and Design/Feature Matrix
  • -
  • Covariance Matrix Examples
  • -
  • Correlation Matrix
  • -
  • Correlation Matrix with Pandas
  • -
  • Correlation Matrix with Pandas and the Franke function
  • -
  • Rewriting the Covariance and/or Correlation Matrix
  • -
  • Linking with the SVD
  • -
  • What does it mean?
  • -
  • And finally \( \boldsymbol{X}\boldsymbol{X}^T \)
  • -
  • Ridge and LASSO Regression
  • -
  • Deriving the Ridge Regression Equations
  • -
  • Interpreting the Ridge results
  • -
  • More interpretations
  • -
  • Deriving the Lasso Regression Equations
  • -
  • Exercises for week 35
  • -
  • Exercise 1: Setting up various Python environments
  • -
  • Exercise 2: making your own data and exploring scikit-learn
  • -
  • Exercise 3: Normalizing our data
  • -
  • Exercise 4: Adding Ridge Regression
  • -
  • Exercise 5: Analytical exercises
  • +
  • Reducing the number of degrees of freedom, overarching view
  • +
  • Preprocessing our data
  • +
  • Functionality in Scikit-Learn
  • +
  • More preprocessing
  • +
  • Frequently used scaling functions
  • +
  • Example of own Standard scaling
  • +
  • Min-Max Scaling
  • +
  • Testing the Means Squared Error as function of Complexity
  • +
  • More preprocessing examples, two-dimensional example, the Franke function
  • +
  • To think about, first part
  • +
  • More thinking
  • +
  • Still thinking
  • +
  • What does centering (subtracting the mean values) mean mathematically?
  • +
  • Further Manipulations
  • +
  • Wrapping it up
  • +
  • Linear Regression code, Intercept handling first
  • +
  • The Boston housing data example
  • +
  • Housing data, the code
  • +
  • Material for lecture Thursday, August 31
  • +
  • Mathematical Interpretation of Ordinary Least Squares
  • +
  • Residual Error
  • +
  • Simple case
  • +
  • The singular value decomposition
  • +
  • Linear Regression Problems
  • +
  • Fixing the singularity
  • +
  • Basic math of the SVD
  • +
  • The SVD, a Fantastic Algorithm
  • +
  • Economy-size SVD
  • +
  • Codes for the SVD
  • +
  • Note about SVD Calculations
  • +
  • Mathematics of the SVD and implications
  • +
  • Example Matrix
  • +
  • Setting up the Matrix to be inverted
  • +
  • Further properties (important for our analyses later)
  • +
  • Meet the Covariance Matrix
  • +
  • Introducing the Covariance and Correlation functions
  • +
  • Covariance and Correlation Matrix
  • +
  • Correlation Function and Design/Feature Matrix
  • +
  • Covariance Matrix Examples
  • +
  • Correlation Matrix
  • +
  • Correlation Matrix with Pandas
  • +
  • Correlation Matrix with Pandas and the Franke function
  • +
  • Rewriting the Covariance and/or Correlation Matrix
  • +
  • Linking with the SVD
  • +
  • What does it mean?
  • +
  • And finally \( \boldsymbol{X}\boldsymbol{X}^T \)
  • +
  • Ridge and LASSO Regression
  • +
  • Deriving the Ridge Regression Equations
  • +
  • Interpreting the Ridge results
  • +
  • More interpretations
  • +
  • Deriving the Lasso Regression Equations
  • @@ -366,45 +367,40 @@ MathJax.Hub.Config({

     

     

     

    -

    Setting up the Matrix to be inverted

    +

    Basic math of the SVD

    -

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

    +

    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 +

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

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

    - +

    and the eigenvalues are given by the diagonal matrix

    $$ -\boldsymbol{X}^T\boldsymbol{X}=\boldsymbol{V}\boldsymbol{\Sigma}^T\boldsymbol{\Sigma}\boldsymbol{V}^T. +\boldsymbol{\Sigma}=\mathrm{Diag}(\lambda_1, \dots,\lambda_n). $$ -

    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

    - +

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

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

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

    +

    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

    $$ -\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} = \begin{bmatrix} +1& -1 \\ +1& -1\\ +\end{bmatrix} $$ -

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

    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.

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

  • 57
  • 58
  • ...
  • -
  • 68
  • +
  • 74
  • »
  • diff --git a/doc/pub/week35/html/._week35-bs049.html b/doc/pub/week35/html/._week35-bs049.html index 7d70bb251..9f09e9650 100644 --- a/doc/pub/week35/html/._week35-bs049.html +++ b/doc/pub/week35/html/._week35-bs049.html @@ -75,10 +75,10 @@ doconce format html week35.do.txt --html_style=bootstrap --pygments_html_style=d 2, None, 'interpretations-and-optimizing-our-parameters'), - ('Examples relevant for the exercises', + ('Example relevant for the exercises', 2, None, - 'examples-relevant-for-the-exercises'), + 'example-relevant-for-the-exercises'), ('Own code for Ordinary Least Squares', 2, None, @@ -91,16 +91,14 @@ doconce format html week35.do.txt --html_style=bootstrap --pygments_html_style=d 2, None, 'splitting-our-data-in-training-and-test-data'), - ('Examples', 2, None, 'examples'), + ('The complete code with a simple data set', + 2, + None, + 'the-complete-code-with-a-simple-data-set'), ('Making your own test-train splitting', 2, None, 'making-your-own-test-train-splitting'), - ('The Boston housing data example', - 2, - None, - 'the-boston-housing-data-example'), - ('Housing data, the code', 2, None, 'housing-data-the-code'), ('Reducing the number of degrees of freedom, overarching view', 2, None, @@ -124,10 +122,33 @@ doconce format html week35.do.txt --html_style=bootstrap --pygments_html_style=d 2, None, 'testing-the-means-squared-error-as-function-of-complexity'), - ('More preprocessing examples, Franke function and regression', + ('More preprocessing examples, two-dimensional example, the ' + 'Franke function', 2, None, - 'more-preprocessing-examples-franke-function-and-regression'), + 'more-preprocessing-examples-two-dimensional-example-the-franke-function'), + ('To think about, first part', + 2, + None, + 'to-think-about-first-part'), + ('More thinking', 2, None, 'more-thinking'), + ('Still thinking', 2, None, 'still-thinking'), + ('What does centering (subtracting the mean values) mean ' + 'mathematically?', + 2, + None, + 'what-does-centering-subtracting-the-mean-values-mean-mathematically'), + ('Further Manipulations', 2, None, 'further-manipulations'), + ('Wrapping it up', 2, None, 'wrapping-it-up'), + ('Linear Regression code, Intercept handling first', + 2, + None, + 'linear-regression-code-intercept-handling-first'), + ('The Boston housing data example', + 2, + None, + 'the-boston-housing-data-example'), + ('Housing data, the code', 2, None, 'housing-data-the-code'), ('Material for lecture Thursday, August 31', 2, None, @@ -226,28 +247,7 @@ doconce format html week35.do.txt --html_style=bootstrap --pygments_html_style=d ('Deriving the Lasso Regression Equations', 2, None, - 'deriving-the-lasso-regression-equations'), - ('Exercises for week 35', 2, None, 'exercises-for-week-35'), - ('Exercise 1: Setting up various Python environments', - 2, - None, - 'exercise-1-setting-up-various-python-environments'), - ('Exercise 2: making your own data and exploring scikit-learn', - 2, - None, - 'exercise-2-making-your-own-data-and-exploring-scikit-learn'), - ('Exercise 3: Normalizing our data', - 2, - None, - 'exercise-3-normalizing-our-data'), - ('Exercise 4: Adding Ridge Regression', - 2, - None, - 'exercise-4-adding-ridge-regression'), - ('Exercise 5: Analytical exercises', - 2, - None, - 'exercise-5-analytical-exercises')]} + 'deriving-the-lasso-regression-equations')]} end of tocinfo --> @@ -299,62 +299,63 @@ MathJax.Hub.Config({
  • Other useful relations
  • Meet the Hessian Matrix
  • Interpretations and optimizing our parameters
  • -
  • Examples relevant for the exercises
  • +
  • Example relevant for the exercises
  • Own code for Ordinary Least Squares
  • Adding error analysis and training set up
  • Splitting our Data in Training and Test data
  • -
  • Examples
  • +
  • The complete code with a simple data set
  • Making your own test-train splitting
  • -
  • The Boston housing data example
  • -
  • Housing data, the code
  • -
  • Reducing the number of degrees of freedom, overarching view
  • -
  • Preprocessing our data
  • -
  • Functionality in Scikit-Learn
  • -
  • More preprocessing
  • -
  • Frequently used scaling functions
  • -
  • Example of own Standard scaling
  • -
  • Min-Max Scaling
  • -
  • Testing the Means Squared Error as function of Complexity
  • -
  • More preprocessing examples, Franke function and regression
  • -
  • Material for lecture Thursday, August 31
  • -
  • Mathematical Interpretation of Ordinary Least Squares
  • -
  • Residual Error
  • -
  • Simple case
  • -
  • The singular value decomposition
  • -
  • Linear Regression Problems
  • -
  • Fixing the singularity
  • -
  • Basic math of the SVD
  • -
  • The SVD, a Fantastic Algorithm
  • -
  • Economy-size SVD
  • -
  • Codes for the SVD
  • -
  • Note about SVD Calculations
  • -
  • Mathematics of the SVD and implications
  • -
  • Example Matrix
  • -
  • Setting up the Matrix to be inverted
  • -
  • Further properties (important for our analyses later)
  • -
  • Meet the Covariance Matrix
  • -
  • Introducing the Covariance and Correlation functions
  • -
  • Covariance and Correlation Matrix
  • -
  • Correlation Function and Design/Feature Matrix
  • -
  • Covariance Matrix Examples
  • -
  • Correlation Matrix
  • -
  • Correlation Matrix with Pandas
  • -
  • Correlation Matrix with Pandas and the Franke function
  • -
  • Rewriting the Covariance and/or Correlation Matrix
  • -
  • Linking with the SVD
  • -
  • What does it mean?
  • -
  • And finally \( \boldsymbol{X}\boldsymbol{X}^T \)
  • -
  • Ridge and LASSO Regression
  • -
  • Deriving the Ridge Regression Equations
  • -
  • Interpreting the Ridge results
  • -
  • More interpretations
  • -
  • Deriving the Lasso Regression Equations
  • -
  • Exercises for week 35
  • -
  • Exercise 1: Setting up various Python environments
  • -
  • Exercise 2: making your own data and exploring scikit-learn
  • -
  • Exercise 3: Normalizing our data
  • -
  • Exercise 4: Adding Ridge Regression
  • -
  • Exercise 5: Analytical exercises
  • +
  • Reducing the number of degrees of freedom, overarching view
  • +
  • Preprocessing our data
  • +
  • Functionality in Scikit-Learn
  • +
  • More preprocessing
  • +
  • Frequently used scaling functions
  • +
  • Example of own Standard scaling
  • +
  • Min-Max Scaling
  • +
  • Testing the Means Squared Error as function of Complexity
  • +
  • More preprocessing examples, two-dimensional example, the Franke function
  • +
  • To think about, first part
  • +
  • More thinking
  • +
  • Still thinking
  • +
  • What does centering (subtracting the mean values) mean mathematically?
  • +
  • Further Manipulations
  • +
  • Wrapping it up
  • +
  • Linear Regression code, Intercept handling first
  • +
  • The Boston housing data example
  • +
  • Housing data, the code
  • +
  • Material for lecture Thursday, August 31
  • +
  • Mathematical Interpretation of Ordinary Least Squares
  • +
  • Residual Error
  • +
  • Simple case
  • +
  • The singular value decomposition
  • +
  • Linear Regression Problems
  • +
  • Fixing the singularity
  • +
  • Basic math of the SVD
  • +
  • The SVD, a Fantastic Algorithm
  • +
  • Economy-size SVD
  • +
  • Codes for the SVD
  • +
  • Note about SVD Calculations
  • +
  • Mathematics of the SVD and implications
  • +
  • Example Matrix
  • +
  • Setting up the Matrix to be inverted
  • +
  • Further properties (important for our analyses later)
  • +
  • Meet the Covariance Matrix
  • +
  • Introducing the Covariance and Correlation functions
  • +
  • Covariance and Correlation Matrix
  • +
  • Correlation Function and Design/Feature Matrix
  • +
  • Covariance Matrix Examples
  • +
  • Correlation Matrix
  • +
  • Correlation Matrix with Pandas
  • +
  • Correlation Matrix with Pandas and the Franke function
  • +
  • Rewriting the Covariance and/or Correlation Matrix
  • +
  • Linking with the SVD
  • +
  • What does it mean?
  • +
  • And finally \( \boldsymbol{X}\boldsymbol{X}^T \)
  • +
  • Ridge and LASSO Regression
  • +
  • Deriving the Ridge Regression Equations
  • +
  • Interpreting the Ridge results
  • +
  • More interpretations
  • +
  • Deriving the Lasso Regression Equations
  • @@ -366,54 +367,53 @@ MathJax.Hub.Config({

     

     

     

    -

    Further properties (important for our analyses later)

    +

    The SVD, a Fantastic Algorithm

    -

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

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

    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

    -

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

    +

      @@ -439,7 +439,7 @@ for the definition of for example the covariance matrix and its relation to the
    • 58
    • 59
    • ...
    • -
    • 68
    • +
    • 74
    • »
    diff --git a/doc/pub/week35/html/._week35-bs050.html b/doc/pub/week35/html/._week35-bs050.html index 02fbf41de..9522b411b 100644 --- a/doc/pub/week35/html/._week35-bs050.html +++ b/doc/pub/week35/html/._week35-bs050.html @@ -75,10 +75,10 @@ doconce format html week35.do.txt --html_style=bootstrap --pygments_html_style=d 2, None, 'interpretations-and-optimizing-our-parameters'), - ('Examples relevant for the exercises', + ('Example relevant for the exercises', 2, None, - 'examples-relevant-for-the-exercises'), + 'example-relevant-for-the-exercises'), ('Own code for Ordinary Least Squares', 2, None, @@ -91,16 +91,14 @@ doconce format html week35.do.txt --html_style=bootstrap --pygments_html_style=d 2, None, 'splitting-our-data-in-training-and-test-data'), - ('Examples', 2, None, 'examples'), + ('The complete code with a simple data set', + 2, + None, + 'the-complete-code-with-a-simple-data-set'), ('Making your own test-train splitting', 2, None, 'making-your-own-test-train-splitting'), - ('The Boston housing data example', - 2, - None, - 'the-boston-housing-data-example'), - ('Housing data, the code', 2, None, 'housing-data-the-code'), ('Reducing the number of degrees of freedom, overarching view', 2, None, @@ -124,10 +122,33 @@ doconce format html week35.do.txt --html_style=bootstrap --pygments_html_style=d 2, None, 'testing-the-means-squared-error-as-function-of-complexity'), - ('More preprocessing examples, Franke function and regression', + ('More preprocessing examples, two-dimensional example, the ' + 'Franke function', 2, None, - 'more-preprocessing-examples-franke-function-and-regression'), + 'more-preprocessing-examples-two-dimensional-example-the-franke-function'), + ('To think about, first part', + 2, + None, + 'to-think-about-first-part'), + ('More thinking', 2, None, 'more-thinking'), + ('Still thinking', 2, None, 'still-thinking'), + ('What does centering (subtracting the mean values) mean ' + 'mathematically?', + 2, + None, + 'what-does-centering-subtracting-the-mean-values-mean-mathematically'), + ('Further Manipulations', 2, None, 'further-manipulations'), + ('Wrapping it up', 2, None, 'wrapping-it-up'), + ('Linear Regression code, Intercept handling first', + 2, + None, + 'linear-regression-code-intercept-handling-first'), + ('The Boston housing data example', + 2, + None, + 'the-boston-housing-data-example'), + ('Housing data, the code', 2, None, 'housing-data-the-code'), ('Material for lecture Thursday, August 31', 2, None, @@ -226,28 +247,7 @@ doconce format html week35.do.txt --html_style=bootstrap --pygments_html_style=d ('Deriving the Lasso Regression Equations', 2, None, - 'deriving-the-lasso-regression-equations'), - ('Exercises for week 35', 2, None, 'exercises-for-week-35'), - ('Exercise 1: Setting up various Python environments', - 2, - None, - 'exercise-1-setting-up-various-python-environments'), - ('Exercise 2: making your own data and exploring scikit-learn', - 2, - None, - 'exercise-2-making-your-own-data-and-exploring-scikit-learn'), - ('Exercise 3: Normalizing our data', - 2, - None, - 'exercise-3-normalizing-our-data'), - ('Exercise 4: Adding Ridge Regression', - 2, - None, - 'exercise-4-adding-ridge-regression'), - ('Exercise 5: Analytical exercises', - 2, - None, - 'exercise-5-analytical-exercises')]} + 'deriving-the-lasso-regression-equations')]} end of tocinfo --> @@ -299,62 +299,63 @@ MathJax.Hub.Config({
  • Other useful relations
  • Meet the Hessian Matrix
  • Interpretations and optimizing our parameters
  • -
  • Examples relevant for the exercises
  • +
  • Example relevant for the exercises
  • Own code for Ordinary Least Squares
  • Adding error analysis and training set up
  • Splitting our Data in Training and Test data
  • -
  • Examples
  • +
  • The complete code with a simple data set
  • Making your own test-train splitting
  • -
  • The Boston housing data example
  • -
  • Housing data, the code
  • -
  • Reducing the number of degrees of freedom, overarching view
  • -
  • Preprocessing our data
  • -
  • Functionality in Scikit-Learn
  • -
  • More preprocessing
  • -
  • Frequently used scaling functions
  • -
  • Example of own Standard scaling
  • -
  • Min-Max Scaling
  • -
  • Testing the Means Squared Error as function of Complexity
  • -
  • More preprocessing examples, Franke function and regression
  • -
  • Material for lecture Thursday, August 31
  • -
  • Mathematical Interpretation of Ordinary Least Squares
  • -
  • Residual Error
  • -
  • Simple case
  • -
  • The singular value decomposition
  • -
  • Linear Regression Problems
  • -
  • Fixing the singularity
  • -
  • Basic math of the SVD
  • -
  • The SVD, a Fantastic Algorithm
  • -
  • Economy-size SVD
  • -
  • Codes for the SVD
  • -
  • Note about SVD Calculations
  • -
  • Mathematics of the SVD and implications
  • -
  • Example Matrix
  • -
  • Setting up the Matrix to be inverted
  • -
  • Further properties (important for our analyses later)
  • -
  • Meet the Covariance Matrix
  • -
  • Introducing the Covariance and Correlation functions
  • -
  • Covariance and Correlation Matrix
  • -
  • Correlation Function and Design/Feature Matrix
  • -
  • Covariance Matrix Examples
  • -
  • Correlation Matrix
  • -
  • Correlation Matrix with Pandas
  • -
  • Correlation Matrix with Pandas and the Franke function
  • -
  • Rewriting the Covariance and/or Correlation Matrix
  • -
  • Linking with the SVD
  • -
  • What does it mean?
  • -
  • And finally \( \boldsymbol{X}\boldsymbol{X}^T \)
  • -
  • Ridge and LASSO Regression
  • -
  • Deriving the Ridge Regression Equations
  • -
  • Interpreting the Ridge results
  • -
  • More interpretations
  • -
  • Deriving the Lasso Regression Equations
  • -
  • Exercises for week 35
  • -
  • Exercise 1: Setting up various Python environments
  • -
  • Exercise 2: making your own data and exploring scikit-learn
  • -
  • Exercise 3: Normalizing our data
  • -
  • Exercise 4: Adding Ridge Regression
  • -
  • Exercise 5: Analytical exercises
  • +
  • Reducing the number of degrees of freedom, overarching view
  • +
  • Preprocessing our data
  • +
  • Functionality in Scikit-Learn
  • +
  • More preprocessing
  • +
  • Frequently used scaling functions
  • +
  • Example of own Standard scaling
  • +
  • Min-Max Scaling
  • +
  • Testing the Means Squared Error as function of Complexity
  • +
  • More preprocessing examples, two-dimensional example, the Franke function
  • +
  • To think about, first part
  • +
  • More thinking
  • +
  • Still thinking
  • +
  • What does centering (subtracting the mean values) mean mathematically?
  • +
  • Further Manipulations
  • +
  • Wrapping it up
  • +
  • Linear Regression code, Intercept handling first
  • +
  • The Boston housing data example
  • +
  • Housing data, the code
  • +
  • Material for lecture Thursday, August 31
  • +
  • Mathematical Interpretation of Ordinary Least Squares
  • +
  • Residual Error
  • +
  • Simple case
  • +
  • The singular value decomposition
  • +
  • Linear Regression Problems
  • +
  • Fixing the singularity
  • +
  • Basic math of the SVD
  • +
  • The SVD, a Fantastic Algorithm
  • +
  • Economy-size SVD
  • +
  • Codes for the SVD
  • +
  • Note about SVD Calculations
  • +
  • Mathematics of the SVD and implications
  • +
  • Example Matrix
  • +
  • Setting up the Matrix to be inverted
  • +
  • Further properties (important for our analyses later)
  • +
  • Meet the Covariance Matrix
  • +
  • Introducing the Covariance and Correlation functions
  • +
  • Covariance and Correlation Matrix
  • +
  • Correlation Function and Design/Feature Matrix
  • +
  • Covariance Matrix Examples
  • +
  • Correlation Matrix
  • +
  • Correlation Matrix with Pandas
  • +
  • Correlation Matrix with Pandas and the Franke function
  • +
  • Rewriting the Covariance and/or Correlation Matrix
  • +
  • Linking with the SVD
  • +
  • What does it mean?
  • +
  • And finally \( \boldsymbol{X}\boldsymbol{X}^T \)
  • +
  • Ridge and LASSO Regression
  • +
  • Deriving the Ridge Regression Equations
  • +
  • Interpreting the Ridge results
  • +
  • More interpretations
  • +
  • Deriving the Lasso Regression Equations
  • @@ -366,31 +367,26 @@ MathJax.Hub.Config({

     

     

     

    -

    Meet the Covariance Matrix

    +

    Economy-size SVD

    -

    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 +

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

    -$$ -\frac{\partial^2 C(\boldsymbol{\beta})}{\partial \boldsymbol{\beta}^T\partial \boldsymbol{\beta}} =\frac{2}{n}\boldsymbol{X}^T\boldsymbol{X}. -$$ +

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

    -

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

    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.

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

  • 59
  • 60
  • ...
  • -
  • 68
  • +
  • 74
  • »
  • diff --git a/doc/pub/week35/html/._week35-bs051.html b/doc/pub/week35/html/._week35-bs051.html index 824f0f952..5019639d8 100644 --- a/doc/pub/week35/html/._week35-bs051.html +++ b/doc/pub/week35/html/._week35-bs051.html @@ -75,10 +75,10 @@ doconce format html week35.do.txt --html_style=bootstrap --pygments_html_style=d 2, None, 'interpretations-and-optimizing-our-parameters'), - ('Examples relevant for the exercises', + ('Example relevant for the exercises', 2, None, - 'examples-relevant-for-the-exercises'), + 'example-relevant-for-the-exercises'), ('Own code for Ordinary Least Squares', 2, None, @@ -91,16 +91,14 @@ doconce format html week35.do.txt --html_style=bootstrap --pygments_html_style=d 2, None, 'splitting-our-data-in-training-and-test-data'), - ('Examples', 2, None, 'examples'), + ('The complete code with a simple data set', + 2, + None, + 'the-complete-code-with-a-simple-data-set'), ('Making your own test-train splitting', 2, None, 'making-your-own-test-train-splitting'), - ('The Boston housing data example', - 2, - None, - 'the-boston-housing-data-example'), - ('Housing data, the code', 2, None, 'housing-data-the-code'), ('Reducing the number of degrees of freedom, overarching view', 2, None, @@ -124,10 +122,33 @@ doconce format html week35.do.txt --html_style=bootstrap --pygments_html_style=d 2, None, 'testing-the-means-squared-error-as-function-of-complexity'), - ('More preprocessing examples, Franke function and regression', + ('More preprocessing examples, two-dimensional example, the ' + 'Franke function', 2, None, - 'more-preprocessing-examples-franke-function-and-regression'), + 'more-preprocessing-examples-two-dimensional-example-the-franke-function'), + ('To think about, first part', + 2, + None, + 'to-think-about-first-part'), + ('More thinking', 2, None, 'more-thinking'), + ('Still thinking', 2, None, 'still-thinking'), + ('What does centering (subtracting the mean values) mean ' + 'mathematically?', + 2, + None, + 'what-does-centering-subtracting-the-mean-values-mean-mathematically'), + ('Further Manipulations', 2, None, 'further-manipulations'), + ('Wrapping it up', 2, None, 'wrapping-it-up'), + ('Linear Regression code, Intercept handling first', + 2, + None, + 'linear-regression-code-intercept-handling-first'), + ('The Boston housing data example', + 2, + None, + 'the-boston-housing-data-example'), + ('Housing data, the code', 2, None, 'housing-data-the-code'), ('Material for lecture Thursday, August 31', 2, None, @@ -226,28 +247,7 @@ doconce format html week35.do.txt --html_style=bootstrap --pygments_html_style=d ('Deriving the Lasso Regression Equations', 2, None, - 'deriving-the-lasso-regression-equations'), - ('Exercises for week 35', 2, None, 'exercises-for-week-35'), - ('Exercise 1: Setting up various Python environments', - 2, - None, - 'exercise-1-setting-up-various-python-environments'), - ('Exercise 2: making your own data and exploring scikit-learn', - 2, - None, - 'exercise-2-making-your-own-data-and-exploring-scikit-learn'), - ('Exercise 3: Normalizing our data', - 2, - None, - 'exercise-3-normalizing-our-data'), - ('Exercise 4: Adding Ridge Regression', - 2, - None, - 'exercise-4-adding-ridge-regression'), - ('Exercise 5: Analytical exercises', - 2, - None, - 'exercise-5-analytical-exercises')]} + 'deriving-the-lasso-regression-equations')]} end of tocinfo --> @@ -299,62 +299,63 @@ MathJax.Hub.Config({
  • Other useful relations
  • Meet the Hessian Matrix
  • Interpretations and optimizing our parameters
  • -
  • Examples relevant for the exercises
  • +
  • Example relevant for the exercises
  • Own code for Ordinary Least Squares
  • Adding error analysis and training set up
  • Splitting our Data in Training and Test data
  • -
  • Examples
  • +
  • The complete code with a simple data set
  • Making your own test-train splitting
  • -
  • The Boston housing data example
  • -
  • Housing data, the code
  • -
  • Reducing the number of degrees of freedom, overarching view
  • -
  • Preprocessing our data
  • -
  • Functionality in Scikit-Learn
  • -
  • More preprocessing
  • -
  • Frequently used scaling functions
  • -
  • Example of own Standard scaling
  • -
  • Min-Max Scaling
  • -
  • Testing the Means Squared Error as function of Complexity
  • -
  • More preprocessing examples, Franke function and regression
  • -
  • Material for lecture Thursday, August 31
  • -
  • Mathematical Interpretation of Ordinary Least Squares
  • -
  • Residual Error
  • -
  • Simple case
  • -
  • The singular value decomposition
  • -
  • Linear Regression Problems
  • -
  • Fixing the singularity
  • -
  • Basic math of the SVD
  • -
  • The SVD, a Fantastic Algorithm
  • -
  • Economy-size SVD
  • -
  • Codes for the SVD
  • -
  • Note about SVD Calculations
  • -
  • Mathematics of the SVD and implications
  • -
  • Example Matrix
  • -
  • Setting up the Matrix to be inverted
  • -
  • Further properties (important for our analyses later)
  • -
  • Meet the Covariance Matrix
  • -
  • Introducing the Covariance and Correlation functions
  • -
  • Covariance and Correlation Matrix
  • -
  • Correlation Function and Design/Feature Matrix
  • -
  • Covariance Matrix Examples
  • -
  • Correlation Matrix
  • -
  • Correlation Matrix with Pandas
  • -
  • Correlation Matrix with Pandas and the Franke function
  • -
  • Rewriting the Covariance and/or Correlation Matrix
  • -
  • Linking with the SVD
  • -
  • What does it mean?
  • -
  • And finally \( \boldsymbol{X}\boldsymbol{X}^T \)
  • -
  • Ridge and LASSO Regression
  • -
  • Deriving the Ridge Regression Equations
  • -
  • Interpreting the Ridge results
  • -
  • More interpretations
  • -
  • Deriving the Lasso Regression Equations
  • -
  • Exercises for week 35
  • -
  • Exercise 1: Setting up various Python environments
  • -
  • Exercise 2: making your own data and exploring scikit-learn
  • -
  • Exercise 3: Normalizing our data
  • -
  • Exercise 4: Adding Ridge Regression
  • -
  • Exercise 5: Analytical exercises
  • +
  • Reducing the number of degrees of freedom, overarching view
  • +
  • Preprocessing our data
  • +
  • Functionality in Scikit-Learn
  • +
  • More preprocessing
  • +
  • Frequently used scaling functions
  • +
  • Example of own Standard scaling
  • +
  • Min-Max Scaling
  • +
  • Testing the Means Squared Error as function of Complexity
  • +
  • More preprocessing examples, two-dimensional example, the Franke function
  • +
  • To think about, first part
  • +
  • More thinking
  • +
  • Still thinking
  • +
  • What does centering (subtracting the mean values) mean mathematically?
  • +
  • Further Manipulations
  • +
  • Wrapping it up
  • +
  • Linear Regression code, Intercept handling first
  • +
  • The Boston housing data example
  • +
  • Housing data, the code
  • +
  • Material for lecture Thursday, August 31
  • +
  • Mathematical Interpretation of Ordinary Least Squares
  • +
  • Residual Error
  • +
  • Simple case
  • +
  • The singular value decomposition
  • +
  • Linear Regression Problems
  • +
  • Fixing the singularity
  • +
  • Basic math of the SVD
  • +
  • The SVD, a Fantastic Algorithm
  • +
  • Economy-size SVD
  • +
  • Codes for the SVD
  • +
  • Note about SVD Calculations
  • +
  • Mathematics of the SVD and implications
  • +
  • Example Matrix
  • +
  • Setting up the Matrix to be inverted
  • +
  • Further properties (important for our analyses later)
  • +
  • Meet the Covariance Matrix
  • +
  • Introducing the Covariance and Correlation functions
  • +
  • Covariance and Correlation Matrix
  • +
  • Correlation Function and Design/Feature Matrix
  • +
  • Covariance Matrix Examples
  • +
  • Correlation Matrix
  • +
  • Correlation Matrix with Pandas
  • +
  • Correlation Matrix with Pandas and the Franke function
  • +
  • Rewriting the Covariance and/or Correlation Matrix
  • +
  • Linking with the SVD
  • +
  • What does it mean?
  • +
  • And finally \( \boldsymbol{X}\boldsymbol{X}^T \)
  • +
  • Ridge and LASSO Regression
  • +
  • Deriving the Ridge Regression Equations
  • +
  • Interpreting the Ridge results
  • +
  • More interpretations
  • +
  • Deriving the Lasso Regression Equations
  • @@ -366,46 +367,67 @@ MathJax.Hub.Config({

     

     

     

    -

    Introducing the Covariance and Correlation functions

    +

    Codes for the SVD

    -

    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 -

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

    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}). -$$ + D = np.zeros((len(U),len(VT))) + for i in range(0,len(VT)): + D[i,i]=S[i] + return U @ D @ VT -

    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}. -$$ +X = np.array([ [1.0,-1.0], [1.0,-1.0]]) +#X = np.array([[1, 2], [3, 4], [5, 6]]) -

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

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

  • 60
  • 61
  • ...
  • -
  • 68
  • +
  • 74
  • »
  • diff --git a/doc/pub/week35/html/._week35-bs052.html b/doc/pub/week35/html/._week35-bs052.html index 0fc958417..f26b1fc29 100644 --- a/doc/pub/week35/html/._week35-bs052.html +++ b/doc/pub/week35/html/._week35-bs052.html @@ -75,10 +75,10 @@ doconce format html week35.do.txt --html_style=bootstrap --pygments_html_style=d 2, None, 'interpretations-and-optimizing-our-parameters'), - ('Examples relevant for the exercises', + ('Example relevant for the exercises', 2, None, - 'examples-relevant-for-the-exercises'), + 'example-relevant-for-the-exercises'), ('Own code for Ordinary Least Squares', 2, None, @@ -91,16 +91,14 @@ doconce format html week35.do.txt --html_style=bootstrap --pygments_html_style=d 2, None, 'splitting-our-data-in-training-and-test-data'), - ('Examples', 2, None, 'examples'), + ('The complete code with a simple data set', + 2, + None, + 'the-complete-code-with-a-simple-data-set'), ('Making your own test-train splitting', 2, None, 'making-your-own-test-train-splitting'), - ('The Boston housing data example', - 2, - None, - 'the-boston-housing-data-example'), - ('Housing data, the code', 2, None, 'housing-data-the-code'), ('Reducing the number of degrees of freedom, overarching view', 2, None, @@ -124,10 +122,33 @@ doconce format html week35.do.txt --html_style=bootstrap --pygments_html_style=d 2, None, 'testing-the-means-squared-error-as-function-of-complexity'), - ('More preprocessing examples, Franke function and regression', + ('More preprocessing examples, two-dimensional example, the ' + 'Franke function', 2, None, - 'more-preprocessing-examples-franke-function-and-regression'), + 'more-preprocessing-examples-two-dimensional-example-the-franke-function'), + ('To think about, first part', + 2, + None, + 'to-think-about-first-part'), + ('More thinking', 2, None, 'more-thinking'), + ('Still thinking', 2, None, 'still-thinking'), + ('What does centering (subtracting the mean values) mean ' + 'mathematically?', + 2, + None, + 'what-does-centering-subtracting-the-mean-values-mean-mathematically'), + ('Further Manipulations', 2, None, 'further-manipulations'), + ('Wrapping it up', 2, None, 'wrapping-it-up'), + ('Linear Regression code, Intercept handling first', + 2, + None, + 'linear-regression-code-intercept-handling-first'), + ('The Boston housing data example', + 2, + None, + 'the-boston-housing-data-example'), + ('Housing data, the code', 2, None, 'housing-data-the-code'), ('Material for lecture Thursday, August 31', 2, None, @@ -226,28 +247,7 @@ doconce format html week35.do.txt --html_style=bootstrap --pygments_html_style=d ('Deriving the Lasso Regression Equations', 2, None, - 'deriving-the-lasso-regression-equations'), - ('Exercises for week 35', 2, None, 'exercises-for-week-35'), - ('Exercise 1: Setting up various Python environments', - 2, - None, - 'exercise-1-setting-up-various-python-environments'), - ('Exercise 2: making your own data and exploring scikit-learn', - 2, - None, - 'exercise-2-making-your-own-data-and-exploring-scikit-learn'), - ('Exercise 3: Normalizing our data', - 2, - None, - 'exercise-3-normalizing-our-data'), - ('Exercise 4: Adding Ridge Regression', - 2, - None, - 'exercise-4-adding-ridge-regression'), - ('Exercise 5: Analytical exercises', - 2, - None, - 'exercise-5-analytical-exercises')]} + 'deriving-the-lasso-regression-equations')]} end of tocinfo --> @@ -299,62 +299,63 @@ MathJax.Hub.Config({
  • Other useful relations
  • Meet the Hessian Matrix
  • Interpretations and optimizing our parameters
  • -
  • Examples relevant for the exercises
  • +
  • Example relevant for the exercises
  • Own code for Ordinary Least Squares
  • Adding error analysis and training set up
  • Splitting our Data in Training and Test data
  • -
  • Examples
  • +
  • The complete code with a simple data set
  • Making your own test-train splitting
  • -
  • The Boston housing data example
  • -
  • Housing data, the code
  • -
  • Reducing the number of degrees of freedom, overarching view
  • -
  • Preprocessing our data
  • -
  • Functionality in Scikit-Learn
  • -
  • More preprocessing
  • -
  • Frequently used scaling functions
  • -
  • Example of own Standard scaling
  • -
  • Min-Max Scaling
  • -
  • Testing the Means Squared Error as function of Complexity
  • -
  • More preprocessing examples, Franke function and regression
  • -
  • Material for lecture Thursday, August 31
  • -
  • Mathematical Interpretation of Ordinary Least Squares
  • -
  • Residual Error
  • -
  • Simple case
  • -
  • The singular value decomposition
  • -
  • Linear Regression Problems
  • -
  • Fixing the singularity
  • -
  • Basic math of the SVD
  • -
  • The SVD, a Fantastic Algorithm
  • -
  • Economy-size SVD
  • -
  • Codes for the SVD
  • -
  • Note about SVD Calculations
  • -
  • Mathematics of the SVD and implications
  • -
  • Example Matrix
  • -
  • Setting up the Matrix to be inverted
  • -
  • Further properties (important for our analyses later)
  • -
  • Meet the Covariance Matrix
  • -
  • Introducing the Covariance and Correlation functions
  • -
  • Covariance and Correlation Matrix
  • -
  • Correlation Function and Design/Feature Matrix
  • -
  • Covariance Matrix Examples
  • -
  • Correlation Matrix
  • -
  • Correlation Matrix with Pandas
  • -
  • Correlation Matrix with Pandas and the Franke function
  • -
  • Rewriting the Covariance and/or Correlation Matrix
  • -
  • Linking with the SVD
  • -
  • What does it mean?
  • -
  • And finally \( \boldsymbol{X}\boldsymbol{X}^T \)
  • -
  • Ridge and LASSO Regression
  • -
  • Deriving the Ridge Regression Equations
  • -
  • Interpreting the Ridge results
  • -
  • More interpretations
  • -
  • Deriving the Lasso Regression Equations
  • -
  • Exercises for week 35
  • -
  • Exercise 1: Setting up various Python environments
  • -
  • Exercise 2: making your own data and exploring scikit-learn
  • -
  • Exercise 3: Normalizing our data
  • -
  • Exercise 4: Adding Ridge Regression
  • -
  • Exercise 5: Analytical exercises
  • +
  • Reducing the number of degrees of freedom, overarching view
  • +
  • Preprocessing our data
  • +
  • Functionality in Scikit-Learn
  • +
  • More preprocessing
  • +
  • Frequently used scaling functions
  • +
  • Example of own Standard scaling
  • +
  • Min-Max Scaling
  • +
  • Testing the Means Squared Error as function of Complexity
  • +
  • More preprocessing examples, two-dimensional example, the Franke function
  • +
  • To think about, first part
  • +
  • More thinking
  • +
  • Still thinking
  • +
  • What does centering (subtracting the mean values) mean mathematically?
  • +
  • Further Manipulations
  • +
  • Wrapping it up
  • +
  • Linear Regression code, Intercept handling first
  • +
  • The Boston housing data example
  • +
  • Housing data, the code
  • +
  • Material for lecture Thursday, August 31
  • +
  • Mathematical Interpretation of Ordinary Least Squares
  • +
  • Residual Error
  • +
  • Simple case
  • +
  • The singular value decomposition
  • +
  • Linear Regression Problems
  • +
  • Fixing the singularity
  • +
  • Basic math of the SVD
  • +
  • The SVD, a Fantastic Algorithm
  • +
  • Economy-size SVD
  • +
  • Codes for the SVD
  • +
  • Note about SVD Calculations
  • +
  • Mathematics of the SVD and implications
  • +
  • Example Matrix
  • +
  • Setting up the Matrix to be inverted
  • +
  • Further properties (important for our analyses later)
  • +
  • Meet the Covariance Matrix
  • +
  • Introducing the Covariance and Correlation functions
  • +
  • Covariance and Correlation Matrix
  • +
  • Correlation Function and Design/Feature Matrix
  • +
  • Covariance Matrix Examples
  • +
  • Correlation Matrix
  • +
  • Correlation Matrix with Pandas
  • +
  • Correlation Matrix with Pandas and the Franke function
  • +
  • Rewriting the Covariance and/or Correlation Matrix
  • +
  • Linking with the SVD
  • +
  • What does it mean?
  • +
  • And finally \( \boldsymbol{X}\boldsymbol{X}^T \)
  • +
  • Ridge and LASSO Regression
  • +
  • Deriving the Ridge Regression Equations
  • +
  • Interpreting the Ridge results
  • +
  • More interpretations
  • +
  • Deriving the Lasso Regression Equations
  • @@ -366,32 +367,23 @@ MathJax.Hub.Config({

     

     

     

    -

    Covariance and Correlation Matrix

    +

    Note about SVD Calculations

    -

    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 +

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

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

    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.

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

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

    +

    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 +

    @@ -418,7 +410,7 @@ $$

  • 61
  • 62
  • ...
  • -
  • 68
  • +
  • 74
  • »
  • diff --git a/doc/pub/week35/html/._week35-bs053.html b/doc/pub/week35/html/._week35-bs053.html index a81a30c7a..b9481893f 100644 --- a/doc/pub/week35/html/._week35-bs053.html +++ b/doc/pub/week35/html/._week35-bs053.html @@ -75,10 +75,10 @@ doconce format html week35.do.txt --html_style=bootstrap --pygments_html_style=d 2, None, 'interpretations-and-optimizing-our-parameters'), - ('Examples relevant for the exercises', + ('Example relevant for the exercises', 2, None, - 'examples-relevant-for-the-exercises'), + 'example-relevant-for-the-exercises'), ('Own code for Ordinary Least Squares', 2, None, @@ -91,16 +91,14 @@ doconce format html week35.do.txt --html_style=bootstrap --pygments_html_style=d 2, None, 'splitting-our-data-in-training-and-test-data'), - ('Examples', 2, None, 'examples'), + ('The complete code with a simple data set', + 2, + None, + 'the-complete-code-with-a-simple-data-set'), ('Making your own test-train splitting', 2, None, 'making-your-own-test-train-splitting'), - ('The Boston housing data example', - 2, - None, - 'the-boston-housing-data-example'), - ('Housing data, the code', 2, None, 'housing-data-the-code'), ('Reducing the number of degrees of freedom, overarching view', 2, None, @@ -124,10 +122,33 @@ doconce format html week35.do.txt --html_style=bootstrap --pygments_html_style=d 2, None, 'testing-the-means-squared-error-as-function-of-complexity'), - ('More preprocessing examples, Franke function and regression', + ('More preprocessing examples, two-dimensional example, the ' + 'Franke function', 2, None, - 'more-preprocessing-examples-franke-function-and-regression'), + 'more-preprocessing-examples-two-dimensional-example-the-franke-function'), + ('To think about, first part', + 2, + None, + 'to-think-about-first-part'), + ('More thinking', 2, None, 'more-thinking'), + ('Still thinking', 2, None, 'still-thinking'), + ('What does centering (subtracting the mean values) mean ' + 'mathematically?', + 2, + None, + 'what-does-centering-subtracting-the-mean-values-mean-mathematically'), + ('Further Manipulations', 2, None, 'further-manipulations'), + ('Wrapping it up', 2, None, 'wrapping-it-up'), + ('Linear Regression code, Intercept handling first', + 2, + None, + 'linear-regression-code-intercept-handling-first'), + ('The Boston housing data example', + 2, + None, + 'the-boston-housing-data-example'), + ('Housing data, the code', 2, None, 'housing-data-the-code'), ('Material for lecture Thursday, August 31', 2, None, @@ -226,28 +247,7 @@ doconce format html week35.do.txt --html_style=bootstrap --pygments_html_style=d ('Deriving the Lasso Regression Equations', 2, None, - 'deriving-the-lasso-regression-equations'), - ('Exercises for week 35', 2, None, 'exercises-for-week-35'), - ('Exercise 1: Setting up various Python environments', - 2, - None, - 'exercise-1-setting-up-various-python-environments'), - ('Exercise 2: making your own data and exploring scikit-learn', - 2, - None, - 'exercise-2-making-your-own-data-and-exploring-scikit-learn'), - ('Exercise 3: Normalizing our data', - 2, - None, - 'exercise-3-normalizing-our-data'), - ('Exercise 4: Adding Ridge Regression', - 2, - None, - 'exercise-4-adding-ridge-regression'), - ('Exercise 5: Analytical exercises', - 2, - None, - 'exercise-5-analytical-exercises')]} + 'deriving-the-lasso-regression-equations')]} end of tocinfo --> @@ -299,62 +299,63 @@ MathJax.Hub.Config({
  • Other useful relations
  • Meet the Hessian Matrix
  • Interpretations and optimizing our parameters
  • -
  • Examples relevant for the exercises
  • +
  • Example relevant for the exercises
  • Own code for Ordinary Least Squares
  • Adding error analysis and training set up
  • Splitting our Data in Training and Test data
  • -
  • Examples
  • +
  • The complete code with a simple data set
  • Making your own test-train splitting
  • -
  • The Boston housing data example
  • -
  • Housing data, the code
  • -
  • Reducing the number of degrees of freedom, overarching view
  • -
  • Preprocessing our data
  • -
  • Functionality in Scikit-Learn
  • -
  • More preprocessing
  • -
  • Frequently used scaling functions
  • -
  • Example of own Standard scaling
  • -
  • Min-Max Scaling
  • -
  • Testing the Means Squared Error as function of Complexity
  • -
  • More preprocessing examples, Franke function and regression
  • -
  • Material for lecture Thursday, August 31
  • -
  • Mathematical Interpretation of Ordinary Least Squares
  • -
  • Residual Error
  • -
  • Simple case
  • -
  • The singular value decomposition
  • -
  • Linear Regression Problems
  • -
  • Fixing the singularity
  • -
  • Basic math of the SVD
  • -
  • The SVD, a Fantastic Algorithm
  • -
  • Economy-size SVD
  • -
  • Codes for the SVD
  • -
  • Note about SVD Calculations
  • -
  • Mathematics of the SVD and implications
  • -
  • Example Matrix
  • -
  • Setting up the Matrix to be inverted
  • -
  • Further properties (important for our analyses later)
  • -
  • Meet the Covariance Matrix
  • -
  • Introducing the Covariance and Correlation functions
  • -
  • Covariance and Correlation Matrix
  • -
  • Correlation Function and Design/Feature Matrix
  • -
  • Covariance Matrix Examples
  • -
  • Correlation Matrix
  • -
  • Correlation Matrix with Pandas
  • -
  • Correlation Matrix with Pandas and the Franke function
  • -
  • Rewriting the Covariance and/or Correlation Matrix
  • -
  • Linking with the SVD
  • -
  • What does it mean?
  • -
  • And finally \( \boldsymbol{X}\boldsymbol{X}^T \)
  • -
  • Ridge and LASSO Regression
  • -
  • Deriving the Ridge Regression Equations
  • -
  • Interpreting the Ridge results
  • -
  • More interpretations
  • -
  • Deriving the Lasso Regression Equations
  • -
  • Exercises for week 35
  • -
  • Exercise 1: Setting up various Python environments
  • -
  • Exercise 2: making your own data and exploring scikit-learn
  • -
  • Exercise 3: Normalizing our data
  • -
  • Exercise 4: Adding Ridge Regression
  • -
  • Exercise 5: Analytical exercises
  • +
  • Reducing the number of degrees of freedom, overarching view
  • +
  • Preprocessing our data
  • +
  • Functionality in Scikit-Learn
  • +
  • More preprocessing
  • +
  • Frequently used scaling functions
  • +
  • Example of own Standard scaling
  • +
  • Min-Max Scaling
  • +
  • Testing the Means Squared Error as function of Complexity
  • +
  • More preprocessing examples, two-dimensional example, the Franke function
  • +
  • To think about, first part
  • +
  • More thinking
  • +
  • Still thinking
  • +
  • What does centering (subtracting the mean values) mean mathematically?
  • +
  • Further Manipulations
  • +
  • Wrapping it up
  • +
  • Linear Regression code, Intercept handling first
  • +
  • The Boston housing data example
  • +
  • Housing data, the code
  • +
  • Material for lecture Thursday, August 31
  • +
  • Mathematical Interpretation of Ordinary Least Squares
  • +
  • Residual Error
  • +
  • Simple case
  • +
  • The singular value decomposition
  • +
  • Linear Regression Problems
  • +
  • Fixing the singularity
  • +
  • Basic math of the SVD
  • +
  • The SVD, a Fantastic Algorithm
  • +
  • Economy-size SVD
  • +
  • Codes for the SVD
  • +
  • Note about SVD Calculations
  • +
  • Mathematics of the SVD and implications
  • +
  • Example Matrix
  • +
  • Setting up the Matrix to be inverted
  • +
  • Further properties (important for our analyses later)
  • +
  • Meet the Covariance Matrix
  • +
  • Introducing the Covariance and Correlation functions
  • +
  • Covariance and Correlation Matrix
  • +
  • Correlation Function and Design/Feature Matrix
  • +
  • Covariance Matrix Examples
  • +
  • Correlation Matrix
  • +
  • Correlation Matrix with Pandas
  • +
  • Correlation Matrix with Pandas and the Franke function
  • +
  • Rewriting the Covariance and/or Correlation Matrix
  • +
  • Linking with the SVD
  • +
  • What does it mean?
  • +
  • And finally \( \boldsymbol{X}\boldsymbol{X}^T \)
  • +
  • Ridge and LASSO Regression
  • +
  • Deriving the Ridge Regression Equations
  • +
  • Interpreting the Ridge results
  • +
  • More interpretations
  • +
  • Deriving the Lasso Regression Equations
  • @@ -366,12 +367,11 @@ MathJax.Hub.Config({

     

     

     

    -

    Correlation Function and Design/Feature Matrix

    +

    Mathematics of the SVD and implications

    -

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

    +

    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}\\ @@ -380,51 +380,25 @@ 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}, +\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 -

    +

    We can SVD decompose our matrix as

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

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

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

    -

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

    +

    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

    $$ -\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}, +\sigma_0 > \sigma_1 > \sigma_2 > \dots > \sigma_{p-1} > 0. $$ +

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

    @@ -451,7 +425,7 @@ $$

  • 62
  • 63
  • ...
  • -
  • 68
  • +
  • 74
  • »
  • diff --git a/doc/pub/week35/html/._week35-bs054.html b/doc/pub/week35/html/._week35-bs054.html index 66adcbdd5..2a462ab19 100644 --- a/doc/pub/week35/html/._week35-bs054.html +++ b/doc/pub/week35/html/._week35-bs054.html @@ -75,10 +75,10 @@ doconce format html week35.do.txt --html_style=bootstrap --pygments_html_style=d 2, None, 'interpretations-and-optimizing-our-parameters'), - ('Examples relevant for the exercises', + ('Example relevant for the exercises', 2, None, - 'examples-relevant-for-the-exercises'), + 'example-relevant-for-the-exercises'), ('Own code for Ordinary Least Squares', 2, None, @@ -91,16 +91,14 @@ doconce format html week35.do.txt --html_style=bootstrap --pygments_html_style=d 2, None, 'splitting-our-data-in-training-and-test-data'), - ('Examples', 2, None, 'examples'), + ('The complete code with a simple data set', + 2, + None, + 'the-complete-code-with-a-simple-data-set'), ('Making your own test-train splitting', 2, None, 'making-your-own-test-train-splitting'), - ('The Boston housing data example', - 2, - None, - 'the-boston-housing-data-example'), - ('Housing data, the code', 2, None, 'housing-data-the-code'), ('Reducing the number of degrees of freedom, overarching view', 2, None, @@ -124,10 +122,33 @@ doconce format html week35.do.txt --html_style=bootstrap --pygments_html_style=d 2, None, 'testing-the-means-squared-error-as-function-of-complexity'), - ('More preprocessing examples, Franke function and regression', + ('More preprocessing examples, two-dimensional example, the ' + 'Franke function', 2, None, - 'more-preprocessing-examples-franke-function-and-regression'), + 'more-preprocessing-examples-two-dimensional-example-the-franke-function'), + ('To think about, first part', + 2, + None, + 'to-think-about-first-part'), + ('More thinking', 2, None, 'more-thinking'), + ('Still thinking', 2, None, 'still-thinking'), + ('What does centering (subtracting the mean values) mean ' + 'mathematically?', + 2, + None, + 'what-does-centering-subtracting-the-mean-values-mean-mathematically'), + ('Further Manipulations', 2, None, 'further-manipulations'), + ('Wrapping it up', 2, None, 'wrapping-it-up'), + ('Linear Regression code, Intercept handling first', + 2, + None, + 'linear-regression-code-intercept-handling-first'), + ('The Boston housing data example', + 2, + None, + 'the-boston-housing-data-example'), + ('Housing data, the code', 2, None, 'housing-data-the-code'), ('Material for lecture Thursday, August 31', 2, None, @@ -226,28 +247,7 @@ doconce format html week35.do.txt --html_style=bootstrap --pygments_html_style=d ('Deriving the Lasso Regression Equations', 2, None, - 'deriving-the-lasso-regression-equations'), - ('Exercises for week 35', 2, None, 'exercises-for-week-35'), - ('Exercise 1: Setting up various Python environments', - 2, - None, - 'exercise-1-setting-up-various-python-environments'), - ('Exercise 2: making your own data and exploring scikit-learn', - 2, - None, - 'exercise-2-making-your-own-data-and-exploring-scikit-learn'), - ('Exercise 3: Normalizing our data', - 2, - None, - 'exercise-3-normalizing-our-data'), - ('Exercise 4: Adding Ridge Regression', - 2, - None, - 'exercise-4-adding-ridge-regression'), - ('Exercise 5: Analytical exercises', - 2, - None, - 'exercise-5-analytical-exercises')]} + 'deriving-the-lasso-regression-equations')]} end of tocinfo --> @@ -299,62 +299,63 @@ MathJax.Hub.Config({
  • Other useful relations
  • Meet the Hessian Matrix
  • Interpretations and optimizing our parameters
  • -
  • Examples relevant for the exercises
  • +
  • Example relevant for the exercises
  • Own code for Ordinary Least Squares
  • Adding error analysis and training set up
  • Splitting our Data in Training and Test data
  • -
  • Examples
  • +
  • The complete code with a simple data set
  • Making your own test-train splitting
  • -
  • The Boston housing data example
  • -
  • Housing data, the code
  • -
  • Reducing the number of degrees of freedom, overarching view
  • -
  • Preprocessing our data
  • -
  • Functionality in Scikit-Learn
  • -
  • More preprocessing
  • -
  • Frequently used scaling functions
  • -
  • Example of own Standard scaling
  • -
  • Min-Max Scaling
  • -
  • Testing the Means Squared Error as function of Complexity
  • -
  • More preprocessing examples, Franke function and regression
  • -
  • Material for lecture Thursday, August 31
  • -
  • Mathematical Interpretation of Ordinary Least Squares
  • -
  • Residual Error
  • -
  • Simple case
  • -
  • The singular value decomposition
  • -
  • Linear Regression Problems
  • -
  • Fixing the singularity
  • -
  • Basic math of the SVD
  • -
  • The SVD, a Fantastic Algorithm
  • -
  • Economy-size SVD
  • -
  • Codes for the SVD
  • -
  • Note about SVD Calculations
  • -
  • Mathematics of the SVD and implications
  • -
  • Example Matrix
  • -
  • Setting up the Matrix to be inverted
  • -
  • Further properties (important for our analyses later)
  • -
  • Meet the Covariance Matrix
  • -
  • Introducing the Covariance and Correlation functions
  • -
  • Covariance and Correlation Matrix
  • -
  • Correlation Function and Design/Feature Matrix
  • -
  • Covariance Matrix Examples
  • -
  • Correlation Matrix
  • -
  • Correlation Matrix with Pandas
  • -
  • Correlation Matrix with Pandas and the Franke function
  • -
  • Rewriting the Covariance and/or Correlation Matrix
  • -
  • Linking with the SVD
  • -
  • What does it mean?
  • -
  • And finally \( \boldsymbol{X}\boldsymbol{X}^T \)
  • -
  • Ridge and LASSO Regression
  • -
  • Deriving the Ridge Regression Equations
  • -
  • Interpreting the Ridge results
  • -
  • More interpretations
  • -
  • Deriving the Lasso Regression Equations
  • -
  • Exercises for week 35
  • -
  • Exercise 1: Setting up various Python environments
  • -
  • Exercise 2: making your own data and exploring scikit-learn
  • -
  • Exercise 3: Normalizing our data
  • -
  • Exercise 4: Adding Ridge Regression
  • -
  • Exercise 5: Analytical exercises
  • +
  • Reducing the number of degrees of freedom, overarching view
  • +
  • Preprocessing our data
  • +
  • Functionality in Scikit-Learn
  • +
  • More preprocessing
  • +
  • Frequently used scaling functions
  • +
  • Example of own Standard scaling
  • +
  • Min-Max Scaling
  • +
  • Testing the Means Squared Error as function of Complexity
  • +
  • More preprocessing examples, two-dimensional example, the Franke function
  • +
  • To think about, first part
  • +
  • More thinking
  • +
  • Still thinking
  • +
  • What does centering (subtracting the mean values) mean mathematically?
  • +
  • Further Manipulations
  • +
  • Wrapping it up
  • +
  • Linear Regression code, Intercept handling first
  • +
  • The Boston housing data example
  • +
  • Housing data, the code
  • +
  • Material for lecture Thursday, August 31
  • +
  • Mathematical Interpretation of Ordinary Least Squares
  • +
  • Residual Error
  • +
  • Simple case
  • +
  • The singular value decomposition
  • +
  • Linear Regression Problems
  • +
  • Fixing the singularity
  • +
  • Basic math of the SVD
  • +
  • The SVD, a Fantastic Algorithm
  • +
  • Economy-size SVD
  • +
  • Codes for the SVD
  • +
  • Note about SVD Calculations
  • +
  • Mathematics of the SVD and implications
  • +
  • Example Matrix
  • +
  • Setting up the Matrix to be inverted
  • +
  • Further properties (important for our analyses later)
  • +
  • Meet the Covariance Matrix
  • +
  • Introducing the Covariance and Correlation functions
  • +
  • Covariance and Correlation Matrix
  • +
  • Correlation Function and Design/Feature Matrix
  • +
  • Covariance Matrix Examples
  • +
  • Correlation Matrix
  • +
  • Correlation Matrix with Pandas
  • +
  • Correlation Matrix with Pandas and the Franke function
  • +
  • Rewriting the Covariance and/or Correlation Matrix
  • +
  • Linking with the SVD
  • +
  • What does it mean?
  • +
  • And finally \( \boldsymbol{X}\boldsymbol{X}^T \)
  • +
  • Ridge and LASSO Regression
  • +
  • Deriving the Ridge Regression Equations
  • +
  • Interpreting the Ridge results
  • +
  • More interpretations
  • +
  • Deriving the Lasso Regression Equations
  • @@ -366,62 +367,63 @@ MathJax.Hub.Config({

     

     

     

    -

    Covariance Matrix Examples

    +

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

    +

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

    -

    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}, +\boldsymbol{\Sigma}= +\begin{bmatrix} +2& 0 \\ +0 & 1 \\ +0 & 0 \\ +\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 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.

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

    diff --git a/doc/pub/week35/html/._week35-bs055.html b/doc/pub/week35/html/._week35-bs055.html index e687998eb..d74381f9b 100644 --- a/doc/pub/week35/html/._week35-bs055.html +++ b/doc/pub/week35/html/._week35-bs055.html @@ -75,10 +75,10 @@ doconce format html week35.do.txt --html_style=bootstrap --pygments_html_style=d 2, None, 'interpretations-and-optimizing-our-parameters'), - ('Examples relevant for the exercises', + ('Example relevant for the exercises', 2, None, - 'examples-relevant-for-the-exercises'), + 'example-relevant-for-the-exercises'), ('Own code for Ordinary Least Squares', 2, None, @@ -91,16 +91,14 @@ doconce format html week35.do.txt --html_style=bootstrap --pygments_html_style=d 2, None, 'splitting-our-data-in-training-and-test-data'), - ('Examples', 2, None, 'examples'), + ('The complete code with a simple data set', + 2, + None, + 'the-complete-code-with-a-simple-data-set'), ('Making your own test-train splitting', 2, None, 'making-your-own-test-train-splitting'), - ('The Boston housing data example', - 2, - None, - 'the-boston-housing-data-example'), - ('Housing data, the code', 2, None, 'housing-data-the-code'), ('Reducing the number of degrees of freedom, overarching view', 2, None, @@ -124,10 +122,33 @@ doconce format html week35.do.txt --html_style=bootstrap --pygments_html_style=d 2, None, 'testing-the-means-squared-error-as-function-of-complexity'), - ('More preprocessing examples, Franke function and regression', + ('More preprocessing examples, two-dimensional example, the ' + 'Franke function', 2, None, - 'more-preprocessing-examples-franke-function-and-regression'), + 'more-preprocessing-examples-two-dimensional-example-the-franke-function'), + ('To think about, first part', + 2, + None, + 'to-think-about-first-part'), + ('More thinking', 2, None, 'more-thinking'), + ('Still thinking', 2, None, 'still-thinking'), + ('What does centering (subtracting the mean values) mean ' + 'mathematically?', + 2, + None, + 'what-does-centering-subtracting-the-mean-values-mean-mathematically'), + ('Further Manipulations', 2, None, 'further-manipulations'), + ('Wrapping it up', 2, None, 'wrapping-it-up'), + ('Linear Regression code, Intercept handling first', + 2, + None, + 'linear-regression-code-intercept-handling-first'), + ('The Boston housing data example', + 2, + None, + 'the-boston-housing-data-example'), + ('Housing data, the code', 2, None, 'housing-data-the-code'), ('Material for lecture Thursday, August 31', 2, None, @@ -226,28 +247,7 @@ doconce format html week35.do.txt --html_style=bootstrap --pygments_html_style=d ('Deriving the Lasso Regression Equations', 2, None, - 'deriving-the-lasso-regression-equations'), - ('Exercises for week 35', 2, None, 'exercises-for-week-35'), - ('Exercise 1: Setting up various Python environments', - 2, - None, - 'exercise-1-setting-up-various-python-environments'), - ('Exercise 2: making your own data and exploring scikit-learn', - 2, - None, - 'exercise-2-making-your-own-data-and-exploring-scikit-learn'), - ('Exercise 3: Normalizing our data', - 2, - None, - 'exercise-3-normalizing-our-data'), - ('Exercise 4: Adding Ridge Regression', - 2, - None, - 'exercise-4-adding-ridge-regression'), - ('Exercise 5: Analytical exercises', - 2, - None, - 'exercise-5-analytical-exercises')]} + 'deriving-the-lasso-regression-equations')]} end of tocinfo --> @@ -299,62 +299,63 @@ MathJax.Hub.Config({
  • Other useful relations
  • Meet the Hessian Matrix
  • Interpretations and optimizing our parameters
  • -
  • Examples relevant for the exercises
  • +
  • Example relevant for the exercises
  • Own code for Ordinary Least Squares
  • Adding error analysis and training set up
  • Splitting our Data in Training and Test data
  • -
  • Examples
  • +
  • The complete code with a simple data set
  • Making your own test-train splitting
  • -
  • The Boston housing data example
  • -
  • Housing data, the code
  • -
  • Reducing the number of degrees of freedom, overarching view
  • -
  • Preprocessing our data
  • -
  • Functionality in Scikit-Learn
  • -
  • More preprocessing
  • -
  • Frequently used scaling functions
  • -
  • Example of own Standard scaling
  • -
  • Min-Max Scaling
  • -
  • Testing the Means Squared Error as function of Complexity
  • -
  • More preprocessing examples, Franke function and regression
  • -
  • Material for lecture Thursday, August 31
  • -
  • Mathematical Interpretation of Ordinary Least Squares
  • -
  • Residual Error
  • -
  • Simple case
  • -
  • The singular value decomposition
  • -
  • Linear Regression Problems
  • -
  • Fixing the singularity
  • -
  • Basic math of the SVD
  • -
  • The SVD, a Fantastic Algorithm
  • -
  • Economy-size SVD
  • -
  • Codes for the SVD
  • -
  • Note about SVD Calculations
  • -
  • Mathematics of the SVD and implications
  • -
  • Example Matrix
  • -
  • Setting up the Matrix to be inverted
  • -
  • Further properties (important for our analyses later)
  • -
  • Meet the Covariance Matrix
  • -
  • Introducing the Covariance and Correlation functions
  • -
  • Covariance and Correlation Matrix
  • -
  • Correlation Function and Design/Feature Matrix
  • -
  • Covariance Matrix Examples
  • -
  • Correlation Matrix
  • -
  • Correlation Matrix with Pandas
  • -
  • Correlation Matrix with Pandas and the Franke function
  • -
  • Rewriting the Covariance and/or Correlation Matrix
  • -
  • Linking with the SVD
  • -
  • What does it mean?
  • -
  • And finally \( \boldsymbol{X}\boldsymbol{X}^T \)
  • -
  • Ridge and LASSO Regression
  • -
  • Deriving the Ridge Regression Equations
  • -
  • Interpreting the Ridge results
  • -
  • More interpretations
  • -
  • Deriving the Lasso Regression Equations
  • -
  • Exercises for week 35
  • -
  • Exercise 1: Setting up various Python environments
  • -
  • Exercise 2: making your own data and exploring scikit-learn
  • -
  • Exercise 3: Normalizing our data
  • -
  • Exercise 4: Adding Ridge Regression
  • -
  • Exercise 5: Analytical exercises
  • +
  • Reducing the number of degrees of freedom, overarching view
  • +
  • Preprocessing our data
  • +
  • Functionality in Scikit-Learn
  • +
  • More preprocessing
  • +
  • Frequently used scaling functions
  • +
  • Example of own Standard scaling
  • +
  • Min-Max Scaling
  • +
  • Testing the Means Squared Error as function of Complexity
  • +
  • More preprocessing examples, two-dimensional example, the Franke function
  • +
  • To think about, first part
  • +
  • More thinking
  • +
  • Still thinking
  • +
  • What does centering (subtracting the mean values) mean mathematically?
  • +
  • Further Manipulations
  • +
  • Wrapping it up
  • +
  • Linear Regression code, Intercept handling first
  • +
  • The Boston housing data example
  • +
  • Housing data, the code
  • +
  • Material for lecture Thursday, August 31
  • +
  • Mathematical Interpretation of Ordinary Least Squares
  • +
  • Residual Error
  • +
  • Simple case
  • +
  • The singular value decomposition
  • +
  • Linear Regression Problems
  • +
  • Fixing the singularity
  • +
  • Basic math of the SVD
  • +
  • The SVD, a Fantastic Algorithm
  • +
  • Economy-size SVD
  • +
  • Codes for the SVD
  • +
  • Note about SVD Calculations
  • +
  • Mathematics of the SVD and implications
  • +
  • Example Matrix
  • +
  • Setting up the Matrix to be inverted
  • +
  • Further properties (important for our analyses later)
  • +
  • Meet the Covariance Matrix
  • +
  • Introducing the Covariance and Correlation functions
  • +
  • Covariance and Correlation Matrix
  • +
  • Correlation Function and Design/Feature Matrix
  • +
  • Covariance Matrix Examples
  • +
  • Correlation Matrix
  • +
  • Correlation Matrix with Pandas
  • +
  • Correlation Matrix with Pandas and the Franke function
  • +
  • Rewriting the Covariance and/or Correlation Matrix
  • +
  • Linking with the SVD
  • +
  • What does it mean?
  • +
  • And finally \( \boldsymbol{X}\boldsymbol{X}^T \)
  • +
  • Ridge and LASSO Regression
  • +
  • Deriving the Ridge Regression Equations
  • +
  • Interpreting the Ridge results
  • +
  • More interpretations
  • +
  • Deriving the Lasso Regression Equations
  • @@ -366,65 +367,47 @@ MathJax.Hub.Config({

     

     

     

    -

    Correlation Matrix

    +

    Setting up the Matrix to be inverted

    -

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

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

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

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

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

    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

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

    and using our SVD decomposition of \( \boldsymbol{X} \) 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}, +$$ + +

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

    - - -
    -
    -
    -
    -
    -
    import numpy as np
    -n = 100
    -# define two vectors                                                                                           
    -x = np.random.random(size=n)
    -y = 4+3*x+np.random.normal(size=n)
    -#scaling the x and y vectors                                                                                   
    -x = x - np.mean(x)
    -y = y - np.mean(y)
    -variance_x = np.sum(x@x)/n
    -variance_y = np.sum(y@y)/n
    -print(variance_x)
    -print(variance_y)
    -cov_xy = np.sum(x@y)/n
    -cov_xx = np.sum(x@x)/n
    -cov_yy = np.sum(y@y)/n
    -C = np.zeros((2,2))
    -C[0,0]= cov_xx/variance_x
    -C[1,1]= cov_yy/variance_y
    -C[0,1]= cov_xy/np.sqrt(variance_y*variance_x)
    -C[1,0]= C[0,1]
    -print(C)
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    - -

    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.

    -

      @@ -450,7 +433,7 @@ this matrix we easily see that it is a positive definite matrix.
    • 64
    • 65
    • ...
    • -
    • 68
    • +
    • 74
    • »
    diff --git a/doc/pub/week35/html/._week35-bs056.html b/doc/pub/week35/html/._week35-bs056.html index 5f66a167b..9930d7ae9 100644 --- a/doc/pub/week35/html/._week35-bs056.html +++ b/doc/pub/week35/html/._week35-bs056.html @@ -75,10 +75,10 @@ doconce format html week35.do.txt --html_style=bootstrap --pygments_html_style=d 2, None, 'interpretations-and-optimizing-our-parameters'), - ('Examples relevant for the exercises', + ('Example relevant for the exercises', 2, None, - 'examples-relevant-for-the-exercises'), + 'example-relevant-for-the-exercises'), ('Own code for Ordinary Least Squares', 2, None, @@ -91,16 +91,14 @@ doconce format html week35.do.txt --html_style=bootstrap --pygments_html_style=d 2, None, 'splitting-our-data-in-training-and-test-data'), - ('Examples', 2, None, 'examples'), + ('The complete code with a simple data set', + 2, + None, + 'the-complete-code-with-a-simple-data-set'), ('Making your own test-train splitting', 2, None, 'making-your-own-test-train-splitting'), - ('The Boston housing data example', - 2, - None, - 'the-boston-housing-data-example'), - ('Housing data, the code', 2, None, 'housing-data-the-code'), ('Reducing the number of degrees of freedom, overarching view', 2, None, @@ -124,10 +122,33 @@ doconce format html week35.do.txt --html_style=bootstrap --pygments_html_style=d 2, None, 'testing-the-means-squared-error-as-function-of-complexity'), - ('More preprocessing examples, Franke function and regression', + ('More preprocessing examples, two-dimensional example, the ' + 'Franke function', 2, None, - 'more-preprocessing-examples-franke-function-and-regression'), + 'more-preprocessing-examples-two-dimensional-example-the-franke-function'), + ('To think about, first part', + 2, + None, + 'to-think-about-first-part'), + ('More thinking', 2, None, 'more-thinking'), + ('Still thinking', 2, None, 'still-thinking'), + ('What does centering (subtracting the mean values) mean ' + 'mathematically?', + 2, + None, + 'what-does-centering-subtracting-the-mean-values-mean-mathematically'), + ('Further Manipulations', 2, None, 'further-manipulations'), + ('Wrapping it up', 2, None, 'wrapping-it-up'), + ('Linear Regression code, Intercept handling first', + 2, + None, + 'linear-regression-code-intercept-handling-first'), + ('The Boston housing data example', + 2, + None, + 'the-boston-housing-data-example'), + ('Housing data, the code', 2, None, 'housing-data-the-code'), ('Material for lecture Thursday, August 31', 2, None, @@ -226,28 +247,7 @@ doconce format html week35.do.txt --html_style=bootstrap --pygments_html_style=d ('Deriving the Lasso Regression Equations', 2, None, - 'deriving-the-lasso-regression-equations'), - ('Exercises for week 35', 2, None, 'exercises-for-week-35'), - ('Exercise 1: Setting up various Python environments', - 2, - None, - 'exercise-1-setting-up-various-python-environments'), - ('Exercise 2: making your own data and exploring scikit-learn', - 2, - None, - 'exercise-2-making-your-own-data-and-exploring-scikit-learn'), - ('Exercise 3: Normalizing our data', - 2, - None, - 'exercise-3-normalizing-our-data'), - ('Exercise 4: Adding Ridge Regression', - 2, - None, - 'exercise-4-adding-ridge-regression'), - ('Exercise 5: Analytical exercises', - 2, - None, - 'exercise-5-analytical-exercises')]} + 'deriving-the-lasso-regression-equations')]} end of tocinfo --> @@ -299,62 +299,63 @@ MathJax.Hub.Config({
  • Other useful relations
  • Meet the Hessian Matrix
  • Interpretations and optimizing our parameters
  • -
  • Examples relevant for the exercises
  • +
  • Example relevant for the exercises
  • Own code for Ordinary Least Squares
  • Adding error analysis and training set up
  • Splitting our Data in Training and Test data
  • -
  • Examples
  • +
  • The complete code with a simple data set
  • Making your own test-train splitting
  • -
  • The Boston housing data example
  • -
  • Housing data, the code
  • -
  • Reducing the number of degrees of freedom, overarching view
  • -
  • Preprocessing our data
  • -
  • Functionality in Scikit-Learn
  • -
  • More preprocessing
  • -
  • Frequently used scaling functions
  • -
  • Example of own Standard scaling
  • -
  • Min-Max Scaling
  • -
  • Testing the Means Squared Error as function of Complexity
  • -
  • More preprocessing examples, Franke function and regression
  • -
  • Material for lecture Thursday, August 31
  • -
  • Mathematical Interpretation of Ordinary Least Squares
  • -
  • Residual Error
  • -
  • Simple case
  • -
  • The singular value decomposition
  • -
  • Linear Regression Problems
  • -
  • Fixing the singularity
  • -
  • Basic math of the SVD
  • -
  • The SVD, a Fantastic Algorithm
  • -
  • Economy-size SVD
  • -
  • Codes for the SVD
  • -
  • Note about SVD Calculations
  • -
  • Mathematics of the SVD and implications
  • -
  • Example Matrix
  • -
  • Setting up the Matrix to be inverted
  • -
  • Further properties (important for our analyses later)
  • -
  • Meet the Covariance Matrix
  • -
  • Introducing the Covariance and Correlation functions
  • -
  • Covariance and Correlation Matrix
  • -
  • Correlation Function and Design/Feature Matrix
  • -
  • Covariance Matrix Examples
  • -
  • Correlation Matrix
  • -
  • Correlation Matrix with Pandas
  • -
  • Correlation Matrix with Pandas and the Franke function
  • -
  • Rewriting the Covariance and/or Correlation Matrix
  • -
  • Linking with the SVD
  • -
  • What does it mean?
  • -
  • And finally \( \boldsymbol{X}\boldsymbol{X}^T \)
  • -
  • Ridge and LASSO Regression
  • -
  • Deriving the Ridge Regression Equations
  • -
  • Interpreting the Ridge results
  • -
  • More interpretations
  • -
  • Deriving the Lasso Regression Equations
  • -
  • Exercises for week 35
  • -
  • Exercise 1: Setting up various Python environments
  • -
  • Exercise 2: making your own data and exploring scikit-learn
  • -
  • Exercise 3: Normalizing our data
  • -
  • Exercise 4: Adding Ridge Regression
  • -
  • Exercise 5: Analytical exercises
  • +
  • Reducing the number of degrees of freedom, overarching view
  • +
  • Preprocessing our data
  • +
  • Functionality in Scikit-Learn
  • +
  • More preprocessing
  • +
  • Frequently used scaling functions
  • +
  • Example of own Standard scaling
  • +
  • Min-Max Scaling
  • +
  • Testing the Means Squared Error as function of Complexity
  • +
  • More preprocessing examples, two-dimensional example, the Franke function
  • +
  • To think about, first part
  • +
  • More thinking
  • +
  • Still thinking
  • +
  • What does centering (subtracting the mean values) mean mathematically?
  • +
  • Further Manipulations
  • +
  • Wrapping it up
  • +
  • Linear Regression code, Intercept handling first
  • +
  • The Boston housing data example
  • +
  • Housing data, the code
  • +
  • Material for lecture Thursday, August 31
  • +
  • Mathematical Interpretation of Ordinary Least Squares
  • +
  • Residual Error
  • +
  • Simple case
  • +
  • The singular value decomposition
  • +
  • Linear Regression Problems
  • +
  • Fixing the singularity
  • +
  • Basic math of the SVD
  • +
  • The SVD, a Fantastic Algorithm
  • +
  • Economy-size SVD
  • +
  • Codes for the SVD
  • +
  • Note about SVD Calculations
  • +
  • Mathematics of the SVD and implications
  • +
  • Example Matrix
  • +
  • Setting up the Matrix to be inverted
  • +
  • Further properties (important for our analyses later)
  • +
  • Meet the Covariance Matrix
  • +
  • Introducing the Covariance and Correlation functions
  • +
  • Covariance and Correlation Matrix
  • +
  • Correlation Function and Design/Feature Matrix
  • +
  • Covariance Matrix Examples
  • +
  • Correlation Matrix
  • +
  • Correlation Matrix with Pandas
  • +
  • Correlation Matrix with Pandas and the Franke function
  • +
  • Rewriting the Covariance and/or Correlation Matrix
  • +
  • Linking with the SVD
  • +
  • What does it mean?
  • +
  • And finally \( \boldsymbol{X}\boldsymbol{X}^T \)
  • +
  • Ridge and LASSO Regression
  • +
  • Deriving the Ridge Regression Equations
  • +
  • Interpreting the Ridge results
  • +
  • More interpretations
  • +
  • Deriving the Lasso Regression Equations
  • @@ -366,46 +367,53 @@ MathJax.Hub.Config({

     

     

     

    -

    Correlation Matrix with Pandas

    +

    Further properties (important for our analyses later)

    -

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

    +

    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. +$$ - -
    -
    -
    -
    -
    -
    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)
    -Xpd = pd.DataFrame(X)
    -print(Xpd)
    -correlation_matrix = Xpd.corr()
    -print(correlation_matrix)
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    +

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

    We expand this model to the Franke function discussed above.

    +

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

    + +

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

    @@ -432,7 +440,7 @@ correlation_matrix = Xpd65

  • 66
  • ...
  • -
  • 68
  • +
  • 74
  • »
  • diff --git a/doc/pub/week35/html/._week35-bs057.html b/doc/pub/week35/html/._week35-bs057.html index 1cb0e8c9a..5c4bde9f6 100644 --- a/doc/pub/week35/html/._week35-bs057.html +++ b/doc/pub/week35/html/._week35-bs057.html @@ -75,10 +75,10 @@ doconce format html week35.do.txt --html_style=bootstrap --pygments_html_style=d 2, None, 'interpretations-and-optimizing-our-parameters'), - ('Examples relevant for the exercises', + ('Example relevant for the exercises', 2, None, - 'examples-relevant-for-the-exercises'), + 'example-relevant-for-the-exercises'), ('Own code for Ordinary Least Squares', 2, None, @@ -91,16 +91,14 @@ doconce format html week35.do.txt --html_style=bootstrap --pygments_html_style=d 2, None, 'splitting-our-data-in-training-and-test-data'), - ('Examples', 2, None, 'examples'), + ('The complete code with a simple data set', + 2, + None, + 'the-complete-code-with-a-simple-data-set'), ('Making your own test-train splitting', 2, None, 'making-your-own-test-train-splitting'), - ('The Boston housing data example', - 2, - None, - 'the-boston-housing-data-example'), - ('Housing data, the code', 2, None, 'housing-data-the-code'), ('Reducing the number of degrees of freedom, overarching view', 2, None, @@ -124,10 +122,33 @@ doconce format html week35.do.txt --html_style=bootstrap --pygments_html_style=d 2, None, 'testing-the-means-squared-error-as-function-of-complexity'), - ('More preprocessing examples, Franke function and regression', + ('More preprocessing examples, two-dimensional example, the ' + 'Franke function', 2, None, - 'more-preprocessing-examples-franke-function-and-regression'), + 'more-preprocessing-examples-two-dimensional-example-the-franke-function'), + ('To think about, first part', + 2, + None, + 'to-think-about-first-part'), + ('More thinking', 2, None, 'more-thinking'), + ('Still thinking', 2, None, 'still-thinking'), + ('What does centering (subtracting the mean values) mean ' + 'mathematically?', + 2, + None, + 'what-does-centering-subtracting-the-mean-values-mean-mathematically'), + ('Further Manipulations', 2, None, 'further-manipulations'), + ('Wrapping it up', 2, None, 'wrapping-it-up'), + ('Linear Regression code, Intercept handling first', + 2, + None, + 'linear-regression-code-intercept-handling-first'), + ('The Boston housing data example', + 2, + None, + 'the-boston-housing-data-example'), + ('Housing data, the code', 2, None, 'housing-data-the-code'), ('Material for lecture Thursday, August 31', 2, None, @@ -226,28 +247,7 @@ doconce format html week35.do.txt --html_style=bootstrap --pygments_html_style=d ('Deriving the Lasso Regression Equations', 2, None, - 'deriving-the-lasso-regression-equations'), - ('Exercises for week 35', 2, None, 'exercises-for-week-35'), - ('Exercise 1: Setting up various Python environments', - 2, - None, - 'exercise-1-setting-up-various-python-environments'), - ('Exercise 2: making your own data and exploring scikit-learn', - 2, - None, - 'exercise-2-making-your-own-data-and-exploring-scikit-learn'), - ('Exercise 3: Normalizing our data', - 2, - None, - 'exercise-3-normalizing-our-data'), - ('Exercise 4: Adding Ridge Regression', - 2, - None, - 'exercise-4-adding-ridge-regression'), - ('Exercise 5: Analytical exercises', - 2, - None, - 'exercise-5-analytical-exercises')]} + 'deriving-the-lasso-regression-equations')]} end of tocinfo --> @@ -299,62 +299,63 @@ MathJax.Hub.Config({
  • Other useful relations
  • Meet the Hessian Matrix
  • Interpretations and optimizing our parameters
  • -
  • Examples relevant for the exercises
  • +
  • Example relevant for the exercises
  • Own code for Ordinary Least Squares
  • Adding error analysis and training set up
  • Splitting our Data in Training and Test data
  • -
  • Examples
  • +
  • The complete code with a simple data set
  • Making your own test-train splitting
  • -
  • The Boston housing data example
  • -
  • Housing data, the code
  • -
  • Reducing the number of degrees of freedom, overarching view
  • -
  • Preprocessing our data
  • -
  • Functionality in Scikit-Learn
  • -
  • More preprocessing
  • -
  • Frequently used scaling functions
  • -
  • Example of own Standard scaling
  • -
  • Min-Max Scaling
  • -
  • Testing the Means Squared Error as function of Complexity
  • -
  • More preprocessing examples, Franke function and regression
  • -
  • Material for lecture Thursday, August 31
  • -
  • Mathematical Interpretation of Ordinary Least Squares
  • -
  • Residual Error
  • -
  • Simple case
  • -
  • The singular value decomposition
  • -
  • Linear Regression Problems
  • -
  • Fixing the singularity
  • -
  • Basic math of the SVD
  • -
  • The SVD, a Fantastic Algorithm
  • -
  • Economy-size SVD
  • -
  • Codes for the SVD
  • -
  • Note about SVD Calculations
  • -
  • Mathematics of the SVD and implications
  • -
  • Example Matrix
  • -
  • Setting up the Matrix to be inverted
  • -
  • Further properties (important for our analyses later)
  • -
  • Meet the Covariance Matrix
  • -
  • Introducing the Covariance and Correlation functions
  • -
  • Covariance and Correlation Matrix
  • -
  • Correlation Function and Design/Feature Matrix
  • -
  • Covariance Matrix Examples
  • -
  • Correlation Matrix
  • -
  • Correlation Matrix with Pandas
  • -
  • Correlation Matrix with Pandas and the Franke function
  • -
  • Rewriting the Covariance and/or Correlation Matrix
  • -
  • Linking with the SVD
  • -
  • What does it mean?
  • -
  • And finally \( \boldsymbol{X}\boldsymbol{X}^T \)
  • -
  • Ridge and LASSO Regression
  • -
  • Deriving the Ridge Regression Equations
  • -
  • Interpreting the Ridge results
  • -
  • More interpretations
  • -
  • Deriving the Lasso Regression Equations
  • -
  • Exercises for week 35
  • -
  • Exercise 1: Setting up various Python environments
  • -
  • Exercise 2: making your own data and exploring scikit-learn
  • -
  • Exercise 3: Normalizing our data
  • -
  • Exercise 4: Adding Ridge Regression
  • -
  • Exercise 5: Analytical exercises
  • +
  • Reducing the number of degrees of freedom, overarching view
  • +
  • Preprocessing our data
  • +
  • Functionality in Scikit-Learn
  • +
  • More preprocessing
  • +
  • Frequently used scaling functions
  • +
  • Example of own Standard scaling
  • +
  • Min-Max Scaling
  • +
  • Testing the Means Squared Error as function of Complexity
  • +
  • More preprocessing examples, two-dimensional example, the Franke function
  • +
  • To think about, first part
  • +
  • More thinking
  • +
  • Still thinking
  • +
  • What does centering (subtracting the mean values) mean mathematically?
  • +
  • Further Manipulations
  • +
  • Wrapping it up
  • +
  • Linear Regression code, Intercept handling first
  • +
  • The Boston housing data example
  • +
  • Housing data, the code
  • +
  • Material for lecture Thursday, August 31
  • +
  • Mathematical Interpretation of Ordinary Least Squares
  • +
  • Residual Error
  • +
  • Simple case
  • +
  • The singular value decomposition
  • +
  • Linear Regression Problems
  • +
  • Fixing the singularity
  • +
  • Basic math of the SVD
  • +
  • The SVD, a Fantastic Algorithm
  • +
  • Economy-size SVD
  • +
  • Codes for the SVD
  • +
  • Note about SVD Calculations
  • +
  • Mathematics of the SVD and implications
  • +
  • Example Matrix
  • +
  • Setting up the Matrix to be inverted
  • +
  • Further properties (important for our analyses later)
  • +
  • Meet the Covariance Matrix
  • +
  • Introducing the Covariance and Correlation functions
  • +
  • Covariance and Correlation Matrix
  • +
  • Correlation Function and Design/Feature Matrix
  • +
  • Covariance Matrix Examples
  • +
  • Correlation Matrix
  • +
  • Correlation Matrix with Pandas
  • +
  • Correlation Matrix with Pandas and the Franke function
  • +
  • Rewriting the Covariance and/or Correlation Matrix
  • +
  • Linking with the SVD
  • +
  • What does it mean?
  • +
  • And finally \( \boldsymbol{X}\boldsymbol{X}^T \)
  • +
  • Ridge and LASSO Regression
  • +
  • Deriving the Ridge Regression Equations
  • +
  • Interpreting the Ridge results
  • +
  • More interpretations
  • +
  • Deriving the Lasso Regression Equations
  • @@ -366,82 +367,31 @@ MathJax.Hub.Config({

     

     

     

    -

    Correlation Matrix with Pandas and the Franke function

    +

    Meet the Covariance Matrix

    +

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

    - -
    -
    -
    -
    -
    -
    # Common imports
    -import numpy as np
    -import pandas as pd
    -
    -
    -def FrankeFunction(x,y):
    -	term1 = 0.75*np.exp(-(0.25*(9*x-2)**2) - 0.25*((9*y-2)**2))
    -	term2 = 0.75*np.exp(-((9*x+1)**2)/49.0 - 0.1*(9*y+1))
    -	term3 = 0.5*np.exp(-(9*x-7)**2/4.0 - 0.25*((9*y-3)**2))
    -	term4 = -0.2*np.exp(-(9*x-4)**2 - (9*y-7)**2)
    -	return term1 + term2 + term3 + term4
    -
    -
    -def create_X(x, y, n ):
    -	if len(x.shape) > 1:
    -		x = np.ravel(x)
    -		y = np.ravel(y)
    -
    -	N = len(x)
    -	l = int((n+1)*(n+2)/2)		# Number of elements in beta
    -	X = np.ones((N,l))
    -
    -	for i in range(1,n+1):
    -		q = int((i)*(i+1)/2)
    -		for k in range(i+1):
    -			X[:,q+k] = (x**(i-k))*(y**k)
    -
    -	return X
    -
    -
    -# Making meshgrid of datapoints and compute Franke's function
    -n = 4
    -N = 100
    -x = np.sort(np.random.uniform(0, 1, N))
    -y = np.sort(np.random.uniform(0, 1, N))
    -z = FrankeFunction(x, y)
    -X = create_X(x, y, n=n)    
    -
    -Xpd = pd.DataFrame(X)
    -# subtract the mean values and set up the covariance matrix
    -Xpd = Xpd - Xpd.mean()
    -covariance_matrix = Xpd.cov()
    -print(covariance_matrix)
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    - -

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

    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

    -

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

    @@ -469,7 +419,7 @@ matrix without these elements.

  • 66
  • 67
  • ...
  • -
  • 68
  • +
  • 74
  • »
  • diff --git a/doc/pub/week35/html/._week35-bs058.html b/doc/pub/week35/html/._week35-bs058.html index 4f59121ab..f52640fb5 100644 --- a/doc/pub/week35/html/._week35-bs058.html +++ b/doc/pub/week35/html/._week35-bs058.html @@ -75,10 +75,10 @@ doconce format html week35.do.txt --html_style=bootstrap --pygments_html_style=d 2, None, 'interpretations-and-optimizing-our-parameters'), - ('Examples relevant for the exercises', + ('Example relevant for the exercises', 2, None, - 'examples-relevant-for-the-exercises'), + 'example-relevant-for-the-exercises'), ('Own code for Ordinary Least Squares', 2, None, @@ -91,16 +91,14 @@ doconce format html week35.do.txt --html_style=bootstrap --pygments_html_style=d 2, None, 'splitting-our-data-in-training-and-test-data'), - ('Examples', 2, None, 'examples'), + ('The complete code with a simple data set', + 2, + None, + 'the-complete-code-with-a-simple-data-set'), ('Making your own test-train splitting', 2, None, 'making-your-own-test-train-splitting'), - ('The Boston housing data example', - 2, - None, - 'the-boston-housing-data-example'), - ('Housing data, the code', 2, None, 'housing-data-the-code'), ('Reducing the number of degrees of freedom, overarching view', 2, None, @@ -124,10 +122,33 @@ doconce format html week35.do.txt --html_style=bootstrap --pygments_html_style=d 2, None, 'testing-the-means-squared-error-as-function-of-complexity'), - ('More preprocessing examples, Franke function and regression', + ('More preprocessing examples, two-dimensional example, the ' + 'Franke function', 2, None, - 'more-preprocessing-examples-franke-function-and-regression'), + 'more-preprocessing-examples-two-dimensional-example-the-franke-function'), + ('To think about, first part', + 2, + None, + 'to-think-about-first-part'), + ('More thinking', 2, None, 'more-thinking'), + ('Still thinking', 2, None, 'still-thinking'), + ('What does centering (subtracting the mean values) mean ' + 'mathematically?', + 2, + None, + 'what-does-centering-subtracting-the-mean-values-mean-mathematically'), + ('Further Manipulations', 2, None, 'further-manipulations'), + ('Wrapping it up', 2, None, 'wrapping-it-up'), + ('Linear Regression code, Intercept handling first', + 2, + None, + 'linear-regression-code-intercept-handling-first'), + ('The Boston housing data example', + 2, + None, + 'the-boston-housing-data-example'), + ('Housing data, the code', 2, None, 'housing-data-the-code'), ('Material for lecture Thursday, August 31', 2, None, @@ -226,28 +247,7 @@ doconce format html week35.do.txt --html_style=bootstrap --pygments_html_style=d ('Deriving the Lasso Regression Equations', 2, None, - 'deriving-the-lasso-regression-equations'), - ('Exercises for week 35', 2, None, 'exercises-for-week-35'), - ('Exercise 1: Setting up various Python environments', - 2, - None, - 'exercise-1-setting-up-various-python-environments'), - ('Exercise 2: making your own data and exploring scikit-learn', - 2, - None, - 'exercise-2-making-your-own-data-and-exploring-scikit-learn'), - ('Exercise 3: Normalizing our data', - 2, - None, - 'exercise-3-normalizing-our-data'), - ('Exercise 4: Adding Ridge Regression', - 2, - None, - 'exercise-4-adding-ridge-regression'), - ('Exercise 5: Analytical exercises', - 2, - None, - 'exercise-5-analytical-exercises')]} + 'deriving-the-lasso-regression-equations')]} end of tocinfo --> @@ -299,62 +299,63 @@ MathJax.Hub.Config({
  • Other useful relations
  • Meet the Hessian Matrix
  • Interpretations and optimizing our parameters
  • -
  • Examples relevant for the exercises
  • +
  • Example relevant for the exercises
  • Own code for Ordinary Least Squares
  • Adding error analysis and training set up
  • Splitting our Data in Training and Test data
  • -
  • Examples
  • +
  • The complete code with a simple data set
  • Making your own test-train splitting
  • -
  • The Boston housing data example
  • -
  • Housing data, the code
  • -
  • Reducing the number of degrees of freedom, overarching view
  • -
  • Preprocessing our data
  • -
  • Functionality in Scikit-Learn
  • -
  • More preprocessing
  • -
  • Frequently used scaling functions
  • -
  • Example of own Standard scaling
  • -
  • Min-Max Scaling
  • -
  • Testing the Means Squared Error as function of Complexity
  • -
  • More preprocessing examples, Franke function and regression
  • -
  • Material for lecture Thursday, August 31
  • -
  • Mathematical Interpretation of Ordinary Least Squares
  • -
  • Residual Error
  • -
  • Simple case
  • -
  • The singular value decomposition
  • -
  • Linear Regression Problems
  • -
  • Fixing the singularity
  • -
  • Basic math of the SVD
  • -
  • The SVD, a Fantastic Algorithm
  • -
  • Economy-size SVD
  • -
  • Codes for the SVD
  • -
  • Note about SVD Calculations
  • -
  • Mathematics of the SVD and implications
  • -
  • Example Matrix
  • -
  • Setting up the Matrix to be inverted
  • -
  • Further properties (important for our analyses later)
  • -
  • Meet the Covariance Matrix
  • -
  • Introducing the Covariance and Correlation functions
  • -
  • Covariance and Correlation Matrix
  • -
  • Correlation Function and Design/Feature Matrix
  • -
  • Covariance Matrix Examples
  • -
  • Correlation Matrix
  • -
  • Correlation Matrix with Pandas
  • -
  • Correlation Matrix with Pandas and the Franke function
  • -
  • Rewriting the Covariance and/or Correlation Matrix
  • -
  • Linking with the SVD
  • -
  • What does it mean?
  • -
  • And finally \( \boldsymbol{X}\boldsymbol{X}^T \)
  • -
  • Ridge and LASSO Regression
  • -
  • Deriving the Ridge Regression Equations
  • -
  • Interpreting the Ridge results
  • -
  • More interpretations
  • -
  • Deriving the Lasso Regression Equations
  • -
  • Exercises for week 35
  • -
  • Exercise 1: Setting up various Python environments
  • -
  • Exercise 2: making your own data and exploring scikit-learn
  • -
  • Exercise 3: Normalizing our data
  • -
  • Exercise 4: Adding Ridge Regression
  • -
  • Exercise 5: Analytical exercises
  • +
  • Reducing the number of degrees of freedom, overarching view
  • +
  • Preprocessing our data
  • +
  • Functionality in Scikit-Learn
  • +
  • More preprocessing
  • +
  • Frequently used scaling functions
  • +
  • Example of own Standard scaling
  • +
  • Min-Max Scaling
  • +
  • Testing the Means Squared Error as function of Complexity
  • +
  • More preprocessing examples, two-dimensional example, the Franke function
  • +
  • To think about, first part
  • +
  • More thinking
  • +
  • Still thinking
  • +
  • What does centering (subtracting the mean values) mean mathematically?
  • +
  • Further Manipulations
  • +
  • Wrapping it up
  • +
  • Linear Regression code, Intercept handling first
  • +
  • The Boston housing data example
  • +
  • Housing data, the code
  • +
  • Material for lecture Thursday, August 31
  • +
  • Mathematical Interpretation of Ordinary Least Squares
  • +
  • Residual Error
  • +
  • Simple case
  • +
  • The singular value decomposition
  • +
  • Linear Regression Problems
  • +
  • Fixing the singularity
  • +
  • Basic math of the SVD
  • +
  • The SVD, a Fantastic Algorithm
  • +
  • Economy-size SVD
  • +
  • Codes for the SVD
  • +
  • Note about SVD Calculations
  • +
  • Mathematics of the SVD and implications
  • +
  • Example Matrix
  • +
  • Setting up the Matrix to be inverted
  • +
  • Further properties (important for our analyses later)
  • +
  • Meet the Covariance Matrix
  • +
  • Introducing the Covariance and Correlation functions
  • +
  • Covariance and Correlation Matrix
  • +
  • Correlation Function and Design/Feature Matrix
  • +
  • Covariance Matrix Examples
  • +
  • Correlation Matrix
  • +
  • Correlation Matrix with Pandas
  • +
  • Correlation Matrix with Pandas and the Franke function
  • +
  • Rewriting the Covariance and/or Correlation Matrix
  • +
  • Linking with the SVD
  • +
  • What does it mean?
  • +
  • And finally \( \boldsymbol{X}\boldsymbol{X}^T \)
  • +
  • Ridge and LASSO Regression
  • +
  • Deriving the Ridge Regression Equations
  • +
  • Interpreting the Ridge results
  • +
  • More interpretations
  • +
  • Deriving the Lasso Regression Equations
  • @@ -366,41 +367,47 @@ MathJax.Hub.Config({

     

     

     

    -

    Rewriting the Covariance and/or Correlation Matrix

    +

    Introducing the Covariance and Correlation functions

    -

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

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

    -

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

    +

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

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

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

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

    +

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

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

    +

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

    @@ -426,6 +433,8 @@ $$

  • 66
  • 67
  • 68
  • +
  • ...
  • +
  • 74
  • »
  • diff --git a/doc/pub/week35/html/._week35-bs059.html b/doc/pub/week35/html/._week35-bs059.html index cdd48dfd3..db72c6af8 100644 --- a/doc/pub/week35/html/._week35-bs059.html +++ b/doc/pub/week35/html/._week35-bs059.html @@ -75,10 +75,10 @@ doconce format html week35.do.txt --html_style=bootstrap --pygments_html_style=d 2, None, 'interpretations-and-optimizing-our-parameters'), - ('Examples relevant for the exercises', + ('Example relevant for the exercises', 2, None, - 'examples-relevant-for-the-exercises'), + 'example-relevant-for-the-exercises'), ('Own code for Ordinary Least Squares', 2, None, @@ -91,16 +91,14 @@ doconce format html week35.do.txt --html_style=bootstrap --pygments_html_style=d 2, None, 'splitting-our-data-in-training-and-test-data'), - ('Examples', 2, None, 'examples'), + ('The complete code with a simple data set', + 2, + None, + 'the-complete-code-with-a-simple-data-set'), ('Making your own test-train splitting', 2, None, 'making-your-own-test-train-splitting'), - ('The Boston housing data example', - 2, - None, - 'the-boston-housing-data-example'), - ('Housing data, the code', 2, None, 'housing-data-the-code'), ('Reducing the number of degrees of freedom, overarching view', 2, None, @@ -124,10 +122,33 @@ doconce format html week35.do.txt --html_style=bootstrap --pygments_html_style=d 2, None, 'testing-the-means-squared-error-as-function-of-complexity'), - ('More preprocessing examples, Franke function and regression', + ('More preprocessing examples, two-dimensional example, the ' + 'Franke function', 2, None, - 'more-preprocessing-examples-franke-function-and-regression'), + 'more-preprocessing-examples-two-dimensional-example-the-franke-function'), + ('To think about, first part', + 2, + None, + 'to-think-about-first-part'), + ('More thinking', 2, None, 'more-thinking'), + ('Still thinking', 2, None, 'still-thinking'), + ('What does centering (subtracting the mean values) mean ' + 'mathematically?', + 2, + None, + 'what-does-centering-subtracting-the-mean-values-mean-mathematically'), + ('Further Manipulations', 2, None, 'further-manipulations'), + ('Wrapping it up', 2, None, 'wrapping-it-up'), + ('Linear Regression code, Intercept handling first', + 2, + None, + 'linear-regression-code-intercept-handling-first'), + ('The Boston housing data example', + 2, + None, + 'the-boston-housing-data-example'), + ('Housing data, the code', 2, None, 'housing-data-the-code'), ('Material for lecture Thursday, August 31', 2, None, @@ -226,28 +247,7 @@ doconce format html week35.do.txt --html_style=bootstrap --pygments_html_style=d ('Deriving the Lasso Regression Equations', 2, None, - 'deriving-the-lasso-regression-equations'), - ('Exercises for week 35', 2, None, 'exercises-for-week-35'), - ('Exercise 1: Setting up various Python environments', - 2, - None, - 'exercise-1-setting-up-various-python-environments'), - ('Exercise 2: making your own data and exploring scikit-learn', - 2, - None, - 'exercise-2-making-your-own-data-and-exploring-scikit-learn'), - ('Exercise 3: Normalizing our data', - 2, - None, - 'exercise-3-normalizing-our-data'), - ('Exercise 4: Adding Ridge Regression', - 2, - None, - 'exercise-4-adding-ridge-regression'), - ('Exercise 5: Analytical exercises', - 2, - None, - 'exercise-5-analytical-exercises')]} + 'deriving-the-lasso-regression-equations')]} end of tocinfo --> @@ -299,62 +299,63 @@ MathJax.Hub.Config({
  • Other useful relations
  • Meet the Hessian Matrix
  • Interpretations and optimizing our parameters
  • -
  • Examples relevant for the exercises
  • +
  • Example relevant for the exercises
  • Own code for Ordinary Least Squares
  • Adding error analysis and training set up
  • Splitting our Data in Training and Test data
  • -
  • Examples
  • +
  • The complete code with a simple data set
  • Making your own test-train splitting
  • -
  • The Boston housing data example
  • -
  • Housing data, the code
  • -
  • Reducing the number of degrees of freedom, overarching view
  • -
  • Preprocessing our data
  • -
  • Functionality in Scikit-Learn
  • -
  • More preprocessing
  • -
  • Frequently used scaling functions
  • -
  • Example of own Standard scaling
  • -
  • Min-Max Scaling
  • -
  • Testing the Means Squared Error as function of Complexity
  • -
  • More preprocessing examples, Franke function and regression
  • -
  • Material for lecture Thursday, August 31
  • -
  • Mathematical Interpretation of Ordinary Least Squares
  • -
  • Residual Error
  • -
  • Simple case
  • -
  • The singular value decomposition
  • -
  • Linear Regression Problems
  • -
  • Fixing the singularity
  • -
  • Basic math of the SVD
  • -
  • The SVD, a Fantastic Algorithm
  • -
  • Economy-size SVD
  • -
  • Codes for the SVD
  • -
  • Note about SVD Calculations
  • -
  • Mathematics of the SVD and implications
  • -
  • Example Matrix
  • -
  • Setting up the Matrix to be inverted
  • -
  • Further properties (important for our analyses later)
  • -
  • Meet the Covariance Matrix
  • -
  • Introducing the Covariance and Correlation functions
  • -
  • Covariance and Correlation Matrix
  • -
  • Correlation Function and Design/Feature Matrix
  • -
  • Covariance Matrix Examples
  • -
  • Correlation Matrix
  • -
  • Correlation Matrix with Pandas
  • -
  • Correlation Matrix with Pandas and the Franke function
  • -
  • Rewriting the Covariance and/or Correlation Matrix
  • -
  • Linking with the SVD
  • -
  • What does it mean?
  • -
  • And finally \( \boldsymbol{X}\boldsymbol{X}^T \)
  • -
  • Ridge and LASSO Regression
  • -
  • Deriving the Ridge Regression Equations
  • -
  • Interpreting the Ridge results
  • -
  • More interpretations
  • -
  • Deriving the Lasso Regression Equations
  • -
  • Exercises for week 35
  • -
  • Exercise 1: Setting up various Python environments
  • -
  • Exercise 2: making your own data and exploring scikit-learn
  • -
  • Exercise 3: Normalizing our data
  • -
  • Exercise 4: Adding Ridge Regression
  • -
  • Exercise 5: Analytical exercises
  • +
  • Reducing the number of degrees of freedom, overarching view
  • +
  • Preprocessing our data
  • +
  • Functionality in Scikit-Learn
  • +
  • More preprocessing
  • +
  • Frequently used scaling functions
  • +
  • Example of own Standard scaling
  • +
  • Min-Max Scaling
  • +
  • Testing the Means Squared Error as function of Complexity
  • +
  • More preprocessing examples, two-dimensional example, the Franke function
  • +
  • To think about, first part
  • +
  • More thinking
  • +
  • Still thinking
  • +
  • What does centering (subtracting the mean values) mean mathematically?
  • +
  • Further Manipulations
  • +
  • Wrapping it up
  • +
  • Linear Regression code, Intercept handling first
  • +
  • The Boston housing data example
  • +
  • Housing data, the code
  • +
  • Material for lecture Thursday, August 31
  • +
  • Mathematical Interpretation of Ordinary Least Squares
  • +
  • Residual Error
  • +
  • Simple case
  • +
  • The singular value decomposition
  • +
  • Linear Regression Problems
  • +
  • Fixing the singularity
  • +
  • Basic math of the SVD
  • +
  • The SVD, a Fantastic Algorithm
  • +
  • Economy-size SVD
  • +
  • Codes for the SVD
  • +
  • Note about SVD Calculations
  • +
  • Mathematics of the SVD and implications
  • +
  • Example Matrix
  • +
  • Setting up the Matrix to be inverted
  • +
  • Further properties (important for our analyses later)
  • +
  • Meet the Covariance Matrix
  • +
  • Introducing the Covariance and Correlation functions
  • +
  • Covariance and Correlation Matrix
  • +
  • Correlation Function and Design/Feature Matrix
  • +
  • Covariance Matrix Examples
  • +
  • Correlation Matrix
  • +
  • Correlation Matrix with Pandas
  • +
  • Correlation Matrix with Pandas and the Franke function
  • +
  • Rewriting the Covariance and/or Correlation Matrix
  • +
  • Linking with the SVD
  • +
  • What does it mean?
  • +
  • And finally \( \boldsymbol{X}\boldsymbol{X}^T \)
  • +
  • Ridge and LASSO Regression
  • +
  • Deriving the Ridge Regression Equations
  • +
  • Interpreting the Ridge results
  • +
  • More interpretations
  • +
  • Deriving the Lasso Regression Equations
  • @@ -366,39 +367,32 @@ MathJax.Hub.Config({

     

     

     

    -

    Linking with the SVD

    +

    Covariance and Correlation Matrix

    -

    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

    +

    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 +

    $$ -\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}, +\mathrm{corr}[\boldsymbol{x},\boldsymbol{y}]=\frac{\mathrm{cov}[\boldsymbol{x},\boldsymbol{y}]}{\sqrt{\mathrm{var}[\boldsymbol{x}] \mathrm{var}[\boldsymbol{y}]}}. $$ -

    meaning we can write

    +

    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{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{K}[\boldsymbol{x},\boldsymbol{y}] = \begin{bmatrix} 1 & \mathrm{corr}[\boldsymbol{x},\boldsymbol{y}] \\ + \mathrm{corr}[\boldsymbol{y},\boldsymbol{x}] & 1 \\ + \end{bmatrix}, $$ +

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

    @@ -423,6 +417,9 @@ $$

  • 66
  • 67
  • 68
  • +
  • 69
  • +
  • ...
  • +
  • 74
  • »
  • diff --git a/doc/pub/week35/html/._week35-bs060.html b/doc/pub/week35/html/._week35-bs060.html index e7e269093..418072f79 100644 --- a/doc/pub/week35/html/._week35-bs060.html +++ b/doc/pub/week35/html/._week35-bs060.html @@ -75,10 +75,10 @@ doconce format html week35.do.txt --html_style=bootstrap --pygments_html_style=d 2, None, 'interpretations-and-optimizing-our-parameters'), - ('Examples relevant for the exercises', + ('Example relevant for the exercises', 2, None, - 'examples-relevant-for-the-exercises'), + 'example-relevant-for-the-exercises'), ('Own code for Ordinary Least Squares', 2, None, @@ -91,16 +91,14 @@ doconce format html week35.do.txt --html_style=bootstrap --pygments_html_style=d 2, None, 'splitting-our-data-in-training-and-test-data'), - ('Examples', 2, None, 'examples'), + ('The complete code with a simple data set', + 2, + None, + 'the-complete-code-with-a-simple-data-set'), ('Making your own test-train splitting', 2, None, 'making-your-own-test-train-splitting'), - ('The Boston housing data example', - 2, - None, - 'the-boston-housing-data-example'), - ('Housing data, the code', 2, None, 'housing-data-the-code'), ('Reducing the number of degrees of freedom, overarching view', 2, None, @@ -124,10 +122,33 @@ doconce format html week35.do.txt --html_style=bootstrap --pygments_html_style=d 2, None, 'testing-the-means-squared-error-as-function-of-complexity'), - ('More preprocessing examples, Franke function and regression', + ('More preprocessing examples, two-dimensional example, the ' + 'Franke function', 2, None, - 'more-preprocessing-examples-franke-function-and-regression'), + 'more-preprocessing-examples-two-dimensional-example-the-franke-function'), + ('To think about, first part', + 2, + None, + 'to-think-about-first-part'), + ('More thinking', 2, None, 'more-thinking'), + ('Still thinking', 2, None, 'still-thinking'), + ('What does centering (subtracting the mean values) mean ' + 'mathematically?', + 2, + None, + 'what-does-centering-subtracting-the-mean-values-mean-mathematically'), + ('Further Manipulations', 2, None, 'further-manipulations'), + ('Wrapping it up', 2, None, 'wrapping-it-up'), + ('Linear Regression code, Intercept handling first', + 2, + None, + 'linear-regression-code-intercept-handling-first'), + ('The Boston housing data example', + 2, + None, + 'the-boston-housing-data-example'), + ('Housing data, the code', 2, None, 'housing-data-the-code'), ('Material for lecture Thursday, August 31', 2, None, @@ -226,28 +247,7 @@ doconce format html week35.do.txt --html_style=bootstrap --pygments_html_style=d ('Deriving the Lasso Regression Equations', 2, None, - 'deriving-the-lasso-regression-equations'), - ('Exercises for week 35', 2, None, 'exercises-for-week-35'), - ('Exercise 1: Setting up various Python environments', - 2, - None, - 'exercise-1-setting-up-various-python-environments'), - ('Exercise 2: making your own data and exploring scikit-learn', - 2, - None, - 'exercise-2-making-your-own-data-and-exploring-scikit-learn'), - ('Exercise 3: Normalizing our data', - 2, - None, - 'exercise-3-normalizing-our-data'), - ('Exercise 4: Adding Ridge Regression', - 2, - None, - 'exercise-4-adding-ridge-regression'), - ('Exercise 5: Analytical exercises', - 2, - None, - 'exercise-5-analytical-exercises')]} + 'deriving-the-lasso-regression-equations')]} end of tocinfo --> @@ -299,62 +299,63 @@ MathJax.Hub.Config({
  • Other useful relations
  • Meet the Hessian Matrix
  • Interpretations and optimizing our parameters
  • -
  • Examples relevant for the exercises
  • +
  • Example relevant for the exercises
  • Own code for Ordinary Least Squares
  • Adding error analysis and training set up
  • Splitting our Data in Training and Test data
  • -
  • Examples
  • +
  • The complete code with a simple data set
  • Making your own test-train splitting
  • -
  • The Boston housing data example
  • -
  • Housing data, the code
  • -
  • Reducing the number of degrees of freedom, overarching view
  • -
  • Preprocessing our data
  • -
  • Functionality in Scikit-Learn
  • -
  • More preprocessing
  • -
  • Frequently used scaling functions
  • -
  • Example of own Standard scaling
  • -
  • Min-Max Scaling
  • -
  • Testing the Means Squared Error as function of Complexity
  • -
  • More preprocessing examples, Franke function and regression
  • -
  • Material for lecture Thursday, August 31
  • -
  • Mathematical Interpretation of Ordinary Least Squares
  • -
  • Residual Error
  • -
  • Simple case
  • -
  • The singular value decomposition
  • -
  • Linear Regression Problems
  • -
  • Fixing the singularity
  • -
  • Basic math of the SVD
  • -
  • The SVD, a Fantastic Algorithm
  • -
  • Economy-size SVD
  • -
  • Codes for the SVD
  • -
  • Note about SVD Calculations
  • -
  • Mathematics of the SVD and implications
  • -
  • Example Matrix
  • -
  • Setting up the Matrix to be inverted
  • -
  • Further properties (important for our analyses later)
  • -
  • Meet the Covariance Matrix
  • -
  • Introducing the Covariance and Correlation functions
  • -
  • Covariance and Correlation Matrix
  • -
  • Correlation Function and Design/Feature Matrix
  • -
  • Covariance Matrix Examples
  • -
  • Correlation Matrix
  • -
  • Correlation Matrix with Pandas
  • -
  • Correlation Matrix with Pandas and the Franke function
  • -
  • Rewriting the Covariance and/or Correlation Matrix
  • -
  • Linking with the SVD
  • -
  • What does it mean?
  • -
  • And finally \( \boldsymbol{X}\boldsymbol{X}^T \)
  • -
  • Ridge and LASSO Regression
  • -
  • Deriving the Ridge Regression Equations
  • -
  • Interpreting the Ridge results
  • -
  • More interpretations
  • -
  • Deriving the Lasso Regression Equations
  • -
  • Exercises for week 35
  • -
  • Exercise 1: Setting up various Python environments
  • -
  • Exercise 2: making your own data and exploring scikit-learn
  • -
  • Exercise 3: Normalizing our data
  • -
  • Exercise 4: Adding Ridge Regression
  • -
  • Exercise 5: Analytical exercises
  • +
  • Reducing the number of degrees of freedom, overarching view
  • +
  • Preprocessing our data
  • +
  • Functionality in Scikit-Learn
  • +
  • More preprocessing
  • +
  • Frequently used scaling functions
  • +
  • Example of own Standard scaling
  • +
  • Min-Max Scaling
  • +
  • Testing the Means Squared Error as function of Complexity
  • +
  • More preprocessing examples, two-dimensional example, the Franke function
  • +
  • To think about, first part
  • +
  • More thinking
  • +
  • Still thinking
  • +
  • What does centering (subtracting the mean values) mean mathematically?
  • +
  • Further Manipulations
  • +
  • Wrapping it up
  • +
  • Linear Regression code, Intercept handling first
  • +
  • The Boston housing data example
  • +
  • Housing data, the code
  • +
  • Material for lecture Thursday, August 31
  • +
  • Mathematical Interpretation of Ordinary Least Squares
  • +
  • Residual Error
  • +
  • Simple case
  • +
  • The singular value decomposition
  • +
  • Linear Regression Problems
  • +
  • Fixing the singularity
  • +
  • Basic math of the SVD
  • +
  • The SVD, a Fantastic Algorithm
  • +
  • Economy-size SVD
  • +
  • Codes for the SVD
  • +
  • Note about SVD Calculations
  • +
  • Mathematics of the SVD and implications
  • +
  • Example Matrix
  • +
  • Setting up the Matrix to be inverted
  • +
  • Further properties (important for our analyses later)
  • +
  • Meet the Covariance Matrix
  • +
  • Introducing the Covariance and Correlation functions
  • +
  • Covariance and Correlation Matrix
  • +
  • Correlation Function and Design/Feature Matrix
  • +
  • Covariance Matrix Examples
  • +
  • Correlation Matrix
  • +
  • Correlation Matrix with Pandas
  • +
  • Correlation Matrix with Pandas and the Franke function
  • +
  • Rewriting the Covariance and/or Correlation Matrix
  • +
  • Linking with the SVD
  • +
  • What does it mean?
  • +
  • And finally \( \boldsymbol{X}\boldsymbol{X}^T \)
  • +
  • Ridge and LASSO Regression
  • +
  • Deriving the Ridge Regression Equations
  • +
  • Interpreting the Ridge results
  • +
  • More interpretations
  • +
  • Deriving the Lasso Regression Equations
  • @@ -366,45 +367,65 @@ MathJax.Hub.Config({

     

     

     

    -

    What does it mean?

    +

    Correlation Function and Design/Feature Matrix

    -

    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 +

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

    $$ -\left(\boldsymbol{X}^T\boldsymbol{X}\right)\boldsymbol{v}_i=\boldsymbol{v}_i\sigma_i^2. +\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}, $$ -

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

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

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

    +

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

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

    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{C}[\boldsymbol{X}]=\frac{1}{n}\boldsymbol{X}^T\boldsymbol{X}, +\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}, $$ -

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

    @@ -428,6 +449,10 @@ absolute value of the eigenvalues of \( \boldsymbol{X} \).

  • 66
  • 67
  • 68
  • +
  • 69
  • +
  • 70
  • +
  • ...
  • +
  • 74
  • »
  • diff --git a/doc/pub/week35/html/._week35-bs061.html b/doc/pub/week35/html/._week35-bs061.html index 75b2c105d..c3878645a 100644 --- a/doc/pub/week35/html/._week35-bs061.html +++ b/doc/pub/week35/html/._week35-bs061.html @@ -75,10 +75,10 @@ doconce format html week35.do.txt --html_style=bootstrap --pygments_html_style=d 2, None, 'interpretations-and-optimizing-our-parameters'), - ('Examples relevant for the exercises', + ('Example relevant for the exercises', 2, None, - 'examples-relevant-for-the-exercises'), + 'example-relevant-for-the-exercises'), ('Own code for Ordinary Least Squares', 2, None, @@ -91,16 +91,14 @@ doconce format html week35.do.txt --html_style=bootstrap --pygments_html_style=d 2, None, 'splitting-our-data-in-training-and-test-data'), - ('Examples', 2, None, 'examples'), + ('The complete code with a simple data set', + 2, + None, + 'the-complete-code-with-a-simple-data-set'), ('Making your own test-train splitting', 2, None, 'making-your-own-test-train-splitting'), - ('The Boston housing data example', - 2, - None, - 'the-boston-housing-data-example'), - ('Housing data, the code', 2, None, 'housing-data-the-code'), ('Reducing the number of degrees of freedom, overarching view', 2, None, @@ -124,10 +122,33 @@ doconce format html week35.do.txt --html_style=bootstrap --pygments_html_style=d 2, None, 'testing-the-means-squared-error-as-function-of-complexity'), - ('More preprocessing examples, Franke function and regression', + ('More preprocessing examples, two-dimensional example, the ' + 'Franke function', 2, None, - 'more-preprocessing-examples-franke-function-and-regression'), + 'more-preprocessing-examples-two-dimensional-example-the-franke-function'), + ('To think about, first part', + 2, + None, + 'to-think-about-first-part'), + ('More thinking', 2, None, 'more-thinking'), + ('Still thinking', 2, None, 'still-thinking'), + ('What does centering (subtracting the mean values) mean ' + 'mathematically?', + 2, + None, + 'what-does-centering-subtracting-the-mean-values-mean-mathematically'), + ('Further Manipulations', 2, None, 'further-manipulations'), + ('Wrapping it up', 2, None, 'wrapping-it-up'), + ('Linear Regression code, Intercept handling first', + 2, + None, + 'linear-regression-code-intercept-handling-first'), + ('The Boston housing data example', + 2, + None, + 'the-boston-housing-data-example'), + ('Housing data, the code', 2, None, 'housing-data-the-code'), ('Material for lecture Thursday, August 31', 2, None, @@ -226,28 +247,7 @@ doconce format html week35.do.txt --html_style=bootstrap --pygments_html_style=d ('Deriving the Lasso Regression Equations', 2, None, - 'deriving-the-lasso-regression-equations'), - ('Exercises for week 35', 2, None, 'exercises-for-week-35'), - ('Exercise 1: Setting up various Python environments', - 2, - None, - 'exercise-1-setting-up-various-python-environments'), - ('Exercise 2: making your own data and exploring scikit-learn', - 2, - None, - 'exercise-2-making-your-own-data-and-exploring-scikit-learn'), - ('Exercise 3: Normalizing our data', - 2, - None, - 'exercise-3-normalizing-our-data'), - ('Exercise 4: Adding Ridge Regression', - 2, - None, - 'exercise-4-adding-ridge-regression'), - ('Exercise 5: Analytical exercises', - 2, - None, - 'exercise-5-analytical-exercises')]} + 'deriving-the-lasso-regression-equations')]} end of tocinfo --> @@ -299,62 +299,63 @@ MathJax.Hub.Config({
  • Other useful relations
  • Meet the Hessian Matrix
  • Interpretations and optimizing our parameters
  • -
  • Examples relevant for the exercises
  • +
  • Example relevant for the exercises
  • Own code for Ordinary Least Squares
  • Adding error analysis and training set up
  • Splitting our Data in Training and Test data
  • -
  • Examples
  • +
  • The complete code with a simple data set
  • Making your own test-train splitting
  • -
  • The Boston housing data example
  • -
  • Housing data, the code
  • -
  • Reducing the number of degrees of freedom, overarching view
  • -
  • Preprocessing our data
  • -
  • Functionality in Scikit-Learn
  • -
  • More preprocessing
  • -
  • Frequently used scaling functions
  • -
  • Example of own Standard scaling
  • -
  • Min-Max Scaling
  • -
  • Testing the Means Squared Error as function of Complexity
  • -
  • More preprocessing examples, Franke function and regression
  • -
  • Material for lecture Thursday, August 31
  • -
  • Mathematical Interpretation of Ordinary Least Squares
  • -
  • Residual Error
  • -
  • Simple case
  • -
  • The singular value decomposition
  • -
  • Linear Regression Problems
  • -
  • Fixing the singularity
  • -
  • Basic math of the SVD
  • -
  • The SVD, a Fantastic Algorithm
  • -
  • Economy-size SVD
  • -
  • Codes for the SVD
  • -
  • Note about SVD Calculations
  • -
  • Mathematics of the SVD and implications
  • -
  • Example Matrix
  • -
  • Setting up the Matrix to be inverted
  • -
  • Further properties (important for our analyses later)
  • -
  • Meet the Covariance Matrix
  • -
  • Introducing the Covariance and Correlation functions
  • -
  • Covariance and Correlation Matrix
  • -
  • Correlation Function and Design/Feature Matrix
  • -
  • Covariance Matrix Examples
  • -
  • Correlation Matrix
  • -
  • Correlation Matrix with Pandas
  • -
  • Correlation Matrix with Pandas and the Franke function
  • -
  • Rewriting the Covariance and/or Correlation Matrix
  • -
  • Linking with the SVD
  • -
  • What does it mean?
  • -
  • And finally \( \boldsymbol{X}\boldsymbol{X}^T \)
  • -
  • Ridge and LASSO Regression
  • -
  • Deriving the Ridge Regression Equations
  • -
  • Interpreting the Ridge results
  • -
  • More interpretations
  • -
  • Deriving the Lasso Regression Equations
  • -
  • Exercises for week 35
  • -
  • Exercise 1: Setting up various Python environments
  • -
  • Exercise 2: making your own data and exploring scikit-learn
  • -
  • Exercise 3: Normalizing our data
  • -
  • Exercise 4: Adding Ridge Regression
  • -
  • Exercise 5: Analytical exercises
  • +
  • Reducing the number of degrees of freedom, overarching view
  • +
  • Preprocessing our data
  • +
  • Functionality in Scikit-Learn
  • +
  • More preprocessing
  • +
  • Frequently used scaling functions
  • +
  • Example of own Standard scaling
  • +
  • Min-Max Scaling
  • +
  • Testing the Means Squared Error as function of Complexity
  • +
  • More preprocessing examples, two-dimensional example, the Franke function
  • +
  • To think about, first part
  • +
  • More thinking
  • +
  • Still thinking
  • +
  • What does centering (subtracting the mean values) mean mathematically?
  • +
  • Further Manipulations
  • +
  • Wrapping it up
  • +
  • Linear Regression code, Intercept handling first
  • +
  • The Boston housing data example
  • +
  • Housing data, the code
  • +
  • Material for lecture Thursday, August 31
  • +
  • Mathematical Interpretation of Ordinary Least Squares
  • +
  • Residual Error
  • +
  • Simple case
  • +
  • The singular value decomposition
  • +
  • Linear Regression Problems
  • +
  • Fixing the singularity
  • +
  • Basic math of the SVD
  • +
  • The SVD, a Fantastic Algorithm
  • +
  • Economy-size SVD
  • +
  • Codes for the SVD
  • +
  • Note about SVD Calculations
  • +
  • Mathematics of the SVD and implications
  • +
  • Example Matrix
  • +
  • Setting up the Matrix to be inverted
  • +
  • Further properties (important for our analyses later)
  • +
  • Meet the Covariance Matrix
  • +
  • Introducing the Covariance and Correlation functions
  • +
  • Covariance and Correlation Matrix
  • +
  • Correlation Function and Design/Feature Matrix
  • +
  • Covariance Matrix Examples
  • +
  • Correlation Matrix
  • +
  • Correlation Matrix with Pandas
  • +
  • Correlation Matrix with Pandas and the Franke function
  • +
  • Rewriting the Covariance and/or Correlation Matrix
  • +
  • Linking with the SVD
  • +
  • What does it mean?
  • +
  • And finally \( \boldsymbol{X}\boldsymbol{X}^T \)
  • +
  • Ridge and LASSO Regression
  • +
  • Deriving the Ridge Regression Equations
  • +
  • Interpreting the Ridge results
  • +
  • More interpretations
  • +
  • Deriving the Lasso Regression Equations
  • @@ -366,40 +367,62 @@ MathJax.Hub.Config({

     

     

     

    -

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

    +

    Covariance Matrix Examples

    -

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

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

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

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

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

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

    -

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

    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.

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

      @@ -421,6 +444,11 @@ values and the column vectors of \( \boldsymbol{V} \).
    • 66
    • 67
    • 68
    • +
    • 69
    • +
    • 70
    • +
    • 71
    • +
    • ...
    • +
    • 74
    • »
    diff --git a/doc/pub/week35/html/._week35-bs062.html b/doc/pub/week35/html/._week35-bs062.html index 29b43b2b7..bb7512922 100644 --- a/doc/pub/week35/html/._week35-bs062.html +++ b/doc/pub/week35/html/._week35-bs062.html @@ -75,10 +75,10 @@ doconce format html week35.do.txt --html_style=bootstrap --pygments_html_style=d 2, None, 'interpretations-and-optimizing-our-parameters'), - ('Examples relevant for the exercises', + ('Example relevant for the exercises', 2, None, - 'examples-relevant-for-the-exercises'), + 'example-relevant-for-the-exercises'), ('Own code for Ordinary Least Squares', 2, None, @@ -91,16 +91,14 @@ doconce format html week35.do.txt --html_style=bootstrap --pygments_html_style=d 2, None, 'splitting-our-data-in-training-and-test-data'), - ('Examples', 2, None, 'examples'), + ('The complete code with a simple data set', + 2, + None, + 'the-complete-code-with-a-simple-data-set'), ('Making your own test-train splitting', 2, None, 'making-your-own-test-train-splitting'), - ('The Boston housing data example', - 2, - None, - 'the-boston-housing-data-example'), - ('Housing data, the code', 2, None, 'housing-data-the-code'), ('Reducing the number of degrees of freedom, overarching view', 2, None, @@ -124,10 +122,33 @@ doconce format html week35.do.txt --html_style=bootstrap --pygments_html_style=d 2, None, 'testing-the-means-squared-error-as-function-of-complexity'), - ('More preprocessing examples, Franke function and regression', + ('More preprocessing examples, two-dimensional example, the ' + 'Franke function', 2, None, - 'more-preprocessing-examples-franke-function-and-regression'), + 'more-preprocessing-examples-two-dimensional-example-the-franke-function'), + ('To think about, first part', + 2, + None, + 'to-think-about-first-part'), + ('More thinking', 2, None, 'more-thinking'), + ('Still thinking', 2, None, 'still-thinking'), + ('What does centering (subtracting the mean values) mean ' + 'mathematically?', + 2, + None, + 'what-does-centering-subtracting-the-mean-values-mean-mathematically'), + ('Further Manipulations', 2, None, 'further-manipulations'), + ('Wrapping it up', 2, None, 'wrapping-it-up'), + ('Linear Regression code, Intercept handling first', + 2, + None, + 'linear-regression-code-intercept-handling-first'), + ('The Boston housing data example', + 2, + None, + 'the-boston-housing-data-example'), + ('Housing data, the code', 2, None, 'housing-data-the-code'), ('Material for lecture Thursday, August 31', 2, None, @@ -226,28 +247,7 @@ doconce format html week35.do.txt --html_style=bootstrap --pygments_html_style=d ('Deriving the Lasso Regression Equations', 2, None, - 'deriving-the-lasso-regression-equations'), - ('Exercises for week 35', 2, None, 'exercises-for-week-35'), - ('Exercise 1: Setting up various Python environments', - 2, - None, - 'exercise-1-setting-up-various-python-environments'), - ('Exercise 2: making your own data and exploring scikit-learn', - 2, - None, - 'exercise-2-making-your-own-data-and-exploring-scikit-learn'), - ('Exercise 3: Normalizing our data', - 2, - None, - 'exercise-3-normalizing-our-data'), - ('Exercise 4: Adding Ridge Regression', - 2, - None, - 'exercise-4-adding-ridge-regression'), - ('Exercise 5: Analytical exercises', - 2, - None, - 'exercise-5-analytical-exercises')]} + 'deriving-the-lasso-regression-equations')]} end of tocinfo --> @@ -299,62 +299,63 @@ MathJax.Hub.Config({
  • Other useful relations
  • Meet the Hessian Matrix
  • Interpretations and optimizing our parameters
  • -
  • Examples relevant for the exercises
  • +
  • Example relevant for the exercises
  • Own code for Ordinary Least Squares
  • Adding error analysis and training set up
  • Splitting our Data in Training and Test data
  • -
  • Examples
  • +
  • The complete code with a simple data set
  • Making your own test-train splitting
  • -
  • The Boston housing data example
  • -
  • Housing data, the code
  • -
  • Reducing the number of degrees of freedom, overarching view
  • -
  • Preprocessing our data
  • -
  • Functionality in Scikit-Learn
  • -
  • More preprocessing
  • -
  • Frequently used scaling functions
  • -
  • Example of own Standard scaling
  • -
  • Min-Max Scaling
  • -
  • Testing the Means Squared Error as function of Complexity
  • -
  • More preprocessing examples, Franke function and regression
  • -
  • Material for lecture Thursday, August 31
  • -
  • Mathematical Interpretation of Ordinary Least Squares
  • -
  • Residual Error
  • -
  • Simple case
  • -
  • The singular value decomposition
  • -
  • Linear Regression Problems
  • -
  • Fixing the singularity
  • -
  • Basic math of the SVD
  • -
  • The SVD, a Fantastic Algorithm
  • -
  • Economy-size SVD
  • -
  • Codes for the SVD
  • -
  • Note about SVD Calculations
  • -
  • Mathematics of the SVD and implications
  • -
  • Example Matrix
  • -
  • Setting up the Matrix to be inverted
  • -
  • Further properties (important for our analyses later)
  • -
  • Meet the Covariance Matrix
  • -
  • Introducing the Covariance and Correlation functions
  • -
  • Covariance and Correlation Matrix
  • -
  • Correlation Function and Design/Feature Matrix
  • -
  • Covariance Matrix Examples
  • -
  • Correlation Matrix
  • -
  • Correlation Matrix with Pandas
  • -
  • Correlation Matrix with Pandas and the Franke function
  • -
  • Rewriting the Covariance and/or Correlation Matrix
  • -
  • Linking with the SVD
  • -
  • What does it mean?
  • -
  • And finally \( \boldsymbol{X}\boldsymbol{X}^T \)
  • -
  • Ridge and LASSO Regression
  • -
  • Deriving the Ridge Regression Equations
  • -
  • Interpreting the Ridge results
  • -
  • More interpretations
  • -
  • Deriving the Lasso Regression Equations
  • -
  • Exercises for week 35
  • -
  • Exercise 1: Setting up various Python environments
  • -
  • Exercise 2: making your own data and exploring scikit-learn
  • -
  • Exercise 3: Normalizing our data
  • -
  • Exercise 4: Adding Ridge Regression
  • -
  • Exercise 5: Analytical exercises
  • +
  • Reducing the number of degrees of freedom, overarching view
  • +
  • Preprocessing our data
  • +
  • Functionality in Scikit-Learn
  • +
  • More preprocessing
  • +
  • Frequently used scaling functions
  • +
  • Example of own Standard scaling
  • +
  • Min-Max Scaling
  • +
  • Testing the Means Squared Error as function of Complexity
  • +
  • More preprocessing examples, two-dimensional example, the Franke function
  • +
  • To think about, first part
  • +
  • More thinking
  • +
  • Still thinking
  • +
  • What does centering (subtracting the mean values) mean mathematically?
  • +
  • Further Manipulations
  • +
  • Wrapping it up
  • +
  • Linear Regression code, Intercept handling first
  • +
  • The Boston housing data example
  • +
  • Housing data, the code
  • +
  • Material for lecture Thursday, August 31
  • +
  • Mathematical Interpretation of Ordinary Least Squares
  • +
  • Residual Error
  • +
  • Simple case
  • +
  • The singular value decomposition
  • +
  • Linear Regression Problems
  • +
  • Fixing the singularity
  • +
  • Basic math of the SVD
  • +
  • The SVD, a Fantastic Algorithm
  • +
  • Economy-size SVD
  • +
  • Codes for the SVD
  • +
  • Note about SVD Calculations
  • +
  • Mathematics of the SVD and implications
  • +
  • Example Matrix
  • +
  • Setting up the Matrix to be inverted
  • +
  • Further properties (important for our analyses later)
  • +
  • Meet the Covariance Matrix
  • +
  • Introducing the Covariance and Correlation functions
  • +
  • Covariance and Correlation Matrix
  • +
  • Correlation Function and Design/Feature Matrix
  • +
  • Covariance Matrix Examples
  • +
  • Correlation Matrix
  • +
  • Correlation Matrix with Pandas
  • +
  • Correlation Matrix with Pandas and the Franke function
  • +
  • Rewriting the Covariance and/or Correlation Matrix
  • +
  • Linking with the SVD
  • +
  • What does it mean?
  • +
  • And finally \( \boldsymbol{X}\boldsymbol{X}^T \)
  • +
  • Ridge and LASSO Regression
  • +
  • Deriving the Ridge Regression Equations
  • +
  • Interpreting the Ridge results
  • +
  • More interpretations
  • +
  • Deriving the Lasso Regression Equations
  • @@ -366,59 +367,64 @@ MathJax.Hub.Config({

     

     

     

    -

    Ridge and LASSO Regression

    +

    Correlation Matrix

    -

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

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

    or we can state it as

    -$$ -{\displaystyle \min_{\boldsymbol{\beta}\in -{\mathbb{R}}^{p}}}\frac{1}{n}\sum_{i=0}^{n-1}\left(y_i-\tilde{y}_i\right)^2=\frac{1}{n}\vert\vert \boldsymbol{y}-\boldsymbol{X}\boldsymbol{\beta}\vert\vert_2^2, -$$ - -

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

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

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

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

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

    +
    +
    +
    +
    +
    import numpy as np
    +n = 100
    +# define two vectors                                                                                           
    +x = np.random.random(size=n)
    +y = 4+3*x+np.random.normal(size=n)
    +#scaling the x and y vectors                                                                                   
    +x = x - np.mean(x)
    +y = y - np.mean(y)
    +variance_x = np.sum(x@x)/n
    +variance_y = np.sum(y@y)/n
    +print(variance_x)
    +print(variance_y)
    +cov_xy = np.sum(x@y)/n
    +cov_xx = np.sum(x@x)/n
    +cov_yy = np.sum(y@y)/n
    +C = np.zeros((2,2))
    +C[0,0]= cov_xx/variance_x
    +C[1,1]= cov_yy/variance_y
    +C[0,1]= cov_xy/np.sqrt(variance_y*variance_x)
    +C[1,0]= C[0,1]
    +print(C)
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    + +

    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.

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

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

    @@ -440,6 +446,12 @@ $$

  • 66
  • 67
  • 68
  • +
  • 69
  • +
  • 70
  • +
  • 71
  • +
  • 72
  • +
  • ...
  • +
  • 74
  • »
  • diff --git a/doc/pub/week35/html/._week35-bs063.html b/doc/pub/week35/html/._week35-bs063.html index 29c811a45..198b9bb3c 100644 --- a/doc/pub/week35/html/._week35-bs063.html +++ b/doc/pub/week35/html/._week35-bs063.html @@ -75,10 +75,10 @@ doconce format html week35.do.txt --html_style=bootstrap --pygments_html_style=d 2, None, 'interpretations-and-optimizing-our-parameters'), - ('Examples relevant for the exercises', + ('Example relevant for the exercises', 2, None, - 'examples-relevant-for-the-exercises'), + 'example-relevant-for-the-exercises'), ('Own code for Ordinary Least Squares', 2, None, @@ -91,16 +91,14 @@ doconce format html week35.do.txt --html_style=bootstrap --pygments_html_style=d 2, None, 'splitting-our-data-in-training-and-test-data'), - ('Examples', 2, None, 'examples'), + ('The complete code with a simple data set', + 2, + None, + 'the-complete-code-with-a-simple-data-set'), ('Making your own test-train splitting', 2, None, 'making-your-own-test-train-splitting'), - ('The Boston housing data example', - 2, - None, - 'the-boston-housing-data-example'), - ('Housing data, the code', 2, None, 'housing-data-the-code'), ('Reducing the number of degrees of freedom, overarching view', 2, None, @@ -124,10 +122,33 @@ doconce format html week35.do.txt --html_style=bootstrap --pygments_html_style=d 2, None, 'testing-the-means-squared-error-as-function-of-complexity'), - ('More preprocessing examples, Franke function and regression', + ('More preprocessing examples, two-dimensional example, the ' + 'Franke function', 2, None, - 'more-preprocessing-examples-franke-function-and-regression'), + 'more-preprocessing-examples-two-dimensional-example-the-franke-function'), + ('To think about, first part', + 2, + None, + 'to-think-about-first-part'), + ('More thinking', 2, None, 'more-thinking'), + ('Still thinking', 2, None, 'still-thinking'), + ('What does centering (subtracting the mean values) mean ' + 'mathematically?', + 2, + None, + 'what-does-centering-subtracting-the-mean-values-mean-mathematically'), + ('Further Manipulations', 2, None, 'further-manipulations'), + ('Wrapping it up', 2, None, 'wrapping-it-up'), + ('Linear Regression code, Intercept handling first', + 2, + None, + 'linear-regression-code-intercept-handling-first'), + ('The Boston housing data example', + 2, + None, + 'the-boston-housing-data-example'), + ('Housing data, the code', 2, None, 'housing-data-the-code'), ('Material for lecture Thursday, August 31', 2, None, @@ -226,28 +247,7 @@ doconce format html week35.do.txt --html_style=bootstrap --pygments_html_style=d ('Deriving the Lasso Regression Equations', 2, None, - 'deriving-the-lasso-regression-equations'), - ('Exercises for week 35', 2, None, 'exercises-for-week-35'), - ('Exercise 1: Setting up various Python environments', - 2, - None, - 'exercise-1-setting-up-various-python-environments'), - ('Exercise 2: making your own data and exploring scikit-learn', - 2, - None, - 'exercise-2-making-your-own-data-and-exploring-scikit-learn'), - ('Exercise 3: Normalizing our data', - 2, - None, - 'exercise-3-normalizing-our-data'), - ('Exercise 4: Adding Ridge Regression', - 2, - None, - 'exercise-4-adding-ridge-regression'), - ('Exercise 5: Analytical exercises', - 2, - None, - 'exercise-5-analytical-exercises')]} + 'deriving-the-lasso-regression-equations')]} end of tocinfo --> @@ -299,62 +299,63 @@ MathJax.Hub.Config({
  • Other useful relations
  • Meet the Hessian Matrix
  • Interpretations and optimizing our parameters
  • -
  • Examples relevant for the exercises
  • +
  • Example relevant for the exercises
  • Own code for Ordinary Least Squares
  • Adding error analysis and training set up
  • Splitting our Data in Training and Test data
  • -
  • Examples
  • +
  • The complete code with a simple data set
  • Making your own test-train splitting
  • -
  • The Boston housing data example
  • -
  • Housing data, the code
  • -
  • Reducing the number of degrees of freedom, overarching view
  • -
  • Preprocessing our data
  • -
  • Functionality in Scikit-Learn
  • -
  • More preprocessing
  • -
  • Frequently used scaling functions
  • -
  • Example of own Standard scaling
  • -
  • Min-Max Scaling
  • -
  • Testing the Means Squared Error as function of Complexity
  • -
  • More preprocessing examples, Franke function and regression
  • -
  • Material for lecture Thursday, August 31
  • -
  • Mathematical Interpretation of Ordinary Least Squares
  • -
  • Residual Error
  • -
  • Simple case
  • -
  • The singular value decomposition
  • -
  • Linear Regression Problems
  • -
  • Fixing the singularity
  • -
  • Basic math of the SVD
  • -
  • The SVD, a Fantastic Algorithm
  • -
  • Economy-size SVD
  • -
  • Codes for the SVD
  • -
  • Note about SVD Calculations
  • -
  • Mathematics of the SVD and implications
  • -
  • Example Matrix
  • -
  • Setting up the Matrix to be inverted
  • -
  • Further properties (important for our analyses later)
  • -
  • Meet the Covariance Matrix
  • -
  • Introducing the Covariance and Correlation functions
  • -
  • Covariance and Correlation Matrix
  • -
  • Correlation Function and Design/Feature Matrix
  • -
  • Covariance Matrix Examples
  • -
  • Correlation Matrix
  • -
  • Correlation Matrix with Pandas
  • -
  • Correlation Matrix with Pandas and the Franke function
  • -
  • Rewriting the Covariance and/or Correlation Matrix
  • -
  • Linking with the SVD
  • -
  • What does it mean?
  • -
  • And finally \( \boldsymbol{X}\boldsymbol{X}^T \)
  • -
  • Ridge and LASSO Regression
  • -
  • Deriving the Ridge Regression Equations
  • -
  • Interpreting the Ridge results
  • -
  • More interpretations
  • -
  • Deriving the Lasso Regression Equations
  • -
  • Exercises for week 35
  • -
  • Exercise 1: Setting up various Python environments
  • -
  • Exercise 2: making your own data and exploring scikit-learn
  • -
  • Exercise 3: Normalizing our data
  • -
  • Exercise 4: Adding Ridge Regression
  • -
  • Exercise 5: Analytical exercises
  • +
  • Reducing the number of degrees of freedom, overarching view
  • +
  • Preprocessing our data
  • +
  • Functionality in Scikit-Learn
  • +
  • More preprocessing
  • +
  • Frequently used scaling functions
  • +
  • Example of own Standard scaling
  • +
  • Min-Max Scaling
  • +
  • Testing the Means Squared Error as function of Complexity
  • +
  • More preprocessing examples, two-dimensional example, the Franke function
  • +
  • To think about, first part
  • +
  • More thinking
  • +
  • Still thinking
  • +
  • What does centering (subtracting the mean values) mean mathematically?
  • +
  • Further Manipulations
  • +
  • Wrapping it up
  • +
  • Linear Regression code, Intercept handling first
  • +
  • The Boston housing data example
  • +
  • Housing data, the code
  • +
  • Material for lecture Thursday, August 31
  • +
  • Mathematical Interpretation of Ordinary Least Squares
  • +
  • Residual Error
  • +
  • Simple case
  • +
  • The singular value decomposition
  • +
  • Linear Regression Problems
  • +
  • Fixing the singularity
  • +
  • Basic math of the SVD
  • +
  • The SVD, a Fantastic Algorithm
  • +
  • Economy-size SVD
  • +
  • Codes for the SVD
  • +
  • Note about SVD Calculations
  • +
  • Mathematics of the SVD and implications
  • +
  • Example Matrix
  • +
  • Setting up the Matrix to be inverted
  • +
  • Further properties (important for our analyses later)
  • +
  • Meet the Covariance Matrix
  • +
  • Introducing the Covariance and Correlation functions
  • +
  • Covariance and Correlation Matrix
  • +
  • Correlation Function and Design/Feature Matrix
  • +
  • Covariance Matrix Examples
  • +
  • Correlation Matrix
  • +
  • Correlation Matrix with Pandas
  • +
  • Correlation Matrix with Pandas and the Franke function
  • +
  • Rewriting the Covariance and/or Correlation Matrix
  • +
  • Linking with the SVD
  • +
  • What does it mean?
  • +
  • And finally \( \boldsymbol{X}\boldsymbol{X}^T \)
  • +
  • Ridge and LASSO Regression
  • +
  • Deriving the Ridge Regression Equations
  • +
  • Interpreting the Ridge results
  • +
  • More interpretations
  • +
  • Deriving the Lasso Regression Equations
  • @@ -366,67 +367,46 @@ MathJax.Hub.Config({

     

     

     

    -

    Deriving the Ridge Regression Equations

    +

    Correlation Matrix with Pandas

    -

    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

    +

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

    -$$ -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}, -$$ + +
    +
    +
    +
    +
    +
    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)
    +Xpd = pd.DataFrame(X)
    +print(Xpd)
    +correlation_matrix = Xpd.corr()
    +print(correlation_matrix)
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    -

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

    - -

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

    +

    We expand this model to the Franke function discussed above.

    @@ -447,6 +427,13 @@ $$

  • 66
  • 67
  • 68
  • +
  • 69
  • +
  • 70
  • +
  • 71
  • +
  • 72
  • +
  • 73
  • +
  • ...
  • +
  • 74
  • »
  • diff --git a/doc/pub/week35/html/._week35-bs064.html b/doc/pub/week35/html/._week35-bs064.html index c00ff73f7..26e116788 100644 --- a/doc/pub/week35/html/._week35-bs064.html +++ b/doc/pub/week35/html/._week35-bs064.html @@ -75,10 +75,10 @@ doconce format html week35.do.txt --html_style=bootstrap --pygments_html_style=d 2, None, 'interpretations-and-optimizing-our-parameters'), - ('Examples relevant for the exercises', + ('Example relevant for the exercises', 2, None, - 'examples-relevant-for-the-exercises'), + 'example-relevant-for-the-exercises'), ('Own code for Ordinary Least Squares', 2, None, @@ -91,16 +91,14 @@ doconce format html week35.do.txt --html_style=bootstrap --pygments_html_style=d 2, None, 'splitting-our-data-in-training-and-test-data'), - ('Examples', 2, None, 'examples'), + ('The complete code with a simple data set', + 2, + None, + 'the-complete-code-with-a-simple-data-set'), ('Making your own test-train splitting', 2, None, 'making-your-own-test-train-splitting'), - ('The Boston housing data example', - 2, - None, - 'the-boston-housing-data-example'), - ('Housing data, the code', 2, None, 'housing-data-the-code'), ('Reducing the number of degrees of freedom, overarching view', 2, None, @@ -124,10 +122,33 @@ doconce format html week35.do.txt --html_style=bootstrap --pygments_html_style=d 2, None, 'testing-the-means-squared-error-as-function-of-complexity'), - ('More preprocessing examples, Franke function and regression', + ('More preprocessing examples, two-dimensional example, the ' + 'Franke function', 2, None, - 'more-preprocessing-examples-franke-function-and-regression'), + 'more-preprocessing-examples-two-dimensional-example-the-franke-function'), + ('To think about, first part', + 2, + None, + 'to-think-about-first-part'), + ('More thinking', 2, None, 'more-thinking'), + ('Still thinking', 2, None, 'still-thinking'), + ('What does centering (subtracting the mean values) mean ' + 'mathematically?', + 2, + None, + 'what-does-centering-subtracting-the-mean-values-mean-mathematically'), + ('Further Manipulations', 2, None, 'further-manipulations'), + ('Wrapping it up', 2, None, 'wrapping-it-up'), + ('Linear Regression code, Intercept handling first', + 2, + None, + 'linear-regression-code-intercept-handling-first'), + ('The Boston housing data example', + 2, + None, + 'the-boston-housing-data-example'), + ('Housing data, the code', 2, None, 'housing-data-the-code'), ('Material for lecture Thursday, August 31', 2, None, @@ -226,28 +247,7 @@ doconce format html week35.do.txt --html_style=bootstrap --pygments_html_style=d ('Deriving the Lasso Regression Equations', 2, None, - 'deriving-the-lasso-regression-equations'), - ('Exercises for week 35', 2, None, 'exercises-for-week-35'), - ('Exercise 1: Setting up various Python environments', - 2, - None, - 'exercise-1-setting-up-various-python-environments'), - ('Exercise 2: making your own data and exploring scikit-learn', - 2, - None, - 'exercise-2-making-your-own-data-and-exploring-scikit-learn'), - ('Exercise 3: Normalizing our data', - 2, - None, - 'exercise-3-normalizing-our-data'), - ('Exercise 4: Adding Ridge Regression', - 2, - None, - 'exercise-4-adding-ridge-regression'), - ('Exercise 5: Analytical exercises', - 2, - None, - 'exercise-5-analytical-exercises')]} + 'deriving-the-lasso-regression-equations')]} end of tocinfo --> @@ -299,62 +299,63 @@ MathJax.Hub.Config({
  • Other useful relations
  • Meet the Hessian Matrix
  • Interpretations and optimizing our parameters
  • -
  • Examples relevant for the exercises
  • +
  • Example relevant for the exercises
  • Own code for Ordinary Least Squares
  • Adding error analysis and training set up
  • Splitting our Data in Training and Test data
  • -
  • Examples
  • +
  • The complete code with a simple data set
  • Making your own test-train splitting
  • -
  • The Boston housing data example
  • -
  • Housing data, the code
  • -
  • Reducing the number of degrees of freedom, overarching view
  • -
  • Preprocessing our data
  • -
  • Functionality in Scikit-Learn
  • -
  • More preprocessing
  • -
  • Frequently used scaling functions
  • -
  • Example of own Standard scaling
  • -
  • Min-Max Scaling
  • -
  • Testing the Means Squared Error as function of Complexity
  • -
  • More preprocessing examples, Franke function and regression
  • -
  • Material for lecture Thursday, August 31
  • -
  • Mathematical Interpretation of Ordinary Least Squares
  • -
  • Residual Error
  • -
  • Simple case
  • -
  • The singular value decomposition
  • -
  • Linear Regression Problems
  • -
  • Fixing the singularity
  • -
  • Basic math of the SVD
  • -
  • The SVD, a Fantastic Algorithm
  • -
  • Economy-size SVD
  • -
  • Codes for the SVD
  • -
  • Note about SVD Calculations
  • -
  • Mathematics of the SVD and implications
  • -
  • Example Matrix
  • -
  • Setting up the Matrix to be inverted
  • -
  • Further properties (important for our analyses later)
  • -
  • Meet the Covariance Matrix
  • -
  • Introducing the Covariance and Correlation functions
  • -
  • Covariance and Correlation Matrix
  • -
  • Correlation Function and Design/Feature Matrix
  • -
  • Covariance Matrix Examples
  • -
  • Correlation Matrix
  • -
  • Correlation Matrix with Pandas
  • -
  • Correlation Matrix with Pandas and the Franke function
  • -
  • Rewriting the Covariance and/or Correlation Matrix
  • -
  • Linking with the SVD
  • -
  • What does it mean?
  • -
  • And finally \( \boldsymbol{X}\boldsymbol{X}^T \)
  • -
  • Ridge and LASSO Regression
  • -
  • Deriving the Ridge Regression Equations
  • -
  • Interpreting the Ridge results
  • -
  • More interpretations
  • -
  • Deriving the Lasso Regression Equations
  • -
  • Exercises for week 35
  • -
  • Exercise 1: Setting up various Python environments
  • -
  • Exercise 2: making your own data and exploring scikit-learn
  • -
  • Exercise 3: Normalizing our data
  • -
  • Exercise 4: Adding Ridge Regression
  • -
  • Exercise 5: Analytical exercises
  • +
  • Reducing the number of degrees of freedom, overarching view
  • +
  • Preprocessing our data
  • +
  • Functionality in Scikit-Learn
  • +
  • More preprocessing
  • +
  • Frequently used scaling functions
  • +
  • Example of own Standard scaling
  • +
  • Min-Max Scaling
  • +
  • Testing the Means Squared Error as function of Complexity
  • +
  • More preprocessing examples, two-dimensional example, the Franke function
  • +
  • To think about, first part
  • +
  • More thinking
  • +
  • Still thinking
  • +
  • What does centering (subtracting the mean values) mean mathematically?
  • +
  • Further Manipulations
  • +
  • Wrapping it up
  • +
  • Linear Regression code, Intercept handling first
  • +
  • The Boston housing data example
  • +
  • Housing data, the code
  • +
  • Material for lecture Thursday, August 31
  • +
  • Mathematical Interpretation of Ordinary Least Squares
  • +
  • Residual Error
  • +
  • Simple case
  • +
  • The singular value decomposition
  • +
  • Linear Regression Problems
  • +
  • Fixing the singularity
  • +
  • Basic math of the SVD
  • +
  • The SVD, a Fantastic Algorithm
  • +
  • Economy-size SVD
  • +
  • Codes for the SVD
  • +
  • Note about SVD Calculations
  • +
  • Mathematics of the SVD and implications
  • +
  • Example Matrix
  • +
  • Setting up the Matrix to be inverted
  • +
  • Further properties (important for our analyses later)
  • +
  • Meet the Covariance Matrix
  • +
  • Introducing the Covariance and Correlation functions
  • +
  • Covariance and Correlation Matrix
  • +
  • Correlation Function and Design/Feature Matrix
  • +
  • Covariance Matrix Examples
  • +
  • Correlation Matrix
  • +
  • Correlation Matrix with Pandas
  • +
  • Correlation Matrix with Pandas and the Franke function
  • +
  • Rewriting the Covariance and/or Correlation Matrix
  • +
  • Linking with the SVD
  • +
  • What does it mean?
  • +
  • And finally \( \boldsymbol{X}\boldsymbol{X}^T \)
  • +
  • Ridge and LASSO Regression
  • +
  • Deriving the Ridge Regression Equations
  • +
  • Interpreting the Ridge results
  • +
  • More interpretations
  • +
  • Deriving the Lasso Regression Equations
  • @@ -366,22 +367,83 @@ MathJax.Hub.Config({

     

     

     

    -

    Interpreting the Ridge results

    +

    Correlation Matrix with Pandas and the Franke function

    -

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

    -$$ -\frac{\sigma_j^2}{\sigma_j^2+\lambda} \leq 1. -$$ + +
    +
    +
    +
    +
    +
    # Common imports
    +import numpy as np
    +import pandas as pd
     
    -

    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} \). + +def FrankeFunction(x,y): + term1 = 0.75*np.exp(-(0.25*(9*x-2)**2) - 0.25*((9*y-2)**2)) + term2 = 0.75*np.exp(-((9*x+1)**2)/49.0 - 0.1*(9*y+1)) + term3 = 0.5*np.exp(-(9*x-7)**2/4.0 - 0.25*((9*y-3)**2)) + term4 = -0.2*np.exp(-(9*x-4)**2 - (9*y-7)**2) + return term1 + term2 + term3 + term4 + + +def create_X(x, y, n ): + if len(x.shape) > 1: + x = np.ravel(x) + y = np.ravel(y) + + N = len(x) + l = int((n+1)*(n+2)/2) # Number of elements in beta + X = np.ones((N,l)) + + for i in range(1,n+1): + q = int((i)*(i+1)/2) + for k in range(i+1): + X[:,q+k] = (x**(i-k))*(y**k) + + return X + + +# Making meshgrid of datapoints and compute Franke's function +n = 4 +N = 100 +x = np.sort(np.random.uniform(0, 1, N)) +y = np.sort(np.random.uniform(0, 1, N)) +z = FrankeFunction(x, y) +X = create_X(x, y, n=n) + +Xpd = pd.DataFrame(X) +# subtract the mean values and set up the covariance matrix +Xpd = Xpd - Xpd.mean() +covariance_matrix = Xpd.cov() +print(covariance_matrix) +

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

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

    -

    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.

    +

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

    @@ -401,6 +463,12 @@ eigenvalues ordered in a descending way, that is \( \sigma_i \geq

  • 66
  • 67
  • 68
  • +
  • 69
  • +
  • 70
  • +
  • 71
  • +
  • 72
  • +
  • 73
  • +
  • 74
  • »
  • diff --git a/doc/pub/week35/html/._week35-bs065.html b/doc/pub/week35/html/._week35-bs065.html index 4568f1a37..5a8058565 100644 --- a/doc/pub/week35/html/._week35-bs065.html +++ b/doc/pub/week35/html/._week35-bs065.html @@ -75,10 +75,10 @@ doconce format html week35.do.txt --html_style=bootstrap --pygments_html_style=d 2, None, 'interpretations-and-optimizing-our-parameters'), - ('Examples relevant for the exercises', + ('Example relevant for the exercises', 2, None, - 'examples-relevant-for-the-exercises'), + 'example-relevant-for-the-exercises'), ('Own code for Ordinary Least Squares', 2, None, @@ -91,16 +91,14 @@ doconce format html week35.do.txt --html_style=bootstrap --pygments_html_style=d 2, None, 'splitting-our-data-in-training-and-test-data'), - ('Examples', 2, None, 'examples'), + ('The complete code with a simple data set', + 2, + None, + 'the-complete-code-with-a-simple-data-set'), ('Making your own test-train splitting', 2, None, 'making-your-own-test-train-splitting'), - ('The Boston housing data example', - 2, - None, - 'the-boston-housing-data-example'), - ('Housing data, the code', 2, None, 'housing-data-the-code'), ('Reducing the number of degrees of freedom, overarching view', 2, None, @@ -124,10 +122,33 @@ doconce format html week35.do.txt --html_style=bootstrap --pygments_html_style=d 2, None, 'testing-the-means-squared-error-as-function-of-complexity'), - ('More preprocessing examples, Franke function and regression', + ('More preprocessing examples, two-dimensional example, the ' + 'Franke function', 2, None, - 'more-preprocessing-examples-franke-function-and-regression'), + 'more-preprocessing-examples-two-dimensional-example-the-franke-function'), + ('To think about, first part', + 2, + None, + 'to-think-about-first-part'), + ('More thinking', 2, None, 'more-thinking'), + ('Still thinking', 2, None, 'still-thinking'), + ('What does centering (subtracting the mean values) mean ' + 'mathematically?', + 2, + None, + 'what-does-centering-subtracting-the-mean-values-mean-mathematically'), + ('Further Manipulations', 2, None, 'further-manipulations'), + ('Wrapping it up', 2, None, 'wrapping-it-up'), + ('Linear Regression code, Intercept handling first', + 2, + None, + 'linear-regression-code-intercept-handling-first'), + ('The Boston housing data example', + 2, + None, + 'the-boston-housing-data-example'), + ('Housing data, the code', 2, None, 'housing-data-the-code'), ('Material for lecture Thursday, August 31', 2, None, @@ -226,28 +247,7 @@ doconce format html week35.do.txt --html_style=bootstrap --pygments_html_style=d ('Deriving the Lasso Regression Equations', 2, None, - 'deriving-the-lasso-regression-equations'), - ('Exercises for week 35', 2, None, 'exercises-for-week-35'), - ('Exercise 1: Setting up various Python environments', - 2, - None, - 'exercise-1-setting-up-various-python-environments'), - ('Exercise 2: making your own data and exploring scikit-learn', - 2, - None, - 'exercise-2-making-your-own-data-and-exploring-scikit-learn'), - ('Exercise 3: Normalizing our data', - 2, - None, - 'exercise-3-normalizing-our-data'), - ('Exercise 4: Adding Ridge Regression', - 2, - None, - 'exercise-4-adding-ridge-regression'), - ('Exercise 5: Analytical exercises', - 2, - None, - 'exercise-5-analytical-exercises')]} + 'deriving-the-lasso-regression-equations')]} end of tocinfo --> @@ -299,62 +299,63 @@ MathJax.Hub.Config({
  • Other useful relations
  • Meet the Hessian Matrix
  • Interpretations and optimizing our parameters
  • -
  • Examples relevant for the exercises
  • +
  • Example relevant for the exercises
  • Own code for Ordinary Least Squares
  • Adding error analysis and training set up
  • Splitting our Data in Training and Test data
  • -
  • Examples
  • +
  • The complete code with a simple data set
  • Making your own test-train splitting
  • -
  • The Boston housing data example
  • -
  • Housing data, the code
  • -
  • Reducing the number of degrees of freedom, overarching view
  • -
  • Preprocessing our data
  • -
  • Functionality in Scikit-Learn
  • -
  • More preprocessing
  • -
  • Frequently used scaling functions
  • -
  • Example of own Standard scaling
  • -
  • Min-Max Scaling
  • -
  • Testing the Means Squared Error as function of Complexity
  • -
  • More preprocessing examples, Franke function and regression
  • -
  • Material for lecture Thursday, August 31
  • -
  • Mathematical Interpretation of Ordinary Least Squares
  • -
  • Residual Error
  • -
  • Simple case
  • -
  • The singular value decomposition
  • -
  • Linear Regression Problems
  • -
  • Fixing the singularity
  • -
  • Basic math of the SVD
  • -
  • The SVD, a Fantastic Algorithm
  • -
  • Economy-size SVD
  • -
  • Codes for the SVD
  • -
  • Note about SVD Calculations
  • -
  • Mathematics of the SVD and implications
  • -
  • Example Matrix
  • -
  • Setting up the Matrix to be inverted
  • -
  • Further properties (important for our analyses later)
  • -
  • Meet the Covariance Matrix
  • -
  • Introducing the Covariance and Correlation functions
  • -
  • Covariance and Correlation Matrix
  • -
  • Correlation Function and Design/Feature Matrix
  • -
  • Covariance Matrix Examples
  • -
  • Correlation Matrix
  • -
  • Correlation Matrix with Pandas
  • -
  • Correlation Matrix with Pandas and the Franke function
  • -
  • Rewriting the Covariance and/or Correlation Matrix
  • -
  • Linking with the SVD
  • -
  • What does it mean?
  • -
  • And finally \( \boldsymbol{X}\boldsymbol{X}^T \)
  • -
  • Ridge and LASSO Regression
  • -
  • Deriving the Ridge Regression Equations
  • -
  • Interpreting the Ridge results
  • -
  • More interpretations
  • -
  • Deriving the Lasso Regression Equations
  • -
  • Exercises for week 35
  • -
  • Exercise 1: Setting up various Python environments
  • -
  • Exercise 2: making your own data and exploring scikit-learn
  • -
  • Exercise 3: Normalizing our data
  • -
  • Exercise 4: Adding Ridge Regression
  • -
  • Exercise 5: Analytical exercises
  • +
  • Reducing the number of degrees of freedom, overarching view
  • +
  • Preprocessing our data
  • +
  • Functionality in Scikit-Learn
  • +
  • More preprocessing
  • +
  • Frequently used scaling functions
  • +
  • Example of own Standard scaling
  • +
  • Min-Max Scaling
  • +
  • Testing the Means Squared Error as function of Complexity
  • +
  • More preprocessing examples, two-dimensional example, the Franke function
  • +
  • To think about, first part
  • +
  • More thinking
  • +
  • Still thinking
  • +
  • What does centering (subtracting the mean values) mean mathematically?
  • +
  • Further Manipulations
  • +
  • Wrapping it up
  • +
  • Linear Regression code, Intercept handling first
  • +
  • The Boston housing data example
  • +
  • Housing data, the code
  • +
  • Material for lecture Thursday, August 31
  • +
  • Mathematical Interpretation of Ordinary Least Squares
  • +
  • Residual Error
  • +
  • Simple case
  • +
  • The singular value decomposition
  • +
  • Linear Regression Problems
  • +
  • Fixing the singularity
  • +
  • Basic math of the SVD
  • +
  • The SVD, a Fantastic Algorithm
  • +
  • Economy-size SVD
  • +
  • Codes for the SVD
  • +
  • Note about SVD Calculations
  • +
  • Mathematics of the SVD and implications
  • +
  • Example Matrix
  • +
  • Setting up the Matrix to be inverted
  • +
  • Further properties (important for our analyses later)
  • +
  • Meet the Covariance Matrix
  • +
  • Introducing the Covariance and Correlation functions
  • +
  • Covariance and Correlation Matrix
  • +
  • Correlation Function and Design/Feature Matrix
  • +
  • Covariance Matrix Examples
  • +
  • Correlation Matrix
  • +
  • Correlation Matrix with Pandas
  • +
  • Correlation Matrix with Pandas and the Franke function
  • +
  • Rewriting the Covariance and/or Correlation Matrix
  • +
  • Linking with the SVD
  • +
  • What does it mean?
  • +
  • And finally \( \boldsymbol{X}\boldsymbol{X}^T \)
  • +
  • Ridge and LASSO Regression
  • +
  • Deriving the Ridge Regression Equations
  • +
  • Interpreting the Ridge results
  • +
  • More interpretations
  • +
  • Deriving the Lasso Regression Equations
  • @@ -366,35 +367,41 @@ MathJax.Hub.Config({

     

     

     

    -

    More interpretations

    - -

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

    +

    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{X}^T\boldsymbol{X}=(\boldsymbol{X}^T\boldsymbol{X})^{-1} =\boldsymbol{I}. +\boldsymbol{C}[\boldsymbol{x}] = \frac{1}{n}\boldsymbol{X}^T\boldsymbol{X}= \mathbb{E}[\boldsymbol{X}^T\boldsymbol{X}]. $$ -

    In this case the standard OLS results in

    +

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

    $$ -\boldsymbol{\beta}^{\mathrm{OLS}} = \boldsymbol{X}^T\boldsymbol{y}=\sum_{i=0}^{n-1}\boldsymbol{u}_i\boldsymbol{u}_i^T\boldsymbol{y}, +\boldsymbol{X}=\begin{bmatrix} +x_{00} & x_{01}\\ +x_{10} & x_{11}\\ +\end{bmatrix}=\begin{bmatrix} +\boldsymbol{x}_{0} & \boldsymbol{x}_{1}\\ +\end{bmatrix}. $$ -

    and

    - +

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

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

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

    +

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

    We will come back to more interpreations after we have gone through some of the statistical analysis part.

    +

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

    -

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

    +

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

    @@ -413,6 +420,12 @@ Similarly, Mehta et al

  • 66
  • 67
  • 68
  • +
  • 69
  • +
  • 70
  • +
  • 71
  • +
  • 72
  • +
  • 73
  • +
  • 74
  • »
  • diff --git a/doc/pub/week35/html/._week35-bs066.html b/doc/pub/week35/html/._week35-bs066.html index 620d9850e..110940728 100644 --- a/doc/pub/week35/html/._week35-bs066.html +++ b/doc/pub/week35/html/._week35-bs066.html @@ -75,10 +75,10 @@ doconce format html week35.do.txt --html_style=bootstrap --pygments_html_style=d 2, None, 'interpretations-and-optimizing-our-parameters'), - ('Examples relevant for the exercises', + ('Example relevant for the exercises', 2, None, - 'examples-relevant-for-the-exercises'), + 'example-relevant-for-the-exercises'), ('Own code for Ordinary Least Squares', 2, None, @@ -91,16 +91,14 @@ doconce format html week35.do.txt --html_style=bootstrap --pygments_html_style=d 2, None, 'splitting-our-data-in-training-and-test-data'), - ('Examples', 2, None, 'examples'), + ('The complete code with a simple data set', + 2, + None, + 'the-complete-code-with-a-simple-data-set'), ('Making your own test-train splitting', 2, None, 'making-your-own-test-train-splitting'), - ('The Boston housing data example', - 2, - None, - 'the-boston-housing-data-example'), - ('Housing data, the code', 2, None, 'housing-data-the-code'), ('Reducing the number of degrees of freedom, overarching view', 2, None, @@ -124,10 +122,33 @@ doconce format html week35.do.txt --html_style=bootstrap --pygments_html_style=d 2, None, 'testing-the-means-squared-error-as-function-of-complexity'), - ('More preprocessing examples, Franke function and regression', + ('More preprocessing examples, two-dimensional example, the ' + 'Franke function', 2, None, - 'more-preprocessing-examples-franke-function-and-regression'), + 'more-preprocessing-examples-two-dimensional-example-the-franke-function'), + ('To think about, first part', + 2, + None, + 'to-think-about-first-part'), + ('More thinking', 2, None, 'more-thinking'), + ('Still thinking', 2, None, 'still-thinking'), + ('What does centering (subtracting the mean values) mean ' + 'mathematically?', + 2, + None, + 'what-does-centering-subtracting-the-mean-values-mean-mathematically'), + ('Further Manipulations', 2, None, 'further-manipulations'), + ('Wrapping it up', 2, None, 'wrapping-it-up'), + ('Linear Regression code, Intercept handling first', + 2, + None, + 'linear-regression-code-intercept-handling-first'), + ('The Boston housing data example', + 2, + None, + 'the-boston-housing-data-example'), + ('Housing data, the code', 2, None, 'housing-data-the-code'), ('Material for lecture Thursday, August 31', 2, None, @@ -226,28 +247,7 @@ doconce format html week35.do.txt --html_style=bootstrap --pygments_html_style=d ('Deriving the Lasso Regression Equations', 2, None, - 'deriving-the-lasso-regression-equations'), - ('Exercises for week 35', 2, None, 'exercises-for-week-35'), - ('Exercise 1: Setting up various Python environments', - 2, - None, - 'exercise-1-setting-up-various-python-environments'), - ('Exercise 2: making your own data and exploring scikit-learn', - 2, - None, - 'exercise-2-making-your-own-data-and-exploring-scikit-learn'), - ('Exercise 3: Normalizing our data', - 2, - None, - 'exercise-3-normalizing-our-data'), - ('Exercise 4: Adding Ridge Regression', - 2, - None, - 'exercise-4-adding-ridge-regression'), - ('Exercise 5: Analytical exercises', - 2, - None, - 'exercise-5-analytical-exercises')]} + 'deriving-the-lasso-regression-equations')]} end of tocinfo --> @@ -299,62 +299,63 @@ MathJax.Hub.Config({
  • Other useful relations
  • Meet the Hessian Matrix
  • Interpretations and optimizing our parameters
  • -
  • Examples relevant for the exercises
  • +
  • Example relevant for the exercises
  • Own code for Ordinary Least Squares
  • Adding error analysis and training set up
  • Splitting our Data in Training and Test data
  • -
  • Examples
  • +
  • The complete code with a simple data set
  • Making your own test-train splitting
  • -
  • The Boston housing data example
  • -
  • Housing data, the code
  • -
  • Reducing the number of degrees of freedom, overarching view
  • -
  • Preprocessing our data
  • -
  • Functionality in Scikit-Learn
  • -
  • More preprocessing
  • -
  • Frequently used scaling functions
  • -
  • Example of own Standard scaling
  • -
  • Min-Max Scaling
  • -
  • Testing the Means Squared Error as function of Complexity
  • -
  • More preprocessing examples, Franke function and regression
  • -
  • Material for lecture Thursday, August 31
  • -
  • Mathematical Interpretation of Ordinary Least Squares
  • -
  • Residual Error
  • -
  • Simple case
  • -
  • The singular value decomposition
  • -
  • Linear Regression Problems
  • -
  • Fixing the singularity
  • -
  • Basic math of the SVD
  • -
  • The SVD, a Fantastic Algorithm
  • -
  • Economy-size SVD
  • -
  • Codes for the SVD
  • -
  • Note about SVD Calculations
  • -
  • Mathematics of the SVD and implications
  • -
  • Example Matrix
  • -
  • Setting up the Matrix to be inverted
  • -
  • Further properties (important for our analyses later)
  • -
  • Meet the Covariance Matrix
  • -
  • Introducing the Covariance and Correlation functions
  • -
  • Covariance and Correlation Matrix
  • -
  • Correlation Function and Design/Feature Matrix
  • -
  • Covariance Matrix Examples
  • -
  • Correlation Matrix
  • -
  • Correlation Matrix with Pandas
  • -
  • Correlation Matrix with Pandas and the Franke function
  • -
  • Rewriting the Covariance and/or Correlation Matrix
  • -
  • Linking with the SVD
  • -
  • What does it mean?
  • -
  • And finally \( \boldsymbol{X}\boldsymbol{X}^T \)
  • -
  • Ridge and LASSO Regression
  • -
  • Deriving the Ridge Regression Equations
  • -
  • Interpreting the Ridge results
  • -
  • More interpretations
  • -
  • Deriving the Lasso Regression Equations
  • -
  • Exercises for week 35
  • -
  • Exercise 1: Setting up various Python environments
  • -
  • Exercise 2: making your own data and exploring scikit-learn
  • -
  • Exercise 3: Normalizing our data
  • -
  • Exercise 4: Adding Ridge Regression
  • -
  • Exercise 5: Analytical exercises
  • +
  • Reducing the number of degrees of freedom, overarching view
  • +
  • Preprocessing our data
  • +
  • Functionality in Scikit-Learn
  • +
  • More preprocessing
  • +
  • Frequently used scaling functions
  • +
  • Example of own Standard scaling
  • +
  • Min-Max Scaling
  • +
  • Testing the Means Squared Error as function of Complexity
  • +
  • More preprocessing examples, two-dimensional example, the Franke function
  • +
  • To think about, first part
  • +
  • More thinking
  • +
  • Still thinking
  • +
  • What does centering (subtracting the mean values) mean mathematically?
  • +
  • Further Manipulations
  • +
  • Wrapping it up
  • +
  • Linear Regression code, Intercept handling first
  • +
  • The Boston housing data example
  • +
  • Housing data, the code
  • +
  • Material for lecture Thursday, August 31
  • +
  • Mathematical Interpretation of Ordinary Least Squares
  • +
  • Residual Error
  • +
  • Simple case
  • +
  • The singular value decomposition
  • +
  • Linear Regression Problems
  • +
  • Fixing the singularity
  • +
  • Basic math of the SVD
  • +
  • The SVD, a Fantastic Algorithm
  • +
  • Economy-size SVD
  • +
  • Codes for the SVD
  • +
  • Note about SVD Calculations
  • +
  • Mathematics of the SVD and implications
  • +
  • Example Matrix
  • +
  • Setting up the Matrix to be inverted
  • +
  • Further properties (important for our analyses later)
  • +
  • Meet the Covariance Matrix
  • +
  • Introducing the Covariance and Correlation functions
  • +
  • Covariance and Correlation Matrix
  • +
  • Correlation Function and Design/Feature Matrix
  • +
  • Covariance Matrix Examples
  • +
  • Correlation Matrix
  • +
  • Correlation Matrix with Pandas
  • +
  • Correlation Matrix with Pandas and the Franke function
  • +
  • Rewriting the Covariance and/or Correlation Matrix
  • +
  • Linking with the SVD
  • +
  • What does it mean?
  • +
  • And finally \( \boldsymbol{X}\boldsymbol{X}^T \)
  • +
  • Ridge and LASSO Regression
  • +
  • Deriving the Ridge Regression Equations
  • +
  • Interpreting the Ridge results
  • +
  • More interpretations
  • +
  • Deriving the Lasso Regression Equations
  • @@ -366,31 +367,39 @@ MathJax.Hub.Config({

     

     

     

    -

    Deriving the Lasso Regression Equations

    - -

    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

    +

    Linking with the SVD

    +

    We saw earlier that

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

    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)

    +

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

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

    we have that the derivative of the cost function is

    +

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

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

    and reordering we have

    +

    meaning we can write

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

    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.

    @@ -408,6 +417,12 @@ $$

  • 66
  • 67
  • 68
  • +
  • 69
  • +
  • 70
  • +
  • 71
  • +
  • 72
  • +
  • 73
  • +
  • 74
  • »
  • diff --git a/doc/pub/week35/html/._week35-bs067.html b/doc/pub/week35/html/._week35-bs067.html index e12610601..4539a0722 100644 --- a/doc/pub/week35/html/._week35-bs067.html +++ b/doc/pub/week35/html/._week35-bs067.html @@ -75,10 +75,10 @@ doconce format html week35.do.txt --html_style=bootstrap --pygments_html_style=d 2, None, 'interpretations-and-optimizing-our-parameters'), - ('Examples relevant for the exercises', + ('Example relevant for the exercises', 2, None, - 'examples-relevant-for-the-exercises'), + 'example-relevant-for-the-exercises'), ('Own code for Ordinary Least Squares', 2, None, @@ -91,16 +91,14 @@ doconce format html week35.do.txt --html_style=bootstrap --pygments_html_style=d 2, None, 'splitting-our-data-in-training-and-test-data'), - ('Examples', 2, None, 'examples'), + ('The complete code with a simple data set', + 2, + None, + 'the-complete-code-with-a-simple-data-set'), ('Making your own test-train splitting', 2, None, 'making-your-own-test-train-splitting'), - ('The Boston housing data example', - 2, - None, - 'the-boston-housing-data-example'), - ('Housing data, the code', 2, None, 'housing-data-the-code'), ('Reducing the number of degrees of freedom, overarching view', 2, None, @@ -124,10 +122,33 @@ doconce format html week35.do.txt --html_style=bootstrap --pygments_html_style=d 2, None, 'testing-the-means-squared-error-as-function-of-complexity'), - ('More preprocessing examples, Franke function and regression', + ('More preprocessing examples, two-dimensional example, the ' + 'Franke function', 2, None, - 'more-preprocessing-examples-franke-function-and-regression'), + 'more-preprocessing-examples-two-dimensional-example-the-franke-function'), + ('To think about, first part', + 2, + None, + 'to-think-about-first-part'), + ('More thinking', 2, None, 'more-thinking'), + ('Still thinking', 2, None, 'still-thinking'), + ('What does centering (subtracting the mean values) mean ' + 'mathematically?', + 2, + None, + 'what-does-centering-subtracting-the-mean-values-mean-mathematically'), + ('Further Manipulations', 2, None, 'further-manipulations'), + ('Wrapping it up', 2, None, 'wrapping-it-up'), + ('Linear Regression code, Intercept handling first', + 2, + None, + 'linear-regression-code-intercept-handling-first'), + ('The Boston housing data example', + 2, + None, + 'the-boston-housing-data-example'), + ('Housing data, the code', 2, None, 'housing-data-the-code'), ('Material for lecture Thursday, August 31', 2, None, @@ -226,28 +247,7 @@ doconce format html week35.do.txt --html_style=bootstrap --pygments_html_style=d ('Deriving the Lasso Regression Equations', 2, None, - 'deriving-the-lasso-regression-equations'), - ('Exercises for week 35', 2, None, 'exercises-for-week-35'), - ('Exercise 1: Setting up various Python environments', - 2, - None, - 'exercise-1-setting-up-various-python-environments'), - ('Exercise 2: making your own data and exploring scikit-learn', - 2, - None, - 'exercise-2-making-your-own-data-and-exploring-scikit-learn'), - ('Exercise 3: Normalizing our data', - 2, - None, - 'exercise-3-normalizing-our-data'), - ('Exercise 4: Adding Ridge Regression', - 2, - None, - 'exercise-4-adding-ridge-regression'), - ('Exercise 5: Analytical exercises', - 2, - None, - 'exercise-5-analytical-exercises')]} + 'deriving-the-lasso-regression-equations')]} end of tocinfo --> @@ -299,62 +299,63 @@ MathJax.Hub.Config({
  • Other useful relations
  • Meet the Hessian Matrix
  • Interpretations and optimizing our parameters
  • -
  • Examples relevant for the exercises
  • +
  • Example relevant for the exercises
  • Own code for Ordinary Least Squares
  • Adding error analysis and training set up
  • Splitting our Data in Training and Test data
  • -
  • Examples
  • +
  • The complete code with a simple data set
  • Making your own test-train splitting
  • -
  • The Boston housing data example
  • -
  • Housing data, the code
  • -
  • Reducing the number of degrees of freedom, overarching view
  • -
  • Preprocessing our data
  • -
  • Functionality in Scikit-Learn
  • -
  • More preprocessing
  • -
  • Frequently used scaling functions
  • -
  • Example of own Standard scaling
  • -
  • Min-Max Scaling
  • -
  • Testing the Means Squared Error as function of Complexity
  • -
  • More preprocessing examples, Franke function and regression
  • -
  • Material for lecture Thursday, August 31
  • -
  • Mathematical Interpretation of Ordinary Least Squares
  • -
  • Residual Error
  • -
  • Simple case
  • -
  • The singular value decomposition
  • -
  • Linear Regression Problems
  • -
  • Fixing the singularity
  • -
  • Basic math of the SVD
  • -
  • The SVD, a Fantastic Algorithm
  • -
  • Economy-size SVD
  • -
  • Codes for the SVD
  • -
  • Note about SVD Calculations
  • -
  • Mathematics of the SVD and implications
  • -
  • Example Matrix
  • -
  • Setting up the Matrix to be inverted
  • -
  • Further properties (important for our analyses later)
  • -
  • Meet the Covariance Matrix
  • -
  • Introducing the Covariance and Correlation functions
  • -
  • Covariance and Correlation Matrix
  • -
  • Correlation Function and Design/Feature Matrix
  • -
  • Covariance Matrix Examples
  • -
  • Correlation Matrix
  • -
  • Correlation Matrix with Pandas
  • -
  • Correlation Matrix with Pandas and the Franke function
  • -
  • Rewriting the Covariance and/or Correlation Matrix
  • -
  • Linking with the SVD
  • -
  • What does it mean?
  • -
  • And finally \( \boldsymbol{X}\boldsymbol{X}^T \)
  • -
  • Ridge and LASSO Regression
  • -
  • Deriving the Ridge Regression Equations
  • -
  • Interpreting the Ridge results
  • -
  • More interpretations
  • -
  • Deriving the Lasso Regression Equations
  • -
  • Exercises for week 35
  • -
  • Exercise 1: Setting up various Python environments
  • -
  • Exercise 2: making your own data and exploring scikit-learn
  • -
  • Exercise 3: Normalizing our data
  • -
  • Exercise 4: Adding Ridge Regression
  • -
  • Exercise 5: Analytical exercises
  • +
  • Reducing the number of degrees of freedom, overarching view
  • +
  • Preprocessing our data
  • +
  • Functionality in Scikit-Learn
  • +
  • More preprocessing
  • +
  • Frequently used scaling functions
  • +
  • Example of own Standard scaling
  • +
  • Min-Max Scaling
  • +
  • Testing the Means Squared Error as function of Complexity
  • +
  • More preprocessing examples, two-dimensional example, the Franke function
  • +
  • To think about, first part
  • +
  • More thinking
  • +
  • Still thinking
  • +
  • What does centering (subtracting the mean values) mean mathematically?
  • +
  • Further Manipulations
  • +
  • Wrapping it up
  • +
  • Linear Regression code, Intercept handling first
  • +
  • The Boston housing data example
  • +
  • Housing data, the code
  • +
  • Material for lecture Thursday, August 31
  • +
  • Mathematical Interpretation of Ordinary Least Squares
  • +
  • Residual Error
  • +
  • Simple case
  • +
  • The singular value decomposition
  • +
  • Linear Regression Problems
  • +
  • Fixing the singularity
  • +
  • Basic math of the SVD
  • +
  • The SVD, a Fantastic Algorithm
  • +
  • Economy-size SVD
  • +
  • Codes for the SVD
  • +
  • Note about SVD Calculations
  • +
  • Mathematics of the SVD and implications
  • +
  • Example Matrix
  • +
  • Setting up the Matrix to be inverted
  • +
  • Further properties (important for our analyses later)
  • +
  • Meet the Covariance Matrix
  • +
  • Introducing the Covariance and Correlation functions
  • +
  • Covariance and Correlation Matrix
  • +
  • Correlation Function and Design/Feature Matrix
  • +
  • Covariance Matrix Examples
  • +
  • Correlation Matrix
  • +
  • Correlation Matrix with Pandas
  • +
  • Correlation Matrix with Pandas and the Franke function
  • +
  • Rewriting the Covariance and/or Correlation Matrix
  • +
  • Linking with the SVD
  • +
  • What does it mean?
  • +
  • And finally \( \boldsymbol{X}\boldsymbol{X}^T \)
  • +
  • Ridge and LASSO Regression
  • +
  • Deriving the Ridge Regression Equations
  • +
  • Interpreting the Ridge results
  • +
  • More interpretations
  • +
  • Deriving the Lasso Regression Equations
  • @@ -366,610 +367,46 @@ MathJax.Hub.Config({

     

     

     

    -

    Exercises for week 35

    +

    What does it mean?

    -

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

    - - -

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

    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 -

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

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

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

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

    - - - -

    -

    -

    - -

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

    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 +

    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

    $$ -f(\boldsymbol{x}) =\boldsymbol{A}\boldsymbol{x}, +\left(\boldsymbol{X}^T\boldsymbol{X}\right)\boldsymbol{v}_i=\boldsymbol{v}_i\sigma_i^2. $$ -

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

    +

    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 +

    $$ -f_i =\sum_{j=0}^{n-1}a_{ij}x_j, +\boldsymbol{C}[\boldsymbol{X}]=\frac{1}{n}\boldsymbol{X}^T\boldsymbol{X}, $$ -

    which leads to

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

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

    -

    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-bs068.html b/doc/pub/week35/html/._week35-bs068.html index af5b8cceb..a72784598 100644 --- a/doc/pub/week35/html/._week35-bs068.html +++ b/doc/pub/week35/html/._week35-bs068.html @@ -43,45 +43,11 @@ doconce format html week35.do.txt --html_style=bootstrap --pygments_html_style=d 2, None, 'why-linear-regression-aka-ordinary-least-squares-and-family-repeat-from-last-week'), - ('Regression analysis, overarching aims', + ('The equations for ordinary least squares', 2, None, - 'regression-analysis-overarching-aims'), - ('Regression analysis, overarching aims II', - 2, - None, - 'regression-analysis-overarching-aims-ii'), - ('Examples', 2, None, 'examples'), - ('General linear models', 2, None, 'general-linear-models'), - ('Rewriting the fitting procedure as a linear algebra problem', - 2, - None, - 'rewriting-the-fitting-procedure-as-a-linear-algebra-problem'), - ('Rewriting the fitting procedure as a linear algebra problem, ' - 'more details', - 2, - None, - 'rewriting-the-fitting-procedure-as-a-linear-algebra-problem-more-details'), - ('Generalizing the fitting procedure as a linear algebra problem', - 2, - None, - 'generalizing-the-fitting-procedure-as-a-linear-algebra-problem'), - ('Generalizing the fitting procedure as a linear algebra problem', - 2, - None, - 'generalizing-the-fitting-procedure-as-a-linear-algebra-problem'), - ('Optimizing our parameters', - 2, - None, - 'optimizing-our-parameters'), - ('Examples relevant for the exercises', - 2, - None, - 'examples-relevant-for-the-exercises'), - ('Optimizing our parameters, more details', - 2, - None, - 'optimizing-our-parameters-more-details'), + 'the-equations-for-ordinary-least-squares'), + ('The cost/loss function', 2, None, 'the-cost-loss-function'), ('Interpretations and optimizing our parameters', 2, None, @@ -109,6 +75,10 @@ doconce format html week35.do.txt --html_style=bootstrap --pygments_html_style=d 2, None, 'interpretations-and-optimizing-our-parameters'), + ('Example relevant for the exercises', + 2, + None, + 'example-relevant-for-the-exercises'), ('Own code for Ordinary Least Squares', 2, None, @@ -121,16 +91,14 @@ doconce format html week35.do.txt --html_style=bootstrap --pygments_html_style=d 2, None, 'splitting-our-data-in-training-and-test-data'), - ('Examples', 2, None, 'examples'), + ('The complete code with a simple data set', + 2, + None, + 'the-complete-code-with-a-simple-data-set'), ('Making your own test-train splitting', 2, None, 'making-your-own-test-train-splitting'), - ('The Boston housing data example', - 2, - None, - 'the-boston-housing-data-example'), - ('Housing data, the code', 2, None, 'housing-data-the-code'), ('Reducing the number of degrees of freedom, overarching view', 2, None, @@ -154,10 +122,33 @@ doconce format html week35.do.txt --html_style=bootstrap --pygments_html_style=d 2, None, 'testing-the-means-squared-error-as-function-of-complexity'), - ('More preprocessing examples, Franke function and regression', + ('More preprocessing examples, two-dimensional example, the ' + 'Franke function', 2, None, - 'more-preprocessing-examples-franke-function-and-regression'), + 'more-preprocessing-examples-two-dimensional-example-the-franke-function'), + ('To think about, first part', + 2, + None, + 'to-think-about-first-part'), + ('More thinking', 2, None, 'more-thinking'), + ('Still thinking', 2, None, 'still-thinking'), + ('What does centering (subtracting the mean values) mean ' + 'mathematically?', + 2, + None, + 'what-does-centering-subtracting-the-mean-values-mean-mathematically'), + ('Further Manipulations', 2, None, 'further-manipulations'), + ('Wrapping it up', 2, None, 'wrapping-it-up'), + ('Linear Regression code, Intercept handling first', + 2, + None, + 'linear-regression-code-intercept-handling-first'), + ('The Boston housing data example', + 2, + None, + 'the-boston-housing-data-example'), + ('Housing data, the code', 2, None, 'housing-data-the-code'), ('Material for lecture Thursday, August 31', 2, None, @@ -256,28 +247,7 @@ doconce format html week35.do.txt --html_style=bootstrap --pygments_html_style=d ('Deriving the Lasso Regression Equations', 2, None, - 'deriving-the-lasso-regression-equations'), - ('Exercises for week 35', 2, None, 'exercises-for-week-35'), - ('Exercise 1: Setting up various Python environments', - 2, - None, - 'exercise-1-setting-up-various-python-environments'), - ('Exercise 2: making your own data and exploring scikit-learn', - 2, - None, - 'exercise-2-making-your-own-data-and-exploring-scikit-learn'), - ('Exercise 3: Normalizing our data', - 2, - None, - 'exercise-3-normalizing-our-data'), - ('Exercise 4: Adding Ridge Regression', - 2, - None, - 'exercise-4-adding-ridge-regression'), - ('Exercise 5: Analytical exercises', - 2, - None, - 'exercise-5-analytical-exercises')]} + 'deriving-the-lasso-regression-equations')]} end of tocinfo --> @@ -315,84 +285,77 @@ MathJax.Hub.Config({
  • Plans for week 35
  •    Reading recommendations:
  • Why Linear Regression (aka Ordinary Least Squares and family), repeat from last week
  • -
  • Regression analysis, overarching aims
  • -
  • Regression analysis, overarching aims II
  • -
  • Examples
  • -
  • General linear models
  • -
  • Rewriting the fitting procedure as a linear algebra problem
  • -
  • Rewriting the fitting procedure as a linear algebra problem, more details
  • -
  • Generalizing the fitting procedure as a linear algebra problem
  • -
  • Generalizing the fitting procedure as a linear algebra problem
  • -
  • Optimizing our parameters
  • -
  • Examples relevant for the exercises
  • -
  • Optimizing our parameters, more details
  • -
  • Interpretations and optimizing our parameters
  • -
  • Interpretations and optimizing our parameters
  • -
  • Some useful matrix and vector expressions
  • -
  • The Jacobian
  • -
  • Derivatives, example 1
  • -
  • Example 2
  • -
  • Example 3
  • -
  • Example 4
  • -
  • The mean squared error and its derivative
  • -
  • Other useful relations
  • -
  • Meet the Hessian Matrix
  • -
  • Interpretations and optimizing our parameters
  • -
  • Own code for Ordinary Least Squares
  • -
  • Adding error analysis and training set up
  • -
  • Splitting our Data in Training and Test data
  • -
  • Examples
  • -
  • Making your own test-train splitting
  • -
  • The Boston housing data example
  • -
  • Housing data, the code
  • -
  • Reducing the number of degrees of freedom, overarching view
  • -
  • Preprocessing our data
  • -
  • Functionality in Scikit-Learn
  • -
  • More preprocessing
  • -
  • Frequently used scaling functions
  • -
  • Example of own Standard scaling
  • -
  • Min-Max Scaling
  • -
  • Testing the Means Squared Error as function of Complexity
  • -
  • More preprocessing examples, Franke function and regression
  • -
  • Material for lecture Thursday, August 31
  • -
  • Mathematical Interpretation of Ordinary Least Squares
  • -
  • Residual Error
  • -
  • Simple case
  • -
  • The singular value decomposition
  • -
  • Linear Regression Problems
  • -
  • Fixing the singularity
  • -
  • Basic math of the SVD
  • -
  • The SVD, a Fantastic Algorithm
  • -
  • Economy-size SVD
  • -
  • Codes for the SVD
  • -
  • Note about SVD Calculations
  • -
  • Mathematics of the SVD and implications
  • -
  • Example Matrix
  • -
  • Setting up the Matrix to be inverted
  • -
  • Further properties (important for our analyses later)
  • -
  • Meet the Covariance Matrix
  • -
  • Introducing the Covariance and Correlation functions
  • -
  • Covariance and Correlation Matrix
  • -
  • Correlation Function and Design/Feature Matrix
  • -
  • Covariance Matrix Examples
  • -
  • Correlation Matrix
  • -
  • Correlation Matrix with Pandas
  • -
  • Correlation Matrix with Pandas and the Franke function
  • -
  • Rewriting the Covariance and/or Correlation Matrix
  • -
  • Linking with the SVD
  • -
  • What does it mean?
  • -
  • And finally \( \boldsymbol{X}\boldsymbol{X}^T \)
  • -
  • Ridge and LASSO Regression
  • -
  • Deriving the Ridge Regression Equations
  • -
  • Interpreting the Ridge results
  • -
  • More interpretations
  • -
  • Deriving the Lasso Regression Equations
  • -
  • Exercises for week 35
  • -
  • Exercise 1: Setting up various Python environments
  • -
  • Exercise 2: making your own data and exploring scikit-learn
  • -
  • Exercise 3: Normalizing our data
  • -
  • Exercise 4: Adding Ridge Regression
  • -
  • Exercise 5: Analytical exercises
  • +
  • The equations for ordinary least squares
  • +
  • The cost/loss function
  • +
  • Interpretations and optimizing our parameters
  • +
  • Interpretations and optimizing our parameters
  • +
  • Some useful matrix and vector expressions
  • +
  • The Jacobian
  • +
  • Derivatives, example 1
  • +
  • Example 2
  • +
  • Example 3
  • +
  • Example 4
  • +
  • The mean squared error and its derivative
  • +
  • Other useful relations
  • +
  • Meet the Hessian Matrix
  • +
  • Interpretations and optimizing our parameters
  • +
  • Example relevant for the exercises
  • +
  • Own code for Ordinary Least Squares
  • +
  • Adding error analysis and training set up
  • +
  • Splitting our Data in Training and Test data
  • +
  • The complete code with a simple data set
  • +
  • Making your own test-train splitting
  • +
  • Reducing the number of degrees of freedom, overarching view
  • +
  • Preprocessing our data
  • +
  • Functionality in Scikit-Learn
  • +
  • More preprocessing
  • +
  • Frequently used scaling functions
  • +
  • Example of own Standard scaling
  • +
  • Min-Max Scaling
  • +
  • Testing the Means Squared Error as function of Complexity
  • +
  • More preprocessing examples, two-dimensional example, the Franke function
  • +
  • To think about, first part
  • +
  • More thinking
  • +
  • Still thinking
  • +
  • What does centering (subtracting the mean values) mean mathematically?
  • +
  • Further Manipulations
  • +
  • Wrapping it up
  • +
  • Linear Regression code, Intercept handling first
  • +
  • The Boston housing data example
  • +
  • Housing data, the code
  • +
  • Material for lecture Thursday, August 31
  • +
  • Mathematical Interpretation of Ordinary Least Squares
  • +
  • Residual Error
  • +
  • Simple case
  • +
  • The singular value decomposition
  • +
  • Linear Regression Problems
  • +
  • Fixing the singularity
  • +
  • Basic math of the SVD
  • +
  • The SVD, a Fantastic Algorithm
  • +
  • Economy-size SVD
  • +
  • Codes for the SVD
  • +
  • Note about SVD Calculations
  • +
  • Mathematics of the SVD and implications
  • +
  • Example Matrix
  • +
  • Setting up the Matrix to be inverted
  • +
  • Further properties (important for our analyses later)
  • +
  • Meet the Covariance Matrix
  • +
  • Introducing the Covariance and Correlation functions
  • +
  • Covariance and Correlation Matrix
  • +
  • Correlation Function and Design/Feature Matrix
  • +
  • Covariance Matrix Examples
  • +
  • Correlation Matrix
  • +
  • Correlation Matrix with Pandas
  • +
  • Correlation Matrix with Pandas and the Franke function
  • +
  • Rewriting the Covariance and/or Correlation Matrix
  • +
  • Linking with the SVD
  • +
  • What does it mean?
  • +
  • And finally \( \boldsymbol{X}\boldsymbol{X}^T \)
  • +
  • Ridge and LASSO Regression
  • +
  • Deriving the Ridge Regression Equations
  • +
  • Interpreting the Ridge results
  • +
  • More interpretations
  • +
  • Deriving the Lasso Regression Equations
  • @@ -404,44 +367,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} \).

    @@ -464,8 +421,6 @@ absolute value of the eigenvalues of \( \boldsymbol{X} \).

  • 72
  • 73
  • 74
  • -
  • 75
  • -
  • 76
  • »
  • diff --git a/doc/pub/week35/html/._week35-bs069.html b/doc/pub/week35/html/._week35-bs069.html index 82912439a..b852e8f62 100644 --- a/doc/pub/week35/html/._week35-bs069.html +++ b/doc/pub/week35/html/._week35-bs069.html @@ -43,45 +43,11 @@ doconce format html week35.do.txt --html_style=bootstrap --pygments_html_style=d 2, None, 'why-linear-regression-aka-ordinary-least-squares-and-family-repeat-from-last-week'), - ('Regression analysis, overarching aims', + ('The equations for ordinary least squares', 2, None, - 'regression-analysis-overarching-aims'), - ('Regression analysis, overarching aims II', - 2, - None, - 'regression-analysis-overarching-aims-ii'), - ('Examples', 2, None, 'examples'), - ('General linear models', 2, None, 'general-linear-models'), - ('Rewriting the fitting procedure as a linear algebra problem', - 2, - None, - 'rewriting-the-fitting-procedure-as-a-linear-algebra-problem'), - ('Rewriting the fitting procedure as a linear algebra problem, ' - 'more details', - 2, - None, - 'rewriting-the-fitting-procedure-as-a-linear-algebra-problem-more-details'), - ('Generalizing the fitting procedure as a linear algebra problem', - 2, - None, - 'generalizing-the-fitting-procedure-as-a-linear-algebra-problem'), - ('Generalizing the fitting procedure as a linear algebra problem', - 2, - None, - 'generalizing-the-fitting-procedure-as-a-linear-algebra-problem'), - ('Optimizing our parameters', - 2, - None, - 'optimizing-our-parameters'), - ('Examples relevant for the exercises', - 2, - None, - 'examples-relevant-for-the-exercises'), - ('Optimizing our parameters, more details', - 2, - None, - 'optimizing-our-parameters-more-details'), + 'the-equations-for-ordinary-least-squares'), + ('The cost/loss function', 2, None, 'the-cost-loss-function'), ('Interpretations and optimizing our parameters', 2, None, @@ -109,6 +75,10 @@ doconce format html week35.do.txt --html_style=bootstrap --pygments_html_style=d 2, None, 'interpretations-and-optimizing-our-parameters'), + ('Example relevant for the exercises', + 2, + None, + 'example-relevant-for-the-exercises'), ('Own code for Ordinary Least Squares', 2, None, @@ -121,16 +91,14 @@ doconce format html week35.do.txt --html_style=bootstrap --pygments_html_style=d 2, None, 'splitting-our-data-in-training-and-test-data'), - ('Examples', 2, None, 'examples'), + ('The complete code with a simple data set', + 2, + None, + 'the-complete-code-with-a-simple-data-set'), ('Making your own test-train splitting', 2, None, 'making-your-own-test-train-splitting'), - ('The Boston housing data example', - 2, - None, - 'the-boston-housing-data-example'), - ('Housing data, the code', 2, None, 'housing-data-the-code'), ('Reducing the number of degrees of freedom, overarching view', 2, None, @@ -154,10 +122,33 @@ doconce format html week35.do.txt --html_style=bootstrap --pygments_html_style=d 2, None, 'testing-the-means-squared-error-as-function-of-complexity'), - ('More preprocessing examples, Franke function and regression', + ('More preprocessing examples, two-dimensional example, the ' + 'Franke function', 2, None, - 'more-preprocessing-examples-franke-function-and-regression'), + 'more-preprocessing-examples-two-dimensional-example-the-franke-function'), + ('To think about, first part', + 2, + None, + 'to-think-about-first-part'), + ('More thinking', 2, None, 'more-thinking'), + ('Still thinking', 2, None, 'still-thinking'), + ('What does centering (subtracting the mean values) mean ' + 'mathematically?', + 2, + None, + 'what-does-centering-subtracting-the-mean-values-mean-mathematically'), + ('Further Manipulations', 2, None, 'further-manipulations'), + ('Wrapping it up', 2, None, 'wrapping-it-up'), + ('Linear Regression code, Intercept handling first', + 2, + None, + 'linear-regression-code-intercept-handling-first'), + ('The Boston housing data example', + 2, + None, + 'the-boston-housing-data-example'), + ('Housing data, the code', 2, None, 'housing-data-the-code'), ('Material for lecture Thursday, August 31', 2, None, @@ -256,28 +247,7 @@ doconce format html week35.do.txt --html_style=bootstrap --pygments_html_style=d ('Deriving the Lasso Regression Equations', 2, None, - 'deriving-the-lasso-regression-equations'), - ('Exercises for week 35', 2, None, 'exercises-for-week-35'), - ('Exercise 1: Setting up various Python environments', - 2, - None, - 'exercise-1-setting-up-various-python-environments'), - ('Exercise 2: making your own data and exploring scikit-learn', - 2, - None, - 'exercise-2-making-your-own-data-and-exploring-scikit-learn'), - ('Exercise 3: Normalizing our data', - 2, - None, - 'exercise-3-normalizing-our-data'), - ('Exercise 4: Adding Ridge Regression', - 2, - None, - 'exercise-4-adding-ridge-regression'), - ('Exercise 5: Analytical exercises', - 2, - None, - 'exercise-5-analytical-exercises')]} + 'deriving-the-lasso-regression-equations')]} end of tocinfo --> @@ -315,84 +285,77 @@ MathJax.Hub.Config({
  • Plans for week 35
  •    Reading recommendations:
  • Why Linear Regression (aka Ordinary Least Squares and family), repeat from last week
  • -
  • Regression analysis, overarching aims
  • -
  • Regression analysis, overarching aims II
  • -
  • Examples
  • -
  • General linear models
  • -
  • Rewriting the fitting procedure as a linear algebra problem
  • -
  • Rewriting the fitting procedure as a linear algebra problem, more details
  • -
  • Generalizing the fitting procedure as a linear algebra problem
  • -
  • Generalizing the fitting procedure as a linear algebra problem
  • -
  • Optimizing our parameters
  • -
  • Examples relevant for the exercises
  • -
  • Optimizing our parameters, more details
  • -
  • Interpretations and optimizing our parameters
  • -
  • Interpretations and optimizing our parameters
  • -
  • Some useful matrix and vector expressions
  • -
  • The Jacobian
  • -
  • Derivatives, example 1
  • -
  • Example 2
  • -
  • Example 3
  • -
  • Example 4
  • -
  • The mean squared error and its derivative
  • -
  • Other useful relations
  • -
  • Meet the Hessian Matrix
  • -
  • Interpretations and optimizing our parameters
  • -
  • Own code for Ordinary Least Squares
  • -
  • Adding error analysis and training set up
  • -
  • Splitting our Data in Training and Test data
  • -
  • Examples
  • -
  • Making your own test-train splitting
  • -
  • The Boston housing data example
  • -
  • Housing data, the code
  • -
  • Reducing the number of degrees of freedom, overarching view
  • -
  • Preprocessing our data
  • -
  • Functionality in Scikit-Learn
  • -
  • More preprocessing
  • -
  • Frequently used scaling functions
  • -
  • Example of own Standard scaling
  • -
  • Min-Max Scaling
  • -
  • Testing the Means Squared Error as function of Complexity
  • -
  • More preprocessing examples, Franke function and regression
  • -
  • Material for lecture Thursday, August 31
  • -
  • Mathematical Interpretation of Ordinary Least Squares
  • -
  • Residual Error
  • -
  • Simple case
  • -
  • The singular value decomposition
  • -
  • Linear Regression Problems
  • -
  • Fixing the singularity
  • -
  • Basic math of the SVD
  • -
  • The SVD, a Fantastic Algorithm
  • -
  • Economy-size SVD
  • -
  • Codes for the SVD
  • -
  • Note about SVD Calculations
  • -
  • Mathematics of the SVD and implications
  • -
  • Example Matrix
  • -
  • Setting up the Matrix to be inverted
  • -
  • Further properties (important for our analyses later)
  • -
  • Meet the Covariance Matrix
  • -
  • Introducing the Covariance and Correlation functions
  • -
  • Covariance and Correlation Matrix
  • -
  • Correlation Function and Design/Feature Matrix
  • -
  • Covariance Matrix Examples
  • -
  • Correlation Matrix
  • -
  • Correlation Matrix with Pandas
  • -
  • Correlation Matrix with Pandas and the Franke function
  • -
  • Rewriting the Covariance and/or Correlation Matrix
  • -
  • Linking with the SVD
  • -
  • What does it mean?
  • -
  • And finally \( \boldsymbol{X}\boldsymbol{X}^T \)
  • -
  • Ridge and LASSO Regression
  • -
  • Deriving the Ridge Regression Equations
  • -
  • Interpreting the Ridge results
  • -
  • More interpretations
  • -
  • Deriving the Lasso Regression Equations
  • -
  • Exercises for week 35
  • -
  • Exercise 1: Setting up various Python environments
  • -
  • Exercise 2: making your own data and exploring scikit-learn
  • -
  • Exercise 3: Normalizing our data
  • -
  • Exercise 4: Adding Ridge Regression
  • -
  • Exercise 5: Analytical exercises
  • +
  • The equations for ordinary least squares
  • +
  • The cost/loss function
  • +
  • Interpretations and optimizing our parameters
  • +
  • Interpretations and optimizing our parameters
  • +
  • Some useful matrix and vector expressions
  • +
  • The Jacobian
  • +
  • Derivatives, example 1
  • +
  • Example 2
  • +
  • Example 3
  • +
  • Example 4
  • +
  • The mean squared error and its derivative
  • +
  • Other useful relations
  • +
  • Meet the Hessian Matrix
  • +
  • Interpretations and optimizing our parameters
  • +
  • Example relevant for the exercises
  • +
  • Own code for Ordinary Least Squares
  • +
  • Adding error analysis and training set up
  • +
  • Splitting our Data in Training and Test data
  • +
  • The complete code with a simple data set
  • +
  • Making your own test-train splitting
  • +
  • Reducing the number of degrees of freedom, overarching view
  • +
  • Preprocessing our data
  • +
  • Functionality in Scikit-Learn
  • +
  • More preprocessing
  • +
  • Frequently used scaling functions
  • +
  • Example of own Standard scaling
  • +
  • Min-Max Scaling
  • +
  • Testing the Means Squared Error as function of Complexity
  • +
  • More preprocessing examples, two-dimensional example, the Franke function
  • +
  • To think about, first part
  • +
  • More thinking
  • +
  • Still thinking
  • +
  • What does centering (subtracting the mean values) mean mathematically?
  • +
  • Further Manipulations
  • +
  • Wrapping it up
  • +
  • Linear Regression code, Intercept handling first
  • +
  • The Boston housing data example
  • +
  • Housing data, the code
  • +
  • Material for lecture Thursday, August 31
  • +
  • Mathematical Interpretation of Ordinary Least Squares
  • +
  • Residual Error
  • +
  • Simple case
  • +
  • The singular value decomposition
  • +
  • Linear Regression Problems
  • +
  • Fixing the singularity
  • +
  • Basic math of the SVD
  • +
  • The SVD, a Fantastic Algorithm
  • +
  • Economy-size SVD
  • +
  • Codes for the SVD
  • +
  • Note about SVD Calculations
  • +
  • Mathematics of the SVD and implications
  • +
  • Example Matrix
  • +
  • Setting up the Matrix to be inverted
  • +
  • Further properties (important for our analyses later)
  • +
  • Meet the Covariance Matrix
  • +
  • Introducing the Covariance and Correlation functions
  • +
  • Covariance and Correlation Matrix
  • +
  • Correlation Function and Design/Feature Matrix
  • +
  • Covariance Matrix Examples
  • +
  • Correlation Matrix
  • +
  • Correlation Matrix with Pandas
  • +
  • Correlation Matrix with Pandas and the Franke function
  • +
  • Rewriting the Covariance and/or Correlation Matrix
  • +
  • Linking with the SVD
  • +
  • What does it mean?
  • +
  • And finally \( \boldsymbol{X}\boldsymbol{X}^T \)
  • +
  • Ridge and LASSO Regression
  • +
  • Deriving the Ridge Regression Equations
  • +
  • Interpreting the Ridge results
  • +
  • More interpretations
  • +
  • Deriving the Lasso Regression Equations
  • @@ -404,40 +367,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. +$$ + +

      @@ -457,8 +440,6 @@ values and the column vectors of \( \boldsymbol{V} \).
    • 72
    • 73
    • 74
    • -
    • 75
    • -
    • 76
    • »
    diff --git a/doc/pub/week35/html/._week35-bs070.html b/doc/pub/week35/html/._week35-bs070.html index bdb242f8a..8bc4e5853 100644 --- a/doc/pub/week35/html/._week35-bs070.html +++ b/doc/pub/week35/html/._week35-bs070.html @@ -43,45 +43,11 @@ doconce format html week35.do.txt --html_style=bootstrap --pygments_html_style=d 2, None, 'why-linear-regression-aka-ordinary-least-squares-and-family-repeat-from-last-week'), - ('Regression analysis, overarching aims', + ('The equations for ordinary least squares', 2, None, - 'regression-analysis-overarching-aims'), - ('Regression analysis, overarching aims II', - 2, - None, - 'regression-analysis-overarching-aims-ii'), - ('Examples', 2, None, 'examples'), - ('General linear models', 2, None, 'general-linear-models'), - ('Rewriting the fitting procedure as a linear algebra problem', - 2, - None, - 'rewriting-the-fitting-procedure-as-a-linear-algebra-problem'), - ('Rewriting the fitting procedure as a linear algebra problem, ' - 'more details', - 2, - None, - 'rewriting-the-fitting-procedure-as-a-linear-algebra-problem-more-details'), - ('Generalizing the fitting procedure as a linear algebra problem', - 2, - None, - 'generalizing-the-fitting-procedure-as-a-linear-algebra-problem'), - ('Generalizing the fitting procedure as a linear algebra problem', - 2, - None, - 'generalizing-the-fitting-procedure-as-a-linear-algebra-problem'), - ('Optimizing our parameters', - 2, - None, - 'optimizing-our-parameters'), - ('Examples relevant for the exercises', - 2, - None, - 'examples-relevant-for-the-exercises'), - ('Optimizing our parameters, more details', - 2, - None, - 'optimizing-our-parameters-more-details'), + 'the-equations-for-ordinary-least-squares'), + ('The cost/loss function', 2, None, 'the-cost-loss-function'), ('Interpretations and optimizing our parameters', 2, None, @@ -109,6 +75,10 @@ doconce format html week35.do.txt --html_style=bootstrap --pygments_html_style=d 2, None, 'interpretations-and-optimizing-our-parameters'), + ('Example relevant for the exercises', + 2, + None, + 'example-relevant-for-the-exercises'), ('Own code for Ordinary Least Squares', 2, None, @@ -121,16 +91,14 @@ doconce format html week35.do.txt --html_style=bootstrap --pygments_html_style=d 2, None, 'splitting-our-data-in-training-and-test-data'), - ('Examples', 2, None, 'examples'), + ('The complete code with a simple data set', + 2, + None, + 'the-complete-code-with-a-simple-data-set'), ('Making your own test-train splitting', 2, None, 'making-your-own-test-train-splitting'), - ('The Boston housing data example', - 2, - None, - 'the-boston-housing-data-example'), - ('Housing data, the code', 2, None, 'housing-data-the-code'), ('Reducing the number of degrees of freedom, overarching view', 2, None, @@ -154,10 +122,33 @@ doconce format html week35.do.txt --html_style=bootstrap --pygments_html_style=d 2, None, 'testing-the-means-squared-error-as-function-of-complexity'), - ('More preprocessing examples, Franke function and regression', + ('More preprocessing examples, two-dimensional example, the ' + 'Franke function', 2, None, - 'more-preprocessing-examples-franke-function-and-regression'), + 'more-preprocessing-examples-two-dimensional-example-the-franke-function'), + ('To think about, first part', + 2, + None, + 'to-think-about-first-part'), + ('More thinking', 2, None, 'more-thinking'), + ('Still thinking', 2, None, 'still-thinking'), + ('What does centering (subtracting the mean values) mean ' + 'mathematically?', + 2, + None, + 'what-does-centering-subtracting-the-mean-values-mean-mathematically'), + ('Further Manipulations', 2, None, 'further-manipulations'), + ('Wrapping it up', 2, None, 'wrapping-it-up'), + ('Linear Regression code, Intercept handling first', + 2, + None, + 'linear-regression-code-intercept-handling-first'), + ('The Boston housing data example', + 2, + None, + 'the-boston-housing-data-example'), + ('Housing data, the code', 2, None, 'housing-data-the-code'), ('Material for lecture Thursday, August 31', 2, None, @@ -256,28 +247,7 @@ doconce format html week35.do.txt --html_style=bootstrap --pygments_html_style=d ('Deriving the Lasso Regression Equations', 2, None, - 'deriving-the-lasso-regression-equations'), - ('Exercises for week 35', 2, None, 'exercises-for-week-35'), - ('Exercise 1: Setting up various Python environments', - 2, - None, - 'exercise-1-setting-up-various-python-environments'), - ('Exercise 2: making your own data and exploring scikit-learn', - 2, - None, - 'exercise-2-making-your-own-data-and-exploring-scikit-learn'), - ('Exercise 3: Normalizing our data', - 2, - None, - 'exercise-3-normalizing-our-data'), - ('Exercise 4: Adding Ridge Regression', - 2, - None, - 'exercise-4-adding-ridge-regression'), - ('Exercise 5: Analytical exercises', - 2, - None, - 'exercise-5-analytical-exercises')]} + 'deriving-the-lasso-regression-equations')]} end of tocinfo --> @@ -315,84 +285,77 @@ MathJax.Hub.Config({
  • Plans for week 35
  •    Reading recommendations:
  • Why Linear Regression (aka Ordinary Least Squares and family), repeat from last week
  • -
  • Regression analysis, overarching aims
  • -
  • Regression analysis, overarching aims II
  • -
  • Examples
  • -
  • General linear models
  • -
  • Rewriting the fitting procedure as a linear algebra problem
  • -
  • Rewriting the fitting procedure as a linear algebra problem, more details
  • -
  • Generalizing the fitting procedure as a linear algebra problem
  • -
  • Generalizing the fitting procedure as a linear algebra problem
  • -
  • Optimizing our parameters
  • -
  • Examples relevant for the exercises
  • -
  • Optimizing our parameters, more details
  • -
  • Interpretations and optimizing our parameters
  • -
  • Interpretations and optimizing our parameters
  • -
  • Some useful matrix and vector expressions
  • -
  • The Jacobian
  • -
  • Derivatives, example 1
  • -
  • Example 2
  • -
  • Example 3
  • -
  • Example 4
  • -
  • The mean squared error and its derivative
  • -
  • Other useful relations
  • -
  • Meet the Hessian Matrix
  • -
  • Interpretations and optimizing our parameters
  • -
  • Own code for Ordinary Least Squares
  • -
  • Adding error analysis and training set up
  • -
  • Splitting our Data in Training and Test data
  • -
  • Examples
  • -
  • Making your own test-train splitting
  • -
  • The Boston housing data example
  • -
  • Housing data, the code
  • -
  • Reducing the number of degrees of freedom, overarching view
  • -
  • Preprocessing our data
  • -
  • Functionality in Scikit-Learn
  • -
  • More preprocessing
  • -
  • Frequently used scaling functions
  • -
  • Example of own Standard scaling
  • -
  • Min-Max Scaling
  • -
  • Testing the Means Squared Error as function of Complexity
  • -
  • More preprocessing examples, Franke function and regression
  • -
  • Material for lecture Thursday, August 31
  • -
  • Mathematical Interpretation of Ordinary Least Squares
  • -
  • Residual Error
  • -
  • Simple case
  • -
  • The singular value decomposition
  • -
  • Linear Regression Problems
  • -
  • Fixing the singularity
  • -
  • Basic math of the SVD
  • -
  • The SVD, a Fantastic Algorithm
  • -
  • Economy-size SVD
  • -
  • Codes for the SVD
  • -
  • Note about SVD Calculations
  • -
  • Mathematics of the SVD and implications
  • -
  • Example Matrix
  • -
  • Setting up the Matrix to be inverted
  • -
  • Further properties (important for our analyses later)
  • -
  • Meet the Covariance Matrix
  • -
  • Introducing the Covariance and Correlation functions
  • -
  • Covariance and Correlation Matrix
  • -
  • Correlation Function and Design/Feature Matrix
  • -
  • Covariance Matrix Examples
  • -
  • Correlation Matrix
  • -
  • Correlation Matrix with Pandas
  • -
  • Correlation Matrix with Pandas and the Franke function
  • -
  • Rewriting the Covariance and/or Correlation Matrix
  • -
  • Linking with the SVD
  • -
  • What does it mean?
  • -
  • And finally \( \boldsymbol{X}\boldsymbol{X}^T \)
  • -
  • Ridge and LASSO Regression
  • -
  • Deriving the Ridge Regression Equations
  • -
  • Interpreting the Ridge results
  • -
  • More interpretations
  • -
  • Deriving the Lasso Regression Equations
  • -
  • Exercises for week 35
  • -
  • Exercise 1: Setting up various Python environments
  • -
  • Exercise 2: making your own data and exploring scikit-learn
  • -
  • Exercise 3: Normalizing our data
  • -
  • Exercise 4: Adding Ridge Regression
  • -
  • Exercise 5: Analytical exercises
  • +
  • The equations for ordinary least squares
  • +
  • The cost/loss function
  • +
  • Interpretations and optimizing our parameters
  • +
  • Interpretations and optimizing our parameters
  • +
  • Some useful matrix and vector expressions
  • +
  • The Jacobian
  • +
  • Derivatives, example 1
  • +
  • Example 2
  • +
  • Example 3
  • +
  • Example 4
  • +
  • The mean squared error and its derivative
  • +
  • Other useful relations
  • +
  • Meet the Hessian Matrix
  • +
  • Interpretations and optimizing our parameters
  • +
  • Example relevant for the exercises
  • +
  • Own code for Ordinary Least Squares
  • +
  • Adding error analysis and training set up
  • +
  • Splitting our Data in Training and Test data
  • +
  • The complete code with a simple data set
  • +
  • Making your own test-train splitting
  • +
  • Reducing the number of degrees of freedom, overarching view
  • +
  • Preprocessing our data
  • +
  • Functionality in Scikit-Learn
  • +
  • More preprocessing
  • +
  • Frequently used scaling functions
  • +
  • Example of own Standard scaling
  • +
  • Min-Max Scaling
  • +
  • Testing the Means Squared Error as function of Complexity
  • +
  • More preprocessing examples, two-dimensional example, the Franke function
  • +
  • To think about, first part
  • +
  • More thinking
  • +
  • Still thinking
  • +
  • What does centering (subtracting the mean values) mean mathematically?
  • +
  • Further Manipulations
  • +
  • Wrapping it up
  • +
  • Linear Regression code, Intercept handling first
  • +
  • The Boston housing data example
  • +
  • Housing data, the code
  • +
  • Material for lecture Thursday, August 31
  • +
  • Mathematical Interpretation of Ordinary Least Squares
  • +
  • Residual Error
  • +
  • Simple case
  • +
  • The singular value decomposition
  • +
  • Linear Regression Problems
  • +
  • Fixing the singularity
  • +
  • Basic math of the SVD
  • +
  • The SVD, a Fantastic Algorithm
  • +
  • Economy-size SVD
  • +
  • Codes for the SVD
  • +
  • Note about SVD Calculations
  • +
  • Mathematics of the SVD and implications
  • +
  • Example Matrix
  • +
  • Setting up the Matrix to be inverted
  • +
  • Further properties (important for our analyses later)
  • +
  • Meet the Covariance Matrix
  • +
  • Introducing the Covariance and Correlation functions
  • +
  • Covariance and Correlation Matrix
  • +
  • Correlation Function and Design/Feature Matrix
  • +
  • Covariance Matrix Examples
  • +
  • Correlation Matrix
  • +
  • Correlation Matrix with Pandas
  • +
  • Correlation Matrix with Pandas and the Franke function
  • +
  • Rewriting the Covariance and/or Correlation Matrix
  • +
  • Linking with the SVD
  • +
  • What does it mean?
  • +
  • And finally \( \boldsymbol{X}\boldsymbol{X}^T \)
  • +
  • Ridge and LASSO Regression
  • +
  • Deriving the Ridge Regression Equations
  • +
  • Interpreting the Ridge results
  • +
  • More interpretations
  • +
  • Deriving the Lasso Regression Equations
  • @@ -404,59 +367,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} \).

    @@ -476,8 +447,6 @@ $$

  • 72
  • 73
  • 74
  • -
  • 75
  • -
  • 76
  • »
  • diff --git a/doc/pub/week35/html/._week35-bs071.html b/doc/pub/week35/html/._week35-bs071.html index 8eb5061bc..89051e519 100644 --- a/doc/pub/week35/html/._week35-bs071.html +++ b/doc/pub/week35/html/._week35-bs071.html @@ -43,45 +43,11 @@ doconce format html week35.do.txt --html_style=bootstrap --pygments_html_style=d 2, None, 'why-linear-regression-aka-ordinary-least-squares-and-family-repeat-from-last-week'), - ('Regression analysis, overarching aims', + ('The equations for ordinary least squares', 2, None, - 'regression-analysis-overarching-aims'), - ('Regression analysis, overarching aims II', - 2, - None, - 'regression-analysis-overarching-aims-ii'), - ('Examples', 2, None, 'examples'), - ('General linear models', 2, None, 'general-linear-models'), - ('Rewriting the fitting procedure as a linear algebra problem', - 2, - None, - 'rewriting-the-fitting-procedure-as-a-linear-algebra-problem'), - ('Rewriting the fitting procedure as a linear algebra problem, ' - 'more details', - 2, - None, - 'rewriting-the-fitting-procedure-as-a-linear-algebra-problem-more-details'), - ('Generalizing the fitting procedure as a linear algebra problem', - 2, - None, - 'generalizing-the-fitting-procedure-as-a-linear-algebra-problem'), - ('Generalizing the fitting procedure as a linear algebra problem', - 2, - None, - 'generalizing-the-fitting-procedure-as-a-linear-algebra-problem'), - ('Optimizing our parameters', - 2, - None, - 'optimizing-our-parameters'), - ('Examples relevant for the exercises', - 2, - None, - 'examples-relevant-for-the-exercises'), - ('Optimizing our parameters, more details', - 2, - None, - 'optimizing-our-parameters-more-details'), + 'the-equations-for-ordinary-least-squares'), + ('The cost/loss function', 2, None, 'the-cost-loss-function'), ('Interpretations and optimizing our parameters', 2, None, @@ -109,6 +75,10 @@ doconce format html week35.do.txt --html_style=bootstrap --pygments_html_style=d 2, None, 'interpretations-and-optimizing-our-parameters'), + ('Example relevant for the exercises', + 2, + None, + 'example-relevant-for-the-exercises'), ('Own code for Ordinary Least Squares', 2, None, @@ -121,16 +91,14 @@ doconce format html week35.do.txt --html_style=bootstrap --pygments_html_style=d 2, None, 'splitting-our-data-in-training-and-test-data'), - ('Examples', 2, None, 'examples'), + ('The complete code with a simple data set', + 2, + None, + 'the-complete-code-with-a-simple-data-set'), ('Making your own test-train splitting', 2, None, 'making-your-own-test-train-splitting'), - ('The Boston housing data example', - 2, - None, - 'the-boston-housing-data-example'), - ('Housing data, the code', 2, None, 'housing-data-the-code'), ('Reducing the number of degrees of freedom, overarching view', 2, None, @@ -154,10 +122,33 @@ doconce format html week35.do.txt --html_style=bootstrap --pygments_html_style=d 2, None, 'testing-the-means-squared-error-as-function-of-complexity'), - ('More preprocessing examples, Franke function and regression', + ('More preprocessing examples, two-dimensional example, the ' + 'Franke function', 2, None, - 'more-preprocessing-examples-franke-function-and-regression'), + 'more-preprocessing-examples-two-dimensional-example-the-franke-function'), + ('To think about, first part', + 2, + None, + 'to-think-about-first-part'), + ('More thinking', 2, None, 'more-thinking'), + ('Still thinking', 2, None, 'still-thinking'), + ('What does centering (subtracting the mean values) mean ' + 'mathematically?', + 2, + None, + 'what-does-centering-subtracting-the-mean-values-mean-mathematically'), + ('Further Manipulations', 2, None, 'further-manipulations'), + ('Wrapping it up', 2, None, 'wrapping-it-up'), + ('Linear Regression code, Intercept handling first', + 2, + None, + 'linear-regression-code-intercept-handling-first'), + ('The Boston housing data example', + 2, + None, + 'the-boston-housing-data-example'), + ('Housing data, the code', 2, None, 'housing-data-the-code'), ('Material for lecture Thursday, August 31', 2, None, @@ -256,28 +247,7 @@ doconce format html week35.do.txt --html_style=bootstrap --pygments_html_style=d ('Deriving the Lasso Regression Equations', 2, None, - 'deriving-the-lasso-regression-equations'), - ('Exercises for week 35', 2, None, 'exercises-for-week-35'), - ('Exercise 1: Setting up various Python environments', - 2, - None, - 'exercise-1-setting-up-various-python-environments'), - ('Exercise 2: making your own data and exploring scikit-learn', - 2, - None, - 'exercise-2-making-your-own-data-and-exploring-scikit-learn'), - ('Exercise 3: Normalizing our data', - 2, - None, - 'exercise-3-normalizing-our-data'), - ('Exercise 4: Adding Ridge Regression', - 2, - None, - 'exercise-4-adding-ridge-regression'), - ('Exercise 5: Analytical exercises', - 2, - None, - 'exercise-5-analytical-exercises')]} + 'deriving-the-lasso-regression-equations')]} end of tocinfo --> @@ -315,84 +285,77 @@ MathJax.Hub.Config({
  • Plans for week 35
  •    Reading recommendations:
  • Why Linear Regression (aka Ordinary Least Squares and family), repeat from last week
  • -
  • Regression analysis, overarching aims
  • -
  • Regression analysis, overarching aims II
  • -
  • Examples
  • -
  • General linear models
  • -
  • Rewriting the fitting procedure as a linear algebra problem
  • -
  • Rewriting the fitting procedure as a linear algebra problem, more details
  • -
  • Generalizing the fitting procedure as a linear algebra problem
  • -
  • Generalizing the fitting procedure as a linear algebra problem
  • -
  • Optimizing our parameters
  • -
  • Examples relevant for the exercises
  • -
  • Optimizing our parameters, more details
  • -
  • Interpretations and optimizing our parameters
  • -
  • Interpretations and optimizing our parameters
  • -
  • Some useful matrix and vector expressions
  • -
  • The Jacobian
  • -
  • Derivatives, example 1
  • -
  • Example 2
  • -
  • Example 3
  • -
  • Example 4
  • -
  • The mean squared error and its derivative
  • -
  • Other useful relations
  • -
  • Meet the Hessian Matrix
  • -
  • Interpretations and optimizing our parameters
  • -
  • Own code for Ordinary Least Squares
  • -
  • Adding error analysis and training set up
  • -
  • Splitting our Data in Training and Test data
  • -
  • Examples
  • -
  • Making your own test-train splitting
  • -
  • The Boston housing data example
  • -
  • Housing data, the code
  • -
  • Reducing the number of degrees of freedom, overarching view
  • -
  • Preprocessing our data
  • -
  • Functionality in Scikit-Learn
  • -
  • More preprocessing
  • -
  • Frequently used scaling functions
  • -
  • Example of own Standard scaling
  • -
  • Min-Max Scaling
  • -
  • Testing the Means Squared Error as function of Complexity
  • -
  • More preprocessing examples, Franke function and regression
  • -
  • Material for lecture Thursday, August 31
  • -
  • Mathematical Interpretation of Ordinary Least Squares
  • -
  • Residual Error
  • -
  • Simple case
  • -
  • The singular value decomposition
  • -
  • Linear Regression Problems
  • -
  • Fixing the singularity
  • -
  • Basic math of the SVD
  • -
  • The SVD, a Fantastic Algorithm
  • -
  • Economy-size SVD
  • -
  • Codes for the SVD
  • -
  • Note about SVD Calculations
  • -
  • Mathematics of the SVD and implications
  • -
  • Example Matrix
  • -
  • Setting up the Matrix to be inverted
  • -
  • Further properties (important for our analyses later)
  • -
  • Meet the Covariance Matrix
  • -
  • Introducing the Covariance and Correlation functions
  • -
  • Covariance and Correlation Matrix
  • -
  • Correlation Function and Design/Feature Matrix
  • -
  • Covariance Matrix Examples
  • -
  • Correlation Matrix
  • -
  • Correlation Matrix with Pandas
  • -
  • Correlation Matrix with Pandas and the Franke function
  • -
  • Rewriting the Covariance and/or Correlation Matrix
  • -
  • Linking with the SVD
  • -
  • What does it mean?
  • -
  • And finally \( \boldsymbol{X}\boldsymbol{X}^T \)
  • -
  • Ridge and LASSO Regression
  • -
  • Deriving the Ridge Regression Equations
  • -
  • Interpreting the Ridge results
  • -
  • More interpretations
  • -
  • Deriving the Lasso Regression Equations
  • -
  • Exercises for week 35
  • -
  • Exercise 1: Setting up various Python environments
  • -
  • Exercise 2: making your own data and exploring scikit-learn
  • -
  • Exercise 3: Normalizing our data
  • -
  • Exercise 4: Adding Ridge Regression
  • -
  • Exercise 5: Analytical exercises
  • +
  • The equations for ordinary least squares
  • +
  • The cost/loss function
  • +
  • Interpretations and optimizing our parameters
  • +
  • Interpretations and optimizing our parameters
  • +
  • Some useful matrix and vector expressions
  • +
  • The Jacobian
  • +
  • Derivatives, example 1
  • +
  • Example 2
  • +
  • Example 3
  • +
  • Example 4
  • +
  • The mean squared error and its derivative
  • +
  • Other useful relations
  • +
  • Meet the Hessian Matrix
  • +
  • Interpretations and optimizing our parameters
  • +
  • Example relevant for the exercises
  • +
  • Own code for Ordinary Least Squares
  • +
  • Adding error analysis and training set up
  • +
  • Splitting our Data in Training and Test data
  • +
  • The complete code with a simple data set
  • +
  • Making your own test-train splitting
  • +
  • Reducing the number of degrees of freedom, overarching view
  • +
  • Preprocessing our data
  • +
  • Functionality in Scikit-Learn
  • +
  • More preprocessing
  • +
  • Frequently used scaling functions
  • +
  • Example of own Standard scaling
  • +
  • Min-Max Scaling
  • +
  • Testing the Means Squared Error as function of Complexity
  • +
  • More preprocessing examples, two-dimensional example, the Franke function
  • +
  • To think about, first part
  • +
  • More thinking
  • +
  • Still thinking
  • +
  • What does centering (subtracting the mean values) mean mathematically?
  • +
  • Further Manipulations
  • +
  • Wrapping it up
  • +
  • Linear Regression code, Intercept handling first
  • +
  • The Boston housing data example
  • +
  • Housing data, the code
  • +
  • Material for lecture Thursday, August 31
  • +
  • Mathematical Interpretation of Ordinary Least Squares
  • +
  • Residual Error
  • +
  • Simple case
  • +
  • The singular value decomposition
  • +
  • Linear Regression Problems
  • +
  • Fixing the singularity
  • +
  • Basic math of the SVD
  • +
  • The SVD, a Fantastic Algorithm
  • +
  • Economy-size SVD
  • +
  • Codes for the SVD
  • +
  • Note about SVD Calculations
  • +
  • Mathematics of the SVD and implications
  • +
  • Example Matrix
  • +
  • Setting up the Matrix to be inverted
  • +
  • Further properties (important for our analyses later)
  • +
  • Meet the Covariance Matrix
  • +
  • Introducing the Covariance and Correlation functions
  • +
  • Covariance and Correlation Matrix
  • +
  • Correlation Function and Design/Feature Matrix
  • +
  • Covariance Matrix Examples
  • +
  • Correlation Matrix
  • +
  • Correlation Matrix with Pandas
  • +
  • Correlation Matrix with Pandas and the Franke function
  • +
  • Rewriting the Covariance and/or Correlation Matrix
  • +
  • Linking with the SVD
  • +
  • What does it mean?
  • +
  • And finally \( \boldsymbol{X}\boldsymbol{X}^T \)
  • +
  • Ridge and LASSO Regression
  • +
  • Deriving the Ridge Regression Equations
  • +
  • Interpreting the Ridge results
  • +
  • More interpretations
  • +
  • Deriving the Lasso Regression Equations
  • @@ -404,67 +367,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.

    @@ -483,8 +401,6 @@ $$

  • 72
  • 73
  • 74
  • -
  • 75
  • -
  • 76
  • »
  • diff --git a/doc/pub/week35/html/week35-bs.html b/doc/pub/week35/html/week35-bs.html index d90915830..2656060af 100644 --- a/doc/pub/week35/html/week35-bs.html +++ b/doc/pub/week35/html/week35-bs.html @@ -75,10 +75,10 @@ doconce format html week35.do.txt --html_style=bootstrap --pygments_html_style=d 2, None, 'interpretations-and-optimizing-our-parameters'), - ('Examples relevant for the exercises', + ('Example relevant for the exercises', 2, None, - 'examples-relevant-for-the-exercises'), + 'example-relevant-for-the-exercises'), ('Own code for Ordinary Least Squares', 2, None, @@ -91,16 +91,14 @@ doconce format html week35.do.txt --html_style=bootstrap --pygments_html_style=d 2, None, 'splitting-our-data-in-training-and-test-data'), - ('Examples', 2, None, 'examples'), + ('The complete code with a simple data set', + 2, + None, + 'the-complete-code-with-a-simple-data-set'), ('Making your own test-train splitting', 2, None, 'making-your-own-test-train-splitting'), - ('The Boston housing data example', - 2, - None, - 'the-boston-housing-data-example'), - ('Housing data, the code', 2, None, 'housing-data-the-code'), ('Reducing the number of degrees of freedom, overarching view', 2, None, @@ -124,10 +122,33 @@ doconce format html week35.do.txt --html_style=bootstrap --pygments_html_style=d 2, None, 'testing-the-means-squared-error-as-function-of-complexity'), - ('More preprocessing examples, Franke function and regression', + ('More preprocessing examples, two-dimensional example, the ' + 'Franke function', 2, None, - 'more-preprocessing-examples-franke-function-and-regression'), + 'more-preprocessing-examples-two-dimensional-example-the-franke-function'), + ('To think about, first part', + 2, + None, + 'to-think-about-first-part'), + ('More thinking', 2, None, 'more-thinking'), + ('Still thinking', 2, None, 'still-thinking'), + ('What does centering (subtracting the mean values) mean ' + 'mathematically?', + 2, + None, + 'what-does-centering-subtracting-the-mean-values-mean-mathematically'), + ('Further Manipulations', 2, None, 'further-manipulations'), + ('Wrapping it up', 2, None, 'wrapping-it-up'), + ('Linear Regression code, Intercept handling first', + 2, + None, + 'linear-regression-code-intercept-handling-first'), + ('The Boston housing data example', + 2, + None, + 'the-boston-housing-data-example'), + ('Housing data, the code', 2, None, 'housing-data-the-code'), ('Material for lecture Thursday, August 31', 2, None, @@ -226,28 +247,7 @@ doconce format html week35.do.txt --html_style=bootstrap --pygments_html_style=d ('Deriving the Lasso Regression Equations', 2, None, - 'deriving-the-lasso-regression-equations'), - ('Exercises for week 35', 2, None, 'exercises-for-week-35'), - ('Exercise 1: Setting up various Python environments', - 2, - None, - 'exercise-1-setting-up-various-python-environments'), - ('Exercise 2: making your own data and exploring scikit-learn', - 2, - None, - 'exercise-2-making-your-own-data-and-exploring-scikit-learn'), - ('Exercise 3: Normalizing our data', - 2, - None, - 'exercise-3-normalizing-our-data'), - ('Exercise 4: Adding Ridge Regression', - 2, - None, - 'exercise-4-adding-ridge-regression'), - ('Exercise 5: Analytical exercises', - 2, - None, - 'exercise-5-analytical-exercises')]} + 'deriving-the-lasso-regression-equations')]} end of tocinfo --> @@ -299,62 +299,63 @@ MathJax.Hub.Config({
  • Other useful relations
  • Meet the Hessian Matrix
  • Interpretations and optimizing our parameters
  • -
  • Examples relevant for the exercises
  • +
  • Example relevant for the exercises
  • Own code for Ordinary Least Squares
  • Adding error analysis and training set up
  • Splitting our Data in Training and Test data
  • -
  • Examples
  • +
  • The complete code with a simple data set
  • Making your own test-train splitting
  • -
  • The Boston housing data example
  • -
  • Housing data, the code
  • -
  • Reducing the number of degrees of freedom, overarching view
  • -
  • Preprocessing our data
  • -
  • Functionality in Scikit-Learn
  • -
  • More preprocessing
  • -
  • Frequently used scaling functions
  • -
  • Example of own Standard scaling
  • -
  • Min-Max Scaling
  • -
  • Testing the Means Squared Error as function of Complexity
  • -
  • More preprocessing examples, Franke function and regression
  • -
  • Material for lecture Thursday, August 31
  • -
  • Mathematical Interpretation of Ordinary Least Squares
  • -
  • Residual Error
  • -
  • Simple case
  • -
  • The singular value decomposition
  • -
  • Linear Regression Problems
  • -
  • Fixing the singularity
  • -
  • Basic math of the SVD
  • -
  • The SVD, a Fantastic Algorithm
  • -
  • Economy-size SVD
  • -
  • Codes for the SVD
  • -
  • Note about SVD Calculations
  • -
  • Mathematics of the SVD and implications
  • -
  • Example Matrix
  • -
  • Setting up the Matrix to be inverted
  • -
  • Further properties (important for our analyses later)
  • -
  • Meet the Covariance Matrix
  • -
  • Introducing the Covariance and Correlation functions
  • -
  • Covariance and Correlation Matrix
  • -
  • Correlation Function and Design/Feature Matrix
  • -
  • Covariance Matrix Examples
  • -
  • Correlation Matrix
  • -
  • Correlation Matrix with Pandas
  • -
  • Correlation Matrix with Pandas and the Franke function
  • -
  • Rewriting the Covariance and/or Correlation Matrix
  • -
  • Linking with the SVD
  • -
  • What does it mean?
  • -
  • And finally \( \boldsymbol{X}\boldsymbol{X}^T \)
  • -
  • Ridge and LASSO Regression
  • -
  • Deriving the Ridge Regression Equations
  • -
  • Interpreting the Ridge results
  • -
  • More interpretations
  • -
  • Deriving the Lasso Regression Equations
  • -
  • Exercises for week 35
  • -
  • Exercise 1: Setting up various Python environments
  • -
  • Exercise 2: making your own data and exploring scikit-learn
  • -
  • Exercise 3: Normalizing our data
  • -
  • Exercise 4: Adding Ridge Regression
  • -
  • Exercise 5: Analytical exercises
  • +
  • Reducing the number of degrees of freedom, overarching view
  • +
  • Preprocessing our data
  • +
  • Functionality in Scikit-Learn
  • +
  • More preprocessing
  • +
  • Frequently used scaling functions
  • +
  • Example of own Standard scaling
  • +
  • Min-Max Scaling
  • +
  • Testing the Means Squared Error as function of Complexity
  • +
  • More preprocessing examples, two-dimensional example, the Franke function
  • +
  • To think about, first part
  • +
  • More thinking
  • +
  • Still thinking
  • +
  • What does centering (subtracting the mean values) mean mathematically?
  • +
  • Further Manipulations
  • +
  • Wrapping it up
  • +
  • Linear Regression code, Intercept handling first
  • +
  • The Boston housing data example
  • +
  • Housing data, the code
  • +
  • Material for lecture Thursday, August 31
  • +
  • Mathematical Interpretation of Ordinary Least Squares
  • +
  • Residual Error
  • +
  • Simple case
  • +
  • The singular value decomposition
  • +
  • Linear Regression Problems
  • +
  • Fixing the singularity
  • +
  • Basic math of the SVD
  • +
  • The SVD, a Fantastic Algorithm
  • +
  • Economy-size SVD
  • +
  • Codes for the SVD
  • +
  • Note about SVD Calculations
  • +
  • Mathematics of the SVD and implications
  • +
  • Example Matrix
  • +
  • Setting up the Matrix to be inverted
  • +
  • Further properties (important for our analyses later)
  • +
  • Meet the Covariance Matrix
  • +
  • Introducing the Covariance and Correlation functions
  • +
  • Covariance and Correlation Matrix
  • +
  • Correlation Function and Design/Feature Matrix
  • +
  • Covariance Matrix Examples
  • +
  • Correlation Matrix
  • +
  • Correlation Matrix with Pandas
  • +
  • Correlation Matrix with Pandas and the Franke function
  • +
  • Rewriting the Covariance and/or Correlation Matrix
  • +
  • Linking with the SVD
  • +
  • What does it mean?
  • +
  • And finally \( \boldsymbol{X}\boldsymbol{X}^T \)
  • +
  • Ridge and LASSO Regression
  • +
  • Deriving the Ridge Regression Equations
  • +
  • Interpreting the Ridge results
  • +
  • More interpretations
  • +
  • Deriving the Lasso Regression Equations
  • @@ -409,7 +410,7 @@ MathJax.Hub.Config({
  • 9
  • 10
  • ...
  • -
  • 68
  • +
  • 74
  • »
  • diff --git a/doc/pub/week35/html/week35-reveal.html b/doc/pub/week35/html/week35-reveal.html index 52e8a3bf2..f3558b563 100644 --- a/doc/pub/week35/html/week35-reveal.html +++ b/doc/pub/week35/html/week35-reveal.html @@ -203,8 +203,8 @@ MathJax.Hub.Config({

  • Brief repetition from last week
  • Derivation of the equations for ordinary least squares
  • Discussion on how to prepare data and examples of applications of linear regression
  • -

  • Mathematical interpretations of linear regression
  • -

  • Ridge and Lasso regression and Singular Value Decomposition
  • +

  • Material for the lecture on Thursday: Mathematical interpretations of linear regression
  • +

  • Thursday: Ridge and Lasso regression and Singular Value Decomposition
  • Reading recommendations:

    @@ -244,7 +244,7 @@ Similarly, Mehta et a

    Our data which we want to apply a machine learning method on, consist of a set of inputs \( \boldsymbol{x}^T=[x_0,x_1,x_2,\dots,x_{n-1}] \) and the outputs we want to model \( \boldsymbol{x}^T=[y_0,y_1,y_2,\dots,y_{n-1}] \). -We assumed also that the output data can be represented for a regression case by continuous function \( f \) +We assume that the output data can be represented (for a regression case) by a continuous function \( f \) through

     
    @@ -253,9 +253,16 @@ y_i=f(x_i)+\epsilon_i, $$

     
    -

    where \( \epsilon_i \) represents some noise which is normally assumed to +

    or in general

    +

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

     
    + +

    where \( \boldsymbol{\epsilon} \) represents some noise which is normally assumed to be distributed via a normal probability distribution with zero mean -value and a variance \( \sigma_i^ \). +value and a variance \( \sigma^2 \).

    In linear regression we approximate the unknown function with another @@ -277,7 +284,7 @@ $$

    and in order to find the optimal parameters \( \beta_i \) we defined a function which gives a measure of the spread between the values \( y_i \) (which -represent output values we want to reproduce) and the parametrized +represent the output values we want to reproduce) and the parametrized values \( \tilde{y}_i \), namely the so-called cost/loss function.

    @@ -325,7 +332,7 @@ $$

     

    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 +When linking (see the discussions next week) with the maximum likelihood approach below, we will indeed interpret \( y_i \) as a mean value

     
    $$ @@ -365,7 +372,7 @@ $$ $$

     
    -

    or in a matrix-vector form as

    +

    or in a matrix-vector form as (multiplying away the factor \( -2/n \))

     
    $$ \frac{\partial C(\boldsymbol{\beta})}{\partial \boldsymbol{\beta}} = 0 = \boldsymbol{X}^T\left( \boldsymbol{y}-\boldsymbol{X}\boldsymbol{\beta}\right). @@ -727,8 +734,8 @@ $$

    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 +

    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 parameters \( \boldsymbol{\beta} \). Using the above expression for derivatives of vectors and matrices, we find that the second derivative of the mean squared error as cost function is, @@ -792,7 +799,7 @@ $$

    -

    Examples relevant for the exercises

    +

    Example relevant for the exercises

    In order to understand the relation among the predictors \( p \), the set of data \( n \) and the target (outcome, output etc) \( \boldsymbol{y} \), we condiser a simple polynomial fit. @@ -804,22 +811,15 @@ $$ $$

     
    -

    we have five predictors, that is the intercept $\beta_0$and the other terms \( \beta_i \). -This gives \( p=0,1,2,3,4 \). Furthermore we have \( n \) entries for each predictor. It means that our design matrix is a +

    we have five predictors/features. The first is the intercept \( \beta_0 \). The other terms are \( \beta_i \) with \( i=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. -

    Own code for Ordinary Least Squares

    -

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

    +

    It is rather straightforward to implement the matrix inversion and obtain the parameters \( \boldsymbol{\beta} \). After having defined the matrix \( \boldsymbol{X} \) and the outputs \( \boldsymbol{y} \) we have

    @@ -828,7 +828,7 @@ write
    # matrix inversion to find beta
    -beta = np.linalg.inv(X.T.dot(X)).dot(X.T).dot(Energies)
    +beta = (np.linalg.inv(X.T @ X) @ X.T ) @ y
     # and then make the prediction
     ytilde = X @ beta
     
    @@ -870,41 +870,6 @@ 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()
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    @@ -1038,7 +1003,7 @@ but now splitting the data into a training set and a test set.
    -

    Examples

    +

    The complete code with a simple data set

    @@ -1064,11 +1029,13 @@ 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)) +# The design matrix now as function of a fourth-order polynomial +X = np.zeros((len(x),5)) X[:,0] = 1.0 X[:,1] = x X[:,2] = x**2 +X[:,3] = x**3 +X[:,4] = x**4 # 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 @@ -1146,6 +1113,790 @@ normally recommend using the latter functionality.

    +
    +

    Reducing the number of degrees of freedom, overarching view

    +
    + +

    + +

    Many Machine Learning problems involve thousands or even millions of +features for each training instance. Not only does this make training +extremely slow, it can also make it much harder to find a good +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. +

    + +

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

    +
    +
    + +
    +

    Preprocessing our data

    +
    + +

    + +

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

    + +

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

    +
    +
    + +
    +

    Functionality in Scikit-Learn

    + +

    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 +

    +
    + +
    +

    More preprocessing

    + +
    + +

    +

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

    +
    +
    + +
    +

    Frequently used scaling functions

    + +

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

    + +

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

    +
    + +
    +

    Example of own Standard 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. +

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

    +
    + +
    +

    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 +

    + +

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

     
    + +

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

    +
    + +
    +

    Testing the Means Squared Error as function of Complexity

    + +

    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.

    + +

    Write a first code which sets up a design matrix \( X \) defined by a fourth-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
    +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()
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    + +
    +

    More preprocessing examples, two-dimensional example, the Franke function

    + + + +
    +
    +
    +
    +
    +
    # 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
    +
    +# Where to save the figures and data files
    +PROJECT_ROOT_DIR = "Results"
    +FIGURE_ID = "Results/FigureFiles"
    +DATA_ID = "DataFiles/"
    +
    +if not os.path.exists(PROJECT_ROOT_DIR):
    +    os.mkdir(PROJECT_ROOT_DIR)
    +
    +if not os.path.exists(FIGURE_ID):
    +    os.makedirs(FIGURE_ID)
    +
    +if not os.path.exists(DATA_ID):
    +    os.makedirs(DATA_ID)
    +
    +def image_path(fig_id):
    +    return os.path.join(FIGURE_ID, fig_id)
    +
    +def data_path(dat_id):
    +    return os.path.join(DATA_ID, dat_id)
    +
    +def save_fig(fig_id):
    +    plt.savefig(image_path(fig_id) + ".png", format='png')
    +
    +
    +def 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)))
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    + +
    +

    To think about, first part

    + +

    When you are comparing your own code with for example Scikit-Learn's +library, there are some technicalities to keep in mind. The examples +here demonstrate some of these aspects with potential pitfalls. +

    + +

    The discussion here focuses on the role of the intercept, how we can +set up the design matrix, what scaling we should use and other topics +which tend confuse us. +

    + +

    The intercept can be interpreted as the expected value of our +target/output variables when all other predictors are set to zero. +Thus, if we cannot assume that the expected outputs/targets are zero +when all predictors are zero (the columns in the design matrix), it +may be a bad idea to implement a model which penalizes the intercept. +Furthermore, in for example Ridge and Lasso regression, the default solutions +from the library Scikit-Learn (when not shrinking \( \beta_0 \)) for the unknown parameters +\( \boldsymbol{\beta} \), are derived under the assumption that both \( \boldsymbol{y} \) and +\( \boldsymbol{X} \) are zero centered, that is we subtract the mean values. +

    +
    + +
    +

    More thinking

    + +

    If our predictors represent different scales, then it is important to +standardize the design matrix \( \boldsymbol{X} \) by subtracting the mean of each +column from the corresponding column and dividing the column with its +standard deviation. Most machine learning libraries do this as a default. This means that if you compare your code with the results from a given library, +the results may differ. +

    + +

    The +Standadscaler +function in Scikit-Learn does this for us. For the data sets we +have been studying in our various examples, the data are in many cases +already scaled and there is no need to scale them. You as a user of different machine learning algorithms, should always perform a +survey of your data, with a critical assessment of them in case you need to scale the data. +

    + +

    If you need to scale the data, not doing so will give an unfair +penalization of the parameters since their magnitude depends on the +scale of their corresponding predictor. +

    + +

    Suppose as an example that you +you have an input variable given by the heights of different persons. +Human height might be measured in inches or meters or +kilometers. If measured in kilometers, a standard linear regression +model with this predictor would probably give a much bigger +coefficient term, than if measured in millimeters. +This can clearly lead to problems in evaluating the cost/loss functions. +

    +
    + +
    +

    Still thinking

    + +

    Keep in mind that when you transform your data set before training a model, the same transformation needs to be done +on your eventual new data set before making a prediction. If we translate this into a Python code, it would could be implemented as follows +

    + + + +
    +
    +
    +
    +
    +
    #Model training, we compute the mean value of y and X
    +y_train_mean = np.mean(y_train)
    +X_train_mean = np.mean(X_train,axis=0)
    +X_train = X_train - X_train_mean
    +y_train = y_train - y_train_mean
    +
    +# The we fit our model with the training data
    +trained_model = some_model.fit(X_train,y_train)
    +
    +
    +#Model prediction, we need also to transform our data set used for the prediction.
    +X_test = X_test - X_train_mean #Use mean from training data
    +y_pred = trained_model(X_test)
    +y_pred = y_pred + y_train_mean
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    + +
    +

    What does centering (subtracting the mean values) mean mathematically?

    + +

    Let us try to understand what this may imply mathematically when we +subtract the mean values, also known as zero centering. For +simplicity, we will focus on ordinary regression, as done in the above example. +

    + +

    The cost/loss function for regression is

    +

     
    +$$ +C(\beta_0, \beta_1, ... , \beta_{p-1}) = \frac{1}{n}\sum_{i=0}^{n} \left(y_i - \beta_0 - \sum_{j=1}^{p-1} X_{ij}\beta_j\right)^2,. +$$ +

     
    + +

    Recall also that we use the squared value since this leads to an increase of the penalty for higher differences between predicted and output/target values.

    + +

    What we have done is to single out the \( \beta_0 \) term in the definition of the mean squared error (MSE). +The design matrix +\( X \) does in this case not contain any intercept column. +When we take the derivative with respect to \( \beta_0 \), we want the derivative to obey +

    +

     
    +$$ +\frac{\partial C}{\partial \beta_j} = 0, +$$ +

     
    + +

    for all \( j \). For \( \beta_0 \) we have

    + +

     
    +$$ +\frac{\partial C}{\partial \beta_0} = -\frac{2}{n}\sum_{i=0}^{n-1} \left(y_i - \beta_0 - \sum_{j=1}^{p-1} X_{ij} \beta_j\right). +$$ +

     
    + +

    Multiplying away the constant \( 2/n \), we obtain

    +

     
    +$$ +\sum_{i=0}^{n-1} \beta_0 = \sum_{i=0}^{n-1}y_i - \sum_{i=0}^{n-1} \sum_{j=1}^{p-1} X_{ij} \beta_j. +$$ +

     
    +

    + +
    +

    Further Manipulations

    + +

    Let us special first to the case where we have only two parameters \( \beta_0 \) and \( \beta_1 \). +Our result for \( \beta_0 \) simplifies then to +

    +

     
    +$$ +n\beta_0 = \sum_{i=0}^{n-1}y_i - \sum_{i=0}^{n-1} X_{i1} \beta_1. +$$ +

     
    + +

    We obtain then

    +

     
    +$$ +\beta_0 = \frac{1}{n}\sum_{i=0}^{n-1}y_i - \beta_1\frac{1}{n}\sum_{i=0}^{n-1} X_{i1}. +$$ +

     
    + +

    If we define

    +

     
    +$$ +\mu_1=\frac{1}{n}\sum_{i=0}^{n-1} (X_{i1}, +$$ +

     
    + +

    and if we define the mean value of the outputs as

    +

     
    +$$ +\mu_y=\frac{1}{n}\sum_{i=0}^{n-1}y_i, +$$ +

     
    + +

    we have

    +

     
    +$$ +\beta_0 = \mu_y - \beta_1\mu_{1}. +$$ +

     
    + +

    In the general case, that is we have more parameters than \( \beta_0 \) and \( \beta_1 \), we have

    +

     
    +$$ +\beta_0 = \frac{1}{n}\sum_{i=0}^{n-1}y_i - \frac{1}{n}\sum_{i=0}^{n-1}\sum_{j=1}^{p-1} X_{ij}\beta_j. +$$ +

     
    + +

    Replacing \( y_i \) with \( y_i - y_i - \overline{\boldsymbol{y}} \) and centering also our design matrix results in a cost function (in vector-matrix disguise)

    +

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

     
    +

    + +
    +

    Wrapping it up

    + +

    If we minimize with respect to \( \boldsymbol{\beta} \) we have then

    + +

     
    +$$ +\hat{\boldsymbol{\beta}} = (\tilde{X}^T\tilde{X})^{-1}\tilde{X}^T\boldsymbol{\tilde{y}}, +$$ +

     
    + +

    where \( \boldsymbol{\tilde{y}} = \boldsymbol{y} - \overline{\boldsymbol{y}} \) +and \( \tilde{X}_{ij} = X_{ij} - \frac{1}{n}\sum_{k=0}^{n-1}X_{kj} \). +

    + +

    For Ridge regression we need to add \( \lambda \boldsymbol{\beta}^T\boldsymbol{\beta} \) to the cost function and get then

    +

     
    +$$ +\hat{\boldsymbol{\beta}} = (\tilde{X}^T\tilde{X} + \lambda I)^{-1}\tilde{X}^T\boldsymbol{\tilde{y}}. +$$ +

     
    + +

    What does this mean? And why do we insist on all this? Let us look at some examples.

    +
    + +
    +

    Linear Regression code, Intercept handling first

    + +

    This code shows a simple first-order fit to a data set using the above transformed data, where we consider the role of the intercept first, by either excluding it or including it (code example thanks to Øyvind Sigmundson Schøyen). Here our scaling of the data is done by subtracting the mean values only. +Note also that we do not split the data into training and test. +

    + + + +
    +
    +
    +
    +
    +
    import numpy as np
    +import matplotlib.pyplot as plt
    +
    +from sklearn.linear_model import LinearRegression
    +
    +
    +np.random.seed(2021)
    +
    +def MSE(y_data,y_model):
    +    n = np.size(y_model)
    +    return np.sum((y_data-y_model)**2)/n
    +
    +
    +def fit_beta(X, y):
    +    return np.linalg.pinv(X.T @ X) @ X.T @ y
    +
    +
    +true_beta = [2, 0.5, 3.7]
    +
    +x = np.linspace(0, 1, 11)
    +y = np.sum(
    +    np.asarray([x ** p * b for p, b in enumerate(true_beta)]), axis=0
    +) + 0.1 * np.random.normal(size=len(x))
    +
    +degree = 3
    +X = np.zeros((len(x), degree))
    +
    +# Include the intercept in the design matrix
    +for p in range(degree):
    +    X[:, p] = x ** p
    +
    +beta = fit_beta(X, y)
    +
    +# Intercept is included in the design matrix
    +skl = LinearRegression(fit_intercept=False).fit(X, y)
    +
    +print(f"True beta: {true_beta}")
    +print(f"Fitted beta: {beta}")
    +print(f"Sklearn fitted beta: {skl.coef_}")
    +ypredictOwn = X @ beta
    +ypredictSKL = skl.predict(X)
    +print(f"MSE with intercept column")
    +print(MSE(y,ypredictOwn))
    +print(f"MSE with intercept column from SKL")
    +print(MSE(y,ypredictSKL))
    +
    +
    +plt.figure()
    +plt.scatter(x, y, label="Data")
    +plt.plot(x, X @ beta, label="Fit")
    +plt.plot(x, skl.predict(X), label="Sklearn (fit_intercept=False)")
    +
    +
    +# Do not include the intercept in the design matrix
    +X = np.zeros((len(x), degree - 1))
    +
    +for p in range(degree - 1):
    +    X[:, p] = x ** (p + 1)
    +
    +# Intercept is not included in the design matrix
    +skl = LinearRegression(fit_intercept=True).fit(X, y)
    +
    +# Use centered values for X and y when computing coefficients
    +y_offset = np.average(y, axis=0)
    +X_offset = np.average(X, axis=0)
    +
    +beta = fit_beta(X - X_offset, y - y_offset)
    +intercept = np.mean(y_offset - X_offset @ beta)
    +
    +print(f"Manual intercept: {intercept}")
    +print(f"Fitted beta (wiothout intercept): {beta}")
    +print(f"Sklearn intercept: {skl.intercept_}")
    +print(f"Sklearn fitted beta (without intercept): {skl.coef_}")
    +ypredictOwn = X @ beta
    +ypredictSKL = skl.predict(X)
    +print(f"MSE with Manual intercept")
    +print(MSE(y,ypredictOwn+intercept))
    +print(f"MSE with Sklearn intercept")
    +print(MSE(y,ypredictSKL))
    +
    +plt.plot(x, X @ beta + intercept, "--", label="Fit (manual intercept)")
    +plt.plot(x, skl.predict(X), "--", label="Sklearn (fit_intercept=True)")
    +plt.grid()
    +plt.legend()
    +
    +plt.show()
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    + +

    The intercept is the value of our output/target variable +when all our features are zero and our function crosses the \( y \)-axis (for a one-dimensional case). +

    + +

    Printing the MSE, we see first that both methods give the same MSE, as +they should. However, when we move to for example Ridge regression, +the way we treat the intercept may give a larger or smaller MSE, +meaning that the MSE can be penalized by the value of the +intercept. Not including the intercept in the fit, means that the +regularization term does not include \( \beta_0 \). For different values +of \( \lambda \), this may lead to differeing MSE values. +

    + +

    To remind the reader, the regularization term, with the intercept in Ridge regression is given by

    +

     
    +$$ +\lambda \vert\vert \boldsymbol{\beta} \vert\vert_2^2 = \lambda \sum_{j=0}^{p-1}\beta_j^2, +$$ +

     
    + +

    but when we take out the intercept, this equation becomes

    +

     
    +$$ +\lambda \vert\vert \boldsymbol{\beta} \vert\vert_2^2 = \lambda \sum_{j=1}^{p-1}\beta_j^2. +$$ +

     
    + +

    For Lasso regression we have

    +

     
    +$$ +\lambda \vert\vert \boldsymbol{\beta} \vert\vert_1 = \lambda \sum_{j=1}^{p-1}\vert\beta_j\vert. +$$ +

     
    + +

    It means that, when scaling the design matrix and the outputs/targets, by subtracting the mean values, we have an optimization problem which is not penalized by the intercept. The MSE value can then be smaller since it focuses only on the remaining quantities. If we however bring back the intercept, we will get an MSE which then contains the intercept. This becomes more important when we discuss Ridge and Lasso regression next week.

    +
    +

    The Boston housing data example

    @@ -1517,412 +2268,6 @@ plt.show()
    -
    -

    Reducing the number of degrees of freedom, overarching view

    -
    - -

    - -

    Many Machine Learning problems involve thousands or even millions of -features for each training instance. Not only does this make training -extremely slow, it can also make it much harder to find a good -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. -

    - -

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

    -
    -
    - -
    -

    Preprocessing our data

    -
    - -

    - -

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

    - -

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

    -
    -
    - -
    -

    Functionality in Scikit-Learn

    - -

    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 -

    -
    - -
    -

    More preprocessing

    - -
    - -

    -

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

    -
    -
    - -
    -

    Frequently used scaling functions

    - -

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

    - -

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

    -
    - -
    -

    Example of own Standard 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. -

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

    -
    - -
    -

    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 -

    - -

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

     
    - -

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

    -
    - -
    -

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

    - -

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

    More preprocessing examples, Franke function and regression

    - - - -
    -
    -
    -
    -
    -
    # 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
    -
    -# Where to save the figures and data files
    -PROJECT_ROOT_DIR = "Results"
    -FIGURE_ID = "Results/FigureFiles"
    -DATA_ID = "DataFiles/"
    -
    -if not os.path.exists(PROJECT_ROOT_DIR):
    -    os.mkdir(PROJECT_ROOT_DIR)
    -
    -if not os.path.exists(FIGURE_ID):
    -    os.makedirs(FIGURE_ID)
    -
    -if not os.path.exists(DATA_ID):
    -    os.makedirs(DATA_ID)
    -
    -def image_path(fig_id):
    -    return os.path.join(FIGURE_ID, fig_id)
    -
    -def data_path(dat_id):
    -    return os.path.join(DATA_ID, dat_id)
    -
    -def save_fig(fig_id):
    -    plt.savefig(image_path(fig_id) + ".png", format='png')
    -
    -
    -def 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)))
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -

    Material for lecture Thursday, August 31

    @@ -3429,632 +3774,6 @@ $$

    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.

    -
    -

    Exercises for week 35

    - -

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

    - - -

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

     
    - -

    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 -

    -

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

     
    - -

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

    -

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

     
    - -

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

    - - -

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

     
    - -

    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-solarized.html b/doc/pub/week35/html/week35-solarized.html index 589365e7f..f400d9d40 100644 --- a/doc/pub/week35/html/week35-solarized.html +++ b/doc/pub/week35/html/week35-solarized.html @@ -102,10 +102,10 @@ div.toc p,a { 2, None, 'interpretations-and-optimizing-our-parameters'), - ('Examples relevant for the exercises', + ('Example relevant for the exercises', 2, None, - 'examples-relevant-for-the-exercises'), + 'example-relevant-for-the-exercises'), ('Own code for Ordinary Least Squares', 2, None, @@ -118,16 +118,14 @@ div.toc p,a { 2, None, 'splitting-our-data-in-training-and-test-data'), - ('Examples', 2, None, 'examples'), + ('The complete code with a simple data set', + 2, + None, + 'the-complete-code-with-a-simple-data-set'), ('Making your own test-train splitting', 2, None, 'making-your-own-test-train-splitting'), - ('The Boston housing data example', - 2, - None, - 'the-boston-housing-data-example'), - ('Housing data, the code', 2, None, 'housing-data-the-code'), ('Reducing the number of degrees of freedom, overarching view', 2, None, @@ -151,10 +149,33 @@ div.toc p,a { 2, None, 'testing-the-means-squared-error-as-function-of-complexity'), - ('More preprocessing examples, Franke function and regression', + ('More preprocessing examples, two-dimensional example, the ' + 'Franke function', 2, None, - 'more-preprocessing-examples-franke-function-and-regression'), + 'more-preprocessing-examples-two-dimensional-example-the-franke-function'), + ('To think about, first part', + 2, + None, + 'to-think-about-first-part'), + ('More thinking', 2, None, 'more-thinking'), + ('Still thinking', 2, None, 'still-thinking'), + ('What does centering (subtracting the mean values) mean ' + 'mathematically?', + 2, + None, + 'what-does-centering-subtracting-the-mean-values-mean-mathematically'), + ('Further Manipulations', 2, None, 'further-manipulations'), + ('Wrapping it up', 2, None, 'wrapping-it-up'), + ('Linear Regression code, Intercept handling first', + 2, + None, + 'linear-regression-code-intercept-handling-first'), + ('The Boston housing data example', + 2, + None, + 'the-boston-housing-data-example'), + ('Housing data, the code', 2, None, 'housing-data-the-code'), ('Material for lecture Thursday, August 31', 2, None, @@ -253,28 +274,7 @@ div.toc p,a { ('Deriving the Lasso Regression Equations', 2, None, - 'deriving-the-lasso-regression-equations'), - ('Exercises for week 35', 2, None, 'exercises-for-week-35'), - ('Exercise 1: Setting up various Python environments', - 2, - None, - 'exercise-1-setting-up-various-python-environments'), - ('Exercise 2: making your own data and exploring scikit-learn', - 2, - None, - 'exercise-2-making-your-own-data-and-exploring-scikit-learn'), - ('Exercise 3: Normalizing our data', - 2, - None, - 'exercise-3-normalizing-our-data'), - ('Exercise 4: Adding Ridge Regression', - 2, - None, - 'exercise-4-adding-ridge-regression'), - ('Exercise 5: Analytical exercises', - 2, - None, - 'exercise-5-analytical-exercises')]} + 'deriving-the-lasso-regression-equations')]} end of tocinfo --> @@ -325,8 +325,8 @@ MathJax.Hub.Config({
  • Brief repetition from last week
  • Derivation of the equations for ordinary least squares
  • Discussion on how to prepare data and examples of applications of linear regression
  • -
  • Mathematical interpretations of linear regression
  • -
  • Ridge and Lasso regression and Singular Value Decomposition
  • +
  • Material for the lecture on Thursday: Mathematical interpretations of linear regression
  • +
  • Thursday: Ridge and Lasso regression and Singular Value Decomposition
  • Reading recommendations:

    @@ -361,16 +361,21 @@ Similarly, Mehta et a

    Our data which we want to apply a machine learning method on, consist of a set of inputs \( \boldsymbol{x}^T=[x_0,x_1,x_2,\dots,x_{n-1}] \) and the outputs we want to model \( \boldsymbol{x}^T=[y_0,y_1,y_2,\dots,y_{n-1}] \). -We assumed also that the output data can be represented for a regression case by continuous function \( f \) +We assume that the output data can be represented (for a regression case) by a continuous function \( f \) through

    $$ y_i=f(x_i)+\epsilon_i, $$ -

    where \( \epsilon_i \) represents some noise which is normally assumed to +

    or in general

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

    where \( \boldsymbol{\epsilon} \) represents some noise which is normally assumed to be distributed via a normal probability distribution with zero mean -value and a variance \( \sigma_i^ \). +value and a variance \( \sigma^2 \).

    In linear regression we approximate the unknown function with another @@ -390,7 +395,7 @@ $$

    and in order to find the optimal parameters \( \beta_i \) we defined a function which gives a measure of the spread between the values \( y_i \) (which -represent output values we want to reproduce) and the parametrized +represent the output values we want to reproduce) and the parametrized values \( \tilde{y}_i \), namely the so-called cost/loss function.

    @@ -428,7 +433,7 @@ C(\boldsymbol{\beta})=\frac{1}{n}\left\{\left(\boldsymbol{y}-\boldsymbol{X}\bold $$

    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 +When linking (see the discussions next week) with the maximum likelihood approach below, we will indeed interpret \( y_i \) as a mean value

    $$ y_{i}=\langle y_i \rangle = \beta_0x_{i,0}+\beta_1x_{i,1}+\beta_2x_{i,2}+\dots+\beta_{n-1}x_{i,n-1}+\epsilon_i, @@ -460,7 +465,7 @@ $$ \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

    +

    or in a matrix-vector form as (multiplying away the factor \( -2/n \))

    $$ \frac{\partial C(\boldsymbol{\beta})}{\partial \boldsymbol{\beta}} = 0 = \boldsymbol{X}^T\left( \boldsymbol{y}-\boldsymbol{X}\boldsymbol{\beta}\right). $$ @@ -753,8 +758,8 @@ $$









    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 +

    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 parameters \( \boldsymbol{\beta} \). Using the above expression for derivatives of vectors and matrices, we find that the second derivative of the mean squared error as cost function is, @@ -807,7 +812,7 @@ $$









    -

    Examples relevant for the exercises

    +

    Example relevant for the exercises

    In order to understand the relation among the predictors \( p \), the set of data \( n \) and the target (outcome, output etc) \( \boldsymbol{y} \), we condiser a simple polynomial fit. @@ -817,21 +822,14 @@ $$ \tilde{y}_i = \beta_0+\beta_1x_i+\beta_2x_i^2+\beta_3x_i^3+\beta_4x_i^4. $$ -

    we have five predictors, that is the intercept $\beta_0$and the other terms \( \beta_i \). -This gives \( p=0,1,2,3,4 \). Furthermore we have \( n \) entries for each predictor. It means that our design matrix is a +

    we have five predictors/features. The first is the intercept \( \beta_0 \). The other terms are \( \beta_i \) with \( i=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. -

    -









    Own code for Ordinary Least Squares

    -

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

    +

    It is rather straightforward to implement the matrix inversion and obtain the parameters \( \boldsymbol{\beta} \). After having defined the matrix \( \boldsymbol{X} \) and the outputs \( \boldsymbol{y} \) we have

    @@ -840,7 +838,7 @@ write
    # matrix inversion to find beta
    -beta = np.linalg.inv(X.T.dot(X)).dot(X.T).dot(Energies)
    +beta = (np.linalg.inv(X.T @ X) @ X.T ) @ y
     # and then make the prediction
     ytilde = X @ beta
     
    @@ -883,41 +881,6 @@ ytildenp = np.dot(fit,X.T)
    -

    And finally we plot our fit with and compare with data

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









    Adding error analysis and training set up

    @@ -1050,7 +1013,7 @@ but now splitting the data into a training set and a test set.









    -

    Examples

    +

    The complete code with a simple data set

    @@ -1076,11 +1039,13 @@ 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)) +# The design matrix now as function of a fourth-order polynomial +X = np.zeros((len(x),5)) X[:,0] = 1.0 X[:,1] = x X[:,2] = x**2 +X[:,3] = x**3 +X[:,4] = x**4 # 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 @@ -1157,6 +1122,746 @@ it interfaces easily with tensorflow and other libraries, we normally recommend using the latter functionality.

    +









    +

    Reducing the number of degrees of freedom, overarching view

    +
    + +

    + +

    Many Machine Learning problems involve thousands or even millions of +features for each training instance. Not only does this make training +extremely slow, it can also make it much harder to find a good +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. +

    + +

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

    +
    + + +









    +

    Preprocessing our data

    +
    + +

    + +

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

    + +

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

    +
    + + +









    +

    Functionality in Scikit-Learn

    + +

    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 +

    + +









    +

    More preprocessing

    + +
    + +

    +

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

    +
    + + +









    +

    Frequently used scaling functions

    + +

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

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

    + +









    +

    Example of own Standard 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. +

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

    + +









    +

    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 +

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

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

    + +









    +

    Testing the Means Squared Error as function of Complexity

    + +

    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.

    + +

    Write a first code which sets up a design matrix \( X \) defined by a fourth-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
    +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()
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    + + +









    +

    More preprocessing examples, two-dimensional example, the Franke function

    + + + +
    +
    +
    +
    +
    +
    # 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
    +
    +# Where to save the figures and data files
    +PROJECT_ROOT_DIR = "Results"
    +FIGURE_ID = "Results/FigureFiles"
    +DATA_ID = "DataFiles/"
    +
    +if not os.path.exists(PROJECT_ROOT_DIR):
    +    os.mkdir(PROJECT_ROOT_DIR)
    +
    +if not os.path.exists(FIGURE_ID):
    +    os.makedirs(FIGURE_ID)
    +
    +if not os.path.exists(DATA_ID):
    +    os.makedirs(DATA_ID)
    +
    +def image_path(fig_id):
    +    return os.path.join(FIGURE_ID, fig_id)
    +
    +def data_path(dat_id):
    +    return os.path.join(DATA_ID, dat_id)
    +
    +def save_fig(fig_id):
    +    plt.savefig(image_path(fig_id) + ".png", format='png')
    +
    +
    +def 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)))
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    + + +









    +

    To think about, first part

    + +

    When you are comparing your own code with for example Scikit-Learn's +library, there are some technicalities to keep in mind. The examples +here demonstrate some of these aspects with potential pitfalls. +

    + +

    The discussion here focuses on the role of the intercept, how we can +set up the design matrix, what scaling we should use and other topics +which tend confuse us. +

    + +

    The intercept can be interpreted as the expected value of our +target/output variables when all other predictors are set to zero. +Thus, if we cannot assume that the expected outputs/targets are zero +when all predictors are zero (the columns in the design matrix), it +may be a bad idea to implement a model which penalizes the intercept. +Furthermore, in for example Ridge and Lasso regression, the default solutions +from the library Scikit-Learn (when not shrinking \( \beta_0 \)) for the unknown parameters +\( \boldsymbol{\beta} \), are derived under the assumption that both \( \boldsymbol{y} \) and +\( \boldsymbol{X} \) are zero centered, that is we subtract the mean values. +

    + +









    +

    More thinking

    + +

    If our predictors represent different scales, then it is important to +standardize the design matrix \( \boldsymbol{X} \) by subtracting the mean of each +column from the corresponding column and dividing the column with its +standard deviation. Most machine learning libraries do this as a default. This means that if you compare your code with the results from a given library, +the results may differ. +

    + +

    The +Standadscaler +function in Scikit-Learn does this for us. For the data sets we +have been studying in our various examples, the data are in many cases +already scaled and there is no need to scale them. You as a user of different machine learning algorithms, should always perform a +survey of your data, with a critical assessment of them in case you need to scale the data. +

    + +

    If you need to scale the data, not doing so will give an unfair +penalization of the parameters since their magnitude depends on the +scale of their corresponding predictor. +

    + +

    Suppose as an example that you +you have an input variable given by the heights of different persons. +Human height might be measured in inches or meters or +kilometers. If measured in kilometers, a standard linear regression +model with this predictor would probably give a much bigger +coefficient term, than if measured in millimeters. +This can clearly lead to problems in evaluating the cost/loss functions. +

    + +









    +

    Still thinking

    + +

    Keep in mind that when you transform your data set before training a model, the same transformation needs to be done +on your eventual new data set before making a prediction. If we translate this into a Python code, it would could be implemented as follows +

    + + + +
    +
    +
    +
    +
    +
    #Model training, we compute the mean value of y and X
    +y_train_mean = np.mean(y_train)
    +X_train_mean = np.mean(X_train,axis=0)
    +X_train = X_train - X_train_mean
    +y_train = y_train - y_train_mean
    +
    +# The we fit our model with the training data
    +trained_model = some_model.fit(X_train,y_train)
    +
    +
    +#Model prediction, we need also to transform our data set used for the prediction.
    +X_test = X_test - X_train_mean #Use mean from training data
    +y_pred = trained_model(X_test)
    +y_pred = y_pred + y_train_mean
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    + + +









    +

    What does centering (subtracting the mean values) mean mathematically?

    + +

    Let us try to understand what this may imply mathematically when we +subtract the mean values, also known as zero centering. For +simplicity, we will focus on ordinary regression, as done in the above example. +

    + +

    The cost/loss function for regression is

    +$$ +C(\beta_0, \beta_1, ... , \beta_{p-1}) = \frac{1}{n}\sum_{i=0}^{n} \left(y_i - \beta_0 - \sum_{j=1}^{p-1} X_{ij}\beta_j\right)^2,. +$$ + +

    Recall also that we use the squared value since this leads to an increase of the penalty for higher differences between predicted and output/target values.

    + +

    What we have done is to single out the \( \beta_0 \) term in the definition of the mean squared error (MSE). +The design matrix +\( X \) does in this case not contain any intercept column. +When we take the derivative with respect to \( \beta_0 \), we want the derivative to obey +

    +$$ +\frac{\partial C}{\partial \beta_j} = 0, +$$ + +

    for all \( j \). For \( \beta_0 \) we have

    + +$$ +\frac{\partial C}{\partial \beta_0} = -\frac{2}{n}\sum_{i=0}^{n-1} \left(y_i - \beta_0 - \sum_{j=1}^{p-1} X_{ij} \beta_j\right). +$$ + +

    Multiplying away the constant \( 2/n \), we obtain

    +$$ +\sum_{i=0}^{n-1} \beta_0 = \sum_{i=0}^{n-1}y_i - \sum_{i=0}^{n-1} \sum_{j=1}^{p-1} X_{ij} \beta_j. +$$ + + +









    +

    Further Manipulations

    + +

    Let us special first to the case where we have only two parameters \( \beta_0 \) and \( \beta_1 \). +Our result for \( \beta_0 \) simplifies then to +

    +$$ +n\beta_0 = \sum_{i=0}^{n-1}y_i - \sum_{i=0}^{n-1} X_{i1} \beta_1. +$$ + +

    We obtain then

    +$$ +\beta_0 = \frac{1}{n}\sum_{i=0}^{n-1}y_i - \beta_1\frac{1}{n}\sum_{i=0}^{n-1} X_{i1}. +$$ + +

    If we define

    +$$ +\mu_1=\frac{1}{n}\sum_{i=0}^{n-1} (X_{i1}, +$$ + +

    and if we define the mean value of the outputs as

    +$$ +\mu_y=\frac{1}{n}\sum_{i=0}^{n-1}y_i, +$$ + +

    we have

    +$$ +\beta_0 = \mu_y - \beta_1\mu_{1}. +$$ + +

    In the general case, that is we have more parameters than \( \beta_0 \) and \( \beta_1 \), we have

    +$$ +\beta_0 = \frac{1}{n}\sum_{i=0}^{n-1}y_i - \frac{1}{n}\sum_{i=0}^{n-1}\sum_{j=1}^{p-1} X_{ij}\beta_j. +$$ + +

    Replacing \( y_i \) with \( y_i - y_i - \overline{\boldsymbol{y}} \) and centering also our design matrix results in a cost function (in vector-matrix disguise)

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









    +

    Wrapping it up

    + +

    If we minimize with respect to \( \boldsymbol{\beta} \) we have then

    + +$$ +\hat{\boldsymbol{\beta}} = (\tilde{X}^T\tilde{X})^{-1}\tilde{X}^T\boldsymbol{\tilde{y}}, +$$ + +

    where \( \boldsymbol{\tilde{y}} = \boldsymbol{y} - \overline{\boldsymbol{y}} \) +and \( \tilde{X}_{ij} = X_{ij} - \frac{1}{n}\sum_{k=0}^{n-1}X_{kj} \). +

    + +

    For Ridge regression we need to add \( \lambda \boldsymbol{\beta}^T\boldsymbol{\beta} \) to the cost function and get then

    +$$ +\hat{\boldsymbol{\beta}} = (\tilde{X}^T\tilde{X} + \lambda I)^{-1}\tilde{X}^T\boldsymbol{\tilde{y}}. +$$ + +

    What does this mean? And why do we insist on all this? Let us look at some examples.

    + +









    +

    Linear Regression code, Intercept handling first

    + +

    This code shows a simple first-order fit to a data set using the above transformed data, where we consider the role of the intercept first, by either excluding it or including it (code example thanks to Øyvind Sigmundson Schøyen). Here our scaling of the data is done by subtracting the mean values only. +Note also that we do not split the data into training and test. +

    + + + +
    +
    +
    +
    +
    +
    import numpy as np
    +import matplotlib.pyplot as plt
    +
    +from sklearn.linear_model import LinearRegression
    +
    +
    +np.random.seed(2021)
    +
    +def MSE(y_data,y_model):
    +    n = np.size(y_model)
    +    return np.sum((y_data-y_model)**2)/n
    +
    +
    +def fit_beta(X, y):
    +    return np.linalg.pinv(X.T @ X) @ X.T @ y
    +
    +
    +true_beta = [2, 0.5, 3.7]
    +
    +x = np.linspace(0, 1, 11)
    +y = np.sum(
    +    np.asarray([x ** p * b for p, b in enumerate(true_beta)]), axis=0
    +) + 0.1 * np.random.normal(size=len(x))
    +
    +degree = 3
    +X = np.zeros((len(x), degree))
    +
    +# Include the intercept in the design matrix
    +for p in range(degree):
    +    X[:, p] = x ** p
    +
    +beta = fit_beta(X, y)
    +
    +# Intercept is included in the design matrix
    +skl = LinearRegression(fit_intercept=False).fit(X, y)
    +
    +print(f"True beta: {true_beta}")
    +print(f"Fitted beta: {beta}")
    +print(f"Sklearn fitted beta: {skl.coef_}")
    +ypredictOwn = X @ beta
    +ypredictSKL = skl.predict(X)
    +print(f"MSE with intercept column")
    +print(MSE(y,ypredictOwn))
    +print(f"MSE with intercept column from SKL")
    +print(MSE(y,ypredictSKL))
    +
    +
    +plt.figure()
    +plt.scatter(x, y, label="Data")
    +plt.plot(x, X @ beta, label="Fit")
    +plt.plot(x, skl.predict(X), label="Sklearn (fit_intercept=False)")
    +
    +
    +# Do not include the intercept in the design matrix
    +X = np.zeros((len(x), degree - 1))
    +
    +for p in range(degree - 1):
    +    X[:, p] = x ** (p + 1)
    +
    +# Intercept is not included in the design matrix
    +skl = LinearRegression(fit_intercept=True).fit(X, y)
    +
    +# Use centered values for X and y when computing coefficients
    +y_offset = np.average(y, axis=0)
    +X_offset = np.average(X, axis=0)
    +
    +beta = fit_beta(X - X_offset, y - y_offset)
    +intercept = np.mean(y_offset - X_offset @ beta)
    +
    +print(f"Manual intercept: {intercept}")
    +print(f"Fitted beta (wiothout intercept): {beta}")
    +print(f"Sklearn intercept: {skl.intercept_}")
    +print(f"Sklearn fitted beta (without intercept): {skl.coef_}")
    +ypredictOwn = X @ beta
    +ypredictSKL = skl.predict(X)
    +print(f"MSE with Manual intercept")
    +print(MSE(y,ypredictOwn+intercept))
    +print(f"MSE with Sklearn intercept")
    +print(MSE(y,ypredictSKL))
    +
    +plt.plot(x, X @ beta + intercept, "--", label="Fit (manual intercept)")
    +plt.plot(x, skl.predict(X), "--", label="Sklearn (fit_intercept=True)")
    +plt.grid()
    +plt.legend()
    +
    +plt.show()
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    + +

    The intercept is the value of our output/target variable +when all our features are zero and our function crosses the \( y \)-axis (for a one-dimensional case). +

    + +

    Printing the MSE, we see first that both methods give the same MSE, as +they should. However, when we move to for example Ridge regression, +the way we treat the intercept may give a larger or smaller MSE, +meaning that the MSE can be penalized by the value of the +intercept. Not including the intercept in the fit, means that the +regularization term does not include \( \beta_0 \). For different values +of \( \lambda \), this may lead to differeing MSE values. +

    + +

    To remind the reader, the regularization term, with the intercept in Ridge regression is given by

    +$$ +\lambda \vert\vert \boldsymbol{\beta} \vert\vert_2^2 = \lambda \sum_{j=0}^{p-1}\beta_j^2, +$$ + +

    but when we take out the intercept, this equation becomes

    +$$ +\lambda \vert\vert \boldsymbol{\beta} \vert\vert_2^2 = \lambda \sum_{j=1}^{p-1}\beta_j^2. +$$ + +

    For Lasso regression we have

    +$$ +\lambda \vert\vert \boldsymbol{\beta} \vert\vert_1 = \lambda \sum_{j=1}^{p-1}\vert\beta_j\vert. +$$ + +

    It means that, when scaling the design matrix and the outputs/targets, by subtracting the mean values, we have an optimization problem which is not penalized by the intercept. The MSE value can then be smaller since it focuses only on the remaining quantities. If we however bring back the intercept, we will get an MSE which then contains the intercept. This becomes more important when we discuss Ridge and Lasso regression next week.

    +

    The Boston housing data example

    @@ -1526,404 +2231,6 @@ plt.show()
    -









    -

    Reducing the number of degrees of freedom, overarching view

    -
    - -

    - -

    Many Machine Learning problems involve thousands or even millions of -features for each training instance. Not only does this make training -extremely slow, it can also make it much harder to find a good -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. -

    - -

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

    -
    - - -









    -

    Preprocessing our data

    -
    - -

    - -

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

    - -

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

    -
    - - -









    -

    Functionality in Scikit-Learn

    - -

    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 -

    - -









    -

    More preprocessing

    - -
    - -

    -

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

    -
    - - -









    -

    Frequently used scaling functions

    - -

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

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

    - -









    -

    Example of own Standard 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. -

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

    - -









    -

    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 -

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

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

    - -









    -

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

    - -

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









    -

    More preprocessing examples, Franke function and regression

    - - - -
    -
    -
    -
    -
    -
    # 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
    -
    -# Where to save the figures and data files
    -PROJECT_ROOT_DIR = "Results"
    -FIGURE_ID = "Results/FigureFiles"
    -DATA_ID = "DataFiles/"
    -
    -if not os.path.exists(PROJECT_ROOT_DIR):
    -    os.mkdir(PROJECT_ROOT_DIR)
    -
    -if not os.path.exists(FIGURE_ID):
    -    os.makedirs(FIGURE_ID)
    -
    -if not os.path.exists(DATA_ID):
    -    os.makedirs(DATA_ID)
    -
    -def image_path(fig_id):
    -    return os.path.join(FIGURE_ID, fig_id)
    -
    -def data_path(dat_id):
    -    return os.path.join(DATA_ID, dat_id)
    -
    -def save_fig(fig_id):
    -    plt.savefig(image_path(fig_id) + ".png", format='png')
    -
    -
    -def 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)))
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    - -









    Material for lecture Thursday, August 31

    @@ -3224,597 +3531,6 @@ $$

    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.

    -









    -

    Exercises for week 35

    - -

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

    - - -

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

    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 -

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

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

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

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

    - - -

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

    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}. -$$ - - -
    © 1999-2023, Morten Hjorth-Jensen. Released under CC Attribution-NonCommercial 4.0 license diff --git a/doc/pub/week35/html/week35.html b/doc/pub/week35/html/week35.html index 5ff4a3c67..bd967bfc0 100644 --- a/doc/pub/week35/html/week35.html +++ b/doc/pub/week35/html/week35.html @@ -179,10 +179,10 @@ div.toc p,a { 2, None, 'interpretations-and-optimizing-our-parameters'), - ('Examples relevant for the exercises', + ('Example relevant for the exercises', 2, None, - 'examples-relevant-for-the-exercises'), + 'example-relevant-for-the-exercises'), ('Own code for Ordinary Least Squares', 2, None, @@ -195,16 +195,14 @@ div.toc p,a { 2, None, 'splitting-our-data-in-training-and-test-data'), - ('Examples', 2, None, 'examples'), + ('The complete code with a simple data set', + 2, + None, + 'the-complete-code-with-a-simple-data-set'), ('Making your own test-train splitting', 2, None, 'making-your-own-test-train-splitting'), - ('The Boston housing data example', - 2, - None, - 'the-boston-housing-data-example'), - ('Housing data, the code', 2, None, 'housing-data-the-code'), ('Reducing the number of degrees of freedom, overarching view', 2, None, @@ -228,10 +226,33 @@ div.toc p,a { 2, None, 'testing-the-means-squared-error-as-function-of-complexity'), - ('More preprocessing examples, Franke function and regression', + ('More preprocessing examples, two-dimensional example, the ' + 'Franke function', 2, None, - 'more-preprocessing-examples-franke-function-and-regression'), + 'more-preprocessing-examples-two-dimensional-example-the-franke-function'), + ('To think about, first part', + 2, + None, + 'to-think-about-first-part'), + ('More thinking', 2, None, 'more-thinking'), + ('Still thinking', 2, None, 'still-thinking'), + ('What does centering (subtracting the mean values) mean ' + 'mathematically?', + 2, + None, + 'what-does-centering-subtracting-the-mean-values-mean-mathematically'), + ('Further Manipulations', 2, None, 'further-manipulations'), + ('Wrapping it up', 2, None, 'wrapping-it-up'), + ('Linear Regression code, Intercept handling first', + 2, + None, + 'linear-regression-code-intercept-handling-first'), + ('The Boston housing data example', + 2, + None, + 'the-boston-housing-data-example'), + ('Housing data, the code', 2, None, 'housing-data-the-code'), ('Material for lecture Thursday, August 31', 2, None, @@ -330,28 +351,7 @@ div.toc p,a { ('Deriving the Lasso Regression Equations', 2, None, - 'deriving-the-lasso-regression-equations'), - ('Exercises for week 35', 2, None, 'exercises-for-week-35'), - ('Exercise 1: Setting up various Python environments', - 2, - None, - 'exercise-1-setting-up-various-python-environments'), - ('Exercise 2: making your own data and exploring scikit-learn', - 2, - None, - 'exercise-2-making-your-own-data-and-exploring-scikit-learn'), - ('Exercise 3: Normalizing our data', - 2, - None, - 'exercise-3-normalizing-our-data'), - ('Exercise 4: Adding Ridge Regression', - 2, - None, - 'exercise-4-adding-ridge-regression'), - ('Exercise 5: Analytical exercises', - 2, - None, - 'exercise-5-analytical-exercises')]} + 'deriving-the-lasso-regression-equations')]} end of tocinfo --> @@ -402,8 +402,8 @@ MathJax.Hub.Config({
  • Brief repetition from last week
  • Derivation of the equations for ordinary least squares
  • Discussion on how to prepare data and examples of applications of linear regression
  • -
  • Mathematical interpretations of linear regression
  • -
  • Ridge and Lasso regression and Singular Value Decomposition
  • +
  • Material for the lecture on Thursday: Mathematical interpretations of linear regression
  • +
  • Thursday: Ridge and Lasso regression and Singular Value Decomposition
  • Reading recommendations:

    @@ -438,16 +438,21 @@ Similarly, Mehta et a

    Our data which we want to apply a machine learning method on, consist of a set of inputs \( \boldsymbol{x}^T=[x_0,x_1,x_2,\dots,x_{n-1}] \) and the outputs we want to model \( \boldsymbol{x}^T=[y_0,y_1,y_2,\dots,y_{n-1}] \). -We assumed also that the output data can be represented for a regression case by continuous function \( f \) +We assume that the output data can be represented (for a regression case) by a continuous function \( f \) through

    $$ y_i=f(x_i)+\epsilon_i, $$ -

    where \( \epsilon_i \) represents some noise which is normally assumed to +

    or in general

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

    where \( \boldsymbol{\epsilon} \) represents some noise which is normally assumed to be distributed via a normal probability distribution with zero mean -value and a variance \( \sigma_i^ \). +value and a variance \( \sigma^2 \).

    In linear regression we approximate the unknown function with another @@ -467,7 +472,7 @@ $$

    and in order to find the optimal parameters \( \beta_i \) we defined a function which gives a measure of the spread between the values \( y_i \) (which -represent output values we want to reproduce) and the parametrized +represent the output values we want to reproduce) and the parametrized values \( \tilde{y}_i \), namely the so-called cost/loss function.

    @@ -505,7 +510,7 @@ C(\boldsymbol{\beta})=\frac{1}{n}\left\{\left(\boldsymbol{y}-\boldsymbol{X}\bold $$

    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 +When linking (see the discussions next week) with the maximum likelihood approach below, we will indeed interpret \( y_i \) as a mean value

    $$ y_{i}=\langle y_i \rangle = \beta_0x_{i,0}+\beta_1x_{i,1}+\beta_2x_{i,2}+\dots+\beta_{n-1}x_{i,n-1}+\epsilon_i, @@ -537,7 +542,7 @@ $$ \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

    +

    or in a matrix-vector form as (multiplying away the factor \( -2/n \))

    $$ \frac{\partial C(\boldsymbol{\beta})}{\partial \boldsymbol{\beta}} = 0 = \boldsymbol{X}^T\left( \boldsymbol{y}-\boldsymbol{X}\boldsymbol{\beta}\right). $$ @@ -830,8 +835,8 @@ $$









    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 +

    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 parameters \( \boldsymbol{\beta} \). Using the above expression for derivatives of vectors and matrices, we find that the second derivative of the mean squared error as cost function is, @@ -884,7 +889,7 @@ $$









    -

    Examples relevant for the exercises

    +

    Example relevant for the exercises

    In order to understand the relation among the predictors \( p \), the set of data \( n \) and the target (outcome, output etc) \( \boldsymbol{y} \), we condiser a simple polynomial fit. @@ -894,21 +899,14 @@ $$ \tilde{y}_i = \beta_0+\beta_1x_i+\beta_2x_i^2+\beta_3x_i^3+\beta_4x_i^4. $$ -

    we have five predictors, that is the intercept $\beta_0$and the other terms \( \beta_i \). -This gives \( p=0,1,2,3,4 \). Furthermore we have \( n \) entries for each predictor. It means that our design matrix is a +

    we have five predictors/features. The first is the intercept \( \beta_0 \). The other terms are \( \beta_i \) with \( i=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. -

    -









    Own code for Ordinary Least Squares

    -

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

    +

    It is rather straightforward to implement the matrix inversion and obtain the parameters \( \boldsymbol{\beta} \). After having defined the matrix \( \boldsymbol{X} \) and the outputs \( \boldsymbol{y} \) we have

    @@ -917,7 +915,7 @@ write
    # matrix inversion to find beta
    -beta = np.linalg.inv(X.T.dot(X)).dot(X.T).dot(Energies)
    +beta = (np.linalg.inv(X.T @ X) @ X.T ) @ y
     # and then make the prediction
     ytilde = X @ beta
     
    @@ -960,41 +958,6 @@ ytildenp = np.<
    -

    And finally we plot our fit with and compare with data

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









    Adding error analysis and training set up

    @@ -1127,7 +1090,7 @@ but now splitting the data into a training set and a test set.









    -

    Examples

    +

    The complete code with a simple data set

    @@ -1153,11 +1116,13 @@ x = np.r 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)) +# The design matrix now as function of a fourth-order polynomial +X = np.zeros((len(x),5)) X[:,0] = 1.0 X[:,1] = x X[:,2] = x**2 +X[:,3] = x**3 +X[:,4] = x**4 # 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 @@ -1234,6 +1199,746 @@ it interfaces easily with tensorflow and other libraries, we normally recommend using the latter functionality.

    +









    +

    Reducing the number of degrees of freedom, overarching view

    +
    + +

    + +

    Many Machine Learning problems involve thousands or even millions of +features for each training instance. Not only does this make training +extremely slow, it can also make it much harder to find a good +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. +

    + +

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

    +
    + + +









    +

    Preprocessing our data

    +
    + +

    + +

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

    + +

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

    +
    + + +









    +

    Functionality in Scikit-Learn

    + +

    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 +

    + +









    +

    More preprocessing

    + +
    + +

    +

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

    +
    + + +









    +

    Frequently used scaling functions

    + +

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

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

    + +









    +

    Example of own Standard 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. +

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

    + +









    +

    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 +

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

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

    + +









    +

    Testing the Means Squared Error as function of Complexity

    + +

    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.

    + +

    Write a first code which sets up a design matrix \( X \) defined by a fourth-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
    +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()
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    + + +









    +

    More preprocessing examples, two-dimensional example, the Franke function

    + + + +
    +
    +
    +
    +
    +
    # 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
    +
    +# Where to save the figures and data files
    +PROJECT_ROOT_DIR = "Results"
    +FIGURE_ID = "Results/FigureFiles"
    +DATA_ID = "DataFiles/"
    +
    +if not os.path.exists(PROJECT_ROOT_DIR):
    +    os.mkdir(PROJECT_ROOT_DIR)
    +
    +if not os.path.exists(FIGURE_ID):
    +    os.makedirs(FIGURE_ID)
    +
    +if not os.path.exists(DATA_ID):
    +    os.makedirs(DATA_ID)
    +
    +def image_path(fig_id):
    +    return os.path.join(FIGURE_ID, fig_id)
    +
    +def data_path(dat_id):
    +    return os.path.join(DATA_ID, dat_id)
    +
    +def save_fig(fig_id):
    +    plt.savefig(image_path(fig_id) + ".png", format='png')
    +
    +
    +def 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)))
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    + + +









    +

    To think about, first part

    + +

    When you are comparing your own code with for example Scikit-Learn's +library, there are some technicalities to keep in mind. The examples +here demonstrate some of these aspects with potential pitfalls. +

    + +

    The discussion here focuses on the role of the intercept, how we can +set up the design matrix, what scaling we should use and other topics +which tend confuse us. +

    + +

    The intercept can be interpreted as the expected value of our +target/output variables when all other predictors are set to zero. +Thus, if we cannot assume that the expected outputs/targets are zero +when all predictors are zero (the columns in the design matrix), it +may be a bad idea to implement a model which penalizes the intercept. +Furthermore, in for example Ridge and Lasso regression, the default solutions +from the library Scikit-Learn (when not shrinking \( \beta_0 \)) for the unknown parameters +\( \boldsymbol{\beta} \), are derived under the assumption that both \( \boldsymbol{y} \) and +\( \boldsymbol{X} \) are zero centered, that is we subtract the mean values. +

    + +









    +

    More thinking

    + +

    If our predictors represent different scales, then it is important to +standardize the design matrix \( \boldsymbol{X} \) by subtracting the mean of each +column from the corresponding column and dividing the column with its +standard deviation. Most machine learning libraries do this as a default. This means that if you compare your code with the results from a given library, +the results may differ. +

    + +

    The +Standadscaler +function in Scikit-Learn does this for us. For the data sets we +have been studying in our various examples, the data are in many cases +already scaled and there is no need to scale them. You as a user of different machine learning algorithms, should always perform a +survey of your data, with a critical assessment of them in case you need to scale the data. +

    + +

    If you need to scale the data, not doing so will give an unfair +penalization of the parameters since their magnitude depends on the +scale of their corresponding predictor. +

    + +

    Suppose as an example that you +you have an input variable given by the heights of different persons. +Human height might be measured in inches or meters or +kilometers. If measured in kilometers, a standard linear regression +model with this predictor would probably give a much bigger +coefficient term, than if measured in millimeters. +This can clearly lead to problems in evaluating the cost/loss functions. +

    + +









    +

    Still thinking

    + +

    Keep in mind that when you transform your data set before training a model, the same transformation needs to be done +on your eventual new data set before making a prediction. If we translate this into a Python code, it would could be implemented as follows +

    + + + +
    +
    +
    +
    +
    +
    #Model training, we compute the mean value of y and X
    +y_train_mean = np.mean(y_train)
    +X_train_mean = np.mean(X_train,axis=0)
    +X_train = X_train - X_train_mean
    +y_train = y_train - y_train_mean
    +
    +# The we fit our model with the training data
    +trained_model = some_model.fit(X_train,y_train)
    +
    +
    +#Model prediction, we need also to transform our data set used for the prediction.
    +X_test = X_test - X_train_mean #Use mean from training data
    +y_pred = trained_model(X_test)
    +y_pred = y_pred + y_train_mean
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    + + +









    +

    What does centering (subtracting the mean values) mean mathematically?

    + +

    Let us try to understand what this may imply mathematically when we +subtract the mean values, also known as zero centering. For +simplicity, we will focus on ordinary regression, as done in the above example. +

    + +

    The cost/loss function for regression is

    +$$ +C(\beta_0, \beta_1, ... , \beta_{p-1}) = \frac{1}{n}\sum_{i=0}^{n} \left(y_i - \beta_0 - \sum_{j=1}^{p-1} X_{ij}\beta_j\right)^2,. +$$ + +

    Recall also that we use the squared value since this leads to an increase of the penalty for higher differences between predicted and output/target values.

    + +

    What we have done is to single out the \( \beta_0 \) term in the definition of the mean squared error (MSE). +The design matrix +\( X \) does in this case not contain any intercept column. +When we take the derivative with respect to \( \beta_0 \), we want the derivative to obey +

    +$$ +\frac{\partial C}{\partial \beta_j} = 0, +$$ + +

    for all \( j \). For \( \beta_0 \) we have

    + +$$ +\frac{\partial C}{\partial \beta_0} = -\frac{2}{n}\sum_{i=0}^{n-1} \left(y_i - \beta_0 - \sum_{j=1}^{p-1} X_{ij} \beta_j\right). +$$ + +

    Multiplying away the constant \( 2/n \), we obtain

    +$$ +\sum_{i=0}^{n-1} \beta_0 = \sum_{i=0}^{n-1}y_i - \sum_{i=0}^{n-1} \sum_{j=1}^{p-1} X_{ij} \beta_j. +$$ + + +









    +

    Further Manipulations

    + +

    Let us special first to the case where we have only two parameters \( \beta_0 \) and \( \beta_1 \). +Our result for \( \beta_0 \) simplifies then to +

    +$$ +n\beta_0 = \sum_{i=0}^{n-1}y_i - \sum_{i=0}^{n-1} X_{i1} \beta_1. +$$ + +

    We obtain then

    +$$ +\beta_0 = \frac{1}{n}\sum_{i=0}^{n-1}y_i - \beta_1\frac{1}{n}\sum_{i=0}^{n-1} X_{i1}. +$$ + +

    If we define

    +$$ +\mu_1=\frac{1}{n}\sum_{i=0}^{n-1} (X_{i1}, +$$ + +

    and if we define the mean value of the outputs as

    +$$ +\mu_y=\frac{1}{n}\sum_{i=0}^{n-1}y_i, +$$ + +

    we have

    +$$ +\beta_0 = \mu_y - \beta_1\mu_{1}. +$$ + +

    In the general case, that is we have more parameters than \( \beta_0 \) and \( \beta_1 \), we have

    +$$ +\beta_0 = \frac{1}{n}\sum_{i=0}^{n-1}y_i - \frac{1}{n}\sum_{i=0}^{n-1}\sum_{j=1}^{p-1} X_{ij}\beta_j. +$$ + +

    Replacing \( y_i \) with \( y_i - y_i - \overline{\boldsymbol{y}} \) and centering also our design matrix results in a cost function (in vector-matrix disguise)

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









    +

    Wrapping it up

    + +

    If we minimize with respect to \( \boldsymbol{\beta} \) we have then

    + +$$ +\hat{\boldsymbol{\beta}} = (\tilde{X}^T\tilde{X})^{-1}\tilde{X}^T\boldsymbol{\tilde{y}}, +$$ + +

    where \( \boldsymbol{\tilde{y}} = \boldsymbol{y} - \overline{\boldsymbol{y}} \) +and \( \tilde{X}_{ij} = X_{ij} - \frac{1}{n}\sum_{k=0}^{n-1}X_{kj} \). +

    + +

    For Ridge regression we need to add \( \lambda \boldsymbol{\beta}^T\boldsymbol{\beta} \) to the cost function and get then

    +$$ +\hat{\boldsymbol{\beta}} = (\tilde{X}^T\tilde{X} + \lambda I)^{-1}\tilde{X}^T\boldsymbol{\tilde{y}}. +$$ + +

    What does this mean? And why do we insist on all this? Let us look at some examples.

    + +









    +

    Linear Regression code, Intercept handling first

    + +

    This code shows a simple first-order fit to a data set using the above transformed data, where we consider the role of the intercept first, by either excluding it or including it (code example thanks to Øyvind Sigmundson Schøyen). Here our scaling of the data is done by subtracting the mean values only. +Note also that we do not split the data into training and test. +

    + + + +
    +
    +
    +
    +
    +
    import numpy as np
    +import matplotlib.pyplot as plt
    +
    +from sklearn.linear_model import LinearRegression
    +
    +
    +np.random.seed(2021)
    +
    +def MSE(y_data,y_model):
    +    n = np.size(y_model)
    +    return np.sum((y_data-y_model)**2)/n
    +
    +
    +def fit_beta(X, y):
    +    return np.linalg.pinv(X.T @ X) @ X.T @ y
    +
    +
    +true_beta = [2, 0.5, 3.7]
    +
    +x = np.linspace(0, 1, 11)
    +y = np.sum(
    +    np.asarray([x ** p * b for p, b in enumerate(true_beta)]), axis=0
    +) + 0.1 * np.random.normal(size=len(x))
    +
    +degree = 3
    +X = np.zeros((len(x), degree))
    +
    +# Include the intercept in the design matrix
    +for p in range(degree):
    +    X[:, p] = x ** p
    +
    +beta = fit_beta(X, y)
    +
    +# Intercept is included in the design matrix
    +skl = LinearRegression(fit_intercept=False).fit(X, y)
    +
    +print(f"True beta: {true_beta}")
    +print(f"Fitted beta: {beta}")
    +print(f"Sklearn fitted beta: {skl.coef_}")
    +ypredictOwn = X @ beta
    +ypredictSKL = skl.predict(X)
    +print(f"MSE with intercept column")
    +print(MSE(y,ypredictOwn))
    +print(f"MSE with intercept column from SKL")
    +print(MSE(y,ypredictSKL))
    +
    +
    +plt.figure()
    +plt.scatter(x, y, label="Data")
    +plt.plot(x, X @ beta, label="Fit")
    +plt.plot(x, skl.predict(X), label="Sklearn (fit_intercept=False)")
    +
    +
    +# Do not include the intercept in the design matrix
    +X = np.zeros((len(x), degree - 1))
    +
    +for p in range(degree - 1):
    +    X[:, p] = x ** (p + 1)
    +
    +# Intercept is not included in the design matrix
    +skl = LinearRegression(fit_intercept=True).fit(X, y)
    +
    +# Use centered values for X and y when computing coefficients
    +y_offset = np.average(y, axis=0)
    +X_offset = np.average(X, axis=0)
    +
    +beta = fit_beta(X - X_offset, y - y_offset)
    +intercept = np.mean(y_offset - X_offset @ beta)
    +
    +print(f"Manual intercept: {intercept}")
    +print(f"Fitted beta (wiothout intercept): {beta}")
    +print(f"Sklearn intercept: {skl.intercept_}")
    +print(f"Sklearn fitted beta (without intercept): {skl.coef_}")
    +ypredictOwn = X @ beta
    +ypredictSKL = skl.predict(X)
    +print(f"MSE with Manual intercept")
    +print(MSE(y,ypredictOwn+intercept))
    +print(f"MSE with Sklearn intercept")
    +print(MSE(y,ypredictSKL))
    +
    +plt.plot(x, X @ beta + intercept, "--", label="Fit (manual intercept)")
    +plt.plot(x, skl.predict(X), "--", label="Sklearn (fit_intercept=True)")
    +plt.grid()
    +plt.legend()
    +
    +plt.show()
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    + +

    The intercept is the value of our output/target variable +when all our features are zero and our function crosses the \( y \)-axis (for a one-dimensional case). +

    + +

    Printing the MSE, we see first that both methods give the same MSE, as +they should. However, when we move to for example Ridge regression, +the way we treat the intercept may give a larger or smaller MSE, +meaning that the MSE can be penalized by the value of the +intercept. Not including the intercept in the fit, means that the +regularization term does not include \( \beta_0 \). For different values +of \( \lambda \), this may lead to differeing MSE values. +

    + +

    To remind the reader, the regularization term, with the intercept in Ridge regression is given by

    +$$ +\lambda \vert\vert \boldsymbol{\beta} \vert\vert_2^2 = \lambda \sum_{j=0}^{p-1}\beta_j^2, +$$ + +

    but when we take out the intercept, this equation becomes

    +$$ +\lambda \vert\vert \boldsymbol{\beta} \vert\vert_2^2 = \lambda \sum_{j=1}^{p-1}\beta_j^2. +$$ + +

    For Lasso regression we have

    +$$ +\lambda \vert\vert \boldsymbol{\beta} \vert\vert_1 = \lambda \sum_{j=1}^{p-1}\vert\beta_j\vert. +$$ + +

    It means that, when scaling the design matrix and the outputs/targets, by subtracting the mean values, we have an optimization problem which is not penalized by the intercept. The MSE value can then be smaller since it focuses only on the remaining quantities. If we however bring back the intercept, we will get an MSE which then contains the intercept. This becomes more important when we discuss Ridge and Lasso regression next week.

    +

    The Boston housing data example

    @@ -1603,404 +2308,6 @@ plt.show()
    -









    -

    Reducing the number of degrees of freedom, overarching view

    -
    - -

    - -

    Many Machine Learning problems involve thousands or even millions of -features for each training instance. Not only does this make training -extremely slow, it can also make it much harder to find a good -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. -

    - -

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

    -
    - - -









    -

    Preprocessing our data

    -
    - -

    - -

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

    - -

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

    -
    - - -









    -

    Functionality in Scikit-Learn

    - -

    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 -

    - -









    -

    More preprocessing

    - -
    - -

    -

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

    -
    - - -









    -

    Frequently used scaling functions

    - -

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

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

    - -









    -

    Example of own Standard 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. -

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

    - -









    -

    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 -

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

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

    - -









    -

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

    - -

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









    -

    More preprocessing examples, Franke function and regression

    - - - -
    -
    -
    -
    -
    -
    # 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
    -
    -# Where to save the figures and data files
    -PROJECT_ROOT_DIR = "Results"
    -FIGURE_ID = "Results/FigureFiles"
    -DATA_ID = "DataFiles/"
    -
    -if not os.path.exists(PROJECT_ROOT_DIR):
    -    os.mkdir(PROJECT_ROOT_DIR)
    -
    -if not os.path.exists(FIGURE_ID):
    -    os.makedirs(FIGURE_ID)
    -
    -if not os.path.exists(DATA_ID):
    -    os.makedirs(DATA_ID)
    -
    -def image_path(fig_id):
    -    return os.path.join(FIGURE_ID, fig_id)
    -
    -def data_path(dat_id):
    -    return os.path.join(DATA_ID, dat_id)
    -
    -def save_fig(fig_id):
    -    plt.savefig(image_path(fig_id) + ".png", format='png')
    -
    -
    -def 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)))
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    - -









    Material for lecture Thursday, August 31

    @@ -3301,597 +3608,6 @@ $$

    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.

    -









    -

    Exercises for week 35

    - -

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

    - - -

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

    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 -

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

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

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

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

    - - -

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

    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}. -$$ - - -
    © 1999-2023, Morten Hjorth-Jensen. Released under CC Attribution-NonCommercial 4.0 license diff --git a/doc/pub/week35/ipynb/ipynb-week35-src.tar.gz b/doc/pub/week35/ipynb/ipynb-week35-src.tar.gz index 39ebf4d4cd348bf3546429227e22755e552a4f2c..7dca4cfff0198e36bcc7ae2d7dfea577bbaa3c84 100644 GIT binary patch delta 122 zcmV-=0EPd+0l)zVABzY8VKeNJ2Ty8^NlZDTKxoWYJOHxXNiUss!VIT0)ftsV^=@t$ zE6Wdi=2zgEf8tn43)_9~Dy=|ihq=}@+z{)SN3!iz4uwWLw!q-ElLkSk9z;<{C$$on cur>N*L}R1y*UxyK=Xqay0BY=`4FCuL0G)R>B>(^b delta 122 zcmV-=0EPd+0l)zVABzY8fxGLG2Ty8Ur7=$k1wvyUvjE6)C%tsm2{WA1RA*Ec)w{W2 ztSmq5nO}it{)uBHEo}F_tF!{89p+lsa6_zP9?7;>ITRZ0*aCysP8tNEdJsh+ozzNP c!q(`M5si()Uq9n{p67k-0W@lm%>W1h0A?OFQUCw| diff --git a/doc/pub/week35/ipynb/week35.ipynb b/doc/pub/week35/ipynb/week35.ipynb index e9102e764..2e295a77c 100644 --- a/doc/pub/week35/ipynb/week35.ipynb +++ b/doc/pub/week35/ipynb/week35.ipynb @@ -2,7 +2,7 @@ "cells": [ { "cell_type": "markdown", - "id": "c26c8c40", + "id": "48814d17", "metadata": { "editable": true }, @@ -14,7 +14,7 @@ }, { "cell_type": "markdown", - "id": "f160cea3", + "id": "bc61e6c3", "metadata": { "editable": true }, @@ -27,7 +27,7 @@ }, { "cell_type": "markdown", - "id": "a6ee75d2", + "id": "1de6c7de", "metadata": { "editable": true }, @@ -42,14 +42,14 @@ "\n", "3. Discussion on how to prepare data and examples of applications of linear regression\n", "\n", - "4. Mathematical interpretations of linear regression\n", + "4. Material for the lecture on Thursday: Mathematical interpretations of linear regression\n", "\n", - "5. Ridge and Lasso regression and Singular Value Decomposition" + "5. Thursday: Ridge and Lasso regression and Singular Value Decomposition" ] }, { "cell_type": "markdown", - "id": "0259f6b6", + "id": "540f9b28", "metadata": { "editable": true }, @@ -63,7 +63,7 @@ }, { "cell_type": "markdown", - "id": "63ede91c", + "id": "8fa69b6b", "metadata": { "editable": true }, @@ -97,7 +97,7 @@ }, { "cell_type": "markdown", - "id": "e96aa4f7", + "id": "75116bcf", "metadata": { "editable": true }, @@ -107,13 +107,13 @@ "Our data which we want to apply a machine learning method on, consist\n", "of a set of inputs $\\boldsymbol{x}^T=[x_0,x_1,x_2,\\dots,x_{n-1}]$ and the\n", "outputs we want to model $\\boldsymbol{x}^T=[y_0,y_1,y_2,\\dots,y_{n-1}]$.\n", - "We assumed also that the output data can be represented for a regression case by continuous function $f$\n", + "We assume that the output data can be represented (for a regression case) by a continuous function $f$\n", "through" ] }, { "cell_type": "markdown", - "id": "1988e01f", + "id": "8cea2508", "metadata": { "editable": true }, @@ -125,14 +125,36 @@ }, { "cell_type": "markdown", - "id": "b9ba24fe", + "id": "f1cff657", "metadata": { "editable": true }, "source": [ - "where $\\epsilon_i$ represents some noise which is normally assumed to\n", + "or in general" + ] + }, + { + "cell_type": "markdown", + "id": "bca208b6", + "metadata": { + "editable": true + }, + "source": [ + "$$\n", + "\\boldsymbol{y}=f(\\boldsymbol{x})+\\boldsymbol{\\epsilon},\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "7e1e2c71", + "metadata": { + "editable": true + }, + "source": [ + "where $\\boldsymbol{\\epsilon}$ represents some noise which is normally assumed to\n", "be distributed via a normal probability distribution with zero mean\n", - "value and a variance $\\sigma_i^$.\n", + "value and a variance $\\sigma^2$.\n", "\n", "In linear regression we approximate the unknown function with another\n", "continuous function $\\tilde{\\boldsymbol{y}}(\\boldsymbol{x})$ which depends linearly on\n", @@ -146,7 +168,7 @@ }, { "cell_type": "markdown", - "id": "19678800", + "id": "aa01ecd2", "metadata": { "editable": true }, @@ -158,20 +180,20 @@ }, { "cell_type": "markdown", - "id": "7e7fe0ca", + "id": "ef34b811", "metadata": { "editable": true }, "source": [ "and in order to find the optimal parameters $\\beta_i$ we defined a function which\n", "gives a measure of the spread between the values $y_i$ (which\n", - "represent output values we want to reproduce) and the parametrized\n", + "represent the output values we want to reproduce) and the parametrized\n", "values $\\tilde{y}_i$, namely the so-called cost/loss function." ] }, { "cell_type": "markdown", - "id": "4318ca6d", + "id": "2c121448", "metadata": { "editable": true }, @@ -183,7 +205,7 @@ }, { "cell_type": "markdown", - "id": "23268b5a", + "id": "6001c152", "metadata": { "editable": true }, @@ -195,7 +217,7 @@ }, { "cell_type": "markdown", - "id": "0da1ef7b", + "id": "3b3e380d", "metadata": { "editable": true }, @@ -205,7 +227,7 @@ }, { "cell_type": "markdown", - "id": "6ac95a92", + "id": "b227c100", "metadata": { "editable": true }, @@ -217,7 +239,7 @@ }, { "cell_type": "markdown", - "id": "8e8bfb04", + "id": "0eea8ce0", "metadata": { "editable": true }, @@ -230,7 +252,7 @@ }, { "cell_type": "markdown", - "id": "10a32fc6", + "id": "77959af4", "metadata": { "editable": true }, @@ -242,7 +264,7 @@ }, { "cell_type": "markdown", - "id": "4622de9f", + "id": "32483693", "metadata": { "editable": true }, @@ -252,7 +274,7 @@ }, { "cell_type": "markdown", - "id": "53060ef6", + "id": "a471dd4d", "metadata": { "editable": true }, @@ -264,7 +286,7 @@ }, { "cell_type": "markdown", - "id": "7f2bfa26", + "id": "964a050a", "metadata": { "editable": true }, @@ -276,18 +298,18 @@ }, { "cell_type": "markdown", - "id": "45c4ecde", + "id": "87f8eda7", "metadata": { "editable": true }, "source": [ "can be linked to the variance of the quantity $y_i$ if we interpret the latter as the mean value. \n", - "When linking (see the discussion below) with the maximum likelihood approach below, we will indeed interpret $y_i$ as a mean value" + "When linking (see the discussions next week) with the maximum likelihood approach below, we will indeed interpret $y_i$ as a mean value" ] }, { "cell_type": "markdown", - "id": "0e9fd375", + "id": "71f3d982", "metadata": { "editable": true }, @@ -299,7 +321,7 @@ }, { "cell_type": "markdown", - "id": "d3ebdd38", + "id": "f20e60e4", "metadata": { "editable": true }, @@ -318,7 +340,7 @@ }, { "cell_type": "markdown", - "id": "83557125", + "id": "e82ee421", "metadata": { "editable": true }, @@ -331,7 +353,7 @@ }, { "cell_type": "markdown", - "id": "1b709c34", + "id": "29dafa20", "metadata": { "editable": true }, @@ -341,7 +363,7 @@ }, { "cell_type": "markdown", - "id": "7bc9d5d6", + "id": "865b2f5d", "metadata": { "editable": true }, @@ -353,7 +375,7 @@ }, { "cell_type": "markdown", - "id": "d3837db0", + "id": "d2f7d6c6", "metadata": { "editable": true }, @@ -363,7 +385,7 @@ }, { "cell_type": "markdown", - "id": "8778f012", + "id": "45903ab2", "metadata": { "editable": true }, @@ -375,17 +397,17 @@ }, { "cell_type": "markdown", - "id": "8dd26344", + "id": "d11e2e5c", "metadata": { "editable": true }, "source": [ - "or in a matrix-vector form as" + "or in a matrix-vector form as (multiplying away the factor $-2/n$)" ] }, { "cell_type": "markdown", - "id": "75d44780", + "id": "0ebbd61d", "metadata": { "editable": true }, @@ -397,7 +419,7 @@ }, { "cell_type": "markdown", - "id": "b46af42d", + "id": "88529a18", "metadata": { "editable": true }, @@ -408,7 +430,7 @@ }, { "cell_type": "markdown", - "id": "c8e19d18", + "id": "713ac93a", "metadata": { "editable": true }, @@ -420,7 +442,7 @@ }, { "cell_type": "markdown", - "id": "cb4a4ad0", + "id": "75776840", "metadata": { "editable": true }, @@ -430,7 +452,7 @@ }, { "cell_type": "markdown", - "id": "547cc922", + "id": "36f9ea8c", "metadata": { "editable": true }, @@ -442,7 +464,7 @@ }, { "cell_type": "markdown", - "id": "5441cd18", + "id": "9390b294", "metadata": { "editable": true }, @@ -452,7 +474,7 @@ }, { "cell_type": "markdown", - "id": "a1174ef5", + "id": "30c81789", "metadata": { "editable": true }, @@ -464,7 +486,7 @@ }, { "cell_type": "markdown", - "id": "b95b2e19", + "id": "c035d652", "metadata": { "editable": true }, @@ -485,7 +507,7 @@ }, { "cell_type": "markdown", - "id": "1039bd58", + "id": "ff3ad5f2", "metadata": { "editable": true }, @@ -512,7 +534,7 @@ }, { "cell_type": "markdown", - "id": "36cfd6de", + "id": "cb65be24", "metadata": { "editable": true }, @@ -524,7 +546,7 @@ }, { "cell_type": "markdown", - "id": "cc431a16", + "id": "5bb8744e", "metadata": { "editable": true }, @@ -536,7 +558,7 @@ }, { "cell_type": "markdown", - "id": "2c85f572", + "id": "1e452b6a", "metadata": { "editable": true }, @@ -552,7 +574,7 @@ }, { "cell_type": "markdown", - "id": "4187e999", + "id": "1c7dfcc4", "metadata": { "editable": true }, @@ -570,7 +592,7 @@ }, { "cell_type": "markdown", - "id": "94ce876e", + "id": "57bb103b", "metadata": { "editable": true }, @@ -582,7 +604,7 @@ }, { "cell_type": "markdown", - "id": "5ed61186", + "id": "e097d436", "metadata": { "editable": true }, @@ -594,7 +616,7 @@ }, { "cell_type": "markdown", - "id": "d063159b", + "id": "9624a15b", "metadata": { "editable": true }, @@ -605,7 +627,7 @@ }, { "cell_type": "markdown", - "id": "d9c68473", + "id": "2fe00b2d", "metadata": { "editable": true }, @@ -617,7 +639,7 @@ }, { "cell_type": "markdown", - "id": "92947358", + "id": "2cfbed2f", "metadata": { "editable": true }, @@ -627,7 +649,7 @@ }, { "cell_type": "markdown", - "id": "5c3a7158", + "id": "7f4c4c29", "metadata": { "editable": true }, @@ -639,7 +661,7 @@ }, { "cell_type": "markdown", - "id": "1b8c774e", + "id": "173f1116", "metadata": { "editable": true }, @@ -653,7 +675,7 @@ }, { "cell_type": "markdown", - "id": "ef2f0f0e", + "id": "0429caf6", "metadata": { "editable": true }, @@ -665,7 +687,7 @@ }, { "cell_type": "markdown", - "id": "ab8a6ea5", + "id": "3004627d", "metadata": { "editable": true }, @@ -677,7 +699,7 @@ }, { "cell_type": "markdown", - "id": "ca4e3713", + "id": "9be48075", "metadata": { "editable": true }, @@ -689,7 +711,7 @@ }, { "cell_type": "markdown", - "id": "e471aa6f", + "id": "774d2b3c", "metadata": { "editable": true }, @@ -699,7 +721,7 @@ }, { "cell_type": "markdown", - "id": "cd03a03d", + "id": "6f1d157e", "metadata": { "editable": true }, @@ -711,7 +733,7 @@ }, { "cell_type": "markdown", - "id": "09d684ce", + "id": "c134c6c5", "metadata": { "editable": true }, @@ -721,7 +743,7 @@ }, { "cell_type": "markdown", - "id": "27730224", + "id": "5c70ca39", "metadata": { "editable": true }, @@ -733,7 +755,7 @@ }, { "cell_type": "markdown", - "id": "899ccea9", + "id": "d75344c2", "metadata": { "editable": true }, @@ -747,7 +769,7 @@ }, { "cell_type": "markdown", - "id": "bef1e7ca", + "id": "4135d0c7", "metadata": { "editable": true }, @@ -759,7 +781,7 @@ }, { "cell_type": "markdown", - "id": "7d9c29b9", + "id": "c99dcd9d", "metadata": { "editable": true }, @@ -771,7 +793,7 @@ }, { "cell_type": "markdown", - "id": "2e416557", + "id": "f1cdd616", "metadata": { "editable": true }, @@ -783,7 +805,7 @@ }, { "cell_type": "markdown", - "id": "2352bb20", + "id": "8eaa500d", "metadata": { "editable": true }, @@ -793,7 +815,7 @@ }, { "cell_type": "markdown", - "id": "35c4c4eb", + "id": "5cbe436e", "metadata": { "editable": true }, @@ -805,7 +827,7 @@ }, { "cell_type": "markdown", - "id": "61b51a76", + "id": "9f60d600", "metadata": { "editable": true }, @@ -815,7 +837,7 @@ }, { "cell_type": "markdown", - "id": "12b4948e", + "id": "7207d303", "metadata": { "editable": true }, @@ -827,7 +849,7 @@ }, { "cell_type": "markdown", - "id": "7b395cb8", + "id": "d02f7e0b", "metadata": { "editable": true }, @@ -837,7 +859,7 @@ }, { "cell_type": "markdown", - "id": "9cc111b0", + "id": "3630e104", "metadata": { "editable": true }, @@ -849,7 +871,7 @@ }, { "cell_type": "markdown", - "id": "ac28510a", + "id": "54bf967b", "metadata": { "editable": true }, @@ -861,7 +883,7 @@ }, { "cell_type": "markdown", - "id": "12e2f6df", + "id": "9120827b", "metadata": { "editable": true }, @@ -873,7 +895,7 @@ }, { "cell_type": "markdown", - "id": "7b9f0de2", + "id": "3eea746b", "metadata": { "editable": true }, @@ -888,7 +910,7 @@ }, { "cell_type": "markdown", - "id": "00ac6e0d", + "id": "d4283866", "metadata": { "editable": true }, @@ -900,7 +922,7 @@ }, { "cell_type": "markdown", - "id": "d1e16191", + "id": "a40bf496", "metadata": { "editable": true }, @@ -910,7 +932,7 @@ }, { "cell_type": "markdown", - "id": "ffca159e", + "id": "108364a8", "metadata": { "editable": true }, @@ -922,7 +944,7 @@ }, { "cell_type": "markdown", - "id": "9fb6265f", + "id": "225fdf02", "metadata": { "editable": true }, @@ -932,7 +954,7 @@ }, { "cell_type": "markdown", - "id": "11663b09", + "id": "c254f629", "metadata": { "editable": true }, @@ -944,7 +966,7 @@ }, { "cell_type": "markdown", - "id": "986904ba", + "id": "e00dbb5c", "metadata": { "editable": true }, @@ -954,7 +976,7 @@ }, { "cell_type": "markdown", - "id": "fefb5f19", + "id": "d6ae171e", "metadata": { "editable": true }, @@ -966,7 +988,7 @@ }, { "cell_type": "markdown", - "id": "19c58d14", + "id": "64090d25", "metadata": { "editable": true }, @@ -978,7 +1000,7 @@ }, { "cell_type": "markdown", - "id": "372a3ffa", + "id": "ca920a83", "metadata": { "editable": true }, @@ -990,7 +1012,7 @@ }, { "cell_type": "markdown", - "id": "ef420100", + "id": "6cf46fcb", "metadata": { "editable": true }, @@ -1000,7 +1022,7 @@ }, { "cell_type": "markdown", - "id": "346a0a55", + "id": "d7f69bce", "metadata": { "editable": true }, @@ -1012,7 +1034,7 @@ }, { "cell_type": "markdown", - "id": "19d9aaa8", + "id": "e96b7e86", "metadata": { "editable": true }, @@ -1025,7 +1047,7 @@ }, { "cell_type": "markdown", - "id": "36727d50", + "id": "d128efac", "metadata": { "editable": true }, @@ -1037,7 +1059,7 @@ }, { "cell_type": "markdown", - "id": "90f9247c", + "id": "7efcf864", "metadata": { "editable": true }, @@ -1047,7 +1069,7 @@ }, { "cell_type": "markdown", - "id": "1e12cafd", + "id": "2d31fe86", "metadata": { "editable": true }, @@ -1059,7 +1081,7 @@ }, { "cell_type": "markdown", - "id": "883b71ee", + "id": "de727a1f", "metadata": { "editable": true }, @@ -1069,7 +1091,7 @@ }, { "cell_type": "markdown", - "id": "2d089f75", + "id": "3ae45138", "metadata": { "editable": true }, @@ -1081,7 +1103,7 @@ }, { "cell_type": "markdown", - "id": "e24f6588", + "id": "2ce6a086", "metadata": { "editable": true }, @@ -1091,7 +1113,7 @@ }, { "cell_type": "markdown", - "id": "5ba9309c", + "id": "168f47a1", "metadata": { "editable": true }, @@ -1103,7 +1125,7 @@ }, { "cell_type": "markdown", - "id": "46d74349", + "id": "46c9bef4", "metadata": { "editable": true }, @@ -1113,7 +1135,7 @@ }, { "cell_type": "markdown", - "id": "01fe33e5", + "id": "517fe316", "metadata": { "editable": true }, @@ -1125,7 +1147,7 @@ }, { "cell_type": "markdown", - "id": "8c2e23bd", + "id": "0eac480c", "metadata": { "editable": true }, @@ -1135,7 +1157,7 @@ }, { "cell_type": "markdown", - "id": "3e2cd8e4", + "id": "9f870277", "metadata": { "editable": true }, @@ -1147,7 +1169,7 @@ }, { "cell_type": "markdown", - "id": "f09d5105", + "id": "90d819f0", "metadata": { "editable": true }, @@ -1159,7 +1181,7 @@ }, { "cell_type": "markdown", - "id": "495aa3c8", + "id": "7c054d38", "metadata": { "editable": true }, @@ -1171,7 +1193,7 @@ }, { "cell_type": "markdown", - "id": "7ab4b562", + "id": "a74afd02", "metadata": { "editable": true }, @@ -1183,7 +1205,7 @@ }, { "cell_type": "markdown", - "id": "7acbceb4", + "id": "5daf72a9", "metadata": { "editable": true }, @@ -1195,15 +1217,15 @@ }, { "cell_type": "markdown", - "id": "2f3f523f", + "id": "b2cdc0f7", "metadata": { "editable": true }, "source": [ "## Meet the Hessian Matrix\n", "\n", - "A very important matrix we will meet again and again in Machine\n", - "Learning is the Hessian. It is given by the second derivative of the\n", + "A very important matrix we will meet again and again in machine\n", + "learning is the Hessian. It is given by the second derivative of the\n", "cost function with respect to the parameters $\\boldsymbol{\\beta}$. Using the above\n", "expression for derivatives of vectors and matrices, we find that the\n", "second derivative of the mean squared error as cost function is," @@ -1211,7 +1233,7 @@ }, { "cell_type": "markdown", - "id": "bdd69917", + "id": "3840002f", "metadata": { "editable": true }, @@ -1223,7 +1245,7 @@ }, { "cell_type": "markdown", - "id": "d1a5cb65", + "id": "fbb502ee", "metadata": { "editable": true }, @@ -1233,7 +1255,7 @@ }, { "cell_type": "markdown", - "id": "2faebd04", + "id": "94f74938", "metadata": { "editable": true }, @@ -1245,7 +1267,7 @@ }, { "cell_type": "markdown", - "id": "fc4d295d", + "id": "0c387c69", "metadata": { "editable": true }, @@ -1263,7 +1285,7 @@ }, { "cell_type": "markdown", - "id": "9ecc2ddd", + "id": "0d804211", "metadata": { "editable": true }, @@ -1275,7 +1297,7 @@ }, { "cell_type": "markdown", - "id": "77233b0a", + "id": "53d01ed8", "metadata": { "editable": true }, @@ -1287,7 +1309,7 @@ }, { "cell_type": "markdown", - "id": "ac6304bf", + "id": "4e460081", "metadata": { "editable": true }, @@ -1297,7 +1319,7 @@ }, { "cell_type": "markdown", - "id": "69e06d28", + "id": "076effdd", "metadata": { "editable": true }, @@ -1309,7 +1331,7 @@ }, { "cell_type": "markdown", - "id": "f0c09603", + "id": "31e4cff9", "metadata": { "editable": true }, @@ -1319,7 +1341,7 @@ }, { "cell_type": "markdown", - "id": "36ca02f1", + "id": "10f160dd", "metadata": { "editable": true }, @@ -1331,7 +1353,7 @@ }, { "cell_type": "markdown", - "id": "cf405b01", + "id": "06ad3ea3", "metadata": { "editable": true }, @@ -1341,12 +1363,12 @@ }, { "cell_type": "markdown", - "id": "b6f8243d", + "id": "a5f71548", "metadata": { "editable": true }, "source": [ - "## Examples relevant for the exercises\n", + "## Example relevant for the exercises\n", "\n", "In order to understand the relation among the predictors $p$, the set of data $n$ and the target (outcome, output etc) $\\boldsymbol{y}$,\n", "we condiser a simple polynomial fit.\n", @@ -1355,7 +1377,7 @@ }, { "cell_type": "markdown", - "id": "b672f320", + "id": "421b5969", "metadata": { "editable": true }, @@ -1367,36 +1389,31 @@ }, { "cell_type": "markdown", - "id": "541778f1", + "id": "382915d9", "metadata": { "editable": true }, "source": [ - "we have five predictors, that is the intercept $\\beta_0$and the other terms $\\beta_i$.\n", - "This gives $p=0,1,2,3,4$. Furthermore we have $n$ entries for each predictor. It means that our design matrix is a \n", - "$p\\times n$ matrix $\\boldsymbol{X}$.\n", - "\n", - "Here the predictors are based on a model we have made. A popular data set which is widely encountered in ML applications is the\n", - "so-called [credit card default data from Taiwan](https://www.sciencedirect.com/science/article/pii/S0957417407006719?via%3Dihub). The data set contains data on $n=30000$ credit card holders with predictors like gender, marital status, age, profession, education, etc. In total there are $24$ such predictors or attributes leading to a design matrix of dimensionality $24 \\times 30000$. This is however a classification problem and we will come back to it when we discuss Logistic Regression." + "we have five predictors/features. The first is the intercept $\\beta_0$. The other terms are $\\beta_i$ with $i=1,2,3,4$. Furthermore we have $n$ entries for each predictor. It means that our design matrix is a \n", + "$p\\times n$ matrix $\\boldsymbol{X}$." ] }, { "cell_type": "markdown", - "id": "fda1bb2d", + "id": "053fc460", "metadata": { "editable": true }, "source": [ "## Own code for Ordinary Least Squares\n", "\n", - "It is rather straightforward to implement the matrix inversion and obtain the parameters $\\boldsymbol{\\beta}$. After having defined the matrix $\\boldsymbol{X}$ we simply need to \n", - "write" + "It is rather straightforward to implement the matrix inversion and obtain the parameters $\\boldsymbol{\\beta}$. After having defined the matrix $\\boldsymbol{X}$ and the outputs $\\boldsymbol{y}$ we have" ] }, { "cell_type": "code", "execution_count": 1, - "id": "6847e932", + "id": "f4596688", "metadata": { "collapsed": false, "editable": true @@ -1404,14 +1421,14 @@ "outputs": [], "source": [ "# matrix inversion to find beta\n", - "beta = np.linalg.inv(X.T.dot(X)).dot(X.T).dot(Energies)\n", + "beta = (np.linalg.inv(X.T @ X) @ X.T ) @ y\n", "# and then make the prediction\n", "ytilde = X @ beta" ] }, { "cell_type": "markdown", - "id": "3338d06b", + "id": "65c4e9b3", "metadata": { "editable": true }, @@ -1422,7 +1439,7 @@ { "cell_type": "code", "execution_count": 2, - "id": "99180a65", + "id": "8ef47e51", "metadata": { "collapsed": false, "editable": true @@ -1435,41 +1452,7 @@ }, { "cell_type": "markdown", - "id": "de333405", - "metadata": { - "editable": true - }, - "source": [ - "And finally we plot our fit with and compare with data" - ] - }, - { - "cell_type": "code", - "execution_count": 3, - "id": "aa07361c", - "metadata": { - "collapsed": false, - "editable": true - }, - "outputs": [], - "source": [ - "Masses['Eapprox'] = ytilde\n", - "# Generate a plot comparing the experimental with the fitted values values.\n", - "fig, ax = plt.subplots()\n", - "ax.set_xlabel(r'$A = N + Z$')\n", - "ax.set_ylabel(r'$E_\\mathrm{bind}\\,/\\mathrm{MeV}$')\n", - "ax.plot(Masses['A'], Masses['Ebinding'], alpha=0.7, lw=2,\n", - " label='Ame2016')\n", - "ax.plot(Masses['A'], Masses['Eapprox'], alpha=0.7, lw=2, c='m',\n", - " label='Fit')\n", - "ax.legend()\n", - "save_fig(\"Masses2016OLS\")\n", - "plt.show()" - ] - }, - { - "cell_type": "markdown", - "id": "d4790c93", + "id": "f55e615f", "metadata": { "editable": true }, @@ -1482,8 +1465,8 @@ }, { "cell_type": "code", - "execution_count": 4, - "id": "10f7cefc", + "execution_count": 3, + "id": "53b41f14", "metadata": { "collapsed": false, "editable": true @@ -1496,7 +1479,7 @@ }, { "cell_type": "markdown", - "id": "07f12d06", + "id": "a880dd98", "metadata": { "editable": true }, @@ -1506,8 +1489,8 @@ }, { "cell_type": "code", - "execution_count": 5, - "id": "fbfe97a6", + "execution_count": 4, + "id": "a98298a6", "metadata": { "collapsed": false, "editable": true @@ -1519,7 +1502,7 @@ }, { "cell_type": "markdown", - "id": "ce0c901c", + "id": "ea20f812", "metadata": { "editable": true }, @@ -1529,8 +1512,8 @@ }, { "cell_type": "code", - "execution_count": 6, - "id": "078a14ba", + "execution_count": 5, + "id": "b0c16cad", "metadata": { "collapsed": false, "editable": true @@ -1546,7 +1529,7 @@ }, { "cell_type": "markdown", - "id": "9dcfd726", + "id": "575e1949", "metadata": { "editable": true }, @@ -1556,8 +1539,8 @@ }, { "cell_type": "code", - "execution_count": 7, - "id": "a938844d", + "execution_count": 6, + "id": "69dc8db3", "metadata": { "collapsed": false, "editable": true @@ -1571,7 +1554,7 @@ }, { "cell_type": "markdown", - "id": "3aeb174b", + "id": "e619e325", "metadata": { "editable": true }, @@ -1592,18 +1575,18 @@ }, { "cell_type": "markdown", - "id": "c9bfe7fd", + "id": "61132ee3", "metadata": { "editable": true }, "source": [ - "## Examples" + "## The complete code with a simple data set" ] }, { "cell_type": "code", - "execution_count": 8, - "id": "d3463b82", + "execution_count": 7, + "id": "a5f35f01", "metadata": { "collapsed": false, "editable": true @@ -1629,11 +1612,13 @@ "y = 2.0+5*x*x+0.1*np.random.randn(100)\n", "\n", "\n", - "# The design matrix now as function of a given polynomial\n", - "X = np.zeros((len(x),3))\n", + "# The design matrix now as function of a fourth-order polynomial\n", + "X = np.zeros((len(x),5))\n", "X[:,0] = 1.0\n", "X[:,1] = x\n", "X[:,2] = x**2\n", + "X[:,3] = x**3\n", + "X[:,4] = x**4\n", "# We split the data in test and training data\n", "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2)\n", "# matrix inversion to find beta\n", @@ -1654,7 +1639,7 @@ }, { "cell_type": "markdown", - "id": "97428a40", + "id": "7f317a8b", "metadata": { "editable": true }, @@ -1664,8 +1649,8 @@ }, { "cell_type": "code", - "execution_count": 9, - "id": "47b779b9", + "execution_count": 8, + "id": "e9687fbf", "metadata": { "collapsed": false, "editable": true @@ -1690,7 +1675,7 @@ }, { "cell_type": "markdown", - "id": "00bbe01d", + "id": "bd7417f3", "metadata": { "editable": true }, @@ -1702,371 +1687,7 @@ }, { "cell_type": "markdown", - "id": "3c52f6b0", - "metadata": { - "editable": true - }, - "source": [ - "## The Boston housing data example\n", - "\n", - "The Boston housing \n", - "data set was originally a part of UCI Machine Learning Repository\n", - "and has been removed now. The data set is now included in **Scikit-Learn**'s \n", - "library. There are 506 samples and 13 feature (predictor) variables\n", - "in this data set. The objective is to predict the value of prices of\n", - "the house using the features (predictors) listed here.\n", - "\n", - "The features/predictors are\n", - "1. CRIM: Per capita crime rate by town\n", - "\n", - "2. ZN: Proportion of residential land zoned for lots over 25000 square feet\n", - "\n", - "3. INDUS: Proportion of non-retail business acres per town\n", - "\n", - "4. CHAS: Charles River dummy variable (= 1 if tract bounds river; 0 otherwise)\n", - "\n", - "5. NOX: Nitric oxide concentration (parts per 10 million)\n", - "\n", - "6. RM: Average number of rooms per dwelling\n", - "\n", - "7. AGE: Proportion of owner-occupied units built prior to 1940\n", - "\n", - "8. DIS: Weighted distances to five Boston employment centers\n", - "\n", - "9. RAD: Index of accessibility to radial highways\n", - "\n", - "10. TAX: Full-value property tax rate per USD10000\n", - "\n", - "11. B: $1000(Bk - 0.63)^2$, where $Bk$ is the proportion of [people of African American descent] by town\n", - "\n", - "12. LSTAT: Percentage of lower status of the population\n", - "\n", - "13. MEDV: Median value of owner-occupied homes in USD 1000s" - ] - }, - { - "cell_type": "markdown", - "id": "b760d8fd", - "metadata": { - "editable": true - }, - "source": [ - "## Housing data, the code\n", - "We start by importing the libraries" - ] - }, - { - "cell_type": "code", - "execution_count": 10, - "id": "12780605", - "metadata": { - "collapsed": false, - "editable": true - }, - "outputs": [], - "source": [ - "import numpy as np\n", - "import matplotlib.pyplot as plt \n", - "\n", - "import pandas as pd \n", - "import seaborn as sns" - ] - }, - { - "cell_type": "markdown", - "id": "622f54c4", - "metadata": { - "editable": true - }, - "source": [ - "and load the Boston Housing DataSet from **Scikit-Learn**" - ] - }, - { - "cell_type": "code", - "execution_count": 11, - "id": "d2674c8f", - "metadata": { - "collapsed": false, - "editable": true - }, - "outputs": [], - "source": [ - "from sklearn.datasets import load_boston\n", - "\n", - "boston_dataset = load_boston()\n", - "\n", - "# boston_dataset is a dictionary\n", - "# let's check what it contains\n", - "boston_dataset.keys()" - ] - }, - { - "cell_type": "markdown", - "id": "235049ba", - "metadata": { - "editable": true - }, - "source": [ - "Then we invoke Pandas" - ] - }, - { - "cell_type": "code", - "execution_count": 12, - "id": "cc50f39a", - "metadata": { - "collapsed": false, - "editable": true - }, - "outputs": [], - "source": [ - "boston = pd.DataFrame(boston_dataset.data, columns=boston_dataset.feature_names)\n", - "boston.head()\n", - "boston['MEDV'] = boston_dataset.target" - ] - }, - { - "cell_type": "markdown", - "id": "93424e35", - "metadata": { - "editable": true - }, - "source": [ - "and preprocess the data" - ] - }, - { - "cell_type": "code", - "execution_count": 13, - "id": "b19e3cc5", - "metadata": { - "collapsed": false, - "editable": true - }, - "outputs": [], - "source": [ - "# check for missing values in all the columns\n", - "boston.isnull().sum()" - ] - }, - { - "cell_type": "markdown", - "id": "8b4d12d6", - "metadata": { - "editable": true - }, - "source": [ - "We can then visualize the data" - ] - }, - { - "cell_type": "code", - "execution_count": 14, - "id": "dad32927", - "metadata": { - "collapsed": false, - "editable": true - }, - "outputs": [], - "source": [ - "# set the size of the figure\n", - "sns.set(rc={'figure.figsize':(11.7,8.27)})\n", - "\n", - "# plot a histogram showing the distribution of the target values\n", - "sns.distplot(boston['MEDV'], bins=30)\n", - "plt.show()" - ] - }, - { - "cell_type": "markdown", - "id": "1996eb45", - "metadata": { - "editable": true - }, - "source": [ - "It is now useful to look at the correlation matrix" - ] - }, - { - "cell_type": "code", - "execution_count": 15, - "id": "e8d428f5", - "metadata": { - "collapsed": false, - "editable": true - }, - "outputs": [], - "source": [ - "# compute the pair wise correlation for all columns \n", - "correlation_matrix = boston.corr().round(2)\n", - "# use the heatmap function from seaborn to plot the correlation matrix\n", - "# annot = True to print the values inside the square\n", - "sns.heatmap(data=correlation_matrix, annot=True)" - ] - }, - { - "cell_type": "markdown", - "id": "1b880255", - "metadata": { - "editable": true - }, - "source": [ - "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" - ] - }, - { - "cell_type": "code", - "execution_count": 16, - "id": "7c79dcb1", - "metadata": { - "collapsed": false, - "editable": true - }, - "outputs": [], - "source": [ - "plt.figure(figsize=(20, 5))\n", - "\n", - "features = ['LSTAT', 'RM']\n", - "target = boston['MEDV']\n", - "\n", - "for i, col in enumerate(features):\n", - " plt.subplot(1, len(features) , i+1)\n", - " x = boston[col]\n", - " y = target\n", - " plt.scatter(x, y, marker='o')\n", - " plt.title(col)\n", - " plt.xlabel(col)\n", - " plt.ylabel('MEDV')" - ] - }, - { - "cell_type": "markdown", - "id": "c144b36b", - "metadata": { - "editable": true - }, - "source": [ - "Now we start training our model" - ] - }, - { - "cell_type": "code", - "execution_count": 17, - "id": "fe1d83f1", - "metadata": { - "collapsed": false, - "editable": true - }, - "outputs": [], - "source": [ - "X = pd.DataFrame(np.c_[boston['LSTAT'], boston['RM']], columns = ['LSTAT','RM'])\n", - "Y = boston['MEDV']" - ] - }, - { - "cell_type": "markdown", - "id": "705de21c", - "metadata": { - "editable": true - }, - "source": [ - "We split the data into training and test sets" - ] - }, - { - "cell_type": "code", - "execution_count": 18, - "id": "fb11b77d", - "metadata": { - "collapsed": false, - "editable": true - }, - "outputs": [], - "source": [ - "from sklearn.model_selection import train_test_split\n", - "\n", - "# splits the training and test data set in 80% : 20%\n", - "# assign random_state to any value.This ensures consistency.\n", - "X_train, X_test, Y_train, Y_test = train_test_split(X, Y, test_size = 0.2, random_state=5)\n", - "print(X_train.shape)\n", - "print(X_test.shape)\n", - "print(Y_train.shape)\n", - "print(Y_test.shape)" - ] - }, - { - "cell_type": "markdown", - "id": "450c012c", - "metadata": { - "editable": true - }, - "source": [ - "Then we use the linear regression functionality from **Scikit-Learn**" - ] - }, - { - "cell_type": "code", - "execution_count": 19, - "id": "66e0c54a", - "metadata": { - "collapsed": false, - "editable": true - }, - "outputs": [], - "source": [ - "from sklearn.linear_model import LinearRegression\n", - "from sklearn.metrics import mean_squared_error, r2_score\n", - "\n", - "lin_model = LinearRegression()\n", - "lin_model.fit(X_train, Y_train)\n", - "\n", - "# model evaluation for training set\n", - "\n", - "y_train_predict = lin_model.predict(X_train)\n", - "rmse = (np.sqrt(mean_squared_error(Y_train, y_train_predict)))\n", - "r2 = r2_score(Y_train, y_train_predict)\n", - "\n", - "print(\"The model performance for training set\")\n", - "print(\"--------------------------------------\")\n", - "print('RMSE is {}'.format(rmse))\n", - "print('R2 score is {}'.format(r2))\n", - "print(\"\\n\")\n", - "\n", - "# model evaluation for testing set\n", - "\n", - "y_test_predict = lin_model.predict(X_test)\n", - "# root mean square error of the model\n", - "rmse = (np.sqrt(mean_squared_error(Y_test, y_test_predict)))\n", - "\n", - "# r-squared score of the model\n", - "r2 = r2_score(Y_test, y_test_predict)\n", - "\n", - "print(\"The model performance for testing set\")\n", - "print(\"--------------------------------------\")\n", - "print('RMSE is {}'.format(rmse))\n", - "print('R2 score is {}'.format(r2))" - ] - }, - { - "cell_type": "code", - "execution_count": 20, - "id": "08bedc62", - "metadata": { - "collapsed": false, - "editable": true - }, - "outputs": [], - "source": [ - "# plotting the y_test vs y_pred\n", - "# ideally should have been a straight line\n", - "plt.scatter(Y_test, y_test_predict)\n", - "plt.show()" - ] - }, - { - "cell_type": "markdown", - "id": "5096c3e8", + "id": "f586d0bb", "metadata": { "editable": true }, @@ -2095,7 +1716,7 @@ }, { "cell_type": "markdown", - "id": "cf4f6b80", + "id": "e60a9ab8", "metadata": { "editable": true }, @@ -2120,7 +1741,7 @@ }, { "cell_type": "markdown", - "id": "029c4ac4", + "id": "337c20e1", "metadata": { "editable": true }, @@ -2140,7 +1761,7 @@ }, { "cell_type": "markdown", - "id": "5575a2b5", + "id": "e1a68a5d", "metadata": { "editable": true }, @@ -2167,7 +1788,7 @@ }, { "cell_type": "markdown", - "id": "957124c9", + "id": "f8b2ab1a", "metadata": { "editable": true }, @@ -2180,7 +1801,7 @@ }, { "cell_type": "markdown", - "id": "43d5ce14", + "id": "7da909f4", "metadata": { "editable": true }, @@ -2192,7 +1813,7 @@ }, { "cell_type": "markdown", - "id": "3898e1ee", + "id": "811c0870", "metadata": { "editable": true }, @@ -2203,7 +1824,7 @@ }, { "cell_type": "markdown", - "id": "fcd90940", + "id": "9721560a", "metadata": { "editable": true }, @@ -2218,8 +1839,8 @@ }, { "cell_type": "code", - "execution_count": 21, - "id": "15fec229", + "execution_count": 9, + "id": "65a4f0c3", "metadata": { "collapsed": false, "editable": true @@ -2253,7 +1874,7 @@ }, { "cell_type": "markdown", - "id": "52b3f98d", + "id": "80a703b0", "metadata": { "editable": true }, @@ -2263,7 +1884,7 @@ }, { "cell_type": "markdown", - "id": "0b64da0f", + "id": "f540d5c9", "metadata": { "editable": true }, @@ -2278,7 +1899,7 @@ }, { "cell_type": "markdown", - "id": "e6ce0015", + "id": "3637a69b", "metadata": { "editable": true }, @@ -2290,7 +1911,7 @@ }, { "cell_type": "markdown", - "id": "15b8832b", + "id": "6baf7db9", "metadata": { "editable": true }, @@ -2300,23 +1921,23 @@ }, { "cell_type": "markdown", - "id": "dfe806b5", + "id": "bb3b37b8", "metadata": { "editable": true }, "source": [ "## Testing the Means Squared Error as function of Complexity\n", + "\n", "One of \n", "the aims is to reproduce Figure 2.11 of [Hastie et al](https://github.com/CompPhysics/MLErasmus/blob/master/doc/Textbooks/elementsstat.pdf).\n", - "We will also use Ridge and Lasso regression. \n", "\n", "Our data is defined by $x\\in [-3,3]$ with a total of for example $100$ data points." ] }, { "cell_type": "code", - "execution_count": 22, - "id": "a6c55a10", + "execution_count": 10, + "id": "099cdcf3", "metadata": { "collapsed": false, "editable": true @@ -2333,20 +1954,20 @@ }, { "cell_type": "markdown", - "id": "743313b8", + "id": "a28399c3", "metadata": { "editable": true }, "source": [ "where $y$ is the function we want to fit with a given polynomial.\n", "\n", - "Write a first code which sets up a design matrix $X$ defined by a fifth-order polynomial. Scale your data and split it in training and test data." + "Write a first code which sets up a design matrix $X$ defined by a fourth-order polynomial. Scale your data and split it in training and test data." ] }, { "cell_type": "code", - "execution_count": 23, - "id": "2af9b43a", + "execution_count": 11, + "id": "eea94fac", "metadata": { "collapsed": false, "editable": true @@ -2355,7 +1976,7 @@ "source": [ "import matplotlib.pyplot as plt\n", "import numpy as np\n", - "from sklearn.linear_model import LinearRegression, Ridge, Lasso\n", + "from sklearn.linear_model import LinearRegression\n", "from sklearn.preprocessing import PolynomialFeatures\n", "from sklearn.model_selection import train_test_split\n", "from sklearn.pipeline import make_pipeline\n", @@ -2393,18 +2014,18 @@ }, { "cell_type": "markdown", - "id": "ccd542f7", + "id": "c0ce9e6e", "metadata": { "editable": true }, "source": [ - "## More preprocessing examples, Franke function and regression" + "## More preprocessing examples, two-dimensional example, the Franke function" ] }, { "cell_type": "code", - "execution_count": 24, - "id": "8e506799", + "execution_count": 12, + "id": "f9432055", "metadata": { "collapsed": false, "editable": true @@ -2507,7 +2128,986 @@ }, { "cell_type": "markdown", - "id": "69d59b89", + "id": "1d262f6d", + "metadata": { + "editable": true + }, + "source": [ + "## To think about, first part\n", + "\n", + "When you are comparing your own code with for example **Scikit-Learn**'s\n", + "library, there are some technicalities to keep in mind. The examples\n", + "here demonstrate some of these aspects with potential pitfalls.\n", + "\n", + "The discussion here focuses on the role of the intercept, how we can\n", + "set up the design matrix, what scaling we should use and other topics\n", + "which tend confuse us.\n", + "\n", + "The intercept can be interpreted as the expected value of our\n", + "target/output variables when all other predictors are set to zero.\n", + "Thus, if we cannot assume that the expected outputs/targets are zero\n", + "when all predictors are zero (the columns in the design matrix), it\n", + "may be a bad idea to implement a model which penalizes the intercept.\n", + "Furthermore, in for example Ridge and Lasso regression, the default solutions\n", + "from the library **Scikit-Learn** (when not shrinking $\\beta_0$) for the unknown parameters\n", + "$\\boldsymbol{\\beta}$, are derived under the assumption that both $\\boldsymbol{y}$ and\n", + "$\\boldsymbol{X}$ are zero centered, that is we subtract the mean values." + ] + }, + { + "cell_type": "markdown", + "id": "311efbd3", + "metadata": { + "editable": true + }, + "source": [ + "## More thinking\n", + "\n", + "If our predictors represent different scales, then it is important to\n", + "standardize the design matrix $\\boldsymbol{X}$ by subtracting the mean of each\n", + "column from the corresponding column and dividing the column with its\n", + "standard deviation. Most machine learning libraries do this as a default. This means that if you compare your code with the results from a given library,\n", + "the results may differ. \n", + "\n", + "The\n", + "[Standadscaler](https://scikit-learn.org/stable/modules/generated/sklearn.preprocessing.StandardScaler.html)\n", + "function in **Scikit-Learn** does this for us. For the data sets we\n", + "have been studying in our various examples, the data are in many cases\n", + "already scaled and there is no need to scale them. You as a user of different machine learning algorithms, should always perform a\n", + "survey of your data, with a critical assessment of them in case you need to scale the data.\n", + "\n", + "If you need to scale the data, not doing so will give an *unfair*\n", + "penalization of the parameters since their magnitude depends on the\n", + "scale of their corresponding predictor.\n", + "\n", + "Suppose as an example that you \n", + "you have an input variable given by the heights of different persons.\n", + "Human height might be measured in inches or meters or\n", + "kilometers. If measured in kilometers, a standard linear regression\n", + "model with this predictor would probably give a much bigger\n", + "coefficient term, than if measured in millimeters.\n", + "This can clearly lead to problems in evaluating the cost/loss functions." + ] + }, + { + "cell_type": "markdown", + "id": "9931c947", + "metadata": { + "editable": true + }, + "source": [ + "## Still thinking\n", + "\n", + "Keep in mind that when you transform your data set before training a model, the same transformation needs to be done\n", + "on your eventual new data set before making a prediction. If we translate this into a Python code, it would could be implemented as follows" + ] + }, + { + "cell_type": "code", + "execution_count": 13, + "id": "3a03b7ba", + "metadata": { + "collapsed": false, + "editable": true + }, + "outputs": [], + "source": [ + "#Model training, we compute the mean value of y and X\n", + "y_train_mean = np.mean(y_train)\n", + "X_train_mean = np.mean(X_train,axis=0)\n", + "X_train = X_train - X_train_mean\n", + "y_train = y_train - y_train_mean\n", + "\n", + "# The we fit our model with the training data\n", + "trained_model = some_model.fit(X_train,y_train)\n", + "\n", + "\n", + "#Model prediction, we need also to transform our data set used for the prediction.\n", + "X_test = X_test - X_train_mean #Use mean from training data\n", + "y_pred = trained_model(X_test)\n", + "y_pred = y_pred + y_train_mean" + ] + }, + { + "cell_type": "markdown", + "id": "542e3a89", + "metadata": { + "editable": true + }, + "source": [ + "## What does centering (subtracting the mean values) mean mathematically?\n", + "\n", + "Let us try to understand what this may imply mathematically when we\n", + "subtract the mean values, also known as *zero centering*. For\n", + "simplicity, we will focus on ordinary regression, as done in the above example.\n", + "\n", + "The cost/loss function for regression is" + ] + }, + { + "cell_type": "markdown", + "id": "81d0d338", + "metadata": { + "editable": true + }, + "source": [ + "$$\n", + "C(\\beta_0, \\beta_1, ... , \\beta_{p-1}) = \\frac{1}{n}\\sum_{i=0}^{n} \\left(y_i - \\beta_0 - \\sum_{j=1}^{p-1} X_{ij}\\beta_j\\right)^2,.\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "f970b32f", + "metadata": { + "editable": true + }, + "source": [ + "Recall also that we use the squared value since this leads to an increase of the penalty for higher differences between predicted and output/target values.\n", + "\n", + "What we have done is to single out the $\\beta_0$ term in the definition of the mean squared error (MSE).\n", + "The design matrix\n", + "$X$ does in this case not contain any intercept column.\n", + "When we take the derivative with respect to $\\beta_0$, we want the derivative to obey" + ] + }, + { + "cell_type": "markdown", + "id": "4517c17b", + "metadata": { + "editable": true + }, + "source": [ + "$$\n", + "\\frac{\\partial C}{\\partial \\beta_j} = 0,\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "2e83e766", + "metadata": { + "editable": true + }, + "source": [ + "for all $j$. For $\\beta_0$ we have" + ] + }, + { + "cell_type": "markdown", + "id": "5573d14d", + "metadata": { + "editable": true + }, + "source": [ + "$$\n", + "\\frac{\\partial C}{\\partial \\beta_0} = -\\frac{2}{n}\\sum_{i=0}^{n-1} \\left(y_i - \\beta_0 - \\sum_{j=1}^{p-1} X_{ij} \\beta_j\\right).\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "c03595b1", + "metadata": { + "editable": true + }, + "source": [ + "Multiplying away the constant $2/n$, we obtain" + ] + }, + { + "cell_type": "markdown", + "id": "7c7103e6", + "metadata": { + "editable": true + }, + "source": [ + "$$\n", + "\\sum_{i=0}^{n-1} \\beta_0 = \\sum_{i=0}^{n-1}y_i - \\sum_{i=0}^{n-1} \\sum_{j=1}^{p-1} X_{ij} \\beta_j.\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "a6d143de", + "metadata": { + "editable": true + }, + "source": [ + "## Further Manipulations\n", + "\n", + "Let us special first to the case where we have only two parameters $\\beta_0$ and $\\beta_1$.\n", + "Our result for $\\beta_0$ simplifies then to" + ] + }, + { + "cell_type": "markdown", + "id": "a6a497e9", + "metadata": { + "editable": true + }, + "source": [ + "$$\n", + "n\\beta_0 = \\sum_{i=0}^{n-1}y_i - \\sum_{i=0}^{n-1} X_{i1} \\beta_1.\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "00c903d6", + "metadata": { + "editable": true + }, + "source": [ + "We obtain then" + ] + }, + { + "cell_type": "markdown", + "id": "a1eb68d4", + "metadata": { + "editable": true + }, + "source": [ + "$$\n", + "\\beta_0 = \\frac{1}{n}\\sum_{i=0}^{n-1}y_i - \\beta_1\\frac{1}{n}\\sum_{i=0}^{n-1} X_{i1}.\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "e60d2955", + "metadata": { + "editable": true + }, + "source": [ + "If we define" + ] + }, + { + "cell_type": "markdown", + "id": "fd989568", + "metadata": { + "editable": true + }, + "source": [ + "$$\n", + "\\mu_1=\\frac{1}{n}\\sum_{i=0}^{n-1} (X_{i1},\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "f18e5655", + "metadata": { + "editable": true + }, + "source": [ + "and if we define the mean value of the outputs as" + ] + }, + { + "cell_type": "markdown", + "id": "1ae7b2a1", + "metadata": { + "editable": true + }, + "source": [ + "$$\n", + "\\mu_y=\\frac{1}{n}\\sum_{i=0}^{n-1}y_i,\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "2e4d559e", + "metadata": { + "editable": true + }, + "source": [ + "we have" + ] + }, + { + "cell_type": "markdown", + "id": "5ab9bac7", + "metadata": { + "editable": true + }, + "source": [ + "$$\n", + "\\beta_0 = \\mu_y - \\beta_1\\mu_{1}.\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "8823ed6b", + "metadata": { + "editable": true + }, + "source": [ + "In the general case, that is we have more parameters than $\\beta_0$ and $\\beta_1$, we have" + ] + }, + { + "cell_type": "markdown", + "id": "319ca663", + "metadata": { + "editable": true + }, + "source": [ + "$$\n", + "\\beta_0 = \\frac{1}{n}\\sum_{i=0}^{n-1}y_i - \\frac{1}{n}\\sum_{i=0}^{n-1}\\sum_{j=1}^{p-1} X_{ij}\\beta_j.\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "b58c4a86", + "metadata": { + "editable": true + }, + "source": [ + "Replacing $y_i$ with $y_i - y_i - \\overline{\\boldsymbol{y}}$ and centering also our design matrix results in a cost function (in vector-matrix disguise)" + ] + }, + { + "cell_type": "markdown", + "id": "167fe9fd", + "metadata": { + "editable": true + }, + "source": [ + "$$\n", + "C(\\boldsymbol{\\beta}) = (\\boldsymbol{\\tilde{y}} - \\tilde{X}\\boldsymbol{\\beta})^T(\\boldsymbol{\\tilde{y}} - \\tilde{X}\\boldsymbol{\\beta}).\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "8abba21b", + "metadata": { + "editable": true + }, + "source": [ + "## Wrapping it up\n", + "\n", + "If we minimize with respect to $\\boldsymbol{\\beta}$ we have then" + ] + }, + { + "cell_type": "markdown", + "id": "a95f6f87", + "metadata": { + "editable": true + }, + "source": [ + "$$\n", + "\\hat{\\boldsymbol{\\beta}} = (\\tilde{X}^T\\tilde{X})^{-1}\\tilde{X}^T\\boldsymbol{\\tilde{y}},\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "6ca18ea2", + "metadata": { + "editable": true + }, + "source": [ + "where $\\boldsymbol{\\tilde{y}} = \\boldsymbol{y} - \\overline{\\boldsymbol{y}}$\n", + "and $\\tilde{X}_{ij} = X_{ij} - \\frac{1}{n}\\sum_{k=0}^{n-1}X_{kj}$.\n", + "\n", + "For Ridge regression we need to add $\\lambda \\boldsymbol{\\beta}^T\\boldsymbol{\\beta}$ to the cost function and get then" + ] + }, + { + "cell_type": "markdown", + "id": "9630f6ff", + "metadata": { + "editable": true + }, + "source": [ + "$$\n", + "\\hat{\\boldsymbol{\\beta}} = (\\tilde{X}^T\\tilde{X} + \\lambda I)^{-1}\\tilde{X}^T\\boldsymbol{\\tilde{y}}.\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "406b9ba8", + "metadata": { + "editable": true + }, + "source": [ + "What does this mean? And why do we insist on all this? Let us look at some examples." + ] + }, + { + "cell_type": "markdown", + "id": "5557c0e8", + "metadata": { + "editable": true + }, + "source": [ + "## Linear Regression code, Intercept handling first\n", + "\n", + "This code shows a simple first-order fit to a data set using the above transformed data, where we consider the role of the intercept first, by either excluding it or including it (*code example thanks to Øyvind Sigmundson Schøyen*). Here our scaling of the data is done by subtracting the mean values only.\n", + "Note also that we do not split the data into training and test." + ] + }, + { + "cell_type": "code", + "execution_count": 14, + "id": "27b9d36a", + "metadata": { + "collapsed": false, + "editable": true + }, + "outputs": [], + "source": [ + "import numpy as np\n", + "import matplotlib.pyplot as plt\n", + "\n", + "from sklearn.linear_model import LinearRegression\n", + "\n", + "\n", + "np.random.seed(2021)\n", + "\n", + "def MSE(y_data,y_model):\n", + " n = np.size(y_model)\n", + " return np.sum((y_data-y_model)**2)/n\n", + "\n", + "\n", + "def fit_beta(X, y):\n", + " return np.linalg.pinv(X.T @ X) @ X.T @ y\n", + "\n", + "\n", + "true_beta = [2, 0.5, 3.7]\n", + "\n", + "x = np.linspace(0, 1, 11)\n", + "y = np.sum(\n", + " np.asarray([x ** p * b for p, b in enumerate(true_beta)]), axis=0\n", + ") + 0.1 * np.random.normal(size=len(x))\n", + "\n", + "degree = 3\n", + "X = np.zeros((len(x), degree))\n", + "\n", + "# Include the intercept in the design matrix\n", + "for p in range(degree):\n", + " X[:, p] = x ** p\n", + "\n", + "beta = fit_beta(X, y)\n", + "\n", + "# Intercept is included in the design matrix\n", + "skl = LinearRegression(fit_intercept=False).fit(X, y)\n", + "\n", + "print(f\"True beta: {true_beta}\")\n", + "print(f\"Fitted beta: {beta}\")\n", + "print(f\"Sklearn fitted beta: {skl.coef_}\")\n", + "ypredictOwn = X @ beta\n", + "ypredictSKL = skl.predict(X)\n", + "print(f\"MSE with intercept column\")\n", + "print(MSE(y,ypredictOwn))\n", + "print(f\"MSE with intercept column from SKL\")\n", + "print(MSE(y,ypredictSKL))\n", + "\n", + "\n", + "plt.figure()\n", + "plt.scatter(x, y, label=\"Data\")\n", + "plt.plot(x, X @ beta, label=\"Fit\")\n", + "plt.plot(x, skl.predict(X), label=\"Sklearn (fit_intercept=False)\")\n", + "\n", + "\n", + "# Do not include the intercept in the design matrix\n", + "X = np.zeros((len(x), degree - 1))\n", + "\n", + "for p in range(degree - 1):\n", + " X[:, p] = x ** (p + 1)\n", + "\n", + "# Intercept is not included in the design matrix\n", + "skl = LinearRegression(fit_intercept=True).fit(X, y)\n", + "\n", + "# Use centered values for X and y when computing coefficients\n", + "y_offset = np.average(y, axis=0)\n", + "X_offset = np.average(X, axis=0)\n", + "\n", + "beta = fit_beta(X - X_offset, y - y_offset)\n", + "intercept = np.mean(y_offset - X_offset @ beta)\n", + "\n", + "print(f\"Manual intercept: {intercept}\")\n", + "print(f\"Fitted beta (wiothout intercept): {beta}\")\n", + "print(f\"Sklearn intercept: {skl.intercept_}\")\n", + "print(f\"Sklearn fitted beta (without intercept): {skl.coef_}\")\n", + "ypredictOwn = X @ beta\n", + "ypredictSKL = skl.predict(X)\n", + "print(f\"MSE with Manual intercept\")\n", + "print(MSE(y,ypredictOwn+intercept))\n", + "print(f\"MSE with Sklearn intercept\")\n", + "print(MSE(y,ypredictSKL))\n", + "\n", + "plt.plot(x, X @ beta + intercept, \"--\", label=\"Fit (manual intercept)\")\n", + "plt.plot(x, skl.predict(X), \"--\", label=\"Sklearn (fit_intercept=True)\")\n", + "plt.grid()\n", + "plt.legend()\n", + "\n", + "plt.show()" + ] + }, + { + "cell_type": "markdown", + "id": "36ddd15f", + "metadata": { + "editable": true + }, + "source": [ + "The intercept is the value of our output/target variable\n", + "when all our features are zero and our function crosses the $y$-axis (for a one-dimensional case). \n", + "\n", + "Printing the MSE, we see first that both methods give the same MSE, as\n", + "they should. However, when we move to for example Ridge regression,\n", + "the way we treat the intercept may give a larger or smaller MSE,\n", + "meaning that the MSE can be penalized by the value of the\n", + "intercept. Not including the intercept in the fit, means that the\n", + "regularization term does not include $\\beta_0$. For different values\n", + "of $\\lambda$, this may lead to differeing MSE values. \n", + "\n", + "To remind the reader, the regularization term, with the intercept in Ridge regression is given by" + ] + }, + { + "cell_type": "markdown", + "id": "dcf20838", + "metadata": { + "editable": true + }, + "source": [ + "$$\n", + "\\lambda \\vert\\vert \\boldsymbol{\\beta} \\vert\\vert_2^2 = \\lambda \\sum_{j=0}^{p-1}\\beta_j^2,\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "16787ea5", + "metadata": { + "editable": true + }, + "source": [ + "but when we take out the intercept, this equation becomes" + ] + }, + { + "cell_type": "markdown", + "id": "54c12897", + "metadata": { + "editable": true + }, + "source": [ + "$$\n", + "\\lambda \\vert\\vert \\boldsymbol{\\beta} \\vert\\vert_2^2 = \\lambda \\sum_{j=1}^{p-1}\\beta_j^2.\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "f6f833bd", + "metadata": { + "editable": true + }, + "source": [ + "For Lasso regression we have" + ] + }, + { + "cell_type": "markdown", + "id": "83afca1f", + "metadata": { + "editable": true + }, + "source": [ + "$$\n", + "\\lambda \\vert\\vert \\boldsymbol{\\beta} \\vert\\vert_1 = \\lambda \\sum_{j=1}^{p-1}\\vert\\beta_j\\vert.\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "3025c3ef", + "metadata": { + "editable": true + }, + "source": [ + "It means that, when scaling the design matrix and the outputs/targets, by subtracting the mean values, we have an optimization problem which is not penalized by the intercept. The MSE value can then be smaller since it focuses only on the remaining quantities. If we however bring back the intercept, we will get an MSE which then contains the intercept. This becomes more important when we discuss Ridge and Lasso regression next week." + ] + }, + { + "cell_type": "markdown", + "id": "675a5b61", + "metadata": { + "editable": true + }, + "source": [ + "## The Boston housing data example\n", + "\n", + "The Boston housing \n", + "data set was originally a part of UCI Machine Learning Repository\n", + "and has been removed now. The data set is now included in **Scikit-Learn**'s \n", + "library. There are 506 samples and 13 feature (predictor) variables\n", + "in this data set. The objective is to predict the value of prices of\n", + "the house using the features (predictors) listed here.\n", + "\n", + "The features/predictors are\n", + "1. CRIM: Per capita crime rate by town\n", + "\n", + "2. ZN: Proportion of residential land zoned for lots over 25000 square feet\n", + "\n", + "3. INDUS: Proportion of non-retail business acres per town\n", + "\n", + "4. CHAS: Charles River dummy variable (= 1 if tract bounds river; 0 otherwise)\n", + "\n", + "5. NOX: Nitric oxide concentration (parts per 10 million)\n", + "\n", + "6. RM: Average number of rooms per dwelling\n", + "\n", + "7. AGE: Proportion of owner-occupied units built prior to 1940\n", + "\n", + "8. DIS: Weighted distances to five Boston employment centers\n", + "\n", + "9. RAD: Index of accessibility to radial highways\n", + "\n", + "10. TAX: Full-value property tax rate per USD10000\n", + "\n", + "11. B: $1000(Bk - 0.63)^2$, where $Bk$ is the proportion of [people of African American descent] by town\n", + "\n", + "12. LSTAT: Percentage of lower status of the population\n", + "\n", + "13. MEDV: Median value of owner-occupied homes in USD 1000s" + ] + }, + { + "cell_type": "markdown", + "id": "d2918e16", + "metadata": { + "editable": true + }, + "source": [ + "## Housing data, the code\n", + "We start by importing the libraries" + ] + }, + { + "cell_type": "code", + "execution_count": 15, + "id": "aa97ca51", + "metadata": { + "collapsed": false, + "editable": true + }, + "outputs": [], + "source": [ + "import numpy as np\n", + "import matplotlib.pyplot as plt \n", + "\n", + "import pandas as pd \n", + "import seaborn as sns" + ] + }, + { + "cell_type": "markdown", + "id": "34ffd981", + "metadata": { + "editable": true + }, + "source": [ + "and load the Boston Housing DataSet from **Scikit-Learn**" + ] + }, + { + "cell_type": "code", + "execution_count": 16, + "id": "e86122fb", + "metadata": { + "collapsed": false, + "editable": true + }, + "outputs": [], + "source": [ + "from sklearn.datasets import load_boston\n", + "\n", + "boston_dataset = load_boston()\n", + "\n", + "# boston_dataset is a dictionary\n", + "# let's check what it contains\n", + "boston_dataset.keys()" + ] + }, + { + "cell_type": "markdown", + "id": "2ab5f3f1", + "metadata": { + "editable": true + }, + "source": [ + "Then we invoke Pandas" + ] + }, + { + "cell_type": "code", + "execution_count": 17, + "id": "73bb029f", + "metadata": { + "collapsed": false, + "editable": true + }, + "outputs": [], + "source": [ + "boston = pd.DataFrame(boston_dataset.data, columns=boston_dataset.feature_names)\n", + "boston.head()\n", + "boston['MEDV'] = boston_dataset.target" + ] + }, + { + "cell_type": "markdown", + "id": "04650405", + "metadata": { + "editable": true + }, + "source": [ + "and preprocess the data" + ] + }, + { + "cell_type": "code", + "execution_count": 18, + "id": "b1ba0529", + "metadata": { + "collapsed": false, + "editable": true + }, + "outputs": [], + "source": [ + "# check for missing values in all the columns\n", + "boston.isnull().sum()" + ] + }, + { + "cell_type": "markdown", + "id": "fb86d39a", + "metadata": { + "editable": true + }, + "source": [ + "We can then visualize the data" + ] + }, + { + "cell_type": "code", + "execution_count": 19, + "id": "9269bc8c", + "metadata": { + "collapsed": false, + "editable": true + }, + "outputs": [], + "source": [ + "# set the size of the figure\n", + "sns.set(rc={'figure.figsize':(11.7,8.27)})\n", + "\n", + "# plot a histogram showing the distribution of the target values\n", + "sns.distplot(boston['MEDV'], bins=30)\n", + "plt.show()" + ] + }, + { + "cell_type": "markdown", + "id": "a553bff9", + "metadata": { + "editable": true + }, + "source": [ + "It is now useful to look at the correlation matrix" + ] + }, + { + "cell_type": "code", + "execution_count": 20, + "id": "f0a35752", + "metadata": { + "collapsed": false, + "editable": true + }, + "outputs": [], + "source": [ + "# compute the pair wise correlation for all columns \n", + "correlation_matrix = boston.corr().round(2)\n", + "# use the heatmap function from seaborn to plot the correlation matrix\n", + "# annot = True to print the values inside the square\n", + "sns.heatmap(data=correlation_matrix, annot=True)" + ] + }, + { + "cell_type": "markdown", + "id": "f6006385", + "metadata": { + "editable": true + }, + "source": [ + "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" + ] + }, + { + "cell_type": "code", + "execution_count": 21, + "id": "a7a242b8", + "metadata": { + "collapsed": false, + "editable": true + }, + "outputs": [], + "source": [ + "plt.figure(figsize=(20, 5))\n", + "\n", + "features = ['LSTAT', 'RM']\n", + "target = boston['MEDV']\n", + "\n", + "for i, col in enumerate(features):\n", + " plt.subplot(1, len(features) , i+1)\n", + " x = boston[col]\n", + " y = target\n", + " plt.scatter(x, y, marker='o')\n", + " plt.title(col)\n", + " plt.xlabel(col)\n", + " plt.ylabel('MEDV')" + ] + }, + { + "cell_type": "markdown", + "id": "1f0d201f", + "metadata": { + "editable": true + }, + "source": [ + "Now we start training our model" + ] + }, + { + "cell_type": "code", + "execution_count": 22, + "id": "1ebe4233", + "metadata": { + "collapsed": false, + "editable": true + }, + "outputs": [], + "source": [ + "X = pd.DataFrame(np.c_[boston['LSTAT'], boston['RM']], columns = ['LSTAT','RM'])\n", + "Y = boston['MEDV']" + ] + }, + { + "cell_type": "markdown", + "id": "1e4b17f6", + "metadata": { + "editable": true + }, + "source": [ + "We split the data into training and test sets" + ] + }, + { + "cell_type": "code", + "execution_count": 23, + "id": "2d320774", + "metadata": { + "collapsed": false, + "editable": true + }, + "outputs": [], + "source": [ + "from sklearn.model_selection import train_test_split\n", + "\n", + "# splits the training and test data set in 80% : 20%\n", + "# assign random_state to any value.This ensures consistency.\n", + "X_train, X_test, Y_train, Y_test = train_test_split(X, Y, test_size = 0.2, random_state=5)\n", + "print(X_train.shape)\n", + "print(X_test.shape)\n", + "print(Y_train.shape)\n", + "print(Y_test.shape)" + ] + }, + { + "cell_type": "markdown", + "id": "de6cb89b", + "metadata": { + "editable": true + }, + "source": [ + "Then we use the linear regression functionality from **Scikit-Learn**" + ] + }, + { + "cell_type": "code", + "execution_count": 24, + "id": "406f9cc7", + "metadata": { + "collapsed": false, + "editable": true + }, + "outputs": [], + "source": [ + "from sklearn.linear_model import LinearRegression\n", + "from sklearn.metrics import mean_squared_error, r2_score\n", + "\n", + "lin_model = LinearRegression()\n", + "lin_model.fit(X_train, Y_train)\n", + "\n", + "# model evaluation for training set\n", + "\n", + "y_train_predict = lin_model.predict(X_train)\n", + "rmse = (np.sqrt(mean_squared_error(Y_train, y_train_predict)))\n", + "r2 = r2_score(Y_train, y_train_predict)\n", + "\n", + "print(\"The model performance for training set\")\n", + "print(\"--------------------------------------\")\n", + "print('RMSE is {}'.format(rmse))\n", + "print('R2 score is {}'.format(r2))\n", + "print(\"\\n\")\n", + "\n", + "# model evaluation for testing set\n", + "\n", + "y_test_predict = lin_model.predict(X_test)\n", + "# root mean square error of the model\n", + "rmse = (np.sqrt(mean_squared_error(Y_test, y_test_predict)))\n", + "\n", + "# r-squared score of the model\n", + "r2 = r2_score(Y_test, y_test_predict)\n", + "\n", + "print(\"The model performance for testing set\")\n", + "print(\"--------------------------------------\")\n", + "print('RMSE is {}'.format(rmse))\n", + "print('R2 score is {}'.format(r2))" + ] + }, + { + "cell_type": "code", + "execution_count": 25, + "id": "1790d8c6", + "metadata": { + "collapsed": false, + "editable": true + }, + "outputs": [], + "source": [ + "# plotting the y_test vs y_pred\n", + "# ideally should have been a straight line\n", + "plt.scatter(Y_test, y_test_predict)\n", + "plt.show()" + ] + }, + { + "cell_type": "markdown", + "id": "a602af77", "metadata": { "editable": true }, @@ -2517,7 +3117,7 @@ }, { "cell_type": "markdown", - "id": "19d6571f", + "id": "0190db0a", "metadata": { "editable": true }, @@ -2531,7 +3131,7 @@ }, { "cell_type": "markdown", - "id": "9c527993", + "id": "42ea647f", "metadata": { "editable": true }, @@ -2543,7 +3143,7 @@ }, { "cell_type": "markdown", - "id": "173b0e02", + "id": "88ef32a4", "metadata": { "editable": true }, @@ -2555,7 +3155,7 @@ }, { "cell_type": "markdown", - "id": "92457955", + "id": "7ce1fdc1", "metadata": { "editable": true }, @@ -2567,7 +3167,7 @@ }, { "cell_type": "markdown", - "id": "00500a2b", + "id": "d15bf8e4", "metadata": { "editable": true }, @@ -2577,7 +3177,7 @@ }, { "cell_type": "markdown", - "id": "6a148f50", + "id": "e8bbed74", "metadata": { "editable": true }, @@ -2589,7 +3189,7 @@ }, { "cell_type": "markdown", - "id": "c268e5b4", + "id": "27b4b670", "metadata": { "editable": true }, @@ -2599,7 +3199,7 @@ }, { "cell_type": "markdown", - "id": "754386b0", + "id": "2933e7b2", "metadata": { "editable": true }, @@ -2611,7 +3211,7 @@ }, { "cell_type": "markdown", - "id": "638a6cce", + "id": "cc646006", "metadata": { "editable": true }, @@ -2622,7 +3222,7 @@ }, { "cell_type": "markdown", - "id": "25da3ab7", + "id": "f0578c51", "metadata": { "editable": true }, @@ -2634,7 +3234,7 @@ }, { "cell_type": "markdown", - "id": "8b2e04bb", + "id": "6332e593", "metadata": { "editable": true }, @@ -2646,7 +3246,7 @@ }, { "cell_type": "markdown", - "id": "60b11db3", + "id": "e5c62994", "metadata": { "editable": true }, @@ -2656,7 +3256,7 @@ }, { "cell_type": "markdown", - "id": "8475e69a", + "id": "dd70468f", "metadata": { "editable": true }, @@ -2668,7 +3268,7 @@ }, { "cell_type": "markdown", - "id": "74f30ffe", + "id": "66fce1fe", "metadata": { "editable": true }, @@ -2680,7 +3280,7 @@ }, { "cell_type": "markdown", - "id": "cc5874d0", + "id": "4811da1c", "metadata": { "editable": true }, @@ -2690,7 +3290,7 @@ }, { "cell_type": "markdown", - "id": "e397eeb4", + "id": "d4127df0", "metadata": { "editable": true }, @@ -2702,7 +3302,7 @@ }, { "cell_type": "markdown", - "id": "212f7b8c", + "id": "5bcc3a1e", "metadata": { "editable": true }, @@ -2712,7 +3312,7 @@ }, { "cell_type": "markdown", - "id": "1e7908b5", + "id": "fe9806bb", "metadata": { "editable": true }, @@ -2724,7 +3324,7 @@ }, { "cell_type": "markdown", - "id": "ff655d0e", + "id": "646d3f00", "metadata": { "editable": true }, @@ -2734,7 +3334,7 @@ }, { "cell_type": "markdown", - "id": "b11e9a6e", + "id": "fe0220de", "metadata": { "editable": true }, @@ -2774,7 +3374,7 @@ }, { "cell_type": "markdown", - "id": "bf0346d1", + "id": "4ab0e0c3", "metadata": { "editable": true }, @@ -2791,7 +3391,7 @@ }, { "cell_type": "markdown", - "id": "d0794736", + "id": "bc43fd7f", "metadata": { "editable": true }, @@ -2814,7 +3414,7 @@ }, { "cell_type": "markdown", - "id": "5516a764", + "id": "687c4056", "metadata": { "editable": true }, @@ -2831,7 +3431,7 @@ }, { "cell_type": "markdown", - "id": "f4b6a7d9", + "id": "5dae4f20", "metadata": { "editable": true }, @@ -2850,7 +3450,7 @@ }, { "cell_type": "markdown", - "id": "6306b161", + "id": "39ed048b", "metadata": { "editable": true }, @@ -2861,7 +3461,7 @@ }, { "cell_type": "markdown", - "id": "e5cc2f9b", + "id": "eeca30df", "metadata": { "editable": true }, @@ -2873,7 +3473,7 @@ }, { "cell_type": "markdown", - "id": "88ca190c", + "id": "14eebe7d", "metadata": { "editable": true }, @@ -2891,7 +3491,7 @@ }, { "cell_type": "markdown", - "id": "0d0afcac", + "id": "6d4a9b40", "metadata": { "editable": true }, @@ -2907,7 +3507,7 @@ }, { "cell_type": "markdown", - "id": "89f4e6b7", + "id": "941de2f0", "metadata": { "editable": true }, @@ -2919,7 +3519,7 @@ }, { "cell_type": "markdown", - "id": "259c1101", + "id": "a1d055f6", "metadata": { "editable": true }, @@ -2929,7 +3529,7 @@ }, { "cell_type": "markdown", - "id": "88e70ae1", + "id": "9022b09b", "metadata": { "editable": true }, @@ -2944,7 +3544,7 @@ }, { "cell_type": "markdown", - "id": "a1ff1e8b", + "id": "c6b0e69e", "metadata": { "editable": true }, @@ -2956,7 +3556,7 @@ }, { "cell_type": "markdown", - "id": "7a90b131", + "id": "76452c40", "metadata": { "editable": true }, @@ -2966,7 +3566,7 @@ }, { "cell_type": "markdown", - "id": "3780c2ae", + "id": "dadb0dad", "metadata": { "editable": true }, @@ -2978,7 +3578,7 @@ }, { "cell_type": "markdown", - "id": "78e23d75", + "id": "d6aa2f86", "metadata": { "editable": true }, @@ -2988,7 +3588,7 @@ }, { "cell_type": "markdown", - "id": "3f062043", + "id": "483467c0", "metadata": { "editable": true }, @@ -3000,7 +3600,7 @@ }, { "cell_type": "markdown", - "id": "164c48fd", + "id": "ec45b064", "metadata": { "editable": true }, @@ -3012,7 +3612,7 @@ }, { "cell_type": "markdown", - "id": "55fa19ea", + "id": "f287a968", "metadata": { "editable": true }, @@ -3027,7 +3627,7 @@ }, { "cell_type": "markdown", - "id": "361fa30c", + "id": "ce946d04", "metadata": { "editable": true }, @@ -3038,7 +3638,7 @@ }, { "cell_type": "markdown", - "id": "95170d56", + "id": "ebb8258f", "metadata": { "editable": true }, @@ -3058,7 +3658,7 @@ }, { "cell_type": "markdown", - "id": "20d579bd", + "id": "57d25c28", "metadata": { "editable": true }, @@ -3070,7 +3670,7 @@ }, { "cell_type": "markdown", - "id": "662ff6f7", + "id": "5c63309c", "metadata": { "editable": true }, @@ -3080,7 +3680,7 @@ }, { "cell_type": "markdown", - "id": "8472a9ec", + "id": "531d6591", "metadata": { "editable": true }, @@ -3092,7 +3692,7 @@ }, { "cell_type": "markdown", - "id": "c8b2b974", + "id": "06ea8edf", "metadata": { "editable": true }, @@ -3121,7 +3721,7 @@ }, { "cell_type": "markdown", - "id": "ffe7bea9", + "id": "c8207881", "metadata": { "editable": true }, @@ -3148,7 +3748,7 @@ }, { "cell_type": "markdown", - "id": "0589a567", + "id": "0f679a3e", "metadata": { "editable": true }, @@ -3158,8 +3758,8 @@ }, { "cell_type": "code", - "execution_count": 25, - "id": "d8b999da", + "execution_count": 26, + "id": "f303dd05", "metadata": { "collapsed": false, "editable": true @@ -3199,7 +3799,7 @@ }, { "cell_type": "markdown", - "id": "efc3ef1c", + "id": "3b89ae6a", "metadata": { "editable": true }, @@ -3216,7 +3816,7 @@ }, { "cell_type": "markdown", - "id": "d48b0b13", + "id": "ccc2ace3", "metadata": { "editable": true }, @@ -3239,7 +3839,7 @@ }, { "cell_type": "markdown", - "id": "15f09549", + "id": "ec0bc486", "metadata": { "editable": true }, @@ -3253,7 +3853,7 @@ }, { "cell_type": "markdown", - "id": "97b312ac", + "id": "2f25f47f", "metadata": { "editable": true }, @@ -3272,7 +3872,7 @@ }, { "cell_type": "markdown", - "id": "d5629243", + "id": "950d6d71", "metadata": { "editable": true }, @@ -3282,7 +3882,7 @@ }, { "cell_type": "markdown", - "id": "031b2357", + "id": "61595420", "metadata": { "editable": true }, @@ -3294,7 +3894,7 @@ }, { "cell_type": "markdown", - "id": "d5a3313b", + "id": "81dbfc66", "metadata": { "editable": true }, @@ -3308,7 +3908,7 @@ }, { "cell_type": "markdown", - "id": "34671947", + "id": "6e69a431", "metadata": { "editable": true }, @@ -3320,7 +3920,7 @@ }, { "cell_type": "markdown", - "id": "1d7179b3", + "id": "c512a377", "metadata": { "editable": true }, @@ -3330,7 +3930,7 @@ }, { "cell_type": "markdown", - "id": "eef33b7a", + "id": "f380e36b", "metadata": { "editable": true }, @@ -3342,7 +3942,7 @@ }, { "cell_type": "markdown", - "id": "eb685e58", + "id": "d5a0b156", "metadata": { "editable": true }, @@ -3359,7 +3959,7 @@ }, { "cell_type": "markdown", - "id": "ce2e1629", + "id": "c4fbe6ee", "metadata": { "editable": true }, @@ -3369,7 +3969,7 @@ }, { "cell_type": "markdown", - "id": "f7f814ac", + "id": "43f9dca0", "metadata": { "editable": true }, @@ -3385,7 +3985,7 @@ }, { "cell_type": "markdown", - "id": "8ace03c6", + "id": "bd10fa38", "metadata": { "editable": true }, @@ -3395,7 +3995,7 @@ }, { "cell_type": "markdown", - "id": "84e44b9e", + "id": "197008d7", "metadata": { "editable": true }, @@ -3411,7 +4011,7 @@ }, { "cell_type": "markdown", - "id": "8d2251e0", + "id": "d7d03027", "metadata": { "editable": true }, @@ -3421,7 +4021,7 @@ }, { "cell_type": "markdown", - "id": "d89c6f00", + "id": "a545ab28", "metadata": { "editable": true }, @@ -3437,7 +4037,7 @@ }, { "cell_type": "markdown", - "id": "83d009db", + "id": "0c39be82", "metadata": { "editable": true }, @@ -3447,7 +4047,7 @@ }, { "cell_type": "markdown", - "id": "8ba4aa6c", + "id": "b73a0d64", "metadata": { "editable": true }, @@ -3464,7 +4064,7 @@ }, { "cell_type": "markdown", - "id": "716d52f2", + "id": "6aa1af58", "metadata": { "editable": true }, @@ -3476,7 +4076,7 @@ }, { "cell_type": "markdown", - "id": "806400ad", + "id": "83e55282", "metadata": { "editable": true }, @@ -3488,7 +4088,7 @@ }, { "cell_type": "markdown", - "id": "d8b16e14", + "id": "f57493d4", "metadata": { "editable": true }, @@ -3500,7 +4100,7 @@ }, { "cell_type": "markdown", - "id": "54551d2b", + "id": "1a2c5145", "metadata": { "editable": true }, @@ -3510,7 +4110,7 @@ }, { "cell_type": "markdown", - "id": "d032122f", + "id": "7e9c396a", "metadata": { "editable": true }, @@ -3522,7 +4122,7 @@ }, { "cell_type": "markdown", - "id": "4a317bc9", + "id": "530d69f7", "metadata": { "editable": true }, @@ -3534,7 +4134,7 @@ }, { "cell_type": "markdown", - "id": "f7d1aa92", + "id": "99f5df84", "metadata": { "editable": true }, @@ -3546,7 +4146,7 @@ }, { "cell_type": "markdown", - "id": "1406b185", + "id": "05f10d74", "metadata": { "editable": true }, @@ -3556,7 +4156,7 @@ }, { "cell_type": "markdown", - "id": "577033a5", + "id": "d2eca91e", "metadata": { "editable": true }, @@ -3568,7 +4168,7 @@ }, { "cell_type": "markdown", - "id": "c2547853", + "id": "2ae2fef1", "metadata": { "editable": true }, @@ -3578,7 +4178,7 @@ }, { "cell_type": "markdown", - "id": "d5a4d900", + "id": "71f1ea41", "metadata": { "editable": true }, @@ -3590,7 +4190,7 @@ }, { "cell_type": "markdown", - "id": "b5d2bdc6", + "id": "f3ee9ee7", "metadata": { "editable": true }, @@ -3604,7 +4204,7 @@ }, { "cell_type": "markdown", - "id": "6dfac505", + "id": "8b7a74f0", "metadata": { "editable": true }, @@ -3616,7 +4216,7 @@ }, { "cell_type": "markdown", - "id": "f6ce34dc", + "id": "4250e3bf", "metadata": { "editable": true }, @@ -3628,7 +4228,7 @@ }, { "cell_type": "markdown", - "id": "3b1a24c1", + "id": "2c4099f9", "metadata": { "editable": true }, @@ -3638,7 +4238,7 @@ }, { "cell_type": "markdown", - "id": "2141c1fd", + "id": "be49edc5", "metadata": { "editable": true }, @@ -3650,7 +4250,7 @@ }, { "cell_type": "markdown", - "id": "b5223c32", + "id": "cd0a8bc6", "metadata": { "editable": true }, @@ -3661,7 +4261,7 @@ }, { "cell_type": "markdown", - "id": "81ff0150", + "id": "733b034c", "metadata": { "editable": true }, @@ -3673,7 +4273,7 @@ }, { "cell_type": "markdown", - "id": "1a5a189d", + "id": "ac74afd8", "metadata": { "editable": true }, @@ -3683,7 +4283,7 @@ }, { "cell_type": "markdown", - "id": "07697a38", + "id": "ad262b2a", "metadata": { "editable": true }, @@ -3695,7 +4295,7 @@ }, { "cell_type": "markdown", - "id": "3b0b302b", + "id": "c569cf69", "metadata": { "editable": true }, @@ -3705,7 +4305,7 @@ }, { "cell_type": "markdown", - "id": "7fd799ca", + "id": "b574522e", "metadata": { "editable": true }, @@ -3717,7 +4317,7 @@ }, { "cell_type": "markdown", - "id": "55b9753c", + "id": "45586d81", "metadata": { "editable": true }, @@ -3728,7 +4328,7 @@ }, { "cell_type": "markdown", - "id": "9ee6c210", + "id": "c7c9d818", "metadata": { "editable": true }, @@ -3740,7 +4340,7 @@ }, { "cell_type": "markdown", - "id": "5edc5461", + "id": "1a9d86fc", "metadata": { "editable": true }, @@ -3758,7 +4358,7 @@ }, { "cell_type": "markdown", - "id": "9b459210", + "id": "347a807e", "metadata": { "editable": true }, @@ -3774,7 +4374,7 @@ }, { "cell_type": "markdown", - "id": "6bf9dcc1", + "id": "a52e2b26", "metadata": { "editable": true }, @@ -3786,7 +4386,7 @@ }, { "cell_type": "markdown", - "id": "f4d8f1ec", + "id": "dfbc1bb8", "metadata": { "editable": true }, @@ -3798,7 +4398,7 @@ }, { "cell_type": "markdown", - "id": "25543485", + "id": "9d4a8790", "metadata": { "editable": true }, @@ -3810,7 +4410,7 @@ }, { "cell_type": "markdown", - "id": "26616c4b", + "id": "15117986", "metadata": { "editable": true }, @@ -3823,7 +4423,7 @@ }, { "cell_type": "markdown", - "id": "f264b2ad", + "id": "05926fd4", "metadata": { "editable": true }, @@ -3839,7 +4439,7 @@ }, { "cell_type": "markdown", - "id": "ceff0417", + "id": "5bb56f45", "metadata": { "editable": true }, @@ -3853,7 +4453,7 @@ }, { "cell_type": "markdown", - "id": "8ad48994", + "id": "bfe1b957", "metadata": { "editable": true }, @@ -3863,7 +4463,7 @@ }, { "cell_type": "markdown", - "id": "95b2c5c3", + "id": "f6baf9c0", "metadata": { "editable": true }, @@ -3875,7 +4475,7 @@ }, { "cell_type": "markdown", - "id": "8eeb9425", + "id": "ed9da1e2", "metadata": { "editable": true }, @@ -3885,7 +4485,7 @@ }, { "cell_type": "markdown", - "id": "83a0d485", + "id": "68353e8c", "metadata": { "editable": true }, @@ -3897,7 +4497,7 @@ }, { "cell_type": "markdown", - "id": "474540a1", + "id": "3ea76834", "metadata": { "editable": true }, @@ -3907,7 +4507,7 @@ }, { "cell_type": "markdown", - "id": "47421455", + "id": "543e1fa1", "metadata": { "editable": true }, @@ -3921,7 +4521,7 @@ }, { "cell_type": "markdown", - "id": "45ef89cf", + "id": "cf004dc8", "metadata": { "editable": true }, @@ -3938,7 +4538,7 @@ }, { "cell_type": "markdown", - "id": "9bf5803c", + "id": "70fa6885", "metadata": { "editable": true }, @@ -3954,7 +4554,7 @@ }, { "cell_type": "markdown", - "id": "972e21fa", + "id": "dcc0c4c1", "metadata": { "editable": true }, @@ -3966,7 +4566,7 @@ }, { "cell_type": "markdown", - "id": "bb51d5fe", + "id": "26d7e490", "metadata": { "editable": true }, @@ -3979,7 +4579,7 @@ }, { "cell_type": "markdown", - "id": "8d76827a", + "id": "a0a36a83", "metadata": { "editable": true }, @@ -3993,7 +4593,7 @@ }, { "cell_type": "markdown", - "id": "ec772b3e", + "id": "97743931", "metadata": { "editable": true }, @@ -4003,7 +4603,7 @@ }, { "cell_type": "markdown", - "id": "9f4e08b7", + "id": "e1c9d958", "metadata": { "editable": true }, @@ -4016,7 +4616,7 @@ }, { "cell_type": "markdown", - "id": "10b49297", + "id": "1c653a67", "metadata": { "editable": true }, @@ -4035,7 +4635,7 @@ }, { "cell_type": "markdown", - "id": "b0772f5b", + "id": "a260bd35", "metadata": { "editable": true }, @@ -4047,7 +4647,7 @@ }, { "cell_type": "markdown", - "id": "177f3a4b", + "id": "5cc7a553", "metadata": { "editable": true }, @@ -4059,7 +4659,7 @@ }, { "cell_type": "markdown", - "id": "68d70446", + "id": "6cdc22ce", "metadata": { "editable": true }, @@ -4069,7 +4669,7 @@ }, { "cell_type": "markdown", - "id": "a372cef4", + "id": "be7da0d5", "metadata": { "editable": true }, @@ -4081,7 +4681,7 @@ }, { "cell_type": "markdown", - "id": "e771c2b7", + "id": "3d4d66f2", "metadata": { "editable": true }, @@ -4094,7 +4694,7 @@ }, { "cell_type": "markdown", - "id": "a5cf8180", + "id": "f8d2fd2c", "metadata": { "editable": true }, @@ -4113,7 +4713,7 @@ }, { "cell_type": "markdown", - "id": "f9568a84", + "id": "2f432d38", "metadata": { "editable": true }, @@ -4123,7 +4723,7 @@ }, { "cell_type": "markdown", - "id": "9a33aefe", + "id": "64a695ad", "metadata": { "editable": true }, @@ -4142,7 +4742,7 @@ }, { "cell_type": "markdown", - "id": "09fe18a8", + "id": "8d112930", "metadata": { "editable": true }, @@ -4160,7 +4760,7 @@ }, { "cell_type": "markdown", - "id": "640502bc", + "id": "62633ba5", "metadata": { "editable": true }, @@ -4174,7 +4774,7 @@ }, { "cell_type": "markdown", - "id": "114dde4d", + "id": "74f22dd0", "metadata": { "editable": true }, @@ -4188,8 +4788,8 @@ }, { "cell_type": "code", - "execution_count": 26, - "id": "045dc84f", + "execution_count": 27, + "id": "10208407", "metadata": { "collapsed": false, "editable": true @@ -4210,7 +4810,7 @@ }, { "cell_type": "markdown", - "id": "622017ff", + "id": "fff9f0df", "metadata": { "editable": true }, @@ -4226,8 +4826,8 @@ }, { "cell_type": "code", - "execution_count": 27, - "id": "798d02b0", + "execution_count": 28, + "id": "72df9047", "metadata": { "collapsed": false, "editable": true @@ -4259,7 +4859,7 @@ }, { "cell_type": "markdown", - "id": "89d042fe", + "id": "35ba27c4", "metadata": { "editable": true }, @@ -4273,7 +4873,7 @@ }, { "cell_type": "markdown", - "id": "61888d91", + "id": "813e8edd", "metadata": { "editable": true }, @@ -4285,8 +4885,8 @@ }, { "cell_type": "code", - "execution_count": 28, - "id": "0cb55d52", + "execution_count": 29, + "id": "b21385d7", "metadata": { "collapsed": false, "editable": true @@ -4311,7 +4911,7 @@ }, { "cell_type": "markdown", - "id": "2158c63e", + "id": "6e4af867", "metadata": { "editable": true }, @@ -4321,7 +4921,7 @@ }, { "cell_type": "markdown", - "id": "c1767789", + "id": "4eeffe9a", "metadata": { "editable": true }, @@ -4331,8 +4931,8 @@ }, { "cell_type": "code", - "execution_count": 29, - "id": "d9e23e45", + "execution_count": 30, + "id": "3cb27e05", "metadata": { "collapsed": false, "editable": true @@ -4386,7 +4986,7 @@ }, { "cell_type": "markdown", - "id": "55dc8237", + "id": "5897c0af", "metadata": { "editable": true }, @@ -4403,7 +5003,7 @@ }, { "cell_type": "markdown", - "id": "476061f1", + "id": "d5e30492", "metadata": { "editable": true }, @@ -4415,7 +5015,7 @@ }, { "cell_type": "markdown", - "id": "3dee9a86", + "id": "2da8a6f6", "metadata": { "editable": true }, @@ -4427,7 +5027,7 @@ }, { "cell_type": "markdown", - "id": "6c74904d", + "id": "06eac8d4", "metadata": { "editable": true }, @@ -4437,7 +5037,7 @@ }, { "cell_type": "markdown", - "id": "0154c547", + "id": "7c90bb0e", "metadata": { "editable": true }, @@ -4454,7 +5054,7 @@ }, { "cell_type": "markdown", - "id": "966e4960", + "id": "59adda50", "metadata": { "editable": true }, @@ -4464,7 +5064,7 @@ }, { "cell_type": "markdown", - "id": "8b2c133b", + "id": "65b5748f", "metadata": { "editable": true }, @@ -4479,7 +5079,7 @@ }, { "cell_type": "markdown", - "id": "04c185c1", + "id": "bc3e9830", "metadata": { "editable": true }, @@ -4489,7 +5089,7 @@ }, { "cell_type": "markdown", - "id": "605968c6", + "id": "b458de4d", "metadata": { "editable": true }, @@ -4503,7 +5103,7 @@ }, { "cell_type": "markdown", - "id": "9f2dedc5", + "id": "4a57a8e0", "metadata": { "editable": true }, @@ -4515,7 +5115,7 @@ }, { "cell_type": "markdown", - "id": "676fe220", + "id": "0c426ac7", "metadata": { "editable": true }, @@ -4527,7 +5127,7 @@ }, { "cell_type": "markdown", - "id": "350f8c2b", + "id": "a6d06a3f", "metadata": { "editable": true }, @@ -4539,7 +5139,7 @@ }, { "cell_type": "markdown", - "id": "daa496b7", + "id": "219f9ccb", "metadata": { "editable": true }, @@ -4549,7 +5149,7 @@ }, { "cell_type": "markdown", - "id": "646c7bce", + "id": "e0af609e", "metadata": { "editable": true }, @@ -4561,7 +5161,7 @@ }, { "cell_type": "markdown", - "id": "1c2b1f45", + "id": "721e39cb", "metadata": { "editable": true }, @@ -4571,7 +5171,7 @@ }, { "cell_type": "markdown", - "id": "3e55aa0e", + "id": "ec989cfc", "metadata": { "editable": true }, @@ -4588,7 +5188,7 @@ }, { "cell_type": "markdown", - "id": "0e2cfaea", + "id": "57275f46", "metadata": { "editable": true }, @@ -4598,7 +5198,7 @@ }, { "cell_type": "markdown", - "id": "2e709ae4", + "id": "59dfa6be", "metadata": { "editable": true }, @@ -4610,7 +5210,7 @@ }, { "cell_type": "markdown", - "id": "f62dd939", + "id": "c6e46e3a", "metadata": { "editable": true }, @@ -4620,7 +5220,7 @@ }, { "cell_type": "markdown", - "id": "75431dd1", + "id": "82d0b1d4", "metadata": { "editable": true }, @@ -4632,7 +5232,7 @@ }, { "cell_type": "markdown", - "id": "bea32c07", + "id": "2a20d514", "metadata": { "editable": true }, @@ -4646,7 +5246,7 @@ }, { "cell_type": "markdown", - "id": "a5e8478a", + "id": "1df4e973", "metadata": { "editable": true }, @@ -4658,7 +5258,7 @@ }, { "cell_type": "markdown", - "id": "2e54ddfd", + "id": "775b345d", "metadata": { "editable": true }, @@ -4680,7 +5280,7 @@ }, { "cell_type": "markdown", - "id": "90685bf2", + "id": "ea73a27d", "metadata": { "editable": true }, @@ -4692,7 +5292,7 @@ }, { "cell_type": "markdown", - "id": "e36d06a4", + "id": "5073c271", "metadata": { "editable": true }, @@ -4707,7 +5307,7 @@ }, { "cell_type": "markdown", - "id": "8b6b8846", + "id": "e82ec69f", "metadata": { "editable": true }, @@ -4719,7 +5319,7 @@ }, { "cell_type": "markdown", - "id": "1c291829", + "id": "6e11ce54", "metadata": { "editable": true }, @@ -4731,7 +5331,7 @@ }, { "cell_type": "markdown", - "id": "cb36f715", + "id": "969b47a9", "metadata": { "editable": true }, @@ -4741,7 +5341,7 @@ }, { "cell_type": "markdown", - "id": "94df0dcd", + "id": "93eb339d", "metadata": { "editable": true }, @@ -4753,7 +5353,7 @@ }, { "cell_type": "markdown", - "id": "c594530e", + "id": "59d3c243", "metadata": { "editable": true }, @@ -4763,7 +5363,7 @@ }, { "cell_type": "markdown", - "id": "c60fdcdb", + "id": "88905c12", "metadata": { "editable": true }, @@ -4775,7 +5375,7 @@ }, { "cell_type": "markdown", - "id": "c06b4a5a", + "id": "6cc970fd", "metadata": { "editable": true }, @@ -4785,7 +5385,7 @@ }, { "cell_type": "markdown", - "id": "5dc51f4c", + "id": "079ac9ba", "metadata": { "editable": true }, @@ -4797,7 +5397,7 @@ }, { "cell_type": "markdown", - "id": "1a065600", + "id": "2633ab97", "metadata": { "editable": true }, @@ -4814,7 +5414,7 @@ }, { "cell_type": "markdown", - "id": "3a56b35e", + "id": "dfeab33f", "metadata": { "editable": true }, @@ -4827,7 +5427,7 @@ }, { "cell_type": "markdown", - "id": "8bdfcb68", + "id": "0f33a0d4", "metadata": { "editable": true }, @@ -4839,7 +5439,7 @@ }, { "cell_type": "markdown", - "id": "81a3ff8e", + "id": "9eeab640", "metadata": { "editable": true }, @@ -4849,7 +5449,7 @@ }, { "cell_type": "markdown", - "id": "b10c855f", + "id": "8fa01e32", "metadata": { "editable": true }, @@ -4862,7 +5462,7 @@ }, { "cell_type": "markdown", - "id": "c2ea9e83", + "id": "387a69ff", "metadata": { "editable": true }, @@ -4872,7 +5472,7 @@ }, { "cell_type": "markdown", - "id": "72091db8", + "id": "b53f3c66", "metadata": { "editable": true }, @@ -4884,7 +5484,7 @@ }, { "cell_type": "markdown", - "id": "31080949", + "id": "db9ef814", "metadata": { "editable": true }, @@ -4897,7 +5497,7 @@ }, { "cell_type": "markdown", - "id": "43bc9eb7", + "id": "bd9eff5d", "metadata": { "editable": true }, @@ -4910,7 +5510,7 @@ }, { "cell_type": "markdown", - "id": "50f02424", + "id": "5ef7b233", "metadata": { "editable": true }, @@ -4922,7 +5522,7 @@ }, { "cell_type": "markdown", - "id": "03d1a84a", + "id": "254828fb", "metadata": { "editable": true }, @@ -4934,7 +5534,7 @@ }, { "cell_type": "markdown", - "id": "ef42ef37", + "id": "535f6d77", "metadata": { "editable": true }, @@ -4944,7 +5544,7 @@ }, { "cell_type": "markdown", - "id": "0e9f1315", + "id": "1b39ea82", "metadata": { "editable": true }, @@ -4957,7 +5557,7 @@ }, { "cell_type": "markdown", - "id": "7ffecf2a", + "id": "ca9ed98e", "metadata": { "editable": true }, @@ -4969,7 +5569,7 @@ }, { "cell_type": "markdown", - "id": "06696f01", + "id": "2d621f3c", "metadata": { "editable": true }, @@ -4981,7 +5581,7 @@ }, { "cell_type": "markdown", - "id": "81980128", + "id": "1525b1e5", "metadata": { "editable": true }, @@ -4993,7 +5593,7 @@ }, { "cell_type": "markdown", - "id": "79dd0486", + "id": "566ddc35", "metadata": { "editable": true }, @@ -5005,7 +5605,7 @@ }, { "cell_type": "markdown", - "id": "dc8cbb55", + "id": "5ec1de70", "metadata": { "editable": true }, @@ -5019,7 +5619,7 @@ }, { "cell_type": "markdown", - "id": "a22c501f", + "id": "7b615513", "metadata": { "editable": true }, @@ -5031,7 +5631,7 @@ }, { "cell_type": "markdown", - "id": "4268c475", + "id": "7af6c783", "metadata": { "editable": true }, @@ -5041,7 +5641,7 @@ }, { "cell_type": "markdown", - "id": "bb4c3b0f", + "id": "058050d7", "metadata": { "editable": true }, @@ -5053,7 +5653,7 @@ }, { "cell_type": "markdown", - "id": "43b5fd1b", + "id": "7c671f5e", "metadata": { "editable": true }, @@ -5065,7 +5665,7 @@ }, { "cell_type": "markdown", - "id": "f7fc2763", + "id": "e79b23a7", "metadata": { "editable": true }, @@ -5077,7 +5677,7 @@ }, { "cell_type": "markdown", - "id": "b4a36c03", + "id": "d44102d2", "metadata": { "editable": true }, @@ -5089,7 +5689,7 @@ }, { "cell_type": "markdown", - "id": "d06f190c", + "id": "b1f6463c", "metadata": { "editable": true }, @@ -5101,7 +5701,7 @@ }, { "cell_type": "markdown", - "id": "e075c119", + "id": "ed757eb1", "metadata": { "editable": true }, @@ -5120,7 +5720,7 @@ }, { "cell_type": "markdown", - "id": "268b7ff5", + "id": "905b7d64", "metadata": { "editable": true }, @@ -5132,7 +5732,7 @@ }, { "cell_type": "markdown", - "id": "764e130f", + "id": "9f4de44d", "metadata": { "editable": true }, @@ -5142,7 +5742,7 @@ }, { "cell_type": "markdown", - "id": "ab113ded", + "id": "62a13ed4", "metadata": { "editable": true }, @@ -5154,7 +5754,7 @@ }, { "cell_type": "markdown", - "id": "4fb193fb", + "id": "3c17eb55", "metadata": { "editable": true }, @@ -5164,7 +5764,7 @@ }, { "cell_type": "markdown", - "id": "493ce164", + "id": "54630506", "metadata": { "editable": true }, @@ -5176,7 +5776,7 @@ }, { "cell_type": "markdown", - "id": "9e2ad1e0", + "id": "0d18500c", "metadata": { "editable": true }, @@ -5188,7 +5788,7 @@ }, { "cell_type": "markdown", - "id": "eb752467", + "id": "2a493e6a", "metadata": { "editable": true }, @@ -5204,7 +5804,7 @@ }, { "cell_type": "markdown", - "id": "3e7a79bc", + "id": "00ecc387", "metadata": { "editable": true }, @@ -5216,7 +5816,7 @@ }, { "cell_type": "markdown", - "id": "699790f7", + "id": "1ec18d73", "metadata": { "editable": true }, @@ -5228,7 +5828,7 @@ }, { "cell_type": "markdown", - "id": "d2449819", + "id": "71435169", "metadata": { "editable": true }, @@ -5238,7 +5838,7 @@ }, { "cell_type": "markdown", - "id": "a6acb89d", + "id": "61c878a8", "metadata": { "editable": true }, @@ -5250,7 +5850,7 @@ }, { "cell_type": "markdown", - "id": "882fe6bd", + "id": "30f48730", "metadata": { "editable": true }, @@ -5260,7 +5860,7 @@ }, { "cell_type": "markdown", - "id": "d907592e", + "id": "a79a72a8", "metadata": { "editable": true }, @@ -5272,7 +5872,7 @@ }, { "cell_type": "markdown", - "id": "96d05e6e", + "id": "eafc2e6c", "metadata": { "editable": true }, @@ -5289,7 +5889,7 @@ }, { "cell_type": "markdown", - "id": "fcdbc7a2", + "id": "bebba502", "metadata": { "editable": true }, @@ -5301,7 +5901,7 @@ }, { "cell_type": "markdown", - "id": "968f5028", + "id": "65667551", "metadata": { "editable": true }, @@ -5313,7 +5913,7 @@ }, { "cell_type": "markdown", - "id": "31330c4c", + "id": "cdba7875", "metadata": { "editable": true }, @@ -5323,7 +5923,7 @@ }, { "cell_type": "markdown", - "id": "91a958a6", + "id": "8e0d7210", "metadata": { "editable": true }, @@ -5335,7 +5935,7 @@ }, { "cell_type": "markdown", - "id": "e65c9bbc", + "id": "0840d7b4", "metadata": { "editable": true }, @@ -5345,7 +5945,7 @@ }, { "cell_type": "markdown", - "id": "b37a1548", + "id": "ba1ea89b", "metadata": { "editable": true }, @@ -5357,7 +5957,7 @@ }, { "cell_type": "markdown", - "id": "eb887fb8", + "id": "2eba4be0", "metadata": { "editable": true }, @@ -5367,7 +5967,7 @@ }, { "cell_type": "markdown", - "id": "7c9a4615", + "id": "c5f3e12e", "metadata": { "editable": true }, @@ -5379,816 +5979,13 @@ }, { "cell_type": "markdown", - "id": "6702bafb", + "id": "4680607a", "metadata": { "editable": true }, "source": [ "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](https://cvxopt.org/). We will discuss this later." ] - }, - { - "cell_type": "markdown", - "id": "0cdb4d6e", - "metadata": { - "editable": true - }, - "source": [ - "## Exercises for week 35\n", - "\n", - "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)." - ] - }, - { - "cell_type": "markdown", - "id": "68e443b7", - "metadata": { - "editable": true - }, - "source": [ - "## Exercise 1: Setting up various Python environments\n", - "\n", - "The first exercise here is of a mere technical art. We want you to have \n", - "* git as a version control software and to establish a user account on a provider like GitHub. Other providers like GitLab etc are equally fine. You can also use the University of Oslo [GitHub facilities](https://www.uio.no/tjenester/it/maskin/filer/versjonskontroll/github.html). \n", - "\n", - "* Install various Python packages\n", - "\n", - "We will make extensive use of Python as programming language and its\n", - "myriad of available libraries. You will find\n", - "IPython/Jupyter notebooks invaluable in your work. You can run **R**\n", - "codes in the Jupyter/IPython notebooks, with the immediate benefit of\n", - "visualizing your data. You can also use compiled languages like C++,\n", - "Rust, Fortran etc if you prefer. The focus in these lectures will be\n", - "on Python.\n", - "\n", - "If you have Python installed (we recommend Python3) and you feel\n", - "pretty familiar with installing different packages, we recommend that\n", - "you install the following Python packages via **pip** as \n", - "\n", - "1. pip install numpy scipy matplotlib ipython scikit-learn sympy pandas pillow \n", - "\n", - "For **Tensorflow**, we recommend following the instructions in the text of \n", - "[Aurelien Geron, Hands‑On Machine Learning with Scikit‑Learn and TensorFlow, O'Reilly](http://shop.oreilly.com/product/0636920052289.do)\n", - "\n", - "We will come back to **tensorflow** later. \n", - "\n", - "For Python3, replace **pip** with **pip3**.\n", - "\n", - "For OSX users we recommend, after having installed Xcode, to\n", - "install **brew**. Brew allows for a seamless installation of additional\n", - "software via for example \n", - "\n", - "1. brew install python3\n", - "\n", - "For Linux users, with its variety of distributions like for example the widely popular Ubuntu distribution,\n", - "you can use **pip** as well and simply install Python as \n", - "\n", - "1. sudo apt-get install python3 (or python for Python2.7)\n", - "\n", - "If you don't want to perform these operations separately and venture\n", - "into the hassle of exploring how to set up dependencies and paths, we\n", - "recommend two widely used distrubutions which set up all relevant\n", - "dependencies for Python, namely \n", - "\n", - "* [Anaconda](https://docs.anaconda.com/), \n", - "\n", - "which is an open source\n", - "distribution of the Python and R programming languages for large-scale\n", - "data processing, predictive analytics, and scientific computing, that\n", - "aims to simplify package management and deployment. Package versions\n", - "are managed by the package management system **conda**. \n", - "\n", - "* [Enthought canopy](https://www.enthought.com/product/canopy/) \n", - "\n", - "is a Python\n", - "distribution for scientific and analytic computing distribution and\n", - "analysis environment, available for free and under a commercial\n", - "license.\n", - "\n", - "We recommend using **Anaconda** if you are not too familiar with setting paths in a terminal environment." - ] - }, - { - "cell_type": "markdown", - "id": "cd9b57ac", - "metadata": { - "editable": true - }, - "source": [ - "## Exercise 2: making your own data and exploring scikit-learn\n", - "\n", - "We will generate our own dataset for a function $y(x)$ where $x \\in [0,1]$ and defined by random numbers computed with the uniform distribution. The function $y$ is a quadratic polynomial in $x$ with added stochastic noise according to the normal distribution $\\cal {N}(0,1)$.\n", - "The following simple Python instructions define our $x$ and $y$ values (with 100 data points)." - ] - }, - { - "cell_type": "code", - "execution_count": 30, - "id": "9d41347f", - "metadata": { - "collapsed": false, - "editable": true - }, - "outputs": [], - "source": [ - "x = np.random.rand(100,1)\n", - "y = 2.0+5*x*x+0.1*np.random.randn(100,1)" - ] - }, - { - "cell_type": "markdown", - "id": "457efec1", - "metadata": { - "editable": true - }, - "source": [ - "1. Write your own code (following the examples under the [regression notes](https://compphysics.github.io/MachineLearning/doc/LectureNotes/_build/html/chapter1.html)) for computing the parametrization of the data set fitting a second-order polynomial. \n", - "\n", - "2. Use thereafter **scikit-learn** (see again the examples in the regression slides) and compare with your own code. When compairing with _scikit_learn_, make sure you set the option for the intercept to **FALSE**, see . This feature will be explained in more detail during the lectures of week 35 and week 36. You can find more in .\n", - "\n", - "3. Using scikit-learn, compute also the mean square error, a risk metric corresponding to the expected value of the squared (quadratic) error defined as" - ] - }, - { - "cell_type": "markdown", - "id": "d1e25dc5", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "MSE(\\boldsymbol{y},\\boldsymbol{\\tilde{y}}) = \\frac{1}{n}\n", - "\\sum_{i=0}^{n-1}(y_i-\\tilde{y}_i)^2,\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "f938e3fe", - "metadata": { - "editable": true - }, - "source": [ - "and the $R^2$ score function.\n", - "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" - ] - }, - { - "cell_type": "markdown", - "id": "64769546", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "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},\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "775263e2", - "metadata": { - "editable": true - }, - "source": [ - "where we have defined the mean value of $\\boldsymbol{y}$ as" - ] - }, - { - "cell_type": "markdown", - "id": "1fdee59d", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\bar{y} = \\frac{1}{n} \\sum_{i=0}^{n - 1} y_i.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "2bbaa7d8", - "metadata": { - "editable": true - }, - "source": [ - "You can use the functionality included in scikit-learn. If you feel for it, you can use your own program and define functions which compute the above two functions. \n", - "Discuss the meaning of these results. Try also to vary the coefficient in front of the added stochastic noise term and discuss the quality of the fits.\n", - "\n", - "\n", - "**Solution.**\n", - "The code here is an example of where we define our own design matrix and fit parameters $\\beta$." - ] - }, - { - "cell_type": "code", - "execution_count": 31, - "id": "60d0051d", - "metadata": { - "collapsed": false, - "editable": true - }, - "outputs": [], - "source": [ - "import os\n", - "import numpy as np\n", - "import pandas as pd\n", - "import matplotlib.pyplot as plt\n", - "from sklearn.model_selection import train_test_split\n", - "\n", - "def save_fig(fig_id):\n", - " plt.savefig(image_path(fig_id) + \".png\", format='png')\n", - "\n", - "def R2(y_data, y_model):\n", - " return 1 - np.sum((y_data - y_model) ** 2) / np.sum((y_data - np.mean(y_data)) ** 2)\n", - "def MSE(y_data,y_model):\n", - " n = np.size(y_model)\n", - " return np.sum((y_data-y_model)**2)/n\n", - "\n", - "x = np.random.rand(100)\n", - "y = 2.0+5*x*x+0.1*np.random.randn(100)\n", - "\n", - "\n", - "# The design matrix now as function of a given polynomial\n", - "X = np.zeros((len(x),3))\n", - "X[:,0] = 1.0\n", - "X[:,1] = x\n", - "X[:,2] = x**2\n", - "# We split the data in test and training data\n", - "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2)\n", - "# matrix inversion to find beta\n", - "beta = np.linalg.inv(X_train.T @ X_train) @ X_train.T @ y_train\n", - "print(beta)\n", - "# and then make the prediction\n", - "ytilde = X_train @ beta\n", - "print(\"Training R2\")\n", - "print(R2(y_train,ytilde))\n", - "print(\"Training MSE\")\n", - "print(MSE(y_train,ytilde))\n", - "ypredict = X_test @ beta\n", - "print(\"Test R2\")\n", - "print(R2(y_test,ypredict))\n", - "print(\"Test MSE\")\n", - "print(MSE(y_test,ypredict))" - ] - }, - { - "cell_type": "markdown", - "id": "cb34894b", - "metadata": { - "editable": true - }, - "source": [ - "" - ] - }, - { - "cell_type": "markdown", - "id": "3d6116ae", - "metadata": { - "editable": true - }, - "source": [ - "## Exercise 3: Normalizing our data\n", - "\n", - "A much used approach before starting to train the data is to preprocess our\n", - "data. Normally the data may need a rescaling and/or may be sensitive\n", - "to extreme values. Scaling the data renders our inputs much more\n", - "suitable for the algorithms we want to employ.\n", - "\n", - "**Scikit-Learn** has several functions which allow us to rescale the\n", - "data, normally resulting in much better results in terms of various\n", - "accuracy scores. The **StandardScaler** function in **Scikit-Learn**\n", - "ensures that for each feature/predictor we study the mean value is\n", - "zero and the variance is one (every column in the design/feature\n", - "matrix). This scaling has the drawback that it does not ensure that\n", - "we have a particular maximum or minimum in our data set. Another\n", - "function included in **Scikit-Learn** is the **MinMaxScaler** which\n", - "ensures that all features are exactly between $0$ and $1$. The\n", - "\n", - "The **Normalizer** scales each data\n", - "point such that the feature vector has a euclidean length of one. In other words, it\n", - "projects a data point on the circle (or sphere in the case of higher dimensions) with a\n", - "radius of 1. This means every data point is scaled by a different number (by the\n", - "inverse of it’s length).\n", - "This normalization is often used when only the direction (or angle) of the data matters,\n", - "not the length of the feature vector.\n", - "\n", - "The **RobustScaler** works similarly to the StandardScaler in that it\n", - "ensures statistical properties for each feature that guarantee that\n", - "they are on the same scale. However, the RobustScaler uses the median\n", - "and quartiles, instead of mean and variance. This makes the\n", - "RobustScaler ignore data points that are very different from the rest\n", - "(like measurement errors). These odd data points are also called\n", - "outliers, and might often lead to trouble for other scaling\n", - "techniques.\n", - "\n", - "It also common to split the data in a **training** set and a **testing** set. A typical split is to use $80\\%$ of the data for training and the rest\n", - "for testing. This can be done as follows with our design matrix $\\boldsymbol{X}$ and data $\\boldsymbol{y}$ (remember to import **scikit-learn**)" - ] - }, - { - "cell_type": "code", - "execution_count": 32, - "id": "7ddb4563", - "metadata": { - "collapsed": false, - "editable": true - }, - "outputs": [], - "source": [ - "# split in training and test data\n", - "X_train, X_test, y_train, y_test = train_test_split(X,y,test_size=0.2)" - ] - }, - { - "cell_type": "markdown", - "id": "81b6d4d7", - "metadata": { - "editable": true - }, - "source": [ - "Then we can use the standard scaler to scale our data as" - ] - }, - { - "cell_type": "code", - "execution_count": 33, - "id": "b535878c", - "metadata": { - "collapsed": false, - "editable": true - }, - "outputs": [], - "source": [ - "scaler = StandardScaler()\n", - "scaler.fit(X_train)\n", - "X_train_scaled = scaler.transform(X_train)\n", - "X_test_scaled = scaler.transform(X_test)" - ] - }, - { - "cell_type": "markdown", - "id": "06075529", - "metadata": { - "editable": true - }, - "source": [ - "In this exercise we want you to to compute the MSE for the training\n", - "data and the test data as function of the complexity of a polynomial,\n", - "that is the degree of a given polynomial. We want you also to compute the $R2$ score as function of the complexity of the model for both training data and test data. You should also run the calculation with and without scaling. \n", - "\n", - "One of \n", - "the aims is to reproduce Figure 2.11 of [Hastie et al](https://github.com/CompPhysics/MLErasmus/blob/master/doc/Textbooks/elementsstat.pdf).\n", - "\n", - "Our data is defined by $x\\in [-3,3]$ with a total of for example $100$ data points." - ] - }, - { - "cell_type": "code", - "execution_count": 34, - "id": "c724a0b7", - "metadata": { - "collapsed": false, - "editable": true - }, - "outputs": [], - "source": [ - "np.random.seed()\n", - "n = 100\n", - "maxdegree = 14\n", - "# Make data set.\n", - "x = np.linspace(-3, 3, n).reshape(-1, 1)\n", - "y = np.exp(-x**2) + 1.5 * np.exp(-(x-2)**2)+ np.random.normal(0, 0.1, x.shape)" - ] - }, - { - "cell_type": "markdown", - "id": "146f8778", - "metadata": { - "editable": true - }, - "source": [ - "where $y$ is the function we want to fit with a given polynomial." - ] - }, - { - "cell_type": "markdown", - "id": "2d8e37f0", - "metadata": { - "editable": true - }, - "source": [ - "**a)**\n", - "Write a first code which sets up a design matrix $X$ defined by a fifth-order polynomial. Scale your data and split it in training and test data." - ] - }, - { - "cell_type": "markdown", - "id": "1de49116", - "metadata": { - "editable": true - }, - "source": [ - "**b)**\n", - "Perform an ordinary least squares and compute the means squared error and the $R2$ factor for the training data and the test data, with and without scaling." - ] - }, - { - "cell_type": "markdown", - "id": "10f2ca90", - "metadata": { - "editable": true - }, - "source": [ - "**c)**\n", - "Add now a model which allows you to make polynomials up to degree $15$. Perform a standard OLS fitting of the training data and compute the MSE and $R2$ for the training and test data and plot both test and training data MSE and $R2$ as functions of the polynomial degree. Compare what you see with Figure 2.11 of Hastie et al. Comment your results. For which polynomial degree do you find an optimal MSE (smallest value)?" - ] - }, - { - "cell_type": "markdown", - "id": "09143d06", - "metadata": { - "editable": true - }, - "source": [ - "## Exercise 4: Adding Ridge Regression\n", - "\n", - "This exercise is a continuation of exercise 2. We will use the same function to\n", - "generate our data set, still staying with a simple function $y(x)$\n", - "which we want to fit using linear regression, but now extending the\n", - "analysis to include the Ridge regression method.\n", - "\n", - "We will thus again generate our own dataset for a function $y(x)$ where \n", - "$x \\in [0,1]$ and defined by random numbers computed with the uniform\n", - "distribution. The function $y$ is a quadratic polynomial in $x$ with\n", - "added stochastic noise according to the normal distribution $\\cal{N}(0,1)$.\n", - "\n", - "The following simple Python instructions define our $x$ and $y$ values (with 100 data points)." - ] - }, - { - "cell_type": "code", - "execution_count": 35, - "id": "edb19108", - "metadata": { - "collapsed": false, - "editable": true - }, - "outputs": [], - "source": [ - "x = np.random.rand(100)\n", - "y = 2.0+5*x*x+0.1*np.random.randn(100)" - ] - }, - { - "cell_type": "markdown", - "id": "17f105e5", - "metadata": { - "editable": true - }, - "source": [ - "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)$. \n", - "\n", - "The code here allows you to perform your own Ridge calculation and\n", - "perform calculations for various values of the regularization\n", - "parameter $\\lambda$. This program can easily be extended upon." - ] - }, - { - "cell_type": "code", - "execution_count": 36, - "id": "7b138ad0", - "metadata": { - "collapsed": false, - "editable": true - }, - "outputs": [], - "source": [ - "import os\n", - "import numpy as np\n", - "import pandas as pd\n", - "import matplotlib.pyplot as plt\n", - "from sklearn.model_selection import train_test_split\n", - "from sklearn.preprocessing import StandardScaler\n", - "\n", - "def R2(y_data, y_model):\n", - " return 1 - np.sum((y_data - y_model) ** 2) / np.sum((y_data - np.mean(y_data)) ** 2)\n", - "def MSE(y_data,y_model):\n", - " n = np.size(y_model)\n", - " return np.sum((y_data-y_model)**2)/n\n", - "\n", - "\n", - "# A seed just to ensure that the random numbers are the same for every run.\n", - "# Useful for eventual debugging.\n", - "np.random.seed(3155)\n", - "\n", - "x = np.random.rand(100)\n", - "y = 2.0+5*x*x+0.1*np.random.randn(100)\n", - "\n", - "# number of features p (here degree of polynomial\n", - "p = 3\n", - "# The design matrix now as function of a given polynomial\n", - "X = np.zeros((len(x),p))\n", - "X[:,0] = 1.0\n", - "X[:,1] = x\n", - "X[:,2] = x*x\n", - "# We split the data in test and training data\n", - "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2)\n", - "\n", - "# matrix inversion to find beta\n", - "OLSbeta = np.linalg.inv(X_train.T @ X_train) @ X_train.T @ y_train\n", - "print(OLSbeta)\n", - "# and then make the prediction\n", - "ytildeOLS = X_train @ OLSbeta\n", - "print(\"Training R2 for OLS\")\n", - "print(R2(y_train,ytildeOLS))\n", - "print(\"Training MSE for OLS\")\n", - "print(MSE(y_train,ytildeOLS))\n", - "ypredictOLS = X_test @ OLSbeta\n", - "print(\"Test R2 for OLS\")\n", - "print(R2(y_test,ypredictOLS))\n", - "print(\"Test MSE OLS\")\n", - "print(MSE(y_test,ypredictOLS))\n", - "\n", - "# Repeat now for Ridge regression and various values of the regularization parameter\n", - "I = np.eye(p,p)\n", - "# Decide which values of lambda to use\n", - "nlambdas = 20\n", - "MSEPredict = np.zeros(nlambdas)\n", - "MSETrain = np.zeros(nlambdas)\n", - "lambdas = np.logspace(-4, 1, nlambdas)\n", - "for i in range(nlambdas):\n", - " lmb = lambdas[i]\n", - " Ridgebeta = np.linalg.inv(X_train.T @ X_train+lmb*I) @ X_train.T @ y_train\n", - " # and then make the prediction\n", - " ytildeRidge = X_train @ Ridgebeta\n", - " ypredictRidge = X_test @ Ridgebeta\n", - " MSEPredict[i] = MSE(y_test,ypredictRidge)\n", - " MSETrain[i] = MSE(y_train,ytildeRidge)\n", - "# Now plot the results\n", - "plt.figure()\n", - "plt.plot(np.log10(lambdas), MSETrain, label = 'MSE Ridge train')\n", - "plt.plot(np.log10(lambdas), MSEPredict, 'r--', label = 'MSE Ridge Test')\n", - "plt.xlabel('log10(lambda)')\n", - "plt.ylabel('MSE')\n", - "plt.legend()\n", - "plt.show()" - ] - }, - { - "cell_type": "markdown", - "id": "a054fbdb", - "metadata": { - "editable": true - }, - "source": [ - "Repeat the above but using the functionality of\n", - "**Scikit-Learn**. Compare your code with the results from\n", - "**Scikit-Learn**. Remember to run with the same random numbers for\n", - "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.\n", - "\n", - "Finally, using **Scikit-Learn** or your own code, compute also the mean square error, a risk metric corresponding to the expected value of the squared (quadratic) error defined as" - ] - }, - { - "cell_type": "markdown", - "id": "de552d99", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "MSE(\\hat{y},\\hat{\\tilde{y}}) = \\frac{1}{n}\n", - "\\sum_{i=0}^{n-1}(y_i-\\tilde{y}_i)^2,\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "032eb58d", - "metadata": { - "editable": true - }, - "source": [ - "and the $R^2$ score function.\n", - "If $\\tilde{\\hat{y}}_i$ is the predicted value of the $i-th$ sample and $y_i$ is the corresponding true value, then the score $R^2$ is defined as" - ] - }, - { - "cell_type": "markdown", - "id": "64c9dfdc", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "R^2(\\hat{y}, \\tilde{\\hat{y}}) = 1 - \\frac{\\sum_{i=0}^{n - 1} (y_i - \\tilde{y}_i)^2}{\\sum_{i=0}^{n - 1} (y_i - \\bar{y})^2},\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "209f8ab5", - "metadata": { - "editable": true - }, - "source": [ - "where we have defined the mean value of $\\hat{y}$ as" - ] - }, - { - "cell_type": "markdown", - "id": "5d8d7d88", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\bar{y} = \\frac{1}{n} \\sum_{i=0}^{n - 1} y_i.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "39f44aab", - "metadata": { - "editable": true - }, - "source": [ - "Discuss these quantities as functions of the variable $\\lambda$ in Ridge regression." - ] - }, - { - "cell_type": "markdown", - "id": "2d808310", - "metadata": { - "editable": true - }, - "source": [ - "## Exercise 5: Analytical exercises\n", - "\n", - "In this exercise we derive the expressions for various derivatives of\n", - "products of vectors and matrices. Such derivatives are central to the\n", - "optimization of various cost functions. Although we will often use\n", - "automatic differentiation in actual calculations, to be able to have\n", - "analytical expressions is extremely helpful in case we have simpler\n", - "derivatives as well as when we analyze various properties (like second\n", - "derivatives) of the chosen cost functions. Vectors are always written\n", - "as boldfaced lower case letters and matrices as upper case boldfaced\n", - "letters.\n", - "\n", - "Show that" - ] - }, - { - "cell_type": "markdown", - "id": "d3860398", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\frac{\\partial (\\boldsymbol{b}^T\\boldsymbol{a})}{\\partial \\boldsymbol{a}} = \\boldsymbol{b},\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "e35259b2", - "metadata": { - "editable": true - }, - "source": [ - "and" - ] - }, - { - "cell_type": "markdown", - "id": "6a0715bd", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\frac{\\partial (\\boldsymbol{a}^T\\boldsymbol{A}\\boldsymbol{a})}{\\partial \\boldsymbol{a}} = \\boldsymbol{a}^T(\\boldsymbol{A}+\\boldsymbol{A}^T),\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "de7eab0c", - "metadata": { - "editable": true - }, - "source": [ - "and" - ] - }, - { - "cell_type": "markdown", - "id": "bcd1bf38", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\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},\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "e5504de6", - "metadata": { - "editable": true - }, - "source": [ - "and finally find the second derivative of this function with respect to the vector $\\boldsymbol{s}$.\n", - "\n", - "**Hint**: In these exercises it is always useful to write out with summation indices the various quantities.\n", - "As an example, consider the function" - ] - }, - { - "cell_type": "markdown", - "id": "db3b8c04", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "f(\\boldsymbol{x}) =\\boldsymbol{A}\\boldsymbol{x},\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "b4cc3b0d", - "metadata": { - "editable": true - }, - "source": [ - "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$)" - ] - }, - { - "cell_type": "markdown", - "id": "74f2c9b1", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "f_i =\\sum_{j=0}^{n-1}a_{ij}x_j,\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "9e3b9624", - "metadata": { - "editable": true - }, - "source": [ - "which leads to" - ] - }, - { - "cell_type": "markdown", - "id": "2fd4399c", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\frac{\\partial f_i}{\\partial x_j}= a_{ij},\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "834d7f35", - "metadata": { - "editable": true - }, - "source": [ - "and written out in terms of the vector $\\boldsymbol{x}$ we have" - ] - }, - { - "cell_type": "markdown", - "id": "41e5fc6e", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\frac{\\partial f(\\boldsymbol{x})}{\\partial \\boldsymbol{x}}= \\boldsymbol{A}.\n", - "$$" - ] } ], "metadata": {}, diff --git a/doc/src/week35/exercisesweek35.do.txt b/doc/src/week35/exercisesweek35.do.txt new file mode 100644 index 000000000..2623cd834 --- /dev/null +++ b/doc/src/week35/exercisesweek35.do.txt @@ -0,0 +1,151 @@ +TITLE: Exercises week 35 +AUTHOR: FYS-STK3155/4155 +DATE: August 28-September 1, 2023 + + + + + +===== Exercise: making your own data and exploring scikit-learn ===== + + +We will generate our own dataset for a function $y(x)$ where $x \in [0,1]$ and defined by random numbers computed with the uniform distribution. The function $y$ is a quadratic polynomial in $x$ with added stochastic noise according to the normal distribution $\cal {N}(0,1)$. +The following simple Python instructions define our $x$ and $y$ values (with 100 data points). +!bc pycod +x = np.random.rand(100,1) +y = 2.0+5*x*x+0.1*np.random.randn(100,1) +!ec + +o Write your own code (following the examples under the "regression notes":"https://compphysics.github.io/MachineLearning/doc/LectureNotes/_build/html/chapter1.html") for computing the parametrization of the data set fitting a second-order polynomial. +o Use thereafter _scikit-learn_ (see again the examples in the regression slides) and compare with your own code. +o Using scikit-learn, compute also the mean square error, a risk metric corresponding to the expected value of the squared (quadratic) error defined as +!bt +\[ MSE(\bm{y},\bm{\tilde{y}}) = \frac{1}{n} +\sum_{i=0}^{n-1}(y_i-\tilde{y}_i)^2, +\] +!et +and the $R^2$ score function. +If $\tilde{\bm{y}}_i$ is the predicted value of the $i-th$ sample and $y_i$ is the corresponding true value, then the score $R^2$ is defined as +!bt +\[ +R^2(\bm{y}, \tilde{\bm{y}}) = 1 - \frac{\sum_{i=0}^{n - 1} (y_i - \tilde{y}_i)^2}{\sum_{i=0}^{n - 1} (y_i - \bar{y})^2}, +\] +!et +where we have defined the mean value of $\bm{y}$ as +!bt +\[ +\bar{y} = \frac{1}{n} \sum_{i=0}^{n - 1} y_i. +\] +!et +You can use the functionality included in scikit-learn. If you feel for it, you can use your own program and define functions which compute the above two functions. +Discuss the meaning of these results. Try also to vary the coefficient in front of the added stochastic noise term and discuss the quality of the fits. + +===== Exercise: Split data in test and training data ===== + +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. + +The aim is to reproduce Figure 2.11 of "Hastie et al":"https://github.com/CompPhysics/MLErasmus/blob/master/doc/Textbooks/elementsstat.pdf". + +Our data is defined by $x\in [-3,3]$ with a total of for example $n=100$ data points. You should try to vary the number of data points $n$ in your analysis. +!bc pycod +np.random.seed() +n = 100 +# 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) +!ec +where $y$ is the function we want to fit with a given polynomial. +!bsubex +Write a first code which sets up a design matrix $X$ defined by a fifth-order polynomial and split your data set in training and test data. +!esubex + +!bsubex +Write thereafter (using either _scikit-learn_ or your matrix inversion code using for example _numpy_) +and perform an ordinary least squares fitting and compute the mean squared error for the training data and the test data. These calculations should apply to a model given by a fifth-order polynomial. +!esubex + +!bsubex +Add now a model which allows you to make polynomials up to degree $15$. Perform a standard OLS fitting of the training data and compute the MSE for the training and test data and plot both test and training data MSE 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)? +!esubex + + + + + + + + + + + + + + + + + + + +===== Exercise: 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 +!bt +\[ +\frac{\partial (\bm{b}^T\bm{a})}{\partial \bm{a}} = \bm{b}, +\] +!et +and +!bt +\[ +\frac{\partial (\bm{a}^T\bm{A}\bm{a})}{\partial \bm{a}} = \bm{a}^T(\bm{A}+\bm{A}^T), +\] +!et +and +!bt +\[ +\frac{\partial \left(\bm{x}-\bm{A}\bm{s}\right)^T\left(\bm{x}-\bm{A}\bm{s}\right)}{\partial \bm{s}} = -2\left(\bm{x}-\bm{A}\bm{s}\right)^T\bm{A}, +\] +!et +and finally find the second derivative of this function with respect to the vector $\bm{s}$. + +_Hint_: In these exercises it is always useful to write out with summation indices the various quantities. +As an example, consider the function + +!bt +\[ +f(\bm{x}) =\bm{A}\bm{x}, +\] +!et +which reads for a specific component $f_i$ (we define the matrix $\bm{A}$ to have dimension $n\times n$ and the vector $\bm{x} to have length $n$) + +!bt +\[ +f_i =\sum_{j=0}^{n-1}a_{ij}x_j, +\] +!et +which leads to +!bt +\[ +\frac{\partial f_i}{\partial x_j}= a_{ij}, +\] +!et +and written out in terms of the vector $\bm{x}$ we have +!bt +\[ +\frac{\partial f(\bm{x})}{\partial \bm{x}}= \bm{A}. +\] +!et + + diff --git a/doc/src/week35/week35.do.txt b/doc/src/week35/week35.do.txt index 046c5ad2d..e4927e206 100644 --- a/doc/src/week35/week35.do.txt +++ b/doc/src/week35/week35.do.txt @@ -11,8 +11,8 @@ The main topics are: o Brief repetition from last week o Derivation of the equations for ordinary least squares o Discussion on how to prepare data and examples of applications of linear regression -o Mathematical interpretations of linear regression -o Ridge and Lasso regression and Singular Value Decomposition +o Material for the lecture on Thursday: Mathematical interpretations of linear regression +o Thursday: Ridge and Lasso regression and Singular Value Decomposition @@ -60,17 +60,23 @@ Similarly, "Mehta et al's article":"https://arxiv.org/abs/1803.08823" is also re Our data which we want to apply a machine learning method on, consist of a set of inputs $\bm{x}^T=[x_0,x_1,x_2,\dots,x_{n-1}]$ and the outputs we want to model $\bm{x}^T=[y_0,y_1,y_2,\dots,y_{n-1}]$. -We assumed also that the output data can be represented for a regression case by continuous function $f$ +We assume that the output data can be represented (for a regression case) by a continuous function $f$ through !bt \[ y_i=f(x_i)+\epsilon_i, \] !et +or in general +!bt +\[ +\bm{y}=f(\bm{x})+\bm{\epsilon}, +\] +!et -where $\epsilon_i$ represents some noise which is normally assumed to +where $\bm{\epsilon}$ represents some noise which is normally assumed to be distributed via a normal probability distribution with zero mean -value and a variance $\sigma_i^$. +value and a variance $\sigma^2$. In linear regression we approximate the unknown function with another continuous function $\tilde{\bm{y}}(\bm{x})$ which depends linearly on @@ -90,7 +96,7 @@ $\bm{\beta}$ as and in order to find the optimal parameters $\beta_i$ we defined a function which gives a measure of the spread between the values $y_i$ (which -represent output values we want to reproduce) and the parametrized +represent the output values we want to reproduce) and the parametrized values $\tilde{y}_i$, namely the so-called cost/loss function. @@ -136,7 +142,7 @@ C(\bm{\beta})=\frac{1}{n}\left\{\left(\bm{y}-\bm{X}\bm{\beta}\right)^T\left(\bm{ \] !et 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 +When linking (see the discussions next week) with the maximum likelihood approach below, we will indeed interpret $y_i$ as a mean value !bt \[ y_{i}=\langle y_i \rangle = \beta_0x_{i,0}+\beta_1x_{i,1}+\beta_2x_{i,2}+\dots+\beta_{n-1}x_{i,n-1}+\epsilon_i, @@ -171,7 +177,7 @@ which results in \frac{\partial C(\bm{\beta})}{\partial \beta_j} = -\frac{2}{n}\left[ \sum_{i=0}^{n-1}x_{ij}\left(y_i-\beta_0x_{i,0}-\beta_1x_{i,1}-\beta_2x_{i,2}-\dots-\beta_{n-1}x_{i,n-1}\right)\right]=0, \] !et -or in a matrix-vector form as +or in a matrix-vector form as (multiplying away the factor $-2/n$) !bt \[ \frac{\partial C(\bm{\beta})}{\partial \bm{\beta}} = 0 = \bm{X}^T\left( \bm{y}-\bm{X}\bm{\beta}\right). @@ -495,8 +501,8 @@ We list here some other useful relations we may encounter (recall that vectors a !split ===== 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 +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 parameters $\bm{\beta}$. Using the above expression for derivatives of vectors and matrices, we find that the second derivative of the mean squared error as cost function is, @@ -555,7 +561,7 @@ meaning that the solution for $\bm{\beta}$ is the one which minimizes the residu !split -===== Examples relevant for the exercises ===== +===== Example relevant for the exercises ===== In order to understand the relation among the predictors $p$, the set of data $n$ and the target (outcome, output etc) $\bm{y}$, @@ -566,26 +572,17 @@ We assume our data can represented by a fourth-order polynomial. For the $i$th c \tilde{y}_i = \beta_0+\beta_1x_i+\beta_2x_i^2+\beta_3x_i^3+\beta_4x_i^4. \] !et -we have five predictors, that is the intercept $\beta_0$and the other terms $\beta_i$. -This gives $p=0,1,2,3,4$. Furthermore we have $n$ entries for each predictor. It means that our design matrix is a +we have five predictors/features. The first is the intercept $\beta_0$. The other terms are $\beta_i$ with $i=1,2,3,4$. Furthermore we have $n$ entries for each predictor. It means that our design matrix is a $p\times n$ matrix $\bm{X}$. -Here the predictors are based on a model we have made. A popular data set which is widely encountered in ML applications is the -so-called "credit card default data from Taiwan":"https://www.sciencedirect.com/science/article/pii/S0957417407006719?via%3Dihub". The data set contains data on $n=30000$ credit card holders with predictors like gender, marital status, age, profession, education, etc. In total there are $24$ such predictors or attributes leading to a design matrix of dimensionality $24 \times 30000$. This is however a classification problem and we will come back to it when we discuss Logistic Regression. - - - - - !split ===== Own code for Ordinary Least Squares ===== -It is rather straightforward to implement the matrix inversion and obtain the parameters $\bm{\beta}$. After having defined the matrix $\bm{X}$ we simply need to -write +It is rather straightforward to implement the matrix inversion and obtain the parameters $\bm{\beta}$. After having defined the matrix $\bm{X}$ and the outputs $\bm{y}$ we have !bc pycod # matrix inversion to find beta -beta = np.linalg.inv(X.T.dot(X)).dot(X.T).dot(Energies) +beta = (np.linalg.inv(X.T @ X) @ X.T ) @ y # and then make the prediction ytilde = X @ beta !ec @@ -595,21 +592,6 @@ fit = np.linalg.lstsq(X, Energies, rcond =None)[0] ytildenp = np.dot(fit,X.T) !ec -And finally we plot our fit with and compare with data -!bc pycod -Masses['Eapprox'] = ytilde -# Generate a plot comparing the experimental with the fitted values values. -fig, ax = plt.subplots() -ax.set_xlabel(r'$A = N + Z$') -ax.set_ylabel(r'$E_\mathrm{bind}\,/\mathrm{MeV}$') -ax.plot(Masses['A'], Masses['Ebinding'], alpha=0.7, lw=2, - label='Ame2016') -ax.plot(Masses['A'], Masses['Eapprox'], alpha=0.7, lw=2, c='m', - label='Fit') -ax.legend() -save_fig("Masses2016OLS") -plt.show() -!ec !split ===== Adding error analysis and training set up ===== @@ -661,7 +643,7 @@ but now splitting the data into a training set and a test set. !split -===== Examples ===== +===== The complete code with a simple data set ===== !bc pycod import os @@ -681,11 +663,13 @@ 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)) +# The design matrix now as function of a fourth-order polynomial +X = np.zeros((len(x),5)) X[:,0] = 1.0 X[:,1] = x X[:,2] = x**2 +X[:,3] = x**3 +X[:,4] = x**4 # 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 @@ -731,159 +715,6 @@ it interfaces easily with _tensorflow_ and other libraries, we normally recommend using the latter functionality. -!split -===== The Boston housing data example ===== - -The Boston housing -data set was originally a part of UCI Machine Learning Repository -and has been removed now. The data set is now included in _Scikit-Learn_'s -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 - o CRIM: Per capita crime rate by town - o ZN: Proportion of residential land zoned for lots over 25000 square feet - o INDUS: Proportion of non-retail business acres per town - o CHAS: Charles River dummy variable (= 1 if tract bounds river; 0 otherwise) - o NOX: Nitric oxide concentration (parts per 10 million) - o RM: Average number of rooms per dwelling - o AGE: Proportion of owner-occupied units built prior to 1940 - o DIS: Weighted distances to five Boston employment centers - o RAD: Index of accessibility to radial highways - o TAX: Full-value property tax rate per USD10000 - o B: $1000(Bk - 0.63)^2$, where $Bk$ is the proportion of [people of African American descent] by town - o LSTAT: Percentage of lower status of the population - o MEDV: Median value of owner-occupied homes in USD 1000s - -!split -===== Housing data, the code ===== -We start by importing the libraries -!bc pycod -import numpy as np -import matplotlib.pyplot as plt - -import pandas as pd -import seaborn as sns -!ec -and load the Boston Housing DataSet from _Scikit-Learn_ - - -!bc pycod -from sklearn.datasets import load_boston - -boston_dataset = load_boston() - -# boston_dataset is a dictionary -# let's check what it contains -boston_dataset.keys() -!ec -Then we invoke Pandas -!bc pycod -boston = pd.DataFrame(boston_dataset.data, columns=boston_dataset.feature_names) -boston.head() -boston['MEDV'] = boston_dataset.target -!ec -and preprocess the data -!bc pycod -# check for missing values in all the columns -boston.isnull().sum() -!ec -We can then visualize the data -!bc pycod -# 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() -!ec - -It is now useful to look at the correlation matrix -!bc pycod -# 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) -!ec -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 - -!bc pycod -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') -!ec -Now we start training our model -!bc pycod -X = pd.DataFrame(np.c_[boston['LSTAT'], boston['RM']], columns = ['LSTAT','RM']) -Y = boston['MEDV'] -!ec -We split the data into training and test sets - -!bc pycod -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) -!ec -Then we use the linear regression functionality from _Scikit-Learn_ -!bc pycod -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)) -!ec - -!bc pycod -# plotting the y_test vs y_pred -# ideally should have been a straight line -plt.scatter(Y_test, y_test_predict) -plt.show() -!ec - !split ===== Reducing the number of degrees of freedom, overarching view ===== @@ -1043,10 +874,9 @@ where $\min(x_j)$ and $\max(x_j)$ return the minimum and maximum value of $x_j$ !split ===== Testing the Means Squared Error as function of Complexity ===== + One of the aims is to reproduce Figure 2.11 of "Hastie et al":"https://github.com/CompPhysics/MLErasmus/blob/master/doc/Textbooks/elementsstat.pdf". -We will also use Ridge and Lasso regression. - Our data is defined by $x\in [-3,3]$ with a total of for example $100$ data points. !bc pycod @@ -1059,11 +889,11 @@ y = np.exp(-x**2) + 1.5 * np.exp(-(x-2)**2)+ np.random.normal(0, 0.1, x.shape) !ec 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. +Write a first code which sets up a design matrix $X$ defined by a fourth-order polynomial. Scale your data and split it in training and test data. !bc pycod import matplotlib.pyplot as plt import numpy as np -from sklearn.linear_model import LinearRegression, Ridge, Lasso +from sklearn.linear_model import LinearRegression from sklearn.preprocessing import PolynomialFeatures from sklearn.model_selection import train_test_split from sklearn.pipeline import make_pipeline @@ -1102,7 +932,7 @@ plt.show() !split -===== More preprocessing examples, Franke function and regression ===== +===== More preprocessing examples, two-dimensional example, the Franke function ===== !bc pycod # Common imports @@ -1202,6 +1032,488 @@ print("R2 score for scaled data: {:.2f}".format(clf.score(X_test_scaled,y_test) + +!split +===== To think about, first part ===== + +When you are comparing your own code with for example _Scikit-Learn_'s +library, there are some technicalities to keep in mind. The examples +here demonstrate some of these aspects with potential pitfalls. + +The discussion here focuses on the role of the intercept, how we can +set up the design matrix, what scaling we should use and other topics +which tend confuse us. + + + +The intercept can be interpreted as the expected value of our +target/output variables when all other predictors are set to zero. +Thus, if we cannot assume that the expected outputs/targets are zero +when all predictors are zero (the columns in the design matrix), it +may be a bad idea to implement a model which penalizes the intercept. +Furthermore, in for example Ridge and Lasso regression, the default solutions +from the library _Scikit-Learn_ (when not shrinking $\beta_0$) for the unknown parameters +$\bm{\beta}$, are derived under the assumption that both $\bm{y}$ and +$\bm{X}$ are zero centered, that is we subtract the mean values. + + +!split +===== More thinking ===== + + +If our predictors represent different scales, then it is important to +standardize the design matrix $\bm{X}$ by subtracting the mean of each +column from the corresponding column and dividing the column with its +standard deviation. Most machine learning libraries do this as a default. This means that if you compare your code with the results from a given library, +the results may differ. + +The +"Standadscaler":"https://scikit-learn.org/stable/modules/generated/sklearn.preprocessing.StandardScaler.html" +function in _Scikit-Learn_ does this for us. For the data sets we +have been studying in our various examples, the data are in many cases +already scaled and there is no need to scale them. You as a user of different machine learning algorithms, should always perform a +survey of your data, with a critical assessment of them in case you need to scale the data. + +If you need to scale the data, not doing so will give an *unfair* +penalization of the parameters since their magnitude depends on the +scale of their corresponding predictor. + +Suppose as an example that you +you have an input variable given by the heights of different persons. +Human height might be measured in inches or meters or +kilometers. If measured in kilometers, a standard linear regression +model with this predictor would probably give a much bigger +coefficient term, than if measured in millimeters. +This can clearly lead to problems in evaluating the cost/loss functions. + + +!split +===== Still thinking ===== + +Keep in mind that when you transform your data set before training a model, the same transformation needs to be done +on your eventual new data set before making a prediction. If we translate this into a Python code, it would could be implemented as follows + +!bc pycod +#Model training, we compute the mean value of y and X +y_train_mean = np.mean(y_train) +X_train_mean = np.mean(X_train,axis=0) +X_train = X_train - X_train_mean +y_train = y_train - y_train_mean + +# The we fit our model with the training data +trained_model = some_model.fit(X_train,y_train) + + +#Model prediction, we need also to transform our data set used for the prediction. +X_test = X_test - X_train_mean #Use mean from training data +y_pred = trained_model(X_test) +y_pred = y_pred + y_train_mean +!ec + + +!split +===== What does centering (subtracting the mean values) mean mathematically? ===== + + +Let us try to understand what this may imply mathematically when we +subtract the mean values, also known as *zero centering*. For +simplicity, we will focus on ordinary regression, as done in the above example. + +The cost/loss function for regression is +!bt +\[ +C(\beta_0, \beta_1, ... , \beta_{p-1}) = \frac{1}{n}\sum_{i=0}^{n} \left(y_i - \beta_0 - \sum_{j=1}^{p-1} X_{ij}\beta_j\right)^2,. +\] +!et +Recall also that we use the squared value since this leads to an increase of the penalty for higher differences between predicted and output/target values. + +What we have done is to single out the $\beta_0$ term in the definition of the mean squared error (MSE). +The design matrix +$X$ does in this case not contain any intercept column. +When we take the derivative with respect to $\beta_0$, we want the derivative to obey +!bt +\[ +\frac{\partial C}{\partial \beta_j} = 0, +\] +!et + +for all $j$. For $\beta_0$ we have + +!bt +\[ +\frac{\partial C}{\partial \beta_0} = -\frac{2}{n}\sum_{i=0}^{n-1} \left(y_i - \beta_0 - \sum_{j=1}^{p-1} X_{ij} \beta_j\right). +\] +!et +Multiplying away the constant $2/n$, we obtain +!bt +\[ +\sum_{i=0}^{n-1} \beta_0 = \sum_{i=0}^{n-1}y_i - \sum_{i=0}^{n-1} \sum_{j=1}^{p-1} X_{ij} \beta_j. +\] +!et + +!split +===== Further Manipulations ===== + + +Let us special first to the case where we have only two parameters $\beta_0$ and $\beta_1$. +Our result for $\beta_0$ simplifies then to +!bt +\[ +n\beta_0 = \sum_{i=0}^{n-1}y_i - \sum_{i=0}^{n-1} X_{i1} \beta_1. +\] +!et +We obtain then +!bt +\[ +\beta_0 = \frac{1}{n}\sum_{i=0}^{n-1}y_i - \beta_1\frac{1}{n}\sum_{i=0}^{n-1} X_{i1}. +\] +!et +If we define +!bt +\[ +\mu_1=\frac{1}{n}\sum_{i=0}^{n-1} (X_{i1}, +\] +!et +and if we define the mean value of the outputs as +!bt +\[ +\mu_y=\frac{1}{n}\sum_{i=0}^{n-1}y_i, +\] +!et +we have +!bt +\[ +\beta_0 = \mu_y - \beta_1\mu_{1}. +\] +!et +In the general case, that is we have more parameters than $\beta_0$ and $\beta_1$, we have +!bt +\[ +\beta_0 = \frac{1}{n}\sum_{i=0}^{n-1}y_i - \frac{1}{n}\sum_{i=0}^{n-1}\sum_{j=1}^{p-1} X_{ij}\beta_j. +\] +!et + + + +Replacing $y_i$ with $y_i - y_i - \overline{\bm{y}}$ and centering also our design matrix results in a cost function (in vector-matrix disguise) +!bt +\[ +C(\boldsymbol{\beta}) = (\boldsymbol{\tilde{y}} - \tilde{X}\boldsymbol{\beta})^T(\boldsymbol{\tilde{y}} - \tilde{X}\boldsymbol{\beta}). +\] +!et + +!split +===== Wrapping it up ===== + +If we minimize with respect to $\bm{\beta}$ we have then + +!bt +\[ +\hat{\bm{\beta}} = (\tilde{X}^T\tilde{X})^{-1}\tilde{X}^T\boldsymbol{\tilde{y}}, +\] +!et + +where $\boldsymbol{\tilde{y}} = \boldsymbol{y} - \overline{\bm{y}}$ +and $\tilde{X}_{ij} = X_{ij} - \frac{1}{n}\sum_{k=0}^{n-1}X_{kj}$. + +For Ridge regression we need to add $\lambda \boldsymbol{\beta}^T\boldsymbol{\beta}$ to the cost function and get then +!bt +\[ +\hat{\bm{\beta}} = (\tilde{X}^T\tilde{X} + \lambda I)^{-1}\tilde{X}^T\boldsymbol{\tilde{y}}. +\] +!et + +What does this mean? And why do we insist on all this? Let us look at some examples. + + + +!split +===== Linear Regression code, Intercept handling first ===== + +This code shows a simple first-order fit to a data set using the above transformed data, where we consider the role of the intercept first, by either excluding it or including it (*code example thanks to Øyvind Sigmundson Schøyen*). Here our scaling of the data is done by subtracting the mean values only. +Note also that we do not split the data into training and test. + +!bc pycod +import numpy as np +import matplotlib.pyplot as plt + +from sklearn.linear_model import LinearRegression + + +np.random.seed(2021) + +def MSE(y_data,y_model): + n = np.size(y_model) + return np.sum((y_data-y_model)**2)/n + + +def fit_beta(X, y): + return np.linalg.pinv(X.T @ X) @ X.T @ y + + +true_beta = [2, 0.5, 3.7] + +x = np.linspace(0, 1, 11) +y = np.sum( + np.asarray([x ** p * b for p, b in enumerate(true_beta)]), axis=0 +) + 0.1 * np.random.normal(size=len(x)) + +degree = 3 +X = np.zeros((len(x), degree)) + +# Include the intercept in the design matrix +for p in range(degree): + X[:, p] = x ** p + +beta = fit_beta(X, y) + +# Intercept is included in the design matrix +skl = LinearRegression(fit_intercept=False).fit(X, y) + +print(f"True beta: {true_beta}") +print(f"Fitted beta: {beta}") +print(f"Sklearn fitted beta: {skl.coef_}") +ypredictOwn = X @ beta +ypredictSKL = skl.predict(X) +print(f"MSE with intercept column") +print(MSE(y,ypredictOwn)) +print(f"MSE with intercept column from SKL") +print(MSE(y,ypredictSKL)) + + +plt.figure() +plt.scatter(x, y, label="Data") +plt.plot(x, X @ beta, label="Fit") +plt.plot(x, skl.predict(X), label="Sklearn (fit_intercept=False)") + + +# Do not include the intercept in the design matrix +X = np.zeros((len(x), degree - 1)) + +for p in range(degree - 1): + X[:, p] = x ** (p + 1) + +# Intercept is not included in the design matrix +skl = LinearRegression(fit_intercept=True).fit(X, y) + +# Use centered values for X and y when computing coefficients +y_offset = np.average(y, axis=0) +X_offset = np.average(X, axis=0) + +beta = fit_beta(X - X_offset, y - y_offset) +intercept = np.mean(y_offset - X_offset @ beta) + +print(f"Manual intercept: {intercept}") +print(f"Fitted beta (wiothout intercept): {beta}") +print(f"Sklearn intercept: {skl.intercept_}") +print(f"Sklearn fitted beta (without intercept): {skl.coef_}") +ypredictOwn = X @ beta +ypredictSKL = skl.predict(X) +print(f"MSE with Manual intercept") +print(MSE(y,ypredictOwn+intercept)) +print(f"MSE with Sklearn intercept") +print(MSE(y,ypredictSKL)) + +plt.plot(x, X @ beta + intercept, "--", label="Fit (manual intercept)") +plt.plot(x, skl.predict(X), "--", label="Sklearn (fit_intercept=True)") +plt.grid() +plt.legend() + +plt.show() + +!ec + +The intercept is the value of our output/target variable +when all our features are zero and our function crosses the $y$-axis (for a one-dimensional case). + +Printing the MSE, we see first that both methods give the same MSE, as +they should. However, when we move to for example Ridge regression, +the way we treat the intercept may give a larger or smaller MSE, +meaning that the MSE can be penalized by the value of the +intercept. Not including the intercept in the fit, means that the +regularization term does not include $\beta_0$. For different values +of $\lambda$, this may lead to differeing MSE values. + +To remind the reader, the regularization term, with the intercept in Ridge regression is given by +!bt +\[ +\lambda \vert\vert \bm{\beta} \vert\vert_2^2 = \lambda \sum_{j=0}^{p-1}\beta_j^2, +\] +!et +but when we take out the intercept, this equation becomes +!bt +\[ +\lambda \vert\vert \bm{\beta} \vert\vert_2^2 = \lambda \sum_{j=1}^{p-1}\beta_j^2. +\] +!et + +For Lasso regression we have +!bt +\[ +\lambda \vert\vert \bm{\beta} \vert\vert_1 = \lambda \sum_{j=1}^{p-1}\vert\beta_j\vert. +\] +!et + +It means that, when scaling the design matrix and the outputs/targets, by subtracting the mean values, we have an optimization problem which is not penalized by the intercept. The MSE value can then be smaller since it focuses only on the remaining quantities. If we however bring back the intercept, we will get an MSE which then contains the intercept. This becomes more important when we discuss Ridge and Lasso regression next week. + + + +!split +===== The Boston housing data example ===== + +The Boston housing +data set was originally a part of UCI Machine Learning Repository +and has been removed now. The data set is now included in _Scikit-Learn_'s +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 + o CRIM: Per capita crime rate by town + o ZN: Proportion of residential land zoned for lots over 25000 square feet + o INDUS: Proportion of non-retail business acres per town + o CHAS: Charles River dummy variable (= 1 if tract bounds river; 0 otherwise) + o NOX: Nitric oxide concentration (parts per 10 million) + o RM: Average number of rooms per dwelling + o AGE: Proportion of owner-occupied units built prior to 1940 + o DIS: Weighted distances to five Boston employment centers + o RAD: Index of accessibility to radial highways + o TAX: Full-value property tax rate per USD10000 + o B: $1000(Bk - 0.63)^2$, where $Bk$ is the proportion of [people of African American descent] by town + o LSTAT: Percentage of lower status of the population + o MEDV: Median value of owner-occupied homes in USD 1000s + +!split +===== Housing data, the code ===== +We start by importing the libraries +!bc pycod +import numpy as np +import matplotlib.pyplot as plt + +import pandas as pd +import seaborn as sns +!ec +and load the Boston Housing DataSet from _Scikit-Learn_ + + +!bc pycod +from sklearn.datasets import load_boston + +boston_dataset = load_boston() + +# boston_dataset is a dictionary +# let's check what it contains +boston_dataset.keys() +!ec +Then we invoke Pandas +!bc pycod +boston = pd.DataFrame(boston_dataset.data, columns=boston_dataset.feature_names) +boston.head() +boston['MEDV'] = boston_dataset.target +!ec +and preprocess the data +!bc pycod +# check for missing values in all the columns +boston.isnull().sum() +!ec +We can then visualize the data +!bc pycod +# 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() +!ec + +It is now useful to look at the correlation matrix +!bc pycod +# 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) +!ec +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 + +!bc pycod +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') +!ec +Now we start training our model +!bc pycod +X = pd.DataFrame(np.c_[boston['LSTAT'], boston['RM']], columns = ['LSTAT','RM']) +Y = boston['MEDV'] +!ec +We split the data into training and test sets + +!bc pycod +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) +!ec +Then we use the linear regression functionality from _Scikit-Learn_ +!bc pycod +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)) +!ec + +!bc pycod +# plotting the y_test vs y_pred +# ideally should have been a straight line +plt.scatter(Y_test, y_test_predict) +plt.show() +!ec + + + + !split ===== Material for lecture Thursday, August 31 ===== @@ -2509,435 +2821,6 @@ and reordering we have !et 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":"https://cvxopt.org/". We will discuss this later. -!split -===== Exercises for week 35 ===== -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). - -===== Exercise: Setting up various Python environments ===== - -The first exercise here is of a mere technical art. We want you to have -* git as a version control software and to establish a user account on a provider like GitHub. Other providers like GitLab etc are equally fine. You can also use the University of Oslo "GitHub facilities":"https://www.uio.no/tjenester/it/maskin/filer/versjonskontroll/github.html". -* 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 - -o pip install numpy scipy matplotlib ipython scikit-learn sympy pandas pillow - -For _Tensorflow_, we recommend following the instructions in the text of -"Aurelien Geron, Hands‑On Machine Learning with Scikit‑Learn and TensorFlow, O'Reilly":"http://shop.oreilly.com/product/0636920052289.do" - -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 - -o brew install python3 - -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 - -o sudo apt-get install python3 (or python for Python2.7) - -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 - -* "Anaconda":"https://docs.anaconda.com/", - -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_. - -* "Enthought canopy":"https://www.enthought.com/product/canopy/" - -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: 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). -!bc pycod -x = np.random.rand(100,1) -y = 2.0+5*x*x+0.1*np.random.randn(100,1) -!ec - -o Write your own code (following the examples under the "regression notes":"https://compphysics.github.io/MachineLearning/doc/LectureNotes/_build/html/chapter1.html") for computing the parametrization of the data set fitting a second-order polynomial. -o 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 URL:"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 URL:"https://compphysics.github.io/MachineLearning/doc/LectureNotes/_build/html/chapter3.html#more-on-rescaling-data". -o Using scikit-learn, compute also the mean square error, a risk metric corresponding to the expected value of the squared (quadratic) error defined as -!bt -\[ MSE(\bm{y},\bm{\tilde{y}}) = \frac{1}{n} -\sum_{i=0}^{n-1}(y_i-\tilde{y}_i)^2, -\] -!et -and the $R^2$ score function. -If $\tilde{\bm{y}}_i$ is the predicted value of the $i-th$ sample and $y_i$ is the corresponding true value, then the score $R^2$ is defined as -!bt -\[ -R^2(\bm{y}, \tilde{\bm{y}}) = 1 - \frac{\sum_{i=0}^{n - 1} (y_i - \tilde{y}_i)^2}{\sum_{i=0}^{n - 1} (y_i - \bar{y})^2}, -\] -!et -where we have defined the mean value of $\bm{y}$ as -!bt -\[ -\bar{y} = \frac{1}{n} \sum_{i=0}^{n - 1} y_i. -\] -!et -You can use the functionality included in scikit-learn. If you feel for it, you can use your own program and define functions which compute the above two functions. -Discuss the meaning of these results. Try also to vary the coefficient in front of the added stochastic noise term and discuss the quality of the fits. - -!bsol -The code here is an example of where we define our own design matrix and fit parameters $\beta$. -!bc pycod -import os -import numpy as np -import pandas as pd -import matplotlib.pyplot as plt -from sklearn.model_selection import train_test_split - -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)) -!ec -!esol - - - -===== Exercise: Normalizing our data ===== - - -A much used approach before starting to train the data is to preprocess our -data. Normally the data may need a rescaling and/or may be sensitive -to extreme values. Scaling the data renders our inputs much more -suitable for the algorithms we want to employ. - -_Scikit-Learn_ has several functions which allow us to rescale the -data, normally resulting in much better results in terms of various -accuracy scores. The _StandardScaler_ function in _Scikit-Learn_ -ensures that for each feature/predictor we study the mean value is -zero and the variance is one (every column in the design/feature -matrix). This scaling has the drawback that it does not ensure that -we have a particular maximum or minimum in our data set. Another -function included in _Scikit-Learn_ is the _MinMaxScaler_ which -ensures that all features are exactly between $0$ and $1$. The - - -The _Normalizer_ scales each data -point such that the feature vector has a euclidean length of one. In other words, it -projects a data point on the circle (or sphere in the case of higher dimensions) with a -radius of 1. This means every data point is scaled by a different number (by the -inverse of it’s length). -This normalization is often used when only the direction (or angle) of the data matters, -not the length of the feature vector. - -The _RobustScaler_ works similarly to the StandardScaler in that it -ensures statistical properties for each feature that guarantee that -they are on the same scale. However, the RobustScaler uses the median -and quartiles, instead of mean and variance. This makes the -RobustScaler ignore data points that are very different from the rest -(like measurement errors). These odd data points are also called -outliers, and might often lead to trouble for other scaling -techniques. - - -It also common to split the data in a _training_ set and a _testing_ set. A typical split is to use $80\%$ of the data for training and the rest -for testing. This can be done as follows with our design matrix $\bm{X}$ and data $\bm{y}$ (remember to import _scikit-learn_) -!bc pycod -# split in training and test data -X_train, X_test, y_train, y_test = train_test_split(X,y,test_size=0.2) -!ec -Then we can use the standard scaler to scale our data as -!bc pycod -scaler = StandardScaler() -scaler.fit(X_train) -X_train_scaled = scaler.transform(X_train) -X_test_scaled = scaler.transform(X_test) -!ec - - -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":"https://github.com/CompPhysics/MLErasmus/blob/master/doc/Textbooks/elementsstat.pdf". - - - -Our data is defined by $x\in [-3,3]$ with a total of for example $100$ data points. -!bc pycod -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) -!ec -where $y$ is the function we want to fit with a given polynomial. -!bsubex -Write a first code which sets up a design matrix $X$ defined by a fifth-order polynomial. Scale your data and split it in training and test data. -!esubex - -!bsubex -Perform an ordinary least squares and compute the means squared error and the $R2$ factor for the training data and the test data, with and without scaling. -!esubex - -!bsubex -Add now a model which allows you to make polynomials up to degree $15$. Perform a standard OLS fitting of the training data and compute the MSE and $R2$ for the training and test data and plot both test and training data MSE and $R2$ as functions of the polynomial degree. Compare what you see with Figure 2.11 of Hastie et al. Comment your results. For which polynomial degree do you find an optimal MSE (smallest value)? - -!esubex - - - - - - - -===== Exercise: 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). -!bc pycod -x = np.random.rand(100) -y = 2.0+5*x*x+0.1*np.random.randn(100) -!ec - - -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. - -!bc pycod -import os -import numpy as np -import pandas as pd -import matplotlib.pyplot as plt -from sklearn.model_selection import train_test_split -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() -!ec - - - -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 -!bt -\[ MSE(\hat{y},\hat{\tilde{y}}) = \frac{1}{n} -\sum_{i=0}^{n-1}(y_i-\tilde{y}_i)^2, -\] -!et -and the $R^2$ score function. -If $\tilde{\hat{y}}_i$ is the predicted value of the $i-th$ sample and $y_i$ is the corresponding true value, then the score $R^2$ is defined as -!bt -\[ -R^2(\hat{y}, \tilde{\hat{y}}) = 1 - \frac{\sum_{i=0}^{n - 1} (y_i - \tilde{y}_i)^2}{\sum_{i=0}^{n - 1} (y_i - \bar{y})^2}, -\] -!et -where we have defined the mean value of $\hat{y}$ as -!bt -\[ -\bar{y} = \frac{1}{n} \sum_{i=0}^{n - 1} y_i. -\] -!et -Discuss these quantities as functions of the variable $\lambda$ in Ridge regression. - - - -===== Exercise: 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 -!bt -\[ -\frac{\partial (\bm{b}^T\bm{a})}{\partial \bm{a}} = \bm{b}, -\] -!et -and -!bt -\[ -\frac{\partial (\bm{a}^T\bm{A}\bm{a})}{\partial \bm{a}} = \bm{a}^T(\bm{A}+\bm{A}^T), -\] -!et -and -!bt -\[ -\frac{\partial \left(\bm{x}-\bm{A}\bm{s}\right)^T\left(\bm{x}-\bm{A}\bm{s}\right)}{\partial \bm{s}} = -2\left(\bm{x}-\bm{A}\bm{s}\right)^T\bm{A}, -\] -!et -and finally find the second derivative of this function with respect to the vector $\bm{s}$. - -_Hint_: In these exercises it is always useful to write out with summation indices the various quantities. -As an example, consider the function - -!bt -\[ -f(\bm{x}) =\bm{A}\bm{x}, -\] -!et -which reads for a specific component $f_i$ (we define the matrix $\bm{A}$ to have dimension $n\times n$ and the vector $\bm{x} to have length $n$) - -!bt -\[ -f_i =\sum_{j=0}^{n-1}a_{ij}x_j, -\] -!et -which leads to -!bt -\[ -\frac{\partial f_i}{\partial x_j}= a_{ij}, -\] -!et -and written out in terms of the vector $\bm{x}$ we have -!bt -\[ -\frac{\partial f(\bm{x})}{\partial \bm{x}}= \bm{A}. -\] -!et