diff --git a/doc/pub/week37/html/._week37-bs000.html b/doc/pub/week37/html/._week37-bs000.html index 90c36c573..a875d46ec 100644 --- a/doc/pub/week37/html/._week37-bs000.html +++ b/doc/pub/week37/html/._week37-bs000.html @@ -107,6 +107,10 @@ Automatically generated HTML file from DocOnce source ('Identifying Terms', 2, None, 'identifying-terms'), ('Wrapping it up', 2, None, 'wrapping-it-up'), ('Confidence Intervals', 2, None, 'confidence-intervals'), + ('Standard Approach based on the Normal Distribution', + 2, + None, + 'standard-approach-based-on-the-normal-distribution'), ('Resampling methods: Bootstrap background', 2, None, @@ -244,25 +248,26 @@ MathJax.Hub.Config({
  • Identifying Terms
  • Wrapping it up
  • Confidence Intervals
  • -
  • Resampling methods: Bootstrap background
  • -
  • Resampling methods: More Bootstrap background
  • -
  • Resampling methods: Bootstrap approach
  • -
  • Resampling methods: Bootstrap steps
  • -
  • Code example for the Bootstrap method
  • -
  • Plotting the Histogram
  • -
  • The bias-variance tradeoff
  • -
  • A way to Read the Bias-Variance Tradeoff
  • -
  • Example code for Bias-Variance tradeoff
  • -
  • Understanding what happens
  • -
  • Summing up
  • -
  • Another Example from Scikit-Learn's Repository
  • -
  • Various steps in cross-validation
  • -
  • How to set up the cross-validation for Ridge and/or Lasso
  • -
  • Cross-validation in brief
  • -
  • Code Example for Cross-validation and \( k \)-fold Cross-validation
  • -
  • More examples on bootstrap and cross-validation and errors
  • -
  • The same example but now with cross-validation
  • -
  • Cross-validation with Ridge
  • +
  • Standard Approach based on the Normal Distribution
  • +
  • Resampling methods: Bootstrap background
  • +
  • Resampling methods: More Bootstrap background
  • +
  • Resampling methods: Bootstrap approach
  • +
  • Resampling methods: Bootstrap steps
  • +
  • Code example for the Bootstrap method
  • +
  • Plotting the Histogram
  • +
  • The bias-variance tradeoff
  • +
  • A way to Read the Bias-Variance Tradeoff
  • +
  • Example code for Bias-Variance tradeoff
  • +
  • Understanding what happens
  • +
  • Summing up
  • +
  • Another Example from Scikit-Learn's Repository
  • +
  • Various steps in cross-validation
  • +
  • How to set up the cross-validation for Ridge and/or Lasso
  • +
  • Cross-validation in brief
  • +
  • Code Example for Cross-validation and \( k \)-fold Cross-validation
  • +
  • More examples on bootstrap and cross-validation and errors
  • +
  • The same example but now with cross-validation
  • +
  • Cross-validation with Ridge
  • @@ -321,7 +326,7 @@ MathJax.Hub.Config({
  • 9
  • 10
  • ...
  • -
  • 49
  • +
  • 50
  • »
  • diff --git a/doc/pub/week37/html/._week37-bs001.html b/doc/pub/week37/html/._week37-bs001.html index 525437987..bd1e8ecb4 100644 --- a/doc/pub/week37/html/._week37-bs001.html +++ b/doc/pub/week37/html/._week37-bs001.html @@ -107,6 +107,10 @@ Automatically generated HTML file from DocOnce source ('Identifying Terms', 2, None, 'identifying-terms'), ('Wrapping it up', 2, None, 'wrapping-it-up'), ('Confidence Intervals', 2, None, 'confidence-intervals'), + ('Standard Approach based on the Normal Distribution', + 2, + None, + 'standard-approach-based-on-the-normal-distribution'), ('Resampling methods: Bootstrap background', 2, None, @@ -244,25 +248,26 @@ MathJax.Hub.Config({
  • Identifying Terms
  • Wrapping it up
  • Confidence Intervals
  • -
  • Resampling methods: Bootstrap background
  • -
  • Resampling methods: More Bootstrap background
  • -
  • Resampling methods: Bootstrap approach
  • -
  • Resampling methods: Bootstrap steps
  • -
  • Code example for the Bootstrap method
  • -
  • Plotting the Histogram
  • -
  • The bias-variance tradeoff
  • -
  • A way to Read the Bias-Variance Tradeoff
  • -
  • Example code for Bias-Variance tradeoff
  • -
  • Understanding what happens
  • -
  • Summing up
  • -
  • Another Example from Scikit-Learn's Repository
  • -
  • Various steps in cross-validation
  • -
  • How to set up the cross-validation for Ridge and/or Lasso
  • -
  • Cross-validation in brief
  • -
  • Code Example for Cross-validation and \( k \)-fold Cross-validation
  • -
  • More examples on bootstrap and cross-validation and errors
  • -
  • The same example but now with cross-validation
  • -
  • Cross-validation with Ridge
  • +
  • Standard Approach based on the Normal Distribution
  • +
  • Resampling methods: Bootstrap background
  • +
  • Resampling methods: More Bootstrap background
  • +
  • Resampling methods: Bootstrap approach
  • +
  • Resampling methods: Bootstrap steps
  • +
  • Code example for the Bootstrap method
  • +
  • Plotting the Histogram
  • +
  • The bias-variance tradeoff
  • +
  • A way to Read the Bias-Variance Tradeoff
  • +
  • Example code for Bias-Variance tradeoff
  • +
  • Understanding what happens
  • +
  • Summing up
  • +
  • Another Example from Scikit-Learn's Repository
  • +
  • Various steps in cross-validation
  • +
  • How to set up the cross-validation for Ridge and/or Lasso
  • +
  • Cross-validation in brief
  • +
  • Code Example for Cross-validation and \( k \)-fold Cross-validation
  • +
  • More examples on bootstrap and cross-validation and errors
  • +
  • The same example but now with cross-validation
  • +
  • Cross-validation with Ridge
  • @@ -309,7 +314,7 @@ Recommended Reading:
  • 10
  • 11
  • ...
  • -
  • 49
  • +
  • 50
  • »
  • diff --git a/doc/pub/week37/html/._week37-bs002.html b/doc/pub/week37/html/._week37-bs002.html index 75d4e4db3..e72847e92 100644 --- a/doc/pub/week37/html/._week37-bs002.html +++ b/doc/pub/week37/html/._week37-bs002.html @@ -107,6 +107,10 @@ Automatically generated HTML file from DocOnce source ('Identifying Terms', 2, None, 'identifying-terms'), ('Wrapping it up', 2, None, 'wrapping-it-up'), ('Confidence Intervals', 2, None, 'confidence-intervals'), + ('Standard Approach based on the Normal Distribution', + 2, + None, + 'standard-approach-based-on-the-normal-distribution'), ('Resampling methods: Bootstrap background', 2, None, @@ -244,25 +248,26 @@ MathJax.Hub.Config({
  • Identifying Terms
  • Wrapping it up
  • Confidence Intervals
  • -
  • Resampling methods: Bootstrap background
  • -
  • Resampling methods: More Bootstrap background
  • -
  • Resampling methods: Bootstrap approach
  • -
  • Resampling methods: Bootstrap steps
  • -
  • Code example for the Bootstrap method
  • -
  • Plotting the Histogram
  • -
  • The bias-variance tradeoff
  • -
  • A way to Read the Bias-Variance Tradeoff
  • -
  • Example code for Bias-Variance tradeoff
  • -
  • Understanding what happens
  • -
  • Summing up
  • -
  • Another Example from Scikit-Learn's Repository
  • -
  • Various steps in cross-validation
  • -
  • How to set up the cross-validation for Ridge and/or Lasso
  • -
  • Cross-validation in brief
  • -
  • Code Example for Cross-validation and \( k \)-fold Cross-validation
  • -
  • More examples on bootstrap and cross-validation and errors
  • -
  • The same example but now with cross-validation
  • -
  • Cross-validation with Ridge
  • +
  • Standard Approach based on the Normal Distribution
  • +
  • Resampling methods: Bootstrap background
  • +
  • Resampling methods: More Bootstrap background
  • +
  • Resampling methods: Bootstrap approach
  • +
  • Resampling methods: Bootstrap steps
  • +
  • Code example for the Bootstrap method
  • +
  • Plotting the Histogram
  • +
  • The bias-variance tradeoff
  • +
  • A way to Read the Bias-Variance Tradeoff
  • +
  • Example code for Bias-Variance tradeoff
  • +
  • Understanding what happens
  • +
  • Summing up
  • +
  • Another Example from Scikit-Learn's Repository
  • +
  • Various steps in cross-validation
  • +
  • How to set up the cross-validation for Ridge and/or Lasso
  • +
  • Cross-validation in brief
  • +
  • Code Example for Cross-validation and \( k \)-fold Cross-validation
  • +
  • More examples on bootstrap and cross-validation and errors
  • +
  • The same example but now with cross-validation
  • +
  • Cross-validation with Ridge
  • @@ -298,7 +303,7 @@ MathJax.Hub.Config({
  • 11
  • 12
  • ...
  • -
  • 49
  • +
  • 50
  • »
  • diff --git a/doc/pub/week37/html/._week37-bs003.html b/doc/pub/week37/html/._week37-bs003.html index b59aaa0c6..4b76ff135 100644 --- a/doc/pub/week37/html/._week37-bs003.html +++ b/doc/pub/week37/html/._week37-bs003.html @@ -107,6 +107,10 @@ Automatically generated HTML file from DocOnce source ('Identifying Terms', 2, None, 'identifying-terms'), ('Wrapping it up', 2, None, 'wrapping-it-up'), ('Confidence Intervals', 2, None, 'confidence-intervals'), + ('Standard Approach based on the Normal Distribution', + 2, + None, + 'standard-approach-based-on-the-normal-distribution'), ('Resampling methods: Bootstrap background', 2, None, @@ -244,25 +248,26 @@ MathJax.Hub.Config({
  • Identifying Terms
  • Wrapping it up
  • Confidence Intervals
  • -
  • Resampling methods: Bootstrap background
  • -
  • Resampling methods: More Bootstrap background
  • -
  • Resampling methods: Bootstrap approach
  • -
  • Resampling methods: Bootstrap steps
  • -
  • Code example for the Bootstrap method
  • -
  • Plotting the Histogram
  • -
  • The bias-variance tradeoff
  • -
  • A way to Read the Bias-Variance Tradeoff
  • -
  • Example code for Bias-Variance tradeoff
  • -
  • Understanding what happens
  • -
  • Summing up
  • -
  • Another Example from Scikit-Learn's Repository
  • -
  • Various steps in cross-validation
  • -
  • How to set up the cross-validation for Ridge and/or Lasso
  • -
  • Cross-validation in brief
  • -
  • Code Example for Cross-validation and \( k \)-fold Cross-validation
  • -
  • More examples on bootstrap and cross-validation and errors
  • -
  • The same example but now with cross-validation
  • -
  • Cross-validation with Ridge
  • +
  • Standard Approach based on the Normal Distribution
  • +
  • Resampling methods: Bootstrap background
  • +
  • Resampling methods: More Bootstrap background
  • +
  • Resampling methods: Bootstrap approach
  • +
  • Resampling methods: Bootstrap steps
  • +
  • Code example for the Bootstrap method
  • +
  • Plotting the Histogram
  • +
  • The bias-variance tradeoff
  • +
  • A way to Read the Bias-Variance Tradeoff
  • +
  • Example code for Bias-Variance tradeoff
  • +
  • Understanding what happens
  • +
  • Summing up
  • +
  • Another Example from Scikit-Learn's Repository
  • +
  • Various steps in cross-validation
  • +
  • How to set up the cross-validation for Ridge and/or Lasso
  • +
  • Cross-validation in brief
  • +
  • Code Example for Cross-validation and \( k \)-fold Cross-validation
  • +
  • More examples on bootstrap and cross-validation and errors
  • +
  • The same example but now with cross-validation
  • +
  • Cross-validation with Ridge
  • @@ -318,7 +323,7 @@ $$
  • 12
  • 13
  • ...
  • -
  • 49
  • +
  • 50
  • »
  • diff --git a/doc/pub/week37/html/._week37-bs004.html b/doc/pub/week37/html/._week37-bs004.html index 3b09478a9..92e0cb797 100644 --- a/doc/pub/week37/html/._week37-bs004.html +++ b/doc/pub/week37/html/._week37-bs004.html @@ -107,6 +107,10 @@ Automatically generated HTML file from DocOnce source ('Identifying Terms', 2, None, 'identifying-terms'), ('Wrapping it up', 2, None, 'wrapping-it-up'), ('Confidence Intervals', 2, None, 'confidence-intervals'), + ('Standard Approach based on the Normal Distribution', + 2, + None, + 'standard-approach-based-on-the-normal-distribution'), ('Resampling methods: Bootstrap background', 2, None, @@ -244,25 +248,26 @@ MathJax.Hub.Config({
  • Identifying Terms
  • Wrapping it up
  • Confidence Intervals
  • -
  • Resampling methods: Bootstrap background
  • -
  • Resampling methods: More Bootstrap background
  • -
  • Resampling methods: Bootstrap approach
  • -
  • Resampling methods: Bootstrap steps
  • -
  • Code example for the Bootstrap method
  • -
  • Plotting the Histogram
  • -
  • The bias-variance tradeoff
  • -
  • A way to Read the Bias-Variance Tradeoff
  • -
  • Example code for Bias-Variance tradeoff
  • -
  • Understanding what happens
  • -
  • Summing up
  • -
  • Another Example from Scikit-Learn's Repository
  • -
  • Various steps in cross-validation
  • -
  • How to set up the cross-validation for Ridge and/or Lasso
  • -
  • Cross-validation in brief
  • -
  • Code Example for Cross-validation and \( k \)-fold Cross-validation
  • -
  • More examples on bootstrap and cross-validation and errors
  • -
  • The same example but now with cross-validation
  • -
  • Cross-validation with Ridge
  • +
  • Standard Approach based on the Normal Distribution
  • +
  • Resampling methods: Bootstrap background
  • +
  • Resampling methods: More Bootstrap background
  • +
  • Resampling methods: Bootstrap approach
  • +
  • Resampling methods: Bootstrap steps
  • +
  • Code example for the Bootstrap method
  • +
  • Plotting the Histogram
  • +
  • The bias-variance tradeoff
  • +
  • A way to Read the Bias-Variance Tradeoff
  • +
  • Example code for Bias-Variance tradeoff
  • +
  • Understanding what happens
  • +
  • Summing up
  • +
  • Another Example from Scikit-Learn's Repository
  • +
  • Various steps in cross-validation
  • +
  • How to set up the cross-validation for Ridge and/or Lasso
  • +
  • Cross-validation in brief
  • +
  • Code Example for Cross-validation and \( k \)-fold Cross-validation
  • +
  • More examples on bootstrap and cross-validation and errors
  • +
  • The same example but now with cross-validation
  • +
  • Cross-validation with Ridge
  • @@ -332,7 +337,7 @@ It is a conditional probability (see below) and reads as the likelihood of a dom
  • 13
  • 14
  • ...
  • -
  • 49
  • +
  • 50
  • »
  • diff --git a/doc/pub/week37/html/._week37-bs005.html b/doc/pub/week37/html/._week37-bs005.html index eb68e88a7..696f77f10 100644 --- a/doc/pub/week37/html/._week37-bs005.html +++ b/doc/pub/week37/html/._week37-bs005.html @@ -107,6 +107,10 @@ Automatically generated HTML file from DocOnce source ('Identifying Terms', 2, None, 'identifying-terms'), ('Wrapping it up', 2, None, 'wrapping-it-up'), ('Confidence Intervals', 2, None, 'confidence-intervals'), + ('Standard Approach based on the Normal Distribution', + 2, + None, + 'standard-approach-based-on-the-normal-distribution'), ('Resampling methods: Bootstrap background', 2, None, @@ -244,25 +248,26 @@ MathJax.Hub.Config({
  • Identifying Terms
  • Wrapping it up
  • Confidence Intervals
  • -
  • Resampling methods: Bootstrap background
  • -
  • Resampling methods: More Bootstrap background
  • -
  • Resampling methods: Bootstrap approach
  • -
  • Resampling methods: Bootstrap steps
  • -
  • Code example for the Bootstrap method
  • -
  • Plotting the Histogram
  • -
  • The bias-variance tradeoff
  • -
  • A way to Read the Bias-Variance Tradeoff
  • -
  • Example code for Bias-Variance tradeoff
  • -
  • Understanding what happens
  • -
  • Summing up
  • -
  • Another Example from Scikit-Learn's Repository
  • -
  • Various steps in cross-validation
  • -
  • How to set up the cross-validation for Ridge and/or Lasso
  • -
  • Cross-validation in brief
  • -
  • Code Example for Cross-validation and \( k \)-fold Cross-validation
  • -
  • More examples on bootstrap and cross-validation and errors
  • -
  • The same example but now with cross-validation
  • -
  • Cross-validation with Ridge
  • +
  • Standard Approach based on the Normal Distribution
  • +
  • Resampling methods: Bootstrap background
  • +
  • Resampling methods: More Bootstrap background
  • +
  • Resampling methods: Bootstrap approach
  • +
  • Resampling methods: Bootstrap steps
  • +
  • Code example for the Bootstrap method
  • +
  • Plotting the Histogram
  • +
  • The bias-variance tradeoff
  • +
  • A way to Read the Bias-Variance Tradeoff
  • +
  • Example code for Bias-Variance tradeoff
  • +
  • Understanding what happens
  • +
  • Summing up
  • +
  • Another Example from Scikit-Learn's Repository
  • +
  • Various steps in cross-validation
  • +
  • How to set up the cross-validation for Ridge and/or Lasso
  • +
  • Cross-validation in brief
  • +
  • Code Example for Cross-validation and \( k \)-fold Cross-validation
  • +
  • More examples on bootstrap and cross-validation and errors
  • +
  • The same example but now with cross-validation
  • +
  • Cross-validation with Ridge
  • @@ -326,7 +331,7 @@ is equivalent to the maximization/minimization of the function itself.
  • 14
  • 15
  • ...
  • -
  • 49
  • +
  • 50
  • »
  • diff --git a/doc/pub/week37/html/._week37-bs006.html b/doc/pub/week37/html/._week37-bs006.html index 9a0bd0f18..fcc4b2ef2 100644 --- a/doc/pub/week37/html/._week37-bs006.html +++ b/doc/pub/week37/html/._week37-bs006.html @@ -107,6 +107,10 @@ Automatically generated HTML file from DocOnce source ('Identifying Terms', 2, None, 'identifying-terms'), ('Wrapping it up', 2, None, 'wrapping-it-up'), ('Confidence Intervals', 2, None, 'confidence-intervals'), + ('Standard Approach based on the Normal Distribution', + 2, + None, + 'standard-approach-based-on-the-normal-distribution'), ('Resampling methods: Bootstrap background', 2, None, @@ -244,25 +248,26 @@ MathJax.Hub.Config({
  • Identifying Terms
  • Wrapping it up
  • Confidence Intervals
  • -
  • Resampling methods: Bootstrap background
  • -
  • Resampling methods: More Bootstrap background
  • -
  • Resampling methods: Bootstrap approach
  • -
  • Resampling methods: Bootstrap steps
  • -
  • Code example for the Bootstrap method
  • -
  • Plotting the Histogram
  • -
  • The bias-variance tradeoff
  • -
  • A way to Read the Bias-Variance Tradeoff
  • -
  • Example code for Bias-Variance tradeoff
  • -
  • Understanding what happens
  • -
  • Summing up
  • -
  • Another Example from Scikit-Learn's Repository
  • -
  • Various steps in cross-validation
  • -
  • How to set up the cross-validation for Ridge and/or Lasso
  • -
  • Cross-validation in brief
  • -
  • Code Example for Cross-validation and \( k \)-fold Cross-validation
  • -
  • More examples on bootstrap and cross-validation and errors
  • -
  • The same example but now with cross-validation
  • -
  • Cross-validation with Ridge
  • +
  • Standard Approach based on the Normal Distribution
  • +
  • Resampling methods: Bootstrap background
  • +
  • Resampling methods: More Bootstrap background
  • +
  • Resampling methods: Bootstrap approach
  • +
  • Resampling methods: Bootstrap steps
  • +
  • Code example for the Bootstrap method
  • +
  • Plotting the Histogram
  • +
  • The bias-variance tradeoff
  • +
  • A way to Read the Bias-Variance Tradeoff
  • +
  • Example code for Bias-Variance tradeoff
  • +
  • Understanding what happens
  • +
  • Summing up
  • +
  • Another Example from Scikit-Learn's Repository
  • +
  • Various steps in cross-validation
  • +
  • How to set up the cross-validation for Ridge and/or Lasso
  • +
  • Cross-validation in brief
  • +
  • Code Example for Cross-validation and \( k \)-fold Cross-validation
  • +
  • More examples on bootstrap and cross-validation and errors
  • +
  • The same example but now with cross-validation
  • +
  • Cross-validation with Ridge
  • @@ -326,7 +331,7 @@ $$
  • 15
  • 16
  • ...
  • -
  • 49
  • +
  • 50
  • »
  • diff --git a/doc/pub/week37/html/._week37-bs007.html b/doc/pub/week37/html/._week37-bs007.html index 060ce84f0..881f68e30 100644 --- a/doc/pub/week37/html/._week37-bs007.html +++ b/doc/pub/week37/html/._week37-bs007.html @@ -107,6 +107,10 @@ Automatically generated HTML file from DocOnce source ('Identifying Terms', 2, None, 'identifying-terms'), ('Wrapping it up', 2, None, 'wrapping-it-up'), ('Confidence Intervals', 2, None, 'confidence-intervals'), + ('Standard Approach based on the Normal Distribution', + 2, + None, + 'standard-approach-based-on-the-normal-distribution'), ('Resampling methods: Bootstrap background', 2, None, @@ -244,25 +248,26 @@ MathJax.Hub.Config({
  • Identifying Terms
  • Wrapping it up
  • Confidence Intervals
  • -
  • Resampling methods: Bootstrap background
  • -
  • Resampling methods: More Bootstrap background
  • -
  • Resampling methods: Bootstrap approach
  • -
  • Resampling methods: Bootstrap steps
  • -
  • Code example for the Bootstrap method
  • -
  • Plotting the Histogram
  • -
  • The bias-variance tradeoff
  • -
  • A way to Read the Bias-Variance Tradeoff
  • -
  • Example code for Bias-Variance tradeoff
  • -
  • Understanding what happens
  • -
  • Summing up
  • -
  • Another Example from Scikit-Learn's Repository
  • -
  • Various steps in cross-validation
  • -
  • How to set up the cross-validation for Ridge and/or Lasso
  • -
  • Cross-validation in brief
  • -
  • Code Example for Cross-validation and \( k \)-fold Cross-validation
  • -
  • More examples on bootstrap and cross-validation and errors
  • -
  • The same example but now with cross-validation
  • -
  • Cross-validation with Ridge
  • +
  • Standard Approach based on the Normal Distribution
  • +
  • Resampling methods: Bootstrap background
  • +
  • Resampling methods: More Bootstrap background
  • +
  • Resampling methods: Bootstrap approach
  • +
  • Resampling methods: Bootstrap steps
  • +
  • Code example for the Bootstrap method
  • +
  • Plotting the Histogram
  • +
  • The bias-variance tradeoff
  • +
  • A way to Read the Bias-Variance Tradeoff
  • +
  • Example code for Bias-Variance tradeoff
  • +
  • Understanding what happens
  • +
  • Summing up
  • +
  • Another Example from Scikit-Learn's Repository
  • +
  • Various steps in cross-validation
  • +
  • How to set up the cross-validation for Ridge and/or Lasso
  • +
  • Cross-validation in brief
  • +
  • Code Example for Cross-validation and \( k \)-fold Cross-validation
  • +
  • More examples on bootstrap and cross-validation and errors
  • +
  • The same example but now with cross-validation
  • +
  • Cross-validation with Ridge
  • @@ -317,7 +322,7 @@ which is Bayes' theorem. It allows us to evaluate the uncertainty in in \( X \)
  • 16
  • 17
  • ...
  • -
  • 49
  • +
  • 50
  • »
  • diff --git a/doc/pub/week37/html/._week37-bs008.html b/doc/pub/week37/html/._week37-bs008.html index 782c02532..1091586bf 100644 --- a/doc/pub/week37/html/._week37-bs008.html +++ b/doc/pub/week37/html/._week37-bs008.html @@ -107,6 +107,10 @@ Automatically generated HTML file from DocOnce source ('Identifying Terms', 2, None, 'identifying-terms'), ('Wrapping it up', 2, None, 'wrapping-it-up'), ('Confidence Intervals', 2, None, 'confidence-intervals'), + ('Standard Approach based on the Normal Distribution', + 2, + None, + 'standard-approach-based-on-the-normal-distribution'), ('Resampling methods: Bootstrap background', 2, None, @@ -244,25 +248,26 @@ MathJax.Hub.Config({
  • Identifying Terms
  • Wrapping it up
  • Confidence Intervals
  • -
  • Resampling methods: Bootstrap background
  • -
  • Resampling methods: More Bootstrap background
  • -
  • Resampling methods: Bootstrap approach
  • -
  • Resampling methods: Bootstrap steps
  • -
  • Code example for the Bootstrap method
  • -
  • Plotting the Histogram
  • -
  • The bias-variance tradeoff
  • -
  • A way to Read the Bias-Variance Tradeoff
  • -
  • Example code for Bias-Variance tradeoff
  • -
  • Understanding what happens
  • -
  • Summing up
  • -
  • Another Example from Scikit-Learn's Repository
  • -
  • Various steps in cross-validation
  • -
  • How to set up the cross-validation for Ridge and/or Lasso
  • -
  • Cross-validation in brief
  • -
  • Code Example for Cross-validation and \( k \)-fold Cross-validation
  • -
  • More examples on bootstrap and cross-validation and errors
  • -
  • The same example but now with cross-validation
  • -
  • Cross-validation with Ridge
  • +
  • Standard Approach based on the Normal Distribution
  • +
  • Resampling methods: Bootstrap background
  • +
  • Resampling methods: More Bootstrap background
  • +
  • Resampling methods: Bootstrap approach
  • +
  • Resampling methods: Bootstrap steps
  • +
  • Code example for the Bootstrap method
  • +
  • Plotting the Histogram
  • +
  • The bias-variance tradeoff
  • +
  • A way to Read the Bias-Variance Tradeoff
  • +
  • Example code for Bias-Variance tradeoff
  • +
  • Understanding what happens
  • +
  • Summing up
  • +
  • Another Example from Scikit-Learn's Repository
  • +
  • Various steps in cross-validation
  • +
  • How to set up the cross-validation for Ridge and/or Lasso
  • +
  • Cross-validation in brief
  • +
  • Code Example for Cross-validation and \( k \)-fold Cross-validation
  • +
  • More examples on bootstrap and cross-validation and errors
  • +
  • The same example but now with cross-validation
  • +
  • Cross-validation with Ridge
  • @@ -313,7 +318,7 @@ The function \( p(X) \) on the right hand side is called the prior while the fun
  • 17
  • 18
  • ...
  • -
  • 49
  • +
  • 50
  • »
  • diff --git a/doc/pub/week37/html/._week37-bs009.html b/doc/pub/week37/html/._week37-bs009.html index ddc95d872..53cbd3faf 100644 --- a/doc/pub/week37/html/._week37-bs009.html +++ b/doc/pub/week37/html/._week37-bs009.html @@ -107,6 +107,10 @@ Automatically generated HTML file from DocOnce source ('Identifying Terms', 2, None, 'identifying-terms'), ('Wrapping it up', 2, None, 'wrapping-it-up'), ('Confidence Intervals', 2, None, 'confidence-intervals'), + ('Standard Approach based on the Normal Distribution', + 2, + None, + 'standard-approach-based-on-the-normal-distribution'), ('Resampling methods: Bootstrap background', 2, None, @@ -244,25 +248,26 @@ MathJax.Hub.Config({
  • Identifying Terms
  • Wrapping it up
  • Confidence Intervals
  • -
  • Resampling methods: Bootstrap background
  • -
  • Resampling methods: More Bootstrap background
  • -
  • Resampling methods: Bootstrap approach
  • -
  • Resampling methods: Bootstrap steps
  • -
  • Code example for the Bootstrap method
  • -
  • Plotting the Histogram
  • -
  • The bias-variance tradeoff
  • -
  • A way to Read the Bias-Variance Tradeoff
  • -
  • Example code for Bias-Variance tradeoff
  • -
  • Understanding what happens
  • -
  • Summing up
  • -
  • Another Example from Scikit-Learn's Repository
  • -
  • Various steps in cross-validation
  • -
  • How to set up the cross-validation for Ridge and/or Lasso
  • -
  • Cross-validation in brief
  • -
  • Code Example for Cross-validation and \( k \)-fold Cross-validation
  • -
  • More examples on bootstrap and cross-validation and errors
  • -
  • The same example but now with cross-validation
  • -
  • Cross-validation with Ridge
  • +
  • Standard Approach based on the Normal Distribution
  • +
  • Resampling methods: Bootstrap background
  • +
  • Resampling methods: More Bootstrap background
  • +
  • Resampling methods: Bootstrap approach
  • +
  • Resampling methods: Bootstrap steps
  • +
  • Code example for the Bootstrap method
  • +
  • Plotting the Histogram
  • +
  • The bias-variance tradeoff
  • +
  • A way to Read the Bias-Variance Tradeoff
  • +
  • Example code for Bias-Variance tradeoff
  • +
  • Understanding what happens
  • +
  • Summing up
  • +
  • Another Example from Scikit-Learn's Repository
  • +
  • Various steps in cross-validation
  • +
  • How to set up the cross-validation for Ridge and/or Lasso
  • +
  • Cross-validation in brief
  • +
  • Code Example for Cross-validation and \( k \)-fold Cross-validation
  • +
  • More examples on bootstrap and cross-validation and errors
  • +
  • The same example but now with cross-validation
  • +
  • Cross-validation with Ridge
  • @@ -385,7 +390,7 @@ How can we understand this?
  • 18
  • 19
  • ...
  • -
  • 49
  • +
  • 50
  • »
  • diff --git a/doc/pub/week37/html/._week37-bs010.html b/doc/pub/week37/html/._week37-bs010.html index 533203d1e..14a7e4182 100644 --- a/doc/pub/week37/html/._week37-bs010.html +++ b/doc/pub/week37/html/._week37-bs010.html @@ -107,6 +107,10 @@ Automatically generated HTML file from DocOnce source ('Identifying Terms', 2, None, 'identifying-terms'), ('Wrapping it up', 2, None, 'wrapping-it-up'), ('Confidence Intervals', 2, None, 'confidence-intervals'), + ('Standard Approach based on the Normal Distribution', + 2, + None, + 'standard-approach-based-on-the-normal-distribution'), ('Resampling methods: Bootstrap background', 2, None, @@ -244,25 +248,26 @@ MathJax.Hub.Config({
  • Identifying Terms
  • Wrapping it up
  • Confidence Intervals
  • -
  • Resampling methods: Bootstrap background
  • -
  • Resampling methods: More Bootstrap background
  • -
  • Resampling methods: Bootstrap approach
  • -
  • Resampling methods: Bootstrap steps
  • -
  • Code example for the Bootstrap method
  • -
  • Plotting the Histogram
  • -
  • The bias-variance tradeoff
  • -
  • A way to Read the Bias-Variance Tradeoff
  • -
  • Example code for Bias-Variance tradeoff
  • -
  • Understanding what happens
  • -
  • Summing up
  • -
  • Another Example from Scikit-Learn's Repository
  • -
  • Various steps in cross-validation
  • -
  • How to set up the cross-validation for Ridge and/or Lasso
  • -
  • Cross-validation in brief
  • -
  • Code Example for Cross-validation and \( k \)-fold Cross-validation
  • -
  • More examples on bootstrap and cross-validation and errors
  • -
  • The same example but now with cross-validation
  • -
  • Cross-validation with Ridge
  • +
  • Standard Approach based on the Normal Distribution
  • +
  • Resampling methods: Bootstrap background
  • +
  • Resampling methods: More Bootstrap background
  • +
  • Resampling methods: Bootstrap approach
  • +
  • Resampling methods: Bootstrap steps
  • +
  • Code example for the Bootstrap method
  • +
  • Plotting the Histogram
  • +
  • The bias-variance tradeoff
  • +
  • A way to Read the Bias-Variance Tradeoff
  • +
  • Example code for Bias-Variance tradeoff
  • +
  • Understanding what happens
  • +
  • Summing up
  • +
  • Another Example from Scikit-Learn's Repository
  • +
  • Various steps in cross-validation
  • +
  • How to set up the cross-validation for Ridge and/or Lasso
  • +
  • Cross-validation in brief
  • +
  • Code Example for Cross-validation and \( k \)-fold Cross-validation
  • +
  • More examples on bootstrap and cross-validation and errors
  • +
  • The same example but now with cross-validation
  • +
  • Cross-validation with Ridge
  • @@ -370,7 +375,7 @@ lambdas = np.19
  • 20
  • ...
  • -
  • 49
  • +
  • 50
  • »
  • diff --git a/doc/pub/week37/html/._week37-bs011.html b/doc/pub/week37/html/._week37-bs011.html index 13b0683b2..30046fcfd 100644 --- a/doc/pub/week37/html/._week37-bs011.html +++ b/doc/pub/week37/html/._week37-bs011.html @@ -107,6 +107,10 @@ Automatically generated HTML file from DocOnce source ('Identifying Terms', 2, None, 'identifying-terms'), ('Wrapping it up', 2, None, 'wrapping-it-up'), ('Confidence Intervals', 2, None, 'confidence-intervals'), + ('Standard Approach based on the Normal Distribution', + 2, + None, + 'standard-approach-based-on-the-normal-distribution'), ('Resampling methods: Bootstrap background', 2, None, @@ -244,25 +248,26 @@ MathJax.Hub.Config({
  • Identifying Terms
  • Wrapping it up
  • Confidence Intervals
  • -
  • Resampling methods: Bootstrap background
  • -
  • Resampling methods: More Bootstrap background
  • -
  • Resampling methods: Bootstrap approach
  • -
  • Resampling methods: Bootstrap steps
  • -
  • Code example for the Bootstrap method
  • -
  • Plotting the Histogram
  • -
  • The bias-variance tradeoff
  • -
  • A way to Read the Bias-Variance Tradeoff
  • -
  • Example code for Bias-Variance tradeoff
  • -
  • Understanding what happens
  • -
  • Summing up
  • -
  • Another Example from Scikit-Learn's Repository
  • -
  • Various steps in cross-validation
  • -
  • How to set up the cross-validation for Ridge and/or Lasso
  • -
  • Cross-validation in brief
  • -
  • Code Example for Cross-validation and \( k \)-fold Cross-validation
  • -
  • More examples on bootstrap and cross-validation and errors
  • -
  • The same example but now with cross-validation
  • -
  • Cross-validation with Ridge
  • +
  • Standard Approach based on the Normal Distribution
  • +
  • Resampling methods: Bootstrap background
  • +
  • Resampling methods: More Bootstrap background
  • +
  • Resampling methods: Bootstrap approach
  • +
  • Resampling methods: Bootstrap steps
  • +
  • Code example for the Bootstrap method
  • +
  • Plotting the Histogram
  • +
  • The bias-variance tradeoff
  • +
  • A way to Read the Bias-Variance Tradeoff
  • +
  • Example code for Bias-Variance tradeoff
  • +
  • Understanding what happens
  • +
  • Summing up
  • +
  • Another Example from Scikit-Learn's Repository
  • +
  • Various steps in cross-validation
  • +
  • How to set up the cross-validation for Ridge and/or Lasso
  • +
  • Cross-validation in brief
  • +
  • Code Example for Cross-validation and \( k \)-fold Cross-validation
  • +
  • More examples on bootstrap and cross-validation and errors
  • +
  • The same example but now with cross-validation
  • +
  • Cross-validation with Ridge
  • @@ -336,7 +341,7 @@ We have a model for \( p(\boldsymbol{D}\vert\boldsymbol{\beta}) \) but need one
  • 20
  • 21
  • ...
  • -
  • 49
  • +
  • 50
  • »
  • diff --git a/doc/pub/week37/html/._week37-bs012.html b/doc/pub/week37/html/._week37-bs012.html index 012c8e223..b601102c1 100644 --- a/doc/pub/week37/html/._week37-bs012.html +++ b/doc/pub/week37/html/._week37-bs012.html @@ -107,6 +107,10 @@ Automatically generated HTML file from DocOnce source ('Identifying Terms', 2, None, 'identifying-terms'), ('Wrapping it up', 2, None, 'wrapping-it-up'), ('Confidence Intervals', 2, None, 'confidence-intervals'), + ('Standard Approach based on the Normal Distribution', + 2, + None, + 'standard-approach-based-on-the-normal-distribution'), ('Resampling methods: Bootstrap background', 2, None, @@ -244,25 +248,26 @@ MathJax.Hub.Config({
  • Identifying Terms
  • Wrapping it up
  • Confidence Intervals
  • -
  • Resampling methods: Bootstrap background
  • -
  • Resampling methods: More Bootstrap background
  • -
  • Resampling methods: Bootstrap approach
  • -
  • Resampling methods: Bootstrap steps
  • -
  • Code example for the Bootstrap method
  • -
  • Plotting the Histogram
  • -
  • The bias-variance tradeoff
  • -
  • A way to Read the Bias-Variance Tradeoff
  • -
  • Example code for Bias-Variance tradeoff
  • -
  • Understanding what happens
  • -
  • Summing up
  • -
  • Another Example from Scikit-Learn's Repository
  • -
  • Various steps in cross-validation
  • -
  • How to set up the cross-validation for Ridge and/or Lasso
  • -
  • Cross-validation in brief
  • -
  • Code Example for Cross-validation and \( k \)-fold Cross-validation
  • -
  • More examples on bootstrap and cross-validation and errors
  • -
  • The same example but now with cross-validation
  • -
  • Cross-validation with Ridge
  • +
  • Standard Approach based on the Normal Distribution
  • +
  • Resampling methods: Bootstrap background
  • +
  • Resampling methods: More Bootstrap background
  • +
  • Resampling methods: Bootstrap approach
  • +
  • Resampling methods: Bootstrap steps
  • +
  • Code example for the Bootstrap method
  • +
  • Plotting the Histogram
  • +
  • The bias-variance tradeoff
  • +
  • A way to Read the Bias-Variance Tradeoff
  • +
  • Example code for Bias-Variance tradeoff
  • +
  • Understanding what happens
  • +
  • Summing up
  • +
  • Another Example from Scikit-Learn's Repository
  • +
  • Various steps in cross-validation
  • +
  • How to set up the cross-validation for Ridge and/or Lasso
  • +
  • Cross-validation in brief
  • +
  • Code Example for Cross-validation and \( k \)-fold Cross-validation
  • +
  • More examples on bootstrap and cross-validation and errors
  • +
  • The same example but now with cross-validation
  • +
  • Cross-validation with Ridge
  • @@ -342,7 +347,7 @@ which is our Ridge cost function! Nice, isn't it?
  • 21
  • 22
  • ...
  • -
  • 49
  • +
  • 50
  • »
  • diff --git a/doc/pub/week37/html/._week37-bs013.html b/doc/pub/week37/html/._week37-bs013.html index 92de2c566..5dbaa7e5b 100644 --- a/doc/pub/week37/html/._week37-bs013.html +++ b/doc/pub/week37/html/._week37-bs013.html @@ -107,6 +107,10 @@ Automatically generated HTML file from DocOnce source ('Identifying Terms', 2, None, 'identifying-terms'), ('Wrapping it up', 2, None, 'wrapping-it-up'), ('Confidence Intervals', 2, None, 'confidence-intervals'), + ('Standard Approach based on the Normal Distribution', + 2, + None, + 'standard-approach-based-on-the-normal-distribution'), ('Resampling methods: Bootstrap background', 2, None, @@ -244,25 +248,26 @@ MathJax.Hub.Config({
  • Identifying Terms
  • Wrapping it up
  • Confidence Intervals
  • -
  • Resampling methods: Bootstrap background
  • -
  • Resampling methods: More Bootstrap background
  • -
  • Resampling methods: Bootstrap approach
  • -
  • Resampling methods: Bootstrap steps
  • -
  • Code example for the Bootstrap method
  • -
  • Plotting the Histogram
  • -
  • The bias-variance tradeoff
  • -
  • A way to Read the Bias-Variance Tradeoff
  • -
  • Example code for Bias-Variance tradeoff
  • -
  • Understanding what happens
  • -
  • Summing up
  • -
  • Another Example from Scikit-Learn's Repository
  • -
  • Various steps in cross-validation
  • -
  • How to set up the cross-validation for Ridge and/or Lasso
  • -
  • Cross-validation in brief
  • -
  • Code Example for Cross-validation and \( k \)-fold Cross-validation
  • -
  • More examples on bootstrap and cross-validation and errors
  • -
  • The same example but now with cross-validation
  • -
  • Cross-validation with Ridge
  • +
  • Standard Approach based on the Normal Distribution
  • +
  • Resampling methods: Bootstrap background
  • +
  • Resampling methods: More Bootstrap background
  • +
  • Resampling methods: Bootstrap approach
  • +
  • Resampling methods: Bootstrap steps
  • +
  • Code example for the Bootstrap method
  • +
  • Plotting the Histogram
  • +
  • The bias-variance tradeoff
  • +
  • A way to Read the Bias-Variance Tradeoff
  • +
  • Example code for Bias-Variance tradeoff
  • +
  • Understanding what happens
  • +
  • Summing up
  • +
  • Another Example from Scikit-Learn's Repository
  • +
  • Various steps in cross-validation
  • +
  • How to set up the cross-validation for Ridge and/or Lasso
  • +
  • Cross-validation in brief
  • +
  • Code Example for Cross-validation and \( k \)-fold Cross-validation
  • +
  • More examples on bootstrap and cross-validation and errors
  • +
  • The same example but now with cross-validation
  • +
  • Cross-validation with Ridge
  • @@ -336,7 +341,7 @@ which is our Lasso cost function!
  • 22
  • 23
  • ...
  • -
  • 49
  • +
  • 50
  • »
  • diff --git a/doc/pub/week37/html/._week37-bs014.html b/doc/pub/week37/html/._week37-bs014.html index 44b585130..7188c2993 100644 --- a/doc/pub/week37/html/._week37-bs014.html +++ b/doc/pub/week37/html/._week37-bs014.html @@ -107,6 +107,10 @@ Automatically generated HTML file from DocOnce source ('Identifying Terms', 2, None, 'identifying-terms'), ('Wrapping it up', 2, None, 'wrapping-it-up'), ('Confidence Intervals', 2, None, 'confidence-intervals'), + ('Standard Approach based on the Normal Distribution', + 2, + None, + 'standard-approach-based-on-the-normal-distribution'), ('Resampling methods: Bootstrap background', 2, None, @@ -244,25 +248,26 @@ MathJax.Hub.Config({
  • Identifying Terms
  • Wrapping it up
  • Confidence Intervals
  • -
  • Resampling methods: Bootstrap background
  • -
  • Resampling methods: More Bootstrap background
  • -
  • Resampling methods: Bootstrap approach
  • -
  • Resampling methods: Bootstrap steps
  • -
  • Code example for the Bootstrap method
  • -
  • Plotting the Histogram
  • -
  • The bias-variance tradeoff
  • -
  • A way to Read the Bias-Variance Tradeoff
  • -
  • Example code for Bias-Variance tradeoff
  • -
  • Understanding what happens
  • -
  • Summing up
  • -
  • Another Example from Scikit-Learn's Repository
  • -
  • Various steps in cross-validation
  • -
  • How to set up the cross-validation for Ridge and/or Lasso
  • -
  • Cross-validation in brief
  • -
  • Code Example for Cross-validation and \( k \)-fold Cross-validation
  • -
  • More examples on bootstrap and cross-validation and errors
  • -
  • The same example but now with cross-validation
  • -
  • Cross-validation with Ridge
  • +
  • Standard Approach based on the Normal Distribution
  • +
  • Resampling methods: Bootstrap background
  • +
  • Resampling methods: More Bootstrap background
  • +
  • Resampling methods: Bootstrap approach
  • +
  • Resampling methods: Bootstrap steps
  • +
  • Code example for the Bootstrap method
  • +
  • Plotting the Histogram
  • +
  • The bias-variance tradeoff
  • +
  • A way to Read the Bias-Variance Tradeoff
  • +
  • Example code for Bias-Variance tradeoff
  • +
  • Understanding what happens
  • +
  • Summing up
  • +
  • Another Example from Scikit-Learn's Repository
  • +
  • Various steps in cross-validation
  • +
  • How to set up the cross-validation for Ridge and/or Lasso
  • +
  • Cross-validation in brief
  • +
  • Code Example for Cross-validation and \( k \)-fold Cross-validation
  • +
  • More examples on bootstrap and cross-validation and errors
  • +
  • The same example but now with cross-validation
  • +
  • Cross-validation with Ridge
  • @@ -318,7 +323,7 @@ and discuss how to select a given model (one of the difficult parts in machine l
  • 23
  • 24
  • ...
  • -
  • 49
  • +
  • 50
  • »
  • diff --git a/doc/pub/week37/html/._week37-bs015.html b/doc/pub/week37/html/._week37-bs015.html index bc7bbd54d..191af6385 100644 --- a/doc/pub/week37/html/._week37-bs015.html +++ b/doc/pub/week37/html/._week37-bs015.html @@ -107,6 +107,10 @@ Automatically generated HTML file from DocOnce source ('Identifying Terms', 2, None, 'identifying-terms'), ('Wrapping it up', 2, None, 'wrapping-it-up'), ('Confidence Intervals', 2, None, 'confidence-intervals'), + ('Standard Approach based on the Normal Distribution', + 2, + None, + 'standard-approach-based-on-the-normal-distribution'), ('Resampling methods: Bootstrap background', 2, None, @@ -244,25 +248,26 @@ MathJax.Hub.Config({
  • Identifying Terms
  • Wrapping it up
  • Confidence Intervals
  • -
  • Resampling methods: Bootstrap background
  • -
  • Resampling methods: More Bootstrap background
  • -
  • Resampling methods: Bootstrap approach
  • -
  • Resampling methods: Bootstrap steps
  • -
  • Code example for the Bootstrap method
  • -
  • Plotting the Histogram
  • -
  • The bias-variance tradeoff
  • -
  • A way to Read the Bias-Variance Tradeoff
  • -
  • Example code for Bias-Variance tradeoff
  • -
  • Understanding what happens
  • -
  • Summing up
  • -
  • Another Example from Scikit-Learn's Repository
  • -
  • Various steps in cross-validation
  • -
  • How to set up the cross-validation for Ridge and/or Lasso
  • -
  • Cross-validation in brief
  • -
  • Code Example for Cross-validation and \( k \)-fold Cross-validation
  • -
  • More examples on bootstrap and cross-validation and errors
  • -
  • The same example but now with cross-validation
  • -
  • Cross-validation with Ridge
  • +
  • Standard Approach based on the Normal Distribution
  • +
  • Resampling methods: Bootstrap background
  • +
  • Resampling methods: More Bootstrap background
  • +
  • Resampling methods: Bootstrap approach
  • +
  • Resampling methods: Bootstrap steps
  • +
  • Code example for the Bootstrap method
  • +
  • Plotting the Histogram
  • +
  • The bias-variance tradeoff
  • +
  • A way to Read the Bias-Variance Tradeoff
  • +
  • Example code for Bias-Variance tradeoff
  • +
  • Understanding what happens
  • +
  • Summing up
  • +
  • Another Example from Scikit-Learn's Repository
  • +
  • Various steps in cross-validation
  • +
  • How to set up the cross-validation for Ridge and/or Lasso
  • +
  • Cross-validation in brief
  • +
  • Code Example for Cross-validation and \( k \)-fold Cross-validation
  • +
  • More examples on bootstrap and cross-validation and errors
  • +
  • The same example but now with cross-validation
  • +
  • Cross-validation with Ridge
  • @@ -335,7 +340,7 @@ cross-validation and the bootstrap method.
  • 24
  • 25
  • ...
  • -
  • 49
  • +
  • 50
  • »
  • diff --git a/doc/pub/week37/html/._week37-bs016.html b/doc/pub/week37/html/._week37-bs016.html index 4ae2cc1dd..f38127961 100644 --- a/doc/pub/week37/html/._week37-bs016.html +++ b/doc/pub/week37/html/._week37-bs016.html @@ -107,6 +107,10 @@ Automatically generated HTML file from DocOnce source ('Identifying Terms', 2, None, 'identifying-terms'), ('Wrapping it up', 2, None, 'wrapping-it-up'), ('Confidence Intervals', 2, None, 'confidence-intervals'), + ('Standard Approach based on the Normal Distribution', + 2, + None, + 'standard-approach-based-on-the-normal-distribution'), ('Resampling methods: Bootstrap background', 2, None, @@ -244,25 +248,26 @@ MathJax.Hub.Config({
  • Identifying Terms
  • Wrapping it up
  • Confidence Intervals
  • -
  • Resampling methods: Bootstrap background
  • -
  • Resampling methods: More Bootstrap background
  • -
  • Resampling methods: Bootstrap approach
  • -
  • Resampling methods: Bootstrap steps
  • -
  • Code example for the Bootstrap method
  • -
  • Plotting the Histogram
  • -
  • The bias-variance tradeoff
  • -
  • A way to Read the Bias-Variance Tradeoff
  • -
  • Example code for Bias-Variance tradeoff
  • -
  • Understanding what happens
  • -
  • Summing up
  • -
  • Another Example from Scikit-Learn's Repository
  • -
  • Various steps in cross-validation
  • -
  • How to set up the cross-validation for Ridge and/or Lasso
  • -
  • Cross-validation in brief
  • -
  • Code Example for Cross-validation and \( k \)-fold Cross-validation
  • -
  • More examples on bootstrap and cross-validation and errors
  • -
  • The same example but now with cross-validation
  • -
  • Cross-validation with Ridge
  • +
  • Standard Approach based on the Normal Distribution
  • +
  • Resampling methods: Bootstrap background
  • +
  • Resampling methods: More Bootstrap background
  • +
  • Resampling methods: Bootstrap approach
  • +
  • Resampling methods: Bootstrap steps
  • +
  • Code example for the Bootstrap method
  • +
  • Plotting the Histogram
  • +
  • The bias-variance tradeoff
  • +
  • A way to Read the Bias-Variance Tradeoff
  • +
  • Example code for Bias-Variance tradeoff
  • +
  • Understanding what happens
  • +
  • Summing up
  • +
  • Another Example from Scikit-Learn's Repository
  • +
  • Various steps in cross-validation
  • +
  • How to set up the cross-validation for Ridge and/or Lasso
  • +
  • Cross-validation in brief
  • +
  • Code Example for Cross-validation and \( k \)-fold Cross-validation
  • +
  • More examples on bootstrap and cross-validation and errors
  • +
  • The same example but now with cross-validation
  • +
  • Cross-validation with Ridge
  • @@ -331,7 +336,7 @@ bootstrap is widely used.
  • 25
  • 26
  • ...
  • -
  • 49
  • +
  • 50
  • »
  • diff --git a/doc/pub/week37/html/._week37-bs017.html b/doc/pub/week37/html/._week37-bs017.html index bc0b9197f..4132e5b49 100644 --- a/doc/pub/week37/html/._week37-bs017.html +++ b/doc/pub/week37/html/._week37-bs017.html @@ -107,6 +107,10 @@ Automatically generated HTML file from DocOnce source ('Identifying Terms', 2, None, 'identifying-terms'), ('Wrapping it up', 2, None, 'wrapping-it-up'), ('Confidence Intervals', 2, None, 'confidence-intervals'), + ('Standard Approach based on the Normal Distribution', + 2, + None, + 'standard-approach-based-on-the-normal-distribution'), ('Resampling methods: Bootstrap background', 2, None, @@ -244,25 +248,26 @@ MathJax.Hub.Config({
  • Identifying Terms
  • Wrapping it up
  • Confidence Intervals
  • -
  • Resampling methods: Bootstrap background
  • -
  • Resampling methods: More Bootstrap background
  • -
  • Resampling methods: Bootstrap approach
  • -
  • Resampling methods: Bootstrap steps
  • -
  • Code example for the Bootstrap method
  • -
  • Plotting the Histogram
  • -
  • The bias-variance tradeoff
  • -
  • A way to Read the Bias-Variance Tradeoff
  • -
  • Example code for Bias-Variance tradeoff
  • -
  • Understanding what happens
  • -
  • Summing up
  • -
  • Another Example from Scikit-Learn's Repository
  • -
  • Various steps in cross-validation
  • -
  • How to set up the cross-validation for Ridge and/or Lasso
  • -
  • Cross-validation in brief
  • -
  • Code Example for Cross-validation and \( k \)-fold Cross-validation
  • -
  • More examples on bootstrap and cross-validation and errors
  • -
  • The same example but now with cross-validation
  • -
  • Cross-validation with Ridge
  • +
  • Standard Approach based on the Normal Distribution
  • +
  • Resampling methods: Bootstrap background
  • +
  • Resampling methods: More Bootstrap background
  • +
  • Resampling methods: Bootstrap approach
  • +
  • Resampling methods: Bootstrap steps
  • +
  • Code example for the Bootstrap method
  • +
  • Plotting the Histogram
  • +
  • The bias-variance tradeoff
  • +
  • A way to Read the Bias-Variance Tradeoff
  • +
  • Example code for Bias-Variance tradeoff
  • +
  • Understanding what happens
  • +
  • Summing up
  • +
  • Another Example from Scikit-Learn's Repository
  • +
  • Various steps in cross-validation
  • +
  • How to set up the cross-validation for Ridge and/or Lasso
  • +
  • Cross-validation in brief
  • +
  • Code Example for Cross-validation and \( k \)-fold Cross-validation
  • +
  • More examples on bootstrap and cross-validation and errors
  • +
  • The same example but now with cross-validation
  • +
  • Cross-validation with Ridge
  • @@ -318,7 +323,7 @@ MathJax.Hub.Config({
  • 26
  • 27
  • ...
  • -
  • 49
  • +
  • 50
  • »
  • diff --git a/doc/pub/week37/html/._week37-bs018.html b/doc/pub/week37/html/._week37-bs018.html index 5dc9cc2b0..bdaf94e8e 100644 --- a/doc/pub/week37/html/._week37-bs018.html +++ b/doc/pub/week37/html/._week37-bs018.html @@ -107,6 +107,10 @@ Automatically generated HTML file from DocOnce source ('Identifying Terms', 2, None, 'identifying-terms'), ('Wrapping it up', 2, None, 'wrapping-it-up'), ('Confidence Intervals', 2, None, 'confidence-intervals'), + ('Standard Approach based on the Normal Distribution', + 2, + None, + 'standard-approach-based-on-the-normal-distribution'), ('Resampling methods: Bootstrap background', 2, None, @@ -244,25 +248,26 @@ MathJax.Hub.Config({
  • Identifying Terms
  • Wrapping it up
  • Confidence Intervals
  • -
  • Resampling methods: Bootstrap background
  • -
  • Resampling methods: More Bootstrap background
  • -
  • Resampling methods: Bootstrap approach
  • -
  • Resampling methods: Bootstrap steps
  • -
  • Code example for the Bootstrap method
  • -
  • Plotting the Histogram
  • -
  • The bias-variance tradeoff
  • -
  • A way to Read the Bias-Variance Tradeoff
  • -
  • Example code for Bias-Variance tradeoff
  • -
  • Understanding what happens
  • -
  • Summing up
  • -
  • Another Example from Scikit-Learn's Repository
  • -
  • Various steps in cross-validation
  • -
  • How to set up the cross-validation for Ridge and/or Lasso
  • -
  • Cross-validation in brief
  • -
  • Code Example for Cross-validation and \( k \)-fold Cross-validation
  • -
  • More examples on bootstrap and cross-validation and errors
  • -
  • The same example but now with cross-validation
  • -
  • Cross-validation with Ridge
  • +
  • Standard Approach based on the Normal Distribution
  • +
  • Resampling methods: Bootstrap background
  • +
  • Resampling methods: More Bootstrap background
  • +
  • Resampling methods: Bootstrap approach
  • +
  • Resampling methods: Bootstrap steps
  • +
  • Code example for the Bootstrap method
  • +
  • Plotting the Histogram
  • +
  • The bias-variance tradeoff
  • +
  • A way to Read the Bias-Variance Tradeoff
  • +
  • Example code for Bias-Variance tradeoff
  • +
  • Understanding what happens
  • +
  • Summing up
  • +
  • Another Example from Scikit-Learn's Repository
  • +
  • Various steps in cross-validation
  • +
  • How to set up the cross-validation for Ridge and/or Lasso
  • +
  • Cross-validation in brief
  • +
  • Code Example for Cross-validation and \( k \)-fold Cross-validation
  • +
  • More examples on bootstrap and cross-validation and errors
  • +
  • The same example but now with cross-validation
  • +
  • Cross-validation with Ridge
  • @@ -324,7 +329,7 @@ MathJax.Hub.Config({
  • 27
  • 28
  • ...
  • -
  • 49
  • +
  • 50
  • »
  • diff --git a/doc/pub/week37/html/._week37-bs019.html b/doc/pub/week37/html/._week37-bs019.html index 4cf039cf9..8a320e3fb 100644 --- a/doc/pub/week37/html/._week37-bs019.html +++ b/doc/pub/week37/html/._week37-bs019.html @@ -107,6 +107,10 @@ Automatically generated HTML file from DocOnce source ('Identifying Terms', 2, None, 'identifying-terms'), ('Wrapping it up', 2, None, 'wrapping-it-up'), ('Confidence Intervals', 2, None, 'confidence-intervals'), + ('Standard Approach based on the Normal Distribution', + 2, + None, + 'standard-approach-based-on-the-normal-distribution'), ('Resampling methods: Bootstrap background', 2, None, @@ -244,25 +248,26 @@ MathJax.Hub.Config({
  • Identifying Terms
  • Wrapping it up
  • Confidence Intervals
  • -
  • Resampling methods: Bootstrap background
  • -
  • Resampling methods: More Bootstrap background
  • -
  • Resampling methods: Bootstrap approach
  • -
  • Resampling methods: Bootstrap steps
  • -
  • Code example for the Bootstrap method
  • -
  • Plotting the Histogram
  • -
  • The bias-variance tradeoff
  • -
  • A way to Read the Bias-Variance Tradeoff
  • -
  • Example code for Bias-Variance tradeoff
  • -
  • Understanding what happens
  • -
  • Summing up
  • -
  • Another Example from Scikit-Learn's Repository
  • -
  • Various steps in cross-validation
  • -
  • How to set up the cross-validation for Ridge and/or Lasso
  • -
  • Cross-validation in brief
  • -
  • Code Example for Cross-validation and \( k \)-fold Cross-validation
  • -
  • More examples on bootstrap and cross-validation and errors
  • -
  • The same example but now with cross-validation
  • -
  • Cross-validation with Ridge
  • +
  • Standard Approach based on the Normal Distribution
  • +
  • Resampling methods: Bootstrap background
  • +
  • Resampling methods: More Bootstrap background
  • +
  • Resampling methods: Bootstrap approach
  • +
  • Resampling methods: Bootstrap steps
  • +
  • Code example for the Bootstrap method
  • +
  • Plotting the Histogram
  • +
  • The bias-variance tradeoff
  • +
  • A way to Read the Bias-Variance Tradeoff
  • +
  • Example code for Bias-Variance tradeoff
  • +
  • Understanding what happens
  • +
  • Summing up
  • +
  • Another Example from Scikit-Learn's Repository
  • +
  • Various steps in cross-validation
  • +
  • How to set up the cross-validation for Ridge and/or Lasso
  • +
  • Cross-validation in brief
  • +
  • Code Example for Cross-validation and \( k \)-fold Cross-validation
  • +
  • More examples on bootstrap and cross-validation and errors
  • +
  • The same example but now with cross-validation
  • +
  • Cross-validation with Ridge
  • @@ -330,7 +335,7 @@ training error reaches a saturation.
  • 28
  • 29
  • ...
  • -
  • 49
  • +
  • 50
  • »
  • diff --git a/doc/pub/week37/html/._week37-bs020.html b/doc/pub/week37/html/._week37-bs020.html index 5cdcbe802..3536f8fe1 100644 --- a/doc/pub/week37/html/._week37-bs020.html +++ b/doc/pub/week37/html/._week37-bs020.html @@ -107,6 +107,10 @@ Automatically generated HTML file from DocOnce source ('Identifying Terms', 2, None, 'identifying-terms'), ('Wrapping it up', 2, None, 'wrapping-it-up'), ('Confidence Intervals', 2, None, 'confidence-intervals'), + ('Standard Approach based on the Normal Distribution', + 2, + None, + 'standard-approach-based-on-the-normal-distribution'), ('Resampling methods: Bootstrap background', 2, None, @@ -244,25 +248,26 @@ MathJax.Hub.Config({
  • Identifying Terms
  • Wrapping it up
  • Confidence Intervals
  • -
  • Resampling methods: Bootstrap background
  • -
  • Resampling methods: More Bootstrap background
  • -
  • Resampling methods: Bootstrap approach
  • -
  • Resampling methods: Bootstrap steps
  • -
  • Code example for the Bootstrap method
  • -
  • Plotting the Histogram
  • -
  • The bias-variance tradeoff
  • -
  • A way to Read the Bias-Variance Tradeoff
  • -
  • Example code for Bias-Variance tradeoff
  • -
  • Understanding what happens
  • -
  • Summing up
  • -
  • Another Example from Scikit-Learn's Repository
  • -
  • Various steps in cross-validation
  • -
  • How to set up the cross-validation for Ridge and/or Lasso
  • -
  • Cross-validation in brief
  • -
  • Code Example for Cross-validation and \( k \)-fold Cross-validation
  • -
  • More examples on bootstrap and cross-validation and errors
  • -
  • The same example but now with cross-validation
  • -
  • Cross-validation with Ridge
  • +
  • Standard Approach based on the Normal Distribution
  • +
  • Resampling methods: Bootstrap background
  • +
  • Resampling methods: More Bootstrap background
  • +
  • Resampling methods: Bootstrap approach
  • +
  • Resampling methods: Bootstrap steps
  • +
  • Code example for the Bootstrap method
  • +
  • Plotting the Histogram
  • +
  • The bias-variance tradeoff
  • +
  • A way to Read the Bias-Variance Tradeoff
  • +
  • Example code for Bias-Variance tradeoff
  • +
  • Understanding what happens
  • +
  • Summing up
  • +
  • Another Example from Scikit-Learn's Repository
  • +
  • Various steps in cross-validation
  • +
  • How to set up the cross-validation for Ridge and/or Lasso
  • +
  • Cross-validation in brief
  • +
  • Code Example for Cross-validation and \( k \)-fold Cross-validation
  • +
  • More examples on bootstrap and cross-validation and errors
  • +
  • The same example but now with cross-validation
  • +
  • Cross-validation with Ridge
  • @@ -324,7 +329,7 @@ need for bootstrapping.
  • 29
  • 30
  • ...
  • -
  • 49
  • +
  • 50
  • »
  • diff --git a/doc/pub/week37/html/._week37-bs021.html b/doc/pub/week37/html/._week37-bs021.html index 4720dff62..a066d0e55 100644 --- a/doc/pub/week37/html/._week37-bs021.html +++ b/doc/pub/week37/html/._week37-bs021.html @@ -107,6 +107,10 @@ Automatically generated HTML file from DocOnce source ('Identifying Terms', 2, None, 'identifying-terms'), ('Wrapping it up', 2, None, 'wrapping-it-up'), ('Confidence Intervals', 2, None, 'confidence-intervals'), + ('Standard Approach based on the Normal Distribution', + 2, + None, + 'standard-approach-based-on-the-normal-distribution'), ('Resampling methods: Bootstrap background', 2, None, @@ -244,25 +248,26 @@ MathJax.Hub.Config({
  • Identifying Terms
  • Wrapping it up
  • Confidence Intervals
  • -
  • Resampling methods: Bootstrap background
  • -
  • Resampling methods: More Bootstrap background
  • -
  • Resampling methods: Bootstrap approach
  • -
  • Resampling methods: Bootstrap steps
  • -
  • Code example for the Bootstrap method
  • -
  • Plotting the Histogram
  • -
  • The bias-variance tradeoff
  • -
  • A way to Read the Bias-Variance Tradeoff
  • -
  • Example code for Bias-Variance tradeoff
  • -
  • Understanding what happens
  • -
  • Summing up
  • -
  • Another Example from Scikit-Learn's Repository
  • -
  • Various steps in cross-validation
  • -
  • How to set up the cross-validation for Ridge and/or Lasso
  • -
  • Cross-validation in brief
  • -
  • Code Example for Cross-validation and \( k \)-fold Cross-validation
  • -
  • More examples on bootstrap and cross-validation and errors
  • -
  • The same example but now with cross-validation
  • -
  • Cross-validation with Ridge
  • +
  • Standard Approach based on the Normal Distribution
  • +
  • Resampling methods: Bootstrap background
  • +
  • Resampling methods: More Bootstrap background
  • +
  • Resampling methods: Bootstrap approach
  • +
  • Resampling methods: Bootstrap steps
  • +
  • Code example for the Bootstrap method
  • +
  • Plotting the Histogram
  • +
  • The bias-variance tradeoff
  • +
  • A way to Read the Bias-Variance Tradeoff
  • +
  • Example code for Bias-Variance tradeoff
  • +
  • Understanding what happens
  • +
  • Summing up
  • +
  • Another Example from Scikit-Learn's Repository
  • +
  • Various steps in cross-validation
  • +
  • How to set up the cross-validation for Ridge and/or Lasso
  • +
  • Cross-validation in brief
  • +
  • Code Example for Cross-validation and \( k \)-fold Cross-validation
  • +
  • More examples on bootstrap and cross-validation and errors
  • +
  • The same example but now with cross-validation
  • +
  • Cross-validation with Ridge
  • @@ -320,7 +325,7 @@ number \( i \) is left out. Using this notation, define
  • 30
  • 31
  • ...
  • -
  • 49
  • +
  • 50
  • »
  • diff --git a/doc/pub/week37/html/._week37-bs022.html b/doc/pub/week37/html/._week37-bs022.html index 0bc5446aa..4cbef0650 100644 --- a/doc/pub/week37/html/._week37-bs022.html +++ b/doc/pub/week37/html/._week37-bs022.html @@ -107,6 +107,10 @@ Automatically generated HTML file from DocOnce source ('Identifying Terms', 2, None, 'identifying-terms'), ('Wrapping it up', 2, None, 'wrapping-it-up'), ('Confidence Intervals', 2, None, 'confidence-intervals'), + ('Standard Approach based on the Normal Distribution', + 2, + None, + 'standard-approach-based-on-the-normal-distribution'), ('Resampling methods: Bootstrap background', 2, None, @@ -244,25 +248,26 @@ MathJax.Hub.Config({
  • Identifying Terms
  • Wrapping it up
  • Confidence Intervals
  • -
  • Resampling methods: Bootstrap background
  • -
  • Resampling methods: More Bootstrap background
  • -
  • Resampling methods: Bootstrap approach
  • -
  • Resampling methods: Bootstrap steps
  • -
  • Code example for the Bootstrap method
  • -
  • Plotting the Histogram
  • -
  • The bias-variance tradeoff
  • -
  • A way to Read the Bias-Variance Tradeoff
  • -
  • Example code for Bias-Variance tradeoff
  • -
  • Understanding what happens
  • -
  • Summing up
  • -
  • Another Example from Scikit-Learn's Repository
  • -
  • Various steps in cross-validation
  • -
  • How to set up the cross-validation for Ridge and/or Lasso
  • -
  • Cross-validation in brief
  • -
  • Code Example for Cross-validation and \( k \)-fold Cross-validation
  • -
  • More examples on bootstrap and cross-validation and errors
  • -
  • The same example but now with cross-validation
  • -
  • Cross-validation with Ridge
  • +
  • Standard Approach based on the Normal Distribution
  • +
  • Resampling methods: Bootstrap background
  • +
  • Resampling methods: More Bootstrap background
  • +
  • Resampling methods: Bootstrap approach
  • +
  • Resampling methods: Bootstrap steps
  • +
  • Code example for the Bootstrap method
  • +
  • Plotting the Histogram
  • +
  • The bias-variance tradeoff
  • +
  • A way to Read the Bias-Variance Tradeoff
  • +
  • Example code for Bias-Variance tradeoff
  • +
  • Understanding what happens
  • +
  • Summing up
  • +
  • Another Example from Scikit-Learn's Repository
  • +
  • Various steps in cross-validation
  • +
  • How to set up the cross-validation for Ridge and/or Lasso
  • +
  • Cross-validation in brief
  • +
  • Code Example for Cross-validation and \( k \)-fold Cross-validation
  • +
  • More examples on bootstrap and cross-validation and errors
  • +
  • The same example but now with cross-validation
  • +
  • Cross-validation with Ridge
  • @@ -337,7 +342,7 @@ t = jackknife(x, stat)
  • 31
  • 32
  • ...
  • -
  • 49
  • +
  • 50
  • »
  • diff --git a/doc/pub/week37/html/._week37-bs023.html b/doc/pub/week37/html/._week37-bs023.html index 2f517da77..eef1a79a9 100644 --- a/doc/pub/week37/html/._week37-bs023.html +++ b/doc/pub/week37/html/._week37-bs023.html @@ -107,6 +107,10 @@ Automatically generated HTML file from DocOnce source ('Identifying Terms', 2, None, 'identifying-terms'), ('Wrapping it up', 2, None, 'wrapping-it-up'), ('Confidence Intervals', 2, None, 'confidence-intervals'), + ('Standard Approach based on the Normal Distribution', + 2, + None, + 'standard-approach-based-on-the-normal-distribution'), ('Resampling methods: Bootstrap background', 2, None, @@ -244,25 +248,26 @@ MathJax.Hub.Config({
  • Identifying Terms
  • Wrapping it up
  • Confidence Intervals
  • -
  • Resampling methods: Bootstrap background
  • -
  • Resampling methods: More Bootstrap background
  • -
  • Resampling methods: Bootstrap approach
  • -
  • Resampling methods: Bootstrap steps
  • -
  • Code example for the Bootstrap method
  • -
  • Plotting the Histogram
  • -
  • The bias-variance tradeoff
  • -
  • A way to Read the Bias-Variance Tradeoff
  • -
  • Example code for Bias-Variance tradeoff
  • -
  • Understanding what happens
  • -
  • Summing up
  • -
  • Another Example from Scikit-Learn's Repository
  • -
  • Various steps in cross-validation
  • -
  • How to set up the cross-validation for Ridge and/or Lasso
  • -
  • Cross-validation in brief
  • -
  • Code Example for Cross-validation and \( k \)-fold Cross-validation
  • -
  • More examples on bootstrap and cross-validation and errors
  • -
  • The same example but now with cross-validation
  • -
  • Cross-validation with Ridge
  • +
  • Standard Approach based on the Normal Distribution
  • +
  • Resampling methods: Bootstrap background
  • +
  • Resampling methods: More Bootstrap background
  • +
  • Resampling methods: Bootstrap approach
  • +
  • Resampling methods: Bootstrap steps
  • +
  • Code example for the Bootstrap method
  • +
  • Plotting the Histogram
  • +
  • The bias-variance tradeoff
  • +
  • A way to Read the Bias-Variance Tradeoff
  • +
  • Example code for Bias-Variance tradeoff
  • +
  • Understanding what happens
  • +
  • Summing up
  • +
  • Another Example from Scikit-Learn's Repository
  • +
  • Various steps in cross-validation
  • +
  • How to set up the cross-validation for Ridge and/or Lasso
  • +
  • Cross-validation in brief
  • +
  • Code Example for Cross-validation and \( k \)-fold Cross-validation
  • +
  • More examples on bootstrap and cross-validation and errors
  • +
  • The same example but now with cross-validation
  • +
  • Cross-validation with Ridge
  • @@ -329,7 +334,7 @@ Before we proceed however, we need to remind ourselves about a central theorem i
  • 32
  • 33
  • ...
  • -
  • 49
  • +
  • 50
  • »
  • diff --git a/doc/pub/week37/html/._week37-bs024.html b/doc/pub/week37/html/._week37-bs024.html index c83575a69..e9fdfa5c1 100644 --- a/doc/pub/week37/html/._week37-bs024.html +++ b/doc/pub/week37/html/._week37-bs024.html @@ -107,6 +107,10 @@ Automatically generated HTML file from DocOnce source ('Identifying Terms', 2, None, 'identifying-terms'), ('Wrapping it up', 2, None, 'wrapping-it-up'), ('Confidence Intervals', 2, None, 'confidence-intervals'), + ('Standard Approach based on the Normal Distribution', + 2, + None, + 'standard-approach-based-on-the-normal-distribution'), ('Resampling methods: Bootstrap background', 2, None, @@ -244,25 +248,26 @@ MathJax.Hub.Config({
  • Identifying Terms
  • Wrapping it up
  • Confidence Intervals
  • -
  • Resampling methods: Bootstrap background
  • -
  • Resampling methods: More Bootstrap background
  • -
  • Resampling methods: Bootstrap approach
  • -
  • Resampling methods: Bootstrap steps
  • -
  • Code example for the Bootstrap method
  • -
  • Plotting the Histogram
  • -
  • The bias-variance tradeoff
  • -
  • A way to Read the Bias-Variance Tradeoff
  • -
  • Example code for Bias-Variance tradeoff
  • -
  • Understanding what happens
  • -
  • Summing up
  • -
  • Another Example from Scikit-Learn's Repository
  • -
  • Various steps in cross-validation
  • -
  • How to set up the cross-validation for Ridge and/or Lasso
  • -
  • Cross-validation in brief
  • -
  • Code Example for Cross-validation and \( k \)-fold Cross-validation
  • -
  • More examples on bootstrap and cross-validation and errors
  • -
  • The same example but now with cross-validation
  • -
  • Cross-validation with Ridge
  • +
  • Standard Approach based on the Normal Distribution
  • +
  • Resampling methods: Bootstrap background
  • +
  • Resampling methods: More Bootstrap background
  • +
  • Resampling methods: Bootstrap approach
  • +
  • Resampling methods: Bootstrap steps
  • +
  • Code example for the Bootstrap method
  • +
  • Plotting the Histogram
  • +
  • The bias-variance tradeoff
  • +
  • A way to Read the Bias-Variance Tradeoff
  • +
  • Example code for Bias-Variance tradeoff
  • +
  • Understanding what happens
  • +
  • Summing up
  • +
  • Another Example from Scikit-Learn's Repository
  • +
  • Various steps in cross-validation
  • +
  • How to set up the cross-validation for Ridge and/or Lasso
  • +
  • Cross-validation in brief
  • +
  • Code Example for Cross-validation and \( k \)-fold Cross-validation
  • +
  • More examples on bootstrap and cross-validation and errors
  • +
  • The same example but now with cross-validation
  • +
  • Cross-validation with Ridge
  • @@ -323,7 +328,7 @@ the question we pose is which is the PDF of the new variable \( z \).
  • 33
  • 34
  • ...
  • -
  • 49
  • +
  • 50
  • »
  • diff --git a/doc/pub/week37/html/._week37-bs025.html b/doc/pub/week37/html/._week37-bs025.html index 1dea5c181..997d46288 100644 --- a/doc/pub/week37/html/._week37-bs025.html +++ b/doc/pub/week37/html/._week37-bs025.html @@ -107,6 +107,10 @@ Automatically generated HTML file from DocOnce source ('Identifying Terms', 2, None, 'identifying-terms'), ('Wrapping it up', 2, None, 'wrapping-it-up'), ('Confidence Intervals', 2, None, 'confidence-intervals'), + ('Standard Approach based on the Normal Distribution', + 2, + None, + 'standard-approach-based-on-the-normal-distribution'), ('Resampling methods: Bootstrap background', 2, None, @@ -244,25 +248,26 @@ MathJax.Hub.Config({
  • Identifying Terms
  • Wrapping it up
  • Confidence Intervals
  • -
  • Resampling methods: Bootstrap background
  • -
  • Resampling methods: More Bootstrap background
  • -
  • Resampling methods: Bootstrap approach
  • -
  • Resampling methods: Bootstrap steps
  • -
  • Code example for the Bootstrap method
  • -
  • Plotting the Histogram
  • -
  • The bias-variance tradeoff
  • -
  • A way to Read the Bias-Variance Tradeoff
  • -
  • Example code for Bias-Variance tradeoff
  • -
  • Understanding what happens
  • -
  • Summing up
  • -
  • Another Example from Scikit-Learn's Repository
  • -
  • Various steps in cross-validation
  • -
  • How to set up the cross-validation for Ridge and/or Lasso
  • -
  • Cross-validation in brief
  • -
  • Code Example for Cross-validation and \( k \)-fold Cross-validation
  • -
  • More examples on bootstrap and cross-validation and errors
  • -
  • The same example but now with cross-validation
  • -
  • Cross-validation with Ridge
  • +
  • Standard Approach based on the Normal Distribution
  • +
  • Resampling methods: Bootstrap background
  • +
  • Resampling methods: More Bootstrap background
  • +
  • Resampling methods: Bootstrap approach
  • +
  • Resampling methods: Bootstrap steps
  • +
  • Code example for the Bootstrap method
  • +
  • Plotting the Histogram
  • +
  • The bias-variance tradeoff
  • +
  • A way to Read the Bias-Variance Tradeoff
  • +
  • Example code for Bias-Variance tradeoff
  • +
  • Understanding what happens
  • +
  • Summing up
  • +
  • Another Example from Scikit-Learn's Repository
  • +
  • Various steps in cross-validation
  • +
  • How to set up the cross-validation for Ridge and/or Lasso
  • +
  • Cross-validation in brief
  • +
  • Code Example for Cross-validation and \( k \)-fold Cross-validation
  • +
  • More examples on bootstrap and cross-validation and errors
  • +
  • The same example but now with cross-validation
  • +
  • Cross-validation with Ridge
  • @@ -321,7 +326,7 @@ product of individual \( p(x_i) \). The independence assumption is important in
  • 34
  • 35
  • ...
  • -
  • 49
  • +
  • 50
  • »
  • diff --git a/doc/pub/week37/html/._week37-bs026.html b/doc/pub/week37/html/._week37-bs026.html index d5f3f4423..179f172d8 100644 --- a/doc/pub/week37/html/._week37-bs026.html +++ b/doc/pub/week37/html/._week37-bs026.html @@ -107,6 +107,10 @@ Automatically generated HTML file from DocOnce source ('Identifying Terms', 2, None, 'identifying-terms'), ('Wrapping it up', 2, None, 'wrapping-it-up'), ('Confidence Intervals', 2, None, 'confidence-intervals'), + ('Standard Approach based on the Normal Distribution', + 2, + None, + 'standard-approach-based-on-the-normal-distribution'), ('Resampling methods: Bootstrap background', 2, None, @@ -244,25 +248,26 @@ MathJax.Hub.Config({
  • Identifying Terms
  • Wrapping it up
  • Confidence Intervals
  • -
  • Resampling methods: Bootstrap background
  • -
  • Resampling methods: More Bootstrap background
  • -
  • Resampling methods: Bootstrap approach
  • -
  • Resampling methods: Bootstrap steps
  • -
  • Code example for the Bootstrap method
  • -
  • Plotting the Histogram
  • -
  • The bias-variance tradeoff
  • -
  • A way to Read the Bias-Variance Tradeoff
  • -
  • Example code for Bias-Variance tradeoff
  • -
  • Understanding what happens
  • -
  • Summing up
  • -
  • Another Example from Scikit-Learn's Repository
  • -
  • Various steps in cross-validation
  • -
  • How to set up the cross-validation for Ridge and/or Lasso
  • -
  • Cross-validation in brief
  • -
  • Code Example for Cross-validation and \( k \)-fold Cross-validation
  • -
  • More examples on bootstrap and cross-validation and errors
  • -
  • The same example but now with cross-validation
  • -
  • Cross-validation with Ridge
  • +
  • Standard Approach based on the Normal Distribution
  • +
  • Resampling methods: Bootstrap background
  • +
  • Resampling methods: More Bootstrap background
  • +
  • Resampling methods: Bootstrap approach
  • +
  • Resampling methods: Bootstrap steps
  • +
  • Code example for the Bootstrap method
  • +
  • Plotting the Histogram
  • +
  • The bias-variance tradeoff
  • +
  • A way to Read the Bias-Variance Tradeoff
  • +
  • Example code for Bias-Variance tradeoff
  • +
  • Understanding what happens
  • +
  • Summing up
  • +
  • Another Example from Scikit-Learn's Repository
  • +
  • Various steps in cross-validation
  • +
  • How to set up the cross-validation for Ridge and/or Lasso
  • +
  • Cross-validation in brief
  • +
  • Code Example for Cross-validation and \( k \)-fold Cross-validation
  • +
  • More examples on bootstrap and cross-validation and errors
  • +
  • The same example but now with cross-validation
  • +
  • Cross-validation with Ridge
  • @@ -330,7 +335,7 @@ $$
  • 35
  • 36
  • ...
  • -
  • 49
  • +
  • 50
  • »
  • diff --git a/doc/pub/week37/html/._week37-bs027.html b/doc/pub/week37/html/._week37-bs027.html index 0eb1e4da9..be548ef7f 100644 --- a/doc/pub/week37/html/._week37-bs027.html +++ b/doc/pub/week37/html/._week37-bs027.html @@ -107,6 +107,10 @@ Automatically generated HTML file from DocOnce source ('Identifying Terms', 2, None, 'identifying-terms'), ('Wrapping it up', 2, None, 'wrapping-it-up'), ('Confidence Intervals', 2, None, 'confidence-intervals'), + ('Standard Approach based on the Normal Distribution', + 2, + None, + 'standard-approach-based-on-the-normal-distribution'), ('Resampling methods: Bootstrap background', 2, None, @@ -244,25 +248,26 @@ MathJax.Hub.Config({
  • Identifying Terms
  • Wrapping it up
  • Confidence Intervals
  • -
  • Resampling methods: Bootstrap background
  • -
  • Resampling methods: More Bootstrap background
  • -
  • Resampling methods: Bootstrap approach
  • -
  • Resampling methods: Bootstrap steps
  • -
  • Code example for the Bootstrap method
  • -
  • Plotting the Histogram
  • -
  • The bias-variance tradeoff
  • -
  • A way to Read the Bias-Variance Tradeoff
  • -
  • Example code for Bias-Variance tradeoff
  • -
  • Understanding what happens
  • -
  • Summing up
  • -
  • Another Example from Scikit-Learn's Repository
  • -
  • Various steps in cross-validation
  • -
  • How to set up the cross-validation for Ridge and/or Lasso
  • -
  • Cross-validation in brief
  • -
  • Code Example for Cross-validation and \( k \)-fold Cross-validation
  • -
  • More examples on bootstrap and cross-validation and errors
  • -
  • The same example but now with cross-validation
  • -
  • Cross-validation with Ridge
  • +
  • Standard Approach based on the Normal Distribution
  • +
  • Resampling methods: Bootstrap background
  • +
  • Resampling methods: More Bootstrap background
  • +
  • Resampling methods: Bootstrap approach
  • +
  • Resampling methods: Bootstrap steps
  • +
  • Code example for the Bootstrap method
  • +
  • Plotting the Histogram
  • +
  • The bias-variance tradeoff
  • +
  • A way to Read the Bias-Variance Tradeoff
  • +
  • Example code for Bias-Variance tradeoff
  • +
  • Understanding what happens
  • +
  • Summing up
  • +
  • Another Example from Scikit-Learn's Repository
  • +
  • Various steps in cross-validation
  • +
  • How to set up the cross-validation for Ridge and/or Lasso
  • +
  • Cross-validation in brief
  • +
  • Code Example for Cross-validation and \( k \)-fold Cross-validation
  • +
  • More examples on bootstrap and cross-validation and errors
  • +
  • The same example but now with cross-validation
  • +
  • Cross-validation with Ridge
  • @@ -332,7 +337,7 @@ and \( \mu \) is also the mean of the PDF \( p(x) \).
  • 36
  • 37
  • ...
  • -
  • 49
  • +
  • 50
  • »
  • diff --git a/doc/pub/week37/html/._week37-bs028.html b/doc/pub/week37/html/._week37-bs028.html index 9a94e716c..8ee114b55 100644 --- a/doc/pub/week37/html/._week37-bs028.html +++ b/doc/pub/week37/html/._week37-bs028.html @@ -107,6 +107,10 @@ Automatically generated HTML file from DocOnce source ('Identifying Terms', 2, None, 'identifying-terms'), ('Wrapping it up', 2, None, 'wrapping-it-up'), ('Confidence Intervals', 2, None, 'confidence-intervals'), + ('Standard Approach based on the Normal Distribution', + 2, + None, + 'standard-approach-based-on-the-normal-distribution'), ('Resampling methods: Bootstrap background', 2, None, @@ -244,25 +248,26 @@ MathJax.Hub.Config({
  • Identifying Terms
  • Wrapping it up
  • Confidence Intervals
  • -
  • Resampling methods: Bootstrap background
  • -
  • Resampling methods: More Bootstrap background
  • -
  • Resampling methods: Bootstrap approach
  • -
  • Resampling methods: Bootstrap steps
  • -
  • Code example for the Bootstrap method
  • -
  • Plotting the Histogram
  • -
  • The bias-variance tradeoff
  • -
  • A way to Read the Bias-Variance Tradeoff
  • -
  • Example code for Bias-Variance tradeoff
  • -
  • Understanding what happens
  • -
  • Summing up
  • -
  • Another Example from Scikit-Learn's Repository
  • -
  • Various steps in cross-validation
  • -
  • How to set up the cross-validation for Ridge and/or Lasso
  • -
  • Cross-validation in brief
  • -
  • Code Example for Cross-validation and \( k \)-fold Cross-validation
  • -
  • More examples on bootstrap and cross-validation and errors
  • -
  • The same example but now with cross-validation
  • -
  • Cross-validation with Ridge
  • +
  • Standard Approach based on the Normal Distribution
  • +
  • Resampling methods: Bootstrap background
  • +
  • Resampling methods: More Bootstrap background
  • +
  • Resampling methods: Bootstrap approach
  • +
  • Resampling methods: Bootstrap steps
  • +
  • Code example for the Bootstrap method
  • +
  • Plotting the Histogram
  • +
  • The bias-variance tradeoff
  • +
  • A way to Read the Bias-Variance Tradeoff
  • +
  • Example code for Bias-Variance tradeoff
  • +
  • Understanding what happens
  • +
  • Summing up
  • +
  • Another Example from Scikit-Learn's Repository
  • +
  • Various steps in cross-validation
  • +
  • How to set up the cross-validation for Ridge and/or Lasso
  • +
  • Cross-validation in brief
  • +
  • Code Example for Cross-validation and \( k \)-fold Cross-validation
  • +
  • More examples on bootstrap and cross-validation and errors
  • +
  • The same example but now with cross-validation
  • +
  • Cross-validation with Ridge
  • @@ -338,7 +343,7 @@ in particular if correlations are strong, may be too simplistic.
  • 37
  • 38
  • ...
  • -
  • 49
  • +
  • 50
  • »
  • diff --git a/doc/pub/week37/html/._week37-bs029.html b/doc/pub/week37/html/._week37-bs029.html index 8a968dea6..e12afed29 100644 --- a/doc/pub/week37/html/._week37-bs029.html +++ b/doc/pub/week37/html/._week37-bs029.html @@ -107,6 +107,10 @@ Automatically generated HTML file from DocOnce source ('Identifying Terms', 2, None, 'identifying-terms'), ('Wrapping it up', 2, None, 'wrapping-it-up'), ('Confidence Intervals', 2, None, 'confidence-intervals'), + ('Standard Approach based on the Normal Distribution', + 2, + None, + 'standard-approach-based-on-the-normal-distribution'), ('Resampling methods: Bootstrap background', 2, None, @@ -244,25 +248,26 @@ MathJax.Hub.Config({
  • Identifying Terms
  • Wrapping it up
  • Confidence Intervals
  • -
  • Resampling methods: Bootstrap background
  • -
  • Resampling methods: More Bootstrap background
  • -
  • Resampling methods: Bootstrap approach
  • -
  • Resampling methods: Bootstrap steps
  • -
  • Code example for the Bootstrap method
  • -
  • Plotting the Histogram
  • -
  • The bias-variance tradeoff
  • -
  • A way to Read the Bias-Variance Tradeoff
  • -
  • Example code for Bias-Variance tradeoff
  • -
  • Understanding what happens
  • -
  • Summing up
  • -
  • Another Example from Scikit-Learn's Repository
  • -
  • Various steps in cross-validation
  • -
  • How to set up the cross-validation for Ridge and/or Lasso
  • -
  • Cross-validation in brief
  • -
  • Code Example for Cross-validation and \( k \)-fold Cross-validation
  • -
  • More examples on bootstrap and cross-validation and errors
  • -
  • The same example but now with cross-validation
  • -
  • Cross-validation with Ridge
  • +
  • Standard Approach based on the Normal Distribution
  • +
  • Resampling methods: Bootstrap background
  • +
  • Resampling methods: More Bootstrap background
  • +
  • Resampling methods: Bootstrap approach
  • +
  • Resampling methods: Bootstrap steps
  • +
  • Code example for the Bootstrap method
  • +
  • Plotting the Histogram
  • +
  • The bias-variance tradeoff
  • +
  • A way to Read the Bias-Variance Tradeoff
  • +
  • Example code for Bias-Variance tradeoff
  • +
  • Understanding what happens
  • +
  • Summing up
  • +
  • Another Example from Scikit-Learn's Repository
  • +
  • Various steps in cross-validation
  • +
  • How to set up the cross-validation for Ridge and/or Lasso
  • +
  • Cross-validation in brief
  • +
  • Code Example for Cross-validation and \( k \)-fold Cross-validation
  • +
  • More examples on bootstrap and cross-validation and errors
  • +
  • The same example but now with cross-validation
  • +
  • Cross-validation with Ridge
  • @@ -280,6 +285,23 @@ MathJax.Hub.Config({

    Confidence Intervals

    +

    +Confidence intervals are used in statistics is a type of estimate +computed from the observed data. This gives a range of values for an +unknown parameter such as the parameters \( \boldsymbol{\beta} \) from linear regression. + +

    +With the OLS expressions for the parameters \( \boldsymbol{\beta} \) we found +\( \mathbb{E}(\boldsymbol{\beta}) = \boldsymbol{\beta} \), which means that the estimator of the regression parameters is unbiased. + +

    +We found also that the variance of the estimate of the \( j \)-th regression coefficient is +\( \boldsymbol{\sigma}^2 (\boldsymbol{\beta}_j ) = \boldsymbol{\sigma}^2 [(\mathbf{X}^{T} \mathbf{X})^{-1}]_{jj} \). + +

    +This quantity will be used to +construct a confidence interval for the estimates. +

    @@ -306,7 +328,7 @@ MathJax.Hub.Config({

  • 38
  • 39
  • ...
  • -
  • 49
  • +
  • 50
  • »
  • diff --git a/doc/pub/week37/html/._week37-bs030.html b/doc/pub/week37/html/._week37-bs030.html index 6f77ecd2f..41ca0cf00 100644 --- a/doc/pub/week37/html/._week37-bs030.html +++ b/doc/pub/week37/html/._week37-bs030.html @@ -107,6 +107,10 @@ Automatically generated HTML file from DocOnce source ('Identifying Terms', 2, None, 'identifying-terms'), ('Wrapping it up', 2, None, 'wrapping-it-up'), ('Confidence Intervals', 2, None, 'confidence-intervals'), + ('Standard Approach based on the Normal Distribution', + 2, + None, + 'standard-approach-based-on-the-normal-distribution'), ('Resampling methods: Bootstrap background', 2, None, @@ -244,25 +248,26 @@ MathJax.Hub.Config({
  • Identifying Terms
  • Wrapping it up
  • Confidence Intervals
  • -
  • Resampling methods: Bootstrap background
  • -
  • Resampling methods: More Bootstrap background
  • -
  • Resampling methods: Bootstrap approach
  • -
  • Resampling methods: Bootstrap steps
  • -
  • Code example for the Bootstrap method
  • -
  • Plotting the Histogram
  • -
  • The bias-variance tradeoff
  • -
  • A way to Read the Bias-Variance Tradeoff
  • -
  • Example code for Bias-Variance tradeoff
  • -
  • Understanding what happens
  • -
  • Summing up
  • -
  • Another Example from Scikit-Learn's Repository
  • -
  • Various steps in cross-validation
  • -
  • How to set up the cross-validation for Ridge and/or Lasso
  • -
  • Cross-validation in brief
  • -
  • Code Example for Cross-validation and \( k \)-fold Cross-validation
  • -
  • More examples on bootstrap and cross-validation and errors
  • -
  • The same example but now with cross-validation
  • -
  • Cross-validation with Ridge
  • +
  • Standard Approach based on the Normal Distribution
  • +
  • Resampling methods: Bootstrap background
  • +
  • Resampling methods: More Bootstrap background
  • +
  • Resampling methods: Bootstrap approach
  • +
  • Resampling methods: Bootstrap steps
  • +
  • Code example for the Bootstrap method
  • +
  • Plotting the Histogram
  • +
  • The bias-variance tradeoff
  • +
  • A way to Read the Bias-Variance Tradeoff
  • +
  • Example code for Bias-Variance tradeoff
  • +
  • Understanding what happens
  • +
  • Summing up
  • +
  • Another Example from Scikit-Learn's Repository
  • +
  • Various steps in cross-validation
  • +
  • How to set up the cross-validation for Ridge and/or Lasso
  • +
  • Cross-validation in brief
  • +
  • Code Example for Cross-validation and \( k \)-fold Cross-validation
  • +
  • More examples on bootstrap and cross-validation and errors
  • +
  • The same example but now with cross-validation
  • +
  • Cross-validation with Ridge
  • @@ -278,18 +283,32 @@ MathJax.Hub.Config({ -

    Resampling methods: Bootstrap background

    +

    Standard Approach based on the Normal Distribution

    -Since \( \widehat{\beta} = \widehat{\beta}(\boldsymbol{X}) \) is a function of random variables, -\( \widehat{\beta} \) itself must be a random variable. Thus it has -a pdf, call this function \( p(\boldsymbol{t}) \). The aim of the bootstrap is to -estimate \( p(\boldsymbol{t}) \) by the relative frequency of -\( \widehat{\beta} \). You can think of this as using a histogram -in the place of \( p(\boldsymbol{t}) \). If the relative frequency closely -resembles \( p(\vec{t}) \), then using numerics, it is straight forward to -estimate all the interesting parameters of \( p(\boldsymbol{t}) \) using point -estimators. +We will assume that the parameters \( \beta \) follow a normal +distribution. We can then define the confidence interval. Here we will be using as +shorthands \( \mu_{\beta} \) for the above mean value and \( \sigma_{\beta} \) +for the standard deviation. We have then a confidence interval + +$$ +\left(\mu_{\beta}\pm \frac{z\sigma_{\beta}}{\sqrt{n}}\right), +$$ + +

    +where \( z \) defines the level of certainty (or confidence). For a normal +distribution typical parameters are \( z=2.576 \) which corresponds to a +confidence of \( 99\% \) while \( z=1.96 \) corresponds to a confidence of +\( 95\% \). A confidence level of \( 95\% \) is commonly used and it is +normally referred to as a two-sigmas confidence level, that is we +approximate \( z\approx 2 \). + +

    +For more discussions of confidence intervals (and in particular linked with a discussion of the bootstrap method), see chapter 5 of the textbook by Davison on the Bootstrap Methods and their Applications + +

    +In this text you will also find an in-depth discussion of the +Bootstrap method, why it works and various theorems related to it.

    @@ -317,7 +336,7 @@ estimators.

  • 39
  • 40
  • ...
  • -
  • 49
  • +
  • 50
  • »
  • diff --git a/doc/pub/week37/html/._week37-bs031.html b/doc/pub/week37/html/._week37-bs031.html index 967a7319a..3216467fa 100644 --- a/doc/pub/week37/html/._week37-bs031.html +++ b/doc/pub/week37/html/._week37-bs031.html @@ -107,6 +107,10 @@ Automatically generated HTML file from DocOnce source ('Identifying Terms', 2, None, 'identifying-terms'), ('Wrapping it up', 2, None, 'wrapping-it-up'), ('Confidence Intervals', 2, None, 'confidence-intervals'), + ('Standard Approach based on the Normal Distribution', + 2, + None, + 'standard-approach-based-on-the-normal-distribution'), ('Resampling methods: Bootstrap background', 2, None, @@ -244,25 +248,26 @@ MathJax.Hub.Config({
  • Identifying Terms
  • Wrapping it up
  • Confidence Intervals
  • -
  • Resampling methods: Bootstrap background
  • -
  • Resampling methods: More Bootstrap background
  • -
  • Resampling methods: Bootstrap approach
  • -
  • Resampling methods: Bootstrap steps
  • -
  • Code example for the Bootstrap method
  • -
  • Plotting the Histogram
  • -
  • The bias-variance tradeoff
  • -
  • A way to Read the Bias-Variance Tradeoff
  • -
  • Example code for Bias-Variance tradeoff
  • -
  • Understanding what happens
  • -
  • Summing up
  • -
  • Another Example from Scikit-Learn's Repository
  • -
  • Various steps in cross-validation
  • -
  • How to set up the cross-validation for Ridge and/or Lasso
  • -
  • Cross-validation in brief
  • -
  • Code Example for Cross-validation and \( k \)-fold Cross-validation
  • -
  • More examples on bootstrap and cross-validation and errors
  • -
  • The same example but now with cross-validation
  • -
  • Cross-validation with Ridge
  • +
  • Standard Approach based on the Normal Distribution
  • +
  • Resampling methods: Bootstrap background
  • +
  • Resampling methods: More Bootstrap background
  • +
  • Resampling methods: Bootstrap approach
  • +
  • Resampling methods: Bootstrap steps
  • +
  • Code example for the Bootstrap method
  • +
  • Plotting the Histogram
  • +
  • The bias-variance tradeoff
  • +
  • A way to Read the Bias-Variance Tradeoff
  • +
  • Example code for Bias-Variance tradeoff
  • +
  • Understanding what happens
  • +
  • Summing up
  • +
  • Another Example from Scikit-Learn's Repository
  • +
  • Various steps in cross-validation
  • +
  • How to set up the cross-validation for Ridge and/or Lasso
  • +
  • Cross-validation in brief
  • +
  • Code Example for Cross-validation and \( k \)-fold Cross-validation
  • +
  • More examples on bootstrap and cross-validation and errors
  • +
  • The same example but now with cross-validation
  • +
  • Cross-validation with Ridge
  • @@ -278,24 +283,18 @@ MathJax.Hub.Config({ -

    Resampling methods: More Bootstrap background

    +

    Resampling methods: Bootstrap background

    -In the case that \( \widehat{\beta} \) has -more than one component, and the components are independent, we use the -same estimator on each component separately. If the probability -density function of \( X_i \), \( p(x) \), had been known, then it would have -been straightforward to do this by: - -

      -
    1. Drawing lots of numbers from \( p(x) \), suppose we call one such set of numbers \( (X_1^*, X_2^*, \cdots, X_n^*) \).
    2. -
    3. Then using these numbers, we could compute a replica of \( \widehat{\beta} \) called \( \widehat{\beta}^* \).
    4. -
    - -By repeated use of the above two points, many -estimates of \( \widehat{\beta} \) can be obtained. The -idea is to use the relative frequency of \( \widehat{\beta}^* \) -(think of a histogram) as an estimate of \( p(\boldsymbol{t}) \). +Since \( \widehat{\beta} = \widehat{\beta}(\boldsymbol{X}) \) is a function of random variables, +\( \widehat{\beta} \) itself must be a random variable. Thus it has +a pdf, call this function \( p(\boldsymbol{t}) \). The aim of the bootstrap is to +estimate \( p(\boldsymbol{t}) \) by the relative frequency of +\( \widehat{\beta} \). You can think of this as using a histogram +in the place of \( p(\boldsymbol{t}) \). If the relative frequency closely +resembles \( p(\vec{t}) \), then using numerics, it is straight forward to +estimate all the interesting parameters of \( p(\boldsymbol{t}) \) using point +estimators.

    @@ -323,7 +322,7 @@ idea is to use the relative frequency of \( \widehat{\beta}^* \)

  • 40
  • 41
  • ...
  • -
  • 49
  • +
  • 50
  • »
  • diff --git a/doc/pub/week37/html/._week37-bs032.html b/doc/pub/week37/html/._week37-bs032.html index c3b39e6a9..07bd0eda2 100644 --- a/doc/pub/week37/html/._week37-bs032.html +++ b/doc/pub/week37/html/._week37-bs032.html @@ -107,6 +107,10 @@ Automatically generated HTML file from DocOnce source ('Identifying Terms', 2, None, 'identifying-terms'), ('Wrapping it up', 2, None, 'wrapping-it-up'), ('Confidence Intervals', 2, None, 'confidence-intervals'), + ('Standard Approach based on the Normal Distribution', + 2, + None, + 'standard-approach-based-on-the-normal-distribution'), ('Resampling methods: Bootstrap background', 2, None, @@ -244,25 +248,26 @@ MathJax.Hub.Config({
  • Identifying Terms
  • Wrapping it up
  • Confidence Intervals
  • -
  • Resampling methods: Bootstrap background
  • -
  • Resampling methods: More Bootstrap background
  • -
  • Resampling methods: Bootstrap approach
  • -
  • Resampling methods: Bootstrap steps
  • -
  • Code example for the Bootstrap method
  • -
  • Plotting the Histogram
  • -
  • The bias-variance tradeoff
  • -
  • A way to Read the Bias-Variance Tradeoff
  • -
  • Example code for Bias-Variance tradeoff
  • -
  • Understanding what happens
  • -
  • Summing up
  • -
  • Another Example from Scikit-Learn's Repository
  • -
  • Various steps in cross-validation
  • -
  • How to set up the cross-validation for Ridge and/or Lasso
  • -
  • Cross-validation in brief
  • -
  • Code Example for Cross-validation and \( k \)-fold Cross-validation
  • -
  • More examples on bootstrap and cross-validation and errors
  • -
  • The same example but now with cross-validation
  • -
  • Cross-validation with Ridge
  • +
  • Standard Approach based on the Normal Distribution
  • +
  • Resampling methods: Bootstrap background
  • +
  • Resampling methods: More Bootstrap background
  • +
  • Resampling methods: Bootstrap approach
  • +
  • Resampling methods: Bootstrap steps
  • +
  • Code example for the Bootstrap method
  • +
  • Plotting the Histogram
  • +
  • The bias-variance tradeoff
  • +
  • A way to Read the Bias-Variance Tradeoff
  • +
  • Example code for Bias-Variance tradeoff
  • +
  • Understanding what happens
  • +
  • Summing up
  • +
  • Another Example from Scikit-Learn's Repository
  • +
  • Various steps in cross-validation
  • +
  • How to set up the cross-validation for Ridge and/or Lasso
  • +
  • Cross-validation in brief
  • +
  • Code Example for Cross-validation and \( k \)-fold Cross-validation
  • +
  • More examples on bootstrap and cross-validation and errors
  • +
  • The same example but now with cross-validation
  • +
  • Cross-validation with Ridge
  • @@ -278,20 +283,24 @@ MathJax.Hub.Config({ -

    Resampling methods: Bootstrap approach

    +

    Resampling methods: More Bootstrap background

    -But -unless there is enough information available about the process that -generated \( X_1,X_2,\cdots,X_n \), \( p(x) \) is in general -unknown. Therefore, Efron in 1979 asked the -question: What if we replace \( p(x) \) by the relative frequency -of the observation \( X_i \)? +In the case that \( \widehat{\beta} \) has +more than one component, and the components are independent, we use the +same estimator on each component separately. If the probability +density function of \( X_i \), \( p(x) \), had been known, then it would have +been straightforward to do this by: -

    -If we draw observations in accordance with -the relative frequency of the observations, will we obtain the same -result in some asymptotic sense? The answer is yes. +

      +
    1. Drawing lots of numbers from \( p(x) \), suppose we call one such set of numbers \( (X_1^*, X_2^*, \cdots, X_n^*) \).
    2. +
    3. Then using these numbers, we could compute a replica of \( \widehat{\beta} \) called \( \widehat{\beta}^* \).
    4. +
    + +By repeated use of the above two points, many +estimates of \( \widehat{\beta} \) can be obtained. The +idea is to use the relative frequency of \( \widehat{\beta}^* \) +(think of a histogram) as an estimate of \( p(\boldsymbol{t}) \).

    @@ -319,7 +328,7 @@ result in some asymptotic sense? The answer is yes.

  • 41
  • 42
  • ...
  • -
  • 49
  • +
  • 50
  • »
  • diff --git a/doc/pub/week37/html/._week37-bs033.html b/doc/pub/week37/html/._week37-bs033.html index 93bbdb824..a5326292c 100644 --- a/doc/pub/week37/html/._week37-bs033.html +++ b/doc/pub/week37/html/._week37-bs033.html @@ -107,6 +107,10 @@ Automatically generated HTML file from DocOnce source ('Identifying Terms', 2, None, 'identifying-terms'), ('Wrapping it up', 2, None, 'wrapping-it-up'), ('Confidence Intervals', 2, None, 'confidence-intervals'), + ('Standard Approach based on the Normal Distribution', + 2, + None, + 'standard-approach-based-on-the-normal-distribution'), ('Resampling methods: Bootstrap background', 2, None, @@ -244,25 +248,26 @@ MathJax.Hub.Config({
  • Identifying Terms
  • Wrapping it up
  • Confidence Intervals
  • -
  • Resampling methods: Bootstrap background
  • -
  • Resampling methods: More Bootstrap background
  • -
  • Resampling methods: Bootstrap approach
  • -
  • Resampling methods: Bootstrap steps
  • -
  • Code example for the Bootstrap method
  • -
  • Plotting the Histogram
  • -
  • The bias-variance tradeoff
  • -
  • A way to Read the Bias-Variance Tradeoff
  • -
  • Example code for Bias-Variance tradeoff
  • -
  • Understanding what happens
  • -
  • Summing up
  • -
  • Another Example from Scikit-Learn's Repository
  • -
  • Various steps in cross-validation
  • -
  • How to set up the cross-validation for Ridge and/or Lasso
  • -
  • Cross-validation in brief
  • -
  • Code Example for Cross-validation and \( k \)-fold Cross-validation
  • -
  • More examples on bootstrap and cross-validation and errors
  • -
  • The same example but now with cross-validation
  • -
  • Cross-validation with Ridge
  • +
  • Standard Approach based on the Normal Distribution
  • +
  • Resampling methods: Bootstrap background
  • +
  • Resampling methods: More Bootstrap background
  • +
  • Resampling methods: Bootstrap approach
  • +
  • Resampling methods: Bootstrap steps
  • +
  • Code example for the Bootstrap method
  • +
  • Plotting the Histogram
  • +
  • The bias-variance tradeoff
  • +
  • A way to Read the Bias-Variance Tradeoff
  • +
  • Example code for Bias-Variance tradeoff
  • +
  • Understanding what happens
  • +
  • Summing up
  • +
  • Another Example from Scikit-Learn's Repository
  • +
  • Various steps in cross-validation
  • +
  • How to set up the cross-validation for Ridge and/or Lasso
  • +
  • Cross-validation in brief
  • +
  • Code Example for Cross-validation and \( k \)-fold Cross-validation
  • +
  • More examples on bootstrap and cross-validation and errors
  • +
  • The same example but now with cross-validation
  • +
  • Cross-validation with Ridge
  • @@ -278,27 +283,20 @@ MathJax.Hub.Config({ -

    Resampling methods: Bootstrap steps

    +

    Resampling methods: Bootstrap approach

    -The independent bootstrap works like this: +But +unless there is enough information available about the process that +generated \( X_1,X_2,\cdots,X_n \), \( p(x) \) is in general +unknown. Therefore, Efron in 1979 asked the +question: What if we replace \( p(x) \) by the relative frequency +of the observation \( X_i \)? -

      -
    1. Draw with replacement \( n \) numbers for the observed variables \( \boldsymbol{x} = (x_1,x_2,\cdots,x_n) \).
    2. -
    3. Define a vector \( \boldsymbol{x}^* \) containing the values which were drawn from \( \boldsymbol{x} \).
    4. -
    5. Using the vector \( \boldsymbol{x}^* \) compute \( \widehat{\beta}^* \) by evaluating \( \widehat \beta \) under the observations \( \boldsymbol{x}^* \).
    6. -
    7. Repeat this process \( k \) times.
    8. -
    - -When you are done, you can draw a histogram of the relative frequency -of \( \widehat \beta^* \). This is your estimate of the probability -distribution \( p(t) \). Using this probability distribution you can -estimate any statistics thereof. In principle you never draw the -histogram of the relative frequency of \( \widehat{\beta}^* \). Instead -you use the estimators corresponding to the statistic of interest. For -example, if you are interested in estimating the variance of \( \widehat -\beta \), apply the etsimator \( \widehat \sigma^2 \) to the values -\( \widehat \beta^* \). +

    +If we draw observations in accordance with +the relative frequency of the observations, will we obtain the same +result in some asymptotic sense? The answer is yes.

    @@ -326,7 +324,7 @@ example, if you are interested in estimating the variance of \( \widehat

  • 42
  • 43
  • ...
  • -
  • 49
  • +
  • 50
  • »
  • diff --git a/doc/pub/week37/html/._week37-bs034.html b/doc/pub/week37/html/._week37-bs034.html index 2a1d959bf..075043c3d 100644 --- a/doc/pub/week37/html/._week37-bs034.html +++ b/doc/pub/week37/html/._week37-bs034.html @@ -107,6 +107,10 @@ Automatically generated HTML file from DocOnce source ('Identifying Terms', 2, None, 'identifying-terms'), ('Wrapping it up', 2, None, 'wrapping-it-up'), ('Confidence Intervals', 2, None, 'confidence-intervals'), + ('Standard Approach based on the Normal Distribution', + 2, + None, + 'standard-approach-based-on-the-normal-distribution'), ('Resampling methods: Bootstrap background', 2, None, @@ -244,25 +248,26 @@ MathJax.Hub.Config({
  • Identifying Terms
  • Wrapping it up
  • Confidence Intervals
  • -
  • Resampling methods: Bootstrap background
  • -
  • Resampling methods: More Bootstrap background
  • -
  • Resampling methods: Bootstrap approach
  • -
  • Resampling methods: Bootstrap steps
  • -
  • Code example for the Bootstrap method
  • -
  • Plotting the Histogram
  • -
  • The bias-variance tradeoff
  • -
  • A way to Read the Bias-Variance Tradeoff
  • -
  • Example code for Bias-Variance tradeoff
  • -
  • Understanding what happens
  • -
  • Summing up
  • -
  • Another Example from Scikit-Learn's Repository
  • -
  • Various steps in cross-validation
  • -
  • How to set up the cross-validation for Ridge and/or Lasso
  • -
  • Cross-validation in brief
  • -
  • Code Example for Cross-validation and \( k \)-fold Cross-validation
  • -
  • More examples on bootstrap and cross-validation and errors
  • -
  • The same example but now with cross-validation
  • -
  • Cross-validation with Ridge
  • +
  • Standard Approach based on the Normal Distribution
  • +
  • Resampling methods: Bootstrap background
  • +
  • Resampling methods: More Bootstrap background
  • +
  • Resampling methods: Bootstrap approach
  • +
  • Resampling methods: Bootstrap steps
  • +
  • Code example for the Bootstrap method
  • +
  • Plotting the Histogram
  • +
  • The bias-variance tradeoff
  • +
  • A way to Read the Bias-Variance Tradeoff
  • +
  • Example code for Bias-Variance tradeoff
  • +
  • Understanding what happens
  • +
  • Summing up
  • +
  • Another Example from Scikit-Learn's Repository
  • +
  • Various steps in cross-validation
  • +
  • How to set up the cross-validation for Ridge and/or Lasso
  • +
  • Cross-validation in brief
  • +
  • Code Example for Cross-validation and \( k \)-fold Cross-validation
  • +
  • More examples on bootstrap and cross-validation and errors
  • +
  • The same example but now with cross-validation
  • +
  • Cross-validation with Ridge
  • @@ -278,59 +283,27 @@ MathJax.Hub.Config({ -

    Code example for the Bootstrap method

    +

    Resampling methods: Bootstrap steps

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

    +

      +
    1. Draw with replacement \( n \) numbers for the observed variables \( \boldsymbol{x} = (x_1,x_2,\cdots,x_n) \).
    2. +
    3. Define a vector \( \boldsymbol{x}^* \) containing the values which were drawn from \( \boldsymbol{x} \).
    4. +
    5. Using the vector \( \boldsymbol{x}^* \) compute \( \widehat{\beta}^* \) by evaluating \( \widehat \beta \) under the observations \( \boldsymbol{x}^* \).
    6. +
    7. Repeat this process \( k \) times.
    8. +
    - -
    from numpy import *
    -from numpy.random import randint, randn
    -from time import time
    -import matplotlib.mlab as mlab
    -import matplotlib.pyplot as plt
    -
    -# Returns mean of bootstrap samples                                                                              # Alternatively, we can run it using Scikit-Learn's function resample                                            # See the examples below
    -
    -def statistics(data):
    -    return mean(data)
    -
    -
    -# Bootstrap algorithm
    -def bootstrap(data, statistic, R):
    -    t = zeros(R); n = len(data); inds = arange(n); t0 = time()
    -    # non-parametric bootstrap         
    -    for i in range(R):
    -        t[i] = statistic(data[randint(0,n,n)])
    -
    -    # analysis    
    -    print("Runtime: %g sec" % (time()-t0)); print("Bootstrap Statistics :")
    -    print("original           bias      std. error")
    -    print("%8g %8g %14g %15g" % (statistic(data), std(data),mean(t),std(t)))
    -    return t
    -
    -
    -mu, sigma = 100, 15
    -datapoints = 10000
    -x = mu + sigma*random.randn(datapoints)
    -# bootstrap returns the data sample                                    
    -t = bootstrap(x, statistics, datapoints)
    -
    -

    -We see that our new variance and from that the standard deviation, agrees with the central limit theorem. +When you are done, you can draw a histogram of the relative frequency +of \( \widehat \beta^* \). This is your estimate of the probability +distribution \( p(t) \). Using this probability distribution you can +estimate any statistics thereof. In principle you never draw the +histogram of the relative frequency of \( \widehat{\beta}^* \). Instead +you use the estimators corresponding to the statistic of interest. For +example, if you are interested in estimating the variance of \( \widehat +\beta \), apply the etsimator \( \widehat \sigma^2 \) to the values +\( \widehat \beta^* \).

    @@ -358,7 +331,7 @@ We see that our new variance and from that the standard deviation, agrees with t

  • 43
  • 44
  • ...
  • -
  • 49
  • +
  • 50
  • »
  • diff --git a/doc/pub/week37/html/._week37-bs035.html b/doc/pub/week37/html/._week37-bs035.html index e2fb6f7a4..e462a453f 100644 --- a/doc/pub/week37/html/._week37-bs035.html +++ b/doc/pub/week37/html/._week37-bs035.html @@ -107,6 +107,10 @@ Automatically generated HTML file from DocOnce source ('Identifying Terms', 2, None, 'identifying-terms'), ('Wrapping it up', 2, None, 'wrapping-it-up'), ('Confidence Intervals', 2, None, 'confidence-intervals'), + ('Standard Approach based on the Normal Distribution', + 2, + None, + 'standard-approach-based-on-the-normal-distribution'), ('Resampling methods: Bootstrap background', 2, None, @@ -244,25 +248,26 @@ MathJax.Hub.Config({
  • Identifying Terms
  • Wrapping it up
  • Confidence Intervals
  • -
  • Resampling methods: Bootstrap background
  • -
  • Resampling methods: More Bootstrap background
  • -
  • Resampling methods: Bootstrap approach
  • -
  • Resampling methods: Bootstrap steps
  • -
  • Code example for the Bootstrap method
  • -
  • Plotting the Histogram
  • -
  • The bias-variance tradeoff
  • -
  • A way to Read the Bias-Variance Tradeoff
  • -
  • Example code for Bias-Variance tradeoff
  • -
  • Understanding what happens
  • -
  • Summing up
  • -
  • Another Example from Scikit-Learn's Repository
  • -
  • Various steps in cross-validation
  • -
  • How to set up the cross-validation for Ridge and/or Lasso
  • -
  • Cross-validation in brief
  • -
  • Code Example for Cross-validation and \( k \)-fold Cross-validation
  • -
  • More examples on bootstrap and cross-validation and errors
  • -
  • The same example but now with cross-validation
  • -
  • Cross-validation with Ridge
  • +
  • Standard Approach based on the Normal Distribution
  • +
  • Resampling methods: Bootstrap background
  • +
  • Resampling methods: More Bootstrap background
  • +
  • Resampling methods: Bootstrap approach
  • +
  • Resampling methods: Bootstrap steps
  • +
  • Code example for the Bootstrap method
  • +
  • Plotting the Histogram
  • +
  • The bias-variance tradeoff
  • +
  • A way to Read the Bias-Variance Tradeoff
  • +
  • Example code for Bias-Variance tradeoff
  • +
  • Understanding what happens
  • +
  • Summing up
  • +
  • Another Example from Scikit-Learn's Repository
  • +
  • Various steps in cross-validation
  • +
  • How to set up the cross-validation for Ridge and/or Lasso
  • +
  • Cross-validation in brief
  • +
  • Code Example for Cross-validation and \( k \)-fold Cross-validation
  • +
  • More examples on bootstrap and cross-validation and errors
  • +
  • The same example but now with cross-validation
  • +
  • Cross-validation with Ridge
  • @@ -278,23 +283,60 @@ MathJax.Hub.Config({ -

    Plotting the Histogram

    +

    Code example for the Bootstrap method

    + +

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

    -

    # the histogram of the bootstrapped  data                                                                                                    
    -n, binsboot, patches = plt.hist(t, 50, normed=1, facecolor='red', alpha=0.75)
    +
    from numpy import *
    +from numpy.random import randint, randn
    +from time import time
    +import matplotlib.mlab as mlab
    +import matplotlib.pyplot as plt
     
    -# add a 'best fit' line  
    -y = mlab.normpdf( binsboot, mean(t), std(t))
    -lt = plt.plot(binsboot, y, 'r--', linewidth=1)
    -plt.xlabel('Smarts')
    -plt.ylabel('Probability')
    -plt.axis([99.5, 100.6, 0, 3.0])
    -plt.grid(True)
    +# Returns mean of bootstrap samples                                                                              # Alternatively, we can run it using Scikit-Learn's function resample                                            # See the examples below
     
    -plt.show()
    +def statistics(data):
    +    return mean(data)
    +
    +
    +# Bootstrap algorithm
    +def bootstrap(data, statistic, R):
    +    t = zeros(R); n = len(data); inds = arange(n); t0 = time()
    +    # non-parametric bootstrap         
    +    for i in range(R):
    +        t[i] = statistic(data[randint(0,n,n)])
    +
    +    # analysis    
    +    print("Runtime: %g sec" % (time()-t0)); print("Bootstrap Statistics :")
    +    print("original           bias      std. error")
    +    print("%8g %8g %14g %15g" % (statistic(data), std(data),mean(t),std(t)))
    +    return t
    +
    +
    +mu, sigma = 100, 15
    +datapoints = 10000
    +x = mu + sigma*random.randn(datapoints)
    +# bootstrap returns the data sample                                    
    +t = bootstrap(x, statistics, datapoints)
     
    +

    +We see that our new variance and from that the standard deviation, agrees with the central limit theorem. +

    @@ -321,7 +363,7 @@ plt.show()

  • 44
  • 45
  • ...
  • -
  • 49
  • +
  • 50
  • »
  • diff --git a/doc/pub/week37/html/._week37-bs036.html b/doc/pub/week37/html/._week37-bs036.html index 89fcaeb1c..dc3ca707e 100644 --- a/doc/pub/week37/html/._week37-bs036.html +++ b/doc/pub/week37/html/._week37-bs036.html @@ -107,6 +107,10 @@ Automatically generated HTML file from DocOnce source ('Identifying Terms', 2, None, 'identifying-terms'), ('Wrapping it up', 2, None, 'wrapping-it-up'), ('Confidence Intervals', 2, None, 'confidence-intervals'), + ('Standard Approach based on the Normal Distribution', + 2, + None, + 'standard-approach-based-on-the-normal-distribution'), ('Resampling methods: Bootstrap background', 2, None, @@ -244,25 +248,26 @@ MathJax.Hub.Config({
  • Identifying Terms
  • Wrapping it up
  • Confidence Intervals
  • -
  • Resampling methods: Bootstrap background
  • -
  • Resampling methods: More Bootstrap background
  • -
  • Resampling methods: Bootstrap approach
  • -
  • Resampling methods: Bootstrap steps
  • -
  • Code example for the Bootstrap method
  • -
  • Plotting the Histogram
  • -
  • The bias-variance tradeoff
  • -
  • A way to Read the Bias-Variance Tradeoff
  • -
  • Example code for Bias-Variance tradeoff
  • -
  • Understanding what happens
  • -
  • Summing up
  • -
  • Another Example from Scikit-Learn's Repository
  • -
  • Various steps in cross-validation
  • -
  • How to set up the cross-validation for Ridge and/or Lasso
  • -
  • Cross-validation in brief
  • -
  • Code Example for Cross-validation and \( k \)-fold Cross-validation
  • -
  • More examples on bootstrap and cross-validation and errors
  • -
  • The same example but now with cross-validation
  • -
  • Cross-validation with Ridge
  • +
  • Standard Approach based on the Normal Distribution
  • +
  • Resampling methods: Bootstrap background
  • +
  • Resampling methods: More Bootstrap background
  • +
  • Resampling methods: Bootstrap approach
  • +
  • Resampling methods: Bootstrap steps
  • +
  • Code example for the Bootstrap method
  • +
  • Plotting the Histogram
  • +
  • The bias-variance tradeoff
  • +
  • A way to Read the Bias-Variance Tradeoff
  • +
  • Example code for Bias-Variance tradeoff
  • +
  • Understanding what happens
  • +
  • Summing up
  • +
  • Another Example from Scikit-Learn's Repository
  • +
  • Various steps in cross-validation
  • +
  • How to set up the cross-validation for Ridge and/or Lasso
  • +
  • Cross-validation in brief
  • +
  • Code Example for Cross-validation and \( k \)-fold Cross-validation
  • +
  • More examples on bootstrap and cross-validation and errors
  • +
  • The same example but now with cross-validation
  • +
  • Cross-validation with Ridge
  • @@ -278,69 +283,23 @@ MathJax.Hub.Config({ -

    The bias-variance tradeoff

    - +

    Plotting the Histogram

    -We will discuss the bias-variance tradeoff in the context of -continuous predictions such as regression. However, many of the -intuitions and ideas discussed here also carry over to classification -tasks. Consider a dataset \( \mathcal{L} \) consisting of the data -\( \mathbf{X}_\mathcal{L}=\{(y_j, \boldsymbol{x}_j), j=0\ldots n-1\} \). -

    -Let us assume that the true data is generated from a noisy model + +

    # the histogram of the bootstrapped  data                                                                                                    
    +n, binsboot, patches = plt.hist(t, 50, normed=1, facecolor='red', alpha=0.75)
     
    -$$
    -\boldsymbol{y}=f(\boldsymbol{x}) + \boldsymbol{\epsilon}
    -$$
    -
    -

    -where \( \epsilon \) is normally distributed with mean zero and standard deviation \( \sigma^2 \). - -

    -In our derivation of the ordinary least squares method we defined then -an approximation to the function \( f \) in terms of the parameters -\( \boldsymbol{\beta} \) and the design matrix \( \boldsymbol{X} \) which embody our model, -that is \( \boldsymbol{\tilde{y}}=\boldsymbol{X}\boldsymbol{\beta} \). - -

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

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

    -The three terms represent the square of the bias of the learning -method, which can be thought of as the error caused by the simplifying -assumptions built into the method. The second term represents the -variance of the chosen model and finally the last terms is variance of -the error \( \boldsymbol{\epsilon} \). - -

    -To derive this equation, we need to recall that the variance of \( \boldsymbol{y} \) and \( \boldsymbol{\epsilon} \) are both equal to \( \sigma^2 \). The mean value of \( \boldsymbol{\epsilon} \) is by definition equal to zero. Furthermore, the function \( f \) is not a stochastics variable, idem for \( \boldsymbol{\tilde{y}} \). -We use a more compact notation in terms of the expectation value -$$ -\mathbb{E}\left[(\boldsymbol{y}-\boldsymbol{\tilde{y}})^2\right]=\mathbb{E}\left[(\boldsymbol{f}+\boldsymbol{\epsilon}-\boldsymbol{\tilde{y}})^2\right], -$$ - -and adding and subtracting \( \mathbb{E}\left[\boldsymbol{\tilde{y}}\right] \) we get -$$ -\mathbb{E}\left[(\boldsymbol{y}-\boldsymbol{\tilde{y}})^2\right]=\mathbb{E}\left[(\boldsymbol{f}+\boldsymbol{\epsilon}-\boldsymbol{\tilde{y}}+\mathbb{E}\left[\boldsymbol{\tilde{y}}\right]-\mathbb{E}\left[\boldsymbol{\tilde{y}}\right])^2\right], -$$ - -which, using the abovementioned expectation values can be rewritten as -$$ -\mathbb{E}\left[(\boldsymbol{y}-\boldsymbol{\tilde{y}})^2\right]=\mathbb{E}\left[(\boldsymbol{y}-\mathbb{E}\left[\boldsymbol{\tilde{y}}\right])^2\right]+\mathrm{Var}\left[\boldsymbol{\tilde{y}}\right]+\sigma^2, -$$ - -that is the rewriting in terms of the so-called bias, the variance of the model \( \boldsymbol{\tilde{y}} \) and the variance of \( \boldsymbol{\epsilon} \). +# add a 'best fit' line +y = mlab.normpdf( binsboot, mean(t), std(t)) +lt = plt.plot(binsboot, y, 'r--', linewidth=1) +plt.xlabel('Smarts') +plt.ylabel('Probability') +plt.axis([99.5, 100.6, 0, 3.0]) +plt.grid(True) +plt.show() +

    @@ -367,7 +326,7 @@ that is the rewriting in terms of the so-called bias, the variance of the model

  • 45
  • 46
  • ...
  • -
  • 49
  • +
  • 50
  • »
  • diff --git a/doc/pub/week37/html/._week37-bs037.html b/doc/pub/week37/html/._week37-bs037.html index 312464bb6..39584b03e 100644 --- a/doc/pub/week37/html/._week37-bs037.html +++ b/doc/pub/week37/html/._week37-bs037.html @@ -107,6 +107,10 @@ Automatically generated HTML file from DocOnce source ('Identifying Terms', 2, None, 'identifying-terms'), ('Wrapping it up', 2, None, 'wrapping-it-up'), ('Confidence Intervals', 2, None, 'confidence-intervals'), + ('Standard Approach based on the Normal Distribution', + 2, + None, + 'standard-approach-based-on-the-normal-distribution'), ('Resampling methods: Bootstrap background', 2, None, @@ -244,25 +248,26 @@ MathJax.Hub.Config({
  • Identifying Terms
  • Wrapping it up
  • Confidence Intervals
  • -
  • Resampling methods: Bootstrap background
  • -
  • Resampling methods: More Bootstrap background
  • -
  • Resampling methods: Bootstrap approach
  • -
  • Resampling methods: Bootstrap steps
  • -
  • Code example for the Bootstrap method
  • -
  • Plotting the Histogram
  • -
  • The bias-variance tradeoff
  • -
  • A way to Read the Bias-Variance Tradeoff
  • -
  • Example code for Bias-Variance tradeoff
  • -
  • Understanding what happens
  • -
  • Summing up
  • -
  • Another Example from Scikit-Learn's Repository
  • -
  • Various steps in cross-validation
  • -
  • How to set up the cross-validation for Ridge and/or Lasso
  • -
  • Cross-validation in brief
  • -
  • Code Example for Cross-validation and \( k \)-fold Cross-validation
  • -
  • More examples on bootstrap and cross-validation and errors
  • -
  • The same example but now with cross-validation
  • -
  • Cross-validation with Ridge
  • +
  • Standard Approach based on the Normal Distribution
  • +
  • Resampling methods: Bootstrap background
  • +
  • Resampling methods: More Bootstrap background
  • +
  • Resampling methods: Bootstrap approach
  • +
  • Resampling methods: Bootstrap steps
  • +
  • Code example for the Bootstrap method
  • +
  • Plotting the Histogram
  • +
  • The bias-variance tradeoff
  • +
  • A way to Read the Bias-Variance Tradeoff
  • +
  • Example code for Bias-Variance tradeoff
  • +
  • Understanding what happens
  • +
  • Summing up
  • +
  • Another Example from Scikit-Learn's Repository
  • +
  • Various steps in cross-validation
  • +
  • How to set up the cross-validation for Ridge and/or Lasso
  • +
  • Cross-validation in brief
  • +
  • Code Example for Cross-validation and \( k \)-fold Cross-validation
  • +
  • More examples on bootstrap and cross-validation and errors
  • +
  • The same example but now with cross-validation
  • +
  • Cross-validation with Ridge
  • @@ -278,10 +283,68 @@ MathJax.Hub.Config({ -

    A way to Read the Bias-Variance Tradeoff

    +

    The bias-variance tradeoff

    -



    +We will discuss the bias-variance tradeoff in the context of +continuous predictions such as regression. However, many of the +intuitions and ideas discussed here also carry over to classification +tasks. Consider a dataset \( \mathcal{L} \) consisting of the data +\( \mathbf{X}_\mathcal{L}=\{(y_j, \boldsymbol{x}_j), j=0\ldots n-1\} \). + +

    +Let us assume that the true data is generated from a noisy model + +$$ +\boldsymbol{y}=f(\boldsymbol{x}) + \boldsymbol{\epsilon} +$$ + +

    +where \( \epsilon \) is normally distributed with mean zero and standard deviation \( \sigma^2 \). + +

    +In our derivation of the ordinary least squares method we defined then +an approximation to the function \( f \) in terms of the parameters +\( \boldsymbol{\beta} \) and the design matrix \( \boldsymbol{X} \) which embody our model, +that is \( \boldsymbol{\tilde{y}}=\boldsymbol{X}\boldsymbol{\beta} \). + +

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

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

    +The three terms represent the square of the bias of the learning +method, which can be thought of as the error caused by the simplifying +assumptions built into the method. The second term represents the +variance of the chosen model and finally the last terms is variance of +the error \( \boldsymbol{\epsilon} \). + +

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

    @@ -309,7 +372,7 @@ MathJax.Hub.Config({

  • 46
  • 47
  • ...
  • -
  • 49
  • +
  • 50
  • »
  • diff --git a/doc/pub/week37/html/._week37-bs038.html b/doc/pub/week37/html/._week37-bs038.html index c7a6fa753..a87e4533e 100644 --- a/doc/pub/week37/html/._week37-bs038.html +++ b/doc/pub/week37/html/._week37-bs038.html @@ -107,6 +107,10 @@ Automatically generated HTML file from DocOnce source ('Identifying Terms', 2, None, 'identifying-terms'), ('Wrapping it up', 2, None, 'wrapping-it-up'), ('Confidence Intervals', 2, None, 'confidence-intervals'), + ('Standard Approach based on the Normal Distribution', + 2, + None, + 'standard-approach-based-on-the-normal-distribution'), ('Resampling methods: Bootstrap background', 2, None, @@ -244,25 +248,26 @@ MathJax.Hub.Config({
  • Identifying Terms
  • Wrapping it up
  • Confidence Intervals
  • -
  • Resampling methods: Bootstrap background
  • -
  • Resampling methods: More Bootstrap background
  • -
  • Resampling methods: Bootstrap approach
  • -
  • Resampling methods: Bootstrap steps
  • -
  • Code example for the Bootstrap method
  • -
  • Plotting the Histogram
  • -
  • The bias-variance tradeoff
  • -
  • A way to Read the Bias-Variance Tradeoff
  • -
  • Example code for Bias-Variance tradeoff
  • -
  • Understanding what happens
  • -
  • Summing up
  • -
  • Another Example from Scikit-Learn's Repository
  • -
  • Various steps in cross-validation
  • -
  • How to set up the cross-validation for Ridge and/or Lasso
  • -
  • Cross-validation in brief
  • -
  • Code Example for Cross-validation and \( k \)-fold Cross-validation
  • -
  • More examples on bootstrap and cross-validation and errors
  • -
  • The same example but now with cross-validation
  • -
  • Cross-validation with Ridge
  • +
  • Standard Approach based on the Normal Distribution
  • +
  • Resampling methods: Bootstrap background
  • +
  • Resampling methods: More Bootstrap background
  • +
  • Resampling methods: Bootstrap approach
  • +
  • Resampling methods: Bootstrap steps
  • +
  • Code example for the Bootstrap method
  • +
  • Plotting the Histogram
  • +
  • The bias-variance tradeoff
  • +
  • A way to Read the Bias-Variance Tradeoff
  • +
  • Example code for Bias-Variance tradeoff
  • +
  • Understanding what happens
  • +
  • Summing up
  • +
  • Another Example from Scikit-Learn's Repository
  • +
  • Various steps in cross-validation
  • +
  • How to set up the cross-validation for Ridge and/or Lasso
  • +
  • Cross-validation in brief
  • +
  • Code Example for Cross-validation and \( k \)-fold Cross-validation
  • +
  • More examples on bootstrap and cross-validation and errors
  • +
  • The same example but now with cross-validation
  • +
  • Cross-validation with Ridge
  • @@ -278,65 +283,11 @@ MathJax.Hub.Config({ -

    Example code for Bias-Variance tradeoff

    +

    A way to Read the Bias-Variance Tradeoff

    +

    +



    - -
    import matplotlib.pyplot as plt
    -import numpy as np
    -from sklearn.linear_model import LinearRegression, Ridge, Lasso
    -from sklearn.preprocessing import PolynomialFeatures
    -from sklearn.model_selection import train_test_split
    -from sklearn.pipeline import make_pipeline
    -from sklearn.utils import resample
    -
    -np.random.seed(2018)
    -
    -n = 500
    -n_boostraps = 100
    -degree = 18  # A quite high value, just to show.
    -noise = 0.1
    -
    -# Make data set.
    -x = np.linspace(-1, 3, n).reshape(-1, 1)
    -y = np.exp(-x**2) + 1.5 * np.exp(-(x-2)**2) + np.random.normal(0, 0.1, x.shape)
    -
    -# Hold out some test data that is never used in training.
    -x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.2)
    -
    -# Combine x transformation and model into one operation.
    -# Not neccesary, but convenient.
    -model = make_pipeline(PolynomialFeatures(degree=degree), LinearRegression(fit_intercept=False))
    -
    -# The following (m x n_bootstraps) matrix holds the column vectors y_pred
    -# for each bootstrap iteration.
    -y_pred = np.empty((y_test.shape[0], n_boostraps))
    -for i in range(n_boostraps):
    -    x_, y_ = resample(x_train, y_train)
    -
    -    # Evaluate the new model on the same test data each time.
    -    y_pred[:, i] = model.fit(x_, y_).predict(x_test).ravel()
    -
    -# Note: Expectations and variances taken w.r.t. different training
    -# data sets, hence the axis=1. Subsequent means are taken across the test data
    -# set in order to obtain a total value, but before this we have error/bias/variance
    -# calculated per data point in the test set.
    -# Note 2: The use of keepdims=True is important in the calculation of bias as this 
    -# maintains the column vector form. Dropping this yields very unexpected results.
    -error = np.mean( np.mean((y_test - y_pred)**2, axis=1, keepdims=True) )
    -bias = np.mean( (y_test - np.mean(y_pred, axis=1, keepdims=True))**2 )
    -variance = np.mean( np.var(y_pred, axis=1, keepdims=True) )
    -print('Error:', error)
    -print('Bias^2:', bias)
    -print('Var:', variance)
    -print('{} >= {} + {} = {}'.format(error, bias, variance, bias+variance))
    -
    -plt.plot(x[::5, :], y[::5, :], label='f(x)')
    -plt.scatter(x_test, y_test, label='Data points')
    -plt.scatter(x_test, np.mean(y_pred, axis=1), label='Pred')
    -plt.legend()
    -plt.show()
    -

    @@ -363,7 +314,7 @@ plt.show()

  • 47
  • 48
  • ...
  • -
  • 49
  • +
  • 50
  • »
  • diff --git a/doc/pub/week37/html/._week37-bs039.html b/doc/pub/week37/html/._week37-bs039.html index eec737109..782349de7 100644 --- a/doc/pub/week37/html/._week37-bs039.html +++ b/doc/pub/week37/html/._week37-bs039.html @@ -107,6 +107,10 @@ Automatically generated HTML file from DocOnce source ('Identifying Terms', 2, None, 'identifying-terms'), ('Wrapping it up', 2, None, 'wrapping-it-up'), ('Confidence Intervals', 2, None, 'confidence-intervals'), + ('Standard Approach based on the Normal Distribution', + 2, + None, + 'standard-approach-based-on-the-normal-distribution'), ('Resampling methods: Bootstrap background', 2, None, @@ -244,25 +248,26 @@ MathJax.Hub.Config({
  • Identifying Terms
  • Wrapping it up
  • Confidence Intervals
  • -
  • Resampling methods: Bootstrap background
  • -
  • Resampling methods: More Bootstrap background
  • -
  • Resampling methods: Bootstrap approach
  • -
  • Resampling methods: Bootstrap steps
  • -
  • Code example for the Bootstrap method
  • -
  • Plotting the Histogram
  • -
  • The bias-variance tradeoff
  • -
  • A way to Read the Bias-Variance Tradeoff
  • -
  • Example code for Bias-Variance tradeoff
  • -
  • Understanding what happens
  • -
  • Summing up
  • -
  • Another Example from Scikit-Learn's Repository
  • -
  • Various steps in cross-validation
  • -
  • How to set up the cross-validation for Ridge and/or Lasso
  • -
  • Cross-validation in brief
  • -
  • Code Example for Cross-validation and \( k \)-fold Cross-validation
  • -
  • More examples on bootstrap and cross-validation and errors
  • -
  • The same example but now with cross-validation
  • -
  • Cross-validation with Ridge
  • +
  • Standard Approach based on the Normal Distribution
  • +
  • Resampling methods: Bootstrap background
  • +
  • Resampling methods: More Bootstrap background
  • +
  • Resampling methods: Bootstrap approach
  • +
  • Resampling methods: Bootstrap steps
  • +
  • Code example for the Bootstrap method
  • +
  • Plotting the Histogram
  • +
  • The bias-variance tradeoff
  • +
  • A way to Read the Bias-Variance Tradeoff
  • +
  • Example code for Bias-Variance tradeoff
  • +
  • Understanding what happens
  • +
  • Summing up
  • +
  • Another Example from Scikit-Learn's Repository
  • +
  • Various steps in cross-validation
  • +
  • How to set up the cross-validation for Ridge and/or Lasso
  • +
  • Cross-validation in brief
  • +
  • Code Example for Cross-validation and \( k \)-fold Cross-validation
  • +
  • More examples on bootstrap and cross-validation and errors
  • +
  • The same example but now with cross-validation
  • +
  • Cross-validation with Ridge
  • @@ -278,7 +283,7 @@ MathJax.Hub.Config({ -

    Understanding what happens

    +

    Example code for Bias-Variance tradeoff

    @@ -292,40 +297,48 @@ MathJax.Hub.Config({ np.random.seed(2018) -n = 40 +n = 500 n_boostraps = 100 -maxdegree = 14 - +degree = 18 # A quite high value, just to show. +noise = 0.1 # Make data set. -x = np.linspace(-3, 3, n).reshape(-1, 1) -y = np.exp(-x**2) + 1.5 * np.exp(-(x-2)**2)+ np.random.normal(0, 0.1, x.shape) -error = np.zeros(maxdegree) -bias = np.zeros(maxdegree) -variance = np.zeros(maxdegree) -polydegree = np.zeros(maxdegree) +x = np.linspace(-1, 3, n).reshape(-1, 1) +y = np.exp(-x**2) + 1.5 * np.exp(-(x-2)**2) + np.random.normal(0, 0.1, x.shape) + +# Hold out some test data that is never used in training. x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.2) -for degree in range(maxdegree): - model = make_pipeline(PolynomialFeatures(degree=degree), LinearRegression(fit_intercept=False)) - y_pred = np.empty((y_test.shape[0], n_boostraps)) - for i in range(n_boostraps): - x_, y_ = resample(x_train, y_train) - y_pred[:, i] = model.fit(x_, y_).predict(x_test).ravel() +# Combine x transformation and model into one operation. +# Not neccesary, but convenient. +model = make_pipeline(PolynomialFeatures(degree=degree), LinearRegression(fit_intercept=False)) - polydegree[degree] = degree - error[degree] = np.mean( np.mean((y_test - y_pred)**2, axis=1, keepdims=True) ) - bias[degree] = np.mean( (y_test - np.mean(y_pred, axis=1, keepdims=True))**2 ) - variance[degree] = np.mean( np.var(y_pred, axis=1, keepdims=True) ) - print('Polynomial degree:', degree) - print('Error:', error[degree]) - print('Bias^2:', bias[degree]) - print('Var:', variance[degree]) - print('{} >= {} + {} = {}'.format(error[degree], bias[degree], variance[degree], bias[degree]+variance[degree])) +# The following (m x n_bootstraps) matrix holds the column vectors y_pred +# for each bootstrap iteration. +y_pred = np.empty((y_test.shape[0], n_boostraps)) +for i in range(n_boostraps): + x_, y_ = resample(x_train, y_train) -plt.plot(polydegree, error, label='Error') -plt.plot(polydegree, bias, label='bias') -plt.plot(polydegree, variance, label='Variance') + # Evaluate the new model on the same test data each time. + y_pred[:, i] = model.fit(x_, y_).predict(x_test).ravel() + +# Note: Expectations and variances taken w.r.t. different training +# data sets, hence the axis=1. Subsequent means are taken across the test data +# set in order to obtain a total value, but before this we have error/bias/variance +# calculated per data point in the test set. +# Note 2: The use of keepdims=True is important in the calculation of bias as this +# maintains the column vector form. Dropping this yields very unexpected results. +error = np.mean( np.mean((y_test - y_pred)**2, axis=1, keepdims=True) ) +bias = np.mean( (y_test - np.mean(y_pred, axis=1, keepdims=True))**2 ) +variance = np.mean( np.var(y_pred, axis=1, keepdims=True) ) +print('Error:', error) +print('Bias^2:', bias) +print('Var:', variance) +print('{} >= {} + {} = {}'.format(error, bias, variance, bias+variance)) + +plt.plot(x[::5, :], y[::5, :], label='f(x)') +plt.scatter(x_test, y_test, label='Data points') +plt.scatter(x_test, np.mean(y_pred, axis=1), label='Pred') plt.legend() plt.show()

    @@ -354,6 +367,8 @@ plt.show()
  • 47
  • 48
  • 49
  • +
  • ...
  • +
  • 50
  • »
  • diff --git a/doc/pub/week37/html/week37-bs.html b/doc/pub/week37/html/week37-bs.html index 90c36c573..a875d46ec 100644 --- a/doc/pub/week37/html/week37-bs.html +++ b/doc/pub/week37/html/week37-bs.html @@ -107,6 +107,10 @@ Automatically generated HTML file from DocOnce source ('Identifying Terms', 2, None, 'identifying-terms'), ('Wrapping it up', 2, None, 'wrapping-it-up'), ('Confidence Intervals', 2, None, 'confidence-intervals'), + ('Standard Approach based on the Normal Distribution', + 2, + None, + 'standard-approach-based-on-the-normal-distribution'), ('Resampling methods: Bootstrap background', 2, None, @@ -244,25 +248,26 @@ MathJax.Hub.Config({
  • Identifying Terms
  • Wrapping it up
  • Confidence Intervals
  • -
  • Resampling methods: Bootstrap background
  • -
  • Resampling methods: More Bootstrap background
  • -
  • Resampling methods: Bootstrap approach
  • -
  • Resampling methods: Bootstrap steps
  • -
  • Code example for the Bootstrap method
  • -
  • Plotting the Histogram
  • -
  • The bias-variance tradeoff
  • -
  • A way to Read the Bias-Variance Tradeoff
  • -
  • Example code for Bias-Variance tradeoff
  • -
  • Understanding what happens
  • -
  • Summing up
  • -
  • Another Example from Scikit-Learn's Repository
  • -
  • Various steps in cross-validation
  • -
  • How to set up the cross-validation for Ridge and/or Lasso
  • -
  • Cross-validation in brief
  • -
  • Code Example for Cross-validation and \( k \)-fold Cross-validation
  • -
  • More examples on bootstrap and cross-validation and errors
  • -
  • The same example but now with cross-validation
  • -
  • Cross-validation with Ridge
  • +
  • Standard Approach based on the Normal Distribution
  • +
  • Resampling methods: Bootstrap background
  • +
  • Resampling methods: More Bootstrap background
  • +
  • Resampling methods: Bootstrap approach
  • +
  • Resampling methods: Bootstrap steps
  • +
  • Code example for the Bootstrap method
  • +
  • Plotting the Histogram
  • +
  • The bias-variance tradeoff
  • +
  • A way to Read the Bias-Variance Tradeoff
  • +
  • Example code for Bias-Variance tradeoff
  • +
  • Understanding what happens
  • +
  • Summing up
  • +
  • Another Example from Scikit-Learn's Repository
  • +
  • Various steps in cross-validation
  • +
  • How to set up the cross-validation for Ridge and/or Lasso
  • +
  • Cross-validation in brief
  • +
  • Code Example for Cross-validation and \( k \)-fold Cross-validation
  • +
  • More examples on bootstrap and cross-validation and errors
  • +
  • The same example but now with cross-validation
  • +
  • Cross-validation with Ridge
  • @@ -321,7 +326,7 @@ MathJax.Hub.Config({
  • 9
  • 10
  • ...
  • -
  • 49
  • +
  • 50
  • »
  • diff --git a/doc/pub/week37/html/week37-reveal.html b/doc/pub/week37/html/week37-reveal.html index 2f6b49944..01abf33b2 100644 --- a/doc/pub/week37/html/week37-reveal.html +++ b/doc/pub/week37/html/week37-reveal.html @@ -1058,6 +1058,55 @@ in particular if correlations are strong, may be too simplistic.

    Confidence Intervals

    + +

    +Confidence intervals are used in statistics is a type of estimate +computed from the observed data. This gives a range of values for an +unknown parameter such as the parameters \( \boldsymbol{\beta} \) from linear regression. + +

    +With the OLS expressions for the parameters \( \boldsymbol{\beta} \) we found +\( \mathbb{E}(\boldsymbol{\beta}) = \boldsymbol{\beta} \), which means that the estimator of the regression parameters is unbiased. + +

    +We found also that the variance of the estimate of the \( j \)-th regression coefficient is +\( \boldsymbol{\sigma}^2 (\boldsymbol{\beta}_j ) = \boldsymbol{\sigma}^2 [(\mathbf{X}^{T} \mathbf{X})^{-1}]_{jj} \). + +

    +This quantity will be used to +construct a confidence interval for the estimates. +

    + + +
    +

    Standard Approach based on the Normal Distribution

    + +

    +We will assume that the parameters \( \beta \) follow a normal +distribution. We can then define the confidence interval. Here we will be using as +shorthands \( \mu_{\beta} \) for the above mean value and \( \sigma_{\beta} \) +for the standard deviation. We have then a confidence interval + +

     
    +$$ +\left(\mu_{\beta}\pm \frac{z\sigma_{\beta}}{\sqrt{n}}\right), +$$ +

     
    + +

    +where \( z \) defines the level of certainty (or confidence). For a normal +distribution typical parameters are \( z=2.576 \) which corresponds to a +confidence of \( 99\% \) while \( z=1.96 \) corresponds to a confidence of +\( 95\% \). A confidence level of \( 95\% \) is commonly used and it is +normally referred to as a two-sigmas confidence level, that is we +approximate \( z\approx 2 \). + +

    +For more discussions of confidence intervals (and in particular linked with a discussion of the bootstrap method), see chapter 5 of the textbook by Davison on the Bootstrap Methods and their Applications + +

    +In this text you will also find an in-depth discussion of the +Bootstrap method, why it works and various theorems related to it.

    diff --git a/doc/pub/week37/html/week37-solarized.html b/doc/pub/week37/html/week37-solarized.html index ead40591c..30d039770 100644 --- a/doc/pub/week37/html/week37-solarized.html +++ b/doc/pub/week37/html/week37-solarized.html @@ -127,6 +127,10 @@ div { text-align: justify; text-justify: inter-word; } ('Identifying Terms', 2, None, 'identifying-terms'), ('Wrapping it up', 2, None, 'wrapping-it-up'), ('Confidence Intervals', 2, None, 'confidence-intervals'), + ('Standard Approach based on the Normal Distribution', + 2, + None, + 'standard-approach-based-on-the-normal-distribution'), ('Resampling methods: Bootstrap background', 2, None, @@ -1076,6 +1080,53 @@ in particular if correlations are strong, may be too simplistic.

    Confidence Intervals

    +

    +Confidence intervals are used in statistics is a type of estimate +computed from the observed data. This gives a range of values for an +unknown parameter such as the parameters \( \boldsymbol{\beta} \) from linear regression. + +

    +With the OLS expressions for the parameters \( \boldsymbol{\beta} \) we found +\( \mathbb{E}(\boldsymbol{\beta}) = \boldsymbol{\beta} \), which means that the estimator of the regression parameters is unbiased. + +

    +We found also that the variance of the estimate of the \( j \)-th regression coefficient is +\( \boldsymbol{\sigma}^2 (\boldsymbol{\beta}_j ) = \boldsymbol{\sigma}^2 [(\mathbf{X}^{T} \mathbf{X})^{-1}]_{jj} \). + +

    +This quantity will be used to +construct a confidence interval for the estimates. + +

    +









    + +

    Standard Approach based on the Normal Distribution

    + +

    +We will assume that the parameters \( \beta \) follow a normal +distribution. We can then define the confidence interval. Here we will be using as +shorthands \( \mu_{\beta} \) for the above mean value and \( \sigma_{\beta} \) +for the standard deviation. We have then a confidence interval + +$$ +\left(\mu_{\beta}\pm \frac{z\sigma_{\beta}}{\sqrt{n}}\right), +$$ + +

    +where \( z \) defines the level of certainty (or confidence). For a normal +distribution typical parameters are \( z=2.576 \) which corresponds to a +confidence of \( 99\% \) while \( z=1.96 \) corresponds to a confidence of +\( 95\% \). A confidence level of \( 95\% \) is commonly used and it is +normally referred to as a two-sigmas confidence level, that is we +approximate \( z\approx 2 \). + +

    +For more discussions of confidence intervals (and in particular linked with a discussion of the bootstrap method), see chapter 5 of the textbook by Davison on the Bootstrap Methods and their Applications + +

    +In this text you will also find an in-depth discussion of the +Bootstrap method, why it works and various theorems related to it. +











    diff --git a/doc/pub/week37/html/week37.html b/doc/pub/week37/html/week37.html index 059126495..d729b7279 100644 --- a/doc/pub/week37/html/week37.html +++ b/doc/pub/week37/html/week37.html @@ -132,6 +132,10 @@ div { text-align: justify; text-justify: inter-word; } ('Identifying Terms', 2, None, 'identifying-terms'), ('Wrapping it up', 2, None, 'wrapping-it-up'), ('Confidence Intervals', 2, None, 'confidence-intervals'), + ('Standard Approach based on the Normal Distribution', + 2, + None, + 'standard-approach-based-on-the-normal-distribution'), ('Resampling methods: Bootstrap background', 2, None, @@ -1081,6 +1085,53 @@ in particular if correlations are strong, may be too simplistic.

    Confidence Intervals

    +

    +Confidence intervals are used in statistics is a type of estimate +computed from the observed data. This gives a range of values for an +unknown parameter such as the parameters \( \boldsymbol{\beta} \) from linear regression. + +

    +With the OLS expressions for the parameters \( \boldsymbol{\beta} \) we found +\( \mathbb{E}(\boldsymbol{\beta}) = \boldsymbol{\beta} \), which means that the estimator of the regression parameters is unbiased. + +

    +We found also that the variance of the estimate of the \( j \)-th regression coefficient is +\( \boldsymbol{\sigma}^2 (\boldsymbol{\beta}_j ) = \boldsymbol{\sigma}^2 [(\mathbf{X}^{T} \mathbf{X})^{-1}]_{jj} \). + +

    +This quantity will be used to +construct a confidence interval for the estimates. + +

    +









    + +

    Standard Approach based on the Normal Distribution

    + +

    +We will assume that the parameters \( \beta \) follow a normal +distribution. We can then define the confidence interval. Here we will be using as +shorthands \( \mu_{\beta} \) for the above mean value and \( \sigma_{\beta} \) +for the standard deviation. We have then a confidence interval + +$$ +\left(\mu_{\beta}\pm \frac{z\sigma_{\beta}}{\sqrt{n}}\right), +$$ + +

    +where \( z \) defines the level of certainty (or confidence). For a normal +distribution typical parameters are \( z=2.576 \) which corresponds to a +confidence of \( 99\% \) while \( z=1.96 \) corresponds to a confidence of +\( 95\% \). A confidence level of \( 95\% \) is commonly used and it is +normally referred to as a two-sigmas confidence level, that is we +approximate \( z\approx 2 \). + +

    +For more discussions of confidence intervals (and in particular linked with a discussion of the bootstrap method), see chapter 5 of the textbook by Davison on the Bootstrap Methods and their Applications + +

    +In this text you will also find an in-depth discussion of the +Bootstrap method, why it works and various theorems related to it. +











    diff --git a/doc/pub/week37/ipynb/ipynb-week37-src.tar.gz b/doc/pub/week37/ipynb/ipynb-week37-src.tar.gz index 8893c7353..162a3d267 100644 Binary files a/doc/pub/week37/ipynb/ipynb-week37-src.tar.gz and b/doc/pub/week37/ipynb/ipynb-week37-src.tar.gz differ diff --git a/doc/pub/week37/ipynb/week37.ipynb b/doc/pub/week37/ipynb/week37.ipynb index 59ea57c5a..55f6f8646 100644 --- a/doc/pub/week37/ipynb/week37.ipynb +++ b/doc/pub/week37/ipynb/week37.ipynb @@ -1105,6 +1105,52 @@ "\n", "## Confidence Intervals\n", "\n", + "Confidence intervals are used in statistics is a type of estimate\n", + "computed from the observed data. This gives a range of values for an\n", + "unknown parameter such as the parameters $\\boldsymbol{\\beta}$ from linear regression.\n", + "\n", + "With the OLS expressions for the parameters $\\boldsymbol{\\beta}$ we found \n", + "$\\mathbb{E}(\\boldsymbol{\\beta}) = \\boldsymbol{\\beta}$, which means that the estimator of the regression parameters is unbiased.\n", + "\n", + "We found also that the variance of the estimate of the $j$-th regression coefficient is\n", + "$\\boldsymbol{\\sigma}^2 (\\boldsymbol{\\beta}_j ) = \\boldsymbol{\\sigma}^2 [(\\mathbf{X}^{T} \\mathbf{X})^{-1}]_{jj} $.\n", + "\n", + "This quantity will be used to\n", + "construct a confidence interval for the estimates.\n", + "\n", + "\n", + "## Standard Approach based on the Normal Distribution\n", + "\n", + "We will assume that the parameters $\\beta$ follow a normal\n", + "distribution. We can then define the confidence interval. Here we will be using as\n", + "shorthands $\\mu_{\\beta}$ for the above mean value and $\\sigma_{\\beta}$\n", + "for the standard deviation. We have then a confidence interval" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "$$\n", + "\\left(\\mu_{\\beta}\\pm \\frac{z\\sigma_{\\beta}}{\\sqrt{n}}\\right),\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "where $z$ defines the level of certainty (or confidence). For a normal\n", + "distribution typical parameters are $z=2.576$ which corresponds to a\n", + "confidence of $99\\%$ while $z=1.96$ corresponds to a confidence of\n", + "$95\\%$. A confidence level of $95\\%$ is commonly used and it is\n", + "normally referred to as a *two-sigmas* confidence level, that is we\n", + "approximate $z\\approx 2$.\n", + "\n", + "For more discussions of confidence intervals (and in particular linked with a discussion of the bootstrap method), see chapter 5 of the textbook by [Davison on the Bootstrap Methods and their Applications](https://www.cambridge.org/core/books/bootstrap-methods-and-their-application/ED2FD043579F27952363566DC09CBD6A)\n", + "\n", + "In this text you will also find an in-depth discussion of the\n", + "Bootstrap method, why it works and various theorems related to it. \n", "\n", "## Resampling methods: Bootstrap background\n", "\n", diff --git a/doc/src/week37/._week37-bs000.html b/doc/src/week37/._week37-bs000.html deleted file mode 100644 index 90c36c573..000000000 --- a/doc/src/week37/._week37-bs000.html +++ /dev/null @@ -1,349 +0,0 @@ - - - - - - - - -Week 37: Summary of Ridge and Lasso Regression and Resampling Methods - - - - - - - - - - - - - - - - - - - - - - - -

    - - -
    - -

     

     

     

    - - - - - - -
    -

    Week 37: Summary of Ridge and Lasso Regression and Resampling Methods

    - -

    - - -

    -Morten Hjorth-Jensen [1, 2] -
    - -

    - - -

    [1] Department of Physics, University of Oslo
    -
    [2] Department of Physics and Astronomy and National Superconducting Cyclotron Laboratory, Michigan State University
    -
    -

    -

    Sep 16, 2021

    -
    -

    - - -

    Read »

    - - -
    - -

    - -

    - - -
    - - - - - - - -
    - © 1999-2021, Morten Hjorth-Jensen. Released under CC Attribution-NonCommercial 4.0 license -
    - - - - - - diff --git a/doc/src/week37/._week37-bs001.html b/doc/src/week37/._week37-bs001.html deleted file mode 100644 index 525437987..000000000 --- a/doc/src/week37/._week37-bs001.html +++ /dev/null @@ -1,337 +0,0 @@ - - - - - - - - -Week 37: Summary of Ridge and Lasso Regression and Resampling Methods - - - - - - - - - - - - - - - - - - - - - - - - - - -
    - -

     

     

     

    - - - - -

    Plans for week 37

    - - - -Recommended Reading: - -
      -
    1. Lectures on Resampling methods (these lectures)
    2. -
    3. Bishop 1.3 (cross-validation) and 3.2 (bias-variance tradeoff)
    4. -
    5. Hastie et al Chapter 7, here we recommend 7.1-7.5 and 7.10 (cross-validation) and 7.11 (bootstrap). This chapter is better than Bishop's on these topics. Goodfellow et al discuss this in a superficial way in sections 5.2-5.5.
    6. -
    - -

    - -

    - - -
    - - - - - - - -
    - -
    - - - - - - diff --git a/doc/src/week37/._week37-bs002.html b/doc/src/week37/._week37-bs002.html deleted file mode 100644 index 75d4e4db3..000000000 --- a/doc/src/week37/._week37-bs002.html +++ /dev/null @@ -1,326 +0,0 @@ - - - - - - - - -Week 37: Summary of Ridge and Lasso Regression and Resampling Methods - - - - - - - - - - - - - - - - - - - - - - - - - - -
    - -

     

     

     

    - - - - -

    Thursday September 16, Summary of Ridge and Lasso Regression and start Resampling methods

    - -

    -

    - -

    - - -
    - - - - - - - -
    - -
    - - - - - - diff --git a/doc/src/week37/._week37-bs003.html b/doc/src/week37/._week37-bs003.html deleted file mode 100644 index b59aaa0c6..000000000 --- a/doc/src/week37/._week37-bs003.html +++ /dev/null @@ -1,346 +0,0 @@ - - - - - - - - -Week 37: Summary of Ridge and Lasso Regression and Resampling Methods - - - - - - - - - - - - - - - - - - - - - - - - - - -
    - -

     

     

     

    - - - - -

    Deriving OLS from a probability distribution

    - -

    -Our basic assumption when we derived the OLS equations was to assume -that our output is determined by a given continuous function -\( f(\boldsymbol{x}) \) and a random noise \( \boldsymbol{\epsilon} \) given by the normal -distribution with zero mean value and an undetermined variance -\( \sigma^2 \). - -

    -We found above that the outputs \( \boldsymbol{y} \) have a mean value given by -\( \boldsymbol{X}\hat{\boldsymbol{\beta}} \) and variance \( \sigma^2 \). Since the entries to -the design matrix are not stochastic variables, we can assume that the -probability distribution of our targets is also a normal distribution -but now with mean value \( \boldsymbol{X}\hat{\boldsymbol{\beta}} \). This means that a -single output \( y_i \) is given by the Gaussian distribution - -$$ -y_i\sim \mathcal{N}(\boldsymbol{X}_{i,*}\boldsymbol{\beta}, \sigma^2)=\frac{1}{\sqrt{2\pi\sigma^2}}\exp{\left[-\frac{(y_i-\boldsymbol{X}_{i,*}\boldsymbol{\beta})^2}{2\sigma^2}\right]}. -$$ - -

    -

    - -

    - - -
    - - - - - - - -
    - -
    - - - - - - diff --git a/doc/src/week37/._week37-bs004.html b/doc/src/week37/._week37-bs004.html deleted file mode 100644 index 3b09478a9..000000000 --- a/doc/src/week37/._week37-bs004.html +++ /dev/null @@ -1,360 +0,0 @@ - - - - - - - - -Week 37: Summary of Ridge and Lasso Regression and Resampling Methods - - - - - - - - - - - - - - - - - - - - - - - - - - -
    - -

     

     

     

    - - - - -

    Independent and Identically Distrubuted (iid)

    - -

    -We assume now that the various \( y_i \) values are stochastically distributed according to the above Gaussian distribution. -We define this distribution as -$$ -p(y_i, \boldsymbol{X}\vert\boldsymbol{\beta})=\frac{1}{\sqrt{2\pi\sigma^2}}\exp{\left[-\frac{(y_i-\boldsymbol{X}_{i,*}\boldsymbol{\beta})^2}{2\sigma^2}\right]}, -$$ - -which reads as finding the likelihood of an event \( y_i \) with the input variables \( \boldsymbol{X} \) given the parameters (to be determined) \( \boldsymbol{\beta} \). - -

    -Since these events are assumed to be independent and identicall distributed we can build the probability distribution function (PDF) for all possible event \( \boldsymbol{y} \) as the product of the single events, that is we have - -$$ -p(\boldsymbol{y},\boldsymbol{X}\vert\boldsymbol{\beta})=\prod_{i=0}^{n-1}\frac{1}{\sqrt{2\pi\sigma^2}}\exp{\left[-\frac{(y_i-\boldsymbol{X}_{i,*}\boldsymbol{\beta})^2}{2\sigma^2}\right]}=\prod_{i=0}^{n-1}p(y_i,\boldsymbol{X}\vert\boldsymbol{\beta}). -$$ - -

    -We will write this in a more compact form reserving \( \boldsymbol{D} \) for the domain of events, including the ouputs (targets) and the inputs. That is -in case we have a simple one-dimensional input and output case -$$ -\boldsymbol{D}=[(x_0,y_0), (x_1,y_1),\dots, (x_{n-1},y_{n-1})]. -$$ - -In the more general case the various inputs should be replaced by the possible features represented by the input data set \( \boldsymbol{X} \). -We can now rewrite the above probability as -$$ -p(\boldsymbol{D}\vert\boldsymbol{\beta})=\prod_{i=0}^{n-1}\frac{1}{\sqrt{2\pi\sigma^2}}\exp{\left[-\frac{(y_i-\boldsymbol{X}_{i,*}\boldsymbol{\beta})^2}{2\sigma^2}\right]}. -$$ - -

    -It is a conditional probability (see below) and reads as the likelihood of a domain of events \( \boldsymbol{D} \) given a set of parameters \( \boldsymbol{\beta} \). - -

    -

    - -

    - - -
    - - - - - - - -
    - -
    - - - - - - diff --git a/doc/src/week37/._week37-bs005.html b/doc/src/week37/._week37-bs005.html deleted file mode 100644 index eb68e88a7..000000000 --- a/doc/src/week37/._week37-bs005.html +++ /dev/null @@ -1,354 +0,0 @@ - - - - - - - - -Week 37: Summary of Ridge and Lasso Regression and Resampling Methods - - - - - - - - - - - - - - - - - - - - - - - - - - -
    - -

     

     

     

    - - - - -

    Maximum Likelihood Estimation (MLE)

    - -

    -In statistics, maximum likelihood estimation (MLE) is a method of -estimating the parameters of an assumed probability distribution, -given some observed data. This is achieved by maximizing a likelihood -function so that, under the assumed statistical model, the observed -data is the most probable. - -

    -We will assume here that our events are given by the above Gaussian -distribution and we will determine the optimal parameters \( \beta \) by -maximizing the above PDF. However, computing the derivatives of a -product function is cumbersome and can easily lead to overflow and/or -underflowproblems, with potentials for loss of numerical precision. - -

    -In practice, it is more convenient to maximize the logarithm of the -PDF because it is a monotonically increasing function of the argument. -Alternatively, and this will be our option, we will minimize the -negative of the logarithm since this is a monotonically decreasing -function. - -

    -Note also that maximization/minimization of the logarithm of the PDF -is equivalent to the maximization/minimization of the function itself. - -

    -

    - -

    - - -
    - - - - - - - -
    - -
    - - - - - - diff --git a/doc/src/week37/._week37-bs006.html b/doc/src/week37/._week37-bs006.html deleted file mode 100644 index 9a0bd0f18..000000000 --- a/doc/src/week37/._week37-bs006.html +++ /dev/null @@ -1,354 +0,0 @@ - - - - - - - - -Week 37: Summary of Ridge and Lasso Regression and Resampling Methods - - - - - - - - - - - - - - - - - - - - - - - - - - -
    - -

     

     

     

    - - - - -

    A new Cost Function

    - -

    -We could now define a new cost function to minimize, namely the negative logarithm of the above PDF - -$$ -C(\boldsymbol{\beta}=-\log{\prod_{i=0}^{n-1}p(y_i,\boldsymbol{X}\vert\boldsymbol{\beta})}=-\sum_{i=0}^{n-1}\log{p(y_i,\boldsymbol{X}\vert\boldsymbol{\beta})}, -$$ - -which becomes -$$ -C(\boldsymbol{\beta}=\frac{n}{2}\log{2\pi\sigma^2}+\frac{\vert\vert (\boldsymbol{y}-\boldsymbol{X}\boldsymbol{\beta})\vert\vert_2^2}{2\sigma^2}. -$$ - -

    -Taking the derivative of the new cost function with respect to the parameters \( \beta \) we recognize our familiar OLS equation, namely - -$$ -\boldsymbol{X}^T\left(\boldsymbol{y}-\boldsymbol{X}\boldsymbol{\beta}\right) =0, -$$ - -which leads to the well-known OLS equation for the optimal paramters \( \beta \) -$$ -\hat{\boldsymbol{\beta}}^{\mathrm{OLS}}=\left(\boldsymbol{X}^T\boldsymbol{X}\right)^{-1}\boldsymbol{X}^T\boldsymbol{y}! -$$ - -

    -

    - -

    - - -
    - - - - - - - -
    - -
    - - - - - - diff --git a/doc/src/week37/._week37-bs007.html b/doc/src/week37/._week37-bs007.html deleted file mode 100644 index 060ce84f0..000000000 --- a/doc/src/week37/._week37-bs007.html +++ /dev/null @@ -1,345 +0,0 @@ - - - - - - - - -Week 37: Summary of Ridge and Lasso Regression and Resampling Methods - - - - - - - - - - - - - - - - - - - - - - - - - - -
    - -

     

     

     

    - - - - -

    Bayes' Theorem

    - -

    -If we combine the conditional probability with the marginal probability and the standard product rule, we have -$$ -p(X\vert Y)= \frac{p(X,Y)}{p(Y)}, -$$ - -which we can rewrite as - -$$ -p(X\vert Y)= \frac{p(X,Y)}{\sum_{i=0}^{n-1}p(Y\vert X=x_i)p(x_i)}=\frac{p(Y\vert X)p(X)}{\sum_{i=0}^{n-1}p(Y\vert X=x_i)p(x_i)}, -$$ - -which is Bayes' theorem. It allows us to evaluate the uncertainty in in \( X \) after we have observed \( Y \). We can easily interchange \( X \) with \( Y \). - -

    -

    - -

    - - -
    - - - - - - - -
    - -
    - - - - - - diff --git a/doc/src/week37/._week37-bs008.html b/doc/src/week37/._week37-bs008.html deleted file mode 100644 index 782c02532..000000000 --- a/doc/src/week37/._week37-bs008.html +++ /dev/null @@ -1,341 +0,0 @@ - - - - - - - - -Week 37: Summary of Ridge and Lasso Regression and Resampling Methods - - - - - - - - - - - - - - - - - - - - - - - - - - -
    - -

     

     

     

    - - - - -

    Interpretations of Bayes' Theorem

    - -

    -The quantity \( p(Y\vert X) \) on the right-hand side of the theorem is -evaluated for the observed data \( Y \) and can be viewed as a function of -the parameter space represented by \( X \). This function is not -necesseraly normalized and is normally called the likelihood function. - -

    -The function \( p(X) \) on the right hand side is called the prior while the function on the left hand side is the called the posterior probability. The denominator on the right hand side serves as a normalization factor for the posterior distribution. - -

    -

    - -

    - - -
    - - - - - - - -
    - -
    - - - - - - diff --git a/doc/src/week37/._week37-bs009.html b/doc/src/week37/._week37-bs009.html deleted file mode 100644 index ddc95d872..000000000 --- a/doc/src/week37/._week37-bs009.html +++ /dev/null @@ -1,413 +0,0 @@ - - - - - - - - -Week 37: Summary of Ridge and Lasso Regression and Resampling Methods - - - - - - - - - - - - - - - - - - - - - - - - - - -
    - -

     

     

     

    - - - - -

    Test Function for what happens with OLS, Ridge and Lasso

    - -

    -We will play around with a study of the values for the optimal -parameters \( \boldsymbol{\beta} \) using OLS, Ridge and Lasso regression. For -OLS, you will notice as function of the noise and polynomial degree, -that the parameters \( \beta \) will fluctuate from order to order in the -polynomial fit and that for larger and larger polynomial degrees of freedom, the parameters will tend to increase in value for OLS. - -

    -For Ridge and Lasso regression, the higher order parameters will typically be reduced, providing thereby less fluctuations from one order to another one. - -

    - - -

    import numpy as np
    -import matplotlib.pyplot as plt
    -from sklearn.model_selection import train_test_split
    -from sklearn import linear_model
    -
    -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
    -
    -# Make data set.
    -n = 10000
    -x = np.random.rand(n)
    -y = np.exp(-x**2) + 1.5 * np.exp(-(x-2)**2)+ np.random.randn(n)
    -
    -Maxpolydegree = 5
    -X = np.zeros((len(x),Maxpolydegree))
    -X[:,0] = 1.0
    -
    -for polydegree in range(1, Maxpolydegree):
    -    for degree in range(polydegree):
    -        X[:,degree] = x**(degree)
    -
    -
    -# 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.pinv(X_train.T @ X_train) @ X_train.T @ y_train
    -print(OLSbeta)
    -ypredictOLS = X_test @ OLSbeta
    -print("Test MSE OLS")
    -print(MSE(y_test,ypredictOLS))
    -# Repeat now for Lasso and Ridge regression and various values of the regularization parameter using Scikit-Learn
    -# Decide which values of lambda to use
    -nlambdas = 4
    -MSERidgePredict = np.zeros(nlambdas)
    -MSELassoPredict = np.zeros(nlambdas)
    -lambdas = np.logspace(-3, 1, nlambdas)
    -for i in range(nlambdas):
    -    lmb = lambdas[i]
    -    # Make the fit using Ridge and Lasso
    -    RegRidge = linear_model.Ridge(lmb,fit_intercept=False)
    -    RegRidge.fit(X_train,y_train)
    -    RegLasso = linear_model.Lasso(lmb,fit_intercept=False)
    -    RegLasso.fit(X_train,y_train)
    -    # and then make the prediction
    -    ypredictRidge = RegRidge.predict(X_test)
    -    ypredictLasso = RegLasso.predict(X_test)
    -    # Compute the MSE and print it
    -    MSERidgePredict[i] = MSE(y_test,ypredictRidge)
    -    MSELassoPredict[i] = MSE(y_test,ypredictLasso)
    -    print(lmb,RegRidge.coef_)
    -    print(lmb,RegLasso.coef_)
    -# Now plot the results
    -plt.figure()
    -plt.plot(np.log10(lambdas), MSERidgePredict, 'b', label = 'MSE Ridge Test')
    -plt.plot(np.log10(lambdas), MSELassoPredict, 'r', label = 'MSE Lasso Test')
    -plt.xlabel('log10(lambda)')
    -plt.ylabel('MSE')
    -plt.legend()
    -plt.show()
    -
    -

    -How can we understand this? - -

    -

    - -

    - - -
    - - - - - - - -
    - -
    - - - - - - diff --git a/doc/src/week37/._week37-bs010.html b/doc/src/week37/._week37-bs010.html deleted file mode 100644 index 533203d1e..000000000 --- a/doc/src/week37/._week37-bs010.html +++ /dev/null @@ -1,398 +0,0 @@ - - - - - - - - -Week 37: Summary of Ridge and Lasso Regression and Resampling Methods - - - - - - - - - - - - - - - - - - - - - - - - - - -
    - -

     

     

     

    - - - - -

    Rerunning the above code

    - -

    -Let us write out the values of the coefficients \( \beta_i \) as functions -of the polynomial degree and noise. We will focus only on the Ridge -results and some few selected values of the hyperparameter \( \lambda \). - -

    -If we don't include any noise and run this code for different values -of the polynomial degree, we notice that the results for \( \beta_i \) do -not show great changes from one order to the next. This is an -indication that for higher polynomial orders, our parameters become -less important. - -

    -If we however add noise, what happens is that the polynomial fit is -trying to adjust the fit to traverse in the best possible way all data -points. This can lead to large fluctuations in the parameters -\( \beta_i \) as functions of polynomial order. It will also be reflected -in a larger value of the variance of each parameter \( \beta_i \). What -Ridge regression (and Lasso as well) are doing then is to try to -quench the fluctuations in the parameters of \( \beta_i \) which have a -large variance (normally for higher orders in the polynomial). - -

    - - -

    import numpy as np
    -import pandas as pd
    -from IPython.display import display
    -import matplotlib.pyplot as plt
    -from sklearn.model_selection import train_test_split
    -from sklearn import linear_model
    -
    -# Make data set.
    -n = 1000
    -x = np.random.rand(n)
    -y = np.exp(-x**2) + 1.5 * np.exp(-(x-2)**2)+ np.random.randn(n)
    -
    -Maxpolydegree = 5
    -X = np.zeros((len(x),Maxpolydegree))
    -X[:,0] = 1.0
    -
    -for polydegree in range(1, Maxpolydegree):
    -    for degree in range(polydegree):
    -        X[:,degree] = x**(degree)
    -
    -
    -# 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)
    -
    -# Decide which values of lambda to use
    -nlambdas = 5
    -lambdas = np.logspace(-3, 2, nlambdas)
    -for i in range(nlambdas):
    -    lmb = lambdas[i]
    -    # Make the fit using Ridge only
    -    RegRidge = linear_model.Ridge(lmb,fit_intercept=False)
    -    RegRidge.fit(X_train,y_train)
    -    # and then make the prediction
    -    ypredictRidge = RegRidge.predict(X_test)
    -    Coeffs = np.array(RegRidge.coef_)
    -    BetaValues = pd.DataFrame(Coeffs)
    -    BetaValues.columns = ['beta']
    -    display(BetaValues)    
    -
    -

    -

    - -

    - - -
    - - - - - - - -
    - -
    - - - - - - diff --git a/doc/src/week37/._week37-bs011.html b/doc/src/week37/._week37-bs011.html deleted file mode 100644 index 13b0683b2..000000000 --- a/doc/src/week37/._week37-bs011.html +++ /dev/null @@ -1,364 +0,0 @@ - - - - - - - - -Week 37: Summary of Ridge and Lasso Regression and Resampling Methods - - - - - - - - - - - - - - - - - - - - - - - - - - -
    - -

     

     

     

    - - - - -

    Invoking Bayes' theorem

    - -

    -Using Bayes' theorem we can gain a better intuition about Ridge and Lasso regression. - -

    -For ordinary least squares we postulated that the maximum likelihood for the doamin of events \( \boldsymbol{D} \) (one-dimensional case) -$$ -\boldsymbol{D}=[(x_0,y_0), (x_1,y_1),\dots, (x_{n-1},y_{n-1})], -$$ - -is given by -$$ -p(\boldsymbol{D}\vert\boldsymbol{\beta})=\prod_{i=0}^{n-1}\frac{1}{\sqrt{2\pi\sigma^2}}\exp{\left[-\frac{(y_i-\boldsymbol{X}_{i,*}\boldsymbol{\beta})^2}{2\sigma^2}\right]}. -$$ - -

    -In Bayes' theorem this function plays the role of the so-called likelihood. We could now ask the question what is the posterior probability of a parameter set \( \boldsymbol{\beta} \) given a domain of events \( \boldsymbol{D} \)? That is, how can we define the posterior probability - -$$ -p(\boldsymbol{\beta}\vert\boldsymbol{D}). -$$ - -

    -Bayes' theorem comes to our rescue here since (omitting the normalization constant) -$$ -p(\boldsymbol{\beta}\vert\boldsymbol{D})\propto p(\boldsymbol{D}\vert\boldsymbol{\beta})p(\boldsymbol{\beta}). -$$ - -

    -We have a model for \( p(\boldsymbol{D}\vert\boldsymbol{\beta}) \) but need one for the prior \( p(\boldsymbol{\beta} \)! - -

    -

    - -

    - - -
    - - - - - - - -
    - -
    - - - - - - diff --git a/doc/src/week37/._week37-bs012.html b/doc/src/week37/._week37-bs012.html deleted file mode 100644 index 012c8e223..000000000 --- a/doc/src/week37/._week37-bs012.html +++ /dev/null @@ -1,370 +0,0 @@ - - - - - - - - -Week 37: Summary of Ridge and Lasso Regression and Resampling Methods - - - - - - - - - - - - - - - - - - - - - - - - - - -
    - -

     

     

     

    - - - - -

    Ridge and Bayes

    - -

    -With the posterior probability defined by a likelihood which we have -already modeled and an unknown prior, we are now ready to make -additional models for the prior. - -

    -We can, based on our discussions of the variance of \( \boldsymbol{\beta} \) and the mean value, assume that the prior for the values \( \boldsymbol{\beta} \) is given by a Gaussian with mean value zero and variance \( \tau^2 \), that is - -$$ -p(\boldsymbol{\beta})=\prod_{j=0}^{p-1}\exp{\left(-\frac{\beta_j^2}{2\tau^2}\right)}. -$$ - -

    -Our posterior probability becomes then (omitting the normalization factor which is just a constant) -$$ -p(\boldsymbol{\beta\vert\boldsymbol{D})}=\prod_{i=0}^{n-1}\frac{1}{\sqrt{2\pi\sigma^2}}\exp{\left[-\frac{(y_i-\boldsymbol{X}_{i,*}\boldsymbol{\beta})^2}{2\sigma^2}\right]}\prod_{j=0}^{p-1}\exp{\left(-\frac{\beta_j^2}{2\tau^2}\right)}. -$$ - -

    -We can now optimize this quantity with respect to \( \boldsymbol{\beta} \). As we -did for OLS, this is most conveniently done by taking the negative -logarithm of the posterior probability. Doing so and leaving out the -constants terms that do not depend on \( \beta \), we have - -$$ -C(\boldsymbol{\beta})=\frac{\vert\vert (\boldsymbol{y}-\boldsymbol{X}\boldsymbol{\beta})\vert\vert_2^2}{2\sigma^2}+\frac{1}{2\tau^2}\vert\vert\boldsymbol{\beta}\vert\vert_2^2, -$$ - -and replacing \( 1/2\tau^2 \) with \( \lambda \) we have - -$$ -C(\boldsymbol{\beta})=\frac{\vert\vert (\boldsymbol{y}-\boldsymbol{X}\boldsymbol{\beta})\vert\vert_2^2}{2\sigma^2}+\lambda\vert\vert\boldsymbol{\beta}\vert\vert_2^2, -$$ - -which is our Ridge cost function! Nice, isn't it? - -

    -

    - -

    - - -
    - - - - - - - -
    - -
    - - - - - - diff --git a/doc/src/week37/._week37-bs013.html b/doc/src/week37/._week37-bs013.html deleted file mode 100644 index 92de2c566..000000000 --- a/doc/src/week37/._week37-bs013.html +++ /dev/null @@ -1,364 +0,0 @@ - - - - - - - - -Week 37: Summary of Ridge and Lasso Regression and Resampling Methods - - - - - - - - - - - - - - - - - - - - - - - - - - -
    - -

     

     

     

    - - - - -

    Lasso and Bayes

    - -

    -To derive the Lasso cost function, we simply replace the Gaussian prior with an exponential distribution (Laplace in this case) with zero mean value, that is - -$$ -p(\boldsymbol{\beta})=\prod_{j=0}^{p-1}\exp{\left(-\frac{\vert\beta_j\vert}{\tau}\right)}. -$$ - -

    -Our posterior probability becomes then (omitting the normalization factor which is just a constant) -$$ -p(\boldsymbol{\beta}\vert\boldsymbol{D})=\prod_{i=0}^{n-1}\frac{1}{\sqrt{2\pi\sigma^2}}\exp{\left[-\frac{(y_i-\boldsymbol{X}_{i,*}\boldsymbol{\beta})^2}{2\sigma^2}\right]}\prod_{j=0}^{p-1}\exp{\left(-\frac{\vert\beta_j\vert}{\tau}\right)}. -$$ - -

    -Taking the negative -logarithm of the posterior probability and leaving out the -constants terms that do not depend on \( \beta \), we have - -$$ -C(\boldsymbol{\beta}=\frac{\vert\vert (\boldsymbol{y}-\boldsymbol{X}\boldsymbol{\beta})\vert\vert_2^2}{2\sigma^2}+\frac{1}{\tau}\vert\vert\boldsymbol{\beta}\vert\vert_1, -$$ - -and replacing \( 1/\tau \) with \( \lambda \) we have - -$$ -C(\boldsymbol{\beta}=\frac{\vert\vert (\boldsymbol{y}-\boldsymbol{X}\boldsymbol{\beta})\vert\vert_2^2}{2\sigma^2}+\lambda\vert\vert\boldsymbol{\beta}\vert\vert_1, -$$ - -which is our Lasso cost function! - -

    -

    - -

    - - -
    - - - - - - - -
    - -
    - - - - - - diff --git a/doc/src/week37/._week37-bs014.html b/doc/src/week37/._week37-bs014.html deleted file mode 100644 index 44b585130..000000000 --- a/doc/src/week37/._week37-bs014.html +++ /dev/null @@ -1,346 +0,0 @@ - - - - - - - - -Week 37: Summary of Ridge and Lasso Regression and Resampling Methods - - - - - - - - - - - - - - - - - - - - - - - - - - -
    - -

     

     

     

    - - - - -

    Why resampling methods

    - -

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

      -
    1. look at statistical properties, including a discussion of mean values, variance and the so-called bias-variance tradeoff
    2. -
    3. introduce resampling techniques like cross-validation, bootstrapping and jackknife and more
    4. -
    - -and discuss how to select a given model (one of the difficult parts in machine learning). - -

    -

    - -

    - - -
    - - - - - - - -
    - -
    - - - - - - diff --git a/doc/src/week37/._week37-bs015.html b/doc/src/week37/._week37-bs015.html deleted file mode 100644 index bc7bbd54d..000000000 --- a/doc/src/week37/._week37-bs015.html +++ /dev/null @@ -1,363 +0,0 @@ - - - - - - - - -Week 37: Summary of Ridge and Lasso Regression and Resampling Methods - - - - - - - - - - - - - - - - - - - - - - - - - - -
    - -

     

     

     

    - - - - -

    Resampling methods

    -
    -
    -

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

    -Two resampling methods are often used in Machine Learning analyses, - -

      -
    1. The bootstrap method
    2. -
    3. and Cross-Validation
    4. -
    - -In addition there are several other methods such as the Jackknife and the Blocking methods. We will discuss in particular -cross-validation and the bootstrap method. - -

    -

    -
    - - -

    -

    - -

    - - -
    - - - - - - - -
    - -
    - - - - - - diff --git a/doc/src/week37/._week37-bs016.html b/doc/src/week37/._week37-bs016.html deleted file mode 100644 index 4ae2cc1dd..000000000 --- a/doc/src/week37/._week37-bs016.html +++ /dev/null @@ -1,359 +0,0 @@ - - - - - - - - -Week 37: Summary of Ridge and Lasso Regression and Resampling Methods - - - - - - - - - - - - - - - - - - - - - - - - - - -
    - -

     

     

     

    - - - - -

    Resampling approaches can be computationally expensive

    -
    -
    -

    - -

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

    -

    -
    - - -

    -

    - -

    - - -
    - - - - - - - -
    - -
    - - - - - - diff --git a/doc/src/week37/._week37-bs017.html b/doc/src/week37/._week37-bs017.html deleted file mode 100644 index bc0b9197f..000000000 --- a/doc/src/week37/._week37-bs017.html +++ /dev/null @@ -1,346 +0,0 @@ - - - - - - - - -Week 37: Summary of Ridge and Lasso Regression and Resampling Methods - - - - - - - - - - - - - - - - - - - - - - - - - - -
    - -

     

     

     

    - - - - -

    Why resampling methods ?

    -
    -
    -

    - -

      -
    • Our simulations can be treated as computer experiments. This is particularly the case for Monte Carlo methods which are widely used in statistical analyses.
    • -
    • The results can be analysed with the same statistical tools as we would use when analysing experimental data.
    • -
    • As in all experiments, we are looking for expectation values and an estimate of how accurate they are, i.e., possible sources for errors.
    • -
    -
    -
    - - -

    -

    - -

    - - -
    - - - - - - - -
    - -
    - - - - - - diff --git a/doc/src/week37/._week37-bs018.html b/doc/src/week37/._week37-bs018.html deleted file mode 100644 index 5dc9cc2b0..000000000 --- a/doc/src/week37/._week37-bs018.html +++ /dev/null @@ -1,352 +0,0 @@ - - - - - - - - -Week 37: Summary of Ridge and Lasso Regression and Resampling Methods - - - - - - - - - - - - - - - - - - - - - - - - - - -
    - -

     

     

     

    - - - - -

    Statistical analysis

    -
    -
    -

    - -

      -
    • As in other experiments, many numerical experiments have two classes of errors:
    • - -
        -
      • Statistical errors
      • -
      • Systematical errors
      • -
      - -
    • Statistical errors can be estimated using standard tools from statistics
    • -
    • Systematical errors are method specific and must be treated differently from case to case.
    • -
    -
    -
    - - -

    -

    - -

    - - -
    - - - - - - - -
    - -
    - - - - - - diff --git a/doc/src/week37/._week37-bs019.html b/doc/src/week37/._week37-bs019.html deleted file mode 100644 index 4cf039cf9..000000000 --- a/doc/src/week37/._week37-bs019.html +++ /dev/null @@ -1,358 +0,0 @@ - - - - - - - - -Week 37: Summary of Ridge and Lasso Regression and Resampling Methods - - - - - - - - - - - - - - - - - - - - - - - - - - -
    - -

     

     

     

    - - - - -

    Resampling methods

    - -

    -With all these analytical equations for both the OLS and Ridge -regression, we will now outline how to assess a given model. This will -lead to a discussion of the so-called bias-variance tradeoff (see -below) and so-called resampling methods. - -

    -One of the quantities we have discussed as a way to measure errors is -the mean-squared error (MSE), mainly used for fitting of continuous -functions. Another choice is the absolute error. - -

    -In the discussions below we will focus on the MSE and in particular since we will split the data into test and training data, -we discuss the - -

      -
    1. prediction error or simply the test error \( \mathrm{Err_{Test}} \), where we have a fixed training set and the test error is the MSE arising from the data reserved for testing. We discuss also the
    2. -
    3. training error \( \mathrm{Err_{Train}} \), which is the average loss over the training data.
    4. -
    - -As our model becomes more and more complex, more of the training data tends to used. The training may thence adapt to more complicated structures in the data. This may lead to a decrease in the bias (see below for code example) and a slight increase of the variance for the test error. -For a certain level of complexity the test error will reach minimum, before starting to increase again. The -training error reaches a saturation. - -

    -

    - -

    - - -
    - - - - - - - -
    - -
    - - - - - - diff --git a/doc/src/week37/._week37-bs020.html b/doc/src/week37/._week37-bs020.html deleted file mode 100644 index 5cdcbe802..000000000 --- a/doc/src/week37/._week37-bs020.html +++ /dev/null @@ -1,352 +0,0 @@ - - - - - - - - -Week 37: Summary of Ridge and Lasso Regression and Resampling Methods - - - - - - - - - - - - - - - - - - - - - - - - - - -
    - -

     

     

     

    - - - - -

    Resampling methods: Jackknife and Bootstrap

    - -

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

    -The jackknife is a special case of the independent bootstrap. Still, the jackknife was made -popular prior to the independent bootstrap. And as the popularity of -the independent bootstrap soared, new variants, such as the dependent bootstrap have also been developed.. - -

    -The Jackknife and independent bootstrap work for -independent, identically distributed random variables. -If these conditions are not -satisfied, the methods will fail. Yet, it should be said that if the data are -independent, identically distributed, and we only want to estimate the -variance of \( \overline{X} \) (which often is the case), then there is no -need for bootstrapping. - -

    -

    - -

    - - -
    - - - - - - - -
    - -
    - - - - - - diff --git a/doc/src/week37/._week37-bs021.html b/doc/src/week37/._week37-bs021.html deleted file mode 100644 index 4720dff62..000000000 --- a/doc/src/week37/._week37-bs021.html +++ /dev/null @@ -1,348 +0,0 @@ - - - - - - - - -Week 37: Summary of Ridge and Lasso Regression and Resampling Methods - - - - - - - - - - - - - - - - - - - - - - - - - - -
    - -

     

     

     

    - - - - -

    Resampling methods: Jackknife

    - -

    -The Jackknife works by making many replicas of the estimator \( \widehat{\beta} \). -The jackknife is a resampling method where we systematically leave out one observation from the vector of observed values \( \boldsymbol{x} = (x_1,x_2,\cdots,X_n) \). -Let \( \boldsymbol{x}_i \) denote the vector -$$ -\boldsymbol{x}_i = (x_1,x_2,\cdots,x_{i-1},x_{i+1},\cdots,x_n), -$$ - -

    -which equals the vector \( \boldsymbol{x} \) with the exception that observation -number \( i \) is left out. Using this notation, define -\( \widehat{\beta}_i \) to be the estimator -\( \widehat{\beta} \) computed using \( \vec{X}_i \). - -

    -

    - -

    - - -
    - - - - - - - -
    - -
    - - - - - - diff --git a/doc/src/week37/._week37-bs022.html b/doc/src/week37/._week37-bs022.html deleted file mode 100644 index 0bc5446aa..000000000 --- a/doc/src/week37/._week37-bs022.html +++ /dev/null @@ -1,365 +0,0 @@ - - - - - - - - -Week 37: Summary of Ridge and Lasso Regression and Resampling Methods - - - - - - - - - - - - - - - - - - - - - - - - - - -
    - -

     

     

     

    - - - - -

    Jackknife code example

    -

    - - -

    from numpy import *
    -from numpy.random import randint, randn
    -from time import time
    -
    -def jackknife(data, stat):
    -    n = len(data);t = zeros(n); inds = arange(n); t0 = time()
    -    ## 'jackknifing' by leaving out an observation for each i                                                                                                                      
    -    for i in range(n):
    -        t[i] = stat(delete(data,i) )
    -
    -    # analysis                                                                                                                                                                     
    -    print("Runtime: %g sec" % (time()-t0)); print("Jackknife Statistics :")
    -    print("original           bias      std. error")
    -    print("%8g %14g %15g" % (stat(data),(n-1)*mean(t)/n, (n*var(t))**.5))
    -
    -    return t
    -
    -
    -# Returns mean of data samples                                                                                                                                                     
    -def stat(data):
    -    return mean(data)
    -
    -
    -mu, sigma = 100, 15
    -datapoints = 10000
    -x = mu + sigma*random.randn(datapoints)
    -# jackknife returns the data sample                                                                                                                                                
    -t = jackknife(x, stat)
    -
    -

    -

    - -

    - - -
    - - - - - - - -
    - -
    - - - - - - diff --git a/doc/src/week37/._week37-bs023.html b/doc/src/week37/._week37-bs023.html deleted file mode 100644 index 2f517da77..000000000 --- a/doc/src/week37/._week37-bs023.html +++ /dev/null @@ -1,357 +0,0 @@ - - - - - - - - -Week 37: Summary of Ridge and Lasso Regression and Resampling Methods - - - - - - - - - - - - - - - - - - - - - - - - - - -
    - -

     

     

     

    - - - - -

    Resampling methods: Bootstrap

    -
    -
    -

    -Bootstrapping is a non-parametric approach to statistical inference -that substitutes computation for more traditional distributional -assumptions and asymptotic results. Bootstrapping offers a number of -advantages: - -

      -
    1. The bootstrap is quite general, although there are some cases in which it fails.
    2. -
    3. Because it does not require distributional assumptions (such as normally distributed errors), the bootstrap can provide more accurate inferences when the data are not well behaved or when the sample size is small.
    4. -
    5. It is possible to apply the bootstrap to statistics with sampling distributions that are difficult to derive, even asymptotically.
    6. -
    7. It is relatively simple to apply the bootstrap to complex data-collection plans (such as stratified and clustered samples).
    8. -
    -
    -
    - - -

    -The textbook by Davison on the Bootstrap Methods and their Applications provides many more insights and proofs. In this course we will take a more practical approach and use the results and theorems provided in the literature. For those interested in reading more about the bootstrap methods, we recommend the above text and the one by Efron and Tibshirani. - -

    -Before we proceed however, we need to remind ourselves about a central theorem in statistics, namely the so-called central limit theorem. - -

    -

    - -

    - - -
    - - - - - - - -
    - -
    - - - - - - diff --git a/doc/src/week37/._week37-bs024.html b/doc/src/week37/._week37-bs024.html deleted file mode 100644 index c83575a69..000000000 --- a/doc/src/week37/._week37-bs024.html +++ /dev/null @@ -1,351 +0,0 @@ - - - - - - - - -Week 37: Summary of Ridge and Lasso Regression and Resampling Methods - - - - - - - - - - - - - - - - - - - - - - - - - - -
    - -

     

     

     

    - - - - -

    The Central Limit Theorem

    - -

    -Suppose we have a PDF \( p(x) \) from which we generate a series \( N \) -of averages \( \langle x_i \rangle \). Each mean value \( \langle x_i \rangle \) -is viewed as the average of a specific measurement, e.g., throwing -dice 100 times and then taking the average value, or producing a certain -amount of random numbers. -For notational ease, we set \( \langle x_i \rangle=x_i \) in the discussion -which follows. - -

    -If we compute the mean \( z \) of \( m \) such mean values \( x_i \) -$$ - z=\frac{x_1+x_2+\dots+x_m}{m}, -$$ - -the question we pose is which is the PDF of the new variable \( z \). - -

    -

    - -

    - - -
    - - - - - - - -
    - -
    - - - - - - diff --git a/doc/src/week37/._week37-bs025.html b/doc/src/week37/._week37-bs025.html deleted file mode 100644 index 1dea5c181..000000000 --- a/doc/src/week37/._week37-bs025.html +++ /dev/null @@ -1,349 +0,0 @@ - - - - - - - - -Week 37: Summary of Ridge and Lasso Regression and Resampling Methods - - - - - - - - - - - - - - - - - - - - - - - - - - -
    - -

     

     

     

    - - - - -

    Finding the Limit

    - -

    -The probability of obtaining an average value \( z \) is the product of the -probabilities of obtaining arbitrary individual mean values \( x_i \), -but with the constraint that the average is \( z \). We can express this through -the following expression -$$ - \tilde{p}(z)=\int dx_1p(x_1)\int dx_2p(x_2)\dots\int dx_mp(x_m) - \delta(z-\frac{x_1+x_2+\dots+x_m}{m}), -$$ - -where the \( \delta \)-function enbodies the constraint that the mean is \( z \). -All measurements that lead to each individual \( x_i \) are expected to -be independent, which in turn means that we can express \( \tilde{p} \) as the -product of individual \( p(x_i) \). The independence assumption is important in the derivation of the central limit theorem. - -

    -

    - -

    - - -
    - - - - - - - -
    - -
    - - - - - - diff --git a/doc/src/week37/._week37-bs026.html b/doc/src/week37/._week37-bs026.html deleted file mode 100644 index d5f3f4423..000000000 --- a/doc/src/week37/._week37-bs026.html +++ /dev/null @@ -1,358 +0,0 @@ - - - - - - - - -Week 37: Summary of Ridge and Lasso Regression and Resampling Methods - - - - - - - - - - - - - - - - - - - - - - - - - - -
    - -

     

     

     

    - - - - -

    Rewriting the \( \delta \)-function

    - -

    -If we use the integral expression for the \( \delta \)-function - -$$ - \delta(z-\frac{x_1+x_2+\dots+x_m}{m})=\frac{1}{2\pi}\int_{-\infty}^{\infty} - dq\exp{\left(iq(z-\frac{x_1+x_2+\dots+x_m}{m})\right)}, -$$ - -and inserting \( e^{i\mu q-i\mu q} \) where \( \mu \) is the mean value -we arrive at -$$ - \tilde{p}(z)=\frac{1}{2\pi}\int_{-\infty}^{\infty} - dq\exp{\left(iq(z-\mu)\right)}\left[\int_{-\infty}^{\infty} - dxp(x)\exp{\left(iq(\mu-x)/m\right)}\right]^m, -$$ - -with the integral over \( x \) resulting in - -$$ - \int_{-\infty}^{\infty}dxp(x)\exp{\left(iq(\mu-x)/m\right)}= - \int_{-\infty}^{\infty}dxp(x) - \left[1+\frac{iq(\mu-x)}{m}-\frac{q^2(\mu-x)^2}{2m^2}+\dots\right]. -$$ - -

    -

    - -

    - - -
    - - - - - - - -
    - -
    - - - - - - diff --git a/doc/src/week37/._week37-bs027.html b/doc/src/week37/._week37-bs027.html deleted file mode 100644 index 0eb1e4da9..000000000 --- a/doc/src/week37/._week37-bs027.html +++ /dev/null @@ -1,360 +0,0 @@ - - - - - - - - -Week 37: Summary of Ridge and Lasso Regression and Resampling Methods - - - - - - - - - - - - - - - - - - - - - - - - - - -
    - -

     

     

     

    - - - - -

    Identifying Terms

    - -

    -The second term on the rhs disappears since this is just the mean and -employing the definition of \( \sigma^2 \) we have -$$ - \int_{-\infty}^{\infty}dxp(x)e^{\left(iq(\mu-x)/m\right)}= - 1-\frac{q^2\sigma^2}{2m^2}+\dots, -$$ - -resulting in - -$$ - \left[\int_{-\infty}^{\infty}dxp(x)\exp{\left(iq(\mu-x)/m\right)}\right]^m\approx - \left[1-\frac{q^2\sigma^2}{2m^2}+\dots \right]^m, -$$ - -and in the limit \( m\rightarrow \infty \) we obtain - -$$ - \tilde{p}(z)=\frac{1}{\sqrt{2\pi}(\sigma/\sqrt{m})} - \exp{\left(-\frac{(z-\mu)^2}{2(\sigma/\sqrt{m})^2}\right)}, -$$ - -which is the normal distribution with variance -\( \sigma^2_m=\sigma^2/m \), where \( \sigma \) is the variance of the PDF \( p(x) \) -and \( \mu \) is also the mean of the PDF \( p(x) \). - -

    -

    - -

    - - -
    - - - - - - - -
    - -
    - - - - - - diff --git a/doc/src/week37/._week37-bs028.html b/doc/src/week37/._week37-bs028.html deleted file mode 100644 index 9a94e716c..000000000 --- a/doc/src/week37/._week37-bs028.html +++ /dev/null @@ -1,366 +0,0 @@ - - - - - - - - -Week 37: Summary of Ridge and Lasso Regression and Resampling Methods - - - - - - - - - - - - - - - - - - - - - - - - - - -
    - -

     

     

     

    - - - - -

    Wrapping it up

    - -

    -Thus, the central limit theorem states that the PDF \( \tilde{p}(z) \) of -the average of \( m \) random values corresponding to a PDF \( p(x) \) -is a normal distribution whose mean is the -mean value of the PDF \( p(x) \) and whose variance is the variance -of the PDF \( p(x) \) divided by \( m \), the number of values used to compute \( z \). - -

    -The theorem is satisfied by a large class of PDFs. Note however that for a -finite \( m \), it is not always possible to find a closed expression for -\( \tilde{p}(x) \). -The central limit theorem leads then to the well-known expression for the -standard deviation, given by - -$$ - \sigma_m= -\frac{\sigma}{\sqrt{m}}. -$$ - -

    -The latter is true only if the average value is known exactly. This is obtained in the limit -\( m\rightarrow \infty \) only. Because the mean and the variance are measured quantities we obtain -the familiar expression in statistics -$$ - \sigma_m\approx -\frac{\sigma}{\sqrt{m-1}}. -$$ - -

    -In many cases however the above estimate for the standard deviation, -in particular if correlations are strong, may be too simplistic. - -

    -

    - -

    - - -
    - - - - - - - -
    - -
    - - - - - - diff --git a/doc/src/week37/._week37-bs029.html b/doc/src/week37/._week37-bs029.html deleted file mode 100644 index 8a968dea6..000000000 --- a/doc/src/week37/._week37-bs029.html +++ /dev/null @@ -1,334 +0,0 @@ - - - - - - - - -Week 37: Summary of Ridge and Lasso Regression and Resampling Methods - - - - - - - - - - - - - - - - - - - - - - - - - - -
    - -

     

     

     

    - - - - -

    Confidence Intervals

    - -

    -

    - -

    - - -
    - - - - - - - -
    - -
    - - - - - - diff --git a/doc/src/week37/._week37-bs030.html b/doc/src/week37/._week37-bs030.html deleted file mode 100644 index 6f77ecd2f..000000000 --- a/doc/src/week37/._week37-bs030.html +++ /dev/null @@ -1,345 +0,0 @@ - - - - - - - - -Week 37: Summary of Ridge and Lasso Regression and Resampling Methods - - - - - - - - - - - - - - - - - - - - - - - - - - -
    - -

     

     

     

    - - - - -

    Resampling methods: Bootstrap background

    - -

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

    -

    - -

    - - -
    - - - - - - - -
    - -
    - - - - - - diff --git a/doc/src/week37/._week37-bs031.html b/doc/src/week37/._week37-bs031.html deleted file mode 100644 index 967a7319a..000000000 --- a/doc/src/week37/._week37-bs031.html +++ /dev/null @@ -1,351 +0,0 @@ - - - - - - - - -Week 37: Summary of Ridge and Lasso Regression and Resampling Methods - - - - - - - - - - - - - - - - - - - - - - - - - - -
    - -

     

     

     

    - - - - -

    Resampling methods: More Bootstrap background

    - -

    -In the case that \( \widehat{\beta} \) has -more than one component, and the components are independent, we use the -same estimator on each component separately. If the probability -density function of \( X_i \), \( p(x) \), had been known, then it would have -been straightforward to do this by: - -

      -
    1. Drawing lots of numbers from \( p(x) \), suppose we call one such set of numbers \( (X_1^*, X_2^*, \cdots, X_n^*) \).
    2. -
    3. Then using these numbers, we could compute a replica of \( \widehat{\beta} \) called \( \widehat{\beta}^* \).
    4. -
    - -By repeated use of the above two points, many -estimates of \( \widehat{\beta} \) can be obtained. The -idea is to use the relative frequency of \( \widehat{\beta}^* \) -(think of a histogram) as an estimate of \( p(\boldsymbol{t}) \). - -

    -

    - -

    - - -
    - - - - - - - -
    - -
    - - - - - - diff --git a/doc/src/week37/._week37-bs032.html b/doc/src/week37/._week37-bs032.html deleted file mode 100644 index c3b39e6a9..000000000 --- a/doc/src/week37/._week37-bs032.html +++ /dev/null @@ -1,347 +0,0 @@ - - - - - - - - -Week 37: Summary of Ridge and Lasso Regression and Resampling Methods - - - - - - - - - - - - - - - - - - - - - - - - - - -
    - -

     

     

     

    - - - - -

    Resampling methods: Bootstrap approach

    - -

    -But -unless there is enough information available about the process that -generated \( X_1,X_2,\cdots,X_n \), \( p(x) \) is in general -unknown. Therefore, Efron in 1979 asked the -question: What if we replace \( p(x) \) by the relative frequency -of the observation \( X_i \)? - -

    -If we draw observations in accordance with -the relative frequency of the observations, will we obtain the same -result in some asymptotic sense? The answer is yes. - -

    -

    - -

    - - -
    - - - - - - - -
    - -
    - - - - - - diff --git a/doc/src/week37/._week37-bs033.html b/doc/src/week37/._week37-bs033.html deleted file mode 100644 index 93bbdb824..000000000 --- a/doc/src/week37/._week37-bs033.html +++ /dev/null @@ -1,354 +0,0 @@ - - - - - - - - -Week 37: Summary of Ridge and Lasso Regression and Resampling Methods - - - - - - - - - - - - - - - - - - - - - - - - - - -
    - -

     

     

     

    - - - - -

    Resampling methods: Bootstrap steps

    - -

    -The independent bootstrap works like this: - -

      -
    1. Draw with replacement \( n \) numbers for the observed variables \( \boldsymbol{x} = (x_1,x_2,\cdots,x_n) \).
    2. -
    3. Define a vector \( \boldsymbol{x}^* \) containing the values which were drawn from \( \boldsymbol{x} \).
    4. -
    5. Using the vector \( \boldsymbol{x}^* \) compute \( \widehat{\beta}^* \) by evaluating \( \widehat \beta \) under the observations \( \boldsymbol{x}^* \).
    6. -
    7. Repeat this process \( k \) times.
    8. -
    - -When you are done, you can draw a histogram of the relative frequency -of \( \widehat \beta^* \). This is your estimate of the probability -distribution \( p(t) \). Using this probability distribution you can -estimate any statistics thereof. In principle you never draw the -histogram of the relative frequency of \( \widehat{\beta}^* \). Instead -you use the estimators corresponding to the statistic of interest. For -example, if you are interested in estimating the variance of \( \widehat -\beta \), apply the etsimator \( \widehat \sigma^2 \) to the values -\( \widehat \beta^* \). - -

    -

    - -

    - - -
    - - - - - - - -
    - -
    - - - - - - diff --git a/doc/src/week37/._week37-bs034.html b/doc/src/week37/._week37-bs034.html deleted file mode 100644 index 2a1d959bf..000000000 --- a/doc/src/week37/._week37-bs034.html +++ /dev/null @@ -1,386 +0,0 @@ - - - - - - - - -Week 37: Summary of Ridge and Lasso Regression and Resampling Methods - - - - - - - - - - - - - - - - - - - - - - - - - - -
    - -

     

     

     

    - - - - -

    Code example for the Bootstrap method

    - -

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

    - - -

    from numpy import *
    -from numpy.random import randint, randn
    -from time import time
    -import matplotlib.mlab as mlab
    -import matplotlib.pyplot as plt
    -
    -# Returns mean of bootstrap samples                                                                              # Alternatively, we can run it using Scikit-Learn's function resample                                            # See the examples below
    -
    -def statistics(data):
    -    return mean(data)
    -
    -
    -# Bootstrap algorithm
    -def bootstrap(data, statistic, R):
    -    t = zeros(R); n = len(data); inds = arange(n); t0 = time()
    -    # non-parametric bootstrap         
    -    for i in range(R):
    -        t[i] = statistic(data[randint(0,n,n)])
    -
    -    # analysis    
    -    print("Runtime: %g sec" % (time()-t0)); print("Bootstrap Statistics :")
    -    print("original           bias      std. error")
    -    print("%8g %8g %14g %15g" % (statistic(data), std(data),mean(t),std(t)))
    -    return t
    -
    -
    -mu, sigma = 100, 15
    -datapoints = 10000
    -x = mu + sigma*random.randn(datapoints)
    -# bootstrap returns the data sample                                    
    -t = bootstrap(x, statistics, datapoints)
    -
    -

    -We see that our new variance and from that the standard deviation, agrees with the central limit theorem. - -

    -

    - -

    - - -
    - - - - - - - -
    - -
    - - - - - - diff --git a/doc/src/week37/._week37-bs035.html b/doc/src/week37/._week37-bs035.html deleted file mode 100644 index e2fb6f7a4..000000000 --- a/doc/src/week37/._week37-bs035.html +++ /dev/null @@ -1,349 +0,0 @@ - - - - - - - - -Week 37: Summary of Ridge and Lasso Regression and Resampling Methods - - - - - - - - - - - - - - - - - - - - - - - - - - -
    - -

     

     

     

    - - - - -

    Plotting the Histogram

    -

    - - -

    # the histogram of the bootstrapped  data                                                                                                    
    -n, binsboot, patches = plt.hist(t, 50, normed=1, facecolor='red', alpha=0.75)
    -
    -# add a 'best fit' line  
    -y = mlab.normpdf( binsboot, mean(t), std(t))
    -lt = plt.plot(binsboot, y, 'r--', linewidth=1)
    -plt.xlabel('Smarts')
    -plt.ylabel('Probability')
    -plt.axis([99.5, 100.6, 0, 3.0])
    -plt.grid(True)
    -
    -plt.show()
    -
    -

    -

    - -

    - - -
    - - - - - - - -
    - -
    - - - - - - diff --git a/doc/src/week37/._week37-bs036.html b/doc/src/week37/._week37-bs036.html deleted file mode 100644 index 89fcaeb1c..000000000 --- a/doc/src/week37/._week37-bs036.html +++ /dev/null @@ -1,395 +0,0 @@ - - - - - - - - -Week 37: Summary of Ridge and Lasso Regression and Resampling Methods - - - - - - - - - - - - - - - - - - - - - - - - - - -
    - -

     

     

     

    - - - - -

    The bias-variance tradeoff

    - -

    -We will discuss the bias-variance tradeoff in the context of -continuous predictions such as regression. However, many of the -intuitions and ideas discussed here also carry over to classification -tasks. Consider a dataset \( \mathcal{L} \) consisting of the data -\( \mathbf{X}_\mathcal{L}=\{(y_j, \boldsymbol{x}_j), j=0\ldots n-1\} \). - -

    -Let us assume that the true data is generated from a noisy model - -$$ -\boldsymbol{y}=f(\boldsymbol{x}) + \boldsymbol{\epsilon} -$$ - -

    -where \( \epsilon \) is normally distributed with mean zero and standard deviation \( \sigma^2 \). - -

    -In our derivation of the ordinary least squares method we defined then -an approximation to the function \( f \) in terms of the parameters -\( \boldsymbol{\beta} \) and the design matrix \( \boldsymbol{X} \) which embody our model, -that is \( \boldsymbol{\tilde{y}}=\boldsymbol{X}\boldsymbol{\beta} \). - -

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

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

    -The three terms represent the square of the bias of the learning -method, which can be thought of as the error caused by the simplifying -assumptions built into the method. The second term represents the -variance of the chosen model and finally the last terms is variance of -the error \( \boldsymbol{\epsilon} \). - -

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

    -

    - -

    - - -
    - - - - - - - -
    - -
    - - - - - - diff --git a/doc/src/week37/._week37-bs037.html b/doc/src/week37/._week37-bs037.html deleted file mode 100644 index 312464bb6..000000000 --- a/doc/src/week37/._week37-bs037.html +++ /dev/null @@ -1,337 +0,0 @@ - - - - - - - - -Week 37: Summary of Ridge and Lasso Regression and Resampling Methods - - - - - - - - - - - - - - - - - - - - - - - - - - -
    - -

     

     

     

    - - - - -

    A way to Read the Bias-Variance Tradeoff

    - -

    -



    - -

    -

    - -

    - - -
    - - - - - - - -
    - -
    - - - - - - diff --git a/doc/src/week37/._week37-bs038.html b/doc/src/week37/._week37-bs038.html deleted file mode 100644 index c7a6fa753..000000000 --- a/doc/src/week37/._week37-bs038.html +++ /dev/null @@ -1,391 +0,0 @@ - - - - - - - - -Week 37: Summary of Ridge and Lasso Regression and Resampling Methods - - - - - - - - - - - - - - - - - - - - - - - - - - -
    - -

     

     

     

    - - - - -

    Example code for Bias-Variance tradeoff

    -

    - - -

    import matplotlib.pyplot as plt
    -import numpy as np
    -from sklearn.linear_model import LinearRegression, Ridge, Lasso
    -from sklearn.preprocessing import PolynomialFeatures
    -from sklearn.model_selection import train_test_split
    -from sklearn.pipeline import make_pipeline
    -from sklearn.utils import resample
    -
    -np.random.seed(2018)
    -
    -n = 500
    -n_boostraps = 100
    -degree = 18  # A quite high value, just to show.
    -noise = 0.1
    -
    -# Make data set.
    -x = np.linspace(-1, 3, n).reshape(-1, 1)
    -y = np.exp(-x**2) + 1.5 * np.exp(-(x-2)**2) + np.random.normal(0, 0.1, x.shape)
    -
    -# Hold out some test data that is never used in training.
    -x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.2)
    -
    -# Combine x transformation and model into one operation.
    -# Not neccesary, but convenient.
    -model = make_pipeline(PolynomialFeatures(degree=degree), LinearRegression(fit_intercept=False))
    -
    -# The following (m x n_bootstraps) matrix holds the column vectors y_pred
    -# for each bootstrap iteration.
    -y_pred = np.empty((y_test.shape[0], n_boostraps))
    -for i in range(n_boostraps):
    -    x_, y_ = resample(x_train, y_train)
    -
    -    # Evaluate the new model on the same test data each time.
    -    y_pred[:, i] = model.fit(x_, y_).predict(x_test).ravel()
    -
    -# Note: Expectations and variances taken w.r.t. different training
    -# data sets, hence the axis=1. Subsequent means are taken across the test data
    -# set in order to obtain a total value, but before this we have error/bias/variance
    -# calculated per data point in the test set.
    -# Note 2: The use of keepdims=True is important in the calculation of bias as this 
    -# maintains the column vector form. Dropping this yields very unexpected results.
    -error = np.mean( np.mean((y_test - y_pred)**2, axis=1, keepdims=True) )
    -bias = np.mean( (y_test - np.mean(y_pred, axis=1, keepdims=True))**2 )
    -variance = np.mean( np.var(y_pred, axis=1, keepdims=True) )
    -print('Error:', error)
    -print('Bias^2:', bias)
    -print('Var:', variance)
    -print('{} >= {} + {} = {}'.format(error, bias, variance, bias+variance))
    -
    -plt.plot(x[::5, :], y[::5, :], label='f(x)')
    -plt.scatter(x_test, y_test, label='Data points')
    -plt.scatter(x_test, np.mean(y_pred, axis=1), label='Pred')
    -plt.legend()
    -plt.show()
    -
    -

    -

    - -

    - - -
    - - - - - - - -
    - -
    - - - - - - diff --git a/doc/src/week37/._week37-bs039.html b/doc/src/week37/._week37-bs039.html deleted file mode 100644 index eec737109..000000000 --- a/doc/src/week37/._week37-bs039.html +++ /dev/null @@ -1,381 +0,0 @@ - - - - - - - - -Week 37: Summary of Ridge and Lasso Regression and Resampling Methods - - - - - - - - - - - - - - - - - - - - - - - - - - -
    - -

     

     

     

    - - - - -

    Understanding what happens

    -

    - - -

    import matplotlib.pyplot as plt
    -import numpy as np
    -from sklearn.linear_model import LinearRegression, Ridge, Lasso
    -from sklearn.preprocessing import PolynomialFeatures
    -from sklearn.model_selection import train_test_split
    -from sklearn.pipeline import make_pipeline
    -from sklearn.utils import resample
    -
    -np.random.seed(2018)
    -
    -n = 40
    -n_boostraps = 100
    -maxdegree = 14
    -
    -
    -# Make data set.
    -x = np.linspace(-3, 3, n).reshape(-1, 1)
    -y = np.exp(-x**2) + 1.5 * np.exp(-(x-2)**2)+ np.random.normal(0, 0.1, x.shape)
    -error = np.zeros(maxdegree)
    -bias = np.zeros(maxdegree)
    -variance = np.zeros(maxdegree)
    -polydegree = np.zeros(maxdegree)
    -x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.2)
    -
    -for degree in range(maxdegree):
    -    model = make_pipeline(PolynomialFeatures(degree=degree), LinearRegression(fit_intercept=False))
    -    y_pred = np.empty((y_test.shape[0], n_boostraps))
    -    for i in range(n_boostraps):
    -        x_, y_ = resample(x_train, y_train)
    -        y_pred[:, i] = model.fit(x_, y_).predict(x_test).ravel()
    -
    -    polydegree[degree] = degree
    -    error[degree] = np.mean( np.mean((y_test - y_pred)**2, axis=1, keepdims=True) )
    -    bias[degree] = np.mean( (y_test - np.mean(y_pred, axis=1, keepdims=True))**2 )
    -    variance[degree] = np.mean( np.var(y_pred, axis=1, keepdims=True) )
    -    print('Polynomial degree:', degree)
    -    print('Error:', error[degree])
    -    print('Bias^2:', bias[degree])
    -    print('Var:', variance[degree])
    -    print('{} >= {} + {} = {}'.format(error[degree], bias[degree], variance[degree], bias[degree]+variance[degree]))
    -
    -plt.plot(polydegree, error, label='Error')
    -plt.plot(polydegree, bias, label='bias')
    -plt.plot(polydegree, variance, label='Variance')
    -plt.legend()
    -plt.show()
    -
    -

    -

    - -

    - - -
    - - - - - - - -
    - -
    - - - - - - diff --git a/doc/src/week37/._week37-bs040.html b/doc/src/week37/._week37-bs040.html deleted file mode 100644 index 421faa8c0..000000000 --- a/doc/src/week37/._week37-bs040.html +++ /dev/null @@ -1,363 +0,0 @@ - - - - - - - - -Week 37: Summary of Ridge and Lasso Regression and Resampling Methods - - - - - - - - - - - - - - - - - - - - - - - - - - -
    - -

     

     

     

    - - - - -

    Summing up

    - -

    -The bias-variance tradeoff summarizes the fundamental tension in -machine learning, particularly supervised learning, between the -complexity of a model and the amount of training data needed to train -it. Since data is often limited, in practice it is often useful to -use a less-complex model with higher bias, that is a model whose asymptotic -performance is worse than another model because it is easier to -train and less sensitive to sampling noise arising from having a -finite-sized training dataset (smaller variance). - -

    -The above equations tell us that in -order to minimize the expected test error, we need to select a -statistical learning method that simultaneously achieves low variance -and low bias. Note that variance is inherently a nonnegative quantity, -and squared bias is also nonnegative. Hence, we see that the expected -test MSE can never lie below \( Var(\epsilon) \), the irreducible error. - -

    -What do we mean by the variance and bias of a statistical learning -method? The variance refers to the amount by which our model would change if we -estimated it using a different training data set. Since the training -data are used to fit the statistical learning method, different -training data sets will result in a different estimate. But ideally the -estimate for our model should not vary too much between training -sets. However, if a method has high variance then small changes in -the training data can result in large changes in the model. In general, more -flexible statistical methods have higher variance. - -

    -You may also find this recent article of interest. - -

    -

    - -

    - - -
    - - - - - - - -
    - -
    - - - - - - diff --git a/doc/src/week37/._week37-bs041.html b/doc/src/week37/._week37-bs041.html deleted file mode 100644 index 8b36e07d7..000000000 --- a/doc/src/week37/._week37-bs041.html +++ /dev/null @@ -1,404 +0,0 @@ - - - - - - - - -Week 37: Summary of Ridge and Lasso Regression and Resampling Methods - - - - - - - - - - - - - - - - - - - - - - - - - - -
    - -

     

     

     

    - - - - -

    Another Example from Scikit-Learn's Repository

    -

    - - -

    """
    -============================
    -Underfitting vs. Overfitting
    -============================
    -
    -This example demonstrates the problems of underfitting and overfitting and
    -how we can use linear regression with polynomial features to approximate
    -nonlinear functions. The plot shows the function that we want to approximate,
    -which is a part of the cosine function. In addition, the samples from the
    -real function and the approximations of different models are displayed. The
    -models have polynomial features of different degrees. We can see that a
    -linear function (polynomial with degree 1) is not sufficient to fit the
    -training samples. This is called **underfitting**. A polynomial of degree 4
    -approximates the true function almost perfectly. However, for higher degrees
    -the model will **overfit** the training data, i.e. it learns the noise of the
    -training data.
    -We evaluate quantitatively **overfitting** / **underfitting** by using
    -cross-validation. We calculate the mean squared error (MSE) on the validation
    -set, the higher, the less likely the model generalizes correctly from the
    -training data.
    -"""
    -
    -print(__doc__)
    -
    -import numpy as np
    -import matplotlib.pyplot as plt
    -from sklearn.pipeline import Pipeline
    -from sklearn.preprocessing import PolynomialFeatures
    -from sklearn.linear_model import LinearRegression
    -from sklearn.model_selection import cross_val_score
    -
    -
    -def true_fun(X):
    -    return np.cos(1.5 * np.pi * X)
    -
    -np.random.seed(0)
    -
    -n_samples = 30
    -degrees = [1, 4, 15]
    -
    -X = np.sort(np.random.rand(n_samples))
    -y = true_fun(X) + np.random.randn(n_samples) * 0.1
    -
    -plt.figure(figsize=(14, 5))
    -for i in range(len(degrees)):
    -    ax = plt.subplot(1, len(degrees), i + 1)
    -    plt.setp(ax, xticks=(), yticks=())
    -
    -    polynomial_features = PolynomialFeatures(degree=degrees[i],
    -                                             include_bias=False)
    -    linear_regression = LinearRegression()
    -    pipeline = Pipeline([("polynomial_features", polynomial_features),
    -                         ("linear_regression", linear_regression)])
    -    pipeline.fit(X[:, np.newaxis], y)
    -
    -    # Evaluate the models using crossvalidation
    -    scores = cross_val_score(pipeline, X[:, np.newaxis], y,
    -                             scoring="neg_mean_squared_error", cv=10)
    -
    -    X_test = np.linspace(0, 1, 100)
    -    plt.plot(X_test, pipeline.predict(X_test[:, np.newaxis]), label="Model")
    -    plt.plot(X_test, true_fun(X_test), label="True function")
    -    plt.scatter(X, y, edgecolor='b', s=20, label="Samples")
    -    plt.xlabel("x")
    -    plt.ylabel("y")
    -    plt.xlim((0, 1))
    -    plt.ylim((-2, 2))
    -    plt.legend(loc="best")
    -    plt.title("Degree {}\nMSE = {:.2e}(+/- {:.2e})".format(
    -        degrees[i], -scores.mean(), scores.std()))
    -plt.show()
    -
    -

    -

    - -

    - - -
    - - - - - - - -
    - -
    - - - - - - diff --git a/doc/src/week37/._week37-bs042.html b/doc/src/week37/._week37-bs042.html deleted file mode 100644 index 1c599b23b..000000000 --- a/doc/src/week37/._week37-bs042.html +++ /dev/null @@ -1,345 +0,0 @@ - - - - - - - - -Week 37: Summary of Ridge and Lasso Regression and Resampling Methods - - - - - - - - - - - - - - - - - - - - - - - - - - -
    - -

     

     

     

    - - - - -

    Various steps in cross-validation

    - -

    -When the repetitive splitting of the data set is done randomly, -samples may accidently end up in a fast majority of the splits in -either training or test set. Such samples may have an unbalanced -influence on either model building or prediction evaluation. To avoid -this \( k \)-fold cross-validation structures the data splitting. The -samples are divided into \( k \) more or less equally sized exhaustive and -mutually exclusive subsets. In turn (at each split) one of these -subsets plays the role of the test set while the union of the -remaining subsets constitutes the training set. Such a splitting -warrants a balanced representation of each sample in both training and -test set over the splits. Still the division into the \( k \) subsets -involves a degree of randomness. This may be fully excluded when -choosing \( k=n \). This particular case is referred to as leave-one-out -cross-validation (LOOCV). - -

    -

    - -

    - - -
    - - - - - - - -
    - -
    - - - - - - diff --git a/doc/src/week37/._week37-bs043.html b/doc/src/week37/._week37-bs043.html deleted file mode 100644 index ab4bf59f9..000000000 --- a/doc/src/week37/._week37-bs043.html +++ /dev/null @@ -1,355 +0,0 @@ - - - - - - - - -Week 37: Summary of Ridge and Lasso Regression and Resampling Methods - - - - - - - - - - - - - - - - - - - - - - - - - - -
    - -

     

     

     

    - - - - -

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

    - - - -$$ -\begin{align*} -\boldsymbol{\beta}_{-i}(\lambda) & = ( \boldsymbol{X}_{-i, \ast}^{T} -\boldsymbol{X}_{-i, \ast} + \lambda \boldsymbol{I}_{pp})^{-1} -\boldsymbol{X}_{-i, \ast}^{T} \boldsymbol{y}_{-i} -\end{align*} -$$ - - - - -$$ -\begin{align*} -\frac{1}{n} \sum_{i = 1}^n \log\{L[y_i, \mathbf{X}_{i, \ast}; \boldsymbol{\beta}_{-i}(\lambda), \boldsymbol{\sigma}_{-i}^2(\lambda)]\}. -\end{align*} -$$ - -

    -

    - -

    - - -
    - - - - - - - -
    - -
    - - - - - - diff --git a/doc/src/week37/._week37-bs044.html b/doc/src/week37/._week37-bs044.html deleted file mode 100644 index c77eece25..000000000 --- a/doc/src/week37/._week37-bs044.html +++ /dev/null @@ -1,344 +0,0 @@ - - - - - - - - -Week 37: Summary of Ridge and Lasso Regression and Resampling Methods - - - - - - - - - - - - - - - - - - - - - - - - - - -
    - -

     

     

     

    - - - - -

    Cross-validation in brief

    - -

    -For the various values of \( k \) - -

      -
    1. shuffle the dataset randomly.
    2. -
    3. Split the dataset into \( k \) groups.
    4. -
    5. For each unique group: - -
        -
      1. Decide which group to use as set for test data
      2. -
      3. Take the remaining groups as a training data set
      4. -
      5. Fit a model on the training set and evaluate it on the test set
      6. -
      7. Retain the evaluation score and discard the model
      8. -
      - -
    6. Summarize the model using the sample of model evaluation scores
    7. -
    - -

    - -

    - - -
    - - - - - - - -
    - -
    - - - - - - diff --git a/doc/src/week37/._week37-bs045.html b/doc/src/week37/._week37-bs045.html deleted file mode 100644 index c832537f5..000000000 --- a/doc/src/week37/._week37-bs045.html +++ /dev/null @@ -1,421 +0,0 @@ - - - - - - - - -Week 37: Summary of Ridge and Lasso Regression and Resampling Methods - - - - - - - - - - - - - - - - - - - - - - - - - - -
    - -

     

     

     

    - - - - -

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

    - -

    -The code here uses Ridge regression with cross-validation (CV) resampling and \( k \)-fold CV in order to fit a specific polynomial. -

    - - -

    import numpy as np
    -import matplotlib.pyplot as plt
    -from sklearn.model_selection import KFold
    -from sklearn.linear_model import Ridge
    -from sklearn.model_selection import cross_val_score
    -from sklearn.preprocessing import PolynomialFeatures
    -
    -# A seed just to ensure that the random numbers are the same for every run.
    -# Useful for eventual debugging.
    -np.random.seed(3155)
    -
    -# Generate the data.
    -nsamples = 100
    -x = np.random.randn(nsamples)
    -y = 3*x**2 + np.random.randn(nsamples)
    -
    -## Cross-validation on Ridge regression using KFold only
    -
    -# Decide degree on polynomial to fit
    -poly = PolynomialFeatures(degree = 6)
    -
    -# Decide which values of lambda to use
    -nlambdas = 500
    -lambdas = np.logspace(-3, 5, nlambdas)
    -
    -# Initialize a KFold instance
    -k = 5
    -kfold = KFold(n_splits = k)
    -
    -# Perform the cross-validation to estimate MSE
    -scores_KFold = np.zeros((nlambdas, k))
    -
    -i = 0
    -for lmb in lambdas:
    -    ridge = Ridge(alpha = lmb)
    -    j = 0
    -    for train_inds, test_inds in kfold.split(x):
    -        xtrain = x[train_inds]
    -        ytrain = y[train_inds]
    -
    -        xtest = x[test_inds]
    -        ytest = y[test_inds]
    -
    -        Xtrain = poly.fit_transform(xtrain[:, np.newaxis])
    -        ridge.fit(Xtrain, ytrain[:, np.newaxis])
    -
    -        Xtest = poly.fit_transform(xtest[:, np.newaxis])
    -        ypred = ridge.predict(Xtest)
    -
    -        scores_KFold[i,j] = np.sum((ypred - ytest[:, np.newaxis])**2)/np.size(ypred)
    -
    -        j += 1
    -    i += 1
    -
    -
    -estimated_mse_KFold = np.mean(scores_KFold, axis = 1)
    -
    -## Cross-validation using cross_val_score from sklearn along with KFold
    -
    -# kfold is an instance initialized above as:
    -# kfold = KFold(n_splits = k)
    -
    -estimated_mse_sklearn = np.zeros(nlambdas)
    -i = 0
    -for lmb in lambdas:
    -    ridge = Ridge(alpha = lmb)
    -
    -    X = poly.fit_transform(x[:, np.newaxis])
    -    estimated_mse_folds = cross_val_score(ridge, X, y[:, np.newaxis], scoring='neg_mean_squared_error', cv=kfold)
    -
    -    # cross_val_score return an array containing the estimated negative mse for every fold.
    -    # we have to the the mean of every array in order to get an estimate of the mse of the model
    -    estimated_mse_sklearn[i] = np.mean(-estimated_mse_folds)
    -
    -    i += 1
    -
    -## Plot and compare the slightly different ways to perform cross-validation
    -
    -plt.figure()
    -
    -plt.plot(np.log10(lambdas), estimated_mse_sklearn, label = 'cross_val_score')
    -plt.plot(np.log10(lambdas), estimated_mse_KFold, 'r--', label = 'KFold')
    -
    -plt.xlabel('log10(lambda)')
    -plt.ylabel('mse')
    -
    -plt.legend()
    -
    -plt.show()
    -
    -

    -

    - -

    - - -
    - - - - - - - -
    - -
    - - - - - - diff --git a/doc/src/week37/._week37-bs046.html b/doc/src/week37/._week37-bs046.html deleted file mode 100644 index cd01ccbbf..000000000 --- a/doc/src/week37/._week37-bs046.html +++ /dev/null @@ -1,407 +0,0 @@ - - - - - - - - -Week 37: Summary of Ridge and Lasso Regression and Resampling Methods - - - - - - - - - - - - - - - - - - - - - - - - - - -
    - -

     

     

     

    - - - - -

    More examples on bootstrap and cross-validation and errors

    - -

    - - -

    # Common imports
    -import os
    -import numpy as np
    -import pandas as pd
    -import matplotlib.pyplot as plt
    -from sklearn.linear_model import LinearRegression, Ridge, Lasso
    -from sklearn.model_selection import train_test_split
    -from sklearn.utils import resample
    -from sklearn.metrics import mean_squared_error
    -# Where to save the figures and data files
    -PROJECT_ROOT_DIR = "Results"
    -FIGURE_ID = "Results/FigureFiles"
    -DATA_ID = "DataFiles/"
    -
    -if not os.path.exists(PROJECT_ROOT_DIR):
    -    os.mkdir(PROJECT_ROOT_DIR)
    -
    -if not os.path.exists(FIGURE_ID):
    -    os.makedirs(FIGURE_ID)
    -
    -if not os.path.exists(DATA_ID):
    -    os.makedirs(DATA_ID)
    -
    -def image_path(fig_id):
    -    return os.path.join(FIGURE_ID, fig_id)
    -
    -def data_path(dat_id):
    -    return os.path.join(DATA_ID, dat_id)
    -
    -def save_fig(fig_id):
    -    plt.savefig(image_path(fig_id) + ".png", format='png')
    -
    -infile = open(data_path("EoS.csv"),'r')
    -
    -# Read the EoS data as  csv file and organize the data into two arrays with density and energies
    -EoS = pd.read_csv(infile, names=('Density', 'Energy'))
    -EoS['Energy'] = pd.to_numeric(EoS['Energy'], errors='coerce')
    -EoS = EoS.dropna()
    -Energies = EoS['Energy']
    -Density = EoS['Density']
    -#  The design matrix now as function of various polytrops
    -
    -Maxpolydegree = 30
    -X = np.zeros((len(Density),Maxpolydegree))
    -X[:,0] = 1.0
    -testerror = np.zeros(Maxpolydegree)
    -trainingerror = np.zeros(Maxpolydegree)
    -polynomial = np.zeros(Maxpolydegree)
    -
    -trials = 100
    -for polydegree in range(1, Maxpolydegree):
    -    polynomial[polydegree] = polydegree
    -    for degree in range(polydegree):
    -        X[:,degree] = Density**(degree/3.0)
    -
    -# loop over trials in order to estimate the expectation value of the MSE
    -    testerror[polydegree] = 0.0
    -    trainingerror[polydegree] = 0.0
    -    for samples in range(trials):
    -        x_train, x_test, y_train, y_test = train_test_split(X, Energies, test_size=0.2)
    -        model = LinearRegression(fit_intercept=True).fit(x_train, y_train)
    -        ypred = model.predict(x_train)
    -        ytilde = model.predict(x_test)
    -        testerror[polydegree] += mean_squared_error(y_test, ytilde)
    -        trainingerror[polydegree] += mean_squared_error(y_train, ypred) 
    -
    -    testerror[polydegree] /= trials
    -    trainingerror[polydegree] /= trials
    -    print("Degree of polynomial: %3d"% polynomial[polydegree])
    -    print("Mean squared error on training data: %.8f" % trainingerror[polydegree])
    -    print("Mean squared error on test data: %.8f" % testerror[polydegree])
    -
    -plt.plot(polynomial, np.log10(trainingerror), label='Training Error')
    -plt.plot(polynomial, np.log10(testerror), label='Test Error')
    -plt.xlabel('Polynomial degree')
    -plt.ylabel('log10[MSE]')
    -plt.legend()
    -plt.show()
    -
    -

    -

    - -

    - - -
    - - - - - - - -
    - -
    - - - - - - diff --git a/doc/src/week37/._week37-bs047.html b/doc/src/week37/._week37-bs047.html deleted file mode 100644 index b294cd77d..000000000 --- a/doc/src/week37/._week37-bs047.html +++ /dev/null @@ -1,395 +0,0 @@ - - - - - - - - -Week 37: Summary of Ridge and Lasso Regression and Resampling Methods - - - - - - - - - - - - - - - - - - - - - - - - - - -
    - -

     

     

     

    - - - - -

    The same example but now with cross-validation

    - -

    - - -

    # Common imports
    -import os
    -import numpy as np
    -import pandas as pd
    -import matplotlib.pyplot as plt
    -from sklearn.linear_model import LinearRegression, Ridge, Lasso
    -from sklearn.metrics import mean_squared_error
    -from sklearn.model_selection import KFold
    -from sklearn.model_selection import cross_val_score
    -
    -
    -# Where to save the figures and data files
    -PROJECT_ROOT_DIR = "Results"
    -FIGURE_ID = "Results/FigureFiles"
    -DATA_ID = "DataFiles/"
    -
    -if not os.path.exists(PROJECT_ROOT_DIR):
    -    os.mkdir(PROJECT_ROOT_DIR)
    -
    -if not os.path.exists(FIGURE_ID):
    -    os.makedirs(FIGURE_ID)
    -
    -if not os.path.exists(DATA_ID):
    -    os.makedirs(DATA_ID)
    -
    -def image_path(fig_id):
    -    return os.path.join(FIGURE_ID, fig_id)
    -
    -def data_path(dat_id):
    -    return os.path.join(DATA_ID, dat_id)
    -
    -def save_fig(fig_id):
    -    plt.savefig(image_path(fig_id) + ".png", format='png')
    -
    -infile = open(data_path("EoS.csv"),'r')
    -
    -# Read the EoS data as  csv file and organize the data into two arrays with density and energies
    -EoS = pd.read_csv(infile, names=('Density', 'Energy'))
    -EoS['Energy'] = pd.to_numeric(EoS['Energy'], errors='coerce')
    -EoS = EoS.dropna()
    -Energies = EoS['Energy']
    -Density = EoS['Density']
    -#  The design matrix now as function of various polytrops
    -
    -Maxpolydegree = 30
    -X = np.zeros((len(Density),Maxpolydegree))
    -X[:,0] = 1.0
    -estimated_mse_sklearn = np.zeros(Maxpolydegree)
    -polynomial = np.zeros(Maxpolydegree)
    -k =5
    -kfold = KFold(n_splits = k)
    -
    -for polydegree in range(1, Maxpolydegree):
    -    polynomial[polydegree] = polydegree
    -    for degree in range(polydegree):
    -        X[:,degree] = Density**(degree/3.0)
    -        OLS = LinearRegression()
    -# loop over trials in order to estimate the expectation value of the MSE
    -    estimated_mse_folds = cross_val_score(OLS, X, Energies, scoring='neg_mean_squared_error', cv=kfold)
    -#[:, np.newaxis]
    -    estimated_mse_sklearn[polydegree] = np.mean(-estimated_mse_folds)
    -
    -plt.plot(polynomial, np.log10(estimated_mse_sklearn), label='Test Error')
    -plt.xlabel('Polynomial degree')
    -plt.ylabel('log10[MSE]')
    -plt.legend()
    -plt.show()
    -
    -

    -

    - -

    - - -
    - - - - - - - -
    - -
    - - - - - - diff --git a/doc/src/week37/._week37-bs048.html b/doc/src/week37/._week37-bs048.html deleted file mode 100644 index e78b60bc1..000000000 --- a/doc/src/week37/._week37-bs048.html +++ /dev/null @@ -1,361 +0,0 @@ - - - - - - - - -Week 37: Summary of Ridge and Lasso Regression and Resampling Methods - - - - - - - - - - - - - - - - - - - - - - - - - - -
    - -

     

     

     

    - - - - -

    Cross-validation with Ridge

    -

    - - -

    import numpy as np
    -import matplotlib.pyplot as plt
    -from sklearn.model_selection import KFold
    -from sklearn.linear_model import Ridge
    -from sklearn.model_selection import cross_val_score
    -from sklearn.preprocessing import PolynomialFeatures
    -
    -# A seed just to ensure that the random numbers are the same for every run.
    -np.random.seed(3155)
    -# Generate the data.
    -n = 100
    -x = np.linspace(-3, 3, n).reshape(-1, 1)
    -y = np.exp(-x**2) + 1.5 * np.exp(-(x-2)**2)+ np.random.normal(0, 0.1, x.shape)
    -# Decide degree on polynomial to fit
    -poly = PolynomialFeatures(degree = 10)
    -
    -# Decide which values of lambda to use
    -nlambdas = 500
    -lambdas = np.logspace(-3, 5, nlambdas)
    -# Initialize a KFold instance
    -k = 5
    -kfold = KFold(n_splits = k)
    -estimated_mse_sklearn = np.zeros(nlambdas)
    -i = 0
    -for lmb in lambdas:
    -    ridge = Ridge(alpha = lmb)
    -    estimated_mse_folds = cross_val_score(ridge, x, y, scoring='neg_mean_squared_error', cv=kfold)
    -    estimated_mse_sklearn[i] = np.mean(-estimated_mse_folds)
    -    i += 1
    -plt.figure()
    -plt.plot(np.log10(lambdas), estimated_mse_sklearn, label = 'cross_val_score')
    -plt.xlabel('log10(lambda)')
    -plt.ylabel('MSE')
    -plt.legend()
    -plt.show()
    -
    -

    - -

    - -

    - - -
    - - - - - - - -
    - -
    - - - - - - diff --git a/doc/src/week37/ipynb-week37-src.tar.gz b/doc/src/week37/ipynb-week37-src.tar.gz deleted file mode 100644 index 8893c7353..000000000 Binary files a/doc/src/week37/ipynb-week37-src.tar.gz and /dev/null differ diff --git a/doc/src/week37/reveal.js/.gitignore b/doc/src/week37/reveal.js/.gitignore deleted file mode 100644 index a5df3133d..000000000 --- a/doc/src/week37/reveal.js/.gitignore +++ /dev/null @@ -1,8 +0,0 @@ -.DS_Store -.svn -log/*.log -tmp/** -node_modules/ -.sass-cache -css/reveal.min.css -js/reveal.min.js diff --git a/doc/src/week37/reveal.js/.travis.yml b/doc/src/week37/reveal.js/.travis.yml deleted file mode 100644 index 165d9ae9f..000000000 --- a/doc/src/week37/reveal.js/.travis.yml +++ /dev/null @@ -1,5 +0,0 @@ -language: node_js -node_js: - - 0.10 -before_script: - - npm install -g grunt-cli \ No newline at end of file diff --git a/doc/src/week37/reveal.js/CONTRIBUTING.md b/doc/src/week37/reveal.js/CONTRIBUTING.md deleted file mode 100644 index c2091e88f..000000000 --- a/doc/src/week37/reveal.js/CONTRIBUTING.md +++ /dev/null @@ -1,23 +0,0 @@ -## Contributing - -Please keep the [issue tracker](http://github.com/hakimel/reveal.js/issues) limited to **bug reports**, **feature requests** and **pull requests**. - - -### Personal Support -If you have personal support or setup questions the best place to ask those are [StackOverflow](http://stackoverflow.com/questions/tagged/reveal.js). - - -### Bug Reports -When reporting a bug make sure to include information about which browser and operating system you are on as well as the necessary steps to reproduce the issue. If possible please include a link to a sample presentation where the bug can be tested. - - -### Pull Requests -- Should follow the coding style of the file you work in, most importantly: - - Tabs to indent - - Single-quoted strings -- Should be made towards the **dev branch** -- Should be submitted from a feature/topic branch (not your master) - - -### Plugins -Please do not submit plugins as pull requests. They should be maintained in their own separate repository. More information here: https://github.com/hakimel/reveal.js/wiki/Plugin-Guidelines diff --git a/doc/src/week37/reveal.js/Gruntfile.js b/doc/src/week37/reveal.js/Gruntfile.js deleted file mode 100644 index b257e8f32..000000000 --- a/doc/src/week37/reveal.js/Gruntfile.js +++ /dev/null @@ -1,140 +0,0 @@ -/* global module:false */ -module.exports = function(grunt) { - var port = grunt.option('port') || 8000; - // Project configuration - grunt.initConfig({ - pkg: grunt.file.readJSON('package.json'), - meta: { - banner: - '/*!\n' + - ' * reveal.js <%= pkg.version %> (<%= grunt.template.today("yyyy-mm-dd, HH:MM") %>)\n' + - ' * http://lab.hakim.se/reveal-js\n' + - ' * MIT licensed\n' + - ' *\n' + - ' * Copyright (C) 2014 Hakim El Hattab, http://hakim.se\n' + - ' */' - }, - - qunit: { - files: [ 'test/*.html' ] - }, - - uglify: { - options: { - banner: '<%= meta.banner %>\n' - }, - build: { - src: 'js/reveal.js', - dest: 'js/reveal.min.js' - } - }, - - cssmin: { - compress: { - files: { - 'css/reveal.min.css': [ 'css/reveal.css' ] - } - } - }, - - sass: { - main: { - files: { - 'css/theme/darkgray.css': 'css/theme/source/darkgray.scss', - 'css/theme/beigesmall.css': 'css/theme/source/beigesmall.scss', - 'css/theme/cbc.css': 'css/theme/source/cbc.scss', - 'css/theme/default.css': 'css/theme/source/default.scss', - 'css/theme/beige.css': 'css/theme/source/beige.scss', - 'css/theme/night.css': 'css/theme/source/night.scss', - 'css/theme/serif.css': 'css/theme/source/serif.scss', - 'css/theme/simple.css': 'css/theme/source/simple.scss', - 'css/theme/sky.css': 'css/theme/source/sky.scss', - 'css/theme/moon.css': 'css/theme/source/moon.scss', - 'css/theme/solarized.css': 'css/theme/source/solarized.scss', - 'css/theme/blood.css': 'css/theme/source/blood.scss' - } - } - }, - - jshint: { - options: { - curly: false, - eqeqeq: true, - immed: true, - latedef: true, - newcap: true, - noarg: true, - sub: true, - undef: true, - eqnull: true, - browser: true, - expr: true, - globals: { - head: false, - module: false, - console: false, - unescape: false - } - }, - files: [ 'Gruntfile.js', 'js/reveal.js' ] - }, - - connect: { - server: { - options: { - port: port, - base: '.' - } - } - }, - - zip: { - 'reveal-js-presentation.zip': [ - 'index.html', - 'css/**', - 'js/**', - 'lib/**', - 'images/**', - 'plugin/**' - ] - }, - - watch: { - main: { - files: [ 'Gruntfile.js', 'js/reveal.js', 'css/reveal.css' ], - tasks: 'default' - }, - theme: { - files: [ 'css/theme/source/*.scss', 'css/theme/template/*.scss' ], - tasks: 'themes' - } - } - - }); - - // Dependencies - grunt.loadNpmTasks( 'grunt-contrib-qunit' ); - grunt.loadNpmTasks( 'grunt-contrib-jshint' ); - grunt.loadNpmTasks( 'grunt-contrib-cssmin' ); - grunt.loadNpmTasks( 'grunt-contrib-uglify' ); - grunt.loadNpmTasks( 'grunt-contrib-watch' ); - grunt.loadNpmTasks( 'grunt-contrib-sass' ); - grunt.loadNpmTasks( 'grunt-contrib-connect' ); - grunt.loadNpmTasks( 'grunt-zip' ); - - // Default task - grunt.registerTask( 'default', [ 'jshint', 'cssmin', 'uglify', 'qunit' ] ); - - // Theme task - grunt.registerTask( 'themes', [ 'sass' ] ); - - // Package presentation to archive - grunt.registerTask( 'package', [ 'default', 'zip' ] ); - - // Serve presentation locally - grunt.registerTask( 'serve', [ 'connect', 'watch' ] ); - - // Run tests - grunt.registerTask( 'test', [ 'jshint', 'qunit' ] ); - -}; diff --git a/doc/src/week37/reveal.js/LICENSE b/doc/src/week37/reveal.js/LICENSE deleted file mode 100644 index 09623076f..000000000 --- a/doc/src/week37/reveal.js/LICENSE +++ /dev/null @@ -1,19 +0,0 @@ -Copyright (C) 2015 Hakim El Hattab, http://hakim.se - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. \ No newline at end of file diff --git a/doc/src/week37/reveal.js/README.md b/doc/src/week37/reveal.js/README.md deleted file mode 100644 index 573b19597..000000000 --- a/doc/src/week37/reveal.js/README.md +++ /dev/null @@ -1,1052 +0,0 @@ -# reveal.js [![Build Status](https://travis-ci.org/hakimel/reveal.js.svg?branch=master)](https://travis-ci.org/hakimel/reveal.js) - -A framework for easily creating beautiful presentations using HTML. [Check out the live demo](http://lab.hakim.se/reveal-js/). - -reveal.js comes with a broad range of features including [nested slides](https://github.com/hakimel/reveal.js#markup), [Markdown contents](https://github.com/hakimel/reveal.js#markdown), [PDF export](https://github.com/hakimel/reveal.js#pdf-export), [speaker notes](https://github.com/hakimel/reveal.js#speaker-notes) and a [JavaScript API](https://github.com/hakimel/reveal.js#api). It's best viewed in a modern browser but [fallbacks](https://github.com/hakimel/reveal.js/wiki/Browser-Support) are available to make sure your presentation can still be viewed elsewhere. - - -#### More reading: -- [Installation](#installation): Step-by-step instructions for getting reveal.js running on your computer. -- [Changelog](https://github.com/hakimel/reveal.js/releases): Up-to-date version history. -- [Examples](https://github.com/hakimel/reveal.js/wiki/Example-Presentations): Presentations created with reveal.js, add your own! -- [Browser Support](https://github.com/hakimel/reveal.js/wiki/Browser-Support): Explanation of browser support and fallbacks. -- [Plugins](https://github.com/hakimel/reveal.js/wiki/Plugins,-Tools-and-Hardware): A list of plugins that can be used to extend reveal.js. - -## Online Editor - -Presentations are written using HTML or Markdown but there's also an online editor for those of you who prefer a graphical interface. Give it a try at [http://slides.com](http://slides.com). - - -## Instructions - -### Markup - -Markup hierarchy needs to be ``
    `` where the ``
    `` represents one slide and can be repeated indefinitely. If you place multiple ``
    ``'s inside of another ``
    `` they will be shown as vertical slides. The first of the vertical slides is the "root" of the others (at the top), and it will be included in the horizontal sequence. For example: - -```html -
    -
    -
    Single Horizontal Slide
    -
    -
    Vertical Slide 1
    -
    Vertical Slide 2
    -
    -
    -
    -``` - -### Markdown - -It's possible to write your slides using Markdown. To enable Markdown, add the ```data-markdown``` attribute to your ```
    ``` elements and wrap the contents in a ``` -
    -``` - -#### External Markdown - -You can write your content as a separate file and have reveal.js load it at runtime. Note the separator arguments which determine how slides are delimited in the external file. The ```data-charset``` attribute is optional and specifies which charset to use when loading the external file. - -When used locally, this feature requires that reveal.js [runs from a local web server](#full-setup). - -```html -
    -
    -``` - -#### Element Attributes - -Special syntax (in html comment) is available for adding attributes to Markdown elements. This is useful for fragments, amongst other things. - -```html -
    - -
    -``` - -#### Slide Attributes - -Special syntax (in html comment) is available for adding attributes to the slide `
    ` elements generated by your Markdown. - -```html -
    - -
    -``` - - -### Configuration - -At the end of your page you need to initialize reveal by running the following code. Note that all config values are optional and will default as specified below. - -```javascript -Reveal.initialize({ - - // Display controls in the bottom right corner - controls: true, - - // Display a presentation progress bar - progress: true, - - // Display the page number of the current slide - slideNumber: false, - - // Push each slide change to the browser history - history: false, - - // Enable keyboard shortcuts for navigation - keyboard: true, - - // Enable the slide overview mode - overview: true, - - // Vertical centering of slides - center: true, - - // Enables touch navigation on devices with touch input - touch: true, - - // Loop the presentation - loop: false, - - // Change the presentation direction to be RTL - rtl: false, - - // Turns fragments on and off globally - fragments: true, - - // Flags if the presentation is running in an embedded mode, - // i.e. contained within a limited portion of the screen - embedded: false, - - // Flags if we should show a help overlay when the questionmark - // key is pressed - help: true, - - // Number of milliseconds between automatically proceeding to the - // next slide, disabled when set to 0, this value can be overwritten - // by using a data-autoslide attribute on your slides - autoSlide: 0, - - // Stop auto-sliding after user input - autoSlideStoppable: true, - - // Enable slide navigation via mouse wheel - mouseWheel: false, - - // Hides the address bar on mobile devices - hideAddressBar: true, - - // Opens links in an iframe preview overlay - previewLinks: false, - - // Transition style - transition: 'default', // none/fade/slide/convex/concave/zoom - - // Transition speed - transitionSpeed: 'default', // default/fast/slow - - // Transition style for full page slide backgrounds - backgroundTransition: 'default', // none/fade/slide/convex/concave/zoom - - // Number of slides away from the current that are visible - viewDistance: 3, - - // Parallax background image - parallaxBackgroundImage: '', // e.g. "'https://s3.amazonaws.com/hakim-static/reveal-js/reveal-parallax-1.jpg'" - - // Parallax background size - parallaxBackgroundSize: '', // CSS syntax, e.g. "2100px 900px" - - // Amount to move parallax background (horizontal and vertical) on slide change - // Number, e.g. 100 - parallaxBackgroundHorizontal: '', - parallaxBackgroundVertical: '' - -}); -``` - - -The configuration can be updated after initialization using the ```configure``` method: - -```javascript -// Turn autoSlide off -Reveal.configure({ autoSlide: 0 }); - -// Start auto-sliding every 5s -Reveal.configure({ autoSlide: 5000 }); -``` - - -### Dependencies - -Reveal.js doesn't _rely_ on any third party scripts to work but a few optional libraries are included by default. These libraries are loaded as dependencies in the order they appear, for example: - -```javascript -Reveal.initialize({ - dependencies: [ - // Cross-browser shim that fully implements classList - https://github.com/eligrey/classList.js/ - { src: 'lib/js/classList.js', condition: function() { return !document.body.classList; } }, - - // Interpret Markdown in
    elements - { src: 'plugin/markdown/marked.js', condition: function() { return !!document.querySelector( '[data-markdown]' ); } }, - { src: 'plugin/markdown/markdown.js', condition: function() { return !!document.querySelector( '[data-markdown]' ); } }, - - // Syntax highlight for elements - { src: 'plugin/highlight/highlight.js', async: true, callback: function() { hljs.initHighlightingOnLoad(); } }, - - // Zoom in and out with Alt+click - { src: 'plugin/zoom-js/zoom.js', async: true }, - - // Speaker notes - { src: 'plugin/notes/notes.js', async: true }, - - // Remote control your reveal.js presentation using a touch device - { src: 'plugin/remotes/remotes.js', async: true }, - - // MathJax - { src: 'plugin/math/math.js', async: true } - ] -}); -``` - -You can add your own extensions using the same syntax. The following properties are available for each dependency object: -- **src**: Path to the script to load -- **async**: [optional] Flags if the script should load after reveal.js has started, defaults to false -- **callback**: [optional] Function to execute when the script has loaded -- **condition**: [optional] Function which must return true for the script to be loaded - - -### Ready Event - -A 'ready' event is fired when reveal.js has loaded all non-async dependencies and is ready to start navigating. To check if reveal.js is already 'ready' you can call `Reveal.isReady()`. - -```javascript -Reveal.addEventListener( 'ready', function( event ) { - // event.currentSlide, event.indexh, event.indexv -} ); -``` - - -### Presentation Size - -All presentations have a normal size, that is the resolution at which they are authored. The framework will automatically scale presentations uniformly based on this size to ensure that everything fits on any given display or viewport. - -See below for a list of configuration options related to sizing, including default values: - -```javascript -Reveal.initialize({ - - ... - - // The "normal" size of the presentation, aspect ratio will be preserved - // when the presentation is scaled to fit different resolutions. Can be - // specified using percentage units. - width: 960, - height: 700, - - // Factor of the display size that should remain empty around the content - margin: 0.1, - - // Bounds for smallest/largest possible scale to apply to content - minScale: 0.2, - maxScale: 1.5 - -}); -``` - - -### Auto-sliding - -Presentations can be configured to progress through slides automatically, without any user input. To enable this you will need to tell the framework how many milliseconds it should wait between slides: - -```javascript -// Slide every five seconds -Reveal.configure({ - autoSlide: 5000 -}); -``` -When this is turned on a control element will appear that enables users to pause and resume auto-sliding. Alternatively, sliding can be paused or resumed by pressing »a« on the keyboard. Sliding is paused automatically as soon as the user starts navigating. You can disable these controls by specifying ```autoSlideStoppable: false``` in your reveal.js config. - -You can also override the slide duration for individual slides and fragments by using the ```data-autoslide``` attribute: - -```html -
    -

    After 2 seconds the first fragment will be shown.

    -

    After 10 seconds the next fragment will be shown.

    -

    Now, the fragment is displayed for 2 seconds before the next slide is shown.

    -
    -``` - -Whenever the auto-slide mode is resumed or paused the ```autoslideresumed``` and ```autoslidepaused``` events are fired. - - -### Keyboard Bindings - -If you're unhappy with any of the default keyboard bindings you can override them using the ```keyboard``` config option: - -```javascript -Reveal.configure({ - keyboard: { - 13: 'next', // go to the next slide when the ENTER key is pressed - 27: function() {}, // do something custom when ESC is pressed - 32: null // don't do anything when SPACE is pressed (i.e. disable a reveal.js default binding) - } -}); -``` - -### Lazy Loading - -When working on presentation with a lot of media or iframe content it's important to load lazily. Lazy loading means that reveal.js will only load content for the few slides nearest to the current slide. The number of slides that are preloaded is determined by the `viewDistance` configuration option. - -To enable lazy loading all you need to do is change your "src" attributes to "data-src" as shown below. This is supported for image, video, audio and iframe elements. Lazy loaded iframes will also unload when the containing slide is no longer visible. - -```html -
    - - - -
    -``` - - -### API - -The ``Reveal`` object exposes a JavaScript API for controlling navigation and reading state: - -```javascript -// Navigation -Reveal.slide( indexh, indexv, indexf ); -Reveal.left(); -Reveal.right(); -Reveal.up(); -Reveal.down(); -Reveal.prev(); -Reveal.next(); -Reveal.prevFragment(); -Reveal.nextFragment(); - -// Toggle presentation states, optionally pass true/false to force on/off -Reveal.toggleOverview(); -Reveal.togglePause(); -Reveal.toggleAutoSlide(); - -// Change a config value at runtime -Reveal.configure({ controls: true }); - -// Returns the present configuration options -Reveal.getConfig(); - -// Fetch the current scale of the presentation -Reveal.getScale(); - -// Retrieves the previous and current slide elements -Reveal.getPreviousSlide(); -Reveal.getCurrentSlide(); - -Reveal.getIndices(); // { h: 0, v: 0 } } -Reveal.getProgress(); // 0-1 -Reveal.getTotalSlides(); - -// State checks -Reveal.isFirstSlide(); -Reveal.isLastSlide(); -Reveal.isOverview(); -Reveal.isPaused(); -Reveal.isAutoSliding(); -``` - -### Slide Changed Event - -A 'slidechanged' event is fired each time the slide is changed (regardless of state). The event object holds the index values of the current slide as well as a reference to the previous and current slide HTML nodes. - -Some libraries, like MathJax (see [#226](https://github.com/hakimel/reveal.js/issues/226#issuecomment-10261609)), get confused by the transforms and display states of slides. Often times, this can be fixed by calling their update or render function from this callback. - -```javascript -Reveal.addEventListener( 'slidechanged', function( event ) { - // event.previousSlide, event.currentSlide, event.indexh, event.indexv -} ); -``` - -### Presentation State - -The presentation's current state can be fetched by using the `getState` method. A state object contains all of the information required to put the presentation back as it was when `getState` was first called. Sort of like a snapshot. It's a simple object that can easily be stringified and persisted or sent over the wire. - -```javascript -Reveal.slide( 1 ); -// we're on slide 1 - -var state = Reveal.getState(); - -Reveal.slide( 3 ); -// we're on slide 3 - -Reveal.setState( state ); -// we're back on slide 1 -``` - -### Slide States - -If you set ``data-state="somestate"`` on a slide ``
    ``, "somestate" will be applied as a class on the document element when that slide is opened. This allows you to apply broad style changes to the page based on the active slide. - -Furthermore you can also listen to these changes in state via JavaScript: - -```javascript -Reveal.addEventListener( 'somestate', function() { - // TODO: Sprinkle magic -}, false ); -``` - -### Slide Backgrounds - -Slides are contained within a limited portion of the screen by default to allow them to fit any display and scale uniformly. You can apply full page backgrounds outside of the slide area by adding a ```data-background``` attribute to your ```
    ``` elements. Four different types of backgrounds are supported: color, image, video and iframe. Below are a few examples. - -```html -
    -

    All CSS color formats are supported, like rgba() or hsl().

    -
    -
    -

    This slide will have a full-size background image.

    -
    -
    -

    This background image will be sized to 100px and repeated.

    -
    -
    -

    Video. Multiple sources can be defined using a comma separated list. Video will loop when the data-background-video-loop attribute is provided.

    -
    -
    -

    Embeds a web page as a background. Note that the page won't be interactive.

    -
    -``` - -Backgrounds transition using a fade animation by default. This can be changed to a linear sliding transition by passing ```backgroundTransition: 'slide'``` to the ```Reveal.initialize()``` call. Alternatively you can set ```data-background-transition``` on any section with a background to override that specific transition. - - -### Parallax Background - -If you want to use a parallax scrolling background, set the first two config properties below when initializing reveal.js (the other two are optional). - -```javascript -Reveal.initialize({ - - // Parallax background image - parallaxBackgroundImage: '', // e.g. "https://s3.amazonaws.com/hakim-static/reveal-js/reveal-parallax-1.jpg" - - // Parallax background size - parallaxBackgroundSize: '', // CSS syntax, e.g. "2100px 900px" - currently only pixels are supported (don't use % or auto) - - // Amount of pixels to move the parallax background per slide step, - // a value of 0 disables movement along the given axis - // These are optional, if they aren't specified they'll be calculated automatically - parallaxBackgroundHorizontal: 200, - parallaxBackgroundVertical: 50 - -}); -``` - -Make sure that the background size is much bigger than screen size to allow for some scrolling. [View example](http://lab.hakim.se/reveal-js/?parallaxBackgroundImage=https%3A%2F%2Fs3.amazonaws.com%2Fhakim-static%2Freveal-js%2Freveal-parallax-1.jpg¶llaxBackgroundSize=2100px%20900px). - - - -### Slide Transitions -The global presentation transition is set using the ```transition``` config value. You can override the global transition for a specific slide by using the ```data-transition``` attribute: - -```html -
    -

    This slide will override the presentation transition and zoom!

    -
    - -
    -

    Choose from three transition speeds: default, fast or slow!

    -
    -``` - -You can also use different in and out transitions for the same slide: - -```html -
    - The train goes on … -
    -
    - and on … -
    -
    - and stops. -
    -
    - (Passengers entering and leaving) -
    -
    - And it starts again. -
    -``` - - -Note that this does not work with the page and cube transitions. - - -### Internal links - -It's easy to link between slides. The first example below targets the index of another slide whereas the second targets a slide with an ID attribute (```
    ```): - -```html -Link -Link -``` - -You can also add relative navigation links, similar to the built in reveal.js controls, by appending one of the following classes on any element. Note that each element is automatically given an ```enabled``` class when it's a valid navigation route based on the current slide. - -```html - - - - - - -``` - - -### Fragments -Fragments are used to highlight individual elements on a slide. Every element with the class ```fragment``` will be stepped through before moving on to the next slide. Here's an example: http://lab.hakim.se/reveal-js/#/fragments - -The default fragment style is to start out invisible and fade in. This style can be changed by appending a different class to the fragment: - -```html -
    -

    grow

    -

    shrink

    -

    fade-out

    -

    visible only once

    -

    blue only once

    -

    highlight-red

    -

    highlight-green

    -

    highlight-blue

    -
    -``` - -Multiple fragments can be applied to the same element sequentially by wrapping it, this will fade in the text on the first step and fade it back out on the second. - -```html -
    - - I'll fade in, then out - -
    -``` - -The display order of fragments can be controlled using the ```data-fragment-index``` attribute. - -```html -
    -

    Appears last

    -

    Appears first

    -

    Appears second

    -
    -``` - -### Fragment events - -When a slide fragment is either shown or hidden reveal.js will dispatch an event. - -Some libraries, like MathJax (see #505), get confused by the initially hidden fragment elements. Often times this can be fixed by calling their update or render function from this callback. - -```javascript -Reveal.addEventListener( 'fragmentshown', function( event ) { - // event.fragment = the fragment DOM element -} ); -Reveal.addEventListener( 'fragmenthidden', function( event ) { - // event.fragment = the fragment DOM element -} ); -``` - -### Code syntax highlighting - -By default, Reveal is configured with [highlight.js](http://softwaremaniacs.org/soft/highlight/en/) for code syntax highlighting. Below is an example with clojure code that will be syntax highlighted. When the `data-trim` attribute is present surrounding whitespace is automatically removed. - -```html -
    -
    
    -(def lazy-fib
    -  (concat
    -   [0 1]
    -   ((fn rfib [a b]
    -        (lazy-cons (+ a b) (rfib b (+ a b)))) 0 1)))
    -	
    -
    -``` - -### Slide number -If you would like to display the page number of the current slide you can do so using the ```slideNumber``` configuration value. - -```javascript -// Shows the slide number using default formatting -Reveal.configure({ slideNumber: true }); - -// Slide number formatting can be configured using these variables: -// h: current slide's horizontal index -// v: current slide's vertical index -// c: current slide index (flattened) -// t: total number of slides (flattened) -Reveal.configure({ slideNumber: 'c / t' }); - -``` - - -### Overview mode - -Press "Esc" or "o" keys to toggle the overview mode on and off. While you're in this mode, you can still navigate between slides, -as if you were at 1,000 feet above your presentation. The overview mode comes with a few API hooks: - -```javascript -Reveal.addEventListener( 'overviewshown', function( event ) { /* ... */ } ); -Reveal.addEventListener( 'overviewhidden', function( event ) { /* ... */ } ); - -// Toggle the overview mode programmatically -Reveal.toggleOverview(); -``` - -### Fullscreen mode -Just press »F« on your keyboard to show your presentation in fullscreen mode. Press the »ESC« key to exit fullscreen mode. - - -### Embedded media -Embedded HTML5 `
    - -
    - -

     

     

     

    - - - - - - -
    -

    Week 37: Summary of Ridge and Lasso Regression and Resampling Methods

    - -

    - - -

    -Morten Hjorth-Jensen [1, 2] -
    - -

    - - -

    [1] Department of Physics, University of Oslo
    -
    [2] Department of Physics and Astronomy and National Superconducting Cyclotron Laboratory, Michigan State University
    -
    -

    -

    Sep 16, 2021

    -
    -

    - - -

    Read »

    - - -
    - -

    - -

    - - -
    - - - - - - - -
    - © 1999-2021, Morten Hjorth-Jensen. Released under CC Attribution-NonCommercial 4.0 license -
    - - - - - - diff --git a/doc/src/week37/week37-reveal.html b/doc/src/week37/week37-reveal.html deleted file mode 100644 index 2f6b49944..000000000 --- a/doc/src/week37/week37-reveal.html +++ /dev/null @@ -1,2076 +0,0 @@ - - - - - - - -Week 37: Summary of Ridge and Lasso Regression and Resampling Methods - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    - - - -
    - - - - - - - - - - - - - - -
    - - - - -

    Week 37: Summary of Ridge and Lasso Regression and Resampling Methods

    - -

    - - -

    -Morten Hjorth-Jensen [1, 2] -
    - -

     
    - - -

    [1] Department of Physics, University of Oslo
    -
    [2] Department of Physics and Astronomy and National Superconducting Cyclotron Laboratory, Michigan State University
    -
    -

     
    -

    Sep 16, 2021

    -
    -

    - -

    - © 1999-2021, Morten Hjorth-Jensen. Released under CC Attribution-NonCommercial 4.0 license -
    -
    - - -
    -

    Plans for week 37

    - -
      -

    • Thursday September 16: Summary of Ridge and Lasso with examples and start resampling techniques
    • -

    • Friday September 17: Resampling methods, Cross-validation, Bootstrapping and jackknife
    • -
    -

    - -Recommended Reading: - -

      -

    1. Lectures on Resampling methods (these lectures)
    2. -

    3. Bishop 1.3 (cross-validation) and 3.2 (bias-variance tradeoff)
    4. -

    5. Hastie et al Chapter 7, here we recommend 7.1-7.5 and 7.10 (cross-validation) and 7.11 (bootstrap). This chapter is better than Bishop's on these topics. Goodfellow et al discuss this in a superficial way in sections 5.2-5.5.
    6. -
    -
    - - -
    -

    Thursday September 16, Summary of Ridge and Lasso Regression and start Resampling methods

    -
    - - -
    -

    Deriving OLS from a probability distribution

    - -

    -Our basic assumption when we derived the OLS equations was to assume -that our output is determined by a given continuous function -\( f(\boldsymbol{x}) \) and a random noise \( \boldsymbol{\epsilon} \) given by the normal -distribution with zero mean value and an undetermined variance -\( \sigma^2 \). - -

    -We found above that the outputs \( \boldsymbol{y} \) have a mean value given by -\( \boldsymbol{X}\hat{\boldsymbol{\beta}} \) and variance \( \sigma^2 \). Since the entries to -the design matrix are not stochastic variables, we can assume that the -probability distribution of our targets is also a normal distribution -but now with mean value \( \boldsymbol{X}\hat{\boldsymbol{\beta}} \). This means that a -single output \( y_i \) is given by the Gaussian distribution - -

     
    -$$ -y_i\sim \mathcal{N}(\boldsymbol{X}_{i,*}\boldsymbol{\beta}, \sigma^2)=\frac{1}{\sqrt{2\pi\sigma^2}}\exp{\left[-\frac{(y_i-\boldsymbol{X}_{i,*}\boldsymbol{\beta})^2}{2\sigma^2}\right]}. -$$ -

     
    -

    - - -
    -

    Independent and Identically Distrubuted (iid)

    - -

    -We assume now that the various \( y_i \) values are stochastically distributed according to the above Gaussian distribution. -We define this distribution as -

     
    -$$ -p(y_i, \boldsymbol{X}\vert\boldsymbol{\beta})=\frac{1}{\sqrt{2\pi\sigma^2}}\exp{\left[-\frac{(y_i-\boldsymbol{X}_{i,*}\boldsymbol{\beta})^2}{2\sigma^2}\right]}, -$$ -

     
    - -which reads as finding the likelihood of an event \( y_i \) with the input variables \( \boldsymbol{X} \) given the parameters (to be determined) \( \boldsymbol{\beta} \). - -

    -Since these events are assumed to be independent and identicall distributed we can build the probability distribution function (PDF) for all possible event \( \boldsymbol{y} \) as the product of the single events, that is we have - -

     
    -$$ -p(\boldsymbol{y},\boldsymbol{X}\vert\boldsymbol{\beta})=\prod_{i=0}^{n-1}\frac{1}{\sqrt{2\pi\sigma^2}}\exp{\left[-\frac{(y_i-\boldsymbol{X}_{i,*}\boldsymbol{\beta})^2}{2\sigma^2}\right]}=\prod_{i=0}^{n-1}p(y_i,\boldsymbol{X}\vert\boldsymbol{\beta}). -$$ -

     
    - -

    -We will write this in a more compact form reserving \( \boldsymbol{D} \) for the domain of events, including the ouputs (targets) and the inputs. That is -in case we have a simple one-dimensional input and output case -

     
    -$$ -\boldsymbol{D}=[(x_0,y_0), (x_1,y_1),\dots, (x_{n-1},y_{n-1})]. -$$ -

     
    - -In the more general case the various inputs should be replaced by the possible features represented by the input data set \( \boldsymbol{X} \). -We can now rewrite the above probability as -

     
    -$$ -p(\boldsymbol{D}\vert\boldsymbol{\beta})=\prod_{i=0}^{n-1}\frac{1}{\sqrt{2\pi\sigma^2}}\exp{\left[-\frac{(y_i-\boldsymbol{X}_{i,*}\boldsymbol{\beta})^2}{2\sigma^2}\right]}. -$$ -

     
    - -

    -It is a conditional probability (see below) and reads as the likelihood of a domain of events \( \boldsymbol{D} \) given a set of parameters \( \boldsymbol{\beta} \). -

    - - -
    -

    Maximum Likelihood Estimation (MLE)

    - -

    -In statistics, maximum likelihood estimation (MLE) is a method of -estimating the parameters of an assumed probability distribution, -given some observed data. This is achieved by maximizing a likelihood -function so that, under the assumed statistical model, the observed -data is the most probable. - -

    -We will assume here that our events are given by the above Gaussian -distribution and we will determine the optimal parameters \( \beta \) by -maximizing the above PDF. However, computing the derivatives of a -product function is cumbersome and can easily lead to overflow and/or -underflowproblems, with potentials for loss of numerical precision. - -

    -In practice, it is more convenient to maximize the logarithm of the -PDF because it is a monotonically increasing function of the argument. -Alternatively, and this will be our option, we will minimize the -negative of the logarithm since this is a monotonically decreasing -function. - -

    -Note also that maximization/minimization of the logarithm of the PDF -is equivalent to the maximization/minimization of the function itself. -

    - - -
    -

    A new Cost Function

    - -

    -We could now define a new cost function to minimize, namely the negative logarithm of the above PDF - -

     
    -$$ -C(\boldsymbol{\beta}=-\log{\prod_{i=0}^{n-1}p(y_i,\boldsymbol{X}\vert\boldsymbol{\beta})}=-\sum_{i=0}^{n-1}\log{p(y_i,\boldsymbol{X}\vert\boldsymbol{\beta})}, -$$ -

     
    - -which becomes -

     
    -$$ -C(\boldsymbol{\beta}=\frac{n}{2}\log{2\pi\sigma^2}+\frac{\vert\vert (\boldsymbol{y}-\boldsymbol{X}\boldsymbol{\beta})\vert\vert_2^2}{2\sigma^2}. -$$ -

     
    - -

    -Taking the derivative of the new cost function with respect to the parameters \( \beta \) we recognize our familiar OLS equation, namely - -

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

     
    - -which leads to the well-known OLS equation for the optimal paramters \( \beta \) -

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

     
    -

    - - -
    -

    Bayes' Theorem

    - -

    -If we combine the conditional probability with the marginal probability and the standard product rule, we have -

     
    -$$ -p(X\vert Y)= \frac{p(X,Y)}{p(Y)}, -$$ -

     
    - -which we can rewrite as - -

     
    -$$ -p(X\vert Y)= \frac{p(X,Y)}{\sum_{i=0}^{n-1}p(Y\vert X=x_i)p(x_i)}=\frac{p(Y\vert X)p(X)}{\sum_{i=0}^{n-1}p(Y\vert X=x_i)p(x_i)}, -$$ -

     
    - -which is Bayes' theorem. It allows us to evaluate the uncertainty in in \( X \) after we have observed \( Y \). We can easily interchange \( X \) with \( Y \). -

    - - -
    -

    Interpretations of Bayes' Theorem

    - -

    -The quantity \( p(Y\vert X) \) on the right-hand side of the theorem is -evaluated for the observed data \( Y \) and can be viewed as a function of -the parameter space represented by \( X \). This function is not -necesseraly normalized and is normally called the likelihood function. - -

    -The function \( p(X) \) on the right hand side is called the prior while the function on the left hand side is the called the posterior probability. The denominator on the right hand side serves as a normalization factor for the posterior distribution. -

    - - -
    -

    Test Function for what happens with OLS, Ridge and Lasso

    - -

    -We will play around with a study of the values for the optimal -parameters \( \boldsymbol{\beta} \) using OLS, Ridge and Lasso regression. For -OLS, you will notice as function of the noise and polynomial degree, -that the parameters \( \beta \) will fluctuate from order to order in the -polynomial fit and that for larger and larger polynomial degrees of freedom, the parameters will tend to increase in value for OLS. - -

    -For Ridge and Lasso regression, the higher order parameters will typically be reduced, providing thereby less fluctuations from one order to another one. - -

    - - -

    import numpy as np
    -import matplotlib.pyplot as plt
    -from sklearn.model_selection import train_test_split
    -from sklearn import linear_model
    -
    -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
    -
    -# Make data set.
    -n = 10000
    -x = np.random.rand(n)
    -y = np.exp(-x**2) + 1.5 * np.exp(-(x-2)**2)+ np.random.randn(n)
    -
    -Maxpolydegree = 5
    -X = np.zeros((len(x),Maxpolydegree))
    -X[:,0] = 1.0
    -
    -for polydegree in range(1, Maxpolydegree):
    -    for degree in range(polydegree):
    -        X[:,degree] = x**(degree)
    -
    -
    -# 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.pinv(X_train.T @ X_train) @ X_train.T @ y_train
    -print(OLSbeta)
    -ypredictOLS = X_test @ OLSbeta
    -print("Test MSE OLS")
    -print(MSE(y_test,ypredictOLS))
    -# Repeat now for Lasso and Ridge regression and various values of the regularization parameter using Scikit-Learn
    -# Decide which values of lambda to use
    -nlambdas = 4
    -MSERidgePredict = np.zeros(nlambdas)
    -MSELassoPredict = np.zeros(nlambdas)
    -lambdas = np.logspace(-3, 1, nlambdas)
    -for i in range(nlambdas):
    -    lmb = lambdas[i]
    -    # Make the fit using Ridge and Lasso
    -    RegRidge = linear_model.Ridge(lmb,fit_intercept=False)
    -    RegRidge.fit(X_train,y_train)
    -    RegLasso = linear_model.Lasso(lmb,fit_intercept=False)
    -    RegLasso.fit(X_train,y_train)
    -    # and then make the prediction
    -    ypredictRidge = RegRidge.predict(X_test)
    -    ypredictLasso = RegLasso.predict(X_test)
    -    # Compute the MSE and print it
    -    MSERidgePredict[i] = MSE(y_test,ypredictRidge)
    -    MSELassoPredict[i] = MSE(y_test,ypredictLasso)
    -    print(lmb,RegRidge.coef_)
    -    print(lmb,RegLasso.coef_)
    -# Now plot the results
    -plt.figure()
    -plt.plot(np.log10(lambdas), MSERidgePredict, 'b', label = 'MSE Ridge Test')
    -plt.plot(np.log10(lambdas), MSELassoPredict, 'r', label = 'MSE Lasso Test')
    -plt.xlabel('log10(lambda)')
    -plt.ylabel('MSE')
    -plt.legend()
    -plt.show()
    -
    -

    -How can we understand this? -

    - - -
    -

    Rerunning the above code

    - -

    -Let us write out the values of the coefficients \( \beta_i \) as functions -of the polynomial degree and noise. We will focus only on the Ridge -results and some few selected values of the hyperparameter \( \lambda \). - -

    -If we don't include any noise and run this code for different values -of the polynomial degree, we notice that the results for \( \beta_i \) do -not show great changes from one order to the next. This is an -indication that for higher polynomial orders, our parameters become -less important. - -

    -If we however add noise, what happens is that the polynomial fit is -trying to adjust the fit to traverse in the best possible way all data -points. This can lead to large fluctuations in the parameters -\( \beta_i \) as functions of polynomial order. It will also be reflected -in a larger value of the variance of each parameter \( \beta_i \). What -Ridge regression (and Lasso as well) are doing then is to try to -quench the fluctuations in the parameters of \( \beta_i \) which have a -large variance (normally for higher orders in the polynomial). - -

    - - -

    import numpy as np
    -import pandas as pd
    -from IPython.display import display
    -import matplotlib.pyplot as plt
    -from sklearn.model_selection import train_test_split
    -from sklearn import linear_model
    -
    -# Make data set.
    -n = 1000
    -x = np.random.rand(n)
    -y = np.exp(-x**2) + 1.5 * np.exp(-(x-2)**2)+ np.random.randn(n)
    -
    -Maxpolydegree = 5
    -X = np.zeros((len(x),Maxpolydegree))
    -X[:,0] = 1.0
    -
    -for polydegree in range(1, Maxpolydegree):
    -    for degree in range(polydegree):
    -        X[:,degree] = x**(degree)
    -
    -
    -# 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)
    -
    -# Decide which values of lambda to use
    -nlambdas = 5
    -lambdas = np.logspace(-3, 2, nlambdas)
    -for i in range(nlambdas):
    -    lmb = lambdas[i]
    -    # Make the fit using Ridge only
    -    RegRidge = linear_model.Ridge(lmb,fit_intercept=False)
    -    RegRidge.fit(X_train,y_train)
    -    # and then make the prediction
    -    ypredictRidge = RegRidge.predict(X_test)
    -    Coeffs = np.array(RegRidge.coef_)
    -    BetaValues = pd.DataFrame(Coeffs)
    -    BetaValues.columns = ['beta']
    -    display(BetaValues)    
    -
    -
    - - -
    -

    Invoking Bayes' theorem

    - -

    -Using Bayes' theorem we can gain a better intuition about Ridge and Lasso regression. - -

    -For ordinary least squares we postulated that the maximum likelihood for the doamin of events \( \boldsymbol{D} \) (one-dimensional case) -

     
    -$$ -\boldsymbol{D}=[(x_0,y_0), (x_1,y_1),\dots, (x_{n-1},y_{n-1})], -$$ -

     
    - -is given by -

     
    -$$ -p(\boldsymbol{D}\vert\boldsymbol{\beta})=\prod_{i=0}^{n-1}\frac{1}{\sqrt{2\pi\sigma^2}}\exp{\left[-\frac{(y_i-\boldsymbol{X}_{i,*}\boldsymbol{\beta})^2}{2\sigma^2}\right]}. -$$ -

     
    - -

    -In Bayes' theorem this function plays the role of the so-called likelihood. We could now ask the question what is the posterior probability of a parameter set \( \boldsymbol{\beta} \) given a domain of events \( \boldsymbol{D} \)? That is, how can we define the posterior probability - -

     
    -$$ -p(\boldsymbol{\beta}\vert\boldsymbol{D}). -$$ -

     
    - -

    -Bayes' theorem comes to our rescue here since (omitting the normalization constant) -

     
    -$$ -p(\boldsymbol{\beta}\vert\boldsymbol{D})\propto p(\boldsymbol{D}\vert\boldsymbol{\beta})p(\boldsymbol{\beta}). -$$ -

     
    - -

    -We have a model for \( p(\boldsymbol{D}\vert\boldsymbol{\beta}) \) but need one for the prior \( p(\boldsymbol{\beta} \)! -

    - - -
    -

    Ridge and Bayes

    - -

    -With the posterior probability defined by a likelihood which we have -already modeled and an unknown prior, we are now ready to make -additional models for the prior. - -

    -We can, based on our discussions of the variance of \( \boldsymbol{\beta} \) and the mean value, assume that the prior for the values \( \boldsymbol{\beta} \) is given by a Gaussian with mean value zero and variance \( \tau^2 \), that is - -

     
    -$$ -p(\boldsymbol{\beta})=\prod_{j=0}^{p-1}\exp{\left(-\frac{\beta_j^2}{2\tau^2}\right)}. -$$ -

     
    - -

    -Our posterior probability becomes then (omitting the normalization factor which is just a constant) -

     
    -$$ -p(\boldsymbol{\beta\vert\boldsymbol{D})}=\prod_{i=0}^{n-1}\frac{1}{\sqrt{2\pi\sigma^2}}\exp{\left[-\frac{(y_i-\boldsymbol{X}_{i,*}\boldsymbol{\beta})^2}{2\sigma^2}\right]}\prod_{j=0}^{p-1}\exp{\left(-\frac{\beta_j^2}{2\tau^2}\right)}. -$$ -

     
    - -

    -We can now optimize this quantity with respect to \( \boldsymbol{\beta} \). As we -did for OLS, this is most conveniently done by taking the negative -logarithm of the posterior probability. Doing so and leaving out the -constants terms that do not depend on \( \beta \), we have - -

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

     
    - -and replacing \( 1/2\tau^2 \) with \( \lambda \) we have - -

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

     
    - -which is our Ridge cost function! Nice, isn't it? -

    - - -
    -

    Lasso and Bayes

    - -

    -To derive the Lasso cost function, we simply replace the Gaussian prior with an exponential distribution (Laplace in this case) with zero mean value, that is - -

     
    -$$ -p(\boldsymbol{\beta})=\prod_{j=0}^{p-1}\exp{\left(-\frac{\vert\beta_j\vert}{\tau}\right)}. -$$ -

     
    - -

    -Our posterior probability becomes then (omitting the normalization factor which is just a constant) -

     
    -$$ -p(\boldsymbol{\beta}\vert\boldsymbol{D})=\prod_{i=0}^{n-1}\frac{1}{\sqrt{2\pi\sigma^2}}\exp{\left[-\frac{(y_i-\boldsymbol{X}_{i,*}\boldsymbol{\beta})^2}{2\sigma^2}\right]}\prod_{j=0}^{p-1}\exp{\left(-\frac{\vert\beta_j\vert}{\tau}\right)}. -$$ -

     
    - -

    -Taking the negative -logarithm of the posterior probability and leaving out the -constants terms that do not depend on \( \beta \), we have - -

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

     
    - -and replacing \( 1/\tau \) with \( \lambda \) we have - -

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

     
    - -which is our Lasso cost function! -

    - - -
    -

    Why resampling methods

    - -

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

      -

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

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

    - -and discuss how to select a given model (one of the difficult parts in machine learning). -

    - - -
    -

    Resampling methods

    -
    - -

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

    -Two resampling methods are often used in Machine Learning analyses, - -

      -

    1. The bootstrap method
    2. -

    3. and Cross-Validation
    4. -
    -

    - -In addition there are several other methods such as the Jackknife and the Blocking methods. We will discuss in particular -cross-validation and the bootstrap method. - - -

    -
    - - -
    -

    Resampling approaches can be computationally expensive

    -
    - -

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

    -
    - - -
    -

    Why resampling methods ?

    -
    -Statistical analysis -
      -

    • Our simulations can be treated as computer experiments. This is particularly the case for Monte Carlo methods which are widely used in statistical analyses.
    • -

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

    • As in all experiments, we are looking for expectation values and an estimate of how accurate they are, i.e., possible sources for errors.
    • -
    -
    -
    - - -
    -

    Statistical analysis

    -
    - -
      -

    • As in other experiments, many numerical experiments have two classes of errors:
    • - -
        - -

      • Statistical errors
      • - -

      • Systematical errors
      • -
      -

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

    • Systematical errors are method specific and must be treated differently from case to case.
    • -
    -
    -
    - - -
    -

    Resampling methods

    - -

    -With all these analytical equations for both the OLS and Ridge -regression, we will now outline how to assess a given model. This will -lead to a discussion of the so-called bias-variance tradeoff (see -below) and so-called resampling methods. - -

    -One of the quantities we have discussed as a way to measure errors is -the mean-squared error (MSE), mainly used for fitting of continuous -functions. Another choice is the absolute error. - -

    -In the discussions below we will focus on the MSE and in particular since we will split the data into test and training data, -we discuss the - -

      -

    1. prediction error or simply the test error \( \mathrm{Err_{Test}} \), where we have a fixed training set and the test error is the MSE arising from the data reserved for testing. We discuss also the
    2. -

    3. training error \( \mathrm{Err_{Train}} \), which is the average loss over the training data.
    4. -
    -

    - -As our model becomes more and more complex, more of the training data tends to used. The training may thence adapt to more complicated structures in the data. This may lead to a decrease in the bias (see below for code example) and a slight increase of the variance for the test error. -For a certain level of complexity the test error will reach minimum, before starting to increase again. The -training error reaches a saturation. -

    - - -
    -

    Resampling methods: Jackknife and Bootstrap

    - -

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

    -The jackknife is a special case of the independent bootstrap. Still, the jackknife was made -popular prior to the independent bootstrap. And as the popularity of -the independent bootstrap soared, new variants, such as the dependent bootstrap have also been developed.. - -

    -The Jackknife and independent bootstrap work for -independent, identically distributed random variables. -If these conditions are not -satisfied, the methods will fail. Yet, it should be said that if the data are -independent, identically distributed, and we only want to estimate the -variance of \( \overline{X} \) (which often is the case), then there is no -need for bootstrapping. -

    - - -
    -

    Resampling methods: Jackknife

    - -

    -The Jackknife works by making many replicas of the estimator \( \widehat{\beta} \). -The jackknife is a resampling method where we systematically leave out one observation from the vector of observed values \( \boldsymbol{x} = (x_1,x_2,\cdots,X_n) \). -Let \( \boldsymbol{x}_i \) denote the vector -

     
    -$$ -\boldsymbol{x}_i = (x_1,x_2,\cdots,x_{i-1},x_{i+1},\cdots,x_n), -$$ -

     
    - -

    -which equals the vector \( \boldsymbol{x} \) with the exception that observation -number \( i \) is left out. Using this notation, define -\( \widehat{\beta}_i \) to be the estimator -\( \widehat{\beta} \) computed using \( \vec{X}_i \). -

    - - -
    -

    Jackknife code example

    -

    - - -

    from numpy import *
    -from numpy.random import randint, randn
    -from time import time
    -
    -def jackknife(data, stat):
    -    n = len(data);t = zeros(n); inds = arange(n); t0 = time()
    -    ## 'jackknifing' by leaving out an observation for each i                                                                                                                      
    -    for i in range(n):
    -        t[i] = stat(delete(data,i) )
    -
    -    # analysis                                                                                                                                                                     
    -    print("Runtime: %g sec" % (time()-t0)); print("Jackknife Statistics :")
    -    print("original           bias      std. error")
    -    print("%8g %14g %15g" % (stat(data),(n-1)*mean(t)/n, (n*var(t))**.5))
    -
    -    return t
    -
    -
    -# Returns mean of data samples                                                                                                                                                     
    -def stat(data):
    -    return mean(data)
    -
    -
    -mu, sigma = 100, 15
    -datapoints = 10000
    -x = mu + sigma*random.randn(datapoints)
    -# jackknife returns the data sample                                                                                                                                                
    -t = jackknife(x, stat)
    -
    -
    - - -
    -

    Resampling methods: Bootstrap

    -
    - -

    -Bootstrapping is a non-parametric approach to statistical inference -that substitutes computation for more traditional distributional -assumptions and asymptotic results. Bootstrapping offers a number of -advantages: - -

      -

    1. The bootstrap is quite general, although there are some cases in which it fails.
    2. - -

    3. Because it does not require distributional assumptions (such as normally distributed errors), the bootstrap can provide more accurate inferences when the data are not well behaved or when the sample size is small.
    4. - -

    5. It is possible to apply the bootstrap to statistics with sampling distributions that are difficult to derive, even asymptotically.
    6. -

    7. It is relatively simple to apply the bootstrap to complex data-collection plans (such as stratified and clustered samples).
    8. -
    -
    - -

    -The textbook by Davison on the Bootstrap Methods and their Applications provides many more insights and proofs. In this course we will take a more practical approach and use the results and theorems provided in the literature. For those interested in reading more about the bootstrap methods, we recommend the above text and the one by Efron and Tibshirani. - -

    -Before we proceed however, we need to remind ourselves about a central theorem in statistics, namely the so-called central limit theorem. -

    - - -
    -

    The Central Limit Theorem

    - -

    -Suppose we have a PDF \( p(x) \) from which we generate a series \( N \) -of averages \( \langle x_i \rangle \). Each mean value \( \langle x_i \rangle \) -is viewed as the average of a specific measurement, e.g., throwing -dice 100 times and then taking the average value, or producing a certain -amount of random numbers. -For notational ease, we set \( \langle x_i \rangle=x_i \) in the discussion -which follows. - -

    -If we compute the mean \( z \) of \( m \) such mean values \( x_i \) - -

     
    -$$ - z=\frac{x_1+x_2+\dots+x_m}{m}, -$$ -

     
    - -the question we pose is which is the PDF of the new variable \( z \). -

    - - -
    -

    Finding the Limit

    - -

    -The probability of obtaining an average value \( z \) is the product of the -probabilities of obtaining arbitrary individual mean values \( x_i \), -but with the constraint that the average is \( z \). We can express this through -the following expression -

     
    -$$ - \tilde{p}(z)=\int dx_1p(x_1)\int dx_2p(x_2)\dots\int dx_mp(x_m) - \delta(z-\frac{x_1+x_2+\dots+x_m}{m}), -$$ -

     
    - -where the \( \delta \)-function enbodies the constraint that the mean is \( z \). -All measurements that lead to each individual \( x_i \) are expected to -be independent, which in turn means that we can express \( \tilde{p} \) as the -product of individual \( p(x_i) \). The independence assumption is important in the derivation of the central limit theorem. -

    - - -
    -

    Rewriting the \( \delta \)-function

    - -

    -If we use the integral expression for the \( \delta \)-function - -

     
    -$$ - \delta(z-\frac{x_1+x_2+\dots+x_m}{m})=\frac{1}{2\pi}\int_{-\infty}^{\infty} - dq\exp{\left(iq(z-\frac{x_1+x_2+\dots+x_m}{m})\right)}, -$$ -

     
    - -and inserting \( e^{i\mu q-i\mu q} \) where \( \mu \) is the mean value -we arrive at -

     
    -$$ - \tilde{p}(z)=\frac{1}{2\pi}\int_{-\infty}^{\infty} - dq\exp{\left(iq(z-\mu)\right)}\left[\int_{-\infty}^{\infty} - dxp(x)\exp{\left(iq(\mu-x)/m\right)}\right]^m, -$$ -

     
    - -with the integral over \( x \) resulting in - -

     
    -$$ - \int_{-\infty}^{\infty}dxp(x)\exp{\left(iq(\mu-x)/m\right)}= - \int_{-\infty}^{\infty}dxp(x) - \left[1+\frac{iq(\mu-x)}{m}-\frac{q^2(\mu-x)^2}{2m^2}+\dots\right]. -$$ -

     
    -

    - - -
    -

    Identifying Terms

    - -

    -The second term on the rhs disappears since this is just the mean and -employing the definition of \( \sigma^2 \) we have -

     
    -$$ - \int_{-\infty}^{\infty}dxp(x)e^{\left(iq(\mu-x)/m\right)}= - 1-\frac{q^2\sigma^2}{2m^2}+\dots, -$$ -

     
    - -resulting in - -

     
    -$$ - \left[\int_{-\infty}^{\infty}dxp(x)\exp{\left(iq(\mu-x)/m\right)}\right]^m\approx - \left[1-\frac{q^2\sigma^2}{2m^2}+\dots \right]^m, -$$ -

     
    - -and in the limit \( m\rightarrow \infty \) we obtain - -

     
    -$$ - \tilde{p}(z)=\frac{1}{\sqrt{2\pi}(\sigma/\sqrt{m})} - \exp{\left(-\frac{(z-\mu)^2}{2(\sigma/\sqrt{m})^2}\right)}, -$$ -

     
    - -which is the normal distribution with variance -\( \sigma^2_m=\sigma^2/m \), where \( \sigma \) is the variance of the PDF \( p(x) \) -and \( \mu \) is also the mean of the PDF \( p(x) \). -

    - - -
    -

    Wrapping it up

    - -

    -Thus, the central limit theorem states that the PDF \( \tilde{p}(z) \) of -the average of \( m \) random values corresponding to a PDF \( p(x) \) -is a normal distribution whose mean is the -mean value of the PDF \( p(x) \) and whose variance is the variance -of the PDF \( p(x) \) divided by \( m \), the number of values used to compute \( z \). - -

    -The theorem is satisfied by a large class of PDFs. Note however that for a -finite \( m \), it is not always possible to find a closed expression for -\( \tilde{p}(x) \). -The central limit theorem leads then to the well-known expression for the -standard deviation, given by - -

     
    -$$ - \sigma_m= -\frac{\sigma}{\sqrt{m}}. -$$ -

     
    - -

    -The latter is true only if the average value is known exactly. This is obtained in the limit -\( m\rightarrow \infty \) only. Because the mean and the variance are measured quantities we obtain -the familiar expression in statistics -

     
    -$$ - \sigma_m\approx -\frac{\sigma}{\sqrt{m-1}}. -$$ -

     
    - -

    -In many cases however the above estimate for the standard deviation, -in particular if correlations are strong, may be too simplistic. -

    - - -
    -

    Confidence Intervals

    -
    - - -
    -

    Resampling methods: Bootstrap background

    - -

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

    - - -
    -

    Resampling methods: More Bootstrap background

    - -

    -In the case that \( \widehat{\beta} \) has -more than one component, and the components are independent, we use the -same estimator on each component separately. If the probability -density function of \( X_i \), \( p(x) \), had been known, then it would have -been straightforward to do this by: - -

      -

    1. Drawing lots of numbers from \( p(x) \), suppose we call one such set of numbers \( (X_1^*, X_2^*, \cdots, X_n^*) \).
    2. -

    3. Then using these numbers, we could compute a replica of \( \widehat{\beta} \) called \( \widehat{\beta}^* \).
    4. -
    -

    - -By repeated use of the above two points, many -estimates of \( \widehat{\beta} \) can be obtained. The -idea is to use the relative frequency of \( \widehat{\beta}^* \) -(think of a histogram) as an estimate of \( p(\boldsymbol{t}) \). -

    - - -
    -

    Resampling methods: Bootstrap approach

    - -

    -But -unless there is enough information available about the process that -generated \( X_1,X_2,\cdots,X_n \), \( p(x) \) is in general -unknown. Therefore, Efron in 1979 asked the -question: What if we replace \( p(x) \) by the relative frequency -of the observation \( X_i \)? - -

    -If we draw observations in accordance with -the relative frequency of the observations, will we obtain the same -result in some asymptotic sense? The answer is yes. -

    - - -
    -

    Resampling methods: Bootstrap steps

    - -

    -The independent bootstrap works like this: - -

      -

    1. Draw with replacement \( n \) numbers for the observed variables \( \boldsymbol{x} = (x_1,x_2,\cdots,x_n) \).
    2. -

    3. Define a vector \( \boldsymbol{x}^* \) containing the values which were drawn from \( \boldsymbol{x} \).
    4. -

    5. Using the vector \( \boldsymbol{x}^* \) compute \( \widehat{\beta}^* \) by evaluating \( \widehat \beta \) under the observations \( \boldsymbol{x}^* \).
    6. -

    7. Repeat this process \( k \) times.
    8. -
    -

    - -When you are done, you can draw a histogram of the relative frequency -of \( \widehat \beta^* \). This is your estimate of the probability -distribution \( p(t) \). Using this probability distribution you can -estimate any statistics thereof. In principle you never draw the -histogram of the relative frequency of \( \widehat{\beta}^* \). Instead -you use the estimators corresponding to the statistic of interest. For -example, if you are interested in estimating the variance of \( \widehat -\beta \), apply the etsimator \( \widehat \sigma^2 \) to the values -\( \widehat \beta^* \). -

    - - -
    -

    Code example for the Bootstrap method

    - -

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

    - - -

    from numpy import *
    -from numpy.random import randint, randn
    -from time import time
    -import matplotlib.mlab as mlab
    -import matplotlib.pyplot as plt
    -
    -# Returns mean of bootstrap samples                                                                              # Alternatively, we can run it using Scikit-Learn's function resample                                            # See the examples below
    -
    -def statistics(data):
    -    return mean(data)
    -
    -
    -# Bootstrap algorithm
    -def bootstrap(data, statistic, R):
    -    t = zeros(R); n = len(data); inds = arange(n); t0 = time()
    -    # non-parametric bootstrap         
    -    for i in range(R):
    -        t[i] = statistic(data[randint(0,n,n)])
    -
    -    # analysis    
    -    print("Runtime: %g sec" % (time()-t0)); print("Bootstrap Statistics :")
    -    print("original           bias      std. error")
    -    print("%8g %8g %14g %15g" % (statistic(data), std(data),mean(t),std(t)))
    -    return t
    -
    -
    -mu, sigma = 100, 15
    -datapoints = 10000
    -x = mu + sigma*random.randn(datapoints)
    -# bootstrap returns the data sample                                    
    -t = bootstrap(x, statistics, datapoints)
    -
    -

    -We see that our new variance and from that the standard deviation, agrees with the central limit theorem. -

    - - -
    -

    Plotting the Histogram

    -

    - - -

    # the histogram of the bootstrapped  data                                                                                                    
    -n, binsboot, patches = plt.hist(t, 50, normed=1, facecolor='red', alpha=0.75)
    -
    -# add a 'best fit' line  
    -y = mlab.normpdf( binsboot, mean(t), std(t))
    -lt = plt.plot(binsboot, y, 'r--', linewidth=1)
    -plt.xlabel('Smarts')
    -plt.ylabel('Probability')
    -plt.axis([99.5, 100.6, 0, 3.0])
    -plt.grid(True)
    -
    -plt.show()
    -
    -
    - - -
    -

    The bias-variance tradeoff

    - -

    -We will discuss the bias-variance tradeoff in the context of -continuous predictions such as regression. However, many of the -intuitions and ideas discussed here also carry over to classification -tasks. Consider a dataset \( \mathcal{L} \) consisting of the data -\( \mathbf{X}_\mathcal{L}=\{(y_j, \boldsymbol{x}_j), j=0\ldots n-1\} \). - -

    -Let us assume that the true data is generated from a noisy model - -

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

     
    - -

    -where \( \epsilon \) is normally distributed with mean zero and standard deviation \( \sigma^2 \). - -

    -In our derivation of the ordinary least squares method we defined then -an approximation to the function \( f \) in terms of the parameters -\( \boldsymbol{\beta} \) and the design matrix \( \boldsymbol{X} \) which embody our model, -that is \( \boldsymbol{\tilde{y}}=\boldsymbol{X}\boldsymbol{\beta} \). - -

    -Thereafter we found the parameters \( \boldsymbol{\beta} \) by optimizing the means squared error via the so-called cost function -

     
    -$$ -C(\boldsymbol{X},\boldsymbol{\beta}) =\frac{1}{n}\sum_{i=0}^{n-1}(y_i-\tilde{y}_i)^2=\mathbb{E}\left[(\boldsymbol{y}-\boldsymbol{\tilde{y}})^2\right]. -$$ -

     
    - -

    -We can rewrite this as -

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

     
    - -

    -The three terms represent the square of the bias of the learning -method, which can be thought of as the error caused by the simplifying -assumptions built into the method. The second term represents the -variance of the chosen model and finally the last terms is variance of -the error \( \boldsymbol{\epsilon} \). - -

    -To derive this equation, we need to recall that the variance of \( \boldsymbol{y} \) and \( \boldsymbol{\epsilon} \) are both equal to \( \sigma^2 \). The mean value of \( \boldsymbol{\epsilon} \) is by definition equal to zero. Furthermore, the function \( f \) is not a stochastics variable, idem for \( \boldsymbol{\tilde{y}} \). -We use a more compact notation in terms of the expectation value -

     
    -$$ -\mathbb{E}\left[(\boldsymbol{y}-\boldsymbol{\tilde{y}})^2\right]=\mathbb{E}\left[(\boldsymbol{f}+\boldsymbol{\epsilon}-\boldsymbol{\tilde{y}})^2\right], -$$ -

     
    - -and adding and subtracting \( \mathbb{E}\left[\boldsymbol{\tilde{y}}\right] \) we get -

     
    -$$ -\mathbb{E}\left[(\boldsymbol{y}-\boldsymbol{\tilde{y}})^2\right]=\mathbb{E}\left[(\boldsymbol{f}+\boldsymbol{\epsilon}-\boldsymbol{\tilde{y}}+\mathbb{E}\left[\boldsymbol{\tilde{y}}\right]-\mathbb{E}\left[\boldsymbol{\tilde{y}}\right])^2\right], -$$ -

     
    - -which, using the abovementioned expectation values can be rewritten as -

     
    -$$ -\mathbb{E}\left[(\boldsymbol{y}-\boldsymbol{\tilde{y}})^2\right]=\mathbb{E}\left[(\boldsymbol{y}-\mathbb{E}\left[\boldsymbol{\tilde{y}}\right])^2\right]+\mathrm{Var}\left[\boldsymbol{\tilde{y}}\right]+\sigma^2, -$$ -

     
    - -that is the rewriting in terms of the so-called bias, the variance of the model \( \boldsymbol{\tilde{y}} \) and the variance of \( \boldsymbol{\epsilon} \). -

    - - -
    -

    A way to Read the Bias-Variance Tradeoff

    - -

    -



    -
    - - -
    -

    Example code for Bias-Variance tradeoff

    -

    - - -

    import matplotlib.pyplot as plt
    -import numpy as np
    -from sklearn.linear_model import LinearRegression, Ridge, Lasso
    -from sklearn.preprocessing import PolynomialFeatures
    -from sklearn.model_selection import train_test_split
    -from sklearn.pipeline import make_pipeline
    -from sklearn.utils import resample
    -
    -np.random.seed(2018)
    -
    -n = 500
    -n_boostraps = 100
    -degree = 18  # A quite high value, just to show.
    -noise = 0.1
    -
    -# Make data set.
    -x = np.linspace(-1, 3, n).reshape(-1, 1)
    -y = np.exp(-x**2) + 1.5 * np.exp(-(x-2)**2) + np.random.normal(0, 0.1, x.shape)
    -
    -# Hold out some test data that is never used in training.
    -x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.2)
    -
    -# Combine x transformation and model into one operation.
    -# Not neccesary, but convenient.
    -model = make_pipeline(PolynomialFeatures(degree=degree), LinearRegression(fit_intercept=False))
    -
    -# The following (m x n_bootstraps) matrix holds the column vectors y_pred
    -# for each bootstrap iteration.
    -y_pred = np.empty((y_test.shape[0], n_boostraps))
    -for i in range(n_boostraps):
    -    x_, y_ = resample(x_train, y_train)
    -
    -    # Evaluate the new model on the same test data each time.
    -    y_pred[:, i] = model.fit(x_, y_).predict(x_test).ravel()
    -
    -# Note: Expectations and variances taken w.r.t. different training
    -# data sets, hence the axis=1. Subsequent means are taken across the test data
    -# set in order to obtain a total value, but before this we have error/bias/variance
    -# calculated per data point in the test set.
    -# Note 2: The use of keepdims=True is important in the calculation of bias as this 
    -# maintains the column vector form. Dropping this yields very unexpected results.
    -error = np.mean( np.mean((y_test - y_pred)**2, axis=1, keepdims=True) )
    -bias = np.mean( (y_test - np.mean(y_pred, axis=1, keepdims=True))**2 )
    -variance = np.mean( np.var(y_pred, axis=1, keepdims=True) )
    -print('Error:', error)
    -print('Bias^2:', bias)
    -print('Var:', variance)
    -print('{} >= {} + {} = {}'.format(error, bias, variance, bias+variance))
    -
    -plt.plot(x[::5, :], y[::5, :], label='f(x)')
    -plt.scatter(x_test, y_test, label='Data points')
    -plt.scatter(x_test, np.mean(y_pred, axis=1), label='Pred')
    -plt.legend()
    -plt.show()
    -
    -
    - - -
    -

    Understanding what happens

    -

    - - -

    import matplotlib.pyplot as plt
    -import numpy as np
    -from sklearn.linear_model import LinearRegression, Ridge, Lasso
    -from sklearn.preprocessing import PolynomialFeatures
    -from sklearn.model_selection import train_test_split
    -from sklearn.pipeline import make_pipeline
    -from sklearn.utils import resample
    -
    -np.random.seed(2018)
    -
    -n = 40
    -n_boostraps = 100
    -maxdegree = 14
    -
    -
    -# Make data set.
    -x = np.linspace(-3, 3, n).reshape(-1, 1)
    -y = np.exp(-x**2) + 1.5 * np.exp(-(x-2)**2)+ np.random.normal(0, 0.1, x.shape)
    -error = np.zeros(maxdegree)
    -bias = np.zeros(maxdegree)
    -variance = np.zeros(maxdegree)
    -polydegree = np.zeros(maxdegree)
    -x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.2)
    -
    -for degree in range(maxdegree):
    -    model = make_pipeline(PolynomialFeatures(degree=degree), LinearRegression(fit_intercept=False))
    -    y_pred = np.empty((y_test.shape[0], n_boostraps))
    -    for i in range(n_boostraps):
    -        x_, y_ = resample(x_train, y_train)
    -        y_pred[:, i] = model.fit(x_, y_).predict(x_test).ravel()
    -
    -    polydegree[degree] = degree
    -    error[degree] = np.mean( np.mean((y_test - y_pred)**2, axis=1, keepdims=True) )
    -    bias[degree] = np.mean( (y_test - np.mean(y_pred, axis=1, keepdims=True))**2 )
    -    variance[degree] = np.mean( np.var(y_pred, axis=1, keepdims=True) )
    -    print('Polynomial degree:', degree)
    -    print('Error:', error[degree])
    -    print('Bias^2:', bias[degree])
    -    print('Var:', variance[degree])
    -    print('{} >= {} + {} = {}'.format(error[degree], bias[degree], variance[degree], bias[degree]+variance[degree]))
    -
    -plt.plot(polydegree, error, label='Error')
    -plt.plot(polydegree, bias, label='bias')
    -plt.plot(polydegree, variance, label='Variance')
    -plt.legend()
    -plt.show()
    -
    -
    - - -
    -

    Summing up

    - -

    -The bias-variance tradeoff summarizes the fundamental tension in -machine learning, particularly supervised learning, between the -complexity of a model and the amount of training data needed to train -it. Since data is often limited, in practice it is often useful to -use a less-complex model with higher bias, that is a model whose asymptotic -performance is worse than another model because it is easier to -train and less sensitive to sampling noise arising from having a -finite-sized training dataset (smaller variance). - -

    -The above equations tell us that in -order to minimize the expected test error, we need to select a -statistical learning method that simultaneously achieves low variance -and low bias. Note that variance is inherently a nonnegative quantity, -and squared bias is also nonnegative. Hence, we see that the expected -test MSE can never lie below \( Var(\epsilon) \), the irreducible error. - -

    -What do we mean by the variance and bias of a statistical learning -method? The variance refers to the amount by which our model would change if we -estimated it using a different training data set. Since the training -data are used to fit the statistical learning method, different -training data sets will result in a different estimate. But ideally the -estimate for our model should not vary too much between training -sets. However, if a method has high variance then small changes in -the training data can result in large changes in the model. In general, more -flexible statistical methods have higher variance. - -

    -You may also find this recent article of interest. -

    - - -
    -

    Another Example from Scikit-Learn's Repository

    -

    - - -

    """
    -============================
    -Underfitting vs. Overfitting
    -============================
    -
    -This example demonstrates the problems of underfitting and overfitting and
    -how we can use linear regression with polynomial features to approximate
    -nonlinear functions. The plot shows the function that we want to approximate,
    -which is a part of the cosine function. In addition, the samples from the
    -real function and the approximations of different models are displayed. The
    -models have polynomial features of different degrees. We can see that a
    -linear function (polynomial with degree 1) is not sufficient to fit the
    -training samples. This is called **underfitting**. A polynomial of degree 4
    -approximates the true function almost perfectly. However, for higher degrees
    -the model will **overfit** the training data, i.e. it learns the noise of the
    -training data.
    -We evaluate quantitatively **overfitting** / **underfitting** by using
    -cross-validation. We calculate the mean squared error (MSE) on the validation
    -set, the higher, the less likely the model generalizes correctly from the
    -training data.
    -"""
    -
    -print(__doc__)
    -
    -import numpy as np
    -import matplotlib.pyplot as plt
    -from sklearn.pipeline import Pipeline
    -from sklearn.preprocessing import PolynomialFeatures
    -from sklearn.linear_model import LinearRegression
    -from sklearn.model_selection import cross_val_score
    -
    -
    -def true_fun(X):
    -    return np.cos(1.5 * np.pi * X)
    -
    -np.random.seed(0)
    -
    -n_samples = 30
    -degrees = [1, 4, 15]
    -
    -X = np.sort(np.random.rand(n_samples))
    -y = true_fun(X) + np.random.randn(n_samples) * 0.1
    -
    -plt.figure(figsize=(14, 5))
    -for i in range(len(degrees)):
    -    ax = plt.subplot(1, len(degrees), i + 1)
    -    plt.setp(ax, xticks=(), yticks=())
    -
    -    polynomial_features = PolynomialFeatures(degree=degrees[i],
    -                                             include_bias=False)
    -    linear_regression = LinearRegression()
    -    pipeline = Pipeline([("polynomial_features", polynomial_features),
    -                         ("linear_regression", linear_regression)])
    -    pipeline.fit(X[:, np.newaxis], y)
    -
    -    # Evaluate the models using crossvalidation
    -    scores = cross_val_score(pipeline, X[:, np.newaxis], y,
    -                             scoring="neg_mean_squared_error", cv=10)
    -
    -    X_test = np.linspace(0, 1, 100)
    -    plt.plot(X_test, pipeline.predict(X_test[:, np.newaxis]), label="Model")
    -    plt.plot(X_test, true_fun(X_test), label="True function")
    -    plt.scatter(X, y, edgecolor='b', s=20, label="Samples")
    -    plt.xlabel("x")
    -    plt.ylabel("y")
    -    plt.xlim((0, 1))
    -    plt.ylim((-2, 2))
    -    plt.legend(loc="best")
    -    plt.title("Degree {}\nMSE = {:.2e}(+/- {:.2e})".format(
    -        degrees[i], -scores.mean(), scores.std()))
    -plt.show()
    -
    -
    - - -
    -

    Various steps in cross-validation

    - -

    -When the repetitive splitting of the data set is done randomly, -samples may accidently end up in a fast majority of the splits in -either training or test set. Such samples may have an unbalanced -influence on either model building or prediction evaluation. To avoid -this \( k \)-fold cross-validation structures the data splitting. The -samples are divided into \( k \) more or less equally sized exhaustive and -mutually exclusive subsets. In turn (at each split) one of these -subsets plays the role of the test set while the union of the -remaining subsets constitutes the training set. Such a splitting -warrants a balanced representation of each sample in both training and -test set over the splits. Still the division into the \( k \) subsets -involves a degree of randomness. This may be fully excluded when -choosing \( k=n \). This particular case is referred to as leave-one-out -cross-validation (LOOCV). -

    - - -
    -

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

    - -
      -

    • Define a range of interest for the penalty parameter.
    • -

    • Divide the data set into training and test set comprising samples \( \{1, \ldots, n\} \setminus i \) and \( \{ i \} \), respectively.
    • -

    • Fit the linear regression model by means of ridge estimation for each \( \lambda \) in the grid using the training set, and the corresponding estimate of the error variance \( \boldsymbol{\sigma}_{-i}^2(\lambda) \), as
    • -
    -

     
    -$$ -\begin{align*} -\boldsymbol{\beta}_{-i}(\lambda) & = ( \boldsymbol{X}_{-i, \ast}^{T} -\boldsymbol{X}_{-i, \ast} + \lambda \boldsymbol{I}_{pp})^{-1} -\boldsymbol{X}_{-i, \ast}^{T} \boldsymbol{y}_{-i} -\end{align*} -$$ -

     
    - - -

      -

    • Evaluate the prediction performance of these models on the test set by \( \log\{L[y_i, \boldsymbol{X}_{i, \ast}; \boldsymbol{\beta}_{-i}(\lambda), \boldsymbol{\sigma}_{-i}^2(\lambda)]\} \). Or, by the prediction error \( |y_i - \boldsymbol{X}_{i, \ast} \boldsymbol{\beta}_{-i}(\lambda)| \), the relative error, the error squared or the R2 score function.
    • -

    • Repeat the first three steps such that each sample plays the role of the test set once.
    • -

    • Average the prediction performances of the test sets at each grid point of the penalty bias/parameter. It is an estimate of the prediction performance of the model corresponding to this value of the penalty parameter on novel data. It is defined as
    • -
    -

     
    -$$ -\begin{align*} -\frac{1}{n} \sum_{i = 1}^n \log\{L[y_i, \mathbf{X}_{i, \ast}; \boldsymbol{\beta}_{-i}(\lambda), \boldsymbol{\sigma}_{-i}^2(\lambda)]\}. -\end{align*} -$$ -

     
    -

    - - -
    -

    Cross-validation in brief

    - -

    -For the various values of \( k \) - -

      -

    1. shuffle the dataset randomly.
    2. -

    3. Split the dataset into \( k \) groups.
    4. -

    5. For each unique group: - -
        -

      1. Decide which group to use as set for test data
      2. -

      3. Take the remaining groups as a training data set
      4. -

      5. Fit a model on the training set and evaluate it on the test set
      6. -

      7. Retain the evaluation score and discard the model
      8. -
      -

    6. Summarize the model using the sample of model evaluation scores
    7. -
    -
    - - -
    -

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

    - -

    -The code here uses Ridge regression with cross-validation (CV) resampling and \( k \)-fold CV in order to fit a specific polynomial. -

    - - -

    import numpy as np
    -import matplotlib.pyplot as plt
    -from sklearn.model_selection import KFold
    -from sklearn.linear_model import Ridge
    -from sklearn.model_selection import cross_val_score
    -from sklearn.preprocessing import PolynomialFeatures
    -
    -# A seed just to ensure that the random numbers are the same for every run.
    -# Useful for eventual debugging.
    -np.random.seed(3155)
    -
    -# Generate the data.
    -nsamples = 100
    -x = np.random.randn(nsamples)
    -y = 3*x**2 + np.random.randn(nsamples)
    -
    -## Cross-validation on Ridge regression using KFold only
    -
    -# Decide degree on polynomial to fit
    -poly = PolynomialFeatures(degree = 6)
    -
    -# Decide which values of lambda to use
    -nlambdas = 500
    -lambdas = np.logspace(-3, 5, nlambdas)
    -
    -# Initialize a KFold instance
    -k = 5
    -kfold = KFold(n_splits = k)
    -
    -# Perform the cross-validation to estimate MSE
    -scores_KFold = np.zeros((nlambdas, k))
    -
    -i = 0
    -for lmb in lambdas:
    -    ridge = Ridge(alpha = lmb)
    -    j = 0
    -    for train_inds, test_inds in kfold.split(x):
    -        xtrain = x[train_inds]
    -        ytrain = y[train_inds]
    -
    -        xtest = x[test_inds]
    -        ytest = y[test_inds]
    -
    -        Xtrain = poly.fit_transform(xtrain[:, np.newaxis])
    -        ridge.fit(Xtrain, ytrain[:, np.newaxis])
    -
    -        Xtest = poly.fit_transform(xtest[:, np.newaxis])
    -        ypred = ridge.predict(Xtest)
    -
    -        scores_KFold[i,j] = np.sum((ypred - ytest[:, np.newaxis])**2)/np.size(ypred)
    -
    -        j += 1
    -    i += 1
    -
    -
    -estimated_mse_KFold = np.mean(scores_KFold, axis = 1)
    -
    -## Cross-validation using cross_val_score from sklearn along with KFold
    -
    -# kfold is an instance initialized above as:
    -# kfold = KFold(n_splits = k)
    -
    -estimated_mse_sklearn = np.zeros(nlambdas)
    -i = 0
    -for lmb in lambdas:
    -    ridge = Ridge(alpha = lmb)
    -
    -    X = poly.fit_transform(x[:, np.newaxis])
    -    estimated_mse_folds = cross_val_score(ridge, X, y[:, np.newaxis], scoring='neg_mean_squared_error', cv=kfold)
    -
    -    # cross_val_score return an array containing the estimated negative mse for every fold.
    -    # we have to the the mean of every array in order to get an estimate of the mse of the model
    -    estimated_mse_sklearn[i] = np.mean(-estimated_mse_folds)
    -
    -    i += 1
    -
    -## Plot and compare the slightly different ways to perform cross-validation
    -
    -plt.figure()
    -
    -plt.plot(np.log10(lambdas), estimated_mse_sklearn, label = 'cross_val_score')
    -plt.plot(np.log10(lambdas), estimated_mse_KFold, 'r--', label = 'KFold')
    -
    -plt.xlabel('log10(lambda)')
    -plt.ylabel('mse')
    -
    -plt.legend()
    -
    -plt.show()
    -
    -
    - - -
    -

    More examples on bootstrap and cross-validation and errors

    - -

    - - -

    # Common imports
    -import os
    -import numpy as np
    -import pandas as pd
    -import matplotlib.pyplot as plt
    -from sklearn.linear_model import LinearRegression, Ridge, Lasso
    -from sklearn.model_selection import train_test_split
    -from sklearn.utils import resample
    -from sklearn.metrics import mean_squared_error
    -# Where to save the figures and data files
    -PROJECT_ROOT_DIR = "Results"
    -FIGURE_ID = "Results/FigureFiles"
    -DATA_ID = "DataFiles/"
    -
    -if not os.path.exists(PROJECT_ROOT_DIR):
    -    os.mkdir(PROJECT_ROOT_DIR)
    -
    -if not os.path.exists(FIGURE_ID):
    -    os.makedirs(FIGURE_ID)
    -
    -if not os.path.exists(DATA_ID):
    -    os.makedirs(DATA_ID)
    -
    -def image_path(fig_id):
    -    return os.path.join(FIGURE_ID, fig_id)
    -
    -def data_path(dat_id):
    -    return os.path.join(DATA_ID, dat_id)
    -
    -def save_fig(fig_id):
    -    plt.savefig(image_path(fig_id) + ".png", format='png')
    -
    -infile = open(data_path("EoS.csv"),'r')
    -
    -# Read the EoS data as  csv file and organize the data into two arrays with density and energies
    -EoS = pd.read_csv(infile, names=('Density', 'Energy'))
    -EoS['Energy'] = pd.to_numeric(EoS['Energy'], errors='coerce')
    -EoS = EoS.dropna()
    -Energies = EoS['Energy']
    -Density = EoS['Density']
    -#  The design matrix now as function of various polytrops
    -
    -Maxpolydegree = 30
    -X = np.zeros((len(Density),Maxpolydegree))
    -X[:,0] = 1.0
    -testerror = np.zeros(Maxpolydegree)
    -trainingerror = np.zeros(Maxpolydegree)
    -polynomial = np.zeros(Maxpolydegree)
    -
    -trials = 100
    -for polydegree in range(1, Maxpolydegree):
    -    polynomial[polydegree] = polydegree
    -    for degree in range(polydegree):
    -        X[:,degree] = Density**(degree/3.0)
    -
    -# loop over trials in order to estimate the expectation value of the MSE
    -    testerror[polydegree] = 0.0
    -    trainingerror[polydegree] = 0.0
    -    for samples in range(trials):
    -        x_train, x_test, y_train, y_test = train_test_split(X, Energies, test_size=0.2)
    -        model = LinearRegression(fit_intercept=True).fit(x_train, y_train)
    -        ypred = model.predict(x_train)
    -        ytilde = model.predict(x_test)
    -        testerror[polydegree] += mean_squared_error(y_test, ytilde)
    -        trainingerror[polydegree] += mean_squared_error(y_train, ypred) 
    -
    -    testerror[polydegree] /= trials
    -    trainingerror[polydegree] /= trials
    -    print("Degree of polynomial: %3d"% polynomial[polydegree])
    -    print("Mean squared error on training data: %.8f" % trainingerror[polydegree])
    -    print("Mean squared error on test data: %.8f" % testerror[polydegree])
    -
    -plt.plot(polynomial, np.log10(trainingerror), label='Training Error')
    -plt.plot(polynomial, np.log10(testerror), label='Test Error')
    -plt.xlabel('Polynomial degree')
    -plt.ylabel('log10[MSE]')
    -plt.legend()
    -plt.show()
    -
    -
    - - -
    -

    The same example but now with cross-validation

    - -

    - - -

    # Common imports
    -import os
    -import numpy as np
    -import pandas as pd
    -import matplotlib.pyplot as plt
    -from sklearn.linear_model import LinearRegression, Ridge, Lasso
    -from sklearn.metrics import mean_squared_error
    -from sklearn.model_selection import KFold
    -from sklearn.model_selection import cross_val_score
    -
    -
    -# Where to save the figures and data files
    -PROJECT_ROOT_DIR = "Results"
    -FIGURE_ID = "Results/FigureFiles"
    -DATA_ID = "DataFiles/"
    -
    -if not os.path.exists(PROJECT_ROOT_DIR):
    -    os.mkdir(PROJECT_ROOT_DIR)
    -
    -if not os.path.exists(FIGURE_ID):
    -    os.makedirs(FIGURE_ID)
    -
    -if not os.path.exists(DATA_ID):
    -    os.makedirs(DATA_ID)
    -
    -def image_path(fig_id):
    -    return os.path.join(FIGURE_ID, fig_id)
    -
    -def data_path(dat_id):
    -    return os.path.join(DATA_ID, dat_id)
    -
    -def save_fig(fig_id):
    -    plt.savefig(image_path(fig_id) + ".png", format='png')
    -
    -infile = open(data_path("EoS.csv"),'r')
    -
    -# Read the EoS data as  csv file and organize the data into two arrays with density and energies
    -EoS = pd.read_csv(infile, names=('Density', 'Energy'))
    -EoS['Energy'] = pd.to_numeric(EoS['Energy'], errors='coerce')
    -EoS = EoS.dropna()
    -Energies = EoS['Energy']
    -Density = EoS['Density']
    -#  The design matrix now as function of various polytrops
    -
    -Maxpolydegree = 30
    -X = np.zeros((len(Density),Maxpolydegree))
    -X[:,0] = 1.0
    -estimated_mse_sklearn = np.zeros(Maxpolydegree)
    -polynomial = np.zeros(Maxpolydegree)
    -k =5
    -kfold = KFold(n_splits = k)
    -
    -for polydegree in range(1, Maxpolydegree):
    -    polynomial[polydegree] = polydegree
    -    for degree in range(polydegree):
    -        X[:,degree] = Density**(degree/3.0)
    -        OLS = LinearRegression()
    -# loop over trials in order to estimate the expectation value of the MSE
    -    estimated_mse_folds = cross_val_score(OLS, X, Energies, scoring='neg_mean_squared_error', cv=kfold)
    -#[:, np.newaxis]
    -    estimated_mse_sklearn[polydegree] = np.mean(-estimated_mse_folds)
    -
    -plt.plot(polynomial, np.log10(estimated_mse_sklearn), label='Test Error')
    -plt.xlabel('Polynomial degree')
    -plt.ylabel('log10[MSE]')
    -plt.legend()
    -plt.show()
    -
    -
    - - -
    -

    Cross-validation with Ridge

    -

    - - -

    import numpy as np
    -import matplotlib.pyplot as plt
    -from sklearn.model_selection import KFold
    -from sklearn.linear_model import Ridge
    -from sklearn.model_selection import cross_val_score
    -from sklearn.preprocessing import PolynomialFeatures
    -
    -# A seed just to ensure that the random numbers are the same for every run.
    -np.random.seed(3155)
    -# Generate the data.
    -n = 100
    -x = np.linspace(-3, 3, n).reshape(-1, 1)
    -y = np.exp(-x**2) + 1.5 * np.exp(-(x-2)**2)+ np.random.normal(0, 0.1, x.shape)
    -# Decide degree on polynomial to fit
    -poly = PolynomialFeatures(degree = 10)
    -
    -# Decide which values of lambda to use
    -nlambdas = 500
    -lambdas = np.logspace(-3, 5, nlambdas)
    -# Initialize a KFold instance
    -k = 5
    -kfold = KFold(n_splits = k)
    -estimated_mse_sklearn = np.zeros(nlambdas)
    -i = 0
    -for lmb in lambdas:
    -    ridge = Ridge(alpha = lmb)
    -    estimated_mse_folds = cross_val_score(ridge, x, y, scoring='neg_mean_squared_error', cv=kfold)
    -    estimated_mse_sklearn[i] = np.mean(-estimated_mse_folds)
    -    i += 1
    -plt.figure()
    -plt.plot(np.log10(lambdas), estimated_mse_sklearn, label = 'cross_val_score')
    -plt.xlabel('log10(lambda)')
    -plt.ylabel('MSE')
    -plt.legend()
    -plt.show()
    -
    -
    - - - -
    -
    - - - - - - - - - - - - diff --git a/doc/src/week37/week37-solarized.html b/doc/src/week37/week37-solarized.html deleted file mode 100644 index ead40591c..000000000 --- a/doc/src/week37/week37-solarized.html +++ /dev/null @@ -1,1937 +0,0 @@ - - - - - - - - -Week 37: Summary of Ridge and Lasso Regression and Resampling Methods - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

    Week 37: Summary of Ridge and Lasso Regression and Resampling Methods

    - -

    - - -

    -Morten Hjorth-Jensen [1, 2] -
    - -

    - - -

    [1] Department of Physics, University of Oslo
    -
    [2] Department of Physics and Astronomy and National Superconducting Cyclotron Laboratory, Michigan State University
    -
    -

    -

    Sep 16, 2021

    -
    -

    -









    - -

    Plans for week 37

    - -
      -
    • Thursday September 16: Summary of Ridge and Lasso with examples and start resampling techniques
    • -
    • Friday September 17: Resampling methods, Cross-validation, Bootstrapping and jackknife
    • -
    - -Recommended Reading: - -
      -
    1. Lectures on Resampling methods (these lectures)
    2. -
    3. Bishop 1.3 (cross-validation) and 3.2 (bias-variance tradeoff)
    4. -
    5. Hastie et al Chapter 7, here we recommend 7.1-7.5 and 7.10 (cross-validation) and 7.11 (bootstrap). This chapter is better than Bishop's on these topics. Goodfellow et al discuss this in a superficial way in sections 5.2-5.5.
    6. -
    - -









    - -

    Thursday September 16, Summary of Ridge and Lasso Regression and start Resampling methods

    - -

    -









    - -

    Deriving OLS from a probability distribution

    - -

    -Our basic assumption when we derived the OLS equations was to assume -that our output is determined by a given continuous function -\( f(\boldsymbol{x}) \) and a random noise \( \boldsymbol{\epsilon} \) given by the normal -distribution with zero mean value and an undetermined variance -\( \sigma^2 \). - -

    -We found above that the outputs \( \boldsymbol{y} \) have a mean value given by -\( \boldsymbol{X}\hat{\boldsymbol{\beta}} \) and variance \( \sigma^2 \). Since the entries to -the design matrix are not stochastic variables, we can assume that the -probability distribution of our targets is also a normal distribution -but now with mean value \( \boldsymbol{X}\hat{\boldsymbol{\beta}} \). This means that a -single output \( y_i \) is given by the Gaussian distribution - -$$ -y_i\sim \mathcal{N}(\boldsymbol{X}_{i,*}\boldsymbol{\beta}, \sigma^2)=\frac{1}{\sqrt{2\pi\sigma^2}}\exp{\left[-\frac{(y_i-\boldsymbol{X}_{i,*}\boldsymbol{\beta})^2}{2\sigma^2}\right]}. -$$ - -

    -









    - -

    Independent and Identically Distrubuted (iid)

    - -

    -We assume now that the various \( y_i \) values are stochastically distributed according to the above Gaussian distribution. -We define this distribution as -$$ -p(y_i, \boldsymbol{X}\vert\boldsymbol{\beta})=\frac{1}{\sqrt{2\pi\sigma^2}}\exp{\left[-\frac{(y_i-\boldsymbol{X}_{i,*}\boldsymbol{\beta})^2}{2\sigma^2}\right]}, -$$ - -which reads as finding the likelihood of an event \( y_i \) with the input variables \( \boldsymbol{X} \) given the parameters (to be determined) \( \boldsymbol{\beta} \). - -

    -Since these events are assumed to be independent and identicall distributed we can build the probability distribution function (PDF) for all possible event \( \boldsymbol{y} \) as the product of the single events, that is we have - -$$ -p(\boldsymbol{y},\boldsymbol{X}\vert\boldsymbol{\beta})=\prod_{i=0}^{n-1}\frac{1}{\sqrt{2\pi\sigma^2}}\exp{\left[-\frac{(y_i-\boldsymbol{X}_{i,*}\boldsymbol{\beta})^2}{2\sigma^2}\right]}=\prod_{i=0}^{n-1}p(y_i,\boldsymbol{X}\vert\boldsymbol{\beta}). -$$ - -

    -We will write this in a more compact form reserving \( \boldsymbol{D} \) for the domain of events, including the ouputs (targets) and the inputs. That is -in case we have a simple one-dimensional input and output case -$$ -\boldsymbol{D}=[(x_0,y_0), (x_1,y_1),\dots, (x_{n-1},y_{n-1})]. -$$ - -In the more general case the various inputs should be replaced by the possible features represented by the input data set \( \boldsymbol{X} \). -We can now rewrite the above probability as -$$ -p(\boldsymbol{D}\vert\boldsymbol{\beta})=\prod_{i=0}^{n-1}\frac{1}{\sqrt{2\pi\sigma^2}}\exp{\left[-\frac{(y_i-\boldsymbol{X}_{i,*}\boldsymbol{\beta})^2}{2\sigma^2}\right]}. -$$ - -

    -It is a conditional probability (see below) and reads as the likelihood of a domain of events \( \boldsymbol{D} \) given a set of parameters \( \boldsymbol{\beta} \). - -

    -









    - -

    Maximum Likelihood Estimation (MLE)

    - -

    -In statistics, maximum likelihood estimation (MLE) is a method of -estimating the parameters of an assumed probability distribution, -given some observed data. This is achieved by maximizing a likelihood -function so that, under the assumed statistical model, the observed -data is the most probable. - -

    -We will assume here that our events are given by the above Gaussian -distribution and we will determine the optimal parameters \( \beta \) by -maximizing the above PDF. However, computing the derivatives of a -product function is cumbersome and can easily lead to overflow and/or -underflowproblems, with potentials for loss of numerical precision. - -

    -In practice, it is more convenient to maximize the logarithm of the -PDF because it is a monotonically increasing function of the argument. -Alternatively, and this will be our option, we will minimize the -negative of the logarithm since this is a monotonically decreasing -function. - -

    -Note also that maximization/minimization of the logarithm of the PDF -is equivalent to the maximization/minimization of the function itself. - -

    -









    - -

    A new Cost Function

    - -

    -We could now define a new cost function to minimize, namely the negative logarithm of the above PDF - -$$ -C(\boldsymbol{\beta}=-\log{\prod_{i=0}^{n-1}p(y_i,\boldsymbol{X}\vert\boldsymbol{\beta})}=-\sum_{i=0}^{n-1}\log{p(y_i,\boldsymbol{X}\vert\boldsymbol{\beta})}, -$$ - -which becomes -$$ -C(\boldsymbol{\beta}=\frac{n}{2}\log{2\pi\sigma^2}+\frac{\vert\vert (\boldsymbol{y}-\boldsymbol{X}\boldsymbol{\beta})\vert\vert_2^2}{2\sigma^2}. -$$ - -

    -Taking the derivative of the new cost function with respect to the parameters \( \beta \) we recognize our familiar OLS equation, namely - -$$ -\boldsymbol{X}^T\left(\boldsymbol{y}-\boldsymbol{X}\boldsymbol{\beta}\right) =0, -$$ - -which leads to the well-known OLS equation for the optimal paramters \( \beta \) -$$ -\hat{\boldsymbol{\beta}}^{\mathrm{OLS}}=\left(\boldsymbol{X}^T\boldsymbol{X}\right)^{-1}\boldsymbol{X}^T\boldsymbol{y}! -$$ - -

    -









    - -

    Bayes' Theorem

    - -

    -If we combine the conditional probability with the marginal probability and the standard product rule, we have -$$ -p(X\vert Y)= \frac{p(X,Y)}{p(Y)}, -$$ - -which we can rewrite as - -$$ -p(X\vert Y)= \frac{p(X,Y)}{\sum_{i=0}^{n-1}p(Y\vert X=x_i)p(x_i)}=\frac{p(Y\vert X)p(X)}{\sum_{i=0}^{n-1}p(Y\vert X=x_i)p(x_i)}, -$$ - -which is Bayes' theorem. It allows us to evaluate the uncertainty in in \( X \) after we have observed \( Y \). We can easily interchange \( X \) with \( Y \). - -

    -









    - -

    Interpretations of Bayes' Theorem

    - -

    -The quantity \( p(Y\vert X) \) on the right-hand side of the theorem is -evaluated for the observed data \( Y \) and can be viewed as a function of -the parameter space represented by \( X \). This function is not -necesseraly normalized and is normally called the likelihood function. - -

    -The function \( p(X) \) on the right hand side is called the prior while the function on the left hand side is the called the posterior probability. The denominator on the right hand side serves as a normalization factor for the posterior distribution. - -

    -









    - -

    Test Function for what happens with OLS, Ridge and Lasso

    - -

    -We will play around with a study of the values for the optimal -parameters \( \boldsymbol{\beta} \) using OLS, Ridge and Lasso regression. For -OLS, you will notice as function of the noise and polynomial degree, -that the parameters \( \beta \) will fluctuate from order to order in the -polynomial fit and that for larger and larger polynomial degrees of freedom, the parameters will tend to increase in value for OLS. - -

    -For Ridge and Lasso regression, the higher order parameters will typically be reduced, providing thereby less fluctuations from one order to another one. - -

    - - -

    import numpy as np
    -import matplotlib.pyplot as plt
    -from sklearn.model_selection import train_test_split
    -from sklearn import linear_model
    -
    -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
    -
    -# Make data set.
    -n = 10000
    -x = np.random.rand(n)
    -y = np.exp(-x**2) + 1.5 * np.exp(-(x-2)**2)+ np.random.randn(n)
    -
    -Maxpolydegree = 5
    -X = np.zeros((len(x),Maxpolydegree))
    -X[:,0] = 1.0
    -
    -for polydegree in range(1, Maxpolydegree):
    -    for degree in range(polydegree):
    -        X[:,degree] = x**(degree)
    -
    -
    -# 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.pinv(X_train.T @ X_train) @ X_train.T @ y_train
    -print(OLSbeta)
    -ypredictOLS = X_test @ OLSbeta
    -print("Test MSE OLS")
    -print(MSE(y_test,ypredictOLS))
    -# Repeat now for Lasso and Ridge regression and various values of the regularization parameter using Scikit-Learn
    -# Decide which values of lambda to use
    -nlambdas = 4
    -MSERidgePredict = np.zeros(nlambdas)
    -MSELassoPredict = np.zeros(nlambdas)
    -lambdas = np.logspace(-3, 1, nlambdas)
    -for i in range(nlambdas):
    -    lmb = lambdas[i]
    -    # Make the fit using Ridge and Lasso
    -    RegRidge = linear_model.Ridge(lmb,fit_intercept=False)
    -    RegRidge.fit(X_train,y_train)
    -    RegLasso = linear_model.Lasso(lmb,fit_intercept=False)
    -    RegLasso.fit(X_train,y_train)
    -    # and then make the prediction
    -    ypredictRidge = RegRidge.predict(X_test)
    -    ypredictLasso = RegLasso.predict(X_test)
    -    # Compute the MSE and print it
    -    MSERidgePredict[i] = MSE(y_test,ypredictRidge)
    -    MSELassoPredict[i] = MSE(y_test,ypredictLasso)
    -    print(lmb,RegRidge.coef_)
    -    print(lmb,RegLasso.coef_)
    -# Now plot the results
    -plt.figure()
    -plt.plot(np.log10(lambdas), MSERidgePredict, 'b', label = 'MSE Ridge Test')
    -plt.plot(np.log10(lambdas), MSELassoPredict, 'r', label = 'MSE Lasso Test')
    -plt.xlabel('log10(lambda)')
    -plt.ylabel('MSE')
    -plt.legend()
    -plt.show()
    -
    -

    -How can we understand this? - -

    -









    - -

    Rerunning the above code

    - -

    -Let us write out the values of the coefficients \( \beta_i \) as functions -of the polynomial degree and noise. We will focus only on the Ridge -results and some few selected values of the hyperparameter \( \lambda \). - -

    -If we don't include any noise and run this code for different values -of the polynomial degree, we notice that the results for \( \beta_i \) do -not show great changes from one order to the next. This is an -indication that for higher polynomial orders, our parameters become -less important. - -

    -If we however add noise, what happens is that the polynomial fit is -trying to adjust the fit to traverse in the best possible way all data -points. This can lead to large fluctuations in the parameters -\( \beta_i \) as functions of polynomial order. It will also be reflected -in a larger value of the variance of each parameter \( \beta_i \). What -Ridge regression (and Lasso as well) are doing then is to try to -quench the fluctuations in the parameters of \( \beta_i \) which have a -large variance (normally for higher orders in the polynomial). - -

    - - -

    import numpy as np
    -import pandas as pd
    -from IPython.display import display
    -import matplotlib.pyplot as plt
    -from sklearn.model_selection import train_test_split
    -from sklearn import linear_model
    -
    -# Make data set.
    -n = 1000
    -x = np.random.rand(n)
    -y = np.exp(-x**2) + 1.5 * np.exp(-(x-2)**2)+ np.random.randn(n)
    -
    -Maxpolydegree = 5
    -X = np.zeros((len(x),Maxpolydegree))
    -X[:,0] = 1.0
    -
    -for polydegree in range(1, Maxpolydegree):
    -    for degree in range(polydegree):
    -        X[:,degree] = x**(degree)
    -
    -
    -# 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)
    -
    -# Decide which values of lambda to use
    -nlambdas = 5
    -lambdas = np.logspace(-3, 2, nlambdas)
    -for i in range(nlambdas):
    -    lmb = lambdas[i]
    -    # Make the fit using Ridge only
    -    RegRidge = linear_model.Ridge(lmb,fit_intercept=False)
    -    RegRidge.fit(X_train,y_train)
    -    # and then make the prediction
    -    ypredictRidge = RegRidge.predict(X_test)
    -    Coeffs = np.array(RegRidge.coef_)
    -    BetaValues = pd.DataFrame(Coeffs)
    -    BetaValues.columns = ['beta']
    -    display(BetaValues)    
    -
    -

    -









    - -

    Invoking Bayes' theorem

    - -

    -Using Bayes' theorem we can gain a better intuition about Ridge and Lasso regression. - -

    -For ordinary least squares we postulated that the maximum likelihood for the doamin of events \( \boldsymbol{D} \) (one-dimensional case) -$$ -\boldsymbol{D}=[(x_0,y_0), (x_1,y_1),\dots, (x_{n-1},y_{n-1})], -$$ - -is given by -$$ -p(\boldsymbol{D}\vert\boldsymbol{\beta})=\prod_{i=0}^{n-1}\frac{1}{\sqrt{2\pi\sigma^2}}\exp{\left[-\frac{(y_i-\boldsymbol{X}_{i,*}\boldsymbol{\beta})^2}{2\sigma^2}\right]}. -$$ - -

    -In Bayes' theorem this function plays the role of the so-called likelihood. We could now ask the question what is the posterior probability of a parameter set \( \boldsymbol{\beta} \) given a domain of events \( \boldsymbol{D} \)? That is, how can we define the posterior probability - -$$ -p(\boldsymbol{\beta}\vert\boldsymbol{D}). -$$ - -

    -Bayes' theorem comes to our rescue here since (omitting the normalization constant) -$$ -p(\boldsymbol{\beta}\vert\boldsymbol{D})\propto p(\boldsymbol{D}\vert\boldsymbol{\beta})p(\boldsymbol{\beta}). -$$ - -

    -We have a model for \( p(\boldsymbol{D}\vert\boldsymbol{\beta}) \) but need one for the prior \( p(\boldsymbol{\beta} \)! - -

    -









    - -

    Ridge and Bayes

    - -

    -With the posterior probability defined by a likelihood which we have -already modeled and an unknown prior, we are now ready to make -additional models for the prior. - -

    -We can, based on our discussions of the variance of \( \boldsymbol{\beta} \) and the mean value, assume that the prior for the values \( \boldsymbol{\beta} \) is given by a Gaussian with mean value zero and variance \( \tau^2 \), that is - -$$ -p(\boldsymbol{\beta})=\prod_{j=0}^{p-1}\exp{\left(-\frac{\beta_j^2}{2\tau^2}\right)}. -$$ - -

    -Our posterior probability becomes then (omitting the normalization factor which is just a constant) -$$ -p(\boldsymbol{\beta\vert\boldsymbol{D})}=\prod_{i=0}^{n-1}\frac{1}{\sqrt{2\pi\sigma^2}}\exp{\left[-\frac{(y_i-\boldsymbol{X}_{i,*}\boldsymbol{\beta})^2}{2\sigma^2}\right]}\prod_{j=0}^{p-1}\exp{\left(-\frac{\beta_j^2}{2\tau^2}\right)}. -$$ - -

    -We can now optimize this quantity with respect to \( \boldsymbol{\beta} \). As we -did for OLS, this is most conveniently done by taking the negative -logarithm of the posterior probability. Doing so and leaving out the -constants terms that do not depend on \( \beta \), we have - -$$ -C(\boldsymbol{\beta})=\frac{\vert\vert (\boldsymbol{y}-\boldsymbol{X}\boldsymbol{\beta})\vert\vert_2^2}{2\sigma^2}+\frac{1}{2\tau^2}\vert\vert\boldsymbol{\beta}\vert\vert_2^2, -$$ - -and replacing \( 1/2\tau^2 \) with \( \lambda \) we have - -$$ -C(\boldsymbol{\beta})=\frac{\vert\vert (\boldsymbol{y}-\boldsymbol{X}\boldsymbol{\beta})\vert\vert_2^2}{2\sigma^2}+\lambda\vert\vert\boldsymbol{\beta}\vert\vert_2^2, -$$ - -which is our Ridge cost function! Nice, isn't it? - -

    -









    - -

    Lasso and Bayes

    - -

    -To derive the Lasso cost function, we simply replace the Gaussian prior with an exponential distribution (Laplace in this case) with zero mean value, that is - -$$ -p(\boldsymbol{\beta})=\prod_{j=0}^{p-1}\exp{\left(-\frac{\vert\beta_j\vert}{\tau}\right)}. -$$ - -

    -Our posterior probability becomes then (omitting the normalization factor which is just a constant) -$$ -p(\boldsymbol{\beta}\vert\boldsymbol{D})=\prod_{i=0}^{n-1}\frac{1}{\sqrt{2\pi\sigma^2}}\exp{\left[-\frac{(y_i-\boldsymbol{X}_{i,*}\boldsymbol{\beta})^2}{2\sigma^2}\right]}\prod_{j=0}^{p-1}\exp{\left(-\frac{\vert\beta_j\vert}{\tau}\right)}. -$$ - -

    -Taking the negative -logarithm of the posterior probability and leaving out the -constants terms that do not depend on \( \beta \), we have - -$$ -C(\boldsymbol{\beta}=\frac{\vert\vert (\boldsymbol{y}-\boldsymbol{X}\boldsymbol{\beta})\vert\vert_2^2}{2\sigma^2}+\frac{1}{\tau}\vert\vert\boldsymbol{\beta}\vert\vert_1, -$$ - -and replacing \( 1/\tau \) with \( \lambda \) we have - -$$ -C(\boldsymbol{\beta}=\frac{\vert\vert (\boldsymbol{y}-\boldsymbol{X}\boldsymbol{\beta})\vert\vert_2^2}{2\sigma^2}+\lambda\vert\vert\boldsymbol{\beta}\vert\vert_1, -$$ - -which is our Lasso cost function! - -

    -









    - -

    Why resampling methods

    - -

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

      -
    1. look at statistical properties, including a discussion of mean values, variance and the so-called bias-variance tradeoff
    2. -
    3. introduce resampling techniques like cross-validation, bootstrapping and jackknife and more
    4. -
    - -and discuss how to select a given model (one of the difficult parts in machine learning). - -

    -









    - -

    Resampling methods

    -
    - -

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

    -Two resampling methods are often used in Machine Learning analyses, - -

      -
    1. The bootstrap method
    2. -
    3. and Cross-Validation
    4. -
    - -In addition there are several other methods such as the Jackknife and the Blocking methods. We will discuss in particular -cross-validation and the bootstrap method. - - -
    - - -

    -









    - -

    Resampling approaches can be computationally expensive

    -
    - -

    - -

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

    - - -

    -









    - -

    Why resampling methods ?

    -
    -Statistical analysis -

    - -

      -
    • Our simulations can be treated as computer experiments. This is particularly the case for Monte Carlo methods which are widely used in statistical analyses.
    • -
    • The results can be analysed with the same statistical tools as we would use when analysing experimental data.
    • -
    • As in all experiments, we are looking for expectation values and an estimate of how accurate they are, i.e., possible sources for errors.
    • -
    -
    - - -

    -









    - -

    Statistical analysis

    -
    - -

    - -

      -
    • As in other experiments, many numerical experiments have two classes of errors:
    • - -
        -
      • Statistical errors
      • -
      • Systematical errors
      • -
      - -
    • Statistical errors can be estimated using standard tools from statistics
    • -
    • Systematical errors are method specific and must be treated differently from case to case.
    • -
    -
    - - -

    -









    - -

    Resampling methods

    - -

    -With all these analytical equations for both the OLS and Ridge -regression, we will now outline how to assess a given model. This will -lead to a discussion of the so-called bias-variance tradeoff (see -below) and so-called resampling methods. - -

    -One of the quantities we have discussed as a way to measure errors is -the mean-squared error (MSE), mainly used for fitting of continuous -functions. Another choice is the absolute error. - -

    -In the discussions below we will focus on the MSE and in particular since we will split the data into test and training data, -we discuss the - -

      -
    1. prediction error or simply the test error \( \mathrm{Err_{Test}} \), where we have a fixed training set and the test error is the MSE arising from the data reserved for testing. We discuss also the
    2. -
    3. training error \( \mathrm{Err_{Train}} \), which is the average loss over the training data.
    4. -
    - -As our model becomes more and more complex, more of the training data tends to used. The training may thence adapt to more complicated structures in the data. This may lead to a decrease in the bias (see below for code example) and a slight increase of the variance for the test error. -For a certain level of complexity the test error will reach minimum, before starting to increase again. The -training error reaches a saturation. - -

    -









    - -

    Resampling methods: Jackknife and Bootstrap

    - -

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

    -The jackknife is a special case of the independent bootstrap. Still, the jackknife was made -popular prior to the independent bootstrap. And as the popularity of -the independent bootstrap soared, new variants, such as the dependent bootstrap have also been developed.. - -

    -The Jackknife and independent bootstrap work for -independent, identically distributed random variables. -If these conditions are not -satisfied, the methods will fail. Yet, it should be said that if the data are -independent, identically distributed, and we only want to estimate the -variance of \( \overline{X} \) (which often is the case), then there is no -need for bootstrapping. - -

    -









    - -

    Resampling methods: Jackknife

    - -

    -The Jackknife works by making many replicas of the estimator \( \widehat{\beta} \). -The jackknife is a resampling method where we systematically leave out one observation from the vector of observed values \( \boldsymbol{x} = (x_1,x_2,\cdots,X_n) \). -Let \( \boldsymbol{x}_i \) denote the vector -$$ -\boldsymbol{x}_i = (x_1,x_2,\cdots,x_{i-1},x_{i+1},\cdots,x_n), -$$ - -

    -which equals the vector \( \boldsymbol{x} \) with the exception that observation -number \( i \) is left out. Using this notation, define -\( \widehat{\beta}_i \) to be the estimator -\( \widehat{\beta} \) computed using \( \vec{X}_i \). - -

    -









    - -

    Jackknife code example

    -

    - - -

    from numpy import *
    -from numpy.random import randint, randn
    -from time import time
    -
    -def jackknife(data, stat):
    -    n = len(data);t = zeros(n); inds = arange(n); t0 = time()
    -    ## 'jackknifing' by leaving out an observation for each i                                                                                                                      
    -    for i in range(n):
    -        t[i] = stat(delete(data,i) )
    -
    -    # analysis                                                                                                                                                                     
    -    print("Runtime: %g sec" % (time()-t0)); print("Jackknife Statistics :")
    -    print("original           bias      std. error")
    -    print("%8g %14g %15g" % (stat(data),(n-1)*mean(t)/n, (n*var(t))**.5))
    -
    -    return t
    -
    -
    -# Returns mean of data samples                                                                                                                                                     
    -def stat(data):
    -    return mean(data)
    -
    -
    -mu, sigma = 100, 15
    -datapoints = 10000
    -x = mu + sigma*random.randn(datapoints)
    -# jackknife returns the data sample                                                                                                                                                
    -t = jackknife(x, stat)
    -
    -

    -









    - -

    Resampling methods: Bootstrap

    -
    - -

    -Bootstrapping is a non-parametric approach to statistical inference -that substitutes computation for more traditional distributional -assumptions and asymptotic results. Bootstrapping offers a number of -advantages: - -

      -
    1. The bootstrap is quite general, although there are some cases in which it fails.
    2. -
    3. Because it does not require distributional assumptions (such as normally distributed errors), the bootstrap can provide more accurate inferences when the data are not well behaved or when the sample size is small.
    4. -
    5. It is possible to apply the bootstrap to statistics with sampling distributions that are difficult to derive, even asymptotically.
    6. -
    7. It is relatively simple to apply the bootstrap to complex data-collection plans (such as stratified and clustered samples).
    8. -
    -
    - - -

    -The textbook by Davison on the Bootstrap Methods and their Applications provides many more insights and proofs. In this course we will take a more practical approach and use the results and theorems provided in the literature. For those interested in reading more about the bootstrap methods, we recommend the above text and the one by Efron and Tibshirani. - -

    -Before we proceed however, we need to remind ourselves about a central theorem in statistics, namely the so-called central limit theorem. - -

    -









    - -

    The Central Limit Theorem

    - -

    -Suppose we have a PDF \( p(x) \) from which we generate a series \( N \) -of averages \( \langle x_i \rangle \). Each mean value \( \langle x_i \rangle \) -is viewed as the average of a specific measurement, e.g., throwing -dice 100 times and then taking the average value, or producing a certain -amount of random numbers. -For notational ease, we set \( \langle x_i \rangle=x_i \) in the discussion -which follows. - -

    -If we compute the mean \( z \) of \( m \) such mean values \( x_i \) -$$ - z=\frac{x_1+x_2+\dots+x_m}{m}, -$$ - -the question we pose is which is the PDF of the new variable \( z \). - -

    -









    - -

    Finding the Limit

    - -

    -The probability of obtaining an average value \( z \) is the product of the -probabilities of obtaining arbitrary individual mean values \( x_i \), -but with the constraint that the average is \( z \). We can express this through -the following expression -$$ - \tilde{p}(z)=\int dx_1p(x_1)\int dx_2p(x_2)\dots\int dx_mp(x_m) - \delta(z-\frac{x_1+x_2+\dots+x_m}{m}), -$$ - -where the \( \delta \)-function enbodies the constraint that the mean is \( z \). -All measurements that lead to each individual \( x_i \) are expected to -be independent, which in turn means that we can express \( \tilde{p} \) as the -product of individual \( p(x_i) \). The independence assumption is important in the derivation of the central limit theorem. - -

    -









    - -

    Rewriting the \( \delta \)-function

    - -

    -If we use the integral expression for the \( \delta \)-function - -$$ - \delta(z-\frac{x_1+x_2+\dots+x_m}{m})=\frac{1}{2\pi}\int_{-\infty}^{\infty} - dq\exp{\left(iq(z-\frac{x_1+x_2+\dots+x_m}{m})\right)}, -$$ - -and inserting \( e^{i\mu q-i\mu q} \) where \( \mu \) is the mean value -we arrive at -$$ - \tilde{p}(z)=\frac{1}{2\pi}\int_{-\infty}^{\infty} - dq\exp{\left(iq(z-\mu)\right)}\left[\int_{-\infty}^{\infty} - dxp(x)\exp{\left(iq(\mu-x)/m\right)}\right]^m, -$$ - -with the integral over \( x \) resulting in - -$$ - \int_{-\infty}^{\infty}dxp(x)\exp{\left(iq(\mu-x)/m\right)}= - \int_{-\infty}^{\infty}dxp(x) - \left[1+\frac{iq(\mu-x)}{m}-\frac{q^2(\mu-x)^2}{2m^2}+\dots\right]. -$$ - -

    -









    - -

    Identifying Terms

    - -

    -The second term on the rhs disappears since this is just the mean and -employing the definition of \( \sigma^2 \) we have -$$ - \int_{-\infty}^{\infty}dxp(x)e^{\left(iq(\mu-x)/m\right)}= - 1-\frac{q^2\sigma^2}{2m^2}+\dots, -$$ - -resulting in - -$$ - \left[\int_{-\infty}^{\infty}dxp(x)\exp{\left(iq(\mu-x)/m\right)}\right]^m\approx - \left[1-\frac{q^2\sigma^2}{2m^2}+\dots \right]^m, -$$ - -and in the limit \( m\rightarrow \infty \) we obtain - -$$ - \tilde{p}(z)=\frac{1}{\sqrt{2\pi}(\sigma/\sqrt{m})} - \exp{\left(-\frac{(z-\mu)^2}{2(\sigma/\sqrt{m})^2}\right)}, -$$ - -which is the normal distribution with variance -\( \sigma^2_m=\sigma^2/m \), where \( \sigma \) is the variance of the PDF \( p(x) \) -and \( \mu \) is also the mean of the PDF \( p(x) \). - -

    -









    - -

    Wrapping it up

    - -

    -Thus, the central limit theorem states that the PDF \( \tilde{p}(z) \) of -the average of \( m \) random values corresponding to a PDF \( p(x) \) -is a normal distribution whose mean is the -mean value of the PDF \( p(x) \) and whose variance is the variance -of the PDF \( p(x) \) divided by \( m \), the number of values used to compute \( z \). - -

    -The theorem is satisfied by a large class of PDFs. Note however that for a -finite \( m \), it is not always possible to find a closed expression for -\( \tilde{p}(x) \). -The central limit theorem leads then to the well-known expression for the -standard deviation, given by - -$$ - \sigma_m= -\frac{\sigma}{\sqrt{m}}. -$$ - -

    -The latter is true only if the average value is known exactly. This is obtained in the limit -\( m\rightarrow \infty \) only. Because the mean and the variance are measured quantities we obtain -the familiar expression in statistics -$$ - \sigma_m\approx -\frac{\sigma}{\sqrt{m-1}}. -$$ - -

    -In many cases however the above estimate for the standard deviation, -in particular if correlations are strong, may be too simplistic. - -

    -









    - -

    Confidence Intervals

    - -

    -









    - -

    Resampling methods: Bootstrap background

    - -

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

    -









    - -

    Resampling methods: More Bootstrap background

    - -

    -In the case that \( \widehat{\beta} \) has -more than one component, and the components are independent, we use the -same estimator on each component separately. If the probability -density function of \( X_i \), \( p(x) \), had been known, then it would have -been straightforward to do this by: - -

      -
    1. Drawing lots of numbers from \( p(x) \), suppose we call one such set of numbers \( (X_1^*, X_2^*, \cdots, X_n^*) \).
    2. -
    3. Then using these numbers, we could compute a replica of \( \widehat{\beta} \) called \( \widehat{\beta}^* \).
    4. -
    - -By repeated use of the above two points, many -estimates of \( \widehat{\beta} \) can be obtained. The -idea is to use the relative frequency of \( \widehat{\beta}^* \) -(think of a histogram) as an estimate of \( p(\boldsymbol{t}) \). - -

    -









    - -

    Resampling methods: Bootstrap approach

    - -

    -But -unless there is enough information available about the process that -generated \( X_1,X_2,\cdots,X_n \), \( p(x) \) is in general -unknown. Therefore, Efron in 1979 asked the -question: What if we replace \( p(x) \) by the relative frequency -of the observation \( X_i \)? - -

    -If we draw observations in accordance with -the relative frequency of the observations, will we obtain the same -result in some asymptotic sense? The answer is yes. - -

    -









    - -

    Resampling methods: Bootstrap steps

    - -

    -The independent bootstrap works like this: - -

      -
    1. Draw with replacement \( n \) numbers for the observed variables \( \boldsymbol{x} = (x_1,x_2,\cdots,x_n) \).
    2. -
    3. Define a vector \( \boldsymbol{x}^* \) containing the values which were drawn from \( \boldsymbol{x} \).
    4. -
    5. Using the vector \( \boldsymbol{x}^* \) compute \( \widehat{\beta}^* \) by evaluating \( \widehat \beta \) under the observations \( \boldsymbol{x}^* \).
    6. -
    7. Repeat this process \( k \) times.
    8. -
    - -When you are done, you can draw a histogram of the relative frequency -of \( \widehat \beta^* \). This is your estimate of the probability -distribution \( p(t) \). Using this probability distribution you can -estimate any statistics thereof. In principle you never draw the -histogram of the relative frequency of \( \widehat{\beta}^* \). Instead -you use the estimators corresponding to the statistic of interest. For -example, if you are interested in estimating the variance of \( \widehat -\beta \), apply the etsimator \( \widehat \sigma^2 \) to the values -\( \widehat \beta^* \). - -

    -









    - -

    Code example for the Bootstrap method

    - -

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

    - - -

    from numpy import *
    -from numpy.random import randint, randn
    -from time import time
    -import matplotlib.mlab as mlab
    -import matplotlib.pyplot as plt
    -
    -# Returns mean of bootstrap samples                                                                              # Alternatively, we can run it using Scikit-Learn's function resample                                            # See the examples below
    -
    -def statistics(data):
    -    return mean(data)
    -
    -
    -# Bootstrap algorithm
    -def bootstrap(data, statistic, R):
    -    t = zeros(R); n = len(data); inds = arange(n); t0 = time()
    -    # non-parametric bootstrap         
    -    for i in range(R):
    -        t[i] = statistic(data[randint(0,n,n)])
    -
    -    # analysis    
    -    print("Runtime: %g sec" % (time()-t0)); print("Bootstrap Statistics :")
    -    print("original           bias      std. error")
    -    print("%8g %8g %14g %15g" % (statistic(data), std(data),mean(t),std(t)))
    -    return t
    -
    -
    -mu, sigma = 100, 15
    -datapoints = 10000
    -x = mu + sigma*random.randn(datapoints)
    -# bootstrap returns the data sample                                    
    -t = bootstrap(x, statistics, datapoints)
    -
    -

    -We see that our new variance and from that the standard deviation, agrees with the central limit theorem. - -

    -









    - -

    Plotting the Histogram

    -

    - - -

    # the histogram of the bootstrapped  data                                                                                                    
    -n, binsboot, patches = plt.hist(t, 50, normed=1, facecolor='red', alpha=0.75)
    -
    -# add a 'best fit' line  
    -y = mlab.normpdf( binsboot, mean(t), std(t))
    -lt = plt.plot(binsboot, y, 'r--', linewidth=1)
    -plt.xlabel('Smarts')
    -plt.ylabel('Probability')
    -plt.axis([99.5, 100.6, 0, 3.0])
    -plt.grid(True)
    -
    -plt.show()
    -
    -

    -









    - -

    The bias-variance tradeoff

    - -

    -We will discuss the bias-variance tradeoff in the context of -continuous predictions such as regression. However, many of the -intuitions and ideas discussed here also carry over to classification -tasks. Consider a dataset \( \mathcal{L} \) consisting of the data -\( \mathbf{X}_\mathcal{L}=\{(y_j, \boldsymbol{x}_j), j=0\ldots n-1\} \). - -

    -Let us assume that the true data is generated from a noisy model - -$$ -\boldsymbol{y}=f(\boldsymbol{x}) + \boldsymbol{\epsilon} -$$ - -

    -where \( \epsilon \) is normally distributed with mean zero and standard deviation \( \sigma^2 \). - -

    -In our derivation of the ordinary least squares method we defined then -an approximation to the function \( f \) in terms of the parameters -\( \boldsymbol{\beta} \) and the design matrix \( \boldsymbol{X} \) which embody our model, -that is \( \boldsymbol{\tilde{y}}=\boldsymbol{X}\boldsymbol{\beta} \). - -

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

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

    -The three terms represent the square of the bias of the learning -method, which can be thought of as the error caused by the simplifying -assumptions built into the method. The second term represents the -variance of the chosen model and finally the last terms is variance of -the error \( \boldsymbol{\epsilon} \). - -

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

    -









    - -

    A way to Read the Bias-Variance Tradeoff

    - -

    -



    - -

    -









    - -

    Example code for Bias-Variance tradeoff

    -

    - - -

    import matplotlib.pyplot as plt
    -import numpy as np
    -from sklearn.linear_model import LinearRegression, Ridge, Lasso
    -from sklearn.preprocessing import PolynomialFeatures
    -from sklearn.model_selection import train_test_split
    -from sklearn.pipeline import make_pipeline
    -from sklearn.utils import resample
    -
    -np.random.seed(2018)
    -
    -n = 500
    -n_boostraps = 100
    -degree = 18  # A quite high value, just to show.
    -noise = 0.1
    -
    -# Make data set.
    -x = np.linspace(-1, 3, n).reshape(-1, 1)
    -y = np.exp(-x**2) + 1.5 * np.exp(-(x-2)**2) + np.random.normal(0, 0.1, x.shape)
    -
    -# Hold out some test data that is never used in training.
    -x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.2)
    -
    -# Combine x transformation and model into one operation.
    -# Not neccesary, but convenient.
    -model = make_pipeline(PolynomialFeatures(degree=degree), LinearRegression(fit_intercept=False))
    -
    -# The following (m x n_bootstraps) matrix holds the column vectors y_pred
    -# for each bootstrap iteration.
    -y_pred = np.empty((y_test.shape[0], n_boostraps))
    -for i in range(n_boostraps):
    -    x_, y_ = resample(x_train, y_train)
    -
    -    # Evaluate the new model on the same test data each time.
    -    y_pred[:, i] = model.fit(x_, y_).predict(x_test).ravel()
    -
    -# Note: Expectations and variances taken w.r.t. different training
    -# data sets, hence the axis=1. Subsequent means are taken across the test data
    -# set in order to obtain a total value, but before this we have error/bias/variance
    -# calculated per data point in the test set.
    -# Note 2: The use of keepdims=True is important in the calculation of bias as this 
    -# maintains the column vector form. Dropping this yields very unexpected results.
    -error = np.mean( np.mean((y_test - y_pred)**2, axis=1, keepdims=True) )
    -bias = np.mean( (y_test - np.mean(y_pred, axis=1, keepdims=True))**2 )
    -variance = np.mean( np.var(y_pred, axis=1, keepdims=True) )
    -print('Error:', error)
    -print('Bias^2:', bias)
    -print('Var:', variance)
    -print('{} >= {} + {} = {}'.format(error, bias, variance, bias+variance))
    -
    -plt.plot(x[::5, :], y[::5, :], label='f(x)')
    -plt.scatter(x_test, y_test, label='Data points')
    -plt.scatter(x_test, np.mean(y_pred, axis=1), label='Pred')
    -plt.legend()
    -plt.show()
    -
    -

    -









    - -

    Understanding what happens

    -

    - - -

    import matplotlib.pyplot as plt
    -import numpy as np
    -from sklearn.linear_model import LinearRegression, Ridge, Lasso
    -from sklearn.preprocessing import PolynomialFeatures
    -from sklearn.model_selection import train_test_split
    -from sklearn.pipeline import make_pipeline
    -from sklearn.utils import resample
    -
    -np.random.seed(2018)
    -
    -n = 40
    -n_boostraps = 100
    -maxdegree = 14
    -
    -
    -# Make data set.
    -x = np.linspace(-3, 3, n).reshape(-1, 1)
    -y = np.exp(-x**2) + 1.5 * np.exp(-(x-2)**2)+ np.random.normal(0, 0.1, x.shape)
    -error = np.zeros(maxdegree)
    -bias = np.zeros(maxdegree)
    -variance = np.zeros(maxdegree)
    -polydegree = np.zeros(maxdegree)
    -x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.2)
    -
    -for degree in range(maxdegree):
    -    model = make_pipeline(PolynomialFeatures(degree=degree), LinearRegression(fit_intercept=False))
    -    y_pred = np.empty((y_test.shape[0], n_boostraps))
    -    for i in range(n_boostraps):
    -        x_, y_ = resample(x_train, y_train)
    -        y_pred[:, i] = model.fit(x_, y_).predict(x_test).ravel()
    -
    -    polydegree[degree] = degree
    -    error[degree] = np.mean( np.mean((y_test - y_pred)**2, axis=1, keepdims=True) )
    -    bias[degree] = np.mean( (y_test - np.mean(y_pred, axis=1, keepdims=True))**2 )
    -    variance[degree] = np.mean( np.var(y_pred, axis=1, keepdims=True) )
    -    print('Polynomial degree:', degree)
    -    print('Error:', error[degree])
    -    print('Bias^2:', bias[degree])
    -    print('Var:', variance[degree])
    -    print('{} >= {} + {} = {}'.format(error[degree], bias[degree], variance[degree], bias[degree]+variance[degree]))
    -
    -plt.plot(polydegree, error, label='Error')
    -plt.plot(polydegree, bias, label='bias')
    -plt.plot(polydegree, variance, label='Variance')
    -plt.legend()
    -plt.show()
    -
    -

    - - -

    Summing up

    - -

    -The bias-variance tradeoff summarizes the fundamental tension in -machine learning, particularly supervised learning, between the -complexity of a model and the amount of training data needed to train -it. Since data is often limited, in practice it is often useful to -use a less-complex model with higher bias, that is a model whose asymptotic -performance is worse than another model because it is easier to -train and less sensitive to sampling noise arising from having a -finite-sized training dataset (smaller variance). - -

    -The above equations tell us that in -order to minimize the expected test error, we need to select a -statistical learning method that simultaneously achieves low variance -and low bias. Note that variance is inherently a nonnegative quantity, -and squared bias is also nonnegative. Hence, we see that the expected -test MSE can never lie below \( Var(\epsilon) \), the irreducible error. - -

    -What do we mean by the variance and bias of a statistical learning -method? The variance refers to the amount by which our model would change if we -estimated it using a different training data set. Since the training -data are used to fit the statistical learning method, different -training data sets will result in a different estimate. But ideally the -estimate for our model should not vary too much between training -sets. However, if a method has high variance then small changes in -the training data can result in large changes in the model. In general, more -flexible statistical methods have higher variance. - -

    -You may also find this recent article of interest. - -

    -









    - -

    Another Example from Scikit-Learn's Repository

    -

    - - -

    """
    -============================
    -Underfitting vs. Overfitting
    -============================
    -
    -This example demonstrates the problems of underfitting and overfitting and
    -how we can use linear regression with polynomial features to approximate
    -nonlinear functions. The plot shows the function that we want to approximate,
    -which is a part of the cosine function. In addition, the samples from the
    -real function and the approximations of different models are displayed. The
    -models have polynomial features of different degrees. We can see that a
    -linear function (polynomial with degree 1) is not sufficient to fit the
    -training samples. This is called **underfitting**. A polynomial of degree 4
    -approximates the true function almost perfectly. However, for higher degrees
    -the model will **overfit** the training data, i.e. it learns the noise of the
    -training data.
    -We evaluate quantitatively **overfitting** / **underfitting** by using
    -cross-validation. We calculate the mean squared error (MSE) on the validation
    -set, the higher, the less likely the model generalizes correctly from the
    -training data.
    -"""
    -
    -print(__doc__)
    -
    -import numpy as np
    -import matplotlib.pyplot as plt
    -from sklearn.pipeline import Pipeline
    -from sklearn.preprocessing import PolynomialFeatures
    -from sklearn.linear_model import LinearRegression
    -from sklearn.model_selection import cross_val_score
    -
    -
    -def true_fun(X):
    -    return np.cos(1.5 * np.pi * X)
    -
    -np.random.seed(0)
    -
    -n_samples = 30
    -degrees = [1, 4, 15]
    -
    -X = np.sort(np.random.rand(n_samples))
    -y = true_fun(X) + np.random.randn(n_samples) * 0.1
    -
    -plt.figure(figsize=(14, 5))
    -for i in range(len(degrees)):
    -    ax = plt.subplot(1, len(degrees), i + 1)
    -    plt.setp(ax, xticks=(), yticks=())
    -
    -    polynomial_features = PolynomialFeatures(degree=degrees[i],
    -                                             include_bias=False)
    -    linear_regression = LinearRegression()
    -    pipeline = Pipeline([("polynomial_features", polynomial_features),
    -                         ("linear_regression", linear_regression)])
    -    pipeline.fit(X[:, np.newaxis], y)
    -
    -    # Evaluate the models using crossvalidation
    -    scores = cross_val_score(pipeline, X[:, np.newaxis], y,
    -                             scoring="neg_mean_squared_error", cv=10)
    -
    -    X_test = np.linspace(0, 1, 100)
    -    plt.plot(X_test, pipeline.predict(X_test[:, np.newaxis]), label="Model")
    -    plt.plot(X_test, true_fun(X_test), label="True function")
    -    plt.scatter(X, y, edgecolor='b', s=20, label="Samples")
    -    plt.xlabel("x")
    -    plt.ylabel("y")
    -    plt.xlim((0, 1))
    -    plt.ylim((-2, 2))
    -    plt.legend(loc="best")
    -    plt.title("Degree {}\nMSE = {:.2e}(+/- {:.2e})".format(
    -        degrees[i], -scores.mean(), scores.std()))
    -plt.show()
    -
    -

    - - -

    Various steps in cross-validation

    - -

    -When the repetitive splitting of the data set is done randomly, -samples may accidently end up in a fast majority of the splits in -either training or test set. Such samples may have an unbalanced -influence on either model building or prediction evaluation. To avoid -this \( k \)-fold cross-validation structures the data splitting. The -samples are divided into \( k \) more or less equally sized exhaustive and -mutually exclusive subsets. In turn (at each split) one of these -subsets plays the role of the test set while the union of the -remaining subsets constitutes the training set. Such a splitting -warrants a balanced representation of each sample in both training and -test set over the splits. Still the division into the \( k \) subsets -involves a degree of randomness. This may be fully excluded when -choosing \( k=n \). This particular case is referred to as leave-one-out -cross-validation (LOOCV). - -

    - - -

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

    - -
      -
    • Define a range of interest for the penalty parameter.
    • -
    • Divide the data set into training and test set comprising samples \( \{1, \ldots, n\} \setminus i \) and \( \{ i \} \), respectively.
    • -
    • Fit the linear regression model by means of ridge estimation for each \( \lambda \) in the grid using the training set, and the corresponding estimate of the error variance \( \boldsymbol{\sigma}_{-i}^2(\lambda) \), as
    • -
    - -$$ -\begin{align*} -\boldsymbol{\beta}_{-i}(\lambda) & = ( \boldsymbol{X}_{-i, \ast}^{T} -\boldsymbol{X}_{-i, \ast} + \lambda \boldsymbol{I}_{pp})^{-1} -\boldsymbol{X}_{-i, \ast}^{T} \boldsymbol{y}_{-i} -\end{align*} -$$ - - -
      -
    • Evaluate the prediction performance of these models on the test set by \( \log\{L[y_i, \boldsymbol{X}_{i, \ast}; \boldsymbol{\beta}_{-i}(\lambda), \boldsymbol{\sigma}_{-i}^2(\lambda)]\} \). Or, by the prediction error \( |y_i - \boldsymbol{X}_{i, \ast} \boldsymbol{\beta}_{-i}(\lambda)| \), the relative error, the error squared or the R2 score function.
    • -
    • Repeat the first three steps such that each sample plays the role of the test set once.
    • -
    • Average the prediction performances of the test sets at each grid point of the penalty bias/parameter. It is an estimate of the prediction performance of the model corresponding to this value of the penalty parameter on novel data. It is defined as
    • -
    - -$$ -\begin{align*} -\frac{1}{n} \sum_{i = 1}^n \log\{L[y_i, \mathbf{X}_{i, \ast}; \boldsymbol{\beta}_{-i}(\lambda), \boldsymbol{\sigma}_{-i}^2(\lambda)]\}. -\end{align*} -$$ - -

    -









    - -

    Cross-validation in brief

    - -

    -For the various values of \( k \) - -

      -
    1. shuffle the dataset randomly.
    2. -
    3. Split the dataset into \( k \) groups.
    4. -
    5. For each unique group: - -
        -
      1. Decide which group to use as set for test data
      2. -
      3. Take the remaining groups as a training data set
      4. -
      5. Fit a model on the training set and evaluate it on the test set
      6. -
      7. Retain the evaluation score and discard the model
      8. -
      - -
    6. Summarize the model using the sample of model evaluation scores
    7. -
    - -









    - -

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

    - -

    -The code here uses Ridge regression with cross-validation (CV) resampling and \( k \)-fold CV in order to fit a specific polynomial. -

    - - -

    import numpy as np
    -import matplotlib.pyplot as plt
    -from sklearn.model_selection import KFold
    -from sklearn.linear_model import Ridge
    -from sklearn.model_selection import cross_val_score
    -from sklearn.preprocessing import PolynomialFeatures
    -
    -# A seed just to ensure that the random numbers are the same for every run.
    -# Useful for eventual debugging.
    -np.random.seed(3155)
    -
    -# Generate the data.
    -nsamples = 100
    -x = np.random.randn(nsamples)
    -y = 3*x**2 + np.random.randn(nsamples)
    -
    -## Cross-validation on Ridge regression using KFold only
    -
    -# Decide degree on polynomial to fit
    -poly = PolynomialFeatures(degree = 6)
    -
    -# Decide which values of lambda to use
    -nlambdas = 500
    -lambdas = np.logspace(-3, 5, nlambdas)
    -
    -# Initialize a KFold instance
    -k = 5
    -kfold = KFold(n_splits = k)
    -
    -# Perform the cross-validation to estimate MSE
    -scores_KFold = np.zeros((nlambdas, k))
    -
    -i = 0
    -for lmb in lambdas:
    -    ridge = Ridge(alpha = lmb)
    -    j = 0
    -    for train_inds, test_inds in kfold.split(x):
    -        xtrain = x[train_inds]
    -        ytrain = y[train_inds]
    -
    -        xtest = x[test_inds]
    -        ytest = y[test_inds]
    -
    -        Xtrain = poly.fit_transform(xtrain[:, np.newaxis])
    -        ridge.fit(Xtrain, ytrain[:, np.newaxis])
    -
    -        Xtest = poly.fit_transform(xtest[:, np.newaxis])
    -        ypred = ridge.predict(Xtest)
    -
    -        scores_KFold[i,j] = np.sum((ypred - ytest[:, np.newaxis])**2)/np.size(ypred)
    -
    -        j += 1
    -    i += 1
    -
    -
    -estimated_mse_KFold = np.mean(scores_KFold, axis = 1)
    -
    -## Cross-validation using cross_val_score from sklearn along with KFold
    -
    -# kfold is an instance initialized above as:
    -# kfold = KFold(n_splits = k)
    -
    -estimated_mse_sklearn = np.zeros(nlambdas)
    -i = 0
    -for lmb in lambdas:
    -    ridge = Ridge(alpha = lmb)
    -
    -    X = poly.fit_transform(x[:, np.newaxis])
    -    estimated_mse_folds = cross_val_score(ridge, X, y[:, np.newaxis], scoring='neg_mean_squared_error', cv=kfold)
    -
    -    # cross_val_score return an array containing the estimated negative mse for every fold.
    -    # we have to the the mean of every array in order to get an estimate of the mse of the model
    -    estimated_mse_sklearn[i] = np.mean(-estimated_mse_folds)
    -
    -    i += 1
    -
    -## Plot and compare the slightly different ways to perform cross-validation
    -
    -plt.figure()
    -
    -plt.plot(np.log10(lambdas), estimated_mse_sklearn, label = 'cross_val_score')
    -plt.plot(np.log10(lambdas), estimated_mse_KFold, 'r--', label = 'KFold')
    -
    -plt.xlabel('log10(lambda)')
    -plt.ylabel('mse')
    -
    -plt.legend()
    -
    -plt.show()
    -
    -

    -









    - -

    More examples on bootstrap and cross-validation and errors

    - -

    - - -

    # Common imports
    -import os
    -import numpy as np
    -import pandas as pd
    -import matplotlib.pyplot as plt
    -from sklearn.linear_model import LinearRegression, Ridge, Lasso
    -from sklearn.model_selection import train_test_split
    -from sklearn.utils import resample
    -from sklearn.metrics import mean_squared_error
    -# Where to save the figures and data files
    -PROJECT_ROOT_DIR = "Results"
    -FIGURE_ID = "Results/FigureFiles"
    -DATA_ID = "DataFiles/"
    -
    -if not os.path.exists(PROJECT_ROOT_DIR):
    -    os.mkdir(PROJECT_ROOT_DIR)
    -
    -if not os.path.exists(FIGURE_ID):
    -    os.makedirs(FIGURE_ID)
    -
    -if not os.path.exists(DATA_ID):
    -    os.makedirs(DATA_ID)
    -
    -def image_path(fig_id):
    -    return os.path.join(FIGURE_ID, fig_id)
    -
    -def data_path(dat_id):
    -    return os.path.join(DATA_ID, dat_id)
    -
    -def save_fig(fig_id):
    -    plt.savefig(image_path(fig_id) + ".png", format='png')
    -
    -infile = open(data_path("EoS.csv"),'r')
    -
    -# Read the EoS data as  csv file and organize the data into two arrays with density and energies
    -EoS = pd.read_csv(infile, names=('Density', 'Energy'))
    -EoS['Energy'] = pd.to_numeric(EoS['Energy'], errors='coerce')
    -EoS = EoS.dropna()
    -Energies = EoS['Energy']
    -Density = EoS['Density']
    -#  The design matrix now as function of various polytrops
    -
    -Maxpolydegree = 30
    -X = np.zeros((len(Density),Maxpolydegree))
    -X[:,0] = 1.0
    -testerror = np.zeros(Maxpolydegree)
    -trainingerror = np.zeros(Maxpolydegree)
    -polynomial = np.zeros(Maxpolydegree)
    -
    -trials = 100
    -for polydegree in range(1, Maxpolydegree):
    -    polynomial[polydegree] = polydegree
    -    for degree in range(polydegree):
    -        X[:,degree] = Density**(degree/3.0)
    -
    -# loop over trials in order to estimate the expectation value of the MSE
    -    testerror[polydegree] = 0.0
    -    trainingerror[polydegree] = 0.0
    -    for samples in range(trials):
    -        x_train, x_test, y_train, y_test = train_test_split(X, Energies, test_size=0.2)
    -        model = LinearRegression(fit_intercept=True).fit(x_train, y_train)
    -        ypred = model.predict(x_train)
    -        ytilde = model.predict(x_test)
    -        testerror[polydegree] += mean_squared_error(y_test, ytilde)
    -        trainingerror[polydegree] += mean_squared_error(y_train, ypred) 
    -
    -    testerror[polydegree] /= trials
    -    trainingerror[polydegree] /= trials
    -    print("Degree of polynomial: %3d"% polynomial[polydegree])
    -    print("Mean squared error on training data: %.8f" % trainingerror[polydegree])
    -    print("Mean squared error on test data: %.8f" % testerror[polydegree])
    -
    -plt.plot(polynomial, np.log10(trainingerror), label='Training Error')
    -plt.plot(polynomial, np.log10(testerror), label='Test Error')
    -plt.xlabel('Polynomial degree')
    -plt.ylabel('log10[MSE]')
    -plt.legend()
    -plt.show()
    -
    -

    - - -

    The same example but now with cross-validation

    - -

    - - -

    # Common imports
    -import os
    -import numpy as np
    -import pandas as pd
    -import matplotlib.pyplot as plt
    -from sklearn.linear_model import LinearRegression, Ridge, Lasso
    -from sklearn.metrics import mean_squared_error
    -from sklearn.model_selection import KFold
    -from sklearn.model_selection import cross_val_score
    -
    -
    -# Where to save the figures and data files
    -PROJECT_ROOT_DIR = "Results"
    -FIGURE_ID = "Results/FigureFiles"
    -DATA_ID = "DataFiles/"
    -
    -if not os.path.exists(PROJECT_ROOT_DIR):
    -    os.mkdir(PROJECT_ROOT_DIR)
    -
    -if not os.path.exists(FIGURE_ID):
    -    os.makedirs(FIGURE_ID)
    -
    -if not os.path.exists(DATA_ID):
    -    os.makedirs(DATA_ID)
    -
    -def image_path(fig_id):
    -    return os.path.join(FIGURE_ID, fig_id)
    -
    -def data_path(dat_id):
    -    return os.path.join(DATA_ID, dat_id)
    -
    -def save_fig(fig_id):
    -    plt.savefig(image_path(fig_id) + ".png", format='png')
    -
    -infile = open(data_path("EoS.csv"),'r')
    -
    -# Read the EoS data as  csv file and organize the data into two arrays with density and energies
    -EoS = pd.read_csv(infile, names=('Density', 'Energy'))
    -EoS['Energy'] = pd.to_numeric(EoS['Energy'], errors='coerce')
    -EoS = EoS.dropna()
    -Energies = EoS['Energy']
    -Density = EoS['Density']
    -#  The design matrix now as function of various polytrops
    -
    -Maxpolydegree = 30
    -X = np.zeros((len(Density),Maxpolydegree))
    -X[:,0] = 1.0
    -estimated_mse_sklearn = np.zeros(Maxpolydegree)
    -polynomial = np.zeros(Maxpolydegree)
    -k =5
    -kfold = KFold(n_splits = k)
    -
    -for polydegree in range(1, Maxpolydegree):
    -    polynomial[polydegree] = polydegree
    -    for degree in range(polydegree):
    -        X[:,degree] = Density**(degree/3.0)
    -        OLS = LinearRegression()
    -# loop over trials in order to estimate the expectation value of the MSE
    -    estimated_mse_folds = cross_val_score(OLS, X, Energies, scoring='neg_mean_squared_error', cv=kfold)
    -#[:, np.newaxis]
    -    estimated_mse_sklearn[polydegree] = np.mean(-estimated_mse_folds)
    -
    -plt.plot(polynomial, np.log10(estimated_mse_sklearn), label='Test Error')
    -plt.xlabel('Polynomial degree')
    -plt.ylabel('log10[MSE]')
    -plt.legend()
    -plt.show()
    -
    -

    -









    - -

    Cross-validation with Ridge

    -

    - - -

    import numpy as np
    -import matplotlib.pyplot as plt
    -from sklearn.model_selection import KFold
    -from sklearn.linear_model import Ridge
    -from sklearn.model_selection import cross_val_score
    -from sklearn.preprocessing import PolynomialFeatures
    -
    -# A seed just to ensure that the random numbers are the same for every run.
    -np.random.seed(3155)
    -# Generate the data.
    -n = 100
    -x = np.linspace(-3, 3, n).reshape(-1, 1)
    -y = np.exp(-x**2) + 1.5 * np.exp(-(x-2)**2)+ np.random.normal(0, 0.1, x.shape)
    -# Decide degree on polynomial to fit
    -poly = PolynomialFeatures(degree = 10)
    -
    -# Decide which values of lambda to use
    -nlambdas = 500
    -lambdas = np.logspace(-3, 5, nlambdas)
    -# Initialize a KFold instance
    -k = 5
    -kfold = KFold(n_splits = k)
    -estimated_mse_sklearn = np.zeros(nlambdas)
    -i = 0
    -for lmb in lambdas:
    -    ridge = Ridge(alpha = lmb)
    -    estimated_mse_folds = cross_val_score(ridge, x, y, scoring='neg_mean_squared_error', cv=kfold)
    -    estimated_mse_sklearn[i] = np.mean(-estimated_mse_folds)
    -    i += 1
    -plt.figure()
    -plt.plot(np.log10(lambdas), estimated_mse_sklearn, label = 'cross_val_score')
    -plt.xlabel('log10(lambda)')
    -plt.ylabel('MSE')
    -plt.legend()
    -plt.show()
    -
    -

    - - - - -

    - © 1999-2021, Morten Hjorth-Jensen. Released under CC Attribution-NonCommercial 4.0 license -
    - - - - - - diff --git a/doc/src/week37/week37.dlog b/doc/src/week37/week37.dlog deleted file mode 100644 index 32128f366..000000000 --- a/doc/src/week37/week37.dlog +++ /dev/null @@ -1,18 +0,0 @@ -Translating doconce text in week37.do.txt to html -*** replacing \bm{...} by \boldsymbol{...} (\bm is not supported by MathJax) -output in week37-reveal.html -Translating doconce text in week37.do.txt to html -*** replacing \bm{...} by \boldsymbol{...} (\bm is not supported by MathJax) -output in week37-solarized.html -Translating doconce text in week37.do.txt to html -*** replacing \bm{...} by \boldsymbol{...} (\bm is not supported by MathJax) -output in week37.html -Translating doconce text in week37.do.txt to html -*** replacing \bm{...} by \boldsymbol{...} (\bm is not supported by MathJax) -output in week37-bs.html -Translating doconce text in week37.do.txt to ipynb -*** replacing \bm{...} by \boldsymbol{...} (\bm is not supported by MathJax) -collected all required additional files in ipynb-week37-src.tar.gz which must be distributed with the notebook -Failed to remove ans_at_end environment -Failed to remove sol_at_end environment -output in week37.ipynb diff --git a/doc/src/week37/week37.do.txt b/doc/src/week37/week37.do.txt index 0eabc996b..7ef9e5ab3 100644 --- a/doc/src/week37/week37.do.txt +++ b/doc/src/week37/week37.do.txt @@ -774,6 +774,45 @@ in particular if correlations are strong, may be too simplistic. !split ===== Confidence Intervals ===== +Confidence intervals are used in statistics is a type of estimate +computed from the observed data. This gives a range of values for an +unknown parameter such as the parameters $\bm{\beta}$ from linear regression. + +With the OLS expressions for the parameters $\bm{\beta}$ we found +$\mathbb{E}(\bm{\beta}) = \bm{\beta}$, which means that the estimator of the regression parameters is unbiased. + +We found also that the variance of the estimate of the $j$-th regression coefficient is +$\bm{\sigma}^2 (\bm{\beta}_j ) = \bm{\sigma}^2 [(\mathbf{X}^{T} \mathbf{X})^{-1}]_{jj} $. + +This quantity will be used to +construct a confidence interval for the estimates. + + +!split +===== Standard Approach based on the Normal Distribution ===== + +We will assume that the parameters $\beta$ follow a normal +distribution. We can then define the confidence interval. Here we will be using as +shorthands $\mu_{\beta}$ for the above mean value and $\sigma_{\beta}$ +for the standard deviation. We have then a confidence interval + +!bt +\[ +\left(\mu_{\beta}\pm \frac{z\sigma_{\beta}}{\sqrt{n}}\right), +\] +!et + +where $z$ defines the level of certainty (or confidence). For a normal +distribution typical parameters are $z=2.576$ which corresponds to a +confidence of $99\%$ while $z=1.96$ corresponds to a confidence of +$95\%$. A confidence level of $95\%$ is commonly used and it is +normally referred to as a *two-sigmas* confidence level, that is we +approximate $z\approx 2$. + +For more discussions of confidence intervals (and in particular linked with a discussion of the bootstrap method), see chapter 5 of the textbook by "Davison on the Bootstrap Methods and their Applications":"https://www.cambridge.org/core/books/bootstrap-methods-and-their-application/ED2FD043579F27952363566DC09CBD6A" + +In this text you will also find an in-depth discussion of the +Bootstrap method, why it works and various theorems related to it. !split ===== Resampling methods: Bootstrap background ===== @@ -913,6 +952,7 @@ plt.show() !ec + !split ===== The bias-variance tradeoff ===== @@ -1586,3 +1626,5 @@ plt.show() + + diff --git a/doc/src/week37/week37.html b/doc/src/week37/week37.html deleted file mode 100644 index 059126495..000000000 --- a/doc/src/week37/week37.html +++ /dev/null @@ -1,1942 +0,0 @@ - - - - - - - - -Week 37: Summary of Ridge and Lasso Regression and Resampling Methods - - - - - - - - - - - - - - - - - - - - - - - -

    Week 37: Summary of Ridge and Lasso Regression and Resampling Methods

    - -

    - - -

    -Morten Hjorth-Jensen [1, 2] -
    - -

    - - -

    [1] Department of Physics, University of Oslo
    -
    [2] Department of Physics and Astronomy and National Superconducting Cyclotron Laboratory, Michigan State University
    -
    -

    -

    Sep 16, 2021

    -
    -

    -









    - -

    Plans for week 37

    - -
      -
    • Thursday September 16: Summary of Ridge and Lasso with examples and start resampling techniques
    • -
    • Friday September 17: Resampling methods, Cross-validation, Bootstrapping and jackknife
    • -
    - -Recommended Reading: - -
      -
    1. Lectures on Resampling methods (these lectures)
    2. -
    3. Bishop 1.3 (cross-validation) and 3.2 (bias-variance tradeoff)
    4. -
    5. Hastie et al Chapter 7, here we recommend 7.1-7.5 and 7.10 (cross-validation) and 7.11 (bootstrap). This chapter is better than Bishop's on these topics. Goodfellow et al discuss this in a superficial way in sections 5.2-5.5.
    6. -
    - -









    - -

    Thursday September 16, Summary of Ridge and Lasso Regression and start Resampling methods

    - -

    -









    - -

    Deriving OLS from a probability distribution

    - -

    -Our basic assumption when we derived the OLS equations was to assume -that our output is determined by a given continuous function -\( f(\boldsymbol{x}) \) and a random noise \( \boldsymbol{\epsilon} \) given by the normal -distribution with zero mean value and an undetermined variance -\( \sigma^2 \). - -

    -We found above that the outputs \( \boldsymbol{y} \) have a mean value given by -\( \boldsymbol{X}\hat{\boldsymbol{\beta}} \) and variance \( \sigma^2 \). Since the entries to -the design matrix are not stochastic variables, we can assume that the -probability distribution of our targets is also a normal distribution -but now with mean value \( \boldsymbol{X}\hat{\boldsymbol{\beta}} \). This means that a -single output \( y_i \) is given by the Gaussian distribution - -$$ -y_i\sim \mathcal{N}(\boldsymbol{X}_{i,*}\boldsymbol{\beta}, \sigma^2)=\frac{1}{\sqrt{2\pi\sigma^2}}\exp{\left[-\frac{(y_i-\boldsymbol{X}_{i,*}\boldsymbol{\beta})^2}{2\sigma^2}\right]}. -$$ - -

    -









    - -

    Independent and Identically Distrubuted (iid)

    - -

    -We assume now that the various \( y_i \) values are stochastically distributed according to the above Gaussian distribution. -We define this distribution as -$$ -p(y_i, \boldsymbol{X}\vert\boldsymbol{\beta})=\frac{1}{\sqrt{2\pi\sigma^2}}\exp{\left[-\frac{(y_i-\boldsymbol{X}_{i,*}\boldsymbol{\beta})^2}{2\sigma^2}\right]}, -$$ - -which reads as finding the likelihood of an event \( y_i \) with the input variables \( \boldsymbol{X} \) given the parameters (to be determined) \( \boldsymbol{\beta} \). - -

    -Since these events are assumed to be independent and identicall distributed we can build the probability distribution function (PDF) for all possible event \( \boldsymbol{y} \) as the product of the single events, that is we have - -$$ -p(\boldsymbol{y},\boldsymbol{X}\vert\boldsymbol{\beta})=\prod_{i=0}^{n-1}\frac{1}{\sqrt{2\pi\sigma^2}}\exp{\left[-\frac{(y_i-\boldsymbol{X}_{i,*}\boldsymbol{\beta})^2}{2\sigma^2}\right]}=\prod_{i=0}^{n-1}p(y_i,\boldsymbol{X}\vert\boldsymbol{\beta}). -$$ - -

    -We will write this in a more compact form reserving \( \boldsymbol{D} \) for the domain of events, including the ouputs (targets) and the inputs. That is -in case we have a simple one-dimensional input and output case -$$ -\boldsymbol{D}=[(x_0,y_0), (x_1,y_1),\dots, (x_{n-1},y_{n-1})]. -$$ - -In the more general case the various inputs should be replaced by the possible features represented by the input data set \( \boldsymbol{X} \). -We can now rewrite the above probability as -$$ -p(\boldsymbol{D}\vert\boldsymbol{\beta})=\prod_{i=0}^{n-1}\frac{1}{\sqrt{2\pi\sigma^2}}\exp{\left[-\frac{(y_i-\boldsymbol{X}_{i,*}\boldsymbol{\beta})^2}{2\sigma^2}\right]}. -$$ - -

    -It is a conditional probability (see below) and reads as the likelihood of a domain of events \( \boldsymbol{D} \) given a set of parameters \( \boldsymbol{\beta} \). - -

    -









    - -

    Maximum Likelihood Estimation (MLE)

    - -

    -In statistics, maximum likelihood estimation (MLE) is a method of -estimating the parameters of an assumed probability distribution, -given some observed data. This is achieved by maximizing a likelihood -function so that, under the assumed statistical model, the observed -data is the most probable. - -

    -We will assume here that our events are given by the above Gaussian -distribution and we will determine the optimal parameters \( \beta \) by -maximizing the above PDF. However, computing the derivatives of a -product function is cumbersome and can easily lead to overflow and/or -underflowproblems, with potentials for loss of numerical precision. - -

    -In practice, it is more convenient to maximize the logarithm of the -PDF because it is a monotonically increasing function of the argument. -Alternatively, and this will be our option, we will minimize the -negative of the logarithm since this is a monotonically decreasing -function. - -

    -Note also that maximization/minimization of the logarithm of the PDF -is equivalent to the maximization/minimization of the function itself. - -

    -









    - -

    A new Cost Function

    - -

    -We could now define a new cost function to minimize, namely the negative logarithm of the above PDF - -$$ -C(\boldsymbol{\beta}=-\log{\prod_{i=0}^{n-1}p(y_i,\boldsymbol{X}\vert\boldsymbol{\beta})}=-\sum_{i=0}^{n-1}\log{p(y_i,\boldsymbol{X}\vert\boldsymbol{\beta})}, -$$ - -which becomes -$$ -C(\boldsymbol{\beta}=\frac{n}{2}\log{2\pi\sigma^2}+\frac{\vert\vert (\boldsymbol{y}-\boldsymbol{X}\boldsymbol{\beta})\vert\vert_2^2}{2\sigma^2}. -$$ - -

    -Taking the derivative of the new cost function with respect to the parameters \( \beta \) we recognize our familiar OLS equation, namely - -$$ -\boldsymbol{X}^T\left(\boldsymbol{y}-\boldsymbol{X}\boldsymbol{\beta}\right) =0, -$$ - -which leads to the well-known OLS equation for the optimal paramters \( \beta \) -$$ -\hat{\boldsymbol{\beta}}^{\mathrm{OLS}}=\left(\boldsymbol{X}^T\boldsymbol{X}\right)^{-1}\boldsymbol{X}^T\boldsymbol{y}! -$$ - -

    -









    - -

    Bayes' Theorem

    - -

    -If we combine the conditional probability with the marginal probability and the standard product rule, we have -$$ -p(X\vert Y)= \frac{p(X,Y)}{p(Y)}, -$$ - -which we can rewrite as - -$$ -p(X\vert Y)= \frac{p(X,Y)}{\sum_{i=0}^{n-1}p(Y\vert X=x_i)p(x_i)}=\frac{p(Y\vert X)p(X)}{\sum_{i=0}^{n-1}p(Y\vert X=x_i)p(x_i)}, -$$ - -which is Bayes' theorem. It allows us to evaluate the uncertainty in in \( X \) after we have observed \( Y \). We can easily interchange \( X \) with \( Y \). - -

    -









    - -

    Interpretations of Bayes' Theorem

    - -

    -The quantity \( p(Y\vert X) \) on the right-hand side of the theorem is -evaluated for the observed data \( Y \) and can be viewed as a function of -the parameter space represented by \( X \). This function is not -necesseraly normalized and is normally called the likelihood function. - -

    -The function \( p(X) \) on the right hand side is called the prior while the function on the left hand side is the called the posterior probability. The denominator on the right hand side serves as a normalization factor for the posterior distribution. - -

    -









    - -

    Test Function for what happens with OLS, Ridge and Lasso

    - -

    -We will play around with a study of the values for the optimal -parameters \( \boldsymbol{\beta} \) using OLS, Ridge and Lasso regression. For -OLS, you will notice as function of the noise and polynomial degree, -that the parameters \( \beta \) will fluctuate from order to order in the -polynomial fit and that for larger and larger polynomial degrees of freedom, the parameters will tend to increase in value for OLS. - -

    -For Ridge and Lasso regression, the higher order parameters will typically be reduced, providing thereby less fluctuations from one order to another one. - -

    - - -

    import numpy as np
    -import matplotlib.pyplot as plt
    -from sklearn.model_selection import train_test_split
    -from sklearn import linear_model
    -
    -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
    -
    -# Make data set.
    -n = 10000
    -x = np.random.rand(n)
    -y = np.exp(-x**2) + 1.5 * np.exp(-(x-2)**2)+ np.random.randn(n)
    -
    -Maxpolydegree = 5
    -X = np.zeros((len(x),Maxpolydegree))
    -X[:,0] = 1.0
    -
    -for polydegree in range(1, Maxpolydegree):
    -    for degree in range(polydegree):
    -        X[:,degree] = x**(degree)
    -
    -
    -# 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.pinv(X_train.T @ X_train) @ X_train.T @ y_train
    -print(OLSbeta)
    -ypredictOLS = X_test @ OLSbeta
    -print("Test MSE OLS")
    -print(MSE(y_test,ypredictOLS))
    -# Repeat now for Lasso and Ridge regression and various values of the regularization parameter using Scikit-Learn
    -# Decide which values of lambda to use
    -nlambdas = 4
    -MSERidgePredict = np.zeros(nlambdas)
    -MSELassoPredict = np.zeros(nlambdas)
    -lambdas = np.logspace(-3, 1, nlambdas)
    -for i in range(nlambdas):
    -    lmb = lambdas[i]
    -    # Make the fit using Ridge and Lasso
    -    RegRidge = linear_model.Ridge(lmb,fit_intercept=False)
    -    RegRidge.fit(X_train,y_train)
    -    RegLasso = linear_model.Lasso(lmb,fit_intercept=False)
    -    RegLasso.fit(X_train,y_train)
    -    # and then make the prediction
    -    ypredictRidge = RegRidge.predict(X_test)
    -    ypredictLasso = RegLasso.predict(X_test)
    -    # Compute the MSE and print it
    -    MSERidgePredict[i] = MSE(y_test,ypredictRidge)
    -    MSELassoPredict[i] = MSE(y_test,ypredictLasso)
    -    print(lmb,RegRidge.coef_)
    -    print(lmb,RegLasso.coef_)
    -# Now plot the results
    -plt.figure()
    -plt.plot(np.log10(lambdas), MSERidgePredict, 'b', label = 'MSE Ridge Test')
    -plt.plot(np.log10(lambdas), MSELassoPredict, 'r', label = 'MSE Lasso Test')
    -plt.xlabel('log10(lambda)')
    -plt.ylabel('MSE')
    -plt.legend()
    -plt.show()
    -
    -

    -How can we understand this? - -

    -









    - -

    Rerunning the above code

    - -

    -Let us write out the values of the coefficients \( \beta_i \) as functions -of the polynomial degree and noise. We will focus only on the Ridge -results and some few selected values of the hyperparameter \( \lambda \). - -

    -If we don't include any noise and run this code for different values -of the polynomial degree, we notice that the results for \( \beta_i \) do -not show great changes from one order to the next. This is an -indication that for higher polynomial orders, our parameters become -less important. - -

    -If we however add noise, what happens is that the polynomial fit is -trying to adjust the fit to traverse in the best possible way all data -points. This can lead to large fluctuations in the parameters -\( \beta_i \) as functions of polynomial order. It will also be reflected -in a larger value of the variance of each parameter \( \beta_i \). What -Ridge regression (and Lasso as well) are doing then is to try to -quench the fluctuations in the parameters of \( \beta_i \) which have a -large variance (normally for higher orders in the polynomial). - -

    - - -

    import numpy as np
    -import pandas as pd
    -from IPython.display import display
    -import matplotlib.pyplot as plt
    -from sklearn.model_selection import train_test_split
    -from sklearn import linear_model
    -
    -# Make data set.
    -n = 1000
    -x = np.random.rand(n)
    -y = np.exp(-x**2) + 1.5 * np.exp(-(x-2)**2)+ np.random.randn(n)
    -
    -Maxpolydegree = 5
    -X = np.zeros((len(x),Maxpolydegree))
    -X[:,0] = 1.0
    -
    -for polydegree in range(1, Maxpolydegree):
    -    for degree in range(polydegree):
    -        X[:,degree] = x**(degree)
    -
    -
    -# 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)
    -
    -# Decide which values of lambda to use
    -nlambdas = 5
    -lambdas = np.logspace(-3, 2, nlambdas)
    -for i in range(nlambdas):
    -    lmb = lambdas[i]
    -    # Make the fit using Ridge only
    -    RegRidge = linear_model.Ridge(lmb,fit_intercept=False)
    -    RegRidge.fit(X_train,y_train)
    -    # and then make the prediction
    -    ypredictRidge = RegRidge.predict(X_test)
    -    Coeffs = np.array(RegRidge.coef_)
    -    BetaValues = pd.DataFrame(Coeffs)
    -    BetaValues.columns = ['beta']
    -    display(BetaValues)    
    -
    -

    -









    - -

    Invoking Bayes' theorem

    - -

    -Using Bayes' theorem we can gain a better intuition about Ridge and Lasso regression. - -

    -For ordinary least squares we postulated that the maximum likelihood for the doamin of events \( \boldsymbol{D} \) (one-dimensional case) -$$ -\boldsymbol{D}=[(x_0,y_0), (x_1,y_1),\dots, (x_{n-1},y_{n-1})], -$$ - -is given by -$$ -p(\boldsymbol{D}\vert\boldsymbol{\beta})=\prod_{i=0}^{n-1}\frac{1}{\sqrt{2\pi\sigma^2}}\exp{\left[-\frac{(y_i-\boldsymbol{X}_{i,*}\boldsymbol{\beta})^2}{2\sigma^2}\right]}. -$$ - -

    -In Bayes' theorem this function plays the role of the so-called likelihood. We could now ask the question what is the posterior probability of a parameter set \( \boldsymbol{\beta} \) given a domain of events \( \boldsymbol{D} \)? That is, how can we define the posterior probability - -$$ -p(\boldsymbol{\beta}\vert\boldsymbol{D}). -$$ - -

    -Bayes' theorem comes to our rescue here since (omitting the normalization constant) -$$ -p(\boldsymbol{\beta}\vert\boldsymbol{D})\propto p(\boldsymbol{D}\vert\boldsymbol{\beta})p(\boldsymbol{\beta}). -$$ - -

    -We have a model for \( p(\boldsymbol{D}\vert\boldsymbol{\beta}) \) but need one for the prior \( p(\boldsymbol{\beta} \)! - -

    -









    - -

    Ridge and Bayes

    - -

    -With the posterior probability defined by a likelihood which we have -already modeled and an unknown prior, we are now ready to make -additional models for the prior. - -

    -We can, based on our discussions of the variance of \( \boldsymbol{\beta} \) and the mean value, assume that the prior for the values \( \boldsymbol{\beta} \) is given by a Gaussian with mean value zero and variance \( \tau^2 \), that is - -$$ -p(\boldsymbol{\beta})=\prod_{j=0}^{p-1}\exp{\left(-\frac{\beta_j^2}{2\tau^2}\right)}. -$$ - -

    -Our posterior probability becomes then (omitting the normalization factor which is just a constant) -$$ -p(\boldsymbol{\beta\vert\boldsymbol{D})}=\prod_{i=0}^{n-1}\frac{1}{\sqrt{2\pi\sigma^2}}\exp{\left[-\frac{(y_i-\boldsymbol{X}_{i,*}\boldsymbol{\beta})^2}{2\sigma^2}\right]}\prod_{j=0}^{p-1}\exp{\left(-\frac{\beta_j^2}{2\tau^2}\right)}. -$$ - -

    -We can now optimize this quantity with respect to \( \boldsymbol{\beta} \). As we -did for OLS, this is most conveniently done by taking the negative -logarithm of the posterior probability. Doing so and leaving out the -constants terms that do not depend on \( \beta \), we have - -$$ -C(\boldsymbol{\beta})=\frac{\vert\vert (\boldsymbol{y}-\boldsymbol{X}\boldsymbol{\beta})\vert\vert_2^2}{2\sigma^2}+\frac{1}{2\tau^2}\vert\vert\boldsymbol{\beta}\vert\vert_2^2, -$$ - -and replacing \( 1/2\tau^2 \) with \( \lambda \) we have - -$$ -C(\boldsymbol{\beta})=\frac{\vert\vert (\boldsymbol{y}-\boldsymbol{X}\boldsymbol{\beta})\vert\vert_2^2}{2\sigma^2}+\lambda\vert\vert\boldsymbol{\beta}\vert\vert_2^2, -$$ - -which is our Ridge cost function! Nice, isn't it? - -

    -









    - -

    Lasso and Bayes

    - -

    -To derive the Lasso cost function, we simply replace the Gaussian prior with an exponential distribution (Laplace in this case) with zero mean value, that is - -$$ -p(\boldsymbol{\beta})=\prod_{j=0}^{p-1}\exp{\left(-\frac{\vert\beta_j\vert}{\tau}\right)}. -$$ - -

    -Our posterior probability becomes then (omitting the normalization factor which is just a constant) -$$ -p(\boldsymbol{\beta}\vert\boldsymbol{D})=\prod_{i=0}^{n-1}\frac{1}{\sqrt{2\pi\sigma^2}}\exp{\left[-\frac{(y_i-\boldsymbol{X}_{i,*}\boldsymbol{\beta})^2}{2\sigma^2}\right]}\prod_{j=0}^{p-1}\exp{\left(-\frac{\vert\beta_j\vert}{\tau}\right)}. -$$ - -

    -Taking the negative -logarithm of the posterior probability and leaving out the -constants terms that do not depend on \( \beta \), we have - -$$ -C(\boldsymbol{\beta}=\frac{\vert\vert (\boldsymbol{y}-\boldsymbol{X}\boldsymbol{\beta})\vert\vert_2^2}{2\sigma^2}+\frac{1}{\tau}\vert\vert\boldsymbol{\beta}\vert\vert_1, -$$ - -and replacing \( 1/\tau \) with \( \lambda \) we have - -$$ -C(\boldsymbol{\beta}=\frac{\vert\vert (\boldsymbol{y}-\boldsymbol{X}\boldsymbol{\beta})\vert\vert_2^2}{2\sigma^2}+\lambda\vert\vert\boldsymbol{\beta}\vert\vert_1, -$$ - -which is our Lasso cost function! - -

    -









    - -

    Why resampling methods

    - -

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

      -
    1. look at statistical properties, including a discussion of mean values, variance and the so-called bias-variance tradeoff
    2. -
    3. introduce resampling techniques like cross-validation, bootstrapping and jackknife and more
    4. -
    - -and discuss how to select a given model (one of the difficult parts in machine learning). - -

    -









    - -

    Resampling methods

    -
    - -

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

    -Two resampling methods are often used in Machine Learning analyses, - -

      -
    1. The bootstrap method
    2. -
    3. and Cross-Validation
    4. -
    - -In addition there are several other methods such as the Jackknife and the Blocking methods. We will discuss in particular -cross-validation and the bootstrap method. - - -
    - - -

    -









    - -

    Resampling approaches can be computationally expensive

    -
    - -

    - -

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

    - - -

    -









    - -

    Why resampling methods ?

    -
    -Statistical analysis -

    - -

      -
    • Our simulations can be treated as computer experiments. This is particularly the case for Monte Carlo methods which are widely used in statistical analyses.
    • -
    • The results can be analysed with the same statistical tools as we would use when analysing experimental data.
    • -
    • As in all experiments, we are looking for expectation values and an estimate of how accurate they are, i.e., possible sources for errors.
    • -
    -
    - - -

    -









    - -

    Statistical analysis

    -
    - -

    - -

      -
    • As in other experiments, many numerical experiments have two classes of errors:
    • - -
        -
      • Statistical errors
      • -
      • Systematical errors
      • -
      - -
    • Statistical errors can be estimated using standard tools from statistics
    • -
    • Systematical errors are method specific and must be treated differently from case to case.
    • -
    -
    - - -

    -









    - -

    Resampling methods

    - -

    -With all these analytical equations for both the OLS and Ridge -regression, we will now outline how to assess a given model. This will -lead to a discussion of the so-called bias-variance tradeoff (see -below) and so-called resampling methods. - -

    -One of the quantities we have discussed as a way to measure errors is -the mean-squared error (MSE), mainly used for fitting of continuous -functions. Another choice is the absolute error. - -

    -In the discussions below we will focus on the MSE and in particular since we will split the data into test and training data, -we discuss the - -

      -
    1. prediction error or simply the test error \( \mathrm{Err_{Test}} \), where we have a fixed training set and the test error is the MSE arising from the data reserved for testing. We discuss also the
    2. -
    3. training error \( \mathrm{Err_{Train}} \), which is the average loss over the training data.
    4. -
    - -As our model becomes more and more complex, more of the training data tends to used. The training may thence adapt to more complicated structures in the data. This may lead to a decrease in the bias (see below for code example) and a slight increase of the variance for the test error. -For a certain level of complexity the test error will reach minimum, before starting to increase again. The -training error reaches a saturation. - -

    -









    - -

    Resampling methods: Jackknife and Bootstrap

    - -

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

    -The jackknife is a special case of the independent bootstrap. Still, the jackknife was made -popular prior to the independent bootstrap. And as the popularity of -the independent bootstrap soared, new variants, such as the dependent bootstrap have also been developed.. - -

    -The Jackknife and independent bootstrap work for -independent, identically distributed random variables. -If these conditions are not -satisfied, the methods will fail. Yet, it should be said that if the data are -independent, identically distributed, and we only want to estimate the -variance of \( \overline{X} \) (which often is the case), then there is no -need for bootstrapping. - -

    -









    - -

    Resampling methods: Jackknife

    - -

    -The Jackknife works by making many replicas of the estimator \( \widehat{\beta} \). -The jackknife is a resampling method where we systematically leave out one observation from the vector of observed values \( \boldsymbol{x} = (x_1,x_2,\cdots,X_n) \). -Let \( \boldsymbol{x}_i \) denote the vector -$$ -\boldsymbol{x}_i = (x_1,x_2,\cdots,x_{i-1},x_{i+1},\cdots,x_n), -$$ - -

    -which equals the vector \( \boldsymbol{x} \) with the exception that observation -number \( i \) is left out. Using this notation, define -\( \widehat{\beta}_i \) to be the estimator -\( \widehat{\beta} \) computed using \( \vec{X}_i \). - -

    -









    - -

    Jackknife code example

    -

    - - -

    from numpy import *
    -from numpy.random import randint, randn
    -from time import time
    -
    -def jackknife(data, stat):
    -    n = len(data);t = zeros(n); inds = arange(n); t0 = time()
    -    ## 'jackknifing' by leaving out an observation for each i                                                                                                                      
    -    for i in range(n):
    -        t[i] = stat(delete(data,i) )
    -
    -    # analysis                                                                                                                                                                     
    -    print("Runtime: %g sec" % (time()-t0)); print("Jackknife Statistics :")
    -    print("original           bias      std. error")
    -    print("%8g %14g %15g" % (stat(data),(n-1)*mean(t)/n, (n*var(t))**.5))
    -
    -    return t
    -
    -
    -# Returns mean of data samples                                                                                                                                                     
    -def stat(data):
    -    return mean(data)
    -
    -
    -mu, sigma = 100, 15
    -datapoints = 10000
    -x = mu + sigma*random.randn(datapoints)
    -# jackknife returns the data sample                                                                                                                                                
    -t = jackknife(x, stat)
    -
    -

    -









    - -

    Resampling methods: Bootstrap

    -
    - -

    -Bootstrapping is a non-parametric approach to statistical inference -that substitutes computation for more traditional distributional -assumptions and asymptotic results. Bootstrapping offers a number of -advantages: - -

      -
    1. The bootstrap is quite general, although there are some cases in which it fails.
    2. -
    3. Because it does not require distributional assumptions (such as normally distributed errors), the bootstrap can provide more accurate inferences when the data are not well behaved or when the sample size is small.
    4. -
    5. It is possible to apply the bootstrap to statistics with sampling distributions that are difficult to derive, even asymptotically.
    6. -
    7. It is relatively simple to apply the bootstrap to complex data-collection plans (such as stratified and clustered samples).
    8. -
    -
    - - -

    -The textbook by Davison on the Bootstrap Methods and their Applications provides many more insights and proofs. In this course we will take a more practical approach and use the results and theorems provided in the literature. For those interested in reading more about the bootstrap methods, we recommend the above text and the one by Efron and Tibshirani. - -

    -Before we proceed however, we need to remind ourselves about a central theorem in statistics, namely the so-called central limit theorem. - -

    -









    - -

    The Central Limit Theorem

    - -

    -Suppose we have a PDF \( p(x) \) from which we generate a series \( N \) -of averages \( \langle x_i \rangle \). Each mean value \( \langle x_i \rangle \) -is viewed as the average of a specific measurement, e.g., throwing -dice 100 times and then taking the average value, or producing a certain -amount of random numbers. -For notational ease, we set \( \langle x_i \rangle=x_i \) in the discussion -which follows. - -

    -If we compute the mean \( z \) of \( m \) such mean values \( x_i \) -$$ - z=\frac{x_1+x_2+\dots+x_m}{m}, -$$ - -the question we pose is which is the PDF of the new variable \( z \). - -

    -









    - -

    Finding the Limit

    - -

    -The probability of obtaining an average value \( z \) is the product of the -probabilities of obtaining arbitrary individual mean values \( x_i \), -but with the constraint that the average is \( z \). We can express this through -the following expression -$$ - \tilde{p}(z)=\int dx_1p(x_1)\int dx_2p(x_2)\dots\int dx_mp(x_m) - \delta(z-\frac{x_1+x_2+\dots+x_m}{m}), -$$ - -where the \( \delta \)-function enbodies the constraint that the mean is \( z \). -All measurements that lead to each individual \( x_i \) are expected to -be independent, which in turn means that we can express \( \tilde{p} \) as the -product of individual \( p(x_i) \). The independence assumption is important in the derivation of the central limit theorem. - -

    -









    - -

    Rewriting the \( \delta \)-function

    - -

    -If we use the integral expression for the \( \delta \)-function - -$$ - \delta(z-\frac{x_1+x_2+\dots+x_m}{m})=\frac{1}{2\pi}\int_{-\infty}^{\infty} - dq\exp{\left(iq(z-\frac{x_1+x_2+\dots+x_m}{m})\right)}, -$$ - -and inserting \( e^{i\mu q-i\mu q} \) where \( \mu \) is the mean value -we arrive at -$$ - \tilde{p}(z)=\frac{1}{2\pi}\int_{-\infty}^{\infty} - dq\exp{\left(iq(z-\mu)\right)}\left[\int_{-\infty}^{\infty} - dxp(x)\exp{\left(iq(\mu-x)/m\right)}\right]^m, -$$ - -with the integral over \( x \) resulting in - -$$ - \int_{-\infty}^{\infty}dxp(x)\exp{\left(iq(\mu-x)/m\right)}= - \int_{-\infty}^{\infty}dxp(x) - \left[1+\frac{iq(\mu-x)}{m}-\frac{q^2(\mu-x)^2}{2m^2}+\dots\right]. -$$ - -

    -









    - -

    Identifying Terms

    - -

    -The second term on the rhs disappears since this is just the mean and -employing the definition of \( \sigma^2 \) we have -$$ - \int_{-\infty}^{\infty}dxp(x)e^{\left(iq(\mu-x)/m\right)}= - 1-\frac{q^2\sigma^2}{2m^2}+\dots, -$$ - -resulting in - -$$ - \left[\int_{-\infty}^{\infty}dxp(x)\exp{\left(iq(\mu-x)/m\right)}\right]^m\approx - \left[1-\frac{q^2\sigma^2}{2m^2}+\dots \right]^m, -$$ - -and in the limit \( m\rightarrow \infty \) we obtain - -$$ - \tilde{p}(z)=\frac{1}{\sqrt{2\pi}(\sigma/\sqrt{m})} - \exp{\left(-\frac{(z-\mu)^2}{2(\sigma/\sqrt{m})^2}\right)}, -$$ - -which is the normal distribution with variance -\( \sigma^2_m=\sigma^2/m \), where \( \sigma \) is the variance of the PDF \( p(x) \) -and \( \mu \) is also the mean of the PDF \( p(x) \). - -

    -









    - -

    Wrapping it up

    - -

    -Thus, the central limit theorem states that the PDF \( \tilde{p}(z) \) of -the average of \( m \) random values corresponding to a PDF \( p(x) \) -is a normal distribution whose mean is the -mean value of the PDF \( p(x) \) and whose variance is the variance -of the PDF \( p(x) \) divided by \( m \), the number of values used to compute \( z \). - -

    -The theorem is satisfied by a large class of PDFs. Note however that for a -finite \( m \), it is not always possible to find a closed expression for -\( \tilde{p}(x) \). -The central limit theorem leads then to the well-known expression for the -standard deviation, given by - -$$ - \sigma_m= -\frac{\sigma}{\sqrt{m}}. -$$ - -

    -The latter is true only if the average value is known exactly. This is obtained in the limit -\( m\rightarrow \infty \) only. Because the mean and the variance are measured quantities we obtain -the familiar expression in statistics -$$ - \sigma_m\approx -\frac{\sigma}{\sqrt{m-1}}. -$$ - -

    -In many cases however the above estimate for the standard deviation, -in particular if correlations are strong, may be too simplistic. - -

    -









    - -

    Confidence Intervals

    - -

    -









    - -

    Resampling methods: Bootstrap background

    - -

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

    -









    - -

    Resampling methods: More Bootstrap background

    - -

    -In the case that \( \widehat{\beta} \) has -more than one component, and the components are independent, we use the -same estimator on each component separately. If the probability -density function of \( X_i \), \( p(x) \), had been known, then it would have -been straightforward to do this by: - -

      -
    1. Drawing lots of numbers from \( p(x) \), suppose we call one such set of numbers \( (X_1^*, X_2^*, \cdots, X_n^*) \).
    2. -
    3. Then using these numbers, we could compute a replica of \( \widehat{\beta} \) called \( \widehat{\beta}^* \).
    4. -
    - -By repeated use of the above two points, many -estimates of \( \widehat{\beta} \) can be obtained. The -idea is to use the relative frequency of \( \widehat{\beta}^* \) -(think of a histogram) as an estimate of \( p(\boldsymbol{t}) \). - -

    -









    - -

    Resampling methods: Bootstrap approach

    - -

    -But -unless there is enough information available about the process that -generated \( X_1,X_2,\cdots,X_n \), \( p(x) \) is in general -unknown. Therefore, Efron in 1979 asked the -question: What if we replace \( p(x) \) by the relative frequency -of the observation \( X_i \)? - -

    -If we draw observations in accordance with -the relative frequency of the observations, will we obtain the same -result in some asymptotic sense? The answer is yes. - -

    -









    - -

    Resampling methods: Bootstrap steps

    - -

    -The independent bootstrap works like this: - -

      -
    1. Draw with replacement \( n \) numbers for the observed variables \( \boldsymbol{x} = (x_1,x_2,\cdots,x_n) \).
    2. -
    3. Define a vector \( \boldsymbol{x}^* \) containing the values which were drawn from \( \boldsymbol{x} \).
    4. -
    5. Using the vector \( \boldsymbol{x}^* \) compute \( \widehat{\beta}^* \) by evaluating \( \widehat \beta \) under the observations \( \boldsymbol{x}^* \).
    6. -
    7. Repeat this process \( k \) times.
    8. -
    - -When you are done, you can draw a histogram of the relative frequency -of \( \widehat \beta^* \). This is your estimate of the probability -distribution \( p(t) \). Using this probability distribution you can -estimate any statistics thereof. In principle you never draw the -histogram of the relative frequency of \( \widehat{\beta}^* \). Instead -you use the estimators corresponding to the statistic of interest. For -example, if you are interested in estimating the variance of \( \widehat -\beta \), apply the etsimator \( \widehat \sigma^2 \) to the values -\( \widehat \beta^* \). - -

    -









    - -

    Code example for the Bootstrap method

    - -

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

    - - -

    from numpy import *
    -from numpy.random import randint, randn
    -from time import time
    -import matplotlib.mlab as mlab
    -import matplotlib.pyplot as plt
    -
    -# Returns mean of bootstrap samples                                                                              # Alternatively, we can run it using Scikit-Learn's function resample                                            # See the examples below
    -
    -def statistics(data):
    -    return mean(data)
    -
    -
    -# Bootstrap algorithm
    -def bootstrap(data, statistic, R):
    -    t = zeros(R); n = len(data); inds = arange(n); t0 = time()
    -    # non-parametric bootstrap         
    -    for i in range(R):
    -        t[i] = statistic(data[randint(0,n,n)])
    -
    -    # analysis    
    -    print("Runtime: %g sec" % (time()-t0)); print("Bootstrap Statistics :")
    -    print("original           bias      std. error")
    -    print("%8g %8g %14g %15g" % (statistic(data), std(data),mean(t),std(t)))
    -    return t
    -
    -
    -mu, sigma = 100, 15
    -datapoints = 10000
    -x = mu + sigma*random.randn(datapoints)
    -# bootstrap returns the data sample                                    
    -t = bootstrap(x, statistics, datapoints)
    -
    -

    -We see that our new variance and from that the standard deviation, agrees with the central limit theorem. - -

    -









    - -

    Plotting the Histogram

    -

    - - -

    # the histogram of the bootstrapped  data                                                                                                    
    -n, binsboot, patches = plt.hist(t, 50, normed=1, facecolor='red', alpha=0.75)
    -
    -# add a 'best fit' line  
    -y = mlab.normpdf( binsboot, mean(t), std(t))
    -lt = plt.plot(binsboot, y, 'r--', linewidth=1)
    -plt.xlabel('Smarts')
    -plt.ylabel('Probability')
    -plt.axis([99.5, 100.6, 0, 3.0])
    -plt.grid(True)
    -
    -plt.show()
    -
    -

    -









    - -

    The bias-variance tradeoff

    - -

    -We will discuss the bias-variance tradeoff in the context of -continuous predictions such as regression. However, many of the -intuitions and ideas discussed here also carry over to classification -tasks. Consider a dataset \( \mathcal{L} \) consisting of the data -\( \mathbf{X}_\mathcal{L}=\{(y_j, \boldsymbol{x}_j), j=0\ldots n-1\} \). - -

    -Let us assume that the true data is generated from a noisy model - -$$ -\boldsymbol{y}=f(\boldsymbol{x}) + \boldsymbol{\epsilon} -$$ - -

    -where \( \epsilon \) is normally distributed with mean zero and standard deviation \( \sigma^2 \). - -

    -In our derivation of the ordinary least squares method we defined then -an approximation to the function \( f \) in terms of the parameters -\( \boldsymbol{\beta} \) and the design matrix \( \boldsymbol{X} \) which embody our model, -that is \( \boldsymbol{\tilde{y}}=\boldsymbol{X}\boldsymbol{\beta} \). - -

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

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

    -The three terms represent the square of the bias of the learning -method, which can be thought of as the error caused by the simplifying -assumptions built into the method. The second term represents the -variance of the chosen model and finally the last terms is variance of -the error \( \boldsymbol{\epsilon} \). - -

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

    -









    - -

    A way to Read the Bias-Variance Tradeoff

    - -

    -



    - -

    -









    - -

    Example code for Bias-Variance tradeoff

    -

    - - -

    import matplotlib.pyplot as plt
    -import numpy as np
    -from sklearn.linear_model import LinearRegression, Ridge, Lasso
    -from sklearn.preprocessing import PolynomialFeatures
    -from sklearn.model_selection import train_test_split
    -from sklearn.pipeline import make_pipeline
    -from sklearn.utils import resample
    -
    -np.random.seed(2018)
    -
    -n = 500
    -n_boostraps = 100
    -degree = 18  # A quite high value, just to show.
    -noise = 0.1
    -
    -# Make data set.
    -x = np.linspace(-1, 3, n).reshape(-1, 1)
    -y = np.exp(-x**2) + 1.5 * np.exp(-(x-2)**2) + np.random.normal(0, 0.1, x.shape)
    -
    -# Hold out some test data that is never used in training.
    -x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.2)
    -
    -# Combine x transformation and model into one operation.
    -# Not neccesary, but convenient.
    -model = make_pipeline(PolynomialFeatures(degree=degree), LinearRegression(fit_intercept=False))
    -
    -# The following (m x n_bootstraps) matrix holds the column vectors y_pred
    -# for each bootstrap iteration.
    -y_pred = np.empty((y_test.shape[0], n_boostraps))
    -for i in range(n_boostraps):
    -    x_, y_ = resample(x_train, y_train)
    -
    -    # Evaluate the new model on the same test data each time.
    -    y_pred[:, i] = model.fit(x_, y_).predict(x_test).ravel()
    -
    -# Note: Expectations and variances taken w.r.t. different training
    -# data sets, hence the axis=1. Subsequent means are taken across the test data
    -# set in order to obtain a total value, but before this we have error/bias/variance
    -# calculated per data point in the test set.
    -# Note 2: The use of keepdims=True is important in the calculation of bias as this 
    -# maintains the column vector form. Dropping this yields very unexpected results.
    -error = np.mean( np.mean((y_test - y_pred)**2, axis=1, keepdims=True) )
    -bias = np.mean( (y_test - np.mean(y_pred, axis=1, keepdims=True))**2 )
    -variance = np.mean( np.var(y_pred, axis=1, keepdims=True) )
    -print('Error:', error)
    -print('Bias^2:', bias)
    -print('Var:', variance)
    -print('{} >= {} + {} = {}'.format(error, bias, variance, bias+variance))
    -
    -plt.plot(x[::5, :], y[::5, :], label='f(x)')
    -plt.scatter(x_test, y_test, label='Data points')
    -plt.scatter(x_test, np.mean(y_pred, axis=1), label='Pred')
    -plt.legend()
    -plt.show()
    -
    -

    -









    - -

    Understanding what happens

    -

    - - -

    import matplotlib.pyplot as plt
    -import numpy as np
    -from sklearn.linear_model import LinearRegression, Ridge, Lasso
    -from sklearn.preprocessing import PolynomialFeatures
    -from sklearn.model_selection import train_test_split
    -from sklearn.pipeline import make_pipeline
    -from sklearn.utils import resample
    -
    -np.random.seed(2018)
    -
    -n = 40
    -n_boostraps = 100
    -maxdegree = 14
    -
    -
    -# Make data set.
    -x = np.linspace(-3, 3, n).reshape(-1, 1)
    -y = np.exp(-x**2) + 1.5 * np.exp(-(x-2)**2)+ np.random.normal(0, 0.1, x.shape)
    -error = np.zeros(maxdegree)
    -bias = np.zeros(maxdegree)
    -variance = np.zeros(maxdegree)
    -polydegree = np.zeros(maxdegree)
    -x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.2)
    -
    -for degree in range(maxdegree):
    -    model = make_pipeline(PolynomialFeatures(degree=degree), LinearRegression(fit_intercept=False))
    -    y_pred = np.empty((y_test.shape[0], n_boostraps))
    -    for i in range(n_boostraps):
    -        x_, y_ = resample(x_train, y_train)
    -        y_pred[:, i] = model.fit(x_, y_).predict(x_test).ravel()
    -
    -    polydegree[degree] = degree
    -    error[degree] = np.mean( np.mean((y_test - y_pred)**2, axis=1, keepdims=True) )
    -    bias[degree] = np.mean( (y_test - np.mean(y_pred, axis=1, keepdims=True))**2 )
    -    variance[degree] = np.mean( np.var(y_pred, axis=1, keepdims=True) )
    -    print('Polynomial degree:', degree)
    -    print('Error:', error[degree])
    -    print('Bias^2:', bias[degree])
    -    print('Var:', variance[degree])
    -    print('{} >= {} + {} = {}'.format(error[degree], bias[degree], variance[degree], bias[degree]+variance[degree]))
    -
    -plt.plot(polydegree, error, label='Error')
    -plt.plot(polydegree, bias, label='bias')
    -plt.plot(polydegree, variance, label='Variance')
    -plt.legend()
    -plt.show()
    -
    -

    - - -

    Summing up

    - -

    -The bias-variance tradeoff summarizes the fundamental tension in -machine learning, particularly supervised learning, between the -complexity of a model and the amount of training data needed to train -it. Since data is often limited, in practice it is often useful to -use a less-complex model with higher bias, that is a model whose asymptotic -performance is worse than another model because it is easier to -train and less sensitive to sampling noise arising from having a -finite-sized training dataset (smaller variance). - -

    -The above equations tell us that in -order to minimize the expected test error, we need to select a -statistical learning method that simultaneously achieves low variance -and low bias. Note that variance is inherently a nonnegative quantity, -and squared bias is also nonnegative. Hence, we see that the expected -test MSE can never lie below \( Var(\epsilon) \), the irreducible error. - -

    -What do we mean by the variance and bias of a statistical learning -method? The variance refers to the amount by which our model would change if we -estimated it using a different training data set. Since the training -data are used to fit the statistical learning method, different -training data sets will result in a different estimate. But ideally the -estimate for our model should not vary too much between training -sets. However, if a method has high variance then small changes in -the training data can result in large changes in the model. In general, more -flexible statistical methods have higher variance. - -

    -You may also find this recent article of interest. - -

    -









    - -

    Another Example from Scikit-Learn's Repository

    -

    - - -

    """
    -============================
    -Underfitting vs. Overfitting
    -============================
    -
    -This example demonstrates the problems of underfitting and overfitting and
    -how we can use linear regression with polynomial features to approximate
    -nonlinear functions. The plot shows the function that we want to approximate,
    -which is a part of the cosine function. In addition, the samples from the
    -real function and the approximations of different models are displayed. The
    -models have polynomial features of different degrees. We can see that a
    -linear function (polynomial with degree 1) is not sufficient to fit the
    -training samples. This is called **underfitting**. A polynomial of degree 4
    -approximates the true function almost perfectly. However, for higher degrees
    -the model will **overfit** the training data, i.e. it learns the noise of the
    -training data.
    -We evaluate quantitatively **overfitting** / **underfitting** by using
    -cross-validation. We calculate the mean squared error (MSE) on the validation
    -set, the higher, the less likely the model generalizes correctly from the
    -training data.
    -"""
    -
    -print(__doc__)
    -
    -import numpy as np
    -import matplotlib.pyplot as plt
    -from sklearn.pipeline import Pipeline
    -from sklearn.preprocessing import PolynomialFeatures
    -from sklearn.linear_model import LinearRegression
    -from sklearn.model_selection import cross_val_score
    -
    -
    -def true_fun(X):
    -    return np.cos(1.5 * np.pi * X)
    -
    -np.random.seed(0)
    -
    -n_samples = 30
    -degrees = [1, 4, 15]
    -
    -X = np.sort(np.random.rand(n_samples))
    -y = true_fun(X) + np.random.randn(n_samples) * 0.1
    -
    -plt.figure(figsize=(14, 5))
    -for i in range(len(degrees)):
    -    ax = plt.subplot(1, len(degrees), i + 1)
    -    plt.setp(ax, xticks=(), yticks=())
    -
    -    polynomial_features = PolynomialFeatures(degree=degrees[i],
    -                                             include_bias=False)
    -    linear_regression = LinearRegression()
    -    pipeline = Pipeline([("polynomial_features", polynomial_features),
    -                         ("linear_regression", linear_regression)])
    -    pipeline.fit(X[:, np.newaxis], y)
    -
    -    # Evaluate the models using crossvalidation
    -    scores = cross_val_score(pipeline, X[:, np.newaxis], y,
    -                             scoring="neg_mean_squared_error", cv=10)
    -
    -    X_test = np.linspace(0, 1, 100)
    -    plt.plot(X_test, pipeline.predict(X_test[:, np.newaxis]), label="Model")
    -    plt.plot(X_test, true_fun(X_test), label="True function")
    -    plt.scatter(X, y, edgecolor='b', s=20, label="Samples")
    -    plt.xlabel("x")
    -    plt.ylabel("y")
    -    plt.xlim((0, 1))
    -    plt.ylim((-2, 2))
    -    plt.legend(loc="best")
    -    plt.title("Degree {}\nMSE = {:.2e}(+/- {:.2e})".format(
    -        degrees[i], -scores.mean(), scores.std()))
    -plt.show()
    -
    -

    - - -

    Various steps in cross-validation

    - -

    -When the repetitive splitting of the data set is done randomly, -samples may accidently end up in a fast majority of the splits in -either training or test set. Such samples may have an unbalanced -influence on either model building or prediction evaluation. To avoid -this \( k \)-fold cross-validation structures the data splitting. The -samples are divided into \( k \) more or less equally sized exhaustive and -mutually exclusive subsets. In turn (at each split) one of these -subsets plays the role of the test set while the union of the -remaining subsets constitutes the training set. Such a splitting -warrants a balanced representation of each sample in both training and -test set over the splits. Still the division into the \( k \) subsets -involves a degree of randomness. This may be fully excluded when -choosing \( k=n \). This particular case is referred to as leave-one-out -cross-validation (LOOCV). - -

    - - -

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

    - -
      -
    • Define a range of interest for the penalty parameter.
    • -
    • Divide the data set into training and test set comprising samples \( \{1, \ldots, n\} \setminus i \) and \( \{ i \} \), respectively.
    • -
    • Fit the linear regression model by means of ridge estimation for each \( \lambda \) in the grid using the training set, and the corresponding estimate of the error variance \( \boldsymbol{\sigma}_{-i}^2(\lambda) \), as
    • -
    - -$$ -\begin{align*} -\boldsymbol{\beta}_{-i}(\lambda) & = ( \boldsymbol{X}_{-i, \ast}^{T} -\boldsymbol{X}_{-i, \ast} + \lambda \boldsymbol{I}_{pp})^{-1} -\boldsymbol{X}_{-i, \ast}^{T} \boldsymbol{y}_{-i} -\end{align*} -$$ - - -
      -
    • Evaluate the prediction performance of these models on the test set by \( \log\{L[y_i, \boldsymbol{X}_{i, \ast}; \boldsymbol{\beta}_{-i}(\lambda), \boldsymbol{\sigma}_{-i}^2(\lambda)]\} \). Or, by the prediction error \( |y_i - \boldsymbol{X}_{i, \ast} \boldsymbol{\beta}_{-i}(\lambda)| \), the relative error, the error squared or the R2 score function.
    • -
    • Repeat the first three steps such that each sample plays the role of the test set once.
    • -
    • Average the prediction performances of the test sets at each grid point of the penalty bias/parameter. It is an estimate of the prediction performance of the model corresponding to this value of the penalty parameter on novel data. It is defined as
    • -
    - -$$ -\begin{align*} -\frac{1}{n} \sum_{i = 1}^n \log\{L[y_i, \mathbf{X}_{i, \ast}; \boldsymbol{\beta}_{-i}(\lambda), \boldsymbol{\sigma}_{-i}^2(\lambda)]\}. -\end{align*} -$$ - -

    -









    - -

    Cross-validation in brief

    - -

    -For the various values of \( k \) - -

      -
    1. shuffle the dataset randomly.
    2. -
    3. Split the dataset into \( k \) groups.
    4. -
    5. For each unique group: - -
        -
      1. Decide which group to use as set for test data
      2. -
      3. Take the remaining groups as a training data set
      4. -
      5. Fit a model on the training set and evaluate it on the test set
      6. -
      7. Retain the evaluation score and discard the model
      8. -
      - -
    6. Summarize the model using the sample of model evaluation scores
    7. -
    - -









    - -

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

    - -

    -The code here uses Ridge regression with cross-validation (CV) resampling and \( k \)-fold CV in order to fit a specific polynomial. -

    - - -

    import numpy as np
    -import matplotlib.pyplot as plt
    -from sklearn.model_selection import KFold
    -from sklearn.linear_model import Ridge
    -from sklearn.model_selection import cross_val_score
    -from sklearn.preprocessing import PolynomialFeatures
    -
    -# A seed just to ensure that the random numbers are the same for every run.
    -# Useful for eventual debugging.
    -np.random.seed(3155)
    -
    -# Generate the data.
    -nsamples = 100
    -x = np.random.randn(nsamples)
    -y = 3*x**2 + np.random.randn(nsamples)
    -
    -## Cross-validation on Ridge regression using KFold only
    -
    -# Decide degree on polynomial to fit
    -poly = PolynomialFeatures(degree = 6)
    -
    -# Decide which values of lambda to use
    -nlambdas = 500
    -lambdas = np.logspace(-3, 5, nlambdas)
    -
    -# Initialize a KFold instance
    -k = 5
    -kfold = KFold(n_splits = k)
    -
    -# Perform the cross-validation to estimate MSE
    -scores_KFold = np.zeros((nlambdas, k))
    -
    -i = 0
    -for lmb in lambdas:
    -    ridge = Ridge(alpha = lmb)
    -    j = 0
    -    for train_inds, test_inds in kfold.split(x):
    -        xtrain = x[train_inds]
    -        ytrain = y[train_inds]
    -
    -        xtest = x[test_inds]
    -        ytest = y[test_inds]
    -
    -        Xtrain = poly.fit_transform(xtrain[:, np.newaxis])
    -        ridge.fit(Xtrain, ytrain[:, np.newaxis])
    -
    -        Xtest = poly.fit_transform(xtest[:, np.newaxis])
    -        ypred = ridge.predict(Xtest)
    -
    -        scores_KFold[i,j] = np.sum((ypred - ytest[:, np.newaxis])**2)/np.size(ypred)
    -
    -        j += 1
    -    i += 1
    -
    -
    -estimated_mse_KFold = np.mean(scores_KFold, axis = 1)
    -
    -## Cross-validation using cross_val_score from sklearn along with KFold
    -
    -# kfold is an instance initialized above as:
    -# kfold = KFold(n_splits = k)
    -
    -estimated_mse_sklearn = np.zeros(nlambdas)
    -i = 0
    -for lmb in lambdas:
    -    ridge = Ridge(alpha = lmb)
    -
    -    X = poly.fit_transform(x[:, np.newaxis])
    -    estimated_mse_folds = cross_val_score(ridge, X, y[:, np.newaxis], scoring='neg_mean_squared_error', cv=kfold)
    -
    -    # cross_val_score return an array containing the estimated negative mse for every fold.
    -    # we have to the the mean of every array in order to get an estimate of the mse of the model
    -    estimated_mse_sklearn[i] = np.mean(-estimated_mse_folds)
    -
    -    i += 1
    -
    -## Plot and compare the slightly different ways to perform cross-validation
    -
    -plt.figure()
    -
    -plt.plot(np.log10(lambdas), estimated_mse_sklearn, label = 'cross_val_score')
    -plt.plot(np.log10(lambdas), estimated_mse_KFold, 'r--', label = 'KFold')
    -
    -plt.xlabel('log10(lambda)')
    -plt.ylabel('mse')
    -
    -plt.legend()
    -
    -plt.show()
    -
    -

    -









    - -

    More examples on bootstrap and cross-validation and errors

    - -

    - - -

    # Common imports
    -import os
    -import numpy as np
    -import pandas as pd
    -import matplotlib.pyplot as plt
    -from sklearn.linear_model import LinearRegression, Ridge, Lasso
    -from sklearn.model_selection import train_test_split
    -from sklearn.utils import resample
    -from sklearn.metrics import mean_squared_error
    -# Where to save the figures and data files
    -PROJECT_ROOT_DIR = "Results"
    -FIGURE_ID = "Results/FigureFiles"
    -DATA_ID = "DataFiles/"
    -
    -if not os.path.exists(PROJECT_ROOT_DIR):
    -    os.mkdir(PROJECT_ROOT_DIR)
    -
    -if not os.path.exists(FIGURE_ID):
    -    os.makedirs(FIGURE_ID)
    -
    -if not os.path.exists(DATA_ID):
    -    os.makedirs(DATA_ID)
    -
    -def image_path(fig_id):
    -    return os.path.join(FIGURE_ID, fig_id)
    -
    -def data_path(dat_id):
    -    return os.path.join(DATA_ID, dat_id)
    -
    -def save_fig(fig_id):
    -    plt.savefig(image_path(fig_id) + ".png", format='png')
    -
    -infile = open(data_path("EoS.csv"),'r')
    -
    -# Read the EoS data as  csv file and organize the data into two arrays with density and energies
    -EoS = pd.read_csv(infile, names=('Density', 'Energy'))
    -EoS['Energy'] = pd.to_numeric(EoS['Energy'], errors='coerce')
    -EoS = EoS.dropna()
    -Energies = EoS['Energy']
    -Density = EoS['Density']
    -#  The design matrix now as function of various polytrops
    -
    -Maxpolydegree = 30
    -X = np.zeros((len(Density),Maxpolydegree))
    -X[:,0] = 1.0
    -testerror = np.zeros(Maxpolydegree)
    -trainingerror = np.zeros(Maxpolydegree)
    -polynomial = np.zeros(Maxpolydegree)
    -
    -trials = 100
    -for polydegree in range(1, Maxpolydegree):
    -    polynomial[polydegree] = polydegree
    -    for degree in range(polydegree):
    -        X[:,degree] = Density**(degree/3.0)
    -
    -# loop over trials in order to estimate the expectation value of the MSE
    -    testerror[polydegree] = 0.0
    -    trainingerror[polydegree] = 0.0
    -    for samples in range(trials):
    -        x_train, x_test, y_train, y_test = train_test_split(X, Energies, test_size=0.2)
    -        model = LinearRegression(fit_intercept=True).fit(x_train, y_train)
    -        ypred = model.predict(x_train)
    -        ytilde = model.predict(x_test)
    -        testerror[polydegree] += mean_squared_error(y_test, ytilde)
    -        trainingerror[polydegree] += mean_squared_error(y_train, ypred) 
    -
    -    testerror[polydegree] /= trials
    -    trainingerror[polydegree] /= trials
    -    print("Degree of polynomial: %3d"% polynomial[polydegree])
    -    print("Mean squared error on training data: %.8f" % trainingerror[polydegree])
    -    print("Mean squared error on test data: %.8f" % testerror[polydegree])
    -
    -plt.plot(polynomial, np.log10(trainingerror), label='Training Error')
    -plt.plot(polynomial, np.log10(testerror), label='Test Error')
    -plt.xlabel('Polynomial degree')
    -plt.ylabel('log10[MSE]')
    -plt.legend()
    -plt.show()
    -
    -

    - - -

    The same example but now with cross-validation

    - -

    - - -

    # Common imports
    -import os
    -import numpy as np
    -import pandas as pd
    -import matplotlib.pyplot as plt
    -from sklearn.linear_model import LinearRegression, Ridge, Lasso
    -from sklearn.metrics import mean_squared_error
    -from sklearn.model_selection import KFold
    -from sklearn.model_selection import cross_val_score
    -
    -
    -# Where to save the figures and data files
    -PROJECT_ROOT_DIR = "Results"
    -FIGURE_ID = "Results/FigureFiles"
    -DATA_ID = "DataFiles/"
    -
    -if not os.path.exists(PROJECT_ROOT_DIR):
    -    os.mkdir(PROJECT_ROOT_DIR)
    -
    -if not os.path.exists(FIGURE_ID):
    -    os.makedirs(FIGURE_ID)
    -
    -if not os.path.exists(DATA_ID):
    -    os.makedirs(DATA_ID)
    -
    -def image_path(fig_id):
    -    return os.path.join(FIGURE_ID, fig_id)
    -
    -def data_path(dat_id):
    -    return os.path.join(DATA_ID, dat_id)
    -
    -def save_fig(fig_id):
    -    plt.savefig(image_path(fig_id) + ".png", format='png')
    -
    -infile = open(data_path("EoS.csv"),'r')
    -
    -# Read the EoS data as  csv file and organize the data into two arrays with density and energies
    -EoS = pd.read_csv(infile, names=('Density', 'Energy'))
    -EoS['Energy'] = pd.to_numeric(EoS['Energy'], errors='coerce')
    -EoS = EoS.dropna()
    -Energies = EoS['Energy']
    -Density = EoS['Density']
    -#  The design matrix now as function of various polytrops
    -
    -Maxpolydegree = 30
    -X = np.zeros((len(Density),Maxpolydegree))
    -X[:,0] = 1.0
    -estimated_mse_sklearn = np.zeros(Maxpolydegree)
    -polynomial = np.zeros(Maxpolydegree)
    -k =5
    -kfold = KFold(n_splits = k)
    -
    -for polydegree in range(1, Maxpolydegree):
    -    polynomial[polydegree] = polydegree
    -    for degree in range(polydegree):
    -        X[:,degree] = Density**(degree/3.0)
    -        OLS = LinearRegression()
    -# loop over trials in order to estimate the expectation value of the MSE
    -    estimated_mse_folds = cross_val_score(OLS, X, Energies, scoring='neg_mean_squared_error', cv=kfold)
    -#[:, np.newaxis]
    -    estimated_mse_sklearn[polydegree] = np.mean(-estimated_mse_folds)
    -
    -plt.plot(polynomial, np.log10(estimated_mse_sklearn), label='Test Error')
    -plt.xlabel('Polynomial degree')
    -plt.ylabel('log10[MSE]')
    -plt.legend()
    -plt.show()
    -
    -

    -









    - -

    Cross-validation with Ridge

    -

    - - -

    import numpy as np
    -import matplotlib.pyplot as plt
    -from sklearn.model_selection import KFold
    -from sklearn.linear_model import Ridge
    -from sklearn.model_selection import cross_val_score
    -from sklearn.preprocessing import PolynomialFeatures
    -
    -# A seed just to ensure that the random numbers are the same for every run.
    -np.random.seed(3155)
    -# Generate the data.
    -n = 100
    -x = np.linspace(-3, 3, n).reshape(-1, 1)
    -y = np.exp(-x**2) + 1.5 * np.exp(-(x-2)**2)+ np.random.normal(0, 0.1, x.shape)
    -# Decide degree on polynomial to fit
    -poly = PolynomialFeatures(degree = 10)
    -
    -# Decide which values of lambda to use
    -nlambdas = 500
    -lambdas = np.logspace(-3, 5, nlambdas)
    -# Initialize a KFold instance
    -k = 5
    -kfold = KFold(n_splits = k)
    -estimated_mse_sklearn = np.zeros(nlambdas)
    -i = 0
    -for lmb in lambdas:
    -    ridge = Ridge(alpha = lmb)
    -    estimated_mse_folds = cross_val_score(ridge, x, y, scoring='neg_mean_squared_error', cv=kfold)
    -    estimated_mse_sklearn[i] = np.mean(-estimated_mse_folds)
    -    i += 1
    -plt.figure()
    -plt.plot(np.log10(lambdas), estimated_mse_sklearn, label = 'cross_val_score')
    -plt.xlabel('log10(lambda)')
    -plt.ylabel('MSE')
    -plt.legend()
    -plt.show()
    -
    -

    - - - - -

    - © 1999-2021, Morten Hjorth-Jensen. Released under CC Attribution-NonCommercial 4.0 license -
    - - - - - - diff --git a/doc/src/week37/week37.ipynb b/doc/src/week37/week37.ipynb deleted file mode 100644 index 59ea57c5a..000000000 --- a/doc/src/week37/week37.ipynb +++ /dev/null @@ -1,2095 +0,0 @@ -{ - "cells": [ - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "\n", - "# Week 37: Summary of Ridge and Lasso Regression and Resampling Methods\n", - "\n", - " \n", - "**Morten Hjorth-Jensen**, Department of Physics, University of Oslo and Department of Physics and Astronomy and National Superconducting Cyclotron Laboratory, Michigan State University\n", - "\n", - "Date: **Sep 16, 2021**\n", - "\n", - "Copyright 1999-2021, Morten Hjorth-Jensen. Released under CC Attribution-NonCommercial 4.0 license\n", - "\n", - "\n", - "\n", - "## Plans for week 37\n", - "\n", - "* Thursday September 16: Summary of Ridge and Lasso with examples and start resampling techniques\n", - "\n", - "* Friday September 17: Resampling methods, Cross-validation, Bootstrapping and jackknife\n", - "\n", - "Recommended Reading:\n", - "1. Lectures on Resampling methods (these lectures)\n", - "\n", - "2. Bishop 1.3 (cross-validation) and 3.2 (bias-variance tradeoff)\n", - "\n", - "3. Hastie et al Chapter 7, here we recommend 7.1-7.5 and 7.10 (cross-validation) and 7.11 (bootstrap). This chapter is better than Bishop's on these topics. Goodfellow et al discuss this in a superficial way in sections 5.2-5.5.\n", - "\n", - "## Thursday September 16, Summary of Ridge and Lasso Regression and start Resampling methods\n", - "\n", - "\n", - "## Deriving OLS from a probability distribution\n", - "\n", - "Our basic assumption when we derived the OLS equations was to assume\n", - "that our output is determined by a given continuous function\n", - "$f(\\boldsymbol{x})$ and a random noise $\\boldsymbol{\\epsilon}$ given by the normal\n", - "distribution with zero mean value and an undetermined variance\n", - "$\\sigma^2$.\n", - "\n", - "We found above that the outputs $\\boldsymbol{y}$ have a mean value given by\n", - "$\\boldsymbol{X}\\hat{\\boldsymbol{\\beta}}$ and variance $\\sigma^2$. Since the entries to\n", - "the design matrix are not stochastic variables, we can assume that the\n", - "probability distribution of our targets is also a normal distribution\n", - "but now with mean value $\\boldsymbol{X}\\hat{\\boldsymbol{\\beta}}$. This means that a\n", - "single output $y_i$ is given by the Gaussian distribution" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "y_i\\sim \\mathcal{N}(\\boldsymbol{X}_{i,*}\\boldsymbol{\\beta}, \\sigma^2)=\\frac{1}{\\sqrt{2\\pi\\sigma^2}}\\exp{\\left[-\\frac{(y_i-\\boldsymbol{X}_{i,*}\\boldsymbol{\\beta})^2}{2\\sigma^2}\\right]}.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "## Independent and Identically Distrubuted (iid)\n", - "\n", - "We assume now that the various $y_i$ values are stochastically distributed according to the above Gaussian distribution. \n", - "We define this distribution as" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "p(y_i, \\boldsymbol{X}\\vert\\boldsymbol{\\beta})=\\frac{1}{\\sqrt{2\\pi\\sigma^2}}\\exp{\\left[-\\frac{(y_i-\\boldsymbol{X}_{i,*}\\boldsymbol{\\beta})^2}{2\\sigma^2}\\right]},\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "which reads as finding the likelihood of an event $y_i$ with the input variables $\\boldsymbol{X}$ given the parameters (to be determined) $\\boldsymbol{\\beta}$.\n", - "\n", - "Since these events are assumed to be independent and identicall distributed we can build the probability distribution function (PDF) for all possible event $\\boldsymbol{y}$ as the product of the single events, that is we have" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "p(\\boldsymbol{y},\\boldsymbol{X}\\vert\\boldsymbol{\\beta})=\\prod_{i=0}^{n-1}\\frac{1}{\\sqrt{2\\pi\\sigma^2}}\\exp{\\left[-\\frac{(y_i-\\boldsymbol{X}_{i,*}\\boldsymbol{\\beta})^2}{2\\sigma^2}\\right]}=\\prod_{i=0}^{n-1}p(y_i,\\boldsymbol{X}\\vert\\boldsymbol{\\beta}).\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "We will write this in a more compact form reserving $\\boldsymbol{D}$ for the domain of events, including the ouputs (targets) and the inputs. That is\n", - "in case we have a simple one-dimensional input and output case" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "\\boldsymbol{D}=[(x_0,y_0), (x_1,y_1),\\dots, (x_{n-1},y_{n-1})].\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "In the more general case the various inputs should be replaced by the possible features represented by the input data set $\\boldsymbol{X}$. \n", - "We can now rewrite the above probability as" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "p(\\boldsymbol{D}\\vert\\boldsymbol{\\beta})=\\prod_{i=0}^{n-1}\\frac{1}{\\sqrt{2\\pi\\sigma^2}}\\exp{\\left[-\\frac{(y_i-\\boldsymbol{X}_{i,*}\\boldsymbol{\\beta})^2}{2\\sigma^2}\\right]}.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "It is a conditional probability (see below) and reads as the likelihood of a domain of events $\\boldsymbol{D}$ given a set of parameters $\\boldsymbol{\\beta}$.\n", - "\n", - "## Maximum Likelihood Estimation (MLE)\n", - "\n", - "In statistics, maximum likelihood estimation (MLE) is a method of\n", - "estimating the parameters of an assumed probability distribution,\n", - "given some observed data. This is achieved by maximizing a likelihood\n", - "function so that, under the assumed statistical model, the observed\n", - "data is the most probable. \n", - "\n", - "\n", - "We will assume here that our events are given by the above Gaussian\n", - "distribution and we will determine the optimal parameters $\\beta$ by\n", - "maximizing the above PDF. However, computing the derivatives of a\n", - "product function is cumbersome and can easily lead to overflow and/or\n", - "underflowproblems, with potentials for loss of numerical precision.\n", - "\n", - "\n", - "In practice, it is more convenient to maximize the logarithm of the\n", - "PDF because it is a monotonically increasing function of the argument.\n", - "Alternatively, and this will be our option, we will minimize the\n", - "negative of the logarithm since this is a monotonically decreasing\n", - "function.\n", - "\n", - "Note also that maximization/minimization of the logarithm of the PDF\n", - "is equivalent to the maximization/minimization of the function itself.\n", - "\n", - "\n", - "\n", - "## A new Cost Function\n", - "\n", - "We could now define a new cost function to minimize, namely the negative logarithm of the above PDF" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "C(\\boldsymbol{\\beta}=-\\log{\\prod_{i=0}^{n-1}p(y_i,\\boldsymbol{X}\\vert\\boldsymbol{\\beta})}=-\\sum_{i=0}^{n-1}\\log{p(y_i,\\boldsymbol{X}\\vert\\boldsymbol{\\beta})},\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "which becomes" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "C(\\boldsymbol{\\beta}=\\frac{n}{2}\\log{2\\pi\\sigma^2}+\\frac{\\vert\\vert (\\boldsymbol{y}-\\boldsymbol{X}\\boldsymbol{\\beta})\\vert\\vert_2^2}{2\\sigma^2}.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "Taking the derivative of the *new* cost function with respect to the parameters $\\beta$ we recognize our familiar OLS equation, namely" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "\\boldsymbol{X}^T\\left(\\boldsymbol{y}-\\boldsymbol{X}\\boldsymbol{\\beta}\\right) =0,\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "which leads to the well-known OLS equation for the optimal paramters $\\beta$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "\\hat{\\boldsymbol{\\beta}}^{\\mathrm{OLS}}=\\left(\\boldsymbol{X}^T\\boldsymbol{X}\\right)^{-1}\\boldsymbol{X}^T\\boldsymbol{y}!\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "## Bayes' Theorem\n", - "\n", - "If we combine the conditional probability with the marginal probability and the standard product rule, we have" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "p(X\\vert Y)= \\frac{p(X,Y)}{p(Y)},\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "which we can rewrite as" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "p(X\\vert Y)= \\frac{p(X,Y)}{\\sum_{i=0}^{n-1}p(Y\\vert X=x_i)p(x_i)}=\\frac{p(Y\\vert X)p(X)}{\\sum_{i=0}^{n-1}p(Y\\vert X=x_i)p(x_i)},\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "which is Bayes' theorem. It allows us to evaluate the uncertainty in in $X$ after we have observed $Y$. We can easily interchange $X$ with $Y$. \n", - "\n", - "## Interpretations of Bayes' Theorem\n", - "\n", - "The quantity $p(Y\\vert X)$ on the right-hand side of the theorem is\n", - "evaluated for the observed data $Y$ and can be viewed as a function of\n", - "the parameter space represented by $X$. This function is not\n", - "necesseraly normalized and is normally called the likelihood function.\n", - "\n", - "The function $p(X)$ on the right hand side is called the prior while the function on the left hand side is the called the posterior probability. The denominator on the right hand side serves as a normalization factor for the posterior distribution.\n", - "\n", - "## Test Function for what happens with OLS, Ridge and Lasso\n", - "\n", - "We will play around with a study of the values for the optimal\n", - "parameters $\\boldsymbol{\\beta}$ using OLS, Ridge and Lasso regression. For\n", - "OLS, you will notice as function of the noise and polynomial degree,\n", - "that the parameters $\\beta$ will fluctuate from order to order in the\n", - "polynomial fit and that for larger and larger polynomial degrees of freedom, the parameters will tend to increase in value for OLS.\n", - "\n", - "For Ridge and Lasso regression, the higher order parameters will typically be reduced, providing thereby less fluctuations from one order to another one." - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": false, - "editable": true - }, - "outputs": [], - "source": [ - "%matplotlib inline\n", - "\n", - "import numpy as np\n", - "import matplotlib.pyplot as plt\n", - "from sklearn.model_selection import train_test_split\n", - "from sklearn import linear_model\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", - "# Make data set.\n", - "n = 10000\n", - "x = np.random.rand(n)\n", - "y = np.exp(-x**2) + 1.5 * np.exp(-(x-2)**2)+ np.random.randn(n)\n", - "\n", - "Maxpolydegree = 5\n", - "X = np.zeros((len(x),Maxpolydegree))\n", - "X[:,0] = 1.0\n", - "\n", - "for polydegree in range(1, Maxpolydegree):\n", - " for degree in range(polydegree):\n", - " X[:,degree] = x**(degree)\n", - "\n", - "\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.pinv(X_train.T @ X_train) @ X_train.T @ y_train\n", - "print(OLSbeta)\n", - "ypredictOLS = X_test @ OLSbeta\n", - "print(\"Test MSE OLS\")\n", - "print(MSE(y_test,ypredictOLS))\n", - "# Repeat now for Lasso and Ridge regression and various values of the regularization parameter using Scikit-Learn\n", - "# Decide which values of lambda to use\n", - "nlambdas = 4\n", - "MSERidgePredict = np.zeros(nlambdas)\n", - "MSELassoPredict = np.zeros(nlambdas)\n", - "lambdas = np.logspace(-3, 1, nlambdas)\n", - "for i in range(nlambdas):\n", - " lmb = lambdas[i]\n", - " # Make the fit using Ridge and Lasso\n", - " RegRidge = linear_model.Ridge(lmb,fit_intercept=False)\n", - " RegRidge.fit(X_train,y_train)\n", - " RegLasso = linear_model.Lasso(lmb,fit_intercept=False)\n", - " RegLasso.fit(X_train,y_train)\n", - " # and then make the prediction\n", - " ypredictRidge = RegRidge.predict(X_test)\n", - " ypredictLasso = RegLasso.predict(X_test)\n", - " # Compute the MSE and print it\n", - " MSERidgePredict[i] = MSE(y_test,ypredictRidge)\n", - " MSELassoPredict[i] = MSE(y_test,ypredictLasso)\n", - " print(lmb,RegRidge.coef_)\n", - " print(lmb,RegLasso.coef_)\n", - "# Now plot the results\n", - "plt.figure()\n", - "plt.plot(np.log10(lambdas), MSERidgePredict, 'b', label = 'MSE Ridge Test')\n", - "plt.plot(np.log10(lambdas), MSELassoPredict, 'r', label = 'MSE Lasso Test')\n", - "plt.xlabel('log10(lambda)')\n", - "plt.ylabel('MSE')\n", - "plt.legend()\n", - "plt.show()" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "How can we understand this? \n", - "\n", - "\n", - "## Rerunning the above code\n", - "\n", - "Let us write out the values of the coefficients $\\beta_i$ as functions\n", - "of the polynomial degree and noise. We will focus only on the Ridge\n", - "results and some few selected values of the hyperparameter $\\lambda$.\n", - "\n", - "If we don't include any noise and run this code for different values\n", - "of the polynomial degree, we notice that the results for $\\beta_i$ do\n", - "not show great changes from one order to the next. This is an\n", - "indication that for higher polynomial orders, our parameters become\n", - "less important.\n", - "\n", - "If we however add noise, what happens is that the polynomial fit is\n", - "trying to adjust the fit to traverse in the best possible way all data\n", - "points. This can lead to large fluctuations in the parameters\n", - "$\\beta_i$ as functions of polynomial order. It will also be reflected\n", - "in a larger value of the variance of each parameter $\\beta_i$. What\n", - "Ridge regression (and Lasso as well) are doing then is to try to\n", - "quench the fluctuations in the parameters of $\\beta_i$ which have a\n", - "large variance (normally for higher orders in the polynomial)." - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": false, - "editable": true - }, - "outputs": [], - "source": [ - "import numpy as np\n", - "import pandas as pd\n", - "from IPython.display import display\n", - "import matplotlib.pyplot as plt\n", - "from sklearn.model_selection import train_test_split\n", - "from sklearn import linear_model\n", - "\n", - "# Make data set.\n", - "n = 1000\n", - "x = np.random.rand(n)\n", - "y = np.exp(-x**2) + 1.5 * np.exp(-(x-2)**2)+ np.random.randn(n)\n", - "\n", - "Maxpolydegree = 5\n", - "X = np.zeros((len(x),Maxpolydegree))\n", - "X[:,0] = 1.0\n", - "\n", - "for polydegree in range(1, Maxpolydegree):\n", - " for degree in range(polydegree):\n", - " X[:,degree] = x**(degree)\n", - "\n", - "\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", - "# Decide which values of lambda to use\n", - "nlambdas = 5\n", - "lambdas = np.logspace(-3, 2, nlambdas)\n", - "for i in range(nlambdas):\n", - " lmb = lambdas[i]\n", - " # Make the fit using Ridge only\n", - " RegRidge = linear_model.Ridge(lmb,fit_intercept=False)\n", - " RegRidge.fit(X_train,y_train)\n", - " # and then make the prediction\n", - " ypredictRidge = RegRidge.predict(X_test)\n", - " Coeffs = np.array(RegRidge.coef_)\n", - " BetaValues = pd.DataFrame(Coeffs)\n", - " BetaValues.columns = ['beta']\n", - " display(BetaValues)" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "## Invoking Bayes' theorem\n", - "\n", - "Using Bayes' theorem we can gain a better intuition about Ridge and Lasso regression. \n", - "\n", - "For ordinary least squares we postulated that the maximum likelihood for the doamin of events $\\boldsymbol{D}$ (one-dimensional case)" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "\\boldsymbol{D}=[(x_0,y_0), (x_1,y_1),\\dots, (x_{n-1},y_{n-1})],\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "is given by" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "p(\\boldsymbol{D}\\vert\\boldsymbol{\\beta})=\\prod_{i=0}^{n-1}\\frac{1}{\\sqrt{2\\pi\\sigma^2}}\\exp{\\left[-\\frac{(y_i-\\boldsymbol{X}_{i,*}\\boldsymbol{\\beta})^2}{2\\sigma^2}\\right]}.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "In Bayes' theorem this function plays the role of the so-called likelihood. We could now ask the question what is the posterior probability of a parameter set $\\boldsymbol{\\beta}$ given a domain of events $\\boldsymbol{D}$? That is, how can we define the posterior probability" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "p(\\boldsymbol{\\beta}\\vert\\boldsymbol{D}).\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "Bayes' theorem comes to our rescue here since (omitting the normalization constant)" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "p(\\boldsymbol{\\beta}\\vert\\boldsymbol{D})\\propto p(\\boldsymbol{D}\\vert\\boldsymbol{\\beta})p(\\boldsymbol{\\beta}).\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "We have a model for $p(\\boldsymbol{D}\\vert\\boldsymbol{\\beta})$ but need one for the **prior** $p(\\boldsymbol{\\beta}$! \n", - "\n", - "\n", - "## Ridge and Bayes\n", - "\n", - "With the posterior probability defined by a likelihood which we have\n", - "already modeled and an unknown prior, we are now ready to make\n", - "additional models for the prior.\n", - "\n", - "We can, based on our discussions of the variance of $\\boldsymbol{\\beta}$ and the mean value, assume that the prior for the values $\\boldsymbol{\\beta}$ is given by a Gaussian with mean value zero and variance $\\tau^2$, that is" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "p(\\boldsymbol{\\beta})=\\prod_{j=0}^{p-1}\\exp{\\left(-\\frac{\\beta_j^2}{2\\tau^2}\\right)}.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "Our posterior probability becomes then (omitting the normalization factor which is just a constant)" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "p(\\boldsymbol{\\beta\\vert\\boldsymbol{D})}=\\prod_{i=0}^{n-1}\\frac{1}{\\sqrt{2\\pi\\sigma^2}}\\exp{\\left[-\\frac{(y_i-\\boldsymbol{X}_{i,*}\\boldsymbol{\\beta})^2}{2\\sigma^2}\\right]}\\prod_{j=0}^{p-1}\\exp{\\left(-\\frac{\\beta_j^2}{2\\tau^2}\\right)}.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "We can now optimize this quantity with respect to $\\boldsymbol{\\beta}$. As we\n", - "did for OLS, this is most conveniently done by taking the negative\n", - "logarithm of the posterior probability. Doing so and leaving out the\n", - "constants terms that do not depend on $\\beta$, we have" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "C(\\boldsymbol{\\beta})=\\frac{\\vert\\vert (\\boldsymbol{y}-\\boldsymbol{X}\\boldsymbol{\\beta})\\vert\\vert_2^2}{2\\sigma^2}+\\frac{1}{2\\tau^2}\\vert\\vert\\boldsymbol{\\beta}\\vert\\vert_2^2,\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "and replacing $1/2\\tau^2$ with $\\lambda$ we have" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "C(\\boldsymbol{\\beta})=\\frac{\\vert\\vert (\\boldsymbol{y}-\\boldsymbol{X}\\boldsymbol{\\beta})\\vert\\vert_2^2}{2\\sigma^2}+\\lambda\\vert\\vert\\boldsymbol{\\beta}\\vert\\vert_2^2,\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "which is our Ridge cost function! Nice, isn't it?\n", - "\n", - "## Lasso and Bayes\n", - "\n", - "To derive the Lasso cost function, we simply replace the Gaussian prior with an exponential distribution ([Laplace in this case](https://en.wikipedia.org/wiki/Laplace_distribution)) with zero mean value, that is" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "p(\\boldsymbol{\\beta})=\\prod_{j=0}^{p-1}\\exp{\\left(-\\frac{\\vert\\beta_j\\vert}{\\tau}\\right)}.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "Our posterior probability becomes then (omitting the normalization factor which is just a constant)" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "p(\\boldsymbol{\\beta}\\vert\\boldsymbol{D})=\\prod_{i=0}^{n-1}\\frac{1}{\\sqrt{2\\pi\\sigma^2}}\\exp{\\left[-\\frac{(y_i-\\boldsymbol{X}_{i,*}\\boldsymbol{\\beta})^2}{2\\sigma^2}\\right]}\\prod_{j=0}^{p-1}\\exp{\\left(-\\frac{\\vert\\beta_j\\vert}{\\tau}\\right)}.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "Taking the negative\n", - "logarithm of the posterior probability and leaving out the\n", - "constants terms that do not depend on $\\beta$, we have" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "C(\\boldsymbol{\\beta}=\\frac{\\vert\\vert (\\boldsymbol{y}-\\boldsymbol{X}\\boldsymbol{\\beta})\\vert\\vert_2^2}{2\\sigma^2}+\\frac{1}{\\tau}\\vert\\vert\\boldsymbol{\\beta}\\vert\\vert_1,\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "and replacing $1/\\tau$ with $\\lambda$ we have" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "C(\\boldsymbol{\\beta}=\\frac{\\vert\\vert (\\boldsymbol{y}-\\boldsymbol{X}\\boldsymbol{\\beta})\\vert\\vert_2^2}{2\\sigma^2}+\\lambda\\vert\\vert\\boldsymbol{\\beta}\\vert\\vert_1,\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "which is our Lasso cost function! \n", - "\n", - "\n", - "\n", - "## Why resampling methods\n", - "\n", - "Before we proceed, we need to rethink what we have been doing. In our\n", - "eager to fit the data, we have omitted several important elements in\n", - "our regression analysis. In what follows we will\n", - "1. look at statistical properties, including a discussion of mean values, variance and the so-called bias-variance tradeoff\n", - "\n", - "2. introduce resampling techniques like cross-validation, bootstrapping and jackknife and more\n", - "\n", - "and discuss how to select a given model (one of the difficult parts in machine learning).\n", - "\n", - "\n", - "\n", - "\n", - "\n", - "## Resampling methods\n", - "Resampling methods are an indispensable tool in modern\n", - "statistics. They involve repeatedly drawing samples from a training\n", - "set and refitting a model of interest on each sample in order to\n", - "obtain additional information about the fitted model. For example, in\n", - "order to estimate the variability of a linear regression fit, we can\n", - "repeatedly draw different samples from the training data, fit a linear\n", - "regression to each new sample, and then examine the extent to which\n", - "the resulting fits differ. Such an approach may allow us to obtain\n", - "information that would not be available from fitting the model only\n", - "once using the original training sample.\n", - "\n", - "Two resampling methods are often used in Machine Learning analyses,\n", - "1. The **bootstrap method**\n", - "\n", - "2. and **Cross-Validation**\n", - "\n", - "In addition there are several other methods such as the Jackknife and the Blocking methods. We will discuss in particular\n", - "cross-validation and the bootstrap method.\n", - "\n", - "\n", - "\n", - "\n", - "## Resampling approaches can be computationally expensive\n", - "\n", - "Resampling approaches can be computationally expensive, because they\n", - "involve fitting the same statistical method multiple times using\n", - "different subsets of the training data. However, due to recent\n", - "advances in computing power, the computational requirements of\n", - "resampling methods generally are not prohibitive. In this chapter, we\n", - "discuss two of the most commonly used resampling methods,\n", - "cross-validation and the bootstrap. Both methods are important tools\n", - "in the practical application of many statistical learning\n", - "procedures. For example, cross-validation can be used to estimate the\n", - "test error associated with a given statistical learning method in\n", - "order to evaluate its performance, or to select the appropriate level\n", - "of flexibility. The process of evaluating a model’s performance is\n", - "known as model assessment, whereas the process of selecting the proper\n", - "level of flexibility for a model is known as model selection. The\n", - "bootstrap is widely used.\n", - "\n", - "\n", - "\n", - "## Why resampling methods ?\n", - "**Statistical analysis.**\n", - "\n", - "\n", - "* Our simulations can be treated as *computer experiments*. This is particularly the case for Monte Carlo methods which are widely used in statistical analyses.\n", - "\n", - "* The results can be analysed with the same statistical tools as we would use when analysing experimental data.\n", - "\n", - "* As in all experiments, we are looking for expectation values and an estimate of how accurate they are, i.e., possible sources for errors.\n", - "\n", - " \n", - "\n", - "## Statistical analysis\n", - "\n", - "* As in other experiments, many numerical experiments have two classes of errors:\n", - "\n", - " * Statistical errors\n", - "\n", - " * Systematical errors\n", - "\n", - "\n", - "* Statistical errors can be estimated using standard tools from statistics\n", - "\n", - "* Systematical errors are method specific and must be treated differently from case to case.\n", - "\n", - " \n", - "\n", - "\n", - "\n", - "\n", - "\n", - "## Resampling methods\n", - "\n", - "With all these analytical equations for both the OLS and Ridge\n", - "regression, we will now outline how to assess a given model. This will\n", - "lead to a discussion of the so-called bias-variance tradeoff (see\n", - "below) and so-called resampling methods.\n", - "\n", - "One of the quantities we have discussed as a way to measure errors is\n", - "the mean-squared error (MSE), mainly used for fitting of continuous\n", - "functions. Another choice is the absolute error.\n", - "\n", - "In the discussions below we will focus on the MSE and in particular since we will split the data into test and training data,\n", - "we discuss the\n", - "1. prediction error or simply the **test error** $\\mathrm{Err_{Test}}$, where we have a fixed training set and the test error is the MSE arising from the data reserved for testing. We discuss also the \n", - "\n", - "2. training error $\\mathrm{Err_{Train}}$, which is the average loss over the training data.\n", - "\n", - "As our model becomes more and more complex, more of the training data tends to used. The training may thence adapt to more complicated structures in the data. This may lead to a decrease in the bias (see below for code example) and a slight increase of the variance for the test error.\n", - "For a certain level of complexity the test error will reach minimum, before starting to increase again. The\n", - "training error reaches a saturation.\n", - "\n", - "\n", - "\n", - "\n", - "## Resampling methods: Jackknife and Bootstrap\n", - "\n", - "Two famous\n", - "resampling methods are the **independent bootstrap** and **the jackknife**. \n", - "\n", - "The jackknife is a special case of the independent bootstrap. Still, the jackknife was made\n", - "popular prior to the independent bootstrap. And as the popularity of\n", - "the independent bootstrap soared, new variants, such as **the dependent bootstrap** have also been developed..\n", - "\n", - "The Jackknife and independent bootstrap work for\n", - "independent, identically distributed random variables.\n", - "If these conditions are not\n", - "satisfied, the methods will fail. Yet, it should be said that if the data are\n", - "independent, identically distributed, and we only want to estimate the\n", - "variance of $\\overline{X}$ (which often is the case), then there is no\n", - "need for bootstrapping. \n", - "\n", - "## Resampling methods: Jackknife\n", - "\n", - "The Jackknife works by making many replicas of the estimator $\\widehat{\\beta}$. \n", - "The jackknife is a resampling method where we systematically leave out one observation from the vector of observed values $\\boldsymbol{x} = (x_1,x_2,\\cdots,X_n)$. \n", - "Let $\\boldsymbol{x}_i$ denote the vector" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "\\boldsymbol{x}_i = (x_1,x_2,\\cdots,x_{i-1},x_{i+1},\\cdots,x_n),\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "which equals the vector $\\boldsymbol{x}$ with the exception that observation\n", - "number $i$ is left out. Using this notation, define\n", - "$\\widehat{\\beta}_i$ to be the estimator\n", - "$\\widehat{\\beta}$ computed using $\\vec{X}_i$. \n", - "\n", - "\n", - "## Jackknife code example" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": false, - "editable": true - }, - "outputs": [], - "source": [ - "from numpy import *\n", - "from numpy.random import randint, randn\n", - "from time import time\n", - "\n", - "def jackknife(data, stat):\n", - " n = len(data);t = zeros(n); inds = arange(n); t0 = time()\n", - " ## 'jackknifing' by leaving out an observation for each i \n", - " for i in range(n):\n", - " t[i] = stat(delete(data,i) )\n", - "\n", - " # analysis \n", - " print(\"Runtime: %g sec\" % (time()-t0)); print(\"Jackknife Statistics :\")\n", - " print(\"original bias std. error\")\n", - " print(\"%8g %14g %15g\" % (stat(data),(n-1)*mean(t)/n, (n*var(t))**.5))\n", - "\n", - " return t\n", - "\n", - "\n", - "# Returns mean of data samples \n", - "def stat(data):\n", - " return mean(data)\n", - "\n", - "\n", - "mu, sigma = 100, 15\n", - "datapoints = 10000\n", - "x = mu + sigma*random.randn(datapoints)\n", - "# jackknife returns the data sample \n", - "t = jackknife(x, stat)" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "## Resampling methods: Bootstrap\n", - "Bootstrapping is a non-parametric approach to statistical inference\n", - "that substitutes computation for more traditional distributional\n", - "assumptions and asymptotic results. Bootstrapping offers a number of\n", - "advantages: \n", - "1. The bootstrap is quite general, although there are some cases in which it fails. \n", - "\n", - "2. Because it does not require distributional assumptions (such as normally distributed errors), the bootstrap can provide more accurate inferences when the data are not well behaved or when the sample size is small. \n", - "\n", - "3. It is possible to apply the bootstrap to statistics with sampling distributions that are difficult to derive, even asymptotically. \n", - "\n", - "4. It is relatively simple to apply the bootstrap to complex data-collection plans (such as stratified and clustered samples).\n", - "\n", - "\n", - "\n", - "The textbook by [Davison on the Bootstrap Methods and their Applications](https://www.cambridge.org/core/books/bootstrap-methods-and-their-application/ED2FD043579F27952363566DC09CBD6A) provides many more insights and proofs. In this course we will take a more practical approach and use the results and theorems provided in the literature. For those interested in reading more about the bootstrap methods, we recommend the above text and the one by [Efron and Tibshirani](https://www.routledge.com/An-Introduction-to-the-Bootstrap/Efron-Tibshirani/p/book/9780412042317).\n", - "\n", - "\n", - "Before we proceed however, we need to remind ourselves about a central theorem in statistics, namely the so-called **central limit theorem**.\n", - "\n", - "## The Central Limit Theorem\n", - "\n", - "\n", - "Suppose we have a PDF $p(x)$ from which we generate a series $N$\n", - "of averages $\\langle x_i \\rangle$. Each mean value $\\langle x_i \\rangle$\n", - "is viewed as the average of a specific measurement, e.g., throwing \n", - "dice 100 times and then taking the average value, or producing a certain\n", - "amount of random numbers. \n", - "For notational ease, we set $\\langle x_i \\rangle=x_i$ in the discussion\n", - "which follows. \n", - "\n", - "If we compute the mean $z$ of $m$ such mean values $x_i$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "z=\\frac{x_1+x_2+\\dots+x_m}{m},\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "the question we pose is which is the PDF of the new variable $z$.\n", - "\n", - "## Finding the Limit\n", - "\n", - "The probability of obtaining an average value $z$ is the product of the \n", - "probabilities of obtaining arbitrary individual mean values $x_i$,\n", - "but with the constraint that the average is $z$. We can express this through\n", - "the following expression" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "\\tilde{p}(z)=\\int dx_1p(x_1)\\int dx_2p(x_2)\\dots\\int dx_mp(x_m)\n", - " \\delta(z-\\frac{x_1+x_2+\\dots+x_m}{m}),\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "where the $\\delta$-function enbodies the constraint that the mean is $z$.\n", - "All measurements that lead to each individual $x_i$ are expected to\n", - "be independent, which in turn means that we can express $\\tilde{p}$ as the \n", - "product of individual $p(x_i)$. The independence assumption is important in the derivation of the central limit theorem.\n", - "\n", - "\n", - "## Rewriting the $\\delta$-function\n", - "\n", - "If we use the integral expression for the $\\delta$-function" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "\\delta(z-\\frac{x_1+x_2+\\dots+x_m}{m})=\\frac{1}{2\\pi}\\int_{-\\infty}^{\\infty}\n", - " dq\\exp{\\left(iq(z-\\frac{x_1+x_2+\\dots+x_m}{m})\\right)},\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "and inserting $e^{i\\mu q-i\\mu q}$ where $\\mu$ is the mean value\n", - "we arrive at" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "\\tilde{p}(z)=\\frac{1}{2\\pi}\\int_{-\\infty}^{\\infty}\n", - " dq\\exp{\\left(iq(z-\\mu)\\right)}\\left[\\int_{-\\infty}^{\\infty}\n", - " dxp(x)\\exp{\\left(iq(\\mu-x)/m\\right)}\\right]^m,\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "with the integral over $x$ resulting in" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "\\int_{-\\infty}^{\\infty}dxp(x)\\exp{\\left(iq(\\mu-x)/m\\right)}=\n", - " \\int_{-\\infty}^{\\infty}dxp(x)\n", - " \\left[1+\\frac{iq(\\mu-x)}{m}-\\frac{q^2(\\mu-x)^2}{2m^2}+\\dots\\right].\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "## Identifying Terms\n", - "\n", - "The second term on the rhs disappears since this is just the mean and \n", - "employing the definition of $\\sigma^2$ we have" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "\\int_{-\\infty}^{\\infty}dxp(x)e^{\\left(iq(\\mu-x)/m\\right)}=\n", - " 1-\\frac{q^2\\sigma^2}{2m^2}+\\dots,\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "resulting in" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "\\left[\\int_{-\\infty}^{\\infty}dxp(x)\\exp{\\left(iq(\\mu-x)/m\\right)}\\right]^m\\approx\n", - " \\left[1-\\frac{q^2\\sigma^2}{2m^2}+\\dots \\right]^m,\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "and in the limit $m\\rightarrow \\infty$ we obtain" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "\\tilde{p}(z)=\\frac{1}{\\sqrt{2\\pi}(\\sigma/\\sqrt{m})}\n", - " \\exp{\\left(-\\frac{(z-\\mu)^2}{2(\\sigma/\\sqrt{m})^2}\\right)},\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "which is the normal distribution with variance\n", - "$\\sigma^2_m=\\sigma^2/m$, where $\\sigma$ is the variance of the PDF $p(x)$\n", - "and $\\mu$ is also the mean of the PDF $p(x)$. \n", - "\n", - "## Wrapping it up\n", - "\n", - "Thus, the central limit theorem states that the PDF $\\tilde{p}(z)$ of\n", - "the average of $m$ random values corresponding to a PDF $p(x)$ \n", - "is a normal distribution whose mean is the \n", - "mean value of the PDF $p(x)$ and whose variance is the variance\n", - "of the PDF $p(x)$ divided by $m$, the number of values used to compute $z$.\n", - "\n", - "The theorem is satisfied by a large class of PDFs. Note however that for a\n", - "finite $m$, it is not always possible to find a closed expression for\n", - "$\\tilde{p}(x)$.\n", - "The central limit theorem leads then to the well-known expression for the\n", - "standard deviation, given by" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "\\sigma_m=\n", - "\\frac{\\sigma}{\\sqrt{m}}.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "The latter is true only if the average value is known exactly. This is obtained in the limit\n", - "$m\\rightarrow \\infty$ only. Because the mean and the variance are measured quantities we obtain \n", - "the familiar expression in statistics" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "\\sigma_m\\approx \n", - "\\frac{\\sigma}{\\sqrt{m-1}}.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "In many cases however the above estimate for the standard deviation,\n", - "in particular if correlations are strong, may be too simplistic.\n", - "\n", - "## Confidence Intervals\n", - "\n", - "\n", - "## Resampling methods: Bootstrap background\n", - "\n", - "Since $\\widehat{\\beta} = \\widehat{\\beta}(\\boldsymbol{X})$ is a function of random variables,\n", - "$\\widehat{\\beta}$ itself must be a random variable. Thus it has\n", - "a pdf, call this function $p(\\boldsymbol{t})$. The aim of the bootstrap is to\n", - "estimate $p(\\boldsymbol{t})$ by the relative frequency of\n", - "$\\widehat{\\beta}$. You can think of this as using a histogram\n", - "in the place of $p(\\boldsymbol{t})$. If the relative frequency closely\n", - "resembles $p(\\vec{t})$, then using numerics, it is straight forward to\n", - "estimate all the interesting parameters of $p(\\boldsymbol{t})$ using point\n", - "estimators. \n", - "\n", - "\n", - "## Resampling methods: More Bootstrap background\n", - "\n", - "In the case that $\\widehat{\\beta}$ has\n", - "more than one component, and the components are independent, we use the\n", - "same estimator on each component separately. If the probability\n", - "density function of $X_i$, $p(x)$, had been known, then it would have\n", - "been straightforward to do this by: \n", - "1. Drawing lots of numbers from $p(x)$, suppose we call one such set of numbers $(X_1^*, X_2^*, \\cdots, X_n^*)$. \n", - "\n", - "2. Then using these numbers, we could compute a replica of $\\widehat{\\beta}$ called $\\widehat{\\beta}^*$. \n", - "\n", - "By repeated use of the above two points, many\n", - "estimates of $\\widehat{\\beta}$ can be obtained. The\n", - "idea is to use the relative frequency of $\\widehat{\\beta}^*$\n", - "(think of a histogram) as an estimate of $p(\\boldsymbol{t})$.\n", - "\n", - "## Resampling methods: Bootstrap approach\n", - "\n", - "But\n", - "unless there is enough information available about the process that\n", - "generated $X_1,X_2,\\cdots,X_n$, $p(x)$ is in general\n", - "unknown. Therefore, [Efron in 1979](https://projecteuclid.org/euclid.aos/1176344552) asked the\n", - "question: What if we replace $p(x)$ by the relative frequency\n", - "of the observation $X_i$?\n", - "\n", - "If we draw observations in accordance with\n", - "the relative frequency of the observations, will we obtain the same\n", - "result in some asymptotic sense? The answer is yes.\n", - "\n", - "\n", - "\n", - "## Resampling methods: Bootstrap steps\n", - "\n", - "The independent bootstrap works like this: \n", - "\n", - "1. Draw with replacement $n$ numbers for the observed variables $\\boldsymbol{x} = (x_1,x_2,\\cdots,x_n)$. \n", - "\n", - "2. Define a vector $\\boldsymbol{x}^*$ containing the values which were drawn from $\\boldsymbol{x}$. \n", - "\n", - "3. Using the vector $\\boldsymbol{x}^*$ compute $\\widehat{\\beta}^*$ by evaluating $\\widehat \\beta$ under the observations $\\boldsymbol{x}^*$. \n", - "\n", - "4. Repeat this process $k$ times. \n", - "\n", - "When you are done, you can draw a histogram of the relative frequency\n", - "of $\\widehat \\beta^*$. This is your estimate of the probability\n", - "distribution $p(t)$. Using this probability distribution you can\n", - "estimate any statistics thereof. In principle you never draw the\n", - "histogram of the relative frequency of $\\widehat{\\beta}^*$. Instead\n", - "you use the estimators corresponding to the statistic of interest. For\n", - "example, if you are interested in estimating the variance of $\\widehat\n", - "\\beta$, apply the etsimator $\\widehat \\sigma^2$ to the values\n", - "$\\widehat \\beta^*$.\n", - "\n", - "\n", - "## Code example for the Bootstrap method\n", - "\n", - "The following code starts with a Gaussian distribution with mean value\n", - "$\\mu =100$ and variance $\\sigma=15$. We use this to generate the data\n", - "used in the bootstrap analysis. The bootstrap analysis returns a data\n", - "set after a given number of bootstrap operations (as many as we have\n", - "data points). This data set consists of estimated mean values for each\n", - "bootstrap operation. The histogram generated by the bootstrap method\n", - "shows that the distribution for these mean values is also a Gaussian,\n", - "centered around the mean value $\\mu=100$ but with standard deviation\n", - "$\\sigma/\\sqrt{n}$, where $n$ is the number of bootstrap samples (in\n", - "this case the same as the number of original data points). The value\n", - "of the standard deviation is what we expect from the central limit\n", - "theorem." - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": false, - "editable": true - }, - "outputs": [], - "source": [ - "from numpy import *\n", - "from numpy.random import randint, randn\n", - "from time import time\n", - "import matplotlib.mlab as mlab\n", - "import matplotlib.pyplot as plt\n", - "\n", - "# Returns mean of bootstrap samples # Alternatively, we can run it using Scikit-Learn's function resample # See the examples below\n", - "\n", - "def statistics(data):\n", - " return mean(data)\n", - "\n", - "\n", - "# Bootstrap algorithm\n", - "def bootstrap(data, statistic, R):\n", - " t = zeros(R); n = len(data); inds = arange(n); t0 = time()\n", - " # non-parametric bootstrap \n", - " for i in range(R):\n", - " t[i] = statistic(data[randint(0,n,n)])\n", - "\n", - " # analysis \n", - " print(\"Runtime: %g sec\" % (time()-t0)); print(\"Bootstrap Statistics :\")\n", - " print(\"original bias std. error\")\n", - " print(\"%8g %8g %14g %15g\" % (statistic(data), std(data),mean(t),std(t)))\n", - " return t\n", - "\n", - "\n", - "mu, sigma = 100, 15\n", - "datapoints = 10000\n", - "x = mu + sigma*random.randn(datapoints)\n", - "# bootstrap returns the data sample \n", - "t = bootstrap(x, statistics, datapoints)" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "We see that our new variance and from that the standard deviation, agrees with the central limit theorem.\n", - "\n", - "## Plotting the Histogram" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": false, - "editable": true - }, - "outputs": [], - "source": [ - "# the histogram of the bootstrapped data \n", - "n, binsboot, patches = plt.hist(t, 50, normed=1, facecolor='red', alpha=0.75)\n", - "\n", - "# add a 'best fit' line \n", - "y = mlab.normpdf( binsboot, mean(t), std(t))\n", - "lt = plt.plot(binsboot, y, 'r--', linewidth=1)\n", - "plt.xlabel('Smarts')\n", - "plt.ylabel('Probability')\n", - "plt.axis([99.5, 100.6, 0, 3.0])\n", - "plt.grid(True)\n", - "\n", - "plt.show()" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "## The bias-variance tradeoff\n", - "\n", - "\n", - "We will discuss the bias-variance tradeoff in the context of\n", - "continuous predictions such as regression. However, many of the\n", - "intuitions and ideas discussed here also carry over to classification\n", - "tasks. Consider a dataset $\\mathcal{L}$ consisting of the data\n", - "$\\mathbf{X}_\\mathcal{L}=\\{(y_j, \\boldsymbol{x}_j), j=0\\ldots n-1\\}$. \n", - "\n", - "Let us assume that the true data is generated from a noisy model" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "\\boldsymbol{y}=f(\\boldsymbol{x}) + \\boldsymbol{\\epsilon}\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "where $\\epsilon$ is normally distributed with mean zero and standard deviation $\\sigma^2$.\n", - "\n", - "In our derivation of the ordinary least squares method we defined then\n", - "an approximation to the function $f$ in terms of the parameters\n", - "$\\boldsymbol{\\beta}$ and the design matrix $\\boldsymbol{X}$ which embody our model,\n", - "that is $\\boldsymbol{\\tilde{y}}=\\boldsymbol{X}\\boldsymbol{\\beta}$. \n", - "\n", - "Thereafter we found the parameters $\\boldsymbol{\\beta}$ by optimizing the means squared error via the so-called cost function" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "C(\\boldsymbol{X},\\boldsymbol{\\beta}) =\\frac{1}{n}\\sum_{i=0}^{n-1}(y_i-\\tilde{y}_i)^2=\\mathbb{E}\\left[(\\boldsymbol{y}-\\boldsymbol{\\tilde{y}})^2\\right].\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "We can rewrite this as" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "\\mathbb{E}\\left[(\\boldsymbol{y}-\\boldsymbol{\\tilde{y}})^2\\right]=\\frac{1}{n}\\sum_i(f_i-\\mathbb{E}\\left[\\boldsymbol{\\tilde{y}}\\right])^2+\\frac{1}{n}\\sum_i(\\tilde{y}_i-\\mathbb{E}\\left[\\boldsymbol{\\tilde{y}}\\right])^2+\\sigma^2.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "The three terms represent the square of the bias of the learning\n", - "method, which can be thought of as the error caused by the simplifying\n", - "assumptions built into the method. The second term represents the\n", - "variance of the chosen model and finally the last terms is variance of\n", - "the error $\\boldsymbol{\\epsilon}$.\n", - "\n", - "To derive this equation, we need to recall that the variance of $\\boldsymbol{y}$ and $\\boldsymbol{\\epsilon}$ are both equal to $\\sigma^2$. The mean value of $\\boldsymbol{\\epsilon}$ is by definition equal to zero. Furthermore, the function $f$ is not a stochastics variable, idem for $\\boldsymbol{\\tilde{y}}$.\n", - "We use a more compact notation in terms of the expectation value" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "\\mathbb{E}\\left[(\\boldsymbol{y}-\\boldsymbol{\\tilde{y}})^2\\right]=\\mathbb{E}\\left[(\\boldsymbol{f}+\\boldsymbol{\\epsilon}-\\boldsymbol{\\tilde{y}})^2\\right],\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "and adding and subtracting $\\mathbb{E}\\left[\\boldsymbol{\\tilde{y}}\\right]$ we get" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "\\mathbb{E}\\left[(\\boldsymbol{y}-\\boldsymbol{\\tilde{y}})^2\\right]=\\mathbb{E}\\left[(\\boldsymbol{f}+\\boldsymbol{\\epsilon}-\\boldsymbol{\\tilde{y}}+\\mathbb{E}\\left[\\boldsymbol{\\tilde{y}}\\right]-\\mathbb{E}\\left[\\boldsymbol{\\tilde{y}}\\right])^2\\right],\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "which, using the abovementioned expectation values can be rewritten as" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "\\mathbb{E}\\left[(\\boldsymbol{y}-\\boldsymbol{\\tilde{y}})^2\\right]=\\mathbb{E}\\left[(\\boldsymbol{y}-\\mathbb{E}\\left[\\boldsymbol{\\tilde{y}}\\right])^2\\right]+\\mathrm{Var}\\left[\\boldsymbol{\\tilde{y}}\\right]+\\sigma^2,\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "that is the rewriting in terms of the so-called bias, the variance of the model $\\boldsymbol{\\tilde{y}}$ and the variance of $\\boldsymbol{\\epsilon}$.\n", - "\n", - "\n", - "## A way to Read the Bias-Variance Tradeoff\n", - "\n", - "\n", - "\n", - "

    Figure 1:

    \n", - "\n", - "\n", - "\n", - "## Example code for Bias-Variance tradeoff" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": false, - "editable": true - }, - "outputs": [], - "source": [ - "import matplotlib.pyplot as plt\n", - "import numpy as np\n", - "from sklearn.linear_model import LinearRegression, Ridge, Lasso\n", - "from sklearn.preprocessing import PolynomialFeatures\n", - "from sklearn.model_selection import train_test_split\n", - "from sklearn.pipeline import make_pipeline\n", - "from sklearn.utils import resample\n", - "\n", - "np.random.seed(2018)\n", - "\n", - "n = 500\n", - "n_boostraps = 100\n", - "degree = 18 # A quite high value, just to show.\n", - "noise = 0.1\n", - "\n", - "# Make data set.\n", - "x = np.linspace(-1, 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)\n", - "\n", - "# Hold out some test data that is never used in training.\n", - "x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.2)\n", - "\n", - "# Combine x transformation and model into one operation.\n", - "# Not neccesary, but convenient.\n", - "model = make_pipeline(PolynomialFeatures(degree=degree), LinearRegression(fit_intercept=False))\n", - "\n", - "# The following (m x n_bootstraps) matrix holds the column vectors y_pred\n", - "# for each bootstrap iteration.\n", - "y_pred = np.empty((y_test.shape[0], n_boostraps))\n", - "for i in range(n_boostraps):\n", - " x_, y_ = resample(x_train, y_train)\n", - "\n", - " # Evaluate the new model on the same test data each time.\n", - " y_pred[:, i] = model.fit(x_, y_).predict(x_test).ravel()\n", - "\n", - "# Note: Expectations and variances taken w.r.t. different training\n", - "# data sets, hence the axis=1. Subsequent means are taken across the test data\n", - "# set in order to obtain a total value, but before this we have error/bias/variance\n", - "# calculated per data point in the test set.\n", - "# Note 2: The use of keepdims=True is important in the calculation of bias as this \n", - "# maintains the column vector form. Dropping this yields very unexpected results.\n", - "error = np.mean( np.mean((y_test - y_pred)**2, axis=1, keepdims=True) )\n", - "bias = np.mean( (y_test - np.mean(y_pred, axis=1, keepdims=True))**2 )\n", - "variance = np.mean( np.var(y_pred, axis=1, keepdims=True) )\n", - "print('Error:', error)\n", - "print('Bias^2:', bias)\n", - "print('Var:', variance)\n", - "print('{} >= {} + {} = {}'.format(error, bias, variance, bias+variance))\n", - "\n", - "plt.plot(x[::5, :], y[::5, :], label='f(x)')\n", - "plt.scatter(x_test, y_test, label='Data points')\n", - "plt.scatter(x_test, np.mean(y_pred, axis=1), label='Pred')\n", - "plt.legend()\n", - "plt.show()" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "## Understanding what happens" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": false, - "editable": true - }, - "outputs": [], - "source": [ - "import matplotlib.pyplot as plt\n", - "import numpy as np\n", - "from sklearn.linear_model import LinearRegression, Ridge, Lasso\n", - "from sklearn.preprocessing import PolynomialFeatures\n", - "from sklearn.model_selection import train_test_split\n", - "from sklearn.pipeline import make_pipeline\n", - "from sklearn.utils import resample\n", - "\n", - "np.random.seed(2018)\n", - "\n", - "n = 40\n", - "n_boostraps = 100\n", - "maxdegree = 14\n", - "\n", - "\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)\n", - "error = np.zeros(maxdegree)\n", - "bias = np.zeros(maxdegree)\n", - "variance = np.zeros(maxdegree)\n", - "polydegree = np.zeros(maxdegree)\n", - "x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.2)\n", - "\n", - "for degree in range(maxdegree):\n", - " model = make_pipeline(PolynomialFeatures(degree=degree), LinearRegression(fit_intercept=False))\n", - " y_pred = np.empty((y_test.shape[0], n_boostraps))\n", - " for i in range(n_boostraps):\n", - " x_, y_ = resample(x_train, y_train)\n", - " y_pred[:, i] = model.fit(x_, y_).predict(x_test).ravel()\n", - "\n", - " polydegree[degree] = degree\n", - " error[degree] = np.mean( np.mean((y_test - y_pred)**2, axis=1, keepdims=True) )\n", - " bias[degree] = np.mean( (y_test - np.mean(y_pred, axis=1, keepdims=True))**2 )\n", - " variance[degree] = np.mean( np.var(y_pred, axis=1, keepdims=True) )\n", - " print('Polynomial degree:', degree)\n", - " print('Error:', error[degree])\n", - " print('Bias^2:', bias[degree])\n", - " print('Var:', variance[degree])\n", - " print('{} >= {} + {} = {}'.format(error[degree], bias[degree], variance[degree], bias[degree]+variance[degree]))\n", - "\n", - "plt.plot(polydegree, error, label='Error')\n", - "plt.plot(polydegree, bias, label='bias')\n", - "plt.plot(polydegree, variance, label='Variance')\n", - "plt.legend()\n", - "plt.show()" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "\n", - "## Summing up\n", - "\n", - "\n", - "\n", - "\n", - "The bias-variance tradeoff summarizes the fundamental tension in\n", - "machine learning, particularly supervised learning, between the\n", - "complexity of a model and the amount of training data needed to train\n", - "it. Since data is often limited, in practice it is often useful to\n", - "use a less-complex model with higher bias, that is a model whose asymptotic\n", - "performance is worse than another model because it is easier to\n", - "train and less sensitive to sampling noise arising from having a\n", - "finite-sized training dataset (smaller variance). \n", - "\n", - "\n", - "\n", - "The above equations tell us that in\n", - "order to minimize the expected test error, we need to select a\n", - "statistical learning method that simultaneously achieves low variance\n", - "and low bias. Note that variance is inherently a nonnegative quantity,\n", - "and squared bias is also nonnegative. Hence, we see that the expected\n", - "test MSE can never lie below $Var(\\epsilon)$, the irreducible error.\n", - "\n", - "\n", - "What do we mean by the variance and bias of a statistical learning\n", - "method? The variance refers to the amount by which our model would change if we\n", - "estimated it using a different training data set. Since the training\n", - "data are used to fit the statistical learning method, different\n", - "training data sets will result in a different estimate. But ideally the\n", - "estimate for our model should not vary too much between training\n", - "sets. However, if a method has high variance then small changes in\n", - "the training data can result in large changes in the model. In general, more\n", - "flexible statistical methods have higher variance.\n", - "\n", - "\n", - "You may also find this recent [article](https://www.pnas.org/content/116/32/15849) of interest.\n", - "\n", - "## Another Example from Scikit-Learn's Repository" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": false, - "editable": true - }, - "outputs": [], - "source": [ - "\"\"\"\n", - "============================\n", - "Underfitting vs. Overfitting\n", - "============================\n", - "\n", - "This example demonstrates the problems of underfitting and overfitting and\n", - "how we can use linear regression with polynomial features to approximate\n", - "nonlinear functions. The plot shows the function that we want to approximate,\n", - "which is a part of the cosine function. In addition, the samples from the\n", - "real function and the approximations of different models are displayed. The\n", - "models have polynomial features of different degrees. We can see that a\n", - "linear function (polynomial with degree 1) is not sufficient to fit the\n", - "training samples. This is called **underfitting**. A polynomial of degree 4\n", - "approximates the true function almost perfectly. However, for higher degrees\n", - "the model will **overfit** the training data, i.e. it learns the noise of the\n", - "training data.\n", - "We evaluate quantitatively **overfitting** / **underfitting** by using\n", - "cross-validation. We calculate the mean squared error (MSE) on the validation\n", - "set, the higher, the less likely the model generalizes correctly from the\n", - "training data.\n", - "\"\"\"\n", - "\n", - "print(__doc__)\n", - "\n", - "import numpy as np\n", - "import matplotlib.pyplot as plt\n", - "from sklearn.pipeline import Pipeline\n", - "from sklearn.preprocessing import PolynomialFeatures\n", - "from sklearn.linear_model import LinearRegression\n", - "from sklearn.model_selection import cross_val_score\n", - "\n", - "\n", - "def true_fun(X):\n", - " return np.cos(1.5 * np.pi * X)\n", - "\n", - "np.random.seed(0)\n", - "\n", - "n_samples = 30\n", - "degrees = [1, 4, 15]\n", - "\n", - "X = np.sort(np.random.rand(n_samples))\n", - "y = true_fun(X) + np.random.randn(n_samples) * 0.1\n", - "\n", - "plt.figure(figsize=(14, 5))\n", - "for i in range(len(degrees)):\n", - " ax = plt.subplot(1, len(degrees), i + 1)\n", - " plt.setp(ax, xticks=(), yticks=())\n", - "\n", - " polynomial_features = PolynomialFeatures(degree=degrees[i],\n", - " include_bias=False)\n", - " linear_regression = LinearRegression()\n", - " pipeline = Pipeline([(\"polynomial_features\", polynomial_features),\n", - " (\"linear_regression\", linear_regression)])\n", - " pipeline.fit(X[:, np.newaxis], y)\n", - "\n", - " # Evaluate the models using crossvalidation\n", - " scores = cross_val_score(pipeline, X[:, np.newaxis], y,\n", - " scoring=\"neg_mean_squared_error\", cv=10)\n", - "\n", - " X_test = np.linspace(0, 1, 100)\n", - " plt.plot(X_test, pipeline.predict(X_test[:, np.newaxis]), label=\"Model\")\n", - " plt.plot(X_test, true_fun(X_test), label=\"True function\")\n", - " plt.scatter(X, y, edgecolor='b', s=20, label=\"Samples\")\n", - " plt.xlabel(\"x\")\n", - " plt.ylabel(\"y\")\n", - " plt.xlim((0, 1))\n", - " plt.ylim((-2, 2))\n", - " plt.legend(loc=\"best\")\n", - " plt.title(\"Degree {}\\nMSE = {:.2e}(+/- {:.2e})\".format(\n", - " degrees[i], -scores.mean(), scores.std()))\n", - "plt.show()" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "\n", - "## Various steps in cross-validation\n", - "\n", - "When the repetitive splitting of the data set is done randomly,\n", - "samples may accidently end up in a fast majority of the splits in\n", - "either training or test set. Such samples may have an unbalanced\n", - "influence on either model building or prediction evaluation. To avoid\n", - "this $k$-fold cross-validation structures the data splitting. The\n", - "samples are divided into $k$ more or less equally sized exhaustive and\n", - "mutually exclusive subsets. In turn (at each split) one of these\n", - "subsets plays the role of the test set while the union of the\n", - "remaining subsets constitutes the training set. Such a splitting\n", - "warrants a balanced representation of each sample in both training and\n", - "test set over the splits. Still the division into the $k$ subsets\n", - "involves a degree of randomness. This may be fully excluded when\n", - "choosing $k=n$. This particular case is referred to as leave-one-out\n", - "cross-validation (LOOCV). \n", - "\n", - "\n", - "## How to set up the cross-validation for Ridge and/or Lasso\n", - "\n", - "* Define a range of interest for the penalty parameter.\n", - "\n", - "* Divide the data set into training and test set comprising samples $\\{1, \\ldots, n\\} \\setminus i$ and $\\{ i \\}$, respectively.\n", - "\n", - "* Fit the linear regression model by means of ridge estimation for each $\\lambda$ in the grid using the training set, and the corresponding estimate of the error variance $\\boldsymbol{\\sigma}_{-i}^2(\\lambda)$, as" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "\\begin{align*}\n", - "\\boldsymbol{\\beta}_{-i}(\\lambda) & = ( \\boldsymbol{X}_{-i, \\ast}^{T}\n", - "\\boldsymbol{X}_{-i, \\ast} + \\lambda \\boldsymbol{I}_{pp})^{-1}\n", - "\\boldsymbol{X}_{-i, \\ast}^{T} \\boldsymbol{y}_{-i}\n", - "\\end{align*}\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "* Evaluate the prediction performance of these models on the test set by $\\log\\{L[y_i, \\boldsymbol{X}_{i, \\ast}; \\boldsymbol{\\beta}_{-i}(\\lambda), \\boldsymbol{\\sigma}_{-i}^2(\\lambda)]\\}$. Or, by the prediction error $|y_i - \\boldsymbol{X}_{i, \\ast} \\boldsymbol{\\beta}_{-i}(\\lambda)|$, the relative error, the error squared or the R2 score function.\n", - "\n", - "* Repeat the first three steps such that each sample plays the role of the test set once.\n", - "\n", - "* Average the prediction performances of the test sets at each grid point of the penalty bias/parameter. It is an estimate of the prediction performance of the model corresponding to this value of the penalty parameter on novel data. It is defined as" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "\\begin{align*}\n", - "\\frac{1}{n} \\sum_{i = 1}^n \\log\\{L[y_i, \\mathbf{X}_{i, \\ast}; \\boldsymbol{\\beta}_{-i}(\\lambda), \\boldsymbol{\\sigma}_{-i}^2(\\lambda)]\\}.\n", - "\\end{align*}\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "## Cross-validation in brief\n", - "\n", - "For the various values of $k$\n", - "\n", - "1. shuffle the dataset randomly.\n", - "\n", - "2. Split the dataset into $k$ groups.\n", - "\n", - "3. For each unique group:\n", - "\n", - "a. Decide which group to use as set for test data\n", - "\n", - "b. Take the remaining groups as a training data set\n", - "\n", - "c. Fit a model on the training set and evaluate it on the test set\n", - "\n", - "d. Retain the evaluation score and discard the model\n", - "\n", - "\n", - "5. Summarize the model using the sample of model evaluation scores\n", - "\n", - "## Code Example for Cross-validation and $k$-fold Cross-validation\n", - "\n", - "The code here uses Ridge regression with cross-validation (CV) resampling and $k$-fold CV in order to fit a specific polynomial." - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": false, - "editable": true - }, - "outputs": [], - "source": [ - "import numpy as np\n", - "import matplotlib.pyplot as plt\n", - "from sklearn.model_selection import KFold\n", - "from sklearn.linear_model import Ridge\n", - "from sklearn.model_selection import cross_val_score\n", - "from sklearn.preprocessing import PolynomialFeatures\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", - "# Generate the data.\n", - "nsamples = 100\n", - "x = np.random.randn(nsamples)\n", - "y = 3*x**2 + np.random.randn(nsamples)\n", - "\n", - "## Cross-validation on Ridge regression using KFold only\n", - "\n", - "# Decide degree on polynomial to fit\n", - "poly = PolynomialFeatures(degree = 6)\n", - "\n", - "# Decide which values of lambda to use\n", - "nlambdas = 500\n", - "lambdas = np.logspace(-3, 5, nlambdas)\n", - "\n", - "# Initialize a KFold instance\n", - "k = 5\n", - "kfold = KFold(n_splits = k)\n", - "\n", - "# Perform the cross-validation to estimate MSE\n", - "scores_KFold = np.zeros((nlambdas, k))\n", - "\n", - "i = 0\n", - "for lmb in lambdas:\n", - " ridge = Ridge(alpha = lmb)\n", - " j = 0\n", - " for train_inds, test_inds in kfold.split(x):\n", - " xtrain = x[train_inds]\n", - " ytrain = y[train_inds]\n", - "\n", - " xtest = x[test_inds]\n", - " ytest = y[test_inds]\n", - "\n", - " Xtrain = poly.fit_transform(xtrain[:, np.newaxis])\n", - " ridge.fit(Xtrain, ytrain[:, np.newaxis])\n", - "\n", - " Xtest = poly.fit_transform(xtest[:, np.newaxis])\n", - " ypred = ridge.predict(Xtest)\n", - "\n", - " scores_KFold[i,j] = np.sum((ypred - ytest[:, np.newaxis])**2)/np.size(ypred)\n", - "\n", - " j += 1\n", - " i += 1\n", - "\n", - "\n", - "estimated_mse_KFold = np.mean(scores_KFold, axis = 1)\n", - "\n", - "## Cross-validation using cross_val_score from sklearn along with KFold\n", - "\n", - "# kfold is an instance initialized above as:\n", - "# kfold = KFold(n_splits = k)\n", - "\n", - "estimated_mse_sklearn = np.zeros(nlambdas)\n", - "i = 0\n", - "for lmb in lambdas:\n", - " ridge = Ridge(alpha = lmb)\n", - "\n", - " X = poly.fit_transform(x[:, np.newaxis])\n", - " estimated_mse_folds = cross_val_score(ridge, X, y[:, np.newaxis], scoring='neg_mean_squared_error', cv=kfold)\n", - "\n", - " # cross_val_score return an array containing the estimated negative mse for every fold.\n", - " # we have to the the mean of every array in order to get an estimate of the mse of the model\n", - " estimated_mse_sklearn[i] = np.mean(-estimated_mse_folds)\n", - "\n", - " i += 1\n", - "\n", - "## Plot and compare the slightly different ways to perform cross-validation\n", - "\n", - "plt.figure()\n", - "\n", - "plt.plot(np.log10(lambdas), estimated_mse_sklearn, label = 'cross_val_score')\n", - "plt.plot(np.log10(lambdas), estimated_mse_KFold, 'r--', label = 'KFold')\n", - "\n", - "plt.xlabel('log10(lambda)')\n", - "plt.ylabel('mse')\n", - "\n", - "plt.legend()\n", - "\n", - "plt.show()" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "## More examples on bootstrap and cross-validation and errors" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": false, - "editable": true - }, - "outputs": [], - "source": [ - "# Common imports\n", - "import os\n", - "import numpy as np\n", - "import pandas as pd\n", - "import matplotlib.pyplot as plt\n", - "from sklearn.linear_model import LinearRegression, Ridge, Lasso\n", - "from sklearn.model_selection import train_test_split\n", - "from sklearn.utils import resample\n", - "from sklearn.metrics import mean_squared_error\n", - "# Where to save the figures and data files\n", - "PROJECT_ROOT_DIR = \"Results\"\n", - "FIGURE_ID = \"Results/FigureFiles\"\n", - "DATA_ID = \"DataFiles/\"\n", - "\n", - "if not os.path.exists(PROJECT_ROOT_DIR):\n", - " os.mkdir(PROJECT_ROOT_DIR)\n", - "\n", - "if not os.path.exists(FIGURE_ID):\n", - " os.makedirs(FIGURE_ID)\n", - "\n", - "if not os.path.exists(DATA_ID):\n", - " os.makedirs(DATA_ID)\n", - "\n", - "def image_path(fig_id):\n", - " return os.path.join(FIGURE_ID, fig_id)\n", - "\n", - "def data_path(dat_id):\n", - " return os.path.join(DATA_ID, dat_id)\n", - "\n", - "def save_fig(fig_id):\n", - " plt.savefig(image_path(fig_id) + \".png\", format='png')\n", - "\n", - "infile = open(data_path(\"EoS.csv\"),'r')\n", - "\n", - "# Read the EoS data as csv file and organize the data into two arrays with density and energies\n", - "EoS = pd.read_csv(infile, names=('Density', 'Energy'))\n", - "EoS['Energy'] = pd.to_numeric(EoS['Energy'], errors='coerce')\n", - "EoS = EoS.dropna()\n", - "Energies = EoS['Energy']\n", - "Density = EoS['Density']\n", - "# The design matrix now as function of various polytrops\n", - "\n", - "Maxpolydegree = 30\n", - "X = np.zeros((len(Density),Maxpolydegree))\n", - "X[:,0] = 1.0\n", - "testerror = np.zeros(Maxpolydegree)\n", - "trainingerror = np.zeros(Maxpolydegree)\n", - "polynomial = np.zeros(Maxpolydegree)\n", - "\n", - "trials = 100\n", - "for polydegree in range(1, Maxpolydegree):\n", - " polynomial[polydegree] = polydegree\n", - " for degree in range(polydegree):\n", - " X[:,degree] = Density**(degree/3.0)\n", - "\n", - "# loop over trials in order to estimate the expectation value of the MSE\n", - " testerror[polydegree] = 0.0\n", - " trainingerror[polydegree] = 0.0\n", - " for samples in range(trials):\n", - " x_train, x_test, y_train, y_test = train_test_split(X, Energies, test_size=0.2)\n", - " model = LinearRegression(fit_intercept=True).fit(x_train, y_train)\n", - " ypred = model.predict(x_train)\n", - " ytilde = model.predict(x_test)\n", - " testerror[polydegree] += mean_squared_error(y_test, ytilde)\n", - " trainingerror[polydegree] += mean_squared_error(y_train, ypred) \n", - "\n", - " testerror[polydegree] /= trials\n", - " trainingerror[polydegree] /= trials\n", - " print(\"Degree of polynomial: %3d\"% polynomial[polydegree])\n", - " print(\"Mean squared error on training data: %.8f\" % trainingerror[polydegree])\n", - " print(\"Mean squared error on test data: %.8f\" % testerror[polydegree])\n", - "\n", - "plt.plot(polynomial, np.log10(trainingerror), label='Training Error')\n", - "plt.plot(polynomial, np.log10(testerror), label='Test Error')\n", - "plt.xlabel('Polynomial degree')\n", - "plt.ylabel('log10[MSE]')\n", - "plt.legend()\n", - "plt.show()" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "\n", - "## The same example but now with cross-validation" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": false, - "editable": true - }, - "outputs": [], - "source": [ - "# Common imports\n", - "import os\n", - "import numpy as np\n", - "import pandas as pd\n", - "import matplotlib.pyplot as plt\n", - "from sklearn.linear_model import LinearRegression, Ridge, Lasso\n", - "from sklearn.metrics import mean_squared_error\n", - "from sklearn.model_selection import KFold\n", - "from sklearn.model_selection import cross_val_score\n", - "\n", - "\n", - "# Where to save the figures and data files\n", - "PROJECT_ROOT_DIR = \"Results\"\n", - "FIGURE_ID = \"Results/FigureFiles\"\n", - "DATA_ID = \"DataFiles/\"\n", - "\n", - "if not os.path.exists(PROJECT_ROOT_DIR):\n", - " os.mkdir(PROJECT_ROOT_DIR)\n", - "\n", - "if not os.path.exists(FIGURE_ID):\n", - " os.makedirs(FIGURE_ID)\n", - "\n", - "if not os.path.exists(DATA_ID):\n", - " os.makedirs(DATA_ID)\n", - "\n", - "def image_path(fig_id):\n", - " return os.path.join(FIGURE_ID, fig_id)\n", - "\n", - "def data_path(dat_id):\n", - " return os.path.join(DATA_ID, dat_id)\n", - "\n", - "def save_fig(fig_id):\n", - " plt.savefig(image_path(fig_id) + \".png\", format='png')\n", - "\n", - "infile = open(data_path(\"EoS.csv\"),'r')\n", - "\n", - "# Read the EoS data as csv file and organize the data into two arrays with density and energies\n", - "EoS = pd.read_csv(infile, names=('Density', 'Energy'))\n", - "EoS['Energy'] = pd.to_numeric(EoS['Energy'], errors='coerce')\n", - "EoS = EoS.dropna()\n", - "Energies = EoS['Energy']\n", - "Density = EoS['Density']\n", - "# The design matrix now as function of various polytrops\n", - "\n", - "Maxpolydegree = 30\n", - "X = np.zeros((len(Density),Maxpolydegree))\n", - "X[:,0] = 1.0\n", - "estimated_mse_sklearn = np.zeros(Maxpolydegree)\n", - "polynomial = np.zeros(Maxpolydegree)\n", - "k =5\n", - "kfold = KFold(n_splits = k)\n", - "\n", - "for polydegree in range(1, Maxpolydegree):\n", - " polynomial[polydegree] = polydegree\n", - " for degree in range(polydegree):\n", - " X[:,degree] = Density**(degree/3.0)\n", - " OLS = LinearRegression()\n", - "# loop over trials in order to estimate the expectation value of the MSE\n", - " estimated_mse_folds = cross_val_score(OLS, X, Energies, scoring='neg_mean_squared_error', cv=kfold)\n", - "#[:, np.newaxis]\n", - " estimated_mse_sklearn[polydegree] = np.mean(-estimated_mse_folds)\n", - "\n", - "plt.plot(polynomial, np.log10(estimated_mse_sklearn), label='Test Error')\n", - "plt.xlabel('Polynomial degree')\n", - "plt.ylabel('log10[MSE]')\n", - "plt.legend()\n", - "plt.show()" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "## Cross-validation with Ridge" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": false, - "editable": true - }, - "outputs": [], - "source": [ - "import numpy as np\n", - "import matplotlib.pyplot as plt\n", - "from sklearn.model_selection import KFold\n", - "from sklearn.linear_model import Ridge\n", - "from sklearn.model_selection import cross_val_score\n", - "from sklearn.preprocessing import PolynomialFeatures\n", - "\n", - "# A seed just to ensure that the random numbers are the same for every run.\n", - "np.random.seed(3155)\n", - "# Generate the data.\n", - "n = 100\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)\n", - "# Decide degree on polynomial to fit\n", - "poly = PolynomialFeatures(degree = 10)\n", - "\n", - "# Decide which values of lambda to use\n", - "nlambdas = 500\n", - "lambdas = np.logspace(-3, 5, nlambdas)\n", - "# Initialize a KFold instance\n", - "k = 5\n", - "kfold = KFold(n_splits = k)\n", - "estimated_mse_sklearn = np.zeros(nlambdas)\n", - "i = 0\n", - "for lmb in lambdas:\n", - " ridge = Ridge(alpha = lmb)\n", - " estimated_mse_folds = cross_val_score(ridge, x, y, scoring='neg_mean_squared_error', cv=kfold)\n", - " estimated_mse_sklearn[i] = np.mean(-estimated_mse_folds)\n", - " i += 1\n", - "plt.figure()\n", - "plt.plot(np.log10(lambdas), estimated_mse_sklearn, label = 'cross_val_score')\n", - "plt.xlabel('log10(lambda)')\n", - "plt.ylabel('MSE')\n", - "plt.legend()\n", - "plt.show()" - ] - } - ], - "metadata": {}, - "nbformat": 4, - "nbformat_minor": 4 -}